Merge "sdcard : inode numbers must be fully representable as uint32_t."
diff --git a/adb/tests/test_adb.py b/adb/tests/test_adb.py
new file mode 100644
index 0000000..b0ae07f
--- /dev/null
+++ b/adb/tests/test_adb.py
@@ -0,0 +1,390 @@
+#!/usr/bin/env python2
+"""Simple conformance test for adb.
+
+This script will use the available adb in path and run simple
+tests that attempt to touch all accessible attached devices.
+"""
+import hashlib
+import os
+import random
+import re
+import subprocess
+import tempfile
+import unittest
+import sys
+import shlex
+
+
+def trace(cmd):
+    """Print debug message if tracing enabled."""
+    if False:
+        print >> sys.stderr, cmd
+
+
+def call(cmd_str):
+    """Run process and return output tuple (stdout, stderr, ret code)."""
+    trace(cmd_str)
+    process = subprocess.Popen(shlex.split(cmd_str),
+                               stdout=subprocess.PIPE,
+                               stderr=subprocess.PIPE)
+    stdout, stderr = process.communicate()
+    return stdout, stderr, process.returncode
+
+
+def call_combined(cmd_str):
+    """Run process and return output tuple (stdout+stderr, ret code)."""
+    trace(cmd_str)
+    process = subprocess.Popen(shlex.split(cmd_str),
+                               stdout=subprocess.PIPE,
+                               stderr=subprocess.STDOUT)
+    stdout, _ = process.communicate()
+    return stdout, process.returncode
+
+
+def call_checked(cmd_str):
+    """Run process and get stdout+stderr, raise an exception on trouble."""
+    trace(cmd_str)
+    return subprocess.check_output(shlex.split(cmd_str),
+                                   stderr=subprocess.STDOUT)
+
+
+def call_checked_list(cmd_str):
+    return call_checked(cmd_str).split('\n')
+
+
+def call_checked_list_skip(cmd_str):
+    out_list = call_checked_list(cmd_str)
+
+    def is_init_line(line):
+        if (len(line) >= 3) and (line[0] == "*") and (line[-2] == "*"):
+            return True
+        else:
+            return False
+
+    return [line for line in out_list if not is_init_line(line)]
+
+
+def get_device_list():
+    output = call_checked_list_skip("adb devices")
+    dev_list = []
+    for line in output[1:]:
+        if line.strip() == "":
+            continue
+        device, _ = line.split()
+        dev_list.append(device)
+    return dev_list
+
+
+def get_attached_device_count():
+    return len(get_device_list())
+
+
+def compute_md5(string):
+    hsh = hashlib.md5()
+    hsh.update(string)
+    return hsh.hexdigest()
+
+
+class HostFile(object):
+    def __init__(self, handle, md5):
+        self.handle = handle
+        self.md5 = md5
+        self.full_path = handle.name
+        self.base_name = os.path.basename(self.full_path)
+
+
+class DeviceFile(object):
+    def __init__(self, md5, full_path):
+        self.md5 = md5
+        self.full_path = full_path
+        self.base_name = os.path.basename(self.full_path)
+
+
+def make_random_host_files(in_dir, num_files, rand_size=True):
+    files = {}
+    min_size = 1 * (1 << 10)
+    max_size = 16 * (1 << 10)
+    fixed_size = min_size
+
+    for _ in range(num_files):
+        file_handle = tempfile.NamedTemporaryFile(dir=in_dir)
+
+        if rand_size:
+            size = random.randrange(min_size, max_size, 1024)
+        else:
+            size = fixed_size
+        rand_str = os.urandom(size)
+        file_handle.write(rand_str)
+        file_handle.flush()
+
+        md5 = compute_md5(rand_str)
+        files[file_handle.name] = HostFile(file_handle, md5)
+    return files
+
+
+def make_random_device_files(adb, in_dir, num_files, rand_size=True):
+    files = {}
+    min_size = 1 * (1 << 10)
+    max_size = 16 * (1 << 10)
+    fixed_size = min_size
+
+    for i in range(num_files):
+        if rand_size:
+            size = random.randrange(min_size, max_size, 1024)
+        else:
+            size = fixed_size
+
+        base_name = "device_tmpfile" + str(i)
+        full_path = in_dir + "/" + base_name
+
+        adb.shell("dd if=/dev/urandom of={} bs={} count=1".format(full_path,
+                                                                  size))
+        dev_md5, _ = adb.shell("md5sum {}".format(full_path)).split()
+
+        files[full_path] = DeviceFile(dev_md5, full_path)
+    return files
+
+
+class AdbWrapper(object):
+    """Convenience wrapper object for the adb command."""
+    def __init__(self, device=None, out_dir=None):
+        self.device = device
+        self.out_dir = out_dir
+        self.adb_cmd = "adb "
+        if self.device:
+            self.adb_cmd += "-s {} ".format(device)
+        if self.out_dir:
+            self.adb_cmd += "-p {} ".format(out_dir)
+
+    def shell(self, cmd):
+        return call_checked(self.adb_cmd + "shell " + cmd)
+
+    def shell_nocheck(self, cmd):
+        return call_combined(self.adb_cmd + "shell " + cmd)
+
+    def push(self, local, remote):
+        return call_checked(self.adb_cmd + "push {} {}".format(local, remote))
+
+    def pull(self, remote, local):
+        return call_checked(self.adb_cmd + "pull {} {}".format(remote, local))
+
+    def sync(self, directory=""):
+        return call_checked(self.adb_cmd + "sync {}".format(directory))
+
+    def forward(self, local, remote):
+        return call_checked(self.adb_cmd + "forward {} {}".format(local,
+                                                                  remote))
+
+    def tcpip(self, port):
+        return call_checked(self.adb_cmd + "tcpip {}".format(port))
+
+    def usb(self):
+        return call_checked(self.adb_cmd + "usb")
+
+    def forward_remove(self, local):
+        return call_checked(self.adb_cmd + "forward --remove {}".format(local))
+
+    def forward_remove_all(self):
+        return call_checked(self.adb_cmd + "forward --remove-all")
+
+    def connect(self, host):
+        return call_checked(self.adb_cmd + "connect {}".format(host))
+
+    def disconnect(self, host):
+        return call_checked(self.adb_cmd + "disconnect {}".format(host))
+
+    def reverse(self, remote, local):
+        return call_checked(self.adb_cmd + "reverse {} {}".format(remote,
+                                                                  local))
+
+    def reverse_remove_all(self):
+        return call_checked(self.adb_cmd + "reverse --remove-all")
+
+    def reverse_remove(self, remote):
+        return call_checked(
+            self.adb_cmd + "reverse --remove {}".format(remote))
+
+    def wait(self):
+        return call_checked(self.adb_cmd + "wait-for-device")
+
+
+class AdbBasic(unittest.TestCase):
+    def test_devices(self):
+        """Get uptime for each device plugged in from /proc/uptime."""
+        dev_list = get_device_list()
+        for device in dev_list:
+            out = call_checked(
+                "adb -s {} shell cat /proc/uptime".format(device))
+            self.assertEqual(len(out.split()), 2)
+            self.assertGreater(float(out.split()[0]), 0.0)
+            self.assertGreater(float(out.split()[1]), 0.0)
+
+    def test_help(self):
+        """Make sure we get _something_ out of help."""
+        out = call_checked("adb help")
+        self.assertTrue(len(out) > 0)
+
+    def test_version(self):
+        """Get a version number out of the output of adb."""
+        out = call_checked("adb version").split()
+        version_num = False
+        for item in out:
+            if re.match(r"[\d+\.]*\d", item):
+                version_num = True
+        self.assertTrue(version_num)
+
+
+class AdbFile(unittest.TestCase):
+    SCRATCH_DIR = "/data/local/tmp"
+    DEVICE_TEMP_FILE = SCRATCH_DIR + "/adb_test_file"
+    DEVICE_TEMP_DIR = SCRATCH_DIR + "/adb_test_dir"
+
+    def test_push(self):
+        """Push a file to all attached devices."""
+        dev_list = get_device_list()
+        for device in dev_list:
+            self.push_with_device(device)
+
+    def push_with_device(self, device):
+        """Push a randomly generated file to specified device."""
+        kbytes = 512
+        adb = AdbWrapper(device)
+        with tempfile.NamedTemporaryFile(mode="w") as tmp:
+            rand_str = os.urandom(1024 * kbytes)
+            tmp.write(rand_str)
+            tmp.flush()
+
+            host_md5 = compute_md5(rand_str)
+            adb.shell_nocheck("rm -r {}".format(AdbFile.DEVICE_TEMP_FILE))
+            try:
+                adb.push(local=tmp.name, remote=AdbFile.DEVICE_TEMP_FILE)
+                dev_md5, _ = adb.shell(
+                    "md5sum {}".format(AdbFile.DEVICE_TEMP_FILE)).split()
+                self.assertEqual(host_md5, dev_md5)
+            finally:
+                adb.shell_nocheck("rm {}".format(AdbFile.DEVICE_TEMP_FILE))
+
+    # TODO: write push directory test.
+
+    def test_pull(self):
+        """Pull a file from all attached devices."""
+        dev_list = get_device_list()
+        for device in dev_list:
+            self.pull_with_device(device)
+
+    def pull_with_device(self, device):
+        """Pull a randomly generated file from specified device."""
+        kbytes = 512
+        adb = AdbWrapper(device)
+        adb.shell_nocheck("rm -r {}".format(AdbFile.DEVICE_TEMP_FILE))
+        try:
+            adb.shell("dd if=/dev/urandom of={} bs=1024 count={}".format(
+                AdbFile.DEVICE_TEMP_FILE, kbytes))
+            dev_md5, _ = adb.shell(
+                "md5sum {}".format(AdbFile.DEVICE_TEMP_FILE)).split()
+
+            with tempfile.NamedTemporaryFile(mode="w") as tmp_write:
+                adb.pull(remote=AdbFile.DEVICE_TEMP_FILE, local=tmp_write.name)
+                with open(tmp_write.name) as tmp_read:
+                    host_contents = tmp_read.read()
+                    host_md5 = compute_md5(host_contents)
+                self.assertEqual(dev_md5, host_md5)
+        finally:
+            adb.shell_nocheck("rm {}".format(AdbFile.DEVICE_TEMP_FILE))
+
+    def test_pull_dir(self):
+        """Pull a directory from all attached devices."""
+        dev_list = get_device_list()
+        for device in dev_list:
+            self.pull_dir_with_device(device)
+
+    def pull_dir_with_device(self, device):
+        """Pull a randomly generated directory of files from the device."""
+        adb = AdbWrapper(device)
+        temp_files = {}
+        host_dir = None
+        try:
+            # create temporary host directory
+            host_dir = tempfile.mkdtemp()
+
+            # create temporary dir on device
+            adb.shell_nocheck("rm -r {}".format(AdbFile.DEVICE_TEMP_DIR))
+            adb.shell("mkdir -p {}".format(AdbFile.DEVICE_TEMP_DIR))
+
+            # populate device dir with random files
+            temp_files = make_random_device_files(
+                adb, in_dir=AdbFile.DEVICE_TEMP_DIR, num_files=32)
+
+            adb.pull(remote=AdbFile.DEVICE_TEMP_DIR, local=host_dir)
+
+            for device_full_path in temp_files:
+                host_path = os.path.join(
+                    host_dir, temp_files[device_full_path].base_name)
+                with open(host_path) as host_file:
+                    host_md5 = compute_md5(host_file.read())
+                    self.assertEqual(host_md5,
+                                     temp_files[device_full_path].md5)
+        finally:
+            for dev_file in temp_files.values():
+                host_path = os.path.join(host_dir, dev_file.base_name)
+                os.remove(host_path)
+            adb.shell_nocheck("rm -r {}".format(AdbFile.DEVICE_TEMP_DIR))
+            if host_dir:
+                os.removedirs(host_dir)
+
+    def test_sync(self):
+        """Sync a directory with all attached devices."""
+        dev_list = get_device_list()
+        for device in dev_list:
+            self.sync_dir_with_device(device)
+
+    def sync_dir_with_device(self, device):
+        """Sync a randomly generated directory of files to specified device."""
+        try:
+            adb = AdbWrapper(device)
+            temp_files = {}
+
+            # create temporary host directory
+            base_dir = tempfile.mkdtemp()
+
+            # create mirror device directory hierarchy within base_dir
+            full_dir_path = base_dir + AdbFile.DEVICE_TEMP_DIR
+            os.makedirs(full_dir_path)
+
+            # create 32 random files within the host mirror
+            temp_files = make_random_host_files(in_dir=full_dir_path,
+                                                num_files=32)
+
+            # clean up any trash on the device
+            adb = AdbWrapper(device, out_dir=base_dir)
+            adb.shell_nocheck("rm -r {}".format(AdbFile.DEVICE_TEMP_DIR))
+
+            # issue the sync
+            adb.sync("data")
+
+            # confirm that every file on the device mirrors that on the host
+            for host_full_path in temp_files.keys():
+                device_full_path = os.path.join(
+                    AdbFile.DEVICE_TEMP_DIR,
+                    temp_files[host_full_path].base_name)
+                dev_md5, _ = adb.shell(
+                    "md5sum {}".format(device_full_path)).split()
+                self.assertEqual(temp_files[host_full_path].md5, dev_md5)
+
+        finally:
+            adb.shell_nocheck("rm -r {}".format(AdbFile.DEVICE_TEMP_DIR))
+            if temp_files:
+                for tf in temp_files.values():
+                    tf.handle.close()
+            if base_dir:
+                os.removedirs(base_dir + AdbFile.DEVICE_TEMP_DIR)
+
+
+if __name__ == '__main__':
+    random.seed(0)
+    dev_count = get_attached_device_count()
+    if dev_count:
+        suite = unittest.TestLoader().loadTestsFromName(__name__)
+        unittest.TextTestRunner(verbosity=3).run(suite)
+    else:
+        print "Test suite must be run with attached devices"
diff --git a/include/utils/Mutex.h b/include/utils/Mutex.h
index 4fdd27f..a3b594d 100644
--- a/include/utils/Mutex.h
+++ b/include/utils/Mutex.h
@@ -131,8 +131,8 @@
 #if HAVE_ANDROID_OS
 inline status_t Mutex::timedLock(nsecs_t timeoutNs) {
     const struct timespec ts = {
-        /* .tv_sec = */ timeoutNs / 1000000000,
-        /* .tv_nsec = */ timeoutNs % 1000000000,
+        /* .tv_sec = */ static_cast<time_t>(timeoutNs / 1000000000),
+        /* .tv_nsec = */ static_cast<long>(timeoutNs % 1000000000),
     };
     return -pthread_mutex_timedlock(&mMutex, &ts);
 }
