text:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/io.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/pm_runtime.h>
#include <linux/err.h>
#include <linux/delay.h>
#include <linux/usb/musb-omap.h>
#include <linux/usb/omap_control_usb.h>

#include "musb_core.h"
#include "omap2430.h"

struct omap2430_glue {
	struct device		*dev;
	struct platform_device	*musb;
	enum omap_musb_vbus_id_status status;
	struct work_struct	omap_musb_mailbox_work;
	struct device		*control_otghs;
};
#define glue_to_musb(g)		platform_get_drvdata(g->musb)

static struct omap2430_glue	*_glue;

static struct timer_list musb_idle_timer;

static void musb_do_idle(unsigned long _musb)
{
	struct musb	*musb = (void *)_musb;
	unsigned long	flags;
	u8	power;
	u8	devctl;

	spin_lock_irqsave(&musb->lock, flags);

	switch (musb->xceiv->state) {
	case OTG_STATE_A_WAIT_BCON:

		devctl = musb_readb(musb->mregs, MUSB_DEVCTL);
		if (devctl & MUSB_DEVCTL_BDEVICE) {
			musb->xceiv->state = OTG_STATE_B_IDLE;
			MUSB_DEV_MODE(musb);
		} else {
			musb->xceiv->state = OTG_STATE_A_IDLE;
			MUSB_HST_MODE(musb);
		}
		break;
	case OTG_STATE_A_SUSPEND:
		/* finish RESUME signaling? */
		if (musb->port1_status & MUSB_PORT_STAT_RESUME) {
			power = musb_readb(musb->mregs, MUSB_POWER);
			power &= ~MUSB_POWER_RESUME;
			dev_dbg(musb->controller, "root port resume stopped, power %02x\n", power);
			musb_writeb(musb->mregs, MUSB_POWER, power);
			musb->is_active = 1;
			musb->port1_status &= ~(USB_PORT_STAT_SUSPEND
						| MUSB_PORT_STAT_RESUME);
			musb->port1_status |= USB_PORT_STAT_C_SUSPEND << 16;
			usb_hcd_poll_rh_status(musb_to_hcd(musb));
			/* NOTE: it might really be A_WAIT_BCON ... */
			musb->xceiv->state = OTG_STATE_A_HOST;
		}
		break;
	case OTG_STATE_A_HOST:
		devctl = musb_readb(musb->mregs, MUSB_DEVCTL);
		if (devctl &  MUSB_DEVCTL_BDEVICE)
			musb->xceiv->state = OTG_STATE_B_IDLE;
		else
			musb->xceiv->state = OTG_STATE_A_WAIT_BCON;
	default:
		break;
	}
	spin_unlock_irqrestore(&musb->lock, flags);
}

static void omap2430_musb_try_idle(struct musb *musb, unsigned long timeout)
{
	unsigned long		default_timeout = jiffies + msecs_to_jiffies(3);
	static unsigned long	last_timer;

	if (timeout == 0)
		timeout = default_timeout;

	/* Never idle if active, or when VBUS timeout is not set as host */
	if (musb->is_active || ((musb->a_wait_bcon == 0)
			&& (musb->xceiv->state == OTG_STATE_A_WAIT_BCON))) {
		dev_dbg(musb->controller, "%s active, deleting timer\n",
			usb_otg_state_string(musb->xceiv->state));
		del_timer(&musb_idle_timer);
		last_timer = jiffies;
		return;
	}

	if (time_after(last_timer, timeout)) {
		if (!timer_pending(&musb_idle_timer))
			last_timer = timeout;
		else {
			dev_dbg(musb->controller, "Longer idle timer already pending, ignoring\n");
			return;
		}
	}
	last_timer = timeout;

	dev_dbg(musb->controller, "%s inactive, for idle timer for %lu ms\n",
		usb_otg_state_string(musb->xceiv->state),
		(unsigned long)jiffies_to_msecs(timeout - jiffies));
	mod_timer(&musb_idle_timer, timeout);
}

static void omap2430_musb_set_vbus(struct musb *musb, int is_on)
{
	struct usb_otg	*otg = musb->xceiv->otg;
	u8		devctl;
	unsigned long timeout = jiffies + msecs_to_jiffies(1000);
	/* HDRC controls CPEN, but beware current surges during device
	 * connect.  They can trigger transient overcurrent conditions
	 * that must be ignored.
	 */

	devctl = musb_readb(musb->mregs, MUSB_DEVCTL);

	if (is_on) {
		if (musb->xceiv->state == OTG_STATE_A_IDLE) {
			int loops = 100;
			/* start the session */
			devctl |= MUSB_DEVCTL_SESSION;
			musb_writeb(musb->mregs, MUSB_DEVCTL, devctl);
			/*
			 * Wait for the musb to set as A device to enable the
			 * VBUS
			 */
			while (musb_readb(musb->mregs, MUSB_DEVCTL) & 0x80) {

				mdelay(5);
				cpu_relax();

				if (time_after(jiffies, timeout)
				    || loops-- <= 0) {
					dev_err(musb->controller,
					"configured as A device timeout");
					break;
				}
			}

			otg_set_vbus(otg, 1);
		} else {
			musb->is_active = 1;
			otg->default_a = 1;
			musb->xceiv->state = OTG_STATE_A_WAIT_VRISE;
			devctl |= MUSB_DEVCTL_SESSION;
			MUSB_HST_MODE(musb);
		}
	} else {
		musb->is_active = 0;

		/* NOTE:  we're skipping A_WAIT_VFALL -> A_IDLE and
		 * jumping right to B_IDLE...
		 */

		otg->default_a = 0;
		musb->xceiv->state = OTG_STATE_B_IDLE;
		devctl &= ~MUSB_DEVCTL_SESSION;

		MUSB_DEV_MODE(musb);
	}
	musb_writeb(musb->mregs, MUSB_DEVCTL, devctl);

	dev_dbg(musb->controller, "VBUS %s, devctl %02x "
		/* otg %3x conf %08x prcm %08x */ "\n",
		usb_otg_state_string(musb->xceiv->state),
		musb_readb(musb->mregs, MUSB_DEVCTL));
}

static int omap2430_musb_set_mode(struct musb *musb, u8 musb_mode)
{
	u8	devctl = musb_readb(musb->mregs, MUSB_DEVCTL);

	devctl |= MUSB_DEVCTL_SESSION;
	musb_writeb(musb->mregs, MUSB_DEVCTL, devctl);

	return 0;
}

static inline void omap2430_low_level_exit(struct musb *musb)
{
	u32 l;

	/* in any role */
	l = musb_readl(musb->mregs, OTG_FORCESTDBY);
	l |= ENABLEFORCE;	/* enable MSTANDBY */
	musb_writel(musb->mregs, OTG_FORCESTDBY, l);
}

static inline void omap2430_low_level_init(struct musb *musb)
{
	u32 l;

	l = musb_readl(musb->mregs, OTG_FORCESTDBY);
	l &= ~ENABLEFORCE;	/* disable MSTANDBY */
	musb_writel(musb->mregs, OTG_FORCESTDBY, l);
}

void omap_musb_mailbox(enum omap_musb_vbus_id_status status)
{
	struct omap2430_glue	*glue = _glue;

	if (!glue) {
		pr_err("%s: musb core is not yet initialized\n", __func__);
		return;
	}
	glue->status = status;

	if (!glue_to_musb(glue)) {
		pr_err("%s: musb core is not yet ready\n", __func__);
		return;
	}

	schedule_work(&glue->omap_musb_mailbox_work);
}
EXPORT_SYMBOL_GPL(omap_musb_mailbox);

static void omap_musb_set_mailbox(struct omap2430_glue *glue)
{
	struct musb *musb = glue_to_musb(glue);
	struct device *dev = musb->controller;
	struct musb_hdrc_platform_data *pdata = dev->platform_data;
	struct omap_musb_board_data *data = pdata->board_data;
	struct usb_otg *otg = musb->xceiv->otg;

	switch (glue->status) {
	case OMAP_MUSB_ID_GROUND:
		dev_dbg(dev, "ID GND\n");

		otg->default_a = true;
		musb->xceiv->state = OTG_STATE_A_IDLE;
		musb->xceiv->last_event = USB_EVENT_ID;
		if (musb->gadget_driver) {
			pm_runtime_get_sync(dev);
			omap_control_usb_set_mode(glue->control_otghs,
				USB_MODE_HOST);
			omap2430_musb_set_vbus(musb, 1);
		}
		break;

	case OMAP_MUSB_VBUS_VALID:
		dev_dbg(dev, "VBUS Connect\n");

		otg->default_a = false;
		musb->xceiv->state = OTG_STATE_B_IDLE;
		musb->xceiv->last_event = USB_EVENT_VBUS;
		if (musb->gadget_driver)
			pm_runtime_get_sync(dev);
		omap_control_usb_set_mode(glue->control_otghs, USB_MODE_DEVICE);
		break;

	case OMAP_MUSB_ID_FLOAT:
	case OMAP_MUSB_VBUS_OFF:
		dev_dbg(dev, "VBUS Disconnect\n");

		musb->xceiv->last_event = USB_EVENT_NONE;
		if (musb->gadget_driver) {
			omap2430_musb_set_vbus(musb, 0);
			pm_runtime_mark_last_busy(dev);
			pm_runtime_put_autosuspend(dev);
		}

		if (data->interface_type == MUSB_INTERFACE_UTMI)
			otg_set_vbus(musb->xceiv->otg, 0);

		omap_control_usb_set_mode(glue->control_otghs,
			USB_MODE_DISCONNECT);
		break;
	default:
		dev_dbg(dev, "ID float\n");
	}
}

static void omap_musb_mailbox_work(struct work_struct *mailbox_work)
{
	struct omap2430_glue *glue = container_of(mailbox_work,
				struct omap2430_glue, omap_musb_mailbox_work);
	omap_musb_set_mailbox(glue);
}

static irqreturn_t omap2430_musb_interrupt(int irq, void *__hci)
{
	unsigned long   flags;
	irqreturn_t     retval = IRQ_NONE;
	struct musb     *musb = __hci;

	spin_lock_irqsave(&musb->lock, flags);

	musb->int_usb = musb_readb(musb->mregs, MUSB_INTRUSB);
	musb->int_tx = musb_readw(musb->mregs, MUSB_INTRTX);
	musb->int_rx = musb_readw(musb->mregs, MUSB_INTRRX);

	if (musb->int_usb || musb->int_tx || musb->int_rx)
		retval = musb_interrupt(musb);

	spin_unlock_irqrestore(&musb->lock, flags);

	return retval;
}

static int omap2430_musb_init(struct musb *musb)
{
	u32 l;
	int status = 0;
	struct device *dev = musb->controller;
	struct omap2430_glue *glue = dev_get_drvdata(dev->parent);
	struct musb_hdrc_platform_data *plat = dev->platform_data;
	struct omap_musb_board_data *data = plat->board_data;

	/* We require some kind of external transceiver, hooked
	 * up through ULPI.  TWL4030-family PMICs include one,
	 * which needs a driver, drivers aren't always needed.
	 */
	if (dev->parent->of_node)
		musb->xceiv = devm_usb_get_phy_by_phandle(dev->parent,
		    "usb-phy", 0);
	else
		musb->xceiv = devm_usb_get_phy_dev(dev, 0);

	if (IS_ERR(musb->xceiv)) {
		status = PTR_ERR(musb->xceiv);

		if (status == -ENXIO)
			return status;

		pr_err("HS USB OTG: no transceiver configured\n");
		return -EPROBE_DEFER;
	}

	musb->isr = omap2430_musb_interrupt;

	status = pm_runtime_get_sync(dev);
	if (status < 0) {
		dev_err(dev, "pm_runtime_get_sync FAILED %d\n", status);
		goto err1;
	}

	l = musb_readl(musb->mregs, OTG_INTERFSEL);

	if (data->interface_type == MUSB_INTERFACE_UTMI) {
		/* OMAP4 uses Internal PHY GS70 which uses UTMI interface */
		l &= ~ULPI_12PIN;       /* Disable ULPI */
		l |= UTMI_8BIT;         /* Enable UTMI  */
	} else {
		l |= ULPI_12PIN;
	}

	musb_writel(musb->mregs, OTG_INTERFSEL, l);

	pr_debug("HS USB OTG: revision 0x%x, sysconfig 0x%02x, "
			"sysstatus 0x%x, intrfsel 0x%x, simenable  0x%x\n",
			musb_readl(musb->mregs, OTG_REVISION),
			musb_readl(musb->mregs, OTG_SYSCONFIG),
			musb_readl(musb->mregs, OTG_SYSSTATUS),
			musb_readl(musb->mregs, OTG_INTERFSEL),
			musb_readl(musb->mregs, OTG_SIMENABLE));

	setup_timer(&musb_idle_timer, musb_do_idle, (unsigned long) musb);

	if (glue->status != OMAP_MUSB_UNKNOWN)
		omap_musb_set_mailbox(glue);

	usb_phy_init(musb->xceiv);

	pm_runtime_put_noidle(musb->controller);
	return 0;

err1:
	return status;
}

