arc/irq: Prepare idu_cascade_isr for irq argument removal

The irq argument of most interrupt flow handlers is unused or merily
used instead of a local variable. The handlers which need the irq
argument can retrieve the irq number from the irq descriptor.

Search and update was done with coccinelle and the invaluable help of
Julia Lawall.

Signed-off-by: Thomas Gleixner <00e4cf8f46a57000a44449bf9dd8cbbcc209fd2a@linutronix.de>
Cc: Julia Lawall <3d4a3affaf9163789962e9770780389962bda29d@lip6.fr>
Cc: Vineet Gupta <af669d95a4c0de051445d4cafdbb2c5c4a2838be@synopsys.com>

--- arch/arc/kernel/mcip.c
+++ arch/arc/kernel/mcip.c
@@ -252,9 +252,10 @@

 static int idu_first_irq;

-static void idu_cascade_isr(unsigned int core_irq, struct irq_desc *desc)
+static void idu_cascade_isr(unsigned int __core_irq, struct irq_desc *desc)
 {
 	struct irq_domain *domain = irq_desc_get_handler_data(desc);
+	unsigned int core_irq = irq_desc_get_irq(desc);
 	unsigned int idu_irq;

 	idu_irq = core_irq - idu_first_irq;


Since the ps/2 input ports show up as two different devices, with the same irq, but hppa has no generic shared interrupt code, we need to make sure that gsckbc devices using the same irq know each other, and will pass the interrupt notification to each other. This allow a mouse and a keyboard to work together...

--- arch/hppa/gsc/gsckbc.c
+++ arch/hppa/gsc/gsckbc.c
@@ -1,4 +1,4 @@
-/*	$OpenBSD: gsckbc.c,v 1.2 2003/02/15 23:42:45 miod Exp $	*/
+/*	$OpenBSD: gsckbc.c,v 1.3 2003/02/17 23:06:31 miod Exp $	*/
 /*
  * Copyright (c) 2003, Miodrag Vallat.
  * All rights reserved.
@@ -99,6 +99,8 @@
 	int sc_irq;
 	void *sc_ih;
 	int sc_type;
+
+	struct device *sc_sibling;
 };

 struct cfattach gsckbc_ca = {
@@ -156,6 +158,7 @@
 void pckbc_cleanup(void *);
 int pckbc_cmdresponse(struct pckbc_internal *, pckbc_slot_t, u_char);
 void pckbc_start(struct pckbc_internal *, pckbc_slot_t);
+int gsckbcintr(struct gsckbc_softc *);

 const char *pckbc_slot_names[] = { "kbd", "mouse" };

@@ -360,9 +363,10 @@
 	struct gsckbc_softc *gsc = (void *)self;
 	struct pckbc_softc *sc = &gsc->sc_pckbc;
 	struct pckbc_internal *t;
+	struct device *tdev;
 	bus_space_tag_t iot;
 	bus_space_handle_t ioh;
-	int ident;
+	int ident, dev;

 	iot = ga->ga_ca.ca_iot;
 	gsc->sc_irq = ga->ga_ca.ca_irq;
@@ -394,6 +398,35 @@
 	t->t_sc = sc;
 	timeout_set(&t->t_cleanup, pckbc_cleanup, t);
 	sc->id = t;
+
+	/*
+	 * Several gsckbc attachments might share the same interrupt.
+	 * Try to find existing gsckbc devices, and associate them
+	 * together. We do not expect more than two gsckbc devices to
+	 * share an interrupt.
+	 */
+	for (dev = 0; dev < gsckbc_cd.cd_ndevs; dev++) {
+		tdev = gsckbc_cd.cd_devs[dev];
+		if (tdev != NULL && tdev != self &&
+		    tdev->dv_parent == parent &&
+		    strcmp(tdev->dv_cfdata->cf_driver->cd_name,
+		      gsckbc_cd.cd_name) == 0) {
+			struct gsckbc_softc *alter = (void *)tdev;
+			if (alter->sc_irq == gsc->sc_irq) {
+#ifdef PCKBCDEBUG
+				if (alter->sc_sibling != NULL) {
+					printf(": more than two ps/2 ports"
+					    " sharing the same interrupt???\n");
+					bus_space_unmap(iot, ioh, KBMAPSIZE);
+					return;
+				}
+#endif
+				gsc->sc_sibling = (void *)alter;
+				alter->sc_sibling = self;
+				printf(" (shared with %s)", tdev->dv_xname);
+			}
+		}
+	}

 	printf("\n");

@@ -975,11 +1008,9 @@
 }

 int
-pckbcintr(vsc)
-	void *vsc;
-{
-	struct pckbc_softc *sc = (struct pckbc_softc *)vsc;
-	struct gsckbc_softc *gsc = (void *)sc;
+gsckbcintr(struct gsckbc_softc *gsc)
+{
+	struct pckbc_softc *sc = (struct pckbc_softc *)gsc;
 	struct pckbc_internal *t = sc->id;
 	pckbc_slot_t slot;
 	struct pckbc_slotdata *q;
@@ -1020,3 +1051,22 @@

 	return (served);
 }
+
+int
+pckbcintr(void *vsc)
+{
+	struct gsckbc_softc *gsc = vsc;
+	int claimed;
+
+	claimed = gsckbcintr(gsc);
+
+	/*
+	 * We also need to handle interrupts for the associated slot device,
+	 * if any
+	 */
+	gsc = (struct gsckbc_softc *)gsc->sc_sibling;
+	if (gsc != NULL)
+		claimed |= gsckbcintr(gsc);
+
+	return (claimed);
+}


libpcp/pmns.c - resource_leak
Original Coverity cases #153, #156, #165, #166, #173, #178, #233,
 #234 and #242.
http://people.redhat.com/mgoodwin/pcp-cov/1/153pmns.c.html#error
http://people.redhat.com/mgoodwin/pcp-cov/1/156pmns.c.html#error
http://people.redhat.com/mgoodwin/pcp-cov/1/165pmns.c.html#error
http://people.redhat.com/mgoodwin/pcp-cov/1/166pmns.c.html#error
http://people.redhat.com/mgoodwin/pcp-cov/1/173pmns.c.html#error
http://people.redhat.com/mgoodwin/pcp-cov/1/178pmns.c.html#error
http://people.redhat.com/mgoodwin/pcp-cov/1/233pmns.c.html#error
http://people.redhat.com/mgoodwin/pcp-cov/1/234pmns.c.html#error
http://people.redhat.com/mgoodwin/pcp-cov/1/242pmns.c.html#error

On several error branches, add calls to free() to release storage
that has been allocated but that will not be used as a result of
the error condition ... all very low probability of being seen
and low impact.

--- src/libpcp/src/pmns.c
+++ src/libpcp/src/pmns.c
@@ -70,7 +70,7 @@
 static __pmnsTree *curr_pmns;

 /* The main_pmns points to the loaded PMNS (not from archive). */
-static __pmnsTree *main_pmns;
+static __pmnsTree *main_pmns = NULL;

 /* == 1 if PMNS loaded and __pmExportPMNS has been called */
@@ -572,6 +572,7 @@
 		    snprintf(linebuf, sizeof(linebuf), "Cannot find definition for non-terminal node \"%s\" in name space",
 		        path);
 		    err(linebuf);
+		    free(path);
 		    return PM_ERR_PMNS;
 		}
 		np->first = xp->first;
@@ -794,6 +795,7 @@
     np->parent = np->first = np->hash = np->next = NULL;
     np->name = strdup("root");
     if (np->name == NULL) {
+	free(t);
 	free(np);
 	return -oserror();
     }
@@ -877,8 +879,10 @@
 		return -oserror();

 	    /* fixup name */
-	    if ((np->name = (char *)malloc(nch+1)) == NULL)
+	    if ((np->name = (char *)malloc(nch+1)) == NULL) {
+		free(np);
 		return -oserror();
+	    }
 	    strncpy(np->name, name_p, nch);
 	    np->name[nch] = '\0';

@@ -985,9 +989,9 @@
     __int32_t	chksum;
     long	endsum;
     __psint_t	ord;
-    __pmnsNode	*root;
-    __pmnsNode	**htab;
-    char	*symbol;
+    __pmnsNode	*root = NULL;
+    __pmnsNode	**htab = NULL;
+    char	*symbol = NULL;

     for (try = 0; try < 2; try++) {
 	if (try == 0) {
@@ -1195,6 +1199,16 @@
 bad:
 	__pmNotifyErr(LOG_WARNING, "pmLoadNameSpace: bad binary file, \"%s\"", linebuf);
 	fclose(fbin);
+	if (symbol != NULL)
+	    free(symbol);
+	if (main_pmns != NULL) {
+	    free(main_pmns);
+	    main_pmns = NULL;
+	}
+	if (htab != NULL)
+	    free(htab);
+	if (root != NULL)
+	    free(root);
 	return 0;
     }

@@ -1303,8 +1317,10 @@
 	    if ((np = (__pmnsNode *)malloc(sizeof(*np))) == NULL)
 		return -oserror();
 	    numpmid++;
-	    if ((np->name = (char *)malloc(strlen(tokbuf)+1)) == NULL)
+	    if ((np->name = (char *)malloc(strlen(tokbuf)+1)) == NULL) {
+		free(np);
 		return -oserror();
+	    }
 	    strcpy(np->name, tokbuf);
 	    np->first = np->hash = np->next = np->parent = NULL;
 	    np->pmid = PM_ID_NULL;
@@ -2243,6 +2259,7 @@
 	if (statuslist != NULL) {
 	    if ((status = (int *)malloc(num*sizeof(int))) == NULL) {
 		num = -oserror();
+		free(result);
 		goto report;
 	    }
 	}


libpcp/util.c - negative_returns
Original Coverity case #109.
http://people.redhat.com/mgoodwin/pcp-cov/1/109util.c.html#error

Check dup() fails case.

--- src/libpcp/src/util.c
+++ src/libpcp/src/util.c
@@ -183,45 +183,43 @@
      */

     fflush(oldstream);
+    *status = 1;		/* set to zero if all this works ... */
     oldfd = fileno(oldstream);
-    dupoldfd = dup(oldfd);
-
-    /*
-     * try to remove the file first ... don't bother if this fails,
-     * but if it succeeds, we at least get a chance to define the
-     * owner and mode, rather than inheriting this from an existing
-     * writeable file ... really only a problem when called as with
-     * uid == 0, e.g. from pmcd(1).
-     */
-    unlink(logname);
-
-    oldstream = freopen(logname, "w", oldstream);
-    if (oldstream == NULL) {
-	int	save_error = oserror();	/* need for error message */
-
-	close(oldfd);
-	if (dup(dupoldfd) != oldfd)
-	    /* fd juggling failed! */
-	    oldstream = NULL;
-	else
-	    /* oldfd now re-instated as at entry */
-	    oldstream = fdopen(oldfd, "w");
+    if ((dupoldfd = dup(oldfd)) >= 0) {
+	/*
+	 * try to remove the file first ... don't bother if this fails,
+	 * but if it succeeds, we at least get a chance to define the
+	 * owner and mode, rather than inheriting this from an existing
+	 * writeable file ... really only a problem when called as with
+	 * uid == 0, e.g. from pmcd(1).
+	 */
+	unlink(logname);
+
+	oldstream = freopen(logname, "w", oldstream);
 	if (oldstream == NULL) {
-	    /* serious trouble ... choose least obnoxious alternative */
-	    if (dupoldstream == stderr)
-		oldstream = fdopen(fileno(stdout), "w");
+	    int	save_error = oserror();	/* need for error message */
+
+	    close(oldfd);
+	    if (dup(dupoldfd) != oldfd)
+		/* fd juggling failed! */
+		oldstream = NULL;
 	    else
-		oldstream = fdopen(fileno(stderr), "w");
-	}
-	*status = 0;
-	pmprintf("%s: cannot open log \"%s\" for writing : %s\n",
-		progname, logname, strerror(save_error));
-	pmflush();
-    }
-    else {
-	*status = 1;
-    }
-    close(dupoldfd);
+		/* oldfd now re-instated as at entry */
+		oldstream = fdopen(oldfd, "w");
+	    if (oldstream == NULL) {
+		/* serious trouble ... choose least obnoxious alternative */
+		if (dupoldstream == stderr)
+		    oldstream = fdopen(fileno(stdout), "w");
+		else
+		    oldstream = fdopen(fileno(stderr), "w");
+	    }
+	    *status = 0;
+	    pmprintf("%s: cannot open log \"%s\" for writing : %s\n",
+		    progname, logname, strerror(save_error));
+	    pmflush();
+	}
+	close(dupoldfd);
+    }
     return oldstream;
 }


Registers for the i386.

Registers for the i386.

--- arch/i386/i386_types.h
+++ arch/i386/i386_types.h
@@ -4,41 +4,52 @@
  * the register file
  */

