answer stringlengths 15 1.25M |
|---|
#include <linux/bitops.h>
#include <linux/device.h>
#include <linux/errno.h>
#include <linux/iio/iio.h>
#include <linux/iio/types.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/isa.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#define STX104_NUM_CHAN 2
#define STX104_CHAN(chan) { \
.type = IIO_VOLTAGE, \
.channel = chan, \
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW), \
.indexed = 1, \
.output = 1 \
}
#define STX104_EXTENT 16
/**
* The highest base address possible for an ISA device is 0x3FF; this results in
* 1024 possible base addresses. Dividing the number of possible base addresses
* by the address extent taken by each device results in the maximum number of
* devices on a system.
*/
#define MAX_NUM_STX104 (1024 / STX104_EXTENT)
static unsigned base[MAX_NUM_STX104];
static unsigned num_stx104;
module_param_array(base, uint, &num_stx104, 0);
MODULE_PARM_DESC(base, "Apex Embedded Systems STX104 base addresses");
/**
* struct stx104_iio - IIO device private data structure
* @chan_out_states: channels' output states
* @base: base port address of the IIO device
*/
struct stx104_iio {
unsigned chan_out_states[STX104_NUM_CHAN];
unsigned base;
};
static int stx104_read_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan, int *val, int *val2, long mask)
{
struct stx104_iio *const priv = iio_priv(indio_dev);
if (mask != IIO_CHAN_INFO_RAW)
return -EINVAL;
*val = priv->chan_out_states[chan->channel];
return IIO_VAL_INT;
}
static int stx104_write_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan, int val, int val2, long mask)
{
struct stx104_iio *const priv = iio_priv(indio_dev);
const unsigned chan_addr_offset = 2 * chan->channel;
if (mask != IIO_CHAN_INFO_RAW)
return -EINVAL;
priv->chan_out_states[chan->channel] = val;
outw(val, priv->base + 4 + chan_addr_offset);
return 0;
}
static const struct iio_info stx104_info = {
.driver_module = THIS_MODULE,
.read_raw = stx104_read_raw,
.write_raw = stx104_write_raw
};
static const struct iio_chan_spec stx104_channels[STX104_NUM_CHAN] = {
STX104_CHAN(0),
STX104_CHAN(1)
};
static int stx104_probe(struct device *dev, unsigned int id)
{
struct iio_dev *indio_dev;
struct stx104_iio *priv;
indio_dev = <API key>(dev, sizeof(*priv));
if (!indio_dev)
return -ENOMEM;
if (!devm_request_region(dev, base[id], STX104_EXTENT,
dev_name(dev))) {
dev_err(dev, "Unable to lock port addresses (0x%X-0x%X)\n",
base[id], base[id] + STX104_EXTENT);
return -EBUSY;
}
indio_dev->info = &stx104_info;
indio_dev->modes = INDIO_DIRECT_MODE;
indio_dev->channels = stx104_channels;
indio_dev->num_channels = STX104_NUM_CHAN;
indio_dev->name = dev_name(dev);
priv = iio_priv(indio_dev);
priv->base = base[id];
/* initialize DAC output to 0V */
outw(0, base[id] + 4);
outw(0, base[id] + 6);
return <API key>(dev, indio_dev);
}
static struct isa_driver stx104_driver = {
.probe = stx104_probe,
.driver = {
.name = "stx104"
}
};
static void __exit stx104_exit(void)
{
<API key>(&stx104_driver);
}
static int __init stx104_init(void)
{
return isa_register_driver(&stx104_driver, num_stx104);
}
module_init(stx104_init);
module_exit(stx104_exit);
MODULE_AUTHOR("William Breathitt Gray <vilhelm.gray@gmail.com>");
MODULE_DESCRIPTION("Apex Embedded Systems STX104 DAC driver");
MODULE_LICENSE("GPL v2"); |
/*
* Modem Restart Notifier -- Provides notification
* of modem restart events.
*/
#include <linux/notifier.h>
#include <linux/init.h>
#include <linux/debugfs.h>
#include <linux/module.h>
#include <linux/workqueue.h>
#ifdef CONFIG_SEC_DEBUG
#include <mach/sec_debug.h>
#endif
#include "modem_notifier.h"
#define DEBUG
#ifdef <API key>
#include <asm/uaccess.h>
#include <linux/io.h>
#endif
static struct srcu_notifier_head modem_notifier_list;
static struct workqueue_struct *modem_notifier_wq;
static void <API key>(struct work_struct *work)
{
modem_notify(0, <API key>);
}
static DECLARE_WORK(<API key>, &<API key>);
void <API key>(void)
{
int ret;
ret = queue_work(modem_notifier_wq, &<API key>);
if (!ret)
printk(KERN_ERR "%s\n", __func__);
}
EXPORT_SYMBOL(<API key>);
static void <API key>(struct work_struct *work)
{
modem_notify(0, <API key>);
}
static DECLARE_WORK(<API key>, &<API key>);
void <API key>(void)
{
int ret;
ret = queue_work(modem_notifier_wq, &<API key>);
if (!ret)
printk(KERN_ERR "%s\n", __func__);
}
EXPORT_SYMBOL(<API key>);
static void <API key>(struct work_struct *work)
{
modem_notify(0, <API key>);
}
static DECLARE_WORK(<API key>, &<API key>);
void <API key>(void)
{
int ret;
ret = queue_work(modem_notifier_wq, &<API key>);
if (!ret)
printk(KERN_ERR "%s\n", __func__);
}
EXPORT_SYMBOL(<API key>);
int <API key>(struct notifier_block *nb)
{
int ret;
ret = <API key>(
&modem_notifier_list, nb);
return ret;
}
EXPORT_SYMBOL(<API key>);
int <API key>(struct notifier_block *nb)
{
int ret;
ret = <API key>(
&modem_notifier_list, nb);
return ret;
}
EXPORT_SYMBOL(<API key>);
void modem_notify(void *data, unsigned int state)
{
<API key>(&modem_notifier_list, state, data);
}
EXPORT_SYMBOL(modem_notify);
#if defined(CONFIG_DEBUG_FS)
static int debug_reset_start(const char __user *buf, int count)
{
<API key>();
return 0;
}
static int debug_reset_end(const char __user *buf, int count)
{
<API key>();
return 0;
}
static ssize_t debug_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
int (*fling)(const char __user *buf, int max) = file->private_data;
fling(buf, count);
return count;
}
static int debug_open(struct inode *inode, struct file *file)
{
file->private_data = inode->i_private;
return 0;
}
static const struct file_operations debug_ops = {
.write = debug_write,
.open = debug_open,
};
static void debug_create(const char *name, mode_t mode,
struct dentry *dent,
int (*fling)(const char __user *buf, int max))
{
debugfs_create_file(name, mode, dent, fling, &debug_ops);
}
static void <API key>(void)
{
struct dentry *dent;
dent = debugfs_create_dir("modem_notifier", 0);
if (IS_ERR(dent))
return;
debug_create("reset_start", 0444, dent, debug_reset_start);
debug_create("reset_end", 0444, dent, debug_reset_end);
}
#else
static void <API key>(void) {}
#endif
#define RESET_REASON_NORMAL 0x1A2B3C00
#if defined(DEBUG)
static int <API key>(struct notifier_block *this,
unsigned long code,
void *_cmd)
{
switch (code) {
case <API key>:
printk(KERN_ERR "Notify: start reset\n");
break;
case <API key>:
printk(KERN_ERR "Notify: end reset\n");
break;
case <API key>:
{
printk(KERN_ERR "Notify: smsm init\n");
#ifdef <API key>
if (<API key>() == 0 &&
<API key>() != RESET_REASON_NORMAL) {
loff_t pos = 0;
struct file *fp;
mm_segment_t old_fs;
static char dump_filename[100];
unsigned char *logicalKlogBase;
logicalKlogBase = ioremap(
(<API key>+8), 512*1024);
/* change to KERNEL_DS address limit */
old_fs = get_fs();
set_fs(get_ds());
/* open file to write */
sprintf(dump_filename, "/data/resetdump");
fp = filp_open(dump_filename,
O_WRONLY|O_CREAT, 0666);
if (!fp) {
printk(KERN_EMERG "failed to open the file\n");
goto exit;
}
/* Write buf to file */
fp->f_op->write(fp,
logicalKlogBase, 512*1024, &pos);
/* close file before return */
if (fp)
filp_close(fp, NULL);
exit:
/* restore previous address limit */
iounmap((void __iomem *)logicalKlogBase);
set_fs(old_fs);
}
#endif
break;
}
default:
printk(KERN_ERR "Notify: general\n");
break;
}
return NOTIFY_DONE;
}
static struct notifier_block nb = {
.notifier_call = <API key>,
};
static void <API key>(void)
{
<API key>(&nb);
}
#endif
int __init <API key>(void)
{
static bool registered;
if (registered)
return 0;
registered = true;
<API key>(&modem_notifier_list);
<API key>();
#if defined(DEBUG)
<API key>();
#endif
/* Create the workqueue */
modem_notifier_wq = <API key>("modem_notifier");
if (!modem_notifier_wq) {
<API key>(&modem_notifier_list);
return -ENOMEM;
}
return 0;
}
module_init(<API key>); |
#include "defs.h"
#include "regcache.h"
#include "alpha-tdep.h"
#include "alphabsd-tdep.h"
/* Conviently, GDB uses the same register numbering as the
ptrace register structure used by BSD on Alpha. */
void
alphabsd_supply_reg (struct regcache *regcache, const char *regs, int regno)
{
/* PC is at slot 32; UNIQUE not present. */
<API key> (regcache, regno, regs, regs + 31 * 8, NULL);
}
void
alphabsd_fill_reg (const struct regcache *regcache, char *regs, int regno)
{
/* PC is at slot 32; UNIQUE not present. */
alpha_fill_int_regs (regcache, regno, regs, regs + 31 * 8, NULL);
}
void
<API key> (struct regcache *regcache,
const char *fpregs, int regno)
{
/* FPCR is at slot 33; slot 32 unused. */
<API key> (regcache, regno, fpregs, fpregs + 32 * 8);
}
void
alphabsd_fill_fpreg (const struct regcache *regcache, char *fpregs, int regno)
{
/* FPCR is at slot 33; slot 32 unused. */
alpha_fill_fp_regs (regcache, regno, fpregs, fpregs + 32 * 8);
} |
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/signal.h>
#include <cpu/irq.h>
#include <asm/page.h>
/* Setup for the SMSC FDC37C935 / LAN91C100FD */
#define SMSC_IRQ IRQ_IRL1
/* Setup for PCI Bus 2, which transmits interrupts via the EPLD */
#define PCI2_IRQ IRQ_IRL3
unsigned long epld_virt;
#define EPLD_BASE 0x04002000
#define EPLD_STATUS_BASE (epld_virt + 0x10)
#define EPLD_MASK_BASE (epld_virt + 0x20)
/* Note the SMSC SuperIO chip and SMSC LAN chip interrupts are all muxed onto
the same SH-5 interrupt */
static irqreturn_t <API key>(int irq, void *dev_id)
{
printk(KERN_INFO "CAYMAN: spurious SMSC interrupt\n");
return IRQ_NONE;
}
static irqreturn_t <API key>(int irq, void *dev_id)
{
printk(KERN_INFO "CAYMAN: spurious PCI interrupt, IRQ %d\n", irq);
return IRQ_NONE;
}
static struct irqaction cayman_action_smsc = {
.name = "Cayman SMSC Mux",
.handler = <API key>,
.flags = IRQF_DISABLED,
};
static struct irqaction cayman_action_pci2 = {
.name = "Cayman PCI2 Mux",
.handler = <API key>,
.flags = IRQF_DISABLED,
};
static void enable_cayman_irq(unsigned int irq)
{
unsigned long flags;
unsigned long mask;
unsigned int reg;
unsigned char bit;
irq -= START_EXT_IRQS;
reg = EPLD_MASK_BASE + ((irq / 8) << 2);
bit = 1<<(irq % 8);
local_irq_save(flags);
mask = ctrl_inl(reg);
mask |= bit;
ctrl_outl(mask, reg);
local_irq_restore(flags);
}
void disable_cayman_irq(unsigned int irq)
{
unsigned long flags;
unsigned long mask;
unsigned int reg;
unsigned char bit;
irq -= START_EXT_IRQS;
reg = EPLD_MASK_BASE + ((irq / 8) << 2);
bit = 1<<(irq % 8);
local_irq_save(flags);
mask = ctrl_inl(reg);
mask &= ~bit;
ctrl_outl(mask, reg);
local_irq_restore(flags);
}
static void ack_cayman_irq(unsigned int irq)
{
disable_cayman_irq(irq);
}
static void end_cayman_irq(unsigned int irq)
{
if (!(irq_desc[irq].status & (IRQ_DISABLED|IRQ_INPROGRESS)))
enable_cayman_irq(irq);
}
static unsigned int startup_cayman_irq(unsigned int irq)
{
enable_cayman_irq(irq);
return 0; /* never anything pending */
}
static void shutdown_cayman_irq(unsigned int irq)
{
disable_cayman_irq(irq);
}
struct hw_interrupt_type cayman_irq_type = {
.typename = "Cayman-IRQ",
.startup = startup_cayman_irq,
.shutdown = shutdown_cayman_irq,
.enable = enable_cayman_irq,
.disable = disable_cayman_irq,
.ack = ack_cayman_irq,
.end = end_cayman_irq,
};
int cayman_irq_demux(int evt)
{
int irq = intc_evt_to_irq[evt];
if (irq == SMSC_IRQ) {
unsigned long status;
int i;
status = ctrl_inl(EPLD_STATUS_BASE) &
ctrl_inl(EPLD_MASK_BASE) & 0xff;
if (status == 0) {
irq = -1;
} else {
for (i=0; i<8; i++) {
if (status & (1<<i))
break;
}
irq = START_EXT_IRQS + i;
}
}
if (irq == PCI2_IRQ) {
unsigned long status;
int i;
status = ctrl_inl(EPLD_STATUS_BASE + 3 * sizeof(u32)) &
ctrl_inl(EPLD_MASK_BASE + 3 * sizeof(u32)) & 0xff;
if (status == 0) {
irq = -1;
} else {
for (i=0; i<8; i++) {
if (status & (1<<i))
break;
}
irq = START_EXT_IRQS + (3 * 8) + i;
}
}
return irq;
}
#if defined(CONFIG_PROC_FS) && defined(CONFIG_SYSCTL)
int cayman_irq_describe(char* p, int irq)
{
if (irq < NR_INTC_IRQS) {
return intc_irq_describe(p, irq);
} else if (irq < NR_INTC_IRQS + 8) {
return sprintf(p, "(SMSC %d)", irq - NR_INTC_IRQS);
} else if ((irq >= NR_INTC_IRQS + 24) && (irq < NR_INTC_IRQS + 32)) {
return sprintf(p, "(PCI2 %d)", irq - (NR_INTC_IRQS + 24));
}
return 0;
}
#endif
void init_cayman_irq(void)
{
int i;
epld_virt = onchip_remap(EPLD_BASE, 1024, "EPLD");
if (!epld_virt) {
printk(KERN_ERR "Cayman IRQ: Unable to remap EPLD\n");
return;
}
for (i=0; i<NR_EXT_IRQS; i++) {
irq_desc[START_EXT_IRQS + i].chip = &cayman_irq_type;
}
/* Setup the SMSC interrupt */
setup_irq(SMSC_IRQ, &cayman_action_smsc);
setup_irq(PCI2_IRQ, &cayman_action_pci2);
} |
public class TestCaseSwitch {
@AliveRange(varName="o", bytecodeStart=31, bytecodeLength=16)
@AliveRange(varName="o", bytecodeStart=50, bytecodeLength=15)
@AliveRange(varName="o", bytecodeStart=68, bytecodeLength=1)
@AliveRange(varName="oo", bytecodeStart=39, bytecodeLength=8)
@AliveRange(varName="uu", bytecodeStart=59, bytecodeLength=6)
void m1(String[] args) {
Object o;
switch (args.length) {
case 0:
o = "0";
o.hashCode();
Object oo = "oo";
oo.hashCode();
break;
case 1:
o = "1";
o.hashCode();
Object uu = "uu";
uu.hashCode();
break;
}
o = "return";
}
@AliveRange(varName="o", bytecodeStart=95, bytecodeLength=18)
@AliveRange(varName="o", bytecodeStart=116, bytecodeLength=15)
@AliveRange(varName="o", bytecodeStart=134, bytecodeLength=1)
@AliveRange(varName="oo", bytecodeStart=104, bytecodeLength=9)
@AliveRange(varName="uu", bytecodeStart=125, bytecodeLength=6)
void m2(String[] args) {
Object o;
switch (args[0]) {
case "string0":
o = "0";
o.hashCode();
Object oo = "oo";
oo.hashCode();
break;
case "string1":
o = "1";
o.hashCode();
Object uu = "uu";
uu.hashCode();
break;
}
o = "return";
}
@AliveRange(varName="o", bytecodeStart=35, bytecodeLength=8)
@AliveRange(varName="o", bytecodeStart=46, bytecodeLength=8)
@AliveRange(varName="o", bytecodeStart=78, bytecodeLength=5)
@AliveRange(varName="o", bytecodeStart=86, bytecodeLength=1)
@AliveRange(varName="oo", bytecodeStart=56, bytecodeLength=16)
void m3(int i) {
Object o;
switch (i) {
case 0:
o = "0";
o.hashCode();
break;
case 1:
o = "1";
o.hashCode();
break;
case 2:
int oo = i;
if (oo > 1) {
System.out.println("greater");
}
break;
case 3:
int uu = i;
default:
o = "default";
o.hashCode();
}
o = "finish";
}
@AliveRange(varName="oCache", bytecodeStart=30, bytecodeLength=6)
@AliveRange(varName="cache", bytecodeStart=41, bytecodeLength=3)
@AliveRange(varName="cache", bytecodeStart=54, bytecodeLength=2)
@AliveRange(varName="service", bytecodeStart=39, bytecodeLength=5)
Object m4(int i) {
Object cache;
switch (i) {
case 0:
Object oCache = null;
if (oCache != null) {
return oCache;
}
case 1:
Object service = null;
cache = null;
break;
default:
throw new AssertionError("");
}
return cache;
}
} |
<?php
// This program is free software; you can redistribute it and/or
// as published by the Free Software Foundation; either version 2
class AmcResult implements RsResultIF
{
public $rule;
// public $numeratorLabel;
// public $populationLabel;
public $totalPatients; // Total number of patients considered
public $<API key>; // Number of patients that pass filter
public $patientsExcluded; // Number of patients that are excluded
public $patientsIncluded; // Number of patients that pass target
public $percentage; // Calculated percentage
public function __construct( $rowRule, $totalPatients, $<API key>, $patientsExcluded, $patientsIncluded, $percentage )
{
$this->rule = $rowRule;
// $this->numeratorLabel = $numeratorLabel;
// $this->populationLabel = $populationLabel;
$this->totalPatients = $totalPatients;
$this-><API key> = $<API key>;
$this->patientsExcluded = $patientsExcluded;
$this->patientsIncluded = $patientsIncluded;
$this->percentage = $percentage;
// If itemization is turned on, then record the itemized_test_id
if ($GLOBALS['<API key>']) {
$this->itemized_test_id = array('itemized_test_id' => $GLOBALS['<API key>']);
}
}
public function format()
{
$rowFormat = array(
'is_main'=>TRUE, // TO DO: figure out way to do this when multiple groups.
// 'population_label' => $this->populationLabel,
// 'numerator_label' => $this->numeratorLabel,
'total_patients' => $this->totalPatients,
'excluded' => $this->patientsExcluded,
'pass_filter' => $this-><API key>,
'pass_target' => $this->patientsIncluded,
'percentage' => $this->percentage );
$rowFormat = array_merge( $rowFormat, $this->rule );
// If itemization is turned on, then record the itemized_test_id
if ($GLOBALS['<API key>']) {
$rowFormat = array_merge( $rowFormat, $this->itemized_test_id );
}
return $rowFormat;
}
} |
package docker
import (
"bytes"
"fmt"
"regexp"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/schema"
)
func <API key>() *schema.Resource {
return &schema.Resource{
Create: <API key>,
Read: <API key>,
Update: <API key>,
Delete: <API key>,
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
// Indicates whether the container must be running.
// An assumption is made that configured containers
// should be running; if not, they should not be in
// the configuration. Therefore a stopped container
// should be started. Set to false to have the
// provider leave the container alone.
// Actively-debugged containers are likely to be
// stopped and started manually, and Docker has
// some provisions for restarting containers that
// stop. The utility here comes from the fact that
// this will delete and re-create the container
// following the principle that the containers
// should be pristine when started.
"must_run": &schema.Schema{
Type: schema.TypeBool,
Default: true,
Optional: true,
},
// ForceNew is not true for image because we need to
// sane this against Docker image IDs, as each image
// can have multiple names/tags attached do it.
"image": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"hostname": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"domainname": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"command": &schema.Schema{
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"entrypoint": &schema.Schema{
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"user": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"dns": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"dns_opts": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"dns_search": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"publish_all_ports": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"restart": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "no",
ValidateFunc: func(v interface{}, k string) (ws []string, es []error) {
value := v.(string)
if !regexp.MustCompile(`^(no|on-failure|always|unless-stopped)$`).MatchString(value) {
es = append(es, fmt.Errorf(
"%q must be one of \"no\", \"on-failure\", \"always\" or \"unless-stopped\"", k))
}
return
},
},
"max_retry_count": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"capabilities": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"add": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"drop": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
},
},
Set: <API key>,
},
"volumes": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"from_container": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"container_path": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"host_path": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: func(v interface{}, k string) (ws []string, es []error) {
value := v.(string)
if !regexp.MustCompile(`^/`).MatchString(value) {
es = append(es, fmt.Errorf(
"%q must be an absolute path", k))
}
return
},
},
"volume_name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"read_only": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
},
},
Set: <API key>,
},
"ports": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"internal": &schema.Schema{
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},
"external": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
"ip": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"protocol": &schema.Schema{
Type: schema.TypeString,
Default: "tcp",
Optional: true,
ForceNew: true,
},
},
},
Set: <API key>,
},
"host": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ip": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"host": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
},
Set: <API key>,
},
"env": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"links": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"ip_address": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"ip_prefix_length": &schema.Schema{
Type: schema.TypeInt,
Computed: true,
},
"gateway": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"bridge": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"privileged": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"<API key>": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
},
"labels": &schema.Schema{
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
},
"memory": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: func(v interface{}, k string) (ws []string, es []error) {
value := v.(int)
if value < 0 {
es = append(es, fmt.Errorf("%q must be greater than or equal to 0", k))
}
return
},
},
"memory_swap": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: func(v interface{}, k string) (ws []string, es []error) {
value := v.(int)
if value < -1 {
es = append(es, fmt.Errorf("%q must be greater than or equal to -1", k))
}
return
},
},
"cpu_shares": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
ValidateFunc: func(v interface{}, k string) (ws []string, es []error) {
value := v.(int)
if value < 0 {
es = append(es, fmt.Errorf("%q must be greater than or equal to 0", k))
}
return
},
},
"log_driver": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "json-file",
ValidateFunc: func(v interface{}, k string) (ws []string, es []error) {
value := v.(string)
if !regexp.MustCompile(`^(json-file|syslog|journald|gelf|fluentd)$`).MatchString(value) {
es = append(es, fmt.Errorf(
"%q must be one of \"json-file\", \"syslog\", \"journald\", \"gelf\", or \"fluentd\"", k))
}
return
},
},
"log_opts": &schema.Schema{
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
},
"network_mode": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"networks": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"upload": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"content": &schema.Schema{
Type: schema.TypeString,
Required: true,
// This is intentional. The container is mutated once, and never updated later.
// New configuration forces a new deployment, even with the same binaries.
ForceNew: true,
},
"file": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
},
Set: <API key>,
},
},
}
}
func <API key>(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
if v, ok := m["add"]; ok {
buf.WriteString(fmt.Sprintf("%v-", v))
}
if v, ok := m["remove"]; ok {
buf.WriteString(fmt.Sprintf("%v-", v))
}
return hashcode.String(buf.String())
}
func <API key>(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%v-", m["internal"].(int)))
if v, ok := m["external"]; ok {
buf.WriteString(fmt.Sprintf("%v-", v.(int)))
}
if v, ok := m["ip"]; ok {
buf.WriteString(fmt.Sprintf("%v-", v.(string)))
}
if v, ok := m["protocol"]; ok {
buf.WriteString(fmt.Sprintf("%v-", v.(string)))
}
return hashcode.String(buf.String())
}
func <API key>(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
if v, ok := m["ip"]; ok {
buf.WriteString(fmt.Sprintf("%v-", v.(string)))
}
if v, ok := m["host"]; ok {
buf.WriteString(fmt.Sprintf("%v-", v.(string)))
}
return hashcode.String(buf.String())
}
func <API key>(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
if v, ok := m["from_container"]; ok {
buf.WriteString(fmt.Sprintf("%v-", v.(string)))
}
if v, ok := m["container_path"]; ok {
buf.WriteString(fmt.Sprintf("%v-", v.(string)))
}
if v, ok := m["host_path"]; ok {
buf.WriteString(fmt.Sprintf("%v-", v.(string)))
}
if v, ok := m["volume_name"]; ok {
buf.WriteString(fmt.Sprintf("%v-", v.(string)))
}
if v, ok := m["read_only"]; ok {
buf.WriteString(fmt.Sprintf("%v-", v.(bool)))
}
return hashcode.String(buf.String())
}
func <API key>(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
if v, ok := m["content"]; ok {
buf.WriteString(fmt.Sprintf("%v-", v.(string)))
}
if v, ok := m["file"]; ok {
buf.WriteString(fmt.Sprintf("%v-", v.(string)))
}
return hashcode.String(buf.String())
} |
// Generated by the J2ObjC translator. DO NOT EDIT!
#ifndef <API key>
#define <API key>
#include "J2ObjC_header.h"
@class IOSObjectArray;
@class <API key>;
@class <API key>;
@protocol JavaUtilCollection;
@protocol JavaUtilIterator;
@protocol JavaUtilMap;
@protocol JavaUtilSet;
@interface <API key> : NSObject
#pragma mark Public
- (instancetype)init;
- (instancetype)<API key>:(<API key> *)jo
withNSStringArray:(IOSObjectArray *)names;
- (instancetype)<API key>:(<API key> *)x;
- (instancetype)initWithJavaUtilMap:(id<JavaUtilMap>)map;
- (instancetype)initWithNSString:(NSString *)source;
- (<API key> *)<API key>:(NSString *)key
withId:(id)value;
- (<API key> *)appendWithNSString:(NSString *)key
withId:(id)value;
+ (NSString *)<API key>:(jdouble)d;
- (id)getWithNSString:(NSString *)key;
- (jboolean)<API key>:(NSString *)key;
- (jdouble)<API key>:(NSString *)key;
- (jint)getIntWithNSString:(NSString *)key;
- (<API key> *)<API key>:(NSString *)key;
- (<API key> *)<API key>:(NSString *)key;
- (jlong)getLongWithNSString:(NSString *)key;
+ (IOSObjectArray *)<API key>:(<API key> *)jo;
- (NSString *)<API key>:(NSString *)key;
- (jboolean)hasWithNSString:(NSString *)key;
- (<API key> *)<API key>:(NSString *)key;
- (jboolean)isNullWithNSString:(NSString *)key;
- (id<JavaUtilIterator>)keys;
- (id<JavaUtilSet>)keySet;
- (jint)length;
- (<API key> *)names;
+ (NSString *)<API key>:(NSNumber *)number;
- (id)optWithNSString:(NSString *)key;
- (jboolean)<API key>:(NSString *)key;
- (jboolean)<API key>:(NSString *)key
withBoolean:(jboolean)defaultValue;
- (jdouble)<API key>:(NSString *)key;
- (jdouble)<API key>:(NSString *)key
withDouble:(jdouble)defaultValue;
- (jint)optIntWithNSString:(NSString *)key;
- (jint)optIntWithNSString:(NSString *)key
withInt:(jint)defaultValue;
- (<API key> *)<API key>:(NSString *)key;
- (<API key> *)<API key>:(NSString *)key;
- (jlong)optLongWithNSString:(NSString *)key;
- (jlong)optLongWithNSString:(NSString *)key
withLong:(jlong)defaultValue;
- (NSString *)<API key>:(NSString *)key;
- (NSString *)<API key>:(NSString *)key
withNSString:(NSString *)defaultValue;
- (<API key> *)putWithNSString:(NSString *)key
withBoolean:(jboolean)value;
- (<API key> *)putWithNSString:(NSString *)key
<API key>:(id<JavaUtilCollection>)value;
- (<API key> *)putWithNSString:(NSString *)key
withDouble:(jdouble)value;
- (<API key> *)putWithNSString:(NSString *)key
withInt:(jint)value;
- (<API key> *)putWithNSString:(NSString *)key
withLong:(jlong)value;
- (<API key> *)putWithNSString:(NSString *)key
withJavaUtilMap:(id<JavaUtilMap>)value;
- (<API key> *)putWithNSString:(NSString *)key
withId:(id)value;
- (<API key> *)putOnceWithNSString:(NSString *)key
withId:(id)value;
- (<API key> *)putOptWithNSString:(NSString *)key
withId:(id)value;
- (id)removeWithNSString:(NSString *)key;
- (jboolean)similarWithId:(id)other;
+ (id)<API key>:(NSString *)string;
+ (void)testValidityWithId:(id)o;
- (<API key> *)<API key>:(<API key> *)names;
@end
J2OBJC_STATIC_INIT(<API key>)
FOUNDATION_EXPORT id <API key>;
<API key>(<API key>, NULL__, id)
FOUNDATION_EXPORT void <API key>(<API key> *self);
FOUNDATION_EXPORT <API key> *<API key>() NS_RETURNS_RETAINED;
FOUNDATION_EXPORT void ImActorModelDroidkitJsonJSONObject_initWithImActorModelDroidkitJsonJSONObject_withNSStringArray_(<API key> *self, <API key> *jo, IOSObjectArray *names);
FOUNDATION_EXPORT <API key> *new_ImActorModelDroidkitJsonJSONObject_initWithImActorModelDroidkitJsonJSONObject_withNSStringArray_(<API key> *jo, IOSObjectArray *names) NS_RETURNS_RETAINED;
FOUNDATION_EXPORT void <API key>(<API key> *self, <API key> *x);
FOUNDATION_EXPORT <API key> *new_ImActorModelDroidkitJsonJSONObject_initWithImActorModelDroidkitJsonJSONTokener_(<API key> *x) NS_RETURNS_RETAINED;
FOUNDATION_EXPORT void <API key>(<API key> *self, id<JavaUtilMap> map);
FOUNDATION_EXPORT <API key> *<API key>(id<JavaUtilMap> map) NS_RETURNS_RETAINED;
FOUNDATION_EXPORT void <API key>(<API key> *self, NSString *source);
FOUNDATION_EXPORT <API key> *<API key>(NSString *source) NS_RETURNS_RETAINED;
FOUNDATION_EXPORT NSString *<API key>(jdouble d);
FOUNDATION_EXPORT IOSObjectArray *ImActorModelDroidkitJsonJSONObject_getNamesWithImActorModelDroidkitJsonJSONObject_(<API key> *jo);
FOUNDATION_EXPORT NSString *<API key>(NSNumber *number);
FOUNDATION_EXPORT id <API key>(NSString *string);
FOUNDATION_EXPORT void <API key>(id o);
<API key>(<API key>)
#endif // <API key> |
<?php
return array(
'helper' => array(
'system' => 'Warp\Joomla\Helper\SystemHelper',
'option' => 'Warp\Joomla\Helper\OptionHelper',
'widgets' => 'Warp\Joomla\Helper\WidgetsHelper'
),
'path' => array(
'config' => array(__DIR__.'/config'),
'layouts' => array(__DIR__.'/layouts')
),
'menu' => array(
'pre' => 'Warp\Joomla\Menu\Pre'
)
); |
/* $Id: blake.c 252 2011-06-07 17:55:14Z tp $ */
#include <stddef.h>
#include <string.h>
#include <limits.h>
#include "sph_blake.h"
#if SPH_SMALL_FOOTPRINT && !defined <API key>
#define <API key> 1
#endif
#if <API key>
#define <API key> 1
#endif
#if SPH_64 && (<API key> || !SPH_64_TRUE)
#define <API key> 1
#endif
#ifdef _MSC_VER
#pragma warning (disable: 4146)
#endif
static const sph_u32 IV224[8] = {
SPH_C32(0xC1059ED8), SPH_C32(0x367CD507),
SPH_C32(0x3070DD17), SPH_C32(0xF70E5939),
SPH_C32(0xFFC00B31), SPH_C32(0x68581511),
SPH_C32(0x64F98FA7), SPH_C32(0xBEFA4FA4)
};
static const sph_u32 IV256[8] = {
SPH_C32(0x6A09E667), SPH_C32(0xBB67AE85),
SPH_C32(0x3C6EF372), SPH_C32(0xA54FF53A),
SPH_C32(0x510E527F), SPH_C32(0x9B05688C),
SPH_C32(0x1F83D9AB), SPH_C32(0x5BE0CD19)
};
#if SPH_64
static const sph_u64 IV384[8] = {
SPH_C64(0xCBBB9D5DC1059ED8), SPH_C64(0x629A292A367CD507),
SPH_C64(0x9159015A3070DD17), SPH_C64(0x152FECD8F70E5939),
SPH_C64(0x67332667FFC00B31), SPH_C64(0x8EB44A8768581511),
SPH_C64(0xDB0C2E0D64F98FA7), SPH_C64(0x47B5481DBEFA4FA4)
};
static const sph_u64 IV512[8] = {
SPH_C64(0x6A09E667F3BCC908), SPH_C64(0xBB67AE8584CAA73B),
SPH_C64(0x3C6EF372FE94F82B), SPH_C64(0xA54FF53A5F1D36F1),
SPH_C64(0x510E527FADE682D1), SPH_C64(0x9B05688C2B3E6C1F),
SPH_C64(0x1F83D9ABFB41BD6B), SPH_C64(0x5BE0CD19137E2179)
};
#endif
#if <API key> || <API key>
static const unsigned sigma[16][16] = {
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 },
{ 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 },
{ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 },
{ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 },
{ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 },
{ 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 },
{ 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 },
{ 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 },
{ 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 },
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 },
{ 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 },
{ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 },
{ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 },
{ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }
};
/*
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
14 10 4 8 9 15 13 6 1 12 0 2 11 7 5 3
11 8 12 0 5 2 15 13 10 14 3 6 7 1 9 4
7 9 3 1 13 12 11 14 2 6 5 10 4 0 15 8
9 0 5 7 2 4 10 15 14 1 11 12 6 8 3 13
2 12 6 10 0 11 8 3 4 13 7 5 15 14 1 9
12 5 1 15 14 13 4 10 0 7 6 3 9 2 8 11
13 11 7 14 12 1 3 9 5 0 15 4 8 6 2 10
6 15 14 9 11 3 0 8 12 2 13 7 1 4 10 5
10 2 8 4 7 6 1 5 15 11 9 14 3 12 13 0
*/
#endif
#define Z00 0
#define Z01 1
#define Z02 2
#define Z03 3
#define Z04 4
#define Z05 5
#define Z06 6
#define Z07 7
#define Z08 8
#define Z09 9
#define Z0A A
#define Z0B B
#define Z0C C
#define Z0D D
#define Z0E E
#define Z0F F
#define Z10 E
#define Z11 A
#define Z12 4
#define Z13 8
#define Z14 9
#define Z15 F
#define Z16 D
#define Z17 6
#define Z18 1
#define Z19 C
#define Z1A 0
#define Z1B 2
#define Z1C B
#define Z1D 7
#define Z1E 5
#define Z1F 3
#define Z20 B
#define Z21 8
#define Z22 C
#define Z23 0
#define Z24 5
#define Z25 2
#define Z26 F
#define Z27 D
#define Z28 A
#define Z29 E
#define Z2A 3
#define Z2B 6
#define Z2C 7
#define Z2D 1
#define Z2E 9
#define Z2F 4
#define Z30 7
#define Z31 9
#define Z32 3
#define Z33 1
#define Z34 D
#define Z35 C
#define Z36 B
#define Z37 E
#define Z38 2
#define Z39 6
#define Z3A 5
#define Z3B A
#define Z3C 4
#define Z3D 0
#define Z3E F
#define Z3F 8
#define Z40 9
#define Z41 0
#define Z42 5
#define Z43 7
#define Z44 2
#define Z45 4
#define Z46 A
#define Z47 F
#define Z48 E
#define Z49 1
#define Z4A B
#define Z4B C
#define Z4C 6
#define Z4D 8
#define Z4E 3
#define Z4F D
#define Z50 2
#define Z51 C
#define Z52 6
#define Z53 A
#define Z54 0
#define Z55 B
#define Z56 8
#define Z57 3
#define Z58 4
#define Z59 D
#define Z5A 7
#define Z5B 5
#define Z5C F
#define Z5D E
#define Z5E 1
#define Z5F 9
#define Z60 C
#define Z61 5
#define Z62 1
#define Z63 F
#define Z64 E
#define Z65 D
#define Z66 4
#define Z67 A
#define Z68 0
#define Z69 7
#define Z6A 6
#define Z6B 3
#define Z6C 9
#define Z6D 2
#define Z6E 8
#define Z6F B
#define Z70 D
#define Z71 B
#define Z72 7
#define Z73 E
#define Z74 C
#define Z75 1
#define Z76 3
#define Z77 9
#define Z78 5
#define Z79 0
#define Z7A F
#define Z7B 4
#define Z7C 8
#define Z7D 6
#define Z7E 2
#define Z7F A
#define Z80 6
#define Z81 F
#define Z82 E
#define Z83 9
#define Z84 B
#define Z85 3
#define Z86 0
#define Z87 8
#define Z88 C
#define Z89 2
#define Z8A D
#define Z8B 7
#define Z8C 1
#define Z8D 4
#define Z8E A
#define Z8F 5
#define Z90 A
#define Z91 2
#define Z92 8
#define Z93 4
#define Z94 7
#define Z95 6
#define Z96 1
#define Z97 5
#define Z98 F
#define Z99 B
#define Z9A 9
#define Z9B E
#define Z9C 3
#define Z9D C
#define Z9E D
#define Z9F 0
#define Mx(r, i) Mx_(Z ## r ## i)
#define Mx_(n) Mx__(n)
#define Mx__(n) M
#define CSx(r, i) CSx_(Z ## r ## i)
#define CSx_(n) CSx__(n)
#define CSx__(n) CS
#define CS0 SPH_C32(0x243F6A88)
#define CS1 SPH_C32(0x85A308D3)
#define CS2 SPH_C32(0x13198A2E)
#define CS3 SPH_C32(0x03707344)
#define CS4 SPH_C32(0xA4093822)
#define CS5 SPH_C32(0x299F31D0)
#define CS6 SPH_C32(0x082EFA98)
#define CS7 SPH_C32(0xEC4E6C89)
#define CS8 SPH_C32(0x452821E6)
#define CS9 SPH_C32(0x38D01377)
#define CSA SPH_C32(0xBE5466CF)
#define CSB SPH_C32(0x34E90C6C)
#define CSC SPH_C32(0xC0AC29B7)
#define CSD SPH_C32(0xC97C50DD)
#define CSE SPH_C32(0x3F84D5B5)
#define CSF SPH_C32(0xB5470917)
#if <API key>
static const sph_u32 CS[16] = {
SPH_C32(0x243F6A88), SPH_C32(0x85A308D3),
SPH_C32(0x13198A2E), SPH_C32(0x03707344),
SPH_C32(0xA4093822), SPH_C32(0x299F31D0),
SPH_C32(0x082EFA98), SPH_C32(0xEC4E6C89),
SPH_C32(0x452821E6), SPH_C32(0x38D01377),
SPH_C32(0xBE5466CF), SPH_C32(0x34E90C6C),
SPH_C32(0xC0AC29B7), SPH_C32(0xC97C50DD),
SPH_C32(0x3F84D5B5), SPH_C32(0xB5470917)
};
#endif
#if SPH_64
#define CBx(r, i) CBx_(Z ## r ## i)
#define CBx_(n) CBx__(n)
#define CBx__(n) CB
#define CB0 SPH_C64(0x243F6A8885A308D3)
#define CB1 SPH_C64(0x13198A2E03707344)
#define CB2 SPH_C64(0xA4093822299F31D0)
#define CB3 SPH_C64(0x082EFA98EC4E6C89)
#define CB4 SPH_C64(0x452821E638D01377)
#define CB5 SPH_C64(0xBE5466CF34E90C6C)
#define CB6 SPH_C64(0xC0AC29B7C97C50DD)
#define CB7 SPH_C64(0x3F84D5B5B5470917)
#define CB8 SPH_C64(0x9216D5D98979FB1B)
#define CB9 SPH_C64(0xD1310BA698DFB5AC)
#define CBA SPH_C64(0x2FFD72DBD01ADFB7)
#define CBB SPH_C64(0xB8E1AFED6A267E96)
#define CBC SPH_C64(0xBA7C9045F12C7F99)
#define CBD SPH_C64(0x24A19947B3916CF7)
#define CBE SPH_C64(0x0801F2E2858EFC16)
#define CBF SPH_C64(0x636920D871574E69)
#if <API key>
static const sph_u64 CB[16] = {
SPH_C64(0x243F6A8885A308D3), SPH_C64(0x13198A2E03707344),
SPH_C64(0xA4093822299F31D0), SPH_C64(0x082EFA98EC4E6C89),
SPH_C64(0x452821E638D01377), SPH_C64(0xBE5466CF34E90C6C),
SPH_C64(0xC0AC29B7C97C50DD), SPH_C64(0x3F84D5B5B5470917),
SPH_C64(0x9216D5D98979FB1B), SPH_C64(0xD1310BA698DFB5AC),
SPH_C64(0x2FFD72DBD01ADFB7), SPH_C64(0xB8E1AFED6A267E96),
SPH_C64(0xBA7C9045F12C7F99), SPH_C64(0x24A19947B3916CF7),
SPH_C64(0x0801F2E2858EFC16), SPH_C64(0x636920D871574E69)
};
#endif
#endif
#define GS(m0, m1, c0, c1, a, b, c, d) do { \
a = SPH_T32(a + b + (m0 ^ c1)); \
d = SPH_ROTR32(d ^ a, 16); \
c = SPH_T32(c + d); \
b = SPH_ROTR32(b ^ c, 12); \
a = SPH_T32(a + b + (m1 ^ c0)); \
d = SPH_ROTR32(d ^ a, 8); \
c = SPH_T32(c + d); \
b = SPH_ROTR32(b ^ c, 7); \
} while (0)
#if <API key>
#define ROUND_S(r) do { \
GS(M[sigma[r][0x0]], M[sigma[r][0x1]], \
CS[sigma[r][0x0]], CS[sigma[r][0x1]], V0, V4, V8, VC); \
GS(M[sigma[r][0x2]], M[sigma[r][0x3]], \
CS[sigma[r][0x2]], CS[sigma[r][0x3]], V1, V5, V9, VD); \
GS(M[sigma[r][0x4]], M[sigma[r][0x5]], \
CS[sigma[r][0x4]], CS[sigma[r][0x5]], V2, V6, VA, VE); \
GS(M[sigma[r][0x6]], M[sigma[r][0x7]], \
CS[sigma[r][0x6]], CS[sigma[r][0x7]], V3, V7, VB, VF); \
GS(M[sigma[r][0x8]], M[sigma[r][0x9]], \
CS[sigma[r][0x8]], CS[sigma[r][0x9]], V0, V5, VA, VF); \
GS(M[sigma[r][0xA]], M[sigma[r][0xB]], \
CS[sigma[r][0xA]], CS[sigma[r][0xB]], V1, V6, VB, VC); \
GS(M[sigma[r][0xC]], M[sigma[r][0xD]], \
CS[sigma[r][0xC]], CS[sigma[r][0xD]], V2, V7, V8, VD); \
GS(M[sigma[r][0xE]], M[sigma[r][0xF]], \
CS[sigma[r][0xE]], CS[sigma[r][0xF]], V3, V4, V9, VE); \
} while (0)
#else
#define ROUND_S(r) do { \
GS(Mx(r, 0), Mx(r, 1), CSx(r, 0), CSx(r, 1), V0, V4, V8, VC); \
GS(Mx(r, 2), Mx(r, 3), CSx(r, 2), CSx(r, 3), V1, V5, V9, VD); \
GS(Mx(r, 4), Mx(r, 5), CSx(r, 4), CSx(r, 5), V2, V6, VA, VE); \
GS(Mx(r, 6), Mx(r, 7), CSx(r, 6), CSx(r, 7), V3, V7, VB, VF); \
GS(Mx(r, 8), Mx(r, 9), CSx(r, 8), CSx(r, 9), V0, V5, VA, VF); \
GS(Mx(r, A), Mx(r, B), CSx(r, A), CSx(r, B), V1, V6, VB, VC); \
GS(Mx(r, C), Mx(r, D), CSx(r, C), CSx(r, D), V2, V7, V8, VD); \
GS(Mx(r, E), Mx(r, F), CSx(r, E), CSx(r, F), V3, V4, V9, VE); \
} while (0)
#endif
#if SPH_64
#define GB(m0, m1, c0, c1, a, b, c, d) do { \
a = SPH_T64(a + b + (m0 ^ c1)); \
d = SPH_ROTR64(d ^ a, 32); \
c = SPH_T64(c + d); \
b = SPH_ROTR64(b ^ c, 25); \
a = SPH_T64(a + b + (m1 ^ c0)); \
d = SPH_ROTR64(d ^ a, 16); \
c = SPH_T64(c + d); \
b = SPH_ROTR64(b ^ c, 11); \
} while (0)
#if <API key>
#define ROUND_B(r) do { \
GB(M[sigma[r][0x0]], M[sigma[r][0x1]], \
CB[sigma[r][0x0]], CB[sigma[r][0x1]], V0, V4, V8, VC); \
GB(M[sigma[r][0x2]], M[sigma[r][0x3]], \
CB[sigma[r][0x2]], CB[sigma[r][0x3]], V1, V5, V9, VD); \
GB(M[sigma[r][0x4]], M[sigma[r][0x5]], \
CB[sigma[r][0x4]], CB[sigma[r][0x5]], V2, V6, VA, VE); \
GB(M[sigma[r][0x6]], M[sigma[r][0x7]], \
CB[sigma[r][0x6]], CB[sigma[r][0x7]], V3, V7, VB, VF); \
GB(M[sigma[r][0x8]], M[sigma[r][0x9]], \
CB[sigma[r][0x8]], CB[sigma[r][0x9]], V0, V5, VA, VF); \
GB(M[sigma[r][0xA]], M[sigma[r][0xB]], \
CB[sigma[r][0xA]], CB[sigma[r][0xB]], V1, V6, VB, VC); \
GB(M[sigma[r][0xC]], M[sigma[r][0xD]], \
CB[sigma[r][0xC]], CB[sigma[r][0xD]], V2, V7, V8, VD); \
GB(M[sigma[r][0xE]], M[sigma[r][0xF]], \
CB[sigma[r][0xE]], CB[sigma[r][0xF]], V3, V4, V9, VE); \
} while (0)
#else
#define ROUND_B(r) do { \
GB(Mx(r, 0), Mx(r, 1), CBx(r, 0), CBx(r, 1), V0, V4, V8, VC); \
GB(Mx(r, 2), Mx(r, 3), CBx(r, 2), CBx(r, 3), V1, V5, V9, VD); \
GB(Mx(r, 4), Mx(r, 5), CBx(r, 4), CBx(r, 5), V2, V6, VA, VE); \
GB(Mx(r, 6), Mx(r, 7), CBx(r, 6), CBx(r, 7), V3, V7, VB, VF); \
GB(Mx(r, 8), Mx(r, 9), CBx(r, 8), CBx(r, 9), V0, V5, VA, VF); \
GB(Mx(r, A), Mx(r, B), CBx(r, A), CBx(r, B), V1, V6, VB, VC); \
GB(Mx(r, C), Mx(r, D), CBx(r, C), CBx(r, D), V2, V7, V8, VD); \
GB(Mx(r, E), Mx(r, F), CBx(r, E), CBx(r, F), V3, V4, V9, VE); \
} while (0)
#endif
#endif
#define DECL_STATE32 \
sph_u32 H0, H1, H2, H3, H4, H5, H6, H7; \
sph_u32 S0, S1, S2, S3, T0, T1;
#define READ_STATE32(state) do { \
H0 = (state)->H[0]; \
H1 = (state)->H[1]; \
H2 = (state)->H[2]; \
H3 = (state)->H[3]; \
H4 = (state)->H[4]; \
H5 = (state)->H[5]; \
H6 = (state)->H[6]; \
H7 = (state)->H[7]; \
S0 = (state)->S[0]; \
S1 = (state)->S[1]; \
S2 = (state)->S[2]; \
S3 = (state)->S[3]; \
T0 = (state)->T0; \
T1 = (state)->T1; \
} while (0)
#define WRITE_STATE32(state) do { \
(state)->H[0] = H0; \
(state)->H[1] = H1; \
(state)->H[2] = H2; \
(state)->H[3] = H3; \
(state)->H[4] = H4; \
(state)->H[5] = H5; \
(state)->H[6] = H6; \
(state)->H[7] = H7; \
(state)->S[0] = S0; \
(state)->S[1] = S1; \
(state)->S[2] = S2; \
(state)->S[3] = S3; \
(state)->T0 = T0; \
(state)->T1 = T1; \
} while (0)
#if <API key>
#define COMPRESS32 do { \
sph_u32 M[16]; \
sph_u32 V0, V1, V2, V3, V4, V5, V6, V7; \
sph_u32 V8, V9, VA, VB, VC, VD, VE, VF; \
unsigned r; \
V0 = H0; \
V1 = H1; \
V2 = H2; \
V3 = H3; \
V4 = H4; \
V5 = H5; \
V6 = H6; \
V7 = H7; \
V8 = S0 ^ CS0; \
V9 = S1 ^ CS1; \
VA = S2 ^ CS2; \
VB = S3 ^ CS3; \
VC = T0 ^ CS4; \
VD = T0 ^ CS5; \
VE = T1 ^ CS6; \
VF = T1 ^ CS7; \
M[0x0] = sph_dec32be_aligned(buf + 0); \
M[0x1] = sph_dec32be_aligned(buf + 4); \
M[0x2] = sph_dec32be_aligned(buf + 8); \
M[0x3] = sph_dec32be_aligned(buf + 12); \
M[0x4] = sph_dec32be_aligned(buf + 16); \
M[0x5] = sph_dec32be_aligned(buf + 20); \
M[0x6] = sph_dec32be_aligned(buf + 24); \
M[0x7] = sph_dec32be_aligned(buf + 28); \
M[0x8] = sph_dec32be_aligned(buf + 32); \
M[0x9] = sph_dec32be_aligned(buf + 36); \
M[0xA] = sph_dec32be_aligned(buf + 40); \
M[0xB] = sph_dec32be_aligned(buf + 44); \
M[0xC] = sph_dec32be_aligned(buf + 48); \
M[0xD] = sph_dec32be_aligned(buf + 52); \
M[0xE] = sph_dec32be_aligned(buf + 56); \
M[0xF] = sph_dec32be_aligned(buf + 60); \
for (r = 0; r < 14; r ++) \
ROUND_S(r); \
H0 ^= S0 ^ V0 ^ V8; \
H1 ^= S1 ^ V1 ^ V9; \
H2 ^= S2 ^ V2 ^ VA; \
H3 ^= S3 ^ V3 ^ VB; \
H4 ^= S0 ^ V4 ^ VC; \
H5 ^= S1 ^ V5 ^ VD; \
H6 ^= S2 ^ V6 ^ VE; \
H7 ^= S3 ^ V7 ^ VF; \
} while (0)
#else
#define COMPRESS32 do { \
sph_u32 M0, M1, M2, M3, M4, M5, M6, M7; \
sph_u32 M8, M9, MA, MB, MC, MD, ME, MF; \
sph_u32 V0, V1, V2, V3, V4, V5, V6, V7; \
sph_u32 V8, V9, VA, VB, VC, VD, VE, VF; \
V0 = H0; \
V1 = H1; \
V2 = H2; \
V3 = H3; \
V4 = H4; \
V5 = H5; \
V6 = H6; \
V7 = H7; \
V8 = S0 ^ CS0; \
V9 = S1 ^ CS1; \
VA = S2 ^ CS2; \
VB = S3 ^ CS3; \
VC = T0 ^ CS4; \
VD = T0 ^ CS5; \
VE = T1 ^ CS6; \
VF = T1 ^ CS7; \
M0 = sph_dec32be_aligned(buf + 0); \
M1 = sph_dec32be_aligned(buf + 4); \
M2 = sph_dec32be_aligned(buf + 8); \
M3 = sph_dec32be_aligned(buf + 12); \
M4 = sph_dec32be_aligned(buf + 16); \
M5 = sph_dec32be_aligned(buf + 20); \
M6 = sph_dec32be_aligned(buf + 24); \
M7 = sph_dec32be_aligned(buf + 28); \
M8 = sph_dec32be_aligned(buf + 32); \
M9 = sph_dec32be_aligned(buf + 36); \
MA = sph_dec32be_aligned(buf + 40); \
MB = sph_dec32be_aligned(buf + 44); \
MC = sph_dec32be_aligned(buf + 48); \
MD = sph_dec32be_aligned(buf + 52); \
ME = sph_dec32be_aligned(buf + 56); \
MF = sph_dec32be_aligned(buf + 60); \
ROUND_S(0); \
ROUND_S(1); \
ROUND_S(2); \
ROUND_S(3); \
ROUND_S(4); \
ROUND_S(5); \
ROUND_S(6); \
ROUND_S(7); \
ROUND_S(8); \
ROUND_S(9); \
ROUND_S(0); \
ROUND_S(1); \
ROUND_S(2); \
ROUND_S(3); \
H0 ^= S0 ^ V0 ^ V8; \
H1 ^= S1 ^ V1 ^ V9; \
H2 ^= S2 ^ V2 ^ VA; \
H3 ^= S3 ^ V3 ^ VB; \
H4 ^= S0 ^ V4 ^ VC; \
H5 ^= S1 ^ V5 ^ VD; \
H6 ^= S2 ^ V6 ^ VE; \
H7 ^= S3 ^ V7 ^ VF; \
} while (0)
#endif
#if SPH_64
#define DECL_STATE64 \
sph_u64 H0, H1, H2, H3, H4, H5, H6, H7; \
sph_u64 S0, S1, S2, S3, T0, T1;
#define READ_STATE64(state) do { \
H0 = (state)->H[0]; \
H1 = (state)->H[1]; \
H2 = (state)->H[2]; \
H3 = (state)->H[3]; \
H4 = (state)->H[4]; \
H5 = (state)->H[5]; \
H6 = (state)->H[6]; \
H7 = (state)->H[7]; \
S0 = (state)->S[0]; \
S1 = (state)->S[1]; \
S2 = (state)->S[2]; \
S3 = (state)->S[3]; \
T0 = (state)->T0; \
T1 = (state)->T1; \
} while (0)
#define WRITE_STATE64(state) do { \
(state)->H[0] = H0; \
(state)->H[1] = H1; \
(state)->H[2] = H2; \
(state)->H[3] = H3; \
(state)->H[4] = H4; \
(state)->H[5] = H5; \
(state)->H[6] = H6; \
(state)->H[7] = H7; \
(state)->S[0] = S0; \
(state)->S[1] = S1; \
(state)->S[2] = S2; \
(state)->S[3] = S3; \
(state)->T0 = T0; \
(state)->T1 = T1; \
} while (0)
#if <API key>
#define COMPRESS64 do { \
sph_u64 M[16]; \
sph_u64 V0, V1, V2, V3, V4, V5, V6, V7; \
sph_u64 V8, V9, VA, VB, VC, VD, VE, VF; \
unsigned r; \
V0 = H0; \
V1 = H1; \
V2 = H2; \
V3 = H3; \
V4 = H4; \
V5 = H5; \
V6 = H6; \
V7 = H7; \
V8 = S0 ^ CB0; \
V9 = S1 ^ CB1; \
VA = S2 ^ CB2; \
VB = S3 ^ CB3; \
VC = T0 ^ CB4; \
VD = T0 ^ CB5; \
VE = T1 ^ CB6; \
VF = T1 ^ CB7; \
M[0x0] = sph_dec64be_aligned(buf + 0); \
M[0x1] = sph_dec64be_aligned(buf + 8); \
M[0x2] = sph_dec64be_aligned(buf + 16); \
M[0x3] = sph_dec64be_aligned(buf + 24); \
M[0x4] = sph_dec64be_aligned(buf + 32); \
M[0x5] = sph_dec64be_aligned(buf + 40); \
M[0x6] = sph_dec64be_aligned(buf + 48); \
M[0x7] = sph_dec64be_aligned(buf + 56); \
M[0x8] = sph_dec64be_aligned(buf + 64); \
M[0x9] = sph_dec64be_aligned(buf + 72); \
M[0xA] = sph_dec64be_aligned(buf + 80); \
M[0xB] = sph_dec64be_aligned(buf + 88); \
M[0xC] = sph_dec64be_aligned(buf + 96); \
M[0xD] = sph_dec64be_aligned(buf + 104); \
M[0xE] = sph_dec64be_aligned(buf + 112); \
M[0xF] = sph_dec64be_aligned(buf + 120); \
for (r = 0; r < 16; r ++) \
ROUND_B(r); \
H0 ^= S0 ^ V0 ^ V8; \
H1 ^= S1 ^ V1 ^ V9; \
H2 ^= S2 ^ V2 ^ VA; \
H3 ^= S3 ^ V3 ^ VB; \
H4 ^= S0 ^ V4 ^ VC; \
H5 ^= S1 ^ V5 ^ VD; \
H6 ^= S2 ^ V6 ^ VE; \
H7 ^= S3 ^ V7 ^ VF; \
} while (0)
#else
#define COMPRESS64 do { \
sph_u64 M0, M1, M2, M3, M4, M5, M6, M7; \
sph_u64 M8, M9, MA, MB, MC, MD, ME, MF; \
sph_u64 V0, V1, V2, V3, V4, V5, V6, V7; \
sph_u64 V8, V9, VA, VB, VC, VD, VE, VF; \
V0 = H0; \
V1 = H1; \
V2 = H2; \
V3 = H3; \
V4 = H4; \
V5 = H5; \
V6 = H6; \
V7 = H7; \
V8 = S0 ^ CB0; \
V9 = S1 ^ CB1; \
VA = S2 ^ CB2; \
VB = S3 ^ CB3; \
VC = T0 ^ CB4; \
VD = T0 ^ CB5; \
VE = T1 ^ CB6; \
VF = T1 ^ CB7; \
M0 = sph_dec64be_aligned(buf + 0); \
M1 = sph_dec64be_aligned(buf + 8); \
M2 = sph_dec64be_aligned(buf + 16); \
M3 = sph_dec64be_aligned(buf + 24); \
M4 = sph_dec64be_aligned(buf + 32); \
M5 = sph_dec64be_aligned(buf + 40); \
M6 = sph_dec64be_aligned(buf + 48); \
M7 = sph_dec64be_aligned(buf + 56); \
M8 = sph_dec64be_aligned(buf + 64); \
M9 = sph_dec64be_aligned(buf + 72); \
MA = sph_dec64be_aligned(buf + 80); \
MB = sph_dec64be_aligned(buf + 88); \
MC = sph_dec64be_aligned(buf + 96); \
MD = sph_dec64be_aligned(buf + 104); \
ME = sph_dec64be_aligned(buf + 112); \
MF = sph_dec64be_aligned(buf + 120); \
ROUND_B(0); \
ROUND_B(1); \
ROUND_B(2); \
ROUND_B(3); \
ROUND_B(4); \
ROUND_B(5); \
ROUND_B(6); \
ROUND_B(7); \
ROUND_B(8); \
ROUND_B(9); \
ROUND_B(0); \
ROUND_B(1); \
ROUND_B(2); \
ROUND_B(3); \
ROUND_B(4); \
ROUND_B(5); \
H0 ^= S0 ^ V0 ^ V8; \
H1 ^= S1 ^ V1 ^ V9; \
H2 ^= S2 ^ V2 ^ VA; \
H3 ^= S3 ^ V3 ^ VB; \
H4 ^= S0 ^ V4 ^ VC; \
H5 ^= S1 ^ V5 ^ VD; \
H6 ^= S2 ^ V6 ^ VE; \
H7 ^= S3 ^ V7 ^ VF; \
} while (0)
#endif
#endif
static const sph_u32 salt_zero_small[4] = { 0, 0, 0, 0 };
static void
blake32_init(<API key> *sc,
const sph_u32 *iv, const sph_u32 *salt)
{
memcpy(sc->H, iv, 8 * sizeof(sph_u32));
memcpy(sc->S, salt, 4 * sizeof(sph_u32));
sc->T0 = sc->T1 = 0;
sc->ptr = 0;
}
static void
blake32(<API key> *sc, const void *data, size_t len)
{
unsigned char *buf;
size_t ptr;
DECL_STATE32
buf = sc->buf;
ptr = sc->ptr;
if (len < (sizeof sc->buf) - ptr) {
memcpy(buf + ptr, data, len);
ptr += len;
sc->ptr = ptr;
return;
}
READ_STATE32(sc);
while (len > 0) {
size_t clen;
clen = (sizeof sc->buf) - ptr;
if (clen > len)
clen = len;
memcpy(buf + ptr, data, clen);
ptr += clen;
data = (const unsigned char *)data + clen;
len -= clen;
if (ptr == sizeof sc->buf) {
if ((T0 = SPH_T32(T0 + 512)) < 512)
T1 = SPH_T32(T1 + 1);
COMPRESS32;
ptr = 0;
}
}
WRITE_STATE32(sc);
sc->ptr = ptr;
}
static void
blake32_close(<API key> *sc,
unsigned ub, unsigned n, void *dst, size_t out_size_w32)
{
union {
unsigned char buf[64];
sph_u32 dummy;
} u;
size_t ptr, k;
unsigned bit_len;
unsigned z;
sph_u32 th, tl;
unsigned char *out;
ptr = sc->ptr;
bit_len = ((unsigned)ptr << 3) + n;
z = 0x80 >> n;
u.buf[ptr] = ((ub & -z) | z) & 0xFF;
tl = sc->T0 + bit_len;
th = sc->T1;
if (ptr == 0 && n == 0) {
sc->T0 = SPH_C32(0xFFFFFE00);
sc->T1 = SPH_C32(0xFFFFFFFF);
} else if (sc->T0 == 0) {
sc->T0 = SPH_C32(0xFFFFFE00) + bit_len;
sc->T1 = SPH_T32(sc->T1 - 1);
} else {
sc->T0 -= 512 - bit_len;
}
if (bit_len <= 446) {
memset(u.buf + ptr + 1, 0, 55 - ptr);
if (out_size_w32 == 8)
u.buf[55] |= 1;
sph_enc32be_aligned(u.buf + 56, th);
sph_enc32be_aligned(u.buf + 60, tl);
blake32(sc, u.buf + ptr, 64 - ptr);
} else {
memset(u.buf + ptr + 1, 0, 63 - ptr);
blake32(sc, u.buf + ptr, 64 - ptr);
sc->T0 = SPH_C32(0xFFFFFE00);
sc->T1 = SPH_C32(0xFFFFFFFF);
memset(u.buf, 0, 56);
if (out_size_w32 == 8)
u.buf[55] = 1;
sph_enc32be_aligned(u.buf + 56, th);
sph_enc32be_aligned(u.buf + 60, tl);
blake32(sc, u.buf, 64);
}
out = dst;
for (k = 0; k < out_size_w32; k ++)
sph_enc32be(out + (k << 2), sc->H[k]);
}
#if SPH_64
static const sph_u64 salt_zero_big[4] = { 0, 0, 0, 0 };
static void
blake64_init(<API key> *sc,
const sph_u64 *iv, const sph_u64 *salt)
{
memcpy(sc->H, iv, 8 * sizeof(sph_u64));
memcpy(sc->S, salt, 4 * sizeof(sph_u64));
sc->T0 = sc->T1 = 0;
sc->ptr = 0;
}
static void
blake64(<API key> *sc, const void *data, size_t len)
{
unsigned char *buf;
size_t ptr;
DECL_STATE64
buf = sc->buf;
ptr = sc->ptr;
if (len < (sizeof sc->buf) - ptr) {
memcpy(buf + ptr, data, len);
ptr += len;
sc->ptr = ptr;
return;
}
READ_STATE64(sc);
while (len > 0) {
size_t clen;
clen = (sizeof sc->buf) - ptr;
if (clen > len)
clen = len;
memcpy(buf + ptr, data, clen);
ptr += clen;
data = (const unsigned char *)data + clen;
len -= clen;
if (ptr == sizeof sc->buf) {
if ((T0 = SPH_T64(T0 + 1024)) < 1024)
T1 = SPH_T64(T1 + 1);
COMPRESS64;
ptr = 0;
}
}
WRITE_STATE64(sc);
sc->ptr = ptr;
}
static void
blake64_close(<API key> *sc,
unsigned ub, unsigned n, void *dst, size_t out_size_w64)
{
union {
unsigned char buf[128];
sph_u64 dummy;
} u;
size_t ptr, k;
unsigned bit_len;
unsigned z;
sph_u64 th, tl;
unsigned char *out;
ptr = sc->ptr;
bit_len = ((unsigned)ptr << 3) + n;
z = 0x80 >> n;
u.buf[ptr] = ((ub & -z) | z) & 0xFF;
tl = sc->T0 + bit_len;
th = sc->T1;
if (ptr == 0 && n == 0) {
sc->T0 = SPH_C64(0xFFFFFFFFFFFFFC00);
sc->T1 = SPH_C64(0xFFFFFFFFFFFFFFFF);
} else if (sc->T0 == 0) {
sc->T0 = SPH_C64(0xFFFFFFFFFFFFFC00) + bit_len;
sc->T1 = SPH_T64(sc->T1 - 1);
} else {
sc->T0 -= 1024 - bit_len;
}
if (bit_len <= 894) {
memset(u.buf + ptr + 1, 0, 111 - ptr);
if (out_size_w64 == 8)
u.buf[111] |= 1;
sph_enc64be_aligned(u.buf + 112, th);
sph_enc64be_aligned(u.buf + 120, tl);
blake64(sc, u.buf + ptr, 128 - ptr);
} else {
memset(u.buf + ptr + 1, 0, 127 - ptr);
blake64(sc, u.buf + ptr, 128 - ptr);
sc->T0 = SPH_C64(0xFFFFFFFFFFFFFC00);
sc->T1 = SPH_C64(0xFFFFFFFFFFFFFFFF);
memset(u.buf, 0, 112);
if (out_size_w64 == 8)
u.buf[111] = 1;
sph_enc64be_aligned(u.buf + 112, th);
sph_enc64be_aligned(u.buf + 120, tl);
blake64(sc, u.buf, 128);
}
out = dst;
for (k = 0; k < out_size_w64; k ++)
sph_enc64be(out + (k << 3), sc->H[k]);
}
#endif
/* see sph_blake.h */
void
sph_blake224_init(void *cc)
{
blake32_init(cc, IV224, salt_zero_small);
}
/* see sph_blake.h */
void
sph_blake224(void *cc, const void *data, size_t len)
{
blake32(cc, data, len);
}
/* see sph_blake.h */
void
sph_blake224_close(void *cc, void *dst)
{
<API key>(cc, 0, 0, dst);
}
/* see sph_blake.h */
void
<API key>(void *cc, unsigned ub, unsigned n, void *dst)
{
blake32_close(cc, ub, n, dst, 7);
sph_blake224_init(cc);
}
/* see sph_blake.h */
void
sph_blake256_init(void *cc)
{
blake32_init(cc, IV256, salt_zero_small);
}
/* see sph_blake.h */
void
sph_blake256(void *cc, const void *data, size_t len)
{
blake32(cc, data, len);
}
/* see sph_blake.h */
void
sph_blake256_close(void *cc, void *dst)
{
<API key>(cc, 0, 0, dst);
}
/* see sph_blake.h */
void
<API key>(void *cc, unsigned ub, unsigned n, void *dst)
{
blake32_close(cc, ub, n, dst, 8);
sph_blake256_init(cc);
}
#if SPH_64
/* see sph_blake.h */
void
sph_blake384_init(void *cc)
{
blake64_init(cc, IV384, salt_zero_big);
}
/* see sph_blake.h */
void
sph_blake384(void *cc, const void *data, size_t len)
{
blake64(cc, data, len);
}
/* see sph_blake.h */
void
sph_blake384_close(void *cc, void *dst)
{
<API key>(cc, 0, 0, dst);
}
/* see sph_blake.h */
void
<API key>(void *cc, unsigned ub, unsigned n, void *dst)
{
blake64_close(cc, ub, n, dst, 6);
sph_blake384_init(cc);
}
/* see sph_blake.h */
void
sph_blake512_init(void *cc)
{
blake64_init(cc, IV512, salt_zero_big);
}
/* see sph_blake.h */
void
sph_blake512(void *cc, const void *data, size_t len)
{
blake64(cc, data, len);
}
/* see sph_blake.h */
void
sph_blake512_close(void *cc, void *dst)
{
<API key>(cc, 0, 0, dst);
}
/* see sph_blake.h */
void
<API key>(void *cc, unsigned ub, unsigned n, void *dst)
{
blake64_close(cc, ub, n, dst, 8);
sph_blake512_init(cc);
}
#endif |
#pragma once
#include "quantum.h"
#define LAYOUT_tsangan( \
K000, K001, K002, K003, K004, K005, K006, K007, K008, K009, K010, K011, K012, K013, K413, \
K100, K101, K102, K103, K104, K105, K106, K107, K108, K109, K110, K111, K112, K113, \
K200, K201, K202, K203, K204, K205, K206, K207, K208, K209, K210, K211, K212, \
K300, K301, K302, K303, K304, K305, K306, K307, K308, K309, K310, K311, K312, \
K400, K401, K402, K406, K410, K411, K412 \
) { \
{ K000, K001, K002, K003, K004, K005, K006, K007, K008, K009, K010, K011, K012, K013 }, \
{ K100, K101, K102, K103, K104, K105, K106, K107, K108, K109, K110, K111, K112, K113 }, \
{ K200, K201, K202, K203, K204, K205, K206, K207, K208, K209, K210, K211, K212, KC_NO }, \
{ K300, K301, K302, K303, K304, K305, K306, K307, K308, K309, K310, K311, K312, KC_NO }, \
{ K400, K401, K402, KC_NO, KC_NO, KC_NO, K406, KC_NO, KC_NO, KC_NO, K410, K411, K412, K413 } \
}
/* HHKB Variant */
#define LAYOUT_60_hhkb( \
K000, K001, K002, K003, K004, K005, K006, K007, K008, K009, K010, K011, K012, K013, K413, \
K100, K101, K102, K103, K104, K105, K106, K107, K108, K109, K110, K111, K112, K113, \
K200, K201, K202, K203, K204, K205, K206, K207, K208, K209, K210, K211, K212, \
K300, K301, K302, K303, K304, K305, K306, K307, K308, K309, K310, K311, K312, \
K401, K402, K406, K410, K411 \
) { \
{ K000, K001, K002, K003, K004, K005, K006, K007, K008, K009, K010, K011, K012, K013 }, \
{ K100, K101, K102, K103, K104, K105, K106, K107, K108, K109, K110, K111, K112, K113 }, \
{ K200, K201, K202, K203, K204, K205, K206, K207, K208, K209, K210, K211, K212, KC_NO }, \
{ K300, K301, K302, K303, K304, K305, K306, K307, K308, K309, K310, K311, K312, KC_NO }, \
{ KC_NO, K401, K402, KC_NO, KC_NO, KC_NO, K406, KC_NO, KC_NO, KC_NO, K410, K411, KC_NO, K413 } \
} |
#include <linux/init.h>
#include <linux/clk.h>
#include <linux/serial_8250.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/gpio.h>
#include <linux/spi/spi.h>
#include <asm/mach/map.h>
#include <mach/dm365.h>
#include <mach/cputype.h>
#include <mach/edma.h>
#include <mach/psc.h>
#include <mach/mux.h>
#include <mach/irqs.h>
#include <mach/time.h>
#include <mach/serial.h>
#include <mach/common.h>
#include <mach/asp.h>
#include <mach/keyscan.h>
#include <mach/spi.h>
#include "clock.h"
#include "mux.h"
#define DM365_REF_FREQ 24000000 /* 24 MHz on the DM365 EVM */
static struct pll_data pll1_data = {
.num = 1,
.phys_base = DAVINCI_PLL1_BASE,
.flags = PLL_HAS_POSTDIV | PLL_HAS_PREDIV,
};
static struct pll_data pll2_data = {
.num = 2,
.phys_base = DAVINCI_PLL2_BASE,
.flags = PLL_HAS_POSTDIV | PLL_HAS_PREDIV,
};
static struct clk ref_clk = {
.name = "ref_clk",
.rate = DM365_REF_FREQ,
};
static struct clk pll1_clk = {
.name = "pll1",
.parent = &ref_clk,
.flags = CLK_PLL,
.pll_data = &pll1_data,
};
static struct clk pll1_aux_clk = {
.name = "pll1_aux_clk",
.parent = &pll1_clk,
.flags = CLK_PLL | PRE_PLL,
};
static struct clk pll1_sysclkbp = {
.name = "pll1_sysclkbp",
.parent = &pll1_clk,
.flags = CLK_PLL | PRE_PLL,
.div_reg = BPDIV
};
static struct clk clkout0_clk = {
.name = "clkout0",
.parent = &pll1_clk,
.flags = CLK_PLL | PRE_PLL,
};
static struct clk pll1_sysclk1 = {
.name = "pll1_sysclk1",
.parent = &pll1_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV1,
};
static struct clk pll1_sysclk2 = {
.name = "pll1_sysclk2",
.parent = &pll1_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV2,
};
static struct clk pll1_sysclk3 = {
.name = "pll1_sysclk3",
.parent = &pll1_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV3,
};
static struct clk pll1_sysclk4 = {
.name = "pll1_sysclk4",
.parent = &pll1_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV4,
};
static struct clk pll1_sysclk5 = {
.name = "pll1_sysclk5",
.parent = &pll1_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV5,
};
static struct clk pll1_sysclk6 = {
.name = "pll1_sysclk6",
.parent = &pll1_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV6,
};
static struct clk pll1_sysclk7 = {
.name = "pll1_sysclk7",
.parent = &pll1_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV7,
};
static struct clk pll1_sysclk8 = {
.name = "pll1_sysclk8",
.parent = &pll1_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV8,
};
static struct clk pll1_sysclk9 = {
.name = "pll1_sysclk9",
.parent = &pll1_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV9,
};
static struct clk pll2_clk = {
.name = "pll2",
.parent = &ref_clk,
.flags = CLK_PLL,
.pll_data = &pll2_data,
};
static struct clk pll2_aux_clk = {
.name = "pll2_aux_clk",
.parent = &pll2_clk,
.flags = CLK_PLL | PRE_PLL,
};
static struct clk clkout1_clk = {
.name = "clkout1",
.parent = &pll2_clk,
.flags = CLK_PLL | PRE_PLL,
};
static struct clk pll2_sysclk1 = {
.name = "pll2_sysclk1",
.parent = &pll2_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV1,
};
static struct clk pll2_sysclk2 = {
.name = "pll2_sysclk2",
.parent = &pll2_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV2,
};
static struct clk pll2_sysclk3 = {
.name = "pll2_sysclk3",
.parent = &pll2_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV3,
};
static struct clk pll2_sysclk4 = {
.name = "pll2_sysclk4",
.parent = &pll2_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV4,
};
static struct clk pll2_sysclk5 = {
.name = "pll2_sysclk5",
.parent = &pll2_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV5,
};
static struct clk pll2_sysclk6 = {
.name = "pll2_sysclk6",
.parent = &pll2_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV6,
};
static struct clk pll2_sysclk7 = {
.name = "pll2_sysclk7",
.parent = &pll2_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV7,
};
static struct clk pll2_sysclk8 = {
.name = "pll2_sysclk8",
.parent = &pll2_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV8,
};
static struct clk pll2_sysclk9 = {
.name = "pll2_sysclk9",
.parent = &pll2_clk,
.flags = CLK_PLL,
.div_reg = PLLDIV9,
};
static struct clk vpss_dac_clk = {
.name = "vpss_dac",
.parent = &pll1_sysclk3,
.lpsc = DM365_LPSC_DAC_CLK,
};
static struct clk vpss_master_clk = {
.name = "vpss_master",
.parent = &pll1_sysclk5,
.lpsc = DM365_LPSC_VPSSMSTR,
.flags = CLK_PSC,
};
static struct clk arm_clk = {
.name = "arm_clk",
.parent = &pll2_sysclk2,
.lpsc = DAVINCI_LPSC_ARM,
.flags = ALWAYS_ENABLED,
};
static struct clk uart0_clk = {
.name = "uart0",
.parent = &pll1_aux_clk,
.lpsc = DAVINCI_LPSC_UART0,
};
static struct clk uart1_clk = {
.name = "uart1",
.parent = &pll1_sysclk4,
.lpsc = DAVINCI_LPSC_UART1,
};
static struct clk i2c_clk = {
.name = "i2c",
.parent = &pll1_aux_clk,
.lpsc = DAVINCI_LPSC_I2C,
};
static struct clk mmcsd0_clk = {
.name = "mmcsd0",
.parent = &pll1_sysclk8,
.lpsc = DAVINCI_LPSC_MMC_SD,
};
static struct clk mmcsd1_clk = {
.name = "mmcsd1",
.parent = &pll1_sysclk4,
.lpsc = DM365_LPSC_MMC_SD1,
};
static struct clk spi0_clk = {
.name = "spi0",
.parent = &pll1_sysclk4,
.lpsc = DAVINCI_LPSC_SPI,
};
static struct clk spi1_clk = {
.name = "spi1",
.parent = &pll1_sysclk4,
.lpsc = DM365_LPSC_SPI1,
};
static struct clk spi2_clk = {
.name = "spi2",
.parent = &pll1_sysclk4,
.lpsc = DM365_LPSC_SPI2,
};
static struct clk spi3_clk = {
.name = "spi3",
.parent = &pll1_sysclk4,
.lpsc = DM365_LPSC_SPI3,
};
static struct clk spi4_clk = {
.name = "spi4",
.parent = &pll1_aux_clk,
.lpsc = DM365_LPSC_SPI4,
};
static struct clk gpio_clk = {
.name = "gpio",
.parent = &pll1_sysclk4,
.lpsc = DAVINCI_LPSC_GPIO,
};
static struct clk aemif_clk = {
.name = "aemif",
.parent = &pll1_sysclk4,
.lpsc = DAVINCI_LPSC_AEMIF,
};
static struct clk pwm0_clk = {
.name = "pwm0",
.parent = &pll1_aux_clk,
.lpsc = DAVINCI_LPSC_PWM0,
};
static struct clk pwm1_clk = {
.name = "pwm1",
.parent = &pll1_aux_clk,
.lpsc = DAVINCI_LPSC_PWM1,
};
static struct clk pwm2_clk = {
.name = "pwm2",
.parent = &pll1_aux_clk,
.lpsc = DAVINCI_LPSC_PWM2,
};
static struct clk pwm3_clk = {
.name = "pwm3",
.parent = &ref_clk,
.lpsc = DM365_LPSC_PWM3,
};
static struct clk timer0_clk = {
.name = "timer0",
.parent = &pll1_aux_clk,
.lpsc = DAVINCI_LPSC_TIMER0,
};
static struct clk timer1_clk = {
.name = "timer1",
.parent = &pll1_aux_clk,
.lpsc = DAVINCI_LPSC_TIMER1,
};
static struct clk timer2_clk = {
.name = "timer2",
.parent = &pll1_aux_clk,
.lpsc = DAVINCI_LPSC_TIMER2,
.usecount = 1,
};
static struct clk timer3_clk = {
.name = "timer3",
.parent = &pll1_aux_clk,
.lpsc = DM365_LPSC_TIMER3,
};
static struct clk usb_clk = {
.name = "usb",
.parent = &pll1_aux_clk,
.lpsc = DAVINCI_LPSC_USB,
};
static struct clk emac_clk = {
.name = "emac",
.parent = &pll1_sysclk4,
.lpsc = DM365_LPSC_EMAC,
};
static struct clk voicecodec_clk = {
.name = "voice_codec",
.parent = &pll2_sysclk4,
.lpsc = <API key>,
};
static struct clk asp0_clk = {
.name = "asp0",
.parent = &pll1_sysclk4,
.lpsc = DM365_LPSC_McBSP1,
};
static struct clk rto_clk = {
.name = "rto",
.parent = &pll1_sysclk4,
.lpsc = DM365_LPSC_RTO,
};
static struct clk mjcp_clk = {
.name = "mjcp",
.parent = &pll1_sysclk3,
.lpsc = DM365_LPSC_MJCP,
};
static struct clk_lookup dm365_clks[] = {
CLK(NULL, "ref", &ref_clk),
CLK(NULL, "pll1", &pll1_clk),
CLK(NULL, "pll1_aux", &pll1_aux_clk),
CLK(NULL, "pll1_sysclkbp", &pll1_sysclkbp),
CLK(NULL, "clkout0", &clkout0_clk),
CLK(NULL, "pll1_sysclk1", &pll1_sysclk1),
CLK(NULL, "pll1_sysclk2", &pll1_sysclk2),
CLK(NULL, "pll1_sysclk3", &pll1_sysclk3),
CLK(NULL, "pll1_sysclk4", &pll1_sysclk4),
CLK(NULL, "pll1_sysclk5", &pll1_sysclk5),
CLK(NULL, "pll1_sysclk6", &pll1_sysclk6),
CLK(NULL, "pll1_sysclk7", &pll1_sysclk7),
CLK(NULL, "pll1_sysclk8", &pll1_sysclk8),
CLK(NULL, "pll1_sysclk9", &pll1_sysclk9),
CLK(NULL, "pll2", &pll2_clk),
CLK(NULL, "pll2_aux", &pll2_aux_clk),
CLK(NULL, "clkout1", &clkout1_clk),
CLK(NULL, "pll2_sysclk1", &pll2_sysclk1),
CLK(NULL, "pll2_sysclk2", &pll2_sysclk2),
CLK(NULL, "pll2_sysclk3", &pll2_sysclk3),
CLK(NULL, "pll2_sysclk4", &pll2_sysclk4),
CLK(NULL, "pll2_sysclk5", &pll2_sysclk5),
CLK(NULL, "pll2_sysclk6", &pll2_sysclk6),
CLK(NULL, "pll2_sysclk7", &pll2_sysclk7),
CLK(NULL, "pll2_sysclk8", &pll2_sysclk8),
CLK(NULL, "pll2_sysclk9", &pll2_sysclk9),
CLK(NULL, "vpss_dac", &vpss_dac_clk),
CLK(NULL, "vpss_master", &vpss_master_clk),
CLK(NULL, "arm", &arm_clk),
CLK(NULL, "uart0", &uart0_clk),
CLK(NULL, "uart1", &uart1_clk),
CLK("i2c_davinci.1", NULL, &i2c_clk),
CLK("davinci_mmc.0", NULL, &mmcsd0_clk),
CLK("davinci_mmc.1", NULL, &mmcsd1_clk),
CLK("spi_davinci.0", NULL, &spi0_clk),
CLK("spi_davinci.1", NULL, &spi1_clk),
CLK("spi_davinci.2", NULL, &spi2_clk),
CLK("spi_davinci.3", NULL, &spi3_clk),
CLK("spi_davinci.4", NULL, &spi4_clk),
CLK(NULL, "gpio", &gpio_clk),
CLK(NULL, "aemif", &aemif_clk),
CLK(NULL, "pwm0", &pwm0_clk),
CLK(NULL, "pwm1", &pwm1_clk),
CLK(NULL, "pwm2", &pwm2_clk),
CLK(NULL, "pwm3", &pwm3_clk),
CLK(NULL, "timer0", &timer0_clk),
CLK(NULL, "timer1", &timer1_clk),
CLK("watchdog", NULL, &timer2_clk),
CLK(NULL, "timer3", &timer3_clk),
CLK(NULL, "usb", &usb_clk),
CLK("davinci_emac.1", NULL, &emac_clk),
CLK("davinci_voicecodec", NULL, &voicecodec_clk),
CLK("davinci-mcbsp", NULL, &asp0_clk),
CLK(NULL, "rto", &rto_clk),
CLK(NULL, "mjcp", &mjcp_clk),
CLK(NULL, NULL, NULL),
};
#define INTMUX 0x18
#define EVTMUX 0x1c
static const struct mux_config dm365_pins[] = {
#ifdef CONFIG_DAVINCI_MUX
MUX_CFG(DM365, MMCSD0, 0, 24, 1, 0, false)
MUX_CFG(DM365, SD1_CLK, 0, 16, 3, 1, false)
MUX_CFG(DM365, SD1_CMD, 4, 30, 3, 1, false)
MUX_CFG(DM365, SD1_DATA3, 4, 28, 3, 1, false)
MUX_CFG(DM365, SD1_DATA2, 4, 26, 3, 1, false)
MUX_CFG(DM365, SD1_DATA1, 4, 24, 3, 1, false)
MUX_CFG(DM365, SD1_DATA0, 4, 22, 3, 1, false)
MUX_CFG(DM365, I2C_SDA, 3, 23, 3, 2, false)
MUX_CFG(DM365, I2C_SCL, 3, 21, 3, 2, false)
MUX_CFG(DM365, AEMIF_AR_A14, 2, 0, 3, 1, false)
MUX_CFG(DM365, AEMIF_AR_BA0, 2, 0, 3, 2, false)
MUX_CFG(DM365, AEMIF_A3, 2, 2, 3, 1, false)
MUX_CFG(DM365, AEMIF_A7, 2, 4, 3, 1, false)
MUX_CFG(DM365, AEMIF_D15_8, 2, 6, 1, 1, false)
MUX_CFG(DM365, AEMIF_CE0, 2, 7, 1, 0, false)
MUX_CFG(DM365, AEMIF_CE1, 2, 8, 1, 0, false)
MUX_CFG(DM365, AEMIF_WE_OE, 2, 9, 1, 0, false)
MUX_CFG(DM365, MCBSP0_BDX, 0, 23, 1, 1, false)
MUX_CFG(DM365, MCBSP0_X, 0, 22, 1, 1, false)
MUX_CFG(DM365, MCBSP0_BFSX, 0, 21, 1, 1, false)
MUX_CFG(DM365, MCBSP0_BDR, 0, 20, 1, 1, false)
MUX_CFG(DM365, MCBSP0_R, 0, 19, 1, 1, false)
MUX_CFG(DM365, MCBSP0_BFSR, 0, 18, 1, 1, false)
MUX_CFG(DM365, SPI0_SCLK, 3, 28, 1, 1, false)
MUX_CFG(DM365, SPI0_SDI, 3, 26, 3, 1, false)
MUX_CFG(DM365, SPI0_SDO, 3, 25, 1, 1, false)
MUX_CFG(DM365, SPI0_SDENA0, 3, 29, 3, 1, false)
MUX_CFG(DM365, SPI0_SDENA1, 3, 26, 3, 2, false)
MUX_CFG(DM365, UART0_RXD, 3, 20, 1, 1, false)
MUX_CFG(DM365, UART0_TXD, 3, 19, 1, 1, false)
MUX_CFG(DM365, UART1_RXD, 3, 17, 3, 2, false)
MUX_CFG(DM365, UART1_TXD, 3, 15, 3, 2, false)
MUX_CFG(DM365, UART1_RTS, 3, 23, 3, 1, false)
MUX_CFG(DM365, UART1_CTS, 3, 21, 3, 1, false)
MUX_CFG(DM365, EMAC_TX_EN, 3, 17, 3, 1, false)
MUX_CFG(DM365, EMAC_TX_CLK, 3, 15, 3, 1, false)
MUX_CFG(DM365, EMAC_COL, 3, 14, 1, 1, false)
MUX_CFG(DM365, EMAC_TXD3, 3, 13, 1, 1, false)
MUX_CFG(DM365, EMAC_TXD2, 3, 12, 1, 1, false)
MUX_CFG(DM365, EMAC_TXD1, 3, 11, 1, 1, false)
MUX_CFG(DM365, EMAC_TXD0, 3, 10, 1, 1, false)
MUX_CFG(DM365, EMAC_RXD3, 3, 9, 1, 1, false)
MUX_CFG(DM365, EMAC_RXD2, 3, 8, 1, 1, false)
MUX_CFG(DM365, EMAC_RXD1, 3, 7, 1, 1, false)
MUX_CFG(DM365, EMAC_RXD0, 3, 6, 1, 1, false)
MUX_CFG(DM365, EMAC_RX_CLK, 3, 5, 1, 1, false)
MUX_CFG(DM365, EMAC_RX_DV, 3, 4, 1, 1, false)
MUX_CFG(DM365, EMAC_RX_ER, 3, 3, 1, 1, false)
MUX_CFG(DM365, EMAC_CRS, 3, 2, 1, 1, false)
MUX_CFG(DM365, EMAC_MDIO, 3, 1, 1, 1, false)
MUX_CFG(DM365, EMAC_MDCLK, 3, 0, 1, 1, false)
MUX_CFG(DM365, KEYSCAN, 2, 0, 0x3f, 0x3f, false)
MUX_CFG(DM365, PWM0, 1, 0, 3, 2, false)
MUX_CFG(DM365, PWM0_G23, 3, 26, 3, 3, false)
MUX_CFG(DM365, PWM1, 1, 2, 3, 2, false)
MUX_CFG(DM365, PWM1_G25, 3, 29, 3, 2, false)
MUX_CFG(DM365, PWM2_G87, 1, 10, 3, 2, false)
MUX_CFG(DM365, PWM2_G88, 1, 8, 3, 2, false)
MUX_CFG(DM365, PWM2_G89, 1, 6, 3, 2, false)
MUX_CFG(DM365, PWM2_G90, 1, 4, 3, 2, false)
MUX_CFG(DM365, PWM3_G80, 1, 20, 3, 3, false)
MUX_CFG(DM365, PWM3_G81, 1, 18, 3, 3, false)
MUX_CFG(DM365, PWM3_G85, 1, 14, 3, 2, false)
MUX_CFG(DM365, PWM3_G86, 1, 12, 3, 2, false)
MUX_CFG(DM365, SPI1_SCLK, 4, 2, 3, 1, false)
MUX_CFG(DM365, SPI1_SDI, 3, 31, 1, 1, false)
MUX_CFG(DM365, SPI1_SDO, 4, 0, 3, 1, false)
MUX_CFG(DM365, SPI1_SDENA0, 4, 4, 3, 1, false)
MUX_CFG(DM365, SPI1_SDENA1, 4, 0, 3, 2, false)
MUX_CFG(DM365, SPI2_SCLK, 4, 10, 3, 1, false)
MUX_CFG(DM365, SPI2_SDI, 4, 6, 3, 1, false)
MUX_CFG(DM365, SPI2_SDO, 4, 8, 3, 1, false)
MUX_CFG(DM365, SPI2_SDENA0, 4, 12, 3, 1, false)
MUX_CFG(DM365, SPI2_SDENA1, 4, 8, 3, 2, false)
MUX_CFG(DM365, SPI3_SCLK, 0, 0, 3, 2, false)
MUX_CFG(DM365, SPI3_SDI, 0, 2, 3, 2, false)
MUX_CFG(DM365, SPI3_SDO, 0, 6, 3, 2, false)
MUX_CFG(DM365, SPI3_SDENA0, 0, 4, 3, 2, false)
MUX_CFG(DM365, SPI3_SDENA1, 0, 6, 3, 3, false)
MUX_CFG(DM365, SPI4_SCLK, 4, 18, 3, 1, false)
MUX_CFG(DM365, SPI4_SDI, 4, 14, 3, 1, false)
MUX_CFG(DM365, SPI4_SDO, 4, 16, 3, 1, false)
MUX_CFG(DM365, SPI4_SDENA0, 4, 20, 3, 1, false)
MUX_CFG(DM365, SPI4_SDENA1, 4, 16, 3, 2, false)
MUX_CFG(DM365, CLKOUT0, 4, 20, 3, 3, false)
MUX_CFG(DM365, CLKOUT1, 4, 16, 3, 3, false)
MUX_CFG(DM365, CLKOUT2, 4, 8, 3, 3, false)
MUX_CFG(DM365, GPIO20, 3, 21, 3, 0, false)
MUX_CFG(DM365, GPIO30, 4, 6, 3, 0, false)
MUX_CFG(DM365, GPIO31, 4, 8, 3, 0, false)
MUX_CFG(DM365, GPIO32, 4, 10, 3, 0, false)
MUX_CFG(DM365, GPIO33, 4, 12, 3, 0, false)
MUX_CFG(DM365, GPIO40, 4, 26, 3, 0, false)
MUX_CFG(DM365, GPIO64_57, 2, 6, 1, 0, false)
MUX_CFG(DM365, VOUT_FIELD, 1, 18, 3, 1, false)
MUX_CFG(DM365, VOUT_FIELD_G81, 1, 18, 3, 0, false)
MUX_CFG(DM365, VOUT_HVSYNC, 1, 16, 1, 0, false)
MUX_CFG(DM365, VOUT_COUTL_EN, 1, 0, 0xff, 0x55, false)
MUX_CFG(DM365, VOUT_COUTH_EN, 1, 8, 0xff, 0x55, false)
MUX_CFG(DM365, VIN_CAM_WEN, 0, 14, 3, 0, false)
MUX_CFG(DM365, VIN_CAM_VD, 0, 13, 1, 0, false)
MUX_CFG(DM365, VIN_CAM_HD, 0, 12, 1, 0, false)
MUX_CFG(DM365, VIN_YIN4_7_EN, 0, 0, 0xff, 0, false)
MUX_CFG(DM365, VIN_YIN0_3_EN, 0, 8, 0xf, 0, false)
INT_CFG(DM365, INT_EDMA_CC, 2, 1, 1, false)
INT_CFG(DM365, INT_EDMA_TC0_ERR, 3, 1, 1, false)
INT_CFG(DM365, INT_EDMA_TC1_ERR, 4, 1, 1, false)
INT_CFG(DM365, INT_EDMA_TC2_ERR, 22, 1, 1, false)
INT_CFG(DM365, INT_EDMA_TC3_ERR, 23, 1, 1, false)
INT_CFG(DM365, INT_PRTCSS, 10, 1, 1, false)
INT_CFG(DM365, INT_EMAC_RXTHRESH, 14, 1, 1, false)
INT_CFG(DM365, INT_EMAC_RXPULSE, 15, 1, 1, false)
INT_CFG(DM365, INT_EMAC_TXPULSE, 16, 1, 1, false)
INT_CFG(DM365, INT_EMAC_MISCPULSE, 17, 1, 1, false)
INT_CFG(DM365, INT_IMX0_ENABLE, 0, 1, 0, false)
INT_CFG(DM365, INT_IMX0_DISABLE, 0, 1, 1, false)
INT_CFG(DM365, INT_HDVICP_ENABLE, 0, 1, 1, false)
INT_CFG(DM365, INT_HDVICP_DISABLE, 0, 1, 0, false)
INT_CFG(DM365, INT_IMX1_ENABLE, 24, 1, 1, false)
INT_CFG(DM365, INT_IMX1_DISABLE, 24, 1, 0, false)
INT_CFG(DM365, INT_NSF_ENABLE, 25, 1, 1, false)
INT_CFG(DM365, INT_NSF_DISABLE, 25, 1, 0, false)
EVT_CFG(DM365, EVT2_ASP_TX, 0, 1, 0, false)
EVT_CFG(DM365, EVT3_ASP_RX, 1, 1, 0, false)
EVT_CFG(DM365, EVT2_VC_TX, 0, 1, 1, false)
EVT_CFG(DM365, EVT3_VC_RX, 1, 1, 1, false)
#endif
};
static u64 dm365_spi0_dma_mask = DMA_BIT_MASK(32);
static struct <API key> dm365_spi0_pdata = {
.version = SPI_VERSION_1,
.num_chipselect = 2,
.clk_internal = 1,
.cs_hold = 1,
.intr_level = 0,
.poll_mode = 1, /* 0 -> interrupt mode 1-> polling mode */
.c2tdelay = 0,
.t2cdelay = 0,
};
static struct resource <API key>[] = {
{
.start = 0x01c66000,
.end = 0x01c667ff,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_DM365_SPIINT0_0,
.flags = IORESOURCE_IRQ,
},
{
.start = 17,
.flags = IORESOURCE_DMA,
},
{
.start = 16,
.flags = IORESOURCE_DMA,
},
{
.start = EVENTQ_3,
.flags = IORESOURCE_DMA,
},
};
static struct platform_device dm365_spi0_device = {
.name = "spi_davinci",
.id = 0,
.dev = {
.dma_mask = &dm365_spi0_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &dm365_spi0_pdata,
},
.num_resources = ARRAY_SIZE(<API key>),
.resource = <API key>,
};
void __init dm365_init_spi0(unsigned chipselect_mask,
struct spi_board_info *info, unsigned len)
{
davinci_cfg_reg(DM365_SPI0_SCLK);
davinci_cfg_reg(DM365_SPI0_SDI);
davinci_cfg_reg(DM365_SPI0_SDO);
/* not all slaves will be wired up */
if (chipselect_mask & BIT(0))
davinci_cfg_reg(DM365_SPI0_SDENA0);
if (chipselect_mask & BIT(1))
davinci_cfg_reg(DM365_SPI0_SDENA1);
<API key>(info, len);
<API key>(&dm365_spi0_device);
}
static struct emac_platform_data dm365_emac_pdata = {
.ctrl_reg_offset = <API key>,
.ctrl_mod_reg_offset = <API key>,
.ctrl_ram_offset = <API key>,
.ctrl_ram_size = <API key>,
.version = EMAC_VERSION_2,
};
static struct resource <API key>[] = {
{
.start = DM365_EMAC_BASE,
.end = DM365_EMAC_BASE + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = <API key>,
.end = <API key>,
.flags = IORESOURCE_IRQ,
},
{
.start = <API key>,
.end = <API key>,
.flags = IORESOURCE_IRQ,
},
{
.start = <API key>,
.end = <API key>,
.flags = IORESOURCE_IRQ,
},
{
.start = <API key>,
.end = <API key>,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device dm365_emac_device = {
.name = "davinci_emac",
.id = 1,
.dev = {
.platform_data = &dm365_emac_pdata,
},
.num_resources = ARRAY_SIZE(<API key>),
.resource = <API key>,
};
static struct resource <API key>[] = {
{
.start = <API key>,
.end = <API key> + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device dm365_mdio_device = {
.name = "davinci_mdio",
.id = 0,
.num_resources = ARRAY_SIZE(<API key>),
.resource = <API key>,
};
static u8 <API key>[DAVINCI_N_AINTC_IRQ] = {
[IRQ_VDINT0] = 2,
[IRQ_VDINT1] = 6,
[IRQ_VDINT2] = 6,
[IRQ_HISTINT] = 6,
[IRQ_H3AINT] = 6,
[IRQ_PRVUINT] = 6,
[IRQ_RSZINT] = 6,
[IRQ_DM365_INSFINT] = 7,
[IRQ_VENCINT] = 6,
[IRQ_ASQINT] = 6,
[IRQ_IMXINT] = 6,
[IRQ_DM365_IMCOPINT] = 4,
[IRQ_USBINT] = 4,
[IRQ_DM365_RTOINT] = 7,
[IRQ_DM365_TINT5] = 7,
[IRQ_DM365_TINT6] = 5,
[IRQ_CCINT0] = 5,
[IRQ_CCERRINT] = 5,
[IRQ_TCERRINT0] = 5,
[IRQ_TCERRINT] = 7,
[IRQ_PSCIN] = 4,
[IRQ_DM365_SPINT2_1] = 7,
[IRQ_DM365_TINT7] = 7,
[IRQ_DM365_SDIOINT0] = 7,
[IRQ_MBXINT] = 7,
[IRQ_MBRINT] = 7,
[IRQ_MMCINT] = 7,
[IRQ_DM365_MMCINT1] = 7,
[IRQ_DM365_PWMINT3] = 7,
[IRQ_AEMIFINT] = 2,
[IRQ_DM365_SDIOINT1] = 2,
[IRQ_TINT0_TINT12] = 7,
[IRQ_TINT0_TINT34] = 7,
[IRQ_TINT1_TINT12] = 7,
[IRQ_TINT1_TINT34] = 7,
[IRQ_PWMINT0] = 7,
[IRQ_PWMINT1] = 3,
[IRQ_PWMINT2] = 3,
[IRQ_I2C] = 3,
[IRQ_UARTINT0] = 3,
[IRQ_UARTINT1] = 3,
[IRQ_DM365_RTCINT] = 3,
[IRQ_DM365_SPIINT0_0] = 3,
[IRQ_DM365_SPIINT3_0] = 3,
[IRQ_DM365_GPIO0] = 3,
[IRQ_DM365_GPIO1] = 7,
[IRQ_DM365_GPIO2] = 4,
[IRQ_DM365_GPIO3] = 4,
[IRQ_DM365_GPIO4] = 7,
[IRQ_DM365_GPIO5] = 7,
[IRQ_DM365_GPIO6] = 7,
[IRQ_DM365_GPIO7] = 7,
[<API key>] = 7,
[<API key>] = 7,
[<API key>] = 7,
[<API key>] = 7,
[IRQ_DM365_GPIO12] = 7,
[IRQ_DM365_GPIO13] = 7,
[IRQ_DM365_GPIO14] = 7,
[IRQ_DM365_GPIO15] = 7,
[IRQ_DM365_KEYINT] = 7,
[IRQ_DM365_TCERRINT2] = 7,
[IRQ_DM365_TCERRINT3] = 7,
[IRQ_DM365_EMUINT] = 7,
};
/* Four Transfer Controllers on DM365 */
static const s8
<API key>[][2] = {
/* {event queue no, TC no} */
{0, 0},
{1, 1},
{2, 2},
{3, 3},
{-1, -1},
};
static const s8
<API key>[][2] = {
/* {event queue no, Priority} */
{0, 7},
{1, 7},
{2, 7},
{3, 0},
{-1, -1},
};
static struct edma_soc_info edma_cc0_info = {
.n_channel = 64,
.n_region = 4,
.n_slot = 256,
.n_tc = 4,
.n_cc = 1,
.queue_tc_mapping = <API key>,
.<API key> = <API key>,
.default_queue = EVENTQ_3,
};
static struct edma_soc_info *dm365_edma_info[EDMA_MAX_CC] = {
&edma_cc0_info,
};
static struct resource edma_resources[] = {
{
.name = "edma_cc0",
.start = 0x01c00000,
.end = 0x01c00000 + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "edma_tc0",
.start = 0x01c10000,
.end = 0x01c10000 + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "edma_tc1",
.start = 0x01c10400,
.end = 0x01c10400 + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "edma_tc2",
.start = 0x01c10800,
.end = 0x01c10800 + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "edma_tc3",
.start = 0x01c10c00,
.end = 0x01c10c00 + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "edma0",
.start = IRQ_CCINT0,
.flags = IORESOURCE_IRQ,
},
{
.name = "edma0_err",
.start = IRQ_CCERRINT,
.flags = IORESOURCE_IRQ,
},
/* not using TC*_ERR */
};
static struct platform_device dm365_edma_device = {
.name = "edma",
.id = 0,
.dev.platform_data = dm365_edma_info,
.num_resources = ARRAY_SIZE(edma_resources),
.resource = edma_resources,
};
static struct resource dm365_asp_resources[] = {
{
.start = <API key>,
.end = <API key> + SZ_8K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = DAVINCI_DMA_ASP0_TX,
.end = DAVINCI_DMA_ASP0_TX,
.flags = IORESOURCE_DMA,
},
{
.start = DAVINCI_DMA_ASP0_RX,
.end = DAVINCI_DMA_ASP0_RX,
.flags = IORESOURCE_DMA,
},
};
static struct platform_device dm365_asp_device = {
.name = "davinci-mcbsp",
.id = -1,
.num_resources = ARRAY_SIZE(dm365_asp_resources),
.resource = dm365_asp_resources,
};
static struct resource dm365_vc_resources[] = {
{
.start = <API key>,
.end = <API key> + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = DAVINCI_DMA_VC_TX,
.end = DAVINCI_DMA_VC_TX,
.flags = IORESOURCE_DMA,
},
{
.start = DAVINCI_DMA_VC_RX,
.end = DAVINCI_DMA_VC_RX,
.flags = IORESOURCE_DMA,
},
};
static struct platform_device dm365_vc_device = {
.name = "davinci_voicecodec",
.id = -1,
.num_resources = ARRAY_SIZE(dm365_vc_resources),
.resource = dm365_vc_resources,
};
static struct resource dm365_rtc_resources[] = {
{
.start = DM365_RTC_BASE,
.end = DM365_RTC_BASE + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_DM365_RTCINT,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device dm365_rtc_device = {
.name = "rtc_davinci",
.id = 0,
.num_resources = ARRAY_SIZE(dm365_rtc_resources),
.resource = dm365_rtc_resources,
};
static struct map_desc dm365_io_desc[] = {
{
.virtual = IO_VIRT,
.pfn = __phys_to_pfn(IO_PHYS),
.length = IO_SIZE,
.type = MT_DEVICE
},
{
.virtual = SRAM_VIRT,
.pfn = __phys_to_pfn(0x00010000),
.length = SZ_32K,
.type = MT_MEMORY_NONCACHED,
},
};
static struct resource dm365_ks_resources[] = {
{
/* registers */
.start = DM365_KEYSCAN_BASE,
.end = DM365_KEYSCAN_BASE + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
/* interrupt */
.start = IRQ_DM365_KEYINT,
.end = IRQ_DM365_KEYINT,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device dm365_ks_device = {
.name = "davinci_keyscan",
.id = 0,
.num_resources = ARRAY_SIZE(dm365_ks_resources),
.resource = dm365_ks_resources,
};
/* Contents of JTAG ID register used to identify exact cpu type */
static struct davinci_id dm365_ids[] = {
{
.variant = 0x0,
.part_no = 0xb83e,
.manufacturer = 0x017,
.cpu_id = <API key>,
.name = "dm365_rev1.1",
},
{
.variant = 0x8,
.part_no = 0xb83e,
.manufacturer = 0x017,
.cpu_id = <API key>,
.name = "dm365_rev1.2",
},
};
static u32 dm365_psc_bases[] = { <API key> };
static struct davinci_timer_info dm365_timer_info = {
.timers = <API key>,
.clockevent_id = T0_BOT,
.clocksource_id = T0_TOP,
};
#define DM365_UART1_BASE (IO_PHYS + 0x106000)
static struct <API key> <API key>[] = {
{
.mapbase = DAVINCI_UART0_BASE,
.irq = IRQ_UARTINT0,
.flags = UPF_BOOT_AUTOCONF | UPF_SKIP_TEST |
UPF_IOREMAP,
.iotype = UPIO_MEM,
.regshift = 2,
},
{
.mapbase = DM365_UART1_BASE,
.irq = IRQ_UARTINT1,
.flags = UPF_BOOT_AUTOCONF | UPF_SKIP_TEST |
UPF_IOREMAP,
.iotype = UPIO_MEM,
.regshift = 2,
},
{
.flags = 0
},
};
static struct platform_device dm365_serial_device = {
.name = "serial8250",
.id = <API key>,
.dev = {
.platform_data = <API key>,
},
};
static struct davinci_soc_info <API key> = {
.io_desc = dm365_io_desc,
.io_desc_num = ARRAY_SIZE(dm365_io_desc),
.jtag_id_reg = 0x01c40028,
.ids = dm365_ids,
.ids_num = ARRAY_SIZE(dm365_ids),
.cpu_clks = dm365_clks,
.psc_bases = dm365_psc_bases,
.psc_bases_num = ARRAY_SIZE(dm365_psc_bases),
.pinmux_base = <API key>,
.pinmux_pins = dm365_pins,
.pinmux_pins_num = ARRAY_SIZE(dm365_pins),
.intc_base = <API key>,
.intc_type = <API key>,
.intc_irq_prios = <API key>,
.intc_irq_num = DAVINCI_N_AINTC_IRQ,
.timer_info = &dm365_timer_info,
.gpio_type = GPIO_TYPE_DAVINCI,
.gpio_base = DAVINCI_GPIO_BASE,
.gpio_num = 104,
.gpio_irq = IRQ_DM365_GPIO0,
.gpio_unbanked = 8, /* really 16 ... skip muxed GPIOs */
.serial_dev = &dm365_serial_device,
.emac_pdata = &dm365_emac_pdata,
.sram_dma = 0x00010000,
.sram_len = SZ_32K,
.reset_device = &davinci_wdt_device,
};
void __init dm365_init_asp(struct snd_platform_data *pdata)
{
davinci_cfg_reg(DM365_MCBSP0_BDX);
davinci_cfg_reg(DM365_MCBSP0_X);
davinci_cfg_reg(DM365_MCBSP0_BFSX);
davinci_cfg_reg(DM365_MCBSP0_BDR);
davinci_cfg_reg(DM365_MCBSP0_R);
davinci_cfg_reg(DM365_MCBSP0_BFSR);
davinci_cfg_reg(DM365_EVT2_ASP_TX);
davinci_cfg_reg(DM365_EVT3_ASP_RX);
dm365_asp_device.dev.platform_data = pdata;
<API key>(&dm365_asp_device);
}
void __init dm365_init_vc(struct snd_platform_data *pdata)
{
davinci_cfg_reg(DM365_EVT2_VC_TX);
davinci_cfg_reg(DM365_EVT3_VC_RX);
dm365_vc_device.dev.platform_data = pdata;
<API key>(&dm365_vc_device);
}
void __init dm365_init_ks(struct <API key> *pdata)
{
dm365_ks_device.dev.platform_data = pdata;
<API key>(&dm365_ks_device);
}
void __init dm365_init_rtc(void)
{
davinci_cfg_reg(DM365_INT_PRTCSS);
<API key>(&dm365_rtc_device);
}
void __init dm365_init(void)
{
davinci_common_init(&<API key>);
}
static struct resource <API key>[] = {
{
/* VPSS ISP5 Base address */
.name = "isp5",
.start = 0x01c70000,
.end = 0x01c70000 + 0xff,
.flags = IORESOURCE_MEM,
},
{
/* VPSS CLK Base address */
.name = "vpss",
.start = 0x01c70200,
.end = 0x01c70200 + 0xff,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device dm365_vpss_device = {
.name = "vpss",
.id = -1,
.dev.platform_data = "dm365_vpss",
.num_resources = ARRAY_SIZE(<API key>),
.resource = <API key>,
};
static struct resource vpfe_resources[] = {
{
.start = IRQ_VDINT0,
.end = IRQ_VDINT0,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_VDINT1,
.end = IRQ_VDINT1,
.flags = IORESOURCE_IRQ,
},
};
static u64 <API key> = DMA_BIT_MASK(32);
static struct platform_device vpfe_capture_dev = {
.name = CAPTURE_DRV_NAME,
.id = -1,
.num_resources = ARRAY_SIZE(vpfe_resources),
.resource = vpfe_resources,
.dev = {
.dma_mask = &<API key>,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
};
static void <API key>(void)
{
davinci_cfg_reg(DM365_VIN_CAM_WEN);
davinci_cfg_reg(DM365_VIN_CAM_VD);
davinci_cfg_reg(DM365_VIN_CAM_HD);
davinci_cfg_reg(DM365_VIN_YIN4_7_EN);
davinci_cfg_reg(DM365_VIN_YIN0_3_EN);
}
static struct resource isif_resource[] = {
/* ISIF Base address */
{
.start = 0x01c71000,
.end = 0x01c71000 + 0x1ff,
.flags = IORESOURCE_MEM,
},
/* ISIF Linearization table 0 */
{
.start = 0x1C7C000,
.end = 0x1C7C000 + 0x2ff,
.flags = IORESOURCE_MEM,
},
/* ISIF Linearization table 1 */
{
.start = 0x1C7C400,
.end = 0x1C7C400 + 0x2ff,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device dm365_isif_dev = {
.name = "isif",
.id = -1,
.num_resources = ARRAY_SIZE(isif_resource),
.resource = isif_resource,
.dev = {
.dma_mask = &<API key>,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = <API key>,
},
};
static int __init dm365_init_devices(void)
{
if (!<API key>())
return 0;
davinci_cfg_reg(DM365_INT_EDMA_CC);
<API key>(&dm365_edma_device);
<API key>(&dm365_mdio_device);
<API key>(&dm365_emac_device);
clk_add_alias(NULL, dev_name(&dm365_mdio_device.dev),
NULL, &dm365_emac_device.dev);
/* Add isif clock alias */
clk_add_alias("master", dm365_isif_dev.name, "vpss_master", NULL);
<API key>(&dm365_vpss_device);
<API key>(&dm365_isif_dev);
<API key>(&vpfe_capture_dev);
return 0;
}
postcore_initcall(dm365_init_devices);
void <API key>(struct vpfe_config *cfg)
{
vpfe_capture_dev.dev.platform_data = cfg;
} |
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/file.h>
#include <linux/poll.h>
#include <linux/swap.h>
#include <linux/genalloc.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <plat/iommu.h>
#include <plat/iovmm.h>
#include <plat/dmm_user.h>
#define OMAP_DMM_NAME "iovmm-omap"
static atomic_t num_of_iovmmus;
static struct class *omap_dmm_class;
static dev_t omap_dmm_dev;
static int omap_dmm_ioctl(struct inode *inode, struct file *filp,
unsigned int cmd, unsigned long args)
{
struct iodmm_struct *obj;
int ret = 0;
obj = (struct iodmm_struct *)filp->private_data;
if (!obj)
return -EINVAL;
if (_IOC_TYPE(cmd) != DMM_IOC_MAGIC)
return -ENOTTY;
switch (cmd) {
case DMM_IOCSETTLBENT:
/* if (!capable(CAP_SYS_ADMIN))
return -EPERM; */
ret = program_tlb_entry(obj, (const void __user *)args);
break;
case DMM_IOCCREATEPOOL:
/* if (!capable(CAP_SYS_ADMIN))
return -EPERM; */
ret = <API key>(obj, (const void __user *)args);
break;
case DMM_IOCMEMMAP:
ret = dmm_user(obj, (void __user *)args);
break;
case DMM_IOCMEMUNMAP:
ret = user_un_map(obj, (const void __user *)args);
break;
case IOMMU_IOCEVENTREG:
ret = register_mmufault(obj, (const void __user *)args);
break;
case IOMMU_IOCEVENTUNREG:
ret = unregister_mmufault(obj, (const void __user *)args);
break;
case DMM_IOCMEMFLUSH:
ret = proc_begin_dma(obj, (void __user *)args);
break;
case DMM_IOCMEMINV:
ret = proc_end_dma(obj, (void __user *)args);
break;
/* This ioctl can be deprecated */
case DMM_IOCDELETEPOOL:
break;
case DMM_IOCDATOPA:
default:
return -ENOTTY;
}
return ret;
}
static int omap_dmm_open(struct inode *inode, struct file *filp)
{
struct iodmm_struct *iodmm;
struct iovmm_device *obj;
obj = container_of(inode->i_cdev, struct iovmm_device, cdev);
obj->refcount++;
iodmm = kzalloc(sizeof(struct iodmm_struct), GFP_KERNEL);
INIT_LIST_HEAD(&iodmm->map_list);
iodmm->iovmm = obj;
iodmm->tgid = current->tgid;
obj->iommu = iommu_get(obj->name);
filp->private_data = iodmm;
return 0;
}
static int omap_dmm_release(struct inode *inode, struct file *filp)
{
int status = 0;
struct iodmm_struct *obj;
if (!filp->private_data) {
status = -EIO;
goto err_out;
}
obj = filp->private_data;
flush_signals(current);
status = <API key>(&obj->iovmm->dmm_map_lock);
if (status == 0) {
/*
* Report to remote Processor of the cleanup of these
* resources before cleaning in order to avoid MMU fault
* type of behavior
*/
if (!list_empty(&obj->map_list)) {
iommu_notify_event(obj->iovmm->iommu, IOMMU_CLOSE,
(void *)obj->tgid);
}
mutex_unlock(&obj->iovmm->dmm_map_lock);
} else {
pr_err("%s <API key> returned 0x%x\n",
__func__, status);
}
<API key>(obj);
iommu_put(obj->iovmm->iommu);
/* Delete all the DMM pools after the reference count goes to zero */
if (--obj->iovmm->refcount == 0)
<API key>(obj);
kfree(obj);
filp->private_data = NULL;
err_out:
return status;
}
static const struct file_operations omap_dmm_fops = {
.owner = THIS_MODULE,
.open = omap_dmm_open,
.release = omap_dmm_release,
.ioctl = omap_dmm_ioctl,
};
static int __devinit omap_dmm_probe(struct platform_device *pdev)
{
int err = -ENODEV;
int major, minor;
struct device *tmpdev;
struct iommu_platform_data *pdata =
(struct iommu_platform_data *)pdev->dev.platform_data;
int ret = 0;
struct iovmm_device *obj;
obj = kzalloc(sizeof(struct iovmm_device), GFP_KERNEL);
major = MAJOR(omap_dmm_dev);
minor = atomic_read(&num_of_iovmmus);
atomic_inc(&num_of_iovmmus);
obj->minor = minor;
obj->name = pdata->name;
INIT_LIST_HEAD(&obj->mmap_pool);
cdev_init(&obj->cdev, &omap_dmm_fops);
obj->cdev.owner = THIS_MODULE;
ret = cdev_add(&obj->cdev, MKDEV(major, minor), 1);
if (ret) {
dev_err(&pdev->dev, "%s: cdev_add failed: %d\n", __func__, ret);
goto err_cdev;
}
tmpdev = device_create(omap_dmm_class, NULL,
MKDEV(major, minor),
NULL,
OMAP_DMM_NAME "%d", minor);
if (IS_ERR(tmpdev)) {
ret = PTR_ERR(tmpdev);
pr_err("%s: device_create failed: %d\n", __func__, ret);
goto clean_cdev;
}
pr_info("%s initialized %s, major: %d, base-minor: %d\n",
OMAP_DMM_NAME,
pdata->name,
MAJOR(omap_dmm_dev),
minor);
mutex_init(&obj->dmm_map_lock);
<API key>(pdev, obj);
return 0;
clean_cdev:
cdev_del(&obj->cdev);
err_cdev:
return err;
}
static int __devexit omap_dmm_remove(struct platform_device *pdev)
{
struct iovmm_device *obj = <API key>(pdev);
int major = MAJOR(omap_dmm_dev);
device_destroy(omap_dmm_class, MKDEV(major, obj->minor));
cdev_del(&obj->cdev);
<API key>(pdev, NULL);
kfree(obj);
return 0;
}
static struct platform_driver omap_dmm_driver = {
.probe = omap_dmm_probe,
.remove = __devexit_p(omap_dmm_remove),
.driver = {
.name = "omap-iovmm",
},
};
static int __init dmm_user_init(void)
{
int num, ret;
num = <API key>();
ret = alloc_chrdev_region(&omap_dmm_dev, 0, num, OMAP_DMM_NAME);
if (ret) {
pr_err("%s: alloc_chrdev_region failed: %d\n", __func__, ret);
goto out;
}
omap_dmm_class = class_create(THIS_MODULE, OMAP_DMM_NAME);
if (IS_ERR(omap_dmm_class)) {
ret = PTR_ERR(omap_dmm_class);
pr_err("%s: class_create failed: %d\n", __func__, ret);
goto unreg_region;
}
atomic_set(&num_of_iovmmus, 0);
return <API key>(&omap_dmm_driver);
unreg_region:
<API key>(omap_dmm_dev, num);
out:
return ret;
}
module_init(dmm_user_init);
static void __exit dmm_user_exit(void)
{
int num = <API key>();
class_destroy(omap_dmm_class);
<API key>(omap_dmm_dev, num);
<API key>(&omap_dmm_driver);
}
module_exit(dmm_user_exit);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Userspace DMM to IOMMU");
MODULE_AUTHOR("Hari Kanigeri");
MODULE_AUTHOR("Ramesh Gupta"); |
/* Everything about the rules for NAT. */
#include <linux/types.h>
#include <linux/ip.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/module.h>
#include <linux/kmod.h>
#include <linux/skbuff.h>
#include <linux/proc_fs.h>
#include <linux/slab.h>
#include <net/checksum.h>
#include <net/route.h>
#include <linux/bitops.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include <net/netfilter/nf_nat.h>
#include <net/netfilter/nf_nat_core.h>
#include <net/netfilter/nf_nat_rule.h>
#define NAT_VALID_HOOKS ((1 << NF_INET_PRE_ROUTING) | \
(1 << <API key>) | \
(1 << NF_INET_LOCAL_OUT))
static const struct xt_table nat_table = {
.name = "nat",
.valid_hooks = NAT_VALID_HOOKS,
.me = THIS_MODULE,
.af = NFPROTO_IPV4,
};
/* Source NAT */
static unsigned int
ipt_snat_target(struct sk_buff *skb, const struct xt_target_param *par)
{
struct nf_conn *ct;
enum ip_conntrack_info ctinfo;
const struct <API key> *mr = par->targinfo;
NF_CT_ASSERT(par->hooknum == <API key>);
ct = nf_ct_get(skb, &ctinfo);
/* Connection must be valid and new. */
NF_CT_ASSERT(ct && (ctinfo == IP_CT_NEW || ctinfo == IP_CT_RELATED ||
ctinfo == IP_CT_RELATED + IP_CT_IS_REPLY));
NF_CT_ASSERT(par->out != NULL);
return nf_nat_setup_info(ct, &mr->range[0], IP_NAT_MANIP_SRC);
}
static unsigned int
ipt_dnat_target(struct sk_buff *skb, const struct xt_target_param *par)
{
struct nf_conn *ct;
enum ip_conntrack_info ctinfo;
const struct <API key> *mr = par->targinfo;
NF_CT_ASSERT(par->hooknum == NF_INET_PRE_ROUTING ||
par->hooknum == NF_INET_LOCAL_OUT);
ct = nf_ct_get(skb, &ctinfo);
/* Connection must be valid and new. */
NF_CT_ASSERT(ct && (ctinfo == IP_CT_NEW || ctinfo == IP_CT_RELATED));
return nf_nat_setup_info(ct, &mr->range[0], IP_NAT_MANIP_DST);
}
static bool ipt_snat_checkentry(const struct xt_tgchk_param *par)
{
const struct <API key> *mr = par->targinfo;
/* Must be a valid range */
if (mr->rangesize != 1) {
printk("SNAT: multiple ranges no longer supported\n");
return false;
}
return true;
}
static bool ipt_dnat_checkentry(const struct xt_tgchk_param *par)
{
const struct <API key> *mr = par->targinfo;
/* Must be a valid range */
if (mr->rangesize != 1) {
printk("DNAT: multiple ranges no longer supported\n");
return false;
}
return true;
}
unsigned int
alloc_null_binding(struct nf_conn *ct, unsigned int hooknum)
{
/* Force range to this IP; let proto decide mapping for
per-proto parts (hence not <API key>).
Use reply in case it's already been mangled (eg local packet).
*/
__be32 ip
= (HOOK2MANIP(hooknum) == IP_NAT_MANIP_SRC
? ct->tuplehash[IP_CT_DIR_REPLY].tuple.dst.u3.ip
: ct->tuplehash[IP_CT_DIR_REPLY].tuple.src.u3.ip);
struct nf_nat_range range
= { <API key>, ip, ip, { 0 }, { 0 } };
pr_debug("Allocating NULL binding for %p (%pI4)\n", ct, &ip);
return nf_nat_setup_info(ct, &range, HOOK2MANIP(hooknum));
}
int nf_nat_rule_find(struct sk_buff *skb,
unsigned int hooknum,
const struct net_device *in,
const struct net_device *out,
struct nf_conn *ct)
{
struct net *net = nf_ct_net(ct);
int ret;
ret = ipt_do_table(skb, hooknum, in, out, net->ipv4.nat_table);
if (ret == NF_ACCEPT) {
if (!nf_nat_initialized(ct, HOOK2MANIP(hooknum)))
/* NUL mapping */
ret = alloc_null_binding(ct, hooknum);
}
return ret;
}
static struct xt_target ipt_snat_reg __read_mostly = {
.name = "SNAT",
.target = ipt_snat_target,
.targetsize = sizeof(struct <API key>),
.table = "nat",
.hooks = 1 << <API key>,
.checkentry = ipt_snat_checkentry,
.family = AF_INET,
};
static struct xt_target ipt_dnat_reg __read_mostly = {
.name = "DNAT",
.target = ipt_dnat_target,
.targetsize = sizeof(struct <API key>),
.table = "nat",
.hooks = (1 << NF_INET_PRE_ROUTING) | (1 << NF_INET_LOCAL_OUT),
.checkentry = ipt_dnat_checkentry,
.family = AF_INET,
};
static int __net_init <API key>(struct net *net)
{
struct ipt_replace *repl;
repl = <API key>(&nat_table);
if (repl == NULL)
return -ENOMEM;
net->ipv4.nat_table = ipt_register_table(net, &nat_table, repl);
kfree(repl);
if (IS_ERR(net->ipv4.nat_table))
return PTR_ERR(net->ipv4.nat_table);
return 0;
}
static void __net_exit <API key>(struct net *net)
{
<API key>(net, net->ipv4.nat_table);
}
static struct pernet_operations nf_nat_rule_net_ops = {
.init = <API key>,
.exit = <API key>,
};
int __init nf_nat_rule_init(void)
{
int ret;
ret = <API key>(&nf_nat_rule_net_ops);
if (ret != 0)
goto out;
ret = xt_register_target(&ipt_snat_reg);
if (ret != 0)
goto unregister_table;
ret = xt_register_target(&ipt_dnat_reg);
if (ret != 0)
goto unregister_snat;
return ret;
unregister_snat:
<API key>(&ipt_snat_reg);
unregister_table:
<API key>(&nf_nat_rule_net_ops);
out:
return ret;
}
void nf_nat_rule_cleanup(void)
{
<API key>(&ipt_dnat_reg);
<API key>(&ipt_snat_reg);
<API key>(&nf_nat_rule_net_ops);
} |
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/spi/spi.h>
#include <linux/iio/iio.h>
#include <linux/iio/common/st_sensors.h>
#include <linux/iio/common/st_sensors_spi.h>
#include "st_accel.h"
static int st_accel_spi_probe(struct spi_device *spi)
{
struct iio_dev *indio_dev;
struct st_sensor_data *adata;
int err;
indio_dev = iio_device_alloc(sizeof(*adata));
if (indio_dev == NULL) {
err = -ENOMEM;
goto <API key>;
}
adata = iio_priv(indio_dev);
adata->dev = &spi->dev;
<API key>(indio_dev, spi, adata);
err = <API key>(indio_dev);
if (err < 0)
goto <API key>;
return 0;
<API key>:
iio_device_free(indio_dev);
<API key>:
return err;
}
static int st_accel_spi_remove(struct spi_device *spi)
{
<API key>(spi_get_drvdata(spi));
return 0;
}
static const struct spi_device_id st_accel_id_table[] = {
{ <API key> },
{ <API key> },
{ <API key> },
{ <API key> },
{ <API key> },
{ <API key> },
{ <API key> },
{ <API key> },
{ <API key> },
{ <API key> },
{},
};
MODULE_DEVICE_TABLE(spi, st_accel_id_table);
static struct spi_driver st_accel_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "st-accel-spi",
},
.probe = st_accel_spi_probe,
.remove = st_accel_spi_remove,
.id_table = st_accel_id_table,
};
module_spi_driver(st_accel_driver);
MODULE_AUTHOR("Denis Ciocca <denis.ciocca@st.com>");
MODULE_DESCRIPTION("STMicroelectronics accelerometers spi driver");
MODULE_LICENSE("GPL v2"); |
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/device.h>
#include <linux/usb/typec.h>
#include <linux/power_supply.h>
static struct class *typec_class;
static struct device *typec_dev;
struct power_supply *usb_psy;
/* to get the Type-C Current mode */
static ssize_t current_detect_show(struct device *pdev,
struct device_attribute *attr, char *buf)
{
struct typec_device_ops *typec_ops = dev_get_drvdata(pdev);
enum typec_current_mode current_mode = typec_ops->current_detect();
return snprintf(buf, PAGE_SIZE, "%d\n", current_mode);
}
/* to get the attached state and determine what was attached */
static ssize_t attached_state_show(struct device *pdev,
struct device_attribute *attr, char *buf)
{
struct typec_device_ops *typec_ops = dev_get_drvdata(pdev);
enum <API key> attached_state =
typec_ops-><API key>();
return snprintf(buf, PAGE_SIZE, "%d\n", attached_state);
}
/* to get the current advertisement in DFP or DRP modes */
static ssize_t <API key>(struct device *pdev,
struct device_attribute *attr, char *buf)
{
struct typec_device_ops *typec_ops = dev_get_drvdata(pdev);
enum typec_current_mode current_mode =
typec_ops-><API key>();
return snprintf(buf, PAGE_SIZE, "%d\n", current_mode);
return 0;
}
/* to set the current advertisement in DFP or DRP modes */
static ssize_t <API key>(struct device *pdev,
struct device_attribute *attr,
const char *buff, size_t size)
{
struct typec_device_ops *typec_ops = dev_get_drvdata(pdev);
int current_mode;
if (sscanf(buff, "%d", ¤t_mode) != 1)
return -EINVAL;
if (current_mode >= <API key>)
return -EINVAL;
if (typec_ops-><API key>((enum typec_current_mode)
current_mode))
return -1;
return size;
}
/* to get the port mode (UFP, DFP or DRP) */
static ssize_t port_mode_ctrl_show(struct device *pdev,
struct device_attribute *attr, char *buf)
{
struct typec_device_ops *typec_ops = dev_get_drvdata(pdev);
enum typec_port_mode port_mode = typec_ops->port_mode_get();
return snprintf(buf, PAGE_SIZE, "%d\n", port_mode);
return 0;
}
/* to set the port mode (UFP, DFP or DRP), the chip will operate according the mode */
static ssize_t <API key>(struct device *pdev,
struct device_attribute *attr,
const char *buff, size_t size)
{
struct typec_device_ops *typec_ops = dev_get_drvdata(pdev);
int port_mode;
if (sscanf(buff, "%d", &port_mode) != 1)
return -EINVAL;
if (port_mode > TYPEC_DRP_MODE)
return -EINVAL;
if (typec_ops->port_mode_set((enum typec_port_mode)port_mode))
return -1;
return size;
}
/* to get all the register value */
static ssize_t dump_regs_show(struct device *pdev,
struct device_attribute *attr, char *buf)
{
struct typec_device_ops *typec_ops = dev_get_drvdata(pdev);
return typec_ops->dump_regs(buf);
}
static DEVICE_ATTR(current_detect, S_IRUGO, current_detect_show, NULL);
static DEVICE_ATTR(attached_state, S_IRUGO, attached_state_show, NULL);
static DEVICE_ATTR(current_advertise, S_IRUGO | S_IWUSR, <API key>,
<API key>);
static DEVICE_ATTR(port_mode_ctrl, S_IRUGO | S_IWUSR, port_mode_ctrl_show,
<API key>);
static DEVICE_ATTR(dump_regs, S_IRUGO, dump_regs_show, NULL);
static struct device_attribute *typec_attributes[] = {
&<API key>,
&<API key>,
&<API key>,
&<API key>,
&dev_attr_dump_regs,
NULL
};
int add_typec_device(struct device *parent, struct typec_device_ops *typec_ops)
{
struct device *dev;
struct device_attribute **attrs = typec_attributes;
struct device_attribute *attr;
int err;
if (!typec_ops || !typec_ops->current_detect
|| !typec_ops-><API key>
|| !typec_ops-><API key>
|| !typec_ops-><API key> || !typec_ops->port_mode_get
|| !typec_ops->port_mode_set || !typec_ops->dump_regs
|| !typec_ops-><API key>) {
pr_err("%s: ops is NULL\n", __func__);
return -1;
}
dev = device_create(typec_class, NULL, MKDEV(0, 0), typec_ops,
"typec_device");
if (IS_ERR(dev)) {
pr_err("%s: device_create fail\n", __func__);
return -1;
}
while ((attr = *attrs++)) {
err = device_create_file(dev, attr);
if (err) {
pr_err("%s: device_create_file fail\n", __func__);
device_destroy(typec_class, dev->devt);
return -1;
}
}
typec_dev = dev;
usb_psy = <API key>("usb");
if (!usb_psy) {
pr_err("%s USB supply not found\n", __func__);
}
return 0;
}
/* for charger to detect the typec current mode */
enum typec_current_mode <API key>(void)
{
struct typec_device_ops *typec_ops;
enum typec_current_mode current_mode = <API key>;
if (!typec_dev) {
pr_err("%s: no typec device registered\n", __func__);
return current_mode;
}
typec_ops = dev_get_drvdata(typec_dev);
current_mode = typec_ops-><API key>();
return current_mode;
}
int <API key>(enum typec_event typec_event)
{
if (!usb_psy) {
pr_err("%s USB supply not found\n", __func__);
return -1;
}
<API key>(usb_psy,
(typec_event == TYPEC_SINK_DETECTED) ? 1 : 0);
return 0;
}
#define HIGH_CURRENT_UA 1800000
#define MEDIUM_CURRENT_UA 1500000
#define DEFAULT_CURRENT_UA 500000
void <API key>(enum typec_current_mode current_mode)
{
int limit = DEFAULT_CURRENT_UA;
if (!usb_psy) {
pr_err("%s USB supply not found\n", __func__);
}
switch (current_mode) {
case <API key>:
limit = MEDIUM_CURRENT_UA;
break;
case <API key>:
limit = HIGH_CURRENT_UA;
break;
default:
return;
}
<API key>(usb_psy, limit);
}
static int __init typec_init(void)
{
typec_class = class_create(THIS_MODULE, "typec");
if (IS_ERR(typec_class)) {
pr_err("failed to create typec class --> %ld\n",
PTR_ERR(typec_class));
return PTR_ERR(typec_class);
}
return 0;
}
subsys_initcall(typec_init);
static void __exit typec_exit(void)
{
class_destroy(typec_class);
}
module_exit(typec_exit);
MODULE_AUTHOR("HUAWEI");
MODULE_DESCRIPTION("Type-C connector Framework");
MODULE_LICENSE("GPL v2"); |
#include <linux/module.h>
#include <linux/netdevice.h>
#include "cxgb4.h"
#include "sched.h"
static int <API key>(struct port_info *pi,
struct ch_sched_params *p,
enum sched_fw_ops op)
{
struct adapter *adap = pi->adapter;
struct sched_table *s = pi->sched_tbl;
struct sched_class *e;
int err = 0;
e = &s->tab[p->u.params.class];
switch (op) {
case SCHED_FW_OP_ADD:
case SCHED_FW_OP_DEL:
err = t4_sched_params(adap, p->type,
p->u.params.level, p->u.params.mode,
p->u.params.rateunit,
p->u.params.ratemode,
p->u.params.channel, e->idx,
p->u.params.minrate, p->u.params.maxrate,
p->u.params.weight, p->u.params.pktsize);
break;
default:
err = -ENOTSUPP;
break;
}
return err;
}
static int <API key>(struct port_info *pi, void *arg,
enum sched_bind_type type, bool bind)
{
struct adapter *adap = pi->adapter;
u32 fw_mnem, fw_class, fw_param;
unsigned int pf = adap->pf;
unsigned int vf = 0;
int err = 0;
switch (type) {
case SCHED_QUEUE: {
struct sched_queue_entry *qe;
qe = (struct sched_queue_entry *)arg;
/* Create a template for the FW_PARAMS_CMD mnemonic and
* value (TX Scheduling Class in this case).
*/
fw_mnem = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DMAQ) |
FW_PARAMS_PARAM_X_V(
<API key>));
fw_class = bind ? qe->param.class : FW_SCHED_CLS_NONE;
fw_param = (fw_mnem | <API key>(qe->cntxt_id));
pf = adap->pf;
vf = 0;
err = t4_set_params(adap, adap->mbox, pf, vf, 1,
&fw_param, &fw_class);
break;
}
case SCHED_FLOWC: {
struct sched_flowc_entry *fe;
fe = (struct sched_flowc_entry *)arg;
fw_class = bind ? fe->param.class : FW_SCHED_CLS_NONE;
err = <API key>(adap->port[pi->port_id],
fe->param.tid, fw_class);
break;
}
default:
err = -ENOTSUPP;
break;
}
return err;
}
static void *<API key>(struct port_info *pi,
enum sched_bind_type type,
const u32 val)
{
struct sched_table *s = pi->sched_tbl;
struct sched_class *e, *end;
void *found = NULL;
/* Look for an entry with matching @val */
end = &s->tab[s->sched_size];
for (e = &s->tab[0]; e != end; ++e) {
if (e->state == SCHED_STATE_UNUSED ||
e->bind_type != type)
continue;
switch (type) {
case SCHED_QUEUE: {
struct sched_queue_entry *qe;
list_for_each_entry(qe, &e->entry_list, list) {
if (qe->cntxt_id == val) {
found = qe;
break;
}
}
break;
}
case SCHED_FLOWC: {
struct sched_flowc_entry *fe;
list_for_each_entry(fe, &e->entry_list, list) {
if (fe->param.tid == val) {
found = fe;
break;
}
}
break;
}
default:
return NULL;
}
if (found)
break;
}
return found;
}
struct sched_class *<API key>(struct net_device *dev,
struct ch_sched_queue *p)
{
struct port_info *pi = netdev2pinfo(dev);
struct sched_queue_entry *qe = NULL;
struct adapter *adap = pi->adapter;
struct sge_eth_txq *txq;
if (p->queue < 0 || p->queue >= pi->nqsets)
return NULL;
txq = &adap->sge.ethtxq[pi->first_qset + p->queue];
qe = <API key>(pi, SCHED_QUEUE, txq->q.cntxt_id);
return qe ? &pi->sched_tbl->tab[qe->param.class] : NULL;
}
static int <API key>(struct port_info *pi, struct ch_sched_queue *p)
{
struct sched_queue_entry *qe = NULL;
struct adapter *adap = pi->adapter;
struct sge_eth_txq *txq;
struct sched_class *e;
int err = 0;
if (p->queue < 0 || p->queue >= pi->nqsets)
return -ERANGE;
txq = &adap->sge.ethtxq[pi->first_qset + p->queue];
/* Find the existing entry that the queue is bound to */
qe = <API key>(pi, SCHED_QUEUE, txq->q.cntxt_id);
if (qe) {
err = <API key>(pi, (void *)qe, SCHED_QUEUE,
false);
if (err)
return err;
e = &pi->sched_tbl->tab[qe->param.class];
list_del(&qe->list);
kvfree(qe);
if (atomic_dec_and_test(&e->refcnt))
<API key>(adap->port[pi->port_id], e->idx);
}
return err;
}
static int t4_sched_queue_bind(struct port_info *pi, struct ch_sched_queue *p)
{
struct sched_table *s = pi->sched_tbl;
struct sched_queue_entry *qe = NULL;
struct adapter *adap = pi->adapter;
struct sge_eth_txq *txq;
struct sched_class *e;
unsigned int qid;
int err = 0;
if (p->queue < 0 || p->queue >= pi->nqsets)
return -ERANGE;
qe = kvzalloc(sizeof(struct sched_queue_entry), GFP_KERNEL);
if (!qe)
return -ENOMEM;
txq = &adap->sge.ethtxq[pi->first_qset + p->queue];
qid = txq->q.cntxt_id;
/* Unbind queue from any existing class */
err = <API key>(pi, p);
if (err)
goto out_err;
/* Bind queue to specified class */
qe->cntxt_id = qid;
memcpy(&qe->param, p, sizeof(qe->param));
e = &s->tab[qe->param.class];
err = <API key>(pi, (void *)qe, SCHED_QUEUE, true);
if (err)
goto out_err;
list_add_tail(&qe->list, &e->entry_list);
e->bind_type = SCHED_QUEUE;
atomic_inc(&e->refcnt);
return err;
out_err:
kvfree(qe);
return err;
}
static int <API key>(struct port_info *pi, struct ch_sched_flowc *p)
{
struct sched_flowc_entry *fe = NULL;
struct adapter *adap = pi->adapter;
struct sched_class *e;
int err = 0;
if (p->tid < 0 || p->tid >= adap->tids.neotids)
return -ERANGE;
/* Find the existing entry that the flowc is bound to */
fe = <API key>(pi, SCHED_FLOWC, p->tid);
if (fe) {
err = <API key>(pi, (void *)fe, SCHED_FLOWC,
false);
if (err)
return err;
e = &pi->sched_tbl->tab[fe->param.class];
list_del(&fe->list);
kvfree(fe);
if (atomic_dec_and_test(&e->refcnt))
<API key>(adap->port[pi->port_id], e->idx);
}
return err;
}
static int t4_sched_flowc_bind(struct port_info *pi, struct ch_sched_flowc *p)
{
struct sched_table *s = pi->sched_tbl;
struct sched_flowc_entry *fe = NULL;
struct adapter *adap = pi->adapter;
struct sched_class *e;
int err = 0;
if (p->tid < 0 || p->tid >= adap->tids.neotids)
return -ERANGE;
fe = kvzalloc(sizeof(*fe), GFP_KERNEL);
if (!fe)
return -ENOMEM;
/* Unbind flowc from any existing class */
err = <API key>(pi, p);
if (err)
goto out_err;
/* Bind flowc to specified class */
memcpy(&fe->param, p, sizeof(fe->param));
e = &s->tab[fe->param.class];
err = <API key>(pi, (void *)fe, SCHED_FLOWC, true);
if (err)
goto out_err;
list_add_tail(&fe->list, &e->entry_list);
e->bind_type = SCHED_FLOWC;
atomic_inc(&e->refcnt);
return err;
out_err:
kvfree(fe);
return err;
}
static void <API key>(struct port_info *pi,
struct sched_class *e,
enum sched_bind_type type)
{
if (!e)
return;
switch (type) {
case SCHED_QUEUE: {
struct sched_queue_entry *qe;
list_for_each_entry(qe, &e->entry_list, list)
<API key>(pi, &qe->param);
break;
}
case SCHED_FLOWC: {
struct sched_flowc_entry *fe;
list_for_each_entry(fe, &e->entry_list, list)
<API key>(pi, &fe->param);
break;
}
default:
break;
}
}
static int <API key>(struct port_info *pi, void *arg,
enum sched_bind_type type, bool bind)
{
int err = 0;
if (!arg)
return -EINVAL;
switch (type) {
case SCHED_QUEUE: {
struct ch_sched_queue *qe = (struct ch_sched_queue *)arg;
if (bind)
err = t4_sched_queue_bind(pi, qe);
else
err = <API key>(pi, qe);
break;
}
case SCHED_FLOWC: {
struct ch_sched_flowc *fe = (struct ch_sched_flowc *)arg;
if (bind)
err = t4_sched_flowc_bind(pi, fe);
else
err = <API key>(pi, fe);
break;
}
default:
err = -ENOTSUPP;
break;
}
return err;
}
/**
* <API key> - Bind an entity to a scheduling class
* @dev: net_device pointer
* @arg: Entity opaque data
* @type: Entity type (Queue)
*
* Binds an entity (queue) to a scheduling class. If the entity
* is bound to another class, it will be unbound from the other class
* and bound to the class specified in @arg.
*/
int <API key>(struct net_device *dev, void *arg,
enum sched_bind_type type)
{
struct port_info *pi = netdev2pinfo(dev);
u8 class_id;
if (!can_sched(dev))
return -ENOTSUPP;
if (!arg)
return -EINVAL;
switch (type) {
case SCHED_QUEUE: {
struct ch_sched_queue *qe = (struct ch_sched_queue *)arg;
class_id = qe->class;
break;
}
case SCHED_FLOWC: {
struct ch_sched_flowc *fe = (struct ch_sched_flowc *)arg;
class_id = fe->class;
break;
}
default:
return -ENOTSUPP;
}
if (!valid_class_id(dev, class_id))
return -EINVAL;
if (class_id == SCHED_CLS_NONE)
return -ENOTSUPP;
return <API key>(pi, arg, type, true);
}
/**
* <API key> - Unbind an entity from a scheduling class
* @dev: net_device pointer
* @arg: Entity opaque data
* @type: Entity type (Queue)
*
* Unbinds an entity (queue) from a scheduling class.
*/
int <API key>(struct net_device *dev, void *arg,
enum sched_bind_type type)
{
struct port_info *pi = netdev2pinfo(dev);
u8 class_id;
if (!can_sched(dev))
return -ENOTSUPP;
if (!arg)
return -EINVAL;
switch (type) {
case SCHED_QUEUE: {
struct ch_sched_queue *qe = (struct ch_sched_queue *)arg;
class_id = qe->class;
break;
}
case SCHED_FLOWC: {
struct ch_sched_flowc *fe = (struct ch_sched_flowc *)arg;
class_id = fe->class;
break;
}
default:
return -ENOTSUPP;
}
if (!valid_class_id(dev, class_id))
return -EINVAL;
return <API key>(pi, arg, type, false);
}
/* If @p is NULL, fetch any available unused class */
static struct sched_class *<API key>(struct port_info *pi,
const struct ch_sched_params *p)
{
struct sched_table *s = pi->sched_tbl;
struct sched_class *found = NULL;
struct sched_class *e, *end;
if (!p) {
/* Get any available unused class */
end = &s->tab[s->sched_size];
for (e = &s->tab[0]; e != end; ++e) {
if (e->state == SCHED_STATE_UNUSED) {
found = e;
break;
}
}
} else {
/* Look for a class with matching scheduling parameters */
struct ch_sched_params info;
struct ch_sched_params tp;
memcpy(&tp, p, sizeof(tp));
/* Don't try to match class parameter */
tp.u.params.class = SCHED_CLS_NONE;
end = &s->tab[s->sched_size];
for (e = &s->tab[0]; e != end; ++e) {
if (e->state == SCHED_STATE_UNUSED)
continue;
memcpy(&info, &e->info, sizeof(info));
/* Don't try to match class parameter */
info.u.params.class = SCHED_CLS_NONE;
if ((info.type == tp.type) &&
(!memcmp(&info.u.params, &tp.u.params,
sizeof(info.u.params)))) {
found = e;
break;
}
}
}
return found;
}
static struct sched_class *<API key>(struct port_info *pi,
struct ch_sched_params *p)
{
struct sched_class *e = NULL;
u8 class_id;
int err;
if (!p)
return NULL;
class_id = p->u.params.class;
/* Only accept search for existing class with matching params
* or allocation of new class with specified params
*/
if (class_id != SCHED_CLS_NONE)
return NULL;
/* See if there's an exisiting class with same requested sched
* params. Classes can only be shared among FLOWC types. For
* other types, always request a new class.
*/
if (p->u.params.mode == <API key>)
e = <API key>(pi, p);
if (!e) {
struct ch_sched_params np;
/* Fetch any available unused class */
e = <API key>(pi, NULL);
if (!e)
return NULL;
memcpy(&np, p, sizeof(np));
np.u.params.class = e->idx;
/* New class */
err = <API key>(pi, &np, SCHED_FW_OP_ADD);
if (err)
return NULL;
memcpy(&e->info, &np, sizeof(e->info));
atomic_set(&e->refcnt, 0);
e->state = SCHED_STATE_ACTIVE;
}
return e;
}
/**
* <API key> - allocate a scheduling class
* @dev: net_device pointer
* @p: new scheduling class to create.
*
* Returns pointer to the scheduling class created. If @p is NULL, then
* it allocates and returns any available unused scheduling class. If a
* scheduling class with matching @p is found, then the matching class is
* returned.
*/
struct sched_class *<API key>(struct net_device *dev,
struct ch_sched_params *p)
{
struct port_info *pi = netdev2pinfo(dev);
u8 class_id;
if (!can_sched(dev))
return NULL;
class_id = p->u.params.class;
if (!valid_class_id(dev, class_id))
return NULL;
return <API key>(pi, p);
}
/**
* <API key> - free a scheduling class
* @dev: net_device pointer
* @e: scheduling class
*
* Frees a scheduling class if there are no users.
*/
void <API key>(struct net_device *dev, u8 classid)
{
struct port_info *pi = netdev2pinfo(dev);
struct sched_table *s = pi->sched_tbl;
struct ch_sched_params p;
struct sched_class *e;
u32 speed;
int ret;
e = &s->tab[classid];
if (!atomic_read(&e->refcnt) && e->state != SCHED_STATE_UNUSED) {
/* Port based rate limiting needs explicit reset back
* to max rate. But, we'll do explicit reset for all
* types, instead of just port based type, to be on
* the safer side.
*/
memcpy(&p, &e->info, sizeof(p));
/* Always reset mode to 0. Otherwise, FLOWC mode will
* still be enabled even after resetting the traffic
* class.
*/
p.u.params.mode = 0;
p.u.params.minrate = 0;
p.u.params.pktsize = 0;
ret = t4_get_link_params(pi, NULL, &speed, NULL);
if (!ret)
p.u.params.maxrate = speed * 1000; /* Mbps to Kbps */
else
p.u.params.maxrate = SCHED_MAX_RATE_KBPS;
<API key>(pi, &p, SCHED_FW_OP_DEL);
e->state = SCHED_STATE_UNUSED;
memset(&e->info, 0, sizeof(e->info));
}
}
static void t4_sched_class_free(struct net_device *dev, struct sched_class *e)
{
struct port_info *pi = netdev2pinfo(dev);
<API key>(pi, e, e->bind_type);
<API key>(dev, e->idx);
}
struct sched_table *t4_init_sched(unsigned int sched_size)
{
struct sched_table *s;
unsigned int i;
s = kvzalloc(struct_size(s, tab, sched_size), GFP_KERNEL);
if (!s)
return NULL;
s->sched_size = sched_size;
for (i = 0; i < s->sched_size; i++) {
memset(&s->tab[i], 0, sizeof(struct sched_class));
s->tab[i].idx = i;
s->tab[i].state = SCHED_STATE_UNUSED;
INIT_LIST_HEAD(&s->tab[i].entry_list);
atomic_set(&s->tab[i].refcnt, 0);
}
return s;
}
void t4_cleanup_sched(struct adapter *adap)
{
struct sched_table *s;
unsigned int j, i;
for_each_port(adap, j) {
struct port_info *pi = netdev2pinfo(adap->port[j]);
s = pi->sched_tbl;
if (!s)
continue;
for (i = 0; i < s->sched_size; i++) {
struct sched_class *e;
e = &s->tab[i];
if (e->state == SCHED_STATE_ACTIVE)
t4_sched_class_free(adap->port[j], e);
}
kvfree(s);
}
} |
#ifndef <API key>
#define <API key>
#include <linux/sockios.h>
#define <API key> 0x1
#define <API key> 0x2
//#define <API key> 3
#define <API key> 7 //DUN context 1-7
#define <API key> 10 //based on CP support
#define <API key> (<API key> + 1) //8 for now
#define <API key> (<API key> - <API key>) //RIL context id 8-10
//due to the support for DUN, which requires to use cid starting from 0,
//RIL now has cid range from 8-10 (<API key> - <API key>)
//but android has hardcoded rmnet0 in several places, in order not to change
//android code for later integration compliexity, we map rmnet0-rmnet2 with cid 8-10
//and have rmnet3-rmnet9 with cid 1-7 for DUN
#define RIL_CID_TO_RMNET(cid) (cid - <API key>)
#define DUN_CID_TO_RMNET(cid) (cid + <API key> - 1)
#define RIL_RMNET_TO_CID(rmnetId) (rmnetId + <API key>)
#define DUN_RMNET_TO_CID(rmnetId) (rmnetId - <API key> + 1)
#define RMNET_TO_CID(rmnetId) \
(rmnetId < <API key>)?RIL_RMNET_TO_CID(rmnetId):DUN_RMNET_TO_CID(rmnetId)
#define <API key> 255
#define BCM_NET_DEV_STR "rmnet%d"
typedef struct {
int context_id;
unsigned long ip_addr;
} bcm_fuse_net_pdp_t;
typedef struct {
unsigned short cmd;
void *cmd_data; /* pointer to user buffer */
uint data_len; /* length of user buffer */
} <API key>;
#endif /* <API key> */ |
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
#ifndef <API key>
#define <API key>
#ifdef __cplusplus
extern "C"
{
#endif
JNIEXPORT void JNICALL <API key> (JNIEnv *env, jobject);
JNIEXPORT jintArray JNICALL <API key> (JNIEnv *env, jobject);
JNIEXPORT void JNICALL <API key> (JNIEnv *env, jobject, jintArray);
JNIEXPORT jboolean JNICALL <API key> (JNIEnv *env, jobject, jstring);
JNIEXPORT jboolean JNICALL <API key> (JNIEnv *env, jobject, jbyteArray);
JNIEXPORT void JNICALL <API key> (JNIEnv *env, jobject);
JNIEXPORT void JNICALL <API key> (JNIEnv *env, jobject);
JNIEXPORT void JNICALL <API key> (JNIEnv *env, jobject, jobject, jint);
JNIEXPORT void JNICALL <API key> (JNIEnv *env, jobject, jobject, jint, jint, jint, jint, jint, jboolean);
JNIEXPORT void JNICALL <API key> (JNIEnv *env, jobject, jobject, jint, jint, jint, jint, jint, jint, jint, jboolean);
JNIEXPORT void JNICALL <API key> (JNIEnv *env, jobject, jobject, jobject);
JNIEXPORT void JNICALL <API key> (JNIEnv *env, jobject, jobject, jint, jint, jint, jboolean, jboolean, jint, jint, jint, jint, jint, jint, jint, jint, jboolean);
JNIEXPORT void JNICALL <API key> (JNIEnv *env, jobject, jint, jint, jint, jint, jint, jint);
#ifdef __cplusplus
}
#endif
#endif /* <API key> */ |
#ifndef CIK_H
#define CIK_H
#define <API key> 0x12010001
#define <API key> 2
/* SMC IND registers */
#define GENERAL_PWRMGT 0xC0200000
# define GPU_COUNTER_CLK (1 << 15)
#define CG_CLKPIN_CNTL 0xC05001A0
# define XTALIN_DIVIDE (1 << 1)
#define PCIE_INDEX 0x38
#define PCIE_DATA 0x3C
#define VGA_HDP_CONTROL 0x328
#define VGA_MEMORY_DISABLE (1 << 4)
#define DMIF_ADDR_CALC 0xC00
#define SRBM_GFX_CNTL 0xE44
#define PIPEID(x) ((x) << 0)
#define MEID(x) ((x) << 2)
#define VMID(x) ((x) << 4)
#define QUEUEID(x) ((x) << 8)
#define SRBM_STATUS2 0xE4C
#define SDMA_BUSY (1 << 5)
#define SDMA1_BUSY (1 << 6)
#define SRBM_STATUS 0xE50
#define UVD_RQ_PENDING (1 << 1)
#define GRBM_RQ_PENDING (1 << 5)
#define VMC_BUSY (1 << 8)
#define MCB_BUSY (1 << 9)
#define <API key> (1 << 10)
#define MCC_BUSY (1 << 11)
#define MCD_BUSY (1 << 12)
#define SEM_BUSY (1 << 14)
#define IH_BUSY (1 << 17)
#define UVD_BUSY (1 << 19)
#define SRBM_SOFT_RESET 0xE60
#define SOFT_RESET_BIF (1 << 1)
#define SOFT_RESET_R0PLL (1 << 4)
#define SOFT_RESET_DC (1 << 5)
#define SOFT_RESET_SDMA1 (1 << 6)
#define SOFT_RESET_GRBM (1 << 8)
#define SOFT_RESET_HDP (1 << 9)
#define SOFT_RESET_IH (1 << 10)
#define SOFT_RESET_MC (1 << 11)
#define SOFT_RESET_ROM (1 << 14)
#define SOFT_RESET_SEM (1 << 15)
#define SOFT_RESET_VMC (1 << 17)
#define SOFT_RESET_SDMA (1 << 20)
#define SOFT_RESET_TST (1 << 21)
#define SOFT_RESET_REGBB (1 << 22)
#define SOFT_RESET_ORB (1 << 23)
#define SOFT_RESET_VCE (1 << 24)
#define VM_L2_CNTL 0x1400
#define ENABLE_L2_CACHE (1 << 0)
#define <API key> (1 << 1)
#define <API key>(x) ((x) << 2)
#define <API key>(x) ((x) << 4)
#define <API key> (1 << 9)
#define <API key> (1 << 10)
#define <API key>(x) (((x) & 7) << 15)
#define <API key>(x) (((x) & 3) << 19)
#define VM_L2_CNTL2 0x1404
#define <API key> (1 << 0)
#define INVALIDATE_L2_CACHE (1 << 1)
#define <API key>(x) ((x) << 26)
#define <API key> 0
#define <API key> 1
#define <API key> 2
#define VM_L2_CNTL3 0x1408
#define BANK_SELECT(x) ((x) << 0)
#define <API key>(x) ((x) << 6)
#define <API key>(x) ((x) << 15)
#define <API key> (1 << 20)
#define VM_L2_STATUS 0x140C
#define L2_BUSY (1 << 0)
#define VM_CONTEXT0_CNTL 0x1410
#define ENABLE_CONTEXT (1 << 0)
#define PAGE_TABLE_DEPTH(x) (((x) & 3) << 1)
#define <API key> (1 << 3)
#define <API key> (1 << 4)
#define <API key> (1 << 6)
#define <API key> (1 << 7)
#define <API key> (1 << 9)
#define <API key> (1 << 10)
#define <API key> (1 << 12)
#define <API key> (1 << 13)
#define <API key> (1 << 15)
#define <API key> (1 << 16)
#define <API key> (1 << 18)
#define <API key> (1 << 19)
#define VM_CONTEXT1_CNTL 0x1414
#define VM_CONTEXT0_CNTL2 0x1430
#define VM_CONTEXT1_CNTL2 0x1434
#define <API key> 0x1438
#define <API key> 0x143c
#define <API key> 0x1440
#define <API key> 0x1444
#define <API key> 0x1448
#define <API key> 0x144c
#define <API key> 0x1450
#define <API key> 0x1454
#define <API key> 0x1478
#define <API key> 0x147c
#define <API key> 0x14DC
#define PROTECTIONS_MASK (0xf << 0)
#define PROTECTIONS_SHIFT 0
/* bit 0: range
* bit 1: pde0
* bit 2: valid
* bit 3: read
* bit 4: write
*/
#define <API key> (0xff << 12)
#define <API key> 12
#define <API key> (1 << 24)
#define <API key> 24
#define FAULT_VMID_MASK (0xf << 25)
#define FAULT_VMID_SHIFT 25
#define <API key> 0x14E4
#define <API key> 0x14FC
#define <API key> 0x1518
#define <API key> 0x151c
#define <API key> 0x153c
#define <API key> 0x1540
#define <API key> 0x1544
#define <API key> 0x1548
#define <API key> 0x154c
#define <API key> 0x1550
#define <API key> 0x1554
#define <API key> 0x1558
#define <API key> 0x155c
#define <API key> 0x1560
#define <API key> 0x157C
#define <API key> 0x1580
#define MC_SHARED_CHMAP 0x2004
#define NOOFCHAN_SHIFT 12
#define NOOFCHAN_MASK 0x0000f000
#define MC_SHARED_CHREMAP 0x2008
#define CHUB_CONTROL 0x1864
#define BYPASS_VM (1 << 0)
#define MC_VM_FB_LOCATION 0x2024
#define MC_VM_AGP_TOP 0x2028
#define MC_VM_AGP_BOT 0x202C
#define MC_VM_AGP_BASE 0x2030
#define <API key> 0x2034
#define <API key> 0x2038
#define <API key> 0x203C
#define <API key> 0x2064
#define ENABLE_L1_TLB (1 << 0)
#define <API key> (1 << 1)
#define <API key> (0 << 3)
#define <API key> (1 << 3)
#define <API key> (2 << 3)
#define <API key> (3 << 3)
#define <API key> (0 << 5)
#define <API key> (1 << 6)
#define MC_VM_FB_OFFSET 0x2068
#define <API key> 0x20ac
#define MC_ARB_RAMCFG 0x2760
#define NOOFBANK_SHIFT 0
#define NOOFBANK_MASK 0x00000003
#define NOOFRANK_SHIFT 2
#define NOOFRANK_MASK 0x00000004
#define NOOFROWS_SHIFT 3
#define NOOFROWS_MASK 0x00000038
#define NOOFCOLS_SHIFT 6
#define NOOFCOLS_MASK 0x000000C0
#define CHANSIZE_SHIFT 8
#define CHANSIZE_MASK 0x00000100
#define NOOFGROUPS_SHIFT 12
#define NOOFGROUPS_MASK 0x00001000
#define MC_SEQ_SUP_CNTL 0x28c8
#define RUN_MASK (1 << 0)
#define MC_SEQ_SUP_PGM 0x28cc
#define <API key> 0x28e8
#define TRAIN_DONE_D0 (1 << 30)
#define TRAIN_DONE_D1 (1 << 31)
#define MC_IO_PAD_CNTL_D0 0x29d0
#define MEM_FALL_OUT_CMD (1 << 8)
#define <API key> 0x2a44
#define <API key> 0x2a48
#define HDP_HOST_PATH_CNTL 0x2C00
#define HDP_NONSURFACE_BASE 0x2C04
#define HDP_NONSURFACE_INFO 0x2C08
#define HDP_NONSURFACE_SIZE 0x2C0C
#define HDP_ADDR_CONFIG 0x2F48
#define HDP_MISC_CNTL 0x2F4C
#define <API key> (1 << 0)
#define IH_RB_CNTL 0x3e00
# define IH_RB_ENABLE (1 << 0)
# define IH_RB_SIZE(x) ((x) << 1) /* log2 */
# define <API key> (1 << 6)
# define <API key> (1 << 8)
# define <API key>(x) ((x) << 9) /* log2 */
# define <API key> (1 << 16)
# define <API key> (1 << 31)
#define IH_RB_BASE 0x3e04
#define IH_RB_RPTR 0x3e08
#define IH_RB_WPTR 0x3e0c
# define RB_OVERFLOW (1 << 0)
# define WPTR_OFFSET_MASK 0x3fffc
#define IH_RB_WPTR_ADDR_HI 0x3e10
#define IH_RB_WPTR_ADDR_LO 0x3e14
#define IH_CNTL 0x3e18
# define ENABLE_INTR (1 << 0)
# define IH_MC_SWAP(x) ((x) << 1)
# define IH_MC_SWAP_NONE 0
# define IH_MC_SWAP_16BIT 1
# define IH_MC_SWAP_32BIT 2
# define IH_MC_SWAP_64BIT 3
# define RPTR_REARM (1 << 4)
# define MC_WRREQ_CREDIT(x) ((x) << 15)
# define MC_WR_CLEAN_CNT(x) ((x) << 20)
# define MC_VMID(x) ((x) << 25)
#define CONFIG_MEMSIZE 0x5428
#define INTERRUPT_CNTL 0x5468
# define <API key> (1 << 0)
# define IH_DUMMY_RD_EN (1 << 1)
# define IH_REQ_NONSNOOP_EN (1 << 3)
# define GEN_IH_INT_EN (1 << 8)
#define INTERRUPT_CNTL2 0x546c
#define <API key> 0x5480
#define BIF_FB_EN 0x5490
#define FB_READ_EN (1 << 0)
#define FB_WRITE_EN (1 << 1)
#define <API key> 0x54A0
#define GPU_HDP_FLUSH_REQ 0x54DC
#define GPU_HDP_FLUSH_DONE 0x54E0
#define CP0 (1 << 0)
#define CP1 (1 << 1)
#define CP2 (1 << 2)
#define CP3 (1 << 3)
#define CP4 (1 << 4)
#define CP5 (1 << 5)
#define CP6 (1 << 6)
#define CP7 (1 << 7)
#define CP8 (1 << 8)
#define CP9 (1 << 9)
#define SDMA0 (1 << 10)
#define SDMA1 (1 << 11)
/* 0x6b04, 0x7704, 0x10304, 0x10f04, 0x11b04, 0x12704 */
#define LB_MEMORY_CTRL 0x6b04
#define LB_MEMORY_SIZE(x) ((x) << 0)
#define LB_MEMORY_CONFIG(x) ((x) << 20)
#define <API key> 0x6cc8
# define <API key>(x) ((x) << 8)
#define <API key> 0x6ccc
# define <API key>(x) ((x) << 0)
# define <API key>(x) ((x) << 16)
/* 0x6b24, 0x7724, 0x10324, 0x10f24, 0x11b24, 0x12724 */
#define LB_VLINE_STATUS 0x6b24
# define VLINE_OCCURRED (1 << 0)
# define VLINE_ACK (1 << 4)
# define VLINE_STAT (1 << 12)
# define VLINE_INTERRUPT (1 << 16)
# define <API key> (1 << 17)
/* 0x6b2c, 0x772c, 0x1032c, 0x10f2c, 0x11b2c, 0x1272c */
#define LB_VBLANK_STATUS 0x6b2c
# define VBLANK_OCCURRED (1 << 0)
# define VBLANK_ACK (1 << 4)
# define VBLANK_STAT (1 << 12)
# define VBLANK_INTERRUPT (1 << 16)
# define <API key> (1 << 17)
/* 0x6b20, 0x7720, 0x10320, 0x10f20, 0x11b20, 0x12720 */
#define LB_INTERRUPT_MASK 0x6b20
# define <API key> (1 << 0)
# define <API key> (1 << 4)
# define <API key> (1 << 8)
#define <API key> 0x60f4
# define <API key> (1 << 2)
# define <API key> (1 << 3)
# define DC_HPD1_INTERRUPT (1 << 17)
# define <API key> (1 << 18)
# define <API key> (1 << 22)
# define <API key> (1 << 23)
# define <API key> (1 << 24)
# define <API key> (1 << 25)
#define <API key> 0x60f8
# define <API key> (1 << 2)
# define <API key> (1 << 3)
# define DC_HPD2_INTERRUPT (1 << 17)
# define <API key> (1 << 18)
# define <API key> (1 << 24)
#define <API key> 0x60fc
# define <API key> (1 << 2)
# define <API key> (1 << 3)
# define DC_HPD3_INTERRUPT (1 << 17)
# define <API key> (1 << 18)
#define <API key> 0x6100
# define <API key> (1 << 2)
# define <API key> (1 << 3)
# define DC_HPD4_INTERRUPT (1 << 17)
# define <API key> (1 << 18)
#define <API key> 0x614c
# define <API key> (1 << 2)
# define <API key> (1 << 3)
# define DC_HPD5_INTERRUPT (1 << 17)
# define <API key> (1 << 18)
#define <API key> 0x6150
# define <API key> (1 << 2)
# define <API key> (1 << 3)
# define DC_HPD6_INTERRUPT (1 << 17)
# define <API key> (1 << 18)
#define <API key> 0x6780
#define <API key> 0x67c8
#define DC_HPD1_INT_STATUS 0x601c
#define DC_HPD2_INT_STATUS 0x6028
#define DC_HPD3_INT_STATUS 0x6034
#define DC_HPD4_INT_STATUS 0x6040
#define DC_HPD5_INT_STATUS 0x604c
#define DC_HPD6_INT_STATUS 0x6058
# define DC_HPDx_INT_STATUS (1 << 0)
# define DC_HPDx_SENSE (1 << 1)
# define <API key> (1 << 4)
# define <API key> (1 << 8)
#define DC_HPD1_INT_CONTROL 0x6020
#define DC_HPD2_INT_CONTROL 0x602c
#define DC_HPD3_INT_CONTROL 0x6038
#define DC_HPD4_INT_CONTROL 0x6044
#define DC_HPD5_INT_CONTROL 0x6050
#define DC_HPD6_INT_CONTROL 0x605c
# define DC_HPDx_INT_ACK (1 << 0)
# define <API key> (1 << 8)
# define DC_HPDx_INT_EN (1 << 16)
# define DC_HPDx_RX_INT_ACK (1 << 20)
# define DC_HPDx_RX_INT_EN (1 << 24)
#define DC_HPD1_CONTROL 0x6024
#define DC_HPD2_CONTROL 0x6030
#define DC_HPD3_CONTROL 0x603c
#define DC_HPD4_CONTROL 0x6048
#define DC_HPD5_CONTROL 0x6054
#define DC_HPD6_CONTROL 0x6060
# define <API key>(x) ((x) << 0)
# define <API key>(x) ((x) << 16)
# define DC_HPDx_EN (1 << 28)
#define GRBM_CNTL 0x8000
#define GRBM_READ_TIMEOUT(x) ((x) << 0)
#define GRBM_STATUS2 0x8008
#define <API key> 0x0000000F
#define <API key> (1 << 4)
#define <API key> (1 << 5)
#define ME1PIPE0_RQ_PENDING (1 << 6)
#define ME1PIPE1_RQ_PENDING (1 << 7)
#define ME1PIPE2_RQ_PENDING (1 << 8)
#define ME1PIPE3_RQ_PENDING (1 << 9)
#define ME2PIPE0_RQ_PENDING (1 << 10)
#define ME2PIPE1_RQ_PENDING (1 << 11)
#define ME2PIPE2_RQ_PENDING (1 << 12)
#define ME2PIPE3_RQ_PENDING (1 << 13)
#define RLC_RQ_PENDING (1 << 14)
#define RLC_BUSY (1 << 24)
#define TC_BUSY (1 << 25)
#define CPF_BUSY (1 << 28)
#define CPC_BUSY (1 << 29)
#define CPG_BUSY (1 << 30)
#define GRBM_STATUS 0x8010
#define <API key> 0x0000000F
#define SRBM_RQ_PENDING (1 << 5)
#define <API key> (1 << 7)
#define <API key> (1 << 8)
#define GDS_DMA_RQ_PENDING (1 << 9)
#define DB_CLEAN (1 << 12)
#define CB_CLEAN (1 << 13)
#define TA_BUSY (1 << 14)
#define GDS_BUSY (1 << 15)
#define WD_BUSY_NO_DMA (1 << 16)
#define VGT_BUSY (1 << 17)
#define IA_BUSY_NO_DMA (1 << 18)
#define IA_BUSY (1 << 19)
#define SX_BUSY (1 << 20)
#define WD_BUSY (1 << 21)
#define SPI_BUSY (1 << 22)
#define BCI_BUSY (1 << 23)
#define SC_BUSY (1 << 24)
#define PA_BUSY (1 << 25)
#define DB_BUSY (1 << 26)
#define CP_COHERENCY_BUSY (1 << 28)
#define CP_BUSY (1 << 29)
#define CB_BUSY (1 << 30)
#define GUI_ACTIVE (1 << 31)
#define GRBM_STATUS_SE0 0x8014
#define GRBM_STATUS_SE1 0x8018
#define GRBM_STATUS_SE2 0x8038
#define GRBM_STATUS_SE3 0x803C
#define SE_DB_CLEAN (1 << 1)
#define SE_CB_CLEAN (1 << 2)
#define SE_BCI_BUSY (1 << 22)
#define SE_VGT_BUSY (1 << 23)
#define SE_PA_BUSY (1 << 24)
#define SE_TA_BUSY (1 << 25)
#define SE_SX_BUSY (1 << 26)
#define SE_SPI_BUSY (1 << 27)
#define SE_SC_BUSY (1 << 29)
#define SE_DB_BUSY (1 << 30)
#define SE_CB_BUSY (1 << 31)
#define GRBM_SOFT_RESET 0x8020
#define SOFT_RESET_CP (1 << 0) /* All CP blocks */
#define SOFT_RESET_RLC (1 << 2) /* RLC */
#define SOFT_RESET_GFX (1 << 16) /* GFX */
#define SOFT_RESET_CPF (1 << 17) /* CP fetcher shared by gfx and compute */
#define SOFT_RESET_CPC (1 << 18) /* CP Compute (MEC1/2) */
#define SOFT_RESET_CPG (1 << 19) /* CP GFX (PFP, ME, CE) */
#define GRBM_INT_CNTL 0x8060
# define RDERR_INT_ENABLE (1 << 0)
# define GUI_IDLE_INT_ENABLE (1 << 19)
#define CP_CPC_STATUS 0x8210
#define CP_CPC_BUSY_STAT 0x8214
#define <API key> 0x8218
#define CP_CPF_STATUS 0x821c
#define CP_CPF_BUSY_STAT 0x8220
#define <API key> 0x8224
#define CP_MEC_CNTL 0x8234
#define MEC_ME2_HALT (1 << 28)
#define MEC_ME1_HALT (1 << 30)
#define CP_MEC_CNTL 0x8234
#define MEC_ME2_HALT (1 << 28)
#define MEC_ME1_HALT (1 << 30)
#define CP_STALLED_STAT3 0x8670
#define CP_STALLED_STAT1 0x8674
#define CP_STALLED_STAT2 0x8678
#define CP_STAT 0x8680
#define CP_ME_CNTL 0x86D8
#define CP_CE_HALT (1 << 24)
#define CP_PFP_HALT (1 << 26)
#define CP_ME_HALT (1 << 28)
#define CP_RB0_RPTR 0x8700
#define CP_RB_WPTR_DELAY 0x8704
#define CP_MEQ_THRESHOLDS 0x8764
#define MEQ1_START(x) ((x) << 0)
#define MEQ2_START(x) ((x) << 8)
#define <API key> 0x88B0
#define <API key> 0x88C4
#define CACHE_INVALIDATION(x) ((x) << 0)
#define VC_ONLY 0
#define TC_ONLY 1
#define VC_AND_TC 2
#define AUTO_INVLD_EN(x) ((x) << 6)
#define NO_AUTO 0
#define ES_AUTO 1
#define GS_AUTO 2
#define ES_AND_GS_AUTO 3
#define VGT_GS_VERTEX_REUSE 0x88D4
#define <API key> 0x89bc
#define INACTIVE_CUS_MASK 0xFFFF0000
#define INACTIVE_CUS_SHIFT 16
#define <API key> 0x89c0
#define PA_CL_ENHANCE 0x8A14
#define <API key> (1 << 0)
#define NUM_CLIP_SEQ(x) ((x) << 1)
#define <API key> 0x8B24
#define <API key>(x) ((x) << 0)
#define <API key>(x) ((x) << 16)
#define PA_SC_FIFO_SIZE 0x8BCC
#define <API key>(x) ((x) << 0)
#define <API key>(x) ((x) << 6)
#define <API key>(x) ((x) << 15)
#define <API key>(x) ((x) << 23)
#define PA_SC_ENHANCE 0x8BF0
#define <API key> (1 << 0)
#define <API key> (1 << 13)
#define SQ_CONFIG 0x8C00
#define SH_MEM_BASES 0x8C28
/* if PTR32, these are the bases for scratch and lds */
#define PRIVATE_BASE(x) ((x) << 0) /* scratch */
#define SHARED_BASE(x) ((x) << 16) /* LDS */
#define SH_MEM_APE1_BASE 0x8C2C
/* if PTR32, this is the base location of GPUVM */
#define SH_MEM_APE1_LIMIT 0x8C30
/* if PTR32, this is the upper limit of GPUVM */
#define SH_MEM_CONFIG 0x8C34
#define PTR32 (1 << 0)
#define ALIGNMENT_MODE(x) ((x) << 2)
#define <API key> 0
#define <API key> 1
#define <API key> 2
#define <API key> 3
#define DEFAULT_MTYPE(x) ((x) << 4)
#define APE1_MTYPE(x) ((x) << 7)
#define SX_DEBUG_1 0x9060
#define SPI_CONFIG_CNTL 0x9100
#define SPI_CONFIG_CNTL_1 0x913C
#define VTX_DONE_DELAY(x) ((x) << 0)
#define <API key> (1 << 4)
#define TA_CNTL_AUX 0x9508
#define DB_DEBUG 0x9830
#define DB_DEBUG2 0x9834
#define DB_DEBUG3 0x9838
#define <API key> 0x98F4
#define BACKEND_DISABLE(x) ((x) << 16)
#define GB_ADDR_CONFIG 0x98F8
#define NUM_PIPES(x) ((x) << 0)
#define NUM_PIPES_MASK 0x00000007
#define NUM_PIPES_SHIFT 0
#define <API key>(x) ((x) << 4)
#define <API key> 0x00000070
#define <API key> 4
#define NUM_SHADER_ENGINES(x) ((x) << 12)
#define <API key> 0x00003000
#define <API key> 12
#define <API key>(x) ((x) << 16)
#define <API key> 0x00070000
#define <API key> 16
#define ROW_SIZE(x) ((x) << 28)
#define ROW_SIZE_MASK 0x30000000
#define ROW_SIZE_SHIFT 28
#define GB_TILE_MODE0 0x9910
# define ARRAY_MODE(x) ((x) << 2)
# define <API key> 0
# define <API key> 1
# define <API key> 2
# define <API key> 4
# define <API key> 5
# define <API key> 6
# define PIPE_CONFIG(x) ((x) << 6)
# define ADDR_SURF_P2 0
# define ADDR_SURF_P4_8x16 4
# define ADDR_SURF_P4_16x16 5
# define ADDR_SURF_P4_16x32 6
# define ADDR_SURF_P4_32x32 7
# define <API key> 8
# define <API key> 9
# define <API key> 10
# define <API key> 11
# define <API key> 12
# define <API key> 13
# define <API key> 14
# define TILE_SPLIT(x) ((x) << 11)
# define <API key> 0
# define <API key> 1
# define <API key> 2
# define <API key> 3
# define <API key> 4
# define <API key> 5
# define <API key> 6
# define MICRO_TILE_MODE_NEW(x) ((x) << 22)
# define <API key> 0
# define <API key> 1
# define <API key> 2
# define <API key> 3
# define SAMPLE_SPLIT(x) ((x) << 25)
# define <API key> 0
# define <API key> 1
# define <API key> 2
# define <API key> 3
#define GB_MACROTILE_MODE0 0x9990
# define BANK_WIDTH(x) ((x) << 0)
# define <API key> 0
# define <API key> 1
# define <API key> 2
# define <API key> 3
# define BANK_HEIGHT(x) ((x) << 2)
# define <API key> 0
# define <API key> 1
# define <API key> 2
# define <API key> 3
# define MACRO_TILE_ASPECT(x) ((x) << 4)
# define <API key> 0
# define <API key> 1
# define <API key> 2
# define <API key> 3
# define NUM_BANKS(x) ((x) << 6)
# define ADDR_SURF_2_BANK 0
# define ADDR_SURF_4_BANK 1
# define ADDR_SURF_8_BANK 2
# define ADDR_SURF_16_BANK 3
#define CB_HW_CONTROL 0x9A10
#define <API key> 0x9B7C
#define <API key> 0x00FF0000
#define <API key> 16
#define TCP_CHAN_STEER_LO 0xac0c
#define TCP_CHAN_STEER_HI 0xac10
#define <API key> 0xAC68
#define <API key> 0xAC6C
#define <API key> 0xAC70
#define <API key> 0xAC74
#define <API key> 0xAC78
#define <API key> 0xAC7C
#define <API key> 0xAC80
#define <API key> 0xAC84
#define TC_CFG_L1_VOLATILE 0xAC88
#define TC_CFG_L2_VOLATILE 0xAC8C
#define CP_RB0_BASE 0xC100
#define CP_RB0_CNTL 0xC104
#define RB_BUFSZ(x) ((x) << 0)
#define RB_BLKSZ(x) ((x) << 8)
#define BUF_SWAP_32BIT (2 << 16)
#define RB_NO_UPDATE (1 << 27)
#define RB_RPTR_WR_ENA (1 << 31)
#define CP_RB0_RPTR_ADDR 0xC10C
#define RB_RPTR_SWAP_32BIT (2 << 0)
#define CP_RB0_RPTR_ADDR_HI 0xC110
#define CP_RB0_WPTR 0xC114
#define CP_DEVICE_ID 0xC12C
#define CP_ENDIAN_SWAP 0xC140
#define CP_RB_VMID 0xC144
#define CP_PFP_UCODE_ADDR 0xC150
#define CP_PFP_UCODE_DATA 0xC154
#define CP_ME_RAM_RADDR 0xC158
#define CP_ME_RAM_WADDR 0xC15C
#define CP_ME_RAM_DATA 0xC160
#define CP_CE_UCODE_ADDR 0xC168
#define CP_CE_UCODE_DATA 0xC16C
#define <API key> 0xC170
#define <API key> 0xC174
#define <API key> 0xC178
#define <API key> 0xC17C
#define CP_INT_CNTL_RING0 0xC1A8
# define <API key> (1 << 19)
# define <API key> (1 << 20)
# define <API key> (1 << 22)
# define PRIV_REG_INT_ENABLE (1 << 23)
# define <API key> (1 << 26)
# define <API key> (1 << 29)
# define <API key> (1 << 30)
# define <API key> (1 << 31)
#define CP_INT_STATUS_RING0 0xC1B4
# define PRIV_INSTR_INT_STAT (1 << 22)
# define PRIV_REG_INT_STAT (1 << 23)
# define TIME_STAMP_INT_STAT (1 << 26)
# define CP_RINGID2_INT_STAT (1 << 29)
# define CP_RINGID1_INT_STAT (1 << 30)
# define CP_RINGID0_INT_STAT (1 << 31)
#define CP_CPF_DEBUG 0xC200
#define <API key> 0xC20C
#define WPTR_POLL_EN (1 << 31)
#define <API key> 0xC214
#define <API key> 0xC218
#define <API key> 0xC21C
#define <API key> 0xC220
#define <API key> 0xC224
#define <API key> 0xC228
#define <API key> 0xC22C
#define <API key> 0xC230
# define <API key> (1 << 13)
# define <API key> (1 << 17)
# define PRIV_REG_INT_ENABLE (1 << 23)
# define <API key> (1 << 26)
# define GENERIC2_INT_ENABLE (1 << 29)
# define GENERIC1_INT_ENABLE (1 << 30)
# define GENERIC0_INT_ENABLE (1 << 31)
#define <API key> 0xC214
#define <API key> 0xC218
#define <API key> 0xC21C
#define <API key> 0xC220
#define <API key> 0xC224
#define <API key> 0xC228
#define <API key> 0xC22C
#define <API key> 0xC230
# define <API key> (1 << 13)
# define <API key> (1 << 17)
# define PRIV_REG_INT_STATUS (1 << 23)
# define <API key> (1 << 26)
# define GENERIC2_INT_STATUS (1 << 29)
# define GENERIC1_INT_STATUS (1 << 30)
# define GENERIC0_INT_STATUS (1 << 31)
#define CP_MAX_CONTEXT 0xC2B8
#define CP_RB0_BASE_HI 0xC2C4
#define RLC_CNTL 0xC300
# define RLC_ENABLE (1 << 0)
#define RLC_MC_CNTL 0xC30C
#define RLC_LB_CNTR_MAX 0xC348
#define RLC_LB_CNTL 0xC364
#define RLC_LB_CNTR_INIT 0xC36C
#define <API key> 0xC374
#define <API key> 0xC378
#define RLC_GPM_UCODE_ADDR 0xC388
#define RLC_GPM_UCODE_DATA 0xC38C
#define <API key> 0xC390
#define <API key> 0xC394
#define <API key> 0xC398
#define RLC_UCODE_CNTL 0xC39C
#define RLC_CGCG_CGLS_CTRL 0xC424
#define RLC_LB_INIT_CU_MASK 0xC43C
#define RLC_LB_PARAMS 0xC444
#define <API key> 0xC484
#define <API key> 0xC488
# define SE_MASTER_BUSY_MASK 0x0000ffff
# define GC_MASTER_BUSY (1 << 16)
# define TC0_MASTER_BUSY (1 << 17)
# define TC1_MASTER_BUSY (1 << 18)
#define <API key> 0xC4B0
#define <API key> 0xC4B4
#define <API key> 0xC904
#define <API key> 0xC908
#define CP_HPD_EOP_VMID 0xC90C
#define CP_HPD_EOP_CONTROL 0xC910
#define EOP_SIZE(x) ((x) << 0)
#define EOP_SIZE_MASK (0x3f << 0)
#define CP_MQD_BASE_ADDR 0xC914
#define CP_MQD_BASE_ADDR_HI 0xC918
#define CP_HQD_ACTIVE 0xC91C
#define CP_HQD_VMID 0xC920
#define CP_HQD_PQ_BASE 0xC934
#define CP_HQD_PQ_BASE_HI 0xC938
#define CP_HQD_PQ_RPTR 0xC93C
#define <API key> 0xC940
#define <API key> 0xC944
#define <API key> 0xC948
#define <API key> 0xC94C
#define <API key> 0xC950
#define DOORBELL_OFFSET(x) ((x) << 2)
#define <API key> (0x1fffff << 2)
#define DOORBELL_SOURCE (1 << 28)
#define DOORBELL_SCHD_HIT (1 << 29)
#define DOORBELL_EN (1 << 30)
#define DOORBELL_HIT (1 << 31)
#define CP_HQD_PQ_WPTR 0xC954
#define CP_HQD_PQ_CONTROL 0xC958
#define QUEUE_SIZE(x) ((x) << 0)
#define QUEUE_SIZE_MASK (0x3f << 0)
#define RPTR_BLOCK_SIZE(x) ((x) << 8)
#define <API key> (0x3f << 8)
#define PQ_VOLATILE (1 << 26)
#define NO_UPDATE_RPTR (1 << 27)
#define UNORD_DISPATCH (1 << 28)
#define ROQ_PQ_IB_FLIP (1 << 29)
#define PRIV_STATE (1 << 30)
#define KMD_QUEUE (1 << 31)
#define <API key> 0xC974
#define CP_MQD_CONTROL 0xC99C
#define MQD_VMID(x) ((x) << 0)
#define MQD_VMID_MASK (0xf << 0)
#define PA_SC_RASTER_CONFIG 0x28350
# define <API key> 0
# define <API key> 1
# define <API key> 2
# define <API key> 3
#define VGT_EVENT_INITIATOR 0x28a90
# define <API key> (1 << 0)
# define <API key> (2 << 0)
# define <API key> (3 << 0)
# define CACHE_FLUSH_TS (4 << 0)
# define CACHE_FLUSH (6 << 0)
# define CS_PARTIAL_FLUSH (7 << 0)
# define VGT_STREAMOUT_RESET (10 << 0)
# define END_OF_PIPE_INCR_DE (11 << 0)
# define END_OF_PIPE_IB_END (12 << 0)
# define RST_PIX_CNT (13 << 0)
# define VS_PARTIAL_FLUSH (15 << 0)
# define PS_PARTIAL_FLUSH (16 << 0)
# define <API key> (20 << 0)
# define ZPASS_DONE (21 << 0)
# define <API key> (22 << 0)
# define PERFCOUNTER_START (23 << 0)
# define PERFCOUNTER_STOP (24 << 0)
# define PIPELINESTAT_START (25 << 0)
# define PIPELINESTAT_STOP (26 << 0)
# define PERFCOUNTER_SAMPLE (27 << 0)
# define SAMPLE_PIPELINESTAT (30 << 0)
# define <API key> (31 << 0)
# define <API key> (32 << 0)
# define RESET_VTX_CNT (33 << 0)
# define VGT_FLUSH (36 << 0)
# define BOTTOM_OF_PIPE_TS (40 << 0)
# define <API key> (42 << 0)
# define <API key> (43 << 0)
# define <API key> (44 << 0)
# define <API key> (45 << 0)
# define <API key> (46 << 0)
# define CS_DONE (47 << 0)
# define PS_DONE (48 << 0)
# define <API key> (49 << 0)
# define THREAD_TRACE_START (51 << 0)
# define THREAD_TRACE_STOP (52 << 0)
# define THREAD_TRACE_FLUSH (54 << 0)
# define THREAD_TRACE_FINISH (55 << 0)
# define <API key> (56 << 0)
# define <API key> (57 << 0)
# define <API key> (58 << 0)
#define SCRATCH_REG0 0x30100
#define SCRATCH_REG1 0x30104
#define SCRATCH_REG2 0x30108
#define SCRATCH_REG3 0x3010C
#define SCRATCH_REG4 0x30110
#define SCRATCH_REG5 0x30114
#define SCRATCH_REG6 0x30118
#define SCRATCH_REG7 0x3011C
#define SCRATCH_UMSK 0x30140
#define SCRATCH_ADDR 0x30144
#define CP_SEM_WAIT_TIMER 0x301BC
#define <API key> 0x301C8
#define <API key> 0x301D0
#define GRBM_GFX_INDEX 0x30800
#define INSTANCE_INDEX(x) ((x) << 0)
#define SH_INDEX(x) ((x) << 8)
#define SE_INDEX(x) ((x) << 16)
#define SH_BROADCAST_WRITES (1 << 29)
#define <API key> (1 << 30)
#define SE_BROADCAST_WRITES (1 << 31)
#define VGT_ESGS_RING_SIZE 0x30900
#define VGT_GSVS_RING_SIZE 0x30904
#define VGT_PRIMITIVE_TYPE 0x30908
#define VGT_INDEX_TYPE 0x3090C
#define VGT_NUM_INDICES 0x30930
#define VGT_NUM_INSTANCES 0x30934
#define VGT_TF_RING_SIZE 0x30938
#define <API key> 0x3093C
#define VGT_TF_MEMORY_BASE 0x30940
#define <API key> 0x30a00
#define <API key> 0x30a04
#define SQC_CACHES 0x30d20
#define CP_PERFMON_CNTL 0x36020
#define CGTS_TCC_DISABLE 0x3c00c
#define <API key> 0x3c010
#define TCC_DISABLE_MASK 0xFFFF0000
#define TCC_DISABLE_SHIFT 16
#define CB_CGTT_SCLK_CTRL 0x3c2a0
/*
* PM4
*/
#define PACKET_TYPE0 0
#define PACKET_TYPE1 1
#define PACKET_TYPE2 2
#define PACKET_TYPE3 3
#define CP_PACKET_GET_TYPE(h) (((h) >> 30) & 3)
#define CP_PACKET_GET_COUNT(h) (((h) >> 16) & 0x3FFF)
#define CP_PACKET0_GET_REG(h) (((h) & 0xFFFF) << 2)
#define <API key>(h) (((h) >> 8) & 0xFF)
#define PACKET0(reg, n) ((PACKET_TYPE0 << 30) | \
(((reg) >> 2) & 0xFFFF) | \
((n) & 0x3FFF) << 16)
#define CP_PACKET2 0x80000000
#define PACKET2_PAD_SHIFT 0
#define PACKET2_PAD_MASK (0x3fffffff << 0)
#define PACKET2(v) (CP_PACKET2 | REG_SET(PACKET2_PAD, (v)))
#define PACKET3(op, n) ((PACKET_TYPE3 << 30) | \
(((op) & 0xFF) << 8) | \
((n) & 0x3FFF) << 16)
#define PACKET3_COMPUTE(op, n) (PACKET3(op, n) | 1 << 1)
/* Packet 3 types */
#define PACKET3_NOP 0x10
#define PACKET3_SET_BASE 0x11
#define PACKET3_BASE_INDEX(x) ((x) << 0)
#define CE_PARTITION_BASE 3
#define PACKET3_CLEAR_STATE 0x12
#define <API key> 0x13
#define <API key> 0x15
#define <API key> 0x16
#define PACKET3_ATOMIC_GDS 0x1D
#define PACKET3_ATOMIC_MEM 0x1E
#define <API key> 0x1F
#define <API key> 0x20
#define PACKET3_REG_RMW 0x21
#define PACKET3_COND_EXEC 0x22
#define PACKET3_PRED_EXEC 0x23
#define <API key> 0x24
#define <API key> 0x25
#define PACKET3_INDEX_BASE 0x26
#define <API key> 0x27
#define <API key> 0x28
#define PACKET3_INDEX_TYPE 0x2A
#define <API key> 0x2C
#define <API key> 0x2D
#define <API key> 0x2F
#define <API key> 0x30
#define <API key> 0x33
#define <API key> 0x34
#define <API key> 0x35
#define <API key> 0x36
#define PACKET3_WRITE_DATA 0x37
#define WRITE_DATA_DST_SEL(x) ((x) << 8)
/* 0 - register
* 1 - memory (sync - via GRBM)
* 2 - gl2
* 3 - gds
* 4 - reserved
* 5 - memory (async - direct)
*/
#define WR_ONE_ADDR (1 << 16)
#define WR_CONFIRM (1 << 20)
#define <API key>(x) ((x) << 25)
/* 0 - LRU
* 1 - Stream
*/
#define <API key>(x) ((x) << 30)
/* 0 - me
* 1 - pfp
* 2 - ce
*/
#define <API key> 0x38
#define <API key> 0x39
# define <API key> (0x1 << 16)
# define <API key> (0x1 << 20) /* 0 = increment, 1 = write 1 */
# define <API key> ((x) << 24) /* 0 = CP, 1 = CB, 2 = DB */
# define <API key> (0x6 << 29)
# define <API key> (0x7 << 29)
#define PACKET3_COPY_DW 0x3B
#define <API key> 0x3C
#define <API key>(x) ((x) << 0)
/* 0 - always
* 1 - <
* 2 - <=
* 3 - ==
* 4 - !=
* 5 - >=
* 6 - >
*/
#define <API key>(x) ((x) << 4)
/* 0 - reg
* 1 - mem
*/
#define <API key>(x) ((x) << 6)
/* 0 - wait_reg_mem
* 1 - wr_wait_wr_reg
*/
#define WAIT_REG_MEM_ENGINE(x) ((x) << 8)
/* 0 - me
* 1 - pfp
*/
#define <API key> 0x3F
#define <API key> (1 << 22)
#define <API key> (1 << 23)
#define <API key>(x) ((x) << 28)
/* 0 - LRU
* 1 - Stream
* 2 - Bypass
*/
#define PACKET3_COPY_DATA 0x40
#define PACKET3_PFP_SYNC_ME 0x42
#define <API key> 0x43
# define <API key> (1 << 0)
# define <API key> (1 << 1)
# define <API key> (1 << 6)
# define <API key> (1 << 7)
# define <API key> (1 << 8)
# define <API key> (1 << 9)
# define <API key> (1 << 10)
# define <API key> (1 << 11)
# define <API key> (1 << 12)
# define <API key> (1 << 13)
# define <API key> (1 << 14)
# define <API key> (1 << 15)
# define <API key> (1 << 16)
# define <API key> (1 << 18)
# define <API key> (1 << 19)
# define <API key> (1 << 21)
# define <API key> (1 << 22)
# define <API key> (1 << 23)
# define <API key> (1 << 25)
# define <API key> (1 << 26)
# define <API key> (1 << 27)
# define <API key> (1 << 28)
# define <API key> (1 << 29)
#define PACKET3_COND_WRITE 0x45
#define PACKET3_EVENT_WRITE 0x46
#define EVENT_TYPE(x) ((x) << 0)
#define EVENT_INDEX(x) ((x) << 8)
/* 0 - any non-TS event
* 1 - ZPASS_DONE, PIXEL_PIPE_STAT_*
* 2 - SAMPLE_PIPELINESTAT
* 3 - <API key>*
* 4 - *S_PARTIAL_FLUSH
* 5 - EOP events
* 6 - EOS events
*/
#define <API key> 0x47
#define <API key> (1 << 12)
#define <API key> (1 << 13)
#define EOP_TC_WB_ACTION_EN (1 << 15)
#define EOP_TCL1_ACTION_EN (1 << 16)
#define EOP_TC_ACTION_EN (1 << 17)
#define EOP_CACHE_POLICY(x) ((x) << 25)
/* 0 - LRU
* 1 - Stream
* 2 - Bypass
*/
#define EOP_TCL2_VOLATILE (1 << 27)
#define DATA_SEL(x) ((x) << 29)
/* 0 - discard
* 1 - send low 32bit data
* 2 - send 64bit data
* 3 - send 64bit GPU counter value
* 4 - send 64bit sys counter value
*/
#define INT_SEL(x) ((x) << 24)
/* 0 - none
* 1 - interrupt only (DATA_SEL = 0)
* 2 - interrupt when data write is confirmed
*/
#define DST_SEL(x) ((x) << 16)
/* 0 - MC
* 1 - TC/L2
*/
#define <API key> 0x48
#define PACKET3_RELEASE_MEM 0x49
#define <API key> 0x4A
# define <API key> (2 << 28)
# define <API key> (3 << 28)
#define PACKET3_DMA_DATA 0x50
#define PACKET3_AQUIRE_MEM 0x58
#define PACKET3_REWIND 0x59
#define <API key> 0x5E
#define PACKET3_LOAD_SH_REG 0x5F
#define <API key> 0x60
#define <API key> 0x61
#define <API key> 0x68
#define <API key> 0x00008000
#define <API key> 0x0000b000
#define <API key> 0x69
#define <API key> 0x00028000
#define <API key> 0x00029000
#define <API key> 0x73
#define PACKET3_SET_SH_REG 0x76
#define <API key> 0x0000b000
#define <API key> 0x0000c000
#define <API key> 0x77
#define <API key> 0x78
#define <API key> 0x79
#define <API key> 0x00030000
#define <API key> 0x00031000
#define <API key> 0x7D
#define <API key> 0x7E
#define <API key> 0x80
#define <API key> 0x81
#define <API key> 0x83
#define <API key> 0x84
#define <API key> 0x85
#define <API key> 0x86
#define <API key> 0x88
#define <API key> 0x8B
/* SDMA - first instance at 0xd000, second at 0xd800 */
#define <API key> 0x0 /* not a register */
#define <API key> 0x800 /* not a register */
#define SDMA0_UCODE_ADDR 0xD000
#define SDMA0_UCODE_DATA 0xD004
#define SDMA0_CNTL 0xD010
# define TRAP_ENABLE (1 << 0)
# define <API key> (1 << 1)
# define SEM_WAIT_INT_ENABLE (1 << 2)
# define DATA_SWAP_ENABLE (1 << 3)
# define FENCE_SWAP_ENABLE (1 << 4)
# define AUTO_CTXSW_ENABLE (1 << 18)
# define CTXEMPTY_INT_ENABLE (1 << 28)
#define SDMA0_TILING_CONFIG 0xD018
#define <API key> 0xD020
#define <API key> 0xD024
#define SDMA0_STATUS_REG 0xd034
# define SDMA_IDLE (1 << 0)
#define SDMA0_ME_CNTL 0xD048
# define SDMA_HALT (1 << 0)
#define SDMA0_GFX_RB_CNTL 0xD200
# define SDMA_RB_ENABLE (1 << 0)
# define SDMA_RB_SIZE(x) ((x) << 1) /* log2 */
# define SDMA_RB_SWAP_ENABLE (1 << 9) /* 8IN32 */
# define <API key> (1 << 12)
# define <API key> (1 << 13) /* 8IN32 */
# define <API key>(x) ((x) << 16) /* log2 */
#define SDMA0_GFX_RB_BASE 0xD204
#define <API key> 0xD208
#define SDMA0_GFX_RB_RPTR 0xD20C
#define SDMA0_GFX_RB_WPTR 0xD210
#define <API key> 0xD220
#define <API key> 0xD224
#define SDMA0_GFX_IB_CNTL 0xD228
# define SDMA_IB_ENABLE (1 << 0)
# define SDMA_IB_SWAP_ENABLE (1 << 4)
# define <API key> (1 << 8)
# define SDMA_CMD_VMID(x) ((x) << 16)
#define <API key> 0xD29C
#define SDMA0_GFX_APE1_CNTL 0xD2A0
#define SDMA_PACKET(op, sub_op, e) ((((e) & 0xFFFF) << 16) | \
(((sub_op) & 0xFF) << 8) | \
(((op) & 0xFF) << 0))
/* sDMA opcodes */
#define SDMA_OPCODE_NOP 0
#define SDMA_OPCODE_COPY 1
# define <API key> 0
# define <API key> 1
# define <API key> 3
# define <API key> 4
# define <API key> 5
# define <API key> 6
#define SDMA_OPCODE_WRITE 2
# define <API key> 0
# define <API key> 1
#define <API key> 4
#define SDMA_OPCODE_FENCE 5
#define SDMA_OPCODE_TRAP 6
#define <API key> 7
# define <API key> (1 << 13)
/* 0 - increment
* 1 - write 1
*/
# define <API key> (1 << 14)
/* 0 - wait
* 1 - signal
*/
# define <API key> (1 << 15)
/* mailbox */
#define <API key> 8
# define <API key>(x) ((x) << 10)
/* 0 - wait_reg_mem
* 1 - wr_wait_wr_reg
*/
# define <API key>(x) ((x) << 12)
/* 0 - always
* 1 - <
* 2 - <=
* 3 - ==
* 4 - !=
* 5 - >=
* 6 - >
*/
# define <API key> (1 << 15)
/* 0 = register
* 1 = memory
*/
#define <API key> 9
#define <API key> 11
# define <API key>(x) ((x) << 14)
/* 0 = byte fill
* 2 = DW fill
*/
#define <API key> 12
#define <API key> 13
# define <API key> 0
# define <API key> 1
# define <API key> 2
#define <API key> 14
# define <API key>(x) ((x) << 12)
/* byte mask */
/* UVD */
#define <API key> 0xef4c
#define <API key> 0xef50
#define <API key> 0xef54
#define UVD_LMI_EXT40_ADDR 0xf498
#define UVD_LMI_ADDR_EXT 0xf594
#define <API key> 0xf608
#define <API key> 0xf60c
#define <API key> 0xf610
#define <API key> 0xf614
#define <API key> 0xf618
#define <API key> 0xf61c
#define UVD_RBC_RB_RPTR 0xf690
#define UVD_RBC_RB_WPTR 0xf694
/* UVD clocks */
#define CG_DCLK_CNTL 0xC050009C
# define DCLK_DIVIDER_MASK 0x7f
# define DCLK_DIR_CNTL_EN (1 << 8)
#define CG_DCLK_STATUS 0xC05000A0
# define DCLK_STATUS (1 << 0)
#define CG_VCLK_CNTL 0xC05000A4
#define CG_VCLK_STATUS 0xC05000A8
#endif |
/** \file
*
* Header file for HIDReport.c.
*/
#ifndef _HID_REPORT_H_
#define _HID_REPORT_H_
/* Includes: */
#include <LUFA/Drivers/USB/USB.h>
#include "<API key>.h"
/* Macros: */
/** HID Report Descriptor Usage Page value for a desktop keyboard. */
#define USAGE_PAGE_KEYBOARD 0x07
/* Enums: */
/** Enum for the possible return codes of the \ref GetHIDReportData() function. */
enum <API key>
{
ParseSuccessful = 0, /**< HID report descriptor parsed successfully */
ParseError = 1, /**< Failed to fully process the HID report descriptor */
ParseControlError = 2, /**< Control error occurred while trying to read the device HID descriptor */
};
/* External Variables: */
extern uint16_t HIDReportSize;
extern HID_ReportInfo_t HIDReportInfo;
/* Function Prototypes: */
uint8_t GetHIDReportData(void);
bool <API key>(HID_ReportItem_t* const CurrentItem);
#endif |
<html>
<head>
<script type="text/javascript" src="../../http/tests/inspector-protocol/<API key>.js"></script>
<script>
function addBeforeElement()
{
document.getElementById("style").textContent = "#for-pseudo:before { content: \"BEFORE\" }";
}
function test()
{
var nodeInfo = {};
var childrenCallback;
InspectorTest.eventHandler["DOM.setChildNodes"] = setChildNodes;
InspectorTest.eventHandler["DOM.pseudoElementAdded"] = pseudoElementAdded;
getDocument();
function getDocument()
{
step({
name: "Get the Document",
command: "DOM.getDocument",
parameters: {},
callback: <API key>
});
};
function <API key>(result)
{
var bodyId = result.root.children[0].children[1].nodeId;
childrenCallback = onChildrenRequested;
step({
name: "Get immediate children of the body",
command: "DOM.requestChildNodes",
parameters: {"nodeId": bodyId}
});
};
function onChildrenRequested()
{
step({
name: "Add #for-pseudo:before element",
command: "Runtime.evaluate",
parameters: {expression: "addBeforeElement()"}
});
}
function pseudoElementAdded(message)
{
var nodeData = findNodeById("inner-span");
assertEquals(true, !!nodeData, "#inner-span has been received");
InspectorTest.completeTest();
}
function setChildNodes(message)
{
var nodes = message.params.nodes;
for (var i = 0; i < nodes.length; ++i)
addNode(nodes[i]);
var callback = childrenCallback;
childrenCallback = null;
if (callback)
callback();
}
function step(test)
{
InspectorTest.log("\n=== " + test.name + " ===\n");
InspectorTest.sendCommand(test.command, test.parameters, function(messageObject) {
if (messageObject.hasOwnProperty("error"))
InspectorTest.log("Backend error: " + messageObject.error.message + " (" + messageObject.error.code + ")\n");
if (test.callback)
test.callback(messageObject.result);
});
}
function findNodeById(id)
{
for (var nodeId in nodeInfo) {
var node = nodeInfo[nodeId];
var attrs = node.attributes;
if (!attrs)
continue;
for (var i = 0; i < attrs.length; i += 2) {
var name = attrs[i];
if (name !== "id")
continue;
if (attrs[i + 1] === id)
return {nodeId: nodeId, node: node};
}
}
return null;
}
function addNodesRecursive(root)
{
addNode(root);
if (!root.children)
return;
for (var i = 0; i < root.children.length; ++i)
addNodesRecursive(root.children[i]);
}
function addNode(node)
{
nodeInfo[node.nodeId] = node;
delete node.nodeId;
}
function assertEquals(expected, actual, message)
{
if (expected === actual) {
InspectorTest.log("PASS: " + message);
return;
}
InspectorTest.log("FAIL: " + message + ": expected: <" + expected + "> but found <" + actual + ">");
}
}
</script>
<style id="style">
</style>
</head>
<body id="body" onload="runTest()">
<div id="for-pseudo"><span id="inner-span"></span></div>
</body>
</html> |
<?php
namespace ZFTool\Diagnostics\Reporter;
use ArrayObject;
use Zend\Console\Adapter\AdapterInterface as Console;
use Zend\Console\ColorInterface as Color;
use ZendDiagnostics\Check\CheckInterface;
use ZendDiagnostics\Result\Collection as ResultsCollection;
use ZendDiagnostics\Result\FailureInterface as Failure;
use ZendDiagnostics\Result\ResultInterface;
use ZendDiagnostics\Result\SkipInterface as Skip;
use ZendDiagnostics\Result\SuccessInterface as Success;
use ZendDiagnostics\Result\WarningInterface as Warning;
use ZendDiagnostics\Runner\Reporter\ReporterInterface;
class BasicConsole implements ReporterInterface
{
/**
* @var \Zend\Console\Adapter\AdapterInterface
*/
protected $console;
protected $width = 80;
protected $total = 0;
protected $iter = 1;
protected $pos = 1;
protected $countLength;
protected $gutter;
protected $stopped = false;
/**
* Create instance of reporter.
*
* @param Console $console
*/
public function __construct(Console $console)
{
$this->console = $console;
}
/**
* This method is called right after Reporter starts running, via Runner::run()
*
* @param ArrayObject $checks
* @param array $runnerConfig
* @return void
*/
public function onStart(ArrayObject $checks, $runnerConfig)
{
$this->stopped = false;
$this->width = $this->console->getWidth();
$this->total = $checks->count();
// Calculate gutter width to accommodate number of checks passed
if ($this->total <= $this->width) {
$this->gutter = 0; // everything fits well
} else {
$this->countLength = floor(log10($this->total)) + 1;
$this->gutter = ($this->countLength * 2) + 11;
}
$this->console->writeLine('Starting diagnostics:');
$this->console->writeLine('');
}
/**
* This method is called before each individual Check is performed. If this
* method returns false, the Check will not be performed (will be skipped).
*
* @param CheckInterface $check Check instance that is about to be performed.
* @param bool $alias The alias being targeted by the check
* @return bool|void Return false to prevent check from happening
*/
public function onBeforeRun(CheckInterface $check, $alias = null) {}
/**
* This method is called every time a Check has been performed.
*
* @param CheckInterface $check A Check instance that has just finished running
* @param ResultInterface $result Result for that particular check instance
* @param bool $alias The alias being targeted by the check
* @return bool|void Return false to prevent from running additional Checks
*/
public function onAfterRun(CheckInterface $check, ResultInterface $result, $alias = null)
{
// Draw a symbol
if ($result instanceof Success) {
$this->console->write('.', Color::GREEN);
} elseif ($result instanceof Failure) {
$this->console->write('F', Color::WHITE, Color::RED);
} elseif ($result instanceof Warning) {
$this->console->write('!', Color::YELLOW);
} elseif ($result instanceof Skip) {
$this->console->write('S', Color::YELLOW);
} else {
$this->console->write('?', Color::YELLOW);
}
$this->pos++;
// Check if we need to move to the next line
if ($this->gutter > 0 && $this->pos > $this->width - $this->gutter) {
$this->console->write(
str_pad(
str_pad($this->iter, $this->countLength, ' ', STR_PAD_LEFT) . ' / ' . $this->total .
' (' . str_pad(round($this->iter / $this->total * 100), 3, ' ', STR_PAD_LEFT) . '%)'
, $this->gutter, ' ', STR_PAD_LEFT
)
);
$this->pos = 1;
}
$this->iter++;
}
/**
* This method is called when Runner has been aborted and could not finish the
* whole run().
*
* @param ResultsCollection $results Collection of Results for performed Checks.
* @return void
*/
public function onStop(ResultsCollection $results)
{
$this->stopped = true;
}
/**
* This method is called when Runner has finished its run.
*
* @param ResultsCollection $results Collection of Results for performed Checks.
* @return void
*/
public function onFinish(ResultsCollection $results)
{
/* @var $results \ZendDiagnostics\Result\Collection */
$this->console->writeLine();
$this->console->writeLine();
// Display a summary line
if (
$results->getFailureCount() == 0 &&
$results->getWarningCount() == 0 &&
$results->getUnknownCount() == 0 &&
$results->getSkipCount() == 0
) {
$line = 'OK (' . $this->total . ' diagnostic checks)';
$this->console->writeLine(
str_pad($line, $this->width-1, ' ', STR_PAD_RIGHT),
Color::NORMAL, Color::GREEN
);
} elseif ($results->getFailureCount() == 0) {
$line = $results->getWarningCount() . ' warnings';
if ($results->getSkipCount() > 0) {
$line .= ', ' . $results->getSkipCount() . ' skipped checks';
}
if ($results->getUnknownCount() > 0) {
$line .= ', ' . $results->getUnknownCount() . ' unknown check results';
}
$line .= ', ' . $results->getSuccessCount() . ' successful checks';
$line .= '.';
$this->console->writeLine(
str_pad($line, $this->width-1, ' ', STR_PAD_RIGHT),
Color::NORMAL, Color::YELLOW
);
} else {
$line = $results->getFailureCount() . ' failures, ';
$line .= $results->getWarningCount() . ' warnings';
if ($results->getSkipCount() > 0) {
$line .= ', ' . $results->getSkipCount() . ' skipped checks';
}
if ($results->getUnknownCount() > 0) {
$line .= ', ' . $results->getUnknownCount() . ' unknown check results';
}
$line .= ', ' . $results->getSuccessCount() . ' successful checks';
$line .= '.';
$this->console->writeLine(
str_pad($line, $this->width, ' ', STR_PAD_RIGHT),
Color::NORMAL, Color::RED
);
}
$this->console->writeLine();
// Display a list of failures and warnings
foreach ($results as $check) {
/* @var $check CheckInterface */
/* @var $result ResultInterface */
$result = $results[$check];
if ($result instanceof Failure) {
$this->console->writeLine('Failure: ' . $check->getLabel(), Color::RED);
$message = $result->getMessage();
if ($message) {
$this->console->writeLine($message, Color::RED);
}
$this->console->writeLine();
} elseif ($result instanceof Warning) {
$this->console->writeLine('Warning: ' . $check->getLabel(), Color::YELLOW);
$message = $result->getMessage();
if ($message) {
$this->console->writeLine($message, Color::YELLOW);
}
$this->console->writeLine();
} elseif ($result instanceof Skip) {
$this->console->writeLine('Skipped: ' . $check->getLabel(), Color::YELLOW);
$message = $result->getMessage();
if ($message) {
$this->console->writeLine($message, Color::YELLOW);
}
$this->console->writeLine();
} elseif (!$result instanceof Success) {
$this->console->writeLine('Unknown result ' . get_class($result) . ': ' . $check->getLabel(), Color::YELLOW);
$message = $result->getMessage();
if ($message) {
$this->console->writeLine($message, Color::YELLOW);
}
$this->console->writeLine();
}
}
// Display information that the check has been aborted.
if ($this->stopped) {
$this->console->writeLine('Diagnostics aborted because of a failure.', Color::RED);
}
}
/**
* Set Console adapter to use.
*
* @param Console $console
*/
public function setConsole($console)
{
$this->console = $console;
// Update width
$this->width = $console->getWidth();
}
/**
* Get currently used Console adapter
* @return Console
*/
public function getConsole()
{
return $this->console;
}
} |
/*
* Very basic string functions
*/
#include "boot.h"
int strcmp(const char *str1, const char *str2)
{
const unsigned char *s1 = (const unsigned char *)str1;
const unsigned char *s2 = (const unsigned char *)str2;
int delta = 0;
while (*s1 || *s2) {
delta = *s2 - *s1;
if (delta)
return delta;
s1++;
s2++;
}
return 0;
}
size_t strnlen(const char *s, size_t maxlen)
{
const char *es = s;
while (*es && maxlen) {
es++;
maxlen
}
return (es - s);
}
unsigned int atou(const char *s)
{
unsigned int i = 0;
while (isdigit(*s))
i = i * 10 + (*s++ - '0');
return i;
} |
<?php
/**
*
* Responsible for loading the indexed search class and initiating the reindex command.
* @package Utilities
*/
defined('C5_EXECUTE') or die("Access Denied.");
class <API key> extends Job {
public function getJobName() {
return t("Process Email Posts");
}
public function getJobDescription() {
return t("Polls an email account and grabs private messages/postings that are sent there..");
}
public function run() {
Loader::library('mail/importer');
$list = MailImporter::getEnabledList();
foreach($list as $mi) {
// for each one, we connect and retrieve any mail messages we haven't seen
$messages = $mi->getPendingMessages();
foreach($messages as $me) {
if ($me->validate()) {
$mi->process($me);
$mi->cleanup($me);
} else {
$mh = Loader::helper('mail');
$mh->to($me->getOriginalSender());
$mh->from($mi-><API key>());
$mh->addParameter('originalSubject', $me->getSubject());
$mh->addParameter('error', $mi-><API key>());
$mh->load('mail_importer_error');
$mh->sendMail();
}
}
}
}
}
?> |
'use strict';
describe('socketFactory', function () {
beforeEach(module('btford.socket-io'));
var socket,
scope,
$timeout,
$browser,
mockIoSocket,
spy;
beforeEach(inject(function (socketFactory, _$browser_, $rootScope, _$timeout_) {
$browser = _$browser_;
$timeout = _$timeout_;
scope = $rootScope.$new();
spy = jasmine.createSpy('emitSpy');
mockIoSocket = io.connect();
socket = socketFactory({
ioSocket: mockIoSocket,
scope: scope
});
}));
describe('#on', function () {
it('should apply asynchronously', function () {
socket.on('event', spy);
mockIoSocket.emit('event');
expect(spy).not.toHaveBeenCalled();
$timeout.flush();
expect(spy).toHaveBeenCalled();
});
});
describe('#disconnect', function () {
it('should call the underlying socket.disconnect', function () {
mockIoSocket.disconnect = spy;
socket.disconnect();
expect(spy).toHaveBeenCalled();
});
});
describe('#once', function () {
it('should apply asynchronously', function () {
socket.once('event', spy);
mockIoSocket.emit('event');
expect(spy).not.toHaveBeenCalled();
$timeout.flush();
expect(spy).toHaveBeenCalled();
});
it('should only run once', function () {
var counter = 0;
socket.once('event', function () {
counter += 1;
});
mockIoSocket.emit('event');
mockIoSocket.emit('event');
$timeout.flush();
expect(counter).toBe(1);
});
});
describe('#emit', function () {
it('should call the delegate socket\'s emit', function () {
spyOn(mockIoSocket, 'emit');
socket.emit('event', {foo: 'bar'});
expect(mockIoSocket.emit).toHaveBeenCalled();
});
it('should allow multiple data arguments', function () {
spyOn(mockIoSocket, 'emit');
socket.emit('event', 'x', 'y');
expect(mockIoSocket.emit).<API key>('event', 'x', 'y');
});
it('should wrap the callback with multiple data arguments', function () {
spyOn(mockIoSocket, 'emit');
socket.emit('event', 'x', 'y', spy);
expect(mockIoSocket.emit.mostRecentCall.args[3]).toNotBe(spy);
mockIoSocket.emit.mostRecentCall.args[3]();
expect(spy).not.toHaveBeenCalled();
$timeout.flush();
expect(spy).toHaveBeenCalled();
});
});
describe('#removeListener', function () {
it('should not call after removing an event', function () {
socket.on('event', spy);
socket.removeListener('event', spy);
mockIoSocket.emit('event');
expect($browser.deferredFns.length).toBe(0);
});
});
describe('#removeAllListeners', function () {
it('should not call after removing listeners for an event', function () {
socket.on('event', spy);
socket.removeAllListeners('event');
mockIoSocket.emit('event');
expect($browser.deferredFns.length).toBe(0);
});
it('should not call after removing all listeners', function () {
socket.on('event', spy);
socket.on('event2', spy);
socket.removeAllListeners();
mockIoSocket.emit('event');
mockIoSocket.emit('event2');
expect($browser.deferredFns.length).toBe(0);
});
});
describe('#forward', function () {
it('should forward events', function () {
socket.forward('event');
scope.$on('socket:event', spy);
mockIoSocket.emit('event');
$timeout.flush();
expect(spy).toHaveBeenCalled();
});
it('should forward an array of events', function () {
socket.forward(['e1', 'e2']);
scope.$on('socket:e1', spy);
scope.$on('socket:e2', spy);
mockIoSocket.emit('e1');
mockIoSocket.emit('e2');
$timeout.flush();
expect(spy.callCount).toBe(2);
});
it('should remove watchers when the scope is removed', function () {
socket.forward('event');
scope.$on('socket:event', spy);
mockIoSocket.emit('event');
$timeout.flush();
expect(spy).toHaveBeenCalled();
scope.$destroy();
spy.reset();
mockIoSocket.emit('event');
expect(spy).not.toHaveBeenCalled();
});
it('should use the specified prefix', inject(function (socketFactory) {
var socket = socketFactory({
ioSocket: mockIoSocket,
scope: scope,
prefix: 'custom:'
});
socket.forward('event');
scope.$on('custom:event', spy);
mockIoSocket.emit('event');
$timeout.flush();
expect(spy).toHaveBeenCalled();
}));
it('should forward to the specified scope when one is provided', function () {
var child = scope.$new();
spyOn(child, '$broadcast');
socket.forward('event', child);
scope.$on('socket:event', spy);
mockIoSocket.emit('event');
$timeout.flush();
expect(child.$broadcast).toHaveBeenCalled();
});
});
}); |
import { sample } from "../index";
export = sample; |
import { merge } from "../index";
export = merge; |
#ifndef DLIB_STATIC_MAp_
#define DLIB_STATIC_MAp_
#include "static_map/static_map_kernel_1.h"
#include "static_map/static_map_kernel_c.h"
#include <functional>
namespace dlib
{
template <
typename domain,
typename range,
typename compare = std::less<domain>
>
class static_map
{
static_map() {}
public:
// kernel_1a
typedef static_map_kernel_1<domain,range,compare>
kernel_1a;
typedef static_map_kernel_c<kernel_1a>
kernel_1a_c;
};
}
#endif // DLIB_STATIC_MAp_ |
/* Public Domain Curses */
#include <curspriv.h>
RCSID("$Id: touch.c,v 1.29 2008/07/13 16:08:18 wmcbrine Exp $")
int touchwin(WINDOW *win)
{
int i;
PDC_LOG(("touchwin() - called: Win=%x\n", win));
if (!win)
return ERR;
for (i = 0; i < win->_maxy; i++)
{
win->_firstch[i] = 0;
win->_lastch[i] = win->_maxx - 1;
}
return OK;
}
int touchline(WINDOW *win, int start, int count)
{
int i;
PDC_LOG(("touchline() - called: win=%p start %d count %d\n",
win, start, count));
if (!win || start > win->_maxy || start + count > win->_maxy)
return ERR;
for (i = start; i < start + count; i++)
{
win->_firstch[i] = 0;
win->_lastch[i] = win->_maxx - 1;
}
return OK;
}
int untouchwin(WINDOW *win)
{
int i;
PDC_LOG(("untouchwin() - called: win=%p", win));
if (!win)
return ERR;
for (i = 0; i < win->_maxy; i++)
{
win->_firstch[i] = _NO_CHANGE;
win->_lastch[i] = _NO_CHANGE;
}
return OK;
}
int wtouchln(WINDOW *win, int y, int n, int changed)
{
int i;
PDC_LOG(("wtouchln() - called: win=%p y=%d n=%d changed=%d\n",
win, y, n, changed));
if (!win || y > win->_maxy || y + n > win->_maxy)
return ERR;
for (i = y; i < y + n; i++)
{
if (changed)
{
win->_firstch[i] = 0;
win->_lastch[i] = win->_maxx - 1;
}
else
{
win->_firstch[i] = _NO_CHANGE;
win->_lastch[i] = _NO_CHANGE;
}
}
return OK;
}
bool is_linetouched(WINDOW *win, int line)
{
PDC_LOG(("is_linetouched() - called: win=%p line=%d\n", win, line));
if (!win || line > win->_maxy || line < 0)
return FALSE;
return (win->_firstch[line] != _NO_CHANGE) ? TRUE : FALSE;
}
bool is_wintouched(WINDOW *win)
{
int i;
PDC_LOG(("is_wintouched() - called: win=%p\n", win));
if (win)
for (i = 0; i < win->_maxy; i++)
if (win->_firstch[i] != _NO_CHANGE)
return TRUE;
return FALSE;
} |
#include <linux/init.h>
#include <linux/bitmap.h>
#include <linux/debugfs.h>
#include <linux/export.h>
#include <linux/slab.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/pci.h>
#include <linux/dmar.h>
#include <linux/dma-mapping.h>
#include <linux/mempool.h>
#include <linux/memory.h>
#include <linux/timer.h>
#include <linux/iova.h>
#include <linux/iommu.h>
#include <linux/intel-iommu.h>
#include <linux/syscore_ops.h>
#include <linux/tboot.h>
#include <linux/dmi.h>
#include <linux/pci-ats.h>
#include <linux/memblock.h>
#include <asm/irq_remapping.h>
#include <asm/cacheflush.h>
#include <asm/iommu.h>
#include "irq_remapping.h"
#include "pci.h"
#define ROOT_SIZE VTD_PAGE_SIZE
#define CONTEXT_SIZE VTD_PAGE_SIZE
#define IS_GFX_DEVICE(pdev) ((pdev->class >> 16) == <API key>)
#define IS_ISA_DEVICE(pdev) ((pdev->class >> 8) == <API key>)
#define IS_AZALIA(pdev) ((pdev)->vendor == 0x8086 && (pdev)->device == 0x3a3e)
#define IOAPIC_RANGE_START (0xfee00000)
#define IOAPIC_RANGE_END (0xfeefffff)
#define IOVA_START_ADDR (0x1000)
#define <API key> 48
#define MAX_AGAW_WIDTH 64
#define MAX_AGAW_PFN_WIDTH (MAX_AGAW_WIDTH - VTD_PAGE_SHIFT)
#define __DOMAIN_MAX_PFN(gaw) ((((uint64_t)1) << (gaw-VTD_PAGE_SHIFT)) - 1)
#define __DOMAIN_MAX_ADDR(gaw) ((((uint64_t)1) << gaw) - 1)
/* We limit DOMAIN_MAX_PFN to fit in an unsigned long, and DOMAIN_MAX_ADDR
to match. That way, we can use 'unsigned long' for PFNs with impunity. */
#define DOMAIN_MAX_PFN(gaw) ((unsigned long) min_t(uint64_t, \
__DOMAIN_MAX_PFN(gaw), (unsigned long)-1))
#define DOMAIN_MAX_ADDR(gaw) (((uint64_t)__DOMAIN_MAX_PFN(gaw)) << VTD_PAGE_SHIFT)
#define IOVA_PFN(addr) ((addr) >> PAGE_SHIFT)
#define DMA_32BIT_PFN IOVA_PFN(DMA_BIT_MASK(32))
#define DMA_64BIT_PFN IOVA_PFN(DMA_BIT_MASK(64))
/* page table handling */
#define LEVEL_STRIDE (9)
#define LEVEL_MASK (((u64)1 << LEVEL_STRIDE) - 1)
/*
* This bitmap is used to advertise the page sizes our hardware support
* to the IOMMU core, which will then use this information to split
* physically contiguous memory regions it is mapping into page sizes
* that we support.
*
* Traditionally the IOMMU core just handed us the mappings directly,
* after making sure the size is an order of a 4KiB page and that the
* mapping has natural alignment.
*
* To retain this behavior, we currently advertise that we support
* all page sizes that are an order of 4KiB.
*
* If at some point we'd like to utilize the IOMMU core's new behavior,
* we could change this to advertise the real page sizes we support.
*/
#define INTEL_IOMMU_PGSIZES (~0xFFFUL)
static inline int agaw_to_level(int agaw)
{
return agaw + 2;
}
static inline int agaw_to_width(int agaw)
{
return min_t(int, 30 + agaw * LEVEL_STRIDE, MAX_AGAW_WIDTH);
}
static inline int width_to_agaw(int width)
{
return DIV_ROUND_UP(width - 30, LEVEL_STRIDE);
}
static inline unsigned int <API key>(int level)
{
return (level - 1) * LEVEL_STRIDE;
}
static inline int pfn_level_offset(unsigned long pfn, int level)
{
return (pfn >> <API key>(level)) & LEVEL_MASK;
}
static inline unsigned long level_mask(int level)
{
return -1UL << <API key>(level);
}
static inline unsigned long level_size(int level)
{
return 1UL << <API key>(level);
}
static inline unsigned long align_to_level(unsigned long pfn, int level)
{
return (pfn + level_size(level) - 1) & level_mask(level);
}
static inline unsigned long lvl_to_nr_pages(unsigned int lvl)
{
return 1 << min_t(int, (lvl - 1) * LEVEL_STRIDE, MAX_AGAW_PFN_WIDTH);
}
/* VT-d pages must always be _smaller_ than MM pages. Otherwise things
are never going to work. */
static inline unsigned long dma_to_mm_pfn(unsigned long dma_pfn)
{
return dma_pfn >> (PAGE_SHIFT - VTD_PAGE_SHIFT);
}
static inline unsigned long mm_to_dma_pfn(unsigned long mm_pfn)
{
return mm_pfn << (PAGE_SHIFT - VTD_PAGE_SHIFT);
}
static inline unsigned long page_to_dma_pfn(struct page *pg)
{
return mm_to_dma_pfn(page_to_pfn(pg));
}
static inline unsigned long virt_to_dma_pfn(void *p)
{
return page_to_dma_pfn(virt_to_page(p));
}
/* global iommu list, set NULL for ignored DMAR units */
static struct intel_iommu **g_iommus;
static void __init <API key>(void);
static int rwbf_quirk;
/*
* set to 1 to panic kernel if can't successfully enable VT-d
* (used when kernel is launched w/ TXT)
*/
static int force_on = 0;
/*
* 0: Present
* 1-11: Reserved
* 12-63: Context Ptr (12 - (haw-1))
* 64-127: Reserved
*/
struct root_entry {
u64 val;
u64 rsvd1;
};
#define ROOT_ENTRY_NR (VTD_PAGE_SIZE/sizeof(struct root_entry))
static inline bool root_present(struct root_entry *root)
{
return (root->val & 1);
}
static inline void set_root_present(struct root_entry *root)
{
root->val |= 1;
}
static inline void set_root_value(struct root_entry *root, unsigned long value)
{
root->val |= value & VTD_PAGE_MASK;
}
static inline struct context_entry *
<API key>(struct root_entry *root)
{
return (struct context_entry *)
(root_present(root)?phys_to_virt(
root->val & VTD_PAGE_MASK) :
NULL);
}
/*
* low 64 bits:
* 0: present
* 1: fault processing disable
* 2-3: translation type
* 12-63: address space root
* high 64 bits:
* 0-2: address width
* 3-6: aval
* 8-23: domain id
*/
struct context_entry {
u64 lo;
u64 hi;
};
static inline bool context_present(struct context_entry *context)
{
return (context->lo & 1);
}
static inline void context_set_present(struct context_entry *context)
{
context->lo |= 1;
}
static inline void <API key>(struct context_entry *context)
{
context->lo &= (((u64)-1) << 2) | 1;
}
static inline void <API key>(struct context_entry *context,
unsigned long value)
{
context->lo &= (((u64)-1) << 4) | 3;
context->lo |= (value & 3) << 2;
}
static inline void <API key>(struct context_entry *context,
unsigned long value)
{
context->lo |= value & VTD_PAGE_MASK;
}
static inline void <API key>(struct context_entry *context,
unsigned long value)
{
context->hi |= value & 7;
}
static inline void <API key>(struct context_entry *context,
unsigned long value)
{
context->hi |= (value & ((1 << 16) - 1)) << 8;
}
static inline void context_clear_entry(struct context_entry *context)
{
context->lo = 0;
context->hi = 0;
}
/*
* 0: readable
* 1: writable
* 2-6: reserved
* 7: super page
* 8-10: available
* 11: snoop behavior
* 12-63: Host physcial address
*/
struct dma_pte {
u64 val;
};
static inline void dma_clear_pte(struct dma_pte *pte)
{
pte->val = 0;
}
static inline u64 dma_pte_addr(struct dma_pte *pte)
{
#ifdef CONFIG_64BIT
return pte->val & VTD_PAGE_MASK;
#else
/* Must have a full atomic 64-bit read */
return __cmpxchg64(&pte->val, 0ULL, 0ULL) & VTD_PAGE_MASK;
#endif
}
static inline bool dma_pte_present(struct dma_pte *pte)
{
return (pte->val & 3) != 0;
}
static inline bool dma_pte_superpage(struct dma_pte *pte)
{
return (pte->val & (1 << 7));
}
static inline int first_pte_in_page(struct dma_pte *pte)
{
return !((unsigned long)pte & ~VTD_PAGE_MASK);
}
/*
* This domain is a statically identity mapping domain.
* 1. This domain creats a static 1:1 mapping to all usable memory.
* 2. It maps to each iommu if successful.
* 3. Each iommu mapps to this domain if successful.
*/
static struct dmar_domain *si_domain;
static int hw_pass_through = 1;
/* devices under the same p2p bridge are owned in one domain */
#define <API key> (1 << 0)
/* domain represents a virtual machine, more than one devices
* across iommus may be owned in one domain, e.g. kvm guest.
*/
#define <API key> (1 << 1)
/* si_domain contains mulitple devices */
#define <API key> (1 << 2)
/* define the limit of IOMMUs supported in each domain */
#ifdef CONFIG_X86
# define <API key> MAX_IO_APICS
#else
# define <API key> 64
#endif
struct dmar_domain {
int id; /* domain id */
int nid; /* node id */
DECLARE_BITMAP(iommu_bmp, <API key>);
/* bitmap of iommus this domain uses*/
struct list_head devices; /* all devices' list */
struct iova_domain iovad; /* iova's that belong to this domain */
struct dma_pte *pgd; /* virtual address */
int gaw; /* max guest address width */
/* adjusted guest address width, 0 is level 2 30-bit */
int agaw;
int flags; /* flags to find out type of domain */
int iommu_coherency;/* indicate coherency of iommu access */
int iommu_snooping; /* indicate snooping control feature*/
int iommu_count; /* reference count of iommu */
int iommu_superpage;/* Level of superpages supported:
0 == 4KiB (no superpages), 1 == 2MiB,
2 == 1GiB, 3 == 512GiB, 4 == 1TiB */
spinlock_t iommu_lock; /* protect iommu set in domain */
u64 max_addr; /* maximum mapped address */
};
/* PCI domain-device relationship */
struct device_domain_info {
struct list_head link; /* link to domain siblings */
struct list_head global; /* link to global list */
u8 bus; /* PCI bus number */
u8 devfn; /* PCI devfn number */
struct device *dev; /* it's NULL for PCIe-to-PCI bridge */
struct intel_iommu *iommu; /* IOMMU used by this device */
struct dmar_domain *domain; /* pointer to domain */
};
struct dmar_rmrr_unit {
struct list_head list; /* list of rmrr units */
struct acpi_dmar_header *hdr; /* ACPI header */
u64 base_address; /* reserved base address*/
u64 end_address; /* reserved end address */
struct dmar_dev_scope *devices; /* target devices */
int devices_cnt; /* target device count */
};
struct dmar_atsr_unit {
struct list_head list; /* list of ATSR units */
struct acpi_dmar_header *hdr; /* ACPI header */
struct dmar_dev_scope *devices; /* target devices */
int devices_cnt; /* target device count */
u8 include_all:1; /* include all ports */
};
static LIST_HEAD(dmar_atsr_units);
static LIST_HEAD(dmar_rmrr_units);
#define for_each_rmrr_units(rmrr) \
list_for_each_entry(rmrr, &dmar_rmrr_units, list)
static void <API key>(unsigned long data);
static DEFINE_TIMER(unmap_timer, <API key>, 0, 0);
#define HIGH_WATER_MARK 250
struct <API key> {
int next;
struct iova *iova[HIGH_WATER_MARK];
struct dmar_domain *domain[HIGH_WATER_MARK];
struct page *freelist[HIGH_WATER_MARK];
};
static struct <API key> *deferred_flush;
/* bitmap for indexing intel_iommus */
static int g_num_of_iommus;
static DEFINE_SPINLOCK(<API key>);
static LIST_HEAD(unmaps_to_do);
static int timer_on;
static long list_size;
static void domain_exit(struct dmar_domain *domain);
static void <API key>(struct dmar_domain *domain);
static void <API key>(struct dmar_domain *domain,
struct device *dev);
static void <API key>(struct intel_iommu *iommu,
struct device *dev);
#ifdef <API key>
int dmar_disabled = 0;
#else
int dmar_disabled = 1;
#endif /*<API key>*/
int intel_iommu_enabled = 0;
EXPORT_SYMBOL_GPL(intel_iommu_enabled);
static int dmar_map_gfx = 1;
static int dmar_forcedac;
static int intel_iommu_strict;
static int <API key> = 1;
int <API key>;
EXPORT_SYMBOL_GPL(<API key>);
#define <API key> ((struct device_domain_info *)(-1))
static DEFINE_SPINLOCK(device_domain_lock);
static LIST_HEAD(device_domain_list);
static struct iommu_ops intel_iommu_ops;
static int __init intel_iommu_setup(char *str)
{
if (!str)
return -EINVAL;
while (*str) {
if (!strncmp(str, "on", 2)) {
dmar_disabled = 0;
printk(KERN_INFO "Intel-IOMMU: enabled\n");
} else if (!strncmp(str, "off", 3)) {
dmar_disabled = 1;
printk(KERN_INFO "Intel-IOMMU: disabled\n");
} else if (!strncmp(str, "igfx_off", 8)) {
dmar_map_gfx = 0;
printk(KERN_INFO
"Intel-IOMMU: disable GFX device mapping\n");
} else if (!strncmp(str, "forcedac", 8)) {
printk(KERN_INFO
"Intel-IOMMU: Forcing DAC for PCI devices\n");
dmar_forcedac = 1;
} else if (!strncmp(str, "strict", 6)) {
printk(KERN_INFO
"Intel-IOMMU: disable batched IOTLB flush\n");
intel_iommu_strict = 1;
} else if (!strncmp(str, "sp_off", 6)) {
printk(KERN_INFO
"Intel-IOMMU: disable supported super page\n");
<API key> = 0;
}
str += strcspn(str, ",");
while (*str == ',')
str++;
}
return 0;
}
__setup("intel_iommu=", intel_iommu_setup);
static struct kmem_cache *iommu_domain_cache;
static struct kmem_cache *iommu_devinfo_cache;
static struct kmem_cache *iommu_iova_cache;
static inline void *alloc_pgtable_page(int node)
{
struct page *page;
void *vaddr = NULL;
page = alloc_pages_node(node, GFP_ATOMIC | __GFP_ZERO, 0);
if (page)
vaddr = page_address(page);
return vaddr;
}
static inline void free_pgtable_page(void *vaddr)
{
free_page((unsigned long)vaddr);
}
static inline void *alloc_domain_mem(void)
{
return kmem_cache_alloc(iommu_domain_cache, GFP_ATOMIC);
}
static void free_domain_mem(void *vaddr)
{
kmem_cache_free(iommu_domain_cache, vaddr);
}
static inline void * alloc_devinfo_mem(void)
{
return kmem_cache_alloc(iommu_devinfo_cache, GFP_ATOMIC);
}
static inline void free_devinfo_mem(void *vaddr)
{
kmem_cache_free(iommu_devinfo_cache, vaddr);
}
struct iova *alloc_iova_mem(void)
{
return kmem_cache_alloc(iommu_iova_cache, GFP_ATOMIC);
}
void free_iova_mem(struct iova *iova)
{
kmem_cache_free(iommu_iova_cache, iova);
}
static int <API key>(struct intel_iommu *iommu, int max_gaw)
{
unsigned long sagaw;
int agaw = -1;
sagaw = cap_sagaw(iommu->cap);
for (agaw = width_to_agaw(max_gaw);
agaw >= 0; agaw
if (test_bit(agaw, &sagaw))
break;
}
return agaw;
}
/*
* Calculate max SAGAW for each iommu.
*/
int <API key>(struct intel_iommu *iommu)
{
return <API key>(iommu, MAX_AGAW_WIDTH);
}
/*
* calculate agaw for each iommu.
* "SAGAW" may be different across iommus, use a default agaw, and
* get a supported less agaw for iommus that don't support the default agaw.
*/
int <API key>(struct intel_iommu *iommu)
{
return <API key>(iommu, <API key>);
}
/* This functionin only returns single iommu in a domain */
static struct intel_iommu *domain_get_iommu(struct dmar_domain *domain)
{
int iommu_id;
/* si_domain and vm domain should not get here. */
BUG_ON(domain->flags & <API key>);
BUG_ON(domain->flags & <API key>);
iommu_id = find_first_bit(domain->iommu_bmp, g_num_of_iommus);
if (iommu_id < 0 || iommu_id >= g_num_of_iommus)
return NULL;
return g_iommus[iommu_id];
}
static void <API key>(struct dmar_domain *domain)
{
struct dmar_drhd_unit *drhd;
struct intel_iommu *iommu;
int i, found = 0;
domain->iommu_coherency = 1;
for_each_set_bit(i, domain->iommu_bmp, g_num_of_iommus) {
found = 1;
if (!ecap_coherent(g_iommus[i]->ecap)) {
domain->iommu_coherency = 0;
break;
}
}
if (found)
return;
/* No hardware attached; use lowest common denominator */
rcu_read_lock();
<API key>(iommu, drhd) {
if (!ecap_coherent(iommu->ecap)) {
domain->iommu_coherency = 0;
break;
}
}
rcu_read_unlock();
}
static void <API key>(struct dmar_domain *domain)
{
int i;
domain->iommu_snooping = 1;
for_each_set_bit(i, domain->iommu_bmp, g_num_of_iommus) {
if (!ecap_sc_support(g_iommus[i]->ecap)) {
domain->iommu_snooping = 0;
break;
}
}
}
static void <API key>(struct dmar_domain *domain)
{
struct dmar_drhd_unit *drhd;
struct intel_iommu *iommu = NULL;
int mask = 0xf;
if (!<API key>) {
domain->iommu_superpage = 0;
return;
}
/* set iommu_superpage to the smallest common denominator */
rcu_read_lock();
<API key>(iommu, drhd) {
mask &= cap_super_page_val(iommu->cap);
if (!mask) {
break;
}
}
rcu_read_unlock();
domain->iommu_superpage = fls(mask);
}
/* Some capabilities may be different across iommus */
static void <API key>(struct dmar_domain *domain)
{
<API key>(domain);
<API key>(domain);
<API key>(domain);
}
static struct intel_iommu *device_to_iommu(struct device *dev, u8 *bus, u8 *devfn)
{
struct dmar_drhd_unit *drhd = NULL;
struct intel_iommu *iommu;
struct device *tmp;
struct pci_dev *ptmp, *pdev = NULL;
u16 segment;
int i;
if (dev_is_pci(dev)) {
pdev = to_pci_dev(dev);
segment = pci_domain_nr(pdev->bus);
} else if (ACPI_COMPANION(dev))
dev = &ACPI_COMPANION(dev)->dev;
rcu_read_lock();
<API key>(iommu, drhd) {
if (pdev && segment != drhd->segment)
continue;
<API key>(drhd->devices,
drhd->devices_cnt, i, tmp) {
if (tmp == dev) {
*bus = drhd->devices[i].bus;
*devfn = drhd->devices[i].devfn;
goto out;
}
if (!pdev || !dev_is_pci(tmp))
continue;
ptmp = to_pci_dev(tmp);
if (ptmp->subordinate &&
ptmp->subordinate->number <= pdev->bus->number &&
ptmp->subordinate->busn_res.end >= pdev->bus->number)
goto got_pdev;
}
if (pdev && drhd->include_all) {
got_pdev:
*bus = pdev->bus->number;
*devfn = pdev->devfn;
goto out;
}
}
iommu = NULL;
out:
rcu_read_unlock();
return iommu;
}
static void domain_flush_cache(struct dmar_domain *domain,
void *addr, int size)
{
if (!domain->iommu_coherency)
clflush_cache_range(addr, size);
}
/* Gets context entry for a given bus and devfn */
static struct context_entry * <API key>(struct intel_iommu *iommu,
u8 bus, u8 devfn)
{
struct root_entry *root;
struct context_entry *context;
unsigned long phy_addr;
unsigned long flags;
spin_lock_irqsave(&iommu->lock, flags);
root = &iommu->root_entry[bus];
context = <API key>(root);
if (!context) {
context = (struct context_entry *)
alloc_pgtable_page(iommu->node);
if (!context) {
<API key>(&iommu->lock, flags);
return NULL;
}
__iommu_flush_cache(iommu, (void *)context, CONTEXT_SIZE);
phy_addr = virt_to_phys((void *)context);
set_root_value(root, phy_addr);
set_root_present(root);
__iommu_flush_cache(iommu, root, sizeof(*root));
}
<API key>(&iommu->lock, flags);
return &context[devfn];
}
static int <API key>(struct intel_iommu *iommu, u8 bus, u8 devfn)
{
struct root_entry *root;
struct context_entry *context;
int ret;
unsigned long flags;
spin_lock_irqsave(&iommu->lock, flags);
root = &iommu->root_entry[bus];
context = <API key>(root);
if (!context) {
ret = 0;
goto out;
}
ret = context_present(&context[devfn]);
out:
<API key>(&iommu->lock, flags);
return ret;
}
static void clear_context_table(struct intel_iommu *iommu, u8 bus, u8 devfn)
{
struct root_entry *root;
struct context_entry *context;
unsigned long flags;
spin_lock_irqsave(&iommu->lock, flags);
root = &iommu->root_entry[bus];
context = <API key>(root);
if (context) {
context_clear_entry(&context[devfn]);
__iommu_flush_cache(iommu, &context[devfn], \
sizeof(*context));
}
<API key>(&iommu->lock, flags);
}
static void free_context_table(struct intel_iommu *iommu)
{
struct root_entry *root;
int i;
unsigned long flags;
struct context_entry *context;
spin_lock_irqsave(&iommu->lock, flags);
if (!iommu->root_entry) {
goto out;
}
for (i = 0; i < ROOT_ENTRY_NR; i++) {
root = &iommu->root_entry[i];
context = <API key>(root);
if (context)
free_pgtable_page(context);
}
free_pgtable_page(iommu->root_entry);
iommu->root_entry = NULL;
out:
<API key>(&iommu->lock, flags);
}
static struct dma_pte *pfn_to_dma_pte(struct dmar_domain *domain,
unsigned long pfn, int *target_level)
{
int addr_width = agaw_to_width(domain->agaw) - VTD_PAGE_SHIFT;
struct dma_pte *parent, *pte = NULL;
int level = agaw_to_level(domain->agaw);
int offset;
BUG_ON(!domain->pgd);
if (addr_width < BITS_PER_LONG && pfn >> addr_width)
/* Address beyond IOMMU's addressing capabilities. */
return NULL;
parent = domain->pgd;
while (1) {
void *tmp_page;
offset = pfn_level_offset(pfn, level);
pte = &parent[offset];
if (!*target_level && (dma_pte_superpage(pte) || !dma_pte_present(pte)))
break;
if (level == *target_level)
break;
if (!dma_pte_present(pte)) {
uint64_t pteval;
tmp_page = alloc_pgtable_page(domain->nid);
if (!tmp_page)
return NULL;
domain_flush_cache(domain, tmp_page, VTD_PAGE_SIZE);
pteval = ((uint64_t)virt_to_dma_pfn(tmp_page) << VTD_PAGE_SHIFT) | DMA_PTE_READ | DMA_PTE_WRITE;
if (cmpxchg64(&pte->val, 0ULL, pteval)) {
/* Someone else set it while we were thinking; use theirs. */
free_pgtable_page(tmp_page);
} else {
dma_pte_addr(pte);
domain_flush_cache(domain, pte, sizeof(*pte));
}
}
if (level == 1)
break;
parent = phys_to_virt(dma_pte_addr(pte));
level
}
if (!*target_level)
*target_level = level;
return pte;
}
/* return address's pte at specific level */
static struct dma_pte *dma_pfn_level_pte(struct dmar_domain *domain,
unsigned long pfn,
int level, int *large_page)
{
struct dma_pte *parent, *pte = NULL;
int total = agaw_to_level(domain->agaw);
int offset;
parent = domain->pgd;
while (level <= total) {
offset = pfn_level_offset(pfn, total);
pte = &parent[offset];
if (level == total)
return pte;
if (!dma_pte_present(pte)) {
*large_page = total;
break;
}
if (pte->val & DMA_PTE_LARGE_PAGE) {
*large_page = total;
return pte;
}
parent = phys_to_virt(dma_pte_addr(pte));
total
}
return NULL;
}
/* clear last level pte, a tlb flush should be followed */
static void dma_pte_clear_range(struct dmar_domain *domain,
unsigned long start_pfn,
unsigned long last_pfn)
{
int addr_width = agaw_to_width(domain->agaw) - VTD_PAGE_SHIFT;
unsigned int large_page = 1;
struct dma_pte *first_pte, *pte;
BUG_ON(addr_width < BITS_PER_LONG && start_pfn >> addr_width);
BUG_ON(addr_width < BITS_PER_LONG && last_pfn >> addr_width);
BUG_ON(start_pfn > last_pfn);
/* we don't need lock here; nobody else touches the iova range */
do {
large_page = 1;
first_pte = pte = dma_pfn_level_pte(domain, start_pfn, 1, &large_page);
if (!pte) {
start_pfn = align_to_level(start_pfn + 1, large_page + 1);
continue;
}
do {
dma_clear_pte(pte);
start_pfn += lvl_to_nr_pages(large_page);
pte++;
} while (start_pfn <= last_pfn && !first_pte_in_page(pte));
domain_flush_cache(domain, first_pte,
(void *)pte - (void *)first_pte);
} while (start_pfn && start_pfn <= last_pfn);
}
static void dma_pte_free_level(struct dmar_domain *domain, int level,
struct dma_pte *pte, unsigned long pfn,
unsigned long start_pfn, unsigned long last_pfn)
{
pfn = max(start_pfn, pfn);
pte = &pte[pfn_level_offset(pfn, level)];
do {
unsigned long level_pfn;
struct dma_pte *level_pte;
if (!dma_pte_present(pte) || dma_pte_superpage(pte))
goto next;
level_pfn = pfn & level_mask(level - 1);
level_pte = phys_to_virt(dma_pte_addr(pte));
if (level > 2)
dma_pte_free_level(domain, level - 1, level_pte,
level_pfn, start_pfn, last_pfn);
/* If range covers entire pagetable, free it */
if (!(start_pfn > level_pfn ||
last_pfn < level_pfn + level_size(level) - 1)) {
dma_clear_pte(pte);
domain_flush_cache(domain, pte, sizeof(*pte));
free_pgtable_page(level_pte);
}
next:
pfn += level_size(level);
} while (!first_pte_in_page(++pte) && pfn <= last_pfn);
}
/* free page table pages. last level pte should already be cleared */
static void <API key>(struct dmar_domain *domain,
unsigned long start_pfn,
unsigned long last_pfn)
{
int addr_width = agaw_to_width(domain->agaw) - VTD_PAGE_SHIFT;
BUG_ON(addr_width < BITS_PER_LONG && start_pfn >> addr_width);
BUG_ON(addr_width < BITS_PER_LONG && last_pfn >> addr_width);
BUG_ON(start_pfn > last_pfn);
/* We don't need lock here; nobody else touches the iova range */
dma_pte_free_level(domain, agaw_to_level(domain->agaw),
domain->pgd, 0, start_pfn, last_pfn);
/* free pgd */
if (start_pfn == 0 && last_pfn == DOMAIN_MAX_PFN(domain->gaw)) {
free_pgtable_page(domain->pgd);
domain->pgd = NULL;
}
}
/* When a page at a given level is being unlinked from its parent, we don't
need to *modify* it at all. All we need to do is make a list of all the
pages which can be freed just as soon as we've flushed the IOTLB and we
know the hardware page-walk will no longer touch them.
The 'pte' argument is the *parent* PTE, pointing to the page that is to
be freed. */
static struct page *<API key>(struct dmar_domain *domain,
int level, struct dma_pte *pte,
struct page *freelist)
{
struct page *pg;
pg = pfn_to_page(dma_pte_addr(pte) >> PAGE_SHIFT);
pg->freelist = freelist;
freelist = pg;
if (level == 1)
return freelist;
pte = page_address(pg);
do {
if (dma_pte_present(pte) && !dma_pte_superpage(pte))
freelist = <API key>(domain, level - 1,
pte, freelist);
pte++;
} while (!first_pte_in_page(pte));
return freelist;
}
static struct page *dma_pte_clear_level(struct dmar_domain *domain, int level,
struct dma_pte *pte, unsigned long pfn,
unsigned long start_pfn,
unsigned long last_pfn,
struct page *freelist)
{
struct dma_pte *first_pte = NULL, *last_pte = NULL;
pfn = max(start_pfn, pfn);
pte = &pte[pfn_level_offset(pfn, level)];
do {
unsigned long level_pfn;
if (!dma_pte_present(pte))
goto next;
level_pfn = pfn & level_mask(level);
/* If range covers entire pagetable, free it */
if (start_pfn <= level_pfn &&
last_pfn >= level_pfn + level_size(level) - 1) {
/* These suborbinate page tables are going away entirely. Don't
bother to clear them; we're just going to *free* them. */
if (level > 1 && !dma_pte_superpage(pte))
freelist = <API key>(domain, level - 1, pte, freelist);
dma_clear_pte(pte);
if (!first_pte)
first_pte = pte;
last_pte = pte;
} else if (level > 1) {
/* Recurse down into a level that isn't *entirely* obsolete */
freelist = dma_pte_clear_level(domain, level - 1,
phys_to_virt(dma_pte_addr(pte)),
level_pfn, start_pfn, last_pfn,
freelist);
}
next:
pfn += level_size(level);
} while (!first_pte_in_page(++pte) && pfn <= last_pfn);
if (first_pte)
domain_flush_cache(domain, first_pte,
(void *)++last_pte - (void *)first_pte);
return freelist;
}
/* We can't just free the pages because the IOMMU may still be walking
the page tables, and may have cached the intermediate levels. The
pages can only be freed after the IOTLB flush has been done. */
struct page *domain_unmap(struct dmar_domain *domain,
unsigned long start_pfn,
unsigned long last_pfn)
{
int addr_width = agaw_to_width(domain->agaw) - VTD_PAGE_SHIFT;
struct page *freelist = NULL;
BUG_ON(addr_width < BITS_PER_LONG && start_pfn >> addr_width);
BUG_ON(addr_width < BITS_PER_LONG && last_pfn >> addr_width);
BUG_ON(start_pfn > last_pfn);
/* we don't need lock here; nobody else touches the iova range */
freelist = dma_pte_clear_level(domain, agaw_to_level(domain->agaw),
domain->pgd, 0, start_pfn, last_pfn, NULL);
/* free pgd */
if (start_pfn == 0 && last_pfn == DOMAIN_MAX_PFN(domain->gaw)) {
struct page *pgd_page = virt_to_page(domain->pgd);
pgd_page->freelist = freelist;
freelist = pgd_page;
domain->pgd = NULL;
}
return freelist;
}
void dma_free_pagelist(struct page *freelist)
{
struct page *pg;
while ((pg = freelist)) {
freelist = pg->freelist;
free_pgtable_page(page_address(pg));
}
}
/* iommu handling */
static int <API key>(struct intel_iommu *iommu)
{
struct root_entry *root;
unsigned long flags;
root = (struct root_entry *)alloc_pgtable_page(iommu->node);
if (!root)
return -ENOMEM;
__iommu_flush_cache(iommu, root, ROOT_SIZE);
spin_lock_irqsave(&iommu->lock, flags);
iommu->root_entry = root;
<API key>(&iommu->lock, flags);
return 0;
}
static void <API key>(struct intel_iommu *iommu)
{
void *addr;
u32 sts;
unsigned long flag;
addr = iommu->root_entry;
<API key>(&iommu->register_lock, flag);
dmar_writeq(iommu->reg + DMAR_RTADDR_REG, virt_to_phys(addr));
writel(iommu->gcmd | DMA_GCMD_SRTP, iommu->reg + DMAR_GCMD_REG);
/* Make sure hardware complete it */
IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
readl, (sts & DMA_GSTS_RTPS), sts);
<API key>(&iommu->register_lock, flag);
}
static void <API key>(struct intel_iommu *iommu)
{
u32 val;
unsigned long flag;
if (!rwbf_quirk && !cap_rwbf(iommu->cap))
return;
<API key>(&iommu->register_lock, flag);
writel(iommu->gcmd | DMA_GCMD_WBF, iommu->reg + DMAR_GCMD_REG);
/* Make sure hardware complete it */
IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
readl, (!(val & DMA_GSTS_WBFS)), val);
<API key>(&iommu->register_lock, flag);
}
/* return value determine if we need a write buffer flush */
static void <API key>(struct intel_iommu *iommu,
u16 did, u16 source_id, u8 function_mask,
u64 type)
{
u64 val = 0;
unsigned long flag;
switch (type) {
case <API key>:
val = <API key>;
break;
case <API key>:
val = <API key>|DMA_CCMD_DID(did);
break;
case <API key>:
val = <API key>|DMA_CCMD_DID(did)
| DMA_CCMD_SID(source_id) | DMA_CCMD_FM(function_mask);
break;
default:
BUG();
}
val |= DMA_CCMD_ICC;
<API key>(&iommu->register_lock, flag);
dmar_writeq(iommu->reg + DMAR_CCMD_REG, val);
/* Make sure hardware complete it */
IOMMU_WAIT_OP(iommu, DMAR_CCMD_REG,
dmar_readq, (!(val & DMA_CCMD_ICC)), val);
<API key>(&iommu->register_lock, flag);
}
/* return value determine if we need a write buffer flush */
static void __iommu_flush_iotlb(struct intel_iommu *iommu, u16 did,
u64 addr, unsigned int size_order, u64 type)
{
int tlb_offset = ecap_iotlb_offset(iommu->ecap);
u64 val = 0, val_iva = 0;
unsigned long flag;
switch (type) {
case <API key>:
/* global flush doesn't need set IVA_REG */
val = <API key>|DMA_TLB_IVT;
break;
case DMA_TLB_DSI_FLUSH:
val = DMA_TLB_DSI_FLUSH|DMA_TLB_IVT|DMA_TLB_DID(did);
break;
case DMA_TLB_PSI_FLUSH:
val = DMA_TLB_PSI_FLUSH|DMA_TLB_IVT|DMA_TLB_DID(did);
/* IH bit is passed in as part of address */
val_iva = size_order | addr;
break;
default:
BUG();
}
/* Note: set drain read/write */
#if 0
/*
* This is probably to be super secure.. Looks like we can
* ignore it without any impact.
*/
if (cap_read_drain(iommu->cap))
val |= DMA_TLB_READ_DRAIN;
#endif
if (cap_write_drain(iommu->cap))
val |= DMA_TLB_WRITE_DRAIN;
<API key>(&iommu->register_lock, flag);
/* Note: Only uses first TLB reg currently */
if (val_iva)
dmar_writeq(iommu->reg + tlb_offset, val_iva);
dmar_writeq(iommu->reg + tlb_offset + 8, val);
/* Make sure hardware complete it */
IOMMU_WAIT_OP(iommu, tlb_offset + 8,
dmar_readq, (!(val & DMA_TLB_IVT)), val);
<API key>(&iommu->register_lock, flag);
/* check IOTLB invalidation granularity */
if (DMA_TLB_IAIG(val) == 0)
printk(KERN_ERR"IOMMU: flush IOTLB failed\n");
if (DMA_TLB_IAIG(val) != DMA_TLB_IIRG(type))
pr_debug("IOMMU: tlb flush request %Lx, actual %Lx\n",
(unsigned long long)DMA_TLB_IIRG(type),
(unsigned long long)DMA_TLB_IAIG(val));
}
static struct device_domain_info *
<API key> (struct dmar_domain *domain, struct intel_iommu *iommu,
u8 bus, u8 devfn)
{
int found = 0;
unsigned long flags;
struct device_domain_info *info;
struct pci_dev *pdev;
if (!<API key>(iommu->ecap))
return NULL;
if (!iommu->qi)
return NULL;
spin_lock_irqsave(&device_domain_lock, flags);
list_for_each_entry(info, &domain->devices, link)
if (info->bus == bus && info->devfn == devfn) {
found = 1;
break;
}
<API key>(&device_domain_lock, flags);
if (!found || !info->dev || !dev_is_pci(info->dev))
return NULL;
pdev = to_pci_dev(info->dev);
if (!<API key>(pdev, PCI_EXT_CAP_ID_ATS))
return NULL;
if (!<API key>(pdev))
return NULL;
return info;
}
static void <API key>(struct device_domain_info *info)
{
if (!info || !dev_is_pci(info->dev))
return;
pci_enable_ats(to_pci_dev(info->dev), VTD_PAGE_SHIFT);
}
static void <API key>(struct device_domain_info *info)
{
if (!info->dev || !dev_is_pci(info->dev) ||
!pci_ats_enabled(to_pci_dev(info->dev)))
return;
pci_disable_ats(to_pci_dev(info->dev));
}
static void <API key>(struct dmar_domain *domain,
u64 addr, unsigned mask)
{
u16 sid, qdep;
unsigned long flags;
struct device_domain_info *info;
spin_lock_irqsave(&device_domain_lock, flags);
list_for_each_entry(info, &domain->devices, link) {
struct pci_dev *pdev;
if (!info->dev || !dev_is_pci(info->dev))
continue;
pdev = to_pci_dev(info->dev);
if (!pci_ats_enabled(pdev))
continue;
sid = info->bus << 8 | info->devfn;
qdep = pci_ats_queue_depth(pdev);
qi_flush_dev_iotlb(info->iommu, sid, qdep, addr, mask);
}
<API key>(&device_domain_lock, flags);
}
static void <API key>(struct intel_iommu *iommu, u16 did,
unsigned long pfn, unsigned int pages, int ih, int map)
{
unsigned int mask = ilog2(<API key>(pages));
uint64_t addr = (uint64_t)pfn << VTD_PAGE_SHIFT;
BUG_ON(pages == 0);
if (ih)
ih = 1 << 6;
/*
* Fallback to domain selective flush if no PSI support or the size is
* too big.
* PSI requires page size to be 2 ^ x, and the base address is naturally
* aligned to the size
*/
if (!cap_pgsel_inv(iommu->cap) || mask > cap_max_amask_val(iommu->cap))
iommu->flush.flush_iotlb(iommu, did, 0, 0,
DMA_TLB_DSI_FLUSH);
else
iommu->flush.flush_iotlb(iommu, did, addr | ih, mask,
DMA_TLB_PSI_FLUSH);
/*
* In caching mode, changes of pages from non-present to present require
* flush. However, device IOTLB doesn't need to be flushed in this case.
*/
if (!cap_caching_mode(iommu->cap) || !map)
<API key>(iommu->domains[did], addr, mask);
}
static void <API key>(struct intel_iommu *iommu)
{
u32 pmen;
unsigned long flags;
<API key>(&iommu->register_lock, flags);
pmen = readl(iommu->reg + DMAR_PMEN_REG);
pmen &= ~DMA_PMEN_EPM;
writel(pmen, iommu->reg + DMAR_PMEN_REG);
/* wait for the protected region status bit to clear */
IOMMU_WAIT_OP(iommu, DMAR_PMEN_REG,
readl, !(pmen & DMA_PMEN_PRS), pmen);
<API key>(&iommu->register_lock, flags);
}
static int <API key>(struct intel_iommu *iommu)
{
u32 sts;
unsigned long flags;
<API key>(&iommu->register_lock, flags);
iommu->gcmd |= DMA_GCMD_TE;
writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
/* Make sure hardware complete it */
IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
readl, (sts & DMA_GSTS_TES), sts);
<API key>(&iommu->register_lock, flags);
return 0;
}
static int <API key>(struct intel_iommu *iommu)
{
u32 sts;
unsigned long flag;
<API key>(&iommu->register_lock, flag);
iommu->gcmd &= ~DMA_GCMD_TE;
writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
/* Make sure hardware complete it */
IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
readl, (!(sts & DMA_GSTS_TES)), sts);
<API key>(&iommu->register_lock, flag);
return 0;
}
static int iommu_init_domains(struct intel_iommu *iommu)
{
unsigned long ndomains;
unsigned long nlongs;
ndomains = cap_ndoms(iommu->cap);
pr_debug("IOMMU%d: Number of Domains supported <%ld>\n",
iommu->seq_id, ndomains);
nlongs = BITS_TO_LONGS(ndomains);
spin_lock_init(&iommu->lock);
/* TBD: there might be 64K domains,
* consider other allocation for future chip
*/
iommu->domain_ids = kcalloc(nlongs, sizeof(unsigned long), GFP_KERNEL);
if (!iommu->domain_ids) {
pr_err("IOMMU%d: allocating domain id array failed\n",
iommu->seq_id);
return -ENOMEM;
}
iommu->domains = kcalloc(ndomains, sizeof(struct dmar_domain *),
GFP_KERNEL);
if (!iommu->domains) {
pr_err("IOMMU%d: allocating domain array failed\n",
iommu->seq_id);
kfree(iommu->domain_ids);
iommu->domain_ids = NULL;
return -ENOMEM;
}
/*
* if Caching mode is set, then invalid translations are tagged
* with domainid 0. Hence we need to pre-allocate it.
*/
if (cap_caching_mode(iommu->cap))
set_bit(0, iommu->domain_ids);
return 0;
}
static void free_dmar_iommu(struct intel_iommu *iommu)
{
struct dmar_domain *domain;
int i, count;
unsigned long flags;
if ((iommu->domains) && (iommu->domain_ids)) {
for_each_set_bit(i, iommu->domain_ids, cap_ndoms(iommu->cap)) {
/*
* Domain id 0 is reserved for invalid translation
* if hardware supports caching mode.
*/
if (cap_caching_mode(iommu->cap) && i == 0)
continue;
domain = iommu->domains[i];
clear_bit(i, iommu->domain_ids);
spin_lock_irqsave(&domain->iommu_lock, flags);
count = --domain->iommu_count;
<API key>(&domain->iommu_lock, flags);
if (count == 0)
domain_exit(domain);
}
}
if (iommu->gcmd & DMA_GCMD_TE)
<API key>(iommu);
kfree(iommu->domains);
kfree(iommu->domain_ids);
iommu->domains = NULL;
iommu->domain_ids = NULL;
g_iommus[iommu->seq_id] = NULL;
/* free context mapping */
free_context_table(iommu);
}
static struct dmar_domain *alloc_domain(bool vm)
{
/* domain id for virtual machine, it won't be set in context */
static atomic_t vm_domid = ATOMIC_INIT(0);
struct dmar_domain *domain;
domain = alloc_domain_mem();
if (!domain)
return NULL;
domain->nid = -1;
domain->iommu_count = 0;
memset(domain->iommu_bmp, 0, sizeof(domain->iommu_bmp));
domain->flags = 0;
spin_lock_init(&domain->iommu_lock);
INIT_LIST_HEAD(&domain->devices);
if (vm) {
domain->id = atomic_inc_return(&vm_domid);
domain->flags = <API key>;
}
return domain;
}
static int iommu_attach_domain(struct dmar_domain *domain,
struct intel_iommu *iommu)
{
int num;
unsigned long ndomains;
unsigned long flags;
ndomains = cap_ndoms(iommu->cap);
spin_lock_irqsave(&iommu->lock, flags);
num = find_first_zero_bit(iommu->domain_ids, ndomains);
if (num >= ndomains) {
<API key>(&iommu->lock, flags);
printk(KERN_ERR "IOMMU: no free domain ids\n");
return -ENOMEM;
}
domain->id = num;
domain->iommu_count++;
set_bit(num, iommu->domain_ids);
set_bit(iommu->seq_id, domain->iommu_bmp);
iommu->domains[num] = domain;
<API key>(&iommu->lock, flags);
return 0;
}
static void iommu_detach_domain(struct dmar_domain *domain,
struct intel_iommu *iommu)
{
unsigned long flags;
int num, ndomains;
spin_lock_irqsave(&iommu->lock, flags);
ndomains = cap_ndoms(iommu->cap);
for_each_set_bit(num, iommu->domain_ids, ndomains) {
if (iommu->domains[num] == domain) {
clear_bit(num, iommu->domain_ids);
iommu->domains[num] = NULL;
break;
}
}
<API key>(&iommu->lock, flags);
}
static struct iova_domain reserved_iova_list;
static struct lock_class_key reserved_rbtree_key;
static int <API key>(void)
{
struct pci_dev *pdev = NULL;
struct iova *iova;
int i;
init_iova_domain(&reserved_iova_list, DMA_32BIT_PFN);
lockdep_set_class(&reserved_iova_list.iova_rbtree_lock,
&reserved_rbtree_key);
/* IOAPIC ranges shouldn't be accessed by DMA */
iova = reserve_iova(&reserved_iova_list, IOVA_PFN(IOAPIC_RANGE_START),
IOVA_PFN(IOAPIC_RANGE_END));
if (!iova) {
printk(KERN_ERR "Reserve IOAPIC range failed\n");
return -ENODEV;
}
/* Reserve all PCI MMIO to avoid peer-to-peer access */
for_each_pci_dev(pdev) {
struct resource *r;
for (i = 0; i < PCI_NUM_RESOURCES; i++) {
r = &pdev->resource[i];
if (!r->flags || !(r->flags & IORESOURCE_MEM))
continue;
iova = reserve_iova(&reserved_iova_list,
IOVA_PFN(r->start),
IOVA_PFN(r->end));
if (!iova) {
printk(KERN_ERR "Reserve iova failed\n");
return -ENODEV;
}
}
}
return 0;
}
static void <API key>(struct dmar_domain *domain)
{
copy_reserved_iova(&reserved_iova_list, &domain->iovad);
}
static inline int <API key>(int gaw)
{
int agaw;
int r = (gaw - 12) % 9;
if (r == 0)
agaw = gaw;
else
agaw = gaw + 9 - r;
if (agaw > 64)
agaw = 64;
return agaw;
}
static int domain_init(struct dmar_domain *domain, int guest_width)
{
struct intel_iommu *iommu;
int adjust_width, agaw;
unsigned long sagaw;
init_iova_domain(&domain->iovad, DMA_32BIT_PFN);
<API key>(domain);
/* calculate AGAW */
iommu = domain_get_iommu(domain);
if (guest_width > cap_mgaw(iommu->cap))
guest_width = cap_mgaw(iommu->cap);
domain->gaw = guest_width;
adjust_width = <API key>(guest_width);
agaw = width_to_agaw(adjust_width);
sagaw = cap_sagaw(iommu->cap);
if (!test_bit(agaw, &sagaw)) {
/* hardware doesn't support it, choose a bigger one */
pr_debug("IOMMU: hardware doesn't support agaw %d\n", agaw);
agaw = find_next_bit(&sagaw, 5, agaw);
if (agaw >= 5)
return -ENODEV;
}
domain->agaw = agaw;
if (ecap_coherent(iommu->ecap))
domain->iommu_coherency = 1;
else
domain->iommu_coherency = 0;
if (ecap_sc_support(iommu->ecap))
domain->iommu_snooping = 1;
else
domain->iommu_snooping = 0;
if (<API key>)
domain->iommu_superpage = fls(cap_super_page_val(iommu->cap));
else
domain->iommu_superpage = 0;
domain->nid = iommu->node;
/* always allocate the top pgd */
domain->pgd = (struct dma_pte *)alloc_pgtable_page(domain->nid);
if (!domain->pgd)
return -ENOMEM;
__iommu_flush_cache(iommu, domain->pgd, PAGE_SIZE);
return 0;
}
static void domain_exit(struct dmar_domain *domain)
{
struct dmar_drhd_unit *drhd;
struct intel_iommu *iommu;
struct page *freelist = NULL;
/* Domain 0 is reserved, so dont process it */
if (!domain)
return;
/* Flush any lazy unmaps that may reference this domain */
if (!intel_iommu_strict)
<API key>(0);
/* remove associated devices */
<API key>(domain);
/* destroy iovas */
put_iova_domain(&domain->iovad);
freelist = domain_unmap(domain, 0, DOMAIN_MAX_PFN(domain->gaw));
/* clear attached or cached domains */
rcu_read_lock();
<API key>(iommu, drhd)
if (domain->flags & <API key> ||
test_bit(iommu->seq_id, domain->iommu_bmp))
iommu_detach_domain(domain, iommu);
rcu_read_unlock();
dma_free_pagelist(freelist);
free_domain_mem(domain);
}
static int <API key>(struct dmar_domain *domain,
struct intel_iommu *iommu,
u8 bus, u8 devfn, int translation)
{
struct context_entry *context;
unsigned long flags;
struct dma_pte *pgd;
unsigned long num;
unsigned long ndomains;
int id;
int agaw;
struct device_domain_info *info = NULL;
pr_debug("Set context mapping for %02x:%02x.%d\n",
bus, PCI_SLOT(devfn), PCI_FUNC(devfn));
BUG_ON(!domain->pgd);
BUG_ON(translation != <API key> &&
translation != <API key>);
context = <API key>(iommu, bus, devfn);
if (!context)
return -ENOMEM;
spin_lock_irqsave(&iommu->lock, flags);
if (context_present(context)) {
<API key>(&iommu->lock, flags);
return 0;
}
id = domain->id;
pgd = domain->pgd;
if (domain->flags & <API key> ||
domain->flags & <API key>) {
int found = 0;
/* find an available domain id for this device in iommu */
ndomains = cap_ndoms(iommu->cap);
for_each_set_bit(num, iommu->domain_ids, ndomains) {
if (iommu->domains[num] == domain) {
id = num;
found = 1;
break;
}
}
if (found == 0) {
num = find_first_zero_bit(iommu->domain_ids, ndomains);
if (num >= ndomains) {
<API key>(&iommu->lock, flags);
printk(KERN_ERR "IOMMU: no free domain ids\n");
return -EFAULT;
}
set_bit(num, iommu->domain_ids);
iommu->domains[num] = domain;
id = num;
}
/* Skip top levels of page tables for
* iommu which has less agaw than default.
* Unnecessary for PT mode.
*/
if (translation != <API key>) {
for (agaw = domain->agaw; agaw != iommu->agaw; agaw
pgd = phys_to_virt(dma_pte_addr(pgd));
if (!dma_pte_present(pgd)) {
<API key>(&iommu->lock, flags);
return -ENOMEM;
}
}
}
}
<API key>(context, id);
if (translation != <API key>) {
info = <API key>(domain, iommu, bus, devfn);
translation = info ? <API key> :
<API key>;
}
/*
* In pass through mode, AW must be programmed to indicate the largest
* AGAW value supported by hardware. And ASR is ignored by hardware.
*/
if (unlikely(translation == <API key>))
<API key>(context, iommu->msagaw);
else {
<API key>(context, virt_to_phys(pgd));
<API key>(context, iommu->agaw);
}
<API key>(context, translation);
<API key>(context);
context_set_present(context);
domain_flush_cache(domain, context, sizeof(*context));
/*
* It's a non-present to present mapping. If hardware doesn't cache
* non-present entry we only need to flush the write-buffer. If the
* _does_ cache non-present entries, then it does so in the special
* domain #0, which we have to flush:
*/
if (cap_caching_mode(iommu->cap)) {
iommu->flush.flush_context(iommu, 0,
(((u16)bus) << 8) | devfn,
DMA_CCMD_MASK_NOBIT,
<API key>);
iommu->flush.flush_iotlb(iommu, domain->id, 0, 0, DMA_TLB_DSI_FLUSH);
} else {
<API key>(iommu);
}
<API key>(info);
<API key>(&iommu->lock, flags);
spin_lock_irqsave(&domain->iommu_lock, flags);
if (!test_and_set_bit(iommu->seq_id, domain->iommu_bmp)) {
domain->iommu_count++;
if (domain->iommu_count == 1)
domain->nid = iommu->node;
<API key>(domain);
}
<API key>(&domain->iommu_lock, flags);
return 0;
}
static int
<API key>(struct dmar_domain *domain, struct device *dev,
int translation)
{
int ret;
struct pci_dev *pdev, *tmp, *parent;
struct intel_iommu *iommu;
u8 bus, devfn;
iommu = device_to_iommu(dev, &bus, &devfn);
if (!iommu)
return -ENODEV;
ret = <API key>(domain, iommu, bus, devfn,
translation);
if (ret || !dev_is_pci(dev))
return ret;
/* dependent device mapping */
pdev = to_pci_dev(dev);
tmp = <API key>(pdev);
if (!tmp)
return 0;
/* Secondary interface's bus number and devfn 0 */
parent = pdev->bus->self;
while (parent != tmp) {
ret = <API key>(domain, iommu,
parent->bus->number,
parent->devfn, translation);
if (ret)
return ret;
parent = parent->bus->self;
}
if (pci_is_pcie(tmp)) /* this is a PCIe-to-PCI bridge */
return <API key>(domain, iommu,
tmp->subordinate->number, 0,
translation);
else /* this is a legacy PCI bridge */
return <API key>(domain, iommu,
tmp->bus->number,
tmp->devfn,
translation);
}
static int <API key>(struct device *dev)
{
int ret;
struct pci_dev *pdev, *tmp, *parent;
struct intel_iommu *iommu;
u8 bus, devfn;
iommu = device_to_iommu(dev, &bus, &devfn);
if (!iommu)
return -ENODEV;
ret = <API key>(iommu, bus, devfn);
if (!ret || !dev_is_pci(dev))
return ret;
/* dependent device mapping */
pdev = to_pci_dev(dev);
tmp = <API key>(pdev);
if (!tmp)
return ret;
/* Secondary interface's bus number and devfn 0 */
parent = pdev->bus->self;
while (parent != tmp) {
ret = <API key>(iommu, parent->bus->number,
parent->devfn);
if (!ret)
return ret;
parent = parent->bus->self;
}
if (pci_is_pcie(tmp))
return <API key>(iommu, tmp->subordinate->number,
0);
else
return <API key>(iommu, tmp->bus->number,
tmp->devfn);
}
/* Returns a number of VTD pages, but aligned to MM page size */
static inline unsigned long aligned_nrpages(unsigned long host_addr,
size_t size)
{
host_addr &= ~PAGE_MASK;
return PAGE_ALIGN(host_addr + size) >> VTD_PAGE_SHIFT;
}
/* Return largest possible superpage level for a given mapping */
static inline int <API key>(struct dmar_domain *domain,
unsigned long iov_pfn,
unsigned long phy_pfn,
unsigned long pages)
{
int support, level = 1;
unsigned long pfnmerge;
support = domain->iommu_superpage;
/* To use a large page, the virtual *and* physical addresses
must be aligned to 2MiB/1GiB/etc. Lower bits set in either
of them will mean we have to use smaller pages. So just
merge them and check both at once. */
pfnmerge = iov_pfn | phy_pfn;
while (support && !(pfnmerge & ~VTD_STRIDE_MASK)) {
pages >>= VTD_STRIDE_SHIFT;
if (!pages)
break;
pfnmerge >>= VTD_STRIDE_SHIFT;
level++;
support
}
return level;
}
static int __domain_mapping(struct dmar_domain *domain, unsigned long iov_pfn,
struct scatterlist *sg, unsigned long phys_pfn,
unsigned long nr_pages, int prot)
{
struct dma_pte *first_pte = NULL, *pte = NULL;
phys_addr_t uninitialized_var(pteval);
int addr_width = agaw_to_width(domain->agaw) - VTD_PAGE_SHIFT;
unsigned long sg_res;
unsigned int largepage_lvl = 0;
unsigned long lvl_pages = 0;
BUG_ON(addr_width < BITS_PER_LONG && (iov_pfn + nr_pages - 1) >> addr_width);
if ((prot & (DMA_PTE_READ|DMA_PTE_WRITE)) == 0)
return -EINVAL;
prot &= DMA_PTE_READ | DMA_PTE_WRITE | DMA_PTE_SNP;
if (sg)
sg_res = 0;
else {
sg_res = nr_pages + 1;
pteval = ((phys_addr_t)phys_pfn << VTD_PAGE_SHIFT) | prot;
}
while (nr_pages > 0) {
uint64_t tmp;
if (!sg_res) {
sg_res = aligned_nrpages(sg->offset, sg->length);
sg->dma_address = ((dma_addr_t)iov_pfn << VTD_PAGE_SHIFT) + sg->offset;
sg->dma_length = sg->length;
pteval = page_to_phys(sg_page(sg)) | prot;
phys_pfn = pteval >> VTD_PAGE_SHIFT;
}
if (!pte) {
largepage_lvl = <API key>(domain, iov_pfn, phys_pfn, sg_res);
first_pte = pte = pfn_to_dma_pte(domain, iov_pfn, &largepage_lvl);
if (!pte)
return -ENOMEM;
/* It is large page*/
if (largepage_lvl > 1) {
pteval |= DMA_PTE_LARGE_PAGE;
/* Ensure that old small page tables are removed to make room
for superpage, if they exist. */
dma_pte_clear_range(domain, iov_pfn,
iov_pfn + lvl_to_nr_pages(largepage_lvl) - 1);
<API key>(domain, iov_pfn,
iov_pfn + lvl_to_nr_pages(largepage_lvl) - 1);
} else {
pteval &= ~(uint64_t)DMA_PTE_LARGE_PAGE;
}
}
/* We don't need lock here, nobody else
* touches the iova range
*/
tmp = cmpxchg64_local(&pte->val, 0ULL, pteval);
if (tmp) {
static int dumps = 5;
printk(KERN_CRIT "ERROR: DMA PTE for vPFN 0x%lx already set (to %llx not %llx)\n",
iov_pfn, tmp, (unsigned long long)pteval);
if (dumps) {
dumps
<API key>(NULL);
}
WARN_ON(1);
}
lvl_pages = lvl_to_nr_pages(largepage_lvl);
BUG_ON(nr_pages < lvl_pages);
BUG_ON(sg_res < lvl_pages);
nr_pages -= lvl_pages;
iov_pfn += lvl_pages;
phys_pfn += lvl_pages;
pteval += lvl_pages * VTD_PAGE_SIZE;
sg_res -= lvl_pages;
/* If the next PTE would be the first in a new page, then we
need to flush the cache on the entries we've just written.
And then we'll need to recalculate 'pte', so clear it and
let it get set again in the if (!pte) block above.
If we're done (!nr_pages) we need to flush the cache too.
Also if we've been setting superpages, we may need to
recalculate 'pte' and switch back to smaller pages for the
end of the mapping, if the trailing size is not enough to
use another superpage (i.e. sg_res < lvl_pages). */
pte++;
if (!nr_pages || first_pte_in_page(pte) ||
(largepage_lvl > 1 && sg_res < lvl_pages)) {
domain_flush_cache(domain, first_pte,
(void *)pte - (void *)first_pte);
pte = NULL;
}
if (!sg_res && nr_pages)
sg = sg_next(sg);
}
return 0;
}
static inline int domain_sg_mapping(struct dmar_domain *domain, unsigned long iov_pfn,
struct scatterlist *sg, unsigned long nr_pages,
int prot)
{
return __domain_mapping(domain, iov_pfn, sg, 0, nr_pages, prot);
}
static inline int domain_pfn_mapping(struct dmar_domain *domain, unsigned long iov_pfn,
unsigned long phys_pfn, unsigned long nr_pages,
int prot)
{
return __domain_mapping(domain, iov_pfn, NULL, phys_pfn, nr_pages, prot);
}
static void iommu_detach_dev(struct intel_iommu *iommu, u8 bus, u8 devfn)
{
if (!iommu)
return;
clear_context_table(iommu, bus, devfn);
iommu->flush.flush_context(iommu, 0, 0, 0,
<API key>);
iommu->flush.flush_iotlb(iommu, 0, 0, 0, <API key>);
}
static inline void unlink_domain_info(struct device_domain_info *info)
{
assert_spin_locked(&device_domain_lock);
list_del(&info->link);
list_del(&info->global);
if (info->dev)
info->dev->archdata.iommu = NULL;
}
static void <API key>(struct dmar_domain *domain)
{
struct device_domain_info *info;
unsigned long flags, flags2;
spin_lock_irqsave(&device_domain_lock, flags);
while (!list_empty(&domain->devices)) {
info = list_entry(domain->devices.next,
struct device_domain_info, link);
unlink_domain_info(info);
<API key>(&device_domain_lock, flags);
<API key>(info);
iommu_detach_dev(info->iommu, info->bus, info->devfn);
if (domain->flags & <API key>) {
<API key>(info->iommu, info->dev);
/* clear this iommu in iommu_bmp, update iommu count
* and capabilities
*/
spin_lock_irqsave(&domain->iommu_lock, flags2);
if (test_and_clear_bit(info->iommu->seq_id,
domain->iommu_bmp)) {
domain->iommu_count
<API key>(domain);
}
<API key>(&domain->iommu_lock, flags2);
}
free_devinfo_mem(info);
spin_lock_irqsave(&device_domain_lock, flags);
}
<API key>(&device_domain_lock, flags);
}
/*
* find_domain
* Note: we use struct device->archdata.iommu stores the info
*/
static struct dmar_domain *find_domain(struct device *dev)
{
struct device_domain_info *info;
/* No lock here, assumes no domain exit in normal case */
info = dev->archdata.iommu;
if (info)
return info->domain;
return NULL;
}
static inline struct device_domain_info *
<API key>(int segment, int bus, int devfn)
{
struct device_domain_info *info;
list_for_each_entry(info, &device_domain_list, global)
if (info->iommu->segment == segment && info->bus == bus &&
info->devfn == devfn)
return info;
return NULL;
}
static struct dmar_domain *<API key>(struct intel_iommu *iommu,
int bus, int devfn,
struct device *dev,
struct dmar_domain *domain)
{
struct dmar_domain *found = NULL;
struct device_domain_info *info;
unsigned long flags;
info = alloc_devinfo_mem();
if (!info)
return NULL;
info->bus = bus;
info->devfn = devfn;
info->dev = dev;
info->domain = domain;
info->iommu = iommu;
if (!dev)
domain->flags |= <API key>;
spin_lock_irqsave(&device_domain_lock, flags);
if (dev)
found = find_domain(dev);
else {
struct device_domain_info *info2;
info2 = <API key>(iommu->segment, bus, devfn);
if (info2)
found = info2->domain;
}
if (found) {
<API key>(&device_domain_lock, flags);
free_devinfo_mem(info);
/* Caller must free the original domain */
return found;
}
list_add(&info->link, &domain->devices);
list_add(&info->global, &device_domain_list);
if (dev)
dev->archdata.iommu = info;
<API key>(&device_domain_lock, flags);
return domain;
}
/* domain is initialized */
static struct dmar_domain *get_domain_for_dev(struct device *dev, int gaw)
{
struct dmar_domain *domain, *free = NULL;
struct intel_iommu *iommu = NULL;
struct device_domain_info *info;
struct pci_dev *dev_tmp = NULL;
unsigned long flags;
u8 bus, devfn, bridge_bus, bridge_devfn;
domain = find_domain(dev);
if (domain)
return domain;
if (dev_is_pci(dev)) {
struct pci_dev *pdev = to_pci_dev(dev);
u16 segment;
segment = pci_domain_nr(pdev->bus);
dev_tmp = <API key>(pdev);
if (dev_tmp) {
if (pci_is_pcie(dev_tmp)) {
bridge_bus = dev_tmp->subordinate->number;
bridge_devfn = 0;
} else {
bridge_bus = dev_tmp->bus->number;
bridge_devfn = dev_tmp->devfn;
}
spin_lock_irqsave(&device_domain_lock, flags);
info = <API key>(segment,
bridge_bus,
bridge_devfn);
if (info) {
iommu = info->iommu;
domain = info->domain;
}
<API key>(&device_domain_lock, flags);
/* pcie-pci bridge already has a domain, uses it */
if (info)
goto found_domain;
}
}
iommu = device_to_iommu(dev, &bus, &devfn);
if (!iommu)
goto error;
/* Allocate and initialize new domain for the device */
domain = alloc_domain(false);
if (!domain)
goto error;
if (iommu_attach_domain(domain, iommu)) {
free_domain_mem(domain);
domain = NULL;
goto error;
}
free = domain;
if (domain_init(domain, gaw))
goto error;
/* register pcie-to-pci device */
if (dev_tmp) {
domain = <API key>(iommu, bridge_bus, bridge_devfn,
NULL, domain);
if (!domain)
goto error;
}
found_domain:
domain = <API key>(iommu, bus, devfn, dev, domain);
error:
if (free != domain)
domain_exit(free);
return domain;
}
static int <API key>;
#define IDENTMAP_ALL 1
#define IDENTMAP_GFX 2
#define IDENTMAP_AZALIA 4
static int <API key>(struct dmar_domain *domain,
unsigned long long start,
unsigned long long end)
{
unsigned long first_vpfn = start >> VTD_PAGE_SHIFT;
unsigned long last_vpfn = end >> VTD_PAGE_SHIFT;
if (!reserve_iova(&domain->iovad, dma_to_mm_pfn(first_vpfn),
dma_to_mm_pfn(last_vpfn))) {
printk(KERN_ERR "IOMMU: reserve iova failed\n");
return -ENOMEM;
}
pr_debug("Mapping reserved region %llx-%llx for domain %d\n",
start, end, domain->id);
/*
* RMRR range might have overlap with physical memory range,
* clear it first
*/
dma_pte_clear_range(domain, first_vpfn, last_vpfn);
return domain_pfn_mapping(domain, first_vpfn, first_vpfn,
last_vpfn - first_vpfn + 1,
DMA_PTE_READ|DMA_PTE_WRITE);
}
static int <API key>(struct device *dev,
unsigned long long start,
unsigned long long end)
{
struct dmar_domain *domain;
int ret;
domain = get_domain_for_dev(dev, <API key>);
if (!domain)
return -ENOMEM;
/* For _hardware_ passthrough, don't bother. But for software
passthrough, we do it anyway -- it may indicate a memory
range which is reserved in E820, so which didn't get set
up to start with in si_domain */
if (domain == si_domain && hw_pass_through) {
printk("Ignoring identity map for HW passthrough device %s [0x%Lx - 0x%Lx]\n",
dev_name(dev), start, end);
return 0;
}
printk(KERN_INFO
"IOMMU: Setting identity map for device %s [0x%Lx - 0x%Lx]\n",
dev_name(dev), start, end);
if (end < start) {
WARN(1, "Your BIOS is broken; RMRR ends before it starts!\n"
"BIOS vendor: %s; Ver: %s; Product Version: %s\n",
dmi_get_system_info(DMI_BIOS_VENDOR),
dmi_get_system_info(DMI_BIOS_VERSION),
dmi_get_system_info(DMI_PRODUCT_VERSION));
ret = -EIO;
goto error;
}
if (end >> agaw_to_width(domain->agaw)) {
WARN(1, "Your BIOS is broken; RMRR exceeds permitted address width (%d bits)\n"
"BIOS vendor: %s; Ver: %s; Product Version: %s\n",
agaw_to_width(domain->agaw),
dmi_get_system_info(DMI_BIOS_VENDOR),
dmi_get_system_info(DMI_BIOS_VERSION),
dmi_get_system_info(DMI_PRODUCT_VERSION));
ret = -EIO;
goto error;
}
ret = <API key>(domain, start, end);
if (ret)
goto error;
/* context entry init */
ret = <API key>(domain, dev, <API key>);
if (ret)
goto error;
return 0;
error:
domain_exit(domain);
return ret;
}
static inline int <API key>(struct dmar_rmrr_unit *rmrr,
struct device *dev)
{
if (dev->archdata.iommu == <API key>)
return 0;
return <API key>(dev, rmrr->base_address,
rmrr->end_address);
}
#ifdef <API key>
static inline void iommu_prepare_isa(void)
{
struct pci_dev *pdev;
int ret;
pdev = pci_get_class(<API key> << 8, NULL);
if (!pdev)
return;
printk(KERN_INFO "IOMMU: Prepare 0-16MiB unity mapping for LPC\n");
ret = <API key>(&pdev->dev, 0, 16*1024*1024 - 1);
if (ret)
printk(KERN_ERR "IOMMU: Failed to create 0-16MiB identity map; "
"floppy might not work\n");
}
#else
static inline void iommu_prepare_isa(void)
{
return;
}
#endif /* !<API key> */
static int md_domain_init(struct dmar_domain *domain, int guest_width);
static int __init si_domain_init(int hw)
{
struct dmar_drhd_unit *drhd;
struct intel_iommu *iommu;
int nid, ret = 0;
si_domain = alloc_domain(false);
if (!si_domain)
return -EFAULT;
si_domain->flags = <API key>;
<API key>(iommu, drhd) {
ret = iommu_attach_domain(si_domain, iommu);
if (ret) {
domain_exit(si_domain);
return -EFAULT;
}
}
if (md_domain_init(si_domain, <API key>)) {
domain_exit(si_domain);
return -EFAULT;
}
pr_debug("IOMMU: identity mapping domain is domain %d\n",
si_domain->id);
if (hw)
return 0;
<API key>(nid) {
unsigned long start_pfn, end_pfn;
int i;
<API key>(i, nid, &start_pfn, &end_pfn, NULL) {
ret = <API key>(si_domain,
PFN_PHYS(start_pfn), PFN_PHYS(end_pfn));
if (ret)
return ret;
}
}
return 0;
}
static int identity_mapping(struct device *dev)
{
struct device_domain_info *info;
if (likely(!<API key>))
return 0;
info = dev->archdata.iommu;
if (info && info != <API key>)
return (info->domain == si_domain);
return 0;
}
static int domain_add_dev_info(struct dmar_domain *domain,
struct device *dev, int translation)
{
struct dmar_domain *ndomain;
struct intel_iommu *iommu;
u8 bus, devfn;
int ret;
iommu = device_to_iommu(dev, &bus, &devfn);
if (!iommu)
return -ENODEV;
ndomain = <API key>(iommu, bus, devfn, dev, domain);
if (ndomain != domain)
return -EBUSY;
ret = <API key>(domain, dev, translation);
if (ret) {
<API key>(domain, dev);
return ret;
}
return 0;
}
static bool device_has_rmrr(struct device *dev)
{
struct dmar_rmrr_unit *rmrr;
struct device *tmp;
int i;
rcu_read_lock();
for_each_rmrr_units(rmrr) {
/*
* Return TRUE if this RMRR contains the device that
* is passed in.
*/
<API key>(rmrr->devices,
rmrr->devices_cnt, i, tmp)
if (tmp == dev) {
rcu_read_unlock();
return true;
}
}
rcu_read_unlock();
return false;
}
static int <API key>(struct device *dev, int startup)
{
if (dev_is_pci(dev)) {
struct pci_dev *pdev = to_pci_dev(dev);
/*
* We want to prevent any device associated with an RMRR from
* getting placed into the SI Domain. This is done because
* problems exist when devices are moved in and out of domains
* and their respective RMRR info is lost. We exempt USB devices
* from this process due to their usage of RMRRs that are known
* to not be needed after BIOS hand-off to OS.
*/
if (device_has_rmrr(dev) &&
(pdev->class >> 8) != <API key>)
return 0;
if ((<API key> & IDENTMAP_AZALIA) && IS_AZALIA(pdev))
return 1;
if ((<API key> & IDENTMAP_GFX) && IS_GFX_DEVICE(pdev))
return 1;
if (!(<API key> & IDENTMAP_ALL))
return 0;
/*
* We want to start off with all devices in the 1:1 domain, and
* take them out later if we find they can't access all of memory.
*
* However, we can't do this for PCI devices behind bridges,
* because all PCI devices behind the same bridge will end up
* with the same source-id on their transactions.
*
* Practically speaking, we can't change things around for these
* devices at run-time, because we can't be sure there'll be no
* DMA transactions in flight for any of their siblings.
*
* So PCI devices (unless they're on the root bus) as well as
* their parent PCI-PCI or PCIe-PCI bridges must be left _out_ of
* the 1:1 domain, just in _case_ one of their siblings turns out
* not to be able to map all of memory.
*/
if (!pci_is_pcie(pdev)) {
if (!pci_is_root_bus(pdev->bus))
return 0;
if (pdev->class >> 8 == <API key>)
return 0;
} else if (pci_pcie_type(pdev) == <API key>)
return 0;
} else {
if (device_has_rmrr(dev))
return 0;
}
if (!startup) {
/*
* If the device's dma_mask is less than the system's memory
* size then this is not a candidate for identity mapping.
*/
u64 dma_mask = *dev->dma_mask;
if (dev->coherent_dma_mask &&
dev->coherent_dma_mask < dma_mask)
dma_mask = dev->coherent_dma_mask;
return dma_mask >= <API key>(dev);
}
return 1;
}
static int __init <API key>(struct device *dev, int hw)
{
int ret;
if (!<API key>(dev, 1))
return 0;
ret = domain_add_dev_info(si_domain, dev,
hw ? <API key> :
<API key>);
if (!ret)
pr_info("IOMMU: %s identity mapping for device %s\n",
hw ? "hardware" : "software", dev_name(dev));
else if (ret == -ENODEV)
/* device not associated with an iommu */
ret = 0;
return ret;
}
static int __init <API key>(int hw)
{
struct pci_dev *pdev = NULL;
struct dmar_drhd_unit *drhd;
struct intel_iommu *iommu;
struct device *dev;
int i;
int ret = 0;
ret = si_domain_init(hw);
if (ret)
return -EFAULT;
for_each_pci_dev(pdev) {
ret = <API key>(&pdev->dev, hw);
if (ret)
return ret;
}
<API key>(iommu, drhd)
<API key>(drhd->devices, drhd->devices_cnt, i, dev) {
struct <API key> *pn;
struct acpi_device *adev;
if (dev->bus != &acpi_bus_type)
continue;
adev= to_acpi_device(dev);
mutex_lock(&adev->physical_node_lock);
list_for_each_entry(pn, &adev->physical_node_list, node) {
ret = <API key>(pn->dev, hw);
if (ret)
break;
}
mutex_unlock(&adev->physical_node_lock);
if (ret)
return ret;
}
return 0;
}
static int __init init_dmars(void)
{
struct dmar_drhd_unit *drhd;
struct dmar_rmrr_unit *rmrr;
struct device *dev;
struct intel_iommu *iommu;
int i, ret;
/*
* for each drhd
* allocate root
* initialize and program root entry to not present
* endfor
*/
for_each_drhd_unit(drhd) {
/*
* lock not needed as this is only incremented in the single
* threaded kernel __init code path all other access are read
* only
*/
if (g_num_of_iommus < <API key>) {
g_num_of_iommus++;
continue;
}
printk_once(KERN_ERR "intel-iommu: exceeded %d IOMMUs\n",
<API key>);
}
g_iommus = kcalloc(g_num_of_iommus, sizeof(struct intel_iommu *),
GFP_KERNEL);
if (!g_iommus) {
printk(KERN_ERR "Allocating global iommu array failed\n");
ret = -ENOMEM;
goto error;
}
deferred_flush = kzalloc(g_num_of_iommus *
sizeof(struct <API key>), GFP_KERNEL);
if (!deferred_flush) {
ret = -ENOMEM;
goto free_g_iommus;
}
<API key>(iommu, drhd) {
g_iommus[iommu->seq_id] = iommu;
ret = iommu_init_domains(iommu);
if (ret)
goto free_iommu;
/*
* TBD:
* we could share the same root & context tables
* among all IOMMU's. Need to Split it later.
*/
ret = <API key>(iommu);
if (ret) {
printk(KERN_ERR "IOMMU: allocate root entry failed\n");
goto free_iommu;
}
if (!ecap_pass_through(iommu->ecap))
hw_pass_through = 0;
}
/*
* Start from the sane iommu hardware state.
*/
<API key>(iommu, drhd) {
/*
* If the queued invalidation is already initialized by us
* (for example, while enabling interrupt-remapping) then
* we got the things already rolling from a sane state.
*/
if (iommu->qi)
continue;
/*
* Clear any previous faults.
*/
dmar_fault(-1, iommu);
/*
* Disable queued invalidation if supported and already enabled
* before OS handover.
*/
dmar_disable_qi(iommu);
}
<API key>(iommu, drhd) {
if (dmar_enable_qi(iommu)) {
/*
* Queued Invalidate not enabled, use Register Based
* Invalidate
*/
iommu->flush.flush_context = <API key>;
iommu->flush.flush_iotlb = __iommu_flush_iotlb;
printk(KERN_INFO "IOMMU %d 0x%Lx: using Register based "
"invalidation\n",
iommu->seq_id,
(unsigned long long)drhd->reg_base_addr);
} else {
iommu->flush.flush_context = qi_flush_context;
iommu->flush.flush_iotlb = qi_flush_iotlb;
printk(KERN_INFO "IOMMU %d 0x%Lx: using Queued "
"invalidation\n",
iommu->seq_id,
(unsigned long long)drhd->reg_base_addr);
}
}
if (iommu_pass_through)
<API key> |= IDENTMAP_ALL;
#ifdef <API key>
<API key> |= IDENTMAP_GFX;
#endif
<API key>();
/*
* If pass through is not set or not enabled, setup context entries for
* identity mappings for rmrr, gfx, and isa and may fall back to static
* identity mapping if <API key> is set.
*/
if (<API key>) {
ret = <API key>(hw_pass_through);
if (ret) {
printk(KERN_CRIT "Failed to setup IOMMU pass-through\n");
goto free_iommu;
}
}
/*
* For each rmrr
* for each dev attached to rmrr
* do
* locate drhd for dev, alloc domain for dev
* allocate free domain
* allocate page table entries for rmrr
* if context not allocated for bus
* allocate and init context
* set present in root table for this bus
* init context with domain, translation etc
* endfor
* endfor
*/
printk(KERN_INFO "IOMMU: Setting RMRR:\n");
for_each_rmrr_units(rmrr) {
/* some BIOS lists non-exist devices in DMAR table. */
<API key>(rmrr->devices, rmrr->devices_cnt,
i, dev) {
ret = <API key>(rmrr, dev);
if (ret)
printk(KERN_ERR
"IOMMU: mapping reserved region failed\n");
}
}
iommu_prepare_isa();
/*
* for each drhd
* enable fault log
* global invalidate context cache
* global invalidate iotlb
* enable translation
*/
for_each_iommu(iommu, drhd) {
if (drhd->ignored) {
/*
* we always have to disable PMRs or DMA may fail on
* this device
*/
if (force_on)
<API key>(iommu);
continue;
}
<API key>(iommu);
ret = dmar_set_interrupt(iommu);
if (ret)
goto free_iommu;
<API key>(iommu);
iommu->flush.flush_context(iommu, 0, 0, 0, <API key>);
iommu->flush.flush_iotlb(iommu, 0, 0, 0, <API key>);
ret = <API key>(iommu);
if (ret)
goto free_iommu;
<API key>(iommu);
}
return 0;
free_iommu:
<API key>(iommu, drhd)
free_dmar_iommu(iommu);
kfree(deferred_flush);
free_g_iommus:
kfree(g_iommus);
error:
return ret;
}
/* This takes a number of _MM_ pages, not VTD pages */
static struct iova *intel_alloc_iova(struct device *dev,
struct dmar_domain *domain,
unsigned long nrpages, uint64_t dma_mask)
{
struct iova *iova = NULL;
/* Restrict dma_mask to the width that the iommu can handle */
dma_mask = min_t(uint64_t, DOMAIN_MAX_ADDR(domain->gaw), dma_mask);
if (!dmar_forcedac && dma_mask > DMA_BIT_MASK(32)) {
/*
* First try to allocate an io virtual address in
* DMA_BIT_MASK(32) and if that fails then try allocating
* from higher range
*/
iova = alloc_iova(&domain->iovad, nrpages,
IOVA_PFN(DMA_BIT_MASK(32)), 1);
if (iova)
return iova;
}
iova = alloc_iova(&domain->iovad, nrpages, IOVA_PFN(dma_mask), 1);
if (unlikely(!iova)) {
printk(KERN_ERR "Allocating %ld-page iova for %s failed",
nrpages, dev_name(dev));
return NULL;
}
return iova;
}
static struct dmar_domain *<API key>(struct device *dev)
{
struct dmar_domain *domain;
int ret;
domain = get_domain_for_dev(dev, <API key>);
if (!domain) {
printk(KERN_ERR "Allocating domain for %s failed",
dev_name(dev));
return NULL;
}
/* make sure context mapping is ok */
if (unlikely(!<API key>(dev))) {
ret = <API key>(domain, dev, <API key>);
if (ret) {
printk(KERN_ERR "Domain context map for %s failed",
dev_name(dev));
return NULL;
}
}
return domain;
}
static inline struct dmar_domain *<API key>(struct device *dev)
{
struct device_domain_info *info;
/* No lock here, assumes no domain exit in normal case */
info = dev->archdata.iommu;
if (likely(info))
return info->domain;
return <API key>(dev);
}
static int iommu_dummy(struct device *dev)
{
return dev->archdata.iommu == <API key>;
}
/* Check if the dev needs to go through non-identity map and unmap process.*/
static int iommu_no_mapping(struct device *dev)
{
int found;
if (iommu_dummy(dev))
return 1;
if (!<API key>)
return 0;
found = identity_mapping(dev);
if (found) {
if (<API key>(dev, 0))
return 1;
else {
/*
* 32 bit DMA is removed from si_domain and fall back
* to non-identity mapping.
*/
<API key>(si_domain, dev);
printk(KERN_INFO "32bit %s uses non-identity mapping\n",
dev_name(dev));
return 0;
}
} else {
/*
* In case of a detached 64 bit DMA device from vm, the device
* is put into si_domain for identity mapping.
*/
if (<API key>(dev, 0)) {
int ret;
ret = domain_add_dev_info(si_domain, dev,
hw_pass_through ?
<API key> :
<API key>);
if (!ret) {
printk(KERN_INFO "64bit %s uses identity mapping\n",
dev_name(dev));
return 1;
}
}
}
return 0;
}
static dma_addr_t __intel_map_single(struct device *dev, phys_addr_t paddr,
size_t size, int dir, u64 dma_mask)
{
struct dmar_domain *domain;
phys_addr_t start_paddr;
struct iova *iova;
int prot = 0;
int ret;
struct intel_iommu *iommu;
unsigned long paddr_pfn = paddr >> PAGE_SHIFT;
BUG_ON(dir == DMA_NONE);
if (iommu_no_mapping(dev))
return paddr;
domain = <API key>(dev);
if (!domain)
return 0;
iommu = domain_get_iommu(domain);
size = aligned_nrpages(paddr, size);
iova = intel_alloc_iova(dev, domain, dma_to_mm_pfn(size), dma_mask);
if (!iova)
goto error;
/*
* Check if DMAR supports zero-length reads on write only
* mappings..
*/
if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL || \
!cap_zlr(iommu->cap))
prot |= DMA_PTE_READ;
if (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL)
prot |= DMA_PTE_WRITE;
/*
* paddr - (paddr + size) might be partial page, we should map the whole
* page. Note: if two part of one page are separately mapped, we
* might have two guest_addr mapping to the same host paddr, but this
* is not a big problem
*/
ret = domain_pfn_mapping(domain, mm_to_dma_pfn(iova->pfn_lo),
mm_to_dma_pfn(paddr_pfn), size, prot);
if (ret)
goto error;
/* it's a non-present to present mapping. Only flush if caching mode */
if (cap_caching_mode(iommu->cap))
<API key>(iommu, domain->id, mm_to_dma_pfn(iova->pfn_lo), size, 0, 1);
else
<API key>(iommu);
start_paddr = (phys_addr_t)iova->pfn_lo << PAGE_SHIFT;
start_paddr += paddr & ~PAGE_MASK;
return start_paddr;
error:
if (iova)
__free_iova(&domain->iovad, iova);
printk(KERN_ERR"Device %s request: %zx@%llx dir %d --- failed\n",
dev_name(dev), size, (unsigned long long)paddr, dir);
return 0;
}
static dma_addr_t intel_map_page(struct device *dev, struct page *page,
unsigned long offset, size_t size,
enum dma_data_direction dir,
struct dma_attrs *attrs)
{
return __intel_map_single(dev, page_to_phys(page) + offset, size,
dir, *dev->dma_mask);
}
static void flush_unmaps(void)
{
int i, j;
timer_on = 0;
/* just flush them all */
for (i = 0; i < g_num_of_iommus; i++) {
struct intel_iommu *iommu = g_iommus[i];
if (!iommu)
continue;
if (!deferred_flush[i].next)
continue;
/* In caching mode, global flushes turn emulation expensive */
if (!cap_caching_mode(iommu->cap))
iommu->flush.flush_iotlb(iommu, 0, 0, 0,
<API key>);
for (j = 0; j < deferred_flush[i].next; j++) {
unsigned long mask;
struct iova *iova = deferred_flush[i].iova[j];
struct dmar_domain *domain = deferred_flush[i].domain[j];
/* On real hardware multiple invalidations are expensive */
if (cap_caching_mode(iommu->cap))
<API key>(iommu, domain->id,
iova->pfn_lo, iova->pfn_hi - iova->pfn_lo + 1,
!deferred_flush[i].freelist[j], 0);
else {
mask = ilog2(mm_to_dma_pfn(iova->pfn_hi - iova->pfn_lo + 1));
<API key>(deferred_flush[i].domain[j],
(uint64_t)iova->pfn_lo << PAGE_SHIFT, mask);
}
__free_iova(&deferred_flush[i].domain[j]->iovad, iova);
if (deferred_flush[i].freelist[j])
dma_free_pagelist(deferred_flush[i].freelist[j]);
}
deferred_flush[i].next = 0;
}
list_size = 0;
}
static void <API key>(unsigned long data)
{
unsigned long flags;
spin_lock_irqsave(&<API key>, flags);
flush_unmaps();
<API key>(&<API key>, flags);
}
static void add_unmap(struct dmar_domain *dom, struct iova *iova, struct page *freelist)
{
unsigned long flags;
int next, iommu_id;
struct intel_iommu *iommu;
spin_lock_irqsave(&<API key>, flags);
if (list_size == HIGH_WATER_MARK)
flush_unmaps();
iommu = domain_get_iommu(dom);
iommu_id = iommu->seq_id;
next = deferred_flush[iommu_id].next;
deferred_flush[iommu_id].domain[next] = dom;
deferred_flush[iommu_id].iova[next] = iova;
deferred_flush[iommu_id].freelist[next] = freelist;
deferred_flush[iommu_id].next++;
if (!timer_on) {
mod_timer(&unmap_timer, jiffies + msecs_to_jiffies(10));
timer_on = 1;
}
list_size++;
<API key>(&<API key>, flags);
}
static void intel_unmap_page(struct device *dev, dma_addr_t dev_addr,
size_t size, enum dma_data_direction dir,
struct dma_attrs *attrs)
{
struct dmar_domain *domain;
unsigned long start_pfn, last_pfn;
struct iova *iova;
struct intel_iommu *iommu;
struct page *freelist;
if (iommu_no_mapping(dev))
return;
domain = find_domain(dev);
BUG_ON(!domain);
iommu = domain_get_iommu(domain);
iova = find_iova(&domain->iovad, IOVA_PFN(dev_addr));
if (WARN_ONCE(!iova, "Driver unmaps unmatched page at PFN %llx\n",
(unsigned long long)dev_addr))
return;
start_pfn = mm_to_dma_pfn(iova->pfn_lo);
last_pfn = mm_to_dma_pfn(iova->pfn_hi + 1) - 1;
pr_debug("Device %s unmapping: pfn %lx-%lx\n",
dev_name(dev), start_pfn, last_pfn);
freelist = domain_unmap(domain, start_pfn, last_pfn);
if (intel_iommu_strict) {
<API key>(iommu, domain->id, start_pfn,
last_pfn - start_pfn + 1, !freelist, 0);
/* free iova */
__free_iova(&domain->iovad, iova);
dma_free_pagelist(freelist);
} else {
add_unmap(domain, iova, freelist);
/*
* queue up the release of the unmap to save the 1/6th of the
* cpu used up by the iotlb flush operation...
*/
}
}
static void *<API key>(struct device *dev, size_t size,
dma_addr_t *dma_handle, gfp_t flags,
struct dma_attrs *attrs)
{
void *vaddr;
int order;
size = PAGE_ALIGN(size);
order = get_order(size);
if (!iommu_no_mapping(dev))
flags &= ~(GFP_DMA | GFP_DMA32);
else if (dev->coherent_dma_mask < <API key>(dev)) {
if (dev->coherent_dma_mask < DMA_BIT_MASK(32))
flags |= GFP_DMA;
else
flags |= GFP_DMA32;
}
vaddr = (void *)__get_free_pages(flags, order);
if (!vaddr)
return NULL;
memset(vaddr, 0, size);
*dma_handle = __intel_map_single(dev, virt_to_bus(vaddr), size,
DMA_BIDIRECTIONAL,
dev->coherent_dma_mask);
if (*dma_handle)
return vaddr;
free_pages((unsigned long)vaddr, order);
return NULL;
}
static void intel_free_coherent(struct device *dev, size_t size, void *vaddr,
dma_addr_t dma_handle, struct dma_attrs *attrs)
{
int order;
size = PAGE_ALIGN(size);
order = get_order(size);
intel_unmap_page(dev, dma_handle, size, DMA_BIDIRECTIONAL, NULL);
free_pages((unsigned long)vaddr, order);
}
static void intel_unmap_sg(struct device *dev, struct scatterlist *sglist,
int nelems, enum dma_data_direction dir,
struct dma_attrs *attrs)
{
struct dmar_domain *domain;
unsigned long start_pfn, last_pfn;
struct iova *iova;
struct intel_iommu *iommu;
struct page *freelist;
if (iommu_no_mapping(dev))
return;
domain = find_domain(dev);
BUG_ON(!domain);
iommu = domain_get_iommu(domain);
iova = find_iova(&domain->iovad, IOVA_PFN(sglist[0].dma_address));
if (WARN_ONCE(!iova, "Driver unmaps unmatched sglist at PFN %llx\n",
(unsigned long long)sglist[0].dma_address))
return;
start_pfn = mm_to_dma_pfn(iova->pfn_lo);
last_pfn = mm_to_dma_pfn(iova->pfn_hi + 1) - 1;
freelist = domain_unmap(domain, start_pfn, last_pfn);
if (intel_iommu_strict) {
<API key>(iommu, domain->id, start_pfn,
last_pfn - start_pfn + 1, !freelist, 0);
/* free iova */
__free_iova(&domain->iovad, iova);
dma_free_pagelist(freelist);
} else {
add_unmap(domain, iova, freelist);
/*
* queue up the release of the unmap to save the 1/6th of the
* cpu used up by the iotlb flush operation...
*/
}
}
static int <API key>(struct device *hddev,
struct scatterlist *sglist, int nelems, int dir)
{
int i;
struct scatterlist *sg;
for_each_sg(sglist, sg, nelems, i) {
BUG_ON(!sg_page(sg));
sg->dma_address = page_to_phys(sg_page(sg)) + sg->offset;
sg->dma_length = sg->length;
}
return nelems;
}
static int intel_map_sg(struct device *dev, struct scatterlist *sglist, int nelems,
enum dma_data_direction dir, struct dma_attrs *attrs)
{
int i;
struct dmar_domain *domain;
size_t size = 0;
int prot = 0;
struct iova *iova = NULL;
int ret;
struct scatterlist *sg;
unsigned long start_vpfn;
struct intel_iommu *iommu;
BUG_ON(dir == DMA_NONE);
if (iommu_no_mapping(dev))
return <API key>(dev, sglist, nelems, dir);
domain = <API key>(dev);
if (!domain)
return 0;
iommu = domain_get_iommu(domain);
for_each_sg(sglist, sg, nelems, i)
size += aligned_nrpages(sg->offset, sg->length);
iova = intel_alloc_iova(dev, domain, dma_to_mm_pfn(size),
*dev->dma_mask);
if (!iova) {
sglist->dma_length = 0;
return 0;
}
/*
* Check if DMAR supports zero-length reads on write only
* mappings..
*/
if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL || \
!cap_zlr(iommu->cap))
prot |= DMA_PTE_READ;
if (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL)
prot |= DMA_PTE_WRITE;
start_vpfn = mm_to_dma_pfn(iova->pfn_lo);
ret = domain_sg_mapping(domain, start_vpfn, sglist, size, prot);
if (unlikely(ret)) {
/* clear the page */
dma_pte_clear_range(domain, start_vpfn,
start_vpfn + size - 1);
/* free page tables */
<API key>(domain, start_vpfn,
start_vpfn + size - 1);
/* free iova */
__free_iova(&domain->iovad, iova);
return 0;
}
/* it's a non-present to present mapping. Only flush if caching mode */
if (cap_caching_mode(iommu->cap))
<API key>(iommu, domain->id, start_vpfn, size, 0, 1);
else
<API key>(iommu);
return nelems;
}
static int intel_mapping_error(struct device *dev, dma_addr_t dma_addr)
{
return !dma_addr;
}
struct dma_map_ops intel_dma_ops = {
.alloc = <API key>,
.free = intel_free_coherent,
.map_sg = intel_map_sg,
.unmap_sg = intel_unmap_sg,
.map_page = intel_map_page,
.unmap_page = intel_unmap_page,
.mapping_error = intel_mapping_error,
};
static inline int <API key>(void)
{
int ret = 0;
iommu_domain_cache = kmem_cache_create("iommu_domain",
sizeof(struct dmar_domain),
0,
SLAB_HWCACHE_ALIGN,
NULL);
if (!iommu_domain_cache) {
printk(KERN_ERR "Couldn't create iommu_domain cache\n");
ret = -ENOMEM;
}
return ret;
}
static inline int <API key>(void)
{
int ret = 0;
iommu_devinfo_cache = kmem_cache_create("iommu_devinfo",
sizeof(struct device_domain_info),
0,
SLAB_HWCACHE_ALIGN,
NULL);
if (!iommu_devinfo_cache) {
printk(KERN_ERR "Couldn't create devinfo cache\n");
ret = -ENOMEM;
}
return ret;
}
static inline int <API key>(void)
{
int ret = 0;
iommu_iova_cache = kmem_cache_create("iommu_iova",
sizeof(struct iova),
0,
SLAB_HWCACHE_ALIGN,
NULL);
if (!iommu_iova_cache) {
printk(KERN_ERR "Couldn't create iova cache\n");
ret = -ENOMEM;
}
return ret;
}
static int __init iommu_init_mempool(void)
{
int ret;
ret = <API key>();
if (ret)
return ret;
ret = <API key>();
if (ret)
goto domain_error;
ret = <API key>();
if (!ret)
return ret;
kmem_cache_destroy(iommu_domain_cache);
domain_error:
kmem_cache_destroy(iommu_iova_cache);
return -ENOMEM;
}
static void __init iommu_exit_mempool(void)
{
kmem_cache_destroy(iommu_devinfo_cache);
kmem_cache_destroy(iommu_domain_cache);
kmem_cache_destroy(iommu_iova_cache);
}
static void <API key>(struct pci_dev *pdev)
{
struct dmar_drhd_unit *drhd;
u32 vtbar;
int rc;
/* We know that this device on this chipset has its own IOMMU.
* If we find it under a different IOMMU, then the BIOS is lying
* to us. Hope that the IOMMU for this device is actually
* disabled, and it needs no translation...
*/
rc = <API key>(pdev->bus, PCI_DEVFN(0, 0), 0xb0, &vtbar);
if (rc) {
/* "can't" happen */
dev_info(&pdev->dev, "failed to run vt-d quirk\n");
return;
}
vtbar &= 0xffff0000;
/* we know that the this iommu should be at offset 0xa000 from vtbar */
drhd = <API key>(pdev);
if (WARN_TAINT_ONCE(!drhd || drhd->reg_base_addr - vtbar != 0xa000,
<API key>,
"BIOS assigned incorrect VT-d unit for Intel(R) QuickData Technology device\n"))
pdev->dev.archdata.iommu = <API key>;
}
<API key>(PCI_VENDOR_ID_INTEL, <API key>, <API key>);
static void __init <API key>(void)
{
struct dmar_drhd_unit *drhd;
struct device *dev;
int i;
for_each_drhd_unit(drhd) {
if (!drhd->include_all) {
<API key>(drhd->devices,
drhd->devices_cnt, i, dev)
break;
/* ignore DMAR unit if no devices exist */
if (i == drhd->devices_cnt)
drhd->ignored = 1;
}
}
<API key>(drhd) {
if (drhd->include_all)
continue;
<API key>(drhd->devices,
drhd->devices_cnt, i, dev)
if (!dev_is_pci(dev) || !IS_GFX_DEVICE(to_pci_dev(dev)))
break;
if (i < drhd->devices_cnt)
continue;
/* This IOMMU has *only* gfx devices. Either bypass it or
set the gfx_mapped flag, as appropriate */
if (dmar_map_gfx) {
<API key> = 1;
} else {
drhd->ignored = 1;
<API key>(drhd->devices,
drhd->devices_cnt, i, dev)
dev->archdata.iommu = <API key>;
}
}
}
#ifdef CONFIG_SUSPEND
static int init_iommu_hw(void)
{
struct dmar_drhd_unit *drhd;
struct intel_iommu *iommu = NULL;
<API key>(iommu, drhd)
if (iommu->qi)
dmar_reenable_qi(iommu);
for_each_iommu(iommu, drhd) {
if (drhd->ignored) {
/*
* we always have to disable PMRs or DMA may fail on
* this device
*/
if (force_on)
<API key>(iommu);
continue;
}
<API key>(iommu);
<API key>(iommu);
iommu->flush.flush_context(iommu, 0, 0, 0,
<API key>);
iommu->flush.flush_iotlb(iommu, 0, 0, 0,
<API key>);
if (<API key>(iommu))
return 1;
<API key>(iommu);
}
return 0;
}
static void iommu_flush_all(void)
{
struct dmar_drhd_unit *drhd;
struct intel_iommu *iommu;
<API key>(iommu, drhd) {
iommu->flush.flush_context(iommu, 0, 0, 0,
<API key>);
iommu->flush.flush_iotlb(iommu, 0, 0, 0,
<API key>);
}
}
static int iommu_suspend(void)
{
struct dmar_drhd_unit *drhd;
struct intel_iommu *iommu = NULL;
unsigned long flag;
<API key>(iommu, drhd) {
iommu->iommu_state = kzalloc(sizeof(u32) * MAX_SR_DMAR_REGS,
GFP_ATOMIC);
if (!iommu->iommu_state)
goto nomem;
}
iommu_flush_all();
<API key>(iommu, drhd) {
<API key>(iommu);
<API key>(&iommu->register_lock, flag);
iommu->iommu_state[SR_DMAR_FECTL_REG] =
readl(iommu->reg + DMAR_FECTL_REG);
iommu->iommu_state[SR_DMAR_FEDATA_REG] =
readl(iommu->reg + DMAR_FEDATA_REG);
iommu->iommu_state[SR_DMAR_FEADDR_REG] =
readl(iommu->reg + DMAR_FEADDR_REG);
iommu->iommu_state[SR_DMAR_FEUADDR_REG] =
readl(iommu->reg + DMAR_FEUADDR_REG);
<API key>(&iommu->register_lock, flag);
}
return 0;
nomem:
<API key>(iommu, drhd)
kfree(iommu->iommu_state);
return -ENOMEM;
}
static void iommu_resume(void)
{
struct dmar_drhd_unit *drhd;
struct intel_iommu *iommu = NULL;
unsigned long flag;
if (init_iommu_hw()) {
if (force_on)
panic("tboot: IOMMU setup failed, DMAR can not resume!\n");
else
WARN(1, "IOMMU setup failed, DMAR can not resume!\n");
return;
}
<API key>(iommu, drhd) {
<API key>(&iommu->register_lock, flag);
writel(iommu->iommu_state[SR_DMAR_FECTL_REG],
iommu->reg + DMAR_FECTL_REG);
writel(iommu->iommu_state[SR_DMAR_FEDATA_REG],
iommu->reg + DMAR_FEDATA_REG);
writel(iommu->iommu_state[SR_DMAR_FEADDR_REG],
iommu->reg + DMAR_FEADDR_REG);
writel(iommu->iommu_state[SR_DMAR_FEUADDR_REG],
iommu->reg + DMAR_FEUADDR_REG);
<API key>(&iommu->register_lock, flag);
}
<API key>(iommu, drhd)
kfree(iommu->iommu_state);
}
static struct syscore_ops iommu_syscore_ops = {
.resume = iommu_resume,
.suspend = iommu_suspend,
};
static void __init init_iommu_pm_ops(void)
{
<API key>(&iommu_syscore_ops);
}
#else
static inline void init_iommu_pm_ops(void) {}
#endif /* CONFIG_PM */
int __init dmar_parse_one_rmrr(struct acpi_dmar_header *header)
{
struct <API key> *rmrr;
struct dmar_rmrr_unit *rmrru;
rmrru = kzalloc(sizeof(*rmrru), GFP_KERNEL);
if (!rmrru)
return -ENOMEM;
rmrru->hdr = header;
rmrr = (struct <API key> *)header;
rmrru->base_address = rmrr->base_address;
rmrru->end_address = rmrr->end_address;
rmrru->devices = <API key>((void *)(rmrr + 1),
((void *)rmrr) + rmrr->header.length,
&rmrru->devices_cnt);
if (rmrru->devices_cnt && rmrru->devices == NULL) {
kfree(rmrru);
return -ENOMEM;
}
list_add(&rmrru->list, &dmar_rmrr_units);
return 0;
}
int __init dmar_parse_one_atsr(struct acpi_dmar_header *hdr)
{
struct acpi_dmar_atsr *atsr;
struct dmar_atsr_unit *atsru;
atsr = container_of(hdr, struct acpi_dmar_atsr, header);
atsru = kzalloc(sizeof(*atsru), GFP_KERNEL);
if (!atsru)
return -ENOMEM;
atsru->hdr = hdr;
atsru->include_all = atsr->flags & 0x1;
if (!atsru->include_all) {
atsru->devices = <API key>((void *)(atsr + 1),
(void *)atsr + atsr->header.length,
&atsru->devices_cnt);
if (atsru->devices_cnt && atsru->devices == NULL) {
kfree(atsru);
return -ENOMEM;
}
}
list_add_rcu(&atsru->list, &dmar_atsr_units);
return 0;
}
static void <API key>(struct dmar_atsr_unit *atsru)
{
dmar_free_dev_scope(&atsru->devices, &atsru->devices_cnt);
kfree(atsru);
}
static void <API key>(void)
{
struct dmar_rmrr_unit *rmrru, *rmrr_n;
struct dmar_atsr_unit *atsru, *atsr_n;
<API key>(rmrru, rmrr_n, &dmar_rmrr_units, list) {
list_del(&rmrru->list);
dmar_free_dev_scope(&rmrru->devices, &rmrru->devices_cnt);
kfree(rmrru);
}
<API key>(atsru, atsr_n, &dmar_atsr_units, list) {
list_del(&atsru->list);
<API key>(atsru);
}
}
int <API key>(struct pci_dev *dev)
{
int i, ret = 1;
struct pci_bus *bus;
struct pci_dev *bridge = NULL;
struct device *tmp;
struct acpi_dmar_atsr *atsr;
struct dmar_atsr_unit *atsru;
dev = pci_physfn(dev);
for (bus = dev->bus; bus; bus = bus->parent) {
bridge = bus->self;
if (!bridge || !pci_is_pcie(bridge) ||
pci_pcie_type(bridge) == <API key>)
return 0;
if (pci_pcie_type(bridge) == <API key>)
break;
}
if (!bridge)
return 0;
rcu_read_lock();
<API key>(atsru, &dmar_atsr_units, list) {
atsr = container_of(atsru->hdr, struct acpi_dmar_atsr, header);
if (atsr->segment != pci_domain_nr(dev->bus))
continue;
for_each_dev_scope(atsru->devices, atsru->devices_cnt, i, tmp)
if (tmp == &bridge->dev)
goto out;
if (atsru->include_all)
goto out;
}
ret = 0;
out:
rcu_read_unlock();
return ret;
}
int <API key>(struct <API key> *info)
{
int ret = 0;
struct dmar_rmrr_unit *rmrru;
struct dmar_atsr_unit *atsru;
struct acpi_dmar_atsr *atsr;
struct <API key> *rmrr;
if (!intel_iommu_enabled && system_state != SYSTEM_BOOTING)
return 0;
list_for_each_entry(rmrru, &dmar_rmrr_units, list) {
rmrr = container_of(rmrru->hdr,
struct <API key>, header);
if (info->event == <API key>) {
ret = <API key>(info, (void *)(rmrr + 1),
((void *)rmrr) + rmrr->header.length,
rmrr->segment, rmrru->devices,
rmrru->devices_cnt);
if (ret > 0)
break;
else if(ret < 0)
return ret;
} else if (info->event == <API key>) {
if (<API key>(info, rmrr->segment,
rmrru->devices, rmrru->devices_cnt))
break;
}
}
list_for_each_entry(atsru, &dmar_atsr_units, list) {
if (atsru->include_all)
continue;
atsr = container_of(atsru->hdr, struct acpi_dmar_atsr, header);
if (info->event == <API key>) {
ret = <API key>(info, (void *)(atsr + 1),
(void *)atsr + atsr->header.length,
atsr->segment, atsru->devices,
atsru->devices_cnt);
if (ret > 0)
break;
else if(ret < 0)
return ret;
} else if (info->event == <API key>) {
if (<API key>(info, atsr->segment,
atsru->devices, atsru->devices_cnt))
break;
}
}
return 0;
}
/*
* Here we only respond to action of unbound device from driver.
*
* Added device is not attached to its DMAR domain here yet. That will happen
* when mapping the device to iova.
*/
static int device_notifier(struct notifier_block *nb,
unsigned long action, void *data)
{
struct device *dev = data;
struct dmar_domain *domain;
if (iommu_dummy(dev))
return 0;
if (action != <API key> &&
action != <API key>)
return 0;
domain = find_domain(dev);
if (!domain)
return 0;
down_read(&dmar_global_lock);
<API key>(domain, dev);
if (!(domain->flags & <API key>) &&
!(domain->flags & <API key>) &&
list_empty(&domain->devices))
domain_exit(domain);
up_read(&dmar_global_lock);
return 0;
}
static struct notifier_block device_nb = {
.notifier_call = device_notifier,
};
static int <API key>(struct notifier_block *nb,
unsigned long val, void *v)
{
struct memory_notify *mhp = v;
unsigned long long start, end;
unsigned long start_vpfn, last_vpfn;
switch (val) {
case MEM_GOING_ONLINE:
start = mhp->start_pfn << PAGE_SHIFT;
end = ((mhp->start_pfn + mhp->nr_pages) << PAGE_SHIFT) - 1;
if (<API key>(si_domain, start, end)) {
pr_warn("dmar: failed to build identity map for [%llx-%llx]\n",
start, end);
return NOTIFY_BAD;
}
break;
case MEM_OFFLINE:
case MEM_CANCEL_ONLINE:
start_vpfn = mm_to_dma_pfn(mhp->start_pfn);
last_vpfn = mm_to_dma_pfn(mhp->start_pfn + mhp->nr_pages - 1);
while (start_vpfn <= last_vpfn) {
struct iova *iova;
struct dmar_drhd_unit *drhd;
struct intel_iommu *iommu;
struct page *freelist;
iova = find_iova(&si_domain->iovad, start_vpfn);
if (iova == NULL) {
pr_debug("dmar: failed get IOVA for PFN %lx\n",
start_vpfn);
break;
}
iova = <API key>(&si_domain->iovad, iova,
start_vpfn, last_vpfn);
if (iova == NULL) {
pr_warn("dmar: failed to split IOVA PFN [%lx-%lx]\n",
start_vpfn, last_vpfn);
return NOTIFY_BAD;
}
freelist = domain_unmap(si_domain, iova->pfn_lo,
iova->pfn_hi);
rcu_read_lock();
<API key>(iommu, drhd)
<API key>(iommu, si_domain->id,
iova->pfn_lo,
iova->pfn_hi - iova->pfn_lo + 1,
!freelist, 0);
rcu_read_unlock();
dma_free_pagelist(freelist);
start_vpfn = iova->pfn_hi + 1;
free_iova_mem(iova);
}
break;
}
return NOTIFY_OK;
}
static struct notifier_block <API key> = {
.notifier_call = <API key>,
.priority = 0
};
int __init intel_iommu_init(void)
{
int ret = -ENODEV;
struct dmar_drhd_unit *drhd;
struct intel_iommu *iommu;
/* VT-d is required for a TXT/tboot launch, so enforce that */
force_on = tboot_force_iommu();
if (iommu_init_mempool()) {
if (force_on)
panic("tboot: Failed to initialize iommu memory\n");
return -ENOMEM;
}
down_write(&dmar_global_lock);
if (dmar_table_init()) {
if (force_on)
panic("tboot: Failed to initialize DMAR table\n");
goto out_free_dmar;
}
/*
* Disable translation if already enabled prior to OS handover.
*/
<API key>(iommu, drhd)
if (iommu->gcmd & DMA_GCMD_TE)
<API key>(iommu);
if (dmar_dev_scope_init() < 0) {
if (force_on)
panic("tboot: Failed to initialize DMAR device scope\n");
goto out_free_dmar;
}
if (no_iommu || dmar_disabled)
goto out_free_dmar;
if (list_empty(&dmar_rmrr_units))
printk(KERN_INFO "DMAR: No RMRR found\n");
if (list_empty(&dmar_atsr_units))
printk(KERN_INFO "DMAR: No ATSR found\n");
if (<API key>()) {
if (force_on)
panic("tboot: Failed to reserve iommu ranges\n");
goto <API key>;
}
<API key>();
ret = init_dmars();
if (ret) {
if (force_on)
panic("tboot: Failed to initialize DMARs\n");
printk(KERN_ERR "IOMMU: dmar init failed\n");
goto <API key>;
}
up_write(&dmar_global_lock);
printk(KERN_INFO
"PCI-DMA: Intel(R) Virtualization Technology for Directed I/O\n");
init_timer(&unmap_timer);
#ifdef CONFIG_SWIOTLB
swiotlb = 0;
#endif
dma_ops = &intel_dma_ops;
init_iommu_pm_ops();
bus_set_iommu(&pci_bus_type, &intel_iommu_ops);
<API key>(&pci_bus_type, &device_nb);
if (si_domain && !hw_pass_through)
<API key>(&<API key>);
intel_iommu_enabled = 1;
return 0;
<API key>:
put_iova_domain(&reserved_iova_list);
out_free_dmar:
<API key>();
up_write(&dmar_global_lock);
iommu_exit_mempool();
return ret;
}
static void <API key>(struct intel_iommu *iommu,
struct device *dev)
{
struct pci_dev *tmp, *parent, *pdev;
if (!iommu || !dev || !dev_is_pci(dev))
return;
pdev = to_pci_dev(dev);
/* dependent device detach */
tmp = <API key>(pdev);
/* Secondary interface's bus number and devfn 0 */
if (tmp) {
parent = pdev->bus->self;
while (parent != tmp) {
iommu_detach_dev(iommu, parent->bus->number,
parent->devfn);
parent = parent->bus->self;
}
if (pci_is_pcie(tmp)) /* this is a PCIe-to-PCI bridge */
iommu_detach_dev(iommu,
tmp->subordinate->number, 0);
else /* this is a legacy PCI bridge */
iommu_detach_dev(iommu, tmp->bus->number,
tmp->devfn);
}
}
static void <API key>(struct dmar_domain *domain,
struct device *dev)
{
struct device_domain_info *info, *tmp;
struct intel_iommu *iommu;
unsigned long flags;
int found = 0;
u8 bus, devfn;
iommu = device_to_iommu(dev, &bus, &devfn);
if (!iommu)
return;
spin_lock_irqsave(&device_domain_lock, flags);
<API key>(info, tmp, &domain->devices, link) {
if (info->iommu == iommu && info->bus == bus &&
info->devfn == devfn) {
unlink_domain_info(info);
<API key>(&device_domain_lock, flags);
<API key>(info);
iommu_detach_dev(iommu, info->bus, info->devfn);
<API key>(iommu, dev);
free_devinfo_mem(info);
spin_lock_irqsave(&device_domain_lock, flags);
if (found)
break;
else
continue;
}
/* if there is no other devices under the same iommu
* owned by this domain, clear this iommu in iommu_bmp
* update iommu count and coherency
*/
if (info->iommu == iommu)
found = 1;
}
<API key>(&device_domain_lock, flags);
if (found == 0) {
unsigned long tmp_flags;
spin_lock_irqsave(&domain->iommu_lock, tmp_flags);
clear_bit(iommu->seq_id, domain->iommu_bmp);
domain->iommu_count
<API key>(domain);
<API key>(&domain->iommu_lock, tmp_flags);
if (!(domain->flags & <API key>) &&
!(domain->flags & <API key>)) {
spin_lock_irqsave(&iommu->lock, tmp_flags);
clear_bit(domain->id, iommu->domain_ids);
iommu->domains[domain->id] = NULL;
<API key>(&iommu->lock, tmp_flags);
}
}
}
static int md_domain_init(struct dmar_domain *domain, int guest_width)
{
int adjust_width;
init_iova_domain(&domain->iovad, DMA_32BIT_PFN);
<API key>(domain);
/* calculate AGAW */
domain->gaw = guest_width;
adjust_width = <API key>(guest_width);
domain->agaw = width_to_agaw(adjust_width);
domain->iommu_coherency = 0;
domain->iommu_snooping = 0;
domain->iommu_superpage = 0;
domain->max_addr = 0;
domain->nid = -1;
/* always allocate the top pgd */
domain->pgd = (struct dma_pte *)alloc_pgtable_page(domain->nid);
if (!domain->pgd)
return -ENOMEM;
domain_flush_cache(domain, domain->pgd, PAGE_SIZE);
return 0;
}
static int <API key>(struct iommu_domain *domain)
{
struct dmar_domain *dmar_domain;
dmar_domain = alloc_domain(true);
if (!dmar_domain) {
printk(KERN_ERR
"<API key>: dmar_domain == NULL\n");
return -ENOMEM;
}
if (md_domain_init(dmar_domain, <API key>)) {
printk(KERN_ERR
"<API key>() failed\n");
domain_exit(dmar_domain);
return -ENOMEM;
}
<API key>(dmar_domain);
domain->priv = dmar_domain;
domain->geometry.aperture_start = 0;
domain->geometry.aperture_end = __DOMAIN_MAX_ADDR(dmar_domain->gaw);
domain->geometry.force_aperture = true;
return 0;
}
static void <API key>(struct iommu_domain *domain)
{
struct dmar_domain *dmar_domain = domain->priv;
domain->priv = NULL;
domain_exit(dmar_domain);
}
static int <API key>(struct iommu_domain *domain,
struct device *dev)
{
struct dmar_domain *dmar_domain = domain->priv;
struct intel_iommu *iommu;
int addr_width;
u8 bus, devfn;
/* normally dev is not mapped */
if (unlikely(<API key>(dev))) {
struct dmar_domain *old_domain;
old_domain = find_domain(dev);
if (old_domain) {
if (dmar_domain->flags & <API key> ||
dmar_domain->flags & <API key>)
<API key>(old_domain, dev);
else
<API key>(old_domain);
}
}
iommu = device_to_iommu(dev, &bus, &devfn);
if (!iommu)
return -ENODEV;
/* check if this iommu agaw is sufficient for max mapped address */
addr_width = agaw_to_width(iommu->agaw);
if (addr_width > cap_mgaw(iommu->cap))
addr_width = cap_mgaw(iommu->cap);
if (dmar_domain->max_addr > (1LL << addr_width)) {
printk(KERN_ERR "%s: iommu width (%d) is not "
"sufficient for the mapped address (%llx)\n",
__func__, addr_width, dmar_domain->max_addr);
return -EFAULT;
}
dmar_domain->gaw = addr_width;
/*
* Knock out extra levels of page tables if necessary
*/
while (iommu->agaw < dmar_domain->agaw) {
struct dma_pte *pte;
pte = dmar_domain->pgd;
if (dma_pte_present(pte)) {
dmar_domain->pgd = (struct dma_pte *)
phys_to_virt(dma_pte_addr(pte));
free_pgtable_page(pte);
}
dmar_domain->agaw
}
return domain_add_dev_info(dmar_domain, dev, <API key>);
}
static void <API key>(struct iommu_domain *domain,
struct device *dev)
{
struct dmar_domain *dmar_domain = domain->priv;
<API key>(dmar_domain, dev);
}
static int intel_iommu_map(struct iommu_domain *domain,
unsigned long iova, phys_addr_t hpa,
size_t size, int iommu_prot)
{
struct dmar_domain *dmar_domain = domain->priv;
u64 max_addr;
int prot = 0;
int ret;
if (iommu_prot & IOMMU_READ)
prot |= DMA_PTE_READ;
if (iommu_prot & IOMMU_WRITE)
prot |= DMA_PTE_WRITE;
if ((iommu_prot & IOMMU_CACHE) && dmar_domain->iommu_snooping)
prot |= DMA_PTE_SNP;
max_addr = iova + size;
if (dmar_domain->max_addr < max_addr) {
u64 end;
/* check if minimum agaw is sufficient for mapped address */
end = __DOMAIN_MAX_ADDR(dmar_domain->gaw) + 1;
if (end < max_addr) {
printk(KERN_ERR "%s: iommu width (%d) is not "
"sufficient for the mapped address (%llx)\n",
__func__, dmar_domain->gaw, max_addr);
return -EFAULT;
}
dmar_domain->max_addr = max_addr;
}
/* Round up size to next multiple of PAGE_SIZE, if it and
the low bits of hpa would take us onto the next page */
size = aligned_nrpages(hpa, size);
ret = domain_pfn_mapping(dmar_domain, iova >> VTD_PAGE_SHIFT,
hpa >> VTD_PAGE_SHIFT, size, prot);
return ret;
}
static size_t intel_iommu_unmap(struct iommu_domain *domain,
unsigned long iova, size_t size)
{
struct dmar_domain *dmar_domain = domain->priv;
struct page *freelist = NULL;
struct intel_iommu *iommu;
unsigned long start_pfn, last_pfn;
unsigned int npages;
int iommu_id, num, ndomains, level = 0;
/* Cope with horrid API which requires us to unmap more than the
size argument if it happens to be a large-page mapping. */
if (!pfn_to_dma_pte(dmar_domain, iova >> VTD_PAGE_SHIFT, &level))
BUG();
if (size < VTD_PAGE_SIZE << <API key>(level))
size = VTD_PAGE_SIZE << <API key>(level);
start_pfn = iova >> VTD_PAGE_SHIFT;
last_pfn = (iova + size - 1) >> VTD_PAGE_SHIFT;
freelist = domain_unmap(dmar_domain, start_pfn, last_pfn);
npages = last_pfn - start_pfn + 1;
for_each_set_bit(iommu_id, dmar_domain->iommu_bmp, g_num_of_iommus) {
iommu = g_iommus[iommu_id];
/*
* find bit position of dmar_domain
*/
ndomains = cap_ndoms(iommu->cap);
for_each_set_bit(num, iommu->domain_ids, ndomains) {
if (iommu->domains[num] == dmar_domain)
<API key>(iommu, num, start_pfn,
npages, !freelist, 0);
}
}
dma_free_pagelist(freelist);
if (dmar_domain->max_addr == iova + size)
dmar_domain->max_addr = iova;
return size;
}
static phys_addr_t <API key>(struct iommu_domain *domain,
dma_addr_t iova)
{
struct dmar_domain *dmar_domain = domain->priv;
struct dma_pte *pte;
int level = 0;
u64 phys = 0;
pte = pfn_to_dma_pte(dmar_domain, iova >> VTD_PAGE_SHIFT, &level);
if (pte)
phys = dma_pte_addr(pte);
return phys;
}
static int <API key>(struct iommu_domain *domain,
unsigned long cap)
{
struct dmar_domain *dmar_domain = domain->priv;
if (cap == <API key>)
return dmar_domain->iommu_snooping;
if (cap == <API key>)
return <API key>;
return 0;
}
#define REQ_ACS_FLAGS (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
static int <API key>(struct device *dev)
{
struct pci_dev *pdev = to_pci_dev(dev);
struct pci_dev *bridge, *dma_pdev = NULL;
struct iommu_group *group;
int ret;
u8 bus, devfn;
if (!device_to_iommu(dev, &bus, &devfn))
return -ENODEV;
bridge = <API key>(pdev);
if (bridge) {
if (pci_is_pcie(bridge))
dma_pdev = <API key>(
pci_domain_nr(pdev->bus),
bridge->subordinate->number, 0);
if (!dma_pdev)
dma_pdev = pci_dev_get(bridge);
} else
dma_pdev = pci_dev_get(pdev);
/* Account for quirked devices */
swap_pci_ref(&dma_pdev, pci_get_dma_source(dma_pdev));
/*
* If it's a multifunction device that does not support our
* required ACS flags, add to the same group as lowest numbered
* function that also does not suport the required ACS flags.
*/
if (dma_pdev->multifunction &&
!pci_acs_enabled(dma_pdev, REQ_ACS_FLAGS)) {
u8 i, slot = PCI_SLOT(dma_pdev->devfn);
for (i = 0; i < 8; i++) {
struct pci_dev *tmp;
tmp = pci_get_slot(dma_pdev->bus, PCI_DEVFN(slot, i));
if (!tmp)
continue;
if (!pci_acs_enabled(tmp, REQ_ACS_FLAGS)) {
swap_pci_ref(&dma_pdev, tmp);
break;
}
pci_dev_put(tmp);
}
}
/*
* Devices on the root bus go through the iommu. If that's not us,
* find the next upstream device and test ACS up to the root bus.
* Finding the next device may require skipping virtual buses.
*/
while (!pci_is_root_bus(dma_pdev->bus)) {
struct pci_bus *bus = dma_pdev->bus;
while (!bus->self) {
if (!pci_is_root_bus(bus))
bus = bus->parent;
else
goto root_bus;
}
if (<API key>(bus->self, NULL, REQ_ACS_FLAGS))
break;
swap_pci_ref(&dma_pdev, pci_dev_get(bus->self));
}
root_bus:
group = iommu_group_get(&dma_pdev->dev);
pci_dev_put(dma_pdev);
if (!group) {
group = iommu_group_alloc();
if (IS_ERR(group))
return PTR_ERR(group);
}
ret = <API key>(group, dev);
iommu_group_put(group);
return ret;
}
static void <API key>(struct device *dev)
{
<API key>(dev);
}
static struct iommu_ops intel_iommu_ops = {
.domain_init = <API key>,
.domain_destroy = <API key>,
.attach_dev = <API key>,
.detach_dev = <API key>,
.map = intel_iommu_map,
.unmap = intel_iommu_unmap,
.iova_to_phys = <API key>,
.domain_has_cap = <API key>,
.add_device = <API key>,
.remove_device = <API key>,
.pgsize_bitmap = INTEL_IOMMU_PGSIZES,
};
static void quirk_iommu_g4x_gfx(struct pci_dev *dev)
{
/* G4x/GM45 integrated gfx dmar support is totally busted. */
printk(KERN_INFO "DMAR: Disabling IOMMU for graphics on this chipset\n");
dmar_map_gfx = 0;
}
<API key>(PCI_VENDOR_ID_INTEL, 0x2a40, quirk_iommu_g4x_gfx);
<API key>(PCI_VENDOR_ID_INTEL, 0x2e00, quirk_iommu_g4x_gfx);
<API key>(PCI_VENDOR_ID_INTEL, 0x2e10, quirk_iommu_g4x_gfx);
<API key>(PCI_VENDOR_ID_INTEL, 0x2e20, quirk_iommu_g4x_gfx);
<API key>(PCI_VENDOR_ID_INTEL, 0x2e30, quirk_iommu_g4x_gfx);
<API key>(PCI_VENDOR_ID_INTEL, 0x2e40, quirk_iommu_g4x_gfx);
<API key>(PCI_VENDOR_ID_INTEL, 0x2e90, quirk_iommu_g4x_gfx);
static void quirk_iommu_rwbf(struct pci_dev *dev)
{
/*
* Mobile 4 Series Chipset neglects to set RWBF capability,
* but needs it. Same seems to hold for the desktop versions.
*/
printk(KERN_INFO "DMAR: Forcing write-buffer flush capability\n");
rwbf_quirk = 1;
}
<API key>(PCI_VENDOR_ID_INTEL, 0x2a40, quirk_iommu_rwbf);
<API key>(PCI_VENDOR_ID_INTEL, 0x2e00, quirk_iommu_rwbf);
<API key>(PCI_VENDOR_ID_INTEL, 0x2e10, quirk_iommu_rwbf);
<API key>(PCI_VENDOR_ID_INTEL, 0x2e20, quirk_iommu_rwbf);
<API key>(PCI_VENDOR_ID_INTEL, 0x2e30, quirk_iommu_rwbf);
<API key>(PCI_VENDOR_ID_INTEL, 0x2e40, quirk_iommu_rwbf);
<API key>(PCI_VENDOR_ID_INTEL, 0x2e90, quirk_iommu_rwbf);
#define GGC 0x52
#define <API key> (0xf << 8)
#define <API key> (0x0 << 8)
#define GGC_MEMORY_SIZE_1M (0x1 << 8)
#define GGC_MEMORY_SIZE_2M (0x3 << 8)
#define <API key> (0x8 << 8)
#define <API key> (0x9 << 8)
#define <API key> (0xa << 8)
#define <API key> (0xb << 8)
static void <API key>(struct pci_dev *dev)
{
unsigned short ggc;
if (<API key>(dev, GGC, &ggc))
return;
if (!(ggc & <API key>)) {
printk(KERN_INFO "DMAR: BIOS has allocated no shadow GTT; disabling IOMMU for graphics\n");
dmar_map_gfx = 0;
} else if (dmar_map_gfx) {
/* we have to ensure the gfx device is idle before we flush */
printk(KERN_INFO "DMAR: Disabling batched IOTLB flush on Ironlake\n");
intel_iommu_strict = 1;
}
}
<API key>(PCI_VENDOR_ID_INTEL, 0x0040, <API key>);
<API key>(PCI_VENDOR_ID_INTEL, 0x0044, <API key>);
<API key>(PCI_VENDOR_ID_INTEL, 0x0062, <API key>);
<API key>(PCI_VENDOR_ID_INTEL, 0x006a, <API key>);
/* On Tylersburg chipsets, some BIOSes have been known to enable the
ISOCH DMAR unit for the Azalia sound device, but not give it any
TLB entries, which causes it to deadlock. Check for that. We do
this in a function called from init_dmars(), instead of in a PCI
quirk, because we don't want to print the obnoxious "BIOS broken"
message if VT-d is actually disabled.
*/
static void __init <API key>(void)
{
struct pci_dev *pdev;
uint32_t vtisochctrl;
/* If there's no Azalia in the system anyway, forget it. */
pdev = pci_get_device(PCI_VENDOR_ID_INTEL, 0x3a3e, NULL);
if (!pdev)
return;
pci_dev_put(pdev);
/* System Management Registers. Might be hidden, in which case
we can't do the sanity check. But that's OK, because the
known-broken BIOSes _don't_ actually hide it, so far. */
pdev = pci_get_device(PCI_VENDOR_ID_INTEL, 0x342e, NULL);
if (!pdev)
return;
if (<API key>(pdev, 0x188, &vtisochctrl)) {
pci_dev_put(pdev);
return;
}
pci_dev_put(pdev);
/* If Azalia DMA is routed to the non-isoch DMAR unit, fine. */
if (vtisochctrl & 1)
return;
/* Drop all bits other than the number of TLB entries */
vtisochctrl &= 0x1c;
/* If we have the recommended number of TLB entries (16), fine. */
if (vtisochctrl == 0x10)
return;
/* Zero TLB entries? You get to ride the short bus to school. */
if (!vtisochctrl) {
WARN(1, "Your BIOS is broken; DMA routed to ISOCH DMAR unit but no TLB space.\n"
"BIOS vendor: %s; Ver: %s; Product Version: %s\n",
dmi_get_system_info(DMI_BIOS_VENDOR),
dmi_get_system_info(DMI_BIOS_VERSION),
dmi_get_system_info(DMI_PRODUCT_VERSION));
<API key> |= IDENTMAP_AZALIA;
return;
}
printk(KERN_WARNING "DMAR: Recommended TLB entries for ISOCH unit is 16; your BIOS set %d\n",
vtisochctrl);
} |
#include "virtio_pci_common.h"
static bool force_legacy = false;
#if IS_ENABLED(<API key>)
module_param(force_legacy, bool, 0444);
MODULE_PARM_DESC(force_legacy,
"Force legacy mode for transitional virtio 1 devices");
#endif
/* wait for pending irq handlers */
void <API key>(struct virtio_device *vdev)
{
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
int i;
if (vp_dev->intx_enabled)
synchronize_irq(vp_dev->pci_dev->irq);
for (i = 0; i < vp_dev->msix_vectors; ++i)
synchronize_irq(pci_irq_vector(vp_dev->pci_dev, i));
}
/* the notify function used when creating a virt queue */
bool vp_notify(struct virtqueue *vq)
{
/* we write the queue's selector into the notification register to
* signal the other end */
iowrite16(vq->index, (void __iomem *)vq->priv);
return true;
}
/* Handle a configuration change: Tell driver if it wants to know. */
static irqreturn_t vp_config_changed(int irq, void *opaque)
{
struct virtio_pci_device *vp_dev = opaque;
<API key>(&vp_dev->vdev);
return IRQ_HANDLED;
}
/* Notify all virtqueues on an interrupt. */
static irqreturn_t vp_vring_interrupt(int irq, void *opaque)
{
struct virtio_pci_device *vp_dev = opaque;
struct virtio_pci_vq_info *info;
irqreturn_t ret = IRQ_NONE;
unsigned long flags;
spin_lock_irqsave(&vp_dev->lock, flags);
list_for_each_entry(info, &vp_dev->virtqueues, node) {
if (vring_interrupt(irq, info->vq) == IRQ_HANDLED)
ret = IRQ_HANDLED;
}
<API key>(&vp_dev->lock, flags);
return ret;
}
/* A small wrapper to also acknowledge the interrupt when it's handled.
* I really need an EIO hook for the vring so I can ack the interrupt once we
* know that we'll be handling the IRQ but before we invoke the callback since
* the callback may notify the host which results in the host attempting to
* raise an interrupt that we would then mask once we acknowledged the
* interrupt. */
static irqreturn_t vp_interrupt(int irq, void *opaque)
{
struct virtio_pci_device *vp_dev = opaque;
u8 isr;
/* reading the ISR has the effect of also clearing it so it's very
* important to save off the value. */
isr = ioread8(vp_dev->isr);
/* It's definitely not us if the ISR was not high */
if (!isr)
return IRQ_NONE;
/* Configuration change? Tell driver if it wants to know. */
if (isr & <API key>)
vp_config_changed(irq, opaque);
return vp_vring_interrupt(irq, opaque);
}
static int <API key>(struct virtio_device *vdev, int nvectors,
bool per_vq_vectors, struct irq_affinity *desc)
{
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
const char *name = dev_name(&vp_dev->vdev.dev);
unsigned flags = PCI_IRQ_MSIX;
unsigned i, v;
int err = -ENOMEM;
vp_dev->msix_vectors = nvectors;
vp_dev->msix_names = kmalloc_array(nvectors,
sizeof(*vp_dev->msix_names),
GFP_KERNEL);
if (!vp_dev->msix_names)
goto error;
vp_dev->msix_affinity_masks
= kcalloc(nvectors, sizeof(*vp_dev->msix_affinity_masks),
GFP_KERNEL);
if (!vp_dev->msix_affinity_masks)
goto error;
for (i = 0; i < nvectors; ++i)
if (!alloc_cpumask_var(&vp_dev->msix_affinity_masks[i],
GFP_KERNEL))
goto error;
if (desc) {
flags |= PCI_IRQ_AFFINITY;
desc->pre_vectors++; /* virtio config vector */
}
err = <API key>(vp_dev->pci_dev, nvectors,
nvectors, flags, desc);
if (err < 0)
goto error;
vp_dev->msix_enabled = 1;
/* Set the vector used for configuration */
v = vp_dev->msix_used_vectors;
snprintf(vp_dev->msix_names[v], sizeof *vp_dev->msix_names,
"%s-config", name);
err = request_irq(pci_irq_vector(vp_dev->pci_dev, v),
vp_config_changed, 0, vp_dev->msix_names[v],
vp_dev);
if (err)
goto error;
++vp_dev->msix_used_vectors;
v = vp_dev->config_vector(vp_dev, v);
/* Verify we had enough resources to assign the vector */
if (v == <API key>) {
err = -EBUSY;
goto error;
}
if (!per_vq_vectors) {
/* Shared vector for all VQs */
v = vp_dev->msix_used_vectors;
snprintf(vp_dev->msix_names[v], sizeof *vp_dev->msix_names,
"%s-virtqueues", name);
err = request_irq(pci_irq_vector(vp_dev->pci_dev, v),
vp_vring_interrupt, 0, vp_dev->msix_names[v],
vp_dev);
if (err)
goto error;
++vp_dev->msix_used_vectors;
}
return 0;
error:
return err;
}
static struct virtqueue *vp_setup_vq(struct virtio_device *vdev, unsigned index,
void (*callback)(struct virtqueue *vq),
const char *name,
bool ctx,
u16 msix_vec)
{
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
struct virtio_pci_vq_info *info = kmalloc(sizeof *info, GFP_KERNEL);
struct virtqueue *vq;
unsigned long flags;
/* fill out our structure that represents an active queue */
if (!info)
return ERR_PTR(-ENOMEM);
vq = vp_dev->setup_vq(vp_dev, info, index, callback, name, ctx,
msix_vec);
if (IS_ERR(vq))
goto out_info;
info->vq = vq;
if (callback) {
spin_lock_irqsave(&vp_dev->lock, flags);
list_add(&info->node, &vp_dev->virtqueues);
<API key>(&vp_dev->lock, flags);
} else {
INIT_LIST_HEAD(&info->node);
}
vp_dev->vqs[index] = info;
return vq;
out_info:
kfree(info);
return vq;
}
static void vp_del_vq(struct virtqueue *vq)
{
struct virtio_pci_device *vp_dev = to_vp_device(vq->vdev);
struct virtio_pci_vq_info *info = vp_dev->vqs[vq->index];
unsigned long flags;
spin_lock_irqsave(&vp_dev->lock, flags);
list_del(&info->node);
<API key>(&vp_dev->lock, flags);
vp_dev->del_vq(info);
kfree(info);
}
/* the config->del_vqs() implementation */
void vp_del_vqs(struct virtio_device *vdev)
{
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
struct virtqueue *vq, *n;
int i;
<API key>(vq, n, &vdev->vqs, list) {
if (vp_dev->per_vq_vectors) {
int v = vp_dev->vqs[vq->index]->msix_vector;
if (v != <API key>) {
int irq = pci_irq_vector(vp_dev->pci_dev, v);
<API key>(irq, NULL);
free_irq(irq, vq);
}
}
vp_del_vq(vq);
}
vp_dev->per_vq_vectors = false;
if (vp_dev->intx_enabled) {
free_irq(vp_dev->pci_dev->irq, vp_dev);
vp_dev->intx_enabled = 0;
}
for (i = 0; i < vp_dev->msix_used_vectors; ++i)
free_irq(pci_irq_vector(vp_dev->pci_dev, i), vp_dev);
for (i = 0; i < vp_dev->msix_vectors; i++)
if (vp_dev->msix_affinity_masks[i])
free_cpumask_var(vp_dev->msix_affinity_masks[i]);
if (vp_dev->msix_enabled) {
/* Disable the vector used for configuration */
vp_dev->config_vector(vp_dev, <API key>);
<API key>(vp_dev->pci_dev);
vp_dev->msix_enabled = 0;
}
vp_dev->msix_vectors = 0;
vp_dev->msix_used_vectors = 0;
kfree(vp_dev->msix_names);
vp_dev->msix_names = NULL;
kfree(vp_dev->msix_affinity_masks);
vp_dev->msix_affinity_masks = NULL;
kfree(vp_dev->vqs);
vp_dev->vqs = NULL;
}
static int vp_find_vqs_msix(struct virtio_device *vdev, unsigned nvqs,
struct virtqueue *vqs[], vq_callback_t *callbacks[],
const char * const names[], bool per_vq_vectors,
const bool *ctx,
struct irq_affinity *desc)
{
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
u16 msix_vec;
int i, err, nvectors, allocated_vectors;
vp_dev->vqs = kcalloc(nvqs, sizeof(*vp_dev->vqs), GFP_KERNEL);
if (!vp_dev->vqs)
return -ENOMEM;
if (per_vq_vectors) {
/* Best option: one for change interrupt, one per vq. */
nvectors = 1;
for (i = 0; i < nvqs; ++i)
if (callbacks[i])
++nvectors;
} else {
/* Second best: one for change, shared for all vqs. */
nvectors = 2;
}
err = <API key>(vdev, nvectors, per_vq_vectors,
per_vq_vectors ? desc : NULL);
if (err)
goto error_find;
vp_dev->per_vq_vectors = per_vq_vectors;
allocated_vectors = vp_dev->msix_used_vectors;
for (i = 0; i < nvqs; ++i) {
if (!names[i]) {
vqs[i] = NULL;
continue;
}
if (!callbacks[i])
msix_vec = <API key>;
else if (vp_dev->per_vq_vectors)
msix_vec = allocated_vectors++;
else
msix_vec = VP_MSIX_VQ_VECTOR;
vqs[i] = vp_setup_vq(vdev, i, callbacks[i], names[i],
ctx ? ctx[i] : false,
msix_vec);
if (IS_ERR(vqs[i])) {
err = PTR_ERR(vqs[i]);
goto error_find;
}
if (!vp_dev->per_vq_vectors || msix_vec == <API key>)
continue;
/* allocate per-vq irq if available and necessary */
snprintf(vp_dev->msix_names[msix_vec],
sizeof *vp_dev->msix_names,
"%s-%s",
dev_name(&vp_dev->vdev.dev), names[i]);
err = request_irq(pci_irq_vector(vp_dev->pci_dev, msix_vec),
vring_interrupt, 0,
vp_dev->msix_names[msix_vec],
vqs[i]);
if (err)
goto error_find;
}
return 0;
error_find:
vp_del_vqs(vdev);
return err;
}
static int vp_find_vqs_intx(struct virtio_device *vdev, unsigned nvqs,
struct virtqueue *vqs[], vq_callback_t *callbacks[],
const char * const names[], const bool *ctx)
{
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
int i, err;
vp_dev->vqs = kcalloc(nvqs, sizeof(*vp_dev->vqs), GFP_KERNEL);
if (!vp_dev->vqs)
return -ENOMEM;
err = request_irq(vp_dev->pci_dev->irq, vp_interrupt, IRQF_SHARED,
dev_name(&vdev->dev), vp_dev);
if (err)
goto out_del_vqs;
vp_dev->intx_enabled = 1;
vp_dev->per_vq_vectors = false;
for (i = 0; i < nvqs; ++i) {
if (!names[i]) {
vqs[i] = NULL;
continue;
}
vqs[i] = vp_setup_vq(vdev, i, callbacks[i], names[i],
ctx ? ctx[i] : false,
<API key>);
if (IS_ERR(vqs[i])) {
err = PTR_ERR(vqs[i]);
goto out_del_vqs;
}
}
return 0;
out_del_vqs:
vp_del_vqs(vdev);
return err;
}
/* the config->find_vqs() implementation */
int vp_find_vqs(struct virtio_device *vdev, unsigned nvqs,
struct virtqueue *vqs[], vq_callback_t *callbacks[],
const char * const names[], const bool *ctx,
struct irq_affinity *desc)
{
int err;
/* Try MSI-X with one vector per queue. */
err = vp_find_vqs_msix(vdev, nvqs, vqs, callbacks, names, true, ctx, desc);
if (!err)
return 0;
/* Fallback: MSI-X with one vector for config, one shared for queues. */
err = vp_find_vqs_msix(vdev, nvqs, vqs, callbacks, names, false, ctx, desc);
if (!err)
return 0;
/* Finally fall back to regular interrupts. */
return vp_find_vqs_intx(vdev, nvqs, vqs, callbacks, names, ctx);
}
const char *vp_bus_name(struct virtio_device *vdev)
{
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
return pci_name(vp_dev->pci_dev);
}
/* Setup the affinity for a virtqueue:
* - force the affinity for per vq vector
* - OR over all affinities for shared MSI
* - ignore the affinity request if we're using INTX
*/
int vp_set_vq_affinity(struct virtqueue *vq, const struct cpumask *cpu_mask)
{
struct virtio_device *vdev = vq->vdev;
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
struct virtio_pci_vq_info *info = vp_dev->vqs[vq->index];
struct cpumask *mask;
unsigned int irq;
if (!vq->callback)
return -EINVAL;
if (vp_dev->msix_enabled) {
mask = vp_dev->msix_affinity_masks[info->msix_vector];
irq = pci_irq_vector(vp_dev->pci_dev, info->msix_vector);
if (!cpu_mask)
<API key>(irq, NULL);
else {
cpumask_copy(mask, cpu_mask);
<API key>(irq, mask);
}
}
return 0;
}
const struct cpumask *vp_get_vq_affinity(struct virtio_device *vdev, int index)
{
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
if (!vp_dev->per_vq_vectors ||
vp_dev->vqs[index]->msix_vector == <API key>)
return NULL;
return <API key>(vp_dev->pci_dev,
vp_dev->vqs[index]->msix_vector);
}
#ifdef CONFIG_PM_SLEEP
static int virtio_pci_freeze(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct virtio_pci_device *vp_dev = pci_get_drvdata(pci_dev);
int ret;
ret = <API key>(&vp_dev->vdev);
if (!ret)
pci_disable_device(pci_dev);
return ret;
}
static int virtio_pci_restore(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct virtio_pci_device *vp_dev = pci_get_drvdata(pci_dev);
int ret;
ret = pci_enable_device(pci_dev);
if (ret)
return ret;
pci_set_master(pci_dev);
return <API key>(&vp_dev->vdev);
}
static const struct dev_pm_ops virtio_pci_pm_ops = {
<API key>(virtio_pci_freeze, virtio_pci_restore)
};
#endif
/* Qumranet donated their vendor ID for devices 0x1000 thru 0x10FF. */
static const struct pci_device_id virtio_pci_id_table[] = {
{ PCI_DEVICE(<API key>, PCI_ANY_ID) },
{ 0 }
};
MODULE_DEVICE_TABLE(pci, virtio_pci_id_table);
static void <API key>(struct device *_d)
{
struct virtio_device *vdev = dev_to_virtio(_d);
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
/* As struct device is a kobject, it's not safe to
* free the memory (including the reference counter itself)
* until it's release callback. */
kfree(vp_dev);
}
static int virtio_pci_probe(struct pci_dev *pci_dev,
const struct pci_device_id *id)
{
struct virtio_pci_device *vp_dev, *reg_dev = NULL;
int rc;
/* allocate our structure and fill it out */
vp_dev = kzalloc(sizeof(struct virtio_pci_device), GFP_KERNEL);
if (!vp_dev)
return -ENOMEM;
pci_set_drvdata(pci_dev, vp_dev);
vp_dev->vdev.dev.parent = &pci_dev->dev;
vp_dev->vdev.dev.release = <API key>;
vp_dev->pci_dev = pci_dev;
INIT_LIST_HEAD(&vp_dev->virtqueues);
spin_lock_init(&vp_dev->lock);
/* enable the device */
rc = pci_enable_device(pci_dev);
if (rc)
goto err_enable_device;
if (force_legacy) {
rc = <API key>(vp_dev);
/* Also try modern mode if we can't map BAR0 (no IO space). */
if (rc == -ENODEV || rc == -ENOMEM)
rc = <API key>(vp_dev);
if (rc)
goto err_probe;
} else {
rc = <API key>(vp_dev);
if (rc == -ENODEV)
rc = <API key>(vp_dev);
if (rc)
goto err_probe;
}
pci_set_master(pci_dev);
rc = <API key>(&vp_dev->vdev);
reg_dev = vp_dev;
if (rc)
goto err_register;
return 0;
err_register:
if (vp_dev->ioaddr)
<API key>(vp_dev);
else
<API key>(vp_dev);
err_probe:
pci_disable_device(pci_dev);
err_enable_device:
if (reg_dev)
put_device(&vp_dev->vdev.dev);
else
kfree(vp_dev);
return rc;
}
static void virtio_pci_remove(struct pci_dev *pci_dev)
{
struct virtio_pci_device *vp_dev = pci_get_drvdata(pci_dev);
struct device *dev = get_device(&vp_dev->vdev.dev);
pci_disable_sriov(pci_dev);
<API key>(&vp_dev->vdev);
if (vp_dev->ioaddr)
<API key>(vp_dev);
else
<API key>(vp_dev);
pci_disable_device(pci_dev);
put_device(dev);
}
static int <API key>(struct pci_dev *pci_dev, int num_vfs)
{
struct virtio_pci_device *vp_dev = pci_get_drvdata(pci_dev);
struct virtio_device *vdev = &vp_dev->vdev;
int ret;
if (!(vdev->config->get_status(vdev) & <API key>))
return -EBUSY;
if (!__virtio_test_bit(vdev, VIRTIO_F_SR_IOV))
return -EINVAL;
if (pci_vfs_assigned(pci_dev))
return -EPERM;
if (num_vfs == 0) {
pci_disable_sriov(pci_dev);
return 0;
}
ret = pci_enable_sriov(pci_dev, num_vfs);
if (ret < 0)
return ret;
return num_vfs;
}
static struct pci_driver virtio_pci_driver = {
.name = "virtio-pci",
.id_table = virtio_pci_id_table,
.probe = virtio_pci_probe,
.remove = virtio_pci_remove,
#ifdef CONFIG_PM_SLEEP
.driver.pm = &virtio_pci_pm_ops,
#endif
.sriov_configure = <API key>,
};
module_pci_driver(virtio_pci_driver);
MODULE_AUTHOR("Anthony Liguori <aliguori@us.ibm.com>");
MODULE_DESCRIPTION("virtio-pci");
MODULE_LICENSE("GPL");
MODULE_VERSION("1"); |
// 2005-02-27 Douglas Gregor <doug.gregor -at- gmail.com>
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// with this library; see the file COPYING3. If not see
// 2.1 reference wrappers
#include <tr1/functional>
#include <tr1/type_traits>
#include <testsuite_hooks.h>
#include <testsuite_tr1.h>
using namespace __gnu_test;
struct X {};
struct int_result_type { typedef int result_type; };
struct derives_unary : std::unary_function<int, int> {};
struct derives_binary : std::binary_function<int, float, int> {};
struct <API key>
: std::unary_function<int, int>,
std::binary_function<int, float, int>
{
typedef int result_type;
};
void test01()
{
bool test __attribute__((unused)) = true;
using std::tr1::reference_wrapper;
using std::tr1::is_same;
using std::tr1::is_convertible;
using std::unary_function;
using std::binary_function;
// Check result_type typedef
VERIFY((is_same<reference_wrapper<int_result_type>::result_type, int>::value));
VERIFY((is_same<reference_wrapper<derives_unary>::result_type, int>::value));
VERIFY((is_same<reference_wrapper<derives_binary>::result_type, int>::value));
VERIFY((is_same<reference_wrapper<<API key>>::result_type, int>::value));
VERIFY((is_same<reference_wrapper<int(void)>::result_type, int>::value));
VERIFY((is_same<reference_wrapper<int(*)(void)>::result_type, int>::value));
VERIFY((is_same<reference_wrapper<int (::X::*)()>::result_type, int>::value));
VERIFY((is_same<reference_wrapper<int (::X::*)(float)>::result_type, int>::value));
// Check derivation from unary_function
VERIFY((is_convertible<reference_wrapper<derives_unary>*, unary_function<int, int>*>::value));
VERIFY((is_convertible<reference_wrapper<<API key>>*, unary_function<int, int>*>::value));
VERIFY((is_convertible<reference_wrapper<int(int)>*, unary_function<int, int>*>::value));
VERIFY((is_convertible<reference_wrapper<int(*)(int)>*, unary_function<int, int>*>::value));
VERIFY((is_convertible<reference_wrapper<int (::X::*)()>*, unary_function< ::X*, int>*>::value));
VERIFY((is_convertible<reference_wrapper<int (::X::*)() const>*, unary_function<const ::X*, int>*>::value));
VERIFY((is_convertible<reference_wrapper<int (::X::*)() volatile>*, unary_function<volatile ::X*, int>*>::value));
VERIFY((is_convertible<reference_wrapper<int (::X::*)() const volatile>*, unary_function<const volatile ::X*, int>*>::value));
// Check derivation from binary_function
VERIFY((is_convertible<reference_wrapper<derives_binary>*, binary_function<int, float, int>*>::value));
VERIFY((is_convertible<reference_wrapper<<API key>>*, binary_function<int, float, int>*>::value));
VERIFY((is_convertible<reference_wrapper<int(int, float)>*, binary_function<int, float, int>*>::value));
VERIFY((is_convertible<reference_wrapper<int(*)(int, float)>*, binary_function<int, float, int>*>::value));
VERIFY((is_convertible<reference_wrapper<int (::X::*)(float)>*, binary_function< ::X*, float, int>*>::value));
VERIFY((is_convertible<reference_wrapper<int (::X::*)(float) const>*, binary_function<const ::X*, float, int>*>::value));
VERIFY((is_convertible<reference_wrapper<int (::X::*)(float) volatile>*, binary_function<volatile ::X*, float, int>*>::value));
VERIFY((is_convertible<reference_wrapper<int (::X::*)(float) const volatile>*, binary_function<const volatile ::X*, float, int>*>::value));
}
int main()
{
test01();
return 0;
} |
#include "qemu-common.h"
#include "usb.h"
#include "usb-desc.h"
#include "net.h"
#include "bt.h"
struct USBBtState {
USBDevice dev;
struct HCIInfo *hci;
int altsetting;
int config;
#define CFIFO_LEN_MASK 255
#define DFIFO_LEN_MASK 4095
struct usb_hci_in_fifo_s {
uint8_t data[(DFIFO_LEN_MASK + 1) * 2];
struct {
uint8_t *data;
int len;
} fifo[CFIFO_LEN_MASK + 1];
int dstart, dlen, dsize, start, len;
} evt, acl, sco;
struct usb_hci_out_fifo_s {
uint8_t data[4096];
int len;
} outcmd, outacl, outsco;
};
#define USB_EVT_EP 1
#define USB_ACL_EP 2
#define USB_SCO_EP 3
enum {
STR_MANUFACTURER = 1,
STR_SERIALNUMBER,
};
static const USBDescStrings desc_strings = {
[STR_MANUFACTURER] = "QEMU " QEMU_VERSION,
[STR_SERIALNUMBER] = "1",
};
static const USBDescIface <API key>[] = {
{
.bInterfaceNumber = 0,
.bNumEndpoints = 3,
.bInterfaceClass = 0xe0, /* Wireless */
.bInterfaceSubClass = 0x01, /* Radio Frequency */
.bInterfaceProtocol = 0x01, /* Bluetooth */
.eps = (USBDescEndpoint[]) {
{
.bEndpointAddress = USB_DIR_IN | USB_EVT_EP,
.bmAttributes = <API key>,
.wMaxPacketSize = 0x10,
.bInterval = 0x02,
},
{
.bEndpointAddress = USB_DIR_OUT | USB_ACL_EP,
.bmAttributes = <API key>,
.wMaxPacketSize = 0x40,
.bInterval = 0x0a,
},
{
.bEndpointAddress = USB_DIR_IN | USB_ACL_EP,
.bmAttributes = <API key>,
.wMaxPacketSize = 0x40,
.bInterval = 0x0a,
},
},
},{
.bInterfaceNumber = 1,
.bAlternateSetting = 0,
.bNumEndpoints = 2,
.bInterfaceClass = 0xe0, /* Wireless */
.bInterfaceSubClass = 0x01, /* Radio Frequency */
.bInterfaceProtocol = 0x01, /* Bluetooth */
.eps = (USBDescEndpoint[]) {
{
.bEndpointAddress = USB_DIR_OUT | USB_SCO_EP,
.bmAttributes = <API key>,
.wMaxPacketSize = 0,
.bInterval = 0x01,
},
{
.bEndpointAddress = USB_DIR_IN | USB_SCO_EP,
.bmAttributes = <API key>,
.wMaxPacketSize = 0,
.bInterval = 0x01,
},
},
},{
.bInterfaceNumber = 1,
.bAlternateSetting = 1,
.bNumEndpoints = 2,
.bInterfaceClass = 0xe0, /* Wireless */
.bInterfaceSubClass = 0x01, /* Radio Frequency */
.bInterfaceProtocol = 0x01, /* Bluetooth */
.eps = (USBDescEndpoint[]) {
{
.bEndpointAddress = USB_DIR_OUT | USB_SCO_EP,
.bmAttributes = <API key>,
.wMaxPacketSize = 0x09,
.bInterval = 0x01,
},
{
.bEndpointAddress = USB_DIR_IN | USB_SCO_EP,
.bmAttributes = <API key>,
.wMaxPacketSize = 0x09,
.bInterval = 0x01,
},
},
},{
.bInterfaceNumber = 1,
.bAlternateSetting = 2,
.bNumEndpoints = 2,
.bInterfaceClass = 0xe0, /* Wireless */
.bInterfaceSubClass = 0x01, /* Radio Frequency */
.bInterfaceProtocol = 0x01, /* Bluetooth */
.eps = (USBDescEndpoint[]) {
{
.bEndpointAddress = USB_DIR_OUT | USB_SCO_EP,
.bmAttributes = <API key>,
.wMaxPacketSize = 0x11,
.bInterval = 0x01,
},
{
.bEndpointAddress = USB_DIR_IN | USB_SCO_EP,
.bmAttributes = <API key>,
.wMaxPacketSize = 0x11,
.bInterval = 0x01,
},
},
},{
.bInterfaceNumber = 1,
.bAlternateSetting = 3,
.bNumEndpoints = 2,
.bInterfaceClass = 0xe0, /* Wireless */
.bInterfaceSubClass = 0x01, /* Radio Frequency */
.bInterfaceProtocol = 0x01, /* Bluetooth */
.eps = (USBDescEndpoint[]) {
{
.bEndpointAddress = USB_DIR_OUT | USB_SCO_EP,
.bmAttributes = <API key>,
.wMaxPacketSize = 0x19,
.bInterval = 0x01,
},
{
.bEndpointAddress = USB_DIR_IN | USB_SCO_EP,
.bmAttributes = <API key>,
.wMaxPacketSize = 0x19,
.bInterval = 0x01,
},
},
},{
.bInterfaceNumber = 1,
.bAlternateSetting = 4,
.bNumEndpoints = 2,
.bInterfaceClass = 0xe0, /* Wireless */
.bInterfaceSubClass = 0x01, /* Radio Frequency */
.bInterfaceProtocol = 0x01, /* Bluetooth */
.eps = (USBDescEndpoint[]) {
{
.bEndpointAddress = USB_DIR_OUT | USB_SCO_EP,
.bmAttributes = <API key>,
.wMaxPacketSize = 0x21,
.bInterval = 0x01,
},
{
.bEndpointAddress = USB_DIR_IN | USB_SCO_EP,
.bmAttributes = <API key>,
.wMaxPacketSize = 0x21,
.bInterval = 0x01,
},
},
},{
.bInterfaceNumber = 1,
.bAlternateSetting = 5,
.bNumEndpoints = 2,
.bInterfaceClass = 0xe0, /* Wireless */
.bInterfaceSubClass = 0x01, /* Radio Frequency */
.bInterfaceProtocol = 0x01, /* Bluetooth */
.eps = (USBDescEndpoint[]) {
{
.bEndpointAddress = USB_DIR_OUT | USB_SCO_EP,
.bmAttributes = <API key>,
.wMaxPacketSize = 0x31,
.bInterval = 0x01,
},
{
.bEndpointAddress = USB_DIR_IN | USB_SCO_EP,
.bmAttributes = <API key>,
.wMaxPacketSize = 0x31,
.bInterval = 0x01,
},
},
}
};
static const USBDescDevice <API key> = {
.bcdUSB = 0x0110,
.bDeviceClass = 0xe0, /* Wireless */
.bDeviceSubClass = 0x01, /* Radio Frequency */
.bDeviceProtocol = 0x01, /* Bluetooth */
.bMaxPacketSize0 = 64,
.bNumConfigurations = 1,
.confs = (USBDescConfig[]) {
{
.bNumInterfaces = 2,
.bConfigurationValue = 1,
.bmAttributes = 0xc0,
.bMaxPower = 0,
.nif = ARRAY_SIZE(<API key>),
.ifs = <API key>,
},
},
};
static const USBDesc desc_bluetooth = {
.id = {
.idVendor = 0x0a12,
.idProduct = 0x0001,
.bcdDevice = 0x1958,
.iManufacturer = STR_MANUFACTURER,
.iProduct = 0,
.iSerialNumber = STR_SERIALNUMBER,
},
.full = &<API key>,
.str = desc_strings,
};
static void usb_bt_fifo_reset(struct usb_hci_in_fifo_s *fifo)
{
fifo->dstart = 0;
fifo->dlen = 0;
fifo->dsize = DFIFO_LEN_MASK + 1;
fifo->start = 0;
fifo->len = 0;
}
static void usb_bt_fifo_enqueue(struct usb_hci_in_fifo_s *fifo,
const uint8_t *data, int len)
{
int off = fifo->dstart + fifo->dlen;
uint8_t *buf;
fifo->dlen += len;
if (off <= DFIFO_LEN_MASK) {
if (off + len > DFIFO_LEN_MASK + 1 &&
(fifo->dsize = off + len) > (DFIFO_LEN_MASK + 1) * 2) {
fprintf(stderr, "%s: can't alloc %i bytes\n", __FUNCTION__, len);
exit(-1);
}
buf = fifo->data + off;
} else {
if (fifo->dlen > fifo->dsize) {
fprintf(stderr, "%s: can't alloc %i bytes\n", __FUNCTION__, len);
exit(-1);
}
buf = fifo->data + off - fifo->dsize;
}
off = (fifo->start + fifo->len ++) & CFIFO_LEN_MASK;
fifo->fifo[off].data = memcpy(buf, data, len);
fifo->fifo[off].len = len;
}
static inline int usb_bt_fifo_dequeue(struct usb_hci_in_fifo_s *fifo,
USBPacket *p)
{
int len;
if (likely(!fifo->len))
return USB_RET_STALL;
len = MIN(p->iov.size, fifo->fifo[fifo->start].len);
usb_packet_copy(p, fifo->fifo[fifo->start].data, len);
if (len == p->iov.size) {
fifo->fifo[fifo->start].len -= len;
fifo->fifo[fifo->start].data += len;
} else {
fifo->start ++;
fifo->start &= CFIFO_LEN_MASK;
fifo->len
}
fifo->dstart += len;
fifo->dlen -= len;
if (fifo->dstart >= fifo->dsize) {
fifo->dstart = 0;
fifo->dsize = DFIFO_LEN_MASK + 1;
}
return len;
}
static inline void <API key>(struct USBBtState *s,
struct usb_hci_out_fifo_s *fifo,
void (*send)(struct HCIInfo *, const uint8_t *, int),
int (*complete)(const uint8_t *, int),
USBPacket *p)
{
usb_packet_copy(p, fifo->data + fifo->len, p->iov.size);
fifo->len += p->iov.size;
if (complete(fifo->data, fifo->len)) {
send(s->hci, fifo->data, fifo->len);
fifo->len = 0;
}
/* TODO: do we need to loop? */
}
static int <API key>(const uint8_t *data, int len)
{
len -= <API key>;
return len >= 0 &&
len >= ((struct hci_command_hdr *) data)->plen;
}
static int <API key>(const uint8_t *data, int len)
{
len -= HCI_ACL_HDR_SIZE;
return len >= 0 &&
len >= le16_to_cpu(((struct hci_acl_hdr *) data)->dlen);
}
static int <API key>(const uint8_t *data, int len)
{
len -= HCI_SCO_HDR_SIZE;
return len >= 0 &&
len >= ((struct hci_sco_hdr *) data)->dlen;
}
static void usb_bt_handle_reset(USBDevice *dev)
{
struct USBBtState *s = (struct USBBtState *) dev->opaque;
usb_bt_fifo_reset(&s->evt);
usb_bt_fifo_reset(&s->acl);
usb_bt_fifo_reset(&s->sco);
s->outcmd.len = 0;
s->outacl.len = 0;
s->outsco.len = 0;
s->altsetting = 0;
}
static int <API key>(USBDevice *dev, USBPacket *p,
int request, int value, int index, int length, uint8_t *data)
{
struct USBBtState *s = (struct USBBtState *) dev->opaque;
int ret;
ret = <API key>(dev, p, request, value, index, length, data);
if (ret >= 0) {
switch (request) {
case DeviceRequest | <API key>:
s->config = 0;
break;
case DeviceOutRequest | <API key>:
s->config = 1;
usb_bt_fifo_reset(&s->evt);
usb_bt_fifo_reset(&s->acl);
usb_bt_fifo_reset(&s->sco);
break;
}
return ret;
}
ret = 0;
switch (request) {
case InterfaceRequest | USB_REQ_GET_STATUS:
case EndpointRequest | USB_REQ_GET_STATUS:
data[0] = 0x00;
data[1] = 0x00;
ret = 2;
break;
case InterfaceOutRequest | <API key>:
case EndpointOutRequest | <API key>:
goto fail;
case InterfaceOutRequest | USB_REQ_SET_FEATURE:
case EndpointOutRequest | USB_REQ_SET_FEATURE:
goto fail;
break;
case InterfaceRequest | <API key>:
if (value != 0 || (index & ~1) || length != 1)
goto fail;
if (index == 1)
data[0] = s->altsetting;
else
data[0] = 0;
ret = 1;
break;
case InterfaceOutRequest | <API key>:
if ((index & ~1) || length != 0 ||
(index == 1 && (value < 0 || value > 4)) ||
(index == 0 && value != 0)) {
printf("%s: Wrong SET_INTERFACE request (%i, %i)\n",
__FUNCTION__, index, value);
goto fail;
}
s->altsetting = value;
ret = 0;
break;
case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_DEVICE) << 8):
if (s->config)
<API key>(s, &s->outcmd, s->hci->cmd_send,
<API key>, p);
break;
default:
fail:
ret = USB_RET_STALL;
break;
}
return ret;
}
static int usb_bt_handle_data(USBDevice *dev, USBPacket *p)
{
struct USBBtState *s = (struct USBBtState *) dev->opaque;
int ret = 0;
if (!s->config)
goto fail;
switch (p->pid) {
case USB_TOKEN_IN:
switch (p->devep & 0xf) {
case USB_EVT_EP:
ret = usb_bt_fifo_dequeue(&s->evt, p);
break;
case USB_ACL_EP:
ret = usb_bt_fifo_dequeue(&s->acl, p);
break;
case USB_SCO_EP:
ret = usb_bt_fifo_dequeue(&s->sco, p);
break;
default:
goto fail;
}
break;
case USB_TOKEN_OUT:
switch (p->devep & 0xf) {
case USB_ACL_EP:
<API key>(s, &s->outacl, s->hci->acl_send,
<API key>, p);
break;
case USB_SCO_EP:
<API key>(s, &s->outsco, s->hci->sco_send,
<API key>, p);
break;
default:
goto fail;
}
break;
default:
fail:
ret = USB_RET_STALL;
break;
}
return ret;
}
static void <API key>(void *opaque,
const uint8_t *data, int len)
{
struct USBBtState *s = (struct USBBtState *) opaque;
usb_bt_fifo_enqueue(&s->evt, data, len);
}
static void <API key>(void *opaque,
const uint8_t *data, int len)
{
struct USBBtState *s = (struct USBBtState *) opaque;
usb_bt_fifo_enqueue(&s->acl, data, len);
}
static void <API key>(USBDevice *dev)
{
struct USBBtState *s = (struct USBBtState *) dev->opaque;
s->hci->opaque = NULL;
s->hci->evt_recv = NULL;
s->hci->acl_recv = NULL;
}
static int usb_bt_initfn(USBDevice *dev)
{
usb_desc_init(dev);
return 0;
}
USBDevice *usb_bt_init(HCIInfo *hci)
{
USBDevice *dev;
struct USBBtState *s;
if (!hci)
return NULL;
dev = usb_create_simple(NULL /* FIXME */, "usb-bt-dongle");
if (!dev) {
return NULL;
}
s = DO_UPCAST(struct USBBtState, dev, dev);
s->dev.opaque = s;
s->hci = hci;
s->hci->opaque = s;
s->hci->evt_recv = <API key>;
s->hci->acl_recv = <API key>;
usb_bt_handle_reset(&s->dev);
return dev;
}
static const VMStateDescription vmstate_usb_bt = {
.name = "usb-bt",
.unmigratable = 1,
};
static struct USBDeviceInfo bt_info = {
.product_desc = "QEMU BT dongle",
.qdev.name = "usb-bt-dongle",
.qdev.size = sizeof(struct USBBtState),
.qdev.vmsd = &vmstate_usb_bt,
.usb_desc = &desc_bluetooth,
.init = usb_bt_initfn,
.handle_packet = <API key>,
.handle_reset = usb_bt_handle_reset,
.handle_control = <API key>,
.handle_data = usb_bt_handle_data,
.handle_destroy = <API key>,
};
static void <API key>(void)
{
usb_qdev_register(&bt_info);
}
device_init(<API key>) |
<%! from capa.util import remove_markup %>
<div id="<API key>${id}" class="<API key>">
<div class="script_placeholder" data-src="${previewer}"/>
<div class="${status.classname}">
<input type="text" name="input_${id}" id="input_${id}" aria-label="${remove_markup(response_data['label'])}"
aria-describedby="answer_${id}" data-input-id="${id}" value="${value|h}"
% if size:
size="${size}"
% endif
/>
<p class="indicator-container">
${value|h}
<%include file="status_span.html" args="status=status, status_id=id"/>
</p>
<div id="input_${id}_preview" class="equation"></div>
<p id="answer_${id}" class="answer"></p>
</div>
</div> |
<?php
namespace PhpOffice\PhpSpreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
abstract class DefinedName
{
protected const <API key> = '[^_\p{N}\p{L}:, \$\'!]';
/**
* Name.
*
* @var string
*/
protected $name;
/**
* Worksheet on which the defined name can be resolved.
*
* @var Worksheet
*/
protected $worksheet;
/**
* Value of the named object.
*
* @var string
*/
protected $value;
/**
* Is the defined named local? (i.e. can only be used on $this->worksheet).
*
* @var bool
*/
protected $localOnly;
/**
* Scope.
*
* @var Worksheet
*/
protected $scope;
/**
* Whether this is a named range or a named formula.
*
* @var bool
*/
protected $isFormula;
/**
* Create a new Defined Name.
*/
public function __construct(
string $name,
?Worksheet $worksheet = null,
?string $value = null,
bool $localOnly = false,
?Worksheet $scope = null
) {
if ($worksheet === null) {
$worksheet = $scope;
}
// Set local members
$this->name = $name;
$this->worksheet = $worksheet;
$this->value = (string) $value;
$this->localOnly = $localOnly;
// If local only, then the scope will be set to worksheet unless a scope is explicitly set
$this->scope = ($localOnly === true) ? (($scope === null) ? $worksheet : $scope) : null;
// If the range string contains characters that aren't associated with the range definition (A-Z,1-9
// for cell references, and $, or the range operators (colon comma or space), quotes and ! for
// worksheet names
// then this is treated as a named formula, and not a named range
$this->isFormula = self::testIfFormula($this->value);
}
/**
* Create a new defined name, either a range or a formula.
*/
public static function createInstance(
string $name,
?Worksheet $worksheet = null,
?string $value = null,
bool $localOnly = false,
?Worksheet $scope = null
): self {
$value = (string) $value;
$isFormula = self::testIfFormula($value);
if ($isFormula) {
return new NamedFormula($name, $worksheet, $value, $localOnly, $scope);
}
return new NamedRange($name, $worksheet, $value, $localOnly, $scope);
}
public static function testIfFormula(string $value): bool
{
if (substr($value, 0, 1) === '=') {
$value = substr($value, 1);
}
if (is_numeric($value)) {
return true;
}
$segMatcher = false;
foreach (explode("'", $value) as $subVal) {
// Only test in alternate array entries (the non-quoted blocks)
if (
($segMatcher = !$segMatcher) &&
(preg_match('/' . self::<API key> . '/miu', $subVal))
) {
return true;
}
}
return false;
}
/**
* Get name.
*/
public function getName(): string
{
return $this->name;
}
/**
* Set name.
*/
public function setName(string $name): self
{
if (!empty($name)) {
// Old title
$oldTitle = $this->name;
// Re-attach
if ($this->worksheet !== null) {
$this->worksheet->getParent()->removeNamedRange($this->name, $this->worksheet);
}
$this->name = $name;
if ($this->worksheet !== null) {
$this->worksheet->getParent()->addNamedRange($this);
}
// New title
$newTitle = $this->name;
ReferenceHelper::getInstance()->updateNamedFormulas($this->worksheet->getParent(), $oldTitle, $newTitle);
}
return $this;
}
/**
* Get worksheet.
*/
public function getWorksheet(): ?Worksheet
{
return $this->worksheet;
}
/**
* Set worksheet.
*/
public function setWorksheet(?Worksheet $value): self
{
$this->worksheet = $value;
return $this;
}
/**
* Get range or formula value.
*/
public function getValue(): string
{
return $this->value;
}
/**
* Set range or formula value.
*/
public function setValue(string $value): self
{
$this->value = $value;
return $this;
}
/**
* Get localOnly.
*/
public function getLocalOnly(): bool
{
return $this->localOnly;
}
/**
* Set localOnly.
*/
public function setLocalOnly(bool $value): self
{
$this->localOnly = $value;
$this->scope = $value ? $this->worksheet : null;
return $this;
}
/**
* Get scope.
*/
public function getScope(): ?Worksheet
{
return $this->scope;
}
/**
* Set scope.
*/
public function setScope(?Worksheet $value): self
{
$this->scope = $value;
$this->localOnly = $value !== null;
return $this;
}
/**
* Identify whether this is a named range or a named formula.
*/
public function isFormula(): bool
{
return $this->isFormula;
}
/**
* Resolve a named range to a regular cell range or formula.
*/
public static function resolveName(string $pDefinedName, Worksheet $pSheet): ?self
{
return $pSheet->getParent()->getDefinedName($pDefinedName, $pSheet);
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
} |
// @(#)root/g3d:$Id$
// TMaterial //
// Materials used in the Geometry Shapes //
#ifndef ROOT_TMaterial
#define ROOT_TMaterial
#ifndef ROOT_TNamed
#include "TNamed.h"
#endif
#ifndef ROOT_TAttFill
#include "TAttFill.h"
#endif
class TMaterial : public TNamed, public TAttFill {
protected:
Int_t fNumber; //Material matrix number
Float_t fA; //A of Material
Float_t fZ; //Z of Material
Float_t fDensity; //Material density in gr/cm3
Float_t fRadLength; //Material radiation length
Float_t fInterLength; //Material interaction length
public:
TMaterial();
TMaterial(const char *name, const char *title, Float_t a, Float_t z, Float_t density);
TMaterial(const char *name, const char *title, Float_t a, Float_t z, Float_t density, Float_t radl, Float_t inter);
virtual ~TMaterial();
virtual Int_t GetNumber() const {return fNumber;}
virtual Float_t GetA() const {return fA;}
virtual Float_t GetZ() const {return fZ;}
virtual Float_t GetDensity() const {return fDensity;}
virtual Float_t GetRadLength() const {return fRadLength;}
virtual Float_t GetInterLength() const {return fInterLength;}
ClassDef(TMaterial,3) //Materials used in the Geometry Shapes
};
#endif |
/**
* @module
* @description
* Change detection enables data binding in Angular.
*/
export {<API key>, ChangeDetectorRef, <API key>, <API key>, <API key>, IterableChanges, IterableDiffer, <API key>, IterableDiffers, <API key>, KeyValueChanges, KeyValueDiffer, <API key>, KeyValueDiffers, NgIterable, PipeTransform, SimpleChange, SimpleChanges, TrackByFunction, WrappedValue} from './change_detection/change_detection'; |
// This library implements a cron spec parser and runner. See the README for
// more details.
package cron
import (
"log"
"runtime"
"sort"
"time"
)
// Cron keeps track of any number of entries, invoking the associated func as
// specified by the schedule. It may be started, stopped, and the entries may
// be inspected while running.
type Cron struct {
entries []*Entry
stop chan struct{}
add chan *Entry
snapshot chan []*Entry
running bool
ErrorLog *log.Logger
}
// Job is an interface for submitted cron jobs.
type Job interface {
Run()
}
// The Schedule describes a job's duty cycle.
type Schedule interface {
// Return the next activation time, later than the given time.
// Next is invoked initially, and then each time the job is run.
Next(time.Time) time.Time
}
// Entry consists of a schedule and the func to execute on that schedule.
type Entry struct {
Description string
Spec string
// The schedule on which this job should be run.
Schedule Schedule
// The next time the job will run. This is the zero time if Cron has not been
// started or this entry's schedule is unsatisfiable
Next time.Time
// The last time this job was run. This is the zero time if the job has never
// been run.
Prev time.Time
// The Job to run.
Job Job
ExecTimes int // Execute times count.
}
// byTime is a wrapper for sorting the entry array by time
// (with zero time at the end).
type byTime []*Entry
func (s byTime) Len() int { return len(s) }
func (s byTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s byTime) Less(i, j int) bool {
// Two zero times should return false.
// Otherwise, zero is "greater" than any other time.
// (To sort it at the end of the list.)
if s[i].Next.IsZero() {
return false
}
if s[j].Next.IsZero() {
return true
}
return s[i].Next.Before(s[j].Next)
}
// New returns a new Cron job runner.
func New() *Cron {
return &Cron{
entries: nil,
add: make(chan *Entry),
stop: make(chan struct{}),
snapshot: make(chan []*Entry),
running: false,
ErrorLog: nil,
}
}
// A wrapper that turns a func() into a cron.Job
type FuncJob func()
func (f FuncJob) Run() { f() }
// AddFunc adds a func to the Cron to be run on the given schedule.
func (c *Cron) AddFunc(desc, spec string, cmd func()) (*Entry, error) {
return c.AddJob(desc, spec, FuncJob(cmd))
}
// AddJob adds a Job to the Cron to be run on the given schedule.
func (c *Cron) AddJob(desc, spec string, cmd Job) (*Entry, error) {
schedule, err := Parse(spec)
if err != nil {
return nil, err
}
return c.Schedule(desc, spec, schedule, cmd), nil
}
// Schedule adds a Job to the Cron to be run on the given schedule.
func (c *Cron) Schedule(desc, spec string, schedule Schedule, cmd Job) *Entry {
entry := &Entry{
Description: desc,
Spec: spec,
Schedule: schedule,
Job: cmd,
}
if c.running {
c.add <- entry
} else {
c.entries = append(c.entries, entry)
}
return entry
}
// Entries returns a snapshot of the cron entries.
func (c *Cron) Entries() []*Entry {
if c.running {
c.snapshot <- nil
x := <-c.snapshot
return x
}
return c.entrySnapshot()
}
// Start the cron scheduler in its own go-routine, or no-op if already started.
func (c *Cron) Start() {
if c.running {
return
}
c.running = true
go c.run()
}
func (c *Cron) runWithRecovery(j Job) {
defer func() {
if r := recover(); r != nil {
const size = 64 << 10
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)]
c.logf("cron: panic running job: %v\n%s", r, buf)
}
}()
j.Run()
}
// Run the scheduler.. this is private just due to the need to synchronize
// access to the 'running' state variable.
func (c *Cron) run() {
// Figure out the next activation times for each entry.
now := time.Now().Local()
for _, entry := range c.entries {
entry.Next = entry.Schedule.Next(now)
}
for {
// Determine the next entry to run.
sort.Sort(byTime(c.entries))
var effective time.Time
if len(c.entries) == 0 || c.entries[0].Next.IsZero() {
// If there are no entries yet, just sleep - it still handles new entries
// and stop requests.
effective = now.AddDate(10, 0, 0)
} else {
effective = c.entries[0].Next
}
timer := time.NewTimer(effective.Sub(now))
select {
case now = <-timer.C:
// Run every entry whose next time was this effective time.
for _, e := range c.entries {
if e.Next != effective {
break
}
go c.runWithRecovery(e.Job)
e.ExecTimes++
e.Prev = e.Next
e.Next = e.Schedule.Next(now)
}
continue
case newEntry := <-c.add:
c.entries = append(c.entries, newEntry)
newEntry.Next = newEntry.Schedule.Next(time.Now().Local())
case <-c.snapshot:
c.snapshot <- c.entrySnapshot()
case <-c.stop:
timer.Stop()
return
}
// 'now' should be updated after newEntry and snapshot cases.
now = time.Now().Local()
timer.Stop()
}
}
// Logs an error to stderr or to the configured error log
func (c *Cron) logf(format string, args ...interface{}) {
if c.ErrorLog != nil {
c.ErrorLog.Printf(format, args...)
} else {
log.Printf(format, args...)
}
}
// Stop stops the cron scheduler if it is running; otherwise it does nothing.
func (c *Cron) Stop() {
if !c.running {
return
}
c.stop <- struct{}{}
c.running = false
}
// entrySnapshot returns a copy of the current cron entry list.
func (c *Cron) entrySnapshot() []*Entry {
entries := []*Entry{}
for _, e := range c.entries {
entries = append(entries, &Entry{
Description: e.Description,
Spec: e.Spec,
Schedule: e.Schedule,
Next: e.Next,
Prev: e.Prev,
Job: e.Job,
ExecTimes: e.ExecTimes,
})
}
return entries
} |
// Bot
// class for performing various twitter actions
var Twit = require('../lib/twitter');
var Bot = module.exports = function(config) {
this.twit = new Twit(config);
};
// post a tweet
Bot.prototype.tweet = function (status, callback) {
if(typeof status !== 'string') {
return callback(new Error('tweet must be of type String'));
} else if(status.length > 140) {
return callback(new Error('tweet is too long: ' + status.length));
}
this.twit.post('statuses/update', { status: status }, callback);
};
// choose a random tweet and follow that user
Bot.prototype.searchFollow = function (params, callback) {
var self = this;
self.twit.get('search/tweets', params, function (err, reply) {
if(err) return callback(err);
var tweets = reply.statuses;
var rTweet = randIndex(tweets)
if(typeof rTweet != 'undefined')
{
var target = rTweet.user.id_str;
self.twit.post('friendships/create', { id: target }, callback);
}
});
};
// retweet
Bot.prototype.retweet = function (params, callback) {
var self = this;
self.twit.get('search/tweets', params, function (err, reply) {
if(err) return callback(err);
var tweets = reply.statuses;
var randomTweet = randIndex(tweets);
if(typeof randomTweet != 'undefined')
self.twit.post('statuses/retweet/:id', { id: randomTweet.id_str }, callback);
});
};
// favorite a tweet
Bot.prototype.favorite = function (params, callback) {
var self = this;
self.twit.get('search/tweets', params, function (err, reply) {
if(err) return callback(err);
var tweets = reply.statuses;
var randomTweet = randIndex(tweets);
if(typeof randomTweet != 'undefined')
self.twit.post('favorites/create', { id: randomTweet.id_str }, callback);
});
};
// choose a random friend of one of your followers, and follow that user
Bot.prototype.mingle = function (callback) {
var self = this;
this.twit.get('followers/ids', function(err, reply) {
if(err) { return callback(err); }
var followers = reply.ids
, randFollower = randIndex(followers);
self.twit.get('friends/ids', { user_id: randFollower }, function(err, reply) {
if(err) { return callback(err); }
var friends = reply.ids
, target = randIndex(friends);
self.twit.post('friendships/create', { id: target }, callback);
})
})
};
// prune your followers list; unfollow a friend that hasn't followed you back
Bot.prototype.prune = function (callback) {
var self = this;
this.twit.get('followers/ids', function(err, reply) {
if(err) return callback(err);
var followers = reply.ids;
self.twit.get('friends/ids', function(err, reply) {
if(err) return callback(err);
var friends = reply.ids
, pruned = false;
while(!pruned) {
var target = randIndex(friends);
if(!~followers.indexOf(target)) {
pruned = true;
self.twit.post('friendships/destroy', { id: target }, callback);
}
}
});
});
};
function randIndex (arr) {
var index = Math.floor(arr.length*Math.random());
return arr[index];
}; |
#ifndef <API key> // NOLINT
#define <API key>
#include "libyuv/basic_types.h"
#include "libyuv/rotate.h" // For enum RotationMode.
// TODO(fbarchard): This set of functions should exactly match convert.h
// TODO(fbarchard): Add tests. Create random content of right size and convert
// with C vs Opt and or to I420 and compare.
// TODO(fbarchard): Some of these functions lack parameter setting.
#ifdef __cplusplus
namespace libyuv {
extern "C" {
#endif
// Alias.
#define ARGBToARGB ARGBCopy
// Copy ARGB to ARGB.
LIBYUV_API
int ARGBCopy(const uint8* src_argb, int src_stride_argb,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert I420 to ARGB.
LIBYUV_API
int I420ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert I422 to ARGB.
LIBYUV_API
int I422ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert I444 to ARGB.
LIBYUV_API
int I444ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert J444 to ARGB.
LIBYUV_API
int J444ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert I444 to ABGR.
LIBYUV_API
int I444ToABGR(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_abgr, int dst_stride_abgr,
int width, int height);
// Convert I411 to ARGB.
LIBYUV_API
int I411ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert I420 with Alpha to preattenuated ARGB.
LIBYUV_API
int I420AlphaToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
const uint8* src_a, int src_stride_a,
uint8* dst_argb, int dst_stride_argb,
int width, int height, int attenuate);
// Convert I420 with Alpha to preattenuated ABGR.
LIBYUV_API
int I420AlphaToABGR(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
const uint8* src_a, int src_stride_a,
uint8* dst_abgr, int dst_stride_abgr,
int width, int height, int attenuate);
// Convert I400 (grey) to ARGB. Reverse of ARGBToI400.
LIBYUV_API
int I400ToARGB(const uint8* src_y, int src_stride_y,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert J400 (jpeg grey) to ARGB.
LIBYUV_API
int J400ToARGB(const uint8* src_y, int src_stride_y,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Alias.
#define YToARGB I400ToARGB
// Convert NV12 to ARGB.
LIBYUV_API
int NV12ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_uv, int src_stride_uv,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert NV21 to ARGB.
LIBYUV_API
int NV21ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_vu, int src_stride_vu,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert M420 to ARGB.
LIBYUV_API
int M420ToARGB(const uint8* src_m420, int src_stride_m420,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert YUY2 to ARGB.
LIBYUV_API
int YUY2ToARGB(const uint8* src_yuy2, int src_stride_yuy2,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert UYVY to ARGB.
LIBYUV_API
int UYVYToARGB(const uint8* src_uyvy, int src_stride_uyvy,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert J420 to ARGB.
LIBYUV_API
int J420ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert J422 to ARGB.
LIBYUV_API
int J422ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert J420 to ABGR.
LIBYUV_API
int J420ToABGR(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_abgr, int dst_stride_abgr,
int width, int height);
// Convert J422 to ABGR.
LIBYUV_API
int J422ToABGR(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_abgr, int dst_stride_abgr,
int width, int height);
// Convert H420 to ARGB.
LIBYUV_API
int H420ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert H422 to ARGB.
LIBYUV_API
int H422ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Convert H420 to ABGR.
LIBYUV_API
int H420ToABGR(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_abgr, int dst_stride_abgr,
int width, int height);
// Convert H422 to ABGR.
LIBYUV_API
int H422ToABGR(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_abgr, int dst_stride_abgr,
int width, int height);
// BGRA little endian (argb in memory) to ARGB.
LIBYUV_API
int BGRAToARGB(const uint8* src_frame, int src_stride_frame,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// ABGR little endian (rgba in memory) to ARGB.
LIBYUV_API
int ABGRToARGB(const uint8* src_frame, int src_stride_frame,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// RGBA little endian (abgr in memory) to ARGB.
LIBYUV_API
int RGBAToARGB(const uint8* src_frame, int src_stride_frame,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// Deprecated function name.
#define BG24ToARGB RGB24ToARGB
// RGB little endian (bgr in memory) to ARGB.
LIBYUV_API
int RGB24ToARGB(const uint8* src_frame, int src_stride_frame,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// RGB big endian (rgb in memory) to ARGB.
LIBYUV_API
int RAWToARGB(const uint8* src_frame, int src_stride_frame,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// RGB16 (RGBP fourcc) little endian to ARGB.
LIBYUV_API
int RGB565ToARGB(const uint8* src_frame, int src_stride_frame,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// RGB15 (RGBO fourcc) little endian to ARGB.
LIBYUV_API
int ARGB1555ToARGB(const uint8* src_frame, int src_stride_frame,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
// RGB12 (R444 fourcc) little endian to ARGB.
LIBYUV_API
int ARGB4444ToARGB(const uint8* src_frame, int src_stride_frame,
uint8* dst_argb, int dst_stride_argb,
int width, int height);
#ifdef HAVE_JPEG
// src_width/height provided by capture
// dst_width/height for clipping determine final size.
LIBYUV_API
int MJPGToARGB(const uint8* sample, size_t sample_size,
uint8* dst_argb, int dst_stride_argb,
int src_width, int src_height,
int dst_width, int dst_height);
#endif
// Convert camera sample to ARGB with cropping, rotation and vertical flip.
// "src_size" is needed to parse MJPG.
// "dst_stride_argb" number of bytes in a row of the dst_argb plane.
// Normally this would be the same as dst_width, with recommended alignment
// to 16 bytes for better efficiency.
// If rotation of 90 or 270 is used, stride is affected. The caller should
// allocate the I420 buffer according to rotation.
// "dst_stride_u" number of bytes in a row of the dst_u plane.
// Normally this would be the same as (dst_width + 1) / 2, with
// recommended alignment to 16 bytes for better efficiency.
// If rotation of 90 or 270 is used, stride is affected.
// "crop_x" and "crop_y" are starting position for cropping.
// To center, crop_x = (src_width - dst_width) / 2
// crop_y = (src_height - dst_height) / 2
// "src_width" / "src_height" is size of src_frame in pixels.
// "src_height" can be negative indicating a vertically flipped image source.
// "crop_width" / "crop_height" is the size to crop the src to.
// Must be less than or equal to src_width/src_height
// Cropping parameters are pre-rotation.
// "rotation" can be 0, 90, 180 or 270.
// "format" is a fourcc. ie 'I420', 'YUY2'
// Returns 0 for successful; -1 for invalid parameter. Non-zero for failure.
LIBYUV_API
int ConvertToARGB(const uint8* src_frame, size_t src_size,
uint8* dst_argb, int dst_stride_argb,
int crop_x, int crop_y,
int src_width, int src_height,
int crop_width, int crop_height,
enum RotationMode rotation,
uint32 format);
#ifdef __cplusplus
} // extern "C"
} // namespace libyuv
#endif
#endif // <API key> NOLINT |
#include "hpdf_conf.h"
#include "hpdf_utils.h"
#include "hpdf_fontdef.h"
static const HPDF_CharData CHAR_DATA_COURIER[316] = {
{32, 0x0020, 600},
{33, 0x0021, 600},
{34, 0x0022, 600},
{35, 0x0023, 600},
{36, 0x0024, 600},
{37, 0x0025, 600},
{38, 0x0026, 600},
{39, 0x2019, 600},
{40, 0x0028, 600},
{41, 0x0029, 600},
{42, 0x002A, 600},
{43, 0x002B, 600},
{44, 0x002C, 600},
{45, 0x002D, 600},
{46, 0x002E, 600},
{47, 0x002F, 600},
{48, 0x0030, 600},
{49, 0x0031, 600},
{50, 0x0032, 600},
{51, 0x0033, 600},
{52, 0x0034, 600},
{53, 0x0035, 600},
{54, 0x0036, 600},
{55, 0x0037, 600},
{56, 0x0038, 600},
{57, 0x0039, 600},
{58, 0x003A, 600},
{59, 0x003B, 600},
{60, 0x003C, 600},
{61, 0x003D, 600},
{62, 0x003E, 600},
{63, 0x003F, 600},
{64, 0x0040, 600},
{65, 0x0041, 600},
{66, 0x0042, 600},
{67, 0x0043, 600},
{68, 0x0044, 600},
{69, 0x0045, 600},
{70, 0x0046, 600},
{71, 0x0047, 600},
{72, 0x0048, 600},
{73, 0x0049, 600},
{74, 0x004A, 600},
{75, 0x004B, 600},
{76, 0x004C, 600},
{77, 0x004D, 600},
{78, 0x004E, 600},
{79, 0x004F, 600},
{80, 0x0050, 600},
{81, 0x0051, 600},
{82, 0x0052, 600},
{83, 0x0053, 600},
{84, 0x0054, 600},
{85, 0x0055, 600},
{86, 0x0056, 600},
{87, 0x0057, 600},
{88, 0x0058, 600},
{89, 0x0059, 600},
{90, 0x005A, 600},
{91, 0x005B, 600},
{92, 0x005C, 600},
{93, 0x005D, 600},
{94, 0x005E, 600},
{95, 0x005F, 600},
{96, 0x2018, 600},
{97, 0x0061, 600},
{98, 0x0062, 600},
{99, 0x0063, 600},
{100, 0x0064, 600},
{101, 0x0065, 600},
{102, 0x0066, 600},
{103, 0x0067, 600},
{104, 0x0068, 600},
{105, 0x0069, 600},
{106, 0x006A, 600},
{107, 0x006B, 600},
{108, 0x006C, 600},
{109, 0x006D, 600},
{110, 0x006E, 600},
{111, 0x006F, 600},
{112, 0x0070, 600},
{113, 0x0071, 600},
{114, 0x0072, 600},
{115, 0x0073, 600},
{116, 0x0074, 600},
{117, 0x0075, 600},
{118, 0x0076, 600},
{119, 0x0077, 600},
{120, 0x0078, 600},
{121, 0x0079, 600},
{122, 0x007A, 600},
{123, 0x007B, 600},
{124, 0x007C, 600},
{125, 0x007D, 600},
{126, 0x007E, 600},
{161, 0x00A1, 600},
{162, 0x00A2, 600},
{163, 0x00A3, 600},
{164, 0x2044, 600},
{165, 0x00A5, 600},
{166, 0x0192, 600},
{167, 0x00A7, 600},
{168, 0x00A4, 600},
{169, 0x0027, 600},
{170, 0x201C, 600},
{171, 0x00AB, 600},
{172, 0x2039, 600},
{173, 0x203A, 600},
{174, 0xFB01, 600},
{175, 0xFB02, 600},
{177, 0x2013, 600},
{178, 0x2020, 600},
{179, 0x2021, 600},
{180, 0x00B7, 600},
{182, 0x00B6, 600},
{183, 0x2022, 600},
{184, 0x201A, 600},
{185, 0x201E, 600},
{186, 0x201D, 600},
{187, 0x00BB, 600},
{188, 0x2026, 600},
{189, 0x2030, 600},
{191, 0x00BF, 600},
{193, 0x0060, 600},
{194, 0x00B4, 600},
{195, 0x02C6, 600},
{196, 0x02DC, 600},
{197, 0x00AF, 600},
{198, 0x02D8, 600},
{199, 0x02D9, 600},
{200, 0x00A8, 600},
{202, 0x02DA, 600},
{203, 0x00B8, 600},
{205, 0x02DD, 600},
{206, 0x02DB, 600},
{207, 0x02C7, 600},
{208, 0x2014, 600},
{225, 0x00C6, 600},
{227, 0x00AA, 600},
{232, 0x0141, 600},
{233, 0x00D8, 600},
{234, 0x0152, 600},
{235, 0x00BA, 600},
{241, 0x00E6, 600},
{245, 0x0131, 600},
{248, 0x0142, 600},
{249, 0x00F8, 600},
{250, 0x0153, 600},
{251, 0x00DF, 600},
{-1, 0x00CF, 600},
{-1, 0x00E9, 600},
{-1, 0x0103, 600},
{-1, 0x0171, 600},
{-1, 0x011B, 600},
{-1, 0x0178, 600},
{-1, 0x00F7, 600},
{-1, 0x00DD, 600},
{-1, 0x00C2, 600},
{-1, 0x00E1, 600},
{-1, 0x00DB, 600},
{-1, 0x00FD, 600},
{-1, 0x0219, 600},
{-1, 0x00EA, 600},
{-1, 0x016E, 600},
{-1, 0x00DC, 600},
{-1, 0x0105, 600},
{-1, 0x00DA, 600},
{-1, 0x0173, 600},
{-1, 0x00CB, 600},
{-1, 0x0110, 600},
{-1, 0xF6C3, 600},
{-1, 0x00A9, 600},
{-1, 0x0112, 600},
{-1, 0x010D, 600},
{-1, 0x00E5, 600},
{-1, 0x0145, 600},
{-1, 0x013A, 600},
{-1, 0x00E0, 600},
{-1, 0x0162, 600},
{-1, 0x0106, 600},
{-1, 0x00E3, 600},
{-1, 0x0116, 600},
{-1, 0x0161, 600},
{-1, 0x015F, 600},
{-1, 0x00ED, 600},
{-1, 0x25CA, 600},
{-1, 0x0158, 600},
{-1, 0x0122, 600},
{-1, 0x00FB, 600},
{-1, 0x00E2, 600},
{-1, 0x0100, 600},
{-1, 0x0159, 600},
{-1, 0x00E7, 600},
{-1, 0x017B, 600},
{-1, 0x00DE, 600},
{-1, 0x014C, 600},
{-1, 0x0154, 600},
{-1, 0x015A, 600},
{-1, 0x010F, 600},
{-1, 0x016A, 600},
{-1, 0x016F, 600},
{-1, 0x00B3, 600},
{-1, 0x00D2, 600},
{-1, 0x00C0, 600},
{-1, 0x0102, 600},
{-1, 0x00D7, 600},
{-1, 0x00FA, 600},
{-1, 0x0164, 600},
{-1, 0x2202, 600},
{-1, 0x00FF, 600},
{-1, 0x0143, 600},
{-1, 0x00EE, 600},
{-1, 0x00CA, 600},
{-1, 0x00E4, 600},
{-1, 0x00EB, 600},
{-1, 0x0107, 600},
{-1, 0x0144, 600},
{-1, 0x016B, 600},
{-1, 0x0147, 600},
{-1, 0x00CD, 600},
{-1, 0x00B1, 600},
{-1, 0x00A6, 600},
{-1, 0x00AE, 600},
{-1, 0x011E, 600},
{-1, 0x0130, 600},
{-1, 0x2211, 600},
{-1, 0x00C8, 600},
{-1, 0x0155, 600},
{-1, 0x014D, 600},
{-1, 0x0179, 600},
{-1, 0x017D, 600},
{-1, 0x2265, 600},
{-1, 0x00D0, 600},
{-1, 0x00C7, 600},
{-1, 0x013C, 600},
{-1, 0x0165, 600},
{-1, 0x0119, 600},
{-1, 0x0172, 600},
{-1, 0x00C1, 600},
{-1, 0x00C4, 600},
{-1, 0x00E8, 600},
{-1, 0x017A, 600},
{-1, 0x012F, 600},
{-1, 0x00D3, 600},
{-1, 0x00F3, 600},
{-1, 0x0101, 600},
{-1, 0x015B, 600},
{-1, 0x00EF, 600},
{-1, 0x00D4, 600},
{-1, 0x00D9, 600},
{-1, 0x0394, 600},
{-1, 0x00FE, 600},
{-1, 0x00B2, 600},
{-1, 0x00D6, 600},
{-1, 0x00B5, 600},
{-1, 0x00EC, 600},
{-1, 0x0151, 600},
{-1, 0x0118, 600},
{-1, 0x0111, 600},
{-1, 0x00BE, 600},
{-1, 0x015E, 600},
{-1, 0x013E, 600},
{-1, 0x0136, 600},
{-1, 0x0139, 600},
{-1, 0x2122, 600},
{-1, 0x0117, 600},
{-1, 0x00CC, 600},
{-1, 0x012A, 600},
{-1, 0x013D, 600},
{-1, 0x00BD, 600},
{-1, 0x2264, 600},
{-1, 0x00F4, 600},
{-1, 0x00F1, 600},
{-1, 0x0170, 600},
{-1, 0x00C9, 600},
{-1, 0x0113, 600},
{-1, 0x011F, 600},
{-1, 0x00BC, 600},
{-1, 0x0160, 600},
{-1, 0x0218, 600},
{-1, 0x0150, 600},
{-1, 0x00B0, 600},
{-1, 0x00F2, 600},
{-1, 0x010C, 600},
{-1, 0x00F9, 600},
{-1, 0x221A, 600},
{-1, 0x010E, 600},
{-1, 0x0157, 600},
{-1, 0x00D1, 600},
{-1, 0x00F5, 600},
{-1, 0x0156, 600},
{-1, 0x013B, 600},
{-1, 0x00C3, 600},
{-1, 0x0104, 600},
{-1, 0x00C5, 600},
{-1, 0x00D5, 600},
{-1, 0x017C, 600},
{-1, 0x011A, 600},
{-1, 0x012E, 600},
{-1, 0x0137, 600},
{-1, 0x2212, 600},
{-1, 0x00CE, 600},
{-1, 0x0148, 600},
{-1, 0x0163, 600},
{-1, 0x00AC, 600},
{-1, 0x00F6, 600},
{-1, 0x00FC, 600},
{-1, 0x2260, 600},
{-1, 0x0123, 600},
{-1, 0x00F0, 600},
{-1, 0x017E, 600},
{-1, 0x0146, 600},
{-1, 0x00B9, 600},
{-1, 0x012B, 600},
{-1, 0x20AC, 600},
{-1, 0xFFFF, 0}
};
static const HPDF_CharData <API key>[316] = {
{32, 0x0020, 600},
{33, 0x0021, 600},
{34, 0x0022, 600},
{35, 0x0023, 600},
{36, 0x0024, 600},
{37, 0x0025, 600},
{38, 0x0026, 600},
{39, 0x2019, 600},
{40, 0x0028, 600},
{41, 0x0029, 600},
{42, 0x002A, 600},
{43, 0x002B, 600},
{44, 0x002C, 600},
{45, 0x002D, 600},
{46, 0x002E, 600},
{47, 0x002F, 600},
{48, 0x0030, 600},
{49, 0x0031, 600},
{50, 0x0032, 600},
{51, 0x0033, 600},
{52, 0x0034, 600},
{53, 0x0035, 600},
{54, 0x0036, 600},
{55, 0x0037, 600},
{56, 0x0038, 600},
{57, 0x0039, 600},
{58, 0x003A, 600},
{59, 0x003B, 600},
{60, 0x003C, 600},
{61, 0x003D, 600},
{62, 0x003E, 600},
{63, 0x003F, 600},
{64, 0x0040, 600},
{65, 0x0041, 600},
{66, 0x0042, 600},
{67, 0x0043, 600},
{68, 0x0044, 600},
{69, 0x0045, 600},
{70, 0x0046, 600},
{71, 0x0047, 600},
{72, 0x0048, 600},
{73, 0x0049, 600},
{74, 0x004A, 600},
{75, 0x004B, 600},
{76, 0x004C, 600},
{77, 0x004D, 600},
{78, 0x004E, 600},
{79, 0x004F, 600},
{80, 0x0050, 600},
{81, 0x0051, 600},
{82, 0x0052, 600},
{83, 0x0053, 600},
{84, 0x0054, 600},
{85, 0x0055, 600},
{86, 0x0056, 600},
{87, 0x0057, 600},
{88, 0x0058, 600},
{89, 0x0059, 600},
{90, 0x005A, 600},
{91, 0x005B, 600},
{92, 0x005C, 600},
{93, 0x005D, 600},
{94, 0x005E, 600},
{95, 0x005F, 600},
{96, 0x2018, 600},
{97, 0x0061, 600},
{98, 0x0062, 600},
{99, 0x0063, 600},
{100, 0x0064, 600},
{101, 0x0065, 600},
{102, 0x0066, 600},
{103, 0x0067, 600},
{104, 0x0068, 600},
{105, 0x0069, 600},
{106, 0x006A, 600},
{107, 0x006B, 600},
{108, 0x006C, 600},
{109, 0x006D, 600},
{110, 0x006E, 600},
{111, 0x006F, 600},
{112, 0x0070, 600},
{113, 0x0071, 600},
{114, 0x0072, 600},
{115, 0x0073, 600},
{116, 0x0074, 600},
{117, 0x0075, 600},
{118, 0x0076, 600},
{119, 0x0077, 600},
{120, 0x0078, 600},
{121, 0x0079, 600},
{122, 0x007A, 600},
{123, 0x007B, 600},
{124, 0x007C, 600},
{125, 0x007D, 600},
{126, 0x007E, 600},
{161, 0x00A1, 600},
{162, 0x00A2, 600},
{163, 0x00A3, 600},
{164, 0x2044, 600},
{165, 0x00A5, 600},
{166, 0x0192, 600},
{167, 0x00A7, 600},
{168, 0x00A4, 600},
{169, 0x0027, 600},
{170, 0x201C, 600},
{171, 0x00AB, 600},
{172, 0x2039, 600},
{173, 0x203A, 600},
{174, 0xFB01, 600},
{175, 0xFB02, 600},
{177, 0x2013, 600},
{178, 0x2020, 600},
{179, 0x2021, 600},
{180, 0x00B7, 600},
{182, 0x00B6, 600},
{183, 0x2022, 600},
{184, 0x201A, 600},
{185, 0x201E, 600},
{186, 0x201D, 600},
{187, 0x00BB, 600},
{188, 0x2026, 600},
{189, 0x2030, 600},
{191, 0x00BF, 600},
{193, 0x0060, 600},
{194, 0x00B4, 600},
{195, 0x02C6, 600},
{196, 0x02DC, 600},
{197, 0x00AF, 600},
{198, 0x02D8, 600},
{199, 0x02D9, 600},
{200, 0x00A8, 600},
{202, 0x02DA, 600},
{203, 0x00B8, 600},
{205, 0x02DD, 600},
{206, 0x02DB, 600},
{207, 0x02C7, 600},
{208, 0x2014, 600},
{225, 0x00C6, 600},
{227, 0x00AA, 600},
{232, 0x0141, 600},
{233, 0x00D8, 600},
{234, 0x0152, 600},
{235, 0x00BA, 600},
{241, 0x00E6, 600},
{245, 0x0131, 600},
{248, 0x0142, 600},
{249, 0x00F8, 600},
{250, 0x0153, 600},
{251, 0x00DF, 600},
{-1, 0x00CF, 600},
{-1, 0x00E9, 600},
{-1, 0x0103, 600},
{-1, 0x0171, 600},
{-1, 0x011B, 600},
{-1, 0x0178, 600},
{-1, 0x00F7, 600},
{-1, 0x00DD, 600},
{-1, 0x00C2, 600},
{-1, 0x00E1, 600},
{-1, 0x00DB, 600},
{-1, 0x00FD, 600},
{-1, 0x0219, 600},
{-1, 0x00EA, 600},
{-1, 0x016E, 600},
{-1, 0x00DC, 600},
{-1, 0x0105, 600},
{-1, 0x00DA, 600},
{-1, 0x0173, 600},
{-1, 0x00CB, 600},
{-1, 0x0110, 600},
{-1, 0xF6C3, 600},
{-1, 0x00A9, 600},
{-1, 0x0112, 600},
{-1, 0x010D, 600},
{-1, 0x00E5, 600},
{-1, 0x0145, 600},
{-1, 0x013A, 600},
{-1, 0x00E0, 600},
{-1, 0x0162, 600},
{-1, 0x0106, 600},
{-1, 0x00E3, 600},
{-1, 0x0116, 600},
{-1, 0x0161, 600},
{-1, 0x015F, 600},
{-1, 0x00ED, 600},
{-1, 0x25CA, 600},
{-1, 0x0158, 600},
{-1, 0x0122, 600},
{-1, 0x00FB, 600},
{-1, 0x00E2, 600},
{-1, 0x0100, 600},
{-1, 0x0159, 600},
{-1, 0x00E7, 600},
{-1, 0x017B, 600},
{-1, 0x00DE, 600},
{-1, 0x014C, 600},
{-1, 0x0154, 600},
{-1, 0x015A, 600},
{-1, 0x010F, 600},
{-1, 0x016A, 600},
{-1, 0x016F, 600},
{-1, 0x00B3, 600},
{-1, 0x00D2, 600},
{-1, 0x00C0, 600},
{-1, 0x0102, 600},
{-1, 0x00D7, 600},
{-1, 0x00FA, 600},
{-1, 0x0164, 600},
{-1, 0x2202, 600},
{-1, 0x00FF, 600},
{-1, 0x0143, 600},
{-1, 0x00EE, 600},
{-1, 0x00CA, 600},
{-1, 0x00E4, 600},
{-1, 0x00EB, 600},
{-1, 0x0107, 600},
{-1, 0x0144, 600},
{-1, 0x016B, 600},
{-1, 0x0147, 600},
{-1, 0x00CD, 600},
{-1, 0x00B1, 600},
{-1, 0x00A6, 600},
{-1, 0x00AE, 600},
{-1, 0x011E, 600},
{-1, 0x0130, 600},
{-1, 0x2211, 600},
{-1, 0x00C8, 600},
{-1, 0x0155, 600},
{-1, 0x014D, 600},
{-1, 0x0179, 600},
{-1, 0x017D, 600},
{-1, 0x2265, 600},
{-1, 0x00D0, 600},
{-1, 0x00C7, 600},
{-1, 0x013C, 600},
{-1, 0x0165, 600},
{-1, 0x0119, 600},
{-1, 0x0172, 600},
{-1, 0x00C1, 600},
{-1, 0x00C4, 600},
{-1, 0x00E8, 600},
{-1, 0x017A, 600},
{-1, 0x012F, 600},
{-1, 0x00D3, 600},
{-1, 0x00F3, 600},
{-1, 0x0101, 600},
{-1, 0x015B, 600},
{-1, 0x00EF, 600},
{-1, 0x00D4, 600},
{-1, 0x00D9, 600},
{-1, 0x0394, 600},
{-1, 0x00FE, 600},
{-1, 0x00B2, 600},
{-1, 0x00D6, 600},
{-1, 0x00B5, 600},
{-1, 0x00EC, 600},
{-1, 0x0151, 600},
{-1, 0x0118, 600},
{-1, 0x0111, 600},
{-1, 0x00BE, 600},
{-1, 0x015E, 600},
{-1, 0x013E, 600},
{-1, 0x0136, 600},
{-1, 0x0139, 600},
{-1, 0x2122, 600},
{-1, 0x0117, 600},
{-1, 0x00CC, 600},
{-1, 0x012A, 600},
{-1, 0x013D, 600},
{-1, 0x00BD, 600},
{-1, 0x2264, 600},
{-1, 0x00F4, 600},
{-1, 0x00F1, 600},
{-1, 0x0170, 600},
{-1, 0x00C9, 600},
{-1, 0x0113, 600},
{-1, 0x011F, 600},
{-1, 0x00BC, 600},
{-1, 0x0160, 600},
{-1, 0x0218, 600},
{-1, 0x0150, 600},
{-1, 0x00B0, 600},
{-1, 0x00F2, 600},
{-1, 0x010C, 600},
{-1, 0x00F9, 600},
{-1, 0x221A, 600},
{-1, 0x010E, 600},
{-1, 0x0157, 600},
{-1, 0x00D1, 600},
{-1, 0x00F5, 600},
{-1, 0x0156, 600},
{-1, 0x013B, 600},
{-1, 0x00C3, 600},
{-1, 0x0104, 600},
{-1, 0x00C5, 600},
{-1, 0x00D5, 600},
{-1, 0x017C, 600},
{-1, 0x011A, 600},
{-1, 0x012E, 600},
{-1, 0x0137, 600},
{-1, 0x2212, 600},
{-1, 0x00CE, 600},
{-1, 0x0148, 600},
{-1, 0x0163, 600},
{-1, 0x00AC, 600},
{-1, 0x00F6, 600},
{-1, 0x00FC, 600},
{-1, 0x2260, 600},
{-1, 0x0123, 600},
{-1, 0x00F0, 600},
{-1, 0x017E, 600},
{-1, 0x0146, 600},
{-1, 0x00B9, 600},
{-1, 0x012B, 600},
{-1, 0x20AC, 600},
{-1, 0xFFFF, 0}
};
static const HPDF_CharData <API key>[316] = {
{32, 0x0020, 600},
{33, 0x0021, 600},
{34, 0x0022, 600},
{35, 0x0023, 600},
{36, 0x0024, 600},
{37, 0x0025, 600},
{38, 0x0026, 600},
{39, 0x2019, 600},
{40, 0x0028, 600},
{41, 0x0029, 600},
{42, 0x002A, 600},
{43, 0x002B, 600},
{44, 0x002C, 600},
{45, 0x002D, 600},
{46, 0x002E, 600},
{47, 0x002F, 600},
{48, 0x0030, 600},
{49, 0x0031, 600},
{50, 0x0032, 600},
{51, 0x0033, 600},
{52, 0x0034, 600},
{53, 0x0035, 600},
{54, 0x0036, 600},
{55, 0x0037, 600},
{56, 0x0038, 600},
{57, 0x0039, 600},
{58, 0x003A, 600},
{59, 0x003B, 600},
{60, 0x003C, 600},
{61, 0x003D, 600},
{62, 0x003E, 600},
{63, 0x003F, 600},
{64, 0x0040, 600},
{65, 0x0041, 600},
{66, 0x0042, 600},
{67, 0x0043, 600},
{68, 0x0044, 600},
{69, 0x0045, 600},
{70, 0x0046, 600},
{71, 0x0047, 600},
{72, 0x0048, 600},
{73, 0x0049, 600},
{74, 0x004A, 600},
{75, 0x004B, 600},
{76, 0x004C, 600},
{77, 0x004D, 600},
{78, 0x004E, 600},
{79, 0x004F, 600},
{80, 0x0050, 600},
{81, 0x0051, 600},
{82, 0x0052, 600},
{83, 0x0053, 600},
{84, 0x0054, 600},
{85, 0x0055, 600},
{86, 0x0056, 600},
{87, 0x0057, 600},
{88, 0x0058, 600},
{89, 0x0059, 600},
{90, 0x005A, 600},
{91, 0x005B, 600},
{92, 0x005C, 600},
{93, 0x005D, 600},
{94, 0x005E, 600},
{95, 0x005F, 600},
{96, 0x2018, 600},
{97, 0x0061, 600},
{98, 0x0062, 600},
{99, 0x0063, 600},
{100, 0x0064, 600},
{101, 0x0065, 600},
{102, 0x0066, 600},
{103, 0x0067, 600},
{104, 0x0068, 600},
{105, 0x0069, 600},
{106, 0x006A, 600},
{107, 0x006B, 600},
{108, 0x006C, 600},
{109, 0x006D, 600},
{110, 0x006E, 600},
{111, 0x006F, 600},
{112, 0x0070, 600},
{113, 0x0071, 600},
{114, 0x0072, 600},
{115, 0x0073, 600},
{116, 0x0074, 600},
{117, 0x0075, 600},
{118, 0x0076, 600},
{119, 0x0077, 600},
{120, 0x0078, 600},
{121, 0x0079, 600},
{122, 0x007A, 600},
{123, 0x007B, 600},
{124, 0x007C, 600},
{125, 0x007D, 600},
{126, 0x007E, 600},
{161, 0x00A1, 600},
{162, 0x00A2, 600},
{163, 0x00A3, 600},
{164, 0x2044, 600},
{165, 0x00A5, 600},
{166, 0x0192, 600},
{167, 0x00A7, 600},
{168, 0x00A4, 600},
{169, 0x0027, 600},
{170, 0x201C, 600},
{171, 0x00AB, 600},
{172, 0x2039, 600},
{173, 0x203A, 600},
{174, 0xFB01, 600},
{175, 0xFB02, 600},
{177, 0x2013, 600},
{178, 0x2020, 600},
{179, 0x2021, 600},
{180, 0x00B7, 600},
{182, 0x00B6, 600},
{183, 0x2022, 600},
{184, 0x201A, 600},
{185, 0x201E, 600},
{186, 0x201D, 600},
{187, 0x00BB, 600},
{188, 0x2026, 600},
{189, 0x2030, 600},
{191, 0x00BF, 600},
{193, 0x0060, 600},
{194, 0x00B4, 600},
{195, 0x02C6, 600},
{196, 0x02DC, 600},
{197, 0x00AF, 600},
{198, 0x02D8, 600},
{199, 0x02D9, 600},
{200, 0x00A8, 600},
{202, 0x02DA, 600},
{203, 0x00B8, 600},
{205, 0x02DD, 600},
{206, 0x02DB, 600},
{207, 0x02C7, 600},
{208, 0x2014, 600},
{225, 0x00C6, 600},
{227, 0x00AA, 600},
{232, 0x0141, 600},
{233, 0x00D8, 600},
{234, 0x0152, 600},
{235, 0x00BA, 600},
{241, 0x00E6, 600},
{245, 0x0131, 600},
{248, 0x0142, 600},
{249, 0x00F8, 600},
{250, 0x0153, 600},
{251, 0x00DF, 600},
{-1, 0x00CF, 600},
{-1, 0x00E9, 600},
{-1, 0x0103, 600},
{-1, 0x0171, 600},
{-1, 0x011B, 600},
{-1, 0x0178, 600},
{-1, 0x00F7, 600},
{-1, 0x00DD, 600},
{-1, 0x00C2, 600},
{-1, 0x00E1, 600},
{-1, 0x00DB, 600},
{-1, 0x00FD, 600},
{-1, 0x0219, 600},
{-1, 0x00EA, 600},
{-1, 0x016E, 600},
{-1, 0x00DC, 600},
{-1, 0x0105, 600},
{-1, 0x00DA, 600},
{-1, 0x0173, 600},
{-1, 0x00CB, 600},
{-1, 0x0110, 600},
{-1, 0xF6C3, 600},
{-1, 0x00A9, 600},
{-1, 0x0112, 600},
{-1, 0x010D, 600},
{-1, 0x00E5, 600},
{-1, 0x0145, 600},
{-1, 0x013A, 600},
{-1, 0x00E0, 600},
{-1, 0x0162, 600},
{-1, 0x0106, 600},
{-1, 0x00E3, 600},
{-1, 0x0116, 600},
{-1, 0x0161, 600},
{-1, 0x015F, 600},
{-1, 0x00ED, 600},
{-1, 0x25CA, 600},
{-1, 0x0158, 600},
{-1, 0x0122, 600},
{-1, 0x00FB, 600},
{-1, 0x00E2, 600},
{-1, 0x0100, 600},
{-1, 0x0159, 600},
{-1, 0x00E7, 600},
{-1, 0x017B, 600},
{-1, 0x00DE, 600},
{-1, 0x014C, 600},
{-1, 0x0154, 600},
{-1, 0x015A, 600},
{-1, 0x010F, 600},
{-1, 0x016A, 600},
{-1, 0x016F, 600},
{-1, 0x00B3, 600},
{-1, 0x00D2, 600},
{-1, 0x00C0, 600},
{-1, 0x0102, 600},
{-1, 0x00D7, 600},
{-1, 0x00FA, 600},
{-1, 0x0164, 600},
{-1, 0x2202, 600},
{-1, 0x00FF, 600},
{-1, 0x0143, 600},
{-1, 0x00EE, 600},
{-1, 0x00CA, 600},
{-1, 0x00E4, 600},
{-1, 0x00EB, 600},
{-1, 0x0107, 600},
{-1, 0x0144, 600},
{-1, 0x016B, 600},
{-1, 0x0147, 600},
{-1, 0x00CD, 600},
{-1, 0x00B1, 600},
{-1, 0x00A6, 600},
{-1, 0x00AE, 600},
{-1, 0x011E, 600},
{-1, 0x0130, 600},
{-1, 0x2211, 600},
{-1, 0x00C8, 600},
{-1, 0x0155, 600},
{-1, 0x014D, 600},
{-1, 0x0179, 600},
{-1, 0x017D, 600},
{-1, 0x2265, 600},
{-1, 0x00D0, 600},
{-1, 0x00C7, 600},
{-1, 0x013C, 600},
{-1, 0x0165, 600},
{-1, 0x0119, 600},
{-1, 0x0172, 600},
{-1, 0x00C1, 600},
{-1, 0x00C4, 600},
{-1, 0x00E8, 600},
{-1, 0x017A, 600},
{-1, 0x012F, 600},
{-1, 0x00D3, 600},
{-1, 0x00F3, 600},
{-1, 0x0101, 600},
{-1, 0x015B, 600},
{-1, 0x00EF, 600},
{-1, 0x00D4, 600},
{-1, 0x00D9, 600},
{-1, 0x0394, 600},
{-1, 0x00FE, 600},
{-1, 0x00B2, 600},
{-1, 0x00D6, 600},
{-1, 0x00B5, 600},
{-1, 0x00EC, 600},
{-1, 0x0151, 600},
{-1, 0x0118, 600},
{-1, 0x0111, 600},
{-1, 0x00BE, 600},
{-1, 0x015E, 600},
{-1, 0x013E, 600},
{-1, 0x0136, 600},
{-1, 0x0139, 600},
{-1, 0x2122, 600},
{-1, 0x0117, 600},
{-1, 0x00CC, 600},
{-1, 0x012A, 600},
{-1, 0x013D, 600},
{-1, 0x00BD, 600},
{-1, 0x2264, 600},
{-1, 0x00F4, 600},
{-1, 0x00F1, 600},
{-1, 0x0170, 600},
{-1, 0x00C9, 600},
{-1, 0x0113, 600},
{-1, 0x011F, 600},
{-1, 0x00BC, 600},
{-1, 0x0160, 600},
{-1, 0x0218, 600},
{-1, 0x0150, 600},
{-1, 0x00B0, 600},
{-1, 0x00F2, 600},
{-1, 0x010C, 600},
{-1, 0x00F9, 600},
{-1, 0x221A, 600},
{-1, 0x010E, 600},
{-1, 0x0157, 600},
{-1, 0x00D1, 600},
{-1, 0x00F5, 600},
{-1, 0x0156, 600},
{-1, 0x013B, 600},
{-1, 0x00C3, 600},
{-1, 0x0104, 600},
{-1, 0x00C5, 600},
{-1, 0x00D5, 600},
{-1, 0x017C, 600},
{-1, 0x011A, 600},
{-1, 0x012E, 600},
{-1, 0x0137, 600},
{-1, 0x2212, 600},
{-1, 0x00CE, 600},
{-1, 0x0148, 600},
{-1, 0x0163, 600},
{-1, 0x00AC, 600},
{-1, 0x00F6, 600},
{-1, 0x00FC, 600},
{-1, 0x2260, 600},
{-1, 0x0123, 600},
{-1, 0x00F0, 600},
{-1, 0x017E, 600},
{-1, 0x0146, 600},
{-1, 0x00B9, 600},
{-1, 0x012B, 600},
{-1, 0x20AC, 600},
{-1, 0xFFFF, 0}
};
static const HPDF_CharData <API key>[316] = {
{32, 0x0020, 600},
{33, 0x0021, 600},
{34, 0x0022, 600},
{35, 0x0023, 600},
{36, 0x0024, 600},
{37, 0x0025, 600},
{38, 0x0026, 600},
{39, 0x2019, 600},
{40, 0x0028, 600},
{41, 0x0029, 600},
{42, 0x002A, 600},
{43, 0x002B, 600},
{44, 0x002C, 600},
{45, 0x002D, 600},
{46, 0x002E, 600},
{47, 0x002F, 600},
{48, 0x0030, 600},
{49, 0x0031, 600},
{50, 0x0032, 600},
{51, 0x0033, 600},
{52, 0x0034, 600},
{53, 0x0035, 600},
{54, 0x0036, 600},
{55, 0x0037, 600},
{56, 0x0038, 600},
{57, 0x0039, 600},
{58, 0x003A, 600},
{59, 0x003B, 600},
{60, 0x003C, 600},
{61, 0x003D, 600},
{62, 0x003E, 600},
{63, 0x003F, 600},
{64, 0x0040, 600},
{65, 0x0041, 600},
{66, 0x0042, 600},
{67, 0x0043, 600},
{68, 0x0044, 600},
{69, 0x0045, 600},
{70, 0x0046, 600},
{71, 0x0047, 600},
{72, 0x0048, 600},
{73, 0x0049, 600},
{74, 0x004A, 600},
{75, 0x004B, 600},
{76, 0x004C, 600},
{77, 0x004D, 600},
{78, 0x004E, 600},
{79, 0x004F, 600},
{80, 0x0050, 600},
{81, 0x0051, 600},
{82, 0x0052, 600},
{83, 0x0053, 600},
{84, 0x0054, 600},
{85, 0x0055, 600},
{86, 0x0056, 600},
{87, 0x0057, 600},
{88, 0x0058, 600},
{89, 0x0059, 600},
{90, 0x005A, 600},
{91, 0x005B, 600},
{92, 0x005C, 600},
{93, 0x005D, 600},
{94, 0x005E, 600},
{95, 0x005F, 600},
{96, 0x2018, 600},
{97, 0x0061, 600},
{98, 0x0062, 600},
{99, 0x0063, 600},
{100, 0x0064, 600},
{101, 0x0065, 600},
{102, 0x0066, 600},
{103, 0x0067, 600},
{104, 0x0068, 600},
{105, 0x0069, 600},
{106, 0x006A, 600},
{107, 0x006B, 600},
{108, 0x006C, 600},
{109, 0x006D, 600},
{110, 0x006E, 600},
{111, 0x006F, 600},
{112, 0x0070, 600},
{113, 0x0071, 600},
{114, 0x0072, 600},
{115, 0x0073, 600},
{116, 0x0074, 600},
{117, 0x0075, 600},
{118, 0x0076, 600},
{119, 0x0077, 600},
{120, 0x0078, 600},
{121, 0x0079, 600},
{122, 0x007A, 600},
{123, 0x007B, 600},
{124, 0x007C, 600},
{125, 0x007D, 600},
{126, 0x007E, 600},
{161, 0x00A1, 600},
{162, 0x00A2, 600},
{163, 0x00A3, 600},
{164, 0x2044, 600},
{165, 0x00A5, 600},
{166, 0x0192, 600},
{167, 0x00A7, 600},
{168, 0x00A4, 600},
{169, 0x0027, 600},
{170, 0x201C, 600},
{171, 0x00AB, 600},
{172, 0x2039, 600},
{173, 0x203A, 600},
{174, 0xFB01, 600},
{175, 0xFB02, 600},
{177, 0x2013, 600},
{178, 0x2020, 600},
{179, 0x2021, 600},
{180, 0x00B7, 600},
{182, 0x00B6, 600},
{183, 0x2022, 600},
{184, 0x201A, 600},
{185, 0x201E, 600},
{186, 0x201D, 600},
{187, 0x00BB, 600},
{188, 0x2026, 600},
{189, 0x2030, 600},
{191, 0x00BF, 600},
{193, 0x0060, 600},
{194, 0x00B4, 600},
{195, 0x02C6, 600},
{196, 0x02DC, 600},
{197, 0x00AF, 600},
{198, 0x02D8, 600},
{199, 0x02D9, 600},
{200, 0x00A8, 600},
{202, 0x02DA, 600},
{203, 0x00B8, 600},
{205, 0x02DD, 600},
{206, 0x02DB, 600},
{207, 0x02C7, 600},
{208, 0x2014, 600},
{225, 0x00C6, 600},
{227, 0x00AA, 600},
{232, 0x0141, 600},
{233, 0x00D8, 600},
{234, 0x0152, 600},
{235, 0x00BA, 600},
{241, 0x00E6, 600},
{245, 0x0131, 600},
{248, 0x0142, 600},
{249, 0x00F8, 600},
{250, 0x0153, 600},
{251, 0x00DF, 600},
{-1, 0x00CF, 600},
{-1, 0x00E9, 600},
{-1, 0x0103, 600},
{-1, 0x0171, 600},
{-1, 0x011B, 600},
{-1, 0x0178, 600},
{-1, 0x00F7, 600},
{-1, 0x00DD, 600},
{-1, 0x00C2, 600},
{-1, 0x00E1, 600},
{-1, 0x00DB, 600},
{-1, 0x00FD, 600},
{-1, 0x0219, 600},
{-1, 0x00EA, 600},
{-1, 0x016E, 600},
{-1, 0x00DC, 600},
{-1, 0x0105, 600},
{-1, 0x00DA, 600},
{-1, 0x0173, 600},
{-1, 0x00CB, 600},
{-1, 0x0110, 600},
{-1, 0xF6C3, 600},
{-1, 0x00A9, 600},
{-1, 0x0112, 600},
{-1, 0x010D, 600},
{-1, 0x00E5, 600},
{-1, 0x0145, 600},
{-1, 0x013A, 600},
{-1, 0x00E0, 600},
{-1, 0x0162, 600},
{-1, 0x0106, 600},
{-1, 0x00E3, 600},
{-1, 0x0116, 600},
{-1, 0x0161, 600},
{-1, 0x015F, 600},
{-1, 0x00ED, 600},
{-1, 0x25CA, 600},
{-1, 0x0158, 600},
{-1, 0x0122, 600},
{-1, 0x00FB, 600},
{-1, 0x00E2, 600},
{-1, 0x0100, 600},
{-1, 0x0159, 600},
{-1, 0x00E7, 600},
{-1, 0x017B, 600},
{-1, 0x00DE, 600},
{-1, 0x014C, 600},
{-1, 0x0154, 600},
{-1, 0x015A, 600},
{-1, 0x010F, 600},
{-1, 0x016A, 600},
{-1, 0x016F, 600},
{-1, 0x00B3, 600},
{-1, 0x00D2, 600},
{-1, 0x00C0, 600},
{-1, 0x0102, 600},
{-1, 0x00D7, 600},
{-1, 0x00FA, 600},
{-1, 0x0164, 600},
{-1, 0x2202, 600},
{-1, 0x00FF, 600},
{-1, 0x0143, 600},
{-1, 0x00EE, 600},
{-1, 0x00CA, 600},
{-1, 0x00E4, 600},
{-1, 0x00EB, 600},
{-1, 0x0107, 600},
{-1, 0x0144, 600},
{-1, 0x016B, 600},
{-1, 0x0147, 600},
{-1, 0x00CD, 600},
{-1, 0x00B1, 600},
{-1, 0x00A6, 600},
{-1, 0x00AE, 600},
{-1, 0x011E, 600},
{-1, 0x0130, 600},
{-1, 0x2211, 600},
{-1, 0x00C8, 600},
{-1, 0x0155, 600},
{-1, 0x014D, 600},
{-1, 0x0179, 600},
{-1, 0x017D, 600},
{-1, 0x2265, 600},
{-1, 0x00D0, 600},
{-1, 0x00C7, 600},
{-1, 0x013C, 600},
{-1, 0x0165, 600},
{-1, 0x0119, 600},
{-1, 0x0172, 600},
{-1, 0x00C1, 600},
{-1, 0x00C4, 600},
{-1, 0x00E8, 600},
{-1, 0x017A, 600},
{-1, 0x012F, 600},
{-1, 0x00D3, 600},
{-1, 0x00F3, 600},
{-1, 0x0101, 600},
{-1, 0x015B, 600},
{-1, 0x00EF, 600},
{-1, 0x00D4, 600},
{-1, 0x00D9, 600},
{-1, 0x0394, 600},
{-1, 0x00FE, 600},
{-1, 0x00B2, 600},
{-1, 0x00D6, 600},
{-1, 0x00B5, 600},
{-1, 0x00EC, 600},
{-1, 0x0151, 600},
{-1, 0x0118, 600},
{-1, 0x0111, 600},
{-1, 0x00BE, 600},
{-1, 0x015E, 600},
{-1, 0x013E, 600},
{-1, 0x0136, 600},
{-1, 0x0139, 600},
{-1, 0x2122, 600},
{-1, 0x0117, 600},
{-1, 0x00CC, 600},
{-1, 0x012A, 600},
{-1, 0x013D, 600},
{-1, 0x00BD, 600},
{-1, 0x2264, 600},
{-1, 0x00F4, 600},
{-1, 0x00F1, 600},
{-1, 0x0170, 600},
{-1, 0x00C9, 600},
{-1, 0x0113, 600},
{-1, 0x011F, 600},
{-1, 0x00BC, 600},
{-1, 0x0160, 600},
{-1, 0x0218, 600},
{-1, 0x0150, 600},
{-1, 0x00B0, 600},
{-1, 0x00F2, 600},
{-1, 0x010C, 600},
{-1, 0x00F9, 600},
{-1, 0x221A, 600},
{-1, 0x010E, 600},
{-1, 0x0157, 600},
{-1, 0x00D1, 600},
{-1, 0x00F5, 600},
{-1, 0x0156, 600},
{-1, 0x013B, 600},
{-1, 0x00C3, 600},
{-1, 0x0104, 600},
{-1, 0x00C5, 600},
{-1, 0x00D5, 600},
{-1, 0x017C, 600},
{-1, 0x011A, 600},
{-1, 0x012E, 600},
{-1, 0x0137, 600},
{-1, 0x2212, 600},
{-1, 0x00CE, 600},
{-1, 0x0148, 600},
{-1, 0x0163, 600},
{-1, 0x00AC, 600},
{-1, 0x00F6, 600},
{-1, 0x00FC, 600},
{-1, 0x2260, 600},
{-1, 0x0123, 600},
{-1, 0x00F0, 600},
{-1, 0x017E, 600},
{-1, 0x0146, 600},
{-1, 0x00B9, 600},
{-1, 0x012B, 600},
{-1, 0x20AC, 600},
{-1, 0xFFFF, 0}
};
static const HPDF_CharData CHAR_DATA_HELVETICA[316] = {
{32, 0x0020, 278},
{33, 0x0021, 278},
{34, 0x0022, 355},
{35, 0x0023, 556},
{36, 0x0024, 556},
{37, 0x0025, 889},
{38, 0x0026, 667},
{39, 0x2019, 222},
{40, 0x0028, 333},
{41, 0x0029, 333},
{42, 0x002A, 389},
{43, 0x002B, 584},
{44, 0x002C, 278},
{45, 0x002D, 333},
{46, 0x002E, 278},
{47, 0x002F, 278},
{48, 0x0030, 556},
{49, 0x0031, 556},
{50, 0x0032, 556},
{51, 0x0033, 556},
{52, 0x0034, 556},
{53, 0x0035, 556},
{54, 0x0036, 556},
{55, 0x0037, 556},
{56, 0x0038, 556},
{57, 0x0039, 556},
{58, 0x003A, 278},
{59, 0x003B, 278},
{60, 0x003C, 584},
{61, 0x003D, 584},
{62, 0x003E, 584},
{63, 0x003F, 556},
{64, 0x0040, 1015},
{65, 0x0041, 667},
{66, 0x0042, 667},
{67, 0x0043, 722},
{68, 0x0044, 722},
{69, 0x0045, 667},
{70, 0x0046, 611},
{71, 0x0047, 778},
{72, 0x0048, 722},
{73, 0x0049, 278},
{74, 0x004A, 500},
{75, 0x004B, 667},
{76, 0x004C, 556},
{77, 0x004D, 833},
{78, 0x004E, 722},
{79, 0x004F, 778},
{80, 0x0050, 667},
{81, 0x0051, 778},
{82, 0x0052, 722},
{83, 0x0053, 667},
{84, 0x0054, 611},
{85, 0x0055, 722},
{86, 0x0056, 667},
{87, 0x0057, 944},
{88, 0x0058, 667},
{89, 0x0059, 667},
{90, 0x005A, 611},
{91, 0x005B, 278},
{92, 0x005C, 278},
{93, 0x005D, 278},
{94, 0x005E, 469},
{95, 0x005F, 556},
{96, 0x2018, 222},
{97, 0x0061, 556},
{98, 0x0062, 556},
{99, 0x0063, 500},
{100, 0x0064, 556},
{101, 0x0065, 556},
{102, 0x0066, 278},
{103, 0x0067, 556},
{104, 0x0068, 556},
{105, 0x0069, 222},
{106, 0x006A, 222},
{107, 0x006B, 500},
{108, 0x006C, 222},
{109, 0x006D, 833},
{110, 0x006E, 556},
{111, 0x006F, 556},
{112, 0x0070, 556},
{113, 0x0071, 556},
{114, 0x0072, 333},
{115, 0x0073, 500},
{116, 0x0074, 278},
{117, 0x0075, 556},
{118, 0x0076, 500},
{119, 0x0077, 722},
{120, 0x0078, 500},
{121, 0x0079, 500},
{122, 0x007A, 500},
{123, 0x007B, 334},
{124, 0x007C, 260},
{125, 0x007D, 334},
{126, 0x007E, 584},
{161, 0x00A1, 333},
{162, 0x00A2, 556},
{163, 0x00A3, 556},
{164, 0x2044, 167},
{165, 0x00A5, 556},
{166, 0x0192, 556},
{167, 0x00A7, 556},
{168, 0x00A4, 556},
{169, 0x0027, 191},
{170, 0x201C, 333},
{171, 0x00AB, 556},
{172, 0x2039, 333},
{173, 0x203A, 333},
{174, 0xFB01, 500},
{175, 0xFB02, 500},
{177, 0x2013, 556},
{178, 0x2020, 556},
{179, 0x2021, 556},
{180, 0x00B7, 278},
{182, 0x00B6, 537},
{183, 0x2022, 350},
{184, 0x201A, 222},
{185, 0x201E, 333},
{186, 0x201D, 333},
{187, 0x00BB, 556},
{188, 0x2026, 1000},
{189, 0x2030, 1000},
{191, 0x00BF, 611},
{193, 0x0060, 333},
{194, 0x00B4, 333},
{195, 0x02C6, 333},
{196, 0x02DC, 333},
{197, 0x00AF, 333},
{198, 0x02D8, 333},
{199, 0x02D9, 333},
{200, 0x00A8, 333},
{202, 0x02DA, 333},
{203, 0x00B8, 333},
{205, 0x02DD, 333},
{206, 0x02DB, 333},
{207, 0x02C7, 333},
{208, 0x2014, 1000},
{225, 0x00C6, 1000},
{227, 0x00AA, 370},
{232, 0x0141, 556},
{233, 0x00D8, 778},
{234, 0x0152, 1000},
{235, 0x00BA, 365},
{241, 0x00E6, 889},
{245, 0x0131, 278},
{248, 0x0142, 222},
{249, 0x00F8, 611},
{250, 0x0153, 944},
{251, 0x00DF, 611},
{-1, 0x00CF, 278},
{-1, 0x00E9, 556},
{-1, 0x0103, 556},
{-1, 0x0171, 556},
{-1, 0x011B, 556},
{-1, 0x0178, 667},
{-1, 0x00F7, 584},
{-1, 0x00DD, 667},
{-1, 0x00C2, 667},
{-1, 0x00E1, 556},
{-1, 0x00DB, 722},
{-1, 0x00FD, 500},
{-1, 0x0219, 500},
{-1, 0x00EA, 556},
{-1, 0x016E, 722},
{-1, 0x00DC, 722},
{-1, 0x0105, 556},
{-1, 0x00DA, 722},
{-1, 0x0173, 556},
{-1, 0x00CB, 667},
{-1, 0x0110, 722},
{-1, 0xF6C3, 250},
{-1, 0x00A9, 737},
{-1, 0x0112, 667},
{-1, 0x010D, 500},
{-1, 0x00E5, 556},
{-1, 0x0145, 722},
{-1, 0x013A, 222},
{-1, 0x00E0, 556},
{-1, 0x0162, 611},
{-1, 0x0106, 722},
{-1, 0x00E3, 556},
{-1, 0x0116, 667},
{-1, 0x0161, 500},
{-1, 0x015F, 500},
{-1, 0x00ED, 278},
{-1, 0x25CA, 471},
{-1, 0x0158, 722},
{-1, 0x0122, 778},
{-1, 0x00FB, 556},
{-1, 0x00E2, 556},
{-1, 0x0100, 667},
{-1, 0x0159, 333},
{-1, 0x00E7, 500},
{-1, 0x017B, 611},
{-1, 0x00DE, 667},
{-1, 0x014C, 778},
{-1, 0x0154, 722},
{-1, 0x015A, 667},
{-1, 0x010F, 643},
{-1, 0x016A, 722},
{-1, 0x016F, 556},
{-1, 0x00B3, 333},
{-1, 0x00D2, 778},
{-1, 0x00C0, 667},
{-1, 0x0102, 667},
{-1, 0x00D7, 584},
{-1, 0x00FA, 556},
{-1, 0x0164, 611},
{-1, 0x2202, 476},
{-1, 0x00FF, 500},
{-1, 0x0143, 722},
{-1, 0x00EE, 278},
{-1, 0x00CA, 667},
{-1, 0x00E4, 556},
{-1, 0x00EB, 556},
{-1, 0x0107, 500},
{-1, 0x0144, 556},
{-1, 0x016B, 556},
{-1, 0x0147, 722},
{-1, 0x00CD, 278},
{-1, 0x00B1, 584},
{-1, 0x00A6, 260},
{-1, 0x00AE, 737},
{-1, 0x011E, 778},
{-1, 0x0130, 278},
{-1, 0x2211, 600},
{-1, 0x00C8, 667},
{-1, 0x0155, 333},
{-1, 0x014D, 556},
{-1, 0x0179, 611},
{-1, 0x017D, 611},
{-1, 0x2265, 549},
{-1, 0x00D0, 722},
{-1, 0x00C7, 722},
{-1, 0x013C, 222},
{-1, 0x0165, 316},
{-1, 0x0119, 556},
{-1, 0x0172, 722},
{-1, 0x00C1, 667},
{-1, 0x00C4, 667},
{-1, 0x00E8, 556},
{-1, 0x017A, 500},
{-1, 0x012F, 222},
{-1, 0x00D3, 778},
{-1, 0x00F3, 556},
{-1, 0x0101, 556},
{-1, 0x015B, 500},
{-1, 0x00EF, 278},
{-1, 0x00D4, 778},
{-1, 0x00D9, 722},
{-1, 0x0394, 612},
{-1, 0x00FE, 556},
{-1, 0x00B2, 333},
{-1, 0x00D6, 778},
{-1, 0x00B5, 556},
{-1, 0x00EC, 278},
{-1, 0x0151, 556},
{-1, 0x0118, 667},
{-1, 0x0111, 556},
{-1, 0x00BE, 834},
{-1, 0x015E, 667},
{-1, 0x013E, 299},
{-1, 0x0136, 667},
{-1, 0x0139, 556},
{-1, 0x2122, 1000},
{-1, 0x0117, 556},
{-1, 0x00CC, 278},
{-1, 0x012A, 278},
{-1, 0x013D, 556},
{-1, 0x00BD, 834},
{-1, 0x2264, 549},
{-1, 0x00F4, 556},
{-1, 0x00F1, 556},
{-1, 0x0170, 722},
{-1, 0x00C9, 667},
{-1, 0x0113, 556},
{-1, 0x011F, 556},
{-1, 0x00BC, 834},
{-1, 0x0160, 667},
{-1, 0x0218, 667},
{-1, 0x0150, 778},
{-1, 0x00B0, 400},
{-1, 0x00F2, 556},
{-1, 0x010C, 722},
{-1, 0x00F9, 556},
{-1, 0x221A, 453},
{-1, 0x010E, 722},
{-1, 0x0157, 333},
{-1, 0x00D1, 722},
{-1, 0x00F5, 556},
{-1, 0x0156, 722},
{-1, 0x013B, 556},
{-1, 0x00C3, 667},
{-1, 0x0104, 667},
{-1, 0x00C5, 667},
{-1, 0x00D5, 778},
{-1, 0x017C, 500},
{-1, 0x011A, 667},
{-1, 0x012E, 278},
{-1, 0x0137, 500},
{-1, 0x2212, 584},
{-1, 0x00CE, 278},
{-1, 0x0148, 556},
{-1, 0x0163, 278},
{-1, 0x00AC, 584},
{-1, 0x00F6, 556},
{-1, 0x00FC, 556},
{-1, 0x2260, 549},
{-1, 0x0123, 556},
{-1, 0x00F0, 556},
{-1, 0x017E, 500},
{-1, 0x0146, 556},
{-1, 0x00B9, 333},
{-1, 0x012B, 278},
{-1, 0x20AC, 556},
{-1, 0xFFFF, 0}
};
static const HPDF_CharData <API key>[316] = {
{32, 0x0020, 278},
{33, 0x0021, 333},
{34, 0x0022, 474},
{35, 0x0023, 556},
{36, 0x0024, 556},
{37, 0x0025, 889},
{38, 0x0026, 722},
{39, 0x2019, 278},
{40, 0x0028, 333},
{41, 0x0029, 333},
{42, 0x002A, 389},
{43, 0x002B, 584},
{44, 0x002C, 278},
{45, 0x002D, 333},
{46, 0x002E, 278},
{47, 0x002F, 278},
{48, 0x0030, 556},
{49, 0x0031, 556},
{50, 0x0032, 556},
{51, 0x0033, 556},
{52, 0x0034, 556},
{53, 0x0035, 556},
{54, 0x0036, 556},
{55, 0x0037, 556},
{56, 0x0038, 556},
{57, 0x0039, 556},
{58, 0x003A, 333},
{59, 0x003B, 333},
{60, 0x003C, 584},
{61, 0x003D, 584},
{62, 0x003E, 584},
{63, 0x003F, 611},
{64, 0x0040, 975},
{65, 0x0041, 722},
{66, 0x0042, 722},
{67, 0x0043, 722},
{68, 0x0044, 722},
{69, 0x0045, 667},
{70, 0x0046, 611},
{71, 0x0047, 778},
{72, 0x0048, 722},
{73, 0x0049, 278},
{74, 0x004A, 556},
{75, 0x004B, 722},
{76, 0x004C, 611},
{77, 0x004D, 833},
{78, 0x004E, 722},
{79, 0x004F, 778},
{80, 0x0050, 667},
{81, 0x0051, 778},
{82, 0x0052, 722},
{83, 0x0053, 667},
{84, 0x0054, 611},
{85, 0x0055, 722},
{86, 0x0056, 667},
{87, 0x0057, 944},
{88, 0x0058, 667},
{89, 0x0059, 667},
{90, 0x005A, 611},
{91, 0x005B, 333},
{92, 0x005C, 278},
{93, 0x005D, 333},
{94, 0x005E, 584},
{95, 0x005F, 556},
{96, 0x2018, 278},
{97, 0x0061, 556},
{98, 0x0062, 611},
{99, 0x0063, 556},
{100, 0x0064, 611},
{101, 0x0065, 556},
{102, 0x0066, 333},
{103, 0x0067, 611},
{104, 0x0068, 611},
{105, 0x0069, 278},
{106, 0x006A, 278},
{107, 0x006B, 556},
{108, 0x006C, 278},
{109, 0x006D, 889},
{110, 0x006E, 611},
{111, 0x006F, 611},
{112, 0x0070, 611},
{113, 0x0071, 611},
{114, 0x0072, 389},
{115, 0x0073, 556},
{116, 0x0074, 333},
{117, 0x0075, 611},
{118, 0x0076, 556},
{119, 0x0077, 778},
{120, 0x0078, 556},
{121, 0x0079, 556},
{122, 0x007A, 500},
{123, 0x007B, 389},
{124, 0x007C, 280},
{125, 0x007D, 389},
{126, 0x007E, 584},
{161, 0x00A1, 333},
{162, 0x00A2, 556},
{163, 0x00A3, 556},
{164, 0x2044, 167},
{165, 0x00A5, 556},
{166, 0x0192, 556},
{167, 0x00A7, 556},
{168, 0x00A4, 556},
{169, 0x0027, 238},
{170, 0x201C, 500},
{171, 0x00AB, 556},
{172, 0x2039, 333},
{173, 0x203A, 333},
{174, 0xFB01, 611},
{175, 0xFB02, 611},
{177, 0x2013, 556},
{178, 0x2020, 556},
{179, 0x2021, 556},
{180, 0x00B7, 278},
{182, 0x00B6, 556},
{183, 0x2022, 350},
{184, 0x201A, 278},
{185, 0x201E, 500},
{186, 0x201D, 500},
{187, 0x00BB, 556},
{188, 0x2026, 1000},
{189, 0x2030, 1000},
{191, 0x00BF, 611},
{193, 0x0060, 333},
{194, 0x00B4, 333},
{195, 0x02C6, 333},
{196, 0x02DC, 333},
{197, 0x00AF, 333},
{198, 0x02D8, 333},
{199, 0x02D9, 333},
{200, 0x00A8, 333},
{202, 0x02DA, 333},
{203, 0x00B8, 333},
{205, 0x02DD, 333},
{206, 0x02DB, 333},
{207, 0x02C7, 333},
{208, 0x2014, 1000},
{225, 0x00C6, 1000},
{227, 0x00AA, 370},
{232, 0x0141, 611},
{233, 0x00D8, 778},
{234, 0x0152, 1000},
{235, 0x00BA, 365},
{241, 0x00E6, 889},
{245, 0x0131, 278},
{248, 0x0142, 278},
{249, 0x00F8, 611},
{250, 0x0153, 944},
{251, 0x00DF, 611},
{-1, 0x00CF, 278},
{-1, 0x00E9, 556},
{-1, 0x0103, 556},
{-1, 0x0171, 611},
{-1, 0x011B, 556},
{-1, 0x0178, 667},
{-1, 0x00F7, 584},
{-1, 0x00DD, 667},
{-1, 0x00C2, 722},
{-1, 0x00E1, 556},
{-1, 0x00DB, 722},
{-1, 0x00FD, 556},
{-1, 0x0219, 556},
{-1, 0x00EA, 556},
{-1, 0x016E, 722},
{-1, 0x00DC, 722},
{-1, 0x0105, 556},
{-1, 0x00DA, 722},
{-1, 0x0173, 611},
{-1, 0x00CB, 667},
{-1, 0x0110, 722},
{-1, 0xF6C3, 250},
{-1, 0x00A9, 737},
{-1, 0x0112, 667},
{-1, 0x010D, 556},
{-1, 0x00E5, 556},
{-1, 0x0145, 722},
{-1, 0x013A, 278},
{-1, 0x00E0, 556},
{-1, 0x0162, 611},
{-1, 0x0106, 722},
{-1, 0x00E3, 556},
{-1, 0x0116, 667},
{-1, 0x0161, 556},
{-1, 0x015F, 556},
{-1, 0x00ED, 278},
{-1, 0x25CA, 494},
{-1, 0x0158, 722},
{-1, 0x0122, 778},
{-1, 0x00FB, 611},
{-1, 0x00E2, 556},
{-1, 0x0100, 722},
{-1, 0x0159, 389},
{-1, 0x00E7, 556},
{-1, 0x017B, 611},
{-1, 0x00DE, 667},
{-1, 0x014C, 778},
{-1, 0x0154, 722},
{-1, 0x015A, 667},
{-1, 0x010F, 743},
{-1, 0x016A, 722},
{-1, 0x016F, 611},
{-1, 0x00B3, 333},
{-1, 0x00D2, 778},
{-1, 0x00C0, 722},
{-1, 0x0102, 722},
{-1, 0x00D7, 584},
{-1, 0x00FA, 611},
{-1, 0x0164, 611},
{-1, 0x2202, 494},
{-1, 0x00FF, 556},
{-1, 0x0143, 722},
{-1, 0x00EE, 278},
{-1, 0x00CA, 667},
{-1, 0x00E4, 556},
{-1, 0x00EB, 556},
{-1, 0x0107, 556},
{-1, 0x0144, 611},
{-1, 0x016B, 611},
{-1, 0x0147, 722},
{-1, 0x00CD, 278},
{-1, 0x00B1, 584},
{-1, 0x00A6, 280},
{-1, 0x00AE, 737},
{-1, 0x011E, 778},
{-1, 0x0130, 278},
{-1, 0x2211, 600},
{-1, 0x00C8, 667},
{-1, 0x0155, 389},
{-1, 0x014D, 611},
{-1, 0x0179, 611},
{-1, 0x017D, 611},
{-1, 0x2265, 549},
{-1, 0x00D0, 722},
{-1, 0x00C7, 722},
{-1, 0x013C, 278},
{-1, 0x0165, 389},
{-1, 0x0119, 556},
{-1, 0x0172, 722},
{-1, 0x00C1, 722},
{-1, 0x00C4, 722},
{-1, 0x00E8, 556},
{-1, 0x017A, 500},
{-1, 0x012F, 278},
{-1, 0x00D3, 778},
{-1, 0x00F3, 611},
{-1, 0x0101, 556},
{-1, 0x015B, 556},
{-1, 0x00EF, 278},
{-1, 0x00D4, 778},
{-1, 0x00D9, 722},
{-1, 0x0394, 612},
{-1, 0x00FE, 611},
{-1, 0x00B2, 333},
{-1, 0x00D6, 778},
{-1, 0x00B5, 611},
{-1, 0x00EC, 278},
{-1, 0x0151, 611},
{-1, 0x0118, 667},
{-1, 0x0111, 611},
{-1, 0x00BE, 834},
{-1, 0x015E, 667},
{-1, 0x013E, 400},
{-1, 0x0136, 722},
{-1, 0x0139, 611},
{-1, 0x2122, 1000},
{-1, 0x0117, 556},
{-1, 0x00CC, 278},
{-1, 0x012A, 278},
{-1, 0x013D, 611},
{-1, 0x00BD, 834},
{-1, 0x2264, 549},
{-1, 0x00F4, 611},
{-1, 0x00F1, 611},
{-1, 0x0170, 722},
{-1, 0x00C9, 667},
{-1, 0x0113, 556},
{-1, 0x011F, 611},
{-1, 0x00BC, 834},
{-1, 0x0160, 667},
{-1, 0x0218, 667},
{-1, 0x0150, 778},
{-1, 0x00B0, 400},
{-1, 0x00F2, 611},
{-1, 0x010C, 722},
{-1, 0x00F9, 611},
{-1, 0x221A, 549},
{-1, 0x010E, 722},
{-1, 0x0157, 389},
{-1, 0x00D1, 722},
{-1, 0x00F5, 611},
{-1, 0x0156, 722},
{-1, 0x013B, 611},
{-1, 0x00C3, 722},
{-1, 0x0104, 722},
{-1, 0x00C5, 722},
{-1, 0x00D5, 778},
{-1, 0x017C, 500},
{-1, 0x011A, 667},
{-1, 0x012E, 278},
{-1, 0x0137, 556},
{-1, 0x2212, 584},
{-1, 0x00CE, 278},
{-1, 0x0148, 611},
{-1, 0x0163, 333},
{-1, 0x00AC, 584},
{-1, 0x00F6, 611},
{-1, 0x00FC, 611},
{-1, 0x2260, 549},
{-1, 0x0123, 611},
{-1, 0x00F0, 611},
{-1, 0x017E, 500},
{-1, 0x0146, 611},
{-1, 0x00B9, 333},
{-1, 0x012B, 278},
{-1, 0x20AC, 556},
{-1, 0xFFFF, 0}
};
static const HPDF_CharData <API key>[316] = {
{32, 0x0020, 278},
{33, 0x0021, 333},
{34, 0x0022, 474},
{35, 0x0023, 556},
{36, 0x0024, 556},
{37, 0x0025, 889},
{38, 0x0026, 722},
{39, 0x2019, 278},
{40, 0x0028, 333},
{41, 0x0029, 333},
{42, 0x002A, 389},
{43, 0x002B, 584},
{44, 0x002C, 278},
{45, 0x002D, 333},
{46, 0x002E, 278},
{47, 0x002F, 278},
{48, 0x0030, 556},
{49, 0x0031, 556},
{50, 0x0032, 556},
{51, 0x0033, 556},
{52, 0x0034, 556},
{53, 0x0035, 556},
{54, 0x0036, 556},
{55, 0x0037, 556},
{56, 0x0038, 556},
{57, 0x0039, 556},
{58, 0x003A, 333},
{59, 0x003B, 333},
{60, 0x003C, 584},
{61, 0x003D, 584},
{62, 0x003E, 584},
{63, 0x003F, 611},
{64, 0x0040, 975},
{65, 0x0041, 722},
{66, 0x0042, 722},
{67, 0x0043, 722},
{68, 0x0044, 722},
{69, 0x0045, 667},
{70, 0x0046, 611},
{71, 0x0047, 778},
{72, 0x0048, 722},
{73, 0x0049, 278},
{74, 0x004A, 556},
{75, 0x004B, 722},
{76, 0x004C, 611},
{77, 0x004D, 833},
{78, 0x004E, 722},
{79, 0x004F, 778},
{80, 0x0050, 667},
{81, 0x0051, 778},
{82, 0x0052, 722},
{83, 0x0053, 667},
{84, 0x0054, 611},
{85, 0x0055, 722},
{86, 0x0056, 667},
{87, 0x0057, 944},
{88, 0x0058, 667},
{89, 0x0059, 667},
{90, 0x005A, 611},
{91, 0x005B, 333},
{92, 0x005C, 278},
{93, 0x005D, 333},
{94, 0x005E, 584},
{95, 0x005F, 556},
{96, 0x2018, 278},
{97, 0x0061, 556},
{98, 0x0062, 611},
{99, 0x0063, 556},
{100, 0x0064, 611},
{101, 0x0065, 556},
{102, 0x0066, 333},
{103, 0x0067, 611},
{104, 0x0068, 611},
{105, 0x0069, 278},
{106, 0x006A, 278},
{107, 0x006B, 556},
{108, 0x006C, 278},
{109, 0x006D, 889},
{110, 0x006E, 611},
{111, 0x006F, 611},
{112, 0x0070, 611},
{113, 0x0071, 611},
{114, 0x0072, 389},
{115, 0x0073, 556},
{116, 0x0074, 333},
{117, 0x0075, 611},
{118, 0x0076, 556},
{119, 0x0077, 778},
{120, 0x0078, 556},
{121, 0x0079, 556},
{122, 0x007A, 500},
{123, 0x007B, 389},
{124, 0x007C, 280},
{125, 0x007D, 389},
{126, 0x007E, 584},
{161, 0x00A1, 333},
{162, 0x00A2, 556},
{163, 0x00A3, 556},
{164, 0x2044, 167},
{165, 0x00A5, 556},
{166, 0x0192, 556},
{167, 0x00A7, 556},
{168, 0x00A4, 556},
{169, 0x0027, 238},
{170, 0x201C, 500},
{171, 0x00AB, 556},
{172, 0x2039, 333},
{173, 0x203A, 333},
{174, 0xFB01, 611},
{175, 0xFB02, 611},
{177, 0x2013, 556},
{178, 0x2020, 556},
{179, 0x2021, 556},
{180, 0x00B7, 278},
{182, 0x00B6, 556},
{183, 0x2022, 350},
{184, 0x201A, 278},
{185, 0x201E, 500},
{186, 0x201D, 500},
{187, 0x00BB, 556},
{188, 0x2026, 1000},
{189, 0x2030, 1000},
{191, 0x00BF, 611},
{193, 0x0060, 333},
{194, 0x00B4, 333},
{195, 0x02C6, 333},
{196, 0x02DC, 333},
{197, 0x00AF, 333},
{198, 0x02D8, 333},
{199, 0x02D9, 333},
{200, 0x00A8, 333},
{202, 0x02DA, 333},
{203, 0x00B8, 333},
{205, 0x02DD, 333},
{206, 0x02DB, 333},
{207, 0x02C7, 333},
{208, 0x2014, 1000},
{225, 0x00C6, 1000},
{227, 0x00AA, 370},
{232, 0x0141, 611},
{233, 0x00D8, 778},
{234, 0x0152, 1000},
{235, 0x00BA, 365},
{241, 0x00E6, 889},
{245, 0x0131, 278},
{248, 0x0142, 278},
{249, 0x00F8, 611},
{250, 0x0153, 944},
{251, 0x00DF, 611},
{-1, 0x00CF, 278},
{-1, 0x00E9, 556},
{-1, 0x0103, 556},
{-1, 0x0171, 611},
{-1, 0x011B, 556},
{-1, 0x0178, 667},
{-1, 0x00F7, 584},
{-1, 0x00DD, 667},
{-1, 0x00C2, 722},
{-1, 0x00E1, 556},
{-1, 0x00DB, 722},
{-1, 0x00FD, 556},
{-1, 0x0219, 556},
{-1, 0x00EA, 556},
{-1, 0x016E, 722},
{-1, 0x00DC, 722},
{-1, 0x0105, 556},
{-1, 0x00DA, 722},
{-1, 0x0173, 611},
{-1, 0x00CB, 667},
{-1, 0x0110, 722},
{-1, 0xF6C3, 250},
{-1, 0x00A9, 737},
{-1, 0x0112, 667},
{-1, 0x010D, 556},
{-1, 0x00E5, 556},
{-1, 0x0145, 722},
{-1, 0x013A, 278},
{-1, 0x00E0, 556},
{-1, 0x0162, 611},
{-1, 0x0106, 722},
{-1, 0x00E3, 556},
{-1, 0x0116, 667},
{-1, 0x0161, 556},
{-1, 0x015F, 556},
{-1, 0x00ED, 278},
{-1, 0x25CA, 494},
{-1, 0x0158, 722},
{-1, 0x0122, 778},
{-1, 0x00FB, 611},
{-1, 0x00E2, 556},
{-1, 0x0100, 722},
{-1, 0x0159, 389},
{-1, 0x00E7, 556},
{-1, 0x017B, 611},
{-1, 0x00DE, 667},
{-1, 0x014C, 778},
{-1, 0x0154, 722},
{-1, 0x015A, 667},
{-1, 0x010F, 743},
{-1, 0x016A, 722},
{-1, 0x016F, 611},
{-1, 0x00B3, 333},
{-1, 0x00D2, 778},
{-1, 0x00C0, 722},
{-1, 0x0102, 722},
{-1, 0x00D7, 584},
{-1, 0x00FA, 611},
{-1, 0x0164, 611},
{-1, 0x2202, 494},
{-1, 0x00FF, 556},
{-1, 0x0143, 722},
{-1, 0x00EE, 278},
{-1, 0x00CA, 667},
{-1, 0x00E4, 556},
{-1, 0x00EB, 556},
{-1, 0x0107, 556},
{-1, 0x0144, 611},
{-1, 0x016B, 611},
{-1, 0x0147, 722},
{-1, 0x00CD, 278},
{-1, 0x00B1, 584},
{-1, 0x00A6, 280},
{-1, 0x00AE, 737},
{-1, 0x011E, 778},
{-1, 0x0130, 278},
{-1, 0x2211, 600},
{-1, 0x00C8, 667},
{-1, 0x0155, 389},
{-1, 0x014D, 611},
{-1, 0x0179, 611},
{-1, 0x017D, 611},
{-1, 0x2265, 549},
{-1, 0x00D0, 722},
{-1, 0x00C7, 722},
{-1, 0x013C, 278},
{-1, 0x0165, 389},
{-1, 0x0119, 556},
{-1, 0x0172, 722},
{-1, 0x00C1, 722},
{-1, 0x00C4, 722},
{-1, 0x00E8, 556},
{-1, 0x017A, 500},
{-1, 0x012F, 278},
{-1, 0x00D3, 778},
{-1, 0x00F3, 611},
{-1, 0x0101, 556},
{-1, 0x015B, 556},
{-1, 0x00EF, 278},
{-1, 0x00D4, 778},
{-1, 0x00D9, 722},
{-1, 0x0394, 612},
{-1, 0x00FE, 611},
{-1, 0x00B2, 333},
{-1, 0x00D6, 778},
{-1, 0x00B5, 611},
{-1, 0x00EC, 278},
{-1, 0x0151, 611},
{-1, 0x0118, 667},
{-1, 0x0111, 611},
{-1, 0x00BE, 834},
{-1, 0x015E, 667},
{-1, 0x013E, 400},
{-1, 0x0136, 722},
{-1, 0x0139, 611},
{-1, 0x2122, 1000},
{-1, 0x0117, 556},
{-1, 0x00CC, 278},
{-1, 0x012A, 278},
{-1, 0x013D, 611},
{-1, 0x00BD, 834},
{-1, 0x2264, 549},
{-1, 0x00F4, 611},
{-1, 0x00F1, 611},
{-1, 0x0170, 722},
{-1, 0x00C9, 667},
{-1, 0x0113, 556},
{-1, 0x011F, 611},
{-1, 0x00BC, 834},
{-1, 0x0160, 667},
{-1, 0x0218, 667},
{-1, 0x0150, 778},
{-1, 0x00B0, 400},
{-1, 0x00F2, 611},
{-1, 0x010C, 722},
{-1, 0x00F9, 611},
{-1, 0x221A, 549},
{-1, 0x010E, 722},
{-1, 0x0157, 389},
{-1, 0x00D1, 722},
{-1, 0x00F5, 611},
{-1, 0x0156, 722},
{-1, 0x013B, 611},
{-1, 0x00C3, 722},
{-1, 0x0104, 722},
{-1, 0x00C5, 722},
{-1, 0x00D5, 778},
{-1, 0x017C, 500},
{-1, 0x011A, 667},
{-1, 0x012E, 278},
{-1, 0x0137, 556},
{-1, 0x2212, 584},
{-1, 0x00CE, 278},
{-1, 0x0148, 611},
{-1, 0x0163, 333},
{-1, 0x00AC, 584},
{-1, 0x00F6, 611},
{-1, 0x00FC, 611},
{-1, 0x2260, 549},
{-1, 0x0123, 611},
{-1, 0x00F0, 611},
{-1, 0x017E, 500},
{-1, 0x0146, 611},
{-1, 0x00B9, 333},
{-1, 0x012B, 278},
{-1, 0x20AC, 556},
{-1, 0xFFFF, 0}
};
static const HPDF_CharData <API key>[316] = {
{32, 0x0020, 278},
{33, 0x0021, 278},
{34, 0x0022, 355},
{35, 0x0023, 556},
{36, 0x0024, 556},
{37, 0x0025, 889},
{38, 0x0026, 667},
{39, 0x2019, 222},
{40, 0x0028, 333},
{41, 0x0029, 333},
{42, 0x002A, 389},
{43, 0x002B, 584},
{44, 0x002C, 278},
{45, 0x002D, 333},
{46, 0x002E, 278},
{47, 0x002F, 278},
{48, 0x0030, 556},
{49, 0x0031, 556},
{50, 0x0032, 556},
{51, 0x0033, 556},
{52, 0x0034, 556},
{53, 0x0035, 556},
{54, 0x0036, 556},
{55, 0x0037, 556},
{56, 0x0038, 556},
{57, 0x0039, 556},
{58, 0x003A, 278},
{59, 0x003B, 278},
{60, 0x003C, 584},
{61, 0x003D, 584},
{62, 0x003E, 584},
{63, 0x003F, 556},
{64, 0x0040, 1015},
{65, 0x0041, 667},
{66, 0x0042, 667},
{67, 0x0043, 722},
{68, 0x0044, 722},
{69, 0x0045, 667},
{70, 0x0046, 611},
{71, 0x0047, 778},
{72, 0x0048, 722},
{73, 0x0049, 278},
{74, 0x004A, 500},
{75, 0x004B, 667},
{76, 0x004C, 556},
{77, 0x004D, 833},
{78, 0x004E, 722},
{79, 0x004F, 778},
{80, 0x0050, 667},
{81, 0x0051, 778},
{82, 0x0052, 722},
{83, 0x0053, 667},
{84, 0x0054, 611},
{85, 0x0055, 722},
{86, 0x0056, 667},
{87, 0x0057, 944},
{88, 0x0058, 667},
{89, 0x0059, 667},
{90, 0x005A, 611},
{91, 0x005B, 278},
{92, 0x005C, 278},
{93, 0x005D, 278},
{94, 0x005E, 469},
{95, 0x005F, 556},
{96, 0x2018, 222},
{97, 0x0061, 556},
{98, 0x0062, 556},
{99, 0x0063, 500},
{100, 0x0064, 556},
{101, 0x0065, 556},
{102, 0x0066, 278},
{103, 0x0067, 556},
{104, 0x0068, 556},
{105, 0x0069, 222},
{106, 0x006A, 222},
{107, 0x006B, 500},
{108, 0x006C, 222},
{109, 0x006D, 833},
{110, 0x006E, 556},
{111, 0x006F, 556},
{112, 0x0070, 556},
{113, 0x0071, 556},
{114, 0x0072, 333},
{115, 0x0073, 500},
{116, 0x0074, 278},
{117, 0x0075, 556},
{118, 0x0076, 500},
{119, 0x0077, 722},
{120, 0x0078, 500},
{121, 0x0079, 500},
{122, 0x007A, 500},
{123, 0x007B, 334},
{124, 0x007C, 260},
{125, 0x007D, 334},
{126, 0x007E, 584},
{161, 0x00A1, 333},
{162, 0x00A2, 556},
{163, 0x00A3, 556},
{164, 0x2044, 167},
{165, 0x00A5, 556},
{166, 0x0192, 556},
{167, 0x00A7, 556},
{168, 0x00A4, 556},
{169, 0x0027, 191},
{170, 0x201C, 333},
{171, 0x00AB, 556},
{172, 0x2039, 333},
{173, 0x203A, 333},
{174, 0xFB01, 500},
{175, 0xFB02, 500},
{177, 0x2013, 556},
{178, 0x2020, 556},
{179, 0x2021, 556},
{180, 0x00B7, 278},
{182, 0x00B6, 537},
{183, 0x2022, 350},
{184, 0x201A, 222},
{185, 0x201E, 333},
{186, 0x201D, 333},
{187, 0x00BB, 556},
{188, 0x2026, 1000},
{189, 0x2030, 1000},
{191, 0x00BF, 611},
{193, 0x0060, 333},
{194, 0x00B4, 333},
{195, 0x02C6, 333},
{196, 0x02DC, 333},
{197, 0x00AF, 333},
{198, 0x02D8, 333},
{199, 0x02D9, 333},
{200, 0x00A8, 333},
{202, 0x02DA, 333},
{203, 0x00B8, 333},
{205, 0x02DD, 333},
{206, 0x02DB, 333},
{207, 0x02C7, 333},
{208, 0x2014, 1000},
{225, 0x00C6, 1000},
{227, 0x00AA, 370},
{232, 0x0141, 556},
{233, 0x00D8, 778},
{234, 0x0152, 1000},
{235, 0x00BA, 365},
{241, 0x00E6, 889},
{245, 0x0131, 278},
{248, 0x0142, 222},
{249, 0x00F8, 611},
{250, 0x0153, 944},
{251, 0x00DF, 611},
{-1, 0x00CF, 278},
{-1, 0x00E9, 556},
{-1, 0x0103, 556},
{-1, 0x0171, 556},
{-1, 0x011B, 556},
{-1, 0x0178, 667},
{-1, 0x00F7, 584},
{-1, 0x00DD, 667},
{-1, 0x00C2, 667},
{-1, 0x00E1, 556},
{-1, 0x00DB, 722},
{-1, 0x00FD, 500},
{-1, 0x0219, 500},
{-1, 0x00EA, 556},
{-1, 0x016E, 722},
{-1, 0x00DC, 722},
{-1, 0x0105, 556},
{-1, 0x00DA, 722},
{-1, 0x0173, 556},
{-1, 0x00CB, 667},
{-1, 0x0110, 722},
{-1, 0xF6C3, 250},
{-1, 0x00A9, 737},
{-1, 0x0112, 667},
{-1, 0x010D, 500},
{-1, 0x00E5, 556},
{-1, 0x0145, 722},
{-1, 0x013A, 222},
{-1, 0x00E0, 556},
{-1, 0x0162, 611},
{-1, 0x0106, 722},
{-1, 0x00E3, 556},
{-1, 0x0116, 667},
{-1, 0x0161, 500},
{-1, 0x015F, 500},
{-1, 0x00ED, 278},
{-1, 0x25CA, 471},
{-1, 0x0158, 722},
{-1, 0x0122, 778},
{-1, 0x00FB, 556},
{-1, 0x00E2, 556},
{-1, 0x0100, 667},
{-1, 0x0159, 333},
{-1, 0x00E7, 500},
{-1, 0x017B, 611},
{-1, 0x00DE, 667},
{-1, 0x014C, 778},
{-1, 0x0154, 722},
{-1, 0x015A, 667},
{-1, 0x010F, 643},
{-1, 0x016A, 722},
{-1, 0x016F, 556},
{-1, 0x00B3, 333},
{-1, 0x00D2, 778},
{-1, 0x00C0, 667},
{-1, 0x0102, 667},
{-1, 0x00D7, 584},
{-1, 0x00FA, 556},
{-1, 0x0164, 611},
{-1, 0x2202, 476},
{-1, 0x00FF, 500},
{-1, 0x0143, 722},
{-1, 0x00EE, 278},
{-1, 0x00CA, 667},
{-1, 0x00E4, 556},
{-1, 0x00EB, 556},
{-1, 0x0107, 500},
{-1, 0x0144, 556},
{-1, 0x016B, 556},
{-1, 0x0147, 722},
{-1, 0x00CD, 278},
{-1, 0x00B1, 584},
{-1, 0x00A6, 260},
{-1, 0x00AE, 737},
{-1, 0x011E, 778},
{-1, 0x0130, 278},
{-1, 0x2211, 600},
{-1, 0x00C8, 667},
{-1, 0x0155, 333},
{-1, 0x014D, 556},
{-1, 0x0179, 611},
{-1, 0x017D, 611},
{-1, 0x2265, 549},
{-1, 0x00D0, 722},
{-1, 0x00C7, 722},
{-1, 0x013C, 222},
{-1, 0x0165, 316},
{-1, 0x0119, 556},
{-1, 0x0172, 722},
{-1, 0x00C1, 667},
{-1, 0x00C4, 667},
{-1, 0x00E8, 556},
{-1, 0x017A, 500},
{-1, 0x012F, 222},
{-1, 0x00D3, 778},
{-1, 0x00F3, 556},
{-1, 0x0101, 556},
{-1, 0x015B, 500},
{-1, 0x00EF, 278},
{-1, 0x00D4, 778},
{-1, 0x00D9, 722},
{-1, 0x0394, 612},
{-1, 0x00FE, 556},
{-1, 0x00B2, 333},
{-1, 0x00D6, 778},
{-1, 0x00B5, 556},
{-1, 0x00EC, 278},
{-1, 0x0151, 556},
{-1, 0x0118, 667},
{-1, 0x0111, 556},
{-1, 0x00BE, 834},
{-1, 0x015E, 667},
{-1, 0x013E, 299},
{-1, 0x0136, 667},
{-1, 0x0139, 556},
{-1, 0x2122, 1000},
{-1, 0x0117, 556},
{-1, 0x00CC, 278},
{-1, 0x012A, 278},
{-1, 0x013D, 556},
{-1, 0x00BD, 834},
{-1, 0x2264, 549},
{-1, 0x00F4, 556},
{-1, 0x00F1, 556},
{-1, 0x0170, 722},
{-1, 0x00C9, 667},
{-1, 0x0113, 556},
{-1, 0x011F, 556},
{-1, 0x00BC, 834},
{-1, 0x0160, 667},
{-1, 0x0218, 667},
{-1, 0x0150, 778},
{-1, 0x00B0, 400},
{-1, 0x00F2, 556},
{-1, 0x010C, 722},
{-1, 0x00F9, 556},
{-1, 0x221A, 453},
{-1, 0x010E, 722},
{-1, 0x0157, 333},
{-1, 0x00D1, 722},
{-1, 0x00F5, 556},
{-1, 0x0156, 722},
{-1, 0x013B, 556},
{-1, 0x00C3, 667},
{-1, 0x0104, 667},
{-1, 0x00C5, 667},
{-1, 0x00D5, 778},
{-1, 0x017C, 500},
{-1, 0x011A, 667},
{-1, 0x012E, 278},
{-1, 0x0137, 500},
{-1, 0x2212, 584},
{-1, 0x00CE, 278},
{-1, 0x0148, 556},
{-1, 0x0163, 278},
{-1, 0x00AC, 584},
{-1, 0x00F6, 556},
{-1, 0x00FC, 556},
{-1, 0x2260, 549},
{-1, 0x0123, 556},
{-1, 0x00F0, 556},
{-1, 0x017E, 500},
{-1, 0x0146, 556},
{-1, 0x00B9, 333},
{-1, 0x012B, 278},
{-1, 0x20AC, 556},
{-1, 0xFFFF, 0}
};
static const HPDF_CharData <API key>[316] = {
{32, 0x0020, 250},
{33, 0x0021, 333},
{34, 0x0022, 408},
{35, 0x0023, 500},
{36, 0x0024, 500},
{37, 0x0025, 833},
{38, 0x0026, 778},
{39, 0x2019, 333},
{40, 0x0028, 333},
{41, 0x0029, 333},
{42, 0x002A, 500},
{43, 0x002B, 564},
{44, 0x002C, 250},
{45, 0x002D, 333},
{46, 0x002E, 250},
{47, 0x002F, 278},
{48, 0x0030, 500},
{49, 0x0031, 500},
{50, 0x0032, 500},
{51, 0x0033, 500},
{52, 0x0034, 500},
{53, 0x0035, 500},
{54, 0x0036, 500},
{55, 0x0037, 500},
{56, 0x0038, 500},
{57, 0x0039, 500},
{58, 0x003A, 278},
{59, 0x003B, 278},
{60, 0x003C, 564},
{61, 0x003D, 564},
{62, 0x003E, 564},
{63, 0x003F, 444},
{64, 0x0040, 921},
{65, 0x0041, 722},
{66, 0x0042, 667},
{67, 0x0043, 667},
{68, 0x0044, 722},
{69, 0x0045, 611},
{70, 0x0046, 556},
{71, 0x0047, 722},
{72, 0x0048, 722},
{73, 0x0049, 333},
{74, 0x004A, 389},
{75, 0x004B, 722},
{76, 0x004C, 611},
{77, 0x004D, 889},
{78, 0x004E, 722},
{79, 0x004F, 722},
{80, 0x0050, 556},
{81, 0x0051, 722},
{82, 0x0052, 667},
{83, 0x0053, 556},
{84, 0x0054, 611},
{85, 0x0055, 722},
{86, 0x0056, 722},
{87, 0x0057, 944},
{88, 0x0058, 722},
{89, 0x0059, 722},
{90, 0x005A, 611},
{91, 0x005B, 333},
{92, 0x005C, 278},
{93, 0x005D, 333},
{94, 0x005E, 469},
{95, 0x005F, 500},
{96, 0x2018, 333},
{97, 0x0061, 444},
{98, 0x0062, 500},
{99, 0x0063, 444},
{100, 0x0064, 500},
{101, 0x0065, 444},
{102, 0x0066, 333},
{103, 0x0067, 500},
{104, 0x0068, 500},
{105, 0x0069, 278},
{106, 0x006A, 278},
{107, 0x006B, 500},
{108, 0x006C, 278},
{109, 0x006D, 778},
{110, 0x006E, 500},
{111, 0x006F, 500},
{112, 0x0070, 500},
{113, 0x0071, 500},
{114, 0x0072, 333},
{115, 0x0073, 389},
{116, 0x0074, 278},
{117, 0x0075, 500},
{118, 0x0076, 500},
{119, 0x0077, 722},
{120, 0x0078, 500},
{121, 0x0079, 500},
{122, 0x007A, 444},
{123, 0x007B, 480},
{124, 0x007C, 200},
{125, 0x007D, 480},
{126, 0x007E, 541},
{161, 0x00A1, 333},
{162, 0x00A2, 500},
{163, 0x00A3, 500},
{164, 0x2044, 167},
{165, 0x00A5, 500},
{166, 0x0192, 500},
{167, 0x00A7, 500},
{168, 0x00A4, 500},
{169, 0x0027, 180},
{170, 0x201C, 444},
{171, 0x00AB, 500},
{172, 0x2039, 333},
{173, 0x203A, 333},
{174, 0xFB01, 556},
{175, 0xFB02, 556},
{177, 0x2013, 500},
{178, 0x2020, 500},
{179, 0x2021, 500},
{180, 0x00B7, 250},
{182, 0x00B6, 453},
{183, 0x2022, 350},
{184, 0x201A, 333},
{185, 0x201E, 444},
{186, 0x201D, 444},
{187, 0x00BB, 500},
{188, 0x2026, 1000},
{189, 0x2030, 1000},
{191, 0x00BF, 444},
{193, 0x0060, 333},
{194, 0x00B4, 333},
{195, 0x02C6, 333},
{196, 0x02DC, 333},
{197, 0x00AF, 333},
{198, 0x02D8, 333},
{199, 0x02D9, 333},
{200, 0x00A8, 333},
{202, 0x02DA, 333},
{203, 0x00B8, 333},
{205, 0x02DD, 333},
{206, 0x02DB, 333},
{207, 0x02C7, 333},
{208, 0x2014, 1000},
{225, 0x00C6, 889},
{227, 0x00AA, 276},
{232, 0x0141, 611},
{233, 0x00D8, 722},
{234, 0x0152, 889},
{235, 0x00BA, 310},
{241, 0x00E6, 667},
{245, 0x0131, 278},
{248, 0x0142, 278},
{249, 0x00F8, 500},
{250, 0x0153, 722},
{251, 0x00DF, 500},
{-1, 0x00CF, 333},
{-1, 0x00E9, 444},
{-1, 0x0103, 444},
{-1, 0x0171, 500},
{-1, 0x011B, 444},
{-1, 0x0178, 722},
{-1, 0x00F7, 564},
{-1, 0x00DD, 722},
{-1, 0x00C2, 722},
{-1, 0x00E1, 444},
{-1, 0x00DB, 722},
{-1, 0x00FD, 500},
{-1, 0x0219, 389},
{-1, 0x00EA, 444},
{-1, 0x016E, 722},
{-1, 0x00DC, 722},
{-1, 0x0105, 444},
{-1, 0x00DA, 722},
{-1, 0x0173, 500},
{-1, 0x00CB, 611},
{-1, 0x0110, 722},
{-1, 0xF6C3, 250},
{-1, 0x00A9, 760},
{-1, 0x0112, 611},
{-1, 0x010D, 444},
{-1, 0x00E5, 444},
{-1, 0x0145, 722},
{-1, 0x013A, 278},
{-1, 0x00E0, 444},
{-1, 0x0162, 611},
{-1, 0x0106, 667},
{-1, 0x00E3, 444},
{-1, 0x0116, 611},
{-1, 0x0161, 389},
{-1, 0x015F, 389},
{-1, 0x00ED, 278},
{-1, 0x25CA, 471},
{-1, 0x0158, 667},
{-1, 0x0122, 722},
{-1, 0x00FB, 500},
{-1, 0x00E2, 444},
{-1, 0x0100, 722},
{-1, 0x0159, 333},
{-1, 0x00E7, 444},
{-1, 0x017B, 611},
{-1, 0x00DE, 556},
{-1, 0x014C, 722},
{-1, 0x0154, 667},
{-1, 0x015A, 556},
{-1, 0x010F, 588},
{-1, 0x016A, 722},
{-1, 0x016F, 500},
{-1, 0x00B3, 300},
{-1, 0x00D2, 722},
{-1, 0x00C0, 722},
{-1, 0x0102, 722},
{-1, 0x00D7, 564},
{-1, 0x00FA, 500},
{-1, 0x0164, 611},
{-1, 0x2202, 476},
{-1, 0x00FF, 500},
{-1, 0x0143, 722},
{-1, 0x00EE, 278},
{-1, 0x00CA, 611},
{-1, 0x00E4, 444},
{-1, 0x00EB, 444},
{-1, 0x0107, 444},
{-1, 0x0144, 500},
{-1, 0x016B, 500},
{-1, 0x0147, 722},
{-1, 0x00CD, 333},
{-1, 0x00B1, 564},
{-1, 0x00A6, 200},
{-1, 0x00AE, 760},
{-1, 0x011E, 722},
{-1, 0x0130, 333},
{-1, 0x2211, 600},
{-1, 0x00C8, 611},
{-1, 0x0155, 333},
{-1, 0x014D, 500},
{-1, 0x0179, 611},
{-1, 0x017D, 611},
{-1, 0x2265, 549},
{-1, 0x00D0, 722},
{-1, 0x00C7, 667},
{-1, 0x013C, 278},
{-1, 0x0165, 326},
{-1, 0x0119, 444},
{-1, 0x0172, 722},
{-1, 0x00C1, 722},
{-1, 0x00C4, 722},
{-1, 0x00E8, 444},
{-1, 0x017A, 444},
{-1, 0x012F, 278},
{-1, 0x00D3, 722},
{-1, 0x00F3, 500},
{-1, 0x0101, 444},
{-1, 0x015B, 389},
{-1, 0x00EF, 278},
{-1, 0x00D4, 722},
{-1, 0x00D9, 722},
{-1, 0x0394, 612},
{-1, 0x00FE, 500},
{-1, 0x00B2, 300},
{-1, 0x00D6, 722},
{-1, 0x00B5, 500},
{-1, 0x00EC, 278},
{-1, 0x0151, 500},
{-1, 0x0118, 611},
{-1, 0x0111, 500},
{-1, 0x00BE, 750},
{-1, 0x015E, 556},
{-1, 0x013E, 344},
{-1, 0x0136, 722},
{-1, 0x0139, 611},
{-1, 0x2122, 980},
{-1, 0x0117, 444},
{-1, 0x00CC, 333},
{-1, 0x012A, 333},
{-1, 0x013D, 611},
{-1, 0x00BD, 750},
{-1, 0x2264, 549},
{-1, 0x00F4, 500},
{-1, 0x00F1, 500},
{-1, 0x0170, 722},
{-1, 0x00C9, 611},
{-1, 0x0113, 444},
{-1, 0x011F, 500},
{-1, 0x00BC, 750},
{-1, 0x0160, 556},
{-1, 0x0218, 556},
{-1, 0x0150, 722},
{-1, 0x00B0, 400},
{-1, 0x00F2, 500},
{-1, 0x010C, 667},
{-1, 0x00F9, 500},
{-1, 0x221A, 453},
{-1, 0x010E, 722},
{-1, 0x0157, 333},
{-1, 0x00D1, 722},
{-1, 0x00F5, 500},
{-1, 0x0156, 667},
{-1, 0x013B, 611},
{-1, 0x00C3, 722},
{-1, 0x0104, 722},
{-1, 0x00C5, 722},
{-1, 0x00D5, 722},
{-1, 0x017C, 444},
{-1, 0x011A, 611},
{-1, 0x012E, 333},
{-1, 0x0137, 500},
{-1, 0x2212, 564},
{-1, 0x00CE, 333},
{-1, 0x0148, 500},
{-1, 0x0163, 278},
{-1, 0x00AC, 564},
{-1, 0x00F6, 500},
{-1, 0x00FC, 500},
{-1, 0x2260, 549},
{-1, 0x0123, 500},
{-1, 0x00F0, 500},
{-1, 0x017E, 444},
{-1, 0x0146, 500},
{-1, 0x00B9, 300},
{-1, 0x012B, 278},
{-1, 0x20AC, 500},
{-1, 0xFFFF, 0}
};
static const HPDF_CharData <API key>[316] = {
{32, 0x0020, 250},
{33, 0x0021, 333},
{34, 0x0022, 555},
{35, 0x0023, 500},
{36, 0x0024, 500},
{37, 0x0025, 1000},
{38, 0x0026, 833},
{39, 0x2019, 333},
{40, 0x0028, 333},
{41, 0x0029, 333},
{42, 0x002A, 500},
{43, 0x002B, 570},
{44, 0x002C, 250},
{45, 0x002D, 333},
{46, 0x002E, 250},
{47, 0x002F, 278},
{48, 0x0030, 500},
{49, 0x0031, 500},
{50, 0x0032, 500},
{51, 0x0033, 500},
{52, 0x0034, 500},
{53, 0x0035, 500},
{54, 0x0036, 500},
{55, 0x0037, 500},
{56, 0x0038, 500},
{57, 0x0039, 500},
{58, 0x003A, 333},
{59, 0x003B, 333},
{60, 0x003C, 570},
{61, 0x003D, 570},
{62, 0x003E, 570},
{63, 0x003F, 500},
{64, 0x0040, 930},
{65, 0x0041, 722},
{66, 0x0042, 667},
{67, 0x0043, 722},
{68, 0x0044, 722},
{69, 0x0045, 667},
{70, 0x0046, 611},
{71, 0x0047, 778},
{72, 0x0048, 778},
{73, 0x0049, 389},
{74, 0x004A, 500},
{75, 0x004B, 778},
{76, 0x004C, 667},
{77, 0x004D, 944},
{78, 0x004E, 722},
{79, 0x004F, 778},
{80, 0x0050, 611},
{81, 0x0051, 778},
{82, 0x0052, 722},
{83, 0x0053, 556},
{84, 0x0054, 667},
{85, 0x0055, 722},
{86, 0x0056, 722},
{87, 0x0057, 1000},
{88, 0x0058, 722},
{89, 0x0059, 722},
{90, 0x005A, 667},
{91, 0x005B, 333},
{92, 0x005C, 278},
{93, 0x005D, 333},
{94, 0x005E, 581},
{95, 0x005F, 500},
{96, 0x2018, 333},
{97, 0x0061, 500},
{98, 0x0062, 556},
{99, 0x0063, 444},
{100, 0x0064, 556},
{101, 0x0065, 444},
{102, 0x0066, 333},
{103, 0x0067, 500},
{104, 0x0068, 556},
{105, 0x0069, 278},
{106, 0x006A, 333},
{107, 0x006B, 556},
{108, 0x006C, 278},
{109, 0x006D, 833},
{110, 0x006E, 556},
{111, 0x006F, 500},
{112, 0x0070, 556},
{113, 0x0071, 556},
{114, 0x0072, 444},
{115, 0x0073, 389},
{116, 0x0074, 333},
{117, 0x0075, 556},
{118, 0x0076, 500},
{119, 0x0077, 722},
{120, 0x0078, 500},
{121, 0x0079, 500},
{122, 0x007A, 444},
{123, 0x007B, 394},
{124, 0x007C, 220},
{125, 0x007D, 394},
{126, 0x007E, 520},
{161, 0x00A1, 333},
{162, 0x00A2, 500},
{163, 0x00A3, 500},
{164, 0x2044, 167},
{165, 0x00A5, 500},
{166, 0x0192, 500},
{167, 0x00A7, 500},
{168, 0x00A4, 500},
{169, 0x0027, 278},
{170, 0x201C, 500},
{171, 0x00AB, 500},
{172, 0x2039, 333},
{173, 0x203A, 333},
{174, 0xFB01, 556},
{175, 0xFB02, 556},
{177, 0x2013, 500},
{178, 0x2020, 500},
{179, 0x2021, 500},
{180, 0x00B7, 250},
{182, 0x00B6, 540},
{183, 0x2022, 350},
{184, 0x201A, 333},
{185, 0x201E, 500},
{186, 0x201D, 500},
{187, 0x00BB, 500},
{188, 0x2026, 1000},
{189, 0x2030, 1000},
{191, 0x00BF, 500},
{193, 0x0060, 333},
{194, 0x00B4, 333},
{195, 0x02C6, 333},
{196, 0x02DC, 333},
{197, 0x00AF, 333},
{198, 0x02D8, 333},
{199, 0x02D9, 333},
{200, 0x00A8, 333},
{202, 0x02DA, 333},
{203, 0x00B8, 333},
{205, 0x02DD, 333},
{206, 0x02DB, 333},
{207, 0x02C7, 333},
{208, 0x2014, 1000},
{225, 0x00C6, 1000},
{227, 0x00AA, 300},
{232, 0x0141, 667},
{233, 0x00D8, 778},
{234, 0x0152, 1000},
{235, 0x00BA, 330},
{241, 0x00E6, 722},
{245, 0x0131, 278},
{248, 0x0142, 278},
{249, 0x00F8, 500},
{250, 0x0153, 722},
{251, 0x00DF, 556},
{-1, 0x00CF, 389},
{-1, 0x00E9, 444},
{-1, 0x0103, 500},
{-1, 0x0171, 556},
{-1, 0x011B, 444},
{-1, 0x0178, 722},
{-1, 0x00F7, 570},
{-1, 0x00DD, 722},
{-1, 0x00C2, 722},
{-1, 0x00E1, 500},
{-1, 0x00DB, 722},
{-1, 0x00FD, 500},
{-1, 0x0219, 389},
{-1, 0x00EA, 444},
{-1, 0x016E, 722},
{-1, 0x00DC, 722},
{-1, 0x0105, 500},
{-1, 0x00DA, 722},
{-1, 0x0173, 556},
{-1, 0x00CB, 667},
{-1, 0x0110, 722},
{-1, 0xF6C3, 250},
{-1, 0x00A9, 747},
{-1, 0x0112, 667},
{-1, 0x010D, 444},
{-1, 0x00E5, 500},
{-1, 0x0145, 722},
{-1, 0x013A, 278},
{-1, 0x00E0, 500},
{-1, 0x0162, 667},
{-1, 0x0106, 722},
{-1, 0x00E3, 500},
{-1, 0x0116, 667},
{-1, 0x0161, 389},
{-1, 0x015F, 389},
{-1, 0x00ED, 278},
{-1, 0x25CA, 494},
{-1, 0x0158, 722},
{-1, 0x0122, 778},
{-1, 0x00FB, 556},
{-1, 0x00E2, 500},
{-1, 0x0100, 722},
{-1, 0x0159, 444},
{-1, 0x00E7, 444},
{-1, 0x017B, 667},
{-1, 0x00DE, 611},
{-1, 0x014C, 778},
{-1, 0x0154, 722},
{-1, 0x015A, 556},
{-1, 0x010F, 672},
{-1, 0x016A, 722},
{-1, 0x016F, 556},
{-1, 0x00B3, 300},
{-1, 0x00D2, 778},
{-1, 0x00C0, 722},
{-1, 0x0102, 722},
{-1, 0x00D7, 570},
{-1, 0x00FA, 556},
{-1, 0x0164, 667},
{-1, 0x2202, 494},
{-1, 0x00FF, 500},
{-1, 0x0143, 722},
{-1, 0x00EE, 278},
{-1, 0x00CA, 667},
{-1, 0x00E4, 500},
{-1, 0x00EB, 444},
{-1, 0x0107, 444},
{-1, 0x0144, 556},
{-1, 0x016B, 556},
{-1, 0x0147, 722},
{-1, 0x00CD, 389},
{-1, 0x00B1, 570},
{-1, 0x00A6, 220},
{-1, 0x00AE, 747},
{-1, 0x011E, 778},
{-1, 0x0130, 389},
{-1, 0x2211, 600},
{-1, 0x00C8, 667},
{-1, 0x0155, 444},
{-1, 0x014D, 500},
{-1, 0x0179, 667},
{-1, 0x017D, 667},
{-1, 0x2265, 549},
{-1, 0x00D0, 722},
{-1, 0x00C7, 722},
{-1, 0x013C, 278},
{-1, 0x0165, 416},
{-1, 0x0119, 444},
{-1, 0x0172, 722},
{-1, 0x00C1, 722},
{-1, 0x00C4, 722},
{-1, 0x00E8, 444},
{-1, 0x017A, 444},
{-1, 0x012F, 278},
{-1, 0x00D3, 778},
{-1, 0x00F3, 500},
{-1, 0x0101, 500},
{-1, 0x015B, 389},
{-1, 0x00EF, 278},
{-1, 0x00D4, 778},
{-1, 0x00D9, 722},
{-1, 0x0394, 612},
{-1, 0x00FE, 556},
{-1, 0x00B2, 300},
{-1, 0x00D6, 778},
{-1, 0x00B5, 556},
{-1, 0x00EC, 278},
{-1, 0x0151, 500},
{-1, 0x0118, 667},
{-1, 0x0111, 556},
{-1, 0x00BE, 750},
{-1, 0x015E, 556},
{-1, 0x013E, 394},
{-1, 0x0136, 778},
{-1, 0x0139, 667},
{-1, 0x2122, 1000},
{-1, 0x0117, 444},
{-1, 0x00CC, 389},
{-1, 0x012A, 389},
{-1, 0x013D, 667},
{-1, 0x00BD, 750},
{-1, 0x2264, 549},
{-1, 0x00F4, 500},
{-1, 0x00F1, 556},
{-1, 0x0170, 722},
{-1, 0x00C9, 667},
{-1, 0x0113, 444},
{-1, 0x011F, 500},
{-1, 0x00BC, 750},
{-1, 0x0160, 556},
{-1, 0x0218, 556},
{-1, 0x0150, 778},
{-1, 0x00B0, 400},
{-1, 0x00F2, 500},
{-1, 0x010C, 722},
{-1, 0x00F9, 556},
{-1, 0x221A, 549},
{-1, 0x010E, 722},
{-1, 0x0157, 444},
{-1, 0x00D1, 722},
{-1, 0x00F5, 500},
{-1, 0x0156, 722},
{-1, 0x013B, 667},
{-1, 0x00C3, 722},
{-1, 0x0104, 722},
{-1, 0x00C5, 722},
{-1, 0x00D5, 778},
{-1, 0x017C, 444},
{-1, 0x011A, 667},
{-1, 0x012E, 389},
{-1, 0x0137, 556},
{-1, 0x2212, 570},
{-1, 0x00CE, 389},
{-1, 0x0148, 556},
{-1, 0x0163, 333},
{-1, 0x00AC, 570},
{-1, 0x00F6, 500},
{-1, 0x00FC, 556},
{-1, 0x2260, 549},
{-1, 0x0123, 500},
{-1, 0x00F0, 500},
{-1, 0x017E, 444},
{-1, 0x0146, 556},
{-1, 0x00B9, 300},
{-1, 0x012B, 278},
{-1, 0x20AC, 500},
{-1, 0xFFFF, 0}
};
static const HPDF_CharData <API key>[316] = {
{32, 0x0020, 250},
{33, 0x0021, 389},
{34, 0x0022, 555},
{35, 0x0023, 500},
{36, 0x0024, 500},
{37, 0x0025, 833},
{38, 0x0026, 778},
{39, 0x2019, 333},
{40, 0x0028, 333},
{41, 0x0029, 333},
{42, 0x002A, 500},
{43, 0x002B, 570},
{44, 0x002C, 250},
{45, 0x002D, 333},
{46, 0x002E, 250},
{47, 0x002F, 278},
{48, 0x0030, 500},
{49, 0x0031, 500},
{50, 0x0032, 500},
{51, 0x0033, 500},
{52, 0x0034, 500},
{53, 0x0035, 500},
{54, 0x0036, 500},
{55, 0x0037, 500},
{56, 0x0038, 500},
{57, 0x0039, 500},
{58, 0x003A, 333},
{59, 0x003B, 333},
{60, 0x003C, 570},
{61, 0x003D, 570},
{62, 0x003E, 570},
{63, 0x003F, 500},
{64, 0x0040, 832},
{65, 0x0041, 667},
{66, 0x0042, 667},
{67, 0x0043, 667},
{68, 0x0044, 722},
{69, 0x0045, 667},
{70, 0x0046, 667},
{71, 0x0047, 722},
{72, 0x0048, 778},
{73, 0x0049, 389},
{74, 0x004A, 500},
{75, 0x004B, 667},
{76, 0x004C, 611},
{77, 0x004D, 889},
{78, 0x004E, 722},
{79, 0x004F, 722},
{80, 0x0050, 611},
{81, 0x0051, 722},
{82, 0x0052, 667},
{83, 0x0053, 556},
{84, 0x0054, 611},
{85, 0x0055, 722},
{86, 0x0056, 667},
{87, 0x0057, 889},
{88, 0x0058, 667},
{89, 0x0059, 611},
{90, 0x005A, 611},
{91, 0x005B, 333},
{92, 0x005C, 278},
{93, 0x005D, 333},
{94, 0x005E, 570},
{95, 0x005F, 500},
{96, 0x2018, 333},
{97, 0x0061, 500},
{98, 0x0062, 500},
{99, 0x0063, 444},
{100, 0x0064, 500},
{101, 0x0065, 444},
{102, 0x0066, 333},
{103, 0x0067, 500},
{104, 0x0068, 556},
{105, 0x0069, 278},
{106, 0x006A, 278},
{107, 0x006B, 500},
{108, 0x006C, 278},
{109, 0x006D, 778},
{110, 0x006E, 556},
{111, 0x006F, 500},
{112, 0x0070, 500},
{113, 0x0071, 500},
{114, 0x0072, 389},
{115, 0x0073, 389},
{116, 0x0074, 278},
{117, 0x0075, 556},
{118, 0x0076, 444},
{119, 0x0077, 667},
{120, 0x0078, 500},
{121, 0x0079, 444},
{122, 0x007A, 389},
{123, 0x007B, 348},
{124, 0x007C, 220},
{125, 0x007D, 348},
{126, 0x007E, 570},
{161, 0x00A1, 389},
{162, 0x00A2, 500},
{163, 0x00A3, 500},
{164, 0x2044, 167},
{165, 0x00A5, 500},
{166, 0x0192, 500},
{167, 0x00A7, 500},
{168, 0x00A4, 500},
{169, 0x0027, 278},
{170, 0x201C, 500},
{171, 0x00AB, 500},
{172, 0x2039, 333},
{173, 0x203A, 333},
{174, 0xFB01, 556},
{175, 0xFB02, 556},
{177, 0x2013, 500},
{178, 0x2020, 500},
{179, 0x2021, 500},
{180, 0x00B7, 250},
{182, 0x00B6, 500},
{183, 0x2022, 350},
{184, 0x201A, 333},
{185, 0x201E, 500},
{186, 0x201D, 500},
{187, 0x00BB, 500},
{188, 0x2026, 1000},
{189, 0x2030, 1000},
{191, 0x00BF, 500},
{193, 0x0060, 333},
{194, 0x00B4, 333},
{195, 0x02C6, 333},
{196, 0x02DC, 333},
{197, 0x00AF, 333},
{198, 0x02D8, 333},
{199, 0x02D9, 333},
{200, 0x00A8, 333},
{202, 0x02DA, 333},
{203, 0x00B8, 333},
{205, 0x02DD, 333},
{206, 0x02DB, 333},
{207, 0x02C7, 333},
{208, 0x2014, 1000},
{225, 0x00C6, 944},
{227, 0x00AA, 266},
{232, 0x0141, 611},
{233, 0x00D8, 722},
{234, 0x0152, 944},
{235, 0x00BA, 300},
{241, 0x00E6, 722},
{245, 0x0131, 278},
{248, 0x0142, 278},
{249, 0x00F8, 500},
{250, 0x0153, 722},
{251, 0x00DF, 500},
{-1, 0x00CF, 389},
{-1, 0x00E9, 444},
{-1, 0x0103, 500},
{-1, 0x0171, 556},
{-1, 0x011B, 444},
{-1, 0x0178, 611},
{-1, 0x00F7, 570},
{-1, 0x00DD, 611},
{-1, 0x00C2, 667},
{-1, 0x00E1, 500},
{-1, 0x00DB, 722},
{-1, 0x00FD, 444},
{-1, 0x0219, 389},
{-1, 0x00EA, 444},
{-1, 0x016E, 722},
{-1, 0x00DC, 722},
{-1, 0x0105, 500},
{-1, 0x00DA, 722},
{-1, 0x0173, 556},
{-1, 0x00CB, 667},
{-1, 0x0110, 722},
{-1, 0xF6C3, 250},
{-1, 0x00A9, 747},
{-1, 0x0112, 667},
{-1, 0x010D, 444},
{-1, 0x00E5, 500},
{-1, 0x0145, 722},
{-1, 0x013A, 278},
{-1, 0x00E0, 500},
{-1, 0x0162, 611},
{-1, 0x0106, 667},
{-1, 0x00E3, 500},
{-1, 0x0116, 667},
{-1, 0x0161, 389},
{-1, 0x015F, 389},
{-1, 0x00ED, 278},
{-1, 0x25CA, 494},
{-1, 0x0158, 667},
{-1, 0x0122, 722},
{-1, 0x00FB, 556},
{-1, 0x00E2, 500},
{-1, 0x0100, 667},
{-1, 0x0159, 389},
{-1, 0x00E7, 444},
{-1, 0x017B, 611},
{-1, 0x00DE, 611},
{-1, 0x014C, 722},
{-1, 0x0154, 667},
{-1, 0x015A, 556},
{-1, 0x010F, 608},
{-1, 0x016A, 722},
{-1, 0x016F, 556},
{-1, 0x00B3, 300},
{-1, 0x00D2, 722},
{-1, 0x00C0, 667},
{-1, 0x0102, 667},
{-1, 0x00D7, 570},
{-1, 0x00FA, 556},
{-1, 0x0164, 611},
{-1, 0x2202, 494},
{-1, 0x00FF, 444},
{-1, 0x0143, 722},
{-1, 0x00EE, 278},
{-1, 0x00CA, 667},
{-1, 0x00E4, 500},
{-1, 0x00EB, 444},
{-1, 0x0107, 444},
{-1, 0x0144, 556},
{-1, 0x016B, 556},
{-1, 0x0147, 722},
{-1, 0x00CD, 389},
{-1, 0x00B1, 570},
{-1, 0x00A6, 220},
{-1, 0x00AE, 747},
{-1, 0x011E, 722},
{-1, 0x0130, 389},
{-1, 0x2211, 600},
{-1, 0x00C8, 667},
{-1, 0x0155, 389},
{-1, 0x014D, 500},
{-1, 0x0179, 611},
{-1, 0x017D, 611},
{-1, 0x2265, 549},
{-1, 0x00D0, 722},
{-1, 0x00C7, 667},
{-1, 0x013C, 278},
{-1, 0x0165, 366},
{-1, 0x0119, 444},
{-1, 0x0172, 722},
{-1, 0x00C1, 667},
{-1, 0x00C4, 667},
{-1, 0x00E8, 444},
{-1, 0x017A, 389},
{-1, 0x012F, 278},
{-1, 0x00D3, 722},
{-1, 0x00F3, 500},
{-1, 0x0101, 500},
{-1, 0x015B, 389},
{-1, 0x00EF, 278},
{-1, 0x00D4, 722},
{-1, 0x00D9, 722},
{-1, 0x0394, 612},
{-1, 0x00FE, 500},
{-1, 0x00B2, 300},
{-1, 0x00D6, 722},
{-1, 0x00B5, 576},
{-1, 0x00EC, 278},
{-1, 0x0151, 500},
{-1, 0x0118, 667},
{-1, 0x0111, 500},
{-1, 0x00BE, 750},
{-1, 0x015E, 556},
{-1, 0x013E, 382},
{-1, 0x0136, 667},
{-1, 0x0139, 611},
{-1, 0x2122, 1000},
{-1, 0x0117, 444},
{-1, 0x00CC, 389},
{-1, 0x012A, 389},
{-1, 0x013D, 611},
{-1, 0x00BD, 750},
{-1, 0x2264, 549},
{-1, 0x00F4, 500},
{-1, 0x00F1, 556},
{-1, 0x0170, 722},
{-1, 0x00C9, 667},
{-1, 0x0113, 444},
{-1, 0x011F, 500},
{-1, 0x00BC, 750},
{-1, 0x0160, 556},
{-1, 0x0218, 556},
{-1, 0x0150, 722},
{-1, 0x00B0, 400},
{-1, 0x00F2, 500},
{-1, 0x010C, 667},
{-1, 0x00F9, 556},
{-1, 0x221A, 549},
{-1, 0x010E, 722},
{-1, 0x0157, 389},
{-1, 0x00D1, 722},
{-1, 0x00F5, 500},
{-1, 0x0156, 667},
{-1, 0x013B, 611},
{-1, 0x00C3, 667},
{-1, 0x0104, 667},
{-1, 0x00C5, 667},
{-1, 0x00D5, 722},
{-1, 0x017C, 389},
{-1, 0x011A, 667},
{-1, 0x012E, 389},
{-1, 0x0137, 500},
{-1, 0x2212, 606},
{-1, 0x00CE, 389},
{-1, 0x0148, 556},
{-1, 0x0163, 278},
{-1, 0x00AC, 606},
{-1, 0x00F6, 500},
{-1, 0x00FC, 556},
{-1, 0x2260, 549},
{-1, 0x0123, 500},
{-1, 0x00F0, 500},
{-1, 0x017E, 389},
{-1, 0x0146, 556},
{-1, 0x00B9, 300},
{-1, 0x012B, 278},
{-1, 0x20AC, 500},
{-1, 0xFFFF, 0}
};
static const HPDF_CharData <API key>[316] = {
{32, 0x0020, 250},
{33, 0x0021, 333},
{34, 0x0022, 420},
{35, 0x0023, 500},
{36, 0x0024, 500},
{37, 0x0025, 833},
{38, 0x0026, 778},
{39, 0x2019, 333},
{40, 0x0028, 333},
{41, 0x0029, 333},
{42, 0x002A, 500},
{43, 0x002B, 675},
{44, 0x002C, 250},
{45, 0x002D, 333},
{46, 0x002E, 250},
{47, 0x002F, 278},
{48, 0x0030, 500},
{49, 0x0031, 500},
{50, 0x0032, 500},
{51, 0x0033, 500},
{52, 0x0034, 500},
{53, 0x0035, 500},
{54, 0x0036, 500},
{55, 0x0037, 500},
{56, 0x0038, 500},
{57, 0x0039, 500},
{58, 0x003A, 333},
{59, 0x003B, 333},
{60, 0x003C, 675},
{61, 0x003D, 675},
{62, 0x003E, 675},
{63, 0x003F, 500},
{64, 0x0040, 920},
{65, 0x0041, 611},
{66, 0x0042, 611},
{67, 0x0043, 667},
{68, 0x0044, 722},
{69, 0x0045, 611},
{70, 0x0046, 611},
{71, 0x0047, 722},
{72, 0x0048, 722},
{73, 0x0049, 333},
{74, 0x004A, 444},
{75, 0x004B, 667},
{76, 0x004C, 556},
{77, 0x004D, 833},
{78, 0x004E, 667},
{79, 0x004F, 722},
{80, 0x0050, 611},
{81, 0x0051, 722},
{82, 0x0052, 611},
{83, 0x0053, 500},
{84, 0x0054, 556},
{85, 0x0055, 722},
{86, 0x0056, 611},
{87, 0x0057, 833},
{88, 0x0058, 611},
{89, 0x0059, 556},
{90, 0x005A, 556},
{91, 0x005B, 389},
{92, 0x005C, 278},
{93, 0x005D, 389},
{94, 0x005E, 422},
{95, 0x005F, 500},
{96, 0x2018, 333},
{97, 0x0061, 500},
{98, 0x0062, 500},
{99, 0x0063, 444},
{100, 0x0064, 500},
{101, 0x0065, 444},
{102, 0x0066, 278},
{103, 0x0067, 500},
{104, 0x0068, 500},
{105, 0x0069, 278},
{106, 0x006A, 278},
{107, 0x006B, 444},
{108, 0x006C, 278},
{109, 0x006D, 722},
{110, 0x006E, 500},
{111, 0x006F, 500},
{112, 0x0070, 500},
{113, 0x0071, 500},
{114, 0x0072, 389},
{115, 0x0073, 389},
{116, 0x0074, 278},
{117, 0x0075, 500},
{118, 0x0076, 444},
{119, 0x0077, 667},
{120, 0x0078, 444},
{121, 0x0079, 444},
{122, 0x007A, 389},
{123, 0x007B, 400},
{124, 0x007C, 275},
{125, 0x007D, 400},
{126, 0x007E, 541},
{161, 0x00A1, 389},
{162, 0x00A2, 500},
{163, 0x00A3, 500},
{164, 0x2044, 167},
{165, 0x00A5, 500},
{166, 0x0192, 500},
{167, 0x00A7, 500},
{168, 0x00A4, 500},
{169, 0x0027, 214},
{170, 0x201C, 556},
{171, 0x00AB, 500},
{172, 0x2039, 333},
{173, 0x203A, 333},
{174, 0xFB01, 500},
{175, 0xFB02, 500},
{177, 0x2013, 500},
{178, 0x2020, 500},
{179, 0x2021, 500},
{180, 0x00B7, 250},
{182, 0x00B6, 523},
{183, 0x2022, 350},
{184, 0x201A, 333},
{185, 0x201E, 556},
{186, 0x201D, 556},
{187, 0x00BB, 500},
{188, 0x2026, 889},
{189, 0x2030, 1000},
{191, 0x00BF, 500},
{193, 0x0060, 333},
{194, 0x00B4, 333},
{195, 0x02C6, 333},
{196, 0x02DC, 333},
{197, 0x00AF, 333},
{198, 0x02D8, 333},
{199, 0x02D9, 333},
{200, 0x00A8, 333},
{202, 0x02DA, 333},
{203, 0x00B8, 333},
{205, 0x02DD, 333},
{206, 0x02DB, 333},
{207, 0x02C7, 333},
{208, 0x2014, 889},
{225, 0x00C6, 889},
{227, 0x00AA, 276},
{232, 0x0141, 556},
{233, 0x00D8, 722},
{234, 0x0152, 944},
{235, 0x00BA, 310},
{241, 0x00E6, 667},
{245, 0x0131, 278},
{248, 0x0142, 278},
{249, 0x00F8, 500},
{250, 0x0153, 667},
{251, 0x00DF, 500},
{-1, 0x00CF, 333},
{-1, 0x00E9, 444},
{-1, 0x0103, 500},
{-1, 0x0171, 500},
{-1, 0x011B, 444},
{-1, 0x0178, 556},
{-1, 0x00F7, 675},
{-1, 0x00DD, 556},
{-1, 0x00C2, 611},
{-1, 0x00E1, 500},
{-1, 0x00DB, 722},
{-1, 0x00FD, 444},
{-1, 0x0219, 389},
{-1, 0x00EA, 444},
{-1, 0x016E, 722},
{-1, 0x00DC, 722},
{-1, 0x0105, 500},
{-1, 0x00DA, 722},
{-1, 0x0173, 500},
{-1, 0x00CB, 611},
{-1, 0x0110, 722},
{-1, 0xF6C3, 250},
{-1, 0x00A9, 760},
{-1, 0x0112, 611},
{-1, 0x010D, 444},
{-1, 0x00E5, 500},
{-1, 0x0145, 667},
{-1, 0x013A, 278},
{-1, 0x00E0, 500},
{-1, 0x0162, 556},
{-1, 0x0106, 667},
{-1, 0x00E3, 500},
{-1, 0x0116, 611},
{-1, 0x0161, 389},
{-1, 0x015F, 389},
{-1, 0x00ED, 278},
{-1, 0x25CA, 471},
{-1, 0x0158, 611},
{-1, 0x0122, 722},
{-1, 0x00FB, 500},
{-1, 0x00E2, 500},
{-1, 0x0100, 611},
{-1, 0x0159, 389},
{-1, 0x00E7, 444},
{-1, 0x017B, 556},
{-1, 0x00DE, 611},
{-1, 0x014C, 722},
{-1, 0x0154, 611},
{-1, 0x015A, 500},
{-1, 0x010F, 544},
{-1, 0x016A, 722},
{-1, 0x016F, 500},
{-1, 0x00B3, 300},
{-1, 0x00D2, 722},
{-1, 0x00C0, 611},
{-1, 0x0102, 611},
{-1, 0x00D7, 675},
{-1, 0x00FA, 500},
{-1, 0x0164, 556},
{-1, 0x2202, 476},
{-1, 0x00FF, 444},
{-1, 0x0143, 667},
{-1, 0x00EE, 278},
{-1, 0x00CA, 611},
{-1, 0x00E4, 500},
{-1, 0x00EB, 444},
{-1, 0x0107, 444},
{-1, 0x0144, 500},
{-1, 0x016B, 500},
{-1, 0x0147, 667},
{-1, 0x00CD, 333},
{-1, 0x00B1, 675},
{-1, 0x00A6, 275},
{-1, 0x00AE, 760},
{-1, 0x011E, 722},
{-1, 0x0130, 333},
{-1, 0x2211, 600},
{-1, 0x00C8, 611},
{-1, 0x0155, 389},
{-1, 0x014D, 500},
{-1, 0x0179, 556},
{-1, 0x017D, 556},
{-1, 0x2265, 549},
{-1, 0x00D0, 722},
{-1, 0x00C7, 667},
{-1, 0x013C, 278},
{-1, 0x0165, 300},
{-1, 0x0119, 444},
{-1, 0x0172, 722},
{-1, 0x00C1, 611},
{-1, 0x00C4, 611},
{-1, 0x00E8, 444},
{-1, 0x017A, 389},
{-1, 0x012F, 278},
{-1, 0x00D3, 722},
{-1, 0x00F3, 500},
{-1, 0x0101, 500},
{-1, 0x015B, 389},
{-1, 0x00EF, 278},
{-1, 0x00D4, 722},
{-1, 0x00D9, 722},
{-1, 0x0394, 612},
{-1, 0x00FE, 500},
{-1, 0x00B2, 300},
{-1, 0x00D6, 722},
{-1, 0x00B5, 500},
{-1, 0x00EC, 278},
{-1, 0x0151, 500},
{-1, 0x0118, 611},
{-1, 0x0111, 500},
{-1, 0x00BE, 750},
{-1, 0x015E, 500},
{-1, 0x013E, 300},
{-1, 0x0136, 667},
{-1, 0x0139, 556},
{-1, 0x2122, 980},
{-1, 0x0117, 444},
{-1, 0x00CC, 333},
{-1, 0x012A, 333},
{-1, 0x013D, 611},
{-1, 0x00BD, 750},
{-1, 0x2264, 549},
{-1, 0x00F4, 500},
{-1, 0x00F1, 500},
{-1, 0x0170, 722},
{-1, 0x00C9, 611},
{-1, 0x0113, 444},
{-1, 0x011F, 500},
{-1, 0x00BC, 750},
{-1, 0x0160, 500},
{-1, 0x0218, 500},
{-1, 0x0150, 722},
{-1, 0x00B0, 400},
{-1, 0x00F2, 500},
{-1, 0x010C, 667},
{-1, 0x00F9, 500},
{-1, 0x221A, 453},
{-1, 0x010E, 722},
{-1, 0x0157, 389},
{-1, 0x00D1, 667},
{-1, 0x00F5, 500},
{-1, 0x0156, 611},
{-1, 0x013B, 556},
{-1, 0x00C3, 611},
{-1, 0x0104, 611},
{-1, 0x00C5, 611},
{-1, 0x00D5, 722},
{-1, 0x017C, 389},
{-1, 0x011A, 611},
{-1, 0x012E, 333},
{-1, 0x0137, 444},
{-1, 0x2212, 675},
{-1, 0x00CE, 333},
{-1, 0x0148, 500},
{-1, 0x0163, 278},
{-1, 0x00AC, 675},
{-1, 0x00F6, 500},
{-1, 0x00FC, 500},
{-1, 0x2260, 549},
{-1, 0x0123, 500},
{-1, 0x00F0, 500},
{-1, 0x017E, 389},
{-1, 0x0146, 500},
{-1, 0x00B9, 300},
{-1, 0x012B, 278},
{-1, 0x20AC, 500},
{-1, 0xFFFF, 0}
};
static const HPDF_CharData <API key>[203] = {
{32, 0x0020, 278},
{33, 0x0021, 974},
{34, 0x0022, 961},
{35, 0x0023, 974},
{36, 0x0024, 980},
{37, 0x0025, 719},
{38, 0x0026, 789},
{39, 0x0027, 790},
{40, 0x0028, 791},
{41, 0x0029, 690},
{42, 0x002A, 960},
{43, 0x002B, 939},
{44, 0x002C, 549},
{45, 0x002D, 855},
{46, 0x002E, 911},
{47, 0x002F, 933},
{48, 0x0030, 911},
{49, 0x0031, 945},
{50, 0x0032, 974},
{51, 0x0033, 755},
{52, 0x0034, 846},
{53, 0x0035, 762},
{54, 0x0036, 761},
{55, 0x0037, 571},
{56, 0x0038, 677},
{57, 0x0039, 763},
{58, 0x003A, 760},
{59, 0x003B, 759},
{60, 0x003C, 754},
{61, 0x003D, 494},
{62, 0x003E, 552},
{63, 0x003F, 537},
{64, 0x0040, 577},
{65, 0x0041, 692},
{66, 0x0042, 786},
{67, 0x0043, 788},
{68, 0x0044, 788},
{69, 0x0045, 790},
{70, 0x0046, 793},
{71, 0x0047, 794},
{72, 0x0048, 816},
{73, 0x0049, 823},
{74, 0x004A, 789},
{75, 0x004B, 841},
{76, 0x004C, 823},
{77, 0x004D, 833},
{78, 0x004E, 816},
{79, 0x004F, 831},
{80, 0x0050, 923},
{81, 0x0051, 744},
{82, 0x0052, 723},
{83, 0x0053, 749},
{84, 0x0054, 790},
{85, 0x0055, 792},
{86, 0x0056, 695},
{87, 0x0057, 776},
{88, 0x0058, 768},
{89, 0x0059, 792},
{90, 0x005A, 759},
{91, 0x005B, 707},
{92, 0x005C, 708},
{93, 0x005D, 682},
{94, 0x005E, 701},
{95, 0x005F, 826},
{96, 0x0060, 815},
{97, 0x0061, 789},
{98, 0x0062, 789},
{99, 0x0063, 707},
{100, 0x0064, 687},
{101, 0x0065, 696},
{102, 0x0066, 689},
{103, 0x0067, 786},
{104, 0x0068, 787},
{105, 0x0069, 713},
{106, 0x006A, 791},
{107, 0x006B, 785},
{108, 0x006C, 791},
{109, 0x006D, 873},
{110, 0x006E, 761},
{111, 0x006F, 762},
{112, 0x0070, 762},
{113, 0x0071, 759},
{114, 0x0072, 759},
{115, 0x0073, 892},
{116, 0x0074, 892},
{117, 0x0075, 788},
{118, 0x0076, 784},
{119, 0x0077, 438},
{120, 0x0078, 138},
{121, 0x0079, 277},
{122, 0x007A, 415},
{123, 0x007B, 392},
{124, 0x007C, 392},
{125, 0x007D, 668},
{126, 0x007E, 668},
{128, 0x0080, 390},
{129, 0x0081, 390},
{130, 0x0082, 317},
{131, 0x0083, 317},
{132, 0x0084, 276},
{133, 0x0085, 276},
{134, 0x0086, 509},
{135, 0x0087, 509},
{136, 0x0088, 410},
{137, 0x0089, 410},
{138, 0x008A, 234},
{139, 0x008B, 234},
{140, 0x008C, 334},
{141, 0x008D, 334},
{161, 0x00A1, 732},
{162, 0x00A2, 544},
{163, 0x00A3, 544},
{164, 0x00A4, 910},
{165, 0x00A5, 667},
{166, 0x00A6, 760},
{167, 0x00A7, 760},
{168, 0x00A8, 776},
{169, 0x00A9, 595},
{170, 0x00AA, 694},
{171, 0x00AB, 626},
{172, 0x00AC, 788},
{173, 0x00AD, 788},
{174, 0x00AE, 788},
{175, 0x00AF, 788},
{176, 0x00B0, 788},
{177, 0x00B1, 788},
{178, 0x00B2, 788},
{179, 0x00B3, 788},
{180, 0x00B4, 788},
{181, 0x00B5, 788},
{182, 0x00B6, 788},
{183, 0x00B7, 788},
{184, 0x00B8, 788},
{185, 0x00B9, 788},
{186, 0x00BA, 788},
{187, 0x00BB, 788},
{188, 0x00BC, 788},
{189, 0x00BD, 788},
{190, 0x00BE, 788},
{191, 0x00BF, 788},
{192, 0x00C0, 788},
{193, 0x00C1, 788},
{194, 0x00C2, 788},
{195, 0x00C3, 788},
{196, 0x00C4, 788},
{197, 0x00C5, 788},
{198, 0x00C6, 788},
{199, 0x00C7, 788},
{200, 0x00C8, 788},
{201, 0x00C9, 788},
{202, 0x00CA, 788},
{203, 0x00CB, 788},
{204, 0x00CC, 788},
{205, 0x00CD, 788},
{206, 0x00CE, 788},
{207, 0x00CF, 788},
{208, 0x00D0, 788},
{209, 0x00D1, 788},
{210, 0x00D2, 788},
{211, 0x00D3, 788},
{212, 0x00D4, 894},
{213, 0x00D5, 838},
{214, 0x00D6, 1016},
{215, 0x00D7, 458},
{216, 0x00D8, 748},
{217, 0x00D9, 924},
{218, 0x00DA, 748},
{219, 0x00DB, 918},
{220, 0x00DC, 927},
{221, 0x00DD, 928},
{222, 0x00DE, 928},
{223, 0x00DF, 834},
{224, 0x00E0, 873},
{225, 0x00E1, 828},
{226, 0x00E2, 924},
{227, 0x00E3, 924},
{228, 0x00E4, 917},
{229, 0x00E5, 930},
{230, 0x00E6, 931},
{231, 0x00E7, 463},
{232, 0x00E8, 883},
{233, 0x00E9, 836},
{234, 0x00EA, 836},
{235, 0x00EB, 867},
{236, 0x00EC, 867},
{237, 0x00ED, 696},
{238, 0x00EE, 696},
{239, 0x00EF, 874},
{241, 0x00F1, 874},
{242, 0x00F2, 760},
{243, 0x00F3, 946},
{244, 0x00F4, 771},
{245, 0x00F5, 865},
{246, 0x00F6, 771},
{247, 0x00F7, 888},
{248, 0x00F8, 967},
{249, 0x00F9, 888},
{250, 0x00FA, 831},
{251, 0x00FB, 873},
{252, 0x00FC, 927},
{253, 0x00FD, 970},
{254, 0x00FE, 918},
{-1, 0xFFFF, 0}
};
static const HPDF_CharData CHAR_DATA_SYMBOL[190] = {
{32, 0x0020, 250},
{33, 0x0021, 333},
{34, 0x0022, 713},
{35, 0x0023, 500},
{36, 0x0024, 549},
{37, 0x0025, 833},
{38, 0x0026, 778},
{39, 0x0027, 439},
{40, 0x0028, 333},
{41, 0x0029, 333},
{42, 0x002A, 500},
{43, 0x002B, 549},
{44, 0x002C, 250},
{45, 0x002D, 549},
{46, 0x002E, 250},
{47, 0x002F, 278},
{48, 0x0030, 500},
{49, 0x0031, 500},
{50, 0x0032, 500},
{51, 0x0033, 500},
{52, 0x0034, 500},
{53, 0x0035, 500},
{54, 0x0036, 500},
{55, 0x0037, 500},
{56, 0x0038, 500},
{57, 0x0039, 500},
{58, 0x003A, 278},
{59, 0x003B, 278},
{60, 0x003C, 549},
{61, 0x003D, 549},
{62, 0x003E, 549},
{63, 0x003F, 444},
{64, 0x0040, 549},
{65, 0x0041, 722},
{66, 0x0042, 667},
{67, 0x0043, 722},
{68, 0x0044, 612},
{69, 0x0045, 611},
{70, 0x0046, 763},
{71, 0x0047, 603},
{72, 0x0048, 722},
{73, 0x0049, 333},
{74, 0x004A, 631},
{75, 0x004B, 722},
{76, 0x004C, 686},
{77, 0x004D, 889},
{78, 0x004E, 722},
{79, 0x004F, 722},
{80, 0x0050, 768},
{81, 0x0051, 741},
{82, 0x0052, 556},
{83, 0x0053, 592},
{84, 0x0054, 611},
{85, 0x0055, 690},
{86, 0x0056, 439},
{87, 0x0057, 768},
{88, 0x0058, 645},
{89, 0x0059, 795},
{90, 0x005A, 611},
{91, 0x005B, 333},
{92, 0x005C, 863},
{93, 0x005D, 333},
{94, 0x005E, 658},
{95, 0x005F, 500},
{96, 0x0060, 500},
{97, 0x0061, 631},
{98, 0x0062, 549},
{99, 0x0063, 549},
{100, 0x0064, 494},
{101, 0x0065, 439},
{102, 0x0066, 521},
{103, 0x0067, 411},
{104, 0x0068, 603},
{105, 0x0069, 329},
{106, 0x006A, 603},
{107, 0x006B, 549},
{108, 0x006C, 549},
{109, 0x006D, 576},
{110, 0x006E, 521},
{111, 0x006F, 549},
{112, 0x0070, 549},
{113, 0x0071, 521},
{114, 0x0072, 549},
{115, 0x0073, 603},
{116, 0x0074, 439},
{117, 0x0075, 576},
{118, 0x0076, 713},
{119, 0x0077, 686},
{120, 0x0078, 493},
{121, 0x0079, 686},
{122, 0x007A, 494},
{123, 0x007B, 480},
{124, 0x007C, 200},
{125, 0x007D, 480},
{126, 0x007E, 549},
{160, 0x00A0, 750},
{161, 0x00A1, 620},
{162, 0x00A2, 247},
{163, 0x00A3, 549},
{164, 0x00A4, 167},
{165, 0x00A5, 713},
{166, 0x00A6, 500},
{167, 0x00A7, 753},
{168, 0x00A8, 753},
{169, 0x00A9, 753},
{170, 0x00AA, 753},
{171, 0x00AB, 1042},
{172, 0x00AC, 987},
{173, 0x00AD, 603},
{174, 0x00AE, 987},
{175, 0x00AF, 603},
{176, 0x00B0, 400},
{177, 0x00B1, 549},
{178, 0x00B2, 411},
{179, 0x00B3, 549},
{180, 0x00B4, 549},
{181, 0x00B5, 713},
{182, 0x00B6, 494},
{183, 0x00B7, 460},
{184, 0x00B8, 549},
{185, 0x00B9, 549},
{186, 0x00BA, 549},
{187, 0x00BB, 549},
{188, 0x00BC, 1000},
{189, 0x00BD, 603},
{190, 0x00BE, 1000},
{191, 0x00BF, 658},
{192, 0x00C0, 823},
{193, 0x00C1, 686},
{194, 0x00C2, 795},
{195, 0x00C3, 987},
{196, 0x00C4, 768},
{197, 0x00C5, 768},
{198, 0x00C6, 823},
{199, 0x00C7, 768},
{200, 0x00C8, 768},
{201, 0x00C9, 713},
{202, 0x00CA, 713},
{203, 0x00CB, 713},
{204, 0x00CC, 713},
{205, 0x00CD, 713},
{206, 0x00CE, 713},
{207, 0x00CF, 713},
{208, 0x00D0, 768},
{209, 0x00D1, 713},
{210, 0x00D2, 790},
{211, 0x00D3, 790},
{212, 0x00D4, 890},
{213, 0x00D5, 823},
{214, 0x00D6, 549},
{215, 0x00D7, 250},
{216, 0x00D8, 713},
{217, 0x00D9, 603},
{218, 0x00DA, 603},
{219, 0x00DB, 1042},
{220, 0x00DC, 987},
{221, 0x00DD, 603},
{222, 0x00DE, 987},
{223, 0x00DF, 603},
{224, 0x00E0, 494},
{225, 0x00E1, 329},
{226, 0x00E2, 790},
{227, 0x00E3, 790},
{228, 0x00E4, 786},
{229, 0x00E5, 713},
{230, 0x00E6, 384},
{231, 0x00E7, 384},
{232, 0x00E8, 384},
{233, 0x00E9, 384},
{234, 0x00EA, 384},
{235, 0x00EB, 384},
{236, 0x00EC, 494},
{237, 0x00ED, 494},
{238, 0x00EE, 494},
{239, 0x00EF, 494},
{241, 0x00F1, 329},
{242, 0x00F2, 274},
{243, 0x00F3, 686},
{244, 0x00F4, 686},
{245, 0x00F5, 686},
{246, 0x00F6, 384},
{247, 0x00F7, 384},
{248, 0x00F8, 384},
{249, 0x00F9, 384},
{250, 0x00FA, 384},
{251, 0x00FB, 384},
{252, 0x00FC, 494},
{253, 0x00FD, 494},
{254, 0x00FE, 494},
{-1, 0xFFFF, 0}
};
#define HPDF_FONT_COURIER "Courier"
#define <API key> "Courier-Bold"
#define <API key> "Courier-Oblique"
#define <API key> "Courier-BoldOblique"
#define HPDF_FONT_HELVETICA "Helvetica"
#define <API key> "Helvetica-Bold"
#define <API key> "Helvetica-Oblique"
#define <API key> "<API key>"
#define <API key> "Times-Roman"
#define <API key> "Times-Bold"
#define <API key> "Times-Italic"
#define <API key> "Times-BoldItalic"
#define HPDF_FONT_SYMBOL "Symbol"
#define <API key> "ZapfDingbats"
typedef struct <API key> {
const char *font_name;
const HPDF_CharData *widths_table;
HPDF_BOOL is_font_specific;
HPDF_INT16 ascent;
HPDF_INT16 descent;
HPDF_UINT16 x_height;
HPDF_UINT16 cap_height;
HPDF_Box bbox;
} <API key>;
static const <API key> HPDF_BUILTIN_FONTS[] = {
{
HPDF_FONT_COURIER,
CHAR_DATA_COURIER,
HPDF_FALSE,
629,
-157,
426,
562,
{-23, -250, 715, 805}
},
{
<API key>,
<API key>,
HPDF_FALSE,
629,
-157,
439,
562,
{-113, -250, 749, 801}
},
{
<API key>,
<API key>,
HPDF_FALSE,
629,
-157,
426,
562,
{-27, -250, 849, 805}
},
{
<API key>,
<API key>,
HPDF_FALSE,
629,
-157,
439,
562,
{-57, -250, 869, 801}
},
{
HPDF_FONT_HELVETICA,
CHAR_DATA_HELVETICA,
HPDF_FALSE,
718,
-207,
523,
718,
{-166, -225, 1000, 931}
},
{
<API key>,
<API key>,
HPDF_FALSE,
718,
-207,
532,
718,
{-170, -228, 1003, 962}
},
{
<API key>,
<API key>,
HPDF_FALSE,
718,
-207,
532,
718,
{-170, -225, 1116, 931}
},
{
<API key>,
<API key>,
HPDF_FALSE,
718,
-207,
532,
718,
{-174, -228, 1114, 962}
},
{
<API key>,
<API key>,
HPDF_FALSE,
683,
-217,
450,
662,
{-168, -218, 1000, 898}
},
{
<API key>,
<API key>,
HPDF_FALSE,
683,
-217,
461,
676,
{-168, -218, 1000, 935}
},
{
<API key>,
<API key>,
HPDF_FALSE,
683,
-217,
441,
653,
{-169, -217, 1010, 883}
},
{
<API key>,
<API key>,
HPDF_FALSE,
683,
-217,
462,
669,
{-200, -218, 996, 921}
},
{
HPDF_FONT_SYMBOL,
CHAR_DATA_SYMBOL,
HPDF_TRUE,
0,
0,
0,
0,
{-180, -293, 1090, 1010}
},
{
<API key>,
<API key>,
HPDF_TRUE,
0,
0,
0,
0,
{-1, -143, 981, 820}
},
{
NULL,
NULL,
HPDF_FALSE,
0,
0,
0,
0,
{0, 0, 0, 0}
},
};
const <API key>*
<API key> (const char *font_name);
const <API key>*
<API key> (const char *font_name)
{
HPDF_UINT i = 0;
while (HPDF_BUILTIN_FONTS[i].font_name) {
if (HPDF_StrCmp (HPDF_BUILTIN_FONTS[i].font_name, font_name) == 0)
break;
i++;
}
return &HPDF_BUILTIN_FONTS[i];
}
HPDF_FontDef
<API key> (HPDF_MMgr mmgr,
const char *font_name)
{
HPDF_FontDef fontdef;
HPDF_STATUS ret;
const <API key> *data;
char *eptr;
<API key> attr;
fontdef = <API key> (mmgr);
if (!fontdef)
return NULL;
data = <API key> (font_name);
if (!data->font_name) {
HPDF_SetError (mmgr->error, <API key>, 0);
HPDF_FontDef_Free (fontdef);
return NULL;
}
eptr = fontdef->base_font + <API key>;
HPDF_StrCpy (fontdef->base_font, data->font_name, eptr);
attr = (<API key>)fontdef->attr;
attr->is_base14font = HPDF_TRUE;
if (data->is_font_specific)
HPDF_StrCpy (attr->encoding_scheme, <API key>,
attr->encoding_scheme + <API key>);
ret = <API key> (fontdef, data->widths_table);
if (ret != HPDF_OK) {
HPDF_FontDef_Free (fontdef);
return NULL;
}
fontdef->font_bbox = data->bbox;
fontdef->ascent = data->ascent;
fontdef->descent = data->descent;
fontdef->x_height = data->x_height;
fontdef->cap_height = data->cap_height;
fontdef->valid = HPDF_TRUE;
return fontdef;
} |
/* Most of this hacked by Steve Chamberlain <sac@cygnus.com>. */
/* These routines are used by coff-h8300 and coff-z8k to do
relocation.
FIXME: This code should be rewritten to support the new COFF
linker. Basically, they need to deal with COFF relocs rather than
BFD generic relocs. They should store the relocs in some location
where coff_link_input_bfd can find them (and coff_link_input_bfd
should be changed to use this location rather than rereading the
file) (unless info->keep_memory is FALSE, in which case they should
free up the relocs after dealing with them). */
#include "sysdep.h"
#include "bfd.h"
#include "libbfd.h"
#include "bfdlink.h"
#include "genlink.h"
#include "coff/internal.h"
#include "libcoff.h"
bfd_vma
<API key> (arelent *reloc,
struct bfd_link_info *link_info,
asection *input_section)
{
bfd_vma value;
asymbol *symbol = *(reloc->sym_ptr_ptr);
/* A symbol holds a pointer to a section, and an offset from the
base of the section. To relocate, we find where the section will
live in the output and add that in. */
if (bfd_is_und_section (symbol->section)
|| bfd_is_com_section (symbol->section))
{
struct bfd_link_hash_entry *h;
/* The symbol is undefined in this BFD. Look it up in the
global linker hash table. FIXME: This should be changed when
we convert this stuff to use a specific final_link function
and change the interface to bfd_relax_section to not require
the generic symbols. */
h = <API key> (input_section->owner, link_info,
bfd_asymbol_name (symbol),
FALSE, FALSE, TRUE);
if (h != (struct bfd_link_hash_entry *) NULL
&& (h->type == <API key>
|| h->type == <API key>))
value = (h->u.def.value
+ h->u.def.section->output_section->vma
+ h->u.def.section->output_offset);
else if (h != (struct bfd_link_hash_entry *) NULL
&& h->type == <API key>)
value = h->u.c.size;
else if (h != (struct bfd_link_hash_entry *) NULL
&& h->type == <API key>)
/* This is a GNU extension. */
value = 0;
else
{
if (!((*link_info->callbacks->undefined_symbol)
(link_info, bfd_asymbol_name (symbol),
input_section->owner, input_section, reloc->address,
TRUE)))
abort ();
value = 0;
}
}
else
{
value = symbol->value
+ symbol->section->output_offset
+ symbol->section->output_section->vma;
}
/* Add the value contained in the relocation. */
value += reloc->addend;
return value;
}
void
bfd_perform_slip (bfd *abfd,
unsigned int slip,
asection *input_section,
bfd_vma value)
{
asymbol **s;
s = <API key> (abfd);
BFD_ASSERT (s != (asymbol **) NULL);
/* Find all symbols past this point, and make them know
what's happened. */
while (*s)
{
asymbol *p = *s;
if (p->section == input_section)
{
/* This was pointing into this section, so mangle it. */
if (p->value > value)
{
p->value -= slip;
if (p->udata.p != NULL)
{
struct <API key> *h;
h = (struct <API key> *) p->udata.p;
BFD_ASSERT (h->root.type == <API key>
|| h->root.type == <API key>);
h->root.u.def.value -= slip;
BFD_ASSERT (h->root.u.def.value == p->value);
}
}
}
s++;
}
}
bfd_boolean
<API key> (bfd *abfd,
asection *input_section,
struct bfd_link_info *link_info,
bfd_boolean *again)
{
/* Get enough memory to hold the stuff. */
bfd *input_bfd = input_section->owner;
unsigned *shrinks;
unsigned shrink = 0;
long reloc_size = <API key> (input_bfd, input_section);
arelent **reloc_vector = NULL;
long reloc_count;
if (link_info->relocatable)
(*link_info->callbacks->einfo)
(_("%P%F: --relax and -r may not be used together\n"));
/* We only do global relaxation once. It is not safe to do it multiple
times (see discussion of the "shrinks" array below). */
*again = FALSE;
if (reloc_size < 0)
return FALSE;
reloc_vector = (arelent **) bfd_malloc ((bfd_size_type) reloc_size);
if (!reloc_vector && reloc_size > 0)
return FALSE;
/* Get the relocs and think about them. */
reloc_count =
<API key> (input_bfd, input_section, reloc_vector,
<API key> (input_bfd));
if (reloc_count < 0)
{
free (reloc_vector);
return FALSE;
}
/* The reloc16.c and related relaxing code is very simple, the price
for that simplicity is we can only call this function once for
each section.
So, to get the best results within that limitation, we do multiple
relaxing passes over each section here. That involves keeping track
of the "shrink" at each reloc in the section. This allows us to
accurately determine the relative location of two relocs within
this section.
In theory, if we kept the "shrinks" array for each section for the
entire link, we could use the generic relaxing code in the linker
and get better results, particularly for jsr->bsr and 24->16 bit
memory reference relaxations. */
if (reloc_count > 0)
{
int another_pass = 0;
bfd_size_type amt;
/* Allocate and initialize the shrinks array for this section.
The last element is used as an accumulator of shrinks. */
amt = reloc_count + 1;
amt *= sizeof (unsigned);
shrinks = (unsigned *) bfd_zmalloc (amt);
/* Loop until nothing changes in this section. */
do
{
arelent **parent;
unsigned int i;
long j;
another_pass = 0;
for (i = 0, parent = reloc_vector; *parent; parent++, i++)
{
/* Let the target/machine dependent code examine each reloc
in this section and attempt to shrink it. */
shrink = <API key> (abfd, input_section, *parent,
shrinks[i], link_info);
/* If it shrunk, note it in the shrinks array and set up for
another pass. */
if (shrink != shrinks[i])
{
another_pass = 1;
for (j = i + 1; j <= reloc_count; j++)
shrinks[j] += shrink - shrinks[i];
}
}
}
while (another_pass);
shrink = shrinks[reloc_count];
free ((char *) shrinks);
}
input_section->rawsize = input_section->size;
input_section->size -= shrink;
free ((char *) reloc_vector);
return TRUE;
}
bfd_byte *
<API key>
(bfd *in_abfd,
struct bfd_link_info *link_info,
struct bfd_link_order *link_order,
bfd_byte *data,
bfd_boolean relocatable,
asymbol **symbols)
{
/* Get enough memory to hold the stuff. */
bfd *input_bfd = link_order->u.indirect.section->owner;
asection *input_section = link_order->u.indirect.section;
long reloc_size = <API key> (input_bfd, input_section);
arelent **reloc_vector;
long reloc_count;
bfd_size_type sz;
if (reloc_size < 0)
return NULL;
/* If producing relocatable output, don't bother to relax. */
if (relocatable)
return <API key> (in_abfd, link_info,
link_order,
data, relocatable,
symbols);
/* Read in the section. */
sz = input_section->rawsize ? input_section->rawsize : input_section->size;
if (!<API key> (input_bfd, input_section, data, 0, sz))
return NULL;
reloc_vector = (arelent **) bfd_malloc ((bfd_size_type) reloc_size);
if (!reloc_vector && reloc_size != 0)
return NULL;
reloc_count = <API key> (input_bfd,
input_section,
reloc_vector,
symbols);
if (reloc_count < 0)
{
free (reloc_vector);
return NULL;
}
if (reloc_count > 0)
{
arelent **parent = reloc_vector;
arelent *reloc;
unsigned int dst_address = 0;
unsigned int src_address = 0;
unsigned int run;
unsigned int idx;
/* Find how long a run we can do. */
while (dst_address < link_order->size)
{
reloc = *parent;
if (reloc)
{
/* Note that the relaxing didn't tie up the addresses in the
relocation, so we use the original address to work out the
run of non-relocated data. */
run = reloc->address - src_address;
parent++;
}
else
{
run = link_order->size - dst_address;
}
/* Copy the bytes. */
for (idx = 0; idx < run; idx++)
data[dst_address++] = data[src_address++];
/* Now do the relocation. */
if (reloc)
{
<API key> (input_bfd, link_info, link_order,
reloc, data, &src_address,
&dst_address);
}
}
}
free ((char *) reloc_vector);
return data;
} |
Clazz.declarePackage ("JU");
Clazz.load (["JU.DataReader"], "JU.ArrayDataReader", null, function () {
c$ = Clazz.decorateAsClass (function () {
this.data = null;
this.pt = 0;
this.len = 0;
Clazz.instantialize (this, arguments);
}, JU, "ArrayDataReader", JU.DataReader);
Clazz.overrideMethod (c$, "setData",
function (data) {
this.data = data;
this.len = this.data.length;
return this;
}, "~O");
Clazz.overrideMethod (c$, "read",
function (buf, off, len) {
return this.readBuf (buf, off, len);
}, "~A,~N,~N");
Clazz.overrideMethod (c$, "readLine",
function () {
return (this.pt < this.len ? this.data[this.pt++] : null);
});
Clazz.defineMethod (c$, "mark",
function (ptr) {
this.ptMark = this.pt;
}, "~N");
Clazz.overrideMethod (c$, "reset",
function () {
this.pt = this.ptMark;
});
}); |
<!
Copyright (c) 2015 The Khronos Group Inc.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and/or associated documentation files (the
"Materials"), to deal in the Materials without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Materials, and to
permit persons to whom the Materials are 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 Materials.
THE MATERIALS ARE 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
MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
<!
This file is auto-generated from py/<API key>.py
DO NOT EDIT!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../../../resources/js-test-style.css"/>
<script src=/resources/testharness.js></script>
<script src=/resources/testharnessreport.js></script>
<script src="../../../js/js-test-pre.js"></script>
<script src="../../../js/webgl-test-utils.js"></script>
<script src="../../../js/tests/<API key>.js"></script>
<script src="../../../js/tests/<API key>.js"></script>
<script src="../../../js/tests/<API key>.js"></script>
</head>
<body>
<canvas id="example" width="32" height="32"></canvas>
<div id="description"></div>
<div id="console"></div>
<script>
"use strict";
function testPrologue(gl) {
return true;
}
generateTest("SRGB8", "RGB", "UNSIGNED_BYTE", testPrologue, "../../../resources/", 2)();
</script>
</body>
</html> |
using System;
using System.Threading;
using Roslyn.Collections.Immutable;
namespace Roslyn.Utilities
{
internal static class <API key>
{
<summary>
Obtains the value for the specified key from a dictionary, or adds a new value to the dictionary where the key did not previously exist.
</summary>
<typeparam name="TKey">The type of key stored by the dictionary.</typeparam>
<typeparam name="TValue">The type of value stored by the dictionary.</typeparam>
<typeparam name="TArg">The type of argument supplied to the value factory.</typeparam>
<param name="location">The variable or field to atomically update if the specified <paramref name="key" /> is not in the dictionary.</param>
<param name="key">The key for the value to retrieve or add.</param>
<param name="valueFactory">The function to execute to obtain the value to insert into the dictionary if the key is not found.</param>
<param name="factoryArgument">The argument to pass to the value factory.</param>
<returns>The value obtained from the dictionary or <paramref name="valueFactory" /> if it was not present.</returns>
public static TValue GetOrAdd<TKey, TValue, TArg>(ref ImmutableHashMap<TKey, TValue> location, TKey key, Func<TKey, TArg, TValue> valueFactory, TArg factoryArgument)
{
Contract.ThrowIfNull(valueFactory);
var map = Volatile.Read(ref location);
Contract.ThrowIfNull(map);
if (map.TryGetValue(key, out var existingValue))
{
return existingValue;
}
TValue newValue = valueFactory(key, factoryArgument);
do
{
var augmentedMap = map.Add(key, newValue);
var replacedMap = Interlocked.CompareExchange(ref location, augmentedMap, map);
if (replacedMap == map)
{
return newValue;
}
map = replacedMap;
}
while (!map.TryGetValue(key, out existingValue));
return existingValue;
}
}
} |
/**
* @author Dongsheng Cai <dongsheng@moodle.com>
*/
// No need to require lang packs in moodle plugins.
var ed, url;
if (url = tinyMCEPopup.getParam("<API key>")) {
document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>');
}
function init() {
ed = tinyMCEPopup.editor;
document.getElementById('<API key>').innerHTML = getFileBrowserHTML('filebrowser','src','media','media');
}
function insertMedia() {
var f = document.forms[0];
var url = f.filename.value;
var linkname = url.substring(url.lastIndexOf('/')+1);
var h = '<a href="'+f.src.value+'">'+linkname+'</a>';
ed.execCommand('mceInsertContent', false, h);
tinyMCEPopup.close();
}
function serializeParameters() {
var d = document, s = '';
s += getStr(null, 'src');
// delete the tail comma
s = s.length > 0 ? s.substring(0, s.length - 1) : s;
return s;
}
function getStr(p, n, d) {
var e = document.forms[0].elements[(p != null ? p + "_" : "") + n];
var v = e.type == "hidden" ? e.value : e.options[e.selectedIndex].value;
if (n == 'src')
v = tinyMCEPopup.editor.convertURL(v, 'src', null);
return ((n == d || v == '') ? '' : n + ":'" + jsEncode(v) + "',");
}
function jsEncode(s) {
s = s.replace(new RegExp('\\\\', 'g'), '\\\\');
s = s.replace(new RegExp('"', 'g'), '\\"');
s = s.replace(new RegExp("'", 'g'), "\\'");
return s;
}
function generatePreview(c) {
var f = document.forms[0], p = document.getElementById('prev');
p.innerHTML = '';
var re = new RegExp("(.+)\
var result = f.src.value.match(re);
if (result) {
f.src.value = result[1];
f.filename.value = result[2];
} else {
f.src.value = f.src.value;
f.filename.value = f.src.value;
}
// After constrain
var pl = serializeParameters();
if (pl == '') {
p.innerHTML = '';
return;
}
pl = tinyMCEPopup.editor.plugins.moodlemedia._parse(pl);
if (!pl.src) {
p.innerHTML = '';
return;
}
pl.src = tinyMCEPopup.editor.documentBaseURI.toAbsolute(pl.src);
// NOTE: Do not try to prevent https security popups here - users would get them later on real page anyway!
// We can not include URL directly in parameters because some security filters might block it.
p.innerHTML = '<iframe src="' + tinyMCEPopup.editor.getParam("moodle_plugin_base") + 'moodlemedia/preview.php'
+ '?media=' + encodeURIComponent(encode64(pl.src.toString()))
+ '&sesskey=' + encodeURIComponent(parent.M.cfg.sesskey)
+ '" width="100%" height="100%"></iframe>';
}
function encode64(input) {
var keyStr = "<API key>+/=";
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
do {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
keyStr.charAt(enc1) +
keyStr.charAt(enc2) +
keyStr.charAt(enc3) +
keyStr.charAt(enc4);
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
}
tinyMCEPopup.onInit.add(init); |
// PFQuery.m
#import <Foundation/Foundation.h>
#import "PFGeoPoint.h"
#import "PFObject.h"
#import "PFUser.h"
/*!
A class that defines a query that is used to query for PFObjects.
*/
@interface PFQuery : NSObject {
NSOperation *cancellationToken;
NSString *className;
NSMutableDictionary *where;
NSMutableArray *include;
NSInteger limit;
NSInteger skip;
NSString *order;
PFCachePolicy cachePolicy;
BOOL trace;
}
#pragma mark Query options
/** @name Creating a Query for a Class */
/*!
Returns a PFQuery for a given class.
@param className The class to query on.
@return A PFQuery object.
*/
+ (PFQuery *)queryWithClassName:(NSString *)className;
/*!
Creates a PFQuery with the constraints given by predicate.
The following types of predicates are supported:
* Simple comparisons such as =, !=, <, >, <=, >=, and BETWEEN with a key and a constant.
* Containment predicates, such as "x IN {1, 2, 3}".
* Key-existence predicates, such as "x IN SELF".
* BEGINSWITH expressions.
* Compound predicates with AND, OR, and NOT.
* SubQueries with "key IN %@", subquery.
The following types of predicates are NOT supported:
* Aggregate operations, such as ANY, SOME, ALL, or NONE.
* Regular expressions, such as LIKE, MATCHES, CONTAINS, or ENDSWITH.
* Predicates comparing one key to another.
* Complex predicates with many ORed clauses.
*/
+ (PFQuery *)queryWithClassName:(NSString *)className predicate:(NSPredicate *)predicate;
/*!
Initializes the query with a class name.
@param newClassName The class name.
*/
- (id)initWithClassName:(NSString *)newClassName;
/*!
The class name to query for
*/
@property (nonatomic, retain) NSString *className;
/** @name Adding Basic Constraints */
/*!
Make the query include PFObjects that have a reference stored at the provided key.
This has an effect similar to a join. You can use dot notation to specify which fields in
the included object are also fetch.
@param key The key to load child PFObjects for.
*/
- (void)includeKey:(NSString *)key;
/*!
Add a constraint that requires a particular key exists.
@param key The key that should exist.
*/
- (void)whereKeyExists:(NSString *)key;
/*!
Add a constraint that requires a key not exist.
@param key The key that should not exist.
*/
- (void)<API key>:(NSString *)key;
/*!
Add a constraint to the query that requires a particular key's object to be equal to the provided object.
@param key The key to be constrained.
@param object The object that must be equalled.
*/
- (void)whereKey:(NSString *)key equalTo:(id)object;
/*!
Add a constraint to the query that requires a particular key's object to be less than the provided object.
@param key The key to be constrained.
@param object The object that provides an upper bound.
*/
- (void)whereKey:(NSString *)key lessThan:(id)object;
/*!
Add a constraint to the query that requires a particular key's object to be less than or equal to the provided object.
@param key The key to be constrained.
@param object The object that must be equalled.
*/
- (void)whereKey:(NSString *)key lessThanOrEqualTo:(id)object;
/*!
Add a constraint to the query that requires a particular key's object to be greater than the provided object.
@param key The key to be constrained.
@param object The object that must be equalled.
*/
- (void)whereKey:(NSString *)key greaterThan:(id)object;
/*!
Add a constraint to the query that requires a particular key's object to be greater than or equal to the provided object.
@param key The key to be constrained.
@param object The object that must be equalled.
*/
- (void)whereKey:(NSString *)key <API key>:(id)object;
/*!
Add a constraint to the query that requires a particular key's object to be not equal to the provided object.
@param key The key to be constrained.
@param object The object that must not be equalled.
*/
- (void)whereKey:(NSString *)key notEqualTo:(id)object;
/*!
Add a constraint to the query that requires a particular key's object to be contained in the provided array.
@param key The key to be constrained.
@param array The possible values for the key's object.
*/
- (void)whereKey:(NSString *)key containedIn:(NSArray *)array;
/*!
Add a constraint to the query that requires a particular key's object not be contained in the provided array.
@param key The key to be constrained.
@param array The list of values the key's object should not be.
*/
- (void)whereKey:(NSString *)key notContainedIn:(NSArray *)array;
/*!
Add a constraint to the query that requires a particular key's array contains every element of the provided array.
@param arrayKey The key to be constrained.
@param array The array of values to search for.
*/
- (void)whereKey:(NSString *)key <API key>:(NSArray *)array;
/** @name Adding Location Constraints */
/*!
Add a constraint to the query that requires a particular key's coordinates (specified via PFGeoPoint) be near
a reference point. Distance is calculated based on angular distance on a sphere. Results will be sorted by distance
from reference point.
@param key The key to be constrained.
@param geopoint The reference point. A PFGeoPoint.
*/
- (void)whereKey:(NSString *)key nearGeoPoint:(PFGeoPoint *)geopoint;
/*!
Add a constraint to the query that requires a particular key's coordinates (specified via PFGeoPoint) be near
a reference point and within the maximum distance specified (in miles). Distance is calculated based on
a spherical coordinate system. Results will be sorted by distance (nearest to farthest) from the reference point.
@param key The key to be constrained.
@param geopoint The reference point. A PFGeoPoint.
@param maxDistance Maximum distance in miles.
*/
- (void)whereKey:(NSString *)key nearGeoPoint:(PFGeoPoint *)geopoint withinMiles:(double)maxDistance;
/*!
Add a constraint to the query that requires a particular key's coordinates (specified via PFGeoPoint) be near
a reference point and within the maximum distance specified (in kilometers). Distance is calculated based on
a spherical coordinate system. Results will be sorted by distance (nearest to farthest) from the reference point.
@param key The key to be constrained.
@param geopoint The reference point. A PFGeoPoint.
@param maxDistance Maximum distance in kilometers.
*/
- (void)whereKey:(NSString *)key nearGeoPoint:(PFGeoPoint *)geopoint withinKilometers:(double)maxDistance;
/*!
Add a constraint to the query that requires a particular key's coordinates (specified via PFGeoPoint) be near
a reference point and within the maximum distance specified (in radians). Distance is calculated based on
angular distance on a sphere. Results will be sorted by distance (nearest to farthest) from the reference point.
@param key The key to be constrained.
@param geopoint The reference point. A PFGeoPoint.
@param maxDistance Maximum distance in radians.
*/
- (void)whereKey:(NSString *)key nearGeoPoint:(PFGeoPoint *)geopoint withinRadians:(double)maxDistance;
/*!
Add a constraint to the query that requires a particular key's coordinates (specified via PFGeoPoint) be
contained within a given rectangular geographic bounding box.
@param key The key to be constrained.
@param southwest The lower-left inclusive corner of the box.
@param northeast The upper-right inclusive corner of the box.
*/
- (void)whereKey:(NSString *)key <API key>:(PFGeoPoint *)southwest toNortheast:(PFGeoPoint *)northeast;
/** @name Adding String Constraints */
/*!
Add a regular expression constraint for finding string values that match the provided regular expression.
This may be slow for large datasets.
@param key The key that the string to match is stored in.
@param regex The regular expression pattern to match.
*/
- (void)whereKey:(NSString *)key matchesRegex:(NSString *)regex;
/*!
Add a regular expression constraint for finding string values that match the provided regular expression.
This may be slow for large datasets.
@param key The key that the string to match is stored in.
@param regex The regular expression pattern to match.
@param modifiers Any of the following supported PCRE modifiers:<br><code>i</code> - Case insensitive search<br><code>m</code> - Search across multiple lines of input
*/
- (void)whereKey:(NSString *)key matchesRegex:(NSString *)regex modifiers:(NSString *)modifiers;
/*!
Add a constraint for finding string values that contain a provided substring.
This will be slow for large datasets.
@param key The key that the string to match is stored in.
@param substring The substring that the value must contain.
*/
- (void)whereKey:(NSString *)key containsString:(NSString *)substring;
/*!
Add a constraint for finding string values that start with a provided prefix.
This will use smart indexing, so it will be fast for large datasets.
@param key The key that the string to match is stored in.
@param prefix The substring that the value must start with.
*/
- (void)whereKey:(NSString *)key hasPrefix:(NSString *)prefix;
/*!
Add a constraint for finding string values that end with a provided suffix.
This will be slow for large datasets.
@param key The key that the string to match is stored in.
@param suffix The substring that the value must end with.
*/
- (void)whereKey:(NSString *)key hasSuffix:(NSString *)suffix;
/** @name Adding Subqueries */
/*!
Returns a PFQuery that is the or of the passed in PFQuerys.
@param queries The list of queries to or together.
@result a PFQuery that is the or of the passed in PFQuerys.
*/
+ (PFQuery *)<API key>:(NSArray *)queries;
/*!
Adds a constraint that requires that a key's value matches a value in another key
in objects returned by a sub query.
@param key The key that the value is stored
@param otherKey The key in objects in the returned by the sub query whose value should match
@param query The query to run.
*/
- (void)whereKey:(NSString *)key matchesKey:(NSString *)otherKey inQuery:(PFQuery *)query;
/*!
Adds a constraint that requires that a key's value NOT match a value in another key
in objects returned by a sub query.
@param key The key that the value is stored
@param otherKey The key in objects in the returned by the sub query whose value should match
@param query The query to run.
*/
- (void)whereKey:(NSString *)key doesNotMatchKey:(NSString *)otherKey inQuery:(PFQuery *)query;
/*!
Add a constraint that requires that a key's value matches a PFQuery constraint.
This only works where the key's values are PFObjects or arrays of PFObjects.
@param key The key that the value is stored in
@param query The query the value should match
*/
- (void)whereKey:(NSString *)key matchesQuery:(PFQuery *)query;
/*!
Add a constraint that requires that a key's value to not match a PFQuery constraint.
This only works where the key's values are PFObjects or arrays of PFObjects.
@param key The key that the value is stored in
@param query The query the value should not match
*/
- (void)whereKey:(NSString *)key doesNotMatchQuery:(PFQuery *)query;
#pragma mark -
#pragma mark Sorting
/** @name Sorting */
/*!
Sort the results in ascending order with the given key.
@param key The key to order by.
*/
- (void)orderByAscending:(NSString *)key;
/*!
Also sort in ascending order by the given key. The previous keys provided will
precedence over this key.
@param key The key to order bye
*/
- (void)addAscendingOrder:(NSString *)key;
/*!
Sort the results in descending order with the given key.
@param key The key to order by.
*/
- (void)orderByDescending:(NSString *)key;
/*!
Also sort in descending order by the given key. The previous keys provided will
precedence over this key.
@param key The key to order bye
*/
- (void)addDescendingOrder:(NSString *)key;
/*!
Sort the results in descending order with the given descriptor.
@param sortDescriptor The NSSortDescriptor to order by.
*/
- (void)<API key>:(NSSortDescriptor *)sortDescriptor;
/*!
Sort the results in descending order with the given descriptors.
@param sortDescriptors An NSArray of NSSortDescriptor instances to order by.
*/
- (void)<API key>:(NSArray *)sortDescriptors;
#pragma mark -
#pragma mark Get methods
/** @name Getting Objects by ID */
/*!
Returns a PFObject with a given class and id.
@param objectClass The class name for the object that is being requested.
@param objectId The id of the object that is being requested.
@result The PFObject if found. Returns nil if the object isn't found, or if there was an error.
*/
+ (PFObject *)getObjectOfClass:(NSString *)objectClass
objectId:(NSString *)objectId;
/*!
Returns a PFObject with a given class and id and sets an error if necessary.
@param error Pointer to an NSError that will be set if necessary.
@result The PFObject if found. Returns nil if the object isn't found, or if there was an error.
*/
+ (PFObject *)getObjectOfClass:(NSString *)objectClass
objectId:(NSString *)objectId
error:(NSError **)error;
/*!
Returns a PFObject with the given id.
This mutates the PFQuery.
@param objectId The id of the object that is being requested.
@result The PFObject if found. Returns nil if the object isn't found, or if there was an error.
*/
- (PFObject *)getObjectWithId:(NSString *)objectId;
/*!
Returns a PFObject with the given id and sets an error if necessary.
This mutates the PFQuery
@param error Pointer to an NSError that will be set if necessary.
@result The PFObject if found. Returns nil if the object isn't found, or if there was an error.
*/
- (PFObject *)getObjectWithId:(NSString *)objectId error:(NSError **)error;
/*!
Gets a PFObject asynchronously and calls the given block with the result.
This mutates the PFQuery
@param block The block to execute. The block should have the following argument signature: (NSArray *object, NSError *error)
*/
- (void)<API key>:(NSString *)objectId
block:(PFObjectResultBlock)block;
/*!
Gets a PFObject asynchronously.
This mutates the PFQuery
@param objectId The id of the object being requested.
@param target The target for the callback selector.
@param selector The selector for the callback. It should have the following signature: (void)callbackWithResult:(PFObject *)result error:(NSError *)error. result will be nil if error is set and vice versa.
*/
- (void)<API key>:(NSString *)objectId
target:(id)target
selector:(SEL)selector;
#pragma mark -
#pragma mark Getting Users
/*! @name Getting User Objects */
/*!
Returns a PFUser with a given id.
@param objectId The id of the object that is being requested.
@result The PFUser if found. Returns nil if the object isn't found, or if there was an error.
*/
+ (PFUser *)getUserObjectWithId:(NSString *)objectId;
/*!
Returns a PFUser with a given class and id and sets an error if necessary.
@param error Pointer to an NSError that will be set if necessary.
@result The PFUser if found. Returns nil if the object isn't found, or if there was an error.
*/
+ (PFUser *)getUserObjectWithId:(NSString *)objectId
error:(NSError **)error;
/*!
Deprecated. Please use [PFUser query] instead.
*/
+ (PFQuery *)queryForUser __attribute__ ((deprecated));
#pragma mark -
#pragma mark Find methods
/** @name Getting all Matches for a Query */
/*!
Finds objects based on the constructed query.
@result Returns an array of PFObjects that were found.
*/
- (NSArray *)findObjects;
/*!
Finds objects based on the constructed query and sets an error if there was one.
@param error Pointer to an NSError that will be set if necessary.
@result Returns an array of PFObjects that were found.
*/
- (NSArray *)findObjects:(NSError **)error;
/*!
Finds objects asynchronously and calls the given block with the results.
@param block The block to execute. The block should have the following argument signature:(NSArray *objects, NSError *error)
*/
- (void)<API key>:(PFArrayResultBlock)block;
/*!
Finds objects asynchronously and calls the given callback with the results.
@param target The object to call the selector on.
@param selector The selector to call. It should have the following signature: (void)callbackWithResult:(NSArray *)result error:(NSError *)error. result will be nil if error is set and vice versa.
*/
- (void)<API key>:(id)target selector:(SEL)selector;
/** @name Getting the First Match in a Query */
/*!
Gets an object based on the constructed query.
This mutates the PFQuery.
@result Returns a PFObject, or nil if none was found.
*/
- (PFObject *)getFirstObject;
/*!
Gets an object based on the constructed query and sets an error if any occurred.
This mutates the PFQuery.
@param error Pointer to an NSError that will be set if necessary.
@result Returns a PFObject, or nil if none was found.
*/
- (PFObject *)getFirstObject:(NSError **)error;
/*!
Gets an object asynchronously and calls the given block with the result.
This mutates the PFQuery.
@param block The block to execute. The block should have the following argument signature:(PFObject *object, NSError *error) result will be nil if error is set OR no object was found matching the query. error will be nil if result is set OR if the query succeeded, but found no results.
*/
- (void)<API key>:(PFObjectResultBlock)block;
/*!
Gets an object asynchronously and calls the given callback with the results.
This mutates the PFQuery.
@param target The object to call the selector on.
@param selector The selector to call. It should have the following signature: (void)callbackWithResult:(PFObject *)result error:(NSError *)error. result will be nil if error is set OR no object was found matching the query. error will be nil if result is set OR if the query succeeded, but found no results.
*/
- (void)<API key>:(id)target selector:(SEL)selector;
#pragma mark -
#pragma mark Count methods
/** @name Counting the Matches in a Query */
/*!
Counts objects based on the constructed query.
@result Returns the number of PFObjects that match the query, or -1 if there is an error.
*/
- (NSInteger)countObjects;
/*!
Counts objects based on the constructed query and sets an error if there was one.
@param error Pointer to an NSError that will be set if necessary.
@result Returns the number of PFObjects that match the query, or -1 if there is an error.
*/
- (NSInteger)countObjects:(NSError **)error;
/*!
Counts objects asynchronously and calls the given block with the counts.
@param block The block to execute. The block should have the following argument signature:
(int count, NSError *error)
*/
- (void)<API key>:(<API key>)block;
/*!
Counts objects asynchronously and calls the given callback with the count.
@param target The object to call the selector on.
@param selector The selector to call. It should have the following signature: (void)callbackWithResult:(NSNumber *)result error:(NSError *)error. */
- (void)<API key>:(id)target selector:(SEL)selector;
#pragma mark -
#pragma mark Cancel methods
/** @name Cancelling a Query */
/*!
Cancels the current network request (if any). Ensures that callbacks won't be called.
*/
- (void)cancel;
#pragma mark -
#pragma mark Pagination properties
/** @name Paginating Results */
/*!
A limit on the number of objects to return. The default limit is 100, with a
maximum of 1000 results being returned at a time.
Note: If you are calling findObject with limit=1, you may find it easier to use getFirst instead.
*/
@property (nonatomic) NSInteger limit;
/*!
The number of objects to skip before returning any.
*/
@property (nonatomic) NSInteger skip;
#pragma mark -
#pragma mark Cache methods
/** @name Controlling Caching Behavior */
/*!
The cache policy to use for requests.
*/
@property (readwrite, assign) PFCachePolicy cachePolicy;
/* !
The age after which a cached value will be ignored
*/
@property (readwrite, assign) NSTimeInterval maxCacheAge;
/*!
Returns whether there is a cached result for this query.
@result YES if there is a cached result for this query, and NO otherwise.
*/
- (BOOL)hasCachedResult;
/*!
Clears the cached result for this query. If there is no cached result, this is a noop.
*/
- (void)clearCachedResult;
/*!
Clears the cached results for all queries.
*/
+ (void)<API key>;
#pragma mark - Advanced Settings
/** @name Advanced Settings */
/*!
Whether or not performance tracing should be done on the query.
This should not be set in most cases.
*/
@property (nonatomic, assign) BOOL trace;
@end |
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var textCellEditor_1 = require("./textCellEditor");
var PopupTextCellEditor = (function (_super) {
__extends(PopupTextCellEditor, _super);
function PopupTextCellEditor() {
_super.apply(this, arguments);
}
PopupTextCellEditor.prototype.isPopup = function () {
return true;
};
return PopupTextCellEditor;
})(textCellEditor_1.TextCellEditor);
exports.PopupTextCellEditor = PopupTextCellEditor; |
var web3 = require('../index');
var testMethod = require('./helpers/test.method.js');
var method = 'estimateGas';
var tests = [{
args: [{
to: '<API key>',
data: '0x23455654',
gas: 11,
gasPrice: 11
}],
formattedArgs: [{
to: '<API key>',
data: '0x23455654',
gas: '0xb',
gasPrice: '0xb'
}],
result: '0x31981',
formattedResult: 203137,
call: 'eth_'+ method
}];
testMethod.runTests('eth', method, tests); |
// { dg-do run }
// { dg-xfail-if "" { "*-*-hpux11.23" } { "*" } { "" } } */
// { dg-options "-finput-charset=ISO8859-1" }
// { dg-require-iconv "ISO8859-1" }
// { <API key> "en_US" }
// { <API key> "fr_FR" }
// { <API key> "de_DE" }
// 2001-08-15 Benjamin Kosnik <bkoz@redhat.com>
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// with this library; see the file COPYING3. If not see
// 22.2.4.1.1 collate members
#include <locale>
#include <testsuite_hooks.h>
// Check German "de_DE" locale.
void test02()
{
using namespace std;
typedef std::collate<wchar_t>::string_type string_type;
bool test __attribute__((unused)) = true;
// basic construction
locale loc_c = locale::classic();
locale loc_us = locale("en_US");
locale loc_fr = locale("fr_FR");
locale loc_de = locale("de_DE");
VERIFY( loc_c != loc_de );
VERIFY( loc_us != loc_fr );
VERIFY( loc_us != loc_de );
VERIFY( loc_de != loc_fr );
// cache the collate facets
const collate<wchar_t>& coll_de = use_facet<collate<wchar_t> >(loc_de);
// int compare(const charT*, const charT*, const charT*, const charT*) const
const wchar_t* strlit1 = L"monkey picked tikuanyin oolong";
const wchar_t* strlit3 = L"Äuglein Augment";
const wchar_t* strlit4 = L"Base baß Baß Bast";
int i1;
int i2;
int size1 = char_traits<wchar_t>::length(strlit1) - 1;
int size3 = char_traits<wchar_t>::length(strlit3) - 1;
int size4 = char_traits<wchar_t>::length(strlit4) - 1;
i1 = coll_de.compare(strlit3, strlit3 + size3, strlit3, strlit3 + 7);
VERIFY ( i1 == 1 );
i1 = coll_de.compare(strlit3, strlit3 + 7, strlit3, strlit3 + size1);
VERIFY ( i1 == -1 );
i1 = coll_de.compare(strlit3, strlit3 + 7, strlit3, strlit3 + 7);
VERIFY ( i1 == 0 );
i1 = coll_de.compare(strlit3, strlit3 + 6, strlit3 + 8, strlit3 + 14);
VERIFY ( i1 == -1 );
i2 = coll_de.compare(strlit4, strlit4 + size4, strlit4, strlit4 + 13);
VERIFY ( i2 == 1 );
i2 = coll_de.compare(strlit4, strlit4 + 13, strlit4, strlit4 + size4);
VERIFY ( i2 == -1 );
i2 = coll_de.compare(strlit4, strlit4 + size4, strlit4, strlit4 + size4);
VERIFY ( i2 == 0 );
}
int main()
{
test02();
return 0;
} |
#ifndef LINUX_MMC_CORE_H
#define LINUX_MMC_CORE_H
#include <linux/interrupt.h>
#include <linux/device.h>
struct request;
struct mmc_data;
struct mmc_request;
struct mmc_command {
u32 opcode;
u32 arg;
u32 resp[4];
unsigned int flags; /* expected response type */
#define MMC_RSP_PRESENT (1 << 0)
#define MMC_RSP_136 (1 << 1) /* 136 bit response */
#define MMC_RSP_CRC (1 << 2) /* expect valid crc */
#define MMC_RSP_BUSY (1 << 3) /* card may send busy */
#define MMC_RSP_OPCODE (1 << 4) /* response contains opcode */
#define MMC_CMD_MASK (3 << 5) /* non-SPI command type */
#define MMC_CMD_AC (0 << 5)
#define MMC_CMD_ADTC (1 << 5)
#define MMC_CMD_BC (2 << 5)
#define MMC_CMD_BCR (3 << 5)
#define MMC_RSP_SPI_S1 (1 << 7) /* one status byte */
#define MMC_RSP_SPI_S2 (1 << 8) /* second byte */
#define MMC_RSP_SPI_B4 (1 << 9) /* four data bytes */
#define MMC_RSP_SPI_BUSY (1 << 10) /* card may send busy */
/*
* These are the native response types, and correspond to valid bit
* patterns of the above flags. One additional valid pattern
* is all zeros, which means we don't expect a response.
*/
#define MMC_RSP_NONE (0)
#define MMC_RSP_R1 (MMC_RSP_PRESENT|MMC_RSP_CRC|MMC_RSP_OPCODE)
#define MMC_RSP_R1B (MMC_RSP_PRESENT|MMC_RSP_CRC|MMC_RSP_OPCODE|MMC_RSP_BUSY)
#define MMC_RSP_R2 (MMC_RSP_PRESENT|MMC_RSP_136|MMC_RSP_CRC)
#define MMC_RSP_R3 (MMC_RSP_PRESENT)
#define MMC_RSP_R4 (MMC_RSP_PRESENT)
#define MMC_RSP_R5 (MMC_RSP_PRESENT|MMC_RSP_CRC|MMC_RSP_OPCODE)
#define MMC_RSP_R6 (MMC_RSP_PRESENT|MMC_RSP_CRC|MMC_RSP_OPCODE)
#define MMC_RSP_R7 (MMC_RSP_PRESENT|MMC_RSP_CRC|MMC_RSP_OPCODE)
#define mmc_resp_type(cmd) ((cmd)->flags & (MMC_RSP_PRESENT|MMC_RSP_136|MMC_RSP_CRC|MMC_RSP_BUSY|MMC_RSP_OPCODE))
/*
* These are the SPI response types for MMC, SD, and SDIO cards.
* Commands return R1, with maybe more info. Zero is an error type;
* callers must always provide the appropriate MMC_RSP_SPI_Rx flags.
*/
#define MMC_RSP_SPI_R1 (MMC_RSP_SPI_S1)
#define MMC_RSP_SPI_R1B (MMC_RSP_SPI_S1|MMC_RSP_SPI_BUSY)
#define MMC_RSP_SPI_R2 (MMC_RSP_SPI_S1|MMC_RSP_SPI_S2)
#define MMC_RSP_SPI_R3 (MMC_RSP_SPI_S1|MMC_RSP_SPI_B4)
#define MMC_RSP_SPI_R4 (MMC_RSP_SPI_S1|MMC_RSP_SPI_B4)
#define MMC_RSP_SPI_R5 (MMC_RSP_SPI_S1|MMC_RSP_SPI_S2)
#define MMC_RSP_SPI_R7 (MMC_RSP_SPI_S1|MMC_RSP_SPI_B4)
#define mmc_spi_resp_type(cmd) ((cmd)->flags & \
(MMC_RSP_SPI_S1|MMC_RSP_SPI_BUSY|MMC_RSP_SPI_S2|MMC_RSP_SPI_B4))
/*
* These are the command types.
*/
#define mmc_cmd_type(cmd) ((cmd)->flags & MMC_CMD_MASK)
unsigned int retries; /* max number of retries */
unsigned int error; /* command error */
/*
* Standard errno values are used for errors, but some have specific
* meaning in the MMC layer:
*
* ETIMEDOUT Card took too long to respond
* EILSEQ Basic format problem with the received or sent data
* (e.g. CRC check failed, incorrect opcode in response
* or bad end bit)
* EINVAL Request cannot be performed because of restrictions
* in hardware and/or the driver
* ENOMEDIUM Host can determine that the slot is empty and is
* actively failing requests
*/
unsigned int cmd_timeout_ms; /* in milliseconds */
struct mmc_data *data; /* data segment associated with cmd */
struct mmc_request *mrq; /* associated request */
};
struct mmc_data {
unsigned int timeout_ns; /* data timeout (in ns, max 80ms) */
unsigned int timeout_clks; /* data timeout (in clocks) */
unsigned int blksz; /* data block size */
unsigned int blocks; /* number of blocks */
unsigned int error; /* data error */
unsigned int flags;
#define MMC_DATA_WRITE (1 << 8)
#define MMC_DATA_READ (1 << 9)
#define MMC_DATA_STREAM (1 << 10)
unsigned int bytes_xfered;
struct mmc_command *stop; /* stop command */
struct mmc_request *mrq; /* associated request */
unsigned int sg_len; /* size of scatter list */
struct scatterlist *sg; /* I/O scatter list */
};
struct mmc_request {
struct mmc_command *sbc; /* SET_BLOCK_COUNT for multiblock */
struct mmc_command *cmd;
struct mmc_data *data;
struct mmc_command *stop;
void *done_data; /* completion data */
void (*done)(struct mmc_request *);/* completion function */
};
struct mmc_host;
struct mmc_card;
extern void mmc_wait_for_req(struct mmc_host *, struct mmc_request *);
extern int mmc_wait_for_cmd(struct mmc_host *, struct mmc_command *, int);
extern int mmc_app_cmd(struct mmc_host *, struct mmc_card *);
extern int <API key>(struct mmc_host *, struct mmc_card *,
struct mmc_command *, int);
extern int mmc_switch(struct mmc_card *, u8, u8, u8, unsigned int);
#define MMC_ERASE_ARG 0x00000000
/* #define <API key> 0x80000000 */
#define MMC_TRIM_ARG 0x00000001
#define MMC_DISCARD_ARG 0x00000003
/* #define <API key> 0x80000001
#define <API key> 0x80008000 */
#define MMC_SECURE_ARGS 0x80000000
#define MMC_TRIM_ARGS 0x00008001
extern int mmc_erase(struct mmc_card *card, unsigned int from, unsigned int nr,
unsigned int arg);
extern int mmc_can_erase(struct mmc_card *card);
extern int mmc_can_trim(struct mmc_card *card);
extern int mmc_can_discard(struct mmc_card *card);
extern int <API key>(struct mmc_card *card);
extern int <API key>(struct mmc_card *card, unsigned int from,
unsigned int nr);
extern int mmc_set_blocklen(struct mmc_card *card, unsigned int blocklen);
extern void <API key>(struct mmc_data *, const struct mmc_card *);
extern unsigned int mmc_align_data_size(struct mmc_card *, unsigned int);
extern int __mmc_claim_host(struct mmc_host *host, atomic_t *abort);
extern void mmc_release_host(struct mmc_host *host);
extern void mmc_do_release_host(struct mmc_host *host);
extern int mmc_try_claim_host(struct mmc_host *host);
extern int <API key>(struct mmc_host *host);
/**
* mmc_claim_host - exclusively claim a host
* @host: mmc host to claim
*
* Claim a host for a set of operations.
*/
static inline void mmc_claim_host(struct mmc_host *host)
{
__mmc_claim_host(host, NULL);
}
extern u32 <API key>(int vdd_min, int vdd_max);
#endif |
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/timer.h>
#include <linux/init.h>
#include <linux/gpio.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/proc_fs.h>
#include <linux/serial_core.h>
#include <linux/serial_s3c.h>
#include <linux/io.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <asm/mach/flash.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/mach-types.h>
#include <mach/fb.h>
#include <mach/regs-lcd.h>
#include <mach/regs-gpio.h>
#include <mach/gpio-samsung.h>
#include <linux/platform_data/i2c-s3c2410.h>
#include <plat/devs.h>
#include <plat/cpu.h>
#include <plat/gpio-cfg.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/map.h>
#include <linux/mtd/physmap.h>
#include <plat/samsung-time.h>
#include "common.h"
static struct resource <API key> =
DEFINE_RES_MEM(0x00000000, SZ_16M);
static struct mtd_partition <API key>[] = {
{
.name = "System",
.size = 0x240000,
.offset = 0,
.mask_flags = MTD_WRITEABLE, /* force read-only */
}, {
.name = "Kernel",
.size = 0x100000,
.offset = MTDPART_OFS_APPEND,
}, {
.name = "Ramdisk",
.size = 0x300000,
.offset = MTDPART_OFS_APPEND,
}, {
.name = "JFFS2",
.size = 0x9A0000,
.offset = MTDPART_OFS_APPEND,
}, {
.name = "Settings",
.size = MTDPART_SIZ_FULL,
.offset = MTDPART_OFS_APPEND,
}
};
static struct physmap_flash_data amlm5900_flash_data = {
.width = 2,
.parts = <API key>,
.nr_parts = ARRAY_SIZE(<API key>),
};
static struct platform_device amlm5900_device_nor = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &amlm5900_flash_data,
},
.num_resources = 1,
.resource = &<API key>,
};
static struct map_desc amlm5900_iodesc[] __initdata = {
};
#define UCON <API key>
#define ULCON S3C2410_LCON_CS8 | S3C2410_LCON_PNONE | S3C2410_LCON_STOPB
#define UFCON <API key> | <API key>
static struct s3c2410_uartcfg amlm5900_uartcfgs[] = {
[0] = {
.hwport = 0,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
[1] = {
.hwport = 1,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
[2] = {
.hwport = 2,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
}
};
static struct platform_device *amlm5900_devices[] __initdata = {
#ifdef CONFIG_FB_S3C2410
&s3c_device_lcd,
#endif
&s3c_device_adc,
&s3c_device_wdt,
&s3c_device_i2c0,
&s3c_device_ohci,
&s3c_device_rtc,
&<API key>,
&s3c_device_sdi,
&amlm5900_device_nor,
};
static void __init amlm5900_map_io(void)
{
s3c24xx_init_io(amlm5900_iodesc, ARRAY_SIZE(amlm5900_iodesc));
s3c24xx_init_clocks(0);
s3c24xx_init_uarts(amlm5900_uartcfgs, ARRAY_SIZE(amlm5900_uartcfgs));
<API key>(SAMSUNG_PWM3, SAMSUNG_PWM4);
}
#ifdef CONFIG_FB_S3C2410
static struct s3c2410fb_display __initdata amlm5900_lcd_info = {
.width = 160,
.height = 160,
.type = <API key>,
.pixclock = 680000, /* HCLK = 100MHz */
.xres = 160,
.yres = 160,
.bpp = 4,
.left_margin = 1 << (4 + 3),
.right_margin = 8 << 3,
.hsync_len = 48,
.upper_margin = 0,
.lower_margin = 0,
.lcdcon5 = 0x00000001,
};
static struct s3c2410fb_mach_info __initdata amlm5900_fb_info = {
.displays = &amlm5900_lcd_info,
.num_displays = 1,
.default_display = 0,
.gpccon = 0xaaaaaaaa,
.gpccon_mask = 0xffffffff,
.gpcup = 0x0000ffff,
.gpcup_mask = 0xffffffff,
.gpdcon = 0xaaaaaaaa,
.gpdcon_mask = 0xffffffff,
.gpdup = 0x0000ffff,
.gpdup_mask = 0xffffffff,
};
#endif
static irqreturn_t
<API key>(int irq, void *ignored)
{
return IRQ_HANDLED;
}
static void amlm5900_init_pm(void)
{
int ret = 0;
ret = request_irq(IRQ_EINT9, &<API key>,
IRQF_TRIGGER_RISING | IRQF_SHARED,
"amlm5900_wakeup", &<API key>);
if (ret != 0) {
printk(KERN_ERR "AML-M5900: no wakeup irq, %d?\n", ret);
} else {
enable_irq_wake(IRQ_EINT9);
/* configure the suspend/resume status pin */
s3c_gpio_cfgpin(S3C2410_GPF(2), S3C2410_GPIO_OUTPUT);
s3c_gpio_setpull(S3C2410_GPF(2), S3C_GPIO_PULL_UP);
}
}
static void __init amlm5900_init(void)
{
amlm5900_init_pm();
#ifdef CONFIG_FB_S3C2410
<API key>(&amlm5900_fb_info);
#endif
<API key>(NULL);
<API key>(amlm5900_devices, ARRAY_SIZE(amlm5900_devices));
}
MACHINE_START(AML_M5900, "AML_M5900")
.atag_offset = 0x100,
.map_io = amlm5900_map_io,
.init_irq = s3c2410_init_irq,
.init_machine = amlm5900_init,
.init_time = samsung_timer_init,
.restart = s3c2410_restart,
MACHINE_END |
#undef TRACE_SYSTEM
#define TRACE_SYSTEM sched
#if !defined(_TRACE_SCHED_H) || defined(<API key>)
#define _TRACE_SCHED_H
#include <linux/sched.h>
#include <linux/tracepoint.h>
#include <linux/binfmts.h>
/*
* Tracepoint for calling kthread_stop, performed to end a kthread:
*/
TRACE_EVENT(sched_kthread_stop,
TP_PROTO(struct task_struct *t),
TP_ARGS(t),
TP_STRUCT__entry(
__array( char, comm, TASK_COMM_LEN )
__field( pid_t, pid )
),
TP_fast_assign(
memcpy(__entry->comm, t->comm, TASK_COMM_LEN);
__entry->pid = t->pid;
),
TP_printk("comm=%s pid=%d", __entry->comm, __entry->pid)
);
/*
* Tracepoint for the return value of the kthread stopping:
*/
TRACE_EVENT(<API key>,
TP_PROTO(int ret),
TP_ARGS(ret),
TP_STRUCT__entry(
__field( int, ret )
),
TP_fast_assign(
__entry->ret = ret;
),
TP_printk("ret=%d", __entry->ret)
);
/*
* Tracepoint for waking up a task:
*/
DECLARE_EVENT_CLASS(<API key>,
TP_PROTO(struct task_struct *p, int success),
TP_ARGS(p, success),
TP_STRUCT__entry(
__array( char, comm, TASK_COMM_LEN )
__field( pid_t, pid )
__field( int, prio )
__field( int, success )
__field( int, target_cpu )
),
TP_fast_assign(
memcpy(__entry->comm, p->comm, TASK_COMM_LEN);
__entry->pid = p->pid;
__entry->prio = p->prio;
__entry->success = success;
__entry->target_cpu = task_cpu(p);
)
TP_perf_assign(
__perf_task(p);
),
TP_printk("comm=%s pid=%d prio=%d success=%d target_cpu=%03d",
__entry->comm, __entry->pid, __entry->prio,
__entry->success, __entry->target_cpu)
);
DEFINE_EVENT(<API key>, sched_wakeup,
TP_PROTO(struct task_struct *p, int success),
TP_ARGS(p, success));
/*
* Tracepoint for waking up a new task:
*/
DEFINE_EVENT(<API key>, sched_wakeup_new,
TP_PROTO(struct task_struct *p, int success),
TP_ARGS(p, success));
#ifdef CREATE_TRACE_POINTS
static inline long <API key>(struct task_struct *p)
{
long state = p->state;
#ifdef CONFIG_PREEMPT
/*
* For all intents and purposes a preempted task is a running task.
*/
if (task_thread_info(p)->preempt_count & PREEMPT_ACTIVE)
state = TASK_RUNNING | TASK_STATE_MAX;
#endif
return state;
}
#endif
/*
* Tracepoint for task switches, performed by the scheduler:
*/
TRACE_EVENT(sched_switch,
TP_PROTO(struct task_struct *prev,
struct task_struct *next),
TP_ARGS(prev, next),
TP_STRUCT__entry(
__array( char, prev_comm, TASK_COMM_LEN )
__field( pid_t, prev_pid )
__field( int, prev_prio )
__field( long, prev_state )
__array( char, next_comm, TASK_COMM_LEN )
__field( pid_t, next_pid )
__field( int, next_prio )
),
TP_fast_assign(
memcpy(__entry->next_comm, next->comm, TASK_COMM_LEN);
__entry->prev_pid = prev->pid;
__entry->prev_prio = prev->prio;
__entry->prev_state = <API key>(prev);
memcpy(__entry->prev_comm, prev->comm, TASK_COMM_LEN);
__entry->next_pid = next->pid;
__entry->next_prio = next->prio;
),
TP_printk("prev_comm=%s prev_pid=%d prev_prio=%d prev_state=%s%s ==> next_comm=%s next_pid=%d next_prio=%d",
__entry->prev_comm, __entry->prev_pid, __entry->prev_prio,
__entry->prev_state & (TASK_STATE_MAX-1) ?
__print_flags(__entry->prev_state & (TASK_STATE_MAX-1), "|",
{ 1, "S"} , { 2, "D" }, { 4, "T" }, { 8, "t" },
{ 16, "Z" }, { 32, "X" }, { 64, "x" },
{ 128, "K" }, { 256, "W" }, { 512, "P" }) : "R",
__entry->prev_state & TASK_STATE_MAX ? "+" : "",
__entry->next_comm, __entry->next_pid, __entry->next_prio)
);
/*
* Tracepoint for a task being migrated:
*/
TRACE_EVENT(sched_migrate_task,
TP_PROTO(struct task_struct *p, int dest_cpu),
TP_ARGS(p, dest_cpu),
TP_STRUCT__entry(
__array( char, comm, TASK_COMM_LEN )
__field( pid_t, pid )
__field( int, prio )
__field( int, orig_cpu )
__field( int, dest_cpu )
),
TP_fast_assign(
memcpy(__entry->comm, p->comm, TASK_COMM_LEN);
__entry->pid = p->pid;
__entry->prio = p->prio;
__entry->orig_cpu = task_cpu(p);
__entry->dest_cpu = dest_cpu;
),
TP_printk("comm=%s pid=%d prio=%d orig_cpu=%d dest_cpu=%d",
__entry->comm, __entry->pid, __entry->prio,
__entry->orig_cpu, __entry->dest_cpu)
);
DECLARE_EVENT_CLASS(<API key>,
TP_PROTO(struct task_struct *p),
TP_ARGS(p),
TP_STRUCT__entry(
__array( char, comm, TASK_COMM_LEN )
__field( pid_t, pid )
__field( int, prio )
),
TP_fast_assign(
memcpy(__entry->comm, p->comm, TASK_COMM_LEN);
__entry->pid = p->pid;
__entry->prio = p->prio;
),
TP_printk("comm=%s pid=%d prio=%d",
__entry->comm, __entry->pid, __entry->prio)
);
/*
* Tracepoint for freeing a task:
*/
DEFINE_EVENT(<API key>, sched_process_free,
TP_PROTO(struct task_struct *p),
TP_ARGS(p));
/*
* Tracepoint for a task exiting:
*/
DEFINE_EVENT(<API key>, sched_process_exit,
TP_PROTO(struct task_struct *p),
TP_ARGS(p));
/*
* Tracepoint for waiting on task to unschedule:
*/
DEFINE_EVENT(<API key>, sched_wait_task,
TP_PROTO(struct task_struct *p),
TP_ARGS(p));
/*
* Tracepoint for a waiting task:
*/
TRACE_EVENT(sched_process_wait,
TP_PROTO(struct pid *pid),
TP_ARGS(pid),
TP_STRUCT__entry(
__array( char, comm, TASK_COMM_LEN )
__field( pid_t, pid )
__field( int, prio )
),
TP_fast_assign(
memcpy(__entry->comm, current->comm, TASK_COMM_LEN);
__entry->pid = pid_nr(pid);
__entry->prio = current->prio;
),
TP_printk("comm=%s pid=%d prio=%d",
__entry->comm, __entry->pid, __entry->prio)
);
/*
* Tracepoint for do_fork:
*/
TRACE_EVENT(sched_process_fork,
TP_PROTO(struct task_struct *parent, struct task_struct *child),
TP_ARGS(parent, child),
TP_STRUCT__entry(
__array( char, parent_comm, TASK_COMM_LEN )
__field( pid_t, parent_pid )
__array( char, child_comm, TASK_COMM_LEN )
__field( pid_t, child_pid )
),
TP_fast_assign(
memcpy(__entry->parent_comm, parent->comm, TASK_COMM_LEN);
__entry->parent_pid = parent->pid;
memcpy(__entry->child_comm, child->comm, TASK_COMM_LEN);
__entry->child_pid = child->pid;
),
TP_printk("comm=%s pid=%d child_comm=%s child_pid=%d",
__entry->parent_comm, __entry->parent_pid,
__entry->child_comm, __entry->child_pid)
);
/*
* Tracepoint for exec:
*/
TRACE_EVENT(sched_process_exec,
TP_PROTO(struct task_struct *p, pid_t old_pid,
struct linux_binprm *bprm),
TP_ARGS(p, old_pid, bprm),
TP_STRUCT__entry(
__string( filename, bprm->filename )
__field( pid_t, pid )
__field( pid_t, old_pid )
),
TP_fast_assign(
__assign_str(filename, bprm->filename);
__entry->pid = p->pid;
__entry->old_pid = old_pid;
),
TP_printk("filename=%s pid=%d old_pid=%d", __get_str(filename),
__entry->pid, __entry->old_pid)
);
/*
* XXX the below sched_stat tracepoints only apply to SCHED_OTHER/BATCH/IDLE
* adding sched_stat support to SCHED_FIFO/RR would be welcome.
*/
DECLARE_EVENT_CLASS(sched_stat_template,
TP_PROTO(struct task_struct *tsk, u64 delay),
TP_ARGS(tsk, delay),
TP_STRUCT__entry(
__array( char, comm, TASK_COMM_LEN )
__field( pid_t, pid )
__field( u64, delay )
),
TP_fast_assign(
memcpy(__entry->comm, tsk->comm, TASK_COMM_LEN);
__entry->pid = tsk->pid;
__entry->delay = delay;
)
TP_perf_assign(
__perf_count(delay);
__perf_task(tsk);
),
TP_printk("comm=%s pid=%d delay=%Lu [ns]",
__entry->comm, __entry->pid,
(unsigned long long)__entry->delay)
);
/*
* Tracepoint for accounting wait time (time the task is runnable
* but not actually running due to scheduler contention).
*/
DEFINE_EVENT(sched_stat_template, sched_stat_wait,
TP_PROTO(struct task_struct *tsk, u64 delay),
TP_ARGS(tsk, delay));
/*
* Tracepoint for accounting sleep time (time the task is not runnable,
* including iowait, see below).
*/
DEFINE_EVENT(sched_stat_template, sched_stat_sleep,
TP_PROTO(struct task_struct *tsk, u64 delay),
TP_ARGS(tsk, delay));
/*
* Tracepoint for accounting iowait time (time the task is not runnable
* due to waiting on IO to complete).
*/
DEFINE_EVENT(sched_stat_template, sched_stat_iowait,
TP_PROTO(struct task_struct *tsk, u64 delay),
TP_ARGS(tsk, delay));
/*
* Tracepoint for accounting blocked time (time the task is in uninterruptible).
*/
DEFINE_EVENT(sched_stat_template, sched_stat_blocked,
TP_PROTO(struct task_struct *tsk, u64 delay),
TP_ARGS(tsk, delay));
/*
* Tracepoint for accounting runtime (time the task is executing
* on a CPU).
*/
TRACE_EVENT(sched_stat_runtime,
TP_PROTO(struct task_struct *tsk, u64 runtime, u64 vruntime),
TP_ARGS(tsk, runtime, vruntime),
TP_STRUCT__entry(
__array( char, comm, TASK_COMM_LEN )
__field( pid_t, pid )
__field( u64, runtime )
__field( u64, vruntime )
),
TP_fast_assign(
memcpy(__entry->comm, tsk->comm, TASK_COMM_LEN);
__entry->pid = tsk->pid;
__entry->runtime = runtime;
__entry->vruntime = vruntime;
)
TP_perf_assign(
__perf_count(runtime);
),
TP_printk("comm=%s pid=%d runtime=%Lu [ns] vruntime=%Lu [ns]",
__entry->comm, __entry->pid,
(unsigned long long)__entry->runtime,
(unsigned long long)__entry->vruntime)
);
/*
* Tracepoint for showing priority inheritance modifying a tasks
* priority.
*/
TRACE_EVENT(sched_pi_setprio,
TP_PROTO(struct task_struct *tsk, int newprio),
TP_ARGS(tsk, newprio),
TP_STRUCT__entry(
__array( char, comm, TASK_COMM_LEN )
__field( pid_t, pid )
__field( int, oldprio )
__field( int, newprio )
),
TP_fast_assign(
memcpy(__entry->comm, tsk->comm, TASK_COMM_LEN);
__entry->pid = tsk->pid;
__entry->oldprio = tsk->prio;
__entry->newprio = newprio;
),
TP_printk("comm=%s pid=%d oldprio=%d newprio=%d",
__entry->comm, __entry->pid,
__entry->oldprio, __entry->newprio)
);
/*
* Tracepoint for showing tracked load contribution.
*/
TRACE_EVENT(<API key>,
TP_PROTO(struct task_struct *tsk, unsigned long load_contrib),
TP_ARGS(tsk, load_contrib),
TP_STRUCT__entry(
__array(char, comm, TASK_COMM_LEN)
__field(pid_t, pid)
__field(unsigned long, load_contrib)
),
TP_fast_assign(
memcpy(__entry->comm, tsk->comm, TASK_COMM_LEN);
__entry->pid = tsk->pid;
__entry->load_contrib = load_contrib;
),
TP_printk("comm=%s pid=%d load_contrib=%lu",
__entry->comm, __entry->pid,
__entry->load_contrib)
);
/*
* Tracepoint for showing tracked task runnable ratio [0..1023].
*/
TRACE_EVENT(<API key>,
TP_PROTO(struct task_struct *tsk, unsigned long ratio),
TP_ARGS(tsk, ratio),
TP_STRUCT__entry(
__array(char, comm, TASK_COMM_LEN)
__field(pid_t, pid)
__field(unsigned long, ratio)
),
TP_fast_assign(
memcpy(__entry->comm, tsk->comm, TASK_COMM_LEN);
__entry->pid = tsk->pid;
__entry->ratio = ratio;
),
TP_printk("comm=%s pid=%d ratio=%lu",
__entry->comm, __entry->pid,
__entry->ratio)
);
/*
* Tracepoint for showing tracked rq runnable ratio [0..1023].
*/
TRACE_EVENT(<API key>,
TP_PROTO(int cpu, unsigned long ratio),
TP_ARGS(cpu, ratio),
TP_STRUCT__entry(
__field(int, cpu)
__field(unsigned long, ratio)
),
TP_fast_assign(
__entry->cpu = cpu;
__entry->ratio = ratio;
),
TP_printk("cpu=%d ratio=%lu",
__entry->cpu,
__entry->ratio)
);
/*
* Tracepoint for showing tracked rq runnable load.
*/
TRACE_EVENT(<API key>,
TP_PROTO(int cpu, u64 load),
TP_ARGS(cpu, load),
TP_STRUCT__entry(
__field(int, cpu)
__field(u64, load)
),
TP_fast_assign(
__entry->cpu = cpu;
__entry->load = load;
),
TP_printk("cpu=%d load=%llu",
__entry->cpu,
__entry->load)
);
TRACE_EVENT(sched_rq_nr_running,
TP_PROTO(int cpu, unsigned int nr_running, int nr_iowait),
TP_ARGS(cpu, nr_running, nr_iowait),
TP_STRUCT__entry(
__field(int, cpu)
__field(unsigned int, nr_running)
__field(int, nr_iowait)
),
TP_fast_assign(
__entry->cpu = cpu;
__entry->nr_running = nr_running;
__entry->nr_iowait = nr_iowait;
),
TP_printk("cpu=%d nr_running=%u nr_iowait=%d",
__entry->cpu,
__entry->nr_running, __entry->nr_iowait)
);
/*
* Tracepoint for showing tracked task cpu usage ratio [0..1023].
*/
TRACE_EVENT(<API key>,
TP_PROTO(struct task_struct *tsk, unsigned long ratio),
TP_ARGS(tsk, ratio),
TP_STRUCT__entry(
__array(char, comm, TASK_COMM_LEN)
__field(pid_t, pid)
__field(unsigned long, ratio)
),
TP_fast_assign(
memcpy(__entry->comm, tsk->comm, TASK_COMM_LEN);
__entry->pid = tsk->pid;
__entry->ratio = ratio;
),
TP_printk("comm=%s pid=%d ratio=%lu",
__entry->comm, __entry->pid,
__entry->ratio)
);
/*
* Tracepoint for HMP (CONFIG_SCHED_HMP) task migrations,
* marking the forced transition of runnable or running tasks.
*/
TRACE_EVENT(<API key>,
TP_PROTO(struct task_struct *tsk, int running),
TP_ARGS(tsk, running),
TP_STRUCT__entry(
__array(char, comm, TASK_COMM_LEN)
__field(int, running)
),
TP_fast_assign(
memcpy(__entry->comm, tsk->comm, TASK_COMM_LEN);
__entry->running = running;
),
TP_printk("running=%d comm=%s",
__entry->running, __entry->comm)
);
/*
* Tracepoint for HMP (CONFIG_SCHED_HMP) task migrations,
* marking the forced transition of runnable or running
* tasks when a task is about to go idle.
*/
TRACE_EVENT(<API key>,
TP_PROTO(struct task_struct *tsk, int running),
TP_ARGS(tsk, running),
TP_STRUCT__entry(
__array(char, comm, TASK_COMM_LEN)
__field(int, running)
),
TP_fast_assign(
memcpy(__entry->comm, tsk->comm, TASK_COMM_LEN);
__entry->running = running;
),
TP_printk("running=%d comm=%s",
__entry->running, __entry->comm)
);
/*
* Tracepoint for HMP (CONFIG_SCHED_HMP) task migrations.
*/
#define HMP_MIGRATE_WAKEUP 0
#define HMP_MIGRATE_FORCE 1
#define HMP_MIGRATE_OFFLOAD 2
#define <API key> 3
TRACE_EVENT(sched_hmp_migrate,
TP_PROTO(struct task_struct *tsk, int dest, int force),
TP_ARGS(tsk, dest, force),
TP_STRUCT__entry(
__array(char, comm, TASK_COMM_LEN)
__field(pid_t, pid)
__field(int, dest)
__field(int, force)
),
TP_fast_assign(
memcpy(__entry->comm, tsk->comm, TASK_COMM_LEN);
__entry->pid = tsk->pid;
__entry->dest = dest;
__entry->force = force;
),
TP_printk("comm=%s pid=%d dest=%d force=%d",
__entry->comm, __entry->pid,
__entry->dest, __entry->force)
);
TRACE_EVENT(<API key>,
TP_PROTO(int cpu, int data, char *label),
TP_ARGS(cpu,data,label),
TP_STRUCT__entry(
__array(char, label, 64)
__field(int, cpu)
__field(int, data)
),
TP_fast_assign(
strncpy(__entry->label, label, 64);
__entry->cpu = cpu;
__entry->data = data;
),
TP_printk("cpu=%d data=%d label=%63s",
__entry->cpu, __entry->data,
__entry->label)
);
TRACE_EVENT(<API key>,
TP_PROTO(int cpu, int dest_cpu),
TP_ARGS(cpu,dest_cpu),
TP_STRUCT__entry(
__field(int, cpu)
__field(int, dest_cpu)
),
TP_fast_assign(
__entry->cpu = cpu;
__entry->dest_cpu = dest_cpu;
),
TP_printk("cpu=%d dest=%d",
__entry->cpu,
__entry->dest_cpu)
);
#endif /* _TRACE_SCHED_H */
/* This part must be outside protection */
#include <trace/define_trace.h> |
// <meta> timeout=long
importScripts("/resources/testharness.js");
importScripts("../util/helpers.js");
importScripts("successes.js");
run_test(["AES-CTR"]);
done(); |
"""Test script for popen2.py"""
import warnings
warnings.filterwarnings("ignore", ".*popen2 module is deprecated.*",
DeprecationWarning)
warnings.filterwarnings("ignore", "os\.popen. is deprecated.*",
DeprecationWarning)
import os
import sys
import unittest
import popen2
from test.test_support import run_unittest, reap_children
if sys.platform[:4] == 'beos' or sys.platform[:6] == 'atheos':
# Locks get messed up or something. Generally we're supposed
# to avoid mixing "posix" fork & exec with native threads, and
# they may be right about that after all.
raise unittest.SkipTest("popen2() doesn't work on " + sys.platform)
# if we don't have os.popen, check that
# we have os.fork. if not, skip the test
# (by raising an ImportError)
try:
from os import popen
del popen
except ImportError:
from os import fork
del fork
class Popen2Test(unittest.TestCase):
cmd = "cat"
if os.name == "nt":
cmd = "more"
teststr = "ab cd\n"
# "more" doesn't act the same way across Windows flavors,
# sometimes adding an extra newline at the start or the
# end. So we strip whitespace off both ends for comparison.
expected = teststr.strip()
def setUp(self):
popen2._cleanup()
# When the test runs, there shouldn't be any open pipes
self.assertFalse(popen2._active, "Active pipes when test starts" +
repr([c.cmd for c in popen2._active]))
def tearDown(self):
for inst in popen2._active:
inst.wait()
popen2._cleanup()
self.assertFalse(popen2._active, "popen2._active not empty")
# The os.popen*() API delegates to the subprocess module (on Unix)
import subprocess
for inst in subprocess._active:
inst.wait()
subprocess._cleanup()
self.assertFalse(subprocess._active, "subprocess._active not empty")
reap_children()
def validate_output(self, teststr, expected_out, r, w, e=None):
w.write(teststr)
w.close()
got = r.read()
self.assertEqual(expected_out, got.strip(), "wrote %r read %r" %
(teststr, got))
if e is not None:
got = e.read()
self.assertFalse(got, "unexpected %r on stderr" % got)
def test_popen2(self):
r, w = popen2.popen2(self.cmd)
self.validate_output(self.teststr, self.expected, r, w)
def test_popen3(self):
if os.name == 'posix':
r, w, e = popen2.popen3([self.cmd])
self.validate_output(self.teststr, self.expected, r, w, e)
r, w, e = popen2.popen3(self.cmd)
self.validate_output(self.teststr, self.expected, r, w, e)
def test_os_popen2(self):
# same test as test_popen2(), but using the os.popen*() API
if os.name == 'posix':
w, r = os.popen2([self.cmd])
self.validate_output(self.teststr, self.expected, r, w)
w, r = os.popen2(["echo", self.teststr])
got = r.read()
self.assertEqual(got, self.teststr + "\n")
w, r = os.popen2(self.cmd)
self.validate_output(self.teststr, self.expected, r, w)
def test_os_popen3(self):
# same test as test_popen3(), but using the os.popen*() API
if os.name == 'posix':
w, r, e = os.popen3([self.cmd])
self.validate_output(self.teststr, self.expected, r, w, e)
w, r, e = os.popen3(["echo", self.teststr])
got = r.read()
self.assertEqual(got, self.teststr + "\n")
got = e.read()
self.assertFalse(got, "unexpected %r on stderr" % got)
w, r, e = os.popen3(self.cmd)
self.validate_output(self.teststr, self.expected, r, w, e)
def test_os_popen4(self):
if os.name == 'posix':
w, r = os.popen4([self.cmd])
self.validate_output(self.teststr, self.expected, r, w)
w, r = os.popen4(["echo", self.teststr])
got = r.read()
self.assertEqual(got, self.teststr + "\n")
w, r = os.popen4(self.cmd)
self.validate_output(self.teststr, self.expected, r, w)
def test_main():
run_unittest(Popen2Test)
if __name__ == "__main__":
test_main() |
<reference path='../resources/jest.d.ts'/>
<reference path='../dist/immutable.d.ts'/>
jest.autoMockOff();
import I = require('immutable');
describe('get', () => {
it('gets any index', () => {
var seq = I.Range(0, 100);
expect(seq.get(20)).toBe(20);
});
it('gets first', () => {
var seq = I.Range(0, 100);
expect(seq.first()).toBe(0);
});
it('gets last', () => {
var seq = I.Range(0, 100);
expect(seq.last()).toBe(99);
});
it('gets any index after reversing', () => {
var seq = I.Range(0, 100).reverse();
expect(seq.get(20)).toBe(79);
});
it('gets first after reversing', () => {
var seq = I.Range(0, 100).reverse();
expect(seq.first()).toBe(99);
});
it('gets last after reversing', () => {
var seq = I.Range(0, 100).reverse();
expect(seq.last()).toBe(0);
});
it('gets any index when size is unknown', () => {
var seq = I.Range(0, 100).filter(x => x % 2 === 1);
expect(seq.get(20)).toBe(41);
});
it('gets first when size is unknown', () => {
var seq = I.Range(0, 100).filter(x => x % 2 === 1);
expect(seq.first()).toBe(1);
});
it('gets last when size is unknown', () => {
var seq = I.Range(0, 100).filter(x => x % 2 === 1);
expect(seq.last()).toBe(99); // Note: this is O(N)
});
}); |
<!DOCTYPE html>
<html>
<head>
<script>
if (window.testRunner) {
testRunner.dumpAsText();
testRunner.waitUntilDone();
testRunner.<API key>(true);
}
</script>
</head>
<body>
<iframe src='http://localhost:8000/security/xssAuditor/resources/<API key>.html#%3Ca%20id%3D%22anchorLink%22%20href%3D%22%23%22%20onclick%3D%22alert%280%29%22%3EClick%3C/a%3E'>
</iframe>
</body>
</html> |
// From private/<API key>.idl,
// modified Tue Feb 18 18:03:36 2014.
#include "ppapi/c/<API key>.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/c/private/<API key>.h"
#include "ppapi/shared_impl/tracked_callback.h"
#include "ppapi/thunk/enter.h"
#include "ppapi/thunk/ppapi_thunk_export.h"
#include "ppapi/thunk/<API key>.h"
namespace ppapi {
namespace thunk {
namespace {
PP_Resource Create(PP_Instance instance) {
VLOG(4) << "<API key>::Create()";
<API key> enter(instance);
if (enter.failed())
return 0;
return enter.functions()-><API key>(instance);
}
PP_Bool <API key>(PP_Resource resource) {
VLOG(4) << "<API key>::<API key>()";
EnterResource<<API key>> enter(resource, false);
return PP_FromBool(enter.succeeded());
}
int32_t GetColorProfile(PP_Resource <API key>,
struct PP_ArrayOutput color_profile,
struct <API key> callback) {
VLOG(4) << "<API key>::GetColorProfile()";
EnterResource<<API key>> enter(<API key>,
callback,
true);
if (enter.failed())
return enter.retval();
return enter.SetResult(enter.object()->GetColorProfile(color_profile,
enter.callback()));
}
int32_t <API key>(
PP_Resource <API key>,
struct <API key> callback) {
VLOG(4) <<
"<API key>::<API key>()";
EnterResource<<API key>> enter(<API key>,
callback,
true);
if (enter.failed())
return enter.retval();
return enter.SetResult(enter.object()-><API key>(
enter.callback()));
}
const <API key>
<API key> = {
&Create,
&<API key>,
&GetColorProfile,
&<API key>
};
} // namespace
PPAPI_THUNK_EXPORT const <API key>*
<API key>() {
return &<API key>;
}
} // namespace thunk
} // namespace ppapi |
var chai = require('chai');
var expect = chai.expect;
var formatParamOutput = require('../index').utils.formatParamOutput;
describe('#formatParamOutput()', function() {
it('should correct return formatted string if all elements in array are strings', function() {
expect(formatParamOutput(['hey', 'yo', 'hello'])).to.equal('hey.yo.hello');
});
it('should return a string with integers in brackets', function() {
expect(formatParamOutput(['hey', 'yo', '0', 'hello'])).to.equal('hey.yo[0].hello');
expect(formatParamOutput(['hey', 'yo', 0, 'hello'])).to.equal('hey.yo[0].hello');
expect(formatParamOutput(['hey', 'yo', 0, 0, 'hello'])).to.equal('hey.yo[0][0].hello');
expect(formatParamOutput(['hey', 'yo', 2342342, 'hello'])).to.equal('hey.yo[2342342].hello');
expect(formatParamOutput(['hey', 'yo', '2342342', 'hello'])).to.equal('hey.yo[2342342].hello');
expect(formatParamOutput(['hey', 'yo', '234ALPHA2342', 'hello'])).to.not.equal('hey.yo[234ALPHA2342].hello');
expect(formatParamOutput(['hey', 'yo', 'hello', 0])).to.equal('hey.yo.hello[0]');
expect(formatParamOutput(['hey', 'yo', 'hello', 0, 0])).to.equal('hey.yo.hello[0][0]');
expect(formatParamOutput(['hey', 'yo', 0, 'hello', 0, 0])).to.equal('hey.yo[0].hello[0][0]');
});
it('should return the original param if not an array', function() {
expect(formatParamOutput('yo')).to.equal('yo');
});
}); |
module.exports = function(hljs) {
/* missing support for heredoc-like string (OCaml 4.0.2+) */
return {
aliases: ['ml'],
keywords: {
keyword:
'and as assert asr begin class constraint do done downto else end ' +
'exception external for fun function functor if in include ' +
'inherit! inherit initializer land lazy let lor lsl lsr lxor match method!|10 method ' +
'mod module mutable new object of open! open or private rec sig struct ' +
'then to try type val! val virtual when while with ' +
/* camlp4 */
'parser value',
built_in:
/* built-in types */
'array bool bytes char exn|5 float int int32 int64 list lazy_t|5 nativeint|5 string unit ' +
/* (some) types in Pervasives */
'in_channel out_channel ref',
literal:
'true false'
},
illegal: /\/\/|>>/,
lexemes: '[a-z_]\\w*!?',
contains: [
{
className: 'literal',
begin: '\\[(\\|\\|)?\\]|\\(\\)'
},
hljs.COMMENT(
'\\(\\*',
'\\*\\)',
{
contains: ['self']
}
),
{ /* type variable */
className: 'symbol',
begin: '\'[A-Za-z_](?!\')[\\w\']*'
/* the grammar is ambiguous on how 'a'b should be interpreted but not the compiler */
},
{ /* polymorphic variant */
className: 'tag',
begin: '`[A-Z][\\w\']*'
},
{ /* module or constructor */
className: 'type',
begin: '\\b[A-Z][\\w\']*',
relevance: 0
},
{ /* don't color identifiers, but safely catch all identifiers with '*/
begin: '[a-z_]\\w*\'[\\w\']*'
},
hljs.inherit(hljs.APOS_STRING_MODE, {className: 'char', relevance: 0}),
hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null}),
{
className: 'number',
begin:
'\\b(0[xX][a-fA-F0-9_]+[Lln]?|' +
'0[oO][0-7_]+[Lln]?|' +
'0[bB][01_]+[Lln]?|' +
'[0-9][0-9_]*([Lln]|(\\.[0-9_]*)?([eE][-+]?[0-9_]+)?)?)',
relevance: 0
},
{
begin: /[-=]>/ // relevance booster
}
]
}
}; |
/* <API key>: GPL-2.0 WITH Linux-syscall-note */
#ifndef <API key>
#define <API key>
#include <linux/types.h>
enum {
RDMA_NL_RDMA_CM = 1,
RDMA_NL_IWCM,
RDMA_NL_RSVD,
RDMA_NL_LS, /* RDMA Local Services */
RDMA_NL_NLDEV, /* RDMA device interface */
RDMA_NL_NUM_CLIENTS
};
enum {
RDMA_NL_GROUP_CM = 1,
RDMA_NL_GROUP_IWPM,
RDMA_NL_GROUP_LS,
RDMA_NL_NUM_GROUPS
};
#define RDMA_NL_GET_CLIENT(type) ((type & (((1 << 6) - 1) << 10)) >> 10)
#define RDMA_NL_GET_OP(type) (type & ((1 << 10) - 1))
#define RDMA_NL_GET_TYPE(client, op) ((client << 10) + op)
enum {
<API key> = 0,
<API key>
};
enum {
<API key> = 1,
<API key>,
<API key>,
};
/* iwarp port mapper op-codes */
enum {
<API key> = 0,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>
};
struct rdma_cm_id_stats {
__u32 qp_num;
__u32 bound_dev_if;
__u32 port_space;
__s32 pid;
__u8 cm_state;
__u8 node_type;
__u8 port_num;
__u8 qp_type;
};
enum {
<API key> = 0,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>
};
enum {
<API key> = 0,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>
};
enum {
<API key> = 0,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>
};
#define <API key> 3
#define <API key> 4
#define <API key> 3
enum {
<API key> = 0,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>
};
enum {
<API key> = 0,
<API key>,
<API key>,
<API key>
};
enum {
<API key> = 0,
<API key>,
<API key>,
<API key>
};
enum {
<API key> = 0,
<API key>,
<API key>,
<API key>,
<API key>
};
enum {
IWPM_NLA_ERR_UNSPEC = 0,
IWPM_NLA_ERR_SEQ,
IWPM_NLA_ERR_CODE,
IWPM_NLA_ERR_MAX
};
/*
* Local service operations:
* RESOLVE - The client requests the local service to resolve a path.
* SET_TIMEOUT - The local service requests the client to set the timeout.
* IP_RESOLVE - The client requests the local service to resolve an IP to GID.
*/
enum {
<API key> = 0,
<API key>,
<API key>,
RDMA_NL_LS_NUM_OPS
};
/* Local service netlink message flags */
#define RDMA_NL_LS_F_ERR 0x0100 /* Failed response */
/*
* Local service resolve operation family header.
* The layout for the resolve operation:
* nlmsg header
* family header
* attributes
*/
/*
* Local service path use:
* Specify how the path(s) will be used.
* ALL - For connected CM operation (6 pathrecords)
* UNIDIRECTIONAL - For unidirectional UD (1 pathrecord)
* GMP - For miscellaneous GMP like operation (at least 1 reversible
* pathrecord)
*/
enum {
<API key> = 0,
<API key>,
<API key>,
<API key>
};
#define LS_DEVICE_NAME_MAX 64
struct <API key> {
__u8 device_name[LS_DEVICE_NAME_MAX];
__u8 port_num;
__u8 path_use;
};
struct <API key> {
__u32 ifindex;
};
/* Local service attribute type */
#define <API key> (1 << 13)
#define RDMA_NLA_TYPE_MASK (~(NLA_F_NESTED | NLA_F_NET_BYTEORDER | \
<API key>))
enum {
LS_NLA_TYPE_UNSPEC = 0,
<API key>,
LS_NLA_TYPE_TIMEOUT,
<API key>,
LS_NLA_TYPE_DGID,
LS_NLA_TYPE_SGID,
LS_NLA_TYPE_TCLASS,
LS_NLA_TYPE_PKEY,
<API key>,
LS_NLA_TYPE_IPV4,
LS_NLA_TYPE_IPV6,
LS_NLA_TYPE_MAX
};
/* Local service DGID/SGID attribute: big endian */
struct rdma_nla_ls_gid {
__u8 gid[16];
};
enum rdma_nldev_command {
<API key>,
RDMA_NLDEV_CMD_GET, /* can dump */
RDMA_NLDEV_CMD_SET,
RDMA_NLDEV_CMD_NEW,
RDMA_NLDEV_CMD_DEL,
<API key>, /* can dump */
<API key>,
<API key>,
<API key>,
RDMA_NLDEV_NUM_OPS
};
enum rdma_nldev_attr {
/* don't change the order or add anything between, this is ABI! */
<API key>,
/* Identifier for ib_device */
<API key>, /* u32 */
<API key>, /* string */
/*
* Device index together with port index are identifiers
* for port/link properties.
*
* For RDMA_NLDEV_CMD_GET commamnd, port index will return number
* of available ports in ib_device, while for port specific operations,
* it will be real port index as it appears in sysfs. Port index follows
* sysfs notation and starts from 1 for the first port.
*/
<API key>, /* u32 */
/*
* Device and port capabilities
*/
<API key>, /* u64 */
/*
* FW version
*/
<API key>, /* string */
/*
* Node GUID (in host byte order) associated with the RDMA device.
*/
<API key>, /* u64 */
/*
* System image GUID (in host byte order) associated with
* this RDMA device and other devices which are part of a
* single system.
*/
<API key>, /* u64 */
/*
* Subnet prefix (in host byte order)
*/
<API key>, /* u64 */
/*
* Local Identifier (LID),
* According to IB specification, It is 16-bit address assigned
* by the Subnet Manager. Extended to be 32-bit for OmniPath users.
*/
RDMA_NLDEV_ATTR_LID, /* u32 */
<API key>, /* u32 */
/*
* LID mask control (LMC)
*/
RDMA_NLDEV_ATTR_LMC,
<API key>,
<API key>,
<API key>,
RDMA_NLDEV_ATTR_MAX
};
#endif /* <API key> */ |
<?php
/**
* @file
* Contains \Drupal\taxonomy\Controller\<API key>.
*/
namespace Drupal\taxonomy\Controller;
use Drupal\Component\Utility\Tags;
use Drupal\Component\Utility\Unicode;
use Drupal\Component\Utility\String;
use Drupal\Core\DependencyInjection\<API key>;
use Drupal\Core\Entity\<API key>;
use Drupal\Core\Entity\Query\QueryInterface;
use Drupal\taxonomy\VocabularyInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
* Returns autocomplete responses for taxonomy terms.
*/
class <API key> implements <API key> {
/**
* Taxonomy term entity query interface.
*
* @var \Drupal\Core\Entity\Query\QueryInterface
*/
protected $termEntityQuery;
/**
* Entity manager.
*
* @var \Drupal\Core\Entity\<API key>
*/
protected $entityManager;
/**
* Constructs a new \Drupal\taxonomy\Controller\<API key> object.
*
* @param \Drupal\Core\Entity\Query\QueryInterface $term_entity_query
* The entity query service.
* @param \Drupal\Core\Entity\<API key>
* The entity manager.
*/
public function __construct(QueryInterface $term_entity_query, <API key> $entity_manager) {
$this->termEntityQuery = $term_entity_query;
$this->entityManager = $entity_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity.query')->get('taxonomy_term'),
$container->get('entity.manager')
);
}
/**
* Retrieves suggestions for taxonomy term autocompletion.
*
* This function outputs term name suggestions in response to Ajax requests
* made by the taxonomy autocomplete widget for taxonomy term reference
* fields. The output is a JSON object of plain-text term suggestions, keyed
* by the user-entered value with the completed term name appended.
* Term names containing commas are wrapped in quotes.
*
* For example, suppose the user has entered the string 'red fish, blue' in
* the field, and there are two taxonomy terms, 'blue fish' and 'blue moon'.
* The JSON output would have the following structure:
* @code
* {
* "red fish, blue fish": "blue fish",
* "red fish, blue moon": "blue moon",
* };
* @endcode
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The request object.
* @param string $entity_type
* The entity_type.
* @param string $field_name
* The name of the term reference field.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response
* When valid field name is specified, a JSON response containing the
* autocomplete suggestions for taxonomy terms. Otherwise a normal response
* containing an error message.
*/
public function autocomplete(Request $request, $entity_type, $field_name) {
// A comma-separated list of term names entered in the autocomplete form
// element. Only the last term is used for autocompletion.
$tags_typed = $request->query->get('q');
// Make sure the field exists and is a taxonomy field.
$<API key> = $this->entityManager-><API key>($entity_type);
if (!isset($<API key>[$field_name]) || $<API key>[$field_name]->getType() !== '<API key>') {
// Error string. The JavaScript handler will realize this is not JSON and
// will display it as debugging information.
return new Response(t('Taxonomy field @field_name not found.', array('@field_name' => $field_name)), 403);
}
$field_storage = $<API key>[$field_name];
// The user enters a comma-separated list of tags. We only autocomplete the
// last tag.
$tags_typed = Tags::explode($tags_typed);
$tag_last = Unicode::strtolower(array_pop($tags_typed));
$matches = array();
if ($tag_last != '') {
// Part of the criteria for the query come from the field's own settings.
$vids = array();
foreach ($field_storage->getSetting('allowed_values') as $tree) {
$vids[] = $tree['vocabulary'];
}
$matches = $this->getMatchingTerms($tags_typed, $vids, $tag_last);
}
return new JsonResponse($matches);
}
/**
* Retrieves suggestions for taxonomy term autocompletion by vocabulary ID.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The request object.
* @param \Drupal\taxonomy\VocabularyInterface $taxonomy_vocabulary
* The vocabulary to filter by.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* A JSON response containing the autocomplete suggestions for taxonomy
* terms.
*/
public function autocompletePerVid(Request $request, VocabularyInterface $taxonomy_vocabulary) {
// A comma-separated list of term names entered in the autocomplete form
// element. Only the last term is used for autocompletion.
$tags_typed = $request->query->get('q');
$tags_typed = Tags::explode($tags_typed);
$tag_last = Unicode::strtolower(array_pop($tags_typed));
$matches = array();
if ($tag_last != '') {
$vids = array($taxonomy_vocabulary->id());
$matches = $this->getMatchingTerms($tags_typed, $vids, $tag_last);
}
return new JsonResponse($matches);
}
/**
* Gets terms which matches some typed terms.
*
* @param string $tags_typed
* The full typed tags string.
* @param array $vids
* An array of vocabulary IDs which
* @param $tag_last
* The lasted typed tag.
*
* @return array
* Returns an array of matching terms.
*/
protected function getMatchingTerms($tags_typed, array $vids, $tag_last) {
$matches = array();
$this->termEntityQuery->addTag('term_access');
// Do not select already entered terms.
if (!empty($tags_typed)) {
$this->termEntityQuery->condition('name', $tags_typed, 'NOT IN');
}
// Select rows that match by term name.
$tids = $this->termEntityQuery
->condition('vid', $vids, 'IN')
->condition('name', $tag_last, 'CONTAINS')
->range(0, 10)
->execute();
$prefix = count($tags_typed) ? Tags::implode($tags_typed) . ', ' : '';
if (!empty($tids)) {
$terms = $this->entityManager->getStorage('taxonomy_term')->loadMultiple(array_keys($tids));
foreach ($terms as $term) {
// Term names containing commas or quotes must be wrapped in quotes.
$name = Tags::encode($term->getName());
$matches[] = array('value' => $prefix . $name, 'label' => String::checkPlain($term->getName()));
}
return $matches;
}
return $matches;
}
} |
<html>
<head>
<title>Editors and Tools Supporting CTAGS</title>
</head>
<body>
<center>
<h1>Editors and Tools Supporting CTAGS</h1>
</center>
<h2>Editors</h2>
<ul>
<li>
<h3>Vi-style editors</h3>
<ul>
<li><a href="http:
Vim</a>, the official editor of <strong>Exuberant Ctags</strong></li>
<li><a href="http:
<li><a href="http:
a <strong>vi</strong> clone [Windows 95/NT].</li>
<li><a href="http:
Other <strong>vi</strong> clones</a></li>
</ul>
</li>
<li>
<h3>Other editors</h3>
<ul>
<li><a href="http:
<li><a href="http:
<li><a href="http:
<li><a href="http://software.jessies.org/evergreen/">Evergreen</a> [Unix, Windows, Mac OS X]</li>
<li><a href="http://fte.sourceforge.net">FTE (Folding Text Editor)</a> [Unix, Windows, MSDOS, OS/2]</li>
<li><a href="http:
<li><a href="http://space.mit.edu/~davis/jed">JED</a> [Unix, VMS, MSDOS, OS/2, BeOS, QNX, Windows]</li>
<li><a href="http:
<li><a href="http://towo.net/mined/">Mined</a> [Unix, DOS/Windows]</li>
<li><a href="http://nedit.org">NEdit (Nirvana Edit)</a>, a GUI editor [Unix with Motif]</li>
<li><a href="http://setedit.sourceforge.net/">SETEdit</a> [Unix, Windows, DOS, QNX]</li>
<li><a href="http:
<li><a href="http:
<li><a href="http://pages.infinit.net/micbel/">WorkSpace</a> [QNX]</li>
<li><a href="http:
<li><a href="http:
<li><a href="http:
<li><a href="http:
</ul>
</li>
</ul>
<h2>Tools</h2>
<ul>
<li><a href="http:
<li><a href="http:
<li><a href="http:
<li><a href="http://users.pandora.be/bdr/pub/cshow">CShow (greps C functions out of source code)</a></li>
<li><a href="http://code.google.com/p/dwoop/">Dreamweaver IDE</a> [Windows]</li>
<li><a href="http:
<li><a href="http:
<li><a href="http://guisearch.sourceforge.net">GUISearch</a> [Unix]</li>
<li><a href="http:
<li><a href="http://icomplete.sourceforge.net">IComplete</a></li>
<li><a href="http:
<li><a href="http://insenvim.sourceforge.net">Intellisense plugin for Vim</a></li>
<li><a href="http://sourceforge.net/projects/lxr">lxr</a> [Linux]</li>
<li><a href="http:
<li><a href="http://workspacewhiz.com">Workspace Whiz!</a> [Win32]</li>
<li><a href="http:
</ul>
<hr>
<a href="http:index.html">Back to <strong>Exuberant Ctags</strong></a>
</body>
</html>
<!-- vim:set et ts=2 sts=2 sw=2: --> |
/*
* aoeblk.c
* block device routines
*/
#include <linux/kernel.h>
#include <linux/hdreg.h>
#include <linux/blkdev.h>
#include <linux/backing-dev.h>
#include <linux/fs.h>
#include <linux/ioctl.h>
#include <linux/slab.h>
#include <linux/ratelimit.h>
#include <linux/genhd.h>
#include <linux/netdevice.h>
#include <linux/mutex.h>
#include <linux/export.h>
#include <linux/moduleparam.h>
#include <linux/debugfs.h>
#include <scsi/sg.h>
#include "aoe.h"
static DEFINE_MUTEX(aoeblk_mutex);
static struct kmem_cache *buf_pool_cache;
static struct dentry *aoe_debugfs_dir;
/* GPFS needs a larger value than the default. */
static int aoe_maxsectors;
module_param(aoe_maxsectors, int, 0644);
MODULE_PARM_DESC(aoe_maxsectors,
"When nonzero, set the maximum number of sectors per I/O request");
static ssize_t aoedisk_show_state(struct device *dev,
struct device_attribute *attr, char *page)
{
struct gendisk *disk = dev_to_disk(dev);
struct aoedev *d = disk->private_data;
return snprintf(page, PAGE_SIZE,
"%s%s\n",
(d->flags & DEVFL_UP) ? "up" : "down",
(d->flags & DEVFL_KICKME) ? ",kickme" :
(d->nopen && !(d->flags & DEVFL_UP)) ? ",closewait" : "");
/* I'd rather see nopen exported so we can ditch closewait */
}
static ssize_t aoedisk_show_mac(struct device *dev,
struct device_attribute *attr, char *page)
{
struct gendisk *disk = dev_to_disk(dev);
struct aoedev *d = disk->private_data;
struct aoetgt *t = d->targets[0];
if (t == NULL)
return snprintf(page, PAGE_SIZE, "none\n");
return snprintf(page, PAGE_SIZE, "%pm\n", t->addr);
}
static ssize_t aoedisk_show_netif(struct device *dev,
struct device_attribute *attr, char *page)
{
struct gendisk *disk = dev_to_disk(dev);
struct aoedev *d = disk->private_data;
struct net_device *nds[8], **nd, **nnd, **ne;
struct aoetgt **t, **te;
struct aoeif *ifp, *e;
char *p;
memset(nds, 0, sizeof nds);
nd = nds;
ne = nd + ARRAY_SIZE(nds);
t = d->targets;
te = t + d->ntargets;
for (; t < te && *t; t++) {
ifp = (*t)->ifs;
e = ifp + NAOEIFS;
for (; ifp < e && ifp->nd; ifp++) {
for (nnd = nds; nnd < nd; nnd++)
if (*nnd == ifp->nd)
break;
if (nnd == nd && nd != ne)
*nd++ = ifp->nd;
}
}
ne = nd;
nd = nds;
if (*nd == NULL)
return snprintf(page, PAGE_SIZE, "none\n");
for (p = page; nd < ne; nd++)
p += snprintf(p, PAGE_SIZE - (p-page), "%s%s",
p == page ? "" : ",", (*nd)->name);
p += snprintf(p, PAGE_SIZE - (p-page), "\n");
return p-page;
}
/* firmware version */
static ssize_t aoedisk_show_fwver(struct device *dev,
struct device_attribute *attr, char *page)
{
struct gendisk *disk = dev_to_disk(dev);
struct aoedev *d = disk->private_data;
return snprintf(page, PAGE_SIZE, "0x%04x\n", (unsigned int) d->fw_ver);
}
static ssize_t <API key>(struct device *dev,
struct device_attribute *attr, char *page)
{
struct gendisk *disk = dev_to_disk(dev);
struct aoedev *d = disk->private_data;
return snprintf(page, PAGE_SIZE, "%lu\n", d->maxbcnt);
}
static int <API key>(struct seq_file *s, void *ignored)
{
struct aoedev *d;
struct aoetgt **t, **te;
struct aoeif *ifp, *ife;
unsigned long flags;
char c;
d = s->private;
seq_printf(s, "rttavg: %d rttdev: %d\n",
d->rttavg >> RTTSCALE,
d->rttdev >> RTTDSCALE);
seq_printf(s, "nskbpool: %d\n", skb_queue_len(&d->skbpool));
seq_printf(s, "kicked: %ld\n", d->kicked);
seq_printf(s, "maxbcnt: %ld\n", d->maxbcnt);
seq_printf(s, "ref: %ld\n", d->ref);
spin_lock_irqsave(&d->lock, flags);
t = d->targets;
te = t + d->ntargets;
for (; t < te && *t; t++) {
c = '\t';
seq_printf(s, "falloc: %ld\n", (*t)->falloc);
seq_printf(s, "ffree: %p\n",
list_empty(&(*t)->ffree) ? NULL : (*t)->ffree.next);
seq_printf(s, "%pm:%d:%d:%d\n", (*t)->addr, (*t)->nout,
(*t)->maxout, (*t)->nframes);
seq_printf(s, "\tssthresh:%d\n", (*t)->ssthresh);
seq_printf(s, "\ttaint:%d\n", (*t)->taint);
seq_printf(s, "\tr:%d\n", (*t)->rpkts);
seq_printf(s, "\tw:%d\n", (*t)->wpkts);
ifp = (*t)->ifs;
ife = ifp + ARRAY_SIZE((*t)->ifs);
for (; ifp->nd && ifp < ife; ifp++) {
seq_printf(s, "%c%s", c, ifp->nd->name);
c = ',';
}
seq_puts(s, "\n");
}
<API key>(&d->lock, flags);
return 0;
}
static int aoe_debugfs_open(struct inode *inode, struct file *file)
{
return single_open(file, <API key>, inode->i_private);
}
static DEVICE_ATTR(state, 0444, aoedisk_show_state, NULL);
static DEVICE_ATTR(mac, 0444, aoedisk_show_mac, NULL);
static DEVICE_ATTR(netif, 0444, aoedisk_show_netif, NULL);
static struct device_attribute <API key> = {
.attr = { .name = "firmware-version", .mode = 0444 },
.show = aoedisk_show_fwver,
};
static DEVICE_ATTR(payload, 0444, <API key>, NULL);
static struct attribute *aoe_attrs[] = {
&dev_attr_state.attr,
&dev_attr_mac.attr,
&dev_attr_netif.attr,
&<API key>.attr,
&dev_attr_payload.attr,
NULL,
};
static const struct attribute_group attr_group = {
.attrs = aoe_attrs,
};
static const struct file_operations aoe_debugfs_fops = {
.open = aoe_debugfs_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static void
aoedisk_add_debugfs(struct aoedev *d)
{
struct dentry *entry;
char *p;
if (aoe_debugfs_dir == NULL)
return;
p = strchr(d->gd->disk_name, '/');
if (p == NULL)
p = d->gd->disk_name;
else
p++;
BUG_ON(*p == '\0');
entry = debugfs_create_file(p, 0444, aoe_debugfs_dir, d,
&aoe_debugfs_fops);
if (IS_ERR_OR_NULL(entry)) {
pr_info("aoe: cannot create debugfs file for %s\n",
d->gd->disk_name);
return;
}
BUG_ON(d->debugfs);
d->debugfs = entry;
}
void
aoedisk_rm_debugfs(struct aoedev *d)
{
debugfs_remove(d->debugfs);
d->debugfs = NULL;
}
static int
aoedisk_add_sysfs(struct aoedev *d)
{
return sysfs_create_group(&disk_to_dev(d->gd)->kobj, &attr_group);
}
void
aoedisk_rm_sysfs(struct aoedev *d)
{
sysfs_remove_group(&disk_to_dev(d->gd)->kobj, &attr_group);
}
static int
aoeblk_open(struct block_device *bdev, fmode_t mode)
{
struct aoedev *d = bdev->bd_disk->private_data;
ulong flags;
if (!virt_addr_valid(d)) {
pr_crit("aoe: invalid device pointer in %s\n",
__func__);
WARN_ON(1);
return -ENODEV;
}
if (!(d->flags & DEVFL_UP) || d->flags & DEVFL_TKILL)
return -ENODEV;
mutex_lock(&aoeblk_mutex);
spin_lock_irqsave(&d->lock, flags);
if (d->flags & DEVFL_UP && !(d->flags & DEVFL_TKILL)) {
d->nopen++;
<API key>(&d->lock, flags);
mutex_unlock(&aoeblk_mutex);
return 0;
}
<API key>(&d->lock, flags);
mutex_unlock(&aoeblk_mutex);
return -ENODEV;
}
static void
aoeblk_release(struct gendisk *disk, fmode_t mode)
{
struct aoedev *d = disk->private_data;
ulong flags;
spin_lock_irqsave(&d->lock, flags);
if (--d->nopen == 0) {
<API key>(&d->lock, flags);
aoecmd_cfg(d->aoemajor, d->aoeminor);
return;
}
<API key>(&d->lock, flags);
}
static void
aoeblk_request(struct request_queue *q)
{
struct aoedev *d;
struct request *rq;
d = q->queuedata;
if ((d->flags & DEVFL_UP) == 0) {
pr_info_ratelimited("aoe: device %ld.%d is not up\n",
d->aoemajor, d->aoeminor);
while ((rq = blk_peek_request(q))) {
blk_start_request(rq);
aoe_end_request(d, rq, 1);
}
return;
}
aoecmd_work(d);
}
static int
aoeblk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
{
struct aoedev *d = bdev->bd_disk->private_data;
if ((d->flags & DEVFL_UP) == 0) {
printk(KERN_ERR "aoe: disk not up\n");
return -ENODEV;
}
geo->cylinders = d->geo.cylinders;
geo->heads = d->geo.heads;
geo->sectors = d->geo.sectors;
return 0;
}
static int
aoeblk_ioctl(struct block_device *bdev, fmode_t mode, uint cmd, ulong arg)
{
struct aoedev *d;
if (!arg)
return -EINVAL;
d = bdev->bd_disk->private_data;
if ((d->flags & DEVFL_UP) == 0) {
pr_err("aoe: disk not up\n");
return -ENODEV;
}
if (cmd == HDIO_GET_IDENTITY) {
if (!copy_to_user((void __user *) arg, &d->ident,
sizeof(d->ident)))
return 0;
return -EFAULT;
}
/* udev calls scsi_id, which uses SG_IO, resulting in noise */
if (cmd != SG_IO)
pr_info("aoe: unknown ioctl 0x%x\n", cmd);
return -ENOTTY;
}
static const struct <API key> aoe_bdops = {
.open = aoeblk_open,
.release = aoeblk_release,
.ioctl = aoeblk_ioctl,
.getgeo = aoeblk_getgeo,
.owner = THIS_MODULE,
};
/* alloc_disk and add_disk can sleep */
void
aoeblk_gdalloc(void *vp)
{
struct aoedev *d = vp;
struct gendisk *gd;
mempool_t *mp;
struct request_queue *q;
enum { KB = 1024, MB = KB * KB, READ_AHEAD = 2 * MB, };
ulong flags;
int late = 0;
spin_lock_irqsave(&d->lock, flags);
if (d->flags & DEVFL_GDALLOC
&& !(d->flags & DEVFL_TKILL)
&& !(d->flags & DEVFL_GD_NOW))
d->flags |= DEVFL_GD_NOW;
else
late = 1;
<API key>(&d->lock, flags);
if (late)
return;
gd = alloc_disk(AOE_PARTITIONS);
if (gd == NULL) {
pr_err("aoe: cannot allocate disk structure for %ld.%d\n",
d->aoemajor, d->aoeminor);
goto err;
}
mp = mempool_create(MIN_BUFS, mempool_alloc_slab, mempool_free_slab,
buf_pool_cache);
if (mp == NULL) {
printk(KERN_ERR "aoe: cannot allocate bufpool for %ld.%d\n",
d->aoemajor, d->aoeminor);
goto err_disk;
}
q = blk_init_queue(aoeblk_request, &d->lock);
if (q == NULL) {
pr_err("aoe: cannot allocate block queue for %ld.%d\n",
d->aoemajor, d->aoeminor);
goto err_mempool;
}
spin_lock_irqsave(&d->lock, flags);
WARN_ON(!(d->flags & DEVFL_GD_NOW));
WARN_ON(!(d->flags & DEVFL_GDALLOC));
WARN_ON(d->flags & DEVFL_TKILL);
WARN_ON(d->gd);
WARN_ON(d->flags & DEVFL_UP);
<API key>(q, BLK_DEF_MAX_SECTORS);
q->backing_dev_info->name = "aoe";
q->backing_dev_info->ra_pages = READ_AHEAD / PAGE_SIZE;
d->bufpool = mp;
d->blkq = gd->queue = q;
q->queuedata = d;
d->gd = gd;
if (aoe_maxsectors)
<API key>(q, aoe_maxsectors);
gd->major = AOE_MAJOR;
gd->first_minor = d->sysminor;
gd->fops = &aoe_bdops;
gd->private_data = d;
set_capacity(gd, d->ssize);
snprintf(gd->disk_name, sizeof gd->disk_name, "etherd/e%ld.%d",
d->aoemajor, d->aoeminor);
d->flags &= ~DEVFL_GDALLOC;
d->flags |= DEVFL_UP;
<API key>(&d->lock, flags);
add_disk(gd);
aoedisk_add_sysfs(d);
aoedisk_add_debugfs(d);
spin_lock_irqsave(&d->lock, flags);
WARN_ON(!(d->flags & DEVFL_GD_NOW));
d->flags &= ~DEVFL_GD_NOW;
<API key>(&d->lock, flags);
return;
err_mempool:
mempool_destroy(mp);
err_disk:
put_disk(gd);
err:
spin_lock_irqsave(&d->lock, flags);
d->flags &= ~DEVFL_GD_NOW;
schedule_work(&d->work);
<API key>(&d->lock, flags);
}
void
aoeblk_exit(void)
{
<API key>(aoe_debugfs_dir);
aoe_debugfs_dir = NULL;
kmem_cache_destroy(buf_pool_cache);
}
int __init
aoeblk_init(void)
{
buf_pool_cache = kmem_cache_create("aoe_bufs",
sizeof(struct buf),
0, 0, NULL);
if (buf_pool_cache == NULL)
return -ENOMEM;
aoe_debugfs_dir = debugfs_create_dir("aoe", NULL);
if (IS_ERR_OR_NULL(aoe_debugfs_dir)) {
pr_info("aoe: cannot create debugfs directory\n");
aoe_debugfs_dir = NULL;
}
return 0;
} |
extern "C" void abort ();
__attribute__((noinline, noclone)) void
foo (int *&p, int *&q, int *&r, int n, int m)
{
int i, err, *s = r;
int sep = 1;
#pragma omp target map(to:sep)
sep = 0;
#pragma omp target data map(to:p[0:8])
{
/* For zero length array sections, p points to the start of
already mapped range, q to the end of it (with nothing mapped
after it), and r does not point to an mapped range. */
#pragma omp target map(alloc:p[:0]) map(to:q[:0]) map(from:r[:0]) private(i) map(from:err) firstprivate (s)
{
err = 0;
for (i = 0; i < 8; i++)
if (p[i] != i + 1)
err = 1;
if (sep)
{
if (q != (int *) 0 || r != (int *) 0)
err = 1;
}
else if (p + 8 != q || r != s)
err = 1;
}
if (err)
abort ();
/* Implicit mapping of pointers behaves the same way. */
#pragma omp target private(i) map(from:err) firstprivate (s)
{
err = 0;
for (i = 0; i < 8; i++)
if (p[i] != i + 1)
err = 1;
if (sep)
{
if (q != (int *) 0 || r != (int *) 0)
err = 1;
}
else if (p + 8 != q || r != s)
err = 1;
}
if (err)
abort ();
/* And zero-length array sections, though not known at compile
time, behave the same. */
#pragma omp target map(p[:n]) map(tofrom:q[:n]) map(alloc:r[:n]) private(i) map(from:err) firstprivate (s)
{
err = 0;
for (i = 0; i < 8; i++)
if (p[i] != i + 1)
err = 1;
if (sep)
{
if (q != (int *) 0 || r != (int *) 0)
err = 1;
}
else if (p + 8 != q || r != s)
err = 1;
}
if (err)
abort ();
/* Non-zero length array sections, though not known at compile,
behave differently. */
#pragma omp target map(p[:m]) map(tofrom:q[:m]) map(to:r[:m]) private(i) map(from:err)
{
err = 0;
for (i = 0; i < 8; i++)
if (p[i] != i + 1)
err = 1;
if (q[0] != 9 || r[0] != 10)
err = 1;
}
if (err)
abort ();
#pragma omp target data map(to:q[0:1])
{
/* For zero length array sections, p points to the start of
already mapped range, q points to the start of another one,
and r to the end of the second one. */
#pragma omp target map(to:p[:0]) map(from:q[:0]) map(tofrom:r[:0]) private(i) map(from:err)
{
err = 0;
for (i = 0; i < 8; i++)
if (p[i] != i + 1)
err = 1;
if (q[0] != 9)
err = 1;
else if (sep)
{
if (r != (int *) 0)
err = 1;
}
else if (r != q + 1)
err = 1;
}
if (err)
abort ();
/* Implicit mapping of pointers behaves the same way. */
#pragma omp target private(i) map(from:err)
{
err = 0;
for (i = 0; i < 8; i++)
if (p[i] != i + 1)
err = 1;
if (q[0] != 9)
err = 1;
else if (sep)
{
if (r != (int *) 0)
err = 1;
}
else if (r != q + 1)
err = 1;
}
if (err)
abort ();
/* And zero-length array sections, though not known at compile
time, behave the same. */
#pragma omp target map(p[:n]) map(alloc:q[:n]) map(from:r[:n]) private(i) map(from:err)
{
err = 0;
for (i = 0; i < 8; i++)
if (p[i] != i + 1)
err = 1;
if (q[0] != 9)
err = 1;
else if (sep)
{
if (r != (int *) 0)
err = 1;
}
else if (r != q + 1)
err = 1;
}
if (err)
abort ();
/* Non-zero length array sections, though not known at compile,
behave differently. */
#pragma omp target map(p[:m]) map(alloc:q[:m]) map(tofrom:r[:m]) private(i) map(from:err)
{
err = 0;
for (i = 0; i < 8; i++)
if (p[i] != i + 1)
err = 1;
if (q[0] != 9 || r[0] != 10)
err = 1;
}
if (err)
abort ();
}
}
}
int
main ()
{
int a[32], i;
for (i = 0; i < 32; i++)
a[i] = i;
int *p = a + 1, *q = a + 9, *r = a + 10;
foo (p, q, r, 0, 1);
return 0;
} |
<?php
/* This file is part of the Thelia package. */
/* email : dev@thelia.net */
/* file that was distributed with this source code. */
namespace Thelia\Core\Event\Product;
use Thelia\Model\Product;
class <API key> extends ProductEvent
{
protected $accessory_id;
public function __construct(Product $product, $accessory_id)
{
parent::__construct($product);
$this->accessory_id = $accessory_id;
}
public function getAccessoryId()
{
return $this->accessory_id;
}
public function setAccessoryId($accessory_id)
{
$this->accessory_id = $accessory_id;
}
} |
"""Tests for the system_log component.""" |
int
main (void)
{
return 0;
} |
<?php
/**
* Retrieve the author of the current post.
*
* @since 1.5
* @uses $authordata The current author's DB object.
* @uses apply_filters() Calls 'the_author' hook on the author display name.
*
* @param string $deprecated Deprecated.
* @return string The author's display name.
*/
function get_the_author($deprecated = '') {
global $authordata;
if ( !empty( $deprecated ) )
<API key>( __FUNCTION__, '2.1' );
return apply_filters('the_author', is_object($authordata) ? $authordata->display_name : null);
}
function the_author( $deprecated = '', $deprecated_echo = true ) {
if ( !empty( $deprecated ) )
<API key>( __FUNCTION__, '2.1' );
if ( $deprecated_echo !== true )
<API key>( __FUNCTION__, '1.5', __('Use <code>get_the_author()</code> instead if you do not want the value echoed.') );
if ( $deprecated_echo )
echo get_the_author();
return get_the_author();
}
/**
* Retrieve the author who last edited the current post.
*
* @since 2.8
* @uses $post The current post's DB object.
* @uses get_post_meta() Retrieves the ID of the author who last edited the current post.
* @uses get_userdata() Retrieves the author's DB object.
* @uses apply_filters() Calls 'the_modified_author' hook on the author display name.
* @return string The author's display name.
*/
function <API key>() {
global $post;
if ( $last_id = get_post_meta($post->ID, '_edit_last', true) ) {
$last_user = get_userdata($last_id);
return apply_filters('the_modified_author', $last_user->display_name);
}
}
/**
* Display the name of the author who last edited the current post.
*
* @since 2.8
* @see get_the_author()
* @return string The author's display name, from <API key>().
*/
function the_modified_author() {
echo <API key>();
}
function get_the_author_meta( $field = '', $user_id = false ) {
if ( ! $user_id ) {
global $authordata;
$user_id = isset( $authordata->ID ) ? $authordata->ID : 0;
} else {
$authordata = get_userdata( $user_id );
}
if ( in_array( $field, array( 'login', 'pass', 'nicename', 'email', 'url', 'registered', 'activation_key', 'status' ) ) )
$field = 'user_' . $field;
$value = isset( $authordata->$field ) ? $authordata->$field : '';
return apply_filters( 'get_the_author_' . $field, $value, $user_id );
}
function the_author_meta($field = '', $user_id = false) {
echo apply_filters('the_author_' . $field, get_the_author_meta($field, $user_id), $user_id);
}
/**
* Retrieve either author's link or author's name.
*
* If the author has a home page set, return an HTML link, otherwise just return the
* author's name.
*
* @uses get_the_author_meta()
* @uses get_the_author()
*/
function get_the_author_link() {
if ( get_the_author_meta('url') ) {
return '<a href="' . get_the_author_meta('url') . '" title="' . esc_attr( sprintf(__("Visit %s’s website"), get_the_author()) ) . '" rel="author external">' . get_the_author() . '</a>';
} else {
return get_the_author();
}
}
function the_author_link() {
echo get_the_author_link();
}
/**
* Retrieve the number of posts by the author of the current post.
*
* @since 1.5
* @uses $post The current post in the Loop's DB object.
* @uses count_user_posts()
* @return int The number of posts by the author.
*/
function <API key>() {
global $post;
return count_user_posts($post->post_author);
}
function the_author_posts() {
echo <API key>();
}
function <API key>($deprecated = '') {
if ( !empty( $deprecated ) )
<API key>( __FUNCTION__, '2.1' );
global $authordata;
if ( !is_object( $authordata ) )
return false;
$link = sprintf(
'<a href="%1$s" title="%2$s" rel="author">%3$s</a>',
<API key>( $authordata->ID, $authordata->user_nicename ),
esc_attr( sprintf( __( 'Posts by %s' ), get_the_author() ) ),
get_the_author()
);
echo apply_filters( '<API key>', $link );
}
/**
* Retrieve the URL to the author page for the user with the ID provided.
*
* @since 2.1.0
* @uses $wp_rewrite WP_Rewrite
* @return string The URL to the author's page.
*/
function <API key>($author_id, $author_nicename = '') {
global $wp_rewrite;
$auth_ID = (int) $author_id;
$link = $wp_rewrite-><API key>();
if ( empty($link) ) {
$file = home_url( '/' );
$link = $file . '?author=' . $auth_ID;
} else {
if ( '' == $author_nicename ) {
$user = get_userdata($author_id);
if ( !empty($user->user_nicename) )
$author_nicename = $user->user_nicename;
}
$link = str_replace('%author%', $author_nicename, $link);
$link = home_url( <API key>( $link ) );
}
$link = apply_filters('author_link', $link, $author_id, $author_nicename);
return $link;
}
function wp_list_authors($args = '') {
global $wpdb;
$defaults = array(
'orderby' => 'name', 'order' => 'ASC', 'number' => '',
'optioncount' => false, 'exclude_admin' => true,
'show_fullname' => false, 'hide_empty' => true,
'feed' => '', 'feed_image' => '', 'feed_type' => '', 'echo' => true,
'style' => 'list', 'html' => true
);
$args = wp_parse_args( $args, $defaults );
extract( $args, EXTR_SKIP );
$return = '';
$query_args = <API key>( $args, array( 'orderby', 'order', 'number' ) );
$query_args['fields'] = 'ids';
$authors = get_users( $query_args );
$author_count = array();
foreach ( (array) $wpdb->get_results("SELECT DISTINCT post_author, COUNT(ID) AS count FROM $wpdb->posts WHERE post_type = 'post' AND " . <API key>( 'post' ) . " GROUP BY post_author") as $row )
$author_count[$row->post_author] = $row->count;
foreach ( $authors as $author_id ) {
$author = get_userdata( $author_id );
if ( $exclude_admin && 'admin' == $author->display_name )
continue;
$posts = isset( $author_count[$author->ID] ) ? $author_count[$author->ID] : 0;
if ( !$posts && $hide_empty )
continue;
$link = '';
if ( $show_fullname && $author->first_name && $author->last_name )
$name = "$author->first_name $author->last_name";
else
$name = $author->display_name;
if ( !$html ) {
$return .= $name . ', ';
continue; // No need to go further to process HTML.
}
if ( 'list' == $style ) {
$return .= '<li>';
}
$link = '<a href="' . <API key>( $author->ID, $author->user_nicename ) . '" title="' . esc_attr( sprintf(__("Posts by %s"), $author->display_name) ) . '">' . $name . '</a>';
if ( !empty( $feed_image ) || !empty( $feed ) ) {
$link .= ' ';
if ( empty( $feed_image ) ) {
$link .= '(';
}
$link .= '<a href="' . <API key>( $author->ID ) . '"';
$alt = $title = '';
if ( !empty( $feed ) ) {
$title = ' title="' . esc_attr( $feed ) . '"';
$alt = ' alt="' . esc_attr( $feed ) . '"';
$name = $feed;
$link .= $title;
}
$link .= '>';
if ( !empty( $feed_image ) )
$link .= '<img src="' . esc_url( $feed_image ) . '" style="border: none;"' . $alt . $title . ' />';
else
$link .= $name;
$link .= '</a>';
if ( empty( $feed_image ) )
$link .= ')';
}
if ( $optioncount )
$link .= ' ('. $posts . ')';
$return .= $link;
$return .= ( 'list' == $style ) ? '</li>' : ', ';
}
$return = rtrim($return, ', ');
if ( !$echo )
return $return;
echo $return;
}
/**
* Does this site have more than one author
*
* Checks to see if more than one author has published posts.
*
* @since 3.2.0
* @return bool Whether or not we have more than one author
*/
function is_multi_author() {
global $wpdb;
if ( false === ( $is_multi_author = wp_cache_get('is_multi_author', 'posts') ) ) {
$rows = (array) $wpdb->get_col("SELECT DISTINCT post_author FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' LIMIT 2");
$is_multi_author = 1 < count( $rows ) ? 1 : 0;
wp_cache_set('is_multi_author', $is_multi_author, 'posts');
}
return apply_filters( 'is_multi_author', (bool) $is_multi_author );
}
/**
* Helper function to clear the cache for number of authors.
*
* @private
*/
function <API key>() {
wp_cache_delete('is_multi_author', 'posts');
}
add_action('<API key>', '<API key>'); |
require 'delegate'
require 'active_support/core_ext/string/strip'
module ActionDispatch
module Routing
class RouteWrapper < SimpleDelegator
def endpoint
rack_app ? rack_app.inspect : "#{controller}##{action}"
end
def constraints
requirements.except(:controller, :action)
end
def rack_app(app = self.app)
@rack_app ||= begin
class_name = app.class.name.to_s
if class_name == "ActionDispatch::Routing::Mapper::Constraints"
rack_app(app.app)
elsif ActionDispatch::Routing::Redirect === app || class_name !~ /^ActionDispatch::Routing/
app
end
end
end
def verb
super.source.gsub(/[$^]/, '')
end
def path
super.spec.to_s
end
def name
super.to_s
end
def regexp
__getobj__.path.to_regexp
end
def json_regexp
str = regexp.inspect.
sub('\\A' , '^').
sub('\\Z' , '$').
sub('\\z' , '$').
sub(/^\
sub(/\/[a-z]*$/ , '').
gsub(/\(\?
gsub(/\(\?-\w+:/ , '(').
gsub(/\s/ , '')
Regexp.new(str).source
end
def reqs
@reqs ||= begin
reqs = endpoint
reqs += " #{constraints.to_s}" unless constraints.empty?
reqs
end
end
def controller
requirements[:controller] || ':controller'
end
def action
requirements[:action] || ':action'
end
def internal?
controller.to_s =~ %r{\Arails/(info|welcome)} || path =~ %r{\A#{Rails.application.config.assets.prefix}\z}
end
def engine?
rack_app && rack_app.respond_to?(:routes)
end
end
# This class is just used for displaying route information when someone
# executes `rake routes` or looks at the RoutingError page.
# People should not use this class.
class RoutesInspector # :nodoc:
def initialize(routes)
@engines = {}
@routes = routes
end
def format(formatter, filter = nil)
routes_to_display = filter_routes(filter)
routes = collect_routes(routes_to_display)
if routes.none?
formatter.no_routes
return formatter.result
end
formatter.header routes
formatter.section routes
@engines.each do |name, engine_routes|
formatter.section_title "Routes for #{name}"
formatter.section engine_routes
end
formatter.result
end
private
def filter_routes(filter)
if filter
@routes.select { |route| route.defaults[:controller] == filter }
else
@routes
end
end
def collect_routes(routes)
routes.collect do |route|
RouteWrapper.new(route)
end.reject do |route|
route.internal?
end.collect do |route|
<API key>(route)
{ name: route.name,
verb: route.verb,
path: route.path,
reqs: route.reqs,
regexp: route.json_regexp }
end
end
def <API key>(route)
name = route.endpoint
return unless route.engine?
return if @engines[name]
routes = route.rack_app.routes
if routes.is_a?(ActionDispatch::Routing::RouteSet)
@engines[name] = collect_routes(routes.routes)
end
end
end
class ConsoleFormatter
def initialize
@buffer = []
end
def result
@buffer.join("\n")
end
def section_title(title)
@buffer << "\n#{title}:"
end
def section(routes)
@buffer << draw_section(routes)
end
def header(routes)
@buffer << draw_header(routes)
end
def no_routes
@buffer << <<-MESSAGE.strip_heredoc
You don't have any routes defined!
Please add some routes in config/routes.rb.
For more information about routes, see the Rails guide: http://guides.rubyonrails.org/routing.html.
MESSAGE
end
private
def draw_section(routes)
header_lengths = ['Prefix', 'Verb', 'URI Pattern'].map(&:length)
name_width, verb_width, path_width = widths(routes).zip(header_lengths).map(&:max)
routes.map do |r|
"#{r[:name].rjust(name_width)} #{r[:verb].ljust(verb_width)} #{r[:path].ljust(path_width)} #{r[:reqs]}"
end
end
def draw_header(routes)
name_width, verb_width, path_width = widths(routes)
"#{"Prefix".rjust(name_width)} #{"Verb".ljust(verb_width)} #{"URI Pattern".ljust(path_width)} Controller#Action"
end
def widths(routes)
[routes.map { |r| r[:name].length }.max || 0,
routes.map { |r| r[:verb].length }.max || 0,
routes.map { |r| r[:path].length }.max || 0]
end
end
class HtmlTableFormatter
def initialize(view)
@view = view
@buffer = []
end
def section_title(title)
@buffer << %(<tr><th colspan="4">#{title}</th></tr>)
end
def section(routes)
@buffer << @view.render(partial: "routes/route", collection: routes)
end
# the header is part of the HTML page, so we don't construct it here.
def header(routes)
end
def no_routes
@buffer << <<-MESSAGE.strip_heredoc
<p>You don't have any routes defined!</p>
<ul>
<li>Please add some routes in <tt>config/routes.rb</tt>.</li>
<li>
For more information about routes, please see the Rails guide
<a href="http://guides.rubyonrails.org/routing.html">Rails Routing from the Outside In</a>.
</li>
</ul>
MESSAGE
end
def result
@view.raw @view.render(layout: "routes/table") {
@view.raw @buffer.join("\n")
}
end
end
end
end |
// Use of this source code is governed by a MIT
package identicon
var (
// 4cos(0),cos(90),cos(180),cos(270)
cos = []float64{1, 0, -1, 0}
// 4sin(0),sin(90),sin(180),sin(270)
sin = []float64{0, 1, 0, -1}
)
// pointsx,yangle
// angle[0,1,2,3][090180270]
func rotate(points []float64, x, y float64, angle int) {
if angle < 0 || angle > 3 {
panic("rotate:angle0,1,2,3")
}
for i := 0; i < len(points); i += 2 {
px := points[i] - x
py := points[i+1] - y
points[i] = px*cos[angle] - py*sin[angle] + x
points[i+1] = px*sin[angle] + py*cos[angle] + y
}
}
// points
func pointInPolygon(x float64, y float64, points []float64) bool {
if len(points) < 8 {
return false
}
// - y>0(x>0 && y==0)
// - y<0(x<0 && y==0)
// y>0y<0
// 2==abs(r)
r := 0
x1, y1 := points[0], points[1]
prev := (y1 > y) || ((x1 > x) && (y1 == y))
for i := 2; i < len(points); i += 2 {
x2, y2 := points[i], points[i+1]
curr := (y2 > y) || ((x2 > x) && (y2 == y))
if curr == prev {
x1, y1 = x2, y2
continue
}
mul := (x1-x)*(y2-y) - (x2-x)*(y1-y)
if mul > 0 {
r++
} else if mul < 0 {
r
}
x1, y1 = x2, y2
prev = curr
}
return r == 2 || r == -2
} |
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.<API key>(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var context_1 = require("../context/context");
var logger_1 = require("../logger");
var columnController_1 = require("../columnController/columnController");
var column_1 = require("../entities/column");
var utils_1 = require("../utils");
var <API key> = require("../dragAndDrop/dragAndDropService");
var gridPanel_1 = require("../gridPanel/gridPanel");
var <API key> = require("../gridOptionsWrapper");
var <API key> = (function () {
function <API key>(pinned) {
this.needToMoveLeft = false;
this.needToMoveRight = false;
this.pinned = pinned;
this.centerContainer = !utils_1.Utils.exists(pinned);
}
<API key>.prototype.init = function () {
this.logger = this.loggerFactory.create('<API key>');
};
<API key>.prototype.onDragEnter = function (draggingEvent) {
// we do dummy drag, so make sure column appears in the right location when first placed
var columns = draggingEvent.dragSource.dragItem;
this.columnController.setColumnsVisible(columns, true);
this.columnController.setColumnsPinned(columns, this.pinned);
this.onDragging(draggingEvent, true);
};
<API key>.prototype.onDragLeave = function (draggingEvent) {
if (!this.gridOptionsWrapper.<API key>()) {
var columns = draggingEvent.dragSource.dragItem;
this.columnController.setColumnsVisible(columns, false);
}
this.<API key>();
};
<API key>.prototype.onDragStop = function () {
this.<API key>();
};
<API key>.prototype.adjustXForScroll = function (draggingEvent) {
if (this.centerContainer) {
return draggingEvent.x + this.gridPanel.<API key>();
}
else {
return draggingEvent.x;
}
};
<API key>.prototype.workOutNewIndex = function (displayedColumns, allColumns, dragColumn, direction, xAdjustedForScroll) {
if (direction === <API key>.DragAndDropService.DIRECTION_LEFT) {
return this.<API key>(displayedColumns, allColumns, dragColumn, xAdjustedForScroll);
}
else {
return this.<API key>(displayedColumns, allColumns, dragColumn, xAdjustedForScroll);
}
};
<API key>.prototype.<API key> = function (xAdjustedForScroll) {
if (this.centerContainer) {
// scroll if the mouse has gone outside the grid (or just outside the scrollable part if pinning)
// putting in 50 buffer, so even if user gets to edge of grid, a scroll will happen
var firstVisiblePixel = this.gridPanel.<API key>();
var lastVisiblePixel = firstVisiblePixel + this.gridPanel.getCenterWidth();
this.needToMoveLeft = xAdjustedForScroll < (firstVisiblePixel + 50);
this.needToMoveRight = xAdjustedForScroll > (lastVisiblePixel - 50);
if (this.needToMoveLeft || this.needToMoveRight) {
this.<API key>();
}
else {
this.<API key>();
}
}
};
<API key>.prototype.onDragging = function (draggingEvent, fromEnter) {
if (fromEnter === void 0) { fromEnter = false; }
this.lastDraggingEvent = draggingEvent;
// if moving up or down (ie not left or right) then do nothing
if (!draggingEvent.direction) {
return;
}
var xAdjustedForScroll = this.adjustXForScroll(draggingEvent);
// if the user is dragging into the panel, ie coming from the side panel into the main grid,
// we don't want to scroll the grid this time, it would appear like the table is jumping
// each time a column is dragged in.
if (!fromEnter) {
this.<API key>(xAdjustedForScroll);
}
var columnsToMove = draggingEvent.dragSource.dragItem;
this.attemptMoveColumns(columnsToMove, draggingEvent.direction, xAdjustedForScroll, fromEnter);
};
<API key>.prototype.attemptMoveColumns = function (allMovingColumns, dragDirection, xAdjustedForScroll, fromEnter) {
var displayedColumns = this.columnController.getDisplayedColumns(this.pinned);
var gridColumns = this.columnController.getAllGridColumns();
var draggingLeft = dragDirection === <API key>.DragAndDropService.DIRECTION_LEFT;
var draggingRight = dragDirection === <API key>.DragAndDropService.DIRECTION_RIGHT;
var dragColumn;
var <API key> = utils_1.Utils.filter(allMovingColumns, function (column) { return displayedColumns.indexOf(column) >= 0; });
// if dragging left, we want to use the left most column, ie move the left most column to
// under the mouse pointer
if (draggingLeft) {
dragColumn = <API key>[0];
}
else {
dragColumn = <API key>[<API key>.length - 1];
}
var newIndex = this.workOutNewIndex(displayedColumns, gridColumns, dragColumn, dragDirection, xAdjustedForScroll);
var oldIndex = gridColumns.indexOf(dragColumn);
// the two check below stop an error when the user grabs a group my a middle column, then
// it is possible the mouse pointer is to the right of a column while been dragged left.
// so we need to make sure that the mouse pointer is actually left of the left most column
// if moving left, and right of the right most column if moving right
// we check 'fromEnter' below so we move the column to the new spot if the mouse is coming from
// outside the grid, eg if the column is moving from side panel, mouse is moving left, then we should
// place the column to the RHS even if the mouse is moving left and the column is already on
// the LHS. otherwise we stick to the rule described above.
// only allow left drag if this column is moving left
if (!fromEnter && draggingLeft && newIndex >= oldIndex) {
return;
}
// only allow right drag if this column is moving right
if (!fromEnter && draggingRight && newIndex <= oldIndex) {
return;
}
// if moving right, the new index is the index of the right most column, so adjust to first column
if (draggingRight) {
newIndex = newIndex - allMovingColumns.length + 1;
}
this.columnController.moveColumns(allMovingColumns, newIndex);
};
<API key>.prototype.<API key> = function (displayedColumns, allColumns, dragColumn, x) {
var usedX = 0;
var leftColumn = null;
for (var i = 0; i < displayedColumns.length; i++) {
var currentColumn = displayedColumns[i];
if (currentColumn === dragColumn) {
continue;
}
usedX += currentColumn.getActualWidth();
if (usedX > x) {
break;
}
leftColumn = currentColumn;
}
var newIndex;
if (leftColumn) {
newIndex = allColumns.indexOf(leftColumn) + 1;
var oldIndex = allColumns.indexOf(dragColumn);
if (oldIndex < newIndex) {
newIndex
}
}
else {
newIndex = 0;
}
return newIndex;
};
<API key>.prototype.<API key> = function (displayedColumns, allColumns, dragColumnOrGroup, x) {
var dragColumn = dragColumnOrGroup;
var usedX = dragColumn.getActualWidth();
var leftColumn = null;
for (var i = 0; i < displayedColumns.length; i++) {
if (usedX > x) {
break;
}
var currentColumn = displayedColumns[i];
if (currentColumn === dragColumn) {
continue;
}
usedX += currentColumn.getActualWidth();
leftColumn = currentColumn;
}
var newIndex;
if (leftColumn) {
newIndex = allColumns.indexOf(leftColumn) + 1;
var oldIndex = allColumns.indexOf(dragColumn);
if (oldIndex < newIndex) {
newIndex
}
}
else {
newIndex = 0;
}
return newIndex;
};
<API key>.prototype.<API key> = function () {
if (!this.movingIntervalId) {
this.intervalCount = 0;
this.failedMoveAttempts = 0;
this.movingIntervalId = setInterval(this.moveInterval.bind(this), 100);
if (this.needToMoveLeft) {
this.dragAndDropService.setGhostIcon(<API key>.DragAndDropService.ICON_LEFT, true);
}
else {
this.dragAndDropService.setGhostIcon(<API key>.DragAndDropService.ICON_RIGHT, true);
}
}
};
<API key>.prototype.<API key> = function () {
if (this.moveInterval) {
clearInterval(this.movingIntervalId);
this.movingIntervalId = null;
this.dragAndDropService.setGhostIcon(<API key>.DragAndDropService.ICON_MOVE);
}
};
<API key>.prototype.moveInterval = function () {
var pixelsToMove;
this.intervalCount++;
pixelsToMove = 10 + (this.intervalCount * 5);
if (pixelsToMove > 100) {
pixelsToMove = 100;
}
var pixelsMoved;
if (this.needToMoveLeft) {
pixelsMoved = this.gridPanel.scrollHorizontally(-pixelsToMove);
}
else if (this.needToMoveRight) {
pixelsMoved = this.gridPanel.scrollHorizontally(pixelsToMove);
}
if (pixelsMoved !== 0) {
this.onDragging(this.lastDraggingEvent);
this.failedMoveAttempts = 0;
}
else {
this.failedMoveAttempts++;
this.dragAndDropService.setGhostIcon(<API key>.DragAndDropService.ICON_PINNED);
if (this.failedMoveAttempts > 7) {
var columns = this.lastDraggingEvent.dragSource.dragItem;
var pinType = this.needToMoveLeft ? column_1.Column.PINNED_LEFT : column_1.Column.PINNED_RIGHT;
this.columnController.setColumnsPinned(columns, pinType);
this.dragAndDropService.nudge();
}
}
};
__decorate([
context_1.Autowired('loggerFactory'),
__metadata('design:type', logger_1.LoggerFactory)
], <API key>.prototype, "loggerFactory", void 0);
__decorate([
context_1.Autowired('columnController'),
__metadata('design:type', columnController_1.ColumnController)
], <API key>.prototype, "columnController", void 0);
__decorate([
context_1.Autowired('gridPanel'),
__metadata('design:type', gridPanel_1.GridPanel)
], <API key>.prototype, "gridPanel", void 0);
__decorate([
context_1.Autowired('dragAndDropService'),
__metadata('design:type', <API key>.DragAndDropService)
], <API key>.prototype, "dragAndDropService", void 0);
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata('design:type', <API key>.GridOptionsWrapper)
], <API key>.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_1.PostConstruct,
__metadata('design:type', Function),
__metadata('design:paramtypes', []),
__metadata('design:returntype', void 0)
], <API key>.prototype, "init", null);
return <API key>;
})();
exports.<API key> = <API key>; |
// { dg-options "-std=gnu++11" }
// { dg-do compile }
// 2007-06-02 Paolo Carlini <pcarlini@suse.de>
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// with this library; see the file COPYING3. If not see
#include <type_traits>
#include <testsuite_tr1.h>
void test01()
{
using std::is_rvalue_reference;
using namespace __gnu_test;
static_assert(test_category<is_rvalue_reference, int&&>(true), "");
static_assert(test_category<is_rvalue_reference, ClassType&&>(true), "");
static_assert(test_category<is_rvalue_reference, int(&&)(int)>(true), "");
// Sanity check.
static_assert(test_category<is_rvalue_reference, int&>(false), "");
static_assert(test_category<is_rvalue_reference, ClassType>(false), "");
} |
#include "libgfortran.h"
#include <stdlib.h>
#include <assert.h>
#if defined (HAVE_GFC_LOGICAL_16)
extern void all_l16 (gfc_array_l16 * const restrict,
gfc_array_l1 * const restrict, const index_type * const restrict);
export_proto(all_l16);
void
all_l16 (gfc_array_l16 * const restrict retarray,
gfc_array_l1 * const restrict array,
const index_type * const restrict pdim)
{
index_type count[GFC_MAX_DIMENSIONS];
index_type extent[GFC_MAX_DIMENSIONS];
index_type sstride[GFC_MAX_DIMENSIONS];
index_type dstride[GFC_MAX_DIMENSIONS];
const GFC_LOGICAL_1 * restrict base;
GFC_LOGICAL_16 * restrict dest;
index_type rank;
index_type n;
index_type len;
index_type delta;
index_type dim;
int src_kind;
int continue_loop;
/* Make dim zero based to avoid confusion. */
dim = (*pdim) - 1;
rank = GFC_DESCRIPTOR_RANK (array) - 1;
src_kind = GFC_DESCRIPTOR_SIZE (array);
len = <API key>(array,dim);
if (len < 0)
len = 0;
delta = <API key>(array,dim);
for (n = 0; n < dim; n++)
{
sstride[n] = <API key>(array,n);
extent[n] = <API key>(array,n);
if (extent[n] < 0)
extent[n] = 0;
}
for (n = dim; n < rank; n++)
{
sstride[n] = <API key>(array,n + 1);
extent[n] = <API key>(array,n + 1);
if (extent[n] < 0)
extent[n] = 0;
}
if (retarray->base_addr == NULL)
{
size_t alloc_size, str;
for (n = 0; n < rank; n++)
{
if (n == 0)
str = 1;
else
str = <API key>(retarray,n-1) * extent[n-1];
GFC_DIMENSION_SET(retarray->dim[n], 0, extent[n] - 1, str);
}
retarray->offset = 0;
retarray->dtype = (array->dtype & ~GFC_DTYPE_RANK_MASK) | rank;
alloc_size = <API key>(retarray,rank-1) * extent[rank-1];
if (alloc_size == 0)
{
/* Make sure we have a zero-sized array. */
GFC_DIMENSION_SET(retarray->dim[0], 0, -1, 1);
return;
}
else
retarray->base_addr = xmallocarray (alloc_size, sizeof (GFC_LOGICAL_16));
}
else
{
if (rank != GFC_DESCRIPTOR_RANK (retarray))
runtime_error ("rank of return array incorrect in"
" ALL intrinsic: is %ld, should be %ld",
(long int) GFC_DESCRIPTOR_RANK (retarray),
(long int) rank);
if (unlikely (compile_options.bounds_check))
{
for (n=0; n < rank; n++)
{
index_type ret_extent;
ret_extent = <API key>(retarray,n);
if (extent[n] != ret_extent)
runtime_error ("Incorrect extent in return value of"
" ALL intrinsic in dimension %d:"
" is %ld, should be %ld", (int) n + 1,
(long int) ret_extent, (long int) extent[n]);
}
}
}
for (n = 0; n < rank; n++)
{
count[n] = 0;
dstride[n] = <API key>(retarray,n);
if (extent[n] <= 0)
return;
}
base = array->base_addr;
if (src_kind == 1 || src_kind == 2 || src_kind == 4 || src_kind == 8
#ifdef HAVE_GFC_LOGICAL_16
|| src_kind == 16
#endif
)
{
if (base)
base = GFOR_POINTER_TO_L1 (base, src_kind);
}
else
internal_error (NULL, "Funny sized logical array in ALL intrinsic");
dest = retarray->base_addr;
continue_loop = 1;
while (continue_loop)
{
const GFC_LOGICAL_1 * restrict src;
GFC_LOGICAL_16 result;
src = base;
{
/* Return true only if all the elements are set. */
result = 1;
if (len <= 0)
*dest = 1;
else
{
for (n = 0; n < len; n++, src += delta)
{
if (! *src)
{
result = 0;
break;
}
}
*dest = result;
}
}
/* Advance to the next element. */
count[0]++;
base += sstride[0];
dest += dstride[0];
n = 0;
while (count[n] == extent[n])
{
/* When we get to the end of a dimension, reset it and increment
the next dimension. */
count[n] = 0;
/* We could precalculate these products, but this is a less
frequently used path so probably not worth it. */
base -= sstride[n] * extent[n];
dest -= dstride[n] * extent[n];
n++;
if (n == rank)
{
/* Break out of the look. */
continue_loop = 0;
break;
}
else
{
count[n]++;
base += sstride[n];
dest += dstride[n];
}
}
}
}
#endif |
#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/param.h>
#include <linux/spinlock.h>
#include <linux/string.h>
#include "csr1212.h"
#include "ieee1394_types.h"
#include "hosts.h"
#include "ieee1394.h"
#include "highlevel.h"
#include "ieee1394_core.h"
/* Module Parameters */
/* this module parameter can be used to disable mapping of the FCP registers */
static int fcp = 1;
module_param(fcp, int, 0444);
MODULE_PARM_DESC(fcp, "Map FCP registers (default = 1, disable = 0).");
static struct csr1212_keyval *node_cap = NULL;
static void add_host(struct hpsb_host *host);
static void remove_host(struct hpsb_host *host);
static void host_reset(struct hpsb_host *host);
static int read_maps(struct hpsb_host *host, int nodeid, quadlet_t *buffer,
u64 addr, size_t length, u16 fl);
static int write_fcp(struct hpsb_host *host, int nodeid, int dest,
quadlet_t *data, u64 addr, size_t length, u16 flags);
static int read_regs(struct hpsb_host *host, int nodeid, quadlet_t *buf,
u64 addr, size_t length, u16 flags);
static int write_regs(struct hpsb_host *host, int nodeid, int destid,
quadlet_t *data, u64 addr, size_t length, u16 flags);
static int lock_regs(struct hpsb_host *host, int nodeid, quadlet_t *store,
u64 addr, quadlet_t data, quadlet_t arg, int extcode, u16 fl);
static int lock64_regs(struct hpsb_host *host, int nodeid, octlet_t * store,
u64 addr, octlet_t data, octlet_t arg, int extcode, u16 fl);
static int read_config_rom(struct hpsb_host *host, int nodeid, quadlet_t *buffer,
u64 addr, size_t length, u16 fl);
static u64 allocate_addr_range(u64 size, u32 alignment, void *__host);
static void release_addr_range(u64 addr, void *__host);
static struct hpsb_highlevel csr_highlevel = {
.name = "standard registers",
.add_host = add_host,
.remove_host = remove_host,
.host_reset = host_reset,
};
static struct hpsb_address_ops map_ops = {
.read = read_maps,
};
static struct hpsb_address_ops fcp_ops = {
.write = write_fcp,
};
static struct hpsb_address_ops reg_ops = {
.read = read_regs,
.write = write_regs,
.lock = lock_regs,
.lock64 = lock64_regs,
};
static struct hpsb_address_ops config_rom_ops = {
.read = read_config_rom,
};
struct csr1212_bus_ops csr_bus_ops = {
.allocate_addr_range = allocate_addr_range,
.release_addr = release_addr_range,
};
static u16 csr_crc16(unsigned *data, int length)
{
int check=0, i;
int shift, sum, next=0;
for (i = length; i; i
for (next = check, shift = 28; shift >= 0; shift -= 4 ) {
sum = ((next >> 12) ^ (be32_to_cpu(*data) >> shift)) & 0xf;
next = (next << 4) ^ (sum << 12) ^ (sum << 5) ^ (sum);
}
check = next & 0xffff;
data++;
}
return check;
}
static void host_reset(struct hpsb_host *host)
{
host->csr.state &= 0x300;
host->csr.bus_manager_id = 0x3f;
host->csr.bandwidth_available = 4915;
host->csr.<API key> = 0xfffffffe; /* pre-alloc ch 31 per 1394a-2000 */
host->csr.<API key> = ~0;
host->csr.broadcast_channel = 0x80000000 | 31;
if (host->is_irm) {
if (host->driver->hw_csr_reg) {
host->driver->hw_csr_reg(host, 2, 0xfffffffe, ~0);
}
}
host->csr.node_ids = host->node_id << 16;
if (!host->is_root) {
/* clear cmstr bit */
host->csr.state &= ~0x100;
}
be32_add_cpu(&host->csr.topology_map[1], 1);
host->csr.topology_map[2] = cpu_to_be32(host->node_count << 16
| host->selfid_count);
host->csr.topology_map[0] =
cpu_to_be32((host->selfid_count + 2) << 16
| csr_crc16(host->csr.topology_map + 1,
host->selfid_count + 2));
be32_add_cpu(&host->csr.speed_map[1], 1);
host->csr.speed_map[0] = cpu_to_be32(0x3f1 << 16
| csr_crc16(host->csr.speed_map+1,
0x3f1));
}
/*
* HI == seconds (bits 0:2)
* LO == fractions of a second in units of 125usec (bits 19:31)
*
* Convert SPLIT_TIMEOUT to jiffies.
* The default and minimum as per 1394a-2000 clause 8.3.2.2.6 is 100ms.
*/
static inline void calculate_expire(struct csr_control *csr)
{
unsigned int usecs = (csr->split_timeout_hi & 7) * 1000000 +
(csr->split_timeout_lo >> 19) * 125;
csr->expire = usecs_to_jiffies(usecs > 100000 ? usecs : 100000);
HPSB_VERBOSE("CSR: setting expire to %lu, HZ=%u", csr->expire, HZ);
}
static void add_host(struct hpsb_host *host)
{
struct csr1212_keyval *root;
quadlet_t bus_info[CSR_BUS_INFO_SIZE];
<API key>(&csr_highlevel, host, ®_ops,
CSR_REGISTER_BASE,
CSR_REGISTER_BASE + CSR_CONFIG_ROM);
<API key>(&csr_highlevel, host, &config_rom_ops,
CSR_REGISTER_BASE + CSR_CONFIG_ROM,
CSR_REGISTER_BASE + CSR_CONFIG_ROM_END);
if (fcp) {
<API key>(&csr_highlevel, host, &fcp_ops,
CSR_REGISTER_BASE + CSR_FCP_COMMAND,
CSR_REGISTER_BASE + CSR_FCP_END);
}
<API key>(&csr_highlevel, host, &map_ops,
CSR_REGISTER_BASE + CSR_TOPOLOGY_MAP,
CSR_REGISTER_BASE + <API key>);
<API key>(&csr_highlevel, host, &map_ops,
CSR_REGISTER_BASE + CSR_SPEED_MAP,
CSR_REGISTER_BASE + CSR_SPEED_MAP_END);
spin_lock_init(&host->csr.lock);
host->csr.state = 0;
host->csr.node_ids = 0;
host->csr.split_timeout_hi = 0;
host->csr.split_timeout_lo = 800 << 19;
calculate_expire(&host->csr);
host->csr.cycle_time = 0;
host->csr.bus_time = 0;
host->csr.bus_manager_id = 0x3f;
host->csr.bandwidth_available = 4915;
host->csr.<API key> = 0xfffffffe; /* pre-alloc ch 31 per 1394a-2000 */
host->csr.<API key> = ~0;
host->csr.broadcast_channel = 0x80000000 | 31;
if (host->is_irm) {
if (host->driver->hw_csr_reg) {
host->driver->hw_csr_reg(host, 2, 0xfffffffe, ~0);
}
}
if (host->csr.max_rec >= 9)
host->csr.max_rom = 2;
else if (host->csr.max_rec >= 5)
host->csr.max_rom = 1;
else
host->csr.max_rom = 0;
host->csr.generation = 2;
bus_info[1] = <API key>(0x31333934);
bus_info[2] = cpu_to_be32((hpsb_disable_irm ? 0 : 1 << CSR_IRMC_SHIFT) |
(1 << CSR_CMC_SHIFT) |
(1 << CSR_ISC_SHIFT) |
(0 << CSR_BMC_SHIFT) |
(0 << CSR_PMC_SHIFT) |
(host->csr.cyc_clk_acc << <API key>) |
(host->csr.max_rec << CSR_MAX_REC_SHIFT) |
(host->csr.max_rom << CSR_MAX_ROM_SHIFT) |
(host->csr.generation << <API key>) |
host->csr.lnk_spd);
bus_info[3] = cpu_to_be32(host->csr.guid_hi);
bus_info[4] = cpu_to_be32(host->csr.guid_lo);
/* The hardware copy of the bus info block will be set later when a
* bus reset is issued. */
<API key>(host->csr.rom, bus_info, host->csr.max_rom);
root = host->csr.rom->root_kv;
if(<API key>(root, node_cap) != CSR1212_SUCCESS) {
HPSB_ERR("Failed to attach Node Capabilities to root directory");
}
host->update_config_rom = 1;
}
static void remove_host(struct hpsb_host *host)
{
quadlet_t bus_info[CSR_BUS_INFO_SIZE];
bus_info[1] = <API key>(0x31333934);
bus_info[2] = cpu_to_be32((0 << CSR_IRMC_SHIFT) |
(0 << CSR_CMC_SHIFT) |
(0 << CSR_ISC_SHIFT) |
(0 << CSR_BMC_SHIFT) |
(0 << CSR_PMC_SHIFT) |
(host->csr.cyc_clk_acc << <API key>) |
(host->csr.max_rec << CSR_MAX_REC_SHIFT) |
(0 << CSR_MAX_ROM_SHIFT) |
(0 << <API key>) |
host->csr.lnk_spd);
bus_info[3] = cpu_to_be32(host->csr.guid_hi);
bus_info[4] = cpu_to_be32(host->csr.guid_lo);
<API key>(host->csr.rom->root_kv, node_cap);
<API key>(host->csr.rom, bus_info, 0);
host->update_config_rom = 1;
}
int <API key>(struct hpsb_host *host, const quadlet_t *new_rom,
size_t buffersize, unsigned char rom_version)
{
unsigned long flags;
int ret;
HPSB_NOTICE("<API key>() is deprecated");
spin_lock_irqsave(&host->csr.lock, flags);
if (rom_version != host->csr.generation)
ret = -1;
else if (buffersize > host->csr.rom->cache_head->size)
ret = -2;
else {
/* Just overwrite the generated ConfigROM image with new data,
* it can be regenerated later. */
memcpy(host->csr.rom->cache_head->data, new_rom, buffersize);
host->csr.rom->cache_head->len = buffersize;
if (host->driver->set_hw_config_rom)
host->driver->set_hw_config_rom(host, host->csr.rom->bus_info_data);
/* Increment the generation number to keep some sort of sync
* with the newer ConfigROM manipulation method. */
host->csr.generation++;
if (host->csr.generation > 0xf || host->csr.generation < 2)
host->csr.generation = 2;
ret=0;
}
<API key>(&host->csr.lock, flags);
return ret;
}
/* Read topology / speed maps and configuration ROM */
static int read_maps(struct hpsb_host *host, int nodeid, quadlet_t *buffer,
u64 addr, size_t length, u16 fl)
{
unsigned long flags;
int csraddr = addr - CSR_REGISTER_BASE;
const char *src;
spin_lock_irqsave(&host->csr.lock, flags);
if (csraddr < CSR_SPEED_MAP) {
src = ((char *)host->csr.topology_map) + csraddr
- CSR_TOPOLOGY_MAP;
} else {
src = ((char *)host->csr.speed_map) + csraddr - CSR_SPEED_MAP;
}
memcpy(buffer, src, length);
<API key>(&host->csr.lock, flags);
return RCODE_COMPLETE;
}
#define out if (--length == 0) break
static int read_regs(struct hpsb_host *host, int nodeid, quadlet_t *buf,
u64 addr, size_t length, u16 flags)
{
int csraddr = addr - CSR_REGISTER_BASE;
int oldcycle;
quadlet_t ret;
if ((csraddr | length) & 0x3)
return RCODE_TYPE_ERROR;
length /= 4;
switch (csraddr) {
case CSR_STATE_CLEAR:
*(buf++) = cpu_to_be32(host->csr.state);
out;
case CSR_STATE_SET:
*(buf++) = cpu_to_be32(host->csr.state);
out;
case CSR_NODE_IDS:
*(buf++) = cpu_to_be32(host->csr.node_ids);
out;
case CSR_RESET_START:
return RCODE_TYPE_ERROR;
/* address gap - handled by default below */
case <API key>:
*(buf++) = cpu_to_be32(host->csr.split_timeout_hi);
out;
case <API key>:
*(buf++) = cpu_to_be32(host->csr.split_timeout_lo);
out;
/* address gap */
return RCODE_ADDRESS_ERROR;
case CSR_CYCLE_TIME:
oldcycle = host->csr.cycle_time;
host->csr.cycle_time =
host->driver->devctl(host, GET_CYCLE_COUNTER, 0);
if (oldcycle > host->csr.cycle_time) {
/* cycle time wrapped around */
host->csr.bus_time += 1 << 7;
}
*(buf++) = cpu_to_be32(host->csr.cycle_time);
out;
case CSR_BUS_TIME:
oldcycle = host->csr.cycle_time;
host->csr.cycle_time =
host->driver->devctl(host, GET_CYCLE_COUNTER, 0);
if (oldcycle > host->csr.cycle_time) {
/* cycle time wrapped around */
host->csr.bus_time += (1 << 7);
}
*(buf++) = cpu_to_be32(host->csr.bus_time
| (host->csr.cycle_time >> 25));
out;
/* address gap */
return RCODE_ADDRESS_ERROR;
case CSR_BUSY_TIMEOUT:
/* not yet implemented */
return RCODE_ADDRESS_ERROR;
case CSR_BUS_MANAGER_ID:
if (host->driver->hw_csr_reg)
ret = host->driver->hw_csr_reg(host, 0, 0, 0);
else
ret = host->csr.bus_manager_id;
*(buf++) = cpu_to_be32(ret);
out;
case <API key>:
if (host->driver->hw_csr_reg)
ret = host->driver->hw_csr_reg(host, 1, 0, 0);
else
ret = host->csr.bandwidth_available;
*(buf++) = cpu_to_be32(ret);
out;
case <API key>:
if (host->driver->hw_csr_reg)
ret = host->driver->hw_csr_reg(host, 2, 0, 0);
else
ret = host->csr.<API key>;
*(buf++) = cpu_to_be32(ret);
out;
case <API key>:
if (host->driver->hw_csr_reg)
ret = host->driver->hw_csr_reg(host, 3, 0, 0);
else
ret = host->csr.<API key>;
*(buf++) = cpu_to_be32(ret);
out;
case <API key>:
*(buf++) = cpu_to_be32(host->csr.broadcast_channel);
out;
/* address gap to end - fall through to default */
default:
return RCODE_ADDRESS_ERROR;
}
return RCODE_COMPLETE;
}
static int write_regs(struct hpsb_host *host, int nodeid, int destid,
quadlet_t *data, u64 addr, size_t length, u16 flags)
{
int csraddr = addr - CSR_REGISTER_BASE;
if ((csraddr | length) & 0x3)
return RCODE_TYPE_ERROR;
length /= 4;
switch (csraddr) {
case CSR_STATE_CLEAR:
/* FIXME FIXME FIXME */
printk("doh, someone wants to mess with state clear\n");
out;
case CSR_STATE_SET:
printk("doh, someone wants to mess with state set\n");
out;
case CSR_NODE_IDS:
host->csr.node_ids &= NODE_MASK << 16;
host->csr.node_ids |= be32_to_cpu(*(data++)) & (BUS_MASK << 16);
host->node_id = host->csr.node_ids >> 16;
host->driver->devctl(host, SET_BUS_ID, host->node_id >> 6);
out;
case CSR_RESET_START:
/* FIXME - perform command reset */
out;
/* address gap */
return RCODE_ADDRESS_ERROR;
case <API key>:
host->csr.split_timeout_hi =
be32_to_cpu(*(data++)) & 0x00000007;
calculate_expire(&host->csr);
out;
case <API key>:
host->csr.split_timeout_lo =
be32_to_cpu(*(data++)) & 0xfff80000;
calculate_expire(&host->csr);
out;
/* address gap */
return RCODE_ADDRESS_ERROR;
case CSR_CYCLE_TIME:
/* should only be set by cycle start packet, automatically */
host->csr.cycle_time = be32_to_cpu(*data);
host->driver->devctl(host, SET_CYCLE_COUNTER,
be32_to_cpu(*(data++)));
out;
case CSR_BUS_TIME:
host->csr.bus_time = be32_to_cpu(*(data++)) & 0xffffff80;
out;
/* address gap */
return RCODE_ADDRESS_ERROR;
case CSR_BUSY_TIMEOUT:
/* not yet implemented */
return RCODE_ADDRESS_ERROR;
case CSR_BUS_MANAGER_ID:
case <API key>:
case <API key>:
case <API key>:
/* these are not writable, only lockable */
return RCODE_TYPE_ERROR;
case <API key>:
/* only the valid bit can be written */
host->csr.broadcast_channel = (host->csr.broadcast_channel & ~0x40000000)
| (be32_to_cpu(*data) & 0x40000000);
out;
/* address gap to end - fall through */
default:
return RCODE_ADDRESS_ERROR;
}
return RCODE_COMPLETE;
}
#undef out
static int lock_regs(struct hpsb_host *host, int nodeid, quadlet_t *store,
u64 addr, quadlet_t data, quadlet_t arg, int extcode, u16 fl)
{
int csraddr = addr - CSR_REGISTER_BASE;
unsigned long flags;
quadlet_t *regptr = NULL;
if (csraddr & 0x3)
return RCODE_TYPE_ERROR;
if (csraddr < CSR_BUS_MANAGER_ID || csraddr > <API key>
|| extcode != <API key>)
goto unsupported_lockreq;
data = be32_to_cpu(data);
arg = be32_to_cpu(arg);
/* Is somebody releasing the broadcast_channel on us? */
if (csraddr == <API key> && (data & 0x1)) {
/* Note: this is may not be the right way to handle
* the problem, so we should look into the proper way
* eventually. */
HPSB_WARN("Node [" NODE_BUS_FMT "] wants to release "
"broadcast channel 31. Ignoring.",
NODE_BUS_ARGS(host, nodeid));
data &= ~0x1; /* keep broadcast channel allocated */
}
if (host->driver->hw_csr_reg) {
quadlet_t old;
old = host->driver->
hw_csr_reg(host, (csraddr - CSR_BUS_MANAGER_ID) >> 2,
data, arg);
*store = cpu_to_be32(old);
return RCODE_COMPLETE;
}
spin_lock_irqsave(&host->csr.lock, flags);
switch (csraddr) {
case CSR_BUS_MANAGER_ID:
regptr = &host->csr.bus_manager_id;
*store = cpu_to_be32(*regptr);
if (*regptr == arg)
*regptr = data;
break;
case <API key>:
{
quadlet_t bandwidth;
quadlet_t old;
quadlet_t new;
regptr = &host->csr.bandwidth_available;
old = *regptr;
/* bandwidth available algorithm adapted from IEEE 1394a-2000 spec */
if (arg > 0x1fff) {
*store = cpu_to_be32(old); /* change nothing */
break;
}
data &= 0x1fff;
if (arg >= data) {
/* allocate bandwidth */
bandwidth = arg - data;
if (old >= bandwidth) {
new = old - bandwidth;
*store = cpu_to_be32(arg);
*regptr = new;
} else {
*store = cpu_to_be32(old);
}
} else {
/* deallocate bandwidth */
bandwidth = data - arg;
if (old + bandwidth < 0x2000) {
new = old + bandwidth;
*store = cpu_to_be32(arg);
*regptr = new;
} else {
*store = cpu_to_be32(old);
}
}
break;
}
case <API key>:
{
/* Lock algorithm for CHANNELS_AVAILABLE as recommended by 1394a-2000 */
quadlet_t affected_channels = arg ^ data;
regptr = &host->csr.<API key>;
if ((arg & affected_channels) == (*regptr & affected_channels)) {
*regptr ^= affected_channels;
*store = cpu_to_be32(arg);
} else {
*store = cpu_to_be32(*regptr);
}
break;
}
case <API key>:
{
/* Lock algorithm for CHANNELS_AVAILABLE as recommended by 1394a-2000 */
quadlet_t affected_channels = arg ^ data;
regptr = &host->csr.<API key>;
if ((arg & affected_channels) == (*regptr & affected_channels)) {
*regptr ^= affected_channels;
*store = cpu_to_be32(arg);
} else {
*store = cpu_to_be32(*regptr);
}
break;
}
}
<API key>(&host->csr.lock, flags);
return RCODE_COMPLETE;
unsupported_lockreq:
switch (csraddr) {
case CSR_STATE_CLEAR:
case CSR_STATE_SET:
case CSR_RESET_START:
case CSR_NODE_IDS:
case <API key>:
case <API key>:
case CSR_CYCLE_TIME:
case CSR_BUS_TIME:
case <API key>:
return RCODE_TYPE_ERROR;
case CSR_BUSY_TIMEOUT:
/* not yet implemented - fall through */
default:
return RCODE_ADDRESS_ERROR;
}
}
static int lock64_regs(struct hpsb_host *host, int nodeid, octlet_t * store,
u64 addr, octlet_t data, octlet_t arg, int extcode, u16 fl)
{
int csraddr = addr - CSR_REGISTER_BASE;
unsigned long flags;
data = be64_to_cpu(data);
arg = be64_to_cpu(arg);
if (csraddr & 0x3)
return RCODE_TYPE_ERROR;
if (csraddr != <API key>
|| extcode != <API key>)
goto <API key>;
/* Is somebody releasing the broadcast_channel on us? */
if (csraddr == <API key> && (data & 0x100000000ULL)) {
/* Note: this is may not be the right way to handle
* the problem, so we should look into the proper way
* eventually. */
HPSB_WARN("Node [" NODE_BUS_FMT "] wants to release "
"broadcast channel 31. Ignoring.",
NODE_BUS_ARGS(host, nodeid));
data &= ~0x100000000ULL; /* keep broadcast channel allocated */
}
if (host->driver->hw_csr_reg) {
quadlet_t data_hi, data_lo;
quadlet_t arg_hi, arg_lo;
quadlet_t old_hi, old_lo;
data_hi = data >> 32;
data_lo = data & 0xFFFFFFFF;
arg_hi = arg >> 32;
arg_lo = arg & 0xFFFFFFFF;
old_hi = host->driver->hw_csr_reg(host, (csraddr - CSR_BUS_MANAGER_ID) >> 2,
data_hi, arg_hi);
old_lo = host->driver->hw_csr_reg(host, ((csraddr + 4) - CSR_BUS_MANAGER_ID) >> 2,
data_lo, arg_lo);
*store = cpu_to_be64(((octlet_t)old_hi << 32) | old_lo);
} else {
octlet_t old;
octlet_t affected_channels = arg ^ data;
spin_lock_irqsave(&host->csr.lock, flags);
old = ((octlet_t)host->csr.<API key> << 32) | host->csr.<API key>;
if ((arg & affected_channels) == (old & affected_channels)) {
host->csr.<API key> ^= (affected_channels >> 32);
host->csr.<API key> ^= (affected_channels & 0xffffffff);
*store = cpu_to_be64(arg);
} else {
*store = cpu_to_be64(old);
}
<API key>(&host->csr.lock, flags);
}
/* Is somebody erroneously releasing the broadcast_channel on us? */
if (host->csr.<API key> & 0x1)
host->csr.<API key> &= ~0x1;
return RCODE_COMPLETE;
<API key>:
switch (csraddr) {
case CSR_STATE_CLEAR:
case CSR_STATE_SET:
case CSR_RESET_START:
case CSR_NODE_IDS:
case <API key>:
case <API key>:
case CSR_CYCLE_TIME:
case CSR_BUS_TIME:
case CSR_BUS_MANAGER_ID:
case <API key>:
case CSR_BUSY_TIMEOUT:
case <API key>:
return RCODE_TYPE_ERROR;
default:
return RCODE_ADDRESS_ERROR;
}
}
static int write_fcp(struct hpsb_host *host, int nodeid, int dest,
quadlet_t *data, u64 addr, size_t length, u16 flags)
{
int csraddr = addr - CSR_REGISTER_BASE;
if (length > 512)
return RCODE_TYPE_ERROR;
switch (csraddr) {
case CSR_FCP_COMMAND:
<API key>(host, nodeid, 0, (u8 *)data, length);
break;
case CSR_FCP_RESPONSE:
<API key>(host, nodeid, 1, (u8 *)data, length);
break;
default:
return RCODE_TYPE_ERROR;
}
return RCODE_COMPLETE;
}
static int read_config_rom(struct hpsb_host *host, int nodeid, quadlet_t *buffer,
u64 addr, size_t length, u16 fl)
{
u32 offset = addr - <API key>;
if (csr1212_read(host->csr.rom, offset, buffer, length) == CSR1212_SUCCESS)
return RCODE_COMPLETE;
else
return RCODE_ADDRESS_ERROR;
}
static u64 allocate_addr_range(u64 size, u32 alignment, void *__host)
{
struct hpsb_host *host = (struct hpsb_host*)__host;
return <API key>(&csr_highlevel,
host,
&config_rom_ops,
size, alignment,
<API key>,
<API key>);
}
static void release_addr_range(u64 addr, void *__host)
{
struct hpsb_host *host = (struct hpsb_host*)__host;
<API key>(&csr_highlevel, host, addr);
}
int init_csr(void)
{
node_cap = <API key>(<API key>, 0x0083c0);
if (!node_cap) {
HPSB_ERR("Failed to allocate memory for Node Capabilties ConfigROM entry!");
return -ENOMEM;
}
<API key>(&csr_highlevel);
return 0;
}
void cleanup_csr(void)
{
if (node_cap)
<API key>(node_cap);
<API key>(&csr_highlevel);
} |
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/proc_fs.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <linux/pci.h>
#include <linux/pci_hotplug.h>
#include <linux/init.h>
#include <asm/uaccess.h>
#include "cpqphp.h"
#include "cpqphp_nvram.h"
#define ROM_INT15_PHY_ADDR 0x0FF859
#define READ_EV 0xD8A4
#define WRITE_EV 0xD8A5
struct register_foo {
union {
unsigned long lword; /* eax */
unsigned short word;
struct {
unsigned char low;
unsigned char high;
} byte;
} data;
unsigned char opcode; /* see below */
unsigned long length; /* if the reg. is a pointer, how much data */
} __attribute__ ((packed));
struct all_reg {
struct register_foo eax_reg;
struct register_foo ebx_reg;
struct register_foo ecx_reg;
struct register_foo edx_reg;
struct register_foo edi_reg;
struct register_foo esi_reg;
struct register_foo eflags_reg;
} __attribute__ ((packed));
struct ev_hrt_header {
u8 Version;
u8 num_of_ctrl;
u8 next;
};
struct ev_hrt_ctrl {
u8 bus;
u8 device;
u8 function;
u8 mem_avail;
u8 p_mem_avail;
u8 io_avail;
u8 bus_avail;
u8 next;
};
static u8 evbuffer_init;
static u8 evbuffer_length;
static u8 evbuffer[1024];
static void __iomem *<API key>;
/* lock for ordering int15_bios_call() */
static spinlock_t int15_lock;
/* This is a series of function that deals with
* setting & getting the hotplug resource table in some environment variable.
*/
/*
* We really shouldn't be doing this unless there is a _very_ good reason to!!!
* greg k-h
*/
static u32 add_byte( u32 **p_buffer, u8 value, u32 *used, u32 *avail)
{
u8 **tByte;
if ((*used + 1) > *avail)
return(1);
*((u8*)*p_buffer) = value;
tByte = (u8**)p_buffer;
(*tByte)++;
*used+=1;
return(0);
}
static u32 add_dword( u32 **p_buffer, u32 value, u32 *used, u32 *avail)
{
if ((*used + 4) > *avail)
return(1);
**p_buffer = value;
(*p_buffer)++;
*used+=4;
return(0);
}
/*
* <API key>
*
* this routine verifies that the ROM OEM string is 'COMPAQ'
*
* returns 0 for non-Compaq ROM, 1 for Compaq ROM
*/
static int <API key> (void __iomem *rom_start)
{
u8 temp1, temp2, temp3, temp4, temp5, temp6;
int result = 0;
temp1 = readb(rom_start + 0xffea + 0);
temp2 = readb(rom_start + 0xffea + 1);
temp3 = readb(rom_start + 0xffea + 2);
temp4 = readb(rom_start + 0xffea + 3);
temp5 = readb(rom_start + 0xffea + 4);
temp6 = readb(rom_start + 0xffea + 5);
if ((temp1 == 'C') &&
(temp2 == 'O') &&
(temp3 == 'M') &&
(temp4 == 'P') &&
(temp5 == 'A') &&
(temp6 == 'Q')) {
result = 1;
}
dbg ("%s - returned %d\n", __func__, result);
return result;
}
static u32 access_EV (u16 operation, u8 *ev_name, u8 *buffer, u32 *buf_size)
{
unsigned long flags;
int op = operation;
int ret_val;
if (!<API key>)
return -ENODEV;
spin_lock_irqsave(&int15_lock, flags);
__asm__ (
"xorl %%ebx,%%ebx\n" \
"xorl %%edx,%%edx\n" \
"pushf\n" \
"push %%cs\n" \
"cli\n" \
"call *%6\n"
: "=c" (*buf_size), "=a" (ret_val)
: "a" (op), "c" (*buf_size), "S" (ev_name),
"D" (buffer), "m" (<API key>)
: "%ebx", "%edx");
<API key>(&int15_lock, flags);
return((ret_val & 0xFF00) >> 8);
}
/*
* load_HRT
*
* Read the hot plug Resource Table from NVRAM
*/
static int load_HRT (void __iomem *rom_start)
{
u32 available;
u32 temp_dword;
u8 temp_byte = 0xFF;
u32 rc;
if (!<API key>(rom_start)) {
return -ENODEV;
}
available = 1024;
/* Now load the EV */
temp_dword = available;
rc = access_EV(READ_EV, "CQTHPS", evbuffer, &temp_dword);
evbuffer_length = temp_dword;
/* We're maintaining the resource lists so write FF to invalidate old
* info
*/
temp_dword = 1;
rc = access_EV(WRITE_EV, "CQTHPS", &temp_byte, &temp_dword);
return rc;
}
/*
* store_HRT
*
* Save the hot plug Resource Table in NVRAM
*/
static u32 store_HRT (void __iomem *rom_start)
{
u32 *buffer;
u32 *pFill;
u32 usedbytes;
u32 available;
u32 temp_dword;
u32 rc;
u8 loop;
u8 numCtrl = 0;
struct controller *ctrl;
struct pci_resource *resNode;
struct ev_hrt_header *p_EV_header;
struct ev_hrt_ctrl *p_ev_ctrl;
available = 1024;
if (!<API key>(rom_start)) {
return(1);
}
buffer = (u32*) evbuffer;
if (!buffer)
return(1);
pFill = buffer;
usedbytes = 0;
p_EV_header = (struct ev_hrt_header *) pFill;
ctrl = cpqhp_ctrl_list;
/* The revision of this structure */
rc = add_byte( &pFill, 1 + ctrl->push_flag, &usedbytes, &available);
if (rc)
return(rc);
/* The number of controllers */
rc = add_byte( &pFill, 1, &usedbytes, &available);
if (rc)
return(rc);
while (ctrl) {
p_ev_ctrl = (struct ev_hrt_ctrl *) pFill;
numCtrl++;
/* The bus number */
rc = add_byte( &pFill, ctrl->bus, &usedbytes, &available);
if (rc)
return(rc);
/* The device Number */
rc = add_byte( &pFill, PCI_SLOT(ctrl->pci_dev->devfn), &usedbytes, &available);
if (rc)
return(rc);
/* The function Number */
rc = add_byte( &pFill, PCI_FUNC(ctrl->pci_dev->devfn), &usedbytes, &available);
if (rc)
return(rc);
/* Skip the number of available entries */
rc = add_dword( &pFill, 0, &usedbytes, &available);
if (rc)
return(rc);
/* Figure out memory Available */
resNode = ctrl->mem_head;
loop = 0;
while (resNode) {
loop ++;
/* base */
rc = add_dword( &pFill, resNode->base, &usedbytes, &available);
if (rc)
return(rc);
/* length */
rc = add_dword( &pFill, resNode->length, &usedbytes, &available);
if (rc)
return(rc);
resNode = resNode->next;
}
/* Fill in the number of entries */
p_ev_ctrl->mem_avail = loop;
/* Figure out prefetchable memory Available */
resNode = ctrl->p_mem_head;
loop = 0;
while (resNode) {
loop ++;
/* base */
rc = add_dword( &pFill, resNode->base, &usedbytes, &available);
if (rc)
return(rc);
/* length */
rc = add_dword( &pFill, resNode->length, &usedbytes, &available);
if (rc)
return(rc);
resNode = resNode->next;
}
/* Fill in the number of entries */
p_ev_ctrl->p_mem_avail = loop;
/* Figure out IO Available */
resNode = ctrl->io_head;
loop = 0;
while (resNode) {
loop ++;
/* base */
rc = add_dword( &pFill, resNode->base, &usedbytes, &available);
if (rc)
return(rc);
/* length */
rc = add_dword( &pFill, resNode->length, &usedbytes, &available);
if (rc)
return(rc);
resNode = resNode->next;
}
/* Fill in the number of entries */
p_ev_ctrl->io_avail = loop;
/* Figure out bus Available */
resNode = ctrl->bus_head;
loop = 0;
while (resNode) {
loop ++;
/* base */
rc = add_dword( &pFill, resNode->base, &usedbytes, &available);
if (rc)
return(rc);
/* length */
rc = add_dword( &pFill, resNode->length, &usedbytes, &available);
if (rc)
return(rc);
resNode = resNode->next;
}
/* Fill in the number of entries */
p_ev_ctrl->bus_avail = loop;
ctrl = ctrl->next;
}
p_EV_header->num_of_ctrl = numCtrl;
/* Now store the EV */
temp_dword = usedbytes;
rc = access_EV(WRITE_EV, "CQTHPS", (u8*) buffer, &temp_dword);
dbg("usedbytes = 0x%x, length = 0x%x\n", usedbytes, temp_dword);
evbuffer_length = temp_dword;
if (rc) {
err(msg_unable_to_save);
return(1);
}
return(0);
}
void compaq_nvram_init (void __iomem *rom_start)
{
if (rom_start) {
<API key> = (rom_start + ROM_INT15_PHY_ADDR - ROM_PHY_ADDR);
}
dbg("int15 entry = %p\n", <API key>);
/* initialize our int15 lock */
spin_lock_init(&int15_lock);
}
int compaq_nvram_load (void __iomem *rom_start, struct controller *ctrl)
{
u8 bus, device, function;
u8 nummem, numpmem, numio, numbus;
u32 rc;
u8 *p_byte;
struct pci_resource *mem_node;
struct pci_resource *p_mem_node;
struct pci_resource *io_node;
struct pci_resource *bus_node;
struct ev_hrt_ctrl *p_ev_ctrl;
struct ev_hrt_header *p_EV_header;
if (!evbuffer_init) {
/* Read the resource list information in from NVRAM */
if (load_HRT(rom_start))
memset (evbuffer, 0, 1024);
evbuffer_init = 1;
}
/* If we saved information in NVRAM, use it now */
p_EV_header = (struct ev_hrt_header *) evbuffer;
/* The following code is for systems where version 1.0 of this
* driver has been loaded, but doesn't support the hardware.
* In that case, the driver would incorrectly store something
* in NVRAM.
*/
if ((p_EV_header->Version == 2) ||
((p_EV_header->Version == 1) && !ctrl->push_flag)) {
p_byte = &(p_EV_header->next);
p_ev_ctrl = (struct ev_hrt_ctrl *) &(p_EV_header->next);
p_byte += 3;
if (p_byte > ((u8*)p_EV_header + evbuffer_length))
return 2;
bus = p_ev_ctrl->bus;
device = p_ev_ctrl->device;
function = p_ev_ctrl->function;
while ((bus != ctrl->bus) ||
(device != PCI_SLOT(ctrl->pci_dev->devfn)) ||
(function != PCI_FUNC(ctrl->pci_dev->devfn))) {
nummem = p_ev_ctrl->mem_avail;
numpmem = p_ev_ctrl->p_mem_avail;
numio = p_ev_ctrl->io_avail;
numbus = p_ev_ctrl->bus_avail;
p_byte += 4;
if (p_byte > ((u8*)p_EV_header + evbuffer_length))
return 2;
/* Skip forward to the next entry */
p_byte += (nummem + numpmem + numio + numbus) * 8;
if (p_byte > ((u8*)p_EV_header + evbuffer_length))
return 2;
p_ev_ctrl = (struct ev_hrt_ctrl *) p_byte;
p_byte += 3;
if (p_byte > ((u8*)p_EV_header + evbuffer_length))
return 2;
bus = p_ev_ctrl->bus;
device = p_ev_ctrl->device;
function = p_ev_ctrl->function;
}
nummem = p_ev_ctrl->mem_avail;
numpmem = p_ev_ctrl->p_mem_avail;
numio = p_ev_ctrl->io_avail;
numbus = p_ev_ctrl->bus_avail;
p_byte += 4;
if (p_byte > ((u8*)p_EV_header + evbuffer_length))
return 2;
while (nummem
mem_node = kmalloc(sizeof(struct pci_resource), GFP_KERNEL);
if (!mem_node)
break;
mem_node->base = *(u32*)p_byte;
dbg("mem base = %8.8x\n",mem_node->base);
p_byte += 4;
if (p_byte > ((u8*)p_EV_header + evbuffer_length)) {
kfree(mem_node);
return 2;
}
mem_node->length = *(u32*)p_byte;
dbg("mem length = %8.8x\n",mem_node->length);
p_byte += 4;
if (p_byte > ((u8*)p_EV_header + evbuffer_length)) {
kfree(mem_node);
return 2;
}
mem_node->next = ctrl->mem_head;
ctrl->mem_head = mem_node;
}
while (numpmem
p_mem_node = kmalloc(sizeof(struct pci_resource), GFP_KERNEL);
if (!p_mem_node)
break;
p_mem_node->base = *(u32*)p_byte;
dbg("pre-mem base = %8.8x\n",p_mem_node->base);
p_byte += 4;
if (p_byte > ((u8*)p_EV_header + evbuffer_length)) {
kfree(p_mem_node);
return 2;
}
p_mem_node->length = *(u32*)p_byte;
dbg("pre-mem length = %8.8x\n",p_mem_node->length);
p_byte += 4;
if (p_byte > ((u8*)p_EV_header + evbuffer_length)) {
kfree(p_mem_node);
return 2;
}
p_mem_node->next = ctrl->p_mem_head;
ctrl->p_mem_head = p_mem_node;
}
while (numio
io_node = kmalloc(sizeof(struct pci_resource), GFP_KERNEL);
if (!io_node)
break;
io_node->base = *(u32*)p_byte;
dbg("io base = %8.8x\n",io_node->base);
p_byte += 4;
if (p_byte > ((u8*)p_EV_header + evbuffer_length)) {
kfree(io_node);
return 2;
}
io_node->length = *(u32*)p_byte;
dbg("io length = %8.8x\n",io_node->length);
p_byte += 4;
if (p_byte > ((u8*)p_EV_header + evbuffer_length)) {
kfree(io_node);
return 2;
}
io_node->next = ctrl->io_head;
ctrl->io_head = io_node;
}
while (numbus
bus_node = kmalloc(sizeof(struct pci_resource), GFP_KERNEL);
if (!bus_node)
break;
bus_node->base = *(u32*)p_byte;
p_byte += 4;
if (p_byte > ((u8*)p_EV_header + evbuffer_length)) {
kfree(bus_node);
return 2;
}
bus_node->length = *(u32*)p_byte;
p_byte += 4;
if (p_byte > ((u8*)p_EV_header + evbuffer_length)) {
kfree(bus_node);
return 2;
}
bus_node->next = ctrl->bus_head;
ctrl->bus_head = bus_node;
}
/* If all of the following fail, we don't have any resources for
* hot plug add
*/
rc = 1;
rc &= <API key>(&(ctrl->mem_head));
rc &= <API key>(&(ctrl->p_mem_head));
rc &= <API key>(&(ctrl->io_head));
rc &= <API key>(&(ctrl->bus_head));
if (rc)
return(rc);
} else {
if ((evbuffer[0] != 0) && (!ctrl->push_flag))
return 1;
}
return 0;
}
int compaq_nvram_store (void __iomem *rom_start)
{
int rc = 1;
if (rom_start == NULL)
return -ENODEV;
if (evbuffer_init) {
rc = store_HRT(rom_start);
if (rc) {
err(msg_unable_to_save);
}
}
return rc;
} |
using System;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using GitCommands;
using GitUI.CommandsDialogs.SubmodulesDialog;
using <API key>;
using ResourceManager;
namespace GitUI.CommandsDialogs
{
public partial class FormSubmodules : GitModuleForm
{
private readonly TranslationString <API key> =
new TranslationString("Are you sure you want remove the selected submodule?");
private readonly TranslationString <API key> = new TranslationString("Remove");
private BindingList<IGitSubmoduleInfo> modules = new BindingList<IGitSubmoduleInfo>();
private GitSubmoduleInfo _oldSubmoduleInfo;
public FormSubmodules(GitUICommands aCommands)
: base(aCommands)
{
InitializeComponent();
Translate();
<API key>.DataSource = modules;
}
private void AddSubmoduleClick(object sender, EventArgs e)
{
using (var formAddSubmodule = new FormAddSubmodule(UICommands))
formAddSubmodule.ShowDialog(this);
Initialize();
}
private void FormSubmodulesShown(object sender, EventArgs e)
{
Initialize();
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bw = sender as BackgroundWorker;
foreach (var oldSubmodule in Module.GetSubmodulesInfo())
{
if (bw.CancellationPending)
{
e.Cancel = true;
break;
}
bw.ReportProgress(0, oldSubmodule);
}
}
private void bw_ProgressChanged(object sender, <API key> e)
{
lock (modules)
{
lock (modules)
modules.Add(e.UserState as GitSubmoduleInfo);
if (_oldSubmoduleInfo != null)
{
DataGridViewRow row = Submodules.Rows
.Cast<DataGridViewRow>()
.FirstOrDefault(r => r.DataBoundItem as GitSubmoduleInfo == _oldSubmoduleInfo);
if (row != null)
row.Selected = true;
}
}
}
private void <API key>(object sender, EventArgs e)
{
UseWaitCursor = false;
}
private BackgroundWorker bw;
private void Initialize()
{
if (bw != null)
bw.CancelAsync();
UseWaitCursor = true;
_oldSubmoduleInfo = null;
if (Submodules.SelectedRows.Count == 1)
_oldSubmoduleInfo = Submodules.SelectedRows[0].DataBoundItem as GitSubmoduleInfo;
lock (modules)
modules.Clear();
bw = new BackgroundWorker();
bw.DoWork += bw_DoWork;
bw.ProgressChanged += bw_ProgressChanged;
bw.RunWorkerCompleted += <API key>;
bw.<API key> = true;
bw.<API key> = true;
bw.RunWorkerAsync();
}
private void <API key>(object sender, EventArgs e)
{
UseWaitCursor = true;
FormProcess.ShowDialog(this, GitCommandHelpers.SubmoduleSyncCmd(SubModuleLocalPath.Text));
Initialize();
UseWaitCursor = false;
}
private void <API key>(object sender, EventArgs e)
{
UseWaitCursor = true;
FormProcess.ShowDialog(this, GitCommandHelpers.SubmoduleUpdateCmd(SubModuleLocalPath.Text));
Initialize();
UseWaitCursor = false;
}
private void <API key>(object sender, EventArgs e)
{
if (Submodules.SelectedRows.Count != 1 ||
MessageBox.Show(this, <API key>.Text, <API key>.Text,
MessageBoxButtons.YesNo) !=
DialogResult.Yes)
return;
UseWaitCursor = true;
Module.UnstageFile(SubModuleLocalPath.Text);
var modules = Module.<API key>();
modules.RemoveConfigSection("submodule \"" + SubModuleName.Text + "\"");
if (modules.ConfigSections.Count > 0)
{
modules.Save();
Module.StageFile(".gitmodules");
}
else
Module.UnstageFile(".gitmodules");
var configFile = Module.LocalConfigFile;
configFile.RemoveConfigSection("submodule \"" + SubModuleName.Text + "\"");
configFile.Save();
Initialize();
UseWaitCursor = false;
}
private void Pull_Click(object sender, EventArgs e)
{
var submodule = Module.GetSubmodule(SubModuleLocalPath.Text);
if (submodule == null)
return;
GitUICommands uiCommands = new GitUICommands(submodule);
uiCommands.StartPullDialog(this);
UseWaitCursor = true;
Initialize();
UseWaitCursor = false;
}
}
} |
/*
Commonjs package manager support (eg componentjs).
*/
"use strict";// NOTE: textAngularVersion must match the Gruntfile.js 'setVersion' task.... and have format v/d+./d+./d+
var textAngularVersion = 'v1.5.6-0'; // This is automatically updated during the build process to the current release!
// We need this as IE sometimes plays funny tricks with the contenteditable.
// If you're not in IE (or IE version is less than 5) then:
// Thus, to detect IE:
// if (ie) {}
// ie > 7 // IE8, IE9, IE10 ...
// ie < 9 // Anything less than IE9
/* istanbul ignore next: untestable browser check */
var _browserDetect = {
ie: (function(){
var undef,
v = 3,
div = document.createElement('div'),
all = div.<API key>('i');
while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
all[0]
);
return v > 4 ? v : undef;
}()),
webkit: /AppleWebKit\/([\d.]+)/i.test(navigator.userAgent),
isFirefox: navigator.userAgent.toLowerCase().indexOf('firefox') > -1
};
// Global to textAngular to measure performance where needed
var performance = performance || {};
performance.now = (function() {
return performance.now ||
performance.mozNow ||
performance.msNow ||
performance.oNow ||
performance.webkitNow ||
function() { return new Date().getTime(); };
})();
// usage is:
// var t0 = performance.now();
// doSomething();
// var t1 = performance.now();
// console.log('Took', (t1 - t0).toFixed(4), 'milliseconds to do something!');
// turn html into pure text that shows visiblity
function stripHtmlToText(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
var res = tmp.textContent || tmp.innerText || '';
res.replace('\u200B', ''); // zero width space
res = res.trim();
return res;
}
// get html
function getDomFromHtml(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp;
}
// Global to textAngular REGEXP vars for block and list elements.
var BLOCKELEMENTS = /^(address|article|aside|audio|blockquote|canvas|dd|div|dl|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|noscript|ol|output|p|pre|section|table|tfoot|ul|video)$/i;
var LISTELEMENTS = /^(ul|li|ol)$/i;
var VALIDELEMENTS = /^(address|article|aside|audio|blockquote|canvas|dd|div|dl|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|noscript|ol|output|p|pre|section|table|tfoot|ul|video|li)$/i;
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Compatibility
/* istanbul ignore next: trim shim for older browsers */
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
var sheet, addCSSRule, removeCSSRule, _addCSSRule, _removeCSSRule, _getRuleIndex;
/* istanbul ignore else: IE <8 test*/
if(_browserDetect.ie > 8 || _browserDetect.ie === undefined){
var _sheets = document.styleSheets;
/* istanbul ignore next: preference for stylesheet loaded externally */
for(var i = 0; i < _sheets.length; i++){
if(_sheets[i].media.length === 0 || _sheets[i].media.mediaText.match(/(all|screen)/ig)){
if(_sheets[i].href){
if(_sheets[i].href.match(/textangular\.(min\.|)css/ig)){
sheet = _sheets[i];
break;
}
}
}
}
/* istanbul ignore next: preference for stylesheet loaded externally */
if(!sheet){
// this sheet is used for the placeholders later on.
sheet = (function() {
// Create the <style> tag
var style = document.createElement("style");
/* istanbul ignore else : WebKit hack :( */
if(_browserDetect.webkit) style.appendChild(document.createTextNode(""));
// Add the <style> element to the page, add as first so the styles can be overridden by custom stylesheets
document.<API key>('head')[0].appendChild(style);
return style.sheet;
})();
}
// use as: addCSSRule("header", "float: left");
addCSSRule = function(selector, rules) {
return _addCSSRule(sheet, selector, rules);
};
_addCSSRule = function(_sheet, selector, rules){
var insertIndex;
var insertedRule;
// This order is important as IE 11 has both cssRules and rules but they have different lengths - cssRules is correct, rules gives an error in IE 11
/* istanbul ignore next: browser catches */
if(_sheet.cssRules) insertIndex = Math.max(_sheet.cssRules.length - 1, 0);
else if(_sheet.rules) insertIndex = Math.max(_sheet.rules.length - 1, 0);
/* istanbul ignore else: untestable IE option */
if(_sheet.insertRule) {
_sheet.insertRule(selector + "{" + rules + "}", insertIndex);
}
else {
_sheet.addRule(selector, rules, insertIndex);
}
/* istanbul ignore next: browser catches */
if(sheet.rules) insertedRule = sheet.rules[insertIndex];
else if(sheet.cssRules) insertedRule = sheet.cssRules[insertIndex];
// return the inserted stylesheet rule
return insertedRule;
};
_getRuleIndex = function(rule, rules) {
var i, ruleIndex;
for (i=0; i < rules.length; i++) {
/* istanbul ignore else: check for correct rule */
if (rules[i].cssText === rule.cssText) {
ruleIndex = i;
break;
}
}
return ruleIndex;
};
removeCSSRule = function(rule){
_removeCSSRule(sheet, rule);
};
/* istanbul ignore next: tests are browser specific */
_removeCSSRule = function(sheet, rule){
var rules = sheet.cssRules || sheet.rules;
if(!rules || rules.length === 0) return;
var ruleIndex = _getRuleIndex(rule, rules);
if(sheet.removeRule){
sheet.removeRule(ruleIndex);
}else{
sheet.deleteRule(ruleIndex);
}
};
}
angular.module('textAngular.factories', [])
.factory('taBrowserTag', [function(){
return function(tag){
/* istanbul ignore next: ie specific test */
if(!tag) return (_browserDetect.ie <= 8)? 'P' : 'p';
else if(tag === '') return (_browserDetect.ie === undefined)? 'div' : (_browserDetect.ie <= 8)? 'P' : 'p';
else return (_browserDetect.ie <= 8)? tag.toUpperCase() : tag;
};
}]).factory('<API key>', ['taCustomRenderers', 'taDOM', function(taCustomRenderers, taDOM){
return function(val){
var element = angular.element('<div></div>');
element[0].innerHTML = val;
angular.forEach(taCustomRenderers, function(renderer){
var elements = [];
// get elements based on what is defined. If both defined do secondary filter in the forEach after using selector string
if(renderer.selector && renderer.selector !== '')
elements = element.find(renderer.selector);
/* istanbul ignore else: shouldn't fire, if it does we're ignoring everything */
else if(renderer.customAttribute && renderer.customAttribute !== '')
elements = taDOM.getByAttribute(element, renderer.customAttribute);
// process elements if any found
angular.forEach(elements, function(_element){
_element = angular.element(_element);
if(renderer.selector && renderer.selector !== '' && renderer.customAttribute && renderer.customAttribute !== ''){
if(_element.attr(renderer.customAttribute) !== undefined) renderer.renderLogic(_element);
} else renderer.renderLogic(_element);
});
});
return element[0].innerHTML;
};
}]).factory('taFixChrome', function(){
// get whaterever rubbish is inserted in chrome
// should be passed an html string, returns an html string
var taFixChrome = function(html){
if(!html || !angular.isString(html) || html.length <= 0) return html;
// grab all elements with a style attibute
var spanMatch = /<([^>\/]+?)style=("([^\"]+)"|'([^']+)')([^>]*)>/ig;
var <API key> = /<span class="<API key>">([^<]+)<\/span>/ig;
var match, styleVal, appleSpaceVal, newTag, finalHtml = '', lastIndex = 0;
// remove all the <API key> spans and replace with the content of the span
/* istanbul ignore next: <API key> span match */
while(match = <API key>.exec(html)){
appleSpaceVal = match[1];
appleSpaceVal = appleSpaceVal.replace(/ /ig, ' ');
finalHtml += html.substring(lastIndex, match.index) + appleSpaceVal;
lastIndex = match.index + match[0].length;
}
/* istanbul ignore next: <API key> span has matched */
if (lastIndex) {
// modified....
html=finalHtml;
finalHtml='';
lastIndex=0;
}
while(match = spanMatch.exec(html)){
// one of the quoted values ' or "
/* istanbul ignore next: quotations match */
styleVal = match[3] || match[4];
// test for chrome inserted junk
if(styleVal && styleVal.match(/line-height: 1.[0-9]{3,12};|color: inherit; line-height: 1.1;|color: rgb\(\d{1,3}, \d{1,3}, \d{1,3}\);|background-color: rgb\(\d{1,3}, \d{1,3}, \d{1,3}\);/i)){
// replace original tag with new tag
styleVal = styleVal.replace(/( |)font-family: inherit;|( |)line-height: 1.[0-9]{3,12};|( |)color: inherit;|( |)color: rgb\(\d{1,3}, \d{1,3}, \d{1,3}\);|( |)background-color: rgb\(\d{1,3}, \d{1,3}, \d{1,3}\);/ig, '');
newTag = '<' + match[1].trim();
if(styleVal.trim().length > 0) newTag += ' style=' + match[2].substring(0,1) + styleVal + match[2].substring(0,1);
newTag += match[5].trim() + ">";
finalHtml += html.substring(lastIndex, match.index) + newTag;
lastIndex = match.index + match[0].length;
}
}
finalHtml += html.substring(lastIndex);
// only replace when something has changed, else we get focus problems on inserting lists
if(lastIndex > 0){
// replace all empty strings
return finalHtml.replace(/<span\s?>(.*?)<\/span>(<br(\/|)>|)/ig, '$1');
} else return html;
};
return taFixChrome;
}).factory('taSanitize', ['$sanitize', function taSanitizeFactory($sanitize){
var convert_infos = [
{
property: 'font-weight',
values: [ 'bold' ],
tag: 'b'
},
{
property: 'font-style',
values: [ 'italic' ],
tag: 'i'
}
];
var styleMatch = [];
for(var i = 0; i < convert_infos.length; i++){
var _partialStyle = '(' + convert_infos[i].property + ':\\s*(';
for(var j = 0; j < convert_infos[i].values.length; j++){
/* istanbul ignore next: not needed to be tested yet */
if(j > 0) _partialStyle += '|';
_partialStyle += convert_infos[i].values[j];
}
_partialStyle += ');)';
styleMatch.push(_partialStyle);
}
var styleRegexString = '(' + styleMatch.join('|') + ')';
function wrapNested(html, wrapTag) {
var depth = 0;
var lastIndex = 0;
var match;
var tagRegex = /<[^>]*>/ig;
while(match = tagRegex.exec(html)){
lastIndex = match.index;
if(match[0].substr(1, 1) === '/'){
if(depth === 0) break;
else depth
}else depth++;
}
return wrapTag +
html.substring(0, lastIndex) +
// get the start tags reversed - this is safe as we construct the strings with no content except the tags
angular.element(wrapTag)[0].outerHTML.substring(wrapTag.length) +
html.substring(lastIndex);
}
function <API key>(html){
if(!html || !angular.isString(html) || html.length <= 0) return html;
var i;
var styleElementMatch = /<([^>\/]+?)style=("([^"]+)"|'([^']+)')([^>]*)>/ig;
var match, subMatch, styleVal, newTag, lastNewTag = '', newHtml, finalHtml = '', lastIndex = 0;
while(match = styleElementMatch.exec(html)){
// one of the quoted values ' or "
/* istanbul ignore next: quotations match */
styleVal = match[3] || match[4];
var styleRegex = new RegExp(styleRegexString, 'i');
// test for style values to change
if(angular.isString(styleVal) && styleRegex.test(styleVal)){
// remove build tag list
newTag = '';
// init regex here for exec
var styleRegexExec = new RegExp(styleRegexString, 'ig');
// find relevand tags and build a string of them
while(subMatch = styleRegexExec.exec(styleVal)){
for(i = 0; i < convert_infos.length; i++){
if(!!subMatch[(i*2) + 2]){
newTag += '<' + convert_infos[i].tag + '>';
}
}
}
// recursively find more legacy styles in html before this tag and after the previous match (if any)
newHtml = <API key>(html.substring(lastIndex, match.index));
// build up html
if(lastNewTag.length > 0){
finalHtml += wrapNested(newHtml, lastNewTag);
}else finalHtml += newHtml;
// grab the style val without the transformed values
styleVal = styleVal.replace(new RegExp(styleRegexString, 'ig'), '');
// build the html tag
finalHtml += '<' + match[1].trim();
if(styleVal.length > 0) finalHtml += ' style="' + styleVal + '"';
finalHtml += match[5] + '>';
// update the start index to after this tag
lastIndex = match.index + match[0].length;
lastNewTag = newTag;
}
}
if(lastNewTag.length > 0){
finalHtml += wrapNested(html.substring(lastIndex), lastNewTag);
}
else finalHtml += html.substring(lastIndex);
return finalHtml;
}
function <API key>(html){
if(!html || !angular.isString(html) || html.length <= 0) return html;
// replace all align='...' tags with text-align attributes
var attrElementMatch = /<([^>\/]+?)align=("([^"]+)"|'([^']+)')([^>]*)>/ig;
var match, finalHtml = '', lastIndex = 0;
// match all attr tags
while(match = attrElementMatch.exec(html)){
// add all html before this tag
finalHtml += html.substring(lastIndex, match.index);
// record last index after this tag
lastIndex = match.index + match[0].length;
// construct tag without the align attribute
var newTag = '<' + match[1] + match[5];
// add the style attribute
if(/style=("([^"]+)"|'([^']+)')/ig.test(newTag)){
/* istanbul ignore next: quotations match */
newTag = newTag.replace(/style=("([^"]+)"|'([^']+)')/i, 'style="$2$3 text-align:' + (match[3] || match[4]) + ';"');
}else{
/* istanbul ignore next: quotations match */
newTag += ' style="text-align:' + (match[3] || match[4]) + ';"';
}
newTag += '>';
// add to html
finalHtml += newTag;
}
// return with remaining html
return finalHtml + html.substring(lastIndex);
}
return function taSanitize(unsafe, oldsafe, ignore){
// unsafe html should NEVER built into a DOM object via angular.element. This allows XSS to be inserted and run.
if ( !ignore ) {
try {
unsafe = <API key>(unsafe);
} catch (e) {
}
}
// unsafe and oldsafe should be valid HTML strings
// any exceptions (lets say, color for example) should be made here but with great care
// setup unsafe element for modification
unsafe = <API key>(unsafe);
var safe;
try {
safe = $sanitize(unsafe);
// do this afterwards, then the $sanitizer should still throw for bad markup
if(ignore) safe = unsafe;
} catch (e){
safe = oldsafe || '';
}
// Do processing for <pre> tags, removing tabs and return carriages outside of them
var _preTags = safe.match(/(<pre[^>]*>.*?<\/pre[^>]*>)/ig);
var processedSafe = safe.replace(/(&#(9|10);)*/ig, '');
var re = /<pre[^>]*>.*?<\/pre[^>]*>/ig;
var index = 0;
var lastIndex = 0;
var origTag;
safe = '';
while((origTag = re.exec(processedSafe)) !== null && index < _preTags.length){
safe += processedSafe.substring(lastIndex, origTag.index) + _preTags[index];
lastIndex = origTag.index + origTag[0].length;
index++;
}
return safe + processedSafe.substring(lastIndex);
};
}]).factory('taToolExecuteAction', ['$q', '$log', function($q, $log){
// this must be called on a toolScope or instance
return function(editor){
if(editor !== undefined) this.$editor = function(){ return editor; };
var deferred = $q.defer(),
promise = deferred.promise,
_editor = this.$editor();
// pass into the action the deferred function and also the function to reload the current selection if rangy available
var result;
try{
result = this.action(deferred, _editor.startAction());
// We set the .finally callback here to make sure it doesn't get executed before any other .then callback.
promise['finally'](function(){
_editor.endAction.call(_editor);
});
}catch(exc){
$log.error(exc);
}
if(result || result === undefined){
// if true or undefined is returned then the action has finished. Otherwise the deferred action will be resolved manually.
deferred.resolve();
}
};
}]);
angular.module('textAngular.DOM', ['textAngular.factories'])
.factory('taExecCommand', ['taSelection', 'taBrowserTag', '$document', function(taSelection, taBrowserTag, $document){
var listToDefault = function(listElement, defaultWrap){
var $target, i;
// if all selected then we should remove the list
// grab all li elements and convert to taDefaultWrap tags
var children = listElement.find('li');
for(i = children.length - 1; i >= 0; i
$target = angular.element('<' + defaultWrap + '>' + children[i].innerHTML + '</' + defaultWrap + '>');
listElement.after($target);
}
listElement.remove();
taSelection.<API key>($target[0]);
};
var selectLi = function(liElement){
if(/(<br(|\/)>)$/i.test(liElement.innerHTML.trim())) taSelection.<API key>(angular.element(liElement).find("br")[0]);
else taSelection.<API key>(liElement);
};
var listToList = function(listElement, newListTag){
var $target = angular.element('<' + newListTag + '>' + listElement[0].innerHTML + '</' + newListTag + '>');
listElement.after($target);
listElement.remove();
selectLi($target.find('li')[0]);
};
var childElementsToList = function(elements, listElement, newListTag){
var html = '';
for(var i = 0; i < elements.length; i++){
html += '<' + taBrowserTag('li') + '>' + elements[i].innerHTML + '</' + taBrowserTag('li') + '>';
}
var $target = angular.element('<' + newListTag + '>' + html + '</' + newListTag + '>');
listElement.after($target);
listElement.remove();
selectLi($target.find('li')[0]);
};
return function(taDefaultWrap, topNode){
// NOTE: here we are dealing with the html directly from the browser and not the html the user sees.
// IF you want to modify the html the user sees, do it when the user does a switchView
taDefaultWrap = taBrowserTag(taDefaultWrap);
return function(command, showUI, options, <API key>){
var i, $target, html, _nodes, next, optionsTagName, selectedElement, ourSelection;
var defaultWrapper = angular.element('<' + taDefaultWrap + '>');
try{
if (taSelection.getSelection) {
ourSelection = taSelection.getSelection();
}
selectedElement = taSelection.getSelectionElement();
//console.log('selectedElement', selectedElement);
// special checks and fixes when we are selecting the whole container
var __h, _innerNode;
/* istanbul ignore next */
if (selectedElement.tagName.toLowerCase() === 'div' &&
/taTextElement.+/.test(selectedElement.id) &&
ourSelection && ourSelection.start &&
ourSelection.start.offset === 1 &&
ourSelection.end.offset === 1) {
// opps we are actually selecting the whole container!
//console.log('selecting whole container!');
__h = selectedElement.innerHTML;
if (/<br>/i.test(__h)) {
// Firefox adds <br>'s and so we remove the <br>
__h = __h.replace(/<br>/i, '​'); // no space-space
}
if (/<br\/>/i.test(__h)) {
// Firefox adds <br/>'s and so we remove the <br/>
__h = __h.replace(/<br\/>/i, '​'); // no space-space
}
// remove stacked up <span>'s
if (/<span>(<span>)+/i.test(__h)) {
__h = __.replace(/<span>(<span>)+/i, '<span>');
}
// remove stacked up </span>'s
if (/<\/span>(<\/span>)+/i.test(__h)) {
__h = __.replace(/<\/span>(<\/span>)+/i, '<\/span>');
}
if (/<span><\/span>/i.test(__h)) {
// if we end up with a <span></span> here we remove it...
__h = __h.replace(/<span><\/span>/i, '');
}
//console.log('inner whole container', selectedElement.childNodes);
_innerNode = '<div>' + __h + '</div>';
selectedElement.innerHTML = _innerNode;
//console.log('childNodes:', selectedElement.childNodes);
taSelection.<API key>(selectedElement.childNodes[0]);
selectedElement = taSelection.getSelectionElement();
} else if (selectedElement.tagName.toLowerCase() === 'span' &&
ourSelection && ourSelection.start &&
ourSelection.start.offset === 1 &&
ourSelection.end.offset === 1) {
// just a span -- this is a problem...
//console.log('selecting span!');
__h = selectedElement.innerHTML;
if (/<br>/i.test(__h)) {
// Firefox adds <br>'s and so we remove the <br>
__h = __h.replace(/<br>/i, '​'); // no space-space
}
if (/<br\/>/i.test(__h)) {
// Firefox adds <br/>'s and so we remove the <br/>
__h = __h.replace(/<br\/>/i, '​'); // no space-space
}
// remove stacked up <span>'s
if (/<span>(<span>)+/i.test(__h)) {
__h = __.replace(/<span>(<span>)+/i, '<span>');
}
// remove stacked up </span>'s
if (/<\/span>(<\/span>)+/i.test(__h)) {
__h = __.replace(/<\/span>(<\/span>)+/i, '<\/span>');
}
if (/<span><\/span>/i.test(__h)) {
// if we end up with a <span></span> here we remove it...
__h = __h.replace(/<span><\/span>/i, '');
}
//console.log('inner span', selectedElement.childNodes);
// we wrap this in a <div> because otherwise the browser get confused when we attempt to select the whole node
// and the focus is not set correctly no matter what we do
_innerNode = '<div>' + __h + '</div>';
selectedElement.innerHTML = _innerNode;
taSelection.<API key>(selectedElement.childNodes[0]);
selectedElement = taSelection.getSelectionElement();
//console.log(selectedElement.innerHTML);
} else if (selectedElement.tagName.toLowerCase() === 'p' &&
ourSelection && ourSelection.start &&
ourSelection.start.offset === 1 &&
ourSelection.end.offset === 1) {
//console.log('p special');
// we need to remove the </br> that firefox adds!
__h = selectedElement.innerHTML;
if (/<br>/i.test(__h)) {
// Firefox adds <br>'s and so we remove the <br>
__h = __h.replace(/<br>/i, '​'); // no space-space
}
selectedElement.innerHTML = __h;
}
}catch(e){
/* istanbul ignore next */
// we ignore errors from testing...
if (e.codeName !== 'INDEX_SIZE_ERR') console.error(e);
}
var $selected = angular.element(selectedElement);
if(selectedElement !== undefined){
var tagName = selectedElement.tagName.toLowerCase();
if(command.toLowerCase() === 'insertorderedlist' || command.toLowerCase() === 'insertunorderedlist'){
var selfTag = taBrowserTag((command.toLowerCase() === 'insertorderedlist')? 'ol' : 'ul');
if(tagName === selfTag){
// if all selected then we should remove the list
// grab all li elements and convert to taDefaultWrap tags
return listToDefault($selected, taDefaultWrap);
}else if(tagName === 'li' && $selected.parent()[0].tagName.toLowerCase() === selfTag && $selected.parent().children().length === 1){
// catch for the previous statement if only one li exists
return listToDefault($selected.parent(), taDefaultWrap);
}else if(tagName === 'li' && $selected.parent()[0].tagName.toLowerCase() !== selfTag && $selected.parent().children().length === 1){
// catch for the previous statement if only one li exists
return listToList($selected.parent(), selfTag);
}else if(tagName.match(BLOCKELEMENTS) && !$selected.hasClass('ta-bind')){
// if it's one of those block elements we have to change the contents
// if it's a ol/ul we are changing from one to the other
if(tagName === 'ol' || tagName === 'ul'){
return listToList($selected, selfTag);
}else{
var childBlockElements = false;
angular.forEach($selected.children(), function(elem){
if(elem.tagName.match(BLOCKELEMENTS)) {
childBlockElements = true;
}
});
if(childBlockElements){
return childElementsToList($selected.children(), $selected, selfTag);
}else{
return childElementsToList([angular.element('<div>' + selectedElement.innerHTML + '</div>')[0]], $selected, selfTag);
}
}
}else if(tagName.match(BLOCKELEMENTS)){
// if we get here then all the contents of the ta-bind are selected
_nodes = taSelection.<API key>();
if(_nodes.length === 0){
// here is if there is only text in ta-bind ie <div ta-bind>test content</div>
$target = angular.element('<' + selfTag + '><li>' + selectedElement.innerHTML + '</li></' + selfTag + '>');
$selected.html('');
$selected.append($target);
}else if(_nodes.length === 1 && (_nodes[0].tagName.toLowerCase() === 'ol' || _nodes[0].tagName.toLowerCase() === 'ul')){
if(_nodes[0].tagName.toLowerCase() === selfTag){
// remove
return listToDefault(angular.element(_nodes[0]), taDefaultWrap);
}else{
return listToList(angular.element(_nodes[0]), selfTag);
}
}else{
html = '';
var $nodes = [];
for(i = 0; i < _nodes.length; i++){
/* istanbul ignore else: catch for real-world can't make it occur in testing */
if(_nodes[i].nodeType !== 3){
var $n = angular.element(_nodes[i]);
/* istanbul ignore if: browser check only, phantomjs doesn't return children nodes but chrome at least does */
if(_nodes[i].tagName.toLowerCase() === 'li') continue;
else if(_nodes[i].tagName.toLowerCase() === 'ol' || _nodes[i].tagName.toLowerCase() === 'ul'){
html += $n[0].innerHTML; // if it's a list, add all it's children
}else if(_nodes[i].tagName.toLowerCase() === 'span' && (_nodes[i].childNodes[0].tagName.toLowerCase() === 'ol' || _nodes[i].childNodes[0].tagName.toLowerCase() === 'ul')){
html += $n[0].childNodes[0].innerHTML; // if it's a list, add all it's children
}else{
html += '<' + taBrowserTag('li') + '>' + $n[0].innerHTML + '</' + taBrowserTag('li') + '>';
}
$nodes.unshift($n);
}
}
$target = angular.element('<' + selfTag + '>' + html + '</' + selfTag + '>');
$nodes.pop().replaceWith($target);
angular.forEach($nodes, function($node){ $node.remove(); });
}
taSelection.<API key>($target[0]);
return;
}
}else if(command.toLowerCase() === 'formatblock'){
optionsTagName = options.toLowerCase().replace(/[<>]/ig, '');
if(optionsTagName.trim() === 'default') {
optionsTagName = taDefaultWrap;
options = '<' + taDefaultWrap + '>';
}
if(tagName === 'li') $target = $selected.parent();
else $target = $selected;
// find the first blockElement
while(!$target[0].tagName || !$target[0].tagName.match(BLOCKELEMENTS) && !$target.parent().attr('contenteditable')){
$target = $target.parent();
/* istanbul ignore next */
tagName = ($target[0].tagName || '').toLowerCase();
}
if(tagName === optionsTagName){
// $target is wrap element
_nodes = $target.children();
var hasBlock = false;
for(i = 0; i < _nodes.length; i++){
hasBlock = hasBlock || _nodes[i].tagName.match(BLOCKELEMENTS);
}
if(hasBlock){
$target.after(_nodes);
next = $target.next();
$target.remove();
$target = next;
}else{
defaultWrapper.append($target[0].childNodes);
$target.after(defaultWrapper);
$target.remove();
$target = defaultWrapper;
}
}else if($target.parent()[0].tagName.toLowerCase() === optionsTagName &&
!$target.parent().hasClass('ta-bind')){
//unwrap logic for parent
var blockElement = $target.parent();
var contents = blockElement.contents();
for(i = 0; i < contents.length; i ++){
/* istanbul ignore next: can't test - some wierd thing with how phantomjs works */
if(blockElement.parent().hasClass('ta-bind') && contents[i].nodeType === 3){
defaultWrapper = angular.element('<' + taDefaultWrap + '>');
defaultWrapper[0].innerHTML = contents[i].outerHTML;
contents[i] = defaultWrapper[0];
}
blockElement.parent()[0].insertBefore(contents[i], blockElement[0]);
}
blockElement.remove();
}else if(tagName.match(LISTELEMENTS)){
// wrapping a list element
$target.wrap(options);
}else{
// default wrap behaviour
_nodes = taSelection.<API key>();
//console.log('default wrap behavior', _nodes);
if(_nodes.length === 0) {
// no nodes at all....
_nodes = [$target[0]];
}
// find the parent block element if any of the nodes are inline or text
for(i = 0; i < _nodes.length; i++){
if(_nodes[i].nodeType === 3 || !_nodes[i].tagName.match(BLOCKELEMENTS)){
while(_nodes[i].nodeType === 3 || !_nodes[i].tagName || !_nodes[i].tagName.match(BLOCKELEMENTS)){
_nodes[i] = _nodes[i].parentNode;
}
}
}
// remove any duplicates from the array of _nodes!
_nodes = _nodes.filter(function(value, index, self) {
return self.indexOf(value) === index;
});
if(angular.element(_nodes[0]).hasClass('ta-bind')){
$target = angular.element(options);
$target[0].innerHTML = _nodes[0].innerHTML;
_nodes[0].innerHTML = $target[0].outerHTML;
}else if(optionsTagName === 'blockquote'){
// blockquotes wrap other block elements
html = '';
for(i = 0; i < _nodes.length; i++){
html += _nodes[i].outerHTML;
}
$target = angular.element(options);
$target[0].innerHTML = html;
_nodes[0].parentNode.insertBefore($target[0],_nodes[0]);
for(i = _nodes.length - 1; i >= 0; i
/* istanbul ignore else: */
if(_nodes[i].parentNode) _nodes[i].parentNode.removeChild(_nodes[i]);
}
}
else {
// regular block elements replace other block elements
for(i = 0; i < _nodes.length; i++){
$target = angular.element(options);
$target[0].innerHTML = _nodes[i].innerHTML;
_nodes[i].parentNode.insertBefore($target[0],_nodes[i]);
_nodes[i].parentNode.removeChild(_nodes[i]);
}
}
}
taSelection.<API key>($target[0]);
// looses focus when we have the whole container selected and no text!
// refocus on the shown display element, this fixes a bug when using firefox
$target[0].focus();
//console.log($document[0].activeElement.childNodes);
//$document[0].activeElement.childNodes[0].focus();
return;
}else if(command.toLowerCase() === 'createlink'){
var tagBegin = '<a href="' + options + '" target="' +
(<API key>.a.target ? <API key>.a.target : '') +
'">',
tagEnd = '</a>',
_selection = taSelection.getSelection();
if(_selection.collapsed){
// insert text at selection, then select then just let normal exec-command run
taSelection.insertHtml(tagBegin + options + tagEnd, topNode);
}else if(rangy.getSelection().getRangeAt(0).canSurroundContents()){
var node = angular.element(tagBegin + tagEnd)[0];
rangy.getSelection().getRangeAt(0).surroundContents(node);
}
return;
}else if(command.toLowerCase() === 'inserthtml'){
taSelection.insertHtml(options, topNode);
return;
}
}
try{
$document[0].execCommand(command, showUI, options);
}catch(e){
/* istanbul ignore next */
// we ignore errors from testing...
if (e.codeName !== 'INDEX_SIZE_ERR') console.error(e);
}
};
};
}]).service('taSelection', ['$document', 'taDOM',
/* istanbul ignore next: all browser specifics and PhantomJS dosen't seem to support half of it */
function($document, taDOM){
// need to dereference the document else the calls don't work correctly
var _document = $document[0];
var brException = function (element, offset) {
/* check if selection is a BR element at the beginning of a container. If so, get
* the parentNode instead.
* offset should be zero in this case. Otherwise, return the original
* element.
*/
if (element.tagName && element.tagName.match(/^br$/i) && offset === 0 && !element.previousSibling) {
return {
element: element.parentNode,
offset: 0
};
} else {
return {
element: element,
offset: offset
};
}
};
var api = {
getSelection: function(){
var range = rangy.getSelection().getRangeAt(0);
var container = range.<API key>;
var selection = {
start: brException(range.startContainer, range.startOffset),
end: brException(range.endContainer, range.endOffset),
collapsed: range.collapsed
};
// Check if the container is a text node and return its parent if so
container = container.nodeType === 3 ? container.parentNode : container;
if (container.parentNode === selection.start.element ||
container.parentNode === selection.end.element) {
selection.container = container.parentNode;
} else {
selection.container = container;
}
return selection;
},
<API key>: function(){
var range = rangy.getSelection().getRangeAt(0);
var container = range.<API key>;
// Check if the container is a text node and return its parent if so
container = container.nodeType === 3 ? container.parentNode : container;
return range.getNodes([1], function(node){
return node.parentNode === container;
});
},
// Some basic selection functions
getSelectionElement: function () {
return api.getSelection().container;
},
setSelection: function(el, start, end){
var range = rangy.createRange();
range.setStart(el, start);
range.setEnd(el, end);
rangy.getSelection().setSingleRange(range);
},
<API key>: function (el){
var range = rangy.createRange();
range.selectNode(el);
range.collapse(true);
rangy.getSelection().setSingleRange(range);
},
<API key>: function (el){
var range = rangy.createRange();
range.selectNode(el);
range.collapse(false);
rangy.getSelection().setSingleRange(range);
},
<API key>: function (el){
var range = rangy.createRange();
range.selectNodeContents(el);
range.collapse(true);
rangy.getSelection().setSingleRange(range);
},
<API key>: function (el){
var range = rangy.createRange();
range.selectNodeContents(el);
range.collapse(false);
if(el.childNodes && el.childNodes[el.childNodes.length - 1] && el.childNodes[el.childNodes.length - 1].nodeName === 'br'){
range.startOffset = range.endOffset = range.startOffset - 1;
}
rangy.getSelection().setSingleRange(range);
},
// topNode is the contenteditable normally, all manipulation MUST be inside this.
insertHtml: function(html, topNode){
var parent, secondParent, _childI, nodes, i, lastNode, _tempFrag;
var element = angular.element("<div>" + html + "</div>");
var range = rangy.getSelection().getRangeAt(0);
var frag = _document.<API key>();
var children = element[0].childNodes;
var isInline = true;
if(children.length > 0){
// NOTE!! We need to do the following:
// check for blockelements - if they exist then we have to split the current element in half (and all others up to the closest block element) and insert all children in-between.
// If there are no block elements, or there is a mixture we need to create textNodes for the non wrapped text (we don't want them spans messing up the picture).
nodes = [];
for(_childI = 0; _childI < children.length; _childI++){
if(!(
(children[_childI].nodeName.toLowerCase() === 'p' && children[_childI].innerHTML.trim() === '') || // empty p element
(children[_childI].nodeType === 3 && children[_childI].nodeValue.trim() === '') // empty text node
)){
isInline = isInline && !BLOCKELEMENTS.test(children[_childI].nodeName);
nodes.push(children[_childI]);
}
}
for(var _n = 0; _n < nodes.length; _n++) lastNode = frag.appendChild(nodes[_n]);
if(!isInline && range.collapsed && /^(|<br(|\/)>)$/i.test(range.startContainer.innerHTML)) range.selectNode(range.startContainer);
}else{
isInline = true;
// paste text of some sort
lastNode = frag = _document.createTextNode(html);
}
// Other Edge case - selected data spans multiple blocks.
if(isInline){
range.deleteContents();
}else{ // not inline insert
if(range.collapsed && range.startContainer !== topNode){
if(range.startContainer.innerHTML && range.startContainer.innerHTML.match(/^<[^>]*>$/i)){
// this log is to catch when innerHTML is something like `<img ...>`
parent = range.startContainer;
if(range.startOffset === 1){
// before single tag
range.setStartAfter(parent);
range.setEndAfter(parent);
}else{
// after single tag
range.setStartBefore(parent);
range.setEndBefore(parent);
}
}else{
// split element into 2 and insert block element in middle
if(range.startContainer.nodeType === 3 && range.startContainer.parentNode !== topNode){ // if text node
parent = range.startContainer.parentNode;
secondParent = parent.cloneNode();
// split the nodes into two lists - before and after, splitting the node with the selection into 2 text nodes.
taDOM.splitNodes(parent.childNodes, parent, secondParent, range.startContainer, range.startOffset);
// Escape out of the inline tags like b
while(!VALIDELEMENTS.test(parent.nodeName)){
angular.element(parent).after(secondParent);
parent = parent.parentNode;
var _lastSecondParent = secondParent;
secondParent = parent.cloneNode();
// split the nodes into two lists - before and after, splitting the node with the selection into 2 text nodes.
taDOM.splitNodes(parent.childNodes, parent, secondParent, _lastSecondParent);
}
}else{
parent = range.startContainer;
secondParent = parent.cloneNode();
taDOM.splitNodes(parent.childNodes, parent, secondParent, undefined, undefined, range.startOffset);
}
angular.element(parent).after(secondParent);
// put cursor to end of inserted content
//console.log('setStartAfter', parent);
range.setStartAfter(parent);
range.setEndAfter(parent);
if(/^(|<br(|\/)>)$/i.test(parent.innerHTML.trim())){
range.setStartBefore(parent);
range.setEndBefore(parent);
angular.element(parent).remove();
}
if(/^(|<br(|\/)>)$/i.test(secondParent.innerHTML.trim())) angular.element(secondParent).remove();
if(parent.nodeName.toLowerCase() === 'li'){
_tempFrag = _document.<API key>();
for(i = 0; i < frag.childNodes.length; i++){
element = angular.element('<li>');
taDOM.transferChildNodes(frag.childNodes[i], element[0]);
taDOM.<API key>(frag.childNodes[i], element[0]);
_tempFrag.appendChild(element[0]);
}
frag = _tempFrag;
if(lastNode){
lastNode = frag.childNodes[frag.childNodes.length - 1];
lastNode = lastNode.childNodes[lastNode.childNodes.length - 1];
}
}
}
}else{
range.deleteContents();
}
}
range.insertNode(frag);
if(lastNode){
api.<API key>(lastNode);
}
}
};
return api;
}]).service('taDOM', function(){
var taDOM = {
// recursive function that returns an array of angular.elements that have the passed attribute set on them
getByAttribute: function(element, attribute){
var resultingElements = [];
var childNodes = element.children();
if(childNodes.length){
angular.forEach(childNodes, function(child){
resultingElements = resultingElements.concat(taDOM.getByAttribute(angular.element(child), attribute));
});
}
if(element.attr(attribute) !== undefined) resultingElements.push(element);
return resultingElements;
},
transferChildNodes: function(source, target){
// clear out target
target.innerHTML = '';
while(source.childNodes.length > 0) target.appendChild(source.childNodes[0]);
return target;
},
splitNodes: function(nodes, target1, target2, splitNode, subSplitIndex, splitIndex){
if(!splitNode && isNaN(splitIndex)) throw new Error('taDOM.splitNodes requires a splitNode or splitIndex');
var startNodes = document.<API key>();
var endNodes = document.<API key>();
var index = 0;
while(nodes.length > 0 && (isNaN(splitIndex) || splitIndex !== index) && nodes[0] !== splitNode){
startNodes.appendChild(nodes[0]); // this removes from the nodes array (if proper childNodes object.
index++;
}
if(!isNaN(subSplitIndex) && subSplitIndex >= 0 && nodes[0]){
startNodes.appendChild(document.createTextNode(nodes[0].nodeValue.substring(0, subSplitIndex)));
nodes[0].nodeValue = nodes[0].nodeValue.substring(subSplitIndex);
}
while(nodes.length > 0) endNodes.appendChild(nodes[0]);
taDOM.transferChildNodes(startNodes, target1);
taDOM.transferChildNodes(endNodes, target2);
},
<API key>: function(source, target){
for(var i = 0; i < source.attributes.length; i++) target.setAttribute(source.attributes[i].name, source.attributes[i].value);
return target;
}
};
return taDOM;
});
angular.module('textAngular.validators', [])
.directive('taMaxText', function(){
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs, ctrl){
var max = parseInt(scope.$eval(attrs.taMaxText));
if (isNaN(max)){
throw('Max text must be an integer');
}
attrs.$observe('taMaxText', function(value){
max = parseInt(value);
if (isNaN(max)){
throw('Max text must be an integer');
}
if (ctrl.$dirty){
ctrl.$validate();
}
});
ctrl.$validators.taMaxText = function(viewValue){
var source = angular.element('<div/>');
source.html(viewValue);
return source.text().length <= max;
};
}
};
}).directive('taMinText', function(){
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs, ctrl){
var min = parseInt(scope.$eval(attrs.taMinText));
if (isNaN(min)){
throw('Min text must be an integer');
}
attrs.$observe('taMinText', function(value){
min = parseInt(value);
if (isNaN(min)){
throw('Min text must be an integer');
}
if (ctrl.$dirty){
ctrl.$validate();
}
});
ctrl.$validators.taMinText = function(viewValue){
var source = angular.element('<div/>');
source.html(viewValue);
return !source.text().length || source.text().length >= min;
};
}
};
});
angular.module('textAngular.taBind', ['textAngular.factories', 'textAngular.DOM'])
.service('_taBlankTest', [function(){
return function(_blankVal){
// we radically restructure this code.
// what was here before was incredibly fragile.
// What we do now is to check that the html is non-blank visually
// which we check by looking at html->text
if(!_blankVal) return true;
// find first non-tag match - ie start of string or after tag that is not whitespace
// var t0 = performance.now();
// Takes a small fraction of a mSec to do this...
var _text_ = stripHtmlToText(_blankVal);
// var t1 = performance.now();
// console.log('Took', (t1 - t0).toFixed(4), 'milliseconds to generate:');
if (_text_=== '') {
// img generates a visible item so it is not blank!
if (/<img[^>]+>/.test(_blankVal)) {
return false;
}
return true;
} else {
return false;
}
};
}])
.directive('taButton', [function(){
return {
link: function(scope, element, attrs){
element.attr('unselectable', 'on');
element.on('mousedown', function(e, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(e, eventData);
// this prevents focusout from firing on the editor when clicking toolbar buttons
e.preventDefault();
return false;
});
}
};
}])
.directive('taBind', [
'taSanitize', '$timeout', '$document', 'taFixChrome', 'taBrowserTag',
'taSelection', '<API key>', '<API key>', 'taOptions',
'_taBlankTest', '$parse', 'taDOM', 'textAngularManager',
function(
taSanitize, $timeout, $document, taFixChrome, taBrowserTag,
taSelection, <API key>, <API key>, taOptions,
_taBlankTest, $parse, taDOM, textAngularManager){
// Uses for this are textarea or input with ng-model and ta-bind='text'
// OR any non-form element with contenteditable="contenteditable" ta-bind="html|text" ng-model
return {
priority: 2, // So we override validators correctly
require: ['ngModel','?ngModelOptions'],
link: function(scope, element, attrs, controller){
var ngModel = controller[0];
var ngModelOptions = controller[1] || {};
// the option to use taBind on an input or textarea is required as it will sanitize all input into it correctly.
var _isContentEditable = element.attr('contenteditable') !== undefined && element.attr('contenteditable');
var _isInputFriendly = _isContentEditable || element[0].tagName.toLowerCase() === 'textarea' || element[0].tagName.toLowerCase() === 'input';
var _isReadonly = false;
var _focussed = false;
var _skipRender = false;
var _disableSanitizer = attrs.taUnsafeSanitizer || taOptions.disableSanitizer;
var _lastKey;
// NOTE Mute On|Off 173 (Opera MSIE Safari Chrome) 181 (Firefox)
// BLOCKED_KEYS are special keys...
// Tab, pause/break, CapsLock, Esc, Page Up, End, Home,
// Left arrow, Up arrow, Right arrow, Down arrow, Insert, Delete,
// f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12
// NumLock, ScrollLock
var BLOCKED_KEYS = /^(9|19|20|27|33|34|35|36|37|38|39|40|45|112|113|114|115|116|117|118|119|120|121|122|123|144|145)$/i;
// UNDO_TRIGGER_KEYS - spaces, enter, delete, backspace, all punctuation
// Backspace, Enter, Space, Delete, (; :) (Firefox), (= +) (Firefox),
// Numpad +, Numpad -, (; :), (= +),
// NOTE - Firefox: 173 = (- _) -- adding this to UNDO_TRIGGER_KEYS
var UNDO_TRIGGER_KEYS = /^(8|13|32|46|59|61|107|109|173|186|187|188|189|190|191|192|219|220|221|222)$/i;
var _pasteHandler;
// defaults to the paragraph element, but we need the line-break or it doesn't allow you to type into the empty element
// non IE is '<p><br/></p>', ie is '<p></p>' as for once IE gets it correct...
var _defaultVal, _defaultTest;
var _CTRL_KEY = 0x0001;
var _META_KEY = 0x0002;
var _ALT_KEY = 0x0004;
var _SHIFT_KEY = 0x0008;
// map events to special keys...
// mappings is an array of maps from events to specialKeys as declared in textAngularSetup
var _keyMappings = [
// ctrl/command + z
{
specialKey: 'UndoKey',
forbiddenModifiers: _ALT_KEY + _SHIFT_KEY,
mustHaveModifiers: [_META_KEY + _CTRL_KEY],
keyCode: 90
},
// ctrl/command + shift + z
{
specialKey: 'RedoKey',
forbiddenModifiers: _ALT_KEY,
mustHaveModifiers: [_META_KEY + _CTRL_KEY, _SHIFT_KEY],
keyCode: 90
},
// ctrl/command + y
{
specialKey: 'RedoKey',
forbiddenModifiers: _ALT_KEY + _SHIFT_KEY,
mustHaveModifiers: [_META_KEY + _CTRL_KEY],
keyCode: 89
},
// TabKey
{
specialKey: 'TabKey',
forbiddenModifiers: _META_KEY + _SHIFT_KEY + _ALT_KEY + _CTRL_KEY,
mustHaveModifiers: [],
keyCode: 9
},
// shift + TabKey
{
specialKey: 'ShiftTabKey',
forbiddenModifiers: _META_KEY + _ALT_KEY + _CTRL_KEY,
mustHaveModifiers: [_SHIFT_KEY],
keyCode: 9
}
];
function _mapKeys(event) {
var specialKey;
_keyMappings.forEach(function (map){
if (map.keyCode === event.keyCode) {
var netModifiers = (event.metaKey ? _META_KEY: 0) +
(event.ctrlKey ? _CTRL_KEY: 0) +
(event.shiftKey ? _SHIFT_KEY: 0) +
(event.altKey ? _ALT_KEY: 0);
if (map.forbiddenModifiers & netModifiers) return;
if (map.mustHaveModifiers.every(function (modifier) { return netModifiers & modifier; })){
specialKey = map.specialKey;
}
}
});
return specialKey;
}
// set the default to be a paragraph value
if(attrs.taDefaultWrap === undefined) attrs.taDefaultWrap = 'p';
/* istanbul ignore next: ie specific test */
if(attrs.taDefaultWrap === ''){
_defaultVal = '';
_defaultTest = (_browserDetect.ie === undefined)? '<div><br></div>' : (_browserDetect.ie >= 11)? '<p><br></p>' : (_browserDetect.ie <= 8)? '<P> </P>' : '<p> </p>';
}else{
_defaultVal = (_browserDetect.ie === undefined || _browserDetect.ie >= 11)?
'<' + attrs.taDefaultWrap + '><br></' + attrs.taDefaultWrap + '>' :
(_browserDetect.ie <= 8)?
'<' + attrs.taDefaultWrap.toUpperCase() + '></' + attrs.taDefaultWrap.toUpperCase() + '>' :
'<' + attrs.taDefaultWrap + '></' + attrs.taDefaultWrap + '>';
_defaultTest = (_browserDetect.ie === undefined || _browserDetect.ie >= 11)?
'<' + attrs.taDefaultWrap + '><br></' + attrs.taDefaultWrap + '>' :
(_browserDetect.ie <= 8)?
'<' + attrs.taDefaultWrap.toUpperCase() + '> </' + attrs.taDefaultWrap.toUpperCase() + '>' :
'<' + attrs.taDefaultWrap + '> </' + attrs.taDefaultWrap + '>';
}
/* istanbul ignore else */
if(!ngModelOptions.$options) ngModelOptions.$options = {}; // ng-model-options support
var <API key> = function(value) {
if (_taBlankTest(value)) return value;
var domTest = angular.element("<div>" + value + "</div>");
//console.log('domTest.children().length():', domTest.children().length);
//console.log('<API key>', domTest.children());
//console.log(value, attrs.taDefaultWrap);
if (domTest.children().length === 0) {
// if we have a <br> and the attrs.taDefaultWrap is a <p> we need to remove the <br>
//value = value.replace(/<br>/i, '');
value = "<" + attrs.taDefaultWrap + ">" + value + "</" + attrs.taDefaultWrap + ">";
} else {
var _children = domTest[0].childNodes;
var i;
var _foundBlockElement = false;
for (i = 0; i < _children.length; i++) {
if (_foundBlockElement = _children[i].nodeName.toLowerCase().match(BLOCKELEMENTS)) break;
}
if (!_foundBlockElement) {
value = "<" + attrs.taDefaultWrap + ">" + value + "</" + attrs.taDefaultWrap + ">";
}
else{
value = "";
for(i = 0; i < _children.length; i++){
var node = _children[i];
var nodeName = node.nodeName.toLowerCase();
//console.log('node#:', i, 'name:', nodeName);
if(nodeName === '#comment') {
value += '<!--' + node.nodeValue + '-->';
} else if(nodeName === '#text') {
// determine if this is all whitespace, if so, we will leave it as it is.
// otherwise, we will wrap it as it is
var text = node.textContent;
if (!text.trim()) {
// just whitespace
value += text;
} else {
// not pure white space so wrap in <p>...</p> or whatever attrs.taDefaultWrap is set to.
value += "<" + attrs.taDefaultWrap + ">" + text + "</" + attrs.taDefaultWrap + ">";
}
} else if(!nodeName.match(BLOCKELEMENTS)){
/* istanbul ignore next: Doesn't seem to trigger on tests */
var _subVal = (node.outerHTML || node.nodeValue);
/* istanbul ignore else: Doesn't seem to trigger on tests, is tested though */
if(_subVal.trim() !== '')
value += "<" + attrs.taDefaultWrap + ">" + _subVal + "</" + attrs.taDefaultWrap + ">";
else value += _subVal;
} else {
value += node.outerHTML;
}
//console.log(value);
}
}
}
//console.log(value);
return value;
};
if(attrs.taPaste) {
_pasteHandler = $parse(attrs.taPaste);
}
element.addClass('ta-bind');
var _undoKeyupTimeout;
scope['$undoManager' + (attrs.id || '')] = ngModel.$undoManager = {
_stack: [],
_index: 0,
_max: 1000,
push: function(value){
if((typeof value === "undefined" || value === null) ||
((typeof this.current() !== "undefined" && this.current() !== null) && value === this.current())) return value;
if(this._index < this._stack.length - 1){
this._stack = this._stack.slice(0,this._index+1);
}
this._stack.push(value);
if(_undoKeyupTimeout) $timeout.cancel(_undoKeyupTimeout);
if(this._stack.length > this._max) this._stack.shift();
this._index = this._stack.length - 1;
return value;
},
undo: function(){
return this.setToIndex(this._index-1);
},
redo: function(){
return this.setToIndex(this._index+1);
},
setToIndex: function(index){
if(index < 0 || index > this._stack.length - 1){
return undefined;
}
this._index = index;
return this.current();
},
current: function(){
return this._stack[this._index];
}
};
var _redoUndoTimeout;
var _undo = scope['$undoTaBind' + (attrs.id || '')] = function(){
/* istanbul ignore else: can't really test it due to all changes being ignored as well in readonly */
if(!_isReadonly && _isContentEditable){
var content = ngModel.$undoManager.undo();
if(typeof content !== "undefined" && content !== null){
_setInnerHTML(content);
_setViewValue(content, false);
if(_redoUndoTimeout) $timeout.cancel(_redoUndoTimeout);
_redoUndoTimeout = $timeout(function(){
element[0].focus();
taSelection.<API key>(element[0]);
}, 1);
}
}
};
var _redo = scope['$redoTaBind' + (attrs.id || '')] = function(){
/* istanbul ignore else: can't really test it due to all changes being ignored as well in readonly */
if(!_isReadonly && _isContentEditable){
var content = ngModel.$undoManager.redo();
if(typeof content !== "undefined" && content !== null){
_setInnerHTML(content);
_setViewValue(content, false);
/* istanbul ignore next */
if(_redoUndoTimeout) $timeout.cancel(_redoUndoTimeout);
_redoUndoTimeout = $timeout(function(){
element[0].focus();
taSelection.<API key>(element[0]);
}, 1);
}
}
};
// in here we are undoing the converts used elsewhere to prevent the < > and & being displayed when they shouldn't in the code.
var _compileHtml = function(){
if(_isContentEditable) {
return element[0].innerHTML;
}
if(_isInputFriendly) {
return element.val();
}
throw ('textAngular Error: attempting to update non-editable taBind');
};
var _setViewValue = function(_val, triggerUndo, skipRender){
_skipRender = skipRender || false;
if(typeof triggerUndo === "undefined" || triggerUndo === null) triggerUndo = true && _isContentEditable; // if not contentEditable then the native undo/redo is fine
if(typeof _val === "undefined" || _val === null) _val = _compileHtml();
if(_taBlankTest(_val)){
// this avoids us from tripping the ng-pristine flag if we click in and out with out typing
if(ngModel.$viewValue !== '') ngModel.$setViewValue('');
if(triggerUndo && ngModel.$undoManager.current() !== '') ngModel.$undoManager.push('');
}else{
<API key>();
if(ngModel.$viewValue !== _val){
ngModel.$setViewValue(_val);
if(triggerUndo) ngModel.$undoManager.push(_val);
}
}
ngModel.$render();
};
//used for updating when inserting wrapped elements
scope['updateTaBind' + (attrs.id || '')] = function(){
if(!_isReadonly) _setViewValue(undefined, undefined, true);
};
// catch DOM XSS via taSanitize
// Sanitizing both ways is identical
var _sanitize = function(unsafe){
return (ngModel.$oldViewValue = taSanitize(taFixChrome(unsafe), ngModel.$oldViewValue, _disableSanitizer));
};
// trigger the validation calls
if(element.attr('required')) ngModel.$validators.required = function(modelValue, viewValue) {
return !_taBlankTest(modelValue || viewValue);
};
// parsers trigger from the above keyup function or any other time that the viewValue is updated and parses it for storage in the ngModel
ngModel.$parsers.push(_sanitize);
ngModel.$parsers.unshift(<API key>);
// because textAngular is bi-directional (which is awesome) we need to also sanitize values going in from the server
ngModel.$formatters.push(_sanitize);
ngModel.$formatters.unshift(<API key>);
ngModel.$formatters.unshift(function(value){
return ngModel.$undoManager.push(value || '');
});
//this code is used to update the models when data is entered/deleted
if(_isInputFriendly){
scope.events = {};
if(!_isContentEditable){
// if a textarea or input just add in change and blur handlers, everything else is done by angulars input directive
element.on('change blur', scope.events.change = scope.events.blur = function(){
if(!_isReadonly) ngModel.$setViewValue(_compileHtml());
});
element.on('keydown', scope.events.keydown = function(event, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(event, eventData);
/* istanbul ignore else: otherwise normal functionality */
if(event.keyCode === 9){ // tab was pressed
// get caret position/selection
var start = this.selectionStart;
var end = this.selectionEnd;
var value = element.val();
if(event.shiftKey){
// find \t
var _linebreak = value.lastIndexOf('\n', start), _tab = value.lastIndexOf('\t', start);
if(_tab !== -1 && _tab >= _linebreak){
// set textarea value to: text before caret + tab + text after caret
element.val(value.substring(0, _tab) + value.substring(_tab + 1));
// put caret at right position again (add one for the tab)
this.selectionStart = this.selectionEnd = start - 1;
}
}else{
// set textarea value to: text before caret + tab + text after caret
element.val(value.substring(0, start) + "\t" + value.substring(end));
// put caret at right position again (add one for the tab)
this.selectionStart = this.selectionEnd = start + 1;
}
// prevent the focus lose
event.preventDefault();
}
});
var _repeat = function(string, n){
var result = '';
for(var _n = 0; _n < n; _n++) result += string;
return result;
};
// add a forEach function that will work on a NodeList, etc..
var forEach = function (array, callback, scope) {
for (var i= 0; i<array.length; i++) {
callback.call(scope, i, array[i]);
}
};
// handle <ul> or <ol> nodes
var recursiveListFormat = function(listNode, tablevel){
var _html = '';
var _subnodes = listNode.childNodes;
tablevel++;
// tab out and add the <ul> or <ol> html piece
_html += _repeat('\t', tablevel-1) + listNode.outerHTML.substring(0, 4);
forEach(_subnodes, function (index, node) {
/* istanbul ignore next: browser catch */
var nodeName = node.nodeName.toLowerCase();
if (nodeName === '#comment') {
_html += '<!--' + node.nodeValue + '-->';
return;
}
if (nodeName === '#text') {
_html += node.textContent;
return;
}
/* istanbul ignore next: not tested, and this was original code -- so not wanting to possibly cause an issue, leaving it... */
if(!node.outerHTML) {
// no html to add
return;
}
if(nodeName === 'ul' || nodeName === 'ol') {
_html += '\n' + recursiveListFormat(node, tablevel);
}
else {
// no reformatting within this subnode, so just do the tabing...
_html += '\n' + _repeat('\t', tablevel) + node.outerHTML;
}
});
// now add on the </ol> or </ul> piece
_html += '\n' + _repeat('\t', tablevel-1) + listNode.outerHTML.substring(listNode.outerHTML.lastIndexOf('<'));
return _html;
};
// handle formating of something like:
// <ol><!--First comment-->
// <li>Test Line 1<!--comment test list 1--></li>
// <ul><!--comment ul-->
// <li>Nested Line 1</li>
// <!--comment between nested lines--><li>Nested Line 2</li>
// <li>Test Line 3</li>
ngModel.$formatters.unshift(function(htmlValue){
// tabulate the HTML so it looks nicer
// first get a list of the nodes...
// we do this by using the element parser...
// doing this -- which is simpiler -- breaks our tests...
//var _nodes=angular.element(htmlValue);
var _nodes = angular.element('<div>' + htmlValue + '</div>')[0].childNodes;
if(_nodes.length > 0){
// do the reformatting of the layout...
htmlValue = '';
forEach(_nodes, function (index, node) {
var nodeName = node.nodeName.toLowerCase();
if (nodeName === '#comment') {
htmlValue += '<!--' + node.nodeValue + '-->';
return;
}
if (nodeName === '#text') {
htmlValue += node.textContent;
return;
}
/* istanbul ignore next: not tested, and this was original code -- so not wanting to possibly cause an issue, leaving it... */
if(!node.outerHTML)
{
// nothing to format!
return;
}
if(htmlValue.length > 0) {
// we aready have some content, so drop to a new line
htmlValue += '\n';
}
if(nodeName === 'ul' || nodeName === 'ol') {
// okay a set of list stuff we want to reformat in a nested way
htmlValue += '' + recursiveListFormat(node, 0);
}
else {
// just use the original without any additional formating
htmlValue += '' + node.outerHTML;
}
});
}
return htmlValue;
});
}else{
// all the code specific to contenteditable divs
var _processingPaste = false;
/* istanbul ignore next: phantom js cannot test this for some reason */
var processpaste = function(text) {
var _isOneNote = text!==undefined? text.match(/content=["']*OneNote.File/i): false;
/* istanbul ignore else: don't care if nothing pasted */
//console.log(text);
if(text && text.trim().length){
// test paste from word/microsoft product
if(text.match(/class=["']*Mso(Normal|List)/i) || text.match(/content=["']*Word.Document/i) || text.match(/content=["']*OneNote.File/i)){
var textFragment = text.match(/<!--StartFragment-->([\s\S]*?)<!--EndFragment-->/i);
if(!textFragment) textFragment = text;
else textFragment = textFragment[1];
textFragment = textFragment.replace(/<o:p>[\s\S]*?<\/o:p>/ig, '').replace(/class=(["']|)MsoNormal(["']|)/ig, '');
var dom = angular.element("<div>" + textFragment + "</div>");
var targetDom = angular.element("<div></div>");
var _list = {
element: null,
lastIndent: [],
lastLi: null,
isUl: false
};
_list.lastIndent.peek = function(){
var n = this.length;
if (n>0) return this[n-1];
};
var _resetList = function(isUl){
_list.isUl = isUl;
_list.element = angular.element(isUl ? "<ul>" : "<ol>");
_list.lastIndent = [];
_list.lastIndent.peek = function(){
var n = this.length;
if (n>0) return this[n-1];
};
_list.lastLevelMatch = null;
};
for(var i = 0; i <= dom[0].childNodes.length; i++){
if(!dom[0].childNodes[i] || dom[0].childNodes[i].nodeName === "#text"){
continue;
} else {
var tagName = dom[0].childNodes[i].tagName.toLowerCase();
if(tagName !== "p" && tagName !== "h1" && tagName !== "h2" && tagName !== "h3" && tagName !== "h4" && tagName !== "h5" && tagName !== "h6"){
continue;
}
}
var el = angular.element(dom[0].childNodes[i]);
var _listMatch = (el.attr('class') || '').match(/MsoList(Bullet|Number|Paragraph)(CxSp(First|Middle|Last)|)/i);
if(_listMatch){
if(el[0].childNodes.length < 2 || el[0].childNodes[1].childNodes.length < 1){
continue;
}
var isUl = _listMatch[1].toLowerCase() === "bullet" || (_listMatch[1].toLowerCase() !== "number" && !(/^[^0-9a-z<]*[0-9a-z]+[^0-9a-z<>]</i.test(el[0].childNodes[1].innerHTML) || /^[^0-9a-z<]*[0-9a-z]+[^0-9a-z<>]</i.test(el[0].childNodes[1].childNodes[0].innerHTML)));
var _indentMatch = (el.attr('style') || '').match(/margin-left:([\-\.0-9]*)/i);
var indent = parseFloat((_indentMatch)?_indentMatch[1]:0);
var _levelMatch = (el.attr('style') || '').match(/mso-list:l([0-9]+) level([0-9]+) lfo[0-9+]($|;)/i);
// prefers the mso-list syntax
if(_levelMatch && _levelMatch[2]) indent = parseInt(_levelMatch[2]);
if ((_levelMatch && (!_list.lastLevelMatch || _levelMatch[1] !== _list.lastLevelMatch[1])) || !_listMatch[3] || _listMatch[3].toLowerCase() === "first" || (_list.lastIndent.peek() === null) || (_list.isUl !== isUl && _list.lastIndent.peek() === indent)) {
_resetList(isUl);
targetDom.append(_list.element);
} else if (_list.lastIndent.peek() != null && _list.lastIndent.peek() < indent){
_list.element = angular.element(isUl ? "<ul>" : "<ol>");
_list.lastLi.append(_list.element);
} else if (_list.lastIndent.peek() != null && _list.lastIndent.peek() > indent){
while(_list.lastIndent.peek() != null && _list.lastIndent.peek() > indent){
if(_list.element.parent()[0].tagName.toLowerCase() === 'li'){
_list.element = _list.element.parent();
continue;
}else if(/[uo]l/i.test(_list.element.parent()[0].tagName.toLowerCase())){
_list.element = _list.element.parent();
}else{ // else it's it should be a sibling
break;
}
_list.lastIndent.pop();
}
_list.isUl = _list.element[0].tagName.toLowerCase() === "ul";
if (isUl !== _list.isUl) {
_resetList(isUl);
targetDom.append(_list.element);
}
}
_list.lastLevelMatch = _levelMatch;
if(indent !== _list.lastIndent.peek()) _list.lastIndent.push(indent);
_list.lastLi = angular.element("<li>");
_list.element.append(_list.lastLi);
_list.lastLi.html(el.html().replace(/<!(--|)\[if !supportLists\](--|)>[\s\S]*?<!(--|)\[endif\](--|)>/ig, ''));
el.remove();
}else{
_resetList(false);
targetDom.append(el);
}
}
var _unwrapElement = function(node){
node = angular.element(node);
for(var _n = node[0].childNodes.length - 1; _n >= 0; _n--) node.after(node[0].childNodes[_n]);
node.remove();
};
angular.forEach(targetDom.find('span'), function(node){
node.removeAttribute('lang');
if(node.attributes.length <= 0) _unwrapElement(node);
});
angular.forEach(targetDom.find('font'), _unwrapElement);
text = targetDom.html();
if(_isOneNote){
text = targetDom.html() || dom.html();
}
}else{
// remove unnecessary chrome insert
text = text.replace(/<(|\/)meta[^>]*?>/ig, '');
if(text.match(/<[^>]*?(ta-bind)[^>]*?>/)){
// entire text-angular or ta-bind has been pasted, REMOVE AT ONCE!!
if(text.match(/<[^>]*?(text-angular)[^>]*?>/)){
var _el = angular.element("<div>" + text + "</div>");
_el.find('textarea').remove();
var binds = taDOM.getByAttribute(_el, 'ta-bind');
for(var _b = 0; _b < binds.length; _b++){
var _target = binds[_b][0].parentNode.parentNode;
for(var _c = 0; _c < binds[_b][0].childNodes.length; _c++){
_target.parentNode.insertBefore(binds[_b][0].childNodes[_c], _target);
}
_target.parentNode.removeChild(_target);
}
text = _el.html().replace('<br class="<API key>">', '');
}
}else if(text.match(/^<span/)){
// in case of pasting only a span - chrome paste, remove them. THis is just some wierd formatting
// if we remove the '<span class="<API key>"> </span>' here we destroy the spacing
// on paste from even ourselves!
if (!text.match(/<span class=(\"<API key>\"|\'<API key>\')>.<\/span>/ig)) {
text = text.replace(/<(|\/)span[^>]*?>/ig, '');
}
}
// Webkit on Apple tags
text = text.replace(/<br class="<API key>"[^>]*?>/ig, '').replace(/<span class="<API key>">( | )<\/span>/ig, ' ');
}
if (/<li(\s.*)?>/i.test(text) && /(<ul(\s.*)?>|<ol(\s.*)?>).*<li(\s.*)?>/i.test(text) === false) {
// insert missing parent of li element
text = text.replace(/<li(\s.*)?>.*<\/li(\s.*)?>/i, '<ul>$&</ul>');
}
// parse whitespace from plaintext input, starting with preceding spaces that get stripped on paste
text = text.replace(/^[ |\u00A0]+/gm, function (match) {
var result = '';
for (var i = 0; i < match.length; i++) {
result += ' ';
}
return result;
}).replace(/\n|\r\n|\r/g, '<br />').replace(/\t/g, ' ');
if(_pasteHandler) text = _pasteHandler(scope, {$html: text}) || text;
text = taSanitize(text, '', _disableSanitizer);
taSelection.insertHtml(text, element[0]);
$timeout(function(){
ngModel.$setViewValue(_compileHtml());
_processingPaste = false;
element.removeClass('processing-paste');
}, 0);
}else{
_processingPaste = false;
element.removeClass('processing-paste');
}
};
element.on('paste', scope.events.paste = function(e, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(e, eventData);
if(_isReadonly || _processingPaste){
e.stopPropagation();
e.preventDefault();
return false;
}
// Code adapted from http://stackoverflow.com/questions/2176861/<API key>/6804718#6804718
_processingPaste = true;
element.addClass('processing-paste');
var pastedContent;
var clipboardData = (e.originalEvent || e).clipboardData;
if (clipboardData && clipboardData.getData && clipboardData.types.length > 0) {// Webkit - get data from clipboard, put into editdiv, cleanup, then cancel event
var _types = "";
for(var _t = 0; _t < clipboardData.types.length; _t++){
_types += " " + clipboardData.types[_t];
}
/* istanbul ignore next: browser tests */
if (/text\/html/i.test(_types)) {
pastedContent = clipboardData.getData('text/html');
} else if (/text\/plain/i.test(_types)) {
pastedContent = clipboardData.getData('text/plain');
}
processpaste(pastedContent);
e.stopPropagation();
e.preventDefault();
return false;
} else {// Everything else - empty editdiv and allow browser to paste content into it, then cleanup
var _savedSelection = rangy.saveSelection(),
_tempDiv = angular.element('<div class="ta-hidden-input" contenteditable="true"></div>');
$document.find('body').append(_tempDiv);
_tempDiv[0].focus();
$timeout(function(){
// restore selection
rangy.restoreSelection(_savedSelection);
processpaste(_tempDiv[0].innerHTML);
element[0].focus();
_tempDiv.remove();
}, 0);
}
});
element.on('cut', scope.events.cut = function(e){
// timeout to next is needed as otherwise the paste/cut event has not finished actually changing the display
if(!_isReadonly) $timeout(function(){
ngModel.$setViewValue(_compileHtml());
}, 0);
else e.preventDefault();
});
element.on('keydown', scope.events.keydown = function(event, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(event, eventData);
event.specialKey = _mapKeys(event);
var userSpecialKey;
/* istanbul ignore next: difficult to test */
taOptions.keyMappings.forEach(function (mapping) {
if (event.specialKey === mapping.commandKeyCode) {
// taOptions has remapped this binding... so
// we disable our own
event.specialKey = undefined;
}
if (mapping.testForKey(event)) {
userSpecialKey = mapping.commandKeyCode;
}
if ((mapping.commandKeyCode === 'UndoKey') || (mapping.commandKeyCode === 'RedoKey')) {
// this is necessary to fully stop the propagation.
if (!mapping.enablePropagation) {
event.preventDefault();
}
}
});
/* istanbul ignore next: difficult to test */
if (typeof userSpecialKey !== 'undefined') {
event.specialKey = userSpecialKey;
}
/* istanbul ignore next: difficult to test as can't seem to select */
if ((typeof event.specialKey !== 'undefined') && (
event.specialKey !== 'UndoKey' || event.specialKey !== 'RedoKey'
)) {
event.preventDefault();
textAngularManager.sendKeyCommand(scope, event);
}
/* istanbul ignore else: readonly check */
if(!_isReadonly){
if (event.specialKey==='UndoKey') {
_undo();
event.preventDefault();
}
if (event.specialKey==='RedoKey') {
_redo();
event.preventDefault();
}
/* istanbul ignore next: difficult to test as can't seem to select */
if(event.keyCode === 13 && !event.shiftKey){
var contains = function(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
};
var $selection;
var selection = taSelection.getSelectionElement();
if(!selection.tagName.match(VALIDELEMENTS)) return;
var _new = angular.element(_defaultVal);
// if we are in the last element of a blockquote, or ul or ol and the element is blank
// we need to pull the element outside of the said type
var moveOutsideElements = ['blockquote', 'ul', 'ol'];
if (contains(moveOutsideElements, selection.parentNode.tagName.toLowerCase())) {
if (/^<br(|\/)>$/i.test(selection.innerHTML.trim()) && !selection.nextSibling) {
// if last element is blank, pull element outside.
$selection = angular.element(selection);
var _parent = $selection.parent();
_parent.after(_new);
$selection.remove();
if (_parent.children().length === 0) _parent.remove();
taSelection.<API key>(_new[0]);
event.preventDefault();
}
if (/^<[^>]+><br(|\/)><\/[^>]+>$/i.test(selection.innerHTML.trim())) {
$selection = angular.element(selection);
$selection.after(_new);
$selection.remove();
taSelection.<API key>(_new[0]);
event.preventDefault();
}
}
}
}
});
var _keyupTimeout;
element.on('keyup', scope.events.keyup = function(event, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(event, eventData);
/* istanbul ignore next: FF specific bug fix */
if (event.keyCode === 9) {
var _selection = taSelection.getSelection();
if(_selection.start.element === element[0] && element.children().length) taSelection.<API key>(element.children()[0]);
return;
}
if(_undoKeyupTimeout) $timeout.cancel(_undoKeyupTimeout);
if(!_isReadonly && !BLOCKED_KEYS.test(event.keyCode)){
// if enter - insert new taDefaultWrap, if shift+enter insert <br/>
if(_defaultVal !== '' && event.keyCode === 13){
if(!event.shiftKey){
// new paragraph, br should be caught correctly
var selection = taSelection.getSelectionElement();
while(!selection.tagName.match(VALIDELEMENTS) && selection !== element[0]){
selection = selection.parentNode;
}
if(selection.tagName.toLowerCase() !==
attrs.taDefaultWrap &&
selection.tagName.toLowerCase() !== 'li' &&
(selection.innerHTML.trim() === '' || selection.innerHTML.trim() === '<br>')
) {
var _new = angular.element(_defaultVal);
angular.element(selection).replaceWith(_new);
taSelection.<API key>(_new[0]);
}
}
}
var val = _compileHtml();
if(_defaultVal !== '' && (val.trim() === '' || val.trim() === '<br>')){
_setInnerHTML(_defaultVal);
taSelection.<API key>(element.children()[0]);
}else if(val.substring(0, 1) !== '<' && attrs.taDefaultWrap !== ''){
/* we no longer do this, since there can be comments here and white space
var _savedSelection = rangy.saveSelection();
val = _compileHtml();
val = "<" + attrs.taDefaultWrap + ">" + val + "</" + attrs.taDefaultWrap + ">";
_setInnerHTML(val);
rangy.restoreSelection(_savedSelection);
*/
}
var triggerUndo = _lastKey !== event.keyCode && UNDO_TRIGGER_KEYS.test(event.keyCode);
if(_keyupTimeout) $timeout.cancel(_keyupTimeout);
_keyupTimeout = $timeout(function() {
_setViewValue(val, triggerUndo, true);
}, ngModelOptions.$options.debounce || 400);
if(!triggerUndo) _undoKeyupTimeout = $timeout(function(){ ngModel.$undoManager.push(val); }, 250);
_lastKey = event.keyCode;
}
});
element.on('blur', scope.events.blur = function(){
_focussed = false;
/* istanbul ignore else: if readonly don't update model */
if(!_isReadonly){
_setViewValue(undefined, undefined, true);
}else{
_skipRender = true; // don't redo the whole thing, just check the placeholder logic
ngModel.$render();
}
});
// Placeholders not supported on ie 8 and below
if(attrs.placeholder && (_browserDetect.ie > 8 || _browserDetect.ie === undefined)){
var rule;
if(attrs.id) rule = addCSSRule('#' + attrs.id + '.placeholder-text:before', 'content: "' + attrs.placeholder + '"');
else throw('textAngular Error: An unique ID is required for placeholders to work');
scope.$on('$destroy', function(){
removeCSSRule(rule);
});
}
element.on('focus', scope.events.focus = function(){
_focussed = true;
element.removeClass('placeholder-text');
<API key>();
});
element.on('mouseup', scope.events.mouseup = function(){
var _selection = taSelection.getSelection();
if(_selection.start.element === element[0] && element.children().length) taSelection.<API key>(element.children()[0]);
});
// prevent propagation on mousedown in editor, see #206
element.on('mousedown', scope.events.mousedown = function(event, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(event, eventData);
event.stopPropagation();
});
}
}
var <API key> = function(event){
// emit the element-select event, pass the element
scope.$emit('ta-element-select', this);
event.preventDefault();
return false;
};
var fileDropHandler = function(event, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(event, eventData);
// emit the drop event, pass the element, preventing should be done elsewhere
if(!dropFired && !_isReadonly){
dropFired = true;
var dataTransfer;
if(event.originalEvent) dataTransfer = event.originalEvent.dataTransfer;
else dataTransfer = event.dataTransfer;
scope.$emit('ta-drop-event', this, event, dataTransfer);
$timeout(function(){
dropFired = false;
_setViewValue(undefined, undefined, true);
}, 100);
}
};
//used for updating when inserting wrapped elements
var <API key> = scope['<API key>' + (attrs.id || '')] = function(){
/* istanbul ignore else */
if(!_isReadonly) angular.forEach(<API key>, function(selector){
// check we don't apply the handler twice
element.find(selector)
.off('click', <API key>)
.on('click', <API key>);
});
};
var _setInnerHTML = function(newval){
element[0].innerHTML = newval;
};
var _renderTimeout;
var _renderInProgress = false;
// changes to the model variable from outside the html/text inputs
ngModel.$render = function(){
/* istanbul ignore if: Catches rogue renders, hard to replicate in tests */
if(_renderInProgress) return;
else _renderInProgress = true;
// catch model being null or undefined
var val = ngModel.$viewValue || '';
// if the editor isn't focused it needs to be updated, otherwise it's receiving user input
if(!_skipRender){
/* istanbul ignore else: in other cases we don't care */
if(_isContentEditable && _focussed){
// update while focussed
element.removeClass('placeholder-text');
if(_renderTimeout) $timeout.cancel(_renderTimeout);
_renderTimeout = $timeout(function(){
/* istanbul ignore if: Can't be bothered testing this... */
if(!_focussed){
element[0].focus();
taSelection.<API key>(element.children()[element.children().length - 1]);
}
_renderTimeout = undefined;
}, 1);
}
if(_isContentEditable){
// WYSIWYG Mode
if(attrs.placeholder){
if(val === ''){
// blank
_setInnerHTML(_defaultVal);
}else{
// not-blank
_setInnerHTML(val);
}
}else{
_setInnerHTML((val === '') ? _defaultVal : val);
}
// if in WYSIWYG and readOnly we kill the use of links by clicking
if(!_isReadonly){
<API key>();
element.on('drop', fileDropHandler);
}else{
element.off('drop', fileDropHandler);
}
}else if(element[0].tagName.toLowerCase() !== 'textarea' && element[0].tagName.toLowerCase() !== 'input'){
// make sure the end user can SEE the html code as a display. This is a read-only display element
_setInnerHTML(<API key>(val));
}else{
// only for input and textarea inputs
element.val(val);
}
}
if(_isContentEditable && attrs.placeholder){
if(val === ''){
if(_focussed) element.removeClass('placeholder-text');
else element.addClass('placeholder-text');
}else{
element.removeClass('placeholder-text');
}
}
_renderInProgress = _skipRender = false;
};
if(attrs.taReadonly){
//set initial value
_isReadonly = scope.$eval(attrs.taReadonly);
if(_isReadonly){
element.addClass('ta-readonly');
// we changed to readOnly mode (taReadonly='true')
if(element[0].tagName.toLowerCase() === 'textarea' || element[0].tagName.toLowerCase() === 'input'){
element.attr('disabled', 'disabled');
}
if(element.attr('contenteditable') !== undefined && element.attr('contenteditable')){
element.removeAttr('contenteditable');
}
}else{
element.removeClass('ta-readonly');
// we changed to NOT readOnly mode (taReadonly='false')
if(element[0].tagName.toLowerCase() === 'textarea' || element[0].tagName.toLowerCase() === 'input'){
element.removeAttr('disabled');
}else if(_isContentEditable){
element.attr('contenteditable', 'true');
}
}
// taReadonly only has an effect if the taBind element is an input or textarea or has contenteditable='true' on it.
// Otherwise it is readonly by default
scope.$watch(attrs.taReadonly, function(newVal, oldVal){
if(oldVal === newVal) return;
if(newVal){
element.addClass('ta-readonly');
// we changed to readOnly mode (taReadonly='true')
if(element[0].tagName.toLowerCase() === 'textarea' || element[0].tagName.toLowerCase() === 'input'){
element.attr('disabled', 'disabled');
}
if(element.attr('contenteditable') !== undefined && element.attr('contenteditable')){
element.removeAttr('contenteditable');
}
// turn ON selector click handlers
angular.forEach(<API key>, function(selector){
element.find(selector).on('click', <API key>);
});
element.off('drop', fileDropHandler);
}else{
element.removeClass('ta-readonly');
// we changed to NOT readOnly mode (taReadonly='false')
if(element[0].tagName.toLowerCase() === 'textarea' || element[0].tagName.toLowerCase() === 'input'){
element.removeAttr('disabled');
}else if(_isContentEditable){
element.attr('contenteditable', 'true');
}
// remove the selector click handlers
angular.forEach(<API key>, function(selector){
element.find(selector).off('click', <API key>);
});
element.on('drop', fileDropHandler);
}
_isReadonly = newVal;
});
}
// Initialise the selectableElements
// if in WYSIWYG and readOnly we kill the use of links by clicking
if(_isContentEditable && !_isReadonly){
angular.forEach(<API key>, function(selector){
element.find(selector).on('click', <API key>);
});
element.on('drop', fileDropHandler);
}
}
};
}]);
// this global var is used to prevent multiple fires of the drop event. Needs to be global to the textAngular file.
var dropFired = false;
var textAngular = angular.module("textAngular", ['ngSanitize', 'textAngularSetup', 'textAngular.factories', 'textAngular.DOM', 'textAngular.validators', 'textAngular.taBind']); //This makes ngSanitize required
textAngular.config([function(){
// clear taTools variable. Just catches testing and any other time that this config may run multiple times...
angular.forEach(taTools, function(value, key){ delete taTools[key]; });
}]);
textAngular.directive("textAngular", [
'$compile', '$timeout', 'taOptions', 'taSelection', 'taExecCommand',
'textAngularManager', '$document', '$animate', '$log', '$q', '$parse',
function($compile, $timeout, taOptions, taSelection, taExecCommand,
textAngularManager, $document, $animate, $log, $q, $parse){
return {
require: '?ngModel',
scope: {},
restrict: "EA",
priority: 2, // So we override validators correctly
link: function(scope, element, attrs, ngModel){
// all these vars should not be accessable outside this directive
var _keydown, _keyup, _keypress, _mouseup, _focusin, _focusout,
_originalContents, _toolbars,
_serial = (attrs.serial) ? attrs.serial : Math.floor(Math.random() * 10000000000000000),
_taExecCommand, _resizeMouseDown, <API key>;
scope._name = (attrs.name) ? attrs.name : 'textAngularEditor' + _serial;
var oneEvent = function(_element, event, action){
$timeout(function(){
// shim the .one till fixed
var _func = function(){
_element.off(event, _func);
action.apply(this, arguments);
};
_element.on(event, _func);
}, 100);
};
_taExecCommand = taExecCommand(attrs.taDefaultWrap);
// get the settings from the defaults and add our specific functions that need to be on the scope
angular.extend(scope, angular.copy(taOptions), {
// wraps the selection in the provided tag / execCommand function. Should only be called in WYSIWYG mode.
wrapSelection: function(command, opt, <API key>){
if(command.toLowerCase() === "undo"){
scope['$<API key>' + _serial]();
}else if(command.toLowerCase() === "redo"){
scope['$<API key>' + _serial]();
}else{
// catch errors like FF erroring when you try to force an undo with nothing done
_taExecCommand(command, false, opt, scope.<API key>);
if(<API key>){
// re-apply the selectable tool events
scope['<API key>' + _serial]();
}
// refocus on the shown display element, this fixes a display bug when using :focus styles to outline the box.
// You still have focus on the text/html input it just doesn't show up
scope.displayElements.text[0].focus();
}
},
showHtml: scope.$eval(attrs.taShowHtml) || false
});
// setup the options from the optional attributes
if(attrs.taFocussedClass) scope.classes.focussed = attrs.taFocussedClass;
if(attrs.taTextEditorClass) scope.classes.textEditor = attrs.taTextEditorClass;
if(attrs.taHtmlEditorClass) scope.classes.htmlEditor = attrs.taHtmlEditorClass;
if(attrs.<API key>){
try {
// TODO: This should use angular.merge to enhance functionality once angular 1.4 is required
angular.extend(scope.<API key>, angular.fromJson(attrs.<API key>));
} catch (error) {
$log.error(error);
}
}
// optional setup functions
if(attrs.taTextEditorSetup) scope.setup.textEditorSetup = scope.$parent.$eval(attrs.taTextEditorSetup);
if(attrs.taHtmlEditorSetup) scope.setup.htmlEditorSetup = scope.$parent.$eval(attrs.taHtmlEditorSetup);
// optional fileDropHandler function
if(attrs.taFileDrop) scope.fileDropHandler = scope.$parent.$eval(attrs.taFileDrop);
else scope.fileDropHandler = scope.<API key>;
_originalContents = element[0].innerHTML;
// clear the original content
element[0].innerHTML = '';
// Setup the HTML elements as variable references for use later
scope.displayElements = {
// we still need the hidden input even with a textarea as the textarea may have invalid/old input in it,
// wheras the input will ALLWAYS have the correct value.
forminput: angular.element("<input type='hidden' tabindex='-1' style='display: none;'>"),
html: angular.element("<textarea></textarea>"),
text: angular.element("<div></div>"),
// other toolbased elements
scrollWindow: angular.element("<div class='ta-scroll-window'></div>"),
popover: angular.element('<div class="popover fade bottom" style="max-width: none; width: 305px;"></div>'),
popoverArrow: angular.element('<div class="arrow"></div>'),
popoverContainer: angular.element('<div class="popover-content"></div>'),
resize: {
overlay: angular.element('<div class="<API key>"></div>'),
background: angular.element('<div class="<API key>"></div>'),
anchors: [
angular.element('<div class="<API key> <API key>"></div>'),
angular.element('<div class="<API key> <API key>"></div>'),
angular.element('<div class="<API key> <API key>"></div>'),
angular.element('<div class="<API key> <API key>"></div>')
],
info: angular.element('<div class="<API key>"></div>')
}
};
// Setup the popover
scope.displayElements.popover.append(scope.displayElements.popoverArrow);
scope.displayElements.popover.append(scope.displayElements.popoverContainer);
scope.displayElements.scrollWindow.append(scope.displayElements.popover);
scope.displayElements.popover.on('mousedown', function(e, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(e, eventData);
// this prevents focusout from firing on the editor when clicking anything in the popover
e.preventDefault();
return false;
});
// define the popover show and hide functions
scope.showPopover = function(_el){
scope.displayElements.popover.css('display', 'block');
scope.reflowPopover(_el);
$animate.addClass(scope.displayElements.popover, 'in');
oneEvent($document.find('body'), 'click keyup', function(){scope.hidePopover();});
};
scope.reflowPopover = function(_el){
/* istanbul ignore if: catches only if near bottom of editor */
if(scope.displayElements.text[0].offsetHeight - 51 > _el[0].offsetTop){
scope.displayElements.popover.css('top', _el[0].offsetTop + _el[0].offsetHeight + scope.displayElements.scrollWindow[0].scrollTop + 'px');
scope.displayElements.popover.removeClass('top').addClass('bottom');
}else{
scope.displayElements.popover.css('top', _el[0].offsetTop - 54 + scope.displayElements.scrollWindow[0].scrollTop + 'px');
scope.displayElements.popover.removeClass('bottom').addClass('top');
}
var _maxLeft = scope.displayElements.text[0].offsetWidth - scope.displayElements.popover[0].offsetWidth;
var _targetLeft = _el[0].offsetLeft + (_el[0].offsetWidth / 2.0) - (scope.displayElements.popover[0].offsetWidth / 2.0);
scope.displayElements.popover.css('left', Math.max(0, Math.min(_maxLeft, _targetLeft)) + 'px');
scope.displayElements.popoverArrow.css('margin-left', (Math.min(_targetLeft, (Math.max(0, _targetLeft - _maxLeft))) - 11) + 'px');
};
scope.hidePopover = function(){
scope.displayElements.popover.css('display', '');
scope.displayElements.popoverContainer.attr('style', '');
scope.displayElements.popoverContainer.attr('class', 'popover-content');
scope.displayElements.popover.removeClass('in');
};
// setup the resize overlay
scope.displayElements.resize.overlay.append(scope.displayElements.resize.background);
angular.forEach(scope.displayElements.resize.anchors, function(anchor){ scope.displayElements.resize.overlay.append(anchor);});
scope.displayElements.resize.overlay.append(scope.displayElements.resize.info);
scope.displayElements.scrollWindow.append(scope.displayElements.resize.overlay);
// define the show and hide events
scope.reflowResizeOverlay = function(_el){
_el = angular.element(_el)[0];
scope.displayElements.resize.overlay.css({
'display': 'block',
'left': _el.offsetLeft - 5 + 'px',
'top': _el.offsetTop - 5 + 'px',
'width': _el.offsetWidth + 10 + 'px',
'height': _el.offsetHeight + 10 + 'px'
});
scope.displayElements.resize.info.text(_el.offsetWidth + ' x ' + _el.offsetHeight);
};
/* istanbul ignore next: pretty sure phantomjs won't test this */
scope.showResizeOverlay = function(_el){
var _body = $document.find('body');
_resizeMouseDown = function(event){
var startPosition = {
width: parseInt(_el.attr('width')),
height: parseInt(_el.attr('height')),
x: event.clientX,
y: event.clientY
};
if(startPosition.width === undefined || isNaN(startPosition.width)) startPosition.width = _el[0].offsetWidth;
if(startPosition.height === undefined || isNaN(startPosition.height)) startPosition.height = _el[0].offsetHeight;
scope.hidePopover();
var ratio = startPosition.height / startPosition.width;
var mousemove = function(event){
// calculate new size
var pos = {
x: Math.max(0, startPosition.width + (event.clientX - startPosition.x)),
y: Math.max(0, startPosition.height + (event.clientY - startPosition.y))
};
// DEFAULT: the aspect ratio is not locked unless the Shift key is pressed.
// attribute: <API key> -- locks resize into maintaing the aspect ratio
var bForceAspectRatio = (attrs.<API key> !== undefined);
// attribute: <API key>=true causes the space ratio to remain locked
// unless the Shift key is pressed
var bFlipKeyBinding = attrs.<API key>;
var bKeepRatio = bForceAspectRatio || (bFlipKeyBinding && !event.shiftKey);
if(bKeepRatio) {
var newRatio = pos.y / pos.x;
pos.x = ratio > newRatio ? pos.x : pos.y / ratio;
pos.y = ratio > newRatio ? pos.x * ratio : pos.y;
}
var el = angular.element(_el);
function roundedMaxVal(val) {
return Math.round(Math.max(0, val));
}
el.css('height', roundedMaxVal(pos.y) + 'px');
el.css('width', roundedMaxVal(pos.x) + 'px');
// reflow the popover tooltip
scope.reflowResizeOverlay(_el);
};
_body.on('mousemove', mousemove);
oneEvent(_body, 'mouseup', function(event){
event.preventDefault();
event.stopPropagation();
_body.off('mousemove', mousemove);
// at this point, we need to force the model to update! since the css has changed!
// this fixes bug: #862 - we now hide the popover -- as this seems more consitent.
// there are still issues under firefox, the window does not repaint. -- not sure
// how best to resolve this, but clicking anywhere works.
scope.$apply(function (){
scope.hidePopover();
scope.<API key>();
}, 100);
});
event.stopPropagation();
event.preventDefault();
};
scope.displayElements.resize.anchors[3].off('mousedown');
scope.displayElements.resize.anchors[3].on('mousedown', _resizeMouseDown);
scope.reflowResizeOverlay(_el);
oneEvent(_body, 'click', function(){scope.hideResizeOverlay();});
};
/* istanbul ignore next: pretty sure phantomjs won't test this */
scope.hideResizeOverlay = function(){
scope.displayElements.resize.anchors[3].off('mousedown', _resizeMouseDown);
scope.displayElements.resize.overlay.css('display', '');
};
// allow for insertion of custom directives on the textarea and div
scope.setup.htmlEditorSetup(scope.displayElements.html);
scope.setup.textEditorSetup(scope.displayElements.text);
scope.displayElements.html.attr({
'id': 'taHtmlElement' + _serial,
'ng-show': 'showHtml',
'ta-bind': 'ta-bind',
'ng-model': 'html',
'ng-model-options': element.attr('ng-model-options')
});
scope.displayElements.text.attr({
'id': 'taTextElement' + _serial,
'contentEditable': 'true',
'ta-bind': 'ta-bind',
'ng-model': 'html',
'ng-model-options': element.attr('ng-model-options')
});
scope.displayElements.scrollWindow.attr({'ng-hide': 'showHtml'});
if(attrs.taDefaultWrap) {
// taDefaultWrap is only applied to the text and not the html view
scope.displayElements.text.attr('ta-default-wrap', attrs.taDefaultWrap);
}
if(attrs.taUnsafeSanitizer){
scope.displayElements.text.attr('ta-unsafe-sanitizer', attrs.taUnsafeSanitizer);
scope.displayElements.html.attr('ta-unsafe-sanitizer', attrs.taUnsafeSanitizer);
}
// add the main elements to the origional element
scope.displayElements.scrollWindow.append(scope.displayElements.text);
element.append(scope.displayElements.scrollWindow);
element.append(scope.displayElements.html);
scope.displayElements.forminput.attr('name', scope._name);
element.append(scope.displayElements.forminput);
if(attrs.tabindex){
element.removeAttr('tabindex');
scope.displayElements.text.attr('tabindex', attrs.tabindex);
scope.displayElements.html.attr('tabindex', attrs.tabindex);
}
if (attrs.placeholder) {
scope.displayElements.text.attr('placeholder', attrs.placeholder);
scope.displayElements.html.attr('placeholder', attrs.placeholder);
}
if(attrs.taDisabled){
scope.displayElements.text.attr('ta-readonly', 'disabled');
scope.displayElements.html.attr('ta-readonly', 'disabled');
scope.disabled = scope.$parent.$eval(attrs.taDisabled);
scope.$parent.$watch(attrs.taDisabled, function(newVal){
scope.disabled = newVal;
if(scope.disabled){
element.addClass(scope.classes.disabled);
}else{
element.removeClass(scope.classes.disabled);
}
});
}
if(attrs.taPaste){
scope._pasteHandler = function(_html){
return $parse(attrs.taPaste)(scope.$parent, {$html: _html});
};
scope.displayElements.text.attr('ta-paste', '_pasteHandler($html)');
}
// compile the scope with the text and html elements only - if we do this with the main element it causes a compile loop
$compile(scope.displayElements.scrollWindow)(scope);
$compile(scope.displayElements.html)(scope);
scope.<API key> = scope['<API key>' + _serial];
scope.<API key> = scope['<API key>' + _serial];
// add the classes manually last
element.addClass("ta-root");
scope.displayElements.scrollWindow.addClass("ta-text ta-editor " + scope.classes.textEditor);
scope.displayElements.html.addClass("ta-html ta-editor " + scope.classes.htmlEditor);
// used in the toolbar actions
scope._actionRunning = false;
var _savedSelection = false;
scope.startAction = function(){
scope._actionRunning = true;
// if rangy library is loaded return a function to reload the current selection
_savedSelection = rangy.saveSelection();
return function(){
//console.log('restore to:', _savedSelection);
if(_savedSelection) rangy.restoreSelection(_savedSelection);
};
};
scope.endAction = function(){
scope._actionRunning = false;
if(_savedSelection){
if(scope.showHtml){
scope.displayElements.html[0].focus();
}else{
scope.displayElements.text[0].focus();
}
// rangy.restoreSelection(_savedSelection);
rangy.removeMarkers(_savedSelection);
}
_savedSelection = false;
scope.<API key>();
// only update if in text or WYSIWYG mode
if(!scope.showHtml) scope['<API key>' + _serial]();
};
// cascades to displayElements.text and displayElements.html automatically.
_focusin = function(){
scope.focussed = true;
element.addClass(scope.classes.focussed);
_toolbars.focus();
element.triggerHandler('focus');
};
scope.displayElements.html.on('focus', _focusin);
scope.displayElements.text.on('focus', _focusin);
_focusout = function(e){
// if we are NOT runnig an action and have NOT focussed again on the text etc then fire the blur events
if(!scope._actionRunning && $document[0].activeElement !== scope.displayElements.html[0] && $document[0].activeElement !== scope.displayElements.text[0]){
element.removeClass(scope.classes.focussed);
_toolbars.unfocus();
// to prevent multiple apply error defer to next seems to work.
$timeout(function(){
scope.<API key> = false;
element.triggerHandler('blur');
scope.focussed = false;
}, 0);
}
e.preventDefault();
return false;
};
scope.displayElements.html.on('blur', _focusout);
scope.displayElements.text.on('blur', _focusout);
scope.displayElements.text.on('paste', function(event){
element.triggerHandler('paste', event);
});
// Setup the default toolbar tools, this way allows the user to add new tools like plugins.
// This is on the editor for future proofing if we find a better way to do this.
scope.<API key> = function(command){
// $document[0].queryCommandValue('formatBlock') errors in Firefox if we call this when focussed on the textarea
return !scope.showHtml && command.toLowerCase() === $document[0].queryCommandValue('formatBlock').toLowerCase();
};
scope.queryCommandState = function(command){
// $document[0].queryCommandValue('formatBlock') errors in Firefox if we call this when focussed on the textarea
return (!scope.showHtml) ? $document[0].queryCommandState(command) : '';
};
scope.switchView = function(){
scope.showHtml = !scope.showHtml;
$animate.enabled(false, scope.displayElements.html);
$animate.enabled(false, scope.displayElements.text);
//Show the HTML view
/* istanbul ignore next: ngModel exists check */
/*
var _model;
if (ngModel) {
_model = ngModel.$viewValue;
} else {
_model = scope.html;
}
var _html = scope.displayElements.html[0].value;
if (getDomFromHtml(_html).childElementCount !== getDomFromHtml(_model).childElementCount) {
// the model and the html do not agree
// they can get out of sync and when they do, we correct that here...
scope.displayElements.html.val(_model);
}
*/
if(scope.showHtml){
//defer until the element is visible
$timeout(function(){
$animate.enabled(true, scope.displayElements.html);
$animate.enabled(true, scope.displayElements.text);
// [0] dereferences the DOM object from the angular.element
return scope.displayElements.html[0].focus();
}, 100);
}else{
//Show the WYSIWYG view
//defer until the element is visible
$timeout(function(){
$animate.enabled(true, scope.displayElements.html);
$animate.enabled(true, scope.displayElements.text);
// [0] dereferences the DOM object from the angular.element
return scope.displayElements.text[0].focus();
}, 100);
}
};
// changes to the model variable from outside the html/text inputs
// if no ngModel, then the only input is from inside text-angular
if(attrs.ngModel){
var _firstRun = true;
ngModel.$render = function(){
if(_firstRun){
// we need this firstRun to set the originalContents otherwise it gets overrided by the setting of ngModel to undefined from NaN
_firstRun = false;
// if view value is null or undefined initially and there was original content, set to the original content
var _initialValue = scope.$parent.$eval(attrs.ngModel);
if((_initialValue === undefined || _initialValue === null) && (_originalContents && _originalContents !== '')){
// on passing through to taBind it will be sanitised
ngModel.$setViewValue(_originalContents);
}
}
scope.displayElements.forminput.val(ngModel.$viewValue);
// if the editors aren't focused they need to be updated, otherwise they are doing the updating
scope.html = ngModel.$viewValue || '';
};
// trigger the validation calls
if(element.attr('required')) ngModel.$validators.required = function(modelValue, viewValue) {
var value = modelValue || viewValue;
return !(!value || value.trim() === '');
};
}else{
// if no ngModel then update from the contents of the origional html.
scope.displayElements.forminput.val(_originalContents);
scope.html = _originalContents;
}
// changes from taBind back up to here
scope.$watch('html', function(newValue, oldValue){
if(newValue !== oldValue){
if(attrs.ngModel && ngModel.$viewValue !== newValue) ngModel.$setViewValue(newValue);
scope.displayElements.forminput.val(newValue);
}
});
if(attrs.taTargetToolbars) _toolbars = textAngularManager.registerEditor(scope._name, scope, attrs.taTargetToolbars.split(','));
else{
var _toolbar = angular.element('<div <API key> name="textAngularToolbar' + _serial + '">');
// passthrough init of toolbar options
if(attrs.taToolbar) _toolbar.attr('ta-toolbar', attrs.taToolbar);
if(attrs.taToolbarClass) _toolbar.attr('ta-toolbar-class', attrs.taToolbarClass);
if(attrs.taToolbarGroupClass) _toolbar.attr('<API key>', attrs.taToolbarGroupClass);
if(attrs.<API key>) _toolbar.attr('<API key>', attrs.<API key>);
if(attrs.<API key>) _toolbar.attr('<API key>', attrs.<API key>);
if(attrs.taFocussedClass) _toolbar.attr('ta-focussed-class', attrs.taFocussedClass);
element.prepend(_toolbar);
$compile(_toolbar)(scope.$parent);
_toolbars = textAngularManager.registerEditor(scope._name, scope, ['textAngularToolbar' + _serial]);
}
scope.$on('$destroy', function(){
textAngularManager.unregisterEditor(scope._name);
angular.element(window).off('blur');
});
// catch element select event and pass to toolbar tools
scope.$on('ta-element-select', function(event, element){
if(_toolbars.<API key>(event, element)){
scope['<API key>' + _serial]();
}
});
scope.$on('ta-drop-event', function(event, element, dropEvent, dataTransfer){
scope.displayElements.text[0].focus();
if(dataTransfer && dataTransfer.files && dataTransfer.files.length > 0){
angular.forEach(dataTransfer.files, function(file){
// taking advantage of boolean execution, if the fileDropHandler returns true, nothing else after it is executed
// If it is false then execute the <API key> if the fileDropHandler is NOT the default one
// Once one of these has been executed wrap the result as a promise, if undefined or variable update the taBind, else we should wait for the promise
try{
$q.when(scope.fileDropHandler(file, scope.wrapSelection) ||
(scope.fileDropHandler !== scope.<API key> &&
$q.when(scope.<API key>(file, scope.wrapSelection)))).then(function(){
scope['<API key>' + _serial]();
});
}catch(error){
$log.error(error);
}
});
dropEvent.preventDefault();
dropEvent.stopPropagation();
/* istanbul ignore else, the updates if moved text */
}else{
$timeout(function(){
scope['<API key>' + _serial]();
}, 0);
}
});
// the following is for applying the active states to the tools that support it
scope.<API key> = false;
/* istanbul ignore next: browser window/tab leave check */
angular.element(window).on('blur', function(){
scope.<API key> = false;
scope.focussed = false;
});
// loop through all the tools polling their activeState function if it exists
scope.<API key> = function(){
var _selection;
/* istanbul ignore next: This check is to ensure multiple timeouts don't exist */
if(<API key>) $timeout.cancel(<API key>);
// test if the common element ISN'T the root ta-text node
if((_selection = taSelection.getSelectionElement()) !== undefined && _selection.parentNode !== scope.displayElements.text[0]){
_toolbars.<API key>(angular.element(_selection));
}else _toolbars.<API key>();
// used to update the active state when a key is held down, ie the left arrow
/* istanbul ignore else: browser only check */
if(scope.<API key>) <API key> = $timeout(scope.<API key>, 200);
};
// start updating on keydown
_keydown = function(){
/* istanbul ignore next: ie catch */
if(!scope.focussed){
scope.<API key> = false;
return;
}
/* istanbul ignore else: don't run if already running */
if(!scope.<API key>){
scope.<API key> = true;
scope.$apply(function(){
scope.<API key>();
});
}
};
scope.displayElements.html.on('keydown', _keydown);
scope.displayElements.text.on('keydown', _keydown);
// stop updating on key up and update the display/model
_keyup = function(){
scope.<API key> = false;
};
scope.displayElements.html.on('keyup', _keyup);
scope.displayElements.text.on('keyup', _keyup);
// stop updating on key up and update the display/model
_keypress = function(event, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(event, eventData);
scope.$apply(function(){
if(_toolbars.sendKeyCommand(event)){
/* istanbul ignore else: don't run if already running */
if(!scope.<API key>){
scope.<API key>();
}
event.preventDefault();
return false;
}
});
};
scope.displayElements.html.on('keypress', _keypress);
scope.displayElements.text.on('keypress', _keypress);
// update the toolbar active states when we click somewhere in the text/html boxed
_mouseup = function(){
// ensure only one execution of <API key>()
scope.<API key> = false;
scope.$apply(function(){
scope.<API key>();
});
};
scope.displayElements.html.on('mouseup', _mouseup);
scope.displayElements.text.on('mouseup', _mouseup);
}
};
}
]);
textAngular.service('textAngularManager', ['taToolExecuteAction', 'taTools', 'taRegisterTool', '$interval', '$rootScope', function(taToolExecuteAction, taTools, taRegisterTool, $interval, $rootScope){
// this service is used to manage all textAngular editors and toolbars.
// All publicly published functions that modify/need to access the toolbar or editor scopes should be in here
// these contain references to all the editors and toolbars that have been initialised in this app
var toolbars = {}, editors = {};
// toolbarScopes is an ARRAY of toolbar scopes
var toolbarScopes = [];
// we touch the time any change occurs through register of an editor or tool so that we
// in the future will fire and event to trigger an updateSelection
var <API key> = 0;
var updateStyles = function(selectedElement){
angular.forEach(editors, function(editor) {
editor.editorFunctions.<API key>(selectedElement);
});
};
var triggerInterval = 50;
var <API key>;
var <API key> = function() {
<API key> = Date.now();
/* istanbul ignore next: setup a one time updateStyles() */
<API key> = $interval(function() {
updateStyles();
<API key> = undefined;
}, triggerInterval, 1); // only trigger once
};
/* istanbul ignore next: make sure clean up on destroy */
$rootScope.$on('destroy', function() {
if (<API key>) {
$interval.cancel(<API key>);
<API key> = undefined;
}
});
var touchModification = function() {
if (Math.abs(Date.now() - <API key>) > triggerInterval) {
// we have already triggered the updateStyles a long time back... so setup it again...
<API key>();
}
};
// when we focus into a toolbar, we need to set the TOOLBAR's $parent to be the toolbars it's linked to.
// We also need to set the tools to be updated to be the toolbars...
return {
// register an editor and the toolbars that it is affected by
registerEditor: function(name, scope, targetToolbars){
// targetToolbars are optional, we don't require a toolbar to function
if(!name || name === '') throw('textAngular Error: An editor requires a name');
if(!scope) throw('textAngular Error: An editor requires a scope');
if(editors[name]) throw('textAngular Error: An Editor with name "' + name + '" already exists');
angular.forEach(targetToolbars, function(_name){
if(toolbars[_name]) toolbarScopes.push(toolbars[_name]);
// if it doesn't exist it may not have been compiled yet and it will be added later
});
editors[name] = {
scope: scope,
toolbars: targetToolbars,
<API key>: function(toolbarScope){
// add to the list late
if(this.toolbars.indexOf(toolbarScope.name) >= 0) toolbarScopes.push(toolbarScope);
},
// this is a suite of functions the editor should use to update all it's linked toolbars
editorFunctions: {
disable: function(){
// disable all linked toolbars
angular.forEach(toolbarScopes, function(toolbarScope){ toolbarScope.disabled = true; });
},
enable: function(){
// enable all linked toolbars
angular.forEach(toolbarScopes, function(toolbarScope){ toolbarScope.disabled = false; });
},
focus: function(){
// this should be called when the editor is focussed
angular.forEach(toolbarScopes, function(toolbarScope){
toolbarScope._parent = scope;
toolbarScope.disabled = false;
toolbarScope.focussed = true;
scope.focussed = true;
});
},
unfocus: function(){
// this should be called when the editor becomes unfocussed
angular.forEach(toolbarScopes, function(toolbarScope){
toolbarScope.disabled = true;
toolbarScope.focussed = false;
});
scope.focussed = false;
},
<API key>: function(selectedElement){
// update the active state of all buttons on liked toolbars
angular.forEach(toolbarScopes, function(toolbarScope){
angular.forEach(toolbarScope.tools, function(toolScope){
if(toolScope.activeState){
toolbarScope._parent = scope;
// selectedElement may be undefined if nothing selected
toolScope.active = toolScope.activeState(selectedElement);
}
});
});
},
sendKeyCommand: function(event){
// we return true if we applied an action, false otherwise
var result = false;
if(event.ctrlKey || event.metaKey || event.specialKey) angular.forEach(taTools, function(tool, name){
if(tool.commandKeyCode && (tool.commandKeyCode === event.which || tool.commandKeyCode === event.specialKey)){
for(var _t = 0; _t < toolbarScopes.length; _t++){
if(toolbarScopes[_t].tools[name] !== undefined){
taToolExecuteAction.call(toolbarScopes[_t].tools[name], scope);
result = true;
break;
}
}
}
});
return result;
},
<API key>: function(event, element){
// search through the taTools to see if a match for the tag is made.
// if there is, see if the tool is on a registered toolbar and not disabled.
// NOTE: This can trigger on MULTIPLE tools simultaneously.
var elementHasAttrs = function(_element, attrs){
var result = true;
for(var i = 0; i < attrs.length; i++) result = result && _element.attr(attrs[i]);
return result;
};
var workerTools = [];
var unfilteredTools = {};
var result = false;
element = angular.element(element);
// get all valid tools by element name, keep track if one matches the
var onlyWithAttrsFilter = false;
angular.forEach(taTools, function(tool, name){
if(
tool.onElementSelect &&
tool.onElementSelect.element &&
tool.onElementSelect.element.toLowerCase() === element[0].tagName.toLowerCase() &&
(!tool.onElementSelect.filter || tool.onElementSelect.filter(element))
){
// this should only end up true if the element matches the only attributes
onlyWithAttrsFilter = onlyWithAttrsFilter ||
(angular.isArray(tool.onElementSelect.onlyWithAttrs) && elementHasAttrs(element, tool.onElementSelect.onlyWithAttrs));
if(!tool.onElementSelect.onlyWithAttrs || elementHasAttrs(element, tool.onElementSelect.onlyWithAttrs)) unfilteredTools[name] = tool;
}
});
// if we matched attributes to filter on, then filter, else continue
if(onlyWithAttrsFilter){
angular.forEach(unfilteredTools, function(tool, name){
if(tool.onElementSelect.onlyWithAttrs && elementHasAttrs(element, tool.onElementSelect.onlyWithAttrs)) workerTools.push({'name': name, 'tool': tool});
});
// sort most specific (most attrs to find) first
workerTools.sort(function(a,b){
return b.tool.onElementSelect.onlyWithAttrs.length - a.tool.onElementSelect.onlyWithAttrs.length;
});
}else{
angular.forEach(unfilteredTools, function(tool, name){
workerTools.push({'name': name, 'tool': tool});
});
}
// Run the actions on the first visible filtered tool only
if(workerTools.length > 0){
for(var _i = 0; _i < workerTools.length; _i++){
var tool = workerTools[_i].tool;
var name = workerTools[_i].name;
for(var _t = 0; _t < toolbarScopes.length; _t++){
if(toolbarScopes[_t].tools[name] !== undefined){
tool.onElementSelect.action.call(toolbarScopes[_t].tools[name], event, element, scope);
result = true;
break;
}
}
if(result) break;
}
}
return result;
}
}
};
touchModification();
return editors[name].editorFunctions;
},
// retrieve editor by name, largely used by testing suites only
retrieveEditor: function(name){
return editors[name];
},
unregisterEditor: function(name){
delete editors[name];
touchModification();
},
// registers a toolbar such that it can be linked to editors
registerToolbar: function(scope){
if(!scope) throw('textAngular Error: A toolbar requires a scope');
if(!scope.name || scope.name === '') throw('textAngular Error: A toolbar requires a name');
if(toolbars[scope.name]) throw('textAngular Error: A toolbar with name "' + scope.name + '" already exists');
toolbars[scope.name] = scope;
angular.forEach(editors, function(_editor){
_editor.<API key>(scope);
});
touchModification();
},
// retrieve toolbar by name, largely used by testing suites only
retrieveToolbar: function(name){
return toolbars[name];
},
// retrieve toolbars by editor name, largely used by testing suites only
<API key>: function(name){
var result = [], _this = this;
angular.forEach(this.retrieveEditor(name).toolbars, function(name){
result.push(_this.retrieveToolbar(name));
});
return result;
},
unregisterToolbar: function(name){
delete toolbars[name];
// we remove the scope from the toolbarScopes so that we no longer have a memory leak.
var tmp = [];
for (var index in toolbarScopes) {
if (toolbarScopes[index].name !== name) {
tmp.push(toolbarScopes[index]);
}
}
toolbarScopes = tmp;
touchModification();
},
// functions for updating the toolbar buttons display
updateToolsDisplay: function(newTaTools){
// pass a partial struct of the taTools, this allows us to update the tools on the fly, will not change the defaults.
var _this = this;
angular.forEach(newTaTools, function(_newTool, key){
_this.updateToolDisplay(key, _newTool);
});
},
// this function resets all toolbars to their default tool definitions
resetToolsDisplay: function(){
var _this = this;
angular.forEach(taTools, function(_newTool, key){
_this.resetToolDisplay(key);
});
touchModification();
},
// update a tool on all toolbars
updateToolDisplay: function(toolKey, _newTool){
var _this = this;
angular.forEach(toolbars, function(toolbarScope, toolbarKey){
_this.<API key>(toolbarKey, toolKey, _newTool);
});
touchModification();
},
// resets a tool to the default/starting state on all toolbars
resetToolDisplay: function(toolKey){
var _this = this;
angular.forEach(toolbars, function(toolbarScope, toolbarKey){
_this.<API key>(toolbarKey, toolKey);
});
touchModification();
},
// update a tool on a specific toolbar
<API key>: function(toolbarKey, toolKey, _newTool){
if(toolbars[toolbarKey]) toolbars[toolbarKey].updateToolDisplay(toolKey, _newTool);
else throw('textAngular Error: No Toolbar with name "' + toolbarKey + '" exists');
},
// reset a tool on a specific toolbar to it's default starting value
<API key>: function(toolbarKey, toolKey){
if(toolbars[toolbarKey]) toolbars[toolbarKey].updateToolDisplay(toolKey, taTools[toolKey], true);
else throw('textAngular Error: No Toolbar with name "' + toolbarKey + '" exists');
},
// removes a tool from all toolbars and it's definition
removeTool: function(toolKey){
delete taTools[toolKey];
angular.forEach(toolbars, function(toolbarScope){
delete toolbarScope.tools[toolKey];
for(var i = 0; i < toolbarScope.toolbar.length; i++){
var toolbarIndex;
for(var j = 0; j < toolbarScope.toolbar[i].length; j++){
if(toolbarScope.toolbar[i][j] === toolKey){
toolbarIndex = {
group: i,
index: j
};
break;
}
if(toolbarIndex !== undefined) break;
}
if(toolbarIndex !== undefined){
toolbarScope.toolbar[toolbarIndex.group].slice(toolbarIndex.index, 1);
toolbarScope._$element.children().eq(toolbarIndex.group).children().eq(toolbarIndex.index).remove();
}
}
});
touchModification();
},
// toolkey, toolDefinition are required. If group is not specified will pick the last group, if index isnt defined will append to group
addTool: function(toolKey, toolDefinition, group, index){
taRegisterTool(toolKey, toolDefinition);
angular.forEach(toolbars, function(toolbarScope){
toolbarScope.addTool(toolKey, toolDefinition, group, index);
});
touchModification();
},
// adds a Tool but only to one toolbar not all
addToolToToolbar: function(toolKey, toolDefinition, toolbarKey, group, index){
taRegisterTool(toolKey, toolDefinition);
toolbars[toolbarKey].addTool(toolKey, toolDefinition, group, index);
touchModification();
},
// this is used when externally the html of an editor has been changed and textAngular needs to be notified to update the model.
// this will call a $digest if not already happening
refreshEditor: function(name){
if(editors[name]){
editors[name].scope.<API key>();
/* istanbul ignore else: phase catch */
if(!editors[name].scope.$$phase) editors[name].scope.$digest();
}else throw('textAngular Error: No Editor with name "' + name + '" exists');
touchModification();
},
// this is used by taBind to send a key command in response to a special key event
sendKeyCommand: function(scope, event){
var _editor = editors[scope._name];
/* istanbul ignore else: if nothing to do, do nothing */
if (_editor && _editor.editorFunctions.sendKeyCommand(event)) {
/* istanbul ignore else: don't run if already running */
if(!scope.<API key>){
scope.<API key>();
}
event.preventDefault();
return false;
}
},
// When a toolbar and tools are created, it isn't until there is a key event or mouse event
// that the <API key>() is called behind the scenes.
// This function forces an update through the existing editors to help the application make sure
// the inital state is correct.
updateStyles: updateStyles,
// return the current version of textAngular in use to the user
getVersion: function () { return textAngularVersion; },
// for testing
getToolbarScopes: function () { return toolbarScopes; }
};
}]);
textAngular.directive('textAngularToolbar', [
'$compile', 'textAngularManager', 'taOptions', 'taTools', 'taToolExecuteAction', '$window',
function($compile, textAngularManager, taOptions, taTools, taToolExecuteAction, $window){
return {
scope: {
name: '@' // a name IS required
},
restrict: "EA",
link: function(scope, element, attrs){
if(!scope.name || scope.name === '') throw('textAngular Error: A toolbar requires a name');
angular.extend(scope, angular.copy(taOptions));
if(attrs.taToolbar) scope.toolbar = scope.$parent.$eval(attrs.taToolbar);
if(attrs.taToolbarClass) scope.classes.toolbar = attrs.taToolbarClass;
if(attrs.taToolbarGroupClass) scope.classes.toolbarGroup = attrs.taToolbarGroupClass;
if(attrs.<API key>) scope.classes.toolbarButton = attrs.<API key>;
if(attrs.<API key>) scope.classes.toolbarButtonActive = attrs.<API key>;
if(attrs.taFocussedClass) scope.classes.focussed = attrs.taFocussedClass;
scope.disabled = true;
scope.focussed = false;
scope._$element = element;
element[0].innerHTML = '';
element.addClass("ta-toolbar " + scope.classes.toolbar);
scope.$watch('focussed', function(){
if(scope.focussed) element.addClass(scope.classes.focussed);
else element.removeClass(scope.classes.focussed);
});
var setupToolElement = function(toolDefinition, toolScope){
var toolElement;
if(toolDefinition && toolDefinition.display){
toolElement = angular.element(toolDefinition.display);
}
else toolElement = angular.element("<button type='button'>");
if(toolDefinition && toolDefinition["class"]) toolElement.addClass(toolDefinition["class"]);
else toolElement.addClass(scope.classes.toolbarButton);
toolElement.attr('name', toolScope.name);
// important to not take focus from the main text/html entry
toolElement.attr('ta-button', 'ta-button');
toolElement.attr('ng-disabled', 'isDisabled()');
toolElement.attr('tabindex', '-1');
toolElement.attr('ng-click', 'executeAction()');
toolElement.attr('ng-class', '<API key>(active)');
if (toolDefinition && toolDefinition.tooltiptext) {
toolElement.attr('title', toolDefinition.tooltiptext);
}
if(toolDefinition && !toolDefinition.display && !toolScope._display){
// first clear out the current contents if any
toolElement[0].innerHTML = '';
// add the buttonText
if(toolDefinition.buttontext) toolElement[0].innerHTML = toolDefinition.buttontext;
// add the icon to the front of the button if there is content
if(toolDefinition.iconclass){
var icon = angular.element('<i>'), content = toolElement[0].innerHTML;
icon.addClass(toolDefinition.iconclass);
toolElement[0].innerHTML = '';
toolElement.append(icon);
if(content && content !== '') toolElement.append(' ' + content);
}
}
toolScope._lastToolDefinition = angular.copy(toolDefinition);
return $compile(toolElement)(toolScope);
};
// Keep a reference for updating the active states later
scope.tools = {};
// create the tools in the toolbar
// default functions and values to prevent errors in testing and on init
scope._parent = {
disabled: true,
showHtml: false,
<API key>: function(){ return false; },
queryCommandState: function(){ return false; }
};
var defaultChildScope = {
$window: $window,
$editor: function(){
// dynamically gets the editor as it is set
return scope._parent;
},
isDisabled: function(){
// view selection button is always enabled since it doesn not depend on a selction!
if (this.name === 'html' && scope._parent.startAction) {
return false;
}
// to set your own disabled logic set a function or boolean on the tool called 'disabled'
return ( // this bracket is important as without it it just returns the first bracket and ignores the rest
// when the button's disabled function/value evaluates to true
(typeof this.$eval('disabled') !== 'function' && this.$eval('disabled')) || this.$eval('disabled()') ||
// all buttons except the HTML Switch button should be disabled in the showHtml (RAW html) mode
(this.name !== 'html' && this.$editor().showHtml) ||
// if the toolbar is disabled
this.$parent.disabled ||
// if the current editor is disabled
this.$editor().disabled
);
},
<API key>: function(active){
return (active)? scope.classes.toolbarButtonActive : '';
},
executeAction: taToolExecuteAction
};
angular.forEach(scope.toolbar, function(group){
// setup the toolbar group
var groupElement = angular.element("<div>");
groupElement.addClass(scope.classes.toolbarGroup);
angular.forEach(group, function(tool){
// init and add the tools to the group
// a tool name (key name from taTools struct)
//creates a child scope of the main angularText scope and then extends the childScope with the functions of this particular tool
// reference to the scope and element kept
scope.tools[tool] = angular.extend(scope.$new(true), taTools[tool], defaultChildScope, {name: tool});
scope.tools[tool].$element = setupToolElement(taTools[tool], scope.tools[tool]);
// append the tool compiled with the childScope to the group element
groupElement.append(scope.tools[tool].$element);
});
// append the group to the toolbar
element.append(groupElement);
});
// update a tool
// if a value is set to null, remove from the display
// when forceNew is set to true it will ignore all previous settings, used to reset to taTools definition
// to reset to defaults pass in taTools[key] as _newTool and forceNew as true, ie `updateToolDisplay(key, taTools[key], true);`
scope.updateToolDisplay = function(key, _newTool, forceNew){
var toolInstance = scope.tools[key];
if(toolInstance){
// get the last toolDefinition, then override with the new definition
if(toolInstance._lastToolDefinition && !forceNew) _newTool = angular.extend({}, toolInstance._lastToolDefinition, _newTool);
if(_newTool.buttontext === null && _newTool.iconclass === null && _newTool.display === null)
throw('textAngular Error: Tool Definition for updating "' + key + '" does not have a valid display/iconclass/buttontext value');
// if tool is defined on this toolbar, update/redo the tool
if(_newTool.buttontext === null){
delete _newTool.buttontext;
}
if(_newTool.iconclass === null){
delete _newTool.iconclass;
}
if(_newTool.display === null){
delete _newTool.display;
}
var toolElement = setupToolElement(_newTool, toolInstance);
toolInstance.$element.replaceWith(toolElement);
toolInstance.$element = toolElement;
}
};
// we assume here that all values passed are valid and correct
scope.addTool = function(key, _newTool, groupIndex, index){
scope.tools[key] = angular.extend(scope.$new(true), taTools[key], defaultChildScope, {name: key});
scope.tools[key].$element = setupToolElement(taTools[key], scope.tools[key]);
var group;
if(groupIndex === undefined) groupIndex = scope.toolbar.length - 1;
group = angular.element(element.children()[groupIndex]);
if(index === undefined){
group.append(scope.tools[key].$element);
scope.toolbar[groupIndex][scope.toolbar[groupIndex].length - 1] = key;
}else{
group.children().eq(index).after(scope.tools[key].$element);
scope.toolbar[groupIndex][index] = key;
}
};
textAngularManager.registerToolbar(scope);
scope.$on('$destroy', function(){
textAngularManager.unregisterToolbar(scope.name);
});
}
};
}
]);
textAngular.directive('textAngularVersion', ['textAngularManager',
function(textAngularManager) {
var version = textAngularManager.getVersion();
return {
restrict: "EA",
link: function (scope, element, attrs) {
element.html(version);
}
};
}
]); |
body {
opacity: 1;
-webkit-transition: opacity 1s ease;
-moz-transition: opacity 1s ease;
transition: opacity 1s;
}
.ng-cloak {
opacity: 0;
}
.ng-invalid {
border: 1px solid red !important;
}
section {
padding-top: 30px;
}
.page-header h1 > small > a {
color: #999;
}
.page-header h1 > small > a:hover {
text-decoration: none;
}
.footer {
text-align: center;
padding: 30px 0;
margin-top: 70px;
border-top: 1px solid #e5e5e5;
background-color: #f5f5f5;
}
.bs-social {
margin-top: 20px;
margin-bottom: 20px;
text-align: center;
}
@media (min-width: 768px) {
.bs-social {
text-align: left;
}
}
.nav, .pagination, .carousel, .panel-title a {
cursor: pointer;
}
.bs-social-buttons {
display: inline-block;
margin-bottom: 0;
padding-left: 0;
list-style: none;
}
.bs-social-buttons li {
display: inline-block;
padding: 5px 8px;
line-height: 1;
}
@media (max-width: 767px) {
.visible-xs.collapse.in {
display: block!important;
}
.visible-xs.collapse {
display: none!important;
}
}
.navbar-fixed-top .collapse {
border-top: 1px solid #e7e7e7;
margin-left: -15px;
margin-right: -15px;
padding-right: 15px;
padding-left: 15px;
}
.show-grid {
margin-bottom: 15px;
}
/*
* Container
*
* Tweak to width of container.
*/
/*@media (min-width: 1200px) {
.container{
max-width: 970px;
}
}*/
/*
* Tabs
*
* Tweaks to the Tabs.
*/
.code .nav-tabs {
border-bottom: 1px solid #ccc;
}
.code pre, .code code {
border-top: none;
<API key>: 0;
<API key>: 0;
}
.code .nav-tabs>li.active>a, .code .nav-tabs>li.active>a:hover, .code .nav-tabs>li.active>a:focus {
background-color: #f8f8f8;
border: 1px solid #ccc;
border-bottom-color: transparent;
}
/*
* Button Inverse
*
* Buttons in the masthead.
*/
.btn-outline-inverse {
color: #fff;
background-color: transparent;
border-color: #cdbfe3;
margin: 10px;
}
@media (min-width: 768px) {
.btn-outline-inverse {
width: auto;
margin: 20px 5px 20px 0;
padding: 18px 24px;
font-size: 21px;
}
}
.btn-outline-inverse:hover, .btn-outline-inverse:focus, .btn-outline-inverse:active {
color: #563d7c;
text-shadow: none;
background-color: #fff;
border-color: #fff;
}
/* Page headers */
.bs-header {
padding: 30px 15px 40px; /* side padding builds on .container 15px, so 30px */
font-size: 16px;
text-align: center;
text-shadow: 0 1px 0 rgba(0,0,0,.15);
color: #cdbfe3;
background-color: #563d7c;
background-image: url(header.png);
}
.bs-header a {
color: #fff;
font-weight: normal;
}
.bs-header h1 {
color: #fff;
}
.bs-header p {
font-weight: 200;
line-height: 1.4;
}
.bs-header .container {
position: relative;
}
@media (min-width: 768px) {
.bs-header {
font-size: 30px;
text-align: left;
}
.bs-header h1 {
font-size: 100px;
line-height: 1;
}
}
@media (min-width: 992px) {
.bs-header p {
margin-right: 25%;
}
}
.navbar-inner {
-webkit-box-shadow: 0 3px 3px rgba(0,0,0,0.175);
box-shadow: 0 3px 3px rgba(0,0,0,0.175);
}
/*
* Side navigation
*
* Scrollspy and affixed enhanced navigation to highlight sections and secondary
* sections of docs content.
*/
/* By default it's not affixed in mobile views, so undo that */
.bs-sidebar.affix {
position: static;
}
/* First level of nav */
.bs-sidenav {
margin-top: 30px;
margin-bottom: 30px;
padding-top: 10px;
padding-bottom: 10px;
text-shadow: 0 1px 0 #fff;
background-color: #f7f5fa;
border-radius: 5px;
}
/* All levels of nav */
.bs-sidebar .nav > li > a {
display: block;
color: #716b7a;
padding: 5px 20px;
}
.bs-sidebar .nav > li > a:hover,
.bs-sidebar .nav > li > a:focus {
text-decoration: none;
background-color: #e5e3e9;
border-right: 1px solid #dbd8e0;
}
.bs-sidebar .nav > .active > a,
.bs-sidebar .nav > .active:hover > a,
.bs-sidebar .nav > .active:focus > a {
font-weight: bold;
color: #563d7c;
background-color: transparent;
border-right: 1px solid #563d7c;
}
/* Nav: second level (shown on .active) */
.bs-sidebar .nav .nav {
display: none; /* Hide by default, but at >768px, show it */
margin-bottom: 8px;
}
.bs-sidebar .nav .nav > li > a {
padding-top: 3px;
padding-bottom: 3px;
padding-left: 30px;
font-size: 90%;
}
/* Show and affix the side nav when space allows it */
@media (min-width: 992px) {
.bs-sidebar .nav > .active > ul {
display: block;
}
/* Widen the fixed sidebar */
.bs-sidebar.affix,
.bs-sidebar.affix-bottom {
width: 213px;
}
.bs-sidebar.affix {
position: fixed; /* Undo the static from mobile first approach */
top: 80px;
}
.bs-sidebar.affix-bottom {
position: absolute; /* Undo the static from mobile first approach */
}
.bs-sidebar.affix-bottom .bs-sidenav,
.bs-sidebar.affix .bs-sidenav {
margin-top: 0;
margin-bottom: 0;
}
}
@media (min-width: 1200px) {
/* Widen the fixed sidebar again */
.bs-sidebar.affix-bottom,
.bs-sidebar.affix {
width: 263px;
}
}
/* Not enough room on mobile for markup tab, js tab, and plunk btn.
And no one cares about plunk button on a phone anyway */
@media only screen and (max-device-width: 480px) {
#plunk-btn {
display: none;
}
}
.navbar-nav .dropdown .navbar-brand {
max-width: 100%;
margin-right: inherit;
margin-left: inherit;
}
.header-placeholder {
height: 50px;
}
@media screen and (min-width: 768px) {
.dropdown.open > .navbar-brand + .dropdown-menu {
left: 10px;
}
.header-placeholder {
height: 50px;
}
.navbar-nav .dropdown .navbar-brand {
max-width: 200px;
margin-right: 5px;
margin-left: 10px;
}
} |
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "glib.h"
#include "gstdio.h"
static void
<API key> (void)
{
gchar buf[128];
gint res;
res = g_snprintf (buf, 0, "abc");
g_assert_cmpint (res, ==, 3);
res = g_snprintf (NULL, 0, "abc");
g_assert_cmpint (res, ==, 3);
res = g_snprintf (buf, 5, "abc");
g_assert_cmpint (res, ==, 3);
res = g_snprintf (buf, 1, "abc");
g_assert_cmpint (res, ==, 3);
g_assert (buf[0] == '\0');
g_assert_cmpstr (buf, ==, "");
res = g_snprintf (buf, 2, "abc");
g_assert_cmpint (res, ==, 3);
g_assert (buf[1] == '\0');
g_assert_cmpstr (buf, ==, "a");
res = g_snprintf (buf, 3, "abc");
g_assert_cmpint (res, ==, 3);
g_assert (buf[2] == '\0');
g_assert_cmpstr (buf, ==, "ab");
res = g_snprintf (buf, 4, "abc");
g_assert_cmpint (res, ==, 3);
g_assert (buf[3] == '\0');
g_assert_cmpstr (buf, ==, "abc");
res = g_snprintf (buf, 5, "abc");
g_assert_cmpint (res, ==, 3);
g_assert (buf[3] == '\0');
g_assert_cmpstr (buf, ==, "abc");
}
static void
test_d (void)
{
gchar buf[128];
gint res;
const gchar *fmt;
/* %d basic formatting */
res = g_snprintf (buf, 128, "%d", 5);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "5");
res = g_snprintf (buf, 128, "%d", 0);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "0");
res = g_snprintf (buf, 128, "%.0d", 0);
g_assert_cmpint (res, ==, 0);
g_assert_cmpstr (buf, ==, "");
res = g_snprintf (buf, 128, "%.0d", 1);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "1");
res = g_snprintf (buf, 128, "%.d", 2);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "2");
res = g_snprintf (buf, 128, "%d", -1);
g_assert_cmpint (res, ==, 2);
g_assert_cmpstr (buf, ==, "-1");
res = g_snprintf (buf, 128, "%.3d", 5);
g_assert_cmpint (res, ==, 3);
g_assert_cmpstr (buf, ==, "005");
res = g_snprintf (buf, 128, "%.3d", -5);
g_assert_cmpint (res, ==, 4);
g_assert_cmpstr (buf, ==, "-005");
res = g_snprintf (buf, 128, "%5.3d", 5);
g_assert_cmpint (res, ==, 5);
g_assert_cmpstr (buf, ==, " 005");
res = g_snprintf (buf, 128, "%-5.3d", -5);
g_assert_cmpint (res, ==, 5);
g_assert_cmpstr (buf, ==, "-005 ");
/* %d, length modifiers */
res = g_snprintf (buf, 128, "%" G_GINT16_FORMAT, (gint16)-5);
g_assert_cmpint (res, ==, 2);
g_assert_cmpstr (buf, ==, "-5");
res = g_snprintf (buf, 128, "%" G_GUINT16_FORMAT, (guint16)5);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "5");
res = g_snprintf (buf, 128, "%" G_GINT32_FORMAT, (gint32)-5);
g_assert_cmpint (res, ==, 2);
g_assert_cmpstr (buf, ==, "-5");
res = g_snprintf (buf, 128, "%" G_GUINT32_FORMAT, (guint32)5);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "5");
res = g_snprintf (buf, 128, "%" G_GINT64_FORMAT, (gint64)-5);
g_assert_cmpint (res, ==, 2);
g_assert_cmpstr (buf, ==, "-5");
res = g_snprintf (buf, 128, "%" G_GUINT64_FORMAT, (guint64)5);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "5");
res = g_snprintf (buf, 128, "%" G_GSSIZE_FORMAT, (gssize)-5);
g_assert_cmpint (res, ==, 2);
g_assert_cmpstr (buf, ==, "-5");
res = g_snprintf (buf, 128, "%" G_GSIZE_FORMAT, (gsize)5);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "5");
/* %d, flags */
res = g_snprintf (buf, 128, "%-d", 5);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "5");
res = g_snprintf (buf, 128, "%-+d", 5);
g_assert_cmpint (res, ==, 2);
g_assert_cmpstr (buf, ==, "+5");
res = g_snprintf (buf, 128, "%+-d", 5);
g_assert_cmpint (res, ==, 2);
g_assert_cmpstr (buf, ==, "+5");
res = g_snprintf (buf, 128, "%+d", -5);
g_assert_cmpint (res, ==, 2);
g_assert_cmpstr (buf, ==, "-5");
res = g_snprintf (buf, 128, "% d", 5);
g_assert_cmpint (res, ==, 2);
g_assert_cmpstr (buf, ==, " 5");
res = g_snprintf (buf, 128, "% .0d", 0);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, " ");
res = g_snprintf (buf, 128, "%03d", 5);
g_assert_cmpint (res, ==, 3);
g_assert_cmpstr (buf, ==, "005");
res = g_snprintf (buf, 128, "%03d", -5);
g_assert_cmpint (res, ==, 3);
g_assert_cmpstr (buf, ==, "-05");
/* gcc emits warnings for the following formats, since the C spec
* says some of the flags must be ignored. (The " " in "% +d" and
* the "0" in "%-03d".) But we need to test that our printf gets
* those rules right. So we fool gcc into not warning.
*/
fmt = "% +d";
res = g_snprintf (buf, 128, fmt, 5);
g_assert_cmpint (res, ==, 2);
g_assert_cmpstr (buf, ==, "+5");
fmt = "%-03d";
res = g_snprintf (buf, 128, fmt, -5);
g_assert_cmpint (res, ==, 3);
g_assert_cmpstr (buf, ==, "-5 ");
}
static void
test_o (void)
{
gchar buf[128];
gint res;
/* %o basic formatting */
res = g_snprintf (buf, 128, "%o", 5);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "5");
res = g_snprintf (buf, 128, "%o", 8);
g_assert_cmpint (res, ==, 2);
g_assert_cmpstr (buf, ==, "10");
res = g_snprintf (buf, 128, "%o", 0);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "0");
res = g_snprintf (buf, 128, "%.0o", 0);
g_assert_cmpint (res, ==, 0);
g_assert_cmpstr (buf, ==, "");
res = g_snprintf (buf, 128, "%.0o", 1);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "1");
res = g_snprintf (buf, 128, "%.3o", 5);
g_assert_cmpint (res, ==, 3);
g_assert_cmpstr (buf, ==, "005");
res = g_snprintf (buf, 128, "%.3o", 8);
g_assert_cmpint (res, ==, 3);
g_assert_cmpstr (buf, ==, "010");
res = g_snprintf (buf, 128, "%5.3o", 5);
g_assert_cmpint (res, ==, 5);
g_assert_cmpstr (buf, ==, " 005");
}
static void
test_u (void)
{
gchar buf[128];
gint res;
/* %u, basic formatting */
res = g_snprintf (buf, 128, "%u", 5);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "5");
res = g_snprintf (buf, 128, "%u", 0);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "0");
res = g_snprintf (buf, 128, "%.0u", 0);
g_assert_cmpint (res, ==, 0);
g_assert_cmpstr (buf, ==, "");
res = g_snprintf (buf, 128, "%.0u", 1);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "1");
res = g_snprintf (buf, 128, "%.3u", 5);
g_assert_cmpint (res, ==, 3);
g_assert_cmpstr (buf, ==, "005");
res = g_snprintf (buf, 128, "%5.3u", 5);
g_assert_cmpint (res, ==, 5);
g_assert_cmpstr (buf, ==, " 005");
}
static void
test_x (void)
{
gchar buf[128];
gint res;
/* %x, basic formatting */
res = g_snprintf (buf, 128, "%x", 5);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "5");
res = g_snprintf (buf, 128, "%x", 31);
g_assert_cmpint (res, ==, 2);
g_assert_cmpstr (buf, ==, "1f");
res = g_snprintf (buf, 128, "%x", 0);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "0");
res = g_snprintf (buf, 128, "%.0x", 0);
g_assert_cmpint (res, ==, 0);
g_assert_cmpstr (buf, ==, "");
res = g_snprintf (buf, 128, "%.0x", 1);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "1");
res = g_snprintf (buf, 128, "%.3x", 5);
g_assert_cmpint (res, ==, 3);
g_assert_cmpstr (buf, ==, "005");
res = g_snprintf (buf, 128, "%.3x", 31);
g_assert_cmpint (res, ==, 3);
g_assert_cmpstr (buf, ==, "01f");
res = g_snprintf (buf, 128, "%5.3x", 5);
g_assert_cmpint (res, ==, 5);
g_assert_cmpstr (buf, ==, " 005");
/* %x, flags */
res = g_snprintf (buf, 128, "%-x", 5);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "5");
res = g_snprintf (buf, 128, "%03x", 5);
g_assert_cmpint (res, ==, 3);
g_assert_cmpstr (buf, ==, "005");
res = g_snprintf (buf, 128, "%#x", 31);
g_assert_cmpint (res, ==, 4);
g_assert_cmpstr (buf, ==, "0x1f");
res = g_snprintf (buf, 128, "%#x", 0);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "0");
}
static void
test_X (void)
{
gchar buf[128];
gint res;
/* %X, basic formatting */
res = g_snprintf (buf, 128, "%X", 5);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "5");
res = g_snprintf (buf, 128, "%X", 31);
g_assert_cmpint (res, ==, 2);
g_assert_cmpstr (buf, ==, "1F");
res = g_snprintf (buf, 128, "%X", 0);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "0");
res = g_snprintf (buf, 128, "%.0X", 0);
g_assert_cmpint (res, ==, 0);
g_assert_cmpstr (buf, ==, "");
res = g_snprintf (buf, 128, "%.0X", 1);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "1");
res = g_snprintf (buf, 128, "%.3X", 5);
g_assert_cmpint (res, ==, 3);
g_assert_cmpstr (buf, ==, "005");
res = g_snprintf (buf, 128, "%.3X", 31);
g_assert_cmpint (res, ==, 3);
g_assert_cmpstr (buf, ==, "01F");
res = g_snprintf (buf, 128, "%5.3X", 5);
g_assert_cmpint (res, ==, 5);
g_assert_cmpstr (buf, ==, " 005");
/* %X, flags */
res = g_snprintf (buf, 128, "%-X", 5);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "5");
res = g_snprintf (buf, 128, "%03X", 5);
g_assert_cmpint (res, ==, 3);
g_assert_cmpstr (buf, ==, "005");
res = g_snprintf (buf, 128, "%#X", 31);
g_assert_cmpint (res, ==, 4);
g_assert_cmpstr (buf, ==, "0X1F");
res = g_snprintf (buf, 128, "%#X", 0);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "0");
}
static void
test_f (void)
{
gchar buf[128];
gint res;
/* %f, basic formattting */
res = g_snprintf (buf, 128, "%f", G_PI);
g_assert_cmpint (res, ==, 8);
g_assert (0 == strncmp (buf, "3.14159", 7));
res = g_snprintf (buf, 128, "%.8f", G_PI);
g_assert_cmpint (res, ==, 10);
g_assert (0 == strncmp (buf, "3.1415926", 9));
res = g_snprintf (buf, 128, "%.0f", G_PI);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "3");
res = g_snprintf (buf, 128, "%1.f", G_PI);
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "3");
res = g_snprintf (buf, 128, "%3.f", G_PI);
g_assert_cmpint (res, ==, 3);
g_assert_cmpstr (buf, ==, " 3");
/* %f, flags */
res = g_snprintf (buf, 128, "%+f", G_PI);
g_assert_cmpint (res, ==, 9);
g_assert (0 == strncmp (buf, "+3.14159", 8));
res = g_snprintf (buf, 128, "% f", G_PI);
g_assert_cmpint (res, ==, 9);
g_assert (0 == strncmp (buf, " 3.14159", 8));
res = g_snprintf (buf, 128, "%#.0f", G_PI);
g_assert_cmpint (res, ==, 2);
g_assert_cmpstr (buf, ==, "3.");
res = g_snprintf (buf, 128, "%05.2f", G_PI);
g_assert_cmpint (res, ==, 5);
g_assert_cmpstr (buf, ==, "03.14");
}
static gboolean
same_value (const gchar *actual,
const gchar *expected)
{
gdouble actual_value, expected_value;
actual_value = g_ascii_strtod (actual, NULL);
expected_value = g_ascii_strtod (expected, NULL);
return actual_value == expected_value;
}
static void
test_e (void)
{
gchar buf[128];
gint res;
/* %e, basic formatting */
/* for %e we can't expect to reproduce exact strings and lengths, since SUS
* only guarantees that the exponent shall always contain at least two
* digits. On Windows, it seems to be at least three digits long.
* Therefore, we compare the results of parsing the expected result and the
* actual result.
*/
res = g_snprintf (buf, 128, "%e", G_PI);
g_assert_cmpint (res, >=, 12);
g_assert (same_value (buf, "3.141593e+00"));
res = g_snprintf (buf, 128, "%.8e", G_PI);
g_assert_cmpint (res, >=, 14);
g_assert (same_value (buf, "3.14159265e+00"));
res = g_snprintf (buf, 128, "%.0e", G_PI);
g_assert_cmpint (res, >=, 5);
g_assert (same_value (buf, "3e+00"));
res = g_snprintf (buf, 128, "%.1e", 0.0);
g_assert_cmpint (res, >=, 7);
g_assert (same_value (buf, "0.0e+00"));
res = g_snprintf (buf, 128, "%.1e", 0.00001);
g_assert_cmpint (res, >=, 7);
g_assert (same_value (buf, "1.0e-05"));
res = g_snprintf (buf, 128, "%.1e", 10000.0);
g_assert_cmpint (res, >=, 7);
g_assert (same_value (buf, "1.0e+04"));
/* %e, flags */
res = g_snprintf (buf, 128, "%+e", G_PI);
g_assert_cmpint (res, >=, 13);
g_assert (same_value (buf, "+3.141593e+00"));
res = g_snprintf (buf, 128, "% e", G_PI);
g_assert_cmpint (res, >=, 13);
g_assert (same_value (buf, " 3.141593e+00"));
res = g_snprintf (buf, 128, "%#.0e", G_PI);
g_assert_cmpint (res, >=, 6);
g_assert (same_value (buf, "3.e+00"));
res = g_snprintf (buf, 128, "%09.2e", G_PI);
g_assert_cmpint (res, >=, 9);
g_assert (same_value (buf, "03.14e+00"));
}
static void
test_c (void)
{
gchar buf[128];
gint res;
res = g_snprintf (buf, 128, "%c", 'a');
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "a");
}
static void
test_s (void)
{
gchar buf[128];
gint res;
res = g_snprintf (buf, 128, "%.2s", "abc");
g_assert_cmpint (res, ==, 2);
g_assert_cmpstr (buf, ==, "ab");
res = g_snprintf (buf, 128, "%.6s", "abc");
g_assert_cmpint (res, ==, 3);
g_assert_cmpstr (buf, ==, "abc");
res = g_snprintf (buf, 128, "%5s", "abc");
g_assert_cmpint (res, ==, 5);
g_assert_cmpstr (buf, ==, " abc");
res = g_snprintf (buf, 128, "%-5s", "abc");
g_assert_cmpint (res, ==, 5);
g_assert_cmpstr (buf, ==, "abc ");
res = g_snprintf (buf, 128, "%5.2s", "abc");
g_assert_cmpint (res, ==, 5);
g_assert_cmpstr (buf, ==, " ab");
res = g_snprintf (buf, 128, "%*s", 5, "abc");
g_assert_cmpint (res, ==, 5);
g_assert_cmpstr (buf, ==, " abc");
#if 0 /* HP-UX doesn't get this right */
res = g_snprintf (buf, 128, "%*s", -5, "abc");
g_assert_cmpint (res, ==, 5);
g_assert_cmpstr (buf, ==, "abc ");
#endif
res = g_snprintf (buf, 128, "%*.*s", 5, 2, "abc");
g_assert_cmpint (res, ==, 5);
g_assert_cmpstr (buf, ==, " ab");
}
static void
test_n (void)
{
gchar buf[128];
gint res;
gint i;
glong l;
res = g_snprintf (buf, 128, "abc%n", &i);
g_assert_cmpint (res, ==, 3);
g_assert_cmpstr (buf, ==, "abc");
g_assert_cmpint (i, ==, 3);
res = g_snprintf (buf, 128, "abc%ln", &l);
g_assert_cmpint (res, ==, 3);
g_assert_cmpstr (buf, ==, "abc");
g_assert_cmpint (l, ==, 3);
}
static void
test_percent (void)
{
gchar buf[128];
gint res;
res = g_snprintf (buf, 128, "%%");
g_assert_cmpint (res, ==, 1);
g_assert_cmpstr (buf, ==, "%");
}
static void
<API key> (void)
{
gchar buf[128];
gint res;
res = g_snprintf (buf, 128, "%2$c %1$c", 'b', 'a');
g_assert_cmpint (res, ==, 3);
g_assert_cmpstr (buf, ==, "a b");
res = g_snprintf (buf, 128, "%1$*2$.*3$s", "abc", 5, 2);
g_assert_cmpint (res, ==, 5);
g_assert_cmpstr (buf, ==, " ab");
res = g_snprintf (buf, 128, "%1$s%1$s", "abc");
g_assert_cmpint (res, ==, 6);
g_assert_cmpstr (buf, ==, "abcabc");
}
static void
<API key> (void)
{
gint res;
if (g_test_trap_fork (0, <API key>))
{
res = g_printf ("%2$c %1$c", 'b', 'a');
g_assert_cmpint (res, ==, 3);
exit (0);
}
<API key> ();
<API key> ("*a b*");
if (g_test_trap_fork (0, <API key>))
{
res = g_printf ("%1$*2$.*3$s", "abc", 5, 2);
g_assert_cmpint (res, ==, 5);
exit (0);
}
<API key> ();
<API key> ("* ab*");
if (g_test_trap_fork (0, <API key>))
{
res = g_printf ("%1$s%1$s", "abc");
g_assert_cmpint (res, ==, 6);
exit (0);
}
<API key> ();
<API key> ("*abcabc*");
}
static void
<API key> (void)
{
gchar buf[128];
gint res;
res = g_sprintf (buf, "%2$c %1$c", 'b', 'a');
g_assert_cmpint (res, ==, 3);
g_assert_cmpstr (buf, ==, "a b");
res = g_sprintf (buf, "%1$*2$.*3$s", "abc", 5, 2);
g_assert_cmpint (res, ==, 5);
g_assert_cmpstr (buf, ==, " ab");
res = g_sprintf (buf, "%1$s%1$s", "abc");
g_assert_cmpint (res, ==, 6);
g_assert_cmpstr (buf, ==, "abcabc");
}
static void
test_percent2 (void)
{
gint res;
if (g_test_trap_fork (0, <API key>))
{
res = g_printf ("%%");
g_assert_cmpint (res, ==, 1);
exit (0);
}
<API key> ();
<API key> ("*%*");
}
static void
test_64bit (void)
{
gchar buf[128];
gint res;
res = g_snprintf (buf, 128, "%" G_GINT64_FORMAT, (gint64)123456);
g_assert_cmpint (res, ==, 6);
g_assert_cmpstr (buf, ==, "123456");
res = g_snprintf (buf, 128, "%" G_GINT64_FORMAT, (gint64)-123456);
g_assert_cmpint (res, ==, 7);
g_assert_cmpstr (buf, ==, "-123456");
res = g_snprintf (buf, 128, "%" G_GUINT64_FORMAT, (guint64)123456);
g_assert_cmpint (res, ==, 6);
g_assert_cmpstr (buf, ==, "123456");
res = g_snprintf (buf, 128, "%" G_GINT64_MODIFIER "o", (gint64)123456);
g_assert_cmpint (res, ==, 6);
g_assert_cmpstr (buf, ==, "361100");
res = g_snprintf (buf, 128, "%#" G_GINT64_MODIFIER "o", (gint64)123456);
g_assert_cmpint (res, ==, 7);
g_assert_cmpstr (buf, ==, "0361100");
res = g_snprintf (buf, 128, "%" G_GINT64_MODIFIER "x", (gint64)123456);
g_assert_cmpint (res, ==, 5);
g_assert_cmpstr (buf, ==, "1e240");
res = g_snprintf (buf, 128, "%#" G_GINT64_MODIFIER "x", (gint64)123456);
g_assert_cmpint (res, ==, 7);
g_assert_cmpstr (buf, ==, "0x1e240");
res = g_snprintf (buf, 128, "%" G_GINT64_MODIFIER "X", (gint64)123456);
g_assert_cmpint (res, ==, 5);
g_assert_cmpstr (buf, ==, "1E240");
#ifdef G_OS_WIN32
/* On Win32, test that the "ll" modifier also works, for backward
* compatibility. One really should use the G_GINT64_MODIFIER (which
* on Win32 is the "I64" that the (msvcrt) C library's printf uses),
* but "ll" used to work with the "trio" g_printf implementation in
* GLib 2.2, so it's best if it continues to work.
*/
res = g_snprintf (buf, 128, "%" "lli", (gint64)123456);
g_assert_cmpint (res, ==, 6);
g_assert_cmpstr (buf, ==, "123456");
res = g_snprintf (buf, 128, "%" "lli", (gint64)-123456);
g_assert_cmpint (res, ==, 7);
g_assert_cmpstr (buf, ==, "-123456");
res = g_snprintf (buf, 128, "%" "llu", (guint64)123456);
g_assert_cmpint (res, ==, 6);
g_assert_cmpstr (buf, ==, "123456");
res = g_snprintf (buf, 128, "%" "ll" "o", (gint64)123456);
g_assert_cmpint (res, ==, 6);
g_assert_cmpstr (buf, ==, "361100");
res = g_snprintf (buf, 128, "%#" "ll" "o", (gint64)123456);
g_assert_cmpint (res, ==, 7);
g_assert_cmpstr (buf, ==, "0361100");
res = g_snprintf (buf, 128, "%" "ll" "x", (gint64)123456);
g_assert_cmpint (res, ==, 5);
g_assert_cmpstr (buf, ==, "1e240");
res = g_snprintf (buf, 128, "%#" "ll" "x", (gint64)123456);
g_assert_cmpint (res, ==, 7);
g_assert_cmpstr (buf, ==, "0x1e240");
res = g_snprintf (buf, 128, "%" "ll" "X", (gint64)123456);
g_assert_cmpint (res, ==, 5);
g_assert_cmpstr (buf, ==, "1E240");
#endif
}
static void
test_64bit2 (void)
{
gint res;
if (g_test_trap_fork (0, <API key>))
{
res = g_printf ("%" G_GINT64_FORMAT, (gint64)123456);
g_assert_cmpint (res, ==, 6);
exit (0);
}
<API key> ();
<API key> ("*123456*");
if (g_test_trap_fork (0, <API key>))
{
res = g_printf ("%" G_GINT64_FORMAT, (gint64)-123456);
g_assert_cmpint (res, ==, 7);
exit (0);
}
<API key> ();
<API key> ("*-123456*");
if (g_test_trap_fork (0, <API key>))
{
res = g_printf ("%" G_GUINT64_FORMAT, (guint64)123456);
g_assert_cmpint (res, ==, 6);
exit (0);
}
<API key> ();
<API key> ("*123456*");
if (g_test_trap_fork (0, <API key>))
{
res = g_printf ("%" G_GINT64_MODIFIER "o", (gint64)123456);
g_assert_cmpint (res, ==, 6);
exit (0);
}
<API key> ();
<API key> ("*361100*");
if (g_test_trap_fork (0, <API key>))
{
res = g_printf ("%#" G_GINT64_MODIFIER "o", (gint64)123456);
g_assert_cmpint (res, ==, 7);
exit (0);
}
<API key> ();
<API key> ("*0361100*");
if (g_test_trap_fork (0, <API key>))
{
res = g_printf ("%" G_GINT64_MODIFIER "x", (gint64)123456);
g_assert_cmpint (res, ==, 5);
exit (0);
}
<API key> ();
<API key> ("*1e240*");
if (g_test_trap_fork (0, <API key>))
{
res = g_printf ("%#" G_GINT64_MODIFIER "x", (gint64)123456);
g_assert_cmpint (res, ==, 7);
exit (0);
}
<API key> ();
<API key> ("*0x1e240*");
if (g_test_trap_fork (0, <API key>))
{
res = g_printf ("%" G_GINT64_MODIFIER "X", (gint64)123456);
g_assert_cmpint (res, ==, 5);
exit (0);
}
<API key> ();
<API key> ("*1E240*");
#ifdef G_OS_WIN32
/* On Win32, test that the "ll" modifier also works, for backward
* compatibility. One really should use the G_GINT64_MODIFIER (which
* on Win32 is the "I64" that the (msvcrt) C library's printf uses),
* but "ll" used to work with the "trio" g_printf implementation in
* GLib 2.2, so it's best if it continues to work.
*/
if (g_test_trap_fork (0, <API key>))
{
res = g_printf ("%" "lli", (gint64)123456);
g_assert_cmpint (res, ==, 6);
exit (0);
}
<API key> ();
<API key> ("*123456*");
if (g_test_trap_fork (0, <API key>))
{
res = g_printf ("%" "lli", (gint64)-123456);
g_assert_cmpint (res, ==, 7);
exit (0);
}
<API key> ();
<API key> ("*-123456*");
if (g_test_trap_fork (0, <API key>))
{
res = g_printf ("%" "llu", (guint64)123456);
g_assert_cmpint (res, ==, 6);
exit (0);
}
<API key> ();
<API key> ("*123456*");
if (g_test_trap_fork (0, <API key>))
{
res = g_printf ("%" "ll" "o", (gint64)123456);
g_assert_cmpint (res, ==, 6);
exit (0);
}
<API key> ();
<API key> ("*361100*");
if (g_test_trap_fork (0, <API key>))
{
res = g_printf ("%#" "ll" "o", (gint64)123456);
g_assert_cmpint (res, ==, 7);
exit (0);
}
<API key> ();
<API key> ("*0361100*");
if (g_test_trap_fork (0, <API key>))
{
res = g_printf ("%" "ll" "x", (gint64)123456);
g_assert_cmpint (res, ==, 5);
exit (0);
}
<API key> ();
<API key> ("*1e240*");
if (g_test_trap_fork (0, <API key>))
{
res = g_printf ("%#" "ll" "x", (gint64)123456);
g_assert_cmpint (res, ==, 7);
exit (0);
}
<API key> ();
<API key> ("*0x1e240*");
if (g_test_trap_fork (0, <API key>))
{
res = g_printf ("%" "ll" "X", (gint64)123456);
g_assert_cmpint (res, ==, 5);
exit (0);
}
<API key> ();
<API key> ("*1E240*");
#endif
}
int
main (int argc,
char *argv[])
{
g_test_init (&argc, &argv, NULL);
g_test_add_func ("/snprintf/retval-and-trunc", <API key>);
g_test_add_func ("/snprintf/%d", test_d);
g_test_add_func ("/snprintf/%o", test_o);
g_test_add_func ("/snprintf/%u", test_u);
g_test_add_func ("/snprintf/%x", test_x);
g_test_add_func ("/snprintf/%X", test_X);
g_test_add_func ("/snprintf/%f", test_f);
g_test_add_func ("/snprintf/%e", test_e);
g_test_add_func ("/snprintf/%c", test_c);
g_test_add_func ("/snprintf/%s", test_s);
g_test_add_func ("/snprintf/%n", test_n);
g_test_add_func ("/snprintf/test-percent", test_percent);
g_test_add_func ("/snprintf/<API key>", <API key>);
g_test_add_func ("/snprintf/test-64bit", test_64bit);
g_test_add_func ("/printf/test-percent", test_percent2);
g_test_add_func ("/printf/<API key>", <API key>);
g_test_add_func ("/printf/test-64bit", test_64bit2);
g_test_add_func ("/sprintf/<API key>", <API key>);
return g_test_run();
} |
pre code {
display: block; padding: 0.5em;
color: #000;
background: #fff;
}
pre .subst,
pre .title {
font-weight: normal;
color: #000;
}
pre .comment,
pre .template_comment,
pre .javadoc,
pre .diff .header {
color: #808080;
font-style: italic;
}
pre .annotation,
pre .decorator,
pre .preprocessor,
pre .doctype,
pre .pi,
pre .chunk,
pre .shebang,
pre .apache .cbracket,
pre .input_number,
pre .http .title {
color: #808000;
}
pre .tag,
pre .pi {
background: #efefef;
}
pre .tag .title,
pre .id,
pre .attr_selector,
pre .pseudo,
pre .literal,
pre .keyword,
pre .hexcolor,
pre .css .function,
pre .ini .title,
pre .css .class,
pre .list .title,
pre .clojure .title,
pre .nginx .title,
pre .tex .command,
pre .request,
pre .status {
font-weight: bold;
color: #000080;
}
pre .attribute,
pre .rules .keyword,
pre .number,
pre .date,
pre .regexp,
pre .tex .special {
font-weight: bold;
color: #0000ff;
}
pre .number,
pre .regexp {
font-weight: normal;
}
pre .string,
pre .value,
pre .filter .argument,
pre .css .function .params,
pre .apache .tag {
color: #008000;
font-weight: bold;
}
pre .symbol,
pre .ruby .symbol .string,
pre .char,
pre .tex .formula {
color: #000;
background: #d0eded;
font-style: italic;
}
pre .phpdoc,
pre .yardoctag,
pre .javadoctag {
text-decoration: underline;
}
pre .variable,
pre .envvar,
pre .apache .sqbracket,
pre .nginx .built_in {
color: #660e7a;
}
pre .addition {
background: #baeeba;
}
pre .deletion {
background: #ffc8bd;
}
pre .diff .change {
background: #bccff9;
} |
<?php
// Moodle is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Moodle is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
require_once("$CFG->dirroot/mod/scorm/lib.php");
require_once("$CFG->libdir/filelib.php");
// Constants and settings for module scorm.
define('SCORM_UPDATE_NEVER', '0');
define('<API key>', '2');
define('<API key>', '3');
define('<API key>', '0');
define('<API key>', '1');
define('<API key>', '2');
define('SCO_ALL', 0);
define('SCO_DATA', 1);
define('SCO_ONLY', 2);
define('GRADESCOES', '0');
define('GRADEHIGHEST', '1');
define('GRADEAVERAGE', '2');
define('GRADESUM', '3');
define('HIGHESTATTEMPT', '0');
define('AVERAGEATTEMPT', '1');
define('FIRSTATTEMPT', '2');
define('LASTATTEMPT', '3');
define('TOCJSLINK', 1);
define('TOCFULLURL', 2);
// Local Library of functions for module scorm.
class <API key> extends file_info_stored {
public function get_parent() {
if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') {
return $this->browser->get_file_info($this->context);
}
return parent::get_parent();
}
public function get_visible_name() {
if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') {
return $this->topvisiblename;
}
return parent::get_visible_name();
}
}
/**
* Returns an array of the popup options for SCORM and each options default value
*
* @return array an array of popup options as the key and their defaults as the value
*/
function <API key>() {
$cfgscorm = get_config('scorm');
return array('scrollbars' => isset($cfgscorm->scrollbars) ? $cfgscorm->scrollbars : 0,
'directories' => isset($cfgscorm->directories) ? $cfgscorm->directories : 0,
'location' => isset($cfgscorm->location) ? $cfgscorm->location : 0,
'menubar' => isset($cfgscorm->menubar) ? $cfgscorm->menubar : 0,
'toolbar' => isset($cfgscorm->toolbar) ? $cfgscorm->toolbar : 0,
'status' => isset($cfgscorm->status) ? $cfgscorm->status : 0);
}
/**
* Returns an array of the array of what grade options
*
* @return array an array of what grade options
*/
function <API key>() {
return array (GRADESCOES => get_string('gradescoes', 'scorm'),
GRADEHIGHEST => get_string('gradehighest', 'scorm'),
GRADEAVERAGE => get_string('gradeaverage', 'scorm'),
GRADESUM => get_string('gradesum', 'scorm'));
}
/**
* Returns an array of the array of what grade options
*
* @return array an array of what grade options
*/
function <API key>() {
return array (HIGHESTATTEMPT => get_string('highestattempt', 'scorm'),
AVERAGEATTEMPT => get_string('averageattempt', 'scorm'),
FIRSTATTEMPT => get_string('firstattempt', 'scorm'),
LASTATTEMPT => get_string('lastattempt', 'scorm'));
}
/**
* Returns an array of the array of skip view options
*
* @return array an array of skip view options
*/
function <API key>() {
return array(<API key> => get_string('never'),
<API key> => get_string('firstaccess', 'scorm'),
<API key> => get_string('always'));
}
/**
* Returns an array of the array of hide table of contents options
*
* @return array an array of hide table of contents options
*/
function <API key>() {
return array(SCORM_TOC_SIDE => get_string('sided', 'scorm'),
SCORM_TOC_HIDDEN => get_string('hidden', 'scorm'),
SCORM_TOC_POPUP => get_string('popupmenu', 'scorm'),
SCORM_TOC_DISABLED => get_string('disabled', 'scorm'));
}
/**
* Returns an array of the array of update frequency options
*
* @return array an array of update frequency options
*/
function <API key>() {
return array(SCORM_UPDATE_NEVER => get_string('never'),
<API key> => get_string('everyday', 'scorm'),
<API key> => get_string('everytime', 'scorm'));
}
/**
* Returns an array of the array of popup display options
*
* @return array an array of popup display options
*/
function <API key>() {
return array(0 => get_string('currentwindow', 'scorm'),
1 => get_string('popup', 'scorm'));
}
/**
* Returns an array of the array of navigation buttons display options
*
* @return array an array of navigation buttons display options
*/
function <API key>() {
return array(SCORM_NAV_DISABLED => get_string('no'),
<API key> => get_string('undercontent', 'scorm'),
SCORM_NAV_FLOATING => get_string('floating', 'scorm'));
}
/**
* Returns an array of the array of attempt options
*
* @return array an array of attempt options
*/
function <API key>() {
$attempts = array(0 => get_string('nolimit', 'scorm'),
1 => get_string('attempt1', 'scorm'));
for ($i = 2; $i <= 6; $i++) {
$attempts[$i] = get_string('attemptsx', 'scorm', $i);
}
return $attempts;
}
/**
* Returns an array of the attempt status options
*
* @return array an array of attempt status options
*/
function <API key>() {
return array(<API key> => get_string('no'),
<API key> => get_string('attemptstatusall', 'scorm'),
<API key> => get_string('attemptstatusmy', 'scorm'),
<API key> => get_string('attemptstatusentry', 'scorm'));
}
/**
* Extracts scrom package, sets up all variables.
* Called whenever scorm changes
* @param object $scorm instance - fields are updated and changes saved into database
* @param bool $full force full update if true
* @return void
*/
function scorm_parse($scorm, $full) {
global $CFG, $DB;
$cfgscorm = get_config('scorm');
if (!isset($scorm->cmid)) {
$cm = <API key>('scorm', $scorm->id);
$scorm->cmid = $cm->id;
}
$context = context_module::instance($scorm->cmid);
$newhash = $scorm->sha1hash;
if ($scorm->scormtype === SCORM_TYPE_LOCAL or $scorm->scormtype === <API key>) {
$fs = get_file_storage();
$packagefile = false;
$<API key> = false;
if ($scorm->scormtype === SCORM_TYPE_LOCAL) {
if ($packagefile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, '/', $scorm->reference)) {
if ($packagefile->is_external_file()) { // Get zip file so we can check it is correct.
$packagefile-><API key>();
}
$newhash = $packagefile->get_contenthash();
if (strtolower($packagefile->get_filename()) == 'imsmanifest.xml') {
$<API key> = true;
}
} else {
$newhash = null;
}
} else {
if (!$cfgscorm->allowtypelocalsync) {
// Sorry - localsync disabled.
return;
}
if ($scorm->reference !== '') {
$fs->delete_area_files($context->id, 'mod_scorm', 'package');
$filerecord = array('contextid' => $context->id, 'component' => 'mod_scorm', 'filearea' => 'package',
'itemid' => 0, 'filepath' => '/');
if ($packagefile = $fs-><API key>($filerecord, $scorm->reference, array('calctimeout' => true), true)) {
$newhash = $packagefile->get_contenthash();
} else {
$newhash = null;
}
}
}
if ($packagefile) {
if (!$full and $packagefile and $scorm->sha1hash === $newhash) {
if (strpos($scorm->version, 'SCORM') !== false) {
if ($<API key> || $fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
// No need to update.
return;
}
} else if (strpos($scorm->version, 'AICC') !== false) {
// TODO: add more sanity checks - something really exists in scorm_content area.
return;
}
}
if (!$<API key>) {
// Now extract files.
$fs->delete_area_files($context->id, 'mod_scorm', 'content');
$packer = get_file_packer('application/zip');
$packagefile->extract_to_storage($packer, $context->id, 'mod_scorm', 'content', 0, '/');
}
} else if (!$full) {
return;
}
if ($<API key>) {
require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
// Direct link to imsmanifest.xml file.
if (!scorm_parse_scorm($scorm, $packagefile)) {
$scorm->version = 'ERROR';
}
} else if ($manifest = $fs->get_file($context->id, 'mod_scorm', 'content', 0, '/', 'imsmanifest.xml')) {
require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
// SCORM.
if (!scorm_parse_scorm($scorm, $manifest)) {
$scorm->version = 'ERROR';
}
} else {
require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
// AICC.
$result = scorm_parse_aicc($scorm);
if (!$result) {
$scorm->version = 'ERROR';
} else {
$scorm->version = 'AICC';
}
}
} else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL and $cfgscorm->allowtypeexternal) {
require_once("$CFG->dirroot/mod/scorm/datamodels/scormlib.php");
// SCORM only, AICC can not be external.
if (!scorm_parse_scorm($scorm, $scorm->reference)) {
$scorm->version = 'ERROR';
}
$newhash = sha1($scorm->reference);
} else if ($scorm->scormtype === SCORM_TYPE_AICCURL and $cfgscorm-><API key>) {
require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
// AICC.
$result = scorm_parse_aicc($scorm);
if (!$result) {
$scorm->version = 'ERROR';
} else {
$scorm->version = 'AICC';
}
} else {
// Sorry, disabled type.
return;
}
$scorm->revision++;
$scorm->sha1hash = $newhash;
$DB->update_record('scorm', $scorm);
}
function scorm_array_search($item, $needle, $haystacks, $strict=false) {
if (!empty($haystacks)) {
foreach ($haystacks as $key => $element) {
if ($strict) {
if ($element->{$item} === $needle) {
return $key;
}
} else {
if ($element->{$item} == $needle) {
return $key;
}
}
}
}
return false;
}
function scorm_repeater($what, $times) {
if ($times <= 0) {
return null;
}
$return = '';
for ($i = 0; $i < $times; $i++) {
$return .= $what;
}
return $return;
}
function scorm_external_link($link) {
// Check if a link is external.
$result = false;
$link = strtolower($link);
if (substr($link, 0, 7) == 'http:
$result = true;
} else if (substr($link, 0, 8) == 'https:
$result = true;
} else if (substr($link, 0, 4) == 'www.') {
$result = true;
}
return $result;
}
/**
* Returns an object containing all datas relative to the given sco ID
*
* @param integer $id The sco ID
* @return mixed (false if sco id does not exists)
*/
function scorm_get_sco($id, $what=SCO_ALL) {
global $DB;
if ($sco = $DB->get_record('scorm_scoes', array('id' => $id))) {
$sco = ($what == SCO_DATA) ? new stdClass() : $sco;
if (($what != SCO_ONLY) && ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid' => $id)))) {
foreach ($scodatas as $scodata) {
$sco->{$scodata->name} = $scodata->value;
}
} else if (($what != SCO_ONLY) && (!($scodatas = $DB->get_records('scorm_scoes_data', array('scoid' => $id))))) {
$sco->parameters = '';
}
return $sco;
} else {
return false;
}
}
/**
* Returns an object (array) containing all the scoes data related to the given sco ID
*
* @param integer $id The sco ID
* @param integer $organisation an organisation ID - defaults to false if not required
* @return mixed (false if there are no scoes or an array)
*/
function scorm_get_scoes($id, $organisation=false) {
global $DB;
$queryarray = array('scorm' => $id);
if (!empty($organisation)) {
$queryarray['organization'] = $organisation;
}
if ($scoes = $DB->get_records('scorm_scoes', $queryarray, 'sortorder, id')) {
// Drop keys so that it is a simple array as expected.
$scoes = array_values($scoes);
foreach ($scoes as $sco) {
if ($scodatas = $DB->get_records('scorm_scoes_data', array('scoid' => $sco->id))) {
foreach ($scodatas as $scodata) {
$sco->{$scodata->name} = $scodata->value;
}
}
}
return $scoes;
} else {
return false;
}
}
function scorm_insert_track($userid, $scormid, $scoid, $attempt, $element, $value, $forcecompleted=false, $trackdata = null) {
global $DB, $CFG;
$id = null;
if ($forcecompleted) {
// TODO - this could be broadened to encompass SCORM 2004 in future.
if (($element == 'cmi.core.lesson_status') && ($value == 'incomplete')) {
if ($track = $DB->get_record_select('scorm_scoes_track',
'userid=? AND scormid=? AND scoid=? AND attempt=? '.
'AND element=\'cmi.core.score.raw\'',
array($userid, $scormid, $scoid, $attempt))) {
$value = 'completed';
}
}
if ($element == 'cmi.core.score.raw') {
if ($tracktest = $DB->get_record_select('scorm_scoes_track',
'userid=? AND scormid=? AND scoid=? AND attempt=? '.
'AND element=\'cmi.core.lesson_status\'',
array($userid, $scormid, $scoid, $attempt))) {
if ($tracktest->value == "incomplete") {
$tracktest->value = "completed";
$DB->update_record('scorm_scoes_track', $tracktest);
}
}
}
if (($element == 'cmi.success_status') && ($value == 'passed' || $value == 'failed')) {
if ($DB->get_record('scorm_scoes_data', array('scoid' => $scoid, 'name' => '<API key>'))) {
$<API key> = true;
$<API key> = false;
if ($value == 'passed') {
$<API key> = true;
}
if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
'scormid' => $scormid,
'scoid' => $scoid,
'attempt' => $attempt,
'element' => '<API key>'))) {
$track->value = $<API key>;
$track->timemodified = time();
$DB->update_record('scorm_scoes_track', $track);
$id = $track->id;
} else {
$track = new stdClass();
$track->userid = $userid;
$track->scormid = $scormid;
$track->scoid = $scoid;
$track->attempt = $attempt;
$track->element = '<API key>';
$track->value = $<API key>;
$track->timemodified = time();
$id = $DB->insert_record('scorm_scoes_track', $track);
}
if ($<API key>) {
if ($track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
'scormid' => $scormid,
'scoid' => $scoid,
'attempt' => $attempt,
'element' => '<API key>'))) {
$track->value = $<API key>;
$track->timemodified = time();
$DB->update_record('scorm_scoes_track', $track);
$id = $track->id;
} else {
$track = new stdClass();
$track->userid = $userid;
$track->scormid = $scormid;
$track->scoid = $scoid;
$track->attempt = $attempt;
$track->element = '<API key>';
$track->value = $<API key>;
$track->timemodified = time();
$id = $DB->insert_record('scorm_scoes_track', $track);
}
}
}
}
}
$track = null;
if ($trackdata !== null) {
if (isset($trackdata[$element])) {
$track = $trackdata[$element];
}
} else {
$track = $DB->get_record('scorm_scoes_track', array('userid' => $userid,
'scormid' => $scormid,
'scoid' => $scoid,
'attempt' => $attempt,
'element' => $element));
}
if ($track) {
if ($element != 'x.start.time' ) { // Don't update x.start.time - keep the original value.
if ($track->value != $value) {
$track->value = $value;
$track->timemodified = time();
$DB->update_record('scorm_scoes_track', $track);
}
$id = $track->id;
}
} else {
$track = new stdClass();
$track->userid = $userid;
$track->scormid = $scormid;
$track->scoid = $scoid;
$track->attempt = $attempt;
$track->element = $element;
$track->value = $value;
$track->timemodified = time();
$id = $DB->insert_record('scorm_scoes_track', $track);
$track->id = $id;
}
// Trigger updating grades based on a given set of SCORM CMI elements.
$scorm = false;
if (strstr($element, '.score.raw') ||
(in_array($element, array('cmi.completion_status', 'cmi.core.lesson_status', 'cmi.success_status'))
&& in_array($track->value, array('completed', 'passed')))) {
$scorm = $DB->get_record('scorm', array('id' => $scormid));
include_once($CFG->dirroot.'/mod/scorm/lib.php');
scorm_update_grades($scorm, $userid);
}
// Trigger CMI element events.
if (strstr($element, '.score.raw') ||
(in_array($element, array('cmi.completion_status', 'cmi.core.lesson_status', 'cmi.success_status'))
&& in_array($track->value, array('completed', 'failed', 'passed')))) {
if (!$scorm) {
$scorm = $DB->get_record('scorm', array('id' => $scormid));
}
$cm = <API key>('scorm', $scormid);
$data = array(
'other' => array('attemptid' => $attempt, 'cmielement' => $element, 'cmivalue' => $track->value),
'objectid' => $scorm->id,
'context' => context_module::instance($cm->id),
'relateduserid' => $userid
);
if (strstr($element, '.score.raw')) {
// Create score submitted event.
$event = \mod_scorm\event\scoreraw_submitted::create($data);
} else {
// Create status submitted event.
$event = \mod_scorm\event\status_submitted::create($data);
}
// Fix the missing track keys when the SCORM track record already exists, see $trackdata in datamodel.php.
// There, for performances reasons, columns are limited to: element, id, value, timemodified.
// Missing fields are: userid, scormid, scoid, attempt.
$track->userid = $userid;
$track->scormid = $scormid;
$track->scoid = $scoid;
$track->attempt = $attempt;
// Trigger submitted event.
$event->add_record_snapshot('scorm_scoes_track', $track);
$event->add_record_snapshot('course_modules', $cm);
$event->add_record_snapshot('scorm', $scorm);
$event->trigger();
}
return $id;
}
/**
* simple quick function to return true/false if this user has tracks in this scorm
*
* @param integer $scormid The scorm ID
* @param integer $userid the users id
* @return boolean (false if there are no tracks)
*/
function scorm_has_tracks($scormid, $userid) {
global $DB;
return $DB->record_exists('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scormid));
}
function scorm_get_tracks($scoid, $userid, $attempt='') {
// Gets all tracks of specified sco and user.
global $DB;
if (empty($attempt)) {
if ($scormid = $DB->get_field('scorm_scoes', 'scorm', array('id' => $scoid))) {
$attempt = <API key>($scormid, $userid);
} else {
$attempt = 1;
}
}
if ($tracks = $DB->get_records('scorm_scoes_track', array('userid' => $userid, 'scoid' => $scoid,
'attempt' => $attempt), 'element ASC')) {
$usertrack = <API key>($tracks);
$usertrack->userid = $userid;
$usertrack->scoid = $scoid;
return $usertrack;
} else {
return false;
}
}
/**
* helper function to return a formatted list of interactions for reports.
*
* @param array $trackdata the records from scorm_scoes_track table
* @return object formatted list of interactions
*/
function <API key>($trackdata) {
$usertrack = new stdClass();
// Defined in order to unify scorm1.2 and scorm2004.
$usertrack->score_raw = '';
$usertrack->status = '';
$usertrack->total_time = '00:00:00';
$usertrack->session_time = '00:00:00';
$usertrack->timemodified = 0;
foreach ($trackdata as $track) {
$element = $track->element;
$usertrack->{$element} = $track->value;
switch ($element) {
case 'cmi.core.lesson_status':
case 'cmi.completion_status':
if ($track->value == 'not attempted') {
$track->value = 'notattempted';
}
$usertrack->status = $track->value;
break;
case 'cmi.core.score.raw':
case 'cmi.score.raw':
$usertrack->score_raw = (float) sprintf('%2.2f', $track->value);
break;
case 'cmi.core.session_time':
case 'cmi.session_time':
$usertrack->session_time = $track->value;
break;
case 'cmi.core.total_time':
case 'cmi.total_time':
$usertrack->total_time = $track->value;
break;
}
if (isset($track->timemodified) && ($track->timemodified > $usertrack->timemodified)) {
$usertrack->timemodified = $track->timemodified;
}
}
return $usertrack;
}
/* Find the start and finsh time for a a given SCO attempt
*
* @param int $scormid SCORM Id
* @param int $scoid SCO Id
* @param int $userid User Id
* @param int $attemt Attempt Id
*
* @return object start and finsh time EPOC secods
*
*/
function <API key>($scormid, $scoid, $userid, $attempt=1) {
global $DB;
$timedata = new stdClass();
$params = array('userid' => $userid, 'scormid' => $scormid, 'attempt' => $attempt);
if (!empty($scoid)) {
$params['scoid'] = $scoid;
}
$tracks = $DB->get_records('scorm_scoes_track', $params, "timemodified ASC");
if ($tracks) {
$tracks = array_values($tracks);
}
if ($tracks) {
$timedata->start = $tracks[0]->timemodified;
} else {
$timedata->start = false;
}
if ($tracks && $track = array_pop($tracks)) {
$timedata->finish = $track->timemodified;
} else {
$timedata->finish = $timedata->start;
}
return $timedata;
}
function <API key>($scorm, $userid, $attempt=1) {
global $DB;
$attemptscore = new stdClass();
$attemptscore->scoes = 0;
$attemptscore->values = 0;
$attemptscore->max = 0;
$attemptscore->sum = 0;
$attemptscore->lastmodify = 0;
if (!$scoes = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id), 'sortorder, id')) {
return null;
}
foreach ($scoes as $sco) {
if ($userdata = scorm_get_tracks($sco->id, $userid, $attempt)) {
if (($userdata->status == 'completed') || ($userdata->status == 'passed')) {
$attemptscore->scoes++;
}
if (!empty($userdata->score_raw) || (isset($scorm->type) && $scorm->type == 'sco' && isset($userdata->score_raw))) {
$attemptscore->values++;
$attemptscore->sum += $userdata->score_raw;
$attemptscore->max = ($userdata->score_raw > $attemptscore->max) ? $userdata->score_raw : $attemptscore->max;
if (isset($userdata->timemodified) && ($userdata->timemodified > $attemptscore->lastmodify)) {
$attemptscore->lastmodify = $userdata->timemodified;
} else {
$attemptscore->lastmodify = 0;
}
}
}
}
switch ($scorm->grademethod) {
case GRADEHIGHEST:
$score = (float) $attemptscore->max;
break;
case GRADEAVERAGE:
if ($attemptscore->values > 0) {
$score = $attemptscore->sum / $attemptscore->values;
} else {
$score = 0;
}
break;
case GRADESUM:
$score = $attemptscore->sum;
break;
case GRADESCOES:
$score = $attemptscore->scoes;
break;
default:
$score = $attemptscore->max; // Remote Learner GRADEHIGHEST is default.
}
return $score;
}
function scorm_grade_user($scorm, $userid) {
// Ensure we dont grade user beyond $scorm->maxattempt settings.
$lastattempt = <API key>($scorm->id, $userid);
if ($scorm->maxattempt != 0 && $lastattempt >= $scorm->maxattempt) {
$lastattempt = $scorm->maxattempt;
}
switch ($scorm->whatgrade) {
case FIRSTATTEMPT:
return <API key>($scorm, $userid, 1);
break;
case LASTATTEMPT:
return <API key>($scorm, $userid, <API key>($scorm->id, $userid));
break;
case HIGHESTATTEMPT:
$maxscore = 0;
for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
$attemptscore = <API key>($scorm, $userid, $attempt);
$maxscore = $attemptscore > $maxscore ? $attemptscore : $maxscore;
}
return $maxscore;
break;
case AVERAGEATTEMPT:
$attemptcount = <API key>($userid, $scorm, true, true);
if (empty($attemptcount)) {
return 0;
} else {
$attemptcount = count($attemptcount);
}
$lastattempt = <API key>($scorm->id, $userid);
$sumscore = 0;
for ($attempt = 1; $attempt <= $lastattempt; $attempt++) {
$attemptscore = <API key>($scorm, $userid, $attempt);
$sumscore += $attemptscore;
}
return round($sumscore / $attemptcount);
break;
}
}
function <API key>($scormid, $organization='') {
global $DB;
$sqlorganization = '';
$params = array($scormid);
if (!empty($organization)) {
$sqlorganization = " AND organization=?";
$params[] = $organization;
}
return $DB-><API key>('scorm_scoes', "scorm = ? $sqlorganization AND ".
$DB->sql_isnotempty('scorm_scoes', 'launch', false, true),
$params);
}
/**
* Returns the last attempt used - if no attempts yet, returns 1 for first attempt
*
* @param int $scormid the id of the scorm.
* @param int $userid the id of the user.
*
* @return int The attempt number to use.
*/
function <API key>($scormid, $userid) {
global $DB;
// Find the last attempt number for the given user id and scorm id.
$sql = "SELECT MAX(attempt)
FROM {scorm_scoes_track}
WHERE userid = ? AND scormid = ?";
$lastattempt = $DB->get_field_sql($sql, array($userid, $scormid));
if (empty($lastattempt)) {
return '1';
} else {
return $lastattempt;
}
}
/**
* Returns the last completed attempt used - if no completed attempts yet, returns 1 for first attempt
*
* @param int $scormid the id of the scorm.
* @param int $userid the id of the user.
*
* @return int The attempt number to use.
*/
function <API key>($scormid, $userid) {
global $DB;
// Find the last completed attempt number for the given user id and scorm id.
$sql = "SELECT MAX(attempt)
FROM {scorm_scoes_track}
WHERE userid = ? AND scormid = ?
AND (".$DB->sql_compare_text('value')." = ".$DB->sql_compare_text('?')." OR ".
$DB->sql_compare_text('value')." = ".$DB->sql_compare_text('?').")";
$lastattempt = $DB->get_field_sql($sql, array($userid, $scormid, 'completed', 'passed'));
if (empty($lastattempt)) {
return '1';
} else {
return $lastattempt;
}
}
/**
* Returns the full list of attempts a user has made.
*
* @param int $scormid the id of the scorm.
* @param int $userid the id of the user.
*
* @return array array of attemptids
*/
function <API key>($scormid, $userid) {
global $DB;
$attemptids = array();
$sql = "SELECT DISTINCT attempt FROM {scorm_scoes_track} WHERE userid = ? AND scormid = ? ORDER BY attempt";
$attempts = $DB->get_records_sql($sql, array($userid, $scormid));
foreach ($attempts as $attempt) {
$attemptids[] = $attempt->attempt;
}
return $attemptids;
}
/**
* Displays the entry form and toc if required.
*
* @param stdClass $user user object
* @param stdClass $scorm scorm object
* @param string $action base URL for the organizations select box
* @param stdClass $cm course module object
*/
function scorm_print_launch ($user, $scorm, $action, $cm) {
global $CFG, $DB, $PAGE, $OUTPUT, $COURSE;
if ($scorm->updatefreq == <API key>) {
scorm_parse($scorm, false);
}
$organization = optional_param('organization', '', PARAM_INT);
if ($scorm-><API key> == 1) {
echo $OUTPUT->box_start('generalbox boxaligncenter toc', 'toc');
echo html_writer::div(get_string('contents', 'scorm'), 'structurehead');
}
if (empty($organization)) {
$organization = $scorm->launch;
}
if ($orgs = $DB-><API key>('scorm_scoes', 'scorm = ? AND '.
$DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
$DB->sql_isempty('scorm_scoes', 'organization', false, false),
array($scorm->id), 'sortorder, id', 'id,title')) {
if (count($orgs) > 1) {
$select = new single_select(new moodle_url($action), 'organization', $orgs, $organization, null);
$select->label = get_string('organizations', 'scorm');
$select->class = 'scorm-center';
echo $OUTPUT->render($select);
}
}
$orgidentifier = '';
if ($sco = scorm_get_sco($organization, SCO_ONLY)) {
if (($sco->organization == '') && ($sco->launch == '')) {
$orgidentifier = $sco->identifier;
} else {
$orgidentifier = $sco->organization;
}
}
$scorm->version = strtolower(clean_param($scorm->version, PARAM_SAFEDIR)); // Just to be safe.
if (!file_exists($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php')) {
$scorm->version = 'scorm_12';
}
require_once($CFG->dirroot.'/mod/scorm/datamodels/'.$scorm->version.'lib.php');
$result = scorm_get_toc($user, $scorm, $cm->id, TOCFULLURL, $orgidentifier);
$incomplete = $result->incomplete;
// Do we want the TOC to be displayed?
if ($scorm-><API key> == 1) {
echo $result->toc;
echo $OUTPUT->box_end();
}
// Is this the first attempt ?
$attemptcount = <API key>($user->id, $scorm);
// Do not give the player launch FORM if the SCORM object is locked after the final attempt.
if ($scorm->lastattemptlock == 0 || $result->attemptleft > 0) {
echo html_writer::start_div('scorm-center');
echo html_writer::start_tag('form', array('id' => 'scormviewform',
'method' => 'post',
'action' => $CFG->wwwroot.'/mod/scorm/player.php'));
if ($scorm->hidebrowse == 0) {
print_string('mode', 'scorm');
echo ': '.html_writer::empty_tag('input', array('type' => 'radio', 'id' => 'b', 'name' => 'mode', 'value' => 'browse')).
html_writer::label(get_string('browse', 'scorm'), 'b');
echo html_writer::empty_tag('input', array('type' => 'radio',
'id' => 'n', 'name' => 'mode',
'value' => 'normal', 'checked' => 'checked')).
html_writer::label(get_string('normal', 'scorm'), 'n');
} else {
echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'mode', 'value' => 'normal'));
}
if ($scorm->forcenewattempt == 1) {
if ($incomplete === false) {
echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'newattempt', 'value' => 'on'));
}
} else if (!empty($attemptcount) && ($incomplete === false) && (($result->attemptleft > 0)||($scorm->maxattempt == 0))) {
echo html_writer::empty_tag('br');
echo html_writer::checkbox('newattempt', 'on', false, '', array('id' => 'a'));
echo html_writer::label(get_string('newattempt', 'scorm'), 'a');
}
if (!empty($scorm->popup)) {
echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'display', 'value' => 'popup'));
}
echo html_writer::empty_tag('br');
echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'scoid', 'value' => $scorm->launch));
echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'cm', 'value' => $cm->id));
echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'currentorg', 'value' => $orgidentifier));
echo html_writer::empty_tag('input', array('type' => 'submit', 'value' => get_string('enter', 'scorm')));
echo html_writer::end_tag('form');
echo html_writer::end_div();
}
}
function scorm_simple_play($scorm, $user, $context, $cmid) {
global $DB;
$result = false;
if (has_capability('mod/scorm:viewreport', $context)) {
// If this user can view reports, don't skipview so they can see links to reports.
return $result;
}
if ($scorm->updatefreq == <API key>) {
scorm_parse($scorm, false);
}
$scoes = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.
$DB->sql_isnotempty('scorm_scoes', 'launch', false, true), array($scorm->id), 'sortorder, id', 'id');
if ($scoes) {
$orgidentifier = '';
if ($sco = scorm_get_sco($scorm->launch, SCO_ONLY)) {
if (($sco->organization == '') && ($sco->launch == '')) {
$orgidentifier = $sco->identifier;
} else {
$orgidentifier = $sco->organization;
}
}
if ($scorm->skipview >= <API key>) {
$sco = current($scoes);
$url = new moodle_url('/mod/scorm/player.php', array('a' => $scorm->id,
'currentorg' => $orgidentifier,
'scoid' => $sco->id));
if ($scorm->skipview == <API key> || !scorm_has_tracks($scorm->id, $user->id)) {
if (!empty($scorm->forcenewattempt)) {
$result = scorm_get_toc($user, $scorm, $cmid, TOCFULLURL, $orgidentifier);
if ($result->incomplete === false) {
$url->param('newattempt', 'on');
}
}
redirect($url);
}
}
}
return $result;
}
function <API key>($scormid, $groupingid=null) {
global $CFG, $DB;
if (!empty($groupingid)) {
$sql = "SELECT COUNT(DISTINCT st.userid)
FROM {scorm_scoes_track} st
INNER JOIN {groups_members} gm ON st.userid = gm.userid
INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
WHERE st.scormid = ? AND gg.groupingid = ?
";
$params = array($scormid, $groupingid);
} else {
$sql = "SELECT COUNT(DISTINCT st.userid)
FROM {scorm_scoes_track} st
WHERE st.scormid = ?
";
$params = array($scormid);
}
return ($DB->count_records_sql($sql, $params));
}
/**
* Build up the JavaScript representation of an array element
*
* @param string $sversion SCORM API version
* @param array $userdata User track data
* @param string $elementname Name of array element to get values for
* @param array $children list of sub elements of this array element that also need instantiating
* @return Javascript array elements
*/
function <API key>($sversion, $userdata, $elementname, $children) {
// Reconstitute <API key> and comments_from_lms.
$current = '';
$currentsubelement = '';
$currentsub = '';
$count = 0;
$countsub = 0;
$scormseperator = '_';
$return = '';
if (scorm_version_check($sversion, SCORM_13)) { // Scorm 1.3 elements use a . instead of an _ .
$scormseperator = '.';
}
// Filter out the ones we want.
$elementlist = array();
foreach ($userdata as $element => $value) {
if (substr($element, 0, strlen($elementname)) == $elementname) {
$elementlist[$element] = $value;
}
}
// Sort elements in .n array order.
uksort($elementlist, "scorm_element_cmp");
// Generate JavaScript.
foreach ($elementlist as $element => $value) {
if (scorm_version_check($sversion, SCORM_13)) {
$element = preg_replace('/\.(\d+)\./', ".N\$1.", $element);
preg_match('/\.(N\d+)\./', $element, $matches);
} else {
$element = preg_replace('/\.(\d+)\./', "_\$1.", $element);
preg_match('/\_(\d+)\./', $element, $matches);
}
if (count($matches) > 0 && $current != $matches[1]) {
if ($countsub > 0) {
$return .= ' '.$elementname.$scormseperator.$current.'.'.$currentsubelement.'._count = '.$countsub.";\n";
}
$current = $matches[1];
$count++;
$currentsubelement = '';
$currentsub = '';
$countsub = 0;
$end = strpos($element, $matches[1]) + strlen($matches[1]);
$subelement = substr($element, 0, $end);
$return .= ' '.$subelement." = new Object();\n";
// Now add the children.
foreach ($children as $child) {
$return .= ' '.$subelement.".".$child." = new Object();\n";
$return .= ' '.$subelement.".".$child."._children = ".$child."_children;\n";
}
}
// Now - flesh out the second level elements if there are any.
if (scorm_version_check($sversion, SCORM_13)) {
$element = preg_replace('/(.*?\.N\d+\..*?)\.(\d+)\./', "\$1.N\$2.", $element);
preg_match('/.*?\.N\d+\.(.*?)\.(N\d+)\./', $element, $matches);
} else {
$element = preg_replace('/(.*?\_\d+\..*?)\.(\d+)\./', "\$1_\$2.", $element);
preg_match('/.*?\_\d+\.(.*?)\_(\d+)\./', $element, $matches);
}
// Check the sub element type.
if (count($matches) > 0 && $currentsubelement != $matches[1]) {
if ($countsub > 0) {
$return .= ' '.$elementname.$scormseperator.$current.'.'.$currentsubelement.'._count = '.$countsub.";\n";
}
$currentsubelement = $matches[1];
$currentsub = '';
$countsub = 0;
$end = strpos($element, $matches[1]) + strlen($matches[1]);
$subelement = substr($element, 0, $end);
$return .= ' '.$subelement." = new Object();\n";
}
// Now check the subelement subscript.
if (count($matches) > 0 && $currentsub != $matches[2]) {
$currentsub = $matches[2];
$countsub++;
$end = strrpos($element, $matches[2]) + strlen($matches[2]);
$subelement = substr($element, 0, $end);
$return .= ' '.$subelement." = new Object();\n";
}
$return .= ' '.$element.' = '.json_encode($value).";\n";
}
if ($countsub > 0) {
$return .= ' '.$elementname.$scormseperator.$current.'.'.$currentsubelement.'._count = '.$countsub.";\n";
}
if ($count > 0) {
$return .= ' '.$elementname.'._count = '.$count.";\n";
}
return $return;
}
/**
* Build up the JavaScript representation of an array element
*
* @param string $a left array element
* @param string $b right array element
* @return comparator - 0,1,-1
*/
function scorm_element_cmp($a, $b) {
preg_match('/.*?(\d+)\./', $a, $matches);
$left = intval($matches[1]);
preg_match('/.?(\d+)\./', $b, $matches);
$right = intval($matches[1]);
if ($left < $right) {
return -1; // Smaller.
} else if ($left > $right) {
return 1; // Bigger.
} else {
// Look for a second level qualifier eg cmi.interactions_0.correct_responses_0.pattern.
if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $a, $matches)) {
$leftterm = intval($matches[2]);
$left = intval($matches[3]);
if (preg_match('/.*?(\d+)\.(.*?)\.(\d+)\./', $b, $matches)) {
$rightterm = intval($matches[2]);
$right = intval($matches[3]);
if ($leftterm < $rightterm) {
return -1; // Smaller.
} else if ($leftterm > $rightterm) {
return 1; // Bigger.
} else {
if ($left < $right) {
return -1; // Smaller.
} else if ($left > $right) {
return 1; // Bigger.
}
}
}
}
// Fall back for no second level matches or second level matches are equal.
return 0; // Equal to.
}
}
/**
* Generate the user attempt status string
*
* @param object $user Current context user
* @param object $scorm a moodle scrom object - mdl_scorm
* @return string - Attempt status string
*/
function <API key>($user, $scorm, $cm='') {
global $DB, $PAGE, $OUTPUT;
$attempts = <API key>($user->id, $scorm, true);
if (empty($attempts)) {
$attemptcount = 0;
} else {
$attemptcount = count($attempts);
}
$result = html_writer::start_tag('p').get_string('noattemptsallowed', 'scorm').': ';
if ($scorm->maxattempt > 0) {
$result .= $scorm->maxattempt . html_writer::empty_tag('br');
} else {
$result .= get_string('unlimited').html_writer::empty_tag('br');
}
$result .= get_string('noattemptsmade', 'scorm').': ' . $attemptcount . html_writer::empty_tag('br');
if ($scorm->maxattempt == 1) {
switch ($scorm->grademethod) {
case GRADEHIGHEST:
$grademethod = get_string('gradehighest', 'scorm');
break;
case GRADEAVERAGE:
$grademethod = get_string('gradeaverage', 'scorm');
break;
case GRADESUM:
$grademethod = get_string('gradesum', 'scorm');
break;
case GRADESCOES:
$grademethod = get_string('gradescoes', 'scorm');
break;
}
} else {
switch ($scorm->whatgrade) {
case HIGHESTATTEMPT:
$grademethod = get_string('highestattempt', 'scorm');
break;
case AVERAGEATTEMPT:
$grademethod = get_string('averageattempt', 'scorm');
break;
case FIRSTATTEMPT:
$grademethod = get_string('firstattempt', 'scorm');
break;
case LASTATTEMPT:
$grademethod = get_string('lastattempt', 'scorm');
break;
}
}
if (!empty($attempts)) {
$i = 1;
foreach ($attempts as $attempt) {
$gradereported = <API key>($scorm, $user->id, $attempt->attemptnumber);
if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
$gradereported = $gradereported / $scorm->maxgrade;
$gradereported = number_format($gradereported * 100, 0) .'%';
}
$result .= get_string('gradeforattempt', 'scorm').' ' . $i . ': ' . $gradereported .html_writer::empty_tag('br');
$i++;
}
}
$calculatedgrade = scorm_grade_user($scorm, $user->id);
if ($scorm->grademethod !== GRADESCOES && !empty($scorm->maxgrade)) {
$calculatedgrade = $calculatedgrade / $scorm->maxgrade;
$calculatedgrade = number_format($calculatedgrade * 100, 0) .'%';
}
$result .= get_string('grademethod', 'scorm'). ': ' . $grademethod;
if (empty($attempts)) {
$result .= html_writer::empty_tag('br').get_string('gradereported', 'scorm').
': '.get_string('none').html_writer::empty_tag('br');
} else {
$result .= html_writer::empty_tag('br').get_string('gradereported', 'scorm').
': '.$calculatedgrade.html_writer::empty_tag('br');
}
$result .= html_writer::end_tag('p');
if ($attemptcount >= $scorm->maxattempt and $scorm->maxattempt > 0) {
$result .= html_writer::tag('p', get_string('exceededmaxattempts', 'scorm'), array('class' => 'exceededmaxattempts'));
}
if (!empty($cm)) {
$context = context_module::instance($cm->id);
if (has_capability('mod/scorm:deleteownresponses', $context) &&
$DB->record_exists('scorm_scoes_track', array('userid' => $user->id, 'scormid' => $scorm->id))) {
// Check to see if any data is stored for this user.
$deleteurl = new moodle_url($PAGE->url, array('action' => 'delete', 'sesskey' => sesskey()));
$result .= $OUTPUT->single_button($deleteurl, get_string('deleteallattempts', 'scorm'));
}
}
return $result;
}
/**
* Get SCORM attempt count
*
* @param object $user Current context user
* @param object $scorm a moodle scrom object - mdl_scorm
* @param bool $returnobjects if true returns a object with attempts, if false returns count of attempts.
* @param bool $<API key> - ignores attempts that haven't reported a grade/completion.
* @return int - no. of attempts so far
*/
function <API key>($userid, $scorm, $returnobjects = false, $<API key> = false) {
global $DB;
// Historically attempts that don't report these elements haven't been included in the average attempts grading method
// we may want to change this in future, but to avoid unexpected grade decreases we're leaving this in. MDL-43222 .
if (scorm_version_check($scorm->version, SCORM_13)) {
$element = 'cmi.score.raw';
} else if ($scorm->grademethod == GRADESCOES) {
$element = 'cmi.core.lesson_status';
} else {
$element = 'cmi.core.score.raw';
}
if ($returnobjects) {
$params = array('userid' => $userid, 'scormid' => $scorm->id);
if ($<API key>) { // Exclude attempts that don't have the completion element requested.
$params['element'] = $element;
}
$attempts = $DB->get_records('scorm_scoes_track', $params, 'attempt', 'DISTINCT attempt AS attemptnumber');
return $attempts;
} else {
$params = array($userid, $scorm->id);
$sql = "SELECT COUNT(DISTINCT attempt)
FROM {scorm_scoes_track}
WHERE userid = ? AND scormid = ?";
if ($<API key>) { // Exclude attempts that don't have the completion element requested.
$sql .= ' AND element = ?';
$params[] = $element;
}
$attemptscount = $DB->count_records_sql($sql, $params);
return $attemptscount;
}
}
/**
* Figure out with this is a debug situation
*
* @param object $scorm a moodle scrom object - mdl_scorm
* @return boolean - debugging true/false
*/
function scorm_debugging($scorm) {
global $USER;
$cfgscorm = get_config('scorm');
if (!$cfgscorm->allowapidebug) {
return false;
}
$identifier = $USER->username.':'.$scorm->name;
$test = $cfgscorm->apidebugmask;
// Check the regex is only a short list of safe characters.
if (!preg_match('/^[\w\s\*\.\?\+\:\_\\\]+$/', $test)) {
return false;
}
if (preg_match('/^'.$test.'/', $identifier)) {
return true;
}
return false;
}
/**
* Delete Scorm tracks for selected users
*
* @param array $attemptids list of attempts that need to be deleted
* @param stdClass $scorm instance
*
* @return bool true deleted all responses, false failed deleting an attempt - stopped here
*/
function <API key>($attemptids, $scorm) {
if (!is_array($attemptids) || empty($attemptids)) {
return false;
}
foreach ($attemptids as $num => $attemptid) {
if (empty($attemptid)) {
unset($attemptids[$num]);
}
}
foreach ($attemptids as $attempt) {
$keys = explode(':', $attempt);
if (count($keys) == 2) {
$userid = clean_param($keys[0], PARAM_INT);
$attemptid = clean_param($keys[1], PARAM_INT);
if (!$userid || !$attemptid || !<API key>($userid, $scorm, $attemptid)) {
return false;
}
} else {
return false;
}
}
return true;
}
/**
* Delete Scorm tracks for selected users
*
* @param int $userid ID of User
* @param stdClass $scorm Scorm object
* @param int $attemptid user attempt that need to be deleted
*
* @return bool true suceeded
*/
function <API key>($userid, $scorm, $attemptid) {
global $DB;
$DB->delete_records('scorm_scoes_track', array('userid' => $userid, 'scormid' => $scorm->id, 'attempt' => $attemptid));
$cm = <API key>('scorm', $scorm->id);
// Trigger instances list viewed event.
$event = \mod_scorm\event\attempt_deleted::create(array(
'other' => array('attemptid' => $attemptid),
'context' => context_module::instance($cm->id),
'relateduserid' => $userid
));
$event->add_record_snapshot('course_modules', $cm);
$event->add_record_snapshot('scorm', $scorm);
$event->trigger();
include_once('lib.php');
scorm_update_grades($scorm, $userid, true);
return true;
}
/**
* Converts SCORM duration notation to human-readable format
* The function works with both SCORM 1.2 and SCORM 2004 time formats
* @param $duration string SCORM duration
* @return string human-readable date/time
*/
function <API key>($duration) {
// Fetch date/time strings.
$stryears = get_string('years');
$strmonths = get_string('nummonths');
$strdays = get_string('days');
$strhours = get_string('hours');
$strminutes = get_string('minutes');
$strseconds = get_string('seconds');
if ($duration[0] == 'P') {
// If timestamp starts with 'P' - it's a SCORM 2004 format
// this regexp discards empty sections, takes Month/Minute ambiguity into consideration,
// and outputs filled sections, discarding leading zeroes and any format literals
// also saves the only zero before seconds decimals (if there are any) and discards decimals if they are zero.
$pattern = array( '#([A-Z])0+Y#', '#([A-Z])0+M#', '#([A-Z])0+D#', '#P(|\d+Y)0*(\d+)M#',
'#0*(\d+)Y#', '#0*(\d+)D#', '#P#', '#([A-Z])0+H#', '#([A-Z])[0.]+S#',
'#\.0+S#', '#T(|\d+H)0*(\d+)M#', '#0*(\d+)H#', '#0+\.(\d+)S#',
'#0*([\d.]+)S#', '#T#' );
$replace = array( '$1', '$1', '$1', '$1$2 '.$strmonths.' ', '$1 '.$stryears.' ', '$1 '.$strdays.' ',
'', '$1', '$1', 'S', '$1$2 '.$strminutes.' ', '$1 '.$strhours.' ',
'0.$1 '.$strseconds, '$1 '.$strseconds, '');
} else {
// Else we have SCORM 1.2 format there
// first convert the timestamp to some SCORM 2004-like format for conveniency.
$duration = preg_replace('#^(\d+):(\d+):([\d.]+)$#', 'T$1H$2M$3S', $duration);
// Then convert in the same way as SCORM 2004.
$pattern = array( '#T0+H#', '#([A-Z])0+M#', '#([A-Z])[0.]+S#', '#\.0+S#', '#0*(\d+)H#',
'#0*(\d+)M#', '#0+\.(\d+)S#', '#0*([\d.]+)S#', '#T#' );
$replace = array( 'T', '$1', '$1', 'S', '$1 '.$strhours.' ', '$1 '.$strminutes.' ',
'0.$1 '.$strseconds, '$1 '.$strseconds, '' );
}
$result = preg_replace($pattern, $replace, $duration);
return $result;
}
function <API key>($user, $scorm, $currentorg='', $scoid='', $mode='normal', $attempt='',
$play=false, $organizationsco=null) {
global $CFG, $DB, $PAGE, $OUTPUT;
// Always pass the mode even if empty as that is what is done elsewhere and the urls have to match.
$modestr = '&mode=';
if ($mode != 'normal') {
$modestr = '&mode='.$mode;
}
$result = array();
$incomplete = false;
if (!empty($organizationsco)) {
$result[0] = $organizationsco;
$result[0]->isvisible = 'true';
$result[0]->statusicon = '';
$result[0]->url = '';
}
if ($scoes = scorm_get_scoes($scorm->id, $currentorg)) {
// Retrieve user tracking data for each learning object.
$usertracks = array();
foreach ($scoes as $sco) {
if (!empty($sco->launch)) {
if ($usertrack = scorm_get_tracks($sco->id, $user->id, $attempt)) {
if ($usertrack->status == '') {
$usertrack->status = 'notattempted';
}
$usertracks[$sco->identifier] = $usertrack;
}
}
}
foreach ($scoes as $sco) {
if (!isset($sco->isvisible)) {
$sco->isvisible = 'true';
}
if (empty($sco->title)) {
$sco->title = $sco->identifier;
}
if (scorm_version_check($scorm->version, SCORM_13)) {
$sco->prereq = true;
} else {
$sco->prereq = empty($sco->prerequisites) || <API key>($sco->prerequisites, $usertracks);
}
if ($sco->isvisible === 'true') {
if (!empty($sco->launch)) {
if (empty($scoid) && ($mode != 'normal')) {
$scoid = $sco->id;
}
if (isset($usertracks[$sco->identifier])) {
$usertrack = $usertracks[$sco->identifier];
$strstatus = get_string($usertrack->status, 'scorm');
if ($sco->scormtype == 'sco') {
$statusicon = html_writer::img($OUTPUT->pix_url($usertrack->status, 'scorm'), $strstatus,
array('title' => $strstatus));
} else {
$statusicon = html_writer::img($OUTPUT->pix_url('asset', 'scorm'), get_string('assetlaunched', 'scorm'),
array('title' => get_string('assetlaunched', 'scorm')));
}
if (($usertrack->status == 'notattempted') ||
($usertrack->status == 'incomplete') ||
($usertrack->status == 'browsed')) {
$incomplete = true;
if ($play && empty($scoid)) {
$scoid = $sco->id;
}
}
$strsuspended = get_string('suspended', 'scorm');
$exitvar = 'cmi.core.exit';
if (scorm_version_check($scorm->version, SCORM_13)) {
$exitvar = 'cmi.exit';
}
if ($incomplete && isset($usertrack->{$exitvar}) && ($usertrack->{$exitvar} == 'suspend')) {
$statusicon = html_writer::img($OUTPUT->pix_url('suspend', 'scorm'), $strstatus.' - '.$strsuspended,
array('title' => $strstatus.' - '.$strsuspended));
}
} else {
if ($play && empty($scoid)) {
$scoid = $sco->id;
}
$incomplete = true;
if ($sco->scormtype == 'sco') {
$statusicon = html_writer::img($OUTPUT->pix_url('notattempted', 'scorm'),
get_string('notattempted', 'scorm'),
array('title' => get_string('notattempted', 'scorm')));
} else {
$statusicon = html_writer::img($OUTPUT->pix_url('asset', 'scorm'), get_string('asset', 'scorm'),
array('title' => get_string('asset', 'scorm')));
}
}
}
}
if (empty($statusicon)) {
$sco->statusicon = html_writer::img($OUTPUT->pix_url('notattempted', 'scorm'), get_string('notattempted', 'scorm'),
array('title' => get_string('notattempted', 'scorm')));
} else {
$sco->statusicon = $statusicon;
}
$sco->url = 'a='.$scorm->id.'&scoid='.$sco->id.'¤torg='.$currentorg.$modestr.'&attempt='.$attempt;
$sco->incomplete = $incomplete;
if (!in_array($sco->id, array_keys($result))) {
$result[$sco->id] = $sco;
}
}
}
// Get the parent scoes!
$result = <API key>($result, $currentorg);
// Be safe, prevent warnings from showing up while returning array.
if (!isset($scoid)) {
$scoid = '';
}
return array('scoes' => $result, 'usertracks' => $usertracks, 'scoid' => $scoid);
}
function <API key>(&$result, $currentorg) {
$final = array();
$level = 0;
// Organization is always the root, prevparent.
if (!empty($currentorg)) {
$prevparent = $currentorg;
} else {
$prevparent = '/';
}
foreach ($result as $sco) {
if ($sco->parent == '/') {
$final[$level][$sco->identifier] = $sco;
$prevparent = $sco->identifier;
unset($result[$sco->id]);
} else {
if ($sco->parent == $prevparent) {
$final[$level][$sco->identifier] = $sco;
$prevparent = $sco->identifier;
unset($result[$sco->id]);
} else {
if (!empty($final[$level])) {
$found = false;
foreach ($final[$level] as $fin) {
if ($sco->parent == $fin->identifier) {
$found = true;
}
}
if ($found) {
$final[$level][$sco->identifier] = $sco;
unset($result[$sco->id]);
$found = false;
} else {
$level++;
$final[$level][$sco->identifier] = $sco;
unset($result[$sco->id]);
}
}
}
}
}
for ($i = 0; $i <= $level; $i++) {
$prevparent = '';
foreach ($final[$i] as $ident => $sco) {
if (empty($prevparent)) {
$prevparent = $ident;
}
if (!isset($final[$i][$prevparent]->children)) {
$final[$i][$prevparent]->children = array();
}
if ($sco->parent == $prevparent) {
$final[$i][$prevparent]->children[] = $sco;
$prevparent = $ident;
} else {
$parent = false;
foreach ($final[$i] as $identifier => $scoobj) {
if ($identifier == $sco->parent) {
$parent = $identifier;
}
}
if ($parent !== false) {
$final[$i][$parent]->children[] = $sco;
}
}
}
}
$results = array();
for ($i = 0; $i <= $level; $i++) {
$keys = array_keys($final[$i]);
$results[] = $final[$i][$keys[0]];
}
return $results;
}
function <API key>($user, $scorm, $scoes, $usertracks, $cmid, $toclink=TOCJSLINK, $currentorg='',
$attempt='', $play=false, $organizationsco=null, $children=false) {
global $CFG;
$result = new stdClass();
$result->prerequisites = true;
$result->incomplete = true;
$result->toc = '';
if (!$children) {
$attemptsmade = <API key>($user->id, $scorm);
$result->attemptleft = $scorm->maxattempt == 0 ? 1 : $scorm->maxattempt - $attemptsmade;
}
if (!$children) {
$result->toc = html_writer::start_tag('ul');
if (!$play && !empty($organizationsco)) {
$result->toc .= html_writer::start_tag('li').$organizationsco->title.html_writer::end_tag('li');
}
}
$prevsco = '';
if (!empty($scoes)) {
foreach ($scoes as $sco) {
if ($sco->isvisible === 'false') {
continue;
}
$result->toc .= html_writer::start_tag('li');
$scoid = $sco->id;
$score = '';
if (isset($usertracks[$sco->identifier])) {
$viewscore = has_capability('mod/scorm:viewscores', context_module::instance($cmid));
if (isset($usertracks[$sco->identifier]->score_raw) && $viewscore) {
if ($usertracks[$sco->identifier]->score_raw != '') {
$score = '('.get_string('score', 'scorm').': '.$usertracks[$sco->identifier]->score_raw.')';
}
}
}
if (!empty($sco->prereq)) {
if ($sco->id == $scoid) {
$result->prerequisites = true;
}
if (!empty($prevsco) && scorm_version_check($scorm->version, SCORM_13) && !empty($prevsco->hidecontinue)) {
if ($sco->scormtype == 'sco') {
$result->toc .= html_writer::span($sco->statusicon.' '.format_string($sco->title));
} else {
$result->toc .= html_writer::span(' '.format_string($sco->title));
}
} else if ($toclink == TOCFULLURL) {
$url = $CFG->wwwroot.'/mod/scorm/player.php?'.$sco->url;
if (!empty($sco->launch)) {
if ($sco->scormtype == 'sco') {
$result->toc .= $sco->statusicon.' ';
$result->toc .= html_writer::link($url, format_string($sco->title)).$score;
} else {
$result->toc .= ' '.html_writer::link($url, format_string($sco->title),
array('data-scoid' => $sco->id)).$score;
}
} else {
if ($sco->scormtype == 'sco') {
$result->toc .= $sco->statusicon.' '.format_string($sco->title).$score;
} else {
$result->toc .= ' '.format_string($sco->title).$score;
}
}
} else {
if (!empty($sco->launch)) {
if ($sco->scormtype == 'sco') {
$result->toc .= html_writer::tag('a', $sco->statusicon.' '.
format_string($sco->title).' '.$score,
array('data-scoid' => $sco->id, 'title' => $sco->url));
} else {
$result->toc .= html_writer::tag('a', ' '.format_string($sco->title).' '.$score,
array('data-scoid' => $sco->id, 'title' => $sco->url));
}
} else {
if ($sco->scormtype == 'sco') {
$result->toc .= html_writer::span($sco->statusicon.' '.format_string($sco->title));
} else {
$result->toc .= html_writer::span(' '.format_string($sco->title));
}
}
}
} else {
if ($play) {
if ($sco->scormtype == 'sco') {
$result->toc .= html_writer::span($sco->statusicon.' '.format_string($sco->title));
} else {
$result->toc .= ' '.format_string($sco->title).html_writer::end_span();
}
} else {
if ($sco->scormtype == 'sco') {
$result->toc .= $sco->statusicon.' '.format_string($sco->title);
} else {
$result->toc .= ' '.format_string($sco->title);
}
}
}
if (!empty($sco->children)) {
$result->toc .= html_writer::start_tag('ul');
$childresult = <API key>($user, $scorm, $sco->children, $usertracks, $cmid,
$toclink, $currentorg, $attempt, $play, $organizationsco, true);
// Is any of the children incomplete?
$sco->incomplete = $childresult->incomplete;
$result->toc .= $childresult->toc;
$result->toc .= html_writer::end_tag('ul');
$result->toc .= html_writer::end_tag('li');
} else {
$result->toc .= html_writer::end_tag('li');
}
$prevsco = $sco;
}
$result->incomplete = $sco->incomplete;
}
if (!$children) {
$result->toc .= html_writer::end_tag('ul');
}
return $result;
}
function <API key>($scorm, $scoes, $usertracks, $currentorg='', $organizationsco=null,
$children=false, $level=0, $tocmenus=array()) {
if (!empty($scoes)) {
if (!empty($organizationsco) && !$children) {
$tocmenus[$organizationsco->id] = $organizationsco->title;
}
$parents[$level] = '/';
foreach ($scoes as $sco) {
if ($parents[$level] != $sco->parent) {
if ($newlevel = array_search($sco->parent, $parents)) {
$level = $newlevel;
} else {
$i = $level;
while (($i > 0) && ($parents[$level] != $sco->parent)) {
$i
}
if (($i == 0) && ($sco->parent != $currentorg)) {
$level++;
} else {
$level = $i;
}
$parents[$level] = $sco->parent;
}
}
if ($sco->scormtype == 'sco') {
$tocmenus[$sco->id] = scorm_repeater('−', $level) . '>' . format_string($sco->title);
}
if (!empty($sco->children)) {
$tocmenus = <API key>($scorm, $sco->children, $usertracks, $currentorg,
$organizationsco, true, $level, $tocmenus);
}
}
}
return $tocmenus;
}
function scorm_get_toc($user, $scorm, $cmid, $toclink=TOCJSLINK, $currentorg='', $scoid='', $mode='normal',
$attempt='', $play=false, $tocheader=false) {
global $CFG, $DB, $OUTPUT;
if (empty($attempt)) {
$attempt = <API key>($scorm->id, $user->id);
}
$result = new stdClass();
$organizationsco = null;
if ($tocheader) {
$result->toc = html_writer::start_div('yui3-g-r', array('id' => 'scorm_layout'));
$result->toc .= html_writer::start_div('yui3-u-1-5', array('id' => 'scorm_toc'));
$result->toc .= html_writer::div('', '', array('id' => 'scorm_toc_title'));
$result->toc .= html_writer::start_div('', array('id' => 'scorm_tree'));
}
if (!empty($currentorg)) {
$organizationsco = $DB->get_record('scorm_scoes', array('scorm' => $scorm->id, 'identifier' => $currentorg));
if (!empty($organizationsco->title)) {
if ($play) {
$result->toctitle = $organizationsco->title;
}
}
}
$scoes = <API key>($user, $scorm, $currentorg, $scoid, $mode, $attempt, $play, $organizationsco);
$treeview = <API key>($user, $scorm, $scoes['scoes'][0]->children, $scoes['usertracks'], $cmid,
$toclink, $currentorg, $attempt, $play, $organizationsco, false);
if ($tocheader) {
$result->toc .= $treeview->toc;
} else {
$result->toc = $treeview->toc;
}
if (!empty($scoes['scoid'])) {
$scoid = $scoes['scoid'];
}
if (empty($scoid)) {
// If this is a normal package with an org sco and child scos get the first child.
if (!empty($scoes['scoes'][0]->children)) {
$result->sco = $scoes['scoes'][0]->children[0];
} else { // This package only has one sco - it may be a simple external AICC package.
$result->sco = $scoes['scoes'][0];
}
} else {
$result->sco = scorm_get_sco($scoid);
}
if ($scorm->hidetoc == SCORM_TOC_POPUP) {
$tocmenu = <API key>($scorm, $scoes['scoes'][0]->children, $scoes['usertracks'],
$currentorg, $organizationsco);
$modestr = '';
if ($mode != 'normal') {
$modestr = '&mode='.$mode;
}
$url = new moodle_url('/mod/scorm/player.php?a='.$scorm->id.'¤torg='.$currentorg.$modestr);
$result->tocmenu = $OUTPUT->single_select($url, 'scoid', $tocmenu, $result->sco->id, null, "tocmenu");
}
$result->prerequisites = $treeview->prerequisites;
$result->incomplete = $treeview->incomplete;
$result->attemptleft = $treeview->attemptleft;
if ($tocheader) {
$result->toc .= html_writer::end_div().html_writer::end_div();
$result->toc .= html_writer::start_div('', array('id' => 'scorm_toc_toggle'));
$result->toc .= html_writer::tag('button', '', array('id' => '<API key>')).html_writer::end_div();
$result->toc .= html_writer::start_div('', array('id' => 'scorm_content'));
$result->toc .= html_writer::div('', '', array('id' => 'scorm_navpanel'));
$result->toc .= html_writer::end_div().html_writer::end_div();
}
return $result;
}
function <API key> ($scoes, &$adlnav = array(), $parentscoid = null) {
if (is_object($scoes)) {
$sco = $scoes;
if (isset($sco->url)) {
$adlnav[$sco->id]['identifier'] = $sco->identifier;
$adlnav[$sco->id]['launch'] = $sco->launch;
$adlnav[$sco->id]['title'] = $sco->title;
$adlnav[$sco->id]['url'] = $sco->url;
$adlnav[$sco->id]['parent'] = $sco->parent;
if (isset($sco->choice)) {
$adlnav[$sco->id]['choice'] = $sco->choice;
}
if (isset($sco->flow)) {
$adlnav[$sco->id]['flow'] = $sco->flow;
} else if (isset($parentscoid) && isset($adlnav[$parentscoid]['flow'])) {
$adlnav[$sco->id]['flow'] = $adlnav[$parentscoid]['flow'];
}
if (isset($sco->isvisible)) {
$adlnav[$sco->id]['isvisible'] = $sco->isvisible;
}
if (isset($sco->parameters)) {
$adlnav[$sco->id]['parameters'] = $sco->parameters;
}
if (isset($sco->hidecontinue)) {
$adlnav[$sco->id]['hidecontinue'] = $sco->hidecontinue;
}
if (isset($sco->hideprevious)) {
$adlnav[$sco->id]['hideprevious'] = $sco->hideprevious;
}
if (isset($sco->hidesuspendall)) {
$adlnav[$sco->id]['hidesuspendall'] = $sco->hidesuspendall;
}
if (!empty($parentscoid)) {
$adlnav[$sco->id]['parentscoid'] = $parentscoid;
}
if (isset($adlnav['prevscoid'])) {
$adlnav[$sco->id]['prevscoid'] = $adlnav['prevscoid'];
$adlnav[$adlnav['prevscoid']]['nextscoid'] = $sco->id;
if (isset($adlnav['prevparent']) && $adlnav['prevparent'] == $sco->parent) {
$adlnav[$sco->id]['prevsibling'] = $adlnav['prevscoid'];
$adlnav[$adlnav['prevscoid']]['nextsibling'] = $sco->id;
}
}
$adlnav['prevscoid'] = $sco->id;
$adlnav['prevparent'] = $sco->parent;
}
if (isset($sco->children)) {
foreach ($sco->children as $children) {
<API key>($children, $adlnav, $sco->id);
}
}
} else {
foreach ($scoes as $sco) {
<API key> ($sco, $adlnav);
}
unset($adlnav['prevscoid']);
unset($adlnav['prevparent']);
}
return json_encode($adlnav);
}
/**
* Check for the availability of a resource by URL.
*
* Check is performed using an HTTP HEAD call.
*
* @param $url string A valid URL
* @return bool|string True if no issue is found. The error string message, otherwise
*/
function scorm_check_url($url) {
$curl = new curl;
// Same options as in {@link <API key>()}, used in {@link scorm_parse_scorm()}.
$curl->setopt(array('<API key>' => true, 'CURLOPT_MAXREDIRS' => 5));
$cmsg = $curl->head($url);
$info = $curl->get_info();
if (empty($info['http_code']) || $info['http_code'] != 200) {
return get_string('invalidurlhttpcheck', 'scorm', array('cmsg' => $cmsg));
}
return true;
}
/**
* Check for a parameter in userdata and return it if it's set
* or return the value from $ifempty if its empty
*
* @param stdClass $userdata Contains user's data
* @param string $param parameter that should be checked
* @param string $ifempty value to be replaced with if $param is not set
* @return string value from $userdata->$param if its not empty, or $ifempty
*/
function scorm_isset($userdata, $param, $ifempty = '') {
if (isset($userdata->$param)) {
return $userdata->$param;
} else {
return $ifempty;
}
}
/**
* Check if the current sco is launchable
* If not, find the next launchable sco
*
* @param stdClass $scorm Scorm object
* @param integer $scoid id of scorm_scoes record.
* @return integer scoid of correct sco to launch or empty if one cannot be found, which will trigger first sco.
*/
function <API key>($scorm, $scoid) {
global $DB;
if ($sco = scorm_get_sco($scoid, SCO_ONLY)) {
if ($sco->launch == '') {
// This scoid might be a top level org that can't be launched, find the first launchable sco after this sco.
$scoes = $DB->get_records_select('scorm_scoes',
'scorm = ? AND '.$DB->sql_isnotempty('scorm_scoes', 'launch', false, true).
' AND id > ?', array($scorm->id, $sco->id), 'sortorder, id', 'id', 0, 1);
if (!empty($scoes)) {
$sco = reset($scoes); // Get first item from the list.
return $sco->id;
}
} else {
return $sco->id;
}
}
// Returning 0 will cause default behaviour which will find the first launchable sco in the package.
return 0;
}
/**
* Check if a SCORM is available for the current user.
*
* @param stdClass $scorm SCORM record
* @param boolean $checkviewreportcap Check the scorm:viewreport cap
* @param stdClass $context Module context, required if $checkviewreportcap is set to true
* @return array status (available or not and possible warnings)
* @since Moodle 3.0
*/
function <API key>($scorm, $checkviewreportcap = false, $context = null) {
$open = true;
$closed = false;
$warnings = array();
$timenow = time();
if (!empty($scorm->timeopen) and $scorm->timeopen > $timenow) {
$open = false;
}
if (!empty($scorm->timeclose) and $timenow > $scorm->timeclose) {
$closed = true;
}
if (!$open or $closed) {
if ($checkviewreportcap and !empty($context) and has_capability('mod/scorm:viewreport', $context)) {
return array(true, $warnings);
}
if (!$open) {
$warnings['notopenyet'] = userdate($scorm->timeopen);
}
if ($closed) {
$warnings['expired'] = userdate($scorm->timeclose);
}
return array(false, $warnings);
}
// Scorm is available.
return array(true, $warnings);
}
/**
* Requires a SCORM package to be available for the current user.
*
* @param stdClass $scorm SCORM record
* @param boolean $checkviewreportcap Check the scorm:viewreport cap
* @param stdClass $context Module context, required if $checkviewreportcap is set to true
* @throws moodle_exception
* @since Moodle 3.0
*/
function <API key>($scorm, $checkviewreportcap = false, $context = null) {
list($available, $warnings) = <API key>($scorm, $checkviewreportcap, $context);
if (!$available) {
$reason = current(array_keys($warnings));
throw new moodle_exception($reason, 'scorm', '', $warnings[$reason]);
}
}
/**
* Return a SCO object and the SCO launch URL
*
* @param stdClass $scorm SCORM object
* @param int $scoid The SCO id in database
* @param stdClass $context context object
* @return array the SCO object and URL
* @since Moodle 3.1
*/
function <API key>($scorm, $scoid, $context) {
global $CFG, $DB;
if (!empty($scoid)) {
// Direct SCO request.
if ($sco = scorm_get_sco($scoid)) {
if ($sco->launch == '') {
// Search for the next launchable sco.
if ($scoes = $DB->get_records_select(
'scorm_scoes',
'scorm = ? AND '.$DB->sql_isnotempty('scorm_scoes', 'launch', false, true).' AND id > ?',
array($scorm->id, $sco->id),
'sortorder, id')) {
$sco = current($scoes);
}
}
}
}
// If no sco was found get the first of SCORM package.
if (!isset($sco)) {
$scoes = $DB->get_records_select(
'scorm_scoes',
'scorm = ? AND '.$DB->sql_isnotempty('scorm_scoes', 'launch', false, true),
array($scorm->id),
'sortorder, id'
);
$sco = current($scoes);
}
$connector = '';
$version = substr($scorm->version, 0, 4);
if ((isset($sco->parameters) && (!empty($sco->parameters))) || ($version == 'AICC')) {
if (stripos($sco->launch, '?') !== false) {
$connector = '&';
} else {
$connector = '?';
}
if ((isset($sco->parameters) && (!empty($sco->parameters))) && ($sco->parameters[0] == '?')) {
$sco->parameters = substr($sco->parameters, 1);
}
}
if ($version == 'AICC') {
require_once("$CFG->dirroot/mod/scorm/datamodels/aicclib.php");
$aiccsid = <API key>($scorm->id);
if (empty($aiccsid)) {
$aiccsid = sesskey();
}
$scoparams = '';
if (isset($sco->parameters) && (!empty($sco->parameters))) {
$scoparams = '&'. $sco->parameters;
}
$launcher = $sco->launch.$connector.'aicc_sid='.$aiccsid.'&aicc_url='.$CFG->wwwroot.'/mod/scorm/aicc.php'.$scoparams;
} else {
if (isset($sco->parameters) && (!empty($sco->parameters))) {
$launcher = $sco->launch.$connector.$sco->parameters;
} else {
$launcher = $sco->launch;
}
}
if (scorm_external_link($sco->launch)) {
// TODO: does this happen?
$scolaunchurl = $launcher;
} else if ($scorm->scormtype === SCORM_TYPE_EXTERNAL) {
// Remote learning activity.
$scolaunchurl = dirname($scorm->reference).'/'.$launcher;
} else if ($scorm->scormtype === SCORM_TYPE_LOCAL && strtolower($scorm->reference) == 'imsmanifest.xml') {
// This SCORM content sits in a repository that allows relative links.
$scolaunchurl = "$CFG->wwwroot/pluginfile.php/$context->id/mod_scorm/imsmanifest/$scorm->revision/$launcher";
} else if ($scorm->scormtype === SCORM_TYPE_LOCAL or $scorm->scormtype === <API key>) {
// Note: do not convert this to use moodle_url().
// SCORM does not work without slasharguments and moodle_url() encodes querystring vars.
$scolaunchurl = "$CFG->wwwroot/pluginfile.php/$context->id/mod_scorm/content/$scorm->revision/$launcher";
}
return array($sco, $scolaunchurl);
}
/**
* Trigger the scorm_launched event.
*
* @param stdClass $scorm scorm object
* @param stdClass $sco sco object
* @param stdClass $cm course module object
* @param stdClass $context context object
* @param string $scourl SCO URL
* @since Moodle 3.1
*/
function scorm_launch_sco($scorm, $sco, $cm, $context, $scourl) {
$event = \mod_scorm\event\sco_launched::create(array(
'objectid' => $sco->id,
'context' => $context,
'other' => array('instanceid' => $scorm->id, 'loadedcontent' => $scourl)
));
$event->add_record_snapshot('course_modules', $cm);
$event->add_record_snapshot('scorm', $scorm);
$event->add_record_snapshot('scorm_scoes', $sco);
$event->trigger();
} |
// File : $RCSfile$
// Version : $Revision: 49312 $
// Description : simple helpers for creating cusom output manipulators
#ifndef <API key>
#define <API key>
// STL
#include <iosfwd>
#include <boost/test/detail/suppress_warnings.hpp>
//<API key>//
namespace boost {
namespace unit_test {
template<typename Manip>
struct custom_printer {
explicit custom_printer( std::ostream& ostr ) : m_ostr( &ostr ) {}
std::ostream& operator*() const { return *m_ostr; }
private:
std::ostream* const m_ostr;
};
//<API key>//
template<typename Uniq> struct custom_manip {};
//<API key>//
template<typename Uniq>
inline custom_printer<custom_manip<Uniq> >
operator<<( std::ostream& ostr, custom_manip<Uniq> const& ) { return custom_printer<custom_manip<Uniq> >( ostr ); }
//<API key>//
} // namespace unit_test
} // namespace boost
//<API key>//
#include <boost/test/detail/enable_warnings.hpp>
#endif // <API key> |
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
global $currentModule;
global $mod_strings;
global $app_strings;
global $theme;
global $focus;
global $action;
// focus_list is the means of passing data to a SubPanelView.
global $focus_list;
$button = "<table cellspacing='0' cellpadding='1' border='0'><form border='0' action='index.php' method='post' name='form' id='form'>\n";
$button .= "<input type='hidden' name='module' value='Contacts'>\n";
if ($currentModule == 'Accounts') $button .= "<input type='hidden' name='account_id' value='$focus->id'>\n<input type='hidden' name='account_name' value='$focus->name'>\n";
$button .= "<input type='hidden' name='return_module' value='".$currentModule."'>\n";
$button .= "<input type='hidden' name='return_action' value='".$action."'>\n";
$button .= "<input type='hidden' name='return_id' value='".$focus->id."'>\n";
$button .= "<input type='hidden' name='action'>\n";
$button .= "<tr><td> </td>";
if ($focus->parent_type == "Accounts") $button .= "<td><input title='".$app_strings['<API key>']."' type='button' class='button' value='".$app_strings['<API key>']."' name='button' LANGUAGE=javascript onclick='window.open(\"index.php?module=Contacts&action=Popup&html=Popup_picker&form=DetailView&form_submit=true&query=true&account_id=$focus->parent_id&account_name=".urlencode($focus->parent_name)."\",\"new\",\"width=600,height=400,resizable=1,scrollbars=1\");'></td>\n";
else $button .= "<td><input title='".$app_strings['<API key>']."' type='button' class='button' value='".$app_strings['<API key>']."' name='button' LANGUAGE=javascript onclick='window.open(\"index.php?module=Contacts&action=Popup&html=Popup_picker&form=DetailView&form_submit=true\",\"new\",\"width=600,height=400,resizable=1,scrollbars=1\");'></td>\n";
$button .= "<td><input title='".$app_strings['<API key>']."' type='button' class='button' value='".$app_strings['<API key>']."' name='button' LANGUAGE=javascript onclick='window.open(\"index.php?module=Users&action=Popup&html=Popup_picker&form=DetailView&form_submit=true\",\"new\",\"width=600,height=400,resizable=1,scrollbars=1\");'></td>\n";
$button .= "</tr></form></table>\n";
// Stick the form header out there.
echo get_form_header($mod_strings['LBL_INVITEE'], $button, false);
$xtpl=new XTemplate ('modules/Emails/<API key>.html');
$xtpl->assign("MOD", $mod_strings);
$xtpl->assign("APP", $app_strings);
$xtpl->assign("RETURN_URL", "&return_module=$currentModule&return_action=DetailView&return_id=$focus->id");
$xtpl->assign("EMAIL_ID", $focus->id);
$xtpl->assign("DELETE_INLINE_PNG", SugarThemeRegistry::current()->getImage('delete_inline','align="absmiddle" border="0"',null,null,'.gif',$app_strings['LNK_REMOVE']));
$xtpl->assign("EDIT_INLINE_PNG", SugarThemeRegistry::current()->getImage('edit_inline','align="absmiddle" border="0"', null,null,'.gif',$app_strings['LNK_EDIT']));
$oddRow = true;
foreach($focus_users_list as $user)
{
$user_fields = array(
'USER_NAME' => $user->user_name,
'FULL_NAME' => $user->first_name." ".$user->last_name,
'ID' => $user->id,
'EMAIL' => $user->email1,
'PHONE_WORK' => $user->phone_work
);
$xtpl->assign("USER", $user_fields);
if($oddRow)
{
//todo move to themes
$xtpl->assign("ROW_COLOR", 'oddListRow');
}
else
{
//todo move to themes
$xtpl->assign("ROW_COLOR", 'evenListRow');
}
$oddRow = !$oddRow;
$xtpl->parse("users.row");
// Put the rows in.
}
$xtpl->parse("users");
$xtpl->out("users");
$oddRow = true;
print count($focus_contacts_list);
foreach($focus_contacts_list as $contact)
{
$contact_fields = array(
'FIRST_NAME' => $contact->first_name,
'LAST_NAME' => $contact->last_name,
'ACCOUNT_NAME' => $contact->account_name,
'ID' => $contact->id,
'EMAIL' => $contact->email1,
'PHONE_WORK' => $contact->phone_work
);
$xtpl->assign("CONTACT", $contact_fields);
if($oddRow)
{
//todo move to themes
$xtpl->assign("ROW_COLOR", 'oddListRow');
}
else
{
//todo move to themes
$xtpl->assign("ROW_COLOR", 'evenListRow');
}
$oddRow = !$oddRow;
$xtpl->parse("contacts.row");
// Put the rows in.
}
$xtpl->parse("contacts");
$xtpl->out("contacts");
?> |
#include <linux/i2c.h>
#include "mhl_i2c_utils.h"
#include "mhl_8334.h"
uint8_t slave_addrs[MAX_PAGES] = {
DEV_PAGE_TPI_0 ,
DEV_PAGE_TX_L0_0 ,
DEV_PAGE_TX_L1_0 ,
DEV_PAGE_TX_2_0 ,
DEV_PAGE_TX_3_0 ,
DEV_PAGE_CBUS ,
DEV_PAGE_DDC_EDID ,
DEV_PAGE_DDC_SEGM ,
};
int mhl_i2c_reg_read(uint8_t slave_addr_index, uint8_t reg_offset)
{
struct i2c_msg msgs[2];
uint8_t buffer = 0;
int ret = -1;
pr_debug("MRR: Reading from slave_addr_index=[%x] and offset=[%x]\n",
slave_addr_index, reg_offset);
pr_debug("MRR: Addr slave_addr_index=[%x]\n",
slave_addrs[slave_addr_index]);
/* Slave addr */
msgs[0].addr = slave_addrs[slave_addr_index] >> 1;
msgs[1].addr = slave_addrs[slave_addr_index] >> 1;
/* Write Command */
msgs[0].flags = 0;
msgs[1].flags = I2C_M_RD;
/* Register offset for the next transaction */
msgs[0].buf = ®_offset;
msgs[1].buf = &buffer;
/* Offset is 1 Byte long */
msgs[0].len = 1;
msgs[1].len = 1;
ret = i2c_transfer(mhl_msm_state->i2c_client->adapter, msgs, 2);
if (ret < 1) {
pr_err("I2C READ FAILED=[%d]\n", ret);
return -EACCES;
}
pr_debug("Buffer is [%x]\n", buffer);
return buffer;
}
int mhl_i2c_reg_write(uint8_t slave_addr_index, uint8_t reg_offset,
uint8_t value)
{
return <API key>(slave_addr_index, reg_offset, &value, 1);
}
int <API key>(uint8_t slave_addr_index, uint8_t reg_offset,
uint8_t *value, uint16_t count)
{
struct i2c_msg msgs[1];
uint8_t data[2];
int status = -EACCES;
msgs[0].addr = slave_addrs[slave_addr_index] >> 1;
msgs[0].flags = 0;
msgs[0].len = 2;
msgs[0].buf = data;
data[0] = reg_offset;
data[1] = *value;
status = i2c_transfer(mhl_msm_state->i2c_client->adapter, msgs, 1);
if (status < 1) {
pr_err("I2C WRITE FAILED=[%d]\n", status);
return -EACCES;
}
return status;
}
void mhl_i2c_reg_modify(uint8_t slave_addr_index, uint8_t reg_offset,
uint8_t mask, uint8_t val)
{
uint8_t temp;
temp = mhl_i2c_reg_read(slave_addr_index, reg_offset);
temp &= (~mask);
temp |= (mask & val);
mhl_i2c_reg_write(slave_addr_index, reg_offset, temp);
} |
module.exports = require('./lib/less-node'); |
#include <linux/kernel.h>
#include <linux/syscalls.h>
#include <linux/sysctl.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/signal.h>
#include <linux/resource.h>
#include <linux/times.h>
#include <linux/utsname.h>
#include <linux/smp.h>
#include <linux/smp_lock.h>
#include <linux/sem.h>
#include <linux/msg.h>
#include <linux/mm.h>
#include <linux/shm.h>
#include <linux/slab.h>
#include <linux/uio.h>
#include <linux/nfs_fs.h>
#include <linux/quota.h>
#include <linux/syscalls.h>
#include <linux/sunrpc/svc.h>
#include <linux/nfsd/nfsd.h>
#include <linux/nfsd/cache.h>
#include <linux/nfsd/xdr.h>
#include <linux/nfsd/syscall.h>
#include <linux/poll.h>
#include <linux/eventpoll.h>
#include <linux/personality.h>
#include <linux/ptrace.h>
#include <linux/stat.h>
#include <linux/ipc.h>
#include <linux/capability.h>
#include <linux/compat.h>
#include <linux/vfs.h>
#include <linux/mman.h>
#include <linux/mutex.h>
#include <asm/intrinsics.h>
#include <asm/types.h>
#include <asm/uaccess.h>
#include <asm/unistd.h>
#include "ia32priv.h"
#include <net/scm.h>
#include <net/sock.h>
#define DEBUG 0
#if DEBUG
# define DBG(fmt...) printk(KERN_DEBUG fmt)
#else
# define DBG(fmt...)
#endif
#define ROUND_UP(x,a) ((__typeof__(x))(((unsigned long)(x) + ((a) - 1)) & ~((a) - 1)))
#define OFFSET4K(a) ((a) & 0xfff)
#define PAGE_START(addr) ((addr) & PAGE_MASK)
#define MINSIGSTKSZ_IA32 2048
#define high2lowuid(uid) ((uid) > 65535 ? 65534 : (uid))
#define high2lowgid(gid) ((gid) > 65535 ? 65534 : (gid))
/*
* Anything that modifies or inspects ia32 user virtual memory must hold this semaphore
* while doing so.
*/
/* XXX make per-mm: */
static DEFINE_MUTEX(ia32_mmap_mutex);
asmlinkage long
sys32_execve (char __user *name, compat_uptr_t __user *argv, compat_uptr_t __user *envp,
struct pt_regs *regs)
{
long error;
char *filename;
unsigned long old_map_base, old_task_size, tssd;
filename = getname(name);
error = PTR_ERR(filename);
if (IS_ERR(filename))
return error;
old_map_base = current->thread.map_base;
old_task_size = current->thread.task_size;
tssd = ia64_get_kr(IA64_KR_TSSD);
/* we may be exec'ing a 64-bit process: reset map base, task-size, and io-base: */
current->thread.map_base = DEFAULT_MAP_BASE;
current->thread.task_size = DEFAULT_TASK_SIZE;
ia64_set_kr(IA64_KR_IO_BASE, current->thread.old_iob);
ia64_set_kr(IA64_KR_TSSD, current->thread.old_k1);
error = compat_do_execve(filename, argv, envp, regs);
putname(filename);
if (error < 0) {
/* oops, execve failed, switch back to old values... */
ia64_set_kr(IA64_KR_IO_BASE, IA32_IOBASE);
ia64_set_kr(IA64_KR_TSSD, tssd);
current->thread.map_base = old_map_base;
current->thread.task_size = old_task_size;
}
return error;
}
int cp_compat_stat(struct kstat *stat, struct compat_stat __user *ubuf)
{
compat_ino_t ino;
int err;
if ((u64) stat->size > MAX_NON_LFS ||
!old_valid_dev(stat->dev) ||
!old_valid_dev(stat->rdev))
return -EOVERFLOW;
ino = stat->ino;
if (sizeof(ino) < sizeof(stat->ino) && ino != stat->ino)
return -EOVERFLOW;
if (clear_user(ubuf, sizeof(*ubuf)))
return -EFAULT;
err = __put_user(old_encode_dev(stat->dev), &ubuf->st_dev);
err |= __put_user(ino, &ubuf->st_ino);
err |= __put_user(stat->mode, &ubuf->st_mode);
err |= __put_user(stat->nlink, &ubuf->st_nlink);
err |= __put_user(high2lowuid(stat->uid), &ubuf->st_uid);
err |= __put_user(high2lowgid(stat->gid), &ubuf->st_gid);
err |= __put_user(old_encode_dev(stat->rdev), &ubuf->st_rdev);
err |= __put_user(stat->size, &ubuf->st_size);
err |= __put_user(stat->atime.tv_sec, &ubuf->st_atime);
err |= __put_user(stat->atime.tv_nsec, &ubuf->st_atime_nsec);
err |= __put_user(stat->mtime.tv_sec, &ubuf->st_mtime);
err |= __put_user(stat->mtime.tv_nsec, &ubuf->st_mtime_nsec);
err |= __put_user(stat->ctime.tv_sec, &ubuf->st_ctime);
err |= __put_user(stat->ctime.tv_nsec, &ubuf->st_ctime_nsec);
err |= __put_user(stat->blksize, &ubuf->st_blksize);
err |= __put_user(stat->blocks, &ubuf->st_blocks);
return err;
}
#if PAGE_SHIFT > IA32_PAGE_SHIFT
static int
get_page_prot (struct vm_area_struct *vma, unsigned long addr)
{
int prot = 0;
if (!vma || vma->vm_start > addr)
return 0;
if (vma->vm_flags & VM_READ)
prot |= PROT_READ;
if (vma->vm_flags & VM_WRITE)
prot |= PROT_WRITE;
if (vma->vm_flags & VM_EXEC)
prot |= PROT_EXEC;
return prot;
}
/*
* Map a subpage by creating an anonymous page that contains the union of the old page and
* the subpage.
*/
static unsigned long
mmap_subpage (struct file *file, unsigned long start, unsigned long end, int prot, int flags,
loff_t off)
{
void *page = NULL;
struct inode *inode;
unsigned long ret = 0;
struct vm_area_struct *vma = find_vma(current->mm, start);
int old_prot = get_page_prot(vma, start);
DBG("mmap_subpage(file=%p,start=0x%lx,end=0x%lx,prot=%x,flags=%x,off=0x%llx)\n",
file, start, end, prot, flags, off);
/* Optimize the case where the old mmap and the new mmap are both anonymous */
if ((old_prot & PROT_WRITE) && (flags & MAP_ANONYMOUS) && !vma->vm_file) {
if (clear_user((void __user *) start, end - start)) {
ret = -EFAULT;
goto out;
}
goto skip_mmap;
}
page = (void *) get_zeroed_page(GFP_KERNEL);
if (!page)
return -ENOMEM;
if (old_prot)
copy_from_user(page, (void __user *) PAGE_START(start), PAGE_SIZE);
down_write(¤t->mm->mmap_sem);
{
ret = do_mmap(NULL, PAGE_START(start), PAGE_SIZE, prot | PROT_WRITE,
flags | MAP_FIXED | MAP_ANONYMOUS, 0);
}
up_write(¤t->mm->mmap_sem);
if (IS_ERR((void *) ret))
goto out;
if (old_prot) {
/* copy back the old page contents. */
if (offset_in_page(start))
copy_to_user((void __user *) PAGE_START(start), page,
offset_in_page(start));
if (offset_in_page(end))
copy_to_user((void __user *) end, page + offset_in_page(end),
PAGE_SIZE - offset_in_page(end));
}
if (!(flags & MAP_ANONYMOUS)) {
/* read the file contents */
inode = file->f_path.dentry->d_inode;
if (!inode->i_fop || !file->f_op->read
|| ((*file->f_op->read)(file, (char __user *) start, end - start, &off) < 0))
{
ret = -EINVAL;
goto out;
}
}
skip_mmap:
if (!(prot & PROT_WRITE))
ret = sys_mprotect(PAGE_START(start), PAGE_SIZE, prot | old_prot);
out:
if (page)
free_page((unsigned long) page);
return ret;
}
/* SLAB cache for partial_page structures */
struct kmem_cache *partial_page_cachep;
/*
* init partial_page_list.
* return 0 means kmalloc fail.
*/
struct partial_page_list*
ia32_init_pp_list(void)
{
struct partial_page_list *p;
if ((p = kmalloc(sizeof(*p), GFP_KERNEL)) == NULL)
return p;
p->pp_head = NULL;
p->ppl_rb = RB_ROOT;
p->pp_hint = NULL;
atomic_set(&p->pp_count, 1);
return p;
}
/*
* Search for the partial page with @start in partial page list @ppl.
* If finds the partial page, return the found partial page.
* Else, return 0 and provide @pprev, @rb_link, @rb_parent to
* be used by later __ia32_insert_pp().
*/
static struct partial_page *
__ia32_find_pp(struct partial_page_list *ppl, unsigned int start,
struct partial_page **pprev, struct rb_node ***rb_link,
struct rb_node **rb_parent)
{
struct partial_page *pp;
struct rb_node **__rb_link, *__rb_parent, *rb_prev;
pp = ppl->pp_hint;
if (pp && pp->base == start)
return pp;
__rb_link = &ppl->ppl_rb.rb_node;
rb_prev = __rb_parent = NULL;
while (*__rb_link) {
__rb_parent = *__rb_link;
pp = rb_entry(__rb_parent, struct partial_page, pp_rb);
if (pp->base == start) {
ppl->pp_hint = pp;
return pp;
} else if (pp->base < start) {
rb_prev = __rb_parent;
__rb_link = &__rb_parent->rb_right;
} else {
__rb_link = &__rb_parent->rb_left;
}
}
*rb_link = __rb_link;
*rb_parent = __rb_parent;
*pprev = NULL;
if (rb_prev)
*pprev = rb_entry(rb_prev, struct partial_page, pp_rb);
return NULL;
}
/*
* insert @pp into @ppl.
*/
static void
__ia32_insert_pp(struct partial_page_list *ppl, struct partial_page *pp,
struct partial_page *prev, struct rb_node **rb_link,
struct rb_node *rb_parent)
{
/* link list */
if (prev) {
pp->next = prev->next;
prev->next = pp;
} else {
ppl->pp_head = pp;
if (rb_parent)
pp->next = rb_entry(rb_parent,
struct partial_page, pp_rb);
else
pp->next = NULL;
}
/* link rb */
rb_link_node(&pp->pp_rb, rb_parent, rb_link);
rb_insert_color(&pp->pp_rb, &ppl->ppl_rb);
ppl->pp_hint = pp;
}
/*
* delete @pp from partial page list @ppl.
*/
static void
__ia32_delete_pp(struct partial_page_list *ppl, struct partial_page *pp,
struct partial_page *prev)
{
if (prev) {
prev->next = pp->next;
if (ppl->pp_hint == pp)
ppl->pp_hint = prev;
} else {
ppl->pp_head = pp->next;
if (ppl->pp_hint == pp)
ppl->pp_hint = pp->next;
}
rb_erase(&pp->pp_rb, &ppl->ppl_rb);
kmem_cache_free(partial_page_cachep, pp);
}
static struct partial_page *
__pp_prev(struct partial_page *pp)
{
struct rb_node *prev = rb_prev(&pp->pp_rb);
if (prev)
return rb_entry(prev, struct partial_page, pp_rb);
else
return NULL;
}
/*
* Delete partial pages with address between @start and @end.
* @start and @end are page aligned.
*/
static void
<API key>(unsigned int start, unsigned int end)
{
struct partial_page *pp, *prev;
struct rb_node **rb_link, *rb_parent;
if (start >= end)
return;
pp = __ia32_find_pp(current->thread.ppl, start, &prev,
&rb_link, &rb_parent);
if (pp)
prev = __pp_prev(pp);
else {
if (prev)
pp = prev->next;
else
pp = current->thread.ppl->pp_head;
}
while (pp && pp->base < end) {
struct partial_page *tmp = pp->next;
__ia32_delete_pp(current->thread.ppl, pp, prev);
pp = tmp;
}
}
/*
* Set the range between @start and @end in bitmap.
* @start and @end should be IA32 page aligned and in the same IA64 page.
*/
static int
__ia32_set_pp(unsigned int start, unsigned int end, int flags)
{
struct partial_page *pp, *prev;
struct rb_node ** rb_link, *rb_parent;
unsigned int pstart, start_bit, end_bit, i;
pstart = PAGE_START(start);
start_bit = (start % PAGE_SIZE) / IA32_PAGE_SIZE;
end_bit = (end % PAGE_SIZE) / IA32_PAGE_SIZE;
if (end_bit == 0)
end_bit = PAGE_SIZE / IA32_PAGE_SIZE;
pp = __ia32_find_pp(current->thread.ppl, pstart, &prev,
&rb_link, &rb_parent);
if (pp) {
for (i = start_bit; i < end_bit; i++)
set_bit(i, &pp->bitmap);
/*
* Check: if this partial page has been set to a full page,
* then delete it.
*/
if (find_first_zero_bit(&pp->bitmap, sizeof(pp->bitmap)*8) >=
PAGE_SIZE/IA32_PAGE_SIZE) {
__ia32_delete_pp(current->thread.ppl, pp, __pp_prev(pp));
}
return 0;
}
/*
* MAP_FIXED may lead to overlapping mmap.
* In this case, the requested mmap area may already mmaped as a full
* page. So check vma before adding a new partial page.
*/
if (flags & MAP_FIXED) {
struct vm_area_struct *vma = find_vma(current->mm, pstart);
if (vma && vma->vm_start <= pstart)
return 0;
}
/* new a partial_page */
pp = kmem_cache_alloc(partial_page_cachep, GFP_KERNEL);
if (!pp)
return -ENOMEM;
pp->base = pstart;
pp->bitmap = 0;
for (i=start_bit; i<end_bit; i++)
set_bit(i, &(pp->bitmap));
pp->next = NULL;
__ia32_insert_pp(current->thread.ppl, pp, prev, rb_link, rb_parent);
return 0;
}
/*
* @start and @end should be IA32 page aligned, but don't need to be in the
* same IA64 page. Split @start and @end to make sure they're in the same IA64
* page, then call __ia32_set_pp().
*/
static void
ia32_set_pp(unsigned int start, unsigned int end, int flags)
{
down_write(¤t->mm->mmap_sem);
if (flags & MAP_FIXED) {
/*
* MAP_FIXED may lead to overlapping mmap. When this happens,
* a series of complete IA64 pages results in deletion of
* old partial pages in that range.
*/
<API key>(PAGE_ALIGN(start), PAGE_START(end));
}
if (end < PAGE_ALIGN(start)) {
__ia32_set_pp(start, end, flags);
} else {
if (offset_in_page(start))
__ia32_set_pp(start, PAGE_ALIGN(start), flags);
if (offset_in_page(end))
__ia32_set_pp(PAGE_START(end), end, flags);
}
up_write(¤t->mm->mmap_sem);
}
/*
* Unset the range between @start and @end in bitmap.
* @start and @end should be IA32 page aligned and in the same IA64 page.
* After doing that, if the bitmap is 0, then free the page and return 1,
* else return 0;
* If not find the partial page in the list, then
* If the vma exists, then the full page is set to a partial page;
* Else return -ENOMEM.
*/
static int
__ia32_unset_pp(unsigned int start, unsigned int end)
{
struct partial_page *pp, *prev;
struct rb_node ** rb_link, *rb_parent;
unsigned int pstart, start_bit, end_bit, i;
struct vm_area_struct *vma;
pstart = PAGE_START(start);
start_bit = (start % PAGE_SIZE) / IA32_PAGE_SIZE;
end_bit = (end % PAGE_SIZE) / IA32_PAGE_SIZE;
if (end_bit == 0)
end_bit = PAGE_SIZE / IA32_PAGE_SIZE;
pp = __ia32_find_pp(current->thread.ppl, pstart, &prev,
&rb_link, &rb_parent);
if (pp) {
for (i = start_bit; i < end_bit; i++)
clear_bit(i, &pp->bitmap);
if (pp->bitmap == 0) {
__ia32_delete_pp(current->thread.ppl, pp, __pp_prev(pp));
return 1;
}
return 0;
}
vma = find_vma(current->mm, pstart);
if (!vma || vma->vm_start > pstart) {
return -ENOMEM;
}
/* new a partial_page */
pp = kmem_cache_alloc(partial_page_cachep, GFP_KERNEL);
if (!pp)
return -ENOMEM;
pp->base = pstart;
pp->bitmap = 0;
for (i = 0; i < start_bit; i++)
set_bit(i, &(pp->bitmap));
for (i = end_bit; i < PAGE_SIZE / IA32_PAGE_SIZE; i++)
set_bit(i, &(pp->bitmap));
pp->next = NULL;
__ia32_insert_pp(current->thread.ppl, pp, prev, rb_link, rb_parent);
return 0;
}
/*
* Delete pp between PAGE_ALIGN(start) and PAGE_START(end) by calling
* <API key>(). Unset possible partial pages by calling
* __ia32_unset_pp().
* The returned value see __ia32_unset_pp().
*/
static int
ia32_unset_pp(unsigned int *startp, unsigned int *endp)
{
unsigned int start = *startp, end = *endp;
int ret = 0;
down_write(¤t->mm->mmap_sem);
<API key>(PAGE_ALIGN(start), PAGE_START(end));
if (end < PAGE_ALIGN(start)) {
ret = __ia32_unset_pp(start, end);
if (ret == 1) {
*startp = PAGE_START(start);
*endp = PAGE_ALIGN(end);
}
if (ret == 0) {
/* to shortcut sys_munmap() in sys32_munmap() */
*startp = PAGE_START(start);
*endp = PAGE_START(end);
}
} else {
if (offset_in_page(start)) {
ret = __ia32_unset_pp(start, PAGE_ALIGN(start));
if (ret == 1)
*startp = PAGE_START(start);
if (ret == 0)
*startp = PAGE_ALIGN(start);
if (ret < 0)
goto out;
}
if (offset_in_page(end)) {
ret = __ia32_unset_pp(PAGE_START(end), end);
if (ret == 1)
*endp = PAGE_ALIGN(end);
if (ret == 0)
*endp = PAGE_START(end);
}
}
out:
up_write(¤t->mm->mmap_sem);
return ret;
}
/*
* Compare the range between @start and @end with bitmap in partial page.
* @start and @end should be IA32 page aligned and in the same IA64 page.
*/
static int
__ia32_compare_pp(unsigned int start, unsigned int end)
{
struct partial_page *pp, *prev;
struct rb_node ** rb_link, *rb_parent;
unsigned int pstart, start_bit, end_bit, size;
unsigned int first_bit, next_zero_bit; /* the first range in bitmap */
pstart = PAGE_START(start);
pp = __ia32_find_pp(current->thread.ppl, pstart, &prev,
&rb_link, &rb_parent);
if (!pp)
return 1;
start_bit = (start % PAGE_SIZE) / IA32_PAGE_SIZE;
end_bit = (end % PAGE_SIZE) / IA32_PAGE_SIZE;
size = sizeof(pp->bitmap) * 8;
first_bit = find_first_bit(&pp->bitmap, size);
next_zero_bit = find_next_zero_bit(&pp->bitmap, size, first_bit);
if ((start_bit < first_bit) || (end_bit > next_zero_bit)) {
/* exceeds the first range in bitmap */
return -ENOMEM;
} else if ((start_bit == first_bit) && (end_bit == next_zero_bit)) {
first_bit = find_next_bit(&pp->bitmap, size, next_zero_bit);
if ((next_zero_bit < first_bit) && (first_bit < size))
return 1; /* has next range */
else
return 0; /* no next range */
} else
return 1;
}
/*
* @start and @end should be IA32 page aligned, but don't need to be in the
* same IA64 page. Split @start and @end to make sure they're in the same IA64
* page, then call __ia32_compare_pp().
*
* Take this as example: the range is the 1st and 2nd 4K page.
* Return 0 if they fit bitmap exactly, i.e. bitmap = 00000011;
* Return 1 if the range doesn't cover whole bitmap, e.g. bitmap = 00001111;
* Return -ENOMEM if the range exceeds the bitmap, e.g. bitmap = 00000001 or
* bitmap = 00000101.
*/
static int
ia32_compare_pp(unsigned int *startp, unsigned int *endp)
{
unsigned int start = *startp, end = *endp;
int retval = 0;
down_write(¤t->mm->mmap_sem);
if (end < PAGE_ALIGN(start)) {
retval = __ia32_compare_pp(start, end);
if (retval == 0) {
*startp = PAGE_START(start);
*endp = PAGE_ALIGN(end);
}
} else {
if (offset_in_page(start)) {
retval = __ia32_compare_pp(start,
PAGE_ALIGN(start));
if (retval == 0)
*startp = PAGE_START(start);
if (retval < 0)
goto out;
}
if (offset_in_page(end)) {
retval = __ia32_compare_pp(PAGE_START(end), end);
if (retval == 0)
*endp = PAGE_ALIGN(end);
}
}
out:
up_write(¤t->mm->mmap_sem);
return retval;
}
static void
__ia32_drop_pp_list(struct partial_page_list *ppl)
{
struct partial_page *pp = ppl->pp_head;
while (pp) {
struct partial_page *next = pp->next;
kmem_cache_free(partial_page_cachep, pp);
pp = next;
}
kfree(ppl);
}
void
<API key>(struct task_struct *task)
{
struct partial_page_list* ppl = task->thread.ppl;
if (ppl && atomic_dec_and_test(&ppl->pp_count))
__ia32_drop_pp_list(ppl);
}
/*
* Copy current->thread.ppl to ppl (already initialized).
*/
static int
__ia32_copy_pp_list(struct partial_page_list *ppl)
{
struct partial_page *pp, *tmp, *prev;
struct rb_node **rb_link, *rb_parent;
ppl->pp_head = NULL;
ppl->pp_hint = NULL;
ppl->ppl_rb = RB_ROOT;
rb_link = &ppl->ppl_rb.rb_node;
rb_parent = NULL;
prev = NULL;
for (pp = current->thread.ppl->pp_head; pp; pp = pp->next) {
tmp = kmem_cache_alloc(partial_page_cachep, GFP_KERNEL);
if (!tmp)
return -ENOMEM;
*tmp = *pp;
__ia32_insert_pp(ppl, tmp, prev, rb_link, rb_parent);
prev = tmp;
rb_link = &tmp->pp_rb.rb_right;
rb_parent = &tmp->pp_rb;
}
return 0;
}
int
<API key>(struct task_struct *p, unsigned long clone_flags)
{
int retval = 0;
if (clone_flags & CLONE_VM) {
atomic_inc(¤t->thread.ppl->pp_count);
p->thread.ppl = current->thread.ppl;
} else {
p->thread.ppl = ia32_init_pp_list();
if (!p->thread.ppl)
return -ENOMEM;
down_write(¤t->mm->mmap_sem);
{
retval = __ia32_copy_pp_list(p->thread.ppl);
}
up_write(¤t->mm->mmap_sem);
}
return retval;
}
static unsigned long
emulate_mmap (struct file *file, unsigned long start, unsigned long len, int prot, int flags,
loff_t off)
{
unsigned long tmp, end, pend, pstart, ret, is_congruent, fudge = 0;
struct inode *inode;
loff_t poff;
end = start + len;
pstart = PAGE_START(start);
pend = PAGE_ALIGN(end);
if (flags & MAP_FIXED) {
ia32_set_pp((unsigned int)start, (unsigned int)end, flags);
if (start > pstart) {
if (flags & MAP_SHARED)
printk(KERN_INFO
"%s(%d): emulate_mmap() can't share head (addr=0x%lx)\n",
current->comm, current->pid, start);
ret = mmap_subpage(file, start, min(PAGE_ALIGN(start), end), prot, flags,
off);
if (IS_ERR((void *) ret))
return ret;
pstart += PAGE_SIZE;
if (pstart >= pend)
goto out; /* done */
}
if (end < pend) {
if (flags & MAP_SHARED)
printk(KERN_INFO
"%s(%d): emulate_mmap() can't share tail (end=0x%lx)\n",
current->comm, current->pid, end);
ret = mmap_subpage(file, max(start, PAGE_START(end)), end, prot, flags,
(off + len) - offset_in_page(end));
if (IS_ERR((void *) ret))
return ret;
pend -= PAGE_SIZE;
if (pstart >= pend)
goto out; /* done */
}
} else {
/*
* If a start address was specified, use it if the entire rounded out area
* is available.
*/
if (start && !pstart)
fudge = 1; /* handle case of mapping to range (0,PAGE_SIZE) */
tmp = <API key>(file, pstart - fudge, pend - pstart, 0, flags);
if (tmp != pstart) {
pstart = tmp;
start = pstart + offset_in_page(off); /* make start congruent with off */
end = start + len;
pend = PAGE_ALIGN(end);
}
}
poff = off + (pstart - start); /* note: (pstart - start) may be negative */
is_congruent = (flags & MAP_ANONYMOUS) || (offset_in_page(poff) == 0);
if ((flags & MAP_SHARED) && !is_congruent)
printk(KERN_INFO "%s(%d): emulate_mmap() can't share contents of incongruent mmap "
"(addr=0x%lx,off=0x%llx)\n", current->comm, current->pid, start, off);
DBG("mmap_body: mapping [0x%lx-0x%lx) %s with poff 0x%llx\n", pstart, pend,
is_congruent ? "congruent" : "not congruent", poff);
down_write(¤t->mm->mmap_sem);
{
if (!(flags & MAP_ANONYMOUS) && is_congruent)
ret = do_mmap(file, pstart, pend - pstart, prot, flags | MAP_FIXED, poff);
else
ret = do_mmap(NULL, pstart, pend - pstart,
prot | ((flags & MAP_ANONYMOUS) ? 0 : PROT_WRITE),
flags | MAP_FIXED | MAP_ANONYMOUS, 0);
}
up_write(¤t->mm->mmap_sem);
if (IS_ERR((void *) ret))
return ret;
if (!is_congruent) {
/* read the file contents */
inode = file->f_path.dentry->d_inode;
if (!inode->i_fop || !file->f_op->read
|| ((*file->f_op->read)(file, (char __user *) pstart, pend - pstart, &poff)
< 0))
{
sys_munmap(pstart, pend - pstart);
return -EINVAL;
}
if (!(prot & PROT_WRITE) && sys_mprotect(pstart, pend - pstart, prot) < 0)
return -EINVAL;
}
if (!(flags & MAP_FIXED))
ia32_set_pp((unsigned int)start, (unsigned int)end, flags);
out:
return start;
}
#endif /* PAGE_SHIFT > IA32_PAGE_SHIFT */
static inline unsigned int
get_prot32 (unsigned int prot)
{
if (prot & PROT_WRITE)
/* on x86, PROT_WRITE implies PROT_READ which implies PROT_EEC */
prot |= PROT_READ | PROT_WRITE | PROT_EXEC;
else if (prot & (PROT_READ | PROT_EXEC))
/* on x86, there is no distinction between PROT_READ and PROT_EXEC */
prot |= (PROT_READ | PROT_EXEC);
return prot;
}
unsigned long
ia32_do_mmap (struct file *file, unsigned long addr, unsigned long len, int prot, int flags,
loff_t offset)
{
DBG("ia32_do_mmap(file=%p,addr=0x%lx,len=0x%lx,prot=%x,flags=%x,offset=0x%llx)\n",
file, addr, len, prot, flags, offset);
if (file && (!file->f_op || !file->f_op->mmap))
return -ENODEV;
len = IA32_PAGE_ALIGN(len);
if (len == 0)
return addr;
if (len > IA32_PAGE_OFFSET || addr > IA32_PAGE_OFFSET - len)
{
if (flags & MAP_FIXED)
return -ENOMEM;
else
return -EINVAL;
}
if (OFFSET4K(offset))
return -EINVAL;
prot = get_prot32(prot);
#if PAGE_SHIFT > IA32_PAGE_SHIFT
mutex_lock(&ia32_mmap_mutex);
{
addr = emulate_mmap(file, addr, len, prot, flags, offset);
}
mutex_unlock(&ia32_mmap_mutex);
#else
down_write(¤t->mm->mmap_sem);
{
addr = do_mmap(file, addr, len, prot, flags, offset);
}
up_write(¤t->mm->mmap_sem);
#endif
DBG("ia32_do_mmap: returning 0x%lx\n", addr);
return addr;
}
/*
* Linux/i386 didn't use to be able to handle more than 4 system call parameters, so these
* system calls used a memory block for parameter passing..
*/
struct mmap_arg_struct {
unsigned int addr;
unsigned int len;
unsigned int prot;
unsigned int flags;
unsigned int fd;
unsigned int offset;
};
asmlinkage long
sys32_mmap (struct mmap_arg_struct __user *arg)
{
struct mmap_arg_struct a;
struct file *file = NULL;
unsigned long addr;
int flags;
if (copy_from_user(&a, arg, sizeof(a)))
return -EFAULT;
if (OFFSET4K(a.offset))
return -EINVAL;
flags = a.flags;
flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);
if (!(flags & MAP_ANONYMOUS)) {
file = fget(a.fd);
if (!file)
return -EBADF;
}
addr = ia32_do_mmap(file, a.addr, a.len, a.prot, flags, a.offset);
if (file)
fput(file);
return addr;
}
asmlinkage long
sys32_mmap2 (unsigned int addr, unsigned int len, unsigned int prot, unsigned int flags,
unsigned int fd, unsigned int pgoff)
{
struct file *file = NULL;
unsigned long retval;
flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);
if (!(flags & MAP_ANONYMOUS)) {
file = fget(fd);
if (!file)
return -EBADF;
}
retval = ia32_do_mmap(file, addr, len, prot, flags,
(unsigned long) pgoff << IA32_PAGE_SHIFT);
if (file)
fput(file);
return retval;
}
asmlinkage long
sys32_munmap (unsigned int start, unsigned int len)
{
unsigned int end = start + len;
long ret;
#if PAGE_SHIFT <= IA32_PAGE_SHIFT
ret = sys_munmap(start, end - start);
#else
if (OFFSET4K(start))
return -EINVAL;
end = IA32_PAGE_ALIGN(end);
if (start >= end)
return -EINVAL;
ret = ia32_unset_pp(&start, &end);
if (ret < 0)
return ret;
if (start >= end)
return 0;
mutex_lock(&ia32_mmap_mutex);
ret = sys_munmap(start, end - start);
mutex_unlock(&ia32_mmap_mutex);
#endif
return ret;
}
#if PAGE_SHIFT > IA32_PAGE_SHIFT
static long
mprotect_subpage (unsigned long address, int new_prot)
{
int old_prot;
struct vm_area_struct *vma;
if (new_prot == PROT_NONE)
return 0; /* optimize case where nothing changes... */
vma = find_vma(current->mm, address);
old_prot = get_page_prot(vma, address);
return sys_mprotect(address, PAGE_SIZE, new_prot | old_prot);
}
#endif /* PAGE_SHIFT > IA32_PAGE_SHIFT */
asmlinkage long
sys32_mprotect (unsigned int start, unsigned int len, int prot)
{
unsigned int end = start + len;
#if PAGE_SHIFT > IA32_PAGE_SHIFT
long retval = 0;
#endif
prot = get_prot32(prot);
#if PAGE_SHIFT <= IA32_PAGE_SHIFT
return sys_mprotect(start, end - start, prot);
#else
if (OFFSET4K(start))
return -EINVAL;
end = IA32_PAGE_ALIGN(end);
if (end < start)
return -EINVAL;
retval = ia32_compare_pp(&start, &end);
if (retval < 0)
return retval;
mutex_lock(&ia32_mmap_mutex);
{
if (offset_in_page(start)) {
/* start address is 4KB aligned but not page aligned. */
retval = mprotect_subpage(PAGE_START(start), prot);
if (retval < 0)
goto out;
start = PAGE_ALIGN(start);
if (start >= end)
goto out; /* retval is already zero... */
}
if (offset_in_page(end)) {
/* end address is 4KB aligned but not page aligned. */
retval = mprotect_subpage(PAGE_START(end), prot);
if (retval < 0)
goto out;
end = PAGE_START(end);
}
retval = sys_mprotect(start, end - start, prot);
}
out:
mutex_unlock(&ia32_mmap_mutex);
return retval;
#endif
}
asmlinkage long
sys32_mremap (unsigned int addr, unsigned int old_len, unsigned int new_len,
unsigned int flags, unsigned int new_addr)
{
long ret;
#if PAGE_SHIFT <= IA32_PAGE_SHIFT
ret = sys_mremap(addr, old_len, new_len, flags, new_addr);
#else
unsigned int old_end, new_end;
if (OFFSET4K(addr))
return -EINVAL;
old_len = IA32_PAGE_ALIGN(old_len);
new_len = IA32_PAGE_ALIGN(new_len);
old_end = addr + old_len;
new_end = addr + new_len;
if (!new_len)
return -EINVAL;
if ((flags & MREMAP_FIXED) && (OFFSET4K(new_addr)))
return -EINVAL;
if (old_len >= new_len) {
ret = sys32_munmap(addr + new_len, old_len - new_len);
if (ret && old_len != new_len)
return ret;
ret = addr;
if (!(flags & MREMAP_FIXED) || (new_addr == addr))
return ret;
old_len = new_len;
}
addr = PAGE_START(addr);
old_len = PAGE_ALIGN(old_end) - addr;
new_len = PAGE_ALIGN(new_end) - addr;
mutex_lock(&ia32_mmap_mutex);
ret = sys_mremap(addr, old_len, new_len, flags, new_addr);
mutex_unlock(&ia32_mmap_mutex);
if ((ret >= 0) && (old_len < new_len)) {
/* mremap expanded successfully */
ia32_set_pp(old_end, new_end, flags);
}
#endif
return ret;
}
asmlinkage long
sys32_pipe (int __user *fd)
{
int retval;
int fds[2];
retval = do_pipe(fds);
if (retval)
goto out;
if (copy_to_user(fd, fds, sizeof(fds)))
retval = -EFAULT;
out:
return retval;
}
static inline long
get_tv32 (struct timeval *o, struct compat_timeval __user *i)
{
return (!access_ok(VERIFY_READ, i, sizeof(*i)) ||
(__get_user(o->tv_sec, &i->tv_sec) | __get_user(o->tv_usec, &i->tv_usec)));
}
static inline long
put_tv32 (struct compat_timeval __user *o, struct timeval *i)
{
return (!access_ok(VERIFY_WRITE, o, sizeof(*o)) ||
(__put_user(i->tv_sec, &o->tv_sec) | __put_user(i->tv_usec, &o->tv_usec)));
}
asmlinkage unsigned long
sys32_alarm (unsigned int seconds)
{
return alarm_setitimer(seconds);
}
/* Translations due to time_t size differences. Which affects all
sorts of things, like timeval and itimerval. */
extern struct timezone sys_tz;
asmlinkage long
sys32_gettimeofday (struct compat_timeval __user *tv, struct timezone __user *tz)
{
if (tv) {
struct timeval ktv;
do_gettimeofday(&ktv);
if (put_tv32(tv, &ktv))
return -EFAULT;
}
if (tz) {
if (copy_to_user(tz, &sys_tz, sizeof(sys_tz)))
return -EFAULT;
}
return 0;
}
asmlinkage long
sys32_settimeofday (struct compat_timeval __user *tv, struct timezone __user *tz)
{
struct timeval ktv;
struct timespec kts;
struct timezone ktz;
if (tv) {
if (get_tv32(&ktv, tv))
return -EFAULT;
kts.tv_sec = ktv.tv_sec;
kts.tv_nsec = ktv.tv_usec * 1000;
}
if (tz) {
if (copy_from_user(&ktz, tz, sizeof(ktz)))
return -EFAULT;
}
return do_sys_settimeofday(tv ? &kts : NULL, tz ? &ktz : NULL);
}
struct getdents32_callback {
struct compat_dirent __user *current_dir;
struct compat_dirent __user *previous;
int count;
int error;
};
struct readdir32_callback {
struct old_linux32_dirent __user * dirent;
int count;
};
static int
filldir32 (void *__buf, const char *name, int namlen, loff_t offset, u64 ino,
unsigned int d_type)
{
struct compat_dirent __user * dirent;
struct getdents32_callback * buf = (struct getdents32_callback *) __buf;
int reclen = ROUND_UP(offsetof(struct compat_dirent, d_name) + namlen + 1, 4);
u32 d_ino;
buf->error = -EINVAL; /* only used if we fail.. */
if (reclen > buf->count)
return -EINVAL;
d_ino = ino;
if (sizeof(d_ino) < sizeof(ino) && d_ino != ino)
return -EOVERFLOW;
buf->error = -EFAULT; /* only used if we fail.. */
dirent = buf->previous;
if (dirent)
if (put_user(offset, &dirent->d_off))
return -EFAULT;
dirent = buf->current_dir;
buf->previous = dirent;
if (put_user(d_ino, &dirent->d_ino)
|| put_user(reclen, &dirent->d_reclen)
|| copy_to_user(dirent->d_name, name, namlen)
|| put_user(0, dirent->d_name + namlen))
return -EFAULT;
dirent = (struct compat_dirent __user *) ((char __user *) dirent + reclen);
buf->current_dir = dirent;
buf->count -= reclen;
return 0;
}
asmlinkage long
sys32_getdents (unsigned int fd, struct compat_dirent __user *dirent, unsigned int count)
{
struct file * file;
struct compat_dirent __user * lastdirent;
struct getdents32_callback buf;
int error;
error = -EFAULT;
if (!access_ok(VERIFY_WRITE, dirent, count))
goto out;
error = -EBADF;
file = fget(fd);
if (!file)
goto out;
buf.current_dir = dirent;
buf.previous = NULL;
buf.count = count;
buf.error = 0;
error = vfs_readdir(file, filldir32, &buf);
if (error < 0)
goto out_putf;
error = buf.error;
lastdirent = buf.previous;
if (lastdirent) {
if (put_user(file->f_pos, &lastdirent->d_off))
error = -EFAULT;
else
error = count - buf.count;
}
out_putf:
fput(file);
out:
return error;
}
static int
fillonedir32 (void * __buf, const char * name, int namlen, loff_t offset, u64 ino,
unsigned int d_type)
{
struct readdir32_callback * buf = (struct readdir32_callback *) __buf;
struct old_linux32_dirent __user * dirent;
u32 d_ino;
if (buf->count)
return -EINVAL;
d_ino = ino;
if (sizeof(d_ino) < sizeof(ino) && d_ino != ino)
return -EOVERFLOW;
buf->count++;
dirent = buf->dirent;
if (put_user(d_ino, &dirent->d_ino)
|| put_user(offset, &dirent->d_offset)
|| put_user(namlen, &dirent->d_namlen)
|| copy_to_user(dirent->d_name, name, namlen)
|| put_user(0, dirent->d_name + namlen))
return -EFAULT;
return 0;
}
asmlinkage long
sys32_readdir (unsigned int fd, void __user *dirent, unsigned int count)
{
int error;
struct file * file;
struct readdir32_callback buf;
error = -EBADF;
file = fget(fd);
if (!file)
goto out;
buf.count = 0;
buf.dirent = dirent;
error = vfs_readdir(file, fillonedir32, &buf);
if (error >= 0)
error = buf.count;
fput(file);
out:
return error;
}
struct sel_arg_struct {
unsigned int n;
unsigned int inp;
unsigned int outp;
unsigned int exp;
unsigned int tvp;
};
asmlinkage long
sys32_old_select (struct sel_arg_struct __user *arg)
{
struct sel_arg_struct a;
if (copy_from_user(&a, arg, sizeof(a)))
return -EFAULT;
return compat_sys_select(a.n, compat_ptr(a.inp), compat_ptr(a.outp),
compat_ptr(a.exp), compat_ptr(a.tvp));
}
#define SEMOP 1
#define SEMGET 2
#define SEMCTL 3
#define SEMTIMEDOP 4
#define MSGSND 11
#define MSGRCV 12
#define MSGGET 13
#define MSGCTL 14
#define SHMAT 21
#define SHMDT 22
#define SHMGET 23
#define SHMCTL 24
asmlinkage long
sys32_ipc(u32 call, int first, int second, int third, u32 ptr, u32 fifth)
{
int version;
version = call >> 16; /* hack for backward compatibility */
call &= 0xffff;
switch (call) {
case SEMTIMEDOP:
if (fifth)
return <API key>(first, compat_ptr(ptr),
second, compat_ptr(fifth));
/* else fall through for normal semop() */
case SEMOP:
/* struct sembuf is the same on 32 and 64bit :)) */
return sys_semtimedop(first, compat_ptr(ptr), second,
NULL);
case SEMGET:
return sys_semget(first, second, third);
case SEMCTL:
return compat_sys_semctl(first, second, third, compat_ptr(ptr));
case MSGSND:
return compat_sys_msgsnd(first, second, third, compat_ptr(ptr));
case MSGRCV:
return compat_sys_msgrcv(first, second, fifth, third, version, compat_ptr(ptr));
case MSGGET:
return sys_msgget((key_t) first, second);
case MSGCTL:
return compat_sys_msgctl(first, second, compat_ptr(ptr));
case SHMAT:
return compat_sys_shmat(first, second, third, version, compat_ptr(ptr));
break;
case SHMDT:
return sys_shmdt(compat_ptr(ptr));
case SHMGET:
return sys_shmget(first, (unsigned)second, third);
case SHMCTL:
return compat_sys_shmctl(first, second, compat_ptr(ptr));
default:
return -ENOSYS;
}
return -EINVAL;
}
asmlinkage long
compat_sys_wait4 (compat_pid_t pid, compat_uint_t * stat_addr, int options,
struct compat_rusage *ru);
asmlinkage long
sys32_waitpid (int pid, unsigned int *stat_addr, int options)
{
return compat_sys_wait4(pid, stat_addr, options, NULL);
}
static unsigned int
ia32_peek (struct task_struct *child, unsigned long addr, unsigned int *val)
{
size_t copied;
unsigned int ret;
copied = access_process_vm(child, addr, val, sizeof(*val), 0);
return (copied != sizeof(ret)) ? -EIO : 0;
}
static unsigned int
ia32_poke (struct task_struct *child, unsigned long addr, unsigned int val)
{
if (access_process_vm(child, addr, &val, sizeof(val), 1) != sizeof(val))
return -EIO;
return 0;
}
/*
* The order in which registers are stored in the ptrace regs structure
*/
#define PT_EBX 0
#define PT_ECX 1
#define PT_EDX 2
#define PT_ESI 3
#define PT_EDI 4
#define PT_EBP 5
#define PT_EAX 6
#define PT_DS 7
#define PT_ES 8
#define PT_FS 9
#define PT_GS 10
#define PT_ORIG_EAX 11
#define PT_EIP 12
#define PT_CS 13
#define PT_EFL 14
#define PT_UESP 15
#define PT_SS 16
static unsigned int
getreg (struct task_struct *child, int regno)
{
struct pt_regs *child_regs;
child_regs = task_pt_regs(child);
switch (regno / sizeof(int)) {
case PT_EBX: return child_regs->r11;
case PT_ECX: return child_regs->r9;
case PT_EDX: return child_regs->r10;
case PT_ESI: return child_regs->r14;
case PT_EDI: return child_regs->r15;
case PT_EBP: return child_regs->r13;
case PT_EAX: return child_regs->r8;
case PT_ORIG_EAX: return child_regs->r1; /* see <API key>() */
case PT_EIP: return child_regs->cr_iip;
case PT_UESP: return child_regs->r12;
case PT_EFL: return child->thread.eflag;
case PT_DS: case PT_ES: case PT_FS: case PT_GS: case PT_SS:
return __USER_DS;
case PT_CS: return __USER_CS;
default:
printk(KERN_ERR "ia32.getreg(): unknown register %d\n", regno);
break;
}
return 0;
}
static void
putreg (struct task_struct *child, int regno, unsigned int value)
{
struct pt_regs *child_regs;
child_regs = task_pt_regs(child);
switch (regno / sizeof(int)) {
case PT_EBX: child_regs->r11 = value; break;
case PT_ECX: child_regs->r9 = value; break;
case PT_EDX: child_regs->r10 = value; break;
case PT_ESI: child_regs->r14 = value; break;
case PT_EDI: child_regs->r15 = value; break;
case PT_EBP: child_regs->r13 = value; break;
case PT_EAX: child_regs->r8 = value; break;
case PT_ORIG_EAX: child_regs->r1 = value; break;
case PT_EIP: child_regs->cr_iip = value; break;
case PT_UESP: child_regs->r12 = value; break;
case PT_EFL: child->thread.eflag = value; break;
case PT_DS: case PT_ES: case PT_FS: case PT_GS: case PT_SS:
if (value != __USER_DS)
printk(KERN_ERR
"ia32.putreg: attempt to set invalid segment register %d = %x\n",
regno, value);
break;
case PT_CS:
if (value != __USER_CS)
printk(KERN_ERR
"ia32.putreg: attempt to to set invalid segment register %d = %x\n",
regno, value);
break;
default:
printk(KERN_ERR "ia32.putreg: unknown register %d\n", regno);
break;
}
}
static void
put_fpreg (int regno, struct _fpreg_ia32 __user *reg, struct pt_regs *ptp,
struct switch_stack *swp, int tos)
{
struct _fpreg_ia32 *f;
char buf[32];
f = (struct _fpreg_ia32 *)(((unsigned long)buf + 15) & ~15);
if ((regno += tos) >= 8)
regno -= 8;
switch (regno) {
case 0:
ia64f2ia32f(f, &ptp->f8);
break;
case 1:
ia64f2ia32f(f, &ptp->f9);
break;
case 2:
ia64f2ia32f(f, &ptp->f10);
break;
case 3:
ia64f2ia32f(f, &ptp->f11);
break;
case 4:
case 5:
case 6:
case 7:
ia64f2ia32f(f, &swp->f12 + (regno - 4));
break;
}
copy_to_user(reg, f, sizeof(*reg));
}
static void
get_fpreg (int regno, struct _fpreg_ia32 __user *reg, struct pt_regs *ptp,
struct switch_stack *swp, int tos)
{
if ((regno += tos) >= 8)
regno -= 8;
switch (regno) {
case 0:
copy_from_user(&ptp->f8, reg, sizeof(*reg));
break;
case 1:
copy_from_user(&ptp->f9, reg, sizeof(*reg));
break;
case 2:
copy_from_user(&ptp->f10, reg, sizeof(*reg));
break;
case 3:
copy_from_user(&ptp->f11, reg, sizeof(*reg));
break;
case 4:
case 5:
case 6:
case 7:
copy_from_user(&swp->f12 + (regno - 4), reg, sizeof(*reg));
break;
}
return;
}
int
save_ia32_fpstate (struct task_struct *tsk, struct <API key> __user *save)
{
struct switch_stack *swp;
struct pt_regs *ptp;
int i, tos;
if (!access_ok(VERIFY_WRITE, save, sizeof(*save)))
return -EFAULT;
__put_user(tsk->thread.fcr & 0xffff, &save->cwd);
__put_user(tsk->thread.fsr & 0xffff, &save->swd);
__put_user((tsk->thread.fsr>>16) & 0xffff, &save->twd);
__put_user(tsk->thread.fir, &save->fip);
__put_user((tsk->thread.fir>>32) & 0xffff, &save->fcs);
__put_user(tsk->thread.fdr, &save->foo);
__put_user((tsk->thread.fdr>>32) & 0xffff, &save->fos);
/*
* Stack frames start with 16-bytes of temp space
*/
swp = (struct switch_stack *)(tsk->thread.ksp + 16);
ptp = task_pt_regs(tsk);
tos = (tsk->thread.fsr >> 11) & 7;
for (i = 0; i < 8; i++)
put_fpreg(i, &save->st_space[i], ptp, swp, tos);
return 0;
}
static int
<API key> (struct task_struct *tsk, struct <API key> __user *save)
{
struct switch_stack *swp;
struct pt_regs *ptp;
int i, tos;
unsigned int fsrlo, fsrhi, num32;
if (!access_ok(VERIFY_READ, save, sizeof(*save)))
return(-EFAULT);
__get_user(num32, (unsigned int __user *)&save->cwd);
tsk->thread.fcr = (tsk->thread.fcr & (~0x1f3f)) | (num32 & 0x1f3f);
__get_user(fsrlo, (unsigned int __user *)&save->swd);
__get_user(fsrhi, (unsigned int __user *)&save->twd);
num32 = (fsrhi << 16) | fsrlo;
tsk->thread.fsr = (tsk->thread.fsr & (~0xffffffff)) | num32;
__get_user(num32, (unsigned int __user *)&save->fip);
tsk->thread.fir = (tsk->thread.fir & (~0xffffffff)) | num32;
__get_user(num32, (unsigned int __user *)&save->foo);
tsk->thread.fdr = (tsk->thread.fdr & (~0xffffffff)) | num32;
/*
* Stack frames start with 16-bytes of temp space
*/
swp = (struct switch_stack *)(tsk->thread.ksp + 16);
ptp = task_pt_regs(tsk);
tos = (tsk->thread.fsr >> 11) & 7;
for (i = 0; i < 8; i++)
get_fpreg(i, &save->st_space[i], ptp, swp, tos);
return 0;
}
int
save_ia32_fpxstate (struct task_struct *tsk, struct <API key> __user *save)
{
struct switch_stack *swp;
struct pt_regs *ptp;
int i, tos;
unsigned long mxcsr=0;
unsigned long num128[2];
if (!access_ok(VERIFY_WRITE, save, sizeof(*save)))
return -EFAULT;
__put_user(tsk->thread.fcr & 0xffff, &save->cwd);
__put_user(tsk->thread.fsr & 0xffff, &save->swd);
__put_user((tsk->thread.fsr>>16) & 0xffff, &save->twd);
__put_user(tsk->thread.fir, &save->fip);
__put_user((tsk->thread.fir>>32) & 0xffff, &save->fcs);
__put_user(tsk->thread.fdr, &save->foo);
__put_user((tsk->thread.fdr>>32) & 0xffff, &save->fos);
/*
* Stack frames start with 16-bytes of temp space
*/
swp = (struct switch_stack *)(tsk->thread.ksp + 16);
ptp = task_pt_regs(tsk);
tos = (tsk->thread.fsr >> 11) & 7;
for (i = 0; i < 8; i++)
put_fpreg(i, (struct _fpreg_ia32 __user *)&save->st_space[4*i], ptp, swp, tos);
mxcsr = ((tsk->thread.fcr>>32) & 0xff80) | ((tsk->thread.fsr>>32) & 0x3f);
__put_user(mxcsr & 0xffff, &save->mxcsr);
for (i = 0; i < 8; i++) {
memcpy(&(num128[0]), &(swp->f16) + i*2, sizeof(unsigned long));
memcpy(&(num128[1]), &(swp->f17) + i*2, sizeof(unsigned long));
copy_to_user(&save->xmm_space[0] + 4*i, num128, sizeof(struct _xmmreg_ia32));
}
return 0;
}
static int
<API key> (struct task_struct *tsk, struct <API key> __user *save)
{
struct switch_stack *swp;
struct pt_regs *ptp;
int i, tos;
unsigned int fsrlo, fsrhi, num32;
int mxcsr;
unsigned long num64;
unsigned long num128[2];
if (!access_ok(VERIFY_READ, save, sizeof(*save)))
return(-EFAULT);
__get_user(num32, (unsigned int __user *)&save->cwd);
tsk->thread.fcr = (tsk->thread.fcr & (~0x1f3f)) | (num32 & 0x1f3f);
__get_user(fsrlo, (unsigned int __user *)&save->swd);
__get_user(fsrhi, (unsigned int __user *)&save->twd);
num32 = (fsrhi << 16) | fsrlo;
tsk->thread.fsr = (tsk->thread.fsr & (~0xffffffff)) | num32;
__get_user(num32, (unsigned int __user *)&save->fip);
tsk->thread.fir = (tsk->thread.fir & (~0xffffffff)) | num32;
__get_user(num32, (unsigned int __user *)&save->foo);
tsk->thread.fdr = (tsk->thread.fdr & (~0xffffffff)) | num32;
/*
* Stack frames start with 16-bytes of temp space
*/
swp = (struct switch_stack *)(tsk->thread.ksp + 16);
ptp = task_pt_regs(tsk);
tos = (tsk->thread.fsr >> 11) & 7;
for (i = 0; i < 8; i++)
get_fpreg(i, (struct _fpreg_ia32 __user *)&save->st_space[4*i], ptp, swp, tos);
__get_user(mxcsr, (unsigned int __user *)&save->mxcsr);
num64 = mxcsr & 0xff10;
tsk->thread.fcr = (tsk->thread.fcr & (~0xff1000000000UL)) | (num64<<32);
num64 = mxcsr & 0x3f;
tsk->thread.fsr = (tsk->thread.fsr & (~0x3f00000000UL)) | (num64<<32);
for (i = 0; i < 8; i++) {
copy_from_user(num128, &save->xmm_space[0] + 4*i, sizeof(struct _xmmreg_ia32));
memcpy(&(swp->f16) + i*2, &(num128[0]), sizeof(unsigned long));
memcpy(&(swp->f17) + i*2, &(num128[1]), sizeof(unsigned long));
}
return 0;
}
asmlinkage long
sys32_ptrace (int request, pid_t pid, unsigned int addr, unsigned int data)
{
struct task_struct *child;
unsigned int value, tmp;
long i, ret;
lock_kernel();
if (request == PTRACE_TRACEME) {
ret = ptrace_traceme();
goto out;
}
child = <API key>(pid);
if (IS_ERR(child)) {
ret = PTR_ERR(child);
goto out;
}
if (request == PTRACE_ATTACH) {
ret = sys_ptrace(request, pid, addr, data);
goto out_tsk;
}
ret = ptrace_check_attach(child, request == PTRACE_KILL);
if (ret < 0)
goto out_tsk;
switch (request) {
case PTRACE_PEEKTEXT:
case PTRACE_PEEKDATA: /* read word at location addr */
ret = ia32_peek(child, addr, &value);
if (ret == 0)
ret = put_user(value, (unsigned int __user *) compat_ptr(data));
else
ret = -EIO;
goto out_tsk;
case PTRACE_POKETEXT:
case PTRACE_POKEDATA: /* write the word at location addr */
ret = ia32_poke(child, addr, data);
goto out_tsk;
case PTRACE_PEEKUSR: /* read word at addr in USER area */
ret = -EIO;
if ((addr & 3) || addr > 17*sizeof(int))
break;
tmp = getreg(child, addr);
if (!put_user(tmp, (unsigned int __user *) compat_ptr(data)))
ret = 0;
break;
case PTRACE_POKEUSR: /* write word at addr in USER area */
ret = -EIO;
if ((addr & 3) || addr > 17*sizeof(int))
break;
putreg(child, addr, data);
ret = 0;
break;
case IA32_PTRACE_GETREGS:
if (!access_ok(VERIFY_WRITE, compat_ptr(data), 17*sizeof(int))) {
ret = -EIO;
break;
}
for (i = 0; i < (int) (17*sizeof(int)); i += sizeof(int) ) {
put_user(getreg(child, i), (unsigned int __user *) compat_ptr(data));
data += sizeof(int);
}
ret = 0;
break;
case IA32_PTRACE_SETREGS:
if (!access_ok(VERIFY_READ, compat_ptr(data), 17*sizeof(int))) {
ret = -EIO;
break;
}
for (i = 0; i < (int) (17*sizeof(int)); i += sizeof(int) ) {
get_user(tmp, (unsigned int __user *) compat_ptr(data));
putreg(child, i, tmp);
data += sizeof(int);
}
ret = 0;
break;
case <API key>:
ret = save_ia32_fpstate(child, (struct <API key> __user *)
compat_ptr(data));
break;
case <API key>:
ret = save_ia32_fpxstate(child, (struct <API key> __user *)
compat_ptr(data));
break;
case <API key>:
ret = <API key>(child, (struct <API key> __user *)
compat_ptr(data));
break;
case <API key>:
ret = <API key>(child, (struct <API key> __user *)
compat_ptr(data));
break;
case PTRACE_GETEVENTMSG:
ret = put_user(child->ptrace_message, (unsigned int __user *) compat_ptr(data));
break;
case PTRACE_SYSCALL: /* continue, stop after next syscall */
case PTRACE_CONT: /* restart after signal. */
case PTRACE_KILL:
case PTRACE_SINGLESTEP: /* execute chile for one instruction */
case PTRACE_DETACH: /* detach a process */
ret = sys_ptrace(request, pid, addr, data);
break;
default:
ret = ptrace_request(child, request, addr, data);
break;
}
out_tsk:
put_task_struct(child);
out:
unlock_kernel();
return ret;
}
typedef struct {
unsigned int ss_sp;
unsigned int ss_flags;
unsigned int ss_size;
} ia32_stack_t;
asmlinkage long
sys32_sigaltstack (ia32_stack_t __user *uss32, ia32_stack_t __user *uoss32,
long arg2, long arg3, long arg4, long arg5, long arg6,
long arg7, struct pt_regs pt)
{
stack_t uss, uoss;
ia32_stack_t buf32;
int ret;
mm_segment_t old_fs = get_fs();
if (uss32) {
if (copy_from_user(&buf32, uss32, sizeof(ia32_stack_t)))
return -EFAULT;
uss.ss_sp = (void __user *) (long) buf32.ss_sp;
uss.ss_flags = buf32.ss_flags;
/* MINSIGSTKSZ is different for ia32 vs ia64. We lie here to pass the
check and set it to the user requested value later */
if ((buf32.ss_flags != SS_DISABLE) && (buf32.ss_size < MINSIGSTKSZ_IA32)) {
ret = -ENOMEM;
goto out;
}
uss.ss_size = MINSIGSTKSZ;
}
set_fs(KERNEL_DS);
ret = do_sigaltstack(uss32 ? (stack_t __user *) &uss : NULL,
(stack_t __user *) &uoss, pt.r12);
current->sas_ss_size = buf32.ss_size;
set_fs(old_fs);
out:
if (ret < 0)
return(ret);
if (uoss32) {
buf32.ss_sp = (long __user) uoss.ss_sp;
buf32.ss_flags = uoss.ss_flags;
buf32.ss_size = uoss.ss_size;
if (copy_to_user(uoss32, &buf32, sizeof(ia32_stack_t)))
return -EFAULT;
}
return ret;
}
asmlinkage int
sys32_pause (void)
{
current->state = TASK_INTERRUPTIBLE;
schedule();
return -ERESTARTNOHAND;
}
asmlinkage int
sys32_msync (unsigned int start, unsigned int len, int flags)
{
unsigned int addr;
if (OFFSET4K(start))
return -EINVAL;
addr = PAGE_START(start);
return sys_msync(addr, len + (start - addr), flags);
}
struct sysctl32 {
unsigned int name;
int nlen;
unsigned int oldval;
unsigned int oldlenp;
unsigned int newval;
unsigned int newlen;
unsigned int __unused[4];
};
#ifdef <API key>
asmlinkage long
sys32_sysctl (struct sysctl32 __user *args)
{
struct sysctl32 a32;
mm_segment_t old_fs = get_fs ();
void __user *oldvalp, *newvalp;
size_t oldlen;
int __user *namep;
long ret;
if (copy_from_user(&a32, args, sizeof(a32)))
return -EFAULT;
/*
* We need to pre-validate these because we have to disable address checking
* before calling do_sysctl() because of OLDLEN but we can't run the risk of the
* user specifying bad addresses here. Well, since we're dealing with 32 bit
* addresses, we KNOW that access_ok() will always succeed, so this is an
* expensive NOP, but so what...
*/
namep = (int __user *) compat_ptr(a32.name);
oldvalp = compat_ptr(a32.oldval);
newvalp = compat_ptr(a32.newval);
if ((oldvalp && get_user(oldlen, (int __user *) compat_ptr(a32.oldlenp)))
|| !access_ok(VERIFY_WRITE, namep, 0)
|| !access_ok(VERIFY_WRITE, oldvalp, 0)
|| !access_ok(VERIFY_WRITE, newvalp, 0))
return -EFAULT;
set_fs(KERNEL_DS);
lock_kernel();
ret = do_sysctl(namep, a32.nlen, oldvalp, (size_t __user *) &oldlen,
newvalp, (size_t) a32.newlen);
unlock_kernel();
set_fs(old_fs);
if (oldvalp && put_user (oldlen, (int __user *) compat_ptr(a32.oldlenp)))
return -EFAULT;
return ret;
}
#endif
asmlinkage long
sys32_newuname (struct new_utsname __user *name)
{
int ret = sys_newuname(name);
if (!ret)
if (copy_to_user(name->machine, "i686\0\0\0", 8))
ret = -EFAULT;
return ret;
}
asmlinkage long
sys32_getresuid16 (u16 __user *ruid, u16 __user *euid, u16 __user *suid)
{
uid_t a, b, c;
int ret;
mm_segment_t old_fs = get_fs();
set_fs(KERNEL_DS);
ret = sys_getresuid((uid_t __user *) &a, (uid_t __user *) &b, (uid_t __user *) &c);
set_fs(old_fs);
if (put_user(a, ruid) || put_user(b, euid) || put_user(c, suid))
return -EFAULT;
return ret;
}
asmlinkage long
sys32_getresgid16 (u16 __user *rgid, u16 __user *egid, u16 __user *sgid)
{
gid_t a, b, c;
int ret;
mm_segment_t old_fs = get_fs();
set_fs(KERNEL_DS);
ret = sys_getresgid((gid_t __user *) &a, (gid_t __user *) &b, (gid_t __user *) &c);
set_fs(old_fs);
if (ret)
return ret;
return put_user(a, rgid) | put_user(b, egid) | put_user(c, sgid);
}
asmlinkage long
sys32_lseek (unsigned int fd, int offset, unsigned int whence)
{
/* Sign-extension of "offset" is important here... */
return sys_lseek(fd, offset, whence);
}
static int
groups16_to_user(short __user *grouplist, struct group_info *group_info)
{
int i;
short group;
for (i = 0; i < group_info->ngroups; i++) {
group = (short)GROUP_AT(group_info, i);
if (put_user(group, grouplist+i))
return -EFAULT;
}
return 0;
}
static int
groups16_from_user(struct group_info *group_info, short __user *grouplist)
{
int i;
short group;
for (i = 0; i < group_info->ngroups; i++) {
if (get_user(group, grouplist+i))
return -EFAULT;
GROUP_AT(group_info, i) = (gid_t)group;
}
return 0;
}
asmlinkage long
sys32_getgroups16 (int gidsetsize, short __user *grouplist)
{
int i;
if (gidsetsize < 0)
return -EINVAL;
get_group_info(current->group_info);
i = current->group_info->ngroups;
if (gidsetsize) {
if (i > gidsetsize) {
i = -EINVAL;
goto out;
}
if (groups16_to_user(grouplist, current->group_info)) {
i = -EFAULT;
goto out;
}
}
out:
put_group_info(current->group_info);
return i;
}
asmlinkage long
sys32_setgroups16 (int gidsetsize, short __user *grouplist)
{
struct group_info *group_info;
int retval;
if (!capable(CAP_SETGID))
return -EPERM;
if ((unsigned)gidsetsize > NGROUPS_MAX)
return -EINVAL;
group_info = groups_alloc(gidsetsize);
if (!group_info)
return -ENOMEM;
retval = groups16_from_user(group_info, grouplist);
if (retval) {
put_group_info(group_info);
return retval;
}
retval = set_current_groups(group_info);
put_group_info(group_info);
return retval;
}
asmlinkage long
sys32_truncate64 (unsigned int path, unsigned int len_lo, unsigned int len_hi)
{
return sys_truncate(compat_ptr(path), ((unsigned long) len_hi << 32) | len_lo);
}
asmlinkage long
sys32_ftruncate64 (int fd, unsigned int len_lo, unsigned int len_hi)
{
return sys_ftruncate(fd, ((unsigned long) len_hi << 32) | len_lo);
}
static int
putstat64 (struct stat64 __user *ubuf, struct kstat *kbuf)
{
int err;
u64 hdev;
if (clear_user(ubuf, sizeof(*ubuf)))
return -EFAULT;
hdev = huge_encode_dev(kbuf->dev);
err = __put_user(hdev, (u32 __user*)&ubuf->st_dev);
err |= __put_user(hdev >> 32, ((u32 __user*)&ubuf->st_dev) + 1);
err |= __put_user(kbuf->ino, &ubuf->__st_ino);
err |= __put_user(kbuf->ino, &ubuf->st_ino_lo);
err |= __put_user(kbuf->ino >> 32, &ubuf->st_ino_hi);
err |= __put_user(kbuf->mode, &ubuf->st_mode);
err |= __put_user(kbuf->nlink, &ubuf->st_nlink);
err |= __put_user(kbuf->uid, &ubuf->st_uid);
err |= __put_user(kbuf->gid, &ubuf->st_gid);
hdev = huge_encode_dev(kbuf->rdev);
err = __put_user(hdev, (u32 __user*)&ubuf->st_rdev);
err |= __put_user(hdev >> 32, ((u32 __user*)&ubuf->st_rdev) + 1);
err |= __put_user(kbuf->size, &ubuf->st_size_lo);
err |= __put_user((kbuf->size >> 32), &ubuf->st_size_hi);
err |= __put_user(kbuf->atime.tv_sec, &ubuf->st_atime);
err |= __put_user(kbuf->atime.tv_nsec, &ubuf->st_atime_nsec);
err |= __put_user(kbuf->mtime.tv_sec, &ubuf->st_mtime);
err |= __put_user(kbuf->mtime.tv_nsec, &ubuf->st_mtime_nsec);
err |= __put_user(kbuf->ctime.tv_sec, &ubuf->st_ctime);
err |= __put_user(kbuf->ctime.tv_nsec, &ubuf->st_ctime_nsec);
err |= __put_user(kbuf->blksize, &ubuf->st_blksize);
err |= __put_user(kbuf->blocks, &ubuf->st_blocks);
return err;
}
asmlinkage long
sys32_stat64 (char __user *filename, struct stat64 __user *statbuf)
{
struct kstat s;
long ret = vfs_stat(filename, &s);
if (!ret)
ret = putstat64(statbuf, &s);
return ret;
}
asmlinkage long
sys32_lstat64 (char __user *filename, struct stat64 __user *statbuf)
{
struct kstat s;
long ret = vfs_lstat(filename, &s);
if (!ret)
ret = putstat64(statbuf, &s);
return ret;
}
asmlinkage long
sys32_fstat64 (unsigned int fd, struct stat64 __user *statbuf)
{
struct kstat s;
long ret = vfs_fstat(fd, &s);
if (!ret)
ret = putstat64(statbuf, &s);
return ret;
}
asmlinkage long
<API key> (pid_t pid, struct compat_timespec __user *interval)
{
mm_segment_t old_fs = get_fs();
struct timespec t;
long ret;
set_fs(KERNEL_DS);
ret = <API key>(pid, (struct timespec __user *) &t);
set_fs(old_fs);
if (put_compat_timespec(&t, interval))
return -EFAULT;
return ret;
}
asmlinkage long
sys32_pread (unsigned int fd, void __user *buf, unsigned int count, u32 pos_lo, u32 pos_hi)
{
return sys_pread64(fd, buf, count, ((unsigned long) pos_hi << 32) | pos_lo);
}
asmlinkage long
sys32_pwrite (unsigned int fd, void __user *buf, unsigned int count, u32 pos_lo, u32 pos_hi)
{
return sys_pwrite64(fd, buf, count, ((unsigned long) pos_hi << 32) | pos_lo);
}
asmlinkage long
sys32_sendfile (int out_fd, int in_fd, int __user *offset, unsigned int count)
{
mm_segment_t old_fs = get_fs();
long ret;
off_t of;
if (offset && get_user(of, offset))
return -EFAULT;
set_fs(KERNEL_DS);
ret = sys_sendfile(out_fd, in_fd, offset ? (off_t __user *) &of : NULL, count);
set_fs(old_fs);
if (offset && put_user(of, offset))
return -EFAULT;
return ret;
}
asmlinkage long
sys32_personality (unsigned int personality)
{
long ret;
if (current->personality == PER_LINUX32 && personality == PER_LINUX)
personality = PER_LINUX32;
ret = sys_personality(personality);
if (ret == PER_LINUX32)
ret = PER_LINUX;
return ret;
}
asmlinkage unsigned long
sys32_brk (unsigned int brk)
{
unsigned long ret, obrk;
struct mm_struct *mm = current->mm;
obrk = mm->brk;
ret = sys_brk(brk);
if (ret < obrk)
clear_user(compat_ptr(ret), PAGE_ALIGN(ret) - ret);
return ret;
}
/* Structure for ia32 emulation on ia64 */
struct epoll_event32
{
u32 events;
u32 data[2];
};
asmlinkage long
sys32_epoll_ctl(int epfd, int op, int fd, struct epoll_event32 __user *event)
{
mm_segment_t old_fs = get_fs();
struct epoll_event event64;
int error;
u32 data_halfword;
if (!access_ok(VERIFY_READ, event, sizeof(struct epoll_event32)))
return -EFAULT;
__get_user(event64.events, &event->events);
__get_user(data_halfword, &event->data[0]);
event64.data = data_halfword;
__get_user(data_halfword, &event->data[1]);
event64.data |= (u64)data_halfword << 32;
set_fs(KERNEL_DS);
error = sys_epoll_ctl(epfd, op, fd, (struct epoll_event __user *) &event64);
set_fs(old_fs);
return error;
}
asmlinkage long
sys32_epoll_wait(int epfd, struct epoll_event32 __user * events, int maxevents,
int timeout)
{
struct epoll_event *events64 = NULL;
mm_segment_t old_fs = get_fs();
int numevents, size;
int evt_idx;
int do_free_pages = 0;
if (maxevents <= 0) {
return -EINVAL;
}
/* Verify that the area passed by the user is writeable */
if (!access_ok(VERIFY_WRITE, events, maxevents * sizeof(struct epoll_event32)))
return -EFAULT;
/*
* Allocate space for the intermediate copy. If the space needed
* is large enough to cause kmalloc to fail, then try again with
* __get_free_pages.
*/
size = maxevents * sizeof(struct epoll_event);
events64 = kmalloc(size, GFP_KERNEL);
if (events64 == NULL) {
events64 = (struct epoll_event *)
__get_free_pages(GFP_KERNEL, get_order(size));
if (events64 == NULL)
return -ENOMEM;
do_free_pages = 1;
}
/* Do the system call */
set_fs(KERNEL_DS); /* copy_to/from_user should work on kernel mem*/
numevents = sys_epoll_wait(epfd, (struct epoll_event __user *) events64,
maxevents, timeout);
set_fs(old_fs);
/* Don't modify userspace memory if we're returning an error */
if (numevents > 0) {
/* Translate the 64-bit structures back into the 32-bit
structures */
for (evt_idx = 0; evt_idx < numevents; evt_idx++) {
__put_user(events64[evt_idx].events,
&events[evt_idx].events);
__put_user((u32)events64[evt_idx].data,
&events[evt_idx].data[0]);
__put_user((u32)(events64[evt_idx].data >> 32),
&events[evt_idx].data[1]);
}
}
if (do_free_pages)
free_pages((unsigned long) events64, get_order(size));
else
kfree(events64);
return numevents;
}
/*
* Get a yet unused TLS descriptor index.
*/
static int
get_free_idx (void)
{
struct thread_struct *t = ¤t->thread;
int idx;
for (idx = 0; idx < <API key>; idx++)
if (desc_empty(t->tls_array + idx))
return idx + GDT_ENTRY_TLS_MIN;
return -ESRCH;
}
/*
* Set a given TLS descriptor:
*/
asmlinkage int
<API key> (struct ia32_user_desc __user *u_info)
{
struct thread_struct *t = ¤t->thread;
struct ia32_user_desc info;
struct desc_struct *desc;
int cpu, idx;
if (copy_from_user(&info, u_info, sizeof(info)))
return -EFAULT;
idx = info.entry_number;
/*
* index -1 means the kernel should try to find and allocate an empty descriptor:
*/
if (idx == -1) {
idx = get_free_idx();
if (idx < 0)
return idx;
if (put_user(idx, &u_info->entry_number))
return -EFAULT;
}
if (idx < GDT_ENTRY_TLS_MIN || idx > GDT_ENTRY_TLS_MAX)
return -EINVAL;
desc = t->tls_array + idx - GDT_ENTRY_TLS_MIN;
cpu = smp_processor_id();
if (LDT_empty(&info)) {
desc->a = 0;
desc->b = 0;
} else {
desc->a = LDT_entry_a(&info);
desc->b = LDT_entry_b(&info);
}
load_TLS(t, cpu);
return 0;
}
/*
* Get the current Thread-Local Storage area:
*/
#define GET_BASE(desc) ( \
(((desc)->a >> 16) & 0x0000ffff) | \
(((desc)->b << 16) & 0x00ff0000) | \
( (desc)->b & 0xff000000) )
#define GET_LIMIT(desc) ( \
((desc)->a & 0x0ffff) | \
((desc)->b & 0xf0000) )
#define GET_32BIT(desc) (((desc)->b >> 22) & 1)
#define GET_CONTENTS(desc) (((desc)->b >> 10) & 3)
#define GET_WRITABLE(desc) (((desc)->b >> 9) & 1)
#define GET_LIMIT_PAGES(desc) (((desc)->b >> 23) & 1)
#define GET_PRESENT(desc) (((desc)->b >> 15) & 1)
#define GET_USEABLE(desc) (((desc)->b >> 20) & 1)
asmlinkage int
<API key> (struct ia32_user_desc __user *u_info)
{
struct ia32_user_desc info;
struct desc_struct *desc;
int idx;
if (get_user(idx, &u_info->entry_number))
return -EFAULT;
if (idx < GDT_ENTRY_TLS_MIN || idx > GDT_ENTRY_TLS_MAX)
return -EINVAL;
desc = current->thread.tls_array + idx - GDT_ENTRY_TLS_MIN;
info.entry_number = idx;
info.base_addr = GET_BASE(desc);
info.limit = GET_LIMIT(desc);
info.seg_32bit = GET_32BIT(desc);
info.contents = GET_CONTENTS(desc);
info.read_exec_only = !GET_WRITABLE(desc);
info.limit_in_pages = GET_LIMIT_PAGES(desc);
info.seg_not_present = !GET_PRESENT(desc);
info.useable = GET_USEABLE(desc);
if (copy_to_user(u_info, &info, sizeof(info)))
return -EFAULT;
return 0;
}
long sys32_fadvise64_64(int fd, __u32 offset_low, __u32 offset_high,
__u32 len_low, __u32 len_high, int advice)
{
return sys_fadvise64_64(fd,
(((u64)offset_high)<<32) | offset_low,
(((u64)len_high)<<32) | len_low,
advice);
}
#ifdef NOTYET /* UNTESTED FOR IA64 FROM HERE DOWN */
asmlinkage long sys32_setreuid(compat_uid_t ruid, compat_uid_t euid)
{
uid_t sruid, seuid;
sruid = (ruid == (compat_uid_t)-1) ? ((uid_t)-1) : ((uid_t)ruid);
seuid = (euid == (compat_uid_t)-1) ? ((uid_t)-1) : ((uid_t)euid);
return sys_setreuid(sruid, seuid);
}
asmlinkage long
sys32_setresuid(compat_uid_t ruid, compat_uid_t euid,
compat_uid_t suid)
{
uid_t sruid, seuid, ssuid;
sruid = (ruid == (compat_uid_t)-1) ? ((uid_t)-1) : ((uid_t)ruid);
seuid = (euid == (compat_uid_t)-1) ? ((uid_t)-1) : ((uid_t)euid);
ssuid = (suid == (compat_uid_t)-1) ? ((uid_t)-1) : ((uid_t)suid);
return sys_setresuid(sruid, seuid, ssuid);
}
asmlinkage long
sys32_setregid(compat_gid_t rgid, compat_gid_t egid)
{
gid_t srgid, segid;
srgid = (rgid == (compat_gid_t)-1) ? ((gid_t)-1) : ((gid_t)rgid);
segid = (egid == (compat_gid_t)-1) ? ((gid_t)-1) : ((gid_t)egid);
return sys_setregid(srgid, segid);
}
asmlinkage long
sys32_setresgid(compat_gid_t rgid, compat_gid_t egid,
compat_gid_t sgid)
{
gid_t srgid, segid, ssgid;
srgid = (rgid == (compat_gid_t)-1) ? ((gid_t)-1) : ((gid_t)rgid);
segid = (egid == (compat_gid_t)-1) ? ((gid_t)-1) : ((gid_t)egid);
ssgid = (sgid == (compat_gid_t)-1) ? ((gid_t)-1) : ((gid_t)sgid);
return sys_setresgid(srgid, segid, ssgid);
}
#endif /* NOTYET */ |
# This file is part of Sick Beard.
# Sick Beard is free software: you can redistribute it and/or modify
# (at your option) any later version.
# Sick Beard is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import os
import cgi
import sickbeard
from sickbeard import logger, common
def diagnose():
'''
Check the environment for reasons libnotify isn't working. Return a
user-readable message indicating possible issues.
'''
try:
import pynotify #@UnusedImport
except ImportError:
return (u"<p>Error: pynotify isn't installed. On Ubuntu/Debian, install the "
u"<a href=\"apt:python-notify\">python-notify</a> package.")
if 'DISPLAY' not in os.environ and '<API key>' not in os.environ:
return (u"<p>Error: Environment variables DISPLAY and <API key> "
u"aren't set. libnotify will only work when you run Sick Beard "
u"from a desktop login.")
try:
import dbus
except ImportError:
pass
else:
try:
bus = dbus.SessionBus()
except dbus.DBusException, e:
return (u"<p>Error: unable to connect to D-Bus session bus: <code>%s</code>."
u"<p>Are you running Sick Beard in a desktop session?") % (cgi.escape(e),)
try:
bus.get_object('org.freedesktop.Notifications',
'/org/freedesktop/Notifications')
except dbus.DBusException, e:
return (u"<p>Error: there doesn't seem to be a notification daemon available: <code>%s</code> "
u"<p>Try installing notification-daemon or notify-osd.") % (cgi.escape(e),)
return u"<p>Error: Unable to send notification."
class LibnotifyNotifier:
def __init__(self):
self.pynotify = None
self.gobject = None
def init_pynotify(self):
if self.pynotify is not None:
return True
try:
import pynotify
except ImportError:
logger.log(u"Unable to import pynotify. libnotify notifications won't work.")
return False
try:
import gobject
except ImportError:
logger.log(u"Unable to import gobject. We can't catch a GError in display.")
return False
if not pynotify.init('Sick Beard'):
logger.log(u"Initialization of pynotify failed. libnotify notifications won't work.")
return False
self.pynotify = pynotify
self.gobject = gobject
return True
def notify_snatch(self, ep_name):
if sickbeard.<API key>:
self._notify(common.notifyStrings[common.NOTIFY_SNATCH], ep_name)
def notify_download(self, ep_name):
if sickbeard.<API key>:
self._notify(common.notifyStrings[common.NOTIFY_DOWNLOAD], ep_name)
def <API key>(self, ep_name, lang):
if sickbeard.<API key>:
self._notify(common.notifyStrings[common.<API key>], ep_name + ": " + lang)
def test_notify(self):
return self._notify('Test notification', "This is a test notification from Sick Beard", force=True)
def _notify(self, title, message, force=False):
if not sickbeard.USE_LIBNOTIFY and not force:
return False
if not self.init_pynotify():
return False
# Can't make this a global constant because PROG_DIR isn't available
# when the module is imported.
icon_path = os.path.join(sickbeard.PROG_DIR, "data/images/<API key>.png")
icon_uri = 'file://' + os.path.abspath(icon_path)
# If the session bus can't be acquired here a bunch of warning messages
# will be printed but the call to show() will still return True.
# pynotify doesn't seem too keen on error handling.
n = self.pynotify.Notification(title, message, icon_uri)
try:
return n.show()
except self.gobject.GError:
return False
notifier = LibnotifyNotifier |
# E-mail: fuzzyman AT voidspace DOT org DOT uk
import unittest2 as unittest
from mock.tests.support import is_instance, X, SomeClass
from mock import (
Mock, MagicMock, <API key>,
NonCallableMock, patch, create_autospec,
CallableMixin
)
class TestCallable(unittest.TestCase):
def assertNotCallable(self, mock):
self.assertTrue(is_instance(mock, <API key>))
self.assertFalse(is_instance(mock, CallableMixin))
def test_non_callable(self):
for mock in <API key>(), NonCallableMock():
self.assertRaises(TypeError, mock)
self.assertFalse(hasattr(mock, '__call__'))
self.assertIn(mock.__class__.__name__, repr(mock))
def test_heirarchy(self):
self.assertTrue(issubclass(MagicMock, Mock))
self.assertTrue(issubclass(<API key>, NonCallableMock))
def test_attributes(self):
one = NonCallableMock()
self.assertTrue(issubclass(type(one.one), Mock))
two = <API key>()
self.assertTrue(issubclass(type(two.two), MagicMock))
def test_subclasses(self):
class MockSub(Mock):
pass
one = MockSub()
self.assertTrue(issubclass(type(one.one), MockSub))
class MagicSub(MagicMock):
pass
two = MagicSub()
self.assertTrue(issubclass(type(two.two), MagicSub))
def test_patch_spec(self):
patcher = patch('%s.X' % __name__, spec=True)
mock = patcher.start()
self.addCleanup(patcher.stop)
instance = mock()
mock.<API key>()
self.assertNotCallable(instance)
self.assertRaises(TypeError, instance)
def test_patch_spec_set(self):
patcher = patch('%s.X' % __name__, spec_set=True)
mock = patcher.start()
self.addCleanup(patcher.stop)
instance = mock()
mock.<API key>()
self.assertNotCallable(instance)
self.assertRaises(TypeError, instance)
def <API key>(self):
patcher = patch('%s.X' % __name__, spec=X())
mock = patcher.start()
self.addCleanup(patcher.stop)
self.assertNotCallable(mock)
self.assertRaises(TypeError, mock)
def <API key>(self):
patcher = patch('%s.X' % __name__, spec_set=X())
mock = patcher.start()
self.addCleanup(patcher.stop)
self.assertNotCallable(mock)
self.assertRaises(TypeError, mock)
def <API key>(self):
class CallableX(X):
def __call__(self):
pass
class Sub(CallableX):
pass
class Multi(SomeClass, Sub):
pass
class OldStyle:
def __call__(self):
pass
class OldStyleSub(OldStyle):
pass
for arg in 'spec', 'spec_set':
for Klass in CallableX, Sub, Multi, OldStyle, OldStyleSub:
with patch('%s.X' % __name__, **{arg: Klass}) as mock:
instance = mock()
mock.<API key>()
self.assertTrue(is_instance(instance, MagicMock))
# inherited spec
self.assertRaises(AttributeError, getattr, instance,
'foobarbaz')
result = instance()
# instance is callable, result has no spec
instance.<API key>()
result(3, 2, 1)
result.<API key>(3, 2, 1)
result.foo(3, 2, 1)
result.foo.<API key>(3, 2, 1)
def <API key>(self):
mock = create_autospec(X)
instance = mock()
self.assertRaises(TypeError, instance)
mock = create_autospec(X())
self.assertRaises(TypeError, mock)
def <API key>(self):
mock = create_autospec(SomeClass, instance=True)
self.assertRaises(TypeError, mock)
mock.wibble()
mock.wibble.<API key>()
self.assertRaises(TypeError, mock.wibble, 'some', 'args')
if __name__ == "__main__":
unittest.main() |
# -*- coding: utf-8 -*-
from odoo import api, _
from odoo.exceptions import UserError
from odoo.addons.account.wizard.pos_box import CashBox
class PosBox(CashBox):
_register = False
@api.multi
def run(self):
active_model = self.env.context.get('active_model', False)
active_ids = self.env.context.get('active_ids', [])
if active_model == 'pos.session':
bank_statements = [session.cash_register_id for session in self.env[active_model].browse(active_ids) if session.cash_register_id]
if not bank_statements:
raise UserError(_("There is no cash register for this PoS Session"))
return self._run(bank_statements)
else:
return super(PosBox, self).run()
class PosBoxIn(PosBox):
_inherit = 'cash.box.in'
def <API key>(self, record):
values = super(PosBoxIn, self).<API key>(record=record)
active_model = self.env.context.get('active_model', False)
active_ids = self.env.context.get('active_ids', [])
if active_model == 'pos.session' and active_ids:
values['ref'] = self.env[active_model].browse(active_ids)[0].name
return values
class PosBoxOut(PosBox):
_inherit = 'cash.box.out'
def <API key>(self, record):
values = super(PosBoxOut, self).<API key>(record)
active_model = self.env.context.get('active_model', False)
active_ids = self.env.context.get('active_ids', [])
if active_model == 'pos.session' and active_ids:
values['ref'] = self.env[active_model].browse(active_ids)[0].name
return values |
<?php
/**
* Class <API key>
*
* @uses TribeEventsCache
*/
class <API key> {
/**
* @var string
*/
private $template;
/**
* @var int
*/
private $expiration;
/**
* @var string
*/
private $expiration_trigger;
/**
* @var TribeEventsCache
*/
private $cache;
/**
* @var string
*/
private $html;
/**
** Short description
*
* @param $template - which template in the views directory is being cached (relative path).
* @param $id - a unique identifier for this fragment.
* @param $expiration - expiration time for the cached fragment.
* @param $expiration_trigger - wordpress hook to expire on.
*/
public function __construct( $template, $id, $expiration, $expiration_trigger ) {
$this->template = $template;
$this->key = $template . '_' . $id;
$this->expiration = $expiration;
$this->expiration_trigger = $expiration_trigger;
$this->cache = new <API key>();
$this->add_hooks();
}
/**
* Hook in to show cached content and bypass queries where needed
*/
public function add_hooks() {
// set the cached html in transients after the template part is included
add_filter( '<API key>', array( $this, 'set' ), 10, 2 );
// get the cached html right before the setup_view runs so it's available for bypassing any view logic
add_action( '<API key>', array( $this, 'get' ), 9, 1 );
// when the specified template part is included, show the cached html instead
add_filter( '<API key>' . $this->template, array( $this, 'display' ) );
}
/**
* Checks if there is a cached html fragment in the transients, if it's there,
* don't include the requested file path. If not, just return the file path like normal
*
* @param $path file path to the month view template part
*
* @return bool
* @uses <API key>[template] hook
*/
public function display( $path ) {
if ( $this->html !== false ) {
echo $this->html;
return false;
}
return $path;
}
/**
* Set cached html in transients
*
* @param $html
* @param $template
*
* @return string
* @uses <API key> hook
*/
public function set( $html, $template ) {
if ( $template == $this->template ) {
$this->cache->set_transient( $this->key, $html, $this->expiration, $this->expiration_trigger );
}
return $html;
}
/**
* Retrieve the cached html from transients, set class property
*
* @uses <API key> hook
*/
public function get() {
if ( isset( $this->html ) ) {
return $this->html;
}
$this->html = $this->cache->get_transient( $this->key, $this->expiration_trigger );
return $this->html;
}
} |
/* File object interface (what's left of it -- see io.py) */
#ifndef Py_FILEOBJECT_H
#define Py_FILEOBJECT_H
#ifdef __cplusplus
extern "C" {
#endif
#define PY_STDIOTEXTMODE "b"
PyAPI_FUNC(PyObject *) PyFile_FromFd(int, char *, char *, int, char *, char *,
char *, int);
PyAPI_FUNC(PyObject *) PyFile_GetLine(PyObject *, int);
PyAPI_FUNC(int) PyFile_WriteObject(PyObject *, PyObject *, int);
PyAPI_FUNC(int) PyFile_WriteString(const char *, PyObject *);
PyAPI_FUNC(int) <API key>(PyObject *);
#ifndef Py_LIMITED_API
PyAPI_FUNC(char *) <API key>(char *, int, FILE*, PyObject *);
#endif
/* The default encoding used by the platform file system APIs
If non-NULL, this is different than the default encoding for strings
*/
PyAPI_DATA(const char *) <API key>;
PyAPI_DATA(int) <API key>;
/* Internal API
The std printer acts as a preliminary sys.stderr until the new io
infrastructure is in place. */
#ifndef Py_LIMITED_API
PyAPI_FUNC(PyObject *) <API key>(int);
PyAPI_DATA(PyTypeObject) PyStdPrinter_Type;
#if defined _MSC_VER && _MSC_VER >= 1400
/* A routine to check if a file descriptor is valid on Windows. Returns 0
* and sets errno to EBADF if it isn't. This is to avoid Assertions
* from various functions in the Windows CRT beginning with
* Visual Studio 2005
*/
int _PyVerify_fd(int fd);
#else
#define _PyVerify_fd(A) (1) /* dummy */
#endif
#endif /* Py_LIMITED_API */
#ifdef __cplusplus
}
#endif
#endif /* !Py_FILEOBJECT_H */ |
<!DOCTYPE html>
<title>Canvas test: 2d.composite.solid.lighter</title>
<script src="../tests.js"></script>
<link rel="stylesheet" href="../tests.css">
<body>
<p id="passtext">Pass</p>
<p id="failtext">Fail</p>
<p class="output">These images should be identical:</p>
<canvas id="c" class="output" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas>
<p class="output expectedtext">Expected output:<p><img src="2d.composite.solid.lighter.png" class="output expected" id="expected" alt="">
<ul id="d"></ul>
<script>
_addTest(function(canvas, ctx) {
ctx.fillStyle = 'rgba(0, 255, 255, 1.0)';
ctx.fillRect(0, 0, 100, 50);
ctx.<API key> = 'lighter';
ctx.fillStyle = 'rgba(255, 255, 0, 1.0)';
ctx.fillRect(0, 0, 100, 50);
_assertPixelApprox(canvas, 50,25, 255,255,255,255, "50,25", "255,255,255,255", 5);
});
</script> |
// Type definitions for Google Apps Script 2015-11-12
<reference path="google-apps-script.types.d.ts" />
<reference path="google-apps-script.base.d.ts" />
declare module GoogleAppsScript {
export module Contacts {
/**
* Address field in a contact.
*/
export interface AddressField {
deleteAddressField(): void;
getAddress(): string;
getLabel(): Object;
isPrimary(): boolean;
setAddress(address: string): AddressField;
setAsPrimary(): AddressField;
setLabel(field: Field): AddressField;
setLabel(label: string): AddressField;
}
/**
* Company field in a Contact.
*/
export interface CompanyField {
deleteCompanyField(): void;
getCompanyName(): string;
getJobTitle(): string;
isPrimary(): boolean;
setAsPrimary(): CompanyField;
setCompanyName(company: string): CompanyField;
setJobTitle(title: string): CompanyField;
}
/**
* A Contact contains the name, address, and various contact details of a contact.
*/
export interface Contact {
addAddress(label: Object, address: string): AddressField;
addCompany(company: string, title: string): CompanyField;
addCustomField(label: Object, content: Object): CustomField;
addDate(label: Object, month: Base.Month, day: Integer, year: Integer): DateField;
addEmail(label: Object, address: string): EmailField;
addIM(label: Object, address: string): IMField;
addPhone(label: Object, number: string): PhoneField;
addToGroup(group: ContactGroup): Contact;
addUrl(label: Object, url: string): UrlField;
deleteContact(): void;
getAddresses(): AddressField[];
getAddresses(label: Object): AddressField[];
getCompanies(): CompanyField[];
getContactGroups(): ContactGroup[];
getCustomFields(): CustomField[];
getCustomFields(label: Object): CustomField[];
getDates(): DateField[];
getDates(label: Object): DateField[];
getEmails(): EmailField[];
getEmails(label: Object): EmailField[];
getFamilyName(): string;
getFullName(): string;
getGivenName(): string;
getIMs(): IMField[];
getIMs(label: Object): IMField[];
getId(): string;
getInitials(): string;
getLastUpdated(): Date;
getMaidenName(): string;
getMiddleName(): string;
getNickname(): string;
getNotes(): string;
getPhones(): PhoneField[];
getPhones(label: Object): PhoneField[];
getPrefix(): string;
getPrimaryEmail(): string;
getShortName(): string;
getSuffix(): string;
getUrls(): UrlField[];
getUrls(label: Object): UrlField[];
removeFromGroup(group: ContactGroup): Contact;
setFamilyName(familyName: string): Contact;
setFullName(fullName: string): Contact;
setGivenName(givenName: string): Contact;
setInitials(initials: string): Contact;
setMaidenName(maidenName: string): Contact;
setMiddleName(middleName: string): Contact;
setNickname(nickname: string): Contact;
setNotes(notes: string): Contact;
setPrefix(prefix: string): Contact;
setShortName(shortName: string): Contact;
setSuffix(suffix: string): Contact;
getEmailAddresses(): String[];
getHomeAddress(): string;
getHomeFax(): string;
getHomePhone(): string;
getMobilePhone(): string;
getPager(): string;
getUserDefinedField(key: string): string;
<API key>(): Object;
getWorkAddress(): string;
getWorkFax(): string;
getWorkPhone(): string;
setHomeAddress(addr: string): void;
setHomeFax(phone: string): void;
setHomePhone(phone: string): void;
setMobilePhone(phone: string): void;
setPager(phone: string): void;
setPrimaryEmail(primaryEmail: string): void;
setUserDefinedField(key: string, value: string): void;
<API key>(o: Object): void;
setWorkAddress(addr: string): void;
setWorkFax(phone: string): void;
setWorkPhone(phone: string): void;
}
/**
* A ContactGroup is is a group of contacts.
*/
export interface ContactGroup {
addContact(contact: Contact): ContactGroup;
deleteGroup(): void;
getContacts(): Contact[];
getId(): string;
getName(): string;
isSystemGroup(): boolean;
removeContact(contact: Contact): ContactGroup;
setName(name: string): ContactGroup;
getGroupName(): string;
setGroupName(name: string): void;
}
/**
* This class allows users to access their own Google Contacts and create, remove, and update
* contacts listed therein.
*/
export interface ContactsApp {
ExtendedField: ExtendedField
Field: Field
Gender: Gender
Month: Base.Month
Priority: Priority
Sensitivity: Sensitivity
createContact(givenName: string, familyName: string, email: string): Contact;
createContactGroup(name: string): ContactGroup;
deleteContact(contact: Contact): void;
deleteContactGroup(group: ContactGroup): void;
getContact(emailAddress: string): Contact;
getContactById(id: string): Contact;
getContactGroup(name: string): ContactGroup;
getContactGroupById(id: string): ContactGroup;
getContactGroups(): ContactGroup[];
getContacts(): Contact[];
<API key>(query: string): Contact[];
<API key>(query: string, label: Field): Contact[];
<API key>(query: string, label: string): Contact[];
<API key>(query: string): Contact[];
<API key>(query: Object, label: ExtendedField): Contact[];
getContactsByDate(month: Base.Month, day: Integer, label: Field): Contact[];
getContactsByDate(month: Base.Month, day: Integer, year: Integer, label: Field): Contact[];
getContactsByDate(month: Base.Month, day: Integer, year: Integer, label: string): Contact[];
getContactsByDate(month: Base.Month, day: Integer, label: string): Contact[];
<API key>(query: string): Contact[];
<API key>(query: string, label: Field): Contact[];
<API key>(query: string, label: string): Contact[];
getContactsByGroup(group: ContactGroup): Contact[];
getContactsByIM(query: string): Contact[];
getContactsByIM(query: string, label: Field): Contact[];
getContactsByIM(query: string, label: string): Contact[];
<API key>(query: string): Contact[];
getContactsByName(query: string): Contact[];
getContactsByName(query: string, label: Field): Contact[];
getContactsByNotes(query: string): Contact[];
getContactsByPhone(query: string): Contact[];
getContactsByPhone(query: string, label: Field): Contact[];
getContactsByPhone(query: string, label: string): Contact[];
getContactsByUrl(query: string): Contact[];
getContactsByUrl(query: string, label: Field): Contact[];
getContactsByUrl(query: string, label: string): Contact[];
findByEmailAddress(email: string): Contact;
findContactGroup(name: string): ContactGroup;
getAllContacts(): Contact[];
}
/**
* A custom field in a Contact.
*/
export interface CustomField {
deleteCustomField(): void;
getLabel(): Object;
getValue(): Object;
setLabel(field: ExtendedField): CustomField;
setLabel(label: string): CustomField;
setValue(value: Object): CustomField;
}
/**
* A date field in a Contact.
*/
export interface DateField {
deleteDateField(): void;
getDay(): Integer;
getLabel(): Object;
getMonth(): Base.Month;
getYear(): Integer;
setDate(month: Base.Month, day: Integer): DateField;
setDate(month: Base.Month, day: Integer, year: Integer): DateField;
setLabel(label: Field): DateField;
setLabel(label: string): DateField;
}
/**
* An email field in a Contact.
*/
export interface EmailField {
deleteEmailField(): void;
getAddress(): string;
getDisplayName(): string;
getLabel(): Object;
isPrimary(): boolean;
setAddress(address: string): EmailField;
setAsPrimary(): EmailField;
setDisplayName(name: string): EmailField;
setLabel(field: Field): EmailField;
setLabel(label: string): EmailField;
}
/**
* An enum for extended contacts fields.
*/
export enum ExtendedField { HOBBY, MILEAGE, LANGUAGE, GENDER, BILLING_INFORMATION, DIRECTORY_SERVER, SENSITIVITY, PRIORITY, HOME, WORK, USER, OTHER }
/**
* An enum for contacts fields.
*/
export enum Field { FULL_NAME, GIVEN_NAME, MIDDLE_NAME, FAMILY_NAME, MAIDEN_NAME, NICKNAME, SHORT_NAME, INITIALS, PREFIX, SUFFIX, HOME_EMAIL, WORK_EMAIL, BIRTHDAY, ANNIVERSARY, HOME_ADDRESS, WORK_ADDRESS, ASSISTANT_PHONE, CALLBACK_PHONE, MAIN_PHONE, PAGER, HOME_FAX, WORK_FAX, HOME_PHONE, WORK_PHONE, MOBILE_PHONE, GOOGLE_VOICE, NOTES, GOOGLE_TALK, AIM, YAHOO, SKYPE, QQ, MSN, ICQ, JABBER, BLOG, FTP, PROFILE, HOME_PAGE, WORK_WEBSITE, HOME_WEBSITE, JOB_TITLE, COMPANY }
/**
* An enum for contact gender.
*/
export enum Gender { MALE, FEMALE }
/**
* An instant messaging field in a Contact.
*/
export interface IMField {
deleteIMField(): void;
getAddress(): string;
getLabel(): Object;
isPrimary(): boolean;
setAddress(address: string): IMField;
setAsPrimary(): IMField;
setLabel(field: Field): IMField;
setLabel(label: string): IMField;
}
/**
* A phone number field in a Contact.
*/
export interface PhoneField {
deletePhoneField(): void;
getLabel(): Object;
getPhoneNumber(): string;
isPrimary(): boolean;
setAsPrimary(): PhoneField;
setLabel(field: Field): PhoneField;
setLabel(label: string): PhoneField;
setPhoneNumber(number: string): PhoneField;
}
/**
* An enum for contact priority.
*/
export enum Priority { HIGH, LOW, NORMAL }
/**
* An enum for contact sensitivity.
*/
export enum Sensitivity { CONFIDENTIAL, NORMAL, PERSONAL, PRIVATE }
/**
* A URL field in a Contact.
*/
export interface UrlField {
deleteUrlField(): void;
getAddress(): string;
getLabel(): Object;
isPrimary(): boolean;
setAddress(address: string): UrlField;
setAsPrimary(): UrlField;
setLabel(field: Field): UrlField;
setLabel(label: string): UrlField;
}
}
}
declare var ContactsApp: GoogleAppsScript.Contacts.ContactsApp; |
.sv_window {
position: fixed;
bottom: 3px;
right: 10px;
background-color: cadetblue;
padding: 1px;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
font-style: normal;
font-weight: 400;
line-height: 1.42857143;
text-align: left;
text-align: start;
text-decoration: none;
text-shadow: none;
text-transform: none;
letter-spacing: normal;
word-break: normal;
word-spacing: normal;
word-wrap: normal;
white-space: normal;
background-color: #fff;
-<API key>: padding-box;
background-clip: padding-box;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 6px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
line-break: auto; }
.sv_window_title {
padding: 8px 14px;
margin: 0;
font-size: 14px;
background-color: #f7f7f7;
border-bottom: 1px solid #ebebeb;
border-radius: 5px 5px 0 0; }
.sv_window_content {
padding: 8px;
margin: 0; }
.sv_window_title a,
.sv_window_title a:link,
.sv_window_title a:visited {
text-decoration: none;
font-size: 14px;
font-style: normal;
color: black; }
.sv_main {
background-color: #f4f4f4; }
.sv_main hr {
border-bottom: 1px solid #e7e7e7; }
.sv_main input[type="button"],
.sv_main button {
color: white;
background-color: #1ab394; }
.sv_main input[type="button"]:hover,
.sv_main button:hover {
background-color: #179d82; }
.sv_main .sv_q_other input,
.sv_main .sv_q_text_root,
.sv_main .<API key>,
.sv_main input[type="text"],
.sv_main select,
.sv_main textarea {
border: 1px solid #e7e7e7;
color: #6d7072;
background-color: white; }
.sv_main .sv_q_other input:focus,
.sv_main .sv_q_text_root:focus,
.sv_main .<API key>:focus,
.sv_main input[type="text"]:focus,
.sv_main select:focus,
.sv_main textarea:focus {
border: 1px solid #1ab394; }
.sv_main .sv_select_wrapper {
background-color: white; }
.sv_main .sv_select_wrapper:before {
background-color: #1ab394; }
.sv_main .sv_header {
color: #6d7072; }
.sv_main .sv_custom_header {
background-color: #e7e7e7; }
.sv_main .sv_container {
color: #6d7072; }
.sv_main .sv_body {
background-color: white;
border-top: 2px solid #1ab394; }
.sv_main .sv_progress {
background-color: #e7e7e7; }
.sv_main .sv_progress_bar {
background-color: #1ab394; }
.sv_main .sv_p_root > .sv_row {
border-bottom: 1px solid #e7e7e7; }
.sv_main .sv_p_root > .sv_row:nth-child(odd) {
background-color: white; }
.sv_main .sv_p_root > .sv_row:nth-child(even) {
background-color: #f4f4f4; }
.sv_main .sv_q_erbox:not([style*="display: none"]):not([style*="display:none"]) {
border: 1px solid #ed5565;
background-color: #fcdfe2;
color: #ed5565; }
.sv_main .sv_q_erbox:not([style*="display: none"]):not([style*="display:none"]) + input,
.sv_main .sv_q_erbox:not([style*="display: none"]):not([style*="display:none"]) + textarea,
.sv_main .sv_q_erbox:not([style*="display: none"]):not([style*="display:none"]) + .sv_select_wrapper select {
border: 1px solid #ed5565; }
.sv_main .sv_q_erbox:not([style*="display: none"]):not([style*="display:none"]) + input:focus,
.sv_main .sv_q_erbox:not([style*="display: none"]):not([style*="display:none"]) + textarea:focus,
.sv_main .sv_q_erbox:not([style*="display: none"]):not([style*="display:none"]) + .sv_select_wrapper select:focus {
outline: #ed5565 auto 5px; }
.sv_main table.sv_q_matrix tr,
.sv_main table.<API key> tr,
.sv_main table.sv_q_matrix_dynamic tr {
border-bottom: 1px solid #e7e7e7; }
.sv_main .sv_q_rating_item.active .<API key> {
background-color: #179d82;
border-color: #179d82;
color: white; }
.sv_main .sv_q_rating_item .<API key> {
border: 1px solid #e7e7e7; }
.sv_main .sv_q_rating_item .<API key>:hover {
border: 1px solid #179d82; }
.sv_main {
position: relative;
width: 100%;
font-family: "Segoe UI", Frutiger, "Frutiger Linotype", "Dejavu Sans", "Helvetica Neue", Arial, sans-serif;
font-size: 14px; }
.sv_main hr {
border: none; }
.sv_main input[type="button"],
.sv_main button {
font-size: 0.85em;
font-weight: bold;
line-height: 2em;
border: none;
min-width: 100px;
cursor: pointer;
padding: 0 2em;
border-radius: 2px; }
.sv_main .sv_custom_header {
position: absolute;
width: 100%;
height: 275px; }
.sv_main .sv_container {
max-width: 80%;
margin: auto;
position: relative;
padding: 0 1em; }
.sv_main .sv_container .sv_header {
padding-top: 5em;
padding-bottom: 1em;
padding-left: 1em;
padding-right: 1em; }
.sv_main .sv_container .sv_header h3 {
font-size: 2em;
font-weight: 300;
text-align: left;
margin: 0; }
.sv_main .sv_container .sv_body {
padding: 1em 1em 5em 1em; }
.sv_main .sv_container .sv_body .sv_progress {
height: 0.3em; }
.sv_main .sv_container .sv_body .sv_progress .sv_progress_bar {
height: 100%;
position: relative;
margin-top: 2em; }
.sv_main .sv_container .sv_body .sv_progress .sv_progress_bar > span {
position: absolute;
top: -1.5em;
display: inline-block; }
.sv_main .sv_container .sv_body .sv_p_root .sv_page_title {
font-size: 1em;
margin-top: 0.1em;
font-weight: normal; }
.sv_main .sv_container .sv_body .sv_p_root .sv_p_title {
font-weight: bold;
font-size: 1.15em;
margin: 1.5em 0 0 0; }
.sv_main .sv_container .sv_body .sv_p_root > .sv_row {
padding: 0; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q_title {
font-weight: bold;
font-size: 1em;
margin: 0.5em 0; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q_description {
margin-top: -0.6em; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q {
padding: 0.5em 1em 1.5em 1em;
box-sizing: border-box; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q .sv_panel_dynamic .sv_q_title {
font-weight: normal; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q .sv_q_erbox:not([style*="display: none"]):not([style*="display:none"]) {
margin: 1em 0;
padding: 1em; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q .sv_q_other input,
.sv_main .sv_container .sv_body .sv_p_root .sv_q .sv_q_text_root,
.sv_main .sv_container .sv_body .sv_p_root .sv_q .<API key>,
.sv_main .sv_container .sv_body .sv_p_root .sv_q input[type="text"],
.sv_main .sv_container .sv_body .sv_p_root .sv_q select,
.sv_main .sv_container .sv_body .sv_p_root .sv_q textarea {
position: relative;
width: 100%;
box-sizing: border-box;
font-size: 1em;
line-height: 2em;
padding-left: 1em; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q .sv_q_other input:focus,
.sv_main .sv_container .sv_body .sv_p_root .sv_q .sv_q_text_root:focus,
.sv_main .sv_container .sv_body .sv_p_root .sv_q .<API key>:focus,
.sv_main .sv_container .sv_body .sv_p_root .sv_q input[type="text"]:focus,
.sv_main .sv_container .sv_body .sv_p_root .sv_q select:focus,
.sv_main .sv_container .sv_body .sv_p_root .sv_q textarea:focus {
outline: none; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q div.sv_q_text_root,
.sv_main .sv_container .sv_body .sv_p_root .sv_q div.<API key> {
min-height: 2.43em;
min-width: 7em; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q .sv_select_wrapper {
width: 100%;
position: relative;
display: inline-block; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q .sv_select_wrapper select {
display: block;
background: transparent;
appearance: none;
-webkit-appearance: none;
-moz-appearance: none; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q .sv_select_wrapper select::-ms-expand {
display: none; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q .sv_select_wrapper:before {
padding: 1em;
position: absolute;
right: 1px;
right: 0;
top: 1px;
background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDIxLjEuMCwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPgo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4IgoJIHZpZXdCb3g9IjAgMCAzNCAzNCIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgMzQgMzQ7IiB4bWw6c3BhY2U9InByZXNlcnZlIj4KPHN0eWxlIHR5cGU9InRleHQvY3NzIj4KCS5zdDB7ZmlsbDojRkZGRkZGO30KPC9zdHlsZT4KPHBvbHlnb24gY2xhc3M9InN0MCIgcG9pbnRzPSIxMiwxNiAxNCwxNCAxNywxNyAyMCwxNCAyMiwxNiAxNywyMSAiLz4KPC9zdmc+Cg==);
content: "";
background-repeat: no-repeat;
background-position: center; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q input[type="color"] {
min-height: 2em;
padding: 0; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q input[type="radio"],
.sv_main .sv_container .sv_body .sv_p_root .sv_q input[type="checkbox"] {
margin: 0;
margin-right: 0.55em;
width: 1.2em;
height: 1.2em;
vertical-align: middle;
font-size: 1em;
margin-top: -0.1em; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q input[type="radio"]:focus,
.sv_main .sv_container .sv_body .sv_p_root .sv_q input[type="checkbox"]:focus {
outline: none; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q .sv_q_radiogroup.<API key>:not(:last-child),
.sv_main .sv_container .sv_body .sv_p_root .sv_q .sv_q_checkbox.<API key>:not(:last-child) {
margin-right: 1.5em; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q .sv_q_radiogroup > label,
.sv_main .sv_container .sv_body .sv_p_root .sv_q .sv_q_checkbox > label {
white-space: nowrap; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q .<API key>,
.sv_main .sv_container .sv_body .sv_p_root .sv_q .<API key> {
line-height: 2em; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q .sv_q_footer {
padding: 1em 0; }
.sv_main .sv_container .sv_body .sv_p_root table {
width: 100%;
border-collapse: collapse; }
.sv_main .sv_container .sv_body .sv_p_root table.sv_q_matrix .<API key>, .sv_main .sv_container .sv_body .sv_p_root table.<API key> .<API key>, .sv_main .sv_container .sv_body .sv_p_root table.sv_q_matrix_dynamic .<API key> {
padding: 0.3em 2em; }
.sv_main .sv_container .sv_body .sv_p_root table.sv_q_matrix .sv_q_checkbox_label,
.sv_main .sv_container .sv_body .sv_p_root table.sv_q_matrix .<API key>, .sv_main .sv_container .sv_body .sv_p_root table.<API key> .sv_q_checkbox_label,
.sv_main .sv_container .sv_body .sv_p_root table.<API key> .<API key>, .sv_main .sv_container .sv_body .sv_p_root table.sv_q_matrix_dynamic .sv_q_checkbox_label,
.sv_main .sv_container .sv_body .sv_p_root table.sv_q_matrix_dynamic .<API key> {
margin-right: 1.5em; }
.sv_main .sv_container .sv_body .sv_p_root table.sv_q_matrix td {
min-width: 10em; }
.sv_main .sv_container .sv_body .sv_p_root table.sv_q_matrix td .sv_q_m_label {
position: static; }
.sv_main .sv_container .sv_body .sv_p_root table.<API key> .sv_qcbc .<API key> {
margin-right: 1.5em; }
.sv_main .sv_container .sv_body .sv_p_root table td,
.sv_main .sv_container .sv_body .sv_p_root table th {
text-align: left;
padding: 0 1em; }
.sv_main .sv_container .sv_body .sv_p_root table td {
padding: 0.5em;
padding-right: 2em; }
.sv_main .sv_container .sv_body .sv_p_root table th {
line-height: 1.3em;
padding: 0.5em;
vertical-align: bottom;
font-weight: normal; }
.sv_main .sv_container .sv_body .sv_p_root fieldset.sv_qcbc {
line-height: 2em;
padding-top: 0.1em; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q_other {
margin-left: 1em; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q_rating {
line-height: 2em; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q_rating .sv_q_rating_item {
cursor: pointer;
word-spacing: -0.3em; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q_rating .sv_q_rating_item > * {
word-spacing: initial; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q_rating .sv_q_rating_item .<API key> {
display: inline-block;
width: 2em;
margin-left: -1px;
text-align: center; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q_rating .sv_q_rating_item:not(:first-child) .<API key>:not(:hover) {
border-left-color: transparent; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q_rating .<API key> {
margin-right: 0.5em; }
.sv_main .sv_container .sv_body .sv_p_root .sv_q_rating .<API key> {
margin-left: 0.5em; }
.sv_main .sv_container .sv_body .sv_nav {
padding: 1em 0;
min-height: 2em; }
.sv_main .sv_container .sv_body .sv_nav .sv_start_btn,
.sv_main .sv_container .sv_body .sv_nav .sv_next_btn,
.sv_main .sv_container .sv_body .sv_nav .sv_complete_btn {
float: right; }
.sv_main .sv_container .sv_body .sv_nav .sv_prev_btn {
float: left; } |
module.exports = bugs
bugs.usage = 'npm bugs [<pkgname>]'
var npm = require('./npm.js')
var log = require('npmlog')
var opener = require('opener')
var <API key> = require('./<API key>.js')
bugs.completion = function (opts, cb) {
// FIXME: there used to be registry completion here, but it stopped making
// sense somewhere around 50,000 packages on the registry
cb()
}
function bugs (args, cb) {
var n = args.length ? args[0] : '.'
<API key>(n, '.', function (er, d) {
if (er) return cb(er)
var url = d.bugs && ((typeof d.bugs === 'string') ? d.bugs : d.bugs.url)
if (!url) {
url = 'https:
}
log.silly('bugs', 'url', url)
opener(url, { command: npm.config.get('browser') }, cb)
})
} |
import datetime
import decimal
import unicodedata
from importlib import import_module
from django.conf import settings
from django.utils import dateformat, datetime_safe, numberformat
from django.utils.functional import lazy
from django.utils.translation import (
check_for_language, get_language, to_locale,
)
# format_cache is a mapping from (format_type, lang) to the format string.
# By using the cache, it is possible to avoid running get_format_modules
# repeatedly.
_format_cache = {}
<API key> = {}
ISO_INPUT_FORMATS = {
'DATE_INPUT_FORMATS': ['%Y-%m-%d'],
'TIME_INPUT_FORMATS': ['%H:%M:%S', '%H:%M:%S.%f', '%H:%M'],
'<API key>': [
'%Y-%m-%d %H:%M:%S',
'%Y-%m-%d %H:%M:%S.%f',
'%Y-%m-%d %H:%M',
'%Y-%m-%d'
],
}
FORMAT_SETTINGS = frozenset([
'DECIMAL_SEPARATOR',
'THOUSAND_SEPARATOR',
'NUMBER_GROUPING',
'FIRST_DAY_OF_WEEK',
'MONTH_DAY_FORMAT',
'TIME_FORMAT',
'DATE_FORMAT',
'DATETIME_FORMAT',
'SHORT_DATE_FORMAT',
'<API key>',
'YEAR_MONTH_FORMAT',
'DATE_INPUT_FORMATS',
'TIME_INPUT_FORMATS',
'<API key>',
])
def reset_format_cache():
"""Clear any cached formats.
This method is provided primarily for testing purposes,
so that the effects of cached formats can be removed.
"""
global _format_cache, <API key>
_format_cache = {}
<API key> = {}
def iter_format_modules(lang, format_module_path=None):
"""Find format modules."""
if not check_for_language(lang):
return
if format_module_path is None:
format_module_path = settings.FORMAT_MODULE_PATH
format_locations = []
if format_module_path:
if isinstance(format_module_path, str):
format_module_path = [format_module_path]
for path in format_module_path:
format_locations.append(path + '.%s')
format_locations.append('django.conf.locale.%s')
locale = to_locale(lang)
locales = [locale]
if '_' in locale:
locales.append(locale.split('_')[0])
for location in format_locations:
for loc in locales:
try:
yield import_module('%s.formats' % (location % loc))
except ImportError:
pass
def get_format_modules(lang=None, reverse=False):
"""Return a list of the format modules found."""
if lang is None:
lang = get_language()
if lang not in <API key>:
<API key>[lang] = list(iter_format_modules(lang, settings.FORMAT_MODULE_PATH))
modules = <API key>[lang]
if reverse:
return list(reversed(modules))
return modules
def get_format(format_type, lang=None, use_l10n=None):
"""
For a specific format type, return the format for the current
language (locale). Default to the format in the settings.
format_type is the name of the format, e.g. 'DATE_FORMAT'.
If use_l10n is provided and is not None, it forces the value to
be localized (or not), overriding the value of settings.USE_L10N.
"""
use_l10n = use_l10n or (use_l10n is None and settings.USE_L10N)
if use_l10n and lang is None:
lang = get_language()
cache_key = (format_type, lang)
try:
return _format_cache[cache_key]
except KeyError:
pass
# The requested format_type has not been cached yet. Try to find it in any
# of the format_modules for the given lang if l10n is enabled. If it's not
# there or if l10n is disabled, fall back to the project settings.
val = None
if use_l10n:
for module in get_format_modules(lang):
val = getattr(module, format_type, None)
if val is not None:
break
if val is None:
if format_type not in FORMAT_SETTINGS:
return format_type
val = getattr(settings, format_type)
elif format_type in ISO_INPUT_FORMATS:
# If a list of input formats from one of the format_modules was
# retrieved, make sure the ISO_INPUT_FORMATS are in this list.
val = list(val)
for iso_input in ISO_INPUT_FORMATS.get(format_type, ()):
if iso_input not in val:
val.append(iso_input)
_format_cache[cache_key] = val
return val
get_format_lazy = lazy(get_format, str, list, tuple)
def date_format(value, format=None, use_l10n=None):
"""
Format a datetime.date or datetime.datetime object using a
localizable format.
If use_l10n is provided and is not None, that will force the value to
be localized (or not), overriding the value of settings.USE_L10N.
"""
return dateformat.format(value, get_format(format or 'DATE_FORMAT', use_l10n=use_l10n))
def time_format(value, format=None, use_l10n=None):
"""
Format a datetime.time object using a localizable format.
If use_l10n is provided and is not None, it forces the value to
be localized (or not), overriding the value of settings.USE_L10N.
"""
return dateformat.time_format(value, get_format(format or 'TIME_FORMAT', use_l10n=use_l10n))
def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False):
"""
Format a numeric value using localization settings.
If use_l10n is provided and is not None, it forces the value to
be localized (or not), overriding the value of settings.USE_L10N.
"""
if use_l10n or (use_l10n is None and settings.USE_L10N):
lang = get_language()
else:
lang = None
return numberformat.format(
value,
get_format('DECIMAL_SEPARATOR', lang, use_l10n=use_l10n),
decimal_pos,
get_format('NUMBER_GROUPING', lang, use_l10n=use_l10n),
get_format('THOUSAND_SEPARATOR', lang, use_l10n=use_l10n),
force_grouping=force_grouping,
use_l10n=use_l10n,
)
def localize(value, use_l10n=None):
"""
Check if value is a localizable type (date, number...) and return it
formatted as a string using current locale format.
If use_l10n is provided and is not None, it forces the value to
be localized (or not), overriding the value of settings.USE_L10N.
"""
if isinstance(value, str): # Handle strings first for performance reasons.
return value
elif isinstance(value, bool): # Make sure booleans don't get treated as numbers
return str(value)
elif isinstance(value, (decimal.Decimal, float, int)):
return number_format(value, use_l10n=use_l10n)
elif isinstance(value, datetime.datetime):
return date_format(value, 'DATETIME_FORMAT', use_l10n=use_l10n)
elif isinstance(value, datetime.date):
return date_format(value, use_l10n=use_l10n)
elif isinstance(value, datetime.time):
return time_format(value, 'TIME_FORMAT', use_l10n=use_l10n)
return value
def localize_input(value, default=None):
"""
Check if an input value is a localizable type and return it
formatted with the appropriate formatting string of the current locale.
"""
if isinstance(value, str): # Handle strings first for performance reasons.
return value
elif isinstance(value, bool): # Don't treat booleans as numbers.
return str(value)
elif isinstance(value, (decimal.Decimal, float, int)):
return number_format(value)
elif isinstance(value, datetime.datetime):
value = datetime_safe.new_datetime(value)
format = default or get_format('<API key>')[0]
return value.strftime(format)
elif isinstance(value, datetime.date):
value = datetime_safe.new_date(value)
format = default or get_format('DATE_INPUT_FORMATS')[0]
return value.strftime(format)
elif isinstance(value, datetime.time):
format = default or get_format('TIME_INPUT_FORMATS')[0]
return value.strftime(format)
return value
def sanitize_separators(value):
"""
Sanitize a value according to the current decimal and
thousand separator setting. Used with form field input.
"""
if isinstance(value, str):
parts = []
decimal_separator = get_format('DECIMAL_SEPARATOR')
if decimal_separator in value:
value, decimals = value.split(decimal_separator, 1)
parts.append(decimals)
if settings.<API key>:
thousand_sep = get_format('THOUSAND_SEPARATOR')
if thousand_sep == '.' and value.count('.') == 1 and len(value.split('.')[-1]) != 3:
# Special case where we suspect a dot meant decimal separator (see #22171)
pass
else:
for replacement in {
thousand_sep, unicodedata.normalize('NFKD', thousand_sep)}:
value = value.replace(replacement, '')
parts.append(value)
value = '.'.join(reversed(parts))
return value |
# encoding: utf-8
require 'active_support/core_ext/module/delegation'
require 'active_support/deprecation'
module ActiveSupport
class << self
delegate :<API key>, :<API key>=,
:<API key>, :<API key>=,
:to => :'ActiveSupport::JSON::Encoding'
end
module JSON
# matches YAML-formatted dates
DATE_REGEX = /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[ \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?))$/
class << self
delegate :encode, :to => :'ActiveSupport::JSON::Encoding'
end
module Encoding #:nodoc:
class <API key> < StandardError
end
ESCAPED_CHARS = {
"\x00" => '\u0000', "\x01" => '\u0001', "\x02" => '\u0002',
"\x03" => '\u0003', "\x04" => '\u0004', "\x05" => '\u0005',
"\x06" => '\u0006', "\x07" => '\u0007', "\x0B" => '\u000B',
"\x0E" => '\u000E', "\x0F" => '\u000F', "\x10" => '\u0010',
"\x11" => '\u0011', "\x12" => '\u0012', "\x13" => '\u0013',
"\x14" => '\u0014', "\x15" => '\u0015', "\x16" => '\u0016',
"\x17" => '\u0017', "\x18" => '\u0018', "\x19" => '\u0019',
"\x1A" => '\u001A', "\x1B" => '\u001B', "\x1C" => '\u001C',
"\x1D" => '\u001D', "\x1E" => '\u001E', "\x1F" => '\u001F',
"\010" => '\b',
"\f" => '\f',
"\n" => '\n',
"\r" => '\r',
"\t" => '\t',
'"' => '\"',
'\\' => '\\\\',
'>' => '\u003E',
'<' => '\u003C',
'&' => '\u0026' }
class << self
# If true, use ISO 8601 format for dates and times. Otherwise, fall back to the Active Support legacy format.
attr_accessor :<API key>
attr_accessor :escape_regex
attr_reader :<API key>
def <API key>=(value)
self.escape_regex = \
if @<API key> = value
/[\x00-\x1F"\\><&]/
else
/[\x00-\x1F"\\]/
end
end
def escape(string)
string = string.dup.force_encoding(::Encoding::BINARY) if string.respond_to?(:force_encoding)
json = string.
gsub(escape_regex) { |s| ESCAPED_CHARS[s] }.
gsub(/([\xC0-\xDF][\x80-\xBF]|
[\xE0-\xEF][\x80-\xBF]{2}|
[\xF0-\xF7][\x80-\xBF]{3})+/nx) { |s|
s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/n, '\\\\u\&')
}
%("#{json}")
end
# Converts a Ruby object into a JSON string.
def encode(value, options = nil)
options = {} unless Hash === options
seen = (options[:seen] ||= [])
raise <API key>, 'object references itself' if seen.include?(value)
seen << value
value.to_json(options)
ensure
seen.pop
end
end
self.<API key> = true
end
<API key> = Deprecation::<API key>.new('ActiveSupport::JSON::<API key>', Encoding::<API key>)
end
end
# Hack to load json gem first so we can overwrite its to_json.
begin
require 'json'
rescue LoadError
end
require 'active_support/json/variable'
require 'active_support/json/encoders/date'
require 'active_support/json/encoders/date_time'
require 'active_support/json/encoders/enumerable'
require 'active_support/json/encoders/false_class'
require 'active_support/json/encoders/hash'
require 'active_support/json/encoders/nil_class'
require 'active_support/json/encoders/numeric'
require 'active_support/json/encoders/object'
require 'active_support/json/encoders/regexp'
require 'active_support/json/encoders/string'
require 'active_support/json/encoders/symbol'
require 'active_support/json/encoders/time'
require 'active_support/json/encoders/true_class' |
from unittest import TestCase
from django.template.loader import <API key>
from django.template import VariableNode
class NodelistTest(TestCase):
def test_for(self):
source = '{% for i in 1 %}{{ a }}{% endfor %}'
template = <API key>(source)
vars = template.nodelist.get_nodes_by_type(VariableNode)
self.assertEqual(len(vars), 1)
def test_if(self):
source = '{% if x %}{{ a }}{% endif %}'
template = <API key>(source)
vars = template.nodelist.get_nodes_by_type(VariableNode)
self.assertEqual(len(vars), 1)
def test_ifequal(self):
source = '{% ifequal x y %}{{ a }}{% endifequal %}'
template = <API key>(source)
vars = template.nodelist.get_nodes_by_type(VariableNode)
self.assertEqual(len(vars), 1)
def test_ifchanged(self):
source = '{% ifchanged x %}{{ a }}{% endifchanged %}'
template = <API key>(source)
vars = template.nodelist.get_nodes_by_type(VariableNode)
self.assertEqual(len(vars), 1) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.