static void omap2430_musb_enable(struct musb *musb)
{
	u8		devctl;
	unsigned long timeout = jiffies + msecs_to_jiffies(1000);
	struct device *dev = musb->controller;
	struct omap2430_glue *glue = dev_get_drvdata(dev->parent);
	struct musb_hdrc_platform_data *pdata = dev->platform_data;
	struct omap_musb_board_data *data = pdata->board_data;

	switch (glue->status) {

	case OMAP_MUSB_ID_GROUND:
		omap_control_usb_set_mode(glue->control_otghs, USB_MODE_HOST);
		if (data->interface_type != MUSB_INTERFACE_UTMI)
			break;
		devctl = musb_readb(musb->mregs, MUSB_DEVCTL);
		/* start the session */
		devctl |= MUSB_DEVCTL_SESSION;
		musb_writeb(musb->mregs, MUSB_DEVCTL, devctl);
		while (musb_readb(musb->mregs, MUSB_DEVCTL) &
				MUSB_DEVCTL_BDEVICE) {
			cpu_relax();

			if (time_after(jiffies, timeout)) {
				dev_err(dev, "configured as A device timeout");
				break;
			}
		}
		break;

	case OMAP_MUSB_VBUS_VALID:
		omap_control_usb_set_mode(glue->control_otghs, USB_MODE_DEVICE);
		break;

	default:
		break;
	}
}

static void omap2430_musb_disable(struct musb *musb)
{
	struct device *dev = musb->controller;
	struct omap2430_glue *glue = dev_get_drvdata(dev->parent);

	if (glue->status != OMAP_MUSB_UNKNOWN)
		omap_control_usb_set_mode(glue->control_otghs,
			USB_MODE_DISCONNECT);
}

static int omap2430_musb_exit(struct musb *musb)
{
	del_timer_sync(&musb_idle_timer);

	omap2430_low_level_exit(musb);

	return 0;
}

static const struct musb_platform_ops omap2430_ops = {
	.init		= omap2430_musb_init,
	.exit		= omap2430_musb_exit,

	.set_mode	= omap2430_musb_set_mode,
	.try_idle	= omap2430_musb_try_idle,

	.set_vbus	= omap2430_musb_set_vbus,

	.enable		= omap2430_musb_enable,
	.disable	= omap2430_musb_disable,
};

static u64 omap2430_dmamask = DMA_BIT_MASK(32);

static int omap2430_probe(struct platform_device *pdev)
{
	struct musb_hdrc_platform_data	*pdata = pdev->dev.platform_data;
	struct omap_musb_board_data	*data;
	struct platform_device		*musb;
	struct omap2430_glue		*glue;
	struct device_node		*np = pdev->dev.of_node;
	struct musb_hdrc_config		*config;
	int				ret = -ENOMEM;

	glue = devm_kzalloc(&pdev->dev, sizeof(*glue), GFP_KERNEL);
	if (!glue) {
		dev_err(&pdev->dev, "failed to allocate glue context\n");
		goto err0;
	}

	musb = platform_device_alloc("musb-hdrc", PLATFORM_DEVID_AUTO);
	if (!musb) {
		dev_err(&pdev->dev, "failed to allocate musb device\n");
		goto err0;
	}

	musb->dev.parent		= &pdev->dev;
	musb->dev.dma_mask		= &omap2430_dmamask;
	musb->dev.coherent_dma_mask	= omap2430_dmamask;

	glue->dev			= &pdev->dev;
	glue->musb			= musb;
	glue->status			= OMAP_MUSB_UNKNOWN;

	if (np) {
		pdata = devm_kzalloc(&pdev->dev, sizeof(*pdata), GFP_KERNEL);
		if (!pdata) {
			dev_err(&pdev->dev,
				"failed to allocate musb platfrom data\n");
			goto err2;
		}

		data = devm_kzalloc(&pdev->dev, sizeof(*data), GFP_KERNEL);
		if (!data) {
			dev_err(&pdev->dev,
				"failed to allocate musb board data\n");
			goto err2;
		}

		config = devm_kzalloc(&pdev->dev, sizeof(*config), GFP_KERNEL);
		if (!config) {
			dev_err(&pdev->dev,
				"failed to allocate musb hdrc config\n");
			goto err2;
		}

		of_property_read_u32(np, "mode", (u32 *)&pdata->mode);
		of_property_read_u32(np, "interface-type",
						(u32 *)&data->interface_type);
		of_property_read_u32(np, "num-eps", (u32 *)&config->num_eps);
		of_property_read_u32(np, "ram-bits", (u32 *)&config->ram_bits);
		of_property_read_u32(np, "power", (u32 *)&pdata->power);
		config->multipoint = of_property_read_bool(np, "multipoint");
		pdata->has_mailbox = of_property_read_bool(np,
		    "ti,has-mailbox");

		pdata->board_data	= data;
		pdata->config		= config;
	}

	if (pdata->has_mailbox) {
		glue->control_otghs = omap_get_control_dev();
		if (IS_ERR(glue->control_otghs)) {
			dev_vdbg(&pdev->dev, "Failed to get control device\n");
			ret = PTR_ERR(glue->control_otghs);
			goto err2;
		}
	} else {
		glue->control_otghs = ERR_PTR(-ENODEV);
	}
	pdata->platform_ops		= &omap2430_ops;

	platform_set_drvdata(pdev, glue);

	/*
	 * REVISIT if we ever have two instances of the wrapper, we will be
	 * in big trouble
	 */
	_glue	= glue;

	INIT_WORK(&glue->omap_musb_mailbox_work, omap_musb_mailbox_work);

	ret = platform_device_add_resources(musb, pdev->resource,
			pdev->num_resources);
	if (ret) {
		dev_err(&pdev->dev, "failed to add resources\n");
		goto err2;
	}

	ret = platform_device_add_data(musb, pdata, sizeof(*pdata));
	if (ret) {
		dev_err(&pdev->dev, "failed to add platform_data\n");
		goto err2;
	}

	pm_runtime_enable(&pdev->dev);

	ret = platform_device_add(musb);
	if (ret) {
		dev_err(&pdev->dev, "failed to register musb device\n");
		goto err2;
	}

	return 0;

err2:
	platform_device_put(musb);

err0:
	return ret;
}

static int omap2430_remove(struct platform_device *pdev)
{
	struct omap2430_glue		*glue = platform_get_drvdata(pdev);

	cancel_work_sync(&glue->omap_musb_mailbox_work);
	platform_device_unregister(glue->musb);

	return 0;
}

#ifdef CONFIG_PM

static int omap2430_runtime_suspend(struct device *dev)
{
	struct omap2430_glue		*glue = dev_get_drvdata(dev);
	struct musb			*musb = glue_to_musb(glue);

	if (musb) {
		musb->context.otg_interfsel = musb_readl(musb->mregs,
				OTG_INTERFSEL);

		omap2430_low_level_exit(musb);
		usb_phy_set_suspend(musb->xceiv, 1);
	}

	return 0;
}

static int omap2430_runtime_resume(struct device *dev)
{
	struct omap2430_glue		*glue = dev_get_drvdata(dev);
	struct musb			*musb = glue_to_musb(glue);

	if (musb) {
		omap2430_low_level_init(musb);
		musb_writel(musb->mregs, OTG_INTERFSEL,
				musb->context.otg_interfsel);

		usb_phy_set_suspend(musb->xceiv, 0);
	}

	return 0;
}

static struct dev_pm_ops omap2430_pm_ops = {
	.runtime_suspend = omap2430_runtime_suspend,
	.runtime_resume = omap2430_runtime_resume,
};

#define DEV_PM_OPS	(&omap2430_pm_ops)
#else
#define DEV_PM_OPS	NULL
#endif

#ifdef CONFIG_OF
static const struct of_device_id omap2430_id_table[] = {
	{
		.compatible = "ti,omap4-musb"
	},
	{
		.compatible = "ti,omap3-musb"
	},
	{},
};
MODULE_DEVICE_TABLE(of, omap2430_id_table);
#endif

static struct platform_driver omap2430_driver = {
	.probe		= omap2430_probe,
	.remove		= omap2430_remove,
	.driver		= {
		.name	= "musb-omap2430",
		.pm	= DEV_PM_OPS,
		.of_match_table = of_match_ptr(omap2430_id_table),
	},
};

MODULE_DESCRIPTION("OMAP2PLUS MUSB Glue Layer");
MODULE_AUTHOR("Felipe Balbi <balbi@ti.com>");
MODULE_LICENSE("GPL v2");

static int __init omap2430_init(void)
{
	return platform_driver_register(&omap2430_driver);
}
subsys_initcall(omap2430_init);

static void __exit omap2430_exit(void)
{
	platform_driver_unregister(&omap2430_driver);
}
module_exit(omap2430_exit);


text:
"""Tests for layout.

Includes positioning and dimensioning of boxes, line breaks, page breaks.

"""

redpajama_set_name: RedPajamaGithub


text:
;------------------------------------------------------------------------------
;
; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR>
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution.  The full text of the license may be found at
; http://opensource.org/licenses/bsd-license.php
;
; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
;
; Module Name:
;
;   ReadDr5.Asm
;
; Abstract:
;
;   AsmReadDr5 function
;
; Notes:
;
;------------------------------------------------------------------------------

    .586p
    .model  flat,C
    .code

;------------------------------------------------------------------------------
; UINTN
; EFIAPI
; AsmReadDr5 (
;   VOID
;   );
;------------------------------------------------------------------------------
AsmReadDr5  PROC
    ;
    ; DR5 is alias to DR7 only if DE (in CR4) is cleared. Otherwise, reading
    ; this register will cause a #UD exception.
    ;
    ; MS assembler doesn't support this instruction since no one would use it
    ; under normal circustances. Here opcode is used.
    ;
    DB      0fh, 21h, 0e8h
    ret
AsmReadDr5  ENDP

    END


text:
/*
 * A simple DMA pool losely based on dmapool.c. It has certain advantages
 * over the DMA pools:
 * - Pool collects resently freed pages for reuse (and hooks up to
 *   the shrinker).
 * - Tracks currently in use pages
 * - Tracks whether the page is UC, WB or cached (and reverts to WB
 *   when freed).
 */

#define pr_fmt(fmt) "[TTM] " fmt

#include <linux/dma-mapping.h>
#include <linux/list.h>
#include <linux/seq_file.h> /* for seq_printf */
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/highmem.h>
#include <linux/mm_types.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/atomic.h>
#include <linux/device.h>
#include <linux/kthread.h>
#include <drm/ttm/ttm_bo_driver.h>
#include <drm/ttm/ttm_page_alloc.h>
#ifdef TTM_HAS_AGP
#include <asm/agp.h>
#endif

#define NUM_PAGES_TO_ALLOC		(PAGE_SIZE/sizeof(struct page *))
#define SMALL_ALLOCATION		4
#define FREE_ALL_PAGES			(~0U)
/* times are in msecs */
#define IS_UNDEFINED			(0)
#define IS_WC				(1<<1)
#define IS_UC				(1<<2)
#define IS_CACHED			(1<<3)
#define IS_DMA32			(1<<4)

enum pool_type {
	POOL_IS_UNDEFINED,
	POOL_IS_WC = IS_WC,
	POOL_IS_UC = IS_UC,
	POOL_IS_CACHED = IS_CACHED,
	POOL_IS_WC_DMA32 = IS_WC | IS_DMA32,
	POOL_IS_UC_DMA32 = IS_UC | IS_DMA32,
	POOL_IS_CACHED_DMA32 = IS_CACHED | IS_DMA32,
};
/*
 * The pool structure. There are usually six pools:
 *  - generic (not restricted to DMA32):
 *      - write combined, uncached, cached.
 *  - dma32 (up to 2^32 - so up 4GB):
 *      - write combined, uncached, cached.
 * for each 'struct device'. The 'cached' is for pages that are actively used.
 * The other ones can be shrunk by the shrinker API if neccessary.
 * @pools: The 'struct device->dma_pools' link.
 * @type: Type of the pool
 * @lock: Protects the inuse_list and free_list from concurrnet access. Must be
 * used with irqsave/irqrestore variants because pool allocator maybe called
 * from delayed work.
 * @inuse_list: Pool of pages that are in use. The order is very important and
 *   it is in the order that the TTM pages that are put back are in.
 * @free_list: Pool of pages that are free to be used. No order requirements.
 * @dev: The device that is associated with these pools.
 * @size: Size used during DMA allocation.
 * @npages_free: Count of available pages for re-use.
 * @npages_in_use: Count of pages that are in use.
 * @nfrees: Stats when pool is shrinking.
 * @nrefills: Stats when the pool is grown.
 * @gfp_flags: Flags to pass for alloc_page.
 * @name: Name of the pool.
 * @dev_name: Name derieved from dev - similar to how dev_info works.
 *   Used during shutdown as the dev_info during release is unavailable.
 */
struct dma_pool {
	struct list_head pools; /* The 'struct device->dma_pools link */
	enum pool_type type;
	spinlock_t lock;
	struct list_head inuse_list;
	struct list_head free_list;
	struct device *dev;
	unsigned size;
	unsigned npages_free;
	unsigned npages_in_use;
	unsigned long nfrees; /* Stats when shrunk. */
	unsigned long nrefills; /* Stats when grown. */
	gfp_t gfp_flags;
	char name[13]; /* "cached dma32" */
	char dev_name[64]; /* Constructed from dev */
};