-/* XXX: high and low byte endianess! */
-#define DEFINE_SPLIT_REG(_reg, _high, _low) \
+#define DEFINE_REG_32_SPLIT(_extended, _reg, _high, _low) \
 	union {					\
-		uint16_t		_reg;	\
-		struct {			\
-			uint8_t		_high;	\
-			uint8_t		_low;	\
+		uint32_t		_extended; \
+		struct {					\
+			uint16_t		_reg;	\
+			struct {			\
+				uint8_t		_high;	\
+				uint8_t		_low;	\
+			};				\
 		};				\
 	};

-#define DEFINE_REG(_reg)			\
+#define DEFINE_REG_32(_extended, _reg)			\
+	union {				\
+		uint32_t		_extended; \
+		uint16_t		_reg;	\
+	};
+
+#define DEFINE_REG_16(_reg)			\
 	struct {				\
-		uint16_t		_reg;	\
-	}
+		uint16_t		_reg; \
+	};
+

 PACKED(struct reg_i386_s {
 	/*General registers */
-	DEFINE_SPLIT_REG(ax, ah, al);
-	DEFINE_SPLIT_REG(bx, bh, bl);
-	DEFINE_SPLIT_REG(cx, ch, cl);
-	DEFINE_SPLIT_REG(dx, dh, dl);
+	DEFINE_REG_32_SPLIT(eax, ax, ah, al);
+	DEFINE_REG_32_SPLIT(ebx, bx, bh, bl);
+	DEFINE_REG_32_SPLIT(ecx, cx, ch, cl);
+	DEFINE_REG_32_SPLIT(edx, dx, dh, dl);
 	/* Index registers */
-	DEFINE_REG(si);
-	DEFINE_REG(di);
+	DEFINE_REG_32(esi, si);
+	DEFINE_REG_32(edi, di);
 	/* Pointer registers */
-	DEFINE_REG(bp);
-	DEFINE_REG(sp);
+	DEFINE_REG_32(ebp, bp);
+	DEFINE_REG_32(esp, sp);
 	/* Special purpose registers */
-	DEFINE_REG(ip);
+	DEFINE_REG_32(eip, ip);
 	/* Flags register */
-	DEFINE_REG(flags);
+	DEFINE_REG_32(eflags, flags);
 	/* Segment registers */
-	DEFINE_REG(cs);
-	DEFINE_REG(ds);
-	DEFINE_REG(ss);
-	DEFINE_REG(es);
+	DEFINE_REG_16(cs);
+	DEFINE_REG_16(ds);
+	DEFINE_REG_16(ss);
+	DEFINE_REG_16(es);
+	DEFINE_REG_16(fs);
+	DEFINE_REG_16(gs);
 });
 typedef struct reg_i386_s reg_i386_t;


[PATCH] i386: Remove unneeded externs in nmi.c

All were already in some header
Signed-off-by: Andi Kleen <0474aee45985f5ae829f53849df476200e876990@suse.de>

--- arch/i386/kernel/nmi.c
+++ arch/i386/kernel/nmi.c
@@ -74,9 +74,6 @@

 /* local prototypes */
 static int unknown_nmi_panic_callback(struct pt_regs *regs, int cpu);
-
-extern void show_registers(struct pt_regs *regs);
-extern int unknown_nmi_panic;

 /* converts an msr to an appropriate reservation bit */
 static inline unsigned int nmi_perfctr_msr_to_bit(unsigned int msr)


m68knommu: use generic section names in mm/init code

We should be including and using sections.h to get at the extern
definitions of the linker sections in the m68knommu mm init code.
Not defining them locally.

Signed-off-by: Greg Ungerer <ed22c22dbde360207569092e60b4298397efb8da@uclinux.org>

--- arch/m68k/mm/init_no.c
+++ arch/m68k/mm/init_no.c
@@ -32,6 +32,7 @@
 #include <linux/gfp.h>

 #include <asm/setup.h>
+#include <asm/sections.h>
 #include <asm/segment.h>
 #include <asm/page.h>
 #include <asm/pgtable.h>
@@ -78,7 +79,6 @@
 {
 	int codek = 0, datak = 0, initk = 0;
 	unsigned long tmp;
-	extern char _etext, _stext, _sdata, _ebss, __init_begin, __init_end;
 	extern unsigned int _ramend, _rambase;
 	unsigned long len = _ramend - _rambase;
 	unsigned long start_mem = memory_start; /* DAVIDM - these must start at end of kernel */
@@ -95,9 +95,9 @@
 	/* this will put all memory onto the freelists */
 	totalram_pages = free_all_bootmem();

-	codek = (&_etext - &_stext) >> 10;
-	datak = (&_ebss - &_sdata) >> 10;
-	initk = (&__init_begin - &__init_end) >> 10;
+	codek = (_etext - _stext) >> 10;
+	datak = (_ebss - _sdata) >> 10;
+	initk = (__init_begin - __init_end) >> 10;

 	tmp = nr_free_pages() << PAGE_SHIFT;
 	printk(KERN_INFO "Memory available: %luk/%luk RAM, (%dk kernel code, %dk data)\n",
@@ -129,22 +129,21 @@
 {
 #ifdef CONFIG_RAMKERNEL
 	unsigned long addr;
-	extern char __init_begin, __init_end;
 	/*
 	 * The following code should be cool even if these sections
 	 * are not page aligned.
 	 */
-	addr = PAGE_ALIGN((unsigned long)(&__init_begin));
+	addr = PAGE_ALIGN((unsigned long) __init_begin);
 	/* next to check that the page we free is not a partial page */
-	for (; addr + PAGE_SIZE < (unsigned long)(&__init_end); addr +=PAGE_SIZE) {
+	for (; addr + PAGE_SIZE < ((unsigned long) __init_end); addr += PAGE_SIZE) {
 		ClearPageReserved(virt_to_page(addr));
 		init_page_count(virt_to_page(addr));
 		free_page(addr);
 		totalram_pages++;
 	}
 	pr_notice("Freeing unused kernel memory: %luk freed (0x%x - 0x%x)\n",
-			(addr - PAGE_ALIGN((long) &__init_begin)) >> 10,
-			(int)(PAGE_ALIGN((unsigned long)(&__init_begin))),
+			(addr - PAGE_ALIGN((unsigned long) __init_begin)) >> 10,
+			(int)(PAGE_ALIGN((unsigned long) __init_begin)),
 			(int)(addr - PAGE_SIZE));
 #endif
 }


Unbreak after recent shutdown-hook removal.

--- arch/macppc/dev/mesh.c
+++ arch/macppc/dev/mesh.c
@@ -1,4 +1,4 @@
-/*	$OpenBSD: mesh.c,v 1.30 2013/05/30 16:15:01 deraadt Exp $	*/
+/*	$OpenBSD: mesh.c,v 1.31 2013/05/31 14:30:51 mpi Exp $	*/
 /*	$NetBSD: mesh.c,v 1.1 1999/02/19 13:06:03 tsubai Exp $	*/

 /*-
@@ -383,7 +383,7 @@
 	struct mesh_softc *sc = (struct mesh_softc *)self;
 	int ret = 0;

-	reg = config_activate_children(self, act);
+	ret = config_activate_children(self, act);

 	switch (act) {
 	case DVACT_POWERDOWN:


fix comment typo

fix comment typo

--- src/schema_matcher.h
+++ src/schema_matcher.h
@@ -451,7 +451,7 @@
 	}

 	void match_keys(Statements &alter_statements, const Table &from_table, Table &to_table) {
-		// if the columns list doesn't match up yet, then comparing the keys make attempt to access invalid indices in the columns list
+		// if the columns list doesn't match up yet, then comparing the keys may attempt to access invalid indices in the columns list
 		if (from_table.columns != to_table.columns) return;

 		Keys::const_iterator from_key = from_table.keys.begin();


Cleanup some KNF nits, if we can't grab a SCB dont return at splbio. ok sometime ago dlg@

--- arch/macppc/dev/mesh.c
+++ arch/macppc/dev/mesh.c
@@ -1,4 +1,4 @@
-/*	$OpenBSD: mesh.c,v 1.11 2006/09/26 00:00:38 gwk Exp $	*/
+/*	$OpenBSD: mesh.c,v 1.12 2006/11/26 22:31:12 gwk Exp $	*/
 /*	$NetBSD: mesh.c,v 1.1 1999/02/19 13:06:03 tsubai Exp $	*/

 /*-
@@ -110,7 +110,6 @@

 	int sc_flags;
 	int sc_cfflags;			/* copy of config flags */
-	int sc_meshid;			/* MESH version */
 	int sc_minsync;			/* minimum sync period */
 	int sc_irq;
 	int sc_freq;			/* SCSI bus frequency in MHz */
@@ -231,7 +230,6 @@
 	sc->sc_dmareg = mapiodev(reg[2], reg[3]);

 	sc->sc_cfflags = sc->sc_dev.dv_cfdata->cf_flags;
-	sc->sc_meshid = mesh_read_reg(sc, MESH_MESH_ID) & 0x1f;

 	if (OF_getprop(ca->ca_node, "clock-frequency", &sc->sc_freq, 4) != 4) {
 		printf(": cannot get clock-frequency\n");
@@ -263,7 +261,7 @@
 	mesh_bus_reset(sc);

 	printf(" irq %d: %dMHz, SCSI ID %d\n",
-		sc->sc_irq, sc->sc_freq, sc->sc_id);
+	    sc->sc_irq, sc->sc_freq, sc->sc_id);

 	sc->sc_link.adapter_softc = sc;
 	sc->sc_link.adapter_target = sc->sc_id;
@@ -274,7 +272,7 @@
 	config_found(&sc->sc_dev, &sc->sc_link, scsiprint);

 	mac_intr_establish(parent, sc->sc_irq, IST_LEVEL, IPL_BIO, mesh_intr,
-	     sc, "mesh");
+	    sc, "mesh");

 	/* Reset SCSI bus when halt. */
 	shutdownhook_establish(mesh_shutdownhook, sc);
@@ -373,17 +371,17 @@
 					char *cp;

 					cp = (char *)scb->daddr + scb->dlen
-						- fifocnt;
+					    - fifocnt;
 					DPRINTF("fifocnt = %d, resid = %d\n",
-						fifocnt, scb->resid);
+					    fifocnt, scb->resid);
 					while (fifocnt > 0) {
 						*cp++ = mesh_read_reg(sc,
-								MESH_FIFO);
+						    MESH_FIFO);
 						fifocnt--;
 					}
 				} else {
 					mesh_set_reg(sc, MESH_SEQUENCE,
-							MESH_CMD_FLUSH_FIFO);
+					    MESH_CMD_FLUSH_FIFO);
 				}
 			} else {
 				/* Clear all interrupts */
@@ -394,7 +392,7 @@

 	if (intr & MESH_INTR_ERROR) {
 		printf("%s: error %02x %02x\n",
-			sc->sc_dev.dv_xname, error, exception);
+		    sc->sc_dev.dv_xname, error, exception);
 		mesh_error(sc, scb, error, 0);
 		return 1;
 	}
@@ -409,11 +407,11 @@
 		/* phase mismatch */
 		if (exception & MESH_EXC_PHASEMM) {
 			DPRINTF("%s: PHASE MISMATCH; nextstate = %d -> ",
-				sc->sc_dev.dv_xname, sc->sc_nextstate);
+			    sc->sc_dev.dv_xname, sc->sc_nextstate);
 			sc->sc_nextstate = status0 & MESH_PHASE_MASK;

 			DPRINTF("%d, resid = %d\n",
-				sc->sc_nextstate, scb->resid);
+			    sc->sc_nextstate, scb->resid);
 		}
 	}

@@ -430,8 +428,10 @@
 		break;
 	case MESH_DATAIN:
 	case MESH_DATAOUT:
-		if (mesh_dataio(sc, scb))
-			return(1);
+		if (mesh_dataio(sc, scb)) {
+			scb->xs->error = XS_DRIVER_STUFFUP;
+			mesh_done(sc, scb);
+		}
 		break;
 	case MESH_STATUS:
 		mesh_status(sc, scb);
@@ -586,12 +586,12 @@
 		if (i + 1 == sc->sc_dmamap->dm_nsegs)
 			cmd = datain ? DBDMA_CMD_IN_LAST : DBDMA_CMD_OUT_LAST;
 		DBDMA_BUILD(cmdp, cmd, 0, sc->sc_dmamap->dm_segs[i].ds_len,
-			sc->sc_dmamap->dm_segs[i].ds_addr,
-			DBDMA_INT_NEVER, DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);
+		    sc->sc_dmamap->dm_segs[i].ds_addr, DBDMA_INT_NEVER,
+		    DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);
 	}

 	DBDMA_BUILD(cmdp, DBDMA_CMD_STOP, 0, 0, 0,
-		DBDMA_INT_NEVER, DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);
+	    DBDMA_INT_NEVER, DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);

 	return(0);
 }
@@ -613,6 +613,7 @@
 		mesh_set_reg(sc, MESH_SEQUENCE, MESH_CMD_DATAIN | MESH_SEQ_DMA);
 	else
 		mesh_set_reg(sc, MESH_SEQUENCE, MESH_CMD_DATAOUT | MESH_SEQ_DMA);
+
 	dbdma_start(sc->sc_dmareg, sc->sc_dbdma);
 	sc->sc_flags |= MESH_DMA_ACTIVE;
 	sc->sc_nextstate = MESH_STATUS;
@@ -713,7 +714,7 @@
 	default:
 		sc_print_addr(scb->xs->sc_link);
 		printf("unrecognized MESSAGE(0x%02x); sending REJECT\n",
-			sc->sc_imsg[0]);
+		    sc->sc_imsg[0]);

 	reject:
 		mesh_msgout(sc, SEND_REJECT);
@@ -750,7 +751,7 @@
 	  }
 	default:
 		printf("%s target %d: rejecting extended message 0x%x\n",
-			sc->sc_dev.dv_xname, scb->target, sc->sc_imsg[0]);
+		    sc->sc_dev.dv_xname, scb->target, sc->sc_imsg[0]);
 		goto reject;
 	}

@@ -919,13 +920,10 @@
 mesh_get_scb(struct mesh_softc *sc)
 {
 	struct mesh_scb *scb;
-	int s;
-
-	s = splbio();
+
 	scb = TAILQ_FIRST(&sc->free_scb);
 	if (scb)
 		TAILQ_REMOVE(&sc->free_scb, scb, chain);
-	splx(s);

 	return scb;
 }
@@ -933,11 +931,7 @@
 void
 mesh_free_scb(struct mesh_softc *sc, struct mesh_scb *scb)
 {
-	int s;
-
-	s = splbio();
 	TAILQ_INSERT_TAIL(&sc->free_scb, scb, chain);
-	splx(s);
 }

 int