diff --git a/init/property_service.c b/init/property_service.c
index 1f98e13..55e37b9 100644
--- a/init/property_service.c
+++ b/init/property_service.c
@@ -534,6 +534,7 @@
     load_properties_from_file(PROP_PATH_SYSTEM_BUILD, NULL);
     load_properties_from_file(PROP_PATH_SYSTEM_DEFAULT, NULL);
     load_properties_from_file(PROP_PATH_VENDOR_BUILD, NULL);
+    load_properties_from_file(PROP_PATH_BOOTIMAGE_BUILD, NULL);
     load_properties_from_file(PROP_PATH_FACTORY, "ro.*");
 
     load_override_properties();
diff --git a/logd/LogBuffer.cpp b/logd/LogBuffer.cpp
index 1c74ba5..6307bed 100644
--- a/logd/LogBuffer.cpp
+++ b/logd/LogBuffer.cpp
@@ -242,7 +242,7 @@
     LastLogTimes::iterator t = mTimes.begin();
     while(t != mTimes.end()) {
         LogTimeEntry *entry = (*t);
-        if (entry->owned_Locked()
+        if (entry->owned_Locked() && entry->isWatching(id)
                 && (!oldest || (oldest->mStart > entry->mStart))) {
             oldest = entry;
         }
@@ -354,7 +354,7 @@
                         // kick a misbehaving log reader client off the island
                         oldest->release_Locked();
                     } else {
-                        oldest->triggerSkip_Locked(pruneRows);
+                        oldest->triggerSkip_Locked(id, pruneRows);
                     }
                 }
                 break;