/*
 * The accounting page keeping track of the allocated page along with
 * the DMA address.
 * @page_list: The link to the 'page_list' in 'struct dma_pool'.
 * @vaddr: The virtual address of the page
 * @dma: The bus address of the page. If the page is not allocated
 *   via the DMA API, it will be -1.
 */
struct dma_page {
	struct list_head page_list;
	void *vaddr;
	struct page *p;
	dma_addr_t dma;
};

/*
 * Limits for the pool. They are handled without locks because only place where
 * they may change is in sysfs store. They won't have immediate effect anyway
 * so forcing serialization to access them is pointless.
 */

struct ttm_pool_opts {
	unsigned	alloc_size;
	unsigned	max_size;
	unsigned	small;
};

/*
 * Contains the list of all of the 'struct device' and their corresponding
 * DMA pools. Guarded by _mutex->lock.
 * @pools: The link to 'struct ttm_pool_manager->pools'
 * @dev: The 'struct device' associated with the 'pool'
 * @pool: The 'struct dma_pool' associated with the 'dev'
 */
struct device_pools {
	struct list_head pools;
	struct device *dev;
	struct dma_pool *pool;
};

/*
 * struct ttm_pool_manager - Holds memory pools for fast allocation
 *
 * @lock: Lock used when adding/removing from pools
 * @pools: List of 'struct device' and 'struct dma_pool' tuples.
 * @options: Limits for the pool.
 * @npools: Total amount of pools in existence.
 * @shrinker: The structure used by [un|]register_shrinker
 */
struct ttm_pool_manager {
	struct mutex		lock;
	struct list_head	pools;
	struct ttm_pool_opts	options;
	unsigned		npools;
	struct shrinker		mm_shrink;
	struct kobject		kobj;
};

static struct ttm_pool_manager *_manager;

static struct attribute ttm_page_pool_max = {
	.name = "pool_max_size",
	.mode = S_IRUGO | S_IWUSR
};
static struct attribute ttm_page_pool_small = {
	.name = "pool_small_allocation",
	.mode = S_IRUGO | S_IWUSR
};
static struct attribute ttm_page_pool_alloc_size = {
	.name = "pool_allocation_size",
	.mode = S_IRUGO | S_IWUSR
};

static struct attribute *ttm_pool_attrs[] = {
	&ttm_page_pool_max,
	&ttm_page_pool_small,
	&ttm_page_pool_alloc_size,
	NULL
};

static void ttm_pool_kobj_release(struct kobject *kobj)
{
	struct ttm_pool_manager *m =
		container_of(kobj, struct ttm_pool_manager, kobj);
	kfree(m);
}

static ssize_t ttm_pool_store(struct kobject *kobj, struct attribute *attr,
			      const char *buffer, size_t size)
{
	struct ttm_pool_manager *m =
		container_of(kobj, struct ttm_pool_manager, kobj);
	int chars;
	unsigned val;
	chars = sscanf(buffer, "%u", &val);
	if (chars == 0)
		return size;

	/* Convert kb to number of pages */
	val = val / (PAGE_SIZE >> 10);

	if (attr == &ttm_page_pool_max)
		m->options.max_size = val;
	else if (attr == &ttm_page_pool_small)
		m->options.small = val;
	else if (attr == &ttm_page_pool_alloc_size) {
		if (val > NUM_PAGES_TO_ALLOC*8) {
			pr_err("Setting allocation size to %lu is not allowed. Recommended size is %lu\n",
			       NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 7),
			       NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 10));
			return size;
		} else if (val > NUM_PAGES_TO_ALLOC) {
			pr_warn("Setting allocation size to larger than %lu is not recommended\n",
				NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 10));
		}
		m->options.alloc_size = val;
	}

	return size;
}

static ssize_t ttm_pool_show(struct kobject *kobj, struct attribute *attr,
			     char *buffer)
{
	struct ttm_pool_manager *m =
		container_of(kobj, struct ttm_pool_manager, kobj);
	unsigned val = 0;

	if (attr == &ttm_page_pool_max)
		val = m->options.max_size;
	else if (attr == &ttm_page_pool_small)
		val = m->options.small;
	else if (attr == &ttm_page_pool_alloc_size)
		val = m->options.alloc_size;

	val = val * (PAGE_SIZE >> 10);

	return snprintf(buffer, PAGE_SIZE, "%u\n", val);
}

static const struct sysfs_ops ttm_pool_sysfs_ops = {
	.show = &ttm_pool_show,
	.store = &ttm_pool_store,
};

static struct kobj_type ttm_pool_kobj_type = {
	.release = &ttm_pool_kobj_release,
	.sysfs_ops = &ttm_pool_sysfs_ops,
	.default_attrs = ttm_pool_attrs,
};

#ifndef CONFIG_X86
static int set_pages_array_wb(struct page **pages, int addrinarray)
{
#ifdef TTM_HAS_AGP
	int i;

	for (i = 0; i < addrinarray; i++)
		unmap_page_from_agp(pages[i]);
#endif
	return 0;
}

static int set_pages_array_wc(struct page **pages, int addrinarray)
{
#ifdef TTM_HAS_AGP
	int i;

	for (i = 0; i < addrinarray; i++)
		map_page_into_agp(pages[i]);
#endif
	return 0;
}

static int set_pages_array_uc(struct page **pages, int addrinarray)
{
#ifdef TTM_HAS_AGP
	int i;

	for (i = 0; i < addrinarray; i++)
		map_page_into_agp(pages[i]);
#endif
	return 0;
}
#endif /* for !CONFIG_X86 */

static int ttm_set_pages_caching(struct dma_pool *pool,
				 struct page **pages, unsigned cpages)
{
	int r = 0;
	/* Set page caching */
	if (pool->type & IS_UC) {
		r = set_pages_array_uc(pages, cpages);
		if (r)
			pr_err("%s: Failed to set %d pages to uc!\n",
			       pool->dev_name, cpages);
	}
	if (pool->type & IS_WC) {
		r = set_pages_array_wc(pages, cpages);
		if (r)
			pr_err("%s: Failed to set %d pages to wc!\n",
			       pool->dev_name, cpages);
	}
	return r;
}

static void __ttm_dma_free_page(struct dma_pool *pool, struct dma_page *d_page)
{
	dma_addr_t dma = d_page->dma;
	dma_free_coherent(pool->dev, pool->size, d_page->vaddr, dma);

	kfree(d_page);
	d_page = NULL;
}
static struct dma_page *__ttm_dma_alloc_page(struct dma_pool *pool)
{
	struct dma_page *d_page;

	d_page = kmalloc(sizeof(struct dma_page), GFP_KERNEL);
	if (!d_page)
		return NULL;

	d_page->vaddr = dma_alloc_coherent(pool->dev, pool->size,
					   &d_page->dma,
					   pool->gfp_flags);
	if (d_page->vaddr)
		d_page->p = virt_to_page(d_page->vaddr);
	else {
		kfree(d_page);
		d_page = NULL;
	}
	return d_page;
}
static enum pool_type ttm_to_type(int flags, enum ttm_caching_state cstate)
{
	enum pool_type type = IS_UNDEFINED;

	if (flags & TTM_PAGE_FLAG_DMA32)
		type |= IS_DMA32;
	if (cstate == tt_cached)
		type |= IS_CACHED;
	else if (cstate == tt_uncached)
		type |= IS_UC;
	else
		type |= IS_WC;

	return type;
}

static void ttm_pool_update_free_locked(struct dma_pool *pool,
					unsigned freed_pages)
{
	pool->npages_free -= freed_pages;
	pool->nfrees += freed_pages;

}

/* set memory back to wb and free the pages. */
static void ttm_dma_pages_put(struct dma_pool *pool, struct list_head *d_pages,
			      struct page *pages[], unsigned npages)
{
	struct dma_page *d_page, *tmp;

	/* Don't set WB on WB page pool. */
	if (npages && !(pool->type & IS_CACHED) &&
	    set_pages_array_wb(pages, npages))
		pr_err("%s: Failed to set %d pages to wb!\n",
		       pool->dev_name, npages);

	list_for_each_entry_safe(d_page, tmp, d_pages, page_list) {
		list_del(&d_page->page_list);
		__ttm_dma_free_page(pool, d_page);
	}
}

static void ttm_dma_page_put(struct dma_pool *pool, struct dma_page *d_page)
{
	/* Don't set WB on WB page pool. */
	if (!(pool->type & IS_CACHED) && set_pages_array_wb(&d_page->p, 1))
		pr_err("%s: Failed to set %d pages to wb!\n",
		       pool->dev_name, 1);

	list_del(&d_page->page_list);
	__ttm_dma_free_page(pool, d_page);
}

/*
 * Free pages from pool.
 *
 * To prevent hogging the ttm_swap process we only free NUM_PAGES_TO_ALLOC
 * number of pages in one go.
 *
 * @pool: to free the pages from
 * @nr_free: If set to true will free all pages in pool
 **/
static unsigned ttm_dma_page_pool_free(struct dma_pool *pool, unsigned nr_free)
{
	unsigned long irq_flags;
	struct dma_page *dma_p, *tmp;
	struct page **pages_to_free;
	struct list_head d_pages;
	unsigned freed_pages = 0,
		 npages_to_free = nr_free;

	if (NUM_PAGES_TO_ALLOC < nr_free)
		npages_to_free = NUM_PAGES_TO_ALLOC;
#if 0
	if (nr_free > 1) {
		pr_debug("%s: (%s:%d) Attempting to free %d (%d) pages\n",
			 pool->dev_name, pool->name, current->pid,
			 npages_to_free, nr_free);
	}
#endif
	pages_to_free = kmalloc(npages_to_free * sizeof(struct page *),
			GFP_KERNEL);

	if (!pages_to_free) {
		pr_err("%s: Failed to allocate memory for pool free operation\n",
		       pool->dev_name);
		return 0;
	}
	INIT_LIST_HEAD(&d_pages);
restart:
	spin_lock_irqsave(&pool->lock, irq_flags);

	/* We picking the oldest ones off the list */
	list_for_each_entry_safe_reverse(dma_p, tmp, &pool->free_list,
					 page_list) {
		if (freed_pages >= npages_to_free)
			break;

		/* Move the dma_page from one list to another. */
		list_move(&dma_p->page_list, &d_pages);

		pages_to_free[freed_pages++] = dma_p->p;
		/* We can only remove NUM_PAGES_TO_ALLOC at a time. */
		if (freed_pages >= NUM_PAGES_TO_ALLOC) {

			ttm_pool_update_free_locked(pool, freed_pages);
			/**
			 * Because changing page caching is costly
			 * we unlock the pool to prevent stalling.
			 */
			spin_unlock_irqrestore(&pool->lock, irq_flags);

			ttm_dma_pages_put(pool, &d_pages, pages_to_free,
					  freed_pages);

			INIT_LIST_HEAD(&d_pages);

			if (likely(nr_free != FREE_ALL_PAGES))
				nr_free -= freed_pages;

			if (NUM_PAGES_TO_ALLOC >= nr_free)
				npages_to_free = nr_free;
			else
				npages_to_free = NUM_PAGES_TO_ALLOC;

			freed_pages = 0;

			/* free all so restart the processing */
			if (nr_free)
				goto restart;

			/* Not allowed to fall through or break because
			 * following context is inside spinlock while we are
			 * outside here.
			 */
			goto out;

		}
	}

	/* remove range of pages from the pool */
	if (freed_pages) {
		ttm_pool_update_free_locked(pool, freed_pages);
		nr_free -= freed_pages;
	}

	spin_unlock_irqrestore(&pool->lock, irq_flags);

	if (freed_pages)
		ttm_dma_pages_put(pool, &d_pages, pages_to_free, freed_pages);
out:
	kfree(pages_to_free);
	return nr_free;
}

static void ttm_dma_free_pool(struct device *dev, enum pool_type type)
{
	struct device_pools *p;
	struct dma_pool *pool;

	if (!dev)
		return;

	mutex_lock(&_manager->lock);
	list_for_each_entry_reverse(p, &_manager->pools, pools) {
		if (p->dev != dev)
			continue;
		pool = p->pool;
		if (pool->type != type)
			continue;

		list_del(&p->pools);
		kfree(p);
		_manager->npools--;
		break;
	}
	list_for_each_entry_reverse(pool, &dev->dma_pools, pools) {
		if (pool->type != type)
			continue;
		/* Takes a spinlock.. */
		ttm_dma_page_pool_free(pool, FREE_ALL_PAGES);
		WARN_ON(((pool->npages_in_use + pool->npages_free) != 0));
		/* This code path is called after _all_ references to the
		 * struct device has been dropped - so nobody should be
		 * touching it. In case somebody is trying to _add_ we are
		 * guarded by the mutex. */
		list_del(&pool->pools);
		kfree(pool);
		break;
	}
	mutex_unlock(&_manager->lock);
}

/*
 * On free-ing of the 'struct device' this deconstructor is run.
 * Albeit the pool might have already been freed earlier.
 */