@@ -951,9 +945,10 @@

 	flags = xs->flags;
 	s = splbio();
-	if ((scb = mesh_get_scb(sc)) == NULL)
+	scb = mesh_get_scb(sc);
+	splx(s);
+	if (scb == NULL)
 		return (TRY_AGAIN_LATER);
-	splx(s);
 	DPRINTF("cmdlen: %d\n", xs->cmdlen);
 	scb->xs = xs;
 	scb->flags = 0;
@@ -977,19 +972,17 @@
 	if (sc->sc_nexus == NULL)
 		mesh_sched(sc);
 	splx(s);
-

-	if ((xs->flags & SCSI_POLL) == 0)
-		return SUCCESSFULLY_QUEUED;
-
-	if (mesh_poll(xs)) {
-	       	if (mesh_poll(xs)) {
-			printf("timeout\n");
+	if (xs->flags & SCSI_POLL) {
+		if (mesh_poll(xs)) {
+			printf("%s: poll timeout\n",
+			    sc->sc_dev.dv_xname);
+
 		}
-	}
-
-	return COMPLETE;
-
+		return COMPLETE;
+	}
+
+	return SUCCESSFULLY_QUEUED;
 }

 void


remove the warning for masked flags

remove the warning for masked flags

Although a nice idea in a lot of ways, there's no particular reason why we should do this for things that are represented by flags and not do it for the things represented by other Column attributes.

We could output a similar warning for the things changed in convert_unsupported_database_schema, but many of those are promotions (eg. width increases preserving type) and some not (eg. replacing UUID type with a character field), and it's hard to say which changes are relevant enough to warn about.

Complaining on every run is probably not desirable for many users, so it doesn't work well enough at the moment to be worth keeping, and it's better to be simple and consistent.

--- src/schema_matcher.h
+++ src/schema_matcher.h
@@ -411,11 +411,7 @@

 	void mask_unsupported_flags(Table &from_table) {
 		for (Column &column : from_table.columns) {
-			ColumnFlags masked_flags = (ColumnFlags)(column.flags & client.supported_flags());
-			if (column.flags != masked_flags) {
-				cerr << "Warning: the schema for column " << from_table.name << '.' << column.name << " is not fully supported by this database." << endl;
-				column.flags = masked_flags;
-			}
+			column.flags = (ColumnFlags)(column.flags & client.supported_flags());
 		}
 	}


KVM: PPC: allow ppc440gp to pass the compatibility check

Match only the first part of cur_cpu_spec->platform.

440GP (the first 440 processor) is identified by the string "ppc440gp", while
all later 440 processors use simply "ppc440".

Signed-off-by: Hollis Blanchard <cd9c751a7d90e05d28d5b07e1a27ef2eba49db0a@mentor.com>
Signed-off-by: Alexander Graf <3ad82b0c937b9aa51276120cedd545efc822be04@suse.de>

--- arch/powerpc/kvm/44x.c
+++ arch/powerpc/kvm/44x.c
@@ -43,7 +43,7 @@
 {
 	int r;

-	if (strcmp(cur_cpu_spec->platform, "ppc440") == 0)
+	if (strncmp(cur_cpu_spec->platform, "ppc440", 6) == 0)
 		r = 0;
 	else
 		r = -ENOTSUPP;
@@ -72,6 +72,7 @@
 	/* Since the guest can directly access the timebase, it must know the
 	 * real timebase frequency. Accordingly, it must see the state of
 	 * CCR1[TCS]. */
+	/* XXX CCR1 doesn't exist on all 440 SoCs. */
 	vcpu->arch.ccr1 = mfspr(SPRN_CCR1);

 	for (i = 0; i < ARRAY_SIZE(vcpu_44x->shadow_refs); i++)


lmtp proxy: Avoid hanging at the end of message input.

--- src/lmtp/lmtp-proxy.c
+++ src/lmtp/lmtp-proxy.c
@@ -376,6 +376,14 @@
 		proxy->to = timeout_add(proxy->max_timeout_msecs,
 					lmtp_proxy_output_timeout, proxy);
 	}
+}
+
+static void proxy_send_more(struct lmtp_proxy *proxy)
+{
+	struct lmtp_proxy_connection *const *conns;
+
+	array_foreach(&proxy->connections, conns)
+		lmtp_client_send_more((*conns)->client);
 }

 static bool lmtp_proxy_data_read(struct lmtp_proxy *proxy)
@@ -404,6 +412,8 @@
 		if (proxy->data_input->stream_errno != 0)
 			lmtp_proxy_fail_all(proxy, "disconnect");
 		else {
+			/* make sure LMTP clients see the EOF */
+			proxy_send_more(proxy);
 			/* finished reading data input. now we'll just have to
 			   wait for replies. */
 			lmtp_proxy_wait_for_output(proxy);
@@ -423,14 +433,11 @@

 static void lmtp_proxy_data_input(struct lmtp_proxy *proxy)
 {
-	struct lmtp_proxy_connection *const *conns;
-
 	i_assert(!proxy->handling_data_input);

 	proxy->handling_data_input = TRUE;
 	do {
-		array_foreach(&proxy->connections, conns)
-			lmtp_client_send_more((*conns)->client);
+		proxy_send_more(proxy);
 	} while (lmtp_proxy_data_read(proxy));
 	proxy->handling_data_input = FALSE;
 }


powerpc: Ensure random space between stack and mmaps

get_random_int() returns the same value within a 1 jiffy interval. This means
that the mmap and stack regions will almost always end up the same distance
apart, making a relative offset based attack possible.

To fix this, shift the randomness we use for the mmap region by 1 bit.

Signed-off-by: Anton Blanchard <14deb5e5e417133e888bf47bb6a3555c9bb7d81c@samba.org>
Signed-off-by: Benjamin Herrenschmidt <a7089bb6e7e92505d88aaff006cbdd60cc9120b6@kernel.crashing.org>

--- arch/powerpc/mm/mmap.c
+++ arch/powerpc/mm/mmap.c
@@ -46,6 +46,14 @@
 	return sysctl_legacy_va_layout;
 }

+/*
+ * Since get_random_int() returns the same value within a 1 jiffy window,
+ * we will almost always get the same randomisation for the stack and mmap
+ * region. This will mean the relative distance between stack and mmap will
+ * be the same.
+ *
+ * To avoid this we can shift the randomness by 1 bit.
+ */
 static unsigned long mmap_rnd(void)
 {
 	unsigned long rnd = 0;
@@ -53,11 +61,11 @@
 	if (current->flags & PF_RANDOMIZE) {
 		/* 8MB for 32bit, 1GB for 64bit */
 		if (is_32bit_task())
-			rnd = (long)(get_random_int() % (1<<(23-PAGE_SHIFT)));
+			rnd = (long)(get_random_int() % (1<<(22-PAGE_SHIFT)));
 		else
-			rnd = (long)(get_random_int() % (1<<(30-PAGE_SHIFT)));
+			rnd = (long)(get_random_int() % (1<<(29-PAGE_SHIFT)));
 	}
-	return rnd << PAGE_SHIFT;
+	return (rnd << PAGE_SHIFT) * 2;
 }

 static inline unsigned long mmap_base(void)


sh: Drop associative writes for SH-4 cache flushes.

When flushing/invalidating the icache/dcache via the memory-mapped IC/OC
address arrays, the associative bit should only be used in conjunction with
virtual addresses. However, we currently flush cache lines based on physical
address, so stop using the associative bit.

It is a better strategy to use non-associative writes (and physical tags) for
flushing the caches anyway, because flushing by virtual address (as with the
A-bit set) requires a valid TLB entry for that virtual address. If one does not
exist in the TLB no exception is generated and the flush is silently ignored.

This is also future-proofing for SH-4A parts which are gradually phasing out
associative writes to the cache array due to the aforementioned case of certain
flushes silently turning in to nops.

Signed-off-by: Matt Fleming <1fa2ef4755a9226cb9a0a4840bd89b158ac71391@console-pimps.org>
Signed-off-by: Paul Mundt <38b52dbb5f0b63d149982b6c5de788ec93a89032@linux-sh.org>

--- arch/sh/mm/cache-sh4.c
+++ arch/sh/mm/cache-sh4.c
@@ -98,7 +98,7 @@
 		exec_offset = cached_to_uncached;

 	local_irq_save(flags);
-	__flush_cache_one(start | SH_CACHE_ASSOC, phys, exec_offset);
+	__flush_cache_one(start, phys, exec_offset);
 	local_irq_restore(flags);
 }

@@ -123,7 +123,7 @@

 		/* Loop all the D-cache */
 		n = boot_cpu_data.dcache.n_aliases;
-		for (i = 0; i <= n; i++, addr += PAGE_SIZE)
+		for (i = 0; i < n; i++, addr += PAGE_SIZE)
 			flush_cache_one(addr, phys);
 	}


Cast in places where we discard volatile pointers in function calls.  We know that what we are doing is ok, so let gcc know this.

--- arch/sparc/dev/if_le.c
+++ arch/sparc/dev/if_le.c
@@ -412,7 +412,7 @@
 		ler2->ler2_tmd[i].tmd3 = 0;
 	}

-bzero(&ler2->ler2_rbuf[0][0], (LERBUF + LETBUF) * LEMTU);
+bzero((void *)&ler2->ler2_rbuf[0][0], (LERBUF + LETBUF) * LEMTU);
 	/* lance will stuff packet into receive buffer 0 next */
 	sc->sc_rmd = 0;

@@ -483,14 +483,14 @@
 	IF_DEQUEUE(&sc->sc_if.if_snd, m);
 	if (m == 0)
 		return;
-	len = leput(sc->sc_r2->ler2_tbuf[0], m);
+	len = leput((char *)sc->sc_r2->ler2_tbuf[0], m);
 #if NBPFILTER > 0
 	/*
 	 * If bpf is listening on this interface, let it
 	 * see the packet before we commit it to the wire.
 	 */
 	if (sc->sc_if.if_bpf)
-		bpf_tap(sc->sc_if.if_bpf, sc->sc_r2->ler2_tbuf[0], len);
+		bpf_tap(sc->sc_if.if_bpf, (u_char *)sc->sc_r2->ler2_tbuf[0], len);
 #endif

 #ifdef PACKETSTATS
@@ -672,7 +672,7 @@
 				return;
 			}
 		} else {
-			leread(sc, sc->sc_r2->ler2_rbuf[bix], len);
+			leread(sc, (char *)sc->sc_r2->ler2_rbuf[bix], len);
 #ifdef PACKETSTATS
 			lerpacketsizes[len]++;
 #endif


libnvdimm, e820: skip module loading when no type-12

If there are no persistent memory ranges present then don't bother
creating the platform device.  Otherwise, it loads the full libnvdimm
sub-system only to discover no resources present.

Reported-by: Andy Lutomirski <2cc0d0d76de2e6f37b92deeb83c85cb306fc5dc1@amacapital.net>
Acked-by: Andy Lutomirski <2cc0d0d76de2e6f37b92deeb83c85cb306fc5dc1@amacapital.net>
Signed-off-by: Dan Williams <24ee2bf0bd8ac766c348bf1f0639943bac1535c6@intel.com>


KVM: x86 emulator: Check segment limits in real mode too

Segment limits are verified in real mode, not just protected mode.

Signed-off-by: Avi Kivity <8f920f22884d6fea9df883843c4a8095a2e5ac6f@redhat.com>
Signed-off-by: Marcelo Tosatti <958bcd1f4a7a8c36dca09fe3fa9cb5f1483adf51@redhat.com>

--- arch/x86/kvm/emulate.c
+++ arch/x86/kvm/emulate.c
@@ -668,8 +668,6 @@

 	la = seg_base(ctxt, addr.seg) + addr.ea;
 	switch (ctxt->mode) {
-	case X86EMUL_MODE_REAL:
-		break;
 	case X86EMUL_MODE_PROT64:
 		if (((signed long)la << 16) >> 16 != la)
 			return emulate_gp(ctxt, 0);
@@ -699,7 +697,10 @@
 				goto bad;
 		}
 		cpl = ctxt->ops->cpl(ctxt);
-		rpl = sel & 3;
+		if (ctxt->mode == X86EMUL_MODE_REAL)
+			rpl = 0;
+		else
+			rpl = sel & 3;
 		cpl = max(cpl, rpl);
 		if (!(desc.type & 8)) {
 			/* data segment */


added a parseTypes function to test

added a parseTypes function to test

--- src/logic/FOLParser.h
+++ src/logic/FOLParser.h
@@ -936,6 +936,15 @@
     iters<ForwardIterator> its(first, last);
     return doParseWeightedFormula(its);
 }
+
+template <class ForwardIterator>
+void parseTypes(const ForwardIterator &first,
+        const ForwardIterator& last,
+        std::map<std::string, std::set<std::string> >& objTypes,
+        std::map<std::string, std::vector<std::string> >& predTypes) {
+    iters<ForwardIterator> its(first, last);
+    doParseType(objTypes, predTypes, its);
+}
 };


KVM: x86 emulator: refuse SrcMemFAddr (e.g. LDS) with register operand

SrcMemFAddr is not defined with the modrm operand designating a register
instead of a memory address.

Signed-off-by: Avi Kivity <8f920f22884d6fea9df883843c4a8095a2e5ac6f@redhat.com>
Signed-off-by: Marcelo Tosatti <958bcd1f4a7a8c36dca09fe3fa9cb5f1483adf51@redhat.com>

--- arch/x86/kvm/emulate.c
+++ arch/x86/kvm/emulate.c
@@ -2974,6 +2974,11 @@
 		goto done;
 	}