@@ -385,7 +385,7 @@
                         // kick a misbehaving log reader client off the island
                         oldest->release_Locked();
                     } else {
-                        oldest->triggerSkip_Locked(pruneRows);
+                        oldest->triggerSkip_Locked(id, pruneRows);
                     }
                     break;
                 }
diff --git a/logd/LogTimes.cpp b/logd/LogTimes.cpp
index ea4e8c8..5f9db8d 100644
--- a/logd/LogTimes.cpp
+++ b/logd/LogTimes.cpp
@@ -36,7 +36,6 @@
         , mReader(reader)
         , mLogMask(logMask)
         , mPid(pid)
-        , skipAhead(0)
         , mCount(0)
         , mTail(tail)
         , mIndex(0)
@@ -46,6 +45,7 @@
         , mEnd(CLOCK_MONOTONIC)
 {
         pthread_cond_init(&threadTriggeredCondition, NULL);
+        cleanSkip_Locked();
 }
 
 void LogTimeEntry::startReader_Locked(void) {
@@ -148,6 +148,8 @@
             break;
         }
 
+        me->cleanSkip_Locked();
+
         pthread_cond_wait(&me->threadTriggeredCondition, &timesLock);
     }
 
@@ -169,7 +171,7 @@
     }
 
     if ((!me->mPid || (me->mPid == element->getPid()))
-            && (me->mLogMask & (1 << element->getLogId()))) {
+            && (me->isWatching(element->getLogId()))) {
         ++me->mCount;
     }
 
