You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mynewt.apache.org by ad...@apache.org on 2017/04/19 18:17:57 UTC

[01/30] incubator-mynewt-core git commit: net/ip; fix memory allocation for tcpip stack.

Repository: incubator-mynewt-core
Updated Branches:
  refs/heads/master 73c8953be -> 28b29f445


net/ip; fix memory allocation for tcpip stack.


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/0429ee55
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/0429ee55
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/0429ee55

Branch: refs/heads/master
Commit: 0429ee55c565368d3728c45552b65a0ce34c7258
Parents: a95f14f
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Fri Apr 14 13:00:45 2017 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Fri Apr 14 13:21:30 2017 -0700

----------------------------------------------------------------------
 net/ip/include/arch/sys_arch.h | 304 ++++++++++++++++++------------------
 1 file changed, 152 insertions(+), 152 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/0429ee55/net/ip/include/arch/sys_arch.h
----------------------------------------------------------------------
diff --git a/net/ip/include/arch/sys_arch.h b/net/ip/include/arch/sys_arch.h
index e01f6aa..f8c53a8 100644
--- a/net/ip/include/arch/sys_arch.h
+++ b/net/ip/include/arch/sys_arch.h
@@ -1,160 +1,160 @@
-/**
- * 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 __LWIP_SYS_ARCH_H__
-#define __LWIP_SYS_ARCH_H__
-
-#include <stdlib.h>
-
+/**
+ * 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 __LWIP_SYS_ARCH_H__
+#define __LWIP_SYS_ARCH_H__
+
+#include <stdlib.h>
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-#undef LITTLE_ENDIAN
-#include <os/os.h>
-#include <ip/os_queue.h>
-
-#define SYS_MBOX_NULL NULL
-#define SYS_SEM_NULL  NULL
-
-struct os_queue;
-
-typedef struct os_sem sys_sem_t;
-typedef struct os_mutex sys_mutex_t;
-typedef struct os_queue sys_mbox_t;
-typedef struct os_task * sys_thread_t;
-typedef os_stack_t portSTACK_TYPE;
-
-typedef int sys_prot_t;
-
-static inline int
-sys_arch_protect(void)
-{
-    int sr;
-
-    OS_ENTER_CRITICAL(sr);
-    return sr;
-}
-
-static inline void
-sys_arch_unprotect(int prev_sr)
-{
-    OS_EXIT_CRITICAL(prev_sr);
-}
-
-static inline void
-sys_init(void)
-{
-}
-
-static inline err_t
-sys_sem_new(sys_sem_t *sem, u8_t count)
-{
-    if (os_sem_init(sem, count)) {
-        return ERR_VAL;
-    }
-    return ERR_OK;
-}
-
-static inline void
-sys_sem_signal(sys_sem_t *sem)
-{
-    os_sem_release(sem);
-}
-
-static inline err_t
-sys_mutex_new(sys_mutex_t *mutex)
-{
-    if (os_mutex_init(mutex)) {
-        return ERR_VAL;
-    }
-    return ERR_OK;
-}
-
-static inline void
-sys_mutex_lock(sys_mutex_t *mutex)
-{
-    os_mutex_pend(mutex, OS_WAIT_FOREVER);
-}
-
-static inline void
-sys_mutex_unlock(sys_mutex_t *mutex)
-{
-    os_mutex_release(mutex);
-}
-
-static inline uint32_t
-sys_now(void)
-{
-    uint32_t t;
-
-    /*
-     * XXX not right when g_os_time rolls over
-     */
-    t = os_time_get() * OS_TICKS_PER_SEC / 1000;
-    return t;
-}
-
-static inline err_t
-sys_mbox_new(sys_mbox_t *mbox, int size)
-{
-    if (os_queue_init(mbox, sizeof(void *), size)) {
-        return ERR_MEM;
-    }
-    return ERR_OK;
-}
-
-static inline void
-sys_mbox_post(sys_mbox_t *mbox, void *msg)
-{
-    os_queue_put(mbox, &msg, OS_WAIT_FOREVER);
-}
-
-static inline err_t
-sys_mbox_trypost(sys_mbox_t *mbox, void *msg)
-{
-    if (os_queue_put(mbox, &msg, 0)) {
-        return ERR_MEM;
-    }
-    return ERR_OK;
-}
-
-static inline sys_thread_t
-sys_thread_new(const char *name, void (*thread)(void *arg), void *arg,
-  int stacksize, int prio)
-{
-    struct os_task *task;
-    os_stack_t *stack;
-
-    task = (struct os_task *)os_malloc(sizeof(*task));
-    assert(task);
-    stack = (os_stack_t *)os_malloc(stacksize);
-    assert(stack);
-    if (os_task_init(task, name, thread, arg, prio, OS_WAIT_FOREVER, stack,
-        stacksize)) {
-        assert(0);
-    }
-    return task;
-}
-
+#undef LITTLE_ENDIAN
+#include <os/os.h>
+#include <ip/os_queue.h>
+
+#define SYS_MBOX_NULL NULL
+#define SYS_SEM_NULL  NULL
+
+struct os_queue;
+
+typedef struct os_sem sys_sem_t;
+typedef struct os_mutex sys_mutex_t;
+typedef struct os_queue sys_mbox_t;
+typedef struct os_task * sys_thread_t;
+typedef os_stack_t portSTACK_TYPE;
+
+typedef int sys_prot_t;
+
+static inline int
+sys_arch_protect(void)
+{
+    int sr;
+
+    OS_ENTER_CRITICAL(sr);
+    return sr;
+}
+
+static inline void
+sys_arch_unprotect(int prev_sr)
+{
+    OS_EXIT_CRITICAL(prev_sr);
+}
+
+static inline void
+sys_init(void)
+{
+}
+
+static inline err_t
+sys_sem_new(sys_sem_t *sem, u8_t count)
+{
+    if (os_sem_init(sem, count)) {
+        return ERR_VAL;
+    }
+    return ERR_OK;
+}
+
+static inline void
+sys_sem_signal(sys_sem_t *sem)
+{
+    os_sem_release(sem);
+}
+
+static inline err_t
+sys_mutex_new(sys_mutex_t *mutex)
+{
+    if (os_mutex_init(mutex)) {
+        return ERR_VAL;
+    }
+    return ERR_OK;
+}
+
+static inline void
+sys_mutex_lock(sys_mutex_t *mutex)
+{
+    os_mutex_pend(mutex, OS_WAIT_FOREVER);
+}
+
+static inline void
+sys_mutex_unlock(sys_mutex_t *mutex)
+{
+    os_mutex_release(mutex);
+}
+
+static inline uint32_t
+sys_now(void)
+{
+    uint32_t t;
+
+    /*
+     * XXX not right when g_os_time rolls over
+     */
+    t = os_time_get() * OS_TICKS_PER_SEC / 1000;
+    return t;
+}
+
+static inline err_t
+sys_mbox_new(sys_mbox_t *mbox, int size)
+{
+    if (os_queue_init(mbox, sizeof(void *), size)) {
+        return ERR_MEM;
+    }
+    return ERR_OK;
+}
+
+static inline void
+sys_mbox_post(sys_mbox_t *mbox, void *msg)
+{
+    os_queue_put(mbox, &msg, OS_WAIT_FOREVER);
+}
+
+static inline err_t
+sys_mbox_trypost(sys_mbox_t *mbox, void *msg)
+{
+    if (os_queue_put(mbox, &msg, 0)) {
+        return ERR_MEM;
+    }
+    return ERR_OK;
+}
+
+static inline sys_thread_t
+sys_thread_new(const char *name, void (*thread)(void *arg), void *arg,
+  int stacksize, int prio)
+{
+    struct os_task *task;
+    os_stack_t *stack;
+
+    task = (struct os_task *)os_malloc(sizeof(*task));
+    assert(task);
+    stack = (os_stack_t *)os_malloc(stacksize * sizeof(os_stack_t));
+    assert(stack);
+    if (os_task_init(task, name, thread, arg, prio, OS_WAIT_FOREVER, stack,
+        stacksize)) {
+        assert(0);
+    }
+    return task;
+}
+
 #ifdef __cplusplus
 }
 #endif
 
-#endif /* __LWIP_SYS_ARCH_H__ */
-
+#endif /* __LWIP_SYS_ARCH_H__ */
+


[27/30] incubator-mynewt-core git commit: native_sockets; fill in LINK flag when querying interfaces in sim.

Posted by ad...@apache.org.
native_sockets; fill in LINK flag when querying interfaces in sim.


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/bcba6bd9
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/bcba6bd9
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/bcba6bd9

Branch: refs/heads/master
Commit: bcba6bd9d35bcd9f8caf2baa3ec5b365097916dc
Parents: ed273ed
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Mon Apr 17 15:25:48 2017 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Apr 17 15:25:48 2017 -0700

----------------------------------------------------------------------
 net/ip/native_sockets/src/native_itf.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/bcba6bd9/net/ip/native_sockets/src/native_itf.c
----------------------------------------------------------------------
diff --git a/net/ip/native_sockets/src/native_itf.c b/net/ip/native_sockets/src/native_itf.c
index 6c186ca..2d491b0 100644
--- a/net/ip/native_sockets/src/native_itf.c
+++ b/net/ip/native_sockets/src/native_itf.c
@@ -34,9 +34,12 @@ itf_flags(int if_flags)
 
     flags = 0;
 
-    if ((if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING)) {
+    if (if_flags & IFF_UP) {
         flags |= MN_ITF_F_UP;
     }
+    if (if_flags & IFF_RUNNING) {
+        flags |= MN_ITF_F_LINK;
+    }
     if (if_flags & IFF_MULTICAST) {
         flags |= MN_ITF_F_MULTICAST;
     }


[14/30] incubator-mynewt-core git commit: net/ip/lwip_base; update to LwIP to tag STABLE-2_0_2_RELEASE

Posted by ad...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/unit/mdns/test_mdns.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/unit/mdns/test_mdns.c b/net/ip/lwip_base/test/unit/mdns/test_mdns.c
index 9cff0fd..ca9be64 100644
--- a/net/ip/lwip_base/test/unit/mdns/test_mdns.c
+++ b/net/ip/lwip_base/test/unit/mdns/test_mdns.c
@@ -26,10 +26,7 @@
  *
  * This file is part of the lwIP TCP/IP stack.
  *
- * Author: Erik Ekman <er...@verisure.com>
- *
- * Please coordinate changes and requests with Erik Ekman
- * <er...@verisure.com>
+ * Author: Erik Ekman <er...@kryo.se>
  *
  */
 
@@ -45,6 +42,7 @@ START_TEST(readname_basic)
   struct pbuf *p;
   struct mdns_domain domain;
   u16_t offset;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;
@@ -63,6 +61,7 @@ START_TEST(readname_anydata)
   struct pbuf *p;
   struct mdns_domain domain;
   u16_t offset;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;
@@ -81,6 +80,7 @@ START_TEST(readname_short_buf)
   struct pbuf *p;
   struct mdns_domain domain;
   u16_t offset;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;
@@ -92,18 +92,20 @@ START_TEST(readname_short_buf)
 END_TEST
 
 START_TEST(readname_long_label)
-{  static const u8_t data[] = {
+{
+  static const u8_t data[] = {
       0x05, 'm', 'u', 'l', 't', 'i',
       0x52, 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a',
       'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a',
       'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a',
       'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a',
       'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a',
-      'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 0x00,
+      'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 0x00
   };
   struct pbuf *p;
   struct mdns_domain domain;
   u16_t offset;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;
@@ -154,11 +156,12 @@ START_TEST(readname_overflow)
       0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't',
       0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't',
       0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't',
-      0x00,
+      0x00
   };
   struct pbuf *p;
   struct mdns_domain domain;
   u16_t offset;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;
@@ -175,14 +178,15 @@ START_TEST(readname_jump_earlier)
       /* Some padding needed, not supported to jump to bytes containing dns header */
       /*  0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       /* 10 */ 0x0f, 0x0e, 0x05, 'l', 'o', 'c', 'a', 'l', 0x00, 0xab,
-      /* 20 */ 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0xc0, 0x0c,
+      /* 20 */ 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0xc0, 0x0c
   };
   static const u8_t fullname[] = {
-      0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'l', 'o', 'c', 'a', 'l', 0x00,
+      0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'l', 'o', 'c', 'a', 'l', 0x00
   };
   struct pbuf *p;
   struct mdns_domain domain;
   u16_t offset;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;
@@ -203,14 +207,15 @@ START_TEST(readname_jump_earlier_jump)
       /* 0x00 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       /* 0x08 */ 0x00, 0x00, 0x00, 0x00, 0x03, 0x0b, 0x0a, 0xf2,
       /* 0x10 */ 0x04, 'c', 'a', 's', 't', 0x00, 0xc0, 0x10,
-      /* 0x18 */ 0x05, 'm', 'u', 'l', 't', 'i', 0xc0, 0x16,
+      /* 0x18 */ 0x05, 'm', 'u', 'l', 't', 'i', 0xc0, 0x16
   };
   static const u8_t fullname[] = {
-      0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x00,
+      0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x00
   };
   struct pbuf *p;
   struct mdns_domain domain;
   u16_t offset;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;
@@ -234,16 +239,17 @@ START_TEST(readname_jump_maxdepth)
       /* 0x18 */ 0x03, 'd', 'n', 's', 0xc0, 0x10, 0xc0, 0x10,
       /* 0x20 */ 0x04, 'd', 'e', 'e', 'p', 0xc0, 0x18, 0x00,
       /* 0x28 */ 0x04, 'c', 'a', 's', 't', 0xc0, 0x20, 0xb0,
-      /* 0x30 */ 0x05, 'm', 'u', 'l', 't', 'i', 0xc0, 0x28,
+      /* 0x30 */ 0x05, 'm', 'u', 'l', 't', 'i', 0xc0, 0x28
   };
   static const u8_t fullname[] = {
       0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't',
       0x04, 'd', 'e', 'e', 'p', 0x03, 'd', 'n', 's',
-      0x04, 'n', 'a', 'm', 'e', 0x00,
+      0x04, 'n', 'a', 'm', 'e', 0x00
   };
   struct pbuf *p;
   struct mdns_domain domain;
   u16_t offset;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;
@@ -261,14 +267,15 @@ START_TEST(readname_jump_later)
 {
   static const u8_t data[] = {
       /* 0x00 */ 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0xc0, 0x10, 0x00, 0x01, 0x40,
-      /* 0x10 */ 0x05, 'l', 'o', 'c', 'a', 'l', 0x00, 0xab,
+      /* 0x10 */ 0x05, 'l', 'o', 'c', 'a', 'l', 0x00, 0xab
   };
   static const u8_t fullname[] = {
-      0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'l', 'o', 'c', 'a', 'l', 0x00,
+      0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x05, 'l', 'o', 'c', 'a', 'l', 0x00
   };
   struct pbuf *p;
   struct mdns_domain domain;
   u16_t offset;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;
@@ -285,11 +292,12 @@ END_TEST
 START_TEST(readname_half_jump)
 {
   static const u8_t data[] = {
-      0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0xc0,
+      0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0xc0
   };
   struct pbuf *p;
   struct mdns_domain domain;
   u16_t offset;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;
@@ -303,11 +311,12 @@ END_TEST
 START_TEST(readname_jump_toolong)
 {
   static const u8_t data[] = {
-      0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0xc2, 0x10, 0x00, 0x01, 0x40,
+      0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0xc2, 0x10, 0x00, 0x01, 0x40
   };
   struct pbuf *p;
   struct mdns_domain domain;
   u16_t offset;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;
@@ -322,11 +331,12 @@ START_TEST(readname_jump_loop_label)
 {
   static const u8_t data[] = {
       /*  0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-      /* 10 */ 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0xc0, 0x10,
+      /* 10 */ 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0xc0, 0x10
   };
   struct pbuf *p;
   struct mdns_domain domain;
   u16_t offset;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;
@@ -341,11 +351,12 @@ START_TEST(readname_jump_loop_jump)
 {
   static const u8_t data[] = {
       /*  0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-      /* 10 */ 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0xc0, 0x15,
+      /* 10 */ 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0xc0, 0x15
   };
   struct pbuf *p;
   struct mdns_domain domain;
   u16_t offset;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;
@@ -361,6 +372,7 @@ START_TEST(add_label_basic)
   static const u8_t data[] = { 0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x00 };
   struct mdns_domain domain;
   err_t res;
+  LWIP_UNUSED_ARG(_i);
 
   memset(&domain, 0, sizeof(domain));
   res = mdns_domain_add_label(&domain, "multi", 5);
@@ -379,6 +391,7 @@ START_TEST(add_label_long_label)
   static const char *toolong = "abcdefghijklmnopqrstuvwxyz0123456789-abcdefghijklmnopqrstuvwxyz0123456789-abcdefghijklmnopqrstuvwxyz0123456789-";
   struct mdns_domain domain;
   err_t res;
+  LWIP_UNUSED_ARG(_i);
 
   memset(&domain, 0, sizeof(domain));
   res = mdns_domain_add_label(&domain, "multi", 5);
@@ -393,6 +406,7 @@ START_TEST(add_label_full)
   static const char *label = "0123456789abcdef0123456789abcdef";
   struct mdns_domain domain;
   err_t res;
+  LWIP_UNUSED_ARG(_i);
 
   memset(&domain, 0, sizeof(domain));
   res = mdns_domain_add_label(&domain, label, (u8_t)strlen(label));
@@ -440,10 +454,11 @@ END_TEST
 START_TEST(domain_eq_basic)
 {
   static const u8_t data[] = {
-      0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x00,
+      0x05, 'm', 'u', 'l', 't', 'i', 0x04, 'c', 'a', 's', 't', 0x00
   };
   struct mdns_domain domain1, domain2;
   err_t res;
+  LWIP_UNUSED_ARG(_i);
 
   memset(&domain1, 0, sizeof(domain1));
   res = mdns_domain_add_label(&domain1, "multi", 5);
@@ -470,6 +485,7 @@ START_TEST(domain_eq_diff)
 {
   struct mdns_domain domain1, domain2;
   err_t res;
+  LWIP_UNUSED_ARG(_i);
 
   memset(&domain1, 0, sizeof(domain1));
   res = mdns_domain_add_label(&domain1, "multi", 5);
@@ -495,6 +511,7 @@ START_TEST(domain_eq_case)
 {
   struct mdns_domain domain1, domain2;
   err_t res;
+  LWIP_UNUSED_ARG(_i);
 
   memset(&domain1, 0, sizeof(domain1));
   res = mdns_domain_add_label(&domain1, "multi", 5);
@@ -522,6 +539,7 @@ START_TEST(domain_eq_anydata)
   static const u8_t data2[] = { 0x7f, 0x8c, 0x01, 0xff, 0xcf };
   struct mdns_domain domain1, domain2;
   err_t res;
+  LWIP_UNUSED_ARG(_i);
 
   memset(&domain1, 0, sizeof(domain1));
   res = mdns_domain_add_label(&domain1, (const char*)data1, sizeof(data1));
@@ -551,6 +569,7 @@ START_TEST(domain_eq_length)
 {
   struct mdns_domain domain1, domain2;
   err_t res;
+  LWIP_UNUSED_ARG(_i);
 
   memset(&domain1, 0, sizeof(domain1));
   memset(domain1.name, 0xAA, sizeof(MDNS_DOMAIN_MAXLEN));
@@ -581,6 +600,7 @@ START_TEST(compress_full_match)
   u16_t offset;
   u16_t length;
   err_t res;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;
@@ -615,6 +635,7 @@ START_TEST(compress_full_match_subset)
   u16_t offset;
   u16_t length;
   err_t res;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;
@@ -644,13 +665,14 @@ START_TEST(compress_full_match_jump)
     /* 0x00 */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
     /* 0x10 */ 0x04, 'l', 'w', 'i', 'p', 0x05, 'l', 'o', 'c', 'a', 'l', 0x00, 0xc0, 0x00, 0x02, 0x00,
-    /* 0x20 */ 0x06, 'f', 'o', 'o', 'b', 'a', 'r', 0xc0, 0x15,
+    /* 0x20 */ 0x06, 'f', 'o', 'o', 'b', 'a', 'r', 0xc0, 0x15
   };
   struct pbuf *p;
   struct mdns_domain domain;
   u16_t offset;
   u16_t length;
   err_t res;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;
@@ -685,6 +707,7 @@ START_TEST(compress_no_match)
   u16_t offset;
   u16_t length;
   err_t res;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;
@@ -718,6 +741,7 @@ START_TEST(compress_2nd_label)
   u16_t offset;
   u16_t length;
   err_t res;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;
@@ -752,6 +776,7 @@ START_TEST(compress_2nd_label_short)
   u16_t offset;
   u16_t length;
   err_t res;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;
@@ -781,13 +806,14 @@ START_TEST(compress_jump_to_jump)
       /* 0x00 */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
       /* 0x10 */ 0x04, 'l', 'w', 'i', 'p', 0x05, 'l', 'o', 'c', 'a', 'l', 0x00, 0xc0, 0x00, 0x02, 0x00,
-      /* 0x20 */ 0x07, 'b', 'a', 'n', 'a', 'n', 'a', 's', 0xc0, 0x15,
+      /* 0x20 */ 0x07, 'b', 'a', 'n', 'a', 'n', 'a', 's', 0xc0, 0x15
   };
   struct pbuf *p;
   struct mdns_domain domain;
   u16_t offset;
   u16_t length;
   err_t res;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;
@@ -827,6 +853,7 @@ START_TEST(compress_long_match)
   u16_t offset;
   u16_t length;
   err_t res;
+  LWIP_UNUSED_ARG(_i);
 
   p = pbuf_alloc(PBUF_RAW, sizeof(data), PBUF_ROM);
   p->payload = (void *)(size_t)data;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/unit/mdns/test_mdns.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/unit/mdns/test_mdns.h b/net/ip/lwip_base/test/unit/mdns/test_mdns.h
index 413ee82..c3df339 100644
--- a/net/ip/lwip_base/test/unit/mdns/test_mdns.h
+++ b/net/ip/lwip_base/test/unit/mdns/test_mdns.h
@@ -3,14 +3,6 @@
 
 #include "../lwip_check.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 Suite* mdns_suite(void);
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/unit/tcp/tcp_helper.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/unit/tcp/tcp_helper.c b/net/ip/lwip_base/test/unit/tcp/tcp_helper.c
index fc7e67f..64121ca 100644
--- a/net/ip/lwip_base/test/unit/tcp/tcp_helper.c
+++ b/net/ip/lwip_base/test/unit/tcp/tcp_helper.c
@@ -141,24 +141,33 @@ void
 tcp_set_state(struct tcp_pcb* pcb, enum tcp_state state, ip_addr_t* local_ip,
                    ip_addr_t* remote_ip, u16_t local_port, u16_t remote_port)
 {
+  u32_t iss;
+
   /* @todo: are these all states? */
   /* @todo: remove from previous list */
   pcb->state = state;
+  
+  iss = tcp_next_iss(pcb);
+  pcb->snd_wl2 = iss;
+  pcb->snd_nxt = iss;
+  pcb->lastack = iss;
+  pcb->snd_lbb = iss;
+  
   if (state == ESTABLISHED) {
     TCP_REG(&tcp_active_pcbs, pcb);
-    pcb->local_ip.addr = local_ip->addr;
+    ip_addr_copy(pcb->local_ip, *local_ip);
     pcb->local_port = local_port;
-    pcb->remote_ip.addr = remote_ip->addr;
+    ip_addr_copy(pcb->remote_ip, *remote_ip);
     pcb->remote_port = remote_port;
   } else if(state == LISTEN) {
     TCP_REG(&tcp_listen_pcbs.pcbs, pcb);
-    pcb->local_ip.addr = local_ip->addr;
+    ip_addr_copy(pcb->local_ip, *local_ip);
     pcb->local_port = local_port;
   } else if(state == TIME_WAIT) {
     TCP_REG(&tcp_tw_pcbs, pcb);
-    pcb->local_ip.addr = local_ip->addr;
+    ip_addr_copy(pcb->local_ip, *local_ip);
     pcb->local_port = local_port;
-    pcb->remote_ip.addr = remote_ip->addr;
+    ip_addr_copy(pcb->remote_ip, *remote_ip);
     pcb->remote_port = remote_port;
   } else {
     fail();
@@ -293,8 +302,8 @@ void test_tcp_init_netif(struct netif *netif, struct test_tcp_txcounters *txcoun
   }
   netif->output = test_tcp_netif_output;
   netif->flags |= NETIF_FLAG_UP | NETIF_FLAG_LINK_UP;
-  ip4_addr_copy(netif->netmask, *ip_2_ip4(netmask));
-  ip4_addr_copy(netif->ip_addr, *ip_2_ip4(ip_addr));
+  ip_addr_copy_from_ip4(netif->netmask, *ip_2_ip4(netmask));
+  ip_addr_copy_from_ip4(netif->ip_addr, *ip_2_ip4(ip_addr));
   for (n = netif_list; n != NULL; n = n->next) {
     if (n == netif) {
       return;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/unit/tcp/tcp_helper.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/unit/tcp/tcp_helper.h b/net/ip/lwip_base/test/unit/tcp/tcp_helper.h
index f666249..0497481 100644
--- a/net/ip/lwip_base/test/unit/tcp/tcp_helper.h
+++ b/net/ip/lwip_base/test/unit/tcp/tcp_helper.h
@@ -6,10 +6,6 @@
 #include "lwip/tcp.h"
 #include "lwip/netif.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /* counters used for test_tcp_counters_* callback functions */
 struct test_tcp_counters {
   u32_t recv_calls;
@@ -53,8 +49,4 @@ void test_tcp_init_netif(struct netif *netif, struct test_tcp_txcounters *txcoun
                          ip_addr_t *ip_addr, ip_addr_t *netmask);
 
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/unit/tcp/test_tcp.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/unit/tcp/test_tcp.c b/net/ip/lwip_base/test/unit/tcp/test_tcp.c
index bfcfa1d..d99b807 100644
--- a/net/ip/lwip_base/test/unit/tcp/test_tcp.c
+++ b/net/ip/lwip_base/test/unit/tcp/test_tcp.c
@@ -35,8 +35,8 @@ tcp_setup(void)
 {
   /* reset iss to default (6510) */
   tcp_ticks = 0;
-  tcp_ticks = 0 - (tcp_next_iss() - 6510);
-  tcp_next_iss();
+  tcp_ticks = 0 - (tcp_next_iss(NULL) - 6510);
+  tcp_next_iss(NULL);
   tcp_ticks = 0;
 
   test_tcp_timer = 0;
@@ -46,9 +46,9 @@ tcp_setup(void)
 static void
 tcp_teardown(void)
 {
-  tcp_remove_all();
   netif_list = NULL;
   netif_default = NULL;
+  tcp_remove_all();
 }
 
 
@@ -418,11 +418,12 @@ START_TEST(test_tcp_fast_rexmit_wraparound)
   tcp_ticks = SEQNO1 - ISS;
   pcb = test_tcp_new_counters_pcb(&counters);
   EXPECT_RET(pcb != NULL);
-  EXPECT(pcb->lastack == SEQNO1);
   tcp_set_state(pcb, ESTABLISHED, &local_ip, &remote_ip, local_port, remote_port);
   pcb->mss = TCP_MSS;
   /* disable initial congestion window (we don't send a SYN here...) */
   pcb->cwnd = 2*TCP_MSS;
+  /* start in congestion advoidance */
+  pcb->ssthresh = pcb->cwnd;
 
   /* send 6 mss-sized segments */
   for (i = 0; i < 6; i++) {
@@ -443,7 +444,9 @@ START_TEST(test_tcp_fast_rexmit_wraparound)
   /* ACK the first segment */
   p = tcp_create_rx_segment(pcb, NULL, 0, 0, TCP_MSS, TCP_ACK);
   test_tcp_input(p, &netif);
-  /* ensure this didn't trigger a retransmission */
+  /* ensure this didn't trigger a retransmission. Only one
+  segment should be transmitted because cwnd opened up by
+  TCP_MSS and a fraction since we are in congestion avoidance */
   EXPECT(txcounters.num_tx_calls == 1);
   EXPECT(txcounters.num_tx_bytes == TCP_MSS + 40U);
   memset(&txcounters, 0, sizeof(txcounters));
@@ -513,11 +516,10 @@ START_TEST(test_tcp_rto_rexmit_wraparound)
 
   /* create and initialize the pcb */
   tcp_ticks = 0;
-  tcp_ticks = 0 - tcp_next_iss();
-  tcp_ticks = SEQNO1 - tcp_next_iss();
+  tcp_ticks = 0 - tcp_next_iss(NULL);
+  tcp_ticks = SEQNO1 - tcp_next_iss(NULL);
   pcb = test_tcp_new_counters_pcb(&counters);
   EXPECT_RET(pcb != NULL);
-  EXPECT(pcb->lastack == SEQNO1);
   tcp_set_state(pcb, ESTABLISHED, &local_ip, &remote_ip, local_port, remote_port);
   pcb->mss = TCP_MSS;
   /* disable initial congestion window (we don't send a SYN here...) */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/unit/tcp/test_tcp.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/unit/tcp/test_tcp.h b/net/ip/lwip_base/test/unit/tcp/test_tcp.h
index c6c56dd..f28ee56 100644
--- a/net/ip/lwip_base/test/unit/tcp/test_tcp.h
+++ b/net/ip/lwip_base/test/unit/tcp/test_tcp.h
@@ -3,14 +3,6 @@
 
 #include "../lwip_check.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 Suite *tcp_suite(void);
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/unit/tcp/test_tcp_oos.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/unit/tcp/test_tcp_oos.h b/net/ip/lwip_base/test/unit/tcp/test_tcp_oos.h
index d0b7976..5b82013 100644
--- a/net/ip/lwip_base/test/unit/tcp/test_tcp_oos.h
+++ b/net/ip/lwip_base/test/unit/tcp/test_tcp_oos.h
@@ -3,14 +3,6 @@
 
 #include "../lwip_check.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 Suite *tcp_oos_suite(void);
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/unit/udp/test_udp.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/unit/udp/test_udp.h b/net/ip/lwip_base/test/unit/udp/test_udp.h
index 783739c..5426bf4 100644
--- a/net/ip/lwip_base/test/unit/udp/test_udp.h
+++ b/net/ip/lwip_base/test/unit/udp/test_udp.h
@@ -3,14 +3,6 @@
 
 #include "../lwip_check.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 Suite* udp_suite(void);
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif


[09/30] incubator-mynewt-core git commit: STM32 ethernet driver for LwIP. Make it functional.

Posted by ad...@apache.org.
STM32 ethernet driver for LwIP. Make it functional.


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/c5f8cf66
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/c5f8cf66
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/c5f8cf66

Branch: refs/heads/master
Commit: c5f8cf661026c137cf5832133183b8a76452df9b
Parents: 0092753
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Fri Apr 14 10:37:34 2017 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Fri Apr 14 13:21:30 2017 -0700

----------------------------------------------------------------------
 .../stm32_eth/include/stm32_eth/stm32_eth.h     |  49 ++
 .../stm32_eth/include/stm32_eth/stm32_eth_cfg.h |  47 ++
 hw/drivers/lwip/stm32_eth/pkg.yml               |  41 +
 hw/drivers/lwip/stm32_eth/src/stm32_eth.c       | 538 +++++++++++++
 .../include/stm32f4_eth/stm32f4_eth.h           |  27 -
 .../include/stm32f4_eth/stm32f4_eth_cfg.h       |  32 -
 hw/drivers/lwip/stm32f4_eth/pkg.yml             |  33 -
 hw/drivers/lwip/stm32f4_eth/src/stm32f4_eth.c   | 746 -------------------
 8 files changed, 675 insertions(+), 838 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/c5f8cf66/hw/drivers/lwip/stm32_eth/include/stm32_eth/stm32_eth.h
----------------------------------------------------------------------
diff --git a/hw/drivers/lwip/stm32_eth/include/stm32_eth/stm32_eth.h b/hw/drivers/lwip/stm32_eth/include/stm32_eth/stm32_eth.h
new file mode 100644
index 0000000..fa2f048
--- /dev/null
+++ b/hw/drivers/lwip/stm32_eth/include/stm32_eth/stm32_eth.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 __STM32_ETH_H__
+#define __STM32_ETH_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Initialize the ethernet device with cfg.
+ *
+ * @param cfg HW specific configuration.
+ *
+ * @return int 0 on success, non-zero error code on failure.
+ */
+int stm32_eth_init(const void *cfg);
+
+/*
+ * Set the MAC address for ethernet to use.
+ *
+ * @param addr Byte array of 6 bytes to use as MAC address.
+ *
+ * @return int 0 on success, non-zero error code on failure.
+ */
+int stm32_eth_set_hwaddr(uint8_t *addr);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __STM32_ETH_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/c5f8cf66/hw/drivers/lwip/stm32_eth/include/stm32_eth/stm32_eth_cfg.h
----------------------------------------------------------------------
diff --git a/hw/drivers/lwip/stm32_eth/include/stm32_eth/stm32_eth_cfg.h b/hw/drivers/lwip/stm32_eth/include/stm32_eth/stm32_eth_cfg.h
new file mode 100644
index 0000000..db11201
--- /dev/null
+++ b/hw/drivers/lwip/stm32_eth/include/stm32_eth/stm32_eth_cfg.h
@@ -0,0 +1,47 @@
+/*
+ * 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 __STM32_ETH_CFG_H__
+#define __STM32_ETH_CFG_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * BSP specific ethernet settings.
+ */
+#define STM32_MAX_PORTS	9
+
+struct stm32_eth_cfg {
+    /* Mask of pins from ports A-I to use */
+    uint32_t sec_port_mask[STM32_MAX_PORTS];
+    enum {
+        SMSC_8710_RMII,
+        LAN_8742_RMII
+    } sec_phy_type;
+    int sec_phy_irq;
+    uint8_t sec_phy_addr;
+};
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __STM32_ETH_CFG_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/c5f8cf66/hw/drivers/lwip/stm32_eth/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/drivers/lwip/stm32_eth/pkg.yml b/hw/drivers/lwip/stm32_eth/pkg.yml
new file mode 100644
index 0000000..5250d4d
--- /dev/null
+++ b/hw/drivers/lwip/stm32_eth/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/drivers/lwip/stm32_eth
+pkg.description: Driver for STM32FXXXX on-chip ethernet
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+    - ip
+    - lwip
+    - ethernet
+pkg.deps:
+    - hw/hal
+    - net/ip/lwip_base
+
+pkg.deps.MCU_STM32F4:
+    - hw/mcu/stm/stm32f4xx
+
+pkg.deps.MCU_STM32F7:
+    - hw/mcu/stm/stm32f7xx
+
+pkg.req_apis: 
+
+pkg.init:
+    stm32_eth_open: 240

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/c5f8cf66/hw/drivers/lwip/stm32_eth/src/stm32_eth.c
----------------------------------------------------------------------
diff --git a/hw/drivers/lwip/stm32_eth/src/stm32_eth.c b/hw/drivers/lwip/stm32_eth/src/stm32_eth.c
new file mode 100755
index 0000000..c9f028d
--- /dev/null
+++ b/hw/drivers/lwip/stm32_eth/src/stm32_eth.c
@@ -0,0 +1,538 @@
+/**
+ * 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 <syscfg/syscfg.h>
+
+#include <hal/hal_gpio.h>
+#include <hal/hal_timer.h>
+#include <bsp/cmsis_nvic.h>
+
+#include <os/os_cputime.h>
+
+#if MYNEWT_VAL(MCU_STM32F4)
+#include <bsp/stm32f4xx_hal_conf.h>
+#include <mcu/stm32f4_bsp.h>
+#endif
+#if MYNEWT_VAL(MCU_STM32F7)
+#include <bsp/stm32f7xx_hal_conf.h>
+#include <mcu/stm32f7_bsp.h>
+#endif
+
+#include <netif/etharp.h>
+#include <netif/ethernet.h>
+#include <lwip/tcpip.h>
+#include <lwip/ethip6.h>
+#include <string.h>
+
+#include "stm32_eth/stm32_eth.h"
+#include "stm32_eth/stm32_eth_cfg.h"
+
+/*
+ * PHY polling frequency, when HW has no interrupt line to report link status
+ * changes.
+ *
+ * Note STM32F767ZI errata regarding RMII sometimes corrupting RX.
+ * This shows up as MMCRFCECR going up, and no valid RX happening.
+ */
+#define STM32_PHY_POLL_FREQ os_cputime_usecs_to_ticks(1500000) /* 1.5 secs */
+
+/*
+ * Phy specific registers
+ */
+#define SMSC_8710_ISR 29
+#define SMSC_8710_IMR 30
+
+#define SMSC_8710_ISR_AUTO_DONE 0x40
+#define SMSC_8710_ISR_LINK_DOWN 0x10
+
+#define STM32_ETH_RX_DESC_SZ 3
+#define STM32_ETH_TX_DESC_SZ 4
+
+struct stm32_eth_desc {
+    volatile ETH_DMADescTypeDef desc;
+    struct pbuf *p;
+};
+
+struct stm32_eth_state {
+    struct netif st_nif;
+    ETH_HandleTypeDef st_eth;
+    struct stm32_eth_desc st_rx_descs[STM32_ETH_RX_DESC_SZ];
+    struct stm32_eth_desc st_tx_descs[STM32_ETH_TX_DESC_SZ];
+    uint8_t st_rx_head;
+    uint8_t st_rx_tail;
+    uint8_t st_tx_head;
+    uint8_t st_tx_tail;
+    struct hal_timer st_phy_tmr;
+    const struct stm32_eth_cfg *cfg;
+};
+
+struct stm32_eth_stats {
+    uint32_t oframe;
+    uint32_t odone;
+    uint32_t oerr;
+    uint32_t iframe;
+    uint32_t imem;
+} stm32_eth_stats;
+
+static struct stm32_eth_state stm32_eth_state;
+
+static void
+stm32_eth_setup_descs(struct stm32_eth_desc *descs, int cnt)
+{
+    int i;
+
+    for (i = 0; i < cnt - 1; i++) {
+        descs[i].desc.Status = 0;
+        descs[i].desc.Buffer2NextDescAddr = (uint32_t)&descs[i + 1].desc;
+    }
+    descs[cnt - 1].desc.Status = 0;
+    descs[cnt - 1].desc.Buffer2NextDescAddr = (uint32_t)&descs[0].desc;
+}
+
+static void
+stm32_eth_fill_rx(struct stm32_eth_state *ses)
+{
+    struct stm32_eth_desc *sed;
+    struct pbuf *p;
+
+    while (1) {
+        sed = &ses->st_rx_descs[ses->st_rx_tail];
+        if (sed->p) {
+            break;
+        }
+        p = pbuf_alloc(PBUF_RAW, ETH_MAX_PACKET_SIZE, PBUF_POOL);
+        if (!p) {
+            ++stm32_eth_stats.imem;
+            break;
+        }
+        sed->p = p;
+        sed->desc.Status = 0;
+        sed->desc.ControlBufferSize = ETH_DMARXDESC_RCH | ETH_MAX_PACKET_SIZE;
+        sed->desc.Buffer1Addr = (uint32_t)p->payload;
+        sed->desc.Status = ETH_DMARXDESC_OWN;
+
+        ses->st_rx_tail++;
+        if (ses->st_rx_tail >= STM32_ETH_RX_DESC_SZ) {
+            ses->st_rx_tail = 0;
+        }
+    }
+}
+
+static struct pbuf *
+stm32_eth_input(struct stm32_eth_state *ses)
+{
+    struct stm32_eth_desc *sed;
+    struct pbuf *p;
+    struct netif *nif;
+
+    nif = &ses->st_nif;
+
+    while (1) {
+        sed = &ses->st_rx_descs[ses->st_rx_head];
+        if (!sed->p) {
+            break;
+        }
+        if (sed->desc.Status & ETH_DMARXDESC_OWN) {
+            break;
+        }
+        p = sed->p;
+        sed->p = NULL;
+        if (!(sed->desc.Status & ETH_DMARXDESC_LS)) {
+            /*
+             * Incoming data spans multiple pbufs. XXX support later
+             */
+            pbuf_free(p);
+            continue;
+        }
+        p->len = p->tot_len = (sed->desc.Status & ETH_DMARXDESC_FL) >> 16;
+        ++stm32_eth_stats.iframe;
+        nif->input(p, nif);
+        ses->st_rx_head++;
+        if (ses->st_rx_head >= STM32_ETH_RX_DESC_SZ) {
+            ses->st_rx_head = 0;
+        }
+    }
+
+    stm32_eth_fill_rx(ses);
+
+    if (ses->st_eth.Instance->DMASR & ETH_DMASR_RBUS)  {
+        /*
+         * Resume DMA reception
+         */
+        ses->st_eth.Instance->DMASR = ETH_DMASR_RBUS;
+        ses->st_eth.Instance->DMARPDR = 0;
+    }
+
+    return p;
+}
+
+void
+HAL_ETH_RxCpltCallback(ETH_HandleTypeDef *heth)
+{
+    stm32_eth_input(&stm32_eth_state);
+}
+
+/*
+ * Hardware configuration. Should be called from BSP init.
+ */
+int
+stm32_eth_init(const void *cfg)
+{
+    stm32_eth_state.cfg = (const struct stm32_eth_cfg *)cfg;
+    return 0;
+}
+
+/*
+ * XXX do proper multicast filtering at some stage
+ */
+#if LWIP_IGMP
+static err_t
+stm32_igmp_mac_filter(struct netif *nif, const ip4_addr_t *group,
+  enum netif_mac_filter_action action)
+{
+    return -1;
+}
+#endif
+
+#if LWIP_IPV6 && LWIP_IPV6_MLD
+static err_t
+stm32_mld_mac_filter(struct netif *nif, const ip6_addr_t *group,
+  enum netif_mac_filter_action action)
+{
+    return -1;
+}
+#endif
+
+static void
+stm32_eth_output_done(struct stm32_eth_state *ses)
+{
+    struct stm32_eth_desc *sed;
+
+    while (1) {
+        sed = &ses->st_tx_descs[ses->st_tx_tail];
+        if (!sed->p) {
+            break;
+        }
+        if (sed->desc.Status & ETH_DMATXDESC_OWN) {
+            /*
+             * Belongs to board
+             */
+            break;
+        }
+        if (sed->desc.Status & ETH_DMATXDESC_ES) {
+            ++stm32_eth_stats.oerr;
+        } else {
+            ++stm32_eth_stats.odone;
+        }
+        pbuf_free(sed->p);
+        sed->p = NULL;
+        ses->st_tx_tail++;
+        if (ses->st_tx_tail >= STM32_ETH_TX_DESC_SZ) {
+            ses->st_tx_tail = 0;
+        }
+    }
+}
+
+static err_t
+stm32_eth_output(struct netif *nif, struct pbuf *p)
+{
+    struct stm32_eth_state *ses = (struct stm32_eth_state *)nif;
+    struct stm32_eth_desc *sed;
+    uint32_t reg;
+    struct pbuf *q;
+    err_t errval;
+
+    stm32_eth_output_done(ses);
+
+    ++stm32_eth_stats.oframe;
+    sed = &ses->st_tx_descs[ses->st_tx_head];
+    for (q = p; q; q = q->next) {
+        if (!q->len) {
+            continue;
+        }
+        if (sed->desc.Status & ETH_DMATXDESC_OWN) {
+            /*
+             * Not enough space.
+             */
+            errval = ERR_MEM;
+            goto error;
+        }
+        sed = (struct stm32_eth_desc *)sed->desc.Buffer2NextDescAddr;
+    }
+
+    for (q = p; q; q = q->next) {
+        if (!q->len) {
+            continue;
+        }
+        sed = &ses->st_tx_descs[ses->st_tx_head];
+        if (q == p) {
+            reg = ETH_DMATXDESC_FS | ETH_DMATXDESC_TCH;
+        } else {
+            reg = ETH_DMATXDESC_TCH;
+        }
+        if (q->next == NULL) {
+            reg |= ETH_DMATXDESC_LS;
+        }
+        sed->desc.Status = reg;
+        sed->desc.ControlBufferSize = p->len;
+        sed->desc.Buffer1Addr = (uint32_t)p->payload;
+        sed->p = p;
+        pbuf_ref(p);
+        sed->desc.Status = reg | ETH_DMATXDESC_OWN;
+        ses->st_tx_head++;
+        if (ses->st_tx_head >= STM32_ETH_TX_DESC_SZ) {
+            ses->st_tx_head = 0;
+        }
+    }
+
+    if (ses->st_eth.Instance->DMASR & ETH_DMASR_TBUS) {
+        /*
+         * Resume DMA transmission.
+         */
+        ses->st_eth.Instance->DMASR = ETH_DMASR_TBUS;
+        ses->st_eth.Instance->DMATPDR = 0U;
+    }
+
+    return ERR_OK;
+error:
+    ++stm32_eth_stats.oerr;
+    return errval;
+}
+
+static void
+stm32_eth_isr(void)
+{
+    HAL_ETH_IRQHandler(&stm32_eth_state.st_eth);
+}
+
+static void
+stm32_phy_isr(void *arg)
+{
+    struct stm32_eth_state *ses = (void *)arg;
+    uint32_t reg;
+
+    HAL_ETH_ReadPHYRegister(&ses->st_eth, PHY_BSR, &reg);
+    if (reg & PHY_LINKED_STATUS &&
+        (ses->st_nif.flags & NETIF_FLAG_LINK_UP) == 0) {
+        netif_set_link_up(&ses->st_nif);
+    } else if ((reg & PHY_LINKED_STATUS) == 0 &&
+               ses->st_nif.flags & NETIF_FLAG_LINK_UP) {
+        netif_set_link_down(&ses->st_nif);
+    }
+    switch (ses->cfg->sec_phy_type) {
+    case SMSC_8710_RMII:
+    case LAN_8742_RMII:
+        HAL_ETH_ReadPHYRegister(&ses->st_eth, SMSC_8710_ISR, &reg);
+    }
+}
+
+static void
+stm32_phy_poll(void *arg)
+{
+    struct stm32_eth_state *ses = (void *)arg;
+
+    stm32_phy_isr(arg);
+    os_cputime_timer_relative(&ses->st_phy_tmr, STM32_PHY_POLL_FREQ);
+}
+
+static err_t
+stm32_lwip_init(struct netif *nif)
+{
+    struct stm32_eth_state *ses = &stm32_eth_state;
+    int i, j;
+    const struct stm32_eth_cfg *cfg;
+    uint32_t reg;
+
+    /*
+     * LwIP clears most of these field in netif_add() before calling
+     * this init routine. So we need to fill them in here.
+     */
+    memcpy(nif->name, "st", 2);
+    nif->output = etharp_output;
+#if LWIP_IPV6
+    nif->output_ip6 = ethip6_output;
+#endif
+    nif->linkoutput = stm32_eth_output;
+    nif->mtu = 1500;
+    nif->hwaddr_len = ETHARP_HWADDR_LEN;
+    nif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP;
+
+#if LWIP_IGMP
+    nif->flags |= NETIF_FLAG_IGMP;
+    nif->igmp_mac_filter = stm32_igmp_mac_filter;
+#endif
+#if LWIP_IPV6 && LWIP_IPV6_MLD
+    nif->flags |= NETIF_FLAG_MLD6;
+    nif->mld_mac_filter = stm32_mld_mac_filter;
+#endif
+
+    cfg = ses->cfg;
+
+    /*
+     * Now take the BSP specific HW config and set up the hardware.
+     */
+    for (i = 0; i < STM32_MAX_PORTS; i++) {
+        for (j = 0; j < 32; j++) {
+            if ((cfg->sec_port_mask[i] & (1 << j)) == 0) {
+                continue;
+            }
+            hal_gpio_init_af(i * 16 + j, GPIO_AF11_ETH, GPIO_NOPULL, 0);
+        }
+    }
+
+    NVIC_SetVector(ETH_IRQn, (uint32_t)stm32_eth_isr);
+    __HAL_RCC_ETH_CLK_ENABLE();
+
+    ses->st_eth.Instance = ETH;
+
+    ses->st_eth.Init.AutoNegotiation = ETH_AUTONEGOTIATION_ENABLE;
+    ses->st_eth.Init.Speed = ETH_SPEED_100M;
+    ses->st_eth.Init.DuplexMode = ETH_MODE_FULLDUPLEX;
+    ses->st_eth.Init.PhyAddress = cfg->sec_phy_addr;
+    ses->st_eth.Init.RxMode = ETH_RXINTERRUPT_MODE;
+    ses->st_eth.Init.ChecksumMode = ETH_CHECKSUM_BY_HARDWARE;
+
+    switch (cfg->sec_phy_type) {
+    case SMSC_8710_RMII:
+    case LAN_8742_RMII:
+        ses->st_eth.Init.MediaInterface = ETH_MEDIA_INTERFACE_RMII;
+    }
+
+    ses->st_rx_head = 0;
+    ses->st_rx_tail = 0;
+    ses->st_tx_head = 0;
+    ses->st_tx_tail = 0;
+
+    stm32_eth_setup_descs(ses->st_rx_descs, STM32_ETH_RX_DESC_SZ);
+    stm32_eth_setup_descs(ses->st_tx_descs, STM32_ETH_TX_DESC_SZ);
+    stm32_eth_fill_rx(ses);
+
+    if (HAL_ETH_Init(&ses->st_eth) == HAL_ERROR) {
+        return ERR_IF;
+    }
+
+    /*
+     * XXX pass all multicast traffic for now
+     */
+    ses->st_eth.Instance->MACFFR |= ETH_MULTICASTFRAMESFILTER_NONE;
+    ses->st_eth.Instance->DMATDLAR = (uint32_t)ses->st_tx_descs;
+    ses->st_eth.Instance->DMARDLAR = (uint32_t)ses->st_rx_descs;
+
+    /*
+     * Generate an interrupt when link state changes
+     */
+    if (cfg->sec_phy_irq >= 0) {
+        switch (cfg->sec_phy_type) {
+        case SMSC_8710_RMII:
+            HAL_ETH_ReadPHYRegister(&ses->st_eth, SMSC_8710_IMR, &reg);
+            reg |= (SMSC_8710_ISR_AUTO_DONE | SMSC_8710_ISR_LINK_DOWN);
+            HAL_ETH_WritePHYRegister(&ses->st_eth, SMSC_8710_IMR, reg);
+        case LAN_8742_RMII:
+            /* XXX */
+            break;
+        }
+    } else {
+        os_cputime_timer_init(&ses->st_phy_tmr, stm32_phy_poll, ses);
+        os_cputime_timer_relative(&ses->st_phy_tmr, STM32_PHY_POLL_FREQ);
+    }
+    NVIC_EnableIRQ(ETH_IRQn);
+    HAL_ETH_Start(&ses->st_eth);
+
+    /*
+     * Check for link.
+     */
+    stm32_phy_isr(ses);
+    return ERR_OK;
+}
+
+int
+stm32_mii_dump(void (*func)(const char *fmt, ...))
+{
+    int i;
+    struct stm32_eth_state *ses = &stm32_eth_state;
+    uint32_t reg;
+    int rc;
+
+    for (i = 0; i <= 6; i++) {
+        rc = HAL_ETH_ReadPHYRegister(&ses->st_eth, i, &reg);
+        func("%d: %x (%d)\n", i, reg, rc);
+    }
+    for (i = 17; i <= 18; i++) {
+        rc = HAL_ETH_ReadPHYRegister(&ses->st_eth, i, &reg);
+        func("%d: %x (%d)\n", i, reg, rc);
+    }
+    for (i = 26; i <= 31; i++) {
+        rc = HAL_ETH_ReadPHYRegister(&ses->st_eth, i, &reg);
+        func("%d: %x (%d)\n", i, reg, rc);
+    }
+    return 0;
+}
+
+int
+stm32_eth_set_hwaddr(uint8_t *addr)
+{
+    struct stm32_eth_state *ses = &stm32_eth_state;
+
+    if (ses->st_nif.name[0] != '\0') {
+        /*
+         * Needs to be called before stm32_eth_open() is called.
+         */
+        return -1;
+    }
+    memcpy(ses->st_nif.hwaddr, addr, ETHARP_HWADDR_LEN);
+    ses->st_eth.Init.MACAddr = ses->st_nif.hwaddr;
+    return 0;
+}
+
+int
+stm32_eth_open(void)
+{
+    struct stm32_eth_state *ses = &stm32_eth_state;
+    struct netif *nif;
+    struct ip4_addr addr;
+    int rc;
+
+    if (ses->cfg == NULL) {
+        /*
+         * HW configuration not passed in.
+         */
+        return -1;
+    }
+    if (ses->st_eth.Init.MACAddr == NULL) {
+        /*
+         * MAC address not set
+         */
+        return -1;
+    }
+
+    if (ses->cfg->sec_phy_irq >= 0) {
+        rc = hal_gpio_irq_init(ses->cfg->sec_phy_irq, stm32_phy_isr, ses,
+                               HAL_GPIO_TRIG_FALLING, HAL_GPIO_PULL_UP);
+        assert(rc == 0);
+    }
+
+    /*
+     * Register network interface with LwIP.
+     */
+    memset(&addr, 0, sizeof(addr));
+    nif = netif_add(&ses->st_nif, &addr, &addr, &addr, NULL, stm32_lwip_init,
+                    tcpip_input);
+    assert(nif);
+    return 0;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/c5f8cf66/hw/drivers/lwip/stm32f4_eth/include/stm32f4_eth/stm32f4_eth.h
----------------------------------------------------------------------
diff --git a/hw/drivers/lwip/stm32f4_eth/include/stm32f4_eth/stm32f4_eth.h b/hw/drivers/lwip/stm32f4_eth/include/stm32f4_eth/stm32f4_eth.h
deleted file mode 100644
index c9dde0d..0000000
--- a/hw/drivers/lwip/stm32f4_eth/include/stm32f4_eth/stm32f4_eth.h
+++ /dev/null
@@ -1,27 +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.
- */
-
-#ifndef __STM32F4_ETH_H__
-#define __STM32F4_ETH_H__
-
-int stm32f4_eth_init(void *cfg);
-int stm32f4_eth_open(void);
-int stm32f4_eth_close(void);
-
-#endif /* __STM32F4_ETH_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/c5f8cf66/hw/drivers/lwip/stm32f4_eth/include/stm32f4_eth/stm32f4_eth_cfg.h
----------------------------------------------------------------------
diff --git a/hw/drivers/lwip/stm32f4_eth/include/stm32f4_eth/stm32f4_eth_cfg.h b/hw/drivers/lwip/stm32f4_eth/include/stm32f4_eth/stm32f4_eth_cfg.h
deleted file mode 100644
index 49f5fed..0000000
--- a/hw/drivers/lwip/stm32f4_eth/include/stm32f4_eth/stm32f4_eth_cfg.h
+++ /dev/null
@@ -1,32 +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.
- */
-
-#ifndef __STM32F4_ETH_CFG_H__
-#define __STM32F4_ETH_CFG_H__
-
-/*
- * BSP specific ethernet settings.
- */
-#define STM32F4_MAX_PORTS	9
-
-struct stm32f4_eth_cfg {
-    /* Mask of pins from ports A-I to use */
-    uint32_t sec_port_mask[STM32F4_MAX_PORTS];
-};
-#endif /* __STM32F4_ETH_CFG_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/c5f8cf66/hw/drivers/lwip/stm32f4_eth/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/drivers/lwip/stm32f4_eth/pkg.yml b/hw/drivers/lwip/stm32f4_eth/pkg.yml
deleted file mode 100644
index 606bf1f..0000000
--- a/hw/drivers/lwip/stm32f4_eth/pkg.yml
+++ /dev/null
@@ -1,33 +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.
-#
-
-pkg.name: hw/drivers/lwip/stm32f4_eth
-pkg.description: Driver for STM43F4 on-chip ethernet
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-    - ip
-    - lwip
-    - ethernet
-pkg.deps:
-    - hw/hal
-    - hw/mcu/stm/stm32f4xx
-    - net/ip/lwip_base
-pkg.req_apis: 
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/c5f8cf66/hw/drivers/lwip/stm32f4_eth/src/stm32f4_eth.c
----------------------------------------------------------------------
diff --git a/hw/drivers/lwip/stm32f4_eth/src/stm32f4_eth.c b/hw/drivers/lwip/stm32f4_eth/src/stm32f4_eth.c
deleted file mode 100755
index 0660a19..0000000
--- a/hw/drivers/lwip/stm32f4_eth/src/stm32f4_eth.c
+++ /dev/null
@@ -1,746 +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.
- */
-
-#include <hal/hal_gpio.h>
-#include <bsp/cmsis_nvic.h>
-
-#include <stm32f4xx.h>
-#include <stm32f4xx_hal_gpio.h>
-#include <stm32f4xx_hal_eth.h>
-#include <stm32f4xx_hal_rcc.h>
-#include <mcu/stm32f4_bsp.h>
-
-#include <netif/etharp.h>
-#include <netif/ethernet.h>
-#include <lwip/ethip6.h>
-#include <string.h>
-
-#include "stm32f4_eth/stm32f4_eth.h"
-#include "stm32f4_eth/stm32f4_eth_cfg.h"
-
-#if 0
-/* Private typedef -----------------------------------------------------------*/
-/* Private define ------------------------------------------------------------*/
-/* Network interface name */
-#define IFNAME0 's'
-#define IFNAME1 't'
-
-/* Private macro -------------------------------------------------------------*/
-/* Private variables ---------------------------------------------------------*/
-#if defined ( __ICCARM__ ) /*!< IAR Compiler */
-  #pragma data_alignment=4
-#endif
-__ALIGN_BEGIN ETH_DMADescTypeDef  DMARxDscrTab[ETH_RXBUFNB] __ALIGN_END;/* Ethernet Rx MA Descriptor */
-
-#if defined ( __ICCARM__ ) /*!< IAR Compiler */
-  #pragma data_alignment=4
-#endif
-__ALIGN_BEGIN ETH_DMADescTypeDef  DMATxDscrTab[ETH_TXBUFNB] __ALIGN_END;/* Ethernet Tx DMA Descriptor */
-
-#if defined ( __ICCARM__ ) /*!< IAR Compiler */
-  #pragma data_alignment=4
-#endif
-__ALIGN_BEGIN uint8_t Rx_Buff[ETH_RXBUFNB][ETH_RX_BUF_SIZE] __ALIGN_END; /* Ethernet Receive Buffer */
-
-#if defined ( __ICCARM__ ) /*!< IAR Compiler */
-  #pragma data_alignment=4
-#endif
-__ALIGN_BEGIN uint8_t Tx_Buff[ETH_TXBUFNB][ETH_TX_BUF_SIZE] __ALIGN_END; /* Ethernet Transmit Buffer */
-
-ETH_HandleTypeDef EthHandle;
-
-/* Private function prototypes -----------------------------------------------*/
-/* Private functions ---------------------------------------------------------*/
-/*******************************************************************************
-                       Ethernet MSP Routines
-*******************************************************************************/
-/**
-  * @brief  Initializes the ETH MSP.
-  * @param  heth: ETH handle
-  * @retval None
-  */
-void HAL_ETH_MspInit(ETH_HandleTypeDef *heth)
-{ 
-  GPIO_InitTypeDef GPIO_InitStructure;
-  
-  /* Enable GPIOs clocks */
-  __HAL_RCC_GPIOA_CLK_ENABLE();
-  __HAL_RCC_GPIOB_CLK_ENABLE();
-  __HAL_RCC_GPIOC_CLK_ENABLE();
-  __HAL_RCC_GPIOF_CLK_ENABLE();
-  __HAL_RCC_GPIOG_CLK_ENABLE();
-  __HAL_RCC_GPIOH_CLK_ENABLE();
-  __HAL_RCC_GPIOI_CLK_ENABLE(); 
-
-/* Ethernet pins configuration ************************************************/
-   /*
-        ETH_MDIO -------------------------> PA2
-        ETH_MDC --------------------------> PC1
-        ETH_PPS_OUT ----------------------> PB5
-        ETH_MII_CRS ----------------------> PH2
-        ETH_MII_COL ----------------------> PH3
-        ETH_MII_RX_ER --------------------> PI10
-        ETH_MII_RXD2 ---------------------> PH6
-        ETH_MII_RXD3 ---------------------> PH7
-        ETH_MII_TX_CLK -------------------> PC3
-        ETH_MII_TXD2 ---------------------> PC2
-        ETH_MII_TXD3 ---------------------> PB8
-        ETH_MII_RX_CLK/ETH_RMII_REF_CLK---> PA1
-        ETH_MII_RX_DV/ETH_RMII_CRS_DV ----> PA7
-        ETH_MII_RXD0/ETH_RMII_RXD0 -------> PC4
-        ETH_MII_RXD1/ETH_RMII_RXD1 -------> PC5
-        ETH_MII_TX_EN/ETH_RMII_TX_EN -----> PG11
-        ETH_MII_TXD0/ETH_RMII_TXD0 -------> PG13
-        ETH_MII_TXD1/ETH_RMII_TXD1 -------> PG14
-                                                  */
-
-  /* Configure PA1, PA2 , PA7 */
-  GPIO_InitStructure.Pin = GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_7;
-  GPIO_InitStructure.Speed = GPIO_SPEED_HIGH;
-  GPIO_InitStructure.Mode = GPIO_MODE_AF_PP;
-  GPIO_InitStructure.Pull = GPIO_NOPULL; 
-  GPIO_InitStructure.Alternate = GPIO_AF11_ETH;
-  HAL_GPIO_Init(GPIOA, &GPIO_InitStructure);
-
-  /* Configure PB5 and PB8 */
-  GPIO_InitStructure.Pin = GPIO_PIN_5 | GPIO_PIN_8;
-  HAL_GPIO_Init(GPIOB, &GPIO_InitStructure);
-
-  /* Configure PC1, PC2, PC3, PC4 and PC5 */
-  GPIO_InitStructure.Pin = GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5;
-  HAL_GPIO_Init(GPIOC, &GPIO_InitStructure);
-                             
-  /* Configure PG11, PG14 and PG13 */
-  GPIO_InitStructure.Pin =  GPIO_PIN_11 | GPIO_PIN_13 | GPIO_PIN_14;
-  HAL_GPIO_Init(GPIOG, &GPIO_InitStructure);
-
-  /* Configure PH2, PH3, PH6, PH7 */
-  GPIO_InitStructure.Pin = GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_6 | GPIO_PIN_7;
-  HAL_GPIO_Init(GPIOH, &GPIO_InitStructure);
-
-  /* Configure PI10 */
-  GPIO_InitStructure.Pin = GPIO_PIN_10;
-  HAL_GPIO_Init(GPIOI, &GPIO_InitStructure);
-  
-  /* Enable ETHERNET clock  */
-  __HAL_RCC_ETH_CLK_ENABLE();
-  
-  if (heth->Init.MediaInterface == ETH_MEDIA_INTERFACE_MII)
-  {
-    /* Output HSE clock (25MHz) on MCO pin (PA8) to clock the PHY */
-    HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_HSE, RCC_MCODIV_1);
-  }
-}
-
-/*******************************************************************************
-                       LL Driver Interface ( LwIP stack --> ETH) 
-*******************************************************************************/
-/**
-  * In this function, the hardware should be initialized.
-  * Called from ethernetif_init().
-  *
-  * @param netif the already initialized lwip network interface structure
-  *        for this ethernetif
-  */
-static void low_level_init(struct netif *netif)
-{ 
-  uint32_t regvalue = 0;
-  uint8_t macaddress[6]= { MAC_ADDR0, MAC_ADDR1, MAC_ADDR2, MAC_ADDR3, MAC_ADDR4, MAC_ADDR5 };
-
-  EthHandle.Instance = ETH;  
-  EthHandle.Init.MACAddr = macaddress;
-  EthHandle.Init.AutoNegotiation = ETH_AUTONEGOTIATION_ENABLE;
-  EthHandle.Init.Speed = ETH_SPEED_100M;
-  EthHandle.Init.DuplexMode = ETH_MODE_FULLDUPLEX;
-  EthHandle.Init.MediaInterface = ETH_MEDIA_INTERFACE_MII;
-  EthHandle.Init.RxMode = ETH_RXPOLLING_MODE;
-  EthHandle.Init.ChecksumMode = ETH_CHECKSUM_BY_HARDWARE;
-  EthHandle.Init.PhyAddress = DP83848_PHY_ADDRESS;
-  
-  /* configure ethernet peripheral (GPIOs, clocks, MAC, DMA) */
-  if (HAL_ETH_Init(&EthHandle) == HAL_OK)
-  {
-    /* Set netif link flag */
-    netif->flags |= NETIF_FLAG_LINK_UP;
-  }
-  
-  /* Initialize Tx Descriptors list: Chain Mode */
-  HAL_ETH_DMATxDescListInit(&EthHandle, DMATxDscrTab, &Tx_Buff[0][0], ETH_TXBUFNB);
-     
-  /* Initialize Rx Descriptors list: Chain Mode  */
-  HAL_ETH_DMARxDescListInit(&EthHandle, DMARxDscrTab, &Rx_Buff[0][0], ETH_RXBUFNB);
-
-  /* set MAC hardware address length */
-  netif->hwaddr_len = ETHARP_HWADDR_LEN;
-  
-  /* set MAC hardware address */
-  netif->hwaddr[0] =  MAC_ADDR0;
-  netif->hwaddr[1] =  MAC_ADDR1;
-  netif->hwaddr[2] =  MAC_ADDR2;
-  netif->hwaddr[3] =  MAC_ADDR3;
-  netif->hwaddr[4] =  MAC_ADDR4;
-  netif->hwaddr[5] =  MAC_ADDR5;
-  
-  /* maximum transfer unit */
-  netif->mtu = 1500;
-  
-  /* device capabilities */
-  /* don't set NETIF_FLAG_ETHARP if this device is not an ethernet one */
-  netif->flags |= NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP;
-  
-  /* Enable MAC and DMA transmission and reception */
-  HAL_ETH_Start(&EthHandle);
-  
-  /**** Configure PHY to generate an interrupt when Eth Link state changes ****/
-  /* Read Register Configuration */
-  HAL_ETH_ReadPHYRegister(&EthHandle, PHY_MICR, &regvalue);
-  
-  regvalue |= (PHY_MICR_INT_EN | PHY_MICR_INT_OE);
-
-  /* Enable Interrupts */
-  HAL_ETH_WritePHYRegister(&EthHandle, PHY_MICR, regvalue );
-  
-  /* Read Register Configuration */
-  HAL_ETH_ReadPHYRegister(&EthHandle, PHY_MISR, &regvalue);
-  
-  regvalue |= PHY_MISR_LINK_INT_EN;
-    
-  /* Enable Interrupt on change of link status */
-  HAL_ETH_WritePHYRegister(&EthHandle, PHY_MISR, regvalue);
-}
-
-/**
-  * This function should do the actual transmission of the packet. The packet is
-  * contained in the pbuf that is passed to the function. This pbuf
-  * might be chained.
-  *
-  * @param netif the lwip network interface structure for this ethernetif
-  * @param p the MAC packet to send (e.g. IP packet including MAC addresses and type)
-  * @return ERR_OK if the packet could be sent
-  *         an err_t value if the packet couldn't be sent
-  *
-  * @note Returning ERR_MEM here if a DMA queue of your MAC is full can lead to
-  *       strange results. You might consider waiting for space in the DMA queue
-  *       to become availale since the stack doesn't retry to send a packet
-  *       dropped because of memory failure (except for the TCP timers).
-  */
-static err_t low_level_output(struct netif *netif, struct pbuf *p)
-{
-  err_t errval;
-  struct pbuf *q;
-  uint8_t *buffer = (uint8_t *)(EthHandle.TxDesc->Buffer1Addr);
-  __IO ETH_DMADescTypeDef *DmaTxDesc;
-  uint32_t framelength = 0;
-  uint32_t bufferoffset = 0;
-  uint32_t byteslefttocopy = 0;
-  uint32_t payloadoffset = 0;
-
-  DmaTxDesc = EthHandle.TxDesc;
-  bufferoffset = 0;
-  
-  /* copy frame from pbufs to driver buffers */
-  for(q = p; q != NULL; q = q->next)
-  {
-    /* Is this buffer available? If not, goto error */
-    if((DmaTxDesc->Status & ETH_DMATXDESC_OWN) != (uint32_t)RESET)
-    {
-      errval = ERR_USE;
-      goto error;
-    }
-    
-    /* Get bytes in current lwIP buffer */
-    byteslefttocopy = q->len;
-    payloadoffset = 0;
-    
-    /* Check if the length of data to copy is bigger than Tx buffer size*/
-    while( (byteslefttocopy + bufferoffset) > ETH_TX_BUF_SIZE )
-    {
-      /* Copy data to Tx buffer*/
-      memcpy( (uint8_t*)((uint8_t*)buffer + bufferoffset), (uint8_t*)((uint8_t*)q->payload + payloadoffset), (ETH_TX_BUF_SIZE - bufferoffset) );
-      
-      /* Point to next descriptor */
-      DmaTxDesc = (ETH_DMADescTypeDef *)(DmaTxDesc->Buffer2NextDescAddr);
-      
-      /* Check if the buffer is available */
-      if((DmaTxDesc->Status & ETH_DMATXDESC_OWN) != (uint32_t)RESET)
-      {
-        errval = ERR_USE;
-        goto error;
-      }
-      
-      buffer = (uint8_t *)(DmaTxDesc->Buffer1Addr);
-      
-      byteslefttocopy = byteslefttocopy - (ETH_TX_BUF_SIZE - bufferoffset);
-      payloadoffset = payloadoffset + (ETH_TX_BUF_SIZE - bufferoffset);
-      framelength = framelength + (ETH_TX_BUF_SIZE - bufferoffset);
-      bufferoffset = 0;
-    }
-    
-    /* Copy the remaining bytes */
-    memcpy( (uint8_t*)((uint8_t*)buffer + bufferoffset), (uint8_t*)((uint8_t*)q->payload + payloadoffset), byteslefttocopy );
-    bufferoffset = bufferoffset + byteslefttocopy;
-    framelength = framelength + byteslefttocopy;
-  }
-  
-  /* Prepare transmit descriptors to give to DMA */ 
-  HAL_ETH_TransmitFrame(&EthHandle, framelength);
-  
-  errval = ERR_OK;
-  
-error:
-  
-  /* When Transmit Underflow flag is set, clear it and issue a Transmit Poll Demand to resume transmission */
-  if ((EthHandle.Instance->DMASR & ETH_DMASR_TUS) != (uint32_t)RESET)
-  {
-    /* Clear TUS ETHERNET DMA flag */
-    EthHandle.Instance->DMASR = ETH_DMASR_TUS;
-    
-    /* Resume DMA transmission*/
-    EthHandle.Instance->DMATPDR = 0;
-  }
-  return errval;
-}
-
-/**
-  * Should allocate a pbuf and transfer the bytes of the incoming
-  * packet from the interface into the pbuf.
-  *
-  * @param netif the lwip network interface structure for this ethernetif
-  * @return a pbuf filled with the received packet (including MAC header)
-  *         NULL on memory error
-  */
-static struct pbuf * low_level_input(struct netif *netif)
-{
-  struct pbuf *p = NULL;
-  struct pbuf *q;
-  uint16_t len;
-  uint8_t *buffer;
-  __IO ETH_DMADescTypeDef *dmarxdesc;
-  uint32_t bufferoffset = 0;
-  uint32_t payloadoffset = 0;
-  uint32_t byteslefttocopy = 0;
-  uint32_t i=0;
-  
-  if (HAL_ETH_GetReceivedFrame(&EthHandle) != HAL_OK)
-    return NULL;
-  
-  /* Obtain the size of the packet and put it into the "len" variable. */
-  len = EthHandle.RxFrameInfos.length;
-  buffer = (uint8_t *)EthHandle.RxFrameInfos.buffer;
-  
-  /* We allocate a pbuf chain of pbufs from the Lwip buffer pool */
-  p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL);
-  
-  if (p != NULL)
-  {
-    dmarxdesc = EthHandle.RxFrameInfos.FSRxDesc;
-    bufferoffset = 0;
-    for(q = p; q != NULL; q = q->next)
-    {
-      byteslefttocopy = q->len;
-      payloadoffset = 0;
-      
-      /* Check if the length of bytes to copy in current pbuf is bigger than Rx buffer size*/
-      while( (byteslefttocopy + bufferoffset) > ETH_RX_BUF_SIZE )
-      {
-        /* Copy data to pbuf*/
-        memcpy( (u8_t*)((u8_t*)q->payload + payloadoffset), (u8_t*)((u8_t*)buffer + bufferoffset), (ETH_RX_BUF_SIZE - bufferoffset));
-        
-        /* Point to next descriptor */
-        dmarxdesc = (ETH_DMADescTypeDef *)(dmarxdesc->Buffer2NextDescAddr);
-        buffer = (unsigned char *)(dmarxdesc->Buffer1Addr);
-        
-        byteslefttocopy = byteslefttocopy - (ETH_RX_BUF_SIZE - bufferoffset);
-        payloadoffset = payloadoffset + (ETH_RX_BUF_SIZE - bufferoffset);
-        bufferoffset = 0;
-      }
-      /* Copy remaining data in pbuf */
-      memcpy( (u8_t*)((u8_t*)q->payload + payloadoffset), (u8_t*)((u8_t*)buffer + bufferoffset), byteslefttocopy);
-      bufferoffset = bufferoffset + byteslefttocopy;
-    }
-  }
-  
-  dmarxdesc = EthHandle.RxFrameInfos.FSRxDesc;
-  
-  /* Set Own bit in Rx descriptors: gives the buffers back to DMA */
-  for (i=0; i< (EthHandle.RxFrameInfos).SegCount; i++)
-  {  
-    dmarxdesc->Status = ETH_DMARXDESC_OWN;
-    dmarxdesc = (ETH_DMADescTypeDef *)(dmarxdesc->Buffer2NextDescAddr);
-  }
-  
-  /* Clear Segment_Count */
-  (EthHandle.RxFrameInfos).SegCount =0;
-  
-  /* When Rx Buffer unavailable flag is set: clear it and resume reception */
-  if (((EthHandle.Instance)->DMASR & ETH_DMASR_RBUS) != (uint32_t)RESET)  
-  {
-    /* Clear RBUS ETHERNET DMA flag */
-    (EthHandle.Instance)->DMASR = ETH_DMASR_RBUS;
-    /* Resume DMA reception */
-    (EthHandle.Instance)->DMARPDR = 0;
-  }
-  return p;
-}
-
-/**
-  * This function should be called when a packet is ready to be read
-  * from the interface. It uses the function low_level_input() that
-  * should handle the actual reception of bytes from the network
-  * interface. Then the type of the received packet is determined and
-  * the appropriate input function is called.
-  *
-  * @param netif the lwip network interface structure for this ethernetif
-  */
-void ethernetif_input(struct netif *netif)
-{
-  err_t err;
-  struct pbuf *p;
-  
-  /* move received packet into a new pbuf */
-  p = low_level_input(netif);
-    
-  /* no packet could be read, silently ignore this */
-  if (p == NULL) return;
-    
-  /* entry point to the LwIP stack */
-  err = netif->input(p, netif);
-    
-  if (err != ERR_OK)
-  {
-    LWIP_DEBUGF(NETIF_DEBUG, ("ethernetif_input: IP input error\n"));
-    pbuf_free(p);
-    p = NULL;
-  }
-}
-
-/**
-  * Should be called at the beginning of the program to set up the
-  * network interface. It calls the function low_level_init() to do the
-  * actual setup of the hardware.
-  *
-  * This function should be passed as a parameter to netif_add().
-  *
-  * @param netif the lwip network interface structure for this ethernetif
-  * @return ERR_OK if the loopif is initialized
-  *         ERR_MEM if private data couldn't be allocated
-  *         any other err_t on error
-  */
-err_t ethernetif_init(struct netif *netif)
-{
-  LWIP_ASSERT("netif != NULL", (netif != NULL));
-  
-#if LWIP_NETIF_HOSTNAME
-  /* Initialize interface hostname */
-  netif->hostname = "lwip";
-#endif /* LWIP_NETIF_HOSTNAME */
-
-  netif->name[0] = IFNAME0;
-  netif->name[1] = IFNAME1;
-  /* We directly use etharp_output() here to save a function call.
-   * You can instead declare your own function an call etharp_output()
-   * from it if you have to do some checks before sending (e.g. if link
-   * is available...) */
-  netif->output = etharp_output;
-  netif->linkoutput = low_level_output;
-
-  /* initialize the hardware */
-  low_level_init(netif);
-
-  return ERR_OK;
-}
-
-/**
-  * @brief  Returns the current time in milliseconds
-  *         when LWIP_TIMERS == 1 and NO_SYS == 1
-  * @param  None
-  * @retval Time
-  */
-u32_t sys_now(void)
-{
-  return HAL_GetTick();
-}
-
-/**
-  * @brief  This function sets the netif link status.
-  * @param  netif: the network interface
-  * @retval None
-  */
-void ethernetif_set_link(struct netif *netif)
-{
-  uint32_t regvalue = 0;
-  
-  /* Read PHY_MISR*/
-  HAL_ETH_ReadPHYRegister(&EthHandle, PHY_MISR, &regvalue);
-  
-  /* Check whether the link interrupt has occurred or not */
-  if((regvalue & PHY_LINK_INTERRUPT) != (uint16_t)RESET)
-  {
-    /* Read PHY_SR*/
-    HAL_ETH_ReadPHYRegister(&EthHandle, PHY_SR, &regvalue);
-    
-    /* Check whether the link is up or down*/
-    if((regvalue & PHY_LINK_STATUS)!= (uint16_t)RESET)
-    {
-      netif_set_link_up(netif);
-    }
-    else
-    {
-      netif_set_link_down(netif);
-    }
-  }
-}
-
-/**
-  * @brief  Link callback function, this function is called on change of link status
-  *         to update low level driver configuration.
-  * @param  netif: The network interface
-  * @retval None
-  */
-void ethernetif_update_config(struct netif *netif)
-{
-  __IO uint32_t tickstart = 0;
-  uint32_t regvalue = 0;
-  
-  if(netif_is_link_up(netif))
-  { 
-    /* Restart the auto-negotiation */
-    if(EthHandle.Init.AutoNegotiation != ETH_AUTONEGOTIATION_DISABLE)
-    {
-      /* Enable Auto-Negotiation */
-      HAL_ETH_WritePHYRegister(&EthHandle, PHY_BCR, PHY_AUTONEGOTIATION);
-      
-      /* Get tick */
-      tickstart = HAL_GetTick();
-      
-      /* Wait until the auto-negotiation will be completed */
-      do
-      {
-        HAL_ETH_ReadPHYRegister(&EthHandle, PHY_BSR, &regvalue);
-        
-        /* Check for the Timeout ( 1s ) */
-        if((HAL_GetTick() - tickstart ) > 1000)
-        {
-          /* In case of timeout */
-          goto error;
-        }
-        
-      } while (((regvalue & PHY_AUTONEGO_COMPLETE) != PHY_AUTONEGO_COMPLETE));
-      
-      /* Read the result of the auto-negotiation */
-      HAL_ETH_ReadPHYRegister(&EthHandle, PHY_SR, &regvalue);
-      
-      /* Configure the MAC with the Duplex Mode fixed by the auto-negotiation process */
-      if((regvalue & PHY_DUPLEX_STATUS) != (uint32_t)RESET)
-      {
-        /* Set Ethernet duplex mode to Full-duplex following the auto-negotiation */
-        EthHandle.Init.DuplexMode = ETH_MODE_FULLDUPLEX;  
-      }
-      else
-      {
-        /* Set Ethernet duplex mode to Half-duplex following the auto-negotiation */
-        EthHandle.Init.DuplexMode = ETH_MODE_HALFDUPLEX;           
-      }
-      /* Configure the MAC with the speed fixed by the auto-negotiation process */
-      if(regvalue & PHY_SPEED_STATUS)
-      {  
-        /* Set Ethernet speed to 10M following the auto-negotiation */
-        EthHandle.Init.Speed = ETH_SPEED_10M; 
-      }
-      else
-      {   
-        /* Set Ethernet speed to 100M following the auto-negotiation */ 
-        EthHandle.Init.Speed = ETH_SPEED_100M;
-      }
-    }
-    else /* AutoNegotiation Disable */
-    {
-    error :
-      /* Check parameters */
-      assert_param(IS_ETH_SPEED(EthHandle.Init.Speed));
-      assert_param(IS_ETH_DUPLEX_MODE(EthHandle.Init.DuplexMode));
-      
-      /* Set MAC Speed and Duplex Mode to PHY */
-      HAL_ETH_WritePHYRegister(&EthHandle, PHY_BCR, ((uint16_t)(EthHandle.Init.DuplexMode >> 3) |
-                                                     (uint16_t)(EthHandle.Init.Speed >> 1))); 
-    }
-
-    /* ETHERNET MAC Re-Configuration */
-    HAL_ETH_ConfigMAC(&EthHandle, (ETH_MACInitTypeDef *) NULL);
-
-    /* Restart MAC interface */
-    HAL_ETH_Start(&EthHandle);   
-  }
-  else
-  {
-    /* Stop MAC interface */
-    HAL_ETH_Stop(&EthHandle);
-  }
-
-  ethernetif_notify_conn_changed(netif);
-}
-
-/**
-  * @brief  This function notify user about link status changement.
-  * @param  netif: the network interface
-  * @retval None
-  */
-__weak void ethernetif_notify_conn_changed(struct netif *netif)
-{
-  /* NOTE : This is function clould be implemented in user file 
-            when the callback is needed,
-  */  
-}
-#endif
-
-struct stm32f4_eth_state {
-    struct netif nif;
-    ETH_HandleTypeDef st_eth;
-    struct stm32f4_eth_cfg *cfg;
-};
-
-static struct stm32f4_eth_state stm32f4_eth_state;
-
-/*
- * Hardware configuration. Should be called from BSP init.
- */
-int
-stm32f4_eth_init(void *cfg)
-{
-    stm32f4_eth_state.cfg = cfg;
-    return 0;
-}
-
-#if LWIP_IGMP
-static err_t
-stm32f4_igmp_mac_filter(struct netif *nif, const ip4_addr_t *group,
-  enum netif_mac_filter_action action)
-{
-    return -1;
-}
-#endif
-
-#if LWIP_IPV6 && LWIP_IPV6_MLD
-static err_t
-stm32f4_mld_mac_filter(struct netif *nif, const ip6_addr_t *group,
-  enum netif_mac_filter_action action)
-{
-    return -1;
-}
-#endif
-
-static err_t
-stm32f4_output(struct netif *nif, struct pbuf *p)
-{
-    return ERR_OK;
-}
-
-static void
-stm32f4_eth_isr(void)
-{
-#if 0
-    HAL_ETH_IRQHandler(&stmref4_eth_State.st_eth);
-#endif
-}
-
-static err_t
-stm32f4_lwip_init(struct netif *nif)
-{
-    struct stm32f4_eth_state *ses = &stm32f4_eth_state;
-    int i, j;
-    struct stm32f4_eth_cfg *cfg;
-
-    /*
-     * LwIP clears most of these field in netif_add() before calling
-     * this init routine. So we need to fill them in here.
-     */
-    memcpy(nif->name, "st", 2);
-    nif->output = etharp_output;
-#if LWIP_IPV6
-    nif->output_ip6 = ethip6_output;
-#endif
-    nif->linkoutput = stm32f4_output;
-    nif->mtu = 1500;
-    nif->hwaddr_len = ETHARP_HWADDR_LEN;
-    nif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP;
-
-#if LWIP_IGMP
-    nif->flags |= NETIF_FLAG_IGMP;
-    nif->igmp_mac_filter = stm32f4_igmp_mac_filter;
-#endif
-#if LWIP_IPV6 && LWIP_IPV6_MLD
-    nif->flags |= NETIF_FLAG_MLD6;
-    nif->mld_mac_filter = stm32f4_mld_mac_filter;
-#endif
-
-    cfg = ses->cfg;
-
-    /*
-     * Now take the BSP specific HW config and set up the hardware.
-     */
-    for (i = 0; i < STM32F4_MAX_PORTS; i++) {
-        for (j = 0; j < 32; j++) {
-            if ((cfg->sec_port_mask[i] & (1 << j)) == 0) {
-                continue;
-            }
-#if 0
-            hal_gpio_init_af(i * 16 + j, GPIO_AF11_ETH, GPIO_NOPULL);
-#endif
-        }
-    }
-
-    NVIC_SetVector(ETH_IRQn, (uint32_t)stm32f4_eth_isr);
-    NVIC_EnableIRQ(ETH_IRQn);
-    __HAL_RCC_ETH_CLK_ENABLE();
-
-    ses->st_eth.Instance = ETH;
-    ses->st_eth.Init.MACAddr[1] = 2;
-#if 0
-    ses->st_eth.Init.Autonegotiation = ETH_AUTONEGOTIATION_ENABLE;
-#endif
-    ses->st_eth.Init.Speed = ETH_SPEED_100M;
-    ses->st_eth.Init.DuplexMode = ETH_MODE_FULLDUPLEX;
-    ses->st_eth.Init.PhyAddress = 0;
-    ses->st_eth.Init.RxMode = ETH_RXINTERRUPT_MODE;
-    ses->st_eth.Init.ChecksumMode = ETH_CHECKSUM_BY_HARDWARE;
-    ses->st_eth.Init.MediaInterface = ETH_MEDIA_INTERFACE_RMII;
-
-    return ERR_OK;
-}
-
-int
-stm32f4_eth_open(void)
-{
-    struct stm32f4_eth_state *ses = &stm32f4_eth_state;
-    struct netif *nif;
-    struct ip4_addr addr;
-
-    if (ses->cfg == NULL) {
-        return -1;
-    }
-
-    /*
-     * Register network interface with LwIP.
-     */
-    memset(&addr, 0, sizeof(addr));
-    nif = netif_add(&ses->nif, &addr, &addr, &addr, NULL, stm32f4_lwip_init,
-      ethernet_input);
-    assert(nif);
-    return 0;
-}


[08/30] incubator-mynewt-core git commit: stm32f767-nucleo; add syscfg option to enable ethernet.

Posted by ad...@apache.org.
stm32f767-nucleo; add syscfg option to enable ethernet.


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/383906f4
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/383906f4
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/383906f4

Branch: refs/heads/master
Commit: 383906f4318f518add476699c04cf7a7d961d0d0
Parents: c9afda6
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Fri Apr 14 10:44:47 2017 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Fri Apr 14 13:21:30 2017 -0700

----------------------------------------------------------------------
 hw/bsp/stm32f767-nucleo/pkg.yml       |  3 ++
 hw/bsp/stm32f767-nucleo/src/hal_bsp.c | 50 ++++++++++++++++++++++++++++++
 hw/bsp/stm32f767-nucleo/syscfg.yml    |  4 +++
 3 files changed, 57 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/383906f4/hw/bsp/stm32f767-nucleo/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/stm32f767-nucleo/pkg.yml b/hw/bsp/stm32f767-nucleo/pkg.yml
index 5b3e684..da9cfb2 100644
--- a/hw/bsp/stm32f767-nucleo/pkg.yml
+++ b/hw/bsp/stm32f767-nucleo/pkg.yml
@@ -38,3 +38,6 @@ pkg.deps:
 
 pkg.deps.UART_0:
     - hw/drivers/uart/uart_hal
+
+pkg.deps.ETH_0:
+    - hw/drivers/lwip/stm32_eth

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/383906f4/hw/bsp/stm32f767-nucleo/src/hal_bsp.c
----------------------------------------------------------------------
diff --git a/hw/bsp/stm32f767-nucleo/src/hal_bsp.c b/hw/bsp/stm32f767-nucleo/src/hal_bsp.c
index 34fd01c..6a7b8e0 100644
--- a/hw/bsp/stm32f767-nucleo/src/hal_bsp.c
+++ b/hw/bsp/stm32f767-nucleo/src/hal_bsp.c
@@ -21,6 +21,7 @@
 #include <syscfg/syscfg.h>
 
 #include <os/os_dev.h>
+#include <os/os_cputime.h>
 #if MYNEWT_VAL(UART_0)
 #include <uart/uart.h>
 #include <uart_hal/uart_hal.h>
@@ -35,6 +36,11 @@
 #include <stm32f7xx_hal_gpio_ex.h>
 #include <mcu/stm32f7_bsp.h>
 
+#if MYNEWT_VAL(ETH_0)
+#include <stm32_eth/stm32_eth.h>
+#include <stm32_eth/stm32_eth_cfg.h>
+#endif
+
 #include "bsp/bsp.h"
 
 #if MYNEWT_VAL(UART_0)
@@ -55,6 +61,41 @@ static const struct stm32f7_uart_cfg uart_cfg[UART_CNT] = {
 };
 #endif
 
+#if MYNEWT_VAL(ETH_0)
+static const struct stm32_eth_cfg eth_cfg = {
+    /*
+     * PORTA
+     *   PA1 - ETH_RMII_REF_CLK
+     *   PA2 - ETH_RMII_MDIO
+     *   PA7 - ETH_RMII_CRS_DV
+     */
+    .sec_port_mask[0] = (1 << 1) | (1 << 2) | (1 << 7),
+
+    /*
+     * PORTB
+     *   PB13 - ETH_RMII_TXD1
+     */
+    .sec_port_mask[1] = (1 << 13),
+
+    /*
+     * PORTC
+     *   PC1 - ETH_RMII_MDC
+     *   PC4 - ETH_RMII_RXD0
+     *   PC5 - ETH_RMII_RXD1
+     */
+    .sec_port_mask[2] = (1 << 1) | (1 << 4) | (1 << 5),
+
+    /*
+     * PORTG
+     *   PG11 - ETH_RMII_TXEN
+     *   PG13 - ETH_RMII_TXD0
+     */
+    .sec_port_mask[6] = (1 << 11) | (1 << 13),
+    .sec_phy_type = LAN_8742_RMII,
+    .sec_phy_irq = -1
+};
+#endif
+
 /* FIXME */
 static const struct hal_bsp_mem_dump dump_cfg[] = {
     [0] = {
@@ -114,6 +155,15 @@ hal_bsp_init(void)
 #if MYNEWT_VAL(TIMER_2)
     hal_timer_init(2, TIM9);
 #endif
+
+#if (MYNEWT_VAL(OS_CPUTIME_TIMER_NUM) >= 0)
+    rc = os_cputime_init(MYNEWT_VAL(OS_CPUTIME_FREQ));
+    assert(rc == 0);
+#endif
+
+#if MYNEWT_VAL(ETH_0)
+    stm32_eth_init(&eth_cfg);
+#endif
 }
 
 /**

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/383906f4/hw/bsp/stm32f767-nucleo/syscfg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/stm32f767-nucleo/syscfg.yml b/hw/bsp/stm32f767-nucleo/syscfg.yml
index a4d2a73..fb083ed 100644
--- a/hw/bsp/stm32f767-nucleo/syscfg.yml
+++ b/hw/bsp/stm32f767-nucleo/syscfg.yml
@@ -31,6 +31,10 @@ syscfg.defs:
         description: 'Timer 2'
         value: 1
 
+    ETH_0:
+        description: 'Ethernet driver for LwIP'
+        value: 0
+
 syscfg.vals:
     REBOOT_LOG_FLASH_AREA: FLASH_AREA_REBOOT_LOG
     CONFIG_FCB_FLASH_AREA: FLASH_AREA_NFFS


[04/30] incubator-mynewt-core git commit: mn_socket; add LINK flag, mn_itf_get() convenience function.

Posted by ad...@apache.org.
mn_socket; add LINK flag, mn_itf_get() convenience function.


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/7701a125
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/7701a125
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/7701a125

Branch: refs/heads/master
Commit: 7701a125257fc850a129f8fc2e6a5695094d0a4a
Parents: e120cfc
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Fri Apr 14 12:47:19 2017 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Fri Apr 14 13:21:30 2017 -0700

----------------------------------------------------------------------
 net/ip/mn_socket/include/mn_socket/mn_socket.h |  7 +++++++
 net/ip/mn_socket/src/mn_socket.c               | 16 ++++++++++++++++
 2 files changed, 23 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/7701a125/net/ip/mn_socket/include/mn_socket/mn_socket.h
----------------------------------------------------------------------
diff --git a/net/ip/mn_socket/include/mn_socket/mn_socket.h b/net/ip/mn_socket/include/mn_socket/mn_socket.h
index b21bc33..b90ce1a 100644
--- a/net/ip/mn_socket/include/mn_socket/mn_socket.h
+++ b/net/ip/mn_socket/include/mn_socket/mn_socket.h
@@ -55,6 +55,7 @@ extern "C" {
 #define MN_EUNKNOWN             11
 #define MN_EADDRNOTAVAIL        12
 #define MN_ENETUNREACH          13
+#define MN_OPNOSUPPORT          14
 
 /*
  * Multicast macros
@@ -198,6 +199,7 @@ const char *mn_inet_ntop(int af, const void *src, void *dst, int len);
  */
 #define MN_ITF_F_UP        1
 #define MN_ITF_F_MULTICAST 2
+#define MN_ITF_F_LINK      4
 
 struct mn_itf {
     char mif_name[MN_ITF_NAME_MAX];
@@ -220,6 +222,11 @@ struct mn_itf_addr {
 int mn_itf_getnext(struct mn_itf *);
 int mn_itf_addr_getnext(struct mn_itf *, struct mn_itf_addr *);
 
+/*
+ * Find specific interface, given name.
+ */
+int mn_itf_get(char *name, struct mn_itf *mi);
+
 #ifdef __cplusplus
 }
 #endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/7701a125/net/ip/mn_socket/src/mn_socket.c
----------------------------------------------------------------------
diff --git a/net/ip/mn_socket/src/mn_socket.c b/net/ip/mn_socket/src/mn_socket.c
index 2d0d06e..d0070c3 100644
--- a/net/ip/mn_socket/src/mn_socket.c
+++ b/net/ip/mn_socket/src/mn_socket.c
@@ -19,6 +19,7 @@
 
 #include <inttypes.h>
 #include <assert.h>
+#include <string.h>
 
 #include <os/os.h>
 
@@ -136,3 +137,18 @@ mn_itf_addr_getnext(struct mn_itf *mi, struct mn_itf_addr *mia)
 {
     return mn_sock_tgt->mso_itf_addr_getnext(mi, mia);
 }
+
+int
+mn_itf_get(char *name, struct mn_itf *mi)
+{
+    memset(mi, 0, sizeof(*mi));
+    while (1) {
+        if (mn_itf_getnext(mi)) {
+            break;
+        }
+        if (!strcmp(name, mi->mif_name)) {
+            return 0;
+        }
+    }
+    return -1;
+}


[23/30] incubator-mynewt-core git commit: net/ip; updates needed for LwIP 2.0.2

Posted by ad...@apache.org.
net/ip; updates needed for LwIP 2.0.2


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/54c29c66
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/54c29c66
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/54c29c66

Branch: refs/heads/master
Commit: 54c29c6625fedbebd5b9997acf8b9338147b3933
Parents: f52033e
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Fri Apr 14 17:36:26 2017 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Fri Apr 14 17:36:26 2017 -0700

----------------------------------------------------------------------
 net/ip/include/lwipopts.h | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54c29c66/net/ip/include/lwipopts.h
----------------------------------------------------------------------
diff --git a/net/ip/include/lwipopts.h b/net/ip/include/lwipopts.h
index 7382692..2110570 100644
--- a/net/ip/include/lwipopts.h
+++ b/net/ip/include/lwipopts.h
@@ -181,9 +181,9 @@ extern "C" {
 
 /* ---------- Statistics options ---------- */
 /* XXX hook into sys/stats */
-#define STATS                           0
+#define LWIP_STATS                           0
 
-#if STATS
+#if LWIP_STATS
 #define LINK_STATS                      1
 #define IP_STATS                        1
 #define ICMP_STATS                      1
@@ -196,6 +196,7 @@ extern "C" {
 #endif /* STATS */
 
 #define LWIP_PROVIDE_ERRNO 1
+#define LWIP_DONT_PROVIDE_BYTEORDER_FUNCTIONS 1
 #define ERRNO                     0
 
 #ifdef __cplusplus


[28/30] incubator-mynewt-core git commit: hw/bsp: MYNEWT-730 Add BSP for Ruuvi tag

Posted by ad...@apache.org.
hw/bsp: MYNEWT-730 Add BSP for Ruuvi tag

Add BSP for Ruuvi tag revision B3/B4. Not sure if this same BSP
will work on other Ruuvi Tag B revisions. Note that the UART
only uses tx/rx and goes to test points on the board (the
test points are TP10 and TP11).


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/f4e2b349
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/f4e2b349
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/f4e2b349

Branch: refs/heads/master
Commit: f4e2b34905df1960f436145dd7346b17516edd4c
Parents: 813463e
Author: William San Filippo <wi...@runtime.io>
Authored: Tue Apr 18 16:36:28 2017 -0700
Committer: William San Filippo <wi...@runtime.io>
Committed: Tue Apr 18 16:36:28 2017 -0700

----------------------------------------------------------------------
 hw/bsp/ruuvi_tag_revb2/boot-nrf52xxaa.ld        |  25 ++
 hw/bsp/ruuvi_tag_revb2/bsp.yml                  |  64 ++++
 hw/bsp/ruuvi_tag_revb2/include/bsp/boards.h     |  19 ++
 hw/bsp/ruuvi_tag_revb2/include/bsp/bsp.h        |  73 +++++
 hw/bsp/ruuvi_tag_revb2/include/bsp/cmsis_nvic.h |  29 ++
 hw/bsp/ruuvi_tag_revb2/nrf52dk_debug.cmd        |  22 ++
 hw/bsp/ruuvi_tag_revb2/nrf52dk_debug.sh         |  46 +++
 hw/bsp/ruuvi_tag_revb2/nrf52dk_download.cmd     |  22 ++
 hw/bsp/ruuvi_tag_revb2/nrf52dk_download.sh      |  40 +++
 hw/bsp/ruuvi_tag_revb2/nrf52dk_no_boot.ld       | 191 ++++++++++++
 hw/bsp/ruuvi_tag_revb2/nrf52xxaa.ld             |  25 ++
 hw/bsp/ruuvi_tag_revb2/pkg.yml                  |  97 ++++++
 hw/bsp/ruuvi_tag_revb2/split-nrf52dk.ld         | 208 +++++++++++++
 .../src/arch/cortex_m4/gcc_startup_nrf52.s      | 301 ++++++++++++++++++
 .../arch/cortex_m4/gcc_startup_nrf52_split.s    | 166 ++++++++++
 hw/bsp/ruuvi_tag_revb2/src/hal_bsp.c            | 303 +++++++++++++++++++
 hw/bsp/ruuvi_tag_revb2/src/sbrk.c               |  59 ++++
 hw/bsp/ruuvi_tag_revb2/syscfg.yml               |  95 ++++++
 18 files changed, 1785 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f4e2b349/hw/bsp/ruuvi_tag_revb2/boot-nrf52xxaa.ld
----------------------------------------------------------------------
diff --git a/hw/bsp/ruuvi_tag_revb2/boot-nrf52xxaa.ld b/hw/bsp/ruuvi_tag_revb2/boot-nrf52xxaa.ld
new file mode 100755
index 0000000..d1f1b99
--- /dev/null
+++ b/hw/bsp/ruuvi_tag_revb2/boot-nrf52xxaa.ld
@@ -0,0 +1,25 @@
+/* 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.
+ */
+MEMORY
+{
+  FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x4000
+  RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x10000
+}
+
+/* The bootloader does not contain an image header */
+_imghdr_size = 0x0;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f4e2b349/hw/bsp/ruuvi_tag_revb2/bsp.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/ruuvi_tag_revb2/bsp.yml b/hw/bsp/ruuvi_tag_revb2/bsp.yml
new file mode 100644
index 0000000..918392c
--- /dev/null
+++ b/hw/bsp/ruuvi_tag_revb2/bsp.yml
@@ -0,0 +1,64 @@
+#
+# 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.
+#
+
+bsp.arch: cortex_m4
+bsp.compiler: compiler/arm-none-eabi-m4
+bsp.linkerscript:
+    - "hw/bsp/ruuvi_tag_revb2/nrf52xxaa.ld"
+    - "hw/mcu/nordic/nrf52xxx/nrf52.ld"
+bsp.linkerscript.BOOT_LOADER.OVERWRITE:
+    - "hw/bsp/ruuvi_tag_revb2/boot-nrf52xxaa.ld"
+    - "hw/mcu/nordic/nrf52xxx/nrf52.ld"
+bsp.part2linkerscript: "hw/bsp/ruuvi_tag_revb2/split-nrf52dk.ld"
+bsp.downloadscript: "hw/bsp/ruuvi_tag_revb2/nrf52dk_download.sh"
+bsp.debugscript: "hw/bsp/ruuvi_tag_revb2/nrf52dk_debug.sh"
+bsp.downloadscript.WINDOWS.OVERWRITE: "hw/bsp/ruuvi_tag_revb2/nrf52dk_download.cmd"
+bsp.debugscript.WINDOWS.OVERWRITE: "hw/bsp/ruuvi_tag_revb2/nrf52dk_debug.cmd"
+
+bsp.flash_map:
+    areas:
+        # System areas.
+        FLASH_AREA_BOOTLOADER:
+            device: 0
+            offset: 0x00000000
+            size: 16kB
+        FLASH_AREA_IMAGE_0:
+            device: 0
+            offset: 0x00008000
+            size: 232kB
+        FLASH_AREA_IMAGE_1:
+            device: 0
+            offset: 0x00042000
+            size: 232kB
+        FLASH_AREA_IMAGE_SCRATCH:
+            device: 0
+            offset: 0x0007c000
+            size: 4kB
+
+        # User areas.
+        FLASH_AREA_REBOOT_LOG:
+            user_id: 0
+            device: 0
+            offset: 0x00004000
+            size: 16kB
+        FLASH_AREA_NFFS:
+            user_id: 1
+            device: 0
+            offset: 0x0007d000
+            size: 12kB

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f4e2b349/hw/bsp/ruuvi_tag_revb2/include/bsp/boards.h
----------------------------------------------------------------------
diff --git a/hw/bsp/ruuvi_tag_revb2/include/bsp/boards.h b/hw/bsp/ruuvi_tag_revb2/include/bsp/boards.h
new file mode 100644
index 0000000..560c31f
--- /dev/null
+++ b/hw/bsp/ruuvi_tag_revb2/include/bsp/boards.h
@@ -0,0 +1,19 @@
+/*
+ * 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.
+ */
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f4e2b349/hw/bsp/ruuvi_tag_revb2/include/bsp/bsp.h
----------------------------------------------------------------------
diff --git a/hw/bsp/ruuvi_tag_revb2/include/bsp/bsp.h b/hw/bsp/ruuvi_tag_revb2/include/bsp/bsp.h
new file mode 100644
index 0000000..e43ad7f
--- /dev/null
+++ b/hw/bsp/ruuvi_tag_revb2/include/bsp/bsp.h
@@ -0,0 +1,73 @@
+/*
+ * 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
+
+#include <inttypes.h>
+
+#include <syscfg/syscfg.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")))
+#define sec_bss_nz_core __attribute__((section(".bss.core.nz")))
+
+/* More convenient section placement macros. */
+#define bssnz_t         sec_bss_nz_core
+
+extern uint8_t _ram_start;
+#define RAM_SIZE        0x10000
+
+/* IRQ */
+#define ACC_INT1        (2)
+#define ACC_INT2        (6)
+
+/* SPI CS */
+#define SPI_HUMI_CS     (3)
+#define SPI_ACC_CS      (8)
+
+/* LED pins */
+#define LED_1           (17)
+#define LED_2           (19)
+#define LED_BLINK_PIN   (LED_1)
+
+/* UART info */
+#define CONSOLE_UART    "uart0"
+
+#if MYNEWT_VAL(BOOT_SERIAL)
+#define BOOT_SERIAL_DETECT_PIN          13 /* Button 1 */
+#define BOOT_SERIAL_DETECT_PIN_CFG      HAL_GPIO_PULL_UP
+#define BOOT_SERIAL_DETECT_PIN_VAL      0
+
+#define BOOT_SERIAL_REPORT_PIN          LED_BLINK_PIN
+#define BOOT_SERIAL_REPORT_FREQ         (MYNEWT_VAL(OS_CPUTIME_FREQ) / 4)
+#endif
+
+#define NFFS_AREA_MAX   (8)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* H_BSP_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f4e2b349/hw/bsp/ruuvi_tag_revb2/include/bsp/cmsis_nvic.h
----------------------------------------------------------------------
diff --git a/hw/bsp/ruuvi_tag_revb2/include/bsp/cmsis_nvic.h b/hw/bsp/ruuvi_tag_revb2/include/bsp/cmsis_nvic.h
new file mode 100644
index 0000000..856f7d0
--- /dev/null
+++ b/hw/bsp/ruuvi_tag_revb2/include/bsp/cmsis_nvic.h
@@ -0,0 +1,29 @@
+/* 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>
+
+#define NVIC_NUM_VECTORS      (16 + 38)   // CORE + MCU Peripherals
+#define NVIC_USER_IRQ_OFFSET  16
+
+#include "nrf52.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/f4e2b349/hw/bsp/ruuvi_tag_revb2/nrf52dk_debug.cmd
----------------------------------------------------------------------
diff --git a/hw/bsp/ruuvi_tag_revb2/nrf52dk_debug.cmd b/hw/bsp/ruuvi_tag_revb2/nrf52dk_debug.cmd
new file mode 100755
index 0000000..96f0b26
--- /dev/null
+++ b/hw/bsp/ruuvi_tag_revb2/nrf52dk_debug.cmd
@@ -0,0 +1,22 @@
+@rem
+@rem Licensed to the Apache Software Foundation (ASF) under one
+@rem or more contributor license agreements.  See the NOTICE file
+@rem distributed with this work for additional information
+@rem regarding copyright ownership.  The ASF licenses this file
+@rem to you under the Apache License, Version 2.0 (the
+@rem "License"); you may not use this file except in compliance
+@rem with the License.  You may obtain a copy of the License at
+@rem
+@rem  http://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing,
+@rem software distributed under the License is distributed on an
+@rem "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+@rem KIND, either express or implied.  See the License for the
+@rem specific language governing permissions and limitations
+@rem under the License.
+@rem
+
+@rem Execute a shell with a script of the same name and .sh extension
+
+@bash "%~dp0%~n0.sh"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f4e2b349/hw/bsp/ruuvi_tag_revb2/nrf52dk_debug.sh
----------------------------------------------------------------------
diff --git a/hw/bsp/ruuvi_tag_revb2/nrf52dk_debug.sh b/hw/bsp/ruuvi_tag_revb2/nrf52dk_debug.sh
new file mode 100755
index 0000000..17b980d
--- /dev/null
+++ b/hw/bsp/ruuvi_tag_revb2/nrf52dk_debug.sh
@@ -0,0 +1,46 @@
+#!/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 with following variables set:
+#  - CORE_PATH is absolute path to @apache-mynewt-core
+#  - BSP_PATH is absolute path to hw/bsp/bsp_name
+#  - BIN_BASENAME is the path to prefix to target binary,
+#    .elf appended to name is the ELF file
+#  - FEATURES holds the target features string
+#  - EXTRA_JTAG_CMD holds extra parameters to pass to jtag software
+#  - RESET set if target should be reset when attaching
+#  - NO_GDB set if we should not start gdb to debug
+#
+
+. $CORE_PATH/hw/scripts/jlink.sh
+
+FILE_NAME=$BIN_BASENAME.elf
+
+if [ $# -gt 2 ]; then
+    SPLIT_ELF_NAME=$3.elf
+    # TODO -- this magic number 0x42000 is the location of the second image
+    # slot. we should either get this from a flash map file or somehow learn
+    # this from the image itself
+    EXTRA_GDB_CMDS="add-symbol-file $SPLIT_ELF_NAME 0x8000 -readnow"
+fi
+
+JLINK_DEV="nRF52"
+
+jlink_debug
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f4e2b349/hw/bsp/ruuvi_tag_revb2/nrf52dk_download.cmd
----------------------------------------------------------------------
diff --git a/hw/bsp/ruuvi_tag_revb2/nrf52dk_download.cmd b/hw/bsp/ruuvi_tag_revb2/nrf52dk_download.cmd
new file mode 100755
index 0000000..96f0b26
--- /dev/null
+++ b/hw/bsp/ruuvi_tag_revb2/nrf52dk_download.cmd
@@ -0,0 +1,22 @@
+@rem
+@rem Licensed to the Apache Software Foundation (ASF) under one
+@rem or more contributor license agreements.  See the NOTICE file
+@rem distributed with this work for additional information
+@rem regarding copyright ownership.  The ASF licenses this file
+@rem to you under the Apache License, Version 2.0 (the
+@rem "License"); you may not use this file except in compliance
+@rem with the License.  You may obtain a copy of the License at
+@rem
+@rem  http://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing,
+@rem software distributed under the License is distributed on an
+@rem "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+@rem KIND, either express or implied.  See the License for the
+@rem specific language governing permissions and limitations
+@rem under the License.
+@rem
+
+@rem Execute a shell with a script of the same name and .sh extension
+
+@bash "%~dp0%~n0.sh"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f4e2b349/hw/bsp/ruuvi_tag_revb2/nrf52dk_download.sh
----------------------------------------------------------------------
diff --git a/hw/bsp/ruuvi_tag_revb2/nrf52dk_download.sh b/hw/bsp/ruuvi_tag_revb2/nrf52dk_download.sh
new file mode 100755
index 0000000..08d45b4
--- /dev/null
+++ b/hw/bsp/ruuvi_tag_revb2/nrf52dk_download.sh
@@ -0,0 +1,40 @@
+#!/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 with following variables set:
+#  - CORE_PATH is absolute path to @apache-mynewt-core
+#  - BSP_PATH is absolute path to hw/bsp/bsp_name
+#  - BIN_BASENAME is the path to prefix to target binary,
+#    .elf appended to name is the ELF file
+#  - IMAGE_SLOT is the image slot to download to (for non-mfg-image, non-boot)
+#  - FEATURES holds the target features string
+#  - EXTRA_JTAG_CMD holds extra parameters to pass to jtag software
+#  - MFG_IMAGE is "1" if this is a manufacturing image
+#  - FLASH_OFFSET contains the flash offset to download to
+#  - BOOT_LOADER is set if downloading a bootloader
+
+. $CORE_PATH/hw/scripts/jlink.sh
+
+if [ "$MFG_IMAGE" ]; then
+    FLASH_OFFSET=0x0
+fi
+
+JLINK_DEV="nRF52"
+
+common_file_to_load
+jlink_load

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f4e2b349/hw/bsp/ruuvi_tag_revb2/nrf52dk_no_boot.ld
----------------------------------------------------------------------
diff --git a/hw/bsp/ruuvi_tag_revb2/nrf52dk_no_boot.ld b/hw/bsp/ruuvi_tag_revb2/nrf52dk_no_boot.ld
new file mode 100755
index 0000000..e2fb5a8
--- /dev/null
+++ b/hw/bsp/ruuvi_tag_revb2/nrf52dk_no_boot.ld
@@ -0,0 +1,191 @@
+/* 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 = 0x80000
+  RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x10000
+}
+
+/* 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
+
+    /* Non-zeroed BSS.  This section is similar to BSS, with the following
+     * caveat:
+     *    1. It does not get zeroed at init-time.
+     */
+    .bssnz :
+    {
+        . = ALIGN(4);
+        __bssnz_start__ = .;
+        *(.bss.core.nz*)
+        . = ALIGN(4);
+        __bssnz_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/f4e2b349/hw/bsp/ruuvi_tag_revb2/nrf52xxaa.ld
----------------------------------------------------------------------
diff --git a/hw/bsp/ruuvi_tag_revb2/nrf52xxaa.ld b/hw/bsp/ruuvi_tag_revb2/nrf52xxaa.ld
new file mode 100755
index 0000000..9433e37
--- /dev/null
+++ b/hw/bsp/ruuvi_tag_revb2/nrf52xxaa.ld
@@ -0,0 +1,25 @@
+/* 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.
+ */
+MEMORY
+{
+  FLASH (rx) : ORIGIN = 0x00008000, LENGTH = 0x3a000
+  RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x10000
+}
+
+/* This linker script is used for images and thus contains an image header */
+_imghdr_size = 0x20;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f4e2b349/hw/bsp/ruuvi_tag_revb2/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/ruuvi_tag_revb2/pkg.yml b/hw/bsp/ruuvi_tag_revb2/pkg.yml
new file mode 100644
index 0000000..7bd4489
--- /dev/null
+++ b/hw/bsp/ruuvi_tag_revb2/pkg.yml
@@ -0,0 +1,97 @@
+#
+# 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/ruuvi_tag_revb
+pkg.type: bsp
+pkg.description: BSP definition for the Ruuvi Tag rev B (B3 and B4).
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+    - ruuvi
+    - ruuvi_tag
+    - nrf52
+    - nrf52dk
+
+pkg.cflags:
+    # Nordic SDK files require these defines.
+    - '-DADC_ENABLED=0'
+    - '-DCLOCK_ENABLED=1'
+    - '-DCOMP_ENABLED=1'
+    - '-DEGU_ENABLED=0'
+    - '-DGPIOTE_ENABLED=1'
+    - '-DI2S_ENABLED=1'
+    - '-DLPCOMP_ENABLED=1'
+    - '-DNRF52'
+    - '-DPDM_ENABLED=0'
+    - '-DPERIPHERAL_RESOURCE_SHARING_ENABLED=1'
+    - '-DPWM0_ENABLED=1'
+    - '-DPWM1_ENABLED=0'
+    - '-DPWM2_ENABLED=0'
+    - '-DQDEC_ENABLED=1'
+    - '-DRNG_ENABLED=1'
+    - '-DRTC0_ENABLED=0'
+    - '-DRTC1_ENABLED=0'
+    - '-DRTC2_ENABLED=0'
+    - '-DSAADC_ENABLED=1'
+    - '-DSPI_MASTER_0_ENABLE=1'
+    - '-DSPI0_CONFIG_MISO_PIN=28'
+    - '-DSPI0_CONFIG_MOSI_PIN=25'
+    - '-DSPI0_CONFIG_SCK_PIN=29'
+    - '-DSPI0_ENABLED=1'
+    - '-DSPI0_USE_EASY_DMA=1'
+    - '-DSPI1_ENABLED=0'
+    - '-DSPI2_ENABLED=0'
+    - '-DSPIS0_CONFIG_MISO_PIN=28'
+    - '-DSPIS0_CONFIG_MOSI_PIN=25'
+    - '-DSPIS0_CONFIG_SCK_PIN=29'
+    - '-DSPIS0_ENABLED=1'
+    - '-DSPIS1_CONFIG_MISO_PIN=4'
+    - '-DSPIS1_CONFIG_MOSI_PIN=3'
+    - '-DSPIS1_CONFIG_SCK_PIN=2'
+    - '-DSPIS1_ENABLED=0'
+    - '-DSPIS2_ENABLED=0'
+    - '-DTIMER0_ENABLED=1'
+    - '-DTIMER1_ENABLED=0'
+    - '-DTIMER2_ENABLED=0'
+    - '-DTIMER3_ENABLED=0'
+    - '-DTIMER4_ENABLED=0'
+    - '-DTWI0_CONFIG_SCL=27'
+    - '-DTWI0_CONFIG_SDA=26'
+    - '-DTWI0_ENABLED=1'
+    - '-DTWI1_ENABLED=1'
+    - '-DTWIS0_ENABLED=1'
+    - '-DTWIS1_ENABLED=0'
+    - '-DUART0_ENABLED=1'
+    - '-DWDT_ENABLED=1'
+
+pkg.cflags.HARDFLOAT:
+    - -mfloat-abi=hard -mfpu=fpv4-sp-d16
+
+pkg.deps:
+    - hw/mcu/nordic/nrf52xxx
+    - libc/baselibc
+
+pkg.deps.BLE_DEVICE:
+    - hw/drivers/nimble/nrf52
+
+pkg.deps.UART_0:
+    - hw/drivers/uart/uart_hal
+
+pkg.deps.UART_1:
+    - hw/drivers/uart/uart_bitbang

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f4e2b349/hw/bsp/ruuvi_tag_revb2/split-nrf52dk.ld
----------------------------------------------------------------------
diff --git a/hw/bsp/ruuvi_tag_revb2/split-nrf52dk.ld b/hw/bsp/ruuvi_tag_revb2/split-nrf52dk.ld
new file mode 100755
index 0000000..f4ffe5a
--- /dev/null
+++ b/hw/bsp/ruuvi_tag_revb2/split-nrf52dk.ld
@@ -0,0 +1,208 @@
+/* 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 =  0x00042000, LENGTH = 0x3a000
+  RAM  (rwx) : ORIGIN =  0x20000000, LENGTH = 0x10000
+}
+
+/* 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_split)
+
+SECTIONS
+{
+    .imghdr (NOLOAD):
+    {
+        . = . + 0x20;
+    } > FLASH
+
+    .text :
+    {
+        __split_isr_vector_start = .;
+        KEEP(*(.isr_vector_split))
+        __split_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 : ALIGN(4)
+    {
+        *(.ARM.extab* .gnu.linkonce.armextab.*)
+    } > 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 = .;
+
+    /* save RAM used by the split image. This assumes that 
+     * the loader uses all the RAM up to its HeapBase  */
+    .loader_ram_contents :
+    {
+        _loader_ram_start = .;
+
+ 	/* this symbol comes from the loader linker */
+	. = . + (ABSOLUTE(__HeapBase_loader) - _loader_ram_start);
+        _loader_ram_end = .;
+    } > RAM
+
+    .data :
+    {
+        __data_start__ = .;
+        *(.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 AT > FLASH
+
+    /* Non-zeroed BSS.  This section is similar to BSS, with the following two
+     * caveats:
+     *    1. It does not get zeroed at init-time.
+     *    2. You cannot use it as source memory for EasyDMA.
+     *
+     * This section exists because of a hardware defect; see errata 33 and 34
+     * in nrf52 errata sheet.
+     */
+    .bssnz :
+    {
+        . = ALIGN(4);
+        __bssnz_start__ = .;
+        *(.bss.core.nz*)
+        . = ALIGN(4);
+        __bssnz_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
+
+    _ram_start = ORIGIN(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/f4e2b349/hw/bsp/ruuvi_tag_revb2/src/arch/cortex_m4/gcc_startup_nrf52.s
----------------------------------------------------------------------
diff --git a/hw/bsp/ruuvi_tag_revb2/src/arch/cortex_m4/gcc_startup_nrf52.s b/hw/bsp/ruuvi_tag_revb2/src/arch/cortex_m4/gcc_startup_nrf52.s
new file mode 100755
index 0000000..8ce6ee5
--- /dev/null
+++ b/hw/bsp/ruuvi_tag_revb2/src/arch/cortex_m4/gcc_startup_nrf52.s
@@ -0,0 +1,301 @@
+/*
+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 armv7-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   UARTE0_UART0_IRQHandler
+    .long   SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0_IRQHandler
+    .long   SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1_IRQHandler
+    .long   NFCT_IRQHandler
+    .long   GPIOTE_IRQHandler
+    .long   SAADC_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   COMP_LPCOMP_IRQHandler
+    .long   SWI0_EGU0_IRQHandler
+    .long   SWI1_EGU1_IRQHandler
+    .long   SWI2_EGU2_IRQHandler
+    .long   SWI3_EGU3_IRQHandler
+    .long   SWI4_EGU4_IRQHandler
+    .long   SWI5_EGU5_IRQHandler
+    .long   TIMER3_IRQHandler
+    .long   TIMER4_IRQHandler
+    .long   PWM0_IRQHandler
+    .long   PDM_IRQHandler
+    .long   0                         /*Reserved */
+    .long   0                         /*Reserved */
+    .long   MWU_IRQHandler
+    .long   PWM1_IRQHandler
+    .long   PWM2_IRQHandler
+    .long   SPIM2_SPIS2_SPI2_IRQHandler
+    .long   RTC2_IRQHandler
+    .long   I2S_IRQHandler
+
+    .size    __isr_vector, . - __isr_vector
+
+/* Reset Handler */
+
+    .text
+    .thumb
+    .thumb_func
+    .align 1
+    .globl    Reset_Handler
+    .type    Reset_Handler, %function
+Reset_Handler:
+    .fnstart
+
+    /* Clear BSS */
+    mov     r0, #0
+    ldr     r2, =__bss_start__
+    ldr     r3, =__bss_end__
+.bss_zero_loop:
+    cmp     r2, r3
+    itt     lt
+    strlt   r0, [r2], #4
+    blt    .bss_zero_loop
+
+
+/*     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, =__HeapBase
+    LDR     R1, =__HeapLimit
+    BL      _sbrkInit
+
+    LDR     R0, =SystemInit
+    BLX     R0
+
+    BL      hal_system_init
+
+    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   HardFault_Handler
+    .type   HardFault_Handler, %function
+HardFault_Handler:
+    B       .
+    .size   HardFault_Handler, . - HardFault_Handler
+
+
+    .weak   MemoryManagement_Handler
+    .type   MemoryManagement_Handler, %function
+MemoryManagement_Handler:
+    B       .
+    .size   MemoryManagement_Handler, . - MemoryManagement_Handler
+
+
+    .weak   BusFault_Handler
+    .type   BusFault_Handler, %function
+BusFault_Handler:
+    B       .
+    .size   BusFault_Handler, . - BusFault_Handler
+
+
+    .weak   UsageFault_Handler
+    .type   UsageFault_Handler, %function
+UsageFault_Handler:
+    B       .
+    .size   UsageFault_Handler, . - UsageFault_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
+
+
+/* IRQ Handlers */
+
+    .globl  Default_Handler
+    .type   Default_Handler, %function
+Default_Handler:
+    B       .
+    .size   Default_Handler, . - Default_Handler
+
+    .macro  IRQ handler
+    .weak   \handler
+    .set    \handler, Default_Handler
+    .endm
+
+    IRQ  POWER_CLOCK_IRQHandler
+    IRQ  RADIO_IRQHandler
+    IRQ  UARTE0_UART0_IRQHandler
+    IRQ  SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0_IRQHandler
+    IRQ  SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1_IRQHandler
+    IRQ  NFCT_IRQHandler
+    IRQ  GPIOTE_IRQHandler
+    IRQ  SAADC_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  COMP_LPCOMP_IRQHandler
+    IRQ  SWI0_EGU0_IRQHandler
+    IRQ  SWI1_EGU1_IRQHandler
+    IRQ  SWI2_EGU2_IRQHandler
+    IRQ  SWI3_EGU3_IRQHandler
+    IRQ  SWI4_EGU4_IRQHandler
+    IRQ  SWI5_EGU5_IRQHandler
+    IRQ  TIMER3_IRQHandler
+    IRQ  TIMER4_IRQHandler
+    IRQ  PWM0_IRQHandler
+    IRQ  PDM_IRQHandler
+    IRQ  MWU_IRQHandler
+    IRQ  PWM1_IRQHandler
+    IRQ  PWM2_IRQHandler
+    IRQ  SPIM2_SPIS2_SPI2_IRQHandler
+    IRQ  RTC2_IRQHandler
+    IRQ  I2S_IRQHandler
+
+  .end

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f4e2b349/hw/bsp/ruuvi_tag_revb2/src/arch/cortex_m4/gcc_startup_nrf52_split.s
----------------------------------------------------------------------
diff --git a/hw/bsp/ruuvi_tag_revb2/src/arch/cortex_m4/gcc_startup_nrf52_split.s b/hw/bsp/ruuvi_tag_revb2/src/arch/cortex_m4/gcc_startup_nrf52_split.s
new file mode 100755
index 0000000..044aa17
--- /dev/null
+++ b/hw/bsp/ruuvi_tag_revb2/src/arch/cortex_m4/gcc_startup_nrf52_split.s
@@ -0,0 +1,166 @@
+/*
+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 armv7-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_split
+    .align 2
+    .globl __isr_vector_split
+__isr_vector_split:
+    .long    __StackTop            /* Top of Stack */
+    .long   Reset_Handler_split               /* Reset Handler */
+
+    .size    __isr_vector_split, . - __isr_vector_split
+
+/* Reset Handler */
+
+    .text
+    .thumb
+    .thumb_func
+    .align 1
+    .globl    Reset_Handler_split
+    .type    Reset_Handler_split, %function
+Reset_Handler_split:
+    .fnstart
+
+    /* Clear CPU state before proceeding */
+    mov     r0, #0
+    msr     control, r0
+    msr     primask, r0
+    /* Clear BSS */
+    ldr     r2, =__bss_start__
+    ldr     r3, =__bss_end__
+.bss_zero_loop:
+    cmp     r2, r3
+    itt     lt
+    strlt   r0, [r2], #4
+    blt    .bss_zero_loop
+
+
+/*     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    r1, =__etext_loader
+    ldr    r2, =__data_start___loader
+    ldr    r3, =__data_end___loader
+
+    subs    r3, r2
+    ble     .LC2
+
+.LC3:
+    subs    r3, 4
+    ldr    r0, [r1,r3]
+    str    r0, [r2,r3]
+    bgt    .LC3
+.LC2:
+
+    subs    r0, r0
+    ldr    r2, =__bss_start___loader
+    ldr    r3, =__bss_end___loader
+
+    subs    r3, r2
+    ble     .LC4
+
+.LC5:
+    subs    r3, 4
+    str    r0, [r2,r3]
+    bgt    .LC5
+.LC4:
+
+    LDR     R0, =__HeapBase
+    LDR     R1, =__HeapLimit
+    BL      _sbrkInit
+
+    LDR     R0, =SystemInit
+    BLX     R0
+
+    BL      hal_system_init
+
+    LDR     R0, =_start_split
+    BX      R0
+
+    .pool
+    .cantunwind
+    .fnend
+    .size   Reset_Handler_split,.-Reset_Handler_split
+
+    .section ".text"
+  .end

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f4e2b349/hw/bsp/ruuvi_tag_revb2/src/hal_bsp.c
----------------------------------------------------------------------
diff --git a/hw/bsp/ruuvi_tag_revb2/src/hal_bsp.c b/hw/bsp/ruuvi_tag_revb2/src/hal_bsp.c
new file mode 100644
index 0000000..ab960ce
--- /dev/null
+++ b/hw/bsp/ruuvi_tag_revb2/src/hal_bsp.c
@@ -0,0 +1,303 @@
+/*
+ * 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 <assert.h>
+#include <nrf52.h>
+#include "os/os_cputime.h"
+#include "syscfg/syscfg.h"
+#include "sysflash/sysflash.h"
+#include "flash_map/flash_map.h"
+#include "hal/hal_bsp.h"
+#include "hal/hal_flash.h"
+#include "hal/hal_spi.h"
+#include "hal/hal_watchdog.h"
+#include "hal/hal_i2c.h"
+#include "mcu/nrf52_hal.h"
+#if MYNEWT_VAL(UART_0) || MYNEWT_VAL(UART_1)
+#include "uart/uart.h"
+#endif
+#if MYNEWT_VAL(UART_0)
+#include "uart_hal/uart_hal.h"
+#endif
+#if MYNEWT_VAL(UART_1)
+#include "uart_bitbang/uart_bitbang.h"
+#endif
+#include "os/os_dev.h"
+#include "bsp.h"
+#if MYNEWT_VAL(LSM303DLHC_PRESENT)
+#include <lsm303dlhc/lsm303dlhc.h>
+static struct lsm303dlhc lsm303dlhc;
+#endif
+#if MYNEWT_VAL(BNO055_PRESENT)
+#include <bno055/bno055.h>
+#endif
+#if MYNEWT_VAL(TSL2561_PRESENT)
+#include <tsl2561/tsl2561.h>
+#endif
+#if MYNEWT_VAL(TCS34725_PRESENT)
+#include <tcs34725/tcs34725.h>
+#endif
+
+#if MYNEWT_VAL(LSM303DLHC_PRESENT)
+static struct lsm303dlhc lsm303dlhc;
+#endif
+
+#if MYNEWT_VAL(BNO055_PRESENT)
+static struct bno055 bno055;
+#endif
+
+#if MYNEWT_VAL(TSL2561_PRESENT)
+static struct tsl2561 tsl2561;
+#endif
+
+#if MYNEWT_VAL(TCS34725_PRESENT)
+static struct tcs34725 tcs34725;
+#endif
+
+#if MYNEWT_VAL(UART_0)
+static struct uart_dev os_bsp_uart0;
+static const struct nrf52_uart_cfg os_bsp_uart0_cfg = {
+    .suc_pin_tx = MYNEWT_VAL(UART_0_PIN_TX),
+    .suc_pin_rx = MYNEWT_VAL(UART_0_PIN_RX),
+    .suc_pin_rts = MYNEWT_VAL(UART_0_PIN_RTS),
+    .suc_pin_cts = MYNEWT_VAL(UART_0_PIN_CTS),
+};
+#endif
+
+#if MYNEWT_VAL(UART_1)
+static struct uart_dev os_bsp_bitbang_uart1;
+static const struct uart_bitbang_conf os_bsp_uart1_cfg = {
+    .ubc_txpin = MYNEWT_VAL(UART_1_PIN_TX),
+    .ubc_rxpin = MYNEWT_VAL(UART_1_PIN_RX),
+    .ubc_cputimer_freq = MYNEWT_VAL(OS_CPUTIME_FREQ),
+};
+#endif
+
+#if MYNEWT_VAL(SPI_0_MASTER)
+/*
+ * NOTE: Our HAL expects that the SS pin, if used, is treated as a gpio line
+ * and is handled outside the SPI routines.
+ */
+static const struct nrf52_hal_spi_cfg os_bsp_spi0m_cfg = {
+    .sck_pin      = 29,
+    .mosi_pin     = 25,
+    .miso_pin     = 28,
+};
+#endif
+
+#if MYNEWT_VAL(SPI_0_SLAVE)
+static const struct nrf52_hal_spi_cfg os_bsp_spi0s_cfg = {
+    .sck_pin      = 29,
+    .mosi_pin     = 25,
+    .miso_pin     = 28,
+    .ss_pin       = 22,
+};
+#endif
+
+#if MYNEWT_VAL(I2C_0)
+static const struct nrf52_hal_i2c_cfg hal_i2c_cfg = {
+    .scl_pin = 27,
+    .sda_pin = 26,
+    .i2c_frequency = 100    /* 100 kHz */
+};
+#endif
+
+/*
+ * What memory to include in coredump.
+ */
+static const struct hal_bsp_mem_dump dump_cfg[] = {
+    [0] = {
+        .hbmd_start = &_ram_start,
+        .hbmd_size = RAM_SIZE
+    }
+};
+
+const struct hal_flash *
+hal_bsp_flash_dev(uint8_t id)
+{
+    /*
+     * Internal flash mapped to id 0.
+     */
+    if (id != 0) {
+        return NULL;
+    }
+    return &nrf52k_flash_dev;
+}
+
+const struct hal_bsp_mem_dump *
+hal_bsp_core_dump(int *area_cnt)
+{
+    *area_cnt = sizeof(dump_cfg) / sizeof(dump_cfg[0]);
+    return dump_cfg;
+}
+
+int
+hal_bsp_power_state(int state)
+{
+    return (0);
+}
+
+/**
+ * Returns the configured priority for the given interrupt. If no priority
+ * configured, return the priority passed in
+ *
+ * @param irq_num
+ * @param pri
+ *
+ * @return uint32_t
+ */
+uint32_t
+hal_bsp_get_nvic_priority(int irq_num, uint32_t pri)
+{
+    uint32_t cfg_pri;
+
+    switch (irq_num) {
+    /* Radio gets highest priority */
+    case RADIO_IRQn:
+        cfg_pri = 0;
+        break;
+    default:
+        cfg_pri = pri;
+    }
+    return cfg_pri;
+}
+
+#if MYNEWT_VAL(LSM303DLHC_PRESENT) || MYNEWT_VAL(BNO055_PRESENT)
+static int
+slinky_accel_init(struct os_dev *dev, void *arg)
+{
+   return (0);
+}
+#endif
+
+#if MYNEWT_VAL(TSL2561_PRESENT)
+static int
+slinky_light_init(struct os_dev *dev, void *arg)
+{
+    return (0);
+}
+#endif
+
+#if MYNEWT_VAL(TCS34725_PRESENT)
+static int
+slinky_color_init(struct os_dev *dev, void *arg)
+{
+    return (0);
+}
+#endif
+
+static void
+sensor_dev_create(void)
+{
+    int rc;
+
+    (void)rc;
+#if MYNEWT_VAL(LSM303DLHC_PRESENT)
+    rc = os_dev_create((struct os_dev *) &lsm303dlhc, "accel0",
+      OS_DEV_INIT_PRIMARY, 0, slinky_accel_init, NULL);
+    assert(rc == 0);
+#endif
+
+#if MYNEWT_VAL(BNO055_PRESENT)
+    rc = os_dev_create((struct os_dev *) &bno055, "accel1",
+      OS_DEV_INIT_PRIMARY, 0, slinky_accel_init, NULL);
+    assert(rc == 0);
+#endif
+
+#if MYNEWT_VAL(TSL2561_PRESENT)
+    rc = os_dev_create((struct os_dev *) &tsl2561, "light0",
+      OS_DEV_INIT_PRIMARY, 0, slinky_light_init, NULL);
+    assert(rc == 0);
+#endif
+
+#if MYNEWT_VAL(TCS34725_PRESENT)
+    rc = os_dev_create((struct os_dev *) &tcs34725, "color0",
+      OS_DEV_INIT_PRIMARY, 0, slinky_color_init, NULL);
+    assert(rc == 0);
+#endif
+
+}
+
+void
+hal_bsp_init(void)
+{
+    int rc;
+
+    (void)rc;
+#if MYNEWT_VAL(TIMER_0)
+    rc = hal_timer_init(0, NULL);
+    assert(rc == 0);
+#endif
+#if MYNEWT_VAL(TIMER_1)
+    rc = hal_timer_init(1, NULL);
+    assert(rc == 0);
+#endif
+#if MYNEWT_VAL(TIMER_2)
+    rc = hal_timer_init(2, NULL);
+    assert(rc == 0);
+#endif
+#if MYNEWT_VAL(TIMER_3)
+    rc = hal_timer_init(3, NULL);
+    assert(rc == 0);
+#endif
+#if MYNEWT_VAL(TIMER_4)
+    rc = hal_timer_init(4, NULL);
+    assert(rc == 0);
+#endif
+#if MYNEWT_VAL(TIMER_5)
+    rc = hal_timer_init(5, NULL);
+    assert(rc == 0);
+#endif
+
+#if (MYNEWT_VAL(OS_CPUTIME_TIMER_NUM) >= 0)
+    rc = os_cputime_init(MYNEWT_VAL(OS_CPUTIME_FREQ));
+    assert(rc == 0);
+#endif
+
+#if MYNEWT_VAL(I2C_0)
+    rc = hal_i2c_init(0, (void *)&hal_i2c_cfg);
+    assert(rc == 0);
+#endif
+
+#if MYNEWT_VAL(SPI_0_MASTER)
+    rc = hal_spi_init(0, (void *)&os_bsp_spi0m_cfg, HAL_SPI_TYPE_MASTER);
+    assert(rc == 0);
+#endif
+
+#if MYNEWT_VAL(SPI_0_SLAVE)
+    rc = hal_spi_init(0, (void *)&os_bsp_spi0s_cfg, HAL_SPI_TYPE_SLAVE);
+    assert(rc == 0);
+#endif
+
+#if MYNEWT_VAL(UART_0)
+    rc = os_dev_create((struct os_dev *) &os_bsp_uart0, "uart0",
+      OS_DEV_INIT_PRIMARY, 0, uart_hal_init, (void *)&os_bsp_uart0_cfg);
+    assert(rc == 0);
+#endif
+
+#if MYNEWT_VAL(UART_1)
+    rc = os_dev_create((struct os_dev *) &os_bsp_bitbang_uart1, "uart1",
+      OS_DEV_INIT_PRIMARY, 0, uart_bitbang_init, (void *)&os_bsp_uart1_cfg);
+    assert(rc == 0);
+#endif
+
+    sensor_dev_create();
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f4e2b349/hw/bsp/ruuvi_tag_revb2/src/sbrk.c
----------------------------------------------------------------------
diff --git a/hw/bsp/ruuvi_tag_revb2/src/sbrk.c b/hw/bsp/ruuvi_tag_revb2/src/sbrk.c
new file mode 100644
index 0000000..5df43c9
--- /dev/null
+++ b/hw/bsp/ruuvi_tag_revb2/src/sbrk.c
@@ -0,0 +1,59 @@
+/*
+ * 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_bsp.h>
+
+/* put these in the data section so they are not cleared by _start */
+static char *sbrkBase __attribute__ ((section (".data")));
+static char *sbrkLimit __attribute__ ((section (".data")));
+static char *brk __attribute__ ((section (".data")));
+
+void
+_sbrkInit(char *base, char *limit) {
+    sbrkBase = base;
+    sbrkLimit = limit;
+    brk = base;
+}
+
+void *
+_sbrk(int incr)
+{
+    void *prev_brk;
+
+    if (incr < 0) {
+        /* Returning memory to the heap. */
+        incr = -incr;
+        if (brk - incr < sbrkBase) {
+            prev_brk = (void *)-1;
+        } else {
+            prev_brk = brk;
+            brk -= incr;
+        }
+    } else {
+        /* Allocating memory from the heap. */
+        if (sbrkLimit - brk >= incr) {
+            prev_brk = brk;
+            brk += incr;
+        } else {
+            prev_brk = (void *)-1;
+        }
+    }
+
+    return prev_brk;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f4e2b349/hw/bsp/ruuvi_tag_revb2/syscfg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/ruuvi_tag_revb2/syscfg.yml b/hw/bsp/ruuvi_tag_revb2/syscfg.yml
new file mode 100644
index 0000000..5c019a6
--- /dev/null
+++ b/hw/bsp/ruuvi_tag_revb2/syscfg.yml
@@ -0,0 +1,95 @@
+# 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.
+#
+
+# Package: hw/bsp/nrf52dk
+
+syscfg.defs:
+    BSP_NRF52:
+        description: 'Set to indicate that BSP has NRF52'
+        value: 1
+
+    XTAL_32768:
+        description: 'External 32k oscillator available.'
+        value: 1
+
+    UART_0:
+        description: 'Whether to enable UART0'
+        value:  1
+    UART_0_PIN_TX:
+        description: 'TX pin for UART0'
+        value:  4
+    UART_0_PIN_RX:
+        description: 'RX pin for UART0'
+        value:  5
+    UART_0_PIN_RTS:
+        description: 'RTS pin for UART0'
+        value:  -1
+    UART_0_PIN_CTS:
+        description: 'CTS pin for UART0'
+        value: -1
+
+    UART_1:
+        description: 'Whether to enable bitbanger UART1'
+        value:  0
+    UART_1_PIN_TX:
+        description: 'TX pin for UART1'
+        value:  -1
+    UART_1_PIN_RX:
+        description: 'RX pin for UART1'
+        value:  -1
+
+    SPI_0_MASTER:
+        description: 'SPI 0 master'
+        value:  0
+        restrictions:
+            - "!SPI_0_SLAVE"
+    SPI_0_SLAVE:
+        description: 'SPI 0 slave'
+        value:  0
+        restrictions:
+            - "!SPI_0_MASTER"
+
+    TIMER_0:
+        description: 'NRF52 Timer 0'
+        value:  1
+    TIMER_1:
+        description: 'NRF52 Timer 1'
+        value:  0
+    TIMER_2:
+        description: 'NRF52 Timer 2'
+        value:  0
+    TIMER_3:
+        description: 'NRF52 Timer 3'
+        value:  0
+    TIMER_4:
+        description: 'NRF52 Timer 4'
+        value:  0
+    TIMER_5:
+        description: 'NRF52 RTC 0'
+        value:  0
+
+    I2C_0:
+        description: 'NRF52 I2C (TWI) interface 0'
+        value:  '0'
+
+syscfg.vals:
+    CONFIG_FCB_FLASH_AREA: FLASH_AREA_NFFS
+    REBOOT_LOG_FLASH_AREA: FLASH_AREA_REBOOT_LOG
+    NFFS_FLASH_AREA: FLASH_AREA_NFFS
+    COREDUMP_FLASH_AREA: FLASH_AREA_IMAGE_1
+    MCU_DCDC_ENABLED: 1


[24/30] incubator-mynewt-core git commit: net/ip; allow multicast join/leave via socket interface.

Posted by ad...@apache.org.
net/ip; allow multicast join/leave via socket 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/f92e6ab0
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/f92e6ab0
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/f92e6ab0

Branch: refs/heads/master
Commit: f92e6ab09ce4c52ca6ce11ee81a36aed0b381984
Parents: 54c29c6
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Mon Apr 17 14:11:26 2017 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Apr 17 14:11:26 2017 -0700

----------------------------------------------------------------------
 net/ip/src/lwip_socket.c | 58 +++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 56 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f92e6ab0/net/ip/src/lwip_socket.c
----------------------------------------------------------------------
diff --git a/net/ip/src/lwip_socket.c b/net/ip/src/lwip_socket.c
index 1a57392..b000e3b 100644
--- a/net/ip/src/lwip_socket.c
+++ b/net/ip/src/lwip_socket.c
@@ -27,6 +27,8 @@
 #include <lwip/tcpip.h>
 #include <lwip/udp.h>
 #include <lwip/tcp.h>
+#include <lwip/igmp.h>
+#include <lwip/mld6.h>
 #include "ip_priv.h"
 
 static int lwip_sock_create(struct mn_socket **sp, uint8_t domain,
@@ -607,10 +609,62 @@ lwip_getsockopt(struct mn_socket *s, uint8_t level,
     return MN_EPROTONOSUPPORT;
 }
 
+static struct netif *
+lwip_nif_from_idx(int idx)
+{
+    struct netif *nif;
+
+    for (nif = netif_list; nif; nif = nif->next) {
+        if (idx == nif->num) {
+            return nif;
+        }
+    }
+    return NULL;
+}
+
 static int
-lwip_setsockopt(struct mn_socket *s, uint8_t level,
-  uint8_t name, void *val)
+lwip_setsockopt(struct mn_socket *ms, uint8_t level, uint8_t name, void *val)
 {
+    struct netif *nif;
+    struct mn_mreq *mreq;
+    int rc = MN_EPROTONOSUPPORT;
+
+    if (level == MN_SO_LEVEL) {
+        switch (name) {
+        case MN_MCAST_JOIN_GROUP:
+        case MN_MCAST_LEAVE_GROUP:
+            mreq = (struct mn_mreq *)val;
+
+            LOCK_TCPIP_CORE();
+            nif = lwip_nif_from_idx(mreq->mm_idx);
+            if (mreq->mm_family == MN_AF_INET) {
+#if LWIP_IGMP
+                if (name == MN_MCAST_JOIN_GROUP) {
+                    rc = igmp_joingroup_netif(nif,
+                                              (ip4_addr_t *)&mreq->mm_addr);
+                } else {
+                    rc = igmp_leavegroup_netif(nif,
+                                              (ip4_addr_t *)&mreq->mm_addr);
+                }
+#endif
+            } else if (mreq->mm_family == MN_AF_INET6) {
+#if LWIP_IPV6_MLD && LWIP_IPV6
+                if (name == MN_MCAST_JOIN_GROUP) {
+                    rc = mld6_joingroup_netif(nif,
+                                              (ip6_addr_t *)&mreq->mm_addr);
+                } else {
+                    rc = mld6_leavegroup_netif(nif,
+                                              (ip6_addr_t *)&mreq->mm_addr);
+                }
+#endif
+            }
+            UNLOCK_TCPIP_CORE();
+            return lwip_err_to_mn_err(rc);
+        case MN_MCAST_IF:
+        default:
+            break;
+        }
+    }
     return MN_EPROTONOSUPPORT;
 }
 


[30/30] incubator-mynewt-core git commit: Merge branch 'lwip_updates' of https://github.com/mkiiskila/incubator-mynewt-core

Posted by ad...@apache.org.
Merge branch 'lwip_updates' of https://github.com/mkiiskila/incubator-mynewt-core

This closes #235.


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/28b29f44
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/28b29f44
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/28b29f44

Branch: refs/heads/master
Commit: 28b29f44549bcb7cec4bf47f10af45237a88d12b
Parents: 8492749 bcba6bd
Author: aditihilbert <ad...@runtime.io>
Authored: Wed Apr 19 11:12:27 2017 -0700
Committer: aditihilbert <ad...@runtime.io>
Committed: Wed Apr 19 11:12:27 2017 -0700

----------------------------------------------------------------------
 apps/iptest/pkg.yml                             |   46 +
 apps/iptest/src/main.c                          |  441 ++++++
 apps/iptest/syscfg.yml                          |   45 +
 .../include/bsp/stm32f4xx_hal_conf.h            |    1 +
 hw/bsp/olimex_stm32-e407_devboard/pkg.yml       |    4 +-
 hw/bsp/olimex_stm32-e407_devboard/src/hal_bsp.c |   41 +-
 hw/bsp/olimex_stm32-e407_devboard/syscfg.yml    |    4 +
 hw/bsp/stm32f767-nucleo/pkg.yml                 |    3 +
 hw/bsp/stm32f767-nucleo/src/hal_bsp.c           |   50 +
 hw/bsp/stm32f767-nucleo/syscfg.yml              |    4 +
 .../stm32_eth/include/stm32_eth/stm32_eth.h     |   49 +
 .../stm32_eth/include/stm32_eth/stm32_eth_cfg.h |   47 +
 hw/drivers/lwip/stm32_eth/pkg.yml               |   41 +
 hw/drivers/lwip/stm32_eth/src/stm32_eth.c       |  538 +++++++
 .../include/stm32f4_eth/stm32f4_eth.h           |   27 -
 .../include/stm32f4_eth/stm32f4_eth_cfg.h       |   32 -
 hw/drivers/lwip/stm32f4_eth/pkg.yml             |   33 -
 hw/drivers/lwip/stm32f4_eth/src/stm32f4_eth.c   |  746 ----------
 hw/hal/include/hal/hal_timer.h                  |    2 +
 hw/mcu/stm/stm32f4xx/syscfg.yml                 |    4 +
 hw/mcu/stm/stm32f7xx/syscfg.yml                 |    4 +
 libc/baselibc/include/string.h                  |    1 +
 libc/baselibc/src/strstr.c                      |    5 +
 net/ip/include/arch/sys_arch.h                  |  304 ++--
 net/ip/include/ip/init.h                        |   32 -
 net/ip/include/lwipopts.h                       |   15 +-
 net/ip/inet_def_service/src/inet_def_service.c  |  110 +-
 net/ip/lwip_base/CHANGELOG                      |  146 ++
 net/ip/lwip_base/UPGRADING                      |   16 +-
 net/ip/lwip_base/doc/NO_SYS_SampleCode.c        |   16 +-
 net/ip/lwip_base/doc/doxygen/generate.sh        |    2 +
 net/ip/lwip_base/doc/doxygen/lwip.Doxyfile      |    7 +-
 net/ip/lwip_base/doc/doxygen/main_page.h        |   75 +-
 net/ip/lwip_base/doc/mqtt_client.txt            |  162 +++
 net/ip/lwip_base/doc/ppp.txt                    |    6 +-
 net/ip/lwip_base/doc/rawapi.txt                 |    8 +-
 net/ip/lwip_base/doc/sys_arch.txt               |    2 +-
 net/ip/lwip_base/include/lwip/api.h             |   31 +-
 net/ip/lwip_base/include/lwip/apps/httpd_opts.h |   30 -
 net/ip/lwip_base/include/lwip/apps/mdns.h       |   10 +-
 net/ip/lwip_base/include/lwip/apps/mdns_opts.h  |   10 +-
 net/ip/lwip_base/include/lwip/apps/mdns_priv.h  |   10 +-
 net/ip/lwip_base/include/lwip/apps/mqtt.h       |  244 ++++
 net/ip/lwip_base/include/lwip/apps/mqtt_opts.h  |  103 ++
 net/ip/lwip_base/include/lwip/apps/netbiosns.h  |    8 -
 .../include/lwip/apps/netbiosns_opts.h          |   18 -
 net/ip/lwip_base/include/lwip/apps/snmp_opts.h  |    8 -
 net/ip/lwip_base/include/lwip/apps/snmpv3.h     |    8 -
 net/ip/lwip_base/include/lwip/apps/sntp_opts.h  |    8 -
 net/ip/lwip_base/include/lwip/apps/tftp_opts.h  |  105 ++
 .../lwip_base/include/lwip/apps/tftp_server.h   |   94 ++
 net/ip/lwip_base/include/lwip/arch.h            |  299 ++--
 net/ip/lwip_base/include/lwip/autoip.h          |    2 +
 net/ip/lwip_base/include/lwip/debug.h           |   81 +-
 net/ip/lwip_base/include/lwip/def.h             |   95 +-
 net/ip/lwip_base/include/lwip/dhcp.h            |    2 +
 net/ip/lwip_base/include/lwip/dhcp6.h           |    8 -
 net/ip/lwip_base/include/lwip/dns.h             |   18 +-
 net/ip/lwip_base/include/lwip/err.h             |    4 +
 net/ip/lwip_base/include/lwip/errno.h           |  193 +++
 net/ip/lwip_base/include/lwip/icmp.h            |    2 +-
 net/ip/lwip_base/include/lwip/icmp6.h           |   89 +-
 net/ip/lwip_base/include/lwip/igmp.h            |    6 +-
 net/ip/lwip_base/include/lwip/inet.h            |    8 +-
 net/ip/lwip_base/include/lwip/inet_chksum.h     |    8 +-
 net/ip/lwip_base/include/lwip/init.h            |    4 +-
 net/ip/lwip_base/include/lwip/ip4_addr.h        |   36 +-
 net/ip/lwip_base/include/lwip/ip6_addr.h        |   66 +-
 net/ip/lwip_base/include/lwip/ip_addr.h         |   73 +-
 net/ip/lwip_base/include/lwip/mem.h             |    3 +-
 net/ip/lwip_base/include/lwip/mld6.h            |    7 +-
 net/ip/lwip_base/include/lwip/nd6.h             |   93 +-
 net/ip/lwip_base/include/lwip/netdb.h           |    3 +-
 net/ip/lwip_base/include/lwip/netif.h           |   10 +-
 net/ip/lwip_base/include/lwip/netifapi.h        |   12 +-
 net/ip/lwip_base/include/lwip/opt.h             |  116 +-
 net/ip/lwip_base/include/lwip/pbuf.h            |   20 +-
 net/ip/lwip_base/include/lwip/priv/api_msg.h    |    3 +-
 net/ip/lwip_base/include/lwip/priv/memp_std.h   |    8 -
 net/ip/lwip_base/include/lwip/priv/nd6_priv.h   |  144 ++
 net/ip/lwip_base/include/lwip/priv/tcp_priv.h   |   27 +-
 net/ip/lwip_base/include/lwip/priv/tcpip_priv.h |    4 +-
 net/ip/lwip_base/include/lwip/prot/dns.h        |   18 +
 net/ip/lwip_base/include/lwip/prot/ethernet.h   |    2 +-
 net/ip/lwip_base/include/lwip/prot/icmp6.h      |   87 ++
 net/ip/lwip_base/include/lwip/prot/ip.h         |    8 -
 net/ip/lwip_base/include/lwip/prot/ip4.h        |   16 +
 net/ip/lwip_base/include/lwip/prot/ip6.h        |   27 +-
 net/ip/lwip_base/include/lwip/prot/mld6.h       |    2 +-
 net/ip/lwip_base/include/lwip/prot/nd6.h        |   24 +
 net/ip/lwip_base/include/lwip/prot/tcp.h        |   14 +-
 net/ip/lwip_base/include/lwip/raw.h             |    2 +
 net/ip/lwip_base/include/lwip/sockets.h         |    5 +-
 net/ip/lwip_base/include/lwip/stats.h           |    4 +-
 net/ip/lwip_base/include/lwip/sys.h             |   44 +-
 net/ip/lwip_base/include/lwip/tcp.h             |   12 +-
 net/ip/lwip_base/include/lwip/tcpip.h           |    2 +
 net/ip/lwip_base/include/lwip/timeouts.h        |    2 +-
 net/ip/lwip_base/include/netif/lowpan6_opts.h   |    8 -
 net/ip/lwip_base/include/netif/ppp/ccp.h        |    8 -
 net/ip/lwip_base/include/netif/ppp/chap-new.h   |    8 -
 net/ip/lwip_base/include/netif/ppp/chap_ms.h    |    8 -
 net/ip/lwip_base/include/netif/ppp/eui64.h      |   10 +-
 net/ip/lwip_base/include/netif/ppp/fsm.h        |    8 -
 net/ip/lwip_base/include/netif/ppp/ipcp.h       |    8 -
 net/ip/lwip_base/include/netif/ppp/ipv6cp.h     |    8 -
 net/ip/lwip_base/include/netif/ppp/lcp.h        |    8 -
 net/ip/lwip_base/include/netif/ppp/magic.h      |    8 -
 net/ip/lwip_base/include/netif/ppp/mppe.h       |   10 +-
 net/ip/lwip_base/include/netif/ppp/ppp.h        |   12 +-
 net/ip/lwip_base/include/netif/ppp/ppp_impl.h   |   12 +-
 net/ip/lwip_base/include/netif/ppp/ppp_opts.h   |    8 -
 net/ip/lwip_base/include/netif/ppp/pppcrypt.h   |    8 -
 net/ip/lwip_base/include/netif/ppp/pppdebug.h   |    8 -
 net/ip/lwip_base/include/netif/ppp/pppoe.h      |    8 -
 net/ip/lwip_base/include/netif/ppp/pppol2tp.h   |    8 -
 net/ip/lwip_base/include/netif/ppp/pppos.h      |    8 -
 net/ip/lwip_base/include/netif/ppp/upap.h       |    8 -
 net/ip/lwip_base/include/netif/ppp/vj.h         |    8 -
 net/ip/lwip_base/include/posix/errno.h          |   33 +
 net/ip/lwip_base/src/Filelists.mk               |   10 +-
 net/ip/lwip_base/src/api/api_lib.c              |   69 +-
 net/ip/lwip_base/src/api/api_msg.c              |  127 +-
 net/ip/lwip_base/src/api/err.c                  |   40 +
 net/ip/lwip_base/src/api/netdb.c                |   10 +-
 net/ip/lwip_base/src/api/netifapi.c             |   14 +-
 net/ip/lwip_base/src/api/sockets.c              |  204 +--
 net/ip/lwip_base/src/api/tcpip.c                |    3 +-
 net/ip/lwip_base/src/apps/httpd/fsdata.h        |    8 -
 net/ip/lwip_base/src/apps/httpd/httpd.c         |  180 +--
 net/ip/lwip_base/src/apps/httpd/httpd_structs.h |    8 -
 net/ip/lwip_base/src/apps/lwiperf/lwiperf.c     |   16 +-
 net/ip/lwip_base/src/apps/mdns/mdns.c           |  161 +--
 net/ip/lwip_base/src/apps/mqtt/mqtt.c           | 1341 ++++++++++++++++++
 net/ip/lwip_base/src/apps/netbiosns/netbiosns.c |    5 +-
 net/ip/lwip_base/src/apps/snmp/snmp_asn1.c      |    8 +-
 net/ip/lwip_base/src/apps/snmp/snmp_core.c      |   84 +-
 net/ip/lwip_base/src/apps/snmp/snmp_mib2_ip.c   |   12 +-
 net/ip/lwip_base/src/apps/snmp/snmp_mib2_tcp.c  |    6 +-
 net/ip/lwip_base/src/apps/snmp/snmp_msg.c       |   11 +-
 net/ip/lwip_base/src/apps/snmp/snmp_netconn.c   |    5 +-
 net/ip/lwip_base/src/apps/snmp/snmp_raw.c       |    2 +-
 .../lwip_base/src/apps/snmp/snmp_threadsync.c   |    1 +
 net/ip/lwip_base/src/apps/snmp/snmp_traps.c     |    9 +-
 net/ip/lwip_base/src/apps/snmp/snmpv3_priv.h    |    8 -
 net/ip/lwip_base/src/apps/sntp/sntp.c           |    9 +-
 net/ip/lwip_base/src/apps/tftp/tftp_server.c    |  417 ++++++
 net/ip/lwip_base/src/core/def.c                 |  177 ++-
 net/ip/lwip_base/src/core/dns.c                 |  239 +++-
 net/ip/lwip_base/src/core/inet_chksum.c         |   15 +-
 net/ip/lwip_base/src/core/init.c                |   12 +-
 net/ip/lwip_base/src/core/ipv4/autoip.c         |   16 +-
 net/ip/lwip_base/src/core/ipv4/dhcp.c           |  114 +-
 net/ip/lwip_base/src/core/ipv4/etharp.c         |   69 +-
 net/ip/lwip_base/src/core/ipv4/icmp.c           |   14 +-
 net/ip/lwip_base/src/core/ipv4/igmp.c           |   75 +-
 net/ip/lwip_base/src/core/ipv4/ip4.c            |   57 +-
 net/ip/lwip_base/src/core/ipv4/ip4_addr.c       |   10 +-
 net/ip/lwip_base/src/core/ipv4/ip4_frag.c       |   88 +-
 net/ip/lwip_base/src/core/ipv6/ethip6.c         |   42 +-
 net/ip/lwip_base/src/core/ipv6/ip6.c            |   62 +-
 net/ip/lwip_base/src/core/ipv6/ip6_addr.c       |   10 +-
 net/ip/lwip_base/src/core/ipv6/ip6_frag.c       |   49 +-
 net/ip/lwip_base/src/core/ipv6/mld6.c           |    7 +-
 net/ip/lwip_base/src/core/ipv6/nd6.c            |  355 +++--
 net/ip/lwip_base/src/core/mem.c                 |    8 +-
 net/ip/lwip_base/src/core/memp.c                |   25 +-
 net/ip/lwip_base/src/core/netif.c               |  127 +-
 net/ip/lwip_base/src/core/pbuf.c                |   91 +-
 net/ip/lwip_base/src/core/raw.c                 |   51 +-
 net/ip/lwip_base/src/core/stats.c               |    6 +-
 net/ip/lwip_base/src/core/sys.c                 |   38 +
 net/ip/lwip_base/src/core/tcp.c                 |  149 +-
 net/ip/lwip_base/src/core/tcp_in.c              |   88 +-
 net/ip/lwip_base/src/core/tcp_out.c             |  195 ++-
 net/ip/lwip_base/src/core/timeouts.c            |    4 +-
 net/ip/lwip_base/src/core/udp.c                 |   72 +-
 net/ip/lwip_base/src/netif/ethernet.c           |   20 +-
 net/ip/lwip_base/src/netif/lowpan6.c            |  103 +-
 net/ip/lwip_base/src/netif/ppp/auth.c           |   10 +-
 net/ip/lwip_base/src/netif/ppp/ipcp.c           |  120 +-
 net/ip/lwip_base/src/netif/ppp/ipv6cp.c         |    4 +-
 net/ip/lwip_base/src/netif/ppp/multilink.c      |    4 +-
 net/ip/lwip_base/src/netif/ppp/ppp.c            |   19 +-
 net/ip/lwip_base/src/netif/ppp/pppapi.c         |    5 +
 net/ip/lwip_base/src/netif/ppp/pppoe.c          |   19 +-
 net/ip/lwip_base/src/netif/ppp/pppol2tp.c       |    9 +-
 net/ip/lwip_base/src/netif/ppp/pppos.c          |   40 +-
 net/ip/lwip_base/src/netif/ppp/utils.c          |    4 +-
 net/ip/lwip_base/src/netif/ppp/vj.c             |   62 +-
 net/ip/lwip_base/src/netif/slipif.c             |    2 +-
 net/ip/lwip_base/test/fuzz/Makefile             |   53 +
 net/ip/lwip_base/test/fuzz/README               |   34 +
 net/ip/lwip_base/test/fuzz/config.h             |    0
 net/ip/lwip_base/test/fuzz/fuzz.c               |  136 ++
 .../lwip_base/test/fuzz/inputs/arp/arp_req.bin  |  Bin 0 -> 42 bytes
 .../test/fuzz/inputs/icmp/icmp_ping.bin         |  Bin 0 -> 98 bytes
 .../fuzz/inputs/ipv6/neighbor_solicitation.bin  |  Bin 0 -> 86 bytes
 .../test/fuzz/inputs/ipv6/router_adv.bin        |  Bin 0 -> 118 bytes
 .../lwip_base/test/fuzz/inputs/tcp/tcp_syn.bin  |  Bin 0 -> 74 bytes
 .../test/fuzz/inputs/udp/udp_port_5000.bin      |  Bin 0 -> 50 bytes
 net/ip/lwip_base/test/fuzz/lwipopts.h           |   68 +
 net/ip/lwip_base/test/fuzz/output_to_pcap.sh    |   31 +
 net/ip/lwip_base/test/unit/core/test_mem.h      |    8 -
 net/ip/lwip_base/test/unit/core/test_pbuf.h     |    8 -
 net/ip/lwip_base/test/unit/dhcp/test_dhcp.c     |  113 +-
 net/ip/lwip_base/test/unit/dhcp/test_dhcp.h     |    8 -
 net/ip/lwip_base/test/unit/etharp/test_etharp.h |    8 -
 net/ip/lwip_base/test/unit/lwip_check.h         |    8 -
 net/ip/lwip_base/test/unit/lwipopts.h           |    8 -
 net/ip/lwip_base/test/unit/mdns/test_mdns.c     |   71 +-
 net/ip/lwip_base/test/unit/mdns/test_mdns.h     |    8 -
 net/ip/lwip_base/test/unit/tcp/tcp_helper.c     |   23 +-
 net/ip/lwip_base/test/unit/tcp/tcp_helper.h     |    8 -
 net/ip/lwip_base/test/unit/tcp/test_tcp.c       |   18 +-
 net/ip/lwip_base/test/unit/tcp/test_tcp.h       |    8 -
 net/ip/lwip_base/test/unit/tcp/test_tcp_oos.h   |    8 -
 net/ip/lwip_base/test/unit/udp/test_udp.h       |    8 -
 net/ip/mn_socket/include/mn_socket/mn_socket.h  |    7 +
 net/ip/mn_socket/src/mn_socket.c                |   16 +
 net/ip/native_sockets/src/native_itf.c          |    5 +-
 net/ip/pkg.yml                                  |    7 +
 net/ip/src/ip_init.c                            |    5 +
 net/ip/src/ip_priv.h                            |    3 +
 net/ip/src/lwip_cli.c                           |  140 ++
 net/ip/src/lwip_if.c                            |   17 +-
 net/ip/src/lwip_socket.c                        |  179 ++-
 net/ip/syscfg.yml                               |   26 +
 228 files changed, 8399 insertions(+), 3777 deletions(-)
----------------------------------------------------------------------



[19/30] incubator-mynewt-core git commit: net/ip/lwip_base; update to LwIP to tag STABLE-2_0_2_RELEASE

Posted by ad...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/apps/httpd/httpd.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/apps/httpd/httpd.c b/net/ip/lwip_base/src/apps/httpd/httpd.c
index f8e2e28..43195d7 100644
--- a/net/ip/lwip_base/src/apps/httpd/httpd.c
+++ b/net/ip/lwip_base/src/apps/httpd/httpd.c
@@ -98,11 +98,11 @@
 #include "lwip/ip.h"
 #include "lwip/tcp.h"
 
-#include <string.h>
-#include <stdlib.h>
+#include <string.h> /* memset */
+#include <stdlib.h> /* atoi */
 #include <stdio.h>
 
-#if LWIP_TCP
+#if LWIP_TCP && LWIP_CALLBACK_API
 
 /** Minimum length for a valid HTTP/0.9 request: "GET /\r\n" -> 7 bytes */
 #define MIN_REQ_LEN   7
@@ -335,85 +335,34 @@ char *http_cgi_param_vals[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Values for each ext
 /** global list of active HTTP connections, use to kill the oldest when
     running out of memory */
 static struct http_state *http_connections;
-#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */
 
-#if LWIP_HTTPD_STRNSTR_PRIVATE
-/** Like strstr but does not need 'buffer' to be NULL-terminated */
-static char*
-strnstr(const char* buffer, const char* token, size_t n)
+static void
+http_add_connection(struct http_state *hs)
 {
-  const char* p;
-  int tokenlen = (int)strlen(token);
-  if (tokenlen == 0) {
-    return (char *)(size_t)buffer;
-  }
-  for (p = buffer; *p && (p + tokenlen <= buffer + n); p++) {
-    if ((*p == *token) && (strncmp(p, token, tokenlen) == 0)) {
-      return (char *)(size_t)p;
-    }
-  }
-  return NULL;
+  /* add the connection to the list */
+  hs->next = http_connections;
+  http_connections = hs;
 }
-#endif /* LWIP_HTTPD_STRNSTR_PRIVATE */
 
-#if LWIP_HTTPD_STRICMP_PRIVATE
-static int
-stricmp(const char* str1, const char* str2)
+static void
+http_remove_connection(struct http_state *hs)
 {
-  char c1, c2;
-
-  do {
-    c1 = *str1++;
-    c2 = *str2++;
-    if (c1 != c2) {
-      char c1_upc = c1 | 0x20;
-      if ((c1_upc >= 'a') && (c1_upc <= 'z')) {
-        /* characters are not equal an one is in the alphabet range:
-        downcase both chars and check again */
-        char c2_upc = c2 | 0x20;
-        if (c1_upc != c2_upc) {
-          /* still not equal */
-          /* don't care for < or > */
-          return 1;
+  /* take the connection off the list */
+  if (http_connections) {
+    if (http_connections == hs) {
+      http_connections = hs->next;
+    } else {
+      struct http_state *last;
+      for(last = http_connections; last->next != NULL; last = last->next) {
+        if (last->next == hs) {
+          last->next = hs->next;
+          break;
         }
-      } else {
-        /* characters are not equal but none is in the alphabet range */
-        return 1;
       }
     }
-  } while (c1 != 0);
-  return 0;
-}
-#endif /* LWIP_HTTPD_STRICMP_PRIVATE */
-
-#if LWIP_HTTPD_ITOA_PRIVATE && LWIP_HTTPD_DYNAMIC_HEADERS
-static void
-httpd_itoa(int value, char* result)
-{
-  const int base = 10;
-  char* ptr = result, *ptr1 = result, tmp_char;
-  int tmp_value;
-
-  do {
-    tmp_value = value;
-    value /= base;
-    *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz"[35 + (tmp_value - value * base)];
-  } while(value);
-
-   /* Apply negative sign */
-  if (tmp_value < 0) {
-     *ptr++ = '-';
-  }
-  *ptr-- = '\0';
-  while(ptr1 < ptr) {
-    tmp_char = *ptr;
-    *ptr--= *ptr1;
-    *ptr1++ = tmp_char;
   }
 }
-#endif
 
-#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED
 static void
 http_kill_oldest_connection(u8_t ssi_required)
 {
@@ -442,6 +391,11 @@ http_kill_oldest_connection(u8_t ssi_required)
     http_close_or_abort_conn(hs_free_next->next->pcb, hs_free_next->next, 1); /* this also unlinks the http_state from the list */
   }
 }
+#else /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */
+
+#define http_add_connection(hs)
+#define http_remove_connection(hs)
+
 #endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */
 
 #if LWIP_HTTPD_SSI
@@ -498,17 +452,7 @@ http_state_alloc(void)
 #endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */
   if (ret != NULL) {
     http_state_init(ret);
-#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED
-    /* add the connection to the list */
-    if (http_connections == NULL) {
-      http_connections = ret;
-    } else {
-      struct http_state *last;
-      for(last = http_connections; last->next != NULL; last = last->next);
-      LWIP_ASSERT("last != NULL", last != NULL);
-      last->next = ret;
-    }
-#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */
+    http_add_connection(ret);
   }
   return ret;
 }
@@ -557,22 +501,7 @@ http_state_free(struct http_state *hs)
 {
   if (hs != NULL) {
     http_state_eof(hs);
-#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED
-    /* take the connection off the list */
-    if (http_connections) {
-      if (http_connections == hs) {
-        http_connections = hs->next;
-      } else {
-        struct http_state *last;
-        for(last = http_connections; last->next != NULL; last = last->next) {
-          if (last->next == hs) {
-            last->next = hs->next;
-            break;
-          }
-        }
-      }
-    }
-#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */
+    http_remove_connection(hs);
     HTTP_FREE_HTTP_STATE(hs);
   }
 }
@@ -714,17 +643,14 @@ http_eof(struct tcp_pcb *pcb, struct http_state *hs)
   /* HTTP/1.1 persistent connection? (Not supported for SSI) */
 #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE
   if (hs->keepalive) {
-#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED
-    struct http_state* next = hs->next;
-#endif
+    http_remove_connection(hs);
+
     http_state_eof(hs);
     http_state_init(hs);
     /* restore state: */
-#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED
-    hs->next = next;
-#endif
     hs->pcb = pcb;
     hs->keepalive = 1;
+    http_add_connection(hs);
     /* ensure nagle doesn't interfere with sending all data as fast as possible: */
     tcp_nagle_disable(pcb);
   } else
@@ -964,7 +890,7 @@ get_http_headers(struct http_state *hs, const char *uri)
     /* Now determine the content type and add the relevant header for that. */
     for (content_type = 0; content_type < NUM_HTTP_HEADERS; content_type++) {
       /* Have we found a matching extension? */
-      if(!stricmp(g_psHTTPHeaders[content_type].extension, ext)) {
+      if(!lwip_stricmp(g_psHTTPHeaders[content_type].extension, ext)) {
         break;
       }
     }
@@ -1012,7 +938,7 @@ get_http_headers(struct http_state *hs, const char *uri)
   }
   if (add_content_len) {
     size_t len;
-    LWIP_HTTPD_ITOA(hs->hdr_content_len, (size_t)LWIP_HTTPD_MAX_CONTENT_LEN_SIZE,
+    lwip_itoa(hs->hdr_content_len, (size_t)LWIP_HTTPD_MAX_CONTENT_LEN_SIZE,
       hs->handle->len);
     len = strlen(hs->hdr_content_len);
     if (len <= LWIP_HTTPD_MAX_CONTENT_LEN_SIZE - LWIP_HTTPD_MAX_CONTENT_LEN_OFFSET) {
@@ -1553,6 +1479,8 @@ http_send_data_ssi(struct tcp_pcb *pcb, struct http_state *hs)
             }
           }
           break;
+        default:
+          break;
       }
     }
   }
@@ -1764,7 +1692,14 @@ http_post_rxpbuf(struct http_state *hs, struct pbuf *p)
       hs->post_content_len_left -= p->tot_len;
     }
   }
+#if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND
+  /* prevent connection being closed if httpd_post_data_recved() is called nested */
+  hs->unrecved_bytes++;
+#endif
   err = httpd_post_receive_data(hs, p);
+#if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND
+  hs->unrecved_bytes--;
+#endif
   if (err != ERR_OK) {
     /* Ignore remaining content in case of application error */
     hs->post_content_len_left = 0;
@@ -1802,16 +1737,16 @@ http_post_request(struct pbuf *inp, struct http_state *hs,
 {
   err_t err;
   /* search for end-of-header (first double-CRLF) */
-  char* crlfcrlf = strnstr(uri_end + 1, CRLF CRLF, data_len - (uri_end + 1 - data));
+  char* crlfcrlf = lwip_strnstr(uri_end + 1, CRLF CRLF, data_len - (uri_end + 1 - data));
 
   if (crlfcrlf != NULL) {
     /* search for "Content-Length: " */
 #define HTTP_HDR_CONTENT_LEN                "Content-Length: "
 #define HTTP_HDR_CONTENT_LEN_LEN            16
 #define HTTP_HDR_CONTENT_LEN_DIGIT_MAX_LEN  10
-    char *scontent_len = strnstr(uri_end + 1, HTTP_HDR_CONTENT_LEN, crlfcrlf - (uri_end + 1));
+    char *scontent_len = lwip_strnstr(uri_end + 1, HTTP_HDR_CONTENT_LEN, crlfcrlf - (uri_end + 1));
     if (scontent_len != NULL) {
-      char *scontent_len_end = strnstr(scontent_len + HTTP_HDR_CONTENT_LEN_LEN, CRLF, HTTP_HDR_CONTENT_LEN_DIGIT_MAX_LEN);
+      char *scontent_len_end = lwip_strnstr(scontent_len + HTTP_HDR_CONTENT_LEN_LEN, CRLF, HTTP_HDR_CONTENT_LEN_DIGIT_MAX_LEN);
       if (scontent_len_end != NULL) {
         int content_len;
         char *content_len_num = scontent_len + HTTP_HDR_CONTENT_LEN_LEN;
@@ -1825,8 +1760,8 @@ http_post_request(struct pbuf *inp, struct http_state *hs,
         if (content_len >= 0) {
           /* adjust length of HTTP header passed to application */
           const char *hdr_start_after_uri = uri_end + 1;
-          u16_t hdr_len = LWIP_MIN(data_len, crlfcrlf + 4 - data);
-          u16_t hdr_data_len = LWIP_MIN(data_len, crlfcrlf + 4 - hdr_start_after_uri);
+          u16_t hdr_len = (u16_t)LWIP_MIN(data_len, crlfcrlf + 4 - data);
+          u16_t hdr_data_len = (u16_t)LWIP_MIN(data_len, crlfcrlf + 4 - hdr_start_after_uri);
           u8_t post_auto_wnd = 1;
           http_uri_buf[0] = 0;
           /* trim http header */
@@ -1953,7 +1888,7 @@ http_continue(void *connection)
  * When data has been received in the correct state, try to parse it
  * as a HTTP request.
  *
- * @param p the received pbuf
+ * @param inp the received pbuf
  * @param hs the connection state
  * @param pcb the tcp_pcb which received this packet
  * @return ERR_OK if request was OK and hs has been initialized correctly
@@ -2020,7 +1955,7 @@ http_parse_request(struct pbuf *inp, struct http_state *hs, struct tcp_pcb *pcb)
   /* received enough data for minimal request? */
   if (data_len >= MIN_REQ_LEN) {
     /* wait for CRLF before parsing anything */
-    crlf = strnstr(data, CRLF, data_len);
+    crlf = lwip_strnstr(data, CRLF, data_len);
     if (crlf != NULL) {
 #if LWIP_HTTPD_SUPPORT_POST
       int is_post = 0;
@@ -2052,11 +1987,11 @@ http_parse_request(struct pbuf *inp, struct http_state *hs, struct tcp_pcb *pcb)
       }
       /* if we come here, method is OK, parse URI */
       left_len = (u16_t)(data_len - ((sp1 +1) - data));
-      sp2 = strnstr(sp1 + 1, " ", left_len);
+      sp2 = lwip_strnstr(sp1 + 1, " ", left_len);
 #if LWIP_HTTPD_SUPPORT_V09
       if (sp2 == NULL) {
         /* HTTP 0.9: respond with correct protocol version */
-        sp2 = strnstr(sp1 + 1, CRLF, left_len);
+        sp2 = lwip_strnstr(sp1 + 1, CRLF, left_len);
         is_09 = 1;
 #if LWIP_HTTPD_SUPPORT_POST
         if (is_post) {
@@ -2069,13 +2004,13 @@ http_parse_request(struct pbuf *inp, struct http_state *hs, struct tcp_pcb *pcb)
       uri_len = (u16_t)(sp2 - (sp1 + 1));
       if ((sp2 != 0) && (sp2 > sp1)) {
         /* wait for CRLFCRLF (indicating end of HTTP headers) before parsing anything */
-        if (strnstr(data, CRLF CRLF, data_len) != NULL) {
+        if (lwip_strnstr(data, CRLF CRLF, data_len) != NULL) {
           char *uri = sp1 + 1;
 #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE
           /* This is HTTP/1.0 compatible: for strict 1.1, a connection
              would always be persistent unless "close" was specified. */
-          if (!is_09 && (strnstr(data, HTTP11_CONNECTIONKEEPALIVE, data_len) ||
-              strnstr(data, HTTP11_CONNECTIONKEEPALIVE2, data_len))) {
+          if (!is_09 && (lwip_strnstr(data, HTTP11_CONNECTIONKEEPALIVE, data_len) ||
+              lwip_strnstr(data, HTTP11_CONNECTIONKEEPALIVE2, data_len))) {
             hs->keepalive = 1;
           } else {
             hs->keepalive = 0;
@@ -2259,7 +2194,7 @@ http_find_file(struct http_state *hs, const char *uri, int is_09)
       }
       tag_check = 0;
       for (loop = 0; loop < NUM_SHTML_EXTENSIONS; loop++) {
-        if (!stricmp(ext, g_pcSSIExtensions[loop])) {
+        if (!lwip_stricmp(ext, g_pcSSIExtensions[loop])) {
           tag_check = 1;
           break;
         }
@@ -2285,7 +2220,7 @@ http_find_file(struct http_state *hs, const char *uri, int is_09)
  * @param is_09 1 if the request is HTTP/0.9 (no HTTP headers in response)
  * @param uri the HTTP header URI
  * @param tag_check enable SSI tag checking
- * @param uri_has_params != NULL if URI has parameters (separated by '?')
+ * @param params != NULL if URI has parameters (separated by '?')
  * @return ERR_OK if file was found and hs has been initialized correctly
  *         another err_t otherwise
  */
@@ -2334,7 +2269,7 @@ http_init_file(struct http_state *hs, struct fs_file *file, int is_09, const cha
     if (is_09 && ((hs->handle->flags & FS_FILE_FLAGS_HEADER_INCLUDED) != 0)) {
       /* HTTP/0.9 responses are sent without HTTP header,
          search for the end of the header. */
-      char *file_start = strnstr(hs->file, CRLF CRLF, hs->left);
+      char *file_start = lwip_strnstr(hs->file, CRLF CRLF, hs->left);
       if (file_start != NULL) {
         size_t diff = file_start + 4 - hs->file;
         hs->file += diff;
@@ -2637,6 +2572,7 @@ httpd_init(void)
   tcp_setprio(pcb, HTTPD_TCP_PRIO);
   /* set SOF_REUSEADDR here to explicitly bind httpd to multiple interfaces */
   err = tcp_bind(pcb, IP_ANY_TYPE, HTTPD_SERVER_PORT);
+  LWIP_UNUSED_ARG(err); /* in case of LWIP_NOASSERT */
   LWIP_ASSERT("httpd_init: tcp_bind failed", err == ERR_OK);
   pcb = tcp_listen(pcb);
   LWIP_ASSERT("httpd_init: tcp_listen failed", pcb != NULL);
@@ -2690,4 +2626,4 @@ http_set_cgi_handlers(const tCGI *cgis, int num_handlers)
 }
 #endif /* LWIP_HTTPD_CGI */
 
-#endif /* LWIP_TCP */
+#endif /* LWIP_TCP && LWIP_CALLBACK_API */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/apps/httpd/httpd_structs.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/apps/httpd/httpd_structs.h b/net/ip/lwip_base/src/apps/httpd/httpd_structs.h
index dc53346..fbd135a 100644
--- a/net/ip/lwip_base/src/apps/httpd/httpd_structs.h
+++ b/net/ip/lwip_base/src/apps/httpd/httpd_structs.h
@@ -3,10 +3,6 @@
 
 #include "lwip/apps/httpd.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #if LWIP_HTTPD_DYNAMIC_HEADERS
 /** This struct is used for a list of HTTP header strings for various
  * filename extensions. */
@@ -115,8 +111,4 @@ static const char * const g_pcSSIExtensions[] = {
 #define NUM_SHTML_EXTENSIONS (sizeof(g_pcSSIExtensions) / sizeof(const char *))
 #endif /* LWIP_HTTPD_SSI */
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_HTTPD_STRUCTS_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/apps/lwiperf/lwiperf.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/apps/lwiperf/lwiperf.c b/net/ip/lwip_base/src/apps/lwiperf/lwiperf.c
index fea2c06..efabe47 100644
--- a/net/ip/lwip_base/src/apps/lwiperf/lwiperf.c
+++ b/net/ip/lwip_base/src/apps/lwiperf/lwiperf.c
@@ -53,7 +53,7 @@
 #include <string.h>
 
 /* Currently, only TCP-over-IPv4 is implemented (does iperf support IPv6 anyway?) */
-#if LWIP_IPV4 && LWIP_TCP
+#if LWIP_IPV4 && LWIP_TCP && LWIP_CALLBACK_API
 
 /** Specify the idle timeout (in seconds) after that the test fails */
 #ifndef LWIPERF_TCP_MAX_IDLE_SEC
@@ -262,7 +262,7 @@ lwiperf_tcp_client_send_more(lwiperf_state_tcp_t* conn)
       /* this session is time-limited */
       u32_t now = sys_now();
       u32_t diff_ms = now - conn->time_started;
-      u32_t time = (u32_t)-(s32_t)htonl(conn->settings.amount);
+      u32_t time = (u32_t)-(s32_t)lwip_htonl(conn->settings.amount);
       u32_t time_ms = time * 10;
       if (diff_ms >= time_ms) {
         /* time specified by the client is over -> close the connection */
@@ -271,7 +271,7 @@ lwiperf_tcp_client_send_more(lwiperf_state_tcp_t* conn)
       }
     } else {
       /* this session is byte-limited */
-      u32_t amount_bytes = htonl(conn->settings.amount);
+      u32_t amount_bytes = lwip_htonl(conn->settings.amount);
       /* @todo: this can send up to 1*MSS more than requested... */
       if (amount_bytes >= conn->bytes_transferred) {
         /* all requested bytes transferred -> close the connection */
@@ -294,7 +294,7 @@ lwiperf_tcp_client_send_more(lwiperf_state_tcp_t* conn)
     } else {
       /* transmit data */
       /* @todo: every x bytes, transmit the settings again */
-      txptr = (void*)(size_t)&lwiperf_txbuf_const[conn->bytes_transferred % 10];
+      txptr = LWIP_CONST_CAST(void*, &lwiperf_txbuf_const[conn->bytes_transferred % 10]);
       txlen_max = TCP_MSS;
       if (conn->bytes_transferred == 48) { /* @todo: fix this for intermediate settings, too */
         txlen_max = TCP_MSS - 24;
@@ -390,7 +390,7 @@ lwiperf_tx_start(lwiperf_state_tcp_t* conn)
   tcp_err(newpcb, lwiperf_tcp_err);
 
   ip_addr_copy(remote_addr, conn->conn_pcb->remote_ip);
-  remote_port = (u16_t)htonl(client_conn->settings.remote_port);
+  remote_port = (u16_t)lwip_htonl(client_conn->settings.remote_port);
 
   err = tcp_connect(newpcb, &remote_addr, remote_port, lwiperf_tcp_client_connected);
   if (err != ERR_OK) {
@@ -494,10 +494,8 @@ lwiperf_tcp_recv(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err)
         return ERR_VAL;
       }
     }
-    packet_idx += i;
-#else
-    packet_idx += q->len;
 #endif
+    packet_idx += q->len;
   }
   LWIP_ASSERT("count mismatch", packet_idx == p->tot_len);
   conn->bytes_transferred += packet_idx;
@@ -660,4 +658,4 @@ lwiperf_abort(void* lwiperf_session)
   }
 }
 
-#endif /* LWIP_IPV4 && LWIP_TCP */
+#endif /* LWIP_IPV4 && LWIP_TCP && LWIP_CALLBACK_API */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/apps/mdns/mdns.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/apps/mdns/mdns.c b/net/ip/lwip_base/src/apps/mdns/mdns.c
index 5da37bc..14334fc 100644
--- a/net/ip/lwip_base/src/apps/mdns/mdns.c
+++ b/net/ip/lwip_base/src/apps/mdns/mdns.c
@@ -52,10 +52,7 @@
  *
  * This file is part of the lwIP TCP/IP stack.
  *
- * Author: Erik Ekman <er...@verisure.com>
- *
- * Please coordinate changes and requests with Erik Ekman
- * <er...@verisure.com>
+ * Author: Erik Ekman <er...@kryo.se>
  *
  */
 
@@ -68,7 +65,6 @@
 #include "lwip/prot/dns.h"
 
 #include <string.h>
-#include <stdlib.h>
 
 #if LWIP_MDNS_RESPONDER
 
@@ -85,13 +81,13 @@
 #if LWIP_IPV4
 #include "lwip/igmp.h"
 /* IPv4 multicast group 224.0.0.251 */
-static const ip_addr_t v4group = IPADDR4_INIT(PP_HTONL(0xE00000FBUL));
+static const ip_addr_t v4group = DNS_MQUERY_IPV4_GROUP_INIT;
 #endif
 
 #if LWIP_IPV6
 #include "lwip/mld6.h"
 /* IPv6 multicast group FF02::FB */
-static const ip_addr_t v6group = IPADDR6_INIT(PP_HTONL(0xFF020000UL), PP_HTONL(0x00000000UL), PP_HTONL(0x00000000UL), PP_HTONL(0x000000FBUL));
+static const ip_addr_t v6group = DNS_MQUERY_IPV6_GROUP_INIT;
 #endif
 
 #define MDNS_PORT 5353
@@ -107,6 +103,8 @@ static const ip_addr_t v6group = IPADDR6_INIT(PP_HTONL(0xFF020000UL), PP_HTONL(0
 static u8_t mdns_netif_client_id;
 static struct udp_pcb *mdns_pcb;
 
+#define NETIF_TO_HOST(netif) (struct mdns_host*)(netif_get_client_data(netif, mdns_netif_client_id))
+
 #define TOPDOMAIN_LOCAL "local"
 
 #define REVERSE_PTR_TOPDOMAIN "arpa"
@@ -263,42 +261,6 @@ struct mdns_answer {
   u16_t rd_offset;
 };
 
-#ifndef LWIP_MDNS_STRNCASECMP
-#define LWIP_MDNS_STRNCASECMP(str1, str2, len) mdns_strncasecmp(str1, str2, len)
-/**
- * A small but sufficient implementation for case insensitive strncmp.
- * This can be defined to e.g. strnicmp for windows or strncasecmp for linux.
- */
-static int
-mdns_strncasecmp(const char* str1, const char* str2, size_t len)
-{
-  char c1, c2;
-
-  do {
-    c1 = *str1++;
-    c2 = *str2++;
-    if (c1 != c2) {
-      char c1_upc = c1 | 0x20;
-      if ((c1_upc >= 'a') && (c1_upc <= 'z')) {
-        /* characters are not equal an one is in the alphabet range:
-        downcase both chars and check again */
-        char c2_upc = c2 | 0x20;
-        if (c1_upc != c2_upc) {
-          /* still not equal */
-          /* don't care for < or > */
-          return 1;
-        }
-      } else {
-        /* characters are not equal but none is in the alphabet range */
-        return 1;
-      }
-    }
-  } while (len-- && c1 != 0);
-  return 0;
-}
-#endif /* LWIP_MDNS_STRNCASECMP */
-
-
 /**
  * Add a label part to a domain
  * @param domain The domain to add a label to
@@ -458,7 +420,7 @@ mdns_domain_eq(struct mdns_domain *a, struct mdns_domain *b)
     len = *ptra;
     ptra++;
     ptrb++;
-    res = LWIP_MDNS_STRNCASECMP((char *) ptra, (char *) ptrb, len);
+    res = lwip_strnicmp((char *) ptra, (char *) ptrb, len);
     if (res != 0) {
       return 0;
     }
@@ -504,15 +466,11 @@ mdns_build_reverse_v4_domain(struct mdns_domain *domain, const ip4_addr_t *addr)
   memset(domain, 0, sizeof(struct mdns_domain));
   ptr = (const u8_t *) addr;
   for (i = sizeof(ip4_addr_t) - 1; i >= 0; i--) {
-    char buf[3];
-    size_t pos = sizeof(buf);
+    char buf[4];
     u8_t val = ptr[i];
-    do {
-      pos--;
-      buf[pos] = '0' + (val % 10);
-      val /= 10;
-    } while (val != 0); /* loop is correct because u8_t needs at most 3 chars */
-    res = mdns_domain_add_label(domain, &buf[pos], (u8_t)(3 - pos));
+
+    lwip_itoa(buf, sizeof(buf), val);
+    res = mdns_domain_add_label(domain, buf, (u8_t)strlen(buf));
     LWIP_ERROR("mdns_build_reverse_v4_domain: Failed to add label", (res == ERR_OK), return res);
   }
   res = mdns_domain_add_label(domain, REVERSE_PTR_V4_DOMAIN, (u8_t)(sizeof(REVERSE_PTR_V4_DOMAIN)-1));
@@ -591,7 +549,7 @@ mdns_build_host_domain(struct mdns_domain *domain, struct mdns_host *mdns)
 {
   err_t res;
   memset(domain, 0, sizeof(struct mdns_domain));
-  LWIP_ERROR("mdns_build_host_domain: Not an mdns netif", (mdns != NULL), return ERR_VAL);
+  LWIP_ERROR("mdns_build_host_domain: mdns != NULL", (mdns != NULL), return ERR_VAL);
   res = mdns_domain_add_label(domain, mdns->name, (u8_t)strlen(mdns->name));
   LWIP_ERROR("mdns_build_host_domain: Failed to add label", (res == ERR_OK), return res);
   return mdns_add_dotlocal(domain);
@@ -611,7 +569,7 @@ mdns_build_dnssd_domain(struct mdns_domain *domain)
   LWIP_ERROR("mdns_build_dnssd_domain: Failed to add label", (res == ERR_OK), return res);
   res = mdns_domain_add_label(domain, "_dns-sd", (u8_t)(sizeof("_dns-sd")-1));
   LWIP_ERROR("mdns_build_dnssd_domain: Failed to add label", (res == ERR_OK), return res);
-  res = mdns_domain_add_label(domain, dnssd_protos[DNSSD_PROTO_UDP], (u8_t)(sizeof(dnssd_protos[DNSSD_PROTO_UDP])-1));
+  res = mdns_domain_add_label(domain, dnssd_protos[DNSSD_PROTO_UDP], (u8_t)strlen(dnssd_protos[DNSSD_PROTO_UDP]));
   LWIP_ERROR("mdns_build_dnssd_domain: Failed to add label", (res == ERR_OK), return res);
   return mdns_add_dotlocal(domain);
 }
@@ -636,7 +594,7 @@ mdns_build_service_domain(struct mdns_domain *domain, struct mdns_service *servi
   }
   res = mdns_domain_add_label(domain, service->service, (u8_t)strlen(service->service));
   LWIP_ERROR("mdns_build_service_domain: Failed to add label", (res == ERR_OK), return res);
-  res = mdns_domain_add_label(domain, dnssd_protos[service->proto], (u8_t)(sizeof(dnssd_protos[DNSSD_PROTO_UDP])-1));
+  res = mdns_domain_add_label(domain, dnssd_protos[service->proto], (u8_t)strlen(dnssd_protos[service->proto]));
   LWIP_ERROR("mdns_build_service_domain: Failed to add label", (res == ERR_OK), return res);
   return mdns_add_dotlocal(domain);
 }
@@ -690,7 +648,7 @@ check_host(struct netif *netif, struct mdns_rr_info *rr, u8_t *reverse_v6_reply)
 #endif
   }
 
-  res = mdns_build_host_domain(&mydomain, (struct mdns_host*)netif->client_data[mdns_netif_client_id]);
+  res = mdns_build_host_domain(&mydomain, NETIF_TO_HOST(netif));
   /* Handle requests for our hostname */
   if (res == ERR_OK && mdns_domain_eq(&rr->domain, &mydomain)) {
     /* TODO return NSEC if unsupported protocol requested */
@@ -858,7 +816,7 @@ mdns_write_domain(struct mdns_outpacket *outpkt, struct mdns_domain *domain)
   }
   if (jump_offset) {
     /* Write jump */
-    jump = htons(DOMAIN_JUMP | jump_offset);
+    jump = lwip_htons(DOMAIN_JUMP | jump_offset);
     res = pbuf_take_at(outpkt->pbuf, &jump, DOMAIN_JUMP_SIZE, outpkt->write_offset);
     if (res != ERR_OK) {
       return res;
@@ -910,7 +868,7 @@ mdns_add_question(struct mdns_outpacket *outpkt, struct mdns_domain *domain, u16
   }
 
   /* Write type */
-  field16 = htons(type);
+  field16 = lwip_htons(type);
   res = pbuf_take_at(outpkt->pbuf, &field16, sizeof(field16), outpkt->write_offset);
   if (res != ERR_OK) {
     return res;
@@ -921,7 +879,7 @@ mdns_add_question(struct mdns_outpacket *outpkt, struct mdns_domain *domain, u16
   if (unicast) {
     klass |= 0x8000;
   }
-  field16 = htons(klass);
+  field16 = lwip_htons(klass);
   res = pbuf_take_at(outpkt->pbuf, &field16, sizeof(field16), outpkt->write_offset);
   if (res != ERR_OK) {
     return res;
@@ -985,7 +943,7 @@ mdns_add_answer(struct mdns_outpacket *reply, struct mdns_domain *domain, u16_t
   mdns_add_question(reply, domain, type, klass, cache_flush);
 
   /* Write TTL */
-  field32 = htonl(ttl);
+  field32 = lwip_htonl(ttl);
   res = pbuf_take_at(reply->pbuf, &field32, sizeof(field32), reply->write_offset);
   if (res != ERR_OK) {
     return res;
@@ -1015,7 +973,7 @@ mdns_add_answer(struct mdns_outpacket *reply, struct mdns_domain *domain, u16_t
   }
 
   /* Write rd_length after when we know the answer size */
-  field16 = htons(reply->write_offset - answer_offset);
+  field16 = lwip_htons(reply->write_offset - answer_offset);
   res = pbuf_take_at(reply->pbuf, &field16, sizeof(field16), rdlen_offset);
 
   return res;
@@ -1043,14 +1001,14 @@ mdns_read_rr_info(struct mdns_packet *pkt, struct mdns_rr_info *info)
     return ERR_VAL;
   }
   pkt->parse_offset += copied;
-  info->type = ntohs(field16);
+  info->type = lwip_ntohs(field16);
 
   copied = pbuf_copy_partial(pkt->pbuf, &field16, sizeof(field16), pkt->parse_offset);
   if (copied != sizeof(field16)) {
     return ERR_VAL;
   }
   pkt->parse_offset += copied;
-  info->klass = ntohs(field16);
+  info->klass = lwip_ntohs(field16);
 
   return ERR_OK;
 }
@@ -1132,14 +1090,14 @@ mdns_read_answer(struct mdns_packet *pkt, struct mdns_answer *answer)
       return ERR_VAL;
     }
     pkt->parse_offset += copied;
-    answer->ttl = ntohl(ttl);
+    answer->ttl = lwip_ntohl(ttl);
 
     copied = pbuf_copy_partial(pkt->pbuf, &field16, sizeof(field16), pkt->parse_offset);
     if (copied != sizeof(field16)) {
       return ERR_VAL;
     }
     pkt->parse_offset += copied;
-    answer->rd_length = ntohs(field16);
+    answer->rd_length = lwip_ntohs(field16);
 
     answer->rd_offset = pkt->parse_offset;
     pkt->parse_offset += answer->rd_length;
@@ -1155,9 +1113,9 @@ static err_t
 mdns_add_a_answer(struct mdns_outpacket *reply, u16_t cache_flush, struct netif *netif)
 {
   struct mdns_domain host;
-  mdns_build_host_domain(&host, (struct mdns_host*)netif->client_data[mdns_netif_client_id]);
+  mdns_build_host_domain(&host, NETIF_TO_HOST(netif));
   LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Responding with A record\n"));
-  return mdns_add_answer(reply, &host, DNS_RRTYPE_A, DNS_RRCLASS_IN, cache_flush, ((struct mdns_host*)netif->client_data[mdns_netif_client_id])->dns_ttl, (const u8_t *) netif_ip4_addr(netif), sizeof(ip4_addr_t), NULL);
+  return mdns_add_answer(reply, &host, DNS_RRTYPE_A, DNS_RRCLASS_IN, cache_flush, (NETIF_TO_HOST(netif))->dns_ttl, (const u8_t *) netif_ip4_addr(netif), sizeof(ip4_addr_t), NULL);
 }
 
 /** Write a 4.3.2.1.in-addr.arpa -> hostname.local PTR RR to outpacket */
@@ -1165,10 +1123,10 @@ static err_t
 mdns_add_hostv4_ptr_answer(struct mdns_outpacket *reply, u16_t cache_flush, struct netif *netif)
 {
   struct mdns_domain host, revhost;
-  mdns_build_host_domain(&host, (struct mdns_host*)netif->client_data[mdns_netif_client_id]);
+  mdns_build_host_domain(&host, NETIF_TO_HOST(netif));
   mdns_build_reverse_v4_domain(&revhost, netif_ip4_addr(netif));
   LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Responding with v4 PTR record\n"));
-  return mdns_add_answer(reply, &revhost, DNS_RRTYPE_PTR, DNS_RRCLASS_IN, cache_flush, ((struct mdns_host*)netif->client_data[mdns_netif_client_id])->dns_ttl, NULL, 0, &host);
+  return mdns_add_answer(reply, &revhost, DNS_RRTYPE_PTR, DNS_RRCLASS_IN, cache_flush, (NETIF_TO_HOST(netif))->dns_ttl, NULL, 0, &host);
 }
 #endif
 
@@ -1178,9 +1136,9 @@ static err_t
 mdns_add_aaaa_answer(struct mdns_outpacket *reply, u16_t cache_flush, struct netif *netif, int addrindex)
 {
   struct mdns_domain host;
-  mdns_build_host_domain(&host, (struct mdns_host*)netif->client_data[mdns_netif_client_id]);
+  mdns_build_host_domain(&host, NETIF_TO_HOST(netif));
   LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Responding with AAAA record\n"));
-  return mdns_add_answer(reply, &host, DNS_RRTYPE_AAAA, DNS_RRCLASS_IN, cache_flush, ((struct mdns_host*)netif->client_data[mdns_netif_client_id])->dns_ttl, (const u8_t *) netif_ip6_addr(netif, addrindex), sizeof(ip6_addr_t), NULL);
+  return mdns_add_answer(reply, &host, DNS_RRTYPE_AAAA, DNS_RRCLASS_IN, cache_flush, (NETIF_TO_HOST(netif))->dns_ttl, (const u8_t *) netif_ip6_addr(netif, addrindex), sizeof(ip6_addr_t), NULL);
 }
 
 /** Write a x.y.z.ip6.arpa -> hostname.local PTR RR to outpacket */
@@ -1188,10 +1146,10 @@ static err_t
 mdns_add_hostv6_ptr_answer(struct mdns_outpacket *reply, u16_t cache_flush, struct netif *netif, int addrindex)
 {
   struct mdns_domain host, revhost;
-  mdns_build_host_domain(&host, (struct mdns_host*)netif->client_data[mdns_netif_client_id]);
+  mdns_build_host_domain(&host, NETIF_TO_HOST(netif));
   mdns_build_reverse_v6_domain(&revhost, netif_ip6_addr(netif, addrindex));
   LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Responding with v6 PTR record\n"));
-  return mdns_add_answer(reply, &revhost, DNS_RRTYPE_PTR, DNS_RRCLASS_IN, cache_flush, ((struct mdns_host*)netif->client_data[mdns_netif_client_id])->dns_ttl, NULL, 0, &host);
+  return mdns_add_answer(reply, &revhost, DNS_RRTYPE_PTR, DNS_RRCLASS_IN, cache_flush, (NETIF_TO_HOST(netif))->dns_ttl, NULL, 0, &host);
 }
 #endif
 
@@ -1232,9 +1190,9 @@ mdns_add_srv_answer(struct mdns_outpacket *reply, u16_t cache_flush, struct mdns
      */
     srvhost.skip_compression = 1;
   }
-  srvdata[0] = htons(SRV_PRIORITY);
-  srvdata[1] = htons(SRV_WEIGHT);
-  srvdata[2] = htons(service->port);
+  srvdata[0] = lwip_htons(SRV_PRIORITY);
+  srvdata[1] = lwip_htons(SRV_WEIGHT);
+  srvdata[2] = lwip_htons(service->port);
   LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Responding with SRV record\n"));
   return mdns_add_answer(reply, &service_instance, DNS_RRTYPE_SRV, DNS_RRCLASS_IN, cache_flush, service->dns_ttl,
                          (const u8_t *) &srvdata, sizeof(srvdata), &srvhost);
@@ -1295,7 +1253,7 @@ mdns_send_outpacket(struct mdns_outpacket *outpkt)
   struct mdns_service *service;
   err_t res;
   int i;
-  struct mdns_host* mdns = (struct mdns_host*)outpkt->netif->client_data[mdns_netif_client_id];
+  struct mdns_host* mdns = NETIF_TO_HOST(outpkt->netif);
 
   /* Write answers to host questions */
 #if LWIP_IPV4
@@ -1449,11 +1407,11 @@ mdns_send_outpacket(struct mdns_outpacket *outpkt)
     /* Write header */
     memset(&hdr, 0, sizeof(hdr));
     hdr.flags1 = DNS_FLAG1_RESPONSE | DNS_FLAG1_AUTHORATIVE;
-    hdr.numanswers = htons(outpkt->answers);
-    hdr.numextrarr = htons(outpkt->additional);
+    hdr.numanswers = lwip_htons(outpkt->answers);
+    hdr.numextrarr = lwip_htons(outpkt->additional);
     if (outpkt->legacy_query) {
-      hdr.numquestions = htons(1);
-      hdr.id = htons(outpkt->tx_id);
+      hdr.numquestions = lwip_htons(1);
+      hdr.id = lwip_htons(outpkt->tx_id);
     }
     pbuf_take(outpkt->pbuf, &hdr, sizeof(hdr));
 
@@ -1495,7 +1453,7 @@ mdns_announce(struct netif *netif, const ip_addr_t *destination)
 {
   struct mdns_outpacket announce;
   int i;
-  struct mdns_host* mdns = (struct mdns_host*)netif->client_data[mdns_netif_client_id];
+  struct mdns_host* mdns = NETIF_TO_HOST(netif);
 
   memset(&announce, 0, sizeof(announce));
   announce.netif = netif;
@@ -1540,7 +1498,7 @@ mdns_handle_question(struct mdns_packet *pkt)
   int replies = 0;
   int i;
   err_t res;
-  struct mdns_host* mdns = (struct mdns_host*)pkt->netif->client_data[mdns_netif_client_id];
+  struct mdns_host* mdns = NETIF_TO_HOST(pkt->netif);
 
   mdns_init_outpacket(&reply, pkt);
 
@@ -1695,19 +1653,19 @@ mdns_handle_question(struct mdns_packet *pkt)
           do {
             /* Check priority field */
             len = pbuf_copy_partial(pkt->pbuf, &field16, sizeof(field16), read_pos);
-            if (len != sizeof(field16) || ntohs(field16) != SRV_PRIORITY) {
+            if (len != sizeof(field16) || lwip_ntohs(field16) != SRV_PRIORITY) {
               break;
             }
             read_pos += len;
             /* Check weight field */
             len = pbuf_copy_partial(pkt->pbuf, &field16, sizeof(field16), read_pos);
-            if (len != sizeof(field16) || ntohs(field16) != SRV_WEIGHT) {
+            if (len != sizeof(field16) || lwip_ntohs(field16) != SRV_WEIGHT) {
               break;
             }
             read_pos += len;
             /* Check port field */
             len = pbuf_copy_partial(pkt->pbuf, &field16, sizeof(field16), read_pos);
-            if (len != sizeof(field16) || ntohs(field16) != service->port) {
+            if (len != sizeof(field16) || lwip_ntohs(field16) != service->port) {
               break;
             }
             read_pos += len;
@@ -1780,8 +1738,6 @@ mdns_handle_response(struct mdns_packet *pkt)
 /**
  * Receive input function for MDNS packets.
  * Handles both IPv4 and IPv6 UDP pcbs.
- *
- * @params see udp.h
  */
 static void
 mdns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port)
@@ -1796,7 +1752,7 @@ mdns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr,
 
   LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Received IPv%d MDNS packet, len %d\n", IP_IS_V6(addr)? 6 : 4, p->tot_len));
 
-  if (recv_netif->client_data[mdns_netif_client_id] == NULL) {
+  if (NETIF_TO_HOST(recv_netif) == NULL) {
     /* From netif not configured for MDNS */
     goto dealloc;
   }
@@ -1818,9 +1774,9 @@ mdns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr,
   packet.netif = recv_netif;
   packet.pbuf = p;
   packet.parse_offset = offset;
-  packet.tx_id = ntohs(hdr.id);
-  packet.questions = packet.questions_left = ntohs(hdr.numquestions);
-  packet.answers = packet.answers_left = ntohs(hdr.numanswers) + ntohs(hdr.numauthrr) + ntohs(hdr.numextrarr);
+  packet.tx_id = lwip_ntohs(hdr.id);
+  packet.questions = packet.questions_left = lwip_ntohs(hdr.numquestions);
+  packet.answers = packet.answers_left = lwip_ntohs(hdr.numanswers) + lwip_ntohs(hdr.numauthrr) + lwip_ntohs(hdr.numextrarr);
 
 #if LWIP_IPV6
   if (IP_IS_V6(ip_current_dest_addr())) {
@@ -1864,6 +1820,7 @@ mdns_resp_init(void)
   mdns_pcb->ttl = MDNS_TTL;
 #endif
   res = udp_bind(mdns_pcb, IP_ANY_TYPE, MDNS_PORT);
+  LWIP_UNUSED_ARG(res); /* in case of LWIP_NOASSERT */
   LWIP_ASSERT("Failed to bind pcb", res == ERR_OK);
   udp_recv(mdns_pcb, mdns_recv, NULL);
 
@@ -1883,7 +1840,7 @@ mdns_resp_netif_settings_changed(struct netif *netif)
 {
   LWIP_ERROR("mdns_resp_netif_ip_changed: netif != NULL", (netif != NULL), return);
 
-  if (netif->client_data[mdns_netif_client_id] == NULL) {
+  if (NETIF_TO_HOST(netif) == NULL) {
     return;
   }
 
@@ -1892,7 +1849,7 @@ mdns_resp_netif_settings_changed(struct netif *netif)
    mdns_announce(netif, IP6_ADDR_ANY);
 #endif
 #if LWIP_IPV4
-   mdns_announce(netif, IP_ADDR_ANY);
+   mdns_announce(netif, IP4_ADDR_ANY);
 #endif
 }
 
@@ -1915,11 +1872,11 @@ mdns_resp_add_netif(struct netif *netif, const char *hostname, u32_t dns_ttl)
   LWIP_ERROR("mdns_resp_add_netif: netif != NULL", (netif != NULL), return ERR_VAL);
   LWIP_ERROR("mdns_resp_add_netif: Hostname too long", (strlen(hostname) <= MDNS_LABEL_MAXLEN), return ERR_VAL);
 
-  LWIP_ASSERT("mdns_resp_add_netif: Double add", netif->client_data[mdns_netif_client_id] == NULL);
+  LWIP_ASSERT("mdns_resp_add_netif: Double add", NETIF_TO_HOST(netif) == NULL);
   mdns = (struct mdns_host *) mem_malloc(sizeof(struct mdns_host));
   LWIP_ERROR("mdns_resp_add_netif: Alloc failed", (mdns != NULL), return ERR_MEM);
 
-  netif->client_data[mdns_netif_client_id] = mdns;
+  netif_set_client_data(netif, mdns_netif_client_id, mdns);
 
   memset(mdns, 0, sizeof(struct mdns_host));
   MEMCPY(&mdns->name, hostname, LWIP_MIN(MDNS_LABEL_MAXLEN, strlen(hostname)));
@@ -1944,7 +1901,7 @@ mdns_resp_add_netif(struct netif *netif, const char *hostname, u32_t dns_ttl)
 
 cleanup:
   mem_free(mdns);
-  netif->client_data[mdns_netif_client_id] = NULL;
+  netif_set_client_data(netif, mdns_netif_client_id, NULL);
   return res;
 }
 
@@ -1962,7 +1919,7 @@ mdns_resp_remove_netif(struct netif *netif)
   struct mdns_host* mdns;
 
   LWIP_ASSERT("mdns_resp_remove_netif: Null pointer", netif);
-  mdns = (struct mdns_host*)netif->client_data[mdns_netif_client_id];
+  mdns = NETIF_TO_HOST(netif);
   LWIP_ERROR("mdns_resp_remove_netif: Not an active netif", (mdns != NULL), return ERR_VAL);
 
   for (i = 0; i < MDNS_MAX_SERVICES; i++) {
@@ -1981,7 +1938,7 @@ mdns_resp_remove_netif(struct netif *netif)
 #endif
 
   mem_free(mdns);
-  netif->client_data[mdns_netif_client_id] = NULL;
+  netif_set_client_data(netif, mdns_netif_client_id, NULL);
   return ERR_OK;
 }
 
@@ -2009,7 +1966,7 @@ mdns_resp_add_service(struct netif *netif, const char *name, const char *service
   struct mdns_host* mdns;
 
   LWIP_ASSERT("mdns_resp_add_service: netif != NULL", netif);
-  mdns = (struct mdns_host*)netif->client_data[mdns_netif_client_id];
+  mdns = NETIF_TO_HOST(netif);
   LWIP_ERROR("mdns_resp_add_service: Not an mdns netif", (mdns != NULL), return ERR_VAL);
 
   LWIP_ERROR("mdns_resp_add_service: Name too long", (strlen(name) <= MDNS_LABEL_MAXLEN), return ERR_VAL);
@@ -2044,7 +2001,7 @@ mdns_resp_add_service(struct netif *netif, const char *name, const char *service
   mdns_announce(netif, IP6_ADDR_ANY);
 #endif
 #if LWIP_IPV4
-  mdns_announce(netif, IP_ADDR_ANY);
+  mdns_announce(netif, IP4_ADDR_ANY);
 #endif
 
   return ERR_OK;
@@ -2062,7 +2019,7 @@ mdns_resp_add_service(struct netif *netif, const char *name, const char *service
 err_t
 mdns_resp_add_service_txtitem(struct mdns_service *service, const char *txt, u8_t txt_len)
 {
-  LWIP_ASSERT("mdns_resp_add_service: service != NULL", service);
+  LWIP_ASSERT("mdns_resp_add_service_txtitem: service != NULL", service);
 
   /* Use a mdns_domain struct to store txt chunks since it is the same encoding */
   return mdns_domain_add_label(&service->txtdata, txt, txt_len);

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/apps/mqtt/mqtt.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/apps/mqtt/mqtt.c b/net/ip/lwip_base/src/apps/mqtt/mqtt.c
new file mode 100644
index 0000000..a0e77b9
--- /dev/null
+++ b/net/ip/lwip_base/src/apps/mqtt/mqtt.c
@@ -0,0 +1,1341 @@
+/**
+ * @file
+ * MQTT client
+ *
+ * @defgroup mqtt MQTT client
+ * @ingroup apps
+ * @verbinclude mqtt_client.txt
+ */
+
+/*
+ * Copyright (c) 2016 Erik Andersson <er...@gmail.com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ * 2. 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.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ *
+ * This file is part of the lwIP TCP/IP stack
+ *
+ * Author: Erik Andersson <er...@gmail.com>
+ *
+ *
+ * @todo:
+ * - Handle large outgoing payloads for PUBLISH messages
+ * - Fix restriction of a single topic in each (UN)SUBSCRIBE message (protocol has support for multiple topics)
+ * - Add support for legacy MQTT protocol version
+ *
+ * Please coordinate changes and requests with Erik Andersson
+ * Erik Andersson <er...@gmail.com>
+ *
+ */
+#include "lwip/apps/mqtt.h"
+#include "lwip/timeouts.h"
+#include "lwip/ip_addr.h"
+#include "lwip/mem.h"
+#include "lwip/err.h"
+#include "lwip/pbuf.h"
+#include "lwip/tcp.h"
+#include <string.h>
+
+#if LWIP_TCP && LWIP_CALLBACK_API
+
+/**
+ * MQTT_DEBUG: Default is off.
+ */
+#if !defined MQTT_DEBUG || defined __DOXYGEN__
+#define MQTT_DEBUG                  LWIP_DBG_OFF
+#endif
+
+#define MQTT_DEBUG_TRACE        (MQTT_DEBUG | LWIP_DBG_TRACE)
+#define MQTT_DEBUG_STATE        (MQTT_DEBUG | LWIP_DBG_STATE)
+#define MQTT_DEBUG_WARN         (MQTT_DEBUG | LWIP_DBG_LEVEL_WARNING)
+#define MQTT_DEBUG_WARN_STATE   (MQTT_DEBUG | LWIP_DBG_LEVEL_WARNING | LWIP_DBG_STATE)
+#define MQTT_DEBUG_SERIOUS      (MQTT_DEBUG | LWIP_DBG_LEVEL_SERIOUS)
+
+static void mqtt_cyclic_timer(void *arg);
+
+/**
+ * MQTT client connection states
+ */
+enum {
+  TCP_DISCONNECTED,
+  TCP_CONNECTING,
+  MQTT_CONNECTING,
+  MQTT_CONNECTED
+};
+
+/**
+ * MQTT control message types
+ */
+enum mqtt_message_type {
+  MQTT_MSG_TYPE_CONNECT = 1,
+  MQTT_MSG_TYPE_CONNACK = 2,
+  MQTT_MSG_TYPE_PUBLISH = 3,
+  MQTT_MSG_TYPE_PUBACK = 4,
+  MQTT_MSG_TYPE_PUBREC = 5,
+  MQTT_MSG_TYPE_PUBREL = 6,
+  MQTT_MSG_TYPE_PUBCOMP = 7,
+  MQTT_MSG_TYPE_SUBSCRIBE = 8,
+  MQTT_MSG_TYPE_SUBACK = 9,
+  MQTT_MSG_TYPE_UNSUBSCRIBE = 10,
+  MQTT_MSG_TYPE_UNSUBACK = 11,
+  MQTT_MSG_TYPE_PINGREQ = 12,
+  MQTT_MSG_TYPE_PINGRESP = 13,
+  MQTT_MSG_TYPE_DISCONNECT = 14
+};
+
+/** Helpers to extract control packet type and qos from first byte in fixed header */
+#define MQTT_CTL_PACKET_TYPE(fixed_hdr_byte0) ((fixed_hdr_byte0 & 0xf0) >> 4)
+#define MQTT_CTL_PACKET_QOS(fixed_hdr_byte0) ((fixed_hdr_byte0 & 0x6) >> 1)
+
+/**
+ * MQTT connect flags, only used in CONNECT message
+ */
+enum mqtt_connect_flag {
+  MQTT_CONNECT_FLAG_USERNAME = 1 << 7,
+  MQTT_CONNECT_FLAG_PASSWORD = 1 << 6,
+  MQTT_CONNECT_FLAG_WILL_RETAIN = 1 << 5,
+  MQTT_CONNECT_FLAG_WILL = 1 << 2,
+  MQTT_CONNECT_FLAG_CLEAN_SESSION = 1 << 1
+};
+
+
+#if defined(LWIP_DEBUG)
+static const char * const mqtt_message_type_str[15] =
+{
+  "UNDEFINED",
+  "CONNECT",
+  "CONNACK",
+  "PUBLISH",
+  "PUBACK",
+  "PUBREC",
+  "PUBREL",
+  "PUBCOMP",
+  "SUBSCRIBE",
+  "SUBACK",
+  "UNSUBSCRIBE",
+  "UNSUBACK",
+  "PINGREQ",
+  "PINGRESP",
+  "DISCONNECT"
+};
+
+/**
+ * Message type value to string
+ * @param msg_type see enum mqtt_message_type
+ * 
+ * @return Control message type text string
+ */
+static const char *
+mqtt_msg_type_to_str(u8_t msg_type)
+{
+  if (msg_type >= LWIP_ARRAYSIZE(mqtt_message_type_str)) {
+    msg_type = 0;
+  }
+  return mqtt_message_type_str[msg_type];
+}
+
+#endif
+
+
+/**
+ * Generate MQTT packet identifier
+ * @param client MQTT client
+ * @return New packet identifier, range 1 to 65535
+ */
+static u16_t
+msg_generate_packet_id(mqtt_client_t *client)
+{
+  client->pkt_id_seq++;
+  if (client->pkt_id_seq == 0) {
+    client->pkt_id_seq++;
+  }
+  return client->pkt_id_seq;
+}
+
+/*--------------------------------------------------------------------------------------------------------------------- */
+/* Output ring buffer */
+
+
+#define MQTT_RINGBUF_IDX_MASK ((MQTT_OUTPUT_RINGBUF_SIZE) - 1)
+
+/** Add single item to ring buffer */
+#define mqtt_ringbuf_put(rb, item) ((rb)->buf)[(rb)->put++ & MQTT_RINGBUF_IDX_MASK] = (item)
+
+/** Return number of bytes in ring buffer */
+#define mqtt_ringbuf_len(rb) ((u16_t)((rb)->put - (rb)->get))
+
+/** Return number of bytes free in ring buffer */
+#define mqtt_ringbuf_free(rb) (MQTT_OUTPUT_RINGBUF_SIZE - mqtt_ringbuf_len(rb))
+
+/** Return number of bytes possible to read without wrapping around */
+#define mqtt_ringbuf_linear_read_length(rb) LWIP_MIN(mqtt_ringbuf_len(rb), (MQTT_OUTPUT_RINGBUF_SIZE - ((rb)->get & MQTT_RINGBUF_IDX_MASK)))
+
+/** Return pointer to ring buffer get position */
+#define mqtt_ringbuf_get_ptr(rb) (&(rb)->buf[(rb)->get & MQTT_RINGBUF_IDX_MASK])
+
+#define mqtt_ringbuf_advance_get_idx(rb, len) ((rb)->get += (len))
+
+
+/**
+ * Try send as many bytes as possible from output ring buffer
+ * @param rb Output ring buffer
+ * @param tpcb TCP connection handle
+ */
+static void
+mqtt_output_send(struct mqtt_ringbuf_t *rb, struct tcp_pcb *tpcb)
+{
+  err_t err;
+  u8_t wrap = 0;
+  u16_t ringbuf_lin_len = mqtt_ringbuf_linear_read_length(rb);
+  u16_t send_len = tcp_sndbuf(tpcb);
+  LWIP_ASSERT("mqtt_output_send: tpcb != NULL", tpcb != NULL);
+
+  if (send_len == 0 || ringbuf_lin_len == 0) {
+    return;
+  }
+
+  LWIP_DEBUGF(MQTT_DEBUG_TRACE,("mqtt_output_send: tcp_sndbuf: %d bytes, ringbuf_linear_available: %d, get %d, put %d\n",
+                                send_len, ringbuf_lin_len, ((rb)->get & MQTT_RINGBUF_IDX_MASK), ((rb)->put & MQTT_RINGBUF_IDX_MASK)));
+
+  if (send_len > ringbuf_lin_len) {
+    /* Space in TCP output buffer is larger than available in ring buffer linear portion */
+    send_len = ringbuf_lin_len;
+    /* Wrap around if more data in ring buffer after linear portion */
+    wrap = (mqtt_ringbuf_len(rb) > ringbuf_lin_len);
+  }
+  err = tcp_write(tpcb, mqtt_ringbuf_get_ptr(rb), send_len, TCP_WRITE_FLAG_COPY | (wrap ? TCP_WRITE_FLAG_MORE : 0));
+  if ((err == ERR_OK) && wrap) {
+    mqtt_ringbuf_advance_get_idx(rb, send_len);
+    /* Use the lesser one of ring buffer linear length and TCP send buffer size */
+    send_len = LWIP_MIN(tcp_sndbuf(tpcb), mqtt_ringbuf_linear_read_length(rb));
+    err = tcp_write(tpcb, mqtt_ringbuf_get_ptr(rb), send_len, TCP_WRITE_FLAG_COPY);
+  }
+
+  if (err == ERR_OK) {
+    mqtt_ringbuf_advance_get_idx(rb, send_len);
+    /* Flush */
+    tcp_output(tpcb);
+  } else {
+    LWIP_DEBUGF(MQTT_DEBUG_WARN, ("mqtt_output_send: Send failed with err %d (\"%s\")\n", err, lwip_strerr(err)));
+  }
+}
+
+
+
+/*--------------------------------------------------------------------------------------------------------------------- */
+/* Request queue */
+
+/**
+ * Create request item
+ * @param r_objs Pointer to request objects
+ * @param pkt_id Packet identifier of request
+ * @param cb Packet callback to call when requests lifetime ends
+ * @param arg Parameter following callback
+ * @return Request or NULL if failed to create
+ */
+static struct mqtt_request_t *
+mqtt_create_request(struct mqtt_request_t *r_objs, u16_t pkt_id, mqtt_request_cb_t cb, void *arg)
+{
+  struct mqtt_request_t *r = NULL;
+  u8_t n;
+  LWIP_ASSERT("mqtt_create_request: r_objs != NULL", r_objs != NULL);
+  for (n = 0; n < MQTT_REQ_MAX_IN_FLIGHT; n++) {
+    /* Item point to itself if not in use */
+    if (r_objs[n].next == &r_objs[n]) {
+      r = &r_objs[n];
+      r->next = NULL;
+      r->cb = cb;
+      r->arg = arg;
+      r->pkt_id = pkt_id;
+      break;
+    }
+  }
+  return r;
+}
+
+
+/**
+ * Append request to pending request queue
+ * @param tail Pointer to request queue tail pointer
+ * @param r Request to append
+ */
+static void
+mqtt_append_request(struct mqtt_request_t **tail, struct mqtt_request_t *r)
+{
+  struct mqtt_request_t *head = NULL;
+  s16_t time_before = 0;
+  struct mqtt_request_t *iter;
+
+  LWIP_ASSERT("mqtt_append_request: tail != NULL", tail != NULL);
+
+  /* Iterate trough queue to find head, and count total timeout time */
+  for (iter = *tail; iter != NULL; iter = iter->next) {
+    time_before += iter->timeout_diff;
+    head = iter;
+  }
+
+  LWIP_ASSERT("mqtt_append_request: time_before <= MQTT_REQ_TIMEOUT", time_before <= MQTT_REQ_TIMEOUT);
+  r->timeout_diff = MQTT_REQ_TIMEOUT - time_before;
+  if (head == NULL) {
+    *tail = r;
+  } else {
+    head->next = r;
+  }
+}
+
+
+/**
+ * Delete request item
+ * @param r Request item to delete
+ */
+static void
+mqtt_delete_request(struct mqtt_request_t *r)
+{
+  if (r != NULL) {
+    r->next = r;
+  }
+}
+
+/**
+ * Remove a request item with a specific packet identifier from request queue
+ * @param tail Pointer to request queue tail pointer
+ * @param pkt_id Packet identifier of request to take
+ * @return Request item if found, NULL if not
+ */
+static struct mqtt_request_t *
+mqtt_take_request(struct mqtt_request_t **tail, u16_t pkt_id)
+{
+  struct mqtt_request_t *iter = NULL, *prev = NULL;
+  LWIP_ASSERT("mqtt_take_request: tail != NULL", tail != NULL);
+  /* Search all request for pkt_id */
+  for (iter = *tail; iter != NULL; iter = iter->next) {
+    if (iter->pkt_id == pkt_id) {
+      break;
+    }
+    prev = iter;
+  }
+
+  /* If request was found */
+  if (iter != NULL) {
+    /* unchain */
+    if (prev == NULL) {
+      *tail= iter->next;
+    } else {
+      prev->next = iter->next;
+    }
+    /* If exists, add remaining timeout time for the request to next */
+    if (iter->next != NULL) {
+      iter->next->timeout_diff += iter->timeout_diff;
+    }
+    iter->next = NULL;
+  }
+  return iter;
+}
+
+/**
+ * Handle requests timeout
+ * @param tail Pointer to request queue tail pointer
+ * @param t Time since last call in seconds
+ */
+static void
+mqtt_request_time_elapsed(struct mqtt_request_t **tail, u8_t t)
+{
+  struct mqtt_request_t *r = *tail;
+  LWIP_ASSERT("mqtt_request_time_elapsed: tail != NULL", tail != NULL);
+  while (t > 0 && r != NULL) {
+    if (t >= r->timeout_diff) {
+      t -= (u8_t)r->timeout_diff;
+      /* Unchain */
+      *tail = r->next;
+      /* Notify upper layer about timeout */
+      if (r->cb != NULL) {
+        r->cb(r->arg, ERR_TIMEOUT);
+      }
+      mqtt_delete_request(r);
+      /* Tail might be be modified in callback, so re-read it in every iteration */
+      r = *(struct mqtt_request_t * const volatile *)tail;
+    } else {
+      r->timeout_diff -= t;
+      t = 0;
+    }
+  }
+}
+
+/**
+ * Free all request items
+ * @param tail Pointer to request queue tail pointer
+ */
+static void
+mqtt_clear_requests(struct mqtt_request_t **tail)
+{
+  struct mqtt_request_t *iter, *next;
+  LWIP_ASSERT("mqtt_clear_requests: tail != NULL", tail != NULL);
+  for (iter = *tail; iter != NULL; iter = next) {
+    next = iter->next;
+    mqtt_delete_request(iter);
+  }
+  *tail = NULL;
+}
+/**
+ * Initialize all request items
+ * @param r_objs Pointer to request objects
+ */
+static void
+mqtt_init_requests(struct mqtt_request_t *r_objs)
+{
+  u8_t n;
+  LWIP_ASSERT("mqtt_init_requests: r_objs != NULL", r_objs != NULL);
+  for (n = 0; n < MQTT_REQ_MAX_IN_FLIGHT; n++) {
+    /* Item pointing to itself indicates unused */
+    r_objs[n].next = &r_objs[n];
+  }
+}
+
+/*--------------------------------------------------------------------------------------------------------------------- */
+/* Output message build helpers */
+
+
+static void
+mqtt_output_append_u8(struct mqtt_ringbuf_t *rb, u8_t value)
+{
+  mqtt_ringbuf_put(rb, value);
+}
+
+static
+void mqtt_output_append_u16(struct mqtt_ringbuf_t *rb, u16_t value)
+{
+  mqtt_ringbuf_put(rb, value >> 8);
+  mqtt_ringbuf_put(rb, value & 0xff);
+}
+
+static void
+mqtt_output_append_buf(struct mqtt_ringbuf_t *rb, const void *data, u16_t length)
+{
+  u16_t n;
+  for (n = 0; n < length; n++) {
+    mqtt_ringbuf_put(rb, ((const u8_t *)data)[n]);
+  }
+}
+
+static void
+mqtt_output_append_string(struct mqtt_ringbuf_t *rb, const char *str, u16_t length)
+{
+  u16_t n;
+  mqtt_ringbuf_put(rb, length >> 8);
+  mqtt_ringbuf_put(rb, length & 0xff);
+  for (n = 0; n < length; n++) {
+    mqtt_ringbuf_put(rb, str[n]);
+  }
+}
+
+/**
+ * Append fixed header
+ * @param rb Output ring buffer
+ * @param msg_type see enum mqtt_message_type
+ * @param dup MQTT DUP flag
+ * @param qos MQTT QoS field
+ * @param retain MQTT retain flag
+ * @param r_length Remaining length after fixed header
+ */
+
+static void
+mqtt_output_append_fixed_header(struct mqtt_ringbuf_t *rb, u8_t msg_type, u8_t dup,
+                 u8_t qos, u8_t retain, u16_t r_length)
+{
+  /* Start with control byte */
+  mqtt_output_append_u8(rb, (((msg_type & 0x0f) << 4) | ((dup & 1) << 3) | ((qos & 3) << 1) | (retain & 1)));
+  /* Encode remaining length field */
+  do {
+    mqtt_output_append_u8(rb, (r_length & 0x7f) | (r_length >= 128 ? 0x80 : 0));
+    r_length >>= 7;
+  } while (r_length > 0);
+}
+
+
+/**
+ * Check output buffer space
+ * @param rb Output ring buffer
+ * @param r_length Remaining length after fixed header
+ * @return 1 if message will fit, 0 if not enough buffer space
+ */
+static u8_t
+mqtt_output_check_space(struct mqtt_ringbuf_t *rb, u16_t r_length)
+{
+  /* Start with length of type byte + remaining length */
+  u16_t total_len = 1 + r_length;
+
+  LWIP_ASSERT("mqtt_output_check_space: rb != NULL", rb != NULL);
+
+ /* Calculate number of required bytes to contain the remaining bytes field and add to total*/
+  do {
+    total_len++;
+    r_length >>= 7;
+  } while (r_length > 0);
+
+  return (total_len <= mqtt_ringbuf_free(rb));
+}
+
+
+/**
+ * Close connection to server
+ * @param client MQTT client
+ * @param reason Reason for disconnection
+ */
+static void
+mqtt_close(mqtt_client_t *client, mqtt_connection_status_t reason)
+{
+  LWIP_ASSERT("mqtt_close: client != NULL", client != NULL);
+
+  /* Bring down TCP connection if not already done */
+  if (client->conn != NULL) {
+    err_t res;
+    tcp_recv(client->conn, NULL);
+    tcp_err(client->conn,  NULL);
+    tcp_sent(client->conn, NULL);
+    res = tcp_close(client->conn);
+    if (res != ERR_OK) {
+      tcp_abort(client->conn);
+      LWIP_DEBUGF(MQTT_DEBUG_TRACE,("mqtt_close: Close err=%s\n", lwip_strerr(res)));
+    }
+    client->conn = NULL;
+  }
+
+  /* Remove all pending requests */
+  mqtt_clear_requests(&client->pend_req_queue);
+  /* Stop cyclic timer */
+  sys_untimeout(mqtt_cyclic_timer, client);
+
+  /* Notify upper layer of disconnection if changed state */
+  if (client->conn_state != TCP_DISCONNECTED) {
+
+    client->conn_state = TCP_DISCONNECTED;
+    if (client->connect_cb != NULL) {
+      client->connect_cb(client, client->connect_arg, reason);
+    }
+  }
+}
+
+
+/**
+ * Interval timer, called every MQTT_CYCLIC_TIMER_INTERVAL seconds in MQTT_CONNECTING and MQTT_CONNECTED states
+ * @param arg MQTT client
+ */
+static void
+mqtt_cyclic_timer(void *arg)
+{
+  u8_t restart_timer = 1;
+  mqtt_client_t *client = (mqtt_client_t *)arg;
+  LWIP_ASSERT("mqtt_cyclic_timer: client != NULL", client != NULL);
+
+  if (client->conn_state == MQTT_CONNECTING) {
+    client->cyclic_tick++;
+    if ((client->cyclic_tick * MQTT_CYCLIC_TIMER_INTERVAL) >= MQTT_CONNECT_TIMOUT) {
+      LWIP_DEBUGF(MQTT_DEBUG_TRACE,("mqtt_cyclic_timer: CONNECT attempt to server timed out\n"));
+      /* Disconnect TCP */
+      mqtt_close(client, MQTT_CONNECT_TIMEOUT);
+      restart_timer = 0;
+    }
+  } else if (client->conn_state == MQTT_CONNECTED) {
+    /* Handle timeout for pending requests */
+    mqtt_request_time_elapsed(&client->pend_req_queue, MQTT_CYCLIC_TIMER_INTERVAL);
+
+    /* keep_alive > 0 means keep alive functionality shall be used */
+    if (client->keep_alive > 0) {
+
+      client->server_watchdog++;
+      /* If reception from server has been idle for 1.5*keep_alive time, server is considered unresponsive */
+      if ((client->server_watchdog * MQTT_CYCLIC_TIMER_INTERVAL) > (client->keep_alive + client->keep_alive/2)) {
+        LWIP_DEBUGF(MQTT_DEBUG_WARN,("mqtt_cyclic_timer: Server incoming keep-alive timeout\n"));
+        mqtt_close(client, MQTT_CONNECT_TIMEOUT);
+        restart_timer = 0;
+      }
+
+      /* If time for a keep alive message to be sent, transmission has been idle for keep_alive time */
+      if ((client->cyclic_tick * MQTT_CYCLIC_TIMER_INTERVAL) >= client->keep_alive) {
+        LWIP_DEBUGF(MQTT_DEBUG_TRACE,("mqtt_cyclic_timer: Sending keep-alive message to server\n"));
+        if (mqtt_output_check_space(&client->output, 0) != 0) {
+          mqtt_output_append_fixed_header(&client->output, MQTT_MSG_TYPE_PINGREQ, 0, 0, 0, 0);
+          client->cyclic_tick = 0;
+        }
+      } else {
+        client->cyclic_tick++;
+      }
+    }
+  } else {
+    LWIP_DEBUGF(MQTT_DEBUG_WARN,("mqtt_cyclic_timer: Timer should not be running in state %d\n", client->conn_state));
+    restart_timer = 0;
+  }
+  if (restart_timer) {
+    sys_timeout(MQTT_CYCLIC_TIMER_INTERVAL*1000, mqtt_cyclic_timer, arg);
+  }
+}
+
+
+/**
+ * Send PUBACK, PUBREC or PUBREL response message
+ * @param client MQTT client
+ * @param msg PUBACK, PUBREC or PUBREL
+ * @param pkt_id Packet identifier
+ * @param qos QoS value
+ * @return ERR_OK if successful, ERR_MEM if out of memory
+ */
+static err_t
+pub_ack_rec_rel_response(mqtt_client_t *client, u8_t msg, u16_t pkt_id, u8_t qos)
+{
+  err_t err = ERR_OK;
+  if (mqtt_output_check_space(&client->output, 2)) {
+    mqtt_output_append_fixed_header(&client->output, msg, 0, qos, 0, 2);
+    mqtt_output_append_u16(&client->output, pkt_id);
+    mqtt_output_send(&client->output, client->conn);
+  } else {
+    LWIP_DEBUGF(MQTT_DEBUG_TRACE,("pub_ack_rec_rel_response: OOM creating response: %s with pkt_id: %d\n",
+                                  mqtt_msg_type_to_str(msg), pkt_id));
+    err = ERR_MEM;
+  }
+  return err;
+}
+
+/**
+ * Subscribe response from server
+ * @param r Matching request
+ * @param result Result code from server
+ */
+static void
+mqtt_incomming_suback(struct mqtt_request_t *r, u8_t result)
+{
+  if (r->cb != NULL) {
+    r->cb(r->arg, result < 3 ? ERR_OK : ERR_ABRT);
+  }
+}
+
+
+/**
+ * Complete MQTT message received or buffer full
+ * @param client MQTT client
+ * @param fixed_hdr_idx header index
+ * @param length length received part
+ * @param remaining_length Remaining length of complete message
+ */
+static mqtt_connection_status_t
+  mqtt_message_received(mqtt_client_t *client, u8_t fixed_hdr_idx, u16_t length, u32_t remaining_length)
+{
+  mqtt_connection_status_t res = MQTT_CONNECT_ACCEPTED;
+
+  u8_t *var_hdr_payload = client->rx_buffer + fixed_hdr_idx;
+
+  /* Control packet type */
+  u8_t pkt_type = MQTT_CTL_PACKET_TYPE(client->rx_buffer[0]);
+  u16_t pkt_id = 0;
+
+  if (pkt_type == MQTT_MSG_TYPE_CONNACK) {
+    if (client->conn_state == MQTT_CONNECTING) {
+      /* Get result code from CONNACK */
+      res = (mqtt_connection_status_t)var_hdr_payload[1];
+      LWIP_DEBUGF(MQTT_DEBUG_TRACE,("mqtt_message_received: Connect response code %d\n", res));
+      if (res == MQTT_CONNECT_ACCEPTED) {
+        /* Reset cyclic_tick when changing to connected state */
+        client->cyclic_tick = 0;
+        client->conn_state = MQTT_CONNECTED;
+        /* Notify upper layer */
+        if (client->connect_cb != 0) {
+          client->connect_cb(client, client->connect_arg, res);
+        }
+      }
+    } else {
+      LWIP_DEBUGF(MQTT_DEBUG_WARN,("mqtt_message_received: Received CONNACK in connected state\n"));
+    }
+  } else if (pkt_type == MQTT_MSG_TYPE_PINGRESP) {
+    LWIP_DEBUGF(MQTT_DEBUG_TRACE,( "mqtt_message_received: Received PINGRESP from server\n"));
+
+  } else if (pkt_type == MQTT_MSG_TYPE_PUBLISH) {
+    u16_t payload_offset = 0;
+    u16_t payload_length = length;
+    u8_t qos = MQTT_CTL_PACKET_QOS(client->rx_buffer[0]);
+
+    if (client->msg_idx <= MQTT_VAR_HEADER_BUFFER_LEN) {
+      /* Should have topic and pkt id*/
+      uint8_t *topic;
+      uint16_t after_topic;
+      u8_t bkp;
+      u16_t topic_len = var_hdr_payload[0];
+      topic_len = (topic_len << 8) + (u16_t)(var_hdr_payload[1]);
+
+      topic = var_hdr_payload + 2;
+      after_topic = 2 + topic_len;
+      /* Check length, add one byte even for QoS 0 so that zero termination will fit */
+      if ((after_topic + (qos? 2 : 1)) > length) {
+        LWIP_DEBUGF(MQTT_DEBUG_WARN,("mqtt_message_received: Receive buffer can not fit topic + pkt_id\n"));
+        goto out_disconnect;
+      }
+
+      /* id for QoS 1 and 2 */
+      if (qos > 0) {
+        client->inpub_pkt_id = ((u16_t)var_hdr_payload[after_topic] << 8) + (u16_t)var_hdr_payload[after_topic + 1];
+        after_topic += 2;
+      } else {
+        client->inpub_pkt_id = 0;
+      }
+      /* Take backup of byte after topic */
+      bkp = topic[topic_len];
+      /* Zero terminate string */
+      topic[topic_len] = 0;
+      /* Payload data remaining in receive buffer */
+      payload_length = length - after_topic;
+      payload_offset = after_topic;
+
+      LWIP_DEBUGF(MQTT_DEBUG_TRACE,("mqtt_incomming_publish: Received message with QoS %d at topic: %s, payload length %d\n",
+                                    qos, topic, remaining_length + payload_length));
+      if (client->pub_cb != NULL) {
+        client->pub_cb(client->inpub_arg, (const char *)topic, remaining_length + payload_length);
+      }
+      /* Restore byte after topic */
+      topic[topic_len] = bkp;
+    }
+    if (payload_length > 0 || remaining_length == 0) {
+      client->data_cb(client->inpub_arg, var_hdr_payload + payload_offset, payload_length, remaining_length == 0 ? MQTT_DATA_FLAG_LAST : 0);
+      /* Reply if QoS > 0 */
+      if (remaining_length == 0 && qos > 0) {
+        /* Send PUBACK for QoS 1 or PUBREC for QoS 2 */
+        u8_t resp_msg = (qos == 1) ? MQTT_MSG_TYPE_PUBACK : MQTT_MSG_TYPE_PUBREC;
+        LWIP_DEBUGF(MQTT_DEBUG_TRACE,("mqtt_incomming_publish: Sending publish response: %s with pkt_id: %d\n",
+                                      mqtt_msg_type_to_str(resp_msg), client->inpub_pkt_id));
+        pub_ack_rec_rel_response(client, resp_msg, client->inpub_pkt_id, 0);
+      }
+    }
+  } else {
+    /* Get packet identifier */
+    pkt_id = (u16_t)var_hdr_payload[0] << 8;
+    pkt_id |= (u16_t)var_hdr_payload[1];
+    if (pkt_id == 0) {
+      LWIP_DEBUGF(MQTT_DEBUG_WARN,("mqtt_message_received: Got message with illegal packet identifier: 0\n"));
+      goto out_disconnect;
+    }
+    if (pkt_type == MQTT_MSG_TYPE_PUBREC) {
+      LWIP_DEBUGF(MQTT_DEBUG_TRACE,("mqtt_message_received: PUBREC, sending PUBREL with pkt_id: %d\n",pkt_id));
+      pub_ack_rec_rel_response(client, MQTT_MSG_TYPE_PUBREL, pkt_id, 1);
+
+    } else if (pkt_type == MQTT_MSG_TYPE_PUBREL) {
+      LWIP_DEBUGF(MQTT_DEBUG_TRACE,("mqtt_message_received: PUBREL, sending PUBCOMP response with pkt_id: %d\n",pkt_id));
+      pub_ack_rec_rel_response(client, MQTT_MSG_TYPE_PUBCOMP, pkt_id, 0);
+
+    } else if (pkt_type == MQTT_MSG_TYPE_SUBACK || pkt_type == MQTT_MSG_TYPE_UNSUBACK ||
+              pkt_type == MQTT_MSG_TYPE_PUBCOMP || pkt_type == MQTT_MSG_TYPE_PUBACK) {
+      struct mqtt_request_t *r = mqtt_take_request(&client->pend_req_queue, pkt_id);
+      if (r != NULL) {
+        LWIP_DEBUGF(MQTT_DEBUG_TRACE,("mqtt_message_received: %s response with id %d\n", mqtt_msg_type_to_str(pkt_type), pkt_id));
+        if (pkt_type == MQTT_MSG_TYPE_SUBACK) {
+          if (length < 3) {
+            LWIP_DEBUGF(MQTT_DEBUG_WARN,("mqtt_message_received: To small SUBACK packet\n"));
+            goto out_disconnect;
+          } else {
+            mqtt_incomming_suback(r, var_hdr_payload[2]);
+          }
+        } else if (r->cb != NULL) {
+          r->cb(r->arg, ERR_OK);
+        }
+        mqtt_delete_request(r);
+      } else {
+        LWIP_DEBUGF(MQTT_DEBUG_WARN,( "mqtt_message_received: Received %s reply, with wrong pkt_id: %d\n", mqtt_msg_type_to_str(pkt_type), pkt_id));
+      }
+    } else {
+      LWIP_DEBUGF(MQTT_DEBUG_WARN,( "mqtt_message_received: Received unknown message type: %d\n", pkt_type));
+      goto out_disconnect;
+    }
+  }
+  return res;
+out_disconnect:
+  return MQTT_CONNECT_DISCONNECTED;
+}
+
+
+/**
+ * MQTT incoming message parser
+ * @param client MQTT client
+ * @param p PBUF chain of received data
+ * @return Connection status
+ */
+static mqtt_connection_status_t
+mqtt_parse_incoming(mqtt_client_t *client, struct pbuf *p)
+{
+  u16_t in_offset = 0;
+  u32_t msg_rem_len = 0;
+  u8_t fixed_hdr_idx = 0;
+  u8_t b = 0;
+
+  while (p->tot_len > in_offset) {
+    if ((fixed_hdr_idx < 2) || ((b & 0x80) != 0)) {
+
+      if (fixed_hdr_idx < client->msg_idx) {
+        b = client->rx_buffer[fixed_hdr_idx];
+      } else {
+        b = pbuf_get_at(p, in_offset++);
+        client->rx_buffer[client->msg_idx++] = b;
+      }
+      fixed_hdr_idx++;
+
+      if (fixed_hdr_idx >= 2) {
+        msg_rem_len |= (u32_t)(b & 0x7f) << ((fixed_hdr_idx - 2) * 7);
+        if ((b & 0x80) == 0) {
+          LWIP_DEBUGF(MQTT_DEBUG_TRACE,("mqtt_parse_incoming: Remaining length after fixed header: %d\n", msg_rem_len));
+          if (msg_rem_len == 0) {
+            /* Complete message with no extra headers of payload received */
+            mqtt_message_received(client, fixed_hdr_idx, 0, 0);
+            client->msg_idx = 0;
+            fixed_hdr_idx = 0;
+          } else {
+            /* Bytes remaining in message */
+            msg_rem_len = (msg_rem_len + fixed_hdr_idx) - client->msg_idx;
+          }
+        }
+      }
+    } else {
+      u16_t cpy_len, cpy_start, buffer_space;
+
+      cpy_start = (client->msg_idx - fixed_hdr_idx) % (MQTT_VAR_HEADER_BUFFER_LEN - fixed_hdr_idx) + fixed_hdr_idx;
+
+      /* Allow to copy the lesser one of available length in input data or bytes remaining in message */
+      cpy_len = (u16_t)LWIP_MIN((u16_t)(p->tot_len - in_offset), msg_rem_len);
+
+      /* Limit to available space in buffer */
+      buffer_space = MQTT_VAR_HEADER_BUFFER_LEN - cpy_start;
+      if (cpy_len > buffer_space) {
+        cpy_len = buffer_space;
+      }
+      pbuf_copy_partial(p, client->rx_buffer+cpy_start, cpy_len, in_offset);
+
+      /* Advance get and put indexes  */
+      client->msg_idx += cpy_len;
+      in_offset += cpy_len;
+      msg_rem_len -= cpy_len;
+
+      LWIP_DEBUGF(MQTT_DEBUG_TRACE,("mqtt_parse_incoming: msg_idx: %d, cpy_len: %d, remaining %d\n", client->msg_idx, cpy_len, msg_rem_len));
+      if (msg_rem_len == 0 || cpy_len == buffer_space) {
+        /* Whole message received or buffer is full */
+        mqtt_connection_status_t res = mqtt_message_received(client, fixed_hdr_idx, (cpy_start + cpy_len) - fixed_hdr_idx, msg_rem_len);
+        if (res != MQTT_CONNECT_ACCEPTED) {
+          return res;
+        }
+        if (msg_rem_len == 0) {
+          /* Reset parser state */
+          client->msg_idx = 0;
+          /* msg_tot_len = 0; */
+          fixed_hdr_idx = 0;
+        }
+      }
+    }
+  }
+  return MQTT_CONNECT_ACCEPTED;
+}
+
+
+/**
+ * TCP received callback function. @see tcp_recv_fn
+ * @param arg MQTT client
+ * @param p PBUF chain of received data
+ * @param err Passed as return value if not ERR_OK
+ * @return ERR_OK or err passed into callback
+ */
+static err_t
+mqtt_tcp_recv_cb(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
+{
+  mqtt_client_t *client = (mqtt_client_t *)arg;
+  LWIP_ASSERT("mqtt_tcp_recv_cb: client != NULL", client != NULL);
+  LWIP_ASSERT("mqtt_tcp_recv_cb: client->conn == pcb", client->conn == pcb);
+
+  if (p == NULL) {
+    LWIP_DEBUGF(MQTT_DEBUG_TRACE,("mqtt_tcp_recv_cb: Recv pbuf=NULL, remote has closed connection\n"));
+    mqtt_close(client, MQTT_CONNECT_DISCONNECTED);
+  } else {
+    mqtt_connection_status_t res;
+    if (err != ERR_OK) {
+      LWIP_DEBUGF(MQTT_DEBUG_WARN,("mqtt_tcp_recv_cb: Recv err=%d\n", err));
+      pbuf_free(p);
+      return err;
+    }
+
+    /* Tell remote that data has been received */
+    tcp_recved(pcb, p->tot_len);
+    res = mqtt_parse_incoming(client, p);
+    pbuf_free(p);
+
+    if (res != MQTT_CONNECT_ACCEPTED) {
+      mqtt_close(client, res);
+    }
+    /* If keep alive functionality is used */
+    if (client->keep_alive != 0) {
+      /* Reset server alive watchdog */
+      client->server_watchdog = 0;
+    }
+
+  }
+  return ERR_OK;
+}
+
+
+/**
+ * TCP data sent callback function. @see tcp_sent_fn
+ * @param arg MQTT client
+ * @param tpcb TCP connection handle
+ * @param len Number of bytes sent
+ * @return ERR_OK
+ */
+static err_t
+mqtt_tcp_sent_cb(void *arg, struct tcp_pcb *tpcb, u16_t len)
+{
+  mqtt_client_t *client = (mqtt_client_t *)arg;
+
+  LWIP_UNUSED_ARG(tpcb);
+  LWIP_UNUSED_ARG(len);
+
+  if (client->conn_state == MQTT_CONNECTED) {
+    struct mqtt_request_t *r;
+
+    /* Reset keep-alive send timer and server watchdog */
+    client->cyclic_tick = 0;
+    client->server_watchdog = 0;
+    /* QoS 0 publish has no response from server, so call its callbacks here */
+    while ((r = mqtt_take_request(&client->pend_req_queue, 0)) != NULL) {
+      LWIP_DEBUGF(MQTT_DEBUG_TRACE,("mqtt_tcp_sent_cb: Calling QoS 0 publish complete callback\n"));
+      if (r->cb != NULL) {
+        r->cb(r->arg, ERR_OK);
+      }
+      mqtt_delete_request(r);
+    }
+    /* Try send any remaining buffers from output queue */
+    mqtt_output_send(&client->output, client->conn);
+  }
+  return ERR_OK;
+}
+
+/**
+ * TCP error callback function. @see tcp_err_fn
+ * @param arg MQTT client
+ * @param err Error encountered
+ */
+static void
+mqtt_tcp_err_cb(void *arg, err_t err)
+{
+  mqtt_client_t *client = (mqtt_client_t *)arg;
+  LWIP_UNUSED_ARG(err); /* only used for debug output */
+  LWIP_DEBUGF(MQTT_DEBUG_TRACE,("mqtt_tcp_err_cb: TCP error callback: error %d, arg: %p\n", err, arg));
+  LWIP_ASSERT("mqtt_tcp_err_cb: client != NULL", client != NULL);
+  /* Set conn to null before calling close as pcb is already deallocated*/
+  client->conn = 0;
+  mqtt_close(client, MQTT_CONNECT_DISCONNECTED);
+}
+
+/**
+ * TCP poll callback function. @see tcp_poll_fn
+ * @param arg MQTT client
+ * @param tpcb TCP connection handle
+ * @return err ERR_OK
+ */
+static err_t
+mqtt_tcp_poll_cb(void *arg, struct tcp_pcb *tpcb)
+{
+  mqtt_client_t *client = (mqtt_client_t *)arg;
+  if (client->conn_state == MQTT_CONNECTED) {
+    /* Try send any remaining buffers from output queue */
+    mqtt_output_send(&client->output, tpcb);
+  }
+  return ERR_OK;
+}
+
+/**
+ * TCP connect callback function. @see tcp_connected_fn
+ * @param arg MQTT client
+ * @param err Always ERR_OK, mqtt_tcp_err_cb is called in case of error
+ * @return ERR_OK
+ */
+static err_t
+mqtt_tcp_connect_cb(void *arg, struct tcp_pcb *tpcb, err_t err)
+{
+  mqtt_client_t* client = (mqtt_client_t *)arg;
+
+  if (err != ERR_OK) {
+    LWIP_DEBUGF(MQTT_DEBUG_WARN,("mqtt_tcp_connect_cb: TCP connect error %d\n", err));
+    return err;
+  }
+
+  /* Initiate receiver state */
+  client->msg_idx = 0;
+
+  /* Setup TCP callbacks */
+  tcp_recv(tpcb, mqtt_tcp_recv_cb);
+  tcp_sent(tpcb, mqtt_tcp_sent_cb);
+  tcp_poll(tpcb, mqtt_tcp_poll_cb, 2);
+
+  LWIP_DEBUGF(MQTT_DEBUG_TRACE,("mqtt_tcp_connect_cb: TCP connection established to server\n"));
+  /* Enter MQTT connect state */
+  client->conn_state = MQTT_CONNECTING;
+
+  /* Start cyclic timer */
+  sys_timeout(MQTT_CYCLIC_TIMER_INTERVAL*1000, mqtt_cyclic_timer, client);
+  client->cyclic_tick = 0;
+
+  /* Start transmission from output queue, connect message is the first one out*/
+  mqtt_output_send(&client->output, client->conn);
+
+  return ERR_OK;
+}
+
+
+
+/*---------------------------------------------------------------------------------------------------- */
+/* Public API */
+
+
+/**
+ * @ingroup mqtt
+ * MQTT publish function.
+ * @param client MQTT client
+ * @param topic Publish topic string
+ * @param payload Data to publish (NULL is allowed)
+ * @param payload_length: Length of payload (0 is allowed)
+ * @param qos Quality of service, 0 1 or 2
+ * @param retain MQTT retain flag
+ * @param cb Callback to call when publish is complete or has timed out
+ * @param arg User supplied argument to publish callback
+ * @return ERR_OK if successful
+ *         ERR_CONN if client is disconnected
+ *         ERR_MEM if short on memory
+ */
+err_t
+mqtt_publish(mqtt_client_t *client, const char *topic, const void *payload, u16_t payload_length, u8_t qos, u8_t retain,
+             mqtt_request_cb_t cb, void *arg)
+{
+  struct mqtt_request_t *r;
+  u16_t pkt_id;
+  size_t topic_strlen;
+  size_t total_len;
+  u16_t topic_len;
+  u16_t remaining_length;
+
+  LWIP_ASSERT("mqtt_publish: client != NULL", client);
+  LWIP_ASSERT("mqtt_publish: topic != NULL", topic);
+  LWIP_ERROR("mqtt_publish: TCP disconnected", (client->conn_state != TCP_DISCONNECTED), return ERR_CONN);
+
+  topic_strlen = strlen(topic);
+  LWIP_ERROR("mqtt_publish: topic length overflow", (topic_strlen <= (0xFFFF - 2)), return ERR_ARG);
+  topic_len = (u16_t)topic_strlen;
+  total_len = 2 + topic_len + payload_length;
+  LWIP_ERROR("mqtt_publish: total length overflow", (total_len <= 0xFFFF), return ERR_ARG);
+  remaining_length = (u16_t)total_len;
+
+  LWIP_DEBUGF(MQTT_DEBUG_TRACE,("mqtt_publish: Publish with payload length %d to topic \"%s\"\n", payload_length, topic));
+
+  if (qos > 0) {
+    remaining_length += 2;
+    /* Generate pkt_id id for QoS1 and 2 */
+    pkt_id = msg_generate_packet_id(client);
+  } else {
+    /* Use reserved value pkt_id 0 for QoS 0 in request handle */
+    pkt_id = 0;
+  }
+
+  r = mqtt_create_request(client->req_list, pkt_id, cb, arg);
+  if (r == NULL) {
+    return ERR_MEM;
+  }
+
+  if (mqtt_output_check_space(&client->output, remaining_length) == 0) {
+    mqtt_delete_request(r);
+    return ERR_MEM;
+  }
+  /* Append fixed header */
+  mqtt_output_append_fixed_header(&client->output, MQTT_MSG_TYPE_PUBLISH, 0, qos, retain, remaining_length);
+
+  /* Append Topic */
+  mqtt_output_append_string(&client->output, topic, topic_len);
+
+  /* Append packet if for QoS 1 and 2*/
+  if (qos > 0) {
+    mqtt_output_append_u16(&client->output, pkt_id);
+  }
+
+  /* Append optional publish payload */
+  if ((payload != NULL) && (payload_length > 0)) {
+    mqtt_output_append_buf(&client->output, payload, payload_length);
+  }
+
+  mqtt_append_request(&client->pend_req_queue, r);
+  mqtt_output_send(&client->output, client->conn);
+  return ERR_OK;
+}
+
+
+/**
+ * @ingroup mqtt
+ * MQTT subscribe/unsubscribe function.
+ * @param client MQTT client
+ * @param topic topic to subscribe to
+ * @param qos Quality of service, 0 1 or 2 (only used for subscribe)
+ * @param cb Callback to call when subscribe/unsubscribe reponse is received
+ * @param arg User supplied argument to publish callback
+ * @param sub 1 for subscribe, 0 for unsubscribe
+ * @return ERR_OK if successful, @see err_t enum for other results
+ */
+err_t
+mqtt_sub_unsub(mqtt_client_t *client, const char *topic, u8_t qos, mqtt_request_cb_t cb, void *arg, u8_t sub)
+{
+  size_t topic_strlen;
+  size_t total_len;
+  u16_t topic_len;
+  u16_t remaining_length;
+  u16_t pkt_id;
+  struct mqtt_request_t *r;
+
+  LWIP_ASSERT("mqtt_sub_unsub: client != NULL", client);
+  LWIP_ASSERT("mqtt_sub_unsub: topic != NULL", topic);
+
+  topic_strlen = strlen(topic);
+  LWIP_ERROR("mqtt_sub_unsub: topic length overflow", (topic_strlen <= (0xFFFF - 2)), return ERR_ARG);
+  topic_len = (u16_t)topic_strlen;
+  /* Topic string, pkt_id, qos for subscribe */
+  total_len =  topic_len + 2 + 2 + (sub != 0);
+  LWIP_ERROR("mqtt_sub_unsub: total length overflow", (total_len <= 0xFFFF), return ERR_ARG);
+  remaining_length = (u16_t)total_len;
+
+  LWIP_ASSERT("mqtt_sub_unsub: qos < 3", qos < 3);
+  if (client->conn_state == TCP_DISCONNECTED) {
+    LWIP_DEBUGF(MQTT_DEBUG_WARN,("mqtt_sub_unsub: Can not (un)subscribe in disconnected state\n"));
+    return ERR_CONN;
+  }
+
+  pkt_id = msg_generate_packet_id(client);
+  r = mqtt_create_request(client->req_list, pkt_id, cb, arg);
+  if (r == NULL) {
+    return ERR_MEM;
+  }
+
+  if (mqtt_output_check_space(&client->output, remaining_length) == 0) {
+    mqtt_delete_request(r);
+    return ERR_MEM;
+  }
+
+  LWIP_DEBUGF(MQTT_DEBUG_TRACE,("mqtt_sub_unsub: Client (un)subscribe to topic \"%s\", id: %d\n", topic, pkt_id));
+
+  mqtt_output_append_fixed_header(&client->output, sub ? MQTT_MSG_TYPE_SUBSCRIBE : MQTT_MSG_TYPE_UNSUBSCRIBE, 0, 1, 0, remaining_length);
+  /* Packet id */
+  mqtt_output_append_u16(&client->output, pkt_id);
+  /* Topic */
+  mqtt_output_append_string(&client->output, topic, topic_len);
+  /* QoS */
+  if (sub != 0) {
+    mqtt_output_append_u8(&client->output, LWIP_MIN(qos, 2));
+  }
+
+  mqtt_append_request(&client->pend_req_queue, r);
+  mqtt_output_send(&client->output, client->conn);
+  return ERR_OK;
+}
+
+
+/**
+ * @ingroup mqtt
+ * Set callback to handle incoming publish requests from server
+ * @param client MQTT client
+ * @param pub_cb Callback invoked when publish starts, contain topic and total length of payload
+ * @param data_cb Callback for each fragment of payload that arrives
+ * @param arg User supplied argument to both callbacks
+ */
+void
+mqtt_set_inpub_callback(mqtt_client_t *client, mqtt_incoming_publish_cb_t pub_cb,
+                             mqtt_incoming_data_cb_t data_cb, void *arg)
+{
+  LWIP_ASSERT("mqtt_set_inpub_callback: client != NULL", client != NULL);
+  client->data_cb = data_cb;
+  client->pub_cb = pub_cb;
+  client->inpub_arg = arg;
+}
+
+/**
+ * @ingroup mqtt
+ * Create a new MQTT client instance
+ * @return Pointer to instance on success, NULL otherwise
+ */
+mqtt_client_t *
+mqtt_client_new(void)
+{
+  mqtt_client_t *client = (mqtt_client_t *)mem_malloc(sizeof(mqtt_client_t));
+  if (client != NULL) {
+    memset(client, 0, sizeof(mqtt_client_t));
+  }
+  return client;
+}
+
+
+/**
+ * @ingroup mqtt
+ * Connect to MQTT server
+ * @param client MQTT client
+ * @param ip_addr Server IP
+ * @param port Server port
+ * @param cb Connection state change callback
+ * @param arg User supplied argument to connection callback
+ * @param client_info Client identification and connection options
+ * @return ERR_OK if successful, @see err_t enum for other results
+ */
+err_t
+mqtt_client_connect(mqtt_client_t *client, const ip_addr_t *ip_addr, u16_t port, mqtt_connection_cb_t cb, void *arg,
+                    const struct mqtt_connect_client_info_t *client_info)
+{
+  err_t err;
+  size_t len;
+  u16_t client_id_length;
+  /* Length is the sum of 2+"MQTT", protocol level, flags and keep alive */
+  u16_t remaining_length = 2 + 4 + 1 + 1 + 2;
+  u8_t flags = 0, will_topic_len = 0, will_msg_len = 0;
+
+  LWIP_ASSERT("mqtt_client_connect: client != NULL", client != NULL);
+  LWIP_ASSERT("mqtt_client_connect: ip_addr != NULL", ip_addr != NULL);
+  LWIP_ASSERT("mqtt_client_connect: client_info != NULL", client_info != NULL);
+  LWIP_ASSERT("mqtt_client_connect: client_info->client_id != NULL", client_info->client_id != NULL);
+
+  if (client->conn_state != TCP_DISCONNECTED) {
+    LWIP_DEBUGF(MQTT_DEBUG_WARN,("mqtt_client_connect: Already connected\n"));
+    return ERR_ISCONN;
+  }
+
+  /* Wipe clean */
+  memset(client, 0, sizeof(mqtt_client_t));
+  client->connect_arg = arg;
+  client->connect_cb = cb;
+  client->keep_alive = client_info->keep_alive;
+  mqtt_init_requests(client->req_list);
+
+  /* Build connect message */
+  if (client_info->will_topic != NULL && client_info->will_msg != NULL) {
+    flags |= MQTT_CONNECT_FLAG_WILL;
+    flags |= (client_info->will_qos & 3) << 3;
+    if (client_info->will_retain) {
+      flags |= MQTT_CONNECT_FLAG_WILL_RETAIN;
+    }
+    len = strlen(client_info->will_topic);
+    LWIP_ERROR("mqtt_client_connect: client_info->will_topic length overflow", len <= 0xFF, return ERR_VAL);
+    LWIP_ERROR("mqtt_client_connect: client_info->will_topic length must be > 0", len > 0, return ERR_VAL);
+    will_topic_len = (u8_t)len;
+    len = strlen(client_info->will_msg);
+    LWIP_ERROR("mqtt_client_connect: client_info->will_msg length overflow", len <= 0xFF, return ERR_VAL);
+    will_msg_len = (u8_t)len;
+    len = remaining_length + 2 + will_topic_len + 2 + will_msg_len;
+    LWIP_ERROR("mqtt_client_connect: remaining_length overflow", len <= 0xFFFF, return ERR_VAL);
+    remaining_length = (u16_t)len;
+  }
+
+  /* Don't complicate things, always connect using clean session */
+  flags |= MQTT_CONNECT_FLAG_CLEAN_SESSION;
+
+  len = strlen(client_info->client_id);
+  LWIP_ERROR("mqtt_client_connect: client_info->client_id length overflow", len <= 0xFFFF, return ERR_VAL);
+  client_id_length = (u16_t)len;
+  len = remaining_length + 2 + client_id_length;
+  LWIP_ERROR("mqtt_client_connect: remaining_length overflow", len <= 0xFFFF, return ERR_VAL);
+  remaining_length = (u16_t)len;
+
+  if (mqtt_output_check_space(&client->output, remaining_length) == 0) {
+    return ERR_MEM;
+  }
+
+  client->conn = tcp_new();
+  if (client->conn == NULL) {
+    return ERR_MEM;
+  }
+
+  /* Set arg pointer for callbacks */
+  tcp_arg(client->conn, client);
+  /* Any local address, pick random local port number */
+  err = tcp_bind(client->conn, IP_ADDR_ANY, 0);
+  if (err != ERR_OK) {
+    LWIP_DEBUGF(MQTT_DEBUG_WARN,("mqtt_client_connect: Error binding to local ip/port, %d\n", err));
+    goto tcp_fail;
+  }
+  LWIP_DEBUGF(MQTT_DEBUG_TRACE,("mqtt_client_connect: Connecting to host: %s at port:%"U16_F"\n", ipaddr_ntoa(ip_addr), port));
+
+  /* Connect to server */
+  err = tcp_connect(client->conn, ip_addr, port, mqtt_tcp_connect_cb);
+  if (err != ERR_OK) {
+    LWIP_DEBUGF(MQTT_DEBUG_TRACE,("mqtt_client_connect: Error connecting to remote ip/port, %d\n", err));
+    goto tcp_fail;
+  }
+  /* Set error callback */
+  tcp_err(client->conn, mqtt_tcp_err_cb);
+  client->conn_state = TCP_CONNECTING;
+
+  /* Append fixed header */
+  mqtt_output_append_fixed_header(&client->output, MQTT_MSG_TYPE_CONNECT, 0, 0, 0, remaining_length);
+  /* Append Protocol string */
+  mqtt_output_append_string(&client->output, "MQTT", 4);
+  /* Append Protocol level */
+  mqtt_output_append_u8(&client->output, 4);
+  /* Append connect flags */
+  mqtt_output_append_u8(&client->output, flags);
+  /* Append keep-alive */
+  mqtt_output_append_u16(&client->output, client_info->keep_alive);
+  /* Append client id */
+  mqtt_output_append_string(&client->output, client_info->client_id, client_id_length);
+  /* Append will message if used */
+  if ((flags & MQTT_CONNECT_FLAG_WILL) != 0) {
+    mqtt_output_append_string(&client->output, client_info->will_topic, will_topic_len);
+    mqtt_output_append_string(&client->output, client_info->will_msg, will_msg_len);
+  }
+  return ERR_OK;
+
+tcp_fail:
+  tcp_abort(client->conn);
+  client->conn = NULL;
+  return err;
+}
+
+
+/**
+ * @ingroup mqtt
+ * Disconnect from MQTT server
+ * @param client MQTT client
+ */
+void
+mqtt_disconnect(mqtt_client_t *client)
+{
+  LWIP_ASSERT("mqtt_disconnect: client != NULL", client);
+  /* If connection in not already closed */
+  if (client->conn_state != TCP_DISCONNECTED) {
+    /* Set conn_state before calling mqtt_close to prevent callback from being called */
+    client->conn_state = TCP_DISCONNECTED;
+    mqtt_close(client, (mqtt_connection_status_t)0);
+  }
+}
+
+/**
+ * @ingroup mqtt
+ * Check connection with server
+ * @param client MQTT client
+ * @return 1 if connected to server, 0 otherwise
+ */
+u8_t
+mqtt_client_is_connected(mqtt_client_t *client)
+{
+  LWIP_ASSERT("mqtt_client_is_connected: client != NULL", client);
+  return client->conn_state == MQTT_CONNECTED;
+}
+
+#endif /* LWIP_TCP && LWIP_CALLBACK_API */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/apps/netbiosns/netbiosns.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/apps/netbiosns/netbiosns.c b/net/ip/lwip_base/src/apps/netbiosns/netbiosns.c
index 1b1f952..2dfbe65 100644
--- a/net/ip/lwip_base/src/apps/netbiosns/netbiosns.c
+++ b/net/ip/lwip_base/src/apps/netbiosns/netbiosns.c
@@ -46,6 +46,7 @@
 
 #if LWIP_IPV4 && LWIP_UDP  /* don't build if not configured for use in lwipopts.h */
 
+#include "lwip/def.h"
 #include "lwip/udp.h"
 #include "lwip/netif.h"
 
@@ -270,7 +271,7 @@ netbiosns_recv(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_addr_t
         /* decode the NetBIOS name */
         netbiosns_name_decode((char*)(netbios_name_hdr->encname), netbios_name, sizeof(netbios_name));
         /* if the packet is for us */
-        if (NETBIOS_STRCMP(netbios_name, NETBIOS_LOCAL_NAME) == 0) {
+        if (lwip_strnicmp(netbios_name, NETBIOS_LOCAL_NAME, sizeof(NETBIOS_LOCAL_NAME)) == 0) {
           struct pbuf *q;
           struct netbios_resp *resp;
 
@@ -327,7 +328,7 @@ netbiosns_init(void)
   netbiosns_pcb = udp_new_ip_type(IPADDR_TYPE_ANY);
   if (netbiosns_pcb != NULL) {
     /* we have to be allowed to send broadcast packets! */
-    netbiosns_pcb->so_options |= SOF_BROADCAST;
+    ip_set_option(netbiosns_pcb, SOF_BROADCAST);
     udp_bind(netbiosns_pcb, IP_ANY_TYPE, NETBIOS_PORT);
     udp_recv(netbiosns_pcb, netbiosns_recv, netbiosns_pcb);
   }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/apps/snmp/snmp_asn1.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/apps/snmp/snmp_asn1.c b/net/ip/lwip_base/src/apps/snmp/snmp_asn1.c
index 7b41445..f35b760 100644
--- a/net/ip/lwip_base/src/apps/snmp/snmp_asn1.c
+++ b/net/ip/lwip_base/src/apps/snmp/snmp_asn1.c
@@ -288,7 +288,7 @@ snmp_asn1_enc_oid(struct snmp_pbuf_stream* pbuf_stream, const u32_t *oid, u16_t
 /**
  * Returns octet count for length.
  *
- * @param length
+ * @param length parameter length
  * @param octets_needed points to the return value
  */
 void
@@ -306,7 +306,7 @@ snmp_asn1_enc_length_cnt(u16_t length, u8_t *octets_needed)
 /**
  * Returns octet count for an u32_t.
  *
- * @param value
+ * @param value value to be encoded
  * @param octets_needed points to the return value
  *
  * @note ASN coded integers are _always_ signed. E.g. +0xFFFF is coded
@@ -332,7 +332,7 @@ snmp_asn1_enc_u32t_cnt(u32_t value, u16_t *octets_needed)
 /**
  * Returns octet count for an u64_t.
  *
- * @param value
+ * @param value value to be encoded
  * @param octets_needed points to the return value
  *
  * @note ASN coded integers are _always_ signed. E.g. +0xFFFF is coded
@@ -357,7 +357,7 @@ snmp_asn1_enc_u64t_cnt(const u32_t *value, u16_t *octets_needed)
 /**
  * Returns octet count for an s32_t.
  *
- * @param value
+ * @param value value to be encoded
  * @param octets_needed points to the return value
  *
  * @note ASN coded integers are _always_ signed.


[07/30] incubator-mynewt-core git commit: net/ip; add stub of a CLI for managing interfaces.

Posted by ad...@apache.org.
net/ip; add stub of a CLI for managing interfaces.


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/a95f14fb
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/a95f14fb
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/a95f14fb

Branch: refs/heads/master
Commit: a95f14fba512766d70fde088b437cbeff5b2a45c
Parents: c700fc7
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Fri Apr 14 12:55:02 2017 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Fri Apr 14 13:21:30 2017 -0700

----------------------------------------------------------------------
 net/ip/src/ip_init.c  |   5 ++
 net/ip/src/ip_priv.h  |   3 +
 net/ip/src/lwip_cli.c | 140 +++++++++++++++++++++++++++++++++++++++++++++
 net/ip/syscfg.yml     |  26 +++++++++
 4 files changed, 174 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/a95f14fb/net/ip/src/ip_init.c
----------------------------------------------------------------------
diff --git a/net/ip/src/ip_init.c b/net/ip/src/ip_init.c
index 7916d64..c73df02 100644
--- a/net/ip/src/ip_init.c
+++ b/net/ip/src/ip_init.c
@@ -16,6 +16,8 @@
  * specific language governing permissions and limitations
  * under the License.
  */
+#include "syscfg/syscfg.h"
+
 #include <lwip/tcpip.h>
 
 #include "ip_priv.h"
@@ -25,6 +27,9 @@ int ip_init(void)
     if (lwip_socket_init()) {
         return -1;
     }
+#if MYNEWT_VAL(LWIP_CLI)
+    lwip_cli_init();
+#endif
     tcpip_init(NULL, NULL);
     return 0;
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/a95f14fb/net/ip/src/ip_priv.h
----------------------------------------------------------------------
diff --git a/net/ip/src/ip_priv.h b/net/ip/src/ip_priv.h
index dd50c9f..5189801 100644
--- a/net/ip/src/ip_priv.h
+++ b/net/ip/src/ip_priv.h
@@ -30,6 +30,9 @@ int lwip_itf_getnext(struct mn_itf *mi);
 int lwip_itf_addr_getnext(struct mn_itf *mi, struct mn_itf_addr *mia);
 
 int lwip_socket_init(void);
+void lwip_cli_init(void);
+
+int lwip_err_to_mn_err(int rc);
 
 #ifdef __cplusplus
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/a95f14fb/net/ip/src/lwip_cli.c
----------------------------------------------------------------------
diff --git a/net/ip/src/lwip_cli.c b/net/ip/src/lwip_cli.c
new file mode 100644
index 0000000..adfa2ef
--- /dev/null
+++ b/net/ip/src/lwip_cli.c
@@ -0,0 +1,140 @@
+/*
+ * 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 <syscfg/syscfg.h>
+
+#if MYNEWT_VAL(LWIP_CLI)
+#include <string.h>
+
+#include <mn_socket/mn_socket.h>
+#include <console/console.h>
+#include <shell/shell.h>
+
+#include <lwip/tcpip.h>
+#include <lwip/dhcp.h>
+
+#include "ip_priv.h"
+
+static void
+lwip_nif_print(struct mn_itf *itf)
+{
+    int rc;
+    int flags = 0;
+    struct mn_itf_addr itf_addr;
+    char addr_str[48];
+
+    console_printf("%d: %s %x(", itf->mif_idx, itf->mif_name, itf->mif_flags);
+    if (itf->mif_flags & MN_ITF_F_UP) {
+        flags = 1;
+        console_printf("up");
+    }
+    if (itf->mif_flags & MN_ITF_F_MULTICAST) {
+        if (flags) {
+            console_printf("|");
+        }
+        flags = 1;
+        console_printf("mcast");
+    }
+    if (itf->mif_flags & MN_ITF_F_LINK) {
+        if (flags) {
+            console_printf("|");
+        }
+        flags = 1;
+        console_printf("link");
+    }
+    console_printf(")\n");
+
+    memset(&itf_addr, 0, sizeof(itf_addr));
+    while (1) {
+        rc = mn_itf_addr_getnext(itf, &itf_addr);
+        if (rc) {
+            break;
+        }
+        mn_inet_ntop(itf_addr.mifa_family, &itf_addr.mifa_addr,
+                     addr_str, sizeof(addr_str));
+        console_printf(" %s/%d\n", addr_str, itf_addr.mifa_plen);
+    }
+}
+
+int
+lwip_nif_up(const char *name)
+{
+    struct netif *nif;
+    err_t err;
+
+    nif = netif_find(name);
+    if (!nif) {
+        return MN_EINVAL;
+    }
+    if (nif->flags & NETIF_FLAG_LINK_UP) {
+        netif_set_up(nif);
+        netif_set_default(nif);
+#if LWIP_IPV6
+        nif->ip6_autoconfig_enabled = 1;
+        netif_create_ip6_linklocal_address(nif, 1);
+#endif
+        err = dhcp_start(nif);
+        return lwip_err_to_mn_err(err);
+    }
+    return 0;
+}
+
+static int
+lwip_cli(int argc, char **argv)
+{
+    int rc;
+    struct mn_itf itf;
+
+    if (argc == 1 || !strcmp(argv[1], "listif")) {
+        memset(&itf, 0, sizeof(itf));
+        while (1) {
+            rc = mn_itf_getnext(&itf);
+            if (rc) {
+                break;
+            }
+            lwip_nif_print(&itf);
+        }
+    } else if (mn_itf_get(argv[1], &itf) == 0) {
+        if (argc == 2) {
+            lwip_nif_print(&itf);
+            return 0;
+        }
+        if (!strcmp(argv[2], "up")) {
+            rc = lwip_nif_up(argv[1]);
+            console_printf("lwip_nif_up() = %d\n", rc);
+        } else if (!strcmp(argv[2], "down")) {
+        } else {
+            console_printf("unknown cmd\n");
+        }
+    } else {
+        console_printf("unknown cmd\n");
+    }
+    return 0;
+}
+
+struct shell_cmd lwip_cli_cmd = {
+    .sc_cmd = "ip",
+    .sc_cmd_func = lwip_cli
+};
+
+void
+lwip_cli_init(void)
+{
+    shell_cmd_register(&lwip_cli_cmd);
+}
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/a95f14fb/net/ip/syscfg.yml
----------------------------------------------------------------------
diff --git a/net/ip/syscfg.yml b/net/ip/syscfg.yml
new file mode 100644
index 0000000..7ad651e
--- /dev/null
+++ b/net/ip/syscfg.yml
@@ -0,0 +1,26 @@
+# 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.
+#
+
+# Package: net/ip
+
+syscfg.defs:
+    LWIP_CLI:
+        description: 'CLI for interacting with LwIP'
+        value: 1
+        restrictions:
+          - SHELL_TASK


[05/30] incubator-mynewt-core git commit: net/ip; increase the default pbuf pool, listen socket count to allow inet_def_service to operate.

Posted by ad...@apache.org.
net/ip; increase the default pbuf pool, listen socket count to
allow inet_def_service to operate.


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/66ae3dfe
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/66ae3dfe
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/66ae3dfe

Branch: refs/heads/master
Commit: 66ae3dfe4665f07c9231f65c6b52e55130dc3014
Parents: 1eaee93
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Fri Apr 14 12:50:29 2017 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Fri Apr 14 13:21:30 2017 -0700

----------------------------------------------------------------------
 net/ip/include/lwipopts.h | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/66ae3dfe/net/ip/include/lwipopts.h
----------------------------------------------------------------------
diff --git a/net/ip/include/lwipopts.h b/net/ip/include/lwipopts.h
index e409b2f..7382692 100644
--- a/net/ip/include/lwipopts.h
+++ b/net/ip/include/lwipopts.h
@@ -80,7 +80,7 @@ extern "C" {
 #define MEMP_NUM_TCP_PCB                3	/* XXX */
 /* MEMP_NUM_TCP_PCB_LISTEN: the number of listening TCP
    connections. */
-#define MEMP_NUM_TCP_PCB_LISTEN         1
+#define MEMP_NUM_TCP_PCB_LISTEN         3
 /* MEMP_NUM_TCP_SEG: the number of simultaneously queued TCP
    segments. */
 #define MEMP_NUM_TCP_SEG                (TCP_SND_QUEUELEN + 1)
@@ -101,12 +101,18 @@ extern "C" {
 /* ---------- Pbuf options ---------- */
 /* PBUF_POOL_SIZE: the number of buffers in the pbuf pool. */
 #ifndef PBUF_POOL_SIZE
-#define PBUF_POOL_SIZE                  3
+#define PBUF_POOL_SIZE                  6
 #endif
 
 /* PBUF_POOL_BUFSIZE: the size of each pbuf in the pbuf pool. */
 #define PBUF_POOL_BUFSIZE               1580
 
+/*
+ * Disable this; causes excessive stack use in device drivers calling
+ * pbuf_alloc()
+ */
+#define PBUF_POOL_FREE_OOSEQ            0
+
 /* PBUF_LINK_HLEN: the number of bytes that should be allocated for a
    link level header. */
 #define PBUF_LINK_HLEN                  16


[29/30] incubator-mynewt-core git commit: Merge branch 'ruuvi' of https://github.com/wes3/incubator-mynewt-core

Posted by ad...@apache.org.
Merge branch 'ruuvi' of https://github.com/wes3/incubator-mynewt-core

This closes #236.


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/84927494
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/84927494
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/84927494

Branch: refs/heads/master
Commit: 84927494547020e75dc1fd191666f1283a751f6f
Parents: 73c8953 f4e2b34
Author: aditihilbert <ad...@runtime.io>
Authored: Wed Apr 19 11:11:21 2017 -0700
Committer: aditihilbert <ad...@runtime.io>
Committed: Wed Apr 19 11:11:21 2017 -0700

----------------------------------------------------------------------
 hw/bsp/ruuvi_tag_revb2/boot-nrf52xxaa.ld        |  25 ++
 hw/bsp/ruuvi_tag_revb2/bsp.yml                  |  64 ++++
 hw/bsp/ruuvi_tag_revb2/include/bsp/boards.h     |  19 ++
 hw/bsp/ruuvi_tag_revb2/include/bsp/bsp.h        |  73 +++++
 hw/bsp/ruuvi_tag_revb2/include/bsp/cmsis_nvic.h |  29 ++
 hw/bsp/ruuvi_tag_revb2/nrf52dk_debug.cmd        |  22 ++
 hw/bsp/ruuvi_tag_revb2/nrf52dk_debug.sh         |  46 +++
 hw/bsp/ruuvi_tag_revb2/nrf52dk_download.cmd     |  22 ++
 hw/bsp/ruuvi_tag_revb2/nrf52dk_download.sh      |  40 +++
 hw/bsp/ruuvi_tag_revb2/nrf52dk_no_boot.ld       | 191 ++++++++++++
 hw/bsp/ruuvi_tag_revb2/nrf52xxaa.ld             |  25 ++
 hw/bsp/ruuvi_tag_revb2/pkg.yml                  |  97 ++++++
 hw/bsp/ruuvi_tag_revb2/split-nrf52dk.ld         | 208 +++++++++++++
 .../src/arch/cortex_m4/gcc_startup_nrf52.s      | 301 ++++++++++++++++++
 .../arch/cortex_m4/gcc_startup_nrf52_split.s    | 166 ++++++++++
 hw/bsp/ruuvi_tag_revb2/src/hal_bsp.c            | 303 +++++++++++++++++++
 hw/bsp/ruuvi_tag_revb2/src/sbrk.c               |  59 ++++
 hw/bsp/ruuvi_tag_revb2/syscfg.yml               |  95 ++++++
 18 files changed, 1785 insertions(+)
----------------------------------------------------------------------



[17/30] incubator-mynewt-core git commit: net/ip/lwip_base; update to LwIP to tag STABLE-2_0_2_RELEASE

Posted by ad...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/ipv4/icmp.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/ipv4/icmp.c b/net/ip/lwip_base/src/core/ipv4/icmp.c
index e60e448..5ee24ee 100644
--- a/net/ip/lwip_base/src/core/ipv4/icmp.c
+++ b/net/ip/lwip_base/src/core/ipv4/icmp.c
@@ -51,6 +51,10 @@
 
 #include <string.h>
 
+#ifdef LWIP_HOOK_FILENAME
+#include LWIP_HOOK_FILENAME
+#endif
+
 /** Small optimization: set to 0 if incoming PBUF_POOL pbuf always can be
  * used to modify and send a response packet (and to 1 if this is not the case,
  * e.g. when link header is stripped of when receiving) */
@@ -81,7 +85,7 @@ icmp_input(struct pbuf *p, struct netif *inp)
 #endif /* LWIP_DEBUG */
   struct icmp_echo_hdr *iecho;
   const struct ip_hdr *iphdr_in;
-  s16_t hlen;
+  u16_t hlen;
   const ip4_addr_t* src;
 
   ICMP_STATS_INC(icmp.recv);
@@ -148,7 +152,7 @@ icmp_input(struct pbuf *p, struct netif *inp)
     }
 #endif
 #if LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN
-    if (pbuf_header(p, (hlen + PBUF_LINK_HLEN + PBUF_LINK_ENCAPSULATION_HLEN))) {
+    if (pbuf_header(p, (s16_t)(hlen + PBUF_LINK_HLEN + PBUF_LINK_ENCAPSULATION_HLEN))) {
       /* p is not big enough to contain link headers
        * allocate a new one and copy p into it
        */
@@ -167,7 +171,7 @@ icmp_input(struct pbuf *p, struct netif *inp)
       /* copy the ip header */
       MEMCPY(r->payload, iphdr_in, hlen);
       /* switch r->payload back to icmp header (cannot fail) */
-      if (pbuf_header(r, -hlen)) {
+      if (pbuf_header(r, (s16_t)-hlen)) {
         LWIP_ASSERT("icmp_input: moving r->payload to icmp header failed\n", 0);
         pbuf_free(r);
         goto icmperr;
@@ -194,7 +198,7 @@ icmp_input(struct pbuf *p, struct netif *inp)
     /* We generate an answer by switching the dest and src ip addresses,
      * setting the icmp type to ECHO_RESPONSE and updating the checksum. */
     iecho = (struct icmp_echo_hdr *)p->payload;
-    if (pbuf_header(p, hlen)) {
+    if (pbuf_header(p, (s16_t)hlen)) {
       LWIP_DEBUGF(ICMP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("Can't move over header in packet"));
     } else {
       err_t ret;
@@ -247,7 +251,7 @@ icmp_input(struct pbuf *p, struct netif *inp)
     if (type == ICMP_DUR) {
       MIB2_STATS_INC(mib2.icmpindestunreachs);
     } else if (type == ICMP_TE) {
-      MIB2_STATS_INC(mib2.icmpindestunreachs);
+      MIB2_STATS_INC(mib2.icmpintimeexcds);
     } else if (type == ICMP_PP) {
       MIB2_STATS_INC(mib2.icmpinparmprobs);
     } else if (type == ICMP_SQ) {

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/ipv4/igmp.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/ipv4/igmp.c b/net/ip/lwip_base/src/core/ipv4/igmp.c
index f3db591..74a6c37 100644
--- a/net/ip/lwip_base/src/core/ipv4/igmp.c
+++ b/net/ip/lwip_base/src/core/ipv4/igmp.c
@@ -195,10 +195,13 @@ igmp_report_groups(struct netif *netif)
 
   LWIP_DEBUGF(IGMP_DEBUG, ("igmp_report_groups: sending IGMP reports on if %p\n", (void*)netif));
 
+  /* Skip the first group in the list, it is always the allsystems group added in igmp_start() */
+  if(group != NULL) {
+    group = group->next;
+  }
+  
   while (group != NULL) {
-    if (!(ip4_addr_cmp(&(group->group_address), &allsystems))) {
-      igmp_delaying_member(group, IGMP_JOIN_DELAYING_MEMBER_TMR);
-    }
+    igmp_delaying_member(group, IGMP_JOIN_DELAYING_MEMBER_TMR);
     group = group->next;
   }
 }
@@ -237,10 +240,11 @@ igmp_lookfor_group(struct netif *ifp, const ip4_addr_t *addr)
  * @return a struct igmp_group*,
  *         NULL on memory error.
  */
-struct igmp_group *
+static struct igmp_group *
 igmp_lookup_group(struct netif *ifp, const ip4_addr_t *addr)
 {
   struct igmp_group *group;
+  struct igmp_group *list_head = netif_igmp_data(ifp);
 
   /* Search if the group already exists */
   group = igmp_lookfor_group(ifp, addr);
@@ -248,7 +252,7 @@ igmp_lookup_group(struct netif *ifp, const ip4_addr_t *addr)
     /* Group already exists. */
     return group;
   }
-
+  
   /* Group doesn't exist yet, create a new one */
   group = (struct igmp_group *)memp_malloc(MEMP_IGMP_GROUP);
   if (group != NULL) {
@@ -257,9 +261,21 @@ igmp_lookup_group(struct netif *ifp, const ip4_addr_t *addr)
     group->group_state        = IGMP_GROUP_NON_MEMBER;
     group->last_reporter_flag = 0;
     group->use                = 0;
-    group->next               = netif_igmp_data(ifp);
 
-    netif_set_client_data(ifp, LWIP_NETIF_CLIENT_DATA_INDEX_IGMP, group);
+    /* Ensure allsystems group is always first in list */    
+    if (list_head == NULL) {
+      /* this is the first entry in linked list */
+      LWIP_ASSERT("igmp_lookup_group: first group must be allsystems",
+        (ip4_addr_cmp(addr, &allsystems) != 0));
+      group->next = NULL;
+      netif_set_client_data(ifp, LWIP_NETIF_CLIENT_DATA_INDEX_IGMP, group);
+    } else {
+      /* append _after_ first entry */
+      LWIP_ASSERT("igmp_lookup_group: all except first group must not be allsystems",
+        (ip4_addr_cmp(addr, &allsystems) == 0));
+      group->next = list_head->next;
+      list_head->next = group;
+    }
   }
 
   LWIP_DEBUGF(IGMP_DEBUG, ("igmp_lookup_group: %sallocated a new group with address ", (group?"":"impossible to ")));
@@ -279,24 +295,19 @@ static err_t
 igmp_remove_group(struct netif* netif, struct igmp_group *group)
 {
   err_t err = ERR_OK;
+  struct igmp_group *tmp_group;
 
-  /* Is it the first group? */
-  if (netif_igmp_data(netif) == group) {
-    netif_set_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_IGMP, group->next);
-  } else {
-    /* look for group further down the list */
-    struct igmp_group *tmpGroup;
-    for (tmpGroup = netif_igmp_data(netif); tmpGroup != NULL; tmpGroup = tmpGroup->next) {
-      if (tmpGroup->next == group) {
-        tmpGroup->next = group->next;
-        break;
-      }
-    }
-    /* Group not found in the global igmp_group_list */
-    if (tmpGroup == NULL) {
-      err = ERR_ARG;
+  /* Skip the first group in the list, it is always the allsystems group added in igmp_start() */
+  for (tmp_group = netif_igmp_data(netif); tmp_group != NULL; tmp_group = tmp_group->next) {
+    if (tmp_group->next == group) {
+      tmp_group->next = group->next;
+      break;
     }
   }
+  /* Group not found in the global igmp_group_list */
+  if (tmp_group == NULL) {
+    err = ERR_ARG;
+  }
 
   return err;
 }
@@ -368,11 +379,15 @@ igmp_input(struct pbuf *p, struct netif *inp, const ip4_addr_t *dest)
       }
 
       groupref = netif_igmp_data(inp);
+      
+      /* Do not send messages on the all systems group address! */
+      /* Skip the first group in the list, it is always the allsystems group added in igmp_start() */
+      if(groupref != NULL) {
+        groupref = groupref->next;
+      }
+
       while (groupref) {
-        /* Do not send messages on the all systems group address! */
-        if (!(ip4_addr_cmp(&(groupref->group_address), &allsystems))) {
-          igmp_delaying_member(groupref, igmp->igmp_maxresp);
-        }
+        igmp_delaying_member(groupref, igmp->igmp_maxresp);
         groupref = groupref->next;
       }
     } else {
@@ -658,6 +673,8 @@ igmp_timeout(struct netif *netif, struct igmp_group *group)
     ip4_addr_debug_print(IGMP_DEBUG, &(group->group_address));
     LWIP_DEBUGF(IGMP_DEBUG, (" on if %p\n", (void*)netif));
 
+    group->group_state = IGMP_GROUP_IDLE_MEMBER;
+    
     IGMP_STATS_INC(igmp.tx_report);
     igmp_send(netif, group, IGMP_V2_MEMB_REPORT);
   }
@@ -711,11 +728,9 @@ igmp_delaying_member(struct igmp_group *group, u8_t maxresp)
  * @param p the packet to send (p->payload points to the data, e.g. next
             protocol header; if dest == LWIP_IP_HDRINCL, p already includes an
             IP header and p->payload points to that IP header)
- * @param src the source IP address to send from (if src == IP_ADDR_ANY, the
+ * @param src the source IP address to send from (if src == IP4_ADDR_ANY, the
  *         IP  address of the netif used to send is used as source address)
  * @param dest the destination IP address to send the packet to
- * @param ttl the TTL value to be set in the IP header
- * @param proto the PROTOCOL to be set in the IP header
  * @param netif the netif on which to send this packet
  * @return ERR_OK if the packet was sent OK
  *         ERR_BUF if p doesn't have enough space for IP/LINK headers
@@ -743,7 +758,7 @@ igmp_send(struct netif *netif, struct igmp_group *group, u8_t type)
 {
   struct pbuf*     p    = NULL;
   struct igmp_msg* igmp = NULL;
-  ip4_addr_t   src  = *IP4_ADDR_ANY;
+  ip4_addr_t   src  = *IP4_ADDR_ANY4;
   ip4_addr_t*  dest = NULL;
 
   /* IP header + "router alert" option + IGMP header */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/ipv4/ip4.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/ipv4/ip4.c b/net/ip/lwip_base/src/core/ipv4/ip4.c
index 27747ea..4e4eb61 100644
--- a/net/ip/lwip_base/src/core/ipv4/ip4.c
+++ b/net/ip/lwip_base/src/core/ipv4/ip4.c
@@ -59,6 +59,10 @@
 
 #include <string.h>
 
+#ifdef LWIP_HOOK_FILENAME
+#include LWIP_HOOK_FILENAME
+#endif
+
 /** Set this to 0 in the rare case of wanting to call an extra function to
  * generate the IP checksum (in contrast to calculating it on-the-fly). */
 #ifndef LWIP_INLINE_IP_CHKSUM
@@ -177,7 +181,7 @@ ip4_route(const ip4_addr_t *dest)
   /* loopif is disabled, looopback traffic is passed through any netif */
   if (ip4_addr_isloopback(dest)) {
     /* don't check for link on loopback traffic */
-    if (netif_is_up(netif_default)) {
+    if (netif_default != NULL && netif_is_up(netif_default)) {
       return netif_default;
     }
     /* default netif is not up, just use any netif for loopback traffic */
@@ -222,13 +226,12 @@ ip4_route(const ip4_addr_t *dest)
  * that may not be forwarded, or whether datagrams to that destination
  * may be forwarded.
  * @param p the packet to forward
- * @param dest the destination IP address
  * @return 1: can forward 0: discard
  */
 static int
 ip4_canforward(struct pbuf *p)
 {
-  u32_t addr = htonl(ip4_addr_get_u32(ip4_current_dest_addr()));
+  u32_t addr = lwip_htonl(ip4_addr_get_u32(ip4_current_dest_addr()));
 
   if (p->flags & PBUF_FLAG_LLBCAST) {
     /* don't route link-layer broadcasts */
@@ -405,7 +408,7 @@ ip4_input(struct pbuf *p, struct netif *inp)
   /* calculate IP header length in bytes */
   iphdr_hlen *= 4;
   /* obtain ip length in bytes */
-  iphdr_len = ntohs(IPH_LEN(iphdr));
+  iphdr_len = lwip_ntohs(IPH_LEN(iphdr));
 
   /* Trim pbuf. This is especially required for packets < 60 bytes. */
   if (iphdr_len < p->tot_len) {
@@ -519,6 +522,15 @@ ip4_input(struct pbuf *p, struct netif *inp)
 #endif /* LWIP_AUTOIP */
       }
       if (first) {
+#if !LWIP_NETIF_LOOPBACK || LWIP_HAVE_LOOPIF
+        /* Packets sent to the loopback address must not be accepted on an
+         * interface that does not have the loopback address assigned to it,
+         * unless a non-loopback interface is used for loopback traffic. */
+        if (ip4_addr_isloopback(ip4_current_dest_addr())) {
+          netif = NULL;
+          break;
+        }
+#endif /* !LWIP_NETIF_LOOPBACK || LWIP_HAVE_LOOPIF */
         first = 0;
         netif = netif_list;
       } else {
@@ -545,7 +557,7 @@ ip4_input(struct pbuf *p, struct netif *inp)
     if (IPH_PROTO(iphdr) == IP_PROTO_UDP) {
       struct udp_hdr *udphdr = (struct udp_hdr *)((u8_t *)iphdr + iphdr_hlen);
       LWIP_DEBUGF(IP_DEBUG | LWIP_DBG_TRACE, ("ip4_input: UDP packet to DHCP client port %"U16_F"\n",
-        ntohs(udphdr->dest)));
+        lwip_ntohs(udphdr->dest)));
       if (IP_ACCEPT_LINK_LAYER_ADDRESSED_PORT(udphdr->dest)) {
         LWIP_DEBUGF(IP_DEBUG | LWIP_DBG_TRACE, ("ip4_input: DHCP packet accepted.\n"));
         netif = inp;
@@ -590,6 +602,7 @@ ip4_input(struct pbuf *p, struct netif *inp)
     } else
 #endif /* IP_FORWARD */
     {
+      IP_STATS_INC(ip.drop);
       MIB2_STATS_INC(mib2.ipinaddrerrors);
       MIB2_STATS_INC(mib2.ipindiscards);
     }
@@ -600,7 +613,7 @@ ip4_input(struct pbuf *p, struct netif *inp)
   if ((IPH_OFFSET(iphdr) & PP_HTONS(IP_OFFMASK | IP_MF)) != 0) {
 #if IP_REASSEMBLY /* packet fragment reassembly code present? */
     LWIP_DEBUGF(IP_DEBUG, ("IP packet is a fragment (id=0x%04"X16_F" tot_len=%"U16_F" len=%"U16_F" MF=%"U16_F" offset=%"U16_F"), calling ip4_reass()\n",
-      ntohs(IPH_ID(iphdr)), p->tot_len, ntohs(IPH_LEN(iphdr)), (u16_t)!!(IPH_OFFSET(iphdr) & PP_HTONS(IP_MF)), (u16_t)((ntohs(IPH_OFFSET(iphdr)) & IP_OFFMASK)*8)));
+      lwip_ntohs(IPH_ID(iphdr)), p->tot_len, lwip_ntohs(IPH_LEN(iphdr)), (u16_t)!!(IPH_OFFSET(iphdr) & PP_HTONS(IP_MF)), (u16_t)((lwip_ntohs(IPH_OFFSET(iphdr)) & IP_OFFMASK)*8)));
     /* reassemble the packet*/
     p = ip4_reass(p);
     /* packet not fully reassembled yet? */
@@ -611,7 +624,7 @@ ip4_input(struct pbuf *p, struct netif *inp)
 #else /* IP_REASSEMBLY == 0, no packet fragment reassembly code present */
     pbuf_free(p);
     LWIP_DEBUGF(IP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("IP packet dropped since it was fragmented (0x%"X16_F") (while IP_REASSEMBLY == 0).\n",
-      ntohs(IPH_OFFSET(iphdr))));
+      lwip_ntohs(IPH_OFFSET(iphdr))));
     IP_STATS_INC(ip.opterr);
     IP_STATS_INC(ip.drop);
     /* unsupported protocol feature */
@@ -724,7 +737,7 @@ ip4_input(struct pbuf *p, struct netif *inp)
  * @param p the packet to send (p->payload points to the data, e.g. next
             protocol header; if dest == LWIP_IP_HDRINCL, p already includes an
             IP header and p->payload points to that IP header)
- * @param src the source IP address to send from (if src == IP_ADDR_ANY, the
+ * @param src the source IP address to send from (if src == IP4_ADDR_ANY, the
  *         IP  address of the netif used to send is used as source address)
  * @param dest the destination IP address to send the packet to
  * @param ttl the TTL value to be set in the IP header
@@ -854,7 +867,7 @@ ip4_output_if_opt_src(struct pbuf *p, const ip4_addr_t *src, const ip4_addr_t *d
     IPH_TTL_SET(iphdr, ttl);
     IPH_PROTO_SET(iphdr, proto);
 #if CHECKSUM_GEN_IP_INLINE
-    chk_sum += LWIP_MAKE_U16(proto, ttl);
+    chk_sum += PP_NTOHS(proto | (ttl << 8));
 #endif /* CHECKSUM_GEN_IP_INLINE */
 
     /* dest cannot be NULL here */
@@ -867,21 +880,21 @@ ip4_output_if_opt_src(struct pbuf *p, const ip4_addr_t *src, const ip4_addr_t *d
     IPH_VHL_SET(iphdr, 4, ip_hlen / 4);
     IPH_TOS_SET(iphdr, tos);
 #if CHECKSUM_GEN_IP_INLINE
-    chk_sum += LWIP_MAKE_U16(tos, iphdr->_v_hl);
+    chk_sum += PP_NTOHS(tos | (iphdr->_v_hl << 8));
 #endif /* CHECKSUM_GEN_IP_INLINE */
-    IPH_LEN_SET(iphdr, htons(p->tot_len));
+    IPH_LEN_SET(iphdr, lwip_htons(p->tot_len));
 #if CHECKSUM_GEN_IP_INLINE
     chk_sum += iphdr->_len;
 #endif /* CHECKSUM_GEN_IP_INLINE */
     IPH_OFFSET_SET(iphdr, 0);
-    IPH_ID_SET(iphdr, htons(ip_id));
+    IPH_ID_SET(iphdr, lwip_htons(ip_id));
 #if CHECKSUM_GEN_IP_INLINE
     chk_sum += iphdr->_id;
 #endif /* CHECKSUM_GEN_IP_INLINE */
     ++ip_id;
 
     if (src == NULL) {
-      ip4_addr_copy(iphdr->src, *IP4_ADDR_ANY);
+      ip4_addr_copy(iphdr->src, *IP4_ADDR_ANY4);
     } else {
       /* src cannot be NULL here */
       ip4_addr_copy(iphdr->src, *src);
@@ -955,7 +968,7 @@ ip4_output_if_opt_src(struct pbuf *p, const ip4_addr_t *src, const ip4_addr_t *d
  * @param p the packet to send (p->payload points to the data, e.g. next
             protocol header; if dest == LWIP_IP_HDRINCL, p already includes an
             IP header and p->payload points to that IP header)
- * @param src the source IP address to send from (if src == IP_ADDR_ANY, the
+ * @param src the source IP address to send from (if src == IP4_ADDR_ANY, the
  *         IP  address of the netif used to send is used as source address)
  * @param dest the destination IP address to send the packet to
  * @param ttl the TTL value to be set in the IP header
@@ -990,7 +1003,7 @@ ip4_output(struct pbuf *p, const ip4_addr_t *src, const ip4_addr_t *dest,
  * @param p the packet to send (p->payload points to the data, e.g. next
             protocol header; if dest == LWIP_IP_HDRINCL, p already includes an
             IP header and p->payload points to that IP header)
- * @param src the source IP address to send from (if src == IP_ADDR_ANY, the
+ * @param src the source IP address to send from (if src == IP4_ADDR_ANY, the
  *         IP  address of the netif used to send is used as source address)
  * @param dest the destination IP address to send the packet to
  * @param ttl the TTL value to be set in the IP header
@@ -1041,19 +1054,19 @@ ip4_debug_print(struct pbuf *p)
                     (u16_t)IPH_V(iphdr),
                     (u16_t)IPH_HL(iphdr),
                     (u16_t)IPH_TOS(iphdr),
-                    ntohs(IPH_LEN(iphdr))));
+                    lwip_ntohs(IPH_LEN(iphdr))));
   LWIP_DEBUGF(IP_DEBUG, ("+-------------------------------+\n"));
   LWIP_DEBUGF(IP_DEBUG, ("|    %5"U16_F"      |%"U16_F"%"U16_F"%"U16_F"|    %4"U16_F"   | (id, flags, offset)\n",
-                    ntohs(IPH_ID(iphdr)),
-                    (u16_t)(ntohs(IPH_OFFSET(iphdr)) >> 15 & 1),
-                    (u16_t)(ntohs(IPH_OFFSET(iphdr)) >> 14 & 1),
-                    (u16_t)(ntohs(IPH_OFFSET(iphdr)) >> 13 & 1),
-                    (u16_t)(ntohs(IPH_OFFSET(iphdr)) & IP_OFFMASK)));
+                    lwip_ntohs(IPH_ID(iphdr)),
+                    (u16_t)(lwip_ntohs(IPH_OFFSET(iphdr)) >> 15 & 1),
+                    (u16_t)(lwip_ntohs(IPH_OFFSET(iphdr)) >> 14 & 1),
+                    (u16_t)(lwip_ntohs(IPH_OFFSET(iphdr)) >> 13 & 1),
+                    (u16_t)(lwip_ntohs(IPH_OFFSET(iphdr)) & IP_OFFMASK)));
   LWIP_DEBUGF(IP_DEBUG, ("+-------------------------------+\n"));
   LWIP_DEBUGF(IP_DEBUG, ("|  %3"U16_F"  |  %3"U16_F"  |    0x%04"X16_F"     | (ttl, proto, chksum)\n",
                     (u16_t)IPH_TTL(iphdr),
                     (u16_t)IPH_PROTO(iphdr),
-                    ntohs(IPH_CHKSUM(iphdr))));
+                    lwip_ntohs(IPH_CHKSUM(iphdr))));
   LWIP_DEBUGF(IP_DEBUG, ("+-------------------------------+\n"));
   LWIP_DEBUGF(IP_DEBUG, ("|  %3"U16_F"  |  %3"U16_F"  |  %3"U16_F"  |  %3"U16_F"  | (src)\n",
                     ip4_addr1_16(&iphdr->src),

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/ipv4/ip4_addr.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/ipv4/ip4_addr.c b/net/ip/lwip_base/src/core/ipv4/ip4_addr.c
index 7fe35c9..2d47992 100644
--- a/net/ip/lwip_base/src/core/ipv4/ip4_addr.c
+++ b/net/ip/lwip_base/src/core/ipv4/ip4_addr.c
@@ -43,7 +43,7 @@
 #include "lwip/ip_addr.h"
 #include "lwip/netif.h"
 
-/* used by IP_ADDR_ANY and IP_ADDR_BROADCAST in ip_addr.h */
+/* used by IP4_ADDR_ANY and IP_ADDR_BROADCAST in ip_addr.h */
 const ip_addr_t ip_addr_any = IPADDR4_INIT(IPADDR_ANY);
 const ip_addr_t ip_addr_broadcast = IPADDR4_INIT(IPADDR_BROADCAST);
 
@@ -183,10 +183,10 @@ ip4addr_aton(const char *cp, ip4_addr_t *addr)
     }
     for (;;) {
       if (isdigit(c)) {
-        val = (val * base) + (int)(c - '0');
+        val = (val * base) + (u32_t)(c - '0');
         c = *++cp;
       } else if (base == 16 && isxdigit(c)) {
-        val = (val << 4) | (int)(c + 10 - (islower(c) ? 'a' : 'A'));
+        val = (val << 4) | (u32_t)(c + 10 - (islower(c) ? 'a' : 'A'));
         c = *++cp;
       } else {
         break;
@@ -260,7 +260,7 @@ ip4addr_aton(const char *cp, ip4_addr_t *addr)
     break;
   }
   if (addr) {
-    ip4_addr_set_u32(addr, htonl(val));
+    ip4_addr_set_u32(addr, lwip_htonl(val));
   }
   return 1;
 }
@@ -310,7 +310,7 @@ ip4addr_ntoa_r(const ip4_addr_t *addr, char *buf, int buflen)
     do {
       rem = *ap % (u8_t)10;
       *ap /= (u8_t)10;
-      inv[i++] = '0' + rem;
+      inv[i++] = (char)('0' + rem);
     } while (*ap);
     while (i--) {
       if (len++ >= buflen) {

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/ipv4/ip4_frag.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/ipv4/ip4_frag.c b/net/ip/lwip_base/src/core/ipv4/ip4_frag.c
index 50edd12..57fb44c 100644
--- a/net/ip/lwip_base/src/core/ipv4/ip4_frag.c
+++ b/net/ip/lwip_base/src/core/ipv4/ip4_frag.c
@@ -160,7 +160,7 @@ static int
 ip_reass_free_complete_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev)
 {
   u16_t pbufs_freed = 0;
-  u8_t clen;
+  u16_t clen;
   struct pbuf *p;
   struct ip_reass_helper *iprh;
 
@@ -331,7 +331,7 @@ ip_reass_dequeue_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev)
  * will grow over time as  new pbufs are rx.
  * Also checks that the datagram passes basic continuity checks (if the last
  * fragment was received at least once).
- * @param root_p points to the 'root' pbuf for the current datagram being assembled.
+ * @param ipr points to the reassembly state
  * @param new_p points to the pbuf for the current fragment
  * @return 0 if invalid, >0 otherwise
  */
@@ -346,8 +346,8 @@ ip_reass_chain_frag_into_datagram_and_validate(struct ip_reassdata *ipr, struct
 
   /* Extract length and fragment offset from current fragment */
   fraghdr = (struct ip_hdr*)new_p->payload;
-  len = ntohs(IPH_LEN(fraghdr)) - IPH_HL(fraghdr) * 4;
-  offset = (ntohs(IPH_OFFSET(fraghdr)) & IP_OFFMASK) * 8;
+  len = lwip_ntohs(IPH_LEN(fraghdr)) - IPH_HL(fraghdr) * 4;
+  offset = (lwip_ntohs(IPH_OFFSET(fraghdr)) & IP_OFFMASK) * 8;
 
   /* overwrite the fragment's ip header from the pbuf with our helper struct,
    * and setup the embedded helper structure. */
@@ -487,8 +487,7 @@ ip4_reass(struct pbuf *p)
   struct ip_hdr *fraghdr;
   struct ip_reassdata *ipr;
   struct ip_reass_helper *iprh;
-  u16_t offset, len;
-  u8_t clen;
+  u16_t offset, len, clen;
 
   IPFRAG_STATS_INC(ip_frag.recv);
   MIB2_STATS_INC(mib2.ipreasmreqds);
@@ -501,8 +500,8 @@ ip4_reass(struct pbuf *p)
     goto nullreturn;
   }
 
-  offset = (ntohs(IPH_OFFSET(fraghdr)) & IP_OFFMASK) * 8;
-  len = ntohs(IPH_LEN(fraghdr)) - IPH_HL(fraghdr) * 4;
+  offset = (lwip_ntohs(IPH_OFFSET(fraghdr)) & IP_OFFMASK) * 8;
+  len = lwip_ntohs(IPH_LEN(fraghdr)) - IPH_HL(fraghdr) * 4;
 
   /* Check if we are allowed to enqueue more datagrams. */
   clen = pbuf_clen(p);
@@ -530,7 +529,7 @@ ip4_reass(struct pbuf *p)
        fragment into the buffer. */
     if (IP_ADDRESSES_AND_ID_MATCH(&ipr->iphdr, fraghdr)) {
       LWIP_DEBUGF(IP_REASS_DEBUG, ("ip4_reass: matching previous fragment ID=%"X16_F"\n",
-        ntohs(IPH_ID(fraghdr))));
+        lwip_ntohs(IPH_ID(fraghdr))));
       IPFRAG_STATS_INC(ip_frag.cachehit);
       break;
     }
@@ -544,8 +543,8 @@ ip4_reass(struct pbuf *p)
       goto nullreturn;
     }
   } else {
-    if (((ntohs(IPH_OFFSET(fraghdr)) & IP_OFFMASK) == 0) &&
-      ((ntohs(IPH_OFFSET(&ipr->iphdr)) & IP_OFFMASK) != 0)) {
+    if (((lwip_ntohs(IPH_OFFSET(fraghdr)) & IP_OFFMASK) == 0) &&
+      ((lwip_ntohs(IPH_OFFSET(&ipr->iphdr)) & IP_OFFMASK) != 0)) {
       /* ipr->iphdr is not the header from the first fragment, but fraghdr is
        * -> copy fraghdr into ipr->iphdr since we want to have the header
        * of the first fragment (for ICMP time exceeded and later, for copying
@@ -582,7 +581,7 @@ ip4_reass(struct pbuf *p)
     /* copy the original ip header back to the first pbuf */
     fraghdr = (struct ip_hdr*)(ipr->p->payload);
     SMEMCPY(fraghdr, &ipr->iphdr, IP_HLEN);
-    IPH_LEN_SET(fraghdr, htons(ipr->datagram_len));
+    IPH_LEN_SET(fraghdr, lwip_htons(ipr->datagram_len));
     IPH_OFFSET_SET(fraghdr, 0);
     IPH_CHKSUM_SET(fraghdr, 0);
     /* @todo: do we need to set/calculate the correct checksum? */
@@ -688,53 +687,41 @@ ip4_frag(struct pbuf *p, struct netif *netif, const ip4_addr_t *dest)
   struct pbuf *rambuf;
 #if !LWIP_NETIF_TX_SINGLE_PBUF
   struct pbuf *newpbuf;
+  u16_t newpbuflen = 0;
+  u16_t left_to_copy;
 #endif
   struct ip_hdr *original_iphdr;
   struct ip_hdr *iphdr;
-  u16_t nfb;
-  u16_t left, cop;
-  u16_t mtu = netif->mtu;
-  u16_t ofo, omf;
-  u16_t last;
+  const u16_t nfb = (netif->mtu - IP_HLEN) / 8;
+  u16_t left, fragsize;
+  u16_t ofo;
+  int last;
   u16_t poff = IP_HLEN;
   u16_t tmp;
-#if !LWIP_NETIF_TX_SINGLE_PBUF
-  u16_t newpbuflen = 0;
-  u16_t left_to_copy;
-#endif
 
   original_iphdr = (struct ip_hdr *)p->payload;
   iphdr = original_iphdr;
+  LWIP_ERROR("ip4_frag() does not support IP options", IPH_HL(iphdr) * 4 == IP_HLEN, return ERR_VAL);
 
   /* Save original offset */
-  tmp = ntohs(IPH_OFFSET(iphdr));
+  tmp = lwip_ntohs(IPH_OFFSET(iphdr));
   ofo = tmp & IP_OFFMASK;
-  omf = tmp & IP_MF;
+  LWIP_ERROR("ip_frag(): MF already set", (tmp & IP_MF) == 0, return ERR_VAL);
 
   left = p->tot_len - IP_HLEN;
 
-  nfb = (mtu - IP_HLEN) / 8;
-
   while (left) {
-    last = (left <= mtu - IP_HLEN);
-
-    /* Set new offset and MF flag */
-    tmp = omf | (IP_OFFMASK & (ofo));
-    if (!last) {
-      tmp = tmp | IP_MF;
-    }
-
     /* Fill this fragment */
-    cop = last ? left : nfb * 8;
+    fragsize = LWIP_MIN(left, nfb * 8);
 
 #if LWIP_NETIF_TX_SINGLE_PBUF
-    rambuf = pbuf_alloc(PBUF_IP, cop, PBUF_RAM);
+    rambuf = pbuf_alloc(PBUF_IP, fragsize, PBUF_RAM);
     if (rambuf == NULL) {
       goto memerr;
     }
     LWIP_ASSERT("this needs a pbuf in one piece!",
       (rambuf->len == rambuf->tot_len) && (rambuf->next == NULL));
-    poff += pbuf_copy_partial(p, rambuf->payload, cop, poff);
+    poff += pbuf_copy_partial(p, rambuf->payload, fragsize, poff);
     /* make room for the IP header */
     if (pbuf_header(rambuf, IP_HLEN)) {
       pbuf_free(rambuf);
@@ -758,16 +745,14 @@ ip4_frag(struct pbuf *p, struct netif *netif, const ip4_addr_t *dest)
     SMEMCPY(rambuf->payload, original_iphdr, IP_HLEN);
     iphdr = (struct ip_hdr *)rambuf->payload;
 
-    /* Can just adjust p directly for needed offset. */
-    p->payload = (u8_t *)p->payload + poff;
-    p->len -= poff;
-
-    left_to_copy = cop;
+    left_to_copy = fragsize;
     while (left_to_copy) {
       struct pbuf_custom_ref *pcr;
-      newpbuflen = (left_to_copy < p->len) ? left_to_copy : p->len;
+      u16_t plen = p->len - poff;
+      newpbuflen = LWIP_MIN(left_to_copy, plen);
       /* Is this pbuf already empty? */
       if (!newpbuflen) {
+        poff = 0;
         p = p->next;
         continue;
       }
@@ -777,7 +762,8 @@ ip4_frag(struct pbuf *p, struct netif *netif, const ip4_addr_t *dest)
         goto memerr;
       }
       /* Mirror this pbuf, although we might not need all of it. */
-      newpbuf = pbuf_alloced_custom(PBUF_RAW, newpbuflen, PBUF_REF, &pcr->pc, p->payload, newpbuflen);
+      newpbuf = pbuf_alloced_custom(PBUF_RAW, newpbuflen, PBUF_REF, &pcr->pc,
+        (u8_t*)p->payload + poff, newpbuflen);
       if (newpbuf == NULL) {
         ip_frag_free_pbuf_custom_ref(pcr);
         pbuf_free(rambuf);
@@ -793,15 +779,23 @@ ip4_frag(struct pbuf *p, struct netif *netif, const ip4_addr_t *dest)
       pbuf_cat(rambuf, newpbuf);
       left_to_copy -= newpbuflen;
       if (left_to_copy) {
+        poff = 0;
         p = p->next;
       }
     }
-    poff = newpbuflen;
+    poff += newpbuflen;
 #endif /* LWIP_NETIF_TX_SINGLE_PBUF */
 
     /* Correct header */
-    IPH_OFFSET_SET(iphdr, htons(tmp));
-    IPH_LEN_SET(iphdr, htons(cop + IP_HLEN));
+    last = (left <= netif->mtu - IP_HLEN);
+
+    /* Set new offset and MF flag */
+    tmp = (IP_OFFMASK & (ofo));
+    if (!last) {
+      tmp = tmp | IP_MF;
+    }
+    IPH_OFFSET_SET(iphdr, lwip_htons(tmp));
+    IPH_LEN_SET(iphdr, lwip_htons(fragsize + IP_HLEN));
     IPH_CHKSUM_SET(iphdr, 0);
 #if CHECKSUM_GEN_IP
     IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_IP) {
@@ -823,7 +817,7 @@ ip4_frag(struct pbuf *p, struct netif *netif, const ip4_addr_t *dest)
      */
 
     pbuf_free(rambuf);
-    left -= cop;
+    left -= fragsize;
     ofo += nfb;
   }
   MIB2_STATS_INC(mib2.ipfragoks);

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/ipv6/ethip6.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/ipv6/ethip6.c b/net/ip/lwip_base/src/core/ipv6/ethip6.c
index 1ae784f..8f9a91b 100644
--- a/net/ip/lwip_base/src/core/ipv6/ethip6.c
+++ b/net/ip/lwip_base/src/core/ipv6/ethip6.c
@@ -62,7 +62,9 @@
  * For IPv6 multicast, corresponding Ethernet addresses
  * are selected and the packet is transmitted on the link.
  *
- * For unicast addresses, ...
+ * For unicast addresses, ask the ND6 module what to do. It will either let us
+ * send the the packet right away, or queue the packet for later itself, unless
+ * an error occurs.
  *
  * @todo anycast addresses
  *
@@ -71,14 +73,14 @@
  * @param ip6addr The IP address of the packet destination.
  *
  * @return
- * - ERR_RTE No route to destination (no gateway to external networks),
- * or the return type of either etharp_query() or ethernet_output().
+ * - ERR_OK or the return value of @ref nd6_get_next_hop_addr_or_queue.
  */
 err_t
 ethip6_output(struct netif *netif, struct pbuf *q, const ip6_addr_t *ip6addr)
 {
   struct eth_addr dest;
-  s8_t i;
+  const u8_t *hwaddr;
+  err_t result;
 
   /* multicast destination IP address? */
   if (ip6_addr_ismulticast(ip6addr)) {
@@ -91,36 +93,26 @@ ethip6_output(struct netif *netif, struct pbuf *q, const ip6_addr_t *ip6addr)
     dest.addr[5] = ((const u8_t *)(&(ip6addr->addr[3])))[3];
 
     /* Send out. */
-    return ethernet_output(netif, q, (struct eth_addr*)(netif->hwaddr), &dest, ETHTYPE_IPV6);
+    return ethernet_output(netif, q, (const struct eth_addr*)(netif->hwaddr), &dest, ETHTYPE_IPV6);
   }
 
   /* We have a unicast destination IP address */
   /* @todo anycast? */
-  /* Get next hop record. */
-  i = nd6_get_next_hop_entry(ip6addr, netif);
-  if (i < 0) {
-    /* failed to get a next hop neighbor record. */
-    return ERR_MEM;
-  }
 
-  /* Now that we have a destination record, send or queue the packet. */
-  if (neighbor_cache[i].state == ND6_STALE) {
-    /* Switch to delay state. */
-    neighbor_cache[i].state = ND6_DELAY;
-    neighbor_cache[i].counter.delay_time = LWIP_ND6_DELAY_FIRST_PROBE_TIME;
+  /* Ask ND6 what to do with the packet. */
+  result = nd6_get_next_hop_addr_or_queue(netif, q, ip6addr, &hwaddr);
+  if (result != ERR_OK) {
+    return result;
   }
-  /* @todo should we send or queue if PROBE? send for now, to let unicast NS pass. */
-  if ((neighbor_cache[i].state == ND6_REACHABLE) ||
-      (neighbor_cache[i].state == ND6_DELAY) ||
-      (neighbor_cache[i].state == ND6_PROBE)) {
 
-    /* Send out. */
-    SMEMCPY(dest.addr, neighbor_cache[i].lladdr, 6);
-    return ethernet_output(netif, q, (struct eth_addr*)(netif->hwaddr), &dest, ETHTYPE_IPV6);
+  /* If no hardware address is returned, nd6 has queued the packet for later. */
+  if (hwaddr == NULL) {
+    return ERR_OK;
   }
 
-  /* We should queue packet on this interface. */
-  return nd6_queue_packet(i, q);
+  /* Send out the packet using the returned hardware address. */
+  SMEMCPY(dest.addr, hwaddr, 6);
+  return ethernet_output(netif, q, (const struct eth_addr*)(netif->hwaddr), &dest, ETHTYPE_IPV6);
 }
 
 #endif /* LWIP_IPV6 && LWIP_ETHERNET */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/ipv6/ip6.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/ipv6/ip6.c b/net/ip/lwip_base/src/core/ipv6/ip6.c
index 8cc9c01..f14e334 100644
--- a/net/ip/lwip_base/src/core/ipv6/ip6.c
+++ b/net/ip/lwip_base/src/core/ipv6/ip6.c
@@ -60,6 +60,10 @@
 #include "lwip/debug.h"
 #include "lwip/stats.h"
 
+#ifdef LWIP_HOOK_FILENAME
+#include LWIP_HOOK_FILENAME
+#endif
+
 /**
  * Finds the appropriate network interface for a given IPv6 address. It tries to select
  * a netif following a sequence of heuristics:
@@ -94,7 +98,8 @@ ip6_route(const ip6_addr_t *src, const ip6_addr_t *dest)
   if (ip6_addr_islinklocal(dest)) {
     if (ip6_addr_isany(src)) {
       /* Use default netif, if Up. */
-      if (!netif_is_up(netif_default) || !netif_is_link_up(netif_default)) {
+      if (netif_default == NULL || !netif_is_up(netif_default) ||
+          !netif_is_link_up(netif_default)) {
         return NULL;
       }
       return netif_default;
@@ -114,7 +119,8 @@ ip6_route(const ip6_addr_t *src, const ip6_addr_t *dest)
     }
 
     /* netif not found, use default netif, if up */
-    if (!netif_is_up(netif_default) || !netif_is_link_up(netif_default)) {
+    if (netif_default == NULL || !netif_is_up(netif_default) ||
+        !netif_is_link_up(netif_default)) {
       return NULL;
     }
     return netif_default;
@@ -142,15 +148,9 @@ ip6_route(const ip6_addr_t *src, const ip6_addr_t *dest)
   }
 
   /* Get the netif for a suitable router. */
-  i = nd6_select_router(dest, NULL);
-  if (i >= 0) {
-    if (default_router_list[i].neighbor_entry != NULL) {
-      if (default_router_list[i].neighbor_entry->netif != NULL) {
-        if (netif_is_up(default_router_list[i].neighbor_entry->netif) && netif_is_link_up(default_router_list[i].neighbor_entry->netif)) {
-          return default_router_list[i].neighbor_entry->netif;
-        }
-      }
-    }
+  netif = nd6_find_route(dest);
+  if ((netif != NULL) && netif_is_up(netif) && netif_is_link_up(netif)) {
+    return netif;
   }
 
   /* try with the netif that matches the source address. */
@@ -172,7 +172,7 @@ ip6_route(const ip6_addr_t *src, const ip6_addr_t *dest)
   /* loopif is disabled, loopback traffic is passed through any netif */
   if (ip6_addr_isloopback(dest)) {
     /* don't check for link on loopback traffic */
-    if (netif_is_up(netif_default)) {
+    if (netif_default != NULL && netif_is_up(netif_default)) {
       return netif_default;
     }
     /* default netif is not up, just use any netif for loopback traffic */
@@ -290,8 +290,9 @@ ip6_forward(struct pbuf *p, struct ip6_hdr *iphdr, struct netif *inp)
 {
   struct netif *netif;
 
-  /* do not forward link-local addresses */
-  if (ip6_addr_islinklocal(ip6_current_dest_addr())) {
+  /* do not forward link-local or loopback addresses */
+  if (ip6_addr_islinklocal(ip6_current_dest_addr()) ||
+      ip6_addr_isloopback(ip6_current_dest_addr())) {
     LWIP_DEBUGF(IP6_DEBUG, ("ip6_forward: not forwarding link-local address.\n"));
     IP6_STATS_INC(ip6.rterr);
     IP6_STATS_INC(ip6.drop);
@@ -446,9 +447,11 @@ ip6_input(struct pbuf *p, struct netif *inp)
   ip_addr_copy_from_ip6(ip_data.current_iphdr_dest, ip6hdr->dest);
   ip_addr_copy_from_ip6(ip_data.current_iphdr_src, ip6hdr->src);
 
-  /* Don't accept virtual IPv6 mapped IPv4 addresses */
-  if (ip6_addr_isipv6mappedipv4(ip_2_ip6(&ip_data.current_iphdr_dest)) ||
-     ip6_addr_isipv6mappedipv4(ip_2_ip6(&ip_data.current_iphdr_src))     ) {
+  /* Don't accept virtual IPv4 mapped IPv6 addresses.
+   * Don't accept multicast source addresses. */
+  if (ip6_addr_isipv4mappedipv6(ip_2_ip6(&ip_data.current_iphdr_dest)) ||
+     ip6_addr_isipv4mappedipv6(ip_2_ip6(&ip_data.current_iphdr_src)) ||
+     ip6_addr_ismulticast(ip_2_ip6(&ip_data.current_iphdr_src))) {
     IP6_STATS_INC(ip6.err);
     IP6_STATS_INC(ip6.drop);
     return ERR_OK;
@@ -509,12 +512,21 @@ ip6_input(struct pbuf *p, struct netif *inp)
           }
         }
       }
-      if (ip6_addr_islinklocal(ip6_current_dest_addr())) {
-        /* Do not match link-local addresses to other netifs. */
-        netif = NULL;
-        break;
-      }
       if (first) {
+        if (ip6_addr_islinklocal(ip6_current_dest_addr())
+#if !LWIP_NETIF_LOOPBACK || LWIP_HAVE_LOOPIF
+            || ip6_addr_isloopback(ip6_current_dest_addr())
+#endif /* !LWIP_NETIF_LOOPBACK || LWIP_HAVE_LOOPIF */
+        ) {
+          /* Do not match link-local addresses to other netifs. The loopback
+           * address is to be considered link-local and packets to it should be
+           * dropped on other interfaces, as per RFC 4291 Sec. 2.5.3. This
+           * requirement cannot be implemented in the case that loopback
+           * traffic is sent across a non-loopback interface, however.
+           */
+          netif = NULL;
+          break;
+        }
         first = 0;
         netif = netif_list;
       } else {
@@ -709,7 +721,7 @@ netif_found:
 options_done:
 
   /* p points to IPv6 header again. */
-  pbuf_header_force(p, ip_data.current_ip_header_tot_len);
+  pbuf_header_force(p, (s16_t)ip_data.current_ip_header_tot_len);
 
   /* send to upper layers */
   LWIP_DEBUGF(IP6_DEBUG, ("ip6_input: \n"));
@@ -809,8 +821,8 @@ ip6_output_if(struct pbuf *p, const ip6_addr_t *src, const ip6_addr_t *dest,
   const ip6_addr_t *src_used = src;
   if (dest != LWIP_IP_HDRINCL) {
     if (src != NULL && ip6_addr_isany(src)) {
-      src = ip_2_ip6(ip6_select_source_address(netif, dest));
-      if ((src == NULL) || ip6_addr_isany(src)) {
+      src_used = ip_2_ip6(ip6_select_source_address(netif, dest));
+      if ((src_used == NULL) || ip6_addr_isany(src_used)) {
         /* No appropriate source address was found for this packet. */
         LWIP_DEBUGF(IP6_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("ip6_output: No suitable source address for packet.\n"));
         IP6_STATS_INC(ip6.rterr);

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/ipv6/ip6_addr.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/ipv6/ip6_addr.c b/net/ip/lwip_base/src/core/ipv6/ip6_addr.c
index 1792f62..aa06659 100644
--- a/net/ip/lwip_base/src/core/ipv6/ip6_addr.c
+++ b/net/ip/lwip_base/src/core/ipv6/ip6_addr.c
@@ -132,8 +132,8 @@ ip6addr_aton(const char *cp, ip6_addr_t *addr)
     } else if (isxdigit(*s)) {
       /* add current digit */
       current_block_value = (current_block_value << 4) +
-          (isdigit(*s) ? *s - '0' :
-          10 + (islower(*s) ? *s - 'a' : *s - 'A'));
+          (isdigit(*s) ? (u32_t)(*s - '0') :
+          (u32_t)(10 + (islower(*s) ? *s - 'a' : *s - 'A')));
     } else {
       /* unexpected digit, space? CRLF? */
       break;
@@ -152,7 +152,7 @@ ip6addr_aton(const char *cp, ip6_addr_t *addr)
   /* convert to network byte order. */
   if (addr) {
     for (addr_index = 0; addr_index < 4; addr_index++) {
-      addr->addr[addr_index] = htonl(addr->addr[addr_index]);
+      addr->addr[addr_index] = lwip_htonl(addr->addr[addr_index]);
     }
   }
 
@@ -199,7 +199,7 @@ ip6addr_ntoa_r(const ip6_addr_t *addr, char *buf, int buflen)
 
   for (current_block_index = 0; current_block_index < 8; current_block_index++) {
     /* get the current 16-bit block */
-    current_block_value = htonl(addr->addr[current_block_index >> 1]);
+    current_block_value = lwip_htonl(addr->addr[current_block_index >> 1]);
     if ((current_block_index & 0x1) == 0) {
       current_block_value = current_block_value >> 16;
     }
@@ -218,7 +218,7 @@ ip6addr_ntoa_r(const ip6_addr_t *addr, char *buf, int buflen)
       if (empty_block_flag == 0) {
         /* generate empty block "::", but only if more than one contiguous zero block,
          * according to current formatting suggestions RFC 5952. */
-        next_block_value = htonl(addr->addr[(current_block_index + 1) >> 1]);
+        next_block_value = lwip_htonl(addr->addr[(current_block_index + 1) >> 1]);
         if ((current_block_index & 0x1) == 0x01) {
             next_block_value = next_block_value >> 16;
         }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/ipv6/ip6_frag.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/ipv6/ip6_frag.c b/net/ip/lwip_base/src/core/ipv6/ip6_frag.c
index f41d167..ff07f71 100644
--- a/net/ip/lwip_base/src/core/ipv6/ip6_frag.c
+++ b/net/ip/lwip_base/src/core/ipv6/ip6_frag.c
@@ -147,7 +147,7 @@ ip6_reass_free_complete_datagram(struct ip6_reassdata *ipr)
 {
   struct ip6_reassdata *prev;
   u16_t pbufs_freed = 0;
-  u8_t clen;
+  u16_t clen;
   struct pbuf *p;
   struct ip6_reass_helper *iprh;
 
@@ -262,7 +262,8 @@ ip6_reass(struct pbuf *p)
   struct ip6_reass_helper *iprh, *iprh_tmp, *iprh_prev=NULL;
   struct ip6_frag_hdr *frag_hdr;
   u16_t offset, len;
-  u8_t clen, valid = 1;
+  u16_t clen;
+  u8_t valid = 1;
   struct pbuf *q;
 
   IP6_FRAG_STATS_INC(ip6_frag.recv);
@@ -278,12 +279,12 @@ ip6_reass(struct pbuf *p)
 
   clen = pbuf_clen(p);
 
-  offset = ntohs(frag_hdr->_fragment_offset);
+  offset = lwip_ntohs(frag_hdr->_fragment_offset);
 
   /* Calculate fragment length from IPv6 payload length.
    * Adjust for headers before Fragment Header.
    * And finally adjust by Fragment Header length. */
-  len = ntohs(ip6_current_header()->_plen);
+  len = lwip_ntohs(ip6_current_header()->_plen);
   len -= (u16_t)(((u8_t*)p->payload - (const u8_t*)ip6_current_header()) - IP6_HLEN);
   len -= IP6_FRAG_HLEN;
 
@@ -378,6 +379,7 @@ ip6_reass(struct pbuf *p)
     /* Make room for struct ip6_reass_helper (only required if sizeof(void*) > 4).
        This cannot fail since we already checked when receiving this fragment. */
     u8_t hdrerr = pbuf_header_force(p, IPV6_FRAG_REQROOM);
+    LWIP_UNUSED_ARG(hdrerr); /* in case of LWIP_NOASSERT */
     LWIP_ASSERT("no room for struct ip6_reass_helper", hdrerr == 0);
   }
 #else /* IPV6_FRAG_COPYHEADER */
@@ -529,6 +531,7 @@ ip6_reass(struct pbuf *p)
         if (IPV6_FRAG_REQROOM > 0) {
           /* hide the extra bytes borrowed from ip6_hdr for struct ip6_reass_helper */
           u8_t hdrerr = pbuf_header(next_pbuf, -(s16_t)(IPV6_FRAG_REQROOM));
+          LWIP_UNUSED_ARG(hdrerr); /* in case of LWIP_NOASSERT */
           LWIP_ASSERT("no room for struct ip6_reass_helper", hdrerr == 0);
         }
 #endif
@@ -545,6 +548,7 @@ ip6_reass(struct pbuf *p)
     if (IPV6_FRAG_REQROOM > 0) {
       /* get back room for struct ip6_reass_helper (only required if sizeof(void*) > 4) */
       u8_t hdrerr = pbuf_header(ipr->p, -(s16_t)(IPV6_FRAG_REQROOM));
+      LWIP_UNUSED_ARG(hdrerr); /* in case of LWIP_NOASSERT */
       LWIP_ASSERT("no room for struct ip6_reass_helper", hdrerr == 0);
     }
     iphdr_ptr = (struct ip6_hdr*)((u8_t*)ipr->p->payload - IP6_HLEN);
@@ -559,7 +563,7 @@ ip6_reass(struct pbuf *p)
                          - IP6_HLEN);
 
     /* Set payload length in ip header. */
-    iphdr_ptr->_plen = htons(ipr->datagram_len);
+    iphdr_ptr->_plen = lwip_htons(ipr->datagram_len);
 
     /* Get the first pbuf. */
     p = ipr->p;
@@ -609,6 +613,7 @@ nullreturn:
 
 #if LWIP_IPV6 && LWIP_IPV6_FRAG
 
+#if !LWIP_NETIF_TX_SINGLE_PBUF
 /** Allocate a new struct pbuf_custom_ref */
 static struct pbuf_custom_ref*
 ip6_frag_alloc_pbuf_custom_ref(void)
@@ -637,6 +642,7 @@ ip6_frag_free_pbuf_custom(struct pbuf *p)
   }
   ip6_frag_free_pbuf_custom_ref(pcr);
 }
+#endif /* !LWIP_NETIF_TX_SINGLE_PBUF */
 
 /**
  * Fragment an IPv6 datagram if too large for the netif or path MTU.
@@ -657,7 +663,11 @@ ip6_frag(struct pbuf *p, struct netif *netif, const ip6_addr_t *dest)
   struct ip6_hdr *ip6hdr;
   struct ip6_frag_hdr *frag_hdr;
   struct pbuf *rambuf;
+#if !LWIP_NETIF_TX_SINGLE_PBUF
   struct pbuf *newpbuf;
+  u16_t newpbuflen = 0;
+  u16_t left_to_copy;
+#endif
   static u32_t identification;
   u16_t nfb;
   u16_t left, cop;
@@ -665,8 +675,6 @@ ip6_frag(struct pbuf *p, struct netif *netif, const ip6_addr_t *dest)
   u16_t fragment_offset = 0;
   u16_t last;
   u16_t poff = IP6_HLEN;
-  u16_t newpbuflen = 0;
-  u16_t left_to_copy;
 
   identification++;
 
@@ -685,6 +693,26 @@ ip6_frag(struct pbuf *p, struct netif *netif, const ip6_addr_t *dest)
     /* Fill this fragment */
     cop = last ? left : nfb;
 
+#if LWIP_NETIF_TX_SINGLE_PBUF
+    rambuf = pbuf_alloc(PBUF_IP, cop + IP6_FRAG_HLEN, PBUF_RAM);
+    if (rambuf == NULL) {
+      IP6_FRAG_STATS_INC(ip6_frag.memerr);
+      return ERR_MEM;
+    }
+    LWIP_ASSERT("this needs a pbuf in one piece!",
+      (rambuf->len == rambuf->tot_len) && (rambuf->next == NULL));
+    poff += pbuf_copy_partial(p, (u8_t*)rambuf->payload + IP6_FRAG_HLEN, cop, poff);
+    /* make room for the IP header */
+    if (pbuf_header(rambuf, IP6_HLEN)) {
+      pbuf_free(rambuf);
+      IP6_FRAG_STATS_INC(ip6_frag.memerr);
+      return ERR_MEM;
+    }
+    /* fill in the IP header */
+    SMEMCPY(rambuf->payload, original_ip6hdr, IP6_HLEN);
+    ip6hdr = (struct ip6_hdr *)rambuf->payload;
+    frag_hdr = (struct ip6_frag_hdr *)((u8_t*)rambuf->payload + IP6_HLEN);
+#else
     /* When not using a static buffer, create a chain of pbufs.
      * The first will be a PBUF_RAM holding the link, IPv6, and Fragment header.
      * The rest will be PBUF_REFs mirroring the pbuf chain to be fragged,
@@ -696,7 +724,7 @@ ip6_frag(struct pbuf *p, struct netif *netif, const ip6_addr_t *dest)
       return ERR_MEM;
     }
     LWIP_ASSERT("this needs a pbuf in one piece!",
-                (p->len >= (IP6_HLEN + IP6_FRAG_HLEN)));
+                (p->len >= (IP6_HLEN)));
     SMEMCPY(rambuf->payload, original_ip6hdr, IP6_HLEN);
     ip6hdr = (struct ip6_hdr *)rambuf->payload;
     frag_hdr = (struct ip6_frag_hdr *)((u8_t*)rambuf->payload + IP6_HLEN);
@@ -743,12 +771,13 @@ ip6_frag(struct pbuf *p, struct netif *netif, const ip6_addr_t *dest)
       }
     }
     poff = newpbuflen;
+#endif /* LWIP_NETIF_TX_SINGLE_PBUF */
 
     /* Set headers */
     frag_hdr->_nexth = original_ip6hdr->_nexth;
     frag_hdr->reserved = 0;
-    frag_hdr->_fragment_offset = htons((fragment_offset & IP6_FRAG_OFFSET_MASK) | (last ? 0 : IP6_FRAG_MORE_FLAG));
-    frag_hdr->_identification = htonl(identification);
+    frag_hdr->_fragment_offset = lwip_htons((fragment_offset & IP6_FRAG_OFFSET_MASK) | (last ? 0 : IP6_FRAG_MORE_FLAG));
+    frag_hdr->_identification = lwip_htonl(identification);
 
     IP6H_NEXTH_SET(ip6hdr, IP6_NEXTH_FRAGMENT);
     IP6H_PLEN_SET(ip6hdr, cop + IP6_FRAG_HLEN);

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/ipv6/mld6.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/ipv6/mld6.c b/net/ip/lwip_base/src/core/ipv6/mld6.c
index 2ebcff3..9acb82f 100644
--- a/net/ip/lwip_base/src/core/ipv6/mld6.c
+++ b/net/ip/lwip_base/src/core/ipv6/mld6.c
@@ -564,7 +564,7 @@ mld6_send(struct netif *netif, struct mld_group *group, u8_t type)
   ip6_addr_set(&(mld_hdr->multicast_address), &(group->group_address));
 
 #if CHECKSUM_GEN_ICMP6
-  IF__NETIF_CHECKSUM_ENABLED(group->netif, NETIF_CHECKSUM_GEN_ICMP6) {
+  IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_ICMP6) {
     mld_hdr->chksum = ip6_chksum_pseudo(p, IP6_NEXTH_ICMP6, p->len,
       src_addr, &(group->group_address));
   }
@@ -573,6 +573,11 @@ mld6_send(struct netif *netif, struct mld_group *group, u8_t type)
   /* Add hop-by-hop headers options: router alert with MLD value. */
   ip6_options_add_hbh_ra(p, IP6_NEXTH_ICMP6, IP6_ROUTER_ALERT_VALUE_MLD);
 
+  if (type == ICMP6_TYPE_MLR) {
+    /* Remember we were the last to report */
+    group->last_reporter_flag = 1;
+  }
+
   /* Send the packet out. */
   MLD6_STATS_INC(mld6.xmit);
   ip6_output_if(p, (ip6_addr_isany(src_addr)) ? NULL : src_addr, &(group->group_address),

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/ipv6/nd6.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/ipv6/nd6.c b/net/ip/lwip_base/src/core/ipv6/nd6.c
index 7806f6e..0b36718 100644
--- a/net/ip/lwip_base/src/core/ipv6/nd6.c
+++ b/net/ip/lwip_base/src/core/ipv6/nd6.c
@@ -46,6 +46,7 @@
 #if LWIP_IPV6  /* don't build if not configured for use in lwipopts.h */
 
 #include "lwip/nd6.h"
+#include "lwip/priv/nd6_priv.h"
 #include "lwip/prot/nd6.h"
 #include "lwip/prot/icmp6.h"
 #include "lwip/pbuf.h"
@@ -59,9 +60,14 @@
 #include "lwip/mld6.h"
 #include "lwip/ip.h"
 #include "lwip/stats.h"
+#include "lwip/dns.h"
 
 #include <string.h>
 
+#ifdef LWIP_HOOK_FILENAME
+#include LWIP_HOOK_FILENAME
+#endif
+
 #if LWIP_IPV6_DUP_DETECT_ATTEMPTS > IP6_ADDR_TENTATIVE_COUNT_MASK
 #error LWIP_IPV6_DUP_DETECT_ATTEMPTS > IP6_ADDR_TENTATIVE_COUNT_MASK
 #endif
@@ -93,10 +99,13 @@ static void nd6_free_neighbor_cache_entry(s8_t i);
 static s8_t nd6_find_destination_cache_entry(const ip6_addr_t *ip6addr);
 static s8_t nd6_new_destination_cache_entry(void);
 static s8_t nd6_is_prefix_in_netif(const ip6_addr_t *ip6addr, struct netif *netif);
+static s8_t nd6_select_router(const ip6_addr_t *ip6addr, struct netif *netif);
 static s8_t nd6_get_router(const ip6_addr_t *router_addr, struct netif *netif);
 static s8_t nd6_new_router(const ip6_addr_t *router_addr, struct netif *netif);
 static s8_t nd6_get_onlink_prefix(ip6_addr_t *prefix, struct netif *netif);
 static s8_t nd6_new_onlink_prefix(ip6_addr_t *prefix, struct netif *netif);
+static s8_t nd6_get_next_hop_entry(const ip6_addr_t *ip6addr, struct netif *netif);
+static err_t nd6_queue_packet(s8_t neighbor_index, struct pbuf *q);
 
 #define ND6_SEND_FLAG_MULTICAST_DEST 0x01
 #define ND6_SEND_FLAG_ALLNODES_DEST 0x02
@@ -149,50 +158,27 @@ nd6_input(struct pbuf *p, struct netif *inp)
 
     /* Unsolicited NA?*/
     if (ip6_addr_ismulticast(ip6_current_dest_addr())) {
+      ip6_addr_t target_address;
+      
       /* This is an unsolicited NA.
        * link-layer changed?
        * part of DAD mechanism? */
 
-      /* Check that link-layer address option also fits in packet. */
-      if (p->len < (sizeof(struct na_header) + 2)) {
-        /* @todo debug message */
-        pbuf_free(p);
-        ND6_STATS_INC(nd6.lenerr);
-        ND6_STATS_INC(nd6.drop);
-        return;
-      }
-
-      lladdr_opt = (struct lladdr_option *)((u8_t*)p->payload + sizeof(struct na_header));
-
-      if (p->len < (sizeof(struct na_header) + (lladdr_opt->length << 3))) {
-        /* @todo debug message */
-        pbuf_free(p);
-        ND6_STATS_INC(nd6.lenerr);
-        ND6_STATS_INC(nd6.drop);
-        return;
-      }
-
-      /* Override ip6_current_dest_addr() so that we have an aligned copy. */
-      ip6_addr_set(ip6_current_dest_addr(), &(na_hdr->target_address));
+      /* Create an aligned copy. */
+      ip6_addr_set(&target_address, &(na_hdr->target_address));
 
 #if LWIP_IPV6_DUP_DETECT_ATTEMPTS
       /* If the target address matches this netif, it is a DAD response. */
       for (i = 0; i < LWIP_IPV6_NUM_ADDRESSES; i++) {
         if (!ip6_addr_isinvalid(netif_ip6_addr_state(inp, i)) &&
-            ip6_addr_cmp(ip6_current_dest_addr(), netif_ip6_addr(inp, i))) {
+            ip6_addr_cmp(&target_address, netif_ip6_addr(inp, i))) {
           /* We are using a duplicate address. */
           netif_ip6_addr_set_state(inp, i, IP6_ADDR_INVALID);
 
-#if LWIP_IPV6_MLD
-          /* Leave solicited node multicast group. */
-          ip6_addr_set_solicitednode(&multicast_address, netif_ip6_addr(inp, i)->addr[3]);
-          mld6_leavegroup(netif_ip6_addr(inp, i), &multicast_address);
-#endif /* LWIP_IPV6_MLD */
-
 #if LWIP_IPV6_AUTOCONFIG
           /* Check to see if this address was autoconfigured. */
-          if (!ip6_addr_islinklocal(ip6_current_dest_addr())) {
-            i = nd6_get_onlink_prefix(ip6_current_dest_addr(), inp);
+          if (!ip6_addr_islinklocal(&target_address)) {
+            i = nd6_get_onlink_prefix(&target_address, inp);
             if (i >= 0) {
               /* Mark this prefix as duplicate, so that we don't use it
                * to generate this address again. */
@@ -207,23 +193,44 @@ nd6_input(struct pbuf *p, struct netif *inp)
       }
 #endif /* LWIP_IPV6_DUP_DETECT_ATTEMPTS */
 
+      /* Check that link-layer address option also fits in packet. */
+      if (p->len < (sizeof(struct na_header) + 2)) {
+        /* @todo debug message */
+        pbuf_free(p);
+        ND6_STATS_INC(nd6.lenerr);
+        ND6_STATS_INC(nd6.drop);
+        return;
+      }
+
+      lladdr_opt = (struct lladdr_option *)((u8_t*)p->payload + sizeof(struct na_header));
+
+      if (p->len < (sizeof(struct na_header) + (lladdr_opt->length << 3))) {
+        /* @todo debug message */
+        pbuf_free(p);
+        ND6_STATS_INC(nd6.lenerr);
+        ND6_STATS_INC(nd6.drop);
+        return;
+      }
+
       /* This is an unsolicited NA, most likely there was a LLADDR change. */
-      i = nd6_find_neighbor_cache_entry(ip6_current_dest_addr());
+      i = nd6_find_neighbor_cache_entry(&target_address);
       if (i >= 0) {
         if (na_hdr->flags & ND6_FLAG_OVERRIDE) {
           MEMCPY(neighbor_cache[i].lladdr, lladdr_opt->addr, inp->hwaddr_len);
         }
       }
     } else {
+      ip6_addr_t target_address;
+
       /* This is a solicited NA.
        * neighbor address resolution response?
        * neighbor unreachability detection response? */
 
-      /* Override ip6_current_dest_addr() so that we have an aligned copy. */
-      ip6_addr_set(ip6_current_dest_addr(), &(na_hdr->target_address));
+      /* Create an aligned copy. */
+      ip6_addr_set(&target_address, &(na_hdr->target_address));
 
       /* Find the cache entry corresponding to this na. */
-      i = nd6_find_neighbor_cache_entry(ip6_current_dest_addr());
+      i = nd6_find_neighbor_cache_entry(&target_address);
       if (i < 0) {
         /* We no longer care about this target address. drop it. */
         pbuf_free(p);
@@ -231,8 +238,6 @@ nd6_input(struct pbuf *p, struct netif *inp)
       }
 
       /* Update cache entry. */
-      neighbor_cache[i].netif = inp;
-      neighbor_cache[i].counter.reachable_time = reachable_time;
       if ((na_hdr->flags & ND6_FLAG_OVERRIDE) ||
           (neighbor_cache[i].state == ND6_INCOMPLETE)) {
         /* Check that link-layer address option also fits in packet. */
@@ -256,7 +261,10 @@ nd6_input(struct pbuf *p, struct netif *inp)
 
         MEMCPY(neighbor_cache[i].lladdr, lladdr_opt->addr, inp->hwaddr_len);
       }
+
+      neighbor_cache[i].netif = inp;
       neighbor_cache[i].state = ND6_REACHABLE;
+      neighbor_cache[i].counter.reachable_time = reachable_time;
 
       /* Send queued packets, if any. */
       if (neighbor_cache[i].q != NULL) {
@@ -326,6 +334,8 @@ nd6_input(struct pbuf *p, struct netif *inp)
         }
       }
     } else {
+      ip6_addr_t target_address;
+      
       /* Sender is trying to resolve our address. */
       /* Verify that they included their own link-layer address. */
       if (lladdr_opt == NULL) {
@@ -345,7 +355,7 @@ nd6_input(struct pbuf *p, struct netif *inp)
 
           /* Delay probe in case we get confirmation of reachability from upper layer (TCP). */
           neighbor_cache[i].state = ND6_DELAY;
-          neighbor_cache[i].counter.delay_time = LWIP_ND6_DELAY_FIRST_PROBE_TIME;
+          neighbor_cache[i].counter.delay_time = LWIP_ND6_DELAY_FIRST_PROBE_TIME / ND6_TMR_INTERVAL;
         }
       } else {
         /* Add their IPv6 address and link-layer address to neighbor cache.
@@ -366,14 +376,14 @@ nd6_input(struct pbuf *p, struct netif *inp)
         /* Receiving a message does not prove reachability: only in one direction.
          * Delay probe in case we get confirmation of reachability from upper layer (TCP). */
         neighbor_cache[i].state = ND6_DELAY;
-        neighbor_cache[i].counter.delay_time = LWIP_ND6_DELAY_FIRST_PROBE_TIME;
+        neighbor_cache[i].counter.delay_time = LWIP_ND6_DELAY_FIRST_PROBE_TIME / ND6_TMR_INTERVAL;
       }
 
-      /* Override ip6_current_dest_addr() so that we have an aligned copy. */
-      ip6_addr_set(ip6_current_dest_addr(), &(ns_hdr->target_address));
+      /* Create an aligned copy. */
+      ip6_addr_set(&target_address, &(ns_hdr->target_address));
 
       /* Send back a NA for us. Allocate the reply pbuf. */
-      nd6_send_na(inp, ip6_current_dest_addr(), ND6_FLAG_SOLICITED | ND6_FLAG_OVERRIDE);
+      nd6_send_na(inp, &target_address, ND6_FLAG_SOLICITED | ND6_FLAG_OVERRIDE);
     }
 
     break; /* ICMP6_TYPE_NS */
@@ -383,6 +393,10 @@ nd6_input(struct pbuf *p, struct netif *inp)
     struct ra_header *ra_hdr;
     u8_t *buffer; /* Used to copy options. */
     u16_t offset;
+#if LWIP_ND6_RDNSS_MAX_DNS_SERVERS
+    /* There can by multiple RDNSS options per RA */
+    u8_t rdnss_server_idx = 0;
+#endif /* LWIP_ND6_RDNSS_MAX_DNS_SERVERS */
 
     /* Check that RA header fits in packet. */
     if (p->len < sizeof(struct ra_header)) {
@@ -419,15 +433,15 @@ nd6_input(struct pbuf *p, struct netif *inp)
     }
 
     /* Re-set invalidation timer. */
-    default_router_list[i].invalidation_timer = htons(ra_hdr->router_lifetime);
+    default_router_list[i].invalidation_timer = lwip_htons(ra_hdr->router_lifetime);
 
     /* Re-set default timer values. */
 #if LWIP_ND6_ALLOW_RA_UPDATES
     if (ra_hdr->retrans_timer > 0) {
-      retrans_timer = htonl(ra_hdr->retrans_timer);
+      retrans_timer = lwip_htonl(ra_hdr->retrans_timer);
     }
     if (ra_hdr->reachable_time > 0) {
-      reachable_time = htonl(ra_hdr->reachable_time);
+      reachable_time = lwip_htonl(ra_hdr->reachable_time);
     }
 #endif /* LWIP_ND6_ALLOW_RA_UPDATES */
 
@@ -478,9 +492,9 @@ nd6_input(struct pbuf *p, struct netif *inp)
       {
         struct mtu_option *mtu_opt;
         mtu_opt = (struct mtu_option *)buffer;
-        if (htonl(mtu_opt->mtu) >= 1280) {
+        if (lwip_htonl(mtu_opt->mtu) >= 1280) {
 #if LWIP_ND6_ALLOW_RA_UPDATES
-          inp->mtu = (u16_t)htonl(mtu_opt->mtu);
+          inp->mtu = (u16_t)lwip_htonl(mtu_opt->mtu);
 #endif /* LWIP_ND6_ALLOW_RA_UPDATES */
         }
         break;
@@ -495,18 +509,19 @@ nd6_input(struct pbuf *p, struct netif *inp)
             !ip6_addr_islinklocal(&(prefix_opt->prefix))) {
           /* Add to on-link prefix list. */
           s8_t prefix;
+          ip6_addr_t prefix_addr;
 
           /* Get a memory-aligned copy of the prefix. */
-          ip6_addr_set(ip6_current_dest_addr(), &(prefix_opt->prefix));
+          ip6_addr_set(&prefix_addr, &(prefix_opt->prefix));
 
           /* find cache entry for this prefix. */
-          prefix = nd6_get_onlink_prefix(ip6_current_dest_addr(), inp);
+          prefix = nd6_get_onlink_prefix(&prefix_addr, inp);
           if (prefix < 0) {
             /* Create a new cache entry. */
-            prefix = nd6_new_onlink_prefix(ip6_current_dest_addr(), inp);
+            prefix = nd6_new_onlink_prefix(&prefix_addr, inp);
           }
           if (prefix >= 0) {
-            prefix_list[prefix].invalidation_timer = htonl(prefix_opt->valid_lifetime);
+            prefix_list[prefix].invalidation_timer = lwip_htonl(prefix_opt->valid_lifetime);
 
 #if LWIP_IPV6_AUTOCONFIG
             if (prefix_opt->flags & ND6_PREFIX_FLAG_AUTONOMOUS) {
@@ -526,6 +541,37 @@ nd6_input(struct pbuf *p, struct netif *inp)
         route_opt = (struct route_option *)buffer;*/
 
         break;
+#if LWIP_ND6_RDNSS_MAX_DNS_SERVERS
+      case ND6_OPTION_TYPE_RDNSS:
+      {
+        u8_t num, n;
+        struct rdnss_option * rdnss_opt;
+
+        rdnss_opt = (struct rdnss_option *)buffer;
+        num = (rdnss_opt->length - 1) / 2;
+        for (n = 0; (rdnss_server_idx < DNS_MAX_SERVERS) && (n < num); n++) {
+          ip_addr_t rdnss_address;
+
+          /* Get a memory-aligned copy of the prefix. */
+          ip_addr_copy_from_ip6(rdnss_address, rdnss_opt->rdnss_address[n]);
+
+          if (htonl(rdnss_opt->lifetime) > 0) {
+            /* TODO implement Lifetime > 0 */
+            dns_setserver(rdnss_server_idx++, &rdnss_address);
+          } else {
+            /* TODO implement DNS removal in dns.c */
+            u8_t s;
+            for (s = 0; s < DNS_MAX_SERVERS; s++) {
+              const ip_addr_t *addr = dns_getserver(s);
+              if(ip_addr_cmp(addr, &rdnss_address)) {
+                dns_setserver(s, NULL);
+              }
+            }
+          }
+        }
+        break;
+      }
+#endif /* LWIP_ND6_RDNSS_MAX_DNS_SERVERS */
       default:
         /* Unrecognized option, abort. */
         ND6_STATS_INC(nd6.proterr);
@@ -541,6 +587,7 @@ nd6_input(struct pbuf *p, struct netif *inp)
   {
     struct redirect_header *redir_hdr;
     struct lladdr_option *lladdr_opt;
+    ip6_addr_t tmp;
 
     /* Check that Redir header fits in packet. */
     if (p->len < sizeof(struct redirect_header)) {
@@ -563,10 +610,10 @@ nd6_input(struct pbuf *p, struct netif *inp)
     }
 
     /* Copy original destination address to current source address, to have an aligned copy. */
-    ip6_addr_set(ip6_current_src_addr(), &(redir_hdr->destination_address));
+    ip6_addr_set(&tmp, &(redir_hdr->destination_address));
 
     /* Find dest address in cache */
-    i = nd6_find_destination_cache_entry(ip6_current_src_addr());
+    i = nd6_find_destination_cache_entry(&tmp);
     if (i < 0) {
       /* Destination not in cache, drop packet. */
       pbuf_free(p);
@@ -580,20 +627,20 @@ nd6_input(struct pbuf *p, struct netif *inp)
     if (lladdr_opt != NULL) {
       if (lladdr_opt->type == ND6_OPTION_TYPE_TARGET_LLADDR) {
         /* Copy target address to current source address, to have an aligned copy. */
-        ip6_addr_set(ip6_current_src_addr(), &(redir_hdr->target_address));
+        ip6_addr_set(&tmp, &(redir_hdr->target_address));
 
-        i = nd6_find_neighbor_cache_entry(ip6_current_src_addr());
+        i = nd6_find_neighbor_cache_entry(&tmp);
         if (i < 0) {
           i = nd6_new_neighbor_cache_entry();
           if (i >= 0) {
             neighbor_cache[i].netif = inp;
             MEMCPY(neighbor_cache[i].lladdr, lladdr_opt->addr, inp->hwaddr_len);
-            ip6_addr_set(&(neighbor_cache[i].next_hop_address), ip6_current_src_addr());
+            ip6_addr_set(&(neighbor_cache[i].next_hop_address), &tmp);
 
             /* Receiving a message does not prove reachability: only in one direction.
              * Delay probe in case we get confirmation of reachability from upper layer (TCP). */
             neighbor_cache[i].state = ND6_DELAY;
-            neighbor_cache[i].counter.delay_time = LWIP_ND6_DELAY_FIRST_PROBE_TIME;
+            neighbor_cache[i].counter.delay_time = LWIP_ND6_DELAY_FIRST_PROBE_TIME / ND6_TMR_INTERVAL;
           }
         }
         if (i >= 0) {
@@ -602,7 +649,7 @@ nd6_input(struct pbuf *p, struct netif *inp)
             /* Receiving a message does not prove reachability: only in one direction.
              * Delay probe in case we get confirmation of reachability from upper layer (TCP). */
             neighbor_cache[i].state = ND6_DELAY;
-            neighbor_cache[i].counter.delay_time = LWIP_ND6_DELAY_FIRST_PROBE_TIME;
+            neighbor_cache[i].counter.delay_time = LWIP_ND6_DELAY_FIRST_PROBE_TIME / ND6_TMR_INTERVAL;
           }
         }
       }
@@ -614,6 +661,7 @@ nd6_input(struct pbuf *p, struct netif *inp)
     struct icmp6_hdr *icmp6hdr; /* Packet too big message */
     struct ip6_hdr *ip6hdr; /* IPv6 header of the packet which caused the error */
     u32_t pmtu;
+    ip6_addr_t tmp;
 
     /* Check that ICMPv6 header + IPv6 header fit in payload */
     if (p->len < (sizeof(struct icmp6_hdr) + IP6_HLEN)) {
@@ -628,10 +676,10 @@ nd6_input(struct pbuf *p, struct netif *inp)
     ip6hdr = (struct ip6_hdr *)((u8_t*)p->payload + sizeof(struct icmp6_hdr));
 
     /* Copy original destination address to current source address, to have an aligned copy. */
-    ip6_addr_set(ip6_current_src_addr(), &(ip6hdr->dest));
+    ip6_addr_set(&tmp, &(ip6hdr->dest));
 
     /* Look for entry in destination cache. */
-    i = nd6_find_destination_cache_entry(ip6_current_src_addr());
+    i = nd6_find_destination_cache_entry(&tmp);
     if (i < 0) {
       /* Destination not in cache, drop packet. */
       pbuf_free(p);
@@ -639,7 +687,7 @@ nd6_input(struct pbuf *p, struct netif *inp)
     }
 
     /* Change the Path MTU. */
-    pmtu = htonl(icmp6hdr->data);
+    pmtu = lwip_htonl(icmp6hdr->data);
     destination_cache[i].pmtu = (u16_t)LWIP_MIN(pmtu, 0xFFFF);
 
     break; /* ICMP6_TYPE_PTB */
@@ -698,15 +746,15 @@ nd6_tmr(void)
       }
       break;
     case ND6_STALE:
-      neighbor_cache[i].counter.stale_time += ND6_TMR_INTERVAL;
+      neighbor_cache[i].counter.stale_time++;
       break;
     case ND6_DELAY:
-      if (neighbor_cache[i].counter.delay_time <= ND6_TMR_INTERVAL) {
+      if (neighbor_cache[i].counter.delay_time <= 1) {
         /* Change to PROBE state. */
         neighbor_cache[i].state = ND6_PROBE;
         neighbor_cache[i].counter.probes_sent = 0;
       } else {
-        neighbor_cache[i].counter.delay_time -= ND6_TMR_INTERVAL;
+        neighbor_cache[i].counter.delay_time--;
       }
       break;
     case ND6_PROBE:
@@ -821,13 +869,6 @@ nd6_tmr(void)
           netif_ip6_addr_set_state(netif, i, IP6_ADDR_PREFERRED);
           /* @todo implement preferred and valid lifetimes. */
         } else if (netif->flags & NETIF_FLAG_UP) {
-#if LWIP_IPV6_MLD
-          if ((addr_state & IP6_ADDR_TENTATIVE_COUNT_MASK) == 0) {
-            /* Join solicited node multicast group. */
-            ip6_addr_set_solicitednode(&multicast_address, netif_ip6_addr(netif, i)->addr[3]);
-            mld6_joingroup(netif_ip6_addr(netif, i), &multicast_address);
-          }
-#endif /* LWIP_IPV6_MLD */
           /* Send a NS for this address. */
           nd6_send_ns(netif, netif_ip6_addr(netif, i), ND6_SEND_FLAG_MULTICAST_DEST);
           /* tentative: set next state by increasing by one */
@@ -1286,6 +1327,22 @@ nd6_new_destination_cache_entry(void)
 }
 
 /**
+ * Clear the destination cache.
+ *
+ * This operation may be necessary for consistency in the light of changing
+ * local addresses and/or use of the gateway hook.
+ */
+void
+nd6_clear_destination_cache(void)
+{
+  int i;
+
+  for (i = 0; i < LWIP_ND6_NUM_DESTINATIONS; i++) {
+    ip6_addr_set_any(&destination_cache[i].destination_addr);
+  }
+}
+
+/**
  * Determine whether an address matches an on-link prefix.
  *
  * @param ip6addr the IPv6 address to match
@@ -1320,7 +1377,7 @@ nd6_is_prefix_in_netif(const ip6_addr_t *ip6addr, struct netif *netif)
  * @return the default router entry index, or -1 if no suitable
  *         router is found
  */
-s8_t
+static s8_t
 nd6_select_router(const ip6_addr_t *ip6addr, struct netif *netif)
 {
   s8_t i;
@@ -1373,6 +1430,30 @@ nd6_select_router(const ip6_addr_t *ip6addr, struct netif *netif)
 }
 
 /**
+ * Find a router-announced route to the given destination.
+ *
+ * The caller is responsible for checking whether the returned netif, if any,
+ * is in a suitable state (up, link up) to be used for packet transmission.
+ *
+ * @param ip6addr the destination IPv6 address
+ * @return the netif to use for the destination, or NULL if none found
+ */
+struct netif *
+nd6_find_route(const ip6_addr_t *ip6addr)
+{
+  s8_t i;
+
+  i = nd6_select_router(ip6addr, NULL);
+  if (i >= 0) {
+    if (default_router_list[i].neighbor_entry != NULL) {
+      return default_router_list[i].neighbor_entry->netif; /* may be NULL */
+    }
+  }
+
+  return NULL;
+}
+
+/**
  * Find an entry for a default router.
  *
  * @param router_addr the IPv6 address of the router
@@ -1408,6 +1489,7 @@ static s8_t
 nd6_new_router(const ip6_addr_t *router_addr, struct netif *netif)
 {
   s8_t router_index;
+  s8_t free_router_index;
   s8_t neighbor_index;
 
   /* Do we have a neighbor entry for this router? */
@@ -1431,12 +1513,22 @@ nd6_new_router(const ip6_addr_t *router_addr, struct netif *netif)
   neighbor_cache[neighbor_index].isrouter = 1;
 
   /* Look for empty entry. */
-  for (router_index = 0; router_index < LWIP_ND6_NUM_ROUTERS; router_index++) {
+  free_router_index = LWIP_ND6_NUM_ROUTERS;
+  for (router_index = LWIP_ND6_NUM_ROUTERS - 1; router_index >= 0; router_index--) {
+    /* check if router already exists (this is a special case for 2 netifs on the same subnet
+       - e.g. wifi and cable) */
+    if(default_router_list[router_index].neighbor_entry == &(neighbor_cache[neighbor_index])){ 
+      return router_index; 
+    } 
     if (default_router_list[router_index].neighbor_entry == NULL) {
-      default_router_list[router_index].neighbor_entry = &(neighbor_cache[neighbor_index]);
-      return router_index;
+      /* remember lowest free index to create a new entry */
+      free_router_index = router_index;
     }
   }
+  if (free_router_index < LWIP_ND6_NUM_ROUTERS) {
+    default_router_list[free_router_index].neighbor_entry = &(neighbor_cache[neighbor_index]);
+    return free_router_index;
+  }
 
   /* Could not create a router entry. */
 
@@ -1513,9 +1605,12 @@ nd6_new_onlink_prefix(ip6_addr_t *prefix, struct netif *netif)
  *         suitable next hop was found, ERR_MEM if no cache entry
  *         could be created
  */
-s8_t
+static s8_t
 nd6_get_next_hop_entry(const ip6_addr_t *ip6addr, struct netif *netif)
 {
+#ifdef LWIP_HOOK_ND6_GET_GW
+  const ip6_addr_t *next_hop_addr;
+#endif /* LWIP_HOOK_ND6_GET_GW */
   s8_t i;
 
 #if LWIP_NETIF_HWADDRHINT
@@ -1559,6 +1654,12 @@ nd6_get_next_hop_entry(const ip6_addr_t *ip6addr, struct netif *netif)
         /* Destination in local link. */
         destination_cache[nd6_cached_destination_index].pmtu = netif->mtu;
         ip6_addr_copy(destination_cache[nd6_cached_destination_index].next_hop_addr, destination_cache[nd6_cached_destination_index].destination_addr);
+#ifdef LWIP_HOOK_ND6_GET_GW
+      } else if ((next_hop_addr = LWIP_HOOK_ND6_GET_GW(netif, ip6addr)) != NULL) {
+        /* Next hop for destination provided by hook function. */
+        destination_cache[nd6_cached_destination_index].pmtu = netif->mtu;
+        ip6_addr_set(&destination_cache[nd6_cached_destination_index].next_hop_addr, next_hop_addr);
+#endif /* LWIP_HOOK_ND6_GET_GW */
       } else {
         /* We need to select a router. */
         i = nd6_select_router(ip6addr, netif);
@@ -1626,7 +1727,7 @@ nd6_get_next_hop_entry(const ip6_addr_t *ip6addr, struct netif *netif)
  * @param q packet to be queued
  * @return ERR_OK if succeeded, ERR_MEM if out of memory
  */
-err_t
+static err_t
 nd6_queue_packet(s8_t neighbor_index, struct pbuf *q)
 {
   err_t result = ERR_MEM;
@@ -1762,6 +1863,7 @@ static void
 nd6_send_q(s8_t i)
 {
   struct ip6_hdr *ip6hdr;
+  ip6_addr_t dest;
 #if LWIP_ND6_QUEUEING
   struct nd6_q_entry *q;
 #endif /* LWIP_ND6_QUEUEING */
@@ -1778,10 +1880,10 @@ nd6_send_q(s8_t i)
     neighbor_cache[i].q = q->next;
     /* Get ipv6 header. */
     ip6hdr = (struct ip6_hdr *)(q->p->payload);
-    /* Override ip6_current_dest_addr() so that we have an aligned copy. */
-    ip6_addr_set(ip6_current_dest_addr(), &(ip6hdr->dest));
+    /* Create an aligned copy. */
+    ip6_addr_set(&dest, &(ip6hdr->dest));
     /* send the queued IPv6 packet */
-    (neighbor_cache[i].netif)->output_ip6(neighbor_cache[i].netif, q->p, ip6_current_dest_addr());
+    (neighbor_cache[i].netif)->output_ip6(neighbor_cache[i].netif, q->p, &dest);
     /* free the queued IP packet */
     pbuf_free(q->p);
     /* now queue entry can be freed */
@@ -1791,10 +1893,10 @@ nd6_send_q(s8_t i)
   if (neighbor_cache[i].q != NULL) {
     /* Get ipv6 header. */
     ip6hdr = (struct ip6_hdr *)(neighbor_cache[i].q->payload);
-    /* Override ip6_current_dest_addr() so that we have an aligned copy. */
-    ip6_addr_set(ip6_current_dest_addr(), &(ip6hdr->dest));
+    /* Create an aligned copy. */
+    ip6_addr_set(&dest, &(ip6hdr->dest));
     /* send the queued IPv6 packet */
-    (neighbor_cache[i].netif)->output_ip6(neighbor_cache[i].netif, neighbor_cache[i].q, ip6_current_dest_addr());
+    (neighbor_cache[i].netif)->output_ip6(neighbor_cache[i].netif, neighbor_cache[i].q, &dest);
     /* free the queued IP packet */
     pbuf_free(neighbor_cache[i].q);
     neighbor_cache[i].q = NULL;
@@ -1802,6 +1904,61 @@ nd6_send_q(s8_t i)
 #endif /* LWIP_ND6_QUEUEING */
 }
 
+/**
+ * A packet is to be transmitted to a specific IPv6 destination on a specific
+ * interface. Check if we can find the hardware address of the next hop to use
+ * for the packet. If so, give the hardware address to the caller, which should
+ * use it to send the packet right away. Otherwise, enqueue the packet for
+ * later transmission while looking up the hardware address, if possible.
+ *
+ * As such, this function returns one of three different possible results:
+ *
+ * - ERR_OK with a non-NULL 'hwaddrp': the caller should send the packet now.
+ * - ERR_OK with a NULL 'hwaddrp': the packet has been enqueued for later.
+ * - not ERR_OK: something went wrong; forward the error upward in the stack.
+ *
+ * @param netif The lwIP network interface on which the IP packet will be sent.
+ * @param q The pbuf(s) containing the IP packet to be sent.
+ * @param ip6addr The destination IPv6 address of the packet.
+ * @param hwaddrp On success, filled with a pointer to a HW address or NULL (meaning
+ *        the packet has been queued).
+ * @return
+ * - ERR_OK on success, ERR_RTE if no route was found for the packet,
+ * or ERR_MEM if low memory conditions prohibit sending the packet at all.
+ */
+err_t
+nd6_get_next_hop_addr_or_queue(struct netif *netif, struct pbuf *q, const ip6_addr_t *ip6addr, const u8_t **hwaddrp)
+{
+  s8_t i;
+
+  /* Get next hop record. */
+  i = nd6_get_next_hop_entry(ip6addr, netif);
+  if (i < 0) {
+    /* failed to get a next hop neighbor record. */
+    return i;
+  }
+
+  /* Now that we have a destination record, send or queue the packet. */
+  if (neighbor_cache[i].state == ND6_STALE) {
+    /* Switch to delay state. */
+    neighbor_cache[i].state = ND6_DELAY;
+    neighbor_cache[i].counter.delay_time = LWIP_ND6_DELAY_FIRST_PROBE_TIME / ND6_TMR_INTERVAL;
+  }
+  /* @todo should we send or queue if PROBE? send for now, to let unicast NS pass. */
+  if ((neighbor_cache[i].state == ND6_REACHABLE) ||
+      (neighbor_cache[i].state == ND6_DELAY) ||
+      (neighbor_cache[i].state == ND6_PROBE)) {
+
+    /* Tell the caller to send out the packet now. */
+    *hwaddrp = neighbor_cache[i].lladdr;
+    return ERR_OK;
+  }
+
+  /* We should queue packet on this interface. */
+  *hwaddrp = NULL;
+  return nd6_queue_packet(i, q);
+}
+
 
 /**
  * Get the Path MTU for a destination.
@@ -1908,4 +2065,38 @@ nd6_cleanup_netif(struct netif *netif)
   }
 }
 
+#if LWIP_IPV6_MLD
+/**
+ * The state of a local IPv6 address entry is about to change. If needed, join
+ * or leave the solicited-node multicast group for the address.
+ *
+ * @param netif The netif that owns the address.
+ * @param addr_idx The index of the address.
+ * @param new_state The new (IP6_ADDR_) state for the address.
+ */
+void
+nd6_adjust_mld_membership(struct netif *netif, s8_t addr_idx, u8_t new_state)
+{
+  u8_t old_state, old_member, new_member;
+
+  old_state = netif_ip6_addr_state(netif, addr_idx);
+
+  /* Determine whether we were, and should be, a member of the solicited-node
+   * multicast group for this address. For tentative addresses, the group is
+   * not joined until the address enters the TENTATIVE_1 (or VALID) state. */
+  old_member = (old_state != IP6_ADDR_INVALID && old_state != IP6_ADDR_TENTATIVE);
+  new_member = (new_state != IP6_ADDR_INVALID && new_state != IP6_ADDR_TENTATIVE);
+
+  if (old_member != new_member) {
+    ip6_addr_set_solicitednode(&multicast_address, netif_ip6_addr(netif, addr_idx)->addr[3]);
+
+    if (new_member) {
+      mld6_joingroup_netif(netif, &multicast_address);
+    } else {
+      mld6_leavegroup_netif(netif, &multicast_address);
+    }
+  }
+}
+#endif /* LWIP_IPV6_MLD */
+
 #endif /* LWIP_IPV6 */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/mem.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/mem.c b/net/ip/lwip_base/src/core/mem.c
index 40f4cb9..db3b7cc 100644
--- a/net/ip/lwip_base/src/core/mem.c
+++ b/net/ip/lwip_base/src/core/mem.c
@@ -61,9 +61,13 @@
 #include "lwip/err.h"
 
 #include <string.h>
-#include <stdlib.h>
+
+#if MEM_LIBC_MALLOC
+#include <stdlib.h> /* for malloc()/free() */
+#endif
 
 #if MEM_LIBC_MALLOC || MEM_USE_POOLS
+
 /** mem_init is not used when using pools instead of a heap or using
  * C library malloc().
  */
@@ -162,7 +166,7 @@ void *
 mem_malloc(mem_size_t size)
 {
   void *ret;
-  struct memp_malloc_helper *element;
+  struct memp_malloc_helper *element = NULL;
   memp_t poolnr;
   mem_size_t required_size = size + LWIP_MEM_ALIGN_SIZE(sizeof(struct memp_malloc_helper));
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/memp.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/memp.c b/net/ip/lwip_base/src/core/memp.c
index 19198eb..58fab1a 100644
--- a/net/ip/lwip_base/src/core/memp.c
+++ b/net/ip/lwip_base/src/core/memp.c
@@ -71,11 +71,10 @@
 #include "netif/ppp/ppp_opts.h"
 #include "lwip/netdb.h"
 #include "lwip/dns.h"
-#include "lwip/nd6.h"
+#include "lwip/priv/nd6_priv.h"
 #include "lwip/ip6_frag.h"
 #include "lwip/mld6.h"
 
-
 #define LWIP_MEMPOOL(name,num,size,desc) LWIP_MEMPOOL_DECLARE(name,num,size,desc)
 #include "lwip/priv/memp_std.h"
 
@@ -84,6 +83,10 @@ const struct memp_desc* const memp_pools[MEMP_MAX] = {
 #include "lwip/priv/memp_std.h"
 };
 
+#ifdef LWIP_HOOK_FILENAME
+#include LWIP_HOOK_FILENAME
+#endif
+
 #if MEMP_MEM_MALLOC && MEMP_OVERFLOW_CHECK >= 2
 #undef MEMP_OVERFLOW_CHECK
 /* MEMP_OVERFLOW_CHECK >= 2 does not work with MEMP_MEM_MALLOC, use 1 instead */
@@ -205,11 +208,11 @@ memp_overflow_check_all(void)
   SYS_ARCH_PROTECT(old_level);
 
   for (i = 0; i < MEMP_MAX; ++i) {
-    p = (struct memp *)(size_t)(memp_pools[i]->base);
+    p = (struct memp*)LWIP_MEM_ALIGN(memp_pools[i]->base);
     for (j = 0; j < memp_pools[i]->num; ++j) {
       memp_overflow_check_element_overflow(p, memp_pools[i]);
       memp_overflow_check_element_underflow(p, memp_pools[i]);
-      p = (struct memp*)(size_t)((u8_t*)p + MEMP_SIZE + memp_pools[i]->size + MEMP_SANITY_REGION_AFTER_ALIGNED);
+      p = LWIP_ALIGNMENT_CAST(struct memp*, ((u8_t*)p + MEMP_SIZE + memp_pools[i]->size + MEMP_SANITY_REGION_AFTER_ALIGNED));
     }
   }
   SYS_ARCH_UNPROTECT(old_level);
@@ -301,15 +304,15 @@ do_memp_malloc_pool_fn(const struct memp_desc *desc, const char* file, const int
   SYS_ARCH_PROTECT(old_level);
 
   memp = *desc->tab;
-
-#if MEMP_OVERFLOW_CHECK == 1
-  memp_overflow_check_element_overflow(memp, desc);
-  memp_overflow_check_element_underflow(memp, desc);
-#endif /* MEMP_OVERFLOW_CHECK */
 #endif /* MEMP_MEM_MALLOC */
 
   if (memp != NULL) {
 #if !MEMP_MEM_MALLOC
+#if MEMP_OVERFLOW_CHECK == 1
+    memp_overflow_check_element_overflow(memp, desc);
+    memp_overflow_check_element_underflow(memp, desc);
+#endif /* MEMP_OVERFLOW_CHECK */
+
     *desc->tab = memp->next;
 #if MEMP_OVERFLOW_CHECK
     memp->next = NULL;
@@ -471,6 +474,10 @@ memp_free(memp_t type, void *mem)
 
   LWIP_ERROR("memp_free: type < MEMP_MAX", (type < MEMP_MAX), return;);
 
+  if (mem == NULL) {
+    return;
+  }
+
 #if MEMP_OVERFLOW_CHECK >= 2
   memp_overflow_check_all();
 #endif /* MEMP_OVERFLOW_CHECK >= 2 */


[21/30] incubator-mynewt-core git commit: net/ip/lwip_base; update to LwIP to tag STABLE-2_0_2_RELEASE

Posted by ad...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/def.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/def.h b/net/ip/lwip_base/include/lwip/def.h
index 39d720c..aaa64c7 100644
--- a/net/ip/lwip_base/include/lwip/def.h
+++ b/net/ip/lwip_base/include/lwip/def.h
@@ -57,6 +57,12 @@ extern "C" {
 /* Get the number of entries in an array ('x' must NOT be a pointer!) */
 #define LWIP_ARRAYSIZE(x) (sizeof(x)/sizeof((x)[0]))
 
+/** Create u32_t value from bytes */
+#define LWIP_MAKEU32(a,b,c,d) (((u32_t)((a) & 0xff) << 24) | \
+                               ((u32_t)((b) & 0xff) << 16) | \
+                               ((u32_t)((c) & 0xff) << 8)  | \
+                                (u32_t)((d) & 0xff))
+
 #ifndef NULL
 #ifdef __cplusplus
 #define NULL 0
@@ -65,39 +71,6 @@ extern "C" {
 #endif
 #endif
 
-/* Endianess-optimized shifting of two u8_t to create one u16_t */
-#if BYTE_ORDER == LITTLE_ENDIAN
-#define LWIP_MAKE_U16(a, b) ((a << 8) | b)
-#else
-#define LWIP_MAKE_U16(a, b) ((b << 8) | a)
-#endif
-
-#ifndef LWIP_PLATFORM_BYTESWAP
-#define LWIP_PLATFORM_BYTESWAP 0
-#endif
-
-#ifndef LWIP_PREFIX_BYTEORDER_FUNCS
-/* workaround for naming collisions on some platforms */
-
-#ifdef htons
-#undef htons
-#endif /* htons */
-#ifdef htonl
-#undef htonl
-#endif /* htonl */
-#ifdef ntohs
-#undef ntohs
-#endif /* ntohs */
-#ifdef ntohl
-#undef ntohl
-#endif /* ntohl */
-
-#define htons(x) lwip_htons(x)
-#define ntohs(x) lwip_ntohs(x)
-#define htonl(x) lwip_htonl(x)
-#define ntohl(x) lwip_ntohl(x)
-#endif /* LWIP_PREFIX_BYTEORDER_FUNCS */
-
 #if BYTE_ORDER == BIG_ENDIAN
 #define lwip_htons(x) (x)
 #define lwip_ntohs(x) (x)
@@ -108,34 +81,62 @@ extern "C" {
 #define PP_HTONL(x) (x)
 #define PP_NTOHL(x) (x)
 #else /* BYTE_ORDER != BIG_ENDIAN */
-#if LWIP_PLATFORM_BYTESWAP
-#define lwip_htons(x) LWIP_PLATFORM_HTONS(x)
-#define lwip_ntohs(x) LWIP_PLATFORM_HTONS(x)
-#define lwip_htonl(x) LWIP_PLATFORM_HTONL(x)
-#define lwip_ntohl(x) LWIP_PLATFORM_HTONL(x)
-#else /* LWIP_PLATFORM_BYTESWAP */
+#ifndef lwip_htons
 u16_t lwip_htons(u16_t x);
-u16_t lwip_ntohs(u16_t x);
+#endif
+#define lwip_ntohs(x) lwip_htons(x)
+
+#ifndef lwip_htonl
 u32_t lwip_htonl(u32_t x);
-u32_t lwip_ntohl(u32_t x);
-#endif /* LWIP_PLATFORM_BYTESWAP */
+#endif
+#define lwip_ntohl(x) lwip_htonl(x)
+
+/* Provide usual function names as macros for users, but this can be turned off */
+#ifndef LWIP_DONT_PROVIDE_BYTEORDER_FUNCTIONS
+#define htons(x) lwip_htons(x)
+#define ntohs(x) lwip_ntohs(x)
+#define htonl(x) lwip_htonl(x)
+#define ntohl(x) lwip_ntohl(x)
+#endif
 
 /* These macros should be calculated by the preprocessor and are used
    with compile-time constants only (so that there is no little-endian
    overhead at runtime). */
-#define PP_HTONS(x) ((((x) & 0xff) << 8) | (((x) & 0xff00) >> 8))
+#define PP_HTONS(x) ((((x) & 0x00ffUL) << 8) | (((x) & 0xff00UL) >> 8))
 #define PP_NTOHS(x) PP_HTONS(x)
-#define PP_HTONL(x) ((((x) & 0xff) << 24) | \
-                     (((x) & 0xff00) << 8) | \
-                     (((x) & 0xff0000UL) >> 8) | \
+#define PP_HTONL(x) ((((x) & 0x000000ffUL) << 24) | \
+                     (((x) & 0x0000ff00UL) <<  8) | \
+                     (((x) & 0x00ff0000UL) >>  8) | \
                      (((x) & 0xff000000UL) >> 24))
 #define PP_NTOHL(x) PP_HTONL(x)
 
 #endif /* BYTE_ORDER == BIG_ENDIAN */
 
+/* Functions that are not available as standard implementations.
+ * In cc.h, you can #define these to implementations available on
+ * your platform to save some code bytes if you use these functions
+ * in your application, too.
+ */
+
+#ifndef lwip_itoa
+/* This can be #defined to itoa() or snprintf(result, bufsize, "%d", number) depending on your platform */
+void  lwip_itoa(char* result, size_t bufsize, int number);
+#endif
+#ifndef lwip_strnicmp
+/* This can be #defined to strnicmp() or strncasecmp() depending on your platform */
+int   lwip_strnicmp(const char* str1, const char* str2, size_t len);
+#endif
+#ifndef lwip_stricmp
+/* This can be #defined to stricmp() or strcasecmp() depending on your platform */
+int   lwip_stricmp(const char* str1, const char* str2);
+#endif
+#ifndef lwip_strnstr
+/* This can be #defined to strnstr() depending on your platform */
+char* lwip_strnstr(const char* buffer, const char* token, size_t n);
+#endif
+
 #ifdef __cplusplus
 }
 #endif
 
 #endif /* LWIP_HDR_DEF_H */
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/dhcp.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/dhcp.h b/net/ip/lwip_base/include/lwip/dhcp.h
index f750328..ac1b18e 100644
--- a/net/ip/lwip_base/include/lwip/dhcp.h
+++ b/net/ip/lwip_base/include/lwip/dhcp.h
@@ -132,6 +132,8 @@ void dhcp_fine_tmr(void);
 extern void dhcp_set_ntp_servers(u8_t num_ntp_servers, const ip4_addr_t* ntp_server_addrs);
 #endif /* LWIP_DHCP_GET_NTP_SRV */
 
+#define netif_dhcp_data(netif) ((struct dhcp*)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_DHCP))
+
 #ifdef __cplusplus
 }
 #endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/dhcp6.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/dhcp6.h b/net/ip/lwip_base/include/lwip/dhcp6.h
index e6046c4..455336d 100644
--- a/net/ip/lwip_base/include/lwip/dhcp6.h
+++ b/net/ip/lwip_base/include/lwip/dhcp6.h
@@ -45,10 +45,6 @@
 
 #include "lwip/opt.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #if LWIP_IPV6_DHCP6  /* don't build if not configured for use in lwipopts.h */
 
 
@@ -59,8 +55,4 @@ struct dhcp6
 
 #endif /* LWIP_IPV6_DHCP6 */
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_HDR_IP6_DHCP6_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/dns.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/dns.h b/net/ip/lwip_base/include/lwip/dns.h
index 00d5a78..1453d72 100644
--- a/net/ip/lwip_base/include/lwip/dns.h
+++ b/net/ip/lwip_base/include/lwip/dns.h
@@ -61,7 +61,7 @@ extern "C" {
 #ifndef LWIP_DNS_ADDRTYPE_DEFAULT
 #define LWIP_DNS_ADDRTYPE_DEFAULT   LWIP_DNS_ADDRTYPE_IPV4_IPV6
 #endif
-#elif defined(LWIP_IPV4)
+#elif LWIP_IPV4
 #define LWIP_DNS_ADDRTYPE_DEFAULT   LWIP_DNS_ADDRTYPE_IPV4
 #else
 #define LWIP_DNS_ADDRTYPE_DEFAULT   LWIP_DNS_ADDRTYPE_IPV6
@@ -76,6 +76,7 @@ struct local_hostlist_entry {
   ip_addr_t addr;
   struct local_hostlist_entry *next;
 };
+#define DNS_LOCAL_HOSTLIST_ELEM(name, addr_init) {name, addr_init, NULL}
 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
 #ifndef DNS_LOCAL_HOSTLIST_MAX_NAMELEN
 #define DNS_LOCAL_HOSTLIST_MAX_NAMELEN  DNS_MAX_NAME_LENGTH
@@ -84,6 +85,13 @@ struct local_hostlist_entry {
 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
 #endif /* DNS_LOCAL_HOSTLIST */
 
+#if LWIP_IPV4
+extern const ip_addr_t dns_mquery_v4group;
+#endif /* LWIP_IPV4 */
+#if LWIP_IPV6
+extern const ip_addr_t dns_mquery_v6group;
+#endif /* LWIP_IPV6 */
+
 /** Callback which is invoked when a hostname is found.
  * A function of this type must be implemented by the application using the DNS resolver.
  * @param name pointer to the name that was looked up.
@@ -104,10 +112,14 @@ err_t            dns_gethostbyname_addrtype(const char *hostname, ip_addr_t *add
                                    u8_t dns_addrtype);
 
 
-#if DNS_LOCAL_HOSTLIST && DNS_LOCAL_HOSTLIST_IS_DYNAMIC
+#if DNS_LOCAL_HOSTLIST
+size_t         dns_local_iterate(dns_found_callback iterator_fn, void *iterator_arg);
+err_t          dns_local_lookup(const char *hostname, ip_addr_t *addr, u8_t dns_addrtype);
+#if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
 int            dns_local_removehost(const char *hostname, const ip_addr_t *addr);
 err_t          dns_local_addhost(const char *hostname, const ip_addr_t *addr);
-#endif /* DNS_LOCAL_HOSTLIST && DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
+#endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
+#endif /* DNS_LOCAL_HOSTLIST */
 
 #ifdef __cplusplus
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/err.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/err.h b/net/ip/lwip_base/include/lwip/err.h
index f60c6fc..84e528d 100644
--- a/net/ip/lwip_base/include/lwip/err.h
+++ b/net/ip/lwip_base/include/lwip/err.h
@@ -108,6 +108,10 @@ extern const char *lwip_strerr(err_t err);
 #define lwip_strerr(x) ""
 #endif /* LWIP_DEBUG */
 
+#if !NO_SYS
+int err_to_errno(err_t err);
+#endif /* !NO_SYS */
+
 #ifdef __cplusplus
 }
 #endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/errno.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/errno.h b/net/ip/lwip_base/include/lwip/errno.h
new file mode 100644
index 0000000..641cffb
--- /dev/null
+++ b/net/ip/lwip_base/include/lwip/errno.h
@@ -0,0 +1,193 @@
+/**
+ * @file
+ * Posix Errno defines
+ */
+
+/*
+ * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ * 2. 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.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ *
+ * This file is part of the lwIP TCP/IP stack.
+ *
+ * Author: Adam Dunkels <ad...@sics.se>
+ *
+ */
+#ifndef LWIP_HDR_ERRNO_H
+#define LWIP_HDR_ERRNO_H
+
+#include "lwip/opt.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef LWIP_PROVIDE_ERRNO
+
+#define  EPERM            1  /* Operation not permitted */
+#define  ENOENT           2  /* No such file or directory */
+#define  ESRCH            3  /* No such process */
+#define  EINTR            4  /* Interrupted system call */
+#define  EIO              5  /* I/O error */
+#define  ENXIO            6  /* No such device or address */
+#define  E2BIG            7  /* Arg list too long */
+#define  ENOEXEC          8  /* Exec format error */
+#define  EBADF            9  /* Bad file number */
+#define  ECHILD          10  /* No child processes */
+#define  EAGAIN          11  /* Try again */
+#define  ENOMEM          12  /* Out of memory */
+#define  EACCES          13  /* Permission denied */
+#define  EFAULT          14  /* Bad address */
+#define  ENOTBLK         15  /* Block device required */
+#define  EBUSY           16  /* Device or resource busy */
+#define  EEXIST          17  /* File exists */
+#define  EXDEV           18  /* Cross-device link */
+#define  ENODEV          19  /* No such device */
+#define  ENOTDIR         20  /* Not a directory */
+#define  EISDIR          21  /* Is a directory */
+#define  EINVAL          22  /* Invalid argument */
+#define  ENFILE          23  /* File table overflow */
+#define  EMFILE          24  /* Too many open files */
+#define  ENOTTY          25  /* Not a typewriter */
+#define  ETXTBSY         26  /* Text file busy */
+#define  EFBIG           27  /* File too large */
+#define  ENOSPC          28  /* No space left on device */
+#define  ESPIPE          29  /* Illegal seek */
+#define  EROFS           30  /* Read-only file system */
+#define  EMLINK          31  /* Too many links */
+#define  EPIPE           32  /* Broken pipe */
+#define  EDOM            33  /* Math argument out of domain of func */
+#define  ERANGE          34  /* Math result not representable */
+#define  EDEADLK         35  /* Resource deadlock would occur */
+#define  ENAMETOOLONG    36  /* File name too long */
+#define  ENOLCK          37  /* No record locks available */
+#define  ENOSYS          38  /* Function not implemented */
+#define  ENOTEMPTY       39  /* Directory not empty */
+#define  ELOOP           40  /* Too many symbolic links encountered */
+#define  EWOULDBLOCK     EAGAIN  /* Operation would block */
+#define  ENOMSG          42  /* No message of desired type */
+#define  EIDRM           43  /* Identifier removed */
+#define  ECHRNG          44  /* Channel number out of range */
+#define  EL2NSYNC        45  /* Level 2 not synchronized */
+#define  EL3HLT          46  /* Level 3 halted */
+#define  EL3RST          47  /* Level 3 reset */
+#define  ELNRNG          48  /* Link number out of range */
+#define  EUNATCH         49  /* Protocol driver not attached */
+#define  ENOCSI          50  /* No CSI structure available */
+#define  EL2HLT          51  /* Level 2 halted */
+#define  EBADE           52  /* Invalid exchange */
+#define  EBADR           53  /* Invalid request descriptor */
+#define  EXFULL          54  /* Exchange full */
+#define  ENOANO          55  /* No anode */
+#define  EBADRQC         56  /* Invalid request code */
+#define  EBADSLT         57  /* Invalid slot */
+
+#define  EDEADLOCK       EDEADLK
+
+#define  EBFONT          59  /* Bad font file format */
+#define  ENOSTR          60  /* Device not a stream */
+#define  ENODATA         61  /* No data available */
+#define  ETIME           62  /* Timer expired */
+#define  ENOSR           63  /* Out of streams resources */
+#define  ENONET          64  /* Machine is not on the network */
+#define  ENOPKG          65  /* Package not installed */
+#define  EREMOTE         66  /* Object is remote */
+#define  ENOLINK         67  /* Link has been severed */
+#define  EADV            68  /* Advertise error */
+#define  ESRMNT          69  /* Srmount error */
+#define  ECOMM           70  /* Communication error on send */
+#define  EPROTO          71  /* Protocol error */
+#define  EMULTIHOP       72  /* Multihop attempted */
+#define  EDOTDOT         73  /* RFS specific error */
+#define  EBADMSG         74  /* Not a data message */
+#define  EOVERFLOW       75  /* Value too large for defined data type */
+#define  ENOTUNIQ        76  /* Name not unique on network */
+#define  EBADFD          77  /* File descriptor in bad state */
+#define  EREMCHG         78  /* Remote address changed */
+#define  ELIBACC         79  /* Can not access a needed shared library */
+#define  ELIBBAD         80  /* Accessing a corrupted shared library */
+#define  ELIBSCN         81  /* .lib section in a.out corrupted */
+#define  ELIBMAX         82  /* Attempting to link in too many shared libraries */
+#define  ELIBEXEC        83  /* Cannot exec a shared library directly */
+#define  EILSEQ          84  /* Illegal byte sequence */
+#define  ERESTART        85  /* Interrupted system call should be restarted */
+#define  ESTRPIPE        86  /* Streams pipe error */
+#define  EUSERS          87  /* Too many users */
+#define  ENOTSOCK        88  /* Socket operation on non-socket */
+#define  EDESTADDRREQ    89  /* Destination address required */
+#define  EMSGSIZE        90  /* Message too long */
+#define  EPROTOTYPE      91  /* Protocol wrong type for socket */
+#define  ENOPROTOOPT     92  /* Protocol not available */
+#define  EPROTONOSUPPORT 93  /* Protocol not supported */
+#define  ESOCKTNOSUPPORT 94  /* Socket type not supported */
+#define  EOPNOTSUPP      95  /* Operation not supported on transport endpoint */
+#define  EPFNOSUPPORT    96  /* Protocol family not supported */
+#define  EAFNOSUPPORT    97  /* Address family not supported by protocol */
+#define  EADDRINUSE      98  /* Address already in use */
+#define  EADDRNOTAVAIL   99  /* Cannot assign requested address */
+#define  ENETDOWN       100  /* Network is down */
+#define  ENETUNREACH    101  /* Network is unreachable */
+#define  ENETRESET      102  /* Network dropped connection because of reset */
+#define  ECONNABORTED   103  /* Software caused connection abort */
+#define  ECONNRESET     104  /* Connection reset by peer */
+#define  ENOBUFS        105  /* No buffer space available */
+#define  EISCONN        106  /* Transport endpoint is already connected */
+#define  ENOTCONN       107  /* Transport endpoint is not connected */
+#define  ESHUTDOWN      108  /* Cannot send after transport endpoint shutdown */
+#define  ETOOMANYREFS   109  /* Too many references: cannot splice */
+#define  ETIMEDOUT      110  /* Connection timed out */
+#define  ECONNREFUSED   111  /* Connection refused */
+#define  EHOSTDOWN      112  /* Host is down */
+#define  EHOSTUNREACH   113  /* No route to host */
+#define  EALREADY       114  /* Operation already in progress */
+#define  EINPROGRESS    115  /* Operation now in progress */
+#define  ESTALE         116  /* Stale NFS file handle */
+#define  EUCLEAN        117  /* Structure needs cleaning */
+#define  ENOTNAM        118  /* Not a XENIX named type file */
+#define  ENAVAIL        119  /* No XENIX semaphores available */
+#define  EISNAM         120  /* Is a named type file */
+#define  EREMOTEIO      121  /* Remote I/O error */
+#define  EDQUOT         122  /* Quota exceeded */
+
+#define  ENOMEDIUM      123  /* No medium found */
+#define  EMEDIUMTYPE    124  /* Wrong medium type */
+
+#ifndef errno
+extern int errno;
+#endif
+
+#else /* LWIP_PROVIDE_ERRNO */
+
+/* Define LWIP_ERRNO_INCLUDE to <errno.h> to include the error defines here */
+#ifdef LWIP_ERRNO_INCLUDE
+#include LWIP_ERRNO_INCLUDE
+#endif /* LWIP_ERRNO_INCLUDE */
+
+#endif /* LWIP_PROVIDE_ERRNO */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LWIP_HDR_ERRNO_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/icmp.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/icmp.h b/net/ip/lwip_base/include/lwip/icmp.h
index 490fbf7..f5a31fd 100644
--- a/net/ip/lwip_base/include/lwip/icmp.h
+++ b/net/ip/lwip_base/include/lwip/icmp.h
@@ -69,7 +69,7 @@ enum icmp_dur_type {
 
 /** ICMP time exceeded codes */
 enum icmp_te_type {
-  /* time to live exceeded in transit */
+  /** time to live exceeded in transit */
   ICMP_TE_TTL  = 0,
   /** fragment reassembly time exceeded */
   ICMP_TE_FRAG = 1

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/icmp6.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/icmp6.h b/net/ip/lwip_base/include/lwip/icmp6.h
index e66557d..a29dc8c 100644
--- a/net/ip/lwip_base/include/lwip/icmp6.h
+++ b/net/ip/lwip_base/include/lwip/icmp6.h
@@ -45,99 +45,12 @@
 #include "lwip/pbuf.h"
 #include "lwip/ip6_addr.h"
 #include "lwip/netif.h"
-
+#include "lwip/prot/icmp6.h"
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-/** ICMP type */
-enum icmp6_type {
-  /** Destination unreachable */
-  ICMP6_TYPE_DUR = 1,
-  /** Packet too big */
-  ICMP6_TYPE_PTB = 2,
-  /** Time exceeded */
-  ICMP6_TYPE_TE = 3,
-  /** Parameter problem */
-  ICMP6_TYPE_PP = 4,
-  /** Private experimentation */
-  ICMP6_TYPE_PE1 = 100,
-  /** Private experimentation */
-  ICMP6_TYPE_PE2 = 101,
-  /** Reserved for expansion of error messages */
-  ICMP6_TYPE_RSV_ERR = 127,
-
-  /** Echo request */
-  ICMP6_TYPE_EREQ = 128,
-  /** Echo reply */
-  ICMP6_TYPE_EREP = 129,
-  /** Multicast listener query */
-  ICMP6_TYPE_MLQ = 130,
-  /** Multicast listener report */
-  ICMP6_TYPE_MLR = 131,
-  /** Multicast listener done */
-  ICMP6_TYPE_MLD = 132,
-  /** Router solicitation */
-  ICMP6_TYPE_RS = 133,
-  /** Router advertisement */
-  ICMP6_TYPE_RA = 134,
-  /** Neighbor solicitation */
-  ICMP6_TYPE_NS = 135,
-  /** Neighbor advertisement */
-  ICMP6_TYPE_NA = 136,
-  /** Redirect */
-  ICMP6_TYPE_RD = 137,
-  /** Multicast router advertisement */
-  ICMP6_TYPE_MRA = 151,
-  /** Multicast router solicitation */
-  ICMP6_TYPE_MRS = 152,
-  /** Multicast router termination */
-  ICMP6_TYPE_MRT = 153,
-  /** Private experimentation */
-  ICMP6_TYPE_PE3 = 200,
-  /** Private experimentation */
-  ICMP6_TYPE_PE4 = 201,
-  /** Reserved for expansion of informational messages */
-  ICMP6_TYPE_RSV_INF = 255
-};
-
-/** ICMP destination unreachable codes */
-enum icmp6_dur_code {
-  /** No route to destination */
-  ICMP6_DUR_NO_ROUTE = 0,
-  /** Communication with destination administratively prohibited */
-  ICMP6_DUR_PROHIBITED = 1,
-  /** Beyond scope of source address */
-  ICMP6_DUR_SCOPE = 2,
-  /** Address unreachable */
-  ICMP6_DUR_ADDRESS = 3,
-  /** Port unreachable */
-  ICMP6_DUR_PORT = 4,
-  /** Source address failed ingress/egress policy */
-  ICMP6_DUR_POLICY = 5,
-  /** Reject route to destination */
-  ICMP6_DUR_REJECT_ROUTE = 6
-};
-
-/** ICMP time exceeded codes */
-enum icmp6_te_code {
-  /** Hop limit exceeded in transit */
-  ICMP6_TE_HL = 0,
-  /** Fragment reassembly time exceeded */
-  ICMP6_TE_FRAG = 1
-};
-
-/** ICMP parameter code */
-enum icmp6_pp_code {
-  /** Erroneous header field encountered */
-  ICMP6_PP_FIELD = 0,
-  /** Unrecognized next header type encountered */
-  ICMP6_PP_HEADER = 1,
-  /** Unrecognized IPv6 option encountered */
-  ICMP6_PP_OPTION = 2
-};
-
 #if LWIP_ICMP6 && LWIP_IPV6 /* don't build if not configured for use in lwipopts.h */
 
 void icmp6_input(struct pbuf *p, struct netif *inp);

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/igmp.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/igmp.h b/net/ip/lwip_base/include/lwip/igmp.h
index ba9986b..ffd80e6 100644
--- a/net/ip/lwip_base/include/lwip/igmp.h
+++ b/net/ip/lwip_base/include/lwip/igmp.h
@@ -99,7 +99,11 @@ err_t  igmp_leavegroup(const ip4_addr_t *ifaddr, const ip4_addr_t *groupaddr);
 err_t  igmp_leavegroup_netif(struct netif *netif, const ip4_addr_t *groupaddr);
 void   igmp_tmr(void);
 
-/* Get list of IGMP groups for netif */
+/** @ingroup igmp 
+ * Get list head of IGMP groups for netif.
+ * Note: The allsystems group IP is contained in the list as first entry.
+ * @see @ref netif_set_igmp_mac_filter()
+ */
 #define netif_igmp_data(netif) ((struct igmp_group *)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_IGMP))
 
 #ifdef __cplusplus

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/inet.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/inet.h b/net/ip/lwip_base/include/lwip/inet.h
index 036cd98..4a34f02 100644
--- a/net/ip/lwip_base/include/lwip/inet.h
+++ b/net/ip/lwip_base/include/lwip/inet.h
@@ -132,10 +132,10 @@ extern const struct in6_addr in6addr_any;
 
 #if LWIP_IPV4
 
-#define inet_addr_from_ipaddr(target_inaddr, source_ipaddr) ((target_inaddr)->s_addr = ip4_addr_get_u32(source_ipaddr))
-#define inet_addr_to_ipaddr(target_ipaddr, source_inaddr)   (ip4_addr_set_u32(target_ipaddr, (source_inaddr)->s_addr))
-/* ATTENTION: the next define only works because both s_addr and ip_addr_t are an u32_t effectively! */
-#define inet_addr_to_ipaddr_p(target_ipaddr_p, source_inaddr)   ((target_ipaddr_p) = (ip_addr_t*)&((source_inaddr)->s_addr))
+#define inet_addr_from_ip4addr(target_inaddr, source_ipaddr) ((target_inaddr)->s_addr = ip4_addr_get_u32(source_ipaddr))
+#define inet_addr_to_ip4addr(target_ipaddr, source_inaddr)   (ip4_addr_set_u32(target_ipaddr, (source_inaddr)->s_addr))
+/* ATTENTION: the next define only works because both s_addr and ip4_addr_t are an u32_t effectively! */
+#define inet_addr_to_ip4addr_p(target_ip4addr_p, source_inaddr)   ((target_ip4addr_p) = (ip4_addr_t*)&((source_inaddr)->s_addr))
 
 /* directly map this to the lwip internal functions */
 #define inet_addr(cp)                   ipaddr_addr(cp)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/inet_chksum.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/inet_chksum.h b/net/ip/lwip_base/include/lwip/inet_chksum.h
index 52d76d3..4e23d7f 100644
--- a/net/ip/lwip_base/include/lwip/inet_chksum.h
+++ b/net/ip/lwip_base/include/lwip/inet_chksum.h
@@ -42,15 +42,9 @@
 #include "lwip/pbuf.h"
 #include "lwip/ip_addr.h"
 
-/** Swap the bytes in an u16_t: much like htons() for little-endian */
+/** Swap the bytes in an u16_t: much like lwip_htons() for little-endian */
 #ifndef SWAP_BYTES_IN_WORD
-#if LWIP_PLATFORM_BYTESWAP && (BYTE_ORDER == LITTLE_ENDIAN)
-/* little endian and PLATFORM_BYTESWAP defined */
-#define SWAP_BYTES_IN_WORD(w) LWIP_PLATFORM_HTONS(w)
-#else /* LWIP_PLATFORM_BYTESWAP && (BYTE_ORDER == LITTLE_ENDIAN) */
-/* can't use htons on big endian (or PLATFORM_BYTESWAP not defined)... */
 #define SWAP_BYTES_IN_WORD(w) (((w) & 0xff) << 8) | (((w) & 0xff00) >> 8)
-#endif /* LWIP_PLATFORM_BYTESWAP && (BYTE_ORDER == LITTLE_ENDIAN)*/
 #endif /* SWAP_BYTES_IN_WORD */
 
 /** Split an u32_t in two u16_ts and add them up */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/init.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/init.h b/net/ip/lwip_base/include/lwip/init.h
index b655b43..1dd4437 100644
--- a/net/ip/lwip_base/include/lwip/init.h
+++ b/net/ip/lwip_base/include/lwip/init.h
@@ -54,11 +54,11 @@ extern "C" {
 /** x.X.x: Minor version of the stack */
 #define LWIP_VERSION_MINOR      0
 /** x.x.X: Revision of the stack */
-#define LWIP_VERSION_REVISION   0
+#define LWIP_VERSION_REVISION   1
 /** For release candidates, this is set to 1..254
   * For official releases, this is set to 255 (LWIP_RC_RELEASE)
   * For development versions (Git), this is set to 0 (LWIP_RC_DEVELOPMENT) */
-#define LWIP_VERSION_RC         0
+#define LWIP_VERSION_RC         LWIP_RC_RELEASE
 
 /** LWIP_VERSION_RC is set to LWIP_RC_RELEASE for official releases */
 #define LWIP_RC_RELEASE         255

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/ip4_addr.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/ip4_addr.h b/net/ip/lwip_base/include/lwip/ip4_addr.h
index 2db8bd5..51b46b8 100644
--- a/net/ip/lwip_base/include/lwip/ip4_addr.h
+++ b/net/ip/lwip_base/include/lwip/ip4_addr.h
@@ -52,24 +52,9 @@ struct ip4_addr {
   u32_t addr;
 };
 
-/** This is the packed version of ip4_addr_t,
-   used in network headers that are itself packed */
-#ifdef PACK_STRUCT_USE_INCLUDES
-#  include "arch/bpstruct.h"
-#endif
-PACK_STRUCT_BEGIN
-struct ip4_addr_packed {
-  PACK_STRUCT_FIELD(u32_t addr);
-} PACK_STRUCT_STRUCT;
-PACK_STRUCT_END
-#ifdef PACK_STRUCT_USE_INCLUDES
-#  include "arch/epstruct.h"
-#endif
-
 /** ip4_addr_t uses a struct for convenience only, so that the same defines can
  * operate both on ip4_addr_t as well as on ip4_addr_p_t. */
 typedef struct ip4_addr ip4_addr_t;
-typedef struct ip4_addr_packed ip4_addr_p_t;
 
 /**
  * struct ipaddr2 is used in the definition of the ARP packet format in
@@ -131,23 +116,8 @@ struct netif;
 
 #define IP_LOOPBACKNET      127                 /* official! */
 
-
-#if BYTE_ORDER == BIG_ENDIAN
 /** Set an IP address given by the four byte-parts */
-#define IP4_ADDR(ipaddr, a,b,c,d) \
-        (ipaddr)->addr = ((u32_t)((a) & 0xff) << 24) | \
-                         ((u32_t)((b) & 0xff) << 16) | \
-                         ((u32_t)((c) & 0xff) << 8)  | \
-                          (u32_t)((d) & 0xff)
-#else
-/** Set an IP address given by the four byte-parts.
-    Little-endian version that prevents the use of htonl. */
-#define IP4_ADDR(ipaddr, a,b,c,d) \
-        (ipaddr)->addr = ((u32_t)((d) & 0xff) << 24) | \
-                         ((u32_t)((c) & 0xff) << 16) | \
-                         ((u32_t)((b) & 0xff) << 8)  | \
-                          (u32_t)((a) & 0xff)
-#endif
+#define IP4_ADDR(ipaddr, a,b,c,d)  (ipaddr)->addr = PP_HTONL(LWIP_MAKEU32(a,b,c,d))
 
 /** MEMCPY-like copying of IP addresses where addresses are known to be
  * 16-bit-aligned if the port is correctly configured (so a port could define
@@ -164,7 +134,7 @@ struct netif;
                                     (src)->addr))
 /** Set complete address to zero */
 #define ip4_addr_set_zero(ipaddr)     ((ipaddr)->addr = 0)
-/** Set address to IPADDR_ANY (no need for htonl()) */
+/** Set address to IPADDR_ANY (no need for lwip_htonl()) */
 #define ip4_addr_set_any(ipaddr)      ((ipaddr)->addr = IPADDR_ANY)
 /** Set address to loopback address */
 #define ip4_addr_set_loopback(ipaddr) ((ipaddr)->addr = PP_HTONL(IPADDR_LOOPBACK))
@@ -174,7 +144,7 @@ struct netif;
  * from host- to network-order. */
 #define ip4_addr_set_hton(dest, src) ((dest)->addr = \
                                ((src) == NULL ? 0:\
-                               htonl((src)->addr)))
+                               lwip_htonl((src)->addr)))
 /** IPv4 only: set the IP address given as an u32_t */
 #define ip4_addr_set_u32(dest_ipaddr, src_u32) ((dest_ipaddr)->addr = (src_u32))
 /** IPv4 only: get the IP address as an u32_t */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/ip6_addr.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/ip6_addr.h b/net/ip/lwip_base/include/lwip/ip6_addr.h
index 2d269a6..ee381ae 100644
--- a/net/ip/lwip_base/include/lwip/ip6_addr.h
+++ b/net/ip/lwip_base/include/lwip/ip6_addr.h
@@ -43,6 +43,7 @@
 #define LWIP_HDR_IP6_ADDR_H
 
 #include "lwip/opt.h"
+#include "def.h"
 
 #if LWIP_IPV6  /* don't build if not configured for use in lwipopts.h */
 
@@ -58,41 +59,12 @@ struct ip6_addr {
   u32_t addr[4];
 };
 
-/** This is the packed version of ip6_addr_t,
-    used in network headers that are itself packed */
-#ifdef PACK_STRUCT_USE_INCLUDES
-#  include "arch/bpstruct.h"
-#endif
-PACK_STRUCT_BEGIN
-struct ip6_addr_packed {
-  PACK_STRUCT_FIELD(u32_t addr[4]);
-} PACK_STRUCT_STRUCT;
-PACK_STRUCT_END
-#ifdef PACK_STRUCT_USE_INCLUDES
-#  include "arch/epstruct.h"
-#endif
-
 /** IPv6 address */
 typedef struct ip6_addr ip6_addr_t;
-typedef struct ip6_addr_packed ip6_addr_p_t;
 
-
-#if BYTE_ORDER == BIG_ENDIAN
-/** Set an IPv6 partial address given by byte-parts. */
-#define IP6_ADDR_PART(ip6addr, index, a,b,c,d) \
-  (ip6addr)->addr[index] = ((u32_t)((a) & 0xff) << 24) | \
-                           ((u32_t)((b) & 0xff) << 16) | \
-                           ((u32_t)((c) & 0xff) << 8)  | \
-                            (u32_t)((d) & 0xff)
-#else
-/** Set an IPv6 partial address given by byte-parts.
-Little-endian version, stored in network order (no htonl). */
+/** Set an IPv6 partial address given by byte-parts */
 #define IP6_ADDR_PART(ip6addr, index, a,b,c,d) \
-  (ip6addr)->addr[index] = ((u32_t)((d) & 0xff) << 24) | \
-                           ((u32_t)((c) & 0xff) << 16) | \
-                           ((u32_t)((b) & 0xff) << 8)  | \
-                            (u32_t)((a) & 0xff)
-#endif
+  (ip6addr)->addr[index] = PP_HTONL(LWIP_MAKEU32(a,b,c,d))
 
 /** Set a full IPv6 address by passing the 4 u32_t indices in network byte order
     (use PP_HTONL() for constants) */
@@ -103,21 +75,21 @@ Little-endian version, stored in network order (no htonl). */
   (ip6addr)->addr[3] = idx3; } while(0)
 
 /** Access address in 16-bit block */
-#define IP6_ADDR_BLOCK1(ip6addr) ((u16_t)((htonl((ip6addr)->addr[0]) >> 16) & 0xffff))
+#define IP6_ADDR_BLOCK1(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[0]) >> 16) & 0xffff))
 /** Access address in 16-bit block */
-#define IP6_ADDR_BLOCK2(ip6addr) ((u16_t)((htonl((ip6addr)->addr[0])) & 0xffff))
+#define IP6_ADDR_BLOCK2(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[0])) & 0xffff))
 /** Access address in 16-bit block */
-#define IP6_ADDR_BLOCK3(ip6addr) ((u16_t)((htonl((ip6addr)->addr[1]) >> 16) & 0xffff))
+#define IP6_ADDR_BLOCK3(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[1]) >> 16) & 0xffff))
 /** Access address in 16-bit block */
-#define IP6_ADDR_BLOCK4(ip6addr) ((u16_t)((htonl((ip6addr)->addr[1])) & 0xffff))
+#define IP6_ADDR_BLOCK4(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[1])) & 0xffff))
 /** Access address in 16-bit block */
-#define IP6_ADDR_BLOCK5(ip6addr) ((u16_t)((htonl((ip6addr)->addr[2]) >> 16) & 0xffff))
+#define IP6_ADDR_BLOCK5(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[2]) >> 16) & 0xffff))
 /** Access address in 16-bit block */
-#define IP6_ADDR_BLOCK6(ip6addr) ((u16_t)((htonl((ip6addr)->addr[2])) & 0xffff))
+#define IP6_ADDR_BLOCK6(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[2])) & 0xffff))
 /** Access address in 16-bit block */
-#define IP6_ADDR_BLOCK7(ip6addr) ((u16_t)((htonl((ip6addr)->addr[3]) >> 16) & 0xffff))
+#define IP6_ADDR_BLOCK7(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[3]) >> 16) & 0xffff))
 /** Access address in 16-bit block */
-#define IP6_ADDR_BLOCK8(ip6addr) ((u16_t)((htonl((ip6addr)->addr[3])) & 0xffff))
+#define IP6_ADDR_BLOCK8(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[3])) & 0xffff))
 
 /** Copy IPv6 address - faster than ip6_addr_set: no NULL check */
 #define ip6_addr_copy(dest, src) do{(dest).addr[0] = (src).addr[0]; \
@@ -136,7 +108,7 @@ Little-endian version, stored in network order (no htonl). */
                                          (ip6addr)->addr[2] = 0; \
                                          (ip6addr)->addr[3] = 0;}while(0)
 
-/** Set address to ipv6 'any' (no need for htonl()) */
+/** Set address to ipv6 'any' (no need for lwip_htonl()) */
 #define ip6_addr_set_any(ip6addr)       ip6_addr_set_zero(ip6addr)
 /** Set address to ipv6 loopback address */
 #define ip6_addr_set_loopback(ip6addr) do{(ip6addr)->addr[0] = 0; \
@@ -145,10 +117,10 @@ Little-endian version, stored in network order (no htonl). */
                                           (ip6addr)->addr[3] = PP_HTONL(0x00000001UL);}while(0)
 /** Safely copy one IPv6 address to another and change byte order
  * from host- to network-order. */
-#define ip6_addr_set_hton(dest, src) do{(dest)->addr[0] = (src) == NULL ? 0 : htonl((src)->addr[0]); \
-                                        (dest)->addr[1] = (src) == NULL ? 0 : htonl((src)->addr[1]); \
-                                        (dest)->addr[2] = (src) == NULL ? 0 : htonl((src)->addr[2]); \
-                                        (dest)->addr[3] = (src) == NULL ? 0 : htonl((src)->addr[3]);}while(0)
+#define ip6_addr_set_hton(dest, src) do{(dest)->addr[0] = (src) == NULL ? 0 : lwip_htonl((src)->addr[0]); \
+                                        (dest)->addr[1] = (src) == NULL ? 0 : lwip_htonl((src)->addr[1]); \
+                                        (dest)->addr[2] = (src) == NULL ? 0 : lwip_htonl((src)->addr[2]); \
+                                        (dest)->addr[3] = (src) == NULL ? 0 : lwip_htonl((src)->addr[3]);}while(0)
 
 
 /**
@@ -166,7 +138,7 @@ Little-endian version, stored in network order (no htonl). */
                                     ((addr1)->addr[2] == (addr2)->addr[2]) && \
                                     ((addr1)->addr[3] == (addr2)->addr[3]))
 
-#define ip6_get_subnet_id(ip6addr)   (htonl((ip6addr)->addr[2]) & 0x0000ffffUL)
+#define ip6_get_subnet_id(ip6addr)   (lwip_htonl((ip6addr)->addr[2]) & 0x0000ffffUL)
 
 #define ip6_addr_isany_val(ip6addr) (((ip6addr).addr[0] == 0) && \
                                      ((ip6addr).addr[1] == 0) && \
@@ -187,13 +159,13 @@ Little-endian version, stored in network order (no htonl). */
 
 #define ip6_addr_isuniquelocal(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xfe000000UL)) == PP_HTONL(0xfc000000UL))
 
-#define ip6_addr_isipv6mappedipv4(ip6addr) (((ip6addr)->addr[0] == 0) && ((ip6addr)->addr[1] == 0) && (((ip6addr)->addr[2]) == PP_HTONL(0x0000FFFFUL)))
+#define ip6_addr_isipv4mappedipv6(ip6addr) (((ip6addr)->addr[0] == 0) && ((ip6addr)->addr[1] == 0) && (((ip6addr)->addr[2]) == PP_HTONL(0x0000FFFFUL)))
 
 #define ip6_addr_ismulticast(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xff000000UL)) == PP_HTONL(0xff000000UL))
 #define ip6_addr_multicast_transient_flag(ip6addr)  ((ip6addr)->addr[0] & PP_HTONL(0x00100000UL))
 #define ip6_addr_multicast_prefix_flag(ip6addr)     ((ip6addr)->addr[0] & PP_HTONL(0x00200000UL))
 #define ip6_addr_multicast_rendezvous_flag(ip6addr) ((ip6addr)->addr[0] & PP_HTONL(0x00400000UL))
-#define ip6_addr_multicast_scope(ip6addr) ((htonl((ip6addr)->addr[0]) >> 16) & 0xf)
+#define ip6_addr_multicast_scope(ip6addr) ((lwip_htonl((ip6addr)->addr[0]) >> 16) & 0xf)
 #define IP6_MULTICAST_SCOPE_RESERVED            0x0
 #define IP6_MULTICAST_SCOPE_RESERVED0           0x0
 #define IP6_MULTICAST_SCOPE_INTERFACE_LOCAL     0x1

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/ip_addr.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/ip_addr.h b/net/ip/lwip_base/include/lwip/ip_addr.h
index 4b13e70..11f65d2 100644
--- a/net/ip/lwip_base/include/lwip/ip_addr.h
+++ b/net/ip/lwip_base/include/lwip/ip_addr.h
@@ -47,14 +47,18 @@
 extern "C" {
 #endif
 
-/** Value for ip_addr_t.type: IPv4 */
-#define IPADDR_TYPE_V4                0U
-/** Value for ip_addr_t.type: IPv6 */
-#define IPADDR_TYPE_V6                6U
-/** Value for ip_addr_t.type: IPv4+IPv6 ("dual-stack")
+/** @ingroup ipaddr
+ * IP address types for use in ip_addr_t.type member.
  * @see tcp_new_ip_type(), udp_new_ip_type(), raw_new_ip_type().
  */
-#define IPADDR_TYPE_ANY               46U
+enum lwip_ip_addr_type {
+  /** IPv4 */
+  IPADDR_TYPE_V4 =   0U,
+  /** IPv6 */
+  IPADDR_TYPE_V6 =   6U,
+  /** IPv4+IPv6 ("dual-stack") */
+  IPADDR_TYPE_ANY = 46U
+};
 
 #if LWIP_IPV4 && LWIP_IPV6
 /**
@@ -62,11 +66,12 @@ extern "C" {
  * A union struct for both IP version's addresses.
  * ATTENTION: watch out for its size when adding IPv6 address scope!
  */
-typedef struct _ip_addr {
+typedef struct ip_addr {
   union {
     ip6_addr_t ip6;
     ip4_addr_t ip4;
   } u_addr;
+  /** @ref lwip_ip_addr_type */
   u8_t type;
 } ip_addr_t;
 
@@ -74,8 +79,12 @@ extern const ip_addr_t ip_addr_any_type;
 
 /** @ingroup ip4addr */
 #define IPADDR4_INIT(u32val)          { { { { u32val, 0ul, 0ul, 0ul } } }, IPADDR_TYPE_V4 }
+/** @ingroup ip4addr */
+#define IPADDR4_INIT_BYTES(a,b,c,d)   IPADDR4_INIT(PP_HTONL(LWIP_MAKEU32(a,b,c,d)))
 /** @ingroup ip6addr */
 #define IPADDR6_INIT(a, b, c, d)      { { { { a, b, c, d } } }, IPADDR_TYPE_V6 }
+/** @ingroup ip6addr */
+#define IPADDR6_INIT_HOST(a, b, c, d) { { { { PP_HTONL(a), PP_HTONL(b), PP_HTONL(c), PP_HTONL(d) } } }, IPADDR_TYPE_V6 }
 
 /** @ingroup ipaddr */
 #define IP_IS_ANY_TYPE_VAL(ipaddr)    (IP_GET_TYPE(&ipaddr) == IPADDR_TYPE_ANY)
@@ -113,6 +122,8 @@ extern const ip_addr_t ip_addr_any_type;
 /** @ingroup ip6addr */
 #define IP_ADDR6(ipaddr,i0,i1,i2,i3)  do { IP6_ADDR(ip_2_ip6(ipaddr),i0,i1,i2,i3); \
                                            IP_SET_TYPE_VAL(*(ipaddr), IPADDR_TYPE_V6); } while(0)
+/** @ingroup ip6addr */
+#define IP_ADDR6_HOST(ipaddr,i0,i1,i2,i3)  IP_ADDR6(ipaddr,PP_HTONL(i0),PP_HTONL(i1),PP_HTONL(i2),PP_HTONL(i3))
 
 /** @ingroup ipaddr */
 #define ip_addr_copy(dest, src)      do{ IP_SET_TYPE_VAL(dest, IP_GET_TYPE(&src)); if(IP_IS_V6_VAL(src)){ \
@@ -210,6 +221,19 @@ int ipaddr_aton(const char *cp, ip_addr_t *addr);
 /** @ingroup ipaddr */
 #define IPADDR_STRLEN_MAX   IP6ADDR_STRLEN_MAX
 
+/** @ingroup ipaddr */
+#define ip4_2_ipv4_mapped_ipv6(ip6addr, ip4addr) do { \
+  (ip6addr)->addr[3] = (ip4addr)->addr; \
+  (ip6addr)->addr[2] = PP_HTONL(0x0000FFFFUL); \
+  (ip6addr)->addr[1] = 0; \
+  (ip6addr)->addr[0] = 0; } while(0);
+
+/** @ingroup ipaddr */
+#define unmap_ipv4_mapped_ipv6(ip4addr, ip6addr) \
+  (ip4addr)->addr = (ip6addr)->addr[3];
+
+#define IP46_ADDR_ANY(type) (((type) == IPADDR_TYPE_V6)? IP6_ADDR_ANY : IP4_ADDR_ANY)
+
 #else /* LWIP_IPV4 && LWIP_IPV6 */
 
 #define IP_ADDR_PCB_VERSION_MATCH(addr, pcb)         1
@@ -219,6 +243,7 @@ int ipaddr_aton(const char *cp, ip_addr_t *addr);
 
 typedef ip4_addr_t ip_addr_t;
 #define IPADDR4_INIT(u32val)                    { u32val }
+#define IPADDR4_INIT_BYTES(a,b,c,d)             IPADDR4_INIT(PP_HTONL(LWIP_MAKEU32(a,b,c,d)))
 #define IP_IS_V4_VAL(ipaddr)                    1
 #define IP_IS_V6_VAL(ipaddr)                    0
 #define IP_IS_V4(ipaddr)                        1
@@ -258,10 +283,13 @@ typedef ip4_addr_t ip_addr_t;
 
 #define IPADDR_STRLEN_MAX   IP4ADDR_STRLEN_MAX
 
+#define IP46_ADDR_ANY(type) (IP4_ADDR_ANY)
+
 #else /* LWIP_IPV4 */
 
 typedef ip6_addr_t ip_addr_t;
 #define IPADDR6_INIT(a, b, c, d)                { { a, b, c, d } }
+#define IPADDR6_INIT_HOST(a, b, c, d)           { { PP_HTONL(a), PP_HTONL(b), PP_HTONL(c), PP_HTONL(d) } }
 #define IP_IS_V4_VAL(ipaddr)                    0
 #define IP_IS_V6_VAL(ipaddr)                    1
 #define IP_IS_V4(ipaddr)                        0
@@ -272,6 +300,7 @@ typedef ip6_addr_t ip_addr_t;
 #define IP_GET_TYPE(ipaddr)                     IPADDR_TYPE_V6
 #define ip_2_ip6(ipaddr)                        (ipaddr)
 #define IP_ADDR6(ipaddr,i0,i1,i2,i3)            IP6_ADDR(ipaddr,i0,i1,i2,i3)
+#define IP_ADDR6_HOST(ipaddr,i0,i1,i2,i3)       IP_ADDR6(ipaddr,PP_HTONL(i0),PP_HTONL(i1),PP_HTONL(i2),PP_HTONL(i3))
 
 #define ip_addr_copy(dest, src)                 ip6_addr_copy(dest, src)
 #define ip_addr_copy_from_ip6(dest, src)        ip6_addr_copy(dest, src)
@@ -299,6 +328,8 @@ typedef ip6_addr_t ip_addr_t;
 
 #define IPADDR_STRLEN_MAX   IP6ADDR_STRLEN_MAX
 
+#define IP46_ADDR_ANY(type) (IP6_ADDR_ANY)
+
 #endif /* LWIP_IPV4 */
 #endif /* LWIP_IPV4 && LWIP_IPV6 */
 
@@ -308,19 +339,31 @@ extern const ip_addr_t ip_addr_any;
 extern const ip_addr_t ip_addr_broadcast;
 
 /**
- * @ingroup ipaddr
- * IP_ADDR_ can be used as a fixed/const ip_addr_t
+ * @ingroup ip4addr
+ * Can be used as a fixed/const ip_addr_t
+ * for the IP wildcard.
+ * Defined to @ref IP4_ADDR_ANY when IPv4 is enabled.
+ * Defined to @ref IP6_ADDR_ANY in IPv6 only systems.
+ * Use this if you can handle IPv4 _AND_ IPv6 addresses.
+ * Use @ref IP4_ADDR_ANY or @ref IP6_ADDR_ANY when the IP
+ * type matters.
+ */
+#define IP_ADDR_ANY         IP4_ADDR_ANY
+/**
+ * @ingroup ip4addr
+ * Can be used as a fixed/const ip_addr_t
  * for the IPv4 wildcard and the broadcast address
  */
-#define IP_ADDR_ANY         (&ip_addr_any)
-/** @ingroup ipaddr */
-#define IP_ADDR_BROADCAST   (&ip_addr_broadcast)
+#define IP4_ADDR_ANY        (&ip_addr_any)
 /**
  * @ingroup ip4addr
- * IP4_ADDR_ can be used as a fixed/const ip4_addr_t
+ * Can be used as a fixed/const ip4_addr_t
  * for the wildcard and the broadcast address
  */
-#define IP4_ADDR_ANY        (ip_2_ip4(&ip_addr_any))
+#define IP4_ADDR_ANY4       (ip_2_ip4(&ip_addr_any))
+
+/** @ingroup ip4addr */
+#define IP_ADDR_BROADCAST   (&ip_addr_broadcast)
 /** @ingroup ip4addr */
 #define IP4_ADDR_BROADCAST  (ip_2_ip4(&ip_addr_broadcast))
 
@@ -344,7 +387,7 @@ extern const ip_addr_t ip6_addr_any;
 #define IP6_ADDR_ANY6  (ip_2_ip6(&ip6_addr_any))
 
 #if !LWIP_IPV4
-/** Just a little upgrade-helper for IPv6-only configurations: */
+/** IPv6-only configurations */
 #define IP_ADDR_ANY IP6_ADDR_ANY
 #endif /* !LWIP_IPV4 */
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/mem.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/mem.h b/net/ip/lwip_base/include/lwip/mem.h
index e4f6a64..ff208d2 100644
--- a/net/ip/lwip_base/include/lwip/mem.h
+++ b/net/ip/lwip_base/include/lwip/mem.h
@@ -45,7 +45,8 @@ extern "C" {
 
 #if MEM_LIBC_MALLOC
 
-#include <stddef.h> /* for size_t */
+#include "lwip/arch.h"
+
 typedef size_t mem_size_t;
 #define MEM_SIZE_F SZT_F
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/mld6.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/mld6.h b/net/ip/lwip_base/include/lwip/mld6.h
index eebab25..7fa0797 100644
--- a/net/ip/lwip_base/include/lwip/mld6.h
+++ b/net/ip/lwip_base/include/lwip/mld6.h
@@ -82,7 +82,12 @@ err_t  mld6_joingroup_netif(struct netif *netif, const ip6_addr_t *groupaddr);
 err_t  mld6_leavegroup(const ip6_addr_t *srcaddr, const ip6_addr_t *groupaddr);
 err_t  mld6_leavegroup_netif(struct netif *netif, const ip6_addr_t *groupaddr);
 
-/* Get list of MLD6 groups for netif */
+/** @ingroup mld6
+ * Get list head of MLD6 groups for netif.
+ * Note: The allnodes group IP is NOT in the list, since it must always 
+ * be received for correct IPv6 operation.
+ * @see @ref netif_set_mld_mac_filter()
+ */
 #define netif_mld6_data(netif) ((struct mld_group *)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_MLD6))
 
 #ifdef __cplusplus

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/nd6.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/nd6.h b/net/ip/lwip_base/include/lwip/nd6.h
index c5f27d7..8204fa4 100644
--- a/net/ip/lwip_base/include/lwip/nd6.h
+++ b/net/ip/lwip_base/include/lwip/nd6.h
@@ -48,107 +48,32 @@
 
 #if LWIP_IPV6  /* don't build if not configured for use in lwipopts.h */
 
-#include "lwip/pbuf.h"
-#include "lwip/ip6.h"
 #include "lwip/ip6_addr.h"
-#include "lwip/netif.h"
-
+#include "lwip/err.h"
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-/** Struct for tables. */
-struct nd6_neighbor_cache_entry {
-  ip6_addr_t next_hop_address;
-  struct netif *netif;
-  u8_t lladdr[NETIF_MAX_HWADDR_LEN];
-  /*u32_t pmtu;*/
-#if LWIP_ND6_QUEUEING
-  /** Pointer to queue of pending outgoing packets on this entry. */
-  struct nd6_q_entry *q;
-#else /* LWIP_ND6_QUEUEING */
-  /** Pointer to a single pending outgoing packet on this entry. */
-  struct pbuf *q;
-#endif /* LWIP_ND6_QUEUEING */
-  u8_t state;
-  u8_t isrouter;
-  union {
-    u32_t reachable_time;
-    u32_t delay_time;
-    u32_t probes_sent;
-    u32_t stale_time;
-  } counter;
-};
-
-struct nd6_destination_cache_entry {
-  ip6_addr_t destination_addr;
-  ip6_addr_t next_hop_addr;
-  u16_t pmtu;
-  u32_t age;
-};
-
-struct nd6_prefix_list_entry {
-  ip6_addr_t prefix;
-  struct netif *netif;
-  u32_t invalidation_timer;
-#if LWIP_IPV6_AUTOCONFIG
-  u8_t flags;
-#define ND6_PREFIX_AUTOCONFIG_AUTONOMOUS 0x01
-#define ND6_PREFIX_AUTOCONFIG_ADDRESS_GENERATED 0x02
-#define ND6_PREFIX_AUTOCONFIG_ADDRESS_DUPLICATE 0x04
-#endif /* LWIP_IPV6_AUTOCONFIG */
-};
-
-struct nd6_router_list_entry {
-  struct nd6_neighbor_cache_entry *neighbor_entry;
-  u32_t invalidation_timer;
-  u8_t flags;
-};
-
-enum nd6_neighbor_cache_entry_state {
-  ND6_NO_ENTRY = 0,
-  ND6_INCOMPLETE,
-  ND6_REACHABLE,
-  ND6_STALE,
-  ND6_DELAY,
-  ND6_PROBE
-};
-
-#if LWIP_ND6_QUEUEING
-/** struct for queueing outgoing packets for unknown address
-  * defined here to be accessed by memp.h
-  */
-struct nd6_q_entry {
-  struct nd6_q_entry *next;
-  struct pbuf *p;
-};
-#endif /* LWIP_ND6_QUEUEING */
-
 /** 1 second period */
 #define ND6_TMR_INTERVAL 1000
 
-/* Router tables. */
-/* @todo make these static? and entries accessible through API? */
-extern struct nd6_neighbor_cache_entry neighbor_cache[];
-extern struct nd6_destination_cache_entry destination_cache[];
-extern struct nd6_prefix_list_entry prefix_list[];
-extern struct nd6_router_list_entry default_router_list[];
-
-/* Default values, can be updated by a RA message. */
-extern u32_t reachable_time;
-extern u32_t retrans_timer;
+struct pbuf;
+struct netif;
 
 void nd6_tmr(void);
 void nd6_input(struct pbuf *p, struct netif *inp);
-s8_t nd6_get_next_hop_entry(const ip6_addr_t *ip6addr, struct netif *netif);
-s8_t nd6_select_router(const ip6_addr_t *ip6addr, struct netif *netif);
+void nd6_clear_destination_cache(void);
+struct netif *nd6_find_route(const ip6_addr_t *ip6addr);
+err_t nd6_get_next_hop_addr_or_queue(struct netif *netif, struct pbuf *q, const ip6_addr_t *ip6addr, const u8_t **hwaddrp);
 u16_t nd6_get_destination_mtu(const ip6_addr_t *ip6addr, struct netif *netif);
-err_t nd6_queue_packet(s8_t neighbor_index, struct pbuf *p);
 #if LWIP_ND6_TCP_REACHABILITY_HINTS
 void nd6_reachability_hint(const ip6_addr_t *ip6addr);
 #endif /* LWIP_ND6_TCP_REACHABILITY_HINTS */
 void nd6_cleanup_netif(struct netif *netif);
+#if LWIP_IPV6_MLD
+void nd6_adjust_mld_membership(struct netif *netif, s8_t addr_idx, u8_t new_state);
+#endif /* LWIP_IPV6_MLD */
 
 #ifdef __cplusplus
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/netdb.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/netdb.h b/net/ip/lwip_base/include/lwip/netdb.h
index 21688c6..d3d15df 100644
--- a/net/ip/lwip_base/include/lwip/netdb.h
+++ b/net/ip/lwip_base/include/lwip/netdb.h
@@ -38,8 +38,7 @@
 
 #if LWIP_DNS && LWIP_SOCKET
 
-#include <stddef.h> /* for size_t */
-
+#include "lwip/arch.h"
 #include "lwip/inet.h"
 #include "lwip/sockets.h"
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/netif.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/netif.h b/net/ip/lwip_base/include/lwip/netif.h
index 1d19b27..67a2d24 100644
--- a/net/ip/lwip_base/include/lwip/netif.h
+++ b/net/ip/lwip_base/include/lwip/netif.h
@@ -245,17 +245,19 @@ struct netif {
 #if LWIP_IPV4
   /** This function is called by the IP module when it wants
    *  to send a packet on the interface. This function typically
-   *  first resolves the hardware address, then sends the packet. */
+   *  first resolves the hardware address, then sends the packet.
+   *  For ethernet physical layer, this is usually etharp_output() */
   netif_output_fn output;
 #endif /* LWIP_IPV4 */
-  /** This function is called by the ARP module when it wants
+  /** This function is called by ethernet_output() when it wants
    *  to send a packet on the interface. This function outputs
    *  the pbuf as-is on the link medium. */
   netif_linkoutput_fn linkoutput;
 #if LWIP_IPV6
   /** This function is called by the IPv6 module when it wants
    *  to send a packet on the interface. This function typically
-   *  first resolves the hardware address, then sends the packet. */
+   *  first resolves the hardware address, then sends the packet.
+   *  For ethernet physical layer, this is usually ethip6_output() */
   netif_output_ip6_fn output_ip6;
 #endif /* LWIP_IPV6 */
 #if LWIP_NETIF_STATUS_CALLBACK
@@ -422,11 +424,13 @@ void netif_set_link_callback(struct netif *netif, netif_status_callback_fn link_
 #endif /* LWIP_NETIF_HOSTNAME */
 
 #if LWIP_IGMP
+/** @ingroup netif */
 #define netif_set_igmp_mac_filter(netif, function) do { if((netif) != NULL) { (netif)->igmp_mac_filter = function; }}while(0)
 #define netif_get_igmp_mac_filter(netif) (((netif) != NULL) ? ((netif)->igmp_mac_filter) : NULL)
 #endif /* LWIP_IGMP */
 
 #if LWIP_IPV6 && LWIP_IPV6_MLD
+/** @ingroup netif */
 #define netif_set_mld_mac_filter(netif, function) do { if((netif) != NULL) { (netif)->mld_mac_filter = function; }}while(0)
 #define netif_get_mld_mac_filter(netif) (((netif) != NULL) ? ((netif)->mld_mac_filter) : NULL)
 #define netif_mld_mac_filter(netif, addr, action) do { if((netif) && (netif)->mld_mac_filter) { (netif)->mld_mac_filter((netif), (addr), (action)); }}while(0)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/netifapi.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/netifapi.h b/net/ip/lwip_base/include/lwip/netifapi.h
index 20f8bca..8bd2b4f 100644
--- a/net/ip/lwip_base/include/lwip/netifapi.h
+++ b/net/ip/lwip_base/include/lwip/netifapi.h
@@ -93,13 +93,17 @@ err_t netifapi_netif_common(struct netif *netif, netifapi_void_fn voidfunc,
                             netifapi_errt_fn errtfunc);
 
 /** @ingroup netifapi_netif */
-#define netifapi_netif_remove(n)      netifapi_netif_common(n, netif_remove, NULL)
+#define netifapi_netif_remove(n)        netifapi_netif_common(n, netif_remove, NULL)
 /** @ingroup netifapi_netif */
-#define netifapi_netif_set_up(n)      netifapi_netif_common(n, netif_set_up, NULL)
+#define netifapi_netif_set_up(n)        netifapi_netif_common(n, netif_set_up, NULL)
 /** @ingroup netifapi_netif */
-#define netifapi_netif_set_down(n)    netifapi_netif_common(n, netif_set_down, NULL)
+#define netifapi_netif_set_down(n)      netifapi_netif_common(n, netif_set_down, NULL)
 /** @ingroup netifapi_netif */
-#define netifapi_netif_set_default(n) netifapi_netif_common(n, netif_set_default, NULL)
+#define netifapi_netif_set_default(n)   netifapi_netif_common(n, netif_set_default, NULL)
+/** @ingroup netifapi_netif */
+#define netifapi_netif_set_link_up(n)   netifapi_netif_common(n, netif_set_link_up, NULL)
+/** @ingroup netifapi_netif */
+#define netifapi_netif_set_link_down(n) netifapi_netif_common(n, netif_set_link_down, NULL)
 
 /**
  * @defgroup netifapi_dhcp4 DHCPv4

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/opt.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/opt.h b/net/ip/lwip_base/include/lwip/opt.h
index df26c78..fd459af 100644
--- a/net/ip/lwip_base/include/lwip/opt.h
+++ b/net/ip/lwip_base/include/lwip/opt.h
@@ -44,10 +44,6 @@
 #if !defined LWIP_HDR_OPT_H
 #define LWIP_HDR_OPT_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /*
  * Include user defined options first. Anything not defined in these files
  * will be set to standard values. Override anything you don't like!
@@ -886,6 +882,15 @@ extern "C" {
 #if !defined LWIP_DHCP_MAX_NTP_SERVERS || defined __DOXYGEN__
 #define LWIP_DHCP_MAX_NTP_SERVERS       1
 #endif
+
+/**
+ * LWIP_DHCP_MAX_DNS_SERVERS > 0: Request DNS servers with discover/select.
+ * DHCP servers received in the response are passed to DNS via @ref dns_setserver()
+ * (up to the maximum limit defined here).
+ */
+#if !defined LWIP_DHCP_MAX_DNS_SERVERS || defined __DOXYGEN__
+#define LWIP_DHCP_MAX_DNS_SERVERS       DNS_MAX_SERVERS
+#endif
 /**
  * @}
  */
@@ -1042,11 +1047,9 @@ extern "C" {
 #define LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING 2
 #define LWIP_DNS_SECURE_RAND_SRC_PORT           4
 
-/** DNS_LOCAL_HOSTLIST: Implements a local host-to-address list. If enabled,
- *  you have to define
- *  \#define DNS_LOCAL_HOSTLIST_INIT {{"host1", 0x123}, {"host2", 0x234}}
- *  (an array of structs name/address, where address is an u32_t in network
- *  byte order).
+/** DNS_LOCAL_HOSTLIST: Implements a local host-to-address list. If enabled, you have to define an initializer:
+ *  \#define DNS_LOCAL_HOSTLIST_INIT {DNS_LOCAL_HOSTLIST_ELEM("host_ip4", IPADDR4_INIT_BYTES(1,2,3,4)), \
+ *                                    DNS_LOCAL_HOSTLIST_ELEM("host_ip6", IPADDR6_INIT_HOST(123, 234, 345, 456)}
  *
  *  Instead, you can also use an external function:
  *  \#define DNS_LOOKUP_LOCAL_EXTERN(x) extern err_t my_lookup_function(const char *name, ip_addr_t *addr, u8_t dns_addrtype)
@@ -1061,6 +1064,12 @@ extern "C" {
 #if !defined DNS_LOCAL_HOSTLIST_IS_DYNAMIC || defined __DOXYGEN__
 #define DNS_LOCAL_HOSTLIST_IS_DYNAMIC   0
 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
+
+/** Set this to 1 to enable querying ".local" names via mDNS
+ *  using a One-Shot Multicast DNS Query */
+#if !defined LWIP_DNS_SUPPORT_MDNS_QUERIES || defined __DOXYGEN__
+#define LWIP_DNS_SUPPORT_MDNS_QUERIES  0
+#endif
 /**
  * @}
  */
@@ -1132,7 +1141,10 @@ extern "C" {
 
 /**
  * TCP_WND: The size of a TCP window.  This must be at least
- * (2 * TCP_MSS) for things to work well
+ * (2 * TCP_MSS) for things to work well.
+ * ATTENTION: when using TCP_RCV_SCALE, TCP_WND is the total size
+ * with scaling applied. Maximum window value in the TCP header
+ * will be TCP_WND >> TCP_RCV_SCALE
  */
 #if !defined TCP_WND || defined __DOXYGEN__
 #define TCP_WND                         (4 * TCP_MSS)
@@ -1349,7 +1361,7 @@ extern "C" {
  * for an additional encapsulation header before ethernet headers (e.g. 802.11)
  */
 #if !defined PBUF_LINK_ENCAPSULATION_HLEN || defined __DOXYGEN__
-#define PBUF_LINK_ENCAPSULATION_HLEN    0
+#define PBUF_LINK_ENCAPSULATION_HLEN    0u
 #endif
 
 /**
@@ -2165,7 +2177,7 @@ extern "C" {
 /**
  * LWIP_IPV6_REASS==1: reassemble incoming IPv6 packets that fragmented
  */
-#if !defined LWIP_IPV6_REASS || defined __DOXYGEN__ || defined __DOXYGEN__
+#if !defined LWIP_IPV6_REASS || defined __DOXYGEN__
 #define LWIP_IPV6_REASS                 (LWIP_IPV6)
 #endif
 
@@ -2231,13 +2243,18 @@ extern "C" {
  */
 /**
  * LWIP_IPV6_MLD==1: Enable multicast listener discovery protocol.
+ * If LWIP_IPV6 is enabled but this setting is disabled, the MAC layer must
+ * indiscriminately pass all inbound IPv6 multicast traffic to lwIP.
  */
 #if !defined LWIP_IPV6_MLD || defined __DOXYGEN__
 #define LWIP_IPV6_MLD                   (LWIP_IPV6)
 #endif
 
 /**
- * MEMP_NUM_MLD6_GROUP: Max number of IPv6 multicast that can be joined.
+ * MEMP_NUM_MLD6_GROUP: Max number of IPv6 multicast groups that can be joined.
+ * There must be enough groups so that each netif can join the solicited-node
+ * multicast group for each of its local addresses, plus one for MDNS if
+ * applicable, plus any number of groups to be joined on UDP sockets.
  */
 #if !defined MEMP_NUM_MLD6_GROUP || defined __DOXYGEN__
 #define MEMP_NUM_MLD6_GROUP             4
@@ -2343,7 +2360,7 @@ extern "C" {
  * LWIP_ND6_DELAY_FIRST_PROBE_TIME: Delay before first unicast neighbor solicitation
  * message is sent, during neighbor reachability detection.
  */
-#if !defined LWIP_ND6_DELAY_FIRST_PROBE_TIME || defined __DOXYGEN__s
+#if !defined LWIP_ND6_DELAY_FIRST_PROBE_TIME || defined __DOXYGEN__
 #define LWIP_ND6_DELAY_FIRST_PROBE_TIME 5000
 #endif
 
@@ -2360,9 +2377,18 @@ extern "C" {
  * with reachability hints for connected destinations. This helps avoid sending
  * unicast neighbor solicitation messages.
  */
-#if !defined LWIP_ND6_TCP_REACHABILITY_HINTS || defined __DOXYGEN__ || defined __DOXYGEN__
+#if !defined LWIP_ND6_TCP_REACHABILITY_HINTS || defined __DOXYGEN__
 #define LWIP_ND6_TCP_REACHABILITY_HINTS 1
 #endif
+
+/**
+ * LWIP_ND6_RDNSS_MAX_DNS_SERVERS > 0: Use IPv6 Router Advertisement Recursive
+ * DNS Server Option (as per RFC 6106) to copy a defined maximum number of DNS
+ * servers to the DNS module.
+ */
+#if !defined LWIP_ND6_RDNSS_MAX_DNS_SERVERS || defined __DOXYGEN__
+#define LWIP_ND6_RDNSS_MAX_DNS_SERVERS  0
+#endif
 /**
  * @}
  */
@@ -2388,6 +2414,38 @@ extern "C" {
  */
 
 /**
+ * LWIP_HOOK_FILENAME: Custom filename to #include in files that provide hooks.
+ * Declare your hook function prototypes in there, you may also #include all headers
+ * providing data types that are need in this file.
+ */
+#ifdef __DOXYGEN__
+#define LWIP_HOOK_FILENAME "path/to/my/lwip_hooks.h"
+#endif
+
+/**
+ * LWIP_HOOK_TCP_ISN:
+ * Hook for generation of the Initial Sequence Number (ISN) for a new TCP
+ * connection. The default lwIP ISN generation algorithm is very basic and may
+ * allow for TCP spoofing attacks. This hook provides the means to implement
+ * the standardized ISN generation algorithm from RFC 6528 (see contrib/adons/tcp_isn),
+ * or any other desired algorithm as a replacement.
+ * Called from tcp_connect() and tcp_listen_input() when an ISN is needed for
+ * a new TCP connection, if TCP support (@ref LWIP_TCP) is enabled.\n
+ * Signature: u32_t my_hook_tcp_isn(const ip_addr_t* local_ip, u16_t local_port, const ip_addr_t* remote_ip, u16_t remote_port);
+ * - it may be necessary to use "struct ip_addr" (ip4_addr, ip6_addr) instead of "ip_addr_t" in function declarations\n
+ * Arguments:
+ * - local_ip: pointer to the local IP address of the connection
+ * - local_port: local port number of the connection (host-byte order)
+ * - remote_ip: pointer to the remote IP address of the connection
+ * - remote_port: remote port number of the connection (host-byte order)\n
+ * Return value:
+ * - the 32-bit Initial Sequence Number to use for the new TCP connection.
+ */
+#ifdef __DOXYGEN__
+#define LWIP_HOOK_TCP_ISN(local_ip, local_port, remote_ip, remote_port)
+#endif
+
+/**
  * LWIP_HOOK_IP4_INPUT(pbuf, input_netif):
  * - called from ip_input() (IPv4)
  * - pbuf: received struct pbuf passed to ip_input()
@@ -2428,7 +2486,7 @@ extern "C" {
  * - dest: the destination IPv4 address
  * Returns the IPv4 address of the gateway to handle the specified destination
  * IPv4 address. If NULL is returned, the netif's default gateway is used.
- * The returned address MUST be reachable on the specified netif!
+ * The returned address MUST be directly reachable on the specified netif!
  * This function is meant to implement advanced IPv4 routing together with
  * LWIP_HOOK_IP4_ROUTE(). The actual routing/gateway table implementation is
  * not part of lwIP but can e.g. be hidden in the netif's state argument.
@@ -2465,6 +2523,22 @@ extern "C" {
 #endif
 
 /**
+ * LWIP_HOOK_ND6_GET_GW(netif, dest):
+ * - called from nd6_get_next_hop_entry() (IPv6)
+ * - netif: the netif used for sending
+ * - dest: the destination IPv6 address
+ * Returns the IPv6 address of the next hop to handle the specified destination
+ * IPv6 address. If NULL is returned, a NDP-discovered router is used instead.
+ * The returned address MUST be directly reachable on the specified netif!
+ * This function is meant to implement advanced IPv6 routing together with
+ * LWIP_HOOK_IP6_ROUTE(). The actual routing/gateway table implementation is
+ * not part of lwIP but can e.g. be hidden in the netif's state argument.
+*/
+#ifdef __DOXYGEN__
+#define LWIP_HOOK_ND6_GET_GW(netif, dest)
+#endif
+
+/**
  * LWIP_HOOK_VLAN_CHECK(netif, eth_hdr, vlan_hdr):
  * - called from ethernet_input() if VLAN support is enabled
  * - netif: struct netif on which the packet has been received
@@ -2527,7 +2601,7 @@ extern "C" {
    ---------------------------------------
 */
 /**
- * @defgroup lwip_opts_debugmsg Debugging
+ * @defgroup lwip_opts_debugmsg Debug messages
  * @ingroup lwip_opts_debug
  * @{
  */
@@ -2535,14 +2609,16 @@ extern "C" {
  * LWIP_DBG_MIN_LEVEL: After masking, the value of the debug is
  * compared against this value. If it is smaller, then debugging
  * messages are written.
+ * @see debugging_levels
  */
-#if !defined LWIP_DBG_MIN_LEVEL || defined __DOXYGEN__ || defined __DOXYGEN__
+#if !defined LWIP_DBG_MIN_LEVEL || defined __DOXYGEN__
 #define LWIP_DBG_MIN_LEVEL              LWIP_DBG_LEVEL_ALL
 #endif
 
 /**
  * LWIP_DBG_TYPES_ON: A mask that can be used to globally enable/disable
  * debug messages of certain types.
+ * @see debugging_levels
  */
 #if !defined LWIP_DBG_TYPES_ON || defined __DOXYGEN__
 #define LWIP_DBG_TYPES_ON               LWIP_DBG_ON
@@ -2797,8 +2873,4 @@ extern "C" {
  * @}
  */
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_HDR_OPT_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/pbuf.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/pbuf.h b/net/ip/lwip_base/include/lwip/pbuf.h
index bc7296e..9061046 100644
--- a/net/ip/lwip_base/include/lwip/pbuf.h
+++ b/net/ip/lwip_base/include/lwip/pbuf.h
@@ -80,13 +80,13 @@ typedef enum {
   PBUF_IP,
   /** Includes spare room for link layer header (ethernet header).
    * Use this if you intend to pass the pbuf to functions like ethernet_output().
-   * @see @ref PBUF_LINK_HLEN
+   * @see PBUF_LINK_HLEN
    */
   PBUF_LINK,
   /** Includes spare room for additional encapsulation header before ethernet
    * headers (e.g. 802.11).
    * Use this if you intend to pass the pbuf to functions like netif->linkoutput().
-   * @see @ref PBUF_LINK_ENCAPSULATION_HLEN
+   * @see PBUF_LINK_ENCAPSULATION_HLEN
    */
   PBUF_RAW_TX,
   /** Use this for input packets in a netif driver when calling netif->input()
@@ -231,12 +231,12 @@ u8_t pbuf_header(struct pbuf *p, s16_t header_size);
 u8_t pbuf_header_force(struct pbuf *p, s16_t header_size);
 void pbuf_ref(struct pbuf *p);
 u8_t pbuf_free(struct pbuf *p);
-u8_t pbuf_clen(struct pbuf *p);
+u16_t pbuf_clen(const struct pbuf *p);
 void pbuf_cat(struct pbuf *head, struct pbuf *tail);
 void pbuf_chain(struct pbuf *head, struct pbuf *tail);
 struct pbuf *pbuf_dechain(struct pbuf *p);
-err_t pbuf_copy(struct pbuf *p_to, struct pbuf *p_from);
-u16_t pbuf_copy_partial(struct pbuf *p, void *dataptr, u16_t len, u16_t offset);
+err_t pbuf_copy(struct pbuf *p_to, const struct pbuf *p_from);
+u16_t pbuf_copy_partial(const struct pbuf *p, void *dataptr, u16_t len, u16_t offset);
 err_t pbuf_take(struct pbuf *buf, const void *dataptr, u16_t len);
 err_t pbuf_take_at(struct pbuf *buf, const void *dataptr, u16_t len, u16_t offset);
 struct pbuf *pbuf_skip(struct pbuf* in, u16_t in_offset, u16_t* out_offset);
@@ -249,12 +249,12 @@ err_t pbuf_fill_chksum(struct pbuf *p, u16_t start_offset, const void *dataptr,
 void pbuf_split_64k(struct pbuf *p, struct pbuf **rest);
 #endif /* LWIP_TCP && TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
 
-u8_t pbuf_get_at(struct pbuf* p, u16_t offset);
-int pbuf_try_get_at(struct pbuf* p, u16_t offset);
+u8_t pbuf_get_at(const struct pbuf* p, u16_t offset);
+int pbuf_try_get_at(const struct pbuf* p, u16_t offset);
 void pbuf_put_at(struct pbuf* p, u16_t offset, u8_t data);
-u16_t pbuf_memcmp(struct pbuf* p, u16_t offset, const void* s2, u16_t n);
-u16_t pbuf_memfind(struct pbuf* p, const void* mem, u16_t mem_len, u16_t start_offset);
-u16_t pbuf_strstr(struct pbuf* p, const char* substr);
+u16_t pbuf_memcmp(const struct pbuf* p, u16_t offset, const void* s2, u16_t n);
+u16_t pbuf_memfind(const struct pbuf* p, const void* mem, u16_t mem_len, u16_t start_offset);
+u16_t pbuf_strstr(const struct pbuf* p, const char* substr);
 
 #ifdef __cplusplus
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/priv/api_msg.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/priv/api_msg.h b/net/ip/lwip_base/include/lwip/priv/api_msg.h
index ad38345..f12b8b7 100644
--- a/net/ip/lwip_base/include/lwip/priv/api_msg.h
+++ b/net/ip/lwip_base/include/lwip/priv/api_msg.h
@@ -43,8 +43,7 @@
 /* Note: Netconn API is always available when sockets are enabled -
  * sockets are implemented on top of them */
 
-#include <stddef.h> /* for size_t */
-
+#include "lwip/arch.h"
 #include "lwip/ip_addr.h"
 #include "lwip/err.h"
 #include "lwip/sys.h"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/priv/memp_std.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/priv/memp_std.h b/net/ip/lwip_base/include/lwip/priv/memp_std.h
index dd439d1..ce9fd50 100644
--- a/net/ip/lwip_base/include/lwip/priv/memp_std.h
+++ b/net/ip/lwip_base/include/lwip/priv/memp_std.h
@@ -21,10 +21,6 @@
 /* This treats "malloc pools" just like any other pool.
    The pools are a little bigger to provide 'size' as the amount of user data. */
 #define LWIP_MALLOC_MEMPOOL(num, size) LWIP_MEMPOOL(POOL_##size, num, (size + LWIP_MEM_ALIGN_SIZE(sizeof(struct memp_malloc_helper))), "MALLOC_"#size)
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #define LWIP_MALLOC_MEMPOOL_START
 #define LWIP_MALLOC_MEMPOOL_END
 #endif /* LWIP_MALLOC_MEMPOOL */
@@ -137,10 +133,6 @@ LWIP_PBUF_MEMPOOL(PBUF_POOL, PBUF_POOL_SIZE,           PBUF_POOL_BUFSIZE,
  */
 #if MEMP_USE_CUSTOM_POOLS
 #include "lwippools.h"
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* MEMP_USE_CUSTOM_POOLS */
 
 /*

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/priv/nd6_priv.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/priv/nd6_priv.h b/net/ip/lwip_base/include/lwip/priv/nd6_priv.h
new file mode 100644
index 0000000..4bda0b7
--- /dev/null
+++ b/net/ip/lwip_base/include/lwip/priv/nd6_priv.h
@@ -0,0 +1,144 @@
+/**
+ * @file
+ *
+ * Neighbor discovery and stateless address autoconfiguration for IPv6.
+ * Aims to be compliant with RFC 4861 (Neighbor discovery) and RFC 4862
+ * (Address autoconfiguration).
+ */
+
+/*
+ * Copyright (c) 2010 Inico Technologies Ltd.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ * 2. 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.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ *
+ * This file is part of the lwIP TCP/IP stack.
+ *
+ * Author: Ivan Delamer <de...@inicotech.com>
+ *
+ *
+ * Please coordinate changes and requests with Ivan Delamer
+ * <de...@inicotech.com>
+ */
+
+#ifndef LWIP_HDR_ND6_PRIV_H
+#define LWIP_HDR_ND6_PRIV_H
+
+#include "lwip/opt.h"
+
+#if LWIP_IPV6  /* don't build if not configured for use in lwipopts.h */
+
+#include "lwip/pbuf.h"
+#include "lwip/ip6_addr.h"
+#include "lwip/netif.h"
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if LWIP_ND6_QUEUEING
+/** struct for queueing outgoing packets for unknown address
+  * defined here to be accessed by memp.h
+  */
+struct nd6_q_entry {
+  struct nd6_q_entry *next;
+  struct pbuf *p;
+};
+#endif /* LWIP_ND6_QUEUEING */
+
+/** Struct for tables. */
+struct nd6_neighbor_cache_entry {
+  ip6_addr_t next_hop_address;
+  struct netif *netif;
+  u8_t lladdr[NETIF_MAX_HWADDR_LEN];
+  /*u32_t pmtu;*/
+#if LWIP_ND6_QUEUEING
+  /** Pointer to queue of pending outgoing packets on this entry. */
+  struct nd6_q_entry *q;
+#else /* LWIP_ND6_QUEUEING */
+  /** Pointer to a single pending outgoing packet on this entry. */
+  struct pbuf *q;
+#endif /* LWIP_ND6_QUEUEING */
+  u8_t state;
+  u8_t isrouter;
+  union {
+    u32_t reachable_time; /* in ms since value may originate from network packet */
+    u32_t delay_time;     /* ticks (ND6_TMR_INTERVAL) */
+    u32_t probes_sent;
+    u32_t stale_time;     /* ticks (ND6_TMR_INTERVAL) */
+  } counter;
+};
+
+struct nd6_destination_cache_entry {
+  ip6_addr_t destination_addr;
+  ip6_addr_t next_hop_addr;
+  u16_t pmtu;
+  u32_t age;
+};
+
+struct nd6_prefix_list_entry {
+  ip6_addr_t prefix;
+  struct netif *netif;
+  u32_t invalidation_timer; /* in ms since value may originate from network packet */
+#if LWIP_IPV6_AUTOCONFIG
+  u8_t flags;
+#define ND6_PREFIX_AUTOCONFIG_AUTONOMOUS 0x01
+#define ND6_PREFIX_AUTOCONFIG_ADDRESS_GENERATED 0x02
+#define ND6_PREFIX_AUTOCONFIG_ADDRESS_DUPLICATE 0x04
+#endif /* LWIP_IPV6_AUTOCONFIG */
+};
+
+struct nd6_router_list_entry {
+  struct nd6_neighbor_cache_entry *neighbor_entry;
+  u32_t invalidation_timer; /* in ms since value may originate from network packet */
+  u8_t flags;
+};
+
+enum nd6_neighbor_cache_entry_state {
+  ND6_NO_ENTRY = 0,
+  ND6_INCOMPLETE,
+  ND6_REACHABLE,
+  ND6_STALE,
+  ND6_DELAY,
+  ND6_PROBE
+};
+
+/* Router tables. */
+/* @todo make these static? and entries accessible through API? */
+extern struct nd6_neighbor_cache_entry neighbor_cache[];
+extern struct nd6_destination_cache_entry destination_cache[];
+extern struct nd6_prefix_list_entry prefix_list[];
+extern struct nd6_router_list_entry default_router_list[];
+
+/* Default values, can be updated by a RA message. */
+extern u32_t reachable_time;
+extern u32_t retrans_timer;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LWIP_IPV6 */
+
+#endif /* LWIP_HDR_ND6_PRIV_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/priv/tcp_priv.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/priv/tcp_priv.h b/net/ip/lwip_base/include/lwip/priv/tcp_priv.h
index 736dc32..73e8967 100644
--- a/net/ip/lwip_base/include/lwip/priv/tcp_priv.h
+++ b/net/ip/lwip_base/include/lwip/priv/tcp_priv.h
@@ -34,8 +34,8 @@
  * Author: Adam Dunkels <ad...@sics.se>
  *
  */
-#ifndef LWIP_HDR_TCP_IMPL_H
-#define LWIP_HDR_TCP_IMPL_H
+#ifndef LWIP_HDR_TCP_PRIV_H
+#define LWIP_HDR_TCP_PRIV_H
 
 #include "lwip/opt.h"
 
@@ -170,16 +170,18 @@ err_t            tcp_process_refused_data(struct tcp_pcb *pcb);
                 LWIP_EVENT_RECV, NULL, 0, ERR_OK)
 #define TCP_EVENT_CONNECTED(pcb,err,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\
                 LWIP_EVENT_CONNECTED, NULL, 0, (err))
-#define TCP_EVENT_POLL(pcb,ret)       ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\
-                LWIP_EVENT_POLL, NULL, 0, ERR_OK)
-#define TCP_EVENT_ERR(errf,arg,err)  lwip_tcp_event((arg), NULL, \
-                LWIP_EVENT_ERR, NULL, 0, (err))
+#define TCP_EVENT_POLL(pcb,ret)       do { if ((pcb)->state != SYN_RCVD) {                          \
+                ret = lwip_tcp_event((pcb)->callback_arg, (pcb), LWIP_EVENT_POLL, NULL, 0, ERR_OK); \
+                } else {                                                                            \
+                ret = ERR_ARG; } } while(0)
+#define TCP_EVENT_ERR(last_state,errf,arg,err)  do { if (last_state != SYN_RCVD) {                \
+                lwip_tcp_event((arg), NULL, LWIP_EVENT_ERR, NULL, 0, (err)); } } while(0)
 
 #else /* LWIP_EVENT_API */
 
 #define TCP_EVENT_ACCEPT(lpcb,pcb,arg,err,ret)                 \
   do {                                                         \
-    if((lpcb != NULL) && ((lpcb)->accept != NULL))             \
+    if((lpcb)->accept != NULL)                                 \
       (ret) = (lpcb)->accept((arg),(pcb),(err));               \
     else (ret) = ERR_ARG;                                      \
   } while (0)
@@ -223,8 +225,9 @@ err_t            tcp_process_refused_data(struct tcp_pcb *pcb);
     else (ret) = ERR_OK;                                       \
   } while (0)
 
-#define TCP_EVENT_ERR(errf,arg,err)                            \
+#define TCP_EVENT_ERR(last_state,errf,arg,err)                 \
   do {                                                         \
+    LWIP_UNUSED_ARG(last_state);                               \
     if((errf) != NULL)                                         \
       (errf)((arg),(err));                                     \
   } while (0)
@@ -249,7 +252,7 @@ struct tcp_seg {
 #if TCP_OVERSIZE_DBGCHECK
   u16_t oversize_left;     /* Extra bytes available at the end of the last
                               pbuf in unsent (used for asserting vs.
-                              tcp_pcb.unsent_oversized only) */
+                              tcp_pcb.unsent_oversize only) */
 #endif /* TCP_OVERSIZE_DBGCHECK */
 #if TCP_CHECKSUM_ON_COPY
   u16_t chksum;
@@ -290,7 +293,7 @@ struct tcp_seg {
   (flags & TF_SEG_OPTS_WND_SCALE ? LWIP_TCP_OPT_LEN_WS_OUT : 0)
 
 /** This returns a TCP header option for MSS in an u32_t */
-#define TCP_BUILD_MSS_OPTION(mss) htonl(0x02040000 | ((mss) & 0xFFFF))
+#define TCP_BUILD_MSS_OPTION(mss) lwip_htonl(0x02040000 | ((mss) & 0xFFFF))
 
 #if LWIP_WND_SCALE
 #define TCPWNDSIZE_F       U32_F
@@ -452,7 +455,7 @@ void tcp_rst(u32_t seqno, u32_t ackno,
        const ip_addr_t *local_ip, const ip_addr_t *remote_ip,
        u16_t local_port, u16_t remote_port);
 
-u32_t tcp_next_iss(void);
+u32_t tcp_next_iss(struct tcp_pcb *pcb);
 
 err_t tcp_keepalive(struct tcp_pcb *pcb);
 err_t tcp_zero_window_probe(struct tcp_pcb *pcb);
@@ -501,4 +504,4 @@ void tcp_netif_ip_addr_changed(const ip_addr_t* old_addr, const ip_addr_t* new_a
 
 #endif /* LWIP_TCP */
 
-#endif /* LWIP_HDR_TCP_H */
+#endif /* LWIP_HDR_TCP_PRIV_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/priv/tcpip_priv.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/priv/tcpip_priv.h b/net/ip/lwip_base/include/lwip/priv/tcpip_priv.h
index 5fc80f3..630efb1 100644
--- a/net/ip/lwip_base/include/lwip/priv/tcpip_priv.h
+++ b/net/ip/lwip_base/include/lwip/priv/tcpip_priv.h
@@ -69,7 +69,7 @@ struct netif;
                                         } while(0)
 #define API_VAR_FREE(pool, name)        memp_free(pool, name)
 #define API_VAR_FREE_POOL(pool, name)   LWIP_MEMPOOL_FREE(pool, name)
-#define API_EXPR_REF(expr)              &(expr)
+#define API_EXPR_REF(expr)              (&(expr))
 #if LWIP_NETCONN_SEM_PER_THREAD
 #define API_EXPR_REF_SEM(expr)          (expr)
 #else
@@ -87,7 +87,7 @@ struct netif;
 #define API_VAR_FREE_POOL(pool, name)
 #define API_EXPR_REF(expr)              expr
 #define API_EXPR_REF_SEM(expr)          API_EXPR_REF(expr)
-#define API_EXPR_DEREF(expr)            *(expr)
+#define API_EXPR_DEREF(expr)            (*(expr))
 #define API_MSG_M_DEF(m)                *m
 #define API_MSG_M_DEF_C(t, m)           const t * m
 #endif /* LWIP_MPU_COMPATIBLE */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/prot/dns.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/prot/dns.h b/net/ip/lwip_base/include/lwip/prot/dns.h
index 0a99ab0..94782d6 100644
--- a/net/ip/lwip_base/include/lwip/prot/dns.h
+++ b/net/ip/lwip_base/include/lwip/prot/dns.h
@@ -115,6 +115,24 @@ PACK_STRUCT_END
 #endif
 #define SIZEOF_DNS_HDR 12
 
+
+/* Multicast DNS definitions */
+
+/** UDP port for multicast DNS queries */
+#ifndef DNS_MQUERY_PORT
+#define DNS_MQUERY_PORT             5353
+#endif
+
+/* IPv4 group for multicast DNS queries: 224.0.0.251 */
+#ifndef DNS_MQUERY_IPV4_GROUP_INIT
+#define DNS_MQUERY_IPV4_GROUP_INIT  IPADDR4_INIT_BYTES(224,0,0,251)
+#endif
+
+/* IPv6 group for multicast DNS queries: FF02::FB */
+#ifndef DNS_MQUERY_IPV6_GROUP_INIT
+#define DNS_MQUERY_IPV6_GROUP_INIT  IPADDR6_INIT_HOST(0xFF020000,0,0,0xFB)
+#endif
+
 #ifdef __cplusplus
 }
 #endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/prot/ethernet.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/prot/ethernet.h b/net/ip/lwip_base/include/lwip/prot/ethernet.h
index 792f5a2..e4baa29 100644
--- a/net/ip/lwip_base/include/lwip/prot/ethernet.h
+++ b/net/ip/lwip_base/include/lwip/prot/ethernet.h
@@ -100,7 +100,7 @@ PACK_STRUCT_END
 #endif
 
 #define SIZEOF_VLAN_HDR 4
-#define VLAN_ID(vlan_hdr) (htons((vlan_hdr)->prio_vid) & 0xFFF)
+#define VLAN_ID(vlan_hdr) (lwip_htons((vlan_hdr)->prio_vid) & 0xFFF)
 
 /**
  * @ingroup ethernet

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/prot/icmp6.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/prot/icmp6.h b/net/ip/lwip_base/include/lwip/prot/icmp6.h
index a0a713b..3461120 100644
--- a/net/ip/lwip_base/include/lwip/prot/icmp6.h
+++ b/net/ip/lwip_base/include/lwip/prot/icmp6.h
@@ -43,6 +43,93 @@
 extern "C" {
 #endif
 
+/** ICMP type */
+enum icmp6_type {
+  /** Destination unreachable */
+  ICMP6_TYPE_DUR = 1,
+  /** Packet too big */
+  ICMP6_TYPE_PTB = 2,
+  /** Time exceeded */
+  ICMP6_TYPE_TE = 3,
+  /** Parameter problem */
+  ICMP6_TYPE_PP = 4,
+  /** Private experimentation */
+  ICMP6_TYPE_PE1 = 100,
+  /** Private experimentation */
+  ICMP6_TYPE_PE2 = 101,
+  /** Reserved for expansion of error messages */
+  ICMP6_TYPE_RSV_ERR = 127,
+
+  /** Echo request */
+  ICMP6_TYPE_EREQ = 128,
+  /** Echo reply */
+  ICMP6_TYPE_EREP = 129,
+  /** Multicast listener query */
+  ICMP6_TYPE_MLQ = 130,
+  /** Multicast listener report */
+  ICMP6_TYPE_MLR = 131,
+  /** Multicast listener done */
+  ICMP6_TYPE_MLD = 132,
+  /** Router solicitation */
+  ICMP6_TYPE_RS = 133,
+  /** Router advertisement */
+  ICMP6_TYPE_RA = 134,
+  /** Neighbor solicitation */
+  ICMP6_TYPE_NS = 135,
+  /** Neighbor advertisement */
+  ICMP6_TYPE_NA = 136,
+  /** Redirect */
+  ICMP6_TYPE_RD = 137,
+  /** Multicast router advertisement */
+  ICMP6_TYPE_MRA = 151,
+  /** Multicast router solicitation */
+  ICMP6_TYPE_MRS = 152,
+  /** Multicast router termination */
+  ICMP6_TYPE_MRT = 153,
+  /** Private experimentation */
+  ICMP6_TYPE_PE3 = 200,
+  /** Private experimentation */
+  ICMP6_TYPE_PE4 = 201,
+  /** Reserved for expansion of informational messages */
+  ICMP6_TYPE_RSV_INF = 255
+};
+
+/** ICMP destination unreachable codes */
+enum icmp6_dur_code {
+  /** No route to destination */
+  ICMP6_DUR_NO_ROUTE = 0,
+  /** Communication with destination administratively prohibited */
+  ICMP6_DUR_PROHIBITED = 1,
+  /** Beyond scope of source address */
+  ICMP6_DUR_SCOPE = 2,
+  /** Address unreachable */
+  ICMP6_DUR_ADDRESS = 3,
+  /** Port unreachable */
+  ICMP6_DUR_PORT = 4,
+  /** Source address failed ingress/egress policy */
+  ICMP6_DUR_POLICY = 5,
+  /** Reject route to destination */
+  ICMP6_DUR_REJECT_ROUTE = 6
+};
+
+/** ICMP time exceeded codes */
+enum icmp6_te_code {
+  /** Hop limit exceeded in transit */
+  ICMP6_TE_HL = 0,
+  /** Fragment reassembly time exceeded */
+  ICMP6_TE_FRAG = 1
+};
+
+/** ICMP parameter code */
+enum icmp6_pp_code {
+  /** Erroneous header field encountered */
+  ICMP6_PP_FIELD = 0,
+  /** Unrecognized next header type encountered */
+  ICMP6_PP_HEADER = 1,
+  /** Unrecognized IPv6 option encountered */
+  ICMP6_PP_OPTION = 2
+};
+
 /** This is the standard ICMP6 header. */
 #ifdef PACK_STRUCT_USE_INCLUDES
 #  include "arch/bpstruct.h"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/prot/ip.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/prot/ip.h b/net/ip/lwip_base/include/lwip/prot/ip.h
index 223158f..bbfae36 100644
--- a/net/ip/lwip_base/include/lwip/prot/ip.h
+++ b/net/ip/lwip_base/include/lwip/prot/ip.h
@@ -39,10 +39,6 @@
 
 #include "lwip/arch.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #define IP_PROTO_ICMP    1
 #define IP_PROTO_IGMP    2
 #define IP_PROTO_UDP     17
@@ -52,8 +48,4 @@ extern "C" {
 /** This operates on a void* by loading the first byte */
 #define IP_HDR_GET_VERSION(ptr)   ((*(u8_t*)(ptr)) >> 4)
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_HDR_PROT_IP_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/prot/ip4.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/prot/ip4.h b/net/ip/lwip_base/include/lwip/prot/ip4.h
index c3c3403..bd442c6 100644
--- a/net/ip/lwip_base/include/lwip/prot/ip4.h
+++ b/net/ip/lwip_base/include/lwip/prot/ip4.h
@@ -44,6 +44,22 @@
 extern "C" {
 #endif
 
+/** This is the packed version of ip4_addr_t,
+    used in network headers that are itself packed */
+#ifdef PACK_STRUCT_USE_INCLUDES
+#  include "arch/bpstruct.h"
+#endif
+PACK_STRUCT_BEGIN
+struct ip4_addr_packed {
+  PACK_STRUCT_FIELD(u32_t addr);
+} PACK_STRUCT_STRUCT;
+PACK_STRUCT_END
+#ifdef PACK_STRUCT_USE_INCLUDES
+#  include "arch/epstruct.h"
+#endif
+
+typedef struct ip4_addr_packed ip4_addr_p_t;
+
 /* Size of the IPv4 header. Same as 'sizeof(struct ip_hdr)'. */
 #define IP_HLEN 20
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/prot/ip6.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/prot/ip6.h b/net/ip/lwip_base/include/lwip/prot/ip6.h
index 9a1aaa9..6e1e263 100644
--- a/net/ip/lwip_base/include/lwip/prot/ip6.h
+++ b/net/ip/lwip_base/include/lwip/prot/ip6.h
@@ -43,6 +43,21 @@
 #ifdef __cplusplus
 extern "C" {
 #endif
+   
+/** This is the packed version of ip6_addr_t,
+    used in network headers that are itself packed */
+#ifdef PACK_STRUCT_USE_INCLUDES
+#  include "arch/bpstruct.h"
+#endif
+PACK_STRUCT_BEGIN
+struct ip6_addr_packed {
+  PACK_STRUCT_FIELD(u32_t addr[4]);
+} PACK_STRUCT_STRUCT;
+PACK_STRUCT_END
+#ifdef PACK_STRUCT_USE_INCLUDES
+#  include "arch/epstruct.h"
+#endif
+typedef struct ip6_addr_packed ip6_addr_p_t;
 
 #define IP6_HLEN 40
 
@@ -134,16 +149,16 @@ PACK_STRUCT_END
 #  include "arch/epstruct.h"
 #endif
 
-#define IP6H_V(hdr)  ((ntohl((hdr)->_v_tc_fl) >> 28) & 0x0f)
-#define IP6H_TC(hdr) ((ntohl((hdr)->_v_tc_fl) >> 20) & 0xff)
-#define IP6H_FL(hdr) (ntohl((hdr)->_v_tc_fl) & 0x000fffff)
-#define IP6H_PLEN(hdr) (ntohs((hdr)->_plen))
+#define IP6H_V(hdr)  ((lwip_ntohl((hdr)->_v_tc_fl) >> 28) & 0x0f)
+#define IP6H_TC(hdr) ((lwip_ntohl((hdr)->_v_tc_fl) >> 20) & 0xff)
+#define IP6H_FL(hdr) (lwip_ntohl((hdr)->_v_tc_fl) & 0x000fffff)
+#define IP6H_PLEN(hdr) (lwip_ntohs((hdr)->_plen))
 #define IP6H_NEXTH(hdr) ((hdr)->_nexth)
 #define IP6H_NEXTH_P(hdr) ((u8_t *)(hdr) + 6)
 #define IP6H_HOPLIM(hdr) ((hdr)->_hoplim)
 
-#define IP6H_VTCFL_SET(hdr, v, tc, fl) (hdr)->_v_tc_fl = (htonl((((u32_t)(v)) << 28) | (((u32_t)(tc)) << 20) | (fl)))
-#define IP6H_PLEN_SET(hdr, plen) (hdr)->_plen = htons(plen)
+#define IP6H_VTCFL_SET(hdr, v, tc, fl) (hdr)->_v_tc_fl = (lwip_htonl((((u32_t)(v)) << 28) | (((u32_t)(tc)) << 20) | (fl)))
+#define IP6H_PLEN_SET(hdr, plen) (hdr)->_plen = lwip_htons(plen)
 #define IP6H_NEXTH_SET(hdr, nexth) (hdr)->_nexth = (nexth)
 #define IP6H_HOPLIM_SET(hdr, hl) (hdr)->_hoplim = (u8_t)(hl)
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/prot/mld6.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/prot/mld6.h b/net/ip/lwip_base/include/lwip/prot/mld6.h
index 2664829..be3a006 100644
--- a/net/ip/lwip_base/include/lwip/prot/mld6.h
+++ b/net/ip/lwip_base/include/lwip/prot/mld6.h
@@ -38,7 +38,7 @@
 #define LWIP_HDR_PROT_MLD6_H
 
 #include "lwip/arch.h"
-#include "lwip/ip6_addr.h"
+#include "lwip/prot/ip6.h"
 
 #ifdef __cplusplus
 extern "C" {

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/prot/nd6.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/prot/nd6.h b/net/ip/lwip_base/include/lwip/prot/nd6.h
index eae3d28..2d4903d 100644
--- a/net/ip/lwip_base/include/lwip/prot/nd6.h
+++ b/net/ip/lwip_base/include/lwip/prot/nd6.h
@@ -39,6 +39,7 @@
 
 #include "lwip/arch.h"
 #include "lwip/ip6_addr.h"
+#include "lwip/prot/ip6.h"
 
 #ifdef __cplusplus
 extern "C" {
@@ -246,6 +247,29 @@ PACK_STRUCT_END
 #  include "arch/epstruct.h"
 #endif
 
+/** Recursive DNS Server Option. */
+#if LWIP_ND6_RDNSS_MAX_DNS_SERVERS
+#define LWIP_RDNSS_OPTION_MAX_SERVERS LWIP_ND6_RDNSS_MAX_DNS_SERVERS
+#else
+#define LWIP_RDNSS_OPTION_MAX_SERVERS 1
+#endif
+#define ND6_OPTION_TYPE_RDNSS (25)
+#ifdef PACK_STRUCT_USE_INCLUDES
+#  include "arch/bpstruct.h"
+#endif
+PACK_STRUCT_BEGIN
+struct rdnss_option {
+  PACK_STRUCT_FLD_8(u8_t type);
+  PACK_STRUCT_FLD_8(u8_t length);
+  PACK_STRUCT_FIELD(u16_t reserved);
+  PACK_STRUCT_FIELD(u32_t lifetime);
+  PACK_STRUCT_FLD_S(ip6_addr_p_t rdnss_address[LWIP_RDNSS_OPTION_MAX_SERVERS]);
+} PACK_STRUCT_STRUCT;
+PACK_STRUCT_END
+#ifdef PACK_STRUCT_USE_INCLUDES
+#  include "arch/epstruct.h"
+#endif
+
 #ifdef __cplusplus
 }
 #endif



[26/30] incubator-mynewt-core git commit: net/ip; add sys/shell as conditional dependency.

Posted by ad...@apache.org.
net/ip; add sys/shell as conditional dependency.


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/ed273edb
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/ed273edb
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/ed273edb

Branch: refs/heads/master
Commit: ed273edbe3e3f79b93170dccd12a16ad35cb6030
Parents: 39ad85d
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Mon Apr 17 15:01:02 2017 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Apr 17 15:01:02 2017 -0700

----------------------------------------------------------------------
 net/ip/pkg.yml | 3 +++
 1 file changed, 3 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/ed273edb/net/ip/pkg.yml
----------------------------------------------------------------------
diff --git a/net/ip/pkg.yml b/net/ip/pkg.yml
index 0f657f1..8fb6af6 100644
--- a/net/ip/pkg.yml
+++ b/net/ip/pkg.yml
@@ -32,5 +32,8 @@ pkg.deps:
     - net/ip/lwip_base
     - net/ip/mn_socket
 
+pkg.deps.LWIP_CLI:
+    - sys/shell
+
 pkg.init:
     ip_init: 200


[06/30] incubator-mynewt-core git commit: stm32f4xx/stm32f7xx; add syscfg indicating which version of STM32 is being used.

Posted by ad...@apache.org.
stm32f4xx/stm32f7xx; add syscfg indicating which version of STM32
is being used.


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/8d8cf59c
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/8d8cf59c
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/8d8cf59c

Branch: refs/heads/master
Commit: 8d8cf59ca47d4fdf37dbbef99428c0b25c5893d1
Parents: 383906f
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Fri Apr 14 10:45:22 2017 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Fri Apr 14 13:21:30 2017 -0700

----------------------------------------------------------------------
 hw/mcu/stm/stm32f4xx/syscfg.yml | 4 ++++
 hw/mcu/stm/stm32f7xx/syscfg.yml | 4 ++++
 2 files changed, 8 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/8d8cf59c/hw/mcu/stm/stm32f4xx/syscfg.yml
----------------------------------------------------------------------
diff --git a/hw/mcu/stm/stm32f4xx/syscfg.yml b/hw/mcu/stm/stm32f4xx/syscfg.yml
index d0c40be..42bb13a 100644
--- a/hw/mcu/stm/stm32f4xx/syscfg.yml
+++ b/hw/mcu/stm/stm32f4xx/syscfg.yml
@@ -24,3 +24,7 @@ syscfg.defs:
             Specifies the required alignment for internal flash writes.
             Used internally by the newt tool.
         value: 1
+
+    MCU_STM32F4:
+        description: MCUs are of STM32F4xx family
+        value: 1

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/8d8cf59c/hw/mcu/stm/stm32f7xx/syscfg.yml
----------------------------------------------------------------------
diff --git a/hw/mcu/stm/stm32f7xx/syscfg.yml b/hw/mcu/stm/stm32f7xx/syscfg.yml
index d2cb541..cf82e27 100644
--- a/hw/mcu/stm/stm32f7xx/syscfg.yml
+++ b/hw/mcu/stm/stm32f7xx/syscfg.yml
@@ -22,3 +22,7 @@ syscfg.defs:
             Specifies the required alignment for internal flash writes.
             Used internally by the newt tool.
         value: 1
+
+    MCU_STM32F7:
+        description: MCUs are of STM32F7xx family
+        value: 1


[15/30] incubator-mynewt-core git commit: net/ip/lwip_base; update to LwIP to tag STABLE-2_0_2_RELEASE

Posted by ad...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/netif/lowpan6.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/netif/lowpan6.c b/net/ip/lwip_base/src/netif/lowpan6.c
index 407848c..9a84cbc 100644
--- a/net/ip/lwip_base/src/netif/lowpan6.c
+++ b/net/ip/lwip_base/src/netif/lowpan6.c
@@ -160,13 +160,13 @@ lowpan6_get_address_mode(const ip6_addr_t *ip6addr, const struct ieee_802154_add
   if (mac_addr->addr_len == 2) {
     if ((ip6addr->addr[2] == (u32_t)PP_HTONL(0x000000ff)) &&
       ((ip6addr->addr[3]  & PP_HTONL(0xffff0000)) == PP_NTOHL(0xfe000000))) {
-      if ((ip6addr->addr[3]  & PP_HTONL(0x0000ffff)) == ntohl((mac_addr->addr[0] << 8) | mac_addr->addr[1])) {
+      if ((ip6addr->addr[3]  & PP_HTONL(0x0000ffff)) == lwip_ntohl((mac_addr->addr[0] << 8) | mac_addr->addr[1])) {
         return 3;
       }
     }
   } else if (mac_addr->addr_len == 8) {
-    if ((ip6addr->addr[2] == ntohl(((mac_addr->addr[0] ^ 2) << 24) | (mac_addr->addr[1] << 16) | mac_addr->addr[2] << 8 | mac_addr->addr[3])) &&
-      (ip6addr->addr[3] == ntohl((mac_addr->addr[4] << 24) | (mac_addr->addr[5] << 16) | mac_addr->addr[6] << 8 | mac_addr->addr[7]))) {
+    if ((ip6addr->addr[2] == lwip_ntohl(((mac_addr->addr[0] ^ 2) << 24) | (mac_addr->addr[1] << 16) | mac_addr->addr[2] << 8 | mac_addr->addr[3])) &&
+      (ip6addr->addr[3] == lwip_ntohl((mac_addr->addr[4] << 24) | (mac_addr->addr[5] << 16) | mac_addr->addr[6] << 8 | mac_addr->addr[7]))) {
       return 3;
     }
   }
@@ -611,12 +611,13 @@ lowpan4_output(struct netif *netif, struct pbuf *q, const ip4_addr_t *ipaddr)
  * @param q The pbuf(s) containing the IP packet to be sent.
  * @param ip6addr The IP address of the packet destination.
  *
- * @return
+ * @return err_t
  */
 err_t
 lowpan6_output(struct netif *netif, struct pbuf *q, const ip6_addr_t *ip6addr)
 {
-  s8_t i;
+  err_t result;
+  const u8_t *hwaddr;
   struct ieee_802154_addr src, dest;
 #if LWIP_6LOWPAN_INFER_SHORT_ADDRESS
   ip6_addr_t ip6_src;
@@ -663,35 +664,23 @@ lowpan6_output(struct netif *netif, struct pbuf *q, const ip6_addr_t *ip6addr)
   }
 #endif /* LWIP_6LOWPAN_INFER_SHORT_ADDRESS */
 
-
-  /* Get next hop record. */
-  i = nd6_get_next_hop_entry(ip6addr, netif);
-  if (i < 0) {
+  /* Ask ND6 what to do with the packet. */
+  result = nd6_get_next_hop_addr_or_queue(netif, q, ip6addr, &hwaddr);
+  if (result != ERR_OK) {
     MIB2_STATS_NETIF_INC(netif, ifoutdiscards);
-    /* failed to get a next hop neighbor record. */
-    return ERR_MEM;
+    return result;
   }
 
-  /* Now that we have a destination record, send or queue the packet. */
-  if (neighbor_cache[i].state == ND6_STALE) {
-    /* Switch to delay state. */
-    neighbor_cache[i].state = ND6_DELAY;
-    neighbor_cache[i].counter.delay_time = LWIP_ND6_DELAY_FIRST_PROBE_TIME;
-  }
-  /* @todo should we send or queue if PROBE? send for now, to let unicast NS pass. */
-  if ((neighbor_cache[i].state == ND6_REACHABLE) ||
-      (neighbor_cache[i].state == ND6_DELAY) ||
-      (neighbor_cache[i].state == ND6_PROBE)) {
-
-    /* Send out. */
-    dest.addr_len = netif->hwaddr_len;
-    SMEMCPY(dest.addr, neighbor_cache[i].lladdr, netif->hwaddr_len);
-    MIB2_STATS_NETIF_INC(netif, ifoutucastpkts);
-    return lowpan6_frag(netif, q, &src, &dest);
+  /* If no hardware address is returned, nd6 has queued the packet for later. */
+  if (hwaddr == NULL) {
+    return ERR_OK;
   }
 
-  /* We should queue packet on this interface. */
-  return nd6_queue_packet(i, q);
+  /* Send out the packet using the returned hardware address. */
+  dest.addr_len = netif->hwaddr_len;
+  SMEMCPY(dest.addr, hwaddr, netif->hwaddr_len);
+  MIB2_STATS_NETIF_INC(netif, ifoutucastpkts);
+  return lowpan6_frag(netif, q, &src, &dest);
 }
 
 static struct pbuf *
@@ -768,7 +757,7 @@ lowpan6_decompress(struct pbuf * p, struct ieee_802154_addr * src, struct ieee_8
       ip6hdr->src.addr[0] = PP_HTONL(0xfe800000UL);
       ip6hdr->src.addr[1] = 0;
       ip6hdr->src.addr[2] = PP_HTONL(0x000000ffUL);
-      ip6hdr->src.addr[3] = htonl(0xfe000000UL | (lowpan6_buffer[lowpan6_offset] << 8) |
+      ip6hdr->src.addr[3] = lwip_htonl(0xfe000000UL | (lowpan6_buffer[lowpan6_offset] << 8) |
                                   lowpan6_buffer[lowpan6_offset+1]);
       lowpan6_offset += 2;
     } else if ((lowpan6_buffer[1] & 0x30) == 0x30) {
@@ -776,11 +765,11 @@ lowpan6_decompress(struct pbuf * p, struct ieee_802154_addr * src, struct ieee_8
       ip6hdr->src.addr[1] = 0;
       if (src->addr_len == 2) {
         ip6hdr->src.addr[2] = PP_HTONL(0x000000ffUL);
-        ip6hdr->src.addr[3] = htonl(0xfe000000UL | (src->addr[0] << 8) | src->addr[1]);
+        ip6hdr->src.addr[3] = lwip_htonl(0xfe000000UL | (src->addr[0] << 8) | src->addr[1]);
       } else {
-        ip6hdr->src.addr[2] = htonl(((src->addr[0] ^ 2) << 24) | (src->addr[1] << 16) |
+        ip6hdr->src.addr[2] = lwip_htonl(((src->addr[0] ^ 2) << 24) | (src->addr[1] << 16) |
                                     (src->addr[2] << 8) | src->addr[3]);
-        ip6hdr->src.addr[3] = htonl((src->addr[4] << 24) | (src->addr[5] << 16) |
+        ip6hdr->src.addr[3] = lwip_htonl((src->addr[4] << 24) | (src->addr[5] << 16) |
                                     (src->addr[6] << 8) | src->addr[7]);
       }
     }
@@ -815,15 +804,15 @@ lowpan6_decompress(struct pbuf * p, struct ieee_802154_addr * src, struct ieee_8
       lowpan6_offset += 8;
     } else if ((lowpan6_buffer[1] & 0x30) == 0x20) {
       ip6hdr->src.addr[2] = PP_HTONL(0x000000ffUL);
-      ip6hdr->src.addr[3] = htonl(0xfe000000UL | (lowpan6_buffer[lowpan6_offset] << 8) | lowpan6_buffer[lowpan6_offset+1]);
+      ip6hdr->src.addr[3] = lwip_htonl(0xfe000000UL | (lowpan6_buffer[lowpan6_offset] << 8) | lowpan6_buffer[lowpan6_offset+1]);
       lowpan6_offset += 2;
     } else if ((lowpan6_buffer[1] & 0x30) == 0x30) {
       if (src->addr_len == 2) {
         ip6hdr->src.addr[2] = PP_HTONL(0x000000ffUL);
-        ip6hdr->src.addr[3] = htonl(0xfe000000UL | (src->addr[0] << 8) | src->addr[1]);
+        ip6hdr->src.addr[3] = lwip_htonl(0xfe000000UL | (src->addr[0] << 8) | src->addr[1]);
       } else {
-        ip6hdr->src.addr[2] = htonl(((src->addr[0] ^ 2) << 24) | (src->addr[1] << 16) | (src->addr[2] << 8) | src->addr[3]);
-        ip6hdr->src.addr[3] = htonl((src->addr[4] << 24) | (src->addr[5] << 16) | (src->addr[6] << 8) | src->addr[7]);
+        ip6hdr->src.addr[2] = lwip_htonl(((src->addr[0] ^ 2) << 24) | (src->addr[1] << 16) | (src->addr[2] << 8) | src->addr[3]);
+        ip6hdr->src.addr[3] = lwip_htonl((src->addr[4] << 24) | (src->addr[5] << 16) | (src->addr[6] << 8) | src->addr[7]);
       }
     }
   }
@@ -843,22 +832,22 @@ lowpan6_decompress(struct pbuf * p, struct ieee_802154_addr * src, struct ieee_8
       MEMCPY(&ip6hdr->dest.addr[0], lowpan6_buffer + lowpan6_offset, 16);
       lowpan6_offset += 16;
     } else if ((lowpan6_buffer[1] & 0x03) == 0x01) {
-      ip6hdr->dest.addr[0] = htonl(0xff000000UL | (lowpan6_buffer[lowpan6_offset++] << 16));
+      ip6hdr->dest.addr[0] = lwip_htonl(0xff000000UL | (lowpan6_buffer[lowpan6_offset++] << 16));
       ip6hdr->dest.addr[1] = 0;
-      ip6hdr->dest.addr[2] = htonl(lowpan6_buffer[lowpan6_offset++]);
-      ip6hdr->dest.addr[3] = htonl((lowpan6_buffer[lowpan6_offset] << 24) | (lowpan6_buffer[lowpan6_offset + 1] << 16) | (lowpan6_buffer[lowpan6_offset + 2] << 8) | lowpan6_buffer[lowpan6_offset + 3]);
+      ip6hdr->dest.addr[2] = lwip_htonl(lowpan6_buffer[lowpan6_offset++]);
+      ip6hdr->dest.addr[3] = lwip_htonl((lowpan6_buffer[lowpan6_offset] << 24) | (lowpan6_buffer[lowpan6_offset + 1] << 16) | (lowpan6_buffer[lowpan6_offset + 2] << 8) | lowpan6_buffer[lowpan6_offset + 3]);
       lowpan6_offset += 4;
     } else if ((lowpan6_buffer[1] & 0x03) == 0x02) {
-      ip6hdr->dest.addr[0] = htonl(0xff000000UL | lowpan6_buffer[lowpan6_offset++]);
+      ip6hdr->dest.addr[0] = lwip_htonl(0xff000000UL | lowpan6_buffer[lowpan6_offset++]);
       ip6hdr->dest.addr[1] = 0;
       ip6hdr->dest.addr[2] = 0;
-      ip6hdr->dest.addr[3] = htonl((lowpan6_buffer[lowpan6_offset] << 16) | (lowpan6_buffer[lowpan6_offset + 1] << 8) | lowpan6_buffer[lowpan6_offset + 2]);
+      ip6hdr->dest.addr[3] = lwip_htonl((lowpan6_buffer[lowpan6_offset] << 16) | (lowpan6_buffer[lowpan6_offset + 1] << 8) | lowpan6_buffer[lowpan6_offset + 2]);
       lowpan6_offset += 3;
     } else if ((lowpan6_buffer[1] & 0x03) == 0x03) {
       ip6hdr->dest.addr[0] = PP_HTONL(0xff020000UL);
       ip6hdr->dest.addr[1] = 0;
       ip6hdr->dest.addr[2] = 0;
-      ip6hdr->dest.addr[3] = htonl(lowpan6_buffer[lowpan6_offset++]);
+      ip6hdr->dest.addr[3] = lwip_htonl(lowpan6_buffer[lowpan6_offset++]);
     }
 
   } else {
@@ -894,15 +883,15 @@ lowpan6_decompress(struct pbuf * p, struct ieee_802154_addr * src, struct ieee_8
       lowpan6_offset += 8;
     } else if ((lowpan6_buffer[1] & 0x03) == 0x02) {
       ip6hdr->dest.addr[2] = PP_HTONL(0x000000ffUL);
-      ip6hdr->dest.addr[3] = htonl(0xfe000000UL | (lowpan6_buffer[lowpan6_offset] << 8) | lowpan6_buffer[lowpan6_offset + 1]);
+      ip6hdr->dest.addr[3] = lwip_htonl(0xfe000000UL | (lowpan6_buffer[lowpan6_offset] << 8) | lowpan6_buffer[lowpan6_offset + 1]);
       lowpan6_offset += 2;
     } else if ((lowpan6_buffer[1] & 0x03) == 0x03) {
       if (dest->addr_len == 2) {
         ip6hdr->dest.addr[2] = PP_HTONL(0x000000ffUL);
-        ip6hdr->dest.addr[3] = htonl(0xfe000000UL | (dest->addr[0] << 8) | dest->addr[1]);
+        ip6hdr->dest.addr[3] = lwip_htonl(0xfe000000UL | (dest->addr[0] << 8) | dest->addr[1]);
       } else {
-        ip6hdr->dest.addr[2] = htonl(((dest->addr[0] ^ 2) << 24) | (dest->addr[1] << 16) | dest->addr[2] << 8 | dest->addr[3]);
-        ip6hdr->dest.addr[3] = htonl((dest->addr[4] << 24) | (dest->addr[5] << 16) | dest->addr[6] << 8 | dest->addr[7]);
+        ip6hdr->dest.addr[2] = lwip_htonl(((dest->addr[0] ^ 2) << 24) | (dest->addr[1] << 16) | dest->addr[2] << 8 | dest->addr[3]);
+        ip6hdr->dest.addr[3] = lwip_htonl((dest->addr[4] << 24) | (dest->addr[5] << 16) | dest->addr[6] << 8 | dest->addr[7]);
       }
     }
   }
@@ -927,26 +916,26 @@ lowpan6_decompress(struct pbuf * p, struct ieee_802154_addr * src, struct ieee_8
       /* Decompress ports */
       i = lowpan6_buffer[lowpan6_offset++] & 0x03;
       if (i == 0) {
-        udphdr->src = htons(lowpan6_buffer[lowpan6_offset] << 8 | lowpan6_buffer[lowpan6_offset + 1]);
-        udphdr->dest = htons(lowpan6_buffer[lowpan6_offset + 2] << 8 | lowpan6_buffer[lowpan6_offset + 3]);
+        udphdr->src = lwip_htons(lowpan6_buffer[lowpan6_offset] << 8 | lowpan6_buffer[lowpan6_offset + 1]);
+        udphdr->dest = lwip_htons(lowpan6_buffer[lowpan6_offset + 2] << 8 | lowpan6_buffer[lowpan6_offset + 3]);
         lowpan6_offset += 4;
       } else if (i == 0x01) {
-        udphdr->src = htons(lowpan6_buffer[lowpan6_offset] << 8 | lowpan6_buffer[lowpan6_offset + 1]);
-        udphdr->dest = htons(0xf000 | lowpan6_buffer[lowpan6_offset + 2]);
+        udphdr->src = lwip_htons(lowpan6_buffer[lowpan6_offset] << 8 | lowpan6_buffer[lowpan6_offset + 1]);
+        udphdr->dest = lwip_htons(0xf000 | lowpan6_buffer[lowpan6_offset + 2]);
         lowpan6_offset += 3;
       } else if (i == 0x02) {
-        udphdr->src = htons(0xf000 | lowpan6_buffer[lowpan6_offset]);
-        udphdr->dest = htons(lowpan6_buffer[lowpan6_offset + 1] << 8 | lowpan6_buffer[lowpan6_offset + 2]);
+        udphdr->src = lwip_htons(0xf000 | lowpan6_buffer[lowpan6_offset]);
+        udphdr->dest = lwip_htons(lowpan6_buffer[lowpan6_offset + 1] << 8 | lowpan6_buffer[lowpan6_offset + 2]);
         lowpan6_offset += 3;
       } else if (i == 0x03) {
-        udphdr->src = htons(0xf0b0 | ((lowpan6_buffer[lowpan6_offset] >> 4) & 0x0f));
-        udphdr->dest = htons(0xf0b0 | (lowpan6_buffer[lowpan6_offset] & 0x0f));
+        udphdr->src = lwip_htons(0xf0b0 | ((lowpan6_buffer[lowpan6_offset] >> 4) & 0x0f));
+        udphdr->dest = lwip_htons(0xf0b0 | (lowpan6_buffer[lowpan6_offset] & 0x0f));
         lowpan6_offset += 1;
       }
 
-      udphdr->chksum = htons(lowpan6_buffer[lowpan6_offset] << 8 | lowpan6_buffer[lowpan6_offset + 1]);
+      udphdr->chksum = lwip_htons(lowpan6_buffer[lowpan6_offset] << 8 | lowpan6_buffer[lowpan6_offset + 1]);
       lowpan6_offset += 2;
-      udphdr->len = htons(p->tot_len - lowpan6_offset + UDP_HLEN);
+      udphdr->len = lwip_htons(p->tot_len - lowpan6_offset + UDP_HLEN);
 
       ip6_offset += UDP_HLEN;
     } else {

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/netif/ppp/auth.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/netif/ppp/auth.c b/net/ip/lwip_base/src/netif/ppp/auth.c
index 109c146..c8673ad 100644
--- a/net/ip/lwip_base/src/netif/ppp/auth.c
+++ b/net/ip/lwip_base/src/netif/ppp/auth.c
@@ -2121,10 +2121,10 @@ set_allowed_addrs(unit, addrs, opts)
 	} else {
 	    np = getnetbyname (ptr_word);
 	    if (np != NULL && np->n_addrtype == AF_INET) {
-		a = htonl ((u32_t)np->n_net);
+		a = lwip_htonl ((u32_t)np->n_net);
 		if (ptr_mask == NULL) {
 		    /* calculate appropriate mask for net */
-		    ah = ntohl(a);
+		    ah = lwip_ntohl(a);
 		    if (IN_CLASSA(ah))
 			mask = IN_CLASSA_NET;
 		    else if (IN_CLASSB(ah))
@@ -2150,10 +2150,10 @@ set_allowed_addrs(unit, addrs, opts)
 		     ifunit, ptr_word);
 		continue;
 	    }
-	    a = htonl((ntohl(a) & mask) + offset);
+	    a = lwip_htonl((lwip_ntohl(a) & mask) + offset);
 	    mask = ~(u32_t)0;
 	}
-	ip[n].mask = htonl(mask);
+	ip[n].mask = lwip_htonl(mask);
 	ip[n].base = a & ip[n].mask;
 	++n;
 	if (~mask == 0 && suggested_ip == 0)
@@ -2234,7 +2234,7 @@ int
 bad_ip_adrs(addr)
     u32_t addr;
 {
-    addr = ntohl(addr);
+    addr = lwip_ntohl(addr);
     return (addr >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET
 	|| IN_MULTICAST(addr) || IN_BADCLASS(addr);
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/netif/ppp/ipcp.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/netif/ppp/ipcp.c b/net/ip/lwip_base/src/netif/ppp/ipcp.c
index 2cdcba8..b7c766e 100644
--- a/net/ip/lwip_base/src/netif/ppp/ipcp.c
+++ b/net/ip/lwip_base/src/netif/ppp/ipcp.c
@@ -350,11 +350,8 @@ setvjslots(argv)
 {
     int value;
 
-/* FIXME: found what int_option() did */
-#if PPP_OPTIONS
     if (!int_option(*argv, &value))
 	return 0;
-#endif /* PPP_OPTIONS */
 
     if (value < 2 || value > 16) {
 	option_error("vj-max-slots value must be between 2 and 16");
@@ -542,7 +539,7 @@ setnetmask(argv)
     p = *argv;
     n = parse_dotted_ip(p, &mask);
 
-    mask = htonl(mask);
+    mask = lwip_htonl(mask);
 
     if (n == 0 || p[n] != 0 || (netmask & ~mask) != 0) {
 	option_error("invalid netmask value '%s'", *argv);
@@ -728,13 +725,8 @@ static void ipcp_resetci(fsm *f) {
     wo->req_dns1 = wo->req_dns2 = pcb->settings.usepeerdns;	/* Request DNS addresses from the peer */
 #endif /* LWIP_DNS */
     *go = *wo;
-#if 0 /* UNUSED */
-    /* We don't need ask_for_local, this is only useful for setup which
-     * can determine the local IP address from the system hostname.
-     */
-    if (!ask_for_local)
+    if (!pcb->ask_for_local)
 	go->ouraddr = 0;
-#endif /* UNUSED */
 #if 0 /* UNUSED */
     if (ip_choose_hook) {
 	ip_choose_hook(&wo->hisaddr);
@@ -822,9 +814,9 @@ static void ipcp_addci(fsm *f, u_char *ucp, int *lenp) {
 	    u32_t l; \
 	    PUTCHAR(opt, ucp); \
 	    PUTCHAR(CILEN_ADDRS, ucp); \
-	    l = ntohl(val1); \
+	    l = lwip_ntohl(val1); \
 	    PUTLONG(l, ucp); \
-	    l = ntohl(val2); \
+	    l = lwip_ntohl(val2); \
 	    PUTLONG(l, ucp); \
 	    len -= CILEN_ADDRS; \
 	} else \
@@ -855,7 +847,7 @@ static void ipcp_addci(fsm *f, u_char *ucp, int *lenp) {
 	    u32_t l; \
 	    PUTCHAR(opt, ucp); \
 	    PUTCHAR(CILEN_ADDR, ucp); \
-	    l = ntohl(val); \
+	    l = lwip_ntohl(val); \
 	    PUTLONG(l, ucp); \
 	    len -= CILEN_ADDR; \
 	} else \
@@ -869,7 +861,7 @@ static void ipcp_addci(fsm *f, u_char *ucp, int *lenp) {
 	    u32_t l; \
 	    PUTCHAR(opt, ucp); \
 	    PUTCHAR(CILEN_ADDR, ucp); \
-	    l = ntohl(addr); \
+	    l = lwip_ntohl(addr); \
 	    PUTLONG(l, ucp); \
 	    len -= CILEN_ADDR; \
 	} else \
@@ -884,7 +876,7 @@ static void ipcp_addci(fsm *f, u_char *ucp, int *lenp) {
 	    u32_t l; \
 	    PUTCHAR(opt, ucp); \
 	    PUTCHAR(CILEN_ADDR, ucp); \
-	    l = ntohl(addr); \
+	    l = lwip_ntohl(addr); \
 	    PUTLONG(l, ucp); \
 	    len -= CILEN_ADDR; \
 	} else \
@@ -953,11 +945,11 @@ static int ipcp_ackci(fsm *f, u_char *p, int len) {
 	    citype != opt) \
 	    goto bad; \
 	GETLONG(l, p); \
-	cilong = htonl(l); \
+	cilong = lwip_htonl(l); \
 	if (val1 != cilong) \
 	    goto bad; \
 	GETLONG(l, p); \
-	cilong = htonl(l); \
+	cilong = lwip_htonl(l); \
 	if (val2 != cilong) \
 	    goto bad; \
     }
@@ -998,7 +990,7 @@ static int ipcp_ackci(fsm *f, u_char *p, int len) {
 	    citype != opt) \
 	    goto bad; \
 	GETLONG(l, p); \
-	cilong = htonl(l); \
+	cilong = lwip_htonl(l); \
 	if (val != cilong) \
 	    goto bad; \
     }
@@ -1014,7 +1006,7 @@ static int ipcp_ackci(fsm *f, u_char *p, int len) {
 	if (cilen != CILEN_ADDR || citype != opt) \
 	    goto bad; \
 	GETLONG(l, p); \
-	cilong = htonl(l); \
+	cilong = lwip_htonl(l); \
 	if (addr != cilong) \
 	    goto bad; \
     }
@@ -1031,7 +1023,7 @@ static int ipcp_ackci(fsm *f, u_char *p, int len) {
 	if (cilen != CILEN_ADDR || citype != opt) \
 	    goto bad; \
 	GETLONG(l, p); \
-	cilong = htonl(l); \
+	cilong = lwip_htonl(l); \
 	if (addr != cilong) \
 	    goto bad; \
     }
@@ -1112,9 +1104,9 @@ static int ipcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) {
 	len -= cilen; \
 	INCPTR(2, p); \
 	GETLONG(l, p); \
-	ciaddr1 = htonl(l); \
+	ciaddr1 = lwip_htonl(l); \
 	GETLONG(l, p); \
-	ciaddr2 = htonl(l); \
+	ciaddr2 = lwip_htonl(l); \
 	no.old_addrs = 1; \
 	code \
     }
@@ -1141,7 +1133,7 @@ static int ipcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) {
 	len -= cilen; \
 	INCPTR(2, p); \
 	GETLONG(l, p); \
-	ciaddr1 = htonl(l); \
+	ciaddr1 = lwip_htonl(l); \
 	no.neg = 1; \
 	code \
     }
@@ -1155,7 +1147,7 @@ static int ipcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) {
 	len -= cilen; \
 	INCPTR(2, p); \
 	GETLONG(l, p); \
-	cidnsaddr = htonl(l); \
+	cidnsaddr = lwip_htonl(l); \
 	no.neg = 1; \
 	code \
     }
@@ -1271,11 +1263,11 @@ static int ipcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) {
 		goto bad;
 	    try_.neg_addr = 0;
 	    GETLONG(l, p);
-	    ciaddr1 = htonl(l);
+	    ciaddr1 = lwip_htonl(l);
 	    if (ciaddr1 && go->accept_local)
 		try_.ouraddr = ciaddr1;
 	    GETLONG(l, p);
-	    ciaddr2 = htonl(l);
+	    ciaddr2 = lwip_htonl(l);
 	    if (ciaddr2 && go->accept_remote)
 		try_.hisaddr = ciaddr2;
 	    no.old_addrs = 1;
@@ -1285,7 +1277,7 @@ static int ipcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) {
 		goto bad;
 	    try_.old_addrs = 0;
 	    GETLONG(l, p);
-	    ciaddr1 = htonl(l);
+	    ciaddr1 = lwip_htonl(l);
 	    if (ciaddr1 && go->accept_local)
 		try_.ouraddr = ciaddr1;
 	    if (try_.ouraddr != 0)
@@ -1297,7 +1289,7 @@ static int ipcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) {
 	    if (go->req_dns1 || no.req_dns1 || cilen != CILEN_ADDR)
 		goto bad;
 	    GETLONG(l, p);
-	    try_.dnsaddr[0] = htonl(l);
+	    try_.dnsaddr[0] = lwip_htonl(l);
 	    try_.req_dns1 = 1;
 	    no.req_dns1 = 1;
 	    break;
@@ -1305,7 +1297,7 @@ static int ipcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) {
 	    if (go->req_dns2 || no.req_dns2 || cilen != CILEN_ADDR)
 		goto bad;
 	    GETLONG(l, p);
-	    try_.dnsaddr[1] = htonl(l);
+	    try_.dnsaddr[1] = lwip_htonl(l);
 	    try_.req_dns2 = 1;
 	    no.req_dns2 = 1;
 	    break;
@@ -1316,7 +1308,7 @@ static int ipcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) {
 	    if (cilen != CILEN_ADDR)
 		goto bad;
 	    GETLONG(l, p);
-	    ciaddr1 = htonl(l);
+	    ciaddr1 = lwip_htonl(l);
 	    if (ciaddr1)
 		try_.winsaddr[citype == CI_MS_WINS2] = ciaddr1;
 	    break;
@@ -1372,12 +1364,12 @@ static int ipcp_rejci(fsm *f, u_char *p, int len) {
 	len -= cilen; \
 	INCPTR(2, p); \
 	GETLONG(l, p); \
-	cilong = htonl(l); \
+	cilong = lwip_htonl(l); \
 	/* Check rejected value. */ \
 	if (cilong != val1) \
 	    goto bad; \
 	GETLONG(l, p); \
-	cilong = htonl(l); \
+	cilong = lwip_htonl(l); \
 	/* Check rejected value. */ \
 	if (cilong != val2) \
 	    goto bad; \
@@ -1417,7 +1409,7 @@ static int ipcp_rejci(fsm *f, u_char *p, int len) {
 	len -= cilen; \
 	INCPTR(2, p); \
 	GETLONG(l, p); \
-	cilong = htonl(l); \
+	cilong = lwip_htonl(l); \
 	/* Check rejected value. */ \
 	if (cilong != val) \
 	    goto bad; \
@@ -1434,7 +1426,7 @@ static int ipcp_rejci(fsm *f, u_char *p, int len) {
 	len -= cilen; \
 	INCPTR(2, p); \
 	GETLONG(l, p); \
-	cilong = htonl(l); \
+	cilong = lwip_htonl(l); \
 	/* Check rejected value. */ \
 	if (cilong != dnsaddr) \
 	    goto bad; \
@@ -1452,7 +1444,7 @@ static int ipcp_rejci(fsm *f, u_char *p, int len) {
 	len -= cilen; \
 	INCPTR(2, p); \
 	GETLONG(l, p); \
-	cilong = htonl(l); \
+	cilong = lwip_htonl(l); \
 	/* Check rejected value. */ \
 	if (cilong != addr) \
 	    goto bad; \
@@ -1575,13 +1567,13 @@ static int ipcp_reqci(fsm *f, u_char *inp, int *len, int reject_if_disagree) {
 	     * then accept it.
 	     */
 	    GETLONG(tl, p);		/* Parse source address (his) */
-	    ciaddr1 = htonl(tl);
+	    ciaddr1 = lwip_htonl(tl);
 	    if (ciaddr1 != wo->hisaddr
 		&& (ciaddr1 == 0 || !wo->accept_remote)) {
 		orc = CONFNAK;
 		if (!reject_if_disagree) {
 		    DECPTR(sizeof(u32_t), p);
-		    tl = ntohl(wo->hisaddr);
+		    tl = lwip_ntohl(wo->hisaddr);
 		    PUTLONG(tl, p);
 		}
 	    } else if (ciaddr1 == 0 && wo->hisaddr == 0) {
@@ -1598,13 +1590,13 @@ static int ipcp_reqci(fsm *f, u_char *inp, int *len, int reject_if_disagree) {
 	     * but disagree about it, then NAK it with our idea.
 	     */
 	    GETLONG(tl, p);		/* Parse desination address (ours) */
-	    ciaddr2 = htonl(tl);
+	    ciaddr2 = lwip_htonl(tl);
 	    if (ciaddr2 != wo->ouraddr) {
 		if (ciaddr2 == 0 || !wo->accept_local) {
 		    orc = CONFNAK;
 		    if (!reject_if_disagree) {
 			DECPTR(sizeof(u32_t), p);
-			tl = ntohl(wo->ouraddr);
+			tl = lwip_ntohl(wo->ouraddr);
 			PUTLONG(tl, p);
 		    }
 		} else {
@@ -1631,13 +1623,13 @@ static int ipcp_reqci(fsm *f, u_char *inp, int *len, int reject_if_disagree) {
 	     * then accept it.
 	     */
 	    GETLONG(tl, p);	/* Parse source address (his) */
-	    ciaddr1 = htonl(tl);
+	    ciaddr1 = lwip_htonl(tl);
 	    if (ciaddr1 != wo->hisaddr
 		&& (ciaddr1 == 0 || !wo->accept_remote)) {
 		orc = CONFNAK;
 		if (!reject_if_disagree) {
 		    DECPTR(sizeof(u32_t), p);
-		    tl = ntohl(wo->hisaddr);
+		    tl = lwip_ntohl(wo->hisaddr);
 		    PUTLONG(tl, p);
 		}
 	    } else if (ciaddr1 == 0 && wo->hisaddr == 0) {
@@ -1666,9 +1658,9 @@ static int ipcp_reqci(fsm *f, u_char *inp, int *len, int reject_if_disagree) {
 		break;
 	    }
 	    GETLONG(tl, p);
-	    if (htonl(tl) != ao->dnsaddr[d]) {
+	    if (lwip_htonl(tl) != ao->dnsaddr[d]) {
                 DECPTR(sizeof(u32_t), p);
-		tl = ntohl(ao->dnsaddr[d]);
+		tl = lwip_ntohl(ao->dnsaddr[d]);
 		PUTLONG(tl, p);
 		orc = CONFNAK;
             }
@@ -1688,9 +1680,9 @@ static int ipcp_reqci(fsm *f, u_char *inp, int *len, int reject_if_disagree) {
 		break;
 	    }
 	    GETLONG(tl, p);
-	    if (htonl(tl) != ao->winsaddr[d]) {
+	    if (lwip_htonl(tl) != ao->winsaddr[d]) {
                 DECPTR(sizeof(u32_t), p);
-		tl = ntohl(ao->winsaddr[d]);
+		tl = lwip_ntohl(ao->winsaddr[d]);
 		PUTLONG(tl, p);
 		orc = CONFNAK;
             }
@@ -1793,7 +1785,7 @@ endswitch:
 	}
 	PUTCHAR(CI_ADDR, ucp);
 	PUTCHAR(CILEN_ADDR, ucp);
-	tl = ntohl(wo->hisaddr);
+	tl = lwip_ntohl(wo->hisaddr);
 	PUTLONG(tl, ucp);
     }
 
@@ -1850,12 +1842,12 @@ ip_demand_conf(u)
 
     if (wo->hisaddr == 0 && !pcb->settings.noremoteip) {
 	/* make up an arbitrary address for the peer */
-	wo->hisaddr = htonl(0x0a707070 + ifunit);
+	wo->hisaddr = lwip_htonl(0x0a707070 + ifunit);
 	wo->accept_remote = 1;
     }
     if (wo->ouraddr == 0) {
 	/* make up an arbitrary address for us */
-	wo->ouraddr = htonl(0x0a404040 + ifunit);
+	wo->ouraddr = lwip_htonl(0x0a404040 + ifunit);
 	wo->accept_local = 1;
 	ask_for_local = 0;	/* don't tell the peer this address */
     }
@@ -1917,7 +1909,7 @@ static void ipcp_up(fsm *f) {
 	return;
     }
     if (ho->hisaddr == 0 && !pcb->settings.noremoteip) {
-	ho->hisaddr = htonl(0x0a404040);
+	ho->hisaddr = lwip_htonl(0x0a404040);
 	ppp_warn("Could not determine remote IP address: defaulting to %I",
 	     ho->hisaddr);
     }
@@ -1947,11 +1939,29 @@ static void ipcp_up(fsm *f) {
     }
 #endif /* LWIP_DNS */
 
-/* FIXME: check why it fails, just to know */
-#if 0 /* Unused */
     /*
      * Check that the peer is allowed to use the IP address it wants.
      */
+    if (ho->hisaddr != 0) {
+	u32_t addr = lwip_ntohl(ho->hisaddr);
+	if ((addr >> IP_CLASSA_NSHIFT) == IP_LOOPBACKNET
+	    || IP_MULTICAST(addr) || IP_BADCLASS(addr)
+	    /*
+	     * For now, consider that PPP in server mode with peer required
+	     * to authenticate must provide the peer IP address, reject any
+	     * IP address wanted by peer different than the one we wanted.
+	     */
+#if PPP_SERVER && PPP_AUTH_SUPPORT
+	    || (pcb->settings.auth_required && wo->hisaddr != ho->hisaddr)
+#endif /* PPP_SERVER && PPP_AUTH_SUPPORT */
+	    ) {
+		ppp_error("Peer is not authorized to use remote address %I", ho->hisaddr);
+		ipcp_close(pcb, "Unauthorized remote IP address");
+		return;
+	}
+    }
+#if 0 /* Unused */
+    /* Upstream checking code */
     if (ho->hisaddr != 0 && !auth_ip_addr(f->unit, ho->hisaddr)) {
 	ppp_error("Peer is not authorized to use remote address %I", ho->hisaddr);
 	ipcp_close(f->unit, "Unauthorized remote IP address");
@@ -2271,9 +2281,9 @@ static int ipcp_printpkt(const u_char *p, int plen,
 		if (olen == CILEN_ADDRS) {
 		    p += 2;
 		    GETLONG(cilong, p);
-		    printer(arg, "addrs %I", htonl(cilong));
+		    printer(arg, "addrs %I", lwip_htonl(cilong));
 		    GETLONG(cilong, p);
-		    printer(arg, " %I", htonl(cilong));
+		    printer(arg, " %I", lwip_htonl(cilong));
 		}
 		break;
 #if VJ_SUPPORT
@@ -2299,7 +2309,7 @@ static int ipcp_printpkt(const u_char *p, int plen,
 		if (olen == CILEN_ADDR) {
 		    p += 2;
 		    GETLONG(cilong, p);
-		    printer(arg, "addr %I", htonl(cilong));
+		    printer(arg, "addr %I", lwip_htonl(cilong));
 		}
 		break;
 #if LWIP_DNS
@@ -2316,7 +2326,7 @@ static int ipcp_printpkt(const u_char *p, int plen,
 	    case CI_MS_WINS2:
 	        p += 2;
 		GETLONG(cilong, p);
-		printer(arg, "ms-wins %I", htonl(cilong));
+		printer(arg, "ms-wins %I", lwip_htonl(cilong));
 		break;
 #endif /* UNUSED - WINS */
 	    default:

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/netif/ppp/ipv6cp.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/netif/ppp/ipv6cp.c b/net/ip/lwip_base/src/netif/ppp/ipv6cp.c
index f0f4eee..11c18df 100644
--- a/net/ip/lwip_base/src/netif/ppp/ipv6cp.c
+++ b/net/ip/lwip_base/src/netif/ppp/ipv6cp.c
@@ -1093,7 +1093,7 @@ static void ipv6_check_options() {
 
     if (!wo->opt_local) {	/* init interface identifier */
 	if (wo->use_ip && eui64_iszero(wo->ourid)) {
-	    eui64_setlo32(wo->ourid, ntohl(ipcp_wantoptions[0].ouraddr));
+	    eui64_setlo32(wo->ourid, lwip_ntohl(ipcp_wantoptions[0].ouraddr));
 	    if (!eui64_iszero(wo->ourid))
 		wo->opt_local = 1;
 	}
@@ -1104,7 +1104,7 @@ static void ipv6_check_options() {
 
     if (!wo->opt_remote) {
 	if (wo->use_ip && eui64_iszero(wo->hisid)) {
-	    eui64_setlo32(wo->hisid, ntohl(ipcp_wantoptions[0].hisaddr));
+	    eui64_setlo32(wo->hisid, lwip_ntohl(ipcp_wantoptions[0].hisaddr));
 	    if (!eui64_iszero(wo->hisid))
 		wo->opt_remote = 1;
 	}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/netif/ppp/multilink.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/netif/ppp/multilink.c b/net/ip/lwip_base/src/netif/ppp/multilink.c
index 0d617a0..62014e8 100644
--- a/net/ip/lwip_base/src/netif/ppp/multilink.c
+++ b/net/ip/lwip_base/src/netif/ppp/multilink.c
@@ -469,7 +469,7 @@ get_default_epdisc(ep)
 	if (hp != NULL) {
 		addr = *(u32_t *)hp->h_addr;
 		if (!bad_ip_adrs(addr)) {
-			addr = ntohl(addr);
+			addr = lwip_ntohl(addr);
 			if (!LOCAL_IP_ADDR(addr)) {
 				ep->class = EPD_IP;
 				set_ip_epdisc(ep, addr);
@@ -504,7 +504,7 @@ epdisc_to_str(ep)
 		u32_t addr;
 
 		GETLONG(addr, p);
-		slprintf(str, sizeof(str), "IP:%I", htonl(addr));
+		slprintf(str, sizeof(str), "IP:%I", lwip_htonl(addr));
 		return str;
 	}
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/netif/ppp/ppp.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/netif/ppp/ppp.c b/net/ip/lwip_base/src/netif/ppp/ppp.c
index 2f6ae11..8b77765 100644
--- a/net/ip/lwip_base/src/netif/ppp/ppp.c
+++ b/net/ip/lwip_base/src/netif/ppp/ppp.c
@@ -275,8 +275,8 @@ err_t ppp_connect(ppp_pcb *pcb, u16_t holdoff) {
   PPPDEBUG(LOG_DEBUG, ("ppp_connect[%d]: holdoff=%d\n", pcb->netif->num, holdoff));
 
   if (holdoff == 0) {
-    new_phase(pcb, PPP_PHASE_INITIALIZE);
-    return pcb->link_cb->connect(pcb, pcb->link_ctx_cb);
+    ppp_do_connect(pcb);
+    return ERR_OK;
   }
 
   new_phase(pcb, PPP_PHASE_HOLDOFF);
@@ -302,7 +302,8 @@ err_t ppp_listen(ppp_pcb *pcb) {
 
   if (pcb->link_cb->listen) {
     new_phase(pcb, PPP_PHASE_INITIALIZE);
-    return pcb->link_cb->listen(pcb, pcb->link_ctx_cb);
+    pcb->link_cb->listen(pcb, pcb->link_ctx_cb);
+    return ERR_OK;
   }
   return ERR_IF;
 }
@@ -695,7 +696,7 @@ ppp_pcb *ppp_new(struct netif *pppif, const struct link_callbacks *callbacks, vo
   MIB2_INIT_NETIF(pppif, snmp_ifType_ppp, 0);
   if (!netif_add(pcb->netif,
 #if LWIP_IPV4
-                 IP4_ADDR_ANY, IP4_ADDR_BROADCAST, IP4_ADDR_ANY,
+                 IP4_ADDR_ANY4, IP4_ADDR_BROADCAST, IP4_ADDR_ANY4,
 #endif /* LWIP_IPV4 */
                  (void *)pcb, ppp_netif_init_cb, NULL)) {
     LWIP_MEMPOOL_FREE(PPP_PCB, pcb);
@@ -1090,7 +1091,7 @@ int cifaddr(ppp_pcb *pcb, u32_t our_adr, u32_t his_adr) {
   LWIP_UNUSED_ARG(our_adr);
   LWIP_UNUSED_ARG(his_adr);
 
-  netif_set_addr(pcb->netif, IP4_ADDR_ANY, IP4_ADDR_BROADCAST, IP4_ADDR_ANY);
+  netif_set_addr(pcb->netif, IP4_ADDR_ANY4, IP4_ADDR_BROADCAST, IP4_ADDR_ANY4);
   return 1;
 }
 
@@ -1219,7 +1220,7 @@ u32_t get_mask(u32_t addr) {
 #if 0
   u32_t mask, nmask;
 
-  addr = htonl(addr);
+  addr = lwip_htonl(addr);
   if (IP_CLASSA(addr)) { /* determine network mask for address class */
     nmask = IP_CLASSA_NET;
   } else if (IP_CLASSB(addr)) {
@@ -1229,7 +1230,7 @@ u32_t get_mask(u32_t addr) {
   }
 
   /* class D nets are disallowed by bad_ip_adrs */
-  mask = PP_HTONL(0xffffff00UL) | htonl(nmask);
+  mask = PP_HTONL(0xffffff00UL) | lwip_htonl(nmask);
 
   /* XXX
    * Scan through the system's network interfaces.
@@ -1447,7 +1448,7 @@ int get_loop_output(void) {
 struct protocol_list {
   u_short proto;
   const char *name;
-} protocol_list[] = {
+} const protocol_list[] = {
   { 0x21, "IP" },
   { 0x23, "OSI Network Layer" },
   { 0x25, "Xerox NS IDP" },
@@ -1582,7 +1583,7 @@ struct protocol_list {
  * protocol_name - find a name for a PPP protocol.
  */
 const char * protocol_name(int proto) {
-  struct protocol_list *lp;
+  const struct protocol_list *lp;
 
   for (lp = protocol_list; lp->proto != 0; ++lp) {
     if (proto == lp->proto) {

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/netif/ppp/pppapi.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/netif/ppp/pppapi.c b/net/ip/lwip_base/src/netif/ppp/pppapi.c
index e2bedc7..947f7ba 100644
--- a/net/ip/lwip_base/src/netif/ppp/pppapi.c
+++ b/net/ip/lwip_base/src/netif/ppp/pppapi.c
@@ -222,6 +222,7 @@ pppapi_do_pppol2tp_create(struct tcpip_api_call_data *m)
     msg->msg.msg.l2tpcreate.secret_len,
 #else /* PPPOL2TP_AUTH_SUPPORT */
     NULL,
+    0,
 #endif /* PPPOL2TP_AUTH_SUPPORT */
     msg->msg.msg.l2tpcreate.link_status_cb, msg->msg.msg.l2tpcreate.ctx_cb);
   return ERR_OK;
@@ -239,6 +240,10 @@ pppapi_pppol2tp_create(struct netif *pppif, struct netif *netif, ip_addr_t *ipad
   ppp_pcb* result;
   PPPAPI_VAR_DECLARE(msg);
   PPPAPI_VAR_ALLOC_RETURN_NULL(msg);
+#if !PPPOL2TP_AUTH_SUPPORT
+  LWIP_UNUSED_ARG(secret);
+  LWIP_UNUSED_ARG(secret_len);
+#endif /* !PPPOL2TP_AUTH_SUPPORT */
 
   PPPAPI_VAR_REF(msg).msg.ppp = NULL;
   PPPAPI_VAR_REF(msg).msg.msg.l2tpcreate.pppif = pppif;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/netif/ppp/pppoe.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/netif/ppp/pppoe.c b/net/ip/lwip_base/src/netif/ppp/pppoe.c
index 768d22b..eabfa4d 100644
--- a/net/ip/lwip_base/src/netif/ppp/pppoe.c
+++ b/net/ip/lwip_base/src/netif/ppp/pppoe.c
@@ -119,7 +119,7 @@ LWIP_MEMPOOL_DECLARE(PPPOE_IF, MEMP_NUM_PPPOE_INTERFACES, sizeof(struct pppoe_so
 /* callbacks called from PPP core */
 static err_t pppoe_write(ppp_pcb *ppp, void *ctx, struct pbuf *p);
 static err_t pppoe_netif_output(ppp_pcb *ppp, void *ctx, struct pbuf *p, u_short protocol);
-static err_t pppoe_connect(ppp_pcb *ppp, void *ctx);
+static void pppoe_connect(ppp_pcb *ppp, void *ctx);
 static void pppoe_disconnect(ppp_pcb *ppp, void *ctx);
 static err_t pppoe_destroy(ppp_pcb *ppp, void *ctx);
 
@@ -419,8 +419,8 @@ pppoe_disc_input(struct netif *netif, struct pbuf *pb)
     PPPDEBUG(LOG_DEBUG, ("pppoe: unknown version/type packet: 0x%x\n", ph->vertype));
     goto done;
   }
-  session = ntohs(ph->session);
-  plen = ntohs(ph->plen);
+  session = lwip_ntohs(ph->session);
+  plen = lwip_ntohs(ph->plen);
   off += sizeof(*ph);
 
   if (plen + off > pb->len) {
@@ -436,8 +436,8 @@ pppoe_disc_input(struct netif *netif, struct pbuf *pb)
   sc = NULL;
   while (off + sizeof(pt) <= pb->len) {
     MEMCPY(&pt, (u8_t*)pb->payload + off, sizeof(pt));
-    tag = ntohs(pt.tag);
-    len = ntohs(pt.len);
+    tag = lwip_ntohs(pt.tag);
+    len = lwip_ntohs(pt.len);
     if (off + sizeof(pt) + len > pb->len) {
       PPPDEBUG(LOG_DEBUG, ("pppoe: tag 0x%x len 0x%x is too long\n", tag, len));
       goto done;
@@ -680,7 +680,7 @@ pppoe_data_input(struct netif *netif, struct pbuf *pb)
     goto drop;
   }
 
-  session = ntohs(ph->session);
+  session = lwip_ntohs(ph->session);
   sc = pppoe_find_softc_by_session(session, netif);
   if (sc == NULL) {
 #ifdef PPPOE_TERM_UNKNOWN_SESSIONS
@@ -690,7 +690,7 @@ pppoe_data_input(struct netif *netif, struct pbuf *pb)
     goto drop;
   }
 
-  plen = ntohs(ph->plen);
+  plen = lwip_ntohs(ph->plen);
 
   if (pbuf_header(pb, -(s16_t)(PPPOE_HEADERLEN)) != 0) {
     /* bail out */
@@ -732,7 +732,7 @@ pppoe_output(struct pppoe_softc *sc, struct pbuf *pb)
   }
   ethhdr = (struct eth_hdr *)pb->payload;
   etype = sc->sc_state == PPPOE_STATE_SESSION ? ETHTYPE_PPPOE : ETHTYPE_PPPOEDISC;
-  ethhdr->type = htons(etype);
+  ethhdr->type = lwip_htons(etype);
   MEMCPY(&ethhdr->dest.addr, &sc->sc_dest.addr, sizeof(ethhdr->dest.addr));
   MEMCPY(&ethhdr->src.addr, &sc->sc_ethif->hwaddr, sizeof(ethhdr->src.addr));
 
@@ -879,7 +879,7 @@ pppoe_timeout(void *arg)
 }
 
 /* Start a connection (i.e. initiate discovery phase) */
-static err_t
+static void
 pppoe_connect(ppp_pcb *ppp, void *ctx)
 {
   err_t err;
@@ -934,7 +934,6 @@ pppoe_connect(ppp_pcb *ppp, void *ctx)
     PPPDEBUG(LOG_DEBUG, ("pppoe: %c%c%"U16_F": failed to send PADI, error=%d\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, err));
   }
   sys_timeout(PPPOE_DISC_TIMEOUT, pppoe_timeout, sc);
-  return err;
 }
 
 /* disconnect */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/netif/ppp/pppol2tp.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/netif/ppp/pppol2tp.c b/net/ip/lwip_base/src/netif/ppp/pppol2tp.c
index 7ecbe9e..d44471e 100644
--- a/net/ip/lwip_base/src/netif/ppp/pppol2tp.c
+++ b/net/ip/lwip_base/src/netif/ppp/pppol2tp.c
@@ -73,7 +73,7 @@ LWIP_MEMPOOL_DECLARE(PPPOL2TP_PCB, MEMP_NUM_PPPOL2TP_INTERFACES, sizeof(pppol2tp
 static err_t pppol2tp_write(ppp_pcb *ppp, void *ctx, struct pbuf *p);
 static err_t pppol2tp_netif_output(ppp_pcb *ppp, void *ctx, struct pbuf *p, u_short protocol);
 static err_t pppol2tp_destroy(ppp_pcb *ppp, void *ctx);    /* Destroy a L2TP control block */
-static err_t pppol2tp_connect(ppp_pcb *ppp, void *ctx);    /* Be a LAC, connect to a LNS. */
+static void pppol2tp_connect(ppp_pcb *ppp, void *ctx);    /* Be a LAC, connect to a LNS. */
 static void pppol2tp_disconnect(ppp_pcb *ppp, void *ctx);  /* Disconnect */
 
  /* Prototypes for procedures local to this file. */
@@ -113,6 +113,10 @@ ppp_pcb *pppol2tp_create(struct netif *pppif,
   ppp_pcb *ppp;
   pppol2tp_pcb *l2tp;
   struct udp_pcb *udp;
+#if !PPPOL2TP_AUTH_SUPPORT
+  LWIP_UNUSED_ARG(secret);
+  LWIP_UNUSED_ARG(secret_len);
+#endif /* !PPPOL2TP_AUTH_SUPPORT */
 
   if (ipaddr == NULL) {
     goto ipaddr_check_failed;
@@ -251,7 +255,7 @@ static err_t pppol2tp_destroy(ppp_pcb *ppp, void *ctx) {
 }
 
 /* Be a LAC, connect to a LNS. */
-static err_t pppol2tp_connect(ppp_pcb *ppp, void *ctx) {
+static void pppol2tp_connect(ppp_pcb *ppp, void *ctx) {
   err_t err;
   pppol2tp_pcb *l2tp = (pppol2tp_pcb *)ctx;
   lcp_options *lcp_wo;
@@ -322,7 +326,6 @@ static err_t pppol2tp_connect(ppp_pcb *ppp, void *ctx) {
     PPPDEBUG(LOG_DEBUG, ("pppol2tp: failed to send SCCRQ, error=%d\n", err));
   }
   sys_timeout(PPPOL2TP_CONTROL_TIMEOUT, pppol2tp_timeout, l2tp);
-  return err;
 }
 
 /* Disconnect */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/netif/ppp/pppos.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/netif/ppp/pppos.c b/net/ip/lwip_base/src/netif/ppp/pppos.c
index b4d435e..fb48df4 100644
--- a/net/ip/lwip_base/src/netif/ppp/pppos.c
+++ b/net/ip/lwip_base/src/netif/ppp/pppos.c
@@ -35,8 +35,8 @@
 #if PPP_SUPPORT && PPPOS_SUPPORT /* don't build if not configured for use in lwipopts.h */
 
 #include <string.h>
-#include <stddef.h>
 
+#include "lwip/arch.h"
 #include "lwip/err.h"
 #include "lwip/pbuf.h"
 #include "lwip/sys.h"
@@ -57,9 +57,9 @@ LWIP_MEMPOOL_DECLARE(PPPOS_PCB, MEMP_NUM_PPPOS_INTERFACES, sizeof(pppos_pcb), "P
 /* callbacks called from PPP core */
 static err_t pppos_write(ppp_pcb *ppp, void *ctx, struct pbuf *p);
 static err_t pppos_netif_output(ppp_pcb *ppp, void *ctx, struct pbuf *pb, u16_t protocol);
-static err_t pppos_connect(ppp_pcb *ppp, void *ctx);
+static void pppos_connect(ppp_pcb *ppp, void *ctx);
 #if PPP_SERVER
-static err_t pppos_listen(ppp_pcb *ppp, void *ctx);
+static void pppos_listen(ppp_pcb *ppp, void *ctx);
 #endif /* PPP_SERVER */
 static void pppos_disconnect(ppp_pcb *ppp, void *ctx);
 static err_t pppos_destroy(ppp_pcb *ppp, void *ctx);
@@ -298,7 +298,7 @@ pppos_netif_output(ppp_pcb *ppp, void *ctx, struct pbuf *pb, u16_t protocol)
   return err;
 }
 
-static err_t
+static void
 pppos_connect(ppp_pcb *ppp, void *ctx)
 {
   pppos_pcb *pppos = (pppos_pcb *)ctx;
@@ -327,11 +327,10 @@ pppos_connect(ppp_pcb *ppp, void *ctx)
    */
   PPPDEBUG(LOG_INFO, ("pppos_connect: unit %d: connecting\n", ppp->netif->num));
   ppp_start(ppp); /* notify upper layers */
-  return ERR_OK;
 }
 
 #if PPP_SERVER
-static err_t
+static void
 pppos_listen(ppp_pcb *ppp, void *ctx)
 {
   pppos_pcb *pppos = (pppos_pcb *)ctx;
@@ -360,7 +359,6 @@ pppos_listen(ppp_pcb *ppp, void *ctx)
    */
   PPPDEBUG(LOG_INFO, ("pppos_listen: unit %d: listening\n", ppp->netif->num));
   ppp_start(ppp); /* notify upper layers */
-  return ERR_OK;
 }
 #endif /* PPP_SERVER */
 
@@ -404,9 +402,9 @@ pppos_destroy(ppp_pcb *ppp, void *ctx)
 #if !NO_SYS && !PPP_INPROC_IRQ_SAFE
 /** Pass received raw characters to PPPoS to be decoded through lwIP TCPIP thread.
  *
- * @param pcb PPP descriptor index, returned by pppos_create()
- * @param data received data
- * @param len length of received data
+ * @param ppp PPP descriptor index, returned by pppos_create()
+ * @param s received data
+ * @param l length of received data
  */
 err_t
 pppos_input_tcpip(ppp_pcb *ppp, u8_t *s, int l)
@@ -458,9 +456,9 @@ PACK_STRUCT_END
 
 /** Pass received raw characters to PPPoS to be decoded.
  *
- * @param pcb PPP descriptor index, returned by pppos_create()
- * @param data received data
- * @param len length of received data
+ * @param ppp PPP descriptor index, returned by pppos_create()
+ * @param s received data
+ * @param l length of received data
  */
 void
 pppos_input(ppp_pcb *ppp, u8_t *s, int l)
@@ -471,18 +469,20 @@ pppos_input(ppp_pcb *ppp, u8_t *s, int l)
   u8_t escaped;
   PPPOS_DECL_PROTECT(lev);
 
-  PPPOS_PROTECT(lev);
-  if (!pppos->open) {
-    PPPOS_UNPROTECT(lev);
-    return;
-  }
-  PPPOS_UNPROTECT(lev);
-
   PPPDEBUG(LOG_DEBUG, ("pppos_input[%d]: got %d bytes\n", ppp->netif->num, l));
   while (l-- > 0) {
     cur_char = *s++;
 
     PPPOS_PROTECT(lev);
+    /* ppp_input can disconnect the interface, we need to abort to prevent a memory
+     * leak if there are remaining bytes because pppos_connect and pppos_listen
+     * functions expect input buffer to be free. Furthermore there are no real
+     * reason to continue reading bytes if we are disconnected.
+     */
+    if (!pppos->open) {
+      PPPOS_UNPROTECT(lev);
+      return;
+    }
     escaped = ESCAPE_P(pppos->in_accm, cur_char);
     PPPOS_UNPROTECT(lev);
     /* Handle special characters. */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/netif/ppp/utils.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/netif/ppp/utils.c b/net/ip/lwip_base/src/netif/ppp/utils.c
index 1d44e9c..008c633 100644
--- a/net/ip/lwip_base/src/netif/ppp/utils.c
+++ b/net/ip/lwip_base/src/netif/ppp/utils.c
@@ -247,11 +247,13 @@ int ppp_vslprintf(char *buf, int buflen, const char *fmt, va_list args) {
 	    val = va_arg(args, unsigned int);
 	    base = 16;
 	    break;
+#if 0 /* unused (and wrong on LLP64 systems) */
 	case 'p':
 	    val = (unsigned long) va_arg(args, void *);
 	    base = 16;
 	    neg = 2;
 	    break;
+#endif /* unused (and wrong on LLP64 systems) */
 	case 's':
 	    str = va_arg(args, char *);
 	    break;
@@ -267,7 +269,7 @@ int ppp_vslprintf(char *buf, int buflen, const char *fmt, va_list args) {
 #endif /* do we always have strerror() in embedded ? */
 	case 'I':
 	    ip = va_arg(args, u32_t);
-	    ip = ntohl(ip);
+	    ip = lwip_ntohl(ip);
 	    ppp_slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
 		     (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
 	    str = num;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/netif/ppp/vj.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/netif/ppp/vj.c b/net/ip/lwip_base/src/netif/ppp/vj.c
index dadb38d..168c340 100644
--- a/net/ip/lwip_base/src/netif/ppp/vj.c
+++ b/net/ip/lwip_base/src/netif/ppp/vj.c
@@ -95,32 +95,32 @@ vj_compress_init(struct vjcompress *comp)
 
 #define DECODEL(f) { \
   if (*cp == 0) {\
-    u32_t tmp_ = ntohl(f) + ((cp[1] << 8) | cp[2]); \
-    (f) = htonl(tmp_); \
+    u32_t tmp_ = lwip_ntohl(f) + ((cp[1] << 8) | cp[2]); \
+    (f) = lwip_htonl(tmp_); \
     cp += 3; \
   } else { \
-    u32_t tmp_ = ntohl(f) + (u32_t)*cp++; \
-    (f) = htonl(tmp_); \
+    u32_t tmp_ = lwip_ntohl(f) + (u32_t)*cp++; \
+    (f) = lwip_htonl(tmp_); \
   } \
 }
 
 #define DECODES(f) { \
   if (*cp == 0) {\
-    u16_t tmp_ = ntohs(f) + (((u16_t)cp[1] << 8) | cp[2]); \
-    (f) = htons(tmp_); \
+    u16_t tmp_ = lwip_ntohs(f) + (((u16_t)cp[1] << 8) | cp[2]); \
+    (f) = lwip_htons(tmp_); \
     cp += 3; \
   } else { \
-    u16_t tmp_ = ntohs(f) + (u16_t)*cp++; \
-    (f) = htons(tmp_); \
+    u16_t tmp_ = lwip_ntohs(f) + (u16_t)*cp++; \
+    (f) = lwip_htons(tmp_); \
   } \
 }
 
 #define DECODEU(f) { \
   if (*cp == 0) {\
-    (f) = htons(((u16_t)cp[1] << 8) | cp[2]); \
+    (f) = lwip_htons(((u16_t)cp[1] << 8) | cp[2]); \
     cp += 3; \
   } else { \
-    (f) = htons((u16_t)*cp++); \
+    (f) = lwip_htons((u16_t)*cp++); \
   } \
 }
 
@@ -306,7 +306,7 @@ vj_compress_tcp(struct vjcompress *comp, struct pbuf **pb)
    * needed in this section of code).
    */
   if (TCPH_FLAGS(th) & TCP_URG) {
-    deltaS = ntohs(th->urgp);
+    deltaS = lwip_ntohs(th->urgp);
     ENCODEZ(deltaS);
     changes |= NEW_U;
   } else if (th->urgp != oth->urgp) {
@@ -317,12 +317,12 @@ vj_compress_tcp(struct vjcompress *comp, struct pbuf **pb)
     goto uncompressed;
   }
 
-  if ((deltaS = (u16_t)(ntohs(th->wnd) - ntohs(oth->wnd))) != 0) {
+  if ((deltaS = (u16_t)(lwip_ntohs(th->wnd) - lwip_ntohs(oth->wnd))) != 0) {
     ENCODE(deltaS);
     changes |= NEW_W;
   }
 
-  if ((deltaL = ntohl(th->ackno) - ntohl(oth->ackno)) != 0) {
+  if ((deltaL = lwip_ntohl(th->ackno) - lwip_ntohl(oth->ackno)) != 0) {
     if (deltaL > 0xffff) {
       goto uncompressed;
     }
@@ -331,7 +331,7 @@ vj_compress_tcp(struct vjcompress *comp, struct pbuf **pb)
     changes |= NEW_A;
   }
 
-  if ((deltaL = ntohl(th->seqno) - ntohl(oth->seqno)) != 0) {
+  if ((deltaL = lwip_ntohl(th->seqno) - lwip_ntohl(oth->seqno)) != 0) {
     if (deltaL > 0xffff) {
       goto uncompressed;
     }
@@ -351,7 +351,7 @@ vj_compress_tcp(struct vjcompress *comp, struct pbuf **pb)
      * in case the other side missed the compressed version.
      */
     if (IPH_LEN(ip) != IPH_LEN(&cs->cs_ip) &&
-      ntohs(IPH_LEN(&cs->cs_ip)) == hlen) {
+      lwip_ntohs(IPH_LEN(&cs->cs_ip)) == hlen) {
       break;
     }
     /* no break */
@@ -366,7 +366,7 @@ vj_compress_tcp(struct vjcompress *comp, struct pbuf **pb)
     goto uncompressed;
 
   case NEW_S|NEW_A:
-    if (deltaS == deltaA && deltaS == ntohs(IPH_LEN(&cs->cs_ip)) - hlen) {
+    if (deltaS == deltaA && deltaS == lwip_ntohs(IPH_LEN(&cs->cs_ip)) - hlen) {
       /* special case for echoed terminal traffic */
       changes = SPECIAL_I;
       cp = new_seq;
@@ -374,7 +374,7 @@ vj_compress_tcp(struct vjcompress *comp, struct pbuf **pb)
     break;
 
   case NEW_S:
-    if (deltaS == ntohs(IPH_LEN(&cs->cs_ip)) - hlen) {
+    if (deltaS == lwip_ntohs(IPH_LEN(&cs->cs_ip)) - hlen) {
       /* special case for data xfer */
       changes = SPECIAL_D;
       cp = new_seq;
@@ -384,7 +384,7 @@ vj_compress_tcp(struct vjcompress *comp, struct pbuf **pb)
      break;
   }
 
-  deltaS = (u16_t)(ntohs(IPH_ID(ip)) - ntohs(IPH_ID(&cs->cs_ip)));
+  deltaS = (u16_t)(lwip_ntohs(IPH_ID(ip)) - lwip_ntohs(IPH_ID(&cs->cs_ip)));
   if (deltaS != 1) {
     ENCODEZ(deltaS);
     changes |= NEW_I;
@@ -396,7 +396,7 @@ vj_compress_tcp(struct vjcompress *comp, struct pbuf **pb)
    * Grab the cksum before we overwrite it below.  Then update our
    * state with this packet's header.
    */
-  deltaA = ntohs(th->chksum);
+  deltaA = lwip_ntohs(th->chksum);
   MEMCPY(&cs->cs_ip, ip, hlen);
 
   /*
@@ -538,7 +538,7 @@ vj_uncompress_tcp(struct pbuf **nb, struct vjcompress *comp)
   cs = &comp->rstate[comp->last_recv];
   hlen = IPH_HL(&cs->cs_ip) << 2;
   th = (struct tcp_hdr *)&((u8_t*)&cs->cs_ip)[hlen];
-  th->chksum = htons((*cp << 8) | cp[1]);
+  th->chksum = lwip_htons((*cp << 8) | cp[1]);
   cp += 2;
   if (changes & TCP_PUSH_BIT) {
     TCPH_SET_FLAG(th, TCP_PSH);
@@ -549,19 +549,19 @@ vj_uncompress_tcp(struct pbuf **nb, struct vjcompress *comp)
   switch (changes & SPECIALS_MASK) {
   case SPECIAL_I:
     {
-      u32_t i = ntohs(IPH_LEN(&cs->cs_ip)) - cs->cs_hlen;
+      u32_t i = lwip_ntohs(IPH_LEN(&cs->cs_ip)) - cs->cs_hlen;
       /* some compilers can't nest inline assembler.. */
-      tmp = ntohl(th->ackno) + i;
-      th->ackno = htonl(tmp);
-      tmp = ntohl(th->seqno) + i;
-      th->seqno = htonl(tmp);
+      tmp = lwip_ntohl(th->ackno) + i;
+      th->ackno = lwip_htonl(tmp);
+      tmp = lwip_ntohl(th->seqno) + i;
+      th->seqno = lwip_htonl(tmp);
     }
     break;
 
   case SPECIAL_D:
     /* some compilers can't nest inline assembler.. */
-    tmp = ntohl(th->seqno) + ntohs(IPH_LEN(&cs->cs_ip)) - cs->cs_hlen;
-    th->seqno = htonl(tmp);
+    tmp = lwip_ntohl(th->seqno) + lwip_ntohs(IPH_LEN(&cs->cs_ip)) - cs->cs_hlen;
+    th->seqno = lwip_htonl(tmp);
     break;
 
   default:
@@ -585,8 +585,8 @@ vj_uncompress_tcp(struct pbuf **nb, struct vjcompress *comp)
   if (changes & NEW_I) {
     DECODES(cs->cs_ip._id);
   } else {
-    IPH_ID_SET(&cs->cs_ip, ntohs(IPH_ID(&cs->cs_ip)) + 1);
-    IPH_ID_SET(&cs->cs_ip, htons(IPH_ID(&cs->cs_ip)));
+    IPH_ID_SET(&cs->cs_ip, lwip_ntohs(IPH_ID(&cs->cs_ip)) + 1);
+    IPH_ID_SET(&cs->cs_ip, lwip_htons(IPH_ID(&cs->cs_ip)));
   }
 
   /*
@@ -607,9 +607,9 @@ vj_uncompress_tcp(struct pbuf **nb, struct vjcompress *comp)
 
 #if BYTE_ORDER == LITTLE_ENDIAN
   tmp = n0->tot_len - vjlen + cs->cs_hlen;
-  IPH_LEN_SET(&cs->cs_ip, htons((u16_t)tmp));
+  IPH_LEN_SET(&cs->cs_ip, lwip_htons((u16_t)tmp));
 #else
-  IPH_LEN_SET(&cs->cs_ip, htons(n0->tot_len - vjlen + cs->cs_hlen));
+  IPH_LEN_SET(&cs->cs_ip, lwip_htons(n0->tot_len - vjlen + cs->cs_hlen));
 #endif
 
   /* recompute the ip header checksum */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/netif/slipif.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/netif/slipif.c b/net/ip/lwip_base/src/netif/slipif.c
index 8849fbf..6eb83c3 100644
--- a/net/ip/lwip_base/src/netif/slipif.c
+++ b/net/ip/lwip_base/src/netif/slipif.c
@@ -304,7 +304,7 @@ slipif_rxbyte(struct netif *netif, u8_t c)
 /** Like slipif_rxbyte, but passes completed packets to netif->input
  *
  * @param netif The lwip network interface structure for this slipif
- * @param data received character
+ * @param c received character
  */
 static void
 slipif_rxbyte_input(struct netif *netif, u8_t c)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/fuzz/Makefile
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/fuzz/Makefile b/net/ip/lwip_base/test/fuzz/Makefile
new file mode 100644
index 0000000..67ffb19
--- /dev/null
+++ b/net/ip/lwip_base/test/fuzz/Makefile
@@ -0,0 +1,53 @@
+#
+# Copyright (c) 2001, 2002 Swedish Institute of Computer Science.
+# All rights reserved. 
+# 
+# Redistribution and use in source and binary forms, with or without modification, 
+# are permitted provided that the following conditions are met:
+#
+# 1. Redistributions of source code must retain the above copyright notice,
+#    this list of conditions and the following disclaimer.
+# 2. 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.
+# 3. The name of the author may not be used to endorse or promote products
+#    derived from this software without specific prior written permission. 
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+#
+# This file is part of the lwIP TCP/IP stack.
+# 
+# Author: Adam Dunkels <ad...@sics.se>
+#
+
+all compile: lwip_fuzz
+.PHONY: all clean
+
+CC=afl-gcc
+LDFLAGS=-lm
+CFLAGS=-O0
+
+CONTRIBDIR=../../../lwip-contrib
+include $(CONTRIBDIR)/ports/unix/Common.mk
+
+clean:
+	rm -f *.o $(LWIPLIBCOMMON) lwip_fuzz *.s .depend* *.core core
+
+depend dep: .depend
+
+include .depend
+
+.depend: fuzz.c $(LWIPFILES) $(APPFILES)
+	$(CCDEP) $(CFLAGS) -MM $^ > .depend || rm -f .depend
+
+lwip_fuzz: .depend $(LWIPLIBCOMMON) fuzz.o
+	$(CC) $(CFLAGS) -o lwip_fuzz fuzz.o $(LWIPLIBCOMMON) $(LDFLAGS)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/fuzz/README
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/fuzz/README b/net/ip/lwip_base/test/fuzz/README
new file mode 100644
index 0000000..1d1e3d8
--- /dev/null
+++ b/net/ip/lwip_base/test/fuzz/README
@@ -0,0 +1,34 @@
+
+Fuzzing the lwIP stack (afl-fuzz requires linux/unix or similar)
+
+This directory contains a small app that reads Ethernet frames from stdin and
+processes them. It is used together with the 'american fuzzy lop' tool (found
+at http://lcamtuf.coredump.cx/afl/) and the sample inputs to test how
+unexpected inputs are handled. The afl tool will read the known inputs, and
+try to modify them to exercise as many code paths as possible, by instrumenting
+the code and keeping track of which code is executed.
+
+Just running make will produce the test program.
+
+Then run afl with:
+
+afl-fuzz -i inputs/<INPUT> -o output ./lwip_fuzz
+
+and it should start working. It will probably complain about CPU scheduler,
+set AFL_SKIP_CPUFREQ=1 to ignore it.
+If it complains about invalid "/proc/sys/kernel/core_pattern" setting, try
+executing "sudo bash -c 'echo core > /proc/sys/kernel/core_pattern'".
+
+The input is split into different subdirectories since they test different
+parts of the code, and since you want to run one instance of afl-fuzz on each
+core.
+
+When afl finds a crash or a hang, the input that caused it will be placed in
+the output directory. If you have hexdump and text2pcap tools installed,
+running output_to_pcap.sh <outputdir> will create pcap files for each input
+file to simplify viewing in wireshark.
+
+The lwipopts.h file needs to have checksum checking off, otherwise almost every
+packet will be discarded because of that. The other options can be tuned to
+expose different parts of the code.
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/fuzz/config.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/fuzz/config.h b/net/ip/lwip_base/test/fuzz/config.h
new file mode 100644
index 0000000..e69de29

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/fuzz/fuzz.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/fuzz/fuzz.c b/net/ip/lwip_base/test/fuzz/fuzz.c
new file mode 100644
index 0000000..a9157f1
--- /dev/null
+++ b/net/ip/lwip_base/test/fuzz/fuzz.c
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 2001-2003 Swedish Institute of Computer Science.
+ * All rights reserved. 
+ * 
+ * Redistribution and use in source and binary forms, with or without modification, 
+ * are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ * 2. 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.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission. 
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ *
+ * This file is part of the lwIP TCP/IP stack.
+ * 
+ * Author: Erik Ekman <er...@kryo.se>
+ *
+ */
+
+#include "lwip/init.h"
+#include "lwip/netif.h"
+#include "netif/etharp.h"
+#if LWIP_IPV6
+#include "lwip/ethip6.h"
+#include "lwip/nd6.h"
+#endif
+#include <string.h>
+#include <stdio.h>
+
+/* no-op send function */
+static err_t lwip_tx_func(struct netif *netif, struct pbuf *p)
+{
+  LWIP_UNUSED_ARG(netif);
+  LWIP_UNUSED_ARG(p);
+  return ERR_OK;
+}
+
+static err_t testif_init(struct netif *netif)
+{
+  netif->name[0] = 'f';
+  netif->name[1] = 'z';
+  netif->output = etharp_output;
+  netif->linkoutput = lwip_tx_func;
+  netif->mtu = 1500;
+  netif->hwaddr_len = 6;
+  netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP;
+
+  netif->hwaddr[0] = 0x00;
+  netif->hwaddr[1] = 0x23;
+  netif->hwaddr[2] = 0xC1;
+  netif->hwaddr[3] = 0xDE;
+  netif->hwaddr[4] = 0xD0;
+  netif->hwaddr[5] = 0x0D;
+
+#if LWIP_IPV6
+  netif->output_ip6 = ethip6_output;
+  netif->ip6_autoconfig_enabled = 1;
+  netif_create_ip6_linklocal_address(netif, 1);
+  netif->flags |= NETIF_FLAG_MLD6;
+#endif
+
+  return ERR_OK;
+}
+
+static void input_pkt(struct netif *netif, const u8_t *data, size_t len)
+{
+  struct pbuf *p, *q;
+  err_t err;
+
+  LWIP_ASSERT("pkt too big", len <= 0xFFFF);
+  p = pbuf_alloc(PBUF_RAW, (u16_t)len, PBUF_POOL);
+  LWIP_ASSERT("alloc failed", p);
+  for(q = p; q != NULL; q = q->next) {
+    MEMCPY(q->payload, data, q->len);
+    data += q->len;
+  }
+  err = netif->input(p, netif);
+  if (err != ERR_OK) {
+    pbuf_free(p);
+  }
+}
+
+int main(int argc, char** argv)
+{
+  struct netif net_test;
+  ip4_addr_t addr;
+  ip4_addr_t netmask;
+  ip4_addr_t gw;
+  u8_t pktbuf[2000];
+  size_t len;
+
+  lwip_init();
+
+  IP4_ADDR(&addr, 172, 30, 115, 84);
+  IP4_ADDR(&netmask, 255, 255, 255, 0);
+  IP4_ADDR(&gw, 172, 30, 115, 1);
+
+  netif_add(&net_test, &addr, &netmask, &gw, &net_test, testif_init, ethernet_input);
+  netif_set_up(&net_test);
+
+#if LWIP_IPV6
+  nd6_tmr(); /* tick nd to join multicast groups */
+#endif
+
+  if(argc > 1) {
+    FILE* f;
+    const char* filename;
+    printf("reading input from file... ");
+    fflush(stdout);
+    filename = argv[1];
+    LWIP_ASSERT("invalid filename", filename != NULL);
+    f = fopen(filename, "rb");
+    LWIP_ASSERT("open failed", f != NULL);
+    len = fread(pktbuf, 1, sizeof(pktbuf), f);
+    fclose(f);
+    printf("testing file: \"%s\"...\r\n", filename);
+  } else {
+    len = fread(pktbuf, 1, sizeof(pktbuf), stdin);
+  }
+  input_pkt(&net_test, pktbuf, len);
+
+  return 0;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/fuzz/inputs/arp/arp_req.bin
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/fuzz/inputs/arp/arp_req.bin b/net/ip/lwip_base/test/fuzz/inputs/arp/arp_req.bin
new file mode 100644
index 0000000..b317334
Binary files /dev/null and b/net/ip/lwip_base/test/fuzz/inputs/arp/arp_req.bin differ

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/fuzz/inputs/icmp/icmp_ping.bin
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/fuzz/inputs/icmp/icmp_ping.bin b/net/ip/lwip_base/test/fuzz/inputs/icmp/icmp_ping.bin
new file mode 100644
index 0000000..87e1ea7
Binary files /dev/null and b/net/ip/lwip_base/test/fuzz/inputs/icmp/icmp_ping.bin differ

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/fuzz/inputs/ipv6/neighbor_solicitation.bin
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/fuzz/inputs/ipv6/neighbor_solicitation.bin b/net/ip/lwip_base/test/fuzz/inputs/ipv6/neighbor_solicitation.bin
new file mode 100644
index 0000000..d2f921c
Binary files /dev/null and b/net/ip/lwip_base/test/fuzz/inputs/ipv6/neighbor_solicitation.bin differ

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/fuzz/inputs/ipv6/router_adv.bin
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/fuzz/inputs/ipv6/router_adv.bin b/net/ip/lwip_base/test/fuzz/inputs/ipv6/router_adv.bin
new file mode 100644
index 0000000..3aa9615
Binary files /dev/null and b/net/ip/lwip_base/test/fuzz/inputs/ipv6/router_adv.bin differ

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/fuzz/inputs/tcp/tcp_syn.bin
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/fuzz/inputs/tcp/tcp_syn.bin b/net/ip/lwip_base/test/fuzz/inputs/tcp/tcp_syn.bin
new file mode 100644
index 0000000..d77f6d2
Binary files /dev/null and b/net/ip/lwip_base/test/fuzz/inputs/tcp/tcp_syn.bin differ

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/fuzz/inputs/udp/udp_port_5000.bin
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/fuzz/inputs/udp/udp_port_5000.bin b/net/ip/lwip_base/test/fuzz/inputs/udp/udp_port_5000.bin
new file mode 100644
index 0000000..d77e267
Binary files /dev/null and b/net/ip/lwip_base/test/fuzz/inputs/udp/udp_port_5000.bin differ

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/fuzz/lwipopts.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/fuzz/lwipopts.h b/net/ip/lwip_base/test/fuzz/lwipopts.h
new file mode 100644
index 0000000..4aff09b
--- /dev/null
+++ b/net/ip/lwip_base/test/fuzz/lwipopts.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2001-2003 Swedish Institute of Computer Science.
+ * All rights reserved. 
+ * 
+ * Redistribution and use in source and binary forms, with or without modification, 
+ * are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ * 2. 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.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission. 
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ *
+ * This file is part of the lwIP TCP/IP stack.
+ * 
+ * Author: Simon Goldschmidt
+ *
+ */
+#ifndef LWIP_HDR_LWIPOPTS_H__
+#define LWIP_HDR_LWIPOPTS_H__
+
+/* Prevent having to link sys_arch.c (we don't test the API layers in unit tests) */
+#define NO_SYS                          1
+#define LWIP_NETCONN                    0
+#define LWIP_SOCKET                     0
+#define SYS_LIGHTWEIGHT_PROT            0
+
+#define LWIP_IPV6                       1
+#define IPV6_FRAG_COPYHEADER            1
+#define LWIP_IPV6_DUP_DETECT_ATTEMPTS   0
+
+/* Enable DHCP to test it */
+#define LWIP_DHCP                       1
+
+/* Turn off checksum verification of fuzzed data */
+#define CHECKSUM_CHECK_IP               0
+#define CHECKSUM_CHECK_UDP              0
+#define CHECKSUM_CHECK_TCP              0
+#define CHECKSUM_CHECK_ICMP             0
+#define CHECKSUM_CHECK_ICMP6            0
+
+/* Minimal changes to opt.h required for tcp unit tests: */
+#define MEM_SIZE                        16000
+#define TCP_SND_QUEUELEN                40
+#define MEMP_NUM_TCP_SEG                TCP_SND_QUEUELEN
+#define TCP_SND_BUF                     (12 * TCP_MSS)
+#define TCP_WND                         (10 * TCP_MSS)
+#define LWIP_WND_SCALE                  1
+#define TCP_RCV_SCALE                   0
+#define PBUF_POOL_SIZE                  400 /* pbuf tests need ~200KByte */
+
+/* Minimal changes to opt.h required for etharp unit tests: */
+#define ETHARP_SUPPORT_STATIC_ENTRIES   1
+
+#endif /* LWIP_HDR_LWIPOPTS_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/fuzz/output_to_pcap.sh
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/fuzz/output_to_pcap.sh b/net/ip/lwip_base/test/fuzz/output_to_pcap.sh
new file mode 100644
index 0000000..c999ff0
--- /dev/null
+++ b/net/ip/lwip_base/test/fuzz/output_to_pcap.sh
@@ -0,0 +1,31 @@
+#!/bin/bash
+
+if [ -z "$1" ]
+then
+	echo "This script will make pcap files from the afl-fuzz crash/hang files"
+	echo "It needs hexdump and text2pcap"
+	echo "Please give output directory as argument"
+	exit 2
+fi
+
+for i in `ls $1/crashes/id*`
+do
+	PCAPNAME=`echo $i | grep pcap`
+	if [ -z "$PCAPNAME" ]; then
+		hexdump -C $i > $1/$$.tmp
+		text2pcap $1/$$.tmp ${i}.pcap
+	fi
+done
+for i in `ls $1/hangs/id*`
+do
+	PCAPNAME=`echo $i | grep pcap`
+	if [ -z "$PCAPNAME" ]; then
+		hexdump -C $i > $1/$$.tmp
+		text2pcap $1/$$.tmp ${i}.pcap
+	fi
+done
+rm -f $1/$$.tmp
+
+echo
+echo "Created pcap files:"
+ls $1/*/*.pcap

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/unit/core/test_mem.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/unit/core/test_mem.h b/net/ip/lwip_base/test/unit/core/test_mem.h
index 450bbd7..325134c 100644
--- a/net/ip/lwip_base/test/unit/core/test_mem.h
+++ b/net/ip/lwip_base/test/unit/core/test_mem.h
@@ -3,14 +3,6 @@
 
 #include "../lwip_check.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 Suite *mem_suite(void);
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/unit/core/test_pbuf.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/unit/core/test_pbuf.h b/net/ip/lwip_base/test/unit/core/test_pbuf.h
index bdb7799..da7730a 100644
--- a/net/ip/lwip_base/test/unit/core/test_pbuf.h
+++ b/net/ip/lwip_base/test/unit/core/test_pbuf.h
@@ -3,14 +3,6 @@
 
 #include "../lwip_check.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 Suite *pbuf_suite(void);
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/unit/dhcp/test_dhcp.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/unit/dhcp/test_dhcp.c b/net/ip/lwip_base/test/unit/dhcp/test_dhcp.c
index 68f2881..47aaa08 100644
--- a/net/ip/lwip_base/test/unit/dhcp/test_dhcp.c
+++ b/net/ip/lwip_base/test/unit/dhcp/test_dhcp.c
@@ -120,14 +120,13 @@ static enum tcase {
   TEST_LWIP_DHCP,
   TEST_LWIP_DHCP_NAK,
   TEST_LWIP_DHCP_RELAY,
-  TEST_LWIP_DHCP_NAK_NO_ENDMARKER
+  TEST_LWIP_DHCP_NAK_NO_ENDMARKER,
+  TEST_LWIP_DHCP_INVALID_OVERLOAD
 } tcase;
 
 static int debug = 0;
 static void setdebug(int a) {debug = a;}
 
-#define netif_dhcp_data(netif) ((struct dhcp*)(netif)->client_data[LWIP_NETIF_CLIENT_DATA_INDEX_DHCP])
-
 static int tick = 0;
 static void tick_lwip(void)
 {
@@ -904,6 +903,111 @@ START_TEST(test_dhcp_nak_no_endmarker)
 }
 END_TEST
 
+START_TEST(test_dhcp_invalid_overload)
+{
+  u8_t dhcp_offer_invalid_overload[] = {
+      0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, /* To unit */
+      0x00, 0x0F, 0xEE, 0x30, 0xAB, 0x22, /* From Remote host */
+      0x08, 0x00, /* Protocol: IP */
+      0x45, 0x10, 0x01, 0x48, 0x00, 0x00, 0x00, 0x00, 0x80, 0x11, 0x36, 0xcc, 0xc3, 0xaa, 0xbd, 0xab, 0xc3, 0xaa, 0xbd, 0xc8, /* IP header */
+      0x00, 0x43, 0x00, 0x44, 0x01, 0x34, 0x00, 0x00, /* UDP header */
+
+      0x02, /* Type == Boot reply */
+      0x01, 0x06, /* Hw Ethernet, 6 bytes addrlen */
+      0x00, /* 0 hops */
+      0xAA, 0xAA, 0xAA, 0xAA, /* Transaction id, will be overwritten */
+      0x00, 0x00, /* 0 seconds elapsed */
+      0x00, 0x00, /* Flags (unicast) */
+      0x00, 0x00, 0x00, 0x00, /* Client ip */
+      0xc3, 0xaa, 0xbd, 0xc8, /* Your IP */
+      0xc3, 0xaa, 0xbd, 0xab, /* DHCP server ip */
+      0x00, 0x00, 0x00, 0x00, /* relay agent */
+      0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* MAC addr + padding */
+
+      /* Empty server name */
+      0x34, 0x01, 0x02, 0xff, /* Overload: SNAME + END */
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+      /* Empty boot file name */
+      0x34, 0x01, 0x01, 0xff, /* Overload FILE + END */
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+
+      0x63, 0x82, 0x53, 0x63, /* Magic cookie */
+      0x35, 0x01, 0x02, /* Message type: Offer */
+      0x36, 0x04, 0xc3, 0xaa, 0xbd, 0xab, /* Server identifier (IP) */
+      0x33, 0x04, 0x00, 0x00, 0x00, 0x78, /* Lease time 2 minutes */
+      0x03, 0x04, 0xc3, 0xaa, 0xbd, 0xab, /* Router IP */
+      0x01, 0x04, 0xff, 0xff, 0xff, 0x00, /* Subnet mask */
+      0x34, 0x01, 0x03, /* Overload: FILE + SNAME */
+      0xff, /* End option */
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Padding */
+  };
+  ip4_addr_t addr;
+  ip4_addr_t netmask;
+  ip4_addr_t gw;
+  u32_t xid;
+  LWIP_UNUSED_ARG(_i);
+
+  tcase = TEST_LWIP_DHCP_INVALID_OVERLOAD;
+  setdebug(0);
+
+  IP4_ADDR(&addr, 0, 0, 0, 0);
+  IP4_ADDR(&netmask, 0, 0, 0, 0);
+  IP4_ADDR(&gw, 0, 0, 0, 0);
+
+  netif_add(&net_test, &addr, &netmask, &gw, &net_test, testif_init, ethernet_input);
+  netif_set_up(&net_test);
+
+  dhcp_start(&net_test);
+
+  fail_unless(txpacket == 1); /* DHCP discover sent */
+  xid = htonl(netif_dhcp_data(&net_test)->xid);
+  memcpy(&dhcp_offer_invalid_overload[46], &xid, 4); /* insert correct transaction id */
+  dhcp_offer_invalid_overload[311] = 3;
+  send_pkt(&net_test, dhcp_offer_invalid_overload, sizeof(dhcp_offer_invalid_overload));
+  /* IP addresses should be zero */
+  fail_if(memcmp(&addr, &net_test.ip_addr, sizeof(ip4_addr_t)));
+  fail_if(memcmp(&netmask, &net_test.netmask, sizeof(ip4_addr_t)));
+  fail_if(memcmp(&gw, &net_test.gw, sizeof(ip4_addr_t)));
+  fail_unless(txpacket == 1); /* Nothing more sent */
+
+  dhcp_offer_invalid_overload[311] = 2;
+  send_pkt(&net_test, dhcp_offer_invalid_overload, sizeof(dhcp_offer_invalid_overload));
+  /* IP addresses should be zero */
+  fail_if(memcmp(&addr, &net_test.ip_addr, sizeof(ip4_addr_t)));
+  fail_if(memcmp(&netmask, &net_test.netmask, sizeof(ip4_addr_t)));
+  fail_if(memcmp(&gw, &net_test.gw, sizeof(ip4_addr_t)));
+  fail_unless(txpacket == 1); /* Nothing more sent */
+
+  dhcp_offer_invalid_overload[311] = 1;
+  send_pkt(&net_test, dhcp_offer_invalid_overload, sizeof(dhcp_offer_invalid_overload));
+  /* IP addresses should be zero */
+  fail_if(memcmp(&addr, &net_test.ip_addr, sizeof(ip4_addr_t)));
+  fail_if(memcmp(&netmask, &net_test.netmask, sizeof(ip4_addr_t)));
+  fail_if(memcmp(&gw, &net_test.gw, sizeof(ip4_addr_t)));
+  fail_unless(txpacket == 1); /* Nothing more sent */
+
+  dhcp_offer_invalid_overload[311] = 0;
+  send_pkt(&net_test, dhcp_offer_invalid_overload, sizeof(dhcp_offer));
+
+  fail_unless(netif_dhcp_data(&net_test)->state == DHCP_STATE_REQUESTING);
+
+  fail_unless(txpacket == 2); /* No more sent */
+  xid = htonl(netif_dhcp_data(&net_test)->xid); /* xid updated */
+
+  netif_remove(&net_test);
+}
+END_TEST
 
 /** Create the suite including all tests for this module */
 Suite *
@@ -913,7 +1017,8 @@ dhcp_suite(void)
     TESTFUNC(test_dhcp),
     TESTFUNC(test_dhcp_nak),
     TESTFUNC(test_dhcp_relayed),
-    TESTFUNC(test_dhcp_nak_no_endmarker)
+    TESTFUNC(test_dhcp_nak_no_endmarker),
+    TESTFUNC(test_dhcp_invalid_overload)
   };
   return create_suite("DHCP", tests, sizeof(tests)/sizeof(testfunc), dhcp_setup, dhcp_teardown);
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/unit/dhcp/test_dhcp.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/unit/dhcp/test_dhcp.h b/net/ip/lwip_base/test/unit/dhcp/test_dhcp.h
index 00021f2..0d88fa1 100644
--- a/net/ip/lwip_base/test/unit/dhcp/test_dhcp.h
+++ b/net/ip/lwip_base/test/unit/dhcp/test_dhcp.h
@@ -3,14 +3,6 @@
 
 #include "../lwip_check.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 Suite* dhcp_suite(void);
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/unit/etharp/test_etharp.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/unit/etharp/test_etharp.h b/net/ip/lwip_base/test/unit/etharp/test_etharp.h
index 61742ec..2dd772d 100644
--- a/net/ip/lwip_base/test/unit/etharp/test_etharp.h
+++ b/net/ip/lwip_base/test/unit/etharp/test_etharp.h
@@ -3,14 +3,6 @@
 
 #include "../lwip_check.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 Suite* etharp_suite(void);
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/unit/lwip_check.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/unit/lwip_check.h b/net/ip/lwip_base/test/unit/lwip_check.h
index 6946915..0c218d1 100644
--- a/net/ip/lwip_base/test/unit/lwip_check.h
+++ b/net/ip/lwip_base/test/unit/lwip_check.h
@@ -1,10 +1,6 @@
 #ifndef LWIP_HDR_LWIP_CHECK_H
 #define LWIP_HDR_LWIP_CHECK_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /* Common header file for lwIP unit tests using the check framework */
 
 #include <config.h>
@@ -38,8 +34,4 @@ Suite* create_suite(const char* name, testfunc *tests, size_t num_tests, SFun se
 int lwip_unittests_run(void)
 #endif
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_HDR_LWIP_CHECK_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/test/unit/lwipopts.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/test/unit/lwipopts.h b/net/ip/lwip_base/test/unit/lwipopts.h
index 47ade69..25252b4 100644
--- a/net/ip/lwip_base/test/unit/lwipopts.h
+++ b/net/ip/lwip_base/test/unit/lwipopts.h
@@ -32,10 +32,6 @@
 #ifndef LWIP_HDR_LWIPOPTS_H
 #define LWIP_HDR_LWIPOPTS_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /* Prevent having to link sys_arch.c (we don't test the API layers in unit tests) */
 #define NO_SYS                          1
 #define SYS_LIGHTWEIGHT_PROT            0
@@ -63,8 +59,4 @@ extern "C" {
 /* Minimal changes to opt.h required for etharp unit tests: */
 #define ETHARP_SUPPORT_STATIC_ENTRIES   1
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_HDR_LWIPOPTS_H */


[25/30] incubator-mynewt-core git commit: apps/iptest; add sample task to demonstrate IP config over ethernet.

Posted by ad...@apache.org.
apps/iptest; add sample task to demonstrate IP config over ethernet.


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/39ad85d2
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/39ad85d2
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/39ad85d2

Branch: refs/heads/master
Commit: 39ad85d22ef78e6082167c046ef33dc7c876b7aa
Parents: f92e6ab
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Mon Apr 17 14:35:24 2017 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Apr 17 14:35:24 2017 -0700

----------------------------------------------------------------------
 apps/iptest/pkg.yml    |  46 +++++
 apps/iptest/src/main.c | 441 ++++++++++++++++++++++++++++++++++++++++++++
 apps/iptest/syscfg.yml |  45 +++++
 3 files changed, 532 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/39ad85d2/apps/iptest/pkg.yml
----------------------------------------------------------------------
diff --git a/apps/iptest/pkg.yml b/apps/iptest/pkg.yml
new file mode 100644
index 0000000..a9a5da1
--- /dev/null
+++ b/apps/iptest/pkg.yml
@@ -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.
+#
+
+pkg.name: apps/iptest
+pkg.type: app
+pkg.description: "Example application which uses a variety of mynewt features."
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+
+pkg.deps:
+    - kernel/os
+    - boot/bootutil
+    - sys/shell
+    - sys/config
+    - sys/console/full
+    - sys/id
+    - sys/log/full
+    - sys/stats/full
+    - net/ip/inet_def_service
+
+pkg.deps.CONFIG_NFFS:
+    - fs/nffs
+
+pkg.deps.CONFIG_FCB:
+    - fs/fcb
+
+pkg.deps.BUILD_WITH_OIC:
+    - net/oic
+    - encoding/cborattr

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/39ad85d2/apps/iptest/src/main.c
----------------------------------------------------------------------
diff --git a/apps/iptest/src/main.c b/apps/iptest/src/main.c
new file mode 100755
index 0000000..3ec726e
--- /dev/null
+++ b/apps/iptest/src/main.c
@@ -0,0 +1,441 @@
+/*
+ * 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 "syscfg/syscfg.h"
+#include "sysinit/sysinit.h"
+#include "sysflash/sysflash.h"
+
+#include <os/os.h>
+#include <bsp/bsp.h>
+
+#include <hal/hal_gpio.h>
+#include <hal/hal_flash.h>
+#include <console/console.h>
+
+#include <log/log.h>
+#include <config/config.h>
+#include <hal/hal_system.h>
+
+#include <bootutil/image.h>
+#include <bootutil/bootutil.h>
+
+#include <shell/shell.h>
+#include <mn_socket/mn_socket.h>
+#include <inet_def_service/inet_def_service.h>
+
+#include <assert.h>
+#include <string.h>
+#include <os/os_time.h>
+#include <id/id.h>
+
+#if MYNEWT_VAL(BUILD_WITH_OIC)
+#include <oic/oc_api.h>
+#include <oic/oc_log.h>
+#include <cborattr/cborattr.h>
+#endif
+
+#ifdef ARCH_sim
+#include <mcu/mcu_sim.h>
+#endif
+
+static struct log my_log;
+
+#define MAX_CBMEM_BUF 2048
+
+static uint32_t cbmem_buf[MAX_CBMEM_BUF];
+static struct cbmem cbmem;
+
+static int net_cli(int argc, char **argv);
+struct shell_cmd net_test_cmd = {
+    .sc_cmd = "net",
+    .sc_cmd_func = net_cli
+};
+
+static struct mn_socket *net_test_socket;
+static struct mn_socket *net_test_socket2;
+
+#if MYNEWT_VAL(BUILD_WITH_OIC)
+static void omgr_app_init(void);
+static const oc_handler_t omgr_oc_handler = {
+    .init = omgr_app_init,
+};
+#endif
+
+static void net_test_readable(void *arg, int err)
+{
+    console_printf("net_test_readable %x - %d\n", (int)arg, err);
+}
+
+static void net_test_writable(void *arg, int err)
+{
+    console_printf("net_test_writable %x - %d\n", (int)arg, err);
+}
+
+static const union mn_socket_cb net_test_cbs = {
+    .socket.readable = net_test_readable,
+    .socket.writable = net_test_writable
+};
+
+static int net_test_newconn(void *arg, struct mn_socket *new)
+{
+    console_printf("net_test_newconn %x - %x\n", (int)arg, (int)new);
+    mn_socket_set_cbs(new, NULL, &net_test_cbs);
+    net_test_socket2 = new;
+    return 0;
+}
+
+static const union mn_socket_cb net_listen_cbs =  {
+    .listen.newconn = net_test_newconn,
+};
+
+static int
+net_cli(int argc, char **argv)
+{
+    int rc;
+    struct mn_sockaddr_in sin;
+    struct mn_sockaddr_in *sinp;
+    uint16_t port;
+    uint32_t addr;
+    char *eptr;
+    struct os_mbuf *m;
+
+    if (argc < 2) {
+        return 0;
+    }
+    if (!strcmp(argv[1], "udp")) {
+        rc = mn_socket(&net_test_socket, MN_PF_INET, MN_SOCK_DGRAM, 0);
+        console_printf("mn_socket(UDP) = %d %x\n", rc,
+          (int)net_test_socket);
+    } else if (!strcmp(argv[1], "tcp")) {
+        rc = mn_socket(&net_test_socket, MN_PF_INET, MN_SOCK_STREAM, 0);
+        console_printf("mn_socket(TCP) = %d %x\n", rc,
+          (int)net_test_socket);
+    } else if (!strcmp(argv[1], "connect") || !strcmp(argv[1], "bind")) {
+        if (argc < 4) {
+            return 0;
+        }
+
+        if (mn_inet_pton(MN_AF_INET, argv[2], &addr) != 1) {
+            console_printf("Invalid address %s\n", argv[2]);
+            return 0;
+        }
+
+        port = strtoul(argv[3], &eptr, 0);
+        if (*eptr != '\0') {
+            console_printf("Invalid port %s\n", argv[3]);
+            return 0;
+        }
+        uint8_t *ip = (uint8_t *)&addr;
+
+        console_printf("%d.%d.%d.%d/%d\n", ip[0], ip[1], ip[2], ip[3], port);
+        memset(&sin, 0, sizeof(sin));
+        sin.msin_len = sizeof(sin);
+        sin.msin_family = MN_AF_INET;
+        sin.msin_port = htons(port);
+        sin.msin_addr.s_addr = addr;
+
+        if (!strcmp(argv[1], "connect")) {
+            mn_socket_set_cbs(net_test_socket, NULL, &net_test_cbs);
+            rc = mn_connect(net_test_socket, (struct mn_sockaddr *)&sin);
+            console_printf("mn_connect() = %d\n", rc);
+        } else {
+            mn_socket_set_cbs(net_test_socket, NULL, &net_test_cbs);
+            rc = mn_bind(net_test_socket, (struct mn_sockaddr *)&sin);
+            console_printf("mn_bind() = %d\n", rc);
+        }
+    } else if (!strcmp(argv[1], "listen")) {
+            mn_socket_set_cbs(net_test_socket, NULL, &net_listen_cbs);
+        rc = mn_listen(net_test_socket, 2);
+        console_printf("mn_listen() = %d\n", rc);
+    } else if (!strcmp(argv[1], "close")) {
+        rc = mn_close(net_test_socket);
+        console_printf("mn_close() = %d\n", rc);
+        net_test_socket = NULL;
+        if (net_test_socket2) {
+            rc = mn_close(net_test_socket2);
+            console_printf("mn_close() = %d\n", rc);
+            net_test_socket2 = NULL;
+        }
+    } else if (!strcmp(argv[1], "send")) {
+        if (argc < 3) {
+            return 0;
+        }
+        m = os_msys_get_pkthdr(16, 0);
+        if (!m) {
+            console_printf("out of mbufs\n");
+            return 0;
+        }
+        rc = os_mbuf_copyinto(m, 0, argv[2], strlen(argv[2]));
+        if (rc < 0) {
+            console_printf("can't copy data\n");
+            os_mbuf_free_chain(m);
+            return 0;
+        }
+        if (argc > 4) {
+            if (mn_inet_pton(MN_AF_INET, argv[3], &addr) != 1) {
+                console_printf("Invalid address %s\n", argv[2]);
+                return 0;
+            }
+
+            port = strtoul(argv[4], &eptr, 0);
+            if (*eptr != '\0') {
+                console_printf("Invalid port %s\n", argv[3]);
+                return 0;
+            }
+            uint8_t *ip = (uint8_t *)&addr;
+
+            console_printf("%d.%d.%d.%d/%d\n", ip[0], ip[1], ip[2], ip[3],
+              port);
+            memset(&sin, 0, sizeof(sin));
+            sin.msin_len = sizeof(sin);
+            sin.msin_family = MN_AF_INET;
+            sin.msin_port = htons(port);
+            sin.msin_addr.s_addr = addr;
+            sinp = &sin;
+        } else {
+            sinp = NULL;
+        }
+
+        if (net_test_socket2) {
+            rc = mn_sendto(net_test_socket2, m, (struct mn_sockaddr *)sinp);
+        } else {
+            rc = mn_sendto(net_test_socket, m, (struct mn_sockaddr *)sinp);
+        }
+        console_printf("mn_sendto() = %d\n", rc);
+    } else if (!strcmp(argv[1], "peer")) {
+        if (net_test_socket2) {
+            rc = mn_getpeername(net_test_socket2, (struct mn_sockaddr *)&sin);
+        } else {
+            rc = mn_getpeername(net_test_socket, (struct mn_sockaddr *)&sin);
+        }
+        console_printf("mn_getpeername() = %d\n", rc);
+        uint8_t *ip = (uint8_t *)&sin.msin_addr;
+
+        console_printf("%d.%d.%d.%d/%d\n", ip[0], ip[1], ip[2], ip[3],
+          ntohs(sin.msin_port));
+    } else if (!strcmp(argv[1], "recv")) {
+        if (net_test_socket2) {
+            rc = mn_recvfrom(net_test_socket2, &m, (struct mn_sockaddr *)&sin);
+        } else {
+            rc = mn_recvfrom(net_test_socket, &m, (struct mn_sockaddr *)&sin);
+        }
+        console_printf("mn_recvfrom() = %d\n", rc);
+        if (m) {
+            uint8_t *ip = (uint8_t *)&sin.msin_addr;
+
+            console_printf("%d.%d.%d.%d/%d\n", ip[0], ip[1], ip[2], ip[3],
+              ntohs(sin.msin_port));
+            m->om_data[m->om_len] = '\0';
+            console_printf("received %d bytes >%s<\n",
+              OS_MBUF_PKTHDR(m)->omp_len, (char *)m->om_data);
+            os_mbuf_free_chain(m);
+        }
+    } else if (!strcmp(argv[1], "mcast_join") ||
+      !strcmp(argv[1], "mcast_leave")) {
+        struct mn_mreq mm;
+        int val;
+
+        if (argc < 4) {
+            return 0;
+        }
+
+        val = strtoul(argv[2], &eptr, 0);
+        if (*eptr != '\0') {
+            console_printf("Invalid itf_idx %s\n", argv[2]);
+            return 0;
+        }
+
+        memset(&mm, 0, sizeof(mm));
+        mm.mm_idx = val;
+        mm.mm_family = MN_AF_INET;
+        if (mn_inet_pton(MN_AF_INET, argv[3], &mm.mm_addr) != 1) {
+            console_printf("Invalid address %s\n", argv[2]);
+            return 0;
+        }
+        if (!strcmp(argv[1], "mcast_join")) {
+            val = MN_MCAST_JOIN_GROUP;
+        } else {
+            val = MN_MCAST_LEAVE_GROUP;
+        }
+        rc = mn_setsockopt(net_test_socket, MN_SO_LEVEL, val, &mm);
+        console_printf("mn_setsockopt() = %d\n", rc);
+    } else if (!strcmp(argv[1], "listif")) {
+        struct mn_itf itf;
+        struct mn_itf_addr itf_addr;
+        char addr_str[48];
+
+        memset(&itf, 0, sizeof(itf));
+        while (1) {
+            rc = mn_itf_getnext(&itf);
+            if (rc) {
+                break;
+            }
+            console_printf("%d: %x %s\n", itf.mif_idx, itf.mif_flags,
+              itf.mif_name);
+            memset(&itf_addr, 0, sizeof(itf_addr));
+            while (1) {
+                rc = mn_itf_addr_getnext(&itf, &itf_addr);
+                if (rc) {
+                    break;
+                }
+                mn_inet_ntop(itf_addr.mifa_family, &itf_addr.mifa_addr,
+                  addr_str, sizeof(addr_str));
+                console_printf(" %s/%d\n", addr_str, itf_addr.mifa_plen);
+            }
+        }
+#ifndef ARCH_sim
+    } else if (!strcmp(argv[1], "mii")) {
+        extern int stm32_mii_dump(void (*func)(const char *fmt, ...));
+
+        stm32_mii_dump(console_printf);
+#endif
+    } else if (!strcmp(argv[1], "service")) {
+        inet_def_service_init(os_eventq_dflt_get());
+#if MYNEWT_VAL(BUILD_WITH_OIC)
+    } else if (!strcmp(argv[1], "oic")) {
+        oc_main_init((oc_handler_t *)&omgr_oc_handler);
+#endif
+    } else {
+        console_printf("unknown cmd\n");
+    }
+    return 0;
+}
+
+#if MYNEWT_VAL(BUILD_WITH_OIC)
+static void
+app_get_light(oc_request_t *request, oc_interface_mask_t interface)
+{
+    bool state;
+
+    if (hal_gpio_read(LED_BLINK_PIN)) {
+        state = true;
+    } else {
+        state = false;
+    }
+    oc_rep_start_root_object();
+    switch (interface) {
+    case OC_IF_BASELINE:
+        oc_process_baseline_interface(request->resource);
+    case OC_IF_RW:
+        oc_rep_set_boolean(root, state, state);
+        break;
+    default:
+        break;
+    }
+    oc_rep_end_root_object();
+    oc_send_response(request, OC_STATUS_OK);
+}
+
+static void
+app_set_light(oc_request_t *request, oc_interface_mask_t interface)
+{
+    bool state;
+    int len;
+    uint16_t data_off;
+    struct os_mbuf *m;
+    struct cbor_attr_t attrs[] = {
+        [0] = {
+            .attribute = "state",
+            .type = CborAttrBooleanType,
+            .addr.boolean = &state,
+            .dflt.boolean = false
+        },
+        [1] = {
+        }
+    };
+
+    len = coap_get_payload(request->packet, &m, &data_off);
+    if (cbor_read_mbuf_attrs(m, data_off, len, attrs)) {
+        oc_send_response(request, OC_STATUS_BAD_REQUEST);
+    } else {
+        hal_gpio_write(LED_BLINK_PIN, state == true);
+        oc_send_response(request, OC_STATUS_CHANGED);
+    }
+}
+
+static void
+omgr_app_init(void)
+{
+    oc_resource_t *res;
+
+    oc_init_platform("MyNewt", NULL, NULL);
+    oc_add_device("/oic/d", "oic.d.light", "MynewtLed", "1.0", "1.0", NULL,
+                  NULL);
+
+    res = oc_new_resource("/light/1", 1, 0);
+    oc_resource_bind_resource_type(res, "oic.r.light");
+    oc_resource_bind_resource_interface(res, OC_IF_RW);
+    oc_resource_set_default_interface(res, OC_IF_RW);
+
+    oc_resource_set_discoverable(res);
+    oc_resource_set_periodic_observable(res, 1);
+    oc_resource_set_request_handler(res, OC_GET, app_get_light);
+    oc_resource_set_request_handler(res, OC_PUT, app_set_light);
+    oc_add_resource(res);
+
+    hal_gpio_init_out(LED_BLINK_PIN, 1);
+}
+#endif
+
+/**
+ * main
+ *
+ * The main task for the project. This function initializes the packages, calls
+ * init_tasks to initialize additional tasks (and possibly other objects),
+ * then starts serving events from default event queue.
+ *
+ * @return int NOTE: this function should never return!
+ */
+int
+main(int argc, char **argv)
+{
+#ifdef ARCH_sim
+    mcu_sim_parse_args(argc, argv);
+#endif
+
+#ifndef ARCH_sim
+    {
+        /*
+         * XXX set mac address when using STM32 ethernet XXX
+         * XXX move this somewhere else XXX
+         */
+        static uint8_t mac[6]= { 0, 1, 1, 2, 2, 3 };
+        int stm32_eth_set_hwaddr(uint8_t *addr);
+        stm32_eth_set_hwaddr(mac);
+    }
+#endif
+
+    sysinit();
+
+    console_printf("iptest\n");
+
+    cbmem_init(&cbmem, cbmem_buf, MAX_CBMEM_BUF);
+    log_register("log", &my_log, &log_cbmem_handler, &cbmem, LOG_SYSLEVEL);
+
+    conf_load();
+
+    shell_cmd_register(&net_test_cmd);
+
+    /*
+     * As the last thing, process events from default event queue.
+     */
+    while (1) {
+        os_eventq_run(os_eventq_dflt_get());
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/39ad85d2/apps/iptest/syscfg.yml
----------------------------------------------------------------------
diff --git a/apps/iptest/syscfg.yml b/apps/iptest/syscfg.yml
new file mode 100644
index 0000000..b24891c
--- /dev/null
+++ b/apps/iptest/syscfg.yml
@@ -0,0 +1,45 @@
+# 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.
+#
+
+# Package: apps/iptest
+
+syscfg.defs:
+    BUILD_WITH_OIC:
+       description: 'needed?'
+       value: 0
+
+syscfg.vals:
+    # Enable the shell task.
+    SHELL_TASK: 1
+
+    # Include names for statistics.
+    STATS_NAMES: 1
+
+    # Log reboot messages to a flash circular buffer.
+    REBOOT_LOG_FCB: 1
+    LOG_FCB: 1
+
+    CONFIG_FCB: 1
+
+    # Enable shell commands.
+    STATS_CLI: 1
+    LOG_CLI: 1
+    CONFIG_CLI: 1
+
+    ETH_0: 1
+


[10/30] incubator-mynewt-core git commit: olimex_stm32-e407; add syscfg option to enable ethernet.

Posted by ad...@apache.org.
olimex_stm32-e407; add syscfg option to enable ethernet.


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/c9afda6e
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/c9afda6e
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/c9afda6e

Branch: refs/heads/master
Commit: c9afda6eacafbe2ff004e93d72bdb5e9a2664755
Parents: c5f8cf6
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Fri Apr 14 10:43:49 2017 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Fri Apr 14 13:21:30 2017 -0700

----------------------------------------------------------------------
 .../include/bsp/stm32f4xx_hal_conf.h            |  1 +
 hw/bsp/olimex_stm32-e407_devboard/pkg.yml       |  4 +-
 hw/bsp/olimex_stm32-e407_devboard/src/hal_bsp.c | 41 +++++++++++++++++++-
 hw/bsp/olimex_stm32-e407_devboard/syscfg.yml    |  4 ++
 4 files changed, 46 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/c9afda6e/hw/bsp/olimex_stm32-e407_devboard/include/bsp/stm32f4xx_hal_conf.h
----------------------------------------------------------------------
diff --git a/hw/bsp/olimex_stm32-e407_devboard/include/bsp/stm32f4xx_hal_conf.h b/hw/bsp/olimex_stm32-e407_devboard/include/bsp/stm32f4xx_hal_conf.h
index fb65323..b2b7717 100644
--- a/hw/bsp/olimex_stm32-e407_devboard/include/bsp/stm32f4xx_hal_conf.h
+++ b/hw/bsp/olimex_stm32-e407_devboard/include/bsp/stm32f4xx_hal_conf.h
@@ -95,6 +95,7 @@
 #define HAL_FLASH_MODULE_ENABLED
 #define HAL_GPIO_MODULE_ENABLED
 #define HAL_I2C_MODULE_ENABLED
+#define HAL_ETH_MODULE_ENABLED
 #define HAL_IWDG_MODULE_ENABLED
 #define HAL_PWR_MODULE_ENABLED
 #define HAL_RCC_MODULE_ENABLED

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/c9afda6e/hw/bsp/olimex_stm32-e407_devboard/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/olimex_stm32-e407_devboard/pkg.yml b/hw/bsp/olimex_stm32-e407_devboard/pkg.yml
index 7aefaab..f4e6020 100644
--- a/hw/bsp/olimex_stm32-e407_devboard/pkg.yml
+++ b/hw/bsp/olimex_stm32-e407_devboard/pkg.yml
@@ -48,5 +48,5 @@ pkg.deps.ADC_3:
 pkg.deps.UART_0:
     - hw/drivers/uart/uart_hal
 
-pkg.deps.UART_1:
-    - hw/drivers/uart/uart_bitbang
+pkg.deps.ETH_0:
+    - hw/drivers/lwip/stm32_eth

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/c9afda6e/hw/bsp/olimex_stm32-e407_devboard/src/hal_bsp.c
----------------------------------------------------------------------
diff --git a/hw/bsp/olimex_stm32-e407_devboard/src/hal_bsp.c b/hw/bsp/olimex_stm32-e407_devboard/src/hal_bsp.c
index d0bcc39..8d9daf7 100644
--- a/hw/bsp/olimex_stm32-e407_devboard/src/hal_bsp.c
+++ b/hw/bsp/olimex_stm32-e407_devboard/src/hal_bsp.c
@@ -41,6 +41,10 @@
 #if MYNEWT_VAL(SPI_0_MASTER) || MYNEWT_VAL(SPI_0_SLAVE)
 #include "hal/hal_spi.h"
 #endif
+#if MYNEWT_VAL(ETH_0)
+#include "stm32_eth/stm32_eth.h"
+#include "stm32_eth/stm32_eth_cfg.h"
+#endif
 #include "mcu/stm32f4_bsp.h"
 #include "mcu/stm32f4xx_mynewt_hal.h"
 
@@ -48,8 +52,6 @@
 struct uart_dev hal_uart0;
 #endif
 
-/* XXX should not be here */
-
 #if MYNEWT_VAL(ADC_1)
 struct adc_dev my_dev_adc1;
 #endif
@@ -286,6 +288,36 @@ static const struct stm32f4_uart_cfg uart_cfg0 = {
     .suc_irqn = USART6_IRQn
 };
 #endif
+#if MYNEWT_VAL(ETH_0)
+static const struct stm32_eth_cfg eth_cfg = {
+    /*
+     * PORTA
+     *   PA1 - ETH_RMII_REF_CLK
+     *   PA2 - ETH_RMII_MDIO
+     *   PA3 - ETH_RMII_MDINT  (GPIO irq?)
+     *   PA7 - ETH_RMII_CRS_DV
+     */
+    .sec_port_mask[0] = (1 << 1) | (1 << 2) | (1 << 7),
+
+    /*
+     * PORTC
+     *   PC1 - ETH_RMII_MDC
+     *   PC4 - ETH_RMII_RXD0
+     *   PC5 - ETH_RMII_RXD1
+     */
+    .sec_port_mask[2] = (1 << 1) | (1 << 4) | (1 << 5),
+
+    /*
+     * PORTG
+     *   PG11 - ETH_RMII_TXEN
+     *   PG13 - ETH_RMII_TXD0
+     *   PG14 - ETH_RMII_TXD1
+     */
+    .sec_port_mask[6] = (1 << 11) | (1 << 13) | (1 << 14),
+    .sec_phy_type = SMSC_8710_RMII,
+    .sec_phy_irq = MCU_GPIO_PORTA(3)
+};
+#endif
 static const struct hal_bsp_mem_dump dump_cfg[] = {
     [0] = {
         .hbmd_start = &_ram_start,
@@ -387,4 +419,9 @@ hal_bsp_init(void)
 #if MYNEWT_VAL(TIMER_0)
     hal_timer_init(0, TIM9);
 #endif
+
+#if MYNEWT_VAL(ETH_0)
+    rc = stm32_eth_init(&eth_cfg);
+    assert(rc == 0);
+#endif
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/c9afda6e/hw/bsp/olimex_stm32-e407_devboard/syscfg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/olimex_stm32-e407_devboard/syscfg.yml b/hw/bsp/olimex_stm32-e407_devboard/syscfg.yml
index 7b2fe59..4e49b0c 100644
--- a/hw/bsp/olimex_stm32-e407_devboard/syscfg.yml
+++ b/hw/bsp/olimex_stm32-e407_devboard/syscfg.yml
@@ -52,6 +52,10 @@ syscfg.defs:
         description: 'TIMER_0'
         value: 0
 
+    ETH_0:
+        description: 'Ethernet driver for LwIP'
+        value: 0
+
 syscfg.vals:
     REBOOT_LOG_FLASH_AREA: FLASH_AREA_REBOOT_LOG
     CONFIG_FCB_FLASH_AREA: FLASH_AREA_NFFS


[13/30] incubator-mynewt-core git commit: baselibc; add strnstr() - used by lwip.

Posted by ad...@apache.org.
baselibc; add strnstr() - used by lwip.


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/73a32024
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/73a32024
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/73a32024

Branch: refs/heads/master
Commit: 73a320244d4fd89124bc3b2d38e1aac597729749
Parents: e9ab595
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Fri Apr 14 10:46:49 2017 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Fri Apr 14 13:21:30 2017 -0700

----------------------------------------------------------------------
 libc/baselibc/include/string.h | 1 +
 libc/baselibc/src/strstr.c     | 5 +++++
 2 files changed, 6 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/73a32024/libc/baselibc/include/string.h
----------------------------------------------------------------------
diff --git a/libc/baselibc/include/string.h b/libc/baselibc/include/string.h
index a483a15..3595470 100644
--- a/libc/baselibc/include/string.h
+++ b/libc/baselibc/include/string.h
@@ -45,6 +45,7 @@ __extern char *strpbrk(const char *, const char *);
 __extern char *strsep(char **, const char *);
 __extern size_t strspn(const char *, const char *);
 __extern char *strstr(const char *, const char *);
+__extern char *strnstr(const char *, const char *, size_t);
 __extern char *strtok(char *, const char *);
 __extern char *strtok_r(char *, const char *, char **);
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/73a32024/libc/baselibc/src/strstr.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strstr.c b/libc/baselibc/src/strstr.c
index 8850858..0af23bb 100644
--- a/libc/baselibc/src/strstr.c
+++ b/libc/baselibc/src/strstr.c
@@ -9,3 +9,8 @@ char *strstr(const char *haystack, const char *needle)
 	return (char *)memmem(haystack, strlen(haystack), needle,
 			      strlen(needle));
 }
+
+char *strnstr(const char *haystack, const char *needle, size_t len)
+{
+	return (char *)memmem(haystack, strlen(haystack), needle, len);
+}


[03/30] incubator-mynewt-core git commit: net/ip; use pkg_init to initialize this package.

Posted by ad...@apache.org.
net/ip; use pkg_init to initialize this package.


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/1eaee93d
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/1eaee93d
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/1eaee93d

Branch: refs/heads/master
Commit: 1eaee93d729a752031b8640eb74d4a1afbb5d000
Parents: 7701a12
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Fri Apr 14 12:49:49 2017 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Fri Apr 14 13:21:30 2017 -0700

----------------------------------------------------------------------
 net/ip/include/ip/init.h | 32 --------------------------------
 net/ip/pkg.yml           |  4 ++++
 2 files changed, 4 insertions(+), 32 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/1eaee93d/net/ip/include/ip/init.h
----------------------------------------------------------------------
diff --git a/net/ip/include/ip/init.h b/net/ip/include/ip/init.h
deleted file mode 100644
index af90799..0000000
--- a/net/ip/include/ip/init.h
+++ /dev/null
@@ -1,32 +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.
- */
-#ifndef __IP_INIT_H__
-#define __IP_INIT_H__
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-int ip_init(void);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __IP_INIT_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/1eaee93d/net/ip/pkg.yml
----------------------------------------------------------------------
diff --git a/net/ip/pkg.yml b/net/ip/pkg.yml
index 3387728..0f657f1 100644
--- a/net/ip/pkg.yml
+++ b/net/ip/pkg.yml
@@ -30,3 +30,7 @@ pkg.keywords:
 pkg.deps:
     - kernel/os
     - net/ip/lwip_base
+    - net/ip/mn_socket
+
+pkg.init:
+    ip_init: 200


[16/30] incubator-mynewt-core git commit: net/ip/lwip_base; update to LwIP to tag STABLE-2_0_2_RELEASE

Posted by ad...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/netif.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/netif.c b/net/ip/lwip_base/src/core/netif.c
index 7ea4482..428b148 100644
--- a/net/ip/lwip_base/src/core/netif.c
+++ b/net/ip/lwip_base/src/core/netif.c
@@ -58,6 +58,7 @@
 #include "lwip/netif.h"
 #include "lwip/priv/tcp_priv.h"
 #include "lwip/udp.h"
+#include "lwip/raw.h"
 #include "lwip/snmp.h"
 #include "lwip/igmp.h"
 #include "lwip/etharp.h"
@@ -179,7 +180,7 @@ netif_init(void)
 #endif /* NO_SYS */
 
 #if LWIP_IPV6
-  IP_ADDR6(loop_netif.ip6_addr, 0, 0, 0, PP_HTONL(0x00000001UL));
+  IP_ADDR6_HOST(loop_netif.ip6_addr, 0, 0, 0, 0x00000001UL);
   loop_netif.ip6_addr_state[0] = IP6_ADDR_VALID;
 #endif /* LWIP_IPV6 */
 
@@ -227,8 +228,13 @@ netif_input(struct pbuf *p, struct netif *inp)
  * These functions use netif flags NETIF_FLAG_ETHARP and NETIF_FLAG_ETHERNET
  * to decide whether to forward to ethernet_input() or ip_input().
  * In other words, the functions only work when the netif
- * driver is implemented correctly!
- *
+ * driver is implemented correctly!\n
+ * Most members of struct netif should be be initialized by the 
+ * netif init function = netif driver (init parameter of this function).\n
+ * IPv6: Don't forget to call netif_create_ip6_linklocal_address() after
+ * setting the MAC address in struct netif.hwaddr
+ * (IPv6 requires a link-local address).
+ * 
  * @return netif, or NULL if failed.
  */
 struct netif *
@@ -253,7 +259,7 @@ netif_add(struct netif *netif,
 #if LWIP_IPV6
   for (i = 0; i < LWIP_IPV6_NUM_ADDRESSES; i++) {
     ip_addr_set_zero_ip6(&netif->ip6_addr[i]);
-    netif->ip6_addr_state[0] = IP6_ADDR_INVALID;
+    netif->ip6_addr_state[i] = IP6_ADDR_INVALID;
   }
   netif->output_ip6 = netif_null_output_ip6;
 #endif /* LWIP_IPV6 */
@@ -386,6 +392,9 @@ netif_remove(struct netif *netif)
 #if LWIP_UDP
     udp_netif_ip_addr_changed(netif_ip_addr4(netif), NULL);
 #endif /* LWIP_UDP */
+#if LWIP_RAW
+    raw_netif_ip_addr_changed(netif_ip_addr4(netif), NULL);
+#endif /* LWIP_RAW */
   }
 
 #if LWIP_IGMP
@@ -405,6 +414,9 @@ netif_remove(struct netif *netif)
 #if LWIP_UDP
       udp_netif_ip_addr_changed(netif_ip_addr6(netif, i), NULL);
 #endif /* LWIP_UDP */
+#if LWIP_RAW
+      raw_netif_ip_addr_changed(netif_ip_addr6(netif, i), NULL);
+#endif /* LWIP_RAW */
     }
   }
 #if LWIP_IPV6_MLD
@@ -466,7 +478,7 @@ netif_find(const char *name)
     return NULL;
   }
 
-  num = name[2] - '0';
+  num = (u8_t)(name[2] - '0');
 
   for (netif = netif_list; netif != NULL; netif = netif->next) {
     if (num == netif->num &&
@@ -495,7 +507,7 @@ void
 netif_set_ipaddr(struct netif *netif, const ip4_addr_t *ipaddr)
 {
   ip_addr_t new_addr;
-  *ip_2_ip4(&new_addr) = (ipaddr ? *ipaddr : *IP4_ADDR_ANY);
+  *ip_2_ip4(&new_addr) = (ipaddr ? *ipaddr : *IP4_ADDR_ANY4);
   IP_SET_TYPE_VAL(new_addr, IPADDR_TYPE_V4);
 
   /* address is actually being changed? */
@@ -507,6 +519,9 @@ netif_set_ipaddr(struct netif *netif, const ip4_addr_t *ipaddr)
 #if LWIP_UDP
     udp_netif_ip_addr_changed(netif_ip_addr4(netif), &new_addr);
 #endif /* LWIP_UDP */
+#if LWIP_RAW
+    raw_netif_ip_addr_changed(netif_ip_addr4(netif), &new_addr);
+#endif /* LWIP_RAW */
 
     mib2_remove_ip4(netif);
     mib2_remove_route_ip4(0, netif);
@@ -786,7 +801,7 @@ netif_loop_output(struct netif *netif, struct pbuf *p)
   err_t err;
   struct pbuf *last;
 #if LWIP_LOOPBACK_MAX_PBUFS
-  u8_t clen = 0;
+  u16_t clen = 0;
 #endif /* LWIP_LOOPBACK_MAX_PBUFS */
   /* If we have a loopif, SNMP counters are adjusted for it,
    * if not they are adjusted for 'netif'. */
@@ -889,7 +904,6 @@ netif_loop_output_ipv6(struct netif *netif, struct pbuf *p, const ip6_addr_t* ad
 void
 netif_poll(struct netif *netif)
 {
-  struct pbuf *in;
   /* If we have a loopif, SNMP counters are adjusted for it,
    * if not they are adjusted for 'netif'. */
 #if MIB2_STATS
@@ -901,56 +915,52 @@ netif_poll(struct netif *netif)
 #endif /* MIB2_STATS */
   SYS_ARCH_DECL_PROTECT(lev);
 
-  do {
-    /* Get a packet from the list. With SYS_LIGHTWEIGHT_PROT=1, this is protected */
-    SYS_ARCH_PROTECT(lev);
-    in = netif->loop_first;
-    if (in != NULL) {
-      struct pbuf *in_end = in;
+  /* Get a packet from the list. With SYS_LIGHTWEIGHT_PROT=1, this is protected */
+  SYS_ARCH_PROTECT(lev);
+  while (netif->loop_first != NULL) {
+    struct pbuf *in, *in_end;
 #if LWIP_LOOPBACK_MAX_PBUFS
-      u8_t clen = 1;
+    u8_t clen = 1;
 #endif /* LWIP_LOOPBACK_MAX_PBUFS */
-      while (in_end->len != in_end->tot_len) {
-        LWIP_ASSERT("bogus pbuf: len != tot_len but next == NULL!", in_end->next != NULL);
-        in_end = in_end->next;
+
+    in = in_end = netif->loop_first;
+    while (in_end->len != in_end->tot_len) {
+      LWIP_ASSERT("bogus pbuf: len != tot_len but next == NULL!", in_end->next != NULL);
+      in_end = in_end->next;
 #if LWIP_LOOPBACK_MAX_PBUFS
-        clen++;
+      clen++;
 #endif /* LWIP_LOOPBACK_MAX_PBUFS */
-      }
+    }
 #if LWIP_LOOPBACK_MAX_PBUFS
-      /* adjust the number of pbufs on queue */
-      LWIP_ASSERT("netif->loop_cnt_current underflow",
-        ((netif->loop_cnt_current - clen) < netif->loop_cnt_current));
-      netif->loop_cnt_current -= clen;
+    /* adjust the number of pbufs on queue */
+    LWIP_ASSERT("netif->loop_cnt_current underflow",
+      ((netif->loop_cnt_current - clen) < netif->loop_cnt_current));
+    netif->loop_cnt_current -= clen;
 #endif /* LWIP_LOOPBACK_MAX_PBUFS */
 
-      /* 'in_end' now points to the last pbuf from 'in' */
-      if (in_end == netif->loop_last) {
-        /* this was the last pbuf in the list */
-        netif->loop_first = netif->loop_last = NULL;
-      } else {
-        /* pop the pbuf off the list */
-        netif->loop_first = in_end->next;
-        LWIP_ASSERT("should not be null since first != last!", netif->loop_first != NULL);
-      }
-      /* De-queue the pbuf from its successors on the 'loop_' list. */
-      in_end->next = NULL;
+    /* 'in_end' now points to the last pbuf from 'in' */
+    if (in_end == netif->loop_last) {
+      /* this was the last pbuf in the list */
+      netif->loop_first = netif->loop_last = NULL;
+    } else {
+      /* pop the pbuf off the list */
+      netif->loop_first = in_end->next;
+      LWIP_ASSERT("should not be null since first != last!", netif->loop_first != NULL);
     }
+    /* De-queue the pbuf from its successors on the 'loop_' list. */
+    in_end->next = NULL;
     SYS_ARCH_UNPROTECT(lev);
 
-    if (in != NULL) {
-      LINK_STATS_INC(link.recv);
-      MIB2_STATS_NETIF_ADD(stats_if, ifinoctets, in->tot_len);
-      MIB2_STATS_NETIF_INC(stats_if, ifinucastpkts);
-      /* loopback packets are always IP packets! */
-      if (ip_input(in, netif) != ERR_OK) {
-        pbuf_free(in);
-      }
-      /* Don't reference the packet any more! */
-      in = NULL;
+    LINK_STATS_INC(link.recv);
+    MIB2_STATS_NETIF_ADD(stats_if, ifinoctets, in->tot_len);
+    MIB2_STATS_NETIF_INC(stats_if, ifinucastpkts);
+    /* loopback packets are always IP packets! */
+    if (ip_input(in, netif) != ERR_OK) {
+      pbuf_free(in);
     }
-  /* go on while there is a packet on the list */
-  } while (netif->loop_first != NULL);
+    SYS_ARCH_PROTECT(lev);
+  }
+  SYS_ARCH_UNPROTECT(lev);
 }
 
 #if !LWIP_NETIF_LOOPBACK_MULTITHREADING
@@ -1042,6 +1052,9 @@ netif_ip6_addr_set_parts(struct netif *netif, s8_t addr_idx, u32_t i0, u32_t i1,
 #if LWIP_UDP
       udp_netif_ip_addr_changed(netif_ip_addr6(netif, addr_idx), &new_ipaddr);
 #endif /* LWIP_UDP */
+#if LWIP_RAW
+      raw_netif_ip_addr_changed(netif_ip_addr6(netif, addr_idx), &new_ipaddr);
+#endif /* LWIP_RAW */
     }
     /* @todo: remove/readd mib2 ip6 entries? */
 
@@ -1083,6 +1096,13 @@ netif_ip6_addr_set_state(struct netif* netif, s8_t addr_idx, u8_t state)
     u8_t new_valid = state & IP6_ADDR_VALID;
     LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_STATE, ("netif_ip6_addr_set_state: netif address state being changed\n"));
 
+#if LWIP_IPV6_MLD
+    /* Reevaluate solicited-node multicast group membership. */
+    if (netif->flags & NETIF_FLAG_MLD6) {
+      nd6_adjust_mld_membership(netif, addr_idx, state);
+    }
+#endif /* LWIP_IPV6_MLD */
+
     if (old_valid && !new_valid) {
       /* address about to be removed by setting invalid */
 #if LWIP_TCP
@@ -1091,6 +1111,9 @@ netif_ip6_addr_set_state(struct netif* netif, s8_t addr_idx, u8_t state)
 #if LWIP_UDP
       udp_netif_ip_addr_changed(netif_ip_addr6(netif, addr_idx), NULL);
 #endif /* LWIP_UDP */
+#if LWIP_RAW
+      raw_netif_ip_addr_changed(netif_ip_addr6(netif, addr_idx), NULL);
+#endif /* LWIP_RAW */
       /* @todo: remove mib2 ip6 entries? */
     }
     netif->ip6_addr_state[addr_idx] = state;
@@ -1154,11 +1177,11 @@ netif_create_ip6_linklocal_address(struct netif *netif, u8_t from_mac_48bit)
   /* Generate interface ID. */
   if (from_mac_48bit) {
     /* Assume hwaddr is a 48-bit IEEE 802 MAC. Convert to EUI-64 address. Complement Group bit. */
-    ip_2_ip6(&netif->ip6_addr[0])->addr[2] = htonl((((u32_t)(netif->hwaddr[0] ^ 0x02)) << 24) |
+    ip_2_ip6(&netif->ip6_addr[0])->addr[2] = lwip_htonl((((u32_t)(netif->hwaddr[0] ^ 0x02)) << 24) |
         ((u32_t)(netif->hwaddr[1]) << 16) |
         ((u32_t)(netif->hwaddr[2]) << 8) |
         (0xff));
-    ip_2_ip6(&netif->ip6_addr[0])->addr[3] = htonl((0xfeul << 24) |
+    ip_2_ip6(&netif->ip6_addr[0])->addr[3] = lwip_htonl((0xfeul << 24) |
         ((u32_t)(netif->hwaddr[3]) << 16) |
         ((u32_t)(netif->hwaddr[4]) << 8) |
         (netif->hwaddr[5]));
@@ -1179,10 +1202,10 @@ netif_create_ip6_linklocal_address(struct netif *netif, u8_t from_mac_48bit)
   /* Set address state. */
 #if LWIP_IPV6_DUP_DETECT_ATTEMPTS
   /* Will perform duplicate address detection (DAD). */
-  netif->ip6_addr_state[0] = IP6_ADDR_TENTATIVE;
+  netif_ip6_addr_set_state(netif, 0, IP6_ADDR_TENTATIVE);
 #else
   /* Consider address valid. */
-  netif->ip6_addr_state[0] = IP6_ADDR_PREFERRED;
+  netif_ip6_addr_set_state(netif, 0, IP6_ADDR_PREFERRED);
 #endif /* LWIP_IPV6_AUTOCONFIG */
 }
 
@@ -1212,7 +1235,7 @@ netif_add_ip6_address(struct netif *netif, const ip6_addr_t *ip6addr, s8_t *chos
 
   /* Find a free slot -- musn't be the first one (reserved for link local) */
   for (i = 1; i < LWIP_IPV6_NUM_ADDRESSES; i++) {
-    if (!ip6_addr_isvalid(netif->ip6_addr_state[i])) {
+    if (ip6_addr_isinvalid(netif_ip6_addr_state(netif, i))) {
       ip_addr_copy_from_ip6(netif->ip6_addr[i], *ip6addr);
       netif_ip6_addr_set_state(netif, i, IP6_ADDR_TENTATIVE);
       if (chosen_idx != NULL) {

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/pbuf.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/pbuf.c b/net/ip/lwip_base/src/core/pbuf.c
index a145dff..059f83a 100644
--- a/net/ip/lwip_base/src/core/pbuf.c
+++ b/net/ip/lwip_base/src/core/pbuf.c
@@ -41,21 +41,28 @@ typedef struct my_custom_pbuf
    void* dma_descriptor;
 } my_custom_pbuf_t;
 
+LWIP_MEMPOOL_DECLARE(RX_POOL, 10, sizeof(my_custom_pbuf_t), "Zero-copy RX PBUF pool");
+
 void my_pbuf_free_custom(void* p)
 {
   my_custom_pbuf_t* my_puf = (my_custom_pbuf_t*)p;
+
+  LOCK_INTERRUPTS();
   free_rx_dma_descriptor(my_pbuf->dma_descriptor);
-  my_pbuf_pool_put(my_pbuf);
+  LWIP_MEMPOOL_FREE(RX_POOL, my_pbuf);
+  UNLOCK_INTERRUPTS();
 }
 
 void eth_rx_irq()
 {
   dma_descriptor*   dma_desc = get_RX_DMA_descriptor_from_ethernet();
-  my_custom_pbuf_t* my_pbuf  = my_pbuf_pool_get();
+  my_custom_pbuf_t* my_pbuf  = (my_custom_pbuf_t*)LWIP_MEMPOOL_ALLOC(RX_POOL);
 
   my_pbuf->p.custom_free_function = my_pbuf_free_custom;
   my_pbuf->dma_descriptor         = dma_desc;
 
+  invalidate_cpu_cache(dma_desc->rx_data, dma_desc->rx_length);
+  
   struct pbuf* p = pbuf_alloced_custom(PBUF_RAW,
      dma_desc->rx_length,
      PBUF_REF,
@@ -343,8 +350,18 @@ pbuf_alloc(pbuf_layer layer, u16_t length, pbuf_type type)
 
     break;
   case PBUF_RAM:
-    /* If pbuf is to be allocated in RAM, allocate memory for it. */
-    p = (struct pbuf*)mem_malloc(LWIP_MEM_ALIGN_SIZE(SIZEOF_STRUCT_PBUF + offset) + LWIP_MEM_ALIGN_SIZE(length));
+    {
+      mem_size_t alloc_len = LWIP_MEM_ALIGN_SIZE(SIZEOF_STRUCT_PBUF + offset) + LWIP_MEM_ALIGN_SIZE(length);
+      
+      /* bug #50040: Check for integer overflow when calculating alloc_len */
+      if (alloc_len < LWIP_MEM_ALIGN_SIZE(length)) {
+        return NULL;
+      }
+    
+      /* If pbuf is to be allocated in RAM, allocate memory for it. */
+      p = (struct pbuf*)mem_malloc(alloc_len);
+    }
+
     if (p == NULL) {
       return NULL;
     }
@@ -561,11 +578,11 @@ pbuf_header_impl(struct pbuf *p, s16_t header_size_increment, u8_t force)
   }
 
   if (header_size_increment < 0) {
-    increment_magnitude = -header_size_increment;
+    increment_magnitude = (u16_t)-header_size_increment;
     /* Check that we aren't going to move off the end of the pbuf */
     LWIP_ERROR("increment_magnitude <= p->len", (increment_magnitude <= p->len), return 1;);
   } else {
-    increment_magnitude = header_size_increment;
+    increment_magnitude = (u16_t)header_size_increment;
 #if 0
     /* Can't assert these as some callers speculatively call
          pbuf_header() to see if it's OK.  Will return 1 below instead. */
@@ -779,10 +796,10 @@ pbuf_free(struct pbuf *p)
  * @param p first pbuf of chain
  * @return the number of pbufs in a chain
  */
-u8_t
-pbuf_clen(struct pbuf *p)
+u16_t
+pbuf_clen(const struct pbuf *p)
 {
-  u8_t len;
+  u16_t len;
 
   len = 0;
   while (p != NULL) {
@@ -805,6 +822,7 @@ pbuf_ref(struct pbuf *p)
   /* pbuf given? */
   if (p != NULL) {
     SYS_ARCH_INC(p->ref, 1);
+    LWIP_ASSERT("pbuf ref overflow", p->ref > 0);
   }
 }
 
@@ -927,12 +945,12 @@ pbuf_dechain(struct pbuf *p)
  *                 enough to hold p_from
  */
 err_t
-pbuf_copy(struct pbuf *p_to, struct pbuf *p_from)
+pbuf_copy(struct pbuf *p_to, const struct pbuf *p_from)
 {
   u16_t offset_to=0, offset_from=0, len;
 
   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_copy(%p, %p)\n",
-    (void*)p_to, (void*)p_from));
+    (const void*)p_to, (const void*)p_from));
 
   /* is the target big enough to hold the source? */
   LWIP_ERROR("pbuf_copy: target not big enough to hold source", ((p_to != NULL) &&
@@ -994,9 +1012,9 @@ pbuf_copy(struct pbuf *p_to, struct pbuf *p_from)
  * @return the number of bytes copied, or 0 on failure
  */
 u16_t
-pbuf_copy_partial(struct pbuf *buf, void *dataptr, u16_t len, u16_t offset)
+pbuf_copy_partial(const struct pbuf *buf, void *dataptr, u16_t len, u16_t offset)
 {
-  struct pbuf *p;
+  const struct pbuf *p;
   u16_t left;
   u16_t buf_copy_len;
   u16_t copied_total = 0;
@@ -1082,20 +1100,12 @@ void pbuf_split_64k(struct pbuf *p, struct pbuf **rest)
 }
 #endif /* LWIP_TCP && TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
 
-/**
- * @ingroup pbuf
- * Skip a number of bytes at the start of a pbuf
- *
- * @param in input pbuf
- * @param in_offset offset to skip
- * @param out_offset resulting offset in the returned pbuf
- * @return the pbuf in the queue where the offset is
- */
-struct pbuf*
-pbuf_skip(struct pbuf* in, u16_t in_offset, u16_t* out_offset)
+/* Actual implementation of pbuf_skip() but returning const pointer... */
+static const struct pbuf*
+pbuf_skip_const(const struct pbuf* in, u16_t in_offset, u16_t* out_offset)
 {
   u16_t offset_left = in_offset;
-  struct pbuf* q = in;
+  const struct pbuf* q = in;
 
   /* get the correct pbuf */
   while ((q != NULL) && (q->len <= offset_left)) {
@@ -1110,6 +1120,22 @@ pbuf_skip(struct pbuf* in, u16_t in_offset, u16_t* out_offset)
 
 /**
  * @ingroup pbuf
+ * Skip a number of bytes at the start of a pbuf
+ *
+ * @param in input pbuf
+ * @param in_offset offset to skip
+ * @param out_offset resulting offset in the returned pbuf
+ * @return the pbuf in the queue where the offset is
+ */
+struct pbuf*
+pbuf_skip(struct pbuf* in, u16_t in_offset, u16_t* out_offset)
+{
+  const struct pbuf* out = pbuf_skip_const(in, in_offset, out_offset);
+  return LWIP_CONST_CAST(struct pbuf*, out);
+}
+
+/**
+ * @ingroup pbuf
  * Copy application supplied data into a pbuf.
  * This function can only be used to copy the equivalent of buf->tot_len data.
  *
@@ -1213,6 +1239,7 @@ pbuf_coalesce(struct pbuf *p, pbuf_layer layer)
     return p;
   }
   err = pbuf_copy(q, p);
+  LWIP_UNUSED_ARG(err); /* in case of LWIP_NOASSERT */
   LWIP_ASSERT("pbuf_copy failed", err == ERR_OK);
   pbuf_free(p);
   return q;
@@ -1269,7 +1296,7 @@ pbuf_fill_chksum(struct pbuf *p, u16_t start_offset, const void *dataptr,
  * @return byte at an offset into p OR ZERO IF 'offset' >= p->tot_len
  */
 u8_t
-pbuf_get_at(struct pbuf* p, u16_t offset)
+pbuf_get_at(const struct pbuf* p, u16_t offset)
 {
   int ret = pbuf_try_get_at(p, offset);
   if (ret >= 0) {
@@ -1287,10 +1314,10 @@ pbuf_get_at(struct pbuf* p, u16_t offset)
  * @return byte at an offset into p [0..0xFF] OR negative if 'offset' >= p->tot_len
  */
 int
-pbuf_try_get_at(struct pbuf* p, u16_t offset)
+pbuf_try_get_at(const struct pbuf* p, u16_t offset)
 {
   u16_t q_idx;
-  struct pbuf* q = pbuf_skip(p, offset, &q_idx);
+  const struct pbuf* q = pbuf_skip_const(p, offset, &q_idx);
 
   /* return requested data if pbuf is OK */
   if ((q != NULL) && (q->len > q_idx)) {
@@ -1332,10 +1359,10 @@ pbuf_put_at(struct pbuf* p, u16_t offset, u8_t data)
  *         (0xffff if p is too short, diffoffset+1 otherwise)
  */
 u16_t
-pbuf_memcmp(struct pbuf* p, u16_t offset, const void* s2, u16_t n)
+pbuf_memcmp(const struct pbuf* p, u16_t offset, const void* s2, u16_t n)
 {
   u16_t start = offset;
-  struct pbuf* q = p;
+  const struct pbuf* q = p;
   u16_t i;
  
   /* pbuf long enough to perform check? */
@@ -1374,7 +1401,7 @@ pbuf_memcmp(struct pbuf* p, u16_t offset, const void* s2, u16_t n)
  * @return 0xFFFF if substr was not found in p or the index where it was found
  */
 u16_t
-pbuf_memfind(struct pbuf* p, const void* mem, u16_t mem_len, u16_t start_offset)
+pbuf_memfind(const struct pbuf* p, const void* mem, u16_t mem_len, u16_t start_offset)
 {
   u16_t i;
   u16_t max = p->tot_len - mem_len;
@@ -1401,7 +1428,7 @@ pbuf_memfind(struct pbuf* p, const void* mem, u16_t mem_len, u16_t start_offset)
  * @return 0xFFFF if substr was not found in p or the index where it was found
  */
 u16_t
-pbuf_strstr(struct pbuf* p, const char* substr)
+pbuf_strstr(const struct pbuf* p, const char* substr)
 {
   size_t substr_len;
   if ((substr == NULL) || (substr[0] == 0) || (p->tot_len == 0xFFFF)) {

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/raw.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/raw.c b/net/ip/lwip_base/src/core/raw.c
index a3a9077..80cf9ec 100644
--- a/net/ip/lwip_base/src/core/raw.c
+++ b/net/ip/lwip_base/src/core/raw.c
@@ -196,7 +196,7 @@ raw_input(struct pbuf *p, struct netif *inp)
  * Bind a RAW PCB.
  *
  * @param pcb RAW PCB to be bound with a local address ipaddr.
- * @param ipaddr local IP address to bind with. Use IP_ADDR_ANY to
+ * @param ipaddr local IP address to bind with. Use IP4_ADDR_ANY to
  * bind to all local interfaces.
  *
  * @return lwIP error code.
@@ -209,7 +209,7 @@ raw_input(struct pbuf *p, struct netif *inp)
 err_t
 raw_bind(struct raw_pcb *pcb, const ip_addr_t *ipaddr)
 {
-  if ((pcb == NULL) || (ipaddr == NULL) || !IP_ADDR_PCB_VERSION_MATCH_EXACT(pcb, ipaddr)) {
+  if ((pcb == NULL) || (ipaddr == NULL)) {
     return ERR_VAL;
   }
   ip_addr_set_ipaddr(&pcb->local_ip, ipaddr);
@@ -233,7 +233,7 @@ raw_bind(struct raw_pcb *pcb, const ip_addr_t *ipaddr)
 err_t
 raw_connect(struct raw_pcb *pcb, const ip_addr_t *ipaddr)
 {
-  if ((pcb == NULL) || (ipaddr == NULL) || !IP_ADDR_PCB_VERSION_MATCH_EXACT(pcb, ipaddr)) {
+  if ((pcb == NULL) || (ipaddr == NULL)) {
     return ERR_VAL;
   }
   ip_addr_set_ipaddr(&pcb->remote_ip, ipaddr);
@@ -250,9 +250,6 @@ raw_connect(struct raw_pcb *pcb, const ip_addr_t *ipaddr)
  *   packet will not be passed to other raw PCBs or other protocol layers.
  * - not free the packet, and return zero. The packet will be matched
  *   against further PCBs and/or forwarded to another protocol layers.
- *
- * @return non-zero if the packet was free()d, zero if the packet remains
- * available for others.
  */
 void
 raw_recv(struct raw_pcb *pcb, raw_recv_fn recv, void *recv_arg)
@@ -283,7 +280,6 @@ raw_sendto(struct raw_pcb *pcb, struct pbuf *p, const ip_addr_t *ipaddr)
   const ip_addr_t *src_ip;
   struct pbuf *q; /* q will be sent down the stack */
   s16_t header_size;
-  const ip_addr_t *dst_ip = ipaddr;
 
   if ((pcb == NULL) || (ipaddr == NULL) || !IP_ADDR_PCB_VERSION_MATCH(pcb, ipaddr)) {
     return ERR_VAL;
@@ -324,10 +320,16 @@ raw_sendto(struct raw_pcb *pcb, struct pbuf *p, const ip_addr_t *ipaddr)
     }
   }
 
-  netif = ip_route(&pcb->local_ip, dst_ip);
+  if(IP_IS_ANY_TYPE_VAL(pcb->local_ip)) {
+    /* Don't call ip_route() with IP_ANY_TYPE */
+    netif = ip_route(IP46_ADDR_ANY(IP_GET_TYPE(ipaddr)), ipaddr);
+  } else {
+    netif = ip_route(&pcb->local_ip, ipaddr);
+  }
+
   if (netif == NULL) {
     LWIP_DEBUGF(RAW_DEBUG | LWIP_DBG_LEVEL_WARNING, ("raw_sendto: No route to "));
-    ip_addr_debug_print(RAW_DEBUG | LWIP_DBG_LEVEL_WARNING, dst_ip);
+    ip_addr_debug_print(RAW_DEBUG | LWIP_DBG_LEVEL_WARNING, ipaddr);
     /* free any temporary header pbuf allocated by pbuf_header() */
     if (q != p) {
       pbuf_free(q);
@@ -352,7 +354,7 @@ raw_sendto(struct raw_pcb *pcb, struct pbuf *p, const ip_addr_t *ipaddr)
 
   if (ip_addr_isany(&pcb->local_ip)) {
     /* use outgoing network interface IP address as source address */
-    src_ip = ip_netif_get_local_ip(netif, dst_ip);
+    src_ip = ip_netif_get_local_ip(netif, ipaddr);
 #if LWIP_IPV6
     if (src_ip == NULL) {
       if (q != p) {
@@ -369,15 +371,15 @@ raw_sendto(struct raw_pcb *pcb, struct pbuf *p, const ip_addr_t *ipaddr)
 #if LWIP_IPV6
   /* If requested, based on the IPV6_CHECKSUM socket option per RFC3542,
      compute the checksum and update the checksum in the payload. */
-  if (IP_IS_V6(dst_ip) && pcb->chksum_reqd) {
-    u16_t chksum = ip6_chksum_pseudo(p, pcb->protocol, p->tot_len, ip_2_ip6(src_ip), ip_2_ip6(dst_ip));
+  if (IP_IS_V6(ipaddr) && pcb->chksum_reqd) {
+    u16_t chksum = ip6_chksum_pseudo(p, pcb->protocol, p->tot_len, ip_2_ip6(src_ip), ip_2_ip6(ipaddr));
     LWIP_ASSERT("Checksum must fit into first pbuf", p->len >= (pcb->chksum_offset + 2));
     SMEMCPY(((u8_t *)p->payload) + pcb->chksum_offset, &chksum, sizeof(u16_t));
   }
 #endif
 
   NETIF_SET_HWADDRHINT(netif, &pcb->addr_hint);
-  err = ip_output_if(q, src_ip, dst_ip, pcb->ttl, pcb->tos, pcb->protocol, netif);
+  err = ip_output_if(q, src_ip, ipaddr, pcb->ttl, pcb->tos, pcb->protocol, netif);
   NETIF_SET_HWADDRHINT(netif, NULL);
 
   /* did we chain a header earlier? */
@@ -471,7 +473,7 @@ raw_new(u8_t proto)
  * @return The RAW PCB which was created. NULL if the PCB data structure
  * could not be allocated.
  *
- * @param type IP address type, see IPADDR_TYPE_XX definitions.
+ * @param type IP address type, see @ref lwip_ip_addr_type definitions.
  * If you want to listen to IPv4 and IPv6 (dual-stack) packets,
  * supply @ref IPADDR_TYPE_ANY as argument and bind to @ref IP_ANY_TYPE.
  * @param proto the protocol number (next header) of the IPv6 packet payload
@@ -495,4 +497,25 @@ raw_new_ip_type(u8_t type, u8_t proto)
   return pcb;
 }
 
+/** This function is called from netif.c when address is changed
+ *
+ * @param old_addr IP address of the netif before change
+ * @param new_addr IP address of the netif after change
+ */
+void raw_netif_ip_addr_changed(const ip_addr_t* old_addr, const ip_addr_t* new_addr)
+{
+  struct raw_pcb* rpcb;
+
+  if (!ip_addr_isany(old_addr) && !ip_addr_isany(new_addr)) {
+    for (rpcb = raw_pcbs; rpcb != NULL; rpcb = rpcb->next) {
+      /* PCB bound to current local interface address? */
+      if (ip_addr_cmp(&rpcb->local_ip, old_addr)) {
+        /* The PCB is bound to the old ipaddr and
+         * is set to bound to the new one instead */
+        ip_addr_copy(rpcb->local_ip, *new_addr);
+      }
+    }
+  }
+}
+
 #endif /* LWIP_RAW */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/stats.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/stats.c b/net/ip/lwip_base/src/core/stats.c
index c75fff2..893d199 100644
--- a/net/ip/lwip_base/src/core/stats.c
+++ b/net/ip/lwip_base/src/core/stats.c
@@ -50,7 +50,7 @@
 struct stats_ lwip_stats;
 
 void
-lwip_stats_init(void)
+stats_init(void)
 {
 #ifdef LWIP_DEBUG
 #if MEM_STATS
@@ -96,7 +96,7 @@ stats_display_igmp(struct stats_igmp *igmp, const char *name)
   LWIP_PLATFORM_DIAG(("rx_report: %"STAT_COUNTER_F"\n\t", igmp->rx_report));
   LWIP_PLATFORM_DIAG(("tx_join: %"STAT_COUNTER_F"\n\t", igmp->tx_join));
   LWIP_PLATFORM_DIAG(("tx_leave: %"STAT_COUNTER_F"\n\t", igmp->tx_leave));
-  LWIP_PLATFORM_DIAG(("tx_report: %"STAT_COUNTER_F"\n\t", igmp->tx_report));
+  LWIP_PLATFORM_DIAG(("tx_report: %"STAT_COUNTER_F"\n", igmp->tx_report));
 }
 #endif /* IGMP_STATS || MLD6_STATS */
 
@@ -135,7 +135,7 @@ stats_display_sys(struct stats_sys *sys)
   LWIP_PLATFORM_DIAG(("mutex.err:  %"U32_F"\n\t", (u32_t)sys->mutex.err));
   LWIP_PLATFORM_DIAG(("mbox.used:  %"U32_F"\n\t", (u32_t)sys->mbox.used));
   LWIP_PLATFORM_DIAG(("mbox.max:   %"U32_F"\n\t", (u32_t)sys->mbox.max));
-  LWIP_PLATFORM_DIAG(("mbox.err:   %"U32_F"\n\t", (u32_t)sys->mbox.err));
+  LWIP_PLATFORM_DIAG(("mbox.err:   %"U32_F"\n", (u32_t)sys->mbox.err));
 }
 #endif /* SYS_STATS */
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/sys.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/sys.c b/net/ip/lwip_base/src/core/sys.c
index f177737..7059b4d 100644
--- a/net/ip/lwip_base/src/core/sys.c
+++ b/net/ip/lwip_base/src/core/sys.c
@@ -36,6 +36,44 @@
  *
  */
 
+/**
+ * @defgroup sys_layer Porting (system abstraction layer)
+ * @ingroup lwip
+ * @verbinclude "sys_arch.txt"
+ *
+ * @defgroup sys_os OS abstraction layer
+ * @ingroup sys_layer
+ * No need to implement functions in this section in NO_SYS mode.
+ *
+ * @defgroup sys_sem Semaphores
+ * @ingroup sys_os
+ *
+ * @defgroup sys_mutex Mutexes
+ * @ingroup sys_os
+ * Mutexes are recommended to correctly handle priority inversion,
+ * especially if you use LWIP_CORE_LOCKING .
+ *
+ * @defgroup sys_mbox Mailboxes
+ * @ingroup sys_os
+ *
+ * @defgroup sys_time Time
+ * @ingroup sys_layer
+ *
+ * @defgroup sys_prot Critical sections
+ * @ingroup sys_layer
+ * Used to protect short regions of code against concurrent access.
+ * - Your system is a bare-metal system (probably with an RTOS)
+ *   and interrupts are under your control:
+ *   Implement this as LockInterrupts() / UnlockInterrupts()
+ * - Your system uses an RTOS with deferred interrupt handling from a
+ *   worker thread: Implement as a global mutex or lock/unlock scheduler
+ * - Your system uses a high-level OS with e.g. POSIX signals:
+ *   Implement as a global mutex
+ *
+ * @defgroup sys_misc Misc
+ * @ingroup sys_os
+ */
+
 #include "lwip/opt.h"
 
 #include "lwip/sys.h"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/tcp.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/tcp.c b/net/ip/lwip_base/src/core/tcp.c
index 50aa31f..ec2e1f9 100644
--- a/net/ip/lwip_base/src/core/tcp.c
+++ b/net/ip/lwip_base/src/core/tcp.c
@@ -62,6 +62,10 @@
 
 #include <string.h>
 
+#ifdef LWIP_HOOK_FILENAME
+#include LWIP_HOOK_FILENAME
+#endif
+
 #ifndef TCP_LOCAL_PORT_RANGE_START
 /* From http://www.iana.org/assignments/port-numbers:
    "The Dynamic and/or Private Ports are those from 49152 through 65535" */
@@ -132,6 +136,8 @@ static u8_t tcp_timer;
 static u8_t tcp_timer_ctr;
 static u16_t tcp_new_port(void);
 
+static err_t tcp_close_shutdown_fin(struct tcp_pcb *pcb);
+
 /**
  * Initialize this module.
  */
@@ -258,8 +264,6 @@ tcp_backlog_accepted(struct tcp_pcb* pcb)
 static err_t
 tcp_close_shutdown(struct tcp_pcb *pcb, u8_t rst_on_unacked_data)
 {
-  err_t err;
-
   if (rst_on_unacked_data && ((pcb->state == ESTABLISHED) || (pcb->state == CLOSE_WAIT))) {
     if ((pcb->refused_data != NULL) || (pcb->rcv_wnd != TCP_WND_MAX(pcb))) {
       /* Not all data received by application, send RST to tell the remote
@@ -290,6 +294,8 @@ tcp_close_shutdown(struct tcp_pcb *pcb, u8_t rst_on_unacked_data)
     }
   }
 
+  /* - states which free the pcb are handled here,
+     - states which send FIN and change state are handled in tcp_close_shutdown_fin() */
   switch (pcb->state) {
   case CLOSED:
     /* Closing a pcb in the CLOSED state might seem erroneous,
@@ -299,27 +305,34 @@ tcp_close_shutdown(struct tcp_pcb *pcb, u8_t rst_on_unacked_data)
      * or for a pcb that has been used and then entered the CLOSED state
      * is erroneous, but this should never happen as the pcb has in those cases
      * been freed, and so any remaining handles are bogus. */
-    err = ERR_OK;
     if (pcb->local_port != 0) {
       TCP_RMV(&tcp_bound_pcbs, pcb);
     }
     memp_free(MEMP_TCP_PCB, pcb);
-    pcb = NULL;
     break;
   case LISTEN:
-    err = ERR_OK;
     tcp_listen_closed(pcb);
     tcp_pcb_remove(&tcp_listen_pcbs.pcbs, pcb);
     memp_free(MEMP_TCP_PCB_LISTEN, pcb);
-    pcb = NULL;
     break;
   case SYN_SENT:
-    err = ERR_OK;
     TCP_PCB_REMOVE_ACTIVE(pcb);
     memp_free(MEMP_TCP_PCB, pcb);
-    pcb = NULL;
     MIB2_STATS_INC(mib2.tcpattemptfails);
     break;
+  default:
+    return tcp_close_shutdown_fin(pcb);
+  }
+  return ERR_OK;
+}
+
+static err_t
+tcp_close_shutdown_fin(struct tcp_pcb *pcb)
+{
+  err_t err;
+  LWIP_ASSERT("pcb != NULL", pcb != NULL);
+
+  switch (pcb->state) {
   case SYN_RCVD:
     err = tcp_send_fin(pcb);
     if (err == ERR_OK) {
@@ -344,18 +357,20 @@ tcp_close_shutdown(struct tcp_pcb *pcb, u8_t rst_on_unacked_data)
     break;
   default:
     /* Has already been closed, do nothing. */
-    err = ERR_OK;
-    pcb = NULL;
+    return ERR_OK;
     break;
   }
 
-  if (pcb != NULL && err == ERR_OK) {
+  if (err == ERR_OK) {
     /* To ensure all data has been sent when tcp_close returns, we have
        to make sure tcp_output doesn't fail.
        Since we don't really have to ensure all data has been sent when tcp_close
        returns (unsent data is sent from tcp timer functions, also), we don't care
        for the return value of tcp_output for now. */
     tcp_output(pcb);
+  } else if (err == ERR_MEM) {
+    /* Mark this pcb for closing. Closing is retried from tcp_tmr. */
+    pcb->flags |= TF_CLOSEPEND;
   }
   return err;
 }
@@ -467,6 +482,7 @@ tcp_abandon(struct tcp_pcb *pcb, int reset)
   } else {
     int send_rst = 0;
     u16_t local_port = 0;
+    enum tcp_state last_state;
     seqno = pcb->snd_nxt;
     ackno = pcb->rcv_nxt;
 #if LWIP_CALLBACK_API
@@ -499,8 +515,9 @@ tcp_abandon(struct tcp_pcb *pcb, int reset)
       LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_abandon: sending RST\n"));
       tcp_rst(seqno, ackno, &pcb->local_ip, &pcb->remote_ip, local_port, pcb->remote_port);
     }
+    last_state = pcb->state;
     memp_free(MEMP_TCP_PCB, pcb);
-    TCP_EVENT_ERR(errf, errf_arg, ERR_ABRT);
+    TCP_EVENT_ERR(last_state, errf, errf_arg, ERR_ABRT);
   }
 }
 
@@ -529,7 +546,7 @@ tcp_abort(struct tcp_pcb *pcb)
  *
  * @param pcb the tcp_pcb to bind (no check is done whether this pcb is
  *        already bound!)
- * @param ipaddr the local ip address to bind to (use IP_ADDR_ANY to bind
+ * @param ipaddr the local ip address to bind to (use IP4_ADDR_ANY to bind
  *        to any local address
  * @param port the local port to bind to
  * @return ERR_USE if the port is already in use
@@ -546,12 +563,12 @@ tcp_bind(struct tcp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port)
 #if LWIP_IPV4
   /* Don't propagate NULL pointer (IPv4 ANY) to subsequent functions */
   if (ipaddr == NULL) {
-    ipaddr = IP_ADDR_ANY;
+    ipaddr = IP4_ADDR_ANY;
   }
 #endif /* LWIP_IPV4 */
 
   /* still need to check for ipaddr == NULL in IPv6 only case */
-  if ((pcb == NULL) || (ipaddr == NULL) || !IP_ADDR_PCB_VERSION_MATCH_EXACT(pcb, ipaddr)) {
+  if ((pcb == NULL) || (ipaddr == NULL)) {
     return ERR_VAL;
   }
 
@@ -636,19 +653,44 @@ tcp_accept_null(void *arg, struct tcp_pcb *pcb, err_t err)
  *
  * @note The original tcp_pcb is freed. This function therefore has to be
  *       called like this:
- *             tpcb = tcp_listen(tpcb);
+ *             tpcb = tcp_listen_with_backlog(tpcb, backlog);
  */
 struct tcp_pcb *
 tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog)
 {
-  struct tcp_pcb_listen *lpcb;
+  return tcp_listen_with_backlog_and_err(pcb, backlog, NULL);
+}
+
+/**
+ * @ingroup tcp_raw
+ * Set the state of the connection to be LISTEN, which means that it
+ * is able to accept incoming connections. The protocol control block
+ * is reallocated in order to consume less memory. Setting the
+ * connection to LISTEN is an irreversible process.
+ *
+ * @param pcb the original tcp_pcb
+ * @param backlog the incoming connections queue limit
+ * @param err when NULL is returned, this contains the error reason
+ * @return tcp_pcb used for listening, consumes less memory.
+ *
+ * @note The original tcp_pcb is freed. This function therefore has to be
+ *       called like this:
+ *             tpcb = tcp_listen_with_backlog_and_err(tpcb, backlog, &err);
+ */
+struct tcp_pcb *
+tcp_listen_with_backlog_and_err(struct tcp_pcb *pcb, u8_t backlog, err_t *err)
+{
+  struct tcp_pcb_listen *lpcb = NULL;
+  err_t res;
 
   LWIP_UNUSED_ARG(backlog);
-  LWIP_ERROR("tcp_listen: pcb already connected", pcb->state == CLOSED, return NULL);
+  LWIP_ERROR("tcp_listen: pcb already connected", pcb->state == CLOSED, res = ERR_CLSD; goto done);
 
   /* already listening? */
   if (pcb->state == LISTEN) {
-    return pcb;
+    lpcb = (struct tcp_pcb_listen*)pcb;
+    res = ERR_ALREADY;
+    goto done;
   }
 #if SO_REUSE
   if (ip_get_option(pcb, SOF_REUSEADDR)) {
@@ -659,14 +701,17 @@ tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog)
       if ((lpcb->local_port == pcb->local_port) &&
           ip_addr_cmp(&lpcb->local_ip, &pcb->local_ip)) {
         /* this address/port is already used */
-        return NULL;
+        lpcb = NULL;
+        res = ERR_USE;
+        goto done;
       }
     }
   }
 #endif /* SO_REUSE */
   lpcb = (struct tcp_pcb_listen *)memp_malloc(MEMP_TCP_PCB_LISTEN);
   if (lpcb == NULL) {
-    return NULL;
+    res = ERR_MEM;
+    goto done;
   }
   lpcb->callback_arg = pcb->callback_arg;
   lpcb->local_port = pcb->local_port;
@@ -691,6 +736,11 @@ tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog)
   tcp_backlog_set(lpcb, backlog);
 #endif /* TCP_LISTEN_BACKLOG */
   TCP_REG(&tcp_listen_pcbs.pcbs, (struct tcp_pcb *)lpcb);
+  res = ERR_OK;
+done:
+  if (err != NULL) {
+    *err = res;
+  }
   return (struct tcp_pcb *)lpcb;
 }
 
@@ -826,7 +876,7 @@ tcp_connect(struct tcp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port,
   u32_t iss;
   u16_t old_local_port;
 
-  if ((pcb == NULL) || (ipaddr == NULL) || !IP_ADDR_PCB_VERSION_MATCH_EXACT(pcb, ipaddr)) {
+  if ((pcb == NULL) || (ipaddr == NULL)) {
     return ERR_VAL;
   }
 
@@ -880,10 +930,11 @@ tcp_connect(struct tcp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port,
 #endif /* SO_REUSE */
   }
 
-  iss = tcp_next_iss();
+  iss = tcp_next_iss(pcb);
   pcb->rcv_nxt = 0;
   pcb->snd_nxt = iss;
   pcb->lastack = iss - 1;
+  pcb->snd_wl2 = iss - 1;
   pcb->snd_lbb = iss - 1;
   /* Start with a window that does not need scaling. When window scaling is
      enabled and used, the window is enlarged when both sides agree on scaling. */
@@ -897,7 +948,6 @@ tcp_connect(struct tcp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port,
   pcb->mss = tcp_eff_send_mss(pcb->mss, &pcb->local_ip, &pcb->remote_ip);
 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
   pcb->cwnd = 1;
-  pcb->ssthresh = TCP_WND;
 #if LWIP_CALLBACK_API
   pcb->connected = connected;
 #else /* LWIP_CALLBACK_API */
@@ -963,11 +1013,11 @@ tcp_slowtmr_start:
     pcb_remove = 0;
     pcb_reset = 0;
 
-    if (pcb->state == SYN_SENT && pcb->nrtx == TCP_SYNMAXRTX) {
+    if (pcb->state == SYN_SENT && pcb->nrtx >= TCP_SYNMAXRTX) {
       ++pcb_remove;
       LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max SYN retries reached\n"));
     }
-    else if (pcb->nrtx == TCP_MAXRTX) {
+    else if (pcb->nrtx >= TCP_MAXRTX) {
       ++pcb_remove;
       LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max DATA retries reached\n"));
     } else {
@@ -1001,7 +1051,8 @@ tcp_slowtmr_start:
           /* Double retransmission time-out unless we are trying to
            * connect to somebody (i.e., we are in SYN_SENT). */
           if (pcb->state != SYN_SENT) {
-            pcb->rto = ((pcb->sa >> 3) + pcb->sv) << tcp_backoff[pcb->nrtx];
+            u8_t backoff_idx = LWIP_MIN(pcb->nrtx, sizeof(tcp_backoff)-1);
+            pcb->rto = ((pcb->sa >> 3) + pcb->sv) << tcp_backoff[backoff_idx];
           }
 
           /* Reset the retransmission timer. */
@@ -1098,6 +1149,7 @@ tcp_slowtmr_start:
       tcp_err_fn err_fn = pcb->errf;
 #endif /* LWIP_CALLBACK_API */
       void *err_arg;
+      enum tcp_state last_state;
       tcp_pcb_purge(pcb);
       /* Remove PCB from tcp_active_pcbs list. */
       if (prev != NULL) {
@@ -1115,12 +1167,13 @@ tcp_slowtmr_start:
       }
 
       err_arg = pcb->callback_arg;
+      last_state = pcb->state;
       pcb2 = pcb;
       pcb = pcb->next;
       memp_free(MEMP_TCP_PCB, pcb2);
 
       tcp_active_pcbs_changed = 0;
-      TCP_EVENT_ERR(err_fn, err_arg, ERR_ABRT);
+      TCP_EVENT_ERR(last_state, err_fn, err_arg, ERR_ABRT);
       if (tcp_active_pcbs_changed) {
         goto tcp_slowtmr_start;
       }
@@ -1210,6 +1263,12 @@ tcp_fasttmr_start:
         tcp_output(pcb);
         pcb->flags &= ~(TF_ACK_DELAY | TF_ACK_NOW);
       }
+      /* send pending FIN */
+      if (pcb->flags & TF_CLOSEPEND) {
+        LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: pending FIN\n"));
+        pcb->flags &= ~(TF_CLOSEPEND);
+        tcp_close_shutdown_fin(pcb);
+      }
 
       next = pcb->next;
 
@@ -1491,7 +1550,6 @@ struct tcp_pcb *
 tcp_alloc(u8_t prio)
 {
   struct tcp_pcb *pcb;
-  u32_t iss;
 
   pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
   if (pcb == NULL) {
@@ -1554,14 +1612,17 @@ tcp_alloc(u8_t prio)
     pcb->sv = 3000 / TCP_SLOW_INTERVAL;
     pcb->rtime = -1;
     pcb->cwnd = 1;
-    iss = tcp_next_iss();
-    pcb->snd_wl2 = iss;
-    pcb->snd_nxt = iss;
-    pcb->lastack = iss;
-    pcb->snd_lbb = iss;
     pcb->tmr = tcp_ticks;
     pcb->last_timer = tcp_timer_ctr;
 
+    /* RFC 5681 recommends setting ssthresh abritrarily high and gives an example
+    of using the largest advertised receive window.  We've seen complications with
+    receiving TCPs that use window scaling and/or window auto-tuning where the
+    initial advertised window is very small and then grows rapidly once the
+    connection is established. To avoid these complications, we set ssthresh to the
+    largest effective cwnd (amount of in-flight data) that the sender can have. */
+    pcb->ssthresh = TCP_SND_BUF;
+
 #if LWIP_CALLBACK_API
     pcb->recv = tcp_recv_null;
 #endif /* LWIP_CALLBACK_API */
@@ -1602,7 +1663,7 @@ tcp_new(void)
  * place it on any of the TCP PCB lists.
  * The pcb is not put on any list until binding using tcp_bind().
  *
- * @param type IP address type, see IPADDR_TYPE_XX definitions.
+ * @param type IP address type, see @ref lwip_ip_addr_type definitions.
  * If you want to listen to IPv4 and IPv6 (dual-stack) connections,
  * supply @ref IPADDR_TYPE_ANY as argument and bind to @ref IP_ANY_TYPE.
  * @return a new tcp_pcb that initially is in state CLOSED
@@ -1826,12 +1887,18 @@ tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb)
  * @return u32_t pseudo random sequence number
  */
 u32_t
-tcp_next_iss(void)
+tcp_next_iss(struct tcp_pcb *pcb)
 {
+#ifdef LWIP_HOOK_TCP_ISN
+  return LWIP_HOOK_TCP_ISN(&pcb->local_ip, pcb->local_port, &pcb->remote_ip, pcb->remote_port);
+#else /* LWIP_HOOK_TCP_ISN */
   static u32_t iss = 6510;
 
+  LWIP_UNUSED_ARG(pcb);
+
   iss += tcp_ticks;       /* XXX */
   return iss;
+#endif /* LWIP_HOOK_TCP_ISN */
 }
 
 #if TCP_CALCULATE_EFF_SEND_MSS
@@ -1972,13 +2039,13 @@ tcp_debug_print(struct tcp_hdr *tcphdr)
   LWIP_DEBUGF(TCP_DEBUG, ("TCP header:\n"));
   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
   LWIP_DEBUGF(TCP_DEBUG, ("|    %5"U16_F"      |    %5"U16_F"      | (src port, dest port)\n",
-         ntohs(tcphdr->src), ntohs(tcphdr->dest)));
+         lwip_ntohs(tcphdr->src), lwip_ntohs(tcphdr->dest)));
   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
   LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (seq no)\n",
-          ntohl(tcphdr->seqno)));
+          lwip_ntohl(tcphdr->seqno)));
   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
   LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (ack no)\n",
-         ntohl(tcphdr->ackno)));
+         lwip_ntohl(tcphdr->ackno)));
   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
   LWIP_DEBUGF(TCP_DEBUG, ("| %2"U16_F" |   |%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"|     %5"U16_F"     | (hdrlen, flags (",
        TCPH_HDRLEN(tcphdr),
@@ -1988,12 +2055,12 @@ tcp_debug_print(struct tcp_hdr *tcphdr)
          (u16_t)(TCPH_FLAGS(tcphdr) >> 2 & 1),
          (u16_t)(TCPH_FLAGS(tcphdr) >> 1 & 1),
          (u16_t)(TCPH_FLAGS(tcphdr)      & 1),
-         ntohs(tcphdr->wnd)));
+         lwip_ntohs(tcphdr->wnd)));
   tcp_debug_print_flags(TCPH_FLAGS(tcphdr));
   LWIP_DEBUGF(TCP_DEBUG, ("), win)\n"));
   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
   LWIP_DEBUGF(TCP_DEBUG, ("|    0x%04"X16_F"     |     %5"U16_F"     | (chksum, urgp)\n",
-         ntohs(tcphdr->chksum), ntohs(tcphdr->urgp)));
+         lwip_ntohs(tcphdr->chksum), lwip_ntohs(tcphdr->urgp)));
   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
 }
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/tcp_in.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/tcp_in.c b/net/ip/lwip_base/src/core/tcp_in.c
index dd88e1e..ba87928 100644
--- a/net/ip/lwip_base/src/core/tcp_in.c
+++ b/net/ip/lwip_base/src/core/tcp_in.c
@@ -61,8 +61,6 @@
 
 /** Initial CWND calculation as defined RFC 2581 */
 #define LWIP_TCP_CALC_INITIAL_CWND(mss) LWIP_MIN((4U * (mss)), LWIP_MAX((2U * (mss)), 4380U));
-/** Initial slow start threshold value: we use the full window */
-#define LWIP_TCP_INITIAL_SSTHRESH(pcb)  ((pcb)->snd_wnd)
 
 /* These variables are global to all functions involved in the input
    processing of TCP segments. They are set by the tcp_input()
@@ -209,11 +207,11 @@ tcp_input(struct pbuf *p, struct netif *inp)
   }
 
   /* Convert fields in TCP header to host byte order. */
-  tcphdr->src = ntohs(tcphdr->src);
-  tcphdr->dest = ntohs(tcphdr->dest);
-  seqno = tcphdr->seqno = ntohl(tcphdr->seqno);
-  ackno = tcphdr->ackno = ntohl(tcphdr->ackno);
-  tcphdr->wnd = ntohs(tcphdr->wnd);
+  tcphdr->src = lwip_ntohs(tcphdr->src);
+  tcphdr->dest = lwip_ntohs(tcphdr->dest);
+  seqno = tcphdr->seqno = lwip_ntohl(tcphdr->seqno);
+  ackno = tcphdr->ackno = lwip_ntohl(tcphdr->ackno);
+  tcphdr->wnd = lwip_ntohs(tcphdr->wnd);
 
   flags = TCPH_FLAGS(tcphdr);
   tcplen = p->tot_len + ((flags & (TCP_FIN | TCP_SYN)) ? 1 : 0);
@@ -358,6 +356,11 @@ tcp_input(struct pbuf *p, struct netif *inp)
         ((pcb->refused_data != NULL) && (tcplen > 0))) {
         /* pcb has been aborted or refused data is still refused and the new
            segment contains data */
+        if (pcb->rcv_ann_wnd == 0) {
+          /* this is a zero-window probe, we respond to it with current RCV.NXT
+          and drop the data segment */
+          tcp_send_empty_ack(pcb);
+        }
         TCP_STATS_INC(tcp.drop);
         MIB2_STATS_INC(mib2.tcpinerrs);
         goto aborted;
@@ -373,7 +376,7 @@ tcp_input(struct pbuf *p, struct netif *inp)
            end. We then call the error callback to inform the
            application that the connection is dead before we
            deallocate the PCB. */
-        TCP_EVENT_ERR(pcb->errf, pcb->callback_arg, ERR_RST);
+        TCP_EVENT_ERR(pcb->state, pcb->errf, pcb->callback_arg, ERR_RST);
         tcp_pcb_remove(&tcp_active_pcbs, pcb);
         memp_free(MEMP_TCP_PCB, pcb);
       } else {
@@ -408,7 +411,7 @@ tcp_input(struct pbuf *p, struct netif *inp)
             /* Connection closed although the application has only shut down the
                tx side: call the PCB's err callback and indicate the closure to
                ensure the application doesn't continue using the PCB. */
-            TCP_EVENT_ERR(pcb->errf, pcb->callback_arg, ERR_CLSD);
+            TCP_EVENT_ERR(pcb->state, pcb->errf, pcb->callback_arg, ERR_CLSD);
           }
           tcp_pcb_remove(&tcp_active_pcbs, pcb);
           memp_free(MEMP_TCP_PCB, pcb);
@@ -534,10 +537,7 @@ dropped:
  * connection (from tcp_input()).
  *
  * @param pcb the tcp_pcb_listen for which a segment arrived
- * @return ERR_OK if the segment was processed
- *         another err_t on error
  *
- * @note the return value is not (yet?) used in tcp_input()
  * @note the segment which arrived is saved in global variables, therefore only the pcb
  *       involved is passed as a parameter to this function
  */
@@ -545,6 +545,7 @@ static void
 tcp_listen_input(struct tcp_pcb_listen *pcb)
 {
   struct tcp_pcb *npcb;
+  u32_t iss;
   err_t rc;
 
   if (flags & TCP_RST) {
@@ -592,6 +593,11 @@ tcp_listen_input(struct tcp_pcb_listen *pcb)
     npcb->state = SYN_RCVD;
     npcb->rcv_nxt = seqno + 1;
     npcb->rcv_ann_right_edge = npcb->rcv_nxt;
+    iss = tcp_next_iss(npcb);
+    npcb->snd_wl2 = iss;
+    npcb->snd_nxt = iss;
+    npcb->lastack = iss;
+    npcb->snd_lbb = iss;
     npcb->snd_wl1 = seqno - 1;/* initialise to seqno-1 to force window update */
     npcb->callback_arg = pcb->callback_arg;
 #if LWIP_CALLBACK_API || TCP_LISTEN_BACKLOG
@@ -605,9 +611,8 @@ tcp_listen_input(struct tcp_pcb_listen *pcb)
 
     /* Parse any options in the SYN. */
     tcp_parseopt(npcb);
-    npcb->snd_wnd = SND_WND_SCALE(npcb, tcphdr->wnd);
+    npcb->snd_wnd = tcphdr->wnd;
     npcb->snd_wnd_max = npcb->snd_wnd;
-    npcb->ssthresh = LWIP_TCP_INITIAL_SSTHRESH(npcb);
 
 #if TCP_CALCULATE_EFF_SEND_MSS
     npcb->mss = tcp_eff_send_mss(npcb->mss, &npcb->local_ip, &npcb->remote_ip);
@@ -747,14 +752,14 @@ tcp_process(struct tcp_pcb *pcb)
   switch (pcb->state) {
   case SYN_SENT:
     LWIP_DEBUGF(TCP_INPUT_DEBUG, ("SYN-SENT: ackno %"U32_F" pcb->snd_nxt %"U32_F" unacked %"U32_F"\n", ackno,
-     pcb->snd_nxt, ntohl(pcb->unacked->tcphdr->seqno)));
+     pcb->snd_nxt, lwip_ntohl(pcb->unacked->tcphdr->seqno)));
     /* received SYN ACK with expected sequence number? */
     if ((flags & TCP_ACK) && (flags & TCP_SYN)
         && (ackno == pcb->lastack + 1)) {
       pcb->rcv_nxt = seqno + 1;
       pcb->rcv_ann_right_edge = pcb->rcv_nxt;
       pcb->lastack = ackno;
-      pcb->snd_wnd = SND_WND_SCALE(pcb, tcphdr->wnd);
+      pcb->snd_wnd = tcphdr->wnd;
       pcb->snd_wnd_max = pcb->snd_wnd;
       pcb->snd_wl1 = seqno - 1; /* initialise to seqno - 1 to force window update */
       pcb->state = ESTABLISHED;
@@ -763,9 +768,6 @@ tcp_process(struct tcp_pcb *pcb)
       pcb->mss = tcp_eff_send_mss(pcb->mss, &pcb->local_ip, &pcb->remote_ip);
 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
 
-      /* Set ssthresh again after changing 'mss' and 'snd_wnd' */
-      pcb->ssthresh = LWIP_TCP_INITIAL_SSTHRESH(pcb);
-
       pcb->cwnd = LWIP_TCP_CALC_INITIAL_CWND(pcb->mss);
       LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_process (SENT): cwnd %"TCPWNDSIZE_F
                                    " ssthresh %"TCPWNDSIZE_F"\n",
@@ -808,9 +810,12 @@ tcp_process(struct tcp_pcb *pcb)
       tcp_rst(ackno, seqno + tcplen, ip_current_dest_addr(),
         ip_current_src_addr(), tcphdr->dest, tcphdr->src);
       /* Resend SYN immediately (don't wait for rto timeout) to establish
-        connection faster */
-      pcb->rtime = 0;
-      tcp_rexmit_rto(pcb);
+        connection faster, but do not send more SYNs than we otherwise would
+        have, or we might get caught in a loop on loopback interfaces. */
+      if (pcb->nrtx < TCP_SYNMAXRTX) {
+        pcb->rtime = 0;
+        tcp_rexmit_rto(pcb);
+      }
     }
     break;
   case SYN_RCVD:
@@ -819,14 +824,16 @@ tcp_process(struct tcp_pcb *pcb)
       if (TCP_SEQ_BETWEEN(ackno, pcb->lastack+1, pcb->snd_nxt)) {
         pcb->state = ESTABLISHED;
         LWIP_DEBUGF(TCP_DEBUG, ("TCP connection established %"U16_F" -> %"U16_F".\n", inseg.tcphdr->src, inseg.tcphdr->dest));
+#if LWIP_CALLBACK_API || TCP_LISTEN_BACKLOG
 #if LWIP_CALLBACK_API
         LWIP_ASSERT("pcb->listener->accept != NULL",
           (pcb->listener == NULL) || (pcb->listener->accept != NULL));
+#endif
         if (pcb->listener == NULL) {
           /* listen pcb might be closed by now */
           err = ERR_VAL;
         } else
-#endif
+#endif /* LWIP_CALLBACK_API || TCP_LISTEN_BACKLOG */
         {
           tcp_backlog_accepted(pcb);
           /* Call the accept function. */
@@ -845,11 +852,6 @@ tcp_process(struct tcp_pcb *pcb)
          * we'd better pass it on to the application as well. */
         tcp_receive(pcb);
 
-        /* passive open: update initial ssthresh now that the correct window is
-           known: if the remote side supports window scaling, the window sent
-           with the initial SYN can be smaller than the one used later */
-        pcb->ssthresh = LWIP_TCP_INITIAL_SSTHRESH(pcb);
-
         /* Prevent ACK for SYN to generate a sent event */
         if (recv_acked != 0) {
           recv_acked--;
@@ -886,7 +888,8 @@ tcp_process(struct tcp_pcb *pcb)
   case FIN_WAIT_1:
     tcp_receive(pcb);
     if (recv_flags & TF_GOT_FIN) {
-      if ((flags & TCP_ACK) && (ackno == pcb->snd_nxt)) {
+      if ((flags & TCP_ACK) && (ackno == pcb->snd_nxt) &&
+          pcb->unsent == NULL) {
         LWIP_DEBUGF(TCP_DEBUG,
           ("TCP connection closed: FIN_WAIT_1 %"U16_F" -> %"U16_F".\n", inseg.tcphdr->src, inseg.tcphdr->dest));
         tcp_ack_now(pcb);
@@ -898,7 +901,8 @@ tcp_process(struct tcp_pcb *pcb)
         tcp_ack_now(pcb);
         pcb->state = CLOSING;
       }
-    } else if ((flags & TCP_ACK) && (ackno == pcb->snd_nxt)) {
+    } else if ((flags & TCP_ACK) && (ackno == pcb->snd_nxt) &&
+               pcb->unsent == NULL) {
       pcb->state = FIN_WAIT_2;
     }
     break;
@@ -915,7 +919,7 @@ tcp_process(struct tcp_pcb *pcb)
     break;
   case CLOSING:
     tcp_receive(pcb);
-    if (flags & TCP_ACK && ackno == pcb->snd_nxt) {
+    if ((flags & TCP_ACK) && ackno == pcb->snd_nxt && pcb->unsent == NULL) {
       LWIP_DEBUGF(TCP_DEBUG, ("TCP connection closed: CLOSING %"U16_F" -> %"U16_F".\n", inseg.tcphdr->src, inseg.tcphdr->dest));
       tcp_pcb_purge(pcb);
       TCP_RMV_ACTIVE(pcb);
@@ -925,7 +929,7 @@ tcp_process(struct tcp_pcb *pcb)
     break;
   case LAST_ACK:
     tcp_receive(pcb);
-    if (flags & TCP_ACK && ackno == pcb->snd_nxt) {
+    if ((flags & TCP_ACK) && ackno == pcb->snd_nxt && pcb->unsent == NULL) {
       LWIP_DEBUGF(TCP_DEBUG, ("TCP connection closed: LAST_ACK %"U16_F" -> %"U16_F".\n", inseg.tcphdr->src, inseg.tcphdr->dest));
       /* bugfix #21699: don't set pcb->state to CLOSED here or we risk leaking segments */
       recv_flags |= TF_CLOSED;
@@ -1138,18 +1142,18 @@ tcp_receive(struct tcp_pcb *pcb)
       LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_receive: ACK for %"U32_F", unacked->seqno %"U32_F":%"U32_F"\n",
                                     ackno,
                                     pcb->unacked != NULL?
-                                    ntohl(pcb->unacked->tcphdr->seqno): 0,
+                                    lwip_ntohl(pcb->unacked->tcphdr->seqno): 0,
                                     pcb->unacked != NULL?
-                                    ntohl(pcb->unacked->tcphdr->seqno) + TCP_TCPLEN(pcb->unacked): 0));
+                                    lwip_ntohl(pcb->unacked->tcphdr->seqno) + TCP_TCPLEN(pcb->unacked): 0));
 
       /* Remove segment from the unacknowledged list if the incoming
          ACK acknowledges them. */
       while (pcb->unacked != NULL &&
-             TCP_SEQ_LEQ(ntohl(pcb->unacked->tcphdr->seqno) +
+             TCP_SEQ_LEQ(lwip_ntohl(pcb->unacked->tcphdr->seqno) +
                          TCP_TCPLEN(pcb->unacked), ackno)) {
         LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_receive: removing %"U32_F":%"U32_F" from pcb->unacked\n",
-                                      ntohl(pcb->unacked->tcphdr->seqno),
-                                      ntohl(pcb->unacked->tcphdr->seqno) +
+                                      lwip_ntohl(pcb->unacked->tcphdr->seqno),
+                                      lwip_ntohl(pcb->unacked->tcphdr->seqno) +
                                       TCP_TCPLEN(pcb->unacked)));
 
         next = pcb->unacked;
@@ -1197,10 +1201,10 @@ tcp_receive(struct tcp_pcb *pcb)
        ->unsent list after a retransmission, so these segments may
        in fact have been sent once. */
     while (pcb->unsent != NULL &&
-           TCP_SEQ_BETWEEN(ackno, ntohl(pcb->unsent->tcphdr->seqno) +
+           TCP_SEQ_BETWEEN(ackno, lwip_ntohl(pcb->unsent->tcphdr->seqno) +
                            TCP_TCPLEN(pcb->unsent), pcb->snd_nxt)) {
       LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_receive: removing %"U32_F":%"U32_F" from pcb->unsent\n",
-                                    ntohl(pcb->unsent->tcphdr->seqno), ntohl(pcb->unsent->tcphdr->seqno) +
+                                    lwip_ntohl(pcb->unsent->tcphdr->seqno), lwip_ntohl(pcb->unsent->tcphdr->seqno) +
                                     TCP_TCPLEN(pcb->unsent)));
 
       next = pcb->unsent;
@@ -1407,7 +1411,7 @@ tcp_receive(struct tcp_pcb *pcb)
                    TCP_SEQ_GEQ(seqno + tcplen,
                                next->tcphdr->seqno + next->len)) {
               /* inseg cannot have FIN here (already processed above) */
-              if (TCPH_FLAGS(next->tcphdr) & TCP_FIN &&
+              if ((TCPH_FLAGS(next->tcphdr) & TCP_FIN) != 0 &&
                   (TCPH_FLAGS(inseg.tcphdr) & TCP_SYN) == 0) {
                 TCPH_SET_FLAG(inseg.tcphdr, TCP_FIN);
                 tcplen = TCP_TCPLEN(&inseg);
@@ -1777,12 +1781,12 @@ tcp_parseopt(struct tcp_pcb *pcb)
         tsval |= (tcp_getoptbyte() << 16);
         tsval |= (tcp_getoptbyte() << 24);
         if (flags & TCP_SYN) {
-          pcb->ts_recent = ntohl(tsval);
+          pcb->ts_recent = lwip_ntohl(tsval);
           /* Enable sending timestamps in every segment now that we know
              the remote host supports it. */
           pcb->flags |= TF_TIMESTAMP;
         } else if (TCP_SEQ_BETWEEN(pcb->ts_lastacksent, seqno, seqno+tcplen)) {
-          pcb->ts_recent = ntohl(tsval);
+          pcb->ts_recent = lwip_ntohl(tsval);
         }
         /* Advance to next option (6 bytes already read) */
         tcp_optidx += LWIP_TCP_OPT_LEN_TS - 6;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/tcp_out.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/tcp_out.c b/net/ip/lwip_base/src/core/tcp_out.c
index 70bdfea..2435408 100644
--- a/net/ip/lwip_base/src/core/tcp_out.c
+++ b/net/ip/lwip_base/src/core/tcp_out.c
@@ -114,12 +114,12 @@ tcp_output_alloc_header(struct tcp_pcb *pcb, u16_t optlen, u16_t datalen,
     LWIP_ASSERT("check that first pbuf can hold struct tcp_hdr",
                  (p->len >= TCP_HLEN + optlen));
     tcphdr = (struct tcp_hdr *)p->payload;
-    tcphdr->src = htons(pcb->local_port);
-    tcphdr->dest = htons(pcb->remote_port);
+    tcphdr->src = lwip_htons(pcb->local_port);
+    tcphdr->dest = lwip_htons(pcb->remote_port);
     tcphdr->seqno = seqno_be;
-    tcphdr->ackno = htonl(pcb->rcv_nxt);
+    tcphdr->ackno = lwip_htonl(pcb->rcv_nxt);
     TCPH_HDRLEN_FLAGS_SET(tcphdr, (5 + optlen / 4), TCP_ACK);
-    tcphdr->wnd = htons(TCPWND_MIN16(RCV_WND_SCALE(pcb, pcb->rcv_ann_wnd)));
+    tcphdr->wnd = lwip_htons(TCPWND_MIN16(RCV_WND_SCALE(pcb, pcb->rcv_ann_wnd)));
     tcphdr->chksum = 0;
     tcphdr->urgp = 0;
 
@@ -204,9 +204,9 @@ tcp_create_segment(struct tcp_pcb *pcb, struct pbuf *p, u8_t flags, u32_t seqno,
     return NULL;
   }
   seg->tcphdr = (struct tcp_hdr *)seg->p->payload;
-  seg->tcphdr->src = htons(pcb->local_port);
-  seg->tcphdr->dest = htons(pcb->remote_port);
-  seg->tcphdr->seqno = htonl(seqno);
+  seg->tcphdr->src = lwip_htons(pcb->local_port);
+  seg->tcphdr->dest = lwip_htons(pcb->remote_port);
+  seg->tcphdr->seqno = lwip_htonl(seqno);
   /* ackno is set in tcp_output */
   TCPH_HDRLEN_FLAGS_SET(seg->tcphdr, (5 + optlen / 4), flags);
   /* wnd and chksum are set in tcp_output */
@@ -224,7 +224,7 @@ tcp_create_segment(struct tcp_pcb *pcb, struct pbuf *p, u8_t flags, u32_t seqno,
  * @param length size of the pbuf's payload.
  * @param max_length maximum usable size of payload+oversize.
  * @param oversize pointer to a u16_t that will receive the number of usable tail bytes.
- * @param pcb The TCP connection that willo enqueue the pbuf.
+ * @param pcb The TCP connection that will enqueue the pbuf.
  * @param apiflags API flags given to tcp_write.
  * @param first_seg true when this pbuf will be used in the first enqueued segment.
  */
@@ -242,7 +242,6 @@ tcp_pbuf_prealloc(pbuf_layer layer, u16_t length, u16_t max_length,
   LWIP_UNUSED_ARG(pcb);
   LWIP_UNUSED_ARG(apiflags);
   LWIP_UNUSED_ARG(first_seg);
-  /* always create MSS-sized pbufs */
   alloc = max_length;
 #else /* LWIP_NETIF_TX_SINGLE_PBUF */
   if (length < max_length) {
@@ -377,7 +376,11 @@ tcp_write(struct tcp_pcb *pcb, const void *arg, u16_t len, u8_t apiflags)
 #if TCP_OVERSIZE
   u16_t oversize = 0;
   u16_t oversize_used = 0;
+#if TCP_OVERSIZE_DBGCHECK
+  u16_t oversize_add = 0;
+#endif /* TCP_OVERSIZE_DBGCHECK*/
 #endif /* TCP_OVERSIZE */
+  u16_t extendlen = 0;
 #if TCP_CHECKSUM_ON_COPY
   u16_t concat_chksum = 0;
   u8_t concat_chksum_swapped = 0;
@@ -461,13 +464,13 @@ tcp_write(struct tcp_pcb *pcb, const void *arg, u16_t len, u8_t apiflags)
      */
 #if TCP_OVERSIZE
 #if TCP_OVERSIZE_DBGCHECK
-    /* check that pcb->unsent_oversize matches last_unsent->unsent_oversize */
+    /* check that pcb->unsent_oversize matches last_unsent->oversize_left */
     LWIP_ASSERT("unsent_oversize mismatch (pcb vs. last_unsent)",
                 pcb->unsent_oversize == last_unsent->oversize_left);
 #endif /* TCP_OVERSIZE_DBGCHECK */
     oversize = pcb->unsent_oversize;
     if (oversize > 0) {
-      LWIP_ASSERT("inconsistent oversize vs. space", oversize_used <= space);
+      LWIP_ASSERT("inconsistent oversize vs. space", oversize <= space);
       seg = last_unsent;
       oversize_used = LWIP_MIN(space, LWIP_MIN(oversize, len));
       pos += oversize_used;
@@ -475,18 +478,22 @@ tcp_write(struct tcp_pcb *pcb, const void *arg, u16_t len, u8_t apiflags)
       space -= oversize_used;
     }
     /* now we are either finished or oversize is zero */
-    LWIP_ASSERT("inconsistend oversize vs. len", (oversize == 0) || (pos == len));
+    LWIP_ASSERT("inconsistent oversize vs. len", (oversize == 0) || (pos == len));
 #endif /* TCP_OVERSIZE */
 
     /*
      * Phase 2: Chain a new pbuf to the end of pcb->unsent.
      *
+     * As an exception when NOT copying the data, if the given data buffer
+     * directly follows the last unsent data buffer in memory, extend the last
+     * ROM pbuf reference to the buffer, thus saving a ROM pbuf allocation.
+     *
      * We don't extend segments containing SYN/FIN flags or options
      * (len==0). The new pbuf is kept in concat_p and pbuf_cat'ed at
      * the end.
      */
     if ((pos < len) && (space > 0) && (last_unsent->len > 0)) {
-      u16_t seglen = space < len - pos ? space : len - pos;
+      u16_t seglen = LWIP_MIN(space, len - pos);
       seg = last_unsent;
 
       /* Create a pbuf with a copy or reference to seglen bytes. We
@@ -501,18 +508,30 @@ tcp_write(struct tcp_pcb *pcb, const void *arg, u16_t len, u8_t apiflags)
           goto memerr;
         }
 #if TCP_OVERSIZE_DBGCHECK
-        last_unsent->oversize_left += oversize;
+        oversize_add = oversize;
 #endif /* TCP_OVERSIZE_DBGCHECK */
         TCP_DATA_COPY2(concat_p->payload, (const u8_t*)arg + pos, seglen, &concat_chksum, &concat_chksum_swapped);
 #if TCP_CHECKSUM_ON_COPY
         concat_chksummed += seglen;
 #endif /* TCP_CHECKSUM_ON_COPY */
+        queuelen += pbuf_clen(concat_p);
       } else {
         /* Data is not copied */
-        if ((concat_p = pbuf_alloc(PBUF_RAW, seglen, PBUF_ROM)) == NULL) {
-          LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
-                      ("tcp_write: could not allocate memory for zero-copy pbuf\n"));
-          goto memerr;
+        /* If the last unsent pbuf is of type PBUF_ROM, try to extend it. */
+        struct pbuf *p;
+        for (p = last_unsent->p; p->next != NULL; p = p->next);
+        if (p->type == PBUF_ROM && (const u8_t *)p->payload + p->len == (const u8_t *)arg) {
+          LWIP_ASSERT("tcp_write: ROM pbufs cannot be oversized", pos == 0);
+          extendlen = seglen;
+        } else {
+          if ((concat_p = pbuf_alloc(PBUF_RAW, seglen, PBUF_ROM)) == NULL) {
+            LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
+                        ("tcp_write: could not allocate memory for zero-copy pbuf\n"));
+            goto memerr;
+          }
+          /* reference the non-volatile payload data */
+          ((struct pbuf_rom*)concat_p)->payload = (const u8_t*)arg + pos;
+          queuelen += pbuf_clen(concat_p);
         }
 #if TCP_CHECKSUM_ON_COPY
         /* calculate the checksum of nocopy-data */
@@ -520,12 +539,9 @@ tcp_write(struct tcp_pcb *pcb, const void *arg, u16_t len, u8_t apiflags)
           &concat_chksum, &concat_chksum_swapped);
         concat_chksummed += seglen;
 #endif /* TCP_CHECKSUM_ON_COPY */
-        /* reference the non-volatile payload data */
-        ((struct pbuf_rom*)concat_p)->payload = (const u8_t*)arg + pos;
       }
 
       pos += seglen;
-      queuelen += pbuf_clen(concat_p);
     }
   } else {
 #if TCP_OVERSIZE
@@ -544,7 +560,7 @@ tcp_write(struct tcp_pcb *pcb, const void *arg, u16_t len, u8_t apiflags)
     struct pbuf *p;
     u16_t left = len - pos;
     u16_t max_len = mss_local - optlen;
-    u16_t seglen = left > max_len ? max_len : left;
+    u16_t seglen = LWIP_MIN(left, max_len);
 #if TCP_CHECKSUM_ON_COPY
     u16_t chksum = 0;
     u8_t chksum_swapped = 0;
@@ -633,8 +649,8 @@ tcp_write(struct tcp_pcb *pcb, const void *arg, u16_t len, u8_t apiflags)
     prev_seg = seg;
 
     LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_TRACE, ("tcp_write: queueing %"U32_F":%"U32_F"\n",
-      ntohl(seg->tcphdr->seqno),
-      ntohl(seg->tcphdr->seqno) + TCP_TCPLEN(seg)));
+      lwip_ntohl(seg->tcphdr->seqno),
+      lwip_ntohl(seg->tcphdr->seqno) + TCP_TCPLEN(seg)));
 
     pos += seglen;
   }
@@ -643,6 +659,11 @@ tcp_write(struct tcp_pcb *pcb, const void *arg, u16_t len, u8_t apiflags)
    * All three segmentation phases were successful. We can commit the
    * transaction.
    */
+#if TCP_OVERSIZE_DBGCHECK
+  if ((last_unsent != NULL) && (oversize_add != 0)) {
+    last_unsent->oversize_left += oversize_add;
+  }
+#endif /* TCP_OVERSIZE_DBGCHECK */
 
   /*
    * Phase 1: If data has been added to the preallocated tail of
@@ -670,25 +691,39 @@ tcp_write(struct tcp_pcb *pcb, const void *arg, u16_t len, u8_t apiflags)
 #endif /* TCP_OVERSIZE */
 
   /*
-   * Phase 2: concat_p can be concatenated onto last_unsent->p
+   * Phase 2: concat_p can be concatenated onto last_unsent->p, unless we
+   * determined that the last ROM pbuf can be extended to include the new data.
    */
   if (concat_p != NULL) {
     LWIP_ASSERT("tcp_write: cannot concatenate when pcb->unsent is empty",
       (last_unsent != NULL));
     pbuf_cat(last_unsent->p, concat_p);
     last_unsent->len += concat_p->tot_len;
+  } else if (extendlen > 0) {
+    struct pbuf *p;
+    LWIP_ASSERT("tcp_write: extension of reference requires reference",
+      last_unsent != NULL && last_unsent->p != NULL);
+    for (p = last_unsent->p; p->next != NULL; p = p->next) {
+      p->tot_len += extendlen;
+    }
+    p->tot_len += extendlen;
+    p->len += extendlen;
+    last_unsent->len += extendlen;
+  }
+
 #if TCP_CHECKSUM_ON_COPY
-    if (concat_chksummed) {
-      /*if concat checksumm swapped - swap it back */
-      if (concat_chksum_swapped) {
-        concat_chksum = SWAP_BYTES_IN_WORD(concat_chksum);
-      }
-      tcp_seg_add_chksum(concat_chksum, concat_chksummed, &last_unsent->chksum,
-        &last_unsent->chksum_swapped);
-      last_unsent->flags |= TF_SEG_DATA_CHECKSUMMED;
+  if (concat_chksummed) {
+    LWIP_ASSERT("tcp_write: concat checksum needs concatenated data",
+        concat_p != NULL || extendlen > 0);
+    /*if concat checksumm swapped - swap it back */
+    if (concat_chksum_swapped) {
+      concat_chksum = SWAP_BYTES_IN_WORD(concat_chksum);
     }
-#endif /* TCP_CHECKSUM_ON_COPY */
+    tcp_seg_add_chksum(concat_chksum, concat_chksummed, &last_unsent->chksum,
+      &last_unsent->chksum_swapped);
+    last_unsent->flags |= TF_SEG_DATA_CHECKSUMMED;
   }
+#endif /* TCP_CHECKSUM_ON_COPY */
 
   /*
    * Phase 3: Append queue to pcb->unsent. Queue may be NULL, but that
@@ -808,8 +843,8 @@ tcp_enqueue_flags(struct tcp_pcb *pcb, u8_t flags)
 
   LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_TRACE,
               ("tcp_enqueue_flags: queueing %"U32_F":%"U32_F" (0x%"X16_F")\n",
-               ntohl(seg->tcphdr->seqno),
-               ntohl(seg->tcphdr->seqno) + TCP_TCPLEN(seg),
+               lwip_ntohl(seg->tcphdr->seqno),
+               lwip_ntohl(seg->tcphdr->seqno) + TCP_TCPLEN(seg),
                (u16_t)flags));
 
   /* Now append seg to pcb->unsent queue */
@@ -856,8 +891,8 @@ tcp_build_timestamp_option(struct tcp_pcb *pcb, u32_t *opts)
 {
   /* Pad with two NOP options to make everything nicely aligned */
   opts[0] = PP_HTONL(0x0101080A);
-  opts[1] = htonl(sys_now());
-  opts[2] = htonl(pcb->ts_recent);
+  opts[1] = lwip_htonl(sys_now());
+  opts[2] = lwip_htonl(pcb->ts_recent);
 }
 #endif
 
@@ -896,7 +931,7 @@ tcp_send_empty_ack(struct tcp_pcb *pcb)
   }
 #endif
 
-  p = tcp_output_alloc_header(pcb, optlen, 0, htonl(pcb->snd_nxt));
+  p = tcp_output_alloc_header(pcb, optlen, 0, lwip_htonl(pcb->snd_nxt));
   if (p == NULL) {
     /* let tcp_fasttmr retry sending this ACK */
     pcb->flags |= (TF_ACK_DELAY | TF_ACK_NOW);
@@ -989,7 +1024,7 @@ tcp_output(struct tcp_pcb *pcb)
    */
   if (pcb->flags & TF_ACK_NOW &&
      (seg == NULL ||
-      ntohl(seg->tcphdr->seqno) - pcb->lastack + seg->len > wnd)) {
+      lwip_ntohl(seg->tcphdr->seqno) - pcb->lastack + seg->len > wnd)) {
      return tcp_send_empty_ack(pcb);
   }
 
@@ -1030,13 +1065,31 @@ tcp_output(struct tcp_pcb *pcb)
                 ("tcp_output: snd_wnd %"TCPWNDSIZE_F", cwnd %"TCPWNDSIZE_F", wnd %"U32_F
                  ", effwnd %"U32_F", seq %"U32_F", ack %"U32_F"\n",
                  pcb->snd_wnd, pcb->cwnd, wnd,
-                 ntohl(seg->tcphdr->seqno) - pcb->lastack + seg->len,
-                 ntohl(seg->tcphdr->seqno), pcb->lastack));
+                 lwip_ntohl(seg->tcphdr->seqno) - pcb->lastack + seg->len,
+                 lwip_ntohl(seg->tcphdr->seqno), pcb->lastack));
   }
 #endif /* TCP_CWND_DEBUG */
+  /* Check if we need to start the persistent timer when the next unsent segment
+   * does not fit within the remaining send window and RTO timer is not running (we
+   * have no in-flight data). A traditional approach would fill the remaining window
+   * with part of the unsent segment (which will engage zero-window probing upon
+   * reception of the zero window update from the receiver). This ensures the
+   * subsequent window update is reliably received. With the goal of being lightweight,
+   * we avoid splitting the unsent segment and treat the window as already zero.
+   */
+  if (seg != NULL &&
+      lwip_ntohl(seg->tcphdr->seqno) - pcb->lastack + seg->len > wnd &&
+      wnd > 0 && wnd == pcb->snd_wnd && pcb->unacked == NULL) {
+    /* Start the persist timer */
+    if (pcb->persist_backoff == 0) {
+      pcb->persist_cnt = 0;
+      pcb->persist_backoff = 1;
+    }
+    goto output_done;
+  }
   /* data available and window allows it to be sent? */
   while (seg != NULL &&
-         ntohl(seg->tcphdr->seqno) - pcb->lastack + seg->len <= wnd) {
+         lwip_ntohl(seg->tcphdr->seqno) - pcb->lastack + seg->len <= wnd) {
     LWIP_ASSERT("RST not expected here!",
                 (TCPH_FLAGS(seg->tcphdr) & TCP_RST) == 0);
     /* Stop sending if the nagle algorithm would prevent it
@@ -1053,9 +1106,9 @@ tcp_output(struct tcp_pcb *pcb)
 #if TCP_CWND_DEBUG
     LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_output: snd_wnd %"TCPWNDSIZE_F", cwnd %"TCPWNDSIZE_F", wnd %"U32_F", effwnd %"U32_F", seq %"U32_F", ack %"U32_F", i %"S16_F"\n",
                             pcb->snd_wnd, pcb->cwnd, wnd,
-                            ntohl(seg->tcphdr->seqno) + seg->len -
+                            lwip_ntohl(seg->tcphdr->seqno) + seg->len -
                             pcb->lastack,
-                            ntohl(seg->tcphdr->seqno), pcb->lastack, i));
+                            lwip_ntohl(seg->tcphdr->seqno), pcb->lastack, i));
     ++i;
 #endif /* TCP_CWND_DEBUG */
 
@@ -1076,7 +1129,7 @@ tcp_output(struct tcp_pcb *pcb)
     if (pcb->state != SYN_SENT) {
       pcb->flags &= ~(TF_ACK_DELAY | TF_ACK_NOW);
     }
-    snd_nxt = ntohl(seg->tcphdr->seqno) + TCP_TCPLEN(seg);
+    snd_nxt = lwip_ntohl(seg->tcphdr->seqno) + TCP_TCPLEN(seg);
     if (TCP_SEQ_LT(pcb->snd_nxt, snd_nxt)) {
       pcb->snd_nxt = snd_nxt;
     }
@@ -1092,11 +1145,11 @@ tcp_output(struct tcp_pcb *pcb)
         /* In the case of fast retransmit, the packet should not go to the tail
          * of the unacked queue, but rather somewhere before it. We need to check for
          * this case. -STJ Jul 27, 2004 */
-        if (TCP_SEQ_LT(ntohl(seg->tcphdr->seqno), ntohl(useg->tcphdr->seqno))) {
+        if (TCP_SEQ_LT(lwip_ntohl(seg->tcphdr->seqno), lwip_ntohl(useg->tcphdr->seqno))) {
           /* add segment to before tail of unacked list, keeping the list sorted */
           struct tcp_seg **cur_seg = &(pcb->unacked);
           while (*cur_seg &&
-            TCP_SEQ_LT(ntohl((*cur_seg)->tcphdr->seqno), ntohl(seg->tcphdr->seqno))) {
+            TCP_SEQ_LT(lwip_ntohl((*cur_seg)->tcphdr->seqno), lwip_ntohl(seg->tcphdr->seqno))) {
               cur_seg = &((*cur_seg)->next );
           }
           seg->next = (*cur_seg);
@@ -1113,6 +1166,7 @@ tcp_output(struct tcp_pcb *pcb)
     }
     seg = pcb->unsent;
   }
+output_done:
 #if TCP_OVERSIZE
   if (pcb->unsent == NULL) {
     /* last unsent has been removed, reset unsent_oversize */
@@ -1147,18 +1201,18 @@ tcp_output_segment(struct tcp_seg *seg, struct tcp_pcb *pcb, struct netif *netif
 
   /* The TCP header has already been constructed, but the ackno and
    wnd fields remain. */
-  seg->tcphdr->ackno = htonl(pcb->rcv_nxt);
+  seg->tcphdr->ackno = lwip_htonl(pcb->rcv_nxt);
 
   /* advertise our receive window size in this TCP segment */
 #if LWIP_WND_SCALE
   if (seg->flags & TF_SEG_OPTS_WND_SCALE) {
     /* The Window field in a SYN segment itself (the only type where we send
        the window scale option) is never scaled. */
-    seg->tcphdr->wnd = htons(TCPWND_MIN16(pcb->rcv_ann_wnd));
+    seg->tcphdr->wnd = lwip_htons(TCPWND_MIN16(pcb->rcv_ann_wnd));
   } else
 #endif /* LWIP_WND_SCALE */
   {
-    seg->tcphdr->wnd = htons(TCPWND_MIN16(RCV_WND_SCALE(pcb, pcb->rcv_ann_wnd)));
+    seg->tcphdr->wnd = lwip_htons(TCPWND_MIN16(RCV_WND_SCALE(pcb, pcb->rcv_ann_wnd)));
   }
 
   pcb->rcv_ann_right_edge = pcb->rcv_nxt + pcb->rcv_ann_wnd;
@@ -1200,12 +1254,12 @@ tcp_output_segment(struct tcp_seg *seg, struct tcp_pcb *pcb, struct netif *netif
 
   if (pcb->rttest == 0) {
     pcb->rttest = tcp_ticks;
-    pcb->rtseq = ntohl(seg->tcphdr->seqno);
+    pcb->rtseq = lwip_ntohl(seg->tcphdr->seqno);
 
     LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_output_segment: rtseq %"U32_F"\n", pcb->rtseq));
   }
   LWIP_DEBUGF(TCP_OUTPUT_DEBUG, ("tcp_output_segment: %"U32_F":%"U32_F"\n",
-          htonl(seg->tcphdr->seqno), htonl(seg->tcphdr->seqno) +
+          lwip_htonl(seg->tcphdr->seqno), lwip_htonl(seg->tcphdr->seqno) +
           seg->len));
 
   len = (u16_t)((u8_t *)seg->tcphdr - (u8_t *)seg->p->payload);
@@ -1303,10 +1357,10 @@ tcp_rst(u32_t seqno, u32_t ackno,
               (p->len >= sizeof(struct tcp_hdr)));
 
   tcphdr = (struct tcp_hdr *)p->payload;
-  tcphdr->src = htons(local_port);
-  tcphdr->dest = htons(remote_port);
-  tcphdr->seqno = htonl(seqno);
-  tcphdr->ackno = htonl(ackno);
+  tcphdr->src = lwip_htons(local_port);
+  tcphdr->dest = lwip_htons(remote_port);
+  tcphdr->seqno = lwip_htonl(seqno);
+  tcphdr->ackno = lwip_htonl(ackno);
   TCPH_HDRLEN_FLAGS_SET(tcphdr, TCP_HLEN/4, TCP_RST | TCP_ACK);
 #if LWIP_WND_SCALE
   tcphdr->wnd = PP_HTONS(((TCP_WND >> TCP_RCV_SCALE) & 0xFFFF));
@@ -1366,7 +1420,9 @@ tcp_rexmit_rto(struct tcp_pcb *pcb)
   pcb->unacked = NULL;
 
   /* increment number of retransmissions */
-  ++pcb->nrtx;
+  if (pcb->nrtx < 0xFF) {
+    ++pcb->nrtx;
+  }
 
   /* Don't take any RTT measurements after retransmitting. */
   pcb->rttest = 0;
@@ -1399,7 +1455,7 @@ tcp_rexmit(struct tcp_pcb *pcb)
 
   cur_seg = &(pcb->unsent);
   while (*cur_seg &&
-    TCP_SEQ_LT(ntohl((*cur_seg)->tcphdr->seqno), ntohl(seg->tcphdr->seqno))) {
+    TCP_SEQ_LT(lwip_ntohl((*cur_seg)->tcphdr->seqno), lwip_ntohl(seg->tcphdr->seqno))) {
       cur_seg = &((*cur_seg)->next );
   }
   seg->next = *cur_seg;
@@ -1411,7 +1467,9 @@ tcp_rexmit(struct tcp_pcb *pcb)
   }
 #endif /* TCP_OVERSIZE */
 
-  ++pcb->nrtx;
+  if (pcb->nrtx < 0xFF) {
+    ++pcb->nrtx;
+  }
 
   /* Don't take any rtt measurements after retransmitting. */
   pcb->rttest = 0;
@@ -1437,16 +1495,12 @@ tcp_rexmit_fast(struct tcp_pcb *pcb)
                 ("tcp_receive: dupacks %"U16_F" (%"U32_F
                  "), fast retransmit %"U32_F"\n",
                  (u16_t)pcb->dupacks, pcb->lastack,
-                 ntohl(pcb->unacked->tcphdr->seqno)));
+                 lwip_ntohl(pcb->unacked->tcphdr->seqno)));
     tcp_rexmit(pcb);
 
     /* Set ssthresh to half of the minimum of the current
      * cwnd and the advertised window */
-    if (pcb->cwnd > pcb->snd_wnd) {
-      pcb->ssthresh = pcb->snd_wnd / 2;
-    } else {
-      pcb->ssthresh = pcb->cwnd / 2;
-    }
+    pcb->ssthresh = LWIP_MIN(pcb->cwnd, pcb->snd_wnd) / 2;
 
     /* The minimum value for ssthresh should be 2 MSS */
     if (pcb->ssthresh < (2U * pcb->mss)) {
@@ -1488,7 +1542,7 @@ tcp_keepalive(struct tcp_pcb *pcb)
   LWIP_DEBUGF(TCP_DEBUG, ("tcp_keepalive: tcp_ticks %"U32_F"   pcb->tmr %"U32_F" pcb->keep_cnt_sent %"U16_F"\n",
                           tcp_ticks, pcb->tmr, (u16_t)pcb->keep_cnt_sent));
 
-  p = tcp_output_alloc_header(pcb, 0, 0, htonl(pcb->snd_nxt - 1));
+  p = tcp_output_alloc_header(pcb, 0, 0, lwip_htonl(pcb->snd_nxt - 1));
   if (p == NULL) {
     LWIP_DEBUGF(TCP_DEBUG,
                 ("tcp_keepalive: could not allocate memory for pbuf\n"));
@@ -1537,6 +1591,7 @@ tcp_zero_window_probe(struct tcp_pcb *pcb)
   struct tcp_seg *seg;
   u16_t len;
   u8_t is_fin;
+  u32_t snd_nxt;
   struct netif *netif;
 
   LWIP_DEBUGF(TCP_DEBUG, ("tcp_zero_window_probe: sending ZERO WINDOW probe to "));
@@ -1581,6 +1636,12 @@ tcp_zero_window_probe(struct tcp_pcb *pcb)
     pbuf_copy_partial(seg->p, d, 1, seg->p->tot_len - seg->len);
   }
 
+  /* The byte may be acknowledged without the window being opened. */
+  snd_nxt = lwip_ntohl(seg->tcphdr->seqno) + 1;
+  if (TCP_SEQ_LT(pcb->snd_nxt, snd_nxt)) {
+    pcb->snd_nxt = snd_nxt;
+  }
+
   netif = ip_route(&pcb->local_ip, &pcb->remote_ip);
   if (netif == NULL) {
     err = ERR_RTE;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/timeouts.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/timeouts.c b/net/ip/lwip_base/src/core/timeouts.c
index fcba0a1..227d71f 100644
--- a/net/ip/lwip_base/src/core/timeouts.c
+++ b/net/ip/lwip_base/src/core/timeouts.c
@@ -179,7 +179,7 @@ void sys_timeouts_init(void)
   for (i = 1; i < LWIP_ARRAYSIZE(lwip_cyclic_timers); i++) {
     /* we have to cast via size_t to get rid of const warning
       (this is OK as cyclic_timer() casts back to const* */
-    sys_timeout(lwip_cyclic_timers[i].interval_ms, cyclic_timer, (void*)(size_t)&lwip_cyclic_timers[i]);
+    sys_timeout(lwip_cyclic_timers[i].interval_ms, cyclic_timer, LWIP_CONST_CAST(void*, &lwip_cyclic_timers[i]));
   }
 
   /* Initialise timestamp for sys_check_timeouts */
@@ -360,7 +360,6 @@ sys_check_timeouts(void)
   }
 }
 
-#if NO_SYS
 /** Set back the timestamp of the last call to sys_check_timeouts()
  * This is necessary if sys_check_timeouts() hasn't been called for a long
  * time (e.g. while saving energy) to prevent all timer functions of that
@@ -371,7 +370,6 @@ sys_restart_timeouts(void)
 {
   timeouts_last_time = sys_now();
 }
-#endif /* NO_SYS */
 
 /** Return the time left before the next timeout is due. If no timeouts are
  * enqueued, returns 0xffffffff

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/udp.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/udp.c b/net/ip/lwip_base/src/core/udp.c
index 20e97da..ce2e3d2 100644
--- a/net/ip/lwip_base/src/core/udp.c
+++ b/net/ip/lwip_base/src/core/udp.c
@@ -116,24 +116,6 @@ again:
     }
   }
   return udp_port;
-#if 0
-  struct udp_pcb *ipcb = udp_pcbs;
-  while ((ipcb != NULL) && (udp_port != UDP_LOCAL_PORT_RANGE_END)) {
-    if (ipcb->local_port == udp_port) {
-      /* port is already used by another udp_pcb */
-      udp_port++;
-      /* restart scanning all udp pcbs */
-      ipcb = udp_pcbs;
-    } else {
-      /* go on with next udp pcb */
-      ipcb = ipcb->next;
-    }
-  }
-  if (ipcb != NULL) {
-    return 0;
-  }
-  return udp_port;
-#endif
 }
 
 /** Common code to see if the current input packet matches the pcb
@@ -178,15 +160,8 @@ udp_input_local_match(struct udp_pcb *pcb, struct netif *inp, u8_t broadcast)
       }
     } else
 #endif /* LWIP_IPV4 */
-    /* Handle IPv4 and IPv6: all, multicast or exact match */
-    if (ip_addr_isany(&pcb->local_ip) ||
-#if LWIP_IPV6_MLD
-       (ip_current_is_v6() && ip6_addr_ismulticast(ip6_current_dest_addr())) ||
-#endif /* LWIP_IPV6_MLD */
-#if LWIP_IGMP
-       (!ip_current_is_v6() && ip4_addr_ismulticast(ip4_current_dest_addr())) ||
-#endif /* LWIP_IGMP */
-       ip_addr_cmp(&pcb->local_ip, ip_current_dest_addr())) {
+    /* Handle IPv4 and IPv6: all or exact match */
+    if (ip_addr_isany(&pcb->local_ip) || ip_addr_cmp(&pcb->local_ip, ip_current_dest_addr())) {
       return 1;
     }
   }
@@ -242,17 +217,17 @@ udp_input(struct pbuf *p, struct netif *inp)
   LWIP_DEBUGF(UDP_DEBUG, ("udp_input: received datagram of length %"U16_F"\n", p->tot_len));
 
   /* convert src and dest ports to host byte order */
-  src = ntohs(udphdr->src);
-  dest = ntohs(udphdr->dest);
+  src = lwip_ntohs(udphdr->src);
+  dest = lwip_ntohs(udphdr->dest);
 
   udp_debug_print(udphdr);
 
   /* print the UDP source and destination */
   LWIP_DEBUGF(UDP_DEBUG, ("udp ("));
   ip_addr_debug_print(UDP_DEBUG, ip_current_dest_addr());
-  LWIP_DEBUGF(UDP_DEBUG, (", %"U16_F") <-- (", ntohs(udphdr->dest)));
+  LWIP_DEBUGF(UDP_DEBUG, (", %"U16_F") <-- (", lwip_ntohs(udphdr->dest)));
   ip_addr_debug_print(UDP_DEBUG, ip_current_src_addr());
-  LWIP_DEBUGF(UDP_DEBUG, (", %"U16_F")\n", ntohs(udphdr->src)));
+  LWIP_DEBUGF(UDP_DEBUG, (", %"U16_F")\n", lwip_ntohs(udphdr->src)));
 
   pcb = NULL;
   prev = NULL;
@@ -331,7 +306,7 @@ udp_input(struct pbuf *p, struct netif *inp)
 #if LWIP_UDPLITE
       if (ip_current_header_proto() == IP_PROTO_UDPLITE) {
         /* Do the UDP Lite checksum */
-        u16_t chklen = ntohs(udphdr->len);
+        u16_t chklen = lwip_ntohs(udphdr->len);
         if (chklen < sizeof(struct udp_hdr)) {
           if (chklen == 0) {
             /* For UDP-Lite, checksum length of 0 means checksum
@@ -429,7 +404,7 @@ udp_input(struct pbuf *p, struct netif *inp)
          destination address was broadcast/multicast. */
       if (!broadcast && !ip_addr_ismulticast(ip_current_dest_addr())) {
         /* move payload pointer back to ip header */
-        pbuf_header_force(p, ip_current_header_tot_len() + UDP_HLEN);
+        pbuf_header_force(p, (s16_t)(ip_current_header_tot_len() + UDP_HLEN));
         icmp_port_unreach(ip_current_is_v6(), p);
       }
 #endif /* LWIP_ICMP || LWIP_ICMP6 */
@@ -571,7 +546,12 @@ udp_sendto_chksum(struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *dst_ip,
 #endif /* LWIP_IPV6 || (LWIP_IPV4 && LWIP_MULTICAST_TX_OPTIONS) */
 
   /* find the outgoing network interface for this packet */
-  netif = ip_route(&pcb->local_ip, dst_ip_route);
+  if(IP_IS_ANY_TYPE_VAL(pcb->local_ip)) {
+    /* Don't call ip_route() with IP_ANY_TYPE */
+    netif = ip_route(IP46_ADDR_ANY(IP_GET_TYPE(dst_ip_route)), dst_ip_route);
+  } else {
+    netif = ip_route(&pcb->local_ip, dst_ip_route);
+  }
 
   /* no outgoing network interface could be found? */
   if (netif == NULL) {
@@ -662,7 +642,7 @@ udp_sendto_if_chksum(struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *dst_i
      * this could be an old address if netif->ip_addr has changed */
     if (!ip4_addr_cmp(ip_2_ip4(&(pcb->local_ip)), netif_ip4_addr(netif))) {
       /* local_ip doesn't match, drop the packet */
-      return ERR_VAL;
+      return ERR_RTE;
     }
     /* use UDP PCB local IP address as source address */
     src_ip = &pcb->local_ip;
@@ -752,8 +732,8 @@ udp_sendto_if_src_chksum(struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *d
               (q->len >= sizeof(struct udp_hdr)));
   /* q now represents the packet to be sent */
   udphdr = (struct udp_hdr *)q->payload;
-  udphdr->src = htons(pcb->local_port);
-  udphdr->dest = htons(dst_port);
+  udphdr->src = lwip_htons(pcb->local_port);
+  udphdr->dest = lwip_htons(dst_port);
   /* in UDP, 0 checksum means 'no checksum' */
   udphdr->chksum = 0x0000;
 
@@ -786,7 +766,7 @@ udp_sendto_if_src_chksum(struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *d
       chklen_hdr = 0;
       chklen = q->tot_len;
     }
-    udphdr->len = htons(chklen_hdr);
+    udphdr->len = lwip_htons(chklen_hdr);
     /* calculate checksum */
 #if CHECKSUM_GEN_UDP
     IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_UDP) {
@@ -817,7 +797,7 @@ udp_sendto_if_src_chksum(struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *d
 #endif /* LWIP_UDPLITE */
   {      /* UDP */
     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP packet length %"U16_F"\n", q->tot_len));
-    udphdr->len = htons(q->tot_len);
+    udphdr->len = lwip_htons(q->tot_len);
     /* calculate checksum */
 #if CHECKSUM_GEN_UDP
     IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_UDP) {
@@ -883,7 +863,7 @@ udp_sendto_if_src_chksum(struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *d
  * Bind an UDP PCB.
  *
  * @param pcb UDP PCB to be bound with a local address ipaddr and port.
- * @param ipaddr local IP address to bind with. Use IP_ADDR_ANY to
+ * @param ipaddr local IP address to bind with. Use IP4_ADDR_ANY to
  * bind to all local interfaces.
  * @param port local UDP port to bind with. Use 0 to automatically bind
  * to a random port between UDP_LOCAL_PORT_RANGE_START and
@@ -907,12 +887,12 @@ udp_bind(struct udp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port)
 #if LWIP_IPV4
   /* Don't propagate NULL pointer (IPv4 ANY) to subsequent functions */
   if (ipaddr == NULL) {
-    ipaddr = IP_ADDR_ANY;
+    ipaddr = IP4_ADDR_ANY;
   }
 #endif /* LWIP_IPV4 */
 
   /* still need to check for ipaddr == NULL in IPv6 only case */
-  if ((pcb == NULL) || (ipaddr == NULL) || !IP_ADDR_PCB_VERSION_MATCH_EXACT(pcb, ipaddr)) {
+  if ((pcb == NULL) || (ipaddr == NULL)) {
     return ERR_VAL;
   }
 
@@ -1002,7 +982,7 @@ udp_connect(struct udp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port)
 {
   struct udp_pcb *ipcb;
 
-  if ((pcb == NULL) || (ipaddr == NULL) || !IP_ADDR_PCB_VERSION_MATCH(pcb, ipaddr)) {
+  if ((pcb == NULL) || (ipaddr == NULL)) {
     return ERR_VAL;
   }
 
@@ -1143,7 +1123,7 @@ udp_new(void)
  * @ingroup udp_raw
  * Create a UDP PCB for specific IP type.
  *
- * @param type IP address type, see IPADDR_TYPE_XX definitions.
+ * @param type IP address type, see @ref lwip_ip_addr_type definitions.
  * If you want to listen to IPv4 and IPv6 (dual-stack) packets,
  * supply @ref IPADDR_TYPE_ANY as argument and bind to @ref IP_ANY_TYPE.
  * @return The UDP PCB which was created. NULL if the PCB data structure
@@ -1200,10 +1180,10 @@ udp_debug_print(struct udp_hdr *udphdr)
   LWIP_DEBUGF(UDP_DEBUG, ("UDP header:\n"));
   LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n"));
   LWIP_DEBUGF(UDP_DEBUG, ("|     %5"U16_F"     |     %5"U16_F"     | (src port, dest port)\n",
-                          ntohs(udphdr->src), ntohs(udphdr->dest)));
+                          lwip_ntohs(udphdr->src), lwip_ntohs(udphdr->dest)));
   LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n"));
   LWIP_DEBUGF(UDP_DEBUG, ("|     %5"U16_F"     |     0x%04"X16_F"    | (len, chksum)\n",
-                          ntohs(udphdr->len), ntohs(udphdr->chksum)));
+                          lwip_ntohs(udphdr->len), lwip_ntohs(udphdr->chksum)));
   LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n"));
 }
 #endif /* UDP_DEBUG */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/netif/ethernet.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/netif/ethernet.c b/net/ip/lwip_base/src/netif/ethernet.c
index 621838e..52ea423 100644
--- a/net/ip/lwip_base/src/netif/ethernet.c
+++ b/net/ip/lwip_base/src/netif/ethernet.c
@@ -56,6 +56,10 @@
 #include "netif/ppp/pppoe.h"
 #endif /* PPPOE_SUPPORT */
 
+#ifdef LWIP_HOOK_FILENAME
+#include LWIP_HOOK_FILENAME
+#endif
+
 const struct eth_addr ethbroadcast = {{0xff,0xff,0xff,0xff,0xff,0xff}};
 const struct eth_addr ethzero = {{0,0,0,0,0,0}};
 
@@ -69,9 +73,9 @@ const struct eth_addr ethzero = {{0,0,0,0,0,0}};
  * @param p the received packet, p->payload pointing to the ethernet header
  * @param netif the network interface on which the packet was received
  * 
- * @see @ref LWIP_HOOK_UNKNOWN_ETH_PROTOCOL,
- * @ref ETHARP_SUPPORT_VLAN and
- * @ref LWIP_HOOK_VLAN_CHECK.
+ * @see LWIP_HOOK_UNKNOWN_ETH_PROTOCOL
+ * @see ETHARP_SUPPORT_VLAN
+ * @see LWIP_HOOK_VLAN_CHECK
  */
 err_t
 ethernet_input(struct pbuf *p, struct netif *netif)
@@ -98,7 +102,7 @@ ethernet_input(struct pbuf *p, struct netif *netif)
      (unsigned)ethhdr->dest.addr[3], (unsigned)ethhdr->dest.addr[4], (unsigned)ethhdr->dest.addr[5],
      (unsigned)ethhdr->src.addr[0],  (unsigned)ethhdr->src.addr[1],  (unsigned)ethhdr->src.addr[2],
      (unsigned)ethhdr->src.addr[3],  (unsigned)ethhdr->src.addr[4],  (unsigned)ethhdr->src.addr[5],
-     htons(ethhdr->type)));
+     lwip_htons(ethhdr->type)));
 
   type = ethhdr->type;
 #if ETHARP_SUPPORT_VLAN
@@ -130,7 +134,7 @@ ethernet_input(struct pbuf *p, struct netif *netif)
 #endif /* ETHARP_SUPPORT_VLAN */
 
 #if LWIP_ARP_FILTER_NETIF
-  netif = LWIP_ARP_FILTER_NETIF_FN(p, netif, htons(type));
+  netif = LWIP_ARP_FILTER_NETIF_FN(p, netif, lwip_htons(type));
 #endif /* LWIP_ARP_FILTER_NETIF*/
 
   if (ethhdr->dest.addr[0] & 1) {
@@ -247,7 +251,7 @@ free_and_return:
  * Send an ethernet packet on the network using netif->linkoutput().
  * The ethernet header is filled in before sending.
  *
- * @see @ref LWIP_HOOK_VLAN_SET
+ * @see LWIP_HOOK_VLAN_SET
  *
  * @param netif the lwIP network interface on which to send the packet
  * @param p the packet to send. pbuf layer must be @ref PBUF_LINK.
@@ -262,7 +266,7 @@ ethernet_output(struct netif* netif, struct pbuf* p,
                 u16_t eth_type)
 {
   struct eth_hdr* ethhdr;
-  u16_t eth_type_be = htons(eth_type);
+  u16_t eth_type_be = lwip_htons(eth_type);
 
 #if ETHARP_SUPPORT_VLAN && defined(LWIP_HOOK_VLAN_SET)
   s32_t vlan_prio_vid = LWIP_HOOK_VLAN_SET(netif, p, src, dst, eth_type);
@@ -276,7 +280,7 @@ ethernet_output(struct netif* netif, struct pbuf* p,
     }
     vlanhdr = (struct eth_vlan_hdr*)(((u8_t*)p->payload) + SIZEOF_ETH_HDR);
     vlanhdr->tpid     = eth_type_be;
-    vlanhdr->prio_vid = htons((u16_t)vlan_prio_vid);
+    vlanhdr->prio_vid = lwip_htons((u16_t)vlan_prio_vid);
 
     eth_type_be = PP_HTONS(ETHTYPE_VLAN);
   } else



[02/30] incubator-mynewt-core git commit: net/ip; add locking, and other bug fixes.

Posted by ad...@apache.org.
net/ip; add locking, and other bug fixes.


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/c700fc74
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/c700fc74
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/c700fc74

Branch: refs/heads/master
Commit: c700fc74b966dccff481039c7fd7f617915de779
Parents: 66ae3df
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Fri Apr 14 12:52:29 2017 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Fri Apr 14 13:21:30 2017 -0700

----------------------------------------------------------------------
 net/ip/src/lwip_if.c     |  17 +++---
 net/ip/src/lwip_socket.c | 121 +++++++++++++++++++++++++++---------------
 2 files changed, 89 insertions(+), 49 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/c700fc74/net/ip/src/lwip_if.c
----------------------------------------------------------------------
diff --git a/net/ip/src/lwip_if.c b/net/ip/src/lwip_if.c
index 1b4c427..41d6b2e 100644
--- a/net/ip/src/lwip_if.c
+++ b/net/ip/src/lwip_if.c
@@ -36,19 +36,18 @@ lwip_if_flags(uint8_t if_flags)
 
     flags = 0;
 
-    if ((if_flags & (NETIF_FLAG_UP | NETIF_FLAG_LINK_UP)) ==
-      (NETIF_FLAG_UP | NETIF_FLAG_LINK_UP)) {
+    if (if_flags & NETIF_FLAG_UP) {
         flags |= MN_ITF_F_UP;
     }
+    if (if_flags & NETIF_FLAG_LINK_UP) {
+        flags |= MN_ITF_F_LINK;
+    }
     if (if_flags & (NETIF_FLAG_IGMP | NETIF_FLAG_MLD6)) {
         flags |= MN_ITF_F_MULTICAST;
     }
     return flags;
 }
 
-/*
- * XXX locking
- */
 int
 lwip_itf_getnext(struct mn_itf *mi)
 {
@@ -64,6 +63,7 @@ lwip_itf_getnext(struct mn_itf *mi)
     mi->mif_idx = UCHAR_MAX;
 
     rc = MN_ENOBUFS;
+    LOCK_TCPIP_CORE();
     for (nif = netif_list; nif; nif = nif->next) {
         cur_idx = nif->num;
         if (cur_idx <= prev_idx || cur_idx >= mi->mif_idx) {
@@ -76,6 +76,7 @@ lwip_itf_getnext(struct mn_itf *mi)
         mi->mif_flags = lwip_if_flags(nif->flags);
         rc = 0;
     }
+    UNLOCK_TCPIP_CORE();
     return rc;
 }
 
@@ -109,8 +110,10 @@ lwip_itf_addr_getnext(struct mn_itf *mi, struct mn_itf_addr *mia)
     int copy_next = 0;
 #endif
 
+    LOCK_TCPIP_CORE();
     nif = netif_find(mi->mif_name);
     if (!nif) {
+        UNLOCK_TCPIP_CORE();
         return MN_EINVAL;
     }
 
@@ -122,6 +125,7 @@ lwip_itf_addr_getnext(struct mn_itf *mi, struct mn_itf_addr *mia)
               sizeof(struct mn_in_addr));
             mia->mifa_plen = plen(ip_2_ip4(&nif->netmask),
               sizeof(struct mn_in_addr));
+            UNLOCK_TCPIP_CORE();
             return 0;
         }
 #endif
@@ -139,6 +143,7 @@ lwip_itf_addr_getnext(struct mn_itf *mi, struct mn_itf_addr *mia)
             memcpy(&mia->mifa_addr, netif_ip6_addr(nif, i),
               sizeof(struct mn_in6_addr));
             mia->mifa_plen = 64;
+            UNLOCK_TCPIP_CORE();
             return 0;
         }
         if (!memcmp(&mia->mifa_addr, netif_ip6_addr(nif, i),
@@ -147,6 +152,6 @@ lwip_itf_addr_getnext(struct mn_itf *mi, struct mn_itf_addr *mia)
         }
     }
 #endif
+    UNLOCK_TCPIP_CORE();
     return -1;
 }
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/c700fc74/net/ip/src/lwip_socket.c
----------------------------------------------------------------------
diff --git a/net/ip/src/lwip_socket.c b/net/ip/src/lwip_socket.c
index ddf7be7..1a57392 100644
--- a/net/ip/src/lwip_socket.c
+++ b/net/ip/src/lwip_socket.c
@@ -24,6 +24,7 @@
 #include <mn_socket/mn_socket.h>
 #include <mn_socket/mn_socket_ops.h>
 
+#include <lwip/tcpip.h>
 #include <lwip/udp.h>
 #include <lwip/tcp.h>
 #include "ip_priv.h"
@@ -63,7 +64,7 @@ static const struct mn_socket_ops lwip_sock_ops = {
     .mso_getpeername = lwip_getpeername,
 
     .mso_itf_getnext = lwip_itf_getnext,
-    .mso_itf_addr_getnext = lwip_itf_addr_getnext
+    .mso_itf_addr_getnext = lwip_itf_addr_getnext,
 };
 
 struct lwip_sock {
@@ -93,7 +94,7 @@ lwip_mn_addr_to_addr(struct mn_sockaddr *ms, ip_addr_t *addr, uint16_t *port)
     case MN_AF_INET:
         msin = (struct mn_sockaddr_in *)ms;
         IP_SET_TYPE_VAL(*addr, IPADDR_TYPE_V4);
-        *port = msin->msin_port;
+        *port = ntohs(msin->msin_port);
         memcpy(ip_2_ip4(addr), &msin->msin_addr, sizeof(struct mn_in_addr));
         return 0;
 #endif
@@ -101,7 +102,7 @@ lwip_mn_addr_to_addr(struct mn_sockaddr *ms, ip_addr_t *addr, uint16_t *port)
     case MN_AF_INET6:
         msin6 =  (struct mn_sockaddr_in6 *)ms;
         IP_SET_TYPE_VAL(*addr, IPADDR_TYPE_V6);
-        *port = msin6->msin6_port;
+        *port = ntohs(msin6->msin6_port);
         memcpy(ip_2_ip6(addr), &msin6->msin6_addr, sizeof(struct mn_in6_addr));
         return 0;
 #endif
@@ -122,9 +123,7 @@ lwip_addr_to_mn_addr(struct mn_sockaddr *ms, const ip_addr_t *addr,
     } else {
         ms->msa_family = MN_AF_INET6;
     }
-#if !LWIP_IPV4
-    ms->msa_family = MN_AF_INET;
-#endif
+    port = htons(port);
     switch (ms->msa_family) {
 #if LWIP_IPV4
     case MN_AF_INET:
@@ -145,7 +144,7 @@ lwip_addr_to_mn_addr(struct mn_sockaddr *ms, const ip_addr_t *addr,
     }
 }
 
-static int
+int
 lwip_err_to_mn_err(int rc)
 {
     switch (rc) {
@@ -198,6 +197,7 @@ lwip_sock_udp_rx(void *arg, struct udp_pcb *pcb, struct pbuf *p,
     for (q = p; q; q = q->next) {
         os_mbuf_copyinto(m, off, q->payload, p->len);
     }
+    pbuf_free(p);
     STAILQ_INSERT_TAIL(&s->ls_rx, OS_MBUF_PKTHDR(m), omp_next);
     mn_socket_readable(&s->ls_sock, 0);
 }
@@ -226,6 +226,7 @@ lwip_sock_tcp_rx(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
     for (q = p; q; q = q->next) {
         os_mbuf_copyinto(m, off, q->payload, p->len);
     }
+    pbuf_free(p);
     STAILQ_INSERT_TAIL(&s->ls_rx, OS_MBUF_PKTHDR(m), omp_next);
     mn_socket_readable(&s->ls_sock, 0);
 
@@ -246,7 +247,7 @@ lwip_sock_tcp_connected(void *arg, struct tcp_pcb *pcb, err_t err)
 {
     struct lwip_sock *s = (struct lwip_sock *)arg;
 
-    mn_socket_writable(&s->ls_sock, err);
+    mn_socket_writable(&s->ls_sock, lwip_err_to_mn_err(err));
     return ERR_OK;
 }
 
@@ -255,7 +256,7 @@ lwip_sock_tcp_err(void *arg, err_t err)
 {
     struct lwip_sock *s = (struct lwip_sock *)arg;
 
-    mn_socket_writable(&s->ls_sock, err);
+    mn_socket_writable(&s->ls_sock, lwip_err_to_mn_err(err));
 }
 
 static err_t
@@ -264,11 +265,20 @@ lwip_sock_accept(void *arg, struct tcp_pcb *new, err_t err)
     struct lwip_sock *s = (struct lwip_sock *)arg;
     struct lwip_sock *new_s;
 
+    if (err != ERR_OK) {
+        return err;
+    }
     new_s = os_memblock_get(&lwip_sockets);
-    assert(new_s); /* memory pool should be sized correctly */
+    if (!new_s) {
+        return ERR_MEM;
+    }
     new_s->ls_type = MN_SOCK_STREAM;
     new_s->ls_sock.ms_ops = &lwip_sock_ops;
     new_s->ls_pcb.tcp = new;
+    tcp_arg(new, new_s);
+    tcp_recv(new, lwip_sock_tcp_rx);
+    tcp_sent(new, lwip_sock_tcp_sent);
+    tcp_err(new, lwip_sock_tcp_err);
     STAILQ_INIT(&new_s->ls_rx);
     new_s->ls_tx = NULL;
     if (mn_socket_newconn(&s->ls_sock, &new_s->ls_sock)) {
@@ -293,6 +303,7 @@ lwip_sock_create(struct mn_socket **sp, uint8_t domain, uint8_t type,
     STAILQ_INIT(&s->ls_rx);
     s->ls_tx = NULL;
 
+    LOCK_TCPIP_CORE();
     switch (type) {
 #if LWIP_UDP
     case MN_SOCK_DGRAM:
@@ -312,6 +323,7 @@ lwip_sock_create(struct mn_socket **sp, uint8_t domain, uint8_t type,
     default:
         break;
     }
+    UNLOCK_TCPIP_CORE();
     if (!s->ls_pcb.ip) {
         os_memblock_put(&lwip_sockets, s);
         return MN_EPROTONOSUPPORT;
@@ -327,6 +339,7 @@ lwip_close(struct mn_socket *ms)
     struct lwip_sock *s = (struct lwip_sock *)ms;
     struct os_mbuf_pkthdr *m;
 
+    LOCK_TCPIP_CORE();
     switch (s->ls_type) {
 #if LWIP_UDP
     case MN_SOCK_DGRAM:
@@ -335,10 +348,14 @@ lwip_close(struct mn_socket *ms)
 #endif
 #if LWIP_TCP
     case MN_SOCK_STREAM:
+        tcp_recv(s->ls_pcb.tcp, NULL);
+        tcp_sent(s->ls_pcb.tcp, NULL);
+        tcp_err(s->ls_pcb.tcp, NULL);
         tcp_close(s->ls_pcb.tcp);
         break;
     }
 #endif
+    UNLOCK_TCPIP_CORE();
     while ((m = STAILQ_FIRST(&s->ls_rx))) {
         STAILQ_REMOVE_HEAD(&s->ls_rx, omp_next);
         os_mbuf_free_chain(OS_MBUF_PKTHDR_TO_MBUF(m));
@@ -363,27 +380,26 @@ lwip_connect(struct mn_socket *ms, struct mn_sockaddr *addr)
     if (rc) {
         return rc;
     }
+    rc = MN_EPROTONOSUPPORT;
+    LOCK_TCPIP_CORE();
     switch (s->ls_type) {
 #if LWIP_UDP
     case MN_SOCK_DGRAM:
         rc = udp_connect(s->ls_pcb.udp, &ip, port);
-        if (rc) {
-            return lwip_err_to_mn_err(rc);
-        }
-        return 0;
+        rc = lwip_err_to_mn_err(rc);
+        break;
 #endif
 #if LWIP_TCP
     case MN_SOCK_STREAM:
         rc = tcp_connect(s->ls_pcb.tcp, &ip, port, lwip_sock_tcp_connected);
-        if (rc) {
-            return lwip_err_to_mn_err(rc);
-        }
-        return 0;
+        rc = lwip_err_to_mn_err(rc);
+        break;
 #endif
     default:
         break;
     }
-    return MN_EPROTONOSUPPORT;
+    UNLOCK_TCPIP_CORE();
+    return rc;
 }
 
 static int
@@ -398,27 +414,26 @@ lwip_bind(struct mn_socket *ms, struct mn_sockaddr *addr)
     if (rc) {
         return rc;
     }
+    rc = MN_EPROTONOSUPPORT;
+    LOCK_TCPIP_CORE();
     switch (s->ls_type) {
 #if LWIP_UDP
     case MN_SOCK_DGRAM:
         rc = udp_bind(s->ls_pcb.udp, &ip, port);
-        if (rc) {
-            return lwip_err_to_mn_err(rc);
-        }
-        return 0;
+        rc = lwip_err_to_mn_err(rc);
+        break;
 #endif
 #if LWIP_TCP
     case MN_SOCK_STREAM:
         rc = tcp_bind(s->ls_pcb.tcp, &ip, port);
-        if (rc) {
-            return lwip_err_to_mn_err(rc);
-        }
-        return 0;
+        rc = lwip_err_to_mn_err(rc);
+        break;
 #endif
     default:
         break;
     }
-    return MN_EPROTONOSUPPORT;
+    UNLOCK_TCPIP_CORE();
+    return rc;
 }
 
 static int
@@ -429,12 +444,14 @@ lwip_listen(struct mn_socket *ms, uint8_t qlen)
     struct tcp_pcb *pcb;
 
     if (s->ls_type == MN_SOCK_STREAM) {
-        tcp_accept(s->ls_pcb.tcp, lwip_sock_accept);
+        LOCK_TCPIP_CORE();
         pcb = tcp_listen_with_backlog(s->ls_pcb.tcp, qlen);
+        UNLOCK_TCPIP_CORE();
         if (!pcb) {
             return MN_EADDRINUSE;
         }
         s->ls_pcb.tcp = pcb;
+        tcp_accept(pcb, lwip_sock_accept);
         return 0;
     }
 #endif
@@ -448,6 +465,7 @@ lwip_stream_tx(struct lwip_sock *s, int notify)
     struct os_mbuf *m;
     struct os_mbuf *n;
 
+    rc = 0;
     while (s->ls_tx && rc == 0) {
         m = s->ls_tx;
         n = SLIST_NEXT(m, om_next);
@@ -510,8 +528,9 @@ lwip_sendto(struct mn_socket *ms, struct os_mbuf *m,
             pbuf_take_at(p, n->om_data, n->om_len, off);
             off += n->om_len;
         }
-
+        LOCK_TCPIP_CORE();
         rc = udp_sendto(s->ls_pcb.udp, p, &ip_addr, port);
+        UNLOCK_TCPIP_CORE();
         if (rc) {
             rc = lwip_err_to_mn_err(rc);
             pbuf_free(p);
@@ -525,8 +544,13 @@ lwip_sendto(struct mn_socket *ms, struct os_mbuf *m,
         if (s->ls_tx) {
             return MN_EAGAIN;
         }
+        if (addr) {
+            return MN_EINVAL;
+        }
+        LOCK_TCPIP_CORE();
         s->ls_tx = m;
         rc = lwip_stream_tx(s, 0);
+        UNLOCK_TCPIP_CORE();
         return rc;
 #endif
     default:
@@ -543,6 +567,7 @@ lwip_recvfrom(struct mn_socket *ms, struct os_mbuf **mp,
     struct os_mbuf_pkthdr *m;
     int slen;
 
+    LOCK_TCPIP_CORE();
     m = STAILQ_FIRST(&s->ls_rx);
     if (m) {
         STAILQ_REMOVE_HEAD(&s->ls_rx, omp_next);
@@ -562,12 +587,14 @@ lwip_recvfrom(struct mn_socket *ms, struct os_mbuf **mp,
             } else {
 #if LWIP_TCP
                 lwip_addr_to_mn_addr(addr, &s->ls_pcb.ip->local_ip,
-                  s->ls_pcb.tcp->local_port);
+                                     s->ls_pcb.tcp->local_port);
 #endif
             }
         }
+        UNLOCK_TCPIP_CORE();
         return 0;
     } else {
+        UNLOCK_TCPIP_CORE();
         *mp = NULL;
         return MN_EAGAIN;
     }
@@ -591,48 +618,56 @@ static int
 lwip_getsockname(struct mn_socket *ms, struct mn_sockaddr *addr)
 {
     struct lwip_sock *s = (struct lwip_sock *)ms;
+    int rc;
 
+    rc = MN_EPROTONOSUPPORT;
+    LOCK_TCPIP_CORE();
     switch (s->ls_type) {
 #if LWIP_UDP
     case MN_SOCK_DGRAM:
         lwip_addr_to_mn_addr(addr, &s->ls_pcb.ip->local_ip,
-          s->ls_pcb.udp->local_port);
-        return 0;
+                             s->ls_pcb.udp->local_port);
+        rc = 0;
 #endif
 #if LWIP_TCP
     case MN_SOCK_STREAM:
         lwip_addr_to_mn_addr(addr, &s->ls_pcb.ip->local_ip,
-          s->ls_pcb.tcp->local_port);
-        return 0;
+                             s->ls_pcb.tcp->local_port);
+        rc = 0;
 #endif
     default:
         break;
     }
-    return MN_EPROTONOSUPPORT;
+    UNLOCK_TCPIP_CORE();
+    return rc;
 }
 
 static int
 lwip_getpeername(struct mn_socket *ms, struct mn_sockaddr *addr)
 {
     struct lwip_sock *s = (struct lwip_sock *)ms;
+    int rc;
 
+    rc = MN_EPROTONOSUPPORT;
+    LOCK_TCPIP_CORE();
     switch (s->ls_type) {
 #if LWIP_UDP
     case MN_SOCK_DGRAM:
         lwip_addr_to_mn_addr(addr, &s->ls_pcb.ip->remote_ip,
-          s->ls_pcb.udp->remote_port);
-        return 0;
+                             s->ls_pcb.udp->remote_port);
+        rc = 0;
 #endif
 #if LWIP_TCP
     case MN_SOCK_STREAM:
         lwip_addr_to_mn_addr(addr, &s->ls_pcb.ip->remote_ip,
-          s->ls_pcb.tcp->remote_port);
-        return 0;
+                             s->ls_pcb.tcp->remote_port);
+        rc = 0;
 #endif
     default:
         break;
     }
-    return MN_EPROTONOSUPPORT;
+    UNLOCK_TCPIP_CORE();
+    return rc;
 }
 
 int
@@ -642,8 +677,8 @@ lwip_socket_init(void)
     int cnt;
     void *mem;
 
-    cnt = MEMP_NUM_TCP_PCB + MEMP_NUM_UDP_PCB;
-    mem = malloc(OS_MEMPOOL_SIZE(cnt, sizeof(struct lwip_sock)));
+    cnt = MEMP_NUM_TCP_PCB + MEMP_NUM_UDP_PCB + MEMP_NUM_TCP_PCB_LISTEN;
+    mem = os_malloc(OS_MEMPOOL_BYTES(cnt, sizeof(struct lwip_sock)));
     if (!mem) {
         return -1;
     }


[22/30] incubator-mynewt-core git commit: net/ip/lwip_base; update to LwIP to tag STABLE-2_0_2_RELEASE

Posted by ad...@apache.org.
net/ip/lwip_base; update to LwIP to tag STABLE-2_0_2_RELEASE


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/f52033e9
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/f52033e9
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/f52033e9

Branch: refs/heads/master
Commit: f52033e9a02b2e8e6a378023977543facb29378d
Parents: 0429ee5
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Fri Apr 14 17:35:31 2017 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Fri Apr 14 17:35:31 2017 -0700

----------------------------------------------------------------------
 net/ip/lwip_base/CHANGELOG                      |  146 ++
 net/ip/lwip_base/UPGRADING                      |   16 +-
 net/ip/lwip_base/doc/NO_SYS_SampleCode.c        |   16 +-
 net/ip/lwip_base/doc/doxygen/generate.sh        |    2 +
 net/ip/lwip_base/doc/doxygen/lwip.Doxyfile      |    7 +-
 net/ip/lwip_base/doc/doxygen/main_page.h        |   75 +-
 net/ip/lwip_base/doc/mqtt_client.txt            |  162 +++
 net/ip/lwip_base/doc/ppp.txt                    |    6 +-
 net/ip/lwip_base/doc/rawapi.txt                 |    8 +-
 net/ip/lwip_base/doc/sys_arch.txt               |    2 +-
 net/ip/lwip_base/include/lwip/api.h             |   31 +-
 net/ip/lwip_base/include/lwip/apps/httpd_opts.h |   30 -
 net/ip/lwip_base/include/lwip/apps/mdns.h       |   10 +-
 net/ip/lwip_base/include/lwip/apps/mdns_opts.h  |   10 +-
 net/ip/lwip_base/include/lwip/apps/mdns_priv.h  |   10 +-
 net/ip/lwip_base/include/lwip/apps/mqtt.h       |  244 ++++
 net/ip/lwip_base/include/lwip/apps/mqtt_opts.h  |  103 ++
 net/ip/lwip_base/include/lwip/apps/netbiosns.h  |    8 -
 .../include/lwip/apps/netbiosns_opts.h          |   18 -
 net/ip/lwip_base/include/lwip/apps/snmp_opts.h  |    8 -
 net/ip/lwip_base/include/lwip/apps/snmpv3.h     |    8 -
 net/ip/lwip_base/include/lwip/apps/sntp_opts.h  |    8 -
 net/ip/lwip_base/include/lwip/apps/tftp_opts.h  |  105 ++
 .../lwip_base/include/lwip/apps/tftp_server.h   |   94 ++
 net/ip/lwip_base/include/lwip/arch.h            |  299 ++--
 net/ip/lwip_base/include/lwip/autoip.h          |    2 +
 net/ip/lwip_base/include/lwip/debug.h           |   81 +-
 net/ip/lwip_base/include/lwip/def.h             |   95 +-
 net/ip/lwip_base/include/lwip/dhcp.h            |    2 +
 net/ip/lwip_base/include/lwip/dhcp6.h           |    8 -
 net/ip/lwip_base/include/lwip/dns.h             |   18 +-
 net/ip/lwip_base/include/lwip/err.h             |    4 +
 net/ip/lwip_base/include/lwip/errno.h           |  193 +++
 net/ip/lwip_base/include/lwip/icmp.h            |    2 +-
 net/ip/lwip_base/include/lwip/icmp6.h           |   89 +-
 net/ip/lwip_base/include/lwip/igmp.h            |    6 +-
 net/ip/lwip_base/include/lwip/inet.h            |    8 +-
 net/ip/lwip_base/include/lwip/inet_chksum.h     |    8 +-
 net/ip/lwip_base/include/lwip/init.h            |    4 +-
 net/ip/lwip_base/include/lwip/ip4_addr.h        |   36 +-
 net/ip/lwip_base/include/lwip/ip6_addr.h        |   66 +-
 net/ip/lwip_base/include/lwip/ip_addr.h         |   73 +-
 net/ip/lwip_base/include/lwip/mem.h             |    3 +-
 net/ip/lwip_base/include/lwip/mld6.h            |    7 +-
 net/ip/lwip_base/include/lwip/nd6.h             |   93 +-
 net/ip/lwip_base/include/lwip/netdb.h           |    3 +-
 net/ip/lwip_base/include/lwip/netif.h           |   10 +-
 net/ip/lwip_base/include/lwip/netifapi.h        |   12 +-
 net/ip/lwip_base/include/lwip/opt.h             |  116 +-
 net/ip/lwip_base/include/lwip/pbuf.h            |   20 +-
 net/ip/lwip_base/include/lwip/priv/api_msg.h    |    3 +-
 net/ip/lwip_base/include/lwip/priv/memp_std.h   |    8 -
 net/ip/lwip_base/include/lwip/priv/nd6_priv.h   |  144 ++
 net/ip/lwip_base/include/lwip/priv/tcp_priv.h   |   27 +-
 net/ip/lwip_base/include/lwip/priv/tcpip_priv.h |    4 +-
 net/ip/lwip_base/include/lwip/prot/dns.h        |   18 +
 net/ip/lwip_base/include/lwip/prot/ethernet.h   |    2 +-
 net/ip/lwip_base/include/lwip/prot/icmp6.h      |   87 ++
 net/ip/lwip_base/include/lwip/prot/ip.h         |    8 -
 net/ip/lwip_base/include/lwip/prot/ip4.h        |   16 +
 net/ip/lwip_base/include/lwip/prot/ip6.h        |   27 +-
 net/ip/lwip_base/include/lwip/prot/mld6.h       |    2 +-
 net/ip/lwip_base/include/lwip/prot/nd6.h        |   24 +
 net/ip/lwip_base/include/lwip/prot/tcp.h        |   14 +-
 net/ip/lwip_base/include/lwip/raw.h             |    2 +
 net/ip/lwip_base/include/lwip/sockets.h         |    5 +-
 net/ip/lwip_base/include/lwip/stats.h           |    4 +-
 net/ip/lwip_base/include/lwip/sys.h             |   44 +-
 net/ip/lwip_base/include/lwip/tcp.h             |   12 +-
 net/ip/lwip_base/include/lwip/tcpip.h           |    2 +
 net/ip/lwip_base/include/lwip/timeouts.h        |    2 +-
 net/ip/lwip_base/include/netif/lowpan6_opts.h   |    8 -
 net/ip/lwip_base/include/netif/ppp/ccp.h        |    8 -
 net/ip/lwip_base/include/netif/ppp/chap-new.h   |    8 -
 net/ip/lwip_base/include/netif/ppp/chap_ms.h    |    8 -
 net/ip/lwip_base/include/netif/ppp/eui64.h      |   10 +-
 net/ip/lwip_base/include/netif/ppp/fsm.h        |    8 -
 net/ip/lwip_base/include/netif/ppp/ipcp.h       |    8 -
 net/ip/lwip_base/include/netif/ppp/ipv6cp.h     |    8 -
 net/ip/lwip_base/include/netif/ppp/lcp.h        |    8 -
 net/ip/lwip_base/include/netif/ppp/magic.h      |    8 -
 net/ip/lwip_base/include/netif/ppp/mppe.h       |   10 +-
 net/ip/lwip_base/include/netif/ppp/ppp.h        |   12 +-
 net/ip/lwip_base/include/netif/ppp/ppp_impl.h   |   12 +-
 net/ip/lwip_base/include/netif/ppp/ppp_opts.h   |    8 -
 net/ip/lwip_base/include/netif/ppp/pppcrypt.h   |    8 -
 net/ip/lwip_base/include/netif/ppp/pppdebug.h   |    8 -
 net/ip/lwip_base/include/netif/ppp/pppoe.h      |    8 -
 net/ip/lwip_base/include/netif/ppp/pppol2tp.h   |    8 -
 net/ip/lwip_base/include/netif/ppp/pppos.h      |    8 -
 net/ip/lwip_base/include/netif/ppp/upap.h       |    8 -
 net/ip/lwip_base/include/netif/ppp/vj.h         |    8 -
 net/ip/lwip_base/include/posix/errno.h          |   33 +
 net/ip/lwip_base/src/Filelists.mk               |   10 +-
 net/ip/lwip_base/src/api/api_lib.c              |   69 +-
 net/ip/lwip_base/src/api/api_msg.c              |  127 +-
 net/ip/lwip_base/src/api/err.c                  |   40 +
 net/ip/lwip_base/src/api/netdb.c                |   10 +-
 net/ip/lwip_base/src/api/netifapi.c             |   14 +-
 net/ip/lwip_base/src/api/sockets.c              |  204 +--
 net/ip/lwip_base/src/api/tcpip.c                |    3 +-
 net/ip/lwip_base/src/apps/httpd/fsdata.h        |    8 -
 net/ip/lwip_base/src/apps/httpd/httpd.c         |  180 +--
 net/ip/lwip_base/src/apps/httpd/httpd_structs.h |    8 -
 net/ip/lwip_base/src/apps/lwiperf/lwiperf.c     |   16 +-
 net/ip/lwip_base/src/apps/mdns/mdns.c           |  161 +--
 net/ip/lwip_base/src/apps/mqtt/mqtt.c           | 1341 ++++++++++++++++++
 net/ip/lwip_base/src/apps/netbiosns/netbiosns.c |    5 +-
 net/ip/lwip_base/src/apps/snmp/snmp_asn1.c      |    8 +-
 net/ip/lwip_base/src/apps/snmp/snmp_core.c      |   84 +-
 net/ip/lwip_base/src/apps/snmp/snmp_mib2_ip.c   |   12 +-
 net/ip/lwip_base/src/apps/snmp/snmp_mib2_tcp.c  |    6 +-
 net/ip/lwip_base/src/apps/snmp/snmp_msg.c       |   11 +-
 net/ip/lwip_base/src/apps/snmp/snmp_netconn.c   |    5 +-
 net/ip/lwip_base/src/apps/snmp/snmp_raw.c       |    2 +-
 .../lwip_base/src/apps/snmp/snmp_threadsync.c   |    1 +
 net/ip/lwip_base/src/apps/snmp/snmp_traps.c     |    9 +-
 net/ip/lwip_base/src/apps/snmp/snmpv3_priv.h    |    8 -
 net/ip/lwip_base/src/apps/sntp/sntp.c           |    9 +-
 net/ip/lwip_base/src/apps/tftp/tftp_server.c    |  417 ++++++
 net/ip/lwip_base/src/core/def.c                 |  177 ++-
 net/ip/lwip_base/src/core/dns.c                 |  239 +++-
 net/ip/lwip_base/src/core/inet_chksum.c         |   15 +-
 net/ip/lwip_base/src/core/init.c                |   12 +-
 net/ip/lwip_base/src/core/ipv4/autoip.c         |   16 +-
 net/ip/lwip_base/src/core/ipv4/dhcp.c           |  114 +-
 net/ip/lwip_base/src/core/ipv4/etharp.c         |   69 +-
 net/ip/lwip_base/src/core/ipv4/icmp.c           |   14 +-
 net/ip/lwip_base/src/core/ipv4/igmp.c           |   75 +-
 net/ip/lwip_base/src/core/ipv4/ip4.c            |   57 +-
 net/ip/lwip_base/src/core/ipv4/ip4_addr.c       |   10 +-
 net/ip/lwip_base/src/core/ipv4/ip4_frag.c       |   88 +-
 net/ip/lwip_base/src/core/ipv6/ethip6.c         |   42 +-
 net/ip/lwip_base/src/core/ipv6/ip6.c            |   62 +-
 net/ip/lwip_base/src/core/ipv6/ip6_addr.c       |   10 +-
 net/ip/lwip_base/src/core/ipv6/ip6_frag.c       |   49 +-
 net/ip/lwip_base/src/core/ipv6/mld6.c           |    7 +-
 net/ip/lwip_base/src/core/ipv6/nd6.c            |  355 +++--
 net/ip/lwip_base/src/core/mem.c                 |    8 +-
 net/ip/lwip_base/src/core/memp.c                |   25 +-
 net/ip/lwip_base/src/core/netif.c               |  127 +-
 net/ip/lwip_base/src/core/pbuf.c                |   91 +-
 net/ip/lwip_base/src/core/raw.c                 |   51 +-
 net/ip/lwip_base/src/core/stats.c               |    6 +-
 net/ip/lwip_base/src/core/sys.c                 |   38 +
 net/ip/lwip_base/src/core/tcp.c                 |  149 +-
 net/ip/lwip_base/src/core/tcp_in.c              |   88 +-
 net/ip/lwip_base/src/core/tcp_out.c             |  195 ++-
 net/ip/lwip_base/src/core/timeouts.c            |    4 +-
 net/ip/lwip_base/src/core/udp.c                 |   72 +-
 net/ip/lwip_base/src/netif/ethernet.c           |   20 +-
 net/ip/lwip_base/src/netif/lowpan6.c            |  103 +-
 net/ip/lwip_base/src/netif/ppp/auth.c           |   10 +-
 net/ip/lwip_base/src/netif/ppp/ipcp.c           |  120 +-
 net/ip/lwip_base/src/netif/ppp/ipv6cp.c         |    4 +-
 net/ip/lwip_base/src/netif/ppp/multilink.c      |    4 +-
 net/ip/lwip_base/src/netif/ppp/ppp.c            |   19 +-
 net/ip/lwip_base/src/netif/ppp/pppapi.c         |    5 +
 net/ip/lwip_base/src/netif/ppp/pppoe.c          |   19 +-
 net/ip/lwip_base/src/netif/ppp/pppol2tp.c       |    9 +-
 net/ip/lwip_base/src/netif/ppp/pppos.c          |   40 +-
 net/ip/lwip_base/src/netif/ppp/utils.c          |    4 +-
 net/ip/lwip_base/src/netif/ppp/vj.c             |   62 +-
 net/ip/lwip_base/src/netif/slipif.c             |    2 +-
 net/ip/lwip_base/test/fuzz/Makefile             |   53 +
 net/ip/lwip_base/test/fuzz/README               |   34 +
 net/ip/lwip_base/test/fuzz/config.h             |    0
 net/ip/lwip_base/test/fuzz/fuzz.c               |  136 ++
 .../lwip_base/test/fuzz/inputs/arp/arp_req.bin  |  Bin 0 -> 42 bytes
 .../test/fuzz/inputs/icmp/icmp_ping.bin         |  Bin 0 -> 98 bytes
 .../fuzz/inputs/ipv6/neighbor_solicitation.bin  |  Bin 0 -> 86 bytes
 .../test/fuzz/inputs/ipv6/router_adv.bin        |  Bin 0 -> 118 bytes
 .../lwip_base/test/fuzz/inputs/tcp/tcp_syn.bin  |  Bin 0 -> 74 bytes
 .../test/fuzz/inputs/udp/udp_port_5000.bin      |  Bin 0 -> 50 bytes
 net/ip/lwip_base/test/fuzz/lwipopts.h           |   68 +
 net/ip/lwip_base/test/fuzz/output_to_pcap.sh    |   31 +
 net/ip/lwip_base/test/unit/core/test_mem.h      |    8 -
 net/ip/lwip_base/test/unit/core/test_pbuf.h     |    8 -
 net/ip/lwip_base/test/unit/dhcp/test_dhcp.c     |  113 +-
 net/ip/lwip_base/test/unit/dhcp/test_dhcp.h     |    8 -
 net/ip/lwip_base/test/unit/etharp/test_etharp.h |    8 -
 net/ip/lwip_base/test/unit/lwip_check.h         |    8 -
 net/ip/lwip_base/test/unit/lwipopts.h           |    8 -
 net/ip/lwip_base/test/unit/mdns/test_mdns.c     |   71 +-
 net/ip/lwip_base/test/unit/mdns/test_mdns.h     |    8 -
 net/ip/lwip_base/test/unit/tcp/tcp_helper.c     |   23 +-
 net/ip/lwip_base/test/unit/tcp/tcp_helper.h     |    8 -
 net/ip/lwip_base/test/unit/tcp/test_tcp.c       |   18 +-
 net/ip/lwip_base/test/unit/tcp/test_tcp.h       |    8 -
 net/ip/lwip_base/test/unit/tcp/test_tcp_oos.h   |    8 -
 net/ip/lwip_base/test/unit/udp/test_udp.h       |    8 -
 191 files changed, 6551 insertions(+), 2591 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/CHANGELOG
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/CHANGELOG b/net/ip/lwip_base/CHANGELOG
index 8f030fd..3a27719 100644
--- a/net/ip/lwip_base/CHANGELOG
+++ b/net/ip/lwip_base/CHANGELOG
@@ -4,6 +4,152 @@ HISTORY
 
   * [Enter new changes just after this line - do not remove this line]
 
+(STABLE-2.0.2)
+
+  ++ New features:
+
+  2017-02-10: Dirk Ziegelmeier
+  * Implement task #14367: Hooks need a better place to be defined:
+    We now have a #define for a header file name that is #included in every .c
+    file that provides hooks.
+
+  ++ Bugfixes:
+
+  2017-03-08
+  * tcp: do not keep sending SYNs when getting ACKs
+
+  2017-03-08: Joel Cunningham
+  * tcp: Initialize ssthresh to TCP_SND_BUF (bug #50476)
+
+  2017-03-01: Simon Goldschmidt
+  * httpd: LWIP_HTTPD_POST_MANUAL_WND: fixed double-free when httpd_post_data_recved
+    is called nested from httpd_post_receive_data() (bug #50424)
+
+  2017-02-28: David van Moolenbroek/Simon Goldschmidt
+  * tcp: fixed bug #50418: LWIP_EVENT_API: fix invalid calbacks for SYN_RCVD pcb
+
+  2017-02-17: Simon Goldschmidt
+  * dns: Improved DNS_LOCAL_HOSTLIST interface (bug #50325)
+
+  2017-02-16: Simon Goldschmidt
+  * LWIP_NETCONN_FULLDUPLEX: fixed shutdown during write (bug #50274)
+
+  2017-02-13: Simon Goldschmidt/Dirk Ziegelmeier
+  * For tiny targtes, LWIP_RAND is optional (fix compile time checks)
+
+  2017-02-10: Simon Goldschmidt
+  * tcp: Fixed bug #47485 (tcp_close() should not fail on memory error) by retrying
+    to send FIN from tcp_fasttmr
+
+  2017-02-09: Simon Goldschmidt
+  * sockets: Fixed bug #44032 (LWIP_NETCONN_FULLDUPLEX: select might work on
+    invalid/reused socket) by not allowing to reallocate a socket that has
+    "select_waiting != 0"
+
+  2017-02-09: Simon Goldschmidt
+  * httpd: Fixed bug #50059 (httpd LWIP_HTTPD_SUPPORT_11_KEEPALIVE vs.
+    LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED)
+
+  2017-02-08: Dirk Ziegelmeier
+  * Rename "IPv6 mapped IPv4 addresses" to their correct name from RFC4191:
+    "IPv4-mapped IPv6 address"
+
+  2017-02-08: Luc Revardel
+  * mld6.c: Fix bug #50220 (mld6_leavegroup does not send ICMP6_TYPE_MLD, even
+    if last reporter)
+
+  2017-02-08: David van Moolenbroek
+  * ip6.c: Patch #9250: fix source substitution in ip6_output_if()
+
+  2017-02-08: Simon Goldschmidt
+  * tcp_out.c: Fixed bug #50090 (last_unsent->oversize_left can become wrong value
+    in tcp_write error path)
+
+  2017-02-02: Dirk Ziegelmeier
+  * Fix bug #50206: UDP Netconn bind to IP6_ADDR_ANY fails
+
+  2017-01-18: Dirk Ziegelmeier
+  * Fix zero-copy RX, see bug bug #50064. PBUF_REFs were not supported as ARP requests.
+
+  2017-01-15: Axel Lin, Dirk Ziegelmeier
+  * minor bug fixes in mqtt
+
+  2017-01-11: Knut Andre Tidemann
+  * sockets/netconn: fix broken default ICMPv6 handling of checksums
+
+(STABLE-2.0.1)
+
+  ++ New features:
+
+  2016-12-31: Simon Goldschmidt
+  * tcp.h/.c: added function tcp_listen_with_backlog_and_err() to get the error
+    reason when listening fails (bug #49861)
+
+  2016-12-20: Erik Andersen
+  * Add MQTT client
+
+  2016-12-14: Jan Breuer:
+  * opt.h, ndc.h/.c: add support for RDNSS option (as per RFC 6106)
+
+  2016-12-14: David van Moolenbroek
+  * opt.h, nd6.c: Added LWIP_HOOK_ND6_GET_GW()
+
+  2016-12-09: Dirk Ziegelmeier
+  * ip6_frag.c: Implemented support for LWIP_NETIF_TX_SINGLE_PBUF
+
+  2016-12-09: Simon Goldschmidt
+  * dns.c: added one-shot multicast DNS queries
+
+  2016-11-24: Ambroz Bizjak, David van Moolenbroek
+  * tcp_out.c: Optimize passing contiguous nocopy buffers to tcp_write (bug #46290)
+
+  2016-11-16: Dirk Ziegelmeier
+  * sockets.c: added support for IPv6 mapped IPv4 addresses
+
+  ++ Bugfixes:
+
+  2016-12-16: Thomas Mueller
+  * api_lib.c: fixed race condition in return value of netconn_gethostbyname()
+    (and thus also lwip_gethostbyname/_r() and lwip_getaddrinfo())
+
+  2016-12-15: David van Moolenbroek
+  * opt.h, tcp: added LWIP_HOOK_TCP_ISN() to implement less predictable initial
+    sequence numbers (see contrib/addons/tcp_isn for an example implementation)
+
+  2016-12-05: Dirk Ziegelmeier
+  * fixed compiling with IPv4 disabled (IPv6 only case)
+
+  2016-11-28: Simon Goldschmidt
+  * api_lib.c: fixed bug #49725 (send-timeout: netconn_write() can return
+    ERR_OK without all bytes being written)
+
+  2016-11-28: Ambroz Bizjak
+  * tcpi_in.c: fixed bug #49717 (window size in received SYN and SYN-ACK
+    assumed scaled)
+
+  2016-11-25: Simon Goldschmidt
+  * dhcp.c: fixed bug #49676 (Possible endless loop when parsing dhcp options)
+
+  2016-11-23: Dirk Ziegelmeier
+  * udp.c: fixed bug #49662: multicast traffic is now only received on a UDP PCB
+   (and therefore on a UDP socket/netconn) when the PCB is bound to IP_ADDR_ANY
+
+  2016-11-16: Dirk Ziegelmeier
+  * *: Fixed dual-stack behaviour, IPv6 mapped IPv4 support in socket API
+
+  2016-11-14: Joel Cunningham
+  * tcp_out.c: fixed bug #49533 (start persist timer when unsent seg can't fit
+    in window) 
+
+  2016-11-16: Roberto Barbieri Carrera
+  * autoip.c: fixed bug #49610 (sometimes AutoIP fails to reuse the same address)
+
+  2016-11-11: Dirk Ziegelmeier
+  * sockets.c: fixed bug #49578 (dropping multicast membership does not work
+    with LWIP_SOCKET_OFFSET)
+
+(STABLE-2.0.0)
+
   ++ New features:
 
   2016-07-27: Simon Goldschmidt

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/UPGRADING
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/UPGRADING b/net/ip/lwip_base/UPGRADING
index 2190ec9..f48f591 100644
--- a/net/ip/lwip_base/UPGRADING
+++ b/net/ip/lwip_base/UPGRADING
@@ -8,7 +8,14 @@ with newer versions.
 
   * [Enter new changes just after this line - do not remove this line]
 
-  * TODO
+(2.0.1)
+
+  ++ Application changes:
+
+  * UDP does NOT receive multicast traffic from ALL netifs on an UDP PCB bound to a specific
+    netif any more. Users need to bind to IP_ADDR_ANY to receive multicast traffic and compare 
+    ip_current_netif() to the desired netif for every packet.
+    See bug #49662 for an explanation.
 
 (2.0.0)
 
@@ -46,6 +53,13 @@ with newer versions.
     * Added LWIP_NETCONN_SEM_PER_THREAD to use one "op_completed" semaphore per thread
       instead of using one per netconn (these semaphores are used even with core locking
       enabled as some longer lasting functions like big writes still need to delay)
+    * Added generalized abstraction for itoa(), strnicmp(), stricmp() and strnstr()
+      in def.h (to be overridden in cc.h) instead of config 
+      options for netbiosns, httpd, dns, etc. ...
+    * New abstraction for hton* and ntoh* functions in def.h.
+      To override them, use the following in cc.h: 
+      #define lwip_htons(x) <your_htons>
+      #define lwip_htonl(x) <your_htonl>
 
   +++ new options:
      * TODO

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/doc/NO_SYS_SampleCode.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/doc/NO_SYS_SampleCode.c b/net/ip/lwip_base/doc/NO_SYS_SampleCode.c
index f20106f..f5c6c10 100644
--- a/net/ip/lwip_base/doc/NO_SYS_SampleCode.c
+++ b/net/ip/lwip_base/doc/NO_SYS_SampleCode.c
@@ -46,12 +46,10 @@ static void netif_status_callback(struct netif *netif)
 static err_t netif_init(struct netif *netif)
 {
   netif->linkoutput = netif_output;
-  netif->output = etharp_output;
-  netif->name[0] = 'e';
-  netif->name[1] = '0';
-  netif->mtu = ETHERNET_MTU;
-
-  netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP;
+  netif->output     = etharp_output;
+  netif->output_ip6 = ethip6_output;
+  netif->mtu        = ETHERNET_MTU;
+  netif->flags      = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP | NETIF_FLAG_MLD6;
   MIB2_INIT_NETIF(netif, snmp_ifType_ethernet_csmacd, 100000000);
 
   SMEMCPY(netif->hwaddr, your_mac_address_goes_here, sizeof(netif->hwaddr));
@@ -66,7 +64,11 @@ void main(void)
 
   lwip_init();
 
-  netif_add(&netif, IPADDR_ANY, IPADDR_ANY, IPADDR_ANY, NULL, netif_init, netif_input);
+  netif_add(&netif, IP4_ADDR_ANY, IP4_ADDR_ANY, IP4_ADDR_ANY, NULL, netif_init, netif_input);
+  netif.name[0] = 'e';
+  netif.name[1] = '0';
+  netif_create_ip6_linklocal_address(&netif, 1);
+  netif.ip6_autoconfig_enabled = 1;
   netif_set_status_callback(&netif, netif_status_callback);
   netif_set_default(&netif);
   netif_set_up(&netif);

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/doc/doxygen/generate.sh
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/doc/doxygen/generate.sh b/net/ip/lwip_base/doc/doxygen/generate.sh
index 99afb12..89344b0 100755
--- a/net/ip/lwip_base/doc/doxygen/generate.sh
+++ b/net/ip/lwip_base/doc/doxygen/generate.sh
@@ -1 +1,3 @@
+#!/bin/sh
+
 doxygen lwip.Doxyfile

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/doc/doxygen/lwip.Doxyfile
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/doc/doxygen/lwip.Doxyfile b/net/ip/lwip_base/doc/doxygen/lwip.Doxyfile
index c86326b..0e3349a 100644
--- a/net/ip/lwip_base/doc/doxygen/lwip.Doxyfile
+++ b/net/ip/lwip_base/doc/doxygen/lwip.Doxyfile
@@ -32,19 +32,19 @@ DOXYFILE_ENCODING      = UTF-8
 # title of most generated pages and in a few other places.
 # The default value is: My Project.
 
-PROJECT_NAME           = "lwIP 2.0.0"
+PROJECT_NAME           = "lwIP"
 
 # The PROJECT_NUMBER tag can be used to enter a project or revision number. This
 # could be handy for archiving the generated documentation or if some version
 # control system is used.
 
-PROJECT_NUMBER         = "lwIP 2.0.0"
+PROJECT_NUMBER         = "2.0.2"
 
 # Using the PROJECT_BRIEF tag one can provide an optional one line description
 # for a project that appears at the top of each page and should give viewer a
 # quick idea about the purpose of the project. Keep the description short.
 
-PROJECT_BRIEF          = Lightweight IP stack
+PROJECT_BRIEF          = "Lightweight IP stack"
 
 # With the PROJECT_LOGO tag one can specify a logo or an icon that is included
 # in the documentation. The maximum height of the logo should not exceed 55
@@ -2071,6 +2071,7 @@ INCLUDE_FILE_PATTERNS  = *.h
 PREDEFINED             = __DOXYGEN__=1 \
                          NO_SYS=0 \
                          SYS_LIGHTWEIGHT_PROT=1 \
+                         LWIP_TCPIP_CORE_LOCKING=1 \
                          LWIP_IPV4=1 \
                          LWIP_IPV6=1 \
                          LWIP_ICMP=1 \

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/doc/doxygen/main_page.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/doc/doxygen/main_page.h b/net/ip/lwip_base/doc/doxygen/main_page.h
index 6486a17..d35d16e 100644
--- a/net/ip/lwip_base/doc/doxygen/main_page.h
+++ b/net/ip/lwip_base/doc/doxygen/main_page.h
@@ -1,4 +1,4 @@
-/**
+\ufeff/**
  * @defgroup lwip lwIP
  *
  * @defgroup infrastructure Infrastructure
@@ -7,8 +7,8 @@
  * Non thread-safe APIs, callback style for maximum performance and minimum
  * memory footprint.
  * 
- * @defgroup threadsafe_api Thread-safe APIs
- * Thread-safe APIs, blocking functions. More overhead, but can be called
+ * @defgroup sequential_api Sequential-style APIs
+ * Sequential-style APIs, blocking functions. More overhead, but can be called
  * from any thread except TCPIP thread.
  * 
  * @defgroup addons Addons
@@ -27,11 +27,73 @@
  */
 
 /**
+ * @page changelog Changelog
+ * @verbinclude "CHANGELOG"
+ */
+
+/**
  * @page contrib How to contribute to lwIP
  * @verbinclude "contrib.txt"
  */
 
 /**
+ * @page pitfalls Common pitfalls
+ *
+ * Multiple Execution Contexts in lwIP code
+ * ========================================
+ *
+ * The most common source of lwIP problems is to have multiple execution contexts
+ * inside the lwIP code.
+ * 
+ * lwIP can be used in two basic modes: @ref lwip_nosys (no OS/RTOS 
+ * running on target system) or @ref lwip_os (there is an OS running
+ * on the target system).
+ *
+ * Mainloop Mode
+ * -------------
+ * In mainloop mode, only @ref callbackstyle_api can be used.
+ * The user has two possibilities to ensure there is only one 
+ * exection context at a time in lwIP:
+ *
+ * 1) Deliver RX ethernet packets directly in interrupt context to lwIP
+ *    by calling netif->input directly in interrupt. This implies all lwIP 
+ *    callback functions are called in IRQ context, which may cause further
+ *    problems in application code: IRQ is blocked for a long time, multiple
+ *    execution contexts in application code etc. When the application wants
+ *    to call lwIP, it only needs to disable interrupts during the call.
+ *    If timers are involved, even more locking code is needed to lock out
+ *    timer IRQ and ethernet IRQ from each other, assuming these may be nested.
+ *
+ * 2) Run lwIP in a mainloop. There is example code here: @ref lwip_nosys.
+ *    lwIP is _ONLY_ called from mainloop callstacks here. The ethernet IRQ
+ *    has to put received telegrams into a queue which is polled in the
+ *    mainloop. Ensure lwIP is _NEVER_ called from an interrupt, e.g.
+ *    some SPI IRQ wants to forward data to udp_send() or tcp_write()!
+ *
+ * OS Mode
+ * -------
+ * In OS mode, @ref callbackstyle_api AND @ref sequential_api can be used.
+ * @ref sequential_api are designed to be called from threads other than
+ * the TCPIP thread, so there is nothing to consider here.
+ * But @ref callbackstyle_api functions must _ONLY_ be called from
+ * TCPIP thread. It is a common error to call these from other threads
+ * or from IRQ contexts. \u200bEthernet RX needs to deliver incoming packets
+ * in the correct way by sending a message to TCPIP thread, this is
+ * implemented in tcpip_input().\u200b\u200b
+ * Again, ensure lwIP is _NEVER_ called from an interrupt, e.g.
+ * some SPI IRQ wants to forward data to udp_send() or tcp_write()!
+ * 
+ * 1) tcpip_callback() can be used get called back from TCPIP thread,
+ *    it is safe to call any @ref callbackstyle_api from there.
+ *
+ * 2) Use @ref LWIP_TCPIP_CORE_LOCKING. All @ref callbackstyle_api
+ *    functions can be called when lwIP core lock is aquired, see
+ *    @ref LOCK_TCPIP_CORE() and @ref UNLOCK_TCPIP_CORE().
+ *    These macros cannot be used in an interrupt context!
+ *    Note the OS must correctly handle priority inversion for this.
+ */
+
+/**
  * @page bugs Reporting bugs
  * Please report bugs in the lwIP bug tracker at savannah.\n
  * BEFORE submitting, please check if the bug has already been reported!\n
@@ -46,10 +108,11 @@
  * *not* *from* *interrupt* *context*. You can allocate a @ref pbuf in interrupt
  * context and put them into a queue which is processed from mainloop.\n
  * Call sys_check_timeouts() periodically in the mainloop.\n
- * Porting: implement all functions in @ref sys_time and @ref sys_prot.\n
+ * Porting: implement all functions in @ref sys_time, @ref sys_prot and 
+ * @ref compiler_abstraction.\n
  * You can only use @ref callbackstyle_api in this mode.\n
  * Sample code:\n
- * @verbinclude NO_SYS_SampleCode.c
+ * @include NO_SYS_SampleCode.c
  */
 
 /**
@@ -60,7 +123,7 @@
  * to use @ref LWIP_TCPIP_CORE_LOCKING.\n
  * Porting: implement all functions in @ref sys_layer.\n
  * You can use @ref callbackstyle_api together with @ref tcpip_callback,
- * and all @ref threadsafe_api.
+ * and all @ref sequential_api.
  */
 
 /**

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/doc/mqtt_client.txt
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/doc/mqtt_client.txt b/net/ip/lwip_base/doc/mqtt_client.txt
new file mode 100644
index 0000000..3e67def
--- /dev/null
+++ b/net/ip/lwip_base/doc/mqtt_client.txt
@@ -0,0 +1,162 @@
+MQTT client for lwIP
+
+Author: Erik Andersson
+
+Details of the MQTT protocol can be found at:
+http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html 
+
+-----------------------------------------------------------------
+1. Initial steps, reserve memory and make connection to server:
+
+1.1: Provide storage
+
+Static allocation:
+  mqtt_client_t static_client;
+  example_do_connect(&static_client);
+
+Dynamic allocation:
+  mqtt_client_t *client = mqtt_client_new();
+  if(client != NULL) {
+    example_do_connect(&client);
+  }
+  
+1.2: Establish Connection with server
+
+void example_do_connect(mqtt_client_t *client)
+{
+  struct mqtt_connect_client_info_t ci;
+  err_t err;
+  
+  /* Setup an empty client info structure */
+  memset(&ci, 0, sizeof(ci));
+  
+  /* Minimal amount of information required is client identifier, so set it here */ 
+  ci.client_id = "lwip_test";
+  
+  /* Initiate client and connect to server, if this fails immediately an error code is returned
+     otherwise mqtt_connection_cb will be called with connection result after attempting 
+     to establish a connection with the server. 
+     For now MQTT version 3.1.1 is always used */
+  
+  err = mqtt_client_connect(client, ip_addr, MQTT_PORT, mqtt_connection_cb, 0, &ci);
+  
+  /* For now just print the result code if something goes wrong
+  if(err != ERR_OK) {
+    printf("mqtt_connect return %d\n", err);
+  }
+}
+
+Connection to server can also be probed by calling mqtt_client_is_connected(client) 
+
+-----------------------------------------------------------------
+2. Implementing the connection status callback
+
+
+static void mqtt_connection_cb(mqtt_client_t *client, void *arg, mqtt_connection_status_t status)
+{
+  err_t err;
+  if(status == MQTT_CONNECT_ACCEPTED) {
+    printf("mqtt_connection_cb: Successfully connected\n");
+    
+    /* Setup callback for incoming publish requests */
+    mqtt_set_inpub_callback(client, mqtt_incoming_publish_cb, mqtt_incoming_data_cb, arg);
+    
+    /* Subscribe to a topic named "subtopic" with QoS level 1, call mqtt_sub_request_cb with result */ 
+    err = mqtt_subscribe(client, "subtopic", 1, mqtt_sub_request_cb, arg);
+
+    if(err != ERR_OK) {
+      printf("mqtt_subscribe return: %d\n", err);
+    }
+  } else {
+    printf("mqtt_connection_cb: Disconnected, reason: %d\n", status);
+    
+    /* Its more nice to be connected, so try to reconnect */
+    example_do_connect(client);
+  }  
+}
+
+static void mqtt_sub_request_cb(void *arg, err_t result)
+{
+  /* Just print the result code here for simplicity, 
+     normal behaviour would be to take some action if subscribe fails like 
+     notifying user, retry subscribe or disconnect from server */
+  printf("Subscribe result: %d\n", result);
+}
+
+-----------------------------------------------------------------
+3. Implementing callbacks for incoming publish and data
+
+/* The idea is to demultiplex topic and create some reference to be used in data callbacks
+   Example here uses a global variable, better would be to use a member in arg
+   If RAM and CPU budget allows it, the easiest implementation might be to just take a copy of
+   the topic string and use it in mqtt_incoming_data_cb
+*/
+static int inpub_id;
+static void mqtt_incoming_publish_cb(void *arg, const char *topic, u32_t tot_len)
+{
+  printf("Incoming publish at topic %s with total length %u\n", topic, (unsigned int)tot_len);
+
+  /* Decode topic string into a user defined reference */
+  if(strcmp(topic, "print_payload") == 0) {
+    inpub_id = 0;
+  } else if(topic[0] == 'A') {
+    /* All topics starting with 'A' might be handled at the same way */
+    inpub_id = 1;
+  } else {
+    /* For all other topics */
+    inpub_id = 2;
+  }
+}
+
+static void mqtt_incoming_data_cb(void *arg, const u8_t *data, u16_t len, u8_t flags)
+{
+  printf("Incoming publish payload with length %d, flags %u\n", len, (unsigned int)flags);
+
+  if(flags & MQTT_DATA_FLAG_LAST) {
+    /* Last fragment of payload received (or whole part if payload fits receive buffer
+       See MQTT_VAR_HEADER_BUFFER_LEN)  */
+
+    /* Call function or do action depending on reference, in this case inpub_id */
+    if(inpub_id == 0) {
+      /* Don't trust the publisher, check zero termination */
+      if(data[len-1] == 0) {
+        printf("mqtt_incoming_data_cb: %s\n", (const char *)data);
+      }
+    } else if(inpub_id == 1) {
+      /* Call an 'A' function... */
+    } else {
+      printf("mqtt_incoming_data_cb: Ignoring payload...\n");
+    }
+  } else {
+    /* Handle fragmented payload, store in buffer, write to file or whatever */
+  }
+}
+
+-----------------------------------------------------------------
+4. Using outgoing publish
+
+
+void example_publish(mqtt_client_t *client, void *arg)
+{
+  const char *pub_payload= "PubSubHubLubJub";
+  err_t err;
+  u8_t qos = 2; /* 0 1 or 2, see MQTT specification */
+  u8_t retain = 0; /* No don't retain such crappy payload... */
+  err = mqtt_publish(client, "pub_topic", pub_payload, strlen(pub_payload), qos, retain, mqtt_pub_request_cb, arg);
+  if(err != ERR_OK) {
+    printf("Publish err: %d\n", err);
+  }
+}
+
+/* Called when publish is complete either with sucess or failure */
+static void mqtt_pub_request_cb(void *arg, err_t result)
+{
+  if(result != ERR_OK) {
+    printf("Publish result: %d\n", result);
+  }
+}
+
+-----------------------------------------------------------------
+5. Disconnecting
+
+Simply call mqtt_disconnect(client)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/doc/ppp.txt
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/doc/ppp.txt b/net/ip/lwip_base/doc/ppp.txt
index e40c012..8b88b3a 100644
--- a/net/ip/lwip_base/doc/ppp.txt
+++ b/net/ip/lwip_base/doc/ppp.txt
@@ -79,7 +79,7 @@ static void status_cb(ppp_pcb *pcb, int err_code, void *ctx) {
   switch(err_code) {
     case PPPERR_NONE: {
 #if LWIP_DNS
-      ip_addr_t ns;
+      const ip_addr_t *ns;
 #endif /* LWIP_DNS */
       printf("status_cb: Connected\n");
 #if PPP_IPV4_SUPPORT
@@ -88,9 +88,9 @@ static void status_cb(ppp_pcb *pcb, int err_code, void *ctx) {
       printf("   netmask     = %s\n", ipaddr_ntoa(&pppif->netmask));
 #if LWIP_DNS
       ns = dns_getserver(0);
-      printf("   dns1        = %s\n", ipaddr_ntoa(&ns));
+      printf("   dns1        = %s\n", ipaddr_ntoa(ns));
       ns = dns_getserver(1);
-      printf("   dns2        = %s\n", ipaddr_ntoa(&ns));
+      printf("   dns2        = %s\n", ipaddr_ntoa(ns));
 #endif /* LWIP_DNS */
 #endif /* PPP_IPV4_SUPPORT */
 #if PPP_IPV6_SUPPORT

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/doc/rawapi.txt
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/doc/rawapi.txt b/net/ip/lwip_base/doc/rawapi.txt
index 763a0ef..0cdfdce 100644
--- a/net/ip/lwip_base/doc/rawapi.txt
+++ b/net/ip/lwip_base/doc/rawapi.txt
@@ -456,9 +456,11 @@ introduction to this subject.
 Other significant improvements can be made by supplying
 assembly or inline replacements for htons() and htonl()
 if you're using a little-endian architecture.
-#define LWIP_PLATFORM_BYTESWAP 1
-#define LWIP_PLATFORM_HTONS(x) <your_htons>
-#define LWIP_PLATFORM_HTONL(x) <your_htonl>
+#define lwip_htons(x) <your_htons>
+#define lwip_htonl(x) <your_htonl>
+If you #define them to htons() and htonl(), you should
+#define LWIP_DONT_PROVIDE_BYTEORDER_FUNCTIONS to prevent lwIP from
+defining hton*/ntoh* compatibility macros.
 
 Check your network interface driver if it reads at
 a higher speed than the maximum wire-speed. If the

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/doc/sys_arch.txt
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/doc/sys_arch.txt b/net/ip/lwip_base/doc/sys_arch.txt
index 333946d..4dc727b 100644
--- a/net/ip/lwip_base/doc/sys_arch.txt
+++ b/net/ip/lwip_base/doc/sys_arch.txt
@@ -29,7 +29,7 @@ in a mailbox is just a pointer, nothing more.
 
 Semaphores are represented by the type "sys_sem_t" which is typedef'd
 in the sys_arch.h file. Mailboxes are equivalently represented by the
-type "sys_mbox_t". Mutexes are represented ny the type "sys_mutex_t".
+type "sys_mbox_t". Mutexes are represented by the type "sys_mutex_t".
 lwIP does not place any restrictions on how these types are represented
 internally.
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/api.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/api.h b/net/ip/lwip_base/include/lwip/api.h
index b821841..516bd16 100644
--- a/net/ip/lwip_base/include/lwip/api.h
+++ b/net/ip/lwip_base/include/lwip/api.h
@@ -43,8 +43,7 @@
 /* Note: Netconn API is always available when sockets are enabled -
  * sockets are implemented on top of them */
 
-#include <stddef.h> /* for size_t */
-
+#include "lwip/arch.h"
 #include "lwip/netbuf.h"
 #include "lwip/sys.h"
 #include "lwip/ip_addr.h"
@@ -90,6 +89,7 @@ extern "C" {
 #define NETCONNTYPE_ISUDPLITE(t)     (((t)&0xF3) == NETCONN_UDPLITE)
 #define NETCONNTYPE_ISUDPNOCHKSUM(t) (((t)&0xF3) == NETCONN_UDPNOCHKSUM)
 #else /* LWIP_IPV6 */
+#define NETCONNTYPE_ISIPV6(t)        (0)
 #define NETCONNTYPE_ISUDPLITE(t)     ((t) == NETCONN_UDPLITE)
 #define NETCONNTYPE_ISUDPNOCHKSUM(t) ((t) == NETCONN_UDPNOCHKSUM)
 #endif /* LWIP_IPV6 */
@@ -139,7 +139,32 @@ enum netconn_state {
   NETCONN_CLOSE
 };
 
-/** Use to inform the callback function about changes */
+/** Used to inform the callback function about changes
+ * 
+ * Event explanation:
+ * 
+ * In the netconn implementation, there are three ways to block a client:
+ * 
+ * - accept mbox (sys_arch_mbox_fetch(&conn->acceptmbox, &accept_ptr, 0); in netconn_accept())
+ * - receive mbox (sys_arch_mbox_fetch(&conn->recvmbox, &buf, 0); in netconn_recv_data())
+ * - send queue is full (sys_arch_sem_wait(LWIP_API_MSG_SEM(msg), 0); in lwip_netconn_do_write())
+ * 
+ * The events have to be seen as events signaling the state of these mboxes/semaphores. For non-blocking
+ * connections, you need to know in advance whether a call to a netconn function call would block or not,
+ * and these events tell you about that.
+ * 
+ * RCVPLUS events say: Safe to perform a potentially blocking call call once more. 
+ * They are counted in sockets - three RCVPLUS events for accept mbox means you are safe
+ * to call netconn_accept 3 times without being blocked.
+ * Same thing for receive mbox.
+ * 
+ * RCVMINUS events say: Your call to to a possibly blocking function is "acknowledged".
+ * Socket implementation decrements the counter.
+ * 
+ * For TX, there is no need to count, its merely a flag. SENDPLUS means you may send something.
+ * SENDPLUS occurs when enough data was delivered to peer so netconn_send() can be called again.
+ * A SENDMINUS event occurs when the next call to a netconn_send() would be blocking.
+ */
 enum netconn_evt {
   NETCONN_EVT_RCVPLUS,
   NETCONN_EVT_RCVMINUS,

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/apps/httpd_opts.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/apps/httpd_opts.h b/net/ip/lwip_base/include/lwip/apps/httpd_opts.h
index 424d3d2..340db15 100644
--- a/net/ip/lwip_base/include/lwip/apps/httpd_opts.h
+++ b/net/ip/lwip_base/include/lwip/apps/httpd_opts.h
@@ -43,10 +43,6 @@
 
 #include "lwip/opt.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /**
  * @defgroup httpd_opts Options
  * @ingroup httpd
@@ -165,28 +161,6 @@ extern "C" {
 #define HTTPD_DEBUG_TIMING                  LWIP_DBG_OFF
 #endif
 
-/** Set this to 1 on platforms where strnstr is not available */
-#if !defined LWIP_HTTPD_STRNSTR_PRIVATE || defined __DOXYGEN__
-#define LWIP_HTTPD_STRNSTR_PRIVATE          1
-#endif
-
-/** Set this to 1 on platforms where stricmp is not available */
-#if !defined LWIP_HTTPD_STRICMP_PRIVATE || defined __DOXYGEN__
-#define LWIP_HTTPD_STRICMP_PRIVATE          0
-#endif
-
-/** Define this to a smaller function if you have itoa() at hand... */
-#if !defined LWIP_HTTPD_ITOA || defined __DOXYGEN__
-#if !defined LWIP_HTTPD_ITOA_PRIVATE || defined __DOXYGEN__
-#define LWIP_HTTPD_ITOA_PRIVATE             1
-#endif
-#if LWIP_HTTPD_ITOA_PRIVATE
-#define LWIP_HTTPD_ITOA(buffer, bufsize, number) httpd_itoa(number, buffer)
-#else
-#define LWIP_HTTPD_ITOA(buffer, bufsize, number) snprintf(buffer, bufsize, "%d", number)
-#endif
-#endif
-
 /** Set this to one to show error pages when parsing a request fails instead
     of simply closing the connection. */
 #if !defined LWIP_HTTPD_SUPPORT_EXTSTATUS || defined __DOXYGEN__
@@ -346,8 +320,4 @@ extern "C" {
  * @}
  */
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_HDR_APPS_HTTPD_OPTS_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/apps/mdns.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/apps/mdns.h b/net/ip/lwip_base/include/lwip/apps/mdns.h
index 1d4e3c8..d036816 100644
--- a/net/ip/lwip_base/include/lwip/apps/mdns.h
+++ b/net/ip/lwip_base/include/lwip/apps/mdns.h
@@ -31,7 +31,7 @@
  *
  * This file is part of the lwIP TCP/IP stack.
  *
- * Author: Erik Ekman <er...@verisure.com>
+ * Author: Erik Ekman <er...@kryo.se>
  *
  */
 #ifndef LWIP_HDR_MDNS_H
@@ -40,10 +40,6 @@
 #include "lwip/apps/mdns_opts.h"
 #include "lwip/netif.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #if LWIP_MDNS_RESPONDER
 
 enum mdns_sd_proto {
@@ -70,8 +66,4 @@ void mdns_resp_netif_settings_changed(struct netif *netif);
 
 #endif /* LWIP_MDNS_RESPONDER */
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_HDR_MDNS_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/apps/mdns_opts.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/apps/mdns_opts.h b/net/ip/lwip_base/include/lwip/apps/mdns_opts.h
index d55ecff..bf186bc 100644
--- a/net/ip/lwip_base/include/lwip/apps/mdns_opts.h
+++ b/net/ip/lwip_base/include/lwip/apps/mdns_opts.h
@@ -31,7 +31,7 @@
  *
  * This file is part of the lwIP TCP/IP stack.
  *
- * Author: Erik Ekman <er...@verisure.com>
+ * Author: Erik Ekman <er...@kryo.se>
  *
  */
 
@@ -40,10 +40,6 @@
 
 #include "lwip/opt.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /**
  * @defgroup mdns_opts Options
  * @ingroup mdns
@@ -74,9 +70,5 @@ extern "C" {
  * @}
  */
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_HDR_APPS_MDNS_OPTS_H */
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/apps/mdns_priv.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/apps/mdns_priv.h b/net/ip/lwip_base/include/lwip/apps/mdns_priv.h
index 6dc7884..8ee6db8 100644
--- a/net/ip/lwip_base/include/lwip/apps/mdns_priv.h
+++ b/net/ip/lwip_base/include/lwip/apps/mdns_priv.h
@@ -31,7 +31,7 @@
  *
  * This file is part of the lwIP TCP/IP stack.
  *
- * Author: Erik Ekman <er...@verisure.com>
+ * Author: Erik Ekman <er...@kryo.se>
  *
  */
 #ifndef LWIP_HDR_MDNS_PRIV_H
@@ -40,10 +40,6 @@
 #include "lwip/apps/mdns_opts.h"
 #include "lwip/pbuf.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #if LWIP_MDNS_RESPONDER
 
 /* Domain struct and methods - visible for unit tests */
@@ -67,8 +63,4 @@ u16_t mdns_compress_domain(struct pbuf *pbuf, u16_t *offset, struct mdns_domain
 
 #endif /* LWIP_MDNS_RESPONDER */
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_HDR_MDNS_PRIV_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/apps/mqtt.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/apps/mqtt.h b/net/ip/lwip_base/include/lwip/apps/mqtt.h
new file mode 100644
index 0000000..34b230b
--- /dev/null
+++ b/net/ip/lwip_base/include/lwip/apps/mqtt.h
@@ -0,0 +1,244 @@
+/**
+ * @file
+ * MQTT client
+ */
+
+/*
+ * Copyright (c) 2016 Erik Andersson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ * 2. 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.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ *
+ * This file is part of the lwIP TCP/IP stack.
+ *
+ * Author: Erik Andersson
+ *
+ */
+#ifndef LWIP_HDR_APPS_MQTT_CLIENT_H
+#define LWIP_HDR_APPS_MQTT_CLIENT_H
+
+#include "lwip/apps/mqtt_opts.h"
+#include "lwip/err.h"
+#include "lwip/ip_addr.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct mqtt_client_t mqtt_client_t;
+
+/** @ingroup mqtt
+ * Default MQTT port */
+#define MQTT_PORT 1883
+
+/*---------------------------------------------------------------------------------------------- */
+/* Connection with server */
+
+/**
+ * @ingroup mqtt
+ * Client information and connection parameters */
+struct mqtt_connect_client_info_t {
+  /** Client identifier, must be set by caller */
+  const char *client_id;
+  /** User name and password, set to NULL if not used */
+  const char* client_user;
+  const char* client_pass;
+  /** keep alive time in seconds, 0 to disable keep alive functionality*/
+  u16_t keep_alive;
+  /** will topic, set to NULL if will is not to be used,
+      will_msg, will_qos and will retain are then ignored */
+  const char* will_topic;
+  const char* will_msg;
+  u8_t will_qos;
+  u8_t will_retain;
+};
+
+/**
+ * @ingroup mqtt
+ * Connection status codes */
+typedef enum
+{
+  MQTT_CONNECT_ACCEPTED                 = 0,
+  MQTT_CONNECT_REFUSED_PROTOCOL_VERSION = 1,
+  MQTT_CONNECT_REFUSED_IDENTIFIER       = 2,
+  MQTT_CONNECT_REFUSED_SERVER           = 3,
+  MQTT_CONNECT_REFUSED_USERNAME_PASS    = 4,
+  MQTT_CONNECT_REFUSED_NOT_AUTHORIZED_  = 5,
+  MQTT_CONNECT_DISCONNECTED             = 256,
+  MQTT_CONNECT_TIMEOUT                  = 257
+} mqtt_connection_status_t;
+
+/**
+ * @ingroup mqtt
+ * Function prototype for mqtt connection status callback. Called when
+ * client has connected to the server after initiating a mqtt connection attempt by
+ * calling mqtt_connect() or when connection is closed by server or an error
+ *
+ * @param client MQTT client itself
+ * @param arg Additional argument to pass to the callback function
+ * @param status Connect result code or disconnection notification @see mqtt_connection_status_t
+ *
+ */
+typedef void (*mqtt_connection_cb_t)(mqtt_client_t *client, void *arg, mqtt_connection_status_t status);
+
+
+/**
+ * @ingroup mqtt
+ * Data callback flags */
+enum {
+  /** Flag set when last fragment of data arrives in data callback */
+  MQTT_DATA_FLAG_LAST = 1
+};
+
+/** 
+ * @ingroup mqtt
+ * Function prototype for MQTT incoming publish data callback function. Called when data
+ * arrives to a subscribed topic @see mqtt_subscribe
+ *
+ * @param arg Additional argument to pass to the callback function
+ * @param data User data, pointed object, data may not be referenced after callback return,
+          NULL is passed when all publish data are delivered
+ * @param len Length of publish data fragment
+ * @param flags MQTT_DATA_FLAG_LAST set when this call contains the last part of data from publish message
+ *
+ */
+typedef void (*mqtt_incoming_data_cb_t)(void *arg, const u8_t *data, u16_t len, u8_t flags);
+
+
+/** 
+ * @ingroup mqtt
+ * Function prototype for MQTT incoming publish function. Called when an incoming publish
+ * arrives to a subscribed topic @see mqtt_subscribe
+ *
+ * @param arg Additional argument to pass to the callback function
+ * @param topic Zero terminated Topic text string, topic may not be referenced after callback return
+ * @param tot_len Total length of publish data, if set to 0 (no publish payload) data callback will not be invoked
+ */
+typedef void (*mqtt_incoming_publish_cb_t)(void *arg, const char *topic, u32_t tot_len);
+
+
+/**
+ * @ingroup mqtt
+ * Function prototype for mqtt request callback. Called when a subscribe, unsubscribe
+ * or publish request has completed
+ * @param arg Pointer to user data supplied when invoking request
+ * @param err ERR_OK on success
+ *            ERR_TIMEOUT if no response was received within timeout,
+ *            ERR_ABRT if (un)subscribe was denied
+ */
+typedef void (*mqtt_request_cb_t)(void *arg, err_t err);
+
+
+/**
+ * Pending request item, binds application callback to pending server requests
+ */
+struct mqtt_request_t
+{
+  /** Next item in list, NULL means this is the last in chain,
+      next pointing at itself means request is unallocated */
+  struct mqtt_request_t *next;
+  /** Callback to upper layer */
+  mqtt_request_cb_t cb;
+  void *arg;
+  /** MQTT packet identifier */
+  u16_t pkt_id;
+  /** Expire time relative to element before this  */
+  u16_t timeout_diff;
+};
+
+/** Ring buffer */
+struct mqtt_ringbuf_t {
+  u16_t put;
+  u16_t get;
+  u8_t buf[MQTT_OUTPUT_RINGBUF_SIZE];
+};
+
+/** MQTT client */
+struct mqtt_client_t
+{
+  /** Timers and timeouts */
+  u16_t cyclic_tick;
+  u16_t keep_alive;
+  u16_t server_watchdog;
+  /** Packet identifier generator*/
+  u16_t pkt_id_seq;
+  /** Packet identifier of pending incoming publish */
+  u16_t inpub_pkt_id;
+  /** Connection state */
+  u8_t conn_state;
+  struct tcp_pcb *conn;
+  /** Connection callback */
+  void *connect_arg;
+  mqtt_connection_cb_t connect_cb;
+  /** Pending requests to server */
+  struct mqtt_request_t *pend_req_queue;
+  struct mqtt_request_t req_list[MQTT_REQ_MAX_IN_FLIGHT];
+  void *inpub_arg;
+  /** Incoming data callback */
+  mqtt_incoming_data_cb_t data_cb;
+  mqtt_incoming_publish_cb_t pub_cb;
+  /** Input */
+  u32_t msg_idx;
+  u8_t rx_buffer[MQTT_VAR_HEADER_BUFFER_LEN];
+  /** Output ring-buffer */
+  struct mqtt_ringbuf_t output;
+};
+
+
+/** Connect to server */
+err_t mqtt_client_connect(mqtt_client_t *client, const ip_addr_t *ipaddr, u16_t port, mqtt_connection_cb_t cb, void *arg,
+                   const struct mqtt_connect_client_info_t *client_info);
+
+/** Disconnect from server */
+void mqtt_disconnect(mqtt_client_t *client);
+
+/** Create new client */
+mqtt_client_t *mqtt_client_new(void);
+
+/** Check connection status */
+u8_t mqtt_client_is_connected(mqtt_client_t *client);
+
+/** Set callback to call for incoming publish */
+void mqtt_set_inpub_callback(mqtt_client_t *client, mqtt_incoming_publish_cb_t,
+                             mqtt_incoming_data_cb_t data_cb, void *arg);
+
+/** Common function for subscribe and unsubscribe */
+err_t mqtt_sub_unsub(mqtt_client_t *client, const char *topic, u8_t qos, mqtt_request_cb_t cb, void *arg, u8_t sub);
+
+/** @ingroup mqtt
+ *Subscribe to topic */
+#define mqtt_subscribe(client, topic, qos, cb, arg) mqtt_sub_unsub(client, topic, qos, cb, arg, 1)
+/** @ingroup mqtt
+ *  Unsubscribe to topic */
+#define mqtt_unsubscribe(client, topic, cb, arg) mqtt_sub_unsub(client, topic, 0, cb, arg, 0)
+
+
+/** Publish data to topic */
+err_t mqtt_publish(mqtt_client_t *client, const char *topic, const void *payload, u16_t payload_length, u8_t qos, u8_t retain,
+                                    mqtt_request_cb_t cb, void *arg);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LWIP_HDR_APPS_MQTT_CLIENT_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/apps/mqtt_opts.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/apps/mqtt_opts.h b/net/ip/lwip_base/include/lwip/apps/mqtt_opts.h
new file mode 100644
index 0000000..ffefacd
--- /dev/null
+++ b/net/ip/lwip_base/include/lwip/apps/mqtt_opts.h
@@ -0,0 +1,103 @@
+/**
+ * @file
+ * MQTT client options
+ */
+
+/*
+ * Copyright (c) 2016 Erik Andersson
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ * 2. 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.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ *
+ * This file is part of the lwIP TCP/IP stack.
+ *
+ * Author: Erik Andersson
+ *
+ */
+#ifndef LWIP_HDR_APPS_MQTT_OPTS_H
+#define LWIP_HDR_APPS_MQTT_OPTS_H
+
+#include "lwip/opt.h"
+
+#ifdef	__cplusplus
+extern "C" {
+#endif
+
+/**
+ * @defgroup mqtt_opts Options
+ * @ingroup mqtt
+ * @{
+ */
+
+/**
+ * Output ring-buffer size, must be able to fit largest outgoing publish message topic+payloads
+ */
+#ifndef MQTT_OUTPUT_RINGBUF_SIZE
+#define MQTT_OUTPUT_RINGBUF_SIZE 256
+#endif
+
+/**
+ * Number of bytes in receive buffer, must be at least the size of the longest incoming topic + 8
+ * If one wants to avoid fragmented incoming publish, set length to max incoming topic length + max payload length + 8
+ */
+#ifndef MQTT_VAR_HEADER_BUFFER_LEN
+#define MQTT_VAR_HEADER_BUFFER_LEN 128
+#endif
+
+/**
+ * Maximum number of pending subscribe, unsubscribe and publish requests to server .
+ */
+#ifndef MQTT_REQ_MAX_IN_FLIGHT
+#define MQTT_REQ_MAX_IN_FLIGHT 4
+#endif
+
+/**
+ * Seconds between each cyclic timer call.
+ */
+#ifndef MQTT_CYCLIC_TIMER_INTERVAL
+#define MQTT_CYCLIC_TIMER_INTERVAL 5
+#endif
+
+/**
+ * Publish, subscribe and unsubscribe request timeout in seconds.
+ */
+#ifndef MQTT_REQ_TIMEOUT
+#define MQTT_REQ_TIMEOUT 30
+#endif
+
+/**
+ * Seconds for MQTT connect response timeout after sending connect request
+ */
+#ifndef MQTT_CONNECT_TIMOUT
+#define MQTT_CONNECT_TIMOUT 100
+#endif
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LWIP_HDR_APPS_MQTT_OPTS_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/apps/netbiosns.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/apps/netbiosns.h b/net/ip/lwip_base/include/lwip/apps/netbiosns.h
index a326d33..c9f68d8 100644
--- a/net/ip/lwip_base/include/lwip/apps/netbiosns.h
+++ b/net/ip/lwip_base/include/lwip/apps/netbiosns.h
@@ -34,18 +34,10 @@
 
 #include "lwip/apps/netbiosns_opts.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 void netbiosns_init(void);
 #ifndef NETBIOS_LWIP_NAME
 void netbiosns_set_name(const char* hostname);
 #endif
 void netbiosns_stop(void);
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_HDR_APPS_NETBIOS_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/apps/netbiosns_opts.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/apps/netbiosns_opts.h b/net/ip/lwip_base/include/lwip/apps/netbiosns_opts.h
index df6ea26..0909ef7 100644
--- a/net/ip/lwip_base/include/lwip/apps/netbiosns_opts.h
+++ b/net/ip/lwip_base/include/lwip/apps/netbiosns_opts.h
@@ -34,26 +34,12 @@
 
 #include "lwip/opt.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /**
  * @defgroup netbiosns_opts Options
  * @ingroup netbiosns
  * @{
  */
 
-/** Since there's no standard function for case-insensitive string comparision,
- * we need another define here:
- * define this to stricmp() for windows or strcasecmp() for linux.
- * If not defined, comparision is case sensitive and the provided hostname must be
- * uppercase.
- */
-#if !defined NETBIOS_STRCMP || defined __DOXYGEN__
-#define NETBIOS_STRCMP(str1, str2) strcmp(str1, str2)
-#endif
-
 /** NetBIOS name of lwip device
  * This must be uppercase until NETBIOS_STRCMP() is defined to a string
  * comparision function that is case insensitive.
@@ -70,8 +56,4 @@ extern "C" {
  * @}
  */
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_HDR_APPS_NETBIOS_OPTS_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/apps/snmp_opts.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/apps/snmp_opts.h b/net/ip/lwip_base/include/lwip/apps/snmp_opts.h
index 569a82c..6c9ba7b 100644
--- a/net/ip/lwip_base/include/lwip/apps/snmp_opts.h
+++ b/net/ip/lwip_base/include/lwip/apps/snmp_opts.h
@@ -39,10 +39,6 @@
 
 #include "lwip/opt.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /**
  * @defgroup snmp_opts Options
  * @ingroup snmp
@@ -294,8 +290,4 @@ extern "C" {
 #define LWIP_SNMP_V3_MBEDTLS       LWIP_SNMP_V3
 #endif
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_HDR_SNMP_OPTS_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/apps/snmpv3.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/apps/snmpv3.h b/net/ip/lwip_base/include/lwip/apps/snmpv3.h
index 1008eea..c99fed4 100644
--- a/net/ip/lwip_base/include/lwip/apps/snmpv3.h
+++ b/net/ip/lwip_base/include/lwip/apps/snmpv3.h
@@ -38,10 +38,6 @@
 #include "lwip/apps/snmp_opts.h"
 #include "lwip/err.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #if LWIP_SNMP && LWIP_SNMP_V3
 
 #define SNMP_V3_AUTH_ALGO_INVAL  0
@@ -91,8 +87,4 @@ void snmpv3_password_to_key_sha(
 
 #endif
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_HDR_APPS_SNMP_V3_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/apps/sntp_opts.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/apps/sntp_opts.h b/net/ip/lwip_base/include/lwip/apps/sntp_opts.h
index 2dc3033..f3651f9 100644
--- a/net/ip/lwip_base/include/lwip/apps/sntp_opts.h
+++ b/net/ip/lwip_base/include/lwip/apps/sntp_opts.h
@@ -39,10 +39,6 @@
 
 #include "lwip/opt.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /**
  * @defgroup sntp_opts Options
  * @ingroup sntp
@@ -174,8 +170,4 @@ extern "C" {
  * @}
  */
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_HDR_APPS_SNTP_OPTS_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/apps/tftp_opts.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/apps/tftp_opts.h b/net/ip/lwip_base/include/lwip/apps/tftp_opts.h
new file mode 100644
index 0000000..6968a80
--- /dev/null
+++ b/net/ip/lwip_base/include/lwip/apps/tftp_opts.h
@@ -0,0 +1,105 @@
+/****************************************************************//**
+ *
+ * @file tftp_opts.h
+ *
+ * @author   Logan Gunthorpe <lo...@deltatee.com>
+ *
+ * @brief    Trivial File Transfer Protocol (RFC 1350) implementation options
+ *
+ * Copyright (c) Deltatee Enterprises Ltd. 2013
+ * All rights reserved.
+ *
+ ********************************************************************/
+
+/* 
+ * Redistribution and use in source and binary forms, with or without
+ * modification,are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ * 2. 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.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ *
+ * Author: Logan Gunthorpe <lo...@deltatee.com>
+ *
+ */
+
+#ifndef LWIP_HDR_APPS_TFTP_OPTS_H
+#define LWIP_HDR_APPS_TFTP_OPTS_H
+
+#include "lwip/opt.h"
+
+/**
+ * @defgroup tftp_opts Options
+ * @ingroup tftp
+ * @{
+ */
+
+/**
+ * Enable TFTP debug messages
+ */
+#if !defined TFTP_DEBUG || defined __DOXYGEN__
+#define TFTP_DEBUG            LWIP_DBG_ON
+#endif
+
+/**
+ * TFTP server port
+ */
+#if !defined TFTP_PORT || defined __DOXYGEN__
+#define TFTP_PORT             69
+#endif
+
+/**
+ * TFTP timeout
+ */
+#if !defined TFTP_TIMEOUT_MSECS || defined __DOXYGEN__
+#define TFTP_TIMEOUT_MSECS    10000
+#endif
+
+/**
+ * Max. number of retries when a file is read from server
+ */
+#if !defined TFTP_MAX_RETRIES || defined __DOXYGEN__
+#define TFTP_MAX_RETRIES      5
+#endif
+
+/**
+ * TFTP timer cyclic interval
+ */
+#if !defined TFTP_TIMER_MSECS || defined __DOXYGEN__
+#define TFTP_TIMER_MSECS      50
+#endif
+
+/**
+ * Max. length of TFTP filename
+ */
+#if !defined TFTP_MAX_FILENAME_LEN || defined __DOXYGEN__
+#define TFTP_MAX_FILENAME_LEN 20
+#endif
+
+/**
+ * Max. length of TFTP mode
+ */
+#if !defined TFTP_MAX_MODE_LEN || defined __DOXYGEN__
+#define TFTP_MAX_MODE_LEN     7
+#endif
+
+/**
+ * @}
+ */
+
+#endif /* LWIP_HDR_APPS_TFTP_OPTS_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/apps/tftp_server.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/apps/tftp_server.h b/net/ip/lwip_base/include/lwip/apps/tftp_server.h
new file mode 100644
index 0000000..3fbe701
--- /dev/null
+++ b/net/ip/lwip_base/include/lwip/apps/tftp_server.h
@@ -0,0 +1,94 @@
+/****************************************************************//**
+ *
+ * @file tftp_server.h
+ *
+ * @author   Logan Gunthorpe <lo...@deltatee.com>
+ *
+ * @brief    Trivial File Transfer Protocol (RFC 1350)
+ *
+ * Copyright (c) Deltatee Enterprises Ltd. 2013
+ * All rights reserved.
+ *
+ ********************************************************************/
+
+/* 
+ * Redistribution and use in source and binary forms, with or without
+ * modification,are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ * 2. 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.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ *
+ * Author: Logan Gunthorpe <lo...@deltatee.com>
+ *
+ */
+
+#ifndef LWIP_HDR_APPS_TFTP_SERVER_H
+#define LWIP_HDR_APPS_TFTP_SERVER_H
+
+#include "lwip/apps/tftp_opts.h"
+#include "lwip/err.h"
+#include "lwip/pbuf.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** @ingroup tftp
+ * TFTP context containing callback functions for TFTP transfers
+ */
+struct tftp_context {
+  /**
+   * Open file for read/write.
+   * @param fname Filename
+   * @param mode Mode string from TFTP RFC 1350 (netascii, octet, mail)
+   * @param write Flag indicating read (0) or write (!= 0) access
+   * @returns File handle supplied to other functions
+   */
+  void* (*open)(const char* fname, const char* mode, u8_t write);
+  /**
+   * Close file handle
+   * @param handle File handle returned by open()
+   */
+  void (*close)(void* handle);
+  /**
+   * Read from file 
+   * @param handle File handle returned by open()
+   * @param buf Target buffer to copy read data to
+   * @param bytes Number of bytes to copy to buf
+   * @returns &gt;= 0: Success; &lt; 0: Error
+   */
+  int (*read)(void* handle, void* buf, int bytes);
+  /**
+   * Write to file
+   * @param handle File handle returned by open()
+   * @param pbuf PBUF adjusted such that payload pointer points
+   *             to the beginning of write data. In other words,
+   *             TFTP headers are stripped off.
+   * @returns &gt;= 0: Success; &lt; 0: Error
+   */
+  int (*write)(void* handle, struct pbuf* p);
+};
+
+err_t tftp_init(const struct tftp_context* ctx);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LWIP_HDR_APPS_TFTP_SERVER_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/arch.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/arch.h b/net/ip/lwip_base/include/lwip/arch.h
index ee4a0b9..55714e1 100644
--- a/net/ip/lwip_base/include/lwip/arch.h
+++ b/net/ip/lwip_base/include/lwip/arch.h
@@ -47,12 +47,67 @@
 
 #include "arch/cc.h"
 
+/**
+ * @defgroup compiler_abstraction Compiler/platform abstraction
+ * @ingroup sys_layer
+ * All defines related to this section must not be placed in lwipopts.h,
+ * but in arch/cc.h!
+ * These options cannot be \#defined in lwipopts.h since they are not options
+ * of lwIP itself, but options of the lwIP port to your system.
+ * @{
+ */
+
+/** Define the byte order of the system.
+ * Needed for conversion of network data to host byte order.
+ * Allowed values: LITTLE_ENDIAN and BIG_ENDIAN
+ */
+#ifndef BYTE_ORDER
+#define BYTE_ORDER LITTLE_ENDIAN
+#endif
+
+/** Define random number generator function of your system */
+#ifdef __DOXYGEN__
+#define LWIP_RAND() ((u32_t)rand())
+#endif
+
+/** Platform specific diagnostic output.\n
+ * Note the default implementation pulls in printf, which may
+ * in turn pull in a lot of standard libary code. In resource-constrained 
+ * systems, this should be defined to something less resource-consuming.
+ */
+#ifndef LWIP_PLATFORM_DIAG
+#define LWIP_PLATFORM_DIAG(x) do {printf x;} while(0)
+#include <stdio.h>
+#include <stdlib.h>
+#endif
+
+/** Platform specific assertion handling.\n
+ * Note the default implementation pulls in printf, fflush and abort, which may
+ * in turn pull in a lot of standard libary code. In resource-constrained 
+ * systems, this should be defined to something less resource-consuming.
+ */
+#ifndef LWIP_PLATFORM_ASSERT
+#define LWIP_PLATFORM_ASSERT(x) do {printf("Assertion \"%s\" failed at line %d in %s\n", \
+                                     x, __LINE__, __FILE__); fflush(NULL); abort();} while(0)
+#include <stdio.h>
+#include <stdlib.h>
+#endif
+
+/** Define this to 1 in arch/cc.h of your port if you do not want to
+ * include stddef.h header to get size_t. You need to typedef size_t
+ * by yourself in this case.
+ */
+#ifndef LWIP_NO_STDDEF_H
+#define LWIP_NO_STDDEF_H 0
+#endif
+
+#if !LWIP_NO_STDDEF_H
+#include <stddef.h> /* for size_t */
+#endif
+
 /** Define this to 1 in arch/cc.h of your port if your compiler does not provide
- * the stdint.h header. This cannot be \#defined in lwipopts.h since
- * this is not an option of lwIP itself, but an option of the lwIP port
- * to your system.
- * Additionally, this header is meant to be \#included in lwipopts.h
- * (you may need to declare function prototypes in there).
+ * the stdint.h header. You need to typedef the generic types listed in
+ * lwip/arch.h yourself in this case (u8_t, u16_t...).
  */
 #ifndef LWIP_NO_STDINT_H
 #define LWIP_NO_STDINT_H 0
@@ -71,11 +126,8 @@ typedef uintptr_t mem_ptr_t;
 #endif
 
 /** Define this to 1 in arch/cc.h of your port if your compiler does not provide
- * the inttypes.h header. This cannot be \#defined in lwipopts.h since
- * this is not an option of lwIP itself, but an option of the lwIP port
- * to your system.
- * Additionally, this header is meant to be \#included in lwipopts.h
- * (you may need to declare function prototypes in there).
+ * the inttypes.h header. You need to define the format strings listed in
+ * lwip/arch.h yourself in this case (X8_F, U16_F...).
  */
 #ifndef LWIP_NO_INTTYPES_H
 #define LWIP_NO_INTTYPES_H 0
@@ -110,14 +162,44 @@ typedef uintptr_t mem_ptr_t;
 #endif
 #endif
 
+/** Define this to 1 in arch/cc.h of your port if your compiler does not provide
+ * the limits.h header. You need to define the type limits yourself in this case
+ * (e.g. INT_MAX).
+ */
+#ifndef LWIP_NO_LIMITS_H
+#define LWIP_NO_LIMITS_H 0
+#endif
+
+/* Include limits.h? */
+#if !LWIP_NO_LIMITS_H
+#include <limits.h>
+#endif
+
+/** C++ const_cast<target_type>(val) equivalent to remove constness from a value (GCC -Wcast-qual) */
+#ifndef LWIP_CONST_CAST
+#define LWIP_CONST_CAST(target_type, val) ((target_type)((ptrdiff_t)val))
+#endif
+
+/** Get rid of alignment cast warnings (GCC -Wcast-align) */
+#ifndef LWIP_ALIGNMENT_CAST
+#define LWIP_ALIGNMENT_CAST(target_type, val) LWIP_CONST_CAST(target_type, val)
+#endif
+
+/** Get rid of warnings related to pointer-to-numeric and vice-versa casts,
+ * e.g. "conversion from 'u8_t' to 'void *' of greater size"
+ */
+#ifndef LWIP_PTR_NUMERIC_CAST
+#define LWIP_PTR_NUMERIC_CAST(target_type, val) LWIP_CONST_CAST(target_type, val)
+#endif
+
 /** Allocates a memory buffer of specified size that is of sufficient size to align
  * its start address using LWIP_MEM_ALIGN.
  * You can declare your own version here e.g. to enforce alignment without adding
  * trailing padding bytes (see LWIP_MEM_ALIGN_BUFFER) or your own section placement
- * requirements.
- * e.g. if you use gcc and need 32 bit alignment:
- * \#define LWIP_DECLARE_MEMORY_ALIGNED(variable_name, size) u8_t variable_name[size] __attribute__((aligned(4)))
- * or more portable:
+ * requirements.\n
+ * e.g. if you use gcc and need 32 bit alignment:\n
+ * \#define LWIP_DECLARE_MEMORY_ALIGNED(variable_name, size) u8_t variable_name[size] \_\_attribute\_\_((aligned(4)))\n
+ * or more portable:\n
  * \#define LWIP_DECLARE_MEMORY_ALIGNED(variable_name, size) u32_t variable_name[(size + sizeof(u32_t) - 1) / sizeof(u32_t)]
  */
 #ifndef LWIP_DECLARE_MEMORY_ALIGNED
@@ -151,175 +233,84 @@ typedef uintptr_t mem_ptr_t;
 extern "C" {
 #endif
 
+/** Packed structs support.
+  * Placed BEFORE declaration of a packed struct.\n
+  * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n
+  * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here.
+  */
 #ifndef PACK_STRUCT_BEGIN
 #define PACK_STRUCT_BEGIN
 #endif /* PACK_STRUCT_BEGIN */
 
+/** Packed structs support.
+  * Placed AFTER declaration of a packed struct.\n
+  * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n
+  * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here.
+  */
 #ifndef PACK_STRUCT_END
 #define PACK_STRUCT_END
 #endif /* PACK_STRUCT_END */
 
+/** Packed structs support.
+  * Placed between end of declaration of a packed struct and trailing semicolon.\n
+  * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n
+  * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here.
+  */
 #ifndef PACK_STRUCT_STRUCT
+#if defined(__GNUC__) || defined(__clang__)
+#define PACK_STRUCT_STRUCT __attribute__((packed))
+#else
 #define PACK_STRUCT_STRUCT
+#endif
 #endif /* PACK_STRUCT_STRUCT */
 
+/** Packed structs support.
+  * Wraps u32_t and u16_t members.\n
+  * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n
+  * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here.
+  */
 #ifndef PACK_STRUCT_FIELD
 #define PACK_STRUCT_FIELD(x) x
 #endif /* PACK_STRUCT_FIELD */
 
-/* Used for struct fields of u8_t,
- * where some compilers warn that packing is not necessary */
+/** Packed structs support.
+  * Wraps u8_t members, where some compilers warn that packing is not necessary.\n
+  * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n
+  * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here.
+  */
 #ifndef PACK_STRUCT_FLD_8
 #define PACK_STRUCT_FLD_8(x) PACK_STRUCT_FIELD(x)
 #endif /* PACK_STRUCT_FLD_8 */
 
-/* Used for struct fields of that are packed structs themself,
- * where some compilers warn that packing is not necessary */
+/** Packed structs support.
+  * Wraps members that are packed structs themselves, where some compilers warn that packing is not necessary.\n
+  * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n
+  * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here.
+  */
 #ifndef PACK_STRUCT_FLD_S
 #define PACK_STRUCT_FLD_S(x) PACK_STRUCT_FIELD(x)
 #endif /* PACK_STRUCT_FLD_S */
 
+/** Packed structs support using \#include files before and after struct to be packed.\n
+ * The file included BEFORE the struct is "arch/bpstruct.h".\n
+ * The file included AFTER the struct is "arch/epstruct.h".\n
+ * This can be used to implement struct packing on MS Visual C compilers, see
+ * the Win32 port in the lwIP contrib repository for reference.
+ * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n
+ * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here.
+ */
+#ifdef __DOXYGEN__
+#define PACK_STRUCT_USE_INCLUDES
+#endif
 
+/** Eliminates compiler warning about unused arguments (GCC -Wextra -Wunused). */
 #ifndef LWIP_UNUSED_ARG
 #define LWIP_UNUSED_ARG(x) (void)x
 #endif /* LWIP_UNUSED_ARG */
 
-
-#ifdef LWIP_PROVIDE_ERRNO
-
-#define  EPERM         1  /* Operation not permitted */
-#define  ENOENT        2  /* No such file or directory */
-#define  ESRCH         3  /* No such process */
-#define  EINTR         4  /* Interrupted system call */
-#define  EIO           5  /* I/O error */
-#define  ENXIO         6  /* No such device or address */
-#define  E2BIG         7  /* Arg list too long */
-#define  ENOEXEC       8  /* Exec format error */
-#define  EBADF         9  /* Bad file number */
-#define  ECHILD       10  /* No child processes */
-#define  EAGAIN       11  /* Try again */
-#define  ENOMEM       12  /* Out of memory */
-#define  EACCES       13  /* Permission denied */
-#define  EFAULT       14  /* Bad address */
-#define  ENOTBLK      15  /* Block device required */
-#define  EBUSY        16  /* Device or resource busy */
-#define  EEXIST       17  /* File exists */
-#define  EXDEV        18  /* Cross-device link */
-#define  ENODEV       19  /* No such device */
-#define  ENOTDIR      20  /* Not a directory */
-#define  EISDIR       21  /* Is a directory */
-#define  EINVAL       22  /* Invalid argument */
-#define  ENFILE       23  /* File table overflow */
-#define  EMFILE       24  /* Too many open files */
-#define  ENOTTY       25  /* Not a typewriter */
-#define  ETXTBSY      26  /* Text file busy */
-#define  EFBIG        27  /* File too large */
-#define  ENOSPC       28  /* No space left on device */
-#define  ESPIPE       29  /* Illegal seek */
-#define  EROFS        30  /* Read-only file system */
-#define  EMLINK       31  /* Too many links */
-#define  EPIPE        32  /* Broken pipe */
-#define  EDOM         33  /* Math argument out of domain of func */
-#define  ERANGE       34  /* Math result not representable */
-#define  EDEADLK      35  /* Resource deadlock would occur */
-#define  ENAMETOOLONG 36  /* File name too long */
-#define  ENOLCK       37  /* No record locks available */
-#define  ENOSYS       38  /* Function not implemented */
-#define  ENOTEMPTY    39  /* Directory not empty */
-#define  ELOOP        40  /* Too many symbolic links encountered */
-#define  EWOULDBLOCK  EAGAIN  /* Operation would block */
-#define  ENOMSG       42  /* No message of desired type */
-#define  EIDRM        43  /* Identifier removed */
-#define  ECHRNG       44  /* Channel number out of range */
-#define  EL2NSYNC     45  /* Level 2 not synchronized */
-#define  EL3HLT       46  /* Level 3 halted */
-#define  EL3RST       47  /* Level 3 reset */
-#define  ELNRNG       48  /* Link number out of range */
-#define  EUNATCH      49  /* Protocol driver not attached */
-#define  ENOCSI       50  /* No CSI structure available */
-#define  EL2HLT       51  /* Level 2 halted */
-#define  EBADE        52  /* Invalid exchange */
-#define  EBADR        53  /* Invalid request descriptor */
-#define  EXFULL       54  /* Exchange full */
-#define  ENOANO       55  /* No anode */
-#define  EBADRQC      56  /* Invalid request code */
-#define  EBADSLT      57  /* Invalid slot */
-
-#define  EDEADLOCK    EDEADLK
-
-#define  EBFONT       59  /* Bad font file format */
-#define  ENOSTR       60  /* Device not a stream */
-#define  ENODATA      61  /* No data available */
-#define  ETIME        62  /* Timer expired */
-#define  ENOSR        63  /* Out of streams resources */
-#define  ENONET       64  /* Machine is not on the network */
-#define  ENOPKG       65  /* Package not installed */
-#define  EREMOTE      66  /* Object is remote */
-#define  ENOLINK      67  /* Link has been severed */
-#define  EADV         68  /* Advertise error */
-#define  ESRMNT       69  /* Srmount error */
-#define  ECOMM        70  /* Communication error on send */
-#define  EPROTO       71  /* Protocol error */
-#define  EMULTIHOP    72  /* Multihop attempted */
-#define  EDOTDOT      73  /* RFS specific error */
-#define  EBADMSG      74  /* Not a data message */
-#define  EOVERFLOW    75  /* Value too large for defined data type */
-#define  ENOTUNIQ     76  /* Name not unique on network */
-#define  EBADFD       77  /* File descriptor in bad state */
-#define  EREMCHG      78  /* Remote address changed */
-#define  ELIBACC      79  /* Can not access a needed shared library */
-#define  ELIBBAD      80  /* Accessing a corrupted shared library */
-#define  ELIBSCN      81  /* .lib section in a.out corrupted */
-#define  ELIBMAX      82  /* Attempting to link in too many shared libraries */
-#define  ELIBEXEC     83  /* Cannot exec a shared library directly */
-#define  EILSEQ       84  /* Illegal byte sequence */
-#define  ERESTART     85  /* Interrupted system call should be restarted */
-#define  ESTRPIPE     86  /* Streams pipe error */
-#define  EUSERS       87  /* Too many users */
-#define  ENOTSOCK     88  /* Socket operation on non-socket */
-#define  EDESTADDRREQ 89  /* Destination address required */
-#define  EMSGSIZE     90  /* Message too long */
-#define  EPROTOTYPE   91  /* Protocol wrong type for socket */
-#define  ENOPROTOOPT  92  /* Protocol not available */
-#define  EPROTONOSUPPORT 93  /* Protocol not supported */
-#define  ESOCKTNOSUPPORT 94  /* Socket type not supported */
-#define  EOPNOTSUPP      95  /* Operation not supported on transport endpoint */
-#define  EPFNOSUPPORT    96  /* Protocol family not supported */
-#define  EAFNOSUPPORT    97  /* Address family not supported by protocol */
-#define  EADDRINUSE      98  /* Address already in use */
-#define  EADDRNOTAVAIL   99  /* Cannot assign requested address */
-#define  ENETDOWN       100  /* Network is down */
-#define  ENETUNREACH    101  /* Network is unreachable */
-#define  ENETRESET      102  /* Network dropped connection because of reset */
-#define  ECONNABORTED   103  /* Software caused connection abort */
-#define  ECONNRESET     104  /* Connection reset by peer */
-#define  ENOBUFS        105  /* No buffer space available */
-#define  EISCONN        106  /* Transport endpoint is already connected */
-#define  ENOTCONN       107  /* Transport endpoint is not connected */
-#define  ESHUTDOWN      108  /* Cannot send after transport endpoint shutdown */
-#define  ETOOMANYREFS   109  /* Too many references: cannot splice */
-#define  ETIMEDOUT      110  /* Connection timed out */
-#define  ECONNREFUSED   111  /* Connection refused */
-#define  EHOSTDOWN      112  /* Host is down */
-#define  EHOSTUNREACH   113  /* No route to host */
-#define  EALREADY       114  /* Operation already in progress */
-#define  EINPROGRESS    115  /* Operation now in progress */
-#define  ESTALE         116  /* Stale NFS file handle */
-#define  EUCLEAN        117  /* Structure needs cleaning */
-#define  ENOTNAM        118  /* Not a XENIX named type file */
-#define  ENAVAIL        119  /* No XENIX semaphores available */
-#define  EISNAM         120  /* Is a named type file */
-#define  EREMOTEIO      121  /* Remote I/O error */
-#define  EDQUOT         122  /* Quota exceeded */
-
-#define  ENOMEDIUM      123  /* No medium found */
-#define  EMEDIUMTYPE    124  /* Wrong medium type */
-
-#ifndef errno
-extern int errno;
-#endif
-
-#endif /* LWIP_PROVIDE_ERRNO */
+/**
+ * @}
+ */
 
 #ifdef __cplusplus
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/autoip.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/autoip.h b/net/ip/lwip_base/include/lwip/autoip.h
index 2f66698..1d85bcc 100644
--- a/net/ip/lwip_base/include/lwip/autoip.h
+++ b/net/ip/lwip_base/include/lwip/autoip.h
@@ -88,6 +88,8 @@ u8_t autoip_supplied_address(const struct netif *netif);
 /* for lwIP internal use by ip4.c */
 u8_t autoip_accept_packet(struct netif *netif, const ip4_addr_t *addr);
 
+#define netif_autoip_data(netif) ((struct autoip*)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_AUTOIP))
+
 #ifdef __cplusplus
 }
 #endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/debug.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/debug.h b/net/ip/lwip_base/include/lwip/debug.h
index 11d4775..a142f1c 100644
--- a/net/ip/lwip_base/include/lwip/debug.h
+++ b/net/ip/lwip_base/include/lwip/debug.h
@@ -40,28 +40,45 @@
 #include "lwip/arch.h"
 #include "lwip/opt.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
+/**
+ * @defgroup debugging_levels LWIP_DBG_MIN_LEVEL and LWIP_DBG_TYPES_ON values
+ * @ingroup lwip_opts_debugmsg
+ * @{
+ */
 
-/** lower two bits indicate debug level
- * - 0 all
- * - 1 warning
- * - 2 serious
- * - 3 severe
+/** @name Debug level (LWIP_DBG_MIN_LEVEL)
+ * @{
  */
+/** Debug level: ALL messages*/
 #define LWIP_DBG_LEVEL_ALL     0x00
-#define LWIP_DBG_LEVEL_OFF     LWIP_DBG_LEVEL_ALL /* compatibility define only */
-#define LWIP_DBG_LEVEL_WARNING 0x01 /* bad checksums, dropped packets, ... */
-#define LWIP_DBG_LEVEL_SERIOUS 0x02 /* memory allocation failures, ... */
+/** Debug level: Warnings. bad checksums, dropped packets, ... */
+#define LWIP_DBG_LEVEL_WARNING 0x01
+/** Debug level: Serious. memory allocation failures, ... */
+#define LWIP_DBG_LEVEL_SERIOUS 0x02
+/** Debug level: Severe */
 #define LWIP_DBG_LEVEL_SEVERE  0x03
+/**
+ * @}
+ */
+
 #define LWIP_DBG_MASK_LEVEL    0x03
+/* compatibility define only */
+#define LWIP_DBG_LEVEL_OFF     LWIP_DBG_LEVEL_ALL
 
+/** @name Enable/disable debug messages completely (LWIP_DBG_TYPES_ON)
+ * @{
+ */
 /** flag for LWIP_DEBUGF to enable that debug message */
 #define LWIP_DBG_ON            0x80U
 /** flag for LWIP_DEBUGF to disable that debug message */
 #define LWIP_DBG_OFF           0x00U
+/**
+ * @}
+ */
 
+/** @name Debug message types (LWIP_DBG_TYPES_ON)
+ * @{
+ */
 /** flag for LWIP_DEBUGF indicating a tracing message (to follow program flow) */
 #define LWIP_DBG_TRACE         0x40U
 /** flag for LWIP_DEBUGF indicating a state debug message (to follow module states) */
@@ -70,11 +87,31 @@ extern "C" {
 #define LWIP_DBG_FRESH         0x10U
 /** flag for LWIP_DEBUGF to halt after printing this debug message */
 #define LWIP_DBG_HALT          0x08U
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
 
 /**
- * LWIP_NOASSERT: Disable LWIP_ASSERT checks.
- * -- To disable assertions define LWIP_NOASSERT in arch/cc.h.
+ * @defgroup lwip_assertions Assertion handling
+ * @ingroup lwip_opts_debug
+ * @{
+ */
+/**
+ * LWIP_NOASSERT: Disable LWIP_ASSERT checks:
+ * To disable assertions define LWIP_NOASSERT in arch/cc.h.
  */
+#ifdef __DOXYGEN__
+#define LWIP_NOASSERT
+#undef LWIP_NOASSERT
+#endif
+/**
+ * @}
+ */
+
 #ifndef LWIP_NOASSERT
 #define LWIP_ASSERT(message, assertion) do { if (!(assertion)) { \
   LWIP_PLATFORM_ASSERT(message); }} while(0)
@@ -85,7 +122,6 @@ extern "C" {
 #define LWIP_ASSERT(message, assertion)
 #endif /* LWIP_NOASSERT */
 
-/** if "expression" isn't true, then print "message" and execute "handler" expression */
 #ifndef LWIP_ERROR
 #ifndef LWIP_NOASSERT
 #define LWIP_PLATFORM_ERROR(message) LWIP_PLATFORM_ASSERT(message)
@@ -95,17 +131,23 @@ extern "C" {
 #define LWIP_PLATFORM_ERROR(message)
 #endif
 
+/* if "expression" isn't true, then print "message" and execute "handler" expression */
 #define LWIP_ERROR(message, expression, handler) do { if (!(expression)) { \
   LWIP_PLATFORM_ERROR(message); handler;}} while(0)
 #endif /* LWIP_ERROR */
 
+/** Enable debug message printing, but only if debug message type is enabled
+ *  AND is of correct type AND is at least LWIP_DBG_LEVEL.
+ */
+#ifdef __DOXYGEN__
+#define LWIP_DEBUG
+#undef LWIP_DEBUG
+#endif
+
 #ifdef LWIP_DEBUG
 #ifndef LWIP_PLATFORM_DIAG
 #error "If you want to use LWIP_DEBUG, LWIP_PLATFORM_DIAG(message) needs to be defined in your arch/cc.h"
 #endif
-/** print debug message only if debug message type is enabled...
- *  AND is of correct type AND is at least LWIP_DBG_LEVEL
- */
 #define LWIP_DEBUGF(debug, message) do { \
                                if ( \
                                    ((debug) & LWIP_DBG_ON) && \
@@ -122,9 +164,4 @@ extern "C" {
 #define LWIP_DEBUGF(debug, message)
 #endif /* LWIP_DEBUG */
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_HDR_DEBUG_H */
-



[20/30] incubator-mynewt-core git commit: net/ip/lwip_base; update to LwIP to tag STABLE-2_0_2_RELEASE

Posted by ad...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/prot/tcp.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/prot/tcp.h b/net/ip/lwip_base/include/lwip/prot/tcp.h
index 8ef0bf1..67fe7b9 100644
--- a/net/ip/lwip_base/include/lwip/prot/tcp.h
+++ b/net/ip/lwip_base/include/lwip/prot/tcp.h
@@ -80,15 +80,15 @@ PACK_STRUCT_END
 /* Valid TCP header flags */
 #define TCP_FLAGS 0x3fU
 
-#define TCPH_HDRLEN(phdr) ((u16_t)(ntohs((phdr)->_hdrlen_rsvd_flags) >> 12))
-#define TCPH_FLAGS(phdr)  ((u16_t)(ntohs((phdr)->_hdrlen_rsvd_flags) & TCP_FLAGS))
+#define TCPH_HDRLEN(phdr) ((u16_t)(lwip_ntohs((phdr)->_hdrlen_rsvd_flags) >> 12))
+#define TCPH_FLAGS(phdr)  ((u16_t)(lwip_ntohs((phdr)->_hdrlen_rsvd_flags) & TCP_FLAGS))
 
-#define TCPH_HDRLEN_SET(phdr, len) (phdr)->_hdrlen_rsvd_flags = htons(((len) << 12) | TCPH_FLAGS(phdr))
-#define TCPH_FLAGS_SET(phdr, flags) (phdr)->_hdrlen_rsvd_flags = (((phdr)->_hdrlen_rsvd_flags & PP_HTONS(~TCP_FLAGS)) | htons(flags))
-#define TCPH_HDRLEN_FLAGS_SET(phdr, len, flags) (phdr)->_hdrlen_rsvd_flags = htons(((len) << 12) | (flags))
+#define TCPH_HDRLEN_SET(phdr, len) (phdr)->_hdrlen_rsvd_flags = lwip_htons(((len) << 12) | TCPH_FLAGS(phdr))
+#define TCPH_FLAGS_SET(phdr, flags) (phdr)->_hdrlen_rsvd_flags = (((phdr)->_hdrlen_rsvd_flags & PP_HTONS(~TCP_FLAGS)) | lwip_htons(flags))
+#define TCPH_HDRLEN_FLAGS_SET(phdr, len, flags) (phdr)->_hdrlen_rsvd_flags = (u16_t)(lwip_htons((u16_t)((len) << 12) | (flags)))
 
-#define TCPH_SET_FLAG(phdr, flags ) (phdr)->_hdrlen_rsvd_flags = ((phdr)->_hdrlen_rsvd_flags | htons(flags))
-#define TCPH_UNSET_FLAG(phdr, flags) (phdr)->_hdrlen_rsvd_flags = ((phdr)->_hdrlen_rsvd_flags & ~htons(flags))
+#define TCPH_SET_FLAG(phdr, flags ) (phdr)->_hdrlen_rsvd_flags = ((phdr)->_hdrlen_rsvd_flags | lwip_htons(flags))
+#define TCPH_UNSET_FLAG(phdr, flags) (phdr)->_hdrlen_rsvd_flags = ((phdr)->_hdrlen_rsvd_flags & ~lwip_htons(flags))
 
 #ifdef __cplusplus
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/raw.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/raw.h b/net/ip/lwip_base/include/lwip/raw.h
index f92c8ee..30aa147 100644
--- a/net/ip/lwip_base/include/lwip/raw.h
+++ b/net/ip/lwip_base/include/lwip/raw.h
@@ -104,6 +104,8 @@ void             raw_recv       (struct raw_pcb *pcb, raw_recv_fn recv, void *re
 u8_t             raw_input      (struct pbuf *p, struct netif *inp);
 #define raw_init() /* Compatibility define, no init needed. */
 
+void raw_netif_ip_addr_changed(const ip_addr_t* old_addr, const ip_addr_t* new_addr);
+
 /* for compatibility with older implementation */
 #define raw_new_ip6(proto) raw_new_ip_type(IPADDR_TYPE_V6, proto)
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/sockets.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/sockets.h b/net/ip/lwip_base/include/lwip/sockets.h
index 20ba629..2522056 100644
--- a/net/ip/lwip_base/include/lwip/sockets.h
+++ b/net/ip/lwip_base/include/lwip/sockets.h
@@ -43,11 +43,10 @@
 
 #if LWIP_SOCKET /* don't build if not configured for use in lwipopts.h */
 
-#include <stddef.h> /* for size_t */
-
 #include "lwip/ip_addr.h"
 #include "lwip/err.h"
 #include "lwip/inet.h"
+#include "lwip/errno.h"
 
 #ifdef __cplusplus
 extern "C" {
@@ -427,6 +426,8 @@ typedef struct fd_set
 
 #elif LWIP_SOCKET_OFFSET
 #error LWIP_SOCKET_OFFSET does not work with external FD_SET!
+#elif FD_SETSIZE < MEMP_NUM_NETCONN
+#error "external FD_SETSIZE too small for number of sockets"
 #endif /* FD_SET */
 
 /** LWIP_TIMEVAL_PRIVATE: if you want to use the struct timeval provided

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/stats.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/stats.h b/net/ip/lwip_base/include/lwip/stats.h
index 89f54f3..bcda2ac 100644
--- a/net/ip/lwip_base/include/lwip/stats.h
+++ b/net/ip/lwip_base/include/lwip/stats.h
@@ -304,7 +304,7 @@ struct stats_ {
 extern struct stats_ lwip_stats;
 
 /** Init statistics */
-void lwip_stats_init(void);
+void stats_init(void);
 
 #define STATS_INC(x) ++lwip_stats.x
 #define STATS_DEC(x) --lwip_stats.x
@@ -315,7 +315,7 @@ void lwip_stats_init(void);
                              } while(0)
 #define STATS_GET(x) lwip_stats.x
 #else /* LWIP_STATS */
-#define lwip_stats_init()
+#define stats_init()
 #define STATS_INC(x)
 #define STATS_DEC(x)
 #define STATS_INC_USED(x)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/sys.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/sys.h b/net/ip/lwip_base/include/lwip/sys.h
index f8804df..d12bae0 100644
--- a/net/ip/lwip_base/include/lwip/sys.h
+++ b/net/ip/lwip_base/include/lwip/sys.h
@@ -34,44 +34,6 @@
  * Author: Adam Dunkels <ad...@sics.se>
  */
 
-/**
- * @defgroup sys_layer System abstraction layer
- * @ingroup infrastructure
- * @verbinclude "sys_arch.txt"
- *
- * @defgroup sys_os OS abstraction layer
- * @ingroup sys_layer
- * No need to implement functions in this section in NO_SYS mode.
- *
- * @defgroup sys_sem Semaphores
- * @ingroup sys_os
- *
- * @defgroup sys_mutex Mutexes
- * @ingroup sys_os
- * Mutexes are recommended to correctly handle priority inversion,
- * especially if you use LWIP_CORE_LOCKING .
- *
- * @defgroup sys_mbox Mailboxes
- * @ingroup sys_os
- *
- * @defgroup sys_time Time
- * @ingroup sys_layer
- *
- * @defgroup sys_prot Critical sections
- * @ingroup sys_layer
- * Used to protect short regions of code against concurrent access.
- * - Your system is a bare-metal system (probably with an RTOS)
- *   and interrupts are under your control:
- *   Implement this as LockInterrupts() / UnlockInterrupts()
- * - Your system uses an RTOS with deferred interrupt handling from a
- *   worker thread: Implement as a global mutex or lock/unlock scheduler
- * - Your system uses a high-level OS with e.g. POSIX signals:
- *   Implement as a global mutex
- *
- * @defgroup sys_misc Misc
- * @ingroup sys_os
- */
-
 #ifndef LWIP_HDR_SYS_H
 #define LWIP_HDR_SYS_H
 
@@ -160,9 +122,11 @@ typedef void (*lwip_thread_fn)(void *arg);
 
 /**
  * @ingroup sys_mutex
- * Create a new mutex
+ * Create a new mutex.
+ * Note that mutexes are expected to not be taken recursively by the lwIP code,
+ * so both implementation types (recursive or non-recursive) should work.
  * @param mutex pointer to the mutex to create
- * @return a new mutex
+ * @return ERR_OK if successful, another err_t otherwise
  */
 err_t sys_mutex_new(sys_mutex_t *mutex);
 /**

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/tcp.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/tcp.h b/net/ip/lwip_base/include/lwip/tcp.h
index 35584b4..34d1c10 100644
--- a/net/ip/lwip_base/include/lwip/tcp.h
+++ b/net/ip/lwip_base/include/lwip/tcp.h
@@ -145,7 +145,7 @@ typedef u32_t tcpwnd_size_t;
 typedef u16_t tcpwnd_size_t;
 #endif
 
-#if LWIP_WND_SCALE || TCP_LISTEN_BACKLOG
+#if LWIP_WND_SCALE || TCP_LISTEN_BACKLOG || LWIP_TCP_TIMESTAMPS
 typedef u16_t tcpflags_t;
 #else
 typedef u8_t tcpflags_t;
@@ -210,7 +210,7 @@ struct tcp_pcb {
 #define TF_ACK_DELAY   0x01U   /* Delayed ACK. */
 #define TF_ACK_NOW     0x02U   /* Immediate ACK. */
 #define TF_INFR        0x04U   /* In fast recovery. */
-#define TF_TIMESTAMP   0x08U   /* Timestamp option enabled */
+#define TF_CLOSEPEND   0x08U   /* If this is set, tcp_close failed to enqueue the FIN (retried in tcp_tmr) */
 #define TF_RXCLOSED    0x10U   /* rx closed by tcp_shutdown */
 #define TF_FIN         0x20U   /* Connection was closed locally (FIN segment enqueued). */
 #define TF_NODELAY     0x40U   /* Disable Nagle algorithm */
@@ -221,6 +221,9 @@ struct tcp_pcb {
 #if TCP_LISTEN_BACKLOG
 #define TF_BACKLOGPEND 0x0200U /* If this is set, a connection pcb has increased the backlog on its listener */
 #endif
+#if LWIP_TCP_TIMESTAMPS
+#define TF_TIMESTAMP   0x0400U   /* Timestamp option enabled */
+#endif
 
   /* the rest of the fields are in host byte order
      as we have to do some math with them */
@@ -358,7 +361,11 @@ void             tcp_accept  (struct tcp_pcb *pcb, tcp_accept_fn accept);
 #endif /* LWIP_CALLBACK_API */
 void             tcp_poll    (struct tcp_pcb *pcb, tcp_poll_fn poll, u8_t interval);
 
+#if LWIP_TCP_TIMESTAMPS
 #define          tcp_mss(pcb)             (((pcb)->flags & TF_TIMESTAMP) ? ((pcb)->mss - 12)  : (pcb)->mss)
+#else /* LWIP_TCP_TIMESTAMPS */
+#define          tcp_mss(pcb)             ((pcb)->mss)
+#endif /* LWIP_TCP_TIMESTAMPS */
 #define          tcp_sndbuf(pcb)          (TCPWND16((pcb)->snd_buf))
 #define          tcp_sndqueuelen(pcb)     ((pcb)->snd_queuelen)
 /** @ingroup tcp_raw */
@@ -387,6 +394,7 @@ err_t            tcp_bind    (struct tcp_pcb *pcb, const ip_addr_t *ipaddr,
 err_t            tcp_connect (struct tcp_pcb *pcb, const ip_addr_t *ipaddr,
                               u16_t port, tcp_connected_fn connected);
 
+struct tcp_pcb * tcp_listen_with_backlog_and_err(struct tcp_pcb *pcb, u8_t backlog, err_t *err);
 struct tcp_pcb * tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog);
 /** @ingroup tcp_raw */
 #define          tcp_listen(pcb) tcp_listen_with_backlog(pcb, TCP_DEFAULT_LISTEN_BACKLOG)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/tcpip.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/tcpip.h b/net/ip/lwip_base/include/lwip/tcpip.h
index 404a4a2..f2f6b46 100644
--- a/net/ip/lwip_base/include/lwip/tcpip.h
+++ b/net/ip/lwip_base/include/lwip/tcpip.h
@@ -52,7 +52,9 @@ extern "C" {
 #if LWIP_TCPIP_CORE_LOCKING
 /** The global semaphore to lock the stack. */
 extern sys_mutex_t lock_tcpip_core;
+/** Lock lwIP core mutex (needs @ref LWIP_TCPIP_CORE_LOCKING 1) */
 #define LOCK_TCPIP_CORE()     sys_mutex_lock(&lock_tcpip_core)
+/** Unlock lwIP core mutex (needs @ref LWIP_TCPIP_CORE_LOCKING 1) */
 #define UNLOCK_TCPIP_CORE()   sys_mutex_unlock(&lock_tcpip_core)
 #else /* LWIP_TCPIP_CORE_LOCKING */
 #define LOCK_TCPIP_CORE()

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/lwip/timeouts.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/lwip/timeouts.h b/net/ip/lwip_base/include/lwip/timeouts.h
index 4988b15..c9b93aa 100644
--- a/net/ip/lwip_base/include/lwip/timeouts.h
+++ b/net/ip/lwip_base/include/lwip/timeouts.h
@@ -103,9 +103,9 @@ void sys_timeout(u32_t msecs, sys_timeout_handler handler, void *arg);
 #endif /* LWIP_DEBUG_TIMERNAMES */
 
 void sys_untimeout(sys_timeout_handler handler, void *arg);
+void sys_restart_timeouts(void);
 #if NO_SYS
 void sys_check_timeouts(void);
-void sys_restart_timeouts(void);
 u32_t sys_timeouts_sleeptime(void);
 #else /* NO_SYS */
 void sys_timeouts_mbox_fetch(sys_mbox_t *mbox, void **msg);

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/lowpan6_opts.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/lowpan6_opts.h b/net/ip/lwip_base/include/netif/lowpan6_opts.h
index 140d0c3..fb93ea0 100644
--- a/net/ip/lwip_base/include/netif/lowpan6_opts.h
+++ b/net/ip/lwip_base/include/netif/lowpan6_opts.h
@@ -43,10 +43,6 @@
 
 #include "lwip/opt.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #ifndef LWIP_6LOWPAN
 #define LWIP_6LOWPAN                     0
 #endif
@@ -71,8 +67,4 @@ extern "C" {
 #define LOWPAN6_DEBUG                    LWIP_DBG_OFF
 #endif
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_HDR_LOWPAN6_OPTS_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/ppp/ccp.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/ppp/ccp.h b/net/ip/lwip_base/include/netif/ppp/ccp.h
index b5642db..14dd659 100644
--- a/net/ip/lwip_base/include/netif/ppp/ccp.h
+++ b/net/ip/lwip_base/include/netif/ppp/ccp.h
@@ -36,10 +36,6 @@
 #ifndef CCP_H
 #define CCP_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /*
  * CCP codes.
  */
@@ -157,8 +153,4 @@ extern const struct protent ccp_protent;
 void ccp_resetrequest(ppp_pcb *pcb);  /* Issue a reset-request. */
 
 #endif /* CCP_H */
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* PPP_SUPPORT && CCP_SUPPORT */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/ppp/chap-new.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/ppp/chap-new.h b/net/ip/lwip_base/include/netif/ppp/chap-new.h
index 872979d..64eae32 100644
--- a/net/ip/lwip_base/include/netif/ppp/chap-new.h
+++ b/net/ip/lwip_base/include/netif/ppp/chap-new.h
@@ -36,10 +36,6 @@
 
 #include "ppp.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /*
  * CHAP packets begin with a standard header with code, id, len (2 bytes).
  */
@@ -193,8 +189,4 @@ extern void chap_auth_with_peer(ppp_pcb *pcb, const char *our_name, int digest_c
 extern const struct protent chap_protent;
 
 #endif /* CHAP_H */
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* PPP_SUPPORT && CHAP_SUPPORT */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/ppp/chap_ms.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/ppp/chap_ms.h b/net/ip/lwip_base/include/netif/ppp/chap_ms.h
index 10898c6..0795291 100644
--- a/net/ip/lwip_base/include/netif/ppp/chap_ms.h
+++ b/net/ip/lwip_base/include/netif/ppp/chap_ms.h
@@ -36,17 +36,9 @@
 #ifndef CHAPMS_INCLUDE
 #define CHAPMS_INCLUDE
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 extern const struct chap_digest_type chapms_digest;
 extern const struct chap_digest_type chapms2_digest;
 
 #endif /* CHAPMS_INCLUDE */
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* PPP_SUPPORT && MSCHAP_SUPPORT */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/ppp/eui64.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/ppp/eui64.h b/net/ip/lwip_base/include/netif/ppp/eui64.h
index 758d8e6..20ac22e 100644
--- a/net/ip/lwip_base/include/netif/ppp/eui64.h
+++ b/net/ip/lwip_base/include/netif/ppp/eui64.h
@@ -41,10 +41,6 @@
 #ifndef EUI64_H
 #define EUI64_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /*
  * @todo:
  *
@@ -88,15 +84,11 @@ typedef union
 
 #define eui64_set32(e, l)	do {			\
 				(e).e32[0] = 0;		\
-				(e).e32[1] = htonl(l);	\
+				(e).e32[1] = lwip_htonl(l);	\
 				} while (0)
 #define eui64_setlo32(e, l)	eui64_set32(e, l)
 
 char *eui64_ntoa(eui64_t);	/* Returns ascii representation of id */
 
 #endif /* EUI64_H */
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* PPP_SUPPORT && PPP_IPV6_SUPPORT */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/ppp/fsm.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/ppp/fsm.h b/net/ip/lwip_base/include/netif/ppp/fsm.h
index c5fcc5c..b6915d3 100644
--- a/net/ip/lwip_base/include/netif/ppp/fsm.h
+++ b/net/ip/lwip_base/include/netif/ppp/fsm.h
@@ -50,10 +50,6 @@
 
 #include "ppp.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /*
  * Packet header = Code, id, length.
  */
@@ -176,8 +172,4 @@ void fsm_sdata(fsm *f, u_char code, u_char id, const u_char *data, int datalen);
 
 
 #endif /* FSM_H */
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* PPP_SUPPORT */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/ppp/ipcp.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/ppp/ipcp.h b/net/ip/lwip_base/include/netif/ppp/ipcp.h
index b41bd96..45f46b3 100644
--- a/net/ip/lwip_base/include/netif/ppp/ipcp.h
+++ b/net/ip/lwip_base/include/netif/ppp/ipcp.h
@@ -48,10 +48,6 @@
 #ifndef IPCP_H
 #define	IPCP_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /*
  * Options.
  */
@@ -127,8 +123,4 @@ char *ip_ntoa (u32_t);
 extern const struct protent ipcp_protent;
 
 #endif /* IPCP_H */
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* PPP_SUPPORT && PPP_IPV4_SUPPORT */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/ppp/ipv6cp.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/ppp/ipv6cp.h b/net/ip/lwip_base/include/netif/ppp/ipv6cp.h
index 64c30e3..07d1ae3 100644
--- a/net/ip/lwip_base/include/netif/ppp/ipv6cp.h
+++ b/net/ip/lwip_base/include/netif/ppp/ipv6cp.h
@@ -146,10 +146,6 @@
 
 #include "eui64.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /*
  * Options.
  */
@@ -184,8 +180,4 @@ typedef struct ipv6cp_options {
 extern const struct protent ipv6cp_protent;
 
 #endif /* IPV6CP_H */
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* PPP_SUPPORT && PPP_IPV6_SUPPORT */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/ppp/lcp.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/ppp/lcp.h b/net/ip/lwip_base/include/netif/ppp/lcp.h
index 65f7394..12e2a05 100644
--- a/net/ip/lwip_base/include/netif/ppp/lcp.h
+++ b/net/ip/lwip_base/include/netif/ppp/lcp.h
@@ -50,10 +50,6 @@
 
 #include "ppp.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /*
  * Options.
  */
@@ -172,8 +168,4 @@ extern const struct protent lcp_protent;
 #endif /* moved to ppp_opts.h */
 
 #endif /* LCP_H */
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* PPP_SUPPORT */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/ppp/magic.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/ppp/magic.h b/net/ip/lwip_base/include/netif/ppp/magic.h
index eea645b..a2a9b53 100644
--- a/net/ip/lwip_base/include/netif/ppp/magic.h
+++ b/net/ip/lwip_base/include/netif/ppp/magic.h
@@ -80,10 +80,6 @@
 #ifndef MAGIC_H
 #define MAGIC_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /***********************
 *** PUBLIC FUNCTIONS ***
 ***********************/
@@ -123,8 +119,4 @@ u32_t magic_pow(u8_t pow);
 
 #endif /* MAGIC_H */
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* PPP_SUPPORT */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/ppp/mppe.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/ppp/mppe.h b/net/ip/lwip_base/include/netif/ppp/mppe.h
index d7383a9..1ae8a5d 100644
--- a/net/ip/lwip_base/include/netif/ppp/mppe.h
+++ b/net/ip/lwip_base/include/netif/ppp/mppe.h
@@ -41,10 +41,6 @@
 
 #include "netif/ppp/pppcrypt.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #define MPPE_PAD		4	/* MPPE growth per frame */
 #define MPPE_MAX_KEY_LEN	16	/* largest key length (128-bit) */
 
@@ -63,7 +59,7 @@ extern "C" {
  * This is not nice ... the alternative is a bitfield struct though.
  * And unfortunately, we cannot share the same bits for the option
  * names above since C and H are the same bit.  We could do a u_int32
- * but then we have to do a htonl() all the time and/or we still need
+ * but then we have to do a lwip_htonl() all the time and/or we still need
  * to know which octet is which.
  */
 #define MPPE_C_BIT		0x01	/* MPPC */
@@ -174,8 +170,4 @@ void mppe_decomp_reset(ppp_pcb *pcb, ppp_mppe_state *state);
 err_t mppe_decompress(ppp_pcb *pcb, ppp_mppe_state *state, struct pbuf **pb);
 
 #endif /* MPPE_H */
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* PPP_SUPPORT && MPPE_SUPPORT */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/ppp/ppp.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/ppp/ppp.h b/net/ip/lwip_base/include/netif/ppp/ppp.h
index 58c8e09..d9ea097 100644
--- a/net/ip/lwip_base/include/netif/ppp/ppp.h
+++ b/net/ip/lwip_base/include/netif/ppp/ppp.h
@@ -43,10 +43,6 @@
 #include "lwip/netif.h"
 #include "lwip/sys.h"
 #include "lwip/timeouts.h"
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #if PPP_IPV6_SUPPORT
 #include "lwip/ip6_addr.h"
 #endif /* PPP_IPV6_SUPPORT */
@@ -328,6 +324,7 @@ struct ppp_pcb_s {
 
   /* flags */
 #if PPP_IPV4_SUPPORT
+  unsigned int ask_for_local           :1; /* request our address from peer */
   unsigned int ipcp_is_open            :1; /* haven't called np_finished() */
   unsigned int ipcp_is_up              :1; /* have called ipcp_up() */
   unsigned int if4_up                  :1; /* True when the IPv4 interface is up. */
@@ -479,7 +476,8 @@ void ppp_set_auth(ppp_pcb *pcb, u8_t authtype, const char *user, const char *pas
  *
  * Default is unset (0.0.0.0).
  */
-#define ppp_set_ipcp_ouraddr(ppp, addr) (ppp->ipcp_wantoptions.ouraddr = ip4_addr_get_u32(addr))
+#define ppp_set_ipcp_ouraddr(ppp, addr) do { ppp->ipcp_wantoptions.ouraddr = ip4_addr_get_u32(addr); \
+                                             ppp->ask_for_local = ppp->ipcp_wantoptions.ouraddr != 0; } while(0)
 #define ppp_set_ipcp_hisaddr(ppp, addr) (ppp->ipcp_wantoptions.hisaddr = ip4_addr_get_u32(addr))
 #if LWIP_DNS
 /*
@@ -689,8 +687,4 @@ err_t ppp_ioctl(ppp_pcb *pcb, u8_t cmd, void *arg);
 
 #endif /* PPP_H */
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* PPP_SUPPORT */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/ppp/ppp_impl.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/ppp/ppp_impl.h b/net/ip/lwip_base/include/netif/ppp/ppp_impl.h
index 5fcc858..1d4c774 100644
--- a/net/ip/lwip_base/include/netif/ppp/ppp_impl.h
+++ b/net/ip/lwip_base/include/netif/ppp/ppp_impl.h
@@ -35,10 +35,6 @@
 
 #include "netif/ppp/ppp_opts.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */
 
 #ifdef PPP_INCLUDE_SETTINGS_HEADER
@@ -142,10 +138,10 @@ extern "C" {
  */
 struct link_callbacks {
   /* Start a connection (e.g. Initiate discovery phase) */
-  err_t (*connect) (ppp_pcb *pcb, void *ctx);
+  void (*connect) (ppp_pcb *pcb, void *ctx);
 #if PPP_SERVER
   /* Listen for an incoming connection (Passive mode) */
-  err_t (*listen) (ppp_pcb *pcb, void *ctx);
+  void (*listen) (ppp_pcb *pcb, void *ctx);
 #endif /* PPP_SERVER */
   /* End a connection (i.e. initiate disconnect phase) */
   void (*disconnect) (ppp_pcb *pcb, void *ctx);
@@ -630,8 +626,4 @@ void ppp_dump_packet(ppp_pcb *pcb, const char *tag, unsigned char *p, int len);
 
 
 #endif /* PPP_SUPPORT */
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_HDR_PPP_IMPL_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/ppp/ppp_opts.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/ppp/ppp_opts.h b/net/ip/lwip_base/include/netif/ppp/ppp_opts.h
index dee5153..fa79c09 100644
--- a/net/ip/lwip_base/include/netif/ppp/ppp_opts.h
+++ b/net/ip/lwip_base/include/netif/ppp/ppp_opts.h
@@ -30,10 +30,6 @@
 
 #include "lwip/opt.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /**
  * PPP_SUPPORT==1: Enable PPP.
  */
@@ -594,8 +590,4 @@ extern "C" {
 
 #endif /* PPP_SUPPORT */
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_PPP_OPTS_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/ppp/pppcrypt.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/ppp/pppcrypt.h b/net/ip/lwip_base/include/netif/ppp/pppcrypt.h
index 3bc9d4b..a7b2099 100644
--- a/net/ip/lwip_base/include/netif/ppp/pppcrypt.h
+++ b/net/ip/lwip_base/include/netif/ppp/pppcrypt.h
@@ -38,10 +38,6 @@
 #ifndef PPPCRYPT_H
 #define	PPPCRYPT_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /*
  * If included PolarSSL copy is not used, user is expected to include
  * external libraries in arch/cc.h (which is included by lwip/arch.h).
@@ -137,8 +133,4 @@ void pppcrypt_56_to_64_bit_key(u_char *key, u_char *des_key);
 
 #endif /* PPPCRYPT_H */
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* PPP_SUPPORT */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/ppp/pppdebug.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/ppp/pppdebug.h b/net/ip/lwip_base/include/netif/ppp/pppdebug.h
index 6b927bb..7ead045 100644
--- a/net/ip/lwip_base/include/netif/ppp/pppdebug.h
+++ b/net/ip/lwip_base/include/netif/ppp/pppdebug.h
@@ -40,10 +40,6 @@
 #ifndef PPPDEBUG_H
 #define PPPDEBUG_H
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /* Trace levels. */
 #define LOG_CRITICAL  (PPP_DEBUG | LWIP_DBG_LEVEL_SEVERE)
 #define LOG_ERR       (PPP_DEBUG | LWIP_DBG_LEVEL_SEVERE)
@@ -81,8 +77,4 @@ extern "C" {
 
 #endif /* PPPDEBUG_H */
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* PPP_SUPPORT */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/ppp/pppoe.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/ppp/pppoe.h b/net/ip/lwip_base/include/netif/ppp/pppoe.h
index 10e402d..9f8f289 100644
--- a/net/ip/lwip_base/include/netif/ppp/pppoe.h
+++ b/net/ip/lwip_base/include/netif/ppp/pppoe.h
@@ -76,10 +76,6 @@
 #include "ppp.h"
 #include "lwip/etharp.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #ifdef PACK_STRUCT_USE_INCLUDES
 #  include "arch/bpstruct.h"
 #endif
@@ -180,8 +176,4 @@ void pppoe_data_input(struct netif *netif, struct pbuf *p);
 
 #endif /* PPP_OE_H */
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* PPP_SUPPORT && PPPOE_SUPPORT */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/ppp/pppol2tp.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/ppp/pppol2tp.h b/net/ip/lwip_base/include/netif/ppp/pppol2tp.h
index 79406b0..f03950e 100644
--- a/net/ip/lwip_base/include/netif/ppp/pppol2tp.h
+++ b/net/ip/lwip_base/include/netif/ppp/pppol2tp.h
@@ -39,10 +39,6 @@
 
 #include "ppp.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /* Timeout */
 #define PPPOL2TP_CONTROL_TIMEOUT         (5*1000)  /* base for quick timeout calculation */
 #define PPPOL2TP_SLOW_RETRY              (60*1000) /* persistent retry interval */
@@ -202,8 +198,4 @@ ppp_pcb *pppol2tp_create(struct netif *pppif,
        ppp_link_status_cb_fn link_status_cb, void *ctx_cb);
 
 #endif /* PPPOL2TP_H */
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* PPP_SUPPORT && PPPOL2TP_SUPPORT */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/ppp/pppos.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/ppp/pppos.h b/net/ip/lwip_base/include/netif/ppp/pppos.h
index 6b1c995..d924a9f 100644
--- a/net/ip/lwip_base/include/netif/ppp/pppos.h
+++ b/net/ip/lwip_base/include/netif/ppp/pppos.h
@@ -42,10 +42,6 @@
 #include "ppp.h"
 #include "vj.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /* PPP packet parser states.  Current state indicates operation yet to be
  * completed. */
 enum {
@@ -119,8 +115,4 @@ err_t pppos_input_sys(struct pbuf *p, struct netif *inp);
 #endif /* !NO_SYS && !PPP_INPROC_IRQ_SAFE */
 
 #endif /* PPPOS_H */
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* PPP_SUPPORT && PPPOL2TP_SUPPORT */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/ppp/upap.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/ppp/upap.h b/net/ip/lwip_base/include/netif/ppp/upap.h
index 0d9dd1c..7da792e 100644
--- a/net/ip/lwip_base/include/netif/ppp/upap.h
+++ b/net/ip/lwip_base/include/netif/ppp/upap.h
@@ -50,10 +50,6 @@
 
 #include "ppp.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /*
  * Packet header = Code, id, length.
  */
@@ -124,8 +120,4 @@ void upap_authpeer(ppp_pcb *pcb);
 extern const struct protent pap_protent;
 
 #endif /* UPAP_H */
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* PPP_SUPPORT && PAP_SUPPORT */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/netif/ppp/vj.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/netif/ppp/vj.h b/net/ip/lwip_base/include/netif/ppp/vj.h
index b386c01..7f389c8 100644
--- a/net/ip/lwip_base/include/netif/ppp/vj.h
+++ b/net/ip/lwip_base/include/netif/ppp/vj.h
@@ -31,10 +31,6 @@
 #include "lwip/ip.h"
 #include "lwip/priv/tcp_priv.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #define MAX_SLOTS 16 /* must be > 2 and < 256 */
 #define MAX_HDR   128
 
@@ -162,8 +158,4 @@ extern int   vj_uncompress_tcp   (struct pbuf **nb, struct vjcompress *comp);
 
 #endif /* VJ_H */
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* PPP_SUPPORT && VJ_SUPPORT */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/include/posix/errno.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/include/posix/errno.h b/net/ip/lwip_base/include/posix/errno.h
new file mode 100644
index 0000000..5917c75
--- /dev/null
+++ b/net/ip/lwip_base/include/posix/errno.h
@@ -0,0 +1,33 @@
+/**
+ * @file
+ * This file is a posix wrapper for lwip/errno.h.
+ */
+
+/*
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ * 2. 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.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ *
+ * This file is part of the lwIP TCP/IP stack.
+ *
+ */
+
+#include "lwip/errno.h"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/Filelists.mk
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/Filelists.mk b/net/ip/lwip_base/src/Filelists.mk
index 2dd0d36..7d30bb8 100644
--- a/net/ip/lwip_base/src/Filelists.mk
+++ b/net/ip/lwip_base/src/Filelists.mk
@@ -164,10 +164,18 @@ MDNSFILES=$(LWIPDIR)/apps/mdns/mdns.c
 # NETBIOSNSFILES: NetBIOS name server
 NETBIOSNSFILES=$(LWIPDIR)/apps/netbiosns/netbiosns.c
 
+# TFTPFILES: TFTP server files
+TFTPFILES=$(LWIPDIR)/apps/tftp/tftp_server.c
+
+# MQTTFILES: MQTT client files
+MQTTFILES=$(LWIPDIR)/apps/mqtt/mqtt.c
+
 # LWIPAPPFILES: All LWIP APPs
 LWIPAPPFILES=$(SNMPFILES) \
 	$(HTTPDFILES) \
 	$(LWIPERFFILES) \
 	$(SNTPFILES) \
 	$(MDNSFILES) \
-	$(NETBIOSNSFILES)
+	$(NETBIOSNSFILES) \
+	$(TFTPFILES) \
+	$(MQTTFILES)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/api/api_lib.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/api/api_lib.c b/net/ip/lwip_base/src/api/api_lib.c
index 740fe39..3c1d6a6 100644
--- a/net/ip/lwip_base/src/api/api_lib.c
+++ b/net/ip/lwip_base/src/api/api_lib.c
@@ -3,7 +3,7 @@
  * Sequential API External module
  * 
  * @defgroup netconn Netconn API
- * @ingroup threadsafe_api
+ * @ingroup sequential_api
  * Thread-safe, to be called from non-TCPIP threads only.
  * TX/RX handling based on @ref netbuf (containing @ref pbuf)
  * to avoid copying data around.
@@ -241,8 +241,8 @@ netconn_getaddr(struct netconn *conn, ip_addr_t *addr, u16_t *port, u8_t local)
  * Binding one netconn twice might not always be checked correctly!
  *
  * @param conn the netconn to bind
- * @param addr the local IP address to bind the netconn to (use IP_ADDR_ANY
- *             to bind to all addresses)
+ * @param addr the local IP address to bind the netconn to 
+ *             (use IP4_ADDR_ANY/IP6_ADDR_ANY to bind to all addresses)
  * @param port the local port to bind the netconn to (not used for RAW)
  * @return ERR_OK if bound, any other err_t on failure
  */
@@ -254,10 +254,22 @@ netconn_bind(struct netconn *conn, const ip_addr_t *addr, u16_t port)
   
   LWIP_ERROR("netconn_bind: invalid conn", (conn != NULL), return ERR_ARG;);
 
+#if LWIP_IPV4
   /* Don't propagate NULL pointer (IP_ADDR_ANY alias) to subsequent functions */
   if (addr == NULL) {
-    addr = IP_ADDR_ANY;
+    addr = IP4_ADDR_ANY;
   }
+#endif /* LWIP_IPV4 */
+  
+#if LWIP_IPV4 && LWIP_IPV6
+  /* "Socket API like" dual-stack support: If IP to bind to is IP6_ADDR_ANY,
+   * and NETCONN_FLAG_IPV6_V6ONLY is 0, use IP_ANY_TYPE to bind
+   */
+  if ((netconn_get_ipv6only(conn) == 0) &&
+     ip_addr_cmp(addr, IP6_ADDR_ANY)) {
+    addr = IP_ANY_TYPE;
+  }
+#endif /* LWIP_IPV4 && LWIP_IPV6 */
 
   API_MSG_VAR_ALLOC(msg);
   API_MSG_VAR_REF(msg).conn = conn;
@@ -286,10 +298,12 @@ netconn_connect(struct netconn *conn, const ip_addr_t *addr, u16_t port)
 
   LWIP_ERROR("netconn_connect: invalid conn", (conn != NULL), return ERR_ARG;);
 
+#if LWIP_IPV4
   /* Don't propagate NULL pointer (IP_ADDR_ANY alias) to subsequent functions */
   if (addr == NULL) {
-    addr = IP_ADDR_ANY;
+    addr = IP4_ADDR_ANY;
   }
+#endif /* LWIP_IPV4 */
 
   API_MSG_VAR_ALLOC(msg);
   API_MSG_VAR_REF(msg).conn = conn;
@@ -306,7 +320,7 @@ netconn_connect(struct netconn *conn, const ip_addr_t *addr, u16_t port)
  * Disconnect a netconn from its current peer (only valid for UDP netconns).
  *
  * @param conn the netconn to disconnect
- * @return @todo: return value is not set here...
+ * @return See @ref err_t
  */
 err_t
 netconn_disconnect(struct netconn *conn)
@@ -376,7 +390,6 @@ netconn_accept(struct netconn *conn, struct netconn **new_conn)
 #if LWIP_TCP
   void *accept_ptr;
   struct netconn *newconn;
-  err_t err;
 #if TCP_LISTEN_BACKLOG
   API_MSG_VAR_DECLARE(msg);
 #endif /* TCP_LISTEN_BACKLOG */
@@ -385,11 +398,10 @@ netconn_accept(struct netconn *conn, struct netconn **new_conn)
   *new_conn = NULL;
   LWIP_ERROR("netconn_accept: invalid conn",       (conn != NULL),                      return ERR_ARG;);
 
-  err = conn->last_err;
-  if (ERR_IS_FATAL(err)) {
+  if (ERR_IS_FATAL(conn->last_err)) {
     /* don't recv on fatal errors: this might block the application task
        waiting on acceptmbox forever! */
-    return err;
+    return conn->last_err;
   }
   if (!sys_mbox_valid(&conn->acceptmbox)) {
     return ERR_CLSD;
@@ -465,7 +477,6 @@ netconn_recv_data(struct netconn *conn, void **new_buf)
 {
   void *buf = NULL;
   u16_t len;
-  err_t err;
 #if LWIP_TCP
   API_MSG_VAR_DECLARE(msg);
 #if LWIP_MPU_COMPATIBLE
@@ -489,13 +500,12 @@ netconn_recv_data(struct netconn *conn, void **new_buf)
 #endif /* LWIP_TCP */
   LWIP_ERROR("netconn_recv: invalid recvmbox", sys_mbox_valid(&conn->recvmbox), return ERR_CONN;);
 
-  err = conn->last_err;
-  if (ERR_IS_FATAL(err)) {
+  if (ERR_IS_FATAL(conn->last_err)) {
     /* don't recv on fatal errors: this might block the application task
        waiting on recvmbox forever! */
     /* @todo: this does not allow us to fetch data that has been put into recvmbox
        before the fatal error occurred - is that a problem? */
-    return err;
+    return conn->last_err;
   }
 #if LWIP_TCP
 #if (LWIP_UDP || LWIP_RAW)
@@ -544,6 +554,10 @@ netconn_recv_data(struct netconn *conn, void **new_buf)
     /* If we are closed, we indicate that we no longer wish to use the socket */
     if (buf == NULL) {
       API_EVENT(conn, NETCONN_EVT_RCVMINUS, 0);
+      if (conn->pcb.ip == NULL) {
+        /* race condition: RST during recv */
+        return conn->last_err == ERR_OK ? ERR_RST : conn->last_err;
+      }
       /* RX side is closed, so deallocate the recvmbox */
       netconn_close_shutdown(conn, NETCONN_SHUT_RD);
       /* Don' store ERR_CLSD as conn->err since we are only half-closed */
@@ -558,7 +572,7 @@ netconn_recv_data(struct netconn *conn, void **new_buf)
 #if (LWIP_UDP || LWIP_RAW)
   {
     LWIP_ASSERT("buf != NULL", buf != NULL);
-    len = netbuf_len((struct netbuf *)buf);
+    len = netbuf_len((struct netbuf*)buf);
   }
 #endif /* (LWIP_UDP || LWIP_RAW) */
 
@@ -693,6 +707,7 @@ netconn_send(struct netconn *conn, struct netbuf *buf)
   LWIP_ERROR("netconn_send: invalid conn",  (conn != NULL), return ERR_ARG;);
 
   LWIP_DEBUGF(API_LIB_DEBUG, ("netconn_send: sending %"U16_F" bytes\n", buf->p->tot_len));
+
   API_MSG_VAR_ALLOC(msg);
   API_MSG_VAR_REF(msg).conn = conn;
   API_MSG_VAR_REF(msg).msg.b = buf;
@@ -730,6 +745,11 @@ netconn_write_partly(struct netconn *conn, const void *dataptr, size_t size,
     return ERR_OK;
   }
   dontblock = netconn_is_nonblocking(conn) || (apiflags & NETCONN_DONTBLOCK);
+#if LWIP_SO_SNDTIMEO
+  if (conn->send_timeout != 0) {
+    dontblock = 1;
+  }
+#endif /* LWIP_SO_SNDTIMEO */
   if (dontblock && !bytes_written) {
     /* This implies netconn_write() cannot be used for non-blocking send, since
        it has no way to return the number of bytes written. */
@@ -757,11 +777,7 @@ netconn_write_partly(struct netconn *conn, const void *dataptr, size_t size,
      non-blocking version here. */
   err = netconn_apimsg(lwip_netconn_do_write, &API_MSG_VAR_REF(msg));
   if ((err == ERR_OK) && (bytes_written != NULL)) {
-    if (dontblock
-#if LWIP_SO_SNDTIMEO
-        || (conn->send_timeout != 0)
-#endif /* LWIP_SO_SNDTIMEO */
-       ) {
+    if (dontblock) {
       /* nonblocking write: maybe the data has been sent partly */
       *bytes_written = API_MSG_VAR_REF(msg).msg.w.len;
     } else {
@@ -865,13 +881,15 @@ netconn_join_leave_group(struct netconn *conn,
 
   API_MSG_VAR_ALLOC(msg);
 
+#if LWIP_IPV4
   /* Don't propagate NULL pointer (IP_ADDR_ANY alias) to subsequent functions */
   if (multiaddr == NULL) {
-    multiaddr = IP_ADDR_ANY;
+    multiaddr = IP4_ADDR_ANY;
   }
   if (netif_addr == NULL) {
-    netif_addr = IP_ADDR_ANY;
+    netif_addr = IP4_ADDR_ANY;
   }
+#endif /* LWIP_IPV4 */
 
   API_MSG_VAR_REF(msg).conn = conn;
   API_MSG_VAR_REF(msg).msg.jl.multiaddr = API_MSG_VAR_REF(multiaddr);
@@ -910,6 +928,7 @@ netconn_gethostbyname(const char *name, ip_addr_t *addr)
   sys_sem_t sem;
 #endif /* LWIP_MPU_COMPATIBLE */
   err_t err;
+  err_t cberr;
 
   LWIP_ERROR("netconn_gethostbyname: invalid name", (name != NULL), return ERR_ARG;);
   LWIP_ERROR("netconn_gethostbyname: invalid addr", (addr != NULL), return ERR_ARG;);
@@ -942,13 +961,13 @@ netconn_gethostbyname(const char *name, ip_addr_t *addr)
   }
 #endif /* LWIP_NETCONN_SEM_PER_THREAD */
 
-  err = tcpip_callback(lwip_netconn_do_gethostbyname, &API_VAR_REF(msg));
-  if (err != ERR_OK) {
+  cberr = tcpip_callback(lwip_netconn_do_gethostbyname, &API_VAR_REF(msg));
+  if (cberr != ERR_OK) {
 #if !LWIP_NETCONN_SEM_PER_THREAD
     sys_sem_free(API_EXPR_REF(API_VAR_REF(msg).sem));
 #endif /* !LWIP_NETCONN_SEM_PER_THREAD */
     API_VAR_FREE(MEMP_DNS_API_MSG, msg);
-    return err;
+    return cberr;
   }
   sys_sem_wait(API_EXPR_REF_SEM(API_VAR_REF(msg).sem));
 #if !LWIP_NETCONN_SEM_PER_THREAD

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/api/api_msg.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/api/api_msg.c b/net/ip/lwip_base/src/api/api_msg.c
index 9dfea64..dd99c1e 100644
--- a/net/ip/lwip_base/src/api/api_msg.c
+++ b/net/ip/lwip_base/src/api/api_msg.c
@@ -43,6 +43,7 @@
 #include "lwip/priv/api_msg.h"
 
 #include "lwip/ip.h"
+#include "lwip/ip_addr.h"
 #include "lwip/udp.h"
 #include "lwip/tcp.h"
 #include "lwip/raw.h"
@@ -540,26 +541,41 @@ accept_function(void *arg, struct tcp_pcb *newpcb, err_t err)
  * Called from lwip_netconn_do_newconn().
  *
  * @param msg the api_msg_msg describing the connection type
- * @return msg->conn->err, but the return value is currently ignored
  */
 static void
 pcb_new(struct api_msg *msg)
 {
-  LWIP_ASSERT("pcb_new: pcb already allocated", msg->conn->pcb.tcp == NULL);
+  enum lwip_ip_addr_type iptype = IPADDR_TYPE_V4;
 
+  LWIP_ASSERT("pcb_new: pcb already allocated", msg->conn->pcb.tcp == NULL);
+ 
+#if LWIP_IPV6 && LWIP_IPV4
+  /* IPv6: Dual-stack by default, unless netconn_set_ipv6only() is called */
+  if(NETCONNTYPE_ISIPV6(netconn_type(msg->conn))) {
+    iptype = IPADDR_TYPE_ANY;
+  }
+#endif
+  
   /* Allocate a PCB for this connection */
   switch(NETCONNTYPE_GROUP(msg->conn->type)) {
 #if LWIP_RAW
   case NETCONN_RAW:
-    msg->conn->pcb.raw = raw_new(msg->msg.n.proto);
+    msg->conn->pcb.raw = raw_new_ip_type(iptype, msg->msg.n.proto);
     if (msg->conn->pcb.raw != NULL) {
+#if LWIP_IPV6
+      /* ICMPv6 packets should always have checksum calculated by the stack as per RFC 3542 chapter 3.1 */
+      if (NETCONNTYPE_ISIPV6(msg->conn->type) && msg->conn->pcb.raw->protocol == IP6_NEXTH_ICMP6) {
+        msg->conn->pcb.raw->chksum_reqd = 1;
+        msg->conn->pcb.raw->chksum_offset = 2;
+      }
+#endif /* LWIP_IPV6 */
       raw_recv(msg->conn->pcb.raw, recv_raw, msg->conn);
     }
     break;
 #endif /* LWIP_RAW */
 #if LWIP_UDP
   case NETCONN_UDP:
-    msg->conn->pcb.udp = udp_new();
+    msg->conn->pcb.udp = udp_new_ip_type(iptype);
     if (msg->conn->pcb.udp != NULL) {
 #if LWIP_UDPLITE
       if (NETCONNTYPE_ISUDPLITE(msg->conn->type)) {
@@ -575,7 +591,7 @@ pcb_new(struct api_msg *msg)
 #endif /* LWIP_UDP */
 #if LWIP_TCP
   case NETCONN_TCP:
-    msg->conn->pcb.tcp = tcp_new();
+    msg->conn->pcb.tcp = tcp_new_ip_type(iptype);
     if (msg->conn->pcb.tcp != NULL) {
       setup_tcp(msg->conn);
     }
@@ -589,15 +605,6 @@ pcb_new(struct api_msg *msg)
   if (msg->conn->pcb.ip == NULL) {
     msg->err = ERR_MEM;
   }
-#if LWIP_IPV4 && LWIP_IPV6
-  else {
-    if (NETCONNTYPE_ISIPV6(msg->conn->type)) {
-      /* Convert IPv4 PCB manually to an IPv6 PCB */
-      IP_SET_TYPE_VAL(msg->conn->pcb.ip->local_ip,  IPADDR_TYPE_V6);
-      IP_SET_TYPE_VAL(msg->conn->pcb.ip->remote_ip, IPADDR_TYPE_V6);
-    }
-  }
-#endif /* LWIP_IPV4 && LWIP_IPV6 */
 }
 
 /**
@@ -781,16 +788,18 @@ netconn_drain(struct netconn *conn)
 #if LWIP_TCP
   if (sys_mbox_valid(&conn->acceptmbox)) {
     while (sys_mbox_tryfetch(&conn->acceptmbox, &mem) != SYS_MBOX_EMPTY) {
-      struct netconn *newconn = (struct netconn *)mem;
-      /* Only tcp pcbs have an acceptmbox, so no need to check conn->type */
-      /* pcb might be set to NULL already by err_tcp() */
-      /* drain recvmbox */
-      netconn_drain(newconn);
-      if (newconn->pcb.tcp != NULL) {
-        tcp_abort(newconn->pcb.tcp);
-        newconn->pcb.tcp = NULL;
+      if (mem != &netconn_aborted) {
+        struct netconn *newconn = (struct netconn *)mem;
+        /* Only tcp pcbs have an acceptmbox, so no need to check conn->type */
+        /* pcb might be set to NULL already by err_tcp() */
+        /* drain recvmbox */
+        netconn_drain(newconn);
+        if (newconn->pcb.tcp != NULL) {
+          tcp_abort(newconn->pcb.tcp);
+          newconn->pcb.tcp = NULL;
+        }
+        netconn_free(newconn);
       }
-      netconn_free(newconn);
     }
     sys_mbox_free(&conn->acceptmbox);
     sys_mbox_set_invalid(&conn->acceptmbox);
@@ -805,7 +814,6 @@ netconn_drain(struct netconn *conn)
  * places.
  *
  * @param conn the TCP netconn to close
- * [@param delay 1 if called from sent/poll (wake up calling thread on end)]
  */
 static err_t
 lwip_netconn_do_close_internal(struct netconn *conn  WRITE_DELAYED_PARAM)
@@ -1113,37 +1121,20 @@ lwip_netconn_do_bind(void *m)
   } else {
     msg->err = ERR_VAL;
     if (msg->conn->pcb.tcp != NULL) {
-      const ip_addr_t *ipaddr = API_EXPR_REF(msg->msg.bc.ipaddr);
-
-#if LWIP_IPV4 && LWIP_IPV6
-      /* "Socket API like" dual-stack support: If IP to bind to is IP6_ADDR_ANY,
-       * and NETCONN_FLAG_IPV6_V6ONLY is NOT set, use IP_ANY_TYPE to bind
-       */
-      if (ip_addr_cmp(ipaddr, IP6_ADDR_ANY) &&
-          (netconn_get_ipv6only(msg->conn) == 0)) {
-        /* change PCB type to IPADDR_TYPE_ANY */
-        IP_SET_TYPE_VAL(msg->conn->pcb.ip->local_ip,  IPADDR_TYPE_ANY);
-        IP_SET_TYPE_VAL(msg->conn->pcb.ip->remote_ip, IPADDR_TYPE_ANY);
-        
-        /* bind to IPADDR_TYPE_ANY */
-        ipaddr = IP_ANY_TYPE;
-      }
-#endif /* LWIP_IPV4 && LWIP_IPV6 */
-
       switch (NETCONNTYPE_GROUP(msg->conn->type)) {
 #if LWIP_RAW
       case NETCONN_RAW:
-        msg->err = raw_bind(msg->conn->pcb.raw, ipaddr);
+        msg->err = raw_bind(msg->conn->pcb.raw, API_EXPR_REF(msg->msg.bc.ipaddr));
         break;
 #endif /* LWIP_RAW */
 #if LWIP_UDP
       case NETCONN_UDP:
-        msg->err = udp_bind(msg->conn->pcb.udp, ipaddr, msg->msg.bc.port);
+        msg->err = udp_bind(msg->conn->pcb.udp, API_EXPR_REF(msg->msg.bc.ipaddr), msg->msg.bc.port);
         break;
 #endif /* LWIP_UDP */
 #if LWIP_TCP
       case NETCONN_TCP:
-        msg->err = tcp_bind(msg->conn->pcb.tcp, ipaddr, msg->msg.bc.port);
+        msg->err = tcp_bind(msg->conn->pcb.tcp, API_EXPR_REF(msg->msg.bc.ipaddr), msg->msg.bc.port);
         break;
 #endif /* LWIP_TCP */
       default:
@@ -1323,6 +1314,13 @@ lwip_netconn_do_listen(void *m)
             /* connection is not closed, cannot listen */
             msg->err = ERR_VAL;
           } else {
+            err_t err;
+            u8_t backlog;
+#if TCP_LISTEN_BACKLOG
+            backlog = msg->msg.lb.backlog;
+#else  /* TCP_LISTEN_BACKLOG */
+            backlog = TCP_DEFAULT_LISTEN_BACKLOG;
+#endif /* TCP_LISTEN_BACKLOG */
 #if LWIP_IPV4 && LWIP_IPV6
             /* "Socket API like" dual-stack support: If IP to listen to is IP6_ADDR_ANY,
              * and NETCONN_FLAG_IPV6_V6ONLY is NOT set, use IP_ANY_TYPE to listen
@@ -1335,15 +1333,11 @@ lwip_netconn_do_listen(void *m)
             }
 #endif /* LWIP_IPV4 && LWIP_IPV6 */
 
-#if TCP_LISTEN_BACKLOG
-            lpcb = tcp_listen_with_backlog(msg->conn->pcb.tcp, msg->msg.lb.backlog);
-#else  /* TCP_LISTEN_BACKLOG */
-            lpcb = tcp_listen(msg->conn->pcb.tcp);
-#endif /* TCP_LISTEN_BACKLOG */
+            lpcb = tcp_listen_with_backlog_and_err(msg->conn->pcb.tcp, backlog, &err);
 
             if (lpcb == NULL) {
               /* in this case, the old pcb is still allocated */
-              msg->err = ERR_MEM;
+              msg->err = err;
             } else {
               /* delete the recvmbox and allocate the acceptmbox */
               if (sys_mbox_valid(&msg->conn->recvmbox)) {
@@ -1400,7 +1394,7 @@ lwip_netconn_do_send(void *m)
       switch (NETCONNTYPE_GROUP(msg->conn->type)) {
 #if LWIP_RAW
       case NETCONN_RAW:
-        if (ip_addr_isany(&msg->msg.b->addr)) {
+        if (ip_addr_isany(&msg->msg.b->addr) || IP_IS_ANY_TYPE_VAL(msg->msg.b->addr)) {
           msg->err = raw_send(msg->conn->pcb.raw, msg->msg.b->p);
         } else {
           msg->err = raw_sendto(msg->conn->pcb.raw, msg->msg.b->p, &msg->msg.b->addr);
@@ -1490,7 +1484,6 @@ lwip_netconn_do_accepted(void *m)
  * blocking application thread (waiting in netconn_write) is released.
  *
  * @param conn netconn (that is currently in state NETCONN_WRITE) to process
- * [@param delay 1 if called from sent/poll (wake up calling thread on end)]
  * @return ERR_OK
  *         ERR_MEM if LWIP_TCPIP_CORE_LOCKING=1 and sending hasn't yet finished
  */
@@ -1512,9 +1505,8 @@ lwip_netconn_do_writemore(struct netconn *conn  WRITE_DELAYED_PARAM)
   LWIP_ASSERT("conn->write_offset < conn->current_msg->msg.w.len",
     conn->write_offset < conn->current_msg->msg.w.len);
 
-  dontblock = netconn_is_nonblocking(conn) ||
-       (conn->current_msg->msg.w.apiflags & NETCONN_DONTBLOCK);
   apiflags = conn->current_msg->msg.w.apiflags;
+  dontblock = netconn_is_nonblocking(conn) || (apiflags & NETCONN_DONTBLOCK);
 
 #if LWIP_SO_SNDTIMEO
   if ((conn->send_timeout != 0) &&
@@ -1590,10 +1582,11 @@ err_mem:
         write_finished = 1;
         conn->current_msg->msg.w.len = 0;
       }
-    } else if ((err == ERR_MEM) && !dontblock) {
-      /* If ERR_MEM, we wait for sent_tcp or poll_tcp to be called
-         we do NOT return to the application thread, since ERR_MEM is
-         only a temporary error! */
+    } else if (err == ERR_MEM) {
+      /* If ERR_MEM, we wait for sent_tcp or poll_tcp to be called.
+         For blocking sockets, we do NOT return to the application
+         thread, since ERR_MEM is only a temporary error! Non-blocking
+         will remain non-writable until sent_tcp/poll_tcp is called */
 
       /* tcp_write returned ERR_MEM, try tcp_output anyway */
       err_t out_err = tcp_output(conn->pcb.tcp);
@@ -1604,7 +1597,11 @@ err_mem:
         err = out_err;
         write_finished = 1;
         conn->current_msg->msg.w.len = 0;
-      } else {
+      } else if (dontblock) {
+        /* non-blocking write is done on ERR_MEM */
+        err = ERR_WOULDBLOCK;
+        write_finished = 1;
+        conn->current_msg->msg.w.len = 0;
       }
     } else {
       /* On errors != ERR_MEM, we don't try writing any more but return
@@ -1713,6 +1710,7 @@ lwip_netconn_do_getaddr(void *m)
       ip_addr_copy(API_EXPR_DEREF(msg->msg.ad.ipaddr),
         msg->conn->pcb.ip->remote_ip);
     }
+
     msg->err = ERR_OK;
     switch (NETCONNTYPE_GROUP(msg->conn->type)) {
 #if LWIP_RAW
@@ -1786,25 +1784,28 @@ lwip_netconn_do_close(void *m)
 #if LWIP_NETCONN_FULLDUPLEX
       if (msg->msg.sd.shut & NETCONN_SHUT_WR) {
         /* close requested, abort running write */
-        sys_sem_t* op_completed_sem;
+        sys_sem_t* write_completed_sem;
         LWIP_ASSERT("msg->conn->current_msg != NULL", msg->conn->current_msg != NULL);
-        op_completed_sem = LWIP_API_MSG_SEM(msg->conn->current_msg);
+        write_completed_sem = LWIP_API_MSG_SEM(msg->conn->current_msg);
         msg->conn->current_msg->err = ERR_CLSD;
         msg->conn->current_msg = NULL;
         msg->conn->write_offset = 0;
         msg->conn->state = NETCONN_NONE;
+        state = NETCONN_NONE;
         NETCONN_SET_SAFE_ERR(msg->conn, ERR_CLSD);
-        sys_sem_signal(op_completed_sem);
+        sys_sem_signal(write_completed_sem);
       } else {
         LWIP_ASSERT("msg->msg.sd.shut == NETCONN_SHUT_RD", msg->msg.sd.shut == NETCONN_SHUT_RD);
         /* In this case, let the write continue and do not interfere with
            conn->current_msg or conn->state! */
         msg->err = tcp_shutdown(msg->conn->pcb.tcp, 1, 0);
       }
+    }
+    if (state == NETCONN_NONE) {
 #else /* LWIP_NETCONN_FULLDUPLEX */
       msg->err = ERR_INPROGRESS;
-#endif /* LWIP_NETCONN_FULLDUPLEX */
     } else {
+#endif /* LWIP_NETCONN_FULLDUPLEX */
       if (msg->msg.sd.shut & NETCONN_SHUT_RD) {
         /* Drain and delete mboxes */
         netconn_drain(msg->conn);

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/api/err.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/api/err.c b/net/ip/lwip_base/src/api/err.c
index f3650f4..35e9c02 100644
--- a/net/ip/lwip_base/src/api/err.c
+++ b/net/ip/lwip_base/src/api/err.c
@@ -37,6 +37,43 @@
  */
 
 #include "lwip/err.h"
+#include "lwip/def.h"
+#include "lwip/sys.h"
+
+#include "lwip/errno.h"
+
+#if !NO_SYS
+/** Table to quickly map an lwIP error (err_t) to a socket error
+  * by using -err as an index */
+static const int err_to_errno_table[] = {
+  0,             /* ERR_OK          0      No error, everything OK. */
+  ENOMEM,        /* ERR_MEM        -1      Out of memory error.     */
+  ENOBUFS,       /* ERR_BUF        -2      Buffer error.            */
+  EWOULDBLOCK,   /* ERR_TIMEOUT    -3      Timeout                  */
+  EHOSTUNREACH,  /* ERR_RTE        -4      Routing problem.         */
+  EINPROGRESS,   /* ERR_INPROGRESS -5      Operation in progress    */
+  EINVAL,        /* ERR_VAL        -6      Illegal value.           */
+  EWOULDBLOCK,   /* ERR_WOULDBLOCK -7      Operation would block.   */
+  EADDRINUSE,    /* ERR_USE        -8      Address in use.          */
+  EALREADY,      /* ERR_ALREADY    -9      Already connecting.      */
+  EISCONN,       /* ERR_ISCONN     -10     Conn already established.*/
+  ENOTCONN,      /* ERR_CONN       -11     Not connected.           */
+  -1,            /* ERR_IF         -12     Low-level netif error    */
+  ECONNABORTED,  /* ERR_ABRT       -13     Connection aborted.      */
+  ECONNRESET,    /* ERR_RST        -14     Connection reset.        */
+  ENOTCONN,      /* ERR_CLSD       -15     Connection closed.       */
+  EIO            /* ERR_ARG        -16     Illegal argument.        */
+};
+
+int
+err_to_errno(err_t err)
+{
+  if ((err > 0) || (-err >= (err_t)LWIP_ARRAYSIZE(err_to_errno_table))) {
+    return EIO;
+  }
+  return err_to_errno_table[-err];
+}
+#endif /* !NO_SYS */
 
 #ifdef LWIP_DEBUG
 
@@ -69,6 +106,9 @@ static const char *err_strerr[] = {
 const char *
 lwip_strerr(err_t err)
 {
+  if ((err > 0) || (-err >= (err_t)LWIP_ARRAYSIZE(err_strerr))) {
+    return "Unknown error.";
+  }
   return err_strerr[-err];
 }
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/api/netdb.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/api/netdb.c b/net/ip/lwip_base/src/api/netdb.c
index 670f6b9..ccd9586 100644
--- a/net/ip/lwip_base/src/api/netdb.c
+++ b/net/ip/lwip_base/src/api/netdb.c
@@ -46,8 +46,8 @@
 #include "lwip/api.h"
 #include "lwip/dns.h"
 
-#include <string.h>
-#include <stdlib.h>
+#include <string.h> /* memset */
+#include <stdlib.h> /* atoi */
 
 /** helper struct for gethostbyname_r to access the char* buffer */
 struct gethostbyname_r_helper {
@@ -375,17 +375,17 @@ lwip_getaddrinfo(const char *nodename, const char *servname,
     inet6_addr_from_ip6addr(&sa6->sin6_addr, ip_2_ip6(&addr));
     sa6->sin6_family = AF_INET6;
     sa6->sin6_len = sizeof(struct sockaddr_in6);
-    sa6->sin6_port = htons((u16_t)port_nr);
+    sa6->sin6_port = lwip_htons((u16_t)port_nr);
     ai->ai_family = AF_INET6;
 #endif /* LWIP_IPV6 */
   } else {
 #if LWIP_IPV4
     struct sockaddr_in *sa4 = (struct sockaddr_in*)sa;
     /* set up sockaddr */
-    inet_addr_from_ipaddr(&sa4->sin_addr, ip_2_ip4(&addr));
+    inet_addr_from_ip4addr(&sa4->sin_addr, ip_2_ip4(&addr));
     sa4->sin_family = AF_INET;
     sa4->sin_len = sizeof(struct sockaddr_in);
-    sa4->sin_port = htons((u16_t)port_nr);
+    sa4->sin_port = lwip_htons((u16_t)port_nr);
     ai->ai_family = AF_INET;
 #endif /* LWIP_IPV4 */
   }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/api/netifapi.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/api/netifapi.c b/net/ip/lwip_base/src/api/netifapi.c
index 265b60c..fef05a3 100644
--- a/net/ip/lwip_base/src/api/netifapi.c
+++ b/net/ip/lwip_base/src/api/netifapi.c
@@ -3,7 +3,7 @@
  * Network Interface Sequential API module
  *
  * @defgroup netifapi NETIF API
- * @ingroup threadsafe_api
+ * @ingroup sequential_api
  * Thread-safe functions to be called from non-TCPIP threads
  * 
  * @defgroup netifapi_netif NETIF related
@@ -134,13 +134,13 @@ netifapi_netif_add(struct netif *netif,
 
 #if LWIP_IPV4
   if (ipaddr == NULL) {
-    ipaddr = IP4_ADDR_ANY;
+    ipaddr = IP4_ADDR_ANY4;
   }
   if (netmask == NULL) {
-    netmask = IP4_ADDR_ANY;
+    netmask = IP4_ADDR_ANY4;
   }
   if (gw == NULL) {
-    gw = IP4_ADDR_ANY;
+    gw = IP4_ADDR_ANY4;
   }
 #endif /* LWIP_IPV4 */
 
@@ -177,13 +177,13 @@ netifapi_netif_set_addr(struct netif *netif,
   NETIFAPI_VAR_ALLOC(msg);
 
   if (ipaddr == NULL) {
-    ipaddr = IP4_ADDR_ANY;
+    ipaddr = IP4_ADDR_ANY4;
   }
   if (netmask == NULL) {
-    netmask = IP4_ADDR_ANY;
+    netmask = IP4_ADDR_ANY4;
   }
   if (gw == NULL) {
-    gw = IP4_ADDR_ANY;
+    gw = IP4_ADDR_ANY4;
   }
 
   NETIFAPI_VAR_REF(msg).netif = netif;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/api/sockets.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/api/sockets.c b/net/ip/lwip_base/src/api/sockets.c
index 72e777d..b763248 100644
--- a/net/ip/lwip_base/src/api/sockets.c
+++ b/net/ip/lwip_base/src/api/sockets.c
@@ -3,7 +3,7 @@
  * Sockets BSD-Like API module
  *
  * @defgroup socket Socket API
- * @ingroup threadsafe_api
+ * @ingroup sequential_api
  * BSD-style socket API.\n
  * Thread-safe, to be called from non-TCPIP threads only.\n
  * Can be activated by defining @ref LWIP_SOCKET to 1.\n
@@ -81,25 +81,25 @@
 #define IP4ADDR_PORT_TO_SOCKADDR(sin, ipaddr, port) do { \
       (sin)->sin_len = sizeof(struct sockaddr_in); \
       (sin)->sin_family = AF_INET; \
-      (sin)->sin_port = htons((port)); \
-      inet_addr_from_ipaddr(&(sin)->sin_addr, ipaddr); \
+      (sin)->sin_port = lwip_htons((port)); \
+      inet_addr_from_ip4addr(&(sin)->sin_addr, ipaddr); \
       memset((sin)->sin_zero, 0, SIN_ZERO_LEN); }while(0)
 #define SOCKADDR4_TO_IP4ADDR_PORT(sin, ipaddr, port) do { \
-    inet_addr_to_ipaddr(ip_2_ip4(ipaddr), &((sin)->sin_addr)); \
-    (port) = ntohs((sin)->sin_port); }while(0)
+    inet_addr_to_ip4addr(ip_2_ip4(ipaddr), &((sin)->sin_addr)); \
+    (port) = lwip_ntohs((sin)->sin_port); }while(0)
 #endif /* LWIP_IPV4 */
 
 #if LWIP_IPV6
 #define IP6ADDR_PORT_TO_SOCKADDR(sin6, ipaddr, port) do { \
       (sin6)->sin6_len = sizeof(struct sockaddr_in6); \
       (sin6)->sin6_family = AF_INET6; \
-      (sin6)->sin6_port = htons((port)); \
+      (sin6)->sin6_port = lwip_htons((port)); \
       (sin6)->sin6_flowinfo = 0; \
       inet6_addr_from_ip6addr(&(sin6)->sin6_addr, ipaddr); \
       (sin6)->sin6_scope_id = 0; }while(0)
 #define SOCKADDR6_TO_IP6ADDR_PORT(sin6, ipaddr, port) do { \
     inet6_addr_to_ip6addr(ip_2_ip6(ipaddr), &((sin6)->sin6_addr)); \
-    (port) = ntohs((sin6)->sin6_port); }while(0)
+    (port) = lwip_ntohs((sin6)->sin6_port); }while(0)
 #endif /* LWIP_IPV6 */
 
 #if LWIP_IPV4 && LWIP_IPV6
@@ -266,8 +266,8 @@ union sockaddr_aligned {
 /* This is to keep track of IP_ADD_MEMBERSHIP calls to drop the membership when
    a socket is closed */
 struct lwip_socket_multicast_pair {
-  /** the socket (+1 to not require initialization) */
-  int sa;
+  /** the socket */
+  struct lwip_sock* sock;
   /** the interface address */
   ip4_addr_t if_addr;
   /** the group address */
@@ -289,34 +289,6 @@ static struct lwip_select_cb *select_cb_list;
     and checked in event_callback to see if it has changed. */
 static volatile int select_cb_ctr;
 
-/** Table to quickly map an lwIP error (err_t) to a socket error
-  * by using -err as an index */
-static const int err_to_errno_table[] = {
-  0,             /* ERR_OK          0      No error, everything OK. */
-  ENOMEM,        /* ERR_MEM        -1      Out of memory error.     */
-  ENOBUFS,       /* ERR_BUF        -2      Buffer error.            */
-  EWOULDBLOCK,   /* ERR_TIMEOUT    -3      Timeout                  */
-  EHOSTUNREACH,  /* ERR_RTE        -4      Routing problem.         */
-  EINPROGRESS,   /* ERR_INPROGRESS -5      Operation in progress    */
-  EINVAL,        /* ERR_VAL        -6      Illegal value.           */
-  EWOULDBLOCK,   /* ERR_WOULDBLOCK -7      Operation would block.   */
-  EADDRINUSE,    /* ERR_USE        -8      Address in use.          */
-  EALREADY,      /* ERR_ALREADY    -9      Already connecting.      */
-  EISCONN,       /* ERR_ISCONN     -10     Conn already established.*/
-  ENOTCONN,      /* ERR_CONN       -11     Not connected.           */
-  -1,            /* ERR_IF         -12     Low-level netif error    */
-  ECONNABORTED,  /* ERR_ABRT       -13     Connection aborted.      */
-  ECONNRESET,    /* ERR_RST        -14     Connection reset.        */
-  ENOTCONN,      /* ERR_CLSD       -15     Connection closed.       */
-  EIO            /* ERR_ARG        -16     Illegal argument.        */
-};
-
-#define ERR_TO_ERRNO_TABLE_SIZE LWIP_ARRAYSIZE(err_to_errno_table)
-
-#define err_to_errno(err) \
-  ((unsigned)(-(signed)(err)) < ERR_TO_ERRNO_TABLE_SIZE ? \
-    err_to_errno_table[-(signed)(err)] : EIO)
-
 #if LWIP_SOCKET_SET_ERRNO
 #ifndef set_errno
 #define set_errno(err) do { if (err) { errno = (err); } } while(0)
@@ -435,7 +407,7 @@ alloc_socket(struct netconn *newconn, int accepted)
   for (i = 0; i < NUM_SOCKETS; ++i) {
     /* Protect socket array */
     SYS_ARCH_PROTECT(lev);
-    if (!sockets[i].conn) {
+    if (!sockets[i].conn && (sockets[i].select_waiting == 0)) {
       sockets[i].conn       = newconn;
       /* The socket is not yet known to anyone, so no need to protect
          after having marked it as used. */
@@ -448,7 +420,6 @@ alloc_socket(struct netconn *newconn, int accepted)
       sockets[i].sendevent  = (NETCONNTYPE_GROUP(newconn->type) == NETCONN_TCP ? (accepted != 0) : 1);
       sockets[i].errevent   = 0;
       sockets[i].err        = 0;
-      sockets[i].select_waiting = 0;
       return i + LWIP_SOCKET_OFFSET;
     }
     SYS_ARCH_UNPROTECT(lev);
@@ -510,7 +481,7 @@ lwip_accept(int s, struct sockaddr *addr, socklen_t *addrlen)
 
   if (netconn_is_nonblocking(sock->conn) && (sock->rcvevent <= 0)) {
     LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_accept(%d): returning EWOULDBLOCK\n", s));
-    sock_set_errno(sock, EWOULDBLOCK);
+    set_errno(EWOULDBLOCK);
     return -1;
   }
 
@@ -612,6 +583,14 @@ lwip_bind(int s, const struct sockaddr *name, socklen_t namelen)
   ip_addr_debug_print_val(SOCKETS_DEBUG, local_addr);
   LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F")\n", local_port));
 
+#if LWIP_IPV4 && LWIP_IPV6
+  /* Dual-stack: Unmap IPv4 mapped IPv6 addresses */
+  if (IP_IS_V6_VAL(local_addr) && ip6_addr_isipv4mappedipv6(ip_2_ip6(&local_addr))) {
+    unmap_ipv4_mapped_ipv6(ip_2_ip4(&local_addr), ip_2_ip6(&local_addr));
+    IP_SET_TYPE_VAL(local_addr, IPADDR_TYPE_V4);
+  }
+#endif /* LWIP_IPV4 && LWIP_IPV6 */
+
   err = netconn_bind(sock->conn, &local_addr, local_port);
 
   if (err != ERR_OK) {
@@ -696,6 +675,14 @@ lwip_connect(int s, const struct sockaddr *name, socklen_t namelen)
     ip_addr_debug_print_val(SOCKETS_DEBUG, remote_addr);
     LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F")\n", remote_port));
 
+#if LWIP_IPV4 && LWIP_IPV6
+    /* Dual-stack: Unmap IPv4 mapped IPv6 addresses */
+    if (IP_IS_V6_VAL(remote_addr) && ip6_addr_isipv4mappedipv6(ip_2_ip6(&remote_addr))) {
+      unmap_ipv4_mapped_ipv6(ip_2_ip4(&remote_addr), ip_2_ip6(&remote_addr));
+      IP_SET_TYPE_VAL(remote_addr, IPADDR_TYPE_V4);
+    }
+#endif /* LWIP_IPV4 && LWIP_IPV6 */
+
     err = netconn_connect(sock->conn, &remote_addr, remote_port);
   }
 
@@ -783,7 +770,7 @@ lwip_recvfrom(int s, void *mem, size_t len, int flags,
           return off;
         }
         LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d): returning EWOULDBLOCK\n", s));
-        sock_set_errno(sock, EWOULDBLOCK);
+        set_errno(EWOULDBLOCK);
         return -1;
       }
 
@@ -875,6 +862,15 @@ lwip_recvfrom(int s, void *mem, size_t len, int flags,
           port = netbuf_fromport((struct netbuf *)buf);
           fromaddr = netbuf_fromaddr((struct netbuf *)buf);
         }
+
+#if LWIP_IPV4 && LWIP_IPV6
+        /* Dual-stack: Map IPv4 addresses to IPv4 mapped IPv6 */
+        if (NETCONNTYPE_ISIPV6(netconn_type(sock->conn)) && IP_IS_V4(fromaddr)) {
+          ip4_2_ipv4_mapped_ipv6(ip_2_ip6(fromaddr), ip_2_ip4(fromaddr));
+          IP_SET_TYPE(fromaddr, IPADDR_TYPE_V6);
+        }
+#endif /* LWIP_IPV4 && LWIP_IPV6 */
+
         IPADDR_PORT_TO_SOCKADDR(&saddr, fromaddr, port);
         ip_addr_debug_print(SOCKETS_DEBUG, fromaddr);
         LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F" len=%d\n", port, off));
@@ -998,6 +994,10 @@ lwip_sendmsg(int s, const struct msghdr *msg, int flags)
     ((flags & MSG_DONTWAIT) ? NETCONN_DONTBLOCK : 0);
 
     for (i = 0; i < msg->msg_iovlen; i++) {
+      u8_t apiflags = write_flags;
+      if (i + 1 < msg->msg_iovlen) {
+        apiflags |= NETCONN_MORE;
+      }
       written = 0;
       err = netconn_write_partly(sock->conn, msg->msg_iov[i].iov_base, msg->msg_iov[i].iov_len, write_flags, &written);
       if (err == ERR_OK) {
@@ -1094,6 +1094,14 @@ lwip_sendmsg(int s, const struct msghdr *msg, int flags)
 #endif /* LWIP_NETIF_TX_SINGLE_PBUF */
 
     if (err == ERR_OK) {
+#if LWIP_IPV4 && LWIP_IPV6
+      /* Dual-stack: Unmap IPv4 mapped IPv6 addresses */
+      if (IP_IS_V6_VAL(chain_buf->addr) && ip6_addr_isipv4mappedipv6(ip_2_ip6(&chain_buf->addr))) {
+        unmap_ipv4_mapped_ipv6(ip_2_ip4(&chain_buf->addr), ip_2_ip6(&chain_buf->addr));
+        IP_SET_TYPE_VAL(chain_buf->addr, IPADDR_TYPE_V4);
+      }
+#endif /* LWIP_IPV4 && LWIP_IPV6 */
+
       /* send the data */
       err = netconn_send(sock->conn, chain_buf);
     }
@@ -1135,12 +1143,6 @@ lwip_sendto(int s, const void *data, size_t size, int flags,
 #endif /* LWIP_TCP */
   }
 
-  if ((to != NULL) && !SOCK_ADDR_TYPE_MATCH(to, sock)) {
-    /* sockaddr does not match socket type (IPv4/IPv6) */
-    sock_set_errno(sock, err_to_errno(ERR_VAL));
-    return -1;
-  }
-
   /* @todo: split into multiple sendto's? */
   LWIP_ASSERT("lwip_sendto: size must fit in u16_t", size <= 0xffff);
   short_size = (u16_t)size;
@@ -1190,6 +1192,14 @@ lwip_sendto(int s, const void *data, size_t size, int flags,
   err = netbuf_ref(&buf, data, short_size);
 #endif /* LWIP_NETIF_TX_SINGLE_PBUF */
   if (err == ERR_OK) {
+#if LWIP_IPV4 && LWIP_IPV6
+    /* Dual-stack: Unmap IPv4 mapped IPv6 addresses */
+    if (IP_IS_V6_VAL(buf.addr) && ip6_addr_isipv4mappedipv6(ip_2_ip6(&buf.addr))) {
+      unmap_ipv4_mapped_ipv6(ip_2_ip4(&buf.addr), ip_2_ip6(&buf.addr));
+      IP_SET_TYPE_VAL(buf.addr, IPADDR_TYPE_V4);
+    }
+#endif /* LWIP_IPV4 && LWIP_IPV6 */
+
     /* send the data */
     err = netconn_send(sock->conn, &buf);
   }
@@ -1207,9 +1217,7 @@ lwip_socket(int domain, int type, int protocol)
   struct netconn *conn;
   int i;
 
-#if !LWIP_IPV6
   LWIP_UNUSED_ARG(domain); /* @todo: check this */
-#endif /* LWIP_IPV6 */
 
   /* create a netconn */
   switch (type) {
@@ -1272,7 +1280,7 @@ lwip_writev(int s, const struct iovec *iov, int iovcnt)
   msg.msg_namelen = 0;
   /* Hack: we have to cast via number to cast from 'const' pointer to non-const.
      Blame the opengroup standard for this inconsistency. */
-  msg.msg_iov = (struct iovec *)(size_t)iov;
+  msg.msg_iov = LWIP_CONST_CAST(struct iovec *, iov);
   msg.msg_iovlen = iovcnt;
   msg.msg_control = NULL;
   msg.msg_controllen = 0;
@@ -1286,12 +1294,12 @@ lwip_writev(int s, const struct iovec *iov, int iovcnt)
  * the sockets enabled that had events.
  *
  * @param maxfdp1 the highest socket index in the sets
- * @param readset_in:    set of sockets to check for read events
- * @param writeset_in:   set of sockets to check for write events
- * @param exceptset_in:  set of sockets to check for error events
- * @param readset_out:   set of sockets that had read events
- * @param writeset_out:  set of sockets that had write events
- * @param exceptset_out: set os sockets that had error events
+ * @param readset_in    set of sockets to check for read events
+ * @param writeset_in   set of sockets to check for write events
+ * @param exceptset_in  set of sockets to check for error events
+ * @param readset_out   set of sockets that had read events
+ * @param writeset_out  set of sockets that had write events
+ * @param exceptset_out set os sockets that had error events
  * @return number of sockets that had events (read/write/exception) (>= 0)
  */
 static int
@@ -1485,9 +1493,7 @@ lwip_select(int maxfdp1, fd_set *readset, fd_set *writeset, fd_set *exceptset,
         SYS_ARCH_PROTECT(lev);
         sock = tryget_socket(i);
         if (sock != NULL) {
-          /* @todo: what if this is a new socket (reallocated?) in this case,
-             select_waiting-- would be wrong (a global 'sockalloc' counter,
-             stored per socket could help) */
+          /* for now, handle select_waiting==0... */
           LWIP_ASSERT("sock->select_waiting > 0", sock->select_waiting > 0);
           if (sock->select_waiting > 0) {
             sock->select_waiting--;
@@ -1679,8 +1685,7 @@ again:
 }
 
 /**
- * Unimplemented: Close one end of a full-duplex connection.
- * Currently, the full connection is closed.
+ * Close one end of a full-duplex connection.
  */
 int
 lwip_shutdown(int s, int how)
@@ -1738,12 +1743,21 @@ lwip_getaddrname(int s, struct sockaddr *name, socklen_t *namelen, u8_t local)
   }
 
   /* get the IP address and port */
-  /* @todo: this does not work for IPv6, yet */
   err = netconn_getaddr(sock->conn, &naddr, &port, local);
   if (err != ERR_OK) {
     sock_set_errno(sock, err_to_errno(err));
     return -1;
   }
+
+#if LWIP_IPV4 && LWIP_IPV6
+  /* Dual-stack: Map IPv4 addresses to IPv4 mapped IPv6 */
+  if (NETCONNTYPE_ISIPV6(netconn_type(sock->conn)) &&
+      IP_IS_V4_VAL(naddr)) {
+    ip4_2_ipv4_mapped_ipv6(ip_2_ip6(&naddr), ip_2_ip4(&naddr));
+    IP_SET_TYPE_VAL(naddr, IPADDR_TYPE_V6);
+  }
+#endif /* LWIP_IPV4 && LWIP_IPV6 */
+
   IPADDR_PORT_TO_SOCKADDR(&saddr, &naddr, port);
 
   LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getaddrname(%d, addr=", s));
@@ -2029,7 +2043,7 @@ lwip_getsockopt_impl(int s, int level, int optname, void *optval, socklen_t *opt
       if (NETCONNTYPE_GROUP(netconn_type(sock->conn)) != NETCONN_UDP) {
         return ENOPROTOOPT;
       }
-      inet_addr_from_ipaddr((struct in_addr*)optval, udp_get_multicast_netif_addr(sock->conn->pcb.udp));
+      inet_addr_from_ip4addr((struct in_addr*)optval, udp_get_multicast_netif_addr(sock->conn->pcb.udp));
       LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, IP_MULTICAST_IF) = 0x%"X32_F"\n",
                   s, *(u32_t *)optval));
       break;
@@ -2057,6 +2071,9 @@ lwip_getsockopt_impl(int s, int level, int optname, void *optval, socklen_t *opt
   case IPPROTO_TCP:
     /* Special case: all IPPROTO_TCP option take an int */
     LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB_TYPE(sock, *optlen, int, NETCONN_TCP);
+    if (sock->conn->pcb.tcp->state == LISTEN) {
+      return EINVAL;
+    }
     switch (optname) {
     case TCP_NODELAY:
       *(int*)optval = tcp_nagle_disabled(sock->conn->pcb.tcp);
@@ -2101,10 +2118,6 @@ lwip_getsockopt_impl(int s, int level, int optname, void *optval, socklen_t *opt
     switch (optname) {
     case IPV6_V6ONLY:
       LWIP_SOCKOPT_CHECK_OPTLEN_CONN(sock, *optlen, int);
-      /* @todo: this does not work for datagram sockets, yet */
-      if (NETCONNTYPE_GROUP(netconn_type(sock->conn)) != NETCONN_TCP) {
-        return ENOPROTOOPT;
-      }
       *(int*)optval = (netconn_get_ipv6only(sock->conn) ? 1 : 0);
       LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IPV6, IPV6_V6ONLY) = %d\n",
                   s, *(int *)optval));
@@ -2393,7 +2406,7 @@ lwip_setsockopt_impl(int s, int level, int optname, const void *optval, socklen_
       {
         ip4_addr_t if_addr;
         LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB_TYPE(sock, optlen, struct in_addr, NETCONN_UDP);
-        inet_addr_to_ipaddr(&if_addr, (const struct in_addr*)optval);
+        inet_addr_to_ip4addr(&if_addr, (const struct in_addr*)optval);
         udp_set_multicast_netif_addr(sock->conn->pcb.udp, &if_addr);
       }
       break;
@@ -2417,8 +2430,8 @@ lwip_setsockopt_impl(int s, int level, int optname, const void *optval, socklen_
         ip4_addr_t if_addr;
         ip4_addr_t multi_addr;
         LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB_TYPE(sock, optlen, struct ip_mreq, NETCONN_UDP);
-        inet_addr_to_ipaddr(&if_addr, &imr->imr_interface);
-        inet_addr_to_ipaddr(&multi_addr, &imr->imr_multiaddr);
+        inet_addr_to_ip4addr(&if_addr, &imr->imr_interface);
+        inet_addr_to_ip4addr(&multi_addr, &imr->imr_multiaddr);
         if (optname == IP_ADD_MEMBERSHIP) {
           if (!lwip_socket_register_membership(s, &if_addr, &multi_addr)) {
             /* cannot track membership (out of memory) */
@@ -2450,6 +2463,9 @@ lwip_setsockopt_impl(int s, int level, int optname, const void *optval, socklen_
   case IPPROTO_TCP:
     /* Special case: all IPPROTO_TCP option take an int */
     LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB_TYPE(sock, optlen, int, NETCONN_TCP);
+    if (sock->conn->pcb.tcp->state == LISTEN) {
+      return EINVAL;
+    }
     switch (optname) {
     case TCP_NODELAY:
       if (*(const int*)optval) {
@@ -2497,7 +2513,6 @@ lwip_setsockopt_impl(int s, int level, int optname, const void *optval, socklen_
   case IPPROTO_IPV6:
     switch (optname) {
     case IPV6_V6ONLY:
-      /* @todo: this does not work for datagram sockets, yet */
       LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB_TYPE(sock, optlen, int, NETCONN_TCP);
       if (*(const int*)optval) {
         netconn_set_ipv6only(sock->conn, 1);
@@ -2559,6 +2574,12 @@ lwip_setsockopt_impl(int s, int level, int optname, const void *optval, socklen_
     switch (optname) {
 #if LWIP_IPV6 && LWIP_RAW
     case IPV6_CHECKSUM:
+      /* It should not be possible to disable the checksum generation with ICMPv6
+       * as per RFC 3542 chapter 3.1 */
+      if(sock->conn->pcb.raw->protocol == IPPROTO_ICMPV6) {
+        return EINVAL;
+      }
+
       LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB_TYPE(sock, optlen, int, NETCONN_RAW);
       if (*(const int *)optval < 0) {
         sock->conn->pcb.raw->chksum_reqd = 0;
@@ -2730,14 +2751,16 @@ lwip_fcntl(int s, int cmd, int val)
 static int
 lwip_socket_register_membership(int s, const ip4_addr_t *if_addr, const ip4_addr_t *multi_addr)
 {
-  /* s+1 is stored in the array to prevent having to initialize the array
-     (default initialization is to 0) */
-  int sa = s + 1;
+  struct lwip_sock *sock = get_socket(s);
   int i;
 
+  if (!sock) {
+    return 0;
+  }
+
   for (i = 0; i < LWIP_SOCKET_MAX_MEMBERSHIPS; i++) {
-    if (socket_ipv4_multicast_memberships[i].sa == 0) {
-      socket_ipv4_multicast_memberships[i].sa = sa;
+    if (socket_ipv4_multicast_memberships[i].sock == NULL) {
+      socket_ipv4_multicast_memberships[i].sock = sock;
       ip4_addr_copy(socket_ipv4_multicast_memberships[i].if_addr, *if_addr);
       ip4_addr_copy(socket_ipv4_multicast_memberships[i].multi_addr, *multi_addr);
       return 1;
@@ -2754,16 +2777,18 @@ lwip_socket_register_membership(int s, const ip4_addr_t *if_addr, const ip4_addr
 static void
 lwip_socket_unregister_membership(int s, const ip4_addr_t *if_addr, const ip4_addr_t *multi_addr)
 {
-  /* s+1 is stored in the array to prevent having to initialize the array
-     (default initialization is to 0) */
-  int sa = s + 1;
+  struct lwip_sock *sock = get_socket(s);
   int i;
 
+  if (!sock) {
+    return;
+  }
+
   for (i = 0; i < LWIP_SOCKET_MAX_MEMBERSHIPS; i++) {
-    if ((socket_ipv4_multicast_memberships[i].sa == sa) &&
+    if ((socket_ipv4_multicast_memberships[i].sock == sock) &&
         ip4_addr_cmp(&socket_ipv4_multicast_memberships[i].if_addr, if_addr) &&
         ip4_addr_cmp(&socket_ipv4_multicast_memberships[i].multi_addr, multi_addr)) {
-      socket_ipv4_multicast_memberships[i].sa = 0;
+      socket_ipv4_multicast_memberships[i].sock = NULL;
       ip4_addr_set_zero(&socket_ipv4_multicast_memberships[i].if_addr);
       ip4_addr_set_zero(&socket_ipv4_multicast_memberships[i].multi_addr);
       return;
@@ -2775,25 +2800,26 @@ lwip_socket_unregister_membership(int s, const ip4_addr_t *if_addr, const ip4_ad
  *
  * ATTENTION: this function is NOT called from tcpip_thread (or under CORE_LOCK).
  */
-static void lwip_socket_drop_registered_memberships(int s)
+static void
+lwip_socket_drop_registered_memberships(int s)
 {
-  /* s+1 is stored in the array to prevent having to initialize the array
-     (default initialization is to 0) */
-  int sa = s + 1;
+  struct lwip_sock *sock = get_socket(s);
   int i;
 
-  LWIP_ASSERT("socket has no netconn", sockets[s].conn != NULL);
+  if (!sock) {
+    return;
+  }
 
   for (i = 0; i < LWIP_SOCKET_MAX_MEMBERSHIPS; i++) {
-    if (socket_ipv4_multicast_memberships[i].sa == sa) {
+    if (socket_ipv4_multicast_memberships[i].sock == sock) {
       ip_addr_t multi_addr, if_addr;
       ip_addr_copy_from_ip4(multi_addr, socket_ipv4_multicast_memberships[i].multi_addr);
       ip_addr_copy_from_ip4(if_addr, socket_ipv4_multicast_memberships[i].if_addr);
-      socket_ipv4_multicast_memberships[i].sa = 0;
+      socket_ipv4_multicast_memberships[i].sock = NULL;
       ip4_addr_set_zero(&socket_ipv4_multicast_memberships[i].if_addr);
       ip4_addr_set_zero(&socket_ipv4_multicast_memberships[i].multi_addr);
 
-      netconn_join_leave_group(sockets[s].conn, &multi_addr, &if_addr, NETCONN_LEAVE);
+      netconn_join_leave_group(sock->conn, &multi_addr, &if_addr, NETCONN_LEAVE);
     }
   }
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/api/tcpip.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/api/tcpip.c b/net/ip/lwip_base/src/api/tcpip.c
index 4dfeabd..07b2f98 100644
--- a/net/ip/lwip_base/src/api/tcpip.c
+++ b/net/ip/lwip_base/src/api/tcpip.c
@@ -260,7 +260,7 @@ tcpip_callback_with_block(tcpip_callback_fn function, void *ctx, u8_t block)
 /**
  * call sys_timeout in tcpip_thread
  *
- * @param msec time in milliseconds for timeout
+ * @param msecs time in milliseconds for timeout
  * @param h function to be called on timeout
  * @param arg argument to pass to timeout function h
  * @return ERR_MEM on memory error, ERR_OK otherwise
@@ -288,7 +288,6 @@ tcpip_timeout(u32_t msecs, sys_timeout_handler h, void *arg)
 /**
  * call sys_untimeout in tcpip_thread
  *
- * @param msec time in milliseconds for timeout
  * @param h function to be called on timeout
  * @param arg argument to pass to timeout function h
  * @return ERR_MEM on memory error, ERR_OK otherwise

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/apps/httpd/fsdata.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/apps/httpd/fsdata.h b/net/ip/lwip_base/src/apps/httpd/fsdata.h
index 0c54d39..ac4548c 100644
--- a/net/ip/lwip_base/src/apps/httpd/fsdata.h
+++ b/net/ip/lwip_base/src/apps/httpd/fsdata.h
@@ -35,10 +35,6 @@
 #include "lwip/apps/httpd_opts.h"
 #include "lwip/apps/fs.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 struct fsdata_file {
   const struct fsdata_file *next;
   const unsigned char *name;
@@ -51,8 +47,4 @@ struct fsdata_file {
 #endif /* HTTPD_PRECALCULATED_CHECKSUM */
 };
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_FSDATA_H */


[11/30] incubator-mynewt-core git commit: inet_def_service; fix race when connection is closing.

Posted by ad...@apache.org.
inet_def_service; fix race when connection is closing.


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/e120cfc3
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/e120cfc3
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/e120cfc3

Branch: refs/heads/master
Commit: e120cfc316d7181fdd24e0b7d9da95ad7bf8a7cd
Parents: 73a3202
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Fri Apr 14 12:46:33 2017 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Fri Apr 14 13:21:30 2017 -0700

----------------------------------------------------------------------
 net/ip/inet_def_service/src/inet_def_service.c | 110 ++------------------
 1 file changed, 6 insertions(+), 104 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/e120cfc3/net/ip/inet_def_service/src/inet_def_service.c
----------------------------------------------------------------------
diff --git a/net/ip/inet_def_service/src/inet_def_service.c b/net/ip/inet_def_service/src/inet_def_service.c
index 3bbe59e..ff688da 100644
--- a/net/ip/inet_def_service/src/inet_def_service.c
+++ b/net/ip/inet_def_service/src/inet_def_service.c
@@ -106,7 +106,7 @@ inet_def_tcp_readable(void *arg, int err)
 {
     struct inet_def_tcp *idt = (struct inet_def_tcp *)arg;
 
-    if (err) {
+    if (err && !idt->closed) {
         idt->closed = 1;
         /*
          * No locking here. Assuming new connection notifications, as well as
@@ -241,7 +241,11 @@ inet_def_event(struct os_event *ev)
     case INET_DEF_ECHO:
         while (mn_recvfrom(sock, &m, (struct mn_sockaddr *)&msin) == 0) {
             console_printf("echo %d bytes\n", OS_MBUF_PKTLEN(m));
-            rc = mn_sendto(sock, m, (struct mn_sockaddr *)&msin);
+            if ((int)ev->ev_arg == MN_SOCK_DGRAM) {
+                rc = mn_sendto(sock, m, (struct mn_sockaddr *)&msin);
+            } else {
+                rc = mn_sendto(sock, m, NULL);
+            }
             if (rc) {
                 console_printf("  failed: %d!!!!\n", rc);
                 os_mbuf_free_chain(m);
@@ -308,108 +312,6 @@ inet_def_event(struct os_event *ev)
     }
 }
 
-#if 0
-static void
-inet_def_srv(void *arg)
-{
-    struct inet_def_udp *idu;
-    struct inet_def_tcp *idt;
-    struct mn_socket *sock;
-    struct os_event *ev;
-    struct mn_sockaddr_in msin;
-    struct os_mbuf *m;
-    enum inet_def_type type;
-    int rc;
-    int off;
-    int loop_cnt;
-
-    while (1) {
-        /*
-         * Wait here. When event comes, check what type of socket got it,
-         * and then act on it.
-         */
-        ev = os_eventq_get(inet_def_evq);
-        type = ev->ev_type;
-        idt = (struct inet_def_tcp *)ev;
-        idu = (struct inet_def_udp *)ev;
-        if ((int)ev->ev_arg == MN_SOCK_DGRAM) {
-            sock = idu->socket;
-        } else {
-            sock = idt->socket;
-        }
-        switch (type) {
-        case INET_DEF_ECHO:
-            while (mn_recvfrom(sock, &m, (struct mn_sockaddr *)&msin) == 0) {
-                console_printf("echo %d bytes\n", OS_MBUF_PKTLEN(m));
-                rc = mn_sendto(sock, m, (struct mn_sockaddr *)&msin);
-                if (rc) {
-                    console_printf("  failed: %d!!!!\n", rc);
-                    os_mbuf_free_chain(m);
-                }
-            }
-            break;
-        case INET_DEF_DISCARD:
-            while (mn_recvfrom(sock, &m, NULL) == 0) {
-                console_printf("discard %d bytes\n", OS_MBUF_PKTLEN(m));
-                os_mbuf_free_chain(m);
-            }
-            break;
-        case INET_DEF_CHARGEN:
-            while (mn_recvfrom(sock, &m, NULL) == 0) {
-                os_mbuf_free_chain(m);
-            }
-            if ((int)ev->ev_arg == MN_SOCK_STREAM && idt->closed) {
-                /*
-                 * Don't try to send tons of data to a closed socket.
-                 */
-                break;
-            }
-            loop_cnt = 0;
-            do {
-                m = os_msys_get(CHARGEN_WRITE_SZ, 0);
-                if (m) {
-                    for (off = 0;
-                         OS_MBUF_TRAILINGSPACE(m) >= CHARGEN_PATTERN_SZ;
-                         off += CHARGEN_PATTERN_SZ) {
-                        os_mbuf_copyinto(m, off, chargen_pattern,
-                          CHARGEN_PATTERN_SZ);
-                    }
-                    console_printf("chargen %d bytes\n", m->om_len);
-                    rc = mn_sendto(sock, m, NULL); /* assumes TCP for now */
-                    if (rc) {
-                        os_mbuf_free_chain(m);
-                        if (rc != MN_ENOBUFS && rc != MN_EAGAIN) {
-                            console_write("  sendto fail!!! %d\n", rc);
-                        }
-                        break;
-                    }
-                } else {
-                    /*
-                     * Mbuf shortage. Wait for them to appear.
-                     */
-                    os_time_delay(1);
-                }
-                loop_cnt++;
-            } while (loop_cnt < 32);
-            break;
-        default:
-            assert(0);
-            break;
-        }
-        if ((int)ev->ev_arg == MN_SOCK_STREAM && idt->closed) {
-            /*
-             * Remote end has closed the connection, as indicated in the
-             * callback. Close the socket and free the memory.
-             */
-            mn_socket_set_cbs(idt->socket, NULL, NULL);
-            os_eventq_remove(&inet_def_evq, &idt->ev);
-            mn_close(idt->socket);
-            os_free(idt);
-        }
-    }
-}
-#endif
-
 void
 inet_def_service_init(struct os_eventq *evq)
 {


[12/30] incubator-mynewt-core git commit: hal_timer.h; include inttypes.h

Posted by ad...@apache.org.
hal_timer.h; include inttypes.h


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/e9ab595e
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/e9ab595e
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/e9ab595e

Branch: refs/heads/master
Commit: e9ab595e22c320b5cddc62c4acfd1c5d6e7c2b5b
Parents: 8d8cf59
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Fri Apr 14 10:46:06 2017 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Fri Apr 14 13:21:30 2017 -0700

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


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/e9ab595e/hw/hal/include/hal/hal_timer.h
----------------------------------------------------------------------
diff --git a/hw/hal/include/hal/hal_timer.h b/hw/hal/include/hal/hal_timer.h
index c0a1cff..a2f717a 100644
--- a/hw/hal/include/hal/hal_timer.h
+++ b/hw/hal/include/hal/hal_timer.h
@@ -24,6 +24,8 @@
 extern "C" {
 #endif
 
+#include <inttypes.h>
+
 #include "os/queue.h"
 
 /* HAL timer struct */


[18/30] incubator-mynewt-core git commit: net/ip/lwip_base; update to LwIP to tag STABLE-2_0_2_RELEASE

Posted by ad...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/apps/snmp/snmp_core.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/apps/snmp/snmp_core.c b/net/ip/lwip_base/src/apps/snmp/snmp_core.c
index 1230d62..c041833 100644
--- a/net/ip/lwip_base/src/apps/snmp/snmp_core.c
+++ b/net/ip/lwip_base/src/apps/snmp/snmp_core.c
@@ -270,7 +270,7 @@ snmp_oid_to_ip4(const u32_t *oid, ip4_addr_t *ip)
       (oid[1] > 0xFF) ||
       (oid[2] > 0xFF) ||
       (oid[3] > 0xFF)) {
-    ip4_addr_copy(*ip, *IP4_ADDR_ANY);
+    ip4_addr_copy(*ip, *IP4_ADDR_ANY4);
     return 0;
   }
 
@@ -359,9 +359,9 @@ snmp_ip6_to_oid(const ip6_addr_t *ip, u32_t *oid)
 #if LWIP_IPV4 || LWIP_IPV6
 /**
  * Convert to InetAddressType+InetAddress+InetPortNumber
- * @param ip
- * @param port
- * @param oid
+ * @param ip IP address
+ * @param port Port
+ * @param oid OID
  * @return OID length
  */
 u8_t
@@ -378,8 +378,8 @@ snmp_ip_port_to_oid(const ip_addr_t *ip, u16_t port, u32_t *oid)
 
 /**
  * Convert to InetAddressType+InetAddress
- * @param ip
- * @param oid
+ * @param ip IP address
+ * @param oid OID
  * @return OID length
  */
 u8_t
@@ -412,9 +412,9 @@ snmp_ip_to_oid(const ip_addr_t *ip, u32_t *oid)
 
 /**
  * Convert from InetAddressType+InetAddress to ip_addr_t
- * @param oid
- * @param oid_len
- * @param ip
+ * @param oid OID
+ * @param oid_len OID length
+ * @param ip IP address
  * @return Parsed OID length
  */
 u8_t
@@ -487,10 +487,10 @@ snmp_oid_to_ip(const u32_t *oid, u8_t oid_len, ip_addr_t *ip)
 
 /**
  * Convert from InetAddressType+InetAddress+InetPortNumber to ip_addr_t and u16_t
- * @param oid
- * @param oid_len
- * @param ip
- * @param port
+ * @param oid OID
+ * @param oid_len OID length
+ * @param ip IP address
+ * @param port Port
  * @return Parsed OID length
  */
 u8_t
@@ -520,10 +520,10 @@ snmp_oid_to_ip_port(const u32_t *oid, u8_t oid_len, ip_addr_t *ip, u16_t *port)
 #endif /* LWIP_IPV4 || LWIP_IPV6 */
 
 /**
- * Assign an OID to \struct snmp_obj_id
- * @param target
- * @param oid
- * @param oid_len
+ * Assign an OID to struct snmp_obj_id
+ * @param target Assignment target 
+ * @param oid OID
+ * @param oid_len OID length
  */
 void
 snmp_oid_assign(struct snmp_obj_id* target, const u32_t *oid, u8_t oid_len)
@@ -538,10 +538,10 @@ snmp_oid_assign(struct snmp_obj_id* target, const u32_t *oid, u8_t oid_len)
 }
 
 /**
- * Prefix an OID to OID in \struct snmp_obj_id
- * @param target
- * @param oid
- * @param oid_len
+ * Prefix an OID to OID in struct snmp_obj_id
+ * @param target Assignment target to prefix
+ * @param oid OID
+ * @param oid_len OID length
  */
 void
 snmp_oid_prefix(struct snmp_obj_id* target, const u32_t *oid, u8_t oid_len)
@@ -561,12 +561,12 @@ snmp_oid_prefix(struct snmp_obj_id* target, const u32_t *oid, u8_t oid_len)
 }
 
 /**
- * Combine two OIDs into \struct snmp_obj_id
- * @param target
- * @param oid1
- * @param oid1_len
- * @param oid2
- * @param oid2_len
+ * Combine two OIDs into struct snmp_obj_id
+ * @param target Assignmet target
+ * @param oid1 OID 1
+ * @param oid1_len OID 1 length
+ * @param oid2 OID 2
+ * @param oid2_len OID 2 length
  */
 void
 snmp_oid_combine(struct snmp_obj_id* target, const u32_t *oid1, u8_t oid1_len, const u32_t *oid2, u8_t oid2_len)
@@ -576,10 +576,10 @@ snmp_oid_combine(struct snmp_obj_id* target, const u32_t *oid1, u8_t oid1_len, c
 }
 
 /**
- * Append OIDs to \struct snmp_obj_id
- * @param target
- * @param oid
- * @param oid_len
+ * Append OIDs to struct snmp_obj_id
+ * @param target Assignment target to append to
+ * @param oid OID
+ * @param oid_len OID length
  */
 void
 snmp_oid_append(struct snmp_obj_id* target, const u32_t *oid, u8_t oid_len)
@@ -594,11 +594,11 @@ snmp_oid_append(struct snmp_obj_id* target, const u32_t *oid, u8_t oid_len)
 
 /**
  * Compare two OIDs
- * @param oid1
- * @param oid1_len
- * @param oid2
- * @param oid2_len
- * @return
+ * @param oid1 OID 1
+ * @param oid1_len OID 1 length
+ * @param oid2 OID 2
+ * @param oid2_len OID 2 length
+ * @return -1: OID1&lt;OID2  1: OID1 &gt;OID2 0: equal
  */
 s8_t
 snmp_oid_compare(const u32_t *oid1, u8_t oid1_len, const u32_t *oid2, u8_t oid2_len)
@@ -635,11 +635,11 @@ snmp_oid_compare(const u32_t *oid1, u8_t oid1_len, const u32_t *oid2, u8_t oid2_
 
 /**
  * Check of two OIDs are equal
- * @param oid1
- * @param oid1_len
- * @param oid2
- * @param oid2_len
- * @return
+ * @param oid1 OID 1
+ * @param oid1_len OID 1 length
+ * @param oid2 OID 2
+ * @param oid2_len OID 2 length
+ * @return 1: equal 0: non-equal
  */
 u8_t
 snmp_oid_equal(const u32_t *oid1, u8_t oid1_len, const u32_t *oid2, u8_t oid2_len)
@@ -649,7 +649,7 @@ snmp_oid_equal(const u32_t *oid1, u8_t oid1_len, const u32_t *oid2, u8_t oid2_le
 
 /**
  * Convert netif to interface index
- * @param netif
+ * @param netif netif
  * @return index
  */
 u8_t

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/apps/snmp/snmp_mib2_ip.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/apps/snmp/snmp_mib2_ip.c b/net/ip/lwip_base/src/apps/snmp/snmp_mib2_ip.c
index b14a556..4f05180 100644
--- a/net/ip/lwip_base/src/apps/snmp/snmp_mib2_ip.c
+++ b/net/ip/lwip_base/src/apps/snmp/snmp_mib2_ip.c
@@ -146,7 +146,7 @@ ip_get_value(struct snmp_node_instance* instance, void* value)
 /**
  * Test ip object value before setting.
  *
- * @param od is the object definition
+ * @param instance node instance
  * @param len return value space (in bytes)
  * @param value points to (varbind) space to copy value from.
  *
@@ -326,7 +326,7 @@ ip_RouteTable_get_cell_value_core(struct netif *netif, u8_t default_route, const
   case 1: /* ipRouteDest */
     if (default_route) {
        /* default rte has 0.0.0.0 dest */
-      value->u32 = IP4_ADDR_ANY->addr;
+      value->u32 = IP4_ADDR_ANY4->addr;
     } else {
       /* netifs have netaddress dest */
       ip4_addr_t tmp;
@@ -378,7 +378,7 @@ ip_RouteTable_get_cell_value_core(struct netif *netif, u8_t default_route, const
   case 11: /* ipRouteMask */
     if (default_route) {
       /* default rte use 0.0.0.0 mask */
-      value->u32 = IP4_ADDR_ANY->addr;
+      value->u32 = IP4_ADDR_ANY4->addr;
     } else {
       /* other rtes use netmask */
       value->u32 = netif_ip4_netmask(netif)->addr;
@@ -449,7 +449,7 @@ ip_RouteTable_get_next_cell_instance_and_value(const u32_t* column, struct snmp_
 
   /* check default route */
   if (netif_default != NULL) {
-    snmp_ip4_to_oid(IP4_ADDR_ANY, &test_oid[0]);
+    snmp_ip4_to_oid(IP4_ADDR_ANY4, &test_oid[0]);
     snmp_next_oid_check(&state, test_oid, LWIP_ARRAYSIZE(ip_RouteTable_oid_ranges), netif_default);
   }
 
@@ -581,7 +581,7 @@ ip_NetToMediaTable_get_next_cell_instance_and_value(const u32_t* column, struct
       snmp_ip4_to_oid(ip, &test_oid[1]);
 
       /* check generated OID: is it a candidate for the next one? */
-      snmp_next_oid_check(&state, test_oid, LWIP_ARRAYSIZE(ip_NetToMediaTable_oid_ranges), (void*)(size_t)i);
+      snmp_next_oid_check(&state, test_oid, LWIP_ARRAYSIZE(ip_NetToMediaTable_oid_ranges), LWIP_PTR_NUMERIC_CAST(void*, i));
     }
   }
 
@@ -589,7 +589,7 @@ ip_NetToMediaTable_get_next_cell_instance_and_value(const u32_t* column, struct
   if (state.status == SNMP_NEXT_OID_STATUS_SUCCESS) {
     snmp_oid_assign(row_oid, state.next_oid, state.next_oid_len);
     /* fill in object properties */
-    return ip_NetToMediaTable_get_cell_value_core((u8_t)(size_t)state.reference, column, value, value_len);
+    return ip_NetToMediaTable_get_cell_value_core(LWIP_PTR_NUMERIC_CAST(u8_t, state.reference), column, value, value_len);
   }
 
   /* not found */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/apps/snmp/snmp_mib2_tcp.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/apps/snmp/snmp_mib2_tcp.c b/net/ip/lwip_base/src/apps/snmp/snmp_mib2_tcp.c
index f72e6a5..21f6965 100644
--- a/net/ip/lwip_base/src/apps/snmp/snmp_mib2_tcp.c
+++ b/net/ip/lwip_base/src/apps/snmp/snmp_mib2_tcp.c
@@ -172,7 +172,7 @@ tcp_ConnTable_get_cell_value_core(struct tcp_pcb *pcb, const u32_t* column, unio
     break;
   case 4: /* tcpConnRemAddress */
     if (pcb->state == LISTEN) {
-      value->u32 = IP4_ADDR_ANY->addr;
+      value->u32 = IP4_ADDR_ANY4->addr;
     } else {
       value->u32 = ip_2_ip4(&pcb->remote_ip)->addr;
     }
@@ -224,7 +224,7 @@ tcp_ConnTable_get_cell_value(const u32_t* column, const u32_t* row_oid, u8_t row
 
         /* PCBs in state LISTEN are not connected and have no remote_ip or remote_port */
         if (pcb->state == LISTEN) {
-          if (ip4_addr_cmp(&remote_ip, IP4_ADDR_ANY) && (remote_port == 0)) {
+          if (ip4_addr_cmp(&remote_ip, IP4_ADDR_ANY4) && (remote_port == 0)) {
             /* fill in object properties */
             return tcp_ConnTable_get_cell_value_core(pcb, column, value, value_len);
           }
@@ -268,7 +268,7 @@ tcp_ConnTable_get_next_cell_instance_and_value(const u32_t* column, struct snmp_
 
         /* PCBs in state LISTEN are not connected and have no remote_ip or remote_port */
         if (pcb->state == LISTEN) {
-          snmp_ip4_to_oid(IP4_ADDR_ANY, &test_oid[5]);
+          snmp_ip4_to_oid(IP4_ADDR_ANY4, &test_oid[5]);
           test_oid[9] = 0;
         } else {
           if (IP_IS_V6_VAL(pcb->remote_ip)) { /* should never happen */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/apps/snmp/snmp_msg.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/apps/snmp/snmp_msg.c b/net/ip/lwip_base/src/apps/snmp/snmp_msg.c
index e993db3..0cb7ca9 100644
--- a/net/ip/lwip_base/src/apps/snmp/snmp_msg.c
+++ b/net/ip/lwip_base/src/apps/snmp/snmp_msg.c
@@ -125,6 +125,7 @@ snmp_get_community_trap(void)
 void
 snmp_set_community_write(const char * const community)
 {
+  LWIP_ASSERT("community string must not be NULL", community != NULL);
   LWIP_ASSERT("community string is too long!", strlen(community) <= SNMP_MAX_COMMUNITY_STR_LEN);
   snmp_community_write = community;
 }
@@ -322,7 +323,7 @@ snmp_process_varbind(struct snmp_request *request, struct snmp_varbind *vb, u8_t
 /**
  * Service an internal or external event for SNMP GET.
  *
- * @param msg_ps points to the associated message process state
+ * @param request points to the associated message process state
  */
 static err_t
 snmp_process_get_request(struct snmp_request *request)
@@ -358,7 +359,7 @@ snmp_process_get_request(struct snmp_request *request)
 /**
  * Service an internal or external event for SNMP GET.
  *
- * @param msg_ps points to the associated message process state
+ * @param request points to the associated message process state
  */
 static err_t
 snmp_process_getnext_request(struct snmp_request *request)
@@ -394,7 +395,7 @@ snmp_process_getnext_request(struct snmp_request *request)
 /**
  * Service an internal or external event for SNMP GETBULKT.
  *
- * @param msg_ps points to the associated message process state
+ * @param request points to the associated message process state
  */
 static err_t
 snmp_process_getbulk_request(struct snmp_request *request)
@@ -492,7 +493,7 @@ snmp_process_getbulk_request(struct snmp_request *request)
 /**
  * Service an internal or external event for SNMP SET.
  *
- * @param msg_ps points to the associated message process state
+ * @param request points to the associated message process state
  */
 static err_t
 snmp_process_set_request(struct snmp_request *request)
@@ -910,7 +911,7 @@ snmp_parse_inbound_frame(struct snmp_request *request)
     snmp_authfail_trap();
     return ERR_ARG;
   } else if (request->request_type == SNMP_ASN1_CONTEXT_PDU_SET_REQ) {
-    if (strnlen(snmp_community_write, SNMP_MAX_COMMUNITY_STR_LEN) == 0) {
+    if (snmp_community_write[0] == 0) {
       /* our write community is empty, that means all our objects are readonly */
       request->error_status = SNMP_ERR_NOTWRITABLE;
       request->error_index  = 1;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/apps/snmp/snmp_netconn.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/apps/snmp/snmp_netconn.c b/net/ip/lwip_base/src/apps/snmp/snmp_netconn.c
index 7eead2e..24c3e26 100644
--- a/net/ip/lwip_base/src/apps/snmp/snmp_netconn.c
+++ b/net/ip/lwip_base/src/apps/snmp/snmp_netconn.c
@@ -36,6 +36,7 @@
 
 #if LWIP_SNMP && SNMP_USE_NETCONN
 
+#include <string.h>
 #include "lwip/api.h"
 #include "lwip/ip.h"
 #include "lwip/udp.h"
@@ -52,12 +53,12 @@ snmp_netconn_thread(void *arg)
   LWIP_UNUSED_ARG(arg);
   
   /* Bind to SNMP port with default IP address */
- #if LWIP_IPV6
+#if LWIP_IPV6
   conn = netconn_new(NETCONN_UDP_IPV6);
   netconn_bind(conn, IP6_ADDR_ANY, SNMP_IN_PORT);
 #else /* LWIP_IPV6 */
   conn = netconn_new(NETCONN_UDP);
-  netconn_bind(conn, IP_ADDR_ANY, SNMP_IN_PORT);
+  netconn_bind(conn, IP4_ADDR_ANY, SNMP_IN_PORT);
 #endif /* LWIP_IPV6 */
   LWIP_ERROR("snmp_netconn: invalid conn", (conn != NULL), return;);
   

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/apps/snmp/snmp_raw.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/apps/snmp/snmp_raw.c b/net/ip/lwip_base/src/apps/snmp/snmp_raw.c
index 8cfe77a..4a40864 100644
--- a/net/ip/lwip_base/src/apps/snmp/snmp_raw.c
+++ b/net/ip/lwip_base/src/apps/snmp/snmp_raw.c
@@ -80,7 +80,7 @@ snmp_get_local_ip_for_dst(void* handle, const ip_addr_t *dst, ip_addr_t *result)
 /**
  * @ingroup snmp_core
  * Starts SNMP Agent.
- * Allocates UDP pcb and binds it to IP_ADDR_ANY port 161.
+ * Allocates UDP pcb and binds it to IP_ANY_TYPE port 161.
  */
 void
 snmp_init(void)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/apps/snmp/snmp_threadsync.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/apps/snmp/snmp_threadsync.c b/net/ip/lwip_base/src/apps/snmp/snmp_threadsync.c
index 858c40e..204f265 100644
--- a/net/ip/lwip_base/src/apps/snmp/snmp_threadsync.c
+++ b/net/ip/lwip_base/src/apps/snmp/snmp_threadsync.c
@@ -211,6 +211,7 @@ void snmp_threadsync_init(struct snmp_threadsync_instance *instance, snmp_thread
   err_t err = sys_mutex_new(&instance->sem_usage_mutex);
   LWIP_ASSERT("Failed to set up mutex", err == ERR_OK);
   err = sys_sem_new(&instance->sem, 0);
+  LWIP_UNUSED_ARG(err); /* in case of LWIP_NOASSERT */
   LWIP_ASSERT("Failed to set up semaphore", err == ERR_OK);
   instance->sync_fn = sync_fn;
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/apps/snmp/snmp_traps.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/apps/snmp/snmp_traps.c b/net/ip/lwip_base/src/apps/snmp/snmp_traps.c
index 61ceee6..0d2df64 100644
--- a/net/ip/lwip_base/src/apps/snmp/snmp_traps.c
+++ b/net/ip/lwip_base/src/apps/snmp/snmp_traps.c
@@ -147,7 +147,8 @@ snmp_get_auth_traps_enabled(void)
 
 
 /**
- * Sends an generic or enterprise specific trap message.
+ * @ingroup snmp_traps
+ * Sends a generic or enterprise specific trap message.
  *
  * @param eoid points to enterprise object identifier
  * @param generic_trap is the trap code
@@ -225,7 +226,7 @@ snmp_send_trap(const struct snmp_obj_id* eoid, s32_t generic_trap, s32_t specifi
 
 /**
  * @ingroup snmp_traps
- *  Send generic SNMP trap
+ * Send generic SNMP trap
  */
 err_t 
 snmp_send_trap_generic(s32_t generic_trap)
@@ -235,7 +236,7 @@ snmp_send_trap_generic(s32_t generic_trap)
 }
 
 /**
- *@ingroup snmp_traps
+ * @ingroup snmp_traps
  * Send specific SNMP trap with variable bindings
  */
 err_t
@@ -296,8 +297,8 @@ snmp_trap_varbind_sum(struct snmp_msg_trap *trap, struct snmp_varbind *varbinds)
  * Sums trap header field lengths from tail to head and
  * returns trap_header_lengths for second encoding pass.
  *
+ * @param trap Trap message
  * @param vb_len varbind-list length
- * @param thl points to returned header lengths
  * @return the required length for encoding the trap header
  */
 static u16_t

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/apps/snmp/snmpv3_priv.h
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/apps/snmp/snmpv3_priv.h b/net/ip/lwip_base/src/apps/snmp/snmpv3_priv.h
index 3712d5c..b87666d 100644
--- a/net/ip/lwip_base/src/apps/snmp/snmpv3_priv.h
+++ b/net/ip/lwip_base/src/apps/snmp/snmpv3_priv.h
@@ -37,10 +37,6 @@
 
 #include "lwip/apps/snmp_opts.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 #if LWIP_SNMP && LWIP_SNMP_V3
 
 #include "snmp_pbuf_stream.h"
@@ -67,8 +63,4 @@ err_t snmpv3_build_priv_param(u8_t* priv_param);
 
 #endif
 
-#ifdef __cplusplus
-}
-#endif
-
 #endif /* LWIP_HDR_APPS_SNMP_V3_PRIV_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/apps/sntp/sntp.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/apps/sntp/sntp.c b/net/ip/lwip_base/src/apps/sntp/sntp.c
index 8d43eb0..71b2abe 100644
--- a/net/ip/lwip_base/src/apps/sntp/sntp.c
+++ b/net/ip/lwip_base/src/apps/sntp/sntp.c
@@ -212,13 +212,13 @@ sntp_process(u32_t *receive_timestamp)
   /* convert SNTP time (1900-based) to unix GMT time (1970-based)
    * if MSB is 0, SNTP time is 2036-based!
    */
-  u32_t rx_secs = ntohl(receive_timestamp[0]);
+  u32_t rx_secs = lwip_ntohl(receive_timestamp[0]);
   int is_1900_based = ((rx_secs & 0x80000000) != 0);
   u32_t t = is_1900_based ? (rx_secs - DIFF_SEC_1900_1970) : (rx_secs + DIFF_SEC_1970_2036);
   time_t tim = t;
 
 #if SNTP_CALC_TIME_US
-  u32_t us = ntohl(receive_timestamp[1]) / 4295;
+  u32_t us = lwip_ntohl(receive_timestamp[1]) / 4295;
   SNTP_SET_SYSTEM_TIME_US(t, us);
   /* display local time from GMT time */
   LWIP_DEBUGF(SNTP_DEBUG_TRACE, ("sntp_process: %s, %"U32_F" us", ctime(&tim), us));
@@ -247,10 +247,10 @@ sntp_initialize_request(struct sntp_msg *req)
     u32_t sntp_time_sec, sntp_time_us;
     /* fill in transmit timestamp and save it in 'sntp_last_timestamp_sent' */
     SNTP_GET_SYSTEM_TIME(sntp_time_sec, sntp_time_us);
-    sntp_last_timestamp_sent[0] = htonl(sntp_time_sec + DIFF_SEC_1900_1970);
+    sntp_last_timestamp_sent[0] = lwip_htonl(sntp_time_sec + DIFF_SEC_1900_1970);
     req->transmit_timestamp[0] = sntp_last_timestamp_sent[0];
     /* we send/save us instead of fraction to be faster... */
-    sntp_last_timestamp_sent[1] = htonl(sntp_time_us);
+    sntp_last_timestamp_sent[1] = lwip_htonl(sntp_time_us);
     req->transmit_timestamp[1] = sntp_last_timestamp_sent[1];
   }
 #endif /* SNTP_CHECK_RESPONSE >= 2 */
@@ -573,6 +573,7 @@ sntp_stop(void)
 {
   if (sntp_pcb != NULL) {
     sys_untimeout(sntp_request, NULL);
+    sys_untimeout(sntp_try_next_server, NULL);
     udp_remove(sntp_pcb);
     sntp_pcb = NULL;
   }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/apps/tftp/tftp_server.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/apps/tftp/tftp_server.c b/net/ip/lwip_base/src/apps/tftp/tftp_server.c
new file mode 100644
index 0000000..243b092
--- /dev/null
+++ b/net/ip/lwip_base/src/apps/tftp/tftp_server.c
@@ -0,0 +1,417 @@
+/****************************************************************//**
+ *
+ * @file tftp_server.c
+ *
+ * @author   Logan Gunthorpe <lo...@deltatee.com>
+ *           Dirk Ziegelmeier <dz...@gmx.de>
+ *
+ * @brief    Trivial File Transfer Protocol (RFC 1350)
+ *
+ * Copyright (c) Deltatee Enterprises Ltd. 2013
+ * All rights reserved.
+ *
+ ********************************************************************/
+
+/* 
+ * Redistribution and use in source and binary forms, with or without
+ * modification,are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ * 2. 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.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+ *
+ * Author: Logan Gunthorpe <lo...@deltatee.com>
+ *         Dirk Ziegelmeier <dz...@gmx.de>
+ *
+ */
+
+/**
+ * @defgroup tftp TFTP server
+ * @ingroup apps
+ *
+ * This is simple TFTP server for the lwIP raw API.
+ */
+
+#include "lwip/apps/tftp_server.h"
+
+#if LWIP_UDP
+
+#include "lwip/udp.h"
+#include "lwip/timeouts.h"
+#include "lwip/debug.h"
+
+#define TFTP_MAX_PAYLOAD_SIZE 512
+#define TFTP_HEADER_LENGTH    4
+
+#define TFTP_RRQ   1
+#define TFTP_WRQ   2
+#define TFTP_DATA  3
+#define TFTP_ACK   4
+#define TFTP_ERROR 5
+
+enum tftp_error {
+  TFTP_ERROR_FILE_NOT_FOUND    = 1,
+  TFTP_ERROR_ACCESS_VIOLATION  = 2,
+  TFTP_ERROR_DISK_FULL         = 3,
+  TFTP_ERROR_ILLEGAL_OPERATION = 4,
+  TFTP_ERROR_UNKNOWN_TRFR_ID   = 5,
+  TFTP_ERROR_FILE_EXISTS       = 6,
+  TFTP_ERROR_NO_SUCH_USER      = 7
+};
+
+#include <string.h>
+
+struct tftp_state {
+  const struct tftp_context *ctx;
+  void *handle;
+  struct pbuf *last_data;
+  struct udp_pcb *upcb;
+  ip_addr_t addr;
+  u16_t port;
+  int timer;
+  int last_pkt;
+  u16_t blknum;
+  u8_t retries;
+  u8_t mode_write;
+};
+
+static struct tftp_state tftp_state;
+
+static void tftp_tmr(void* arg);
+
+static void
+close_handle(void)
+{
+  tftp_state.port = 0;
+  ip_addr_set_any(0, &tftp_state.addr);
+
+  if(tftp_state.last_data != NULL) {
+    pbuf_free(tftp_state.last_data);
+    tftp_state.last_data = NULL;
+  }
+
+  sys_untimeout(tftp_tmr, NULL);
+  
+  if (tftp_state.handle) {
+    tftp_state.ctx->close(tftp_state.handle);
+    tftp_state.handle = NULL;
+    LWIP_DEBUGF(TFTP_DEBUG | LWIP_DBG_STATE, ("tftp: closing\n"));
+  }
+}
+
+static void
+send_error(const ip_addr_t *addr, u16_t port, enum tftp_error code, const char *str)
+{
+  int str_length = strlen(str);
+  struct pbuf* p;
+  u16_t* payload;
+  
+  p = pbuf_alloc(PBUF_TRANSPORT, (u16_t)(TFTP_HEADER_LENGTH + str_length + 1), PBUF_RAM);
+  if(p == NULL) {
+    return;
+  }
+
+  payload = (u16_t*) p->payload;
+  payload[0] = PP_HTONS(TFTP_ERROR);
+  payload[1] = lwip_htons(code);
+  MEMCPY(&payload[2], str, str_length + 1);
+
+  udp_sendto(tftp_state.upcb, p, addr, port);
+  pbuf_free(p);
+}
+
+static void
+send_ack(u16_t blknum)
+{
+  struct pbuf* p;
+  u16_t* payload;
+  
+  p = pbuf_alloc(PBUF_TRANSPORT, TFTP_HEADER_LENGTH, PBUF_RAM);
+  if(p == NULL) {
+    return;
+  }
+  payload = (u16_t*) p->payload;
+  
+  payload[0] = PP_HTONS(TFTP_ACK);
+  payload[1] = lwip_htons(blknum);
+  udp_sendto(tftp_state.upcb, p, &tftp_state.addr, tftp_state.port);
+  pbuf_free(p);
+}
+
+static void
+resend_data(void)
+{
+  struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, tftp_state.last_data->len, PBUF_RAM);
+  if(p == NULL) {
+    return;
+  }
+
+  if(pbuf_copy(p, tftp_state.last_data) != ERR_OK) {
+    pbuf_free(p);
+    return;
+  }
+    
+  udp_sendto(tftp_state.upcb, p, &tftp_state.addr, tftp_state.port);
+  pbuf_free(p);
+}
+
+static void
+send_data(void)
+{
+  u16_t *payload;
+  int ret;
+
+  if(tftp_state.last_data != NULL) {
+    pbuf_free(tftp_state.last_data);
+  }
+  
+  tftp_state.last_data = pbuf_alloc(PBUF_TRANSPORT, TFTP_HEADER_LENGTH + TFTP_MAX_PAYLOAD_SIZE, PBUF_RAM);
+  if(tftp_state.last_data == NULL) {
+    return;
+  }
+
+  payload = (u16_t *) tftp_state.last_data->payload;
+  payload[0] = PP_HTONS(TFTP_DATA);
+  payload[1] = lwip_htons(tftp_state.blknum);
+
+  ret = tftp_state.ctx->read(tftp_state.handle, &payload[2], TFTP_MAX_PAYLOAD_SIZE);
+  if (ret < 0) {
+    send_error(&tftp_state.addr, tftp_state.port, TFTP_ERROR_ACCESS_VIOLATION, "Error occured while reading the file.");
+    close_handle();
+    return;
+  }
+
+  pbuf_realloc(tftp_state.last_data, (u16_t)(TFTP_HEADER_LENGTH + ret));
+  resend_data();
+}
+
+static void
+recv(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_addr_t *addr, u16_t port)
+{
+  u16_t *sbuf = (u16_t *) p->payload;
+  int opcode;
+
+  LWIP_UNUSED_ARG(arg);
+  LWIP_UNUSED_ARG(upcb);
+  
+  if (((tftp_state.port != 0) && (port != tftp_state.port)) ||
+      (!ip_addr_isany_val(tftp_state.addr) && !ip_addr_cmp(&tftp_state.addr, addr))) {
+    send_error(addr, port, TFTP_ERROR_ACCESS_VIOLATION, "Only one connection at a time is supported");
+    pbuf_free(p);
+    return;
+  }
+
+  opcode = sbuf[0];
+
+  tftp_state.last_pkt = tftp_state.timer;
+  tftp_state.retries = 0;
+
+  switch (opcode) {
+    case PP_HTONS(TFTP_RRQ): /* fall through */
+    case PP_HTONS(TFTP_WRQ):
+    {
+      const char tftp_null = 0;
+      char filename[TFTP_MAX_FILENAME_LEN];
+      char mode[TFTP_MAX_MODE_LEN];
+      u16_t filename_end_offset;
+      u16_t mode_end_offset;
+
+      if(tftp_state.handle != NULL) {
+        send_error(addr, port, TFTP_ERROR_ACCESS_VIOLATION, "Only one connection at a time is supported");
+        break;
+      }
+      
+      sys_timeout(TFTP_TIMER_MSECS, tftp_tmr, NULL);
+
+      /* find \0 in pbuf -> end of filename string */
+      filename_end_offset = pbuf_memfind(p, &tftp_null, sizeof(tftp_null), 2);
+      if((u16_t)(filename_end_offset-2) > sizeof(filename)) {
+        send_error(addr, port, TFTP_ERROR_ACCESS_VIOLATION, "Filename too long/not NULL terminated");
+        break;
+      }
+      pbuf_copy_partial(p, filename, filename_end_offset-2, 2);
+
+      /* find \0 in pbuf -> end of mode string */
+      mode_end_offset = pbuf_memfind(p, &tftp_null, sizeof(tftp_null), filename_end_offset+1);
+      if((u16_t)(mode_end_offset-filename_end_offset) > sizeof(mode)) {
+        send_error(addr, port, TFTP_ERROR_ACCESS_VIOLATION, "Mode too long/not NULL terminated");
+        break;
+      }
+      pbuf_copy_partial(p, mode, mode_end_offset-filename_end_offset, filename_end_offset+1);
+ 
+      tftp_state.handle = tftp_state.ctx->open(filename, mode, opcode == PP_HTONS(TFTP_WRQ));
+      tftp_state.blknum = 1;
+
+      if (!tftp_state.handle) {
+        send_error(addr, port, TFTP_ERROR_FILE_NOT_FOUND, "Unable to open requested file.");
+        break;
+      }
+
+      LWIP_DEBUGF(TFTP_DEBUG | LWIP_DBG_STATE, ("tftp: %s request from ", (opcode == PP_HTONS(TFTP_WRQ)) ? "write" : "read"));
+      ip_addr_debug_print(TFTP_DEBUG | LWIP_DBG_STATE, addr);
+      LWIP_DEBUGF(TFTP_DEBUG | LWIP_DBG_STATE, (" for '%s' mode '%s'\n", filename, mode));
+
+      ip_addr_copy(tftp_state.addr, *addr);
+      tftp_state.port = port;
+
+      if (opcode == PP_HTONS(TFTP_WRQ)) {
+        tftp_state.mode_write = 1;
+        send_ack(0);
+      } else {
+        tftp_state.mode_write = 0;
+        send_data();
+      }
+
+      break;
+    }
+    
+    case PP_HTONS(TFTP_DATA):
+    {
+      int ret;
+      u16_t blknum;
+      
+      if (tftp_state.handle == NULL) {
+        send_error(addr, port, TFTP_ERROR_ACCESS_VIOLATION, "No connection");
+        break;
+      }
+
+      if (tftp_state.mode_write != 1) {
+        send_error(addr, port, TFTP_ERROR_ACCESS_VIOLATION, "Not a write connection");
+        break;
+      }
+
+      blknum = lwip_ntohs(sbuf[1]);
+      pbuf_header(p, -TFTP_HEADER_LENGTH);
+
+      ret = tftp_state.ctx->write(tftp_state.handle, p);
+      if (ret < 0) {
+        send_error(addr, port, TFTP_ERROR_ACCESS_VIOLATION, "error writing file");
+        close_handle();
+      } else {
+        send_ack(blknum);
+      }
+
+      if (p->tot_len < TFTP_MAX_PAYLOAD_SIZE) {
+        close_handle();
+      }
+      break;
+    }
+
+    case PP_HTONS(TFTP_ACK):
+    {
+      u16_t blknum;
+      int lastpkt;
+
+      if (tftp_state.handle == NULL) {
+        send_error(addr, port, TFTP_ERROR_ACCESS_VIOLATION, "No connection");
+        break;
+      }
+
+      if (tftp_state.mode_write != 0) {
+        send_error(addr, port, TFTP_ERROR_ACCESS_VIOLATION, "Not a read connection");
+        break;
+      }
+
+      blknum = lwip_ntohs(sbuf[1]);
+      if (blknum != tftp_state.blknum) {
+        send_error(addr, port, TFTP_ERROR_UNKNOWN_TRFR_ID, "Wrong block number");
+        break;
+      }
+
+      lastpkt = 0;
+
+      if (tftp_state.last_data != NULL) {
+        lastpkt = tftp_state.last_data->tot_len != (TFTP_MAX_PAYLOAD_SIZE + TFTP_HEADER_LENGTH);
+      }
+
+      if (!lastpkt) {
+        tftp_state.blknum++;
+        send_data();
+      } else {
+        close_handle();
+      }
+
+      break;
+    }
+    
+    default:
+      send_error(addr, port, TFTP_ERROR_ILLEGAL_OPERATION, "Unknown operation");
+      break;
+  }
+
+  pbuf_free(p);
+}
+
+static void
+tftp_tmr(void* arg)
+{
+  LWIP_UNUSED_ARG(arg);
+  
+  tftp_state.timer++;
+
+  if (tftp_state.handle == NULL) {
+    return;
+  }
+
+  sys_timeout(TFTP_TIMER_MSECS, tftp_tmr, NULL);
+
+  if ((tftp_state.timer - tftp_state.last_pkt) > (TFTP_TIMEOUT_MSECS / TFTP_TIMER_MSECS)) {
+    if ((tftp_state.last_data != NULL) && (tftp_state.retries < TFTP_MAX_RETRIES)) {
+      LWIP_DEBUGF(TFTP_DEBUG | LWIP_DBG_STATE, ("tftp: timeout, retrying\n"));
+      resend_data();
+      tftp_state.retries++;
+    } else {
+      LWIP_DEBUGF(TFTP_DEBUG | LWIP_DBG_STATE, ("tftp: timeout\n"));
+      close_handle();
+    }
+  }
+}
+
+/** @ingroup tftp
+ * Initialize TFTP server.
+ * @param ctx TFTP callback struct
+ */
+err_t 
+tftp_init(const struct tftp_context *ctx)
+{
+  err_t ret;
+
+  struct udp_pcb *pcb = udp_new_ip_type(IPADDR_TYPE_ANY);
+  if (pcb == NULL) {
+    return ERR_MEM;
+  }
+
+  ret = udp_bind(pcb, IP_ANY_TYPE, TFTP_PORT);
+  if (ret != ERR_OK) {
+    udp_remove(pcb);
+    return ret;
+  }
+
+  tftp_state.handle    = NULL;
+  tftp_state.port      = 0;
+  tftp_state.ctx       = ctx;
+  tftp_state.timer     = 0;
+  tftp_state.last_data = NULL;
+  tftp_state.upcb      = pcb;
+
+  udp_recv(pcb, recv, NULL);
+
+  return ERR_OK;
+}
+
+#endif /* LWIP_UDP */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/def.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/def.c b/net/ip/lwip_base/src/core/def.c
index 7d3c93f..8125313 100644
--- a/net/ip/lwip_base/src/core/def.c
+++ b/net/ip/lwip_base/src/core/def.c
@@ -7,11 +7,23 @@
  * Byte swapping is the second thing you would want to optimize. You will
  * need to port it to your architecture and in your cc.h:
  *
- * \#define LWIP_PLATFORM_BYTESWAP 1
- * \#define LWIP_PLATFORM_HTONS(x) your_htons
- * \#define LWIP_PLATFORM_HTONL(x) your_htonl
+ * \#define lwip_htons(x) your_htons
+ * \#define lwip_htonl(x) your_htonl
  *
- * Note ntohs() and ntohl() are merely references to the htonx counterparts.
+ * Note lwip_ntohs() and lwip_ntohl() are merely references to the htonx counterparts.
+ * 
+ * If you \#define them to htons() and htonl(), you should
+ * \#define LWIP_DONT_PROVIDE_BYTEORDER_FUNCTIONS to prevent lwIP from
+ * defining htonx/ntohx compatibility macros.
+
+ * @defgroup sys_nonstandard Non-standard functions
+ * @ingroup sys_layer
+ * lwIP provides default implementations for non-standard functions.
+ * These can be mapped to OS functions to reduce code footprint if desired.
+ * All defines related to this section must not be placed in lwipopts.h,
+ * but in arch/cc.h!
+ * These options cannot be \#defined in lwipopts.h since they are not options
+ * of lwIP itself, but options of the lwIP port to your system.
  */
 
 /*
@@ -49,8 +61,11 @@
 #include "lwip/opt.h"
 #include "lwip/def.h"
 
-#if (LWIP_PLATFORM_BYTESWAP == 0) && (BYTE_ORDER == LITTLE_ENDIAN)
+#include <string.h>
+
+#if BYTE_ORDER == LITTLE_ENDIAN
 
+#if !defined(lwip_htons)
 /**
  * Convert an u16_t from host- to network byte order.
  *
@@ -60,21 +75,11 @@
 u16_t
 lwip_htons(u16_t n)
 {
-  return ((n & 0xff) << 8) | ((n & 0xff00) >> 8);
-}
-
-/**
- * Convert an u16_t from network- to host byte order.
- *
- * @param n u16_t in network byte order
- * @return n in host byte order
- */
-u16_t
-lwip_ntohs(u16_t n)
-{
-  return lwip_htons(n);
+  return (u16_t)PP_HTONS(n);
 }
+#endif /* lwip_htons */
 
+#if !defined(lwip_htonl)
 /**
  * Convert an u32_t from host- to network byte order.
  *
@@ -84,22 +89,134 @@ lwip_ntohs(u16_t n)
 u32_t
 lwip_htonl(u32_t n)
 {
-  return ((n & 0xff) << 24) |
-    ((n & 0xff00) << 8) |
-    ((n & 0xff0000UL) >> 8) |
-    ((n & 0xff000000UL) >> 24);
+  return (u32_t)PP_HTONL(n);
 }
+#endif /* lwip_htonl */
+
+#endif /* BYTE_ORDER == LITTLE_ENDIAN */
 
+#ifndef lwip_strnstr
 /**
- * Convert an u32_t from network- to host byte order.
- *
- * @param n u32_t in network byte order
- * @return n in host byte order
+ * @ingroup sys_nonstandard
+ * lwIP default implementation for strnstr() non-standard function.
+ * This can be \#defined to strnstr() depending on your platform port.
  */
-u32_t
-lwip_ntohl(u32_t n)
+char*
+lwip_strnstr(const char* buffer, const char* token, size_t n)
+{
+  const char* p;
+  size_t tokenlen = strlen(token);
+  if (tokenlen == 0) {
+    return LWIP_CONST_CAST(char *, buffer);
+  }
+  for (p = buffer; *p && (p + tokenlen <= buffer + n); p++) {
+    if ((*p == *token) && (strncmp(p, token, tokenlen) == 0)) {
+      return LWIP_CONST_CAST(char *, p);
+    }
+  }
+  return NULL;
+}
+#endif
+
+#ifndef lwip_stricmp
+/**
+ * @ingroup sys_nonstandard
+ * lwIP default implementation for stricmp() non-standard function.
+ * This can be \#defined to stricmp() depending on your platform port.
+ */
+int
+lwip_stricmp(const char* str1, const char* str2)
 {
-  return lwip_htonl(n);
+  char c1, c2;
+
+  do {
+    c1 = *str1++;
+    c2 = *str2++;
+    if (c1 != c2) {
+      char c1_upc = c1 | 0x20;
+      if ((c1_upc >= 'a') && (c1_upc <= 'z')) {
+        /* characters are not equal an one is in the alphabet range:
+        downcase both chars and check again */
+        char c2_upc = c2 | 0x20;
+        if (c1_upc != c2_upc) {
+          /* still not equal */
+          /* don't care for < or > */
+          return 1;
+        }
+      } else {
+        /* characters are not equal but none is in the alphabet range */
+        return 1;
+      }
+    }
+  } while (c1 != 0);
+  return 0;
 }
+#endif
+
+#ifndef lwip_strnicmp
+/**
+ * @ingroup sys_nonstandard
+ * lwIP default implementation for strnicmp() non-standard function.
+ * This can be \#defined to strnicmp() depending on your platform port.
+ */
+int
+lwip_strnicmp(const char* str1, const char* str2, size_t len)
+{
+  char c1, c2;
 
-#endif /* (LWIP_PLATFORM_BYTESWAP == 0) && (BYTE_ORDER == LITTLE_ENDIAN) */
+  do {
+    c1 = *str1++;
+    c2 = *str2++;
+    if (c1 != c2) {
+      char c1_upc = c1 | 0x20;
+      if ((c1_upc >= 'a') && (c1_upc <= 'z')) {
+        /* characters are not equal an one is in the alphabet range:
+        downcase both chars and check again */
+        char c2_upc = c2 | 0x20;
+        if (c1_upc != c2_upc) {
+          /* still not equal */
+          /* don't care for < or > */
+          return 1;
+        }
+      } else {
+        /* characters are not equal but none is in the alphabet range */
+        return 1;
+      }
+    }
+  } while (len-- && c1 != 0);
+  return 0;
+}
+#endif
+
+#ifndef lwip_itoa
+/**
+ * @ingroup sys_nonstandard
+ * lwIP default implementation for itoa() non-standard function.
+ * This can be \#defined to itoa() or snprintf(result, bufsize, "%d", number) depending on your platform port.
+ */
+void
+lwip_itoa(char* result, size_t bufsize, int number)
+{
+  const int base = 10;
+  char* ptr = result, *ptr1 = result, tmp_char;
+  int tmp_value;
+  LWIP_UNUSED_ARG(bufsize);
+
+  do {
+    tmp_value = number;
+    number /= base;
+    *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz"[35 + (tmp_value - number * base)];
+  } while(number);
+
+   /* Apply negative sign */
+  if (tmp_value < 0) {
+     *ptr++ = '-';
+  }
+  *ptr-- = '\0';
+  while(ptr1 < ptr) {
+    tmp_char = *ptr;
+    *ptr--= *ptr1;
+    *ptr1++ = tmp_char;
+  }
+}
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/dns.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/dns.c b/net/ip/lwip_base/src/core/dns.c
index b19f9b0..12c6f16 100644
--- a/net/ip/lwip_base/src/core/dns.c
+++ b/net/ip/lwip_base/src/core/dns.c
@@ -24,6 +24,11 @@
  * the resolver code calls a specified callback function (which
  * must be implemented by the module that uses the resolver).
  * 
+ * Multicast DNS queries are supported for names ending on ".local".
+ * However, only "One-Shot Multicast DNS Queries" are supported (RFC 6762
+ * chapter 5.1), this is not a fully compliant implementation of continuous
+ * mDNS querying!
+ *
  * All functions must be called from TCPIP thread.
  * 
  * @see @ref netconn_common for thread-safe access.
@@ -71,6 +76,7 @@
 /** @todo: define good default values (rfc compliance) */
 /** @todo: improve answer parsing, more checkings... */
 /** @todo: check RFC1035 - 7.3. Processing responses */
+/** @todo: one-shot mDNS: dual-stack fallback to another IP version */
 
 /*-----------------------------------------------------------------------------
  * Includes
@@ -80,6 +86,7 @@
 
 #if LWIP_DNS /* don't build if not configured for use in lwipopts.h */
 
+#include "lwip/def.h"
 #include "lwip/udp.h"
 #include "lwip/mem.h"
 #include "lwip/memp.h"
@@ -115,6 +122,13 @@ static u16_t dns_txid;
 #error DNS_MAX_TTL must be a positive 32-bit value
 #endif
 
+#if DNS_TABLE_SIZE > 255
+#error DNS_TABLE_SIZE must fit into an u8_t
+#endif
+#if DNS_MAX_SERVERS > 255
+#error DNS_MAX_SERVERS must fit into an u8_t
+#endif
+
 /* The number of parallel requests (i.e. calls to dns_gethostbyname
  * that cannot be answered from the DNS table.
  * This is set to the table size by default.
@@ -122,6 +136,10 @@ static u16_t dns_txid;
 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
 #ifndef DNS_MAX_REQUESTS
 #define DNS_MAX_REQUESTS          DNS_TABLE_SIZE
+#else
+#if DNS_MAX_REQUESTS > 255
+#error DNS_MAX_REQUESTS must fit into an u8_t
+#endif
 #endif
 #else
 /* In this configuration, both arrays have to have the same size and are used
@@ -133,6 +151,10 @@ static u16_t dns_txid;
 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
 #ifndef DNS_MAX_SOURCE_PORTS
 #define DNS_MAX_SOURCE_PORTS      DNS_MAX_REQUESTS
+#else
+#if DNS_MAX_SOURCE_PORTS > 255
+#error DNS_MAX_SOURCE_PORTS must fit into an u8_t
+#endif
 #endif
 #else
 #ifdef DNS_MAX_SOURCE_PORTS
@@ -159,6 +181,12 @@ static u16_t dns_txid;
 #define LWIP_DNS_SET_ADDRTYPE(x, y)
 #endif /* LWIP_IPV4 && LWIP_IPV6 */
 
+#if LWIP_DNS_SUPPORT_MDNS_QUERIES
+#define LWIP_DNS_ISMDNS_ARG(x) , x
+#else
+#define LWIP_DNS_ISMDNS_ARG(x)
+#endif
+
 /** DNS query message structure.
     No packing needed: only used locally on the stack. */
 struct dns_query {
@@ -208,6 +236,9 @@ struct dns_table_entry {
 #if LWIP_IPV4 && LWIP_IPV6
   u8_t reqaddrtype;
 #endif /* LWIP_IPV4 && LWIP_IPV6 */
+#if LWIP_DNS_SUPPORT_MDNS_QUERIES
+  u8_t is_mdns;
+#endif
 };
 
 /** DNS request table entry: used when dns_gehostbyname cannot answer the
@@ -249,6 +280,7 @@ DNS_LOCAL_HOSTLIST_STORAGE_PRE struct local_hostlist_entry local_hostlist_static
 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
 
 static void dns_init_local(void);
+static err_t dns_lookup_local(const char *hostname, ip_addr_t *addr LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype));
 #endif /* DNS_LOCAL_HOSTLIST */
 
 
@@ -271,39 +303,12 @@ static struct dns_table_entry dns_table[DNS_TABLE_SIZE];
 static struct dns_req_entry   dns_requests[DNS_MAX_REQUESTS];
 static ip_addr_t              dns_servers[DNS_MAX_SERVERS];
 
-#ifndef LWIP_DNS_STRICMP
-#define LWIP_DNS_STRICMP(str1, str2) dns_stricmp(str1, str2)
-/**
- * A small but sufficient implementation for case insensitive strcmp.
- * This can be defined to e.g. stricmp for windows or strcasecmp for linux. */
-static int
-dns_stricmp(const char* str1, const char* str2)
-{
-  char c1, c2;
-
-  do {
-    c1 = *str1++;
-    c2 = *str2++;
-    if (c1 != c2) {
-      char c1_upc = c1 | 0x20;
-      if ((c1_upc >= 'a') && (c1_upc <= 'z')) {
-        /* characters are not equal an one is in the alphabet range:
-        downcase both chars and check again */
-        char c2_upc = c2 | 0x20;
-        if (c1_upc != c2_upc) {
-          /* still not equal */
-          /* don't care for < or > */
-          return 1;
-        }
-      } else {
-        /* characters are not equal but none is in the alphabet range */
-        return 1;
-      }
-    }
-  } while (c1 != 0);
-  return 0;
-}
-#endif /* LWIP_DNS_STRICMP */
+#if LWIP_IPV4
+const ip_addr_t dns_mquery_v4group = DNS_MQUERY_IPV4_GROUP_INIT;
+#endif /* LWIP_IPV4 */
+#if LWIP_IPV6
+const ip_addr_t dns_mquery_v6group = DNS_MQUERY_IPV6_GROUP_INIT;
+#endif /* LWIP_IPV6 */
 
 /**
  * Initialize the resolver: set up the UDP pcb and configure the default server
@@ -428,20 +433,64 @@ dns_init_local(void)
 
 /**
  * @ingroup dns
+ * Iterate the local host-list for a hostname.
+ *
+ * @param iterator_fn a function that is called for every entry in the local host-list
+ * @param iterator_arg 3rd argument passed to iterator_fn
+ * @return the number of entries in the local host-list
+ */
+size_t
+dns_local_iterate(dns_found_callback iterator_fn, void *iterator_arg)
+{
+  size_t i;
+#if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
+  struct local_hostlist_entry *entry = local_hostlist_dynamic;
+  i = 0;
+  while (entry != NULL) {
+    if (iterator_fn != NULL) {
+      iterator_fn(entry->name, &entry->addr, iterator_arg);
+    }
+    i++;
+    entry = entry->next;
+  }
+#else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
+  for (i = 0; i < LWIP_ARRAYSIZE(local_hostlist_static); i++) {
+    if (iterator_fn != NULL) {
+      iterator_fn(local_hostlist_static[i].name, &local_hostlist_static[i].addr, iterator_arg);
+    }
+  }
+#endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
+  return i;
+}
+
+/**
+ * @ingroup dns
  * Scans the local host-list for a hostname.
  *
  * @param hostname Hostname to look for in the local host-list
  * @param addr the first IP address for the hostname in the local host-list or
  *         IPADDR_NONE if not found.
+ * @param dns_addrtype - LWIP_DNS_ADDRTYPE_IPV4_IPV6: try to resolve IPv4 (ATTENTION: no fallback here!)
+ *                     - LWIP_DNS_ADDRTYPE_IPV6_IPV4: try to resolve IPv6 (ATTENTION: no fallback here!)
+ *                     - LWIP_DNS_ADDRTYPE_IPV4: try to resolve IPv4 only
+ *                     - LWIP_DNS_ADDRTYPE_IPV6: try to resolve IPv6 only
  * @return ERR_OK if found, ERR_ARG if not found
  */
+err_t
+dns_local_lookup(const char *hostname, ip_addr_t *addr, u8_t dns_addrtype)
+{
+  LWIP_UNUSED_ARG(dns_addrtype);
+  return dns_lookup_local(hostname, addr LWIP_DNS_ADDRTYPE_ARG(dns_addrtype));
+}
+
+/* Internal implementation for dns_local_lookup and dns_lookup */
 static err_t
 dns_lookup_local(const char *hostname, ip_addr_t *addr LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype))
 {
 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
   struct local_hostlist_entry *entry = local_hostlist_dynamic;
   while (entry != NULL) {
-    if ((LWIP_DNS_STRICMP(entry->name, hostname) == 0) &&
+    if ((lwip_stricmp(entry->name, hostname) == 0) &&
         LWIP_DNS_ADDRTYPE_MATCH_IP(dns_addrtype, entry->addr)) {
       if (addr) {
         ip_addr_copy(*addr, entry->addr);
@@ -453,7 +502,7 @@ dns_lookup_local(const char *hostname, ip_addr_t *addr LWIP_DNS_ADDRTYPE_ARG(u8_
 #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
   size_t i;
   for (i = 0; i < LWIP_ARRAYSIZE(local_hostlist_static); i++) {
-    if ((LWIP_DNS_STRICMP(local_hostlist_static[i].name, hostname) == 0) &&
+    if ((lwip_stricmp(local_hostlist_static[i].name, hostname) == 0) &&
         LWIP_DNS_ADDRTYPE_MATCH_IP(dns_addrtype, local_hostlist_static[i].addr)) {
       if (addr) {
         ip_addr_copy(*addr, local_hostlist_static[i].addr);
@@ -483,7 +532,7 @@ dns_local_removehost(const char *hostname, const ip_addr_t *addr)
   struct local_hostlist_entry *entry = local_hostlist_dynamic;
   struct local_hostlist_entry *last_entry = NULL;
   while (entry != NULL) {
-    if (((hostname == NULL) || !LWIP_DNS_STRICMP(entry->name, hostname)) &&
+    if (((hostname == NULL) || !lwip_stricmp(entry->name, hostname)) &&
         ((addr == NULL) || ip_addr_cmp(&entry->addr, addr))) {
       struct local_hostlist_entry *free_entry;
       if (last_entry != NULL) {
@@ -572,7 +621,7 @@ dns_lookup(const char *name, ip_addr_t *addr LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addr
   /* Walk through name list, return entry if found. If not, return NULL. */
   for (i = 0; i < DNS_TABLE_SIZE; ++i) {
     if ((dns_table[i].state == DNS_STATE_DONE) &&
-        (LWIP_DNS_STRICMP(name, dns_table[i].name) == 0) &&
+        (lwip_strnicmp(name, dns_table[i].name, sizeof(dns_table[i].name)) == 0) &&
         LWIP_DNS_ADDRTYPE_MATCH_IP(dns_addrtype, dns_table[i].ipaddr)) {
       LWIP_DEBUGF(DNS_DEBUG, ("dns_lookup: \"%s\": found = ", name));
       ip_addr_debug_print(DNS_DEBUG, &(dns_table[i].ipaddr));
@@ -698,7 +747,11 @@ dns_send(u8_t idx)
   LWIP_DEBUGF(DNS_DEBUG, ("dns_send: dns_servers[%"U16_F"] \"%s\": request\n",
               (u16_t)(entry->server_idx), entry->name));
   LWIP_ASSERT("dns server out of array", entry->server_idx < DNS_MAX_SERVERS);
-  if (ip_addr_isany_val(dns_servers[entry->server_idx])) {
+  if (ip_addr_isany_val(dns_servers[entry->server_idx])
+#if LWIP_DNS_SUPPORT_MDNS_QUERIES
+      && !entry->is_mdns
+#endif
+    ) {
     /* DNS server not valid anymore, e.g. PPP netif has been shut down */
     /* call specified callback function if provided */
     dns_call_found(idx, NULL);
@@ -711,9 +764,11 @@ dns_send(u8_t idx)
   p = pbuf_alloc(PBUF_TRANSPORT, (u16_t)(SIZEOF_DNS_HDR + strlen(entry->name) + 2 +
                  SIZEOF_DNS_QUERY), PBUF_RAM);
   if (p != NULL) {
+    const ip_addr_t* dst;
+    u16_t dst_port;
     /* fill dns header */
     memset(&hdr, 0, SIZEOF_DNS_HDR);
-    hdr.id = htons(entry->txid);
+    hdr.id = lwip_htons(entry->txid);
     hdr.flags1 = DNS_FLAG1_RD;
     hdr.numquestions = PP_HTONS(1);
     pbuf_take(p, &hdr, SIZEOF_DNS_HDR);
@@ -753,7 +808,30 @@ dns_send(u8_t idx)
     /* send dns packet */
     LWIP_DEBUGF(DNS_DEBUG, ("sending DNS request ID %d for name \"%s\" to server %d\r\n",
       entry->txid, entry->name, entry->server_idx));
-    err = udp_sendto(dns_pcbs[pcb_idx], p, &dns_servers[entry->server_idx], DNS_SERVER_PORT);
+#if LWIP_DNS_SUPPORT_MDNS_QUERIES
+    if (entry->is_mdns) {
+      dst_port = DNS_MQUERY_PORT;
+#if LWIP_IPV6
+      if (LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype))
+      {
+        dst = &dns_mquery_v6group;
+      }
+#endif
+#if LWIP_IPV4 && LWIP_IPV6
+      else
+#endif
+#if LWIP_IPV4
+      {
+        dst = &dns_mquery_v4group;
+      }
+#endif
+    } else
+#endif /* LWIP_DNS_SUPPORT_MDNS_QUERIES */
+    {
+      dst_port = DNS_SERVER_PORT;
+      dst = &dns_servers[entry->server_idx];
+    }
+    err = udp_sendto(dns_pcbs[pcb_idx], p, dst, dst_port);
 
     /* free pbuf */
     pbuf_free(p);
@@ -956,7 +1034,11 @@ dns_check_entry(u8_t i)
     case DNS_STATE_ASKING:
       if (--entry->tmr == 0) {
         if (++entry->retries == DNS_MAX_RETRIES) {
-          if ((entry->server_idx + 1 < DNS_MAX_SERVERS) && !ip_addr_isany_val(dns_servers[entry->server_idx + 1])) {
+          if ((entry->server_idx + 1 < DNS_MAX_SERVERS) && !ip_addr_isany_val(dns_servers[entry->server_idx + 1])
+#if LWIP_DNS_SUPPORT_MDNS_QUERIES
+            && !entry->is_mdns
+#endif /* LWIP_DNS_SUPPORT_MDNS_QUERIES */
+            ) {
             /* change of server */
             entry->server_idx++;
             entry->tmr = 1;
@@ -1046,8 +1128,6 @@ dns_correct_response(u8_t idx, u32_t ttl)
 }
 /**
  * Receive input function for DNS response packets arriving for the dns UDP pcb.
- *
- * @params see udp.h
  */
 static void
 dns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port)
@@ -1074,7 +1154,7 @@ dns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr,
   /* copy dns payload inside static buffer for processing */
   if (pbuf_copy_partial(p, &hdr, SIZEOF_DNS_HDR, 0) == SIZEOF_DNS_HDR) {
     /* Match the ID in the DNS header with the name table. */
-    txid = htons(hdr.id);
+    txid = lwip_htons(hdr.id);
     for (i = 0; i < DNS_TABLE_SIZE; i++) {
       const struct dns_table_entry *entry = &dns_table[i];
       if ((entry->state == DNS_STATE_ASKING) &&
@@ -1082,8 +1162,8 @@ dns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr,
 
         /* We only care about the question(s) and the answers. The authrr
            and the extrarr are simply discarded. */
-        nquestions = htons(hdr.numquestions);
-        nanswers   = htons(hdr.numanswers);
+        nquestions = lwip_htons(hdr.numquestions);
+        nanswers   = lwip_htons(hdr.numanswers);
 
         /* Check for correct response. */
         if ((hdr.flags1 & DNS_FLAG1_RESPONSE) == 0) {
@@ -1095,10 +1175,15 @@ dns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr,
           goto memerr; /* ignore this packet */
         }
 
-        /* Check whether response comes from the same network address to which the
-           question was sent. (RFC 5452) */
-        if (!ip_addr_cmp(addr, &dns_servers[entry->server_idx])) {
-          goto memerr; /* ignore this packet */
+#if LWIP_DNS_SUPPORT_MDNS_QUERIES
+        if (!entry->is_mdns)
+#endif /* LWIP_DNS_SUPPORT_MDNS_QUERIES */
+        {
+          /* Check whether response comes from the same network address to which the
+             question was sent. (RFC 5452) */
+          if (!ip_addr_cmp(addr, &dns_servers[entry->server_idx])) {
+            goto memerr; /* ignore this packet */
+          }
         }
 
         /* Check if the name in the "question" part match with the name in the entry and
@@ -1154,7 +1239,7 @@ dns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr,
                   ip_addr_copy_from_ip4(dns_table[i].ipaddr, ip4addr);
                   pbuf_free(p);
                   /* handle correct response */
-                  dns_correct_response(i, ntohl(ans.ttl));
+                  dns_correct_response(i, lwip_ntohl(ans.ttl));
                   return;
                 }
               }
@@ -1173,17 +1258,17 @@ dns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr,
                   ip_addr_copy_from_ip6(dns_table[i].ipaddr, ip6addr);
                   pbuf_free(p);
                   /* handle correct response */
-                  dns_correct_response(i, ntohl(ans.ttl));
+                  dns_correct_response(i, lwip_ntohl(ans.ttl));
                   return;
                 }
               }
 #endif /* LWIP_IPV6 */
             }
             /* skip this answer */
-            if ((int)(res_idx + htons(ans.len)) > 0xFFFF) {
+            if ((int)(res_idx + lwip_htons(ans.len)) > 0xFFFF) {
               goto memerr; /* ignore this packet */
             }
-            res_idx += htons(ans.len);
+            res_idx += lwip_htons(ans.len);
             --nanswers;
           }
 #if LWIP_IPV4 && LWIP_IPV6
@@ -1226,11 +1311,11 @@ memerr:
  * @param hostnamelen length of the hostname
  * @param found a callback function to be called on success, failure or timeout
  * @param callback_arg argument to pass to the callback function
- * @return @return a err_t return code.
+ * @return err_t return code.
  */
 static err_t
 dns_enqueue(const char *name, size_t hostnamelen, dns_found_callback found,
-            void *callback_arg LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype))
+            void *callback_arg LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype) LWIP_DNS_ISMDNS_ARG(u8_t is_mdns))
 {
   u8_t i;
   u8_t lseq, lseqi;
@@ -1243,7 +1328,7 @@ dns_enqueue(const char *name, size_t hostnamelen, dns_found_callback found,
   /* check for duplicate entries */
   for (i = 0; i < DNS_TABLE_SIZE; i++) {
     if ((dns_table[i].state == DNS_STATE_ASKING) &&
-        (LWIP_DNS_STRICMP(name, dns_table[i].name) == 0)) {
+        (lwip_strnicmp(name, dns_table[i].name, sizeof(dns_table[i].name)) == 0)) {
 #if LWIP_IPV4 && LWIP_IPV6
       if (dns_table[i].reqaddrtype != dns_addrtype) {
         /* requested address types don't match
@@ -1279,8 +1364,9 @@ dns_enqueue(const char *name, size_t hostnamelen, dns_found_callback found,
     }
     /* check if this is the oldest completed entry */
     if (entry->state == DNS_STATE_DONE) {
-      if ((u8_t)(dns_seqno - entry->seqno) > lseq) {
-        lseq = dns_seqno - entry->seqno;
+      u8_t age = dns_seqno - entry->seqno;
+      if (age > lseq) {
+        lseq = age;
         lseqi = i;
       }
     }
@@ -1345,6 +1431,10 @@ dns_enqueue(const char *name, size_t hostnamelen, dns_found_callback found,
   LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": use DNS pcb %"U16_F"\n", name, (u16_t)(entry->pcb_idx)));
 #endif
 
+#if LWIP_DNS_SUPPORT_MDNS_QUERIES
+  entry->is_mdns = is_mdns;
+#endif
+
   dns_seqno++;
 
   /* force to send query without waiting timer */
@@ -1390,16 +1480,19 @@ dns_gethostbyname(const char *hostname, ip_addr_t *addr, dns_found_callback foun
  * @param found a callback function to be called on success, failure or timeout (only if
  *              ERR_INPROGRESS is returned!)
  * @param callback_arg argument to pass to the callback function
- * @param dns_addrtype: - LWIP_DNS_ADDRTYPE_IPV4_IPV6: try to resolve IPv4 first, try IPv6 if IPv4 fails only
- *                      - LWIP_DNS_ADDRTYPE_IPV6_IPV4: try to resolve IPv6 first, try IPv4 if IPv6 fails only
- *                      - LWIP_DNS_ADDRTYPE_IPV4: try to resolve IPv4 only
- *                      - LWIP_DNS_ADDRTYPE_IPV6: try to resolve IPv6 only
+ * @param dns_addrtype - LWIP_DNS_ADDRTYPE_IPV4_IPV6: try to resolve IPv4 first, try IPv6 if IPv4 fails only
+ *                     - LWIP_DNS_ADDRTYPE_IPV6_IPV4: try to resolve IPv6 first, try IPv4 if IPv6 fails only
+ *                     - LWIP_DNS_ADDRTYPE_IPV4: try to resolve IPv4 only
+ *                     - LWIP_DNS_ADDRTYPE_IPV6: try to resolve IPv6 only
  */
 err_t
 dns_gethostbyname_addrtype(const char *hostname, ip_addr_t *addr, dns_found_callback found,
                            void *callback_arg, u8_t dns_addrtype)
 {
   size_t hostnamelen;
+#if LWIP_DNS_SUPPORT_MDNS_QUERIES
+  u8_t is_mdns;
+#endif
   /* not initialized or no valid server yet, or invalid addr pointer
    * or invalid hostname or invalid hostname length */
   if ((addr == NULL) ||
@@ -1456,13 +1549,25 @@ dns_gethostbyname_addrtype(const char *hostname, ip_addr_t *addr, dns_found_call
   LWIP_UNUSED_ARG(dns_addrtype);
 #endif /* LWIP_IPV4 && LWIP_IPV6 */
 
-  /* prevent calling found callback if no server is set, return error instead */
-  if (ip_addr_isany_val(dns_servers[0])) {
-    return ERR_VAL;
+#if LWIP_DNS_SUPPORT_MDNS_QUERIES
+  if (strstr(hostname, ".local") == &hostname[hostnamelen] - 6) {
+    is_mdns = 1;
+  } else {
+    is_mdns = 0;
+  }
+
+  if (!is_mdns)
+#endif /* LWIP_DNS_SUPPORT_MDNS_QUERIES */
+  {
+    /* prevent calling found callback if no server is set, return error instead */
+    if (ip_addr_isany_val(dns_servers[0])) {
+      return ERR_VAL;
+    }
   }
 
   /* queue query with specified callback */
-  return dns_enqueue(hostname, hostnamelen, found, callback_arg LWIP_DNS_ADDRTYPE_ARG(dns_addrtype));
+  return dns_enqueue(hostname, hostnamelen, found, callback_arg LWIP_DNS_ADDRTYPE_ARG(dns_addrtype)
+     LWIP_DNS_ISMDNS_ARG(is_mdns));
 }
 
 #endif /* LWIP_DNS */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/inet_chksum.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/inet_chksum.c b/net/ip/lwip_base/src/core/inet_chksum.c
index 6ccf839..917f3e4 100644
--- a/net/ip/lwip_base/src/core/inet_chksum.c
+++ b/net/ip/lwip_base/src/core/inet_chksum.c
@@ -51,7 +51,6 @@
 #include "lwip/def.h"
 #include "lwip/ip_addr.h"
 
-#include <stddef.h>
 #include <string.h>
 
 #ifndef LWIP_CHKSUM
@@ -108,10 +107,10 @@ lwip_standard_chksum(const void *dataptr, int len)
   if ((acc & 0xffff0000UL) != 0) {
     acc = (acc >> 16) + (acc & 0x0000ffffUL);
   }
-  /* This maybe a little confusing: reorder sum using htons()
-     instead of ntohs() since it has a little less call overhead.
+  /* This maybe a little confusing: reorder sum using lwip_htons()
+     instead of lwip_ntohs() since it has a little less call overhead.
      The caller must invert bits for Internet sum ! */
-  return htons((u16_t)acc);
+  return lwip_htons((u16_t)acc);
 }
 #endif
 
@@ -283,8 +282,8 @@ inet_cksum_pseudo_base(struct pbuf *p, u8_t proto, u16_t proto_len, u32_t acc)
     acc = SWAP_BYTES_IN_WORD(acc);
   }
 
-  acc += (u32_t)htons((u16_t)proto);
-  acc += (u32_t)htons(proto_len);
+  acc += (u32_t)lwip_htons((u16_t)proto);
+  acc += (u32_t)lwip_htons(proto_len);
 
   /* Fold 32-bit sum to 16 bits
      calling this twice is probably faster than if statements... */
@@ -429,8 +428,8 @@ inet_cksum_pseudo_partial_base(struct pbuf *p, u8_t proto, u16_t proto_len,
     acc = SWAP_BYTES_IN_WORD(acc);
   }
 
-  acc += (u32_t)htons((u16_t)proto);
-  acc += (u32_t)htons(proto_len);
+  acc += (u32_t)lwip_htons((u16_t)proto);
+  acc += (u32_t)lwip_htons(proto_len);
 
   /* Fold 32-bit sum to 16 bits
      calling this twice is probably faster than if statements... */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/init.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/init.c b/net/ip/lwip_base/src/core/init.c
index cf239f2..3131461 100644
--- a/net/ip/lwip_base/src/core/init.c
+++ b/net/ip/lwip_base/src/core/init.c
@@ -141,7 +141,7 @@ PACK_STRUCT_END
 #if (LWIP_TCP && (TCP_WND > 0xffffffff))
   #error "If you want to use TCP, TCP_WND must fit in an u32_t, so, you have to reduce it in your lwipopts.h"
 #endif
-#if (LWIP_TCP && LWIP_WND_SCALE && (TCP_RCV_SCALE > 14))
+#if (LWIP_TCP && (TCP_RCV_SCALE > 14))
   #error "The maximum valid window scale value is 14!"
 #endif
 #if (LWIP_TCP && (TCP_WND > (0xFFFFU << TCP_RCV_SCALE)))
@@ -218,9 +218,6 @@ PACK_STRUCT_END
 #if !LWIP_ETHERNET && (LWIP_ARP || PPPOE_SUPPORT)
   #error "LWIP_ETHERNET needs to be turned on for LWIP_ARP or PPPOE_SUPPORT"
 #endif
-#if (LWIP_IGMP || LWIP_IPV6) && !defined(LWIP_RAND)
-  #error "When using IGMP or IPv6, LWIP_RAND() needs to be defined to a random-function returning an u32_t random value (in arch/cc.h)"
-#endif
 #if LWIP_TCPIP_CORE_LOCKING_INPUT && !LWIP_TCPIP_CORE_LOCKING
   #error "When using LWIP_TCPIP_CORE_LOCKING_INPUT, LWIP_TCPIP_CORE_LOCKING must be enabled, too"
 #endif
@@ -339,12 +336,17 @@ PACK_STRUCT_END
 void
 lwip_init(void)
 {
+#ifndef LWIP_SKIP_CONST_CHECK
+  int a;
+  LWIP_UNUSED_ARG(a);
+  LWIP_ASSERT("LWIP_CONST_CAST not implemented correctly. Check your lwIP port.", LWIP_CONST_CAST(void*, &a) == &a);
+#endif
 #ifndef LWIP_SKIP_PACKING_CHECK
   LWIP_ASSERT("Struct packing not implemented correctly. Check your lwIP port.", sizeof(struct packed_struct_test) == PACKED_STRUCT_TEST_EXPECTED_SIZE);
 #endif
 
   /* Modules initialization */
-  lwip_stats_init();
+  stats_init();
 #if !NO_SYS
   sys_init();
 #endif /* !NO_SYS */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/ipv4/autoip.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/ipv4/autoip.c b/net/ip/lwip_base/src/core/ipv4/autoip.c
index 01fccf8..10db8a3 100644
--- a/net/ip/lwip_base/src/core/ipv4/autoip.c
+++ b/net/ip/lwip_base/src/core/ipv4/autoip.c
@@ -68,7 +68,6 @@
 #include "lwip/etharp.h"
 #include "lwip/prot/autoip.h"
 
-#include <stdlib.h>
 #include <string.h>
 
 /** Pseudo random macro based on netif informations.
@@ -87,7 +86,7 @@
  */
 #ifndef LWIP_AUTOIP_CREATE_SEED_ADDR
 #define LWIP_AUTOIP_CREATE_SEED_ADDR(netif) \
-  htonl(AUTOIP_RANGE_START + ((u32_t)(((u8_t)(netif->hwaddr[4])) | \
+  lwip_htonl(AUTOIP_RANGE_START + ((u32_t)(((u8_t)(netif->hwaddr[4])) | \
                  ((u32_t)((u8_t)(netif->hwaddr[5]))) << 8)))
 #endif /* LWIP_AUTOIP_CREATE_SEED_ADDR */
 
@@ -95,8 +94,6 @@
 static err_t autoip_arp_announce(struct netif *netif);
 static void autoip_start_probing(struct netif *netif);
 
-#define netif_autoip_data(netif) ((struct autoip*)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_AUTOIP))
-
 /**
  * @ingroup autoip 
  * Set a statically allocated struct autoip to work with.
@@ -176,7 +173,7 @@ autoip_create_addr(struct netif *netif, ip4_addr_t *ipaddr)
    * compliant to RFC 3927 Section 2.1
    * We have 254 * 256 possibilities */
 
-  u32_t addr = ntohl(LWIP_AUTOIP_CREATE_SEED_ADDR(netif));
+  u32_t addr = lwip_ntohl(LWIP_AUTOIP_CREATE_SEED_ADDR(netif));
   addr += autoip->tried_llipaddr;
   addr = AUTOIP_NET | (addr & 0xffff);
   /* Now, 169.254.0.0 <= addr <= 169.254.255.255 */
@@ -189,7 +186,7 @@ autoip_create_addr(struct netif *netif, ip4_addr_t *ipaddr)
   }
   LWIP_ASSERT("AUTOIP address not in range", (addr >= AUTOIP_RANGE_START) &&
     (addr <= AUTOIP_RANGE_END));
-  ip4_addr_set_u32(ipaddr, htonl(addr));
+  ip4_addr_set_u32(ipaddr, lwip_htonl(addr));
 
   LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
     ("autoip_create_addr(): tried_llipaddr=%"U16_F", %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n",
@@ -264,7 +261,7 @@ autoip_start(struct netif *netif)
   /* Set IP-Address, Netmask and Gateway to 0 to make sure that
    * ARP Packets are formed correctly
    */
-  netif_set_addr(netif, IP4_ADDR_ANY, IP4_ADDR_ANY, IP4_ADDR_ANY);
+  netif_set_addr(netif, IP4_ADDR_ANY4, IP4_ADDR_ANY4, IP4_ADDR_ANY4);
 
   LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
     ("autoip_start(netif=%p) %c%c%"U16_F"\n", (void*)netif, netif->name[0],
@@ -355,7 +352,7 @@ autoip_stop(struct netif *netif)
   if (autoip != NULL) {
     autoip->state = AUTOIP_STATE_OFF;
     if (ip4_addr_islinklocal(netif_ip4_addr(netif))) {
-      netif_set_addr(netif, IP4_ADDR_ANY, IP4_ADDR_ANY, IP4_ADDR_ANY);
+      netif_set_addr(netif, IP4_ADDR_ANY4, IP4_ADDR_ANY4, IP4_ADDR_ANY4);
     }
   }
   return ERR_OK;
@@ -482,7 +479,8 @@ autoip_arp_reply(struct netif *netif, struct etharp_hdr *hdr)
       * ip.dst == llipaddr && hw.src != own hwaddr
       */
       if ((ip4_addr_cmp(&sipaddr, &autoip->llipaddr)) ||
-          (ip4_addr_cmp(&dipaddr, &autoip->llipaddr) &&
+          (ip4_addr_isany_val(sipaddr) &&
+           ip4_addr_cmp(&dipaddr, &autoip->llipaddr) &&
            !eth_addr_cmp(&netifaddr, &hdr->shwaddr))) {
         LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE | LWIP_DBG_LEVEL_WARNING,
           ("autoip_arp_reply(): Probe Conflict detected\n"));

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/ipv4/dhcp.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/ipv4/dhcp.c b/net/ip/lwip_base/src/core/ipv4/dhcp.c
index 4ffd86b..dd35471 100644
--- a/net/ip/lwip_base/src/core/ipv4/dhcp.c
+++ b/net/ip/lwip_base/src/core/ipv4/dhcp.c
@@ -103,26 +103,40 @@
 
 #define REBOOT_TRIES                2
 
+#if LWIP_DNS && LWIP_DHCP_MAX_DNS_SERVERS
+#if DNS_MAX_SERVERS > LWIP_DHCP_MAX_DNS_SERVERS
+#define LWIP_DHCP_PROVIDE_DNS_SERVERS LWIP_DHCP_MAX_DNS_SERVERS
+#else
+#define LWIP_DHCP_PROVIDE_DNS_SERVERS DNS_MAX_SERVERS
+#endif
+#else
+#define LWIP_DHCP_PROVIDE_DNS_SERVERS 0
+#endif
+
 /** Option handling: options are parsed in dhcp_parse_reply
  * and saved in an array where other functions can load them from.
  * This might be moved into the struct dhcp (not necessarily since
  * lwIP is single-threaded and the array is only used while in recv
  * callback). */
-#define DHCP_OPTION_IDX_OVERLOAD    0
-#define DHCP_OPTION_IDX_MSG_TYPE    1
-#define DHCP_OPTION_IDX_SERVER_ID   2
-#define DHCP_OPTION_IDX_LEASE_TIME  3
-#define DHCP_OPTION_IDX_T1          4
-#define DHCP_OPTION_IDX_T2          5
-#define DHCP_OPTION_IDX_SUBNET_MASK 6
-#define DHCP_OPTION_IDX_ROUTER      7
-#define DHCP_OPTION_IDX_DNS_SERVER  8
+enum dhcp_option_idx {
+  DHCP_OPTION_IDX_OVERLOAD = 0,
+  DHCP_OPTION_IDX_MSG_TYPE,
+  DHCP_OPTION_IDX_SERVER_ID,
+  DHCP_OPTION_IDX_LEASE_TIME,
+  DHCP_OPTION_IDX_T1,
+  DHCP_OPTION_IDX_T2,
+  DHCP_OPTION_IDX_SUBNET_MASK,
+  DHCP_OPTION_IDX_ROUTER,
+#if LWIP_DHCP_PROVIDE_DNS_SERVERS
+  DHCP_OPTION_IDX_DNS_SERVER,
+  DHCP_OPTION_IDX_DNS_SERVER_LAST = DHCP_OPTION_IDX_DNS_SERVER + LWIP_DHCP_PROVIDE_DNS_SERVERS - 1,
+#endif /* LWIP_DHCP_PROVIDE_DNS_SERVERS */
 #if LWIP_DHCP_GET_NTP_SRV
-#define DHCP_OPTION_IDX_NTP_SERVER  (DHCP_OPTION_IDX_DNS_SERVER + DNS_MAX_SERVERS)
-#define DHCP_OPTION_IDX_MAX         (DHCP_OPTION_IDX_NTP_SERVER + LWIP_DHCP_MAX_NTP_SERVERS)
-#else /* LWIP_DHCP_GET_NTP_SRV */
-#define DHCP_OPTION_IDX_MAX         (DHCP_OPTION_IDX_DNS_SERVER + DNS_MAX_SERVERS)
+  DHCP_OPTION_IDX_NTP_SERVER,
+  DHCP_OPTION_IDX_NTP_SERVER_LAST = DHCP_OPTION_IDX_NTP_SERVER + LWIP_DHCP_MAX_NTP_SERVERS - 1,
 #endif /* LWIP_DHCP_GET_NTP_SRV */
+  DHCP_OPTION_IDX_MAX
+};
 
 /** Holds the decoded option values, only valid while in dhcp_recv.
     @todo: move this into struct dhcp? */
@@ -135,8 +149,10 @@ u8_t  dhcp_rx_options_given[DHCP_OPTION_IDX_MAX];
 static u8_t dhcp_discover_request_options[] = {
   DHCP_OPTION_SUBNET_MASK,
   DHCP_OPTION_ROUTER,
-  DHCP_OPTION_BROADCAST,
-  DHCP_OPTION_DNS_SERVER
+  DHCP_OPTION_BROADCAST
+#if LWIP_DHCP_PROVIDE_DNS_SERVERS
+  , DHCP_OPTION_DNS_SERVER
+#endif /* LWIP_DHCP_PROVIDE_DNS_SERVERS */
 #if LWIP_DHCP_GET_NTP_SRV
   , DHCP_OPTION_NTP
 #endif /* LWIP_DHCP_GET_NTP_SRV */
@@ -193,8 +209,6 @@ static void dhcp_option_hostname(struct dhcp *dhcp, struct netif *netif);
 /* always add the DHCP options trailer to end and pad */
 static void dhcp_option_trailer(struct dhcp *dhcp);
 
-#define netif_dhcp_data(netif) ((struct dhcp*)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_DHCP))
-
 /** Ensure DHCP PCB is allocated and bound */
 static err_t
 dhcp_inc_pcb_refcount(void)
@@ -212,8 +226,8 @@ dhcp_inc_pcb_refcount(void)
     ip_set_option(dhcp_pcb, SOF_BROADCAST);
 
     /* set up local and remote port for the pcb -> listen on all interfaces on all src/dest IPs */
-    udp_bind(dhcp_pcb, IP_ADDR_ANY, DHCP_CLIENT_PORT);
-    udp_connect(dhcp_pcb, IP_ADDR_ANY, DHCP_SERVER_PORT);
+    udp_bind(dhcp_pcb, IP4_ADDR_ANY, DHCP_CLIENT_PORT);
+    udp_connect(dhcp_pcb, IP4_ADDR_ANY, DHCP_SERVER_PORT);
     udp_recv(dhcp_pcb, dhcp_recv, NULL);
   }
 
@@ -258,7 +272,7 @@ dhcp_handle_nak(struct netif *netif)
      to ensure the callback can use dhcp_supplied_address() */
   dhcp_set_state(dhcp, DHCP_STATE_BACKING_OFF);
   /* remove IP address from interface (must no longer be used, as per RFC2131) */
-  netif_set_addr(netif, IP4_ADDR_ANY, IP4_ADDR_ANY, IP4_ADDR_ANY);
+  netif_set_addr(netif, IP4_ADDR_ANY4, IP4_ADDR_ANY4, IP4_ADDR_ANY4);
   /* We can immediately restart discovery */
   dhcp_discover(netif);
 }
@@ -311,7 +325,7 @@ dhcp_handle_offer(struct netif *netif)
     (void*)netif, netif->name[0], netif->name[1], (u16_t)netif->num));
   /* obtain the server address */
   if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_SERVER_ID)) {
-    ip_addr_set_ip4_u32(&dhcp->server_ip_addr, htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_SERVER_ID)));
+    ip_addr_set_ip4_u32(&dhcp->server_ip_addr, lwip_htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_SERVER_ID)));
     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_STATE, ("dhcp_handle_offer(): server 0x%08"X32_F"\n",
       ip4_addr_get_u32(ip_2_ip4(&dhcp->server_ip_addr))));
     /* remember offered address */
@@ -353,10 +367,10 @@ dhcp_select(struct netif *netif)
 
     /* MUST request the offered IP address */
     dhcp_option(dhcp, DHCP_OPTION_REQUESTED_IP, 4);
-    dhcp_option_long(dhcp, ntohl(ip4_addr_get_u32(&dhcp->offered_ip_addr)));
+    dhcp_option_long(dhcp, lwip_ntohl(ip4_addr_get_u32(&dhcp->offered_ip_addr)));
 
     dhcp_option(dhcp, DHCP_OPTION_SERVER_ID, 4);
-    dhcp_option_long(dhcp, ntohl(ip4_addr_get_u32(ip_2_ip4(&dhcp->server_ip_addr))));
+    dhcp_option_long(dhcp, lwip_ntohl(ip4_addr_get_u32(ip_2_ip4(&dhcp->server_ip_addr))));
 
     dhcp_option(dhcp, DHCP_OPTION_PARAMETER_REQUEST_LIST, LWIP_ARRAYSIZE(dhcp_discover_request_options));
     for (i = 0; i < LWIP_ARRAYSIZE(dhcp_discover_request_options); i++) {
@@ -372,7 +386,7 @@ dhcp_select(struct netif *netif)
     pbuf_realloc(dhcp->p_out, sizeof(struct dhcp_msg) - DHCP_OPTIONS_LEN + dhcp->options_out_len);
 
     /* send broadcast to any DHCP server */
-    udp_sendto_if_src(dhcp_pcb, dhcp->p_out, IP_ADDR_BROADCAST, DHCP_SERVER_PORT, netif, IP_ADDR_ANY);
+    udp_sendto_if_src(dhcp_pcb, dhcp->p_out, IP_ADDR_BROADCAST, DHCP_SERVER_PORT, netif, IP4_ADDR_ANY);
     dhcp_delete_msg(dhcp);
     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_select: REQUESTING\n"));
   } else {
@@ -572,9 +586,9 @@ dhcp_handle_ack(struct netif *netif)
 {
   struct dhcp *dhcp = netif_dhcp_data(netif);
 
-#if LWIP_DNS || LWIP_DHCP_GET_NTP_SRV
+#if LWIP_DHCP_PROVIDE_DNS_SERVERS || LWIP_DHCP_GET_NTP_SRV
   u8_t n;
-#endif /* LWIP_DNS || LWIP_DHCP_GET_NTP_SRV */
+#endif /* LWIP_DHCP_PROVIDE_DNS_SERVERS || LWIP_DHCP_GET_NTP_SRV */
 #if LWIP_DHCP_GET_NTP_SRV
   ip4_addr_t ntp_server_addrs[LWIP_DHCP_MAX_NTP_SERVERS];
 #endif
@@ -621,7 +635,7 @@ dhcp_handle_ack(struct netif *netif)
   /* subnet mask given? */
   if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_SUBNET_MASK)) {
     /* remember given subnet mask */
-    ip4_addr_set_u32(&dhcp->offered_sn_mask, htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_SUBNET_MASK)));
+    ip4_addr_set_u32(&dhcp->offered_sn_mask, lwip_htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_SUBNET_MASK)));
     dhcp->subnet_mask_given = 1;
   } else {
     dhcp->subnet_mask_given = 0;
@@ -629,25 +643,25 @@ dhcp_handle_ack(struct netif *netif)
 
   /* gateway router */
   if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_ROUTER)) {
-    ip4_addr_set_u32(&dhcp->offered_gw_addr, htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_ROUTER)));
+    ip4_addr_set_u32(&dhcp->offered_gw_addr, lwip_htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_ROUTER)));
   }
 
 #if LWIP_DHCP_GET_NTP_SRV
   /* NTP servers */
   for (n = 0; (n < LWIP_DHCP_MAX_NTP_SERVERS) && dhcp_option_given(dhcp, DHCP_OPTION_IDX_NTP_SERVER + n); n++) {
-    ip4_addr_set_u32(&ntp_server_addrs[n], htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_NTP_SERVER + n)));
+    ip4_addr_set_u32(&ntp_server_addrs[n], lwip_htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_NTP_SERVER + n)));
   }
   dhcp_set_ntp_servers(n, ntp_server_addrs);
 #endif /* LWIP_DHCP_GET_NTP_SRV */
 
-#if LWIP_DNS
+#if LWIP_DHCP_PROVIDE_DNS_SERVERS
   /* DNS servers */
-  for (n = 0; (n < DNS_MAX_SERVERS) && dhcp_option_given(dhcp, DHCP_OPTION_IDX_DNS_SERVER + n); n++) {
+  for (n = 0; (n < LWIP_DHCP_PROVIDE_DNS_SERVERS) && dhcp_option_given(dhcp, DHCP_OPTION_IDX_DNS_SERVER + n); n++) {
     ip_addr_t dns_addr;
-    ip_addr_set_ip4_u32(&dns_addr, htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_DNS_SERVER + n)));
+    ip_addr_set_ip4_u32(&dns_addr, lwip_htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_DNS_SERVER + n)));
     dns_setserver(n, &dns_addr);
   }
-#endif /* LWIP_DNS */
+#endif /* LWIP_DHCP_PROVIDE_DNS_SERVERS */
 }
 
 /**
@@ -913,14 +927,14 @@ dhcp_decline(struct netif *netif)
   result = dhcp_create_msg(netif, dhcp, DHCP_DECLINE);
   if (result == ERR_OK) {
     dhcp_option(dhcp, DHCP_OPTION_REQUESTED_IP, 4);
-    dhcp_option_long(dhcp, ntohl(ip4_addr_get_u32(&dhcp->offered_ip_addr)));
+    dhcp_option_long(dhcp, lwip_ntohl(ip4_addr_get_u32(&dhcp->offered_ip_addr)));
 
     dhcp_option_trailer(dhcp);
     /* resize pbuf to reflect true size of options */
     pbuf_realloc(dhcp->p_out, sizeof(struct dhcp_msg) - DHCP_OPTIONS_LEN + dhcp->options_out_len);
 
     /* per section 4.4.4, broadcast DECLINE messages */
-    udp_sendto_if_src(dhcp_pcb, dhcp->p_out, IP_ADDR_BROADCAST, DHCP_SERVER_PORT, netif, IP_ADDR_ANY);
+    udp_sendto_if_src(dhcp_pcb, dhcp->p_out, IP_ADDR_BROADCAST, DHCP_SERVER_PORT, netif, IP4_ADDR_ANY);
     dhcp_delete_msg(dhcp);
     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_decline: BACKING OFF\n"));
   } else {
@@ -971,7 +985,7 @@ dhcp_discover(struct netif *netif)
     pbuf_realloc(dhcp->p_out, sizeof(struct dhcp_msg) - DHCP_OPTIONS_LEN + dhcp->options_out_len);
 
     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_discover: sendto(DISCOVER, IP_ADDR_BROADCAST, DHCP_SERVER_PORT)\n"));
-    udp_sendto_if_src(dhcp_pcb, dhcp->p_out, IP_ADDR_BROADCAST, DHCP_SERVER_PORT, netif, IP_ADDR_ANY);
+    udp_sendto_if_src(dhcp_pcb, dhcp->p_out, IP_ADDR_BROADCAST, DHCP_SERVER_PORT, netif, IP4_ADDR_ANY);
     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_discover: deleting()ing\n"));
     dhcp_delete_msg(dhcp);
     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_discover: SELECTING\n"));
@@ -1225,10 +1239,10 @@ dhcp_reboot(struct netif *netif)
   result = dhcp_create_msg(netif, dhcp, DHCP_REQUEST);
   if (result == ERR_OK) {
     dhcp_option(dhcp, DHCP_OPTION_MAX_MSG_SIZE, DHCP_OPTION_MAX_MSG_SIZE_LEN);
-    dhcp_option_short(dhcp, 576);
+    dhcp_option_short(dhcp, DHCP_MAX_MSG_LEN_MIN_REQUIRED);
 
     dhcp_option(dhcp, DHCP_OPTION_REQUESTED_IP, 4);
-    dhcp_option_long(dhcp, ntohl(ip4_addr_get_u32(&dhcp->offered_ip_addr)));
+    dhcp_option_long(dhcp, lwip_ntohl(ip4_addr_get_u32(&dhcp->offered_ip_addr)));
 
     dhcp_option(dhcp, DHCP_OPTION_PARAMETER_REQUEST_LIST, LWIP_ARRAYSIZE(dhcp_discover_request_options));
     for (i = 0; i < LWIP_ARRAYSIZE(dhcp_discover_request_options); i++) {
@@ -1300,7 +1314,7 @@ dhcp_release(struct netif *netif)
   result = dhcp_create_msg(netif, dhcp, DHCP_RELEASE);
   if (result == ERR_OK) {
     dhcp_option(dhcp, DHCP_OPTION_SERVER_ID, 4);
-    dhcp_option_long(dhcp, ntohl(ip4_addr_get_u32(ip_2_ip4(&server_ip_addr))));
+    dhcp_option_long(dhcp, lwip_ntohl(ip4_addr_get_u32(ip_2_ip4(&server_ip_addr))));
 
     dhcp_option_trailer(dhcp);
 
@@ -1314,7 +1328,7 @@ dhcp_release(struct netif *netif)
     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp_release: could not allocate DHCP request\n"));
   }
   /* remove IP address from interface (prevents routing from selecting this interface) */
-  netif_set_addr(netif, IP4_ADDR_ANY, IP4_ADDR_ANY, IP4_ADDR_ANY);
+  netif_set_addr(netif, IP4_ADDR_ANY4, IP4_ADDR_ANY4, IP4_ADDR_ANY4);
 
   return result;
 }
@@ -1517,14 +1531,16 @@ again:
         LWIP_ERROR("len >= decode_len", len >= decode_len, return ERR_VAL;);
         decode_idx = DHCP_OPTION_IDX_ROUTER;
         break;
+#if LWIP_DHCP_PROVIDE_DNS_SERVERS
       case(DHCP_OPTION_DNS_SERVER):
         /* special case: there might be more than one server */
-        LWIP_ERROR("len % 4 == 0", len % 4 == 0, return ERR_VAL;);
+        LWIP_ERROR("len %% 4 == 0", len % 4 == 0, return ERR_VAL;);
         /* limit number of DNS servers */
         decode_len = LWIP_MIN(len, 4 * DNS_MAX_SERVERS);
         LWIP_ERROR("len >= decode_len", len >= decode_len, return ERR_VAL;);
         decode_idx = DHCP_OPTION_IDX_DNS_SERVER;
         break;
+#endif /* LWIP_DHCP_PROVIDE_DNS_SERVERS */
       case(DHCP_OPTION_LEASE_TIME):
         LWIP_ERROR("len == 4", len == 4, return ERR_VAL;);
         decode_idx = DHCP_OPTION_IDX_LEASE_TIME;
@@ -1532,7 +1548,7 @@ again:
 #if LWIP_DHCP_GET_NTP_SRV
       case(DHCP_OPTION_NTP):
         /* special case: there might be more than one server */
-        LWIP_ERROR("len % 4 == 0", len % 4 == 0, return ERR_VAL;);
+        LWIP_ERROR("len %% 4 == 0", len % 4 == 0, return ERR_VAL;);
         /* limit number of NTP servers */
         decode_len = LWIP_MIN(len, 4 * LWIP_DHCP_MAX_NTP_SERVERS);
         LWIP_ERROR("len >= decode_len", len >= decode_len, return ERR_VAL;);
@@ -1541,6 +1557,8 @@ again:
 #endif /* LWIP_DHCP_GET_NTP_SRV*/
       case(DHCP_OPTION_OVERLOAD):
         LWIP_ERROR("len == 1", len == 1, return ERR_VAL;);
+        /* decode overload only in options, not in file/sname: invalid packet */
+        LWIP_ERROR("overload in file/sname", options_idx == DHCP_OPTIONS_OFS, return ERR_VAL;);
         decode_idx = DHCP_OPTION_IDX_OVERLOAD;
         break;
       case(DHCP_OPTION_MESSAGE_TYPE):
@@ -1577,15 +1595,15 @@ decode_next:
         }
         if (decode_len > 4) {
           /* decode more than one u32_t */
-          LWIP_ERROR("decode_len % 4 == 0", decode_len % 4 == 0, return ERR_VAL;);
+          LWIP_ERROR("decode_len %% 4 == 0", decode_len % 4 == 0, return ERR_VAL;);
           dhcp_got_option(dhcp, decode_idx);
-          dhcp_set_option_value(dhcp, decode_idx, htonl(value));
+          dhcp_set_option_value(dhcp, decode_idx, lwip_htonl(value));
           decode_len -= 4;
           val_offset += 4;
           decode_idx++;
           goto decode_next;
         } else if (decode_len == 4) {
-          value = ntohl(value);
+          value = lwip_ntohl(value);
         } else {
           LWIP_ERROR("invalid decode_len", decode_len == 1, return ERR_VAL;);
           value = ((u8_t*)&value)[0];
@@ -1704,9 +1722,9 @@ dhcp_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr,
     }
   }
   /* match transaction ID against what we expected */
-  if (ntohl(reply_msg->xid) != dhcp->xid) {
+  if (lwip_ntohl(reply_msg->xid) != dhcp->xid) {
     LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING,
-      ("transaction id mismatch reply_msg->xid(%"X32_F")!=dhcp->xid(%"X32_F")\n",ntohl(reply_msg->xid),dhcp->xid));
+      ("transaction id mismatch reply_msg->xid(%"X32_F")!=dhcp->xid(%"X32_F")\n",lwip_ntohl(reply_msg->xid),dhcp->xid));
     goto free_pbuf_and_return;
   }
   /* option fields could be unfold? */
@@ -1835,7 +1853,7 @@ dhcp_create_msg(struct netif *netif, struct dhcp *dhcp, u8_t message_type)
   dhcp->msg_out->htype = DHCP_HTYPE_ETH;
   dhcp->msg_out->hlen = netif->hwaddr_len;
   dhcp->msg_out->hops = 0;
-  dhcp->msg_out->xid = htonl(dhcp->xid);
+  dhcp->msg_out->xid = lwip_htonl(dhcp->xid);
   dhcp->msg_out->secs = 0;
   /* we don't need the broadcast flag since we can receive unicast traffic
      before being fully configured! */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f52033e9/net/ip/lwip_base/src/core/ipv4/etharp.c
----------------------------------------------------------------------
diff --git a/net/ip/lwip_base/src/core/ipv4/etharp.c b/net/ip/lwip_base/src/core/ipv4/etharp.c
index 364023e..3f48a99 100644
--- a/net/ip/lwip_base/src/core/ipv4/etharp.c
+++ b/net/ip/lwip_base/src/core/ipv4/etharp.c
@@ -56,6 +56,10 @@
 
 #include <string.h>
 
+#ifdef LWIP_HOOK_FILENAME
+#include LWIP_HOOK_FILENAME
+#endif
+
 #if LWIP_IPV4 && LWIP_ARP /* don't build if not configured for use in lwipopts.h */
 
 /** Re-request a used ARP entry 1 minute before it would expire to prevent
@@ -72,6 +76,7 @@
  */
 #define ARP_MAXPENDING 5
 
+/** ARP states */
 enum etharp_state {
   ETHARP_STATE_EMPTY = 0,
   ETHARP_STATE_PENDING,
@@ -127,7 +132,11 @@ static u8_t etharp_cached_entry;
 
 
 static err_t etharp_request_dst(struct netif *netif, const ip4_addr_t *ipaddr, const struct eth_addr* hw_dst_addr);
-
+static err_t etharp_raw(struct netif *netif,
+                        const struct eth_addr *ethsrc_addr, const struct eth_addr *ethdst_addr,
+                        const struct eth_addr *hwsrc_addr, const ip4_addr_t *ipsrc_addr,
+                        const struct eth_addr *hwdst_addr, const ip4_addr_t *ipdst_addr,
+                        const u16_t opcode);
 
 #if ARP_QUEUEING
 /**
@@ -239,7 +248,7 @@ etharp_tmr(void)
  * old entries. Heuristic choose the least important entry for recycling.
  *
  * @param ipaddr IP address to find in ARP cache, or to add if not found.
- * @param flags @see definition of ETHARP_FLAG_*
+ * @param flags See @ref etharp_state
  * @param netif netif related to this address (used for NETIF_HWADDRHINT)
  *
  * @return The ARP entry index that matched or is created, ERR_MEM if no
@@ -402,7 +411,7 @@ etharp_find_entry(const ip4_addr_t *ipaddr, u8_t flags, struct netif* netif)
  * @param netif netif related to this entry (used for NETIF_ADDRHINT)
  * @param ipaddr IP address of the inserted ARP entry.
  * @param ethaddr Ethernet address of the inserted ARP entry.
- * @param flags @see definition of ETHARP_FLAG_*
+ * @param flags See @ref etharp_state
  *
  * @return
  * - ERR_OK Successfully updated ARP cache.
@@ -490,7 +499,7 @@ etharp_update_arp_entry(struct netif *netif, const ip4_addr_t *ipaddr, struct et
  *
  * @param ipaddr IP address for the new static entry
  * @param ethaddr ethernet address for the new static entry
- * @return @see return values of etharp_add_static_entry
+ * @return See return values of etharp_add_static_entry
  */
 err_t
 etharp_add_static_entry(const ip4_addr_t *ipaddr, struct eth_addr *ethaddr)
@@ -626,8 +635,6 @@ etharp_get_entry(u8_t i, ip4_addr_t **ipaddr, struct netif **netif, struct eth_a
  * @param p The ARP packet that arrived on netif. Is freed by this function.
  * @param netif The lwIP network interface on which the ARP packet pbuf arrived.
  *
- * @return NULL
- *
  * @see pbuf_free()
  */
 void
@@ -696,38 +703,12 @@ etharp_input(struct pbuf *p, struct netif *netif)
     LWIP_DEBUGF (ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_input: incoming ARP request\n"));
     /* ARP request for our address? */
     if (for_us) {
-
-      LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_input: replying to ARP request for our IP address\n"));
-      /* Re-use pbuf to send ARP reply.
-         Since we are re-using an existing pbuf, we can't call etharp_raw since
-         that would allocate a new pbuf. */
-      hdr->opcode = htons(ARP_REPLY);
-
-      IPADDR2_COPY(&hdr->dipaddr, &hdr->sipaddr);
-      IPADDR2_COPY(&hdr->sipaddr, netif_ip4_addr(netif));
-
-      LWIP_ASSERT("netif->hwaddr_len must be the same as ETH_HWADDR_LEN for etharp!",
-                  (netif->hwaddr_len == ETH_HWADDR_LEN));
-
-      /* hwtype, hwaddr_len, proto, protolen and the type in the ethernet header
-         are already correct, we tested that before */
-
-      ETHADDR16_COPY(&hdr->dhwaddr, &hdr->shwaddr);
-      ETHADDR16_COPY(&hdr->shwaddr, netif->hwaddr);
-
-      /* return ARP reply */
-#if LWIP_AUTOIP
-      /* If we are using Link-Local, all ARP packets that contain a Link-Local
-       * 'sender IP address' MUST be sent using link-layer broadcast instead of
-       * link-layer unicast. (See RFC3927 Section 2.5, last paragraph) */
-      if (ip4_addr_islinklocal(netif_ip4_addr(netif))) {
-        ethernet_output(netif, p, &hdr->shwaddr, &ethbroadcast, ETHTYPE_ARP);
-      } else
-#endif /* LWIP_AUTOIP */
-      {
-        ethernet_output(netif, p, &hdr->shwaddr, &hdr->dhwaddr, ETHTYPE_ARP);
-      }
-
+      /* send ARP response */
+      etharp_raw(netif,
+                 (struct eth_addr *)netif->hwaddr, &hdr->shwaddr,
+                 (struct eth_addr *)netif->hwaddr, netif_ip4_addr(netif),
+                 &hdr->shwaddr, &sipaddr,
+                 ARP_REPLY);
     /* we are not configured? */
     } else if (ip4_addr_isany_val(*netif_ip4_addr(netif))) {
       /* { for_us == 0 and netif->ip_addr.addr == 0 } */
@@ -750,7 +731,7 @@ etharp_input(struct pbuf *p, struct netif *netif)
 #endif /* (LWIP_DHCP && DHCP_DOES_ARP_CHECK) */
     break;
   default:
-    LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_input: ARP unknown opcode type %"S16_F"\n", htons(hdr->opcode)));
+    LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_input: ARP unknown opcode type %"S16_F"\n", lwip_htons(hdr->opcode)));
     ETHARP_STATS_INC(etharp.err);
     break;
   }
@@ -841,7 +822,7 @@ etharp_output(struct netif *netif, struct pbuf *q, const ip4_addr_t *ipaddr)
     if (!ip4_addr_netcmp(ipaddr, netif_ip4_addr(netif), netif_ip4_netmask(netif)) &&
         !ip4_addr_islinklocal(ipaddr)) {
 #if LWIP_AUTOIP
-      struct ip_hdr *iphdr = (struct ip_hdr*)(size_t)q->payload;
+      struct ip_hdr *iphdr = LWIP_ALIGNMENT_CAST(struct ip_hdr*, q->payload);
       /* According to RFC 3297, chapter 2.6.2 (Forwarding Rules), a packet with
          a link-local source address must always be "directly to its destination
          on the same physical link. The host MUST NOT send the packet to any
@@ -875,6 +856,9 @@ etharp_output(struct netif *netif, struct pbuf *q, const ip4_addr_t *ipaddr)
       if (etharp_cached_entry < ARP_TABLE_SIZE) {
 #endif /* LWIP_NETIF_HWADDRHINT */
         if ((arp_table[etharp_cached_entry].state >= ETHARP_STATE_STABLE) &&
+#if ETHARP_TABLE_MATCH_NETIF
+            (arp_table[etharp_cached_entry].netif == netif) &&
+#endif
             (ip4_addr_cmp(dst_addr, &arp_table[etharp_cached_entry].ipaddr))) {
           /* the per-pcb-cached entry is stable and the right one! */
           ETHARP_STATS_INC(etharp.cachehit);
@@ -889,6 +873,9 @@ etharp_output(struct netif *netif, struct pbuf *q, const ip4_addr_t *ipaddr)
        throughput and etharp_find_entry() is kind of slow */
     for (i = 0; i < ARP_TABLE_SIZE; i++) {
       if ((arp_table[i].state >= ETHARP_STATE_STABLE) &&
+#if ETHARP_TABLE_MATCH_NETIF
+          (arp_table[i].netif == netif) &&
+#endif
           (ip4_addr_cmp(dst_addr, &arp_table[i].ipaddr))) {
         /* found an existing, stable entry */
         ETHARP_SET_HINT(netif, i);
@@ -1138,7 +1125,7 @@ etharp_raw(struct netif *netif, const struct eth_addr *ethsrc_addr,
 
   hdr = (struct etharp_hdr *)p->payload;
   LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_raw: sending raw ARP packet.\n"));
-  hdr->opcode = htons(opcode);
+  hdr->opcode = lwip_htons(opcode);
 
   LWIP_ASSERT("netif->hwaddr_len must be the same as ETH_HWADDR_LEN for etharp!",
               (netif->hwaddr_len == ETH_HWADDR_LEN));