+	if ((c->d & SrcMask) == SrcMemFAddr && c->src.type != OP_MEM) {
+		emulate_ud(ctxt);
+		goto done;
+	}
+
 	/* Privileged instruction can be executed only in CPL=0 */
 	if ((c->d & Priv) && ops->cpl(ctxt->vcpu)) {
 		emulate_gp(ctxt, 0);


KVM: x86 emulator: reserve group code 0

KVM: x86 emulator: reserve group code 0

We'll be using that to distinguish between new-style and old-style groups.

Signed-off-by: Avi Kivity <8f920f22884d6fea9df883843c4a8095a2e5ac6f@redhat.com>
Signed-off-by: Marcelo Tosatti <958bcd1f4a7a8c36dca09fe3fa9cb5f1483adf51@redhat.com>

--- arch/x86/kvm/emulate.c
+++ arch/x86/kvm/emulate.c
@@ -105,7 +105,7 @@
 #define X16(x) X8(x), X8(x)

 enum {
-	Group1, Group1A, Group3, Group4, Group5, Group7, Group8, Group9,
+	NoGrp, Group1, Group1A, Group3, Group4, Group5, Group7, Group8, Group9,
 };

 struct opcode {


session client FEATURE support <get> in addition to <get-data>

Fixes #340

--- src/session_client.c
+++ src/session_client.c
@@ -661,7 +661,7 @@
 }

 static int
-build_schema_info_yl(struct nc_session *session, struct schema_info **result)
+build_schema_info_yl(struct nc_session *session, int has_get_data, struct schema_info **result)
 {
     struct nc_rpc *rpc = NULL;
     struct lyd_node *op = NULL, *envp = NULL;
@@ -672,16 +672,28 @@
     uint32_t u, v, submodules_count, feature_count;
     struct lyd_node *iter, *child;
     struct lys_module *mod;
-    int ret = EXIT_SUCCESS;
+    int ret = 0;
+    const char *rpc_name;

     /* get yang-library data from the server */
-    if (nc_session_cpblt(session, "urn:ietf:params:netconf:capability:xpath:1.0")) {
-        rpc = nc_rpc_getdata("ietf-datastores:operational", "/ietf-yang-library:*", "false", NULL, 0, 0, 0, 0, 0,
-                NC_PARAMTYPE_CONST);
+    if (has_get_data) {
+        rpc_name = "get-data";
+        if (nc_session_cpblt(session, "urn:ietf:params:netconf:capability:xpath:1.0")) {
+            rpc = nc_rpc_getdata("ietf-datastores:operational", "/ietf-yang-library:*", "false", NULL, 0, 0, 0, 0, 0,
+                    NC_PARAMTYPE_CONST);
+        } else {
+            rpc = nc_rpc_getdata("ietf-datastores:operational",
+                    "<modules-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-yang-library\"/>", "false", NULL, 0, 0, 0, 0,
+                    0, NC_PARAMTYPE_CONST);
+        }
     } else {
-        rpc = nc_rpc_getdata("ietf-datastores:operational",
-                "<modules-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-yang-library\"/>", "false", NULL, 0, 0, 0, 0,
-                0, NC_PARAMTYPE_CONST);
+        rpc_name = "get";
+        if (nc_session_cpblt(session, "urn:ietf:params:netconf:capability:xpath:1.0")) {
+            rpc = nc_rpc_get("/ietf-yang-library:*", 0, NC_PARAMTYPE_CONST);
+        } else {
+            rpc = nc_rpc_get("<modules-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-yang-library\"/>", 0,
+                    NC_PARAMTYPE_CONST);
+        }
     }
     if (!rpc) {
         goto cleanup;
@@ -702,34 +714,34 @@
         msg = nc_recv_reply(session, rpc, msgid, NC_READ_ACT_TIMEOUT * 1000, &envp, &op);
     } while (msg == NC_MSG_NOTIF || msg == NC_MSG_REPLY_ERR_MSGID);
     if (msg == NC_MSG_WOULDBLOCK) {
-        WRN(session, "Timeout for receiving reply to a <get-data> yang-library data expired.");
+        WRN(session, "Timeout for receiving reply to a <%s> yang-library data expired.", rpc_name);
         goto cleanup;
     } else if (msg == NC_MSG_ERROR) {
-        WRN(session, "Failed to receive a reply to <get-data> of yang-library data.");
+        WRN(session, "Failed to receive a reply to <%s> of yang-library data.", rpc_name);
         goto cleanup;
     } else if (!op || !lyd_child(op) || strcmp(lyd_child(op)->schema->name, "data")) {
-        WRN(session, "Unexpected reply without data to a yang-library <get-data> RPC.");
+        WRN(session, "Unexpected reply without data to a yang-library <%s> RPC.", rpc_name);
         goto cleanup;
     }

     data = (struct lyd_node_any *)lyd_child(op);
     if (data->value_type != LYD_ANYDATA_DATATREE) {
-        WRN(session, "Unexpected data in reply to a yang-library <get-data> RPC.");
+        WRN(session, "Unexpected data in reply to a yang-library <%s> RPC.", rpc_name);
         goto cleanup;
     } else if (!data->value.tree) {
-        WRN(session, "No data in reply to a yang-library <get-data> RPC.");
+        WRN(session, "No data in reply to a yang-library <%s> RPC.", rpc_name);
         goto cleanup;
     }

     if (lyd_find_xpath(data->value.tree, "/ietf-yang-library:modules-state/module", &modules)) {
-        WRN(session, "No module information in reply to a yang-library <get-data> RPC.");
+        WRN(session, "No module information in reply to a yang-library <%s> RPC.", rpc_name);
         goto cleanup;
     }

     (*result) = calloc(modules->count + 1, sizeof **result);
     if (!(*result)) {
         ERRMEM;
-        ret = EXIT_FAILURE;
+        ret = -1;
         goto cleanup;
     }

@@ -758,7 +770,7 @@
                     ERRMEM;
                     free_schema_info(*result);
                     *result = NULL;
-                    ret = EXIT_FAILURE;
+                    ret = -1;
                     goto cleanup;
                 }
                 (*result)[u].features[feature_count] = strdup(lyd_get_value(iter));
@@ -775,7 +787,7 @@
                 ERRMEM;
                 free_schema_info(*result);
                 *result = NULL;
-                ret = EXIT_FAILURE;
+                ret = -1;
                 goto cleanup;
             } else {
                 v = 0;
@@ -822,7 +834,7 @@
     (*result) = calloc(u + 1, sizeof **result);
     if (!(*result)) {
         ERRMEM;
-        return EXIT_FAILURE;
+        return -1;
     }

     for (u = v = 0; cpblts[u]; ++u) {
@@ -878,14 +890,14 @@
         ++v;
     }

-    return EXIT_SUCCESS;
+    return 0;
 }

 static int
 nc_ctx_fill(struct nc_session *session, struct schema_info *modules, ly_module_imp_clb user_clb, void *user_data,
         int has_get_schema)
 {
-    int ret = EXIT_FAILURE;
+    int ret = -1;
     struct lys_module *mod;
     uint32_t u;

@@ -916,7 +928,7 @@
     }

     /* success */
-    ret = EXIT_SUCCESS;
+    ret = 0;

 cleanup:
     return ret;
@@ -938,7 +950,7 @@
     }
     if (!ietfnc) {
         ERR(session, "Loading base NETCONF schema failed.");
-        return 1;
+        return -1;
     }

     /* set supported capabilities from ietf-netconf */
@@ -956,7 +968,7 @@
 int
 nc_ctx_check_and_fill(struct nc_session *session)
 {
-    int i, get_schema_support = 0, yanglib_support = 0, ret = -1;
+    int i, get_schema_support = 0, yanglib_support = 0, get_data_support = 0, ret = -1;
     ly_module_imp_clb old_clb = NULL;
     void *old_data = NULL;
     struct lys_module *mod = NULL;
@@ -1045,18 +1057,17 @@
             free(revision);

             /* ietf-netconf-nmda is needed to issue get-data */
-            if (nc_ctx_load_module(session, "ietf-netconf-nmda", NULL, server_modules, old_clb, old_data,
+            if (!nc_ctx_load_module(session, "ietf-netconf-nmda", NULL, server_modules, old_clb, old_data,
                     get_schema_support, &mod)) {
-                WRN(session, "Loading NETCONF ietf-netconf-nmda schema failed, unable to use get-data to retrieve "
-                        "yang-library data.");
-                yanglib_support = 0;
+                VRB(session, "Support for <get-data> from ietf-netcon-nmda found.");
+                get_data_support = 1;
             }
         }
     }

     /* prepare structured information about server's schemas */
     if (yanglib_support) {
-        if (build_schema_info_yl(session, &sm)) {
+        if (build_schema_info_yl(session, get_data_support, &sm)) {
             goto cleanup;
         } else if (!sm) {
             VRB(session, "Trying to use capabilities instead of ietf-yang-library data.");


Use mush_caabb_idx in {valid_,}min_max_size.

--- space.98.c
+++ space.98.c
@@ -177,11 +177,11 @@
 	const mush_bounds*, const mush_aabb*, size_t, void*);

 static void mushspace_min_max_size(
-	mush_bounds*, mushspace_consumee*, size_t*, size_t, const mush_aabb*);
+	mush_bounds*, mushspace_consumee*, size_t*, mush_caabb_idx);

 static bool mushspace_valid_min_max_size(
 	bool (*)(const mush_bounds*, const mush_aabb*, size_t, void*), void*,
-	mush_bounds*, mushspace_consumee*, size_t*, size_t, const mush_aabb*);
+	mush_bounds*, mushspace_consumee*, size_t*, mush_caabb_idx);

 static bool mushspace_cheaper_to_alloc(size_t, size_t);

@@ -814,11 +814,13 @@
 		if (c == space->box_count)
 			continue;

-		if (!mush_bounds_contains_bounds(consumer, &space->boxen[c].bounds))
+		mush_caabb_idx box = mushspace_get_caabb_idx(space, c);
+
+		if (!mush_bounds_contains_bounds(consumer, &box.aabb->bounds))
 			continue;

 		subsumees->ptr[subsumees->len++] = c;
-		mushspace_min_max_size(NULL, consumee, used_cells, c, &space->boxen[c]);
+		mushspace_min_max_size(NULL, consumee, used_cells, box);

 		candidates[i] = space->box_count;

@@ -905,7 +907,7 @@

 		mushspace_min_max_size(
 			consumer, consumee, used_cells,
-			subsumees->ptr[i], &space->boxen[subsumees->ptr[i]]);
+			mushspace_get_caabb_idx(space, subsumees->ptr[i]));

 		candidates[corrected] = space->box_count;

@@ -924,14 +926,16 @@
 		if (c == space->box_count)
 			continue;

+		mush_caabb_idx box = mushspace_get_caabb_idx(space, c);
+
 		// All fusables have been removed, so a sufficient condition for
 		// disjointness is non-overlappingness.