static void ttm_dma_pool_release(struct device *dev, void *res)
{
	struct dma_pool *pool = *(struct dma_pool **)res;

	if (pool)
		ttm_dma_free_pool(dev, pool->type);
}

static int ttm_dma_pool_match(struct device *dev, void *res, void *match_data)
{
	return *(struct dma_pool **)res == match_data;
}

static struct dma_pool *ttm_dma_pool_init(struct device *dev, gfp_t flags,
					  enum pool_type type)
{
	char *n[] = {"wc", "uc", "cached", " dma32", "unknown",};
	enum pool_type t[] = {IS_WC, IS_UC, IS_CACHED, IS_DMA32, IS_UNDEFINED};
	struct device_pools *sec_pool = NULL;
	struct dma_pool *pool = NULL, **ptr;
	unsigned i;
	int ret = -ENODEV;
	char *p;

	if (!dev)
		return NULL;

	ptr = devres_alloc(ttm_dma_pool_release, sizeof(*ptr), GFP_KERNEL);
	if (!ptr)
		return NULL;

	ret = -ENOMEM;

	pool = kmalloc_node(sizeof(struct dma_pool), GFP_KERNEL,
			    dev_to_node(dev));
	if (!pool)
		goto err_mem;

	sec_pool = kmalloc_node(sizeof(struct device_pools), GFP_KERNEL,
				dev_to_node(dev));
	if (!sec_pool)
		goto err_mem;

	INIT_LIST_HEAD(&sec_pool->pools);
	sec_pool->dev = dev;
	sec_pool->pool =  pool;

	INIT_LIST_HEAD(&pool->free_list);
	INIT_LIST_HEAD(&pool->inuse_list);
	INIT_LIST_HEAD(&pool->pools);
	spin_lock_init(&pool->lock);
	pool->dev = dev;
	pool->npages_free = pool->npages_in_use = 0;
	pool->nfrees = 0;
	pool->gfp_flags = flags;
	pool->size = PAGE_SIZE;
	pool->type = type;
	pool->nrefills = 0;
	p = pool->name;
	for (i = 0; i < 5; i++) {
		if (type & t[i]) {
			p += snprintf(p, sizeof(pool->name) - (p - pool->name),
				      "%s", n[i]);
		}
	}
	*p = 0;
	/* We copy the name for pr_ calls b/c when dma_pool_destroy is called
	 * - the kobj->name has already been deallocated.*/
	snprintf(pool->dev_name, sizeof(pool->dev_name), "%s %s",
		 dev_driver_string(dev), dev_name(dev));
	mutex_lock(&_manager->lock);
	/* You can get the dma_pool from either the global: */
	list_add(&sec_pool->pools, &_manager->pools);
	_manager->npools++;
	/* or from 'struct device': */
	list_add(&pool->pools, &dev->dma_pools);
	mutex_unlock(&_manager->lock);

	*ptr = pool;
	devres_add(dev, ptr);

	return pool;
err_mem:
	devres_free(ptr);
	kfree(sec_pool);
	kfree(pool);
	return ERR_PTR(ret);
}

static struct dma_pool *ttm_dma_find_pool(struct device *dev,
					  enum pool_type type)
{
	struct dma_pool *pool, *tmp, *found = NULL;

	if (type == IS_UNDEFINED)
		return found;

	/* NB: We iterate on the 'struct dev' which has no spinlock, but
	 * it does have a kref which we have taken. The kref is taken during
	 * graphic driver loading - in the drm_pci_init it calls either
	 * pci_dev_get or pci_register_driver which both end up taking a kref
	 * on 'struct device'.
	 *
	 * On teardown, the graphic drivers end up quiescing the TTM (put_pages)
	 * and calls the dev_res deconstructors: ttm_dma_pool_release. The nice
	 * thing is at that point of time there are no pages associated with the
	 * driver so this function will not be called.
	 */
	list_for_each_entry_safe(pool, tmp, &dev->dma_pools, pools) {
		if (pool->type != type)
			continue;
		found = pool;
		break;
	}
	return found;
}

/*
 * Free pages the pages that failed to change the caching state. If there
 * are pages that have changed their caching state already put them to the
 * pool.
 */
static void ttm_dma_handle_caching_state_failure(struct dma_pool *pool,
						 struct list_head *d_pages,
						 struct page **failed_pages,
						 unsigned cpages)
{
	struct dma_page *d_page, *tmp;
	struct page *p;
	unsigned i = 0;

	p = failed_pages[0];
	if (!p)
		return;
	/* Find the failed page. */
	list_for_each_entry_safe(d_page, tmp, d_pages, page_list) {
		if (d_page->p != p)
			continue;
		/* .. and then progress over the full list. */
		list_del(&d_page->page_list);
		__ttm_dma_free_page(pool, d_page);
		if (++i < cpages)
			p = failed_pages[i];
		else
			break;
	}

}

/*
 * Allocate 'count' pages, and put 'need' number of them on the
 * 'pages' and as well on the 'dma_address' starting at 'dma_offset' offset.
 * The full list of pages should also be on 'd_pages'.
 * We return zero for success, and negative numbers as errors.
 */
static int ttm_dma_pool_alloc_new_pages(struct dma_pool *pool,
					struct list_head *d_pages,
					unsigned count)
{
	struct page **caching_array;
	struct dma_page *dma_p;
	struct page *p;
	int r = 0;
	unsigned i, cpages;
	unsigned max_cpages = min(count,
			(unsigned)(PAGE_SIZE/sizeof(struct page *)));

	/* allocate array for page caching change */
	caching_array = kmalloc(max_cpages*sizeof(struct page *), GFP_KERNEL);

	if (!caching_array) {
		pr_err("%s: Unable to allocate table for new pages\n",
		       pool->dev_name);
		return -ENOMEM;
	}

	if (count > 1) {
		pr_debug("%s: (%s:%d) Getting %d pages\n",
			 pool->dev_name, pool->name, current->pid, count);
	}

	for (i = 0, cpages = 0; i < count; ++i) {
		dma_p = __ttm_dma_alloc_page(pool);
		if (!dma_p) {
			pr_err("%s: Unable to get page %u\n",
			       pool->dev_name, i);

			/* store already allocated pages in the pool after
			 * setting the caching state */
			if (cpages) {
				r = ttm_set_pages_caching(pool, caching_array,
							  cpages);
				if (r)
					ttm_dma_handle_caching_state_failure(
						pool, d_pages, caching_array,
						cpages);
			}
			r = -ENOMEM;
			goto out;
		}
		p = dma_p->p;
#ifdef CONFIG_HIGHMEM
		/* gfp flags of highmem page should never be dma32 so we
		 * we should be fine in such case
		 */
		if (!PageHighMem(p))
#endif
		{
			caching_array[cpages++] = p;
			if (cpages == max_cpages) {
				/* Note: Cannot hold the spinlock */
				r = ttm_set_pages_caching(pool, caching_array,
						 cpages);
				if (r) {
					ttm_dma_handle_caching_state_failure(
						pool, d_pages, caching_array,
						cpages);
					goto out;
				}
				cpages = 0;
			}
		}
		list_add(&dma_p->page_list, d_pages);
	}

	if (cpages) {
		r = ttm_set_pages_caching(pool, caching_array, cpages);
		if (r)
			ttm_dma_handle_caching_state_failure(pool, d_pages,
					caching_array, cpages);
	}
out:
	kfree(caching_array);
	return r;
}

/*
 * @return count of pages still required to fulfill the request.
 */
static int ttm_dma_page_pool_fill_locked(struct dma_pool *pool,
					 unsigned long *irq_flags)
{
	unsigned count = _manager->options.small;
	int r = pool->npages_free;

	if (count > pool->npages_free) {
		struct list_head d_pages;

		INIT_LIST_HEAD(&d_pages);

		spin_unlock_irqrestore(&pool->lock, *irq_flags);

		/* Returns how many more are neccessary to fulfill the
		 * request. */
		r = ttm_dma_pool_alloc_new_pages(pool, &d_pages, count);

		spin_lock_irqsave(&pool->lock, *irq_flags);
		if (!r) {
			/* Add the fresh to the end.. */
			list_splice(&d_pages, &pool->free_list);
			++pool->nrefills;
			pool->npages_free += count;
			r = count;
		} else {
			struct dma_page *d_page;
			unsigned cpages = 0;

			pr_err("%s: Failed to fill %s pool (r:%d)!\n",
			       pool->dev_name, pool->name, r);

			list_for_each_entry(d_page, &d_pages, page_list) {
				cpages++;
			}
			list_splice_tail(&d_pages, &pool->free_list);
			pool->npages_free += cpages;
			r = cpages;
		}
	}
	return r;
}

/*
 * @return count of pages still required to fulfill the request.
 * The populate list is actually a stack (not that is matters as TTM
 * allocates one page at a time.
 */
static int ttm_dma_pool_get_pages(struct dma_pool *pool,
				  struct ttm_dma_tt *ttm_dma,
				  unsigned index)
{
	struct dma_page *d_page;
	struct ttm_tt *ttm = &ttm_dma->ttm;
	unsigned long irq_flags;
	int count, r = -ENOMEM;

	spin_lock_irqsave(&pool->lock, irq_flags);
	count = ttm_dma_page_pool_fill_locked(pool, &irq_flags);
	if (count) {
		d_page = list_first_entry(&pool->free_list, struct dma_page, page_list);
		ttm->pages[index] = d_page->p;
		ttm_dma->dma_address[index] = d_page->dma;
		list_move_tail(&d_page->page_list, &ttm_dma->pages_list);
		r = 0;
		pool->npages_in_use += 1;
		pool->npages_free -= 1;
	}
	spin_unlock_irqrestore(&pool->lock, irq_flags);
	return r;
}

/*
 * On success pages list will hold count number of correctly
 * cached pages. On failure will hold the negative return value (-ENOMEM, etc).
 */
int ttm_dma_populate(struct ttm_dma_tt *ttm_dma, struct device *dev)
{
	struct ttm_tt *ttm = &ttm_dma->ttm;
	struct ttm_mem_global *mem_glob = ttm->glob->mem_glob;
	struct dma_pool *pool;
	enum pool_type type;
	unsigned i;
	gfp_t gfp_flags;
	int ret;

	if (ttm->state != tt_unpopulated)
		return 0;

	type = ttm_to_type(ttm->page_flags, ttm->caching_state);
	if (ttm->page_flags & TTM_PAGE_FLAG_DMA32)
		gfp_flags = GFP_USER | GFP_DMA32;
	else
		gfp_flags = GFP_HIGHUSER;
	if (ttm->page_flags & TTM_PAGE_FLAG_ZERO_ALLOC)
		gfp_flags |= __GFP_ZERO;

	pool = ttm_dma_find_pool(dev, type);
	if (!pool) {
		pool = ttm_dma_pool_init(dev, gfp_flags, type);
		if (IS_ERR_OR_NULL(pool)) {
			return -ENOMEM;
		}
	}

	INIT_LIST_HEAD(&ttm_dma->pages_list);
	for (i = 0; i < ttm->num_pages; ++i) {
		ret = ttm_dma_pool_get_pages(pool, ttm_dma, i);
		if (ret != 0) {
			ttm_dma_unpopulate(ttm_dma, dev);
			return -ENOMEM;
		}

		ret = ttm_mem_global_alloc_page(mem_glob, ttm->pages[i],
						false, false);
		if (unlikely(ret != 0)) {
			ttm_dma_unpopulate(ttm_dma, dev);
			return -ENOMEM;
		}
	}

	if (unlikely(ttm->page_flags & TTM_PAGE_FLAG_SWAPPED)) {
		ret = ttm_tt_swapin(ttm);
		if (unlikely(ret != 0)) {
			ttm_dma_unpopulate(ttm_dma, dev);
			return ret;
		}
	}

	ttm->state = tt_unbound;
	return 0;
}
EXPORT_SYMBOL_GPL(ttm_dma_populate);

/* Get good estimation how many pages are free in pools */
static int ttm_dma_pool_get_num_unused_pages(void)
{
	struct device_pools *p;
	unsigned total = 0;

	mutex_lock(&_manager->lock);
	list_for_each_entry(p, &_manager->pools, pools)
		total += p->pool->npages_free;
	mutex_unlock(&_manager->lock);
	return total;
}

