Probe for QEMU machine types

Probe for QEMU machine types

Currently we hardcode the QEMU machine types. We should really just
parse the output of 'qemu -M ?' so the lists don't get out of sync.

xenner doesn't support '-M ?', so we still need to hardcode that.

The horrible (const char *const *) is removed in a subsequent patch.

* src/qemu_conf.c: kill the arch_info*machines tables, retain the
  hardcoded xenner machine type, add qemudProbeMachineTypes() to
  run and parse 'qemu -M ?' and use it in qemudCapsInitGuest()

--- src/qemu_conf.c
+++ src/qemu_conf.c
@@ -283,31 +283,6 @@
     return 0;
 }

-/* The list of possible machine types for various architectures,
-   as supported by QEMU - taken from 'qemu -M ?' for each arch */
-static const char *const arch_info_hvm_x86_machines[] = {
-    "pc", "isapc"
-};
-static const char *const arch_info_hvm_arm_machines[] = {
-  "versatilepb","integratorcp","versatileab","realview",
-  "akita","spitz","borzoi","terrier","sx1-v1","sx1",
-  "cheetah","n800","n810","lm3s811evb","lm3s6965evb",
-  "connex","verdex","mainstone","musicpal","tosa",
-};
-static const char *const arch_info_hvm_mips_machines[] = {
-    "mips"
-};
-static const char *const arch_info_hvm_sparc_machines[] = {
-    "sun4m"
-};
-static const char *const arch_info_hvm_ppc_machines[] = {
-    "g3beige", "mac99", "prep"
-};
-
-static const char *const arch_info_xen_x86_machines[] = {
-    "xenner"
-};
-
 struct qemu_feature_flags {
     const char *name;
     const int default_on;
@@ -317,8 +292,7 @@
 struct qemu_arch_info {
     const char *arch;
     int wordsize;
-    const char *const *machines;
-    int nmachines;
+    const char *machine;
     const char *binary;
     const char *altbinary;
     const struct qemu_feature_flags *flags;
@@ -340,28 +314,134 @@

 /* The archicture tables for supported QEMU archs */
 static const struct qemu_arch_info const arch_info_hvm[] = {
-    {  "i686", 32, arch_info_hvm_x86_machines, 2,
-       "/usr/bin/qemu", "/usr/bin/qemu-system-x86_64", arch_info_i686_flags, 4 },
-    {  "x86_64", 64, arch_info_hvm_x86_machines, 2,
-       "/usr/bin/qemu-system-x86_64", NULL, arch_info_x86_64_flags, 2 },
-    {  "arm", 32, arch_info_hvm_arm_machines, 20,
-       "/usr/bin/qemu-system-arm", NULL, NULL, 0 },
-    {  "mips", 32, arch_info_hvm_mips_machines, 1,
-       "/usr/bin/qemu-system-mips", NULL, NULL, 0 },
-    {  "mipsel", 32, arch_info_hvm_mips_machines, 1,
-       "/usr/bin/qemu-system-mipsel", NULL, NULL, 0 },
-    {  "sparc", 32, arch_info_hvm_sparc_machines, 1,
-       "/usr/bin/qemu-system-sparc", NULL, NULL, 0 },
-    {  "ppc", 32, arch_info_hvm_ppc_machines, 3,
-       "/usr/bin/qemu-system-ppc", NULL, NULL, 0 },
+    {  "i686",   32, NULL, "/usr/bin/qemu",
+       "/usr/bin/qemu-system-x86_64", arch_info_i686_flags, 4 },
+    {  "x86_64", 64, NULL, "/usr/bin/qemu-system-x86_64",
+       NULL, arch_info_x86_64_flags, 2 },
+    {  "arm",    32, NULL, "/usr/bin/qemu-system-arm",    NULL, NULL, 0 },
+    {  "mips",   32, NULL, "/usr/bin/qemu-system-mips",   NULL, NULL, 0 },
+    {  "mipsel", 32, NULL, "/usr/bin/qemu-system-mipsel", NULL, NULL, 0 },
+    {  "sparc",  32, NULL, "/usr/bin/qemu-system-sparc",  NULL, NULL, 0 },
+    {  "ppc",    32, NULL, "/usr/bin/qemu-system-ppc",    NULL, NULL, 0 },
 };

 static const struct qemu_arch_info const arch_info_xen[] = {
-    {  "i686", 32, arch_info_xen_x86_machines, 1,
-       "/usr/bin/xenner", NULL, arch_info_i686_flags, 4 },
-    {  "x86_64", 64, arch_info_xen_x86_machines, 1,
-       "/usr/bin/xenner", NULL, arch_info_x86_64_flags, 2 },
+    {  "i686",   32, "xenner", "/usr/bin/xenner", NULL, arch_info_i686_flags, 4 },
+    {  "x86_64", 64, "xenner", "/usr/bin/xenner", NULL, arch_info_x86_64_flags, 2 },
 };
+
+
+/* Format is:
+ * <machine> <desc> [(default)]
+ */
+static int
+qemudParseMachineTypesStr(const char *output,
+                          char ***machines,
+                          int *nmachines)
+{
+    const char *p = output;
+    const char *next;
+    char **list = NULL;
+    int i, nitems = 0;
+
+    do {
+        const char *t;
+        char *machine;
+
+        if ((next = strchr(p, '\n')))
+            ++next;
+
+        if (STRPREFIX(p, "Supported machines are:"))
+            continue;
+
+        if (!(t = strchr(p, ' ')) || (next && t >= next))
+            continue;
+
+        if (!(machine = strndup(p, t - p)))
+            goto error;
+
+        if (VIR_REALLOC_N(list, nitems + 1) < 0) {
+            VIR_FREE(machine);
+            goto error;
+        }
+
+        p = t;
+        if (!(t = strstr(p, "(default)")) || (next && t >= next)) {
+            list[nitems++] = machine;
+        } else {
+            /* put the default first in the list */
+            memmove(list + 1, list, sizeof(*list) * nitems);
+            list[0] = machine;
+            nitems++;
+        }
+    } while ((p = next));
+
+    *machines = list;
+    *nmachines = nitems;
+
+    return 0;
+
+error:
+    for (i = 0; i < nitems; i++)
+        VIR_FREE(list[i]);
+    VIR_FREE(list);
+    return -1;
+}
+
+static int
+qemudProbeMachineTypes(const char *binary,
+                       char ***machines,
+                       int *nmachines)
+{
+    const char *const qemuarg[] = { binary, "-M", "?", NULL };
+    const char *const qemuenv[] = { "LC_ALL=C", NULL };
+    char *output;
+    enum { MAX_MACHINES_OUTPUT_SIZE = 1024*4 };
+    pid_t child;
+    int newstdout = -1, len;
+    int ret = -1, status;
+
+    if (virExec(NULL, qemuarg, qemuenv, NULL,
+                &child, -1, &newstdout, NULL, VIR_EXEC_CLEAR_CAPS) < 0)
+        return -1;
+
+    len = virFileReadLimFD(newstdout, MAX_MACHINES_OUTPUT_SIZE, &output);
+    if (len < 0) {
+        virReportSystemError(NULL, errno, "%s",
+                             _("Unable to read 'qemu -M ?' output"));
+        goto cleanup;
+    }
+
+    if (qemudParseMachineTypesStr(output, machines, nmachines) < 0)
+        goto cleanup2;
+
+    ret = 0;
+
+cleanup2:
+    VIR_FREE(output);
+cleanup:
+    if (close(newstdout) < 0)
+        ret = -1;
+
+rewait:
+    if (waitpid(child, &status, 0) != child) {
+        if (errno == EINTR)
+            goto rewait;
+
+        VIR_ERROR(_("Unexpected exit status from qemu %d pid %lu"),
+                  WEXITSTATUS(status), (unsigned long)child);
+        ret = -1;
+    }
+    /* Check & log unexpected exit status, but don't fail,
+     * as there's really no need to throw an error if we did
+     * actually read a valid version number above */
+    if (WEXITSTATUS(status) != 0) {
+        VIR_WARN(_("Unexpected exit status '%d', qemu probably failed"),
+                 WEXITSTATUS(status));
+    }
+
+    return ret;
+}

 static int
 qemudCapsInitGuest(virCapsPtr caps,
@@ -374,6 +454,8 @@
     int haskqemu = 0;
     const char *kvmbin = NULL;
     const char *binary = NULL;
+    char **machines = NULL;
+    int nmachines = 0;

     /* Check for existance of base emulator, or alternate base
      * which can be used with magic cpu choice
@@ -412,6 +494,23 @@
     if (!binary)
         return 0;

+    if (info->machine) {
+        char *machine;
+
+        if (!(machine = strdup(info->machine)))
+            return -1;
+
+        if (VIR_ALLOC_N(machines, nmachines) < 0) {
+            VIR_FREE(machine);
+            return -1;
+        }
+
+        machines[0] = machine;
+        nmachines = 1;
+
+    } else if (qemudProbeMachineTypes(binary, &machines, &nmachines) < 0)
+        return -1;
+
     /* We register kvm as the base emulator too, since we can
      * just give -no-kvm to disable acceleration if required */
     if ((guest = virCapabilitiesAddGuest(caps,
@@ -420,9 +519,17 @@
                                          info->wordsize,
                                          binary,
                                          NULL,
-                                         info->nmachines,
-                                         info->machines)) == NULL)
+                                         nmachines,
+                                         (const char *const *)machines)) == NULL) {
+        for (i = 0; i < nmachines; i++)
+            VIR_FREE(machines[i]);
+        VIR_FREE(machines);
         return -1;
+    }
+
+    for (i = 0; i < nmachines; i++)
+        VIR_FREE(machines[i]);
+    VIR_FREE(machines);

     if (hvm) {
         if (virCapabilitiesAddGuestDomain(guest,


Ignore two cases where we expect mkdir to fail.

1) mkdir will fail if directory already exists
2) mkdir will fail if we call mkdir(""); just don't do that.

--- src/bigfile.c
+++ src/bigfile.c
@@ -1738,13 +1738,19 @@
 {
     char * subdirname = strdup(subdir);
     char * p;
+    int mkdirret;

     char * mydirname;
     for(p = subdirname; *p; p ++) {
         if(*p != '/') continue;
         *p = 0;
         mydirname = _path_join(pathname, subdirname);
-        RAISEIF(mkdir(mydirname, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH),
+        if(mydirname[0] == '\0'){
+            *p='/';
+            continue;
+        }
+        mkdirret = mkdir(mydirname, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
+        RAISEIF(mkdirret !=0 && errno != EEXIST,
             ex_mkdir,
             "Failed to create directory structure at `%s' (%s)",
             mydirname,
@@ -1754,8 +1760,9 @@
         *p = '/';
     }
     mydirname = _path_join(pathname, subdirname);
+    mkdirret = mkdir(mydirname, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
     struct stat buf;
-    RAISEIF(mkdir(mydirname, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) || stat(mydirname, &buf),
+    RAISEIF((mkdirret !=0 && errno != EEXIST) || stat(mydirname, &buf),
             ex_mkdir,
             "Failed to create directory structure at `%s' (%s)",
             mydirname,


process - use the glib memory slice allocator

Trying to reduce heap fragmentation as this is intended to be a long
running process but is doing quite a lot of small heap allocations.

--- src/process.c
+++ src/process.c
@@ -1,8 +1,7 @@
 #include "duckhunter.h"

 void start_processing_event(nlcn_ev_msg * nlcn_msg) {
-    proc_event_baton_t *baton =
-                   (proc_event_baton_t *)calloc(1, sizeof(proc_event_baton_t));
+    proc_event_baton_t *baton = g_slice_new0(proc_event_baton_t);
     baton->req.data = (void *)baton;
     switch(nlcn_msg->nl_body.proc_ev.what) {
         case PROC_EVENT_FORK:
@@ -384,6 +383,6 @@
     bdestroy(baton_p->process_exe);
     bdestroy(baton_p->process_proc_cmdline);
     bdestroy(baton_p->process_cmdline);
-    free(*baton_pp);
+    g_slice_free(proc_event_baton_t, *baton_pp);
     *baton_pp = NULL;
 }


private: trivial format tweaks

private: trivial format tweaks

--- src/private.h
+++ src/private.h
@@ -1,69 +1,95 @@
 #ifndef CHEWING_PRIVATE_H
-#    define CHEWING_PRIVATE_H
+#define CHEWING_PRIVATE_H

-#    ifdef HAVE_CONFIG_H
-#        include <config.h>
-#    endif
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif

 /* Platform-dependent declaration */
-#    include "plat_types.h"
+#include "plat_types.h"

-#    define LOG_VERBOSE(fmt, ...) \
-	do { pgdata->logger(pgdata->loggerData, CHEWING_LOG_VERBOSE, "[%s:%d %s] " fmt "\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__); } while (0)
+#define LOG_VERBOSE(fmt, ...) \
+    do { \
+        pgdata->logger(pgdata->loggerData, CHEWING_LOG_VERBOSE, \
+                       "[%s:%d %s] " fmt "\n", \
+                       __FILE__, __LINE__, __func__, ##__VA_ARGS__); \
+    } while (0)

-#    define LOG_DEBUG(fmt, ...) \
-	do { pgdata->logger(pgdata->loggerData, CHEWING_LOG_DEBUG, "[%s:%d %s] " fmt "\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__); } while (0)
+#define LOG_DEBUG(fmt, ...) \
+    do { \
+        pgdata->logger(pgdata->loggerData, CHEWING_LOG_DEBUG, \
+                       "[%s:%d %s] " fmt "\n", \
+                       __FILE__, __LINE__, __func__, ##__VA_ARGS__); \
+    } while (0)

-#    define LOG_INFO(fmt, ...) \
-	do { pgdata->logger(pgdata->loggerData, CHEWING_LOG_INFO, "[%s:%d %s] " fmt "\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__); } while (0)
+#define LOG_INFO(fmt, ...) \
+    do { \
+        pgdata->logger(pgdata->loggerData, CHEWING_LOG_INFO, \
+                       "[%s:%d %s] " fmt "\n", \
+                       __FILE__, __LINE__, __func__, ##__VA_ARGS__); \
+    } while (0)

-#    define LOG_WARN(fmt, ...) \
-	do { pgdata->logger(pgdata->loggerData, CHEWING_LOG_WARN, "[%s:%d %s] " fmt "\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__); } while (0)
+#define LOG_WARN(fmt, ...) \
+    do { \
+        pgdata->logger(pgdata->loggerData, CHEWING_LOG_WARN, \
+                       "[%s:%d %s] " fmt "\n", \
+                       __FILE__, __LINE__, __func__, ##__VA_ARGS__); \
+    } while (0)

-#    define LOG_ERROR(fmt, ...) \
-	do { pgdata->logger(pgdata->loggerData, CHEWING_LOG_ERROR, "[%s:%d %s] " fmt "\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__); } while (0)
+#define LOG_ERROR(fmt, ...) \
+    do { \
+        pgdata->logger(pgdata->loggerData, CHEWING_LOG_ERROR, \
+                       "[%s:%d %s] " fmt "\n", \
+                       __FILE__, __LINE__, __func__, ##__VA_ARGS__); \
+    } while (0)

-#    define DEBUG_OUT( fmt, ... ) \
-	do { \
-		pgdata->logger( pgdata->loggerData, CHEWING_LOG_INFO, fmt, ##__VA_ARGS__ ); \
-	} while (0)
+#define DEBUG_OUT( fmt, ... ) \
+    do { \
+        pgdata->logger(pgdata->loggerData, CHEWING_LOG_INFO, fmt, \
+        ##__VA_ARGS__ ); \
+    } while (0)

-#    define DEBUG_CHECKPOINT() \
-	do { \
-		pgdata->logger( pgdata->loggerData, CHEWING_LOG_VERBOSE, "[ File: %s  Func: %s  Line: %d ]\n", \
-			__FILE__, __FUNCTION__, __LINE__ ); \
-	} while (0)
+#define DEBUG_CHECKPOINT() \
+    do { \
+        pgdata->logger(pgdata->loggerData, CHEWING_LOG_VERBOSE, \
+                       "[ File: %s  Func: %s  Line: %d ]\n", \
+                       __FILE__, __FUNCTION__, __LINE__ ); \
+    } while (0)

-// Use LOG_API to log all public API call.
-#    define LOG_API(fmt, ...) do { LOG_INFO("API call: " fmt, ##__VA_ARGS__); } while (0)
+/* Use LOG_API to log all public API call. */
+#define LOG_API(fmt, ...) \
+    do { \
+        LOG_INFO("API call: " fmt, ##__VA_ARGS__); \
+    } while (0)

-#    define ALC(type, size) \
-	(type *) calloc( size, sizeof( type ) )
+#define ALC(type, size) \
+    (type *) calloc(size, sizeof(type))

-#    define ASSERT_CONCAT_(a, b) a##b
-#    define ASSERT_CONCAT(a, b) ASSERT_CONCAT_(a, b)
-#    ifdef __COUNTER__
-#        define STATIC_ASSERT(e) \
+#define ASSERT_CONCAT_(a, b) a##b
+#define ASSERT_CONCAT(a, b) ASSERT_CONCAT_(a, b)
+
+#ifdef __COUNTER__
+#define STATIC_ASSERT(e) \
     { enum { ASSERT_CONCAT(static_assert_, __COUNTER__) = 1/(!!(e)) }; }
-#    else
+#else
   /* This can't be used twice on the same line so ensure if using in headers
    * that the headers are not included twice (by wrapping in #ifndef...#endif)
    * Note it doesn't cause an issue when used on same line of separate modules
    * compiled with gcc -combine -fwhole-program.  */
-#        define STATIC_ASSERT(e) \
+#define STATIC_ASSERT(e) \
     { enum { ASSERT_CONCAT(assert_line_, __LINE__) = 1/(!!(e)) }; }
-#    endif
+#endif

-#    ifdef __GNUC__
-#        define ARRAY_SIZE( array ) ( sizeof(array) / sizeof(((typeof(array)){})[0]) )
-#    else
-#        define ARRAY_SIZE( array ) ( sizeof(array) / sizeof(array[0] ) )
-#    endif
+#ifdef __GNUC__
+#define ARRAY_SIZE(array) (sizeof(array) / sizeof(((typeof(array)){})[0]))
+#else
+#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
+#endif

-typedef int (*CompFuncType) (const void *, const void *);
+typedef int (*CompFuncType)(const void *, const void *);

-#    define CEIL_DIV(a, b) (((a) + (b) - 1) / (b))
+#define CEIL_DIV(a, b) (((a) + (b) - 1) / (b))

-#    define __stringify(x)  #x
+#define __stringify(x)  #x

 #endif


dns_rbt_deletefromlevel() did not need its dns_rbt_t argument

--- lib/dns/rbt.c
+++ lib/dns/rbt.c
@@ -15,7 +15,7 @@
  * SOFTWARE.
  */

-/* $Id: rbt.c,v 1.82 2000/06/06 23:25:29 tale Exp $ */
+/* $Id: rbt.c,v 1.83 2000/06/19 22:55:42 tale Exp $ */

 /* Principal Authors: DCL */

@@ -179,8 +179,7 @@
 		   dns_rbtnode_t **rootp, dns_rbtnodechain_t *chain);

 static void
-dns_rbt_deletefromlevel(dns_rbt_t *rbt, dns_rbtnode_t *delete,
-			dns_rbtnode_t **rootp);
+dns_rbt_deletefromlevel(dns_rbtnode_t *delete, dns_rbtnode_t **rootp);

 static void
 dns_rbt_deletetree(dns_rbt_t *rbt, dns_rbtnode_t *node);
@@ -1195,8 +1194,8 @@
 	 * have one to start, or because it was recursively removed).
 	 * So now the node needs to be removed from this level.
 	 */
-	dns_rbt_deletefromlevel(rbt, node,
-				parent == NULL ? &rbt->root : &DOWN(parent));
+	dns_rbt_deletefromlevel(node, parent == NULL ? &rbt->root :
+						       &DOWN(parent));

 	if (rbt->data_deleter != NULL)
 		rbt->data_deleter(DATA(node), rbt->deleter_arg);
@@ -1563,13 +1562,10 @@
  * true red/black tree on a single level.
  */
 static void
-dns_rbt_deletefromlevel(dns_rbt_t *rbt, dns_rbtnode_t *delete,
-			dns_rbtnode_t **rootp)
-{
+dns_rbt_deletefromlevel(dns_rbtnode_t *delete, dns_rbtnode_t **rootp) {
 	dns_rbtnode_t *child, *sibling, *parent;
 	dns_rbtnode_t *successor;

-	REQUIRE(VALID_RBT(rbt));
 	REQUIRE(delete != NULL);

 	/*


add signing -serial to rndc usage

add signing -serial to rndc usage

--- bin/rndc/rndc.c
+++ bin/rndc/rndc.c
@@ -176,6 +176,8 @@
 		Prime zone with NSEC3 chain if not yet signed.\n\
   signing -nsec3param none zone [class [view]]\n\
 		Remove NSEC3 chains from zone.\n\
+  signing -serial <value> zone [class [view]]\n\
+		Set the zones's serial to <value>.\n\
   stats		Write server statistics to the statistics file.\n\
   status	Display status of the server.\n\
   stop		Save pending updates to master files and stop the server.\n\


Long-overdue removal of TODO

Long-overdue removal of TODO

--- src/RenderSystem.h
+++ src/RenderSystem.h
@@ -25,7 +25,7 @@
 		~RenderSystem();

 		void draw(Scene* scene);
-		void resizeWindow(unsigned int width, unsigned int height); //TODO: Window resizing
+		void resizeWindow(unsigned int width, unsigned int height);
 };

 #endif


cosmetics, do not dereference char* whilst incrementing with no side-effect

Signed-off-by: Sebastian Freundt <1f0829204b3475c52f714f96be4e7b39a87b6e74@ga-group.nl>

--- lib/dt-core.c
+++ lib/dt-core.c
@@ -213,9 +213,9 @@
 	}
 	/* and now parse the time */
 	d.st.h = strtoui_lim(sp, &sp, 0, 23);
-	*sp++;
+	sp++;
 	d.st.m = strtoui_lim(sp, &sp, 0, 59);
-	*sp++;
+	sp++;
 	d.st.s = strtoui_lim(sp, &sp, 0, 60);

 	if (d.st.h < -1U && d.st.m < -1U && d.st.s < -1U) {


privsep: Set buffer sizes before setting rights.

--- src/privsep.c
+++ src/privsep.c
@@ -201,6 +201,7 @@
 		*priv_pid = pid;
 		*priv_fd = fd[0];
 		close(fd[1]);
+		ps_setbuf(*priv_fd);
 		if (recv_unpriv_msg == NULL)
 			;
 #ifdef HAVE_CAPSICUM
@@ -217,7 +218,6 @@
 			logerr("%s: eloop_event_add", __func__);
 			return -1;
 		}
-		ps_setbuf(*priv_fd);
 		return pid;
 	}


Fixed segfault on specifying an empty dir

--- src/browser.c
+++ src/browser.c
@@ -473,6 +473,7 @@
     browse_dir = cur;
   if(browse_dir != NULL && browse_dir->parent->sub != browse_dir)
     browse_dir = cur->parent->sub;
-  browse_dir = browse_sort(browse_dir);
-}
-
+  if(browse_dir != NULL)
+    browse_dir = browse_sort(browse_dir);
+}
+


add-in nice field in proc_t

add-in nice field in proc_t

--- src/process.h
+++ src/process.h
@@ -13,6 +13,7 @@
     char *user;
     int pid;
     int cpuset;
+    int nice;
     float mempcent;
     proc_t *next;
 };


chore, introduce DT_UNK as dt_dttyp_t

chore, introduce DT_UNK as dt_dttyp_t

Signed-off-by: Sebastian Freundt <1f0829204b3475c52f714f96be4e7b39a87b6e74@ga-group.nl>

--- lib/dt-core.h
+++ lib/dt-core.h
@@ -63,6 +63,8 @@
 #include "time-core.h"

 typedef enum {
+	/* this one's our own version of UNK */
+	DT_UNK = 0,
 	/* the lower date types come from date-core.h */
 	DT_PACK = DT_NDTYP,
 	DT_YMDHMS = DT_PACK,
@@ -239,13 +241,13 @@
 dt_dt_initialiser(void)
 {
 #if defined __C1X
-	struct dt_dt_s res = {.d.typ = DT_UNK, .d.u = 0, .t.u = 0};
+	struct dt_dt_s res = {.typ = DT_UNK, .d.u = 0, .t.u = 0};
 #else  /* !__C1X */
 	struct dt_dt_s res;
 #endif	/* __C1X */

 #if !defined __C1X
-	res.d.typ = DT_UNK;
+	res.typ = DT_UNK;
 	res.d.u = 0;
 	res.t.u = 0;
 #endif	/* !__C1X */
@@ -270,7 +272,7 @@
 	return d.sandwich && d.typ == DT_UNK;
 }

-#define DT_SANDWICH_UNK		(dt_dttyp_t)(DT_UNK)
+#define DT_SANDWICH_UNK		(DT_UNK)

 static inline void
 dt_make_sandwich(struct dt_dt_s *d, dt_dtyp_t dty, dt_ttyp_t tty)


reintroduce REDISCLI_CLUSTER_YES env variable in redis-cli

the variable was introduced only in the 5.0 branch in #5879 bc6c1c40db

--- src/redis-cli.c
+++ src/redis-cli.c
@@ -73,6 +73,7 @@
 #define REDIS_CLI_RCFILE_ENV "REDISCLI_RCFILE"
 #define REDIS_CLI_RCFILE_DEFAULT ".redisclirc"
 #define REDIS_CLI_AUTH_ENV "REDISCLI_AUTH"
+#define REDIS_CLI_CLUSTER_YES_ENV "REDISCLI_CLUSTER_YES"

 #define CLUSTER_MANAGER_SLOTS               16384
 #define CLUSTER_MANAGER_MIGRATE_TIMEOUT     60000
@@ -1668,6 +1669,11 @@
     if (auth != NULL && config.auth == NULL) {
         config.auth = auth;
     }
+
+    char *cluster_yes = getenv(REDIS_CLI_CLUSTER_YES_ENV);
+    if (cluster_yes != NULL && !strcmp(cluster_yes, "1")) {
+        config.cluster_manager_command.flags |= CLUSTER_MANAGER_CMD_FLAG_YES;
+    }
 }

 static sds readArgFromStdin(void) {


No longer needed

No longer needed

No longer needed

--- src/program.c
+++ src/program.c
@@ -1,162 +0,0 @@
-#include "program.h"
-#include "trigmath.h"
-#include "draw.h"
-#include "images.h"
-#include "space.h"
-
-#include "dynamic_libs/os_functions.h"
-
-void cleanSlate()
-{
-	// clear both buffers
-	int ii;
-	for(ii=0;ii<2;ii++)
-	{
-		fillScreen(0,0,0,0);
-		flipBuffers();
-	}
-}
-int _entryPoint()
-{
-	InitOSFunctionPointers();
-    InitVPadFunctionPointers();
-
-	//Call the Screen initilzation function.
-	OSScreenInit();
-
-	//Grab the buffer size for each screen (TV and gamepad)
-	int buf0_size = OSScreenGetBufferSizeEx(0);
-	int buf1_size = OSScreenGetBufferSizeEx(1);
-	//Set the buffer area.
-	OSScreenSetBufferEx(0, (void *)0xF4000000);
-	OSScreenSetBufferEx(1, (void *)0xF4000000 + buf0_size);
-
-	cleanSlate();
-
-	OSScreenEnableEx(0, 1);
-    OSScreenEnableEx(1, 1);
-
-	/****************************>             Globals             <****************************/
-	struct SpaceGlobals mySpaceGlobals;
-	//Flag for restarting the entire game.
-	mySpaceGlobals.restart = 1;
-
-	// initial state is title screen
-	mySpaceGlobals.state = 1;
-	mySpaceGlobals.titleScreenRefresh = 1;
-
-	//Flags for render states
-	mySpaceGlobals.renderResetFlag = 0;
-	mySpaceGlobals.menuChoice = 0; // 0 is play, 1 is password
-
-	// setup the password list
-	unsigned int pwSeed = 27;
-	int x;
-	for (x=0; x<100; x++)
-		mySpaceGlobals.passwordList[x] = (int)(prand(&pwSeed)*100000);
-
-	// set the starting time
-	unsigned int coreinit_handle;
-	OSDynLoad_Acquire("coreinit.rpl", &coreinit_handle);
-	int64_t (*OSGetTime)();
-	OSDynLoad_FindExport(coreinit_handle, 0, "OSGetTime", &OSGetTime);
-	mySpaceGlobals.seed = OSGetTime();
-
-	/****************************>            VPAD Loop            <****************************/
-	int error;
-	VPADData vpad_data;
-
-	// decompress compressed things into their arrays, final argument is the transparent color in their palette
-	decompress_sprite(3061, 200, 100, compressed_title, mySpaceGlobals.title, 39);
-	decompress_sprite(511, 36, 36, compressed_ship, mySpaceGlobals.orig_ship, 14);
-	decompress_sprite(206, 23, 23, compressed_enemy, mySpaceGlobals.enemy, 9);
-
-	// setup palette and transparent index
-	mySpaceGlobals.curPalette = ship_palette;
-	mySpaceGlobals.transIndex = 14;
-
-	// initialize starfield for this game
-	initStars(&mySpaceGlobals);
-
-	mySpaceGlobals.invalid = 1;
-
-	while (1)
-	{
-		VPADRead(0, &vpad_data, 1, &error);
-
-		//Get the status of the gamepad
-		mySpaceGlobals.button = vpad_data.btns_h;
-
-		mySpaceGlobals.rstick = vpad_data.rstick;
-		mySpaceGlobals.lstick = vpad_data.lstick;
-
-		mySpaceGlobals.touched = vpad_data.tpdata.touched;
-		if (mySpaceGlobals.touched == 1)
-		{
-			mySpaceGlobals.touchX = ((vpad_data.tpdata.x / 9) - 11);
-			mySpaceGlobals.touchY = ((3930 - vpad_data.tpdata.y) / 16);
-		}
-
-		if (mySpaceGlobals.restart == 1)
-		{
-			reset(&mySpaceGlobals);
-			mySpaceGlobals.restart = 0;
-		}
-
-		if (mySpaceGlobals.state == 1) // title screen
-		{
-			displayTitle(&mySpaceGlobals);
-			doMenuAction(&mySpaceGlobals);
-		}
-		else if (mySpaceGlobals.state == 2) // password screen
-		{
-			displayPasswordScreen(&mySpaceGlobals);
-			doPasswordMenuAction(&mySpaceGlobals);
-		}
-		else if (mySpaceGlobals.state == 3) // pause screen
-		{
-			displayPause(&mySpaceGlobals);
-			doMenuAction(&mySpaceGlobals);
-		}
-		else if  (mySpaceGlobals.state == 4) // game over screen
-		{
-			displayGameOver(&mySpaceGlobals);
-			doMenuAction(&mySpaceGlobals);
-		}
-		else 	// game play
-		{
-			//Update location of player1 and 2 paddles
-			p1Move(&mySpaceGlobals);
-
-			// perform any shooting
-			p1Shoot(&mySpaceGlobals);
-
-			// handle any collisions
-			handleCollisions(&mySpaceGlobals);
-
-			// do explosions
-			handleExplosions(&mySpaceGlobals);
-
-			// if we're out of lives, break
-			if (mySpaceGlobals.lives <= 0 && mySpaceGlobals.state == 4)
-				continue;
-
-			// add any new enemies
-			addNewEnemies(&mySpaceGlobals);
-
-			//Render the scene
-			render(&mySpaceGlobals);
-
-			// check for pausing
-			checkPause(&mySpaceGlobals);
-		}
-		//To exit the game
-		if (mySpaceGlobals.button&VPAD_BUTTON_HOME)
-		{
-			break;
-		}
-
-	}
-	cleanSlate();
-	return 0;
-}


Allow drawing the browser frame when there's no directory structure

--- src/browser.c
+++ src/browser.c
@@ -236,16 +236,24 @@
   mvhline(winrows-1, 0, ' ', wincols);
   mvprintw(0,0,"%s %s ~ Use the arrow keys to navigate, press ? for help", PACKAGE_NAME, PACKAGE_VERSION);

-  strcpy(tmp, formatsize(cur->parent->size));
-  mvprintw(winrows-1, 0, " Total disk usage: %s  Apparent size: %s  Items: %d",
-    tmp, formatsize(cur->parent->asize), cur->parent->items);
+  if(cur) {
+    strcpy(tmp, formatsize(cur->parent->size));
+    mvprintw(winrows-1, 0, " Total disk usage: %s  Apparent size: %s  Items: %d",
+      tmp, formatsize(cur->parent->asize), cur->parent->items);
+  } else
+    mvaddstr(winrows-1, 0, " No items to display.");
   attroff(A_REVERSE);

   mvhline(1, 0, '-', wincols);
-  mvaddch(1, 3, ' ');
-  getpath(cur, tmp);
-  mvaddstr(1, 4, cropstr(tmp, wincols-8));
-  mvaddch(1, 4+((int)strlen(tmp) > wincols-8 ? wincols-8 : (int)strlen(tmp)), ' ');
+  if(cur) {
+    mvaddch(1, 3, ' ');
+    getpath(cur, tmp);
+    mvaddstr(1, 4, cropstr(tmp, wincols-8));
+    mvaddch(1, 4+((int)strlen(tmp) > wincols-8 ? wincols-8 : (int)strlen(tmp)), ' ');
+  }
+
+  if(!cur)
+    return 0;

   /* TODO: don't sort when it's not necessary */
   cur = browse_dir = browse_sort(cur);
@@ -437,18 +445,10 @@

 void browse_init(struct dir *cur) {
-  if(cur == NULL || cur->parent == NULL) {
-    if(cur == NULL || cur->sub == NULL) {
-      erase();
-      refresh();
-      endwin();
-      printf("No items to display...\n");
-      exit(0);
-    } else
-      browse_dir = cur->sub;
-  } else
+  pstate = ST_BROWSE;
+  if(cur != NULL && cur->parent == NULL)
+    browse_dir = cur->sub;
+  else
     browse_dir = cur;
-
-  pstate = ST_BROWSE;
-}
-
+}
+


strtoq -> strtoll (strtoq is deprecated)

--- bin/test/test.c
+++ bin/test/test.c
@@ -181,7 +181,7 @@
 static int	equalf __P((const char *, const char *));
 static int	filstat __P((char *, enum token));
 static int	getn __P((const char *));
-static quad_t	getq __P((const char *));
+static long long	getq __P((const char *));
 static int	intcmp __P((const char *, const char *));
 static int	isoperand __P((void));
 int		main __P((int, char **));
@@ -491,15 +491,15 @@
 }

 /* atoi with error detection and 64 bit range */
-static quad_t
+static long long
 getq(s)
 	const char *s;
 {
 	char *p;
-	quad_t r;
+	long long r;

 	errno = 0;
-	r = strtoq(s, &p, 10);
+	r = strtoll(s, &p, 10);

 	if (s == p)
 		error("%s: bad number", s);
@@ -521,7 +521,7 @@
 intcmp (s1, s2)
 	const char *s1, *s2;
 {
-	quad_t q1, q2;
+	long long q1, q2;

 	q1 = getq(s1);


Check that we have connection before enabling pipe mode

--- src/redis-cli.c
+++ src/redis-cli.c
@@ -1233,7 +1233,7 @@

     /* Pipe mode */
     if (config.pipe_mode) {
-        cliConnect(0);
+        if (cliConnect(0) == REDIS_ERR) exit(1);
         pipeMode();
     }


Handle error path upon filename encoding conversion errors

--- src/browser.c
+++ src/browser.c
@@ -1217,9 +1217,15 @@
 		)
 {
 	char const * p;
-
-	if((p = g_filename_to_utf8(*display, -1, NULL, NULL, NULL)) != NULL)
-		*display = p; /* XXX should display be free'd? */
+	GError * error = NULL;
+
+	if((p = g_filename_to_utf8(*display, -1, NULL, NULL, &error)) == NULL)
+	{
+		browser_error(NULL, error->message, 1);
+		g_error_free(error);
+	}
+	else
+		*display = p; /* XXX memory leak */
 	*inode = lst->st_ino;
 	*size = lst->st_size;
 	*dsize = _insert_size(lst->st_size);
@@ -2680,12 +2686,19 @@

 static void _refresh_title(Browser * browser)
 {
+	char const * title = browser->current->data;
+	char * p;
+	GError * error = NULL;
 	char buf[256];
-	char * p;
-
-	p = g_filename_to_utf8(browser->current->data, -1, NULL, NULL, NULL);
-	snprintf(buf, sizeof(buf), "%s%s%s", _("File manager"), " - ",
-			(p != NULL) ? p : (char *)browser->current->data);
+
+	if((p = g_filename_to_utf8(title, -1, NULL, NULL, &error)) == NULL)
+	{
+		browser_error(NULL, error->message, 1);
+		g_error_free(error);
+	}
+	else
+		title = p;
+	snprintf(buf, sizeof(buf), "%s%s%s", _("File manager"), " - ", title);
 	free(p);
 	gtk_window_set_title(GTK_WINDOW(browser->window), buf);
 }
@@ -2694,13 +2707,19 @@
 {
 	static unsigned int cnt = 0;
 	GtkWidget * widget;
+	char * p;
+	GError * error = NULL;
 	unsigned int i;
-	char * p;
 	char * q;

 	widget = gtk_bin_get_child(GTK_BIN(browser->tb_path));
-	p = g_filename_to_utf8(browser->current->data, -1, NULL, NULL, NULL);
-	gtk_entry_set_text(GTK_ENTRY(widget), p != NULL ? p
+	if((p = g_filename_to_utf8(browser->current->data, -1, NULL, NULL,
+					&error)) == NULL)
+	{
+		browser_error(NULL, error->message, 1);
+		g_error_free(error);
+	}
+	gtk_entry_set_text(GTK_ENTRY(widget), (p != NULL) ? p
 			: browser->current->data);
 	free(p);
 	for(i = 0; i < cnt; i++)


Cluster Manager: rebalance command

Cluster Manager: rebalance command

--- src/redis-cli.c
+++ src/redis-cli.c
@@ -71,6 +71,7 @@
 #define CLUSTER_MANAGER_SLOTS 16384
 #define CLUSTER_MANAGER_MIGRATE_TIMEOUT     60000
 #define CLUSTER_MANAGER_MIGRATE_PIPELINE    10
+#define CLUSTER_MANAGER_REBALANCE_THRESHOLD 2

 #define CLUSTER_MANAGER_INVALID_HOST_ARG \
     "Invalid arguments: you need to pass either a valid " \
@@ -108,10 +109,13 @@
 #define CLUSTER_MANAGER_FLAG_DISCONNECT 1 << 4
 #define CLUSTER_MANAGER_FLAG_FAIL       1 << 5

-#define CLUSTER_MANAGER_CMD_FLAG_FIX    1 << 0
-#define CLUSTER_MANAGER_CMD_FLAG_SLAVE  1 << 1
-#define CLUSTER_MANAGER_CMD_FLAG_YES    1 << 2
-#define CLUSTER_MANAGER_CMD_FLAG_COLOR  1 << 7
+#define CLUSTER_MANAGER_CMD_FLAG_FIX            1 << 0
+#define CLUSTER_MANAGER_CMD_FLAG_SLAVE          1 << 1
+#define CLUSTER_MANAGER_CMD_FLAG_YES            1 << 2
+#define CLUSTER_MANAGER_CMD_FLAG_AUTOWEIGHTS    1 << 3
+#define CLUSTER_MANAGER_CMD_FLAG_EMPTYMASTER    1 << 4
+#define CLUSTER_MANAGER_CMD_FLAG_SIMULATE       1 << 5
+#define CLUSTER_MANAGER_CMD_FLAG_COLOR          1 << 7

 #define CLUSTER_MANAGER_OPT_GETFRIENDS  1 << 0
 #define CLUSTER_MANAGER_OPT_COLD        1 << 1
@@ -157,9 +161,12 @@
     int replicas;
     char *from;
     char *to;
+    char **weight;
+    int weight_argc;
     int slots;
     int timeout;
     int pipeline;
+    float threshold;
 } clusterManagerCommand;
 static void createClusterManagerCommand(char *cmdname, int argc, char **argv);

@@ -206,6 +213,7 @@
     int eval_ldb_end;   /* Lua debugging session ended. */
     int enable_ldb_on_eval; /* Handle manual SCRIPT DEBUG + EVAL commands. */
     int last_cmd_type;
+    int verbose;
     clusterManagerCommand cluster_manager_command;
 } config;

@@ -1266,6 +1274,8 @@
         } else if (!strcmp(argv[i],"-d") && !lastarg) {
             sdsfree(config.mb_delim);
             config.mb_delim = sdsnew(argv[++i]);
+        } else if (!strcmp(argv[i],"--verbose")) {
+            config.verbose = 1;
         } else if (!strcmp(argv[i],"--cluster") && !lastarg) {
             if (CLUSTER_MANAGER_MODE()) usage();
             char *cmd = argv[++i];
@@ -1282,15 +1292,35 @@
             config.cluster_manager_command.from = argv[++i];
         } else if (!strcmp(argv[i],"--cluster-to") && !lastarg) {
             config.cluster_manager_command.to = argv[++i];
+        } else if (!strcmp(argv[i],"--cluster-weight") && !lastarg) {
+            int widx = i + 1;
+            char **weight = argv + widx;
+            int wargc = 0;
+            for (; widx < argc; widx++) {
+                if (strstr(argv[widx], "--") == argv[widx]) break;
+                wargc++;
+            }
+            if (wargc > 0) {
+                config.cluster_manager_command.weight = weight;
+                config.cluster_manager_command.weight_argc = wargc;
+            }
         } else if (!strcmp(argv[i],"--cluster-slots") && !lastarg) {
             config.cluster_manager_command.slots = atoi(argv[++i]);
         } else if (!strcmp(argv[i],"--cluster-timeout") && !lastarg) {
             config.cluster_manager_command.timeout = atoi(argv[++i]);
         } else if (!strcmp(argv[i],"--cluster-pipeline") && !lastarg) {
             config.cluster_manager_command.pipeline = atoi(argv[++i]);
+        } else if (!strcmp(argv[i],"--cluster-threshold") && !lastarg) {
+            config.cluster_manager_command.threshold = atof(argv[++i]);
         } else if (!strcmp(argv[i],"--cluster-yes")) {
             config.cluster_manager_command.flags |=
                 CLUSTER_MANAGER_CMD_FLAG_YES;
+        } else if (!strcmp(argv[i],"--cluster-simulate")) {
+            config.cluster_manager_command.flags |=
+                CLUSTER_MANAGER_CMD_FLAG_SIMULATE;
+        } else if (!strcmp(argv[i],"--cluster-use-empty-masters")) {
+            config.cluster_manager_command.flags |=
+                CLUSTER_MANAGER_CMD_FLAG_EMPTYMASTER;
         } else if (!strcmp(argv[i],"-v") || !strcmp(argv[i], "--version")) {
             sds version = cliVersion();
             printf("redis-cli %s\n", version);
@@ -1390,6 +1420,7 @@
 "                     are not rolled back from the server memory.\n"
 "  --cluster <command> [args...] [opts...]\n"
 "                     Cluster Manager command and arguments (see below).\n"
+"  --verbose          Verbose mode.\n"
 "  --help             Output this help and exit.\n"
 "  --version          Output version and exit.\n"
 "\n"
@@ -1749,6 +1780,8 @@
     sds *importing;
     int migrating_count;
     int importing_count;
+    float weight;   /* Weight used by rebalance */
+    int balance;    /* Used by rebalance */
 } clusterManagerNode;

 /* Data structure used to represent a sequence of nodes. */
@@ -1780,6 +1813,7 @@

 static clusterManagerNode *clusterManagerNewNode(char *ip, int port);
 static clusterManagerNode *clusterManagerNodeByName(const char *name);
+static clusterManagerNode *clusterManagerNodeByAbbreviatedName(const char *n);
 static void clusterManagerNodeResetSlots(clusterManagerNode *node);
 static int clusterManagerNodeIsCluster(clusterManagerNode *node, char **err);
 static int clusterManagerNodeLoadInfo(clusterManagerNode *node, int opts,
@@ -1813,6 +1847,7 @@
 static int clusterManagerCommandInfo(int argc, char **argv);
 static int clusterManagerCommandCheck(int argc, char **argv);
 static int clusterManagerCommandReshard(int argc, char **argv);
+static int clusterManagerCommandRebalance(int argc, char **argv);
 static int clusterManagerCommandCall(int argc, char **argv);
 static int clusterManagerCommandHelp(int argc, char **argv);

@@ -1831,6 +1866,9 @@
     {"info", clusterManagerCommandInfo, -1, "host:port", NULL},
     {"reshard", clusterManagerCommandReshard, -1, "host:port",
      "from <arg>,to <arg>,slots <arg>,yes,timeout <arg>,pipeline <arg>"},
+    {"rebalance", clusterManagerCommandRebalance, -1, "host:port",
+     "weight <node1=w1...nodeN=wN>,use-empty-masters,"
+     "timeout <arg>,simulate,pipeline <arg>,threshold <arg>"},
     {"call", clusterManagerCommandCall, -2,
         "host:port command arg arg .. arg", NULL},
     {"help", clusterManagerCommandHelp, 0, NULL, NULL}
@@ -1970,10 +2008,13 @@
     node->migrating_count = 0;
     node->importing_count = 0;
     node->replicas_count = 0;
+    node->weight = 1.0f;
+    node->balance = 0;
     clusterManagerNodeResetSlots(node);
     return node;
 }

+/* Return the node with the specified ID or NULL. */
 static clusterManagerNode *clusterManagerNodeByName(const char *name) {
     if (cluster_manager.nodes == NULL) return NULL;
     clusterManagerNode *found = NULL;
@@ -1986,6 +2027,32 @@
     while ((ln = listNext(&li)) != NULL) {
         clusterManagerNode *n = ln->value;
         if (n->name && !sdscmp(n->name, lcname)) {
+            found = n;
+            break;
+        }
+    }
+    sdsfree(lcname);
+    return found;
+}
+
+/* Like get_node_by_name but the specified name can be just the first
+ * part of the node ID as long as the prefix in unique across the
+ * cluster.
+ */
+static clusterManagerNode *clusterManagerNodeByAbbreviatedName(const char*name)
+{
+    if (cluster_manager.nodes == NULL) return NULL;
+    clusterManagerNode *found = NULL;
+    sds lcname = sdsempty();
+    lcname = sdscpy(lcname, name);
+    sdstolower(lcname);
+    listIter li;
+    listNode *ln;
+    listRewind(cluster_manager.nodes, &li);
+    while ((ln = listNext(&li)) != NULL) {
+        clusterManagerNode *n = ln->value;
+        if (n->name &&
+            strstr(n->name, lcname) == n->name) {
             found = n;
             break;
         }
@@ -2898,6 +2965,12 @@
     return node2->slots_count - node1->slots_count;
 }

+int clusterManagerCompareNodeBalance(const void *n1, const void *n2) {
+    clusterManagerNode *node1 = *((clusterManagerNode **) n1);
+    clusterManagerNode *node2 = *((clusterManagerNode **) n2);
+    return node1->balance - node2->balance;
+}
+
 static sds clusterManagerGetConfigSignature(clusterManagerNode *node) {
     sds signature = NULL;
     int node_count = 0, i = 0, name_len = 0;
@@ -3200,6 +3273,19 @@
     }
 }

+static void clusterManagerReleaseReshardTable(list *table) {
+    if (table != NULL) {
+        listIter li;
+        listNode *ln;
+        listRewind(table, &li);
+        while ((ln = listNext(&li)) != NULL) {
+            clusterManagerReshardTableItem *item = ln->value;
+            zfree(item);
+        }
+        listRelease(table);
+    }
+}
+
 static void clusterManagerLog(int level, const char* fmt, ...) {
     int use_colors =
         (config.cluster_manager_command.flags & CLUSTER_MANAGER_CMD_FLAG_COLOR);
@@ -3775,14 +3861,199 @@
     }
 cleanup:
     listRelease(sources);
-    if (table) {
-        listRewind(table, &li);
+    clusterManagerReleaseReshardTable(table);
+    return result;
+invalid_args:
+    fprintf(stderr, CLUSTER_MANAGER_INVALID_HOST_ARG);
+    return 0;
+}
+
+static int clusterManagerCommandRebalance(int argc, char **argv) {
+    int port = 0;
+    char *ip = NULL;
+    clusterManagerNode **weightedNodes = NULL;
+    list *involved = NULL;
+    if (!getClusterHostFromCmdArgs(argc, argv, &ip, &port)) goto invalid_args;
+    clusterManagerNode *node = clusterManagerNewNode(ip, port);
+    if (!clusterManagerLoadInfoFromNode(node, 0)) return 0;
+    int result = 1, i;
+    if (config.cluster_manager_command.weight != NULL) {
+        for (i = 0; i < config.cluster_manager_command.weight_argc; i++) {
+            char *name = config.cluster_manager_command.weight[i];
+            char *p = strchr(name, '=');
+            if (p == NULL) {
+                result = 0;
+                goto cleanup;
+            }
+            *p = '\0';
+            float w = atof(++p);
+            clusterManagerNode *n = clusterManagerNodeByAbbreviatedName(name);
+            if (n == NULL) {
+                clusterManagerLogErr("*** No such master node %s\n", name);
+                result = 0;
+                goto cleanup;
+            }
+            n->weight = w;
+        }
+    }
+    float total_weight = 0;
+    int nodes_involved = 0;
+    int use_empty = config.cluster_manager_command.flags &
+                    CLUSTER_MANAGER_CMD_FLAG_EMPTYMASTER;
+
+    involved = listCreate();
+    listIter li;
+    listNode *ln;
+    listRewind(cluster_manager.nodes, &li);
+    /* Compute the total cluster weight. */
+    while ((ln = listNext(&li)) != NULL) {
+        clusterManagerNode *n = ln->value;
+        if (n->flags & CLUSTER_MANAGER_FLAG_SLAVE || n->replicate)
+            continue;
+        if (!use_empty && n->slots_count == 0) {
+            n->weight = 0;
+            continue;
+        }
+        total_weight += n->weight;
+        nodes_involved++;
+        listAddNodeTail(involved, n);
+    }
+    weightedNodes = zmalloc(nodes_involved *
+                                                 sizeof(clusterManagerNode *));
+    if (weightedNodes == NULL) goto cleanup;
+    /* Check cluster, only proceed if it looks sane. */
+    clusterManagerCheckCluster(1);
+    if (cluster_manager.errors && listLength(cluster_manager.errors) > 0) {
+        clusterManagerLogErr("*** Please fix your cluster problems "
+                             "before rebalancing" );
+        result = 0;
+        goto cleanup;
+    }
+    /* Calculate the slots balance for each node. It's the number of
+     * slots the node should lose (if positive) or gain (if negative)
+     * in order to be balanced. */
+    int threshold_reached = 0, total_balance = 0;
+    float threshold = config.cluster_manager_command.threshold;
+    i = 0;
+    listRewind(involved, &li);
+    while ((ln = listNext(&li)) != NULL) {
+        clusterManagerNode *n = ln->value;
+        weightedNodes[i++] = n;
+        int expected = (((float)CLUSTER_MANAGER_SLOTS / total_weight) *
+                        (int) n->weight);
+        n->balance = n->slots_count - expected;
+        total_balance += n->balance;
+	/* Compute the percentage of difference between the
+	 * expected number of slots and the real one, to see
+	 * if it's over the threshold specified by the user. */
+        int over_threshold = 0;
+        if (config.cluster_manager_command.threshold > 0) {
+            if (n->slots_count > 0) {
+                float err_perc = fabs((100-(100.0*expected/n->slots_count)));
+                if (err_perc > threshold) over_threshold = 1;
+            } else if (expected > 1) {
+                over_threshold = 1;
+            }
+        }
+        if (over_threshold) threshold_reached = 1;
+    }
+    if (!threshold_reached) {
+        clusterManagerLogErr("*** No rebalancing needed! "
+                             "All nodes are within the %.2f%% threshold.\n",
+                             config.cluster_manager_command.threshold);
+        result = 0;
+        goto cleanup;
+    }
+    /* Because of rounding, it is possible that the balance of all nodes
+     * summed does not give 0. Make sure that nodes that have to provide
+     * slots are always matched by nodes receiving slots. */
+    while (total_balance > 0) {
+        listRewind(involved, &li);
         while ((ln = listNext(&li)) != NULL) {
-            clusterManagerReshardTableItem *item = ln->value;
-            zfree(item);
-        }
-        listRelease(table);
-    }
+            clusterManagerNode *n = ln->value;
+            if (n->balance < 0 && total_balance > 0) {
+                n->balance--;
+                total_balance--;
+            }
+        }
+    }
+    /* Sort nodes by their slots balance. */
+    qsort(weightedNodes, nodes_involved, sizeof(clusterManagerNode *),
+          clusterManagerCompareNodeBalance);
+    clusterManagerLogInfo(">>> Rebalancing across %d nodes. "
+                          "Total weight = %.2f\n",
+                          nodes_involved, total_weight);
+    if (config.verbose) {
+        for (i = 0; i < nodes_involved; i++) {
+            clusterManagerNode *n = weightedNodes[i];
+            printf("%s:%d balance is %d slots\n", n->ip, n->port, n->balance);
+        }
+    }
+    /* Now we have at the start of the 'sn' array nodes that should get
+     * slots, at the end nodes that must give slots.
+     * We take two indexes, one at the start, and one at the end,
+     * incrementing or decrementing the indexes accordingly til we
+     * find nodes that need to get/provide slots. */
+    int dst_idx = 0;
+    int src_idx = nodes_involved - 1;
+    int simulate = config.cluster_manager_command.flags &
+                   CLUSTER_MANAGER_CMD_FLAG_SIMULATE;
+    while (dst_idx < src_idx) {
+        clusterManagerNode *dst = weightedNodes[dst_idx];
+        clusterManagerNode *src = weightedNodes[src_idx];
+        int db = abs(dst->balance);
+        int sb = abs(src->balance);
+        int numslots = (db < sb ? db : sb);
+        if (numslots > 0) {
+            printf("Moving %d slots from %s:%d to %s:%d\n", numslots,
+                                                            src->ip,
+                                                            src->port,
+                                                            dst->ip,
+                                                            dst->port);
+            /* Actaully move the slots. */
+            list *lsrc = listCreate(), *table = NULL;
+            listAddNodeTail(lsrc, src);
+            table = clusterManagerComputeReshardTable(lsrc, numslots);
+            listRelease(lsrc);
+            int table_len = (int) listLength(table);
+            if (!table || table_len != numslots) {
+                clusterManagerLogErr("*** Assertio failed: Reshard table "
+                                     "!= number of slots");
+                result = 0;
+                goto end_move;
+            }
+            if (simulate) {
+                for (i = 0; i < table_len; i++) printf("#");
+            } else {
+                int opts = CLUSTER_MANAGER_OPT_QUIET |
+                           CLUSTER_MANAGER_OPT_UPDATE;
+                listRewind(table, &li);
+                while ((ln = listNext(&li)) != NULL) {
+                    clusterManagerReshardTableItem *item = ln->value;
+                    result = clusterManagerMoveSlot(item->source,
+                                                    dst,
+                                                    item->slot,
+                                                    opts, NULL);
+                    if (!result) goto end_move;
+                    printf("#");
+                    fflush(stdout);
+                }
+
+            }
+            printf("\n");
+end_move:
+            clusterManagerReleaseReshardTable(table);
+            if (!result) goto cleanup;
+        }
+        /* Update nodes balance. */
+        dst->balance += numslots;
+        src->balance -= numslots;
+        if (dst->balance == 0) dst_idx++;
+        if (src->balance == 0) src_idx --;
+    }
+cleanup:
+    if (involved != NULL) listRelease(involved);
+    if (weightedNodes != NULL) zfree(weightedNodes);
     return result;
 invalid_args:
     fprintf(stderr, CLUSTER_MANAGER_INVALID_HOST_ARG);
@@ -5168,6 +5439,7 @@
     config.eval_ldb_sync = 0;
     config.enable_ldb_on_eval = 0;
     config.last_cmd_type = -1;
+    config.verbose = 0;
     config.cluster_manager_command.name = NULL;
     config.cluster_manager_command.argc = 0;
     config.cluster_manager_command.argv = NULL;
@@ -5175,9 +5447,12 @@
     config.cluster_manager_command.replicas = 0;
     config.cluster_manager_command.from = NULL;
     config.cluster_manager_command.to = NULL;
+    config.cluster_manager_command.weight = NULL;
     config.cluster_manager_command.slots = 0;
     config.cluster_manager_command.timeout = CLUSTER_MANAGER_MIGRATE_TIMEOUT;
     config.cluster_manager_command.pipeline = CLUSTER_MANAGER_MIGRATE_PIPELINE;
+    config.cluster_manager_command.threshold =
+        CLUSTER_MANAGER_REBALANCE_THRESHOLD;
     pref.hints = 1;

     spectrum_palette = spectrum_palette_color;


Simplify some functions by using GMP's integer arithmetic

We don't need to do the division on auxiliary floating-point numbers, we can
just use integer numbers we already have.

--- src/bs_size.c
+++ src/bs_size.c
@@ -417,7 +417,7 @@
  *          (IOW, @size1 / @size2 using integer division)
  */
 guint64 bs_size_div (BSSize *size1, BSSize *size2, GError **error) {
-    mpf_t op1, op2;
+    mpz_t result;
     guint64 ret = 0;

     if (mpz_cmp_ui (size2->priv->bytes, 0) == 0) {
@@ -426,23 +426,18 @@
         return 0;
     }

-    mpf_init2 (op1, BS_FLOAT_PREC_BITS);
-    mpf_init2 (op2, BS_FLOAT_PREC_BITS);
-
-    mpf_set_z (op1, size1->priv->bytes);
-    mpf_set_z (op2, size2->priv->bytes);
-
-    mpf_div (op1, op1, op2);
-
-    if (mpf_cmp_ui (op1, G_MAXUINT64) > 0) {
+    mpz_init (result);
+    mpz_fdiv_q (result, size1->priv->bytes, size2->priv->bytes);
+
+    if (mpz_cmp_ui (result, G_MAXUINT64) > 0) {
         g_set_error (error, BS_SIZE_ERROR, BS_SIZE_ERROR_OVER,
                      "The size is too big, cannot be returned as a 64bit number of bytes");
-        mpf_clears (op1, op2, NULL);
+        mpz_clear (result);
         return 0;
     }
-    ret = (guint64) mpf_get_ui (op1);
-
-    mpf_clears (op1, op2, NULL);
+    ret = (guint64) mpz_get_ui (result);
+
+    mpz_clear (result);
     return ret;
 }

@@ -453,7 +448,6 @@
  *                           rounded to a number of bytes
  */
 BSSize* bs_size_div_int (BSSize *size, guint64 divisor, GError **error) {
-    mpf_t dividend;
     BSSize *ret = NULL;

     if (divisor == 0) {
@@ -462,15 +456,8 @@
         return NULL;
     }

-    mpf_init2 (dividend, BS_FLOAT_PREC_BITS);
-    mpf_set_z (dividend, size->priv->bytes);
-
-    mpf_div_ui (dividend, dividend, divisor);
-
     ret = bs_size_new ();
-
-    mpz_set_f (ret->priv->bytes, dividend);
-    mpf_clear (dividend);
+    mpz_fdiv_q_ui (ret->priv->bytes, size->priv->bytes, divisor);

     return ret;
 }
@@ -482,7 +469,6 @@
  *                           @size1 / @size2 using integer division
  */
 BSSize* bs_size_mod (BSSize *size1, BSSize *size2, GError **error) {
-    mpz_t result;
     BSSize *ret = NULL;
     if (mpz_cmp_ui (size2->priv->bytes, 0) == 0) {
         g_set_error (error, BS_SIZE_ERROR, BS_SIZE_ERROR_ZERO_DIV,
@@ -490,13 +476,9 @@
         return 0;
     }

-    mpz_init (result);
-    mpz_mod (result, size1->priv->bytes, size2->priv->bytes);

     ret = bs_size_new ();
-    mpz_set (ret->priv->bytes, result);
-
-    mpz_clear (result);
-
-    return ret;
-}
+    mpz_mod (ret->priv->bytes, size1->priv->bytes, size2->priv->bytes);
+
+    return ret;
+}


[ADD] BIOS disk-read function(x86 junk-BIOS)

--- bios/junk_x86.h
+++ bios/junk_x86.h
@@ -33,13 +33,20 @@
 		ESP = 0x7c00;
 	}

+	Device::Floppy* GetFloppy(){
+		auto& dev = emu->dev;
+		for(size_t i=0;i<dev.size();i++){
+			if(typeid(*dev[i]) == typeid(Device::Floppy))
+				return dynamic_cast<Device::Floppy*>(dev[i]);
+		}
+		return nullptr;
+	}
+
 	Device::Base* GetBootDevice(){
-		auto& dev = emu->dev;
-		for(size_t i=0; i<dev.size(); i++){
-			if(typeid(*dev[i]) == typeid(Device::Floppy))
-				return dev[i];
-		}
-		throw "No bootable device.";
+		auto fd = GetFloppy();
+		if(fd == nullptr)
+			throw "No bootable device.";
+		return fd;
 	}

 	void LoadIPL(){
@@ -58,8 +65,16 @@
 		case 0x10:
 			video_func();
 			break;
+		case 0x13:
+			disk_func();
+			break;
 		default:
-			throw "not implemented: BIOS function";
+			{
+				std::stringstream ss;
+				ss << "not implemented: BIOS function "
+					<< num;
+				throw ss.str();
+			}
 			break;
 		}
 	}
@@ -72,20 +87,63 @@
 			std::cerr<<"warning: not implemented video mode"<<std::endl;
 			break;
 		case 0x0e:
-			std::cout
 #ifdef DEBUG
-			<<"BIOS function putchar: "
+			std::cout <<"BIOS function putchar: " << AL << std::endl;
 #endif
-			<<AL
-#ifdef DEBUG
-			<<std::endl
-#endif
-			;
 			if(disp == nullptr) throw "BIOS: Display is null";
 			disp->Print(static_cast<char>(AL));
 			break;
 		default:
 			throw "not implemented: video_func(junk BIOS)";
+			break;
+		}
+	}
+
+	void disk_func(){
+		auto fd = GetFloppy();
+		switch(AH){
+		//case 0x00:	// システムのリセット
+		case 0x02:	// 読み込み
+		//case 0x03:	// 書き込み
+		//case 0x04:	// ベリファイ
+		//case 0x0c:	// シーク
+			{
+				// CH=シリンダ番号 & 0xff  <=シリンダ番号下位8bit
+				// CL=セクタ番号(0-5bit) | (シリンダ番号 & 0x300) >> 2
+				// CL:0-5bit=セクタ番号
+				// CL:6-7bit=シリンダ番号9,10bit目
+				// 0xff  = 0000,1111,1111
+				// 0x300 = 0011,0000,0000
+
+				// 本当はシリンダ番号の指定は以下のようになるけど，
+				// フロッピーでは0x00～0x4fだから9,10bit目はいらないのでCHだけでok
+				//uint16_t cyl = CH | ((CL << 2) & 0x300)
+				Device::Floppy::Setting set = {
+					.drive = DL,
+					.head  = (DH==0) ? 0 : 1,
+					.cylinder = CH,
+					.sector = CL // 下位5bit
+				};
+				fd->Seek(set);
+				fd->Read(emu->memory, (ES*16)+BX, AL);
+			}
+			break;
+		//case 0x08:	// パラメータ取得
+		//case 0x09:	// パラメータテーブルの初期化(?)
+		//case 0x10:	// ドライブレディーのテスト
+		//case 0x11:	// ドライブの正規化
+		//case 0x14:	// コントローラの診断
+		//case 0x15:	// ディスクタイプ取得
+		//case 0x16:	// FDの交換チェック
+		//case 0x17:	// FDのディスクタイプの設定
+		//case 0x05:	// FDの物理フォーマット
+		default:
+			{
+				std::stringstream ss;
+				ss << "not implemented: BIOS disk func AH=0x"
+					<<std::hex<<static_cast<uint32_t>(AH);
+				throw ss.str();
+			}
 			break;
 		}
 	}


Add P_LIKELY() optimizations for string routines

--- src/pstring.c
+++ src/pstring.c
@@ -30,12 +30,12 @@
 	pchar	*ret;
 	psize	len;

-	if (str == NULL)
+	if (P_UNLIKELY (str == NULL))
 		return NULL;

 	len = strlen (str) + 1;

-	if ((ret = p_malloc (len)) == NULL)
+	if (P_UNLIKELY ((ret = p_malloc (len)) == NULL))
 		return NULL;

 	memcpy (ret, str, len);
@@ -51,7 +51,7 @@
 	pchar		*ret;
 	const pchar	*ptr;

-	if (str == NULL)
+	if (P_UNLIKELY (str == NULL))
 		return NULL;

 	ptr = str;
@@ -74,7 +74,7 @@

 	str_len = pos_end - pos_start + 2;

-	if ((ret = p_malloc0 (str_len)) == NULL)
+	if (P_UNLIKELY ((ret = p_malloc0 (str_len)) == NULL))
 		return NULL;

 	memcpy (ret, str + pos_start, str_len - 1);
@@ -86,12 +86,12 @@
 P_LIB_API pchar *
 p_strtok (pchar *str, const pchar *delim, pchar **buf)
 {
-	if (delim == NULL)
+	if (P_UNLIKELY (delim == NULL))
 		return str;

 #ifdef P_OS_WIN
 #  ifdef P_CC_MSVC
-	if (buf == NULL)
+	if (P_UNLIKELY (buf == NULL))
 		return str;
 #    if _MSC_VER < 1400
 	P_UNUSED (buf);
@@ -104,7 +104,7 @@
 	return strtok (str, delim);
 #  endif
 #else
-	if (buf == NULL)
+	if (P_UNLIKELY (buf == NULL))
 		return str;

 	return strtok_r (str, delim, buf);
@@ -114,17 +114,17 @@
 P_LIB_API double
 p_strtod (const pchar *str)
 {
-	double		sign;
-	double		value;
-	double		scale;
-	double		pow10;
-	unsigned int	expon;
-	int		frac;
-	pchar		*orig_str, *strp;
+	double	sign;
+	double	value;
+	double	scale;
+	double	pow10;
+	puint	expon;
+	pint	frac;
+	pchar	*orig_str, *strp;

 	orig_str = p_strchomp (str);

-	if (orig_str == NULL)
+	if (P_UNLIKELY (orig_str == NULL))
 		return 0.0;

 	strp = orig_str;
@@ -137,7 +137,7 @@
 		strp += 1;

 	/* Get digits before decimal point or exponent, if any */
-	for (value = 0.0; isdigit ((int) *strp); strp += 1)
+	for (value = 0.0; isdigit ((pint) *strp); strp += 1)
 		value = value * 10.0 + (*strp - '0');

 	/* Get digits after decimal point, if any */
@@ -145,7 +145,7 @@
 		pow10 = 10.0;
 		strp += 1;

-		while (isdigit ((int) *strp)) {
+		while (isdigit ((pint) *strp)) {
 			value += (*strp - '0') / pow10;
 			pow10 *= 10.0;
 			strp += 1;
@@ -168,11 +168,10 @@
 			strp += 1;

 		/* Get digits of exponent, if any */
-		for (expon = 0; isdigit ((int) *strp); strp += 1) {
+		for (expon = 0; isdigit ((pint) *strp); strp += 1)
 			expon = expon * 10 + (*strp - '0');
-		}

-		if (expon > P_STR_MAX_EXPON)
+		if (P_UNLIKELY (expon > P_STR_MAX_EXPON))
 			expon = P_STR_MAX_EXPON;

 		/* Calculate scaling factor */


redis-cli: fix big keys search when the key no longer exist.

The code freed a reply object that was never created, resulting in a
segfault every time randomkey returned a key that was deleted before we
queried it for size.

--- src/redis-cli.c
+++ src/redis-cli.c
@@ -1323,7 +1323,6 @@
         } else if (!strcmp(reply2->str,"none")) {
             freeReplyObject(reply1);
             freeReplyObject(reply2);
-            freeReplyObject(reply3);
             continue;
         } else {
             fprintf(stderr, "Unknown key type '%s' for key '%s'\n",


Add translator comments

Add translator comments

--- src/bs_size.c
+++ src/bs_size.c
@@ -38,11 +38,47 @@
 /***************
  * STATIC DATA *
  ***************/
-static char const * const b_units[BS_BUNIT_UNDEF] = {N_("B"), N_("KiB"), N_("MiB"), N_("GiB"), N_("TiB"),
-                                                     N_("PiB"), N_("EiB"), N_("ZiB"), N_("YiB")};
-
-static char const * const d_units[BS_DUNIT_UNDEF] = {N_("B"), N_("KB"), N_("MB"), N_("GB"), N_("TB"),
-                                                     N_("PB"), N_("EB"), N_("ZB"), N_("YB")};
+static char const * const b_units[BS_BUNIT_UNDEF] = {
+    /* TRANSLATORS: 'B' for bytes */
+    N_("B"),
+    /* TRANSLATORS: abbreviation for kibibyte, 2**10 bytes */
+    N_("KiB"),
+    /* TRANSLATORS: abbreviation for mebibyte, 2**20 bytes */
+    N_("MiB"),
+    /* TRANSLATORS: abbreviation for gibibyte, 2**30 bytes */
+    N_("GiB"),
+    /* TRANSLATORS: abbreviation for tebibyte, 2**40 bytes */
+    N_("TiB"),
+    /* TRANSLATORS: abbreviation for pebibyte, 2**50 bytes */
+    N_("PiB"),
+    /* TRANSLATORS: abbreviation for exbibyte, 2**60 bytes */
+    N_("EiB"),
+    /* TRANSLATORS: abbreviation for zebibyte, 2**70 bytes */
+    N_("ZiB"),
+    /* TRANSLATORS: abbreviation for yobibyte, 2**80 bytes */
+    N_("YiB")
+};
+
+static char const * const d_units[BS_DUNIT_UNDEF] = {
+    /* TRANSLATORS: 'B' for bytes */
+    N_("B"),
+    /* TRANSLATORS: abbreviation for kilobyte, 10**3 bytes */
+    N_("KB"),
+    /* TRANSLATORS: abbreviation for megabyte, 10**6 bytes */
+    N_("MB"),
+    /* TRANSLATORS: abbreviation for gigabyte, 10**9 bytes */
+    N_("GB"),
+    /* TRANSLATORS: abbreviation for terabyte, 10**12 bytes */
+    N_("TB"),
+    /* TRANSLATORS: abbreviation for petabyte, 10**15 bytes */
+    N_("PB"),
+    /* TRANSLATORS: abbreviation for exabyte, 10**18 bytes */
+    N_("EB"),
+    /* TRANSLATORS: abbreviation for zettabyte, 10**21 bytes */
+    N_("ZB"),
+    /* TRANSLATORS: abbreviation for yottabyte, 10**24 bytes */
+    N_("YB")
+};

 /****************************


renamed var

renamed var

--- src/publish.c
+++ src/publish.c
@@ -80,10 +80,10 @@
   return 1;
 }

-static int lwmqtt_serialize_publish_length(int qos, lwmqtt_string_t topicName, int payloadlen) {
+static int lwmqtt_serialize_publish_length(int qos, lwmqtt_string_t topicName, int payload_len) {
   int len = 0;

-  len += 2 + lwmqtt_strlen(topicName) + payloadlen;
+  len += 2 + lwmqtt_strlen(topicName) + payload_len;
   if (qos > 0) {
     len += 2;
   }  // packet id


redis-cli: use keepalive socket option.

redis-cli: use keepalive socket option.

This should improve things in two ways:

1) Prevent timeouts caused by the execution of long commands.
2) Improve detection of real connection errors.

This is mostly effective only on Linux because of the bogus default
keepalive settings. In Linux we have OS-specific calls to set the
keepalive interval to reasonable values.

--- src/redis-cli.c
+++ src/redis-cli.c
@@ -56,6 +56,7 @@
 #define OUTPUT_STANDARD 0
 #define OUTPUT_RAW 1
 #define OUTPUT_CSV 2
+#define REDIS_CLI_KEEPALIVE_INTERVAL 15 /* seconds */

 static redisContext *context;
 static struct config {
@@ -331,6 +332,12 @@
             context = NULL;
             return REDIS_ERR;
         }
+
+        /* Set aggressive KEEP_ALIVE socket option in the Redis context socket
+         * in order to prevent timeouts caused by the execution of long
+         * commands. At the same time this improves the detection of real
+         * errors. */
+        anetKeepAlive(NULL, context->fd, REDIS_CLI_KEEPALIVE_INTERVAL);

         /* Do AUTH and select the right DB. */
         if (cliAuth() != REDIS_OK)


Clear mousegrabber if grabber client dies

--- compositor/mousegrabber.c
+++ compositor/mousegrabber.c
@@ -35,11 +35,18 @@
 	wlr_log(WLR_DEBUG, "mousegrabber: mouse grabbed");
 }

+static void unset_mouse(struct wc_server *server) {
+	struct wc_cursor *cursor = server->cursor;
+
+	server->mouse_grab = false;
+	wc_cursor_set_compositor_cursor(cursor, NULL);
+
+	wlr_log(WLR_DEBUG, "mousegrabber: mouse released");
+}
+
 static void release_mouse(
 		struct wl_client *client, struct wl_resource *resource) {
 	struct wc_mousegrabber *mousegrabber = wl_resource_get_user_data(resource);
-	struct wc_server *server = mousegrabber->server;
-	struct wc_cursor *cursor = server->cursor;

 	if (mousegrabber->resource != NULL) {
 		assert(mousegrabber->client);
@@ -52,13 +59,10 @@
 		return;
 	}

-	server->mouse_grab = false;
-	wc_cursor_set_compositor_cursor(cursor, NULL);
+	unset_mouse(mousegrabber->server);

 	// NOTE: Calls our destroy event, which clears client resource pointers.
 	wl_resource_destroy(mousegrabber->resource);
-
-	wlr_log(WLR_DEBUG, "mousegrabber: mouse released");
 }

 static const struct zway_cooler_mousegrabber_interface mousegrabber_impl = {
@@ -70,6 +74,7 @@
 	struct wc_mousegrabber *mousegrabber = wl_resource_get_user_data(resource);

 	if (mousegrabber->resource == resource) {
+		unset_mouse(mousegrabber->server);
 		mousegrabber->resource = NULL;
 		mousegrabber->client = NULL;
 	}


Add regression test for PR15823

Add regression test for PR15823

git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@215941 91177308-0d34-0410-b5e6-96231b3b80d8

error: pathspec 'test/sanitizer_common/TestCases/Linux/clock_gettime.c' did not match any file(s) known to git

--- test/sanitizer_common/TestCases/Linux/clock_gettime.c
+++ test/sanitizer_common/TestCases/Linux/clock_gettime.c
@@ -0,0 +1,11 @@
+// RUN: %clang %s -Wl,-as-needed -o %t && %run %t
+// Regression test for PR15823
+// (http://llvm.org/bugs/show_bug.cgi?id=15823).
+#include <stdio.h>
+#include <time.h>
+
+int main() {
+  struct timespec ts;
+  clock_gettime(CLOCK_REALTIME, &ts);
+  return 0;
+}


Connecting to the server

Connecting to the server

--- src/account/pop3.c
+++ src/account/pop3.c
@@ -15,8 +15,39 @@

+#include <sys/socket.h>
 #include <stdlib.h>
+#ifdef DEBUG
+# include <stdio.h>
+#endif
+#include <string.h>
+#include <errno.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
 #include "Mailer.h"
+
+
+/* POP3 */
+/* private */
+/* types */
+typedef struct _POP3
+{
+	int fd;
+	guint source;
+
+	GIOChannel * channel;
+	char * rd_buf;
+	size_t rd_buf_cnt;
+	guint rd_source;
+	char * wr_buf;
+	size_t wr_buf_cnt;
+	guint wr_source;
+
+	AccountFolder inbox;
+	AccountFolder trash;
+	GtkTextBuffer * tbuf;
+} POP3;

 /* variables */
@@ -35,10 +66,34 @@
 	{ NULL,		NULL,			ACT_NONE,	NULL }
 };

-
-/* functions */
-
-
+static const AccountFolder _pop3_folder_inbox =
+{
+	AFT_INBOX, "Inbox", NULL, NULL
+};
+
+static const AccountFolder _pop3_folder_trash =
+{
+	AFT_TRASH, "Trash", NULL, NULL
+};
+
+
+/* prototypes */
+static int _pop3_init(AccountPlugin * plugin, GtkTreeStore * store,
+		GtkTreeIter * parent, GtkTextBuffer * buffer);
+static int _pop3_destroy(AccountPlugin * plugin);
+static GtkTextBuffer * _pop3_select(AccountPlugin * plugin,
+		AccountFolder * folder, AccountMessage * message);
+
+/* callbacks */
+static gboolean _on_idle(gpointer data);
+static gboolean _on_watch_can_read(GIOChannel * source, GIOCondition condition,
+		gpointer data);
+static gboolean _on_watch_can_write(GIOChannel * source, GIOCondition condition,
+		gpointer data);
+
+
+/* public */
+/* variables */
 AccountPlugin account_plugin =
 {
 	NULL,
@@ -46,9 +101,229 @@
 	_pop3_name,
 	NULL,
 	_pop3_config,
-	NULL,
-	NULL,
-	NULL,
+	_pop3_init,
+	_pop3_destroy,
+	_pop3_select,
 	NULL,
 	NULL
 };
+
+
+/* private */
+/* functions */
+/* pop3_init */
+static int _pop3_init(AccountPlugin * plugin, GtkTreeStore * store,
+		GtkTreeIter * parent, GtkTextBuffer * buffer)
+{
+	POP3 * pop3;
+	GdkPixbuf * pixbuf;
+	GtkTreeIter iter;
+
+	if((pop3 = malloc(sizeof(*pop3))) == NULL)
+		return -1;
+	plugin->priv = pop3;
+	pop3->fd = -1;
+	pop3->source = g_idle_add(_on_idle, plugin);
+	pop3->channel = NULL;
+	pop3->rd_buf = NULL;
+	pop3->rd_buf_cnt = 0;
+	pop3->rd_source = 0;
+	pop3->wr_buf = NULL;
+	pop3->wr_buf_cnt = 0;
+	pop3->wr_source = 0;
+	memcpy(&pop3->inbox, &_pop3_folder_inbox, sizeof(pop3->inbox));
+	memcpy(&pop3->trash, &_pop3_folder_trash, sizeof(pop3->trash));
+	pop3->tbuf = gtk_text_buffer_new(NULL);
+	/* inbox */
+	pixbuf = gtk_icon_theme_load_icon(plugin->helper->theme, "mailer-inbox",
+			16, 0, NULL);
+	gtk_tree_store_append(store, &iter, parent);
+	gtk_tree_store_set(store, &iter, MF_COL_ACCOUNT, NULL, MF_COL_FOLDER,
+			&pop3->inbox, MF_COL_ICON, pixbuf, MF_COL_NAME,
+			pop3->inbox.name, -1);
+	/* trash */
+	pixbuf = gtk_icon_theme_load_icon(plugin->helper->theme,
+			"stock_trash_full", 16, 0, NULL);
+	gtk_tree_store_append(store, &iter, parent);
+	gtk_tree_store_set(store, &iter, MF_COL_ACCOUNT, NULL, MF_COL_FOLDER,
+			&pop3->trash, MF_COL_ICON, pixbuf, MF_COL_NAME,
+			pop3->trash.name, -1);
+	return 0;
+}
+
+
+/* pop3_destroy */
+static int _pop3_destroy(AccountPlugin * plugin)
+{
+	POP3 * pop3 = plugin->priv;
+	GError * error = NULL;
+
+#ifdef DEBUG
+	fprintf(stderr, "DEBUG: %s()\n", __func__);
+#endif
+	if(pop3 == NULL) /* XXX _pop3_destroy() may be called uninitialized */
+		return 0;
+	if(pop3->rd_source != 0)
+		g_source_remove(pop3->rd_source);
+	free(pop3->rd_buf);
+	if(pop3->wr_source != 0)
+		g_source_remove(pop3->wr_source);
+	free(pop3->wr_buf);
+	if(pop3->source != 0)
+		g_source_remove(pop3->source);
+	if(pop3->channel != NULL)
+	{
+		g_io_channel_shutdown(pop3->channel, TRUE, &error);
+		g_io_channel_unref(pop3->channel);
+	}
+	if(pop3->fd >= 0)
+		close(pop3->fd);
+	free(pop3);
+	return 0;
+}
+
+
+/* pop3_select */
+static GtkTextBuffer * _pop3_select(AccountPlugin * plugin,
+		AccountFolder * folder, AccountMessage * message)
+{
+	POP3 * pop3 = plugin->priv;
+
+#ifdef DEBUG
+	fprintf(stderr, "DEBUG: %s()\n", __func__);
+#endif
+	return pop3->tbuf;
+}
+
+
+/* callbacks */
+/* on_idle */
+static gboolean _idle_connect(AccountPlugin * plugin);
+static gboolean _idle_channel(AccountPlugin * plugin);
+
+static gboolean _on_idle(gpointer data)
+{
+	gboolean ret = FALSE;
+	AccountPlugin * plugin = data;
+	POP3 * pop3 = plugin->priv;
+
+#ifdef DEBUG
+	fprintf(stderr, "DEBUG: %s()\n", __func__);
+#endif
+	if(pop3->fd < 0)
+		ret = _idle_connect(plugin);
+	else if(pop3->channel == NULL)
+		ret = _idle_channel(plugin);
+	if(ret == FALSE)
+		pop3->source = 0;
+	return ret;
+}
+
+static gboolean _idle_connect(AccountPlugin * plugin)
+{
+	POP3 * pop3 = plugin->priv;
+	char const * p;
+	struct hostent * he;
+	unsigned short port;
+	struct sockaddr_in sa;
+
+#ifdef DEBUG
+	fprintf(stderr, "DEBUG: %s()\n", __func__);
+#endif
+	/* FIXME report errors */
+	if((p = plugin->config[2].value) == NULL)
+		return FALSE;
+	if((he = gethostbyname(p)) == NULL)
+	{
+		plugin->helper->error(NULL, hstrerror(h_errno), 1);
+		return FALSE;
+	}
+	if((p = plugin->config[3].value) == NULL)
+		return FALSE;
+	port = (unsigned long)p;
+	if((pop3->fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
+	{
+		plugin->helper->error(NULL, strerror(errno), 1);
+		return FALSE;
+	}
+	sa.sin_family = AF_INET;
+	sa.sin_port = htons(port);
+	sa.sin_addr.s_addr = *((uint32_t*)he->h_addr_list[0]);
+#ifdef DEBUG
+	fprintf(stderr, "DEBUG: %s() connecting to %s:%u\n", __func__,
+			inet_ntoa(sa.sin_addr), port);
+#endif
+	if(connect(pop3->fd, (struct sockaddr *)&sa, sizeof(sa)) != 0)
+	{
+		plugin->helper->error(NULL, strerror(errno), 1);
+		close(pop3->fd);
+		pop3->fd = -1;
+		return FALSE;
+	}
+	return TRUE;
+}
+
+static gboolean _idle_channel(AccountPlugin * plugin)
+{
+	POP3 * pop3 = plugin->priv;
+	GError * error = NULL;
+
+	pop3->channel = g_io_channel_unix_new(pop3->fd);
+	g_io_channel_set_encoding(pop3->channel, NULL, &error);
+	g_io_channel_set_buffered(pop3->channel, FALSE);
+	pop3->rd_source = g_io_add_watch(pop3->channel, G_IO_IN,
+			_on_watch_can_read, plugin);
+	return TRUE;
+}
+
+
+/* on_watch_can_read */
+static gboolean _on_watch_can_read(GIOChannel * source, GIOCondition condition,
+		gpointer data)
+{
+	AccountPlugin * plugin = data;
+	POP3 * pop3 = plugin->priv;
+	char * p;
+	gsize cnt = 0;
+	GError * error = NULL;
+	GIOStatus status;
+
+	if(condition != G_IO_IN || source != pop3->channel)
+		return FALSE; /* should not happen */
+	if((p = realloc(pop3->rd_buf, pop3->rd_buf_cnt + 256)) == NULL)
+		return TRUE; /* XXX retries immediately (delay?) */
+	pop3->rd_buf = p;
+	status = g_io_channel_read_chars(source,
+			&pop3->rd_buf[pop3->rd_buf_cnt], 256, &cnt, &error);
+#ifdef DEBUG
+	fprintf(stderr, "%s", "DEBUG: POP3 SERVER: ");
+	fwrite(&pop3->rd_buf[pop3->rd_buf_cnt], sizeof(*p), cnt, stderr);
+#endif
+	pop3->rd_buf_cnt += cnt;
+	switch(status)
+	{
+		case G_IO_STATUS_NORMAL:
+			break;
+		case G_IO_STATUS_ERROR:
+			plugin->helper->error(NULL, error->message, 1);
+		case G_IO_STATUS_EOF:
+		default: /* XXX find a way to recover */
+			pop3->rd_source = 0;
+			return FALSE;
+	}
+	/* FIXME implement the rest */
+	return TRUE;
+}
+
+
+/* on_watch_can_write */
+static gboolean _on_watch_can_write(GIOChannel * source, GIOCondition condition,
+		gpointer data)
+{
+	AccountPlugin * plugin = data;
+	POP3 * pop3 = plugin->priv;
+
+	/* FIXME implement */
+	pop3->wr_source = 0;
+	return FALSE;
+}


Refactor ZSTD_dfast to Use `goto`s

Refactor ZSTD_dfast to Use `goto`s

--- lib/compress/zstd_double_fast.c
+++ lib/compress/zstd_double_fast.c
@@ -106,6 +106,7 @@
     /* Main Search Loop */
     while (ip < ilimit) {   /* < instead of <=, because repcode check at (ip+1) */
         size_t mLength;
+        U32 offset;
         size_t const h2 = ZSTD_hashPtr(ip, hBitsL, 8);
         size_t const h = ZSTD_hashPtr(ip, hBitsS, mls);
         U32 const current = (U32)(ip-base);
@@ -120,6 +121,7 @@
                                base + repIndex;
         hashLong[h2] = hashSmall[h] = current;   /* update hash tables */

+        /* check dictMatchState repcode */
         if (dictMode == ZSTD_dictMatchState
             && ((U32)((prefixLowestIndex-1) - repIndex) >= 3 /* intentional underflow */)
             && (MEM_read32(repMatch) == MEM_read32(ip+1)) ) {
@@ -127,73 +129,93 @@
             mLength = ZSTD_count_2segments(ip+1+4, repMatch+4, iend, repMatchEnd, istart) + 4;
             ip++;
             ZSTD_storeSeq(seqStore, ip-anchor, anchor, 0, mLength-MINMATCH);
-        } else if ( dictMode == ZSTD_noDict
-                 && ((offset_1 > 0) & (MEM_read32(ip+1-offset_1) == MEM_read32(ip+1)))) {
+            goto _match_stored;
+        }
+
+        /* check noDict repcode */
+        if ( dictMode == ZSTD_noDict
+          && ((offset_1 > 0) & (MEM_read32(ip+1-offset_1) == MEM_read32(ip+1)))) {
             mLength = ZSTD_count(ip+1+4, ip+1+4-offset_1, iend) + 4;
             ip++;
             ZSTD_storeSeq(seqStore, ip-anchor, anchor, 0, mLength-MINMATCH);
-        } else {
-            U32 offset;
-            if ( (matchIndexL > prefixLowestIndex) && (MEM_read64(matchLong) == MEM_read64(ip)) ) {
-                mLength = ZSTD_count(ip+8, matchLong+8, iend) + 8;
-                offset = (U32)(ip-matchLong);
-                while (((ip>anchor) & (matchLong>prefixLowest)) && (ip[-1] == matchLong[-1])) { ip--; matchLong--; mLength++; } /* catch up */
-            } else if ( (matchIndexS > prefixLowestIndex) && (MEM_read32(match) == MEM_read32(ip)) ) {
+            goto _match_stored;
+        }
+
+        /* check prefix long match */
+        if ( (matchIndexL > prefixLowestIndex) && (MEM_read64(matchLong) == MEM_read64(ip)) ) {
+            mLength = ZSTD_count(ip+8, matchLong+8, iend) + 8;
+            offset = (U32)(ip-matchLong);
+            while (((ip>anchor) & (matchLong>prefixLowest)) && (ip[-1] == matchLong[-1])) { ip--; matchLong--; mLength++; } /* catch up */
+            goto _match_found;
+        }
+
+        /* check prefix short match */
+        if ( (matchIndexS > prefixLowestIndex) && (MEM_read32(match) == MEM_read32(ip)) ) {
+            size_t const hl3 = ZSTD_hashPtr(ip+1, hBitsL, 8);
+            U32 const matchIndexL3 = hashLong[hl3];
+            const BYTE* matchL3 = base + matchIndexL3;
+            hashLong[hl3] = current + 1;
+
+            /* check prefix + 1 long match */
+            if ( (matchIndexL3 > prefixLowestIndex) && (MEM_read64(matchL3) == MEM_read64(ip+1)) ) {
+                mLength = ZSTD_count(ip+9, matchL3+8, iend) + 8;
+                ip++;
+                offset = (U32)(ip-matchL3);
+                while (((ip>anchor) & (matchL3>prefixLowest)) && (ip[-1] == matchL3[-1])) { ip--; matchL3--; mLength++; } /* catch up */
+            } else {
+                mLength = ZSTD_count(ip+4, match+4, iend) + 4;
+                offset = (U32)(ip-match);
+                while (((ip>anchor) & (match>prefixLowest)) && (ip[-1] == match[-1])) { ip--; match--; mLength++; } /* catch up */
+            }
+            goto _match_found;
+        }
+
+        /* check dictMatchState matches */
+        if (dictMode == ZSTD_dictMatchState) {
+            U32 const dictMatchIndexL = dictHashLong[h2];
+            U32 const dictMatchIndexS = dictHashSmall[h];
+            const BYTE* dictMatchL = dictBase + dictMatchIndexL;
+            const BYTE* dictMatchS = dictBase + dictMatchIndexS;
+            assert(dictMatchL < dictEnd);
+            assert(dictMatchS < dictEnd);
+
+            if (dictMatchL > dictLowest && MEM_read64(dictMatchL) == MEM_read64(ip)) {
+                mLength = ZSTD_count_2segments(ip+8, dictMatchL+8, iend, dictEnd, prefixLowest) + 8;
+                offset = (U32)(current - dictMatchIndexL - dictIndexDelta);
+                while (((ip>anchor) & (dictMatchL>dictLowest)) && (ip[-1] == dictMatchL[-1])) { ip--; dictMatchL--; mLength++; } /* catch up */
+                goto _match_found;
+            }
+
+            if (dictMatchS > dictLowest && MEM_read32(dictMatchS) == MEM_read32(ip)) {
                 size_t const hl3 = ZSTD_hashPtr(ip+1, hBitsL, 8);
-                U32 const matchIndexL3 = hashLong[hl3];
-                const BYTE* matchL3 = base + matchIndexL3;
-                hashLong[hl3] = current + 1;
-                if ( (matchIndexL3 > prefixLowestIndex) && (MEM_read64(matchL3) == MEM_read64(ip+1)) ) {
-                    mLength = ZSTD_count(ip+9, matchL3+8, iend) + 8;
+                U32 const dictMatchIndexL3 = dictHashLong[hl3];
+                const BYTE* dictMatchL3 = dictBase + dictMatchIndexL3;
+                assert(dictMatchL3 < dictEnd);
+                if (dictMatchL3 > dictLowest && MEM_read64(dictMatchL3) == MEM_read64(ip)) {
+                    mLength = ZSTD_count_2segments(ip+1+8, dictMatchL3+8, iend, dictEnd, prefixLowest) + 8;
                     ip++;
-                    offset = (U32)(ip-matchL3);
-                    while (((ip>anchor) & (matchL3>prefixLowest)) && (ip[-1] == matchL3[-1])) { ip--; matchL3--; mLength++; } /* catch up */
+                    offset = (U32)(current + 1 - dictMatchIndexL3 - dictIndexDelta);
+                    while (((ip>anchor) & (dictMatchL3>dictLowest)) && (ip[-1] == dictMatchL3[-1])) { ip--; dictMatchL3--; mLength++; } /* catch up */
                 } else {
-                    mLength = ZSTD_count(ip+4, match+4, iend) + 4;
-                    offset = (U32)(ip-match);
-                    while (((ip>anchor) & (match>prefixLowest)) && (ip[-1] == match[-1])) { ip--; match--; mLength++; } /* catch up */
+                    mLength = ZSTD_count_2segments(ip+4, dictMatchS+4, iend, dictEnd, istart) + 4;
+                    offset = (U32)(current - dictMatchIndexS - dictIndexDelta);
+                    while (((ip>anchor) & (dictMatchS>dictLowest)) && (ip[-1] == dictMatchS[-1])) { ip--; dictMatchS--; mLength++; } /* catch up */
                 }
-            } else if (dictMode == ZSTD_dictMatchState) {
-                U32 const dictMatchIndexL = dictHashLong[h2];
-                U32 const dictMatchIndexS = dictHashSmall[h];
-                const BYTE* dictMatchL = dictBase + dictMatchIndexL;
-                const BYTE* dictMatchS = dictBase + dictMatchIndexS;
-                assert(dictMatchL < dictEnd);
-                assert(dictMatchS < dictEnd);
-                if (dictMatchL > dictLowest && MEM_read64(dictMatchL) == MEM_read64(ip)) {
-                    mLength = ZSTD_count_2segments(ip+8, dictMatchL+8, iend, dictEnd, prefixLowest) + 8;
-                    offset = (U32)(current - dictMatchIndexL - dictIndexDelta);
-                    while (((ip>anchor) & (dictMatchL>dictLowest)) && (ip[-1] == dictMatchL[-1])) { ip--; dictMatchL--; mLength++; } /* catch up */
-                } else if (dictMatchS > dictLowest && MEM_read32(dictMatchS) == MEM_read32(ip)) {
-                    size_t const hl3 = ZSTD_hashPtr(ip+1, hBitsL, 8);
-                    U32 const dictMatchIndexL3 = dictHashLong[hl3];
-                    const BYTE* dictMatchL3 = dictBase + dictMatchIndexL3;
-                    assert(dictMatchL3 < dictEnd);
-                    if (dictMatchL3 > dictLowest && MEM_read64(dictMatchL3) == MEM_read64(ip+1)) {
-                        mLength = ZSTD_count_2segments(ip+1+8, dictMatchL3+8, iend, dictEnd, prefixLowest) + 8;
-                        ip++;
-                        offset = (U32)(current + 1 - dictMatchIndexL3 - dictIndexDelta);
-                        while (((ip>anchor) & (dictMatchL3>dictLowest)) && (ip[-1] == dictMatchL3[-1])) { ip--; dictMatchL3--; mLength++; } /* catch up */
-                    } else {
-                        mLength = ZSTD_count_2segments(ip+4, dictMatchS+4, iend, dictEnd, istart) + 4;
-                        offset = (U32)(current - dictMatchIndexS - dictIndexDelta);
-                        while (((ip>anchor) & (dictMatchS>dictLowest)) && (ip[-1] == dictMatchS[-1])) { ip--; dictMatchS--; mLength++; } /* catch up */
-                    }
-                } else {
-                    ip += ((ip-anchor) >> kSearchStrength) + 1;
-                    continue;
-                }
-            } else {
-                ip += ((ip-anchor) >> kSearchStrength) + 1;
-                continue;
+
+                goto _match_found;
             }
-
-            offset_2 = offset_1;
-            offset_1 = offset;
-
-            ZSTD_storeSeq(seqStore, ip-anchor, anchor, offset + ZSTD_REP_MOVE, mLength-MINMATCH);
-        }
-
+        }
+
+        ip += ((ip-anchor) >> kSearchStrength) + 1;
+        continue;
+
+_match_found:
+        offset_2 = offset_1;
+        offset_1 = offset;
+
+        ZSTD_storeSeq(seqStore, ip-anchor, anchor, offset + ZSTD_REP_MOVE, mLength-MINMATCH);
+
+_match_stored:
         /* match found */
         ip += mLength;
         anchor = ip;


udpate comments

udpate comments

--- src/reactor.h
+++ src/reactor.h
@@ -22,7 +22,7 @@
 // The Reactor will have 3 resource buffers (all with automatically computed
 // capacities based on above params):
 //
-// * fresh: capacity = n_assem_fresh * assem_size
+// * fresh: capacity = n_assem_fresh * assem_size + eps
 //
 // * core: capacity = n_assem_core * assem_size
 //
@@ -43,32 +43,18 @@
 // enough material can be acquired to complete the full assembly.  In this
 // mode, partial assemblies may not be inserted into the core.  When in this
 // mode, resources will never be split/combined by the reactor post assembly
-// discretization.
-// Under either of the following conditions, a reactor will operate in
-// discrete assembly mode:
-//
-// * n_assem_core == n_batches:  pop one assembly per cycle
-//
-// * n_assem_core > 1:  pop floor(n_assem_core / n_batches) assemblies per cycle
-//
-// If neither of those conditions are met (i.e. n_assem_core == 1 && n_assem_core !=
-// n_batches), then the reactor will operate in continuous assembly mode.  In
-// this mode it discharges 1 / n_batches fraction of the single assembly from
-// the core at the end of each cycle, and the same quantity will be
-// extracted/split from the (not assembly discretized) fresh fuel buffer
-// (or requested on DRE if no fresh) and inserted into the core.  Material can
-// be requested+accepted in non-assembly sized quanta.
-//
-// Time to make it code generatable? - Yes  Bring into compliance? - Yes.
-// The BatchReactor currently has no state variables. A UINT type might be
-// useful here.  We should scavenge the batch reactor for pieces as we
-// reimplement a new code-generated version.
+// discretization.  Number of assemblies discharged per cycle is computed:
+//
+//     floor(n_assem_core / n_batches)
+//
+// If that number is zero or results in a significantly rounded batch size,
+// the reactor will throw an exception or print a warning respectively.
 //
 // Meta-data associated with resource objects in inventory (e.g. the in-commod
 // on which they were received) should be associated with resources based on
-// obj_id.  This is necessary for handling the case where in continuous
-// assembly mode where resources are potentially combined/split inside
-// buffers during extraction - and also when decay could change Resource::id.
+// obj_id.  This is necessary for maintaining continuity in the face of
+// potential decay calcs and other things that might change the regular
+// Resource::id.

 class Reactor : public cyclus::Facility {
  public:


qsolver function

qsolver function

--- src/qsolver.h
+++ src/qsolver.h
@@ -1,2 +1 @@
-
 int qsolver(double, double, double, double *, double *);


ratchet root library stripped down

ratchet root library stripped down

error: pathspec 'src/ratchet.c' did not match any file(s) known to git

--- src/ratchet.c
+++ src/ratchet.c
@@ -0,0 +1,92 @@
+/* Copyright (c) 2010 Ian C. Good
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#define _GNU_SOURCE
+#include "config.h"
+
+#include <lua.h>
+#include <lauxlib.h>
+#include <lualib.h>
+
+#include <event.h>
+#include <netdb.h>
+#include <string.h>
+
+#include "ratchet.h"
+#include "misc.h"
+
+#define get_event_base(L, index) (*(struct event_base **) luaL_checkudata (L, index, "ratchet_meta"))
+#define get_thread(L, index, s) luaL_checktype (L, index, LUA_TTHREAD); lua_State *s = lua_tothread (L, index)
+
+const char *ratchet_version (void);
+
+/* ---- Public Functions ---------------------------------------------------- */
+
+/* {{{ luaopen_ratchet() */
+int luaopen_ratchet (lua_State *L)
+{
+	static const luaL_Reg funcs[] = {
+		{NULL}
+	};
+
+	luaL_newlib (L, funcs);
+	lua_pushvalue (L, -1);
+	lua_setglobal (L, "ratchet");
+
+	luaL_requiref (L, "ratchet.kernel", luaopen_ratchet_kernel, 0);
+	lua_setfield (L, -2, "kernel");
+
+#if HAVE_SOCKET
+	luaL_requiref (L, "ratchet.socket", luaopen_ratchet_socket, 0);
+	lua_setfield (L, -2, "socket");
+#endif
+#if HAVE_OPENSSL
+	luaL_requiref (L, "ratchet.ssl", luaopen_ratchet_ssl, 0);
+	lua_setfield (L, -2, "ssl");
+#endif
+#if HAVE_ZMQ
+	luaL_requiref (L, "ratchet.zmqsocket", luaopen_ratchet_zmqsocket, 0);
+	lua_setfield (L, -2, "zmqsocket");
+#endif
+#if HAVE_DNS
+	luaL_requiref (L, "ratchet.dns", luaopen_ratchet_dns, 0);
+	lua_setfield (L, -2, "dns");
+#endif
+#if HAVE_TIMERFD
+	luaL_requiref (L, "ratchet.timerfd", luaopen_ratchet_timerfd, 0);
+	lua_setfield (L, -2, "timerfd");
+#endif
+
+	lua_pushstring (L, PACKAGE_VERSION);
+	lua_setfield (L, -2, "version");
+
+	return 1;
+}
+/* }}} */
+
+/* {{{ ratchet_version() */
+const char *ratchet_version (void)
+{
+	return PACKAGE_VERSION;
+}
+/* }}} */
+
+// vim:foldmethod=marker:ai:ts=4:sw=4:


layers: Use safe_VkSwapchainCreateInfoKHR in CV

Signed-off-by: Chris Forbes <c3279c50043e18e9442c1ae071cafa0e7a4ca967@google.com>

--- layers/core_validation_types.h
+++ layers/core_validation_types.h
@@ -255,17 +255,10 @@

 class SWAPCHAIN_NODE {
   public:
-    VkSwapchainCreateInfoKHR createInfo;
-    uint32_t *pQueueFamilyIndices;
+    safe_VkSwapchainCreateInfoKHR createInfo;
     std::vector<VkImage> images;
-    SWAPCHAIN_NODE(const VkSwapchainCreateInfoKHR *pCreateInfo) : createInfo(*pCreateInfo), pQueueFamilyIndices(NULL) {
-        if (pCreateInfo->queueFamilyIndexCount && pCreateInfo->imageSharingMode == VK_SHARING_MODE_CONCURRENT) {
-            pQueueFamilyIndices = new uint32_t[pCreateInfo->queueFamilyIndexCount];
-            memcpy(pQueueFamilyIndices, pCreateInfo->pQueueFamilyIndices, pCreateInfo->queueFamilyIndexCount * sizeof(uint32_t));
-            createInfo.pQueueFamilyIndices = pQueueFamilyIndices;
-        }
-    }
-    ~SWAPCHAIN_NODE() { delete[] pQueueFamilyIndices; }
+    SWAPCHAIN_NODE(const VkSwapchainCreateInfoKHR *pCreateInfo)
+        : createInfo(pCreateInfo) {}
 };

 enum DRAW_TYPE {


Update io_oper.c

Update io_oper.c

--- bin/hxestorage/io_oper.c
+++ bin/hxestorage/io_oper.c
@@ -225,12 +225,12 @@
                     return(-1);
                 }
                 if(size <=  chunk_size) {
-                    sprintf(msg, "Cannot allocated requested size= %#llx, depricating to %#llx \n", chunk_size, size);
+                    sprintf(msg, "Cannot allocate requested size= %#llx, reducing to %#llx \n", chunk_size, size);
                     user_msg(htx_ds, 0, tctx->io_err_flag, INFO, msg);
                     chunk_size = size;
                     return(0);
                 } else {
-                    sprintf(msg, "Failed to allocated request size for VLUN, cblk_set_size failed wtih ENOMEM, device = %s \n", capi_device );
+                    sprintf(msg, "Failed to allocate request size for VLUN, cblk_set_size failed with ENOMEM, device = %s \n", capi_device );
                     user_msg(htx_ds, ENOMEM, tctx->io_err_flag, HARD, msg);
                     return(-1);
                 }
@@ -2309,7 +2309,7 @@
 #endif

 /*******************************************************************/
-/****   Execute a system command from a psuedo command line     ****/
+/****   Execute a system command from a pseudo command line     ****/
 /*******************************************************************/
 int run_cmd(struct htx_data *htx_ds, char *cmd_line)
 {


git-svn-id: svn+ssh://astrometry.net/svn/trunk/src/astrometry@8298 03a3cea6-2c03-0410-ac9b-9271b1c66c29

--- blind/backend.c
+++ blind/backend.c
@@ -211,6 +211,8 @@

         for (j=-1; j<sl_size(backend->index_paths); j++) {
             char* path;
+            bool ok;
+            char* err;
             if (j == -1)
                 // try as an absolute or relative filename.
                 path = strdup(ind);
@@ -218,7 +220,14 @@
                 asprintf(&path, "%s/%s", sl_get(backend->index_paths, j), ind);

             logverb("Trying path %s...\n", path);
-            if (index_is_file_index(path)) {
+            errors_start_logging_to_string();
+            ok = index_is_file_index(path);
+            err = errors_stop_logging_to_string(": ");
+            if (!ok) {
+                logverb("File is not an index: %s\n", err);
+            }
+            free(err);
+            if (ok) {
                 if (add_index(backend, path))
                     logmsg("Failed to add index \"%s\".\n", path);
                 else {


InvalidInputException

InvalidInputException

error: pathspec 'rooset-domain/exceptions/InvalidInputException.h' did not match any file(s) known to git

--- rooset-domain/exceptions/InvalidInputException.h
+++ rooset-domain/exceptions/InvalidInputException.h
@@ -0,0 +1,17 @@
+#pragma once
+#include "ProjectException.h"
+
+namespace rooset {
+  class InvalidInputException : public ProjectException
+  {
+  private:
+    const char* msg;
+  public:
+    InvalidInputException(char* msg) : ProjectException(msg) {};
+
+    ExceptionCodes getExceptionCode() const override
+    {
+      return ExceptionCodes::INVALID_INPUT;
+    }
+  };
+}


add net_route_list Python binding

add net_route_list Python binding

--- bindings/python/_sigar.c
+++ bindings/python/_sigar.c
@@ -223,6 +223,29 @@
     return RETVAL;
 }

+static PyObject *pysigar_net_route_list(PyObject *self, PyObject *args)
+{
+    int status;
+    sigar_t *sigar = PySIGAR;
+    sigar_net_route_list_t net_routelist;
+    PyObject *RETVAL;
+
+    status = sigar_net_route_list_get(sigar, &net_routelist);
+    if (status != SIGAR_OK) {
+        PySigar_Croak();
+        return NULL;
+    }
+
+    RETVAL = pysigar_new_list((char *)&net_routelist.data[0],
+                              net_routelist.number,
+                              sizeof(*net_routelist.data),
+                              &pysigar_PySigarNetRouteType);
+
+    sigar_net_route_list_destroy(sigar, &net_routelist);
+
+    return RETVAL;
+}
+
 static PyObject *pysigar_arp_list(PyObject *self, PyObject *args)
 {
     int status;
@@ -347,6 +370,7 @@
 static PyMethodDef pysigar_methods[] = {
     { "close", pysigar_close, METH_NOARGS, NULL },
     { "net_interface_list", pysigar_net_interface_list, METH_NOARGS, NULL },
+    { "net_route_list", pysigar_net_route_list, METH_NOARGS, NULL },
     { "file_system_list", pysigar_file_system_list, METH_NOARGS, NULL },
     { "arp_list", pysigar_arp_list, METH_NOARGS, NULL },
     { "loadavg", pysigar_loadavg, METH_NOARGS, NULL },