-		if (mush_bounds_overlaps(consumer, &space->boxen[c].bounds))
+		if (mush_bounds_overlaps(consumer, &box.aabb->bounds))
 			continue;

 		if (mushspace_valid_min_max_size(mushspace_disjoint_mms_validator,
 		                                 NULL, consumer, consumee,
-		                                 used_cells, c, &space->boxen[c]))
+		                                 used_cells, box))
 		{
 			subsumees->ptr[subsumees->len++] = c;
 			candidates[i] = space->box_count;
@@ -960,12 +964,14 @@
 		if (c == space->box_count)
 			continue;

-		if (!mush_bounds_overlaps(consumer, &space->boxen[c].bounds))
+		mush_caabb_idx box = mushspace_get_caabb_idx(space, c);
+
+		if (!mush_bounds_overlaps(consumer, &box.aabb->bounds))
 			continue;

 		if (mushspace_valid_min_max_size(mushspace_overlaps_mms_validator,
 		                                 consumer, consumer, consumee,
-		                                 used_cells, c, &space->boxen[c]))
+		                                 used_cells, box))
 		{
 			subsumees->ptr[subsumees->len++] = c;
 			candidates[i] = space->box_count;
@@ -991,16 +997,16 @@
 static void mushspace_min_max_size(
 	mush_bounds* bounds,
 	mushspace_consumee* max, size_t* total_size,
-	size_t box_idx, const mush_aabb* box)
-{
-	*total_size += box->size;
-	if (box->size > max->size) {
-		max->size = box->size;
-		max->idx  = box_idx;
+	mush_caabb_idx box)
+{
+	*total_size += box.aabb->size;
+	if (box.aabb->size > max->size) {
+		max->size = box.aabb->size;
+		max->idx  = box.idx;
 	}
 	if (bounds) {
-		mushcoords_min_into(&bounds->beg, box->bounds.beg);
-		mushcoords_max_into(&bounds->end, box->bounds.end);
+		mushcoords_min_into(&bounds->beg, box.aabb->bounds.beg);
+		mushcoords_max_into(&bounds->end, box.aabb->bounds.end);
 	}
 }
 // Fills in the input values with the mushspace_min_max_size data, returning
@@ -1017,16 +1023,15 @@
 	void* userdata,
 	mush_bounds* bounds,
 	mushspace_consumee* max, size_t* total_size,
-	size_t box_idx, const mush_aabb* box)
+	mush_caabb_idx box)
 {
 	mush_bounds try_bounds = *bounds;
 	mushspace_consumee try_max = *max;
 	size_t try_total_size = *total_size;

-	mushspace_min_max_size(
-		&try_bounds, &try_max, &try_total_size, box_idx, box);
-
-	if (!valid(&try_bounds, box, *total_size, userdata))
+	mushspace_min_max_size(&try_bounds, &try_max, &try_total_size, box);
+
+	if (!valid(&try_bounds, box.aabb, *total_size, userdata))
 		return false;

 	*bounds     = try_bounds;


Removed code duplication

Removed code duplication

--- src/main/c/jpy_conv.c
+++ src/main/c/jpy_conv.c
@@ -7,26 +7,7 @@

 int JPy_AsJObject(JNIEnv* jenv, PyObject* pyObj, jobject* objectRef)
 {
-    if (pyObj == Py_None) {
-        *objectRef = NULL;
-        return 0;
-    } else if (JObj_Check(pyObj)) {
-        *objectRef = ((JPy_JObj*) pyObj)->objectRef;
-        return 0;
-    } else if (PyBool_Check(pyObj)) {
-        return JPy_AsJObjectWithType(jenv, pyObj, objectRef, JPy_JBooleanObj);
-    } else if (PyLong_Check(pyObj)) {
-        return JPy_AsJObjectWithType(jenv, pyObj, objectRef, JPy_JIntegerObj);
-    } else if (PyFloat_Check(pyObj)) {
-        return JPy_AsJObjectWithType(jenv, pyObj, objectRef, JPy_JDoubleObj);
-    } else if (PyUnicode_Check(pyObj)) {
-        return JPy_AsJObjectWithType(jenv, pyObj, objectRef, JPy_JString);
-    } else {
-        // todo: print Python type(pyObj) info here, otherwise users don't know what went wrong
-        PyErr_SetString(PyExc_RuntimeError, "don't know how to convert Python to Java object");
-        *objectRef = NULL;
-        return -1;
-    }
+    return JType_ConvertPythonToJavaObject(jenv, JPy_JObject, pyObj, objectRef);
 }

 int JPy_AsJObjectWithType(JNIEnv* jenv, PyObject* pyObj, jobject* objectRef, JPy_JType* type)


Modified PCBoard loader to use bit fonts

--- ansilove/ansilove.c
+++ ansilove/ansilove.c
@@ -1022,36 +1022,36 @@
     int32_t font_size_x;
     int32_t font_size_y;
     int32_t columns = 80;
-    char *font_file;
-
+    const unsigned char *font_data;
+
     // let's see what font we should use to render output
     if (strcmp(font, "80x25") == 0) {
-        font_file = "ansilove_font_pc_80x25.png";
-        font_size_x = 9;
+        font_data = font_pc_80x25;
+        font_size_x = 8;
         font_size_y = 16;
     }
     else if (strcmp(font, "80x50") == 0) {
-        font_file = "ansilove_font_pc_80x50.png";
-        font_size_x = 9;
+        font_data = font_pc_80x50;
+        font_size_x = 8;
         font_size_y = 8;
     }
     else if (strcmp(font, "terminus") == 0) {
-        font_file = "ansilove_font_pc_terminus.png";
-        font_size_x = 9;
+        font_data = font_pc_terminus;
+        font_size_x = 8;
         font_size_y = 16;
     }
     else {
         // in all other cases use the standard DOS font
-        font_file = "ansilove_font_pc_80x25.png";
-        font_size_x = 9;
-        font_size_y = 16;
-    }
-
+        font_data = font_pc_80x25;
+        font_size_x = 8;
+        font_size_y = 16;
+    }
+
     // now set bits to 8 if not already value 8 or 9
     if (strcmp(bits, "8") != 0 && strcmp(bits, "9") != 0) {
         sprintf(bits, "%s", "8");
     }
-
+
     // load input file
     FILE *input_file = fopen(input, "r");
     if (input_file == NULL) {
@@ -1061,7 +1061,7 @@
     // get the file size (bytes)
     size_t get_file_size = filesize(input);
     int32_t input_file_size = (int32_t)get_file_size;
-
+
     // next up is loading our file into a dynamically allocated memory buffer
     unsigned char *input_file_buffer;
     size_t result;
@@ -1081,63 +1081,12 @@
     // close input file, we don't need it anymore
     rewind(input_file);
     fclose(input_file);
-
+
     // libgd image pointers
-    gdImagePtr im_PCB, im_Backgrnd, im_Font;
-
-    // additional libgd related declarations
-    FILE *file_Backgrnd, *file_Font;
-    char path_Backgrnd[1000] = { 0 };
-    char path_Font[1000] = { 0 };
-
-    // resolve paths for font and background image
-    sprintf(path_Backgrnd, "%sansilove_background.png", ANSILOVE_FONTS_DIRECTORY);
-    sprintf(path_Font, "%s%s", ANSILOVE_FONTS_DIRECTORY, font_file);
-
-    // open font and background image, allocate libgd image pointers
-    file_Backgrnd = fopen(path_Backgrnd, "rb");
-    file_Font = fopen(path_Font, "rb");
-
-    if (!file_Backgrnd) {
-        fputs ("\nCan't open AnsiLove/C background image, aborted.\n\n", stderr); exit (4);
-    }
-    else {
-        im_Backgrnd = gdImageCreateFromPng(file_Backgrnd);
-    }
-
-    if (!file_Font) {
-        fputs ("\nCan't open AnsiLove/C font file, aborted.\n\n", stderr); exit (5);
-    }
-    else {
-        im_Font = gdImageCreateFromPng(file_Font);
-    }
-
-    // set transparent color index for the font
-    gdImageColorTransparent(im_Font, 20);
-
+    gdImagePtr im_PCB;
+
     // convert numeric command line flags to integer values
     int32_t int_bits = atoi(bits);
-
-    // foreground / background color array
-    int32_t pcb_colors[71];
-
-    // PCB colors
-    pcb_colors[48] = 0;
-    pcb_colors[49] = 4;
-    pcb_colors[50] = 2;
-    pcb_colors[51] = 6;
-    pcb_colors[52] = 1;
-    pcb_colors[53] = 5;
-    pcb_colors[54] = 3;
-    pcb_colors[55] = 7;
-    pcb_colors[56] = 8;
-    pcb_colors[57] = 12;
-    pcb_colors[65] = 10;
-    pcb_colors[66] = 14;
-    pcb_colors[67] = 9;
-    pcb_colors[68] = 13;
-    pcb_colors[69] = 11;
-    pcb_colors[70] = 15;

     // defines for stripping PCBoard codes
     char *stripped_file_buffer;
@@ -1213,8 +1162,8 @@
         if (current_character == 64 & next_character == 88)
         {
             // set graphics rendition
-            color_background = pcb_colors[(input_file_buffer[loop+2])];
-            color_foreground = pcb_colors[(input_file_buffer[loop+3])];
+            color_background = input_file_buffer[loop+2];
+            color_foreground = input_file_buffer[loop+3];

             loop+=3;
         }
@@ -1280,14 +1229,29 @@
     // allocate buffer image memory
     im_PCB = gdImageCreate(columns * int_bits, (position_y_max)*font_size_y);

-    // error output
-    if (!im_Backgrnd) {
-        fputs ("\nCan't allocate PCB buffer image memory.\n\n", stderr); exit (6);
-    }
-
     // allocate black color
     gdImageColorAllocate(im_PCB, 0, 0, 0);
-
+
+    // allocate color palette
+    int32_t colors[71];
+
+    colors[48] = gdImageColorAllocate(im_PCB, 0, 0, 0);
+    colors[49] = gdImageColorAllocate(im_PCB, 0, 0, 170);
+    colors[50] = gdImageColorAllocate(im_PCB, 0, 170, 0);
+    colors[51] = gdImageColorAllocate(im_PCB, 0, 170, 170);
+    colors[52] = gdImageColorAllocate(im_PCB, 170, 0, 0);
+    colors[53] = gdImageColorAllocate(im_PCB, 170, 0, 170);
+    colors[54] = gdImageColorAllocate(im_PCB, 170, 85, 0);
+    colors[55] = gdImageColorAllocate(im_PCB, 170, 170, 170);
+    colors[56] = gdImageColorAllocate(im_PCB, 85, 85, 85);
+    colors[57] = gdImageColorAllocate(im_PCB, 85, 85, 255);
+    colors[65] = gdImageColorAllocate(im_PCB, 85, 255, 85);
+    colors[66] = gdImageColorAllocate(im_PCB, 85, 255, 255);
+    colors[67] = gdImageColorAllocate(im_PCB, 255, 85, 85);
+    colors[68] = gdImageColorAllocate(im_PCB, 255, 85, 255);
+    colors[69] = gdImageColorAllocate(im_PCB, 255, 255, 85);
+    colors[70] = gdImageColorAllocate(im_PCB, 255, 255, 255);
+
     // the last value of loop tells us how many items are stored in there
     int32_t pcbBufferItems = structIndex;

@@ -1301,11 +1265,7 @@
         color_foreground = pcboard_buffer[loop].color_foreground;
         character = pcboard_buffer[loop].current_character;

-        gdImageCopy(im_PCB,im_Backgrnd,position_x * int_bits, position_y *
-                    font_size_y, color_background * 9, 0, int_bits, font_size_y);
-
-        gdImageCopy(im_PCB,im_Font, position_x * int_bits, position_y * font_size_y, character *
-                    font_size_x, color_foreground * font_size_y, int_bits, font_size_y);
+        alDrawChar(im_PCB, font_data, int_bits, font_size_x, font_size_y, position_x, position_y, colors[color_background], colors[color_foreground], character);
     }

     // create output image
@@ -1315,8 +1275,6 @@

     // free memory
     gdImageDestroy(im_PCB);
-    gdImageDestroy(im_Backgrnd);
-    gdImageDestroy(im_Font);
 }

 // BINARY


Added todo regarding String as sequence

Added todo regarding String as sequence

--- src/main/c/jpy_jobj.c
+++ src/main/c/jpy_jobj.c
@@ -269,6 +269,11 @@

     typeObj->tp_getattro = JObj_getattro;

+    // todo: add  <sequence> protocol to 'java.lang.String' type.
+    // Note that we have to do this after assigning the type to the global variable 'JPy_JString'.
+    // However, this function (JType_InitSlots) is called *while* assigning the value 'JPy_JString'
+    // so we cannot use to test against it here.
+
     // If this type is an array type, add support for the <sequence> protocol
     if (type->componentType != NULL) {
         typeObj->tp_as_sequence = &JObj_as_sequence;


Fix 2x2 d45 intra prediction

Fix 2x2 d45 intra prediction

This commit fixes the 2x2 d45 intra prediction. It avoids the use
of out-of-boundary position as reference. This resolves an enc/dec
mismatch issue in cb4x4 mode.

Change-Id: I93d01536a0c004190cc9fe3c724bf41364f6fdde

--- aom_dsp/intrapred.c
+++ aom_dsp/intrapred.c
@@ -495,12 +495,11 @@
   const int B = above[1];
   const int C = above[2];
   const int D = above[3];
-  const int E = above[4];
   (void)stride;
   (void)left;
   DST(0, 0) = AVG3(A, B, C);
   DST(1, 0) = DST(0, 1) = AVG3(B, C, D);
-  DST(1, 1) = AVG3(C, D, E);
+  DST(1, 1) = AVG3(C, D, D);
 }

 void aom_d45e_predictor_2x2_c(uint8_t *dst, ptrdiff_t stride,
@@ -509,12 +508,12 @@
   const int B = above[1];
   const int C = above[2];
   const int D = above[3];
-  const int E = above[4];
   (void)stride;
   (void)left;
+
   DST(0, 0) = AVG3(A, B, C);
   DST(1, 0) = DST(0, 1) = AVG3(B, C, D);
-  DST(1, 1) = AVG3(C, D, E);
+  DST(1, 1) = AVG3(C, D, D);
 }

 void aom_d117_predictor_2x2_c(uint8_t *dst, ptrdiff_t stride,


engine: on shutdown, release collector contexts

Signed-off-by: Eduardo Silva <81f705dc2ce1a61a2621e0e4b442a9474e1d0c70@treasure-data.com>

--- src/flb_engine.c
+++ src/flb_engine.c
@@ -224,7 +224,7 @@

     /* Create and register the timer fd for flush procedure */
-    event = malloc(sizeof(struct mk_event));
+    event = &config->event_flush;
     event->mask = MK_EVENT_EMPTY;
     event->status = MK_EVENT_NONE;

@@ -277,7 +277,7 @@
                      * We are preparing to shutdown, we give a graceful time
                      * of 5 seconds to process any pending event.
                      */
-                    event = malloc(sizeof(struct mk_event));
+                    event = &config->event_shutdown;
                     event->mask = MK_EVENT_EMPTY;
                     event->status = MK_EVENT_NONE;
                     config->shutdown_fd = mk_event_timeout_create(evl, 5, event);
@@ -349,10 +349,19 @@
         }
     }

-    mk_list_foreach(head, &config->collectors) {
+    mk_list_foreach_safe(head, tmp, &config->collectors) {
         collector = mk_list_entry(head, struct flb_input_collector, _head);
-    }
-
+        mk_event_del(config->evl, &collector->event);
+
+        if (collector->type == FLB_COLLECT_TIME) {
+            close(collector->fd_timer);
+        }
+
+        mk_list_del(&collector->_head);
+        free(collector);
+    }
+
+    mk_event_del(config->evl, &config->event_flush);
     close(config->flush_fd);
     mk_event_loop_destroy(config->evl);
     free(config);


filter: validate chunkio return value (CID 185658)

Signed-off-by: Eduardo Silva <81f705dc2ce1a61a2621e0e4b442a9474e1d0c70@treasure-data.com>

--- src/flb_filter.c
+++ src/flb_filter.c
@@ -167,9 +167,13 @@
                 /* Point back the 'data' pointer to the new address */
                 ret = cio_chunk_get_content(ic->chunk,
                                             (char **) &work_data, &cur_size);
-
-                work_data += (cur_size - out_size);
-                work_size = out_size;
+                if (ret == -1) {
+                    flb_error("[filter] error retrieving data chunk");
+                }
+                else {
+                    work_data += (cur_size - out_size);
+                    work_size = out_size;
+                }
                 flb_free(out_buf);
             }
         }