/* Put all pages in pages list to correct pool to wait for reuse */
void ttm_dma_unpopulate(struct ttm_dma_tt *ttm_dma, struct device *dev)
{
	struct ttm_tt *ttm = &ttm_dma->ttm;
	struct dma_pool *pool;
	struct dma_page *d_page, *next;
	enum pool_type type;
	bool is_cached = false;
	unsigned count = 0, i, npages = 0;
	unsigned long irq_flags;

	type = ttm_to_type(ttm->page_flags, ttm->caching_state);
	pool = ttm_dma_find_pool(dev, type);
	if (!pool)
		return;

	is_cached = (ttm_dma_find_pool(pool->dev,
		     ttm_to_type(ttm->page_flags, tt_cached)) == pool);

	/* make sure pages array match list and count number of pages */
	list_for_each_entry(d_page, &ttm_dma->pages_list, page_list) {
		ttm->pages[count] = d_page->p;
		count++;
	}

	spin_lock_irqsave(&pool->lock, irq_flags);
	pool->npages_in_use -= count;
	if (is_cached) {
		pool->nfrees += count;
	} else {
		pool->npages_free += count;
		list_splice(&ttm_dma->pages_list, &pool->free_list);
		npages = count;
		if (pool->npages_free > _manager->options.max_size) {
			npages = pool->npages_free - _manager->options.max_size;
			/* free at least NUM_PAGES_TO_ALLOC number of pages
			 * to reduce calls to set_memory_wb */
			if (npages < NUM_PAGES_TO_ALLOC)
				npages = NUM_PAGES_TO_ALLOC;
		}
	}
	spin_unlock_irqrestore(&pool->lock, irq_flags);

	if (is_cached) {
		list_for_each_entry_safe(d_page, next, &ttm_dma->pages_list, page_list) {
			ttm_mem_global_free_page(ttm->glob->mem_glob,
						 d_page->p);
			ttm_dma_page_put(pool, d_page);
		}
	} else {
		for (i = 0; i < count; i++) {
			ttm_mem_global_free_page(ttm->glob->mem_glob,
						 ttm->pages[i]);
		}
	}

	INIT_LIST_HEAD(&ttm_dma->pages_list);
	for (i = 0; i < ttm->num_pages; i++) {
		ttm->pages[i] = NULL;
		ttm_dma->dma_address[i] = 0;
	}

	/* shrink pool if necessary (only on !is_cached pools)*/
	if (npages)
		ttm_dma_page_pool_free(pool, npages);
	ttm->state = tt_unpopulated;
}
EXPORT_SYMBOL_GPL(ttm_dma_unpopulate);

/**
 * Callback for mm to request pool to reduce number of page held.
 */
static int ttm_dma_pool_mm_shrink(struct shrinker *shrink,
				  struct shrink_control *sc)
{
	static atomic_t start_pool = ATOMIC_INIT(0);
	unsigned idx = 0;
	unsigned pool_offset = atomic_add_return(1, &start_pool);
	unsigned shrink_pages = sc->nr_to_scan;
	struct device_pools *p;

	if (list_empty(&_manager->pools))
		return 0;

	mutex_lock(&_manager->lock);
	pool_offset = pool_offset % _manager->npools;
	list_for_each_entry(p, &_manager->pools, pools) {
		unsigned nr_free;

		if (!p->dev)
			continue;
		if (shrink_pages == 0)
			break;
		/* Do it in round-robin fashion. */
		if (++idx < pool_offset)
			continue;
		nr_free = shrink_pages;
		shrink_pages = ttm_dma_page_pool_free(p->pool, nr_free);
		pr_debug("%s: (%s:%d) Asked to shrink %d, have %d more to go\n",
			 p->pool->dev_name, p->pool->name, current->pid,
			 nr_free, shrink_pages);
	}
	mutex_unlock(&_manager->lock);
	/* return estimated number of unused pages in pool */
	return ttm_dma_pool_get_num_unused_pages();
}

static void ttm_dma_pool_mm_shrink_init(struct ttm_pool_manager *manager)
{
	manager->mm_shrink.shrink = &ttm_dma_pool_mm_shrink;
	manager->mm_shrink.seeks = 1;
	register_shrinker(&manager->mm_shrink);
}

static void ttm_dma_pool_mm_shrink_fini(struct ttm_pool_manager *manager)
{
	unregister_shrinker(&manager->mm_shrink);
}

int ttm_dma_page_alloc_init(struct ttm_mem_global *glob, unsigned max_pages)
{
	int ret = -ENOMEM;

	WARN_ON(_manager);

	pr_info("Initializing DMA pool allocator\n");

	_manager = kzalloc(sizeof(*_manager), GFP_KERNEL);
	if (!_manager)
		goto err;

	mutex_init(&_manager->lock);
	INIT_LIST_HEAD(&_manager->pools);

	_manager->options.max_size = max_pages;
	_manager->options.small = SMALL_ALLOCATION;
	_manager->options.alloc_size = NUM_PAGES_TO_ALLOC;

	/* This takes care of auto-freeing the _manager */
	ret = kobject_init_and_add(&_manager->kobj, &ttm_pool_kobj_type,
				   &glob->kobj, "dma_pool");
	if (unlikely(ret != 0)) {
		kobject_put(&_manager->kobj);
		goto err;
	}
	ttm_dma_pool_mm_shrink_init(_manager);
	return 0;
err:
	return ret;
}

void ttm_dma_page_alloc_fini(void)
{
	struct device_pools *p, *t;

	pr_info("Finalizing DMA pool allocator\n");
	ttm_dma_pool_mm_shrink_fini(_manager);

	list_for_each_entry_safe_reverse(p, t, &_manager->pools, pools) {
		dev_dbg(p->dev, "(%s:%d) Freeing.\n", p->pool->name,
			current->pid);
		WARN_ON(devres_destroy(p->dev, ttm_dma_pool_release,
			ttm_dma_pool_match, p->pool));
		ttm_dma_free_pool(p->dev, p->pool->type);
	}
	kobject_put(&_manager->kobj);
	_manager = NULL;
}

int ttm_dma_page_alloc_debugfs(struct seq_file *m, void *data)
{
	struct device_pools *p;
	struct dma_pool *pool = NULL;
	char *h[] = {"pool", "refills", "pages freed", "inuse", "available",
		     "name", "virt", "busaddr"};

	if (!_manager) {
		seq_printf(m, "No pool allocator running.\n");
		return 0;
	}
	seq_printf(m, "%13s %12s %13s %8s %8s %8s\n",
		   h[0], h[1], h[2], h[3], h[4], h[5]);
	mutex_lock(&_manager->lock);
	list_for_each_entry(p, &_manager->pools, pools) {
		struct device *dev = p->dev;
		if (!dev)
			continue;
		pool = p->pool;
		seq_printf(m, "%13s %12ld %13ld %8d %8d %8s\n",
				pool->name, pool->nrefills,
				pool->nfrees, pool->npages_in_use,
				pool->npages_free,
				pool->dev_name);
	}
	mutex_unlock(&_manager->lock);
	return 0;
}
EXPORT_SYMBOL_GPL(ttm_dma_page_alloc_debugfs);


text:
require 'ffi_yajl'
require 'chef_zero/rest_base'
require 'chef_zero/rest_error_response'

module ChefZero
  module Endpoints
    # /environments/NAME/cookbook_versions
    class EnvironmentCookbookVersionsEndpoint < RestBase

      def post(request)
        cookbook_names = list_data(request, request.rest_path[0..1] + ['cookbooks'])

        # Get the list of cookbooks and versions desired by the runlist
        desired_versions = {}
        run_list = FFI_Yajl::Parser.parse(request.body, :create_additions => false)['run_list']
        run_list.each do |run_list_entry|
          if run_list_entry =~ /(.+)::.+\@(.+)/ || run_list_entry =~ /(.+)\@(.+)/
            raise RestErrorResponse.new(412, "No such cookbook: #{$1}") if !cookbook_names.include?($1)
            raise RestErrorResponse.new(412, "No such cookbook version for cookbook #{$1}: #{$2}") if !list_data(request, request.rest_path[0..1] + ['cookbooks', $1]).include?($2)
            desired_versions[$1] = [ $2 ]
          else
            desired_cookbook = run_list_entry.split('::')[0]
            raise RestErrorResponse.new(412, "No such cookbook: #{desired_cookbook}") if !cookbook_names.include?(desired_cookbook)
            desired_versions[desired_cookbook] = list_data(request, request.rest_path[0..1] + ['cookbooks', desired_cookbook])
          end
        end

        # Filter by environment constraints
        environment = FFI_Yajl::Parser.parse(get_data(request, request.rest_path[0..3]), :create_additions => false)
        environment_constraints = environment['cookbook_versions'] || {}

        desired_versions.each_key do |name|
          desired_versions = filter_by_constraint(desired_versions, name, environment_constraints[name])
        end

        # Depsolve!
        solved = depsolve(request, desired_versions.keys, desired_versions, environment_constraints)
        if !solved
          if @last_missing_dep && !cookbook_names.include?(@last_missing_dep)
            return raise RestErrorResponse.new(412, "No such cookbook: #{@last_missing_dep}")
          elsif @last_constraint_failure
            return raise RestErrorResponse.new(412, "Could not satisfy version constraints for: #{@last_constraint_failure}")
          else

            return raise RestErrorResponse.new(412, "Unsolvable versions!")
          end
        end

        result = {}
        solved.each_pair do |name, versions|
          cookbook = FFI_Yajl::Parser.parse(get_data(request, request.rest_path[0..1] + ['cookbooks', name, versions[0]]), :create_additions => false)
          result[name] = ChefData::DataNormalizer.normalize_cookbook(self, request.rest_path[0..1], cookbook, name, versions[0], request.base_uri, 'MIN')
        end
        json_response(200, result)
      end

      def depsolve(request, unsolved, desired_versions, environment_constraints)
        desired_versions.each do |cb, ver|
          if ver.empty?
            @last_constraint_failure = cb
            return nil
          end
        end

        # If everything is already
        solve_for = unsolved[0]
        return desired_versions if !solve_for

        # Go through each desired version of this cookbook, starting with the latest,
        # until we find one we can solve successfully with
        sort_versions(desired_versions[solve_for]).each do |desired_version|
          new_desired_versions = desired_versions.clone
          new_desired_versions[solve_for] = [ desired_version ]
          new_unsolved = unsolved[1..-1]

          # Pick this cookbook, and add dependencies
          cookbook_obj = FFI_Yajl::Parser.parse(get_data(request, request.rest_path[0..1] + ['cookbooks', solve_for, desired_version]), :create_additions => false)
          cookbook_metadata = cookbook_obj['metadata'] || {}
          cookbook_dependencies = cookbook_metadata['dependencies'] || {}
          dep_not_found = false
          cookbook_dependencies.each_pair do |dep_name, dep_constraint|
            # If the dep is not already in the list, add it to the list to solve
            # and bring in all environment-allowed cookbook versions to desired_versions
            if !new_desired_versions.has_key?(dep_name)
              new_unsolved = new_unsolved + [dep_name]
              # If the dep is missing, we will try other versions of the cookbook that might not have the bad dep.
              if !exists_data_dir?(request, request.rest_path[0..1] + ['cookbooks', dep_name])
                @last_missing_dep = dep_name.to_s
                dep_not_found = true
                break
              end
              new_desired_versions[dep_name] = list_data(request, request.rest_path[0..1] + ['cookbooks', dep_name])
              new_desired_versions = filter_by_constraint(new_desired_versions, dep_name, environment_constraints[dep_name])
            end
            new_desired_versions = filter_by_constraint(new_desired_versions, dep_name, dep_constraint)
          end

          next if dep_not_found

          # Depsolve children with this desired version!  First solution wins.
          result = depsolve(request, new_unsolved, new_desired_versions, environment_constraints)
          return result if result
        end
        return nil
      end

      def sort_versions(versions)
        result = versions.sort_by { |version| Gem::Version.new(version.dup) }
        result.reverse
      end

      def filter_by_constraint(versions, cookbook_name, constraint)
        return versions if !constraint
        constraint = Gem::Requirement.new(constraint)
        new_versions = versions[cookbook_name]
        new_versions = new_versions.select { |version| constraint.satisfied_by?(Gem::Version.new(version.dup)) }
        result = versions.clone
        result[cookbook_name] = new_versions
        result
      end
    end
  end
end


text:
   ({ __typeof__ (a) _a = (a); \
      __typeof__ (b) _b = (b); \
     _a > _b ? _a : _b; })

#define min(a,b) \
   ({ __typeof__ (a) _a = (a); \
      __typeof__ (b) _b = (b); \
     _a < _b ? _a : _b; })

#define MIN_OVERLAP_INSERT 25
#define BAD_MULT 6
#define GOOD_MULT_1 8
#define GOOD_MULT_2 400

jint mid(int x, int y, int z){return x<y ? (x<z ? min(y, z) : x) : (y<z ? min(x, z) : y);}