@@ -184,19 +186,19 @@
 
     LogTimeEntry::lock();
 
-    if (me->skipAhead) {
-        me->skipAhead--;
+    me->mStart = element->getMonotonicTime();
+
+    if (me->skipAhead[element->getLogId()]) {
+        me->skipAhead[element->getLogId()]--;
         goto skip;
     }
 
-    me->mStart = element->getMonotonicTime();
-
     // Truncate to close race between first and second pass
     if (me->mNonBlock && me->mTail && (me->mIndex >= me->mCount)) {
         goto skip;
     }
 
-    if ((me->mLogMask & (1 << element->getLogId())) == 0) {
+    if (!me->isWatching(element->getLogId())) {
         goto skip;
     }
 
@@ -223,7 +225,7 @@
     }
 
 ok:
-    if (!me->skipAhead) {
+    if (!me->skipAhead[element->getLogId()]) {
         LogTimeEntry::unlock();
         return true;
     }
@@ -233,3 +235,9 @@
     LogTimeEntry::unlock();
     return false;
 }
+
+void LogTimeEntry::cleanSkip_Locked(void) {
+    for (log_id_t i = LOG_ID_MIN; i < LOG_ID_MAX; i = (log_id_t) (i + 1)) {
+        skipAhead[i] = 0;
+    }
+}
diff --git a/logd/LogTimes.h b/logd/LogTimes.h
index 0bfa7a2..81aedfb 100644
--- a/logd/LogTimes.h
+++ b/logd/LogTimes.h
@@ -22,6 +22,7 @@
 #include <sys/types.h>
 #include <sysutils/SocketClient.h>
 #include <utils/List.h>
+#include <log/log.h>
 
 class LogReader;
 
@@ -38,7 +39,7 @@
     static void threadStop(void *me);
     const unsigned int mLogMask;
     const pid_t mPid;
-    unsigned int skipAhead;
+    unsigned int skipAhead[LOG_ID_MAX];
     unsigned long mCount;
     unsigned long mTail;
     unsigned long mIndex;
@@ -67,7 +68,8 @@
         pthread_cond_signal(&threadTriggeredCondition);
     }
 
-    void triggerSkip_Locked(unsigned int skip) { skipAhead = skip; }
+    void triggerSkip_Locked(log_id_t id, unsigned int skip) { skipAhead[id] = skip; }
+    void cleanSkip_Locked(void);
 
     // Called after LogTimeEntry removed from list, lock implicitly held
     void release_Locked(void) {
@@ -99,7 +101,7 @@
         // No one else is holding a reference to this
         delete this;
     }
-
+    bool isWatching(log_id_t id) { return (mLogMask & (1<<id)) != 0; }
     // flushTo filter callbacks
     static bool FilterFirstPass(const LogBufferElement *element, void *me);
     static bool FilterSecondPass(const LogBufferElement *element, void *me);
diff --git a/rootdir/etc/hosts b/rootdir/etc/hosts
index 99848f6..649151c 100644
--- a/rootdir/etc/hosts
+++ b/rootdir/etc/hosts
@@ -1 +1,2 @@
-127.0.0.1		    localhost
+127.0.0.1       localhost
+::1             ip6-localhost
diff --git a/rootdir/init.rc b/rootdir/init.rc
index 9093b54..642af09 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -157,6 +157,8 @@
     mount pstore pstore /sys/fs/pstore
     chown system log /sys/fs/pstore/console-ramoops
     chmod 0440 /sys/fs/pstore/console-ramoops
+    chown system log /sys/fs/pstore/pmsg-ramoops-0
+    chmod 0440 /sys/fs/pstore/pmsg-ramoops-0
 
 # Healthd can trigger a full boot from charger mode by signaling this
 # property when the power button is held.