output: initialize TLS instance context as NULL

Signed-off-by: Eduardo Silva <81f705dc2ce1a61a2621e0e4b442a9474e1d0c70@treasure-data.com>

--- src/flb_output.c
+++ src/flb_output.c
@@ -153,6 +153,7 @@
         instance->host.name = NULL;

 #ifdef HAVE_TLS
+        instance->tls.context    = NULL;
         instance->tls_verify     = FLB_TRUE;
         instance->tls_ca_file    = NULL;
         instance->tls_crt_file   = NULL;


parser: fix assignment ambiguity (#913)

parser: fix assignment ambiguity (#913)

I doubt this is causing a problem, but in C, a=-1 is ambiguous
and produces a warning on 'indent' or 'lint'.

Signed-off-by: Don Bowman <1f1e67e5fdb25d2e5cd18ddc0fee425272daab56@agilicus.com>

--- src/flb_parser.c
+++ src/flb_parser.c
@@ -772,9 +772,10 @@
     else {
         pstr = str;
     }
+
     d = strtod(pstr, &p);
     if ((d == 0 && p == pstr) || !p) {
-        ret=-1;
+        ret = -1;
         goto free_and_return;
     }
     *frac = d;


fix for bug#915 fluidsynth.exe short option '-Q' not working when compiled with getopt (#916)

--- src/fluidsynth.c
+++ src/fluidsynth.c
@@ -351,7 +351,7 @@
     int audio_channels = 0;
     int dump = 0;
     int fast_render = 0;
-    static const char optchars[] = "a:C:c:dE:f:F:G:g:hijK:L:lm:nO:o:p:qR:r:sT:Vvz:";
+    static const char optchars[] = "a:C:c:dE:f:F:G:g:hijK:L:lm:nO:o:p:QqR:r:sT:Vvz:";
 #ifdef HAVE_LASH
     int connect_lash = 1;
     int enabled_lash = 0;		/* set to TRUE if lash gets enabled */


New stubs added; support for malloc (_sbrk).

--- lpc1114/src/syscalls.c
+++ lpc1114/src/syscalls.c
@@ -1,31 +1,52 @@
 /*
  * syscalls.c
  *
- * (c) 2015 Lixco Microsystems <lix@paulian.net>
+ * Created on: Jun 4, 2015 (LNP)
  *
- * Created on: Jun 4, 2015 (LNP)
+ * Copyright (c) 2011-2015 Lixco Microsystems <lix@paulian.net>
+ *
+ * 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.
  */

+/* A minimum implementation of the stubs required by newlib */

 #include <sys/types.h>
 #include <errno.h>
+#include <sys/stat.h>
 #include "FreeRTOS.h"
 #include "task.h"
 #include "olimex_p1114.h"

+/* initial heap size, it will be properly set after the first malloc() */
+int free_heap = 8192 - 1024;
+

 caddr_t _sbrk(int incr)
 {
-	extern char _pvHeapStart; /* see linker definition */
+	extern char _pvHeapStart; /* see linker definitions */
 	extern char _vStackTop;

 	static char* current_heap_end;
 	char* current_block_address;

 	if (current_heap_end == 0)
-	{
 		current_heap_end = &_pvHeapStart;
-	}

 	current_block_address = current_heap_end;

@@ -39,6 +60,7 @@
 	}

 	current_heap_end += incr;
+	free_heap = &_vStackTop - current_heap_end;

 	return (caddr_t) current_block_address;
 }
@@ -82,3 +104,33 @@
 	return n;
 }

+int __attribute__((weak))
+_lseek(int file __attribute__((unused)), int ptr __attribute__((unused)),
+    int dir __attribute__((unused)))
+{
+  errno = ENOSYS;
+  return -1;
+}
+
+int __attribute__((weak))
+_fstat(int fildes __attribute__((unused)),
+    struct stat* st __attribute__((unused)))
+{
+  errno = ENOSYS;
+  return -1;
+}
+
+int __attribute__((weak))
+_close(int fildes __attribute__((unused)))
+{
+  errno = ENOSYS;
+  return -1;
+}
+
+int __attribute__((weak))
+_isatty(int file __attribute__((unused)))
+{
+  errno = ENOSYS;
+  return 0;
+}
+


Enhance the performance application to handle small/large CIDs and MAX_CID.