jint mateByOverlap(jbyte * a_bases, const jint a_bases_length, jbyte * b_bases, const jint b_bases_length, jbyte * a_quality, jbyte * b_quality, jfloat * aprob, jfloat * bprob, jint * rvector, jint minOverlap0, const jint minOverlap, const jint minInsert0, jint margin, const jint maxMismatches0, const jint maxMismatches, const jint minq) {

	minOverlap0=min(max(1, minOverlap0), minOverlap);
	margin=max(margin, 0);

	const jbyte *abases=a_bases, *bbases=b_bases;
	jbyte *aqual=NULL;
	jbyte *bqual=NULL;
	if(a_quality!=NULL){
		aqual=a_quality;
	}
	if(b_quality!=NULL){
		bqual=b_quality;
	}
	const jint alen=a_bases_length, blen=b_bases_length;

	jint bestOverlap=-1;
	jint bestGood=-1;
	jint bestBad=maxMismatches0;

	jboolean ambig=0;
	const jint maxOverlap=alen+blen-max(minOverlap, minInsert0);

	const jfloat probCorrect[71] =
	{0.000f, 0.251f, 0.369f, 0.499f, 0.602f, 0.684f, 0.749f, 0.800f, 0.842f, 0.874f, 0.900f, 0.921f, 0.937f, 0.950f, 0.960f, 0.968f,
	 0.975f, 0.980f, 0.984f, 0.987f, 0.990f, 0.992f, 0.994f, 0.995f, 0.996f, 0.997f, 0.997f, 0.998f, 0.998f, 0.999f, 0.999f, 0.999f,
	 0.999f, 0.999f, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};

	if(aqual!=NULL && bqual!=NULL){
		for(int i=0; i<alen; i++){aprob[i]=probCorrect[aqual[i]];}
		for(int i=0; i<blen; i++){bprob[i]=probCorrect[bqual[i]];}
	}else{
		for(int i=0; i<alen; i++){aprob[i]=0.98f;}
		for(int i=0; i<blen; i++){bprob[i]=0.98f;}
	}

	const jfloat minprob=probCorrect[mid(1, minq, 41)];

	for(jint overlap=max(minOverlap0, 0); overlap<maxOverlap; overlap++){
		jint good=0, bad=0;
		jint istart=(overlap<=alen ? 0 : overlap-alen);
		jint jstart=(overlap<=alen ? alen-overlap : 0);
		{
			const jint iters=min(overlap-istart, min(blen-istart, alen-jstart));
			const jint imax=istart+iters;
			const jint badlim=bestBad+margin;

			for(jint i=istart, j=jstart; i<imax && bad<=badlim; i++, j++){
				const jbyte ca1=abases[j], cb1=bbases[i];
				const jfloat pc=aprob[j]*bprob[j];

				if(pc<=minprob){//do nothing
				}else if(ca1==cb1){good++;}
				else{bad++;}
			}
		}

		if(bad*2<good){
			if(good>minOverlap){//Candidate
				if(bad<=bestBad){
					if(bad<bestBad || (bad==bestBad && good>bestGood)){//Current winner
						if(bestBad-bad<margin){ambig=1;}
						bestOverlap=overlap;
						bestBad=bad;
						bestGood=good;
					}else if(bad==bestBad){
						ambig=1;
					}

					if(ambig && bestBad<margin){
						rvector[2]=bestBad;
						rvector[4]=(ambig ? 1 : 0);
						return -1;
					}
				}
			}else if(bad<margin){
				ambig=1;
				rvector[2]=bestBad;
				rvector[4]=(ambig ? 1 : 0);
				return -1;
			}else{
			}
		}
	}

	if(!ambig && bestBad>maxMismatches-margin){bestOverlap=-1;}

	rvector[2]=bestBad;
	rvector[4]=(ambig ? 1 : 0);

	return (bestOverlap<0 ? -1 : alen+blen-bestOverlap);
}

jfloat findBestRatio(jbyte * a_bases, const jint a_bases_length, jbyte * b_bases, const jint b_bases_length, const jint minOverlap0, const jint minOverlap, const jint minInsert, const jfloat maxRatio, const jfloat offset, const jfloat gIncr, const jfloat bIncr) {
	const jbyte *abases=a_bases, *bbases=b_bases;
	const jint alen=a_bases_length, blen=b_bases_length;

	jfloat bestRatio=maxRatio+0.0001f;
	const jint maxOverlap=alen+blen-max(minOverlap, minInsert);
//	const jfloat altBadlimit=max(maxRatio, 0.07f)*2f*alen+1;
	const jfloat halfmax=maxRatio*0.5f;

	for(jint overlap=max(minOverlap0, 0); overlap<maxOverlap; overlap++){
		const jint istart=(overlap<=alen ? 0 : overlap-alen);
		const jint jstart=(overlap<=alen ? alen-overlap : 0);
		const jint overlapLength=min(alen-istart, min(blen-jstart, overlap-istart));

//		const jfloat badlimit=(min(altBadlimit, bestRatio*overlapLength));
		const jfloat badlimit=bestRatio*overlapLength;
		jfloat good=0, bad=0;

		const jint imax=istart+min(overlap-istart, min(blen-istart, alen-jstart));
		for(jint i=istart, j=jstart; i<imax && bad<=badlimit; i++, j++){
			const jbyte ca=abases[j], cb=bbases[i];

			if(ca==cb){good+=gIncr;}
			else{bad+=bIncr;}
		}

		if(bad<=badlimit){
			if(bad==0 && good>minOverlap0 && good<minOverlap){
				return 100.0f;
			}

			jfloat ratio=(bad+offset)/overlapLength;

			if(ratio<bestRatio){
				bestRatio=ratio;
				if(good>=minOverlap && ratio<halfmax){return bestRatio;}
			}
		}
	}

	return bestRatio;
}

jfloat findBestRatio_WithQualities(jbyte * a_bases, const jint a_bases_length, jbyte * b_bases, const jint b_bases_length, jbyte * a_quality, jbyte * b_quality, jfloat * aprob, jfloat * bprob, const jint minOverlap0, const jint minOverlap, const jint minInsert, const jfloat maxRatio, const jfloat offset) {
	const jbyte *abases=a_bases, *bbases=b_bases;
	const jint alen=a_bases_length, blen=b_bases_length;

	jfloat bestRatio=maxRatio+0.0001f;
	const jint maxOverlap=alen+blen-max(minOverlap, minInsert);
//	const jfloat altBadlimit=max(maxRatio, 0.07f)*2f*alen+1;
	const jfloat halfmax=maxRatio*0.5f;

	for(jint overlap=max(minOverlap0, 0); overlap<maxOverlap; overlap++){
		const jint istart=(overlap<=alen ? 0 : overlap-alen);
		const jint jstart=(overlap<=alen ? alen-overlap : 0);
		const jint overlapLength=min(alen-istart, min(blen-jstart, overlap-istart));

//		const jfloat badlimit=(min(altBadlimit, bestRatio*overlapLength));
		const jfloat badlimit=bestRatio*overlapLength;
		jfloat good=0, bad=0;

		const jint imax=istart+min(overlap-istart, min(blen-istart, alen-jstart));
		for(jint i=istart, j=jstart; i<imax && bad<=badlimit; i++, j++){
			const jbyte ca=abases[j], cb=bbases[i];
			const jfloat x=aprob[j]*bprob[i];

			if(ca==cb){good+=x;}
			else{bad+=x;}
		}

		if(bad<=badlimit){
			if(bad==0 && good>minOverlap0 && good<minOverlap){
				return 100.0f;
			}

			jfloat ratio=(bad+offset)/overlapLength;

			if(ratio<bestRatio){
				bestRatio=ratio;
				if(good>=minOverlap && ratio<halfmax){return bestRatio;}
			}
		}
	}

	return bestRatio;
}

jint mateByOverlapRatio_WithQualities(jbyte * a_bases, const jint a_bases_length, jbyte * b_bases, const jint b_bases_length, jbyte * a_quality, jbyte * b_quality, jfloat * aprob, jfloat * bprob, jint * rvector, jint minOverlap0, jint minOverlap, jint minInsert0, jint minInsert, jfloat maxRatio, const jfloat margin, const jfloat offset) {
	minOverlap=max(4, max(minOverlap0, minOverlap));
	minOverlap0=mid(4, minOverlap0, minOverlap);

        const jbyte *abases=a_bases, *bbases=b_bases, *aqual=a_quality, *bqual=b_quality;
        const jint alen=a_bases_length, blen=b_bases_length;
	const jint minLength=min(alen, blen);

	if(aqual!=NULL && bqual!=NULL){
		const jfloat probCorrect[71] =
		{0.000f, 0.251f, 0.369f, 0.499f, 0.602f, 0.684f, 0.749f, 0.800f, 0.842f, 0.874f, 0.900f, 0.921f, 0.937f, 0.950f, 0.960f, 0.968f,
	 	0.975f, 0.980f, 0.984f, 0.987f, 0.990f, 0.992f, 0.994f, 0.995f, 0.996f, 0.997f, 0.997f, 0.998f, 0.998f, 0.999f, 0.999f, 0.999f,
	 	0.999f, 0.999f, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};

		for(jint i=0; i<alen; i++){aprob[i]=probCorrect[aqual[i]];}
		for(jint i=0; i<blen; i++){bprob[i]=probCorrect[bqual[i]];}
	}else{
		for(jint i=0; i<alen; i++){aprob[i]=0.98f;}
		for(jint i=0; i<blen; i++){bprob[i]=0.98f;}
	}
	{
		jfloat x=findBestRatio_WithQualities(a_bases, a_bases_length, b_bases, b_bases_length, a_quality, b_quality, aprob, bprob, minOverlap0, minOverlap, minInsert, maxRatio, offset);
		if(x>maxRatio){
			rvector[2]=minLength;
			rvector[4]=0;
			return -1;
		}
		maxRatio=min(maxRatio, x);
	}

	const jfloat altBadlimit=max(maxRatio, 0.07f)*2.0f*alen+1;
	const jint maxOverlap=alen+blen-max(minOverlap, minInsert0);
	const jfloat margin2=(margin+offset)/minLength;

	jint bestOverlap=-1;
	jfloat bestBad=minLength;
	jfloat bestRatio=1;
	jboolean ambig=0;

	for(jint overlap=max(minOverlap0, 0); overlap<maxOverlap; overlap++){
		jfloat good=0, bad=0;

		const jint istart=(overlap<=alen ? 0 : overlap-alen);
		const jint jstart=(overlap<=alen ? alen-overlap : 0);

		const jint overlapLength=min(alen-istart, max(blen-jstart, overlap-istart));
		const jfloat badlimit=min(altBadlimit, min(bestRatio, maxRatio)*margin*overlapLength);

		const jint imax=istart+min(overlap-istart, max(blen-istart, alen-jstart));
		for(jint i=istart, j=jstart; i<imax && bad<=badlimit; i++, j++){
			const jbyte ca=abases[j], cb=bbases[i];
			const jfloat x=aprob[j]*bprob[i];

			if(ca==cb){good+=x;}
			else{bad+=x;}
		}

		if(bad<=badlimit){
			if(bad==0 && good>minOverlap0 && good<minOverlap){
				rvector[2]=(jint)bestBad;
				rvector[4]=1;
				return -1;
			}

			jfloat ratio=(bad+offset)/overlapLength;

			if(ratio<bestRatio*margin){

				ambig=(ratio*margin>=bestRatio || good<minOverlap);
				if(ratio<bestRatio){
					bestOverlap=overlap;
					bestBad=bad;
					bestRatio=ratio;
				}
				if(ambig && bestRatio<margin2){
					rvector[2]=(jint)bestBad;
					rvector[4]=1;
					return -1;
				}
			}
		}
	}

	if(!ambig && bestRatio>maxRatio){bestOverlap=-1;}

	rvector[2]=(jint)bestBad;
	rvector[4]=(ambig ? 1 : 0);

	return (bestOverlap<0 ? -1 : alen+blen-bestOverlap);

}

jint mateByOverlapRatio(jbyte * a_bases, const jint a_bases_length, jbyte * b_bases, const jint b_bases_length, jint * rvector, jint minOverlap0, jint minOverlap, const jint minInsert0, const jint minInsert, jfloat maxRatio, const jfloat margin, const jfloat offset, const jfloat gIncr, const jfloat bIncr) {

	minOverlap=max(4, max(minOverlap0, minOverlap));
	minOverlap0=mid(4, minOverlap0, minOverlap);

        const jbyte *abases=a_bases, *bbases=b_bases;
        const jint alen=a_bases_length, blen=b_bases_length;
	const jint minLength=min(alen, blen);
	{
		jfloat x=findBestRatio(a_bases, a_bases_length, b_bases, b_bases_length, minOverlap0, minOverlap, minInsert, maxRatio, offset, gIncr, bIncr);
		if(x>=maxRatio){
			rvector[2]=minLength;
			rvector[4]=0;
			return -1;
		}
		maxRatio=min(maxRatio, x);
	}

	const jint maxOverlap=alen+blen-max(minOverlap, minInsert0);
	const jfloat margin2=(margin+offset)/minLength;
	const jfloat altBadlimit=max(maxRatio, 0.07f)*2.0f*alen+1;

	jint bestOverlap=-1;
	jfloat bestBad=minLength;
	jfloat bestRatio=1;
	jboolean ambig=0;

	for(jint overlap=max(minOverlap0, 0); overlap<maxOverlap; overlap++){
		const jint istart=(overlap<=alen ? 0 : overlap-alen);
		const jint jstart=(overlap<=alen ? alen-overlap : 0);
		const jint overlapLength=min(alen-istart, min(blen-jstart, overlap-istart));

		const jfloat badlimit=(min(altBadlimit, min(bestRatio, maxRatio)*margin*overlapLength));
		jfloat good=0, bad=0;

		const int imax=istart+min(overlap-istart, min(blen-istart, alen-jstart));
		for(jint i=istart, j=jstart; i<imax && bad<=badlimit; i++, j++){
			const jbyte ca=abases[j], cb=bbases[i];

			if(ca==cb){good+=gIncr;}
			else{bad+=bIncr;}
		}

		if(bad<=badlimit){
			if(bad==0 && good>minOverlap0 && good<minOverlap){
				rvector[2]=(jint)bestBad;
				rvector[4]=1;
				return -1;
			}

			jfloat ratio=(bad+offset)/overlapLength;

			if(ratio<bestRatio*margin){
				ambig=(ratio*margin>=bestRatio || good<minOverlap);
				if(ratio<bestRatio){
					bestOverlap=overlap;
					bestBad=bad;
					bestRatio=ratio;
				}
				if(ambig && bestRatio<margin2){
					rvector[2]=(jint)bestBad;
					rvector[4]=1;
					return -1;
				}
			}
		}
	}

	if(!ambig && bestRatio>maxRatio){bestOverlap=-1;}

	rvector[2]=(jint)bestBad;
	rvector[4]=(ambig ? 1 : 0);

	return (bestOverlap<0 ? -1 : alen+blen-bestOverlap);

}