diff --git a/rootdir/ueventd.rc b/rootdir/ueventd.rc
index eff24c3..43d7bc9 100644
--- a/rootdir/ueventd.rc
+++ b/rootdir/ueventd.rc
@@ -16,6 +16,7 @@
 # Anyone can read the logs, but if they're not in the "logs"
 # group, then they'll only see log entries for their UID.
 /dev/log/*                0666   root       log
+/dev/pmsg0                0222   root       log
 
 # the msm hw3d client device node is world writable/readable.
 /dev/msm_hw3dc            0666   root       root
diff --git a/toolbox/Android.mk b/toolbox/Android.mk
index ebe94d5..e9fb201 100644
--- a/toolbox/Android.mk
+++ b/toolbox/Android.mk
@@ -13,13 +13,6 @@
 
 
 include $(CLEAR_VARS)
-LOCAL_SRC_FILES := upstream-netbsd/bin/cat/cat.c
-LOCAL_CFLAGS += $(common_cflags) -Dmain=cat_main
-LOCAL_MODULE := libtoolbox_cat
-LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
 LOCAL_SRC_FILES := upstream-netbsd/sbin/chown/chown.c
 LOCAL_CFLAGS += $(common_cflags) -Dmain=chown_main
 LOCAL_MODULE := libtoolbox_chown
@@ -62,7 +55,6 @@
 include $(CLEAR_VARS)
 
 BSD_TOOLS := \
-    cat \
     chown \
     dd \
     du \
@@ -70,13 +62,11 @@
 
 OUR_TOOLS := \
     cmp \
-    date \
     df \
     getevent \
     getprop \
     getsebool \
     id \
-    ifconfig \
     iftop \
     ioctl \
     ionice \
@@ -87,7 +77,6 @@
     mount \
     nandread \
     newfs_msdos \
-    notify \
     ps \
     renice \
     restorecon \
diff --git a/toolbox/date.c b/toolbox/date.c
deleted file mode 100644
index 70ce1d5..0000000
--- a/toolbox/date.c
+++ /dev/null
@@ -1,227 +0,0 @@
-#include <ctype.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <inttypes.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-#include <unistd.h>
-
-#include <linux/android_alarm.h>
-#include <linux/rtc.h>
-#include <sys/ioctl.h>
-
-static int settime_alarm(struct timespec *ts) {
-    int fd, ret;
-
-    fd = open("/dev/alarm", O_RDWR);
-    if (fd < 0)
-        return fd;
-
-    ret = ioctl(fd, ANDROID_ALARM_SET_RTC, ts);
-    close(fd);
-    return ret;
-}
-
-static int settime_alarm_tm(struct tm *tm) {
-    time_t t;
-    struct timespec ts;
-
-    t = mktime(tm);
-    ts.tv_sec = t;
-    ts.tv_nsec = 0;
-    return settime_alarm(&ts);
-}
-
-static int settime_alarm_timeval(struct timeval *tv) {
-    struct timespec ts;
-
-    ts.tv_sec = tv->tv_sec;
-    ts.tv_nsec = tv->tv_usec * 1000;
-    return settime_alarm(&ts);
-}
-
-static int settime_rtc_tm(struct tm *tm) {
-    int fd, ret;
-    struct timeval tv;
-    struct rtc_time rtc;
-
-    fd = open("/dev/rtc0", O_RDWR);
-    if (fd < 0)
-        return fd;
-
-    tv.tv_sec = mktime(tm);
-    tv.tv_usec = 0;
-
-    ret = settimeofday(&tv, NULL);
-    if (ret < 0)
-        goto done;
-
-    memset(&rtc, 0, sizeof(rtc));
-    rtc.tm_sec = tm->tm_sec;
-    rtc.tm_min = tm->tm_min;
-    rtc.tm_hour = tm->tm_hour;
-    rtc.tm_mday = tm->tm_mday;
-    rtc.tm_mon = tm->tm_mon;
-    rtc.tm_year = tm->tm_year;
-    rtc.tm_wday = tm->tm_wday;
-    rtc.tm_yday = tm->tm_yday;
-    rtc.tm_isdst = tm->tm_isdst;
-
-    ret = ioctl(fd, RTC_SET_TIME, rtc);
-done:
-    close(fd);
-    return ret;
-}
-
-static int settime_rtc_timeval(struct timeval *tv) {
-    struct tm tm, *err;
-    time_t t = tv->tv_sec;
-
-    err = gmtime_r(&t, &tm);
-    if (!err)
-        return -1;
-
-    return settime_rtc_tm(&tm);
-}
-
-static void settime(char *s) {
-    struct tm tm;
-    int day = atoi(s);
-    int hour;
-
-    while (*s && *s != '.')
-        s++;
-
-    if (*s)
-        s++;
-
-    hour = atoi(s);
-
-    tm.tm_year = day / 10000 - 1900;
-    tm.tm_mon = (day % 10000) / 100 - 1;
-    tm.tm_mday = (day % 100);
-    tm.tm_hour = hour / 10000;
-    tm.tm_min = (hour % 10000) / 100;
-    tm.tm_sec = (hour % 100);
-    tm.tm_isdst = -1;
-
-    if (settime_alarm_tm(&tm) < 0)
-        settime_rtc_tm(&tm);
-}
-
-static char *parse_time(const char *str, struct timeval *ts) {
-  char *s;
-  long fs = 0; /* fractional seconds */
-
-  ts->tv_sec = strtoumax(str, &s, 10);
-
-  if (*s == '.') {
-    s++;
-    int count = 0;
-
-    /* read up to 6 digits (microseconds) */
-    while (*s && isdigit(*s)) {
-      if (++count < 7) {
-        fs = fs*10 + (*s - '0');
-      }
-      s++;
-    }
-
-    for (; count < 6; count++) {
-      fs *= 10;
-    }
-  }
-
-  ts->tv_usec = fs;
-  return s;
-}
-
-int date_main(int argc, char *argv[])
-{
-    int c;
-    int res;
-    struct tm tm;
-    time_t t;
-    struct timeval tv;
-    char strbuf[260];
-
-    int useutc = 0;
-
-    tzset();
-
-    do {
-        c = getopt(argc, argv, "us:");
-        if (c == EOF)
-            break;
-        switch (c) {
-        case 'u':
-            useutc = 1;
-            break;
-        case 's':
-            settime(optarg);
-            break;
-        case '?':
-            fprintf(stderr, "%s: invalid option -%c\n",
-                argv[0], optopt);
-            exit(1);
-        }
-    } while (1);
-    if(optind + 2 < argc) {
-        fprintf(stderr,"%s [-u] [date]\n", argv[0]);
-        return 1;
-    }
-
-    int hasfmt = argc == optind + 1 && argv[optind][0] == '+';
-    if(optind == argc || hasfmt) {
-        time(&t);
-        if (useutc) {
-            gmtime_r(&t, &tm);
-            strftime(strbuf, sizeof(strbuf),
-                     (hasfmt ? argv[optind] + 1 : "%a %b %e %H:%M:%S GMT %Y"),
-                     &tm);
-        } else {
-            localtime_r(&t, &tm);
-            strftime(strbuf, sizeof(strbuf),
-                     (hasfmt ? argv[optind] + 1 : "%a %b %e %H:%M:%S %Z %Y"),
-                     &tm);
-        }
-        printf("%s\n", strbuf);
-    }
-    else if(optind + 1 == argc) {
-#if 0
-        struct tm *tmptr;
-        tmptr = getdate(argv[optind]);
-        if(tmptr == NULL) {
-            fprintf(stderr,"getdate_r failed\n");
-            return 1;
-        }
-        tm = *tmptr;
-#if 0
-        if(getdate_r(argv[optind], &tm) < 0) {
-            fprintf(stderr,"getdate_r failed %s\n", strerror(errno));
-            return 1;
-        }
-#endif
-#endif
-        //strptime(argv[optind], NULL, &tm);
-        //tv.tv_sec = mktime(&tm);
-        //tv.tv_usec = 0;
-        parse_time(argv[optind], &tv);
-        printf("time %s -> %lu.%lu\n", argv[optind], tv.tv_sec, tv.tv_usec);
-        res = settime_alarm_timeval(&tv);
-        if (res < 0)
-            res = settime_rtc_timeval(&tv);
-        if(res < 0) {
-            fprintf(stderr,"settimeofday failed %s\n", strerror(errno));
-            return 1;
-        }
-    }
-    else {
-        fprintf(stderr,"%s [-s 20070325.123456] [-u] [date]\n", argv[0]);
-        return 1;
-    }
-
-    return 0;
-}
diff --git a/toolbox/ifconfig.c b/toolbox/ifconfig.c
deleted file mode 100644
index b953176..0000000
--- a/toolbox/ifconfig.c
+++ /dev/null
@@ -1,157 +0,0 @@
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-
-#include <errno.h>
-#include <string.h>
-#include <ctype.h>
-
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <linux/if.h>
-#include <linux/sockios.h>
-#include <arpa/inet.h>
-
-static void die(const char *s)
-{
-    fprintf(stderr,"error: %s (%s)\n", s, strerror(errno));
-    exit(-1);
-}
-
-static void setflags(int s, struct ifreq *ifr, int set, int clr)
-{
-    if(ioctl(s, SIOCGIFFLAGS, ifr) < 0) die("SIOCGIFFLAGS");
-    ifr->ifr_flags = (ifr->ifr_flags & (~clr)) | set;
-    if(ioctl(s, SIOCSIFFLAGS, ifr) < 0) die("SIOCSIFFLAGS");
-}
-
-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);
-}
-
-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);
-    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);
-    if(ioctl(s, SIOCSIFADDR, ifr) < 0) die("SIOCSIFADDR");
-}
-
-int ifconfig_main(int argc, char *argv[])
-{
-    struct ifreq ifr;
-    int s;
-    unsigned int flags;
-    char astring[20];
-    char mstring[20];
-    char *updown, *brdcst, *loopbk, *ppp, *running, *multi;
-
-    argc--;
-    argv++;
-
-    if(argc == 0) return 0;
-
-    memset(&ifr, 0, sizeof(struct ifreq));
-    strncpy(ifr.ifr_name, argv[0], IFNAMSIZ);
-    ifr.ifr_name[IFNAMSIZ-1] = 0;
-    argc--, argv++;
-
-    if((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
-        die("cannot open control socket\n");
-    }
-
-    if (argc == 0) {
-        if (ioctl(s, SIOCGIFADDR, &ifr) < 0) {
-            perror(ifr.ifr_name);
-            return -1;
-        } else
-            strlcpy(astring,
-                   inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr),
-                   sizeof(astring));
-
-        if (ioctl(s, SIOCGIFNETMASK, &ifr) < 0) {
-            perror(ifr.ifr_name);
-            return -1;
-        } else
-            strlcpy(mstring,
-                   inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr),
-                   sizeof(mstring));
-
-        if (ioctl(s, SIOCGIFFLAGS, &ifr) < 0) {
-            perror(ifr.ifr_name);
-            return -1;
-        } else
-            flags = ifr.ifr_flags;
-
-        printf("%s: ip %s mask %s flags [", ifr.ifr_name,
-               astring,
-               mstring
-               );
-
-        updown =  (flags & IFF_UP)           ? "up" : "down";
-        brdcst =  (flags & IFF_BROADCAST)    ? " broadcast" : "";
-        loopbk =  (flags & IFF_LOOPBACK)     ? " loopback" : "";
-        ppp =     (flags & IFF_POINTOPOINT)  ? " point-to-point" : "";
-        running = (flags & IFF_RUNNING)      ? " running" : "";
-        multi =   (flags & IFF_MULTICAST)    ? " multicast" : "";
-        printf("%s%s%s%s%s%s]\n", updown, brdcst, loopbk, ppp, running, multi);
-        return 0;
-    }
-    
-    while(argc > 0) {
-        if (!strcmp(argv[0], "up")) {
-            setflags(s, &ifr, IFF_UP, 0);
-        } 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 (!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/notify.c b/toolbox/notify.c
deleted file mode 100644
index 8ce346c..0000000
--- a/toolbox/notify.c
+++ /dev/null
@@ -1,149 +0,0 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <stdint.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <sys/ioctl.h>
-#include <sys/inotify.h>
-#include <errno.h>
-
-int notify_main(int argc, char *argv[])
-{
-    int c;
-    int nfd, ffd;
-    int res;
-	char event_buf[512];
-    struct inotify_event *event;
-	int event_mask = IN_ALL_EVENTS;
-    int event_count = 1;
-	int print_files = 0;
-	int verbose = 2;
-	int width = 80;
-	char **file_names;
-	int file_count;
-	int id_offset = 0;
-	int i;
-	char *buf;
-
-    do {
-        c = getopt(argc, argv, "m:c:pv:w:");
-        if (c == EOF)
-            break;
-        switch (c) {
-        case 'm':
-            event_mask = strtol(optarg, NULL, 0);
-            break;
-        case 'c':
-            event_count = atoi(optarg);
-            break;
-		case 'p':
-			print_files = 1;
-			break;
-        case 'v':
-            verbose = atoi(optarg);
-            break;
-        case 'w':
-            width = atoi(optarg);
-            break;
-        case '?':
-            fprintf(stderr, "%s: invalid option -%c\n",
-                argv[0], optopt);
-            exit(1);
-        }
-    } while (1);
-
-    if (argc <= optind) {
-        fprintf(stderr, "Usage: %s [-m eventmask] [-c count] [-p] [-v verbosity] path [path ...]\n", argv[0]);
-		return 1;
-    }
-
-    nfd = inotify_init();
-    if(nfd < 0) {
-        fprintf(stderr, "inotify_init failed, %s\n", strerror(errno));
-        return 1;
-    }
-	file_names = argv + optind;
-	file_count = argc - optind;
-	for(i = 0; i < file_count; i++) {
-		res = inotify_add_watch(nfd, file_names[i], event_mask);
-		if(res < 0) {
-	        fprintf(stderr, "inotify_add_watch failed for %s, %s\n", file_names[i], strerror(errno));
-			return 1;
-		}
-		if(i == 0)
-			id_offset = -res;
-		if(res + id_offset != i) {
-			fprintf(stderr, "%s got unexpected id %d instead of %d\n", file_names[i], res, i);
-			return 1;
-		}
-	}
-
-	buf = malloc(width + 2);
-    
-    while(1) {
-		int event_pos = 0;
-        res = read(nfd, event_buf, sizeof(event_buf));
-        if(res < (int)sizeof(*event)) {
-			if(errno == EINTR)
-				continue;
-            fprintf(stderr, "could not get event, %s\n", strerror(errno));
-            return 1;
-        }
-		//printf("got %d bytes of event information\n", res);
-		while(res >= (int)sizeof(*event)) {
-			int event_size;
-			event = (struct inotify_event *)(event_buf + event_pos);
-			if(verbose >= 2)
-		        printf("%s: %08x %08x \"%s\"\n", file_names[event->wd + id_offset], event->mask, event->cookie, event->len ? event->name : "");
-			else if(verbose >= 2)
-		        printf("%s: %08x \"%s\"\n", file_names[event->wd + id_offset], event->mask, event->len ? event->name : "");
-			else if(verbose >= 1)
-		        printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
-			if(print_files && (event->mask & IN_MODIFY)) {
-				char* filename = file_names[event->wd + id_offset];
-				char* alloc_buf = NULL;
-				ssize_t read_len;
-				char *display_name;
-				int buflen;
-				if(event->len) {
-					if(asprintf(&alloc_buf, "%s/%s", filename, event->name) < 0) {
-						fprintf(stderr, "asprintf failed, %s\n", strerror(errno));
-						return 1;
-					}
-					filename = alloc_buf;
-				}
-				ffd = open(filename, O_RDONLY);
-				display_name = (verbose >= 2 || event->len == 0) ? filename : event->name;
-				buflen = width - strlen(display_name);
-				read_len = read(ffd, buf, buflen);
-				if(read_len > 0) {
-					if(read_len < buflen && buf[read_len-1] != '\n') {
-						buf[read_len] = '\n';
-						read_len++;
-					}
-					if(read_len == buflen) {
-						buf[--read_len] = '\0';
-						buf[--read_len] = '\n';
-						buf[--read_len] = '.';
-						buf[--read_len] = '.';
-						buf[--read_len] = '.';
-					}
-					else {
-						buf[read_len] = '\0';
-					}
-					printf("%s: %s", display_name, buf);
-				}
-				close(ffd);
-				free(alloc_buf);
-			}
-	        if(event_count && --event_count == 0)
-	            return 0;
-			event_size = sizeof(*event) + event->len;
-			res -= event_size;
-			event_pos += event_size;
-		}
-    }
-
-    return 0;
-}
diff --git a/toolbox/upstream-netbsd/bin/cat/cat.c b/toolbox/upstream-netbsd/bin/cat/cat.c
deleted file mode 100644
index cca8cf5..0000000
--- a/toolbox/upstream-netbsd/bin/cat/cat.c
+++ /dev/null
@@ -1,329 +0,0 @@
-/* $NetBSD: cat.c,v 1.54 2013/12/08 08:32:13 spz Exp $	*/
-
-/*
- * Copyright (c) 1989, 1993
- *	The Regents of the University of California.  All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Kevin Fall.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#if HAVE_NBTOOL_CONFIG_H
-#include "nbtool_config.h"
-#endif
-
-#include <sys/cdefs.h>
-#if !defined(lint)
-__COPYRIGHT(
-"@(#) Copyright (c) 1989, 1993\
- The Regents of the University of California.  All rights reserved.");
-#if 0
-static char sccsid[] = "@(#)cat.c	8.2 (Berkeley) 4/27/95";
-#else
-__RCSID("$NetBSD: cat.c,v 1.54 2013/12/08 08:32:13 spz Exp $");
-#endif
-#endif /* not lint */
-
-#include <sys/param.h>
-#include <sys/stat.h>
-
-#include <ctype.h>
-#include <err.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <locale.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-static int bflag, eflag, fflag, lflag, nflag, sflag, tflag, vflag;
-static size_t bsize;
-static int rval;
-static const char *filename;
-
-void cook_args(char *argv[]);
-void cook_buf(FILE *);
-void raw_args(char *argv[]);
-void raw_cat(int);
-
-int
-main(int argc, char *argv[])
-{
-	int ch;
-	struct flock stdout_lock;
-
-	setprogname(argv[0]);
-	(void)setlocale(LC_ALL, "");
-
-	while ((ch = getopt(argc, argv, "B:beflnstuv")) != -1)
-		switch (ch) {
-		case 'B':
-			bsize = (size_t)strtol(optarg, NULL, 0);
-			break;
-		case 'b':
-			bflag = nflag = 1;	/* -b implies -n */
-			break;
-		case 'e':
-			eflag = vflag = 1;	/* -e implies -v */
-			break;
-		case 'f':
-			fflag = 1;
-			break;
-		case 'l':
-			lflag = 1;
-			break;
-		case 'n':
-			nflag = 1;
-			break;
-		case 's':
-			sflag = 1;
-			break;
-		case 't':
-			tflag = vflag = 1;	/* -t implies -v */
-			break;
-		case 'u':
-			setbuf(stdout, NULL);
-			break;
-		case 'v':
-			vflag = 1;
-			break;
-		default:
-		case '?':
-			(void)fprintf(stderr,
-			    "Usage: %s [-beflnstuv] [-B bsize] [-] "
-			    "[file ...]\n", getprogname());
-			return EXIT_FAILURE;
-		}
-	argv += optind;
-
-	if (lflag) {
-		stdout_lock.l_len = 0;
-		stdout_lock.l_start = 0;
-		stdout_lock.l_type = F_WRLCK;
-		stdout_lock.l_whence = SEEK_SET;
-		if (fcntl(STDOUT_FILENO, F_SETLKW, &stdout_lock) == -1)
-			err(EXIT_FAILURE, "stdout");
-	}
-
-	if (bflag || eflag || nflag || sflag || tflag || vflag)
-		cook_args(argv);
-	else
-		raw_args(argv);
-	if (fclose(stdout))
-		err(EXIT_FAILURE, "stdout");
-	return rval;
-}
-
-void
-cook_args(char **argv)
-{
-	FILE *fp;
-
-	fp = stdin;
-	filename = "stdin";
-	do {
-		if (*argv) {
-			if (!strcmp(*argv, "-"))
-				fp = stdin;
-			else if ((fp = fopen(*argv,
-			    fflag ? "rf" : "r")) == NULL) {
-				warn("%s", *argv);
-				rval = EXIT_FAILURE;
-				++argv;
-				continue;
-			}
-			filename = *argv++;
-		}
-		cook_buf(fp);
-		if (fp != stdin)
-			(void)fclose(fp);
-		else
-			clearerr(fp);
-	} while (*argv);
-}
-
-void
-cook_buf(FILE *fp)
-{
-	int ch, gobble, line, prev;
-
-	line = gobble = 0;
-	for (prev = '\n'; (ch = getc(fp)) != EOF; prev = ch) {
-		if (prev == '\n') {
-			if (ch == '\n') {
-				if (sflag) {
-					if (!gobble && nflag && !bflag)
-						(void)fprintf(stdout,
-							"%6d\t\n", ++line);
-					else if (!gobble && putchar(ch) == EOF)
-						break;
-					gobble = 1;
-					continue;
-				}
-				if (nflag) {
-					if (!bflag) {
-						(void)fprintf(stdout,
-						    "%6d\t", ++line);
-						if (ferror(stdout))
-							break;
-					} else if (eflag) {
-						(void)fprintf(stdout,
-						    "%6s\t", "");
-						if (ferror(stdout))
-							break;
-					}
-				}
-			} else if (nflag) {
-				(void)fprintf(stdout, "%6d\t", ++line);
-				if (ferror(stdout))
-					break;
-			}
-		}
-		gobble = 0;
-		if (ch == '\n') {
-			if (eflag)
-				if (putchar('$') == EOF)
-					break;
-		} else if (ch == '\t') {
-			if (tflag) {
-				if (putchar('^') == EOF || putchar('I') == EOF)
-					break;
-				continue;
-			}
-		} else if (vflag) {
-			if (!isascii(ch)) {
-				if (putchar('M') == EOF || putchar('-') == EOF)
-					break;
-				ch = toascii(ch);
-			}
-			if (iscntrl(ch)) {
-				if (putchar('^') == EOF ||
-				    putchar(ch == '\177' ? '?' :
-				    ch | 0100) == EOF)
-					break;
-				continue;
-			}
-		}
-		if (putchar(ch) == EOF)
-			break;
-	}
-	if (ferror(fp)) {
-		warn("%s", filename);
-		rval = EXIT_FAILURE;
-		clearerr(fp);
-	}
-	if (ferror(stdout))
-		err(EXIT_FAILURE, "stdout");
-}
-
-void
-raw_args(char **argv)
-{
-	int fd;
-
-	fd = fileno(stdin);
-	filename = "stdin";
-	do {
-		if (*argv) {
-			if (!strcmp(*argv, "-")) {
-				fd = fileno(stdin);
-				if (fd < 0)
-					goto skip;
-			} else if (fflag) {
-				struct stat st;
-				fd = open(*argv, O_RDONLY|O_NONBLOCK, 0);
-				if (fd < 0)
-					goto skip;
-
-				if (fstat(fd, &st) == -1) {
-					close(fd);
-					goto skip;
-				}
-				if (!S_ISREG(st.st_mode)) {
-					close(fd);
-					warnx("%s: not a regular file", *argv);
-					goto skipnomsg;
-				}
-			}
-			else if ((fd = open(*argv, O_RDONLY, 0)) < 0) {
-skip:
-				warn("%s", *argv);
-skipnomsg:
-				rval = EXIT_FAILURE;
-				++argv;
-				continue;
-			}
-			filename = *argv++;
-		} else if (fd < 0) {
-			err(EXIT_FAILURE, "stdin");
-		}
-		raw_cat(fd);
-		if (fd != fileno(stdin))
-			(void)close(fd);
-	} while (*argv);
-}
-
-void
-raw_cat(int rfd)
-{
-	static char *buf;
-	static char fb_buf[BUFSIZ];
-
-	ssize_t nr, nw, off;
-	int wfd;
-
-	wfd = fileno(stdout);
-	if (wfd < 0)
-		err(EXIT_FAILURE, "stdout");
-	if (buf == NULL) {
-		struct stat sbuf;
-
-		if (bsize == 0) {
-			if (fstat(wfd, &sbuf) == 0 && sbuf.st_blksize > 0 &&
-			    (size_t)sbuf.st_blksize > sizeof(fb_buf))
-				bsize = sbuf.st_blksize;
-		}
-		if (bsize > sizeof(fb_buf)) {
-			buf = malloc(bsize);
-			if (buf == NULL)
-				warnx("malloc, using %zu buffer", bsize);
-		}
-		if (buf == NULL) {
-			bsize = sizeof(fb_buf);
-			buf = fb_buf;
-		}
-	}
-	while ((nr = read(rfd, buf, bsize)) > 0)
-		for (off = 0; nr; nr -= nw, off += nw)
-			if ((nw = write(wfd, buf + off, (size_t)nr)) < 0)
-				err(EXIT_FAILURE, "stdout");
-	if (nr < 0) {
-		warn("%s", filename);
-		rval = EXIT_FAILURE;
-	}
-}