--- app/performance/test_performance.c
+++ app/performance/test_performance.c
@@ -131,6 +131,8 @@
 static int tune_env_for_perfs(double *coef_nanosec);

 static int test_compression_perfs(char *filename,
+                                  const int use_large_cid,
+                                  const unsigned int max_contexts,
                                   double coef_nanosec,
                                   unsigned long *packet_count,
                                   unsigned long *overflows,
@@ -144,6 +146,8 @@
                                 unsigned long long *time_elapsed);

 static int test_decompression_perfs(char *filename,
+                                    const int use_large_cid,
+                                    const unsigned int max_contexts,
                                     double coef_nanosec,
                                     unsigned long *packet_count,
                                     unsigned long *overflows,
@@ -180,8 +184,11 @@
  */
 int main(int argc, char *argv[])
 {
+	int max_contexts = ROHC_SMALL_CID_MAX + 1;
+	char *cid_type = NULL;
 	char *test_type = NULL; /* the name of the test to perform */
 	char *filename = NULL; /* the name of the PCAP capture used as input */
+	bool use_large_cid;
 #if __i386__
 	unsigned long packet_count = 0;
 	unsigned long overflows = 0;
@@ -222,10 +229,22 @@
 			/* enable verbose mode */
 			is_verbose = 1;
 		}
+		else if(!strcmp(*argv, "--max-contexts"))
+		{
+			/* get the maximum number of contexts the test should use */
+			max_contexts = atoi(argv[1]);
+			argv++;
+			argc--;
+		}
 		else if(test_type == 0)
 		{
 			/* get the name of the test */
 			test_type = argv[0];
+		}
+		else if(cid_type == NULL)
+		{
+			/* get the type of CID to use within the ROHC library */
+			cid_type = argv[0];
 		}
 		else if(filename == NULL)
 		{
@@ -244,6 +263,41 @@
 	/* the test type and source filename are mandatory */
 	if(test_type == NULL || filename == NULL)
 	{
+		usage();
+		goto error;
+	}
+
+	/* check CID type */
+	if(!strcmp(cid_type, "smallcid"))
+	{
+		use_large_cid = false;
+
+		/* the maximum number of ROHC contexts should be valid */
+		if(max_contexts < 1 || max_contexts > (ROHC_SMALL_CID_MAX + 1))
+		{
+			fprintf(stderr, "the maximum number of ROHC contexts should be "
+			        "between 1 and %u\n\n", ROHC_SMALL_CID_MAX + 1);
+			usage();
+			goto error;
+		}
+	}
+	else if(!strcmp(cid_type, "largecid"))
+	{
+		use_large_cid = true;
+
+		/* the maximum number of ROHC contexts should be valid */
+		if(max_contexts < 1 || max_contexts > (ROHC_LARGE_CID_MAX + 1))
+		{
+			fprintf(stderr, "the maximum number of ROHC contexts should be "
+			        "between 1 and %u\n\n", ROHC_LARGE_CID_MAX + 1);
+			usage();
+			goto error;
+		}
+	}
+	else
+	{
+		fprintf(stderr, "invalid CID type '%s', only 'smallcid' and 'largecid' "
+		        "expected\n", cid_type);
 		usage();
 		goto error;
 	}
@@ -264,13 +318,15 @@
 	if(strcmp(test_type, "compression") == 0)
 	{
 		/* test ROHC compression with the packets from the capture */
-		ret = test_compression_perfs(filename, coef_nanosec,
+		ret = test_compression_perfs(filename, use_large_cid, max_contexts,
+		                             coef_nanosec,
 		                             &packet_count, &overflows, &time_elapsed);
 	}
 	else if(strcmp(test_type, "decompression") == 0)
 	{
 		/* test ROHC decompression with the packets from the capture */
-		ret = test_decompression_perfs(filename, coef_nanosec,
+		ret = test_decompression_perfs(filename, use_large_cid, max_contexts,
+		                               coef_nanosec,
 		                               &packet_count, &overflows, &time_elapsed);
 	}
 	else
@@ -321,15 +377,20 @@
 static void usage(void)
 {
 	fprintf(stderr,
-	        "ROHC performance test: test the performance of the ROHC library\n"
-	        "                       with a flow of IP packets\n\n"
-	        "usage: test_performance [-h|--help] [-v|--version] [de]compression flow\n"
-	        "  --version        print version information and exit\n"
-	        "  -v\n"
-	        "  --verbose        tell the application to be more verbose\n"
-	        "  --help           print application usage and exit\n"
-	        "  -h\n"
-	        "  flow  flow of Ethernet frames to (de)compress (PCAP format)\n");
+		"ROHC performance test: test the performance of the ROHC library\n"
+		"                       with a flow of IP packets\n"
+		"\n"
+		"usage: test_performance [-h|--help] [-v|--version] [de]compression (small|large)cid flow\n"
+		"\n"
+		"  --version               Print version information and exit\n"
+		"  -v\n"
+		"  --verbose               Tell the application to be more verbose\n"
+		"  --help                  Print application usage and exit\n"
+		"  -h\n"
+		"  --max-contexts NUM      The maximum number of ROHC contexts to\n"
+		"                          simultaneously use during the test\n"
+		"\n"
+		"  flow  flow of Ethernet frames to (de)compress (PCAP format)\n");
 }

@@ -350,6 +411,8 @@
 #if HAVE_SCHED_H == 1 && SCHED_SETSCHEDULER_PARAMS == 3
 	struct sched_param param;
 #endif
+	const unsigned int nr_tests = 3;
+	const unsigned long test_duration = 5;
 	unsigned long long tics1;
 	unsigned long long tics2;
 	unsigned int i;
@@ -398,16 +461,21 @@
 #endif

 	/* determine CPU tics to nanoseconds coefficient */
+	fprintf(stderr, "estimate CPU frequency (%u tests of %lu seconds)... ",
+	        nr_tests, test_duration);
+	fflush(stderr);
 	*coef_nanosec = 0;
-	for(i = 0; i < 10; i++)
+	for(i = 0; i < nr_tests; i++)
 	{
 		GET_CPU_TICS(tics1);
-		usleep(10e6);
+		usleep(test_duration * 1e6);
 		GET_CPU_TICS(tics2);
-		*coef_nanosec += 1.e9 / (tics2 - tics1);
-	}
-	*coef_nanosec /= 10;
-	fprintf(stderr, "CPU frequency estimated to %.6f GHz\n",
+		*coef_nanosec += (test_duration * 1.e9) / (tics2 - tics1);
+		fprintf(stderr, "%.6fGHz ", 1. / ((*coef_nanosec) / (i + 1)));
+		fflush(stderr);
+	}
+	*coef_nanosec /= nr_tests;
+	fprintf(stderr, "\nCPU frequency estimated to %.6f GHz\n",
 	        1. / (*coef_nanosec));

 	return 0;
@@ -424,6 +492,8 @@
  *        with a flow of IP packets
  *
  * @param filename      The name of the PCAP file that contains the IP packets
+ * @param use_large_cid Whether the compressor shall use large CIDs
+ * @param max_contexts  The maximum number of ROHC contexts to use
  * @param coef_nanosec  The coefficient to convert from CPU tics to nanoseconds
  * @param packet_count  OUT: the number of compressed packets, undefined if
  *                      compression failed
@@ -432,6 +502,8 @@
  * @return              0 in case of success, 1 otherwise
  */
 static int test_compression_perfs(char *filename,
+                                  const int use_large_cid,
+                                  const unsigned int max_contexts,
                                   double coef_nanosec,
                                   unsigned long *packet_count,
                                   unsigned long *overflows,
@@ -452,6 +524,8 @@
 	const unsigned int rtp_ports[NB_RTP_PORTS] =
 		{ 1234, 36780, 33238, 5020, 5002 };

+	assert(max_contexts > 0);
+
 	/* open the PCAP file that contains the stream */
 	handle = pcap_open_offline(filename, errbuf);
 	if(handle == NULL)
@@ -486,7 +560,7 @@
 	}

 	/* create ROHC compressor */
-	comp = rohc_alloc_compressor(ROHC_SMALL_CID_MAX, 0, 0, 0);
+	comp = rohc_alloc_compressor(max_contexts - 1, 0, 0, 0);
 	if(comp == NULL)
 	{
 		fprintf(stderr, "cannot create the ROHC compressor\n");
@@ -514,6 +588,7 @@
 	rohc_activate_profile(comp, ROHC_PROFILE_IP);
 	rohc_activate_profile(comp, ROHC_PROFILE_UDPLITE);
 	rohc_activate_profile(comp, ROHC_PROFILE_ESP);
+	rohc_c_set_large_cid(comp, use_large_cid);

 	/* reset list of RTP ports */
 	if(!rohc_comp_reset_rtp_ports(comp))
@@ -531,6 +606,8 @@
 			goto free_compresssor;
 		}
 	}
+
+	fflush(stderr);

 	/* for each packet in the dump */
 	*packet_count = 0;
@@ -541,6 +618,11 @@
 		unsigned long long packet_time_elapsed = 0;

 		(*packet_count)++;
+		if((*packet_count) != 0 && ((*packet_count) % 50000) == 0)
+		{
+			fprintf(stderr, "packet #%lu\n", *packet_count);
+			fflush(stderr);
+		}

 		/* compress the IP packet */
 		ret = time_compress_packet(comp, *packet_count,
@@ -694,6 +776,8 @@
  *        with a flow of IP packets
  *
  * @param filename      The name of the PCAP file that contains the ROHC packets
+ * @param use_large_cid Whether the decompressor shall use large CIDs
+ * @param max_contexts  The maximum number of ROHC contexts to use
  * @param coef_nanosec  The coefficient to convert from CPU tics to nanoseconds
  * @param packet_count  OUT: the number of decompressed packets, undefined if
  *                      decompression failed
@@ -702,6 +786,8 @@
  * @return              0 in case of success, 1 otherwise
  */
 static int test_decompression_perfs(char *filename,
+                                    const int use_large_cid,
+                                    const unsigned int max_contexts,
                                     double coef_nanosec,
                                     unsigned long *packet_count,
                                     unsigned long *overflows,
@@ -717,6 +803,8 @@
 	int is_failure = 1;
 	int ret;

+	assert(max_contexts > 0);
+
 	/* open the PCAP file that contains the stream */
 	handle = pcap_open_offline(filename, errbuf);
 	if(handle == NULL)
@@ -762,8 +850,42 @@
 	if(!rohc_decomp_set_traces_cb(decomp, print_rohc_traces))
 	{
 		fprintf(stderr, "cannot set trace callback for decompressor\n");
-		goto free_decompresssor;
-	}
+		goto free_decompressor;
+	}
+
+	/* set CID type and MAX_CID for decompressor 1 */
+	if(use_large_cid)
+	{
+		if(!rohc_decomp_set_cid_type(decomp, ROHC_LARGE_CID))
+		{
+			fprintf(stderr, "failed to set CID type to large CIDs for "
+			        "decompressor\n");
+			goto free_decompressor;
+		}
+		if(!rohc_decomp_set_max_cid(decomp, max_contexts - 1))
+		{
+			fprintf(stderr, "failed to set MAX_CID to %d for decompressor\n",
+			        ROHC_LARGE_CID_MAX);
+			goto free_decompressor;
+		}
+	}
+	else
+	{
+		if(!rohc_decomp_set_cid_type(decomp, ROHC_SMALL_CID))
+		{
+			fprintf(stderr, "failed to set CID type to small CIDs for "
+			        "decompressor\n");
+			goto free_decompressor;
+		}
+		if(!rohc_decomp_set_max_cid(decomp, max_contexts - 1))
+		{
+			fprintf(stderr, "failed to set MAX_CID to %d for decompressor\n",
+			        ROHC_SMALL_CID_MAX);
+			goto free_decompressor;
+		}
+	}
+
+	fflush(stderr);

 	/* for each packet in the dump */
 	*packet_count = 0;
@@ -774,6 +896,11 @@
 		unsigned long long packet_time_elapsed = 0;

 		(*packet_count)++;
+		if((*packet_count) != 0 && ((*packet_count) % 50000) == 0)
+		{
+			fprintf(stderr, "packet #%lu\n", *packet_count);
+			fflush(stderr);
+		}

 		/* decompress the ROHC packet */
 		ret = time_decompress_packet(decomp, *packet_count,
@@ -783,7 +910,7 @@
 		{
 			fprintf(stderr, "packet %lu: performance test failed\n",
 			        *packet_count);
-			goto free_decompresssor;
+			goto free_decompressor;
 		}

 		if((*time_elapsed) > (0xffffffff - packet_time_elapsed))
@@ -801,7 +928,7 @@
 	/* everything went fine */
 	is_failure = 0;

-free_decompresssor:
+free_decompressor:
 	rohc_free_decompressor(decomp);
 close_input:
 	pcap_close(handle);


server session BUGFIX call home session freeing corner cases

Refs #51

--- src/session_server.c
+++ src/session_server.c
@@ -2779,8 +2779,8 @@
     struct nc_ch_client *client;

     /* session created, initialize condition */
-    session->opts.server.ch_lock = malloc(sizeof *session->opts.server.ch_lock);
-    session->opts.server.ch_cond = malloc(sizeof *session->opts.server.ch_cond);
+    session->opts.server.ch_lock = calloc(1, sizeof *session->opts.server.ch_lock);
+    session->opts.server.ch_cond = calloc(1, sizeof *session->opts.server.ch_cond);
     if (!session->opts.server.ch_lock || !session->opts.server.ch_cond) {
         ERRMEM;
         nc_session_free(session, NULL);
@@ -2843,13 +2843,13 @@

     } while (session->status == NC_STATUS_RUNNING);

+    /* CH UNLOCK */
+    pthread_mutex_unlock(session->opts.server.ch_lock);
+
     if (session->status == NC_STATUS_CLOSING) {
         /* signal to nc_session_free() that we registered session being freed, otherwise it matters not */
         session->flags &= ~NC_SESSION_CALLHOME;
     }
-
-    /* CH UNLOCK */
-    pthread_mutex_unlock(session->opts.server.ch_lock);

     return ret;
 }


Apply clang-format on any

Apply clang-format on any

--- src/shogun/lib/any.h
+++ src/shogun/lib/any.h
@@ -35,8 +35,8 @@
 #ifndef _ANY_H_
 #define _ANY_H_

+#include <stdexcept>
 #include <string.h>
-#include <stdexcept>
 #include <typeinfo>
 #ifdef HAVE_CXA_DEMANGLE
 #include <cxxabi.h>
@@ -44,419 +44,429 @@

 namespace shogun
 {
-    /** Converts compiler-dependent name of class to
-     * something human readable.
-     * @return human readable name of class
-     */
-    template <typename T>
-    std::string demangledType()
-    {
+	/** Converts compiler-dependent name of class to
+	 * something human readable.
+	 * @return human readable name of class
+	 */
+	template <typename T>
+	std::string demangledType()
+	{
 #ifdef HAVE_CXA_DEMANGLE
 		size_t length;
 		int status;
-		char* demangled = abi::__cxa_demangle(typeid(T).name(), nullptr, &length, &status);
+		char* demangled =
+		    abi::__cxa_demangle(typeid(T).name(), nullptr, &length, &status);
 		std::string demangled_string(demangled);
 		free(demangled);
 #else
 		std::string demangled_string(typeid(T).name());
 #endif
-        return demangled_string;
-    }
-
-    enum class PolicyType {
-        OWNING,
-        NON_OWNING
-    };
-
-    /** @brief An interface for a policy to store a value.
-     * Value can be any data like primitive data-types, shogun objects, etc.
-     * Policy defines how to handle this data. It works with a
-     * provided memory region and is able to set value, clear it
-     * and return the type-name as string.
-     */
-    class BaseAnyPolicy
-    {
-    public:
-        /** Puts provided value pointed by v (untyped to be generic) to storage.
-         * @param storage pointer to a pointer to storage
-         * @param v pointer to value
-         */
-        virtual void set(void** storage, const void* v) const = 0;
-
-        /** Clears storage.
-         * @param storage pointer to a pointer to storage
-         */
-        virtual void clear(void** storage) const = 0;
-
-        /** Returns type-name as string.
-         * @return name of type class
-         */
-        virtual std::string type() const = 0;
-
-        /** Returns type info
-         * @return type info of value's type
-         */
-        virtual const std::type_info& type_info() const = 0;
-
-        /** Compares type.
-         * @param ti type information
-         * @return true if type matches
-         */
-        virtual bool matches(const std::type_info& ti) const = 0;
-
-        /** Compares two storages.
-         * @param storage pointer to a pointer to storage
-         * @param other_storage pointer to a pointer to another storage
-         * @return true if both storages have same value
-         */
-        virtual bool equals(void** storage, void** other_storage) const = 0;
-
-        /** Returns the name of policy.
-         * @return name of policy
-         */
-        virtual std::string policy_name() const = 0;
-
-        /** Returns the type of policy.
-         * @return type of policy
-         */
-        virtual PolicyType policy_type() const = 0;
-    };
-
-    /** @brief This is one concrete implementation of policy that
-     * uses void pointers to store values.
-     */
-    template <typename T>
-    class PointerValueAnyPolicy : public BaseAnyPolicy
-    {
-    public:
-        /** Puts provided value pointed by v (untyped to be generic) to storage.
-         * @param storage pointer to a pointer to storage
-         * @param v pointer to value
-         */
-        virtual void set(void** storage, const void* v) const
-        {
-            *(storage) = new T(*reinterpret_cast<T const*>(v));
-        }
-
-        /** Clears storage.
-         * @param storage pointer to a pointer to storage
-         */
-        virtual void clear(void** storage) const
-        {
-            delete reinterpret_cast<T*>(*storage);
-        }
-
-        /** Returns type-name as string.
-         * @return name of type class
-         */
-        virtual std::string type() const
-        {
-            return demangledType<T>();
-        }
-
-        /** Returns type info
-         * @return type info of value's type
-         */
-        virtual const std::type_info& type_info() const
-        {
-            return typeid(T);
-        }
-
-        /** Compares type.
-         * @param ti type information
-         * @return true if type matches
-         */
-        virtual bool matches(const std::type_info& ti) const
-        {
-            return typeid(T) == ti;
-        }
-
-        /** Compares two storages.
-         * @param storage pointer to a pointer to storage
-         * @param other_storage pointer to a pointer to another storage
-         * @return true if both storages have same value
-         */
-        bool equals(void** storage, void** other_storage) const
-        {
-            T typed_storage = *(reinterpret_cast<T*>(*storage));
-            T typed_other_storage = *(reinterpret_cast<T*>(*other_storage));
-            return typed_storage == typed_other_storage;
-        }
-
-        virtual std::string policy_name() const {
-            return "owning";
-        }
-
-        virtual PolicyType policy_type() const {
-            return PolicyType::OWNING;
-        }
-    };
-
-    template <typename T>
-    class NonOwningAnyPolicy : public BaseAnyPolicy
-    {
-    public:
-        /** Puts provided value pointed by v (untyped to be generic) to storage.
-         * @param storage pointer to a pointer to storage
-         * @param v pointer to value
-         */
-        virtual void set(void** storage, const void* v) const
-        {
-            *(storage) = const_cast<void*>(v);
-        }
-
-        /** Clears storage.
-         * @param storage pointer to a pointer to storage
-         */
-        virtual void clear(void** storage) const
-        {
-        }
-
-        /** Returns type-name as string.
-         * @return name of type class
-         */
-        virtual std::string type() const
-        {
-            return demangledType<T>();
-        }
-
-        /** Returns type info
-         * @return type info of value's type
-         */
-        virtual const std::type_info& type_info() const
-        {
-            return typeid(T);
-        }
-
-        /** Compares type.
-         * @param ti type information
-         * @return true if type matches
-         */
-        virtual bool matches(const std::type_info& ti) const
-        {
-            return typeid(T) == ti;
-        }
-
-        /** Compares two storages.
-         * @param storage pointer to a pointer to storage
-         * @param other_storage pointer to a pointer to another storage
-         * @return true if both storages have same value
-         */
-        bool equals(void** storage, void** other_storage) const
-        {
-            T typed_storage = *(reinterpret_cast<T*>(*storage));
-            T typed_other_storage = *(reinterpret_cast<T*>(*other_storage));
-            return typed_storage == typed_other_storage;
-        }
-
-        virtual std::string policy_name() const {
-            return "non owning";
-        }
-
-        virtual PolicyType policy_type() const {
-            return PolicyType::NON_OWNING;
-        }
-    };
-
-    template <typename T>
-    static BaseAnyPolicy* owning_policy()
-    {
-        typedef PointerValueAnyPolicy<T> Policy;
-        static Policy policy;
-        return &policy;
-    }
-
-    template <typename T>
-    static BaseAnyPolicy* non_owning_policy()
-    {
-        typedef NonOwningAnyPolicy<T> Policy;
-        static Policy policy;
-        return &policy;
-    }
-
-    /** @brief Allows to store objects of arbitrary types
-     * by using a BaseAnyPolicy and provides a type agnostic API.
-     * See its usage in CSGObject::Self, CSGObject::set(), CSGObject::get()
-     * and CSGObject::has().
-     * .
-     */
-    class Any
-    {
-    public:
-        /** Used to denote an empty Any object */
-        struct Empty;
-
-        /** Empty value constructor */
-        Any() : Any(owning_policy<Empty>(), nullptr)
-        {
-        }
-
-        /** Constructor to copy value */
-        template <typename T>
-        explicit Any(const T& v) : Any(owning_policy<T>(), nullptr)
-        {
-            policy->set(&storage, &v);
-        }
-
-        /** Base constructor */
-        Any(BaseAnyPolicy* the_policy, void* the_storage) : policy(the_policy), storage(the_storage)
-        {
-        }
-
-        /** Copy constructor */
-        Any(const Any& other) : Any(other.policy, nullptr)
-        {
-            assert_same_policy_type(other.policy);
-            policy->set(&storage, other.storage);
-        }
-
-        /** Assignment operator
-         * @param other another Any object
-         * @return Any object
-         */
-        Any& operator=(const Any& other)
-        {
-            assert_same_policy_type(other.policy);
-            policy->clear(&storage);
-            policy = other.policy;
-            policy->set(&storage, other.storage);
-            return *(this);
-        }
-
-        /** Equality operator
-         * @param lhs Any object on left hand side
-         * @param rhs Any object on right hand side
-         * @return true if both are equal
-         */
-        friend inline bool operator==(const Any& lhs, const Any& rhs);
-
-        /** Inequality operator
-         * @param lhs Any object on left hand side
-         * @param rhs Any object on right hand side
-         * @return false if both are equal
-         */
-        friend inline bool operator!=(const Any& lhs, const Any& rhs);
-
-        /** Destructor */
-        ~Any()
-        {
-            policy->clear(&storage);
-        }
-
-        /** Casts hidden value to provided type, fails otherwise.
-         * @return type-casted value
-         */
-        template <typename T>
-        T& as() const
-        {
-            if (same_type<T>())
-            {
-                return *(reinterpret_cast<T*>(storage));
-            }
-            else
-            {
-                throw std::logic_error("Bad cast to " + demangledType<T>() +
-                        " but the type is " + policy->type());
-            }
-        }
-
-        /** @return true if type is same. */
-        template <typename T>
-        inline bool same_type() const
-        {
-            return (policy == owning_policy<T>()) || (policy == non_owning_policy<T>()) || same_type_fallback<T>();
-        }
-
-        /** @return true if type-id is same. */
-        template <typename T>
-        bool same_type_fallback() const
-        {
-            return policy->matches(typeid(T));
-        }
-
-        /** @return true if Any object is empty. */
-        bool empty() const
-        {
-            return same_type<Empty>();
-        }
-
-        const std::type_info& type_info() const
-        {
-            return policy->type_info();
-        }
-
-    private:
-
-        void assert_same_policy_type(BaseAnyPolicy* other_policy) {
-            if (policy->policy_type() != other_policy->policy_type()) {
-                throw std::logic_error("The policies are different: " +
-                                       policy->policy_name() + " and " +
-                                       other_policy->policy_name());
-            }
-        }
-
-    private:
-        BaseAnyPolicy* policy;
-        void* storage;
-    };
-
-    inline bool operator==(const Any& lhs, const Any& rhs)
-    {
-        void* lhs_storage = lhs.storage;
-        void* rhs_storage = rhs.storage;
-        return lhs.policy == rhs.policy &&
-            lhs.policy->equals(&lhs_storage, &rhs_storage);
-    }
-
-    inline bool operator!=(const Any& lhs, const Any& rhs)
-    {
-        return !(lhs == rhs);
-    }
-
-    /** Used to denote an empty Any object */
-    struct Any::Empty
-    {
-        /** Equality operator */
-        bool operator==(const Empty& other) const
-        {
-            return true;
-        }
-    };
-
-    /** Erases value type i.e. converts it to Any
-     * For input object of any type, it returns an Any object
-     * which stores the input object's raw value. It saves the type
-     * information internally to be recalled later by using recall_type().
-     *
-     * @param v value
-     * @return Any object with the input value
-     */
-    template <typename T>
-    inline Any erase_type(const T& v)
-    {
-        return Any(v);
-    }
-
-    template <typename T>
-    inline Any erase_type_non_owning(T* v)
-    {
-        return Any(non_owning_policy<T>(), v);
-    }
-
-    /** Tries to recall Any type, fails when type is wrong.
-     * Any stores type information of an object internally in a BaseAnyPolicy.
-     * This function returns type-casted value if the internal type information
-     * matches with the provided typename, otherwise throws std::logic_error.
-     *
-     * @param any object of Any
-     * @return type-casted value
-     */
-    template <typename T>
-    inline T recall_type(const Any& any)
-    {
-        return any.as<T>();
-    }
-
+		return demangled_string;
+	}
+
+	enum class PolicyType
+	{
+		OWNING,
+		NON_OWNING
+	};
+
+	/** @brief An interface for a policy to store a value.
+	 * Value can be any data like primitive data-types, shogun objects, etc.
+	 * Policy defines how to handle this data. It works with a
+	 * provided memory region and is able to set value, clear it
+	 * and return the type-name as string.
+	 */
+	class BaseAnyPolicy
+	{
+	public:
+		/** Puts provided value pointed by v (untyped to be generic) to storage.
+		 * @param storage pointer to a pointer to storage
+		 * @param v pointer to value
+		 */
+		virtual void set(void** storage, const void* v) const = 0;
+
+		/** Clears storage.
+		 * @param storage pointer to a pointer to storage
+		 */
+		virtual void clear(void** storage) const = 0;
+
+		/** Returns type-name as string.
+		 * @return name of type class
+		 */
+		virtual std::string type() const = 0;
+
+		/** Returns type info
+		 * @return type info of value's type
+		 */
+		virtual const std::type_info& type_info() const = 0;
+
+		/** Compares type.
+		 * @param ti type information
+		 * @return true if type matches
+		 */
+		virtual bool matches(const std::type_info& ti) const = 0;
+
+		/** Compares two storages.
+		 * @param storage pointer to a pointer to storage
+		 * @param other_storage pointer to a pointer to another storage
+		 * @return true if both storages have same value
+		 */
+		virtual bool equals(void** storage, void** other_storage) const = 0;
+
+		/** Returns the name of policy.
+		 * @return name of policy
+		 */
+		virtual std::string policy_name() const = 0;
+
+		/** Returns the type of policy.
+		 * @return type of policy
+		 */
+		virtual PolicyType policy_type() const = 0;
+	};
+
+	/** @brief This is one concrete implementation of policy that
+	 * uses void pointers to store values.
+	 */
+	template <typename T>
+	class PointerValueAnyPolicy : public BaseAnyPolicy
+	{
+	public:
+		/** Puts provided value pointed by v (untyped to be generic) to storage.
+		 * @param storage pointer to a pointer to storage
+		 * @param v pointer to value
+		 */
+		virtual void set(void** storage, const void* v) const
+		{
+			*(storage) = new T(*reinterpret_cast<T const*>(v));
+		}
+
+		/** Clears storage.
+		 * @param storage pointer to a pointer to storage
+		 */
+		virtual void clear(void** storage) const
+		{
+			delete reinterpret_cast<T*>(*storage);
+		}
+
+		/** Returns type-name as string.
+		 * @return name of type class
+		 */
+		virtual std::string type() const
+		{
+			return demangledType<T>();
+		}
+
+		/** Returns type info
+		 * @return type info of value's type
+		 */
+		virtual const std::type_info& type_info() const
+		{
+			return typeid(T);
+		}
+
+		/** Compares type.
+		 * @param ti type information
+		 * @return true if type matches
+		 */
+		virtual bool matches(const std::type_info& ti) const
+		{
+			return typeid(T) == ti;
+		}
+
+		/** Compares two storages.
+		 * @param storage pointer to a pointer to storage
+		 * @param other_storage pointer to a pointer to another storage
+		 * @return true if both storages have same value
+		 */
+		bool equals(void** storage, void** other_storage) const
+		{
+			T typed_storage = *(reinterpret_cast<T*>(*storage));
+			T typed_other_storage = *(reinterpret_cast<T*>(*other_storage));
+			return typed_storage == typed_other_storage;
+		}
+
+		virtual std::string policy_name() const
+		{
+			return "owning";
+		}
+
+		virtual PolicyType policy_type() const
+		{
+			return PolicyType::OWNING;
+		}
+	};
+
+	template <typename T>
+	class NonOwningAnyPolicy : public BaseAnyPolicy
+	{
+	public:
+		/** Puts provided value pointed by v (untyped to be generic) to storage.
+		 * @param storage pointer to a pointer to storage
+		 * @param v pointer to value
+		 */
+		virtual void set(void** storage, const void* v) const
+		{
+			*(storage) = const_cast<void*>(v);
+		}
+
+		/** Clears storage.
+		 * @param storage pointer to a pointer to storage
+		 */
+		virtual void clear(void** storage) const
+		{
+		}
+
+		/** Returns type-name as string.
+		 * @return name of type class
+		 */
+		virtual std::string type() const
+		{
+			return demangledType<T>();
+		}
+
+		/** Returns type info
+		 * @return type info of value's type
+		 */
+		virtual const std::type_info& type_info() const
+		{
+			return typeid(T);
+		}
+
+		/** Compares type.
+		 * @param ti type information
+		 * @return true if type matches
+		 */
+		virtual bool matches(const std::type_info& ti) const
+		{
+			return typeid(T) == ti;
+		}
+
+		/** Compares two storages.
+		 * @param storage pointer to a pointer to storage
+		 * @param other_storage pointer to a pointer to another storage
+		 * @return true if both storages have same value
+		 */
+		bool equals(void** storage, void** other_storage) const
+		{
+			T typed_storage = *(reinterpret_cast<T*>(*storage));
+			T typed_other_storage = *(reinterpret_cast<T*>(*other_storage));
+			return typed_storage == typed_other_storage;
+		}
+
+		virtual std::string policy_name() const
+		{
+			return "non owning";
+		}
+
+		virtual PolicyType policy_type() const
+		{
+			return PolicyType::NON_OWNING;
+		}
+	};
+
+	template <typename T>
+	static BaseAnyPolicy* owning_policy()
+	{
+		typedef PointerValueAnyPolicy<T> Policy;
+		static Policy policy;
+		return &policy;
+	}
+
+	template <typename T>
+	static BaseAnyPolicy* non_owning_policy()
+	{
+		typedef NonOwningAnyPolicy<T> Policy;
+		static Policy policy;
+		return &policy;
+	}
+
+	/** @brief Allows to store objects of arbitrary types
+	 * by using a BaseAnyPolicy and provides a type agnostic API.
+	 * See its usage in CSGObject::Self, CSGObject::set(), CSGObject::get()
+	 * and CSGObject::has().
+	 * .
+	 */
+	class Any
+	{
+	public:
+		/** Used to denote an empty Any object */
+		struct Empty;
+
+		/** Empty value constructor */
+		Any() : Any(owning_policy<Empty>(), nullptr)
+		{
+		}
+
+		/** Constructor to copy value */
+		template <typename T>
+		explicit Any(const T& v) : Any(owning_policy<T>(), nullptr)
+		{
+			policy->set(&storage, &v);
+		}
+
+		/** Base constructor */
+		Any(BaseAnyPolicy* the_policy, void* the_storage)
+		    : policy(the_policy), storage(the_storage)
+		{
+		}
+
+		/** Copy constructor */
+		Any(const Any& other) : Any(other.policy, nullptr)
+		{
+			assert_same_policy_type(other.policy);
+			policy->set(&storage, other.storage);
+		}
+
+		/** Assignment operator
+		 * @param other another Any object
+		 * @return Any object
+		 */
+		Any& operator=(const Any& other)
+		{
+			assert_same_policy_type(other.policy);
+			policy->clear(&storage);
+			policy = other.policy;
+			policy->set(&storage, other.storage);
+			return *(this);
+		}
+
+		/** Equality operator
+		 * @param lhs Any object on left hand side
+		 * @param rhs Any object on right hand side
+		 * @return true if both are equal
+		 */
+		friend inline bool operator==(const Any& lhs, const Any& rhs);
+
+		/** Inequality operator
+		 * @param lhs Any object on left hand side
+		 * @param rhs Any object on right hand side
+		 * @return false if both are equal
+		 */
+		friend inline bool operator!=(const Any& lhs, const Any& rhs);
+
+		/** Destructor */
+		~Any()
+		{
+			policy->clear(&storage);
+		}
+
+		/** Casts hidden value to provided type, fails otherwise.
+		 * @return type-casted value
+		 */
+		template <typename T>
+		T& as() const
+		{
+			if (same_type<T>())
+			{
+				return *(reinterpret_cast<T*>(storage));
+			}
+			else
+			{
+				throw std::logic_error(
+				    "Bad cast to " + demangledType<T>() + " but the type is " +
+				    policy->type());
+			}
+		}
+
+		/** @return true if type is same. */
+		template <typename T>
+		inline bool same_type() const
+		{
+			return (policy == owning_policy<T>()) ||
+			       (policy == non_owning_policy<T>()) ||
+			       same_type_fallback<T>();
+		}
+
+		/** @return true if type-id is same. */
+		template <typename T>
+		bool same_type_fallback() const
+		{
+			return policy->matches(typeid(T));
+		}
+
+		/** @return true if Any object is empty. */
+		bool empty() const
+		{
+			return same_type<Empty>();
+		}
+
+		const std::type_info& type_info() const
+		{
+			return policy->type_info();
+		}
+
+	private:
+		void assert_same_policy_type(BaseAnyPolicy* other_policy)
+		{
+			if (policy->policy_type() != other_policy->policy_type())
+			{
+				throw std::logic_error(
+				    "The policies are different: " + policy->policy_name() +
+				    " and " + other_policy->policy_name());
+			}
+		}
+
+	private:
+		BaseAnyPolicy* policy;
+		void* storage;
+	};
+
+	inline bool operator==(const Any& lhs, const Any& rhs)
+	{
+		void* lhs_storage = lhs.storage;
+		void* rhs_storage = rhs.storage;
+		return lhs.policy == rhs.policy &&
+		       lhs.policy->equals(&lhs_storage, &rhs_storage);
+	}
+
+	inline bool operator!=(const Any& lhs, const Any& rhs)
+	{
+		return !(lhs == rhs);
+	}
+
+	/** Used to denote an empty Any object */
+	struct Any::Empty
+	{
+		/** Equality operator */
+		bool operator==(const Empty& other) const
+		{
+			return true;
+		}
+	};
+
+	/** Erases value type i.e. converts it to Any
+	 * For input object of any type, it returns an Any object
+	 * which stores the input object's raw value. It saves the type
+	 * information internally to be recalled later by using recall_type().
+	 *
+	 * @param v value
+	 * @return Any object with the input value
+	 */
+	template <typename T>
+	inline Any erase_type(const T& v)
+	{
+		return Any(v);
+	}
+
+	template <typename T>
+	inline Any erase_type_non_owning(T* v)
+	{
+		return Any(non_owning_policy<T>(), v);
+	}
+
+	/** Tries to recall Any type, fails when type is wrong.
+	 * Any stores type information of an object internally in a BaseAnyPolicy.
+	 * This function returns type-casted value if the internal type information
+	 * matches with the provided typename, otherwise throws std::logic_error.
+	 *
+	 * @param any object of Any
+	 * @return type-casted value
+	 */
+	template <typename T>
+	inline T recall_type(const Any& any)
+	{
+		return any.as<T>();
+	}
 }

-#endif  //_ANY_H_
+#endif //_ANY_H_