JNIEXPORT jint JNICALL Java_jgi_BBMergeOverlapper_mateByOverlapJNI_WithQualities(
							JNIEnv *env,
							jobject obj,
							jbyteArray a_bases,
							jbyteArray b_bases,
							jbyteArray a_quality,
							jbyteArray b_quality,
							jfloatArray aprob,
							jfloatArray bprob,
							jintArray rvector,
							jint minOverlap0,
							jint minOverlap,
							jint minInsert0,
							jint minInsert,
							jfloat maxRatio,
							jfloat margin,
							jfloat offset
                                                        ) {
   jbyte * ja_quality = NULL;
   jbyte * jb_quality = NULL;
   jfloat * japrob = NULL;
   jfloat * jbprob = NULL;

   // Get the size of the read and the reference arrays
   const jint a_bases_length = (*env)->GetArrayLength(env, a_bases);
   const jint b_bases_length = (*env)->GetArrayLength(env, b_bases);

   // Copy arrays from Java
   jbyte * ja_bases = (jbyte*)(*env)->GetPrimitiveArrayCritical(env, a_bases, NULL);
   jbyte * jb_bases = (jbyte*)(*env)->GetPrimitiveArrayCritical(env, b_bases, NULL);
   if(a_quality!=NULL) {ja_quality = (jbyte*)(*env)->GetPrimitiveArrayCritical(env, a_quality, NULL);}
   if(b_quality!=NULL) {jb_quality = (jbyte*)(*env)->GetPrimitiveArrayCritical(env, b_quality, NULL);}
   if(aprob!=NULL) {japrob = (jfloat*)(*env)->GetPrimitiveArrayCritical(env, aprob, NULL);}
   if(bprob!=NULL) {jbprob = (jfloat*)(*env)->GetPrimitiveArrayCritical(env, bprob, NULL);}
   jint * jrvector = (jint*)(*env)->GetPrimitiveArrayCritical(env, rvector, NULL);

   const jint returnVal = mateByOverlapRatio_WithQualities(ja_bases, a_bases_length, jb_bases, b_bases_length, ja_quality, jb_quality, japrob, jbprob, jrvector, minOverlap0, minOverlap, minInsert0, minInsert, maxRatio, margin, offset);

   // Release Java arrays; 0 copies the array back to Java, JNI_ABORT does not copy the current array values to Java
   (*env)->ReleasePrimitiveArrayCritical(env, a_bases, ja_bases, JNI_ABORT);
   (*env)->ReleasePrimitiveArrayCritical(env, b_bases, jb_bases, JNI_ABORT);
   if(ja_quality!=NULL) {(*env)->ReleasePrimitiveArrayCritical(env, a_quality, ja_quality, JNI_ABORT);}
   if(jb_quality!=NULL) {(*env)->ReleasePrimitiveArrayCritical(env, b_quality, jb_quality, JNI_ABORT);}
   if(japrob!=NULL) {(*env)->ReleasePrimitiveArrayCritical(env, aprob, japrob, JNI_ABORT);}
   if(jbprob!=NULL) {(*env)->ReleasePrimitiveArrayCritical(env, bprob, jbprob, JNI_ABORT);}
   (*env)->ReleasePrimitiveArrayCritical(env, rvector, jrvector, 0);

   return returnVal;
}

JNIEXPORT jint JNICALL Java_jgi_BBMergeOverlapper_mateByOverlapJNI(
							JNIEnv *env,
							jobject obj,
							jbyteArray a_bases,
							jbyteArray b_bases,
							jbyteArray a_quality,
							jbyteArray b_quality,
							jfloatArray aprob,
							jfloatArray bprob,
							jintArray rvector,
							jint minOverlap0,
							jint minOverlap,
							jint minInsert0,
							jint margin,
							jint maxMismatches0,
							jint maxMismatches,
							jint minq
                                                        ) {
   jbyte * ja_quality = NULL;
   jbyte * jb_quality = NULL;
   jfloat * japrob = NULL;
   jfloat * jbprob = NULL;

   // Get the size of the read and the reference arrays
   const jint a_bases_length = (*env)->GetArrayLength(env, a_bases);
   const jint b_bases_length = (*env)->GetArrayLength(env, b_bases);

   // Copy arrays from Java
   jbyte * ja_bases = (jbyte*)(*env)->GetPrimitiveArrayCritical(env, a_bases, NULL);
   jbyte * jb_bases = (jbyte*)(*env)->GetPrimitiveArrayCritical(env, b_bases, NULL);
   if(a_quality!=NULL) {ja_quality = (jbyte*)(*env)->GetPrimitiveArrayCritical(env, a_quality, NULL);}
   if(b_quality!=NULL) {jb_quality = (jbyte*)(*env)->GetPrimitiveArrayCritical(env, b_quality, NULL);}
   if(aprob!=NULL) {japrob = (jfloat*)(*env)->GetPrimitiveArrayCritical(env, aprob, NULL);}
   if(bprob!=NULL) {jbprob = (jfloat*)(*env)->GetPrimitiveArrayCritical(env, bprob, NULL);}
   jint * jrvector = (jint*)(*env)->GetPrimitiveArrayCritical(env, rvector, NULL);

   const jint returnVal = mateByOverlap(ja_bases, a_bases_length, jb_bases, b_bases_length, ja_quality, jb_quality, japrob, jbprob, jrvector, minOverlap0, minOverlap, minInsert0, margin, maxMismatches0, maxMismatches, minq);

   // Release Java arrays; 0 copies the array back to Java, JNI_ABORT does not copy the current array values to Java
   (*env)->ReleasePrimitiveArrayCritical(env, a_bases, ja_bases, JNI_ABORT);
   (*env)->ReleasePrimitiveArrayCritical(env, b_bases, jb_bases, JNI_ABORT);
   if(ja_quality!=NULL) {(*env)->ReleasePrimitiveArrayCritical(env, a_quality, ja_quality, JNI_ABORT);}
   if(jb_quality!=NULL) {(*env)->ReleasePrimitiveArrayCritical(env, b_quality, jb_quality, JNI_ABORT);}
   if(japrob!=NULL) {(*env)->ReleasePrimitiveArrayCritical(env, aprob, japrob, JNI_ABORT);}
   if(jbprob!=NULL) {(*env)->ReleasePrimitiveArrayCritical(env, bprob, jbprob, JNI_ABORT);}
   (*env)->ReleasePrimitiveArrayCritical(env, rvector, jrvector, 0);

   return returnVal;
}

JNIEXPORT jint JNICALL Java_jgi_BBMergeOverlapper_mateByOverlapRatioJNI(
							JNIEnv *env,
							jobject obj,
							jbyteArray a_bases,
							jbyteArray b_bases,
							jintArray rvector,
							jint minOverlap0,
							jint minOverlap,
							jint minInsert0,
							jint minInsert,
							jfloat maxRatio,
							jfloat margin,
							jfloat offset,
							jfloat gIncr,
							jfloat bIncr
                                                        ) {
   // Get the size of the read and the reference arrays
   const jint a_bases_length = (*env)->GetArrayLength(env, a_bases);
   const jint b_bases_length = (*env)->GetArrayLength(env, b_bases);

   // Copy arrays from Java
   jbyte * ja_bases = (jbyte*)(*env)->GetPrimitiveArrayCritical(env, a_bases, NULL);
   jbyte * jb_bases = (jbyte*)(*env)->GetPrimitiveArrayCritical(env, b_bases, NULL);
   jint * jrvector = (jint*)(*env)->GetPrimitiveArrayCritical(env, rvector, NULL);

   const jint returnVal = mateByOverlapRatio(ja_bases, a_bases_length, jb_bases, b_bases_length, jrvector, minOverlap0, minOverlap, minInsert0, minInsert, maxRatio, margin, offset, gIncr, bIncr);

   // Release Java arrays; 0 copies the array back to Java, JNI_ABORT does not copy the current array values to Java
   (*env)->ReleasePrimitiveArrayCritical(env, a_bases, ja_bases, JNI_ABORT);
   (*env)->ReleasePrimitiveArrayCritical(env, b_bases, jb_bases, JNI_ABORT);
   (*env)->ReleasePrimitiveArrayCritical(env, rvector, jrvector, 0);

   return returnVal;
}


text:
---
uid: SolidEdgeFrameworkSupport.TextEdit.ContinueNumbering
summary:
remarks:
---


text:
Classification (``classification``)
###################################

.. automodule:: Orange.classification

.. index:: logistic regression
   pair: classification; logistic regression

Logistic Regression
-------------------
.. autoclass:: LogisticRegressionLearner
   :members:

.. index:: random forest
   pair: classification; random forest

Random Forest
-------------
.. autoclass:: RandomForestLearner
   :members:

.. index:: random forest (simple)
   pair: classification; simple random forest

Simple Random Forest
--------------------

.. autoclass:: SimpleRandomForestLearner
   :members:

.. index:: softmax regression classifier
   pair: classification; softmax regression

Softmax Regression Classifier
-----------------------------

.. autoclass:: SoftmaxRegressionLearner
   :members:

.. index:: k-nearest neighbors classifier
   pair: classification; k-nearest neighbors

k-Nearest Neighbors
-------------------
.. autoclass:: KNNLearner
   :members:

.. index:: naive Bayes classifier
   pair: classification; naive Bayes

Naive Bayes
-----------
.. autoclass:: NaiveBayesLearner
   :members:

The following code loads lenses data set (four discrete attributes and discrete
class), constructs naive Bayesian learner, uses it on the entire data set
to construct a classifier, and then applies classifier to the first three
data instances:

    >>> import Orange
    >>> lenses = Orange.data.Table('lenses')
    >>> nb = Orange.classification.NaiveBayesLearner()
    >>> classifier = nb(lenses)
    >>> classifier(lenses[0:3], True)
    array([[ 0.04358755,  0.82671726,  0.12969519],
           [ 0.17428279,  0.20342097,  0.62229625],
           [ 0.18633359,  0.79518516,  0.01848125]])

For data sets that include continuous attributes,

.. _`Naive Bayes`: http://en.wikipedia.org/wiki/Naive_Bayes_classifier
.. _`scikit-learn`: http://scikit-learn.org

.. index:: multilayer perceptron
   pair: classification; multilayer perceptron

Multilayer perceptron (feed-forward neural network)
---------------------------------------------------
.. autoclass:: MLPLearner
   :members:

.. index:: SVM
   pair: classification; SVM

Support Vector Machines
-----------------------
.. autoclass:: SVMLearner
   :members:

.. index:: SVM, linear
   pair: classification; linear SVM

Linear Support Vector Machines
------------------------------
.. autoclass:: LinearSVMLearner
   :members:

.. index:: Nu-SVM
   pair: classification; Nu-SVM

Nu-Support Vector Machines
--------------------------
.. autoclass:: NuSVMLearner
   :members:

.. index:: classification tree
   pair: classification; tree

Classification Tree
-------------------
.. autoclass:: TreeLearner
   :members:

.. index:: classification tree (simple)
   pair: classification; simple tree

Simple Tree
-----------
.. autoclass:: SimpleTreeLearner
   :members:

.. index:: majority classifier
   pair: classification; majority

Majority Classifier
-------------------

.. autoclass:: MajorityLearner
   :members:


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>LiteSQL: Hierarchical Index</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Related Pages

Classes

Files

Directories

Class List

Class Hierarchy

Class Members

Class Hierarchy
Go to the graphical class hierarchy

This inheritance list is sorted roughly, but not completely, alphabetically:

litesql::Backend

litesql::Backend::Cursor

litesql::Cursor< T >

litesql::Database

litesql::Database::SchemaItem

litesql::DataSource< T >

litesql::Date

litesql::DateTime

litesql::Except

litesql::DatabaseError

litesql::InsertionError

litesql::InternalError

litesql::MemoryError

litesql::NotFound

litesql::SQLError

litesql::UnknownError

litesql::Expr

litesql::Connective

litesql::And

litesql::Or

litesql::Not

litesql::Oper

litesql::Eq

litesql::Gt

litesql::GtEq

litesql::In

litesql::Like

litesql::Lt

litesql::LtEq

litesql::NotEq

litesql::RawExpr

litesql::Field< T >

litesql::Persistent

litesql::Record

litesql::RelationHandle< T >

litesql::SelectQuery

litesql::Split

litesql::Time


text:
#include "halfling/halfling_engine.h"

