Merge commit '66e4691ad097cfc37bdb7d3b1705ee9132f3234e' into donut
diff --git a/Android.mk b/Android.mk
index 8b79ceb..fa2f6f8 100644
--- a/Android.mk
+++ b/Android.mk
@@ -21,6 +21,7 @@
   include $(addprefix $(LOCAL_PATH)/,$(addsuffix /Android.mk, \
 	      adb \
 	      libcutils \
+	      libsysutils \
 	      liblog \
 	      libnetutils \
 	      libpixelflinger \
diff --git a/adb/Android.mk b/adb/Android.mk
index ed8b501..9725478 100644
--- a/adb/Android.mk
+++ b/adb/Android.mk
@@ -7,7 +7,6 @@
 
 # adb host tool
 # =========================================================
-ifneq ($(TARGET_SIMULATOR),true) # not 64 bit clean (also unused with the sim)
 include $(CLEAR_VARS)
 
 # Default to a virtual (sockets) usb interface
@@ -59,6 +58,8 @@
 
 ifneq ($(USE_SYSDEPS_WIN32),)
   LOCAL_SRC_FILES += sysdeps_win32.c
+else
+  LOCAL_SRC_FILES += fdevent.c
 endif
 
 LOCAL_CFLAGS += -O2 -g -DADB_HOST=1  -Wall -Wno-unused-parameter
@@ -78,7 +79,6 @@
 $(LOCAL_INSTALLED_MODULE): $(HOST_OUT_EXECUTABLES)/AdbWinApi.dll
 endif
 
-endif
 
 # adbd device daemon
 # =========================================================
@@ -101,6 +101,7 @@
 
 LOCAL_SRC_FILES := \
 	adb.c \
+	fdevent.c \
 	transport.c \
 	transport_local.c \
 	transport_usb.c \
diff --git a/adb/adb.c b/adb/adb.c
index 36130cd..956df54 100644
--- a/adb/adb.c
+++ b/adb/adb.c
@@ -23,6 +23,7 @@
 #include <errno.h>
 #include <string.h>
 #include <time.h>
+#include <sys/time.h>
 
 #include "sysdeps.h"
 #include "adb.h"
@@ -657,10 +658,25 @@
 void start_device_log(void)
 {
     int fd;
-    char    path[100];
+    char    path[PATH_MAX];
+    struct tm now;
+    time_t t;
+    char value[PROPERTY_VALUE_MAX];
 
-    snprintf(path, sizeof path, "/data/adb_%ld.txt", (long)time(NULL));
-    fd = unix_open(path, O_WRONLY | O_CREAT | O_APPEND, 0640);
+    // read the trace mask from persistent property persist.adb.trace_mask
+    // give up if the property is not set or cannot be parsed
+    property_get("persist.adb.trace_mask", value, "");
+    if (sscanf(value, "%x", &adb_trace_mask) != 1)
+        return;
+
+    adb_mkdir("/data/adb", 0775);
+    tzset();
+    time(&t);
+    localtime_r(&t, &now);
+    strftime(path, sizeof(path),
+                "/data/adb/adb-%Y-%m-%d-%H-%M-%S.txt",
+                &now);
+    fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
     if (fd < 0)
         return;
 
@@ -671,11 +687,6 @@
 
     fd = unix_open("/dev/null", O_RDONLY);
     dup2(fd, 0);
-
-    // log everything
-    adb_trace_mask = ~0;
-    // except TRACE_RWX is a bit too verbose
-    adb_trace_mask &= ~TRACE_RWX;
 }
 #endif
 
@@ -820,19 +831,6 @@
 #if !ADB_HOST
     int secure = 0;
     char value[PROPERTY_VALUE_MAX];
-
-    // prevent the OOM killer from killing us
-    char text[64];
-    snprintf(text, sizeof text, "/proc/%d/oom_adj", (int)getpid());
-    int fd = adb_open(text, O_WRONLY);
-    if (fd >= 0) {
-        // -17 should make us immune to OOM
-        snprintf(text, sizeof text, "%d", -17);
-        adb_write(fd, text, strlen(text));
-        adb_close(fd);
-    } else {
-       D("adb: unable to open %s\n", text);
-    }
 #endif
 
     atexit(adb_cleanup);
@@ -888,9 +886,10 @@
         ** AID_INET to diagnose network issues (netcfg, ping)
         ** AID_GRAPHICS to access the frame buffer
         ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
+        ** AID_SDCARD_RW to allow writing to the SD card
         */
         gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS,
-                           AID_NET_BT, AID_NET_BT_ADMIN };
+                           AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_RW };
         setgroups(sizeof(groups)/sizeof(groups[0]), groups);
 
         /* then switch user and group to "shell" */
@@ -1091,9 +1090,8 @@
         adb_device_banner = "recovery";
         recovery_mode = 1;
     }
-#if ADB_DEVICE_LOG
+
     start_device_log();
-#endif
     return adb_main(0);
 #endif
 }
diff --git a/adb/adb.h b/adb/adb.h
index 6c5fc7c..b9ed556 100644
--- a/adb/adb.h
+++ b/adb/adb.h
@@ -345,11 +345,6 @@
 #endif
 
 
-/* set this to log to /data/adb/adb_<time>.txt on the device.
- * has no effect if the /data/adb/ directory does not exist.
- */
-#define ADB_DEVICE_LOG 0
-
 #if !TRACE_PACKETS
 #define print_packet(tag,p) do {} while (0)
 #endif
@@ -361,6 +356,7 @@
 #define ADB_SUBCLASS           0x42
 #define ADB_PROTOCOL           0x1
 
+
 void local_init();
 int  local_connect(int  port);
 
diff --git a/libcutils/fdevent.c b/adb/fdevent.c
similarity index 98%
rename from libcutils/fdevent.c
rename to adb/fdevent.c
index 4cf46fa..c179b20 100644
--- a/libcutils/fdevent.c
+++ b/adb/fdevent.c
@@ -26,7 +26,7 @@
 #include <stdarg.h>
 #include <stddef.h>
 
-#include <cutils/fdevent.h>
+#include "fdevent.h"
 
 #define TRACE(x...) fprintf(stderr,x)
 
@@ -87,7 +87,7 @@
 {
         /* XXX: what's a good size for the passed in hint? */
     epoll_fd = epoll_create(256);
-    
+
     if(epoll_fd < 0) {
         perror("epoll_create() failed");
         exit(1);
@@ -105,7 +105,7 @@
     ev.events = 0;
     ev.data.ptr = fde;
 
-#if 0    
+#if 0
     if(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fde->fd, &ev)) {
         perror("epoll_ctl() failed\n");
         exit(1);
@@ -116,7 +116,7 @@
 static void fdevent_disconnect(fdevent *fde)
 {
     struct epoll_event ev;
-    
+
     memset(&ev, 0, sizeof(ev));
     ev.events = 0;
     ev.data.ptr = fde;
@@ -133,9 +133,9 @@
 {
     struct epoll_event ev;
     int active;
-    
+
     active = (fde->state & FDE_EVENTMASK) != 0;
-    
+
     memset(&ev, 0, sizeof(ev));
     ev.events = 0;
     ev.data.ptr = fde;
@@ -241,7 +241,7 @@
 static void fdevent_disconnect(fdevent *fde)
 {
     int i, n;
-    
+
     FD_CLR(fde->fd, &read_fds);
     FD_CLR(fde->fd, &write_fds);
     FD_CLR(fde->fd, &error_fds);
@@ -283,9 +283,9 @@
     memcpy(&rfd, &read_fds, sizeof(fd_set));
     memcpy(&wfd, &write_fds, sizeof(fd_set));
     memcpy(&efd, &error_fds, sizeof(fd_set));
-    
+
     n = select(select_n, &rfd, &wfd, &efd, 0);
-    
+
     if(n < 0) {
         if(errno == EINTR) return;
         perror("select");
@@ -300,12 +300,12 @@
 
         if(events) {
             n--;
-            
+
             fde = fd_table[i];
             if(fde == 0) FATAL("missing fde for fd %d\n", i);
 
             fde->events |= events;
-            
+
             if(fde->state & FDE_PENDING) continue;
             fde->state |= FDE_PENDING;
             fdevent_plist_enqueue(fde);
@@ -320,7 +320,7 @@
     if(fde->fd < 0) {
         FATAL("bogus negative fd (%d)\n", fde->fd);
     }
-    
+
     if(fde->fd >= fd_table_max) {
         int oldmax = fd_table_max;
         if(fde->fd > 32000) {
@@ -383,9 +383,9 @@
 {
     fdevent *list = &list_pending;
     fdevent *node = list->next;
-    
+
     if(node == list) return 0;
-    
+
     list->next = node->next;
     list->next->prev = list;
     node->next = 0;
@@ -449,9 +449,9 @@
 void fdevent_set(fdevent *fde, unsigned events)
 {
     events &= FDE_EVENTMASK;
-    
+
     if((fde->state & FDE_EVENTMASK) == events) return;
-    
+
     if(fde->state & FDE_ACTIVE) {
         fdevent_update(fde, events);
         dump_fde(fde, "update");
@@ -487,13 +487,13 @@
 void fdevent_loop()
 {
     fdevent *fde;
-    
+
     for(;;) {
 #if DEBUG
         fprintf(stderr,"--- ---- waiting for events\n");
 #endif
         fdevent_process();
-        
+
         while((fde = fdevent_plist_dequeue())) {
             unsigned events = fde->events;
             fde->events = 0;
diff --git a/include/cutils/fdevent.h b/adb/fdevent.h
similarity index 89%
rename from include/cutils/fdevent.h
rename to adb/fdevent.h
index 7a442d4..6b7e7ec 100644
--- a/include/cutils/fdevent.h
+++ b/adb/fdevent.h
@@ -17,10 +17,13 @@
 #ifndef __FDEVENT_H
 #define __FDEVENT_H
 
+#include <stdint.h>  /* for int64_t */
+
 /* events that may be observed */
 #define FDE_READ              0x0001
 #define FDE_WRITE             0x0002
 #define FDE_ERROR             0x0004
+#define FDE_TIMEOUT           0x0008
 
 /* features that may be set (via the events set/add/del interface) */
 #define FDE_DONT_CLOSE        0x0080
@@ -30,6 +33,8 @@
 typedef void (*fd_func)(int fd, unsigned events, void *userdata);
 
 /* Allocate and initialize a new fdevent object
+ * Note: use FD_TIMER as 'fd' to create a fd-less object
+ * (used to implement timers).
 */
 fdevent *fdevent_create(int fd, fd_func func, void *arg);
 
@@ -53,6 +58,8 @@
 void fdevent_add(fdevent *fde, unsigned events);
 void fdevent_del(fdevent *fde, unsigned events);
 
+void fdevent_set_timeout(fdevent *fde, int64_t  timeout_ms);
+
 /* loop forever, handling events.
 */
 void fdevent_loop();
@@ -65,7 +72,7 @@
     int fd;
     unsigned short state;
     unsigned short events;
-    
+
     fd_func func;
     void *arg;
 };
diff --git a/adb/file_sync_client.c b/adb/file_sync_client.c
index 4e6d385..0ebfe73 100644
--- a/adb/file_sync_client.c
+++ b/adb/file_sync_client.c
@@ -165,7 +165,7 @@
 }
 
 static int sync_finish_readtime(int fd, unsigned int *timestamp,
-				unsigned int *mode, unsigned int *size)
+                                unsigned int *mode, unsigned int *size)
 {
     syncmsg msg;
 
@@ -908,12 +908,12 @@
             unsigned int timestamp, mode, size;
             if (sync_finish_readtime(fd, &timestamp, &mode, &size))
                 return 1;
-	    if (size == ci->size) {
+            if (size == ci->size) {
                 /* for links, we cannot update the atime/mtime */
                 if ((S_ISREG(ci->mode & mode) && timestamp == ci->time) ||
-		   (S_ISLNK(ci->mode & mode) && timestamp >= ci->time))
+                    (S_ISLNK(ci->mode & mode) && timestamp >= ci->time))
                     ci->flag = 1;
-	    }
+            }
         }
     }
 #endif
diff --git a/adb/framebuffer_service.c b/adb/framebuffer_service.c
index 0de0dd5..65cb20a 100644
--- a/adb/framebuffer_service.c
+++ b/adb/framebuffer_service.c
@@ -20,7 +20,7 @@
 #include <string.h>
 #include <fcntl.h>
 
-#include <cutils/fdevent.h>
+#include "fdevent.h"
 #include "adb.h"
 
 #include <linux/fb.h>
diff --git a/adb/protocol.txt b/adb/protocol.txt
index d0f307c..398d042 100644
--- a/adb/protocol.txt
+++ b/adb/protocol.txt
@@ -23,7 +23,7 @@
 
 
 --- protocol overview and basics ---------------------------------------
- 
+
 The transport layer deals in "messages", which consist of a 24 byte
 header followed (optionally) by a payload.  The header consists of 6
 32 bit words which are sent across the wire in little endian format.
@@ -52,7 +52,7 @@
 reversed.
 
 
-
+
 --- CONNECT(version, maxdata, "system-identity-string") ----------------
 
 The CONNECT message establishes the presence of a remote system.
@@ -114,7 +114,7 @@
 not change on later READY messages sent to the same stream.
 
 
-
+
 --- WRITE(0, remote-id, "data") ----------------------------------------
 
 The WRITE message sends data to the recipient's stream identified by
@@ -172,7 +172,7 @@
 #define A_WRTE 0x45545257
 
 
-
+
 --- implementation details ---------------------------------------------
 
 The core of the bridge program will use three threads.  One thread
diff --git a/adb/services.c b/adb/services.c
index 1de55e6..0a5edcf 100644
--- a/adb/services.c
+++ b/adb/services.c
@@ -244,6 +244,18 @@
                 cmd, strerror(errno), errno);
         exit(-1);
     } else {
+#if !ADB_HOST
+        // set child's OOM adjustment to zero
+        char text[64];
+        snprintf(text, sizeof text, "/proc/%d/oom_adj", pid);
+        int fd = adb_open(text, O_WRONLY);
+        if (fd >= 0) {
+            adb_write(fd, "0", 1);
+            adb_close(fd);
+        } else {
+           D("adb: unable to open %s\n", text);
+        }
+#endif
         return ptm;
     }
 #endif /* !HAVE_WIN32_PROC */
diff --git a/adb/sysdeps.h b/adb/sysdeps.h
index e5d17a8..389fbd2 100644
--- a/adb/sysdeps.h
+++ b/adb/sysdeps.h
@@ -67,16 +67,16 @@
 
 static __inline__ int  adb_thread_create( adb_thread_t  *thread, adb_thread_func_t  func, void*  arg)
 {
-	thread->tid = _beginthread( (win_thread_func_t)func, 0, arg );
-	if (thread->tid == (unsigned)-1L) {
-		return -1;
-	}
-	return 0;
+    thread->tid = _beginthread( (win_thread_func_t)func, 0, arg );
+    if (thread->tid == (unsigned)-1L) {
+        return -1;
+    }
+    return 0;
 }
 
 static __inline__ void  close_on_exec(int  fd)
 {
-	/* nothing really */
+    /* nothing really */
 }
 
 extern void  disable_tcp_nagle(int  fd);
@@ -138,7 +138,7 @@
 
 static __inline__ int  adb_open_mode(const char* path, int options, int mode)
 {
-	return adb_open(path, options);
+    return adb_open(path, options);
 }
 
 static __inline__ int  unix_open(const char*  path, int options,...)
@@ -169,7 +169,7 @@
 extern int socket_loopback_server(int port, int type);
 extern int socket_inaddr_any_server(int port, int type);
 
-/* normally provided by <cutils/fdevent.h> */
+/* normally provided by "fdevent.h" */
 
 #define FDE_READ              0x0001
 #define FDE_WRITE             0x0002
@@ -203,7 +203,7 @@
 
 static __inline__ void  adb_sleep_ms( int  mseconds )
 {
-	Sleep( mseconds );
+    Sleep( mseconds );
 }
 
 extern int  adb_socket_accept(int  serverfd, struct sockaddr*  addr, socklen_t  *addrlen);
@@ -252,7 +252,7 @@
 
 #else /* !_WIN32 a.k.a. Unix */
 
-#include <cutils/fdevent.h>
+#include "fdevent.h"
 #include <cutils/sockets.h>
 #include <cutils/properties.h>
 #include <cutils/misc.h>
@@ -290,7 +290,7 @@
 
 static __inline__ void  close_on_exec(int  fd)
 {
-	fcntl( fd, F_SETFD, FD_CLOEXEC );
+    fcntl( fd, F_SETFD, FD_CLOEXEC );
 }
 
 static __inline__ int  unix_open(const char*  path, int options,...)
@@ -312,7 +312,7 @@
 
 static __inline__ int  adb_open_mode( const char*  pathname, int  options, int  mode )
 {
-	return open( pathname, options, mode );
+    return open( pathname, options, mode );
 }
 
 
@@ -368,11 +368,11 @@
 {
     int  fd = creat(path, mode);
 
-	if ( fd < 0 )
-		return -1;
+    if ( fd < 0 )
+        return -1;
 
     close_on_exec(fd);
-	return fd;
+    return fd;
 }
 #undef   creat
 #define  creat  ___xxx_creat
@@ -439,12 +439,12 @@
 
 static __inline__ void  adb_sleep_ms( int  mseconds )
 {
-	usleep( mseconds*1000 );
+    usleep( mseconds*1000 );
 }
 
 static __inline__ int  adb_mkdir(const char*  path, int mode)
 {
-	return mkdir(path, mode);
+    return mkdir(path, mode);
 }
 #undef   mkdir
 #define  mkdir  ___xxx_mkdir
diff --git a/adb/sysdeps_win32.c b/adb/sysdeps_win32.c
index c2a9a98..a8e3bb9 100644
--- a/adb/sysdeps_win32.c
+++ b/adb/sysdeps_win32.c
@@ -739,12 +739,12 @@
 {
     FH   serverfh = _fh_from_int(serverfd);
     FH   fh;
-    
+
     if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
         D( "adb_socket_accept: invalid fd %d\n", serverfd );
         return -1;
     }
-    
+
     fh = _fh_alloc( &_fh_socket_class );
     if (!fh) {
         D( "adb_socket_accept: not enough memory to allocate accepted socket descriptor\n" );
@@ -757,7 +757,7 @@
         D( "adb_socket_accept: accept on fd %d return error %ld\n", serverfd, GetLastError() );
         return -1;
     }
-    
+
     snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", _fh_to_int(fh), serverfh->name );
     D( "adb_socket_accept on fd %d returns fd %d\n", serverfd, _fh_to_int(fh) );
     return  _fh_to_int(fh);
@@ -768,7 +768,7 @@
 {
     FH   fh = _fh_from_int(fd);
     int  on;
-    
+
     if ( !fh || fh->clazz != &_fh_socket_class )
         return;
 
@@ -1746,7 +1746,7 @@
 
 /**  FILE EVENT HOOKS
  **/
- 
+
 static void  _event_file_prepare( EventHook  hook )
 {
     if (hook->wanted & (FDE_READ|FDE_WRITE)) {
diff --git a/adb/usb_windows.c b/adb/usb_windows.c
index 7ddaa0c..0951f67 100644
--- a/adb/usb_windows.c
+++ b/adb/usb_windows.c
@@ -446,7 +446,7 @@
 }
 
 void find_devices() {
-	usb_handle* handle = NULL;
+        usb_handle* handle = NULL;
   char entry_buffer[2048];
   char interf_name[2048];
   AdbInterfaceInfo* next_interface = (AdbInterfaceInfo*)(&entry_buffer[0]);
diff --git a/fastboot/bootimg.c b/fastboot/bootimg.c
index 1d77b3c..e5aea4e 100644
--- a/fastboot/bootimg.c
+++ b/fastboot/bootimg.c
@@ -40,7 +40,7 @@
 boot_img_hdr *mkbootimg(void *kernel, unsigned kernel_size,
                         void *ramdisk, unsigned ramdisk_size,
                         void *second, unsigned second_size,
-                        unsigned page_size,
+                        unsigned page_size, unsigned base,
                         unsigned *bootimg_size)
 {
     unsigned kernel_actual;
@@ -65,15 +65,14 @@
 
     memcpy(hdr->magic, BOOT_MAGIC, BOOT_MAGIC_SIZE);
     
-    hdr->kernel_size = kernel_size;
-    hdr->kernel_addr = 0x10008000;
+    hdr->kernel_size =  kernel_size;
     hdr->ramdisk_size = ramdisk_size;
-    hdr->ramdisk_addr = 0x11000000;
-    hdr->second_size = second_size;
-    hdr->second_addr = 0x10F00000;
-    
-    hdr->tags_addr = 0x10000100;
-    hdr->page_size = page_size;
+    hdr->second_size =  second_size;
+    hdr->kernel_addr =  base + 0x00008000;
+    hdr->ramdisk_addr = base + 0x01000000;
+    hdr->second_addr =  base + 0x00F00000;
+    hdr->tags_addr =    base + 0x00000100;
+    hdr->page_size =    page_size;
 
     memcpy(hdr->magic + page_size, 
            kernel, kernel_size);
diff --git a/fastboot/fastboot.c b/fastboot/fastboot.c
index 498b4a6..850e10b 100644
--- a/fastboot/fastboot.c
+++ b/fastboot/fastboot.c
@@ -42,6 +42,14 @@
 
 #include "fastboot.h"
 
+void bootimg_set_cmdline(boot_img_hdr *h, const char *cmdline);
+
+boot_img_hdr *mkbootimg(void *kernel, unsigned kernel_size,
+                        void *ramdisk, unsigned ramdisk_size,
+                        void *second, unsigned second_size,
+                        unsigned page_size, unsigned base,
+                        unsigned *bootimg_size);
+
 static usb_handle *usb = 0;
 static const char *serial = 0;
 static const char *product = 0;
@@ -49,6 +57,8 @@
 static int wipe_data = 0;
 static unsigned short vendor_id = 0;
 
+static unsigned base_addr = 0x10000000;
+
 void die(const char *fmt, ...)
 {
     va_list ap;
@@ -212,6 +222,7 @@
             "  -p <product>                             specify product name\n"
             "  -c <cmdline>                             override kernel commandline\n"
             "  -i <vendor id>                           specify a custom USB vendor id\n"
+            "  -b <base_addr>                           specify a custom kernel base address\n"
         );
     exit(1);
 }
@@ -257,7 +268,7 @@
     }
 
     fprintf(stderr,"creating boot image...\n");
-    bdata = mkbootimg(kdata, ksize, rdata, rsize, 0, 0, 2048, &bsize);
+    bdata = mkbootimg(kdata, ksize, rdata, rsize, 0, 0, 2048, base_addr, &bsize);
     if(bdata == 0) {
         fprintf(stderr,"failed to create boot.img\n");
         return 0;
@@ -545,6 +556,10 @@
         if(!strcmp(*argv, "-w")) {
             wants_wipe = 1;
             skip(1);
+        } else if(!strcmp(*argv, "-b")) {
+            require(2);
+            base_addr = strtoul(argv[1], 0, 16);
+            skip(2);
         } else if(!strcmp(*argv, "-s")) {
             require(2);
             serial = argv[1];
diff --git a/include/android/log.h b/include/android/log.h
new file mode 100644
index 0000000..0ea4c29
--- /dev/null
+++ b/include/android/log.h
@@ -0,0 +1,128 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _ANDROID_LOG_H
+#define _ANDROID_LOG_H
+
+/******************************************************************
+ *
+ * IMPORTANT NOTICE:
+ *
+ *   This file is part of Android's set of stable system headers
+ *   exposed by the Android NDK (Native Development Kit) since
+ *   platform release 1.5
+ *
+ *   Third-party source AND binary code relies on the definitions
+ *   here to be FROZEN ON ALL UPCOMING PLATFORM RELEASES.
+ *
+ *   - DO NOT MODIFY ENUMS (EXCEPT IF YOU ADD NEW 32-BIT VALUES)
+ *   - DO NOT MODIFY CONSTANTS OR FUNCTIONAL MACROS
+ *   - DO NOT CHANGE THE SIGNATURE OF FUNCTIONS IN ANY WAY
+ *   - DO NOT CHANGE THE LAYOUT OR SIZE OF STRUCTURES
+ */
+
+/*
+ * Support routines to send messages to the Android in-kernel log buffer,
+ * which can later be accessed through the 'logcat' utility.
+ *
+ * Each log message must have
+ *   - a priority
+ *   - a log tag
+ *   - some text
+ *
+ * The tag normally corresponds to the component that emits the log message,
+ * and should be reasonably small.
+ *
+ * Log message text may be truncated to less than an implementation-specific
+ * limit (e.g. 1023 characters max).
+ *
+ * Note that a newline character ("\n") will be appended automatically to your
+ * log message, if not already there. It is not possible to send several messages
+ * and have them appear on a single line in logcat.
+ *
+ * PLEASE USE LOGS WITH MODERATION:
+ *
+ *  - Sending log messages eats CPU and slow down your application and the
+ *    system.
+ *
+ *  - The circular log buffer is pretty small (<64KB), sending many messages
+ *    might push off other important log messages from the rest of the system.
+ *
+ *  - In release builds, only send log messages to account for exceptional
+ *    conditions.
+ *
+ * NOTE: These functions MUST be implemented by /system/lib/liblog.so
+ */
+
+#include <stdarg.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Android log priority values, in ascending priority order.
+ */
+typedef enum android_LogPriority {
+    ANDROID_LOG_UNKNOWN = 0,
+    ANDROID_LOG_DEFAULT,    /* only for SetMinPriority() */
+    ANDROID_LOG_VERBOSE,
+    ANDROID_LOG_DEBUG,
+    ANDROID_LOG_INFO,
+    ANDROID_LOG_WARN,
+    ANDROID_LOG_ERROR,
+    ANDROID_LOG_FATAL,
+    ANDROID_LOG_SILENT,     /* only for SetMinPriority(); must be last */
+} android_LogPriority;
+
+/*
+ * Send a simple string to the log.
+ */
+int __android_log_write(int prio, const char *tag, const char *text);
+
+/*
+ * Send a formatted string to the log, used like printf(fmt,...)
+ */
+int __android_log_print(int prio, const char *tag,  const char *fmt, ...)
+#if defined(__GNUC__)
+    __attribute__ ((format(printf, 3, 4)))
+#endif
+    ;
+
+/*
+ * A variant of __android_log_print() that takes a va_list to list
+ * additional parameters.
+ */
+int __android_log_vprint(int prio, const char *tag,
+                         const char *fmt, va_list ap);
+
+/*
+ * Log an assertion failure and SIGTRAP the process to have a chance
+ * to inspect it, if a debugger is attached. This uses the FATAL priority.
+ */
+void __android_log_assert(const char *cond, const char *tag,
+			  const char *fmt, ...)    
+#if defined(__GNUC__)
+    __attribute__ ((noreturn))
+    __attribute__ ((format(printf, 3, 4)))
+#endif
+    ;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _ANDROID_LOG_H */
diff --git a/include/cutils/ashmem.h b/include/cutils/ashmem.h
index fd71352..0683bf2 100644
--- a/include/cutils/ashmem.h
+++ b/include/cutils/ashmem.h
@@ -18,6 +18,7 @@
 int ashmem_set_prot_region(int fd, int prot);
 int ashmem_pin_region(int fd, size_t offset, size_t len);
 int ashmem_unpin_region(int fd, size_t offset, size_t len);
+int ashmem_get_size_region(int fd);
 
 #ifdef __cplusplus
 }
diff --git a/include/cutils/logd.h b/include/cutils/logd.h
index a1cb012..8737639 100644
--- a/include/cutils/logd.h
+++ b/include/cutils/logd.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006 The Android Open Source Project
+ * Copyright (C) 2009 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -17,6 +17,12 @@
 #ifndef _ANDROID_CUTILS_LOGD_H
 #define _ANDROID_CUTILS_LOGD_H
 
+/* the stable/frozen log-related definitions have been
+ * moved to this header, which is exposed by the NDK
+ */
+#include <android/log.h>
+
+/* the rest is only used internally by the system */
 #include <time.h>
 #include <stdio.h>
 #include <unistd.h>
@@ -32,45 +38,10 @@
 extern "C" {
 #endif
 
-/*
- * Priority values, in ascending priority order.
- */
-typedef enum android_LogPriority {
-    ANDROID_LOG_UNKNOWN = 0,
-    ANDROID_LOG_DEFAULT,    /* only for SetMinPriority() */
-    ANDROID_LOG_VERBOSE,
-    ANDROID_LOG_DEBUG,
-    ANDROID_LOG_INFO,
-    ANDROID_LOG_WARN,
-    ANDROID_LOG_ERROR,
-    ANDROID_LOG_FATAL,
-    ANDROID_LOG_SILENT,     /* only for SetMinPriority(); must be last */
-} android_LogPriority;
-
-int __android_log_write(int prio, const char *tag, const char *text);
-
-int __android_log_vprint(int prio, const char *tag,
-			 const char *fmt, va_list ap);
-
 int __android_log_bwrite(int32_t tag, const void *payload, size_t len);
 int __android_log_btwrite(int32_t tag, char type, const void *payload,
     size_t len);
 
-int __android_log_print(int prio, const char *tag,  const char *fmt, ...)
-#if defined(__GNUC__)
-    __attribute__ ((format(printf, 3, 4)))
-#endif
-    ;
-
-
-void __android_log_assert(const char *cond, const char *tag,
-			  const char *fmt, ...)    
-#if defined(__GNUC__)
-    __attribute__ ((noreturn))
-    __attribute__ ((format(printf, 3, 4)))
-#endif
-    ;
-
 #ifdef __cplusplus
 }
 #endif
diff --git a/include/cutils/native_handle.h b/include/cutils/native_handle.h
index 2b64893..89d6b65 100644
--- a/include/cutils/native_handle.h
+++ b/include/cutils/native_handle.h
@@ -17,12 +17,57 @@
 #ifndef NATIVE_HANDLE_H_
 #define NATIVE_HANDLE_H_
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 typedef struct
 {
-    int version;        /* sizeof(native_handle) */
+    int version;        /* sizeof(native_handle_t) */
     int numFds;         /* number of file-descriptors at &data[0] */
     int numInts;        /* number of ints at &data[numFds] */
     int data[0];        /* numFds + numInts ints */
-} native_handle;
+} native_handle_t;
+
+
+/* keep the old definition for backward source-compatibility */
+typedef native_handle_t native_handle;
+
+/*
+ * native_handle_close
+ * 
+ * closes the file descriptors contained in this native_handle_t
+ * 
+ * return 0 on success, or a negative error code on failure
+ * 
+ */
+int native_handle_close(const native_handle_t* h);
+
+
+/*
+ * native_handle_create
+ * 
+ * creates a native_handle_t and initializes it. must be destroyed with
+ * native_handle_delete().
+ * 
+ */
+native_handle_t* native_handle_create(int numFds, int numInts);
+
+/*
+ * native_handle_delete
+ * 
+ * frees a native_handle_t allocated with native_handle_create().
+ * This ONLY frees the memory allocated for the native_handle_t, but doesn't
+ * close the file descriptors; which can be achieved with native_handle_close().
+ * 
+ * return 0 on success, or a negative error code on failure
+ * 
+ */
+int native_handle_delete(native_handle_t* h);
+
+
+#ifdef __cplusplus
+}
+#endif
 
 #endif /* NATIVE_HANDLE_H_ */
diff --git a/include/cutils/tztime.h b/include/cutils/tztime.h
index 9b3ece8..69dbc88 100644
--- a/include/cutils/tztime.h
+++ b/include/cutils/tztime.h
@@ -27,6 +27,7 @@
 struct strftime_locale {
     const char *mon[12];    /* short names */
     const char *month[12];  /* long names */
+    const char *standalone_month[12];  /* long standalone names */
     const char *wday[7];    /* short names */
     const char *weekday[7]; /* long names */
     const char *X_fmt;
diff --git a/include/private/android_filesystem_config.h b/include/private/android_filesystem_config.h
index c855187..a4351ac 100644
--- a/include/private/android_filesystem_config.h
+++ b/include/private/android_filesystem_config.h
@@ -48,6 +48,8 @@
 #define AID_INSTALL       1012  /* group for installing packages */
 #define AID_MEDIA         1013  /* mediaserver process */
 #define AID_DHCP          1014  /* dhcp client */
+#define AID_SDCARD_RW     1015  /* external storage write access */
+#define AID_VPN           1016  /* vpn system */
 
 #define AID_SHELL         2000  /* adb and debug shell user */
 #define AID_CACHE         2001  /* cache access */
@@ -93,6 +95,8 @@
     { "diag",      AID_DIAG, },
     { "net_bt_admin", AID_NET_BT_ADMIN, },
     { "net_bt",    AID_NET_BT, },
+    { "sdcard_rw", AID_SDCARD_RW, },
+    { "vpn",       AID_VPN, },
     { "inet",      AID_INET, }, 
     { "net_raw",   AID_NET_RAW, },
     { "misc",      AID_MISC, },
@@ -168,6 +172,7 @@
     { 06755, AID_ROOT,      AID_ROOT,      "system/xbin/librank" },
     { 06755, AID_ROOT,      AID_ROOT,      "system/xbin/procrank" },
     { 06755, AID_ROOT,      AID_ROOT,      "system/xbin/procmem" },
+    { 06755, AID_ROOT,      AID_ROOT,      "system/xbin/tcpdump" },
     { 00755, AID_ROOT,      AID_SHELL,     "system/bin/*" },
     { 00755, AID_ROOT,      AID_SHELL,     "system/xbin/*" },
     { 00750, AID_ROOT,      AID_SHELL,     "sbin/*" },
diff --git a/include/sysutils/FrameworkClient.h b/include/sysutils/FrameworkClient.h
new file mode 100644
index 0000000..0ef0753
--- /dev/null
+++ b/include/sysutils/FrameworkClient.h
@@ -0,0 +1,21 @@
+#ifndef _FRAMEWORK_CLIENT_H
+#define _FRAMEWORK_CLIENT_H
+
+#include "../../../frameworks/base/include/utils/List.h"
+
+#include <pthread.h>
+
+class FrameworkClient {
+    int             mSocket;
+    pthread_mutex_t mWriteMutex;
+
+public:
+    FrameworkClient(int sock);
+    virtual ~FrameworkClient() {}
+
+    int sendMsg(const char *msg);
+    int sendMsg(const char *msg, const char *data);
+};
+
+typedef android::List<FrameworkClient *> FrameworkClientCollection;
+#endif
diff --git a/include/sysutils/FrameworkCommand.h b/include/sysutils/FrameworkCommand.h
new file mode 100644
index 0000000..5b50247
--- /dev/null
+++ b/include/sysutils/FrameworkCommand.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef __FRAMEWORK_CMD_HANDLER_H
+#define __FRAMEWORK_CMD_HANDLER_H
+
+#include "../../../frameworks/base/include/utils/List.h"
+
+class SocketClient;
+
+class FrameworkCommand { 
+private:
+    const char *mCommand;
+
+public:
+
+    FrameworkCommand(const char *cmd);
+    virtual ~FrameworkCommand() { }
+
+    virtual int runCommand(SocketClient *c, char *data) = 0;
+
+    const char *getCommand() { return mCommand; }
+};
+
+typedef android::List<FrameworkCommand *> FrameworkCommandCollection;
+#endif
diff --git a/include/sysutils/FrameworkListener.h b/include/sysutils/FrameworkListener.h
new file mode 100644
index 0000000..8a83c33
--- /dev/null
+++ b/include/sysutils/FrameworkListener.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef _FRAMEWORKSOCKETLISTENER_H
+#define _FRAMEWORKSOCKETLISTENER_H
+
+#include "SocketListener.h"
+#include "FrameworkCommand.h"
+
+class SocketClient;
+
+class FrameworkListener : public SocketListener {
+private:
+    FrameworkCommandCollection *mCommands;
+
+public:
+    FrameworkListener(const char *socketName);
+    virtual ~FrameworkListener() {}
+
+protected:
+    void registerCmd(FrameworkCommand *cmd);
+    virtual bool onDataAvailable(SocketClient *c);
+
+private:
+    void dispatchCommand(SocketClient *c, char *cmd);
+};
+#endif
diff --git a/include/sysutils/NetlinkEvent.h b/include/sysutils/NetlinkEvent.h
new file mode 100644
index 0000000..95e83a3
--- /dev/null
+++ b/include/sysutils/NetlinkEvent.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef _NETLINKEVENT_H
+#define _NETLINKEVENT_H
+
+#define NL_PARAMS_MAX 32
+
+class NetlinkEvent {
+    int  mSeq;
+    char *mPath;
+    int  mAction;
+    char *mSubsystem;
+    char *mParams[NL_PARAMS_MAX];
+
+public:
+    const static int NlActionUnknown;
+    const static int NlActionAdd;
+    const static int NlActionRemove;
+    const static int NlActionChange;
+
+    NetlinkEvent();
+    virtual ~NetlinkEvent();
+
+    bool decode(char *buffer, int size);
+    const char *findParam(const char *paramName);
+
+    const char *getSubsystem() { return mSubsystem; }
+    int getAction() { return mAction; }
+};
+
+#endif
diff --git a/include/sysutils/NetlinkListener.h b/include/sysutils/NetlinkListener.h
new file mode 100644
index 0000000..6dcc005
--- /dev/null
+++ b/include/sysutils/NetlinkListener.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef _NETLINKLISTENER_H
+#define _NETLINKLISTENER_H
+
+#include "SocketListener.h"
+
+class NetlinkEvent;
+
+class NetlinkListener : public SocketListener {
+    char mBuffer[64 * 1024];
+
+public:
+    NetlinkListener(int socket);
+    virtual ~NetlinkListener() {}
+protected:
+    virtual bool onDataAvailable(SocketClient *cli);
+};
+#endif
diff --git a/include/sysutils/ServiceManager.h b/include/sysutils/ServiceManager.h
new file mode 100644
index 0000000..c31dd8f
--- /dev/null
+++ b/include/sysutils/ServiceManager.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _SERVICE_MANAGER_H
+#define _SERVICE_MANAGER_H
+
+class ServiceManager {
+public:
+    ServiceManager();
+    virtual ~ServiceManager() {}
+
+    int start(const char *name);
+    int stop(const char *name);
+    bool isRunning(const char *name);
+};
+
+#endif
diff --git a/include/sysutils/SocketClient.h b/include/sysutils/SocketClient.h
new file mode 100644
index 0000000..469dd9d
--- /dev/null
+++ b/include/sysutils/SocketClient.h
@@ -0,0 +1,23 @@
+#ifndef _SOCKET_CLIENT_H
+#define _SOCKET_CLIENT_H
+
+#include "../../../frameworks/base/include/utils/List.h"
+
+#include <pthread.h>
+
+class SocketClient {
+    int             mSocket;
+    pthread_mutex_t mWriteMutex;
+
+public:
+    SocketClient(int sock);
+    virtual ~SocketClient() {}
+
+    int getSocket() { return mSocket; }
+
+    int sendMsg(int code, const char *msg, bool addErrno);
+    int sendMsg(const char *msg);
+};
+
+typedef android::List<SocketClient *> SocketClientCollection;
+#endif
diff --git a/include/sysutils/SocketListener.h b/include/sysutils/SocketListener.h
new file mode 100644
index 0000000..68dcb8f
--- /dev/null
+++ b/include/sysutils/SocketListener.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef _SOCKETLISTENER_H
+#define _SOCKETLISTENER_H
+
+#include <pthread.h>
+
+#include <sysutils/SocketClient.h>
+
+class SocketListener {
+    int                     mSock;
+    const char              *mSocketName;
+    SocketClientCollection  *mClients;
+    pthread_mutex_t         mClientsLock;
+    bool                    mListen;
+    int                     mCtrlPipe[2];
+    pthread_t               mThread;
+
+public:
+    SocketListener(const char *socketNames, bool listen);
+    SocketListener(int socketFd, bool listen);
+
+    virtual ~SocketListener() {}
+    int startListener();
+    int stopListener();
+
+    void sendBroadcast(int code, const char *msg, bool addErrno);
+    void sendBroadcast(const char *msg);
+
+protected:
+    virtual bool onDataAvailable(SocketClient *c) = 0;
+
+private:
+    static void *threadStart(void *obj);
+    void runListener();
+};
+#endif
diff --git a/init/builtins.c b/init/builtins.c
index 95fb223..17df0af 100644
--- a/init/builtins.c
+++ b/init/builtins.c
@@ -126,7 +126,7 @@
 static void service_start_if_not_disabled(struct service *svc)
 {
     if (!(svc->flags & SVC_DISABLED)) {
-        service_start(svc);
+        service_start(svc, NULL);
     }
 }
 
@@ -316,7 +316,7 @@
     struct service *svc;
     svc = service_find_by_name(args[1]);
     if (svc) {
-        service_start(svc);
+        service_start(svc, NULL);
     }
     return 0;
 }
@@ -337,7 +337,7 @@
     svc = service_find_by_name(args[1]);
     if (svc) {
         service_stop(svc);
-        service_start(svc);
+        service_start(svc, NULL);
     }
     return 0;
 }
diff --git a/init/devices.c b/init/devices.c
index b1ef6ab..49335a5 100644
--- a/init/devices.c
+++ b/init/devices.c
@@ -115,6 +115,7 @@
     { "/dev/oncrpc/",       0660,   AID_ROOT,       AID_SYSTEM,     1 },
     { "/dev/adsp/",         0660,   AID_SYSTEM,     AID_AUDIO,      1 },
     { "/dev/mt9t013",       0660,   AID_SYSTEM,     AID_SYSTEM,     0 },
+    { "/dev/msm_camera/",   0660,   AID_SYSTEM,     AID_SYSTEM,     1 },
     { "/dev/akm8976_daemon",0640,   AID_COMPASS,    AID_SYSTEM,     0 },
     { "/dev/akm8976_aot",   0640,   AID_COMPASS,    AID_SYSTEM,     0 },
     { "/dev/akm8976_pffd",  0640,   AID_COMPASS,    AID_SYSTEM,     0 },
@@ -126,10 +127,12 @@
     { "/dev/msm_audpre",    0660,   AID_SYSTEM,     AID_AUDIO,      0 },
     { "/dev/htc-acoustic",  0660,   AID_SYSTEM,     AID_AUDIO,      0 },
     { "/dev/smd0",          0640,   AID_RADIO,      AID_RADIO,      0 },
+    { "/dev/qemu_trace",    0666,   AID_SYSTEM,     AID_SYSTEM,     0 },
     { "/dev/qmi",           0640,   AID_RADIO,      AID_RADIO,      0 },
     { "/dev/qmi0",          0640,   AID_RADIO,      AID_RADIO,      0 },
     { "/dev/qmi1",          0640,   AID_RADIO,      AID_RADIO,      0 },
     { "/dev/qmi2",          0640,   AID_RADIO,      AID_RADIO,      0 },
+    { "/dev/tun",           0640,   AID_VPN  ,      AID_VPN,        0 },
     { NULL, 0, 0, 0, 0 },
 };
 
@@ -380,7 +383,10 @@
         } else if (!strncmp(uevent->subsystem, "adsp", 4)) {
             base = "/dev/adsp/";
             mkdir(base, 0755);
-      } else if(!strncmp(uevent->subsystem, "input", 5)) {
+        } else if (!strncmp(uevent->subsystem, "msm_camera", 10)) {
+            base = "/dev/msm_camera/";
+            mkdir(base, 0755);
+        } else if(!strncmp(uevent->subsystem, "input", 5)) {
             base = "/dev/input/";
             mkdir(base, 0755);
         } else if(!strncmp(uevent->subsystem, "mtd", 3)) {
diff --git a/init/init.c b/init/init.c
index b8b4f40..0c1ad3f 100644
--- a/init/init.c
+++ b/init/init.c
@@ -156,7 +156,7 @@
     fcntl(fd, F_SETFD, 0);
 }
 
-void service_start(struct service *svc)
+void service_start(struct service *svc, const char *dynamic_args)
 {
     struct stat s;
     pid_t pid;
@@ -192,6 +192,13 @@
         return;
     }
 
+    if ((!(svc->flags & SVC_ONESHOT)) && dynamic_args) {
+        ERROR("service '%s' must be one-shot to use dynamic args, disabling\n",
+               svc->args[0]);
+        svc->flags |= SVC_DISABLED;
+        return;
+    }
+
     NOTICE("starting '%s'\n", svc->name);
 
     pid = fork();
@@ -248,7 +255,26 @@
             setuid(svc->uid);
         }
 
-        execve(svc->args[0], (char**) svc->args, (char**) ENV);
+        if (!dynamic_args)
+            execve(svc->args[0], (char**) svc->args, (char**) ENV);
+        else {
+            char *arg_ptrs[SVC_MAXARGS+1];
+            int arg_idx = svc->nargs;
+            char *tmp = strdup(dynamic_args);
+            char *next = tmp;
+            char *bword;
+
+            /* Copy the static arguments */
+            memcpy(arg_ptrs, svc->args, (svc->nargs * sizeof(char *)));
+
+            while((bword = strsep(&next, " "))) {
+                arg_ptrs[arg_idx++] = bword;
+                if (arg_idx == SVC_MAXARGS)
+                    break;
+            }
+            arg_ptrs[arg_idx] = '\0';
+            execve(svc->args[0], (char**) arg_ptrs, (char**) ENV);
+        }
         _exit(127);
     }
 
@@ -379,7 +405,7 @@
 
     if (next_start_time <= gettime()) {
         svc->flags &= (~SVC_RESTARTING);
-        service_start(svc);
+        service_start(svc, NULL);
         return;
     }
 
@@ -405,13 +431,28 @@
 
 static void msg_start(const char *name)
 {
-    struct service *svc = service_find_by_name(name);
+    struct service *svc;
+    char *tmp = NULL;
+    char *args = NULL;
+
+    if (!strchr(name, ':'))
+        svc = service_find_by_name(name);
+    else {
+        tmp = strdup(name);
+        args = strchr(tmp, ':');
+        *args = '\0';
+        args++;
+
+        svc = service_find_by_name(tmp);
+    }
     
     if (svc) {
-        service_start(svc);
+        service_start(svc, args);
     } else {
         ERROR("no such service '%s'\n", name);
     }
+    if (tmp)
+        free(tmp);
 }
 
 static void msg_stop(const char *name)
@@ -421,7 +462,7 @@
     if (svc) {
         service_stop(svc);
     } else {
-        ERROR("no such service '%s'\n");
+        ERROR("no such service '%s'\n", name);
     }
 }
 
@@ -737,7 +778,7 @@
     svc = service_find_by_keychord(id);
     if (svc) {
         INFO("starting service %s from keychord\n", svc->name);
-        service_start(svc);   
+        service_start(svc, NULL);
     } else {
         ERROR("service for keychord %d not found\n", id);
     }
diff --git a/init/init.h b/init/init.h
index b686869..f306b7b 100644
--- a/init/init.h
+++ b/init/init.h
@@ -29,7 +29,8 @@
 void log_init(void);
 void log_set_level(int level);
 void log_close(void);
-void log_write(int level, const char *fmt, ...);
+void log_write(int level, const char *fmt, ...)
+    __attribute__ ((format(printf, 2, 3)));
 
 #define ERROR(x...)   log_write(3, "<3>init: " x)
 #define NOTICE(x...)  log_write(5, "<5>init: " x)
@@ -115,6 +116,8 @@
 
 #define NR_SVC_SUPP_GIDS 6    /* six supplementary groups */
 
+#define SVC_MAXARGS 64
+
 struct service {
         /* list of all services */
     struct listnode slist;
@@ -136,15 +139,17 @@
     struct socketinfo *sockets;
     struct svcenvinfo *envvars;
 
-    int nargs;
-    char *args[1];
     struct action onrestart;  /* Actions to execute on restart. */
     
     /* keycodes for triggering this service via /dev/keychord */
     int *keycodes;
     int nkeycodes;
     int keychord_id;
-};
+
+    int nargs;
+    /* "MUST BE AT THE END OF THE STRUCT" */
+    char *args[1];
+}; /*     ^-------'args' MUST be at the end of this struct! */
 
 int parse_config_file(const char *fn);
 
@@ -157,7 +162,7 @@
 void service_for_each_flags(unsigned matchflags,
                             void (*func)(struct service *svc));
 void service_stop(struct service *svc);
-void service_start(struct service *svc);
+void service_start(struct service *svc, const char *dynamic_args);
 void property_changed(const char *name, const char *value);
 
 struct action *action_remove_queue_head(void);
diff --git a/init/parser.c b/init/parser.c
index 6a22d24..33c1a68 100644
--- a/init/parser.c
+++ b/init/parser.c
@@ -60,8 +60,6 @@
 #endif       
 }
 
-#define MAXARGS 64
-
 #define T_EOF 0
 #define T_TEXT 1
 #define T_NEWLINE 2
@@ -357,7 +355,7 @@
 static void parse_config(const char *fn, char *s)
 {
     struct parse_state state;
-    char *args[MAXARGS];
+    char *args[SVC_MAXARGS];
     int nargs;
 
     nargs = 0;
@@ -384,7 +382,7 @@
             }
             break;
         case T_TEXT:
-            if (nargs < MAXARGS) {
+            if (nargs < SVC_MAXARGS) {
                 args[nargs++] = state.text;
             }
             break;
@@ -536,7 +534,7 @@
             const char* name = act->name + strlen("property:");
             const char* equals = strchr(name, '=');
             if (equals) {
-                char* prop_name[PROP_NAME_MAX + 1];
+                char prop_name[PROP_NAME_MAX + 1];
                 const char* value;
                 int length = equals - name;
                 if (length > PROP_NAME_MAX) {
@@ -546,7 +544,7 @@
                     prop_name[length] = 0;
                     
                     /* does the property exist, and match the trigger value? */
-                    value = property_get((const char *)&prop_name[0]);
+                    value = property_get(prop_name);
                     if (value && !strcmp(equals + 1, value)) {
                         action_add_queue_tail(act);
                     }
diff --git a/init/property_service.c b/init/property_service.c
index 0bc6239..48ca3ea 100644
--- a/init/property_service.c
+++ b/init/property_service.c
@@ -296,7 +296,7 @@
         __futex_wake(&pa->serial, INT32_MAX);
     }
     /* If name starts with "net." treat as a DNS property. */
-    if (strncmp("net.", name, sizeof("net.") - 1) == 0)  {
+    if (strncmp("net.", name, strlen("net.")) == 0)  {
         if (strcmp("net.change", name) == 0) {
             return 0;
         }
@@ -307,7 +307,7 @@
         */
         property_set("net.change", name);
     } else if (persistent_properties_loaded &&
-            strncmp("persist.", name, sizeof("persist.") - 1) == 0) {
+            strncmp("persist.", name, strlen("persist.")) == 0) {
         /* 
          * Don't write properties to disk until after we have read all default properties
          * to prevent them from being overwritten by default values.
@@ -446,8 +446,7 @@
 
     if (dir) {
         while ((entry = readdir(dir)) != NULL) {
-            if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..") ||
-                    strncmp("persist.", entry->d_name, sizeof("persist.") - 1))
+            if (strncmp("persist.", entry->d_name, strlen("persist.")))
                 continue;
 #if HAVE_DIRENT_D_TYPE
             if (entry->d_type != DT_REG)
diff --git a/libcutils/Android.mk b/libcutils/Android.mk
index a43f7e3..18d0ee3 100644
--- a/libcutils/Android.mk
+++ b/libcutils/Android.mk
@@ -20,6 +20,7 @@
 	array.c \
 	hashmap.c \
 	atomic.c \
+        native_handle.c \
 	buffer.c \
 	socket_inaddr_any_server.c \
 	socket_local_client.c \
@@ -58,7 +59,6 @@
     commonSources += \
         mspace.c \
         selector.c \
-        fdevent.c \
         tztime.c \
         tzstrftime.c \
         adb_networking.c \
diff --git a/libcutils/ashmem-dev.c b/libcutils/ashmem-dev.c
index 5e158af..8b71f87 100644
--- a/libcutils/ashmem-dev.c
+++ b/libcutils/ashmem-dev.c
@@ -83,3 +83,8 @@
 	struct ashmem_pin pin = { offset, len };
 	return ioctl(fd, ASHMEM_UNPIN, &pin);
 }
+
+int ashmem_get_size_region(int fd)
+{
+  return ioctl(fd, ASHMEM_GET_SIZE, NULL);
+}
diff --git a/libcutils/ashmem-host.c b/libcutils/ashmem-host.c
index dbb52bc..f03e130 100644
--- a/libcutils/ashmem-host.c
+++ b/libcutils/ashmem-host.c
@@ -92,3 +92,23 @@
 {
 	return ASHMEM_IS_UNPINNED;
 }
+
+int ashmem_get_size_region(int fd)
+{
+        struct stat buf;
+        int result;
+
+        result = fstat(fd, &buf);
+        if (result == -1) {
+                return -1;
+        }
+
+        // Check if this is an "ashmem" region.
+        // TODO: This is very hacky, and can easily break. We need some reliable indicator.
+        if (!(buf.st_nlink == 0 && S_ISREG(buf.st_mode))) {
+                errno = ENOTTY;
+                return -1;
+        }
+
+        return (int)buf.st_size;  // TODO: care about overflow (> 2GB file)?
+}
diff --git a/libcutils/native_handle.c b/libcutils/native_handle.c
new file mode 100644
index 0000000..4089968
--- /dev/null
+++ b/libcutils/native_handle.c
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "NativeHandle"
+
+#include <stdint.h>
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include <cutils/log.h>
+#include <cutils/native_handle.h>
+
+native_handle_t* native_handle_create(int numFds, int numInts)
+{
+    native_handle_t* h = malloc(
+            sizeof(native_handle_t) + sizeof(int)*(numFds+numInts));
+
+    h->version = sizeof(native_handle_t);
+    h->numFds = numFds;
+    h->numInts = numInts;
+    return h;
+}
+
+int native_handle_delete(native_handle_t* h)
+{
+    if (h) {
+        if (h->version != sizeof(native_handle_t))
+            return -EINVAL;
+        free(h);
+    }
+    return 0;
+}
+
+int native_handle_close(const native_handle_t* h)
+{
+    if (h->version != sizeof(native_handle_t))
+        return -EINVAL;
+
+    const int numFds = h->numFds;
+    int i;
+    for (i=0 ; i<numFds ; i++) {
+        close(h->data[i]);
+    }
+    return 0;
+}
diff --git a/libcutils/tzstrftime.c b/libcutils/tzstrftime.c
index 29c5015..e37d79a 100644
--- a/libcutils/tzstrftime.c
+++ b/libcutils/tzstrftime.c
@@ -172,10 +172,17 @@
 					pt, ptlim, modifier);
 				continue;
 			case 'B':
-				pt = _add((t->tm_mon < 0 ||
-					t->tm_mon >= MONSPERYEAR) ?
-					"?" : Locale->month[t->tm_mon],
-					pt, ptlim, modifier);
+				if (modifier == '-') {
+					pt = _add((t->tm_mon < 0 ||
+						t->tm_mon >= MONSPERYEAR) ?
+						"?" : Locale->standalone_month[t->tm_mon],
+						pt, ptlim, modifier);
+				} else {
+					pt = _add((t->tm_mon < 0 ||
+						t->tm_mon >= MONSPERYEAR) ?
+						"?" : Locale->month[t->tm_mon],
+						pt, ptlim, modifier);
+				}
 				continue;
 			case 'b':
 			case 'h':
diff --git a/liblog/logd_write.c b/liblog/logd_write.c
index 80867d1..96da38b 100644
--- a/liblog/logd_write.c
+++ b/liblog/logd_write.c
@@ -143,12 +143,16 @@
     /* XXX: This needs to go! */
     if (!strcmp(tag, "HTC_RIL") ||
         !strcmp(tag, "RILJ") ||
+        !strcmp(tag, "RILB") ||
         !strcmp(tag, "RILC") ||
         !strcmp(tag, "RILD") ||
         !strcmp(tag, "RIL") ||
         !strcmp(tag, "AT") ||
         !strcmp(tag, "GSM") ||
-        !strcmp(tag, "STK"))
+        !strcmp(tag, "STK") ||
+        !strcmp(tag, "CDMA") ||
+        !strcmp(tag, "PHONE") ||
+        !strcmp(tag, "SMS"))
             log_id = LOG_ID_RADIO;
 
     vec[0].iov_base   = (unsigned char *) &prio;
diff --git a/libpixelflinger/codeflinger/ARMAssembler.h b/libpixelflinger/codeflinger/ARMAssembler.h
index 8837e07..ef3b66a 100644
--- a/libpixelflinger/codeflinger/ARMAssembler.h
+++ b/libpixelflinger/codeflinger/ARMAssembler.h
@@ -21,8 +21,9 @@
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <utils/Vector.h>
-#include <utils/KeyedVector.h>
+#include "tinyutils/Vector.h"
+#include "tinyutils/KeyedVector.h"
+#include "tinyutils/smartpointer.h"
 
 #include "tinyutils/smartpointer.h"
 #include "codeflinger/ARMAssemblerInterface.h"
diff --git a/libpixelflinger/codeflinger/CodeCache.h b/libpixelflinger/codeflinger/CodeCache.h
index 370ce17..8ff1366 100644
--- a/libpixelflinger/codeflinger/CodeCache.h
+++ b/libpixelflinger/codeflinger/CodeCache.h
@@ -23,8 +23,7 @@
 #include <pthread.h>
 #include <sys/types.h>
 
-#include <utils/KeyedVector.h>
-
+#include "tinyutils/KeyedVector.h"
 #include "tinyutils/smartpointer.h"
 
 namespace android {
diff --git a/libpixelflinger/tinyutils/Errors.h b/libpixelflinger/tinyutils/Errors.h
new file mode 100644
index 0000000..b9fd5f4
--- /dev/null
+++ b/libpixelflinger/tinyutils/Errors.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_ERRORS_H
+#define ANDROID_ERRORS_H
+
+#include <sys/types.h>
+#include <errno.h>
+
+namespace android {
+
+// use this type to return error codes
+typedef int32_t     status_t;
+
+/*
+ * Error codes. 
+ * All error codes are negative values.
+ */
+
+enum {
+    OK                = 0,    // Everything's swell.
+    NO_ERROR          = 0,    // No errors.
+    
+    UNKNOWN_ERROR       = 0x80000000,
+
+    NO_MEMORY           = -ENOMEM,
+    INVALID_OPERATION   = -ENOSYS,
+    BAD_VALUE           = -EINVAL,
+    BAD_TYPE            = 0x80000001,
+    NAME_NOT_FOUND      = -ENOENT,
+    PERMISSION_DENIED   = -EPERM,
+    NO_INIT             = -ENODEV,
+    ALREADY_EXISTS      = -EEXIST,
+    DEAD_OBJECT         = -EPIPE,
+    FAILED_TRANSACTION  = 0x80000002,
+    JPARKS_BROKE_IT     = -EPIPE,
+    BAD_INDEX           = -EOVERFLOW,
+    NOT_ENOUGH_DATA     = -ENODATA,
+    WOULD_BLOCK         = -EWOULDBLOCK, 
+    TIMED_OUT           = -ETIME,
+    UNKNOWN_TRANSACTION = -EBADMSG,
+};
+
+
+}; // namespace android
+    
+// ---------------------------------------------------------------------------
+    
+#endif // ANDROID_ERRORS_H
diff --git a/libpixelflinger/tinyutils/SortedVector.h b/libpixelflinger/tinyutils/SortedVector.h
new file mode 100644
index 0000000..7a6b443
--- /dev/null
+++ b/libpixelflinger/tinyutils/SortedVector.h
@@ -0,0 +1,282 @@
+/*
+ * Copyright (C) 2005 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_SORTED_VECTOR_H
+#define ANDROID_SORTED_VECTOR_H
+
+#include <assert.h>
+#include <stdint.h>
+#include <sys/types.h>
+
+#include "tinyutils/Vector.h"
+#include "tinyutils/VectorImpl.h"
+#include "tinyutils/TypeHelpers.h"
+
+// ---------------------------------------------------------------------------
+
+namespace android {
+
+template <class TYPE>
+class SortedVector : private SortedVectorImpl
+{
+public:
+            typedef TYPE    value_type;
+    
+    /*! 
+     * Constructors and destructors
+     */
+    
+                            SortedVector();
+                            SortedVector(const SortedVector<TYPE>& rhs);
+    virtual                 ~SortedVector();
+
+    /*! copy operator */
+    const SortedVector<TYPE>&   operator = (const SortedVector<TYPE>& rhs) const;    
+    SortedVector<TYPE>&         operator = (const SortedVector<TYPE>& rhs);    
+
+    /*
+     * empty the vector
+     */
+
+    inline  void            clear()             { VectorImpl::clear(); }
+
+    /*! 
+     * vector stats
+     */
+
+    //! returns number of items in the vector
+    inline  size_t          size() const                { return VectorImpl::size(); }
+    //! returns wether or not the vector is empty
+    inline  bool            isEmpty() const             { return VectorImpl::isEmpty(); }
+    //! returns how many items can be stored without reallocating the backing store
+    inline  size_t          capacity() const            { return VectorImpl::capacity(); }
+    //! setst the capacity. capacity can never be reduced less than size()
+    inline  ssize_t         setCapacity(size_t size)    { return VectorImpl::setCapacity(size); }
+
+    /*! 
+     * C-style array access
+     */
+     
+    //! read-only C-style access 
+    inline  const TYPE*     array() const;
+
+    //! read-write C-style access. BE VERY CAREFUL when modifying the array
+    //! you ust keep it sorted! You usually don't use this function.
+            TYPE*           editArray();
+
+            //! finds the index of an item
+            ssize_t         indexOf(const TYPE& item) const;
+            
+            //! finds where this item should be inserted
+            size_t          orderOf(const TYPE& item) const;
+            
+    
+    /*! 
+     * accessors
+     */
+
+    //! read-only access to an item at a given index
+    inline  const TYPE&     operator [] (size_t index) const;
+    //! alternate name for operator []
+    inline  const TYPE&     itemAt(size_t index) const;
+    //! stack-usage of the vector. returns the top of the stack (last element)
+            const TYPE&     top() const;
+    //! same as operator [], but allows to access the vector backward (from the end) with a negative index
+            const TYPE&     mirrorItemAt(ssize_t index) const;
+
+    /*!
+     * modifing the array
+     */
+
+            //! add an item in the right place (and replace the one that is there)
+            ssize_t         add(const TYPE& item);
+            
+            //! editItemAt() MUST NOT change the order of this item
+            TYPE&           editItemAt(size_t index) {
+                return *( static_cast<TYPE *>(VectorImpl::editItemLocation(index)) );
+            }
+
+            //! merges a vector into this one
+            ssize_t         merge(const Vector<TYPE>& vector);
+            ssize_t         merge(const SortedVector<TYPE>& vector);
+            
+            //! removes an item
+            ssize_t         remove(const TYPE&);
+
+    //! remove several items
+    inline  ssize_t         removeItemsAt(size_t index, size_t count = 1);
+    //! remove one item
+    inline  ssize_t         removeAt(size_t index)  { return removeItemsAt(index); }
+            
+protected:
+    virtual void    do_construct(void* storage, size_t num) const;
+    virtual void    do_destroy(void* storage, size_t num) const;
+    virtual void    do_copy(void* dest, const void* from, size_t num) const;
+    virtual void    do_splat(void* dest, const void* item, size_t num) const;
+    virtual void    do_move_forward(void* dest, const void* from, size_t num) const;
+    virtual void    do_move_backward(void* dest, const void* from, size_t num) const;
+    virtual int     do_compare(const void* lhs, const void* rhs) const;
+};
+
+
+// ---------------------------------------------------------------------------
+// No user serviceable parts from here...
+// ---------------------------------------------------------------------------
+
+template<class TYPE> inline
+SortedVector<TYPE>::SortedVector()
+    : SortedVectorImpl(sizeof(TYPE),
+                ((traits<TYPE>::has_trivial_ctor   ? HAS_TRIVIAL_CTOR   : 0)
+                |(traits<TYPE>::has_trivial_dtor   ? HAS_TRIVIAL_DTOR   : 0)
+                |(traits<TYPE>::has_trivial_copy   ? HAS_TRIVIAL_COPY   : 0)
+                |(traits<TYPE>::has_trivial_assign ? HAS_TRIVIAL_ASSIGN : 0))
+                )
+{
+}
+
+template<class TYPE> inline
+SortedVector<TYPE>::SortedVector(const SortedVector<TYPE>& rhs)
+    : SortedVectorImpl(rhs) {
+}
+
+template<class TYPE> inline
+SortedVector<TYPE>::~SortedVector() {
+    finish_vector();
+}
+
+template<class TYPE> inline
+SortedVector<TYPE>& SortedVector<TYPE>::operator = (const SortedVector<TYPE>& rhs) {
+    SortedVectorImpl::operator = (rhs);
+    return *this; 
+}
+
+template<class TYPE> inline
+const SortedVector<TYPE>& SortedVector<TYPE>::operator = (const SortedVector<TYPE>& rhs) const {
+    SortedVectorImpl::operator = (rhs);
+    return *this; 
+}
+
+template<class TYPE> inline
+const TYPE* SortedVector<TYPE>::array() const {
+    return static_cast<const TYPE *>(arrayImpl());
+}
+
+template<class TYPE> inline
+TYPE* SortedVector<TYPE>::editArray() {
+    return static_cast<TYPE *>(editArrayImpl());
+}
+
+
+template<class TYPE> inline
+const TYPE& SortedVector<TYPE>::operator[](size_t index) const {
+    assert( index<size() );
+    return *(array() + index);
+}
+
+template<class TYPE> inline
+const TYPE& SortedVector<TYPE>::itemAt(size_t index) const {
+    return operator[](index);
+}
+
+template<class TYPE> inline
+const TYPE& SortedVector<TYPE>::mirrorItemAt(ssize_t index) const {
+    assert( (index>0 ? index : -index)<size() );
+    return *(array() + ((index<0) ? (size()-index) : index));
+}
+
+template<class TYPE> inline
+const TYPE& SortedVector<TYPE>::top() const {
+    return *(array() + size() - 1);
+}
+
+template<class TYPE> inline
+ssize_t SortedVector<TYPE>::add(const TYPE& item) {
+    return SortedVectorImpl::add(&item);
+}
+
+template<class TYPE> inline
+ssize_t SortedVector<TYPE>::indexOf(const TYPE& item) const {
+    return SortedVectorImpl::indexOf(&item);
+}
+
+template<class TYPE> inline
+size_t SortedVector<TYPE>::orderOf(const TYPE& item) const {
+    return SortedVectorImpl::orderOf(&item);
+}
+
+template<class TYPE> inline
+ssize_t SortedVector<TYPE>::merge(const Vector<TYPE>& vector) {
+    return SortedVectorImpl::merge(reinterpret_cast<const VectorImpl&>(vector));
+}
+
+template<class TYPE> inline
+ssize_t SortedVector<TYPE>::merge(const SortedVector<TYPE>& vector) {
+    return SortedVectorImpl::merge(reinterpret_cast<const SortedVectorImpl&>(vector));
+}
+
+template<class TYPE> inline
+ssize_t SortedVector<TYPE>::remove(const TYPE& item) {
+    return SortedVectorImpl::remove(&item);
+}
+
+template<class TYPE> inline
+ssize_t SortedVector<TYPE>::removeItemsAt(size_t index, size_t count) {
+    return VectorImpl::removeItemsAt(index, count);
+}
+
+// ---------------------------------------------------------------------------
+
+template<class TYPE>
+void SortedVector<TYPE>::do_construct(void* storage, size_t num) const {
+    construct_type( reinterpret_cast<TYPE*>(storage), num );
+}
+
+template<class TYPE>
+void SortedVector<TYPE>::do_destroy(void* storage, size_t num) const {
+    destroy_type( reinterpret_cast<TYPE*>(storage), num );
+}
+
+template<class TYPE>
+void SortedVector<TYPE>::do_copy(void* dest, const void* from, size_t num) const {
+    copy_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(from), num );
+}
+
+template<class TYPE>
+void SortedVector<TYPE>::do_splat(void* dest, const void* item, size_t num) const {
+    splat_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(item), num );
+}
+
+template<class TYPE>
+void SortedVector<TYPE>::do_move_forward(void* dest, const void* from, size_t num) const {
+    move_forward_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(from), num );
+}
+
+template<class TYPE>
+void SortedVector<TYPE>::do_move_backward(void* dest, const void* from, size_t num) const {
+    move_backward_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(from), num );
+}
+
+template<class TYPE>
+int SortedVector<TYPE>::do_compare(const void* lhs, const void* rhs) const {
+    return compare_type( *reinterpret_cast<const TYPE*>(lhs), *reinterpret_cast<const TYPE*>(rhs) );
+}
+
+}; // namespace android
+
+
+// ---------------------------------------------------------------------------
+
+#endif // ANDROID_SORTED_VECTOR_H
diff --git a/libpixelflinger/tinyutils/Vector.h b/libpixelflinger/tinyutils/Vector.h
index 182bc7b..14cf99a 100644
--- a/libpixelflinger/tinyutils/Vector.h
+++ b/libpixelflinger/tinyutils/Vector.h
@@ -15,6 +15,7 @@
 
 #include <cutils/log.h>
 
+#include "tinyutils/Errors.h"
 #include "tinyutils/VectorImpl.h"
 #include "tinyutils/TypeHelpers.h"
 
@@ -302,16 +303,6 @@
     return VectorImpl::removeItemsAt(index, count);
 }
 
-template<class TYPE> inline
-status_t Vector<TYPE>::sort(Vector<TYPE>::compar_t cmp) {
-    return VectorImpl::sort((VectorImpl::compar_t)cmp);
-}
-
-template<class TYPE> inline
-status_t Vector<TYPE>::sort(Vector<TYPE>::compar_r_t cmp, void* state) {
-    return VectorImpl::sort((VectorImpl::compar_r_t)cmp, state);
-}
-
 // ---------------------------------------------------------------------------
 
 template<class TYPE>
diff --git a/libsysutils/Android.mk b/libsysutils/Android.mk
new file mode 100644
index 0000000..dd2b32d
--- /dev/null
+++ b/libsysutils/Android.mk
@@ -0,0 +1,35 @@
+BUILD_LIBSYSUTILS := false
+ifneq ($(TARGET_SIMULATOR),true)
+    BUILD_LIBSYSUTILS := true
+endif
+
+ifeq ($(BUILD_LIBSYSUTILS),true)
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:=                             \
+                  src/SocketListener.cpp      \
+                  src/FrameworkListener.cpp   \
+                  src/NetlinkListener.cpp     \
+                  src/NetlinkEvent.cpp        \
+                  src/FrameworkCommand.cpp    \
+                  src/SocketClient.cpp        \
+                  src/ServiceManager.cpp      \
+
+LOCAL_MODULE:= libsysutils
+
+LOCAL_C_INCLUDES := $(KERNEL_HEADERS) 
+
+LOCAL_CFLAGS := 
+
+LOCAL_SHARED_LIBRARIES := libcutils
+
+ifeq ($(TARGET_SIMULATOR),true)
+  LOCAL_LDLIBS += -lpthread
+endif
+
+include $(BUILD_SHARED_LIBRARY)
+
+endif
diff --git a/libsysutils/src/FrameworkClient.cpp b/libsysutils/src/FrameworkClient.cpp
new file mode 100644
index 0000000..1686996
--- /dev/null
+++ b/libsysutils/src/FrameworkClient.cpp
@@ -0,0 +1,40 @@
+#include <alloca.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <pthread.h>
+
+#define LOG_TAG "FrameworkClient"
+#include <cutils/log.h>
+
+#include <sysutils/FrameworkClient.h>
+
+FrameworkClient::FrameworkClient(int socket) {
+    mSocket = socket;
+    pthread_mutex_init(&mWriteMutex, NULL);
+}
+
+int FrameworkClient::sendMsg(const char *msg) {
+    if (mSocket < 0) {
+        errno = EHOSTUNREACH;
+        return -1;
+    }
+
+    pthread_mutex_lock(&mWriteMutex);
+    if (write(mSocket, msg, strlen(msg) +1) < 0) {
+        LOGW("Unable to send msg '%s' (%s)", msg, strerror(errno));
+    }
+    pthread_mutex_unlock(&mWriteMutex);
+    return 0;
+}
+
+int FrameworkClient::sendMsg(const char *msg, const char *data) {
+    char *buffer = (char *) alloca(strlen(msg) + strlen(data) + 1);
+    if (!buffer) {
+        errno = -ENOMEM;
+        return -1;
+    }
+    strcpy(buffer, msg);
+    strcat(buffer, data);
+    return sendMsg(buffer);
+}
+
diff --git a/libsysutils/src/FrameworkCommand.cpp b/libsysutils/src/FrameworkCommand.cpp
new file mode 100644
index 0000000..94e7426
--- /dev/null
+++ b/libsysutils/src/FrameworkCommand.cpp
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <errno.h>
+
+#define LOG_TAG "FrameworkCommand"
+
+#include <cutils/log.h>
+
+#include <sysutils/FrameworkCommand.h>
+
+FrameworkCommand::FrameworkCommand(const char *cmd) {
+    mCommand = cmd;
+}
+
+int FrameworkCommand::runCommand(SocketClient *c, char *data) {
+    LOGW("Command %s has no run handler!", getCommand());
+    errno = ENOSYS;
+    return -1;
+}
diff --git a/libsysutils/src/FrameworkListener.cpp b/libsysutils/src/FrameworkListener.cpp
new file mode 100644
index 0000000..e8ae847
--- /dev/null
+++ b/libsysutils/src/FrameworkListener.cpp
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <errno.h>
+#include <string.h>
+
+#define LOG_TAG "FrameworkListener"
+
+#include <cutils/log.h>
+
+#include <sysutils/FrameworkListener.h>
+#include <sysutils/FrameworkCommand.h>
+#include <sysutils/SocketClient.h>
+
+FrameworkListener::FrameworkListener(const char *socketName) :
+                            SocketListener(socketName, true) {
+    mCommands = new FrameworkCommandCollection();
+}
+
+bool FrameworkListener::onDataAvailable(SocketClient *c) {
+    char buffer[255];
+    int len;
+
+    if ((len = read(c->getSocket(), buffer, sizeof(buffer) -1)) < 0) {
+        LOGE("read() failed (%s)", strerror(errno));
+        return errno;
+    } else if (!len) {
+        LOGW("Lost connection to client");
+        return false;
+    }
+
+    int offset = 0;
+    int i;
+
+    for (i = 0; i < len; i++) {
+        if (buffer[i] == '\n') {
+            buffer[i] = '\0';
+            dispatchCommand(c, buffer + offset);
+            offset = i + 1;
+        }
+    }
+    return true;
+}
+
+void FrameworkListener::registerCmd(FrameworkCommand *cmd) {
+    mCommands->push_back(cmd);
+}
+
+void FrameworkListener::dispatchCommand(SocketClient *cli, char *cmd) {
+    char *next = cmd;
+    char *cm;
+    char *arg;
+
+    if (!(cm = strsep(&next, ":"))) {
+        cli->sendMsg(500, "Malformatted message", false);
+        return;
+    }
+
+    FrameworkCommandCollection::iterator i;
+
+    for (i = mCommands->begin(); i != mCommands->end(); ++i) {
+        FrameworkCommand *c = *i;
+
+        if (!strcmp(cm, c->getCommand())) {
+            if (c->runCommand(cli, next)) {
+                LOGW("Handler '%s' error (%s)", c->getCommand(), strerror(errno));
+            }
+            return;
+        }
+    }
+
+    cli->sendMsg(500, "Command not recognized", false);
+    return;
+}
diff --git a/libsysutils/src/NetlinkEvent.cpp b/libsysutils/src/NetlinkEvent.cpp
new file mode 100644
index 0000000..5573c3f
--- /dev/null
+++ b/libsysutils/src/NetlinkEvent.cpp
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <stdlib.h>
+#include <string.h>
+
+#define LOG_TAG "NetlinkEvent"
+#include <cutils/log.h>
+
+#include <sysutils/NetlinkEvent.h>
+
+const int NetlinkEvent::NlActionUnknown = 0;
+const int NetlinkEvent::NlActionAdd = 1;
+const int NetlinkEvent::NlActionRemove = 2;
+const int NetlinkEvent::NlActionChange = 3;
+
+NetlinkEvent::NetlinkEvent() {
+    mAction = NlActionUnknown;
+}
+
+NetlinkEvent::~NetlinkEvent() {
+    int i;
+    if (mPath)
+        free(mPath);
+    if (mSubsystem)
+        free(mSubsystem);
+    for (i = 0; i < NL_PARAMS_MAX; i++) {
+        if (!mParams[i])
+            break;
+        free(mParams[i]);
+    }
+}
+
+bool NetlinkEvent::decode(char *buffer, int size) {
+    char *s = buffer;
+    char *end;
+    int param_idx = 0;
+    int i;
+    int first = 1;
+
+    end = s + size;
+    while (s < end) {
+        if (first) {
+            char *p;
+            for (p = s; *p != '@'; p++);
+            p++;
+            mPath = strdup(p);
+            first = 0;
+        } else {
+            if (!strncmp(s, "ACTION=", strlen("ACTION="))) {
+                char *a = s + strlen("ACTION=");
+                if (!strcmp(a, "add"))
+                    mAction = NlActionAdd;
+                else if (!strcmp(a, "remove"))
+                    mAction = NlActionRemove;
+                else if (!strcmp(a, "change"))
+                    mAction = NlActionChange;
+            } else if (!strncmp(s, "SEQNUM=", strlen("SEQNUM=")))
+                mSeq = atoi(s + strlen("SEQNUM="));
+            else if (!strncmp(s, "SUBSYSTEM=", strlen("SUBSYSTEM=")))
+                mSubsystem = strdup(s + strlen("SUBSYSTEM="));
+            else
+                mParams[param_idx++] = strdup(s);
+        }
+        s+= strlen(s) + 1;
+    }
+    return true;
+}
+
+const char *NetlinkEvent::findParam(const char *paramName) {
+    int i;
+
+    for (i = 0; i < NL_PARAMS_MAX; i++) {
+        if (!mParams[i])
+            break;
+        if (!strncmp(mParams[i], paramName, strlen(paramName)))
+            return &mParams[i][strlen(paramName) + 1];
+    }
+
+    LOGE("NetlinkEvent::FindParam(): Parameter '%s' not found", paramName);
+    return NULL;
+}
diff --git a/libsysutils/src/NetlinkListener.cpp b/libsysutils/src/NetlinkListener.cpp
new file mode 100644
index 0000000..3ec9d9d
--- /dev/null
+++ b/libsysutils/src/NetlinkListener.cpp
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <errno.h>
+
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <string.h>
+
+#define LOG_TAG "NetlinkListener"
+#include <cutils/log.h>
+
+#include <sysutils/NetlinkListener.h>
+#include <sysutils/NetlinkEvent.h>
+
+NetlinkListener::NetlinkListener(int socket) :
+                            SocketListener(socket, false) {
+}
+
+bool NetlinkListener::onDataAvailable(SocketClient *cli)
+{
+    int socket = cli->getSocket();
+    LOGD("NetlinkListener::onDataAvailable()");
+
+    int count;
+
+    if ((count = recv(socket, mBuffer, sizeof(mBuffer), 0)) < 0) {
+        LOGE("recv failed (%s)", strerror(errno));
+        return false;
+    }
+
+    NetlinkEvent *evt = new NetlinkEvent();
+    if (!evt->decode(mBuffer, count)) {
+        LOGE("Error decoding NetlinkEvent");
+        goto out;
+    }
+
+    LOGD("Ignoring '%s' netlink event", evt->getSubsystem());
+
+out:
+    delete evt;
+    return true;
+}
diff --git a/libsysutils/src/ServiceManager.cpp b/libsysutils/src/ServiceManager.cpp
new file mode 100644
index 0000000..700ac91
--- /dev/null
+++ b/libsysutils/src/ServiceManager.cpp
@@ -0,0 +1,73 @@
+#include <errno.h>
+
+#include <sysutils/ServiceManager.h>
+
+#define LOG_TAG "Service"
+#include <cutils/log.h>
+#include <cutils/properties.h>
+
+ServiceManager::ServiceManager() {
+}
+
+int ServiceManager::start(const char *name) {
+    if (isRunning(name)) {
+        LOGW("Service '%s' is already running", name);
+        return 0;
+    }
+
+    LOGD("Starting service '%s'", name);
+    property_set("ctl.start", name);
+
+    int count = 200;
+    while(count--) {
+        sched_yield();
+        if (isRunning(name))
+            break;
+    }
+    if (!count) {
+        LOGW("Timed out waiting for service '%s' to start", name);
+        errno = ETIMEDOUT;
+        return -1;
+    }
+    LOGD("Sucessfully started '%s'", name);
+    return 0;
+}
+
+int ServiceManager::stop(const char *name) {
+    if (!isRunning(name)) {
+        LOGW("Service '%s' is already stopped", name);
+        return 0;
+    }
+
+    LOGD("Stopping service '%s'", name);
+    property_set("ctl.stop", name);
+
+    int count = 200;
+    while(count--) {
+        sched_yield();
+        if (!isRunning(name))
+            break;
+    }
+
+    if (!count) {
+        LOGW("Timed out waiting for service '%s' to stop", name);
+        errno = ETIMEDOUT;
+        return -1;
+    }
+    LOGD("Sucessfully stopped '%s'", name);
+    return 0;
+}
+
+bool ServiceManager::isRunning(const char *name) {
+    char propVal[PROPERTY_VALUE_MAX];
+    char propName[255];
+
+    snprintf(propName, sizeof(propVal), "init.svc.%s", name);
+
+
+    if (property_get(propName, propVal, NULL)) {
+        if (!strcmp(propVal, "running"))
+            return true;
+    }
+    return false;
+}
diff --git a/libsysutils/src/SocketClient.cpp b/libsysutils/src/SocketClient.cpp
new file mode 100644
index 0000000..f0e846f
--- /dev/null
+++ b/libsysutils/src/SocketClient.cpp
@@ -0,0 +1,67 @@
+#include <alloca.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <pthread.h>
+#include <string.h>
+
+#define LOG_TAG "SocketClient"
+#include <cutils/log.h>
+
+#include <sysutils/SocketClient.h>
+
+SocketClient::SocketClient(int socket) {
+    mSocket = socket;
+    pthread_mutex_init(&mWriteMutex, NULL);
+}
+
+int SocketClient::sendMsg(int code, const char *msg, bool addErrno) {
+    char *buf;
+
+    if (addErrno) {
+        buf = (char *) alloca(strlen(msg) + strlen(strerror(errno)) + 8);
+        sprintf(buf, "%.3d %s (%s)", code, msg, strerror(errno));
+    } else {
+        buf = (char *) alloca(strlen(msg) + strlen("XXX "));
+        sprintf(buf, "%.3d %s", code, msg);
+    }
+    return sendMsg(buf);
+}
+
+int SocketClient::sendMsg(const char *msg) {
+    if (mSocket < 0) {
+        errno = EHOSTUNREACH;
+        return -1;
+    }
+
+    char *tmp;
+    const char *bp = msg;
+
+    if (msg[strlen(msg)] != '\n') {
+        tmp = (char *) alloca(strlen(msg) + 1);
+        strcpy(tmp, msg);
+        strcat(tmp, "\n");
+        bp = tmp;
+    }
+
+    int rc = 0;
+    const char *p = bp;
+    int brtw = strlen(bp);
+
+    pthread_mutex_lock(&mWriteMutex);
+    while(brtw) {
+        if ((rc = write(mSocket,p, brtw)) < 0) {
+            LOGW("Unable to send msg '%s' (%s)", msg, strerror(errno));
+            pthread_mutex_unlock(&mWriteMutex);
+            return -1;
+        } else if (!rc) {
+            LOGW("0 length write :(");
+            errno = EIO;
+            pthread_mutex_unlock(&mWriteMutex);
+            return -1;
+        }
+        p += rc;
+        brtw -= rc;
+    }
+    pthread_mutex_unlock(&mWriteMutex);
+    return 0;
+}
diff --git a/libsysutils/src/SocketListener.cpp b/libsysutils/src/SocketListener.cpp
new file mode 100644
index 0000000..1f80121
--- /dev/null
+++ b/libsysutils/src/SocketListener.cpp
@@ -0,0 +1,198 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <stdio.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <sys/socket.h>
+#include <sys/select.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <sys/un.h>
+
+#define LOG_TAG "SocketListener"
+#include <cutils/log.h>
+#include <cutils/sockets.h>
+
+#include <sysutils/SocketListener.h>
+#include <sysutils/SocketClient.h>
+
+SocketListener::SocketListener(const char *socketName, bool listen) {
+    mListen = listen;
+    mSocketName = socketName;
+    mSock = -1;
+    pthread_mutex_init(&mClientsLock, NULL);
+    mClients = new SocketClientCollection();
+}
+
+SocketListener::SocketListener(int socketFd, bool listen) {
+    mListen = listen;
+    mSocketName = NULL;
+    mSock = socketFd;
+    pthread_mutex_init(&mClientsLock, NULL);
+    mClients = new SocketClientCollection();
+}
+
+int SocketListener::startListener() {
+
+    if (!mSocketName && mSock == -1) {
+        errno = EINVAL;
+        return -1;
+    } else if (mSocketName) {
+        if ((mSock = android_get_control_socket(mSocketName)) < 0) {
+            LOGE("Obtaining file descriptor socket '%s' failed: %s",
+                 mSocketName, strerror(errno));
+            return -1;
+        }
+    }
+
+    if (mListen && listen(mSock, 4) < 0) {
+        LOGE("Unable to listen on socket (%s)", strerror(errno));
+        return -1;
+    } else if (!mListen)
+        mClients->push_back(new SocketClient(mSock));
+
+    if (pipe(mCtrlPipe))
+        return -1;
+
+    if (pthread_create(&mThread, NULL, SocketListener::threadStart, this))
+        return -1;
+
+    return 0;
+}
+
+int SocketListener::stopListener() {
+    char c = 0;
+
+    if (write(mCtrlPipe[1], &c, 1) != 1) {
+        LOGE("Error writing to control pipe (%s)", strerror(errno));
+        return -1;
+    }
+
+    void *ret;
+    if (pthread_join(mThread, &ret)) {
+        LOGE("Error joining to listener thread (%s)", strerror(errno));
+        return -1;
+    }
+    close(mCtrlPipe[0]);
+    close(mCtrlPipe[1]);
+    return 0;
+}
+
+void *SocketListener::threadStart(void *obj) {
+    SocketListener *me = reinterpret_cast<SocketListener *>(obj);
+
+    me->runListener();
+    pthread_exit(NULL);
+    return NULL;
+}
+
+void SocketListener::runListener() {
+
+    while(1) {
+        SocketClientCollection::iterator it;
+        fd_set read_fds;
+        int rc = 0;
+        int max = 0;
+
+        FD_ZERO(&read_fds);
+
+        if (mListen) {
+            max = mSock;
+            FD_SET(mSock, &read_fds);
+        }
+
+        FD_SET(mCtrlPipe[0], &read_fds);
+        if (mCtrlPipe[0] > max)
+            max = mCtrlPipe[0];
+
+        pthread_mutex_lock(&mClientsLock);
+        for (it = mClients->begin(); it != mClients->end(); ++it) {
+            FD_SET((*it)->getSocket(), &read_fds);
+            if ((*it)->getSocket() > max)
+                max = (*it)->getSocket();
+        }
+        pthread_mutex_unlock(&mClientsLock);
+
+        if ((rc = select(max + 1, &read_fds, NULL, NULL, NULL)) < 0) {
+            LOGE("select failed (%s)", strerror(errno));
+            sleep(1);
+            continue;
+        } else if (!rc)
+            continue;
+
+        if (FD_ISSET(mCtrlPipe[0], &read_fds))
+            break;
+        if (mListen && FD_ISSET(mSock, &read_fds)) {
+            struct sockaddr addr;
+            socklen_t alen = sizeof(addr);
+            int c;
+
+            if ((c = accept(mSock, &addr, &alen)) < 0) {
+                LOGE("accept failed (%s)", strerror(errno));
+                sleep(1);
+                continue;
+            }
+            pthread_mutex_lock(&mClientsLock);
+            mClients->push_back(new SocketClient(c));
+            pthread_mutex_unlock(&mClientsLock);
+        }
+
+        do {
+            pthread_mutex_lock(&mClientsLock);
+            for (it = mClients->begin(); it != mClients->end(); ++it) {
+                int fd = (*it)->getSocket();
+                if (FD_ISSET(fd, &read_fds)) {
+                    pthread_mutex_unlock(&mClientsLock);
+                    if (!onDataAvailable(*it)) {
+                        LOGD("SocketListener closing client socket");
+                        close(fd);
+                        pthread_mutex_lock(&mClientsLock);
+                        delete *it;
+                        it = mClients->erase(it);
+                        pthread_mutex_unlock(&mClientsLock);
+                    }
+                    FD_CLR(fd, &read_fds);
+                    continue;
+                }
+            }
+            pthread_mutex_unlock(&mClientsLock);
+        } while (0);
+    }
+}
+
+void SocketListener::sendBroadcast(int code, const char *msg, bool addErrno) {
+    pthread_mutex_lock(&mClientsLock);
+    SocketClientCollection::iterator i;
+
+    for (i = mClients->begin(); i != mClients->end(); ++i) {
+        if ((*i)->sendMsg(code, msg, addErrno)) {
+            LOGW("Error sending broadcast (%s)", strerror(errno));
+        }
+    }
+    pthread_mutex_unlock(&mClientsLock);
+}
+
+void SocketListener::sendBroadcast(const char *msg) {
+    pthread_mutex_lock(&mClientsLock);
+    SocketClientCollection::iterator i;
+
+    for (i = mClients->begin(); i != mClients->end(); ++i) {
+        if ((*i)->sendMsg(msg)) {
+            LOGW("Error sending broadcast (%s)", strerror(errno));
+        }
+    }
+    pthread_mutex_unlock(&mClientsLock);
+}
diff --git a/logcat/event-log-tags b/logcat/event-log-tags
index 28cad0a..f9355ec 100644
--- a/logcat/event-log-tags
+++ b/logcat/event-log-tags
@@ -323,6 +323,12 @@
 # PDP drop caused by network
 50109 pdp_network_drop (cid|1|5), (network_type|1|5)
 
+# CDMA data network setup failure
+50110 cdma_data_setup_failed (cause|1|5), (cid|1|5), (network_type|1|5)
+
+# CDMA data network drop
+50111 cdma_data_drop (cid|1|5), (network_type|1|5)
+
 # Do not change these names without updating tag in:
 #//device/dalvik/libcore/luni/src/main/native/org_apache_harmony_luni_platform_OSNetworkSystem.c
 51000 socket_stats (send|1|2),(recv|1|2),(ip|1|5),(port|1|5),(close|1|5)
diff --git a/mkbootimg/mkbootimg.c b/mkbootimg/mkbootimg.c
index d803cf6..3642647 100644
--- a/mkbootimg/mkbootimg.c
+++ b/mkbootimg/mkbootimg.c
@@ -63,6 +63,7 @@
             "       [ --second <2ndbootloader-filename> ]\n"
             "       [ --cmdline <kernel-commandline> ]\n"
             "       [ --board <boardname> ]\n"
+            "       [ --base <address> ]\n"
             "       -o|--output <filename>\n"
             );
     return 1;
@@ -104,7 +105,6 @@
     char *bootimg = 0;
     char *board = "";
     unsigned pagesize = 2048;
-    unsigned saddr = 0;
     int fd;
     SHA_CTX ctx;
     uint8_t* sha;
@@ -114,6 +114,14 @@
 
     memset(&hdr, 0, sizeof(hdr));
 
+        /* default load addresses */
+    hdr.kernel_addr =  0x10008000;
+    hdr.ramdisk_addr = 0x11000000;
+    hdr.second_addr =  0x10F00000;
+    hdr.tags_addr =    0x10000100;
+
+    hdr.page_size = pagesize;
+
     while(argc > 0){
         char *arg = argv[0];
         char *val = argv[1];
@@ -132,8 +140,12 @@
             second_fn = val;
         } else if(!strcmp(arg, "--cmdline")) {
             cmdline = val;
-        } else if(!strcmp(arg, "--saddr")) {
-            saddr = strtoul(val, 0, 16);
+        } else if(!strcmp(arg, "--base")) {
+            unsigned base = strtoul(val, 0, 16);
+            hdr.kernel_addr =  base + 0x00008000;
+            hdr.ramdisk_addr = base + 0x01000000;
+            hdr.second_addr =  base + 0x00F00000;
+            hdr.tags_addr =    base + 0x00000100;
         } else if(!strcmp(arg, "--board")) {
             board = val;
         } else {
@@ -163,16 +175,6 @@
 
     strcpy(hdr.name, board);
 
-    hdr.kernel_addr =  0x10008000;
-    hdr.ramdisk_addr = 0x11000000;
-    if(saddr) {
-        hdr.second_addr =  0x00300000;
-    } else {
-        hdr.second_addr =  0x10F00000;
-    }
-    hdr.tags_addr   =  0x10000100;
-    hdr.page_size = pagesize;
-
     memcpy(hdr.magic, BOOT_MAGIC, BOOT_MAGIC_SIZE);
 
     if(strlen(cmdline) > (BOOT_ARGS_SIZE - 1)) {
diff --git a/mountd/ASEC.c b/mountd/ASEC.c
deleted file mode 100644
index a6aab9c..0000000
--- a/mountd/ASEC.c
+++ /dev/null
@@ -1,774 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
-** Android Secure External Cache 
-*/
-
-#include "mountd.h"
-
-#include <stdio.h>
-#include <unistd.h>
-#include <string.h>
-#include <fcntl.h>
-#include <dirent.h>
-#include <ctype.h>
-#include <pwd.h>
-#include <stdlib.h>
-#include <poll.h>
-#include <errno.h>
-
-#include <sys/ioctl.h>
-#include <sys/mount.h>
-#include <sys/stat.h>
-
-#include <linux/dm-ioctl.h>
-#include <linux/loop.h>
-
-#include <cutils/properties.h>
-#include <cutils/misc.h>
-
-#include "ASEC.h"
-
-//#define MODULE_FAILURE_IS_FATAL
-
-extern int init_module(void *, unsigned long, const char *);
-extern int delete_module(const char *, unsigned int);
-
-struct asec_context
-{
-    char *name;           // Device mapper volume name
-    char *srcPath;        // Path to the source (original) mount
-    char *backingFile;    // Name of the image file
-    unsigned int sectors; // Number of sectors
-    char *dstPath;        // Destination mount point
-    char *crypt;          // Crypt options
-
-    boolean needs_format;
-    boolean started;
-    int cacheFd;
-    int lo_num;
-    int dm_num;
-    unsigned char key[16];
-};
-
-static const char *MODULES[] = { "dm_mod", "crypto", "crypto_algapi", "crypto_blkcipher", 
-                                 "cryptomgr", "dm_crypt", "jbd",  
-                                 "twofish_common", "twofish", "cbc",
-                                 "mbcache", "ext3",
-                                 NULL };
-static const char KEY_PATH[] = "/data/system/asec.key";
-static const char MODULE_PATH[] = "/system/lib/modules";
-static const char MKE2FS_PATH[] = "/system/bin/mke2fs";
-static const char E2FSCK_PATH[] = "/system/bin/e2fsck";
-
-boolean AsecIsStarted(void *Handle)
-{
-    struct asec_context *ctx = (struct asec_context *) Handle;
-
-    return ctx->started;
-}
-
-const char *AsecMountPoint(void *Handle)
-{
-    struct asec_context *ctx = (struct asec_context *) Handle;
-
-    return ctx->dstPath;
-}
-
-static boolean AsecIsEnabled()
-{
-    char value[PROPERTY_VALUE_MAX];
-    int  enabled;
-
-    property_get(ASEC_ENABLED, value, "0");
-
-    if (atoi(value) == 1)
-        return true;
-    return false;
-}
-
-void *AsecInit(const char *Name, const char *SrcPath, const char *BackingFile,
-               const char *Size, const char *DstPath, const char *Crypt)
-{
-    struct asec_context *ctx;
-
-    if (!AsecIsEnabled())
-        return NULL;
-
-    LOG_ASEC("AsecInit(%s, %s, %s, %s, %s, %s):\n",
-             Name, SrcPath, BackingFile, Size, DstPath, Crypt);
-
-    if (!Name || !SrcPath || !BackingFile || !Size || !DstPath || !Crypt) {
-        LOG_ERROR("AsecInit(): Invalid arguments\n");
-        return NULL;
-    }
-
-    if (!(ctx = malloc(sizeof(struct asec_context)))) {
-        LOG_ERROR("AsecInit(): Out of memory\n");
-        return NULL;
-    }
-
-    memset(ctx, 0, sizeof(struct asec_context));
-    ctx->name = strdup(Name);
-    ctx->srcPath = strdup(SrcPath);
-    ctx->backingFile = strdup(BackingFile);
-    ctx->sectors = atoi(Size);
-    ctx->dstPath = strdup(DstPath);
-    ctx->crypt = strdup(Crypt);
-    return ctx;
-}
-
-void AsecDeinit(void *Handle)
-{
-    struct asec_context *ctx = (struct asec_context *) Handle;
-
-    free(ctx->name);
-    free(ctx->srcPath);
-    free(ctx->backingFile);
-    free(ctx->dstPath);
-    free(ctx->crypt);
-
-    free(ctx);
-}
-
-static int AsecLoadModules()
-{
-    int i;
-
-    for (i = 0; MODULES[i] != NULL; i++) {
-	const char *moduleName = MODULES[i];
-        char moduleFile[255];
-        int rc = 0;
-        void *module;
-        unsigned int size;
-
-        sprintf(moduleFile, "%s/%s.ko", MODULE_PATH, moduleName);
-        module = load_file(moduleFile, &size);
-        if (!module) {
-            LOG_ERROR("Failed to load module %s (%d)\n", moduleFile, errno);
-            return -1;
-        }
-
-        rc = init_module(module, size, "");
-        free(module);
-        if (rc && errno != EEXIST) {
-            LOG_ERROR("Failed to init module %s (%d)\n", moduleFile, errno);
-            return -errno;
-        }
-    }
-    return 0;
-}
-
-static int AsecUnloadModules()
-{
-    int i, j, rc;
-
-    for (i = 0; MODULES[i] != NULL; i++);
-
-    for (j = (i - 1); j >= 0; j--) {
-	const char *moduleName = MODULES[j];
-        int maxretry = 10;
-        while(maxretry-- > 0) {
-            rc = delete_module(moduleName, O_NONBLOCK | O_EXCL);
-            if (rc < 0 && errno == EAGAIN)
-                usleep(500000);
-            else
-                break;
-        }
-        if (rc != 0) {
-            LOG_ERROR("Failed to unload module %s\n", moduleName);
-            return -errno;
-        }
-    }
-    return 0;
-}
-
-static int AsecGenerateKey(struct asec_context *ctx)
-{
-    LOG_ASEC("AsecGenerateKey():\n");
-
-    memset((void *) ctx->key, 0x69, sizeof(ctx->key));
-    return 0;
-}
-
-static int AsecLoadGenerateKey(struct asec_context *ctx)
-{
-    int fd;
-    int rc = 0;
-
-    if ((fd = open(KEY_PATH, O_RDWR | O_CREAT, 0600)) < 0) {
-        LOG_ERROR("Error opening / creating keyfile (%d)\n", errno);
-        return -errno;
-    }
-
-    if (read(fd, ctx->key, sizeof(ctx->key)) != sizeof(ctx->key)) {
-        LOG_ASEC("Generating key\n");
-        if ((rc = AsecGenerateKey(ctx)) < 0) {
-            LOG_ERROR("Error generating key (%d)\n", rc);
-            goto out;
-        }
-        if (write(fd, ctx->key, sizeof(ctx->key)) != sizeof(ctx->key)) {
-            LOG_ERROR("Error writing keyfile (%d)\n", errno);
-            rc = -1;
-            goto out;
-        }
-    }
-    
- out:
-    close (fd);
-    return rc;
-}
-
-static int AsecFormatFilesystem(struct asec_context *ctx)
-{
-    char cmdline[255];
-    int rc;
-
-    sprintf(cmdline,
-            "%s -b 4096 -m 1 -j -L \"%s\" /dev/block/dm-%d",
-            MKE2FS_PATH, ctx->name, ctx->dm_num);
-
-    LOG_ASEC("Formatting filesystem (%s)\n", cmdline);
-    // XXX: PROTECT FROM VIKING KILLER
-    if ((rc = system(cmdline)) < 0) {
-        LOG_ERROR("Error executing format command (%d)\n", errno);
-        return -errno;
-    }
-
-    rc = WEXITSTATUS(rc);
-
-    if (!rc) {
-        LOG_ASEC("Format completed\n");
-    } else {
-        LOG_ASEC("Format failed (%d)\n", rc);
-    }
-
-    return rc;
-}
-
-static int AsecCheckFilesystem(struct asec_context *ctx)
-{
-    char cmdline[255];
-    int rc;
-
-    sprintf(cmdline, "%s -p /dev/block/dm-%d", E2FSCK_PATH, ctx->dm_num);
-
-    LOG_ASEC("Checking filesystem (%s)\n", cmdline);
-    // XXX: PROTECT FROM VIKING KILLER
-    if ((rc = system(cmdline)) < 0) {
-        LOG_ERROR("Error executing check command (%d)\n", errno);
-        return -errno;
-    }
-
-    rc = WEXITSTATUS(rc);
-
-    if (rc == 0) {
-        LOG_ASEC("ASEC volume '%s' had no errors\n", ctx->name);
-    } else if (rc == 1) {
-        LOG_ASEC("ASEC volume '%s' had corrected errors\n", ctx->name);
-        rc = 0;
-    } else if (rc == 2) {
-        LOG_ERROR("ASEC volume '%s' had corrected errors (system should be rebooted)\n", ctx->name);
-    } else if (rc == 4) {
-        LOG_ERROR("ASEC volume '%s' had uncorrectable errors\n", ctx->name);
-    } else if (rc == 8) {
-        LOG_ERROR("Operational error while checking volume '%s'\n", ctx->name);
-    } else {
-        LOG_ERROR("Unknown e2fsck exit code (%d)\n", rc);
-    }
-    return rc;
-}
-
-static int AsecOpenCreateCache(struct asec_context *ctx)
-{
-    char filepath[255];
-
-    sprintf(filepath, "%s/%s", ctx->srcPath, ctx->backingFile);
-
-    if ((ctx->cacheFd = open(filepath, O_RDWR)) < 0) {
-        if (errno == ENOENT) {
-            int rc = 0;
-
-            LOG_ASEC("Creating cache file (%u sectors)\n", ctx->sectors);
-            if ((ctx->cacheFd = creat(filepath, 0600)) < 0) {
-                LOG_ERROR("Error creating cache (%d)\n", errno);
-                return -errno;
-            }
-            if (ftruncate(ctx->cacheFd, ctx->sectors * 512) < 0) {
-                LOG_ERROR("Error truncating cache (%d)\n", errno);
-                close(ctx->cacheFd);
-                unlink(filepath);
-                return -errno;
-            }
-            LOG_ASEC("Cache created (%u sectors) \n", ctx->sectors);
-            close(ctx->cacheFd); // creat() is WRONLY
-           
-            if ((ctx->cacheFd = open(filepath, O_RDWR)) < 0) {
-               LOG_ERROR("Error opening cache file (%d)\n", errno);
-                close(ctx->cacheFd);
-                unlink(filepath);
-                return -errno;
-            }
-
-            ctx->needs_format = 1;
-        } else
-            return -errno;
-    } else {
-        struct stat stat_buf;
-
-        if (fstat(ctx->cacheFd, &stat_buf) < 0) {
-            LOG_ERROR("Failed to fstat cache (%d)\n", errno);
-            close(ctx->cacheFd);
-            return -errno;
-        }
-        if (stat_buf.st_size != ctx->sectors * 512) {
-            LOG_ERROR("Cache size %lld != configured size %u\n",
-                      stat_buf.st_size, ctx->sectors * 512);
-        }
-
-        // XXX: Verify volume label matches ctx->name
-    }
-
-    return 0;
-}
-
-static void AsecCloseCache(struct asec_context *ctx)
-{
-    close(ctx->cacheFd);
-}
-
-static void *_align(void *ptr, unsigned int a)
-{
-        register unsigned long agn = --a;
-
-        return (void *) (((unsigned long) ptr + agn) & ~agn);
-}
-
-static struct dm_ioctl *_dm_ioctl_setup(struct asec_context *ctx, int flags)
-{
-    void *buffer;
-    void *p;
-    const size_t min_size = 16 * 1024;
-    size_t len = sizeof(struct dm_ioctl);
-    struct dm_ioctl *io;
-    struct dm_target_spec *tgt;
-    int i;
-    char params[1024];
-    char key[80];
-
-    key[0] = '\0';
-
-    for (i = 0; i < (int) sizeof(ctx->key); i++) {
-        char tmp[8];
-
-        sprintf(tmp, "%02x", ctx->key[i]);
-        strcat(key, tmp);
-    }
-
-    // XXX: Handle ctx->crypt 
-    sprintf(params, "twofish %s 0 /dev/block/loop%d 0", key, ctx->lo_num);
- 
-    if (len < min_size)
-        len = min_size;
-
-    if (!(buffer = malloc(len))) {
-        LOG_ERROR("Unable to allocate memory\n");
-        return NULL;
-    }
-
-    memset(buffer, 0, len);
-    io = buffer;
-    tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
-    
-    io->version[0] = 4;
-    io->version[1] = 0;
-    io->version[2] = 0;
-
-    io->data_size = len;
-    io->data_start = sizeof(struct dm_ioctl);
-
-    io->flags = flags;
-    io->dev = 0; 
-
-    io->target_count = 1;
-    io->event_nr = 1;
-    strncpy(io->name, ctx->name, sizeof(io->name));
-
-    tgt->status = 0;
-    tgt->sector_start = 0;
-    tgt->length = ctx->sectors;
-    strncpy(tgt->target_type, "crypt", sizeof(tgt->target_type));
-
-    p = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
-    strcpy((char *) p, params);
-    p+= strlen(params) + 1;
-
-    p = _align(p, 8);
-    tgt->next = p - buffer;
-
-    return io;
-}
-
-static int FindNextAvailableDm()
-{
-    int i;
-
-    for (i = 0; i < 8; i++) {
-        char path[255];
-        sprintf(path, "/dev/block/dm-%d", i);
-        if ((access(path, F_OK) < 0) && (errno == ENOENT))
-            return i;
-    }
-
-    LOG_ERROR("Out of device mapper numbers\n");
-    return -1;
-}
-
-static int AsecCreateDeviceMapping(struct asec_context *ctx)
-{
-    struct dm_ioctl       *io;
-    int                   dmFd;
-    int                   rc = 0;
-
-    ctx->dm_num = FindNextAvailableDm();
-
-    if ((dmFd = open("/dev/device-mapper", O_RDWR)) < 0) {
-        LOG_ERROR("Error opening device mapper (%d)\n", errno);
-        return -errno;
-    }
-
-    if (!(io = _dm_ioctl_setup(ctx, 0))) {
-        LOG_ERROR("Unable to setup ioctl (out of memory)\n");
-        close(dmFd);
-        return -ENOMEM;
-    }
-
-    if ((rc = ioctl(dmFd, DM_DEV_CREATE, io)) < 0) {
-        LOG_ERROR("device-mapper create ioctl failed (%d)\n", errno);
-        rc = -errno;
-        goto out_free;
-    } 
-
-    free(io);
-
-    if (!(io = _dm_ioctl_setup(ctx, DM_STATUS_TABLE_FLAG))) {
-        LOG_ERROR("Unable to setup ioctl (out of memory)\n");
-        rc = -ENOMEM;
-        goto out_nofree;
-    }
- 
-    if ((rc = ioctl(dmFd, DM_TABLE_LOAD, io)) < 0) {
-        LOG_ERROR("device-mapper load ioctl failed (%d)\n", errno);
-        rc = -errno;
-        goto out_free;
-    }
-
-    free(io);
- 
-    if (!(io = _dm_ioctl_setup(ctx, 0))) {
-        LOG_ERROR("Unable to setup ioctl (out of memory)\n");
-        rc = -ENOMEM;
-        goto out_nofree;
-    }
-
-    if ((rc = ioctl(dmFd, DM_DEV_SUSPEND, io)) < 0) {
-        LOG_ERROR("device-mapper resume ioctl failed (%d)\n", errno);
-        rc = -errno;
-        goto out_free;
-    }
-
-out_free:
-    free (io);
-out_nofree:
-    close (dmFd);
-    return rc;
-}
-
-static int AsecDestroyDeviceMapping(struct asec_context *ctx)
-{
-    struct dm_ioctl       *io;
-    int                   dmFd;
-    int                   rc = 0;
-
-    if ((dmFd = open("/dev/device-mapper", O_RDWR)) < 0) {
-        LOG_ERROR("Error opening device mapper (%d)\n", errno);
-        return -errno;
-    }
-
-    if (!(io = _dm_ioctl_setup(ctx, DM_PERSISTENT_DEV_FLAG))) {
-        LOG_ERROR("Unable to setup ioctl (out of memory)\n");
-        rc = -ENOMEM;
-        goto out_nofree;
-    }
-
-    if ((rc = ioctl(dmFd, DM_DEV_REMOVE, io)) < 0) {
-        LOG_ERROR("device-mapper remove ioctl failed (%d)\n", errno);
-        rc = -errno;
-        goto out_free;
-    } 
-
-out_free:
-    free (io);
-out_nofree:
-    close (dmFd);
-    return rc;
-}
-
-static int AsecMountCache(struct asec_context *ctx)
-{
-    int flags = MS_NODEV | MS_NOEXEC | MS_NOSUID | MS_NOATIME | MS_NODIRATIME;
-    char devname[255];
-
-    if (access(ctx->dstPath, R_OK)) {
-        LOG_ERROR("Destination mount point '%s' unavailable (%d)\n", ctx->dstPath, errno);
-        return -errno;
-    }
-
-    sprintf(devname, "/dev/block/dm-%d", ctx->dm_num);
-
-    if (mount(devname, ctx->dstPath, "ext3", flags, NULL)) {
-        LOG_ERROR("ASEC mount failed (%d)\n", errno);
-        return -errno;
-    }
-    
-    return 0;
-}
-
-static int AsecUnmountCache(struct asec_context *ctx)
-{
-    if (umount(ctx->dstPath)) {
-        if (errno == EBUSY) {
-            LOG_ASEC("ASEC volume '%s' still busy\n", ctx->name);
-        } else {
-            LOG_ERROR("ASEC umount failed (%d)\n", errno);
-        }
-        return -errno;
-    }
-    LOG_ASEC("ASEC volume '%s' unmounted\n", ctx->name);
-    return 0;
-}
-
-static int FindNextAvailableLoop()
-{
-    int i;
-
-    for (i = 0; i < MAX_LOOP; i++) {
-        struct loop_info info;
-        char devname[255];
-        int fd;
-
-        sprintf(devname, "/dev/block/loop%d", i);
-
-        if ((fd = open(devname, O_RDONLY)) < 0) {
-            LOG_ERROR("Unable to open %s (%d)\n", devname, errno);
-            return -errno;
-        }
-
-        if (ioctl(fd, LOOP_GET_STATUS, &info) < 0) {
-            close(fd);
-
-            if (errno == ENXIO)
-                return i;
-
-            LOG_ERROR("Unable to get loop status for %s (%d)\n", devname, errno);
-            return -errno;
-        }
-        close(fd);
-    }
-    return -ENXIO;
-}
-
-static int AsecCreateLoop(struct asec_context *ctx)
-{
-    char devname[255];
-    int device_fd;
-    int rc = 0;
-
-    ctx->lo_num = FindNextAvailableLoop();
-    if (ctx->lo_num < 0) {
-        LOG_ERROR("No loop devices available\n");
-        return -ENXIO;
-    }
-
-    sprintf(devname, "/dev/block/loop%d", ctx->lo_num);
-    device_fd = open(devname, O_RDWR);
-    if (device_fd < 0) {
-        LOG_ERROR("failed to open loop device (%d)\n", errno);
-        return -errno;
-    }
-
-    if (ioctl(device_fd, LOOP_SET_FD, ctx->cacheFd) < 0) {
-        LOG_ERROR("loop_set_fd ioctl failed (%d)\n", errno);
-        rc = -errno;
-    }
-    close(device_fd);
-    return rc;
-}
-
-static int AsecDestroyLoop(struct asec_context *ctx)
-{
-    char devname[255];
-    int device_fd;
-    int rc = 0;
-
-    sprintf(devname, "/dev/block/loop%d", ctx->lo_num);
-    device_fd = open(devname, O_RDONLY);
-    if (device_fd < 0) {
-        LOG_ERROR("Failed to open loop (%d)\n", errno);
-        return -errno;
-    }
-
-    if (ioctl(device_fd, LOOP_CLR_FD, 0) < 0) {
-        LOG_ERROR("Failed to destroy loop (%d)\n", errno);
-        rc = -errno;
-    }
-
-    close(device_fd);
-    return rc;
-}
-
-int AsecStart(void *Handle)
-{
-    struct asec_context *ctx = (struct asec_context *) Handle;
-    char value[PROPERTY_VALUE_MAX];
-    int rc = 0;
-
-    if (!ctx)
-        return -EINVAL;
-
-    if (ctx->started)
-        return -EBUSY;
-
-    LOG_ASEC("AsecStart(%s):\n", ctx->name);
-
-    NotifyAsecState(ASEC_BUSY, ctx->dstPath);
-
-    if ((rc = AsecLoadModules()) < 0) {
-        LOG_ERROR("AsecStart: Failed to load kernel modules\n");
-#ifdef MODULE_FAILURE_IS_FATAL
-        NotifyAsecState(ASEC_FAILED_INTERR, ctx->dstPath);
-	return rc;
-#endif
-    }
-
-    if ((rc = AsecLoadGenerateKey(ctx))) {
-        LOG_ERROR("AsecStart: Failed to load / generate key\n");
-        NotifyAsecState(ASEC_FAILED_INTERR, ctx->dstPath);
-	return rc;
-    }
-    
-    if ((rc = AsecOpenCreateCache(ctx)) < 0) {
-        LOG_ERROR("AsecStart: Failed to open / create cache\n");
-        NotifyAsecState(ASEC_FAILED_INTERR, ctx->dstPath);
-	return rc;
-    }
-
-    if ((rc = AsecCreateLoop(ctx)) < 0) {
-        LOG_ERROR("AsecStart: Failed to create loop\n");
-        NotifyAsecState(ASEC_FAILED_INTERR, ctx->dstPath);
-	goto fail_closecache;
-    }
-
-    if ((rc = AsecCreateDeviceMapping(ctx)) < 0) {
-        LOG_ERROR("AsecStart: Failed to create devmapping (%d)\n", rc);
-        NotifyAsecState(ASEC_FAILED_INTERR, ctx->dstPath);
-        goto fail_destroyloop;
-    }
-    
-    if (ctx->needs_format) {
-        if ((rc = AsecFormatFilesystem(ctx))) {
-            LOG_ERROR("AsecStart: Failed to format cache (%d)\n", rc);
-            NotifyAsecState(ASEC_FAILED_INTERR, ctx->dstPath);
-            goto fail_destroydm;
-        }
-        ctx->needs_format = 0;
-    } else {
-        if ((rc = AsecCheckFilesystem(ctx))) {
-            LOG_ERROR("AsecStart: Failed to check filesystem (%d)\n", rc);
-            NotifyAsecState(ASEC_FAILED_INTERR, ctx->dstPath);
-            goto fail_destroydm;
-        }
-    }
-
-    if ((rc = AsecMountCache(ctx)) < 0) {
-        LOG_ERROR("AsecStart: Failed to mount cache (%d)\n", rc);
-        NotifyAsecState(ASEC_FAILED_INTERR, ctx->dstPath);
-        goto fail_destroydm;
-    }
-    
-    NotifyAsecState(ASEC_AVAILABLE, ctx->dstPath);
-    ctx->started = true;
-
-    return rc;
-
- fail_destroydm:
-    AsecDestroyDeviceMapping(ctx);
- fail_destroyloop:
-    AsecDestroyLoop(ctx);
- fail_closecache:
-    AsecCloseCache(ctx);
-    return rc;
-}
-
-int AsecStop(void *Handle)
-{
-    struct asec_context *ctx = (struct asec_context *) Handle;
-    int rc = 0;
-
-    if (!ctx->started)
-        return -EINVAL;
-
-    LOG_ASEC("AsecStop(%s):\n", ctx->name);
-
-    NotifyAsecState(ASEC_BUSY, ctx->dstPath);
-
-    if ((rc = AsecUnmountCache(ctx)) < 0) {
-        LOG_ERROR("AsecStop: Failed to unmount cache (%d)\n", rc);
-        NotifyAsecState(ASEC_FAILED_INTERR, ctx->dstPath);
-	return rc;
-    }
-
-    if ((rc = AsecDestroyDeviceMapping(ctx)) < 0) {
-        LOG_ERROR("AsecStop: Failed to destroy devmapping (%d)\n", rc);
-        NotifyAsecState(ASEC_FAILED_INTERR, ctx->dstPath);
-	return rc;
-    }
-
-    if ((rc = AsecDestroyLoop(ctx)) < 0) {
-        LOG_ERROR("AsecStop: Failed to destroy loop device (%d)\n", rc);
-        NotifyAsecState(ASEC_FAILED_INTERR, ctx->dstPath);
-	return rc;
-    }
-
-    AsecCloseCache(ctx);
- 
-    if ((rc = AsecUnloadModules()) < 0) {
-        if (rc == -EAGAIN) {
-            LOG_ASEC("AsecStop: Kernel modules still in use\n");
-        } else {
-            LOG_ERROR("AsecStop: Failed to unload kernel modules (%d)\n", rc);
-#ifdef MODULE_FAILURE_IS_FATAL
-            NotifyAsecState(ASEC_FAILED_INTERR, ctx->dstPath);
-	    return rc;
-#endif
-        }
-    }
-
-    ctx->started = false;
-    NotifyAsecState(ASEC_DISABLED, ctx->dstPath);
-    return rc;
-}
diff --git a/mountd/ASEC.h b/mountd/ASEC.h
deleted file mode 100644
index c87b288..0000000
--- a/mountd/ASEC.h
+++ /dev/null
@@ -1,66 +0,0 @@
-#ifndef _ASEC_H
-#define _ASEC_H
-
-#define ASEC_STORES_MAX 4
-#define MAX_LOOP 8
-
-typedef enum AsecState {
-    // Feature disabled
-    ASEC_DISABLED,
-
-    // Feature enabled and operational
-    ASEC_AVAILABLE,
-
-    // Busy
-    ASEC_BUSY,
-
-    // Internal Error
-    ASEC_FAILED_INTERR,
-
-    // No media available
-    ASEC_FAILED_NOMEDIA,
-
-    // Media is corrupt
-    ASEC_FAILED_BADMEDIA,
-
-    // Key mismatch
-    ASEC_FAILED_BADKEY,
-} AsecState;
-
-/*
- * ASEC commands
- */
-#define ASEC_CMD_SEND_STATUS		"asec_send_status"
-#define ASEC_CMD_ENABLE			"asec_enable"
-#define ASEC_CMD_DISABLE		"asec_disable"
-
-/*
- * ASEC events
- */
-
-// These events correspond to the states in the AsecState enum.
-// A path to the ASEC mount point follows the colon
-#define ASEC_EVENT_DISABLED		"asec_disabled:"
-#define ASEC_EVENT_AVAILABLE		"asec_available:"
-#define ASEC_EVENT_BUSY			"asec_busy:"
-#define ASEC_EVENT_FAILED_INTERR	"asec_failed_interror:"
-#define ASEC_EVENT_FAILED_NOMEDIA	"asec_failed_nomedia"
-#define ASEC_EVENT_FAILED_BADMEDIA	"asec_failed_badmedia:"
-#define ASEC_EVENT_FAILED_BADKEY	"asec_failed_badkey:"
-
-/*
- * System Properties
- */
-
-#define ASEC_ENABLED			"asec.enabled"
-
-#define ASEC_STATUS			"ro.asec.status"
-#define ASEC_STATUS_DISABLED		"disabled"
-#define ASEC_STATUS_AVAILABLE		"available"
-#define ASEC_STATUS_BUSY			"busy"
-#define ASEC_STATUS_FAILED_INTERR	"internal_error"
-#define ASEC_STATUS_FAILED_NOMEDIA	"no_media"
-#define ASEC_STATUS_FAILED_BADMEDIA	"bad_media"
-#define ASEC_STATUS_FAILED_BADKEY	"bad_key"
-
-#endif
diff --git a/mountd/Android.mk b/mountd/Android.mk
deleted file mode 100644
index 16532fa..0000000
--- a/mountd/Android.mk
+++ /dev/null
@@ -1,22 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES:=        \
-    AutoMount.c          \
-    ProcessKiller.c      \
-    Server.c             \
-    mountd.c		 \
-    ASEC.c		 \
-    logwrapper.c
-
-LOCAL_MODULE:= mountd
-
-LOCAL_C_INCLUDES := $(KERNEL_HEADERS)
-
-LOCAL_CFLAGS := -DCREATE_MOUNT_POINTS=0
-
-LOCAL_SHARED_LIBRARIES := libcutils
-
-# disabled - we are using vold now instead
-# include $(BUILD_EXECUTABLE)
diff --git a/mountd/AutoMount.c b/mountd/AutoMount.c
deleted file mode 100644
index 12ad572..0000000
--- a/mountd/AutoMount.c
+++ /dev/null
@@ -1,1062 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
-** mountd automount support
-*/
-
-#include "mountd.h"
-
-#include <pthread.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <string.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <ctype.h>
-#include <pwd.h>
-#include <stdlib.h>
-#include <poll.h>
-
-#include <sys/mount.h>
-#include <sys/stat.h>
-#include <linux/loop.h>
-#include <sys/inotify.h>
-#include <sys/socket.h>
-#include <sys/un.h>
-#include <linux/netlink.h>
-
-#define DEVPATH    "/dev/block/"
-#define DEVPATHLENGTH 11    // strlen(DEVPATH)
-
-// FIXME - only one loop mount is supported at a time
-#define LOOP_DEVICE "/dev/block/loop0"
-
-// timeout value for poll() when retries are pending
-#define POLL_TIMEOUT    1000
-
-#define MAX_MOUNT_RETRIES   3
-#define MAX_UNMOUNT_RETRIES   5
-
-typedef enum {
-    // device is unmounted
-    kUnmounted,
-    
-    // attempting to mount device
-    kMounting,
-    
-    // device is unmounted
-    kMounted,
-    
-    // attempting to unmount device
-    // so the media can be removed
-    kUnmountingForEject,
-    
-    // attempting to mount device
-    // so it can be shared via USB mass storage
-    kUnmountingForUms,
-} MountState;
-
-typedef struct MountPoint {
-    // block device to mount
-    const char* device;
-    
-    // mount point for device
-    const char* mountPoint;
-
-    // path to the UMS driver file for specifying the block device path
-    const char* driverStorePath;
-    
-    // true if device can be shared via
-    // USB mass storage
-    boolean enableUms;
- 
-    // Array of ASEC handles
-    void *asecHandles[ASEC_STORES_MAX];
-
-    // true if the device is being shared via USB mass storage
-    boolean umsActive;
-    
-    // current state of the mount point
-    MountState state;
-    
-    // number of mount or unmount retries so far, 
-    // when attempting to mount or unmount the device
-    int retryCount; 
- 
-    // next in sMountPointList linked list
-    struct MountPoint* next;   
-} MountPoint;
-
-// list of our mount points (does not change after initialization)
-static MountPoint* sMountPointList = NULL;
-boolean gMassStorageEnabled = false;
-boolean gMassStorageConnected = false;
-
-static pthread_t sAutoMountThread = 0;
-static pid_t gExcludedPids[2] = {-1, -1};
-
-static const char FSCK_MSDOS_PATH[] = "/system/bin/dosfsck";
-
-// number of mount points that have timeouts pending
-static int sRetriesPending = 0;
-
-// for synchronization between sAutoMountThread and the server thread
-static pthread_mutex_t sMutex = PTHREAD_MUTEX_INITIALIZER;
-
-// requests the USB mass_storage driver to begin or end sharing a block device
-// via USB mass storage.
-static void SetBackingStore(MountPoint* mp, boolean enable) 
-{
-    int fd;
-
-    if (!mp->driverStorePath) {
-        LOG_ERROR("no driver_store_path specified in config file for %s", mp->device);
-        return;
-    }
-
-    LOG_MOUNT("SetBackingStore enable: %s\n", (enable ? "true" : "false"));
-    fd = open(mp->driverStorePath, O_WRONLY);
-    if (fd < 0)
-    {
-        LOG_ERROR("could not open driver_store_path %s\n", mp->driverStorePath);
-    }
-    else
-    {
-        if (enable)
-        {
-            write(fd, mp->device, strlen(mp->device));
-            mp->umsActive = true;
-        }
-        else
-        {
-            char ch = 0;
-            write(fd, &ch, 1);
-            mp->umsActive = false;
-        }
-        close(fd);
-    }
-}
-
-static boolean ReadMassStorageState()
-{
-    FILE* file = fopen("/sys/class/switch/usb_mass_storage/state", "r");
-    if (file)
-    {
-        char    buffer[20];
-        fgets(buffer, sizeof(buffer), file);
-        fclose(file);
-        return (strncmp(buffer, "online", strlen("online")) == 0);
-    }
-    else
-    {
-        LOG_ERROR("could not read initial mass storage state\n");
-        return false;
-    }
-}
-
-static boolean IsLoopMounted(const char* path)
-{
-    FILE* f;
-    int count;
-    char device[256];
-    char mount_path[256];
-    char rest[256];
-    int result = 0;
-    int path_length = strlen(path);
-       
-    f = fopen("/proc/mounts", "r");
-    if (!f) {
-        LOG_ERROR("could not open /proc/mounts\n");
-        return -1;
-    }
-
-    do {
-        count = fscanf(f, "%255s %255s %255s\n", device, mount_path, rest);
-        if (count == 3) {
-            if (strcmp(LOOP_DEVICE, device) == 0 && strcmp(path, mount_path) == 0)
-            {
-                result = 1;
-                break;
-            }
-        }
-    } while (count == 3);
-
-    fclose(f);
-    LOG_MOUNT("IsLoopMounted: %s returning %d\n", path, result);
-    return result;
-}
-
-static int CheckFilesystem(const char *device)
-{
-    char cmdline[255];
-    int rc;
-
-    // XXX: SAN: Check for FAT signature
-    
-    int result = access(FSCK_MSDOS_PATH, X_OK);
-    if (result != 0) {
-        LOG_MOUNT("CheckFilesystem(%s): %s not found (skipping checks)\n", FSCK_MSDOS_PATH, device);
-        return 0;
-    }
- 
-    char *args[7];
-    args[0] = FSCK_MSDOS_PATH;
-    args[1] = "-v";
-    args[2] = "-V";
-    args[3] = "-w";
-    args[4] = "-p";
-    args[5] = device;
-    args[6] = NULL;
-
-    LOG_MOUNT("Checking filesystem on %s\n", device);
-    rc = logwrap(6, args);
-  
-    // XXX: We need to be able to distinguish between a FS with an error
-    // and a block device which does not have a FAT fs at all on it
-    if (rc == 0) {
-        LOG_MOUNT("Filesystem check completed OK\n");
-        return 0;
-    } else if (rc == 1) {
-        LOG_MOUNT("Filesystem check failed (general failure)\n");
-        return -EINVAL;
-    } else if (rc == 2) {
-        LOG_MOUNT("Filesystem check failed (invalid usage)\n");
-        return -EIO;
-    } else {
-        LOG_MOUNT("Filesystem check failed (unknown exit code %d)\n", rc);
-        return -EIO;
-    }
-}
-
-static int DoMountDevice(const char* device, const char* mountPoint)
-{
-    LOG_MOUNT("Attempting mount of %s on %s\n", device, mountPoint);
-
-#if CREATE_MOUNT_POINTS
-    // make sure mount point exists
-    mkdir(mountPoint, 0000);
-#endif
-
-    int flags = 0;
-    
-    if (device && strncmp(device, "/dev/", 5))
-    {
-        // mount with the loop driver if device does not start with "/dev/"
-        int file_fd, device_fd;
-        
-        // FIXME - only one loop mount supported at a time
-        file_fd = open(device, O_RDWR);
-        if (file_fd < -1) {
-            LOG_ERROR("open backing file %s failed\n", device);
-            return 1;
-        }
-        device_fd = open(LOOP_DEVICE, O_RDWR);
-        if (device_fd < -1) {
-            LOG_ERROR("open %s failed", LOOP_DEVICE);
-            close(file_fd);
-            return 1;
-        }
-        if (ioctl(device_fd, LOOP_SET_FD, file_fd) < 0)
-        {
-            LOG_ERROR("ioctl LOOP_SET_FD failed\n");
-            close(file_fd);
-            close(device_fd);
-            return 1;
-        }
-
-        close(file_fd);
-        close(device_fd);
-        device = "/dev/block/loop0";
-    }
-
-    int result = access(device, R_OK);
-    if (result) {
-	LOG_ERROR("Unable to access '%s' (%d)\n", device, errno);
-   	return -errno;
-    }
-
-#if 0
-    if ((result = CheckFilesystem(device))) {
-        LOG_ERROR("Not mounting filesystem due to check failure (%d)\n", result);
-        // XXX:  Notify framework - need a new SDCARD state for the following:
-        //       - SD cards which are not present
-        //       - SD cards with no partition table
-        //       - SD cards with no filesystem
-        //       - SD cards with bad filesystem
-        return result;
-    }
-#endif
-
-    // Extra safety measures:
-    flags |= MS_NODEV | MS_NOEXEC | MS_NOSUID | MS_DIRSYNC;
-    // Also, set fmask = 711 so that files cannot be marked executable,
-    // and cannot by opened by uid 1000 (system). Similar, dmask = 700
-    // so that directories cannot be accessed by uid 1000.
-    result = mount(device, mountPoint, "vfat", flags, 
-                       "utf8,uid=1000,gid=1000,fmask=711,dmask=700");
-    if (result && errno == EROFS) {
-        LOG_ERROR("mount failed EROFS, try again read-only\n");
-        flags |= MS_RDONLY;
-        result = mount(device, mountPoint, "vfat", flags,
-                       "utf8,uid=1000,gid=1000,fmask=711,dmask=700");
-    }
-
-    if (result == 0) {
-        LOG_MOUNT("Partition %s mounted on %s\n", device, mountPoint);
-        NotifyMediaState(mountPoint, MEDIA_MOUNTED, (flags & MS_RDONLY) != 0);
-
-        MountPoint* mp = sMountPointList;
-        while (mp) {
-            if (!strcmp(mountPoint, mp->mountPoint)) {
-                int i;
-             
-                for (i = 0; i < ASEC_STORES_MAX; i++) {
-                    if (mp->asecHandles[i] != NULL) {
-                        int a_result;
-                        if ((a_result = AsecStart(mp->asecHandles[i])) < 0) {
-                            LOG_ERROR("ASEC start failure (%d)\n", a_result);
-                        }
-                    }
-                }
-                break;
-            }
-            mp = mp -> next;
-        }
-    } else if (errno == EBUSY) {
-        LOG_MOUNT("Mount failed (already mounted)\n");
-        result = 0;
-    } else {
-#if CREATE_MOUNT_POINTS
-        rmdir(mountPoint);
-#endif
-        LOG_MOUNT("Unable to mount %s on %s\n", device, mountPoint);
-    }
-
-    return result;
-}
-
-static int DoUnmountDevice(MountPoint *mp)
-{
-    boolean loop = IsLoopMounted(mp->mountPoint);
-    int i;
-
-    for (i = 0; i < ASEC_STORES_MAX; i++) {
-        if (mp->asecHandles[i] && AsecIsStarted(mp->asecHandles[i]))
-            AsecStop(mp->asecHandles[i]);
-    }
-
-    int result = umount(mp->mountPoint);
-    LOG_MOUNT("umount returned %d errno: %d\n", result, errno);
-
-    if (result == 0)
-    {
-#if CREATE_MOUNT_POINTS
-        rmdir(mountPoint);
-#endif
-        NotifyMediaState(mp->mountPoint, MEDIA_UNMOUNTED, false);
-    }
-
-    if (loop)
-    {
-        // free the loop device
-        int loop_fd = open(LOOP_DEVICE, O_RDONLY);
-        if (loop_fd < -1) {
-            LOG_ERROR("open loop device failed\n");
-        }
-        if (ioctl(loop_fd, LOOP_CLR_FD, 0) < 0) {
-            LOG_ERROR("ioctl LOOP_CLR_FD failed\n");
-        }
-
-        close(loop_fd);
-    }
-
-    // ignore EINVAL and ENOENT, since it usually means the device is already unmounted
-    if (result && (errno == EINVAL || errno == ENOENT))
-        result = 0;
-
-    return result;
-}
-
-static int MountPartition(const char* device, const char* mountPoint)
-{
-    char    buf[100];
-    int i;
-    
-    // attempt to mount subpartitions of the device
-    for (i = 1; i < 10; i++)
-    {
-        int rc;
-        snprintf(buf, sizeof(buf), "%sp%d", device, i);
-        rc = DoMountDevice(buf, mountPoint);
-        LOG_MOUNT("DoMountDevice(%s, %s) = %d\n", buf, mountPoint, rc);
-        if (rc == 0)
-            return 0;
-    }
-
-    return -1;
-}
-
-/*****************************************************
- * 
- * AUTO-MOUNTER STATE ENGINE IMPLEMENTATION
- * 
- *****************************************************/
-
-static void SetState(MountPoint* mp, MountState state)
-{
-    mp->state = state;
-}
-
-// Enter a state that requires retries and timeouts.
-static void SetRetries(MountPoint* mp, MountState state)
-{
-    SetState(mp, state);
-    mp->retryCount = 0;
-
-    sRetriesPending++;
-    // wake up the automounter thread if we are being called 
-    // from somewhere else with no retries pending
-    if (sRetriesPending == 1 && sAutoMountThread != 0 && 
-            pthread_self() != sAutoMountThread)
-        pthread_kill(sAutoMountThread, SIGUSR1);
-}
-
-// Exit a state that requires retries and timeouts.
-static void ClearRetries(MountPoint* mp, MountState state)
-{
-    SetState(mp, state);
-    sRetriesPending--;
-}
-
-// attempt to mount the specified mount point.
-// set up retry/timeout if it does not succeed at first.
-static void RequestMount(MountPoint* mp)
-{
-    LOG_MOUNT("RequestMount %s\n", mp->mountPoint);
-
-    if (mp->state != kMounted && mp->state != kMounting &&
-            access(mp->device, R_OK) == 0) {
-        // try raw device first
-        if (DoMountDevice(mp->device, mp->mountPoint) == 0 ||
-            MountPartition(mp->device, mp->mountPoint) == 0)
-        {
-            SetState(mp, kMounted);
-        }
-        else 
-        {
-            SetState(mp, kMounting);
-            mp->retryCount = 0;
-            SetRetries(mp, kMounting);
-        }
-    }
-}
-
-// Force the kernel to drop all caches.
-static void DropSystemCaches(void)
-{
-    int fd;
-
-    LOG_MOUNT("Dropping system caches\n");
-    fd = open("/proc/sys/vm/drop_caches", O_WRONLY);
-
-    if (fd > 0) {
-        char ch = 3;
-        int rc;
-
-        rc = write(fd, &ch, 1);
-        if (rc <= 0)
-            LOG_MOUNT("Error dropping caches (%d)\n", rc);
-        close(fd);
-    }
-}
-
-// attempt to unmount the specified mount point.
-// set up retry/timeout if it does not succeed at first.
-static void RequestUnmount(MountPoint* mp, MountState retryState)
-{
-    int result;
-
-    LOG_MOUNT("RequestUnmount %s retryState: %d\n", mp->mountPoint, retryState);
-    
-    if (mp->state == kMounted)
-    {
-        SendUnmountRequest(mp->mountPoint);
-
-        // do this in case the user pulls the SD card before we can successfully unmount
-        sync();
-        DropSystemCaches();
-
-        if (DoUnmountDevice(mp) == 0) 
-        {
-            SetState(mp, kUnmounted);
-            if (retryState == kUnmountingForUms) 
-            {
-                SetBackingStore(mp, true);
-                NotifyMediaState(mp->mountPoint, MEDIA_SHARED, false);
-            }
-        }
-        else 
-        {
-            LOG_MOUNT("unmount failed, set retry\n");
-            SetRetries(mp, retryState);
-        }
-    } 
-    else if (mp->state == kMounting)
-    {
-        SetState(mp, kUnmounted);
-    }
-}
-
-// returns true if the mount point should be shared via USB mass storage
-static boolean MassStorageEnabledForMountPoint(const MountPoint* mp)
-{
-    return (gMassStorageEnabled && gMassStorageConnected && mp->enableUms);
-}
-
-// handles changes in gMassStorageEnabled and gMassStorageConnected
-static void MassStorageStateChanged()
-{
-    MountPoint* mp = sMountPointList;
-
-    boolean enable = (gMassStorageEnabled && gMassStorageConnected);
-    LOG_MOUNT("MassStorageStateChanged enable: %s\n", (enable ? "true" : "false"));
-    
-    while (mp)
-    {
-        if (mp->enableUms)
-        {
-            if (enable)
-            {
-                if (mp->state == kMounting)
-                    SetState(mp, kUnmounted);
-                if (mp->state == kUnmounted) 
-                {
-                    SetBackingStore(mp, true);
-                    NotifyMediaState(mp->mountPoint, MEDIA_SHARED, false);
-                }
-                else
-                {
-                    LOG_MOUNT("MassStorageStateChanged requesting unmount\n");
-                    // need to successfully unmount first
-                    RequestUnmount(mp, kUnmountingForUms);
-                }
-            } else if (mp->umsActive) {
-                SetBackingStore(mp, false);
-                if (mp->state == kUnmountingForUms)
-                {
-                    ClearRetries(mp, kMounted);
-                    NotifyMediaState(mp->mountPoint, MEDIA_MOUNTED, false);
-                }
-                else if (mp->state == kUnmounted)
-                {
-                    NotifyMediaState(mp->mountPoint, MEDIA_UNMOUNTED, false);
-                    RequestMount(mp);
-                }
-            }
-        }
-
-        mp = mp->next;
-    }
-}
-
-// called when USB mass storage connected state changes
-static void HandleMassStorageOnline(boolean connected)
-{
-    if (connected != gMassStorageConnected)
-    {
-        gMassStorageConnected = connected;
-        SendMassStorageConnected(connected);
-        
-        // we automatically reset to mass storage off after USB is connected
-        if (!connected)
-            gMassStorageEnabled = false;
-    
-        MassStorageStateChanged();
-    }
-}
-
-// called when a new block device has been created
-static void HandleMediaInserted(const char* device)
-{
-    MountPoint* mp = sMountPointList;
-    
-    LOG_MOUNT("HandleMediaInserted(%s):\n", device);
-
-    while (mp)
-    {
-        // see if the device matches mount point's block device
-        if (mp->state == kUnmounted &&
-                strncmp(device, mp->device + DEVPATHLENGTH, strlen(mp->device) - DEVPATHLENGTH) == 0) 
-        {
-            if (MassStorageEnabledForMountPoint(mp))
-            {
-                SetBackingStore(mp, true);
-                NotifyMediaState(mp->mountPoint, MEDIA_SHARED, false);
-            }
-            else
-                RequestMount(mp);
-        }  
-        mp = mp->next;
-    }
-}
-
-// called when a new block device has been deleted
-static void HandleMediaRemoved(const char* device)
-{    
-    MountPoint* mp = sMountPointList;
-    while (mp)
-    {
-        if (strncmp(device, mp->device + DEVPATHLENGTH, strlen(mp->device) - DEVPATHLENGTH) == 0)
-        {
-            if (mp->enableUms)
-                SetBackingStore(mp, false);
-
-             if (mp->state == kMounted) 
-            {
-                RequestUnmount(mp, kUnmountingForEject);
-                NotifyMediaState(mp->mountPoint, MEDIA_BAD_REMOVAL, false);
-            }
-            
-            NotifyMediaState(mp->mountPoint, MEDIA_REMOVED, false);
-            break;
-        }  
-        mp = mp->next;
-    }
-}
-
-// Handle retrying to mount or unmount devices, 
-// and handle timeout condition if we have tried too many times
-static void HandleRetries()
-{
-    MountPoint* mp = sMountPointList;
-    
-    while (mp)
-    {
-       if (mp->state == kMounting) 
-       {
-            if (MountPartition(mp->device, mp->mountPoint) == 0)
-            {
-                // mount succeeded - clear the retry for this mount point
-                ClearRetries(mp, kMounted);
-            } 
-            else 
-            {
-                mp->retryCount++;
-                if (mp->retryCount == MAX_MOUNT_RETRIES)
-                {
-                    // we failed to mount the device too many times
-                    ClearRetries(mp, kUnmounted);
-                    // notify that we failed to mount
-                    NotifyMediaState(mp->mountPoint, MEDIA_UNMOUNTABLE, false);
-                }
-            }
-       } 
-       else if (mp->state == kUnmountingForEject || mp->state == kUnmountingForUms)
-       {
-            if (DoUnmountDevice(mp) == 0)
-            {
-                // unmounting succeeded
-                // start mass storage, if state is kUnmountingForUms
-                if (mp->state == kUnmountingForUms)
-                {
-                    SetBackingStore(mp, true);
-                     NotifyMediaState(mp->mountPoint, MEDIA_SHARED, false);
-                }
-                // clear the retry for this mount point
-                ClearRetries(mp, kUnmounted);
-            } 
-            else 
-            {
-                mp->retryCount++;
-                if (mp->retryCount >= MAX_UNMOUNT_RETRIES)
-                {
-                    // kill any processes that are preventing the device from unmounting
-                    // send SIGKILL instead of SIGTERM if the first attempt did not succeed
-                    boolean sigkill = (mp->retryCount > MAX_UNMOUNT_RETRIES);
-                    
-                    int i;
-
-                    for (i = 0; i < ASEC_STORES_MAX; i++) {
-                        if (mp->asecHandles[i] && AsecIsStarted(mp->asecHandles[i])) {
-                            LOG_MOUNT("Killing processes for ASEC path '%s'\n",
-                                      AsecMountPoint(mp->asecHandles[i]));
-                            KillProcessesWithOpenFiles(AsecMountPoint(mp->asecHandles[i]),
-                                                       sigkill,
-                                                       gExcludedPids, sizeof(gExcludedPids) / sizeof(pid_t));
-
-                            // Now that we've killed the processes, try to stop the volume again
-                            AsecStop(mp->asecHandles[i]);
-                        }
-                    }
-
-                    // unmounting the device is failing, so start killing processes
-                    KillProcessesWithOpenFiles(mp->mountPoint, sigkill, gExcludedPids, 
-                                               sizeof(gExcludedPids) / sizeof(pid_t));
-
-                }
-            }
-       } 
-        
-        mp = mp->next;
-    }
-}
-
-/*****************************************************
- * 
- * AUTO-MOUNTER THREAD
- * 
- *****************************************************/
-
-static void sigusr1_handler(int signo)
-{
-    // don't need to do anything here
-}
-
-// create a socket for listening to inotify events
-int CreateINotifySocket()
-{
-    // initialize inotify
-    int fd = inotify_init();
-
-    if (fd < 0) {
-        LOG_ERROR("inotify_init failed, %s\n", strerror(errno));
-        return -1;
-    }
-
-    fcntl(fd, F_SETFL, O_NONBLOCK | fcntl(fd, F_GETFL));
-
-    return fd;
-}
-
-
-// create a socket for listening to uevents
-int CreateUEventSocket()
-{
-    struct sockaddr_nl addr;
-    int sz = 64*1024;
-    int fd;
-
-    memset(&addr, 0, sizeof(addr));
-    addr.nl_family = AF_NETLINK;
-    addr.nl_pid = getpid();
-    addr.nl_groups = 0xffffffff;
-
-   fd = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
-    if(fd < 0)
-    {
-        LOG_ERROR("could not create NETLINK_KOBJECT_UEVENT socket\n");
-        return -1;
-    }
-
-    setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &sz, sizeof(sz));
-
-    if(bind(fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
-        LOG_ERROR("could not bind NETLINK_KOBJECT_UEVENT socket\n");
-        close(fd);
-        return -1;
-    }
-
-    return fd;
-}
-
-/*
- * Automounter main event thread.
- * This thread listens for block devices being created and deleted via inotify,
- * and listens for changes in the USB mass storage connected/disconnected via uevents from the 
- * power supply driver.
- * This thread also handles retries and timeouts for requests to mount or unmount a device.
- */
-static void* AutoMountThread(void* arg)
-{
-    int inotify_fd;
-    int uevent_fd;
-    int id;
-    struct sigaction    actions;
-
-    gExcludedPids[1] = getpid();
-
-    memset(&actions, 0, sizeof(actions));
-    sigemptyset(&actions.sa_mask);
-    actions.sa_flags = 0;
-    actions.sa_handler = sigusr1_handler;
-    sigaction(SIGUSR1, &actions, NULL);
-    
-    // initialize inotify
-    inotify_fd = CreateINotifySocket();
-    // watch for files created and deleted in "/dev"
-    inotify_add_watch(inotify_fd, DEVPATH, IN_CREATE|IN_DELETE);
-
-    // initialize uevent watcher
-    uevent_fd = CreateUEventSocket();
-    if (uevent_fd < 0) 
-    {
-        LOG_ERROR("CreateUEventSocket failed, %s\n", strerror(errno));
-        return NULL;
-    }
-    
-    while (1)
-    {
-        struct pollfd fds[2];
-        int timeout, result;
-
-#define INOTIFY_IDX 0
-#define UEVENT_IDX  1
-    
-        fds[INOTIFY_IDX].fd = inotify_fd;
-        fds[INOTIFY_IDX].events = POLLIN;
-        fds[INOTIFY_IDX].revents = 0;
-        fds[UEVENT_IDX].fd = uevent_fd;
-        fds[UEVENT_IDX].events = POLLIN;
-        fds[UEVENT_IDX].revents = 0;
-        
-        // wait for an event or a timeout to occur.
-        // poll() can also return in response to a SIGUSR1 signal
-        timeout = (sRetriesPending ? POLL_TIMEOUT : -1);
-        result = poll(fds, 2, timeout);
-
-        // lock the mutex while we are handling events
-        pthread_mutex_lock(&sMutex);
-
-        // handle inotify notifications for block device creation and deletion
-        if (fds[INOTIFY_IDX].revents == POLLIN)
-        {
-            struct inotify_event    event;
-            char    buffer[512];
-            int length = read(inotify_fd, buffer, sizeof(buffer));
-            int offset = 0;
- 
-            while (length >= (int)sizeof(struct inotify_event))
-            {
-               struct inotify_event* event = (struct inotify_event *)&buffer[offset];
-               
-               if (event->mask == IN_CREATE)
-               {
-                   LOG_MOUNT("/dev/block/%s created\n", event->name);
-                   HandleMediaInserted(event->name);
-               }
-               else if (event->mask == IN_DELETE)
-               {
-                   LOG_MOUNT("/dev/block/%s deleted\n", event->name);
-                   HandleMediaRemoved(event->name);
-               }
-               
-               int size = sizeof(struct inotify_event) + event->len;
-               length -= size;
-               offset += size;
-            }
-        }
-
-        // handle uevent notifications for USB state changes
-        if (fds[UEVENT_IDX].revents == POLLIN)
-        {
-            char buffer[64*1024];
-            int count;
-            
-            count = recv(uevent_fd, buffer, sizeof(buffer), 0);
-            if (count > 0) {
-                char* s = buffer;
-                char* end = s + count;
-                char* type = NULL;
-                char* online = NULL;
-                char* switchName = NULL;
-                char* switchState = NULL;
-                                
-                while (s < end) {
-                    if (!strncmp("POWER_SUPPLY_TYPE=", s, strlen("POWER_SUPPLY_TYPE=")))
-                        type = s + strlen("POWER_SUPPLY_TYPE=");
-                    else if (!strncmp("POWER_SUPPLY_ONLINE=", s, strlen("POWER_SUPPLY_ONLINE=")))
-                        online = s + strlen("POWER_SUPPLY_ONLINE=");                    
-                    else if (!strncmp("SWITCH_NAME=", s, strlen("SWITCH_NAME=")))
-                        switchName = s + strlen("SWITCH_NAME=");                    
-                    else if (!strncmp("SWITCH_STATE=", s, strlen("SWITCH_STATE=")))
-                        switchState = s + strlen("SWITCH_STATE=");                    
-                    s += (strlen(s) + 1);
-                }
-
-                // we use the usb_mass_storage switch state to tell us when USB is online
-                if (switchName && switchState && 
-                        !strcmp(switchName, "usb_mass_storage") && !strcmp(switchState, "online"))
-                {
-                    LOG_MOUNT("USB online\n");
-                    HandleMassStorageOnline(true);
-                }
-                
-                // and we use the power supply state to tell us when USB is offline
-                // we can't rely on the switch for offline detection because we get false positives
-                // when USB is reenumerated by the host.
-                if (type && online && !strcmp(type, "USB") && !strcmp(online, "0"))
-                {
-                    LOG_MOUNT("USB offline\n");
-                    HandleMassStorageOnline(false);
-                }
-            }
-        }
-
-       // handle retries
-       if (sRetriesPending)
-            HandleRetries();
-
-        // done handling events, so unlock the mutex
-        pthread_mutex_unlock(&sMutex);
-    }
-
-    inotify_rm_watch(inotify_fd, id);
-    close(inotify_fd);
-    close(uevent_fd);
-
-    return NULL;
-}
-
-/*****************************************************
- * 
- * THESE FUNCTIONS ARE CALLED FROM THE SERVER THREAD
- * 
- *****************************************************/
-
-// Called to enable or disable USB mass storage support
-void EnableMassStorage(boolean enable)
-{
-    pthread_mutex_lock(&sMutex);
-
-    LOG_MOUNT("EnableMassStorage %s\n", (enable ? "true" : "false"));
-    gMassStorageEnabled = enable;
-    MassStorageStateChanged();
-    pthread_mutex_unlock(&sMutex);
- }
-
-// Called to request that the specified mount point be mounted
-void MountMedia(const char* mountPoint)
-{
-    MountPoint* mp = sMountPointList;
- 
-    LOG_MOUNT("MountMedia(%s)\n", mountPoint);
-   
-    pthread_mutex_lock(&sMutex);
-    while (mp)
-    {
-        if (strcmp(mp->mountPoint, mountPoint) == 0)
-        {
-            if (mp->state == kUnmountingForEject)
-            {
-                // handle the case where we try to remount before we actually unmounted
-                ClearRetries(mp, kMounted);
-            }
-            
-            // don't attempt to mount if mass storage is active
-            if (!MassStorageEnabledForMountPoint(mp))
-                RequestMount(mp);
-        }
-        
-        mp = mp->next;
-    }
-    pthread_mutex_unlock(&sMutex);
- }
-
-// Called to request that the specified mount point be unmounted
-void UnmountMedia(const char* mountPoint)
-{
-    MountPoint* mp = sMountPointList;
-    
-    pthread_mutex_lock(&sMutex);
-    while (mp)
-    {
-        if (strcmp(mp->mountPoint, mountPoint) == 0)
-            RequestUnmount(mp, kUnmountingForEject);
-        
-        mp = mp->next;
-    }
-    pthread_mutex_unlock(&sMutex);
-}
-
-boolean IsMassStorageEnabled()
-{
-    return gMassStorageEnabled;
-}
-
-boolean IsMassStorageConnected()
-{
-    return gMassStorageConnected;
-}
-
-/***********************************************
- * 
- * THESE FUNCTIONS ARE CALLED ONLY AT STARTUP
- * 
- ***********************************************/
- 
-void *AddMountPoint(const char* device, const char* mountPoint, const char * driverStorePath, boolean enableUms)
-{
-    MountPoint* newMountPoint;
-    
-    LOG_MOUNT("AddMountPoint device: %s, mountPoint: %s driverStorePath: %s\n", device, mountPoint, driverStorePath);
-    // add a new MountPoint to the head of our linked list
-    newMountPoint = (MountPoint *)malloc(sizeof(MountPoint));
-    newMountPoint->device = device;
-    newMountPoint->mountPoint = mountPoint;
-    newMountPoint->driverStorePath = driverStorePath;
-    newMountPoint->enableUms = enableUms;
-    newMountPoint->umsActive = false;
-    newMountPoint->state = kUnmounted;
-    newMountPoint->retryCount = 0;
-
-    // add to linked list
-    newMountPoint->next = sMountPointList;
-    sMountPointList = newMountPoint;
-    return newMountPoint;
-}
-
-int AddAsecToMountPoint(void *Mp, const char *name, const char *backing_file, const char *size,
-                        const char *mount_point, const char *crypt)
-{
-    MountPoint *mp = (MountPoint *) Mp;
-    int i;
-
-    for (i = 0; i < ASEC_STORES_MAX; i++) {
-        if (!mp->asecHandles[i])
-            break;   
-    }
-
-    if (i == ASEC_STORES_MAX) {
-        LOG_ERROR("Maximum # of ASEC stores exceeded\n");
-        return -EINVAL;
-    }
-
-    if (!(mp->asecHandles[i] = AsecInit(name, mp->mountPoint, backing_file, size, mount_point, crypt)))
-        return -1;
-
-    return 0;
-}
-static void MountDevices()
-{
-    MountPoint* mp = sMountPointList;
-    while (mp)
-    {
-        RequestMount(mp);
-        mp = mp->next;
-    }
-}
-
-void StartAutoMounter()
-{
-    gExcludedPids[0] = getpid();
-
-    gMassStorageConnected = ReadMassStorageState();
-    LOG_MOUNT(gMassStorageConnected ? "USB online\n" : "USB offline\n");
-
-    MountDevices();
-    pthread_create(&sAutoMountThread, NULL, AutoMountThread, NULL);
-}
diff --git a/mountd/MODULE_LICENSE_APACHE2 b/mountd/MODULE_LICENSE_APACHE2
deleted file mode 100644
index e69de29..0000000
--- a/mountd/MODULE_LICENSE_APACHE2
+++ /dev/null
diff --git a/mountd/NOTICE b/mountd/NOTICE
deleted file mode 100644
index c5b1efa..0000000
--- a/mountd/NOTICE
+++ /dev/null
@@ -1,190 +0,0 @@
-
-   Copyright (c) 2005-2008, The Android Open Source Project
-
-   Licensed under the Apache License, Version 2.0 (the "License");
-   you may not use this file except in compliance with the License.
-
-   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.
-
-
-                                 Apache License
-                           Version 2.0, January 2004
-                        http://www.apache.org/licenses/
-
-   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-   1. Definitions.
-
-      "License" shall mean the terms and conditions for use, reproduction,
-      and distribution as defined by Sections 1 through 9 of this document.
-
-      "Licensor" shall mean the copyright owner or entity authorized by
-      the copyright owner that is granting the License.
-
-      "Legal Entity" shall mean the union of the acting entity and all
-      other entities that control, are controlled by, or are under common
-      control with that entity. For the purposes of this definition,
-      "control" means (i) the power, direct or indirect, to cause the
-      direction or management of such entity, whether by contract or
-      otherwise, or (ii) ownership of fifty percent (50%) or more of the
-      outstanding shares, or (iii) beneficial ownership of such entity.
-
-      "You" (or "Your") shall mean an individual or Legal Entity
-      exercising permissions granted by this License.
-
-      "Source" form shall mean the preferred form for making modifications,
-      including but not limited to software source code, documentation
-      source, and configuration files.
-
-      "Object" form shall mean any form resulting from mechanical
-      transformation or translation of a Source form, including but
-      not limited to compiled object code, generated documentation,
-      and conversions to other media types.
-
-      "Work" shall mean the work of authorship, whether in Source or
-      Object form, made available under the License, as indicated by a
-      copyright notice that is included in or attached to the work
-      (an example is provided in the Appendix below).
-
-      "Derivative Works" shall mean any work, whether in Source or Object
-      form, that is based on (or derived from) the Work and for which the
-      editorial revisions, annotations, elaborations, or other modifications
-      represent, as a whole, an original work of authorship. For the purposes
-      of this License, Derivative Works shall not include works that remain
-      separable from, or merely link (or bind by name) to the interfaces of,
-      the Work and Derivative Works thereof.
-
-      "Contribution" shall mean any work of authorship, including
-      the original version of the Work and any modifications or additions
-      to that Work or Derivative Works thereof, that is intentionally
-      submitted to Licensor for inclusion in the Work by the copyright owner
-      or by an individual or Legal Entity authorized to submit on behalf of
-      the copyright owner. For the purposes of this definition, "submitted"
-      means any form of electronic, verbal, or written communication sent
-      to the Licensor or its representatives, including but not limited to
-      communication on electronic mailing lists, source code control systems,
-      and issue tracking systems that are managed by, or on behalf of, the
-      Licensor for the purpose of discussing and improving the Work, but
-      excluding communication that is conspicuously marked or otherwise
-      designated in writing by the copyright owner as "Not a Contribution."
-
-      "Contributor" shall mean Licensor and any individual or Legal Entity
-      on behalf of whom a Contribution has been received by Licensor and
-      subsequently incorporated within the Work.
-
-   2. Grant of Copyright License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      copyright license to reproduce, prepare Derivative Works of,
-      publicly display, publicly perform, sublicense, and distribute the
-      Work and such Derivative Works in Source or Object form.
-
-   3. Grant of Patent License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      (except as stated in this section) patent license to make, have made,
-      use, offer to sell, sell, import, and otherwise transfer the Work,
-      where such license applies only to those patent claims licensable
-      by such Contributor that are necessarily infringed by their
-      Contribution(s) alone or by combination of their Contribution(s)
-      with the Work to which such Contribution(s) was submitted. If You
-      institute patent litigation against any entity (including a
-      cross-claim or counterclaim in a lawsuit) alleging that the Work
-      or a Contribution incorporated within the Work constitutes direct
-      or contributory patent infringement, then any patent licenses
-      granted to You under this License for that Work shall terminate
-      as of the date such litigation is filed.
-
-   4. Redistribution. You may reproduce and distribute copies of the
-      Work or Derivative Works thereof in any medium, with or without
-      modifications, and in Source or Object form, provided that You
-      meet the following conditions:
-
-      (a) You must give any other recipients of the Work or
-          Derivative Works a copy of this License; and
-
-      (b) You must cause any modified files to carry prominent notices
-          stating that You changed the files; and
-
-      (c) You must retain, in the Source form of any Derivative Works
-          that You distribute, all copyright, patent, trademark, and
-          attribution notices from the Source form of the Work,
-          excluding those notices that do not pertain to any part of
-          the Derivative Works; and
-
-      (d) If the Work includes a "NOTICE" text file as part of its
-          distribution, then any Derivative Works that You distribute must
-          include a readable copy of the attribution notices contained
-          within such NOTICE file, excluding those notices that do not
-          pertain to any part of the Derivative Works, in at least one
-          of the following places: within a NOTICE text file distributed
-          as part of the Derivative Works; within the Source form or
-          documentation, if provided along with the Derivative Works; or,
-          within a display generated by the Derivative Works, if and
-          wherever such third-party notices normally appear. The contents
-          of the NOTICE file are for informational purposes only and
-          do not modify the License. You may add Your own attribution
-          notices within Derivative Works that You distribute, alongside
-          or as an addendum to the NOTICE text from the Work, provided
-          that such additional attribution notices cannot be construed
-          as modifying the License.
-
-      You may add Your own copyright statement to Your modifications and
-      may provide additional or different license terms and conditions
-      for use, reproduction, or distribution of Your modifications, or
-      for any such Derivative Works as a whole, provided Your use,
-      reproduction, and distribution of the Work otherwise complies with
-      the conditions stated in this License.
-
-   5. Submission of Contributions. Unless You explicitly state otherwise,
-      any Contribution intentionally submitted for inclusion in the Work
-      by You to the Licensor shall be under the terms and conditions of
-      this License, without any additional terms or conditions.
-      Notwithstanding the above, nothing herein shall supersede or modify
-      the terms of any separate license agreement you may have executed
-      with Licensor regarding such Contributions.
-
-   6. Trademarks. This License does not grant permission to use the trade
-      names, trademarks, service marks, or product names of the Licensor,
-      except as required for reasonable and customary use in describing the
-      origin of the Work and reproducing the content of the NOTICE file.
-
-   7. Disclaimer of Warranty. Unless required by applicable law or
-      agreed to in writing, Licensor provides the Work (and each
-      Contributor provides its Contributions) on an "AS IS" BASIS,
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-      implied, including, without limitation, any warranties or conditions
-      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
-      PARTICULAR PURPOSE. You are solely responsible for determining the
-      appropriateness of using or redistributing the Work and assume any
-      risks associated with Your exercise of permissions under this License.
-
-   8. Limitation of Liability. In no event and under no legal theory,
-      whether in tort (including negligence), contract, or otherwise,
-      unless required by applicable law (such as deliberate and grossly
-      negligent acts) or agreed to in writing, shall any Contributor be
-      liable to You for damages, including any direct, indirect, special,
-      incidental, or consequential damages of any character arising as a
-      result of this License or out of the use or inability to use the
-      Work (including but not limited to damages for loss of goodwill,
-      work stoppage, computer failure or malfunction, or any and all
-      other commercial damages or losses), even if such Contributor
-      has been advised of the possibility of such damages.
-
-   9. Accepting Warranty or Additional Liability. While redistributing
-      the Work or Derivative Works thereof, You may choose to offer,
-      and charge a fee for, acceptance of support, warranty, indemnity,
-      or other liability obligations and/or rights consistent with this
-      License. However, in accepting such obligations, You may act only
-      on Your own behalf and on Your sole responsibility, not on behalf
-      of any other Contributor, and only if You agree to indemnify,
-      defend, and hold each Contributor harmless for any liability
-      incurred by, or claims asserted against, such Contributor by reason
-      of your accepting any such warranty or additional liability.
-
-   END OF TERMS AND CONDITIONS
-
diff --git a/mountd/ProcessKiller.c b/mountd/ProcessKiller.c
deleted file mode 100644
index e377774..0000000
--- a/mountd/ProcessKiller.c
+++ /dev/null
@@ -1,222 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
-** mountd process killer
-*/
-
-#include "mountd.h"
-
-#include <stdio.h>
-#include <unistd.h>
-#include <string.h>
-#include <fcntl.h>
-#include <dirent.h>
-#include <ctype.h>
-#include <pwd.h>
-#include <stdlib.h>
-#include <poll.h>
-#include <sys/stat.h>
-
-
-static boolean ReadSymLink(const char* path, char* link)
-{
-    struct stat s;
-    int length;
-
-    if (lstat(path, &s) < 0)
-        return false;
-    if ((s.st_mode & S_IFMT) != S_IFLNK)
-        return false;
-   
-    // we have a symlink    
-    length = readlink(path, link, PATH_MAX - 1);
-    if (length <= 0) 
-        return false;
-    link[length] = 0;
-    return true;
-}
-
-static boolean PathMatchesMountPoint(const char* path, const char* mountPoint)
-{
-    int length = strlen(mountPoint);
-    if (length > 1 && strncmp(path, mountPoint, length) == 0)
-    {
-        // we need to do extra checking if mountPoint does not end in a '/'
-        if (mountPoint[length - 1] == '/')
-            return true;
-        // if mountPoint does not have a trailing slash, we need to make sure
-        // there is one in the path to avoid partial matches.
-        return (path[length] == 0 || path[length] == '/');
-    }
-    
-    return false;
-}
-
-static void GetProcessName(int pid, char buffer[PATH_MAX])
-{
-    int fd;
-    sprintf(buffer, "/proc/%d/cmdline", pid);
-    fd = open(buffer, O_RDONLY);
-    if (fd < 0) {
-        strcpy(buffer, "???");
-    } else {
-        int length = read(fd, buffer, PATH_MAX - 1);
-        buffer[length] = 0;
-        close(fd);
-    }
-}
-
-static boolean CheckFileDescriptorSymLinks(int pid, const char* mountPoint)
-{
-    DIR*    dir;
-    struct dirent* de;
-    boolean fileOpen = false;
-    char    path[PATH_MAX];
-    char    link[PATH_MAX];
-    int     parent_length;
-
-    // compute path to process's directory of open files
-    sprintf(path, "/proc/%d/fd", pid);
-    dir = opendir(path);
-    if (!dir)
-        return false;
-
-    // remember length of the path
-    parent_length = strlen(path);
-    // append a trailing '/'
-    path[parent_length++] = '/';
-    
-    while ((de = readdir(dir)) != 0 && !fileOpen) {
-        if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
-            continue;
-        
-        // append the file name, after truncating to parent directory
-        path[parent_length] = 0;
-        strcat(path, de->d_name);
-
-        if (ReadSymLink(path, link) && PathMatchesMountPoint(link, mountPoint))
-        {
-            char    name[PATH_MAX];
-            GetProcessName(pid, name);
-            LOG_ERROR("process %s (%d) has open file %s\n", name, pid, link);
-            fileOpen = true;
-        }
-    }
-
-    closedir(dir);
-    return fileOpen;
-}
-
-static boolean CheckFileMaps(int pid, const char* mountPoint)
-{
-    FILE*   file;
-    char    buffer[PATH_MAX + 100];
-    boolean mapOpen = false;
-
-    sprintf(buffer, "/proc/%d/maps", pid);
-    file = fopen(buffer, "r");
-    if (!file)
-        return false;
-    
-    while (!mapOpen && fgets(buffer, sizeof(buffer), file))
-    {
-        // skip to the path
-        const char* path = strchr(buffer, '/');
-        if (path && PathMatchesMountPoint(path, mountPoint))
-        {
-            char    name[PATH_MAX];
-            GetProcessName(pid, name);
-            LOG_ERROR("process %s (%d) has open file map for %s\n", name, pid, path);
-            mapOpen = true;
-        }
-    }
-    
-    fclose(file);
-    return mapOpen;
-}
-
-static boolean CheckSymLink(int pid, const char* mountPoint, const char* name, const char* message)
-{
-    char    path[PATH_MAX];
-    char    link[PATH_MAX];
-
-    sprintf(path, "/proc/%d/%s", pid, name);
-    if (ReadSymLink(path, link) && PathMatchesMountPoint(link, mountPoint)) 
-    {
-        char    name[PATH_MAX];
-        GetProcessName(pid, name);
-        LOG_ERROR("process %s (%d) has %s in %s\n", name, pid, message, mountPoint);
-        return true;
-    }
-    else
-        return false;
-}
-
-static int get_pid(const char* s)
-{
-    int result = 0;
-    while (*s) {
-        if (!isdigit(*s)) return -1;
-        result = 10 * result + (*s++ - '0');
-    }
-    return result;
-}
-
-// hunt down and kill processes that have files open on the given mount point
-void KillProcessesWithOpenFiles(const char* mountPoint, boolean sigkill, int *excluded, int num_excluded)
-{
-    DIR*    dir;
-    struct dirent* de;
-
-    LOG_ERROR("KillProcessesWithOpenFiles %s\n", mountPoint);
-    dir = opendir("/proc");
-    if (!dir) return;
-
-    while ((de = readdir(dir)) != 0)
-    {
-        boolean killed = false;
-        // does the name look like a process ID?
-        int pid = get_pid(de->d_name);
-        if (pid == -1) continue;
-
-        if (CheckFileDescriptorSymLinks(pid, mountPoint)    // check for open files
-                || CheckFileMaps(pid, mountPoint)           // check for mmap()
-                || CheckSymLink(pid, mountPoint, "cwd", "working directory")    // check working directory
-                || CheckSymLink(pid, mountPoint, "root", "chroot")              // check for chroot()
-                || CheckSymLink(pid, mountPoint, "exe", "executable path")      // check executable path
-            ) 
-        {
-            int i;
-            boolean hit = false;
-
-            for (i = 0; i < num_excluded; i++) {
-                if (pid == excluded[i]) {
-                    LOG_ERROR("I just need a little more TIME captain!\n");
-                    hit = true;
-                    break;
-                }
-            }
-
-            if (!hit) {
-                LOG_ERROR("Killing process %d\n", pid);
-                kill(pid, (sigkill ? SIGKILL : SIGTERM));
-            }
-        }
-    }
-
-    closedir(dir);
-}        
diff --git a/mountd/Server.c b/mountd/Server.c
deleted file mode 100644
index 64459bd..0000000
--- a/mountd/Server.c
+++ /dev/null
@@ -1,313 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
-**	mountd server support
-*/
-
-#include "mountd.h"
-#include "ASEC.h"
-
-#include <cutils/properties.h>
-#include <cutils/sockets.h>
-
-#include <pthread.h>
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <string.h>
-#include <sys/socket.h>
-
-#include <private/android_filesystem_config.h>
-
-
-// current client file descriptor
-static int sFD = -1;
-
-// to synchronize writing to client
-static pthread_mutex_t sWriteMutex = PTHREAD_MUTEX_INITIALIZER;
-
-// path for media that failed to mount before the runtime is connected
-static char* sDeferredUnmountableMediaPath = NULL;
-
-// last asec msg before the runtime was connected
-static char* sAsecDeferredMessage = NULL;
-static char* sAsecDeferredArgument = NULL;
-
-static int Write(const char* message)
-{
-    int result = -1;
-
-    pthread_mutex_lock(&sWriteMutex);
-    
-    LOG_SERVER("Write: %s\n", message);
-    if (sFD >= 0)
-        result = write(sFD, message, strlen(message) + 1);
-
-    pthread_mutex_unlock(&sWriteMutex); 
-    
-    return result;
-}
-
-static int Write2(const char* message, const char* data)
-{
-    int result = -1;
-
-    char* buffer = (char *)alloca(strlen(message) + strlen(data) + 1);
-    if (!buffer)
-    {
-        LOG_ERROR("alloca failed in Write2\n");
-        return -1;
-    }
-
-    strcpy(buffer, message);
-    strcat(buffer, data);
-    return Write(buffer);
-}
-
-static void SendStatus()
-{
-    Write(IsMassStorageConnected() ? MOUNTD_UMS_CONNECTED : MOUNTD_UMS_DISCONNECTED);
-    Write(IsMassStorageEnabled() ? MOUNTD_UMS_ENABLED : MOUNTD_UMS_DISABLED);
-}
-
-static void DoCommand(const char* command)
-{
-    LOG_SERVER("DoCommand %s\n", command);
-    
-    if (strcmp(command, MOUNTD_ENABLE_UMS) == 0)
-    {
-        EnableMassStorage(true);
-        Write(MOUNTD_UMS_ENABLED);
-     }
-    else if (strcmp(command, MOUNTD_DISABLE_UMS) == 0) 
-    {
-        EnableMassStorage(false);
-        Write(MOUNTD_UMS_DISABLED);
-    }
-    else if (strcmp(command, MOUNTD_SEND_STATUS) == 0)
-    {
-        SendStatus();
-    }
-    else if (strncmp(command, MOUNTD_MOUNT_MEDIA, strlen(MOUNTD_MOUNT_MEDIA)) == 0)
-    {
-        const char* path = command + strlen(MOUNTD_MOUNT_MEDIA);
-        MountMedia(path);
-    }
-    else if (strncmp(command, MOUNTD_EJECT_MEDIA, strlen(MOUNTD_EJECT_MEDIA)) == 0)
-    {
-        const char* path = command + strlen(MOUNTD_EJECT_MEDIA);
-        UnmountMedia(path);
-    } 
-    else if (strncmp(command, ASEC_CMD_ENABLE, strlen(ASEC_CMD_ENABLE)) == 0) {
-        LOG_ASEC("Got ASEC_CMD_ENABLE\n");
-	// XXX: SAN: Impliment
-    }
-    else if (strncmp(command, ASEC_CMD_DISABLE, strlen(ASEC_CMD_DISABLE)) == 0) {
-        LOG_ASEC("Got ASEC_CMD_DISABLE\n");
-	// XXX: SAN: Impliment
-    }
-    else if (strncmp(command, ASEC_CMD_SEND_STATUS, strlen(ASEC_CMD_SEND_STATUS)) == 0) {
-        LOG_ASEC("Got ASEC_CMD_SEND_STATUS\n");
-	// XXX: SAN: Impliment
-    }
-    else
-        LOGE("unknown command %s\n", command);
-}
-
-int RunServer()
-{
-    int socket = android_get_control_socket(MOUNTD_SOCKET);
-    if (socket < 0) {
-        LOGE("Obtaining file descriptor for socket '%s' failed: %s",
-             MOUNTD_SOCKET, strerror(errno));
-        return -1;
-    }
-
-    if (listen(socket, 4) < 0) {
-        LOGE("Unable to listen on file descriptor '%d' for socket '%s': %s",
-             socket, MOUNTD_SOCKET, strerror(errno));
-        return -1;
-    }
-
-    while (1)
-    {
-        struct sockaddr addr;
-        socklen_t alen;
-        struct ucred cred;
-        socklen_t size;
-        
-        alen = sizeof(addr);
-        sFD = accept(socket, &addr, &alen);
-        if (sFD < 0)
-            continue;
-            
-        if (sDeferredUnmountableMediaPath) {
-            NotifyMediaState(sDeferredUnmountableMediaPath, MEDIA_UNMOUNTABLE, false);
-            free(sDeferredUnmountableMediaPath);
-            sDeferredUnmountableMediaPath = NULL;
-        }
-
-        if (sAsecDeferredMessage) {
-    
-            if (Write2(sAsecDeferredMessage, sAsecDeferredArgument) < 0)
-                LOG_ERROR("Failed to deliver deferred ASEC msg to framework\n");
-            free(sAsecDeferredMessage);
-            free(sAsecDeferredArgument);
-            sAsecDeferredMessage = sAsecDeferredArgument = NULL;
-        }
-
-        while (1)
-        {    
-            char    buffer[101];
-            int result = read(sFD, buffer, sizeof(buffer) - 1);
-            if (result > 0)
-            {
-                int start = 0;
-                int i;
-                // command should be zero terminated, but just in case
-                buffer[result] = 0;
-                for (i = 0; i < result; i++) 
-                {
-                    if (buffer[i] == 0) 
-                    {
-                        DoCommand(buffer + start);
-                        start = i + 1;
-                    }                   
-                }
-            }
-            else
-            {
-                close(sFD);
-                sFD = -1;
-                break;
-            }
-        }
-    }  
-
-    // should never get here
-    return 0;
-}
-
-void SendMassStorageConnected(boolean connected)
-{
-    Write(connected ? MOUNTD_UMS_CONNECTED : MOUNTD_UMS_DISCONNECTED);
-}
-
-void SendUnmountRequest(const char* path)
-{
-    Write2(MOUNTD_REQUEST_EJECT, path);
-}
-
-void NotifyAsecState(AsecState state, const char *argument)
-{
-    const char *event = NULL;
-    const char *status = NULL;
-    boolean deferr = true;;
-
-    switch (state) {
-        case ASEC_DISABLED:
-            event = ASEC_EVENT_DISABLED;
-            status = ASEC_STATUS_DISABLED;
-            break;
-        case ASEC_AVAILABLE:
-            event = ASEC_EVENT_AVAILABLE;
-            status = ASEC_STATUS_AVAILABLE;
-            break;
-        case ASEC_BUSY:
-            event = ASEC_EVENT_BUSY;
-            status = ASEC_STATUS_BUSY;
-            deferr = false;
-            break;
-        case ASEC_FAILED_INTERR:
-            event = ASEC_EVENT_FAILED_INTERR;
-            status = ASEC_STATUS_FAILED_INTERR;
-            break;
-        case ASEC_FAILED_NOMEDIA:
-            event = ASEC_EVENT_FAILED_NOMEDIA;
-            status = ASEC_STATUS_FAILED_NOMEDIA;
-            break;
-        case ASEC_FAILED_BADMEDIA:
-            event = ASEC_EVENT_FAILED_BADMEDIA;
-            status = ASEC_STATUS_FAILED_BADMEDIA;
-            break;
-        case ASEC_FAILED_BADKEY:
-            event = ASEC_EVENT_FAILED_BADKEY;
-            status = ASEC_STATUS_FAILED_BADKEY;
-            break;
-        default:
-            LOG_ERROR("unknown AsecState %d in NotifyAsecState\n", state);
-            return;
-    }
-
-    property_set(ASEC_STATUS, status);
-
-    int result = Write2(event, argument);
-    if ((result < 0) && deferr) {
-        if (sAsecDeferredMessage) 
-            free(sAsecDeferredMessage);
-        sAsecDeferredMessage = strdup(event);
-        if (sAsecDeferredArgument)
-            free(sAsecDeferredArgument);
-        sAsecDeferredArgument = strdup(argument);
-        LOG_ASEC("Deferring event '%s' arg '%s' until framework connects\n", event, argument);
-    }
-}
-
-void NotifyMediaState(const char* path, MediaState state, boolean readOnly)
-{
-    const char* event = NULL;
-    const char* propertyValue = NULL;
-    
-    switch (state) {
-        case MEDIA_REMOVED:
-            event = MOUNTD_MEDIA_REMOVED;
-            propertyValue = EXTERNAL_STORAGE_REMOVED;
-            break;
-        case MEDIA_UNMOUNTED:
-            event = MOUNTD_MEDIA_UNMOUNTED;
-            propertyValue = EXTERNAL_STORAGE_UNMOUNTED;
-            break;
-        case MEDIA_MOUNTED:
-            event = (readOnly ? MOUNTD_MEDIA_MOUNTED_READ_ONLY : MOUNTD_MEDIA_MOUNTED);
-             propertyValue = (readOnly ? EXTERNAL_STORAGE_MOUNTED_READ_ONLY : EXTERNAL_STORAGE_MOUNTED);
-           break;
-        case MEDIA_SHARED:
-            event = MOUNTD_MEDIA_SHARED;
-            propertyValue = EXTERNAL_STORAGE_SHARED;
-            break;
-        case MEDIA_BAD_REMOVAL:
-            event = MOUNTD_MEDIA_BAD_REMOVAL;
-            propertyValue = EXTERNAL_STORAGE_BAD_REMOVAL;
-            break;
-        case MEDIA_UNMOUNTABLE:
-            event = MOUNTD_MEDIA_UNMOUNTABLE;
-            propertyValue = EXTERNAL_STORAGE_UNMOUNTABLE;
-            break;
-        default:
-            LOG_ERROR("unknown MediaState %d in NotifyMediaState\n", state);
-            return;
-    }
-    
-    property_set(EXTERNAL_STORAGE_STATE, propertyValue);
-    int result = Write2(event, path);
-    if (result < 0 && state == MEDIA_UNMOUNTABLE) {
-    
-        // if we cannot communicate with the runtime, defer this message until the runtime is available
-        sDeferredUnmountableMediaPath = strdup(path);
-    }
-}
diff --git a/mountd/logwrapper.c b/mountd/logwrapper.c
deleted file mode 100644
index 69606ab..0000000
--- a/mountd/logwrapper.c
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <string.h>
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <errno.h>
-#include <fcntl.h>
-
-#include "private/android_filesystem_config.h"
-#include "cutils/log.h"
-
-int parent(const char *tag, int parent_read) {
-    int status;
-    char buffer[4096];
-
-    int a = 0;  // start index of unprocessed data
-    int b = 0;  // end index of unprocessed data
-    int sz;
-    while ((sz = read(parent_read, &buffer[b], sizeof(buffer) - 1 - b)) > 0) {
-
-        sz += b;
-        // Log one line at a time
-        for (b = 0; b < sz; b++) {
-            if (buffer[b] == '\r') {
-                buffer[b] = '\0';
-            } else if (buffer[b] == '\n') {
-                buffer[b] = '\0';
-                LOG(LOG_INFO, tag, &buffer[a]);
-                a = b + 1;
-            }
-        }
-
-        if (a == 0 && b == sizeof(buffer) - 1) {
-            // buffer is full, flush
-            buffer[b] = '\0';
-            LOG(LOG_INFO, tag, &buffer[a]);
-            b = 0;
-        } else if (a != b) {
-            // Keep left-overs
-            b -= a;
-            memmove(buffer, &buffer[a], b);
-            a = 0;
-        } else {
-            a = 0;
-            b = 0;
-        }
-
-    }
-    // Flush remaining data
-    if (a != b) {
-        buffer[b] = '\0';
-        LOG(LOG_INFO, tag, &buffer[a]);
-    }
-    status = 0xAAAA;
-    if (wait(&status) != -1) {  // Wait for child
-        if (WIFEXITED(status)) {
-            LOG(LOG_INFO, "logwrapper", "%s terminated by exit(%d)", tag,
-                    WEXITSTATUS(status));
-            return WEXITSTATUS(status);
-        } else if (WIFSIGNALED(status))
-            LOG(LOG_INFO, "logwrapper", "%s terminated by signal %d", tag,
-                    WTERMSIG(status));
-        else if (WIFSTOPPED(status))
-            LOG(LOG_INFO, "logwrapper", "%s stopped by signal %d", tag,
-                    WSTOPSIG(status));
-    } else
-        LOG(LOG_INFO, "logwrapper", "%s wait() failed: %s (%d)", tag,
-                strerror(errno), errno);
-    return -EAGAIN;
-}
-
-void child(int argc, char* argv[]) {
-    // create null terminated argv_child array
-    char* argv_child[argc + 1];
-    memcpy(argv_child, argv, argc * sizeof(char *));
-    argv_child[argc] = NULL;
-
-    // XXX: PROTECT FROM VIKING KILLER
-    if (execvp(argv_child[0], argv_child)) {
-        LOG(LOG_ERROR, "logwrapper",
-            "executing %s failed: %s\n", argv_child[0], strerror(errno));
-        exit(-1);
-    }
-}
-
-int logwrap(int argc, char* argv[])
-{
-    pid_t pid;
-
-    int parent_ptty;
-    int child_ptty;
-    char *child_devname = NULL;
-
-    /* Use ptty instead of socketpair so that STDOUT is not buffered */
-    parent_ptty = open("/dev/ptmx", O_RDWR);
-    if (parent_ptty < 0) {
-	LOG(LOG_ERROR, "logwrapper", "Cannot create parent ptty\n");
-	return -errno;
-    }
-
-    if (grantpt(parent_ptty) || unlockpt(parent_ptty) ||
-            ((child_devname = (char*)ptsname(parent_ptty)) == 0)) {
-	LOG(LOG_ERROR, "logwrapper", "Problem with /dev/ptmx\n");
-	return -1;
-    }
-
-    pid = fork();
-    if (pid < 0) {
-	LOG(LOG_ERROR, "logwrapper", "Failed to fork\n");
-        return -errno;
-    } else if (pid == 0) {
-        child_ptty = open(child_devname, O_RDWR);
-        if (child_ptty < 0) {
-	    LOG(LOG_ERROR, "logwrapper", "Problem with child ptty\n");
-            return -errno;
-        }
-
-        // redirect stdout and stderr
-        close(parent_ptty);
-        dup2(child_ptty, 1);
-        dup2(child_ptty, 2);
-        close(child_ptty);
-
-        child(argc, argv);
-    } else {
-        // switch user and group to "log"
-        // this may fail if we are not root, 
-        // but in that case switching user/group is unnecessary 
-        
-      //  setgid(AID_LOG);
-      //  setuid(AID_LOG);
-
-        return parent(argv[0], parent_ptty);
-    }
-
-    return 0;
-}
diff --git a/mountd/mountd.c b/mountd/mountd.c
deleted file mode 100644
index 27ec8de..0000000
--- a/mountd/mountd.c
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
-**    mountd main program
-*/
-
-#include "mountd.h"
-
-#include <cutils/config_utils.h>
-#include <cutils/cpu_info.h>
-#include <cutils/properties.h>
-
-#include <sys/mount.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <linux/capability.h>
-#include <linux/prctl.h>
-
-#include <private/android_filesystem_config.h>
-
-#ifdef MOUNTD_LOG
-FILE*    logFile;
-#endif
-
-struct asec_cfg {
-    const char *name;
-    const char *backing_file;
-    const char *size;
-    const char *mount_point;
-    const char *crypt;
-};
-
-static int ProcessAsecData(cnode *node, struct asec_cfg *stores, int idx)
-{
-    cnode *child = node->first_child;
-    const char *name = NULL;
-    const char *file = NULL;
-    const char *size = NULL;
-    const char *mp = NULL;
-    const char *crypt = NULL;
-
-    LOG_ASEC("ProcessAsecData(%s, %p, %d)\n", node->name, stores, idx);
-
-    while (child) {
-        if (!strcmp(child->name, "name"))
-            name = child->value;
-        else if (!strcmp(child->name, "backing_file"))
-            file = child->value;
-        else if (!strcmp(child->name, "size"))
-            size = child->value;
-        else if (!strcmp(child->name, "mount_point"))
-            mp = child->value;
-        else if (!strcmp(child->name, "crypt"))
-            crypt = child->value;
-        child = child->next;
-    }
-
-    if (!name || !file || !size || !mp || !crypt) {
-        LOG_ERROR("Missing required token from config. Skipping ASEC volume\n");
-        return -1;
-    } else if (idx == ASEC_STORES_MAX) {
-        LOG_ERROR("Maximum # of ASEC stores already defined\n");
-        return -1;
-    }
-
-    stores[idx].name = name;
-    stores[idx].backing_file = file;
-    stores[idx].size = size;
-    stores[idx].mount_point = mp;
-    stores[idx].crypt = crypt;
-    return ++idx;
-}
-
-static void ReadConfigFile(const char* path)
-{
-    cnode* root = config_node("", "");
-    cnode* node;
-
-    config_load_file(root, path);
-    node = root->first_child;
-
-    while (node)
-    {
-        if (strcmp(node->name, "mount") == 0)
-        {
-            const char* block_device = NULL;
-            const char* mount_point = NULL;
-            const char* driver_store_path = NULL;
-            boolean enable_ums = false;
-            cnode* child = node->first_child;
-            struct asec_cfg asec_stores[ASEC_STORES_MAX];
-            int    asec_idx = 0;
-
-            memset(asec_stores, 0, sizeof(asec_stores));
-
-            while (child)
-            {
-                const char* name = child->name;
-                const char* value = child->value;
-
-                if (!strncmp(name, "asec_", 5)) {
-                     int rc = ProcessAsecData(child, asec_stores, asec_idx);
-                     if (rc < 0) {
-                         LOG_ERROR("Error processing ASEC cfg data\n");
-                     } else
-                         asec_idx = rc;
-                } else if (strcmp(name, "block_device") == 0)
-                    block_device = value;
-                else if (strcmp(name, "mount_point") == 0)
-                    mount_point = value;
-                else if (strcmp(name, "driver_store_path") == 0)
-                    driver_store_path = value;
-                else if (strcmp(name, "enable_ums") == 0 &&
-                        strcmp(value, "true") == 0)
-                    enable_ums = true;
-                
-                child = child->next;
-            }
-
-            // mount point and removable fields are optional
-            if (block_device && mount_point)
-            {
-                void *mp = AddMountPoint(block_device, mount_point, driver_store_path, enable_ums);
-                int i;
-
-                for (i = 0; i < asec_idx; i++) {
-                    AddAsecToMountPoint(mp, asec_stores[i].name, asec_stores[i].backing_file,
-                                        asec_stores[i].size, asec_stores[i].mount_point,
-                                        asec_stores[i].crypt);
-                }
-            }
-        }
-            
-        node = node->next;
-    }
-}
-
-int main(int argc, char* argv[])
-{
-    const char*     configPath = "/system/etc/mountd.conf";
-    int             i;    
-
-    for (i = 1; i < argc; i++)
-    {
-        const char* arg = argv[i];
-        
-        if (strcmp(arg, "-f") == 0)
-        {
-            if (i < argc - 1)
-                configPath = argv[++i];
-        }
-    }
-        
-    ReadConfigFile(configPath);
-    StartAutoMounter();
-    return RunServer();
-}
diff --git a/mountd/mountd.h b/mountd/mountd.h
deleted file mode 100644
index c4bc91d..0000000
--- a/mountd/mountd.h
+++ /dev/null
@@ -1,190 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef MOUNTD_H__
-#define MOUNTD_H__
-
-#define LOG_TAG "mountd"
-#include "cutils/log.h"
-
-#include "ASEC.h"
-
-typedef int boolean;
-enum {
-    false = 0,
-    true = 1
-};
-
-#define WEXITSTATUS(status) (((status) & 0xff00) >> 8)
-
-// Set this for logging error messages
-#define ENABLE_LOG_ERROR
-
-// set this to log automounter events
-#define ENABLE_LOG_MOUNT
-
-// set this to log server events
-//#define ENABLE_LOG_SERVER
-
-// set this to log ASEC events
-#define ENABLE_LOG_ASEC
-
-#ifdef ENABLE_LOG_ERROR
-#define LOG_ERROR(fmt, args...) \
-    { LOGE(fmt , ## args); }
-#else
-#define LOG_ERROR(fmt, args...) \
-    do { } while (0)
-#endif /* ENABLE_LOG_ERROR */
-
-#ifdef ENABLE_LOG_MOUNT
-#define LOG_MOUNT(fmt, args...) \
-    { LOGD(fmt , ## args); }
-#else
-#define LOG_MOUNT(fmt, args...) \
-    do { } while (0)
-#endif /* ENABLE_LOG_MOUNT */
-
-#ifdef ENABLE_LOG_SERVER
-#define LOG_SERVER(fmt, args...) \
-    { LOGD(fmt , ## args); }
-#else
-#define LOG_SERVER(fmt, args...) \
-    do { } while (0)
-#endif /* ENABLE_LOG_SERVER */
-
-#ifdef ENABLE_LOG_ASEC
-#define LOG_ASEC(fmt, args...) \
-    { LOGD(fmt , ## args); }
-#else
-#define LOG_ASEC(fmt, args...) \
-    do { } while (0)
-#endif /* ENABLE_LOG_ASEC */
-
-
-typedef enum MediaState {
-    // no media in SD card slot
-    MEDIA_REMOVED,
-    
-    // media in SD card slot, but not mounted
-    MEDIA_UNMOUNTED,
-    
-    // media in SD card slot and mounted at its mount point
-    MEDIA_MOUNTED,
-    
-    // media in SD card slot, unmounted, and shared as a mass storage device
-    MEDIA_SHARED,
-    
-    // media was removed from SD card slot, but mount point was not unmounted
-    // this state is cleared after the mount point is unmounted
-    MEDIA_BAD_REMOVAL,
-
-    // media in SD card slot could not be mounted (corrupt file system?)
-    MEDIA_UNMOUNTABLE,
-} MediaState;
-
-// socket name for connecting to mountd
-#define MOUNTD_SOCKET         "mountd"
-
-// mountd commands
-// these must match the corresponding strings in //device/java/android/android/os/UsbListener.java
-#define MOUNTD_ENABLE_UMS     "enable_ums"
-#define MOUNTD_DISABLE_UMS    "disable_ums"
-#define MOUNTD_SEND_STATUS    "send_status"
-
-// these commands should contain a mount point following the colon
-#define MOUNTD_MOUNT_MEDIA  "mount_media:"
-#define MOUNTD_EJECT_MEDIA  "eject_media:"
-
-// mountd events
-// these must match the corresponding strings in //device/java/android/android/os/UsbListener.java
-#define MOUNTD_UMS_ENABLED              "ums_enabled"
-#define MOUNTD_UMS_DISABLED             "ums_disabled"
-#define MOUNTD_UMS_CONNECTED            "ums_connected"
-#define MOUNTD_UMS_DISCONNECTED         "ums_disconnected"
-
-// these events correspond to the states in the MediaState enum.
-// a path to the mount point follows the colon.
-#define MOUNTD_MEDIA_REMOVED            "media_removed:"
-#define MOUNTD_MEDIA_UNMOUNTED        	"media_unmounted:"
-#define MOUNTD_MEDIA_MOUNTED          	"media_mounted:"
-#define MOUNTD_MEDIA_MOUNTED_READ_ONLY  "media_mounted_ro:"
-#define MOUNTD_MEDIA_SHARED             "media_shared:"
-#define MOUNTD_MEDIA_BAD_REMOVAL        "media_bad_removal:"
-#define MOUNTD_MEDIA_UNMOUNTABLE        "media_unmountable:"
-
-// this event sent to request unmount for media mount point
-#define MOUNTD_REQUEST_EJECT            "request_eject:"
-
-// system properties
-// these must match the corresponding strings in //device/java/android/android/os/Environment.java
-#define EXTERNAL_STORAGE_STATE          "EXTERNAL_STORAGE_STATE"
-#define EXTERNAL_STORAGE_REMOVED        "removed"
-#define EXTERNAL_STORAGE_UNMOUNTED      "unmounted"
-#define EXTERNAL_STORAGE_MOUNTED        "mounted"
-#define EXTERNAL_STORAGE_MOUNTED_READ_ONLY        "mounted_ro"
-#define EXTERNAL_STORAGE_SHARED         "shared"
-#define EXTERNAL_STORAGE_BAD_REMOVAL    "bad_removal"
-#define EXTERNAL_STORAGE_UNMOUNTABLE    "unmountable"
-
-// AutoMount.c
-
-boolean IsMassStorageEnabled();
-boolean IsMassStorageConnected();
-
-void MountMedia(const char* mountPoint);
-void UnmountMedia(const char* mountPoint);
-void EnableMassStorage(boolean enable);
-
-// call this before StartAutoMounter() to add a mount point to monitor
-void *AddMountPoint(const char* device, const char* mountPoint, const char* driverStorePath,
-                    boolean enableUms);
-
-int AddAsecToMountPoint(void *Mp, const char *name, const char *backing_file,
-                        const char *size, const char *mount_point, const char *crypt);
-
-// start automounter thread
-void StartAutoMounter();
-
-// check /proc/mounts for mounted file systems, and notify mount or unmount for any that are in our automount list
-void NotifyExistingMounts();
-
-
-// ASEC.c
-
-void *AsecInit(const char *Name, const char *SrcPath, const char *BackingFile,
-               const char *Size, const char *DstPath, const char *Crypt);
-int AsecStart(void *Handle);
-int AsecStop(void *Handle);
-void AsecDeinit(void *Handle);
-boolean AsecIsStarted(void *Handle);
-const char *AsecMountPoint(void *Handle);
-
-// ProcessKiller.c
-
-void KillProcessesWithOpenFiles(const char* mountPoint, boolean sigkill, pid_t *excluded, int num_excluded);
-
-// logwrapper.c
-int logwrap(int argc, char* argv[]);
-
-// Server.c
-
-int RunServer();
-void SendMassStorageConnected(boolean connected); 
-void SendUnmountRequest(const char* path);
-void NotifyMediaState(const char* path, MediaState state, boolean readOnly);
-void NotifyAsecState(AsecState state, const char *argument);
-#endif // MOUNTD_H__
diff --git a/nexus/Android.mk b/nexus/Android.mk
new file mode 100644
index 0000000..bd4e3d4
--- /dev/null
+++ b/nexus/Android.mk
@@ -0,0 +1,53 @@
+BUILD_NEXUS := false
+ifeq ($(BUILD_NEXUS),true)
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:=                          \
+                  main.cpp                 \
+                  NetworkManager.cpp       \
+                  CommandListener.cpp      \
+                  Controller.cpp           \
+                  WifiController.cpp       \
+                  LoopController.cpp       \
+                  NexusCommand.cpp         \
+                  TiwlanWifiController.cpp \
+                  Supplicant.cpp           \
+                  SupplicantEvent.cpp      \
+                  SupplicantListener.cpp   \
+                  VpnController.cpp        \
+                  ScanResult.cpp           \
+                  WifiScanner.cpp          \
+                  WifiNetwork.cpp          \
+                  OpenVpnController.cpp    \
+                  InterfaceConfig.cpp      \
+                  PropertyManager.cpp      \
+                  SupplicantState.cpp 
+
+LOCAL_MODULE:= nexus
+
+LOCAL_C_INCLUDES := $(KERNEL_HEADERS) -I../../../frameworks/base/include/
+
+LOCAL_CFLAGS := 
+
+LOCAL_SHARED_LIBRARIES := libsysutils libwpa_client
+
+include $(BUILD_EXECUTABLE)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES:=          \
+                  nexctl.c \
+
+LOCAL_MODULE:= nexctl
+
+LOCAL_C_INCLUDES := $(KERNEL_HEADERS)
+
+LOCAL_CFLAGS := 
+
+LOCAL_SHARED_LIBRARIES := libcutils
+
+include $(BUILD_EXECUTABLE)
+
+endif # ifeq ($(BUILD_NEXUS),true)
diff --git a/nexus/CommandListener.cpp b/nexus/CommandListener.cpp
new file mode 100644
index 0000000..e8de7f5
--- /dev/null
+++ b/nexus/CommandListener.cpp
@@ -0,0 +1,245 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdlib.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <errno.h>
+
+#define LOG_TAG "CommandListener"
+#include <cutils/log.h>
+
+#include <sysutils/SocketClient.h>
+
+#include "CommandListener.h"
+#include "Controller.h"
+#include "Property.h"
+#include "NetworkManager.h"
+#include "WifiController.h"
+#include "VpnController.h"
+#include "ErrorCode.h"
+
+CommandListener::CommandListener() :
+                 FrameworkListener("nexus") {
+    registerCmd(new WifiScanResultsCmd());
+    registerCmd(new WifiListNetworksCmd());
+    registerCmd(new WifiCreateNetworkCmd());
+    registerCmd(new WifiRemoveNetworkCmd());
+
+    registerCmd(new GetCmd());
+    registerCmd(new SetCmd());
+    registerCmd(new ListCmd());
+}
+
+/* -------------
+ * Wifi Commands
+ * ------------ */
+
+CommandListener::WifiCreateNetworkCmd::WifiCreateNetworkCmd() :
+                 NexusCommand("wifi_create_network") {
+}
+
+int CommandListener::WifiCreateNetworkCmd::runCommand(SocketClient *cli, char *data) {
+    NetworkManager *nm = NetworkManager::Instance();
+    WifiController *wc = (WifiController *) nm->findController("WIFI");
+    WifiNetwork *wn;
+
+    if (!(wn = wc->createNetwork()))
+        cli->sendMsg(ErrorCode::OperationFailed, "Failed to create network", true);
+    else {
+        char tmp[128];
+        sprintf(tmp, "Created network id %d.", wn->getNetworkId());
+        cli->sendMsg(ErrorCode::CommandOkay, tmp, false);
+    }
+    return 0;
+}
+
+CommandListener::WifiRemoveNetworkCmd::WifiRemoveNetworkCmd() :
+                 NexusCommand("wifi_remove_network") {
+}
+
+int CommandListener::WifiRemoveNetworkCmd::runCommand(SocketClient *cli, char *data) {
+    NetworkManager *nm = NetworkManager::Instance();
+    WifiController *wc = (WifiController *) nm->findController("WIFI");
+
+    if (wc->removeNetwork(atoi(data)))
+        cli->sendMsg(ErrorCode::OperationFailed, "Failed to remove network", true);
+    else {
+        cli->sendMsg(ErrorCode::CommandOkay, "Network removed.", false);
+    }
+    return 0;
+}
+
+CommandListener::WifiScanResultsCmd::WifiScanResultsCmd() :
+                 NexusCommand("wifi_scan_results") {
+}
+
+int CommandListener::WifiScanResultsCmd::runCommand(SocketClient *cli, char *data) {
+    NetworkManager *nm = NetworkManager::Instance();
+    WifiController *wc = (WifiController *) nm->findController("WIFI");
+
+    ScanResultCollection *src = wc->createScanResults();
+    ScanResultCollection::iterator it;
+    char buffer[256];
+
+    for(it = src->begin(); it != src->end(); ++it) {
+        sprintf(buffer, "%s:%u:%d:%s:%s",
+                (*it)->getBssid(), (*it)->getFreq(), (*it)->getLevel(),
+                (*it)->getFlags(), (*it)->getSsid());
+        cli->sendMsg(ErrorCode::WifiScanResult, buffer, false);
+        delete (*it);
+        it = src->erase(it);
+    }
+
+    delete src;
+    cli->sendMsg(ErrorCode::CommandOkay, "Scan results complete.", false);
+    return 0;
+}
+
+CommandListener::WifiListNetworksCmd::WifiListNetworksCmd() :
+                 NexusCommand("wifi_list_networks") {
+}
+
+int CommandListener::WifiListNetworksCmd::runCommand(SocketClient *cli, char *data) {
+    NetworkManager *nm = NetworkManager::Instance();
+    WifiController *wc = (WifiController *) nm->findController("WIFI");
+
+    WifiNetworkCollection *src = wc->createNetworkList();
+    WifiNetworkCollection::iterator it;
+    char buffer[256];
+
+    for(it = src->begin(); it != src->end(); ++it) {
+        sprintf(buffer, "%d:%s", (*it)->getNetworkId(), (*it)->getSsid());
+        cli->sendMsg(ErrorCode::WifiNetworkList, buffer, false);
+        delete (*it);
+    }
+
+    delete src;
+    cli->sendMsg(ErrorCode::CommandOkay, "Network listing complete.", false);
+    return 0;
+}
+
+/* ------------
+ * Vpn Commands
+ * ------------ */
+
+/* ----------------
+ * Generic Commands
+ * ---------------- */
+CommandListener::GetCmd::GetCmd() :
+                 NexusCommand("get") {
+}
+
+int CommandListener::GetCmd::runCommand(SocketClient *cli, char *data) {
+    char *next = data;
+    char *propname;
+
+    if (!(propname = strsep(&next, ":")))
+        goto out_inval;
+
+    char pb[Property::NameMaxSize + 6];
+    snprintf(pb, sizeof(pb), "%s:", propname);
+
+    if (!NetworkManager::Instance()->getPropMngr()->get(propname,
+                                                        &pb[strlen(pb)],
+                                                        sizeof(pb) - strlen(pb))) {
+        goto out_inval;
+    }
+
+    cli->sendMsg(ErrorCode::PropertyRead, pb, false);
+
+    cli->sendMsg(ErrorCode::CommandOkay, "Property read.", false);
+    return 0;
+out_inval:
+    errno = EINVAL;
+    cli->sendMsg(ErrorCode::CommandParameterError, "Failed to read property.", true);
+    return 0;
+}
+
+CommandListener::SetCmd::SetCmd() :
+                 NexusCommand("set") {
+}
+
+int CommandListener::SetCmd::runCommand(SocketClient *cli, char *data) {
+    char *bword;
+    char *last;
+    char propname[Property::NameMaxSize];
+    char propval[Property::ValueMaxSize];
+
+    if (!(bword = strtok_r(data, ":", &last)))
+        goto out_inval;
+
+    strncpy(propname, bword, sizeof(propname));
+
+    if (!(bword = strtok_r(NULL, ":", &last)))
+        goto out_inval;
+
+    strncpy(propval, bword, sizeof(propval));
+
+    if (NetworkManager::Instance()->getPropMngr()->set(propname, propval))
+        goto out_inval;
+
+    cli->sendMsg(ErrorCode::CommandOkay, "Property set.", false);
+    return 0;
+
+out_inval:
+    errno = EINVAL;
+    cli->sendMsg(ErrorCode::CommandParameterError, "Failed to set property.", true);
+    return 0;
+}
+
+CommandListener::ListCmd::ListCmd() :
+                 NexusCommand("list") {
+}
+
+int CommandListener::ListCmd::runCommand(SocketClient *cli, char *data) {
+    android::List<char *> *pc;
+
+    if (!(pc = NetworkManager::Instance()->getPropMngr()->createPropertyList())) {
+        errno = ENODATA;
+        cli->sendMsg(ErrorCode::CommandParameterError, "Failed to list properties.", true);
+        return 0;
+    }
+
+    android::List<char *>::iterator it;
+
+    for (it = pc->begin(); it != pc->end(); ++it) {
+        char p_v[Property::ValueMaxSize];
+
+        if (!NetworkManager::Instance()->getPropMngr()->get((*it),
+                                                            p_v,
+                                                            sizeof(p_v))) {
+            LOGW("Failed to get %s (%s)", (*it), strerror(errno));
+        }
+
+        char *buf;
+        if (asprintf(&buf, "%s:%s", (*it), p_v) < 0) {
+            LOGE("Failed to allocate memory");
+            free((*it));
+            continue;
+        }
+        cli->sendMsg(ErrorCode::PropertyList, buf, false);
+        free(buf);
+
+        free((*it));
+    }
+
+    delete pc;
+
+    cli->sendMsg(ErrorCode::CommandOkay, "Properties list complete.", false);
+    return 0;
+}
diff --git a/nexus/CommandListener.h b/nexus/CommandListener.h
new file mode 100644
index 0000000..b57c25f
--- /dev/null
+++ b/nexus/CommandListener.h
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _COMMANDLISTENER_H__
+#define _COMMANDLISTENER_H__
+
+#include <sysutils/FrameworkListener.h>
+#include "NexusCommand.h"
+
+class CommandListener : public FrameworkListener {
+public:
+    CommandListener();
+    virtual ~CommandListener() {}
+
+private:
+
+    class WifiScanCmd : public NexusCommand {
+    public:
+        WifiScanCmd();
+        virtual ~WifiScanCmd() {}
+        int runCommand(SocketClient *c, char *data);
+    };
+
+    class WifiScanResultsCmd : public NexusCommand {
+    public:
+        WifiScanResultsCmd();
+        virtual ~WifiScanResultsCmd() {}
+        int runCommand(SocketClient *c, char *data);
+    };
+
+    class WifiCreateNetworkCmd : public NexusCommand {
+    public:
+        WifiCreateNetworkCmd();
+        virtual ~WifiCreateNetworkCmd() {}
+        int runCommand(SocketClient *c, char *data);
+    };
+
+    class WifiRemoveNetworkCmd : public NexusCommand {
+    public:
+        WifiRemoveNetworkCmd();
+        virtual ~WifiRemoveNetworkCmd() {}
+        int runCommand(SocketClient *c, char *data);
+    };
+
+    class WifiListNetworksCmd : public NexusCommand {
+    public:
+        WifiListNetworksCmd();
+        virtual ~WifiListNetworksCmd() {}
+        int runCommand(SocketClient *c, char *data);
+    };
+
+    class SetCmd : public NexusCommand {
+    public:
+        SetCmd();
+        virtual ~SetCmd() {}
+        int runCommand(SocketClient *c, char *data);
+    };
+
+    class GetCmd : public NexusCommand {
+    public:
+        GetCmd();
+        virtual ~GetCmd() {}
+        int runCommand(SocketClient *c, char *data);
+    };
+
+    class ListCmd : public NexusCommand {
+    public:
+        ListCmd();
+        virtual ~ListCmd() {}
+        int runCommand(SocketClient *c, char *data);
+    };
+};
+
+#endif
diff --git a/nexus/Controller.cpp b/nexus/Controller.cpp
new file mode 100644
index 0000000..9d4ff3c
--- /dev/null
+++ b/nexus/Controller.cpp
@@ -0,0 +1,174 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <malloc.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#define LOG_TAG "Controller"
+
+#include <cutils/log.h>
+
+#include "Controller.h"
+
+extern "C" int init_module(void *, unsigned int, const char *);
+extern "C" int delete_module(const char *, unsigned int);
+
+Controller::Controller(const char *name, PropertyManager *propMngr) {
+    mPropMngr = propMngr;
+    mName = strdup(name);
+    mBoundInterface = NULL;
+}
+
+Controller::~Controller() {
+    if (mBoundInterface)
+        free(mBoundInterface);
+    if (mName)
+        free(mName);
+}
+
+int Controller::start() {
+    return 0;
+}
+
+int Controller::stop() {
+    return 0;
+}
+
+int Controller::set(const char *name, const char *value) {
+    errno = ENOENT;
+    return -1;
+}
+
+const char *Controller::get(const char *name, char *buffer, size_t maxsize) {
+    errno = ENOENT;
+    return NULL;
+}
+
+int Controller::loadKernelModule(char *modpath, const char *args) {
+    void *module;
+    unsigned int size;
+
+    module = loadFile(modpath, &size);
+    if (!module) {
+        errno = -EIO;
+        return -1;
+    }
+
+    int rc = init_module(module, size, args);
+    free (module);
+    return rc;
+}
+
+int Controller::unloadKernelModule(const char *modtag) {
+    int rc = -1;
+    int retries = 10;
+
+    while (retries--) {
+        rc = delete_module(modtag, O_NONBLOCK | O_EXCL);
+        if (rc < 0 && errno == EAGAIN)
+            usleep(1000*500);
+        else
+            break;
+    }
+
+    if (rc != 0) {
+        LOGW("Unable to unload kernel driver '%s' (%s)", modtag,
+             strerror(errno));
+    }
+    return rc;
+}
+
+bool Controller::isKernelModuleLoaded(const char *modtag) {
+    FILE *fp = fopen("/proc/modules", "r");
+
+    if (!fp) {
+        LOGE("Unable to open /proc/modules (%s)", strerror(errno));
+        return false;
+    }
+
+    char line[255];
+    while(fgets(line, sizeof(line), fp)) {
+        char *endTag = strchr(line, ' ');
+
+        if (!endTag) {
+            LOGW("Unable to find tag for line '%s'", line);
+            continue;
+        }
+        if (!strncmp(line, modtag, (endTag - line))) {
+            fclose(fp);
+            return true;
+        }
+    }
+
+    fclose(fp);
+    return false;
+}
+
+void *Controller::loadFile(char *filename, unsigned int *_size)
+{
+	int ret, fd;
+	struct stat sb;
+	ssize_t size;
+	void *buffer = NULL;
+
+	/* open the file */
+	fd = open(filename, O_RDONLY);
+	if (fd < 0)
+		return NULL;
+
+	/* find out how big it is */
+	if (fstat(fd, &sb) < 0)
+		goto bail;
+	size = sb.st_size;
+
+	/* allocate memory for it to be read into */
+	buffer = malloc(size);
+	if (!buffer)
+		goto bail;
+
+	/* slurp it into our buffer */
+	ret = read(fd, buffer, size);
+	if (ret != size)
+		goto bail;
+
+	/* let the caller know how big it is */
+	*_size = size;
+
+bail:
+	close(fd);
+	return buffer;
+}
+
+int Controller::bindInterface(const char *ifname) {
+    mBoundInterface = strdup(ifname);
+    LOGD("Controller %s bound to %s", mName, ifname);
+    return 0;
+}
+
+int Controller::unbindInterface(const char *ifname) {
+    free(mBoundInterface);
+    mBoundInterface = NULL;
+    LOGD("Controller %s unbound from %s", mName, ifname);
+    return 0;
+}
diff --git a/nexus/Controller.h b/nexus/Controller.h
new file mode 100644
index 0000000..9137f9a
--- /dev/null
+++ b/nexus/Controller.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _CONTROLLER_H
+#define _CONTROLLER_H
+
+#include <unistd.h>
+#include <sys/types.h>
+
+#include <utils/List.h>
+
+class PropertyManager;
+
+#include "PropertyManager.h"
+#include "IPropertyProvider.h"
+
+class Controller : public IPropertyProvider {
+private:
+    /*
+     * Name of this controller - WIFI/VPN/USBNET/BTNET/BTDUN/LOOP/etc
+     */
+    char *mName;
+
+    /*
+     * Name of the system ethernet interface which this controller is
+     * bound to.
+     */
+    char *mBoundInterface;
+
+protected:
+    PropertyManager *mPropMngr;
+    
+public:
+    Controller(const char *name, PropertyManager *propMngr);
+    virtual ~Controller();
+
+    virtual int start();
+    virtual int stop();
+
+    const char *getName() { return mName; }
+    const char *getBoundInterface() { return mBoundInterface; }
+
+    /* IPropertyProvider methods */
+    virtual int set(const char *name, const char *value);
+    virtual const char *get(const char *name, char *buffer, size_t maxsize);
+
+protected:
+    int loadKernelModule(char *modpath, const char *args);
+    bool isKernelModuleLoaded(const char *modtag);
+    int unloadKernelModule(const char *modtag);
+    int bindInterface(const char *ifname);
+    int unbindInterface(const char *ifname);
+
+private:
+    void *loadFile(char *filename, unsigned int *_size);
+};
+
+typedef android::List<Controller *> ControllerCollection;
+#endif
diff --git a/nexus/ErrorCode.h b/nexus/ErrorCode.h
new file mode 100644
index 0000000..414dd2c
--- /dev/null
+++ b/nexus/ErrorCode.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _ERRORCODE_H
+#define _ERRORCODE_H
+
+class ErrorCode {
+public:
+    // 100 series - Requestion action was initiated; expect another reply
+    // before proceeding with a new command.
+    static const int ActionInitiated = 100;
+
+    static const int WifiScanResult = 125;
+    static const int WifiNetworkList = 126;
+
+    static const int PropertyRead = 127;
+    static const int PropertySet = 128;
+    static const int PropertyList = 129;
+
+    // 200 series - Requested action has been successfully completed
+    static const int CommandOkay = 200;
+
+    // 400 series - The command was accepted but the requested action
+    // did not take place.
+    static const int OperationFailed = 400;
+
+    // 500 series - The command was not accepted and the requested
+    // action did not take place.
+    static const int CommandSyntaxError = 500;
+    static const int CommandParameterError = 501;
+
+    // 600 series - Unsolicited broadcasts
+    static const int UnsolicitedInformational = 600;
+};
+#endif
diff --git a/nexus/IPropertyProvider.h b/nexus/IPropertyProvider.h
new file mode 100644
index 0000000..17ad5f8
--- /dev/null
+++ b/nexus/IPropertyProvider.h
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _IPROPERTY_PROVIDER_H
+#define _IPROPERTY_PROVIDER_H
+
+#include <unistd.h>
+#include <sys/types.h>
+
+#include <utils/List.h>
+
+class IPropertyProvider {
+public:
+    virtual int set(const char *name, const char *value) = 0;
+    virtual const char *get(const char *name, char *buffer, size_t max) = 0;
+};
+
+typedef android::List<IPropertyProvider *> IPropertyProviderCollection;
+
+#endif
diff --git a/nexus/ISupplicantEventHandler.h b/nexus/ISupplicantEventHandler.h
new file mode 100644
index 0000000..7e1bd5a
--- /dev/null
+++ b/nexus/ISupplicantEventHandler.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _ISUPPLICANT_EVENT_HANDLER_H
+#define _ISUPPLICANT_EVENT_HANDLER_H
+
+class ISupplicantEventHandler {
+public:
+    virtual int onConnectedEvent(SupplicantEvent *evt) = 0;
+    virtual int onDisconnectedEvent(SupplicantEvent *evt) = 0;
+    virtual int onTerminatingEvent(SupplicantEvent *evt) = 0;
+    virtual int onPasswordChangedEvent(SupplicantEvent *evt) = 0;
+    virtual int onEapNotificationEvent(SupplicantEvent *evt) = 0;
+    virtual int onEapStartedEvent(SupplicantEvent *evt) = 0;
+    virtual int onEapMethodEvent(SupplicantEvent *evt) = 0;
+    virtual int onEapSuccessEvent(SupplicantEvent *evt) = 0;
+    virtual int onEapFailureEvent(SupplicantEvent *evt) = 0;
+    virtual int onScanResultsEvent(SupplicantEvent *evt) = 0;
+    virtual int onStateChangeEvent(SupplicantEvent *evt) = 0;
+    virtual int onLinkSpeedEvent(SupplicantEvent *evt) = 0;
+    virtual int onDriverStateEvent(SupplicantEvent *evt) = 0;
+};
+
+#endif
+
diff --git a/nexus/InterfaceConfig.cpp b/nexus/InterfaceConfig.cpp
new file mode 100644
index 0000000..66861d0
--- /dev/null
+++ b/nexus/InterfaceConfig.cpp
@@ -0,0 +1,169 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdlib.h>
+#include <string.h>
+
+#define LOG_TAG "InterfaceConfig"
+#include <cutils/log.h>
+
+#include "InterfaceConfig.h"
+#include "NetworkManager.h"
+
+const char *InterfaceConfig::PropertyNames[] = { "dhcp", "ip",
+                                                 "netmask",
+                                                 "gateway", "dns1", "dns2",
+                                                 "dns3", '\0' };
+
+InterfaceConfig::InterfaceConfig(const char *prop_prefix) {
+    mPropPrefix = strdup(prop_prefix);
+    mUseDhcp = true;
+    registerProperties();
+}
+
+InterfaceConfig::~InterfaceConfig() {
+    unregisterProperties();
+    free(mPropPrefix);
+}
+
+InterfaceConfig::InterfaceConfig(const char *prop_prefix,
+                    const char *ip, const char *nm,
+                    const char *gw, const char *dns1, const char *dns2,
+                    const char *dns3) {
+    mPropPrefix = strdup(prop_prefix);
+    mUseDhcp = false;
+
+    if (!inet_aton(ip, &mIp))
+        LOGW("Unable to parse ip (%s)", ip);
+    if (!inet_aton(nm, &mNetmask))
+        LOGW("Unable to parse netmask (%s)", nm);
+    if (!inet_aton(gw, &mGateway))
+        LOGW("Unable to parse gateway (%s)", gw);
+    if (!inet_aton(dns1, &mDns1))
+        LOGW("Unable to parse dns1 (%s)", dns1);
+    if (!inet_aton(dns2, &mDns2))
+        LOGW("Unable to parse dns2 (%s)", dns2);
+    if (!inet_aton(dns3, &mDns3))
+        LOGW("Unable to parse dns3 (%s)", dns3);
+    registerProperties();
+}
+
+InterfaceConfig::InterfaceConfig(const char *prop_prefix,
+                    const struct in_addr *ip,
+                    const struct in_addr *nm, const struct in_addr *gw,
+                    const struct in_addr *dns1, const struct in_addr *dns2,
+                    const struct in_addr *dns3) {
+    mPropPrefix = strdup(prop_prefix);
+    mUseDhcp = false;
+
+    memcpy(&mIp, ip, sizeof(struct in_addr));
+    memcpy(&mNetmask, nm, sizeof(struct in_addr));
+    memcpy(&mGateway, gw, sizeof(struct in_addr));
+    memcpy(&mDns1, dns1, sizeof(struct in_addr));
+    memcpy(&mDns2, dns2, sizeof(struct in_addr));
+    memcpy(&mDns3, dns3, sizeof(struct in_addr));
+    registerProperties();
+}
+
+int InterfaceConfig::registerProperties() {
+    for (const char **p = InterfaceConfig::PropertyNames; *p != '\0'; p++) {
+        char *tmp;
+        asprintf(&tmp, "%s.if.%s", mPropPrefix, *p);
+
+        if (NetworkManager::Instance()->getPropMngr()->registerProperty(tmp,
+                                                                        this)) {
+            free(tmp);
+            return -1;
+        }
+        free(tmp);
+    }
+    return 0;
+}
+
+int InterfaceConfig::unregisterProperties() {
+    for (const char **p = InterfaceConfig::PropertyNames; *p != '\0'; p++) {
+        char *tmp;
+        asprintf(&tmp, "%s.if.%s", mPropPrefix, *p);
+
+        if (NetworkManager::Instance()->getPropMngr()->unregisterProperty(tmp))
+            LOGW("Unable to remove property '%s' (%s)", tmp, strerror(errno));
+        free(tmp);
+    }
+    return 0;
+}
+
+int InterfaceConfig::set(const char *name, const char *value) {
+    const char *n;
+
+    for (n = &name[strlen(name)]; *n != '.'; n--);
+    n++;
+
+    if (!strcasecmp(n, "name")) {
+        errno = EROFS;
+        return -1;
+    } else if (!strcasecmp(n, "ip") && !inet_aton(value, &mIp))
+        goto out_inval;
+    else if (!strcasecmp(n, "dhcp"))
+        mUseDhcp = (atoi(value) == 0 ? false : true);
+    else if (!strcasecmp(n, "netmask") && !inet_aton(value, &mNetmask))
+        goto out_inval;
+    else if (!strcasecmp(n, "gateway") && !inet_aton(value, &mGateway))
+        goto out_inval;
+    else if (!strcasecmp(n, "dns1") && !inet_aton(value, &mDns1))
+        goto out_inval;
+    else if (!strcasecmp(n, "dns2") && !inet_aton(value, &mDns2))
+        goto out_inval;
+    else if (!strcasecmp(n, "dns3") && !inet_aton(value, &mDns3))
+        goto out_inval;
+    else {
+        errno = ENOENT;
+        return -1;
+    }
+
+    return 0;
+
+out_inval:
+    errno = EINVAL;
+    return -1;
+}
+
+const char *InterfaceConfig::get(const char *name, char *buffer, size_t max) {
+    const char *n;
+
+    for (n = &name[strlen(name)]; *n != '.'; n--);
+    n++;
+
+    if (!strcasecmp(n, "ip"))
+        strncpy(buffer, inet_ntoa(mIp), max);
+    else if (!strcasecmp(n, "dhcp"))
+        snprintf(buffer, max, "%d", mUseDhcp);
+    else if (!strcasecmp(n, "netmask"))
+        strncpy(buffer, inet_ntoa(mNetmask), max);
+    else if (!strcasecmp(n, "gateway"))
+        strncpy(buffer, inet_ntoa(mGateway), max);
+    else if (!strcasecmp(n, "dns1"))
+        strncpy(buffer, inet_ntoa(mDns1), max);
+    else if (!strcasecmp(n, "dns2"))
+        strncpy(buffer, inet_ntoa(mDns2), max);
+    else if (!strcasecmp(n, "dns3"))
+        strncpy(buffer, inet_ntoa(mDns3), max);
+    else {
+        strncpy(buffer, "(internal error)", max);
+        errno = ENOENT;
+        return NULL;
+    }
+    return buffer;
+}
diff --git a/nexus/InterfaceConfig.h b/nexus/InterfaceConfig.h
new file mode 100644
index 0000000..d97f20b
--- /dev/null
+++ b/nexus/InterfaceConfig.h
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _INTERFACE_CONFIG_H
+#define _INTERFACE_CONFIG_H
+
+#include <unistd.h>
+#include <sys/types.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+#include "IPropertyProvider.h"
+
+class PropertyManager;
+
+class InterfaceConfig : public IPropertyProvider {
+public:
+    static const char *PropertyNames[];
+
+private:
+    char *mPropPrefix;
+    bool mUseDhcp;
+    struct in_addr mIp;
+    struct in_addr mNetmask;
+    struct in_addr mGateway;
+    struct in_addr mDns1;
+    struct in_addr mDns2;
+    struct in_addr mDns3;
+
+public:
+    InterfaceConfig(const char *prop_prefix);
+    InterfaceConfig(const char *prop_prefix,
+                    const char *ip, const char *nm,
+                    const char *gw, const char *dns1, const char *dns2,
+                    const char *dns3);
+
+    InterfaceConfig(const char *prop_prefix,
+                    const struct in_addr *ip,
+                    const struct in_addr *nm, const struct in_addr *gw,
+                    const struct in_addr *dns1, const struct in_addr *dns2,
+                    const struct in_addr *dns3);
+
+    virtual ~InterfaceConfig();
+    
+    int set(const char *name, const char *value);
+    const char *get(const char *name, char *buffer, size_t maxsize);
+
+    bool            getUseDhcp() const { return mUseDhcp; }
+    const struct in_addr &getIp() const { return mIp; }
+    const struct in_addr &getNetmask() const { return mNetmask; }
+    const struct in_addr &getGateway() const { return mGateway; }
+    const struct in_addr &getDns1() const { return mDns1; }
+    const struct in_addr &getDns2() const { return mDns2; }
+    const struct in_addr &getDns3() const { return mDns3; }
+
+private:
+    int registerProperties();
+    int unregisterProperties();
+};
+
+
+#endif
diff --git a/nexus/LoopController.cpp b/nexus/LoopController.cpp
new file mode 100644
index 0000000..a86202a
--- /dev/null
+++ b/nexus/LoopController.cpp
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <errno.h>
+
+#include "LoopController.h"
+#include "PropertyManager.h"
+
+LoopController::LoopController(PropertyManager *propmngr) :
+                Controller("LOOP", propmngr) {
+}
+
+int LoopController::set(const char *name, const char *value) {
+    return Controller::set(name, value);
+}
+
+const char *LoopController::get(const char *name, char *buffer, size_t maxsize) {
+    return Controller::get(name, buffer, maxsize);
+}
+
diff --git a/nexus/LoopController.h b/nexus/LoopController.h
new file mode 100644
index 0000000..bb8314f
--- /dev/null
+++ b/nexus/LoopController.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _LOOP_CONTROLLER_H
+#define _LOOP_CONTROLLER_H
+
+#include "Controller.h"
+
+
+class LoopController : public Controller {
+public:
+    LoopController(PropertyManager *propmngr);
+    virtual ~LoopController() {}
+
+    int set(const char *name, const char *value);
+    const char *get(const char *name, char *buffer, size_t maxsize);
+};
+
+#endif
diff --git a/nexus/NetworkManager.cpp b/nexus/NetworkManager.cpp
new file mode 100644
index 0000000..f4ae88f
--- /dev/null
+++ b/nexus/NetworkManager.cpp
@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+#include <errno.h>
+
+#define LOG_TAG "Nexus"
+
+#include <cutils/log.h>
+
+#include "NetworkManager.h"
+#include "InterfaceConfig.h"
+
+NetworkManager *NetworkManager::sInstance = NULL;
+
+NetworkManager *NetworkManager::Instance() {
+    if (!sInstance)
+        sInstance = new NetworkManager(new PropertyManager());
+    return sInstance;
+}
+
+NetworkManager::NetworkManager(PropertyManager *propMngr) {
+    mBroadcaster = NULL;
+    mControllers = new ControllerCollection();
+    mPropMngr = propMngr;
+}
+
+NetworkManager::~NetworkManager() {
+}
+
+int NetworkManager::run() {
+    if (startControllers()) {
+        LOGW("Unable to start all controllers (%s)", strerror(errno));
+    }
+    return 0;
+}
+
+int NetworkManager::attachController(Controller *c) {
+    mControllers->push_back(c);
+    return 0;
+}
+
+int NetworkManager::startControllers() {
+    int rc = 0;
+    ControllerCollection::iterator i;
+
+    for (i = mControllers->begin(); i != mControllers->end(); ++i) {
+        int irc = (*i)->start();
+        LOGD("Controller '%s' start rc = %d", (*i)->getName(), irc);
+        if (irc && !rc)
+            rc = irc;
+    }
+    return rc;
+}
+
+int NetworkManager::stopControllers() {
+    int rc = 0;
+    ControllerCollection::iterator i;
+
+    for (i = mControllers->begin(); i != mControllers->end(); ++i) {
+        int irc = (*i)->stop();
+        LOGD("Controller '%s' stop rc = %d", (*i)->getName(), irc);
+        if (irc && !rc)
+            rc = irc;
+    }
+    return rc;
+}
+
+Controller *NetworkManager::findController(const char *name) {
+    ControllerCollection::iterator i;
+    for (i = mControllers->begin(); i != mControllers->end(); ++i) {
+        if (!strcmp((*i)->getName(), name))
+            return *i;
+    }
+    LOGW("Controller '%s' not found", name);
+    return NULL;
+}
+
+int NetworkManager::onInterfaceStart(Controller *c, const InterfaceConfig *cfg) {
+    LOGD("Interface %s started by controller %s", c->getBoundInterface(), c->getName());
+
+    // Look up the interface
+
+    if (0) { // already started?
+        errno = EADDRINUSE;
+        return -1;
+    }
+
+    if (cfg->getUseDhcp()) {
+    } else {
+    }
+    return 0;
+}
+
+int NetworkManager::onInterfaceStop(Controller *c, const char *name) {
+    LOGD("Interface %s stopped by controller %s", name, c->getName());
+    return 0;
+}
diff --git a/nexus/NetworkManager.h b/nexus/NetworkManager.h
new file mode 100644
index 0000000..e75382d
--- /dev/null
+++ b/nexus/NetworkManager.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _NETWORKMANAGER_H
+#define _NETWORKMANAGER_H
+
+#include <sysutils/SocketListener.h>
+
+#include "Controller.h"
+
+#include "PropertyManager.h"
+
+class InterfaceConfig;
+
+class NetworkManager {
+private:
+    static NetworkManager *sInstance;
+
+private:
+    ControllerCollection *mControllers;
+    SocketListener       *mBroadcaster;
+    PropertyManager      *mPropMngr;
+
+public:
+    virtual ~NetworkManager();
+
+    int run();
+
+    int attachController(Controller *controller);
+
+    Controller *findController(const char *name);
+
+    void setBroadcaster(SocketListener *sl) { mBroadcaster = sl; }
+    SocketListener *getBroadcaster() { return mBroadcaster; }
+    PropertyManager *getPropMngr() { return mPropMngr; }
+
+    static NetworkManager *Instance();
+
+private:
+    int startControllers();
+    int stopControllers();
+
+    NetworkManager(PropertyManager *propMngr);
+
+public:
+    /*
+     * Called from a controller when an interface is available/ready for use.
+     * 'cfg' contains information on how this interface should be configured.
+     */
+    int onInterfaceStart(Controller *c, const InterfaceConfig *cfg);
+
+    /*
+     * Called from a controller when an interface should be shut down
+     */
+    int onInterfaceStop(Controller *c, const char *name);
+};
+#endif
diff --git a/nexus/NexusCommand.cpp b/nexus/NexusCommand.cpp
new file mode 100644
index 0000000..541eeeb
--- /dev/null
+++ b/nexus/NexusCommand.cpp
@@ -0,0 +1,21 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "NexusCommand.h"
+
+NexusCommand::NexusCommand(const char *cmd) :
+              FrameworkCommand(cmd)  {
+}
diff --git a/nexus/NexusCommand.h b/nexus/NexusCommand.h
new file mode 100644
index 0000000..a7f944a
--- /dev/null
+++ b/nexus/NexusCommand.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _NEXUS_COMMAND_H
+#define _NEXUS_COMMAND_H
+
+#include <sysutils/FrameworkCommand.h>
+
+class NexusCommand : public FrameworkCommand {
+public:
+    NexusCommand(const char *cmd);
+    virtual ~NexusCommand() {}
+};
+
+#endif
diff --git a/nexus/OpenVpnController.cpp b/nexus/OpenVpnController.cpp
new file mode 100644
index 0000000..4c144a4
--- /dev/null
+++ b/nexus/OpenVpnController.cpp
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <errno.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+#define LOG_TAG "OpenVpnController"
+#include <cutils/log.h>
+#include <cutils/properties.h>
+
+#include <sysutils/ServiceManager.h>
+
+#include "OpenVpnController.h"
+#include "PropertyManager.h"
+
+#define DAEMON_PROP_NAME "vpn.openvpn.status"
+#define DAEMON_CONFIG_FILE "/data/misc/openvpn/openvpn.conf"
+
+OpenVpnController::OpenVpnController(PropertyManager *propmngr) :
+                   VpnController(propmngr) {
+    mServiceManager = new ServiceManager();
+}
+
+OpenVpnController::~OpenVpnController() {
+    delete mServiceManager;
+}
+
+int OpenVpnController::start() {
+    return 0;
+}
+
+int OpenVpnController::stop() {
+    return 0;
+}
+
+int OpenVpnController::enable() {
+    char svc[PROPERTY_VALUE_MAX];
+    char tmp[64];
+
+    if (!mPropMngr->get("vpn.gateway", tmp, sizeof(tmp))) {
+        LOGE("Error reading property 'vpn.gateway' (%s)", strerror(errno));
+        return -1;
+    }
+    snprintf(svc, sizeof(svc), "openvpn:--remote %s 1194", tmp);
+
+    if (mServiceManager->start(svc))
+        return -1;
+
+    return 0;
+}
+
+int OpenVpnController::disable() {
+    if (mServiceManager->stop("openvpn"))
+        return -1;
+    return 0;
+}
diff --git a/nexus/OpenVpnController.h b/nexus/OpenVpnController.h
new file mode 100644
index 0000000..323c44c
--- /dev/null
+++ b/nexus/OpenVpnController.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _OPEN_VPN_CONTROLLER_H
+#define _OPEN_VPN_CONTROLLER_H
+
+#include "PropertyManager.h"
+#include "VpnController.h"
+
+class ServiceManager;
+
+class OpenVpnController : public VpnController {
+private:
+    ServiceManager *mServiceManager;
+
+public:
+    OpenVpnController(PropertyManager *propmngr);
+    virtual ~OpenVpnController();
+
+    int start();
+    int stop();
+
+private:
+    int enable();
+    int disable();
+};
+
+#endif
diff --git a/nexus/Property.h b/nexus/Property.h
new file mode 100644
index 0000000..198f722
--- /dev/null
+++ b/nexus/Property.h
@@ -0,0 +1,21 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+class Property {
+public:
+    static const int NameMaxSize = 128;
+    static const int ValueMaxSize  = 255;
+};
diff --git a/nexus/PropertyManager.cpp b/nexus/PropertyManager.cpp
new file mode 100644
index 0000000..3366bab
--- /dev/null
+++ b/nexus/PropertyManager.cpp
@@ -0,0 +1,122 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "PropertyManager"
+
+#include <cutils/log.h>
+
+#include "PropertyManager.h"
+
+PropertyManager::PropertyManager() {
+    mPropertyPairs = new PropertyPairCollection();
+    pthread_mutex_init(&mLock, NULL);
+}
+
+PropertyManager::~PropertyManager() {
+    delete mPropertyPairs;
+}
+
+int PropertyManager::registerProperty(const char *name, IPropertyProvider *pp) {
+    PropertyPairCollection::iterator it;
+
+//    LOGD("registerProperty(%s)", name);
+    pthread_mutex_lock(&mLock);
+    for (it = mPropertyPairs->begin(); it != mPropertyPairs->end(); ++it) {
+        if (!strcmp(name, (*it)->getName())) {
+            errno = EADDRINUSE;
+            LOGE("Failed to register property (%s)", strerror(errno));
+            pthread_mutex_unlock(&mLock);
+            return -1;
+        }
+    }
+    mPropertyPairs->push_back(new PropertyPair(name, pp));
+    pthread_mutex_unlock(&mLock);
+    return 0;
+}
+
+int PropertyManager::unregisterProperty(const char *name) {
+    PropertyPairCollection::iterator it;
+
+//    LOGD("unregisterProperty(%s)", name);
+    pthread_mutex_lock(&mLock);
+    for (it = mPropertyPairs->begin(); it != mPropertyPairs->end(); ++it) {
+        if (!strcmp(name, (*it)->getName())) {
+            delete ((*it));
+            mPropertyPairs->erase(it);
+            pthread_mutex_unlock(&mLock);
+            return 0;
+        }
+    }
+    pthread_mutex_unlock(&mLock);
+    errno = ENOENT;
+    return -1;
+}
+
+/*
+ * IPropertyManager methods
+ */
+
+int PropertyManager::set(const char *name, const char *value) {
+    PropertyPairCollection::iterator it;
+
+    pthread_mutex_lock(&mLock);
+    for (it = mPropertyPairs->begin(); it != mPropertyPairs->end(); ++it) {
+        if (!strcmp(name, (*it)->getName())) {
+            pthread_mutex_unlock(&mLock);
+            return (*it)->getProvider()->set(name, value);
+        }
+    }
+    pthread_mutex_unlock(&mLock);
+    errno = ENOENT;
+    return -1;
+}
+
+const char *PropertyManager::get(const char *name, char *buffer, size_t max) {
+    PropertyPairCollection::iterator it;
+
+    memset(buffer, 0, max);
+    pthread_mutex_lock(&mLock);
+    for (it = mPropertyPairs->begin(); it != mPropertyPairs->end(); ++it) {
+        if (!strcmp(name, (*it)->getName())) {
+            pthread_mutex_unlock(&mLock);
+            return (*it)->getProvider()->get(name, buffer, max);
+            }
+    }
+    pthread_mutex_unlock(&mLock);
+    errno = ENOENT;
+    return NULL;
+}
+
+android::List<char *> *PropertyManager::createPropertyList() {
+    android::List<char *> *c = new android::List<char *>();
+
+    PropertyPairCollection::iterator it;
+
+    pthread_mutex_lock(&mLock);
+    for (it = mPropertyPairs->begin(); it != mPropertyPairs->end(); ++it)
+         c->push_back(strdup((*it)->getName()));
+    pthread_mutex_unlock(&mLock);
+    return c;
+}
+
+PropertyPair::PropertyPair(const char *name, IPropertyProvider *pp) {
+    mName = strdup(name);
+    mPp = pp;
+}
+
+PropertyPair::~PropertyPair() {
+    free(mName);
+}
diff --git a/nexus/PropertyManager.h b/nexus/PropertyManager.h
new file mode 100644
index 0000000..10d0b2a
--- /dev/null
+++ b/nexus/PropertyManager.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _PROPERTY_MANAGER_H
+#define _PROPERTY_MANAGER_H
+
+#include <errno.h>
+#include <pthread.h>
+
+#include <utils/List.h>
+
+#include "IPropertyProvider.h"
+
+class PropertyPair {
+private:
+    char *mName;
+    IPropertyProvider *mPp;
+ 
+public:
+    PropertyPair(const char *name, IPropertyProvider *pp);
+    virtual ~PropertyPair();
+
+    const char *getName() { return mName; }
+    IPropertyProvider *getProvider() { return mPp; }
+};
+
+typedef android::List<PropertyPair *> PropertyPairCollection;
+
+class PropertyManager {
+    PropertyPairCollection *mPropertyPairs;
+    pthread_mutex_t         mLock;
+
+public:
+    PropertyManager();
+    virtual ~PropertyManager();   
+    int registerProperty(const char *name, IPropertyProvider *pp);
+    int unregisterProperty(const char *name);
+    android::List<char *> *createPropertyList();
+
+    int set(const char *name, const char *value);
+    const char *get(const char *name, char *buffer, size_t max);
+};
+
+#endif
diff --git a/nexus/ScanResult.cpp b/nexus/ScanResult.cpp
new file mode 100644
index 0000000..e9a286c
--- /dev/null
+++ b/nexus/ScanResult.cpp
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdlib.h>
+#include <ctype.h>
+
+#define LOG_TAG "ScanResult"
+#include <cutils/log.h>
+
+#include "ScanResult.h"
+
+ScanResult::ScanResult() {
+}
+
+ScanResult::ScanResult(char *rawResult) {
+    char *p = rawResult, *q = rawResult;
+    char tmp[255];
+
+    // BSSID
+    for (q = p; *q != '\t'; ++q);
+    strncpy(tmp, p, (q - p));
+    tmp[q-p] = '\0';
+    mBssid = strdup(tmp);
+    ++q;
+
+    // FREQ
+    for (p = q; *q != '\t'; ++q);
+    strncpy(tmp, p, (q - p));
+    tmp[q-p] = '\0';
+    mFreq = atoi(tmp);
+    ++q;
+
+    // LEVEL
+    for (p = q; *q != '\t'; ++q);
+    strncpy(tmp, p, (q - p));
+    tmp[q-p] = '\0';
+    mLevel = atoi(tmp);
+    ++q;
+
+    // FLAGS
+    for (p = q; *q != '\t'; ++q);
+    strncpy(tmp, p, (q - p));
+    tmp[q-p] = '\0';
+    mFlags = strdup(tmp);
+    ++q;
+
+    // XXX: For some reason Supplicant sometimes sends a double-tab here.
+    // haven't had time to dig into it ...
+    if (*q == '\t')
+        q++;
+
+    for (p = q; *q != '\t'; ++q) {
+        if (*q == '\0')
+            break;
+    }
+
+    strncpy(tmp, p, (q - p));
+    tmp[q-p] = '\0';
+    mSsid = strdup(tmp);
+    ++q;
+
+    return;
+ out_bad:
+    LOGW("Malformatted scan result (%s)", rawResult);
+}
+
+ScanResult::~ScanResult() {
+    if (mBssid)
+        free(mBssid);
+    if (mFlags)
+        free(mFlags);
+    if (mSsid)
+        free(mSsid);
+}
+
+ScanResult *ScanResult::clone() {
+    ScanResult *r = new ScanResult();
+
+    r->mBssid = strdup(mBssid);
+    r->mFreq = mFreq;
+    r->mLevel = mLevel;
+    r->mFlags = strdup(mFlags);
+    r->mSsid = strdup(mSsid);
+
+    return r;
+}
diff --git a/nexus/ScanResult.h b/nexus/ScanResult.h
new file mode 100644
index 0000000..68ad0f0
--- /dev/null
+++ b/nexus/ScanResult.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _SCAN_RESULT_H
+#define _SCAN_RESULT_H
+
+#include <sys/types.h>
+
+#include <utils/List.h>
+
+class ScanResult {
+    char     *mBssid;
+    uint32_t mFreq;
+    int      mLevel;
+    char     *mFlags;
+    char     *mSsid;
+
+private:
+    ScanResult();
+
+public:
+    ScanResult(char *rawResult);
+    virtual ~ScanResult();
+
+    ScanResult *clone();
+
+    const char *getBssid() { return mBssid; }
+    uint32_t getFreq() { return mFreq; }
+    int getLevel() { return mLevel; }
+    const char *getFlags() { return mFlags; }
+    const char *getSsid() { return mSsid; }
+};
+
+typedef android::List<ScanResult *> ScanResultCollection;
+
+#endif
diff --git a/nexus/Supplicant.cpp b/nexus/Supplicant.cpp
new file mode 100644
index 0000000..e69f2c0
--- /dev/null
+++ b/nexus/Supplicant.cpp
@@ -0,0 +1,575 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdlib.h>
+#include <sys/types.h>
+#include <fcntl.h>
+#include <errno.h>
+
+#define LOG_TAG "Supplicant"
+#include <cutils/log.h>
+#include <cutils/properties.h>
+
+#include "private/android_filesystem_config.h"
+
+#include <sysutils/ServiceManager.h>
+
+#include "Supplicant.h"
+#include "SupplicantListener.h"
+#include "SupplicantState.h"
+#include "SupplicantEvent.h"
+#include "ScanResult.h"
+#include "PropertyManager.h"
+#include "NetworkManager.h"
+#include "ErrorCode.h"
+#include "WifiController.h"
+
+#include "libwpa_client/wpa_ctrl.h"
+
+#define IFACE_DIR        "/data/system/wpa_supplicant"
+#define DRIVER_PROP_NAME "wlan.driver.status"
+#define SUPPLICANT_SERVICE_NAME  "wpa_supplicant"
+#define SUPP_CONFIG_TEMPLATE "/system/etc/wifi/wpa_supplicant.conf"
+#define SUPP_CONFIG_FILE "/data/misc/wifi/wpa_supplicant.conf"
+
+Supplicant::Supplicant(WifiController *wc, PropertyManager *propmngr) {
+    mController = wc;
+    mPropMngr = propmngr;
+    mInterfaceName = NULL;
+    mCtrl = NULL;
+    mMonitor = NULL;
+    mListener = NULL;
+   
+    mState = SupplicantState::UNKNOWN;
+
+    mServiceManager = new ServiceManager();
+
+    mLatestScanResults = new ScanResultCollection();
+    pthread_mutex_init(&mLatestScanResultsLock, NULL);
+
+    mNetworks = new WifiNetworkCollection();
+    pthread_mutex_init(&mNetworksLock, NULL);
+}
+
+Supplicant::~Supplicant() {
+    delete mServiceManager;
+    if (mInterfaceName)
+        free(mInterfaceName);
+}
+
+int Supplicant::start() {
+
+    if (setupConfig()) {
+        LOGW("Unable to setup supplicant.conf");
+    }
+
+    if (mServiceManager->start(SUPPLICANT_SERVICE_NAME)) {
+        LOGE("Error starting supplicant (%s)", strerror(errno));
+        return -1;
+    }
+
+    wpa_ctrl_cleanup();
+    if (connectToSupplicant()) {
+        LOGE("Error connecting to supplicant (%s)\n", strerror(errno));
+        return -1;
+    }
+    
+    if (retrieveInterfaceName()) {
+        LOGE("Error retrieving interface name (%s)\n", strerror(errno));
+        return -1;
+    }
+
+    mPropMngr->registerProperty("wifi.supplicant.state", this);
+    return 0;
+}
+
+int Supplicant::stop() {
+
+    mPropMngr->unregisterProperty("wifi.supplicant.state");
+
+    if (mListener->stopListener()) {
+        LOGW("Unable to stop supplicant listener (%s)", strerror(errno));
+        return -1;
+    }
+
+    if (mServiceManager->stop(SUPPLICANT_SERVICE_NAME)) {
+        LOGW("Error stopping supplicant (%s)", strerror(errno));
+    }
+
+    if (mCtrl) {
+        wpa_ctrl_close(mCtrl);
+        mCtrl = NULL;
+    }
+    if (mMonitor) {
+        wpa_ctrl_close(mMonitor);
+        mMonitor = NULL;
+    }
+
+    return 0;
+}
+
+bool Supplicant::isStarted() {
+    return mServiceManager->isRunning(SUPPLICANT_SERVICE_NAME);
+}
+
+int Supplicant::refreshNetworkList() {
+    char *reply;
+    size_t len = 4096;
+
+    if (!(reply = (char *) malloc(len))) {
+        errno = ENOMEM;
+        return -1;
+    }
+
+    if (sendCommand("LIST_NETWORKS", reply, &len)) {
+        free(reply);
+        return -1;
+    }
+
+    char *linep;
+    char *linep_next = NULL;
+
+    if (!strtok_r(reply, "\n", &linep_next)) {
+        LOGW("Malformatted network list\n");
+    } else {
+        pthread_mutex_lock(&mNetworksLock);
+        if (!mNetworks->empty()) {
+            WifiNetworkCollection::iterator i;
+
+            for (i = mNetworks->begin(); i !=mNetworks->end(); ++i)
+                delete *i;
+            mNetworks->clear();
+        }
+
+        while((linep = strtok_r(NULL, "\n", &linep_next))) {
+            WifiNetwork *wn = new WifiNetwork(mController, this, linep);
+            mNetworks->push_back(wn);
+            if (wn->refresh())
+                LOGW("Unable to refresh network id %d", wn->getNetworkId());
+        }
+
+        LOGD("Loaded %d networks\n", mNetworks->size());
+        pthread_mutex_unlock(&mNetworksLock);
+    }
+
+    free(reply);
+    return 0;
+}
+
+int Supplicant::connectToSupplicant() {
+    if (!isStarted())
+        LOGW("Supplicant service not running");
+
+    mCtrl = wpa_ctrl_open("tiwlan0"); // XXX:
+    if (mCtrl == NULL) {
+        LOGE("Unable to open connection to supplicant on \"%s\": %s",
+             "tiwlan0", strerror(errno));
+        return -1;
+    }
+    mMonitor = wpa_ctrl_open("tiwlan0");
+    if (mMonitor == NULL) {
+        wpa_ctrl_close(mCtrl);
+        mCtrl = NULL;
+        return -1;
+    }
+    if (wpa_ctrl_attach(mMonitor) != 0) {
+        wpa_ctrl_close(mMonitor);
+        wpa_ctrl_close(mCtrl);
+        mCtrl = mMonitor = NULL;
+        return -1;
+    }
+
+    mListener = new SupplicantListener(this, mMonitor);
+
+    if (mListener->startListener()) {
+        LOGE("Error - unable to start supplicant listener");
+        stop();
+        return -1;
+    }
+    return 0;
+}
+
+int Supplicant::sendCommand(const char *cmd, char *reply, size_t *reply_len)
+{
+    if (!mCtrl) {
+        errno = ENOTCONN;
+        return -1;
+    }
+
+//    LOGD("sendCommand(): -> '%s'", cmd);
+
+    int rc;
+    memset(reply, 0, *reply_len);
+    if ((rc = wpa_ctrl_request(mCtrl, cmd, strlen(cmd), reply, reply_len, NULL)) == -2)  {
+        errno = ETIMEDOUT;
+        return -1;
+    } else if (rc < 0 || !strncmp(reply, "FAIL", 4)) {
+        strcpy(reply, "FAIL");
+        errno = EIO;
+        return -1;
+    }
+
+//   LOGD("sendCommand(): <- '%s'", reply);
+    return 0;
+}
+
+int Supplicant::triggerScan(bool active) {
+    char reply[255];
+    size_t len = sizeof(reply);
+
+    if (sendCommand((active ? "DRIVER SCAN-ACTIVE" : "DRIVER SCAN-PASSIVE"),
+                     reply, &len)) {
+        LOGW("triggerScan(%d): Error setting scan mode (%s)", active,
+             strerror(errno));
+        return -1;
+    }
+    len = sizeof(reply);
+
+    if (sendCommand("SCAN", reply, &len)) {
+        LOGW("triggerScan(%d): Error initiating scan", active);
+        return -1;
+    }
+    return 0;
+}
+
+int Supplicant::set(const char *name, const char *value) {
+    const char *n = name + strlen("wifi.supplicant.");
+
+    errno = -EROFS;
+    return -1;
+}
+
+const char *Supplicant::get(const char *name, char *buffer, size_t max) {
+    const char *n = name + strlen("wifi.supplicant.");
+
+    if (!strcasecmp(n, "state"))
+        return SupplicantState::toString(mState, buffer, max);
+    errno = ENOENT;
+    return NULL;
+}
+
+int Supplicant::onConnectedEvent(SupplicantEvent *evt) {
+    LOGD("onConnectedEvent(%s)", evt->getEvent());
+    return 0;
+}
+
+int Supplicant::onDisconnectedEvent(SupplicantEvent *evt) {
+    LOGD("onDisconnectedEvent(%s)", evt->getEvent());
+    return 0;
+}
+
+int Supplicant::onTerminatingEvent(SupplicantEvent *evt) {
+    LOGD("onTerminatingEvent(%s)", evt->getEvent());
+    return 0;
+}
+
+int Supplicant::onPasswordChangedEvent(SupplicantEvent *evt) {
+    LOGD("onPasswordChangedEvent(%s)", evt->getEvent());
+    return 0;
+}
+
+int Supplicant::onEapNotificationEvent(SupplicantEvent *evt) {
+    LOGD("onEapNotificationEvent(%s)", evt->getEvent());
+    return 0;
+}
+
+int Supplicant::onEapStartedEvent(SupplicantEvent *evt) {
+    LOGD("onEapStartedEvent(%s)", evt->getEvent());
+    return 0;
+}
+
+int Supplicant::onEapMethodEvent(SupplicantEvent *evt) {
+    LOGD("onEapMethodEvent(%s)", evt->getEvent());
+    return 0;
+}
+
+int Supplicant::onEapSuccessEvent(SupplicantEvent *evt) {
+    LOGD("onEapSuccessEvent(%s)", evt->getEvent());
+    return 0;
+}
+
+int Supplicant::onEapFailureEvent(SupplicantEvent *evt) {
+    LOGD("onEapFailureEvent(%s)", evt->getEvent());
+    return 0;
+}
+
+int Supplicant::onScanResultsEvent(SupplicantEvent *evt) {
+    if (!strcmp(evt->getEvent(), "Ready")) {
+        char *reply;
+
+        if (!(reply = (char *) malloc(4096))) {
+            errno = ENOMEM;
+            return -1;
+        }
+
+        size_t len = 4096;
+
+        if (sendCommand("SCAN_RESULTS", reply, &len)) {
+            LOGW("onScanResultsEvent(%s): Error getting scan results (%s)",
+                  evt->getEvent(), strerror(errno));
+            free(reply);
+            return -1;
+        }
+
+        pthread_mutex_lock(&mLatestScanResultsLock);
+        if (!mLatestScanResults->empty()) {
+            ScanResultCollection::iterator i;
+
+            for (i = mLatestScanResults->begin();
+                 i !=mLatestScanResults->end(); ++i) {
+                delete *i;
+            }
+            mLatestScanResults->clear();
+        }
+
+        char *linep;
+        char *linep_next = NULL;
+
+        if (!strtok_r(reply, "\n", &linep_next)) {
+            free(reply);
+            pthread_mutex_unlock(&mLatestScanResultsLock);
+            return 0;
+        }
+
+        while((linep = strtok_r(NULL, "\n", &linep_next)))
+            mLatestScanResults->push_back(new ScanResult(linep));
+
+        char tmp[128];
+        sprintf(tmp, "Scan results ready (%d)", mLatestScanResults->size());
+        NetworkManager::Instance()->getBroadcaster()->
+                                    sendBroadcast(ErrorCode::UnsolicitedInformational, tmp, false);
+        pthread_mutex_unlock(&mLatestScanResultsLock);
+        free(reply);
+    } else {
+        LOGW("Unknown SCAN_RESULTS event (%s)", evt->getEvent());
+    }
+    return 0;
+}
+
+int Supplicant::onStateChangeEvent(SupplicantEvent *evt) {
+    char *bword, *last;
+    char *tmp = strdup(evt->getEvent());
+
+    if (!(bword = strtok_r(tmp, " ", &last))) {
+        LOGE("Malformatted state update (%s)", evt->getEvent());
+        free(tmp);
+        return 0;
+    }
+
+    if (!(bword = strtok_r(NULL, " ", &last))) {
+        LOGE("Malformatted state update (%s)", evt->getEvent());
+        free(tmp);
+        return 0;
+    }
+
+    mState = atoi(&bword[strlen("state=")]);
+    LOGD("State changed to %d", mState);
+    free(tmp);
+    return 0;
+}
+
+int Supplicant::onLinkSpeedEvent(SupplicantEvent *evt) {
+    LOGD("onLinkSpeedEvent(%s)", evt->getEvent());
+    return 0;
+}
+
+int Supplicant::onDriverStateEvent(SupplicantEvent *evt) {
+    LOGD("onDriverStateEvent(%s)", evt->getEvent());
+    return 0;
+}
+
+// XXX: Use a cursor + smartptr instead
+ScanResultCollection *Supplicant::createLatestScanResults() {
+    ScanResultCollection *d = new ScanResultCollection();
+    ScanResultCollection::iterator i;
+
+    pthread_mutex_lock(&mLatestScanResultsLock);
+    for (i = mLatestScanResults->begin(); i != mLatestScanResults->end(); ++i)
+        d->push_back((*i)->clone());
+
+    pthread_mutex_unlock(&mLatestScanResultsLock);
+    return d;
+}
+
+WifiNetwork *Supplicant::createNetwork() {
+    char reply[255];
+    size_t len = sizeof(reply) -1;
+
+    if (sendCommand("ADD_NETWORK", reply, &len))
+        return NULL;
+
+    if (reply[strlen(reply) -1] == '\n')
+        reply[strlen(reply) -1] = '\0';
+
+    WifiNetwork *wn = new WifiNetwork(mController, this, atoi(reply));
+    pthread_mutex_lock(&mNetworksLock);
+    mNetworks->push_back(wn);
+    pthread_mutex_unlock(&mNetworksLock);
+    return wn;
+}
+
+int Supplicant::removeNetwork(WifiNetwork *wn) {
+    char req[64];
+
+    sprintf(req, "REMOVE_NETWORK %d", wn->getNetworkId());
+    char reply[32];
+    size_t len = sizeof(reply) -1;
+
+    if (sendCommand(req, reply, &len))
+        return -1;
+
+    pthread_mutex_lock(&mNetworksLock);
+    WifiNetworkCollection::iterator it;
+    for (it = mNetworks->begin(); it != mNetworks->end(); ++it) {
+        if ((*it) == wn) {
+            mNetworks->erase(it);
+            break;
+        }
+    }
+    pthread_mutex_unlock(&mNetworksLock);
+    return 0;
+}
+
+WifiNetwork *Supplicant::lookupNetwork(int networkId) {
+    pthread_mutex_lock(&mNetworksLock);
+    WifiNetworkCollection::iterator it;
+    for (it = mNetworks->begin(); it != mNetworks->end(); ++it) {
+        if ((*it)->getNetworkId() == networkId) {
+            pthread_mutex_unlock(&mNetworksLock);
+            return *it;
+        }
+    }
+    pthread_mutex_unlock(&mNetworksLock);
+    errno = ENOENT;
+    return NULL;
+}
+
+WifiNetworkCollection *Supplicant::createNetworkList() {
+    WifiNetworkCollection *d = new WifiNetworkCollection();
+    WifiNetworkCollection::iterator i;
+
+    pthread_mutex_lock(&mNetworksLock);
+    for (i = mNetworks->begin(); i != mNetworks->end(); ++i)
+        d->push_back((*i)->clone());
+
+    pthread_mutex_unlock(&mNetworksLock);
+    return d;
+}
+
+int Supplicant::setupConfig() {
+    char buf[2048];
+    int srcfd, destfd;
+    int nread;
+
+    if (access(SUPP_CONFIG_FILE, R_OK|W_OK) == 0) {
+        return 0;
+    } else if (errno != ENOENT) {
+        LOGE("Cannot access \"%s\": %s", SUPP_CONFIG_FILE, strerror(errno));
+        return -1;
+    }
+
+    srcfd = open(SUPP_CONFIG_TEMPLATE, O_RDONLY);
+    if (srcfd < 0) {
+        LOGE("Cannot open \"%s\": %s", SUPP_CONFIG_TEMPLATE, strerror(errno));
+        return -1;
+    }
+
+    destfd = open(SUPP_CONFIG_FILE, O_CREAT|O_WRONLY, 0660);
+    if (destfd < 0) {
+        close(srcfd);
+        LOGE("Cannot create \"%s\": %s", SUPP_CONFIG_FILE, strerror(errno));
+        return -1;
+    }
+
+    while ((nread = read(srcfd, buf, sizeof(buf))) != 0) {
+        if (nread < 0) {
+            LOGE("Error reading \"%s\": %s", SUPP_CONFIG_TEMPLATE, strerror(errno));
+            close(srcfd);
+            close(destfd);
+            unlink(SUPP_CONFIG_FILE);
+            return -1;
+        }
+        write(destfd, buf, nread);
+    }
+
+    close(destfd);
+    close(srcfd);
+
+    if (chown(SUPP_CONFIG_FILE, AID_SYSTEM, AID_WIFI) < 0) {
+        LOGE("Error changing group ownership of %s to %d: %s",
+             SUPP_CONFIG_FILE, AID_WIFI, strerror(errno));
+        unlink(SUPP_CONFIG_FILE);
+        return -1;
+    }
+    return 0;
+}
+
+int Supplicant::setNetworkVar(int networkId, const char *var, const char *val) {
+    char reply[255];
+    size_t len = sizeof(reply) -1;
+
+    char *tmp;
+    asprintf(&tmp, "SET_NETWORK %d %s \"%s\"", networkId, var, val);
+    if (sendCommand(tmp, reply, &len)) {
+        free(tmp);
+        return -1;
+    }
+    free(tmp);
+    return 0;
+}
+
+const char *Supplicant::getNetworkVar(int networkId, const char *var,
+                                      char *buffer, size_t max) {
+    size_t len = max - 1;
+    char *tmp;
+
+    asprintf(&tmp, "GET_NETWORK %d %s", networkId, var);
+    if (sendCommand(tmp, buffer, &len)) {
+        free(tmp);
+        return NULL;
+    }
+    free(tmp);
+    return buffer;
+}
+
+int Supplicant::enableNetwork(int networkId, bool enabled) {
+    char req[64];
+
+    if (enabled)
+        sprintf(req, "ENABLE_NETWORK %d", networkId);
+    else
+        sprintf(req, "DISABLE_NETWORK %d", networkId);
+
+    char reply[16];
+    size_t len = sizeof(reply) -1;
+
+    if (sendCommand(req, reply, &len))
+        return -1;
+    return 0;
+}
+
+
+int Supplicant::retrieveInterfaceName() {
+    char reply[255];
+    size_t len = sizeof(reply) -1;
+
+    if (sendCommand("INTERFACES", reply, &len))
+        return -1;
+
+    reply[strlen(reply)-1] = '\0';
+    mInterfaceName = strdup(reply);
+    return 0;
+}
diff --git a/nexus/Supplicant.h b/nexus/Supplicant.h
new file mode 100644
index 0000000..42f2f79
--- /dev/null
+++ b/nexus/Supplicant.h
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _SUPPLICANT_H
+#define _SUPPLICANT_H
+
+struct wpa_ctrl;
+class SupplicantListener;
+class SupplicantEvent;
+class ServiceManager;
+class PropertyManager;
+class Controller;
+class WifiController;
+
+#include <pthread.h>
+
+#include "ScanResult.h"
+#include "WifiNetwork.h"
+#include "IPropertyProvider.h"
+#include "ISupplicantEventHandler.h"
+
+class Supplicant : public IPropertyProvider, public ISupplicantEventHandler {
+private:
+    struct wpa_ctrl      *mCtrl;
+    struct wpa_ctrl      *mMonitor;
+    SupplicantListener   *mListener;
+    int                  mState;
+    ServiceManager       *mServiceManager;
+    PropertyManager      *mPropMngr;
+    WifiController       *mController;
+    char                 *mInterfaceName;
+
+    ScanResultCollection *mLatestScanResults;
+    pthread_mutex_t      mLatestScanResultsLock;
+
+    WifiNetworkCollection *mNetworks;
+    pthread_mutex_t        mNetworksLock;
+ 
+public:
+    Supplicant(WifiController *wc, PropertyManager *propmngr);
+    virtual ~Supplicant();
+
+    int start();
+    int stop();
+    bool isStarted();
+
+    int triggerScan(bool active);
+    ScanResultCollection *createLatestScanResults();
+
+    WifiNetwork *createNetwork();
+    WifiNetwork *lookupNetwork(int networkId);
+    int removeNetwork(WifiNetwork *net);
+    WifiNetworkCollection *createNetworkList();
+    int refreshNetworkList();
+
+    int setNetworkVar(int networkId, const char *var, const char *value);
+    const char *getNetworkVar(int networkid, const char *var, char *buffer,
+                              size_t max);
+    int enableNetwork(int networkId, bool enabled);
+
+    int getState() { return mState; }
+    Controller *getController() { return (Controller *) mController; }
+    const char *getInterfaceName() { return mInterfaceName; }
+
+    int set(const char *name, const char *value);
+    const char *get(const char *name, char *buffer, size_t max);
+
+private:
+    int connectToSupplicant();
+    int sendCommand(const char *cmd, char *reply, size_t *reply_len);
+    int setupConfig();
+    int retrieveInterfaceName();
+
+    // ISupplicantEventHandler methods
+    virtual int onConnectedEvent(SupplicantEvent *evt);
+    virtual int onDisconnectedEvent(SupplicantEvent *evt);
+    virtual int onTerminatingEvent(SupplicantEvent *evt);
+    virtual int onPasswordChangedEvent(SupplicantEvent *evt);
+    virtual int onEapNotificationEvent(SupplicantEvent *evt);
+    virtual int onEapStartedEvent(SupplicantEvent *evt);
+    virtual int onEapMethodEvent(SupplicantEvent *evt);
+    virtual int onEapSuccessEvent(SupplicantEvent *evt);
+    virtual int onEapFailureEvent(SupplicantEvent *evt);
+    virtual int onScanResultsEvent(SupplicantEvent *evt);
+    virtual int onStateChangeEvent(SupplicantEvent *evt);
+    virtual int onLinkSpeedEvent(SupplicantEvent *evt);
+    virtual int onDriverStateEvent(SupplicantEvent *evt);
+};
+
+#endif
diff --git a/nexus/SupplicantEvent.cpp b/nexus/SupplicantEvent.cpp
new file mode 100644
index 0000000..2e6d665
--- /dev/null
+++ b/nexus/SupplicantEvent.cpp
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdlib.h>
+
+#define LOG_TAG "SupplicantEvent"
+#include <cutils/log.h>
+
+#include "SupplicantEvent.h"
+
+#include "libwpa_client/wpa_ctrl.h"
+
+SupplicantEvent::SupplicantEvent(char *event, size_t len) {
+
+    if (event[0] == '<') {
+        char *match = strchr(event, '>');
+        if (match) {
+            char tmp[16];
+
+            strncpy(tmp, &event[1], (match - event));
+            mLevel = atoi(tmp);
+            event += (match - event) + 1;
+        } else
+            LOGW("Unclosed level brace in event");
+    } else
+        LOGW("No level specified in event");
+
+    /*
+     * <N>CTRL-EVENT-XXX
+     *    ^
+     *    +---- event
+     */
+
+    if (!strncmp(event, WPA_EVENT_CONNECTED, strlen(WPA_EVENT_CONNECTED)))
+        mType = SupplicantEvent::EVENT_CONNECTED;
+    else if (!strncmp(event, WPA_EVENT_DISCONNECTED, strlen(WPA_EVENT_DISCONNECTED)))
+        mType = SupplicantEvent::EVENT_DISCONNECTED;
+    else if (!strncmp(event, WPA_EVENT_TERMINATING, strlen(WPA_EVENT_TERMINATING)))
+        mType = SupplicantEvent::EVENT_TERMINATING;
+    else if (!strncmp(event, WPA_EVENT_PASSWORD_CHANGED, strlen(WPA_EVENT_PASSWORD_CHANGED)))
+        mType = SupplicantEvent::EVENT_PASSWORD_CHANGED;
+    else if (!strncmp(event, WPA_EVENT_EAP_NOTIFICATION, strlen(WPA_EVENT_EAP_NOTIFICATION)))
+        mType = SupplicantEvent::EVENT_EAP_NOTIFICATION;
+    else if (!strncmp(event, WPA_EVENT_EAP_STARTED, strlen(WPA_EVENT_EAP_STARTED)))
+        mType = SupplicantEvent::EVENT_EAP_STARTED;
+    else if (!strncmp(event, WPA_EVENT_EAP_METHOD, strlen(WPA_EVENT_EAP_METHOD)))
+        mType = SupplicantEvent::EVENT_EAP_METHOD;
+    else if (!strncmp(event, WPA_EVENT_EAP_SUCCESS, strlen(WPA_EVENT_EAP_SUCCESS)))
+        mType = SupplicantEvent::EVENT_EAP_SUCCESS;
+    else if (!strncmp(event, WPA_EVENT_EAP_FAILURE, strlen(WPA_EVENT_EAP_FAILURE)))
+        mType = SupplicantEvent::EVENT_EAP_FAILURE;
+    else if (!strncmp(event, WPA_EVENT_SCAN_RESULTS, strlen(WPA_EVENT_SCAN_RESULTS)))
+        mType = SupplicantEvent::EVENT_SCAN_RESULTS;
+    else if (!strncmp(event, WPA_EVENT_STATE_CHANGE, strlen(WPA_EVENT_STATE_CHANGE)))
+        mType = SupplicantEvent::EVENT_STATE_CHANGE;
+    else if (!strncmp(event, WPA_EVENT_LINK_SPEED, strlen(WPA_EVENT_LINK_SPEED)))
+        mType = SupplicantEvent::EVENT_LINK_SPEED;
+    else if (!strncmp(event, WPA_EVENT_DRIVER_STATE, strlen(WPA_EVENT_DRIVER_STATE)))
+        mType = SupplicantEvent::EVENT_DRIVER_STATE;
+    else {
+        LOGW("Unknown supplicant event '%s'", event);
+        mType = SupplicantEvent::EVENT_UNKNOWN;
+    }
+
+    for (event; *event != ' '; event++);
+    event++;
+
+    /*
+     * <N>CTRL-EVENT-XXX YYYY
+     *                   ^
+     *                   +---- event
+     */
+
+    for (event; *event == ' '; event++);
+
+    mEvent = strdup(event);
+    mLen = len;
+}
+
+SupplicantEvent::~SupplicantEvent() {
+    if (mEvent)
+        free(mEvent);
+}
diff --git a/nexus/SupplicantEvent.h b/nexus/SupplicantEvent.h
new file mode 100644
index 0000000..2dc6722
--- /dev/null
+++ b/nexus/SupplicantEvent.h
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _SUPPLICANT_EVENT_H
+#define _SUPPLICANT_EVENT_H
+
+#include <sys/types.h>
+
+class SupplicantEvent {
+private:
+    int mType;
+    char *mEvent;
+    size_t mLen;
+    int mLevel;
+
+public:
+    static const int EVENT_UNKNOWN          = 0;
+    static const int EVENT_CONNECTED        = 1;
+    static const int EVENT_DISCONNECTED     = 2;
+    static const int EVENT_TERMINATING      = 3;
+    static const int EVENT_PASSWORD_CHANGED = 4;
+    static const int EVENT_EAP_NOTIFICATION = 5;
+    static const int EVENT_EAP_STARTED      = 6;
+    static const int EVENT_EAP_METHOD       = 7;
+    static const int EVENT_EAP_SUCCESS      = 8;
+    static const int EVENT_EAP_FAILURE      = 9;
+    static const int EVENT_SCAN_RESULTS     = 10;
+    static const int EVENT_STATE_CHANGE     = 11;
+    static const int EVENT_LINK_SPEED       = 12;
+    static const int EVENT_DRIVER_STATE     = 13;
+
+public:
+    SupplicantEvent(char *event, size_t len);
+    virtual ~SupplicantEvent();
+
+    int getType() { return mType; }
+    const char *getEvent() { return mEvent; }
+    int getLen() { return mLen; }
+    int getLevel() { return mLevel; }
+};
+
+#endif
diff --git a/nexus/SupplicantListener.cpp b/nexus/SupplicantListener.cpp
new file mode 100644
index 0000000..b94648b
--- /dev/null
+++ b/nexus/SupplicantListener.cpp
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <errno.h>
+#include <sys/types.h>
+#include <pthread.h>
+
+#define LOG_TAG "SupplicantListener"
+#include <cutils/log.h>
+
+#include "libwpa_client/wpa_ctrl.h"
+
+#include "SupplicantListener.h"
+#include "SupplicantEvent.h"
+#include "ISupplicantEventHandler.h"
+
+SupplicantListener::SupplicantListener(ISupplicantEventHandler *handlers, 
+                                       struct wpa_ctrl *monitor) :
+                    SocketListener(wpa_ctrl_get_fd(monitor), false) {
+    mHandlers = handlers;
+    mMonitor = monitor;
+}
+
+bool SupplicantListener::onDataAvailable(SocketClient *cli) {
+    char buf[255];
+    size_t buflen = sizeof(buf);
+    int rc;
+    size_t nread = buflen - 1;
+
+    if ((rc = wpa_ctrl_recv(mMonitor, buf, &nread))) {
+        LOGE("wpa_ctrl_recv failed (%s)", strerror(errno));
+        return false;
+    }
+
+    buf[nread] = '\0';
+    if (!rc && !nread) {
+        LOGD("Received EOF on supplicant socket\n");
+        strncpy(buf, WPA_EVENT_TERMINATING " - signal 0 received", buflen-1);
+        buf[buflen-1] = '\0';
+        return false;
+    }
+
+    SupplicantEvent *evt = new SupplicantEvent(buf, nread);
+
+    // XXX: Make this a factory
+    // XXX: Instead of calling Supplicant directly
+    // extract an Interface and use that instead
+    if (evt->getType() == SupplicantEvent::EVENT_CONNECTED)
+        rc = mHandlers->onConnectedEvent(evt);
+    else if (evt->getType() == SupplicantEvent::EVENT_DISCONNECTED)
+        rc = mHandlers->onDisconnectedEvent(evt);
+    else if (evt->getType() == SupplicantEvent::EVENT_TERMINATING)
+        rc = mHandlers->onTerminatingEvent(evt);
+    else if (evt->getType() == SupplicantEvent::EVENT_PASSWORD_CHANGED)
+        rc = mHandlers->onPasswordChangedEvent(evt);
+    else if (evt->getType() == SupplicantEvent::EVENT_EAP_NOTIFICATION)
+        rc = mHandlers->onEapNotificationEvent(evt);
+    else if (evt->getType() == SupplicantEvent::EVENT_EAP_STARTED)
+        rc = mHandlers->onEapStartedEvent(evt);
+    else if (evt->getType() == SupplicantEvent::EVENT_EAP_SUCCESS)
+        rc = mHandlers->onEapSuccessEvent(evt);
+    else if (evt->getType() == SupplicantEvent::EVENT_EAP_FAILURE)
+        rc = mHandlers->onEapFailureEvent(evt);
+    else if (evt->getType() == SupplicantEvent::EVENT_SCAN_RESULTS)
+        rc = mHandlers->onScanResultsEvent(evt);
+    else if (evt->getType() == SupplicantEvent::EVENT_STATE_CHANGE)
+        rc = mHandlers->onStateChangeEvent(evt);
+    else if (evt->getType() == SupplicantEvent::EVENT_LINK_SPEED)
+        rc = mHandlers->onLinkSpeedEvent(evt);
+    else if (evt->getType() == SupplicantEvent::EVENT_DRIVER_STATE)
+        rc = mHandlers->onDriverStateEvent(evt);
+    else {
+        LOGW("Ignoring unknown event");
+    }
+
+    delete evt;
+
+    if (rc) {
+        LOGW("Handler %d (%s) error: %s", evt->getType(), evt->getEvent(), strerror(errno));
+        return false;
+    }
+    return true;
+}
diff --git a/nexus/SupplicantListener.h b/nexus/SupplicantListener.h
new file mode 100644
index 0000000..3d186ad
--- /dev/null
+++ b/nexus/SupplicantListener.h
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _SUPPLICANTLISTENER_H__
+#define _SUPPLICANTLISTENER_H__
+
+#include <sysutils/SocketListener.h>
+
+struct wpa_ctrl;
+class Supplicant;
+class SocketClient;
+class ISupplicantEventHandler;
+
+class SupplicantListener: public SocketListener {
+private:
+    struct wpa_ctrl         *mMonitor;
+    ISupplicantEventHandler *mHandlers;
+
+public:
+    SupplicantListener(ISupplicantEventHandler *handlers,
+                       struct wpa_ctrl *monitor);
+    virtual ~SupplicantListener() {}
+
+    struct wpa_ctrl *getMonitor() { return mMonitor; }
+
+protected:
+    virtual bool onDataAvailable(SocketClient *c);
+};
+
+#endif
diff --git a/nexus/SupplicantState.cpp b/nexus/SupplicantState.cpp
new file mode 100644
index 0000000..a16d370
--- /dev/null
+++ b/nexus/SupplicantState.cpp
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+
+#define LOG_TAG "SupplicantState"
+#include <cutils/log.h>
+
+#include "SupplicantState.h"
+
+char *SupplicantState::toString(int val, char *buffer, int max) {
+    if (val == SupplicantState::UNKNOWN)
+        strncpy(buffer, "Unknown", max);
+    else if (val == SupplicantState::DISCONNECTED)
+        strncpy(buffer, "Disconnected", max);
+    else if (val == SupplicantState::INACTIVE)
+        strncpy(buffer, "Inactive", max);
+    else if (val == SupplicantState::SCANNING)
+        strncpy(buffer, "Scanning", max);
+    else if (val == SupplicantState::ASSOCIATING)
+        strncpy(buffer, "Associating", max);
+    else if (val == SupplicantState::ASSOCIATED)
+        strncpy(buffer, "Associated", max);
+    else if (val == SupplicantState::FOURWAY_HANDSHAKE)
+        strncpy(buffer, "Fourway Handshake", max);
+    else if (val == SupplicantState::GROUP_HANDSHAKE)
+        strncpy(buffer, "Group Handshake", max);
+    else if (val == SupplicantState::COMPLETED)
+        strncpy(buffer, "Completed", max);
+    else if (val == SupplicantState::IDLE)
+        strncpy(buffer, "Idle", max);
+    else
+        strncpy(buffer, "(internal error)", max);
+
+    return buffer;
+}
diff --git a/nexus/SupplicantState.h b/nexus/SupplicantState.h
new file mode 100644
index 0000000..6882f0c
--- /dev/null
+++ b/nexus/SupplicantState.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _SUPPLICANT_STATE_H
+#define _SUPPLICANT_STATE_H
+
+class SupplicantState {
+public:
+    static const int UNKNOWN           = -1;
+    static const int DISCONNECTED      = 0;
+    static const int INACTIVE          = 1;
+    static const int SCANNING          = 2;
+    static const int ASSOCIATING       = 3;
+    static const int ASSOCIATED        = 4;
+    static const int FOURWAY_HANDSHAKE = 5;
+    static const int GROUP_HANDSHAKE   = 6;
+    static const int COMPLETED         = 7;
+    static const int IDLE              = 8;
+
+    static char *toString(int val, char *buffer, int max);
+};
+
+#endif
diff --git a/nexus/TiwlanWifiController.cpp b/nexus/TiwlanWifiController.cpp
new file mode 100644
index 0000000..307c48c
--- /dev/null
+++ b/nexus/TiwlanWifiController.cpp
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdlib.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <string.h>
+
+#include <cutils/properties.h>
+#define LOG_TAG "TiwlanWifiController"
+#include <cutils/log.h>
+
+#include "PropertyManager.h"
+#include "TiwlanWifiController.h"
+
+#define DRIVER_PROP_NAME "wlan.driver.status"
+
+extern "C" int sched_yield(void);
+
+TiwlanWifiController::TiwlanWifiController(PropertyManager *propmngr, char *modpath, char *modname, char *modargs) :
+                      WifiController(propmngr, modpath, modname, modargs) {
+}
+
+int TiwlanWifiController::powerUp() {
+    return 0; // Powerup is currently done when the driver is loaded
+}
+
+int TiwlanWifiController::powerDown() {
+    return 0; // Powerdown is currently done when the driver is unloaded
+}
+
+bool TiwlanWifiController::isPoweredUp() {
+    return isKernelModuleLoaded(getModuleName());
+}
+
+int TiwlanWifiController::loadFirmware() {
+    char driver_status[PROPERTY_VALUE_MAX];
+    int count = 100;
+
+    property_set("ctl.start", "wlan_loader");
+    sched_yield();
+
+    // Wait for driver to be ready
+    while (count-- > 0) {
+        if (property_get(DRIVER_PROP_NAME, driver_status, NULL)) {
+            if (strcmp(driver_status, "ok") == 0)
+                return 0;
+            else if (strcmp(DRIVER_PROP_NAME, "failed") == 0)
+                return -1;
+        }
+        usleep(200000);
+    }
+    property_set(DRIVER_PROP_NAME, "timeout");
+    return -1;
+}
+
+bool TiwlanWifiController::isFirmwareLoaded() {
+    // Always load the firmware
+    return false;
+}
diff --git a/nexus/TiwlanWifiController.h b/nexus/TiwlanWifiController.h
new file mode 100644
index 0000000..d3ebe88
--- /dev/null
+++ b/nexus/TiwlanWifiController.h
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _TIWLAN_WIFI_CONTROLLER_H
+#define _TIWLAN_WIFI_CONTROLLER_H
+
+#include "PropertyManager.h"
+#include "WifiController.h"
+
+class TiwlanWifiController : public WifiController {
+public:
+    TiwlanWifiController(PropertyManager *propmngr, char *modpath, char *modname, char *modargs);
+    virtual ~TiwlanWifiController() {}
+
+    virtual int powerUp();
+    virtual int powerDown();
+    virtual bool isPoweredUp();
+    virtual int loadFirmware();
+    virtual bool isFirmwareLoaded();
+};
+#endif
diff --git a/nexus/VpnController.cpp b/nexus/VpnController.cpp
new file mode 100644
index 0000000..1246703
--- /dev/null
+++ b/nexus/VpnController.cpp
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+#include "PropertyManager.h"
+#include "VpnController.h"
+
+VpnController::VpnController(PropertyManager *propmngr) :
+               Controller("VPN", propmngr) {
+    mEnabled = false;
+    propmngr->registerProperty("vpn.enabled", this);
+    propmngr->registerProperty("vpn.gateway", this);
+}
+
+int VpnController::start() {
+    return 0;
+}
+
+int VpnController::stop() {
+    return 0;
+}
+
+int VpnController::set(const char *name, const char *value) {
+    if (!strcmp(name, "vpn.enabled")) {
+        int en = atoi(value);
+        int rc;
+
+        if (en == mEnabled)
+            return 0;
+        rc = (en ? enable() : disable());
+
+        if (!rc)
+            mEnabled = en;
+        return rc;
+    } if (!strcmp(name, "vpn.gateway")) {
+        if (!inet_aton(value, &mVpnGateway)) {
+            errno = EINVAL;
+            return -1;
+        }
+        return 0;
+    }
+
+    return Controller::set(name, value);
+}
+
+const char *VpnController::get(const char *name, char *buffer, size_t maxsize) {
+    if (!strcmp(name, "vpn.enabled")) {
+        snprintf(buffer, maxsize, "%d", mEnabled);
+        return buffer;
+    } if (!strcmp(name, "vpn.gateway")) {
+        snprintf(buffer, maxsize, "%s", inet_ntoa(mVpnGateway));
+        return buffer;
+    }
+
+    return Controller::get(name, buffer, maxsize);
+}
diff --git a/nexus/VpnController.h b/nexus/VpnController.h
new file mode 100644
index 0000000..b36856f
--- /dev/null
+++ b/nexus/VpnController.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _VPN_CONTROLLER_H
+#define _VPN_CONTROLLER_H
+
+#include <netinet/in.h>
+
+#include "Controller.h"
+
+class VpnController : public Controller {
+    bool           mEnabled;
+    /*
+     * Gateway of the VPN server to connect to
+     */
+    struct in_addr mVpnGateway;
+
+public:
+    VpnController(PropertyManager *propmngr);
+    virtual ~VpnController() {}
+
+    virtual int start();
+    virtual int stop();
+
+    virtual int set(const char *name, const char *value);
+    virtual const char *get(const char *name, char *buffer, size_t maxlen);
+
+protected:
+    virtual int enable() = 0;
+    virtual int disable() = 0;
+
+};
+
+#endif
diff --git a/nexus/WifiController.cpp b/nexus/WifiController.cpp
new file mode 100644
index 0000000..3d06806
--- /dev/null
+++ b/nexus/WifiController.cpp
@@ -0,0 +1,229 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+#define LOG_TAG "WifiController"
+#include <cutils/log.h>
+
+#include "Supplicant.h"
+#include "WifiController.h"
+#include "WifiScanner.h"
+#include "NetworkManager.h"
+#include "ErrorCode.h"
+#include "WifiNetwork.h"
+
+WifiController::WifiController(PropertyManager *propmngr, char *modpath, char *modname, char *modargs) :
+                Controller("WIFI", propmngr) {
+    strncpy(mModulePath, modpath, sizeof(mModulePath));
+    strncpy(mModuleName, modname, sizeof(mModuleName));
+    strncpy(mModuleArgs, modargs, sizeof(mModuleArgs));
+
+    mSupplicant = new Supplicant(this, propmngr);
+    mScanner = new WifiScanner(mSupplicant, 10);
+    mCurrentScanMode = 0;
+
+    mEnabled = false;
+
+    propmngr->registerProperty("wifi.enabled", this);
+}
+
+int WifiController::start() {
+    return 0;
+}
+
+int WifiController::stop() {
+    errno = ENOSYS;
+    return -1;
+}
+
+int WifiController::enable() {
+    if (!isPoweredUp()) {
+        sendStatusBroadcast("POWERING_UP");
+        if (powerUp()) {
+            LOGE("Powerup failed (%s)", strerror(errno));
+            return -1;
+        }
+    }
+
+    if (mModuleName[0] != '\0' && !isKernelModuleLoaded(mModuleName)) {
+        sendStatusBroadcast("LOADING_DRIVER");
+        if (loadKernelModule(mModulePath, mModuleArgs)) {
+            LOGE("Kernel module load failed (%s)", strerror(errno));
+            goto out_powerdown;
+        }
+    }
+
+    if (!isFirmwareLoaded()) {
+        sendStatusBroadcast("LOADING_FIRMWARE");
+        if (loadFirmware()) {
+            LOGE("Firmware load failed (%s)", strerror(errno));
+            goto out_powerdown;
+        }
+    }
+
+    if (!mSupplicant->isStarted()) {
+        sendStatusBroadcast("STARTING_SUPPLICANT");
+        if (mSupplicant->start()) {
+            LOGE("Supplicant start failed (%s)", strerror(errno));
+            goto out_unloadmodule;
+        }
+    }
+
+    if (Controller::bindInterface(mSupplicant->getInterfaceName())) {
+        LOGE("Error binding interface (%s)", strerror(errno));
+        goto out_unloadmodule;
+    }
+
+    if (mSupplicant->refreshNetworkList())
+        LOGW("Error getting list of networks (%s)", strerror(errno));
+
+    mPropMngr->registerProperty("wifi.scanmode", this);
+    mPropMngr->registerProperty("wifi.interface", this);
+
+    return 0;
+
+out_unloadmodule:
+    if (mModuleName[0] != '\0' && !isKernelModuleLoaded(mModuleName)) {
+        if (unloadKernelModule(mModuleName)) {
+            LOGE("Unable to unload module after failure!");
+        }
+    }
+
+out_powerdown:
+    if (powerDown()) {
+        LOGE("Unable to powerdown after failure!");
+    }
+    return -1;
+}
+
+void WifiController::sendStatusBroadcast(const char *msg) {
+    NetworkManager::Instance()->
+                    getBroadcaster()->
+                    sendBroadcast(ErrorCode::UnsolicitedInformational, msg, false);
+}
+
+int WifiController::disable() {
+
+    mPropMngr->unregisterProperty("wifi.scanmode");
+    if (mSupplicant->isStarted()) {
+        sendStatusBroadcast("STOPPING_SUPPLICANT");
+        if (mSupplicant->stop()) {
+            LOGE("Supplicant stop failed (%s)", strerror(errno));
+            return -1;
+        }
+    } else
+        LOGW("disable(): Supplicant not running?");
+
+    if (mModuleName[0] != '\0' && isKernelModuleLoaded(mModuleName)) {
+        sendStatusBroadcast("UNLOADING_DRIVER");
+        if (unloadKernelModule(mModuleName)) {
+            LOGE("Unable to unload module (%s)", strerror(errno));
+            return -1;
+        }
+    }
+
+    if (isPoweredUp()) {
+        sendStatusBroadcast("POWERING_DOWN");
+        if (powerDown()) {
+            LOGE("Powerdown failed (%s)", strerror(errno));
+            return -1;
+        }
+    }
+    return 0;
+}
+
+int WifiController::loadFirmware() {
+    return 0;
+}
+
+int WifiController::setScanMode(uint32_t mode) {
+    int rc = 0;
+
+    if (mCurrentScanMode == mode)
+        return 0;
+
+    if (!(mode & SCAN_ENABLE_MASK)) {
+        if (mCurrentScanMode & SCAN_REPEAT_MASK)
+            mScanner->stop();
+    } else if (mode & SCAN_REPEAT_MASK)
+        rc = mScanner->start(mode & SCAN_ACTIVE_MASK);
+    else
+        rc = mSupplicant->triggerScan(mode & SCAN_ACTIVE_MASK);
+
+    mCurrentScanMode = mode;
+    return rc;
+}
+
+WifiNetwork *WifiController::createNetwork() {
+    WifiNetwork *wn = mSupplicant->createNetwork();
+    return wn;
+}
+
+int WifiController::removeNetwork(int networkId) {
+    WifiNetwork *wn = mSupplicant->lookupNetwork(networkId);
+
+    if (!wn)
+        return -1;
+    return mSupplicant->removeNetwork(wn);
+}
+
+ScanResultCollection *WifiController::createScanResults() {
+    return mSupplicant->createLatestScanResults();
+}
+
+WifiNetworkCollection *WifiController::createNetworkList() {
+    return mSupplicant->createNetworkList();
+}
+
+int WifiController::set(const char *name, const char *value) {
+    int rc;
+
+    if (!strcmp(name, "wifi.enabled")) {
+        int en = atoi(value);
+
+        if (en == mEnabled)
+            return 0;
+        rc = (en ? enable() : disable());
+        if (!rc)
+            mEnabled = en;
+    } else if (!strcmp(name, "wifi.interface")) {
+        errno = EROFS;
+        return -1;
+    } else if (!strcmp(name, "wifi.scanmode"))
+        return setScanMode((uint32_t) strtoul(value, NULL, 0));
+    else
+        return Controller::set(name, value);
+    return rc;
+}
+
+const char *WifiController::get(const char *name, char *buffer, size_t maxsize) {
+
+    if (!strcmp(name, "wifi.enabled"))
+        snprintf(buffer, maxsize, "%d", mEnabled);
+    else if (!strcmp(name, "wifi.interface")) {
+        snprintf(buffer, maxsize, "%s",
+                 (getBoundInterface() ? getBoundInterface() : "none"));
+    } else if (!strcmp(name, "wifi.scanmode"))
+        snprintf(buffer, maxsize, "0x%.8x", mCurrentScanMode);
+    else
+        return Controller::get(name, buffer, maxsize);
+
+    return buffer;
+}
+
diff --git a/nexus/WifiController.h b/nexus/WifiController.h
new file mode 100644
index 0000000..b2f4530
--- /dev/null
+++ b/nexus/WifiController.h
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _WIFI_CONTROLLER_H
+#define _WIFI_CONTROLLER_H
+
+#include <sys/types.h>
+
+#include "Controller.h"
+
+class NetInterface;
+class Supplicant;
+class WifiScanner;
+
+#include "ScanResult.h"
+#include "WifiNetwork.h"
+
+class WifiController : public Controller {
+public:
+    static const uint32_t SCAN_ENABLE_MASK       = 0x01;
+    static const uint32_t SCAN_ACTIVE_MASK       = 0x02;
+    static const uint32_t SCAN_REPEAT_MASK       = 0x04;
+
+    static const uint32_t SCANMODE_NONE               = 0;
+    static const uint32_t SCANMODE_PASSIVE_ONESHOT    = SCAN_ENABLE_MASK;
+    static const uint32_t SCANMODE_PASSIVE_CONTINUOUS = SCAN_ENABLE_MASK | SCAN_REPEAT_MASK;
+    static const uint32_t SCANMODE_ACTIVE_ONESHOT     = SCAN_ENABLE_MASK | SCAN_ACTIVE_MASK;
+    static const uint32_t SCANMODE_ACTIVE_CONTINUOUS  = SCAN_ENABLE_MASK | SCAN_ACTIVE_MASK | SCAN_REPEAT_MASK;
+
+private:
+    Supplicant *mSupplicant;
+    char        mModulePath[255];
+    char        mModuleName[64];
+    char        mModuleArgs[255];
+    uint32_t    mCurrentScanMode;
+    WifiScanner *mScanner;
+    bool        mEnabled;
+
+public:
+    WifiController(PropertyManager *propmngr, char *modpath, char *modname, char *modargs);
+    virtual ~WifiController() {}
+
+    int start();
+    int stop();
+
+    WifiNetwork *createNetwork();
+    int removeNetwork(int networkId);
+    WifiNetworkCollection *createNetworkList();
+
+    virtual int set(const char *name, const char *value);
+    virtual const char *get(const char *name, char *buffer, size_t maxlen);
+
+    ScanResultCollection *createScanResults();
+
+    char *getModulePath() { return mModulePath; }
+    char *getModuleName() { return mModuleName; }
+    char *getModuleArgs() { return mModuleArgs; }
+
+    Supplicant *getSupplicant() { return mSupplicant; }
+
+protected:
+    // Move this crap into a 'driver'
+    virtual int powerUp() = 0;
+    virtual int powerDown() = 0;
+    virtual int loadFirmware();
+
+    virtual bool isFirmwareLoaded() = 0;
+    virtual bool isPoweredUp() = 0;
+
+private:
+    void sendStatusBroadcast(const char *msg);
+    int setScanMode(uint32_t mode);
+    int enable();
+    int disable();
+};
+
+#endif
diff --git a/nexus/WifiNetwork.cpp b/nexus/WifiNetwork.cpp
new file mode 100644
index 0000000..818b91d
--- /dev/null
+++ b/nexus/WifiNetwork.cpp
@@ -0,0 +1,600 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+#include <sys/types.h>
+
+#define LOG_TAG "WifiNetwork"
+#include <cutils/log.h>
+
+#include "NetworkManager.h"
+#include "WifiNetwork.h"
+#include "Supplicant.h"
+#include "WifiController.h"
+#include "InterfaceConfig.h"
+
+const char *WifiNetwork::PropertyNames[] = { "ssid", "bssid", "psk", "wepkey.1",
+                                             "wepkey.2", "wepkey.3", "wepkey.4",
+                                             "defkeyidx", "pri", "hiddenssid",
+                                             "AllowedKeyManagement",
+                                             "AllowedProtocols",
+                                             "AllowedAuthAlgorithms",
+                                             "AllowedPairwiseCiphers",
+                                             "AllowedGroupCiphers",
+                                             "enabled", '\0' };
+WifiNetwork::WifiNetwork() {
+   // This is private to restrict copy constructors
+}
+
+WifiNetwork::WifiNetwork(WifiController *c, Supplicant *suppl, const char *data) {
+    mController = c;
+    mSuppl = suppl;
+
+    char *tmp = strdup(data);
+    char *next = tmp;
+    char *id;
+    char *ssid;
+    char *bssid;
+    char *flags;
+
+    if (!(id = strsep(&next, "\t")))
+        LOGE("Failed to extract network id");
+    if (!(ssid = strsep(&next, "\t")))
+        LOGE("Failed to extract ssid");
+    if (!(bssid = strsep(&next, "\t")))
+        LOGE("Failed to extract bssid");
+    if (!(flags = strsep(&next, "\t")))
+        LOGE("Failed to extract flags");
+
+   // LOGD("id '%s', ssid '%s', bssid '%s', flags '%s'", id, ssid, bssid,
+   //      flags ? flags :"null");
+
+    if (id)
+        mNetid = atoi(id);
+    if (ssid)
+        mSsid = strdup(ssid);
+    if (bssid)
+        mBssid = strdup(bssid);
+
+    mPsk = NULL;
+    memset(mWepKeys, 0, sizeof(mWepKeys));
+    mDefaultKeyIndex = -1;
+    mPriority = -1;
+    mHiddenSsid = NULL;
+    mAllowedKeyManagement = 0;
+    mAllowedProtocols = 0;
+    mAllowedAuthAlgorithms = 0;
+    mAllowedPairwiseCiphers = 0;
+    mAllowedGroupCiphers = 0;
+    mEnabled = true;
+
+    if (flags && flags[0] != '\0') {
+        if (!strcmp(flags, "[DISABLED]"))
+            mEnabled = false;
+        else
+            LOGW("Unsupported flags '%s'", flags);
+    }
+
+    char *tmp2;
+    asprintf(&tmp2, "wifi.net.%d", mNetid);
+    mIfaceCfg = new InterfaceConfig(tmp2);
+    free(tmp2);
+
+    registerProperties();
+    free(tmp);
+}
+
+WifiNetwork::WifiNetwork(WifiController *c, Supplicant *suppl, int networkId) {
+    mController = c;
+    mSuppl = suppl;
+    mNetid = networkId;
+    mSsid = NULL;
+    mBssid = NULL;
+    mPsk = NULL;
+    memset(mWepKeys, 0, sizeof(mWepKeys));
+    mDefaultKeyIndex = -1;
+    mPriority = -1;
+    mHiddenSsid = NULL;
+    mAllowedKeyManagement = 0;
+    mAllowedProtocols = 0;
+    mAllowedAuthAlgorithms = 0;
+    mAllowedPairwiseCiphers = 0;
+    mAllowedGroupCiphers = 0;
+    mEnabled = false;
+
+    char *tmp2;
+    asprintf(&tmp2, "wifi.net.%d", mNetid);
+    mIfaceCfg = new InterfaceConfig(tmp2);
+    free(tmp2);
+
+    registerProperties();
+}
+
+WifiNetwork *WifiNetwork::clone() {
+    WifiNetwork *r = new WifiNetwork();
+
+    r->mSuppl = mSuppl;
+    r->mNetid = mNetid;
+
+    if (mSsid)
+        r->mSsid = strdup(mSsid);
+    if (mBssid)
+        r->mBssid = strdup(mBssid);
+    if (mPsk)
+        r->mPsk = strdup(mPsk);
+
+    r->mController = mController;
+    memcpy(r->mWepKeys, mWepKeys, sizeof(mWepKeys));
+    r->mDefaultKeyIndex = mDefaultKeyIndex;
+    r->mPriority = mPriority;
+    if (mHiddenSsid)
+        r->mHiddenSsid = strdup(mHiddenSsid);
+    r->mAllowedKeyManagement = mAllowedKeyManagement;
+    r->mAllowedProtocols = mAllowedProtocols;
+    r->mAllowedAuthAlgorithms = mAllowedAuthAlgorithms;
+    r->mAllowedPairwiseCiphers = mAllowedPairwiseCiphers;
+    r->mAllowedGroupCiphers = mAllowedGroupCiphers;
+    return r;
+}
+
+WifiNetwork::~WifiNetwork() {
+    unregisterProperties();
+    if (mSsid)
+        free(mSsid);
+    if (mBssid)
+        free(mBssid);
+    if (mPsk)
+        free(mPsk);
+    for (int i = 0; i < 4; i++) {
+        if (mWepKeys[i])
+            free(mWepKeys[i]);
+    }
+
+    if (mHiddenSsid)
+        free(mHiddenSsid);
+    if (mIfaceCfg)
+        delete(mIfaceCfg);
+}
+
+int WifiNetwork::refresh() {
+    char buffer[255];
+    size_t len;
+
+    len = sizeof(buffer);
+    if (mSuppl->getNetworkVar(mNetid, "psk", buffer, len))
+        mPsk = strdup(buffer);
+
+    for (int i = 0; i < 4; i++) {
+        char *name;
+
+        asprintf(&name, "wep_key%d", i);
+        len = sizeof(buffer);
+        if (mSuppl->getNetworkVar(mNetid, name, buffer, len))
+            mWepKeys[i] = strdup(buffer);
+        free(name);
+    }
+
+    len = sizeof(buffer);
+    if (mSuppl->getNetworkVar(mNetid, "wep_tx_keyidx", buffer, len))
+        mDefaultKeyIndex = atoi(buffer);
+
+    len = sizeof(buffer);
+    if (mSuppl->getNetworkVar(mNetid, "priority", buffer, len))
+        mPriority = atoi(buffer);
+
+    len = sizeof(buffer);
+    if (mSuppl->getNetworkVar(mNetid, "scan_ssid", buffer, len))
+        mHiddenSsid = strdup(buffer);
+
+    len = sizeof(buffer);
+    if (mSuppl->getNetworkVar(mNetid, "key_mgmt", buffer, len)) {
+        // TODO
+    }
+
+    len = sizeof(buffer);
+    if (mSuppl->getNetworkVar(mNetid, "proto", buffer, len)) {
+        // TODO
+    }
+
+    len = sizeof(buffer);
+    if (mSuppl->getNetworkVar(mNetid, "auth_alg", buffer, len)) {
+        // TODO
+    }
+
+    len = sizeof(buffer);
+    if (mSuppl->getNetworkVar(mNetid, "pairwise", buffer, len)) {
+        // TODO
+    }
+
+    len = sizeof(buffer);
+    if (mSuppl->getNetworkVar(mNetid, "group", buffer, len)) {
+        // TODO
+    }
+
+    return 0;
+out_err:
+    LOGE("Refresh failed (%s)",strerror(errno));
+    return -1;
+}
+
+int WifiNetwork::set(const char *name, const char *value) {
+    char *n_tmp = strdup(name + strlen("wifi.net."));
+    char *n_next = n_tmp;
+    char *n_local;
+    char *n_rest;
+    int rc = 0;
+
+    if (!strsep(&n_next, ".")) // skip net id
+        goto out_inval;
+
+    if (!(n_local = strsep(&n_next, ".")))
+        goto out_inval;
+
+    n_rest = n_next;
+
+//    LOGD("set(): var '%s'(%s / %s) = %s", name, n_local, n_rest, value);
+    if (!strcasecmp(n_local, "enabled"))
+        rc = setEnabled(atoi(value));
+    else if (!strcmp(n_local, "ssid"))
+        rc = setSsid(value);
+    else if (!strcasecmp(n_local, "bssid"))
+        rc = setBssid(value);
+    else if (!strcasecmp(n_local, "psk"))
+        rc = setPsk(value);
+    else if (!strcasecmp(n_local, "wepkey"))
+        rc = setWepKey(atoi(n_rest) -1, value);
+    else if (!strcasecmp(n_local, "defkeyidx"))
+        rc = setDefaultKeyIndex(atoi(value));
+    else if (!strcasecmp(n_local, "pri"))
+        rc = setPriority(atoi(value));
+    else if (!strcasecmp(n_local, "hiddenssid"))
+        rc = setHiddenSsid(value);
+    else if (!strcasecmp(n_local, "AllowedKeyManagement")) {
+        uint32_t mask = 0;
+        bool none = false;
+        char *v_tmp = strdup(value);
+        char *v_next = v_tmp;
+        char *v_token;
+
+        while((v_token = strsep(&v_next, " "))) {
+            if (!strcasecmp(v_token, "NONE")) {
+                mask = 0;
+                none = true;
+            } else if (!none) {
+                if (!strcasecmp(v_token, "WPA_PSK"))
+                    mask |= KeyManagementMask::WPA_PSK;
+                else if (!strcasecmp(v_token, "WPA_EAP"))
+                    mask |= KeyManagementMask::WPA_EAP;
+                else if (!strcasecmp(v_token, "IEEE8021X"))
+                    mask |= KeyManagementMask::IEEE8021X;
+                else {
+                    errno = EINVAL;
+                    rc = -1;
+                    free(v_tmp);
+                    goto out;
+                }
+            } else {
+                errno = EINVAL;
+                rc = -1;
+                free(v_tmp);
+                goto out;
+            }
+        }
+        free(v_tmp);
+    } else if (!strcasecmp(n_local, "AllowedProtocols")) {
+        // TODO
+    } else if (!strcasecmp(n_local, "AllowedPairwiseCiphers")) {
+        // TODO
+    } else if (!strcasecmp(n_local, "AllowedAuthAlgorithms")) {
+        // TODO
+    } else if (!strcasecmp(n_local, "AllowedGroupCiphers")) {
+        // TODO
+    } else {
+        errno = ENOENT;
+        free(n_tmp);
+        return -1;
+    }
+
+out:
+    free(n_tmp);
+    return rc;
+
+out_inval:
+    errno = EINVAL;
+    free(n_tmp);
+    return -1;
+}
+
+const char *WifiNetwork::get(const char *name, char *buffer, size_t maxsize) {
+    char *n_tmp = strdup(name + strlen("wifi.net."));
+    char *n_next = n_tmp;
+    char *n_local;
+    char fc[64];
+    char rc[128];
+
+    if (!strsep(&n_next, ".")) // skip net id
+        goto out_inval;
+
+    if (!(n_local = strsep(&n_next, ".")))
+        goto out_inval;
+
+
+    strncpy(fc, n_local, sizeof(fc));
+    rc[0] = '\0';
+    if (n_next)
+        strncpy(rc, n_next, sizeof(rc));
+
+    free(n_tmp);
+
+    if (!strcasecmp(fc, "enabled"))
+        snprintf(buffer, maxsize, "%d", getEnabled());
+    else if (!strcasecmp(fc, "ssid")) {
+        strncpy(buffer,
+                getSsid() ? getSsid() : "none",
+                maxsize);
+    } else if (!strcasecmp(fc, "bssid")) {
+        strncpy(buffer,
+                getBssid() ? getBssid() : "none",
+                maxsize);
+    } else if (!strcasecmp(fc, "psk")) {
+        strncpy(buffer,
+                getPsk() ? getPsk() : "none",
+                maxsize);
+    } else if (!strcasecmp(fc, "wepkey")) {
+        strncpy(buffer,
+                getWepKey(atoi(rc)-1) ? getWepKey(atoi(rc)-1) : "none",
+                maxsize);
+    } else if (!strcasecmp(fc, "defkeyidx"))
+        snprintf(buffer, maxsize, "%d", getDefaultKeyIndex());
+    else if (!strcasecmp(fc, "pri"))
+        snprintf(buffer, maxsize, "%d", getPriority());
+    else if (!strcasecmp(fc, "hiddenssid")) {
+        strncpy(buffer,
+                getHiddenSsid() ? getHiddenSsid() : "none",
+                maxsize);
+    } else {
+        strncpy(buffer, "(internal error)", maxsize);
+        errno = ENOENT;
+        return NULL;
+    }
+
+    return buffer;
+
+out_inval:
+    errno = EINVAL;
+    free(n_tmp);
+    return NULL;
+}
+
+int WifiNetwork::setSsid(const char *ssid) {
+    if (mSuppl->setNetworkVar(mNetid, "ssid", ssid))
+        return -1;
+    if (mSsid)
+        free(mSsid);
+    mSsid = strdup(ssid);
+    return 0;
+}
+
+int WifiNetwork::setBssid(const char *bssid) {
+    if (mSuppl->setNetworkVar(mNetid, "bssid", bssid))
+        return -1;
+    if (mBssid)
+        free(mBssid);
+    mBssid = strdup(bssid);
+    return 0;
+}
+
+int WifiNetwork::setPsk(const char *psk) {
+    if (mSuppl->setNetworkVar(mNetid, "psk", psk))
+        return -1;
+
+    if (mPsk)
+        free(mPsk);
+    mPsk = strdup(psk);
+    return 0;
+}
+
+int WifiNetwork::setWepKey(int idx, const char *key) {
+    char *name;
+
+    asprintf(&name, "wep_key%d", idx);
+    int rc = mSuppl->setNetworkVar(mNetid, name, key);
+    free(name);
+
+    if (rc)
+        return -1;
+
+    if (mWepKeys[idx])
+        free(mWepKeys[idx]);
+    mWepKeys[idx] = strdup(key);
+    return 0;
+}
+
+int WifiNetwork::setDefaultKeyIndex(int idx) {
+    char val[16];
+    sprintf(val, "%d", idx);
+    if (mSuppl->setNetworkVar(mNetid, "wep_tx_keyidx", val))
+        return -1;
+
+    mDefaultKeyIndex = idx;
+    return 0;
+}
+
+int WifiNetwork::setPriority(int priority) {
+    char val[16];
+    sprintf(val, "%d", priority);
+    if (mSuppl->setNetworkVar(mNetid, "priority", val))
+        return -1;
+
+    mPriority = priority;
+    return 0;
+}
+
+int WifiNetwork::setHiddenSsid(const char *ssid) {
+    if (mSuppl->setNetworkVar(mNetid, "scan_ssid", ssid))
+        return -1;
+
+    if (mHiddenSsid)
+        free(mHiddenSsid);
+    mHiddenSsid = strdup(ssid);
+    return 0;
+}
+
+int WifiNetwork::setAllowedKeyManagement(uint32_t mask) {
+    char accum[255];
+
+    if (mask == KeyManagementMask::NONE)
+        strcpy(accum, "NONE");
+    else {
+        if (mask & KeyManagementMask::WPA_PSK)
+            strcat(accum, "WPA_PSK ");
+        if (mask & KeyManagementMask::WPA_EAP)
+            strcat(accum, "WPA_EAP ");
+        if (mask & KeyManagementMask::IEEE8021X)
+            strcat(accum, "IEEE8021X ");
+    }
+
+    if (mSuppl->setNetworkVar(mNetid, "key_mgmt", accum))
+        return -1;
+    mAllowedKeyManagement = mask;
+    return 0;
+}
+
+int WifiNetwork::setAllowedProtocols(uint32_t mask) {
+    char accum[255];
+
+    accum[0] = '\0';
+
+    if (mask & SecurityProtocolMask::WPA)
+        strcpy(accum, "WPA ");
+
+    if (mask & SecurityProtocolMask::RSN)
+        strcat(accum, "RSN");
+
+    if (mSuppl->setNetworkVar(mNetid, "proto", accum))
+        return -1;
+    mAllowedProtocols = mask;
+    return 0;
+}
+
+int WifiNetwork::setAllowedAuthAlgorithms(uint32_t mask) {
+    char accum[255];
+
+    accum[0] = '\0';
+
+    if (mask & AuthenticationAlgorithmMask::OPEN)
+        strcpy(accum, "OPEN ");
+
+    if (mask & AuthenticationAlgorithmMask::SHARED)
+        strcat(accum, "SHARED ");
+
+    if (mask & AuthenticationAlgorithmMask::LEAP)
+        strcat(accum, "LEAP ");
+
+    if (mSuppl->setNetworkVar(mNetid, "auth_alg", accum))
+        return -1;
+
+    mAllowedAuthAlgorithms = mask;
+    return 0;
+}
+
+int WifiNetwork::setAllowedPairwiseCiphers(uint32_t mask) {
+    char accum[255];
+
+    if (mask == PairwiseCiphersMask::NONE)
+        strcpy(accum, "NONE");
+    else {
+        if (mask & PairwiseCiphersMask::TKIP)
+            strcat(accum, "TKIP ");
+        if (mask & PairwiseCiphersMask::CCMP)
+            strcat(accum, "CCMP ");
+    }
+
+    if (mSuppl->setNetworkVar(mNetid, "pairwise", accum))
+        return -1;
+
+    mAllowedPairwiseCiphers = mask;
+    return 0;
+}
+
+int WifiNetwork::setAllowedGroupCiphers(uint32_t mask) {
+    char accum[255];
+
+    if (mask & GroupCiphersMask::WEP40)
+        strcat(accum, "WEP40 ");
+    if (mask & GroupCiphersMask::WEP104)
+        strcat(accum, "WEP104 ");
+    if (mask & GroupCiphersMask::TKIP)
+        strcat(accum, "TKIP ");
+    if (mask & GroupCiphersMask::CCMP)
+        strcat(accum, "CCMP ");
+
+    if (mSuppl->setNetworkVar(mNetid, "group", accum))
+        return -1;
+    mAllowedGroupCiphers = mask;
+    return 0;
+}
+
+int WifiNetwork::setEnabled(bool enabled) {
+
+    if (enabled) {
+        if (getPriority() == -1) {
+            LOGE("Cannot enable network when priority is not set");
+            errno = EAGAIN;
+            return -1;
+        }
+        if (getAllowedKeyManagement() == KeyManagementMask::UNKNOWN) {
+            LOGE("Cannot enable network when KeyManagement is not set");
+            errno = EAGAIN;
+            return -1;
+        }
+    }
+
+    if (mSuppl->enableNetwork(mNetid, enabled))
+        return -1;
+
+    mEnabled = enabled;
+    return 0;
+}
+
+int WifiNetwork::registerProperties() {
+    for (const char **p = WifiNetwork::PropertyNames; *p != '\0'; p++) {
+        char *tmp;
+        asprintf(&tmp, "wifi.net.%d.%s", mNetid, *p);
+
+        if (NetworkManager::Instance()->getPropMngr()->registerProperty(tmp,
+                                                                        this)) {
+            free(tmp);
+            return -1;
+        }
+        free(tmp);
+    }
+    return 0;
+}
+
+int WifiNetwork::unregisterProperties() {
+    for (const char **p = WifiNetwork::PropertyNames; *p != '\0'; p++) {
+        char *tmp;
+        asprintf(&tmp, "wifi.net.%d.%s", mNetid, *p);
+
+        if (NetworkManager::Instance()->getPropMngr()->unregisterProperty(tmp))
+            LOGW("Unable to remove property '%s' (%s)", tmp, strerror(errno));
+        free(tmp);
+    }
+    return 0;
+}
diff --git a/nexus/WifiNetwork.h b/nexus/WifiNetwork.h
new file mode 100644
index 0000000..360ccc2
--- /dev/null
+++ b/nexus/WifiNetwork.h
@@ -0,0 +1,212 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _WIFI_NETWORK_H
+#define _WIFI_NETWORK_H
+
+#include <sys/types.h>
+
+#include <utils/List.h>
+
+class KeyManagementMask {
+public:
+    static const uint32_t UNKNOWN   = 0;
+    static const uint32_t NONE      = 0x01;
+    static const uint32_t WPA_PSK   = 0x02;
+    static const uint32_t WPA_EAP   = 0x04;
+    static const uint32_t IEEE8021X = 0x08;
+    static const uint32_t ALL       = WPA_PSK | WPA_EAP | IEEE8021X;
+};
+
+class SecurityProtocolMask {
+public:
+    static const uint32_t WPA = 0x01;
+    static const uint32_t RSN = 0x02;
+};
+
+class AuthenticationAlgorithmMask {
+public:
+    static const uint32_t OPEN   = 0x01;
+    static const uint32_t SHARED = 0x02;
+    static const uint32_t LEAP   = 0x04;
+};
+
+class PairwiseCiphersMask {
+public:
+    static const uint32_t NONE = 0x00;
+    static const uint32_t TKIP = 0x01;
+    static const uint32_t CCMP = 0x02;
+};
+
+class GroupCiphersMask {
+public:
+    static const uint32_t WEP40  = 0x01;
+    static const uint32_t WEP104 = 0x02;
+    static const uint32_t TKIP   = 0x04;
+    static const uint32_t CCMP   = 0x08;
+};
+
+class Supplicant;
+class InterfaceConfig;
+class Controller;
+class WifiController;
+
+#include "IPropertyProvider.h"
+
+class WifiNetwork : public IPropertyProvider{
+public:
+    static const char *PropertyNames[];
+
+private:
+    Supplicant *mSuppl;
+    InterfaceConfig *mIfaceCfg;
+    WifiController *mController;
+
+    /*
+     * Unique network id - normally provided by supplicant
+     */
+    int mNetid;
+
+    /*
+     * The networks' SSID. Can either be an ASCII string,
+     * which must be enclosed in double quotation marks
+     * (ie: "MyNetwork"), or a string of hex digits which
+     * are not enclosed in quotes (ie: 01ab7893)
+     */
+    char *mSsid;
+
+    /*
+     * When set, this entry should only be used
+     * when associating with the AP having the specified
+     * BSSID. The value is a string in the format of an
+     * Ethernet MAC address
+     */
+    char *mBssid;
+
+    /*
+     *  Pre-shared key for use with WPA-PSK
+     */
+    char *mPsk;
+
+    /*
+     * Up to four WEP keys. Either in ASCII string enclosed in
+     * double quotes, or a string of hex digits
+     */
+    char *mWepKeys[4];
+
+    /*
+     * Default WEP key index, ranging from 0 -> NUM_WEP_KEYS -1
+     */
+    int mDefaultKeyIndex;
+
+    /*
+     * Priority determines the preference given to a network by 
+     * supplicant when choosing an access point with which
+     * to associate
+     */
+    int mPriority;
+
+    /*
+     * This is a network that does not broadcast it's SSID, so an
+     * SSID-specific probe request must be used for scans.
+     */
+    char *mHiddenSsid;
+
+    /*
+     * The set of key management protocols supported by this configuration.
+     */
+    uint32_t mAllowedKeyManagement;
+
+    /*
+     * The set of security protocols supported by this configuration.
+     */
+    uint32_t mAllowedProtocols;
+
+    /*
+     * The set of authentication protocols supported by this configuration.
+     */
+    uint32_t mAllowedAuthAlgorithms;
+
+    /*
+     * The set of pairwise ciphers for WPA supported by this configuration.
+     */
+    uint32_t mAllowedPairwiseCiphers;
+
+    /*
+     * The set of group ciphers for WPA supported by this configuration.
+     */
+    uint32_t mAllowedGroupCiphers;
+
+    /*
+     * Set if this Network is enabled
+     */
+    bool mEnabled;
+
+private:
+    WifiNetwork();
+    int registerProperties();
+    int unregisterProperties();
+
+public:
+    WifiNetwork(WifiController *c, Supplicant *suppl, int networkId);
+    WifiNetwork(WifiController *c, Supplicant *suppl, const char *data);
+
+    virtual ~WifiNetwork();
+
+    WifiNetwork *clone();
+
+    int getNetworkId() { return mNetid; }
+    const char *getSsid() { return mSsid; }
+    const char *getBssid() { return mBssid; }
+    const char *getPsk() { return mPsk; }
+    const char *getWepKey(int idx) { return mWepKeys[idx]; }
+    int getDefaultKeyIndex() { return mDefaultKeyIndex; }
+    int getPriority() { return mPriority; }
+    const char *getHiddenSsid() { return mHiddenSsid; }
+    uint32_t getAllowedKeyManagement() { return mAllowedKeyManagement; }
+    uint32_t getAllowedProtocols() { return mAllowedProtocols; }
+    uint32_t getAllowedAuthAlgorithms() { return mAllowedAuthAlgorithms; }
+    uint32_t getAllowedPairwiseCiphers() { return mAllowedPairwiseCiphers; }
+    uint32_t getAllowedGroupCiphers() { return mAllowedGroupCiphers; }
+    bool getEnabled() { return mEnabled; }
+    Controller *getController() { return (Controller *) mController; }
+
+    int set(const char *name, const char *value);
+    const char *get(const char *name, char *buffer, size_t maxsize);
+
+//    InterfaceConfig *getIfaceCfg() { return mIfaceCfg; }
+
+    int setEnabled(bool enabled);
+    int setSsid(const char *ssid);
+    int setBssid(const char *bssid);
+    int setPsk(const char *psk);
+    int setWepKey(int idx, const char *key);
+    int setDefaultKeyIndex(int idx);
+    int setPriority(int pri);
+    int setHiddenSsid(const char *ssid);
+    int setAllowedKeyManagement(uint32_t mask);
+    int setAllowedProtocols(uint32_t mask);
+    int setAllowedAuthAlgorithms(uint32_t mask);
+    int setAllowedPairwiseCiphers(uint32_t mask);
+    int setAllowedGroupCiphers(uint32_t mask);
+
+    // XXX:Should this really be exposed?.. meh
+    int refresh();
+};
+
+typedef android::List<WifiNetwork *> WifiNetworkCollection;
+
+#endif
diff --git a/nexus/WifiScanner.cpp b/nexus/WifiScanner.cpp
new file mode 100644
index 0000000..bdfa497
--- /dev/null
+++ b/nexus/WifiScanner.cpp
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdlib.h>
+#include <sys/socket.h>
+#include <sys/select.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <errno.h>
+#include <pthread.h>
+
+#define LOG_TAG "WifiScanner"
+#include <cutils/log.h>
+
+#include "WifiScanner.h"
+#include "Supplicant.h"
+
+extern "C" int pthread_cancel(pthread_t thread);
+
+WifiScanner::WifiScanner(Supplicant *suppl, int period) {
+    mSuppl = suppl;
+    mPeriod = period;
+    mActive = false;
+}
+
+int WifiScanner::start(bool active) {
+    mActive = active;
+
+    if(pipe(mCtrlPipe))
+        return -1;
+
+    if (pthread_create(&mThread, NULL, WifiScanner::threadStart, this))
+        return -1;
+    return 0;
+}
+
+void *WifiScanner::threadStart(void *obj) {
+    WifiScanner *me = reinterpret_cast<WifiScanner *>(obj);
+    me->run();
+    pthread_exit(NULL);
+    return NULL;
+}
+
+int WifiScanner::stop() {
+    char c = 0;
+
+    if (write(mCtrlPipe[1], &c, 1) != 1) {
+        LOGE("Error writing to control pipe (%s)", strerror(errno));
+        return -1;
+    }
+
+    void *ret;
+    if (pthread_join(mThread, &ret)) {
+        LOGE("Error joining to scanner thread (%s)", strerror(errno));
+        return -1;
+    }
+
+    close(mCtrlPipe[0]);
+    close(mCtrlPipe[1]);
+    return 0;
+}
+
+void WifiScanner::run() {
+    LOGD("Starting wifi scanner (active = %d)", mActive);
+
+    while(1) {
+        fd_set read_fds;
+        struct timeval to;
+        int rc = 0;
+
+        to.tv_usec = 0;
+        to.tv_sec = mPeriod;
+
+        FD_ZERO(&read_fds);
+        FD_SET(mCtrlPipe[0], &read_fds);
+
+        if (mSuppl->triggerScan(mActive)) {
+            LOGW("Error triggering scan (%s)", strerror(errno));
+        }
+
+        if ((rc = select(mCtrlPipe[0] + 1, &read_fds, NULL, NULL, &to)) < 0) {
+            LOGE("select failed (%s) - sleeping for one scanner period", strerror(errno));
+            sleep(mPeriod);
+            continue;
+        } else if (!rc) {
+        } else if (FD_ISSET(mCtrlPipe[0], &read_fds))
+            break;
+    } // while
+    LOGD("Stopping wifi scanner");
+}
diff --git a/nexus/WifiScanner.h b/nexus/WifiScanner.h
new file mode 100644
index 0000000..92822e9
--- /dev/null
+++ b/nexus/WifiScanner.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _WIFISCANNER_H
+#define _WIFISCANNER_H
+
+#include <pthread.h>
+
+class Supplicant;
+
+class WifiScanner {
+    pthread_t  mThread;
+    int        mCtrlPipe[2];
+    Supplicant *mSuppl;
+    int        mPeriod;
+    bool       mActive;
+    
+
+public:
+    WifiScanner(Supplicant *suppl, int period);
+    virtual ~WifiScanner() {}
+
+    int getPeriod() { return mPeriod; }
+
+    int start(bool active);
+    int stop();
+
+private:
+    static void *threadStart(void *obj);
+
+    void run();
+};
+
+#endif
diff --git a/nexus/main.cpp b/nexus/main.cpp
new file mode 100644
index 0000000..e460d42
--- /dev/null
+++ b/nexus/main.cpp
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdlib.h>
+#include <errno.h>
+
+#define LOG_TAG "Nexus"
+
+#include "cutils/log.h"
+#include "NetworkManager.h"
+#include "CommandListener.h"
+
+#include "LoopController.h"
+#include "OpenVpnController.h"
+#include "TiwlanWifiController.h"
+
+int main() {
+    LOGI("Nexus version 0.1 firing up");
+
+    CommandListener *cl = new CommandListener();
+
+    NetworkManager *nm;
+    if (!(nm = NetworkManager::Instance())) {
+        LOGE("Unable to create NetworkManager");
+        exit (-1);
+    };
+
+    nm->setBroadcaster((SocketListener *) cl);
+
+    nm->attachController(new LoopController(nm->getPropMngr()));
+    nm->attachController(new TiwlanWifiController(nm->getPropMngr(), "/system/lib/modules/wlan.ko", "wlan", ""));
+//    nm->attachController(new AndroidL2TPVpnController());
+    nm->attachController(new OpenVpnController(nm->getPropMngr()));
+
+
+    if (NetworkManager::Instance()->run()) {
+        LOGE("Unable to Run NetworkManager (%s)", strerror(errno));
+        exit (1);
+    }
+
+    if (cl->startListener()) {
+        LOGE("Unable to start CommandListener (%s)", strerror(errno));
+        exit (1);
+    }
+
+    // XXX: we'll use the main thread for the NetworkManager eventually
+
+    while(1) {
+        sleep(1000);
+    }
+
+    LOGI("Nexus exiting");
+    exit(0);
+}
diff --git a/nexus/nexctl.c b/nexus/nexctl.c
new file mode 100644
index 0000000..cfebbf0
--- /dev/null
+++ b/nexus/nexctl.c
@@ -0,0 +1,124 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <string.h>
+#include <signal.h>
+#include <errno.h>
+#include <fcntl.h>
+
+#include <sys/socket.h>
+#include <sys/select.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <sys/un.h>
+
+#include <cutils/sockets.h>
+
+#include <private/android_filesystem_config.h>
+
+int main(int argc, char **argv) {
+    int sock;
+
+    if ((sock = socket_local_client("nexus",
+                                     ANDROID_SOCKET_NAMESPACE_RESERVED,
+                                     SOCK_STREAM)) < 0) {
+        fprintf(stderr, "Error connecting (%s)\n", strerror(errno));
+        exit(1);
+    }
+
+    printf("Connected to nexus\n");
+
+    char line[255];
+    char *buffer = malloc(4096);
+    int cursor = 0;
+    int col = 0;
+
+    while(1) {
+        fd_set read_fds;
+        struct timeval to;
+        int rc = 0;
+
+        to.tv_sec = 10;
+        to.tv_usec = 0;
+
+        FD_ZERO(&read_fds);
+        FD_SET(sock, &read_fds);
+        FD_SET(0, &read_fds);
+
+        if (col == 0) {
+            fprintf(stdout, "-> ");
+            fflush(stdout);
+            col = 3;
+        }
+    
+        if ((rc = select(sock +1, &read_fds, NULL, NULL, &to)) < 0) {
+            fprintf(stderr, "Error in select (%s)\n", strerror(errno));
+            exit(2);
+        } else if (!rc) {
+            continue;
+        } else if (FD_ISSET(sock, &read_fds)) {
+            memset(buffer, 0, 4096);
+            if ((rc = read(sock, buffer, 4096)) <= 0) {
+                 fprintf(stderr, "Error reading response (%s)\n", strerror(errno));
+                 exit(2);
+            }
+            int i;
+            for (i = 0; i < col; i++) {
+                fprintf(stdout, "%c", 8);
+            }
+
+            printf("%s", buffer);
+            printf("-> ");
+            for (i = 0; i < cursor; i++) {
+                fprintf(stdout, "%c", line[i]);
+            }
+            fflush(stdout);
+        } else if (FD_ISSET(0, &read_fds)) {
+            char c;
+
+            if ((rc = read(0, &c, 1)) < 0) {
+                fprintf(stderr, "Error reading from terminal (%s)\n", strerror(errno));
+                exit(2);
+            } else if (!rc) {
+                fprintf(stderr, "0 length read from terminal\n");
+                exit(2);
+            }
+
+            fprintf(stdout, "%c", c);
+            fflush(stdout);
+
+            line[cursor] = c;
+
+            if (c == '\n') {
+                if ((rc = write(sock, line, strlen(line))) < 0) {
+                    fprintf(stderr, "Error writing to nexus (%s)\n", strerror(errno));
+                    exit(2);
+                }
+                memset(line, 0, sizeof(line));
+                cursor = 0;
+                col = 0;
+            } else {
+                cursor++;
+                col++;
+            }
+        }
+    }
+
+    exit(0);
+}
diff --git a/rootdir/etc/init.goldfish.sh b/rootdir/etc/init.goldfish.sh
index 0eb0154..f1b801d 100755
--- a/rootdir/etc/init.goldfish.sh
+++ b/rootdir/etc/init.goldfish.sh
@@ -34,6 +34,10 @@
     ;;
 esac
 
+# call 'qemu-props' to set system properties from the emulator.
+#
+/system/bin/qemu-props
+
 # this line doesn't really do anything useful. however without it the
 # previous setprop doesn't seem to apply for some really odd reason
 setprop ro.qemu.init.completed 1
diff --git a/rootdir/init.rc b/rootdir/init.rc
index bcabecb..9853cc6 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -34,6 +34,24 @@
     write /proc/sys/kernel/sched_latency_ns 10000000
     write /proc/sys/kernel/sched_wakeup_granularity_ns 2000000
 
+# Create cgroup mount points for process groups
+    mkdir /dev/cpuctl
+    mount cgroup none /dev/cpuctl cpu
+    chown sytem system /dev/cpuctl
+    chown system system /dev/cpuctl/tasks
+    chmod 0777 /dev/cpuctl/tasks
+    write /dev/cpuctl/cpu.shares 1024
+
+    mkdir /dev/cpuctl/fg_boost
+    chown system system /dev/cpuctl/fg_boost/tasks
+    chmod 0777 /dev/cpuctl/fg_boost/tasks
+    write /dev/cpuctl/fg_boost/cpu.shares 1024
+
+    mkdir /dev/cpuctl/bg_non_interactive
+    chown system system /dev/cpuctl/bg_non_interactive/tasks
+    chmod 0777 /dev/cpuctl/bg_non_interactive/tasks
+    write /dev/cpuctl/bg_non_interactive/cpu.shares 1024
+
 # mount mtd partitions
     # Mount /system rw first to give the filesystem a chance to save a checkpoint
     mount yaffs2 mtd@system /system 
@@ -199,6 +217,10 @@
 service vold /system/bin/vold
     socket vold stream 0660 root mount
 
+service nexus /system/bin/nexus
+    socket nexus stream 0660 root system
+    disabled
+
 #service mountd /system/bin/mountd
 #    socket mountd stream 0660 root mount
 
@@ -224,6 +246,12 @@
     group audio
     oneshot
 
+service bootanim /system/bin/bootanimation
+    user graphics
+    group graphics
+    disabled
+    oneshot
+
 service dbus /system/bin/dbus-daemon --system --nofork
     socket dbus stream 660 bluetooth bluetooth
     user bluetooth
diff --git a/toolbox/getevent.c b/toolbox/getevent.c
index 14372cb..256720d 100644
--- a/toolbox/getevent.c
+++ b/toolbox/getevent.c
@@ -28,6 +28,7 @@
 {
     uint8_t *bits = NULL;
     ssize_t bits_size = 0;
+    const char* label;
     int i, j, k;
     int res, res2;
     
@@ -45,21 +46,48 @@
                 return 1;
             }
         }
+        res2 = 0;
         switch(i) {
+            case EV_SYN:
+                label = "SYN";
+                break;
             case EV_KEY:
                 res2 = ioctl(fd, EVIOCGKEY(res), bits + bits_size);
+                label = "KEY";
+                break;
+            case EV_REL:
+                label = "REL";
+                break;
+            case EV_ABS:
+                label = "ABS";
+                break;
+            case EV_MSC:
+                label = "MSC";
                 break;
             case EV_LED:
                 res2 = ioctl(fd, EVIOCGLED(res), bits + bits_size);
+                label = "LED";
                 break;
             case EV_SND:
                 res2 = ioctl(fd, EVIOCGSND(res), bits + bits_size);
+                label = "SND";
                 break;
             case EV_SW:
                 res2 = ioctl(fd, EVIOCGSW(bits_size), bits + bits_size);
+                label = "SW ";
+                break;
+            case EV_REP:
+                label = "REP";
+                break;
+            case EV_FF:
+                label = "FF ";
+                break;
+            case EV_PWR:
+                label = "PWR";
                 break;
             default:
                 res2 = 0;
+                label = "???";
         }
         for(j = 0; j < res; j++) {
             for(k = 0; k < 8; k++)
@@ -70,9 +98,9 @@
                     else
                         down = ' ';
                     if(count == 0)
-                        printf("    type %04x:", i);
+                        printf("    %s (%04x):", label, i);
                     else if((count & 0x7) == 0 || i == EV_ABS)
-                        printf("\n              ");
+                        printf("\n               ");
                     printf(" %04x%c", j * 8 + k, down);
                     if(i == EV_ABS) {
                         struct input_absinfo abs;
@@ -264,7 +292,16 @@
 
 static void usage(int argc, char *argv[])
 {
-    fprintf(stderr, "Usage: %s [-t] [-n] [-s switchmask] [-S] [-v [mask]] [-q] [-c count] [-r] [device]\n", argv[0]);
+    fprintf(stderr, "Usage: %s [-t] [-n] [-s switchmask] [-S] [-v [mask]] [-p] [-q] [-c count] [-r] [device]\n", argv[0]);
+    fprintf(stderr, "    -t: show time stamps\n");
+    fprintf(stderr, "    -n: don't print newlines\n");
+    fprintf(stderr, "    -s: print switch states for given bits\n");
+    fprintf(stderr, "    -S: print all switch states\n");
+    fprintf(stderr, "    -v: verbosity mask (errs=1, dev=2, name=4, info=8, vers=16, pos. events=32)\n");
+    fprintf(stderr, "    -p: show possible events (errs, dev, name, pos. events)\n");
+    fprintf(stderr, "    -q: quiet (clear verbosity mask)\n");
+    fprintf(stderr, "    -c: print given number of events then exit\n");
+    fprintf(stderr, "    -r: print rate events are received\n");
 }
 
 int getevent_main(int argc, char *argv[])
@@ -290,7 +327,7 @@
 
     opterr = 0;
     do {
-        c = getopt(argc, argv, "tns:Sv::qc:rh");
+        c = getopt(argc, argv, "tns:Sv::pqc:rh");
         if (c == EOF)
             break;
         switch (c) {
@@ -317,6 +354,12 @@
                 print_flags |= PRINT_DEVICE | PRINT_DEVICE_NAME | PRINT_DEVICE_INFO | PRINT_VERSION;
             print_flags_set = 1;
             break;
+        case 'p':
+            print_flags = PRINT_DEVICE_ERRORS | PRINT_DEVICE | PRINT_DEVICE_NAME | PRINT_POSSIBLE_EVENTS;
+            print_flags_set = 1;
+            if(dont_block == -1)
+                dont_block = 1;
+            break;
         case 'q':
             print_flags = 0;
             print_flags_set = 1;
diff --git a/toolbox/ifconfig.c b/toolbox/ifconfig.c
index e83cd8b..80c0e5c 100644
--- a/toolbox/ifconfig.c
+++ b/toolbox/ifconfig.c
@@ -28,20 +28,32 @@
 
 static inline void init_sockaddr_in(struct sockaddr_in *sin, const char *addr)
 {
-	sin->sin_family = AF_INET;
-	sin->sin_port = 0;
-	sin->sin_addr.s_addr = inet_addr(addr);
+    sin->sin_family = AF_INET;
+    sin->sin_port = 0;
+    sin->sin_addr.s_addr = inet_addr(addr);
+}
+
+static void setmtu(int s, struct ifreq *ifr, const char *mtu)
+{
+    int m = atoi(mtu);
+    ifr->ifr_mtu = m;
+    if(ioctl(s, SIOCSIFMTU, ifr) < 0) die("SIOCSIFMTU");
+}
+static void setdstaddr(int s, struct ifreq *ifr, const char *addr)
+{
+    init_sockaddr_in((struct sockaddr_in *) &ifr->ifr_dstaddr, addr);
+    if(ioctl(s, SIOCSIFDSTADDR, ifr) < 0) die("SIOCSIFDSTADDR");
 }
 
 static void setnetmask(int s, struct ifreq *ifr, const char *addr)
 {
-	init_sockaddr_in((struct sockaddr_in *) &ifr->ifr_netmask, addr);
+    init_sockaddr_in((struct sockaddr_in *) &ifr->ifr_netmask, addr);
     if(ioctl(s, SIOCSIFNETMASK, ifr) < 0) die("SIOCSIFNETMASK");
 }
 
 static void setaddr(int s, struct ifreq *ifr, const char *addr)
 {
-	init_sockaddr_in((struct sockaddr_in *) &ifr->ifr_addr, addr);
+    init_sockaddr_in((struct sockaddr_in *) &ifr->ifr_addr, addr);
     if(ioctl(s, SIOCSIFADDR, ifr) < 0) die("SIOCSIFADDR");
 }
 
@@ -109,31 +121,43 @@
         running = (flags & IFF_RUNNING)      ? " running" : "";
         multi =   (flags & IFF_MULTICAST)    ? " multicast" : "";
         printf("%s%s%s%s%s%s]\n", updown, brdcst, loopbk, ppp, running, multi);
-
-
-
-/*    char *updown, *brdcst, *loopbk, *ppp, *running, *multi; */
-
         return 0;
     }
     
-    while(argc > 0){
-        if(!strcmp(argv[0], "up")) {
+    while(argc > 0) {
+        if (!strcmp(argv[0], "up")) {
             setflags(s, &ifr, IFF_UP, 0);
-        } else if(!strcmp(argv[0], "down")) {
+        } else if (!strcmp(argv[0], "mtu")) {
+            argc--, argv++;
+            if (!argc) {
+                errno = EINVAL;
+                die("expecting a value for parameter \"mtu\"");
+            }
+            setmtu(s, &ifr, argv[0]);
+        } else if (!strcmp(argv[0], "-pointopoint")) {
+            setflags(s, &ifr, IFF_POINTOPOINT, 1);
+        } else if (!strcmp(argv[0], "pointopoint")) {
+            argc--, argv++;
+            if (!argc) { 
+                errno = EINVAL;
+                die("expecting an IP address for parameter \"pointtopoint\"");
+            }
+            setdstaddr(s, &ifr, argv[0]);
+            setflags(s, &ifr, IFF_POINTOPOINT, 0);
+        } else if (!strcmp(argv[0], "down")) {
             setflags(s, &ifr, 0, IFF_UP);
-		} else if(!strcmp(argv[0], "netmask")) {
-			argc--, argv++;
-			if (0 == argc) { 
-				errno = EINVAL;
-				die("expecting an IP address for parameter \"netmask\"");
-			}
-			setnetmask(s, &ifr, argv[0]);
-        } else if(isdigit(argv[0][0])){
+        } else if (!strcmp(argv[0], "netmask")) {
+            argc--, argv++;
+            if (!argc) { 
+                errno = EINVAL;
+                die("expecting an IP address for parameter \"netmask\"");
+            }
+            setnetmask(s, &ifr, argv[0]);
+        } else if (isdigit(argv[0][0])) {
             setaddr(s, &ifr, argv[0]);
+            setflags(s, &ifr, IFF_UP, 0);
         }
         argc--, argv++;
     }
-
     return 0;
 }
diff --git a/toolbox/route.c b/toolbox/route.c
index adf5c69..2fd7108 100644
--- a/toolbox/route.c
+++ b/toolbox/route.c
@@ -2,6 +2,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
+#include <stdarg.h>
 
 #include <errno.h>
 #include <string.h>
@@ -14,9 +15,14 @@
 #include <arpa/inet.h>
 #include <linux/route.h>
 
-static void die(const char *s)
+static void die(const char *fmt, ...)
 {
-    fprintf(stderr,"error: %s (%s)\n", s, strerror(errno));
+    va_list p;
+
+    va_start(p, fmt);
+    fprintf(stderr,"error(%s): ", strerror(errno));
+    fprintf(stderr, fmt, p);
+    va_end(p);
     exit(-1);
 }
 
@@ -36,62 +42,89 @@
 	}                                       \
 } while(0)		
 
-/* current support two kinds of usage */
+/* current support the following routing entries */
 /* route add default dev wlan0 */
 /* route add default gw 192.168.20.1 dev wlan0 */
+/* route add net 192.168.1.1 netmask 255.255.255.0 gw 172.24.192.10 */
 
 int route_main(int argc, char *argv[])
 {
     struct ifreq ifr;
     int s,i;
-	struct rtentry rt;
-	struct sockaddr_in ina;
+    struct rtentry rt;
+    struct sockaddr_in ina;
    
-    if(argc == 0) return 0;
-    
+    if (!argc)
+        return 0;
+
     strncpy(ifr.ifr_name, argv[0], IFNAMSIZ);
     ifr.ifr_name[IFNAMSIZ-1] = 0;
-	ADVANCE(argc, argv);
+    ADVANCE(argc, argv);
 
-    if((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
+    if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
         die("cannot open control socket\n");
     }
 
     while(argc > 0){
-        if(!strcmp(argv[0], "add")) {
-			EXPECT_NEXT(argc, argv);
-			if(!strcmp(argv[0], "default")) {
-				EXPECT_NEXT(argc, argv);
-				memset((char *) &rt, 0, sizeof(struct rtentry));
-				rt.rt_dst.sa_family = AF_INET;	
-				if(!strcmp(argv[0], "dev")) {
-				  EXPECT_NEXT(argc, argv);
-				  rt.rt_flags = RTF_UP | RTF_HOST;
-				  rt.rt_dev = argv[0];
-				  if (ioctl(s, SIOCADDRT, &rt) < 0) die("SIOCADDRT");
-				}else if(!strcmp(argv[0], "gw")) {
-				  EXPECT_NEXT(argc, argv);
-				  rt.rt_flags = RTF_UP | RTF_GATEWAY;
-				  init_sockaddr_in((struct sockaddr_in *)&(rt.rt_genmask), "0.0.0.0");
-				  if(isdigit(argv[0][0])){
-					init_sockaddr_in((struct sockaddr_in *)&(rt.rt_gateway), argv[0]);
-				  }else{
-					die("expecting an IP address for parameter \"gw\"");
-				  }
-				  EXPECT_NEXT(argc, argv);
-				  if(!strcmp(argv[0], "dev")) {
-					EXPECT_NEXT(argc, argv);
-					rt.rt_dev = argv[0];
-					if (ioctl(s, SIOCADDRT, &rt) < 0){
-					  die("SIOCADDRT");
-					}
-				  }
-				}
-			}
+        if (!strcmp(argv[0], "add")) {
+            EXPECT_NEXT(argc, argv);
+            if (!strcmp(argv[0], "default")) {
+                EXPECT_NEXT(argc, argv);
+                memset((char *) &rt, 0, sizeof(struct rtentry));
+                rt.rt_dst.sa_family = AF_INET;	
+                if(!strcmp(argv[0], "dev")) {
+                    EXPECT_NEXT(argc, argv);
+                    rt.rt_flags = RTF_UP | RTF_HOST;
+                    rt.rt_dev = argv[0];
+                    if (ioctl(s, SIOCADDRT, &rt) < 0)
+                        die("SIOCADDRT\n");
+                } else if (!strcmp(argv[0], "gw")) {
+                    EXPECT_NEXT(argc, argv);
+                    rt.rt_flags = RTF_UP | RTF_GATEWAY;
+                    init_sockaddr_in((struct sockaddr_in *)&(rt.rt_genmask), "0.0.0.0");
+                    if(isdigit(argv[0][0])) {
+                        init_sockaddr_in((struct sockaddr_in *)&(rt.rt_gateway), argv[0]);
+                    } else {
+                        die("expecting an IP address for parameter \"gw\"\n");
+                    }
+                    EXPECT_NEXT(argc, argv);
+                    if (!strcmp(argv[0], "dev")) {
+                        EXPECT_NEXT(argc, argv);
+                        rt.rt_dev = argv[0];
+                        if (ioctl(s, SIOCADDRT, &rt) < 0) {
+                            die("SIOCADDRT\n");
+                        }
+                    }
+                }
+            } else {
+                char keywords[3][10] = { "-net", "netmask", "gw" };
+                struct sockaddr_in *paddr[3] = { &rt.rt_dst, &rt.rt_genmask, &rt.rt_gateway };
+                int k = 0;
+
+                memset((char *) &rt, 0, sizeof(struct rtentry));
+                rt.rt_flags = RTF_UP | RTF_GATEWAY;
+                do {
+                     if (!strcmp(argv[0], keywords[k])) {
+                         EXPECT_NEXT(argc, argv);
+                         if (isdigit(argv[0][0])) {
+                             init_sockaddr_in(paddr[k], argv[0]);
+                         } else {
+                            die("expecting an IP/MASK address for parameter %s\n", keywords[k]);
+                         }
+                     if (k < 2)
+                         EXPECT_NEXT(argc, argv);
+                     } else {
+                         die("expecting keyword(s)\n");
+                     }
+                 } while (++k < 3);
+
+                if (ioctl(s, SIOCADDRT, &rt) < 0) {
+                    die("SIOCADDRT\n");
+                }
+            }
         }
-		ADVANCE(argc, argv);
+        ADVANCE(argc, argv);
     }
 
     return 0;
 }
-
diff --git a/vold/volmgr_vfat.c b/vold/volmgr_vfat.c
index 344a166..2b0e1fa 100644
--- a/vold/volmgr_vfat.c
+++ b/vold/volmgr_vfat.c
@@ -39,6 +39,7 @@
 int vfat_check(blkdev_t *dev)
 {
     int rc;
+    boolean rw = true;
 
 #if VFAT_DEBUG
     LOG_VOL("vfat_check(%d:%d):", dev->major, dev->minor);
@@ -50,47 +51,51 @@
         return 0;
     }
 
-#ifdef VERIFY_PASS
-    char *args[7];
-    args[0] = FSCK_MSDOS_PATH;
-    args[1] = "-v";
-    args[2] = "-V";
-    args[3] = "-w";
-    args[4] = "-p";
-    args[5] = blkdev_get_devpath(dev);
-    args[6] = NULL;
-    rc = logwrap(6, args);
-    free(args[5]);
-#else
-    char *args[6];
-    args[0] = FSCK_MSDOS_PATH;
-    args[1] = "-v";
-    args[2] = "-w";
-    args[3] = "-p";
-    args[4] = blkdev_get_devpath(dev);
-    args[5] = NULL;
-    rc = logwrap(5, args);
-    free(args[4]);
-#endif
+    do {
 
-    if (rc == 0) {
-        LOG_VOL("Filesystem check completed OK");
-        return 0;
-    } else if (rc == 1) {
-        LOG_VOL("Filesystem check failed (general failure)");
-        return -EINVAL;
-    } else if (rc == 2) {
-        LOG_VOL("Filesystem check failed (invalid usage)");
-        return -EIO;
-    } else if (rc == 4) {
-        LOG_VOL("Filesystem check completed (errors fixed)");
-    } else if (rc == 8) {
-        LOG_VOL("Filesystem check failed (not a FAT filesystem)");
-        return -ENODATA;
-    } else {
-        LOG_VOL("Filesystem check failed (unknown exit code %d)", rc);
-        return -EIO;
-    }
+        char *args[6];
+        args[0] = FSCK_MSDOS_PATH;
+        args[1] = "-v";
+
+        if (rw) {
+            args[2] = "-w";
+            args[3] = "-p";
+            args[4] = blkdev_get_devpath(dev);
+            args[5] = NULL;
+            rc = logwrap(5, args);
+            free(args[4]);
+        } else {
+            args[2] = "-n";
+            args[3] = blkdev_get_devpath(dev);
+            args[4] = NULL;
+            rc = logwrap(4, args);
+            free(args[3]);
+        }
+
+        if (rc == 0) {
+            LOG_VOL("Filesystem check completed OK");
+            return 0;
+        } else if (rc == 1) {
+            LOG_VOL("Filesystem check failed (general failure)");
+            return -EINVAL;
+        } else if (rc == 2) {
+            LOG_VOL("Filesystem check failed (invalid usage)");
+            return -EIO;
+        } else if (rc == 4) {
+            LOG_VOL("Filesystem check completed (errors fixed)");
+        } else if (rc == 6) {
+            LOG_VOL("Filesystem read-only - retrying check RO");
+            rw = false;
+            continue;
+        } else if (rc == 8) {
+            LOG_VOL("Filesystem check failed (not a FAT filesystem)");
+            return -ENODATA;
+        } else {
+            LOG_VOL("Filesystem check failed (unknown exit code %d)", rc);
+            return -EIO;
+        }
+    } while (0);
+
     return 0;
 }
 
@@ -113,15 +118,22 @@
         flags |= MS_REMOUNT;
     }
 
+    /*
+     * The mount masks restrict access so that:
+     * 1. The 'system' user cannot access the SD card at all - 
+     *    (protects system_server from grabbing file references)
+     * 2. Group users can RWX
+     * 3. Others can only RX
+     */
     rc = mount(devpath, vol->mount_point, "vfat", flags,
-               "utf8,uid=1000,gid=1000,fmask=711,dmask=700,shortname=mixed");
+               "utf8,uid=1000,gid=1015,fmask=702,dmask=702,shortname=mixed");
 
     if (rc && errno == EROFS) {
         LOGE("vfat_mount(%d:%d, %s): Read only filesystem - retrying mount RO",
              dev->major, dev->minor, vol->mount_point);
         flags |= MS_RDONLY;
         rc = mount(devpath, vol->mount_point, "vfat", flags,
-                   "utf8,uid=1000,gid=1000,fmask=711,dmask=700,shortname=mixed");
+                   "utf8,uid=1000,gid=1015,fmask=702,dmask=702,shortname=mixed");
     }
 
 #if VFAT_DEBUG