#include "crate_demo/graphics_manager.h"
#include "crate_demo/game_state_manager.h"

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
	CrateDemo::GameStateManager gameStateManager;
	CrateDemo::GraphicsManager graphicsManager(&gameStateManager);

	Halfling::HalflingEngine engine(hInstance, &graphicsManager, &gameStateManager);

	engine.Initialize(L"Crate Demo", 800, 600, false);
	engine.Run();

	engine.Shutdown();

	return 0;
}


text:
package com.jonathancolt.nicity.core.collection;

/*
 * #%L
 * nicity-core
 * %%
 * Copyright (C) 2013 Jonathan Colt
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

import com.jonathancolt.nicity.core.lang.ICallback;
import com.jonathancolt.nicity.core.lang.IOut;
import com.jonathancolt.nicity.core.lang.UArray;
import com.jonathancolt.nicity.core.lang.UInteger;
import com.jonathancolt.nicity.core.lang.ULong;
import com.jonathancolt.nicity.core.observer.AObservable;

/**
 *
 * @author Administrator
 */
public class CSetOfLongs extends AObservable implements ISetOfLongs {

    //!! cNull = Long.MAX_VALUE would require extra work because zero is the initial memory state!
    static final long cNull = 0;//!! caution! reserved! don't use for a key!
    static final long cSkip = Long.MIN_VALUE;	//!! caution! reserved! don't use for a key!

    /**
     *
     * @param src
     * @return
     */
    public static long[] trim(long[] src) {
        int count = 0;
        int len = src.length;
        long[] array = new long[len];
        for (int i = 0; i < len; i++) {
            if (src[i] == cNull) {
                continue;
            }
            if (src[i] == cSkip) {
                continue;
            }
            array[count++] = src[i];
        }
        if (count < len) {
            array = UArray.trim(array, count);
        }
        return array;
    }

    /**
     *
     * @param src
     * @return
     */
    public static Long[] trimLongs(long[] src) {
        int count = 0;
        int len = src.length;
        Long[] array = new Long[len];
        for (int i = 0; i < len; i++) {
            if (src[i] == cNull) {
                continue;
            }
            if (src[i] == cSkip) {
                continue;
            }
            array[count++] = src[i];
        }
        if (count < len) {
            array = UArray.trim(array, count);
        }
        return array;
    }
    private int maxKeys;
    private int numKeys;
    private int primeLength;
    private long[] keys;
    private static int cMinKeys = 5; // based on aubjex parsing statistics, this is a good min

    /**
     *
     */
    public CSetOfLongs() {
        setMinimumAllocation();
    }

    /**
     *
     * @param _keys
     */
    public CSetOfLongs(long[] _keys) {
        this(_keys.length);
        for (int i = 0; i < _keys.length; i++) {
            add(_keys[i]);
        }
    }

    /**
     *
     * @param maxKeys
     */
    public CSetOfLongs(int maxKeys) {
        if (maxKeys <= cMinKeys) {
            setMinimumAllocation();
            return;
        }
        this.maxKeys = maxKeys;
        primeLength = UInteger.nextPrime(maxKeys + maxKeys / 3);
        numKeys = 0;
        keys = new long[primeLength];
    }

    synchronized private void grow() {
        if (numKeys < maxKeys) {
            return; // prevents possible waiting threads to re-grow needlessly
        }
        if (maxKeys < cMinKeys) {
            setMinimumAllocation();
            return;
        }
        CSetOfLongs grown = new CSetOfLongs(maxKeys + maxKeys / 2);
        for (int i = 0; i < keys.length; i++) {
            if (keys[i] == 0) {
                continue;
            }
            grown.add(keys[i]);
        }
        keys = grown.keys;
        maxKeys = grown.maxKeys;
        numKeys = grown.numKeys;
        primeLength = grown.primeLength;
        grown = null;
    }

    /**
     *
     */
    synchronized public void rehash() {
        CSetOfLongs grown = new CSetOfLongs(maxKeys);
        for (int i = 0; i < keys.length; i++) {
            if (keys[i] == 0) {
                continue;
            }
            grown.add(keys[i]);
        }
        keys = grown.keys;
        maxKeys = grown.maxKeys;
        numKeys = grown.numKeys;
        primeLength = grown.primeLength;
        grown = null;
    }

    synchronized private void setMinimumAllocation() {
        numKeys = 0;
        primeLength = cMinKeys;	// for such a small table, save space and don't worry about key collisions
        maxKeys = cMinKeys;
        keys = new long[primeLength];
        return;
    }

    /**
     *
     */
    public void free() {
    }

    /**
     *
     * @return
     */
    public int getSize() {
        return maxKeys;
    }

    /**
     *
     * @return
     */
    @Override
    public long getCount() {
        return numKeys;
    }

    /**
     *
     * @return
     */
    public long getMaxCount() {
        return maxKeys;
    }

    /**
     *
     * @return
     */
    public long rawSizeInBytes() {
        return keys.length * 8;
    }

    /**
     *
     * @return
     */
    @Override
    synchronized public long[] getAll() {
        return trim(keys);
    }

    /**
     *
     * @param _keys
     * @return
     */
    synchronized public long[] replaceAll(long[] _keys) {
        long[] removedValues = trim(keys);
        setMinimumAllocation();
        for (int i = 0; i < _keys.length; i++) {
            add(_keys[i]);
        }
        if (isBeingObserved()) {
            change("Write", null);
        }
        return removedValues;
    }

    /**
     *
     * @return
     */
    @Override
    synchronized public long[] removeAll() {
        long[] removedValues = trim(keys);
        setMinimumAllocation();
        if (isBeingObserved()) {
            change("Write", null);
        }
        return removedValues;
    }

    final private int hash(long key) {
        long hash = key;
        hash *= hash << 1;
        int result = (int) (hash % primeLength);
        if (result < 0) {
            result = -result;
        }
        return result;
    }

    /**
     *
     * @param _keys
     */
    synchronized public void add(long[] _keys) {
        for (long k : _keys) {
            add(k);
        }
    }

    /**
     *
     * @param key
     * @return
     */
    @Override
    synchronized public boolean add(long key) {
        if (key == 0) {
            return false;
        }

        if (maxKeys == 0) {
            setMinimumAllocation();
        }
        if (numKeys >= maxKeys) {
            grow();
        }
        for (int i = hash(key), j = 0, k = primeLength; // stack vars for efficiency
            j < k; // max search for available slot
            i = (++i) % k, j++ // wraps around table
            ) {

            if (keys[i] == key) {
                return false;
            }
            if (keys[i] == cNull) {
                keys[i] = key;
                numKeys++;
                if (isBeingObserved()) {
                    change("Write", null);
                }
                return true;
            }
        }
        return false;
    }

    /**
     *
     * @param _set
     * @throws Exception
     */
    public void add(CSetOfLongs _set) throws Exception {
        for (long l : _set.getAll()) {
            add(l);
        }
    }

    /**
     *
     * @param key
     * @return
     */
    @Override
    synchronized public boolean contains(long key) {
        if (maxKeys == 0) {
            return false;
        }
        if (key == 0) {
            return false;
        }

        for (int i = hash(key), j = 0, k = primeLength; // stack vars for efficiency
            j < k; // max search for key
            i = (++i) % k, j++) {						// wraps around table

            if (keys[i] == cNull) {
                return false;
            }
            if (keys[i] == key) {
                return true;
            }
        }
        return false;
    }

    /**
     *
     * @param key
     * @return
     */
    @Override
    synchronized public boolean remove(long key) {
        if (maxKeys == 0) {
            return false;
        }
        if (key == 0) {
            return false;
        }

        for (int i = hash(key), j = 0, k = primeLength; // stack vars for efficiency
            j < k; // max search for key
            i = (++i) % k, j++) {					// wraps around table

            if (keys[i] == cNull) {
                return false;
            }
            if (keys[i] == key) {
                keys[i] = cNull;
                numKeys--;

                int next = (i + 1) % k;
                if (keys[next] == cNull) {
                    for (int z = i; z >= 0; z--) {
                        if (keys[z] != cSkip) {
                            break;
                        }
                        keys[z] = cNull;
                    }
                    keys[i] = cNull;
                }
                else {
                    keys[i] = cSkip;
                }
                if (isBeingObserved()) {
                    change("Write", null);
                }
                return true;
            }
        }
        return false;
    }

    /**
     *
     * @param _
     * @param _callback
     */
    @Override
    public void backcall(IOut _, ICallback _callback) {
        try {
            long count = getCount();
            for (int i = 0; i < primeLength; i++) {
                if (count <= 0) {
                    break;
                }
                long key = keys[i];
                if (key == cSkip) {
                    continue;
                }
                if (key == cNull) {
                    continue;
                }
                byte[] ioKey = ULong.longBytes(key);
                Object back = _callback.callback(ioKey);
                if (back != ioKey) {
                    break;
                }
                if (_.canceled()) {
                    break;
                }
                count--;
            }
            return;
        }
        catch (Exception x) {
            return;
        }
    }
}


text:
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)

authorized_app = client \
    .authorized_connect_apps("CN47260e643654388faabe8aaa18ea6756") \
    .fetch()

print(authorized_app.connect_app_homepage_url)


text:
package org.seqcode.tools.location;

import java.io.*;
import java.util.*;

import org.seqcode.genome.Genome;
import org.seqcode.genome.location.Region;
import org.seqcode.gseutils.Args;

/**
 * Reads regions from two tab delimited files (you specify
 * the columns, default is first column) and determines
 * how many from the first file are present in the second
 * given some mismatch window.
 *
 * java RegionListOverlap --species "$MM;mm9" --one fileone.txt --two filetwo.txt --colone 0 --coltwo 3 --window 50 [--stats]
 *
 * --stats says to use --one as a test set and --two as a gold standard set to report the TP and FP rates for one
 */

public class RegionListOverlap {

    public static void main(String args[]) throws Exception {
        Map<String,List<Region>> one = new HashMap<String,List<Region>>();
        Map<String,List<Region>> two = new HashMap<String,List<Region>>();
        String fone = Args.parseString(args,"one",null);
        String ftwo = Args.parseString(args,"two",null);
        int colone = Args.parseInteger(args,"colone",0);
        int coltwo = Args.parseInteger(args,"coltwo",0);
        int window = Args.parseInteger(args,"window",0);
        Genome genome = Args.parseGenome(args).cdr();
        boolean stats = Args.parseFlags(args).contains("stats");

        readFile(genome, fone, colone, one);
        readFile(genome, ftwo, coltwo, two);

        int overlap = 0;
        int onecount = count(one);
        int twocount = count(two);

        Map<Region, Boolean> foundTwo = new HashMap<Region,Boolean>();
        for (String chrom : two.keySet()) {
            for (Region r : two.get(chrom)) {
                foundTwo.put(r,Boolean.FALSE);
            }
        }

        for (String chrom : one.keySet()) {
            if (!two.containsKey(chrom)) { continue;}
            List<Region> lone = one.get(chrom);
            List<Region> ltwo = two.get(chrom);
            Collections.sort(lone);
            Collections.sort(ltwo);
            for (Region orig : lone) {
                Region r = orig.expand(window,window);
                boolean found = false;
                for (Region o : ltwo) {
                    if (r.overlaps(o)) {
                        foundTwo.put(o, Boolean.TRUE);
                        if (stats) {
                            System.out.println("TP\t" + orig);
                        } else {
                            System.out.println(orig.toString());
                        }
                        overlap++;
                        found = true;
                        break;
                    }
                }
                if (stats && !found) {
                    System.out.println("FP\t" + orig);
                }

            }
        }
        int fn = 0;
        for (Region r : foundTwo.keySet()) {
            if (!foundTwo.get(r)) {
                System.out.println("FN\t" + r);
                fn++;
            }

        }

        if (stats) {
            int tp = overlap;
            int fp = onecount - overlap;
            double tprate = ((double)tp) / onecount;
            double fnrate = 1 - ((double)overlap) / twocount;
            System.out.println(String.format("n=%d  tp=%d  fp=%d  fn=%d   tpr=%.2f   fnr=%.2f",
                                             onecount, tp,fp,fn,tprate,fnrate));
        }
    }
    public static int count(Map<String,List<Region>> map) {
        int count = 0;
        for (String chrom : map.keySet()) {
            count += map.get(chrom).size();
        }
        return count;
    }
    public static void readFile(Genome genome, String fname, int column, Map<String,List<Region>> map) throws IOException {
        if (map == null) {
            throw new NullPointerException("Can't give me a null map");
        }
        BufferedReader reader = new BufferedReader(new FileReader(fname));
        String line = null;
        while ((line = reader.readLine()) != null) {
            String pieces[] = line.split("\\t");
            Region r = Region.fromString(genome, pieces[column]);
            if (r == null) {
                System.err.println("Couldn't parse " + pieces[column] + " in " + fname);
                continue;
            }
            if (!map.containsKey(r.getChrom())) {
                map.put(r.getChrom(), new ArrayList<Region>());
            }
            map.get(r.getChrom()).add(r);
        }
        reader.close();
    }

}


text:
"""Implements the VAEP framework."""
from . import features, formula, labels
from .base import VAEP

__all__ = ['VAEP', 'features', 'labels', 'formula']