repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
Jcfunk/navelA-990 | arch/s390/kvm/priv.c | 4093 | 9971 | /*
* priv.c - handling privileged instructions
*
* Copyright IBM Corp. 2008
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (version 2 only)
* as published by the Free Software Foundation.
*
* Author(s): Carsten Otte <cotte@de.ibm.com>
* Christian Borntraeger <borntraeger@de.ibm.com>
*/
#include <linux/kvm.h>
#include <linux/gfp.h>
#include <linux/errno.h>
#include <asm/current.h>
#include <asm/debug.h>
#include <asm/ebcdic.h>
#include <asm/sysinfo.h>
#include "gaccess.h"
#include "kvm-s390.h"
static int handle_set_prefix(struct kvm_vcpu *vcpu)
{
int base2 = vcpu->arch.sie_block->ipb >> 28;
int disp2 = ((vcpu->arch.sie_block->ipb & 0x0fff0000) >> 16);
u64 operand2;
u32 address = 0;
u8 tmp;
vcpu->stat.instruction_spx++;
operand2 = disp2;
if (base2)
operand2 += vcpu->run->s.regs.gprs[base2];
/* must be word boundary */
if (operand2 & 3) {
kvm_s390_inject_program_int(vcpu, PGM_SPECIFICATION);
goto out;
}
/* get the value */
if (get_guest_u32(vcpu, operand2, &address)) {
kvm_s390_inject_program_int(vcpu, PGM_ADDRESSING);
goto out;
}
address = address & 0x7fffe000u;
/* make sure that the new value is valid memory */
if (copy_from_guest_absolute(vcpu, &tmp, address, 1) ||
(copy_from_guest_absolute(vcpu, &tmp, address + PAGE_SIZE, 1))) {
kvm_s390_inject_program_int(vcpu, PGM_ADDRESSING);
goto out;
}
kvm_s390_set_prefix(vcpu, address);
VCPU_EVENT(vcpu, 5, "setting prefix to %x", address);
out:
return 0;
}
static int handle_store_prefix(struct kvm_vcpu *vcpu)
{
int base2 = vcpu->arch.sie_block->ipb >> 28;
int disp2 = ((vcpu->arch.sie_block->ipb & 0x0fff0000) >> 16);
u64 operand2;
u32 address;
vcpu->stat.instruction_stpx++;
operand2 = disp2;
if (base2)
operand2 += vcpu->run->s.regs.gprs[base2];
/* must be word boundary */
if (operand2 & 3) {
kvm_s390_inject_program_int(vcpu, PGM_SPECIFICATION);
goto out;
}
address = vcpu->arch.sie_block->prefix;
address = address & 0x7fffe000u;
/* get the value */
if (put_guest_u32(vcpu, operand2, address)) {
kvm_s390_inject_program_int(vcpu, PGM_ADDRESSING);
goto out;
}
VCPU_EVENT(vcpu, 5, "storing prefix to %x", address);
out:
return 0;
}
static int handle_store_cpu_address(struct kvm_vcpu *vcpu)
{
int base2 = vcpu->arch.sie_block->ipb >> 28;
int disp2 = ((vcpu->arch.sie_block->ipb & 0x0fff0000) >> 16);
u64 useraddr;
int rc;
vcpu->stat.instruction_stap++;
useraddr = disp2;
if (base2)
useraddr += vcpu->run->s.regs.gprs[base2];
if (useraddr & 1) {
kvm_s390_inject_program_int(vcpu, PGM_SPECIFICATION);
goto out;
}
rc = put_guest_u16(vcpu, useraddr, vcpu->vcpu_id);
if (rc == -EFAULT) {
kvm_s390_inject_program_int(vcpu, PGM_ADDRESSING);
goto out;
}
VCPU_EVENT(vcpu, 5, "storing cpu address to %llx", useraddr);
out:
return 0;
}
static int handle_skey(struct kvm_vcpu *vcpu)
{
vcpu->stat.instruction_storage_key++;
vcpu->arch.sie_block->gpsw.addr -= 4;
VCPU_EVENT(vcpu, 4, "%s", "retrying storage key operation");
return 0;
}
static int handle_stsch(struct kvm_vcpu *vcpu)
{
vcpu->stat.instruction_stsch++;
VCPU_EVENT(vcpu, 4, "%s", "store subchannel - CC3");
/* condition code 3 */
vcpu->arch.sie_block->gpsw.mask &= ~(3ul << 44);
vcpu->arch.sie_block->gpsw.mask |= (3 & 3ul) << 44;
return 0;
}
static int handle_chsc(struct kvm_vcpu *vcpu)
{
vcpu->stat.instruction_chsc++;
VCPU_EVENT(vcpu, 4, "%s", "channel subsystem call - CC3");
/* condition code 3 */
vcpu->arch.sie_block->gpsw.mask &= ~(3ul << 44);
vcpu->arch.sie_block->gpsw.mask |= (3 & 3ul) << 44;
return 0;
}
static int handle_stfl(struct kvm_vcpu *vcpu)
{
unsigned int facility_list;
int rc;
vcpu->stat.instruction_stfl++;
/* only pass the facility bits, which we can handle */
facility_list = S390_lowcore.stfl_fac_list & 0xff00fff3;
rc = copy_to_guest(vcpu, offsetof(struct _lowcore, stfl_fac_list),
&facility_list, sizeof(facility_list));
if (rc == -EFAULT)
kvm_s390_inject_program_int(vcpu, PGM_ADDRESSING);
else
VCPU_EVENT(vcpu, 5, "store facility list value %x",
facility_list);
return 0;
}
static int handle_stidp(struct kvm_vcpu *vcpu)
{
int base2 = vcpu->arch.sie_block->ipb >> 28;
int disp2 = ((vcpu->arch.sie_block->ipb & 0x0fff0000) >> 16);
u64 operand2;
int rc;
vcpu->stat.instruction_stidp++;
operand2 = disp2;
if (base2)
operand2 += vcpu->run->s.regs.gprs[base2];
if (operand2 & 7) {
kvm_s390_inject_program_int(vcpu, PGM_SPECIFICATION);
goto out;
}
rc = put_guest_u64(vcpu, operand2, vcpu->arch.stidp_data);
if (rc == -EFAULT) {
kvm_s390_inject_program_int(vcpu, PGM_ADDRESSING);
goto out;
}
VCPU_EVENT(vcpu, 5, "%s", "store cpu id");
out:
return 0;
}
static void handle_stsi_3_2_2(struct kvm_vcpu *vcpu, struct sysinfo_3_2_2 *mem)
{
struct kvm_s390_float_interrupt *fi = &vcpu->kvm->arch.float_int;
int cpus = 0;
int n;
spin_lock(&fi->lock);
for (n = 0; n < KVM_MAX_VCPUS; n++)
if (fi->local_int[n])
cpus++;
spin_unlock(&fi->lock);
/* deal with other level 3 hypervisors */
if (stsi(mem, 3, 2, 2) == -ENOSYS)
mem->count = 0;
if (mem->count < 8)
mem->count++;
for (n = mem->count - 1; n > 0 ; n--)
memcpy(&mem->vm[n], &mem->vm[n - 1], sizeof(mem->vm[0]));
mem->vm[0].cpus_total = cpus;
mem->vm[0].cpus_configured = cpus;
mem->vm[0].cpus_standby = 0;
mem->vm[0].cpus_reserved = 0;
mem->vm[0].caf = 1000;
memcpy(mem->vm[0].name, "KVMguest", 8);
ASCEBC(mem->vm[0].name, 8);
memcpy(mem->vm[0].cpi, "KVM/Linux ", 16);
ASCEBC(mem->vm[0].cpi, 16);
}
static int handle_stsi(struct kvm_vcpu *vcpu)
{
int fc = (vcpu->run->s.regs.gprs[0] & 0xf0000000) >> 28;
int sel1 = vcpu->run->s.regs.gprs[0] & 0xff;
int sel2 = vcpu->run->s.regs.gprs[1] & 0xffff;
int base2 = vcpu->arch.sie_block->ipb >> 28;
int disp2 = ((vcpu->arch.sie_block->ipb & 0x0fff0000) >> 16);
u64 operand2;
unsigned long mem;
vcpu->stat.instruction_stsi++;
VCPU_EVENT(vcpu, 4, "stsi: fc: %x sel1: %x sel2: %x", fc, sel1, sel2);
operand2 = disp2;
if (base2)
operand2 += vcpu->run->s.regs.gprs[base2];
if (operand2 & 0xfff && fc > 0)
return kvm_s390_inject_program_int(vcpu, PGM_SPECIFICATION);
switch (fc) {
case 0:
vcpu->run->s.regs.gprs[0] = 3 << 28;
vcpu->arch.sie_block->gpsw.mask &= ~(3ul << 44);
return 0;
case 1: /* same handling for 1 and 2 */
case 2:
mem = get_zeroed_page(GFP_KERNEL);
if (!mem)
goto out_fail;
if (stsi((void *) mem, fc, sel1, sel2) == -ENOSYS)
goto out_mem;
break;
case 3:
if (sel1 != 2 || sel2 != 2)
goto out_fail;
mem = get_zeroed_page(GFP_KERNEL);
if (!mem)
goto out_fail;
handle_stsi_3_2_2(vcpu, (void *) mem);
break;
default:
goto out_fail;
}
if (copy_to_guest_absolute(vcpu, operand2, (void *) mem, PAGE_SIZE)) {
kvm_s390_inject_program_int(vcpu, PGM_ADDRESSING);
goto out_mem;
}
free_page(mem);
vcpu->arch.sie_block->gpsw.mask &= ~(3ul << 44);
vcpu->run->s.regs.gprs[0] = 0;
return 0;
out_mem:
free_page(mem);
out_fail:
/* condition code 3 */
vcpu->arch.sie_block->gpsw.mask |= 3ul << 44;
return 0;
}
static intercept_handler_t priv_handlers[256] = {
[0x02] = handle_stidp,
[0x10] = handle_set_prefix,
[0x11] = handle_store_prefix,
[0x12] = handle_store_cpu_address,
[0x29] = handle_skey,
[0x2a] = handle_skey,
[0x2b] = handle_skey,
[0x34] = handle_stsch,
[0x5f] = handle_chsc,
[0x7d] = handle_stsi,
[0xb1] = handle_stfl,
};
int kvm_s390_handle_b2(struct kvm_vcpu *vcpu)
{
intercept_handler_t handler;
/*
* a lot of B2 instructions are priviledged. We first check for
* the privileged ones, that we can handle in the kernel. If the
* kernel can handle this instruction, we check for the problem
* state bit and (a) handle the instruction or (b) send a code 2
* program check.
* Anything else goes to userspace.*/
handler = priv_handlers[vcpu->arch.sie_block->ipa & 0x00ff];
if (handler) {
if (vcpu->arch.sie_block->gpsw.mask & PSW_MASK_PSTATE)
return kvm_s390_inject_program_int(vcpu,
PGM_PRIVILEGED_OPERATION);
else
return handler(vcpu);
}
return -EOPNOTSUPP;
}
static int handle_tprot(struct kvm_vcpu *vcpu)
{
int base1 = (vcpu->arch.sie_block->ipb & 0xf0000000) >> 28;
int disp1 = (vcpu->arch.sie_block->ipb & 0x0fff0000) >> 16;
int base2 = (vcpu->arch.sie_block->ipb & 0xf000) >> 12;
int disp2 = vcpu->arch.sie_block->ipb & 0x0fff;
u64 address1 = disp1 + base1 ? vcpu->run->s.regs.gprs[base1] : 0;
u64 address2 = disp2 + base2 ? vcpu->run->s.regs.gprs[base2] : 0;
struct vm_area_struct *vma;
unsigned long user_address;
vcpu->stat.instruction_tprot++;
/* we only handle the Linux memory detection case:
* access key == 0
* guest DAT == off
* everything else goes to userspace. */
if (address2 & 0xf0)
return -EOPNOTSUPP;
if (vcpu->arch.sie_block->gpsw.mask & PSW_MASK_DAT)
return -EOPNOTSUPP;
/* we must resolve the address without holding the mmap semaphore.
* This is ok since the userspace hypervisor is not supposed to change
* the mapping while the guest queries the memory. Otherwise the guest
* might crash or get wrong info anyway. */
user_address = (unsigned long) __guestaddr_to_user(vcpu, address1);
down_read(¤t->mm->mmap_sem);
vma = find_vma(current->mm, user_address);
if (!vma) {
up_read(¤t->mm->mmap_sem);
return kvm_s390_inject_program_int(vcpu, PGM_ADDRESSING);
}
vcpu->arch.sie_block->gpsw.mask &= ~(3ul << 44);
if (!(vma->vm_flags & VM_WRITE) && (vma->vm_flags & VM_READ))
vcpu->arch.sie_block->gpsw.mask |= (1ul << 44);
if (!(vma->vm_flags & VM_WRITE) && !(vma->vm_flags & VM_READ))
vcpu->arch.sie_block->gpsw.mask |= (2ul << 44);
up_read(¤t->mm->mmap_sem);
return 0;
}
int kvm_s390_handle_e5(struct kvm_vcpu *vcpu)
{
/* For e5xx... instructions we only handle TPROT */
if ((vcpu->arch.sie_block->ipa & 0x00ff) == 0x01)
return handle_tprot(vcpu);
return -EOPNOTSUPP;
}
| gpl-2.0 |
djvoleur/kernel_samsung_exynos7420 | drivers/media/pci/cx23885/cx23885-vbi.c | 8189 | 8090 | /*
* Driver for the Conexant CX23885 PCIe bridge
*
* Copyright (c) 2007 Steven Toth <stoth@linuxtv.org>
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include "cx23885.h"
static unsigned int vbibufs = 4;
module_param(vbibufs, int, 0644);
MODULE_PARM_DESC(vbibufs, "number of vbi buffers, range 2-32");
static unsigned int vbi_debug;
module_param(vbi_debug, int, 0644);
MODULE_PARM_DESC(vbi_debug, "enable debug messages [vbi]");
#define dprintk(level, fmt, arg...)\
do { if (vbi_debug >= level)\
printk(KERN_DEBUG "%s/0: " fmt, dev->name, ## arg);\
} while (0)
/* ------------------------------------------------------------------ */
#define VBI_LINE_LENGTH 1440
#define NTSC_VBI_START_LINE 10 /* line 10 - 21 */
#define NTSC_VBI_END_LINE 21
#define NTSC_VBI_LINES (NTSC_VBI_END_LINE - NTSC_VBI_START_LINE + 1)
int cx23885_vbi_fmt(struct file *file, void *priv,
struct v4l2_format *f)
{
struct cx23885_fh *fh = priv;
struct cx23885_dev *dev = fh->dev;
if (dev->tvnorm & V4L2_STD_525_60) {
/* ntsc */
f->fmt.vbi.samples_per_line = VBI_LINE_LENGTH;
f->fmt.vbi.sampling_rate = 27000000;
f->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY;
f->fmt.vbi.offset = 0;
f->fmt.vbi.flags = 0;
f->fmt.vbi.start[0] = 10;
f->fmt.vbi.count[0] = 17;
f->fmt.vbi.start[1] = 263 + 10 + 1;
f->fmt.vbi.count[1] = 17;
} else if (dev->tvnorm & V4L2_STD_625_50) {
/* pal */
f->fmt.vbi.sampling_rate = 35468950;
f->fmt.vbi.start[0] = 7 - 1;
f->fmt.vbi.start[1] = 319 - 1;
}
return 0;
}
/* We're given the Video Interrupt status register.
* The cx23885_video_irq() func has already validated
* the potential error bits, we just need to
* deal with vbi payload and return indication if
* we actually processed any payload.
*/
int cx23885_vbi_irq(struct cx23885_dev *dev, u32 status)
{
u32 count;
int handled = 0;
if (status & VID_BC_MSK_VBI_RISCI1) {
dprintk(1, "%s() VID_BC_MSK_VBI_RISCI1\n", __func__);
spin_lock(&dev->slock);
count = cx_read(VID_A_GPCNT);
cx23885_video_wakeup(dev, &dev->vbiq, count);
spin_unlock(&dev->slock);
handled++;
}
if (status & VID_BC_MSK_VBI_RISCI2) {
dprintk(1, "%s() VID_BC_MSK_VBI_RISCI2\n", __func__);
dprintk(2, "stopper vbi\n");
spin_lock(&dev->slock);
cx23885_restart_vbi_queue(dev, &dev->vbiq);
spin_unlock(&dev->slock);
handled++;
}
return handled;
}
static int cx23885_start_vbi_dma(struct cx23885_dev *dev,
struct cx23885_dmaqueue *q,
struct cx23885_buffer *buf)
{
dprintk(1, "%s()\n", __func__);
/* setup fifo + format */
cx23885_sram_channel_setup(dev, &dev->sram_channels[SRAM_CH02],
buf->vb.width, buf->risc.dma);
/* reset counter */
cx_write(VID_A_GPCNT_CTL, 3);
cx_write(VID_A_VBI_CTRL, 3);
cx_write(VBI_A_GPCNT_CTL, 3);
q->count = 1;
/* enable irq */
cx23885_irq_add_enable(dev, 0x01);
cx_set(VID_A_INT_MSK, 0x000022);
/* start dma */
cx_set(DEV_CNTRL2, (1<<5));
cx_set(VID_A_DMA_CTL, 0x22); /* FIFO and RISC enable */
return 0;
}
int cx23885_restart_vbi_queue(struct cx23885_dev *dev,
struct cx23885_dmaqueue *q)
{
struct cx23885_buffer *buf;
struct list_head *item;
if (list_empty(&q->active))
return 0;
buf = list_entry(q->active.next, struct cx23885_buffer, vb.queue);
dprintk(2, "restart_queue [%p/%d]: restart dma\n",
buf, buf->vb.i);
cx23885_start_vbi_dma(dev, q, buf);
list_for_each(item, &q->active) {
buf = list_entry(item, struct cx23885_buffer, vb.queue);
buf->count = q->count++;
}
mod_timer(&q->timeout, jiffies + (BUFFER_TIMEOUT / 30));
return 0;
}
void cx23885_vbi_timeout(unsigned long data)
{
struct cx23885_dev *dev = (struct cx23885_dev *)data;
struct cx23885_dmaqueue *q = &dev->vbiq;
struct cx23885_buffer *buf;
unsigned long flags;
/* Stop the VBI engine */
cx_clear(VID_A_DMA_CTL, 0x22);
spin_lock_irqsave(&dev->slock, flags);
while (!list_empty(&q->active)) {
buf = list_entry(q->active.next, struct cx23885_buffer,
vb.queue);
list_del(&buf->vb.queue);
buf->vb.state = VIDEOBUF_ERROR;
wake_up(&buf->vb.done);
printk("%s/0: [%p/%d] timeout - dma=0x%08lx\n", dev->name,
buf, buf->vb.i, (unsigned long)buf->risc.dma);
}
cx23885_restart_vbi_queue(dev, q);
spin_unlock_irqrestore(&dev->slock, flags);
}
/* ------------------------------------------------------------------ */
#define VBI_LINE_LENGTH 1440
#define VBI_LINE_COUNT 17
static int
vbi_setup(struct videobuf_queue *q, unsigned int *count, unsigned int *size)
{
*size = VBI_LINE_COUNT * VBI_LINE_LENGTH * 2;
if (0 == *count)
*count = vbibufs;
if (*count < 2)
*count = 2;
if (*count > 32)
*count = 32;
return 0;
}
static int
vbi_prepare(struct videobuf_queue *q, struct videobuf_buffer *vb,
enum v4l2_field field)
{
struct cx23885_fh *fh = q->priv_data;
struct cx23885_dev *dev = fh->dev;
struct cx23885_buffer *buf = container_of(vb,
struct cx23885_buffer, vb);
struct videobuf_dmabuf *dma = videobuf_to_dma(&buf->vb);
unsigned int size;
int rc;
size = VBI_LINE_COUNT * VBI_LINE_LENGTH * 2;
if (0 != buf->vb.baddr && buf->vb.bsize < size)
return -EINVAL;
if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
buf->vb.width = VBI_LINE_LENGTH;
buf->vb.height = VBI_LINE_COUNT;
buf->vb.size = size;
buf->vb.field = V4L2_FIELD_SEQ_TB;
rc = videobuf_iolock(q, &buf->vb, NULL);
if (0 != rc)
goto fail;
cx23885_risc_vbibuffer(dev->pci, &buf->risc,
dma->sglist,
0, buf->vb.width * buf->vb.height,
buf->vb.width, 0,
buf->vb.height);
}
buf->vb.state = VIDEOBUF_PREPARED;
return 0;
fail:
cx23885_free_buffer(q, buf);
return rc;
}
static void
vbi_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
{
struct cx23885_buffer *buf =
container_of(vb, struct cx23885_buffer, vb);
struct cx23885_buffer *prev;
struct cx23885_fh *fh = vq->priv_data;
struct cx23885_dev *dev = fh->dev;
struct cx23885_dmaqueue *q = &dev->vbiq;
/* add jump to stopper */
buf->risc.jmp[0] = cpu_to_le32(RISC_JUMP | RISC_IRQ1 | RISC_CNT_INC);
buf->risc.jmp[1] = cpu_to_le32(q->stopper.dma);
buf->risc.jmp[2] = cpu_to_le32(0); /* bits 63-32 */
if (list_empty(&q->active)) {
list_add_tail(&buf->vb.queue, &q->active);
cx23885_start_vbi_dma(dev, q, buf);
buf->vb.state = VIDEOBUF_ACTIVE;
buf->count = q->count++;
mod_timer(&q->timeout, jiffies + (BUFFER_TIMEOUT / 30));
dprintk(2, "[%p/%d] vbi_queue - first active\n",
buf, buf->vb.i);
} else {
prev = list_entry(q->active.prev, struct cx23885_buffer,
vb.queue);
list_add_tail(&buf->vb.queue, &q->active);
buf->vb.state = VIDEOBUF_ACTIVE;
buf->count = q->count++;
prev->risc.jmp[1] = cpu_to_le32(buf->risc.dma);
prev->risc.jmp[2] = cpu_to_le32(0); /* Bits 63-32 */
dprintk(2, "[%p/%d] buffer_queue - append to active\n",
buf, buf->vb.i);
}
}
static void vbi_release(struct videobuf_queue *q, struct videobuf_buffer *vb)
{
struct cx23885_buffer *buf =
container_of(vb, struct cx23885_buffer, vb);
cx23885_free_buffer(q, buf);
}
struct videobuf_queue_ops cx23885_vbi_qops = {
.buf_setup = vbi_setup,
.buf_prepare = vbi_prepare,
.buf_queue = vbi_queue,
.buf_release = vbi_release,
};
/* ------------------------------------------------------------------ */
/*
* Local variables:
* c-basic-offset: 8
* End:
*/
| gpl-2.0 |
smaccm/odroid-3.14.y-linaro | drivers/net/ethernet/intel/i40e/i40e_common.c | 254 | 68234 | /*******************************************************************************
*
* Intel Ethernet Controller XL710 Family Linux Driver
* Copyright(c) 2013 - 2014 Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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/>.
*
* The full GNU General Public License is included in this distribution in
* the file called "COPYING".
*
* Contact Information:
* e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*
******************************************************************************/
#include "i40e_type.h"
#include "i40e_adminq.h"
#include "i40e_prototype.h"
#include "i40e_virtchnl.h"
/**
* i40e_set_mac_type - Sets MAC type
* @hw: pointer to the HW structure
*
* This function sets the mac type of the adapter based on the
* vendor ID and device ID stored in the hw structure.
**/
static i40e_status i40e_set_mac_type(struct i40e_hw *hw)
{
i40e_status status = 0;
if (hw->vendor_id == PCI_VENDOR_ID_INTEL) {
switch (hw->device_id) {
case I40E_DEV_ID_SFP_XL710:
case I40E_DEV_ID_SFP_X710:
case I40E_DEV_ID_QEMU:
case I40E_DEV_ID_KX_A:
case I40E_DEV_ID_KX_B:
case I40E_DEV_ID_KX_C:
case I40E_DEV_ID_KX_D:
case I40E_DEV_ID_QSFP_A:
case I40E_DEV_ID_QSFP_B:
case I40E_DEV_ID_QSFP_C:
hw->mac.type = I40E_MAC_XL710;
break;
case I40E_DEV_ID_VF:
case I40E_DEV_ID_VF_HV:
hw->mac.type = I40E_MAC_VF;
break;
default:
hw->mac.type = I40E_MAC_GENERIC;
break;
}
} else {
status = I40E_ERR_DEVICE_NOT_SUPPORTED;
}
hw_dbg(hw, "i40e_set_mac_type found mac: %d, returns: %d\n",
hw->mac.type, status);
return status;
}
/**
* i40e_debug_aq
* @hw: debug mask related to admin queue
* @mask: debug mask
* @desc: pointer to admin queue descriptor
* @buffer: pointer to command buffer
*
* Dumps debug log about adminq command with descriptor contents.
**/
void i40e_debug_aq(struct i40e_hw *hw, enum i40e_debug_mask mask, void *desc,
void *buffer)
{
struct i40e_aq_desc *aq_desc = (struct i40e_aq_desc *)desc;
u8 *aq_buffer = (u8 *)buffer;
u32 data[4];
u32 i = 0;
if ((!(mask & hw->debug_mask)) || (desc == NULL))
return;
i40e_debug(hw, mask,
"AQ CMD: opcode 0x%04X, flags 0x%04X, datalen 0x%04X, retval 0x%04X\n",
aq_desc->opcode, aq_desc->flags, aq_desc->datalen,
aq_desc->retval);
i40e_debug(hw, mask, "\tcookie (h,l) 0x%08X 0x%08X\n",
aq_desc->cookie_high, aq_desc->cookie_low);
i40e_debug(hw, mask, "\tparam (0,1) 0x%08X 0x%08X\n",
aq_desc->params.internal.param0,
aq_desc->params.internal.param1);
i40e_debug(hw, mask, "\taddr (h,l) 0x%08X 0x%08X\n",
aq_desc->params.external.addr_high,
aq_desc->params.external.addr_low);
if ((buffer != NULL) && (aq_desc->datalen != 0)) {
memset(data, 0, sizeof(data));
i40e_debug(hw, mask, "AQ CMD Buffer:\n");
for (i = 0; i < le16_to_cpu(aq_desc->datalen); i++) {
data[((i % 16) / 4)] |=
((u32)aq_buffer[i]) << (8 * (i % 4));
if ((i % 16) == 15) {
i40e_debug(hw, mask,
"\t0x%04X %08X %08X %08X %08X\n",
i - 15, data[0], data[1], data[2],
data[3]);
memset(data, 0, sizeof(data));
}
}
if ((i % 16) != 0)
i40e_debug(hw, mask, "\t0x%04X %08X %08X %08X %08X\n",
i - (i % 16), data[0], data[1], data[2],
data[3]);
}
}
/**
* i40e_check_asq_alive
* @hw: pointer to the hw struct
*
* Returns true if Queue is enabled else false.
**/
bool i40e_check_asq_alive(struct i40e_hw *hw)
{
return !!(rd32(hw, hw->aq.asq.len) & I40E_PF_ATQLEN_ATQENABLE_MASK);
}
/**
* i40e_aq_queue_shutdown
* @hw: pointer to the hw struct
* @unloading: is the driver unloading itself
*
* Tell the Firmware that we're shutting down the AdminQ and whether
* or not the driver is unloading as well.
**/
i40e_status i40e_aq_queue_shutdown(struct i40e_hw *hw,
bool unloading)
{
struct i40e_aq_desc desc;
struct i40e_aqc_queue_shutdown *cmd =
(struct i40e_aqc_queue_shutdown *)&desc.params.raw;
i40e_status status;
i40e_fill_default_direct_cmd_desc(&desc,
i40e_aqc_opc_queue_shutdown);
if (unloading)
cmd->driver_unloading = cpu_to_le32(I40E_AQ_DRIVER_UNLOADING);
status = i40e_asq_send_command(hw, &desc, NULL, 0, NULL);
return status;
}
/**
* i40e_init_shared_code - Initialize the shared code
* @hw: pointer to hardware structure
*
* This assigns the MAC type and PHY code and inits the NVM.
* Does not touch the hardware. This function must be called prior to any
* other function in the shared code. The i40e_hw structure should be
* memset to 0 prior to calling this function. The following fields in
* hw structure should be filled in prior to calling this function:
* hw_addr, back, device_id, vendor_id, subsystem_device_id,
* subsystem_vendor_id, and revision_id
**/
i40e_status i40e_init_shared_code(struct i40e_hw *hw)
{
i40e_status status = 0;
u32 reg;
i40e_set_mac_type(hw);
switch (hw->mac.type) {
case I40E_MAC_XL710:
break;
default:
return I40E_ERR_DEVICE_NOT_SUPPORTED;
break;
}
hw->phy.get_link_info = true;
/* Determine port number */
reg = rd32(hw, I40E_PFGEN_PORTNUM);
reg = ((reg & I40E_PFGEN_PORTNUM_PORT_NUM_MASK) >>
I40E_PFGEN_PORTNUM_PORT_NUM_SHIFT);
hw->port = (u8)reg;
/* Determine the PF number based on the PCI fn */
reg = rd32(hw, I40E_GLPCI_CAPSUP);
if (reg & I40E_GLPCI_CAPSUP_ARI_EN_MASK)
hw->pf_id = (u8)((hw->bus.device << 3) | hw->bus.func);
else
hw->pf_id = (u8)hw->bus.func;
status = i40e_init_nvm(hw);
return status;
}
/**
* i40e_aq_mac_address_read - Retrieve the MAC addresses
* @hw: pointer to the hw struct
* @flags: a return indicator of what addresses were added to the addr store
* @addrs: the requestor's mac addr store
* @cmd_details: pointer to command details structure or NULL
**/
static i40e_status i40e_aq_mac_address_read(struct i40e_hw *hw,
u16 *flags,
struct i40e_aqc_mac_address_read_data *addrs,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_mac_address_read *cmd_data =
(struct i40e_aqc_mac_address_read *)&desc.params.raw;
i40e_status status;
i40e_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_mac_address_read);
desc.flags |= cpu_to_le16(I40E_AQ_FLAG_BUF);
status = i40e_asq_send_command(hw, &desc, addrs,
sizeof(*addrs), cmd_details);
*flags = le16_to_cpu(cmd_data->command_flags);
return status;
}
/**
* i40e_aq_mac_address_write - Change the MAC addresses
* @hw: pointer to the hw struct
* @flags: indicates which MAC to be written
* @mac_addr: address to write
* @cmd_details: pointer to command details structure or NULL
**/
i40e_status i40e_aq_mac_address_write(struct i40e_hw *hw,
u16 flags, u8 *mac_addr,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_mac_address_write *cmd_data =
(struct i40e_aqc_mac_address_write *)&desc.params.raw;
i40e_status status;
i40e_fill_default_direct_cmd_desc(&desc,
i40e_aqc_opc_mac_address_write);
cmd_data->command_flags = cpu_to_le16(flags);
cmd_data->mac_sah = cpu_to_le16((u16)mac_addr[0] << 8 | mac_addr[1]);
cmd_data->mac_sal = cpu_to_le32(((u32)mac_addr[2] << 24) |
((u32)mac_addr[3] << 16) |
((u32)mac_addr[4] << 8) |
mac_addr[5]);
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
return status;
}
/**
* i40e_get_mac_addr - get MAC address
* @hw: pointer to the HW structure
* @mac_addr: pointer to MAC address
*
* Reads the adapter's MAC address from register
**/
i40e_status i40e_get_mac_addr(struct i40e_hw *hw, u8 *mac_addr)
{
struct i40e_aqc_mac_address_read_data addrs;
i40e_status status;
u16 flags = 0;
status = i40e_aq_mac_address_read(hw, &flags, &addrs, NULL);
if (flags & I40E_AQC_LAN_ADDR_VALID)
memcpy(mac_addr, &addrs.pf_lan_mac, sizeof(addrs.pf_lan_mac));
return status;
}
/**
* i40e_get_media_type - Gets media type
* @hw: pointer to the hardware structure
**/
static enum i40e_media_type i40e_get_media_type(struct i40e_hw *hw)
{
enum i40e_media_type media;
switch (hw->phy.link_info.phy_type) {
case I40E_PHY_TYPE_10GBASE_SR:
case I40E_PHY_TYPE_10GBASE_LR:
case I40E_PHY_TYPE_40GBASE_SR4:
case I40E_PHY_TYPE_40GBASE_LR4:
media = I40E_MEDIA_TYPE_FIBER;
break;
case I40E_PHY_TYPE_100BASE_TX:
case I40E_PHY_TYPE_1000BASE_T:
case I40E_PHY_TYPE_10GBASE_T:
media = I40E_MEDIA_TYPE_BASET;
break;
case I40E_PHY_TYPE_10GBASE_CR1_CU:
case I40E_PHY_TYPE_40GBASE_CR4_CU:
case I40E_PHY_TYPE_10GBASE_CR1:
case I40E_PHY_TYPE_40GBASE_CR4:
case I40E_PHY_TYPE_10GBASE_SFPP_CU:
media = I40E_MEDIA_TYPE_DA;
break;
case I40E_PHY_TYPE_1000BASE_KX:
case I40E_PHY_TYPE_10GBASE_KX4:
case I40E_PHY_TYPE_10GBASE_KR:
case I40E_PHY_TYPE_40GBASE_KR4:
media = I40E_MEDIA_TYPE_BACKPLANE;
break;
case I40E_PHY_TYPE_SGMII:
case I40E_PHY_TYPE_XAUI:
case I40E_PHY_TYPE_XFI:
case I40E_PHY_TYPE_XLAUI:
case I40E_PHY_TYPE_XLPPI:
default:
media = I40E_MEDIA_TYPE_UNKNOWN;
break;
}
return media;
}
#define I40E_PF_RESET_WAIT_COUNT_A0 200
#define I40E_PF_RESET_WAIT_COUNT 10
/**
* i40e_pf_reset - Reset the PF
* @hw: pointer to the hardware structure
*
* Assuming someone else has triggered a global reset,
* assure the global reset is complete and then reset the PF
**/
i40e_status i40e_pf_reset(struct i40e_hw *hw)
{
u32 cnt = 0;
u32 cnt1 = 0;
u32 reg = 0;
u32 grst_del;
/* Poll for Global Reset steady state in case of recent GRST.
* The grst delay value is in 100ms units, and we'll wait a
* couple counts longer to be sure we don't just miss the end.
*/
grst_del = rd32(hw, I40E_GLGEN_RSTCTL) & I40E_GLGEN_RSTCTL_GRSTDEL_MASK
>> I40E_GLGEN_RSTCTL_GRSTDEL_SHIFT;
for (cnt = 0; cnt < grst_del + 2; cnt++) {
reg = rd32(hw, I40E_GLGEN_RSTAT);
if (!(reg & I40E_GLGEN_RSTAT_DEVSTATE_MASK))
break;
msleep(100);
}
if (reg & I40E_GLGEN_RSTAT_DEVSTATE_MASK) {
hw_dbg(hw, "Global reset polling failed to complete.\n");
return I40E_ERR_RESET_FAILED;
}
/* Now Wait for the FW to be ready */
for (cnt1 = 0; cnt1 < I40E_PF_RESET_WAIT_COUNT; cnt1++) {
reg = rd32(hw, I40E_GLNVM_ULD);
reg &= (I40E_GLNVM_ULD_CONF_CORE_DONE_MASK |
I40E_GLNVM_ULD_CONF_GLOBAL_DONE_MASK);
if (reg == (I40E_GLNVM_ULD_CONF_CORE_DONE_MASK |
I40E_GLNVM_ULD_CONF_GLOBAL_DONE_MASK)) {
hw_dbg(hw, "Core and Global modules ready %d\n", cnt1);
break;
}
usleep_range(10000, 20000);
}
if (!(reg & (I40E_GLNVM_ULD_CONF_CORE_DONE_MASK |
I40E_GLNVM_ULD_CONF_GLOBAL_DONE_MASK))) {
hw_dbg(hw, "wait for FW Reset complete timedout\n");
hw_dbg(hw, "I40E_GLNVM_ULD = 0x%x\n", reg);
return I40E_ERR_RESET_FAILED;
}
/* If there was a Global Reset in progress when we got here,
* we don't need to do the PF Reset
*/
if (!cnt) {
if (hw->revision_id == 0)
cnt = I40E_PF_RESET_WAIT_COUNT_A0;
else
cnt = I40E_PF_RESET_WAIT_COUNT;
reg = rd32(hw, I40E_PFGEN_CTRL);
wr32(hw, I40E_PFGEN_CTRL,
(reg | I40E_PFGEN_CTRL_PFSWR_MASK));
for (; cnt; cnt--) {
reg = rd32(hw, I40E_PFGEN_CTRL);
if (!(reg & I40E_PFGEN_CTRL_PFSWR_MASK))
break;
usleep_range(1000, 2000);
}
if (reg & I40E_PFGEN_CTRL_PFSWR_MASK) {
hw_dbg(hw, "PF reset polling failed to complete.\n");
return I40E_ERR_RESET_FAILED;
}
}
i40e_clear_pxe_mode(hw);
return 0;
}
/**
* i40e_clear_pxe_mode - clear pxe operations mode
* @hw: pointer to the hw struct
*
* Make sure all PXE mode settings are cleared, including things
* like descriptor fetch/write-back mode.
**/
void i40e_clear_pxe_mode(struct i40e_hw *hw)
{
u32 reg;
/* Clear single descriptor fetch/write-back mode */
reg = rd32(hw, I40E_GLLAN_RCTL_0);
if (hw->revision_id == 0) {
/* As a work around clear PXE_MODE instead of setting it */
wr32(hw, I40E_GLLAN_RCTL_0, (reg & (~I40E_GLLAN_RCTL_0_PXE_MODE_MASK)));
} else {
wr32(hw, I40E_GLLAN_RCTL_0, (reg | I40E_GLLAN_RCTL_0_PXE_MODE_MASK));
}
}
/**
* i40e_led_is_mine - helper to find matching led
* @hw: pointer to the hw struct
* @idx: index into GPIO registers
*
* returns: 0 if no match, otherwise the value of the GPIO_CTL register
*/
static u32 i40e_led_is_mine(struct i40e_hw *hw, int idx)
{
u32 gpio_val = 0;
u32 port;
if (!hw->func_caps.led[idx])
return 0;
gpio_val = rd32(hw, I40E_GLGEN_GPIO_CTL(idx));
port = (gpio_val & I40E_GLGEN_GPIO_CTL_PRT_NUM_MASK) >>
I40E_GLGEN_GPIO_CTL_PRT_NUM_SHIFT;
/* if PRT_NUM_NA is 1 then this LED is not port specific, OR
* if it is not our port then ignore
*/
if ((gpio_val & I40E_GLGEN_GPIO_CTL_PRT_NUM_NA_MASK) ||
(port != hw->port))
return 0;
return gpio_val;
}
#define I40E_LED0 22
#define I40E_LINK_ACTIVITY 0xC
/**
* i40e_led_get - return current on/off mode
* @hw: pointer to the hw struct
*
* The value returned is the 'mode' field as defined in the
* GPIO register definitions: 0x0 = off, 0xf = on, and other
* values are variations of possible behaviors relating to
* blink, link, and wire.
**/
u32 i40e_led_get(struct i40e_hw *hw)
{
u32 mode = 0;
int i;
/* as per the documentation GPIO 22-29 are the LED
* GPIO pins named LED0..LED7
*/
for (i = I40E_LED0; i <= I40E_GLGEN_GPIO_CTL_MAX_INDEX; i++) {
u32 gpio_val = i40e_led_is_mine(hw, i);
if (!gpio_val)
continue;
mode = (gpio_val & I40E_GLGEN_GPIO_CTL_LED_MODE_MASK) >>
I40E_GLGEN_GPIO_CTL_LED_MODE_SHIFT;
break;
}
return mode;
}
/**
* i40e_led_set - set new on/off mode
* @hw: pointer to the hw struct
* @mode: 0=off, 0xf=on (else see manual for mode details)
* @blink: true if the LED should blink when on, false if steady
*
* if this function is used to turn on the blink it should
* be used to disable the blink when restoring the original state.
**/
void i40e_led_set(struct i40e_hw *hw, u32 mode, bool blink)
{
int i;
if (mode & 0xfffffff0)
hw_dbg(hw, "invalid mode passed in %X\n", mode);
/* as per the documentation GPIO 22-29 are the LED
* GPIO pins named LED0..LED7
*/
for (i = I40E_LED0; i <= I40E_GLGEN_GPIO_CTL_MAX_INDEX; i++) {
u32 gpio_val = i40e_led_is_mine(hw, i);
if (!gpio_val)
continue;
gpio_val &= ~I40E_GLGEN_GPIO_CTL_LED_MODE_MASK;
/* this & is a bit of paranoia, but serves as a range check */
gpio_val |= ((mode << I40E_GLGEN_GPIO_CTL_LED_MODE_SHIFT) &
I40E_GLGEN_GPIO_CTL_LED_MODE_MASK);
if (mode == I40E_LINK_ACTIVITY)
blink = false;
gpio_val |= (blink ? 1 : 0) <<
I40E_GLGEN_GPIO_CTL_LED_BLINK_SHIFT;
wr32(hw, I40E_GLGEN_GPIO_CTL(i), gpio_val);
break;
}
}
/* Admin command wrappers */
/**
* i40e_aq_set_link_restart_an
* @hw: pointer to the hw struct
* @cmd_details: pointer to command details structure or NULL
*
* Sets up the link and restarts the Auto-Negotiation over the link.
**/
i40e_status i40e_aq_set_link_restart_an(struct i40e_hw *hw,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_set_link_restart_an *cmd =
(struct i40e_aqc_set_link_restart_an *)&desc.params.raw;
i40e_status status;
i40e_fill_default_direct_cmd_desc(&desc,
i40e_aqc_opc_set_link_restart_an);
cmd->command = I40E_AQ_PHY_RESTART_AN;
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
return status;
}
/**
* i40e_aq_get_link_info
* @hw: pointer to the hw struct
* @enable_lse: enable/disable LinkStatusEvent reporting
* @link: pointer to link status structure - optional
* @cmd_details: pointer to command details structure or NULL
*
* Returns the link status of the adapter.
**/
i40e_status i40e_aq_get_link_info(struct i40e_hw *hw,
bool enable_lse, struct i40e_link_status *link,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_get_link_status *resp =
(struct i40e_aqc_get_link_status *)&desc.params.raw;
struct i40e_link_status *hw_link_info = &hw->phy.link_info;
i40e_status status;
u16 command_flags;
i40e_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_get_link_status);
if (enable_lse)
command_flags = I40E_AQ_LSE_ENABLE;
else
command_flags = I40E_AQ_LSE_DISABLE;
resp->command_flags = cpu_to_le16(command_flags);
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
if (status)
goto aq_get_link_info_exit;
/* save off old link status information */
hw->phy.link_info_old = *hw_link_info;
/* update link status */
hw_link_info->phy_type = (enum i40e_aq_phy_type)resp->phy_type;
hw->phy.media_type = i40e_get_media_type(hw);
hw_link_info->link_speed = (enum i40e_aq_link_speed)resp->link_speed;
hw_link_info->link_info = resp->link_info;
hw_link_info->an_info = resp->an_info;
hw_link_info->ext_info = resp->ext_info;
hw_link_info->loopback = resp->loopback;
if (resp->command_flags & cpu_to_le16(I40E_AQ_LSE_ENABLE))
hw_link_info->lse_enable = true;
else
hw_link_info->lse_enable = false;
/* save link status information */
if (link)
*link = *hw_link_info;
/* flag cleared so helper functions don't call AQ again */
hw->phy.get_link_info = false;
aq_get_link_info_exit:
return status;
}
/**
* i40e_aq_add_vsi
* @hw: pointer to the hw struct
* @vsi_ctx: pointer to a vsi context struct
* @cmd_details: pointer to command details structure or NULL
*
* Add a VSI context to the hardware.
**/
i40e_status i40e_aq_add_vsi(struct i40e_hw *hw,
struct i40e_vsi_context *vsi_ctx,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_add_get_update_vsi *cmd =
(struct i40e_aqc_add_get_update_vsi *)&desc.params.raw;
struct i40e_aqc_add_get_update_vsi_completion *resp =
(struct i40e_aqc_add_get_update_vsi_completion *)
&desc.params.raw;
i40e_status status;
i40e_fill_default_direct_cmd_desc(&desc,
i40e_aqc_opc_add_vsi);
cmd->uplink_seid = cpu_to_le16(vsi_ctx->uplink_seid);
cmd->connection_type = vsi_ctx->connection_type;
cmd->vf_id = vsi_ctx->vf_num;
cmd->vsi_flags = cpu_to_le16(vsi_ctx->flags);
desc.flags |= cpu_to_le16((u16)(I40E_AQ_FLAG_BUF | I40E_AQ_FLAG_RD));
if (sizeof(vsi_ctx->info) > I40E_AQ_LARGE_BUF)
desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_LB);
status = i40e_asq_send_command(hw, &desc, &vsi_ctx->info,
sizeof(vsi_ctx->info), cmd_details);
if (status)
goto aq_add_vsi_exit;
vsi_ctx->seid = le16_to_cpu(resp->seid);
vsi_ctx->vsi_number = le16_to_cpu(resp->vsi_number);
vsi_ctx->vsis_allocated = le16_to_cpu(resp->vsi_used);
vsi_ctx->vsis_unallocated = le16_to_cpu(resp->vsi_free);
aq_add_vsi_exit:
return status;
}
/**
* i40e_aq_set_vsi_unicast_promiscuous
* @hw: pointer to the hw struct
* @seid: vsi number
* @set: set unicast promiscuous enable/disable
* @cmd_details: pointer to command details structure or NULL
**/
i40e_status i40e_aq_set_vsi_unicast_promiscuous(struct i40e_hw *hw,
u16 seid, bool set,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_set_vsi_promiscuous_modes *cmd =
(struct i40e_aqc_set_vsi_promiscuous_modes *)&desc.params.raw;
i40e_status status;
u16 flags = 0;
i40e_fill_default_direct_cmd_desc(&desc,
i40e_aqc_opc_set_vsi_promiscuous_modes);
if (set)
flags |= I40E_AQC_SET_VSI_PROMISC_UNICAST;
cmd->promiscuous_flags = cpu_to_le16(flags);
cmd->valid_flags = cpu_to_le16(I40E_AQC_SET_VSI_PROMISC_UNICAST);
cmd->seid = cpu_to_le16(seid);
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
return status;
}
/**
* i40e_aq_set_vsi_multicast_promiscuous
* @hw: pointer to the hw struct
* @seid: vsi number
* @set: set multicast promiscuous enable/disable
* @cmd_details: pointer to command details structure or NULL
**/
i40e_status i40e_aq_set_vsi_multicast_promiscuous(struct i40e_hw *hw,
u16 seid, bool set, struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_set_vsi_promiscuous_modes *cmd =
(struct i40e_aqc_set_vsi_promiscuous_modes *)&desc.params.raw;
i40e_status status;
u16 flags = 0;
i40e_fill_default_direct_cmd_desc(&desc,
i40e_aqc_opc_set_vsi_promiscuous_modes);
if (set)
flags |= I40E_AQC_SET_VSI_PROMISC_MULTICAST;
cmd->promiscuous_flags = cpu_to_le16(flags);
cmd->valid_flags = cpu_to_le16(I40E_AQC_SET_VSI_PROMISC_MULTICAST);
cmd->seid = cpu_to_le16(seid);
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
return status;
}
/**
* i40e_aq_set_vsi_broadcast
* @hw: pointer to the hw struct
* @seid: vsi number
* @set_filter: true to set filter, false to clear filter
* @cmd_details: pointer to command details structure or NULL
*
* Set or clear the broadcast promiscuous flag (filter) for a given VSI.
**/
i40e_status i40e_aq_set_vsi_broadcast(struct i40e_hw *hw,
u16 seid, bool set_filter,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_set_vsi_promiscuous_modes *cmd =
(struct i40e_aqc_set_vsi_promiscuous_modes *)&desc.params.raw;
i40e_status status;
i40e_fill_default_direct_cmd_desc(&desc,
i40e_aqc_opc_set_vsi_promiscuous_modes);
if (set_filter)
cmd->promiscuous_flags
|= cpu_to_le16(I40E_AQC_SET_VSI_PROMISC_BROADCAST);
else
cmd->promiscuous_flags
&= cpu_to_le16(~I40E_AQC_SET_VSI_PROMISC_BROADCAST);
cmd->valid_flags = cpu_to_le16(I40E_AQC_SET_VSI_PROMISC_BROADCAST);
cmd->seid = cpu_to_le16(seid);
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
return status;
}
/**
* i40e_get_vsi_params - get VSI configuration info
* @hw: pointer to the hw struct
* @vsi_ctx: pointer to a vsi context struct
* @cmd_details: pointer to command details structure or NULL
**/
i40e_status i40e_aq_get_vsi_params(struct i40e_hw *hw,
struct i40e_vsi_context *vsi_ctx,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_add_get_update_vsi *cmd =
(struct i40e_aqc_add_get_update_vsi *)&desc.params.raw;
struct i40e_aqc_add_get_update_vsi_completion *resp =
(struct i40e_aqc_add_get_update_vsi_completion *)
&desc.params.raw;
i40e_status status;
i40e_fill_default_direct_cmd_desc(&desc,
i40e_aqc_opc_get_vsi_parameters);
cmd->uplink_seid = cpu_to_le16(vsi_ctx->seid);
desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_BUF);
if (sizeof(vsi_ctx->info) > I40E_AQ_LARGE_BUF)
desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_LB);
status = i40e_asq_send_command(hw, &desc, &vsi_ctx->info,
sizeof(vsi_ctx->info), NULL);
if (status)
goto aq_get_vsi_params_exit;
vsi_ctx->seid = le16_to_cpu(resp->seid);
vsi_ctx->vsi_number = le16_to_cpu(resp->vsi_number);
vsi_ctx->vsis_allocated = le16_to_cpu(resp->vsi_used);
vsi_ctx->vsis_unallocated = le16_to_cpu(resp->vsi_free);
aq_get_vsi_params_exit:
return status;
}
/**
* i40e_aq_update_vsi_params
* @hw: pointer to the hw struct
* @vsi_ctx: pointer to a vsi context struct
* @cmd_details: pointer to command details structure or NULL
*
* Update a VSI context.
**/
i40e_status i40e_aq_update_vsi_params(struct i40e_hw *hw,
struct i40e_vsi_context *vsi_ctx,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_add_get_update_vsi *cmd =
(struct i40e_aqc_add_get_update_vsi *)&desc.params.raw;
i40e_status status;
i40e_fill_default_direct_cmd_desc(&desc,
i40e_aqc_opc_update_vsi_parameters);
cmd->uplink_seid = cpu_to_le16(vsi_ctx->seid);
desc.flags |= cpu_to_le16((u16)(I40E_AQ_FLAG_BUF | I40E_AQ_FLAG_RD));
if (sizeof(vsi_ctx->info) > I40E_AQ_LARGE_BUF)
desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_LB);
status = i40e_asq_send_command(hw, &desc, &vsi_ctx->info,
sizeof(vsi_ctx->info), cmd_details);
return status;
}
/**
* i40e_aq_get_switch_config
* @hw: pointer to the hardware structure
* @buf: pointer to the result buffer
* @buf_size: length of input buffer
* @start_seid: seid to start for the report, 0 == beginning
* @cmd_details: pointer to command details structure or NULL
*
* Fill the buf with switch configuration returned from AdminQ command
**/
i40e_status i40e_aq_get_switch_config(struct i40e_hw *hw,
struct i40e_aqc_get_switch_config_resp *buf,
u16 buf_size, u16 *start_seid,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_switch_seid *scfg =
(struct i40e_aqc_switch_seid *)&desc.params.raw;
i40e_status status;
i40e_fill_default_direct_cmd_desc(&desc,
i40e_aqc_opc_get_switch_config);
desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_BUF);
if (buf_size > I40E_AQ_LARGE_BUF)
desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_LB);
scfg->seid = cpu_to_le16(*start_seid);
status = i40e_asq_send_command(hw, &desc, buf, buf_size, cmd_details);
*start_seid = le16_to_cpu(scfg->seid);
return status;
}
/**
* i40e_aq_get_firmware_version
* @hw: pointer to the hw struct
* @fw_major_version: firmware major version
* @fw_minor_version: firmware minor version
* @api_major_version: major queue version
* @api_minor_version: minor queue version
* @cmd_details: pointer to command details structure or NULL
*
* Get the firmware version from the admin queue commands
**/
i40e_status i40e_aq_get_firmware_version(struct i40e_hw *hw,
u16 *fw_major_version, u16 *fw_minor_version,
u16 *api_major_version, u16 *api_minor_version,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_get_version *resp =
(struct i40e_aqc_get_version *)&desc.params.raw;
i40e_status status;
i40e_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_get_version);
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
if (!status) {
if (fw_major_version != NULL)
*fw_major_version = le16_to_cpu(resp->fw_major);
if (fw_minor_version != NULL)
*fw_minor_version = le16_to_cpu(resp->fw_minor);
if (api_major_version != NULL)
*api_major_version = le16_to_cpu(resp->api_major);
if (api_minor_version != NULL)
*api_minor_version = le16_to_cpu(resp->api_minor);
}
return status;
}
/**
* i40e_aq_send_driver_version
* @hw: pointer to the hw struct
* @dv: driver's major, minor version
* @cmd_details: pointer to command details structure or NULL
*
* Send the driver version to the firmware
**/
i40e_status i40e_aq_send_driver_version(struct i40e_hw *hw,
struct i40e_driver_version *dv,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_driver_version *cmd =
(struct i40e_aqc_driver_version *)&desc.params.raw;
i40e_status status;
if (dv == NULL)
return I40E_ERR_PARAM;
i40e_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_driver_version);
desc.flags |= cpu_to_le16(I40E_AQ_FLAG_SI);
cmd->driver_major_ver = dv->major_version;
cmd->driver_minor_ver = dv->minor_version;
cmd->driver_build_ver = dv->build_version;
cmd->driver_subbuild_ver = dv->subbuild_version;
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
return status;
}
/**
* i40e_get_link_status - get status of the HW network link
* @hw: pointer to the hw struct
*
* Returns true if link is up, false if link is down.
*
* Side effect: LinkStatusEvent reporting becomes enabled
**/
bool i40e_get_link_status(struct i40e_hw *hw)
{
i40e_status status = 0;
bool link_status = false;
if (hw->phy.get_link_info) {
status = i40e_aq_get_link_info(hw, true, NULL, NULL);
if (status)
goto i40e_get_link_status_exit;
}
link_status = hw->phy.link_info.link_info & I40E_AQ_LINK_UP;
i40e_get_link_status_exit:
return link_status;
}
/**
* i40e_aq_add_veb - Insert a VEB between the VSI and the MAC
* @hw: pointer to the hw struct
* @uplink_seid: the MAC or other gizmo SEID
* @downlink_seid: the VSI SEID
* @enabled_tc: bitmap of TCs to be enabled
* @default_port: true for default port VSI, false for control port
* @enable_l2_filtering: true to add L2 filter table rules to regular forwarding rules for cloud support
* @veb_seid: pointer to where to put the resulting VEB SEID
* @cmd_details: pointer to command details structure or NULL
*
* This asks the FW to add a VEB between the uplink and downlink
* elements. If the uplink SEID is 0, this will be a floating VEB.
**/
i40e_status i40e_aq_add_veb(struct i40e_hw *hw, u16 uplink_seid,
u16 downlink_seid, u8 enabled_tc,
bool default_port, bool enable_l2_filtering,
u16 *veb_seid,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_add_veb *cmd =
(struct i40e_aqc_add_veb *)&desc.params.raw;
struct i40e_aqc_add_veb_completion *resp =
(struct i40e_aqc_add_veb_completion *)&desc.params.raw;
i40e_status status;
u16 veb_flags = 0;
/* SEIDs need to either both be set or both be 0 for floating VEB */
if (!!uplink_seid != !!downlink_seid)
return I40E_ERR_PARAM;
i40e_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_add_veb);
cmd->uplink_seid = cpu_to_le16(uplink_seid);
cmd->downlink_seid = cpu_to_le16(downlink_seid);
cmd->enable_tcs = enabled_tc;
if (!uplink_seid)
veb_flags |= I40E_AQC_ADD_VEB_FLOATING;
if (default_port)
veb_flags |= I40E_AQC_ADD_VEB_PORT_TYPE_DEFAULT;
else
veb_flags |= I40E_AQC_ADD_VEB_PORT_TYPE_DATA;
if (enable_l2_filtering)
veb_flags |= I40E_AQC_ADD_VEB_ENABLE_L2_FILTER;
cmd->veb_flags = cpu_to_le16(veb_flags);
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
if (!status && veb_seid)
*veb_seid = le16_to_cpu(resp->veb_seid);
return status;
}
/**
* i40e_aq_get_veb_parameters - Retrieve VEB parameters
* @hw: pointer to the hw struct
* @veb_seid: the SEID of the VEB to query
* @switch_id: the uplink switch id
* @floating: set to true if the VEB is floating
* @statistic_index: index of the stats counter block for this VEB
* @vebs_used: number of VEB's used by function
* @vebs_free: total VEB's not reserved by any function
* @cmd_details: pointer to command details structure or NULL
*
* This retrieves the parameters for a particular VEB, specified by
* uplink_seid, and returns them to the caller.
**/
i40e_status i40e_aq_get_veb_parameters(struct i40e_hw *hw,
u16 veb_seid, u16 *switch_id,
bool *floating, u16 *statistic_index,
u16 *vebs_used, u16 *vebs_free,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_get_veb_parameters_completion *cmd_resp =
(struct i40e_aqc_get_veb_parameters_completion *)
&desc.params.raw;
i40e_status status;
if (veb_seid == 0)
return I40E_ERR_PARAM;
i40e_fill_default_direct_cmd_desc(&desc,
i40e_aqc_opc_get_veb_parameters);
cmd_resp->seid = cpu_to_le16(veb_seid);
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
if (status)
goto get_veb_exit;
if (switch_id)
*switch_id = le16_to_cpu(cmd_resp->switch_id);
if (statistic_index)
*statistic_index = le16_to_cpu(cmd_resp->statistic_index);
if (vebs_used)
*vebs_used = le16_to_cpu(cmd_resp->vebs_used);
if (vebs_free)
*vebs_free = le16_to_cpu(cmd_resp->vebs_free);
if (floating) {
u16 flags = le16_to_cpu(cmd_resp->veb_flags);
if (flags & I40E_AQC_ADD_VEB_FLOATING)
*floating = true;
else
*floating = false;
}
get_veb_exit:
return status;
}
/**
* i40e_aq_add_macvlan
* @hw: pointer to the hw struct
* @seid: VSI for the mac address
* @mv_list: list of macvlans to be added
* @count: length of the list
* @cmd_details: pointer to command details structure or NULL
*
* Add MAC/VLAN addresses to the HW filtering
**/
i40e_status i40e_aq_add_macvlan(struct i40e_hw *hw, u16 seid,
struct i40e_aqc_add_macvlan_element_data *mv_list,
u16 count, struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_macvlan *cmd =
(struct i40e_aqc_macvlan *)&desc.params.raw;
i40e_status status;
u16 buf_size;
if (count == 0 || !mv_list || !hw)
return I40E_ERR_PARAM;
buf_size = count * sizeof(struct i40e_aqc_add_macvlan_element_data);
/* prep the rest of the request */
i40e_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_add_macvlan);
cmd->num_addresses = cpu_to_le16(count);
cmd->seid[0] = cpu_to_le16(I40E_AQC_MACVLAN_CMD_SEID_VALID | seid);
cmd->seid[1] = 0;
cmd->seid[2] = 0;
desc.flags |= cpu_to_le16((u16)(I40E_AQ_FLAG_BUF | I40E_AQ_FLAG_RD));
if (buf_size > I40E_AQ_LARGE_BUF)
desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_LB);
status = i40e_asq_send_command(hw, &desc, mv_list, buf_size,
cmd_details);
return status;
}
/**
* i40e_aq_remove_macvlan
* @hw: pointer to the hw struct
* @seid: VSI for the mac address
* @mv_list: list of macvlans to be removed
* @count: length of the list
* @cmd_details: pointer to command details structure or NULL
*
* Remove MAC/VLAN addresses from the HW filtering
**/
i40e_status i40e_aq_remove_macvlan(struct i40e_hw *hw, u16 seid,
struct i40e_aqc_remove_macvlan_element_data *mv_list,
u16 count, struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_macvlan *cmd =
(struct i40e_aqc_macvlan *)&desc.params.raw;
i40e_status status;
u16 buf_size;
if (count == 0 || !mv_list || !hw)
return I40E_ERR_PARAM;
buf_size = count * sizeof(struct i40e_aqc_remove_macvlan_element_data);
/* prep the rest of the request */
i40e_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_remove_macvlan);
cmd->num_addresses = cpu_to_le16(count);
cmd->seid[0] = cpu_to_le16(I40E_AQC_MACVLAN_CMD_SEID_VALID | seid);
cmd->seid[1] = 0;
cmd->seid[2] = 0;
desc.flags |= cpu_to_le16((u16)(I40E_AQ_FLAG_BUF | I40E_AQ_FLAG_RD));
if (buf_size > I40E_AQ_LARGE_BUF)
desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_LB);
status = i40e_asq_send_command(hw, &desc, mv_list, buf_size,
cmd_details);
return status;
}
/**
* i40e_aq_send_msg_to_vf
* @hw: pointer to the hardware structure
* @vfid: vf id to send msg
* @v_opcode: opcodes for VF-PF communication
* @v_retval: return error code
* @msg: pointer to the msg buffer
* @msglen: msg length
* @cmd_details: pointer to command details
*
* send msg to vf
**/
i40e_status i40e_aq_send_msg_to_vf(struct i40e_hw *hw, u16 vfid,
u32 v_opcode, u32 v_retval, u8 *msg, u16 msglen,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_pf_vf_message *cmd =
(struct i40e_aqc_pf_vf_message *)&desc.params.raw;
i40e_status status;
i40e_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_send_msg_to_vf);
cmd->id = cpu_to_le32(vfid);
desc.cookie_high = cpu_to_le32(v_opcode);
desc.cookie_low = cpu_to_le32(v_retval);
desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_SI);
if (msglen) {
desc.flags |= cpu_to_le16((u16)(I40E_AQ_FLAG_BUF |
I40E_AQ_FLAG_RD));
if (msglen > I40E_AQ_LARGE_BUF)
desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_LB);
desc.datalen = cpu_to_le16(msglen);
}
status = i40e_asq_send_command(hw, &desc, msg, msglen, cmd_details);
return status;
}
/**
* i40e_aq_set_hmc_resource_profile
* @hw: pointer to the hw struct
* @profile: type of profile the HMC is to be set as
* @pe_vf_enabled_count: the number of PE enabled VFs the system has
* @cmd_details: pointer to command details structure or NULL
*
* set the HMC profile of the device.
**/
i40e_status i40e_aq_set_hmc_resource_profile(struct i40e_hw *hw,
enum i40e_aq_hmc_profile profile,
u8 pe_vf_enabled_count,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aq_get_set_hmc_resource_profile *cmd =
(struct i40e_aq_get_set_hmc_resource_profile *)&desc.params.raw;
i40e_status status;
i40e_fill_default_direct_cmd_desc(&desc,
i40e_aqc_opc_set_hmc_resource_profile);
cmd->pm_profile = (u8)profile;
cmd->pe_vf_enabled = pe_vf_enabled_count;
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
return status;
}
/**
* i40e_aq_request_resource
* @hw: pointer to the hw struct
* @resource: resource id
* @access: access type
* @sdp_number: resource number
* @timeout: the maximum time in ms that the driver may hold the resource
* @cmd_details: pointer to command details structure or NULL
*
* requests common resource using the admin queue commands
**/
i40e_status i40e_aq_request_resource(struct i40e_hw *hw,
enum i40e_aq_resources_ids resource,
enum i40e_aq_resource_access_type access,
u8 sdp_number, u64 *timeout,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_request_resource *cmd_resp =
(struct i40e_aqc_request_resource *)&desc.params.raw;
i40e_status status;
i40e_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_request_resource);
cmd_resp->resource_id = cpu_to_le16(resource);
cmd_resp->access_type = cpu_to_le16(access);
cmd_resp->resource_number = cpu_to_le32(sdp_number);
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
/* The completion specifies the maximum time in ms that the driver
* may hold the resource in the Timeout field.
* If the resource is held by someone else, the command completes with
* busy return value and the timeout field indicates the maximum time
* the current owner of the resource has to free it.
*/
if (!status || hw->aq.asq_last_status == I40E_AQ_RC_EBUSY)
*timeout = le32_to_cpu(cmd_resp->timeout);
return status;
}
/**
* i40e_aq_release_resource
* @hw: pointer to the hw struct
* @resource: resource id
* @sdp_number: resource number
* @cmd_details: pointer to command details structure or NULL
*
* release common resource using the admin queue commands
**/
i40e_status i40e_aq_release_resource(struct i40e_hw *hw,
enum i40e_aq_resources_ids resource,
u8 sdp_number,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_request_resource *cmd =
(struct i40e_aqc_request_resource *)&desc.params.raw;
i40e_status status;
i40e_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_release_resource);
cmd->resource_id = cpu_to_le16(resource);
cmd->resource_number = cpu_to_le32(sdp_number);
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
return status;
}
/**
* i40e_aq_read_nvm
* @hw: pointer to the hw struct
* @module_pointer: module pointer location in words from the NVM beginning
* @offset: byte offset from the module beginning
* @length: length of the section to be read (in bytes from the offset)
* @data: command buffer (size [bytes] = length)
* @last_command: tells if this is the last command in a series
* @cmd_details: pointer to command details structure or NULL
*
* Read the NVM using the admin queue commands
**/
i40e_status i40e_aq_read_nvm(struct i40e_hw *hw, u8 module_pointer,
u32 offset, u16 length, void *data,
bool last_command,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_nvm_update *cmd =
(struct i40e_aqc_nvm_update *)&desc.params.raw;
i40e_status status;
/* In offset the highest byte must be zeroed. */
if (offset & 0xFF000000) {
status = I40E_ERR_PARAM;
goto i40e_aq_read_nvm_exit;
}
i40e_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_nvm_read);
/* If this is the last command in a series, set the proper flag. */
if (last_command)
cmd->command_flags |= I40E_AQ_NVM_LAST_CMD;
cmd->module_pointer = module_pointer;
cmd->offset = cpu_to_le32(offset);
cmd->length = cpu_to_le16(length);
desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_BUF);
if (length > I40E_AQ_LARGE_BUF)
desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_LB);
status = i40e_asq_send_command(hw, &desc, data, length, cmd_details);
i40e_aq_read_nvm_exit:
return status;
}
#define I40E_DEV_FUNC_CAP_SWITCH_MODE 0x01
#define I40E_DEV_FUNC_CAP_MGMT_MODE 0x02
#define I40E_DEV_FUNC_CAP_NPAR 0x03
#define I40E_DEV_FUNC_CAP_OS2BMC 0x04
#define I40E_DEV_FUNC_CAP_VALID_FUNC 0x05
#define I40E_DEV_FUNC_CAP_SRIOV_1_1 0x12
#define I40E_DEV_FUNC_CAP_VF 0x13
#define I40E_DEV_FUNC_CAP_VMDQ 0x14
#define I40E_DEV_FUNC_CAP_802_1_QBG 0x15
#define I40E_DEV_FUNC_CAP_802_1_QBH 0x16
#define I40E_DEV_FUNC_CAP_VSI 0x17
#define I40E_DEV_FUNC_CAP_DCB 0x18
#define I40E_DEV_FUNC_CAP_FCOE 0x21
#define I40E_DEV_FUNC_CAP_RSS 0x40
#define I40E_DEV_FUNC_CAP_RX_QUEUES 0x41
#define I40E_DEV_FUNC_CAP_TX_QUEUES 0x42
#define I40E_DEV_FUNC_CAP_MSIX 0x43
#define I40E_DEV_FUNC_CAP_MSIX_VF 0x44
#define I40E_DEV_FUNC_CAP_FLOW_DIRECTOR 0x45
#define I40E_DEV_FUNC_CAP_IEEE_1588 0x46
#define I40E_DEV_FUNC_CAP_MFP_MODE_1 0xF1
#define I40E_DEV_FUNC_CAP_CEM 0xF2
#define I40E_DEV_FUNC_CAP_IWARP 0x51
#define I40E_DEV_FUNC_CAP_LED 0x61
#define I40E_DEV_FUNC_CAP_SDP 0x62
#define I40E_DEV_FUNC_CAP_MDIO 0x63
/**
* i40e_parse_discover_capabilities
* @hw: pointer to the hw struct
* @buff: pointer to a buffer containing device/function capability records
* @cap_count: number of capability records in the list
* @list_type_opc: type of capabilities list to parse
*
* Parse the device/function capabilities list.
**/
static void i40e_parse_discover_capabilities(struct i40e_hw *hw, void *buff,
u32 cap_count,
enum i40e_admin_queue_opc list_type_opc)
{
struct i40e_aqc_list_capabilities_element_resp *cap;
u32 number, logical_id, phys_id;
struct i40e_hw_capabilities *p;
u32 reg_val;
u32 i = 0;
u16 id;
cap = (struct i40e_aqc_list_capabilities_element_resp *) buff;
if (list_type_opc == i40e_aqc_opc_list_dev_capabilities)
p = (struct i40e_hw_capabilities *)&hw->dev_caps;
else if (list_type_opc == i40e_aqc_opc_list_func_capabilities)
p = (struct i40e_hw_capabilities *)&hw->func_caps;
else
return;
for (i = 0; i < cap_count; i++, cap++) {
id = le16_to_cpu(cap->id);
number = le32_to_cpu(cap->number);
logical_id = le32_to_cpu(cap->logical_id);
phys_id = le32_to_cpu(cap->phys_id);
switch (id) {
case I40E_DEV_FUNC_CAP_SWITCH_MODE:
p->switch_mode = number;
break;
case I40E_DEV_FUNC_CAP_MGMT_MODE:
p->management_mode = number;
break;
case I40E_DEV_FUNC_CAP_NPAR:
p->npar_enable = number;
break;
case I40E_DEV_FUNC_CAP_OS2BMC:
p->os2bmc = number;
break;
case I40E_DEV_FUNC_CAP_VALID_FUNC:
p->valid_functions = number;
break;
case I40E_DEV_FUNC_CAP_SRIOV_1_1:
if (number == 1)
p->sr_iov_1_1 = true;
break;
case I40E_DEV_FUNC_CAP_VF:
p->num_vfs = number;
p->vf_base_id = logical_id;
break;
case I40E_DEV_FUNC_CAP_VMDQ:
if (number == 1)
p->vmdq = true;
break;
case I40E_DEV_FUNC_CAP_802_1_QBG:
if (number == 1)
p->evb_802_1_qbg = true;
break;
case I40E_DEV_FUNC_CAP_802_1_QBH:
if (number == 1)
p->evb_802_1_qbh = true;
break;
case I40E_DEV_FUNC_CAP_VSI:
p->num_vsis = number;
break;
case I40E_DEV_FUNC_CAP_DCB:
if (number == 1) {
p->dcb = true;
p->enabled_tcmap = logical_id;
p->maxtc = phys_id;
}
break;
case I40E_DEV_FUNC_CAP_FCOE:
if (number == 1)
p->fcoe = true;
break;
case I40E_DEV_FUNC_CAP_RSS:
p->rss = true;
reg_val = rd32(hw, I40E_PFQF_CTL_0);
if (reg_val & I40E_PFQF_CTL_0_HASHLUTSIZE_MASK)
p->rss_table_size = number;
else
p->rss_table_size = 128;
p->rss_table_entry_width = logical_id;
break;
case I40E_DEV_FUNC_CAP_RX_QUEUES:
p->num_rx_qp = number;
p->base_queue = phys_id;
break;
case I40E_DEV_FUNC_CAP_TX_QUEUES:
p->num_tx_qp = number;
p->base_queue = phys_id;
break;
case I40E_DEV_FUNC_CAP_MSIX:
p->num_msix_vectors = number;
break;
case I40E_DEV_FUNC_CAP_MSIX_VF:
p->num_msix_vectors_vf = number;
break;
case I40E_DEV_FUNC_CAP_MFP_MODE_1:
if (number == 1)
p->mfp_mode_1 = true;
break;
case I40E_DEV_FUNC_CAP_CEM:
if (number == 1)
p->mgmt_cem = true;
break;
case I40E_DEV_FUNC_CAP_IWARP:
if (number == 1)
p->iwarp = true;
break;
case I40E_DEV_FUNC_CAP_LED:
if (phys_id < I40E_HW_CAP_MAX_GPIO)
p->led[phys_id] = true;
break;
case I40E_DEV_FUNC_CAP_SDP:
if (phys_id < I40E_HW_CAP_MAX_GPIO)
p->sdp[phys_id] = true;
break;
case I40E_DEV_FUNC_CAP_MDIO:
if (number == 1) {
p->mdio_port_num = phys_id;
p->mdio_port_mode = logical_id;
}
break;
case I40E_DEV_FUNC_CAP_IEEE_1588:
if (number == 1)
p->ieee_1588 = true;
break;
case I40E_DEV_FUNC_CAP_FLOW_DIRECTOR:
p->fd = true;
p->fd_filters_guaranteed = number;
p->fd_filters_best_effort = logical_id;
break;
default:
break;
}
}
/* additional HW specific goodies that might
* someday be HW version specific
*/
p->rx_buf_chain_len = I40E_MAX_CHAINED_RX_BUFFERS;
}
/**
* i40e_aq_discover_capabilities
* @hw: pointer to the hw struct
* @buff: a virtual buffer to hold the capabilities
* @buff_size: Size of the virtual buffer
* @data_size: Size of the returned data, or buff size needed if AQ err==ENOMEM
* @list_type_opc: capabilities type to discover - pass in the command opcode
* @cmd_details: pointer to command details structure or NULL
*
* Get the device capabilities descriptions from the firmware
**/
i40e_status i40e_aq_discover_capabilities(struct i40e_hw *hw,
void *buff, u16 buff_size, u16 *data_size,
enum i40e_admin_queue_opc list_type_opc,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aqc_list_capabilites *cmd;
struct i40e_aq_desc desc;
i40e_status status = 0;
cmd = (struct i40e_aqc_list_capabilites *)&desc.params.raw;
if (list_type_opc != i40e_aqc_opc_list_func_capabilities &&
list_type_opc != i40e_aqc_opc_list_dev_capabilities) {
status = I40E_ERR_PARAM;
goto exit;
}
i40e_fill_default_direct_cmd_desc(&desc, list_type_opc);
desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_BUF);
if (buff_size > I40E_AQ_LARGE_BUF)
desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_LB);
status = i40e_asq_send_command(hw, &desc, buff, buff_size, cmd_details);
*data_size = le16_to_cpu(desc.datalen);
if (status)
goto exit;
i40e_parse_discover_capabilities(hw, buff, le32_to_cpu(cmd->count),
list_type_opc);
exit:
return status;
}
/**
* i40e_aq_get_lldp_mib
* @hw: pointer to the hw struct
* @bridge_type: type of bridge requested
* @mib_type: Local, Remote or both Local and Remote MIBs
* @buff: pointer to a user supplied buffer to store the MIB block
* @buff_size: size of the buffer (in bytes)
* @local_len : length of the returned Local LLDP MIB
* @remote_len: length of the returned Remote LLDP MIB
* @cmd_details: pointer to command details structure or NULL
*
* Requests the complete LLDP MIB (entire packet).
**/
i40e_status i40e_aq_get_lldp_mib(struct i40e_hw *hw, u8 bridge_type,
u8 mib_type, void *buff, u16 buff_size,
u16 *local_len, u16 *remote_len,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_lldp_get_mib *cmd =
(struct i40e_aqc_lldp_get_mib *)&desc.params.raw;
struct i40e_aqc_lldp_get_mib *resp =
(struct i40e_aqc_lldp_get_mib *)&desc.params.raw;
i40e_status status;
if (buff_size == 0 || !buff)
return I40E_ERR_PARAM;
i40e_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_lldp_get_mib);
/* Indirect Command */
desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_BUF);
cmd->type = mib_type & I40E_AQ_LLDP_MIB_TYPE_MASK;
cmd->type |= ((bridge_type << I40E_AQ_LLDP_BRIDGE_TYPE_SHIFT) &
I40E_AQ_LLDP_BRIDGE_TYPE_MASK);
desc.datalen = cpu_to_le16(buff_size);
desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_BUF);
if (buff_size > I40E_AQ_LARGE_BUF)
desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_LB);
status = i40e_asq_send_command(hw, &desc, buff, buff_size, cmd_details);
if (!status) {
if (local_len != NULL)
*local_len = le16_to_cpu(resp->local_len);
if (remote_len != NULL)
*remote_len = le16_to_cpu(resp->remote_len);
}
return status;
}
/**
* i40e_aq_cfg_lldp_mib_change_event
* @hw: pointer to the hw struct
* @enable_update: Enable or Disable event posting
* @cmd_details: pointer to command details structure or NULL
*
* Enable or Disable posting of an event on ARQ when LLDP MIB
* associated with the interface changes
**/
i40e_status i40e_aq_cfg_lldp_mib_change_event(struct i40e_hw *hw,
bool enable_update,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_lldp_update_mib *cmd =
(struct i40e_aqc_lldp_update_mib *)&desc.params.raw;
i40e_status status;
i40e_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_lldp_update_mib);
if (!enable_update)
cmd->command |= I40E_AQ_LLDP_MIB_UPDATE_DISABLE;
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
return status;
}
/**
* i40e_aq_stop_lldp
* @hw: pointer to the hw struct
* @shutdown_agent: True if LLDP Agent needs to be Shutdown
* @cmd_details: pointer to command details structure or NULL
*
* Stop or Shutdown the embedded LLDP Agent
**/
i40e_status i40e_aq_stop_lldp(struct i40e_hw *hw, bool shutdown_agent,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_lldp_stop *cmd =
(struct i40e_aqc_lldp_stop *)&desc.params.raw;
i40e_status status;
i40e_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_lldp_stop);
if (shutdown_agent)
cmd->command |= I40E_AQ_LLDP_AGENT_SHUTDOWN;
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
return status;
}
/**
* i40e_aq_start_lldp
* @hw: pointer to the hw struct
* @cmd_details: pointer to command details structure or NULL
*
* Start the embedded LLDP Agent on all ports.
**/
i40e_status i40e_aq_start_lldp(struct i40e_hw *hw,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_lldp_start *cmd =
(struct i40e_aqc_lldp_start *)&desc.params.raw;
i40e_status status;
i40e_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_lldp_start);
cmd->command = I40E_AQ_LLDP_AGENT_START;
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
return status;
}
/**
* i40e_aq_add_udp_tunnel
* @hw: pointer to the hw struct
* @udp_port: the UDP port to add
* @header_len: length of the tunneling header length in DWords
* @protocol_index: protocol index type
* @filter_index: pointer to filter index
* @cmd_details: pointer to command details structure or NULL
**/
i40e_status i40e_aq_add_udp_tunnel(struct i40e_hw *hw,
u16 udp_port, u8 header_len,
u8 protocol_index, u8 *filter_index,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_add_udp_tunnel *cmd =
(struct i40e_aqc_add_udp_tunnel *)&desc.params.raw;
struct i40e_aqc_del_udp_tunnel_completion *resp =
(struct i40e_aqc_del_udp_tunnel_completion *)&desc.params.raw;
i40e_status status;
i40e_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_add_udp_tunnel);
cmd->udp_port = cpu_to_le16(udp_port);
cmd->protocol_type = protocol_index;
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
if (!status)
*filter_index = resp->index;
return status;
}
/**
* i40e_aq_del_udp_tunnel
* @hw: pointer to the hw struct
* @index: filter index
* @cmd_details: pointer to command details structure or NULL
**/
i40e_status i40e_aq_del_udp_tunnel(struct i40e_hw *hw, u8 index,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_remove_udp_tunnel *cmd =
(struct i40e_aqc_remove_udp_tunnel *)&desc.params.raw;
i40e_status status;
i40e_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_del_udp_tunnel);
cmd->index = index;
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
return status;
}
/**
* i40e_aq_delete_element - Delete switch element
* @hw: pointer to the hw struct
* @seid: the SEID to delete from the switch
* @cmd_details: pointer to command details structure or NULL
*
* This deletes a switch element from the switch.
**/
i40e_status i40e_aq_delete_element(struct i40e_hw *hw, u16 seid,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_switch_seid *cmd =
(struct i40e_aqc_switch_seid *)&desc.params.raw;
i40e_status status;
if (seid == 0)
return I40E_ERR_PARAM;
i40e_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_delete_element);
cmd->seid = cpu_to_le16(seid);
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
return status;
}
/**
* i40e_aq_dcb_updated - DCB Updated Command
* @hw: pointer to the hw struct
* @cmd_details: pointer to command details structure or NULL
*
* EMP will return when the shared RPB settings have been
* recomputed and modified. The retval field in the descriptor
* will be set to 0 when RPB is modified.
**/
i40e_status i40e_aq_dcb_updated(struct i40e_hw *hw,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
i40e_status status;
i40e_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_dcb_updated);
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
return status;
}
/**
* i40e_aq_tx_sched_cmd - generic Tx scheduler AQ command handler
* @hw: pointer to the hw struct
* @seid: seid for the physical port/switching component/vsi
* @buff: Indirect buffer to hold data parameters and response
* @buff_size: Indirect buffer size
* @opcode: Tx scheduler AQ command opcode
* @cmd_details: pointer to command details structure or NULL
*
* Generic command handler for Tx scheduler AQ commands
**/
static i40e_status i40e_aq_tx_sched_cmd(struct i40e_hw *hw, u16 seid,
void *buff, u16 buff_size,
enum i40e_admin_queue_opc opcode,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_tx_sched_ind *cmd =
(struct i40e_aqc_tx_sched_ind *)&desc.params.raw;
i40e_status status;
bool cmd_param_flag = false;
switch (opcode) {
case i40e_aqc_opc_configure_vsi_ets_sla_bw_limit:
case i40e_aqc_opc_configure_vsi_tc_bw:
case i40e_aqc_opc_enable_switching_comp_ets:
case i40e_aqc_opc_modify_switching_comp_ets:
case i40e_aqc_opc_disable_switching_comp_ets:
case i40e_aqc_opc_configure_switching_comp_ets_bw_limit:
case i40e_aqc_opc_configure_switching_comp_bw_config:
cmd_param_flag = true;
break;
case i40e_aqc_opc_query_vsi_bw_config:
case i40e_aqc_opc_query_vsi_ets_sla_config:
case i40e_aqc_opc_query_switching_comp_ets_config:
case i40e_aqc_opc_query_port_ets_config:
case i40e_aqc_opc_query_switching_comp_bw_config:
cmd_param_flag = false;
break;
default:
return I40E_ERR_PARAM;
}
i40e_fill_default_direct_cmd_desc(&desc, opcode);
/* Indirect command */
desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_BUF);
if (cmd_param_flag)
desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_RD);
if (buff_size > I40E_AQ_LARGE_BUF)
desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_LB);
desc.datalen = cpu_to_le16(buff_size);
cmd->vsi_seid = cpu_to_le16(seid);
status = i40e_asq_send_command(hw, &desc, buff, buff_size, cmd_details);
return status;
}
/**
* i40e_aq_config_vsi_tc_bw - Config VSI BW Allocation per TC
* @hw: pointer to the hw struct
* @seid: VSI seid
* @bw_data: Buffer holding enabled TCs, relative TC BW limit/credits
* @cmd_details: pointer to command details structure or NULL
**/
i40e_status i40e_aq_config_vsi_tc_bw(struct i40e_hw *hw,
u16 seid,
struct i40e_aqc_configure_vsi_tc_bw_data *bw_data,
struct i40e_asq_cmd_details *cmd_details)
{
return i40e_aq_tx_sched_cmd(hw, seid, (void *)bw_data, sizeof(*bw_data),
i40e_aqc_opc_configure_vsi_tc_bw,
cmd_details);
}
/**
* i40e_aq_config_switch_comp_ets - Enable/Disable/Modify ETS on the port
* @hw: pointer to the hw struct
* @seid: seid of the switching component connected to Physical Port
* @ets_data: Buffer holding ETS parameters
* @cmd_details: pointer to command details structure or NULL
**/
i40e_status i40e_aq_config_switch_comp_ets(struct i40e_hw *hw,
u16 seid,
struct i40e_aqc_configure_switching_comp_ets_data *ets_data,
enum i40e_admin_queue_opc opcode,
struct i40e_asq_cmd_details *cmd_details)
{
return i40e_aq_tx_sched_cmd(hw, seid, (void *)ets_data,
sizeof(*ets_data), opcode, cmd_details);
}
/**
* i40e_aq_config_switch_comp_bw_config - Config Switch comp BW Alloc per TC
* @hw: pointer to the hw struct
* @seid: seid of the switching component
* @bw_data: Buffer holding enabled TCs, relative/absolute TC BW limit/credits
* @cmd_details: pointer to command details structure or NULL
**/
i40e_status i40e_aq_config_switch_comp_bw_config(struct i40e_hw *hw,
u16 seid,
struct i40e_aqc_configure_switching_comp_bw_config_data *bw_data,
struct i40e_asq_cmd_details *cmd_details)
{
return i40e_aq_tx_sched_cmd(hw, seid, (void *)bw_data, sizeof(*bw_data),
i40e_aqc_opc_configure_switching_comp_bw_config,
cmd_details);
}
/**
* i40e_aq_query_vsi_bw_config - Query VSI BW configuration
* @hw: pointer to the hw struct
* @seid: seid of the VSI
* @bw_data: Buffer to hold VSI BW configuration
* @cmd_details: pointer to command details structure or NULL
**/
i40e_status i40e_aq_query_vsi_bw_config(struct i40e_hw *hw,
u16 seid,
struct i40e_aqc_query_vsi_bw_config_resp *bw_data,
struct i40e_asq_cmd_details *cmd_details)
{
return i40e_aq_tx_sched_cmd(hw, seid, (void *)bw_data, sizeof(*bw_data),
i40e_aqc_opc_query_vsi_bw_config,
cmd_details);
}
/**
* i40e_aq_query_vsi_ets_sla_config - Query VSI BW configuration per TC
* @hw: pointer to the hw struct
* @seid: seid of the VSI
* @bw_data: Buffer to hold VSI BW configuration per TC
* @cmd_details: pointer to command details structure or NULL
**/
i40e_status i40e_aq_query_vsi_ets_sla_config(struct i40e_hw *hw,
u16 seid,
struct i40e_aqc_query_vsi_ets_sla_config_resp *bw_data,
struct i40e_asq_cmd_details *cmd_details)
{
return i40e_aq_tx_sched_cmd(hw, seid, (void *)bw_data, sizeof(*bw_data),
i40e_aqc_opc_query_vsi_ets_sla_config,
cmd_details);
}
/**
* i40e_aq_query_switch_comp_ets_config - Query Switch comp BW config per TC
* @hw: pointer to the hw struct
* @seid: seid of the switching component
* @bw_data: Buffer to hold switching component's per TC BW config
* @cmd_details: pointer to command details structure or NULL
**/
i40e_status i40e_aq_query_switch_comp_ets_config(struct i40e_hw *hw,
u16 seid,
struct i40e_aqc_query_switching_comp_ets_config_resp *bw_data,
struct i40e_asq_cmd_details *cmd_details)
{
return i40e_aq_tx_sched_cmd(hw, seid, (void *)bw_data, sizeof(*bw_data),
i40e_aqc_opc_query_switching_comp_ets_config,
cmd_details);
}
/**
* i40e_aq_query_port_ets_config - Query Physical Port ETS configuration
* @hw: pointer to the hw struct
* @seid: seid of the VSI or switching component connected to Physical Port
* @bw_data: Buffer to hold current ETS configuration for the Physical Port
* @cmd_details: pointer to command details structure or NULL
**/
i40e_status i40e_aq_query_port_ets_config(struct i40e_hw *hw,
u16 seid,
struct i40e_aqc_query_port_ets_config_resp *bw_data,
struct i40e_asq_cmd_details *cmd_details)
{
return i40e_aq_tx_sched_cmd(hw, seid, (void *)bw_data, sizeof(*bw_data),
i40e_aqc_opc_query_port_ets_config,
cmd_details);
}
/**
* i40e_aq_query_switch_comp_bw_config - Query Switch comp BW configuration
* @hw: pointer to the hw struct
* @seid: seid of the switching component
* @bw_data: Buffer to hold switching component's BW configuration
* @cmd_details: pointer to command details structure or NULL
**/
i40e_status i40e_aq_query_switch_comp_bw_config(struct i40e_hw *hw,
u16 seid,
struct i40e_aqc_query_switching_comp_bw_config_resp *bw_data,
struct i40e_asq_cmd_details *cmd_details)
{
return i40e_aq_tx_sched_cmd(hw, seid, (void *)bw_data, sizeof(*bw_data),
i40e_aqc_opc_query_switching_comp_bw_config,
cmd_details);
}
/**
* i40e_validate_filter_settings
* @hw: pointer to the hardware structure
* @settings: Filter control settings
*
* Check and validate the filter control settings passed.
* The function checks for the valid filter/context sizes being
* passed for FCoE and PE.
*
* Returns 0 if the values passed are valid and within
* range else returns an error.
**/
static i40e_status i40e_validate_filter_settings(struct i40e_hw *hw,
struct i40e_filter_control_settings *settings)
{
u32 fcoe_cntx_size, fcoe_filt_size;
u32 pe_cntx_size, pe_filt_size;
u32 fcoe_fmax, pe_fmax;
u32 val;
/* Validate FCoE settings passed */
switch (settings->fcoe_filt_num) {
case I40E_HASH_FILTER_SIZE_1K:
case I40E_HASH_FILTER_SIZE_2K:
case I40E_HASH_FILTER_SIZE_4K:
case I40E_HASH_FILTER_SIZE_8K:
case I40E_HASH_FILTER_SIZE_16K:
case I40E_HASH_FILTER_SIZE_32K:
fcoe_filt_size = I40E_HASH_FILTER_BASE_SIZE;
fcoe_filt_size <<= (u32)settings->fcoe_filt_num;
break;
default:
return I40E_ERR_PARAM;
}
switch (settings->fcoe_cntx_num) {
case I40E_DMA_CNTX_SIZE_512:
case I40E_DMA_CNTX_SIZE_1K:
case I40E_DMA_CNTX_SIZE_2K:
case I40E_DMA_CNTX_SIZE_4K:
fcoe_cntx_size = I40E_DMA_CNTX_BASE_SIZE;
fcoe_cntx_size <<= (u32)settings->fcoe_cntx_num;
break;
default:
return I40E_ERR_PARAM;
}
/* Validate PE settings passed */
switch (settings->pe_filt_num) {
case I40E_HASH_FILTER_SIZE_1K:
case I40E_HASH_FILTER_SIZE_2K:
case I40E_HASH_FILTER_SIZE_4K:
case I40E_HASH_FILTER_SIZE_8K:
case I40E_HASH_FILTER_SIZE_16K:
case I40E_HASH_FILTER_SIZE_32K:
case I40E_HASH_FILTER_SIZE_64K:
case I40E_HASH_FILTER_SIZE_128K:
case I40E_HASH_FILTER_SIZE_256K:
case I40E_HASH_FILTER_SIZE_512K:
case I40E_HASH_FILTER_SIZE_1M:
pe_filt_size = I40E_HASH_FILTER_BASE_SIZE;
pe_filt_size <<= (u32)settings->pe_filt_num;
break;
default:
return I40E_ERR_PARAM;
}
switch (settings->pe_cntx_num) {
case I40E_DMA_CNTX_SIZE_512:
case I40E_DMA_CNTX_SIZE_1K:
case I40E_DMA_CNTX_SIZE_2K:
case I40E_DMA_CNTX_SIZE_4K:
case I40E_DMA_CNTX_SIZE_8K:
case I40E_DMA_CNTX_SIZE_16K:
case I40E_DMA_CNTX_SIZE_32K:
case I40E_DMA_CNTX_SIZE_64K:
case I40E_DMA_CNTX_SIZE_128K:
case I40E_DMA_CNTX_SIZE_256K:
pe_cntx_size = I40E_DMA_CNTX_BASE_SIZE;
pe_cntx_size <<= (u32)settings->pe_cntx_num;
break;
default:
return I40E_ERR_PARAM;
}
/* FCHSIZE + FCDSIZE should not be greater than PMFCOEFMAX */
val = rd32(hw, I40E_GLHMC_FCOEFMAX);
fcoe_fmax = (val & I40E_GLHMC_FCOEFMAX_PMFCOEFMAX_MASK)
>> I40E_GLHMC_FCOEFMAX_PMFCOEFMAX_SHIFT;
if (fcoe_filt_size + fcoe_cntx_size > fcoe_fmax)
return I40E_ERR_INVALID_SIZE;
/* PEHSIZE + PEDSIZE should not be greater than PMPEXFMAX */
val = rd32(hw, I40E_GLHMC_PEXFMAX);
pe_fmax = (val & I40E_GLHMC_PEXFMAX_PMPEXFMAX_MASK)
>> I40E_GLHMC_PEXFMAX_PMPEXFMAX_SHIFT;
if (pe_filt_size + pe_cntx_size > pe_fmax)
return I40E_ERR_INVALID_SIZE;
return 0;
}
/**
* i40e_set_filter_control
* @hw: pointer to the hardware structure
* @settings: Filter control settings
*
* Set the Queue Filters for PE/FCoE and enable filters required
* for a single PF. It is expected that these settings are programmed
* at the driver initialization time.
**/
i40e_status i40e_set_filter_control(struct i40e_hw *hw,
struct i40e_filter_control_settings *settings)
{
i40e_status ret = 0;
u32 hash_lut_size = 0;
u32 val;
if (!settings)
return I40E_ERR_PARAM;
/* Validate the input settings */
ret = i40e_validate_filter_settings(hw, settings);
if (ret)
return ret;
/* Read the PF Queue Filter control register */
val = rd32(hw, I40E_PFQF_CTL_0);
/* Program required PE hash buckets for the PF */
val &= ~I40E_PFQF_CTL_0_PEHSIZE_MASK;
val |= ((u32)settings->pe_filt_num << I40E_PFQF_CTL_0_PEHSIZE_SHIFT) &
I40E_PFQF_CTL_0_PEHSIZE_MASK;
/* Program required PE contexts for the PF */
val &= ~I40E_PFQF_CTL_0_PEDSIZE_MASK;
val |= ((u32)settings->pe_cntx_num << I40E_PFQF_CTL_0_PEDSIZE_SHIFT) &
I40E_PFQF_CTL_0_PEDSIZE_MASK;
/* Program required FCoE hash buckets for the PF */
val &= ~I40E_PFQF_CTL_0_PFFCHSIZE_MASK;
val |= ((u32)settings->fcoe_filt_num <<
I40E_PFQF_CTL_0_PFFCHSIZE_SHIFT) &
I40E_PFQF_CTL_0_PFFCHSIZE_MASK;
/* Program required FCoE DDP contexts for the PF */
val &= ~I40E_PFQF_CTL_0_PFFCDSIZE_MASK;
val |= ((u32)settings->fcoe_cntx_num <<
I40E_PFQF_CTL_0_PFFCDSIZE_SHIFT) &
I40E_PFQF_CTL_0_PFFCDSIZE_MASK;
/* Program Hash LUT size for the PF */
val &= ~I40E_PFQF_CTL_0_HASHLUTSIZE_MASK;
if (settings->hash_lut_size == I40E_HASH_LUT_SIZE_512)
hash_lut_size = 1;
val |= (hash_lut_size << I40E_PFQF_CTL_0_HASHLUTSIZE_SHIFT) &
I40E_PFQF_CTL_0_HASHLUTSIZE_MASK;
/* Enable FDIR, Ethertype and MACVLAN filters for PF and VFs */
if (settings->enable_fdir)
val |= I40E_PFQF_CTL_0_FD_ENA_MASK;
if (settings->enable_ethtype)
val |= I40E_PFQF_CTL_0_ETYPE_ENA_MASK;
if (settings->enable_macvlan)
val |= I40E_PFQF_CTL_0_MACVLAN_ENA_MASK;
wr32(hw, I40E_PFQF_CTL_0, val);
return 0;
}
/**
* i40e_aq_add_rem_control_packet_filter - Add or Remove Control Packet Filter
* @hw: pointer to the hw struct
* @mac_addr: MAC address to use in the filter
* @ethtype: Ethertype to use in the filter
* @flags: Flags that needs to be applied to the filter
* @vsi_seid: seid of the control VSI
* @queue: VSI queue number to send the packet to
* @is_add: Add control packet filter if True else remove
* @stats: Structure to hold information on control filter counts
* @cmd_details: pointer to command details structure or NULL
*
* This command will Add or Remove control packet filter for a control VSI.
* In return it will update the total number of perfect filter count in
* the stats member.
**/
i40e_status i40e_aq_add_rem_control_packet_filter(struct i40e_hw *hw,
u8 *mac_addr, u16 ethtype, u16 flags,
u16 vsi_seid, u16 queue, bool is_add,
struct i40e_control_filter_stats *stats,
struct i40e_asq_cmd_details *cmd_details)
{
struct i40e_aq_desc desc;
struct i40e_aqc_add_remove_control_packet_filter *cmd =
(struct i40e_aqc_add_remove_control_packet_filter *)
&desc.params.raw;
struct i40e_aqc_add_remove_control_packet_filter_completion *resp =
(struct i40e_aqc_add_remove_control_packet_filter_completion *)
&desc.params.raw;
i40e_status status;
if (vsi_seid == 0)
return I40E_ERR_PARAM;
if (is_add) {
i40e_fill_default_direct_cmd_desc(&desc,
i40e_aqc_opc_add_control_packet_filter);
cmd->queue = cpu_to_le16(queue);
} else {
i40e_fill_default_direct_cmd_desc(&desc,
i40e_aqc_opc_remove_control_packet_filter);
}
if (mac_addr)
memcpy(cmd->mac, mac_addr, ETH_ALEN);
cmd->etype = cpu_to_le16(ethtype);
cmd->flags = cpu_to_le16(flags);
cmd->seid = cpu_to_le16(vsi_seid);
status = i40e_asq_send_command(hw, &desc, NULL, 0, cmd_details);
if (!status && stats) {
stats->mac_etype_used = le16_to_cpu(resp->mac_etype_used);
stats->etype_used = le16_to_cpu(resp->etype_used);
stats->mac_etype_free = le16_to_cpu(resp->mac_etype_free);
stats->etype_free = le16_to_cpu(resp->etype_free);
}
return status;
}
/**
* i40e_set_pci_config_data - store PCI bus info
* @hw: pointer to hardware structure
* @link_status: the link status word from PCI config space
*
* Stores the PCI bus info (speed, width, type) within the i40e_hw structure
**/
void i40e_set_pci_config_data(struct i40e_hw *hw, u16 link_status)
{
hw->bus.type = i40e_bus_type_pci_express;
switch (link_status & PCI_EXP_LNKSTA_NLW) {
case PCI_EXP_LNKSTA_NLW_X1:
hw->bus.width = i40e_bus_width_pcie_x1;
break;
case PCI_EXP_LNKSTA_NLW_X2:
hw->bus.width = i40e_bus_width_pcie_x2;
break;
case PCI_EXP_LNKSTA_NLW_X4:
hw->bus.width = i40e_bus_width_pcie_x4;
break;
case PCI_EXP_LNKSTA_NLW_X8:
hw->bus.width = i40e_bus_width_pcie_x8;
break;
default:
hw->bus.width = i40e_bus_width_unknown;
break;
}
switch (link_status & PCI_EXP_LNKSTA_CLS) {
case PCI_EXP_LNKSTA_CLS_2_5GB:
hw->bus.speed = i40e_bus_speed_2500;
break;
case PCI_EXP_LNKSTA_CLS_5_0GB:
hw->bus.speed = i40e_bus_speed_5000;
break;
case PCI_EXP_LNKSTA_CLS_8_0GB:
hw->bus.speed = i40e_bus_speed_8000;
break;
default:
hw->bus.speed = i40e_bus_speed_unknown;
break;
}
}
| gpl-2.0 |
Rastrian/ElunaTrinityWotlk | dep/g3dlite/source/Vector2.cpp | 254 | 5439 | /**
@file Vector2.cpp
2D vector class, used for texture coordinates primarily.
@maintainer Morgan McGuire, http://graphics.cs.williams.edu
@cite Portions based on Dave Eberly'x Magic Software Library
at http://www.magic-software.com
@created 2001-06-02
@edited 2010-11-16
*/
#include "G3D/platform.h"
#include <stdlib.h>
#include "G3D/Vector2.h"
#include "G3D/Vector2int32.h"
#include "G3D/g3dmath.h"
#include "G3D/format.h"
#include "G3D/BinaryInput.h"
#include "G3D/BinaryOutput.h"
#include "G3D/TextInput.h"
#include "G3D/TextOutput.h"
#include "G3D/Any.h"
namespace G3D {
Vector2::Vector2(const Vector2int32& other) : x((float)other.x), y((float)other.y) {
}
Vector2::Vector2(const Any& any) {
any.verifyName("Vector2", "Point2");
any.verifyType(Any::TABLE, Any::ARRAY);
any.verifySize(2);
if (any.type() == Any::ARRAY) {
x = any[0];
y = any[1];
} else {
// Table
x = any["x"];
y = any["y"];
}
}
Vector2& Vector2::operator=(const Any& a) {
*this = Vector2(a);
return *this;
}
Any Vector2::toAny() const {
Any any(Any::ARRAY, "Vector2");
any.append(x, y);
return any;
}
const Vector2& Vector2::one() {
static const Vector2 v(1, 1); return v;
}
const Vector2& Vector2::zero() {
static Vector2 v(0, 0);
return v;
}
const Vector2& Vector2::unitX() {
static Vector2 v(1, 0);
return v;
}
const Vector2& Vector2::unitY() {
static Vector2 v(0, 1);
return v;
}
const Vector2& Vector2::inf() {
static Vector2 v(G3D::finf(), G3D::finf());
return v;
}
const Vector2& Vector2::nan() {
static Vector2 v(G3D::fnan(), G3D::fnan());
return v;
}
const Vector2& Vector2::minFinite() {
static Vector2 v(-FLT_MAX, -FLT_MAX);
return v;
}
const Vector2& Vector2::maxFinite() {
static Vector2 v(FLT_MAX, FLT_MAX);
return v;
}
size_t Vector2::hashCode() const {
unsigned int xhash = (*(int*)(void*)(&x));
unsigned int yhash = (*(int*)(void*)(&y));
return xhash + (yhash * 37);
}
Vector2::Vector2(BinaryInput& b) {
deserialize(b);
}
void Vector2::deserialize(BinaryInput& b) {
x = b.readFloat32();
y = b.readFloat32();
}
void Vector2::serialize(BinaryOutput& b) const {
b.writeFloat32(x);
b.writeFloat32(y);
}
void Vector2::deserialize(TextInput& t) {
t.readSymbol("(");
x = (float)t.readNumber();
t.readSymbol(",");
y = (float)t.readNumber();
t.readSymbol(")");
}
void Vector2::serialize(TextOutput& t) const {
t.writeSymbol("(");
t.writeNumber(x);
t.writeSymbol(",");
t.writeNumber(y);
t.writeSymbol(")");
}
//----------------------------------------------------------------------------
Vector2 Vector2::random(G3D::Random& r) {
Vector2 result;
do {
result = Vector2(r.uniform(-1, 1), r.uniform(-1, 1));
} while (result.squaredLength() >= 1.0f);
return result.direction();
}
Vector2 Vector2::operator/ (float k) const {
return *this * (1.0f / k);
}
Vector2& Vector2::operator/= (float k) {
this->x /= k;
this->y /= k;
return *this;
}
//----------------------------------------------------------------------------
std::string Vector2::toString() const {
return G3D::format("(%g, %g)", x, y);
}
// 2-char swizzles
Vector2 Vector2::xx() const { return Vector2 (x, x); }
Vector2 Vector2::yx() const { return Vector2 (y, x); }
Vector2 Vector2::xy() const { return Vector2 (x, y); }
Vector2 Vector2::yy() const { return Vector2 (y, y); }
// 3-char swizzles
Vector3 Vector2::xxx() const { return Vector3 (x, x, x); }
Vector3 Vector2::yxx() const { return Vector3 (y, x, x); }
Vector3 Vector2::xyx() const { return Vector3 (x, y, x); }
Vector3 Vector2::yyx() const { return Vector3 (y, y, x); }
Vector3 Vector2::xxy() const { return Vector3 (x, x, y); }
Vector3 Vector2::yxy() const { return Vector3 (y, x, y); }
Vector3 Vector2::xyy() const { return Vector3 (x, y, y); }
Vector3 Vector2::yyy() const { return Vector3 (y, y, y); }
// 4-char swizzles
Vector4 Vector2::xxxx() const { return Vector4 (x, x, x, x); }
Vector4 Vector2::yxxx() const { return Vector4 (y, x, x, x); }
Vector4 Vector2::xyxx() const { return Vector4 (x, y, x, x); }
Vector4 Vector2::yyxx() const { return Vector4 (y, y, x, x); }
Vector4 Vector2::xxyx() const { return Vector4 (x, x, y, x); }
Vector4 Vector2::yxyx() const { return Vector4 (y, x, y, x); }
Vector4 Vector2::xyyx() const { return Vector4 (x, y, y, x); }
Vector4 Vector2::yyyx() const { return Vector4 (y, y, y, x); }
Vector4 Vector2::xxxy() const { return Vector4 (x, x, x, y); }
Vector4 Vector2::yxxy() const { return Vector4 (y, x, x, y); }
Vector4 Vector2::xyxy() const { return Vector4 (x, y, x, y); }
Vector4 Vector2::yyxy() const { return Vector4 (y, y, x, y); }
Vector4 Vector2::xxyy() const { return Vector4 (x, x, y, y); }
Vector4 Vector2::yxyy() const { return Vector4 (y, x, y, y); }
Vector4 Vector2::xyyy() const { return Vector4 (x, y, y, y); }
Vector4 Vector2::yyyy() const { return Vector4 (y, y, y, y); }
void serialize(const Vector2& v, class BinaryOutput& b) {
v.serialize(b);
}
void deserialize(Vector2& v, class BinaryInput& b) {
v.deserialize(b);
}
} // namespace
| gpl-2.0 |
akuster/linux-yocto-3.14 | tools/vm/page-types.c | 254 | 22191 | /*
* page-types: Tool for querying page flags
*
* 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; version 2.
*
* 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 find a copy of v2 of the GNU General Public License somewhere on
* your Linux system; if not, write to the Free Software Foundation, Inc., 59
* Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*
* Copyright (C) 2009 Intel corporation
*
* Authors: Wu Fengguang <fengguang.wu@intel.com>
*/
#define _LARGEFILE64_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>
#include <getopt.h>
#include <limits.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/errno.h>
#include <sys/fcntl.h>
#include <sys/mount.h>
#include <sys/statfs.h>
#include "../../include/uapi/linux/magic.h"
#include "../../include/uapi/linux/kernel-page-flags.h"
#include <api/fs/debugfs.h>
#ifndef MAX_PATH
# define MAX_PATH 256
#endif
#ifndef STR
# define _STR(x) #x
# define STR(x) _STR(x)
#endif
/*
* pagemap kernel ABI bits
*/
#define PM_ENTRY_BYTES sizeof(uint64_t)
#define PM_STATUS_BITS 3
#define PM_STATUS_OFFSET (64 - PM_STATUS_BITS)
#define PM_STATUS_MASK (((1LL << PM_STATUS_BITS) - 1) << PM_STATUS_OFFSET)
#define PM_STATUS(nr) (((nr) << PM_STATUS_OFFSET) & PM_STATUS_MASK)
#define PM_PSHIFT_BITS 6
#define PM_PSHIFT_OFFSET (PM_STATUS_OFFSET - PM_PSHIFT_BITS)
#define PM_PSHIFT_MASK (((1LL << PM_PSHIFT_BITS) - 1) << PM_PSHIFT_OFFSET)
#define __PM_PSHIFT(x) (((uint64_t) (x) << PM_PSHIFT_OFFSET) & PM_PSHIFT_MASK)
#define PM_PFRAME_MASK ((1LL << PM_PSHIFT_OFFSET) - 1)
#define PM_PFRAME(x) ((x) & PM_PFRAME_MASK)
#define __PM_SOFT_DIRTY (1LL)
#define PM_PRESENT PM_STATUS(4LL)
#define PM_SWAP PM_STATUS(2LL)
#define PM_SOFT_DIRTY __PM_PSHIFT(__PM_SOFT_DIRTY)
/*
* kernel page flags
*/
#define KPF_BYTES 8
#define PROC_KPAGEFLAGS "/proc/kpageflags"
/* [32-] kernel hacking assistances */
#define KPF_RESERVED 32
#define KPF_MLOCKED 33
#define KPF_MAPPEDTODISK 34
#define KPF_PRIVATE 35
#define KPF_PRIVATE_2 36
#define KPF_OWNER_PRIVATE 37
#define KPF_ARCH 38
#define KPF_UNCACHED 39
#define KPF_SOFTDIRTY 40
/* [48-] take some arbitrary free slots for expanding overloaded flags
* not part of kernel API
*/
#define KPF_READAHEAD 48
#define KPF_SLOB_FREE 49
#define KPF_SLUB_FROZEN 50
#define KPF_SLUB_DEBUG 51
#define KPF_ALL_BITS ((uint64_t)~0ULL)
#define KPF_HACKERS_BITS (0xffffULL << 32)
#define KPF_OVERLOADED_BITS (0xffffULL << 48)
#define BIT(name) (1ULL << KPF_##name)
#define BITS_COMPOUND (BIT(COMPOUND_HEAD) | BIT(COMPOUND_TAIL))
static const char * const page_flag_names[] = {
[KPF_LOCKED] = "L:locked",
[KPF_ERROR] = "E:error",
[KPF_REFERENCED] = "R:referenced",
[KPF_UPTODATE] = "U:uptodate",
[KPF_DIRTY] = "D:dirty",
[KPF_LRU] = "l:lru",
[KPF_ACTIVE] = "A:active",
[KPF_SLAB] = "S:slab",
[KPF_WRITEBACK] = "W:writeback",
[KPF_RECLAIM] = "I:reclaim",
[KPF_BUDDY] = "B:buddy",
[KPF_MMAP] = "M:mmap",
[KPF_ANON] = "a:anonymous",
[KPF_SWAPCACHE] = "s:swapcache",
[KPF_SWAPBACKED] = "b:swapbacked",
[KPF_COMPOUND_HEAD] = "H:compound_head",
[KPF_COMPOUND_TAIL] = "T:compound_tail",
[KPF_HUGE] = "G:huge",
[KPF_UNEVICTABLE] = "u:unevictable",
[KPF_HWPOISON] = "X:hwpoison",
[KPF_NOPAGE] = "n:nopage",
[KPF_KSM] = "x:ksm",
[KPF_THP] = "t:thp",
[KPF_RESERVED] = "r:reserved",
[KPF_MLOCKED] = "m:mlocked",
[KPF_MAPPEDTODISK] = "d:mappedtodisk",
[KPF_PRIVATE] = "P:private",
[KPF_PRIVATE_2] = "p:private_2",
[KPF_OWNER_PRIVATE] = "O:owner_private",
[KPF_ARCH] = "h:arch",
[KPF_UNCACHED] = "c:uncached",
[KPF_SOFTDIRTY] = "f:softdirty",
[KPF_READAHEAD] = "I:readahead",
[KPF_SLOB_FREE] = "P:slob_free",
[KPF_SLUB_FROZEN] = "A:slub_frozen",
[KPF_SLUB_DEBUG] = "E:slub_debug",
};
static const char * const debugfs_known_mountpoints[] = {
"/sys/kernel/debug",
"/debug",
0,
};
/*
* data structures
*/
static int opt_raw; /* for kernel developers */
static int opt_list; /* list pages (in ranges) */
static int opt_no_summary; /* don't show summary */
static pid_t opt_pid; /* process to walk */
#define MAX_ADDR_RANGES 1024
static int nr_addr_ranges;
static unsigned long opt_offset[MAX_ADDR_RANGES];
static unsigned long opt_size[MAX_ADDR_RANGES];
#define MAX_VMAS 10240
static int nr_vmas;
static unsigned long pg_start[MAX_VMAS];
static unsigned long pg_end[MAX_VMAS];
#define MAX_BIT_FILTERS 64
static int nr_bit_filters;
static uint64_t opt_mask[MAX_BIT_FILTERS];
static uint64_t opt_bits[MAX_BIT_FILTERS];
static int page_size;
static int pagemap_fd;
static int kpageflags_fd;
static int opt_hwpoison;
static int opt_unpoison;
static char *hwpoison_debug_fs;
static int hwpoison_inject_fd;
static int hwpoison_forget_fd;
#define HASH_SHIFT 13
#define HASH_SIZE (1 << HASH_SHIFT)
#define HASH_MASK (HASH_SIZE - 1)
#define HASH_KEY(flags) (flags & HASH_MASK)
static unsigned long total_pages;
static unsigned long nr_pages[HASH_SIZE];
static uint64_t page_flags[HASH_SIZE];
/*
* helper functions
*/
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
#define min_t(type, x, y) ({ \
type __min1 = (x); \
type __min2 = (y); \
__min1 < __min2 ? __min1 : __min2; })
#define max_t(type, x, y) ({ \
type __max1 = (x); \
type __max2 = (y); \
__max1 > __max2 ? __max1 : __max2; })
static unsigned long pages2mb(unsigned long pages)
{
return (pages * page_size) >> 20;
}
static void fatal(const char *x, ...)
{
va_list ap;
va_start(ap, x);
vfprintf(stderr, x, ap);
va_end(ap);
exit(EXIT_FAILURE);
}
static int checked_open(const char *pathname, int flags)
{
int fd = open(pathname, flags);
if (fd < 0) {
perror(pathname);
exit(EXIT_FAILURE);
}
return fd;
}
/*
* pagemap/kpageflags routines
*/
static unsigned long do_u64_read(int fd, char *name,
uint64_t *buf,
unsigned long index,
unsigned long count)
{
long bytes;
if (index > ULONG_MAX / 8)
fatal("index overflow: %lu\n", index);
if (lseek(fd, index * 8, SEEK_SET) < 0) {
perror(name);
exit(EXIT_FAILURE);
}
bytes = read(fd, buf, count * 8);
if (bytes < 0) {
perror(name);
exit(EXIT_FAILURE);
}
if (bytes % 8)
fatal("partial read: %lu bytes\n", bytes);
return bytes / 8;
}
static unsigned long kpageflags_read(uint64_t *buf,
unsigned long index,
unsigned long pages)
{
return do_u64_read(kpageflags_fd, PROC_KPAGEFLAGS, buf, index, pages);
}
static unsigned long pagemap_read(uint64_t *buf,
unsigned long index,
unsigned long pages)
{
return do_u64_read(pagemap_fd, "/proc/pid/pagemap", buf, index, pages);
}
static unsigned long pagemap_pfn(uint64_t val)
{
unsigned long pfn;
if (val & PM_PRESENT)
pfn = PM_PFRAME(val);
else
pfn = 0;
return pfn;
}
/*
* page flag names
*/
static char *page_flag_name(uint64_t flags)
{
static char buf[65];
int present;
size_t i, j;
for (i = 0, j = 0; i < ARRAY_SIZE(page_flag_names); i++) {
present = (flags >> i) & 1;
if (!page_flag_names[i]) {
if (present)
fatal("unknown flag bit %d\n", i);
continue;
}
buf[j++] = present ? page_flag_names[i][0] : '_';
}
return buf;
}
static char *page_flag_longname(uint64_t flags)
{
static char buf[1024];
size_t i, n;
for (i = 0, n = 0; i < ARRAY_SIZE(page_flag_names); i++) {
if (!page_flag_names[i])
continue;
if ((flags >> i) & 1)
n += snprintf(buf + n, sizeof(buf) - n, "%s,",
page_flag_names[i] + 2);
}
if (n)
n--;
buf[n] = '\0';
return buf;
}
/*
* page list and summary
*/
static void show_page_range(unsigned long voffset,
unsigned long offset, uint64_t flags)
{
static uint64_t flags0;
static unsigned long voff;
static unsigned long index;
static unsigned long count;
if (flags == flags0 && offset == index + count &&
(!opt_pid || voffset == voff + count)) {
count++;
return;
}
if (count) {
if (opt_pid)
printf("%lx\t", voff);
printf("%lx\t%lx\t%s\n",
index, count, page_flag_name(flags0));
}
flags0 = flags;
index = offset;
voff = voffset;
count = 1;
}
static void show_page(unsigned long voffset,
unsigned long offset, uint64_t flags)
{
if (opt_pid)
printf("%lx\t", voffset);
printf("%lx\t%s\n", offset, page_flag_name(flags));
}
static void show_summary(void)
{
size_t i;
printf(" flags\tpage-count MB"
" symbolic-flags\t\t\tlong-symbolic-flags\n");
for (i = 0; i < ARRAY_SIZE(nr_pages); i++) {
if (nr_pages[i])
printf("0x%016llx\t%10lu %8lu %s\t%s\n",
(unsigned long long)page_flags[i],
nr_pages[i],
pages2mb(nr_pages[i]),
page_flag_name(page_flags[i]),
page_flag_longname(page_flags[i]));
}
printf(" total\t%10lu %8lu\n",
total_pages, pages2mb(total_pages));
}
/*
* page flag filters
*/
static int bit_mask_ok(uint64_t flags)
{
int i;
for (i = 0; i < nr_bit_filters; i++) {
if (opt_bits[i] == KPF_ALL_BITS) {
if ((flags & opt_mask[i]) == 0)
return 0;
} else {
if ((flags & opt_mask[i]) != opt_bits[i])
return 0;
}
}
return 1;
}
static uint64_t expand_overloaded_flags(uint64_t flags, uint64_t pme)
{
/* SLOB/SLUB overload several page flags */
if (flags & BIT(SLAB)) {
if (flags & BIT(PRIVATE))
flags ^= BIT(PRIVATE) | BIT(SLOB_FREE);
if (flags & BIT(ACTIVE))
flags ^= BIT(ACTIVE) | BIT(SLUB_FROZEN);
if (flags & BIT(ERROR))
flags ^= BIT(ERROR) | BIT(SLUB_DEBUG);
}
/* PG_reclaim is overloaded as PG_readahead in the read path */
if ((flags & (BIT(RECLAIM) | BIT(WRITEBACK))) == BIT(RECLAIM))
flags ^= BIT(RECLAIM) | BIT(READAHEAD);
if (pme & PM_SOFT_DIRTY)
flags |= BIT(SOFTDIRTY);
return flags;
}
static uint64_t well_known_flags(uint64_t flags)
{
/* hide flags intended only for kernel hacker */
flags &= ~KPF_HACKERS_BITS;
/* hide non-hugeTLB compound pages */
if ((flags & BITS_COMPOUND) && !(flags & BIT(HUGE)))
flags &= ~BITS_COMPOUND;
return flags;
}
static uint64_t kpageflags_flags(uint64_t flags, uint64_t pme)
{
if (opt_raw)
flags = expand_overloaded_flags(flags, pme);
else
flags = well_known_flags(flags);
return flags;
}
/*
* page actions
*/
static void prepare_hwpoison_fd(void)
{
char buf[MAX_PATH + 1];
hwpoison_debug_fs = debugfs_mount(NULL);
if (!hwpoison_debug_fs) {
perror("mount debugfs");
exit(EXIT_FAILURE);
}
if (opt_hwpoison && !hwpoison_inject_fd) {
snprintf(buf, MAX_PATH, "%s/hwpoison/corrupt-pfn",
hwpoison_debug_fs);
hwpoison_inject_fd = checked_open(buf, O_WRONLY);
}
if (opt_unpoison && !hwpoison_forget_fd) {
snprintf(buf, MAX_PATH, "%s/hwpoison/unpoison-pfn",
hwpoison_debug_fs);
hwpoison_forget_fd = checked_open(buf, O_WRONLY);
}
}
static int hwpoison_page(unsigned long offset)
{
char buf[100];
int len;
len = sprintf(buf, "0x%lx\n", offset);
len = write(hwpoison_inject_fd, buf, len);
if (len < 0) {
perror("hwpoison inject");
return len;
}
return 0;
}
static int unpoison_page(unsigned long offset)
{
char buf[100];
int len;
len = sprintf(buf, "0x%lx\n", offset);
len = write(hwpoison_forget_fd, buf, len);
if (len < 0) {
perror("hwpoison forget");
return len;
}
return 0;
}
/*
* page frame walker
*/
static size_t hash_slot(uint64_t flags)
{
size_t k = HASH_KEY(flags);
size_t i;
/* Explicitly reserve slot 0 for flags 0: the following logic
* cannot distinguish an unoccupied slot from slot (flags==0).
*/
if (flags == 0)
return 0;
/* search through the remaining (HASH_SIZE-1) slots */
for (i = 1; i < ARRAY_SIZE(page_flags); i++, k++) {
if (!k || k >= ARRAY_SIZE(page_flags))
k = 1;
if (page_flags[k] == 0) {
page_flags[k] = flags;
return k;
}
if (page_flags[k] == flags)
return k;
}
fatal("hash table full: bump up HASH_SHIFT?\n");
exit(EXIT_FAILURE);
}
static void add_page(unsigned long voffset,
unsigned long offset, uint64_t flags, uint64_t pme)
{
flags = kpageflags_flags(flags, pme);
if (!bit_mask_ok(flags))
return;
if (opt_hwpoison)
hwpoison_page(offset);
if (opt_unpoison)
unpoison_page(offset);
if (opt_list == 1)
show_page_range(voffset, offset, flags);
else if (opt_list == 2)
show_page(voffset, offset, flags);
nr_pages[hash_slot(flags)]++;
total_pages++;
}
#define KPAGEFLAGS_BATCH (64 << 10) /* 64k pages */
static void walk_pfn(unsigned long voffset,
unsigned long index,
unsigned long count,
uint64_t pme)
{
uint64_t buf[KPAGEFLAGS_BATCH];
unsigned long batch;
unsigned long pages;
unsigned long i;
while (count) {
batch = min_t(unsigned long, count, KPAGEFLAGS_BATCH);
pages = kpageflags_read(buf, index, batch);
if (pages == 0)
break;
for (i = 0; i < pages; i++)
add_page(voffset + i, index + i, buf[i], pme);
index += pages;
count -= pages;
}
}
#define PAGEMAP_BATCH (64 << 10)
static void walk_vma(unsigned long index, unsigned long count)
{
uint64_t buf[PAGEMAP_BATCH];
unsigned long batch;
unsigned long pages;
unsigned long pfn;
unsigned long i;
while (count) {
batch = min_t(unsigned long, count, PAGEMAP_BATCH);
pages = pagemap_read(buf, index, batch);
if (pages == 0)
break;
for (i = 0; i < pages; i++) {
pfn = pagemap_pfn(buf[i]);
if (pfn)
walk_pfn(index + i, pfn, 1, buf[i]);
}
index += pages;
count -= pages;
}
}
static void walk_task(unsigned long index, unsigned long count)
{
const unsigned long end = index + count;
unsigned long start;
int i = 0;
while (index < end) {
while (pg_end[i] <= index)
if (++i >= nr_vmas)
return;
if (pg_start[i] >= end)
return;
start = max_t(unsigned long, pg_start[i], index);
index = min_t(unsigned long, pg_end[i], end);
assert(start < index);
walk_vma(start, index - start);
}
}
static void add_addr_range(unsigned long offset, unsigned long size)
{
if (nr_addr_ranges >= MAX_ADDR_RANGES)
fatal("too many addr ranges\n");
opt_offset[nr_addr_ranges] = offset;
opt_size[nr_addr_ranges] = min_t(unsigned long, size, ULONG_MAX-offset);
nr_addr_ranges++;
}
static void walk_addr_ranges(void)
{
int i;
kpageflags_fd = checked_open(PROC_KPAGEFLAGS, O_RDONLY);
if (!nr_addr_ranges)
add_addr_range(0, ULONG_MAX);
for (i = 0; i < nr_addr_ranges; i++)
if (!opt_pid)
walk_pfn(0, opt_offset[i], opt_size[i], 0);
else
walk_task(opt_offset[i], opt_size[i]);
close(kpageflags_fd);
}
/*
* user interface
*/
static const char *page_flag_type(uint64_t flag)
{
if (flag & KPF_HACKERS_BITS)
return "(r)";
if (flag & KPF_OVERLOADED_BITS)
return "(o)";
return " ";
}
static void usage(void)
{
size_t i, j;
printf(
"page-types [options]\n"
" -r|--raw Raw mode, for kernel developers\n"
" -d|--describe flags Describe flags\n"
" -a|--addr addr-spec Walk a range of pages\n"
" -b|--bits bits-spec Walk pages with specified bits\n"
" -p|--pid pid Walk process address space\n"
#if 0 /* planned features */
" -f|--file filename Walk file address space\n"
#endif
" -l|--list Show page details in ranges\n"
" -L|--list-each Show page details one by one\n"
" -N|--no-summary Don't show summary info\n"
" -X|--hwpoison hwpoison pages\n"
" -x|--unpoison unpoison pages\n"
" -h|--help Show this usage message\n"
"flags:\n"
" 0x10 bitfield format, e.g.\n"
" anon bit-name, e.g.\n"
" 0x10,anon comma-separated list, e.g.\n"
"addr-spec:\n"
" N one page at offset N (unit: pages)\n"
" N+M pages range from N to N+M-1\n"
" N,M pages range from N to M-1\n"
" N, pages range from N to end\n"
" ,M pages range from 0 to M-1\n"
"bits-spec:\n"
" bit1,bit2 (flags & (bit1|bit2)) != 0\n"
" bit1,bit2=bit1 (flags & (bit1|bit2)) == bit1\n"
" bit1,~bit2 (flags & (bit1|bit2)) == bit1\n"
" =bit1,bit2 flags == (bit1|bit2)\n"
"bit-names:\n"
);
for (i = 0, j = 0; i < ARRAY_SIZE(page_flag_names); i++) {
if (!page_flag_names[i])
continue;
printf("%16s%s", page_flag_names[i] + 2,
page_flag_type(1ULL << i));
if (++j > 3) {
j = 0;
putchar('\n');
}
}
printf("\n "
"(r) raw mode bits (o) overloaded bits\n");
}
static unsigned long long parse_number(const char *str)
{
unsigned long long n;
n = strtoll(str, NULL, 0);
if (n == 0 && str[0] != '0')
fatal("invalid name or number: %s\n", str);
return n;
}
static void parse_pid(const char *str)
{
FILE *file;
char buf[5000];
opt_pid = parse_number(str);
sprintf(buf, "/proc/%d/pagemap", opt_pid);
pagemap_fd = checked_open(buf, O_RDONLY);
sprintf(buf, "/proc/%d/maps", opt_pid);
file = fopen(buf, "r");
if (!file) {
perror(buf);
exit(EXIT_FAILURE);
}
while (fgets(buf, sizeof(buf), file) != NULL) {
unsigned long vm_start;
unsigned long vm_end;
unsigned long long pgoff;
int major, minor;
char r, w, x, s;
unsigned long ino;
int n;
n = sscanf(buf, "%lx-%lx %c%c%c%c %llx %x:%x %lu",
&vm_start,
&vm_end,
&r, &w, &x, &s,
&pgoff,
&major, &minor,
&ino);
if (n < 10) {
fprintf(stderr, "unexpected line: %s\n", buf);
continue;
}
pg_start[nr_vmas] = vm_start / page_size;
pg_end[nr_vmas] = vm_end / page_size;
if (++nr_vmas >= MAX_VMAS) {
fprintf(stderr, "too many VMAs\n");
break;
}
}
fclose(file);
}
static void parse_file(const char *name)
{
}
static void parse_addr_range(const char *optarg)
{
unsigned long offset;
unsigned long size;
char *p;
p = strchr(optarg, ',');
if (!p)
p = strchr(optarg, '+');
if (p == optarg) {
offset = 0;
size = parse_number(p + 1);
} else if (p) {
offset = parse_number(optarg);
if (p[1] == '\0')
size = ULONG_MAX;
else {
size = parse_number(p + 1);
if (*p == ',') {
if (size < offset)
fatal("invalid range: %lu,%lu\n",
offset, size);
size -= offset;
}
}
} else {
offset = parse_number(optarg);
size = 1;
}
add_addr_range(offset, size);
}
static void add_bits_filter(uint64_t mask, uint64_t bits)
{
if (nr_bit_filters >= MAX_BIT_FILTERS)
fatal("too much bit filters\n");
opt_mask[nr_bit_filters] = mask;
opt_bits[nr_bit_filters] = bits;
nr_bit_filters++;
}
static uint64_t parse_flag_name(const char *str, int len)
{
size_t i;
if (!*str || !len)
return 0;
if (len <= 8 && !strncmp(str, "compound", len))
return BITS_COMPOUND;
for (i = 0; i < ARRAY_SIZE(page_flag_names); i++) {
if (!page_flag_names[i])
continue;
if (!strncmp(str, page_flag_names[i] + 2, len))
return 1ULL << i;
}
return parse_number(str);
}
static uint64_t parse_flag_names(const char *str, int all)
{
const char *p = str;
uint64_t flags = 0;
while (1) {
if (*p == ',' || *p == '=' || *p == '\0') {
if ((*str != '~') || (*str == '~' && all && *++str))
flags |= parse_flag_name(str, p - str);
if (*p != ',')
break;
str = p + 1;
}
p++;
}
return flags;
}
static void parse_bits_mask(const char *optarg)
{
uint64_t mask;
uint64_t bits;
const char *p;
p = strchr(optarg, '=');
if (p == optarg) {
mask = KPF_ALL_BITS;
bits = parse_flag_names(p + 1, 0);
} else if (p) {
mask = parse_flag_names(optarg, 0);
bits = parse_flag_names(p + 1, 0);
} else if (strchr(optarg, '~')) {
mask = parse_flag_names(optarg, 1);
bits = parse_flag_names(optarg, 0);
} else {
mask = parse_flag_names(optarg, 0);
bits = KPF_ALL_BITS;
}
add_bits_filter(mask, bits);
}
static void describe_flags(const char *optarg)
{
uint64_t flags = parse_flag_names(optarg, 0);
printf("0x%016llx\t%s\t%s\n",
(unsigned long long)flags,
page_flag_name(flags),
page_flag_longname(flags));
}
static const struct option opts[] = {
{ "raw" , 0, NULL, 'r' },
{ "pid" , 1, NULL, 'p' },
{ "file" , 1, NULL, 'f' },
{ "addr" , 1, NULL, 'a' },
{ "bits" , 1, NULL, 'b' },
{ "describe" , 1, NULL, 'd' },
{ "list" , 0, NULL, 'l' },
{ "list-each" , 0, NULL, 'L' },
{ "no-summary", 0, NULL, 'N' },
{ "hwpoison" , 0, NULL, 'X' },
{ "unpoison" , 0, NULL, 'x' },
{ "help" , 0, NULL, 'h' },
{ NULL , 0, NULL, 0 }
};
int main(int argc, char *argv[])
{
int c;
page_size = getpagesize();
while ((c = getopt_long(argc, argv,
"rp:f:a:b:d:lLNXxh", opts, NULL)) != -1) {
switch (c) {
case 'r':
opt_raw = 1;
break;
case 'p':
parse_pid(optarg);
break;
case 'f':
parse_file(optarg);
break;
case 'a':
parse_addr_range(optarg);
break;
case 'b':
parse_bits_mask(optarg);
break;
case 'd':
describe_flags(optarg);
exit(0);
case 'l':
opt_list = 1;
break;
case 'L':
opt_list = 2;
break;
case 'N':
opt_no_summary = 1;
break;
case 'X':
opt_hwpoison = 1;
prepare_hwpoison_fd();
break;
case 'x':
opt_unpoison = 1;
prepare_hwpoison_fd();
break;
case 'h':
usage();
exit(0);
default:
usage();
exit(1);
}
}
if (opt_list && opt_pid)
printf("voffset\t");
if (opt_list == 1)
printf("offset\tlen\tflags\n");
if (opt_list == 2)
printf("offset\tflags\n");
walk_addr_ranges();
if (opt_list == 1)
show_page_range(0, 0, 0); /* drain the buffer */
if (opt_no_summary)
return 0;
if (opt_list)
printf("\n\n");
show_summary();
return 0;
}
| gpl-2.0 |
ISTweak/android_kernel_panasonic_p01d-cm9 | sound/pci/hda/patch_analog.c | 254 | 152667 | /*
* HD audio interface patch for AD1882, AD1884, AD1981HD, AD1983, AD1984,
* AD1986A, AD1988
*
* Copyright (c) 2005-2007 Takashi Iwai <tiwai@suse.de>
*
* This driver 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 driver 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/pci.h>
#include <sound/core.h>
#include "hda_codec.h"
#include "hda_local.h"
#include "hda_beep.h"
struct ad198x_spec {
struct snd_kcontrol_new *mixers[5];
int num_mixers;
unsigned int beep_amp; /* beep amp value, set via set_beep_amp() */
const struct hda_verb *init_verbs[5]; /* initialization verbs
* don't forget NULL termination!
*/
unsigned int num_init_verbs;
/* playback */
struct hda_multi_out multiout; /* playback set-up
* max_channels, dacs must be set
* dig_out_nid and hp_nid are optional
*/
unsigned int cur_eapd;
unsigned int need_dac_fix;
/* capture */
unsigned int num_adc_nids;
hda_nid_t *adc_nids;
hda_nid_t dig_in_nid; /* digital-in NID; optional */
/* capture source */
const struct hda_input_mux *input_mux;
hda_nid_t *capsrc_nids;
unsigned int cur_mux[3];
/* channel model */
const struct hda_channel_mode *channel_mode;
int num_channel_mode;
/* PCM information */
struct hda_pcm pcm_rec[3]; /* used in alc_build_pcms() */
unsigned int spdif_route;
/* dynamic controls, init_verbs and input_mux */
struct auto_pin_cfg autocfg;
struct snd_array kctls;
struct hda_input_mux private_imux;
hda_nid_t private_dac_nids[AUTO_CFG_MAX_OUTS];
unsigned int jack_present: 1;
unsigned int inv_jack_detect: 1;/* inverted jack-detection */
unsigned int inv_eapd: 1; /* inverted EAPD implementation */
unsigned int analog_beep: 1; /* analog beep input present */
#ifdef CONFIG_SND_HDA_POWER_SAVE
struct hda_loopback_check loopback;
#endif
/* for virtual master */
hda_nid_t vmaster_nid;
const char **slave_vols;
const char **slave_sws;
};
/*
* input MUX handling (common part)
*/
static int ad198x_mux_enum_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct ad198x_spec *spec = codec->spec;
return snd_hda_input_mux_info(spec->input_mux, uinfo);
}
static int ad198x_mux_enum_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct ad198x_spec *spec = codec->spec;
unsigned int adc_idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id);
ucontrol->value.enumerated.item[0] = spec->cur_mux[adc_idx];
return 0;
}
static int ad198x_mux_enum_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct ad198x_spec *spec = codec->spec;
unsigned int adc_idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id);
return snd_hda_input_mux_put(codec, spec->input_mux, ucontrol,
spec->capsrc_nids[adc_idx],
&spec->cur_mux[adc_idx]);
}
/*
* initialization (common callbacks)
*/
static int ad198x_init(struct hda_codec *codec)
{
struct ad198x_spec *spec = codec->spec;
int i;
for (i = 0; i < spec->num_init_verbs; i++)
snd_hda_sequence_write(codec, spec->init_verbs[i]);
return 0;
}
static const char *ad_slave_vols[] = {
"Front Playback Volume",
"Surround Playback Volume",
"Center Playback Volume",
"LFE Playback Volume",
"Side Playback Volume",
"Headphone Playback Volume",
"Mono Playback Volume",
"Speaker Playback Volume",
"IEC958 Playback Volume",
NULL
};
static const char *ad_slave_sws[] = {
"Front Playback Switch",
"Surround Playback Switch",
"Center Playback Switch",
"LFE Playback Switch",
"Side Playback Switch",
"Headphone Playback Switch",
"Mono Playback Switch",
"Speaker Playback Switch",
"IEC958 Playback Switch",
NULL
};
static void ad198x_free_kctls(struct hda_codec *codec);
#ifdef CONFIG_SND_HDA_INPUT_BEEP
/* additional beep mixers; the actual parameters are overwritten at build */
static struct snd_kcontrol_new ad_beep_mixer[] = {
HDA_CODEC_VOLUME("Beep Playback Volume", 0, 0, HDA_OUTPUT),
HDA_CODEC_MUTE_BEEP("Beep Playback Switch", 0, 0, HDA_OUTPUT),
{ } /* end */
};
static struct snd_kcontrol_new ad_beep2_mixer[] = {
HDA_CODEC_VOLUME("Digital Beep Playback Volume", 0, 0, HDA_OUTPUT),
HDA_CODEC_MUTE_BEEP("Digital Beep Playback Switch", 0, 0, HDA_OUTPUT),
{ } /* end */
};
#define set_beep_amp(spec, nid, idx, dir) \
((spec)->beep_amp = HDA_COMPOSE_AMP_VAL(nid, 1, idx, dir)) /* mono */
#else
#define set_beep_amp(spec, nid, idx, dir) /* NOP */
#endif
static int ad198x_build_controls(struct hda_codec *codec)
{
struct ad198x_spec *spec = codec->spec;
struct snd_kcontrol *kctl;
unsigned int i;
int err;
for (i = 0; i < spec->num_mixers; i++) {
err = snd_hda_add_new_ctls(codec, spec->mixers[i]);
if (err < 0)
return err;
}
if (spec->multiout.dig_out_nid) {
err = snd_hda_create_spdif_out_ctls(codec, spec->multiout.dig_out_nid);
if (err < 0)
return err;
err = snd_hda_create_spdif_share_sw(codec,
&spec->multiout);
if (err < 0)
return err;
spec->multiout.share_spdif = 1;
}
if (spec->dig_in_nid) {
err = snd_hda_create_spdif_in_ctls(codec, spec->dig_in_nid);
if (err < 0)
return err;
}
/* create beep controls if needed */
#ifdef CONFIG_SND_HDA_INPUT_BEEP
if (spec->beep_amp) {
struct snd_kcontrol_new *knew;
knew = spec->analog_beep ? ad_beep2_mixer : ad_beep_mixer;
for ( ; knew->name; knew++) {
struct snd_kcontrol *kctl;
kctl = snd_ctl_new1(knew, codec);
if (!kctl)
return -ENOMEM;
kctl->private_value = spec->beep_amp;
err = snd_hda_ctl_add(codec, 0, kctl);
if (err < 0)
return err;
}
}
#endif
/* if we have no master control, let's create it */
if (!snd_hda_find_mixer_ctl(codec, "Master Playback Volume")) {
unsigned int vmaster_tlv[4];
snd_hda_set_vmaster_tlv(codec, spec->vmaster_nid,
HDA_OUTPUT, vmaster_tlv);
err = snd_hda_add_vmaster(codec, "Master Playback Volume",
vmaster_tlv,
(spec->slave_vols ?
spec->slave_vols : ad_slave_vols));
if (err < 0)
return err;
}
if (!snd_hda_find_mixer_ctl(codec, "Master Playback Switch")) {
err = snd_hda_add_vmaster(codec, "Master Playback Switch",
NULL,
(spec->slave_sws ?
spec->slave_sws : ad_slave_sws));
if (err < 0)
return err;
}
ad198x_free_kctls(codec); /* no longer needed */
/* assign Capture Source enums to NID */
kctl = snd_hda_find_mixer_ctl(codec, "Capture Source");
if (!kctl)
kctl = snd_hda_find_mixer_ctl(codec, "Input Source");
for (i = 0; kctl && i < kctl->count; i++) {
err = snd_hda_add_nid(codec, kctl, i, spec->capsrc_nids[i]);
if (err < 0)
return err;
}
/* assign IEC958 enums to NID */
kctl = snd_hda_find_mixer_ctl(codec,
SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "Source");
if (kctl) {
err = snd_hda_add_nid(codec, kctl, 0,
spec->multiout.dig_out_nid);
if (err < 0)
return err;
}
return 0;
}
#ifdef CONFIG_SND_HDA_POWER_SAVE
static int ad198x_check_power_status(struct hda_codec *codec, hda_nid_t nid)
{
struct ad198x_spec *spec = codec->spec;
return snd_hda_check_amp_list_power(codec, &spec->loopback, nid);
}
#endif
/*
* Analog playback callbacks
*/
static int ad198x_playback_pcm_open(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct ad198x_spec *spec = codec->spec;
return snd_hda_multi_out_analog_open(codec, &spec->multiout, substream,
hinfo);
}
static int ad198x_playback_pcm_prepare(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
unsigned int stream_tag,
unsigned int format,
struct snd_pcm_substream *substream)
{
struct ad198x_spec *spec = codec->spec;
return snd_hda_multi_out_analog_prepare(codec, &spec->multiout, stream_tag,
format, substream);
}
static int ad198x_playback_pcm_cleanup(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct ad198x_spec *spec = codec->spec;
return snd_hda_multi_out_analog_cleanup(codec, &spec->multiout);
}
/*
* Digital out
*/
static int ad198x_dig_playback_pcm_open(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct ad198x_spec *spec = codec->spec;
return snd_hda_multi_out_dig_open(codec, &spec->multiout);
}
static int ad198x_dig_playback_pcm_close(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct ad198x_spec *spec = codec->spec;
return snd_hda_multi_out_dig_close(codec, &spec->multiout);
}
static int ad198x_dig_playback_pcm_prepare(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
unsigned int stream_tag,
unsigned int format,
struct snd_pcm_substream *substream)
{
struct ad198x_spec *spec = codec->spec;
return snd_hda_multi_out_dig_prepare(codec, &spec->multiout, stream_tag,
format, substream);
}
static int ad198x_dig_playback_pcm_cleanup(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct ad198x_spec *spec = codec->spec;
return snd_hda_multi_out_dig_cleanup(codec, &spec->multiout);
}
/*
* Analog capture
*/
static int ad198x_capture_pcm_prepare(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
unsigned int stream_tag,
unsigned int format,
struct snd_pcm_substream *substream)
{
struct ad198x_spec *spec = codec->spec;
snd_hda_codec_setup_stream(codec, spec->adc_nids[substream->number],
stream_tag, 0, format);
return 0;
}
static int ad198x_capture_pcm_cleanup(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct ad198x_spec *spec = codec->spec;
snd_hda_codec_cleanup_stream(codec, spec->adc_nids[substream->number]);
return 0;
}
/*
*/
static struct hda_pcm_stream ad198x_pcm_analog_playback = {
.substreams = 1,
.channels_min = 2,
.channels_max = 6, /* changed later */
.nid = 0, /* fill later */
.ops = {
.open = ad198x_playback_pcm_open,
.prepare = ad198x_playback_pcm_prepare,
.cleanup = ad198x_playback_pcm_cleanup
},
};
static struct hda_pcm_stream ad198x_pcm_analog_capture = {
.substreams = 1,
.channels_min = 2,
.channels_max = 2,
.nid = 0, /* fill later */
.ops = {
.prepare = ad198x_capture_pcm_prepare,
.cleanup = ad198x_capture_pcm_cleanup
},
};
static struct hda_pcm_stream ad198x_pcm_digital_playback = {
.substreams = 1,
.channels_min = 2,
.channels_max = 2,
.nid = 0, /* fill later */
.ops = {
.open = ad198x_dig_playback_pcm_open,
.close = ad198x_dig_playback_pcm_close,
.prepare = ad198x_dig_playback_pcm_prepare,
.cleanup = ad198x_dig_playback_pcm_cleanup
},
};
static struct hda_pcm_stream ad198x_pcm_digital_capture = {
.substreams = 1,
.channels_min = 2,
.channels_max = 2,
/* NID is set in alc_build_pcms */
};
static int ad198x_build_pcms(struct hda_codec *codec)
{
struct ad198x_spec *spec = codec->spec;
struct hda_pcm *info = spec->pcm_rec;
codec->num_pcms = 1;
codec->pcm_info = info;
info->name = "AD198x Analog";
info->stream[SNDRV_PCM_STREAM_PLAYBACK] = ad198x_pcm_analog_playback;
info->stream[SNDRV_PCM_STREAM_PLAYBACK].channels_max = spec->multiout.max_channels;
info->stream[SNDRV_PCM_STREAM_PLAYBACK].nid = spec->multiout.dac_nids[0];
info->stream[SNDRV_PCM_STREAM_CAPTURE] = ad198x_pcm_analog_capture;
info->stream[SNDRV_PCM_STREAM_CAPTURE].substreams = spec->num_adc_nids;
info->stream[SNDRV_PCM_STREAM_CAPTURE].nid = spec->adc_nids[0];
if (spec->multiout.dig_out_nid) {
info++;
codec->num_pcms++;
info->name = "AD198x Digital";
info->pcm_type = HDA_PCM_TYPE_SPDIF;
info->stream[SNDRV_PCM_STREAM_PLAYBACK] = ad198x_pcm_digital_playback;
info->stream[SNDRV_PCM_STREAM_PLAYBACK].nid = spec->multiout.dig_out_nid;
if (spec->dig_in_nid) {
info->stream[SNDRV_PCM_STREAM_CAPTURE] = ad198x_pcm_digital_capture;
info->stream[SNDRV_PCM_STREAM_CAPTURE].nid = spec->dig_in_nid;
}
}
return 0;
}
static inline void ad198x_shutup(struct hda_codec *codec)
{
snd_hda_shutup_pins(codec);
}
static void ad198x_free_kctls(struct hda_codec *codec)
{
struct ad198x_spec *spec = codec->spec;
if (spec->kctls.list) {
struct snd_kcontrol_new *kctl = spec->kctls.list;
int i;
for (i = 0; i < spec->kctls.used; i++)
kfree(kctl[i].name);
}
snd_array_free(&spec->kctls);
}
static void ad198x_power_eapd_write(struct hda_codec *codec, hda_nid_t front,
hda_nid_t hp)
{
struct ad198x_spec *spec = codec->spec;
snd_hda_codec_write(codec, front, 0, AC_VERB_SET_EAPD_BTLENABLE,
!spec->inv_eapd ? 0x00 : 0x02);
snd_hda_codec_write(codec, hp, 0, AC_VERB_SET_EAPD_BTLENABLE,
!spec->inv_eapd ? 0x00 : 0x02);
}
static void ad198x_power_eapd(struct hda_codec *codec)
{
/* We currently only handle front, HP */
switch (codec->vendor_id) {
case 0x11d41882:
case 0x11d4882a:
case 0x11d41884:
case 0x11d41984:
case 0x11d41883:
case 0x11d4184a:
case 0x11d4194a:
case 0x11d4194b:
ad198x_power_eapd_write(codec, 0x12, 0x11);
break;
case 0x11d41981:
case 0x11d41983:
ad198x_power_eapd_write(codec, 0x05, 0x06);
break;
case 0x11d41986:
ad198x_power_eapd_write(codec, 0x1b, 0x1a);
break;
case 0x11d41988:
case 0x11d4198b:
case 0x11d4989a:
case 0x11d4989b:
ad198x_power_eapd_write(codec, 0x29, 0x22);
break;
}
}
static void ad198x_free(struct hda_codec *codec)
{
struct ad198x_spec *spec = codec->spec;
if (!spec)
return;
ad198x_shutup(codec);
ad198x_free_kctls(codec);
kfree(spec);
snd_hda_detach_beep_device(codec);
}
#ifdef SND_HDA_NEEDS_RESUME
static int ad198x_suspend(struct hda_codec *codec, pm_message_t state)
{
ad198x_shutup(codec);
ad198x_power_eapd(codec);
return 0;
}
#endif
static struct hda_codec_ops ad198x_patch_ops = {
.build_controls = ad198x_build_controls,
.build_pcms = ad198x_build_pcms,
.init = ad198x_init,
.free = ad198x_free,
#ifdef CONFIG_SND_HDA_POWER_SAVE
.check_power_status = ad198x_check_power_status,
#endif
#ifdef SND_HDA_NEEDS_RESUME
.suspend = ad198x_suspend,
#endif
.reboot_notify = ad198x_shutup,
};
/*
* EAPD control
* the private value = nid
*/
#define ad198x_eapd_info snd_ctl_boolean_mono_info
static int ad198x_eapd_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct ad198x_spec *spec = codec->spec;
if (spec->inv_eapd)
ucontrol->value.integer.value[0] = ! spec->cur_eapd;
else
ucontrol->value.integer.value[0] = spec->cur_eapd;
return 0;
}
static int ad198x_eapd_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct ad198x_spec *spec = codec->spec;
hda_nid_t nid = kcontrol->private_value & 0xff;
unsigned int eapd;
eapd = !!ucontrol->value.integer.value[0];
if (spec->inv_eapd)
eapd = !eapd;
if (eapd == spec->cur_eapd)
return 0;
spec->cur_eapd = eapd;
snd_hda_codec_write_cache(codec, nid,
0, AC_VERB_SET_EAPD_BTLENABLE,
eapd ? 0x02 : 0x00);
return 1;
}
static int ad198x_ch_mode_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo);
static int ad198x_ch_mode_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol);
static int ad198x_ch_mode_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol);
/*
* AD1986A specific
*/
#define AD1986A_SPDIF_OUT 0x02
#define AD1986A_FRONT_DAC 0x03
#define AD1986A_SURR_DAC 0x04
#define AD1986A_CLFE_DAC 0x05
#define AD1986A_ADC 0x06
static hda_nid_t ad1986a_dac_nids[3] = {
AD1986A_FRONT_DAC, AD1986A_SURR_DAC, AD1986A_CLFE_DAC
};
static hda_nid_t ad1986a_adc_nids[1] = { AD1986A_ADC };
static hda_nid_t ad1986a_capsrc_nids[1] = { 0x12 };
static struct hda_input_mux ad1986a_capture_source = {
.num_items = 7,
.items = {
{ "Mic", 0x0 },
{ "CD", 0x1 },
{ "Aux", 0x3 },
{ "Line", 0x4 },
{ "Mix", 0x5 },
{ "Mono", 0x6 },
{ "Phone", 0x7 },
},
};
static struct hda_bind_ctls ad1986a_bind_pcm_vol = {
.ops = &snd_hda_bind_vol,
.values = {
HDA_COMPOSE_AMP_VAL(AD1986A_FRONT_DAC, 3, 0, HDA_OUTPUT),
HDA_COMPOSE_AMP_VAL(AD1986A_SURR_DAC, 3, 0, HDA_OUTPUT),
HDA_COMPOSE_AMP_VAL(AD1986A_CLFE_DAC, 3, 0, HDA_OUTPUT),
0
},
};
static struct hda_bind_ctls ad1986a_bind_pcm_sw = {
.ops = &snd_hda_bind_sw,
.values = {
HDA_COMPOSE_AMP_VAL(AD1986A_FRONT_DAC, 3, 0, HDA_OUTPUT),
HDA_COMPOSE_AMP_VAL(AD1986A_SURR_DAC, 3, 0, HDA_OUTPUT),
HDA_COMPOSE_AMP_VAL(AD1986A_CLFE_DAC, 3, 0, HDA_OUTPUT),
0
},
};
/*
* mixers
*/
static struct snd_kcontrol_new ad1986a_mixers[] = {
/*
* bind volumes/mutes of 3 DACs as a single PCM control for simplicity
*/
HDA_BIND_VOL("PCM Playback Volume", &ad1986a_bind_pcm_vol),
HDA_BIND_SW("PCM Playback Switch", &ad1986a_bind_pcm_sw),
HDA_CODEC_VOLUME("Front Playback Volume", 0x1b, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Front Playback Switch", 0x1b, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Surround Playback Volume", 0x1c, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Surround Playback Switch", 0x1c, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_MONO("Center Playback Volume", 0x1d, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_MONO("LFE Playback Volume", 0x1d, 2, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE_MONO("Center Playback Switch", 0x1d, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE_MONO("LFE Playback Switch", 0x1d, 2, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Headphone Playback Volume", 0x1a, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Headphone Playback Switch", 0x1a, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("CD Playback Volume", 0x15, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("CD Playback Switch", 0x15, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Line Playback Volume", 0x17, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Line Playback Switch", 0x17, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Aux Playback Volume", 0x16, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Aux Playback Switch", 0x16, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Mic Playback Volume", 0x13, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Mic Playback Switch", 0x13, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Mic Boost", 0x0f, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Mono Playback Volume", 0x1e, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Mono Playback Switch", 0x1e, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Capture Volume", 0x12, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Capture Switch", 0x12, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Capture Source",
.info = ad198x_mux_enum_info,
.get = ad198x_mux_enum_get,
.put = ad198x_mux_enum_put,
},
HDA_CODEC_MUTE("Stereo Downmix Switch", 0x09, 0x0, HDA_OUTPUT),
{ } /* end */
};
/* additional mixers for 3stack mode */
static struct snd_kcontrol_new ad1986a_3st_mixers[] = {
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Channel Mode",
.info = ad198x_ch_mode_info,
.get = ad198x_ch_mode_get,
.put = ad198x_ch_mode_put,
},
{ } /* end */
};
/* laptop model - 2ch only */
static hda_nid_t ad1986a_laptop_dac_nids[1] = { AD1986A_FRONT_DAC };
/* master controls both pins 0x1a and 0x1b */
static struct hda_bind_ctls ad1986a_laptop_master_vol = {
.ops = &snd_hda_bind_vol,
.values = {
HDA_COMPOSE_AMP_VAL(0x1a, 3, 0, HDA_OUTPUT),
HDA_COMPOSE_AMP_VAL(0x1b, 3, 0, HDA_OUTPUT),
0,
},
};
static struct hda_bind_ctls ad1986a_laptop_master_sw = {
.ops = &snd_hda_bind_sw,
.values = {
HDA_COMPOSE_AMP_VAL(0x1a, 3, 0, HDA_OUTPUT),
HDA_COMPOSE_AMP_VAL(0x1b, 3, 0, HDA_OUTPUT),
0,
},
};
static struct snd_kcontrol_new ad1986a_laptop_mixers[] = {
HDA_CODEC_VOLUME("PCM Playback Volume", 0x03, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("PCM Playback Switch", 0x03, 0x0, HDA_OUTPUT),
HDA_BIND_VOL("Master Playback Volume", &ad1986a_laptop_master_vol),
HDA_BIND_SW("Master Playback Switch", &ad1986a_laptop_master_sw),
HDA_CODEC_VOLUME("CD Playback Volume", 0x15, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("CD Playback Switch", 0x15, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Line Playback Volume", 0x17, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Line Playback Switch", 0x17, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Aux Playback Volume", 0x16, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Aux Playback Switch", 0x16, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Mic Playback Volume", 0x13, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Mic Playback Switch", 0x13, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Mic Boost", 0x0f, 0x0, HDA_OUTPUT),
/*
HDA_CODEC_VOLUME("Mono Playback Volume", 0x1e, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Mono Playback Switch", 0x1e, 0x0, HDA_OUTPUT), */
HDA_CODEC_VOLUME("Capture Volume", 0x12, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Capture Switch", 0x12, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Capture Source",
.info = ad198x_mux_enum_info,
.get = ad198x_mux_enum_get,
.put = ad198x_mux_enum_put,
},
{ } /* end */
};
/* laptop-eapd model - 2ch only */
static struct hda_input_mux ad1986a_laptop_eapd_capture_source = {
.num_items = 3,
.items = {
{ "Mic", 0x0 },
{ "Internal Mic", 0x4 },
{ "Mix", 0x5 },
},
};
static struct hda_input_mux ad1986a_automic_capture_source = {
.num_items = 2,
.items = {
{ "Mic", 0x0 },
{ "Mix", 0x5 },
},
};
static struct snd_kcontrol_new ad1986a_laptop_master_mixers[] = {
HDA_BIND_VOL("Master Playback Volume", &ad1986a_laptop_master_vol),
HDA_BIND_SW("Master Playback Switch", &ad1986a_laptop_master_sw),
{ } /* end */
};
static struct snd_kcontrol_new ad1986a_laptop_eapd_mixers[] = {
HDA_CODEC_VOLUME("PCM Playback Volume", 0x03, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("PCM Playback Switch", 0x03, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Mic Playback Volume", 0x13, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Mic Playback Switch", 0x13, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Mic Boost", 0x0f, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Capture Volume", 0x12, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Capture Switch", 0x12, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Capture Source",
.info = ad198x_mux_enum_info,
.get = ad198x_mux_enum_get,
.put = ad198x_mux_enum_put,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "External Amplifier",
.subdevice = HDA_SUBDEV_NID_FLAG | 0x1b,
.info = ad198x_eapd_info,
.get = ad198x_eapd_get,
.put = ad198x_eapd_put,
.private_value = 0x1b, /* port-D */
},
{ } /* end */
};
static struct snd_kcontrol_new ad1986a_laptop_intmic_mixers[] = {
HDA_CODEC_VOLUME("Internal Mic Playback Volume", 0x17, 0, HDA_OUTPUT),
HDA_CODEC_MUTE("Internal Mic Playback Switch", 0x17, 0, HDA_OUTPUT),
{ } /* end */
};
/* re-connect the mic boost input according to the jack sensing */
static void ad1986a_automic(struct hda_codec *codec)
{
unsigned int present;
present = snd_hda_jack_detect(codec, 0x1f);
/* 0 = 0x1f, 2 = 0x1d, 4 = mixed */
snd_hda_codec_write(codec, 0x0f, 0, AC_VERB_SET_CONNECT_SEL,
present ? 0 : 2);
}
#define AD1986A_MIC_EVENT 0x36
static void ad1986a_automic_unsol_event(struct hda_codec *codec,
unsigned int res)
{
if ((res >> 26) != AD1986A_MIC_EVENT)
return;
ad1986a_automic(codec);
}
static int ad1986a_automic_init(struct hda_codec *codec)
{
ad198x_init(codec);
ad1986a_automic(codec);
return 0;
}
/* laptop-automute - 2ch only */
static void ad1986a_update_hp(struct hda_codec *codec)
{
struct ad198x_spec *spec = codec->spec;
unsigned int mute;
if (spec->jack_present)
mute = HDA_AMP_MUTE; /* mute internal speaker */
else
/* unmute internal speaker if necessary */
mute = snd_hda_codec_amp_read(codec, 0x1a, 0, HDA_OUTPUT, 0);
snd_hda_codec_amp_stereo(codec, 0x1b, HDA_OUTPUT, 0,
HDA_AMP_MUTE, mute);
}
static void ad1986a_hp_automute(struct hda_codec *codec)
{
struct ad198x_spec *spec = codec->spec;
spec->jack_present = snd_hda_jack_detect(codec, 0x1a);
if (spec->inv_jack_detect)
spec->jack_present = !spec->jack_present;
ad1986a_update_hp(codec);
}
#define AD1986A_HP_EVENT 0x37
static void ad1986a_hp_unsol_event(struct hda_codec *codec, unsigned int res)
{
if ((res >> 26) != AD1986A_HP_EVENT)
return;
ad1986a_hp_automute(codec);
}
static int ad1986a_hp_init(struct hda_codec *codec)
{
ad198x_init(codec);
ad1986a_hp_automute(codec);
return 0;
}
/* bind hp and internal speaker mute (with plug check) */
static int ad1986a_hp_master_sw_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
long *valp = ucontrol->value.integer.value;
int change;
change = snd_hda_codec_amp_update(codec, 0x1a, 0, HDA_OUTPUT, 0,
HDA_AMP_MUTE,
valp[0] ? 0 : HDA_AMP_MUTE);
change |= snd_hda_codec_amp_update(codec, 0x1a, 1, HDA_OUTPUT, 0,
HDA_AMP_MUTE,
valp[1] ? 0 : HDA_AMP_MUTE);
if (change)
ad1986a_update_hp(codec);
return change;
}
static struct snd_kcontrol_new ad1986a_automute_master_mixers[] = {
HDA_BIND_VOL("Master Playback Volume", &ad1986a_laptop_master_vol),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Master Playback Switch",
.subdevice = HDA_SUBDEV_AMP_FLAG,
.info = snd_hda_mixer_amp_switch_info,
.get = snd_hda_mixer_amp_switch_get,
.put = ad1986a_hp_master_sw_put,
.private_value = HDA_COMPOSE_AMP_VAL(0x1a, 3, 0, HDA_OUTPUT),
},
{ } /* end */
};
/*
* initialization verbs
*/
static struct hda_verb ad1986a_init_verbs[] = {
/* Front, Surround, CLFE DAC; mute as default */
{0x03, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x04, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x05, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
/* Downmix - off */
{0x09, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
/* HP, Line-Out, Surround, CLFE selectors */
{0x0a, AC_VERB_SET_CONNECT_SEL, 0x0},
{0x0b, AC_VERB_SET_CONNECT_SEL, 0x0},
{0x0c, AC_VERB_SET_CONNECT_SEL, 0x0},
{0x0d, AC_VERB_SET_CONNECT_SEL, 0x0},
/* Mono selector */
{0x0e, AC_VERB_SET_CONNECT_SEL, 0x0},
/* Mic selector: Mic 1/2 pin */
{0x0f, AC_VERB_SET_CONNECT_SEL, 0x0},
/* Line-in selector: Line-in */
{0x10, AC_VERB_SET_CONNECT_SEL, 0x0},
/* Mic 1/2 swap */
{0x11, AC_VERB_SET_CONNECT_SEL, 0x0},
/* Record selector: mic */
{0x12, AC_VERB_SET_CONNECT_SEL, 0x0},
/* Mic, Phone, CD, Aux, Line-In amp; mute as default */
{0x13, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x14, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x15, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x16, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x17, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
/* PC beep */
{0x18, AC_VERB_SET_CONNECT_SEL, 0x0},
/* HP, Line-Out, Surround, CLFE, Mono pins; mute as default */
{0x1a, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x1b, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x1c, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x1d, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x1e, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
/* HP Pin */
{0x1a, AC_VERB_SET_PIN_WIDGET_CONTROL, 0xc0 },
/* Front, Surround, CLFE Pins */
{0x1b, AC_VERB_SET_PIN_WIDGET_CONTROL, 0x40 },
{0x1c, AC_VERB_SET_PIN_WIDGET_CONTROL, 0x40 },
{0x1d, AC_VERB_SET_PIN_WIDGET_CONTROL, 0x40 },
/* Mono Pin */
{0x1e, AC_VERB_SET_PIN_WIDGET_CONTROL, 0x40 },
/* Mic Pin */
{0x1f, AC_VERB_SET_PIN_WIDGET_CONTROL, 0x24 },
/* Line, Aux, CD, Beep-In Pin */
{0x20, AC_VERB_SET_PIN_WIDGET_CONTROL, 0x20 },
{0x21, AC_VERB_SET_PIN_WIDGET_CONTROL, 0x20 },
{0x22, AC_VERB_SET_PIN_WIDGET_CONTROL, 0x20 },
{0x23, AC_VERB_SET_PIN_WIDGET_CONTROL, 0x20 },
{0x24, AC_VERB_SET_PIN_WIDGET_CONTROL, 0x20 },
{ } /* end */
};
static struct hda_verb ad1986a_ch2_init[] = {
/* Surround out -> Line In */
{ 0x1c, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_IN },
/* Line-in selectors */
{ 0x10, AC_VERB_SET_CONNECT_SEL, 0x1 },
/* CLFE -> Mic in */
{ 0x1d, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80 },
/* Mic selector, mix C/LFE (backmic) and Mic (frontmic) */
{ 0x0f, AC_VERB_SET_CONNECT_SEL, 0x4 },
{ } /* end */
};
static struct hda_verb ad1986a_ch4_init[] = {
/* Surround out -> Surround */
{ 0x1c, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT },
{ 0x10, AC_VERB_SET_CONNECT_SEL, 0x0 },
/* CLFE -> Mic in */
{ 0x1d, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80 },
{ 0x0f, AC_VERB_SET_CONNECT_SEL, 0x4 },
{ } /* end */
};
static struct hda_verb ad1986a_ch6_init[] = {
/* Surround out -> Surround out */
{ 0x1c, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT },
{ 0x10, AC_VERB_SET_CONNECT_SEL, 0x0 },
/* CLFE -> CLFE */
{ 0x1d, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT },
{ 0x0f, AC_VERB_SET_CONNECT_SEL, 0x0 },
{ } /* end */
};
static struct hda_channel_mode ad1986a_modes[3] = {
{ 2, ad1986a_ch2_init },
{ 4, ad1986a_ch4_init },
{ 6, ad1986a_ch6_init },
};
/* eapd initialization */
static struct hda_verb ad1986a_eapd_init_verbs[] = {
{0x1b, AC_VERB_SET_EAPD_BTLENABLE, 0x00 },
{}
};
static struct hda_verb ad1986a_automic_verbs[] = {
{0x1d, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80},
{0x1f, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80},
/*{0x20, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80},*/
{0x0f, AC_VERB_SET_CONNECT_SEL, 0x0},
{0x1f, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | AD1986A_MIC_EVENT},
{}
};
/* Ultra initialization */
static struct hda_verb ad1986a_ultra_init[] = {
/* eapd initialization */
{ 0x1b, AC_VERB_SET_EAPD_BTLENABLE, 0x00 },
/* CLFE -> Mic in */
{ 0x0f, AC_VERB_SET_CONNECT_SEL, 0x2 },
{ 0x1d, AC_VERB_SET_PIN_WIDGET_CONTROL, 0x24 },
{ 0x1d, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080 },
{ } /* end */
};
/* pin sensing on HP jack */
static struct hda_verb ad1986a_hp_init_verbs[] = {
{0x1a, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | AD1986A_HP_EVENT},
{}
};
static void ad1986a_samsung_p50_unsol_event(struct hda_codec *codec,
unsigned int res)
{
switch (res >> 26) {
case AD1986A_HP_EVENT:
ad1986a_hp_automute(codec);
break;
case AD1986A_MIC_EVENT:
ad1986a_automic(codec);
break;
}
}
static int ad1986a_samsung_p50_init(struct hda_codec *codec)
{
ad198x_init(codec);
ad1986a_hp_automute(codec);
ad1986a_automic(codec);
return 0;
}
/* models */
enum {
AD1986A_6STACK,
AD1986A_3STACK,
AD1986A_LAPTOP,
AD1986A_LAPTOP_EAPD,
AD1986A_LAPTOP_AUTOMUTE,
AD1986A_ULTRA,
AD1986A_SAMSUNG,
AD1986A_SAMSUNG_P50,
AD1986A_MODELS
};
static const char *ad1986a_models[AD1986A_MODELS] = {
[AD1986A_6STACK] = "6stack",
[AD1986A_3STACK] = "3stack",
[AD1986A_LAPTOP] = "laptop",
[AD1986A_LAPTOP_EAPD] = "laptop-eapd",
[AD1986A_LAPTOP_AUTOMUTE] = "laptop-automute",
[AD1986A_ULTRA] = "ultra",
[AD1986A_SAMSUNG] = "samsung",
[AD1986A_SAMSUNG_P50] = "samsung-p50",
};
static struct snd_pci_quirk ad1986a_cfg_tbl[] = {
SND_PCI_QUIRK(0x103c, 0x30af, "HP B2800", AD1986A_LAPTOP_EAPD),
SND_PCI_QUIRK(0x1043, 0x1153, "ASUS M9", AD1986A_LAPTOP_EAPD),
SND_PCI_QUIRK(0x1043, 0x11f7, "ASUS U5A", AD1986A_LAPTOP_EAPD),
SND_PCI_QUIRK(0x1043, 0x1213, "ASUS A6J", AD1986A_LAPTOP_EAPD),
SND_PCI_QUIRK(0x1043, 0x1263, "ASUS U5F", AD1986A_LAPTOP_EAPD),
SND_PCI_QUIRK(0x1043, 0x1297, "ASUS Z62F", AD1986A_LAPTOP_EAPD),
SND_PCI_QUIRK(0x1043, 0x12b3, "ASUS V1j", AD1986A_LAPTOP_EAPD),
SND_PCI_QUIRK(0x1043, 0x1302, "ASUS W3j", AD1986A_LAPTOP_EAPD),
SND_PCI_QUIRK(0x1043, 0x1443, "ASUS VX1", AD1986A_LAPTOP),
SND_PCI_QUIRK(0x1043, 0x1447, "ASUS A8J", AD1986A_3STACK),
SND_PCI_QUIRK(0x1043, 0x817f, "ASUS P5", AD1986A_3STACK),
SND_PCI_QUIRK(0x1043, 0x818f, "ASUS P5", AD1986A_LAPTOP),
SND_PCI_QUIRK(0x1043, 0x81b3, "ASUS P5", AD1986A_3STACK),
SND_PCI_QUIRK(0x1043, 0x81cb, "ASUS M2N", AD1986A_3STACK),
SND_PCI_QUIRK(0x1043, 0x8234, "ASUS M2N", AD1986A_3STACK),
SND_PCI_QUIRK(0x10de, 0xcb84, "ASUS A8N-VM", AD1986A_3STACK),
SND_PCI_QUIRK(0x1179, 0xff40, "Toshiba Satellite L40-10Q", AD1986A_3STACK),
SND_PCI_QUIRK(0x144d, 0xb03c, "Samsung R55", AD1986A_3STACK),
SND_PCI_QUIRK(0x144d, 0xc01e, "FSC V2060", AD1986A_LAPTOP),
SND_PCI_QUIRK(0x144d, 0xc024, "Samsung P50", AD1986A_SAMSUNG_P50),
SND_PCI_QUIRK(0x144d, 0xc027, "Samsung Q1", AD1986A_ULTRA),
SND_PCI_QUIRK_MASK(0x144d, 0xff00, 0xc000, "Samsung", AD1986A_SAMSUNG),
SND_PCI_QUIRK(0x144d, 0xc504, "Samsung Q35", AD1986A_3STACK),
SND_PCI_QUIRK(0x17aa, 0x1011, "Lenovo M55", AD1986A_LAPTOP),
SND_PCI_QUIRK(0x17aa, 0x1017, "Lenovo A60", AD1986A_3STACK),
SND_PCI_QUIRK(0x17aa, 0x2066, "Lenovo N100", AD1986A_LAPTOP_AUTOMUTE),
SND_PCI_QUIRK(0x17c0, 0x2017, "Samsung M50", AD1986A_LAPTOP),
{}
};
#ifdef CONFIG_SND_HDA_POWER_SAVE
static struct hda_amp_list ad1986a_loopbacks[] = {
{ 0x13, HDA_OUTPUT, 0 }, /* Mic */
{ 0x14, HDA_OUTPUT, 0 }, /* Phone */
{ 0x15, HDA_OUTPUT, 0 }, /* CD */
{ 0x16, HDA_OUTPUT, 0 }, /* Aux */
{ 0x17, HDA_OUTPUT, 0 }, /* Line */
{ } /* end */
};
#endif
static int is_jack_available(struct hda_codec *codec, hda_nid_t nid)
{
unsigned int conf = snd_hda_codec_get_pincfg(codec, nid);
return get_defcfg_connect(conf) != AC_JACK_PORT_NONE;
}
static int patch_ad1986a(struct hda_codec *codec)
{
struct ad198x_spec *spec;
int err, board_config;
spec = kzalloc(sizeof(*spec), GFP_KERNEL);
if (spec == NULL)
return -ENOMEM;
codec->spec = spec;
err = snd_hda_attach_beep_device(codec, 0x19);
if (err < 0) {
ad198x_free(codec);
return err;
}
set_beep_amp(spec, 0x18, 0, HDA_OUTPUT);
spec->multiout.max_channels = 6;
spec->multiout.num_dacs = ARRAY_SIZE(ad1986a_dac_nids);
spec->multiout.dac_nids = ad1986a_dac_nids;
spec->multiout.dig_out_nid = AD1986A_SPDIF_OUT;
spec->num_adc_nids = 1;
spec->adc_nids = ad1986a_adc_nids;
spec->capsrc_nids = ad1986a_capsrc_nids;
spec->input_mux = &ad1986a_capture_source;
spec->num_mixers = 1;
spec->mixers[0] = ad1986a_mixers;
spec->num_init_verbs = 1;
spec->init_verbs[0] = ad1986a_init_verbs;
#ifdef CONFIG_SND_HDA_POWER_SAVE
spec->loopback.amplist = ad1986a_loopbacks;
#endif
spec->vmaster_nid = 0x1b;
spec->inv_eapd = 1; /* AD1986A has the inverted EAPD implementation */
codec->patch_ops = ad198x_patch_ops;
/* override some parameters */
board_config = snd_hda_check_board_config(codec, AD1986A_MODELS,
ad1986a_models,
ad1986a_cfg_tbl);
switch (board_config) {
case AD1986A_3STACK:
spec->num_mixers = 2;
spec->mixers[1] = ad1986a_3st_mixers;
spec->num_init_verbs = 2;
spec->init_verbs[1] = ad1986a_ch2_init;
spec->channel_mode = ad1986a_modes;
spec->num_channel_mode = ARRAY_SIZE(ad1986a_modes);
spec->need_dac_fix = 1;
spec->multiout.max_channels = 2;
spec->multiout.num_dacs = 1;
break;
case AD1986A_LAPTOP:
spec->mixers[0] = ad1986a_laptop_mixers;
spec->multiout.max_channels = 2;
spec->multiout.num_dacs = 1;
spec->multiout.dac_nids = ad1986a_laptop_dac_nids;
break;
case AD1986A_LAPTOP_EAPD:
spec->num_mixers = 3;
spec->mixers[0] = ad1986a_laptop_master_mixers;
spec->mixers[1] = ad1986a_laptop_eapd_mixers;
spec->mixers[2] = ad1986a_laptop_intmic_mixers;
spec->num_init_verbs = 2;
spec->init_verbs[1] = ad1986a_eapd_init_verbs;
spec->multiout.max_channels = 2;
spec->multiout.num_dacs = 1;
spec->multiout.dac_nids = ad1986a_laptop_dac_nids;
if (!is_jack_available(codec, 0x25))
spec->multiout.dig_out_nid = 0;
spec->input_mux = &ad1986a_laptop_eapd_capture_source;
break;
case AD1986A_SAMSUNG:
spec->num_mixers = 2;
spec->mixers[0] = ad1986a_laptop_master_mixers;
spec->mixers[1] = ad1986a_laptop_eapd_mixers;
spec->num_init_verbs = 3;
spec->init_verbs[1] = ad1986a_eapd_init_verbs;
spec->init_verbs[2] = ad1986a_automic_verbs;
spec->multiout.max_channels = 2;
spec->multiout.num_dacs = 1;
spec->multiout.dac_nids = ad1986a_laptop_dac_nids;
if (!is_jack_available(codec, 0x25))
spec->multiout.dig_out_nid = 0;
spec->input_mux = &ad1986a_automic_capture_source;
codec->patch_ops.unsol_event = ad1986a_automic_unsol_event;
codec->patch_ops.init = ad1986a_automic_init;
break;
case AD1986A_SAMSUNG_P50:
spec->num_mixers = 2;
spec->mixers[0] = ad1986a_automute_master_mixers;
spec->mixers[1] = ad1986a_laptop_eapd_mixers;
spec->num_init_verbs = 4;
spec->init_verbs[1] = ad1986a_eapd_init_verbs;
spec->init_verbs[2] = ad1986a_automic_verbs;
spec->init_verbs[3] = ad1986a_hp_init_verbs;
spec->multiout.max_channels = 2;
spec->multiout.num_dacs = 1;
spec->multiout.dac_nids = ad1986a_laptop_dac_nids;
if (!is_jack_available(codec, 0x25))
spec->multiout.dig_out_nid = 0;
spec->input_mux = &ad1986a_automic_capture_source;
codec->patch_ops.unsol_event = ad1986a_samsung_p50_unsol_event;
codec->patch_ops.init = ad1986a_samsung_p50_init;
break;
case AD1986A_LAPTOP_AUTOMUTE:
spec->num_mixers = 3;
spec->mixers[0] = ad1986a_automute_master_mixers;
spec->mixers[1] = ad1986a_laptop_eapd_mixers;
spec->mixers[2] = ad1986a_laptop_intmic_mixers;
spec->num_init_verbs = 3;
spec->init_verbs[1] = ad1986a_eapd_init_verbs;
spec->init_verbs[2] = ad1986a_hp_init_verbs;
spec->multiout.max_channels = 2;
spec->multiout.num_dacs = 1;
spec->multiout.dac_nids = ad1986a_laptop_dac_nids;
if (!is_jack_available(codec, 0x25))
spec->multiout.dig_out_nid = 0;
spec->input_mux = &ad1986a_laptop_eapd_capture_source;
codec->patch_ops.unsol_event = ad1986a_hp_unsol_event;
codec->patch_ops.init = ad1986a_hp_init;
/* Lenovo N100 seems to report the reversed bit
* for HP jack-sensing
*/
spec->inv_jack_detect = 1;
break;
case AD1986A_ULTRA:
spec->mixers[0] = ad1986a_laptop_eapd_mixers;
spec->num_init_verbs = 2;
spec->init_verbs[1] = ad1986a_ultra_init;
spec->multiout.max_channels = 2;
spec->multiout.num_dacs = 1;
spec->multiout.dac_nids = ad1986a_laptop_dac_nids;
spec->multiout.dig_out_nid = 0;
break;
}
/* AD1986A has a hardware problem that it can't share a stream
* with multiple output pins. The copy of front to surrounds
* causes noisy or silent outputs at a certain timing, e.g.
* changing the volume.
* So, let's disable the shared stream.
*/
spec->multiout.no_share_stream = 1;
codec->no_trigger_sense = 1;
return 0;
}
/*
* AD1983 specific
*/
#define AD1983_SPDIF_OUT 0x02
#define AD1983_DAC 0x03
#define AD1983_ADC 0x04
static hda_nid_t ad1983_dac_nids[1] = { AD1983_DAC };
static hda_nid_t ad1983_adc_nids[1] = { AD1983_ADC };
static hda_nid_t ad1983_capsrc_nids[1] = { 0x15 };
static struct hda_input_mux ad1983_capture_source = {
.num_items = 4,
.items = {
{ "Mic", 0x0 },
{ "Line", 0x1 },
{ "Mix", 0x2 },
{ "Mix Mono", 0x3 },
},
};
/*
* SPDIF playback route
*/
static int ad1983_spdif_route_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
static char *texts[] = { "PCM", "ADC" };
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = 2;
if (uinfo->value.enumerated.item > 1)
uinfo->value.enumerated.item = 1;
strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]);
return 0;
}
static int ad1983_spdif_route_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct ad198x_spec *spec = codec->spec;
ucontrol->value.enumerated.item[0] = spec->spdif_route;
return 0;
}
static int ad1983_spdif_route_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct ad198x_spec *spec = codec->spec;
if (ucontrol->value.enumerated.item[0] > 1)
return -EINVAL;
if (spec->spdif_route != ucontrol->value.enumerated.item[0]) {
spec->spdif_route = ucontrol->value.enumerated.item[0];
snd_hda_codec_write_cache(codec, spec->multiout.dig_out_nid, 0,
AC_VERB_SET_CONNECT_SEL,
spec->spdif_route);
return 1;
}
return 0;
}
static struct snd_kcontrol_new ad1983_mixers[] = {
HDA_CODEC_VOLUME("Front Playback Volume", 0x05, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Front Playback Switch", 0x05, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Headphone Playback Volume", 0x06, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Headphone Playback Switch", 0x06, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_MONO("Mono Playback Volume", 0x07, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE_MONO("Mono Playback Switch", 0x07, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("PCM Playback Volume", 0x11, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("PCM Playback Switch", 0x11, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Mic Playback Volume", 0x12, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Mic Playback Switch", 0x12, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Line Playback Volume", 0x13, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Line Playback Switch", 0x13, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Mic Boost", 0x0c, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Capture Volume", 0x15, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Capture Switch", 0x15, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Capture Source",
.info = ad198x_mux_enum_info,
.get = ad198x_mux_enum_get,
.put = ad198x_mux_enum_put,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "Source",
.info = ad1983_spdif_route_info,
.get = ad1983_spdif_route_get,
.put = ad1983_spdif_route_put,
},
{ } /* end */
};
static struct hda_verb ad1983_init_verbs[] = {
/* Front, HP, Mono; mute as default */
{0x05, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x06, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x07, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
/* Beep, PCM, Mic, Line-In: mute */
{0x10, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x11, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x12, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x13, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
/* Front, HP selectors; from Mix */
{0x05, AC_VERB_SET_CONNECT_SEL, 0x01},
{0x06, AC_VERB_SET_CONNECT_SEL, 0x01},
/* Mono selector; from Mix */
{0x0b, AC_VERB_SET_CONNECT_SEL, 0x03},
/* Mic selector; Mic */
{0x0c, AC_VERB_SET_CONNECT_SEL, 0x0},
/* Line-in selector: Line-in */
{0x0d, AC_VERB_SET_CONNECT_SEL, 0x0},
/* Mic boost: 0dB */
{0x0c, AC_VERB_SET_AMP_GAIN_MUTE, 0xb000},
/* Record selector: mic */
{0x15, AC_VERB_SET_CONNECT_SEL, 0x0},
{0x15, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
/* SPDIF route: PCM */
{0x02, AC_VERB_SET_CONNECT_SEL, 0x0},
/* Front Pin */
{0x05, AC_VERB_SET_PIN_WIDGET_CONTROL, 0x40 },
/* HP Pin */
{0x06, AC_VERB_SET_PIN_WIDGET_CONTROL, 0xc0 },
/* Mono Pin */
{0x07, AC_VERB_SET_PIN_WIDGET_CONTROL, 0x40 },
/* Mic Pin */
{0x08, AC_VERB_SET_PIN_WIDGET_CONTROL, 0x24 },
/* Line Pin */
{0x09, AC_VERB_SET_PIN_WIDGET_CONTROL, 0x20 },
{ } /* end */
};
#ifdef CONFIG_SND_HDA_POWER_SAVE
static struct hda_amp_list ad1983_loopbacks[] = {
{ 0x12, HDA_OUTPUT, 0 }, /* Mic */
{ 0x13, HDA_OUTPUT, 0 }, /* Line */
{ } /* end */
};
#endif
static int patch_ad1983(struct hda_codec *codec)
{
struct ad198x_spec *spec;
int err;
spec = kzalloc(sizeof(*spec), GFP_KERNEL);
if (spec == NULL)
return -ENOMEM;
codec->spec = spec;
err = snd_hda_attach_beep_device(codec, 0x10);
if (err < 0) {
ad198x_free(codec);
return err;
}
set_beep_amp(spec, 0x10, 0, HDA_OUTPUT);
spec->multiout.max_channels = 2;
spec->multiout.num_dacs = ARRAY_SIZE(ad1983_dac_nids);
spec->multiout.dac_nids = ad1983_dac_nids;
spec->multiout.dig_out_nid = AD1983_SPDIF_OUT;
spec->num_adc_nids = 1;
spec->adc_nids = ad1983_adc_nids;
spec->capsrc_nids = ad1983_capsrc_nids;
spec->input_mux = &ad1983_capture_source;
spec->num_mixers = 1;
spec->mixers[0] = ad1983_mixers;
spec->num_init_verbs = 1;
spec->init_verbs[0] = ad1983_init_verbs;
spec->spdif_route = 0;
#ifdef CONFIG_SND_HDA_POWER_SAVE
spec->loopback.amplist = ad1983_loopbacks;
#endif
spec->vmaster_nid = 0x05;
codec->patch_ops = ad198x_patch_ops;
codec->no_trigger_sense = 1;
return 0;
}
/*
* AD1981 HD specific
*/
#define AD1981_SPDIF_OUT 0x02
#define AD1981_DAC 0x03
#define AD1981_ADC 0x04
static hda_nid_t ad1981_dac_nids[1] = { AD1981_DAC };
static hda_nid_t ad1981_adc_nids[1] = { AD1981_ADC };
static hda_nid_t ad1981_capsrc_nids[1] = { 0x15 };
/* 0x0c, 0x09, 0x0e, 0x0f, 0x19, 0x05, 0x18, 0x17 */
static struct hda_input_mux ad1981_capture_source = {
.num_items = 7,
.items = {
{ "Front Mic", 0x0 },
{ "Line", 0x1 },
{ "Mix", 0x2 },
{ "Mix Mono", 0x3 },
{ "CD", 0x4 },
{ "Mic", 0x6 },
{ "Aux", 0x7 },
},
};
static struct snd_kcontrol_new ad1981_mixers[] = {
HDA_CODEC_VOLUME("Front Playback Volume", 0x05, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Front Playback Switch", 0x05, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Headphone Playback Volume", 0x06, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Headphone Playback Switch", 0x06, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_MONO("Mono Playback Volume", 0x07, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE_MONO("Mono Playback Switch", 0x07, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("PCM Playback Volume", 0x11, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("PCM Playback Switch", 0x11, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Front Mic Playback Volume", 0x12, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Front Mic Playback Switch", 0x12, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Line Playback Volume", 0x13, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Line Playback Switch", 0x13, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Aux Playback Volume", 0x1b, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Aux Playback Switch", 0x1b, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Mic Playback Volume", 0x1c, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Mic Playback Switch", 0x1c, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("CD Playback Volume", 0x1d, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("CD Playback Switch", 0x1d, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Front Mic Boost", 0x08, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Mic Boost", 0x18, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Capture Volume", 0x15, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Capture Switch", 0x15, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Capture Source",
.info = ad198x_mux_enum_info,
.get = ad198x_mux_enum_get,
.put = ad198x_mux_enum_put,
},
/* identical with AD1983 */
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "Source",
.info = ad1983_spdif_route_info,
.get = ad1983_spdif_route_get,
.put = ad1983_spdif_route_put,
},
{ } /* end */
};
static struct hda_verb ad1981_init_verbs[] = {
/* Front, HP, Mono; mute as default */
{0x05, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x06, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x07, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
/* Beep, PCM, Front Mic, Line, Rear Mic, Aux, CD-In: mute */
{0x0d, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x11, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x12, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x13, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x1b, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x1c, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x1d, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
/* Front, HP selectors; from Mix */
{0x05, AC_VERB_SET_CONNECT_SEL, 0x01},
{0x06, AC_VERB_SET_CONNECT_SEL, 0x01},
/* Mono selector; from Mix */
{0x0b, AC_VERB_SET_CONNECT_SEL, 0x03},
/* Mic Mixer; select Front Mic */
{0x1e, AC_VERB_SET_AMP_GAIN_MUTE, 0xb000},
{0x1f, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
/* Mic boost: 0dB */
{0x08, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(0)},
{0x18, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(0)},
/* Record selector: Front mic */
{0x15, AC_VERB_SET_CONNECT_SEL, 0x0},
{0x15, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
/* SPDIF route: PCM */
{0x02, AC_VERB_SET_CONNECT_SEL, 0x0},
/* Front Pin */
{0x05, AC_VERB_SET_PIN_WIDGET_CONTROL, 0x40 },
/* HP Pin */
{0x06, AC_VERB_SET_PIN_WIDGET_CONTROL, 0xc0 },
/* Mono Pin */
{0x07, AC_VERB_SET_PIN_WIDGET_CONTROL, 0x40 },
/* Front & Rear Mic Pins */
{0x08, AC_VERB_SET_PIN_WIDGET_CONTROL, 0x24 },
{0x18, AC_VERB_SET_PIN_WIDGET_CONTROL, 0x24 },
/* Line Pin */
{0x09, AC_VERB_SET_PIN_WIDGET_CONTROL, 0x20 },
/* Digital Beep */
{0x0d, AC_VERB_SET_CONNECT_SEL, 0x00},
/* Line-Out as Input: disabled */
{0x1a, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{ } /* end */
};
#ifdef CONFIG_SND_HDA_POWER_SAVE
static struct hda_amp_list ad1981_loopbacks[] = {
{ 0x12, HDA_OUTPUT, 0 }, /* Front Mic */
{ 0x13, HDA_OUTPUT, 0 }, /* Line */
{ 0x1b, HDA_OUTPUT, 0 }, /* Aux */
{ 0x1c, HDA_OUTPUT, 0 }, /* Mic */
{ 0x1d, HDA_OUTPUT, 0 }, /* CD */
{ } /* end */
};
#endif
/*
* Patch for HP nx6320
*
* nx6320 uses EAPD in the reverse way - EAPD-on means the internal
* speaker output enabled _and_ mute-LED off.
*/
#define AD1981_HP_EVENT 0x37
#define AD1981_MIC_EVENT 0x38
static struct hda_verb ad1981_hp_init_verbs[] = {
{0x05, AC_VERB_SET_EAPD_BTLENABLE, 0x00 }, /* default off */
/* pin sensing on HP and Mic jacks */
{0x06, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | AD1981_HP_EVENT},
{0x08, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | AD1981_MIC_EVENT},
{}
};
/* turn on/off EAPD (+ mute HP) as a master switch */
static int ad1981_hp_master_sw_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct ad198x_spec *spec = codec->spec;
if (! ad198x_eapd_put(kcontrol, ucontrol))
return 0;
/* change speaker pin appropriately */
snd_hda_codec_write(codec, 0x05, 0,
AC_VERB_SET_PIN_WIDGET_CONTROL,
spec->cur_eapd ? PIN_OUT : 0);
/* toggle HP mute appropriately */
snd_hda_codec_amp_stereo(codec, 0x06, HDA_OUTPUT, 0,
HDA_AMP_MUTE,
spec->cur_eapd ? 0 : HDA_AMP_MUTE);
return 1;
}
/* bind volumes of both NID 0x05 and 0x06 */
static struct hda_bind_ctls ad1981_hp_bind_master_vol = {
.ops = &snd_hda_bind_vol,
.values = {
HDA_COMPOSE_AMP_VAL(0x05, 3, 0, HDA_OUTPUT),
HDA_COMPOSE_AMP_VAL(0x06, 3, 0, HDA_OUTPUT),
0
},
};
/* mute internal speaker if HP is plugged */
static void ad1981_hp_automute(struct hda_codec *codec)
{
unsigned int present;
present = snd_hda_jack_detect(codec, 0x06);
snd_hda_codec_amp_stereo(codec, 0x05, HDA_OUTPUT, 0,
HDA_AMP_MUTE, present ? HDA_AMP_MUTE : 0);
}
/* toggle input of built-in and mic jack appropriately */
static void ad1981_hp_automic(struct hda_codec *codec)
{
static struct hda_verb mic_jack_on[] = {
{0x1f, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x1e, AC_VERB_SET_AMP_GAIN_MUTE, 0xb000},
{}
};
static struct hda_verb mic_jack_off[] = {
{0x1e, AC_VERB_SET_AMP_GAIN_MUTE, 0xb080},
{0x1f, AC_VERB_SET_AMP_GAIN_MUTE, 0xb000},
{}
};
unsigned int present;
present = snd_hda_jack_detect(codec, 0x08);
if (present)
snd_hda_sequence_write(codec, mic_jack_on);
else
snd_hda_sequence_write(codec, mic_jack_off);
}
/* unsolicited event for HP jack sensing */
static void ad1981_hp_unsol_event(struct hda_codec *codec,
unsigned int res)
{
res >>= 26;
switch (res) {
case AD1981_HP_EVENT:
ad1981_hp_automute(codec);
break;
case AD1981_MIC_EVENT:
ad1981_hp_automic(codec);
break;
}
}
static struct hda_input_mux ad1981_hp_capture_source = {
.num_items = 3,
.items = {
{ "Mic", 0x0 },
{ "Docking-Station", 0x1 },
{ "Mix", 0x2 },
},
};
static struct snd_kcontrol_new ad1981_hp_mixers[] = {
HDA_BIND_VOL("Master Playback Volume", &ad1981_hp_bind_master_vol),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.subdevice = HDA_SUBDEV_NID_FLAG | 0x05,
.name = "Master Playback Switch",
.info = ad198x_eapd_info,
.get = ad198x_eapd_get,
.put = ad1981_hp_master_sw_put,
.private_value = 0x05,
},
HDA_CODEC_VOLUME("PCM Playback Volume", 0x11, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("PCM Playback Switch", 0x11, 0x0, HDA_OUTPUT),
#if 0
/* FIXME: analog mic/line loopback doesn't work with my tests...
* (although recording is OK)
*/
HDA_CODEC_VOLUME("Mic Playback Volume", 0x12, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Mic Playback Switch", 0x12, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Docking-Station Playback Volume", 0x13, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Docking-Station Playback Switch", 0x13, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Internal Mic Playback Volume", 0x1c, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Internal Mic Playback Switch", 0x1c, 0x0, HDA_OUTPUT),
/* FIXME: does this laptop have analog CD connection? */
HDA_CODEC_VOLUME("CD Playback Volume", 0x1d, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("CD Playback Switch", 0x1d, 0x0, HDA_OUTPUT),
#endif
HDA_CODEC_VOLUME("Mic Boost", 0x08, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Internal Mic Boost", 0x18, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Capture Volume", 0x15, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Capture Switch", 0x15, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Capture Source",
.info = ad198x_mux_enum_info,
.get = ad198x_mux_enum_get,
.put = ad198x_mux_enum_put,
},
{ } /* end */
};
/* initialize jack-sensing, too */
static int ad1981_hp_init(struct hda_codec *codec)
{
ad198x_init(codec);
ad1981_hp_automute(codec);
ad1981_hp_automic(codec);
return 0;
}
/* configuration for Toshiba Laptops */
static struct hda_verb ad1981_toshiba_init_verbs[] = {
{0x05, AC_VERB_SET_EAPD_BTLENABLE, 0x01 }, /* default on */
/* pin sensing on HP and Mic jacks */
{0x06, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | AD1981_HP_EVENT},
{0x08, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | AD1981_MIC_EVENT},
{}
};
static struct snd_kcontrol_new ad1981_toshiba_mixers[] = {
HDA_CODEC_VOLUME("Amp Volume", 0x1a, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Amp Switch", 0x1a, 0x0, HDA_OUTPUT),
{ }
};
/* configuration for Lenovo Thinkpad T60 */
static struct snd_kcontrol_new ad1981_thinkpad_mixers[] = {
HDA_CODEC_VOLUME("Master Playback Volume", 0x05, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Master Playback Switch", 0x05, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("PCM Playback Volume", 0x11, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("PCM Playback Switch", 0x11, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Mic Playback Volume", 0x12, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Mic Playback Switch", 0x12, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("CD Playback Volume", 0x1d, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("CD Playback Switch", 0x1d, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Mic Boost", 0x08, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Capture Volume", 0x15, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Capture Switch", 0x15, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Capture Source",
.info = ad198x_mux_enum_info,
.get = ad198x_mux_enum_get,
.put = ad198x_mux_enum_put,
},
/* identical with AD1983 */
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "Source",
.info = ad1983_spdif_route_info,
.get = ad1983_spdif_route_get,
.put = ad1983_spdif_route_put,
},
{ } /* end */
};
static struct hda_input_mux ad1981_thinkpad_capture_source = {
.num_items = 3,
.items = {
{ "Mic", 0x0 },
{ "Mix", 0x2 },
{ "CD", 0x4 },
},
};
/* models */
enum {
AD1981_BASIC,
AD1981_HP,
AD1981_THINKPAD,
AD1981_TOSHIBA,
AD1981_MODELS
};
static const char *ad1981_models[AD1981_MODELS] = {
[AD1981_HP] = "hp",
[AD1981_THINKPAD] = "thinkpad",
[AD1981_BASIC] = "basic",
[AD1981_TOSHIBA] = "toshiba"
};
static struct snd_pci_quirk ad1981_cfg_tbl[] = {
SND_PCI_QUIRK(0x1014, 0x0597, "Lenovo Z60", AD1981_THINKPAD),
SND_PCI_QUIRK(0x1014, 0x05b7, "Lenovo Z60m", AD1981_THINKPAD),
/* All HP models */
SND_PCI_QUIRK_VENDOR(0x103c, "HP nx", AD1981_HP),
SND_PCI_QUIRK(0x1179, 0x0001, "Toshiba U205", AD1981_TOSHIBA),
/* Lenovo Thinkpad T60/X60/Z6xx */
SND_PCI_QUIRK_VENDOR(0x17aa, "Lenovo Thinkpad", AD1981_THINKPAD),
/* HP nx6320 (reversed SSID, H/W bug) */
SND_PCI_QUIRK(0x30b0, 0x103c, "HP nx6320", AD1981_HP),
{}
};
static int patch_ad1981(struct hda_codec *codec)
{
struct ad198x_spec *spec;
int err, board_config;
spec = kzalloc(sizeof(*spec), GFP_KERNEL);
if (spec == NULL)
return -ENOMEM;
codec->spec = spec;
err = snd_hda_attach_beep_device(codec, 0x10);
if (err < 0) {
ad198x_free(codec);
return err;
}
set_beep_amp(spec, 0x0d, 0, HDA_OUTPUT);
spec->multiout.max_channels = 2;
spec->multiout.num_dacs = ARRAY_SIZE(ad1981_dac_nids);
spec->multiout.dac_nids = ad1981_dac_nids;
spec->multiout.dig_out_nid = AD1981_SPDIF_OUT;
spec->num_adc_nids = 1;
spec->adc_nids = ad1981_adc_nids;
spec->capsrc_nids = ad1981_capsrc_nids;
spec->input_mux = &ad1981_capture_source;
spec->num_mixers = 1;
spec->mixers[0] = ad1981_mixers;
spec->num_init_verbs = 1;
spec->init_verbs[0] = ad1981_init_verbs;
spec->spdif_route = 0;
#ifdef CONFIG_SND_HDA_POWER_SAVE
spec->loopback.amplist = ad1981_loopbacks;
#endif
spec->vmaster_nid = 0x05;
codec->patch_ops = ad198x_patch_ops;
/* override some parameters */
board_config = snd_hda_check_board_config(codec, AD1981_MODELS,
ad1981_models,
ad1981_cfg_tbl);
switch (board_config) {
case AD1981_HP:
spec->mixers[0] = ad1981_hp_mixers;
spec->num_init_verbs = 2;
spec->init_verbs[1] = ad1981_hp_init_verbs;
spec->multiout.dig_out_nid = 0;
spec->input_mux = &ad1981_hp_capture_source;
codec->patch_ops.init = ad1981_hp_init;
codec->patch_ops.unsol_event = ad1981_hp_unsol_event;
/* set the upper-limit for mixer amp to 0dB for avoiding the
* possible damage by overloading
*/
snd_hda_override_amp_caps(codec, 0x11, HDA_INPUT,
(0x17 << AC_AMPCAP_OFFSET_SHIFT) |
(0x17 << AC_AMPCAP_NUM_STEPS_SHIFT) |
(0x05 << AC_AMPCAP_STEP_SIZE_SHIFT) |
(1 << AC_AMPCAP_MUTE_SHIFT));
break;
case AD1981_THINKPAD:
spec->mixers[0] = ad1981_thinkpad_mixers;
spec->input_mux = &ad1981_thinkpad_capture_source;
/* set the upper-limit for mixer amp to 0dB for avoiding the
* possible damage by overloading
*/
snd_hda_override_amp_caps(codec, 0x11, HDA_INPUT,
(0x17 << AC_AMPCAP_OFFSET_SHIFT) |
(0x17 << AC_AMPCAP_NUM_STEPS_SHIFT) |
(0x05 << AC_AMPCAP_STEP_SIZE_SHIFT) |
(1 << AC_AMPCAP_MUTE_SHIFT));
break;
case AD1981_TOSHIBA:
spec->mixers[0] = ad1981_hp_mixers;
spec->mixers[1] = ad1981_toshiba_mixers;
spec->num_init_verbs = 2;
spec->init_verbs[1] = ad1981_toshiba_init_verbs;
spec->multiout.dig_out_nid = 0;
spec->input_mux = &ad1981_hp_capture_source;
codec->patch_ops.init = ad1981_hp_init;
codec->patch_ops.unsol_event = ad1981_hp_unsol_event;
break;
}
codec->no_trigger_sense = 1;
return 0;
}
/*
* AD1988
*
* Output pins and routes
*
* Pin Mix Sel DAC (*)
* port-A 0x11 (mute/hp) <- 0x22 <- 0x37 <- 03/04/06
* port-B 0x14 (mute/hp) <- 0x2b <- 0x30 <- 03/04/06
* port-C 0x15 (mute) <- 0x2c <- 0x31 <- 05/0a
* port-D 0x12 (mute/hp) <- 0x29 <- 04
* port-E 0x17 (mute/hp) <- 0x26 <- 0x32 <- 05/0a
* port-F 0x16 (mute) <- 0x2a <- 06
* port-G 0x24 (mute) <- 0x27 <- 05
* port-H 0x25 (mute) <- 0x28 <- 0a
* mono 0x13 (mute/amp)<- 0x1e <- 0x36 <- 03/04/06
*
* DAC0 = 03h, DAC1 = 04h, DAC2 = 05h, DAC3 = 06h, DAC4 = 0ah
* (*) DAC2/3/4 are swapped to DAC3/4/2 on AD198A rev.2 due to a h/w bug.
*
* Input pins and routes
*
* pin boost mix input # / adc input #
* port-A 0x11 -> 0x38 -> mix 2, ADC 0
* port-B 0x14 -> 0x39 -> mix 0, ADC 1
* port-C 0x15 -> 0x3a -> 33:0 - mix 1, ADC 2
* port-D 0x12 -> 0x3d -> mix 3, ADC 8
* port-E 0x17 -> 0x3c -> 34:0 - mix 4, ADC 4
* port-F 0x16 -> 0x3b -> mix 5, ADC 3
* port-G 0x24 -> N/A -> 33:1 - mix 1, 34:1 - mix 4, ADC 6
* port-H 0x25 -> N/A -> 33:2 - mix 1, 34:2 - mix 4, ADC 7
*
*
* DAC assignment
* 6stack - front/surr/CLFE/side/opt DACs - 04/06/05/0a/03
* 3stack - front/surr/CLFE/opt DACs - 04/05/0a/03
*
* Inputs of Analog Mix (0x20)
* 0:Port-B (front mic)
* 1:Port-C/G/H (line-in)
* 2:Port-A
* 3:Port-D (line-in/2)
* 4:Port-E/G/H (mic-in)
* 5:Port-F (mic2-in)
* 6:CD
* 7:Beep
*
* ADC selection
* 0:Port-A
* 1:Port-B (front mic-in)
* 2:Port-C (line-in)
* 3:Port-F (mic2-in)
* 4:Port-E (mic-in)
* 5:CD
* 6:Port-G
* 7:Port-H
* 8:Port-D (line-in/2)
* 9:Mix
*
* Proposed pin assignments by the datasheet
*
* 6-stack
* Port-A front headphone
* B front mic-in
* C rear line-in
* D rear front-out
* E rear mic-in
* F rear surround
* G rear CLFE
* H rear side
*
* 3-stack
* Port-A front headphone
* B front mic
* C rear line-in/surround
* D rear front-out
* E rear mic-in/CLFE
*
* laptop
* Port-A headphone
* B mic-in
* C docking station
* D internal speaker (with EAPD)
* E/F quad mic array
*/
/* models */
enum {
AD1988_6STACK,
AD1988_6STACK_DIG,
AD1988_3STACK,
AD1988_3STACK_DIG,
AD1988_LAPTOP,
AD1988_LAPTOP_DIG,
AD1988_AUTO,
AD1988_MODEL_LAST,
};
/* reivision id to check workarounds */
#define AD1988A_REV2 0x100200
#define is_rev2(codec) \
((codec)->vendor_id == 0x11d41988 && \
(codec)->revision_id == AD1988A_REV2)
/*
* mixers
*/
static hda_nid_t ad1988_6stack_dac_nids[4] = {
0x04, 0x06, 0x05, 0x0a
};
static hda_nid_t ad1988_3stack_dac_nids[3] = {
0x04, 0x05, 0x0a
};
/* for AD1988A revision-2, DAC2-4 are swapped */
static hda_nid_t ad1988_6stack_dac_nids_rev2[4] = {
0x04, 0x05, 0x0a, 0x06
};
static hda_nid_t ad1988_3stack_dac_nids_rev2[3] = {
0x04, 0x0a, 0x06
};
static hda_nid_t ad1988_adc_nids[3] = {
0x08, 0x09, 0x0f
};
static hda_nid_t ad1988_capsrc_nids[3] = {
0x0c, 0x0d, 0x0e
};
#define AD1988_SPDIF_OUT 0x02
#define AD1988_SPDIF_OUT_HDMI 0x0b
#define AD1988_SPDIF_IN 0x07
static hda_nid_t ad1989b_slave_dig_outs[] = {
AD1988_SPDIF_OUT, AD1988_SPDIF_OUT_HDMI, 0
};
static struct hda_input_mux ad1988_6stack_capture_source = {
.num_items = 5,
.items = {
{ "Front Mic", 0x1 }, /* port-B */
{ "Line", 0x2 }, /* port-C */
{ "Mic", 0x4 }, /* port-E */
{ "CD", 0x5 },
{ "Mix", 0x9 },
},
};
static struct hda_input_mux ad1988_laptop_capture_source = {
.num_items = 3,
.items = {
{ "Mic/Line", 0x1 }, /* port-B */
{ "CD", 0x5 },
{ "Mix", 0x9 },
},
};
/*
*/
static int ad198x_ch_mode_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct ad198x_spec *spec = codec->spec;
return snd_hda_ch_mode_info(codec, uinfo, spec->channel_mode,
spec->num_channel_mode);
}
static int ad198x_ch_mode_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct ad198x_spec *spec = codec->spec;
return snd_hda_ch_mode_get(codec, ucontrol, spec->channel_mode,
spec->num_channel_mode, spec->multiout.max_channels);
}
static int ad198x_ch_mode_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct ad198x_spec *spec = codec->spec;
int err = snd_hda_ch_mode_put(codec, ucontrol, spec->channel_mode,
spec->num_channel_mode,
&spec->multiout.max_channels);
if (err >= 0 && spec->need_dac_fix)
spec->multiout.num_dacs = spec->multiout.max_channels / 2;
return err;
}
/* 6-stack mode */
static struct snd_kcontrol_new ad1988_6stack_mixers1[] = {
HDA_CODEC_VOLUME("Front Playback Volume", 0x04, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Surround Playback Volume", 0x06, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_MONO("Center Playback Volume", 0x05, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_MONO("LFE Playback Volume", 0x05, 2, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Side Playback Volume", 0x0a, 0x0, HDA_OUTPUT),
{ } /* end */
};
static struct snd_kcontrol_new ad1988_6stack_mixers1_rev2[] = {
HDA_CODEC_VOLUME("Front Playback Volume", 0x04, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Surround Playback Volume", 0x05, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_MONO("Center Playback Volume", 0x0a, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_MONO("LFE Playback Volume", 0x0a, 2, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Side Playback Volume", 0x06, 0x0, HDA_OUTPUT),
{ } /* end */
};
static struct snd_kcontrol_new ad1988_6stack_mixers2[] = {
HDA_BIND_MUTE("Front Playback Switch", 0x29, 2, HDA_INPUT),
HDA_BIND_MUTE("Surround Playback Switch", 0x2a, 2, HDA_INPUT),
HDA_BIND_MUTE_MONO("Center Playback Switch", 0x27, 1, 2, HDA_INPUT),
HDA_BIND_MUTE_MONO("LFE Playback Switch", 0x27, 2, 2, HDA_INPUT),
HDA_BIND_MUTE("Side Playback Switch", 0x28, 2, HDA_INPUT),
HDA_BIND_MUTE("Headphone Playback Switch", 0x22, 2, HDA_INPUT),
HDA_BIND_MUTE("Mono Playback Switch", 0x1e, 2, HDA_INPUT),
HDA_CODEC_VOLUME("CD Playback Volume", 0x20, 0x6, HDA_INPUT),
HDA_CODEC_MUTE("CD Playback Switch", 0x20, 0x6, HDA_INPUT),
HDA_CODEC_VOLUME("Front Mic Playback Volume", 0x20, 0x0, HDA_INPUT),
HDA_CODEC_MUTE("Front Mic Playback Switch", 0x20, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Line Playback Volume", 0x20, 0x1, HDA_INPUT),
HDA_CODEC_MUTE("Line Playback Switch", 0x20, 0x1, HDA_INPUT),
HDA_CODEC_VOLUME("Mic Playback Volume", 0x20, 0x4, HDA_INPUT),
HDA_CODEC_MUTE("Mic Playback Switch", 0x20, 0x4, HDA_INPUT),
HDA_CODEC_VOLUME("Analog Mix Playback Volume", 0x21, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Analog Mix Playback Switch", 0x21, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Front Mic Boost", 0x39, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Mic Boost", 0x3c, 0x0, HDA_OUTPUT),
{ } /* end */
};
/* 3-stack mode */
static struct snd_kcontrol_new ad1988_3stack_mixers1[] = {
HDA_CODEC_VOLUME("Front Playback Volume", 0x04, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Surround Playback Volume", 0x0a, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_MONO("Center Playback Volume", 0x05, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_MONO("LFE Playback Volume", 0x05, 2, 0x0, HDA_OUTPUT),
{ } /* end */
};
static struct snd_kcontrol_new ad1988_3stack_mixers1_rev2[] = {
HDA_CODEC_VOLUME("Front Playback Volume", 0x04, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Surround Playback Volume", 0x0a, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_MONO("Center Playback Volume", 0x06, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_MONO("LFE Playback Volume", 0x06, 2, 0x0, HDA_OUTPUT),
{ } /* end */
};
static struct snd_kcontrol_new ad1988_3stack_mixers2[] = {
HDA_BIND_MUTE("Front Playback Switch", 0x29, 2, HDA_INPUT),
HDA_BIND_MUTE("Surround Playback Switch", 0x2c, 2, HDA_INPUT),
HDA_BIND_MUTE_MONO("Center Playback Switch", 0x26, 1, 2, HDA_INPUT),
HDA_BIND_MUTE_MONO("LFE Playback Switch", 0x26, 2, 2, HDA_INPUT),
HDA_BIND_MUTE("Headphone Playback Switch", 0x22, 2, HDA_INPUT),
HDA_BIND_MUTE("Mono Playback Switch", 0x1e, 2, HDA_INPUT),
HDA_CODEC_VOLUME("CD Playback Volume", 0x20, 0x6, HDA_INPUT),
HDA_CODEC_MUTE("CD Playback Switch", 0x20, 0x6, HDA_INPUT),
HDA_CODEC_VOLUME("Front Mic Playback Volume", 0x20, 0x0, HDA_INPUT),
HDA_CODEC_MUTE("Front Mic Playback Switch", 0x20, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Line Playback Volume", 0x20, 0x1, HDA_INPUT),
HDA_CODEC_MUTE("Line Playback Switch", 0x20, 0x1, HDA_INPUT),
HDA_CODEC_VOLUME("Mic Playback Volume", 0x20, 0x4, HDA_INPUT),
HDA_CODEC_MUTE("Mic Playback Switch", 0x20, 0x4, HDA_INPUT),
HDA_CODEC_VOLUME("Analog Mix Playback Volume", 0x21, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Analog Mix Playback Switch", 0x21, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Front Mic Boost", 0x39, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Mic Boost", 0x3c, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Channel Mode",
.info = ad198x_ch_mode_info,
.get = ad198x_ch_mode_get,
.put = ad198x_ch_mode_put,
},
{ } /* end */
};
/* laptop mode */
static struct snd_kcontrol_new ad1988_laptop_mixers[] = {
HDA_CODEC_VOLUME("PCM Playback Volume", 0x04, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("PCM Playback Switch", 0x29, 0x0, HDA_INPUT),
HDA_BIND_MUTE("Mono Playback Switch", 0x1e, 2, HDA_INPUT),
HDA_CODEC_VOLUME("CD Playback Volume", 0x20, 0x6, HDA_INPUT),
HDA_CODEC_MUTE("CD Playback Switch", 0x20, 0x6, HDA_INPUT),
HDA_CODEC_VOLUME("Mic Playback Volume", 0x20, 0x0, HDA_INPUT),
HDA_CODEC_MUTE("Mic Playback Switch", 0x20, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Line Playback Volume", 0x20, 0x1, HDA_INPUT),
HDA_CODEC_MUTE("Line Playback Switch", 0x20, 0x1, HDA_INPUT),
HDA_CODEC_VOLUME("Analog Mix Playback Volume", 0x21, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Analog Mix Playback Switch", 0x21, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Mic Boost", 0x39, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "External Amplifier",
.subdevice = HDA_SUBDEV_NID_FLAG | 0x12,
.info = ad198x_eapd_info,
.get = ad198x_eapd_get,
.put = ad198x_eapd_put,
.private_value = 0x12, /* port-D */
},
{ } /* end */
};
/* capture */
static struct snd_kcontrol_new ad1988_capture_mixers[] = {
HDA_CODEC_VOLUME("Capture Volume", 0x0c, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Capture Switch", 0x0c, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_IDX("Capture Volume", 1, 0x0d, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE_IDX("Capture Switch", 1, 0x0d, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_IDX("Capture Volume", 2, 0x0e, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE_IDX("Capture Switch", 2, 0x0e, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
/* The multiple "Capture Source" controls confuse alsamixer
* So call somewhat different..
*/
/* .name = "Capture Source", */
.name = "Input Source",
.count = 3,
.info = ad198x_mux_enum_info,
.get = ad198x_mux_enum_get,
.put = ad198x_mux_enum_put,
},
{ } /* end */
};
static int ad1988_spdif_playback_source_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
static char *texts[] = {
"PCM", "ADC1", "ADC2", "ADC3"
};
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = 4;
if (uinfo->value.enumerated.item >= 4)
uinfo->value.enumerated.item = 3;
strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]);
return 0;
}
static int ad1988_spdif_playback_source_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
unsigned int sel;
sel = snd_hda_codec_read(codec, 0x1d, 0, AC_VERB_GET_AMP_GAIN_MUTE,
AC_AMP_GET_INPUT);
if (!(sel & 0x80))
ucontrol->value.enumerated.item[0] = 0;
else {
sel = snd_hda_codec_read(codec, 0x0b, 0,
AC_VERB_GET_CONNECT_SEL, 0);
if (sel < 3)
sel++;
else
sel = 0;
ucontrol->value.enumerated.item[0] = sel;
}
return 0;
}
static int ad1988_spdif_playback_source_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
unsigned int val, sel;
int change;
val = ucontrol->value.enumerated.item[0];
if (val > 3)
return -EINVAL;
if (!val) {
sel = snd_hda_codec_read(codec, 0x1d, 0,
AC_VERB_GET_AMP_GAIN_MUTE,
AC_AMP_GET_INPUT);
change = sel & 0x80;
if (change) {
snd_hda_codec_write_cache(codec, 0x1d, 0,
AC_VERB_SET_AMP_GAIN_MUTE,
AMP_IN_UNMUTE(0));
snd_hda_codec_write_cache(codec, 0x1d, 0,
AC_VERB_SET_AMP_GAIN_MUTE,
AMP_IN_MUTE(1));
}
} else {
sel = snd_hda_codec_read(codec, 0x1d, 0,
AC_VERB_GET_AMP_GAIN_MUTE,
AC_AMP_GET_INPUT | 0x01);
change = sel & 0x80;
if (change) {
snd_hda_codec_write_cache(codec, 0x1d, 0,
AC_VERB_SET_AMP_GAIN_MUTE,
AMP_IN_MUTE(0));
snd_hda_codec_write_cache(codec, 0x1d, 0,
AC_VERB_SET_AMP_GAIN_MUTE,
AMP_IN_UNMUTE(1));
}
sel = snd_hda_codec_read(codec, 0x0b, 0,
AC_VERB_GET_CONNECT_SEL, 0) + 1;
change |= sel != val;
if (change)
snd_hda_codec_write_cache(codec, 0x0b, 0,
AC_VERB_SET_CONNECT_SEL,
val - 1);
}
return change;
}
static struct snd_kcontrol_new ad1988_spdif_out_mixers[] = {
HDA_CODEC_VOLUME("IEC958 Playback Volume", 0x1b, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "IEC958 Playback Source",
.subdevice = HDA_SUBDEV_NID_FLAG | 0x1b,
.info = ad1988_spdif_playback_source_info,
.get = ad1988_spdif_playback_source_get,
.put = ad1988_spdif_playback_source_put,
},
{ } /* end */
};
static struct snd_kcontrol_new ad1988_spdif_in_mixers[] = {
HDA_CODEC_VOLUME("IEC958 Capture Volume", 0x1c, 0x0, HDA_INPUT),
{ } /* end */
};
static struct snd_kcontrol_new ad1989_spdif_out_mixers[] = {
HDA_CODEC_VOLUME("IEC958 Playback Volume", 0x1b, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("HDMI Playback Volume", 0x1d, 0x0, HDA_OUTPUT),
{ } /* end */
};
/*
* initialization verbs
*/
/*
* for 6-stack (+dig)
*/
static struct hda_verb ad1988_6stack_init_verbs[] = {
/* Front, Surround, CLFE, side DAC; unmute as default */
{0x04, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x06, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x05, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x0a, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
/* Port-A front headphon path */
{0x37, AC_VERB_SET_CONNECT_SEL, 0x01}, /* DAC1:04h */
{0x22, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x22, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x11, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x11, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_HP},
/* Port-D line-out path */
{0x29, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x29, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x12, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x12, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT},
/* Port-F surround path */
{0x2a, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x2a, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x16, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x16, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT},
/* Port-G CLFE path */
{0x27, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x27, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x24, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x24, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT},
/* Port-H side path */
{0x28, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x28, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x25, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x25, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT},
/* Mono out path */
{0x36, AC_VERB_SET_CONNECT_SEL, 0x1}, /* DAC1:04h */
{0x1e, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x1e, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x13, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT},
{0x13, AC_VERB_SET_AMP_GAIN_MUTE, 0xb01f}, /* unmute, 0dB */
/* Port-B front mic-in path */
{0x14, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
{0x14, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80},
{0x39, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_ZERO},
/* Port-C line-in path */
{0x15, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
{0x15, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_IN},
{0x3a, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_ZERO},
{0x33, AC_VERB_SET_CONNECT_SEL, 0x0},
/* Port-E mic-in path */
{0x17, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
{0x17, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80},
{0x3c, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_ZERO},
{0x34, AC_VERB_SET_CONNECT_SEL, 0x0},
/* Analog CD Input */
{0x18, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_IN},
/* Analog Mix output amp */
{0x21, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE | 0x1f}, /* 0dB */
{ }
};
static struct hda_verb ad1988_capture_init_verbs[] = {
/* mute analog mix */
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(2)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(3)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(4)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(5)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(6)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(7)},
/* select ADCs - front-mic */
{0x0c, AC_VERB_SET_CONNECT_SEL, 0x1},
{0x0d, AC_VERB_SET_CONNECT_SEL, 0x1},
{0x0e, AC_VERB_SET_CONNECT_SEL, 0x1},
{ }
};
static struct hda_verb ad1988_spdif_init_verbs[] = {
/* SPDIF out sel */
{0x02, AC_VERB_SET_CONNECT_SEL, 0x0}, /* PCM */
{0x0b, AC_VERB_SET_CONNECT_SEL, 0x0}, /* ADC1 */
{0x1d, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(0)},
{0x1d, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
/* SPDIF out pin */
{0x1b, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE | 0x27}, /* 0dB */
{ }
};
static struct hda_verb ad1988_spdif_in_init_verbs[] = {
/* unmute SPDIF input pin */
{0x1c, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(0)},
{ }
};
/* AD1989 has no ADC -> SPDIF route */
static struct hda_verb ad1989_spdif_init_verbs[] = {
/* SPDIF-1 out pin */
{0x1b, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT },
{0x1b, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE | 0x27}, /* 0dB */
/* SPDIF-2/HDMI out pin */
{0x1d, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT },
{0x1d, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE | 0x27}, /* 0dB */
{ }
};
/*
* verbs for 3stack (+dig)
*/
static struct hda_verb ad1988_3stack_ch2_init[] = {
/* set port-C to line-in */
{ 0x15, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE },
{ 0x15, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_IN },
/* set port-E to mic-in */
{ 0x17, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE },
{ 0x17, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80 },
{ } /* end */
};
static struct hda_verb ad1988_3stack_ch6_init[] = {
/* set port-C to surround out */
{ 0x15, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT },
{ 0x15, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE },
/* set port-E to CLFE out */
{ 0x17, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT },
{ 0x17, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE },
{ } /* end */
};
static struct hda_channel_mode ad1988_3stack_modes[2] = {
{ 2, ad1988_3stack_ch2_init },
{ 6, ad1988_3stack_ch6_init },
};
static struct hda_verb ad1988_3stack_init_verbs[] = {
/* Front, Surround, CLFE, side DAC; unmute as default */
{0x04, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x06, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x05, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x0a, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
/* Port-A front headphon path */
{0x37, AC_VERB_SET_CONNECT_SEL, 0x01}, /* DAC1:04h */
{0x22, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x22, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x11, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x11, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_HP},
/* Port-D line-out path */
{0x29, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x29, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x12, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x12, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT},
/* Mono out path */
{0x36, AC_VERB_SET_CONNECT_SEL, 0x1}, /* DAC1:04h */
{0x1e, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x1e, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x13, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT},
{0x13, AC_VERB_SET_AMP_GAIN_MUTE, 0xb01f}, /* unmute, 0dB */
/* Port-B front mic-in path */
{0x14, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
{0x14, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80},
{0x39, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_ZERO},
/* Port-C line-in/surround path - 6ch mode as default */
{0x15, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT},
{0x15, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x3a, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_ZERO},
{0x31, AC_VERB_SET_CONNECT_SEL, 0x0}, /* output sel: DAC 0x05 */
{0x33, AC_VERB_SET_CONNECT_SEL, 0x0},
/* Port-E mic-in/CLFE path - 6ch mode as default */
{0x17, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT},
{0x17, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x3c, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_ZERO},
{0x32, AC_VERB_SET_CONNECT_SEL, 0x1}, /* output sel: DAC 0x0a */
{0x34, AC_VERB_SET_CONNECT_SEL, 0x0},
/* mute analog mix */
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(2)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(3)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(4)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(5)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(6)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(7)},
/* select ADCs - front-mic */
{0x0c, AC_VERB_SET_CONNECT_SEL, 0x1},
{0x0d, AC_VERB_SET_CONNECT_SEL, 0x1},
{0x0e, AC_VERB_SET_CONNECT_SEL, 0x1},
/* Analog Mix output amp */
{0x21, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE | 0x1f}, /* 0dB */
{ }
};
/*
* verbs for laptop mode (+dig)
*/
static struct hda_verb ad1988_laptop_hp_on[] = {
/* unmute port-A and mute port-D */
{ 0x11, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE },
{ 0x12, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE },
{ } /* end */
};
static struct hda_verb ad1988_laptop_hp_off[] = {
/* mute port-A and unmute port-D */
{ 0x11, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE },
{ 0x12, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE },
{ } /* end */
};
#define AD1988_HP_EVENT 0x01
static struct hda_verb ad1988_laptop_init_verbs[] = {
/* Front, Surround, CLFE, side DAC; unmute as default */
{0x04, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x06, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x05, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x0a, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
/* Port-A front headphon path */
{0x37, AC_VERB_SET_CONNECT_SEL, 0x01}, /* DAC1:04h */
{0x22, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x22, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x11, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x11, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_HP},
/* unsolicited event for pin-sense */
{0x11, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | AD1988_HP_EVENT },
/* Port-D line-out path + EAPD */
{0x29, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x29, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x12, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x12, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT},
{0x12, AC_VERB_SET_EAPD_BTLENABLE, 0x00}, /* EAPD-off */
/* Mono out path */
{0x36, AC_VERB_SET_CONNECT_SEL, 0x1}, /* DAC1:04h */
{0x1e, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x1e, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x13, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT},
{0x13, AC_VERB_SET_AMP_GAIN_MUTE, 0xb01f}, /* unmute, 0dB */
/* Port-B mic-in path */
{0x14, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
{0x14, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80},
{0x39, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_ZERO},
/* Port-C docking station - try to output */
{0x15, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x15, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT},
{0x3a, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_ZERO},
{0x33, AC_VERB_SET_CONNECT_SEL, 0x0},
/* mute analog mix */
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(2)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(3)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(4)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(5)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(6)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(7)},
/* select ADCs - mic */
{0x0c, AC_VERB_SET_CONNECT_SEL, 0x1},
{0x0d, AC_VERB_SET_CONNECT_SEL, 0x1},
{0x0e, AC_VERB_SET_CONNECT_SEL, 0x1},
/* Analog Mix output amp */
{0x21, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE | 0x1f}, /* 0dB */
{ }
};
static void ad1988_laptop_unsol_event(struct hda_codec *codec, unsigned int res)
{
if ((res >> 26) != AD1988_HP_EVENT)
return;
if (snd_hda_jack_detect(codec, 0x11))
snd_hda_sequence_write(codec, ad1988_laptop_hp_on);
else
snd_hda_sequence_write(codec, ad1988_laptop_hp_off);
}
#ifdef CONFIG_SND_HDA_POWER_SAVE
static struct hda_amp_list ad1988_loopbacks[] = {
{ 0x20, HDA_INPUT, 0 }, /* Front Mic */
{ 0x20, HDA_INPUT, 1 }, /* Line */
{ 0x20, HDA_INPUT, 4 }, /* Mic */
{ 0x20, HDA_INPUT, 6 }, /* CD */
{ } /* end */
};
#endif
/*
* Automatic parse of I/O pins from the BIOS configuration
*/
enum {
AD_CTL_WIDGET_VOL,
AD_CTL_WIDGET_MUTE,
AD_CTL_BIND_MUTE,
};
static struct snd_kcontrol_new ad1988_control_templates[] = {
HDA_CODEC_VOLUME(NULL, 0, 0, 0),
HDA_CODEC_MUTE(NULL, 0, 0, 0),
HDA_BIND_MUTE(NULL, 0, 0, 0),
};
/* add dynamic controls */
static int add_control(struct ad198x_spec *spec, int type, const char *name,
unsigned long val)
{
struct snd_kcontrol_new *knew;
snd_array_init(&spec->kctls, sizeof(*knew), 32);
knew = snd_array_new(&spec->kctls);
if (!knew)
return -ENOMEM;
*knew = ad1988_control_templates[type];
knew->name = kstrdup(name, GFP_KERNEL);
if (! knew->name)
return -ENOMEM;
if (get_amp_nid_(val))
knew->subdevice = HDA_SUBDEV_AMP_FLAG;
knew->private_value = val;
return 0;
}
#define AD1988_PIN_CD_NID 0x18
#define AD1988_PIN_BEEP_NID 0x10
static hda_nid_t ad1988_mixer_nids[8] = {
/* A B C D E F G H */
0x22, 0x2b, 0x2c, 0x29, 0x26, 0x2a, 0x27, 0x28
};
static inline hda_nid_t ad1988_idx_to_dac(struct hda_codec *codec, int idx)
{
static hda_nid_t idx_to_dac[8] = {
/* A B C D E F G H */
0x04, 0x06, 0x05, 0x04, 0x0a, 0x06, 0x05, 0x0a
};
static hda_nid_t idx_to_dac_rev2[8] = {
/* A B C D E F G H */
0x04, 0x05, 0x0a, 0x04, 0x06, 0x05, 0x0a, 0x06
};
if (is_rev2(codec))
return idx_to_dac_rev2[idx];
else
return idx_to_dac[idx];
}
static hda_nid_t ad1988_boost_nids[8] = {
0x38, 0x39, 0x3a, 0x3d, 0x3c, 0x3b, 0, 0
};
static int ad1988_pin_idx(hda_nid_t nid)
{
static hda_nid_t ad1988_io_pins[8] = {
0x11, 0x14, 0x15, 0x12, 0x17, 0x16, 0x24, 0x25
};
int i;
for (i = 0; i < ARRAY_SIZE(ad1988_io_pins); i++)
if (ad1988_io_pins[i] == nid)
return i;
return 0; /* should be -1 */
}
static int ad1988_pin_to_loopback_idx(hda_nid_t nid)
{
static int loopback_idx[8] = {
2, 0, 1, 3, 4, 5, 1, 4
};
switch (nid) {
case AD1988_PIN_CD_NID:
return 6;
default:
return loopback_idx[ad1988_pin_idx(nid)];
}
}
static int ad1988_pin_to_adc_idx(hda_nid_t nid)
{
static int adc_idx[8] = {
0, 1, 2, 8, 4, 3, 6, 7
};
switch (nid) {
case AD1988_PIN_CD_NID:
return 5;
default:
return adc_idx[ad1988_pin_idx(nid)];
}
}
/* fill in the dac_nids table from the parsed pin configuration */
static int ad1988_auto_fill_dac_nids(struct hda_codec *codec,
const struct auto_pin_cfg *cfg)
{
struct ad198x_spec *spec = codec->spec;
int i, idx;
spec->multiout.dac_nids = spec->private_dac_nids;
/* check the pins hardwired to audio widget */
for (i = 0; i < cfg->line_outs; i++) {
idx = ad1988_pin_idx(cfg->line_out_pins[i]);
spec->multiout.dac_nids[i] = ad1988_idx_to_dac(codec, idx);
}
spec->multiout.num_dacs = cfg->line_outs;
return 0;
}
/* add playback controls from the parsed DAC table */
static int ad1988_auto_create_multi_out_ctls(struct ad198x_spec *spec,
const struct auto_pin_cfg *cfg)
{
char name[32];
static const char *chname[4] = { "Front", "Surround", NULL /*CLFE*/, "Side" };
hda_nid_t nid;
int i, err;
for (i = 0; i < cfg->line_outs; i++) {
hda_nid_t dac = spec->multiout.dac_nids[i];
if (! dac)
continue;
nid = ad1988_mixer_nids[ad1988_pin_idx(cfg->line_out_pins[i])];
if (i == 2) {
/* Center/LFE */
err = add_control(spec, AD_CTL_WIDGET_VOL,
"Center Playback Volume",
HDA_COMPOSE_AMP_VAL(dac, 1, 0, HDA_OUTPUT));
if (err < 0)
return err;
err = add_control(spec, AD_CTL_WIDGET_VOL,
"LFE Playback Volume",
HDA_COMPOSE_AMP_VAL(dac, 2, 0, HDA_OUTPUT));
if (err < 0)
return err;
err = add_control(spec, AD_CTL_BIND_MUTE,
"Center Playback Switch",
HDA_COMPOSE_AMP_VAL(nid, 1, 2, HDA_INPUT));
if (err < 0)
return err;
err = add_control(spec, AD_CTL_BIND_MUTE,
"LFE Playback Switch",
HDA_COMPOSE_AMP_VAL(nid, 2, 2, HDA_INPUT));
if (err < 0)
return err;
} else {
sprintf(name, "%s Playback Volume", chname[i]);
err = add_control(spec, AD_CTL_WIDGET_VOL, name,
HDA_COMPOSE_AMP_VAL(dac, 3, 0, HDA_OUTPUT));
if (err < 0)
return err;
sprintf(name, "%s Playback Switch", chname[i]);
err = add_control(spec, AD_CTL_BIND_MUTE, name,
HDA_COMPOSE_AMP_VAL(nid, 3, 2, HDA_INPUT));
if (err < 0)
return err;
}
}
return 0;
}
/* add playback controls for speaker and HP outputs */
static int ad1988_auto_create_extra_out(struct hda_codec *codec, hda_nid_t pin,
const char *pfx)
{
struct ad198x_spec *spec = codec->spec;
hda_nid_t nid;
int i, idx, err;
char name[32];
if (! pin)
return 0;
idx = ad1988_pin_idx(pin);
nid = ad1988_idx_to_dac(codec, idx);
/* check whether the corresponding DAC was already taken */
for (i = 0; i < spec->autocfg.line_outs; i++) {
hda_nid_t pin = spec->autocfg.line_out_pins[i];
hda_nid_t dac = ad1988_idx_to_dac(codec, ad1988_pin_idx(pin));
if (dac == nid)
break;
}
if (i >= spec->autocfg.line_outs) {
/* specify the DAC as the extra output */
if (!spec->multiout.hp_nid)
spec->multiout.hp_nid = nid;
else
spec->multiout.extra_out_nid[0] = nid;
/* control HP volume/switch on the output mixer amp */
sprintf(name, "%s Playback Volume", pfx);
err = add_control(spec, AD_CTL_WIDGET_VOL, name,
HDA_COMPOSE_AMP_VAL(nid, 3, 0, HDA_OUTPUT));
if (err < 0)
return err;
}
nid = ad1988_mixer_nids[idx];
sprintf(name, "%s Playback Switch", pfx);
if ((err = add_control(spec, AD_CTL_BIND_MUTE, name,
HDA_COMPOSE_AMP_VAL(nid, 3, 2, HDA_INPUT))) < 0)
return err;
return 0;
}
/* create input playback/capture controls for the given pin */
static int new_analog_input(struct ad198x_spec *spec, hda_nid_t pin,
const char *ctlname, int boost)
{
char name[32];
int err, idx;
sprintf(name, "%s Playback Volume", ctlname);
idx = ad1988_pin_to_loopback_idx(pin);
if ((err = add_control(spec, AD_CTL_WIDGET_VOL, name,
HDA_COMPOSE_AMP_VAL(0x20, 3, idx, HDA_INPUT))) < 0)
return err;
sprintf(name, "%s Playback Switch", ctlname);
if ((err = add_control(spec, AD_CTL_WIDGET_MUTE, name,
HDA_COMPOSE_AMP_VAL(0x20, 3, idx, HDA_INPUT))) < 0)
return err;
if (boost) {
hda_nid_t bnid;
idx = ad1988_pin_idx(pin);
bnid = ad1988_boost_nids[idx];
if (bnid) {
sprintf(name, "%s Boost", ctlname);
return add_control(spec, AD_CTL_WIDGET_VOL, name,
HDA_COMPOSE_AMP_VAL(bnid, 3, idx, HDA_OUTPUT));
}
}
return 0;
}
/* create playback/capture controls for input pins */
static int ad1988_auto_create_analog_input_ctls(struct ad198x_spec *spec,
const struct auto_pin_cfg *cfg)
{
struct hda_input_mux *imux = &spec->private_imux;
int i, err;
for (i = 0; i < AUTO_PIN_LAST; i++) {
err = new_analog_input(spec, cfg->input_pins[i],
auto_pin_cfg_labels[i],
i <= AUTO_PIN_FRONT_MIC);
if (err < 0)
return err;
imux->items[imux->num_items].label = auto_pin_cfg_labels[i];
imux->items[imux->num_items].index = ad1988_pin_to_adc_idx(cfg->input_pins[i]);
imux->num_items++;
}
imux->items[imux->num_items].label = "Mix";
imux->items[imux->num_items].index = 9;
imux->num_items++;
if ((err = add_control(spec, AD_CTL_WIDGET_VOL,
"Analog Mix Playback Volume",
HDA_COMPOSE_AMP_VAL(0x21, 3, 0x0, HDA_OUTPUT))) < 0)
return err;
if ((err = add_control(spec, AD_CTL_WIDGET_MUTE,
"Analog Mix Playback Switch",
HDA_COMPOSE_AMP_VAL(0x21, 3, 0x0, HDA_OUTPUT))) < 0)
return err;
return 0;
}
static void ad1988_auto_set_output_and_unmute(struct hda_codec *codec,
hda_nid_t nid, int pin_type,
int dac_idx)
{
/* set as output */
snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_PIN_WIDGET_CONTROL, pin_type);
snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE);
switch (nid) {
case 0x11: /* port-A - DAC 04 */
snd_hda_codec_write(codec, 0x37, 0, AC_VERB_SET_CONNECT_SEL, 0x01);
break;
case 0x14: /* port-B - DAC 06 */
snd_hda_codec_write(codec, 0x30, 0, AC_VERB_SET_CONNECT_SEL, 0x02);
break;
case 0x15: /* port-C - DAC 05 */
snd_hda_codec_write(codec, 0x31, 0, AC_VERB_SET_CONNECT_SEL, 0x00);
break;
case 0x17: /* port-E - DAC 0a */
snd_hda_codec_write(codec, 0x32, 0, AC_VERB_SET_CONNECT_SEL, 0x01);
break;
case 0x13: /* mono - DAC 04 */
snd_hda_codec_write(codec, 0x36, 0, AC_VERB_SET_CONNECT_SEL, 0x01);
break;
}
}
static void ad1988_auto_init_multi_out(struct hda_codec *codec)
{
struct ad198x_spec *spec = codec->spec;
int i;
for (i = 0; i < spec->autocfg.line_outs; i++) {
hda_nid_t nid = spec->autocfg.line_out_pins[i];
ad1988_auto_set_output_and_unmute(codec, nid, PIN_OUT, i);
}
}
static void ad1988_auto_init_extra_out(struct hda_codec *codec)
{
struct ad198x_spec *spec = codec->spec;
hda_nid_t pin;
pin = spec->autocfg.speaker_pins[0];
if (pin) /* connect to front */
ad1988_auto_set_output_and_unmute(codec, pin, PIN_OUT, 0);
pin = spec->autocfg.hp_pins[0];
if (pin) /* connect to front */
ad1988_auto_set_output_and_unmute(codec, pin, PIN_HP, 0);
}
static void ad1988_auto_init_analog_input(struct hda_codec *codec)
{
struct ad198x_spec *spec = codec->spec;
int i, idx;
for (i = 0; i < AUTO_PIN_LAST; i++) {
hda_nid_t nid = spec->autocfg.input_pins[i];
if (! nid)
continue;
switch (nid) {
case 0x15: /* port-C */
snd_hda_codec_write(codec, 0x33, 0, AC_VERB_SET_CONNECT_SEL, 0x0);
break;
case 0x17: /* port-E */
snd_hda_codec_write(codec, 0x34, 0, AC_VERB_SET_CONNECT_SEL, 0x0);
break;
}
snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_PIN_WIDGET_CONTROL,
i <= AUTO_PIN_FRONT_MIC ? PIN_VREF80 : PIN_IN);
if (nid != AD1988_PIN_CD_NID)
snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_AMP_GAIN_MUTE,
AMP_OUT_MUTE);
idx = ad1988_pin_idx(nid);
if (ad1988_boost_nids[idx])
snd_hda_codec_write(codec, ad1988_boost_nids[idx], 0,
AC_VERB_SET_AMP_GAIN_MUTE,
AMP_OUT_ZERO);
}
}
/* parse the BIOS configuration and set up the alc_spec */
/* return 1 if successful, 0 if the proper config is not found, or a negative error code */
static int ad1988_parse_auto_config(struct hda_codec *codec)
{
struct ad198x_spec *spec = codec->spec;
int err;
if ((err = snd_hda_parse_pin_def_config(codec, &spec->autocfg, NULL)) < 0)
return err;
if ((err = ad1988_auto_fill_dac_nids(codec, &spec->autocfg)) < 0)
return err;
if (! spec->autocfg.line_outs)
return 0; /* can't find valid BIOS pin config */
if ((err = ad1988_auto_create_multi_out_ctls(spec, &spec->autocfg)) < 0 ||
(err = ad1988_auto_create_extra_out(codec,
spec->autocfg.speaker_pins[0],
"Speaker")) < 0 ||
(err = ad1988_auto_create_extra_out(codec, spec->autocfg.hp_pins[0],
"Headphone")) < 0 ||
(err = ad1988_auto_create_analog_input_ctls(spec, &spec->autocfg)) < 0)
return err;
spec->multiout.max_channels = spec->multiout.num_dacs * 2;
if (spec->autocfg.dig_outs)
spec->multiout.dig_out_nid = AD1988_SPDIF_OUT;
if (spec->autocfg.dig_in_pin)
spec->dig_in_nid = AD1988_SPDIF_IN;
if (spec->kctls.list)
spec->mixers[spec->num_mixers++] = spec->kctls.list;
spec->init_verbs[spec->num_init_verbs++] = ad1988_6stack_init_verbs;
spec->input_mux = &spec->private_imux;
return 1;
}
/* init callback for auto-configuration model -- overriding the default init */
static int ad1988_auto_init(struct hda_codec *codec)
{
ad198x_init(codec);
ad1988_auto_init_multi_out(codec);
ad1988_auto_init_extra_out(codec);
ad1988_auto_init_analog_input(codec);
return 0;
}
/*
*/
static const char *ad1988_models[AD1988_MODEL_LAST] = {
[AD1988_6STACK] = "6stack",
[AD1988_6STACK_DIG] = "6stack-dig",
[AD1988_3STACK] = "3stack",
[AD1988_3STACK_DIG] = "3stack-dig",
[AD1988_LAPTOP] = "laptop",
[AD1988_LAPTOP_DIG] = "laptop-dig",
[AD1988_AUTO] = "auto",
};
static struct snd_pci_quirk ad1988_cfg_tbl[] = {
SND_PCI_QUIRK(0x1043, 0x81ec, "Asus P5B-DLX", AD1988_6STACK_DIG),
SND_PCI_QUIRK(0x1043, 0x81f6, "Asus M2N-SLI", AD1988_6STACK_DIG),
SND_PCI_QUIRK(0x1043, 0x8277, "Asus P5K-E/WIFI-AP", AD1988_6STACK_DIG),
SND_PCI_QUIRK(0x1043, 0x8311, "Asus P5Q-Premium/Pro", AD1988_6STACK_DIG),
{}
};
static int patch_ad1988(struct hda_codec *codec)
{
struct ad198x_spec *spec;
int err, board_config;
spec = kzalloc(sizeof(*spec), GFP_KERNEL);
if (spec == NULL)
return -ENOMEM;
codec->spec = spec;
if (is_rev2(codec))
snd_printk(KERN_INFO "patch_analog: AD1988A rev.2 is detected, enable workarounds\n");
board_config = snd_hda_check_board_config(codec, AD1988_MODEL_LAST,
ad1988_models, ad1988_cfg_tbl);
if (board_config < 0) {
printk(KERN_INFO "hda_codec: %s: BIOS auto-probing.\n",
codec->chip_name);
board_config = AD1988_AUTO;
}
if (board_config == AD1988_AUTO) {
/* automatic parse from the BIOS config */
err = ad1988_parse_auto_config(codec);
if (err < 0) {
ad198x_free(codec);
return err;
} else if (! err) {
printk(KERN_INFO "hda_codec: Cannot set up configuration from BIOS. Using 6-stack mode...\n");
board_config = AD1988_6STACK;
}
}
err = snd_hda_attach_beep_device(codec, 0x10);
if (err < 0) {
ad198x_free(codec);
return err;
}
set_beep_amp(spec, 0x10, 0, HDA_OUTPUT);
switch (board_config) {
case AD1988_6STACK:
case AD1988_6STACK_DIG:
spec->multiout.max_channels = 8;
spec->multiout.num_dacs = 4;
if (is_rev2(codec))
spec->multiout.dac_nids = ad1988_6stack_dac_nids_rev2;
else
spec->multiout.dac_nids = ad1988_6stack_dac_nids;
spec->input_mux = &ad1988_6stack_capture_source;
spec->num_mixers = 2;
if (is_rev2(codec))
spec->mixers[0] = ad1988_6stack_mixers1_rev2;
else
spec->mixers[0] = ad1988_6stack_mixers1;
spec->mixers[1] = ad1988_6stack_mixers2;
spec->num_init_verbs = 1;
spec->init_verbs[0] = ad1988_6stack_init_verbs;
if (board_config == AD1988_6STACK_DIG) {
spec->multiout.dig_out_nid = AD1988_SPDIF_OUT;
spec->dig_in_nid = AD1988_SPDIF_IN;
}
break;
case AD1988_3STACK:
case AD1988_3STACK_DIG:
spec->multiout.max_channels = 6;
spec->multiout.num_dacs = 3;
if (is_rev2(codec))
spec->multiout.dac_nids = ad1988_3stack_dac_nids_rev2;
else
spec->multiout.dac_nids = ad1988_3stack_dac_nids;
spec->input_mux = &ad1988_6stack_capture_source;
spec->channel_mode = ad1988_3stack_modes;
spec->num_channel_mode = ARRAY_SIZE(ad1988_3stack_modes);
spec->num_mixers = 2;
if (is_rev2(codec))
spec->mixers[0] = ad1988_3stack_mixers1_rev2;
else
spec->mixers[0] = ad1988_3stack_mixers1;
spec->mixers[1] = ad1988_3stack_mixers2;
spec->num_init_verbs = 1;
spec->init_verbs[0] = ad1988_3stack_init_verbs;
if (board_config == AD1988_3STACK_DIG)
spec->multiout.dig_out_nid = AD1988_SPDIF_OUT;
break;
case AD1988_LAPTOP:
case AD1988_LAPTOP_DIG:
spec->multiout.max_channels = 2;
spec->multiout.num_dacs = 1;
spec->multiout.dac_nids = ad1988_3stack_dac_nids;
spec->input_mux = &ad1988_laptop_capture_source;
spec->num_mixers = 1;
spec->mixers[0] = ad1988_laptop_mixers;
spec->inv_eapd = 1; /* inverted EAPD */
spec->num_init_verbs = 1;
spec->init_verbs[0] = ad1988_laptop_init_verbs;
if (board_config == AD1988_LAPTOP_DIG)
spec->multiout.dig_out_nid = AD1988_SPDIF_OUT;
break;
}
spec->num_adc_nids = ARRAY_SIZE(ad1988_adc_nids);
spec->adc_nids = ad1988_adc_nids;
spec->capsrc_nids = ad1988_capsrc_nids;
spec->mixers[spec->num_mixers++] = ad1988_capture_mixers;
spec->init_verbs[spec->num_init_verbs++] = ad1988_capture_init_verbs;
if (spec->multiout.dig_out_nid) {
if (codec->vendor_id >= 0x11d4989a) {
spec->mixers[spec->num_mixers++] =
ad1989_spdif_out_mixers;
spec->init_verbs[spec->num_init_verbs++] =
ad1989_spdif_init_verbs;
codec->slave_dig_outs = ad1989b_slave_dig_outs;
} else {
spec->mixers[spec->num_mixers++] =
ad1988_spdif_out_mixers;
spec->init_verbs[spec->num_init_verbs++] =
ad1988_spdif_init_verbs;
}
}
if (spec->dig_in_nid && codec->vendor_id < 0x11d4989a) {
spec->mixers[spec->num_mixers++] = ad1988_spdif_in_mixers;
spec->init_verbs[spec->num_init_verbs++] =
ad1988_spdif_in_init_verbs;
}
codec->patch_ops = ad198x_patch_ops;
switch (board_config) {
case AD1988_AUTO:
codec->patch_ops.init = ad1988_auto_init;
break;
case AD1988_LAPTOP:
case AD1988_LAPTOP_DIG:
codec->patch_ops.unsol_event = ad1988_laptop_unsol_event;
break;
}
#ifdef CONFIG_SND_HDA_POWER_SAVE
spec->loopback.amplist = ad1988_loopbacks;
#endif
spec->vmaster_nid = 0x04;
codec->no_trigger_sense = 1;
return 0;
}
/*
* AD1884 / AD1984
*
* port-B - front line/mic-in
* port-E - aux in/out
* port-F - aux in/out
* port-C - rear line/mic-in
* port-D - rear line/hp-out
* port-A - front line/hp-out
*
* AD1984 = AD1884 + two digital mic-ins
*
* FIXME:
* For simplicity, we share the single DAC for both HP and line-outs
* right now. The inidividual playbacks could be easily implemented,
* but no build-up framework is given, so far.
*/
static hda_nid_t ad1884_dac_nids[1] = {
0x04,
};
static hda_nid_t ad1884_adc_nids[2] = {
0x08, 0x09,
};
static hda_nid_t ad1884_capsrc_nids[2] = {
0x0c, 0x0d,
};
#define AD1884_SPDIF_OUT 0x02
static struct hda_input_mux ad1884_capture_source = {
.num_items = 4,
.items = {
{ "Front Mic", 0x0 },
{ "Mic", 0x1 },
{ "CD", 0x2 },
{ "Mix", 0x3 },
},
};
static struct snd_kcontrol_new ad1884_base_mixers[] = {
HDA_CODEC_VOLUME("PCM Playback Volume", 0x04, 0x0, HDA_OUTPUT),
/* HDA_CODEC_VOLUME_IDX("PCM Playback Volume", 1, 0x03, 0x0, HDA_OUTPUT), */
HDA_CODEC_MUTE("Headphone Playback Switch", 0x11, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Front Playback Switch", 0x12, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_MONO("Mono Playback Volume", 0x13, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE_MONO("Mono Playback Switch", 0x13, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Front Mic Playback Volume", 0x20, 0x00, HDA_INPUT),
HDA_CODEC_MUTE("Front Mic Playback Switch", 0x20, 0x00, HDA_INPUT),
HDA_CODEC_VOLUME("Mic Playback Volume", 0x20, 0x01, HDA_INPUT),
HDA_CODEC_MUTE("Mic Playback Switch", 0x20, 0x01, HDA_INPUT),
HDA_CODEC_VOLUME("CD Playback Volume", 0x20, 0x02, HDA_INPUT),
HDA_CODEC_MUTE("CD Playback Switch", 0x20, 0x02, HDA_INPUT),
HDA_CODEC_VOLUME("Mic Boost", 0x15, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Front Mic Boost", 0x14, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Capture Volume", 0x0c, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Capture Switch", 0x0c, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_IDX("Capture Volume", 1, 0x0d, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE_IDX("Capture Switch", 1, 0x0d, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
/* The multiple "Capture Source" controls confuse alsamixer
* So call somewhat different..
*/
/* .name = "Capture Source", */
.name = "Input Source",
.count = 2,
.info = ad198x_mux_enum_info,
.get = ad198x_mux_enum_get,
.put = ad198x_mux_enum_put,
},
/* SPDIF controls */
HDA_CODEC_VOLUME("IEC958 Playback Volume", 0x1b, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "Source",
/* identical with ad1983 */
.info = ad1983_spdif_route_info,
.get = ad1983_spdif_route_get,
.put = ad1983_spdif_route_put,
},
{ } /* end */
};
static struct snd_kcontrol_new ad1984_dmic_mixers[] = {
HDA_CODEC_VOLUME("Digital Mic Capture Volume", 0x05, 0x0, HDA_INPUT),
HDA_CODEC_MUTE("Digital Mic Capture Switch", 0x05, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME_IDX("Digital Mic Capture Volume", 1, 0x06, 0x0,
HDA_INPUT),
HDA_CODEC_MUTE_IDX("Digital Mic Capture Switch", 1, 0x06, 0x0,
HDA_INPUT),
{ } /* end */
};
/*
* initialization verbs
*/
static struct hda_verb ad1884_init_verbs[] = {
/* DACs; mute as default */
{0x03, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_ZERO},
{0x04, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_ZERO},
/* Port-A (HP) mixer */
{0x07, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(0)},
{0x07, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(1)},
/* Port-A pin */
{0x11, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_HP},
{0x11, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* HP selector - select DAC2 */
{0x22, AC_VERB_SET_CONNECT_SEL, 0x1},
/* Port-D (Line-out) mixer */
{0x0a, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(0)},
{0x0a, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(1)},
/* Port-D pin */
{0x12, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_HP},
{0x12, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* Mono-out mixer */
{0x1e, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(0)},
{0x1e, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(1)},
/* Mono-out pin */
{0x13, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_HP},
{0x13, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* Mono selector */
{0x0e, AC_VERB_SET_CONNECT_SEL, 0x1},
/* Port-B (front mic) pin */
{0x14, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80},
{0x14, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(0)},
/* Port-C (rear mic) pin */
{0x15, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80},
{0x15, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(0)},
/* Analog mixer; mute as default */
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(2)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(3)},
/* Analog Mix output amp */
{0x21, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE | 0x1f}, /* 0dB */
/* SPDIF output selector */
{0x02, AC_VERB_SET_CONNECT_SEL, 0x0}, /* PCM */
{0x1b, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE | 0x27}, /* 0dB */
{ } /* end */
};
#ifdef CONFIG_SND_HDA_POWER_SAVE
static struct hda_amp_list ad1884_loopbacks[] = {
{ 0x20, HDA_INPUT, 0 }, /* Front Mic */
{ 0x20, HDA_INPUT, 1 }, /* Mic */
{ 0x20, HDA_INPUT, 2 }, /* CD */
{ 0x20, HDA_INPUT, 4 }, /* Docking */
{ } /* end */
};
#endif
static const char *ad1884_slave_vols[] = {
"PCM Playback Volume",
"Mic Playback Volume",
"Mono Playback Volume",
"Front Mic Playback Volume",
"Mic Playback Volume",
"CD Playback Volume",
"Internal Mic Playback Volume",
"Docking Mic Playback Volume",
/* "Beep Playback Volume", */
"IEC958 Playback Volume",
NULL
};
static int patch_ad1884(struct hda_codec *codec)
{
struct ad198x_spec *spec;
int err;
spec = kzalloc(sizeof(*spec), GFP_KERNEL);
if (spec == NULL)
return -ENOMEM;
codec->spec = spec;
err = snd_hda_attach_beep_device(codec, 0x10);
if (err < 0) {
ad198x_free(codec);
return err;
}
set_beep_amp(spec, 0x10, 0, HDA_OUTPUT);
spec->multiout.max_channels = 2;
spec->multiout.num_dacs = ARRAY_SIZE(ad1884_dac_nids);
spec->multiout.dac_nids = ad1884_dac_nids;
spec->multiout.dig_out_nid = AD1884_SPDIF_OUT;
spec->num_adc_nids = ARRAY_SIZE(ad1884_adc_nids);
spec->adc_nids = ad1884_adc_nids;
spec->capsrc_nids = ad1884_capsrc_nids;
spec->input_mux = &ad1884_capture_source;
spec->num_mixers = 1;
spec->mixers[0] = ad1884_base_mixers;
spec->num_init_verbs = 1;
spec->init_verbs[0] = ad1884_init_verbs;
spec->spdif_route = 0;
#ifdef CONFIG_SND_HDA_POWER_SAVE
spec->loopback.amplist = ad1884_loopbacks;
#endif
spec->vmaster_nid = 0x04;
/* we need to cover all playback volumes */
spec->slave_vols = ad1884_slave_vols;
codec->patch_ops = ad198x_patch_ops;
codec->no_trigger_sense = 1;
return 0;
}
/*
* Lenovo Thinkpad T61/X61
*/
static struct hda_input_mux ad1984_thinkpad_capture_source = {
.num_items = 4,
.items = {
{ "Mic", 0x0 },
{ "Internal Mic", 0x1 },
{ "Mix", 0x3 },
{ "Docking-Station", 0x4 },
},
};
/*
* Dell Precision T3400
*/
static struct hda_input_mux ad1984_dell_desktop_capture_source = {
.num_items = 3,
.items = {
{ "Front Mic", 0x0 },
{ "Line-In", 0x1 },
{ "Mix", 0x3 },
},
};
static struct snd_kcontrol_new ad1984_thinkpad_mixers[] = {
HDA_CODEC_VOLUME("PCM Playback Volume", 0x04, 0x0, HDA_OUTPUT),
/* HDA_CODEC_VOLUME_IDX("PCM Playback Volume", 1, 0x03, 0x0, HDA_OUTPUT), */
HDA_CODEC_MUTE("Headphone Playback Switch", 0x11, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Speaker Playback Switch", 0x12, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Mic Playback Volume", 0x20, 0x00, HDA_INPUT),
HDA_CODEC_MUTE("Mic Playback Switch", 0x20, 0x00, HDA_INPUT),
HDA_CODEC_VOLUME("Internal Mic Playback Volume", 0x20, 0x01, HDA_INPUT),
HDA_CODEC_MUTE("Internal Mic Playback Switch", 0x20, 0x01, HDA_INPUT),
HDA_CODEC_VOLUME("Beep Playback Volume", 0x20, 0x03, HDA_INPUT),
HDA_CODEC_MUTE("Beep Playback Switch", 0x20, 0x03, HDA_INPUT),
HDA_CODEC_VOLUME("Docking Mic Playback Volume", 0x20, 0x04, HDA_INPUT),
HDA_CODEC_MUTE("Docking Mic Playback Switch", 0x20, 0x04, HDA_INPUT),
HDA_CODEC_VOLUME("Mic Boost", 0x14, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Internal Mic Boost", 0x15, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Docking Mic Boost", 0x25, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Capture Volume", 0x0c, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Capture Switch", 0x0c, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_IDX("Capture Volume", 1, 0x0d, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE_IDX("Capture Switch", 1, 0x0d, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
/* The multiple "Capture Source" controls confuse alsamixer
* So call somewhat different..
*/
/* .name = "Capture Source", */
.name = "Input Source",
.count = 2,
.info = ad198x_mux_enum_info,
.get = ad198x_mux_enum_get,
.put = ad198x_mux_enum_put,
},
/* SPDIF controls */
HDA_CODEC_VOLUME("IEC958 Playback Volume", 0x1b, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "Source",
/* identical with ad1983 */
.info = ad1983_spdif_route_info,
.get = ad1983_spdif_route_get,
.put = ad1983_spdif_route_put,
},
{ } /* end */
};
/* additional verbs */
static struct hda_verb ad1984_thinkpad_init_verbs[] = {
/* Port-E (docking station mic) pin */
{0x1c, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80},
{0x1c, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* docking mic boost */
{0x25, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_ZERO},
/* Analog PC Beeper - allow firmware/ACPI beeps */
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(3) | 0x1a},
/* Analog mixer - docking mic; mute as default */
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(4)},
/* enable EAPD bit */
{0x12, AC_VERB_SET_EAPD_BTLENABLE, 0x02},
{ } /* end */
};
/*
* Dell Precision T3400
*/
static struct snd_kcontrol_new ad1984_dell_desktop_mixers[] = {
HDA_CODEC_VOLUME("PCM Playback Volume", 0x04, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Headphone Playback Switch", 0x11, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Speaker Playback Switch", 0x12, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_MONO("Mono Playback Volume", 0x13, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE_MONO("Mono Playback Switch", 0x13, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Front Mic Playback Volume", 0x20, 0x00, HDA_INPUT),
HDA_CODEC_MUTE("Front Mic Playback Switch", 0x20, 0x00, HDA_INPUT),
HDA_CODEC_VOLUME("Line-In Playback Volume", 0x20, 0x01, HDA_INPUT),
HDA_CODEC_MUTE("Line-In Playback Switch", 0x20, 0x01, HDA_INPUT),
HDA_CODEC_VOLUME("Line-In Boost", 0x15, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Front Mic Boost", 0x14, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Capture Volume", 0x0c, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Capture Switch", 0x0c, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_IDX("Capture Volume", 1, 0x0d, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE_IDX("Capture Switch", 1, 0x0d, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
/* The multiple "Capture Source" controls confuse alsamixer
* So call somewhat different..
*/
/* .name = "Capture Source", */
.name = "Input Source",
.count = 2,
.info = ad198x_mux_enum_info,
.get = ad198x_mux_enum_get,
.put = ad198x_mux_enum_put,
},
{ } /* end */
};
/* Digial MIC ADC NID 0x05 + 0x06 */
static int ad1984_pcm_dmic_prepare(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
unsigned int stream_tag,
unsigned int format,
struct snd_pcm_substream *substream)
{
snd_hda_codec_setup_stream(codec, 0x05 + substream->number,
stream_tag, 0, format);
return 0;
}
static int ad1984_pcm_dmic_cleanup(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
snd_hda_codec_cleanup_stream(codec, 0x05 + substream->number);
return 0;
}
static struct hda_pcm_stream ad1984_pcm_dmic_capture = {
.substreams = 2,
.channels_min = 2,
.channels_max = 2,
.nid = 0x05,
.ops = {
.prepare = ad1984_pcm_dmic_prepare,
.cleanup = ad1984_pcm_dmic_cleanup
},
};
static int ad1984_build_pcms(struct hda_codec *codec)
{
struct ad198x_spec *spec = codec->spec;
struct hda_pcm *info;
int err;
err = ad198x_build_pcms(codec);
if (err < 0)
return err;
info = spec->pcm_rec + codec->num_pcms;
codec->num_pcms++;
info->name = "AD1984 Digital Mic";
info->stream[SNDRV_PCM_STREAM_CAPTURE] = ad1984_pcm_dmic_capture;
return 0;
}
/* models */
enum {
AD1984_BASIC,
AD1984_THINKPAD,
AD1984_DELL_DESKTOP,
AD1984_MODELS
};
static const char *ad1984_models[AD1984_MODELS] = {
[AD1984_BASIC] = "basic",
[AD1984_THINKPAD] = "thinkpad",
[AD1984_DELL_DESKTOP] = "dell_desktop",
};
static struct snd_pci_quirk ad1984_cfg_tbl[] = {
/* Lenovo Thinkpad T61/X61 */
SND_PCI_QUIRK_VENDOR(0x17aa, "Lenovo Thinkpad", AD1984_THINKPAD),
SND_PCI_QUIRK(0x1028, 0x0214, "Dell T3400", AD1984_DELL_DESKTOP),
SND_PCI_QUIRK(0x1028, 0x0233, "Dell Latitude E6400", AD1984_DELL_DESKTOP),
{}
};
static int patch_ad1984(struct hda_codec *codec)
{
struct ad198x_spec *spec;
int board_config, err;
err = patch_ad1884(codec);
if (err < 0)
return err;
spec = codec->spec;
board_config = snd_hda_check_board_config(codec, AD1984_MODELS,
ad1984_models, ad1984_cfg_tbl);
switch (board_config) {
case AD1984_BASIC:
/* additional digital mics */
spec->mixers[spec->num_mixers++] = ad1984_dmic_mixers;
codec->patch_ops.build_pcms = ad1984_build_pcms;
break;
case AD1984_THINKPAD:
spec->multiout.dig_out_nid = AD1884_SPDIF_OUT;
spec->input_mux = &ad1984_thinkpad_capture_source;
spec->mixers[0] = ad1984_thinkpad_mixers;
spec->init_verbs[spec->num_init_verbs++] = ad1984_thinkpad_init_verbs;
spec->analog_beep = 1;
break;
case AD1984_DELL_DESKTOP:
spec->multiout.dig_out_nid = 0;
spec->input_mux = &ad1984_dell_desktop_capture_source;
spec->mixers[0] = ad1984_dell_desktop_mixers;
break;
}
return 0;
}
/*
* AD1883 / AD1884A / AD1984A / AD1984B
*
* port-B (0x14) - front mic-in
* port-E (0x1c) - rear mic-in
* port-F (0x16) - CD / ext out
* port-C (0x15) - rear line-in
* port-D (0x12) - rear line-out
* port-A (0x11) - front hp-out
*
* AD1984A = AD1884A + digital-mic
* AD1883 = equivalent with AD1984A
* AD1984B = AD1984A + extra SPDIF-out
*
* FIXME:
* We share the single DAC for both HP and line-outs (see AD1884/1984).
*/
static hda_nid_t ad1884a_dac_nids[1] = {
0x03,
};
#define ad1884a_adc_nids ad1884_adc_nids
#define ad1884a_capsrc_nids ad1884_capsrc_nids
#define AD1884A_SPDIF_OUT 0x02
static struct hda_input_mux ad1884a_capture_source = {
.num_items = 5,
.items = {
{ "Front Mic", 0x0 },
{ "Mic", 0x4 },
{ "Line", 0x1 },
{ "CD", 0x2 },
{ "Mix", 0x3 },
},
};
static struct snd_kcontrol_new ad1884a_base_mixers[] = {
HDA_CODEC_VOLUME("Master Playback Volume", 0x21, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Master Playback Switch", 0x21, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Headphone Playback Switch", 0x11, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Front Playback Switch", 0x12, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_MONO("Mono Playback Volume", 0x13, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE_MONO("Mono Playback Switch", 0x13, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("PCM Playback Volume", 0x20, 0x5, HDA_INPUT),
HDA_CODEC_MUTE("PCM Playback Switch", 0x20, 0x5, HDA_INPUT),
HDA_CODEC_VOLUME("Front Mic Playback Volume", 0x20, 0x00, HDA_INPUT),
HDA_CODEC_MUTE("Front Mic Playback Switch", 0x20, 0x00, HDA_INPUT),
HDA_CODEC_VOLUME("Line Playback Volume", 0x20, 0x01, HDA_INPUT),
HDA_CODEC_MUTE("Line Playback Switch", 0x20, 0x01, HDA_INPUT),
HDA_CODEC_VOLUME("Mic Playback Volume", 0x20, 0x04, HDA_INPUT),
HDA_CODEC_MUTE("Mic Playback Switch", 0x20, 0x04, HDA_INPUT),
HDA_CODEC_VOLUME("CD Playback Volume", 0x20, 0x02, HDA_INPUT),
HDA_CODEC_MUTE("CD Playback Switch", 0x20, 0x02, HDA_INPUT),
HDA_CODEC_VOLUME("Front Mic Boost", 0x14, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Line Boost", 0x15, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Mic Boost", 0x25, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Capture Volume", 0x0c, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Capture Switch", 0x0c, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_IDX("Capture Volume", 1, 0x0d, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE_IDX("Capture Switch", 1, 0x0d, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
/* The multiple "Capture Source" controls confuse alsamixer
* So call somewhat different..
*/
/* .name = "Capture Source", */
.name = "Input Source",
.count = 2,
.info = ad198x_mux_enum_info,
.get = ad198x_mux_enum_get,
.put = ad198x_mux_enum_put,
},
/* SPDIF controls */
HDA_CODEC_VOLUME("IEC958 Playback Volume", 0x1b, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "Source",
/* identical with ad1983 */
.info = ad1983_spdif_route_info,
.get = ad1983_spdif_route_get,
.put = ad1983_spdif_route_put,
},
{ } /* end */
};
/*
* initialization verbs
*/
static struct hda_verb ad1884a_init_verbs[] = {
/* DACs; unmute as default */
{0x03, AC_VERB_SET_AMP_GAIN_MUTE, 0x27}, /* 0dB */
{0x04, AC_VERB_SET_AMP_GAIN_MUTE, 0x27}, /* 0dB */
/* Port-A (HP) mixer - route only from analog mixer */
{0x07, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x07, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(1)},
/* Port-A pin */
{0x11, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_HP},
{0x11, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* Port-D (Line-out) mixer - route only from analog mixer */
{0x0a, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x0a, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(1)},
/* Port-D pin */
{0x12, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_HP},
{0x12, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* Mono-out mixer - route only from analog mixer */
{0x1e, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x1e, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(1)},
/* Mono-out pin */
{0x13, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_HP},
{0x13, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* Port-B (front mic) pin */
{0x14, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80},
{0x14, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(0)},
/* Port-C (rear line-in) pin */
{0x15, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_IN},
{0x15, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(0)},
/* Port-E (rear mic) pin */
{0x1c, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80},
{0x1c, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
{0x25, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_ZERO}, /* no boost */
/* Port-F (CD) pin */
{0x16, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_IN},
{0x16, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* Analog mixer; mute as default */
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(2)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(3)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(4)}, /* aux */
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(5)},
/* Analog Mix output amp */
{0x21, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* capture sources */
{0x0c, AC_VERB_SET_CONNECT_SEL, 0x0},
{0x0c, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
{0x0d, AC_VERB_SET_CONNECT_SEL, 0x0},
{0x0d, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* SPDIF output amp */
{0x1b, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE | 0x27}, /* 0dB */
{ } /* end */
};
#ifdef CONFIG_SND_HDA_POWER_SAVE
static struct hda_amp_list ad1884a_loopbacks[] = {
{ 0x20, HDA_INPUT, 0 }, /* Front Mic */
{ 0x20, HDA_INPUT, 1 }, /* Mic */
{ 0x20, HDA_INPUT, 2 }, /* CD */
{ 0x20, HDA_INPUT, 4 }, /* Docking */
{ } /* end */
};
#endif
/*
* Laptop model
*
* Port A: Headphone jack
* Port B: MIC jack
* Port C: Internal MIC
* Port D: Dock Line Out (if enabled)
* Port E: Dock Line In (if enabled)
* Port F: Internal speakers
*/
static int ad1884a_mobile_master_sw_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
int ret = snd_hda_mixer_amp_switch_put(kcontrol, ucontrol);
int mute = (!ucontrol->value.integer.value[0] &&
!ucontrol->value.integer.value[1]);
/* toggle GPIO1 according to the mute state */
snd_hda_codec_write_cache(codec, 0x01, 0, AC_VERB_SET_GPIO_DATA,
mute ? 0x02 : 0x0);
return ret;
}
static struct snd_kcontrol_new ad1884a_laptop_mixers[] = {
HDA_CODEC_VOLUME("Master Playback Volume", 0x21, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Master Playback Switch",
.subdevice = HDA_SUBDEV_AMP_FLAG,
.info = snd_hda_mixer_amp_switch_info,
.get = snd_hda_mixer_amp_switch_get,
.put = ad1884a_mobile_master_sw_put,
.private_value = HDA_COMPOSE_AMP_VAL(0x21, 3, 0, HDA_OUTPUT),
},
HDA_CODEC_MUTE("Dock Playback Switch", 0x12, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("PCM Playback Volume", 0x20, 0x5, HDA_INPUT),
HDA_CODEC_MUTE("PCM Playback Switch", 0x20, 0x5, HDA_INPUT),
HDA_CODEC_VOLUME("Mic Playback Volume", 0x20, 0x00, HDA_INPUT),
HDA_CODEC_MUTE("Mic Playback Switch", 0x20, 0x00, HDA_INPUT),
HDA_CODEC_VOLUME("Internal Mic Playback Volume", 0x20, 0x01, HDA_INPUT),
HDA_CODEC_MUTE("Internal Mic Playback Switch", 0x20, 0x01, HDA_INPUT),
HDA_CODEC_VOLUME("Dock Mic Playback Volume", 0x20, 0x04, HDA_INPUT),
HDA_CODEC_MUTE("Dock Mic Playback Switch", 0x20, 0x04, HDA_INPUT),
HDA_CODEC_VOLUME("Mic Boost", 0x14, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Internal Mic Boost", 0x15, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Dock Mic Boost", 0x25, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Capture Volume", 0x0c, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Capture Switch", 0x0c, 0x0, HDA_OUTPUT),
{ } /* end */
};
static struct snd_kcontrol_new ad1884a_mobile_mixers[] = {
HDA_CODEC_VOLUME("Master Playback Volume", 0x21, 0x0, HDA_OUTPUT),
/*HDA_CODEC_MUTE("Master Playback Switch", 0x21, 0x0, HDA_OUTPUT),*/
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Master Playback Switch",
.subdevice = HDA_SUBDEV_AMP_FLAG,
.info = snd_hda_mixer_amp_switch_info,
.get = snd_hda_mixer_amp_switch_get,
.put = ad1884a_mobile_master_sw_put,
.private_value = HDA_COMPOSE_AMP_VAL(0x21, 3, 0, HDA_OUTPUT),
},
HDA_CODEC_VOLUME("PCM Playback Volume", 0x20, 0x5, HDA_INPUT),
HDA_CODEC_MUTE("PCM Playback Switch", 0x20, 0x5, HDA_INPUT),
HDA_CODEC_VOLUME("Mic Capture Volume", 0x14, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Internal Mic Capture Volume", 0x15, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Capture Volume", 0x0c, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Capture Switch", 0x0c, 0x0, HDA_OUTPUT),
{ } /* end */
};
/* mute internal speaker if HP is plugged */
static void ad1884a_hp_automute(struct hda_codec *codec)
{
unsigned int present;
present = snd_hda_jack_detect(codec, 0x11);
snd_hda_codec_amp_stereo(codec, 0x16, HDA_OUTPUT, 0,
HDA_AMP_MUTE, present ? HDA_AMP_MUTE : 0);
snd_hda_codec_write(codec, 0x16, 0, AC_VERB_SET_EAPD_BTLENABLE,
present ? 0x00 : 0x02);
}
/* switch to external mic if plugged */
static void ad1884a_hp_automic(struct hda_codec *codec)
{
unsigned int present;
present = snd_hda_jack_detect(codec, 0x14);
snd_hda_codec_write(codec, 0x0c, 0, AC_VERB_SET_CONNECT_SEL,
present ? 0 : 1);
}
#define AD1884A_HP_EVENT 0x37
#define AD1884A_MIC_EVENT 0x36
/* unsolicited event for HP jack sensing */
static void ad1884a_hp_unsol_event(struct hda_codec *codec, unsigned int res)
{
switch (res >> 26) {
case AD1884A_HP_EVENT:
ad1884a_hp_automute(codec);
break;
case AD1884A_MIC_EVENT:
ad1884a_hp_automic(codec);
break;
}
}
/* initialize jack-sensing, too */
static int ad1884a_hp_init(struct hda_codec *codec)
{
ad198x_init(codec);
ad1884a_hp_automute(codec);
ad1884a_hp_automic(codec);
return 0;
}
/* mute internal speaker if HP or docking HP is plugged */
static void ad1884a_laptop_automute(struct hda_codec *codec)
{
unsigned int present;
present = snd_hda_jack_detect(codec, 0x11);
if (!present)
present = snd_hda_jack_detect(codec, 0x12);
snd_hda_codec_amp_stereo(codec, 0x16, HDA_OUTPUT, 0,
HDA_AMP_MUTE, present ? HDA_AMP_MUTE : 0);
snd_hda_codec_write(codec, 0x16, 0, AC_VERB_SET_EAPD_BTLENABLE,
present ? 0x00 : 0x02);
}
/* switch to external mic if plugged */
static void ad1884a_laptop_automic(struct hda_codec *codec)
{
unsigned int idx;
if (snd_hda_jack_detect(codec, 0x14))
idx = 0;
else if (snd_hda_jack_detect(codec, 0x1c))
idx = 4;
else
idx = 1;
snd_hda_codec_write(codec, 0x0c, 0, AC_VERB_SET_CONNECT_SEL, idx);
}
/* unsolicited event for HP jack sensing */
static void ad1884a_laptop_unsol_event(struct hda_codec *codec,
unsigned int res)
{
switch (res >> 26) {
case AD1884A_HP_EVENT:
ad1884a_laptop_automute(codec);
break;
case AD1884A_MIC_EVENT:
ad1884a_laptop_automic(codec);
break;
}
}
/* initialize jack-sensing, too */
static int ad1884a_laptop_init(struct hda_codec *codec)
{
ad198x_init(codec);
ad1884a_laptop_automute(codec);
ad1884a_laptop_automic(codec);
return 0;
}
/* additional verbs for laptop model */
static struct hda_verb ad1884a_laptop_verbs[] = {
/* Port-A (HP) pin - always unmuted */
{0x11, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
/* Port-F (int speaker) mixer - route only from analog mixer */
{0x0b, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x0b, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(1)},
/* Port-F (int speaker) pin */
{0x16, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT},
{0x16, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* required for compaq 6530s/6531s speaker output */
{0x1c, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT},
/* Port-C pin - internal mic-in */
{0x15, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80},
{0x14, AC_VERB_SET_AMP_GAIN_MUTE, 0x7002}, /* raise mic as default */
{0x15, AC_VERB_SET_AMP_GAIN_MUTE, 0x7002}, /* raise mic as default */
/* Port-D (docking line-out) pin - default unmuted */
{0x12, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
/* analog mix */
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(4)},
/* unsolicited event for pin-sense */
{0x11, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | AD1884A_HP_EVENT},
{0x12, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | AD1884A_HP_EVENT},
{0x14, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | AD1884A_MIC_EVENT},
{0x1c, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | AD1884A_MIC_EVENT},
/* allow to touch GPIO1 (for mute control) */
{0x01, AC_VERB_SET_GPIO_MASK, 0x02},
{0x01, AC_VERB_SET_GPIO_DIRECTION, 0x02},
{0x01, AC_VERB_SET_GPIO_DATA, 0x02}, /* first muted */
{ } /* end */
};
static struct hda_verb ad1884a_mobile_verbs[] = {
/* DACs; unmute as default */
{0x03, AC_VERB_SET_AMP_GAIN_MUTE, 0x27}, /* 0dB */
{0x04, AC_VERB_SET_AMP_GAIN_MUTE, 0x27}, /* 0dB */
/* Port-A (HP) mixer - route only from analog mixer */
{0x07, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x07, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(1)},
/* Port-A pin */
{0x11, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_HP},
/* Port-A (HP) pin - always unmuted */
{0x11, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
/* Port-B (mic jack) pin */
{0x14, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80},
{0x14, AC_VERB_SET_AMP_GAIN_MUTE, 0x7002}, /* raise mic as default */
/* Port-C (int mic) pin */
{0x15, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80},
{0x15, AC_VERB_SET_AMP_GAIN_MUTE, 0x7002}, /* raise mic as default */
/* Port-F (int speaker) mixer - route only from analog mixer */
{0x0b, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x0b, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(1)},
/* Port-F pin */
{0x16, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_HP},
{0x16, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* Analog mixer; mute as default */
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(2)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(3)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(4)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(5)},
/* Analog Mix output amp */
{0x21, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* capture sources */
/* {0x0c, AC_VERB_SET_CONNECT_SEL, 0x0}, */ /* set via unsol */
{0x0c, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
{0x0d, AC_VERB_SET_CONNECT_SEL, 0x0},
{0x0d, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* unsolicited event for pin-sense */
{0x11, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | AD1884A_HP_EVENT},
{0x14, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | AD1884A_MIC_EVENT},
/* allow to touch GPIO1 (for mute control) */
{0x01, AC_VERB_SET_GPIO_MASK, 0x02},
{0x01, AC_VERB_SET_GPIO_DIRECTION, 0x02},
{0x01, AC_VERB_SET_GPIO_DATA, 0x02}, /* first muted */
{ } /* end */
};
/*
* Thinkpad X300
* 0x11 - HP
* 0x12 - speaker
* 0x14 - mic-in
* 0x17 - built-in mic
*/
static struct hda_verb ad1984a_thinkpad_verbs[] = {
/* HP unmute */
{0x11, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
/* analog mix */
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(4)},
/* turn on EAPD */
{0x12, AC_VERB_SET_EAPD_BTLENABLE, 0x02},
/* unsolicited event for pin-sense */
{0x11, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | AD1884A_HP_EVENT},
/* internal mic - dmic */
{0x17, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_IN},
/* set magic COEFs for dmic */
{0x01, AC_VERB_SET_COEF_INDEX, 0x13f7},
{0x01, AC_VERB_SET_PROC_COEF, 0x08},
{ } /* end */
};
static struct snd_kcontrol_new ad1984a_thinkpad_mixers[] = {
HDA_CODEC_VOLUME("Master Playback Volume", 0x21, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Master Playback Switch", 0x21, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("PCM Playback Volume", 0x20, 0x5, HDA_INPUT),
HDA_CODEC_MUTE("PCM Playback Switch", 0x20, 0x5, HDA_INPUT),
HDA_CODEC_VOLUME("Mic Playback Volume", 0x20, 0x00, HDA_INPUT),
HDA_CODEC_MUTE("Mic Playback Switch", 0x20, 0x00, HDA_INPUT),
HDA_CODEC_VOLUME("Mic Boost", 0x14, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Internal Mic Boost", 0x17, 0x0, HDA_INPUT),
HDA_CODEC_VOLUME("Capture Volume", 0x0c, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Capture Switch", 0x0c, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Capture Source",
.info = ad198x_mux_enum_info,
.get = ad198x_mux_enum_get,
.put = ad198x_mux_enum_put,
},
{ } /* end */
};
static struct hda_input_mux ad1984a_thinkpad_capture_source = {
.num_items = 3,
.items = {
{ "Mic", 0x0 },
{ "Internal Mic", 0x5 },
{ "Mix", 0x3 },
},
};
/* mute internal speaker if HP is plugged */
static void ad1984a_thinkpad_automute(struct hda_codec *codec)
{
unsigned int present;
present = snd_hda_jack_detect(codec, 0x11);
snd_hda_codec_amp_stereo(codec, 0x12, HDA_OUTPUT, 0,
HDA_AMP_MUTE, present ? HDA_AMP_MUTE : 0);
}
/* unsolicited event for HP jack sensing */
static void ad1984a_thinkpad_unsol_event(struct hda_codec *codec,
unsigned int res)
{
if ((res >> 26) != AD1884A_HP_EVENT)
return;
ad1984a_thinkpad_automute(codec);
}
/* initialize jack-sensing, too */
static int ad1984a_thinkpad_init(struct hda_codec *codec)
{
ad198x_init(codec);
ad1984a_thinkpad_automute(codec);
return 0;
}
/*
* HP Touchsmart
* port-A (0x11) - front hp-out
* port-B (0x14) - unused
* port-C (0x15) - unused
* port-D (0x12) - rear line out
* port-E (0x1c) - front mic-in
* port-F (0x16) - Internal speakers
* digital-mic (0x17) - Internal mic
*/
static struct hda_verb ad1984a_touchsmart_verbs[] = {
/* DACs; unmute as default */
{0x03, AC_VERB_SET_AMP_GAIN_MUTE, 0x27}, /* 0dB */
{0x04, AC_VERB_SET_AMP_GAIN_MUTE, 0x27}, /* 0dB */
/* Port-A (HP) mixer - route only from analog mixer */
{0x07, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x07, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(1)},
/* Port-A pin */
{0x11, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_HP},
/* Port-A (HP) pin - always unmuted */
{0x11, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
/* Port-E (int speaker) mixer - route only from analog mixer */
{0x25, AC_VERB_SET_AMP_GAIN_MUTE, 0x03},
/* Port-E pin */
{0x1c, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_IN},
{0x1c, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE},
{0x1c, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80},
/* Port-F (int speaker) mixer - route only from analog mixer */
{0x0b, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x0b, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(1)},
/* Port-F pin */
{0x16, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_HP},
{0x16, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* Analog mixer; mute as default */
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(2)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(3)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(4)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(5)},
/* Analog Mix output amp */
{0x21, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* capture sources */
/* {0x0c, AC_VERB_SET_CONNECT_SEL, 0x0}, */ /* set via unsol */
{0x0c, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
{0x0d, AC_VERB_SET_CONNECT_SEL, 0x0},
{0x0d, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* unsolicited event for pin-sense */
{0x11, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | AD1884A_HP_EVENT},
{0x1c, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | AD1884A_MIC_EVENT},
/* allow to touch GPIO1 (for mute control) */
{0x01, AC_VERB_SET_GPIO_MASK, 0x02},
{0x01, AC_VERB_SET_GPIO_DIRECTION, 0x02},
{0x01, AC_VERB_SET_GPIO_DATA, 0x02}, /* first muted */
/* internal mic - dmic */
{0x17, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_IN},
/* set magic COEFs for dmic */
{0x01, AC_VERB_SET_COEF_INDEX, 0x13f7},
{0x01, AC_VERB_SET_PROC_COEF, 0x08},
{ } /* end */
};
static struct snd_kcontrol_new ad1984a_touchsmart_mixers[] = {
HDA_CODEC_VOLUME("Master Playback Volume", 0x21, 0x0, HDA_OUTPUT),
/* HDA_CODEC_MUTE("Master Playback Switch", 0x21, 0x0, HDA_OUTPUT),*/
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.subdevice = HDA_SUBDEV_AMP_FLAG,
.name = "Master Playback Switch",
.info = snd_hda_mixer_amp_switch_info,
.get = snd_hda_mixer_amp_switch_get,
.put = ad1884a_mobile_master_sw_put,
.private_value = HDA_COMPOSE_AMP_VAL(0x21, 3, 0, HDA_OUTPUT),
},
HDA_CODEC_VOLUME("PCM Playback Volume", 0x20, 0x5, HDA_INPUT),
HDA_CODEC_MUTE("PCM Playback Switch", 0x20, 0x5, HDA_INPUT),
HDA_CODEC_VOLUME("Capture Volume", 0x0c, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Capture Switch", 0x0c, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Mic Boost", 0x25, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Internal Mic Boost", 0x17, 0x0, HDA_INPUT),
{ } /* end */
};
/* switch to external mic if plugged */
static void ad1984a_touchsmart_automic(struct hda_codec *codec)
{
if (snd_hda_jack_detect(codec, 0x1c))
snd_hda_codec_write(codec, 0x0c, 0,
AC_VERB_SET_CONNECT_SEL, 0x4);
else
snd_hda_codec_write(codec, 0x0c, 0,
AC_VERB_SET_CONNECT_SEL, 0x5);
}
/* unsolicited event for HP jack sensing */
static void ad1984a_touchsmart_unsol_event(struct hda_codec *codec,
unsigned int res)
{
switch (res >> 26) {
case AD1884A_HP_EVENT:
ad1884a_hp_automute(codec);
break;
case AD1884A_MIC_EVENT:
ad1984a_touchsmart_automic(codec);
break;
}
}
/* initialize jack-sensing, too */
static int ad1984a_touchsmart_init(struct hda_codec *codec)
{
ad198x_init(codec);
ad1884a_hp_automute(codec);
ad1984a_touchsmart_automic(codec);
return 0;
}
/*
*/
enum {
AD1884A_DESKTOP,
AD1884A_LAPTOP,
AD1884A_MOBILE,
AD1884A_THINKPAD,
AD1984A_TOUCHSMART,
AD1884A_MODELS
};
static const char *ad1884a_models[AD1884A_MODELS] = {
[AD1884A_DESKTOP] = "desktop",
[AD1884A_LAPTOP] = "laptop",
[AD1884A_MOBILE] = "mobile",
[AD1884A_THINKPAD] = "thinkpad",
[AD1984A_TOUCHSMART] = "touchsmart",
};
static struct snd_pci_quirk ad1884a_cfg_tbl[] = {
SND_PCI_QUIRK(0x103c, 0x3030, "HP", AD1884A_MOBILE),
SND_PCI_QUIRK(0x103c, 0x3037, "HP 2230s", AD1884A_LAPTOP),
SND_PCI_QUIRK(0x103c, 0x3056, "HP", AD1884A_MOBILE),
SND_PCI_QUIRK_MASK(0x103c, 0xfff0, 0x3070, "HP", AD1884A_MOBILE),
SND_PCI_QUIRK_MASK(0x103c, 0xfff0, 0x30d0, "HP laptop", AD1884A_LAPTOP),
SND_PCI_QUIRK_MASK(0x103c, 0xfff0, 0x30e0, "HP laptop", AD1884A_LAPTOP),
SND_PCI_QUIRK_MASK(0x103c, 0xff00, 0x3600, "HP laptop", AD1884A_LAPTOP),
SND_PCI_QUIRK_MASK(0x103c, 0xfff0, 0x7010, "HP laptop", AD1884A_MOBILE),
SND_PCI_QUIRK(0x17aa, 0x20ac, "Thinkpad X300", AD1884A_THINKPAD),
SND_PCI_QUIRK(0x103c, 0x2a82, "Touchsmart", AD1984A_TOUCHSMART),
{}
};
static int patch_ad1884a(struct hda_codec *codec)
{
struct ad198x_spec *spec;
int err, board_config;
spec = kzalloc(sizeof(*spec), GFP_KERNEL);
if (spec == NULL)
return -ENOMEM;
codec->spec = spec;
err = snd_hda_attach_beep_device(codec, 0x10);
if (err < 0) {
ad198x_free(codec);
return err;
}
set_beep_amp(spec, 0x10, 0, HDA_OUTPUT);
spec->multiout.max_channels = 2;
spec->multiout.num_dacs = ARRAY_SIZE(ad1884a_dac_nids);
spec->multiout.dac_nids = ad1884a_dac_nids;
spec->multiout.dig_out_nid = AD1884A_SPDIF_OUT;
spec->num_adc_nids = ARRAY_SIZE(ad1884a_adc_nids);
spec->adc_nids = ad1884a_adc_nids;
spec->capsrc_nids = ad1884a_capsrc_nids;
spec->input_mux = &ad1884a_capture_source;
spec->num_mixers = 1;
spec->mixers[0] = ad1884a_base_mixers;
spec->num_init_verbs = 1;
spec->init_verbs[0] = ad1884a_init_verbs;
spec->spdif_route = 0;
#ifdef CONFIG_SND_HDA_POWER_SAVE
spec->loopback.amplist = ad1884a_loopbacks;
#endif
codec->patch_ops = ad198x_patch_ops;
/* override some parameters */
board_config = snd_hda_check_board_config(codec, AD1884A_MODELS,
ad1884a_models,
ad1884a_cfg_tbl);
switch (board_config) {
case AD1884A_LAPTOP:
spec->mixers[0] = ad1884a_laptop_mixers;
spec->init_verbs[spec->num_init_verbs++] = ad1884a_laptop_verbs;
spec->multiout.dig_out_nid = 0;
codec->patch_ops.unsol_event = ad1884a_laptop_unsol_event;
codec->patch_ops.init = ad1884a_laptop_init;
/* set the upper-limit for mixer amp to 0dB for avoiding the
* possible damage by overloading
*/
snd_hda_override_amp_caps(codec, 0x20, HDA_INPUT,
(0x17 << AC_AMPCAP_OFFSET_SHIFT) |
(0x17 << AC_AMPCAP_NUM_STEPS_SHIFT) |
(0x05 << AC_AMPCAP_STEP_SIZE_SHIFT) |
(1 << AC_AMPCAP_MUTE_SHIFT));
break;
case AD1884A_MOBILE:
spec->mixers[0] = ad1884a_mobile_mixers;
spec->init_verbs[0] = ad1884a_mobile_verbs;
spec->multiout.dig_out_nid = 0;
codec->patch_ops.unsol_event = ad1884a_hp_unsol_event;
codec->patch_ops.init = ad1884a_hp_init;
/* set the upper-limit for mixer amp to 0dB for avoiding the
* possible damage by overloading
*/
snd_hda_override_amp_caps(codec, 0x20, HDA_INPUT,
(0x17 << AC_AMPCAP_OFFSET_SHIFT) |
(0x17 << AC_AMPCAP_NUM_STEPS_SHIFT) |
(0x05 << AC_AMPCAP_STEP_SIZE_SHIFT) |
(1 << AC_AMPCAP_MUTE_SHIFT));
break;
case AD1884A_THINKPAD:
spec->mixers[0] = ad1984a_thinkpad_mixers;
spec->init_verbs[spec->num_init_verbs++] =
ad1984a_thinkpad_verbs;
spec->multiout.dig_out_nid = 0;
spec->input_mux = &ad1984a_thinkpad_capture_source;
codec->patch_ops.unsol_event = ad1984a_thinkpad_unsol_event;
codec->patch_ops.init = ad1984a_thinkpad_init;
break;
case AD1984A_TOUCHSMART:
spec->mixers[0] = ad1984a_touchsmart_mixers;
spec->init_verbs[0] = ad1984a_touchsmart_verbs;
spec->multiout.dig_out_nid = 0;
codec->patch_ops.unsol_event = ad1984a_touchsmart_unsol_event;
codec->patch_ops.init = ad1984a_touchsmart_init;
/* set the upper-limit for mixer amp to 0dB for avoiding the
* possible damage by overloading
*/
snd_hda_override_amp_caps(codec, 0x20, HDA_INPUT,
(0x17 << AC_AMPCAP_OFFSET_SHIFT) |
(0x17 << AC_AMPCAP_NUM_STEPS_SHIFT) |
(0x05 << AC_AMPCAP_STEP_SIZE_SHIFT) |
(1 << AC_AMPCAP_MUTE_SHIFT));
break;
}
codec->no_trigger_sense = 1;
return 0;
}
/*
* AD1882 / AD1882A
*
* port-A - front hp-out
* port-B - front mic-in
* port-C - rear line-in, shared surr-out (3stack)
* port-D - rear line-out
* port-E - rear mic-in, shared clfe-out (3stack)
* port-F - rear surr-out (6stack)
* port-G - rear clfe-out (6stack)
*/
static hda_nid_t ad1882_dac_nids[3] = {
0x04, 0x03, 0x05
};
static hda_nid_t ad1882_adc_nids[2] = {
0x08, 0x09,
};
static hda_nid_t ad1882_capsrc_nids[2] = {
0x0c, 0x0d,
};
#define AD1882_SPDIF_OUT 0x02
/* list: 0x11, 0x39, 0x3a, 0x18, 0x3c, 0x3b, 0x12, 0x20 */
static struct hda_input_mux ad1882_capture_source = {
.num_items = 5,
.items = {
{ "Front Mic", 0x1 },
{ "Mic", 0x4 },
{ "Line", 0x2 },
{ "CD", 0x3 },
{ "Mix", 0x7 },
},
};
/* list: 0x11, 0x39, 0x3a, 0x3c, 0x18, 0x1f, 0x12, 0x20 */
static struct hda_input_mux ad1882a_capture_source = {
.num_items = 5,
.items = {
{ "Front Mic", 0x1 },
{ "Mic", 0x4},
{ "Line", 0x2 },
{ "Digital Mic", 0x06 },
{ "Mix", 0x7 },
},
};
static struct snd_kcontrol_new ad1882_base_mixers[] = {
HDA_CODEC_VOLUME("Front Playback Volume", 0x04, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Surround Playback Volume", 0x03, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_MONO("Center Playback Volume", 0x05, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_MONO("LFE Playback Volume", 0x05, 2, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Headphone Playback Switch", 0x11, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Front Playback Switch", 0x12, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_MONO("Mono Playback Volume", 0x13, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE_MONO("Mono Playback Switch", 0x13, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Mic Boost", 0x3c, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Front Mic Boost", 0x39, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Line-In Boost", 0x3a, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME("Capture Volume", 0x0c, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE("Capture Switch", 0x0c, 0x0, HDA_OUTPUT),
HDA_CODEC_VOLUME_IDX("Capture Volume", 1, 0x0d, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE_IDX("Capture Switch", 1, 0x0d, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
/* The multiple "Capture Source" controls confuse alsamixer
* So call somewhat different..
*/
/* .name = "Capture Source", */
.name = "Input Source",
.count = 2,
.info = ad198x_mux_enum_info,
.get = ad198x_mux_enum_get,
.put = ad198x_mux_enum_put,
},
/* SPDIF controls */
HDA_CODEC_VOLUME("IEC958 Playback Volume", 0x1b, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "Source",
/* identical with ad1983 */
.info = ad1983_spdif_route_info,
.get = ad1983_spdif_route_get,
.put = ad1983_spdif_route_put,
},
{ } /* end */
};
static struct snd_kcontrol_new ad1882_loopback_mixers[] = {
HDA_CODEC_VOLUME("Front Mic Playback Volume", 0x20, 0x00, HDA_INPUT),
HDA_CODEC_MUTE("Front Mic Playback Switch", 0x20, 0x00, HDA_INPUT),
HDA_CODEC_VOLUME("Mic Playback Volume", 0x20, 0x01, HDA_INPUT),
HDA_CODEC_MUTE("Mic Playback Switch", 0x20, 0x01, HDA_INPUT),
HDA_CODEC_VOLUME("Line Playback Volume", 0x20, 0x04, HDA_INPUT),
HDA_CODEC_MUTE("Line Playback Switch", 0x20, 0x04, HDA_INPUT),
HDA_CODEC_VOLUME("CD Playback Volume", 0x20, 0x06, HDA_INPUT),
HDA_CODEC_MUTE("CD Playback Switch", 0x20, 0x06, HDA_INPUT),
{ } /* end */
};
static struct snd_kcontrol_new ad1882a_loopback_mixers[] = {
HDA_CODEC_VOLUME("Front Mic Playback Volume", 0x20, 0x00, HDA_INPUT),
HDA_CODEC_MUTE("Front Mic Playback Switch", 0x20, 0x00, HDA_INPUT),
HDA_CODEC_VOLUME("Mic Playback Volume", 0x20, 0x04, HDA_INPUT),
HDA_CODEC_MUTE("Mic Playback Switch", 0x20, 0x04, HDA_INPUT),
HDA_CODEC_VOLUME("Line Playback Volume", 0x20, 0x01, HDA_INPUT),
HDA_CODEC_MUTE("Line Playback Switch", 0x20, 0x01, HDA_INPUT),
HDA_CODEC_VOLUME("CD Playback Volume", 0x20, 0x06, HDA_INPUT),
HDA_CODEC_MUTE("CD Playback Switch", 0x20, 0x06, HDA_INPUT),
HDA_CODEC_VOLUME("Digital Mic Boost", 0x1f, 0x0, HDA_INPUT),
{ } /* end */
};
static struct snd_kcontrol_new ad1882_3stack_mixers[] = {
HDA_CODEC_MUTE("Surround Playback Switch", 0x15, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE_MONO("Center Playback Switch", 0x17, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE_MONO("LFE Playback Switch", 0x17, 2, 0x0, HDA_OUTPUT),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Channel Mode",
.info = ad198x_ch_mode_info,
.get = ad198x_ch_mode_get,
.put = ad198x_ch_mode_put,
},
{ } /* end */
};
static struct snd_kcontrol_new ad1882_6stack_mixers[] = {
HDA_CODEC_MUTE("Surround Playback Switch", 0x16, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE_MONO("Center Playback Switch", 0x24, 1, 0x0, HDA_OUTPUT),
HDA_CODEC_MUTE_MONO("LFE Playback Switch", 0x24, 2, 0x0, HDA_OUTPUT),
{ } /* end */
};
static struct hda_verb ad1882_ch2_init[] = {
{0x15, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_IN},
{0x2c, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x2c, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x17, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80},
{0x26, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x26, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{ } /* end */
};
static struct hda_verb ad1882_ch4_init[] = {
{0x15, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT},
{0x2c, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(0)},
{0x2c, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(1)},
{0x17, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80},
{0x26, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x26, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{ } /* end */
};
static struct hda_verb ad1882_ch6_init[] = {
{0x15, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT},
{0x2c, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(0)},
{0x2c, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(1)},
{0x17, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT},
{0x26, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(0)},
{0x26, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(1)},
{ } /* end */
};
static struct hda_channel_mode ad1882_modes[3] = {
{ 2, ad1882_ch2_init },
{ 4, ad1882_ch4_init },
{ 6, ad1882_ch6_init },
};
/*
* initialization verbs
*/
static struct hda_verb ad1882_init_verbs[] = {
/* DACs; mute as default */
{0x03, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_ZERO},
{0x04, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_ZERO},
{0x05, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_ZERO},
/* Port-A (HP) mixer */
{0x22, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(0)},
{0x22, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(1)},
/* Port-A pin */
{0x11, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_HP},
{0x11, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* HP selector - select DAC2 */
{0x37, AC_VERB_SET_CONNECT_SEL, 0x1},
/* Port-D (Line-out) mixer */
{0x29, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(0)},
{0x29, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(1)},
/* Port-D pin */
{0x12, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_HP},
{0x12, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* Mono-out mixer */
{0x1e, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(0)},
{0x1e, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_UNMUTE(1)},
/* Mono-out pin */
{0x13, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_HP},
{0x13, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* Port-B (front mic) pin */
{0x14, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80},
{0x14, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
{0x39, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_ZERO}, /* boost */
/* Port-C (line-in) pin */
{0x15, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_IN},
{0x15, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
{0x3a, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_ZERO}, /* boost */
/* Port-C mixer - mute as input */
{0x2c, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x2c, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
/* Port-E (mic-in) pin */
{0x17, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_VREF80},
{0x17, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
{0x3c, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_ZERO}, /* boost */
/* Port-E mixer - mute as input */
{0x26, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x26, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
/* Port-F (surround) */
{0x16, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT},
{0x16, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* Port-G (CLFE) */
{0x24, AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT},
{0x24, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE},
/* Analog mixer; mute as default */
/* list: 0x39, 0x3a, 0x11, 0x12, 0x3c, 0x3b, 0x18, 0x1a */
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(0)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(1)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(2)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(3)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(4)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(5)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(6)},
{0x20, AC_VERB_SET_AMP_GAIN_MUTE, AMP_IN_MUTE(7)},
/* Analog Mix output amp */
{0x21, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE | 0x1f}, /* 0dB */
/* SPDIF output selector */
{0x02, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE | 0x27}, /* 0dB */
{0x02, AC_VERB_SET_CONNECT_SEL, 0x0}, /* PCM */
{0x1b, AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_UNMUTE | 0x27}, /* 0dB */
{ } /* end */
};
#ifdef CONFIG_SND_HDA_POWER_SAVE
static struct hda_amp_list ad1882_loopbacks[] = {
{ 0x20, HDA_INPUT, 0 }, /* Front Mic */
{ 0x20, HDA_INPUT, 1 }, /* Mic */
{ 0x20, HDA_INPUT, 4 }, /* Line */
{ 0x20, HDA_INPUT, 6 }, /* CD */
{ } /* end */
};
#endif
/* models */
enum {
AD1882_3STACK,
AD1882_6STACK,
AD1882_MODELS
};
static const char *ad1882_models[AD1986A_MODELS] = {
[AD1882_3STACK] = "3stack",
[AD1882_6STACK] = "6stack",
};
static int patch_ad1882(struct hda_codec *codec)
{
struct ad198x_spec *spec;
int err, board_config;
spec = kzalloc(sizeof(*spec), GFP_KERNEL);
if (spec == NULL)
return -ENOMEM;
codec->spec = spec;
err = snd_hda_attach_beep_device(codec, 0x10);
if (err < 0) {
ad198x_free(codec);
return err;
}
set_beep_amp(spec, 0x10, 0, HDA_OUTPUT);
spec->multiout.max_channels = 6;
spec->multiout.num_dacs = 3;
spec->multiout.dac_nids = ad1882_dac_nids;
spec->multiout.dig_out_nid = AD1882_SPDIF_OUT;
spec->num_adc_nids = ARRAY_SIZE(ad1882_adc_nids);
spec->adc_nids = ad1882_adc_nids;
spec->capsrc_nids = ad1882_capsrc_nids;
if (codec->vendor_id == 0x11d41882)
spec->input_mux = &ad1882_capture_source;
else
spec->input_mux = &ad1882a_capture_source;
spec->num_mixers = 2;
spec->mixers[0] = ad1882_base_mixers;
if (codec->vendor_id == 0x11d41882)
spec->mixers[1] = ad1882_loopback_mixers;
else
spec->mixers[1] = ad1882a_loopback_mixers;
spec->num_init_verbs = 1;
spec->init_verbs[0] = ad1882_init_verbs;
spec->spdif_route = 0;
#ifdef CONFIG_SND_HDA_POWER_SAVE
spec->loopback.amplist = ad1882_loopbacks;
#endif
spec->vmaster_nid = 0x04;
codec->patch_ops = ad198x_patch_ops;
/* override some parameters */
board_config = snd_hda_check_board_config(codec, AD1882_MODELS,
ad1882_models, NULL);
switch (board_config) {
default:
case AD1882_3STACK:
spec->num_mixers = 3;
spec->mixers[2] = ad1882_3stack_mixers;
spec->channel_mode = ad1882_modes;
spec->num_channel_mode = ARRAY_SIZE(ad1882_modes);
spec->need_dac_fix = 1;
spec->multiout.max_channels = 2;
spec->multiout.num_dacs = 1;
break;
case AD1882_6STACK:
spec->num_mixers = 3;
spec->mixers[2] = ad1882_6stack_mixers;
break;
}
codec->no_trigger_sense = 1;
return 0;
}
/*
* patch entries
*/
static struct hda_codec_preset snd_hda_preset_analog[] = {
{ .id = 0x11d4184a, .name = "AD1884A", .patch = patch_ad1884a },
{ .id = 0x11d41882, .name = "AD1882", .patch = patch_ad1882 },
{ .id = 0x11d41883, .name = "AD1883", .patch = patch_ad1884a },
{ .id = 0x11d41884, .name = "AD1884", .patch = patch_ad1884 },
{ .id = 0x11d4194a, .name = "AD1984A", .patch = patch_ad1884a },
{ .id = 0x11d4194b, .name = "AD1984B", .patch = patch_ad1884a },
{ .id = 0x11d41981, .name = "AD1981", .patch = patch_ad1981 },
{ .id = 0x11d41983, .name = "AD1983", .patch = patch_ad1983 },
{ .id = 0x11d41984, .name = "AD1984", .patch = patch_ad1984 },
{ .id = 0x11d41986, .name = "AD1986A", .patch = patch_ad1986a },
{ .id = 0x11d41988, .name = "AD1988", .patch = patch_ad1988 },
{ .id = 0x11d4198b, .name = "AD1988B", .patch = patch_ad1988 },
{ .id = 0x11d4882a, .name = "AD1882A", .patch = patch_ad1882 },
{ .id = 0x11d4989a, .name = "AD1989A", .patch = patch_ad1988 },
{ .id = 0x11d4989b, .name = "AD1989B", .patch = patch_ad1988 },
{} /* terminator */
};
MODULE_ALIAS("snd-hda-codec-id:11d4*");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Analog Devices HD-audio codec");
static struct hda_codec_preset_list analog_list = {
.preset = snd_hda_preset_analog,
.owner = THIS_MODULE,
};
static int __init patch_analog_init(void)
{
return snd_hda_add_codec_preset(&analog_list);
}
static void __exit patch_analog_exit(void)
{
snd_hda_delete_codec_preset(&analog_list);
}
module_init(patch_analog_init)
module_exit(patch_analog_exit)
| gpl-2.0 |
mik9/ThunderG-Kernel | arch/sparc/mm/init_32.c | 510 | 14232 | /*
* linux/arch/sparc/mm/init.c
*
* Copyright (C) 1995 David S. Miller (davem@caip.rutgers.edu)
* Copyright (C) 1995 Eddie C. Dost (ecd@skynet.be)
* Copyright (C) 1998 Jakub Jelinek (jj@sunsite.mff.cuni.cz)
* Copyright (C) 2000 Anton Blanchard (anton@samba.org)
*/
#include <linux/module.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/ptrace.h>
#include <linux/mman.h>
#include <linux/mm.h>
#include <linux/swap.h>
#include <linux/initrd.h>
#include <linux/init.h>
#include <linux/highmem.h>
#include <linux/bootmem.h>
#include <linux/pagemap.h>
#include <linux/poison.h>
#include <asm/sections.h>
#include <asm/system.h>
#include <asm/vac-ops.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/vaddrs.h>
#include <asm/pgalloc.h> /* bug in asm-generic/tlb.h: check_pgt_cache */
#include <asm/tlb.h>
#include <asm/prom.h>
#include <asm/leon.h>
DEFINE_PER_CPU(struct mmu_gather, mmu_gathers);
unsigned long *sparc_valid_addr_bitmap;
EXPORT_SYMBOL(sparc_valid_addr_bitmap);
unsigned long phys_base;
EXPORT_SYMBOL(phys_base);
unsigned long pfn_base;
EXPORT_SYMBOL(pfn_base);
unsigned long page_kernel;
EXPORT_SYMBOL(page_kernel);
struct sparc_phys_banks sp_banks[SPARC_PHYS_BANKS+1];
unsigned long sparc_unmapped_base;
struct pgtable_cache_struct pgt_quicklists;
/* Initial ramdisk setup */
extern unsigned int sparc_ramdisk_image;
extern unsigned int sparc_ramdisk_size;
unsigned long highstart_pfn, highend_pfn;
pte_t *kmap_pte;
pgprot_t kmap_prot;
#define kmap_get_fixmap_pte(vaddr) \
pte_offset_kernel(pmd_offset(pgd_offset_k(vaddr), (vaddr)), (vaddr))
void __init kmap_init(void)
{
/* cache the first kmap pte */
kmap_pte = kmap_get_fixmap_pte(__fix_to_virt(FIX_KMAP_BEGIN));
kmap_prot = __pgprot(SRMMU_ET_PTE | SRMMU_PRIV | SRMMU_CACHE);
}
void show_mem(void)
{
printk("Mem-info:\n");
show_free_areas();
printk("Free swap: %6ldkB\n",
nr_swap_pages << (PAGE_SHIFT-10));
printk("%ld pages of RAM\n", totalram_pages);
printk("%ld free pages\n", nr_free_pages());
#if 0 /* undefined pgtable_cache_size, pgd_cache_size */
printk("%ld pages in page table cache\n",pgtable_cache_size);
#ifndef CONFIG_SMP
if (sparc_cpu_model == sun4m || sparc_cpu_model == sun4d)
printk("%ld entries in page dir cache\n",pgd_cache_size);
#endif
#endif
}
void __init sparc_context_init(int numctx)
{
int ctx;
ctx_list_pool = __alloc_bootmem(numctx * sizeof(struct ctx_list), SMP_CACHE_BYTES, 0UL);
for(ctx = 0; ctx < numctx; ctx++) {
struct ctx_list *clist;
clist = (ctx_list_pool + ctx);
clist->ctx_number = ctx;
clist->ctx_mm = NULL;
}
ctx_free.next = ctx_free.prev = &ctx_free;
ctx_used.next = ctx_used.prev = &ctx_used;
for(ctx = 0; ctx < numctx; ctx++)
add_to_free_ctxlist(ctx_list_pool + ctx);
}
extern unsigned long cmdline_memory_size;
unsigned long last_valid_pfn;
unsigned long calc_highpages(void)
{
int i;
int nr = 0;
for (i = 0; sp_banks[i].num_bytes != 0; i++) {
unsigned long start_pfn = sp_banks[i].base_addr >> PAGE_SHIFT;
unsigned long end_pfn = (sp_banks[i].base_addr + sp_banks[i].num_bytes) >> PAGE_SHIFT;
if (end_pfn <= max_low_pfn)
continue;
if (start_pfn < max_low_pfn)
start_pfn = max_low_pfn;
nr += end_pfn - start_pfn;
}
return nr;
}
static unsigned long calc_max_low_pfn(void)
{
int i;
unsigned long tmp = pfn_base + (SRMMU_MAXMEM >> PAGE_SHIFT);
unsigned long curr_pfn, last_pfn;
last_pfn = (sp_banks[0].base_addr + sp_banks[0].num_bytes) >> PAGE_SHIFT;
for (i = 1; sp_banks[i].num_bytes != 0; i++) {
curr_pfn = sp_banks[i].base_addr >> PAGE_SHIFT;
if (curr_pfn >= tmp) {
if (last_pfn < tmp)
tmp = last_pfn;
break;
}
last_pfn = (sp_banks[i].base_addr + sp_banks[i].num_bytes) >> PAGE_SHIFT;
}
return tmp;
}
unsigned long __init bootmem_init(unsigned long *pages_avail)
{
unsigned long bootmap_size, start_pfn;
unsigned long end_of_phys_memory = 0UL;
unsigned long bootmap_pfn, bytes_avail, size;
int i;
bytes_avail = 0UL;
for (i = 0; sp_banks[i].num_bytes != 0; i++) {
end_of_phys_memory = sp_banks[i].base_addr +
sp_banks[i].num_bytes;
bytes_avail += sp_banks[i].num_bytes;
if (cmdline_memory_size) {
if (bytes_avail > cmdline_memory_size) {
unsigned long slack = bytes_avail - cmdline_memory_size;
bytes_avail -= slack;
end_of_phys_memory -= slack;
sp_banks[i].num_bytes -= slack;
if (sp_banks[i].num_bytes == 0) {
sp_banks[i].base_addr = 0xdeadbeef;
} else {
sp_banks[i+1].num_bytes = 0;
sp_banks[i+1].base_addr = 0xdeadbeef;
}
break;
}
}
}
/* Start with page aligned address of last symbol in kernel
* image.
*/
start_pfn = (unsigned long)__pa(PAGE_ALIGN((unsigned long) &_end));
/* Now shift down to get the real physical page frame number. */
start_pfn >>= PAGE_SHIFT;
bootmap_pfn = start_pfn;
max_pfn = end_of_phys_memory >> PAGE_SHIFT;
max_low_pfn = max_pfn;
highstart_pfn = highend_pfn = max_pfn;
if (max_low_pfn > pfn_base + (SRMMU_MAXMEM >> PAGE_SHIFT)) {
highstart_pfn = pfn_base + (SRMMU_MAXMEM >> PAGE_SHIFT);
max_low_pfn = calc_max_low_pfn();
printk(KERN_NOTICE "%ldMB HIGHMEM available.\n",
calc_highpages() >> (20 - PAGE_SHIFT));
}
#ifdef CONFIG_BLK_DEV_INITRD
/* Now have to check initial ramdisk, so that bootmap does not overwrite it */
if (sparc_ramdisk_image) {
if (sparc_ramdisk_image >= (unsigned long)&_end - 2 * PAGE_SIZE)
sparc_ramdisk_image -= KERNBASE;
initrd_start = sparc_ramdisk_image + phys_base;
initrd_end = initrd_start + sparc_ramdisk_size;
if (initrd_end > end_of_phys_memory) {
printk(KERN_CRIT "initrd extends beyond end of memory "
"(0x%016lx > 0x%016lx)\ndisabling initrd\n",
initrd_end, end_of_phys_memory);
initrd_start = 0;
}
if (initrd_start) {
if (initrd_start >= (start_pfn << PAGE_SHIFT) &&
initrd_start < (start_pfn << PAGE_SHIFT) + 2 * PAGE_SIZE)
bootmap_pfn = PAGE_ALIGN (initrd_end) >> PAGE_SHIFT;
}
}
#endif
/* Initialize the boot-time allocator. */
bootmap_size = init_bootmem_node(NODE_DATA(0), bootmap_pfn, pfn_base,
max_low_pfn);
/* Now register the available physical memory with the
* allocator.
*/
*pages_avail = 0;
for (i = 0; sp_banks[i].num_bytes != 0; i++) {
unsigned long curr_pfn, last_pfn;
curr_pfn = sp_banks[i].base_addr >> PAGE_SHIFT;
if (curr_pfn >= max_low_pfn)
break;
last_pfn = (sp_banks[i].base_addr + sp_banks[i].num_bytes) >> PAGE_SHIFT;
if (last_pfn > max_low_pfn)
last_pfn = max_low_pfn;
/*
* .. finally, did all the rounding and playing
* around just make the area go away?
*/
if (last_pfn <= curr_pfn)
continue;
size = (last_pfn - curr_pfn) << PAGE_SHIFT;
*pages_avail += last_pfn - curr_pfn;
free_bootmem(sp_banks[i].base_addr, size);
}
#ifdef CONFIG_BLK_DEV_INITRD
if (initrd_start) {
/* Reserve the initrd image area. */
size = initrd_end - initrd_start;
reserve_bootmem(initrd_start, size, BOOTMEM_DEFAULT);
*pages_avail -= PAGE_ALIGN(size) >> PAGE_SHIFT;
initrd_start = (initrd_start - phys_base) + PAGE_OFFSET;
initrd_end = (initrd_end - phys_base) + PAGE_OFFSET;
}
#endif
/* Reserve the kernel text/data/bss. */
size = (start_pfn << PAGE_SHIFT) - phys_base;
reserve_bootmem(phys_base, size, BOOTMEM_DEFAULT);
*pages_avail -= PAGE_ALIGN(size) >> PAGE_SHIFT;
/* Reserve the bootmem map. We do not account for it
* in pages_avail because we will release that memory
* in free_all_bootmem.
*/
size = bootmap_size;
reserve_bootmem((bootmap_pfn << PAGE_SHIFT), size, BOOTMEM_DEFAULT);
*pages_avail -= PAGE_ALIGN(size) >> PAGE_SHIFT;
return max_pfn;
}
/*
* check_pgt_cache
*
* This is called at the end of unmapping of VMA (zap_page_range),
* to rescan the page cache for architecture specific things,
* presumably something like sun4/sun4c PMEGs. Most architectures
* define check_pgt_cache empty.
*
* We simply copy the 2.4 implementation for now.
*/
static int pgt_cache_water[2] = { 25, 50 };
void check_pgt_cache(void)
{
do_check_pgt_cache(pgt_cache_water[0], pgt_cache_water[1]);
}
/*
* paging_init() sets up the page tables: We call the MMU specific
* init routine based upon the Sun model type on the Sparc.
*
*/
extern void sun4c_paging_init(void);
extern void srmmu_paging_init(void);
extern void device_scan(void);
pgprot_t PAGE_SHARED __read_mostly;
EXPORT_SYMBOL(PAGE_SHARED);
void __init paging_init(void)
{
switch(sparc_cpu_model) {
case sun4c:
case sun4e:
case sun4:
sun4c_paging_init();
sparc_unmapped_base = 0xe0000000;
BTFIXUPSET_SETHI(sparc_unmapped_base, 0xe0000000);
break;
case sparc_leon:
leon_init();
/* fall through */
case sun4m:
case sun4d:
srmmu_paging_init();
sparc_unmapped_base = 0x50000000;
BTFIXUPSET_SETHI(sparc_unmapped_base, 0x50000000);
break;
default:
prom_printf("paging_init: Cannot init paging on this Sparc\n");
prom_printf("paging_init: sparc_cpu_model = %d\n", sparc_cpu_model);
prom_printf("paging_init: Halting...\n");
prom_halt();
};
/* Initialize the protection map with non-constant, MMU dependent values. */
protection_map[0] = PAGE_NONE;
protection_map[1] = PAGE_READONLY;
protection_map[2] = PAGE_COPY;
protection_map[3] = PAGE_COPY;
protection_map[4] = PAGE_READONLY;
protection_map[5] = PAGE_READONLY;
protection_map[6] = PAGE_COPY;
protection_map[7] = PAGE_COPY;
protection_map[8] = PAGE_NONE;
protection_map[9] = PAGE_READONLY;
protection_map[10] = PAGE_SHARED;
protection_map[11] = PAGE_SHARED;
protection_map[12] = PAGE_READONLY;
protection_map[13] = PAGE_READONLY;
protection_map[14] = PAGE_SHARED;
protection_map[15] = PAGE_SHARED;
btfixup();
prom_build_devicetree();
of_fill_in_cpu_data();
device_scan();
}
static void __init taint_real_pages(void)
{
int i;
for (i = 0; sp_banks[i].num_bytes; i++) {
unsigned long start, end;
start = sp_banks[i].base_addr;
end = start + sp_banks[i].num_bytes;
while (start < end) {
set_bit(start >> 20, sparc_valid_addr_bitmap);
start += PAGE_SIZE;
}
}
}
static void map_high_region(unsigned long start_pfn, unsigned long end_pfn)
{
unsigned long tmp;
#ifdef CONFIG_DEBUG_HIGHMEM
printk("mapping high region %08lx - %08lx\n", start_pfn, end_pfn);
#endif
for (tmp = start_pfn; tmp < end_pfn; tmp++) {
struct page *page = pfn_to_page(tmp);
ClearPageReserved(page);
init_page_count(page);
__free_page(page);
totalhigh_pages++;
}
}
void __init mem_init(void)
{
int codepages = 0;
int datapages = 0;
int initpages = 0;
int reservedpages = 0;
int i;
if (PKMAP_BASE+LAST_PKMAP*PAGE_SIZE >= FIXADDR_START) {
prom_printf("BUG: fixmap and pkmap areas overlap\n");
prom_printf("pkbase: 0x%lx pkend: 0x%lx fixstart 0x%lx\n",
PKMAP_BASE,
(unsigned long)PKMAP_BASE+LAST_PKMAP*PAGE_SIZE,
FIXADDR_START);
prom_printf("Please mail sparclinux@vger.kernel.org.\n");
prom_halt();
}
/* Saves us work later. */
memset((void *)&empty_zero_page, 0, PAGE_SIZE);
i = last_valid_pfn >> ((20 - PAGE_SHIFT) + 5);
i += 1;
sparc_valid_addr_bitmap = (unsigned long *)
__alloc_bootmem(i << 2, SMP_CACHE_BYTES, 0UL);
if (sparc_valid_addr_bitmap == NULL) {
prom_printf("mem_init: Cannot alloc valid_addr_bitmap.\n");
prom_halt();
}
memset(sparc_valid_addr_bitmap, 0, i << 2);
taint_real_pages();
max_mapnr = last_valid_pfn - pfn_base;
high_memory = __va(max_low_pfn << PAGE_SHIFT);
totalram_pages = free_all_bootmem();
for (i = 0; sp_banks[i].num_bytes != 0; i++) {
unsigned long start_pfn = sp_banks[i].base_addr >> PAGE_SHIFT;
unsigned long end_pfn = (sp_banks[i].base_addr + sp_banks[i].num_bytes) >> PAGE_SHIFT;
num_physpages += sp_banks[i].num_bytes >> PAGE_SHIFT;
if (end_pfn <= highstart_pfn)
continue;
if (start_pfn < highstart_pfn)
start_pfn = highstart_pfn;
map_high_region(start_pfn, end_pfn);
}
totalram_pages += totalhigh_pages;
codepages = (((unsigned long) &_etext) - ((unsigned long)&_start));
codepages = PAGE_ALIGN(codepages) >> PAGE_SHIFT;
datapages = (((unsigned long) &_edata) - ((unsigned long)&_etext));
datapages = PAGE_ALIGN(datapages) >> PAGE_SHIFT;
initpages = (((unsigned long) &__init_end) - ((unsigned long) &__init_begin));
initpages = PAGE_ALIGN(initpages) >> PAGE_SHIFT;
/* Ignore memory holes for the purpose of counting reserved pages */
for (i=0; i < max_low_pfn; i++)
if (test_bit(i >> (20 - PAGE_SHIFT), sparc_valid_addr_bitmap)
&& PageReserved(pfn_to_page(i)))
reservedpages++;
printk(KERN_INFO "Memory: %luk/%luk available (%dk kernel code, %dk reserved, %dk data, %dk init, %ldk highmem)\n",
nr_free_pages() << (PAGE_SHIFT-10),
num_physpages << (PAGE_SHIFT - 10),
codepages << (PAGE_SHIFT-10),
reservedpages << (PAGE_SHIFT - 10),
datapages << (PAGE_SHIFT-10),
initpages << (PAGE_SHIFT-10),
totalhigh_pages << (PAGE_SHIFT-10));
}
void free_initmem (void)
{
unsigned long addr;
unsigned long freed;
addr = (unsigned long)(&__init_begin);
freed = (unsigned long)(&__init_end) - addr;
for (; addr < (unsigned long)(&__init_end); addr += PAGE_SIZE) {
struct page *p;
memset((void *)addr, POISON_FREE_INITMEM, PAGE_SIZE);
p = virt_to_page(addr);
ClearPageReserved(p);
init_page_count(p);
__free_page(p);
totalram_pages++;
num_physpages++;
}
printk(KERN_INFO "Freeing unused kernel memory: %ldk freed\n",
freed >> 10);
}
#ifdef CONFIG_BLK_DEV_INITRD
void free_initrd_mem(unsigned long start, unsigned long end)
{
if (start < end)
printk(KERN_INFO "Freeing initrd memory: %ldk freed\n",
(end - start) >> 10);
for (; start < end; start += PAGE_SIZE) {
struct page *p;
memset((void *)start, POISON_FREE_INITMEM, PAGE_SIZE);
p = virt_to_page(start);
ClearPageReserved(p);
init_page_count(p);
__free_page(p);
totalram_pages++;
num_physpages++;
}
}
#endif
void sparc_flush_page_to_ram(struct page *page)
{
unsigned long vaddr = (unsigned long)page_address(page);
if (vaddr)
__flush_page_to_ram(vaddr);
}
EXPORT_SYMBOL(sparc_flush_page_to_ram);
| gpl-2.0 |
e-yes/mini2440-kernel | drivers/staging/rt3090/common/spectrum.c | 510 | 58622 | /*
*************************************************************************
* Ralink Tech Inc.
* 5F., No.36, Taiyuan St., Jhubei City,
* Hsinchu County 302,
* Taiwan, R.O.C.
*
* (c) Copyright 2002-2007, Ralink Technology, Inc.
*
* 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., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
*************************************************************************
Module Name:
action.c
Abstract:
Handle association related requests either from WSTA or from local MLME
Revision History:
Who When What
--------- ---------- ----------------------------------------------
Fonchi Wu 2008 created for 802.11h
*/
#include "../rt_config.h"
#include "../action.h"
/* The regulatory information in the USA (US) */
DOT11_REGULATORY_INFORMATION USARegulatoryInfo[] =
{
/* "regulatory class" "number of channels" "Max Tx Pwr" "channel list" */
{0, {0, 0, {0}}}, // Invlid entry
{1, {4, 16, {36, 40, 44, 48}}},
{2, {4, 23, {52, 56, 60, 64}}},
{3, {4, 29, {149, 153, 157, 161}}},
{4, {11, 23, {100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140}}},
{5, {5, 30, {149, 153, 157, 161, 165}}},
{6, {10, 14, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}}},
{7, {10, 27, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}}},
{8, {5, 17, {11, 13, 15, 17, 19}}},
{9, {5, 30, {11, 13, 15, 17, 19}}},
{10, {2, 20, {21, 25}}},
{11, {2, 33, {21, 25}}},
{12, {11, 30, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}}}
};
#define USA_REGULATORY_INFO_SIZE (sizeof(USARegulatoryInfo) / sizeof(DOT11_REGULATORY_INFORMATION))
/* The regulatory information in Europe */
DOT11_REGULATORY_INFORMATION EuropeRegulatoryInfo[] =
{
/* "regulatory class" "number of channels" "Max Tx Pwr" "channel list" */
{0, {0, 0, {0}}}, // Invalid entry
{1, {4, 20, {36, 40, 44, 48}}},
{2, {4, 20, {52, 56, 60, 64}}},
{3, {11, 30, {100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140}}},
{4, {13, 20, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}}}
};
#define EU_REGULATORY_INFO_SIZE (sizeof(EuropeRegulatoryInfo) / sizeof(DOT11_REGULATORY_INFORMATION))
/* The regulatory information in Japan */
DOT11_REGULATORY_INFORMATION JapanRegulatoryInfo[] =
{
/* "regulatory class" "number of channels" "Max Tx Pwr" "channel list" */
{0, {0, 0, {0}}}, // Invalid entry
{1, {4, 22, {34, 38, 42, 46}}},
{2, {3, 24, {8, 12, 16}}},
{3, {3, 24, {8, 12, 16}}},
{4, {3, 24, {8, 12, 16}}},
{5, {3, 24, {8, 12, 16}}},
{6, {3, 22, {8, 12, 16}}},
{7, {4, 24, {184, 188, 192, 196}}},
{8, {4, 24, {184, 188, 192, 196}}},
{9, {4, 24, {184, 188, 192, 196}}},
{10, {4, 24, {184, 188, 192, 196}}},
{11, {4, 22, {184, 188, 192, 196}}},
{12, {4, 24, {7, 8, 9, 11}}},
{13, {4, 24, {7, 8, 9, 11}}},
{14, {4, 24, {7, 8, 9, 11}}},
{15, {4, 24, {7, 8, 9, 11}}},
{16, {6, 24, {183, 184, 185, 187, 188, 189}}},
{17, {6, 24, {183, 184, 185, 187, 188, 189}}},
{18, {6, 24, {183, 184, 185, 187, 188, 189}}},
{19, {6, 24, {183, 184, 185, 187, 188, 189}}},
{20, {6, 17, {183, 184, 185, 187, 188, 189}}},
{21, {6, 24, {6, 7, 8, 9, 10, 11}}},
{22, {6, 24, {6, 7, 8, 9, 10, 11}}},
{23, {6, 24, {6, 7, 8, 9, 10, 11}}},
{24, {6, 24, {6, 7, 8, 9, 10, 11}}},
{25, {8, 24, {182, 183, 184, 185, 186, 187, 188, 189}}},
{26, {8, 24, {182, 183, 184, 185, 186, 187, 188, 189}}},
{27, {8, 24, {182, 183, 184, 185, 186, 187, 188, 189}}},
{28, {8, 24, {182, 183, 184, 185, 186, 187, 188, 189}}},
{29, {8, 17, {182, 183, 184, 185, 186, 187, 188, 189}}},
{30, {13, 23, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}}},
{31, {1, 23, {14}}},
{32, {4, 22, {52, 56, 60, 64}}}
};
#define JP_REGULATORY_INFO_SIZE (sizeof(JapanRegulatoryInfo) / sizeof(DOT11_REGULATORY_INFORMATION))
CHAR RTMP_GetTxPwr(
IN PRTMP_ADAPTER pAd,
IN HTTRANSMIT_SETTING HTTxMode)
{
typedef struct __TX_PWR_CFG
{
UINT8 Mode;
UINT8 MCS;
UINT16 req;
UINT8 shift;
UINT32 BitMask;
} TX_PWR_CFG;
UINT32 Value;
INT Idx;
UINT8 PhyMode;
CHAR CurTxPwr;
UINT8 TxPwrRef = 0;
CHAR DaltaPwr;
ULONG TxPwr[5];
TX_PWR_CFG TxPwrCfg[] = {
{MODE_CCK, 0, 0, 4, 0x000000f0},
{MODE_CCK, 1, 0, 0, 0x0000000f},
{MODE_CCK, 2, 0, 12, 0x0000f000},
{MODE_CCK, 3, 0, 8, 0x00000f00},
{MODE_OFDM, 0, 0, 20, 0x00f00000},
{MODE_OFDM, 1, 0, 16, 0x000f0000},
{MODE_OFDM, 2, 0, 28, 0xf0000000},
{MODE_OFDM, 3, 0, 24, 0x0f000000},
{MODE_OFDM, 4, 1, 4, 0x000000f0},
{MODE_OFDM, 5, 1, 0, 0x0000000f},
{MODE_OFDM, 6, 1, 12, 0x0000f000},
{MODE_OFDM, 7, 1, 8, 0x00000f00}
#ifdef DOT11_N_SUPPORT
,{MODE_HTMIX, 0, 1, 20, 0x00f00000},
{MODE_HTMIX, 1, 1, 16, 0x000f0000},
{MODE_HTMIX, 2, 1, 28, 0xf0000000},
{MODE_HTMIX, 3, 1, 24, 0x0f000000},
{MODE_HTMIX, 4, 2, 4, 0x000000f0},
{MODE_HTMIX, 5, 2, 0, 0x0000000f},
{MODE_HTMIX, 6, 2, 12, 0x0000f000},
{MODE_HTMIX, 7, 2, 8, 0x00000f00},
{MODE_HTMIX, 8, 2, 20, 0x00f00000},
{MODE_HTMIX, 9, 2, 16, 0x000f0000},
{MODE_HTMIX, 10, 2, 28, 0xf0000000},
{MODE_HTMIX, 11, 2, 24, 0x0f000000},
{MODE_HTMIX, 12, 3, 4, 0x000000f0},
{MODE_HTMIX, 13, 3, 0, 0x0000000f},
{MODE_HTMIX, 14, 3, 12, 0x0000f000},
{MODE_HTMIX, 15, 3, 8, 0x00000f00}
#endif // DOT11_N_SUPPORT //
};
#define MAX_TXPWR_TAB_SIZE (sizeof(TxPwrCfg) / sizeof(TX_PWR_CFG))
#ifdef SINGLE_SKU
CurTxPwr = pAd->CommonCfg.DefineMaxTxPwr;
#else
CurTxPwr = 19;
#endif
/* check Tx Power setting from UI. */
if (pAd->CommonCfg.TxPowerPercentage > 90)
;
else if (pAd->CommonCfg.TxPowerPercentage > 60) /* reduce Pwr for 1 dB. */
CurTxPwr -= 1;
else if (pAd->CommonCfg.TxPowerPercentage > 30) /* reduce Pwr for 3 dB. */
CurTxPwr -= 3;
else if (pAd->CommonCfg.TxPowerPercentage > 15) /* reduce Pwr for 6 dB. */
CurTxPwr -= 6;
else if (pAd->CommonCfg.TxPowerPercentage > 9) /* reduce Pwr for 9 dB. */
CurTxPwr -= 9;
else /* reduce Pwr for 12 dB. */
CurTxPwr -= 12;
if (pAd->CommonCfg.BBPCurrentBW == BW_40)
{
if (pAd->CommonCfg.CentralChannel > 14)
{
TxPwr[0] = pAd->Tx40MPwrCfgABand[0];
TxPwr[1] = pAd->Tx40MPwrCfgABand[1];
TxPwr[2] = pAd->Tx40MPwrCfgABand[2];
TxPwr[3] = pAd->Tx40MPwrCfgABand[3];
TxPwr[4] = pAd->Tx40MPwrCfgABand[4];
}
else
{
TxPwr[0] = pAd->Tx40MPwrCfgGBand[0];
TxPwr[1] = pAd->Tx40MPwrCfgGBand[1];
TxPwr[2] = pAd->Tx40MPwrCfgGBand[2];
TxPwr[3] = pAd->Tx40MPwrCfgGBand[3];
TxPwr[4] = pAd->Tx40MPwrCfgGBand[4];
}
}
else
{
if (pAd->CommonCfg.Channel > 14)
{
TxPwr[0] = pAd->Tx20MPwrCfgABand[0];
TxPwr[1] = pAd->Tx20MPwrCfgABand[1];
TxPwr[2] = pAd->Tx20MPwrCfgABand[2];
TxPwr[3] = pAd->Tx20MPwrCfgABand[3];
TxPwr[4] = pAd->Tx20MPwrCfgABand[4];
}
else
{
TxPwr[0] = pAd->Tx20MPwrCfgGBand[0];
TxPwr[1] = pAd->Tx20MPwrCfgGBand[1];
TxPwr[2] = pAd->Tx20MPwrCfgGBand[2];
TxPwr[3] = pAd->Tx20MPwrCfgGBand[3];
TxPwr[4] = pAd->Tx20MPwrCfgGBand[4];
}
}
switch(HTTxMode.field.MODE)
{
case MODE_CCK:
case MODE_OFDM:
Value = TxPwr[1];
TxPwrRef = (Value & 0x00000f00) >> 8;
break;
#ifdef DOT11_N_SUPPORT
case MODE_HTMIX:
case MODE_HTGREENFIELD:
if (pAd->CommonCfg.TxStream == 1)
{
Value = TxPwr[2];
TxPwrRef = (Value & 0x00000f00) >> 8;
}
else if (pAd->CommonCfg.TxStream == 2)
{
Value = TxPwr[3];
TxPwrRef = (Value & 0x00000f00) >> 8;
}
break;
#endif // DOT11_N_SUPPORT //
}
PhyMode =
#ifdef DOT11_N_SUPPORT
(HTTxMode.field.MODE == MODE_HTGREENFIELD)
? MODE_HTMIX :
#endif // DOT11_N_SUPPORT //
HTTxMode.field.MODE;
for (Idx = 0; Idx < MAX_TXPWR_TAB_SIZE; Idx++)
{
if ((TxPwrCfg[Idx].Mode == PhyMode)
&& (TxPwrCfg[Idx].MCS == HTTxMode.field.MCS))
{
Value = TxPwr[TxPwrCfg[Idx].req];
DaltaPwr = TxPwrRef - (CHAR)((Value & TxPwrCfg[Idx].BitMask)
>> TxPwrCfg[Idx].shift);
CurTxPwr -= DaltaPwr;
break;
}
}
return CurTxPwr;
}
VOID MeasureReqTabInit(
IN PRTMP_ADAPTER pAd)
{
NdisAllocateSpinLock(&pAd->CommonCfg.MeasureReqTabLock);
pAd->CommonCfg.pMeasureReqTab = kmalloc(sizeof(MEASURE_REQ_TAB), GFP_ATOMIC);
if (pAd->CommonCfg.pMeasureReqTab)
NdisZeroMemory(pAd->CommonCfg.pMeasureReqTab, sizeof(MEASURE_REQ_TAB));
else
DBGPRINT(RT_DEBUG_ERROR, ("%s Fail to alloc memory for pAd->CommonCfg.pMeasureReqTab.\n", __FUNCTION__));
return;
}
VOID MeasureReqTabExit(
IN PRTMP_ADAPTER pAd)
{
NdisFreeSpinLock(&pAd->CommonCfg.MeasureReqTabLock);
if (pAd->CommonCfg.pMeasureReqTab)
kfree(pAd->CommonCfg.pMeasureReqTab);
pAd->CommonCfg.pMeasureReqTab = NULL;
return;
}
PMEASURE_REQ_ENTRY MeasureReqLookUp(
IN PRTMP_ADAPTER pAd,
IN UINT8 DialogToken)
{
UINT HashIdx;
PMEASURE_REQ_TAB pTab = pAd->CommonCfg.pMeasureReqTab;
PMEASURE_REQ_ENTRY pEntry = NULL;
PMEASURE_REQ_ENTRY pPrevEntry = NULL;
if (pTab == NULL)
{
DBGPRINT(RT_DEBUG_ERROR, ("%s: pMeasureReqTab doesn't exist.\n", __FUNCTION__));
return NULL;
}
RTMP_SEM_LOCK(&pAd->CommonCfg.MeasureReqTabLock);
HashIdx = MQ_DIALOGTOKEN_HASH_INDEX(DialogToken);
pEntry = pTab->Hash[HashIdx];
while (pEntry)
{
if (pEntry->DialogToken == DialogToken)
break;
else
{
pPrevEntry = pEntry;
pEntry = pEntry->pNext;
}
}
RTMP_SEM_UNLOCK(&pAd->CommonCfg.MeasureReqTabLock);
return pEntry;
}
PMEASURE_REQ_ENTRY MeasureReqInsert(
IN PRTMP_ADAPTER pAd,
IN UINT8 DialogToken)
{
INT i;
ULONG HashIdx;
PMEASURE_REQ_TAB pTab = pAd->CommonCfg.pMeasureReqTab;
PMEASURE_REQ_ENTRY pEntry = NULL, pCurrEntry;
ULONG Now;
if(pTab == NULL)
{
DBGPRINT(RT_DEBUG_ERROR, ("%s: pMeasureReqTab doesn't exist.\n", __FUNCTION__));
return NULL;
}
pEntry = MeasureReqLookUp(pAd, DialogToken);
if (pEntry == NULL)
{
RTMP_SEM_LOCK(&pAd->CommonCfg.MeasureReqTabLock);
for (i = 0; i < MAX_MEASURE_REQ_TAB_SIZE; i++)
{
NdisGetSystemUpTime(&Now);
pEntry = &pTab->Content[i];
if ((pEntry->Valid == TRUE)
&& RTMP_TIME_AFTER((unsigned long)Now, (unsigned long)(pEntry->lastTime + MQ_REQ_AGE_OUT)))
{
PMEASURE_REQ_ENTRY pPrevEntry = NULL;
ULONG HashIdx = MQ_DIALOGTOKEN_HASH_INDEX(pEntry->DialogToken);
PMEASURE_REQ_ENTRY pProbeEntry = pTab->Hash[HashIdx];
// update Hash list
do
{
if (pProbeEntry == pEntry)
{
if (pPrevEntry == NULL)
{
pTab->Hash[HashIdx] = pEntry->pNext;
}
else
{
pPrevEntry->pNext = pEntry->pNext;
}
break;
}
pPrevEntry = pProbeEntry;
pProbeEntry = pProbeEntry->pNext;
} while (pProbeEntry);
NdisZeroMemory(pEntry, sizeof(MEASURE_REQ_ENTRY));
pTab->Size--;
break;
}
if (pEntry->Valid == FALSE)
break;
}
if (i < MAX_MEASURE_REQ_TAB_SIZE)
{
NdisGetSystemUpTime(&Now);
pEntry->lastTime = Now;
pEntry->Valid = TRUE;
pEntry->DialogToken = DialogToken;
pTab->Size++;
}
else
{
pEntry = NULL;
DBGPRINT(RT_DEBUG_ERROR, ("%s: pMeasureReqTab tab full.\n", __FUNCTION__));
}
// add this Neighbor entry into HASH table
if (pEntry)
{
HashIdx = MQ_DIALOGTOKEN_HASH_INDEX(DialogToken);
if (pTab->Hash[HashIdx] == NULL)
{
pTab->Hash[HashIdx] = pEntry;
}
else
{
pCurrEntry = pTab->Hash[HashIdx];
while (pCurrEntry->pNext != NULL)
pCurrEntry = pCurrEntry->pNext;
pCurrEntry->pNext = pEntry;
}
}
RTMP_SEM_UNLOCK(&pAd->CommonCfg.MeasureReqTabLock);
}
return pEntry;
}
VOID MeasureReqDelete(
IN PRTMP_ADAPTER pAd,
IN UINT8 DialogToken)
{
PMEASURE_REQ_TAB pTab = pAd->CommonCfg.pMeasureReqTab;
PMEASURE_REQ_ENTRY pEntry = NULL;
if(pTab == NULL)
{
DBGPRINT(RT_DEBUG_ERROR, ("%s: pMeasureReqTab doesn't exist.\n", __FUNCTION__));
return;
}
// if empty, return
if (pTab->Size == 0)
{
DBGPRINT(RT_DEBUG_ERROR, ("pMeasureReqTab empty.\n"));
return;
}
pEntry = MeasureReqLookUp(pAd, DialogToken);
if (pEntry != NULL)
{
PMEASURE_REQ_ENTRY pPrevEntry = NULL;
ULONG HashIdx = MQ_DIALOGTOKEN_HASH_INDEX(pEntry->DialogToken);
PMEASURE_REQ_ENTRY pProbeEntry = pTab->Hash[HashIdx];
RTMP_SEM_LOCK(&pAd->CommonCfg.MeasureReqTabLock);
// update Hash list
do
{
if (pProbeEntry == pEntry)
{
if (pPrevEntry == NULL)
{
pTab->Hash[HashIdx] = pEntry->pNext;
}
else
{
pPrevEntry->pNext = pEntry->pNext;
}
break;
}
pPrevEntry = pProbeEntry;
pProbeEntry = pProbeEntry->pNext;
} while (pProbeEntry);
NdisZeroMemory(pEntry, sizeof(MEASURE_REQ_ENTRY));
pTab->Size--;
RTMP_SEM_UNLOCK(&pAd->CommonCfg.MeasureReqTabLock);
}
return;
}
VOID TpcReqTabInit(
IN PRTMP_ADAPTER pAd)
{
NdisAllocateSpinLock(&pAd->CommonCfg.TpcReqTabLock);
pAd->CommonCfg.pTpcReqTab = kmalloc(sizeof(TPC_REQ_TAB), GFP_ATOMIC);
if (pAd->CommonCfg.pTpcReqTab)
NdisZeroMemory(pAd->CommonCfg.pTpcReqTab, sizeof(TPC_REQ_TAB));
else
DBGPRINT(RT_DEBUG_ERROR, ("%s Fail to alloc memory for pAd->CommonCfg.pTpcReqTab.\n", __FUNCTION__));
return;
}
VOID TpcReqTabExit(
IN PRTMP_ADAPTER pAd)
{
NdisFreeSpinLock(&pAd->CommonCfg.TpcReqTabLock);
if (pAd->CommonCfg.pTpcReqTab)
kfree(pAd->CommonCfg.pTpcReqTab);
pAd->CommonCfg.pTpcReqTab = NULL;
return;
}
static PTPC_REQ_ENTRY TpcReqLookUp(
IN PRTMP_ADAPTER pAd,
IN UINT8 DialogToken)
{
UINT HashIdx;
PTPC_REQ_TAB pTab = pAd->CommonCfg.pTpcReqTab;
PTPC_REQ_ENTRY pEntry = NULL;
PTPC_REQ_ENTRY pPrevEntry = NULL;
if (pTab == NULL)
{
DBGPRINT(RT_DEBUG_ERROR, ("%s: pTpcReqTab doesn't exist.\n", __FUNCTION__));
return NULL;
}
RTMP_SEM_LOCK(&pAd->CommonCfg.TpcReqTabLock);
HashIdx = TPC_DIALOGTOKEN_HASH_INDEX(DialogToken);
pEntry = pTab->Hash[HashIdx];
while (pEntry)
{
if (pEntry->DialogToken == DialogToken)
break;
else
{
pPrevEntry = pEntry;
pEntry = pEntry->pNext;
}
}
RTMP_SEM_UNLOCK(&pAd->CommonCfg.TpcReqTabLock);
return pEntry;
}
static PTPC_REQ_ENTRY TpcReqInsert(
IN PRTMP_ADAPTER pAd,
IN UINT8 DialogToken)
{
INT i;
ULONG HashIdx;
PTPC_REQ_TAB pTab = pAd->CommonCfg.pTpcReqTab;
PTPC_REQ_ENTRY pEntry = NULL, pCurrEntry;
ULONG Now;
if(pTab == NULL)
{
DBGPRINT(RT_DEBUG_ERROR, ("%s: pTpcReqTab doesn't exist.\n", __FUNCTION__));
return NULL;
}
pEntry = TpcReqLookUp(pAd, DialogToken);
if (pEntry == NULL)
{
RTMP_SEM_LOCK(&pAd->CommonCfg.TpcReqTabLock);
for (i = 0; i < MAX_TPC_REQ_TAB_SIZE; i++)
{
NdisGetSystemUpTime(&Now);
pEntry = &pTab->Content[i];
if ((pEntry->Valid == TRUE)
&& RTMP_TIME_AFTER((unsigned long)Now, (unsigned long)(pEntry->lastTime + TPC_REQ_AGE_OUT)))
{
PTPC_REQ_ENTRY pPrevEntry = NULL;
ULONG HashIdx = TPC_DIALOGTOKEN_HASH_INDEX(pEntry->DialogToken);
PTPC_REQ_ENTRY pProbeEntry = pTab->Hash[HashIdx];
// update Hash list
do
{
if (pProbeEntry == pEntry)
{
if (pPrevEntry == NULL)
{
pTab->Hash[HashIdx] = pEntry->pNext;
}
else
{
pPrevEntry->pNext = pEntry->pNext;
}
break;
}
pPrevEntry = pProbeEntry;
pProbeEntry = pProbeEntry->pNext;
} while (pProbeEntry);
NdisZeroMemory(pEntry, sizeof(TPC_REQ_ENTRY));
pTab->Size--;
break;
}
if (pEntry->Valid == FALSE)
break;
}
if (i < MAX_TPC_REQ_TAB_SIZE)
{
NdisGetSystemUpTime(&Now);
pEntry->lastTime = Now;
pEntry->Valid = TRUE;
pEntry->DialogToken = DialogToken;
pTab->Size++;
}
else
{
pEntry = NULL;
DBGPRINT(RT_DEBUG_ERROR, ("%s: pTpcReqTab tab full.\n", __FUNCTION__));
}
// add this Neighbor entry into HASH table
if (pEntry)
{
HashIdx = TPC_DIALOGTOKEN_HASH_INDEX(DialogToken);
if (pTab->Hash[HashIdx] == NULL)
{
pTab->Hash[HashIdx] = pEntry;
}
else
{
pCurrEntry = pTab->Hash[HashIdx];
while (pCurrEntry->pNext != NULL)
pCurrEntry = pCurrEntry->pNext;
pCurrEntry->pNext = pEntry;
}
}
RTMP_SEM_UNLOCK(&pAd->CommonCfg.TpcReqTabLock);
}
return pEntry;
}
static VOID TpcReqDelete(
IN PRTMP_ADAPTER pAd,
IN UINT8 DialogToken)
{
PTPC_REQ_TAB pTab = pAd->CommonCfg.pTpcReqTab;
PTPC_REQ_ENTRY pEntry = NULL;
if(pTab == NULL)
{
DBGPRINT(RT_DEBUG_ERROR, ("%s: pTpcReqTab doesn't exist.\n", __FUNCTION__));
return;
}
// if empty, return
if (pTab->Size == 0)
{
DBGPRINT(RT_DEBUG_ERROR, ("pTpcReqTab empty.\n"));
return;
}
pEntry = TpcReqLookUp(pAd, DialogToken);
if (pEntry != NULL)
{
PTPC_REQ_ENTRY pPrevEntry = NULL;
ULONG HashIdx = TPC_DIALOGTOKEN_HASH_INDEX(pEntry->DialogToken);
PTPC_REQ_ENTRY pProbeEntry = pTab->Hash[HashIdx];
RTMP_SEM_LOCK(&pAd->CommonCfg.TpcReqTabLock);
// update Hash list
do
{
if (pProbeEntry == pEntry)
{
if (pPrevEntry == NULL)
{
pTab->Hash[HashIdx] = pEntry->pNext;
}
else
{
pPrevEntry->pNext = pEntry->pNext;
}
break;
}
pPrevEntry = pProbeEntry;
pProbeEntry = pProbeEntry->pNext;
} while (pProbeEntry);
NdisZeroMemory(pEntry, sizeof(TPC_REQ_ENTRY));
pTab->Size--;
RTMP_SEM_UNLOCK(&pAd->CommonCfg.TpcReqTabLock);
}
return;
}
/*
==========================================================================
Description:
Get Current TimeS tamp.
Parametrs:
Return : Current Time Stamp.
==========================================================================
*/
static UINT64 GetCurrentTimeStamp(
IN PRTMP_ADAPTER pAd)
{
// get current time stamp.
return 0;
}
/*
==========================================================================
Description:
Get Current Transmit Power.
Parametrs:
Return : Current Time Stamp.
==========================================================================
*/
static UINT8 GetCurTxPwr(
IN PRTMP_ADAPTER pAd,
IN UINT8 Wcid)
{
return 16; /* 16 dBm */
}
/*
==========================================================================
Description:
Get Current Transmit Power.
Parametrs:
Return : Current Time Stamp.
==========================================================================
*/
VOID InsertChannelRepIE(
IN PRTMP_ADAPTER pAd,
OUT PUCHAR pFrameBuf,
OUT PULONG pFrameLen,
IN PSTRING pCountry,
IN UINT8 RegulatoryClass)
{
ULONG TempLen;
UINT8 Len;
UINT8 IEId = IE_AP_CHANNEL_REPORT;
PUCHAR pChListPtr = NULL;
Len = 1;
if (strncmp(pCountry, "US", 2) == 0)
{
if (RegulatoryClass >= USA_REGULATORY_INFO_SIZE)
{
DBGPRINT(RT_DEBUG_ERROR, ("%s: USA Unknow Requlatory class (%d)\n",
__FUNCTION__, RegulatoryClass));
return;
}
Len += USARegulatoryInfo[RegulatoryClass].ChannelSet.NumberOfChannels;
pChListPtr = USARegulatoryInfo[RegulatoryClass].ChannelSet.ChannelList;
}
else if (strncmp(pCountry, "JP", 2) == 0)
{
if (RegulatoryClass >= JP_REGULATORY_INFO_SIZE)
{
DBGPRINT(RT_DEBUG_ERROR, ("%s: JP Unknow Requlatory class (%d)\n",
__FUNCTION__, RegulatoryClass));
return;
}
Len += JapanRegulatoryInfo[RegulatoryClass].ChannelSet.NumberOfChannels;
pChListPtr = JapanRegulatoryInfo[RegulatoryClass].ChannelSet.ChannelList;
}
else
{
DBGPRINT(RT_DEBUG_ERROR, ("%s: Unknow Country (%s)\n",
__FUNCTION__, pCountry));
return;
}
MakeOutgoingFrame(pFrameBuf, &TempLen,
1, &IEId,
1, &Len,
1, &RegulatoryClass,
Len -1, pChListPtr,
END_OF_ARGS);
*pFrameLen = *pFrameLen + TempLen;
return;
}
/*
==========================================================================
Description:
Insert Dialog Token into frame.
Parametrs:
1. frame buffer pointer.
2. frame length.
3. Dialog token.
Return : None.
==========================================================================
*/
VOID InsertDialogToken(
IN PRTMP_ADAPTER pAd,
OUT PUCHAR pFrameBuf,
OUT PULONG pFrameLen,
IN UINT8 DialogToken)
{
ULONG TempLen;
MakeOutgoingFrame(pFrameBuf, &TempLen,
1, &DialogToken,
END_OF_ARGS);
*pFrameLen = *pFrameLen + TempLen;
return;
}
/*
==========================================================================
Description:
Insert TPC Request IE into frame.
Parametrs:
1. frame buffer pointer.
2. frame length.
Return : None.
==========================================================================
*/
static VOID InsertTpcReqIE(
IN PRTMP_ADAPTER pAd,
OUT PUCHAR pFrameBuf,
OUT PULONG pFrameLen)
{
ULONG TempLen;
ULONG Len = 0;
UINT8 ElementID = IE_TPC_REQUEST;
MakeOutgoingFrame(pFrameBuf, &TempLen,
1, &ElementID,
1, &Len,
END_OF_ARGS);
*pFrameLen = *pFrameLen + TempLen;
return;
}
/*
==========================================================================
Description:
Insert TPC Report IE into frame.
Parametrs:
1. frame buffer pointer.
2. frame length.
3. Transmit Power.
4. Link Margin.
Return : None.
==========================================================================
*/
VOID InsertTpcReportIE(
IN PRTMP_ADAPTER pAd,
OUT PUCHAR pFrameBuf,
OUT PULONG pFrameLen,
IN UINT8 TxPwr,
IN UINT8 LinkMargin)
{
ULONG TempLen;
ULONG Len = sizeof(TPC_REPORT_INFO);
UINT8 ElementID = IE_TPC_REPORT;
TPC_REPORT_INFO TpcReportIE;
TpcReportIE.TxPwr = TxPwr;
TpcReportIE.LinkMargin = LinkMargin;
MakeOutgoingFrame(pFrameBuf, &TempLen,
1, &ElementID,
1, &Len,
Len, &TpcReportIE,
END_OF_ARGS);
*pFrameLen = *pFrameLen + TempLen;
return;
}
/*
==========================================================================
Description:
Insert Channel Switch Announcement IE into frame.
Parametrs:
1. frame buffer pointer.
2. frame length.
3. channel switch announcement mode.
4. new selected channel.
5. channel switch announcement count.
Return : None.
==========================================================================
*/
static VOID InsertChSwAnnIE(
IN PRTMP_ADAPTER pAd,
OUT PUCHAR pFrameBuf,
OUT PULONG pFrameLen,
IN UINT8 ChSwMode,
IN UINT8 NewChannel,
IN UINT8 ChSwCnt)
{
ULONG TempLen;
ULONG Len = sizeof(CH_SW_ANN_INFO);
UINT8 ElementID = IE_CHANNEL_SWITCH_ANNOUNCEMENT;
CH_SW_ANN_INFO ChSwAnnIE;
ChSwAnnIE.ChSwMode = ChSwMode;
ChSwAnnIE.Channel = NewChannel;
ChSwAnnIE.ChSwCnt = ChSwCnt;
MakeOutgoingFrame(pFrameBuf, &TempLen,
1, &ElementID,
1, &Len,
Len, &ChSwAnnIE,
END_OF_ARGS);
*pFrameLen = *pFrameLen + TempLen;
return;
}
/*
==========================================================================
Description:
Insert Measure Request IE into frame.
Parametrs:
1. frame buffer pointer.
2. frame length.
3. Measure Token.
4. Measure Request Mode.
5. Measure Request Type.
6. Measure Channel.
7. Measure Start time.
8. Measure Duration.
Return : None.
==========================================================================
*/
static VOID InsertMeasureReqIE(
IN PRTMP_ADAPTER pAd,
OUT PUCHAR pFrameBuf,
OUT PULONG pFrameLen,
IN UINT8 Len,
IN PMEASURE_REQ_INFO pMeasureReqIE)
{
ULONG TempLen;
UINT8 ElementID = IE_MEASUREMENT_REQUEST;
MakeOutgoingFrame(pFrameBuf, &TempLen,
1, &ElementID,
1, &Len,
sizeof(MEASURE_REQ_INFO), pMeasureReqIE,
END_OF_ARGS);
*pFrameLen = *pFrameLen + TempLen;
return;
}
/*
==========================================================================
Description:
Insert Measure Report IE into frame.
Parametrs:
1. frame buffer pointer.
2. frame length.
3. Measure Token.
4. Measure Request Mode.
5. Measure Request Type.
6. Length of Report Infomation
7. Pointer of Report Infomation Buffer.
Return : None.
==========================================================================
*/
static VOID InsertMeasureReportIE(
IN PRTMP_ADAPTER pAd,
OUT PUCHAR pFrameBuf,
OUT PULONG pFrameLen,
IN PMEASURE_REPORT_INFO pMeasureReportIE,
IN UINT8 ReportLnfoLen,
IN PUINT8 pReportInfo)
{
ULONG TempLen;
ULONG Len;
UINT8 ElementID = IE_MEASUREMENT_REPORT;
Len = sizeof(MEASURE_REPORT_INFO) + ReportLnfoLen;
MakeOutgoingFrame(pFrameBuf, &TempLen,
1, &ElementID,
1, &Len,
Len, pMeasureReportIE,
END_OF_ARGS);
*pFrameLen = *pFrameLen + TempLen;
if ((ReportLnfoLen > 0) && (pReportInfo != NULL))
{
MakeOutgoingFrame(pFrameBuf + *pFrameLen, &TempLen,
ReportLnfoLen, pReportInfo,
END_OF_ARGS);
*pFrameLen = *pFrameLen + TempLen;
}
return;
}
/*
==========================================================================
Description:
Prepare Measurement request action frame and enqueue it into
management queue waiting for transmition.
Parametrs:
1. the destination mac address of the frame.
Return : None.
==========================================================================
*/
VOID MakeMeasurementReqFrame(
IN PRTMP_ADAPTER pAd,
OUT PUCHAR pOutBuffer,
OUT PULONG pFrameLen,
IN UINT8 TotalLen,
IN UINT8 Category,
IN UINT8 Action,
IN UINT8 MeasureToken,
IN UINT8 MeasureReqMode,
IN UINT8 MeasureReqType,
IN UINT8 NumOfRepetitions)
{
ULONG TempLen;
MEASURE_REQ_INFO MeasureReqIE;
InsertActField(pAd, (pOutBuffer + *pFrameLen), pFrameLen, Category, Action);
// fill Dialog Token
InsertDialogToken(pAd, (pOutBuffer + *pFrameLen), pFrameLen, MeasureToken);
/* fill Number of repetitions. */
if (Category == CATEGORY_RM)
{
MakeOutgoingFrame((pOutBuffer+*pFrameLen), &TempLen,
2, &NumOfRepetitions,
END_OF_ARGS);
*pFrameLen += TempLen;
}
// prepare Measurement IE.
NdisZeroMemory(&MeasureReqIE, sizeof(MEASURE_REQ_INFO));
MeasureReqIE.Token = MeasureToken;
MeasureReqIE.ReqMode.word = MeasureReqMode;
MeasureReqIE.ReqType = MeasureReqType;
InsertMeasureReqIE(pAd, (pOutBuffer+*pFrameLen), pFrameLen,
TotalLen, &MeasureReqIE);
return;
}
/*
==========================================================================
Description:
Prepare Measurement report action frame and enqueue it into
management queue waiting for transmition.
Parametrs:
1. the destination mac address of the frame.
Return : None.
==========================================================================
*/
VOID EnqueueMeasurementRep(
IN PRTMP_ADAPTER pAd,
IN PUCHAR pDA,
IN UINT8 DialogToken,
IN UINT8 MeasureToken,
IN UINT8 MeasureReqMode,
IN UINT8 MeasureReqType,
IN UINT8 ReportInfoLen,
IN PUINT8 pReportInfo)
{
PUCHAR pOutBuffer = NULL;
NDIS_STATUS NStatus;
ULONG FrameLen;
HEADER_802_11 ActHdr;
MEASURE_REPORT_INFO MeasureRepIE;
// build action frame header.
MgtMacHeaderInit(pAd, &ActHdr, SUBTYPE_ACTION, 0, pDA,
pAd->CurrentAddress);
NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer); //Get an unused nonpaged memory
if(NStatus != NDIS_STATUS_SUCCESS)
{
DBGPRINT(RT_DEBUG_TRACE, ("%s() allocate memory failed \n", __FUNCTION__));
return;
}
NdisMoveMemory(pOutBuffer, (PCHAR)&ActHdr, sizeof(HEADER_802_11));
FrameLen = sizeof(HEADER_802_11);
InsertActField(pAd, (pOutBuffer + FrameLen), &FrameLen, CATEGORY_SPECTRUM, SPEC_MRP);
// fill Dialog Token
InsertDialogToken(pAd, (pOutBuffer + FrameLen), &FrameLen, DialogToken);
// prepare Measurement IE.
NdisZeroMemory(&MeasureRepIE, sizeof(MEASURE_REPORT_INFO));
MeasureRepIE.Token = MeasureToken;
MeasureRepIE.ReportMode = MeasureReqMode;
MeasureRepIE.ReportType = MeasureReqType;
InsertMeasureReportIE(pAd, (pOutBuffer + FrameLen), &FrameLen, &MeasureRepIE, ReportInfoLen, pReportInfo);
MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
MlmeFreeMemory(pAd, pOutBuffer);
return;
}
/*
==========================================================================
Description:
Prepare TPC Request action frame and enqueue it into
management queue waiting for transmition.
Parametrs:
1. the destination mac address of the frame.
Return : None.
==========================================================================
*/
VOID EnqueueTPCReq(
IN PRTMP_ADAPTER pAd,
IN PUCHAR pDA,
IN UCHAR DialogToken)
{
PUCHAR pOutBuffer = NULL;
NDIS_STATUS NStatus;
ULONG FrameLen;
HEADER_802_11 ActHdr;
// build action frame header.
MgtMacHeaderInit(pAd, &ActHdr, SUBTYPE_ACTION, 0, pDA,
pAd->CurrentAddress);
NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer); //Get an unused nonpaged memory
if(NStatus != NDIS_STATUS_SUCCESS)
{
DBGPRINT(RT_DEBUG_TRACE, ("%s() allocate memory failed \n", __FUNCTION__));
return;
}
NdisMoveMemory(pOutBuffer, (PCHAR)&ActHdr, sizeof(HEADER_802_11));
FrameLen = sizeof(HEADER_802_11);
InsertActField(pAd, (pOutBuffer + FrameLen), &FrameLen, CATEGORY_SPECTRUM, SPEC_TPCRQ);
// fill Dialog Token
InsertDialogToken(pAd, (pOutBuffer + FrameLen), &FrameLen, DialogToken);
// Insert TPC Request IE.
InsertTpcReqIE(pAd, (pOutBuffer + FrameLen), &FrameLen);
MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
MlmeFreeMemory(pAd, pOutBuffer);
return;
}
/*
==========================================================================
Description:
Prepare TPC Report action frame and enqueue it into
management queue waiting for transmition.
Parametrs:
1. the destination mac address of the frame.
Return : None.
==========================================================================
*/
VOID EnqueueTPCRep(
IN PRTMP_ADAPTER pAd,
IN PUCHAR pDA,
IN UINT8 DialogToken,
IN UINT8 TxPwr,
IN UINT8 LinkMargin)
{
PUCHAR pOutBuffer = NULL;
NDIS_STATUS NStatus;
ULONG FrameLen;
HEADER_802_11 ActHdr;
// build action frame header.
MgtMacHeaderInit(pAd, &ActHdr, SUBTYPE_ACTION, 0, pDA,
pAd->CurrentAddress);
NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer); //Get an unused nonpaged memory
if(NStatus != NDIS_STATUS_SUCCESS)
{
DBGPRINT(RT_DEBUG_TRACE, ("%s() allocate memory failed \n", __FUNCTION__));
return;
}
NdisMoveMemory(pOutBuffer, (PCHAR)&ActHdr, sizeof(HEADER_802_11));
FrameLen = sizeof(HEADER_802_11);
InsertActField(pAd, (pOutBuffer + FrameLen), &FrameLen, CATEGORY_SPECTRUM, SPEC_TPCRP);
// fill Dialog Token
InsertDialogToken(pAd, (pOutBuffer + FrameLen), &FrameLen, DialogToken);
// Insert TPC Request IE.
InsertTpcReportIE(pAd, (pOutBuffer + FrameLen), &FrameLen, TxPwr, LinkMargin);
MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
MlmeFreeMemory(pAd, pOutBuffer);
return;
}
/*
==========================================================================
Description:
Prepare Channel Switch Announcement action frame and enqueue it into
management queue waiting for transmition.
Parametrs:
1. the destination mac address of the frame.
2. Channel switch announcement mode.
2. a New selected channel.
Return : None.
==========================================================================
*/
VOID EnqueueChSwAnn(
IN PRTMP_ADAPTER pAd,
IN PUCHAR pDA,
IN UINT8 ChSwMode,
IN UINT8 NewCh)
{
PUCHAR pOutBuffer = NULL;
NDIS_STATUS NStatus;
ULONG FrameLen;
HEADER_802_11 ActHdr;
// build action frame header.
MgtMacHeaderInit(pAd, &ActHdr, SUBTYPE_ACTION, 0, pDA,
pAd->CurrentAddress);
NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer); //Get an unused nonpaged memory
if(NStatus != NDIS_STATUS_SUCCESS)
{
DBGPRINT(RT_DEBUG_TRACE, ("%s() allocate memory failed \n", __FUNCTION__));
return;
}
NdisMoveMemory(pOutBuffer, (PCHAR)&ActHdr, sizeof(HEADER_802_11));
FrameLen = sizeof(HEADER_802_11);
InsertActField(pAd, (pOutBuffer + FrameLen), &FrameLen, CATEGORY_SPECTRUM, SPEC_CHANNEL_SWITCH);
InsertChSwAnnIE(pAd, (pOutBuffer + FrameLen), &FrameLen, ChSwMode, NewCh, 0);
MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
MlmeFreeMemory(pAd, pOutBuffer);
return;
}
static BOOLEAN DfsRequirementCheck(
IN PRTMP_ADAPTER pAd,
IN UINT8 Channel)
{
BOOLEAN Result = FALSE;
INT i;
do
{
// check DFS procedure is running.
// make sure DFS procedure won't start twice.
if (pAd->CommonCfg.RadarDetect.RDMode != RD_NORMAL_MODE)
{
Result = FALSE;
break;
}
// check the new channel carried from Channel Switch Announcemnet is valid.
for (i=0; i<pAd->ChannelListNum; i++)
{
if ((Channel == pAd->ChannelList[i].Channel)
&&(pAd->ChannelList[i].RemainingTimeForUse == 0))
{
// found radar signal in the channel. the channel can't use at least for 30 minutes.
pAd->ChannelList[i].RemainingTimeForUse = 1800;//30 min = 1800 sec
Result = TRUE;
break;
}
}
} while(FALSE);
return Result;
}
VOID NotifyChSwAnnToPeerAPs(
IN PRTMP_ADAPTER pAd,
IN PUCHAR pRA,
IN PUCHAR pTA,
IN UINT8 ChSwMode,
IN UINT8 Channel)
{
#ifdef WDS_SUPPORT
if (!((pRA[0] & 0xff) == 0xff)) // is pRA a broadcase address.
{
INT i;
// info neighbor APs that Radar signal found throgh WDS link.
for (i = 0; i < MAX_WDS_ENTRY; i++)
{
if (ValidWdsEntry(pAd, i))
{
PUCHAR pDA = pAd->WdsTab.WdsEntry[i].PeerWdsAddr;
// DA equal to SA. have no necessary orignal AP which found Radar signal.
if (MAC_ADDR_EQUAL(pTA, pDA))
continue;
// send Channel Switch Action frame to info Neighbro APs.
EnqueueChSwAnn(pAd, pDA, ChSwMode, Channel);
}
}
}
#endif // WDS_SUPPORT //
}
static VOID StartDFSProcedure(
IN PRTMP_ADAPTER pAd,
IN UCHAR Channel,
IN UINT8 ChSwMode)
{
// start DFS procedure
pAd->CommonCfg.Channel = Channel;
#ifdef DOT11_N_SUPPORT
N_ChannelCheck(pAd);
#endif // DOT11_N_SUPPORT //
pAd->CommonCfg.RadarDetect.RDMode = RD_SWITCHING_MODE;
pAd->CommonCfg.RadarDetect.CSCount = 0;
}
/*
==========================================================================
Description:
Channel Switch Announcement action frame sanity check.
Parametrs:
1. MLME message containing the received frame
2. message length.
3. Channel switch announcement infomation buffer.
Return : None.
==========================================================================
*/
/*
Channel Switch Announcement IE.
+----+-----+-----------+------------+-----------+
| ID | Len |Ch Sw Mode | New Ch Num | Ch Sw Cnt |
+----+-----+-----------+------------+-----------+
1 1 1 1 1
*/
static BOOLEAN PeerChSwAnnSanity(
IN PRTMP_ADAPTER pAd,
IN VOID *pMsg,
IN ULONG MsgLen,
OUT PCH_SW_ANN_INFO pChSwAnnInfo)
{
PFRAME_802_11 Fr = (PFRAME_802_11)pMsg;
PUCHAR pFramePtr = Fr->Octet;
BOOLEAN result = FALSE;
PEID_STRUCT eid_ptr;
// skip 802.11 header.
MsgLen -= sizeof(HEADER_802_11);
// skip category and action code.
pFramePtr += 2;
MsgLen -= 2;
if (pChSwAnnInfo == NULL)
return result;
eid_ptr = (PEID_STRUCT)pFramePtr;
while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((PUCHAR)pFramePtr + MsgLen))
{
switch(eid_ptr->Eid)
{
case IE_CHANNEL_SWITCH_ANNOUNCEMENT:
NdisMoveMemory(&pChSwAnnInfo->ChSwMode, eid_ptr->Octet, 1);
NdisMoveMemory(&pChSwAnnInfo->Channel, eid_ptr->Octet + 1, 1);
NdisMoveMemory(&pChSwAnnInfo->ChSwCnt, eid_ptr->Octet + 2, 1);
result = TRUE;
break;
default:
break;
}
eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
}
return result;
}
/*
==========================================================================
Description:
Measurement request action frame sanity check.
Parametrs:
1. MLME message containing the received frame
2. message length.
3. Measurement request infomation buffer.
Return : None.
==========================================================================
*/
static BOOLEAN PeerMeasureReqSanity(
IN PRTMP_ADAPTER pAd,
IN VOID *pMsg,
IN ULONG MsgLen,
OUT PUINT8 pDialogToken,
OUT PMEASURE_REQ_INFO pMeasureReqInfo,
OUT PMEASURE_REQ pMeasureReq)
{
PFRAME_802_11 Fr = (PFRAME_802_11)pMsg;
PUCHAR pFramePtr = Fr->Octet;
BOOLEAN result = FALSE;
PEID_STRUCT eid_ptr;
PUCHAR ptr;
UINT64 MeasureStartTime;
UINT16 MeasureDuration;
// skip 802.11 header.
MsgLen -= sizeof(HEADER_802_11);
// skip category and action code.
pFramePtr += 2;
MsgLen -= 2;
if (pMeasureReqInfo == NULL)
return result;
NdisMoveMemory(pDialogToken, pFramePtr, 1);
pFramePtr += 1;
MsgLen -= 1;
eid_ptr = (PEID_STRUCT)pFramePtr;
while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((PUCHAR)pFramePtr + MsgLen))
{
switch(eid_ptr->Eid)
{
case IE_MEASUREMENT_REQUEST:
NdisMoveMemory(&pMeasureReqInfo->Token, eid_ptr->Octet, 1);
NdisMoveMemory(&pMeasureReqInfo->ReqMode.word, eid_ptr->Octet + 1, 1);
NdisMoveMemory(&pMeasureReqInfo->ReqType, eid_ptr->Octet + 2, 1);
ptr = (PUCHAR)(eid_ptr->Octet + 3);
NdisMoveMemory(&pMeasureReq->ChNum, ptr, 1);
NdisMoveMemory(&MeasureStartTime, ptr + 1, 8);
pMeasureReq->MeasureStartTime = SWAP64(MeasureStartTime);
NdisMoveMemory(&MeasureDuration, ptr + 9, 2);
pMeasureReq->MeasureDuration = SWAP16(MeasureDuration);
result = TRUE;
break;
default:
break;
}
eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
}
return result;
}
/*
==========================================================================
Description:
Measurement report action frame sanity check.
Parametrs:
1. MLME message containing the received frame
2. message length.
3. Measurement report infomation buffer.
4. basic report infomation buffer.
Return : None.
==========================================================================
*/
/*
Measurement Report IE.
+----+-----+-------+-------------+--------------+----------------+
| ID | Len | Token | Report Mode | Measure Type | Measure Report |
+----+-----+-------+-------------+--------------+----------------+
1 1 1 1 1 variable
Basic Report.
+--------+------------+----------+-----+
| Ch Num | Start Time | Duration | Map |
+--------+------------+----------+-----+
1 8 2 1
Map Field Bit Format.
+-----+---------------+---------------------+-------+------------+----------+
| Bss | OFDM Preamble | Unidentified signal | Radar | Unmeasured | Reserved |
+-----+---------------+---------------------+-------+------------+----------+
0 1 2 3 4 5-7
*/
static BOOLEAN PeerMeasureReportSanity(
IN PRTMP_ADAPTER pAd,
IN VOID *pMsg,
IN ULONG MsgLen,
OUT PUINT8 pDialogToken,
OUT PMEASURE_REPORT_INFO pMeasureReportInfo,
OUT PUINT8 pReportBuf)
{
PFRAME_802_11 Fr = (PFRAME_802_11)pMsg;
PUCHAR pFramePtr = Fr->Octet;
BOOLEAN result = FALSE;
PEID_STRUCT eid_ptr;
PUCHAR ptr;
// skip 802.11 header.
MsgLen -= sizeof(HEADER_802_11);
// skip category and action code.
pFramePtr += 2;
MsgLen -= 2;
if (pMeasureReportInfo == NULL)
return result;
NdisMoveMemory(pDialogToken, pFramePtr, 1);
pFramePtr += 1;
MsgLen -= 1;
eid_ptr = (PEID_STRUCT)pFramePtr;
while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((PUCHAR)pFramePtr + MsgLen))
{
switch(eid_ptr->Eid)
{
case IE_MEASUREMENT_REPORT:
NdisMoveMemory(&pMeasureReportInfo->Token, eid_ptr->Octet, 1);
NdisMoveMemory(&pMeasureReportInfo->ReportMode, eid_ptr->Octet + 1, 1);
NdisMoveMemory(&pMeasureReportInfo->ReportType, eid_ptr->Octet + 2, 1);
if (pMeasureReportInfo->ReportType == RM_BASIC)
{
PMEASURE_BASIC_REPORT pReport = (PMEASURE_BASIC_REPORT)pReportBuf;
ptr = (PUCHAR)(eid_ptr->Octet + 3);
NdisMoveMemory(&pReport->ChNum, ptr, 1);
NdisMoveMemory(&pReport->MeasureStartTime, ptr + 1, 8);
NdisMoveMemory(&pReport->MeasureDuration, ptr + 9, 2);
NdisMoveMemory(&pReport->Map, ptr + 11, 1);
}
else if (pMeasureReportInfo->ReportType == RM_CCA)
{
PMEASURE_CCA_REPORT pReport = (PMEASURE_CCA_REPORT)pReportBuf;
ptr = (PUCHAR)(eid_ptr->Octet + 3);
NdisMoveMemory(&pReport->ChNum, ptr, 1);
NdisMoveMemory(&pReport->MeasureStartTime, ptr + 1, 8);
NdisMoveMemory(&pReport->MeasureDuration, ptr + 9, 2);
NdisMoveMemory(&pReport->CCA_Busy_Fraction, ptr + 11, 1);
}
else if (pMeasureReportInfo->ReportType == RM_RPI_HISTOGRAM)
{
PMEASURE_RPI_REPORT pReport = (PMEASURE_RPI_REPORT)pReportBuf;
ptr = (PUCHAR)(eid_ptr->Octet + 3);
NdisMoveMemory(&pReport->ChNum, ptr, 1);
NdisMoveMemory(&pReport->MeasureStartTime, ptr + 1, 8);
NdisMoveMemory(&pReport->MeasureDuration, ptr + 9, 2);
NdisMoveMemory(&pReport->RPI_Density, ptr + 11, 8);
}
result = TRUE;
break;
default:
break;
}
eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
}
return result;
}
/*
==========================================================================
Description:
TPC Request action frame sanity check.
Parametrs:
1. MLME message containing the received frame
2. message length.
3. Dialog Token.
Return : None.
==========================================================================
*/
static BOOLEAN PeerTpcReqSanity(
IN PRTMP_ADAPTER pAd,
IN VOID *pMsg,
IN ULONG MsgLen,
OUT PUINT8 pDialogToken)
{
PFRAME_802_11 Fr = (PFRAME_802_11)pMsg;
PUCHAR pFramePtr = Fr->Octet;
BOOLEAN result = FALSE;
PEID_STRUCT eid_ptr;
MsgLen -= sizeof(HEADER_802_11);
// skip category and action code.
pFramePtr += 2;
MsgLen -= 2;
if (pDialogToken == NULL)
return result;
NdisMoveMemory(pDialogToken, pFramePtr, 1);
pFramePtr += 1;
MsgLen -= 1;
eid_ptr = (PEID_STRUCT)pFramePtr;
while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((PUCHAR)pFramePtr + MsgLen))
{
switch(eid_ptr->Eid)
{
case IE_TPC_REQUEST:
result = TRUE;
break;
default:
break;
}
eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
}
return result;
}
/*
==========================================================================
Description:
TPC Report action frame sanity check.
Parametrs:
1. MLME message containing the received frame
2. message length.
3. Dialog Token.
4. TPC Report IE.
Return : None.
==========================================================================
*/
static BOOLEAN PeerTpcRepSanity(
IN PRTMP_ADAPTER pAd,
IN VOID *pMsg,
IN ULONG MsgLen,
OUT PUINT8 pDialogToken,
OUT PTPC_REPORT_INFO pTpcRepInfo)
{
PFRAME_802_11 Fr = (PFRAME_802_11)pMsg;
PUCHAR pFramePtr = Fr->Octet;
BOOLEAN result = FALSE;
PEID_STRUCT eid_ptr;
MsgLen -= sizeof(HEADER_802_11);
// skip category and action code.
pFramePtr += 2;
MsgLen -= 2;
if (pDialogToken == NULL)
return result;
NdisMoveMemory(pDialogToken, pFramePtr, 1);
pFramePtr += 1;
MsgLen -= 1;
eid_ptr = (PEID_STRUCT)pFramePtr;
while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((PUCHAR)pFramePtr + MsgLen))
{
switch(eid_ptr->Eid)
{
case IE_TPC_REPORT:
NdisMoveMemory(&pTpcRepInfo->TxPwr, eid_ptr->Octet, 1);
NdisMoveMemory(&pTpcRepInfo->LinkMargin, eid_ptr->Octet + 1, 1);
result = TRUE;
break;
default:
break;
}
eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
}
return result;
}
/*
==========================================================================
Description:
Channel Switch Announcement action frame handler.
Parametrs:
Elme - MLME message containing the received frame
Return : None.
==========================================================================
*/
static VOID PeerChSwAnnAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
CH_SW_ANN_INFO ChSwAnnInfo;
PFRAME_802_11 pFr = (PFRAME_802_11)Elem->Msg;
#ifdef CONFIG_STA_SUPPORT
UCHAR index = 0, Channel = 0, NewChannel = 0;
ULONG Bssidx = 0;
#endif // CONFIG_STA_SUPPORT //
NdisZeroMemory(&ChSwAnnInfo, sizeof(CH_SW_ANN_INFO));
if (! PeerChSwAnnSanity(pAd, Elem->Msg, Elem->MsgLen, &ChSwAnnInfo))
{
DBGPRINT(RT_DEBUG_TRACE, ("Invalid Channel Switch Action Frame.\n"));
return;
}
#ifdef CONFIG_STA_SUPPORT
if (pAd->OpMode == OPMODE_STA)
{
Bssidx = BssTableSearch(&pAd->ScanTab, pFr->Hdr.Addr3, pAd->CommonCfg.Channel);
if (Bssidx == BSS_NOT_FOUND)
{
DBGPRINT(RT_DEBUG_TRACE, ("PeerChSwAnnAction - Bssidx is not found\n"));
return;
}
DBGPRINT(RT_DEBUG_TRACE, ("\n****Bssidx is %d, Channel = %d\n", index, pAd->ScanTab.BssEntry[Bssidx].Channel));
hex_dump("SSID",pAd->ScanTab.BssEntry[Bssidx].Bssid ,6);
Channel = pAd->CommonCfg.Channel;
NewChannel = ChSwAnnInfo.Channel;
if ((pAd->CommonCfg.bIEEE80211H == 1) && (NewChannel != 0) && (Channel != NewChannel))
{
// Switching to channel 1 can prevent from rescanning the current channel immediately (by auto reconnection).
// In addition, clear the MLME queue and the scan table to discard the RX packets and previous scanning results.
AsicSwitchChannel(pAd, 1, FALSE);
AsicLockChannel(pAd, 1);
LinkDown(pAd, FALSE);
MlmeQueueInit(&pAd->Mlme.Queue);
BssTableInit(&pAd->ScanTab);
RTMPusecDelay(1000000); // use delay to prevent STA do reassoc
// channel sanity check
for (index = 0 ; index < pAd->ChannelListNum; index++)
{
if (pAd->ChannelList[index].Channel == NewChannel)
{
pAd->ScanTab.BssEntry[Bssidx].Channel = NewChannel;
pAd->CommonCfg.Channel = NewChannel;
AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
AsicLockChannel(pAd, pAd->CommonCfg.Channel);
DBGPRINT(RT_DEBUG_TRACE, ("&&&&&&&&&&&&&&&&PeerChSwAnnAction - STA receive channel switch announcement IE (New Channel =%d)\n", NewChannel));
break;
}
}
if (index >= pAd->ChannelListNum)
{
DBGPRINT_ERR(("&&&&&&&&&&&&&&&&&&&&&&&&&&PeerChSwAnnAction(can not find New Channel=%d in ChannelList[%d]\n", pAd->CommonCfg.Channel, pAd->ChannelListNum));
}
}
}
#endif // CONFIG_STA_SUPPORT //
return;
}
/*
==========================================================================
Description:
Measurement Request action frame handler.
Parametrs:
Elme - MLME message containing the received frame
Return : None.
==========================================================================
*/
static VOID PeerMeasureReqAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
PFRAME_802_11 pFr = (PFRAME_802_11)Elem->Msg;
UINT8 DialogToken;
MEASURE_REQ_INFO MeasureReqInfo;
MEASURE_REQ MeasureReq;
MEASURE_REPORT_MODE ReportMode;
if(PeerMeasureReqSanity(pAd, Elem->Msg, Elem->MsgLen, &DialogToken, &MeasureReqInfo, &MeasureReq))
{
ReportMode.word = 0;
ReportMode.field.Incapable = 1;
EnqueueMeasurementRep(pAd, pFr->Hdr.Addr2, DialogToken, MeasureReqInfo.Token, ReportMode.word, MeasureReqInfo.ReqType, 0, NULL);
}
return;
}
/*
==========================================================================
Description:
Measurement Report action frame handler.
Parametrs:
Elme - MLME message containing the received frame
Return : None.
==========================================================================
*/
static VOID PeerMeasureReportAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
MEASURE_REPORT_INFO MeasureReportInfo;
PFRAME_802_11 pFr = (PFRAME_802_11)Elem->Msg;
UINT8 DialogToken;
PUINT8 pMeasureReportInfo;
// if (pAd->CommonCfg.bIEEE80211H != TRUE)
// return;
if ((pMeasureReportInfo = kmalloc(sizeof(MEASURE_RPI_REPORT), GFP_ATOMIC)) == NULL)
{
DBGPRINT(RT_DEBUG_ERROR, ("%s unable to alloc memory for measure report buffer (size=%d).\n", __FUNCTION__, sizeof(MEASURE_RPI_REPORT)));
return;
}
NdisZeroMemory(&MeasureReportInfo, sizeof(MEASURE_REPORT_INFO));
NdisZeroMemory(pMeasureReportInfo, sizeof(MEASURE_RPI_REPORT));
if (PeerMeasureReportSanity(pAd, Elem->Msg, Elem->MsgLen, &DialogToken, &MeasureReportInfo, pMeasureReportInfo))
{
do {
PMEASURE_REQ_ENTRY pEntry = NULL;
// Not a autonomous measure report.
// check the dialog token field. drop it if the dialog token doesn't match.
if ((DialogToken != 0)
&& ((pEntry = MeasureReqLookUp(pAd, DialogToken)) == NULL))
break;
if (pEntry != NULL)
MeasureReqDelete(pAd, pEntry->DialogToken);
if (MeasureReportInfo.ReportType == RM_BASIC)
{
PMEASURE_BASIC_REPORT pBasicReport = (PMEASURE_BASIC_REPORT)pMeasureReportInfo;
if ((pBasicReport->Map.field.Radar)
&& (DfsRequirementCheck(pAd, pBasicReport->ChNum) == TRUE))
{
NotifyChSwAnnToPeerAPs(pAd, pFr->Hdr.Addr1, pFr->Hdr.Addr2, 1, pBasicReport->ChNum);
StartDFSProcedure(pAd, pBasicReport->ChNum, 1);
}
}
} while (FALSE);
}
else
DBGPRINT(RT_DEBUG_TRACE, ("Invalid Measurement Report Frame.\n"));
kfree(pMeasureReportInfo);
return;
}
/*
==========================================================================
Description:
TPC Request action frame handler.
Parametrs:
Elme - MLME message containing the received frame
Return : None.
==========================================================================
*/
static VOID PeerTpcReqAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
PFRAME_802_11 pFr = (PFRAME_802_11)Elem->Msg;
PUCHAR pFramePtr = pFr->Octet;
UINT8 DialogToken;
UINT8 TxPwr = GetCurTxPwr(pAd, Elem->Wcid);
UINT8 LinkMargin = 0;
CHAR RealRssi;
// link margin: Ratio of the received signal power to the minimum desired by the station (STA). The
// STA may incorporate rate information and channel conditions, including interference, into its computation
// of link margin.
RealRssi = RTMPMaxRssi(pAd, ConvertToRssi(pAd, Elem->Rssi0, RSSI_0),
ConvertToRssi(pAd, Elem->Rssi1, RSSI_1),
ConvertToRssi(pAd, Elem->Rssi2, RSSI_2));
// skip Category and action code.
pFramePtr += 2;
// Dialog token.
NdisMoveMemory(&DialogToken, pFramePtr, 1);
LinkMargin = (RealRssi / MIN_RCV_PWR);
if (PeerTpcReqSanity(pAd, Elem->Msg, Elem->MsgLen, &DialogToken))
EnqueueTPCRep(pAd, pFr->Hdr.Addr2, DialogToken, TxPwr, LinkMargin);
return;
}
/*
==========================================================================
Description:
TPC Report action frame handler.
Parametrs:
Elme - MLME message containing the received frame
Return : None.
==========================================================================
*/
static VOID PeerTpcRepAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
UINT8 DialogToken;
TPC_REPORT_INFO TpcRepInfo;
PTPC_REQ_ENTRY pEntry = NULL;
NdisZeroMemory(&TpcRepInfo, sizeof(TPC_REPORT_INFO));
if (PeerTpcRepSanity(pAd, Elem->Msg, Elem->MsgLen, &DialogToken, &TpcRepInfo))
{
if ((pEntry = TpcReqLookUp(pAd, DialogToken)) != NULL)
{
TpcReqDelete(pAd, pEntry->DialogToken);
DBGPRINT(RT_DEBUG_TRACE, ("%s: DialogToken=%x, TxPwr=%d, LinkMargin=%d\n",
__FUNCTION__, DialogToken, TpcRepInfo.TxPwr, TpcRepInfo.LinkMargin));
}
}
return;
}
/*
==========================================================================
Description:
Spectrun action frames Handler such as channel switch annoucement,
measurement report, measurement request actions frames.
Parametrs:
Elme - MLME message containing the received frame
Return : None.
==========================================================================
*/
VOID PeerSpectrumAction(
IN PRTMP_ADAPTER pAd,
IN MLME_QUEUE_ELEM *Elem)
{
UCHAR Action = Elem->Msg[LENGTH_802_11+1];
if (pAd->CommonCfg.bIEEE80211H != TRUE)
return;
switch(Action)
{
case SPEC_MRQ:
// current rt2860 unable do such measure specified in Measurement Request.
// reject all measurement request.
PeerMeasureReqAction(pAd, Elem);
break;
case SPEC_MRP:
PeerMeasureReportAction(pAd, Elem);
break;
case SPEC_TPCRQ:
PeerTpcReqAction(pAd, Elem);
break;
case SPEC_TPCRP:
PeerTpcRepAction(pAd, Elem);
break;
case SPEC_CHANNEL_SWITCH:
#ifdef DOT11N_DRAFT3
{
SEC_CHA_OFFSET_IE Secondary;
CHA_SWITCH_ANNOUNCE_IE ChannelSwitch;
// 802.11h only has Channel Switch Announcement IE.
RTMPMoveMemory(&ChannelSwitch, &Elem->Msg[LENGTH_802_11+4], sizeof (CHA_SWITCH_ANNOUNCE_IE));
// 802.11n D3.03 adds secondary channel offset element in the end.
if (Elem->MsgLen == (LENGTH_802_11 + 2 + sizeof (CHA_SWITCH_ANNOUNCE_IE) + sizeof (SEC_CHA_OFFSET_IE)))
{
RTMPMoveMemory(&Secondary, &Elem->Msg[LENGTH_802_11+9], sizeof (SEC_CHA_OFFSET_IE));
}
else
{
Secondary.SecondaryChannelOffset = 0;
}
if ((Elem->Msg[LENGTH_802_11+2] == IE_CHANNEL_SWITCH_ANNOUNCEMENT) && (Elem->Msg[LENGTH_802_11+3] == 3))
{
ChannelSwitchAction(pAd, Elem->Wcid, ChannelSwitch.NewChannel, Secondary.SecondaryChannelOffset);
}
}
#endif // DOT11N_DRAFT3 //
PeerChSwAnnAction(pAd, Elem);
break;
}
return;
}
/*
==========================================================================
Description:
Parametrs:
Return : None.
==========================================================================
*/
INT Set_MeasureReq_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
UINT Aid = 1;
UINT ArgIdx;
PSTRING thisChar;
MEASURE_REQ_MODE MeasureReqMode;
UINT8 MeasureReqToken = RandomByte(pAd);
UINT8 MeasureReqType = RM_BASIC;
UINT8 MeasureCh = 1;
UINT64 MeasureStartTime = GetCurrentTimeStamp(pAd);
MEASURE_REQ MeasureReq;
UINT8 TotalLen;
HEADER_802_11 ActHdr;
PUCHAR pOutBuffer = NULL;
NDIS_STATUS NStatus;
ULONG FrameLen;
NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer); //Get an unused nonpaged memory
if(NStatus != NDIS_STATUS_SUCCESS)
{
DBGPRINT(RT_DEBUG_TRACE, ("%s() allocate memory failed \n", __FUNCTION__));
goto END_OF_MEASURE_REQ;
}
ArgIdx = 1;
while ((thisChar = strsep((char **)&arg, "-")) != NULL)
{
switch(ArgIdx)
{
case 1: // Aid.
Aid = (UINT8) simple_strtol(thisChar, 0, 16);
break;
case 2: // Measurement Request Type.
MeasureReqType = simple_strtol(thisChar, 0, 16);
if (MeasureReqType > 3)
{
DBGPRINT(RT_DEBUG_ERROR, ("%s: unknow MeasureReqType(%d)\n", __FUNCTION__, MeasureReqType));
goto END_OF_MEASURE_REQ;
}
break;
case 3: // Measurement channel.
MeasureCh = (UINT8) simple_strtol(thisChar, 0, 16);
break;
}
ArgIdx++;
}
DBGPRINT(RT_DEBUG_TRACE, ("%s::Aid = %d, MeasureReqType=%d MeasureCh=%d\n", __FUNCTION__, Aid, MeasureReqType, MeasureCh));
if (!VALID_WCID(Aid))
{
DBGPRINT(RT_DEBUG_ERROR, ("%s: unknow sta of Aid(%d)\n", __FUNCTION__, Aid));
goto END_OF_MEASURE_REQ;
}
MeasureReqMode.word = 0;
MeasureReqMode.field.Enable = 1;
MeasureReqInsert(pAd, MeasureReqToken);
// build action frame header.
MgtMacHeaderInit(pAd, &ActHdr, SUBTYPE_ACTION, 0, pAd->MacTab.Content[Aid].Addr,
pAd->CurrentAddress);
NdisMoveMemory(pOutBuffer, (PCHAR)&ActHdr, sizeof(HEADER_802_11));
FrameLen = sizeof(HEADER_802_11);
TotalLen = sizeof(MEASURE_REQ_INFO) + sizeof(MEASURE_REQ);
MakeMeasurementReqFrame(pAd, pOutBuffer, &FrameLen,
sizeof(MEASURE_REQ_INFO), CATEGORY_RM, RM_BASIC,
MeasureReqToken, MeasureReqMode.word,
MeasureReqType, 0);
MeasureReq.ChNum = MeasureCh;
MeasureReq.MeasureStartTime = cpu2le64(MeasureStartTime);
MeasureReq.MeasureDuration = cpu2le16(2000);
{
ULONG TempLen;
MakeOutgoingFrame( pOutBuffer+FrameLen, &TempLen,
sizeof(MEASURE_REQ), &MeasureReq,
END_OF_ARGS);
FrameLen += TempLen;
}
MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, (UINT)FrameLen);
END_OF_MEASURE_REQ:
MlmeFreeMemory(pAd, pOutBuffer);
return TRUE;
}
INT Set_TpcReq_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
UINT Aid;
UINT8 TpcReqToken = RandomByte(pAd);
Aid = (UINT) simple_strtol(arg, 0, 16);
DBGPRINT(RT_DEBUG_TRACE, ("%s::Aid = %d\n", __FUNCTION__, Aid));
if (!VALID_WCID(Aid))
{
DBGPRINT(RT_DEBUG_ERROR, ("%s: unknow sta of Aid(%d)\n", __FUNCTION__, Aid));
return TRUE;
}
TpcReqInsert(pAd, TpcReqToken);
EnqueueTPCReq(pAd, pAd->MacTab.Content[Aid].Addr, TpcReqToken);
return TRUE;
}
| gpl-2.0 |
danonbrown/trltetmo-kernel | drivers/staging/comedi/drivers/adv_pci1710.c | 510 | 42339 | /*
* comedi/drivers/adv_pci1710.c
*
* Author: Michal Dobes <dobes@tesnet.cz>
*
* Thanks to ZhenGang Shang <ZhenGang.Shang@Advantech.com.cn>
* for testing and informations.
*
* hardware driver for Advantech cards:
* card: PCI-1710, PCI-1710HG, PCI-1711, PCI-1713, PCI-1720, PCI-1731
* driver: pci1710, pci1710hg, pci1711, pci1713, pci1720, pci1731
*
* Options:
* [0] - PCI bus number - if bus number and slot number are 0,
* then driver search for first unused card
* [1] - PCI slot number
*
*/
/*
Driver: adv_pci1710
Description: Advantech PCI-1710, PCI-1710HG, PCI-1711, PCI-1713,
Advantech PCI-1720, PCI-1731
Author: Michal Dobes <dobes@tesnet.cz>
Devices: [Advantech] PCI-1710 (adv_pci1710), PCI-1710HG (pci1710hg),
PCI-1711 (adv_pci1710), PCI-1713, PCI-1720,
PCI-1731
Status: works
This driver supports AI, AO, DI and DO subdevices.
AI subdevice supports cmd and insn interface,
other subdevices support only insn interface.
The PCI-1710 and PCI-1710HG have the same PCI device ID, so the
driver cannot distinguish between them, as would be normal for a
PCI driver.
Configuration options:
[0] - PCI bus of device (optional)
[1] - PCI slot of device (optional)
If bus/slot is not specified, the first available PCI
device will be used.
*/
#include <linux/pci.h>
#include <linux/interrupt.h>
#include "../comedidev.h"
#include "comedi_fc.h"
#include "8253.h"
#include "amcc_s5933.h"
#define PCI171x_PARANOIDCHECK /* if defined, then is used code which control
* correct channel number on every 12 bit
* sample */
/* hardware types of the cards */
#define TYPE_PCI171X 0
#define TYPE_PCI1713 2
#define TYPE_PCI1720 3
#define PCI171x_AD_DATA 0 /* R: A/D data */
#define PCI171x_SOFTTRG 0 /* W: soft trigger for A/D */
#define PCI171x_RANGE 2 /* W: A/D gain/range register */
#define PCI171x_MUX 4 /* W: A/D multiplexor control */
#define PCI171x_STATUS 6 /* R: status register */
#define PCI171x_CONTROL 6 /* W: control register */
#define PCI171x_CLRINT 8 /* W: clear interrupts request */
#define PCI171x_CLRFIFO 9 /* W: clear FIFO */
#define PCI171x_DA1 10 /* W: D/A register */
#define PCI171x_DA2 12 /* W: D/A register */
#define PCI171x_DAREF 14 /* W: D/A reference control */
#define PCI171x_DI 16 /* R: digi inputs */
#define PCI171x_DO 16 /* R: digi inputs */
#define PCI171x_CNT0 24 /* R/W: 8254 counter 0 */
#define PCI171x_CNT1 26 /* R/W: 8254 counter 1 */
#define PCI171x_CNT2 28 /* R/W: 8254 counter 2 */
#define PCI171x_CNTCTRL 30 /* W: 8254 counter control */
/* upper bits from status register (PCI171x_STATUS) (lower is same with control
* reg) */
#define Status_FE 0x0100 /* 1=FIFO is empty */
#define Status_FH 0x0200 /* 1=FIFO is half full */
#define Status_FF 0x0400 /* 1=FIFO is full, fatal error */
#define Status_IRQ 0x0800 /* 1=IRQ occurred */
/* bits from control register (PCI171x_CONTROL) */
#define Control_CNT0 0x0040 /* 1=CNT0 have external source,
* 0=have internal 100kHz source */
#define Control_ONEFH 0x0020 /* 1=IRQ on FIFO is half full, 0=every sample */
#define Control_IRQEN 0x0010 /* 1=enable IRQ */
#define Control_GATE 0x0008 /* 1=enable external trigger GATE (8254?) */
#define Control_EXT 0x0004 /* 1=external trigger source */
#define Control_PACER 0x0002 /* 1=enable internal 8254 trigger source */
#define Control_SW 0x0001 /* 1=enable software trigger source */
/* bits from counter control register (PCI171x_CNTCTRL) */
#define Counter_BCD 0x0001 /* 0 = binary counter, 1 = BCD counter */
#define Counter_M0 0x0002 /* M0-M2 select modes 0-5 */
#define Counter_M1 0x0004 /* 000 = mode 0, 010 = mode 2 ... */
#define Counter_M2 0x0008
#define Counter_RW0 0x0010 /* RW0/RW1 select read/write mode */
#define Counter_RW1 0x0020
#define Counter_SC0 0x0040 /* Select Counter. Only 00 or 11 may */
#define Counter_SC1 0x0080 /* be used, 00 for CNT0,
* 11 for read-back command */
#define PCI1720_DA0 0 /* W: D/A register 0 */
#define PCI1720_DA1 2 /* W: D/A register 1 */
#define PCI1720_DA2 4 /* W: D/A register 2 */
#define PCI1720_DA3 6 /* W: D/A register 3 */
#define PCI1720_RANGE 8 /* R/W: D/A range register */
#define PCI1720_SYNCOUT 9 /* W: D/A synchronized output register */
#define PCI1720_SYNCONT 15 /* R/W: D/A synchronized control */
/* D/A synchronized control (PCI1720_SYNCONT) */
#define Syncont_SC0 1 /* set synchronous output mode */
static const struct comedi_lrange range_pci1710_3 = { 9, {
BIP_RANGE(5),
BIP_RANGE(2.5),
BIP_RANGE(1.25),
BIP_RANGE(0.625),
BIP_RANGE(10),
UNI_RANGE(10),
UNI_RANGE(5),
UNI_RANGE(2.5),
UNI_RANGE(1.25)
}
};
static const char range_codes_pci1710_3[] = { 0x00, 0x01, 0x02, 0x03, 0x04,
0x10, 0x11, 0x12, 0x13 };
static const struct comedi_lrange range_pci1710hg = { 12, {
BIP_RANGE(5),
BIP_RANGE(0.5),
BIP_RANGE(0.05),
BIP_RANGE(0.005),
BIP_RANGE(10),
BIP_RANGE(1),
BIP_RANGE(0.1),
BIP_RANGE(0.01),
UNI_RANGE(10),
UNI_RANGE(1),
UNI_RANGE(0.1),
UNI_RANGE(0.01)
}
};
static const char range_codes_pci1710hg[] = { 0x00, 0x01, 0x02, 0x03, 0x04,
0x05, 0x06, 0x07, 0x10, 0x11,
0x12, 0x13 };
static const struct comedi_lrange range_pci17x1 = { 5, {
BIP_RANGE(10),
BIP_RANGE(5),
BIP_RANGE(2.5),
BIP_RANGE(1.25),
BIP_RANGE(0.625)
}
};
static const char range_codes_pci17x1[] = { 0x00, 0x01, 0x02, 0x03, 0x04 };
static const struct comedi_lrange range_pci1720 = { 4, {
UNI_RANGE(5),
UNI_RANGE(10),
BIP_RANGE(5),
BIP_RANGE(10)
}
};
static const struct comedi_lrange range_pci171x_da = { 2, {
UNI_RANGE(5),
UNI_RANGE(10),
}
};
enum pci1710_boardid {
BOARD_PCI1710,
BOARD_PCI1710HG,
BOARD_PCI1711,
BOARD_PCI1713,
BOARD_PCI1720,
BOARD_PCI1731,
};
struct boardtype {
const char *name; /* board name */
char have_irq; /* 1=card support IRQ */
char cardtype; /* 0=1710& co. 2=1713, ... */
int n_aichan; /* num of A/D chans */
int n_aichand; /* num of A/D chans in diff mode */
int n_aochan; /* num of D/A chans */
int n_dichan; /* num of DI chans */
int n_dochan; /* num of DO chans */
int n_counter; /* num of counters */
int ai_maxdata; /* resolution of A/D */
int ao_maxdata; /* resolution of D/A */
const struct comedi_lrange *rangelist_ai; /* rangelist for A/D */
const char *rangecode_ai; /* range codes for programming */
const struct comedi_lrange *rangelist_ao; /* rangelist for D/A */
unsigned int ai_ns_min; /* max sample speed of card v ns */
unsigned int fifo_half_size; /* size of FIFO/2 */
};
static const struct boardtype boardtypes[] = {
[BOARD_PCI1710] = {
.name = "pci1710",
.have_irq = 1,
.cardtype = TYPE_PCI171X,
.n_aichan = 16,
.n_aichand = 8,
.n_aochan = 2,
.n_dichan = 16,
.n_dochan = 16,
.n_counter = 1,
.ai_maxdata = 0x0fff,
.ao_maxdata = 0x0fff,
.rangelist_ai = &range_pci1710_3,
.rangecode_ai = range_codes_pci1710_3,
.rangelist_ao = &range_pci171x_da,
.ai_ns_min = 10000,
.fifo_half_size = 2048,
},
[BOARD_PCI1710HG] = {
.name = "pci1710hg",
.have_irq = 1,
.cardtype = TYPE_PCI171X,
.n_aichan = 16,
.n_aichand = 8,
.n_aochan = 2,
.n_dichan = 16,
.n_dochan = 16,
.n_counter = 1,
.ai_maxdata = 0x0fff,
.ao_maxdata = 0x0fff,
.rangelist_ai = &range_pci1710hg,
.rangecode_ai = range_codes_pci1710hg,
.rangelist_ao = &range_pci171x_da,
.ai_ns_min = 10000,
.fifo_half_size = 2048,
},
[BOARD_PCI1711] = {
.name = "pci1711",
.have_irq = 1,
.cardtype = TYPE_PCI171X,
.n_aichan = 16,
.n_aochan = 2,
.n_dichan = 16,
.n_dochan = 16,
.n_counter = 1,
.ai_maxdata = 0x0fff,
.ao_maxdata = 0x0fff,
.rangelist_ai = &range_pci17x1,
.rangecode_ai = range_codes_pci17x1,
.rangelist_ao = &range_pci171x_da,
.ai_ns_min = 10000,
.fifo_half_size = 512,
},
[BOARD_PCI1713] = {
.name = "pci1713",
.have_irq = 1,
.cardtype = TYPE_PCI1713,
.n_aichan = 32,
.n_aichand = 16,
.ai_maxdata = 0x0fff,
.rangelist_ai = &range_pci1710_3,
.rangecode_ai = range_codes_pci1710_3,
.ai_ns_min = 10000,
.fifo_half_size = 2048,
},
[BOARD_PCI1720] = {
.name = "pci1720",
.cardtype = TYPE_PCI1720,
.n_aochan = 4,
.ao_maxdata = 0x0fff,
.rangelist_ao = &range_pci1720,
},
[BOARD_PCI1731] = {
.name = "pci1731",
.have_irq = 1,
.cardtype = TYPE_PCI171X,
.n_aichan = 16,
.n_dichan = 16,
.n_dochan = 16,
.ai_maxdata = 0x0fff,
.rangelist_ai = &range_pci17x1,
.rangecode_ai = range_codes_pci17x1,
.ai_ns_min = 10000,
.fifo_half_size = 512,
},
};
struct pci1710_private {
char neverending_ai; /* we do unlimited AI */
unsigned int CntrlReg; /* Control register */
unsigned int i8254_osc_base; /* frequence of onboard oscilator */
unsigned int ai_do; /* what do AI? 0=nothing, 1 to 4 mode */
unsigned int ai_act_scan; /* how many scans we finished */
unsigned int ai_act_chan; /* actual position in actual scan */
unsigned int ai_buf_ptr; /* data buffer ptr in samples */
unsigned char ai_eos; /* 1=EOS wake up */
unsigned char ai_et;
unsigned int ai_et_CntrlReg;
unsigned int ai_et_MuxVal;
unsigned int ai_et_div1, ai_et_div2;
unsigned int act_chanlist[32]; /* list of scanned channel */
unsigned char act_chanlist_len; /* len of scanlist */
unsigned char act_chanlist_pos; /* actual position in MUX list */
unsigned char da_ranges; /* copy of D/A outpit range register */
unsigned int ai_scans; /* len of scanlist */
unsigned int ai_n_chan; /* how many channels is measured */
unsigned int *ai_chanlist; /* actaul chanlist */
unsigned int ai_flags; /* flaglist */
unsigned int ai_data_len; /* len of data buffer */
short *ai_data; /* data buffer */
unsigned int ai_timer1; /* timers */
unsigned int ai_timer2;
short ao_data[4]; /* data output buffer */
unsigned int cnt0_write_wait; /* after a write, wait for update of the
* internal state */
};
/* used for gain list programming */
static const unsigned int muxonechan[] = {
0x0000, 0x0101, 0x0202, 0x0303, 0x0404, 0x0505, 0x0606, 0x0707,
0x0808, 0x0909, 0x0a0a, 0x0b0b, 0x0c0c, 0x0d0d, 0x0e0e, 0x0f0f,
0x1010, 0x1111, 0x1212, 0x1313, 0x1414, 0x1515, 0x1616, 0x1717,
0x1818, 0x1919, 0x1a1a, 0x1b1b, 0x1c1c, 0x1d1d, 0x1e1e, 0x1f1f
};
/*
==============================================================================
Check if channel list from user is built correctly
If it's ok, then program scan/gain logic.
This works for all cards.
*/
static int check_channel_list(struct comedi_device *dev,
struct comedi_subdevice *s,
unsigned int *chanlist, unsigned int n_chan)
{
unsigned int chansegment[32];
unsigned int i, nowmustbechan, seglen, segpos;
/* correct channel and range number check itself comedi/range.c */
if (n_chan < 1) {
comedi_error(dev, "range/channel list is empty!");
return 0;
}
if (n_chan == 1)
return 1; /* seglen=1 */
chansegment[0] = chanlist[0]; /* first channel is every time ok */
for (i = 1, seglen = 1; i < n_chan; i++, seglen++) {
if (chanlist[0] == chanlist[i])
break; /* we detected a loop, stop */
if ((CR_CHAN(chanlist[i]) & 1) &&
(CR_AREF(chanlist[i]) == AREF_DIFF)) {
comedi_error(dev, "Odd channel cannot be differential input!\n");
return 0;
}
nowmustbechan = (CR_CHAN(chansegment[i - 1]) + 1) % s->n_chan;
if (CR_AREF(chansegment[i - 1]) == AREF_DIFF)
nowmustbechan = (nowmustbechan + 1) % s->n_chan;
if (nowmustbechan != CR_CHAN(chanlist[i])) {
printk("channel list must be continuous! chanlist[%i]=%d but must be %d or %d!\n",
i, CR_CHAN(chanlist[i]), nowmustbechan,
CR_CHAN(chanlist[0]));
return 0;
}
chansegment[i] = chanlist[i]; /* next correct channel in list */
}
for (i = 0, segpos = 0; i < n_chan; i++) {
if (chanlist[i] != chansegment[i % seglen]) {
printk("bad channel, reference or range number! chanlist[%i]=%d,%d,%d and not %d,%d,%d!\n",
i, CR_CHAN(chansegment[i]),
CR_RANGE(chansegment[i]),
CR_AREF(chansegment[i]),
CR_CHAN(chanlist[i % seglen]),
CR_RANGE(chanlist[i % seglen]),
CR_AREF(chansegment[i % seglen]));
return 0;
}
}
return seglen;
}
static void setup_channel_list(struct comedi_device *dev,
struct comedi_subdevice *s,
unsigned int *chanlist, unsigned int n_chan,
unsigned int seglen)
{
const struct boardtype *this_board = comedi_board(dev);
struct pci1710_private *devpriv = dev->private;
unsigned int i, range, chanprog;
devpriv->act_chanlist_len = seglen;
devpriv->act_chanlist_pos = 0;
for (i = 0; i < seglen; i++) { /* store range list to card */
chanprog = muxonechan[CR_CHAN(chanlist[i])];
outw(chanprog, dev->iobase + PCI171x_MUX); /* select channel */
range = this_board->rangecode_ai[CR_RANGE(chanlist[i])];
if (CR_AREF(chanlist[i]) == AREF_DIFF)
range |= 0x0020;
outw(range, dev->iobase + PCI171x_RANGE); /* select gain */
#ifdef PCI171x_PARANOIDCHECK
devpriv->act_chanlist[i] =
(CR_CHAN(chanlist[i]) << 12) & 0xf000;
#endif
}
#ifdef PCI171x_PARANOIDCHECK
for ( ; i < n_chan; i++) { /* store remainder of channel list */
devpriv->act_chanlist[i] =
(CR_CHAN(chanlist[i]) << 12) & 0xf000;
}
#endif
devpriv->ai_et_MuxVal =
CR_CHAN(chanlist[0]) | (CR_CHAN(chanlist[seglen - 1]) << 8);
/* select channel interval to scan */
outw(devpriv->ai_et_MuxVal, dev->iobase + PCI171x_MUX);
}
/*
==============================================================================
*/
static int pci171x_insn_read_ai(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct pci1710_private *devpriv = dev->private;
int n, timeout;
#ifdef PCI171x_PARANOIDCHECK
const struct boardtype *this_board = comedi_board(dev);
unsigned int idata;
#endif
devpriv->CntrlReg &= Control_CNT0;
devpriv->CntrlReg |= Control_SW; /* set software trigger */
outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL);
outb(0, dev->iobase + PCI171x_CLRFIFO);
outb(0, dev->iobase + PCI171x_CLRINT);
setup_channel_list(dev, s, &insn->chanspec, 1, 1);
for (n = 0; n < insn->n; n++) {
outw(0, dev->iobase + PCI171x_SOFTTRG); /* start conversion */
/* udelay(1); */
timeout = 100;
while (timeout--) {
if (!(inw(dev->iobase + PCI171x_STATUS) & Status_FE))
goto conv_finish;
}
comedi_error(dev, "A/D insn timeout");
outb(0, dev->iobase + PCI171x_CLRFIFO);
outb(0, dev->iobase + PCI171x_CLRINT);
data[n] = 0;
return -ETIME;
conv_finish:
#ifdef PCI171x_PARANOIDCHECK
idata = inw(dev->iobase + PCI171x_AD_DATA);
if (this_board->cardtype != TYPE_PCI1713)
if ((idata & 0xf000) != devpriv->act_chanlist[0]) {
comedi_error(dev, "A/D insn data droput!");
return -ETIME;
}
data[n] = idata & 0x0fff;
#else
data[n] = inw(dev->iobase + PCI171x_AD_DATA) & 0x0fff;
#endif
}
outb(0, dev->iobase + PCI171x_CLRFIFO);
outb(0, dev->iobase + PCI171x_CLRINT);
return n;
}
/*
==============================================================================
*/
static int pci171x_insn_write_ao(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct pci1710_private *devpriv = dev->private;
int n, chan, range, ofs;
chan = CR_CHAN(insn->chanspec);
range = CR_RANGE(insn->chanspec);
if (chan) {
devpriv->da_ranges &= 0xfb;
devpriv->da_ranges |= (range << 2);
outw(devpriv->da_ranges, dev->iobase + PCI171x_DAREF);
ofs = PCI171x_DA2;
} else {
devpriv->da_ranges &= 0xfe;
devpriv->da_ranges |= range;
outw(devpriv->da_ranges, dev->iobase + PCI171x_DAREF);
ofs = PCI171x_DA1;
}
for (n = 0; n < insn->n; n++)
outw(data[n], dev->iobase + ofs);
devpriv->ao_data[chan] = data[n];
return n;
}
/*
==============================================================================
*/
static int pci171x_insn_read_ao(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct pci1710_private *devpriv = dev->private;
int n, chan;
chan = CR_CHAN(insn->chanspec);
for (n = 0; n < insn->n; n++)
data[n] = devpriv->ao_data[chan];
return n;
}
/*
==============================================================================
*/
static int pci171x_insn_bits_di(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
data[1] = inw(dev->iobase + PCI171x_DI);
return insn->n;
}
/*
==============================================================================
*/
static int pci171x_insn_bits_do(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
if (data[0]) {
s->state &= ~data[0];
s->state |= (data[0] & data[1]);
outw(s->state, dev->iobase + PCI171x_DO);
}
data[1] = s->state;
return insn->n;
}
/*
==============================================================================
*/
static void start_pacer(struct comedi_device *dev, int mode,
unsigned int divisor1, unsigned int divisor2)
{
outw(0xb4, dev->iobase + PCI171x_CNTCTRL);
outw(0x74, dev->iobase + PCI171x_CNTCTRL);
if (mode == 1) {
outw(divisor2 & 0xff, dev->iobase + PCI171x_CNT2);
outw((divisor2 >> 8) & 0xff, dev->iobase + PCI171x_CNT2);
outw(divisor1 & 0xff, dev->iobase + PCI171x_CNT1);
outw((divisor1 >> 8) & 0xff, dev->iobase + PCI171x_CNT1);
}
}
/*
==============================================================================
*/
static int pci171x_insn_counter_read(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
unsigned int msb, lsb, ccntrl;
int i;
ccntrl = 0xD2; /* count only */
for (i = 0; i < insn->n; i++) {
outw(ccntrl, dev->iobase + PCI171x_CNTCTRL);
lsb = inw(dev->iobase + PCI171x_CNT0) & 0xFF;
msb = inw(dev->iobase + PCI171x_CNT0) & 0xFF;
data[0] = lsb | (msb << 8);
}
return insn->n;
}
/*
==============================================================================
*/
static int pci171x_insn_counter_write(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
struct pci1710_private *devpriv = dev->private;
uint msb, lsb, ccntrl, status;
lsb = data[0] & 0x00FF;
msb = (data[0] & 0xFF00) >> 8;
/* write lsb, then msb */
outw(lsb, dev->iobase + PCI171x_CNT0);
outw(msb, dev->iobase + PCI171x_CNT0);
if (devpriv->cnt0_write_wait) {
/* wait for the new count to be loaded */
ccntrl = 0xE2;
do {
outw(ccntrl, dev->iobase + PCI171x_CNTCTRL);
status = inw(dev->iobase + PCI171x_CNT0) & 0xFF;
} while (status & 0x40);
}
return insn->n;
}
/*
==============================================================================
*/
static int pci171x_insn_counter_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
#ifdef unused
/* This doesn't work like a normal Comedi counter config */
struct pci1710_private *devpriv = dev->private;
uint ccntrl = 0;
devpriv->cnt0_write_wait = data[0] & 0x20;
/* internal or external clock? */
if (!(data[0] & 0x10)) { /* internal */
devpriv->CntrlReg &= ~Control_CNT0;
} else {
devpriv->CntrlReg |= Control_CNT0;
}
outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL);
if (data[0] & 0x01)
ccntrl |= Counter_M0;
if (data[0] & 0x02)
ccntrl |= Counter_M1;
if (data[0] & 0x04)
ccntrl |= Counter_M2;
if (data[0] & 0x08)
ccntrl |= Counter_BCD;
ccntrl |= Counter_RW0; /* set read/write mode */
ccntrl |= Counter_RW1;
outw(ccntrl, dev->iobase + PCI171x_CNTCTRL);
#endif
return 1;
}
/*
==============================================================================
*/
static int pci1720_insn_write_ao(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct pci1710_private *devpriv = dev->private;
int n, rangereg, chan;
chan = CR_CHAN(insn->chanspec);
rangereg = devpriv->da_ranges & (~(0x03 << (chan << 1)));
rangereg |= (CR_RANGE(insn->chanspec) << (chan << 1));
if (rangereg != devpriv->da_ranges) {
outb(rangereg, dev->iobase + PCI1720_RANGE);
devpriv->da_ranges = rangereg;
}
for (n = 0; n < insn->n; n++) {
outw(data[n], dev->iobase + PCI1720_DA0 + (chan << 1));
outb(0, dev->iobase + PCI1720_SYNCOUT); /* update outputs */
}
devpriv->ao_data[chan] = data[n];
return n;
}
/*
==============================================================================
*/
static int pci171x_ai_cancel(struct comedi_device *dev,
struct comedi_subdevice *s)
{
const struct boardtype *this_board = comedi_board(dev);
struct pci1710_private *devpriv = dev->private;
switch (this_board->cardtype) {
default:
devpriv->CntrlReg &= Control_CNT0;
devpriv->CntrlReg |= Control_SW;
outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL); /* reset any operations */
start_pacer(dev, -1, 0, 0);
outb(0, dev->iobase + PCI171x_CLRFIFO);
outb(0, dev->iobase + PCI171x_CLRINT);
break;
}
devpriv->ai_do = 0;
devpriv->ai_act_scan = 0;
s->async->cur_chan = 0;
devpriv->ai_buf_ptr = 0;
devpriv->neverending_ai = 0;
return 0;
}
/*
==============================================================================
*/
static void interrupt_pci1710_every_sample(void *d)
{
struct comedi_device *dev = d;
struct pci1710_private *devpriv = dev->private;
struct comedi_subdevice *s = &dev->subdevices[0];
int m;
#ifdef PCI171x_PARANOIDCHECK
const struct boardtype *this_board = comedi_board(dev);
short sampl;
#endif
m = inw(dev->iobase + PCI171x_STATUS);
if (m & Status_FE) {
printk("comedi%d: A/D FIFO empty (%4x)\n", dev->minor, m);
pci171x_ai_cancel(dev, s);
s->async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
comedi_event(dev, s);
return;
}
if (m & Status_FF) {
printk
("comedi%d: A/D FIFO Full status (Fatal Error!) (%4x)\n",
dev->minor, m);
pci171x_ai_cancel(dev, s);
s->async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
comedi_event(dev, s);
return;
}
outb(0, dev->iobase + PCI171x_CLRINT); /* clear our INT request */
for (; !(inw(dev->iobase + PCI171x_STATUS) & Status_FE);) {
#ifdef PCI171x_PARANOIDCHECK
sampl = inw(dev->iobase + PCI171x_AD_DATA);
if (this_board->cardtype != TYPE_PCI1713)
if ((sampl & 0xf000) !=
devpriv->act_chanlist[s->async->cur_chan]) {
printk
("comedi: A/D data dropout: received data from channel %d, expected %d!\n",
(sampl & 0xf000) >> 12,
(devpriv->
act_chanlist[s->
async->cur_chan] & 0xf000) >>
12);
pci171x_ai_cancel(dev, s);
s->async->events |=
COMEDI_CB_EOA | COMEDI_CB_ERROR;
comedi_event(dev, s);
return;
}
comedi_buf_put(s->async, sampl & 0x0fff);
#else
comedi_buf_put(s->async,
inw(dev->iobase + PCI171x_AD_DATA) & 0x0fff);
#endif
++s->async->cur_chan;
if (s->async->cur_chan >= devpriv->ai_n_chan)
s->async->cur_chan = 0;
if (s->async->cur_chan == 0) { /* one scan done */
devpriv->ai_act_scan++;
if ((!devpriv->neverending_ai) &&
(devpriv->ai_act_scan >= devpriv->ai_scans)) {
/* all data sampled */
pci171x_ai_cancel(dev, s);
s->async->events |= COMEDI_CB_EOA;
comedi_event(dev, s);
return;
}
}
}
outb(0, dev->iobase + PCI171x_CLRINT); /* clear our INT request */
comedi_event(dev, s);
}
/*
==============================================================================
*/
static int move_block_from_fifo(struct comedi_device *dev,
struct comedi_subdevice *s, int n, int turn)
{
struct pci1710_private *devpriv = dev->private;
int i, j;
#ifdef PCI171x_PARANOIDCHECK
const struct boardtype *this_board = comedi_board(dev);
int sampl;
#endif
j = s->async->cur_chan;
for (i = 0; i < n; i++) {
#ifdef PCI171x_PARANOIDCHECK
sampl = inw(dev->iobase + PCI171x_AD_DATA);
if (this_board->cardtype != TYPE_PCI1713)
if ((sampl & 0xf000) != devpriv->act_chanlist[j]) {
printk
("comedi%d: A/D FIFO data dropout: received data from channel %d, expected %d! (%d/%d/%d/%d/%d/%4x)\n",
dev->minor, (sampl & 0xf000) >> 12,
(devpriv->act_chanlist[j] & 0xf000) >> 12,
i, j, devpriv->ai_act_scan, n, turn,
sampl);
pci171x_ai_cancel(dev, s);
s->async->events |=
COMEDI_CB_EOA | COMEDI_CB_ERROR;
comedi_event(dev, s);
return 1;
}
comedi_buf_put(s->async, sampl & 0x0fff);
#else
comedi_buf_put(s->async,
inw(dev->iobase + PCI171x_AD_DATA) & 0x0fff);
#endif
j++;
if (j >= devpriv->ai_n_chan) {
j = 0;
devpriv->ai_act_scan++;
}
}
s->async->cur_chan = j;
return 0;
}
/*
==============================================================================
*/
static void interrupt_pci1710_half_fifo(void *d)
{
struct comedi_device *dev = d;
const struct boardtype *this_board = comedi_board(dev);
struct pci1710_private *devpriv = dev->private;
struct comedi_subdevice *s = &dev->subdevices[0];
int m, samplesinbuf;
m = inw(dev->iobase + PCI171x_STATUS);
if (!(m & Status_FH)) {
printk("comedi%d: A/D FIFO not half full! (%4x)\n",
dev->minor, m);
pci171x_ai_cancel(dev, s);
s->async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
comedi_event(dev, s);
return;
}
if (m & Status_FF) {
printk
("comedi%d: A/D FIFO Full status (Fatal Error!) (%4x)\n",
dev->minor, m);
pci171x_ai_cancel(dev, s);
s->async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
comedi_event(dev, s);
return;
}
samplesinbuf = this_board->fifo_half_size;
if (samplesinbuf * sizeof(short) >= devpriv->ai_data_len) {
m = devpriv->ai_data_len / sizeof(short);
if (move_block_from_fifo(dev, s, m, 0))
return;
samplesinbuf -= m;
}
if (samplesinbuf) {
if (move_block_from_fifo(dev, s, samplesinbuf, 1))
return;
}
if (!devpriv->neverending_ai)
if (devpriv->ai_act_scan >= devpriv->ai_scans) { /* all data
sampled */
pci171x_ai_cancel(dev, s);
s->async->events |= COMEDI_CB_EOA;
comedi_event(dev, s);
return;
}
outb(0, dev->iobase + PCI171x_CLRINT); /* clear our INT request */
comedi_event(dev, s);
}
/*
==============================================================================
*/
static irqreturn_t interrupt_service_pci1710(int irq, void *d)
{
struct comedi_device *dev = d;
struct pci1710_private *devpriv = dev->private;
if (!dev->attached) /* is device attached? */
return IRQ_NONE; /* no, exit */
/* is this interrupt from our board? */
if (!(inw(dev->iobase + PCI171x_STATUS) & Status_IRQ))
return IRQ_NONE; /* no, exit */
if (devpriv->ai_et) { /* Switch from initial TRIG_EXT to TRIG_xxx. */
devpriv->ai_et = 0;
devpriv->CntrlReg &= Control_CNT0;
devpriv->CntrlReg |= Control_SW; /* set software trigger */
outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL);
devpriv->CntrlReg = devpriv->ai_et_CntrlReg;
outb(0, dev->iobase + PCI171x_CLRFIFO);
outb(0, dev->iobase + PCI171x_CLRINT);
outw(devpriv->ai_et_MuxVal, dev->iobase + PCI171x_MUX);
outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL);
/* start pacer */
start_pacer(dev, 1, devpriv->ai_et_div1, devpriv->ai_et_div2);
return IRQ_HANDLED;
}
if (devpriv->ai_eos) { /* We use FIFO half full INT or not? */
interrupt_pci1710_every_sample(d);
} else {
interrupt_pci1710_half_fifo(d);
}
return IRQ_HANDLED;
}
/*
==============================================================================
*/
static int pci171x_ai_docmd_and_mode(int mode, struct comedi_device *dev,
struct comedi_subdevice *s)
{
const struct boardtype *this_board = comedi_board(dev);
struct pci1710_private *devpriv = dev->private;
unsigned int divisor1 = 0, divisor2 = 0;
unsigned int seglen;
start_pacer(dev, -1, 0, 0); /* stop pacer */
seglen = check_channel_list(dev, s, devpriv->ai_chanlist,
devpriv->ai_n_chan);
if (seglen < 1)
return -EINVAL;
setup_channel_list(dev, s, devpriv->ai_chanlist,
devpriv->ai_n_chan, seglen);
outb(0, dev->iobase + PCI171x_CLRFIFO);
outb(0, dev->iobase + PCI171x_CLRINT);
devpriv->ai_do = mode;
devpriv->ai_act_scan = 0;
s->async->cur_chan = 0;
devpriv->ai_buf_ptr = 0;
devpriv->neverending_ai = 0;
devpriv->CntrlReg &= Control_CNT0;
/* don't we want wake up every scan? devpriv->ai_eos=1; */
if ((devpriv->ai_flags & TRIG_WAKE_EOS)) {
devpriv->ai_eos = 1;
} else {
devpriv->CntrlReg |= Control_ONEFH;
devpriv->ai_eos = 0;
}
if ((devpriv->ai_scans == 0) || (devpriv->ai_scans == -1))
devpriv->neverending_ai = 1;
/* well, user want neverending */
else
devpriv->neverending_ai = 0;
switch (mode) {
case 1:
case 2:
if (devpriv->ai_timer1 < this_board->ai_ns_min)
devpriv->ai_timer1 = this_board->ai_ns_min;
devpriv->CntrlReg |= Control_PACER | Control_IRQEN;
if (mode == 2) {
devpriv->ai_et_CntrlReg = devpriv->CntrlReg;
devpriv->CntrlReg &=
~(Control_PACER | Control_ONEFH | Control_GATE);
devpriv->CntrlReg |= Control_EXT;
devpriv->ai_et = 1;
} else {
devpriv->ai_et = 0;
}
i8253_cascade_ns_to_timer(devpriv->i8254_osc_base, &divisor1,
&divisor2, &devpriv->ai_timer1,
devpriv->ai_flags & TRIG_ROUND_MASK);
outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL);
if (mode != 2) {
/* start pacer */
start_pacer(dev, mode, divisor1, divisor2);
} else {
devpriv->ai_et_div1 = divisor1;
devpriv->ai_et_div2 = divisor2;
}
break;
case 3:
devpriv->CntrlReg |= Control_EXT | Control_IRQEN;
outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL);
break;
}
return 0;
}
/*
==============================================================================
*/
static int pci171x_ai_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_cmd *cmd)
{
const struct boardtype *this_board = comedi_board(dev);
struct pci1710_private *devpriv = dev->private;
int err = 0;
int tmp;
unsigned int divisor1 = 0, divisor2 = 0;
/* Step 1 : check if triggers are trivially valid */
err |= cfc_check_trigger_src(&cmd->start_src, TRIG_NOW | TRIG_EXT);
err |= cfc_check_trigger_src(&cmd->scan_begin_src, TRIG_FOLLOW);
err |= cfc_check_trigger_src(&cmd->convert_src, TRIG_TIMER | TRIG_EXT);
err |= cfc_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT);
err |= cfc_check_trigger_src(&cmd->stop_src, TRIG_COUNT | TRIG_NONE);
if (err)
return 1;
/* step 2a: make sure trigger sources are unique */
err |= cfc_check_trigger_is_unique(cmd->start_src);
err |= cfc_check_trigger_is_unique(cmd->convert_src);
err |= cfc_check_trigger_is_unique(cmd->stop_src);
/* step 2b: and mutually compatible */
if (err)
return 2;
/* Step 3: check if arguments are trivially valid */
err |= cfc_check_trigger_arg_is(&cmd->start_arg, 0);
err |= cfc_check_trigger_arg_is(&cmd->scan_begin_arg, 0);
if (cmd->convert_src == TRIG_TIMER)
err |= cfc_check_trigger_arg_min(&cmd->convert_arg,
this_board->ai_ns_min);
else /* TRIG_FOLLOW */
err |= cfc_check_trigger_arg_is(&cmd->convert_arg, 0);
err |= cfc_check_trigger_arg_is(&cmd->scan_end_arg, cmd->chanlist_len);
if (cmd->stop_src == TRIG_COUNT)
err |= cfc_check_trigger_arg_min(&cmd->stop_arg, 1);
else /* TRIG_NONE */
err |= cfc_check_trigger_arg_is(&cmd->stop_arg, 0);
if (err)
return 3;
/* step 4: fix up any arguments */
if (cmd->convert_src == TRIG_TIMER) {
tmp = cmd->convert_arg;
i8253_cascade_ns_to_timer(devpriv->i8254_osc_base, &divisor1,
&divisor2, &cmd->convert_arg,
cmd->flags & TRIG_ROUND_MASK);
if (cmd->convert_arg < this_board->ai_ns_min)
cmd->convert_arg = this_board->ai_ns_min;
if (tmp != cmd->convert_arg)
err++;
}
if (err)
return 4;
/* step 5: complain about special chanlist considerations */
if (cmd->chanlist) {
if (!check_channel_list(dev, s, cmd->chanlist,
cmd->chanlist_len))
return 5; /* incorrect channels list */
}
return 0;
}
/*
==============================================================================
*/
static int pci171x_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
{
struct pci1710_private *devpriv = dev->private;
struct comedi_cmd *cmd = &s->async->cmd;
devpriv->ai_n_chan = cmd->chanlist_len;
devpriv->ai_chanlist = cmd->chanlist;
devpriv->ai_flags = cmd->flags;
devpriv->ai_data_len = s->async->prealloc_bufsz;
devpriv->ai_data = s->async->prealloc_buf;
devpriv->ai_timer1 = 0;
devpriv->ai_timer2 = 0;
if (cmd->stop_src == TRIG_COUNT)
devpriv->ai_scans = cmd->stop_arg;
else
devpriv->ai_scans = 0;
if (cmd->scan_begin_src == TRIG_FOLLOW) { /* mode 1, 2, 3 */
if (cmd->convert_src == TRIG_TIMER) { /* mode 1 and 2 */
devpriv->ai_timer1 = cmd->convert_arg;
return pci171x_ai_docmd_and_mode(cmd->start_src ==
TRIG_EXT ? 2 : 1, dev,
s);
}
if (cmd->convert_src == TRIG_EXT) { /* mode 3 */
return pci171x_ai_docmd_and_mode(3, dev, s);
}
}
return -1;
}
/*
==============================================================================
*/
static int pci171x_reset(struct comedi_device *dev)
{
const struct boardtype *this_board = comedi_board(dev);
struct pci1710_private *devpriv = dev->private;
outw(0x30, dev->iobase + PCI171x_CNTCTRL);
devpriv->CntrlReg = Control_SW | Control_CNT0; /* Software trigger, CNT0=external */
outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL); /* reset any operations */
outb(0, dev->iobase + PCI171x_CLRFIFO); /* clear FIFO */
outb(0, dev->iobase + PCI171x_CLRINT); /* clear INT request */
start_pacer(dev, -1, 0, 0); /* stop 8254 */
devpriv->da_ranges = 0;
if (this_board->n_aochan) {
outb(devpriv->da_ranges, dev->iobase + PCI171x_DAREF); /* set DACs to 0..5V */
outw(0, dev->iobase + PCI171x_DA1); /* set DA outputs to 0V */
devpriv->ao_data[0] = 0x0000;
if (this_board->n_aochan > 1) {
outw(0, dev->iobase + PCI171x_DA2);
devpriv->ao_data[1] = 0x0000;
}
}
outw(0, dev->iobase + PCI171x_DO); /* digital outputs to 0 */
outb(0, dev->iobase + PCI171x_CLRFIFO); /* clear FIFO */
outb(0, dev->iobase + PCI171x_CLRINT); /* clear INT request */
return 0;
}
/*
==============================================================================
*/
static int pci1720_reset(struct comedi_device *dev)
{
struct pci1710_private *devpriv = dev->private;
outb(Syncont_SC0, dev->iobase + PCI1720_SYNCONT); /* set synchronous output mode */
devpriv->da_ranges = 0xAA;
outb(devpriv->da_ranges, dev->iobase + PCI1720_RANGE); /* set all ranges to +/-5V */
outw(0x0800, dev->iobase + PCI1720_DA0); /* set outputs to 0V */
outw(0x0800, dev->iobase + PCI1720_DA1);
outw(0x0800, dev->iobase + PCI1720_DA2);
outw(0x0800, dev->iobase + PCI1720_DA3);
outb(0, dev->iobase + PCI1720_SYNCOUT); /* update outputs */
devpriv->ao_data[0] = 0x0800;
devpriv->ao_data[1] = 0x0800;
devpriv->ao_data[2] = 0x0800;
devpriv->ao_data[3] = 0x0800;
return 0;
}
/*
==============================================================================
*/
static int pci1710_reset(struct comedi_device *dev)
{
const struct boardtype *this_board = comedi_board(dev);
switch (this_board->cardtype) {
case TYPE_PCI1720:
return pci1720_reset(dev);
default:
return pci171x_reset(dev);
}
}
static int pci1710_auto_attach(struct comedi_device *dev,
unsigned long context)
{
struct pci_dev *pcidev = comedi_to_pci_dev(dev);
const struct boardtype *this_board = NULL;
struct pci1710_private *devpriv;
struct comedi_subdevice *s;
int ret, subdev, n_subdevices;
if (context < ARRAY_SIZE(boardtypes))
this_board = &boardtypes[context];
if (!this_board)
return -ENODEV;
dev->board_ptr = this_board;
dev->board_name = this_board->name;
devpriv = kzalloc(sizeof(*devpriv), GFP_KERNEL);
if (!devpriv)
return -ENOMEM;
dev->private = devpriv;
ret = comedi_pci_enable(dev);
if (ret)
return ret;
dev->iobase = pci_resource_start(pcidev, 2);
n_subdevices = 0;
if (this_board->n_aichan)
n_subdevices++;
if (this_board->n_aochan)
n_subdevices++;
if (this_board->n_dichan)
n_subdevices++;
if (this_board->n_dochan)
n_subdevices++;
if (this_board->n_counter)
n_subdevices++;
ret = comedi_alloc_subdevices(dev, n_subdevices);
if (ret)
return ret;
pci1710_reset(dev);
if (this_board->have_irq && pcidev->irq) {
ret = request_irq(pcidev->irq, interrupt_service_pci1710,
IRQF_SHARED, dev->board_name, dev);
if (ret == 0)
dev->irq = pcidev->irq;
}
subdev = 0;
if (this_board->n_aichan) {
s = &dev->subdevices[subdev];
dev->read_subdev = s;
s->type = COMEDI_SUBD_AI;
s->subdev_flags = SDF_READABLE | SDF_COMMON | SDF_GROUND;
if (this_board->n_aichand)
s->subdev_flags |= SDF_DIFF;
s->n_chan = this_board->n_aichan;
s->maxdata = this_board->ai_maxdata;
s->len_chanlist = this_board->n_aichan;
s->range_table = this_board->rangelist_ai;
s->cancel = pci171x_ai_cancel;
s->insn_read = pci171x_insn_read_ai;
if (dev->irq) {
s->subdev_flags |= SDF_CMD_READ;
s->do_cmdtest = pci171x_ai_cmdtest;
s->do_cmd = pci171x_ai_cmd;
}
devpriv->i8254_osc_base = 100; /* 100ns=10MHz */
subdev++;
}
if (this_board->n_aochan) {
s = &dev->subdevices[subdev];
s->type = COMEDI_SUBD_AO;
s->subdev_flags = SDF_WRITABLE | SDF_GROUND | SDF_COMMON;
s->n_chan = this_board->n_aochan;
s->maxdata = this_board->ao_maxdata;
s->len_chanlist = this_board->n_aochan;
s->range_table = this_board->rangelist_ao;
switch (this_board->cardtype) {
case TYPE_PCI1720:
s->insn_write = pci1720_insn_write_ao;
break;
default:
s->insn_write = pci171x_insn_write_ao;
break;
}
s->insn_read = pci171x_insn_read_ao;
subdev++;
}
if (this_board->n_dichan) {
s = &dev->subdevices[subdev];
s->type = COMEDI_SUBD_DI;
s->subdev_flags = SDF_READABLE | SDF_GROUND | SDF_COMMON;
s->n_chan = this_board->n_dichan;
s->maxdata = 1;
s->len_chanlist = this_board->n_dichan;
s->range_table = &range_digital;
s->io_bits = 0; /* all bits input */
s->insn_bits = pci171x_insn_bits_di;
subdev++;
}
if (this_board->n_dochan) {
s = &dev->subdevices[subdev];
s->type = COMEDI_SUBD_DO;
s->subdev_flags = SDF_WRITABLE | SDF_GROUND | SDF_COMMON;
s->n_chan = this_board->n_dochan;
s->maxdata = 1;
s->len_chanlist = this_board->n_dochan;
s->range_table = &range_digital;
/* all bits output */
s->io_bits = (1 << this_board->n_dochan) - 1;
s->state = 0;
s->insn_bits = pci171x_insn_bits_do;
subdev++;
}
if (this_board->n_counter) {
s = &dev->subdevices[subdev];
s->type = COMEDI_SUBD_COUNTER;
s->subdev_flags = SDF_READABLE | SDF_WRITABLE;
s->n_chan = this_board->n_counter;
s->len_chanlist = this_board->n_counter;
s->maxdata = 0xffff;
s->range_table = &range_unknown;
s->insn_read = pci171x_insn_counter_read;
s->insn_write = pci171x_insn_counter_write;
s->insn_config = pci171x_insn_counter_config;
subdev++;
}
dev_info(dev->class_dev, "%s attached, irq %sabled\n",
dev->board_name, dev->irq ? "en" : "dis");
return 0;
}
static void pci1710_detach(struct comedi_device *dev)
{
if (dev->iobase)
pci1710_reset(dev);
if (dev->irq)
free_irq(dev->irq, dev);
comedi_pci_disable(dev);
}
static struct comedi_driver adv_pci1710_driver = {
.driver_name = "adv_pci1710",
.module = THIS_MODULE,
.auto_attach = pci1710_auto_attach,
.detach = pci1710_detach,
};
static int adv_pci1710_pci_probe(struct pci_dev *dev,
const struct pci_device_id *id)
{
return comedi_pci_auto_config(dev, &adv_pci1710_driver,
id->driver_data);
}
static DEFINE_PCI_DEVICE_TABLE(adv_pci1710_pci_table) = {
{
PCI_DEVICE_SUB(PCI_VENDOR_ID_ADVANTECH, 0x1710,
PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_9050),
.driver_data = BOARD_PCI1710,
}, {
PCI_DEVICE_SUB(PCI_VENDOR_ID_ADVANTECH, 0x1710,
PCI_VENDOR_ID_ADVANTECH, 0x0000),
.driver_data = BOARD_PCI1710,
}, {
PCI_DEVICE_SUB(PCI_VENDOR_ID_ADVANTECH, 0x1710,
PCI_VENDOR_ID_ADVANTECH, 0xb100),
.driver_data = BOARD_PCI1710,
}, {
PCI_DEVICE_SUB(PCI_VENDOR_ID_ADVANTECH, 0x1710,
PCI_VENDOR_ID_ADVANTECH, 0xb200),
.driver_data = BOARD_PCI1710,
}, {
PCI_DEVICE_SUB(PCI_VENDOR_ID_ADVANTECH, 0x1710,
PCI_VENDOR_ID_ADVANTECH, 0xc100),
.driver_data = BOARD_PCI1710,
}, {
PCI_DEVICE_SUB(PCI_VENDOR_ID_ADVANTECH, 0x1710,
PCI_VENDOR_ID_ADVANTECH, 0xc200),
.driver_data = BOARD_PCI1710,
}, {
PCI_DEVICE_SUB(PCI_VENDOR_ID_ADVANTECH, 0x1710, 0x1000, 0xd100),
.driver_data = BOARD_PCI1710,
}, {
PCI_DEVICE_SUB(PCI_VENDOR_ID_ADVANTECH, 0x1710,
PCI_VENDOR_ID_ADVANTECH, 0x0002),
.driver_data = BOARD_PCI1710HG,
}, {
PCI_DEVICE_SUB(PCI_VENDOR_ID_ADVANTECH, 0x1710,
PCI_VENDOR_ID_ADVANTECH, 0xb102),
.driver_data = BOARD_PCI1710HG,
}, {
PCI_DEVICE_SUB(PCI_VENDOR_ID_ADVANTECH, 0x1710,
PCI_VENDOR_ID_ADVANTECH, 0xb202),
.driver_data = BOARD_PCI1710HG,
}, {
PCI_DEVICE_SUB(PCI_VENDOR_ID_ADVANTECH, 0x1710,
PCI_VENDOR_ID_ADVANTECH, 0xc102),
.driver_data = BOARD_PCI1710HG,
}, {
PCI_DEVICE_SUB(PCI_VENDOR_ID_ADVANTECH, 0x1710,
PCI_VENDOR_ID_ADVANTECH, 0xc202),
.driver_data = BOARD_PCI1710HG,
}, {
PCI_DEVICE_SUB(PCI_VENDOR_ID_ADVANTECH, 0x1710, 0x1000, 0xd102),
.driver_data = BOARD_PCI1710HG,
},
{ PCI_VDEVICE(ADVANTECH, 0x1711), BOARD_PCI1711 },
{ PCI_VDEVICE(ADVANTECH, 0x1713), BOARD_PCI1713 },
{ PCI_VDEVICE(ADVANTECH, 0x1720), BOARD_PCI1720 },
{ PCI_VDEVICE(ADVANTECH, 0x1731), BOARD_PCI1731 },
{ 0 }
};
MODULE_DEVICE_TABLE(pci, adv_pci1710_pci_table);
static struct pci_driver adv_pci1710_pci_driver = {
.name = "adv_pci1710",
.id_table = adv_pci1710_pci_table,
.probe = adv_pci1710_pci_probe,
.remove = comedi_pci_auto_unconfig,
};
module_comedi_pci_driver(adv_pci1710_driver, adv_pci1710_pci_driver);
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Splitter/android_kernel_htc_msm7x30 | drivers/gpu/drm/drm_sysfs.c | 510 | 14574 |
/*
* drm_sysfs.c - Modifications to drm_sysfs_class.c to support
* extra sysfs attribute from DRM. Normal drm_sysfs_class
* does not allow adding attributes.
*
* Copyright (c) 2004 Jon Smirl <jonsmirl@gmail.com>
* Copyright (c) 2003-2004 Greg Kroah-Hartman <greg@kroah.com>
* Copyright (c) 2003-2004 IBM Corp.
*
* This file is released under the GPLv2
*
*/
#include <linux/device.h>
#include <linux/kdev_t.h>
#include <linux/gfp.h>
#include <linux/err.h>
#include "drm_sysfs.h"
#include "drm_core.h"
#include "drmP.h"
#define to_drm_minor(d) container_of(d, struct drm_minor, kdev)
#define to_drm_connector(d) container_of(d, struct drm_connector, kdev)
static struct device_type drm_sysfs_device_minor = {
.name = "drm_minor"
};
/**
* drm_class_suspend - DRM class suspend hook
* @dev: Linux device to suspend
* @state: power state to enter
*
* Just figures out what the actual struct drm_device associated with
* @dev is and calls its suspend hook, if present.
*/
static int drm_class_suspend(struct device *dev, pm_message_t state)
{
if (dev->type == &drm_sysfs_device_minor) {
struct drm_minor *drm_minor = to_drm_minor(dev);
struct drm_device *drm_dev = drm_minor->dev;
if (drm_minor->type == DRM_MINOR_LEGACY &&
!drm_core_check_feature(drm_dev, DRIVER_MODESET) &&
drm_dev->driver->suspend)
return drm_dev->driver->suspend(drm_dev, state);
}
return 0;
}
/**
* drm_class_resume - DRM class resume hook
* @dev: Linux device to resume
*
* Just figures out what the actual struct drm_device associated with
* @dev is and calls its resume hook, if present.
*/
static int drm_class_resume(struct device *dev)
{
if (dev->type == &drm_sysfs_device_minor) {
struct drm_minor *drm_minor = to_drm_minor(dev);
struct drm_device *drm_dev = drm_minor->dev;
if (drm_minor->type == DRM_MINOR_LEGACY &&
!drm_core_check_feature(drm_dev, DRIVER_MODESET) &&
drm_dev->driver->resume)
return drm_dev->driver->resume(drm_dev);
}
return 0;
}
static char *drm_devnode(struct device *dev, mode_t *mode)
{
return kasprintf(GFP_KERNEL, "dri/%s", dev_name(dev));
}
static CLASS_ATTR_STRING(version, S_IRUGO,
CORE_NAME " "
__stringify(CORE_MAJOR) "."
__stringify(CORE_MINOR) "."
__stringify(CORE_PATCHLEVEL) " "
CORE_DATE);
/**
* drm_sysfs_create - create a struct drm_sysfs_class structure
* @owner: pointer to the module that is to "own" this struct drm_sysfs_class
* @name: pointer to a string for the name of this class.
*
* This is used to create DRM class pointer that can then be used
* in calls to drm_sysfs_device_add().
*
* Note, the pointer created here is to be destroyed when finished by making a
* call to drm_sysfs_destroy().
*/
struct class *drm_sysfs_create(struct module *owner, char *name)
{
struct class *class;
int err;
class = class_create(owner, name);
if (IS_ERR(class)) {
err = PTR_ERR(class);
goto err_out;
}
class->suspend = drm_class_suspend;
class->resume = drm_class_resume;
err = class_create_file(class, &class_attr_version.attr);
if (err)
goto err_out_class;
class->devnode = drm_devnode;
return class;
err_out_class:
class_destroy(class);
err_out:
return ERR_PTR(err);
}
/**
* drm_sysfs_destroy - destroys DRM class
*
* Destroy the DRM device class.
*/
void drm_sysfs_destroy(void)
{
if ((drm_class == NULL) || (IS_ERR(drm_class)))
return;
class_remove_file(drm_class, &class_attr_version.attr);
class_destroy(drm_class);
}
/**
* drm_sysfs_device_release - do nothing
* @dev: Linux device
*
* Normally, this would free the DRM device associated with @dev, along
* with cleaning up any other stuff. But we do that in the DRM core, so
* this function can just return and hope that the core does its job.
*/
static void drm_sysfs_device_release(struct device *dev)
{
memset(dev, 0, sizeof(struct device));
return;
}
/*
* Connector properties
*/
static ssize_t status_show(struct device *device,
struct device_attribute *attr,
char *buf)
{
struct drm_connector *connector = to_drm_connector(device);
enum drm_connector_status status;
status = connector->funcs->detect(connector);
return snprintf(buf, PAGE_SIZE, "%s\n",
drm_get_connector_status_name(status));
}
static ssize_t dpms_show(struct device *device,
struct device_attribute *attr,
char *buf)
{
struct drm_connector *connector = to_drm_connector(device);
struct drm_device *dev = connector->dev;
uint64_t dpms_status;
int ret;
ret = drm_connector_property_get_value(connector,
dev->mode_config.dpms_property,
&dpms_status);
if (ret)
return 0;
return snprintf(buf, PAGE_SIZE, "%s\n",
drm_get_dpms_name((int)dpms_status));
}
static ssize_t enabled_show(struct device *device,
struct device_attribute *attr,
char *buf)
{
struct drm_connector *connector = to_drm_connector(device);
return snprintf(buf, PAGE_SIZE, "%s\n", connector->encoder ? "enabled" :
"disabled");
}
static ssize_t edid_show(struct file *filp, struct kobject *kobj,
struct bin_attribute *attr, char *buf, loff_t off,
size_t count)
{
struct device *connector_dev = container_of(kobj, struct device, kobj);
struct drm_connector *connector = to_drm_connector(connector_dev);
unsigned char *edid;
size_t size;
if (!connector->edid_blob_ptr)
return 0;
edid = connector->edid_blob_ptr->data;
size = connector->edid_blob_ptr->length;
if (!edid)
return 0;
if (off >= size)
return 0;
if (off + count > size)
count = size - off;
memcpy(buf, edid + off, count);
return count;
}
static ssize_t modes_show(struct device *device,
struct device_attribute *attr,
char *buf)
{
struct drm_connector *connector = to_drm_connector(device);
struct drm_display_mode *mode;
int written = 0;
list_for_each_entry(mode, &connector->modes, head) {
written += snprintf(buf + written, PAGE_SIZE - written, "%s\n",
mode->name);
}
return written;
}
static ssize_t subconnector_show(struct device *device,
struct device_attribute *attr,
char *buf)
{
struct drm_connector *connector = to_drm_connector(device);
struct drm_device *dev = connector->dev;
struct drm_property *prop = NULL;
uint64_t subconnector;
int is_tv = 0;
int ret;
switch (connector->connector_type) {
case DRM_MODE_CONNECTOR_DVII:
prop = dev->mode_config.dvi_i_subconnector_property;
break;
case DRM_MODE_CONNECTOR_Composite:
case DRM_MODE_CONNECTOR_SVIDEO:
case DRM_MODE_CONNECTOR_Component:
case DRM_MODE_CONNECTOR_TV:
prop = dev->mode_config.tv_subconnector_property;
is_tv = 1;
break;
default:
DRM_ERROR("Wrong connector type for this property\n");
return 0;
}
if (!prop) {
DRM_ERROR("Unable to find subconnector property\n");
return 0;
}
ret = drm_connector_property_get_value(connector, prop, &subconnector);
if (ret)
return 0;
return snprintf(buf, PAGE_SIZE, "%s", is_tv ?
drm_get_tv_subconnector_name((int)subconnector) :
drm_get_dvi_i_subconnector_name((int)subconnector));
}
static ssize_t select_subconnector_show(struct device *device,
struct device_attribute *attr,
char *buf)
{
struct drm_connector *connector = to_drm_connector(device);
struct drm_device *dev = connector->dev;
struct drm_property *prop = NULL;
uint64_t subconnector;
int is_tv = 0;
int ret;
switch (connector->connector_type) {
case DRM_MODE_CONNECTOR_DVII:
prop = dev->mode_config.dvi_i_select_subconnector_property;
break;
case DRM_MODE_CONNECTOR_Composite:
case DRM_MODE_CONNECTOR_SVIDEO:
case DRM_MODE_CONNECTOR_Component:
case DRM_MODE_CONNECTOR_TV:
prop = dev->mode_config.tv_select_subconnector_property;
is_tv = 1;
break;
default:
DRM_ERROR("Wrong connector type for this property\n");
return 0;
}
if (!prop) {
DRM_ERROR("Unable to find select subconnector property\n");
return 0;
}
ret = drm_connector_property_get_value(connector, prop, &subconnector);
if (ret)
return 0;
return snprintf(buf, PAGE_SIZE, "%s", is_tv ?
drm_get_tv_select_name((int)subconnector) :
drm_get_dvi_i_select_name((int)subconnector));
}
static struct device_attribute connector_attrs[] = {
__ATTR_RO(status),
__ATTR_RO(enabled),
__ATTR_RO(dpms),
__ATTR_RO(modes),
};
/* These attributes are for both DVI-I connectors and all types of tv-out. */
static struct device_attribute connector_attrs_opt1[] = {
__ATTR_RO(subconnector),
__ATTR_RO(select_subconnector),
};
static struct bin_attribute edid_attr = {
.attr.name = "edid",
.attr.mode = 0444,
.size = 0,
.read = edid_show,
};
/**
* drm_sysfs_connector_add - add an connector to sysfs
* @connector: connector to add
*
* Create an connector device in sysfs, along with its associated connector
* properties (so far, connection status, dpms, mode list & edid) and
* generate a hotplug event so userspace knows there's a new connector
* available.
*
* Note:
* This routine should only be called *once* for each DRM minor registered.
* A second call for an already registered device will trigger the BUG_ON
* below.
*/
int drm_sysfs_connector_add(struct drm_connector *connector)
{
struct drm_device *dev = connector->dev;
int attr_cnt = 0;
int opt_cnt = 0;
int i;
int ret = 0;
/* We shouldn't get called more than once for the same connector */
BUG_ON(device_is_registered(&connector->kdev));
connector->kdev.parent = &dev->primary->kdev;
connector->kdev.class = drm_class;
connector->kdev.release = drm_sysfs_device_release;
DRM_DEBUG("adding \"%s\" to sysfs\n",
drm_get_connector_name(connector));
dev_set_name(&connector->kdev, "card%d-%s",
dev->primary->index, drm_get_connector_name(connector));
ret = device_register(&connector->kdev);
if (ret) {
DRM_ERROR("failed to register connector device: %d\n", ret);
goto out;
}
/* Standard attributes */
for (attr_cnt = 0; attr_cnt < ARRAY_SIZE(connector_attrs); attr_cnt++) {
ret = device_create_file(&connector->kdev, &connector_attrs[attr_cnt]);
if (ret)
goto err_out_files;
}
/* Optional attributes */
/*
* In the long run it maybe a good idea to make one set of
* optionals per connector type.
*/
switch (connector->connector_type) {
case DRM_MODE_CONNECTOR_DVII:
case DRM_MODE_CONNECTOR_Composite:
case DRM_MODE_CONNECTOR_SVIDEO:
case DRM_MODE_CONNECTOR_Component:
case DRM_MODE_CONNECTOR_TV:
for (opt_cnt = 0; opt_cnt < ARRAY_SIZE(connector_attrs_opt1); opt_cnt++) {
ret = device_create_file(&connector->kdev, &connector_attrs_opt1[opt_cnt]);
if (ret)
goto err_out_files;
}
break;
default:
break;
}
ret = sysfs_create_bin_file(&connector->kdev.kobj, &edid_attr);
if (ret)
goto err_out_files;
/* Let userspace know we have a new connector */
drm_sysfs_hotplug_event(dev);
return 0;
err_out_files:
for (i = 0; i < opt_cnt; i++)
device_remove_file(&connector->kdev, &connector_attrs_opt1[i]);
for (i = 0; i < attr_cnt; i++)
device_remove_file(&connector->kdev, &connector_attrs[i]);
device_unregister(&connector->kdev);
out:
return ret;
}
EXPORT_SYMBOL(drm_sysfs_connector_add);
/**
* drm_sysfs_connector_remove - remove an connector device from sysfs
* @connector: connector to remove
*
* Remove @connector and its associated attributes from sysfs. Note that
* the device model core will take care of sending the "remove" uevent
* at this time, so we don't need to do it.
*
* Note:
* This routine should only be called if the connector was previously
* successfully registered. If @connector hasn't been registered yet,
* you'll likely see a panic somewhere deep in sysfs code when called.
*/
void drm_sysfs_connector_remove(struct drm_connector *connector)
{
int i;
DRM_DEBUG("removing \"%s\" from sysfs\n",
drm_get_connector_name(connector));
for (i = 0; i < ARRAY_SIZE(connector_attrs); i++)
device_remove_file(&connector->kdev, &connector_attrs[i]);
sysfs_remove_bin_file(&connector->kdev.kobj, &edid_attr);
device_unregister(&connector->kdev);
}
EXPORT_SYMBOL(drm_sysfs_connector_remove);
/**
* drm_sysfs_hotplug_event - generate a DRM uevent
* @dev: DRM device
*
* Send a uevent for the DRM device specified by @dev. Currently we only
* set HOTPLUG=1 in the uevent environment, but this could be expanded to
* deal with other types of events.
*/
void drm_sysfs_hotplug_event(struct drm_device *dev)
{
char *event_string = "HOTPLUG=1";
char *envp[] = { event_string, NULL };
DRM_DEBUG("generating hotplug event\n");
kobject_uevent_env(&dev->primary->kdev.kobj, KOBJ_CHANGE, envp);
}
EXPORT_SYMBOL(drm_sysfs_hotplug_event);
/**
* drm_sysfs_device_add - adds a class device to sysfs for a character driver
* @dev: DRM device to be added
* @head: DRM head in question
*
* Add a DRM device to the DRM's device model class. We use @dev's PCI device
* as the parent for the Linux device, and make sure it has a file containing
* the driver we're using (for userspace compatibility).
*/
int drm_sysfs_device_add(struct drm_minor *minor)
{
int err;
char *minor_str;
minor->kdev.parent = &minor->dev->pdev->dev;
minor->kdev.class = drm_class;
minor->kdev.release = drm_sysfs_device_release;
minor->kdev.devt = minor->device;
minor->kdev.type = &drm_sysfs_device_minor;
if (minor->type == DRM_MINOR_CONTROL)
minor_str = "controlD%d";
else if (minor->type == DRM_MINOR_RENDER)
minor_str = "renderD%d";
else
minor_str = "card%d";
dev_set_name(&minor->kdev, minor_str, minor->index);
err = device_register(&minor->kdev);
if (err) {
DRM_ERROR("device add failed: %d\n", err);
goto err_out;
}
return 0;
err_out:
return err;
}
/**
* drm_sysfs_device_remove - remove DRM device
* @dev: DRM device to remove
*
* This call unregisters and cleans up a class device that was created with a
* call to drm_sysfs_device_add()
*/
void drm_sysfs_device_remove(struct drm_minor *minor)
{
device_unregister(&minor->kdev);
}
/**
* drm_class_device_register - Register a struct device in the drm class.
*
* @dev: pointer to struct device to register.
*
* @dev should have all relevant members pre-filled with the exception
* of the class member. In particular, the device_type member must
* be set.
*/
int drm_class_device_register(struct device *dev)
{
dev->class = drm_class;
return device_register(dev);
}
EXPORT_SYMBOL_GPL(drm_class_device_register);
void drm_class_device_unregister(struct device *dev)
{
return device_unregister(dev);
}
EXPORT_SYMBOL_GPL(drm_class_device_unregister);
| gpl-2.0 |
vbatts/linux | tools/perf/builtin-data.c | 766 | 2633 | #include <linux/compiler.h>
#include "builtin.h"
#include "perf.h"
#include "debug.h"
#include "parse-options.h"
#include "data-convert-bt.h"
typedef int (*data_cmd_fn_t)(int argc, const char **argv, const char *prefix);
struct data_cmd {
const char *name;
const char *summary;
data_cmd_fn_t fn;
};
static struct data_cmd data_cmds[];
#define for_each_cmd(cmd) \
for (cmd = data_cmds; cmd && cmd->name; cmd++)
static const struct option data_options[] = {
OPT_END()
};
static const char * const data_subcommands[] = { "convert", NULL };
static const char *data_usage[] = {
"perf data [<common options>] <command> [<options>]",
NULL
};
static void print_usage(void)
{
struct data_cmd *cmd;
printf("Usage:\n");
printf("\t%s\n\n", data_usage[0]);
printf("\tAvailable commands:\n");
for_each_cmd(cmd) {
printf("\t %s\t- %s\n", cmd->name, cmd->summary);
}
printf("\n");
}
static const char * const data_convert_usage[] = {
"perf data convert [<options>]",
NULL
};
static int cmd_data_convert(int argc, const char **argv,
const char *prefix __maybe_unused)
{
const char *to_ctf = NULL;
bool force = false;
const struct option options[] = {
OPT_INCR('v', "verbose", &verbose, "be more verbose"),
OPT_STRING('i', "input", &input_name, "file", "input file name"),
#ifdef HAVE_LIBBABELTRACE_SUPPORT
OPT_STRING(0, "to-ctf", &to_ctf, NULL, "Convert to CTF format"),
#endif
OPT_BOOLEAN('f', "force", &force, "don't complain, do it"),
OPT_END()
};
#ifndef HAVE_LIBBABELTRACE_SUPPORT
pr_err("No conversion support compiled in.\n");
return -1;
#endif
argc = parse_options(argc, argv, options,
data_convert_usage, 0);
if (argc) {
usage_with_options(data_convert_usage, options);
return -1;
}
if (to_ctf) {
#ifdef HAVE_LIBBABELTRACE_SUPPORT
return bt_convert__perf2ctf(input_name, to_ctf, force);
#else
pr_err("The libbabeltrace support is not compiled in.\n");
return -1;
#endif
}
return 0;
}
static struct data_cmd data_cmds[] = {
{ "convert", "converts data file between formats", cmd_data_convert },
{ .name = NULL, },
};
int cmd_data(int argc, const char **argv, const char *prefix)
{
struct data_cmd *cmd;
const char *cmdstr;
/* No command specified. */
if (argc < 2)
goto usage;
argc = parse_options_subcommand(argc, argv, data_options, data_subcommands, data_usage,
PARSE_OPT_STOP_AT_NON_OPTION);
if (argc < 1)
goto usage;
cmdstr = argv[0];
for_each_cmd(cmd) {
if (strcmp(cmd->name, cmdstr))
continue;
return cmd->fn(argc, argv, prefix);
}
pr_err("Unknown command: %s\n", cmdstr);
usage:
print_usage();
return -1;
}
| gpl-2.0 |
peter-65/rpi-linux | drivers/input/keyboard/omap-keypad.c | 766 | 9875 | /*
* linux/drivers/input/keyboard/omap-keypad.c
*
* OMAP Keypad Driver
*
* Copyright (C) 2003 Nokia Corporation
* Written by Timo Teräs <ext-timo.teras@nokia.com>
*
* Added support for H2 & H3 Keypad
* Copyright (C) 2004 Texas Instruments
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/types.h>
#include <linux/input.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/mutex.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/gpio.h>
#include <linux/platform_data/gpio-omap.h>
#include <linux/platform_data/keypad-omap.h>
#undef NEW_BOARD_LEARNING_MODE
static void omap_kp_tasklet(unsigned long);
static void omap_kp_timer(unsigned long);
static unsigned char keypad_state[8];
static DEFINE_MUTEX(kp_enable_mutex);
static int kp_enable = 1;
static int kp_cur_group = -1;
struct omap_kp {
struct input_dev *input;
struct timer_list timer;
int irq;
unsigned int rows;
unsigned int cols;
unsigned long delay;
unsigned int debounce;
unsigned short keymap[];
};
static DECLARE_TASKLET_DISABLED(kp_tasklet, omap_kp_tasklet, 0);
static unsigned int *row_gpios;
static unsigned int *col_gpios;
#ifdef CONFIG_ARCH_OMAP2
static void set_col_gpio_val(struct omap_kp *omap_kp, u8 value)
{
int col;
for (col = 0; col < omap_kp->cols; col++)
gpio_set_value(col_gpios[col], value & (1 << col));
}
static u8 get_row_gpio_val(struct omap_kp *omap_kp)
{
int row;
u8 value = 0;
for (row = 0; row < omap_kp->rows; row++) {
if (gpio_get_value(row_gpios[row]))
value |= (1 << row);
}
return value;
}
#else
#define set_col_gpio_val(x, y) do {} while (0)
#define get_row_gpio_val(x) 0
#endif
static irqreturn_t omap_kp_interrupt(int irq, void *dev_id)
{
/* disable keyboard interrupt and schedule for handling */
omap_writew(1, OMAP1_MPUIO_BASE + OMAP_MPUIO_KBD_MASKIT);
tasklet_schedule(&kp_tasklet);
return IRQ_HANDLED;
}
static void omap_kp_timer(unsigned long data)
{
tasklet_schedule(&kp_tasklet);
}
static void omap_kp_scan_keypad(struct omap_kp *omap_kp, unsigned char *state)
{
int col = 0;
/* disable keyboard interrupt and schedule for handling */
omap_writew(1, OMAP1_MPUIO_BASE + OMAP_MPUIO_KBD_MASKIT);
/* read the keypad status */
omap_writew(0xff, OMAP1_MPUIO_BASE + OMAP_MPUIO_KBC);
for (col = 0; col < omap_kp->cols; col++) {
omap_writew(~(1 << col) & 0xff,
OMAP1_MPUIO_BASE + OMAP_MPUIO_KBC);
udelay(omap_kp->delay);
state[col] = ~omap_readw(OMAP1_MPUIO_BASE +
OMAP_MPUIO_KBR_LATCH) & 0xff;
}
omap_writew(0x00, OMAP1_MPUIO_BASE + OMAP_MPUIO_KBC);
udelay(2);
}
static void omap_kp_tasklet(unsigned long data)
{
struct omap_kp *omap_kp_data = (struct omap_kp *) data;
unsigned short *keycodes = omap_kp_data->input->keycode;
unsigned int row_shift = get_count_order(omap_kp_data->cols);
unsigned char new_state[8], changed, key_down = 0;
int col, row;
int spurious = 0;
/* check for any changes */
omap_kp_scan_keypad(omap_kp_data, new_state);
/* check for changes and print those */
for (col = 0; col < omap_kp_data->cols; col++) {
changed = new_state[col] ^ keypad_state[col];
key_down |= new_state[col];
if (changed == 0)
continue;
for (row = 0; row < omap_kp_data->rows; row++) {
int key;
if (!(changed & (1 << row)))
continue;
#ifdef NEW_BOARD_LEARNING_MODE
printk(KERN_INFO "omap-keypad: key %d-%d %s\n", col,
row, (new_state[col] & (1 << row)) ?
"pressed" : "released");
#else
key = keycodes[MATRIX_SCAN_CODE(row, col, row_shift)];
if (key < 0) {
printk(KERN_WARNING
"omap-keypad: Spurious key event %d-%d\n",
col, row);
/* We scan again after a couple of seconds */
spurious = 1;
continue;
}
if (!(kp_cur_group == (key & GROUP_MASK) ||
kp_cur_group == -1))
continue;
kp_cur_group = key & GROUP_MASK;
input_report_key(omap_kp_data->input, key & ~GROUP_MASK,
new_state[col] & (1 << row));
#endif
}
}
input_sync(omap_kp_data->input);
memcpy(keypad_state, new_state, sizeof(keypad_state));
if (key_down) {
int delay = HZ / 20;
/* some key is pressed - keep irq disabled and use timer
* to poll the keypad */
if (spurious)
delay = 2 * HZ;
mod_timer(&omap_kp_data->timer, jiffies + delay);
} else {
/* enable interrupts */
omap_writew(0, OMAP1_MPUIO_BASE + OMAP_MPUIO_KBD_MASKIT);
kp_cur_group = -1;
}
}
static ssize_t omap_kp_enable_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%u\n", kp_enable);
}
static ssize_t omap_kp_enable_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct omap_kp *omap_kp = dev_get_drvdata(dev);
int state;
if (sscanf(buf, "%u", &state) != 1)
return -EINVAL;
if ((state != 1) && (state != 0))
return -EINVAL;
mutex_lock(&kp_enable_mutex);
if (state != kp_enable) {
if (state)
enable_irq(omap_kp->irq);
else
disable_irq(omap_kp->irq);
kp_enable = state;
}
mutex_unlock(&kp_enable_mutex);
return strnlen(buf, count);
}
static DEVICE_ATTR(enable, S_IRUGO | S_IWUSR, omap_kp_enable_show, omap_kp_enable_store);
#ifdef CONFIG_PM
static int omap_kp_suspend(struct platform_device *dev, pm_message_t state)
{
/* Nothing yet */
return 0;
}
static int omap_kp_resume(struct platform_device *dev)
{
/* Nothing yet */
return 0;
}
#else
#define omap_kp_suspend NULL
#define omap_kp_resume NULL
#endif
static int omap_kp_probe(struct platform_device *pdev)
{
struct omap_kp *omap_kp;
struct input_dev *input_dev;
struct omap_kp_platform_data *pdata = dev_get_platdata(&pdev->dev);
int i, col_idx, row_idx, ret;
unsigned int row_shift, keycodemax;
if (!pdata->rows || !pdata->cols || !pdata->keymap_data) {
printk(KERN_ERR "No rows, cols or keymap_data from pdata\n");
return -EINVAL;
}
row_shift = get_count_order(pdata->cols);
keycodemax = pdata->rows << row_shift;
omap_kp = kzalloc(sizeof(struct omap_kp) +
keycodemax * sizeof(unsigned short), GFP_KERNEL);
input_dev = input_allocate_device();
if (!omap_kp || !input_dev) {
kfree(omap_kp);
input_free_device(input_dev);
return -ENOMEM;
}
platform_set_drvdata(pdev, omap_kp);
omap_kp->input = input_dev;
/* Disable the interrupt for the MPUIO keyboard */
omap_writew(1, OMAP1_MPUIO_BASE + OMAP_MPUIO_KBD_MASKIT);
if (pdata->delay)
omap_kp->delay = pdata->delay;
if (pdata->row_gpios && pdata->col_gpios) {
row_gpios = pdata->row_gpios;
col_gpios = pdata->col_gpios;
}
omap_kp->rows = pdata->rows;
omap_kp->cols = pdata->cols;
col_idx = 0;
row_idx = 0;
setup_timer(&omap_kp->timer, omap_kp_timer, (unsigned long)omap_kp);
/* get the irq and init timer*/
tasklet_enable(&kp_tasklet);
kp_tasklet.data = (unsigned long) omap_kp;
ret = device_create_file(&pdev->dev, &dev_attr_enable);
if (ret < 0)
goto err2;
/* setup input device */
input_dev->name = "omap-keypad";
input_dev->phys = "omap-keypad/input0";
input_dev->dev.parent = &pdev->dev;
input_dev->id.bustype = BUS_HOST;
input_dev->id.vendor = 0x0001;
input_dev->id.product = 0x0001;
input_dev->id.version = 0x0100;
if (pdata->rep)
__set_bit(EV_REP, input_dev->evbit);
ret = matrix_keypad_build_keymap(pdata->keymap_data, NULL,
pdata->rows, pdata->cols,
omap_kp->keymap, input_dev);
if (ret < 0)
goto err3;
ret = input_register_device(omap_kp->input);
if (ret < 0) {
printk(KERN_ERR "Unable to register omap-keypad input device\n");
goto err3;
}
if (pdata->dbounce)
omap_writew(0xff, OMAP1_MPUIO_BASE + OMAP_MPUIO_GPIO_DEBOUNCING);
/* scan current status and enable interrupt */
omap_kp_scan_keypad(omap_kp, keypad_state);
omap_kp->irq = platform_get_irq(pdev, 0);
if (omap_kp->irq >= 0) {
if (request_irq(omap_kp->irq, omap_kp_interrupt, 0,
"omap-keypad", omap_kp) < 0)
goto err4;
}
omap_writew(0, OMAP1_MPUIO_BASE + OMAP_MPUIO_KBD_MASKIT);
return 0;
err4:
input_unregister_device(omap_kp->input);
input_dev = NULL;
err3:
device_remove_file(&pdev->dev, &dev_attr_enable);
err2:
for (i = row_idx - 1; i >= 0; i--)
gpio_free(row_gpios[i]);
for (i = col_idx - 1; i >= 0; i--)
gpio_free(col_gpios[i]);
kfree(omap_kp);
input_free_device(input_dev);
return -EINVAL;
}
static int omap_kp_remove(struct platform_device *pdev)
{
struct omap_kp *omap_kp = platform_get_drvdata(pdev);
/* disable keypad interrupt handling */
tasklet_disable(&kp_tasklet);
omap_writew(1, OMAP1_MPUIO_BASE + OMAP_MPUIO_KBD_MASKIT);
free_irq(omap_kp->irq, omap_kp);
del_timer_sync(&omap_kp->timer);
tasklet_kill(&kp_tasklet);
/* unregister everything */
input_unregister_device(omap_kp->input);
kfree(omap_kp);
return 0;
}
static struct platform_driver omap_kp_driver = {
.probe = omap_kp_probe,
.remove = omap_kp_remove,
.suspend = omap_kp_suspend,
.resume = omap_kp_resume,
.driver = {
.name = "omap-keypad",
.owner = THIS_MODULE,
},
};
module_platform_driver(omap_kp_driver);
MODULE_AUTHOR("Timo Teräs");
MODULE_DESCRIPTION("OMAP Keypad Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:omap-keypad");
| gpl-2.0 |
dasty/kernel-openwrt-tmp | drivers/tty/serial/8250/8250_fsl.c | 1278 | 1773 | #include <linux/serial_reg.h>
#include <linux/serial_8250.h>
#include "8250.h"
/*
* Freescale 16550 UART "driver", Copyright (C) 2011 Paul Gortmaker.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This isn't a full driver; it just provides an alternate IRQ
* handler to deal with an errata. Everything else is just
* using the bog standard 8250 support.
*
* We follow code flow of serial8250_default_handle_irq() but add
* a check for a break and insert a dummy read on the Rx for the
* immediately following IRQ event.
*
* We re-use the already existing "bug handling" lsr_saved_flags
* field to carry the "what we just did" information from the one
* IRQ event to the next one.
*/
int fsl8250_handle_irq(struct uart_port *port)
{
unsigned char lsr, orig_lsr;
unsigned long flags;
unsigned int iir;
struct uart_8250_port *up = up_to_u8250p(port);
spin_lock_irqsave(&up->port.lock, flags);
iir = port->serial_in(port, UART_IIR);
if (iir & UART_IIR_NO_INT) {
spin_unlock_irqrestore(&up->port.lock, flags);
return 0;
}
/* This is the WAR; if last event was BRK, then read and return */
if (unlikely(up->lsr_saved_flags & UART_LSR_BI)) {
up->lsr_saved_flags &= ~UART_LSR_BI;
port->serial_in(port, UART_RX);
spin_unlock_irqrestore(&up->port.lock, flags);
return 1;
}
lsr = orig_lsr = up->port.serial_in(&up->port, UART_LSR);
if (lsr & (UART_LSR_DR | UART_LSR_BI))
lsr = serial8250_rx_chars(up, lsr);
serial8250_modem_status(up);
if (lsr & UART_LSR_THRE)
serial8250_tx_chars(up);
up->lsr_saved_flags = orig_lsr;
spin_unlock_irqrestore(&up->port.lock, flags);
return 1;
}
| gpl-2.0 |
zf2-laser-dev/android_kernel_asus_Z00E | drivers/spi/spi-sirf.c | 2046 | 18946 | /*
* SPI bus driver for CSR SiRFprimaII
*
* Copyright (c) 2011 Cambridge Silicon Radio Limited, a CSR plc group company.
*
* Licensed under GPLv2 or later.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/clk.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/of.h>
#include <linux/bitops.h>
#include <linux/err.h>
#include <linux/platform_device.h>
#include <linux/of_gpio.h>
#include <linux/spi/spi.h>
#include <linux/spi/spi_bitbang.h>
#include <linux/pinctrl/consumer.h>
#define DRIVER_NAME "sirfsoc_spi"
#define SIRFSOC_SPI_CTRL 0x0000
#define SIRFSOC_SPI_CMD 0x0004
#define SIRFSOC_SPI_TX_RX_EN 0x0008
#define SIRFSOC_SPI_INT_EN 0x000C
#define SIRFSOC_SPI_INT_STATUS 0x0010
#define SIRFSOC_SPI_TX_DMA_IO_CTRL 0x0100
#define SIRFSOC_SPI_TX_DMA_IO_LEN 0x0104
#define SIRFSOC_SPI_TXFIFO_CTRL 0x0108
#define SIRFSOC_SPI_TXFIFO_LEVEL_CHK 0x010C
#define SIRFSOC_SPI_TXFIFO_OP 0x0110
#define SIRFSOC_SPI_TXFIFO_STATUS 0x0114
#define SIRFSOC_SPI_TXFIFO_DATA 0x0118
#define SIRFSOC_SPI_RX_DMA_IO_CTRL 0x0120
#define SIRFSOC_SPI_RX_DMA_IO_LEN 0x0124
#define SIRFSOC_SPI_RXFIFO_CTRL 0x0128
#define SIRFSOC_SPI_RXFIFO_LEVEL_CHK 0x012C
#define SIRFSOC_SPI_RXFIFO_OP 0x0130
#define SIRFSOC_SPI_RXFIFO_STATUS 0x0134
#define SIRFSOC_SPI_RXFIFO_DATA 0x0138
#define SIRFSOC_SPI_DUMMY_DELAY_CTL 0x0144
/* SPI CTRL register defines */
#define SIRFSOC_SPI_SLV_MODE BIT(16)
#define SIRFSOC_SPI_CMD_MODE BIT(17)
#define SIRFSOC_SPI_CS_IO_OUT BIT(18)
#define SIRFSOC_SPI_CS_IO_MODE BIT(19)
#define SIRFSOC_SPI_CLK_IDLE_STAT BIT(20)
#define SIRFSOC_SPI_CS_IDLE_STAT BIT(21)
#define SIRFSOC_SPI_TRAN_MSB BIT(22)
#define SIRFSOC_SPI_DRV_POS_EDGE BIT(23)
#define SIRFSOC_SPI_CS_HOLD_TIME BIT(24)
#define SIRFSOC_SPI_CLK_SAMPLE_MODE BIT(25)
#define SIRFSOC_SPI_TRAN_DAT_FORMAT_8 (0 << 26)
#define SIRFSOC_SPI_TRAN_DAT_FORMAT_12 (1 << 26)
#define SIRFSOC_SPI_TRAN_DAT_FORMAT_16 (2 << 26)
#define SIRFSOC_SPI_TRAN_DAT_FORMAT_32 (3 << 26)
#define SIRFSOC_SPI_CMD_BYTE_NUM(x) ((x & 3) << 28)
#define SIRFSOC_SPI_ENA_AUTO_CLR BIT(30)
#define SIRFSOC_SPI_MUL_DAT_MODE BIT(31)
/* Interrupt Enable */
#define SIRFSOC_SPI_RX_DONE_INT_EN BIT(0)
#define SIRFSOC_SPI_TX_DONE_INT_EN BIT(1)
#define SIRFSOC_SPI_RX_OFLOW_INT_EN BIT(2)
#define SIRFSOC_SPI_TX_UFLOW_INT_EN BIT(3)
#define SIRFSOC_SPI_RX_IO_DMA_INT_EN BIT(4)
#define SIRFSOC_SPI_TX_IO_DMA_INT_EN BIT(5)
#define SIRFSOC_SPI_RXFIFO_FULL_INT_EN BIT(6)
#define SIRFSOC_SPI_TXFIFO_EMPTY_INT_EN BIT(7)
#define SIRFSOC_SPI_RXFIFO_THD_INT_EN BIT(8)
#define SIRFSOC_SPI_TXFIFO_THD_INT_EN BIT(9)
#define SIRFSOC_SPI_FRM_END_INT_EN BIT(10)
#define SIRFSOC_SPI_INT_MASK_ALL 0x1FFF
/* Interrupt status */
#define SIRFSOC_SPI_RX_DONE BIT(0)
#define SIRFSOC_SPI_TX_DONE BIT(1)
#define SIRFSOC_SPI_RX_OFLOW BIT(2)
#define SIRFSOC_SPI_TX_UFLOW BIT(3)
#define SIRFSOC_SPI_RX_FIFO_FULL BIT(6)
#define SIRFSOC_SPI_TXFIFO_EMPTY BIT(7)
#define SIRFSOC_SPI_RXFIFO_THD_REACH BIT(8)
#define SIRFSOC_SPI_TXFIFO_THD_REACH BIT(9)
#define SIRFSOC_SPI_FRM_END BIT(10)
/* TX RX enable */
#define SIRFSOC_SPI_RX_EN BIT(0)
#define SIRFSOC_SPI_TX_EN BIT(1)
#define SIRFSOC_SPI_CMD_TX_EN BIT(2)
#define SIRFSOC_SPI_IO_MODE_SEL BIT(0)
#define SIRFSOC_SPI_RX_DMA_FLUSH BIT(2)
/* FIFO OPs */
#define SIRFSOC_SPI_FIFO_RESET BIT(0)
#define SIRFSOC_SPI_FIFO_START BIT(1)
/* FIFO CTRL */
#define SIRFSOC_SPI_FIFO_WIDTH_BYTE (0 << 0)
#define SIRFSOC_SPI_FIFO_WIDTH_WORD (1 << 0)
#define SIRFSOC_SPI_FIFO_WIDTH_DWORD (2 << 0)
/* FIFO Status */
#define SIRFSOC_SPI_FIFO_LEVEL_MASK 0xFF
#define SIRFSOC_SPI_FIFO_FULL BIT(8)
#define SIRFSOC_SPI_FIFO_EMPTY BIT(9)
/* 256 bytes rx/tx FIFO */
#define SIRFSOC_SPI_FIFO_SIZE 256
#define SIRFSOC_SPI_DAT_FRM_LEN_MAX (64 * 1024)
#define SIRFSOC_SPI_FIFO_SC(x) ((x) & 0x3F)
#define SIRFSOC_SPI_FIFO_LC(x) (((x) & 0x3F) << 10)
#define SIRFSOC_SPI_FIFO_HC(x) (((x) & 0x3F) << 20)
#define SIRFSOC_SPI_FIFO_THD(x) (((x) & 0xFF) << 2)
struct sirfsoc_spi {
struct spi_bitbang bitbang;
struct completion done;
void __iomem *base;
u32 ctrl_freq; /* SPI controller clock speed */
struct clk *clk;
struct pinctrl *p;
/* rx & tx bufs from the spi_transfer */
const void *tx;
void *rx;
/* place received word into rx buffer */
void (*rx_word) (struct sirfsoc_spi *);
/* get word from tx buffer for sending */
void (*tx_word) (struct sirfsoc_spi *);
/* number of words left to be tranmitted/received */
unsigned int left_tx_cnt;
unsigned int left_rx_cnt;
/* tasklet to push tx msg into FIFO */
struct tasklet_struct tasklet_tx;
int chipselect[0];
};
static void spi_sirfsoc_rx_word_u8(struct sirfsoc_spi *sspi)
{
u32 data;
u8 *rx = sspi->rx;
data = readl(sspi->base + SIRFSOC_SPI_RXFIFO_DATA);
if (rx) {
*rx++ = (u8) data;
sspi->rx = rx;
}
sspi->left_rx_cnt--;
}
static void spi_sirfsoc_tx_word_u8(struct sirfsoc_spi *sspi)
{
u32 data = 0;
const u8 *tx = sspi->tx;
if (tx) {
data = *tx++;
sspi->tx = tx;
}
writel(data, sspi->base + SIRFSOC_SPI_TXFIFO_DATA);
sspi->left_tx_cnt--;
}
static void spi_sirfsoc_rx_word_u16(struct sirfsoc_spi *sspi)
{
u32 data;
u16 *rx = sspi->rx;
data = readl(sspi->base + SIRFSOC_SPI_RXFIFO_DATA);
if (rx) {
*rx++ = (u16) data;
sspi->rx = rx;
}
sspi->left_rx_cnt--;
}
static void spi_sirfsoc_tx_word_u16(struct sirfsoc_spi *sspi)
{
u32 data = 0;
const u16 *tx = sspi->tx;
if (tx) {
data = *tx++;
sspi->tx = tx;
}
writel(data, sspi->base + SIRFSOC_SPI_TXFIFO_DATA);
sspi->left_tx_cnt--;
}
static void spi_sirfsoc_rx_word_u32(struct sirfsoc_spi *sspi)
{
u32 data;
u32 *rx = sspi->rx;
data = readl(sspi->base + SIRFSOC_SPI_RXFIFO_DATA);
if (rx) {
*rx++ = (u32) data;
sspi->rx = rx;
}
sspi->left_rx_cnt--;
}
static void spi_sirfsoc_tx_word_u32(struct sirfsoc_spi *sspi)
{
u32 data = 0;
const u32 *tx = sspi->tx;
if (tx) {
data = *tx++;
sspi->tx = tx;
}
writel(data, sspi->base + SIRFSOC_SPI_TXFIFO_DATA);
sspi->left_tx_cnt--;
}
static void spi_sirfsoc_tasklet_tx(unsigned long arg)
{
struct sirfsoc_spi *sspi = (struct sirfsoc_spi *)arg;
/* Fill Tx FIFO while there are left words to be transmitted */
while (!((readl(sspi->base + SIRFSOC_SPI_TXFIFO_STATUS) &
SIRFSOC_SPI_FIFO_FULL)) &&
sspi->left_tx_cnt)
sspi->tx_word(sspi);
}
static irqreturn_t spi_sirfsoc_irq(int irq, void *dev_id)
{
struct sirfsoc_spi *sspi = dev_id;
u32 spi_stat = readl(sspi->base + SIRFSOC_SPI_INT_STATUS);
writel(spi_stat, sspi->base + SIRFSOC_SPI_INT_STATUS);
/* Error Conditions */
if (spi_stat & SIRFSOC_SPI_RX_OFLOW ||
spi_stat & SIRFSOC_SPI_TX_UFLOW) {
complete(&sspi->done);
writel(0x0, sspi->base + SIRFSOC_SPI_INT_EN);
}
if (spi_stat & SIRFSOC_SPI_FRM_END) {
while (!((readl(sspi->base + SIRFSOC_SPI_RXFIFO_STATUS)
& SIRFSOC_SPI_FIFO_EMPTY)) &&
sspi->left_rx_cnt)
sspi->rx_word(sspi);
/* Received all words */
if ((sspi->left_rx_cnt == 0) && (sspi->left_tx_cnt == 0)) {
complete(&sspi->done);
writel(0x0, sspi->base + SIRFSOC_SPI_INT_EN);
}
}
if (spi_stat & SIRFSOC_SPI_RXFIFO_THD_REACH ||
spi_stat & SIRFSOC_SPI_TXFIFO_THD_REACH ||
spi_stat & SIRFSOC_SPI_RX_FIFO_FULL ||
spi_stat & SIRFSOC_SPI_TXFIFO_EMPTY)
tasklet_schedule(&sspi->tasklet_tx);
return IRQ_HANDLED;
}
static int spi_sirfsoc_transfer(struct spi_device *spi, struct spi_transfer *t)
{
struct sirfsoc_spi *sspi;
int timeout = t->len * 10;
sspi = spi_master_get_devdata(spi->master);
sspi->tx = t->tx_buf;
sspi->rx = t->rx_buf;
sspi->left_tx_cnt = sspi->left_rx_cnt = t->len;
INIT_COMPLETION(sspi->done);
writel(SIRFSOC_SPI_INT_MASK_ALL, sspi->base + SIRFSOC_SPI_INT_STATUS);
if (t->len == 1) {
writel(readl(sspi->base + SIRFSOC_SPI_CTRL) |
SIRFSOC_SPI_ENA_AUTO_CLR,
sspi->base + SIRFSOC_SPI_CTRL);
writel(0, sspi->base + SIRFSOC_SPI_TX_DMA_IO_LEN);
writel(0, sspi->base + SIRFSOC_SPI_RX_DMA_IO_LEN);
} else if ((t->len > 1) && (t->len < SIRFSOC_SPI_DAT_FRM_LEN_MAX)) {
writel(readl(sspi->base + SIRFSOC_SPI_CTRL) |
SIRFSOC_SPI_MUL_DAT_MODE |
SIRFSOC_SPI_ENA_AUTO_CLR,
sspi->base + SIRFSOC_SPI_CTRL);
writel(t->len - 1, sspi->base + SIRFSOC_SPI_TX_DMA_IO_LEN);
writel(t->len - 1, sspi->base + SIRFSOC_SPI_RX_DMA_IO_LEN);
} else {
writel(readl(sspi->base + SIRFSOC_SPI_CTRL),
sspi->base + SIRFSOC_SPI_CTRL);
writel(0, sspi->base + SIRFSOC_SPI_TX_DMA_IO_LEN);
writel(0, sspi->base + SIRFSOC_SPI_RX_DMA_IO_LEN);
}
writel(SIRFSOC_SPI_FIFO_RESET, sspi->base + SIRFSOC_SPI_RXFIFO_OP);
writel(SIRFSOC_SPI_FIFO_RESET, sspi->base + SIRFSOC_SPI_TXFIFO_OP);
writel(SIRFSOC_SPI_FIFO_START, sspi->base + SIRFSOC_SPI_RXFIFO_OP);
writel(SIRFSOC_SPI_FIFO_START, sspi->base + SIRFSOC_SPI_TXFIFO_OP);
/* Send the first word to trigger the whole tx/rx process */
sspi->tx_word(sspi);
writel(SIRFSOC_SPI_RX_OFLOW_INT_EN | SIRFSOC_SPI_TX_UFLOW_INT_EN |
SIRFSOC_SPI_RXFIFO_THD_INT_EN | SIRFSOC_SPI_TXFIFO_THD_INT_EN |
SIRFSOC_SPI_FRM_END_INT_EN | SIRFSOC_SPI_RXFIFO_FULL_INT_EN |
SIRFSOC_SPI_TXFIFO_EMPTY_INT_EN, sspi->base + SIRFSOC_SPI_INT_EN);
writel(SIRFSOC_SPI_RX_EN | SIRFSOC_SPI_TX_EN, sspi->base + SIRFSOC_SPI_TX_RX_EN);
if (wait_for_completion_timeout(&sspi->done, timeout) == 0)
dev_err(&spi->dev, "transfer timeout\n");
/* TX, RX FIFO stop */
writel(0, sspi->base + SIRFSOC_SPI_RXFIFO_OP);
writel(0, sspi->base + SIRFSOC_SPI_TXFIFO_OP);
writel(0, sspi->base + SIRFSOC_SPI_TX_RX_EN);
writel(0, sspi->base + SIRFSOC_SPI_INT_EN);
return t->len - sspi->left_rx_cnt;
}
static void spi_sirfsoc_chipselect(struct spi_device *spi, int value)
{
struct sirfsoc_spi *sspi = spi_master_get_devdata(spi->master);
if (sspi->chipselect[spi->chip_select] == 0) {
u32 regval = readl(sspi->base + SIRFSOC_SPI_CTRL);
regval |= SIRFSOC_SPI_CS_IO_OUT;
switch (value) {
case BITBANG_CS_ACTIVE:
if (spi->mode & SPI_CS_HIGH)
regval |= SIRFSOC_SPI_CS_IO_OUT;
else
regval &= ~SIRFSOC_SPI_CS_IO_OUT;
break;
case BITBANG_CS_INACTIVE:
if (spi->mode & SPI_CS_HIGH)
regval &= ~SIRFSOC_SPI_CS_IO_OUT;
else
regval |= SIRFSOC_SPI_CS_IO_OUT;
break;
}
writel(regval, sspi->base + SIRFSOC_SPI_CTRL);
} else {
int gpio = sspi->chipselect[spi->chip_select];
gpio_direction_output(gpio, spi->mode & SPI_CS_HIGH ? 0 : 1);
}
}
static int
spi_sirfsoc_setup_transfer(struct spi_device *spi, struct spi_transfer *t)
{
struct sirfsoc_spi *sspi;
u8 bits_per_word = 0;
int hz = 0;
u32 regval;
u32 txfifo_ctrl, rxfifo_ctrl;
u32 fifo_size = SIRFSOC_SPI_FIFO_SIZE / 4;
sspi = spi_master_get_devdata(spi->master);
bits_per_word = (t) ? t->bits_per_word : spi->bits_per_word;
hz = t && t->speed_hz ? t->speed_hz : spi->max_speed_hz;
/* Enable IO mode for RX, TX */
writel(SIRFSOC_SPI_IO_MODE_SEL, sspi->base + SIRFSOC_SPI_TX_DMA_IO_CTRL);
writel(SIRFSOC_SPI_IO_MODE_SEL, sspi->base + SIRFSOC_SPI_RX_DMA_IO_CTRL);
regval = (sspi->ctrl_freq / (2 * hz)) - 1;
if (regval > 0xFFFF || regval < 0) {
dev_err(&spi->dev, "Speed %d not supported\n", hz);
return -EINVAL;
}
switch (bits_per_word) {
case 8:
regval |= SIRFSOC_SPI_TRAN_DAT_FORMAT_8;
sspi->rx_word = spi_sirfsoc_rx_word_u8;
sspi->tx_word = spi_sirfsoc_tx_word_u8;
txfifo_ctrl = SIRFSOC_SPI_FIFO_THD(SIRFSOC_SPI_FIFO_SIZE / 2) |
SIRFSOC_SPI_FIFO_WIDTH_BYTE;
rxfifo_ctrl = SIRFSOC_SPI_FIFO_THD(SIRFSOC_SPI_FIFO_SIZE / 2) |
SIRFSOC_SPI_FIFO_WIDTH_BYTE;
break;
case 12:
case 16:
regval |= (bits_per_word == 12) ? SIRFSOC_SPI_TRAN_DAT_FORMAT_12 :
SIRFSOC_SPI_TRAN_DAT_FORMAT_16;
sspi->rx_word = spi_sirfsoc_rx_word_u16;
sspi->tx_word = spi_sirfsoc_tx_word_u16;
txfifo_ctrl = SIRFSOC_SPI_FIFO_THD(SIRFSOC_SPI_FIFO_SIZE / 2) |
SIRFSOC_SPI_FIFO_WIDTH_WORD;
rxfifo_ctrl = SIRFSOC_SPI_FIFO_THD(SIRFSOC_SPI_FIFO_SIZE / 2) |
SIRFSOC_SPI_FIFO_WIDTH_WORD;
break;
case 32:
regval |= SIRFSOC_SPI_TRAN_DAT_FORMAT_32;
sspi->rx_word = spi_sirfsoc_rx_word_u32;
sspi->tx_word = spi_sirfsoc_tx_word_u32;
txfifo_ctrl = SIRFSOC_SPI_FIFO_THD(SIRFSOC_SPI_FIFO_SIZE / 2) |
SIRFSOC_SPI_FIFO_WIDTH_DWORD;
rxfifo_ctrl = SIRFSOC_SPI_FIFO_THD(SIRFSOC_SPI_FIFO_SIZE / 2) |
SIRFSOC_SPI_FIFO_WIDTH_DWORD;
break;
default:
dev_err(&spi->dev, "Bits per word %d not supported\n",
bits_per_word);
return -EINVAL;
}
if (!(spi->mode & SPI_CS_HIGH))
regval |= SIRFSOC_SPI_CS_IDLE_STAT;
if (!(spi->mode & SPI_LSB_FIRST))
regval |= SIRFSOC_SPI_TRAN_MSB;
if (spi->mode & SPI_CPOL)
regval |= SIRFSOC_SPI_CLK_IDLE_STAT;
/*
* Data should be driven at least 1/2 cycle before the fetch edge to make
* sure that data gets stable at the fetch edge.
*/
if (((spi->mode & SPI_CPOL) && (spi->mode & SPI_CPHA)) ||
(!(spi->mode & SPI_CPOL) && !(spi->mode & SPI_CPHA)))
regval &= ~SIRFSOC_SPI_DRV_POS_EDGE;
else
regval |= SIRFSOC_SPI_DRV_POS_EDGE;
writel(SIRFSOC_SPI_FIFO_SC(fifo_size - 2) |
SIRFSOC_SPI_FIFO_LC(fifo_size / 2) |
SIRFSOC_SPI_FIFO_HC(2),
sspi->base + SIRFSOC_SPI_TXFIFO_LEVEL_CHK);
writel(SIRFSOC_SPI_FIFO_SC(2) |
SIRFSOC_SPI_FIFO_LC(fifo_size / 2) |
SIRFSOC_SPI_FIFO_HC(fifo_size - 2),
sspi->base + SIRFSOC_SPI_RXFIFO_LEVEL_CHK);
writel(txfifo_ctrl, sspi->base + SIRFSOC_SPI_TXFIFO_CTRL);
writel(rxfifo_ctrl, sspi->base + SIRFSOC_SPI_RXFIFO_CTRL);
writel(regval, sspi->base + SIRFSOC_SPI_CTRL);
return 0;
}
static int spi_sirfsoc_setup(struct spi_device *spi)
{
struct sirfsoc_spi *sspi;
if (!spi->max_speed_hz)
return -EINVAL;
sspi = spi_master_get_devdata(spi->master);
if (!spi->bits_per_word)
spi->bits_per_word = 8;
return spi_sirfsoc_setup_transfer(spi, NULL);
}
static int spi_sirfsoc_probe(struct platform_device *pdev)
{
struct sirfsoc_spi *sspi;
struct spi_master *master;
struct resource *mem_res;
int num_cs, cs_gpio, irq;
int i;
int ret;
ret = of_property_read_u32(pdev->dev.of_node,
"sirf,spi-num-chipselects", &num_cs);
if (ret < 0) {
dev_err(&pdev->dev, "Unable to get chip select number\n");
goto err_cs;
}
master = spi_alloc_master(&pdev->dev, sizeof(*sspi) + sizeof(int) * num_cs);
if (!master) {
dev_err(&pdev->dev, "Unable to allocate SPI master\n");
return -ENOMEM;
}
platform_set_drvdata(pdev, master);
sspi = spi_master_get_devdata(master);
mem_res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!mem_res) {
dev_err(&pdev->dev, "Unable to get IO resource\n");
ret = -ENODEV;
goto free_master;
}
master->num_chipselect = num_cs;
for (i = 0; i < master->num_chipselect; i++) {
cs_gpio = of_get_named_gpio(pdev->dev.of_node, "cs-gpios", i);
if (cs_gpio < 0) {
dev_err(&pdev->dev, "can't get cs gpio from DT\n");
ret = -ENODEV;
goto free_master;
}
sspi->chipselect[i] = cs_gpio;
if (cs_gpio == 0)
continue; /* use cs from spi controller */
ret = gpio_request(cs_gpio, DRIVER_NAME);
if (ret) {
while (i > 0) {
i--;
if (sspi->chipselect[i] > 0)
gpio_free(sspi->chipselect[i]);
}
dev_err(&pdev->dev, "fail to request cs gpios\n");
goto free_master;
}
}
sspi->base = devm_ioremap_resource(&pdev->dev, mem_res);
if (IS_ERR(sspi->base)) {
ret = PTR_ERR(sspi->base);
goto free_master;
}
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
ret = -ENXIO;
goto free_master;
}
ret = devm_request_irq(&pdev->dev, irq, spi_sirfsoc_irq, 0,
DRIVER_NAME, sspi);
if (ret)
goto free_master;
sspi->bitbang.master = spi_master_get(master);
sspi->bitbang.chipselect = spi_sirfsoc_chipselect;
sspi->bitbang.setup_transfer = spi_sirfsoc_setup_transfer;
sspi->bitbang.txrx_bufs = spi_sirfsoc_transfer;
sspi->bitbang.master->setup = spi_sirfsoc_setup;
master->bus_num = pdev->id;
sspi->bitbang.master->dev.of_node = pdev->dev.of_node;
sspi->p = pinctrl_get_select_default(&pdev->dev);
ret = IS_ERR(sspi->p);
if (ret)
goto free_master;
sspi->clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(sspi->clk)) {
ret = -EINVAL;
goto free_pin;
}
clk_prepare_enable(sspi->clk);
sspi->ctrl_freq = clk_get_rate(sspi->clk);
init_completion(&sspi->done);
tasklet_init(&sspi->tasklet_tx, spi_sirfsoc_tasklet_tx,
(unsigned long)sspi);
writel(SIRFSOC_SPI_FIFO_RESET, sspi->base + SIRFSOC_SPI_RXFIFO_OP);
writel(SIRFSOC_SPI_FIFO_RESET, sspi->base + SIRFSOC_SPI_TXFIFO_OP);
writel(SIRFSOC_SPI_FIFO_START, sspi->base + SIRFSOC_SPI_RXFIFO_OP);
writel(SIRFSOC_SPI_FIFO_START, sspi->base + SIRFSOC_SPI_TXFIFO_OP);
/* We are not using dummy delay between command and data */
writel(0, sspi->base + SIRFSOC_SPI_DUMMY_DELAY_CTL);
ret = spi_bitbang_start(&sspi->bitbang);
if (ret)
goto free_clk;
dev_info(&pdev->dev, "registerred, bus number = %d\n", master->bus_num);
return 0;
free_clk:
clk_disable_unprepare(sspi->clk);
clk_put(sspi->clk);
free_pin:
pinctrl_put(sspi->p);
free_master:
spi_master_put(master);
err_cs:
return ret;
}
static int spi_sirfsoc_remove(struct platform_device *pdev)
{
struct spi_master *master;
struct sirfsoc_spi *sspi;
int i;
master = platform_get_drvdata(pdev);
sspi = spi_master_get_devdata(master);
spi_bitbang_stop(&sspi->bitbang);
for (i = 0; i < master->num_chipselect; i++) {
if (sspi->chipselect[i] > 0)
gpio_free(sspi->chipselect[i]);
}
clk_disable_unprepare(sspi->clk);
clk_put(sspi->clk);
pinctrl_put(sspi->p);
spi_master_put(master);
return 0;
}
#ifdef CONFIG_PM
static int spi_sirfsoc_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct spi_master *master = platform_get_drvdata(pdev);
struct sirfsoc_spi *sspi = spi_master_get_devdata(master);
clk_disable(sspi->clk);
return 0;
}
static int spi_sirfsoc_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct spi_master *master = platform_get_drvdata(pdev);
struct sirfsoc_spi *sspi = spi_master_get_devdata(master);
clk_enable(sspi->clk);
writel(SIRFSOC_SPI_FIFO_RESET, sspi->base + SIRFSOC_SPI_RXFIFO_OP);
writel(SIRFSOC_SPI_FIFO_RESET, sspi->base + SIRFSOC_SPI_TXFIFO_OP);
writel(SIRFSOC_SPI_FIFO_START, sspi->base + SIRFSOC_SPI_RXFIFO_OP);
writel(SIRFSOC_SPI_FIFO_START, sspi->base + SIRFSOC_SPI_TXFIFO_OP);
return 0;
}
static const struct dev_pm_ops spi_sirfsoc_pm_ops = {
.suspend = spi_sirfsoc_suspend,
.resume = spi_sirfsoc_resume,
};
#endif
static const struct of_device_id spi_sirfsoc_of_match[] = {
{ .compatible = "sirf,prima2-spi", },
{ .compatible = "sirf,marco-spi", },
{}
};
MODULE_DEVICE_TABLE(of, spi_sirfsoc_of_match);
static struct platform_driver spi_sirfsoc_driver = {
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
#ifdef CONFIG_PM
.pm = &spi_sirfsoc_pm_ops,
#endif
.of_match_table = spi_sirfsoc_of_match,
},
.probe = spi_sirfsoc_probe,
.remove = spi_sirfsoc_remove,
};
module_platform_driver(spi_sirfsoc_driver);
MODULE_DESCRIPTION("SiRF SoC SPI master driver");
MODULE_AUTHOR("Zhiwu Song <Zhiwu.Song@csr.com>, "
"Barry Song <Baohua.Song@csr.com>");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
placiano/NBKernel_NK4 | arch/arm/mach-omap2/board-rx51-video.c | 2046 | 1866 | /*
* linux/arch/arm/mach-omap2/board-rx51-video.c
*
* Copyright (C) 2010 Nokia
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/spi/spi.h>
#include <linux/mm.h>
#include <asm/mach-types.h>
#include <video/omapdss.h>
#include <video/omap-panel-data.h>
#include <linux/platform_data/spi-omap2-mcspi.h>
#include "soc.h"
#include "board-rx51.h"
#include "mux.h"
#define RX51_LCD_RESET_GPIO 90
#if defined(CONFIG_FB_OMAP2) || defined(CONFIG_FB_OMAP2_MODULE)
static struct panel_acx565akm_data lcd_data = {
.reset_gpio = RX51_LCD_RESET_GPIO,
};
static struct omap_dss_device rx51_lcd_device = {
.name = "lcd",
.driver_name = "panel-acx565akm",
.type = OMAP_DISPLAY_TYPE_SDI,
.phy.sdi.datapairs = 2,
.data = &lcd_data,
};
static struct omap_dss_device rx51_tv_device = {
.name = "tv",
.type = OMAP_DISPLAY_TYPE_VENC,
.driver_name = "venc",
.phy.venc.type = OMAP_DSS_VENC_TYPE_COMPOSITE,
};
static struct omap_dss_device *rx51_dss_devices[] = {
&rx51_lcd_device,
&rx51_tv_device,
};
static struct omap_dss_board_info rx51_dss_board_info = {
.num_devices = ARRAY_SIZE(rx51_dss_devices),
.devices = rx51_dss_devices,
.default_device = &rx51_lcd_device,
};
static int __init rx51_video_init(void)
{
if (!machine_is_nokia_rx51())
return 0;
if (omap_mux_init_gpio(RX51_LCD_RESET_GPIO, OMAP_PIN_OUTPUT)) {
pr_err("%s cannot configure MUX for LCD RESET\n", __func__);
return 0;
}
omap_display_init(&rx51_dss_board_info);
return 0;
}
omap_subsys_initcall(rx51_video_init);
#endif /* defined(CONFIG_FB_OMAP2) || defined(CONFIG_FB_OMAP2_MODULE) */
| gpl-2.0 |
ED300/android_kernel_wingtech_86518 | arch/um/kernel/um_arch.c | 2302 | 9240 | /*
* Copyright (C) 2000 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL
*/
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/seq_file.h>
#include <linux/string.h>
#include <linux/utsname.h>
#include <linux/sched.h>
#include <asm/pgtable.h>
#include <asm/processor.h>
#include <asm/setup.h>
#include <as-layout.h>
#include <arch.h>
#include <init.h>
#include <kern.h>
#include <kern_util.h>
#include <mem_user.h>
#include <os.h>
#define DEFAULT_COMMAND_LINE "root=98:0"
/* Changed in add_arg and setup_arch, which run before SMP is started */
static char __initdata command_line[COMMAND_LINE_SIZE] = { 0 };
static void __init add_arg(char *arg)
{
if (strlen(command_line) + strlen(arg) + 1 > COMMAND_LINE_SIZE) {
printf("add_arg: Too many command line arguments!\n");
exit(1);
}
if (strlen(command_line) > 0)
strcat(command_line, " ");
strcat(command_line, arg);
}
/*
* These fields are initialized at boot time and not changed.
* XXX This structure is used only in the non-SMP case. Maybe this
* should be moved to smp.c.
*/
struct cpuinfo_um boot_cpu_data = {
.loops_per_jiffy = 0,
.ipi_pipe = { -1, -1 }
};
union thread_union cpu0_irqstack
__attribute__((__section__(".data..init_irqstack"))) =
{ INIT_THREAD_INFO(init_task) };
unsigned long thread_saved_pc(struct task_struct *task)
{
/* FIXME: Need to look up userspace_pid by cpu */
return os_process_pc(userspace_pid[0]);
}
/* Changed in setup_arch, which is called in early boot */
static char host_info[(__NEW_UTS_LEN + 1) * 5];
static int show_cpuinfo(struct seq_file *m, void *v)
{
int index = 0;
#ifdef CONFIG_SMP
index = (struct cpuinfo_um *) v - cpu_data;
if (!cpu_online(index))
return 0;
#endif
seq_printf(m, "processor\t: %d\n", index);
seq_printf(m, "vendor_id\t: User Mode Linux\n");
seq_printf(m, "model name\t: UML\n");
seq_printf(m, "mode\t\t: skas\n");
seq_printf(m, "host\t\t: %s\n", host_info);
seq_printf(m, "bogomips\t: %lu.%02lu\n\n",
loops_per_jiffy/(500000/HZ),
(loops_per_jiffy/(5000/HZ)) % 100);
return 0;
}
static void *c_start(struct seq_file *m, loff_t *pos)
{
return *pos < NR_CPUS ? cpu_data + *pos : NULL;
}
static void *c_next(struct seq_file *m, void *v, loff_t *pos)
{
++*pos;
return c_start(m, pos);
}
static void c_stop(struct seq_file *m, void *v)
{
}
const struct seq_operations cpuinfo_op = {
.start = c_start,
.next = c_next,
.stop = c_stop,
.show = show_cpuinfo,
};
/* Set in linux_main */
unsigned long uml_physmem;
EXPORT_SYMBOL(uml_physmem);
unsigned long uml_reserved; /* Also modified in mem_init */
unsigned long start_vm;
unsigned long end_vm;
/* Set in uml_ncpus_setup */
int ncpus = 1;
/* Set in early boot */
static int have_root __initdata = 0;
/* Set in uml_mem_setup and modified in linux_main */
long long physmem_size = 32 * 1024 * 1024;
static const char *usage_string =
"User Mode Linux v%s\n"
" available at http://user-mode-linux.sourceforge.net/\n\n";
static int __init uml_version_setup(char *line, int *add)
{
printf("%s\n", init_utsname()->release);
exit(0);
return 0;
}
__uml_setup("--version", uml_version_setup,
"--version\n"
" Prints the version number of the kernel.\n\n"
);
static int __init uml_root_setup(char *line, int *add)
{
have_root = 1;
return 0;
}
__uml_setup("root=", uml_root_setup,
"root=<file containing the root fs>\n"
" This is actually used by the generic kernel in exactly the same\n"
" way as in any other kernel. If you configure a number of block\n"
" devices and want to boot off something other than ubd0, you \n"
" would use something like:\n"
" root=/dev/ubd5\n\n"
);
static int __init no_skas_debug_setup(char *line, int *add)
{
printf("'debug' is not necessary to gdb UML in skas mode - run \n");
printf("'gdb linux'\n");
return 0;
}
__uml_setup("debug", no_skas_debug_setup,
"debug\n"
" this flag is not needed to run gdb on UML in skas mode\n\n"
);
#ifdef CONFIG_SMP
static int __init uml_ncpus_setup(char *line, int *add)
{
if (!sscanf(line, "%d", &ncpus)) {
printf("Couldn't parse [%s]\n", line);
return -1;
}
return 0;
}
__uml_setup("ncpus=", uml_ncpus_setup,
"ncpus=<# of desired CPUs>\n"
" This tells an SMP kernel how many virtual processors to start.\n\n"
);
#endif
static int __init Usage(char *line, int *add)
{
const char **p;
printf(usage_string, init_utsname()->release);
p = &__uml_help_start;
while (p < &__uml_help_end) {
printf("%s", *p);
p++;
}
exit(0);
return 0;
}
__uml_setup("--help", Usage,
"--help\n"
" Prints this message.\n\n"
);
static void __init uml_checksetup(char *line, int *add)
{
struct uml_param *p;
p = &__uml_setup_start;
while (p < &__uml_setup_end) {
size_t n;
n = strlen(p->str);
if (!strncmp(line, p->str, n) && p->setup_func(line + n, add))
return;
p++;
}
}
static void __init uml_postsetup(void)
{
initcall_t *p;
p = &__uml_postsetup_start;
while (p < &__uml_postsetup_end) {
(*p)();
p++;
}
return;
}
static int panic_exit(struct notifier_block *self, unsigned long unused1,
void *unused2)
{
bust_spinlocks(1);
show_regs(&(current->thread.regs));
bust_spinlocks(0);
uml_exitcode = 1;
os_dump_core();
return 0;
}
static struct notifier_block panic_exit_notifier = {
.notifier_call = panic_exit,
.next = NULL,
.priority = 0
};
/* Set during early boot */
unsigned long task_size;
EXPORT_SYMBOL(task_size);
unsigned long host_task_size;
unsigned long brk_start;
unsigned long end_iomem;
EXPORT_SYMBOL(end_iomem);
#define MIN_VMALLOC (32 * 1024 * 1024)
extern char __binary_start;
int __init linux_main(int argc, char **argv)
{
unsigned long avail, diff;
unsigned long virtmem_size, max_physmem;
unsigned long stack;
unsigned int i;
int add;
char * mode;
for (i = 1; i < argc; i++) {
if ((i == 1) && (argv[i][0] == ' '))
continue;
add = 1;
uml_checksetup(argv[i], &add);
if (add)
add_arg(argv[i]);
}
if (have_root == 0)
add_arg(DEFAULT_COMMAND_LINE);
host_task_size = os_get_top_address();
/*
* TASK_SIZE needs to be PGDIR_SIZE aligned or else exit_mmap craps
* out
*/
task_size = host_task_size & PGDIR_MASK;
/* OS sanity checks that need to happen before the kernel runs */
os_early_checks();
can_do_skas();
if (proc_mm && ptrace_faultinfo)
mode = "SKAS3";
else
mode = "SKAS0";
printf("UML running in %s mode\n", mode);
brk_start = (unsigned long) sbrk(0);
/*
* Increase physical memory size for exec-shield users
* so they actually get what they asked for. This should
* add zero for non-exec shield users
*/
diff = UML_ROUND_UP(brk_start) - UML_ROUND_UP(&_end);
if (diff > 1024 * 1024) {
printf("Adding %ld bytes to physical memory to account for "
"exec-shield gap\n", diff);
physmem_size += UML_ROUND_UP(brk_start) - UML_ROUND_UP(&_end);
}
uml_physmem = (unsigned long) &__binary_start & PAGE_MASK;
/* Reserve up to 4M after the current brk */
uml_reserved = ROUND_4M(brk_start) + (1 << 22);
setup_machinename(init_utsname()->machine);
highmem = 0;
iomem_size = (iomem_size + PAGE_SIZE - 1) & PAGE_MASK;
max_physmem = TASK_SIZE - uml_physmem - iomem_size - MIN_VMALLOC;
/*
* Zones have to begin on a 1 << MAX_ORDER page boundary,
* so this makes sure that's true for highmem
*/
max_physmem &= ~((1 << (PAGE_SHIFT + MAX_ORDER)) - 1);
if (physmem_size + iomem_size > max_physmem) {
highmem = physmem_size + iomem_size - max_physmem;
physmem_size -= highmem;
#ifndef CONFIG_HIGHMEM
highmem = 0;
printf("CONFIG_HIGHMEM not enabled - physical memory shrunk "
"to %Lu bytes\n", physmem_size);
#endif
}
high_physmem = uml_physmem + physmem_size;
end_iomem = high_physmem + iomem_size;
high_memory = (void *) end_iomem;
start_vm = VMALLOC_START;
setup_physmem(uml_physmem, uml_reserved, physmem_size, highmem);
if (init_maps(physmem_size, iomem_size, highmem)) {
printf("Failed to allocate mem_map for %Lu bytes of physical "
"memory and %Lu bytes of highmem\n", physmem_size,
highmem);
exit(1);
}
virtmem_size = physmem_size;
stack = (unsigned long) argv;
stack &= ~(1024 * 1024 - 1);
avail = stack - start_vm;
if (physmem_size > avail)
virtmem_size = avail;
end_vm = start_vm + virtmem_size;
if (virtmem_size < physmem_size)
printf("Kernel virtual memory size shrunk to %lu bytes\n",
virtmem_size);
atomic_notifier_chain_register(&panic_notifier_list,
&panic_exit_notifier);
uml_postsetup();
stack_protections((unsigned long) &init_thread_info);
os_flush_stdout();
return start_uml();
}
void __init setup_arch(char **cmdline_p)
{
paging_init();
strlcpy(boot_command_line, command_line, COMMAND_LINE_SIZE);
*cmdline_p = command_line;
setup_hostinfo(host_info, sizeof host_info);
}
void __init check_bugs(void)
{
arch_check_bugs();
os_check_bugs();
}
void apply_alternatives(struct alt_instr *start, struct alt_instr *end)
{
}
#ifdef CONFIG_SMP
void alternatives_smp_module_add(struct module *mod, char *name,
void *locks, void *locks_end,
void *text, void *text_end)
{
}
void alternatives_smp_module_del(struct module *mod)
{
}
#endif
| gpl-2.0 |
Werdo/Clickarm_Kernel_3.8 | drivers/video/msm/mdp_ppp.c | 2558 | 21918 | /* drivers/video/msm/mdp_ppp.c
*
* Copyright (C) 2007 QUALCOMM Incorporated
* Copyright (C) 2007 Google Incorporated
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* 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.
*/
#include <linux/fb.h>
#include <linux/file.h>
#include <linux/delay.h>
#include <linux/msm_mdp.h>
#include <linux/platform_data/video-msm_fb.h>
#include "mdp_hw.h"
#include "mdp_scale_tables.h"
#define DLOG(x...) do {} while (0)
#define MDP_DOWNSCALE_BLUR (MDP_DOWNSCALE_MAX + 1)
static int downscale_y_table = MDP_DOWNSCALE_MAX;
static int downscale_x_table = MDP_DOWNSCALE_MAX;
struct mdp_regs {
uint32_t src0;
uint32_t src1;
uint32_t dst0;
uint32_t dst1;
uint32_t src_cfg;
uint32_t dst_cfg;
uint32_t src_pack;
uint32_t dst_pack;
uint32_t src_rect;
uint32_t dst_rect;
uint32_t src_ystride;
uint32_t dst_ystride;
uint32_t op;
uint32_t src_bpp;
uint32_t dst_bpp;
uint32_t edge;
uint32_t phasex_init;
uint32_t phasey_init;
uint32_t phasex_step;
uint32_t phasey_step;
};
static uint32_t pack_pattern[] = {
PPP_ARRAY0(PACK_PATTERN)
};
static uint32_t src_img_cfg[] = {
PPP_ARRAY1(CFG, SRC)
};
static uint32_t dst_img_cfg[] = {
PPP_ARRAY1(CFG, DST)
};
static uint32_t bytes_per_pixel[] = {
[MDP_RGB_565] = 2,
[MDP_RGB_888] = 3,
[MDP_XRGB_8888] = 4,
[MDP_ARGB_8888] = 4,
[MDP_RGBA_8888] = 4,
[MDP_BGRA_8888] = 4,
[MDP_RGBX_8888] = 4,
[MDP_Y_CBCR_H2V1] = 1,
[MDP_Y_CBCR_H2V2] = 1,
[MDP_Y_CRCB_H2V1] = 1,
[MDP_Y_CRCB_H2V2] = 1,
[MDP_YCRYCB_H2V1] = 2
};
static uint32_t dst_op_chroma[] = {
PPP_ARRAY1(CHROMA_SAMP, DST)
};
static uint32_t src_op_chroma[] = {
PPP_ARRAY1(CHROMA_SAMP, SRC)
};
static uint32_t bg_op_chroma[] = {
PPP_ARRAY1(CHROMA_SAMP, BG)
};
static void rotate_dst_addr_x(struct mdp_blit_req *req, struct mdp_regs *regs)
{
regs->dst0 += (req->dst_rect.w -
min((uint32_t)16, req->dst_rect.w)) * regs->dst_bpp;
regs->dst1 += (req->dst_rect.w -
min((uint32_t)16, req->dst_rect.w)) * regs->dst_bpp;
}
static void rotate_dst_addr_y(struct mdp_blit_req *req, struct mdp_regs *regs)
{
regs->dst0 += (req->dst_rect.h -
min((uint32_t)16, req->dst_rect.h)) *
regs->dst_ystride;
regs->dst1 += (req->dst_rect.h -
min((uint32_t)16, req->dst_rect.h)) *
regs->dst_ystride;
}
static void blit_rotate(struct mdp_blit_req *req,
struct mdp_regs *regs)
{
if (req->flags == MDP_ROT_NOP)
return;
regs->op |= PPP_OP_ROT_ON;
if ((req->flags & MDP_ROT_90 || req->flags & MDP_FLIP_LR) &&
!(req->flags & MDP_ROT_90 && req->flags & MDP_FLIP_LR))
rotate_dst_addr_x(req, regs);
if (req->flags & MDP_ROT_90)
regs->op |= PPP_OP_ROT_90;
if (req->flags & MDP_FLIP_UD) {
regs->op |= PPP_OP_FLIP_UD;
rotate_dst_addr_y(req, regs);
}
if (req->flags & MDP_FLIP_LR)
regs->op |= PPP_OP_FLIP_LR;
}
static void blit_convert(struct mdp_blit_req *req, struct mdp_regs *regs)
{
if (req->src.format == req->dst.format)
return;
if (IS_RGB(req->src.format) && IS_YCRCB(req->dst.format)) {
regs->op |= PPP_OP_CONVERT_RGB2YCBCR | PPP_OP_CONVERT_ON;
} else if (IS_YCRCB(req->src.format) && IS_RGB(req->dst.format)) {
regs->op |= PPP_OP_CONVERT_YCBCR2RGB | PPP_OP_CONVERT_ON;
if (req->dst.format == MDP_RGB_565)
regs->op |= PPP_OP_CONVERT_MATRIX_SECONDARY;
}
}
#define GET_BIT_RANGE(value, high, low) \
(((1 << (high - low + 1)) - 1) & (value >> low))
static uint32_t transp_convert(struct mdp_blit_req *req)
{
uint32_t transp = 0;
if (req->src.format == MDP_RGB_565) {
/* pad each value to 8 bits by copying the high bits into the
* low end, convert RGB to RBG by switching low 2 components */
transp |= ((GET_BIT_RANGE(req->transp_mask, 15, 11) << 3) |
(GET_BIT_RANGE(req->transp_mask, 15, 13))) << 16;
transp |= ((GET_BIT_RANGE(req->transp_mask, 4, 0) << 3) |
(GET_BIT_RANGE(req->transp_mask, 4, 2))) << 8;
transp |= (GET_BIT_RANGE(req->transp_mask, 10, 5) << 2) |
(GET_BIT_RANGE(req->transp_mask, 10, 9));
} else {
/* convert RGB to RBG */
transp |= (GET_BIT_RANGE(req->transp_mask, 15, 8)) |
(GET_BIT_RANGE(req->transp_mask, 23, 16) << 16) |
(GET_BIT_RANGE(req->transp_mask, 7, 0) << 8);
}
return transp;
}
#undef GET_BIT_RANGE
static void blit_blend(struct mdp_blit_req *req, struct mdp_regs *regs)
{
/* TRANSP BLEND */
if (req->transp_mask != MDP_TRANSP_NOP) {
req->transp_mask = transp_convert(req);
if (req->alpha != MDP_ALPHA_NOP) {
/* use blended transparancy mode
* pixel = (src == transp) ? dst : blend
* blend is combo of blend_eq_sel and
* blend_alpha_sel */
regs->op |= PPP_OP_ROT_ON | PPP_OP_BLEND_ON |
PPP_OP_BLEND_ALPHA_BLEND_NORMAL |
PPP_OP_BLEND_CONSTANT_ALPHA |
PPP_BLEND_ALPHA_TRANSP;
} else {
/* simple transparancy mode
* pixel = (src == transp) ? dst : src */
regs->op |= PPP_OP_ROT_ON | PPP_OP_BLEND_ON |
PPP_OP_BLEND_SRCPIXEL_TRANSP;
}
}
req->alpha &= 0xff;
/* ALPHA BLEND */
if (HAS_ALPHA(req->src.format)) {
regs->op |= PPP_OP_ROT_ON | PPP_OP_BLEND_ON |
PPP_OP_BLEND_SRCPIXEL_ALPHA;
} else if (req->alpha < MDP_ALPHA_NOP) {
/* just blend by alpha */
regs->op |= PPP_OP_ROT_ON | PPP_OP_BLEND_ON |
PPP_OP_BLEND_ALPHA_BLEND_NORMAL |
PPP_OP_BLEND_CONSTANT_ALPHA;
}
regs->op |= bg_op_chroma[req->dst.format];
}
#define ONE_HALF (1LL << 32)
#define ONE (1LL << 33)
#define TWO (2LL << 33)
#define THREE (3LL << 33)
#define FRAC_MASK (ONE - 1)
#define INT_MASK (~FRAC_MASK)
static int scale_params(uint32_t dim_in, uint32_t dim_out, uint32_t origin,
uint32_t *phase_init, uint32_t *phase_step)
{
/* to improve precicsion calculations are done in U31.33 and converted
* to U3.29 at the end */
int64_t k1, k2, k3, k4, tmp;
uint64_t n, d, os, os_p, od, od_p, oreq;
unsigned rpa = 0;
int64_t ip64, delta;
if (dim_out % 3 == 0)
rpa = !(dim_in % (dim_out / 3));
n = ((uint64_t)dim_out) << 34;
d = dim_in;
if (!d)
return -1;
do_div(n, d);
k3 = (n + 1) >> 1;
if ((k3 >> 4) < (1LL << 27) || (k3 >> 4) > (1LL << 31)) {
DLOG("crap bad scale\n");
return -1;
}
n = ((uint64_t)dim_in) << 34;
d = (uint64_t)dim_out;
if (!d)
return -1;
do_div(n, d);
k1 = (n + 1) >> 1;
k2 = (k1 - ONE) >> 1;
*phase_init = (int)(k2 >> 4);
k4 = (k3 - ONE) >> 1;
if (rpa) {
os = ((uint64_t)origin << 33) - ONE_HALF;
tmp = (dim_out * os) + ONE_HALF;
if (!dim_in)
return -1;
do_div(tmp, dim_in);
od = tmp - ONE_HALF;
} else {
os = ((uint64_t)origin << 1) - 1;
od = (((k3 * os) >> 1) + k4);
}
od_p = od & INT_MASK;
if (od_p != od)
od_p += ONE;
if (rpa) {
tmp = (dim_in * od_p) + ONE_HALF;
if (!dim_in)
return -1;
do_div(tmp, dim_in);
os_p = tmp - ONE_HALF;
} else {
os_p = ((k1 * (od_p >> 33)) + k2);
}
oreq = (os_p & INT_MASK) - ONE;
ip64 = os_p - oreq;
delta = ((int64_t)(origin) << 33) - oreq;
ip64 -= delta;
/* limit to valid range before the left shift */
delta = (ip64 & (1LL << 63)) ? 4 : -4;
delta <<= 33;
while (abs((int)(ip64 >> 33)) > 4)
ip64 += delta;
*phase_init = (int)(ip64 >> 4);
*phase_step = (uint32_t)(k1 >> 4);
return 0;
}
static void load_scale_table(const struct mdp_info *mdp,
struct mdp_table_entry *table, int len)
{
int i;
for (i = 0; i < len; i++)
mdp_writel(mdp, table[i].val, table[i].reg);
}
enum {
IMG_LEFT,
IMG_RIGHT,
IMG_TOP,
IMG_BOTTOM,
};
static void get_edge_info(uint32_t src, uint32_t src_coord, uint32_t dst,
uint32_t *interp1, uint32_t *interp2,
uint32_t *repeat1, uint32_t *repeat2) {
if (src > 3 * dst) {
*interp1 = 0;
*interp2 = src - 1;
*repeat1 = 0;
*repeat2 = 0;
} else if (src == 3 * dst) {
*interp1 = 0;
*interp2 = src;
*repeat1 = 0;
*repeat2 = 1;
} else if (src > dst && src < 3 * dst) {
*interp1 = -1;
*interp2 = src;
*repeat1 = 1;
*repeat2 = 1;
} else if (src == dst) {
*interp1 = -1;
*interp2 = src + 1;
*repeat1 = 1;
*repeat2 = 2;
} else {
*interp1 = -2;
*interp2 = src + 1;
*repeat1 = 2;
*repeat2 = 2;
}
*interp1 += src_coord;
*interp2 += src_coord;
}
static int get_edge_cond(struct mdp_blit_req *req, struct mdp_regs *regs)
{
int32_t luma_interp[4];
int32_t luma_repeat[4];
int32_t chroma_interp[4];
int32_t chroma_bound[4];
int32_t chroma_repeat[4];
uint32_t dst_w, dst_h;
memset(&luma_interp, 0, sizeof(int32_t) * 4);
memset(&luma_repeat, 0, sizeof(int32_t) * 4);
memset(&chroma_interp, 0, sizeof(int32_t) * 4);
memset(&chroma_bound, 0, sizeof(int32_t) * 4);
memset(&chroma_repeat, 0, sizeof(int32_t) * 4);
regs->edge = 0;
if (req->flags & MDP_ROT_90) {
dst_w = req->dst_rect.h;
dst_h = req->dst_rect.w;
} else {
dst_w = req->dst_rect.w;
dst_h = req->dst_rect.h;
}
if (regs->op & (PPP_OP_SCALE_Y_ON | PPP_OP_SCALE_X_ON)) {
get_edge_info(req->src_rect.h, req->src_rect.y, dst_h,
&luma_interp[IMG_TOP], &luma_interp[IMG_BOTTOM],
&luma_repeat[IMG_TOP], &luma_repeat[IMG_BOTTOM]);
get_edge_info(req->src_rect.w, req->src_rect.x, dst_w,
&luma_interp[IMG_LEFT], &luma_interp[IMG_RIGHT],
&luma_repeat[IMG_LEFT], &luma_repeat[IMG_RIGHT]);
} else {
luma_interp[IMG_LEFT] = req->src_rect.x;
luma_interp[IMG_RIGHT] = req->src_rect.x + req->src_rect.w - 1;
luma_interp[IMG_TOP] = req->src_rect.y;
luma_interp[IMG_BOTTOM] = req->src_rect.y + req->src_rect.h - 1;
luma_repeat[IMG_LEFT] = 0;
luma_repeat[IMG_TOP] = 0;
luma_repeat[IMG_RIGHT] = 0;
luma_repeat[IMG_BOTTOM] = 0;
}
chroma_interp[IMG_LEFT] = luma_interp[IMG_LEFT];
chroma_interp[IMG_RIGHT] = luma_interp[IMG_RIGHT];
chroma_interp[IMG_TOP] = luma_interp[IMG_TOP];
chroma_interp[IMG_BOTTOM] = luma_interp[IMG_BOTTOM];
chroma_bound[IMG_LEFT] = req->src_rect.x;
chroma_bound[IMG_RIGHT] = req->src_rect.x + req->src_rect.w - 1;
chroma_bound[IMG_TOP] = req->src_rect.y;
chroma_bound[IMG_BOTTOM] = req->src_rect.y + req->src_rect.h - 1;
if (IS_YCRCB(req->src.format)) {
chroma_interp[IMG_LEFT] = chroma_interp[IMG_LEFT] >> 1;
chroma_interp[IMG_RIGHT] = (chroma_interp[IMG_RIGHT] + 1) >> 1;
chroma_bound[IMG_LEFT] = chroma_bound[IMG_LEFT] >> 1;
chroma_bound[IMG_RIGHT] = chroma_bound[IMG_RIGHT] >> 1;
}
if (req->src.format == MDP_Y_CBCR_H2V2 ||
req->src.format == MDP_Y_CRCB_H2V2) {
chroma_interp[IMG_TOP] = (chroma_interp[IMG_TOP] - 1) >> 1;
chroma_interp[IMG_BOTTOM] = (chroma_interp[IMG_BOTTOM] + 1)
>> 1;
chroma_bound[IMG_TOP] = (chroma_bound[IMG_TOP] + 1) >> 1;
chroma_bound[IMG_BOTTOM] = chroma_bound[IMG_BOTTOM] >> 1;
}
chroma_repeat[IMG_LEFT] = chroma_bound[IMG_LEFT] -
chroma_interp[IMG_LEFT];
chroma_repeat[IMG_RIGHT] = chroma_interp[IMG_RIGHT] -
chroma_bound[IMG_RIGHT];
chroma_repeat[IMG_TOP] = chroma_bound[IMG_TOP] -
chroma_interp[IMG_TOP];
chroma_repeat[IMG_BOTTOM] = chroma_interp[IMG_BOTTOM] -
chroma_bound[IMG_BOTTOM];
if (chroma_repeat[IMG_LEFT] < 0 || chroma_repeat[IMG_LEFT] > 3 ||
chroma_repeat[IMG_RIGHT] < 0 || chroma_repeat[IMG_RIGHT] > 3 ||
chroma_repeat[IMG_TOP] < 0 || chroma_repeat[IMG_TOP] > 3 ||
chroma_repeat[IMG_BOTTOM] < 0 || chroma_repeat[IMG_BOTTOM] > 3 ||
luma_repeat[IMG_LEFT] < 0 || luma_repeat[IMG_LEFT] > 3 ||
luma_repeat[IMG_RIGHT] < 0 || luma_repeat[IMG_RIGHT] > 3 ||
luma_repeat[IMG_TOP] < 0 || luma_repeat[IMG_TOP] > 3 ||
luma_repeat[IMG_BOTTOM] < 0 || luma_repeat[IMG_BOTTOM] > 3)
return -1;
regs->edge |= (chroma_repeat[IMG_LEFT] & 3) << MDP_LEFT_CHROMA;
regs->edge |= (chroma_repeat[IMG_RIGHT] & 3) << MDP_RIGHT_CHROMA;
regs->edge |= (chroma_repeat[IMG_TOP] & 3) << MDP_TOP_CHROMA;
regs->edge |= (chroma_repeat[IMG_BOTTOM] & 3) << MDP_BOTTOM_CHROMA;
regs->edge |= (luma_repeat[IMG_LEFT] & 3) << MDP_LEFT_LUMA;
regs->edge |= (luma_repeat[IMG_RIGHT] & 3) << MDP_RIGHT_LUMA;
regs->edge |= (luma_repeat[IMG_TOP] & 3) << MDP_TOP_LUMA;
regs->edge |= (luma_repeat[IMG_BOTTOM] & 3) << MDP_BOTTOM_LUMA;
return 0;
}
static int blit_scale(const struct mdp_info *mdp, struct mdp_blit_req *req,
struct mdp_regs *regs)
{
uint32_t phase_init_x, phase_init_y, phase_step_x, phase_step_y;
uint32_t scale_factor_x, scale_factor_y;
uint32_t downscale;
uint32_t dst_w, dst_h;
if (req->flags & MDP_ROT_90) {
dst_w = req->dst_rect.h;
dst_h = req->dst_rect.w;
} else {
dst_w = req->dst_rect.w;
dst_h = req->dst_rect.h;
}
if ((req->src_rect.w == dst_w) && (req->src_rect.h == dst_h) &&
!(req->flags & MDP_BLUR)) {
regs->phasex_init = 0;
regs->phasey_init = 0;
regs->phasex_step = 0;
regs->phasey_step = 0;
return 0;
}
if (scale_params(req->src_rect.w, dst_w, 1, &phase_init_x,
&phase_step_x) ||
scale_params(req->src_rect.h, dst_h, 1, &phase_init_y,
&phase_step_y))
return -1;
scale_factor_x = (dst_w * 10) / req->src_rect.w;
scale_factor_y = (dst_h * 10) / req->src_rect.h;
if (scale_factor_x > 8)
downscale = MDP_DOWNSCALE_PT8TO1;
else if (scale_factor_x > 6)
downscale = MDP_DOWNSCALE_PT6TOPT8;
else if (scale_factor_x > 4)
downscale = MDP_DOWNSCALE_PT4TOPT6;
else
downscale = MDP_DOWNSCALE_PT2TOPT4;
if (downscale != downscale_x_table) {
load_scale_table(mdp, mdp_downscale_x_table[downscale], 64);
downscale_x_table = downscale;
}
if (scale_factor_y > 8)
downscale = MDP_DOWNSCALE_PT8TO1;
else if (scale_factor_y > 6)
downscale = MDP_DOWNSCALE_PT6TOPT8;
else if (scale_factor_y > 4)
downscale = MDP_DOWNSCALE_PT4TOPT6;
else
downscale = MDP_DOWNSCALE_PT2TOPT4;
if (downscale != downscale_y_table) {
load_scale_table(mdp, mdp_downscale_y_table[downscale], 64);
downscale_y_table = downscale;
}
regs->phasex_init = phase_init_x;
regs->phasey_init = phase_init_y;
regs->phasex_step = phase_step_x;
regs->phasey_step = phase_step_y;
regs->op |= (PPP_OP_SCALE_Y_ON | PPP_OP_SCALE_X_ON);
return 0;
}
static void blit_blur(const struct mdp_info *mdp, struct mdp_blit_req *req,
struct mdp_regs *regs)
{
if (!(req->flags & MDP_BLUR))
return;
if (!(downscale_x_table == MDP_DOWNSCALE_BLUR &&
downscale_y_table == MDP_DOWNSCALE_BLUR)) {
load_scale_table(mdp, mdp_gaussian_blur_table, 128);
downscale_x_table = MDP_DOWNSCALE_BLUR;
downscale_y_table = MDP_DOWNSCALE_BLUR;
}
regs->op |= (PPP_OP_SCALE_Y_ON | PPP_OP_SCALE_X_ON);
}
#define IMG_LEN(rect_h, w, rect_w, bpp) (((rect_h) * w) * bpp)
#define Y_TO_CRCB_RATIO(format) \
((format == MDP_Y_CBCR_H2V2 || format == MDP_Y_CRCB_H2V2) ? 2 :\
(format == MDP_Y_CBCR_H2V1 || format == MDP_Y_CRCB_H2V1) ? 1 : 1)
static void get_len(struct mdp_img *img, struct mdp_rect *rect, uint32_t bpp,
uint32_t *len0, uint32_t *len1)
{
*len0 = IMG_LEN(rect->h, img->width, rect->w, bpp);
if (IS_PSEUDOPLNR(img->format))
*len1 = *len0/Y_TO_CRCB_RATIO(img->format);
else
*len1 = 0;
}
static int valid_src_dst(unsigned long src_start, unsigned long src_len,
unsigned long dst_start, unsigned long dst_len,
struct mdp_blit_req *req, struct mdp_regs *regs)
{
unsigned long src_min_ok = src_start;
unsigned long src_max_ok = src_start + src_len;
unsigned long dst_min_ok = dst_start;
unsigned long dst_max_ok = dst_start + dst_len;
uint32_t src0_len, src1_len, dst0_len, dst1_len;
get_len(&req->src, &req->src_rect, regs->src_bpp, &src0_len,
&src1_len);
get_len(&req->dst, &req->dst_rect, regs->dst_bpp, &dst0_len,
&dst1_len);
if (regs->src0 < src_min_ok || regs->src0 > src_max_ok ||
regs->src0 + src0_len > src_max_ok) {
DLOG("invalid_src %x %x %lx %lx\n", regs->src0,
src0_len, src_min_ok, src_max_ok);
return 0;
}
if (regs->src_cfg & PPP_SRC_PLANE_PSEUDOPLNR) {
if (regs->src1 < src_min_ok || regs->src1 > src_max_ok ||
regs->src1 + src1_len > src_max_ok) {
DLOG("invalid_src1");
return 0;
}
}
if (regs->dst0 < dst_min_ok || regs->dst0 > dst_max_ok ||
regs->dst0 + dst0_len > dst_max_ok) {
DLOG("invalid_dst");
return 0;
}
if (regs->dst_cfg & PPP_SRC_PLANE_PSEUDOPLNR) {
if (regs->dst1 < dst_min_ok || regs->dst1 > dst_max_ok ||
regs->dst1 + dst1_len > dst_max_ok) {
DLOG("invalid_dst1");
return 0;
}
}
return 1;
}
static void flush_imgs(struct mdp_blit_req *req, struct mdp_regs *regs,
struct file *src_file, struct file *dst_file)
{
}
static void get_chroma_addr(struct mdp_img *img, struct mdp_rect *rect,
uint32_t base, uint32_t bpp, uint32_t cfg,
uint32_t *addr, uint32_t *ystride)
{
uint32_t compress_v = Y_TO_CRCB_RATIO(img->format);
uint32_t compress_h = 2;
uint32_t offset;
if (IS_PSEUDOPLNR(img->format)) {
offset = (rect->x / compress_h) * compress_h;
offset += rect->y == 0 ? 0 :
((rect->y + 1) / compress_v) * img->width;
*addr = base + (img->width * img->height * bpp);
*addr += offset * bpp;
*ystride |= *ystride << 16;
} else {
*addr = 0;
}
}
static int send_blit(const struct mdp_info *mdp, struct mdp_blit_req *req,
struct mdp_regs *regs, struct file *src_file,
struct file *dst_file)
{
mdp_writel(mdp, 1, 0x060);
mdp_writel(mdp, regs->src_rect, PPP_ADDR_SRC_ROI);
mdp_writel(mdp, regs->src0, PPP_ADDR_SRC0);
mdp_writel(mdp, regs->src1, PPP_ADDR_SRC1);
mdp_writel(mdp, regs->src_ystride, PPP_ADDR_SRC_YSTRIDE);
mdp_writel(mdp, regs->src_cfg, PPP_ADDR_SRC_CFG);
mdp_writel(mdp, regs->src_pack, PPP_ADDR_SRC_PACK_PATTERN);
mdp_writel(mdp, regs->op, PPP_ADDR_OPERATION);
mdp_writel(mdp, regs->phasex_init, PPP_ADDR_PHASEX_INIT);
mdp_writel(mdp, regs->phasey_init, PPP_ADDR_PHASEY_INIT);
mdp_writel(mdp, regs->phasex_step, PPP_ADDR_PHASEX_STEP);
mdp_writel(mdp, regs->phasey_step, PPP_ADDR_PHASEY_STEP);
mdp_writel(mdp, (req->alpha << 24) | (req->transp_mask & 0xffffff),
PPP_ADDR_ALPHA_TRANSP);
mdp_writel(mdp, regs->dst_cfg, PPP_ADDR_DST_CFG);
mdp_writel(mdp, regs->dst_pack, PPP_ADDR_DST_PACK_PATTERN);
mdp_writel(mdp, regs->dst_rect, PPP_ADDR_DST_ROI);
mdp_writel(mdp, regs->dst0, PPP_ADDR_DST0);
mdp_writel(mdp, regs->dst1, PPP_ADDR_DST1);
mdp_writel(mdp, regs->dst_ystride, PPP_ADDR_DST_YSTRIDE);
mdp_writel(mdp, regs->edge, PPP_ADDR_EDGE);
if (regs->op & PPP_OP_BLEND_ON) {
mdp_writel(mdp, regs->dst0, PPP_ADDR_BG0);
mdp_writel(mdp, regs->dst1, PPP_ADDR_BG1);
mdp_writel(mdp, regs->dst_ystride, PPP_ADDR_BG_YSTRIDE);
mdp_writel(mdp, src_img_cfg[req->dst.format], PPP_ADDR_BG_CFG);
mdp_writel(mdp, pack_pattern[req->dst.format],
PPP_ADDR_BG_PACK_PATTERN);
}
flush_imgs(req, regs, src_file, dst_file);
mdp_writel(mdp, 0x1000, MDP_DISPLAY0_START);
return 0;
}
int mdp_ppp_blit(const struct mdp_info *mdp, struct mdp_blit_req *req,
struct file *src_file, unsigned long src_start, unsigned long src_len,
struct file *dst_file, unsigned long dst_start, unsigned long dst_len)
{
struct mdp_regs regs = {0};
if (unlikely(req->src.format >= MDP_IMGTYPE_LIMIT ||
req->dst.format >= MDP_IMGTYPE_LIMIT)) {
printk(KERN_ERR "mpd_ppp: img is of wrong format\n");
return -EINVAL;
}
if (unlikely(req->src_rect.x > req->src.width ||
req->src_rect.y > req->src.height ||
req->dst_rect.x > req->dst.width ||
req->dst_rect.y > req->dst.height)) {
printk(KERN_ERR "mpd_ppp: img rect is outside of img!\n");
return -EINVAL;
}
/* set the src image configuration */
regs.src_cfg = src_img_cfg[req->src.format];
regs.src_cfg |= (req->src_rect.x & 0x1) ? PPP_SRC_BPP_ROI_ODD_X : 0;
regs.src_cfg |= (req->src_rect.y & 0x1) ? PPP_SRC_BPP_ROI_ODD_Y : 0;
regs.src_rect = (req->src_rect.h << 16) | req->src_rect.w;
regs.src_pack = pack_pattern[req->src.format];
/* set the dest image configuration */
regs.dst_cfg = dst_img_cfg[req->dst.format] | PPP_DST_OUT_SEL_AXI;
regs.dst_rect = (req->dst_rect.h << 16) | req->dst_rect.w;
regs.dst_pack = pack_pattern[req->dst.format];
/* set src, bpp, start pixel and ystride */
regs.src_bpp = bytes_per_pixel[req->src.format];
regs.src0 = src_start + req->src.offset;
regs.src_ystride = req->src.width * regs.src_bpp;
get_chroma_addr(&req->src, &req->src_rect, regs.src0, regs.src_bpp,
regs.src_cfg, ®s.src1, ®s.src_ystride);
regs.src0 += (req->src_rect.x + (req->src_rect.y * req->src.width)) *
regs.src_bpp;
/* set dst, bpp, start pixel and ystride */
regs.dst_bpp = bytes_per_pixel[req->dst.format];
regs.dst0 = dst_start + req->dst.offset;
regs.dst_ystride = req->dst.width * regs.dst_bpp;
get_chroma_addr(&req->dst, &req->dst_rect, regs.dst0, regs.dst_bpp,
regs.dst_cfg, ®s.dst1, ®s.dst_ystride);
regs.dst0 += (req->dst_rect.x + (req->dst_rect.y * req->dst.width)) *
regs.dst_bpp;
if (!valid_src_dst(src_start, src_len, dst_start, dst_len, req,
®s)) {
printk(KERN_ERR "mpd_ppp: final src or dst location is "
"invalid, are you trying to make an image too large "
"or to place it outside the screen?\n");
return -EINVAL;
}
/* set up operation register */
regs.op = 0;
blit_rotate(req, ®s);
blit_convert(req, ®s);
if (req->flags & MDP_DITHER)
regs.op |= PPP_OP_DITHER_EN;
blit_blend(req, ®s);
if (blit_scale(mdp, req, ®s)) {
printk(KERN_ERR "mpd_ppp: error computing scale for img.\n");
return -EINVAL;
}
blit_blur(mdp, req, ®s);
regs.op |= dst_op_chroma[req->dst.format] |
src_op_chroma[req->src.format];
/* if the image is YCRYCB, the x and w must be even */
if (unlikely(req->src.format == MDP_YCRYCB_H2V1)) {
req->src_rect.x = req->src_rect.x & (~0x1);
req->src_rect.w = req->src_rect.w & (~0x1);
req->dst_rect.x = req->dst_rect.x & (~0x1);
req->dst_rect.w = req->dst_rect.w & (~0x1);
}
if (get_edge_cond(req, ®s))
return -EINVAL;
send_blit(mdp, req, ®s, src_file, dst_file);
return 0;
}
| gpl-2.0 |
ohadbc/hwspinlock-next | drivers/gpu/drm/radeon/cayman_blit_shaders.c | 3070 | 8297 | /*
* Copyright 2010 Advanced Micro Devices, Inc.
*
* 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 (including the next
* paragraph) 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 COPYRIGHT HOLDER(S) AND/OR ITS SUPPLIERS 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.
*
* Authors:
* Alex Deucher <alexander.deucher@amd.com>
*/
#include <linux/types.h>
#include <linux/kernel.h>
/*
* evergreen cards need to use the 3D engine to blit data which requires
* quite a bit of hw state setup. Rather than pull the whole 3D driver
* (which normally generates the 3D state) into the DRM, we opt to use
* statically generated state tables. The regsiter state and shaders
* were hand generated to support blitting functionality. See the 3D
* driver or documentation for descriptions of the registers and
* shader instructions.
*/
const u32 cayman_default_state[] =
{
0xc0066900,
0x00000000,
0x00000060, /* DB_RENDER_CONTROL */
0x00000000, /* DB_COUNT_CONTROL */
0x00000000, /* DB_DEPTH_VIEW */
0x0000002a, /* DB_RENDER_OVERRIDE */
0x00000000, /* DB_RENDER_OVERRIDE2 */
0x00000000, /* DB_HTILE_DATA_BASE */
0xc0026900,
0x0000000a,
0x00000000, /* DB_STENCIL_CLEAR */
0x00000000, /* DB_DEPTH_CLEAR */
0xc0036900,
0x0000000f,
0x00000000, /* DB_DEPTH_INFO */
0x00000000, /* DB_Z_INFO */
0x00000000, /* DB_STENCIL_INFO */
0xc0016900,
0x00000080,
0x00000000, /* PA_SC_WINDOW_OFFSET */
0xc00d6900,
0x00000083,
0x0000ffff, /* PA_SC_CLIPRECT_RULE */
0x00000000, /* PA_SC_CLIPRECT_0_TL */
0x20002000, /* PA_SC_CLIPRECT_0_BR */
0x00000000,
0x20002000,
0x00000000,
0x20002000,
0x00000000,
0x20002000,
0xaaaaaaaa, /* PA_SC_EDGERULE */
0x00000000, /* PA_SU_HARDWARE_SCREEN_OFFSET */
0x0000000f, /* CB_TARGET_MASK */
0x0000000f, /* CB_SHADER_MASK */
0xc0226900,
0x00000094,
0x80000000, /* PA_SC_VPORT_SCISSOR_0_TL */
0x20002000, /* PA_SC_VPORT_SCISSOR_0_BR */
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x80000000,
0x20002000,
0x00000000, /* PA_SC_VPORT_ZMIN_0 */
0x3f800000, /* PA_SC_VPORT_ZMAX_0 */
0xc0016900,
0x000000d4,
0x00000000, /* SX_MISC */
0xc0026900,
0x000000d9,
0x00000000, /* CP_RINGID */
0x00000000, /* CP_VMID */
0xc0096900,
0x00000100,
0x00ffffff, /* VGT_MAX_VTX_INDX */
0x00000000, /* VGT_MIN_VTX_INDX */
0x00000000, /* VGT_INDX_OFFSET */
0x00000000, /* VGT_MULTI_PRIM_IB_RESET_INDX */
0x00000000, /* SX_ALPHA_TEST_CONTROL */
0x00000000, /* CB_BLEND_RED */
0x00000000, /* CB_BLEND_GREEN */
0x00000000, /* CB_BLEND_BLUE */
0x00000000, /* CB_BLEND_ALPHA */
0xc0016900,
0x00000187,
0x00000100, /* SPI_VS_OUT_ID_0 */
0xc0026900,
0x00000191,
0x00000100, /* SPI_PS_INPUT_CNTL_0 */
0x00000101, /* SPI_PS_INPUT_CNTL_1 */
0xc0016900,
0x000001b1,
0x00000000, /* SPI_VS_OUT_CONFIG */
0xc0106900,
0x000001b3,
0x20000001, /* SPI_PS_IN_CONTROL_0 */
0x00000000, /* SPI_PS_IN_CONTROL_1 */
0x00000000, /* SPI_INTERP_CONTROL_0 */
0x00000000, /* SPI_INPUT_Z */
0x00000000, /* SPI_FOG_CNTL */
0x00100000, /* SPI_BARYC_CNTL */
0x00000000, /* SPI_PS_IN_CONTROL_2 */
0x00000000, /* SPI_COMPUTE_INPUT_CNTL */
0x00000000, /* SPI_COMPUTE_NUM_THREAD_X */
0x00000000, /* SPI_COMPUTE_NUM_THREAD_Y */
0x00000000, /* SPI_COMPUTE_NUM_THREAD_Z */
0x00000000, /* SPI_GPR_MGMT */
0x00000000, /* SPI_LDS_MGMT */
0x00000000, /* SPI_STACK_MGMT */
0x00000000, /* SPI_WAVE_MGMT_1 */
0x00000000, /* SPI_WAVE_MGMT_2 */
0xc0016900,
0x000001e0,
0x00000000, /* CB_BLEND0_CONTROL */
0xc00e6900,
0x00000200,
0x00000000, /* DB_DEPTH_CONTROL */
0x00000000, /* DB_EQAA */
0x00cc0010, /* CB_COLOR_CONTROL */
0x00000210, /* DB_SHADER_CONTROL */
0x00010000, /* PA_CL_CLIP_CNTL */
0x00000004, /* PA_SU_SC_MODE_CNTL */
0x00000100, /* PA_CL_VTE_CNTL */
0x00000000, /* PA_CL_VS_OUT_CNTL */
0x00000000, /* PA_CL_NANINF_CNTL */
0x00000000, /* PA_SU_LINE_STIPPLE_CNTL */
0x00000000, /* PA_SU_LINE_STIPPLE_SCALE */
0x00000000, /* PA_SU_PRIM_FILTER_CNTL */
0x00000000, /* */
0x00000000, /* */
0xc0026900,
0x00000229,
0x00000000, /* SQ_PGM_START_FS */
0x00000000,
0xc0016900,
0x0000023b,
0x00000000, /* SQ_LDS_ALLOC_PS */
0xc0066900,
0x00000240,
0x00000000, /* SQ_ESGS_RING_ITEMSIZE */
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0xc0046900,
0x00000247,
0x00000000, /* SQ_GS_VERT_ITEMSIZE */
0x00000000,
0x00000000,
0x00000000,
0xc0116900,
0x00000280,
0x00000000, /* PA_SU_POINT_SIZE */
0x00000000, /* PA_SU_POINT_MINMAX */
0x00000008, /* PA_SU_LINE_CNTL */
0x00000000, /* PA_SC_LINE_STIPPLE */
0x00000000, /* VGT_OUTPUT_PATH_CNTL */
0x00000000, /* VGT_HOS_CNTL */
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000, /* VGT_GS_MODE */
0xc0026900,
0x00000292,
0x00000000, /* PA_SC_MODE_CNTL_0 */
0x00000000, /* PA_SC_MODE_CNTL_1 */
0xc0016900,
0x000002a1,
0x00000000, /* VGT_PRIMITIVEID_EN */
0xc0016900,
0x000002a5,
0x00000000, /* VGT_MULTI_PRIM_IB_RESET_EN */
0xc0026900,
0x000002a8,
0x00000000, /* VGT_INSTANCE_STEP_RATE_0 */
0x00000000,
0xc0026900,
0x000002ad,
0x00000000, /* VGT_REUSE_OFF */
0x00000000,
0xc0016900,
0x000002d5,
0x00000000, /* VGT_SHADER_STAGES_EN */
0xc0016900,
0x000002dc,
0x0000aa00, /* DB_ALPHA_TO_MASK */
0xc0066900,
0x000002de,
0x00000000, /* PA_SU_POLY_OFFSET_DB_FMT_CNTL */
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0xc0026900,
0x000002e5,
0x00000000, /* VGT_STRMOUT_CONFIG */
0x00000000,
0xc01b6900,
0x000002f5,
0x76543210, /* PA_SC_CENTROID_PRIORITY_0 */
0xfedcba98, /* PA_SC_CENTROID_PRIORITY_1 */
0x00000000, /* PA_SC_LINE_CNTL */
0x00000000, /* PA_SC_AA_CONFIG */
0x00000005, /* PA_SU_VTX_CNTL */
0x3f800000, /* PA_CL_GB_VERT_CLIP_ADJ */
0x3f800000, /* PA_CL_GB_VERT_DISC_ADJ */
0x3f800000, /* PA_CL_GB_HORZ_CLIP_ADJ */
0x3f800000, /* PA_CL_GB_HORZ_DISC_ADJ */
0x00000000, /* PA_SC_AA_SAMPLE_LOCS_PIXEL_X0Y0_0 */
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0xffffffff, /* PA_SC_AA_MASK_X0Y0_X1Y0 */
0xffffffff,
0xc0026900,
0x00000316,
0x0000000e, /* VGT_VERTEX_REUSE_BLOCK_CNTL */
0x00000010, /* */
};
const u32 cayman_vs[] =
{
0x00000004,
0x80400400,
0x0000a03c,
0x95000688,
0x00004000,
0x15000688,
0x00000000,
0x88000000,
0x04000000,
0x67961001,
#ifdef __BIG_ENDIAN
0x00020000,
#else
0x00000000,
#endif
0x00000000,
0x04000000,
0x67961000,
#ifdef __BIG_ENDIAN
0x00020008,
#else
0x00000008,
#endif
0x00000000,
};
const u32 cayman_ps[] =
{
0x00000004,
0xa00c0000,
0x00000008,
0x80400000,
0x00000000,
0x95000688,
0x00000000,
0x88000000,
0x00380400,
0x00146b10,
0x00380000,
0x20146b10,
0x00380400,
0x40146b00,
0x80380000,
0x60146b00,
0x00000010,
0x000d1000,
0xb0800000,
0x00000000,
};
const u32 cayman_ps_size = ARRAY_SIZE(cayman_ps);
const u32 cayman_vs_size = ARRAY_SIZE(cayman_vs);
const u32 cayman_default_size = ARRAY_SIZE(cayman_default_state);
| gpl-2.0 |
TheBootloader/android_kernel_samsung_msm8930-common | drivers/target/target_core_fabric_configfs.c | 3326 | 35082 | /*******************************************************************************
* Filename: target_core_fabric_configfs.c
*
* This file contains generic fabric module configfs infrastructure for
* TCM v4.x code
*
* Copyright (c) 2010,2011 Rising Tide Systems
* Copyright (c) 2010,2011 Linux-iSCSI.org
*
* Copyright (c) Nicholas A. Bellinger <nab@linux-iscsi.org>
*
* 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.
****************************************************************************/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <generated/utsrelease.h>
#include <linux/utsname.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/namei.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/delay.h>
#include <linux/unistd.h>
#include <linux/string.h>
#include <linux/syscalls.h>
#include <linux/configfs.h>
#include <target/target_core_base.h>
#include <target/target_core_fabric.h>
#include <target/target_core_fabric_configfs.h>
#include <target/target_core_configfs.h>
#include <target/configfs_macros.h>
#include "target_core_internal.h"
#include "target_core_alua.h"
#include "target_core_pr.h"
#define TF_CIT_SETUP(_name, _item_ops, _group_ops, _attrs) \
static void target_fabric_setup_##_name##_cit(struct target_fabric_configfs *tf) \
{ \
struct target_fabric_configfs_template *tfc = &tf->tf_cit_tmpl; \
struct config_item_type *cit = &tfc->tfc_##_name##_cit; \
\
cit->ct_item_ops = _item_ops; \
cit->ct_group_ops = _group_ops; \
cit->ct_attrs = _attrs; \
cit->ct_owner = tf->tf_module; \
pr_debug("Setup generic %s\n", __stringify(_name)); \
}
/* Start of tfc_tpg_mappedlun_cit */
static int target_fabric_mappedlun_link(
struct config_item *lun_acl_ci,
struct config_item *lun_ci)
{
struct se_dev_entry *deve;
struct se_lun *lun = container_of(to_config_group(lun_ci),
struct se_lun, lun_group);
struct se_lun_acl *lacl = container_of(to_config_group(lun_acl_ci),
struct se_lun_acl, se_lun_group);
struct se_portal_group *se_tpg;
struct config_item *nacl_ci, *tpg_ci, *tpg_ci_s, *wwn_ci, *wwn_ci_s;
int ret = 0, lun_access;
/*
* Ensure that the source port exists
*/
if (!lun->lun_sep || !lun->lun_sep->sep_tpg) {
pr_err("Source se_lun->lun_sep or lun->lun_sep->sep"
"_tpg does not exist\n");
return -EINVAL;
}
se_tpg = lun->lun_sep->sep_tpg;
nacl_ci = &lun_acl_ci->ci_parent->ci_group->cg_item;
tpg_ci = &nacl_ci->ci_group->cg_item;
wwn_ci = &tpg_ci->ci_group->cg_item;
tpg_ci_s = &lun_ci->ci_parent->ci_group->cg_item;
wwn_ci_s = &tpg_ci_s->ci_group->cg_item;
/*
* Make sure the SymLink is going to the same $FABRIC/$WWN/tpgt_$TPGT
*/
if (strcmp(config_item_name(wwn_ci), config_item_name(wwn_ci_s))) {
pr_err("Illegal Initiator ACL SymLink outside of %s\n",
config_item_name(wwn_ci));
return -EINVAL;
}
if (strcmp(config_item_name(tpg_ci), config_item_name(tpg_ci_s))) {
pr_err("Illegal Initiator ACL Symlink outside of %s"
" TPGT: %s\n", config_item_name(wwn_ci),
config_item_name(tpg_ci));
return -EINVAL;
}
/*
* If this struct se_node_acl was dynamically generated with
* tpg_1/attrib/generate_node_acls=1, use the existing deve->lun_flags,
* which be will write protected (READ-ONLY) when
* tpg_1/attrib/demo_mode_write_protect=1
*/
spin_lock_irq(&lacl->se_lun_nacl->device_list_lock);
deve = lacl->se_lun_nacl->device_list[lacl->mapped_lun];
if (deve->lun_flags & TRANSPORT_LUNFLAGS_INITIATOR_ACCESS)
lun_access = deve->lun_flags;
else
lun_access =
(se_tpg->se_tpg_tfo->tpg_check_prod_mode_write_protect(
se_tpg)) ? TRANSPORT_LUNFLAGS_READ_ONLY :
TRANSPORT_LUNFLAGS_READ_WRITE;
spin_unlock_irq(&lacl->se_lun_nacl->device_list_lock);
/*
* Determine the actual mapped LUN value user wants..
*
* This value is what the SCSI Initiator actually sees the
* iscsi/$IQN/$TPGT/lun/lun_* as on their SCSI Initiator Ports.
*/
ret = core_dev_add_initiator_node_lun_acl(se_tpg, lacl,
lun->unpacked_lun, lun_access);
return (ret < 0) ? -EINVAL : 0;
}
static int target_fabric_mappedlun_unlink(
struct config_item *lun_acl_ci,
struct config_item *lun_ci)
{
struct se_lun *lun;
struct se_lun_acl *lacl = container_of(to_config_group(lun_acl_ci),
struct se_lun_acl, se_lun_group);
struct se_node_acl *nacl = lacl->se_lun_nacl;
struct se_dev_entry *deve = nacl->device_list[lacl->mapped_lun];
struct se_portal_group *se_tpg;
/*
* Determine if the underlying MappedLUN has already been released..
*/
if (!deve->se_lun)
return 0;
lun = container_of(to_config_group(lun_ci), struct se_lun, lun_group);
se_tpg = lun->lun_sep->sep_tpg;
core_dev_del_initiator_node_lun_acl(se_tpg, lun, lacl);
return 0;
}
CONFIGFS_EATTR_STRUCT(target_fabric_mappedlun, se_lun_acl);
#define TCM_MAPPEDLUN_ATTR(_name, _mode) \
static struct target_fabric_mappedlun_attribute target_fabric_mappedlun_##_name = \
__CONFIGFS_EATTR(_name, _mode, \
target_fabric_mappedlun_show_##_name, \
target_fabric_mappedlun_store_##_name);
static ssize_t target_fabric_mappedlun_show_write_protect(
struct se_lun_acl *lacl,
char *page)
{
struct se_node_acl *se_nacl = lacl->se_lun_nacl;
struct se_dev_entry *deve;
ssize_t len;
spin_lock_irq(&se_nacl->device_list_lock);
deve = se_nacl->device_list[lacl->mapped_lun];
len = sprintf(page, "%d\n",
(deve->lun_flags & TRANSPORT_LUNFLAGS_READ_ONLY) ?
1 : 0);
spin_unlock_irq(&se_nacl->device_list_lock);
return len;
}
static ssize_t target_fabric_mappedlun_store_write_protect(
struct se_lun_acl *lacl,
const char *page,
size_t count)
{
struct se_node_acl *se_nacl = lacl->se_lun_nacl;
struct se_portal_group *se_tpg = se_nacl->se_tpg;
unsigned long op;
if (strict_strtoul(page, 0, &op))
return -EINVAL;
if ((op != 1) && (op != 0))
return -EINVAL;
core_update_device_list_access(lacl->mapped_lun, (op) ?
TRANSPORT_LUNFLAGS_READ_ONLY :
TRANSPORT_LUNFLAGS_READ_WRITE,
lacl->se_lun_nacl);
pr_debug("%s_ConfigFS: Changed Initiator ACL: %s"
" Mapped LUN: %u Write Protect bit to %s\n",
se_tpg->se_tpg_tfo->get_fabric_name(),
lacl->initiatorname, lacl->mapped_lun, (op) ? "ON" : "OFF");
return count;
}
TCM_MAPPEDLUN_ATTR(write_protect, S_IRUGO | S_IWUSR);
CONFIGFS_EATTR_OPS(target_fabric_mappedlun, se_lun_acl, se_lun_group);
static void target_fabric_mappedlun_release(struct config_item *item)
{
struct se_lun_acl *lacl = container_of(to_config_group(item),
struct se_lun_acl, se_lun_group);
struct se_portal_group *se_tpg = lacl->se_lun_nacl->se_tpg;
core_dev_free_initiator_node_lun_acl(se_tpg, lacl);
}
static struct configfs_attribute *target_fabric_mappedlun_attrs[] = {
&target_fabric_mappedlun_write_protect.attr,
NULL,
};
static struct configfs_item_operations target_fabric_mappedlun_item_ops = {
.release = target_fabric_mappedlun_release,
.show_attribute = target_fabric_mappedlun_attr_show,
.store_attribute = target_fabric_mappedlun_attr_store,
.allow_link = target_fabric_mappedlun_link,
.drop_link = target_fabric_mappedlun_unlink,
};
TF_CIT_SETUP(tpg_mappedlun, &target_fabric_mappedlun_item_ops, NULL,
target_fabric_mappedlun_attrs);
/* End of tfc_tpg_mappedlun_cit */
/* Start of tfc_tpg_mappedlun_port_cit */
static struct config_group *target_core_mappedlun_stat_mkdir(
struct config_group *group,
const char *name)
{
return ERR_PTR(-ENOSYS);
}
static void target_core_mappedlun_stat_rmdir(
struct config_group *group,
struct config_item *item)
{
return;
}
static struct configfs_group_operations target_fabric_mappedlun_stat_group_ops = {
.make_group = target_core_mappedlun_stat_mkdir,
.drop_item = target_core_mappedlun_stat_rmdir,
};
TF_CIT_SETUP(tpg_mappedlun_stat, NULL, &target_fabric_mappedlun_stat_group_ops,
NULL);
/* End of tfc_tpg_mappedlun_port_cit */
/* Start of tfc_tpg_nacl_attrib_cit */
CONFIGFS_EATTR_OPS(target_fabric_nacl_attrib, se_node_acl, acl_attrib_group);
static struct configfs_item_operations target_fabric_nacl_attrib_item_ops = {
.show_attribute = target_fabric_nacl_attrib_attr_show,
.store_attribute = target_fabric_nacl_attrib_attr_store,
};
TF_CIT_SETUP(tpg_nacl_attrib, &target_fabric_nacl_attrib_item_ops, NULL, NULL);
/* End of tfc_tpg_nacl_attrib_cit */
/* Start of tfc_tpg_nacl_auth_cit */
CONFIGFS_EATTR_OPS(target_fabric_nacl_auth, se_node_acl, acl_auth_group);
static struct configfs_item_operations target_fabric_nacl_auth_item_ops = {
.show_attribute = target_fabric_nacl_auth_attr_show,
.store_attribute = target_fabric_nacl_auth_attr_store,
};
TF_CIT_SETUP(tpg_nacl_auth, &target_fabric_nacl_auth_item_ops, NULL, NULL);
/* End of tfc_tpg_nacl_auth_cit */
/* Start of tfc_tpg_nacl_param_cit */
CONFIGFS_EATTR_OPS(target_fabric_nacl_param, se_node_acl, acl_param_group);
static struct configfs_item_operations target_fabric_nacl_param_item_ops = {
.show_attribute = target_fabric_nacl_param_attr_show,
.store_attribute = target_fabric_nacl_param_attr_store,
};
TF_CIT_SETUP(tpg_nacl_param, &target_fabric_nacl_param_item_ops, NULL, NULL);
/* End of tfc_tpg_nacl_param_cit */
/* Start of tfc_tpg_nacl_base_cit */
CONFIGFS_EATTR_OPS(target_fabric_nacl_base, se_node_acl, acl_group);
static struct config_group *target_fabric_make_mappedlun(
struct config_group *group,
const char *name)
{
struct se_node_acl *se_nacl = container_of(group,
struct se_node_acl, acl_group);
struct se_portal_group *se_tpg = se_nacl->se_tpg;
struct target_fabric_configfs *tf = se_tpg->se_tpg_wwn->wwn_tf;
struct se_lun_acl *lacl;
struct config_item *acl_ci;
struct config_group *lacl_cg = NULL, *ml_stat_grp = NULL;
char *buf;
unsigned long mapped_lun;
int ret = 0;
acl_ci = &group->cg_item;
if (!acl_ci) {
pr_err("Unable to locatel acl_ci\n");
return NULL;
}
buf = kzalloc(strlen(name) + 1, GFP_KERNEL);
if (!buf) {
pr_err("Unable to allocate memory for name buf\n");
return ERR_PTR(-ENOMEM);
}
snprintf(buf, strlen(name) + 1, "%s", name);
/*
* Make sure user is creating iscsi/$IQN/$TPGT/acls/$INITIATOR/lun_$ID.
*/
if (strstr(buf, "lun_") != buf) {
pr_err("Unable to locate \"lun_\" from buf: %s"
" name: %s\n", buf, name);
ret = -EINVAL;
goto out;
}
/*
* Determine the Mapped LUN value. This is what the SCSI Initiator
* Port will actually see.
*/
if (strict_strtoul(buf + 4, 0, &mapped_lun) || mapped_lun > UINT_MAX) {
ret = -EINVAL;
goto out;
}
lacl = core_dev_init_initiator_node_lun_acl(se_tpg, mapped_lun,
config_item_name(acl_ci), &ret);
if (!lacl) {
ret = -EINVAL;
goto out;
}
lacl_cg = &lacl->se_lun_group;
lacl_cg->default_groups = kzalloc(sizeof(struct config_group) * 2,
GFP_KERNEL);
if (!lacl_cg->default_groups) {
pr_err("Unable to allocate lacl_cg->default_groups\n");
ret = -ENOMEM;
goto out;
}
config_group_init_type_name(&lacl->se_lun_group, name,
&TF_CIT_TMPL(tf)->tfc_tpg_mappedlun_cit);
config_group_init_type_name(&lacl->ml_stat_grps.stat_group,
"statistics", &TF_CIT_TMPL(tf)->tfc_tpg_mappedlun_stat_cit);
lacl_cg->default_groups[0] = &lacl->ml_stat_grps.stat_group;
lacl_cg->default_groups[1] = NULL;
ml_stat_grp = &lacl->ml_stat_grps.stat_group;
ml_stat_grp->default_groups = kzalloc(sizeof(struct config_group) * 3,
GFP_KERNEL);
if (!ml_stat_grp->default_groups) {
pr_err("Unable to allocate ml_stat_grp->default_groups\n");
ret = -ENOMEM;
goto out;
}
target_stat_setup_mappedlun_default_groups(lacl);
kfree(buf);
return &lacl->se_lun_group;
out:
if (lacl_cg)
kfree(lacl_cg->default_groups);
kfree(buf);
return ERR_PTR(ret);
}
static void target_fabric_drop_mappedlun(
struct config_group *group,
struct config_item *item)
{
struct se_lun_acl *lacl = container_of(to_config_group(item),
struct se_lun_acl, se_lun_group);
struct config_item *df_item;
struct config_group *lacl_cg = NULL, *ml_stat_grp = NULL;
int i;
ml_stat_grp = &lacl->ml_stat_grps.stat_group;
for (i = 0; ml_stat_grp->default_groups[i]; i++) {
df_item = &ml_stat_grp->default_groups[i]->cg_item;
ml_stat_grp->default_groups[i] = NULL;
config_item_put(df_item);
}
kfree(ml_stat_grp->default_groups);
lacl_cg = &lacl->se_lun_group;
for (i = 0; lacl_cg->default_groups[i]; i++) {
df_item = &lacl_cg->default_groups[i]->cg_item;
lacl_cg->default_groups[i] = NULL;
config_item_put(df_item);
}
kfree(lacl_cg->default_groups);
config_item_put(item);
}
static void target_fabric_nacl_base_release(struct config_item *item)
{
struct se_node_acl *se_nacl = container_of(to_config_group(item),
struct se_node_acl, acl_group);
struct se_portal_group *se_tpg = se_nacl->se_tpg;
struct target_fabric_configfs *tf = se_tpg->se_tpg_wwn->wwn_tf;
tf->tf_ops.fabric_drop_nodeacl(se_nacl);
}
static struct configfs_item_operations target_fabric_nacl_base_item_ops = {
.release = target_fabric_nacl_base_release,
.show_attribute = target_fabric_nacl_base_attr_show,
.store_attribute = target_fabric_nacl_base_attr_store,
};
static struct configfs_group_operations target_fabric_nacl_base_group_ops = {
.make_group = target_fabric_make_mappedlun,
.drop_item = target_fabric_drop_mappedlun,
};
TF_CIT_SETUP(tpg_nacl_base, &target_fabric_nacl_base_item_ops,
&target_fabric_nacl_base_group_ops, NULL);
/* End of tfc_tpg_nacl_base_cit */
/* Start of tfc_node_fabric_stats_cit */
/*
* This is used as a placeholder for struct se_node_acl->acl_fabric_stat_group
* to allow fabrics access to ->acl_fabric_stat_group->default_groups[]
*/
TF_CIT_SETUP(tpg_nacl_stat, NULL, NULL, NULL);
/* End of tfc_wwn_fabric_stats_cit */
/* Start of tfc_tpg_nacl_cit */
static struct config_group *target_fabric_make_nodeacl(
struct config_group *group,
const char *name)
{
struct se_portal_group *se_tpg = container_of(group,
struct se_portal_group, tpg_acl_group);
struct target_fabric_configfs *tf = se_tpg->se_tpg_wwn->wwn_tf;
struct se_node_acl *se_nacl;
struct config_group *nacl_cg;
if (!tf->tf_ops.fabric_make_nodeacl) {
pr_err("tf->tf_ops.fabric_make_nodeacl is NULL\n");
return ERR_PTR(-ENOSYS);
}
se_nacl = tf->tf_ops.fabric_make_nodeacl(se_tpg, group, name);
if (IS_ERR(se_nacl))
return ERR_CAST(se_nacl);
nacl_cg = &se_nacl->acl_group;
nacl_cg->default_groups = se_nacl->acl_default_groups;
nacl_cg->default_groups[0] = &se_nacl->acl_attrib_group;
nacl_cg->default_groups[1] = &se_nacl->acl_auth_group;
nacl_cg->default_groups[2] = &se_nacl->acl_param_group;
nacl_cg->default_groups[3] = &se_nacl->acl_fabric_stat_group;
nacl_cg->default_groups[4] = NULL;
config_group_init_type_name(&se_nacl->acl_group, name,
&TF_CIT_TMPL(tf)->tfc_tpg_nacl_base_cit);
config_group_init_type_name(&se_nacl->acl_attrib_group, "attrib",
&TF_CIT_TMPL(tf)->tfc_tpg_nacl_attrib_cit);
config_group_init_type_name(&se_nacl->acl_auth_group, "auth",
&TF_CIT_TMPL(tf)->tfc_tpg_nacl_auth_cit);
config_group_init_type_name(&se_nacl->acl_param_group, "param",
&TF_CIT_TMPL(tf)->tfc_tpg_nacl_param_cit);
config_group_init_type_name(&se_nacl->acl_fabric_stat_group,
"fabric_statistics",
&TF_CIT_TMPL(tf)->tfc_tpg_nacl_stat_cit);
return &se_nacl->acl_group;
}
static void target_fabric_drop_nodeacl(
struct config_group *group,
struct config_item *item)
{
struct se_node_acl *se_nacl = container_of(to_config_group(item),
struct se_node_acl, acl_group);
struct config_item *df_item;
struct config_group *nacl_cg;
int i;
nacl_cg = &se_nacl->acl_group;
for (i = 0; nacl_cg->default_groups[i]; i++) {
df_item = &nacl_cg->default_groups[i]->cg_item;
nacl_cg->default_groups[i] = NULL;
config_item_put(df_item);
}
/*
* struct se_node_acl free is done in target_fabric_nacl_base_release()
*/
config_item_put(item);
}
static struct configfs_group_operations target_fabric_nacl_group_ops = {
.make_group = target_fabric_make_nodeacl,
.drop_item = target_fabric_drop_nodeacl,
};
TF_CIT_SETUP(tpg_nacl, NULL, &target_fabric_nacl_group_ops, NULL);
/* End of tfc_tpg_nacl_cit */
/* Start of tfc_tpg_np_base_cit */
CONFIGFS_EATTR_OPS(target_fabric_np_base, se_tpg_np, tpg_np_group);
static void target_fabric_np_base_release(struct config_item *item)
{
struct se_tpg_np *se_tpg_np = container_of(to_config_group(item),
struct se_tpg_np, tpg_np_group);
struct se_portal_group *se_tpg = se_tpg_np->tpg_np_parent;
struct target_fabric_configfs *tf = se_tpg->se_tpg_wwn->wwn_tf;
tf->tf_ops.fabric_drop_np(se_tpg_np);
}
static struct configfs_item_operations target_fabric_np_base_item_ops = {
.release = target_fabric_np_base_release,
.show_attribute = target_fabric_np_base_attr_show,
.store_attribute = target_fabric_np_base_attr_store,
};
TF_CIT_SETUP(tpg_np_base, &target_fabric_np_base_item_ops, NULL, NULL);
/* End of tfc_tpg_np_base_cit */
/* Start of tfc_tpg_np_cit */
static struct config_group *target_fabric_make_np(
struct config_group *group,
const char *name)
{
struct se_portal_group *se_tpg = container_of(group,
struct se_portal_group, tpg_np_group);
struct target_fabric_configfs *tf = se_tpg->se_tpg_wwn->wwn_tf;
struct se_tpg_np *se_tpg_np;
if (!tf->tf_ops.fabric_make_np) {
pr_err("tf->tf_ops.fabric_make_np is NULL\n");
return ERR_PTR(-ENOSYS);
}
se_tpg_np = tf->tf_ops.fabric_make_np(se_tpg, group, name);
if (!se_tpg_np || IS_ERR(se_tpg_np))
return ERR_PTR(-EINVAL);
se_tpg_np->tpg_np_parent = se_tpg;
config_group_init_type_name(&se_tpg_np->tpg_np_group, name,
&TF_CIT_TMPL(tf)->tfc_tpg_np_base_cit);
return &se_tpg_np->tpg_np_group;
}
static void target_fabric_drop_np(
struct config_group *group,
struct config_item *item)
{
/*
* struct se_tpg_np is released via target_fabric_np_base_release()
*/
config_item_put(item);
}
static struct configfs_group_operations target_fabric_np_group_ops = {
.make_group = &target_fabric_make_np,
.drop_item = &target_fabric_drop_np,
};
TF_CIT_SETUP(tpg_np, NULL, &target_fabric_np_group_ops, NULL);
/* End of tfc_tpg_np_cit */
/* Start of tfc_tpg_port_cit */
CONFIGFS_EATTR_STRUCT(target_fabric_port, se_lun);
#define TCM_PORT_ATTR(_name, _mode) \
static struct target_fabric_port_attribute target_fabric_port_##_name = \
__CONFIGFS_EATTR(_name, _mode, \
target_fabric_port_show_attr_##_name, \
target_fabric_port_store_attr_##_name);
#define TCM_PORT_ATTOR_RO(_name) \
__CONFIGFS_EATTR_RO(_name, \
target_fabric_port_show_attr_##_name);
/*
* alua_tg_pt_gp
*/
static ssize_t target_fabric_port_show_attr_alua_tg_pt_gp(
struct se_lun *lun,
char *page)
{
if (!lun || !lun->lun_sep)
return -ENODEV;
return core_alua_show_tg_pt_gp_info(lun->lun_sep, page);
}
static ssize_t target_fabric_port_store_attr_alua_tg_pt_gp(
struct se_lun *lun,
const char *page,
size_t count)
{
if (!lun || !lun->lun_sep)
return -ENODEV;
return core_alua_store_tg_pt_gp_info(lun->lun_sep, page, count);
}
TCM_PORT_ATTR(alua_tg_pt_gp, S_IRUGO | S_IWUSR);
/*
* alua_tg_pt_offline
*/
static ssize_t target_fabric_port_show_attr_alua_tg_pt_offline(
struct se_lun *lun,
char *page)
{
if (!lun || !lun->lun_sep)
return -ENODEV;
return core_alua_show_offline_bit(lun, page);
}
static ssize_t target_fabric_port_store_attr_alua_tg_pt_offline(
struct se_lun *lun,
const char *page,
size_t count)
{
if (!lun || !lun->lun_sep)
return -ENODEV;
return core_alua_store_offline_bit(lun, page, count);
}
TCM_PORT_ATTR(alua_tg_pt_offline, S_IRUGO | S_IWUSR);
/*
* alua_tg_pt_status
*/
static ssize_t target_fabric_port_show_attr_alua_tg_pt_status(
struct se_lun *lun,
char *page)
{
if (!lun || !lun->lun_sep)
return -ENODEV;
return core_alua_show_secondary_status(lun, page);
}
static ssize_t target_fabric_port_store_attr_alua_tg_pt_status(
struct se_lun *lun,
const char *page,
size_t count)
{
if (!lun || !lun->lun_sep)
return -ENODEV;
return core_alua_store_secondary_status(lun, page, count);
}
TCM_PORT_ATTR(alua_tg_pt_status, S_IRUGO | S_IWUSR);
/*
* alua_tg_pt_write_md
*/
static ssize_t target_fabric_port_show_attr_alua_tg_pt_write_md(
struct se_lun *lun,
char *page)
{
if (!lun || !lun->lun_sep)
return -ENODEV;
return core_alua_show_secondary_write_metadata(lun, page);
}
static ssize_t target_fabric_port_store_attr_alua_tg_pt_write_md(
struct se_lun *lun,
const char *page,
size_t count)
{
if (!lun || !lun->lun_sep)
return -ENODEV;
return core_alua_store_secondary_write_metadata(lun, page, count);
}
TCM_PORT_ATTR(alua_tg_pt_write_md, S_IRUGO | S_IWUSR);
static struct configfs_attribute *target_fabric_port_attrs[] = {
&target_fabric_port_alua_tg_pt_gp.attr,
&target_fabric_port_alua_tg_pt_offline.attr,
&target_fabric_port_alua_tg_pt_status.attr,
&target_fabric_port_alua_tg_pt_write_md.attr,
NULL,
};
CONFIGFS_EATTR_OPS(target_fabric_port, se_lun, lun_group);
static int target_fabric_port_link(
struct config_item *lun_ci,
struct config_item *se_dev_ci)
{
struct config_item *tpg_ci;
struct se_device *dev;
struct se_lun *lun = container_of(to_config_group(lun_ci),
struct se_lun, lun_group);
struct se_lun *lun_p;
struct se_portal_group *se_tpg;
struct se_subsystem_dev *se_dev = container_of(
to_config_group(se_dev_ci), struct se_subsystem_dev,
se_dev_group);
struct target_fabric_configfs *tf;
int ret;
tpg_ci = &lun_ci->ci_parent->ci_group->cg_item;
se_tpg = container_of(to_config_group(tpg_ci),
struct se_portal_group, tpg_group);
tf = se_tpg->se_tpg_wwn->wwn_tf;
if (lun->lun_se_dev != NULL) {
pr_err("Port Symlink already exists\n");
return -EEXIST;
}
dev = se_dev->se_dev_ptr;
if (!dev) {
pr_err("Unable to locate struct se_device pointer from"
" %s\n", config_item_name(se_dev_ci));
ret = -ENODEV;
goto out;
}
lun_p = core_dev_add_lun(se_tpg, dev->se_hba, dev,
lun->unpacked_lun);
if (IS_ERR(lun_p)) {
pr_err("core_dev_add_lun() failed\n");
ret = PTR_ERR(lun_p);
goto out;
}
if (tf->tf_ops.fabric_post_link) {
/*
* Call the optional fabric_post_link() to allow a
* fabric module to setup any additional state once
* core_dev_add_lun() has been called..
*/
tf->tf_ops.fabric_post_link(se_tpg, lun);
}
return 0;
out:
return ret;
}
static int target_fabric_port_unlink(
struct config_item *lun_ci,
struct config_item *se_dev_ci)
{
struct se_lun *lun = container_of(to_config_group(lun_ci),
struct se_lun, lun_group);
struct se_portal_group *se_tpg = lun->lun_sep->sep_tpg;
struct target_fabric_configfs *tf = se_tpg->se_tpg_wwn->wwn_tf;
if (tf->tf_ops.fabric_pre_unlink) {
/*
* Call the optional fabric_pre_unlink() to allow a
* fabric module to release any additional stat before
* core_dev_del_lun() is called.
*/
tf->tf_ops.fabric_pre_unlink(se_tpg, lun);
}
core_dev_del_lun(se_tpg, lun->unpacked_lun);
return 0;
}
static struct configfs_item_operations target_fabric_port_item_ops = {
.show_attribute = target_fabric_port_attr_show,
.store_attribute = target_fabric_port_attr_store,
.allow_link = target_fabric_port_link,
.drop_link = target_fabric_port_unlink,
};
TF_CIT_SETUP(tpg_port, &target_fabric_port_item_ops, NULL, target_fabric_port_attrs);
/* End of tfc_tpg_port_cit */
/* Start of tfc_tpg_port_stat_cit */
static struct config_group *target_core_port_stat_mkdir(
struct config_group *group,
const char *name)
{
return ERR_PTR(-ENOSYS);
}
static void target_core_port_stat_rmdir(
struct config_group *group,
struct config_item *item)
{
return;
}
static struct configfs_group_operations target_fabric_port_stat_group_ops = {
.make_group = target_core_port_stat_mkdir,
.drop_item = target_core_port_stat_rmdir,
};
TF_CIT_SETUP(tpg_port_stat, NULL, &target_fabric_port_stat_group_ops, NULL);
/* End of tfc_tpg_port_stat_cit */
/* Start of tfc_tpg_lun_cit */
static struct config_group *target_fabric_make_lun(
struct config_group *group,
const char *name)
{
struct se_lun *lun;
struct se_portal_group *se_tpg = container_of(group,
struct se_portal_group, tpg_lun_group);
struct target_fabric_configfs *tf = se_tpg->se_tpg_wwn->wwn_tf;
struct config_group *lun_cg = NULL, *port_stat_grp = NULL;
unsigned long unpacked_lun;
int errno;
if (strstr(name, "lun_") != name) {
pr_err("Unable to locate \'_\" in"
" \"lun_$LUN_NUMBER\"\n");
return ERR_PTR(-EINVAL);
}
if (strict_strtoul(name + 4, 0, &unpacked_lun) || unpacked_lun > UINT_MAX)
return ERR_PTR(-EINVAL);
lun = core_get_lun_from_tpg(se_tpg, unpacked_lun);
if (!lun)
return ERR_PTR(-EINVAL);
lun_cg = &lun->lun_group;
lun_cg->default_groups = kzalloc(sizeof(struct config_group) * 2,
GFP_KERNEL);
if (!lun_cg->default_groups) {
pr_err("Unable to allocate lun_cg->default_groups\n");
return ERR_PTR(-ENOMEM);
}
config_group_init_type_name(&lun->lun_group, name,
&TF_CIT_TMPL(tf)->tfc_tpg_port_cit);
config_group_init_type_name(&lun->port_stat_grps.stat_group,
"statistics", &TF_CIT_TMPL(tf)->tfc_tpg_port_stat_cit);
lun_cg->default_groups[0] = &lun->port_stat_grps.stat_group;
lun_cg->default_groups[1] = NULL;
port_stat_grp = &lun->port_stat_grps.stat_group;
port_stat_grp->default_groups = kzalloc(sizeof(struct config_group) * 3,
GFP_KERNEL);
if (!port_stat_grp->default_groups) {
pr_err("Unable to allocate port_stat_grp->default_groups\n");
errno = -ENOMEM;
goto out;
}
target_stat_setup_port_default_groups(lun);
return &lun->lun_group;
out:
if (lun_cg)
kfree(lun_cg->default_groups);
return ERR_PTR(errno);
}
static void target_fabric_drop_lun(
struct config_group *group,
struct config_item *item)
{
struct se_lun *lun = container_of(to_config_group(item),
struct se_lun, lun_group);
struct config_item *df_item;
struct config_group *lun_cg, *port_stat_grp;
int i;
port_stat_grp = &lun->port_stat_grps.stat_group;
for (i = 0; port_stat_grp->default_groups[i]; i++) {
df_item = &port_stat_grp->default_groups[i]->cg_item;
port_stat_grp->default_groups[i] = NULL;
config_item_put(df_item);
}
kfree(port_stat_grp->default_groups);
lun_cg = &lun->lun_group;
for (i = 0; lun_cg->default_groups[i]; i++) {
df_item = &lun_cg->default_groups[i]->cg_item;
lun_cg->default_groups[i] = NULL;
config_item_put(df_item);
}
kfree(lun_cg->default_groups);
config_item_put(item);
}
static struct configfs_group_operations target_fabric_lun_group_ops = {
.make_group = &target_fabric_make_lun,
.drop_item = &target_fabric_drop_lun,
};
TF_CIT_SETUP(tpg_lun, NULL, &target_fabric_lun_group_ops, NULL);
/* End of tfc_tpg_lun_cit */
/* Start of tfc_tpg_attrib_cit */
CONFIGFS_EATTR_OPS(target_fabric_tpg_attrib, se_portal_group, tpg_attrib_group);
static struct configfs_item_operations target_fabric_tpg_attrib_item_ops = {
.show_attribute = target_fabric_tpg_attrib_attr_show,
.store_attribute = target_fabric_tpg_attrib_attr_store,
};
TF_CIT_SETUP(tpg_attrib, &target_fabric_tpg_attrib_item_ops, NULL, NULL);
/* End of tfc_tpg_attrib_cit */
/* Start of tfc_tpg_param_cit */
CONFIGFS_EATTR_OPS(target_fabric_tpg_param, se_portal_group, tpg_param_group);
static struct configfs_item_operations target_fabric_tpg_param_item_ops = {
.show_attribute = target_fabric_tpg_param_attr_show,
.store_attribute = target_fabric_tpg_param_attr_store,
};
TF_CIT_SETUP(tpg_param, &target_fabric_tpg_param_item_ops, NULL, NULL);
/* End of tfc_tpg_param_cit */
/* Start of tfc_tpg_base_cit */
/*
* For use with TF_TPG_ATTR() and TF_TPG_ATTR_RO()
*/
CONFIGFS_EATTR_OPS(target_fabric_tpg, se_portal_group, tpg_group);
static void target_fabric_tpg_release(struct config_item *item)
{
struct se_portal_group *se_tpg = container_of(to_config_group(item),
struct se_portal_group, tpg_group);
struct se_wwn *wwn = se_tpg->se_tpg_wwn;
struct target_fabric_configfs *tf = wwn->wwn_tf;
tf->tf_ops.fabric_drop_tpg(se_tpg);
}
static struct configfs_item_operations target_fabric_tpg_base_item_ops = {
.release = target_fabric_tpg_release,
.show_attribute = target_fabric_tpg_attr_show,
.store_attribute = target_fabric_tpg_attr_store,
};
TF_CIT_SETUP(tpg_base, &target_fabric_tpg_base_item_ops, NULL, NULL);
/* End of tfc_tpg_base_cit */
/* Start of tfc_tpg_cit */
static struct config_group *target_fabric_make_tpg(
struct config_group *group,
const char *name)
{
struct se_wwn *wwn = container_of(group, struct se_wwn, wwn_group);
struct target_fabric_configfs *tf = wwn->wwn_tf;
struct se_portal_group *se_tpg;
if (!tf->tf_ops.fabric_make_tpg) {
pr_err("tf->tf_ops.fabric_make_tpg is NULL\n");
return ERR_PTR(-ENOSYS);
}
se_tpg = tf->tf_ops.fabric_make_tpg(wwn, group, name);
if (!se_tpg || IS_ERR(se_tpg))
return ERR_PTR(-EINVAL);
/*
* Setup default groups from pre-allocated se_tpg->tpg_default_groups
*/
se_tpg->tpg_group.default_groups = se_tpg->tpg_default_groups;
se_tpg->tpg_group.default_groups[0] = &se_tpg->tpg_lun_group;
se_tpg->tpg_group.default_groups[1] = &se_tpg->tpg_np_group;
se_tpg->tpg_group.default_groups[2] = &se_tpg->tpg_acl_group;
se_tpg->tpg_group.default_groups[3] = &se_tpg->tpg_attrib_group;
se_tpg->tpg_group.default_groups[4] = &se_tpg->tpg_param_group;
se_tpg->tpg_group.default_groups[5] = NULL;
config_group_init_type_name(&se_tpg->tpg_group, name,
&TF_CIT_TMPL(tf)->tfc_tpg_base_cit);
config_group_init_type_name(&se_tpg->tpg_lun_group, "lun",
&TF_CIT_TMPL(tf)->tfc_tpg_lun_cit);
config_group_init_type_name(&se_tpg->tpg_np_group, "np",
&TF_CIT_TMPL(tf)->tfc_tpg_np_cit);
config_group_init_type_name(&se_tpg->tpg_acl_group, "acls",
&TF_CIT_TMPL(tf)->tfc_tpg_nacl_cit);
config_group_init_type_name(&se_tpg->tpg_attrib_group, "attrib",
&TF_CIT_TMPL(tf)->tfc_tpg_attrib_cit);
config_group_init_type_name(&se_tpg->tpg_param_group, "param",
&TF_CIT_TMPL(tf)->tfc_tpg_param_cit);
return &se_tpg->tpg_group;
}
static void target_fabric_drop_tpg(
struct config_group *group,
struct config_item *item)
{
struct se_portal_group *se_tpg = container_of(to_config_group(item),
struct se_portal_group, tpg_group);
struct config_group *tpg_cg = &se_tpg->tpg_group;
struct config_item *df_item;
int i;
/*
* Release default groups, but do not release tpg_cg->default_groups
* memory as it is statically allocated at se_tpg->tpg_default_groups.
*/
for (i = 0; tpg_cg->default_groups[i]; i++) {
df_item = &tpg_cg->default_groups[i]->cg_item;
tpg_cg->default_groups[i] = NULL;
config_item_put(df_item);
}
config_item_put(item);
}
static void target_fabric_release_wwn(struct config_item *item)
{
struct se_wwn *wwn = container_of(to_config_group(item),
struct se_wwn, wwn_group);
struct target_fabric_configfs *tf = wwn->wwn_tf;
tf->tf_ops.fabric_drop_wwn(wwn);
}
static struct configfs_item_operations target_fabric_tpg_item_ops = {
.release = target_fabric_release_wwn,
};
static struct configfs_group_operations target_fabric_tpg_group_ops = {
.make_group = target_fabric_make_tpg,
.drop_item = target_fabric_drop_tpg,
};
TF_CIT_SETUP(tpg, &target_fabric_tpg_item_ops, &target_fabric_tpg_group_ops,
NULL);
/* End of tfc_tpg_cit */
/* Start of tfc_wwn_fabric_stats_cit */
/*
* This is used as a placeholder for struct se_wwn->fabric_stat_group
* to allow fabrics access to ->fabric_stat_group->default_groups[]
*/
TF_CIT_SETUP(wwn_fabric_stats, NULL, NULL, NULL);
/* End of tfc_wwn_fabric_stats_cit */
/* Start of tfc_wwn_cit */
static struct config_group *target_fabric_make_wwn(
struct config_group *group,
const char *name)
{
struct target_fabric_configfs *tf = container_of(group,
struct target_fabric_configfs, tf_group);
struct se_wwn *wwn;
if (!tf->tf_ops.fabric_make_wwn) {
pr_err("tf->tf_ops.fabric_make_wwn is NULL\n");
return ERR_PTR(-ENOSYS);
}
wwn = tf->tf_ops.fabric_make_wwn(tf, group, name);
if (!wwn || IS_ERR(wwn))
return ERR_PTR(-EINVAL);
wwn->wwn_tf = tf;
/*
* Setup default groups from pre-allocated wwn->wwn_default_groups
*/
wwn->wwn_group.default_groups = wwn->wwn_default_groups;
wwn->wwn_group.default_groups[0] = &wwn->fabric_stat_group;
wwn->wwn_group.default_groups[1] = NULL;
config_group_init_type_name(&wwn->wwn_group, name,
&TF_CIT_TMPL(tf)->tfc_tpg_cit);
config_group_init_type_name(&wwn->fabric_stat_group, "fabric_statistics",
&TF_CIT_TMPL(tf)->tfc_wwn_fabric_stats_cit);
return &wwn->wwn_group;
}
static void target_fabric_drop_wwn(
struct config_group *group,
struct config_item *item)
{
struct se_wwn *wwn = container_of(to_config_group(item),
struct se_wwn, wwn_group);
struct config_item *df_item;
struct config_group *cg = &wwn->wwn_group;
int i;
for (i = 0; cg->default_groups[i]; i++) {
df_item = &cg->default_groups[i]->cg_item;
cg->default_groups[i] = NULL;
config_item_put(df_item);
}
config_item_put(item);
}
static struct configfs_group_operations target_fabric_wwn_group_ops = {
.make_group = target_fabric_make_wwn,
.drop_item = target_fabric_drop_wwn,
};
/*
* For use with TF_WWN_ATTR() and TF_WWN_ATTR_RO()
*/
CONFIGFS_EATTR_OPS(target_fabric_wwn, target_fabric_configfs, tf_group);
static struct configfs_item_operations target_fabric_wwn_item_ops = {
.show_attribute = target_fabric_wwn_attr_show,
.store_attribute = target_fabric_wwn_attr_store,
};
TF_CIT_SETUP(wwn, &target_fabric_wwn_item_ops, &target_fabric_wwn_group_ops, NULL);
/* End of tfc_wwn_cit */
/* Start of tfc_discovery_cit */
CONFIGFS_EATTR_OPS(target_fabric_discovery, target_fabric_configfs,
tf_disc_group);
static struct configfs_item_operations target_fabric_discovery_item_ops = {
.show_attribute = target_fabric_discovery_attr_show,
.store_attribute = target_fabric_discovery_attr_store,
};
TF_CIT_SETUP(discovery, &target_fabric_discovery_item_ops, NULL, NULL);
/* End of tfc_discovery_cit */
int target_fabric_setup_cits(struct target_fabric_configfs *tf)
{
target_fabric_setup_discovery_cit(tf);
target_fabric_setup_wwn_cit(tf);
target_fabric_setup_wwn_fabric_stats_cit(tf);
target_fabric_setup_tpg_cit(tf);
target_fabric_setup_tpg_base_cit(tf);
target_fabric_setup_tpg_port_cit(tf);
target_fabric_setup_tpg_port_stat_cit(tf);
target_fabric_setup_tpg_lun_cit(tf);
target_fabric_setup_tpg_np_cit(tf);
target_fabric_setup_tpg_np_base_cit(tf);
target_fabric_setup_tpg_attrib_cit(tf);
target_fabric_setup_tpg_param_cit(tf);
target_fabric_setup_tpg_nacl_cit(tf);
target_fabric_setup_tpg_nacl_base_cit(tf);
target_fabric_setup_tpg_nacl_attrib_cit(tf);
target_fabric_setup_tpg_nacl_auth_cit(tf);
target_fabric_setup_tpg_nacl_param_cit(tf);
target_fabric_setup_tpg_nacl_stat_cit(tf);
target_fabric_setup_tpg_mappedlun_cit(tf);
target_fabric_setup_tpg_mappedlun_stat_cit(tf);
return 0;
}
| gpl-2.0 |
googyanas/GoogyMax-N5 | sound/isa/wavefront/wavefront_fx.c | 3326 | 6309 | /*
* Copyright (c) 1998-2002 by Paul Davis <pbd@op.net>
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <asm/io.h>
#include <linux/init.h>
#include <linux/time.h>
#include <linux/wait.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/firmware.h>
#include <sound/core.h>
#include <sound/snd_wavefront.h>
#include <sound/initval.h>
/* Control bits for the Load Control Register
*/
#define FX_LSB_TRANSFER 0x01 /* transfer after DSP LSB byte written */
#define FX_MSB_TRANSFER 0x02 /* transfer after DSP MSB byte written */
#define FX_AUTO_INCR 0x04 /* auto-increment DSP address after transfer */
#define WAIT_IDLE 0xff
static int
wavefront_fx_idle (snd_wavefront_t *dev)
{
int i;
unsigned int x = 0x80;
for (i = 0; i < 1000; i++) {
x = inb (dev->fx_status);
if ((x & 0x80) == 0) {
break;
}
}
if (x & 0x80) {
snd_printk ("FX device never idle.\n");
return 0;
}
return (1);
}
static void
wavefront_fx_mute (snd_wavefront_t *dev, int onoff)
{
if (!wavefront_fx_idle(dev)) {
return;
}
outb (onoff ? 0x02 : 0x00, dev->fx_op);
}
static int
wavefront_fx_memset (snd_wavefront_t *dev,
int page,
int addr,
int cnt,
unsigned short *data)
{
if (page < 0 || page > 7) {
snd_printk ("FX memset: "
"page must be >= 0 and <= 7\n");
return -(EINVAL);
}
if (addr < 0 || addr > 0x7f) {
snd_printk ("FX memset: "
"addr must be >= 0 and <= 7f\n");
return -(EINVAL);
}
if (cnt == 1) {
outb (FX_LSB_TRANSFER, dev->fx_lcr);
outb (page, dev->fx_dsp_page);
outb (addr, dev->fx_dsp_addr);
outb ((data[0] >> 8), dev->fx_dsp_msb);
outb ((data[0] & 0xff), dev->fx_dsp_lsb);
snd_printk ("FX: addr %d:%x set to 0x%x\n",
page, addr, data[0]);
} else {
int i;
outb (FX_AUTO_INCR|FX_LSB_TRANSFER, dev->fx_lcr);
outb (page, dev->fx_dsp_page);
outb (addr, dev->fx_dsp_addr);
for (i = 0; i < cnt; i++) {
outb ((data[i] >> 8), dev->fx_dsp_msb);
outb ((data[i] & 0xff), dev->fx_dsp_lsb);
if (!wavefront_fx_idle (dev)) {
break;
}
}
if (i != cnt) {
snd_printk ("FX memset "
"(0x%x, 0x%x, 0x%lx, %d) incomplete\n",
page, addr, (unsigned long) data, cnt);
return -(EIO);
}
}
return 0;
}
int
snd_wavefront_fx_detect (snd_wavefront_t *dev)
{
/* This is a crude check, but its the best one I have for now.
Certainly on the Maui and the Tropez, wavefront_fx_idle() will
report "never idle", which suggests that this test should
work OK.
*/
if (inb (dev->fx_status) & 0x80) {
snd_printk ("Hmm, probably a Maui or Tropez.\n");
return -1;
}
return 0;
}
int
snd_wavefront_fx_open (struct snd_hwdep *hw, struct file *file)
{
if (!try_module_get(hw->card->module))
return -EFAULT;
file->private_data = hw;
return 0;
}
int
snd_wavefront_fx_release (struct snd_hwdep *hw, struct file *file)
{
module_put(hw->card->module);
return 0;
}
int
snd_wavefront_fx_ioctl (struct snd_hwdep *sdev, struct file *file,
unsigned int cmd, unsigned long arg)
{
struct snd_card *card;
snd_wavefront_card_t *acard;
snd_wavefront_t *dev;
wavefront_fx_info r;
unsigned short *page_data = NULL;
unsigned short *pd;
int err = 0;
card = sdev->card;
if (snd_BUG_ON(!card))
return -ENODEV;
if (snd_BUG_ON(!card->private_data))
return -ENODEV;
acard = card->private_data;
dev = &acard->wavefront;
if (copy_from_user (&r, (void __user *)arg, sizeof (wavefront_fx_info)))
return -EFAULT;
switch (r.request) {
case WFFX_MUTE:
wavefront_fx_mute (dev, r.data[0]);
return -EIO;
case WFFX_MEMSET:
if (r.data[2] <= 0) {
snd_printk ("cannot write "
"<= 0 bytes to FX\n");
return -EIO;
} else if (r.data[2] == 1) {
pd = (unsigned short *) &r.data[3];
} else {
if (r.data[2] > 256) {
snd_printk ("cannot write "
"> 512 bytes to FX\n");
return -EIO;
}
page_data = memdup_user((unsigned char __user *)
r.data[3],
r.data[2] * sizeof(short));
if (IS_ERR(page_data))
return PTR_ERR(page_data);
pd = page_data;
}
err = wavefront_fx_memset (dev,
r.data[0], /* page */
r.data[1], /* addr */
r.data[2], /* cnt */
pd);
kfree(page_data);
break;
default:
snd_printk ("FX: ioctl %d not yet supported\n",
r.request);
return -ENOTTY;
}
return err;
}
/* YSS225 initialization.
This code was developed using DOSEMU. The Turtle Beach SETUPSND
utility was run with I/O tracing in DOSEMU enabled, and a reconstruction
of the port I/O done, using the Yamaha faxback document as a guide
to add more logic to the code. Its really pretty weird.
This is the approach of just dumping the whole I/O
sequence as a series of port/value pairs and a simple loop
that outputs it.
*/
int
snd_wavefront_fx_start (snd_wavefront_t *dev)
{
unsigned int i;
int err;
const struct firmware *firmware = NULL;
if (dev->fx_initialized)
return 0;
err = request_firmware(&firmware, "yamaha/yss225_registers.bin",
dev->card->dev);
if (err < 0) {
err = -1;
goto out;
}
for (i = 0; i + 1 < firmware->size; i += 2) {
if (firmware->data[i] >= 8 && firmware->data[i] < 16) {
outb(firmware->data[i + 1],
dev->base + firmware->data[i]);
} else if (firmware->data[i] == WAIT_IDLE) {
if (!wavefront_fx_idle(dev)) {
err = -1;
goto out;
}
} else {
snd_printk(KERN_ERR "invalid address"
" in register data\n");
err = -1;
goto out;
}
}
dev->fx_initialized = 1;
err = 0;
out:
release_firmware(firmware);
return err;
}
MODULE_FIRMWARE("yamaha/yss225_registers.bin");
| gpl-2.0 |
lirokoa/android_kernel_samsung_n80xx | drivers/net/wan/hdlc_x25.c | 3582 | 5027 | /*
* Generic HDLC support routines for Linux
* X.25 support
*
* Copyright (C) 1999 - 2006 Krzysztof Halasa <khc@pm.waw.pl>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License
* as published by the Free Software Foundation.
*/
#include <linux/errno.h>
#include <linux/gfp.h>
#include <linux/hdlc.h>
#include <linux/if_arp.h>
#include <linux/inetdevice.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/lapb.h>
#include <linux/module.h>
#include <linux/pkt_sched.h>
#include <linux/poll.h>
#include <linux/rtnetlink.h>
#include <linux/skbuff.h>
#include <net/x25device.h>
static int x25_ioctl(struct net_device *dev, struct ifreq *ifr);
/* These functions are callbacks called by LAPB layer */
static void x25_connect_disconnect(struct net_device *dev, int reason, int code)
{
struct sk_buff *skb;
unsigned char *ptr;
if ((skb = dev_alloc_skb(1)) == NULL) {
printk(KERN_ERR "%s: out of memory\n", dev->name);
return;
}
ptr = skb_put(skb, 1);
*ptr = code;
skb->protocol = x25_type_trans(skb, dev);
netif_rx(skb);
}
static void x25_connected(struct net_device *dev, int reason)
{
x25_connect_disconnect(dev, reason, X25_IFACE_CONNECT);
}
static void x25_disconnected(struct net_device *dev, int reason)
{
x25_connect_disconnect(dev, reason, X25_IFACE_DISCONNECT);
}
static int x25_data_indication(struct net_device *dev, struct sk_buff *skb)
{
unsigned char *ptr;
skb_push(skb, 1);
if (skb_cow(skb, 1))
return NET_RX_DROP;
ptr = skb->data;
*ptr = X25_IFACE_DATA;
skb->protocol = x25_type_trans(skb, dev);
return netif_rx(skb);
}
static void x25_data_transmit(struct net_device *dev, struct sk_buff *skb)
{
hdlc_device *hdlc = dev_to_hdlc(dev);
hdlc->xmit(skb, dev); /* Ignore return value :-( */
}
static netdev_tx_t x25_xmit(struct sk_buff *skb, struct net_device *dev)
{
int result;
/* X.25 to LAPB */
switch (skb->data[0]) {
case X25_IFACE_DATA: /* Data to be transmitted */
skb_pull(skb, 1);
if ((result = lapb_data_request(dev, skb)) != LAPB_OK)
dev_kfree_skb(skb);
return NETDEV_TX_OK;
case X25_IFACE_CONNECT:
if ((result = lapb_connect_request(dev))!= LAPB_OK) {
if (result == LAPB_CONNECTED)
/* Send connect confirm. msg to level 3 */
x25_connected(dev, 0);
else
printk(KERN_ERR "%s: LAPB connect request "
"failed, error code = %i\n",
dev->name, result);
}
break;
case X25_IFACE_DISCONNECT:
if ((result = lapb_disconnect_request(dev)) != LAPB_OK) {
if (result == LAPB_NOTCONNECTED)
/* Send disconnect confirm. msg to level 3 */
x25_disconnected(dev, 0);
else
printk(KERN_ERR "%s: LAPB disconnect request "
"failed, error code = %i\n",
dev->name, result);
}
break;
default: /* to be defined */
break;
}
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
static int x25_open(struct net_device *dev)
{
struct lapb_register_struct cb;
int result;
cb.connect_confirmation = x25_connected;
cb.connect_indication = x25_connected;
cb.disconnect_confirmation = x25_disconnected;
cb.disconnect_indication = x25_disconnected;
cb.data_indication = x25_data_indication;
cb.data_transmit = x25_data_transmit;
result = lapb_register(dev, &cb);
if (result != LAPB_OK)
return result;
return 0;
}
static void x25_close(struct net_device *dev)
{
lapb_unregister(dev);
}
static int x25_rx(struct sk_buff *skb)
{
struct net_device *dev = skb->dev;
if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL) {
dev->stats.rx_dropped++;
return NET_RX_DROP;
}
if (lapb_data_received(dev, skb) == LAPB_OK)
return NET_RX_SUCCESS;
dev->stats.rx_errors++;
dev_kfree_skb_any(skb);
return NET_RX_DROP;
}
static struct hdlc_proto proto = {
.open = x25_open,
.close = x25_close,
.ioctl = x25_ioctl,
.netif_rx = x25_rx,
.xmit = x25_xmit,
.module = THIS_MODULE,
};
static int x25_ioctl(struct net_device *dev, struct ifreq *ifr)
{
hdlc_device *hdlc = dev_to_hdlc(dev);
int result;
switch (ifr->ifr_settings.type) {
case IF_GET_PROTO:
if (dev_to_hdlc(dev)->proto != &proto)
return -EINVAL;
ifr->ifr_settings.type = IF_PROTO_X25;
return 0; /* return protocol only, no settable parameters */
case IF_PROTO_X25:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (dev->flags & IFF_UP)
return -EBUSY;
result=hdlc->attach(dev, ENCODING_NRZ,PARITY_CRC16_PR1_CCITT);
if (result)
return result;
if ((result = attach_hdlc_protocol(dev, &proto, 0)))
return result;
dev->type = ARPHRD_X25;
netif_dormant_off(dev);
return 0;
}
return -EINVAL;
}
static int __init mod_init(void)
{
register_hdlc_protocol(&proto);
return 0;
}
static void __exit mod_exit(void)
{
unregister_hdlc_protocol(&proto);
}
module_init(mod_init);
module_exit(mod_exit);
MODULE_AUTHOR("Krzysztof Halasa <khc@pm.waw.pl>");
MODULE_DESCRIPTION("X.25 protocol support for generic HDLC");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
dekadev/Deka-kernel-CM9-3.0 | drivers/input/serio/libps2.c | 3582 | 8643 | /*
* PS/2 driver library
*
* Copyright (c) 1999-2002 Vojtech Pavlik
* Copyright (c) 2004 Dmitry Torokhov
*/
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*/
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/i8042.h>
#include <linux/init.h>
#include <linux/libps2.h>
#define DRIVER_DESC "PS/2 driver library"
MODULE_AUTHOR("Dmitry Torokhov <dtor@mail.ru>");
MODULE_DESCRIPTION("PS/2 driver library");
MODULE_LICENSE("GPL");
/*
* ps2_sendbyte() sends a byte to the device and waits for acknowledge.
* It doesn't handle retransmission, though it could - because if there
* is a need for retransmissions device has to be replaced anyway.
*
* ps2_sendbyte() can only be called from a process context.
*/
int ps2_sendbyte(struct ps2dev *ps2dev, unsigned char byte, int timeout)
{
serio_pause_rx(ps2dev->serio);
ps2dev->nak = 1;
ps2dev->flags |= PS2_FLAG_ACK;
serio_continue_rx(ps2dev->serio);
if (serio_write(ps2dev->serio, byte) == 0)
wait_event_timeout(ps2dev->wait,
!(ps2dev->flags & PS2_FLAG_ACK),
msecs_to_jiffies(timeout));
serio_pause_rx(ps2dev->serio);
ps2dev->flags &= ~PS2_FLAG_ACK;
serio_continue_rx(ps2dev->serio);
return -ps2dev->nak;
}
EXPORT_SYMBOL(ps2_sendbyte);
void ps2_begin_command(struct ps2dev *ps2dev)
{
mutex_lock(&ps2dev->cmd_mutex);
if (i8042_check_port_owner(ps2dev->serio))
i8042_lock_chip();
}
EXPORT_SYMBOL(ps2_begin_command);
void ps2_end_command(struct ps2dev *ps2dev)
{
if (i8042_check_port_owner(ps2dev->serio))
i8042_unlock_chip();
mutex_unlock(&ps2dev->cmd_mutex);
}
EXPORT_SYMBOL(ps2_end_command);
/*
* ps2_drain() waits for device to transmit requested number of bytes
* and discards them.
*/
void ps2_drain(struct ps2dev *ps2dev, int maxbytes, int timeout)
{
if (maxbytes > sizeof(ps2dev->cmdbuf)) {
WARN_ON(1);
maxbytes = sizeof(ps2dev->cmdbuf);
}
ps2_begin_command(ps2dev);
serio_pause_rx(ps2dev->serio);
ps2dev->flags = PS2_FLAG_CMD;
ps2dev->cmdcnt = maxbytes;
serio_continue_rx(ps2dev->serio);
wait_event_timeout(ps2dev->wait,
!(ps2dev->flags & PS2_FLAG_CMD),
msecs_to_jiffies(timeout));
ps2_end_command(ps2dev);
}
EXPORT_SYMBOL(ps2_drain);
/*
* ps2_is_keyboard_id() checks received ID byte against the list of
* known keyboard IDs.
*/
int ps2_is_keyboard_id(char id_byte)
{
static const char keyboard_ids[] = {
0xab, /* Regular keyboards */
0xac, /* NCD Sun keyboard */
0x2b, /* Trust keyboard, translated */
0x5d, /* Trust keyboard */
0x60, /* NMB SGI keyboard, translated */
0x47, /* NMB SGI keyboard */
};
return memchr(keyboard_ids, id_byte, sizeof(keyboard_ids)) != NULL;
}
EXPORT_SYMBOL(ps2_is_keyboard_id);
/*
* ps2_adjust_timeout() is called after receiving 1st byte of command
* response and tries to reduce remaining timeout to speed up command
* completion.
*/
static int ps2_adjust_timeout(struct ps2dev *ps2dev, int command, int timeout)
{
switch (command) {
case PS2_CMD_RESET_BAT:
/*
* Device has sent the first response byte after
* reset command, reset is thus done, so we can
* shorten the timeout.
* The next byte will come soon (keyboard) or not
* at all (mouse).
*/
if (timeout > msecs_to_jiffies(100))
timeout = msecs_to_jiffies(100);
break;
case PS2_CMD_GETID:
/*
* Microsoft Natural Elite keyboard responds to
* the GET ID command as it were a mouse, with
* a single byte. Fail the command so atkbd will
* use alternative probe to detect it.
*/
if (ps2dev->cmdbuf[1] == 0xaa) {
serio_pause_rx(ps2dev->serio);
ps2dev->flags = 0;
serio_continue_rx(ps2dev->serio);
timeout = 0;
}
/*
* If device behind the port is not a keyboard there
* won't be 2nd byte of ID response.
*/
if (!ps2_is_keyboard_id(ps2dev->cmdbuf[1])) {
serio_pause_rx(ps2dev->serio);
ps2dev->flags = ps2dev->cmdcnt = 0;
serio_continue_rx(ps2dev->serio);
timeout = 0;
}
break;
default:
break;
}
return timeout;
}
/*
* ps2_command() sends a command and its parameters to the mouse,
* then waits for the response and puts it in the param array.
*
* ps2_command() can only be called from a process context
*/
int __ps2_command(struct ps2dev *ps2dev, unsigned char *param, int command)
{
int timeout;
int send = (command >> 12) & 0xf;
int receive = (command >> 8) & 0xf;
int rc = -1;
int i;
if (receive > sizeof(ps2dev->cmdbuf)) {
WARN_ON(1);
return -1;
}
if (send && !param) {
WARN_ON(1);
return -1;
}
serio_pause_rx(ps2dev->serio);
ps2dev->flags = command == PS2_CMD_GETID ? PS2_FLAG_WAITID : 0;
ps2dev->cmdcnt = receive;
if (receive && param)
for (i = 0; i < receive; i++)
ps2dev->cmdbuf[(receive - 1) - i] = param[i];
serio_continue_rx(ps2dev->serio);
/*
* Some devices (Synaptics) peform the reset before
* ACKing the reset command, and so it can take a long
* time before the ACK arrrives.
*/
if (ps2_sendbyte(ps2dev, command & 0xff,
command == PS2_CMD_RESET_BAT ? 1000 : 200))
goto out;
for (i = 0; i < send; i++)
if (ps2_sendbyte(ps2dev, param[i], 200))
goto out;
/*
* The reset command takes a long time to execute.
*/
timeout = msecs_to_jiffies(command == PS2_CMD_RESET_BAT ? 4000 : 500);
timeout = wait_event_timeout(ps2dev->wait,
!(ps2dev->flags & PS2_FLAG_CMD1), timeout);
if (ps2dev->cmdcnt && !(ps2dev->flags & PS2_FLAG_CMD1)) {
timeout = ps2_adjust_timeout(ps2dev, command, timeout);
wait_event_timeout(ps2dev->wait,
!(ps2dev->flags & PS2_FLAG_CMD), timeout);
}
if (param)
for (i = 0; i < receive; i++)
param[i] = ps2dev->cmdbuf[(receive - 1) - i];
if (ps2dev->cmdcnt && (command != PS2_CMD_RESET_BAT || ps2dev->cmdcnt != 1))
goto out;
rc = 0;
out:
serio_pause_rx(ps2dev->serio);
ps2dev->flags = 0;
serio_continue_rx(ps2dev->serio);
return rc;
}
EXPORT_SYMBOL(__ps2_command);
int ps2_command(struct ps2dev *ps2dev, unsigned char *param, int command)
{
int rc;
ps2_begin_command(ps2dev);
rc = __ps2_command(ps2dev, param, command);
ps2_end_command(ps2dev);
return rc;
}
EXPORT_SYMBOL(ps2_command);
/*
* ps2_init() initializes ps2dev structure
*/
void ps2_init(struct ps2dev *ps2dev, struct serio *serio)
{
mutex_init(&ps2dev->cmd_mutex);
lockdep_set_subclass(&ps2dev->cmd_mutex, serio->depth);
init_waitqueue_head(&ps2dev->wait);
ps2dev->serio = serio;
}
EXPORT_SYMBOL(ps2_init);
/*
* ps2_handle_ack() is supposed to be used in interrupt handler
* to properly process ACK/NAK of a command from a PS/2 device.
*/
int ps2_handle_ack(struct ps2dev *ps2dev, unsigned char data)
{
switch (data) {
case PS2_RET_ACK:
ps2dev->nak = 0;
break;
case PS2_RET_NAK:
ps2dev->flags |= PS2_FLAG_NAK;
ps2dev->nak = PS2_RET_NAK;
break;
case PS2_RET_ERR:
if (ps2dev->flags & PS2_FLAG_NAK) {
ps2dev->flags &= ~PS2_FLAG_NAK;
ps2dev->nak = PS2_RET_ERR;
break;
}
/*
* Workaround for mice which don't ACK the Get ID command.
* These are valid mouse IDs that we recognize.
*/
case 0x00:
case 0x03:
case 0x04:
if (ps2dev->flags & PS2_FLAG_WAITID) {
ps2dev->nak = 0;
break;
}
/* Fall through */
default:
return 0;
}
if (!ps2dev->nak) {
ps2dev->flags &= ~PS2_FLAG_NAK;
if (ps2dev->cmdcnt)
ps2dev->flags |= PS2_FLAG_CMD | PS2_FLAG_CMD1;
}
ps2dev->flags &= ~PS2_FLAG_ACK;
wake_up(&ps2dev->wait);
if (data != PS2_RET_ACK)
ps2_handle_response(ps2dev, data);
return 1;
}
EXPORT_SYMBOL(ps2_handle_ack);
/*
* ps2_handle_response() is supposed to be used in interrupt handler
* to properly store device's response to a command and notify process
* waiting for completion of the command.
*/
int ps2_handle_response(struct ps2dev *ps2dev, unsigned char data)
{
if (ps2dev->cmdcnt)
ps2dev->cmdbuf[--ps2dev->cmdcnt] = data;
if (ps2dev->flags & PS2_FLAG_CMD1) {
ps2dev->flags &= ~PS2_FLAG_CMD1;
if (ps2dev->cmdcnt)
wake_up(&ps2dev->wait);
}
if (!ps2dev->cmdcnt) {
ps2dev->flags &= ~PS2_FLAG_CMD;
wake_up(&ps2dev->wait);
}
return 1;
}
EXPORT_SYMBOL(ps2_handle_response);
void ps2_cmd_aborted(struct ps2dev *ps2dev)
{
if (ps2dev->flags & PS2_FLAG_ACK)
ps2dev->nak = 1;
if (ps2dev->flags & (PS2_FLAG_ACK | PS2_FLAG_CMD))
wake_up(&ps2dev->wait);
/* reset all flags except last nack */
ps2dev->flags &= PS2_FLAG_NAK;
}
EXPORT_SYMBOL(ps2_cmd_aborted);
| gpl-2.0 |
NinjahMeh/android_kernel_huawei_angler | arch/mips/pci/fixup-fuloong2e.c | 4350 | 6010 | /*
* Copyright (C) 2004 ICT CAS
* Author: Li xiaoyu, ICT CAS
* lixy@ict.ac.cn
*
* Copyright (C) 2007 Lemote, Inc. & Institute of Computing Technology
* Author: Fuxin Zhang, zhangfx@lemote.com
*
* 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.
*/
#include <linux/init.h>
#include <linux/pci.h>
#include <loongson.h>
/* South bridge slot number is set by the pci probe process */
static u8 sb_slot = 5;
int __init pcibios_map_irq(const struct pci_dev *dev, u8 slot, u8 pin)
{
int irq = 0;
if (slot == sb_slot) {
switch (PCI_FUNC(dev->devfn)) {
case 2:
irq = 10;
break;
case 3:
irq = 11;
break;
case 5:
irq = 9;
break;
}
} else {
irq = LOONGSON_IRQ_BASE + 25 + pin;
}
return irq;
}
/* Do platform specific device initialization at pci_enable_device() time */
int pcibios_plat_dev_init(struct pci_dev *dev)
{
return 0;
}
static void loongson2e_nec_fixup(struct pci_dev *pdev)
{
unsigned int val;
/* Configures port 1, 2, 3, 4 to be validate*/
pci_read_config_dword(pdev, 0xe0, &val);
pci_write_config_dword(pdev, 0xe0, (val & ~7) | 0x4);
/* System clock is 48-MHz Oscillator. */
pci_write_config_dword(pdev, 0xe4, 1 << 5);
}
static void loongson2e_686b_func0_fixup(struct pci_dev *pdev)
{
unsigned char c;
sb_slot = PCI_SLOT(pdev->devfn);
printk(KERN_INFO "via686b fix: ISA bridge\n");
/* Enable I/O Recovery time */
pci_write_config_byte(pdev, 0x40, 0x08);
/* Enable ISA refresh */
pci_write_config_byte(pdev, 0x41, 0x01);
/* disable ISA line buffer */
pci_write_config_byte(pdev, 0x45, 0x00);
/* Gate INTR, and flush line buffer */
pci_write_config_byte(pdev, 0x46, 0xe0);
/* Disable PCI Delay Transaction, Enable EISA ports 4D0/4D1. */
/* pci_write_config_byte(pdev, 0x47, 0x20); */
/*
* enable PCI Delay Transaction, Enable EISA ports 4D0/4D1.
* enable time-out timer
*/
pci_write_config_byte(pdev, 0x47, 0xe6);
/*
* enable level trigger on pci irqs: 9,10,11,13
* important! without this PCI interrupts won't work
*/
outb(0x2e, 0x4d1);
/* 512 K PCI Decode */
pci_write_config_byte(pdev, 0x48, 0x01);
/* Wait for PGNT before grant to ISA Master/DMA */
pci_write_config_byte(pdev, 0x4a, 0x84);
/*
* Plug'n'Play
*
* Parallel DRQ 3, Floppy DRQ 2 (default)
*/
pci_write_config_byte(pdev, 0x50, 0x0e);
/*
* IRQ Routing for Floppy and Parallel port
*
* IRQ 6 for floppy, IRQ 7 for parallel port
*/
pci_write_config_byte(pdev, 0x51, 0x76);
/* IRQ Routing for serial ports (take IRQ 3 and 4) */
pci_write_config_byte(pdev, 0x52, 0x34);
/* All IRQ's level triggered. */
pci_write_config_byte(pdev, 0x54, 0x00);
/* route PIRQA-D irq */
pci_write_config_byte(pdev, 0x55, 0x90); /* bit 7-4, PIRQA */
pci_write_config_byte(pdev, 0x56, 0xba); /* bit 7-4, PIRQC; */
/* 3-0, PIRQB */
pci_write_config_byte(pdev, 0x57, 0xd0); /* bit 7-4, PIRQD */
/* enable function 5/6, audio/modem */
pci_read_config_byte(pdev, 0x85, &c);
c &= ~(0x3 << 2);
pci_write_config_byte(pdev, 0x85, c);
printk(KERN_INFO"via686b fix: ISA bridge done\n");
}
static void loongson2e_686b_func1_fixup(struct pci_dev *pdev)
{
printk(KERN_INFO"via686b fix: IDE\n");
/* Modify IDE controller setup */
pci_write_config_byte(pdev, PCI_LATENCY_TIMER, 48);
pci_write_config_byte(pdev, PCI_COMMAND,
PCI_COMMAND_IO | PCI_COMMAND_MEMORY |
PCI_COMMAND_MASTER);
pci_write_config_byte(pdev, 0x40, 0x0b);
/* legacy mode */
pci_write_config_byte(pdev, 0x42, 0x09);
#if 1/* play safe, otherwise we may see notebook's usb keyboard lockup */
/* disable read prefetch/write post buffers */
pci_write_config_byte(pdev, 0x41, 0x02);
/* use 3/4 as fifo thresh hold */
pci_write_config_byte(pdev, 0x43, 0x0a);
pci_write_config_byte(pdev, 0x44, 0x00);
pci_write_config_byte(pdev, 0x45, 0x00);
#else
pci_write_config_byte(pdev, 0x41, 0xc2);
pci_write_config_byte(pdev, 0x43, 0x35);
pci_write_config_byte(pdev, 0x44, 0x1c);
pci_write_config_byte(pdev, 0x45, 0x10);
#endif
printk(KERN_INFO"via686b fix: IDE done\n");
}
static void loongson2e_686b_func2_fixup(struct pci_dev *pdev)
{
/* irq routing */
pci_write_config_byte(pdev, PCI_INTERRUPT_LINE, 10);
}
static void loongson2e_686b_func3_fixup(struct pci_dev *pdev)
{
/* irq routing */
pci_write_config_byte(pdev, PCI_INTERRUPT_LINE, 11);
}
static void loongson2e_686b_func5_fixup(struct pci_dev *pdev)
{
unsigned int val;
unsigned char c;
/* enable IO */
pci_write_config_byte(pdev, PCI_COMMAND,
PCI_COMMAND_IO | PCI_COMMAND_MEMORY |
PCI_COMMAND_MASTER);
pci_read_config_dword(pdev, 0x4, &val);
pci_write_config_dword(pdev, 0x4, val | 1);
/* route ac97 IRQ */
pci_write_config_byte(pdev, 0x3c, 9);
pci_read_config_byte(pdev, 0x8, &c);
/* link control: enable link & SGD PCM output */
pci_write_config_byte(pdev, 0x41, 0xcc);
/* disable game port, FM, midi, sb, enable write to reg2c-2f */
pci_write_config_byte(pdev, 0x42, 0x20);
/* we are using Avance logic codec */
pci_write_config_word(pdev, 0x2c, 0x1005);
pci_write_config_word(pdev, 0x2e, 0x4710);
pci_read_config_dword(pdev, 0x2c, &val);
pci_write_config_byte(pdev, 0x42, 0x0);
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C686,
loongson2e_686b_func0_fixup);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C586_1,
loongson2e_686b_func1_fixup);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C586_2,
loongson2e_686b_func2_fixup);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C586_3,
loongson2e_686b_func3_fixup);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C686_5,
loongson2e_686b_func5_fixup);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_NEC, PCI_DEVICE_ID_NEC_USB,
loongson2e_nec_fixup);
| gpl-2.0 |
nikhiljan93/sony_yuga_kernel | sound/pci/emu10k1/emupcm.c | 4862 | 58738 | /*
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
* Creative Labs, Inc.
* Routines for control of EMU10K1 chips / PCM routines
* Multichannel PCM support Copyright (c) Lee Revell <rlrevell@joe-job.com>
*
* BUGS:
* --
*
* TODO:
* --
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/time.h>
#include <linux/init.h>
#include <sound/core.h>
#include <sound/emu10k1.h>
static void snd_emu10k1_pcm_interrupt(struct snd_emu10k1 *emu,
struct snd_emu10k1_voice *voice)
{
struct snd_emu10k1_pcm *epcm;
if ((epcm = voice->epcm) == NULL)
return;
if (epcm->substream == NULL)
return;
#if 0
printk(KERN_DEBUG "IRQ: position = 0x%x, period = 0x%x, size = 0x%x\n",
epcm->substream->runtime->hw->pointer(emu, epcm->substream),
snd_pcm_lib_period_bytes(epcm->substream),
snd_pcm_lib_buffer_bytes(epcm->substream));
#endif
snd_pcm_period_elapsed(epcm->substream);
}
static void snd_emu10k1_pcm_ac97adc_interrupt(struct snd_emu10k1 *emu,
unsigned int status)
{
#if 0
if (status & IPR_ADCBUFHALFFULL) {
if (emu->pcm_capture_substream->runtime->mode == SNDRV_PCM_MODE_FRAME)
return;
}
#endif
snd_pcm_period_elapsed(emu->pcm_capture_substream);
}
static void snd_emu10k1_pcm_ac97mic_interrupt(struct snd_emu10k1 *emu,
unsigned int status)
{
#if 0
if (status & IPR_MICBUFHALFFULL) {
if (emu->pcm_capture_mic_substream->runtime->mode == SNDRV_PCM_MODE_FRAME)
return;
}
#endif
snd_pcm_period_elapsed(emu->pcm_capture_mic_substream);
}
static void snd_emu10k1_pcm_efx_interrupt(struct snd_emu10k1 *emu,
unsigned int status)
{
#if 0
if (status & IPR_EFXBUFHALFFULL) {
if (emu->pcm_capture_efx_substream->runtime->mode == SNDRV_PCM_MODE_FRAME)
return;
}
#endif
snd_pcm_period_elapsed(emu->pcm_capture_efx_substream);
}
static snd_pcm_uframes_t snd_emu10k1_efx_playback_pointer(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_emu10k1_pcm *epcm = runtime->private_data;
unsigned int ptr;
if (!epcm->running)
return 0;
ptr = snd_emu10k1_ptr_read(emu, CCCA, epcm->voices[0]->number) & 0x00ffffff;
ptr += runtime->buffer_size;
ptr -= epcm->ccca_start_addr;
ptr %= runtime->buffer_size;
return ptr;
}
static int snd_emu10k1_pcm_channel_alloc(struct snd_emu10k1_pcm * epcm, int voices)
{
int err, i;
if (epcm->voices[1] != NULL && voices < 2) {
snd_emu10k1_voice_free(epcm->emu, epcm->voices[1]);
epcm->voices[1] = NULL;
}
for (i = 0; i < voices; i++) {
if (epcm->voices[i] == NULL)
break;
}
if (i == voices)
return 0; /* already allocated */
for (i = 0; i < ARRAY_SIZE(epcm->voices); i++) {
if (epcm->voices[i]) {
snd_emu10k1_voice_free(epcm->emu, epcm->voices[i]);
epcm->voices[i] = NULL;
}
}
err = snd_emu10k1_voice_alloc(epcm->emu,
epcm->type == PLAYBACK_EMUVOICE ? EMU10K1_PCM : EMU10K1_EFX,
voices,
&epcm->voices[0]);
if (err < 0)
return err;
epcm->voices[0]->epcm = epcm;
if (voices > 1) {
for (i = 1; i < voices; i++) {
epcm->voices[i] = &epcm->emu->voices[epcm->voices[0]->number + i];
epcm->voices[i]->epcm = epcm;
}
}
if (epcm->extra == NULL) {
err = snd_emu10k1_voice_alloc(epcm->emu,
epcm->type == PLAYBACK_EMUVOICE ? EMU10K1_PCM : EMU10K1_EFX,
1,
&epcm->extra);
if (err < 0) {
/*
printk(KERN_DEBUG "pcm_channel_alloc: "
"failed extra: voices=%d, frame=%d\n",
voices, frame);
*/
for (i = 0; i < voices; i++) {
snd_emu10k1_voice_free(epcm->emu, epcm->voices[i]);
epcm->voices[i] = NULL;
}
return err;
}
epcm->extra->epcm = epcm;
epcm->extra->interrupt = snd_emu10k1_pcm_interrupt;
}
return 0;
}
static unsigned int capture_period_sizes[31] = {
384, 448, 512, 640,
384*2, 448*2, 512*2, 640*2,
384*4, 448*4, 512*4, 640*4,
384*8, 448*8, 512*8, 640*8,
384*16, 448*16, 512*16, 640*16,
384*32, 448*32, 512*32, 640*32,
384*64, 448*64, 512*64, 640*64,
384*128,448*128,512*128
};
static struct snd_pcm_hw_constraint_list hw_constraints_capture_period_sizes = {
.count = 31,
.list = capture_period_sizes,
.mask = 0
};
static unsigned int capture_rates[8] = {
8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000
};
static struct snd_pcm_hw_constraint_list hw_constraints_capture_rates = {
.count = 8,
.list = capture_rates,
.mask = 0
};
static unsigned int snd_emu10k1_capture_rate_reg(unsigned int rate)
{
switch (rate) {
case 8000: return ADCCR_SAMPLERATE_8;
case 11025: return ADCCR_SAMPLERATE_11;
case 16000: return ADCCR_SAMPLERATE_16;
case 22050: return ADCCR_SAMPLERATE_22;
case 24000: return ADCCR_SAMPLERATE_24;
case 32000: return ADCCR_SAMPLERATE_32;
case 44100: return ADCCR_SAMPLERATE_44;
case 48000: return ADCCR_SAMPLERATE_48;
default:
snd_BUG();
return ADCCR_SAMPLERATE_8;
}
}
static unsigned int snd_emu10k1_audigy_capture_rate_reg(unsigned int rate)
{
switch (rate) {
case 8000: return A_ADCCR_SAMPLERATE_8;
case 11025: return A_ADCCR_SAMPLERATE_11;
case 12000: return A_ADCCR_SAMPLERATE_12; /* really supported? */
case 16000: return ADCCR_SAMPLERATE_16;
case 22050: return ADCCR_SAMPLERATE_22;
case 24000: return ADCCR_SAMPLERATE_24;
case 32000: return ADCCR_SAMPLERATE_32;
case 44100: return ADCCR_SAMPLERATE_44;
case 48000: return ADCCR_SAMPLERATE_48;
default:
snd_BUG();
return A_ADCCR_SAMPLERATE_8;
}
}
static unsigned int emu10k1_calc_pitch_target(unsigned int rate)
{
unsigned int pitch_target;
pitch_target = (rate << 8) / 375;
pitch_target = (pitch_target >> 1) + (pitch_target & 1);
return pitch_target;
}
#define PITCH_48000 0x00004000
#define PITCH_96000 0x00008000
#define PITCH_85000 0x00007155
#define PITCH_80726 0x00006ba2
#define PITCH_67882 0x00005a82
#define PITCH_57081 0x00004c1c
static unsigned int emu10k1_select_interprom(unsigned int pitch_target)
{
if (pitch_target == PITCH_48000)
return CCCA_INTERPROM_0;
else if (pitch_target < PITCH_48000)
return CCCA_INTERPROM_1;
else if (pitch_target >= PITCH_96000)
return CCCA_INTERPROM_0;
else if (pitch_target >= PITCH_85000)
return CCCA_INTERPROM_6;
else if (pitch_target >= PITCH_80726)
return CCCA_INTERPROM_5;
else if (pitch_target >= PITCH_67882)
return CCCA_INTERPROM_4;
else if (pitch_target >= PITCH_57081)
return CCCA_INTERPROM_3;
else
return CCCA_INTERPROM_2;
}
/*
* calculate cache invalidate size
*
* stereo: channel is stereo
* w_16: using 16bit samples
*
* returns: cache invalidate size in samples
*/
static inline int emu10k1_ccis(int stereo, int w_16)
{
if (w_16) {
return stereo ? 24 : 26;
} else {
return stereo ? 24*2 : 26*2;
}
}
static void snd_emu10k1_pcm_init_voice(struct snd_emu10k1 *emu,
int master, int extra,
struct snd_emu10k1_voice *evoice,
unsigned int start_addr,
unsigned int end_addr,
struct snd_emu10k1_pcm_mixer *mix)
{
struct snd_pcm_substream *substream = evoice->epcm->substream;
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned int silent_page, tmp;
int voice, stereo, w_16;
unsigned char attn, send_amount[8];
unsigned char send_routing[8];
unsigned long flags;
unsigned int pitch_target;
unsigned int ccis;
voice = evoice->number;
stereo = runtime->channels == 2;
w_16 = snd_pcm_format_width(runtime->format) == 16;
if (!extra && stereo) {
start_addr >>= 1;
end_addr >>= 1;
}
if (w_16) {
start_addr >>= 1;
end_addr >>= 1;
}
spin_lock_irqsave(&emu->reg_lock, flags);
/* volume parameters */
if (extra) {
attn = 0;
memset(send_routing, 0, sizeof(send_routing));
send_routing[0] = 0;
send_routing[1] = 1;
send_routing[2] = 2;
send_routing[3] = 3;
memset(send_amount, 0, sizeof(send_amount));
} else {
/* mono, left, right (master voice = left) */
tmp = stereo ? (master ? 1 : 2) : 0;
memcpy(send_routing, &mix->send_routing[tmp][0], 8);
memcpy(send_amount, &mix->send_volume[tmp][0], 8);
}
ccis = emu10k1_ccis(stereo, w_16);
if (master) {
evoice->epcm->ccca_start_addr = start_addr + ccis;
if (extra) {
start_addr += ccis;
end_addr += ccis + emu->delay_pcm_irq;
}
if (stereo && !extra) {
snd_emu10k1_ptr_write(emu, CPF, voice, CPF_STEREO_MASK);
snd_emu10k1_ptr_write(emu, CPF, (voice + 1), CPF_STEREO_MASK);
} else {
snd_emu10k1_ptr_write(emu, CPF, voice, 0);
}
}
/* setup routing */
if (emu->audigy) {
snd_emu10k1_ptr_write(emu, A_FXRT1, voice,
snd_emu10k1_compose_audigy_fxrt1(send_routing));
snd_emu10k1_ptr_write(emu, A_FXRT2, voice,
snd_emu10k1_compose_audigy_fxrt2(send_routing));
snd_emu10k1_ptr_write(emu, A_SENDAMOUNTS, voice,
((unsigned int)send_amount[4] << 24) |
((unsigned int)send_amount[5] << 16) |
((unsigned int)send_amount[6] << 8) |
(unsigned int)send_amount[7]);
} else
snd_emu10k1_ptr_write(emu, FXRT, voice,
snd_emu10k1_compose_send_routing(send_routing));
/* Stop CA */
/* Assumption that PT is already 0 so no harm overwriting */
snd_emu10k1_ptr_write(emu, PTRX, voice, (send_amount[0] << 8) | send_amount[1]);
snd_emu10k1_ptr_write(emu, DSL, voice, end_addr | (send_amount[3] << 24));
snd_emu10k1_ptr_write(emu, PSST, voice,
(start_addr + (extra ? emu->delay_pcm_irq : 0)) |
(send_amount[2] << 24));
if (emu->card_capabilities->emu_model)
pitch_target = PITCH_48000; /* Disable interpolators on emu1010 card */
else
pitch_target = emu10k1_calc_pitch_target(runtime->rate);
if (extra)
snd_emu10k1_ptr_write(emu, CCCA, voice, start_addr |
emu10k1_select_interprom(pitch_target) |
(w_16 ? 0 : CCCA_8BITSELECT));
else
snd_emu10k1_ptr_write(emu, CCCA, voice, (start_addr + ccis) |
emu10k1_select_interprom(pitch_target) |
(w_16 ? 0 : CCCA_8BITSELECT));
/* Clear filter delay memory */
snd_emu10k1_ptr_write(emu, Z1, voice, 0);
snd_emu10k1_ptr_write(emu, Z2, voice, 0);
/* invalidate maps */
silent_page = ((unsigned int)emu->silent_page.addr << 1) | MAP_PTI_MASK;
snd_emu10k1_ptr_write(emu, MAPA, voice, silent_page);
snd_emu10k1_ptr_write(emu, MAPB, voice, silent_page);
/* modulation envelope */
snd_emu10k1_ptr_write(emu, CVCF, voice, 0xffff);
snd_emu10k1_ptr_write(emu, VTFT, voice, 0xffff);
snd_emu10k1_ptr_write(emu, ATKHLDM, voice, 0);
snd_emu10k1_ptr_write(emu, DCYSUSM, voice, 0x007f);
snd_emu10k1_ptr_write(emu, LFOVAL1, voice, 0x8000);
snd_emu10k1_ptr_write(emu, LFOVAL2, voice, 0x8000);
snd_emu10k1_ptr_write(emu, FMMOD, voice, 0);
snd_emu10k1_ptr_write(emu, TREMFRQ, voice, 0);
snd_emu10k1_ptr_write(emu, FM2FRQ2, voice, 0);
snd_emu10k1_ptr_write(emu, ENVVAL, voice, 0x8000);
/* volume envelope */
snd_emu10k1_ptr_write(emu, ATKHLDV, voice, 0x7f7f);
snd_emu10k1_ptr_write(emu, ENVVOL, voice, 0x0000);
/* filter envelope */
snd_emu10k1_ptr_write(emu, PEFE_FILTERAMOUNT, voice, 0x7f);
/* pitch envelope */
snd_emu10k1_ptr_write(emu, PEFE_PITCHAMOUNT, voice, 0);
spin_unlock_irqrestore(&emu->reg_lock, flags);
}
static int snd_emu10k1_playback_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_emu10k1_pcm *epcm = runtime->private_data;
int err;
if ((err = snd_emu10k1_pcm_channel_alloc(epcm, params_channels(hw_params))) < 0)
return err;
if ((err = snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params))) < 0)
return err;
if (err > 0) { /* change */
int mapped;
if (epcm->memblk != NULL)
snd_emu10k1_free_pages(emu, epcm->memblk);
epcm->memblk = snd_emu10k1_alloc_pages(emu, substream);
epcm->start_addr = 0;
if (! epcm->memblk)
return -ENOMEM;
mapped = ((struct snd_emu10k1_memblk *)epcm->memblk)->mapped_page;
if (mapped < 0)
return -ENOMEM;
epcm->start_addr = mapped << PAGE_SHIFT;
}
return 0;
}
static int snd_emu10k1_playback_hw_free(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_emu10k1_pcm *epcm;
if (runtime->private_data == NULL)
return 0;
epcm = runtime->private_data;
if (epcm->extra) {
snd_emu10k1_voice_free(epcm->emu, epcm->extra);
epcm->extra = NULL;
}
if (epcm->voices[1]) {
snd_emu10k1_voice_free(epcm->emu, epcm->voices[1]);
epcm->voices[1] = NULL;
}
if (epcm->voices[0]) {
snd_emu10k1_voice_free(epcm->emu, epcm->voices[0]);
epcm->voices[0] = NULL;
}
if (epcm->memblk) {
snd_emu10k1_free_pages(emu, epcm->memblk);
epcm->memblk = NULL;
epcm->start_addr = 0;
}
snd_pcm_lib_free_pages(substream);
return 0;
}
static int snd_emu10k1_efx_playback_hw_free(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_emu10k1_pcm *epcm;
int i;
if (runtime->private_data == NULL)
return 0;
epcm = runtime->private_data;
if (epcm->extra) {
snd_emu10k1_voice_free(epcm->emu, epcm->extra);
epcm->extra = NULL;
}
for (i = 0; i < NUM_EFX_PLAYBACK; i++) {
if (epcm->voices[i]) {
snd_emu10k1_voice_free(epcm->emu, epcm->voices[i]);
epcm->voices[i] = NULL;
}
}
if (epcm->memblk) {
snd_emu10k1_free_pages(emu, epcm->memblk);
epcm->memblk = NULL;
epcm->start_addr = 0;
}
snd_pcm_lib_free_pages(substream);
return 0;
}
static int snd_emu10k1_playback_prepare(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_emu10k1_pcm *epcm = runtime->private_data;
unsigned int start_addr, end_addr;
start_addr = epcm->start_addr;
end_addr = snd_pcm_lib_period_bytes(substream);
if (runtime->channels == 2) {
start_addr >>= 1;
end_addr >>= 1;
}
end_addr += start_addr;
snd_emu10k1_pcm_init_voice(emu, 1, 1, epcm->extra,
start_addr, end_addr, NULL);
start_addr = epcm->start_addr;
end_addr = epcm->start_addr + snd_pcm_lib_buffer_bytes(substream);
snd_emu10k1_pcm_init_voice(emu, 1, 0, epcm->voices[0],
start_addr, end_addr,
&emu->pcm_mixer[substream->number]);
if (epcm->voices[1])
snd_emu10k1_pcm_init_voice(emu, 0, 0, epcm->voices[1],
start_addr, end_addr,
&emu->pcm_mixer[substream->number]);
return 0;
}
static int snd_emu10k1_efx_playback_prepare(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_emu10k1_pcm *epcm = runtime->private_data;
unsigned int start_addr, end_addr;
unsigned int channel_size;
int i;
start_addr = epcm->start_addr;
end_addr = epcm->start_addr + snd_pcm_lib_buffer_bytes(substream);
/*
* the kX driver leaves some space between voices
*/
channel_size = ( end_addr - start_addr ) / NUM_EFX_PLAYBACK;
snd_emu10k1_pcm_init_voice(emu, 1, 1, epcm->extra,
start_addr, start_addr + (channel_size / 2), NULL);
/* only difference with the master voice is we use it for the pointer */
snd_emu10k1_pcm_init_voice(emu, 1, 0, epcm->voices[0],
start_addr, start_addr + channel_size,
&emu->efx_pcm_mixer[0]);
start_addr += channel_size;
for (i = 1; i < NUM_EFX_PLAYBACK; i++) {
snd_emu10k1_pcm_init_voice(emu, 0, 0, epcm->voices[i],
start_addr, start_addr + channel_size,
&emu->efx_pcm_mixer[i]);
start_addr += channel_size;
}
return 0;
}
static struct snd_pcm_hardware snd_emu10k1_efx_playback =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_NONINTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_RESUME |
SNDRV_PCM_INFO_MMAP_VALID | SNDRV_PCM_INFO_PAUSE),
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_48000,
.rate_min = 48000,
.rate_max = 48000,
.channels_min = NUM_EFX_PLAYBACK,
.channels_max = NUM_EFX_PLAYBACK,
.buffer_bytes_max = (64*1024),
.period_bytes_min = 64,
.period_bytes_max = (64*1024),
.periods_min = 2,
.periods_max = 2,
.fifo_size = 0,
};
static int snd_emu10k1_capture_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
}
static int snd_emu10k1_capture_hw_free(struct snd_pcm_substream *substream)
{
return snd_pcm_lib_free_pages(substream);
}
static int snd_emu10k1_capture_prepare(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_emu10k1_pcm *epcm = runtime->private_data;
int idx;
/* zeroing the buffer size will stop capture */
snd_emu10k1_ptr_write(emu, epcm->capture_bs_reg, 0, 0);
switch (epcm->type) {
case CAPTURE_AC97ADC:
snd_emu10k1_ptr_write(emu, ADCCR, 0, 0);
break;
case CAPTURE_EFX:
if (emu->audigy) {
snd_emu10k1_ptr_write(emu, A_FXWC1, 0, 0);
snd_emu10k1_ptr_write(emu, A_FXWC2, 0, 0);
} else
snd_emu10k1_ptr_write(emu, FXWC, 0, 0);
break;
default:
break;
}
snd_emu10k1_ptr_write(emu, epcm->capture_ba_reg, 0, runtime->dma_addr);
epcm->capture_bufsize = snd_pcm_lib_buffer_bytes(substream);
epcm->capture_bs_val = 0;
for (idx = 0; idx < 31; idx++) {
if (capture_period_sizes[idx] == epcm->capture_bufsize) {
epcm->capture_bs_val = idx + 1;
break;
}
}
if (epcm->capture_bs_val == 0) {
snd_BUG();
epcm->capture_bs_val++;
}
if (epcm->type == CAPTURE_AC97ADC) {
epcm->capture_cr_val = emu->audigy ? A_ADCCR_LCHANENABLE : ADCCR_LCHANENABLE;
if (runtime->channels > 1)
epcm->capture_cr_val |= emu->audigy ? A_ADCCR_RCHANENABLE : ADCCR_RCHANENABLE;
epcm->capture_cr_val |= emu->audigy ?
snd_emu10k1_audigy_capture_rate_reg(runtime->rate) :
snd_emu10k1_capture_rate_reg(runtime->rate);
}
return 0;
}
static void snd_emu10k1_playback_invalidate_cache(struct snd_emu10k1 *emu, int extra, struct snd_emu10k1_voice *evoice)
{
struct snd_pcm_runtime *runtime;
unsigned int voice, stereo, i, ccis, cra = 64, cs, sample;
if (evoice == NULL)
return;
runtime = evoice->epcm->substream->runtime;
voice = evoice->number;
stereo = (!extra && runtime->channels == 2);
sample = snd_pcm_format_width(runtime->format) == 16 ? 0 : 0x80808080;
ccis = emu10k1_ccis(stereo, sample == 0);
/* set cs to 2 * number of cache registers beside the invalidated */
cs = (sample == 0) ? (32-ccis) : (64-ccis+1) >> 1;
if (cs > 16) cs = 16;
for (i = 0; i < cs; i++) {
snd_emu10k1_ptr_write(emu, CD0 + i, voice, sample);
if (stereo) {
snd_emu10k1_ptr_write(emu, CD0 + i, voice + 1, sample);
}
}
/* reset cache */
snd_emu10k1_ptr_write(emu, CCR_CACHEINVALIDSIZE, voice, 0);
snd_emu10k1_ptr_write(emu, CCR_READADDRESS, voice, cra);
if (stereo) {
snd_emu10k1_ptr_write(emu, CCR_CACHEINVALIDSIZE, voice + 1, 0);
snd_emu10k1_ptr_write(emu, CCR_READADDRESS, voice + 1, cra);
}
/* fill cache */
snd_emu10k1_ptr_write(emu, CCR_CACHEINVALIDSIZE, voice, ccis);
if (stereo) {
snd_emu10k1_ptr_write(emu, CCR_CACHEINVALIDSIZE, voice+1, ccis);
}
}
static void snd_emu10k1_playback_prepare_voice(struct snd_emu10k1 *emu, struct snd_emu10k1_voice *evoice,
int master, int extra,
struct snd_emu10k1_pcm_mixer *mix)
{
struct snd_pcm_substream *substream;
struct snd_pcm_runtime *runtime;
unsigned int attn, vattn;
unsigned int voice, tmp;
if (evoice == NULL) /* skip second voice for mono */
return;
substream = evoice->epcm->substream;
runtime = substream->runtime;
voice = evoice->number;
attn = extra ? 0 : 0x00ff;
tmp = runtime->channels == 2 ? (master ? 1 : 2) : 0;
vattn = mix != NULL ? (mix->attn[tmp] << 16) : 0;
snd_emu10k1_ptr_write(emu, IFATN, voice, attn);
snd_emu10k1_ptr_write(emu, VTFT, voice, vattn | 0xffff);
snd_emu10k1_ptr_write(emu, CVCF, voice, vattn | 0xffff);
snd_emu10k1_ptr_write(emu, DCYSUSV, voice, 0x7f7f);
snd_emu10k1_voice_clear_loop_stop(emu, voice);
}
static void snd_emu10k1_playback_trigger_voice(struct snd_emu10k1 *emu, struct snd_emu10k1_voice *evoice, int master, int extra)
{
struct snd_pcm_substream *substream;
struct snd_pcm_runtime *runtime;
unsigned int voice, pitch, pitch_target;
if (evoice == NULL) /* skip second voice for mono */
return;
substream = evoice->epcm->substream;
runtime = substream->runtime;
voice = evoice->number;
pitch = snd_emu10k1_rate_to_pitch(runtime->rate) >> 8;
if (emu->card_capabilities->emu_model)
pitch_target = PITCH_48000; /* Disable interpolators on emu1010 card */
else
pitch_target = emu10k1_calc_pitch_target(runtime->rate);
snd_emu10k1_ptr_write(emu, PTRX_PITCHTARGET, voice, pitch_target);
if (master || evoice->epcm->type == PLAYBACK_EFX)
snd_emu10k1_ptr_write(emu, CPF_CURRENTPITCH, voice, pitch_target);
snd_emu10k1_ptr_write(emu, IP, voice, pitch);
if (extra)
snd_emu10k1_voice_intr_enable(emu, voice);
}
static void snd_emu10k1_playback_stop_voice(struct snd_emu10k1 *emu, struct snd_emu10k1_voice *evoice)
{
unsigned int voice;
if (evoice == NULL)
return;
voice = evoice->number;
snd_emu10k1_voice_intr_disable(emu, voice);
snd_emu10k1_ptr_write(emu, PTRX_PITCHTARGET, voice, 0);
snd_emu10k1_ptr_write(emu, CPF_CURRENTPITCH, voice, 0);
snd_emu10k1_ptr_write(emu, IFATN, voice, 0xffff);
snd_emu10k1_ptr_write(emu, VTFT, voice, 0xffff);
snd_emu10k1_ptr_write(emu, CVCF, voice, 0xffff);
snd_emu10k1_ptr_write(emu, IP, voice, 0);
}
static inline void snd_emu10k1_playback_mangle_extra(struct snd_emu10k1 *emu,
struct snd_emu10k1_pcm *epcm,
struct snd_pcm_substream *substream,
struct snd_pcm_runtime *runtime)
{
unsigned int ptr, period_pos;
/* try to sychronize the current position for the interrupt
source voice */
period_pos = runtime->status->hw_ptr - runtime->hw_ptr_interrupt;
period_pos %= runtime->period_size;
ptr = snd_emu10k1_ptr_read(emu, CCCA, epcm->extra->number);
ptr &= ~0x00ffffff;
ptr |= epcm->ccca_start_addr + period_pos;
snd_emu10k1_ptr_write(emu, CCCA, epcm->extra->number, ptr);
}
static int snd_emu10k1_playback_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_emu10k1_pcm *epcm = runtime->private_data;
struct snd_emu10k1_pcm_mixer *mix;
int result = 0;
/*
printk(KERN_DEBUG "trigger - emu10k1 = 0x%x, cmd = %i, pointer = %i\n",
(int)emu, cmd, substream->ops->pointer(substream))
*/
spin_lock(&emu->reg_lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
snd_emu10k1_playback_invalidate_cache(emu, 1, epcm->extra); /* do we need this? */
snd_emu10k1_playback_invalidate_cache(emu, 0, epcm->voices[0]);
/* follow thru */
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_RESUME:
if (cmd == SNDRV_PCM_TRIGGER_PAUSE_RELEASE)
snd_emu10k1_playback_mangle_extra(emu, epcm, substream, runtime);
mix = &emu->pcm_mixer[substream->number];
snd_emu10k1_playback_prepare_voice(emu, epcm->voices[0], 1, 0, mix);
snd_emu10k1_playback_prepare_voice(emu, epcm->voices[1], 0, 0, mix);
snd_emu10k1_playback_prepare_voice(emu, epcm->extra, 1, 1, NULL);
snd_emu10k1_playback_trigger_voice(emu, epcm->voices[0], 1, 0);
snd_emu10k1_playback_trigger_voice(emu, epcm->voices[1], 0, 0);
snd_emu10k1_playback_trigger_voice(emu, epcm->extra, 1, 1);
epcm->running = 1;
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_SUSPEND:
epcm->running = 0;
snd_emu10k1_playback_stop_voice(emu, epcm->voices[0]);
snd_emu10k1_playback_stop_voice(emu, epcm->voices[1]);
snd_emu10k1_playback_stop_voice(emu, epcm->extra);
break;
default:
result = -EINVAL;
break;
}
spin_unlock(&emu->reg_lock);
return result;
}
static int snd_emu10k1_capture_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_emu10k1_pcm *epcm = runtime->private_data;
int result = 0;
spin_lock(&emu->reg_lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
/* hmm this should cause full and half full interrupt to be raised? */
outl(epcm->capture_ipr, emu->port + IPR);
snd_emu10k1_intr_enable(emu, epcm->capture_inte);
/*
printk(KERN_DEBUG "adccr = 0x%x, adcbs = 0x%x\n",
epcm->adccr, epcm->adcbs);
*/
switch (epcm->type) {
case CAPTURE_AC97ADC:
snd_emu10k1_ptr_write(emu, ADCCR, 0, epcm->capture_cr_val);
break;
case CAPTURE_EFX:
if (emu->audigy) {
snd_emu10k1_ptr_write(emu, A_FXWC1, 0, epcm->capture_cr_val);
snd_emu10k1_ptr_write(emu, A_FXWC2, 0, epcm->capture_cr_val2);
snd_printdd("cr_val=0x%x, cr_val2=0x%x\n", epcm->capture_cr_val, epcm->capture_cr_val2);
} else
snd_emu10k1_ptr_write(emu, FXWC, 0, epcm->capture_cr_val);
break;
default:
break;
}
snd_emu10k1_ptr_write(emu, epcm->capture_bs_reg, 0, epcm->capture_bs_val);
epcm->running = 1;
epcm->first_ptr = 1;
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
epcm->running = 0;
snd_emu10k1_intr_disable(emu, epcm->capture_inte);
outl(epcm->capture_ipr, emu->port + IPR);
snd_emu10k1_ptr_write(emu, epcm->capture_bs_reg, 0, 0);
switch (epcm->type) {
case CAPTURE_AC97ADC:
snd_emu10k1_ptr_write(emu, ADCCR, 0, 0);
break;
case CAPTURE_EFX:
if (emu->audigy) {
snd_emu10k1_ptr_write(emu, A_FXWC1, 0, 0);
snd_emu10k1_ptr_write(emu, A_FXWC2, 0, 0);
} else
snd_emu10k1_ptr_write(emu, FXWC, 0, 0);
break;
default:
break;
}
break;
default:
result = -EINVAL;
}
spin_unlock(&emu->reg_lock);
return result;
}
static snd_pcm_uframes_t snd_emu10k1_playback_pointer(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_emu10k1_pcm *epcm = runtime->private_data;
unsigned int ptr;
if (!epcm->running)
return 0;
ptr = snd_emu10k1_ptr_read(emu, CCCA, epcm->voices[0]->number) & 0x00ffffff;
#if 0 /* Perex's code */
ptr += runtime->buffer_size;
ptr -= epcm->ccca_start_addr;
ptr %= runtime->buffer_size;
#else /* EMU10K1 Open Source code from Creative */
if (ptr < epcm->ccca_start_addr)
ptr += runtime->buffer_size - epcm->ccca_start_addr;
else {
ptr -= epcm->ccca_start_addr;
if (ptr >= runtime->buffer_size)
ptr -= runtime->buffer_size;
}
#endif
/*
printk(KERN_DEBUG
"ptr = 0x%lx, buffer_size = 0x%lx, period_size = 0x%lx\n",
(long)ptr, (long)runtime->buffer_size,
(long)runtime->period_size);
*/
return ptr;
}
static int snd_emu10k1_efx_playback_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_emu10k1_pcm *epcm = runtime->private_data;
int i;
int result = 0;
spin_lock(&emu->reg_lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
/* prepare voices */
for (i = 0; i < NUM_EFX_PLAYBACK; i++) {
snd_emu10k1_playback_invalidate_cache(emu, 0, epcm->voices[i]);
}
snd_emu10k1_playback_invalidate_cache(emu, 1, epcm->extra);
/* follow thru */
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_RESUME:
snd_emu10k1_playback_prepare_voice(emu, epcm->extra, 1, 1, NULL);
snd_emu10k1_playback_prepare_voice(emu, epcm->voices[0], 0, 0,
&emu->efx_pcm_mixer[0]);
for (i = 1; i < NUM_EFX_PLAYBACK; i++)
snd_emu10k1_playback_prepare_voice(emu, epcm->voices[i], 0, 0,
&emu->efx_pcm_mixer[i]);
snd_emu10k1_playback_trigger_voice(emu, epcm->voices[0], 0, 0);
snd_emu10k1_playback_trigger_voice(emu, epcm->extra, 1, 1);
for (i = 1; i < NUM_EFX_PLAYBACK; i++)
snd_emu10k1_playback_trigger_voice(emu, epcm->voices[i], 0, 0);
epcm->running = 1;
break;
case SNDRV_PCM_TRIGGER_SUSPEND:
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
epcm->running = 0;
for (i = 0; i < NUM_EFX_PLAYBACK; i++) {
snd_emu10k1_playback_stop_voice(emu, epcm->voices[i]);
}
snd_emu10k1_playback_stop_voice(emu, epcm->extra);
break;
default:
result = -EINVAL;
break;
}
spin_unlock(&emu->reg_lock);
return result;
}
static snd_pcm_uframes_t snd_emu10k1_capture_pointer(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_emu10k1_pcm *epcm = runtime->private_data;
unsigned int ptr;
if (!epcm->running)
return 0;
if (epcm->first_ptr) {
udelay(50); /* hack, it takes awhile until capture is started */
epcm->first_ptr = 0;
}
ptr = snd_emu10k1_ptr_read(emu, epcm->capture_idx_reg, 0) & 0x0000ffff;
return bytes_to_frames(runtime, ptr);
}
/*
* Playback support device description
*/
static struct snd_pcm_hardware snd_emu10k1_playback =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_RESUME |
SNDRV_PCM_INFO_MMAP_VALID | SNDRV_PCM_INFO_PAUSE),
.formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_96000,
.rate_min = 4000,
.rate_max = 96000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 64,
.period_bytes_max = (128*1024),
.periods_min = 1,
.periods_max = 1024,
.fifo_size = 0,
};
/*
* Capture support device description
*/
static struct snd_pcm_hardware snd_emu10k1_capture =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_RESUME |
SNDRV_PCM_INFO_MMAP_VALID),
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_8000_48000,
.rate_min = 8000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = (64*1024),
.period_bytes_min = 384,
.period_bytes_max = (64*1024),
.periods_min = 2,
.periods_max = 2,
.fifo_size = 0,
};
static struct snd_pcm_hardware snd_emu10k1_capture_efx =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_RESUME |
SNDRV_PCM_INFO_MMAP_VALID),
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000 |
SNDRV_PCM_RATE_88200 | SNDRV_PCM_RATE_96000 |
SNDRV_PCM_RATE_176400 | SNDRV_PCM_RATE_192000,
.rate_min = 44100,
.rate_max = 192000,
.channels_min = 8,
.channels_max = 8,
.buffer_bytes_max = (64*1024),
.period_bytes_min = 384,
.period_bytes_max = (64*1024),
.periods_min = 2,
.periods_max = 2,
.fifo_size = 0,
};
/*
*
*/
static void snd_emu10k1_pcm_mixer_notify1(struct snd_emu10k1 *emu, struct snd_kcontrol *kctl, int idx, int activate)
{
struct snd_ctl_elem_id id;
if (! kctl)
return;
if (activate)
kctl->vd[idx].access &= ~SNDRV_CTL_ELEM_ACCESS_INACTIVE;
else
kctl->vd[idx].access |= SNDRV_CTL_ELEM_ACCESS_INACTIVE;
snd_ctl_notify(emu->card, SNDRV_CTL_EVENT_MASK_VALUE |
SNDRV_CTL_EVENT_MASK_INFO,
snd_ctl_build_ioff(&id, kctl, idx));
}
static void snd_emu10k1_pcm_mixer_notify(struct snd_emu10k1 *emu, int idx, int activate)
{
snd_emu10k1_pcm_mixer_notify1(emu, emu->ctl_send_routing, idx, activate);
snd_emu10k1_pcm_mixer_notify1(emu, emu->ctl_send_volume, idx, activate);
snd_emu10k1_pcm_mixer_notify1(emu, emu->ctl_attn, idx, activate);
}
static void snd_emu10k1_pcm_efx_mixer_notify(struct snd_emu10k1 *emu, int idx, int activate)
{
snd_emu10k1_pcm_mixer_notify1(emu, emu->ctl_efx_send_routing, idx, activate);
snd_emu10k1_pcm_mixer_notify1(emu, emu->ctl_efx_send_volume, idx, activate);
snd_emu10k1_pcm_mixer_notify1(emu, emu->ctl_efx_attn, idx, activate);
}
static void snd_emu10k1_pcm_free_substream(struct snd_pcm_runtime *runtime)
{
kfree(runtime->private_data);
}
static int snd_emu10k1_efx_playback_close(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_emu10k1_pcm_mixer *mix;
int i;
for (i = 0; i < NUM_EFX_PLAYBACK; i++) {
mix = &emu->efx_pcm_mixer[i];
mix->epcm = NULL;
snd_emu10k1_pcm_efx_mixer_notify(emu, i, 0);
}
return 0;
}
static int snd_emu10k1_efx_playback_open(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_emu10k1_pcm *epcm;
struct snd_emu10k1_pcm_mixer *mix;
struct snd_pcm_runtime *runtime = substream->runtime;
int i;
epcm = kzalloc(sizeof(*epcm), GFP_KERNEL);
if (epcm == NULL)
return -ENOMEM;
epcm->emu = emu;
epcm->type = PLAYBACK_EFX;
epcm->substream = substream;
emu->pcm_playback_efx_substream = substream;
runtime->private_data = epcm;
runtime->private_free = snd_emu10k1_pcm_free_substream;
runtime->hw = snd_emu10k1_efx_playback;
for (i = 0; i < NUM_EFX_PLAYBACK; i++) {
mix = &emu->efx_pcm_mixer[i];
mix->send_routing[0][0] = i;
memset(&mix->send_volume, 0, sizeof(mix->send_volume));
mix->send_volume[0][0] = 255;
mix->attn[0] = 0xffff;
mix->epcm = epcm;
snd_emu10k1_pcm_efx_mixer_notify(emu, i, 1);
}
return 0;
}
static int snd_emu10k1_playback_open(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_emu10k1_pcm *epcm;
struct snd_emu10k1_pcm_mixer *mix;
struct snd_pcm_runtime *runtime = substream->runtime;
int i, err;
epcm = kzalloc(sizeof(*epcm), GFP_KERNEL);
if (epcm == NULL)
return -ENOMEM;
epcm->emu = emu;
epcm->type = PLAYBACK_EMUVOICE;
epcm->substream = substream;
runtime->private_data = epcm;
runtime->private_free = snd_emu10k1_pcm_free_substream;
runtime->hw = snd_emu10k1_playback;
if ((err = snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS)) < 0) {
kfree(epcm);
return err;
}
if ((err = snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_BYTES, 256, UINT_MAX)) < 0) {
kfree(epcm);
return err;
}
err = snd_pcm_hw_rule_noresample(runtime, 48000);
if (err < 0) {
kfree(epcm);
return err;
}
mix = &emu->pcm_mixer[substream->number];
for (i = 0; i < 4; i++)
mix->send_routing[0][i] = mix->send_routing[1][i] = mix->send_routing[2][i] = i;
memset(&mix->send_volume, 0, sizeof(mix->send_volume));
mix->send_volume[0][0] = mix->send_volume[0][1] =
mix->send_volume[1][0] = mix->send_volume[2][1] = 255;
mix->attn[0] = mix->attn[1] = mix->attn[2] = 0xffff;
mix->epcm = epcm;
snd_emu10k1_pcm_mixer_notify(emu, substream->number, 1);
return 0;
}
static int snd_emu10k1_playback_close(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_emu10k1_pcm_mixer *mix = &emu->pcm_mixer[substream->number];
mix->epcm = NULL;
snd_emu10k1_pcm_mixer_notify(emu, substream->number, 0);
return 0;
}
static int snd_emu10k1_capture_open(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_emu10k1_pcm *epcm;
epcm = kzalloc(sizeof(*epcm), GFP_KERNEL);
if (epcm == NULL)
return -ENOMEM;
epcm->emu = emu;
epcm->type = CAPTURE_AC97ADC;
epcm->substream = substream;
epcm->capture_ipr = IPR_ADCBUFFULL|IPR_ADCBUFHALFFULL;
epcm->capture_inte = INTE_ADCBUFENABLE;
epcm->capture_ba_reg = ADCBA;
epcm->capture_bs_reg = ADCBS;
epcm->capture_idx_reg = emu->audigy ? A_ADCIDX : ADCIDX;
runtime->private_data = epcm;
runtime->private_free = snd_emu10k1_pcm_free_substream;
runtime->hw = snd_emu10k1_capture;
emu->capture_interrupt = snd_emu10k1_pcm_ac97adc_interrupt;
emu->pcm_capture_substream = substream;
snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_BYTES, &hw_constraints_capture_period_sizes);
snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_RATE, &hw_constraints_capture_rates);
return 0;
}
static int snd_emu10k1_capture_close(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
emu->capture_interrupt = NULL;
emu->pcm_capture_substream = NULL;
return 0;
}
static int snd_emu10k1_capture_mic_open(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_emu10k1_pcm *epcm;
struct snd_pcm_runtime *runtime = substream->runtime;
epcm = kzalloc(sizeof(*epcm), GFP_KERNEL);
if (epcm == NULL)
return -ENOMEM;
epcm->emu = emu;
epcm->type = CAPTURE_AC97MIC;
epcm->substream = substream;
epcm->capture_ipr = IPR_MICBUFFULL|IPR_MICBUFHALFFULL;
epcm->capture_inte = INTE_MICBUFENABLE;
epcm->capture_ba_reg = MICBA;
epcm->capture_bs_reg = MICBS;
epcm->capture_idx_reg = emu->audigy ? A_MICIDX : MICIDX;
substream->runtime->private_data = epcm;
substream->runtime->private_free = snd_emu10k1_pcm_free_substream;
runtime->hw = snd_emu10k1_capture;
runtime->hw.rates = SNDRV_PCM_RATE_8000;
runtime->hw.rate_min = runtime->hw.rate_max = 8000;
runtime->hw.channels_min = 1;
emu->capture_mic_interrupt = snd_emu10k1_pcm_ac97mic_interrupt;
emu->pcm_capture_mic_substream = substream;
snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_BYTES, &hw_constraints_capture_period_sizes);
return 0;
}
static int snd_emu10k1_capture_mic_close(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
emu->capture_interrupt = NULL;
emu->pcm_capture_mic_substream = NULL;
return 0;
}
static int snd_emu10k1_capture_efx_open(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_emu10k1_pcm *epcm;
struct snd_pcm_runtime *runtime = substream->runtime;
int nefx = emu->audigy ? 64 : 32;
int idx;
epcm = kzalloc(sizeof(*epcm), GFP_KERNEL);
if (epcm == NULL)
return -ENOMEM;
epcm->emu = emu;
epcm->type = CAPTURE_EFX;
epcm->substream = substream;
epcm->capture_ipr = IPR_EFXBUFFULL|IPR_EFXBUFHALFFULL;
epcm->capture_inte = INTE_EFXBUFENABLE;
epcm->capture_ba_reg = FXBA;
epcm->capture_bs_reg = FXBS;
epcm->capture_idx_reg = FXIDX;
substream->runtime->private_data = epcm;
substream->runtime->private_free = snd_emu10k1_pcm_free_substream;
runtime->hw = snd_emu10k1_capture_efx;
runtime->hw.rates = SNDRV_PCM_RATE_48000;
runtime->hw.rate_min = runtime->hw.rate_max = 48000;
spin_lock_irq(&emu->reg_lock);
if (emu->card_capabilities->emu_model) {
/* Nb. of channels has been increased to 16 */
/* TODO
* SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S32_LE
* SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000 |
* SNDRV_PCM_RATE_88200 | SNDRV_PCM_RATE_96000 |
* SNDRV_PCM_RATE_176400 | SNDRV_PCM_RATE_192000
* rate_min = 44100,
* rate_max = 192000,
* channels_min = 16,
* channels_max = 16,
* Need to add mixer control to fix sample rate
*
* There are 32 mono channels of 16bits each.
* 24bit Audio uses 2x channels over 16bit
* 96kHz uses 2x channels over 48kHz
* 192kHz uses 4x channels over 48kHz
* So, for 48kHz 24bit, one has 16 channels
* for 96kHz 24bit, one has 8 channels
* for 192kHz 24bit, one has 4 channels
*
*/
#if 1
switch (emu->emu1010.internal_clock) {
case 0:
/* For 44.1kHz */
runtime->hw.rates = SNDRV_PCM_RATE_44100;
runtime->hw.rate_min = runtime->hw.rate_max = 44100;
runtime->hw.channels_min =
runtime->hw.channels_max = 16;
break;
case 1:
/* For 48kHz */
runtime->hw.rates = SNDRV_PCM_RATE_48000;
runtime->hw.rate_min = runtime->hw.rate_max = 48000;
runtime->hw.channels_min =
runtime->hw.channels_max = 16;
break;
};
#endif
#if 0
/* For 96kHz */
runtime->hw.rates = SNDRV_PCM_RATE_96000;
runtime->hw.rate_min = runtime->hw.rate_max = 96000;
runtime->hw.channels_min = runtime->hw.channels_max = 4;
#endif
#if 0
/* For 192kHz */
runtime->hw.rates = SNDRV_PCM_RATE_192000;
runtime->hw.rate_min = runtime->hw.rate_max = 192000;
runtime->hw.channels_min = runtime->hw.channels_max = 2;
#endif
runtime->hw.formats = SNDRV_PCM_FMTBIT_S32_LE;
/* efx_voices_mask[0] is expected to be zero
* efx_voices_mask[1] is expected to have 32bits set
*/
} else {
runtime->hw.channels_min = runtime->hw.channels_max = 0;
for (idx = 0; idx < nefx; idx++) {
if (emu->efx_voices_mask[idx/32] & (1 << (idx%32))) {
runtime->hw.channels_min++;
runtime->hw.channels_max++;
}
}
}
epcm->capture_cr_val = emu->efx_voices_mask[0];
epcm->capture_cr_val2 = emu->efx_voices_mask[1];
spin_unlock_irq(&emu->reg_lock);
emu->capture_efx_interrupt = snd_emu10k1_pcm_efx_interrupt;
emu->pcm_capture_efx_substream = substream;
snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_BYTES, &hw_constraints_capture_period_sizes);
return 0;
}
static int snd_emu10k1_capture_efx_close(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
emu->capture_interrupt = NULL;
emu->pcm_capture_efx_substream = NULL;
return 0;
}
static struct snd_pcm_ops snd_emu10k1_playback_ops = {
.open = snd_emu10k1_playback_open,
.close = snd_emu10k1_playback_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_emu10k1_playback_hw_params,
.hw_free = snd_emu10k1_playback_hw_free,
.prepare = snd_emu10k1_playback_prepare,
.trigger = snd_emu10k1_playback_trigger,
.pointer = snd_emu10k1_playback_pointer,
.page = snd_pcm_sgbuf_ops_page,
};
static struct snd_pcm_ops snd_emu10k1_capture_ops = {
.open = snd_emu10k1_capture_open,
.close = snd_emu10k1_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_emu10k1_capture_hw_params,
.hw_free = snd_emu10k1_capture_hw_free,
.prepare = snd_emu10k1_capture_prepare,
.trigger = snd_emu10k1_capture_trigger,
.pointer = snd_emu10k1_capture_pointer,
};
/* EFX playback */
static struct snd_pcm_ops snd_emu10k1_efx_playback_ops = {
.open = snd_emu10k1_efx_playback_open,
.close = snd_emu10k1_efx_playback_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_emu10k1_playback_hw_params,
.hw_free = snd_emu10k1_efx_playback_hw_free,
.prepare = snd_emu10k1_efx_playback_prepare,
.trigger = snd_emu10k1_efx_playback_trigger,
.pointer = snd_emu10k1_efx_playback_pointer,
.page = snd_pcm_sgbuf_ops_page,
};
int __devinit snd_emu10k1_pcm(struct snd_emu10k1 * emu, int device, struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
struct snd_pcm_substream *substream;
int err;
if (rpcm)
*rpcm = NULL;
if ((err = snd_pcm_new(emu->card, "emu10k1", device, 32, 1, &pcm)) < 0)
return err;
pcm->private_data = emu;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_emu10k1_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_emu10k1_capture_ops);
pcm->info_flags = 0;
pcm->dev_subclass = SNDRV_PCM_SUBCLASS_GENERIC_MIX;
strcpy(pcm->name, "ADC Capture/Standard PCM Playback");
emu->pcm = pcm;
for (substream = pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream; substream; substream = substream->next)
if ((err = snd_pcm_lib_preallocate_pages(substream, SNDRV_DMA_TYPE_DEV_SG, snd_dma_pci_data(emu->pci), 64*1024, 64*1024)) < 0)
return err;
for (substream = pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream; substream; substream = substream->next)
snd_pcm_lib_preallocate_pages(substream, SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(emu->pci), 64*1024, 64*1024);
if (rpcm)
*rpcm = pcm;
return 0;
}
int __devinit snd_emu10k1_pcm_multi(struct snd_emu10k1 * emu, int device, struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
struct snd_pcm_substream *substream;
int err;
if (rpcm)
*rpcm = NULL;
if ((err = snd_pcm_new(emu->card, "emu10k1", device, 1, 0, &pcm)) < 0)
return err;
pcm->private_data = emu;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_emu10k1_efx_playback_ops);
pcm->info_flags = 0;
pcm->dev_subclass = SNDRV_PCM_SUBCLASS_GENERIC_MIX;
strcpy(pcm->name, "Multichannel Playback");
emu->pcm_multi = pcm;
for (substream = pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream; substream; substream = substream->next)
if ((err = snd_pcm_lib_preallocate_pages(substream, SNDRV_DMA_TYPE_DEV_SG, snd_dma_pci_data(emu->pci), 64*1024, 64*1024)) < 0)
return err;
if (rpcm)
*rpcm = pcm;
return 0;
}
static struct snd_pcm_ops snd_emu10k1_capture_mic_ops = {
.open = snd_emu10k1_capture_mic_open,
.close = snd_emu10k1_capture_mic_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_emu10k1_capture_hw_params,
.hw_free = snd_emu10k1_capture_hw_free,
.prepare = snd_emu10k1_capture_prepare,
.trigger = snd_emu10k1_capture_trigger,
.pointer = snd_emu10k1_capture_pointer,
};
int __devinit snd_emu10k1_pcm_mic(struct snd_emu10k1 * emu, int device, struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
int err;
if (rpcm)
*rpcm = NULL;
if ((err = snd_pcm_new(emu->card, "emu10k1 mic", device, 0, 1, &pcm)) < 0)
return err;
pcm->private_data = emu;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_emu10k1_capture_mic_ops);
pcm->info_flags = 0;
strcpy(pcm->name, "Mic Capture");
emu->pcm_mic = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(emu->pci), 64*1024, 64*1024);
if (rpcm)
*rpcm = pcm;
return 0;
}
static int snd_emu10k1_pcm_efx_voices_mask_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
struct snd_emu10k1 *emu = snd_kcontrol_chip(kcontrol);
int nefx = emu->audigy ? 64 : 32;
uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
uinfo->count = nefx;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 1;
return 0;
}
static int snd_emu10k1_pcm_efx_voices_mask_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_emu10k1 *emu = snd_kcontrol_chip(kcontrol);
int nefx = emu->audigy ? 64 : 32;
int idx;
spin_lock_irq(&emu->reg_lock);
for (idx = 0; idx < nefx; idx++)
ucontrol->value.integer.value[idx] = (emu->efx_voices_mask[idx / 32] & (1 << (idx % 32))) ? 1 : 0;
spin_unlock_irq(&emu->reg_lock);
return 0;
}
static int snd_emu10k1_pcm_efx_voices_mask_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_emu10k1 *emu = snd_kcontrol_chip(kcontrol);
unsigned int nval[2], bits;
int nefx = emu->audigy ? 64 : 32;
int nefxb = emu->audigy ? 7 : 6;
int change, idx;
nval[0] = nval[1] = 0;
for (idx = 0, bits = 0; idx < nefx; idx++)
if (ucontrol->value.integer.value[idx]) {
nval[idx / 32] |= 1 << (idx % 32);
bits++;
}
for (idx = 0; idx < nefxb; idx++)
if (1 << idx == bits)
break;
if (idx >= nefxb)
return -EINVAL;
spin_lock_irq(&emu->reg_lock);
change = (nval[0] != emu->efx_voices_mask[0]) ||
(nval[1] != emu->efx_voices_mask[1]);
emu->efx_voices_mask[0] = nval[0];
emu->efx_voices_mask[1] = nval[1];
spin_unlock_irq(&emu->reg_lock);
return change;
}
static struct snd_kcontrol_new snd_emu10k1_pcm_efx_voices_mask = {
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = "Captured FX8010 Outputs",
.info = snd_emu10k1_pcm_efx_voices_mask_info,
.get = snd_emu10k1_pcm_efx_voices_mask_get,
.put = snd_emu10k1_pcm_efx_voices_mask_put
};
static struct snd_pcm_ops snd_emu10k1_capture_efx_ops = {
.open = snd_emu10k1_capture_efx_open,
.close = snd_emu10k1_capture_efx_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_emu10k1_capture_hw_params,
.hw_free = snd_emu10k1_capture_hw_free,
.prepare = snd_emu10k1_capture_prepare,
.trigger = snd_emu10k1_capture_trigger,
.pointer = snd_emu10k1_capture_pointer,
};
/* EFX playback */
#define INITIAL_TRAM_SHIFT 14
#define INITIAL_TRAM_POS(size) ((((size) / 2) - INITIAL_TRAM_SHIFT) - 1)
static void snd_emu10k1_fx8010_playback_irq(struct snd_emu10k1 *emu, void *private_data)
{
struct snd_pcm_substream *substream = private_data;
snd_pcm_period_elapsed(substream);
}
static void snd_emu10k1_fx8010_playback_tram_poke1(unsigned short *dst_left,
unsigned short *dst_right,
unsigned short *src,
unsigned int count,
unsigned int tram_shift)
{
/*
printk(KERN_DEBUG "tram_poke1: dst_left = 0x%p, dst_right = 0x%p, "
"src = 0x%p, count = 0x%x\n",
dst_left, dst_right, src, count);
*/
if ((tram_shift & 1) == 0) {
while (count--) {
*dst_left-- = *src++;
*dst_right-- = *src++;
}
} else {
while (count--) {
*dst_right-- = *src++;
*dst_left-- = *src++;
}
}
}
static void fx8010_pb_trans_copy(struct snd_pcm_substream *substream,
struct snd_pcm_indirect *rec, size_t bytes)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_emu10k1_fx8010_pcm *pcm = &emu->fx8010.pcm[substream->number];
unsigned int tram_size = pcm->buffer_size;
unsigned short *src = (unsigned short *)(substream->runtime->dma_area + rec->sw_data);
unsigned int frames = bytes >> 2, count;
unsigned int tram_pos = pcm->tram_pos;
unsigned int tram_shift = pcm->tram_shift;
while (frames > tram_pos) {
count = tram_pos + 1;
snd_emu10k1_fx8010_playback_tram_poke1((unsigned short *)emu->fx8010.etram_pages.area + tram_pos,
(unsigned short *)emu->fx8010.etram_pages.area + tram_pos + tram_size / 2,
src, count, tram_shift);
src += count * 2;
frames -= count;
tram_pos = (tram_size / 2) - 1;
tram_shift++;
}
snd_emu10k1_fx8010_playback_tram_poke1((unsigned short *)emu->fx8010.etram_pages.area + tram_pos,
(unsigned short *)emu->fx8010.etram_pages.area + tram_pos + tram_size / 2,
src, frames, tram_shift);
tram_pos -= frames;
pcm->tram_pos = tram_pos;
pcm->tram_shift = tram_shift;
}
static int snd_emu10k1_fx8010_playback_transfer(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_emu10k1_fx8010_pcm *pcm = &emu->fx8010.pcm[substream->number];
snd_pcm_indirect_playback_transfer(substream, &pcm->pcm_rec, fx8010_pb_trans_copy);
return 0;
}
static int snd_emu10k1_fx8010_playback_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
}
static int snd_emu10k1_fx8010_playback_hw_free(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_emu10k1_fx8010_pcm *pcm = &emu->fx8010.pcm[substream->number];
unsigned int i;
for (i = 0; i < pcm->channels; i++)
snd_emu10k1_ptr_write(emu, TANKMEMADDRREGBASE + 0x80 + pcm->etram[i], 0, 0);
snd_pcm_lib_free_pages(substream);
return 0;
}
static int snd_emu10k1_fx8010_playback_prepare(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_emu10k1_fx8010_pcm *pcm = &emu->fx8010.pcm[substream->number];
unsigned int i;
/*
printk(KERN_DEBUG "prepare: etram_pages = 0x%p, dma_area = 0x%x, "
"buffer_size = 0x%x (0x%x)\n",
emu->fx8010.etram_pages, runtime->dma_area,
runtime->buffer_size, runtime->buffer_size << 2);
*/
memset(&pcm->pcm_rec, 0, sizeof(pcm->pcm_rec));
pcm->pcm_rec.hw_buffer_size = pcm->buffer_size * 2; /* byte size */
pcm->pcm_rec.sw_buffer_size = snd_pcm_lib_buffer_bytes(substream);
pcm->tram_pos = INITIAL_TRAM_POS(pcm->buffer_size);
pcm->tram_shift = 0;
snd_emu10k1_ptr_write(emu, emu->gpr_base + pcm->gpr_running, 0, 0); /* reset */
snd_emu10k1_ptr_write(emu, emu->gpr_base + pcm->gpr_trigger, 0, 0); /* reset */
snd_emu10k1_ptr_write(emu, emu->gpr_base + pcm->gpr_size, 0, runtime->buffer_size);
snd_emu10k1_ptr_write(emu, emu->gpr_base + pcm->gpr_ptr, 0, 0); /* reset ptr number */
snd_emu10k1_ptr_write(emu, emu->gpr_base + pcm->gpr_count, 0, runtime->period_size);
snd_emu10k1_ptr_write(emu, emu->gpr_base + pcm->gpr_tmpcount, 0, runtime->period_size);
for (i = 0; i < pcm->channels; i++)
snd_emu10k1_ptr_write(emu, TANKMEMADDRREGBASE + 0x80 + pcm->etram[i], 0, (TANKMEMADDRREG_READ|TANKMEMADDRREG_ALIGN) + i * (runtime->buffer_size / pcm->channels));
return 0;
}
static int snd_emu10k1_fx8010_playback_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_emu10k1_fx8010_pcm *pcm = &emu->fx8010.pcm[substream->number];
int result = 0;
spin_lock(&emu->reg_lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
/* follow thru */
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_RESUME:
#ifdef EMU10K1_SET_AC3_IEC958
{
int i;
for (i = 0; i < 3; i++) {
unsigned int bits;
bits = SPCS_CLKACCY_1000PPM | SPCS_SAMPLERATE_48 |
SPCS_CHANNELNUM_LEFT | SPCS_SOURCENUM_UNSPEC | SPCS_GENERATIONSTATUS |
0x00001200 | SPCS_EMPHASIS_NONE | SPCS_COPYRIGHT | SPCS_NOTAUDIODATA;
snd_emu10k1_ptr_write(emu, SPCS0 + i, 0, bits);
}
}
#endif
result = snd_emu10k1_fx8010_register_irq_handler(emu, snd_emu10k1_fx8010_playback_irq, pcm->gpr_running, substream, &pcm->irq);
if (result < 0)
goto __err;
snd_emu10k1_fx8010_playback_transfer(substream); /* roll the ball */
snd_emu10k1_ptr_write(emu, emu->gpr_base + pcm->gpr_trigger, 0, 1);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_SUSPEND:
snd_emu10k1_fx8010_unregister_irq_handler(emu, pcm->irq); pcm->irq = NULL;
snd_emu10k1_ptr_write(emu, emu->gpr_base + pcm->gpr_trigger, 0, 0);
pcm->tram_pos = INITIAL_TRAM_POS(pcm->buffer_size);
pcm->tram_shift = 0;
break;
default:
result = -EINVAL;
break;
}
__err:
spin_unlock(&emu->reg_lock);
return result;
}
static snd_pcm_uframes_t snd_emu10k1_fx8010_playback_pointer(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_emu10k1_fx8010_pcm *pcm = &emu->fx8010.pcm[substream->number];
size_t ptr; /* byte pointer */
if (!snd_emu10k1_ptr_read(emu, emu->gpr_base + pcm->gpr_trigger, 0))
return 0;
ptr = snd_emu10k1_ptr_read(emu, emu->gpr_base + pcm->gpr_ptr, 0) << 2;
return snd_pcm_indirect_playback_pointer(substream, &pcm->pcm_rec, ptr);
}
static struct snd_pcm_hardware snd_emu10k1_fx8010_playback =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_RESUME |
/* SNDRV_PCM_INFO_MMAP_VALID | */ SNDRV_PCM_INFO_PAUSE),
.formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_48000,
.rate_min = 48000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 1,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 1024,
.period_bytes_max = (128*1024),
.periods_min = 2,
.periods_max = 1024,
.fifo_size = 0,
};
static int snd_emu10k1_fx8010_playback_open(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_emu10k1_fx8010_pcm *pcm = &emu->fx8010.pcm[substream->number];
runtime->hw = snd_emu10k1_fx8010_playback;
runtime->hw.channels_min = runtime->hw.channels_max = pcm->channels;
runtime->hw.period_bytes_max = (pcm->buffer_size * 2) / 2;
spin_lock_irq(&emu->reg_lock);
if (pcm->valid == 0) {
spin_unlock_irq(&emu->reg_lock);
return -ENODEV;
}
pcm->opened = 1;
spin_unlock_irq(&emu->reg_lock);
return 0;
}
static int snd_emu10k1_fx8010_playback_close(struct snd_pcm_substream *substream)
{
struct snd_emu10k1 *emu = snd_pcm_substream_chip(substream);
struct snd_emu10k1_fx8010_pcm *pcm = &emu->fx8010.pcm[substream->number];
spin_lock_irq(&emu->reg_lock);
pcm->opened = 0;
spin_unlock_irq(&emu->reg_lock);
return 0;
}
static struct snd_pcm_ops snd_emu10k1_fx8010_playback_ops = {
.open = snd_emu10k1_fx8010_playback_open,
.close = snd_emu10k1_fx8010_playback_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_emu10k1_fx8010_playback_hw_params,
.hw_free = snd_emu10k1_fx8010_playback_hw_free,
.prepare = snd_emu10k1_fx8010_playback_prepare,
.trigger = snd_emu10k1_fx8010_playback_trigger,
.pointer = snd_emu10k1_fx8010_playback_pointer,
.ack = snd_emu10k1_fx8010_playback_transfer,
};
int __devinit snd_emu10k1_pcm_efx(struct snd_emu10k1 * emu, int device, struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
struct snd_kcontrol *kctl;
int err;
if (rpcm)
*rpcm = NULL;
if ((err = snd_pcm_new(emu->card, "emu10k1 efx", device, 8, 1, &pcm)) < 0)
return err;
pcm->private_data = emu;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_emu10k1_fx8010_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_emu10k1_capture_efx_ops);
pcm->info_flags = 0;
strcpy(pcm->name, "Multichannel Capture/PT Playback");
emu->pcm_efx = pcm;
if (rpcm)
*rpcm = pcm;
/* EFX capture - record the "FXBUS2" channels, by default we connect the EXTINs
* to these
*/
/* emu->efx_voices_mask[0] = FXWC_DEFAULTROUTE_C | FXWC_DEFAULTROUTE_A; */
if (emu->audigy) {
emu->efx_voices_mask[0] = 0;
if (emu->card_capabilities->emu_model)
/* Pavel Hofman - 32 voices will be used for
* capture (write mode) -
* each bit = corresponding voice
*/
emu->efx_voices_mask[1] = 0xffffffff;
else
emu->efx_voices_mask[1] = 0xffff;
} else {
emu->efx_voices_mask[0] = 0xffff0000;
emu->efx_voices_mask[1] = 0;
}
/* For emu1010, the control has to set 32 upper bits (voices)
* out of the 64 bits (voices) to true for the 16-channels capture
* to work correctly. Correct A_FXWC2 initial value (0xffffffff)
* is already defined but the snd_emu10k1_pcm_efx_voices_mask
* control can override this register's value.
*/
kctl = snd_ctl_new1(&snd_emu10k1_pcm_efx_voices_mask, emu);
if (!kctl)
return -ENOMEM;
kctl->id.device = device;
snd_ctl_add(emu->card, kctl);
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(emu->pci), 64*1024, 64*1024);
return 0;
}
| gpl-2.0 |
matthiasdiener/kmaf | drivers/video/kyro/STG4000OverlayDevice.c | 13054 | 15651 | /*
* linux/drivers/video/kyro/STG4000OverlayDevice.c
*
* Copyright (C) 2000 Imagination Technologies Ltd
* Copyright (C) 2002 STMicroelectronics
*
* 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.
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/types.h>
#include "STG4000Reg.h"
#include "STG4000Interface.h"
/* HW Defines */
#define STG4000_NO_SCALING 0x800
#define STG4000_NO_DECIMATION 0xFFFFFFFF
/* Primary surface */
#define STG4000_PRIM_NUM_PIX 5
#define STG4000_PRIM_ALIGN 4
#define STG4000_PRIM_ADDR_BITS 20
#define STG4000_PRIM_MIN_WIDTH 640
#define STG4000_PRIM_MAX_WIDTH 1600
#define STG4000_PRIM_MIN_HEIGHT 480
#define STG4000_PRIM_MAX_HEIGHT 1200
/* Overlay surface */
#define STG4000_OVRL_NUM_PIX 4
#define STG4000_OVRL_ALIGN 2
#define STG4000_OVRL_ADDR_BITS 20
#define STG4000_OVRL_NUM_MODES 5
#define STG4000_OVRL_MIN_WIDTH 0
#define STG4000_OVRL_MAX_WIDTH 720
#define STG4000_OVRL_MIN_HEIGHT 0
#define STG4000_OVRL_MAX_HEIGHT 576
/* Decimation and Scaling */
static u32 adwDecim8[33] = {
0xffffffff, 0xfffeffff, 0xffdffbff, 0xfefefeff, 0xfdf7efbf,
0xfbdf7bdf, 0xf7bbddef, 0xeeeeeeef, 0xeeddbb77, 0xedb76db7,
0xdb6db6db, 0xdb5b5b5b, 0xdab5ad6b, 0xd5ab55ab, 0xd555aaab,
0xaaaaaaab, 0xaaaa5555, 0xaa952a55, 0xa94a5295, 0xa5252525,
0xa4924925, 0x92491249, 0x91224489, 0x91111111, 0x90884211,
0x88410821, 0x88102041, 0x81010101, 0x80800801, 0x80010001,
0x80000001, 0x00000001, 0x00000000
};
typedef struct _OVRL_SRC_DEST {
/*clipped on-screen pixel position of overlay */
u32 ulDstX1;
u32 ulDstY1;
u32 ulDstX2;
u32 ulDstY2;
/*clipped pixel pos of source data within buffer thses need to be 128 bit word aligned */
u32 ulSrcX1;
u32 ulSrcY1;
u32 ulSrcX2;
u32 ulSrcY2;
/* on-screen pixel position of overlay */
s32 lDstX1;
s32 lDstY1;
s32 lDstX2;
s32 lDstY2;
} OVRL_SRC_DEST;
static u32 ovlWidth, ovlHeight, ovlStride;
static int ovlLinear;
void ResetOverlayRegisters(volatile STG4000REG __iomem *pSTGReg)
{
u32 tmp;
/* Set Overlay address to default */
tmp = STG_READ_REG(DACOverlayAddr);
CLEAR_BITS_FRM_TO(0, 20);
CLEAR_BIT(31);
STG_WRITE_REG(DACOverlayAddr, tmp);
/* Set Overlay U address */
tmp = STG_READ_REG(DACOverlayUAddr);
CLEAR_BITS_FRM_TO(0, 20);
STG_WRITE_REG(DACOverlayUAddr, tmp);
/* Set Overlay V address */
tmp = STG_READ_REG(DACOverlayVAddr);
CLEAR_BITS_FRM_TO(0, 20);
STG_WRITE_REG(DACOverlayVAddr, tmp);
/* Set Overlay Size */
tmp = STG_READ_REG(DACOverlaySize);
CLEAR_BITS_FRM_TO(0, 10);
CLEAR_BITS_FRM_TO(12, 31);
STG_WRITE_REG(DACOverlaySize, tmp);
/* Set Overlay Vt Decimation */
tmp = STG4000_NO_DECIMATION;
STG_WRITE_REG(DACOverlayVtDec, tmp);
/* Set Overlay format to default value */
tmp = STG_READ_REG(DACPixelFormat);
CLEAR_BITS_FRM_TO(4, 7);
CLEAR_BITS_FRM_TO(16, 22);
STG_WRITE_REG(DACPixelFormat, tmp);
/* Set Vertical scaling to default */
tmp = STG_READ_REG(DACVerticalScal);
CLEAR_BITS_FRM_TO(0, 11);
CLEAR_BITS_FRM_TO(16, 22);
tmp |= STG4000_NO_SCALING; /* Set to no scaling */
STG_WRITE_REG(DACVerticalScal, tmp);
/* Set Horizontal Scaling to default */
tmp = STG_READ_REG(DACHorizontalScal);
CLEAR_BITS_FRM_TO(0, 11);
CLEAR_BITS_FRM_TO(16, 17);
tmp |= STG4000_NO_SCALING; /* Set to no scaling */
STG_WRITE_REG(DACHorizontalScal, tmp);
/* Set Blend mode to Alpha Blend */
/* ????? SG 08/11/2001 Surely this isn't the alpha blend mode,
hopefully its overwrite
*/
tmp = STG_READ_REG(DACBlendCtrl);
CLEAR_BITS_FRM_TO(0, 30);
tmp = (GRAPHICS_MODE << 28);
STG_WRITE_REG(DACBlendCtrl, tmp);
}
int CreateOverlaySurface(volatile STG4000REG __iomem *pSTGReg,
u32 inWidth,
u32 inHeight,
int bLinear,
u32 ulOverlayOffset,
u32 * retStride, u32 * retUVStride)
{
u32 tmp;
u32 ulStride;
if (inWidth > STG4000_OVRL_MAX_WIDTH ||
inHeight > STG4000_OVRL_MAX_HEIGHT) {
return -EINVAL;
}
/* Stride in 16 byte words - 16Bpp */
if (bLinear) {
/* Format is 16bits so num 16 byte words is width/8 */
if ((inWidth & 0x7) == 0) { /* inWidth % 8 */
ulStride = (inWidth / 8);
} else {
/* Round up to next 16byte boundary */
ulStride = ((inWidth + 8) / 8);
}
} else {
/* Y component is 8bits so num 16 byte words is width/16 */
if ((inWidth & 0xf) == 0) { /* inWidth % 16 */
ulStride = (inWidth / 16);
} else {
/* Round up to next 16byte boundary */
ulStride = ((inWidth + 16) / 16);
}
}
/* Set Overlay address and Format mode */
tmp = STG_READ_REG(DACOverlayAddr);
CLEAR_BITS_FRM_TO(0, 20);
if (bLinear) {
CLEAR_BIT(31); /* Overlay format to Linear */
} else {
tmp |= SET_BIT(31); /* Overlay format to Planer */
}
/* Only bits 24:4 of the Overlay address */
tmp |= (ulOverlayOffset >> 4);
STG_WRITE_REG(DACOverlayAddr, tmp);
if (!bLinear) {
u32 uvSize =
(inWidth & 0x1) ? (inWidth + 1 / 2) : (inWidth / 2);
u32 uvStride;
u32 ulOffset;
/* Y component is 8bits so num 32 byte words is width/32 */
if ((uvSize & 0xf) == 0) { /* inWidth % 16 */
uvStride = (uvSize / 16);
} else {
/* Round up to next 32byte boundary */
uvStride = ((uvSize + 16) / 16);
}
ulOffset = ulOverlayOffset + (inHeight * (ulStride * 16));
/* Align U,V data to 32byte boundary */
if ((ulOffset & 0x1f) != 0)
ulOffset = (ulOffset + 32L) & 0xffffffE0L;
tmp = STG_READ_REG(DACOverlayUAddr);
CLEAR_BITS_FRM_TO(0, 20);
tmp |= (ulOffset >> 4);
STG_WRITE_REG(DACOverlayUAddr, tmp);
ulOffset += (inHeight / 2) * (uvStride * 16);
/* Align U,V data to 32byte boundary */
if ((ulOffset & 0x1f) != 0)
ulOffset = (ulOffset + 32L) & 0xffffffE0L;
tmp = STG_READ_REG(DACOverlayVAddr);
CLEAR_BITS_FRM_TO(0, 20);
tmp |= (ulOffset >> 4);
STG_WRITE_REG(DACOverlayVAddr, tmp);
*retUVStride = uvStride * 16;
}
/* Set Overlay YUV pixel format
* Make sure that LUT not used - ??????
*/
tmp = STG_READ_REG(DACPixelFormat);
/* Only support Planer or UYVY linear formats */
CLEAR_BITS_FRM_TO(4, 9);
STG_WRITE_REG(DACPixelFormat, tmp);
ovlWidth = inWidth;
ovlHeight = inHeight;
ovlStride = ulStride;
ovlLinear = bLinear;
*retStride = ulStride << 4; /* In bytes */
return 0;
}
int SetOverlayBlendMode(volatile STG4000REG __iomem *pSTGReg,
OVRL_BLEND_MODE mode,
u32 ulAlpha, u32 ulColorKey)
{
u32 tmp;
tmp = STG_READ_REG(DACBlendCtrl);
CLEAR_BITS_FRM_TO(28, 30);
tmp |= (mode << 28);
switch (mode) {
case COLOR_KEY:
CLEAR_BITS_FRM_TO(0, 23);
tmp |= (ulColorKey & 0x00FFFFFF);
break;
case GLOBAL_ALPHA:
CLEAR_BITS_FRM_TO(24, 27);
tmp |= ((ulAlpha & 0xF) << 24);
break;
case CK_PIXEL_ALPHA:
CLEAR_BITS_FRM_TO(0, 23);
tmp |= (ulColorKey & 0x00FFFFFF);
break;
case CK_GLOBAL_ALPHA:
CLEAR_BITS_FRM_TO(0, 23);
tmp |= (ulColorKey & 0x00FFFFFF);
CLEAR_BITS_FRM_TO(24, 27);
tmp |= ((ulAlpha & 0xF) << 24);
break;
case GRAPHICS_MODE:
case PER_PIXEL_ALPHA:
break;
default:
return -EINVAL;
}
STG_WRITE_REG(DACBlendCtrl, tmp);
return 0;
}
void EnableOverlayPlane(volatile STG4000REG __iomem *pSTGReg)
{
u32 tmp;
/* Enable Overlay */
tmp = STG_READ_REG(DACPixelFormat);
tmp |= SET_BIT(7);
STG_WRITE_REG(DACPixelFormat, tmp);
/* Set video stream control */
tmp = STG_READ_REG(DACStreamCtrl);
tmp |= SET_BIT(1); /* video stream */
STG_WRITE_REG(DACStreamCtrl, tmp);
}
static u32 Overlap(u32 ulBits, u32 ulPattern)
{
u32 ulCount = 0;
while (ulBits) {
if (!(ulPattern & 1))
ulCount++;
ulBits--;
ulPattern = ulPattern >> 1;
}
return ulCount;
}
int SetOverlayViewPort(volatile STG4000REG __iomem *pSTGReg,
u32 left, u32 top,
u32 right, u32 bottom)
{
OVRL_SRC_DEST srcDest;
u32 ulSrcTop, ulSrcBottom;
u32 ulSrc, ulDest;
u32 ulFxScale, ulFxOffset;
u32 ulHeight, ulWidth;
u32 ulPattern;
u32 ulDecimate, ulDecimated;
u32 ulApplied;
u32 ulDacXScale, ulDacYScale;
u32 ulScale;
u32 ulLeft, ulRight;
u32 ulSrcLeft, ulSrcRight;
u32 ulScaleLeft, ulScaleRight;
u32 ulhDecim;
u32 ulsVal;
u32 ulVertDecFactor;
int bResult;
u32 ulClipOff = 0;
u32 ulBits = 0;
u32 ulsAdd = 0;
u32 tmp, ulStride;
u32 ulExcessPixels, ulClip, ulExtraLines;
srcDest.ulSrcX1 = 0;
srcDest.ulSrcY1 = 0;
srcDest.ulSrcX2 = ovlWidth - 1;
srcDest.ulSrcY2 = ovlHeight - 1;
srcDest.ulDstX1 = left;
srcDest.ulDstY1 = top;
srcDest.ulDstX2 = right;
srcDest.ulDstY2 = bottom;
srcDest.lDstX1 = srcDest.ulDstX1;
srcDest.lDstY1 = srcDest.ulDstY1;
srcDest.lDstX2 = srcDest.ulDstX2;
srcDest.lDstY2 = srcDest.ulDstY2;
/************* Vertical decimation/scaling ******************/
/* Get Src Top and Bottom */
ulSrcTop = srcDest.ulSrcY1;
ulSrcBottom = srcDest.ulSrcY2;
ulSrc = ulSrcBottom - ulSrcTop;
ulDest = srcDest.lDstY2 - srcDest.lDstY1; /* on-screen overlay */
if (ulSrc <= 1)
return -EINVAL;
/* First work out the position we are to display as offset from the
* source of the buffer
*/
ulFxScale = (ulDest << 11) / ulSrc; /* fixed point scale factor */
ulFxOffset = (srcDest.lDstY2 - srcDest.ulDstY2) << 11;
ulSrcBottom = ulSrcBottom - (ulFxOffset / ulFxScale);
ulSrc = ulSrcBottom - ulSrcTop;
ulHeight = ulSrc;
ulDest = srcDest.ulDstY2 - (srcDest.ulDstY1 - 1);
ulPattern = adwDecim8[ulBits];
/* At this point ulSrc represents the input decimator */
if (ulSrc > ulDest) {
ulDecimate = ulSrc - ulDest;
ulBits = 0;
ulApplied = ulSrc / 32;
while (((ulBits * ulApplied) +
Overlap((ulSrc % 32),
adwDecim8[ulBits])) < ulDecimate)
ulBits++;
ulPattern = adwDecim8[ulBits];
ulDecimated =
(ulBits * ulApplied) + Overlap((ulSrc % 32),
ulPattern);
ulSrc = ulSrc - ulDecimated; /* the number number of lines that will go into the scaler */
}
if (ulBits && (ulBits != 32)) {
ulVertDecFactor = (63 - ulBits) / (32 - ulBits); /* vertical decimation factor scaled up to nearest integer */
} else {
ulVertDecFactor = 1;
}
ulDacYScale = ((ulSrc - 1) * 2048) / (ulDest + 1);
tmp = STG_READ_REG(DACOverlayVtDec); /* Decimation */
CLEAR_BITS_FRM_TO(0, 31);
tmp = ulPattern;
STG_WRITE_REG(DACOverlayVtDec, tmp);
/***************** Horizontal decimation/scaling ***************************/
/*
* Now we handle the horizontal case, this is a simplified version of
* the vertical case in that we decimate by factors of 2. as we are
* working in words we should always be able to decimate by these
* factors. as we always have to have a buffer which is aligned to a
* whole number of 128 bit words, we must align the left side to the
* lowest to the next lowest 128 bit boundary, and the right hand edge
* to the next largets boundary, (in a similar way to how we didi it in
* PMX1) as the left and right hand edges are aligned to these
* boundaries normally this only becomes an issue when we are chopping
* of one of the sides We shall work out vertical stuff first
*/
ulSrc = srcDest.ulSrcX2 - srcDest.ulSrcX1;
ulDest = srcDest.lDstX2 - srcDest.lDstX1;
#ifdef _OLDCODE
ulLeft = srcDest.ulDstX1;
ulRight = srcDest.ulDstX2;
#else
if (srcDest.ulDstX1 > 2) {
ulLeft = srcDest.ulDstX1 + 2;
ulRight = srcDest.ulDstX2 + 1;
} else {
ulLeft = srcDest.ulDstX1;
ulRight = srcDest.ulDstX2 + 1;
}
#endif
/* first work out the position we are to display as offset from the source of the buffer */
bResult = 1;
do {
if (ulDest == 0)
return -EINVAL;
/* source pixels per dest pixel <<11 */
ulFxScale = ((ulSrc - 1) << 11) / (ulDest);
/* then number of destination pixels out we are */
ulFxOffset = ulFxScale * ((srcDest.ulDstX1 - srcDest.lDstX1) + ulClipOff);
ulFxOffset >>= 11;
/* this replaces the code which was making a decision as to use either ulFxOffset or ulSrcX1 */
ulSrcLeft = srcDest.ulSrcX1 + ulFxOffset;
/* then number of destination pixels out we are */
ulFxOffset = ulFxScale * (srcDest.lDstX2 - srcDest.ulDstX2);
ulFxOffset >>= 11;
ulSrcRight = srcDest.ulSrcX2 - ulFxOffset;
/*
* we must align these to our 128 bit boundaries. we shall
* round down the pixel pos to the nearest 8 pixels.
*/
ulScaleLeft = ulSrcLeft;
ulScaleRight = ulSrcRight;
/* shift fxscale until it is in the range of the scaler */
ulhDecim = 0;
ulScale = (((ulSrcRight - ulSrcLeft) - 1) << (11 - ulhDecim)) / (ulRight - ulLeft + 2);
while (ulScale > 0x800) {
ulhDecim++;
ulScale = (((ulSrcRight - ulSrcLeft) - 1) << (11 - ulhDecim)) / (ulRight - ulLeft + 2);
}
/*
* to try and get the best values We first try and use
* src/dwdest for the scale factor, then we move onto src-1
*
* we want to check to see if we will need to clip data, if so
* then we should clip our source so that we don't need to
*/
if (!ovlLinear) {
ulSrcLeft &= ~0x1f;
/*
* we must align the right hand edge to the next 32
* pixel` boundary, must be on a 256 boundary so u, and
* v are 128 bit aligned
*/
ulSrcRight = (ulSrcRight + 0x1f) & ~0x1f;
} else {
ulSrcLeft &= ~0x7;
/*
* we must align the right hand edge to the next
* 8pixel` boundary
*/
ulSrcRight = (ulSrcRight + 0x7) & ~0x7;
}
/* this is the input size line store needs to cope with */
ulWidth = ulSrcRight - ulSrcLeft;
/*
* use unclipped value to work out scale factror this is the
* scale factor we want we shall now work out the horizonal
* decimation and scaling
*/
ulsVal = ((ulWidth / 8) >> ulhDecim);
if ((ulWidth != (ulsVal << ulhDecim) * 8))
ulsAdd = 1;
/* input pixels to scaler; */
ulSrc = ulWidth >> ulhDecim;
if (ulSrc <= 2)
return -EINVAL;
ulExcessPixels = ((((ulScaleLeft - ulSrcLeft)) << (11 - ulhDecim)) / ulScale);
ulClip = (ulSrc << 11) / ulScale;
ulClip -= (ulRight - ulLeft);
ulClip += ulExcessPixels;
if (ulClip)
ulClip--;
/* We may need to do more here if we really have a HW rev < 5 */
} while (!bResult);
ulExtraLines = (1 << ulhDecim) * ulVertDecFactor;
ulExtraLines += 64;
ulHeight += ulExtraLines;
ulDacXScale = ulScale;
tmp = STG_READ_REG(DACVerticalScal);
CLEAR_BITS_FRM_TO(0, 11);
CLEAR_BITS_FRM_TO(16, 22); /* Vertical Scaling */
/* Calculate new output line stride, this is always the number of 422
words in the line buffer, so it doesn't matter if the
mode is 420. Then set the vertical scale register.
*/
ulStride = (ulWidth >> (ulhDecim + 3)) + ulsAdd;
tmp |= ((ulStride << 16) | (ulDacYScale)); /* DAC_LS_CTRL = stride */
STG_WRITE_REG(DACVerticalScal, tmp);
/* Now set up the overlay size using the modified width and height
from decimate and scaling calculations
*/
tmp = STG_READ_REG(DACOverlaySize);
CLEAR_BITS_FRM_TO(0, 10);
CLEAR_BITS_FRM_TO(12, 31);
if (ovlLinear) {
tmp |=
(ovlStride | ((ulHeight + 1) << 12) |
(((ulWidth / 8) - 1) << 23));
} else {
tmp |=
(ovlStride | ((ulHeight + 1) << 12) |
(((ulWidth / 32) - 1) << 23));
}
STG_WRITE_REG(DACOverlaySize, tmp);
/* Set Video Window Start */
tmp = ((ulLeft << 16)) | (srcDest.ulDstY1);
STG_WRITE_REG(DACVidWinStart, tmp);
/* Set Video Window End */
tmp = ((ulRight) << 16) | (srcDest.ulDstY2);
STG_WRITE_REG(DACVidWinEnd, tmp);
/* Finally set up the rest of the overlay regs in the order
done in the IMG driver
*/
tmp = STG_READ_REG(DACPixelFormat);
tmp = ((ulExcessPixels << 16) | tmp) & 0x7fffffff;
STG_WRITE_REG(DACPixelFormat, tmp);
tmp = STG_READ_REG(DACHorizontalScal);
CLEAR_BITS_FRM_TO(0, 11);
CLEAR_BITS_FRM_TO(16, 17);
tmp |= ((ulhDecim << 16) | (ulDacXScale));
STG_WRITE_REG(DACHorizontalScal, tmp);
return 0;
}
| gpl-2.0 |
yetu/linux-pfla02 | drivers/regulator/of_regulator.c | 255 | 6943 | /*
* OF helpers for regulator framework
*
* Copyright (C) 2011 Texas Instruments, Inc.
* Rajendra Nayak <rnayak@ti.com>
*
* 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.
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/of.h>
#include <linux/regulator/machine.h>
#include <linux/regulator/driver.h>
#include <linux/regulator/of_regulator.h>
#include "internal.h"
static void of_get_regulation_constraints(struct device_node *np,
struct regulator_init_data **init_data)
{
const __be32 *min_uV, *max_uV;
struct regulation_constraints *constraints = &(*init_data)->constraints;
int ret;
u32 pval;
constraints->name = of_get_property(np, "regulator-name", NULL);
min_uV = of_get_property(np, "regulator-min-microvolt", NULL);
if (min_uV)
constraints->min_uV = be32_to_cpu(*min_uV);
max_uV = of_get_property(np, "regulator-max-microvolt", NULL);
if (max_uV)
constraints->max_uV = be32_to_cpu(*max_uV);
/* Voltage change possible? */
if (constraints->min_uV != constraints->max_uV)
constraints->valid_ops_mask |= REGULATOR_CHANGE_VOLTAGE;
/* Only one voltage? Then make sure it's set. */
if (min_uV && max_uV && constraints->min_uV == constraints->max_uV)
constraints->apply_uV = true;
if (!of_property_read_u32(np, "regulator-microvolt-offset", &pval))
constraints->uV_offset = pval;
if (!of_property_read_u32(np, "regulator-min-microamp", &pval))
constraints->min_uA = pval;
if (!of_property_read_u32(np, "regulator-max-microamp", &pval))
constraints->max_uA = pval;
/* Current change possible? */
if (constraints->min_uA != constraints->max_uA)
constraints->valid_ops_mask |= REGULATOR_CHANGE_CURRENT;
constraints->boot_on = of_property_read_bool(np, "regulator-boot-on");
constraints->always_on = of_property_read_bool(np, "regulator-always-on");
if (!constraints->always_on) /* status change should be possible. */
constraints->valid_ops_mask |= REGULATOR_CHANGE_STATUS;
if (of_property_read_bool(np, "regulator-allow-bypass"))
constraints->valid_ops_mask |= REGULATOR_CHANGE_BYPASS;
ret = of_property_read_u32(np, "regulator-ramp-delay", &pval);
if (!ret) {
if (pval)
constraints->ramp_delay = pval;
else
constraints->ramp_disable = true;
}
ret = of_property_read_u32(np, "regulator-enable-ramp-delay", &pval);
if (!ret)
constraints->enable_time = pval;
}
/**
* of_get_regulator_init_data - extract regulator_init_data structure info
* @dev: device requesting for regulator_init_data
*
* Populates regulator_init_data structure by extracting data from device
* tree node, returns a pointer to the populated struture or NULL if memory
* alloc fails.
*/
struct regulator_init_data *of_get_regulator_init_data(struct device *dev,
struct device_node *node)
{
struct regulator_init_data *init_data;
if (!node)
return NULL;
init_data = devm_kzalloc(dev, sizeof(*init_data), GFP_KERNEL);
if (!init_data)
return NULL; /* Out of memory? */
of_get_regulation_constraints(node, &init_data);
return init_data;
}
EXPORT_SYMBOL_GPL(of_get_regulator_init_data);
struct devm_of_regulator_matches {
struct of_regulator_match *matches;
unsigned int num_matches;
};
static void devm_of_regulator_put_matches(struct device *dev, void *res)
{
struct devm_of_regulator_matches *devm_matches = res;
int i;
for (i = 0; i < devm_matches->num_matches; i++)
of_node_put(devm_matches->matches[i].of_node);
}
/**
* of_regulator_match - extract multiple regulator init data from device tree.
* @dev: device requesting the data
* @node: parent device node of the regulators
* @matches: match table for the regulators
* @num_matches: number of entries in match table
*
* This function uses a match table specified by the regulator driver to
* parse regulator init data from the device tree. @node is expected to
* contain a set of child nodes, each providing the init data for one
* regulator. The data parsed from a child node will be matched to a regulator
* based on either the deprecated property regulator-compatible if present,
* or otherwise the child node's name. Note that the match table is modified
* in place and an additional of_node reference is taken for each matched
* regulator.
*
* Returns the number of matches found or a negative error code on failure.
*/
int of_regulator_match(struct device *dev, struct device_node *node,
struct of_regulator_match *matches,
unsigned int num_matches)
{
unsigned int count = 0;
unsigned int i;
const char *name;
struct device_node *child;
struct devm_of_regulator_matches *devm_matches;
if (!dev || !node)
return -EINVAL;
devm_matches = devres_alloc(devm_of_regulator_put_matches,
sizeof(struct devm_of_regulator_matches),
GFP_KERNEL);
if (!devm_matches)
return -ENOMEM;
devm_matches->matches = matches;
devm_matches->num_matches = num_matches;
devres_add(dev, devm_matches);
for (i = 0; i < num_matches; i++) {
struct of_regulator_match *match = &matches[i];
match->init_data = NULL;
match->of_node = NULL;
}
for_each_child_of_node(node, child) {
name = of_get_property(child,
"regulator-compatible", NULL);
if (!name)
name = child->name;
for (i = 0; i < num_matches; i++) {
struct of_regulator_match *match = &matches[i];
if (match->of_node)
continue;
if (strcmp(match->name, name))
continue;
match->init_data =
of_get_regulator_init_data(dev, child);
if (!match->init_data) {
dev_err(dev,
"failed to parse DT for regulator %s\n",
child->name);
return -EINVAL;
}
match->of_node = of_node_get(child);
count++;
break;
}
}
return count;
}
EXPORT_SYMBOL_GPL(of_regulator_match);
struct regulator_init_data *regulator_of_get_init_data(struct device *dev,
const struct regulator_desc *desc,
struct device_node **node)
{
struct device_node *search, *child;
struct regulator_init_data *init_data = NULL;
const char *name;
if (!dev->of_node || !desc->of_match)
return NULL;
if (desc->regulators_node)
search = of_get_child_by_name(dev->of_node,
desc->regulators_node);
else
search = dev->of_node;
if (!search) {
dev_dbg(dev, "Failed to find regulator container node '%s'\n",
desc->regulators_node);
return NULL;
}
for_each_child_of_node(search, child) {
name = of_get_property(child, "regulator-compatible", NULL);
if (!name)
name = child->name;
if (strcmp(desc->of_match, name))
continue;
init_data = of_get_regulator_init_data(dev, child);
if (!init_data) {
dev_err(dev,
"failed to parse DT for regulator %s\n",
child->name);
break;
}
of_node_get(child);
*node = child;
break;
}
of_node_put(search);
return init_data;
}
| gpl-2.0 |
coredumb/linux-grsecurity | drivers/staging/iio/frequency/ad9852.c | 511 | 4931 | /*
* Driver for ADI Direct Digital Synthesis ad9852
*
* Copyright (c) 2010 Analog Devices Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/types.h>
#include <linux/mutex.h>
#include <linux/device.h>
#include <linux/spi/spi.h>
#include <linux/slab.h>
#include <linux/sysfs.h>
#include <linux/module.h>
#include <linux/iio/iio.h>
#include <linux/iio/sysfs.h>
#define DRV_NAME "ad9852"
#define addr_phaad1 0x0
#define addr_phaad2 0x1
#define addr_fretu1 0x2
#define addr_fretu2 0x3
#define addr_delfre 0x4
#define addr_updclk 0x5
#define addr_ramclk 0x6
#define addr_contrl 0x7
#define addr_optskm 0x8
#define addr_optskr 0xa
#define addr_dacctl 0xb
#define COMPPD (1 << 4)
#define REFMULT2 (1 << 2)
#define BYPPLL (1 << 5)
#define PLLRANG (1 << 6)
#define IEUPCLK (1)
#define OSKEN (1 << 5)
#define read_bit (1 << 7)
/* Register format: 1 byte addr + value */
struct ad9852_config {
u8 phajst0[3];
u8 phajst1[3];
u8 fretun1[6];
u8 fretun2[6];
u8 dltafre[6];
u8 updtclk[5];
u8 ramprat[4];
u8 control[5];
u8 outpskm[3];
u8 outpskr[2];
u8 daccntl[3];
};
struct ad9852_state {
struct mutex lock;
struct spi_device *sdev;
};
static ssize_t ad9852_set_parameter(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct spi_transfer xfer;
int ret;
struct ad9852_config *config = (struct ad9852_config *)buf;
struct iio_dev *idev = dev_to_iio_dev(dev);
struct ad9852_state *st = iio_priv(idev);
xfer.len = 3;
xfer.tx_buf = &config->phajst0[0];
mutex_lock(&st->lock);
ret = spi_sync_transfer(st->sdev, &xfer, 1);
if (ret)
goto error_ret;
xfer.len = 3;
xfer.tx_buf = &config->phajst1[0];
ret = spi_sync_transfer(st->sdev, &xfer, 1);
if (ret)
goto error_ret;
xfer.len = 6;
xfer.tx_buf = &config->fretun1[0];
ret = spi_sync_transfer(st->sdev, &xfer, 1);
if (ret)
goto error_ret;
xfer.len = 6;
xfer.tx_buf = &config->fretun2[0];
ret = spi_sync_transfer(st->sdev, &xfer, 1);
if (ret)
goto error_ret;
xfer.len = 6;
xfer.tx_buf = &config->dltafre[0];
ret = spi_sync_transfer(st->sdev, &xfer, 1);
if (ret)
goto error_ret;
xfer.len = 5;
xfer.tx_buf = &config->updtclk[0];
ret = spi_sync_transfer(st->sdev, &xfer, 1);
if (ret)
goto error_ret;
xfer.len = 4;
xfer.tx_buf = &config->ramprat[0];
ret = spi_sync_transfer(st->sdev, &xfer, 1);
if (ret)
goto error_ret;
xfer.len = 5;
xfer.tx_buf = &config->control[0];
ret = spi_sync_transfer(st->sdev, &xfer, 1);
if (ret)
goto error_ret;
xfer.len = 3;
xfer.tx_buf = &config->outpskm[0];
ret = spi_sync_transfer(st->sdev, &xfer, 1);
if (ret)
goto error_ret;
xfer.len = 2;
xfer.tx_buf = &config->outpskr[0];
ret = spi_sync_transfer(st->sdev, &xfer, 1);
if (ret)
goto error_ret;
xfer.len = 3;
xfer.tx_buf = &config->daccntl[0];
ret = spi_sync_transfer(st->sdev, &xfer, 1);
if (ret)
goto error_ret;
error_ret:
mutex_unlock(&st->lock);
return ret ? ret : len;
}
static IIO_DEVICE_ATTR(dds, S_IWUSR, NULL, ad9852_set_parameter, 0);
static void ad9852_init(struct ad9852_state *st)
{
struct spi_transfer xfer;
int ret;
u8 config[5];
config[0] = addr_contrl;
config[1] = COMPPD;
config[2] = REFMULT2 | BYPPLL | PLLRANG;
config[3] = IEUPCLK;
config[4] = OSKEN;
mutex_lock(&st->lock);
xfer.len = 5;
xfer.tx_buf = &config;
ret = spi_sync_transfer(st->sdev, &xfer, 1);
if (ret)
goto error_ret;
error_ret:
mutex_unlock(&st->lock);
}
static struct attribute *ad9852_attributes[] = {
&iio_dev_attr_dds.dev_attr.attr,
NULL,
};
static const struct attribute_group ad9852_attribute_group = {
.attrs = ad9852_attributes,
};
static const struct iio_info ad9852_info = {
.attrs = &ad9852_attribute_group,
.driver_module = THIS_MODULE,
};
static int ad9852_probe(struct spi_device *spi)
{
struct ad9852_state *st;
struct iio_dev *idev;
int ret = 0;
idev = devm_iio_device_alloc(&spi->dev, sizeof(*st));
if (!idev)
return -ENOMEM;
st = iio_priv(idev);
spi_set_drvdata(spi, idev);
mutex_init(&st->lock);
st->sdev = spi;
idev->dev.parent = &spi->dev;
idev->info = &ad9852_info;
idev->modes = INDIO_DIRECT_MODE;
ret = iio_device_register(idev);
if (ret)
return ret;
spi->max_speed_hz = 2000000;
spi->mode = SPI_MODE_3;
spi->bits_per_word = 8;
spi_setup(spi);
ad9852_init(st);
return 0;
}
static int ad9852_remove(struct spi_device *spi)
{
iio_device_unregister(spi_get_drvdata(spi));
return 0;
}
static struct spi_driver ad9852_driver = {
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
},
.probe = ad9852_probe,
.remove = ad9852_remove,
};
module_spi_driver(ad9852_driver);
MODULE_AUTHOR("Cliff Cai");
MODULE_DESCRIPTION("Analog Devices ad9852 driver");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("spi:" DRV_NAME);
| gpl-2.0 |
Jewbie/Kernel-2.6.32 | arch/parisc/kernel/sys_parisc.c | 511 | 7188 |
/*
* PARISC specific syscalls
*
* Copyright (C) 1999-2003 Matthew Wilcox <willy at parisc-linux.org>
* Copyright (C) 2000-2003 Paul Bame <bame at parisc-linux.org>
* Copyright (C) 2001 Thomas Bogendoerfer <tsbogend at parisc-linux.org>
*
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <asm/uaccess.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/linkage.h>
#include <linux/mm.h>
#include <linux/mman.h>
#include <linux/shm.h>
#include <linux/syscalls.h>
#include <linux/utsname.h>
#include <linux/personality.h>
static unsigned long get_unshared_area(unsigned long addr, unsigned long len)
{
struct vm_area_struct *vma;
addr = PAGE_ALIGN(addr);
for (vma = find_vma(current->mm, addr); ; vma = vma->vm_next) {
/* At this point: (!vma || addr < vma->vm_end). */
if (TASK_SIZE - len < addr)
return -ENOMEM;
if (!vma || addr + len <= vma->vm_start)
return addr;
addr = vma->vm_end;
}
}
#define DCACHE_ALIGN(addr) (((addr) + (SHMLBA - 1)) &~ (SHMLBA - 1))
/*
* We need to know the offset to use. Old scheme was to look for
* existing mapping and use the same offset. New scheme is to use the
* address of the kernel data structure as the seed for the offset.
* We'll see how that works...
*
* The mapping is cacheline aligned, so there's no information in the bottom
* few bits of the address. We're looking for 10 bits (4MB / 4k), so let's
* drop the bottom 8 bits and use bits 8-17.
*/
static int get_offset(struct address_space *mapping)
{
int offset = (unsigned long) mapping << (PAGE_SHIFT - 8);
return offset & 0x3FF000;
}
static unsigned long get_shared_area(struct address_space *mapping,
unsigned long addr, unsigned long len, unsigned long pgoff)
{
struct vm_area_struct *vma;
int offset = mapping ? get_offset(mapping) : 0;
addr = DCACHE_ALIGN(addr - offset) + offset;
for (vma = find_vma(current->mm, addr); ; vma = vma->vm_next) {
/* At this point: (!vma || addr < vma->vm_end). */
if (TASK_SIZE - len < addr)
return -ENOMEM;
if (!vma || addr + len <= vma->vm_start)
return addr;
addr = DCACHE_ALIGN(vma->vm_end - offset) + offset;
if (addr < vma->vm_end) /* handle wraparound */
return -ENOMEM;
}
}
unsigned long arch_get_unmapped_area(struct file *filp, unsigned long addr,
unsigned long len, unsigned long pgoff, unsigned long flags)
{
if (len > TASK_SIZE)
return -ENOMEM;
/* Might want to check for cache aliasing issues for MAP_FIXED case
* like ARM or MIPS ??? --BenH.
*/
if (flags & MAP_FIXED)
return addr;
if (!addr)
addr = TASK_UNMAPPED_BASE;
if (filp) {
addr = get_shared_area(filp->f_mapping, addr, len, pgoff);
} else if(flags & MAP_SHARED) {
addr = get_shared_area(NULL, addr, len, pgoff);
} else {
addr = get_unshared_area(addr, len);
}
return addr;
}
asmlinkage unsigned long sys_mmap2(unsigned long addr, unsigned long len,
unsigned long prot, unsigned long flags, unsigned long fd,
unsigned long pgoff)
{
/* Make sure the shift for mmap2 is constant (12), no matter what PAGE_SIZE
we have. */
return sys_mmap_pgoff(addr, len, prot, flags, fd,
pgoff >> (PAGE_SHIFT - 12));
}
asmlinkage unsigned long sys_mmap(unsigned long addr, unsigned long len,
unsigned long prot, unsigned long flags, unsigned long fd,
unsigned long offset)
{
if (!(offset & ~PAGE_MASK)) {
return sys_mmap_pgoff(addr, len, prot, flags, fd,
offset >> PAGE_SHIFT);
} else {
return -EINVAL;
}
}
/* Fucking broken ABI */
#ifdef CONFIG_64BIT
asmlinkage long parisc_truncate64(const char __user * path,
unsigned int high, unsigned int low)
{
return sys_truncate(path, (long)high << 32 | low);
}
asmlinkage long parisc_ftruncate64(unsigned int fd,
unsigned int high, unsigned int low)
{
return sys_ftruncate(fd, (long)high << 32 | low);
}
/* stubs for the benefit of the syscall_table since truncate64 and truncate
* are identical on LP64 */
asmlinkage long sys_truncate64(const char __user * path, unsigned long length)
{
return sys_truncate(path, length);
}
asmlinkage long sys_ftruncate64(unsigned int fd, unsigned long length)
{
return sys_ftruncate(fd, length);
}
asmlinkage long sys_fcntl64(unsigned int fd, unsigned int cmd, unsigned long arg)
{
return sys_fcntl(fd, cmd, arg);
}
#else
asmlinkage long parisc_truncate64(const char __user * path,
unsigned int high, unsigned int low)
{
return sys_truncate64(path, (loff_t)high << 32 | low);
}
asmlinkage long parisc_ftruncate64(unsigned int fd,
unsigned int high, unsigned int low)
{
return sys_ftruncate64(fd, (loff_t)high << 32 | low);
}
#endif
asmlinkage ssize_t parisc_pread64(unsigned int fd, char __user *buf, size_t count,
unsigned int high, unsigned int low)
{
return sys_pread64(fd, buf, count, (loff_t)high << 32 | low);
}
asmlinkage ssize_t parisc_pwrite64(unsigned int fd, const char __user *buf,
size_t count, unsigned int high, unsigned int low)
{
return sys_pwrite64(fd, buf, count, (loff_t)high << 32 | low);
}
asmlinkage ssize_t parisc_readahead(int fd, unsigned int high, unsigned int low,
size_t count)
{
return sys_readahead(fd, (loff_t)high << 32 | low, count);
}
asmlinkage long parisc_fadvise64_64(int fd,
unsigned int high_off, unsigned int low_off,
unsigned int high_len, unsigned int low_len, int advice)
{
return sys_fadvise64_64(fd, (loff_t)high_off << 32 | low_off,
(loff_t)high_len << 32 | low_len, advice);
}
asmlinkage long parisc_sync_file_range(int fd,
u32 hi_off, u32 lo_off, u32 hi_nbytes, u32 lo_nbytes,
unsigned int flags)
{
return sys_sync_file_range(fd, (loff_t)hi_off << 32 | lo_off,
(loff_t)hi_nbytes << 32 | lo_nbytes, flags);
}
asmlinkage unsigned long sys_alloc_hugepages(int key, unsigned long addr, unsigned long len, int prot, int flag)
{
return -ENOMEM;
}
asmlinkage int sys_free_hugepages(unsigned long addr)
{
return -EINVAL;
}
long parisc_personality(unsigned long personality)
{
long err;
if (personality(current->personality) == PER_LINUX32
&& personality == PER_LINUX)
personality = PER_LINUX32;
err = sys_personality(personality);
if (err == PER_LINUX32)
err = PER_LINUX;
return err;
}
long parisc_newuname(struct new_utsname __user *name)
{
int err = sys_newuname(name);
#ifdef CONFIG_COMPAT
if (!err && personality(current->personality) == PER_LINUX32) {
if (__put_user(0, name->machine + 6) ||
__put_user(0, name->machine + 7))
err = -EFAULT;
}
#endif
return err;
}
| gpl-2.0 |
DerickBeckwith/linux-stable | drivers/scsi/arm/cumana_2.c | 2559 | 13776 | /*
* linux/drivers/acorn/scsi/cumana_2.c
*
* Copyright (C) 1997-2005 Russell King
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Changelog:
* 30-08-1997 RMK 0.0.0 Created, READONLY version.
* 22-01-1998 RMK 0.0.1 Updated to 2.1.80.
* 15-04-1998 RMK 0.0.1 Only do PIO if FAS216 will allow it.
* 02-05-1998 RMK 0.0.2 Updated & added DMA support.
* 27-06-1998 RMK Changed asm/delay.h to linux/delay.h
* 18-08-1998 RMK 0.0.3 Fixed synchronous transfer depth.
* 02-04-2000 RMK 0.0.4 Updated for new error handling code.
*/
#include <linux/module.h>
#include <linux/blkdev.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/ioport.h>
#include <linux/proc_fs.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/dma-mapping.h>
#include <asm/dma.h>
#include <asm/ecard.h>
#include <asm/io.h>
#include <asm/pgtable.h>
#include "../scsi.h"
#include <scsi/scsi_host.h>
#include "fas216.h"
#include "scsi.h"
#include <scsi/scsicam.h>
#define CUMANASCSI2_STATUS (0x0000)
#define STATUS_INT (1 << 0)
#define STATUS_DRQ (1 << 1)
#define STATUS_LATCHED (1 << 3)
#define CUMANASCSI2_ALATCH (0x0014)
#define ALATCH_ENA_INT (3)
#define ALATCH_DIS_INT (2)
#define ALATCH_ENA_TERM (5)
#define ALATCH_DIS_TERM (4)
#define ALATCH_ENA_BIT32 (11)
#define ALATCH_DIS_BIT32 (10)
#define ALATCH_ENA_DMA (13)
#define ALATCH_DIS_DMA (12)
#define ALATCH_DMA_OUT (15)
#define ALATCH_DMA_IN (14)
#define CUMANASCSI2_PSEUDODMA (0x0200)
#define CUMANASCSI2_FAS216_OFFSET (0x0300)
#define CUMANASCSI2_FAS216_SHIFT 2
/*
* Version
*/
#define VERSION "1.00 (13/11/2002 2.5.47)"
/*
* Use term=0,1,0,0,0 to turn terminators on/off
*/
static int term[MAX_ECARDS] = { 1, 1, 1, 1, 1, 1, 1, 1 };
#define NR_SG 256
struct cumanascsi2_info {
FAS216_Info info;
struct expansion_card *ec;
void __iomem *base;
unsigned int terms; /* Terminator state */
struct scatterlist sg[NR_SG]; /* Scatter DMA list */
};
#define CSTATUS_IRQ (1 << 0)
#define CSTATUS_DRQ (1 << 1)
/* Prototype: void cumanascsi_2_irqenable(ec, irqnr)
* Purpose : Enable interrupts on Cumana SCSI 2 card
* Params : ec - expansion card structure
* : irqnr - interrupt number
*/
static void
cumanascsi_2_irqenable(struct expansion_card *ec, int irqnr)
{
struct cumanascsi2_info *info = ec->irq_data;
writeb(ALATCH_ENA_INT, info->base + CUMANASCSI2_ALATCH);
}
/* Prototype: void cumanascsi_2_irqdisable(ec, irqnr)
* Purpose : Disable interrupts on Cumana SCSI 2 card
* Params : ec - expansion card structure
* : irqnr - interrupt number
*/
static void
cumanascsi_2_irqdisable(struct expansion_card *ec, int irqnr)
{
struct cumanascsi2_info *info = ec->irq_data;
writeb(ALATCH_DIS_INT, info->base + CUMANASCSI2_ALATCH);
}
static const expansioncard_ops_t cumanascsi_2_ops = {
.irqenable = cumanascsi_2_irqenable,
.irqdisable = cumanascsi_2_irqdisable,
};
/* Prototype: void cumanascsi_2_terminator_ctl(host, on_off)
* Purpose : Turn the Cumana SCSI 2 terminators on or off
* Params : host - card to turn on/off
* : on_off - !0 to turn on, 0 to turn off
*/
static void
cumanascsi_2_terminator_ctl(struct Scsi_Host *host, int on_off)
{
struct cumanascsi2_info *info = (struct cumanascsi2_info *)host->hostdata;
if (on_off) {
info->terms = 1;
writeb(ALATCH_ENA_TERM, info->base + CUMANASCSI2_ALATCH);
} else {
info->terms = 0;
writeb(ALATCH_DIS_TERM, info->base + CUMANASCSI2_ALATCH);
}
}
/* Prototype: void cumanascsi_2_intr(irq, *dev_id, *regs)
* Purpose : handle interrupts from Cumana SCSI 2 card
* Params : irq - interrupt number
* dev_id - user-defined (Scsi_Host structure)
*/
static irqreturn_t
cumanascsi_2_intr(int irq, void *dev_id)
{
struct cumanascsi2_info *info = dev_id;
return fas216_intr(&info->info);
}
/* Prototype: fasdmatype_t cumanascsi_2_dma_setup(host, SCpnt, direction, min_type)
* Purpose : initialises DMA/PIO
* Params : host - host
* SCpnt - command
* direction - DMA on to/off of card
* min_type - minimum DMA support that we must have for this transfer
* Returns : type of transfer to be performed
*/
static fasdmatype_t
cumanascsi_2_dma_setup(struct Scsi_Host *host, struct scsi_pointer *SCp,
fasdmadir_t direction, fasdmatype_t min_type)
{
struct cumanascsi2_info *info = (struct cumanascsi2_info *)host->hostdata;
struct device *dev = scsi_get_device(host);
int dmach = info->info.scsi.dma;
writeb(ALATCH_DIS_DMA, info->base + CUMANASCSI2_ALATCH);
if (dmach != NO_DMA &&
(min_type == fasdma_real_all || SCp->this_residual >= 512)) {
int bufs, map_dir, dma_dir, alatch_dir;
bufs = copy_SCp_to_sg(&info->sg[0], SCp, NR_SG);
if (direction == DMA_OUT)
map_dir = DMA_TO_DEVICE,
dma_dir = DMA_MODE_WRITE,
alatch_dir = ALATCH_DMA_OUT;
else
map_dir = DMA_FROM_DEVICE,
dma_dir = DMA_MODE_READ,
alatch_dir = ALATCH_DMA_IN;
dma_map_sg(dev, info->sg, bufs, map_dir);
disable_dma(dmach);
set_dma_sg(dmach, info->sg, bufs);
writeb(alatch_dir, info->base + CUMANASCSI2_ALATCH);
set_dma_mode(dmach, dma_dir);
enable_dma(dmach);
writeb(ALATCH_ENA_DMA, info->base + CUMANASCSI2_ALATCH);
writeb(ALATCH_DIS_BIT32, info->base + CUMANASCSI2_ALATCH);
return fasdma_real_all;
}
/*
* If we're not doing DMA,
* we'll do pseudo DMA
*/
return fasdma_pio;
}
/*
* Prototype: void cumanascsi_2_dma_pseudo(host, SCpnt, direction, transfer)
* Purpose : handles pseudo DMA
* Params : host - host
* SCpnt - command
* direction - DMA on to/off of card
* transfer - minimum number of bytes we expect to transfer
*/
static void
cumanascsi_2_dma_pseudo(struct Scsi_Host *host, struct scsi_pointer *SCp,
fasdmadir_t direction, int transfer)
{
struct cumanascsi2_info *info = (struct cumanascsi2_info *)host->hostdata;
unsigned int length;
unsigned char *addr;
length = SCp->this_residual;
addr = SCp->ptr;
if (direction == DMA_OUT)
#if 0
while (length > 1) {
unsigned long word;
unsigned int status = readb(info->base + CUMANASCSI2_STATUS);
if (status & STATUS_INT)
goto end;
if (!(status & STATUS_DRQ))
continue;
word = *addr | *(addr + 1) << 8;
writew(word, info->base + CUMANASCSI2_PSEUDODMA);
addr += 2;
length -= 2;
}
#else
printk ("PSEUDO_OUT???\n");
#endif
else {
if (transfer && (transfer & 255)) {
while (length >= 256) {
unsigned int status = readb(info->base + CUMANASCSI2_STATUS);
if (status & STATUS_INT)
return;
if (!(status & STATUS_DRQ))
continue;
readsw(info->base + CUMANASCSI2_PSEUDODMA,
addr, 256 >> 1);
addr += 256;
length -= 256;
}
}
while (length > 0) {
unsigned long word;
unsigned int status = readb(info->base + CUMANASCSI2_STATUS);
if (status & STATUS_INT)
return;
if (!(status & STATUS_DRQ))
continue;
word = readw(info->base + CUMANASCSI2_PSEUDODMA);
*addr++ = word;
if (--length > 0) {
*addr++ = word >> 8;
length --;
}
}
}
}
/* Prototype: int cumanascsi_2_dma_stop(host, SCpnt)
* Purpose : stops DMA/PIO
* Params : host - host
* SCpnt - command
*/
static void
cumanascsi_2_dma_stop(struct Scsi_Host *host, struct scsi_pointer *SCp)
{
struct cumanascsi2_info *info = (struct cumanascsi2_info *)host->hostdata;
if (info->info.scsi.dma != NO_DMA) {
writeb(ALATCH_DIS_DMA, info->base + CUMANASCSI2_ALATCH);
disable_dma(info->info.scsi.dma);
}
}
/* Prototype: const char *cumanascsi_2_info(struct Scsi_Host * host)
* Purpose : returns a descriptive string about this interface,
* Params : host - driver host structure to return info for.
* Returns : pointer to a static buffer containing null terminated string.
*/
const char *cumanascsi_2_info(struct Scsi_Host *host)
{
struct cumanascsi2_info *info = (struct cumanascsi2_info *)host->hostdata;
static char string[150];
sprintf(string, "%s (%s) in slot %d v%s terminators o%s",
host->hostt->name, info->info.scsi.type, info->ec->slot_no,
VERSION, info->terms ? "n" : "ff");
return string;
}
/* Prototype: int cumanascsi_2_set_proc_info(struct Scsi_Host *host, char *buffer, int length)
* Purpose : Set a driver specific function
* Params : host - host to setup
* : buffer - buffer containing string describing operation
* : length - length of string
* Returns : -EINVAL, or 0
*/
static int
cumanascsi_2_set_proc_info(struct Scsi_Host *host, char *buffer, int length)
{
int ret = length;
if (length >= 11 && strncmp(buffer, "CUMANASCSI2", 11) == 0) {
buffer += 11;
length -= 11;
if (length >= 5 && strncmp(buffer, "term=", 5) == 0) {
if (buffer[5] == '1')
cumanascsi_2_terminator_ctl(host, 1);
else if (buffer[5] == '0')
cumanascsi_2_terminator_ctl(host, 0);
else
ret = -EINVAL;
} else
ret = -EINVAL;
} else
ret = -EINVAL;
return ret;
}
static int cumanascsi_2_show_info(struct seq_file *m, struct Scsi_Host *host)
{
struct cumanascsi2_info *info;
info = (struct cumanascsi2_info *)host->hostdata;
seq_printf(m, "Cumana SCSI II driver v%s\n", VERSION);
fas216_print_host(&info->info, m);
seq_printf(m, "Term : o%s\n",
info->terms ? "n" : "ff");
fas216_print_stats(&info->info, m);
fas216_print_devices(&info->info, m);
return 0;
}
static struct scsi_host_template cumanascsi2_template = {
.module = THIS_MODULE,
.show_info = cumanascsi_2_show_info,
.write_info = cumanascsi_2_set_proc_info,
.name = "Cumana SCSI II",
.info = cumanascsi_2_info,
.queuecommand = fas216_queue_command,
.eh_host_reset_handler = fas216_eh_host_reset,
.eh_bus_reset_handler = fas216_eh_bus_reset,
.eh_device_reset_handler = fas216_eh_device_reset,
.eh_abort_handler = fas216_eh_abort,
.can_queue = 1,
.this_id = 7,
.sg_tablesize = SCSI_MAX_SG_CHAIN_SEGMENTS,
.dma_boundary = IOMD_DMA_BOUNDARY,
.cmd_per_lun = 1,
.use_clustering = DISABLE_CLUSTERING,
.proc_name = "cumanascsi2",
};
static int cumanascsi2_probe(struct expansion_card *ec,
const struct ecard_id *id)
{
struct Scsi_Host *host;
struct cumanascsi2_info *info;
void __iomem *base;
int ret;
ret = ecard_request_resources(ec);
if (ret)
goto out;
base = ecardm_iomap(ec, ECARD_RES_MEMC, 0, 0);
if (!base) {
ret = -ENOMEM;
goto out_region;
}
host = scsi_host_alloc(&cumanascsi2_template,
sizeof(struct cumanascsi2_info));
if (!host) {
ret = -ENOMEM;
goto out_region;
}
ecard_set_drvdata(ec, host);
info = (struct cumanascsi2_info *)host->hostdata;
info->ec = ec;
info->base = base;
cumanascsi_2_terminator_ctl(host, term[ec->slot_no]);
info->info.scsi.io_base = base + CUMANASCSI2_FAS216_OFFSET;
info->info.scsi.io_shift = CUMANASCSI2_FAS216_SHIFT;
info->info.scsi.irq = ec->irq;
info->info.scsi.dma = ec->dma;
info->info.ifcfg.clockrate = 40; /* MHz */
info->info.ifcfg.select_timeout = 255;
info->info.ifcfg.asyncperiod = 200; /* ns */
info->info.ifcfg.sync_max_depth = 7;
info->info.ifcfg.cntl3 = CNTL3_BS8 | CNTL3_FASTSCSI | CNTL3_FASTCLK;
info->info.ifcfg.disconnect_ok = 1;
info->info.ifcfg.wide_max_size = 0;
info->info.ifcfg.capabilities = FASCAP_PSEUDODMA;
info->info.dma.setup = cumanascsi_2_dma_setup;
info->info.dma.pseudo = cumanascsi_2_dma_pseudo;
info->info.dma.stop = cumanascsi_2_dma_stop;
ec->irqaddr = info->base + CUMANASCSI2_STATUS;
ec->irqmask = STATUS_INT;
ecard_setirq(ec, &cumanascsi_2_ops, info);
ret = fas216_init(host);
if (ret)
goto out_free;
ret = request_irq(ec->irq, cumanascsi_2_intr,
IRQF_DISABLED, "cumanascsi2", info);
if (ret) {
printk("scsi%d: IRQ%d not free: %d\n",
host->host_no, ec->irq, ret);
goto out_release;
}
if (info->info.scsi.dma != NO_DMA) {
if (request_dma(info->info.scsi.dma, "cumanascsi2")) {
printk("scsi%d: DMA%d not free, using PIO\n",
host->host_no, info->info.scsi.dma);
info->info.scsi.dma = NO_DMA;
} else {
set_dma_speed(info->info.scsi.dma, 180);
info->info.ifcfg.capabilities |= FASCAP_DMA;
}
}
ret = fas216_add(host, &ec->dev);
if (ret == 0)
goto out;
if (info->info.scsi.dma != NO_DMA)
free_dma(info->info.scsi.dma);
free_irq(ec->irq, host);
out_release:
fas216_release(host);
out_free:
scsi_host_put(host);
out_region:
ecard_release_resources(ec);
out:
return ret;
}
static void cumanascsi2_remove(struct expansion_card *ec)
{
struct Scsi_Host *host = ecard_get_drvdata(ec);
struct cumanascsi2_info *info = (struct cumanascsi2_info *)host->hostdata;
ecard_set_drvdata(ec, NULL);
fas216_remove(host);
if (info->info.scsi.dma != NO_DMA)
free_dma(info->info.scsi.dma);
free_irq(ec->irq, info);
fas216_release(host);
scsi_host_put(host);
ecard_release_resources(ec);
}
static const struct ecard_id cumanascsi2_cids[] = {
{ MANU_CUMANA, PROD_CUMANA_SCSI_2 },
{ 0xffff, 0xffff },
};
static struct ecard_driver cumanascsi2_driver = {
.probe = cumanascsi2_probe,
.remove = cumanascsi2_remove,
.id_table = cumanascsi2_cids,
.drv = {
.name = "cumanascsi2",
},
};
static int __init cumanascsi2_init(void)
{
return ecard_register_driver(&cumanascsi2_driver);
}
static void __exit cumanascsi2_exit(void)
{
ecard_remove_driver(&cumanascsi2_driver);
}
module_init(cumanascsi2_init);
module_exit(cumanascsi2_exit);
MODULE_AUTHOR("Russell King");
MODULE_DESCRIPTION("Cumana SCSI-2 driver for Acorn machines");
module_param_array(term, int, NULL, 0);
MODULE_PARM_DESC(term, "SCSI bus termination");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Fevax/exynos8890_stock | drivers/cpufreq/cpufreq_performance.c | 3071 | 1476 | /*
* linux/drivers/cpufreq/cpufreq_performance.c
*
* Copyright (C) 2002 - 2003 Dominik Brodowski <linux@brodo.de>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/cpufreq.h>
#include <linux/init.h>
#include <linux/module.h>
static int cpufreq_governor_performance(struct cpufreq_policy *policy,
unsigned int event)
{
switch (event) {
case CPUFREQ_GOV_START:
case CPUFREQ_GOV_LIMITS:
pr_debug("setting to %u kHz because of event %u\n",
policy->max, event);
__cpufreq_driver_target(policy, policy->max,
CPUFREQ_RELATION_H);
break;
default:
break;
}
return 0;
}
#ifdef CONFIG_CPU_FREQ_GOV_PERFORMANCE_MODULE
static
#endif
struct cpufreq_governor cpufreq_gov_performance = {
.name = "performance",
.governor = cpufreq_governor_performance,
.owner = THIS_MODULE,
};
static int __init cpufreq_gov_performance_init(void)
{
return cpufreq_register_governor(&cpufreq_gov_performance);
}
static void __exit cpufreq_gov_performance_exit(void)
{
cpufreq_unregister_governor(&cpufreq_gov_performance);
}
MODULE_AUTHOR("Dominik Brodowski <linux@brodo.de>");
MODULE_DESCRIPTION("CPUfreq policy governor 'performance'");
MODULE_LICENSE("GPL");
fs_initcall(cpufreq_gov_performance_init);
module_exit(cpufreq_gov_performance_exit);
| gpl-2.0 |
gengzh0016/kernel_BBxM | fs/fat/file.c | 3327 | 11218 | /*
* linux/fs/fat/file.c
*
* Written 1992,1993 by Werner Almesberger
*
* regular file handling primitives for fat-based filesystems
*/
#include <linux/capability.h>
#include <linux/module.h>
#include <linux/compat.h>
#include <linux/mount.h>
#include <linux/time.h>
#include <linux/buffer_head.h>
#include <linux/writeback.h>
#include <linux/backing-dev.h>
#include <linux/blkdev.h>
#include <linux/fsnotify.h>
#include <linux/security.h>
#include "fat.h"
static int fat_ioctl_get_attributes(struct inode *inode, u32 __user *user_attr)
{
u32 attr;
mutex_lock(&inode->i_mutex);
attr = fat_make_attrs(inode);
mutex_unlock(&inode->i_mutex);
return put_user(attr, user_attr);
}
static int fat_ioctl_set_attributes(struct file *file, u32 __user *user_attr)
{
struct inode *inode = file->f_path.dentry->d_inode;
struct msdos_sb_info *sbi = MSDOS_SB(inode->i_sb);
int is_dir = S_ISDIR(inode->i_mode);
u32 attr, oldattr;
struct iattr ia;
int err;
err = get_user(attr, user_attr);
if (err)
goto out;
mutex_lock(&inode->i_mutex);
err = mnt_want_write_file(file);
if (err)
goto out_unlock_inode;
/*
* ATTR_VOLUME and ATTR_DIR cannot be changed; this also
* prevents the user from turning us into a VFAT
* longname entry. Also, we obviously can't set
* any of the NTFS attributes in the high 24 bits.
*/
attr &= 0xff & ~(ATTR_VOLUME | ATTR_DIR);
/* Merge in ATTR_VOLUME and ATTR_DIR */
attr |= (MSDOS_I(inode)->i_attrs & ATTR_VOLUME) |
(is_dir ? ATTR_DIR : 0);
oldattr = fat_make_attrs(inode);
/* Equivalent to a chmod() */
ia.ia_valid = ATTR_MODE | ATTR_CTIME;
ia.ia_ctime = current_fs_time(inode->i_sb);
if (is_dir)
ia.ia_mode = fat_make_mode(sbi, attr, S_IRWXUGO);
else {
ia.ia_mode = fat_make_mode(sbi, attr,
S_IRUGO | S_IWUGO | (inode->i_mode & S_IXUGO));
}
/* The root directory has no attributes */
if (inode->i_ino == MSDOS_ROOT_INO && attr != ATTR_DIR) {
err = -EINVAL;
goto out_drop_write;
}
if (sbi->options.sys_immutable &&
((attr | oldattr) & ATTR_SYS) &&
!capable(CAP_LINUX_IMMUTABLE)) {
err = -EPERM;
goto out_drop_write;
}
/*
* The security check is questionable... We single
* out the RO attribute for checking by the security
* module, just because it maps to a file mode.
*/
err = security_inode_setattr(file->f_path.dentry, &ia);
if (err)
goto out_drop_write;
/* This MUST be done before doing anything irreversible... */
err = fat_setattr(file->f_path.dentry, &ia);
if (err)
goto out_drop_write;
fsnotify_change(file->f_path.dentry, ia.ia_valid);
if (sbi->options.sys_immutable) {
if (attr & ATTR_SYS)
inode->i_flags |= S_IMMUTABLE;
else
inode->i_flags &= ~S_IMMUTABLE;
}
fat_save_attrs(inode, attr);
mark_inode_dirty(inode);
out_drop_write:
mnt_drop_write_file(file);
out_unlock_inode:
mutex_unlock(&inode->i_mutex);
out:
return err;
}
long fat_generic_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
struct inode *inode = filp->f_path.dentry->d_inode;
u32 __user *user_attr = (u32 __user *)arg;
switch (cmd) {
case FAT_IOCTL_GET_ATTRIBUTES:
return fat_ioctl_get_attributes(inode, user_attr);
case FAT_IOCTL_SET_ATTRIBUTES:
return fat_ioctl_set_attributes(filp, user_attr);
default:
return -ENOTTY; /* Inappropriate ioctl for device */
}
}
#ifdef CONFIG_COMPAT
static long fat_generic_compat_ioctl(struct file *filp, unsigned int cmd,
unsigned long arg)
{
return fat_generic_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
}
#endif
static int fat_file_release(struct inode *inode, struct file *filp)
{
if ((filp->f_mode & FMODE_WRITE) &&
MSDOS_SB(inode->i_sb)->options.flush) {
fat_flush_inodes(inode->i_sb, inode, NULL);
congestion_wait(BLK_RW_ASYNC, HZ/10);
}
return 0;
}
int fat_file_fsync(struct file *filp, loff_t start, loff_t end, int datasync)
{
struct inode *inode = filp->f_mapping->host;
int res, err;
res = generic_file_fsync(filp, start, end, datasync);
err = sync_mapping_buffers(MSDOS_SB(inode->i_sb)->fat_inode->i_mapping);
return res ? res : err;
}
const struct file_operations fat_file_operations = {
.llseek = generic_file_llseek,
.read = do_sync_read,
.write = do_sync_write,
.aio_read = generic_file_aio_read,
.aio_write = generic_file_aio_write,
.mmap = generic_file_mmap,
.release = fat_file_release,
.unlocked_ioctl = fat_generic_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = fat_generic_compat_ioctl,
#endif
.fsync = fat_file_fsync,
.splice_read = generic_file_splice_read,
};
static int fat_cont_expand(struct inode *inode, loff_t size)
{
struct address_space *mapping = inode->i_mapping;
loff_t start = inode->i_size, count = size - inode->i_size;
int err;
err = generic_cont_expand_simple(inode, size);
if (err)
goto out;
inode->i_ctime = inode->i_mtime = CURRENT_TIME_SEC;
mark_inode_dirty(inode);
if (IS_SYNC(inode)) {
int err2;
/*
* Opencode syncing since we don't have a file open to use
* standard fsync path.
*/
err = filemap_fdatawrite_range(mapping, start,
start + count - 1);
err2 = sync_mapping_buffers(mapping);
if (!err)
err = err2;
err2 = write_inode_now(inode, 1);
if (!err)
err = err2;
if (!err) {
err = filemap_fdatawait_range(mapping, start,
start + count - 1);
}
}
out:
return err;
}
/* Free all clusters after the skip'th cluster. */
static int fat_free(struct inode *inode, int skip)
{
struct super_block *sb = inode->i_sb;
int err, wait, free_start, i_start, i_logstart;
if (MSDOS_I(inode)->i_start == 0)
return 0;
fat_cache_inval_inode(inode);
wait = IS_DIRSYNC(inode);
i_start = free_start = MSDOS_I(inode)->i_start;
i_logstart = MSDOS_I(inode)->i_logstart;
/* First, we write the new file size. */
if (!skip) {
MSDOS_I(inode)->i_start = 0;
MSDOS_I(inode)->i_logstart = 0;
}
MSDOS_I(inode)->i_attrs |= ATTR_ARCH;
inode->i_ctime = inode->i_mtime = CURRENT_TIME_SEC;
if (wait) {
err = fat_sync_inode(inode);
if (err) {
MSDOS_I(inode)->i_start = i_start;
MSDOS_I(inode)->i_logstart = i_logstart;
return err;
}
} else
mark_inode_dirty(inode);
/* Write a new EOF, and get the remaining cluster chain for freeing. */
if (skip) {
struct fat_entry fatent;
int ret, fclus, dclus;
ret = fat_get_cluster(inode, skip - 1, &fclus, &dclus);
if (ret < 0)
return ret;
else if (ret == FAT_ENT_EOF)
return 0;
fatent_init(&fatent);
ret = fat_ent_read(inode, &fatent, dclus);
if (ret == FAT_ENT_EOF) {
fatent_brelse(&fatent);
return 0;
} else if (ret == FAT_ENT_FREE) {
fat_fs_error(sb,
"%s: invalid cluster chain (i_pos %lld)",
__func__, MSDOS_I(inode)->i_pos);
ret = -EIO;
} else if (ret > 0) {
err = fat_ent_write(inode, &fatent, FAT_ENT_EOF, wait);
if (err)
ret = err;
}
fatent_brelse(&fatent);
if (ret < 0)
return ret;
free_start = ret;
}
inode->i_blocks = skip << (MSDOS_SB(sb)->cluster_bits - 9);
/* Freeing the remained cluster chain */
return fat_free_clusters(inode, free_start);
}
void fat_truncate_blocks(struct inode *inode, loff_t offset)
{
struct msdos_sb_info *sbi = MSDOS_SB(inode->i_sb);
const unsigned int cluster_size = sbi->cluster_size;
int nr_clusters;
/*
* This protects against truncating a file bigger than it was then
* trying to write into the hole.
*/
if (MSDOS_I(inode)->mmu_private > offset)
MSDOS_I(inode)->mmu_private = offset;
nr_clusters = (offset + (cluster_size - 1)) >> sbi->cluster_bits;
fat_free(inode, nr_clusters);
fat_flush_inodes(inode->i_sb, inode, NULL);
}
int fat_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat)
{
struct inode *inode = dentry->d_inode;
generic_fillattr(inode, stat);
stat->blksize = MSDOS_SB(inode->i_sb)->cluster_size;
return 0;
}
EXPORT_SYMBOL_GPL(fat_getattr);
static int fat_sanitize_mode(const struct msdos_sb_info *sbi,
struct inode *inode, umode_t *mode_ptr)
{
umode_t mask, perm;
/*
* Note, the basic check is already done by a caller of
* (attr->ia_mode & ~FAT_VALID_MODE)
*/
if (S_ISREG(inode->i_mode))
mask = sbi->options.fs_fmask;
else
mask = sbi->options.fs_dmask;
perm = *mode_ptr & ~(S_IFMT | mask);
/*
* Of the r and x bits, all (subject to umask) must be present. Of the
* w bits, either all (subject to umask) or none must be present.
*
* If fat_mode_can_hold_ro(inode) is false, can't change w bits.
*/
if ((perm & (S_IRUGO | S_IXUGO)) != (inode->i_mode & (S_IRUGO|S_IXUGO)))
return -EPERM;
if (fat_mode_can_hold_ro(inode)) {
if ((perm & S_IWUGO) && ((perm & S_IWUGO) != (S_IWUGO & ~mask)))
return -EPERM;
} else {
if ((perm & S_IWUGO) != (S_IWUGO & ~mask))
return -EPERM;
}
*mode_ptr &= S_IFMT | perm;
return 0;
}
static int fat_allow_set_time(struct msdos_sb_info *sbi, struct inode *inode)
{
umode_t allow_utime = sbi->options.allow_utime;
if (current_fsuid() != inode->i_uid) {
if (in_group_p(inode->i_gid))
allow_utime >>= 3;
if (allow_utime & MAY_WRITE)
return 1;
}
/* use a default check */
return 0;
}
#define TIMES_SET_FLAGS (ATTR_MTIME_SET | ATTR_ATIME_SET | ATTR_TIMES_SET)
/* valid file mode bits */
#define FAT_VALID_MODE (S_IFREG | S_IFDIR | S_IRWXUGO)
int fat_setattr(struct dentry *dentry, struct iattr *attr)
{
struct msdos_sb_info *sbi = MSDOS_SB(dentry->d_sb);
struct inode *inode = dentry->d_inode;
unsigned int ia_valid;
int error;
/* Check for setting the inode time. */
ia_valid = attr->ia_valid;
if (ia_valid & TIMES_SET_FLAGS) {
if (fat_allow_set_time(sbi, inode))
attr->ia_valid &= ~TIMES_SET_FLAGS;
}
error = inode_change_ok(inode, attr);
attr->ia_valid = ia_valid;
if (error) {
if (sbi->options.quiet)
error = 0;
goto out;
}
/*
* Expand the file. Since inode_setattr() updates ->i_size
* before calling the ->truncate(), but FAT needs to fill the
* hole before it. XXX: this is no longer true with new truncate
* sequence.
*/
if (attr->ia_valid & ATTR_SIZE) {
inode_dio_wait(inode);
if (attr->ia_size > inode->i_size) {
error = fat_cont_expand(inode, attr->ia_size);
if (error || attr->ia_valid == ATTR_SIZE)
goto out;
attr->ia_valid &= ~ATTR_SIZE;
}
}
if (((attr->ia_valid & ATTR_UID) &&
(attr->ia_uid != sbi->options.fs_uid)) ||
((attr->ia_valid & ATTR_GID) &&
(attr->ia_gid != sbi->options.fs_gid)) ||
((attr->ia_valid & ATTR_MODE) &&
(attr->ia_mode & ~FAT_VALID_MODE)))
error = -EPERM;
if (error) {
if (sbi->options.quiet)
error = 0;
goto out;
}
/*
* We don't return -EPERM here. Yes, strange, but this is too
* old behavior.
*/
if (attr->ia_valid & ATTR_MODE) {
if (fat_sanitize_mode(sbi, inode, &attr->ia_mode) < 0)
attr->ia_valid &= ~ATTR_MODE;
}
if (attr->ia_valid & ATTR_SIZE) {
down_write(&MSDOS_I(inode)->truncate_lock);
truncate_setsize(inode, attr->ia_size);
fat_truncate_blocks(inode, attr->ia_size);
up_write(&MSDOS_I(inode)->truncate_lock);
}
setattr_copy(inode, attr);
mark_inode_dirty(inode);
out:
return error;
}
EXPORT_SYMBOL_GPL(fat_setattr);
const struct inode_operations fat_file_inode_operations = {
.setattr = fat_setattr,
.getattr = fat_getattr,
};
| gpl-2.0 |
Mr-AW/Kernel_TeLo_LP_LenovoA6000 | net/wireless/lib80211_crypt_tkip.c | 4095 | 20847 | /*
* lib80211 crypt: host-based TKIP encryption implementation for lib80211
*
* Copyright (c) 2003-2004, Jouni Malinen <j@w1.fi>
* Copyright (c) 2008, John W. Linville <linville@tuxdriver.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation. See README and COPYING for
* more details.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/err.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/random.h>
#include <linux/scatterlist.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/mm.h>
#include <linux/if_ether.h>
#include <linux/if_arp.h>
#include <asm/string.h>
#include <linux/wireless.h>
#include <linux/ieee80211.h>
#include <net/iw_handler.h>
#include <linux/crypto.h>
#include <linux/crc32.h>
#include <net/lib80211.h>
MODULE_AUTHOR("Jouni Malinen");
MODULE_DESCRIPTION("lib80211 crypt: TKIP");
MODULE_LICENSE("GPL");
#define TKIP_HDR_LEN 8
struct lib80211_tkip_data {
#define TKIP_KEY_LEN 32
u8 key[TKIP_KEY_LEN];
int key_set;
u32 tx_iv32;
u16 tx_iv16;
u16 tx_ttak[5];
int tx_phase1_done;
u32 rx_iv32;
u16 rx_iv16;
u16 rx_ttak[5];
int rx_phase1_done;
u32 rx_iv32_new;
u16 rx_iv16_new;
u32 dot11RSNAStatsTKIPReplays;
u32 dot11RSNAStatsTKIPICVErrors;
u32 dot11RSNAStatsTKIPLocalMICFailures;
int key_idx;
struct crypto_blkcipher *rx_tfm_arc4;
struct crypto_hash *rx_tfm_michael;
struct crypto_blkcipher *tx_tfm_arc4;
struct crypto_hash *tx_tfm_michael;
/* scratch buffers for virt_to_page() (crypto API) */
u8 rx_hdr[16], tx_hdr[16];
unsigned long flags;
};
static unsigned long lib80211_tkip_set_flags(unsigned long flags, void *priv)
{
struct lib80211_tkip_data *_priv = priv;
unsigned long old_flags = _priv->flags;
_priv->flags = flags;
return old_flags;
}
static unsigned long lib80211_tkip_get_flags(void *priv)
{
struct lib80211_tkip_data *_priv = priv;
return _priv->flags;
}
static void *lib80211_tkip_init(int key_idx)
{
struct lib80211_tkip_data *priv;
priv = kzalloc(sizeof(*priv), GFP_ATOMIC);
if (priv == NULL)
goto fail;
priv->key_idx = key_idx;
priv->tx_tfm_arc4 = crypto_alloc_blkcipher("ecb(arc4)", 0,
CRYPTO_ALG_ASYNC);
if (IS_ERR(priv->tx_tfm_arc4)) {
priv->tx_tfm_arc4 = NULL;
goto fail;
}
priv->tx_tfm_michael = crypto_alloc_hash("michael_mic", 0,
CRYPTO_ALG_ASYNC);
if (IS_ERR(priv->tx_tfm_michael)) {
priv->tx_tfm_michael = NULL;
goto fail;
}
priv->rx_tfm_arc4 = crypto_alloc_blkcipher("ecb(arc4)", 0,
CRYPTO_ALG_ASYNC);
if (IS_ERR(priv->rx_tfm_arc4)) {
priv->rx_tfm_arc4 = NULL;
goto fail;
}
priv->rx_tfm_michael = crypto_alloc_hash("michael_mic", 0,
CRYPTO_ALG_ASYNC);
if (IS_ERR(priv->rx_tfm_michael)) {
priv->rx_tfm_michael = NULL;
goto fail;
}
return priv;
fail:
if (priv) {
if (priv->tx_tfm_michael)
crypto_free_hash(priv->tx_tfm_michael);
if (priv->tx_tfm_arc4)
crypto_free_blkcipher(priv->tx_tfm_arc4);
if (priv->rx_tfm_michael)
crypto_free_hash(priv->rx_tfm_michael);
if (priv->rx_tfm_arc4)
crypto_free_blkcipher(priv->rx_tfm_arc4);
kfree(priv);
}
return NULL;
}
static void lib80211_tkip_deinit(void *priv)
{
struct lib80211_tkip_data *_priv = priv;
if (_priv) {
if (_priv->tx_tfm_michael)
crypto_free_hash(_priv->tx_tfm_michael);
if (_priv->tx_tfm_arc4)
crypto_free_blkcipher(_priv->tx_tfm_arc4);
if (_priv->rx_tfm_michael)
crypto_free_hash(_priv->rx_tfm_michael);
if (_priv->rx_tfm_arc4)
crypto_free_blkcipher(_priv->rx_tfm_arc4);
}
kfree(priv);
}
static inline u16 RotR1(u16 val)
{
return (val >> 1) | (val << 15);
}
static inline u8 Lo8(u16 val)
{
return val & 0xff;
}
static inline u8 Hi8(u16 val)
{
return val >> 8;
}
static inline u16 Lo16(u32 val)
{
return val & 0xffff;
}
static inline u16 Hi16(u32 val)
{
return val >> 16;
}
static inline u16 Mk16(u8 hi, u8 lo)
{
return lo | (((u16) hi) << 8);
}
static inline u16 Mk16_le(__le16 * v)
{
return le16_to_cpu(*v);
}
static const u16 Sbox[256] = {
0xC6A5, 0xF884, 0xEE99, 0xF68D, 0xFF0D, 0xD6BD, 0xDEB1, 0x9154,
0x6050, 0x0203, 0xCEA9, 0x567D, 0xE719, 0xB562, 0x4DE6, 0xEC9A,
0x8F45, 0x1F9D, 0x8940, 0xFA87, 0xEF15, 0xB2EB, 0x8EC9, 0xFB0B,
0x41EC, 0xB367, 0x5FFD, 0x45EA, 0x23BF, 0x53F7, 0xE496, 0x9B5B,
0x75C2, 0xE11C, 0x3DAE, 0x4C6A, 0x6C5A, 0x7E41, 0xF502, 0x834F,
0x685C, 0x51F4, 0xD134, 0xF908, 0xE293, 0xAB73, 0x6253, 0x2A3F,
0x080C, 0x9552, 0x4665, 0x9D5E, 0x3028, 0x37A1, 0x0A0F, 0x2FB5,
0x0E09, 0x2436, 0x1B9B, 0xDF3D, 0xCD26, 0x4E69, 0x7FCD, 0xEA9F,
0x121B, 0x1D9E, 0x5874, 0x342E, 0x362D, 0xDCB2, 0xB4EE, 0x5BFB,
0xA4F6, 0x764D, 0xB761, 0x7DCE, 0x527B, 0xDD3E, 0x5E71, 0x1397,
0xA6F5, 0xB968, 0x0000, 0xC12C, 0x4060, 0xE31F, 0x79C8, 0xB6ED,
0xD4BE, 0x8D46, 0x67D9, 0x724B, 0x94DE, 0x98D4, 0xB0E8, 0x854A,
0xBB6B, 0xC52A, 0x4FE5, 0xED16, 0x86C5, 0x9AD7, 0x6655, 0x1194,
0x8ACF, 0xE910, 0x0406, 0xFE81, 0xA0F0, 0x7844, 0x25BA, 0x4BE3,
0xA2F3, 0x5DFE, 0x80C0, 0x058A, 0x3FAD, 0x21BC, 0x7048, 0xF104,
0x63DF, 0x77C1, 0xAF75, 0x4263, 0x2030, 0xE51A, 0xFD0E, 0xBF6D,
0x814C, 0x1814, 0x2635, 0xC32F, 0xBEE1, 0x35A2, 0x88CC, 0x2E39,
0x9357, 0x55F2, 0xFC82, 0x7A47, 0xC8AC, 0xBAE7, 0x322B, 0xE695,
0xC0A0, 0x1998, 0x9ED1, 0xA37F, 0x4466, 0x547E, 0x3BAB, 0x0B83,
0x8CCA, 0xC729, 0x6BD3, 0x283C, 0xA779, 0xBCE2, 0x161D, 0xAD76,
0xDB3B, 0x6456, 0x744E, 0x141E, 0x92DB, 0x0C0A, 0x486C, 0xB8E4,
0x9F5D, 0xBD6E, 0x43EF, 0xC4A6, 0x39A8, 0x31A4, 0xD337, 0xF28B,
0xD532, 0x8B43, 0x6E59, 0xDAB7, 0x018C, 0xB164, 0x9CD2, 0x49E0,
0xD8B4, 0xACFA, 0xF307, 0xCF25, 0xCAAF, 0xF48E, 0x47E9, 0x1018,
0x6FD5, 0xF088, 0x4A6F, 0x5C72, 0x3824, 0x57F1, 0x73C7, 0x9751,
0xCB23, 0xA17C, 0xE89C, 0x3E21, 0x96DD, 0x61DC, 0x0D86, 0x0F85,
0xE090, 0x7C42, 0x71C4, 0xCCAA, 0x90D8, 0x0605, 0xF701, 0x1C12,
0xC2A3, 0x6A5F, 0xAEF9, 0x69D0, 0x1791, 0x9958, 0x3A27, 0x27B9,
0xD938, 0xEB13, 0x2BB3, 0x2233, 0xD2BB, 0xA970, 0x0789, 0x33A7,
0x2DB6, 0x3C22, 0x1592, 0xC920, 0x8749, 0xAAFF, 0x5078, 0xA57A,
0x038F, 0x59F8, 0x0980, 0x1A17, 0x65DA, 0xD731, 0x84C6, 0xD0B8,
0x82C3, 0x29B0, 0x5A77, 0x1E11, 0x7BCB, 0xA8FC, 0x6DD6, 0x2C3A,
};
static inline u16 _S_(u16 v)
{
u16 t = Sbox[Hi8(v)];
return Sbox[Lo8(v)] ^ ((t << 8) | (t >> 8));
}
#define PHASE1_LOOP_COUNT 8
static void tkip_mixing_phase1(u16 * TTAK, const u8 * TK, const u8 * TA,
u32 IV32)
{
int i, j;
/* Initialize the 80-bit TTAK from TSC (IV32) and TA[0..5] */
TTAK[0] = Lo16(IV32);
TTAK[1] = Hi16(IV32);
TTAK[2] = Mk16(TA[1], TA[0]);
TTAK[3] = Mk16(TA[3], TA[2]);
TTAK[4] = Mk16(TA[5], TA[4]);
for (i = 0; i < PHASE1_LOOP_COUNT; i++) {
j = 2 * (i & 1);
TTAK[0] += _S_(TTAK[4] ^ Mk16(TK[1 + j], TK[0 + j]));
TTAK[1] += _S_(TTAK[0] ^ Mk16(TK[5 + j], TK[4 + j]));
TTAK[2] += _S_(TTAK[1] ^ Mk16(TK[9 + j], TK[8 + j]));
TTAK[3] += _S_(TTAK[2] ^ Mk16(TK[13 + j], TK[12 + j]));
TTAK[4] += _S_(TTAK[3] ^ Mk16(TK[1 + j], TK[0 + j])) + i;
}
}
static void tkip_mixing_phase2(u8 * WEPSeed, const u8 * TK, const u16 * TTAK,
u16 IV16)
{
/* Make temporary area overlap WEP seed so that the final copy can be
* avoided on little endian hosts. */
u16 *PPK = (u16 *) & WEPSeed[4];
/* Step 1 - make copy of TTAK and bring in TSC */
PPK[0] = TTAK[0];
PPK[1] = TTAK[1];
PPK[2] = TTAK[2];
PPK[3] = TTAK[3];
PPK[4] = TTAK[4];
PPK[5] = TTAK[4] + IV16;
/* Step 2 - 96-bit bijective mixing using S-box */
PPK[0] += _S_(PPK[5] ^ Mk16_le((__le16 *) & TK[0]));
PPK[1] += _S_(PPK[0] ^ Mk16_le((__le16 *) & TK[2]));
PPK[2] += _S_(PPK[1] ^ Mk16_le((__le16 *) & TK[4]));
PPK[3] += _S_(PPK[2] ^ Mk16_le((__le16 *) & TK[6]));
PPK[4] += _S_(PPK[3] ^ Mk16_le((__le16 *) & TK[8]));
PPK[5] += _S_(PPK[4] ^ Mk16_le((__le16 *) & TK[10]));
PPK[0] += RotR1(PPK[5] ^ Mk16_le((__le16 *) & TK[12]));
PPK[1] += RotR1(PPK[0] ^ Mk16_le((__le16 *) & TK[14]));
PPK[2] += RotR1(PPK[1]);
PPK[3] += RotR1(PPK[2]);
PPK[4] += RotR1(PPK[3]);
PPK[5] += RotR1(PPK[4]);
/* Step 3 - bring in last of TK bits, assign 24-bit WEP IV value
* WEPSeed[0..2] is transmitted as WEP IV */
WEPSeed[0] = Hi8(IV16);
WEPSeed[1] = (Hi8(IV16) | 0x20) & 0x7F;
WEPSeed[2] = Lo8(IV16);
WEPSeed[3] = Lo8((PPK[5] ^ Mk16_le((__le16 *) & TK[0])) >> 1);
#ifdef __BIG_ENDIAN
{
int i;
for (i = 0; i < 6; i++)
PPK[i] = (PPK[i] << 8) | (PPK[i] >> 8);
}
#endif
}
static int lib80211_tkip_hdr(struct sk_buff *skb, int hdr_len,
u8 * rc4key, int keylen, void *priv)
{
struct lib80211_tkip_data *tkey = priv;
u8 *pos;
struct ieee80211_hdr *hdr;
hdr = (struct ieee80211_hdr *)skb->data;
if (skb_headroom(skb) < TKIP_HDR_LEN || skb->len < hdr_len)
return -1;
if (rc4key == NULL || keylen < 16)
return -1;
if (!tkey->tx_phase1_done) {
tkip_mixing_phase1(tkey->tx_ttak, tkey->key, hdr->addr2,
tkey->tx_iv32);
tkey->tx_phase1_done = 1;
}
tkip_mixing_phase2(rc4key, tkey->key, tkey->tx_ttak, tkey->tx_iv16);
pos = skb_push(skb, TKIP_HDR_LEN);
memmove(pos, pos + TKIP_HDR_LEN, hdr_len);
pos += hdr_len;
*pos++ = *rc4key;
*pos++ = *(rc4key + 1);
*pos++ = *(rc4key + 2);
*pos++ = (tkey->key_idx << 6) | (1 << 5) /* Ext IV included */ ;
*pos++ = tkey->tx_iv32 & 0xff;
*pos++ = (tkey->tx_iv32 >> 8) & 0xff;
*pos++ = (tkey->tx_iv32 >> 16) & 0xff;
*pos++ = (tkey->tx_iv32 >> 24) & 0xff;
tkey->tx_iv16++;
if (tkey->tx_iv16 == 0) {
tkey->tx_phase1_done = 0;
tkey->tx_iv32++;
}
return TKIP_HDR_LEN;
}
static int lib80211_tkip_encrypt(struct sk_buff *skb, int hdr_len, void *priv)
{
struct lib80211_tkip_data *tkey = priv;
struct blkcipher_desc desc = { .tfm = tkey->tx_tfm_arc4 };
int len;
u8 rc4key[16], *pos, *icv;
u32 crc;
struct scatterlist sg;
if (tkey->flags & IEEE80211_CRYPTO_TKIP_COUNTERMEASURES) {
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
net_dbg_ratelimited("TKIP countermeasures: dropped TX packet to %pM\n",
hdr->addr1);
return -1;
}
if (skb_tailroom(skb) < 4 || skb->len < hdr_len)
return -1;
len = skb->len - hdr_len;
pos = skb->data + hdr_len;
if ((lib80211_tkip_hdr(skb, hdr_len, rc4key, 16, priv)) < 0)
return -1;
crc = ~crc32_le(~0, pos, len);
icv = skb_put(skb, 4);
icv[0] = crc;
icv[1] = crc >> 8;
icv[2] = crc >> 16;
icv[3] = crc >> 24;
crypto_blkcipher_setkey(tkey->tx_tfm_arc4, rc4key, 16);
sg_init_one(&sg, pos, len + 4);
return crypto_blkcipher_encrypt(&desc, &sg, &sg, len + 4);
}
/*
* deal with seq counter wrapping correctly.
* refer to timer_after() for jiffies wrapping handling
*/
static inline int tkip_replay_check(u32 iv32_n, u16 iv16_n,
u32 iv32_o, u16 iv16_o)
{
if ((s32)iv32_n - (s32)iv32_o < 0 ||
(iv32_n == iv32_o && iv16_n <= iv16_o))
return 1;
return 0;
}
static int lib80211_tkip_decrypt(struct sk_buff *skb, int hdr_len, void *priv)
{
struct lib80211_tkip_data *tkey = priv;
struct blkcipher_desc desc = { .tfm = tkey->rx_tfm_arc4 };
u8 rc4key[16];
u8 keyidx, *pos;
u32 iv32;
u16 iv16;
struct ieee80211_hdr *hdr;
u8 icv[4];
u32 crc;
struct scatterlist sg;
int plen;
hdr = (struct ieee80211_hdr *)skb->data;
if (tkey->flags & IEEE80211_CRYPTO_TKIP_COUNTERMEASURES) {
net_dbg_ratelimited("TKIP countermeasures: dropped received packet from %pM\n",
hdr->addr2);
return -1;
}
if (skb->len < hdr_len + TKIP_HDR_LEN + 4)
return -1;
pos = skb->data + hdr_len;
keyidx = pos[3];
if (!(keyidx & (1 << 5))) {
net_dbg_ratelimited("TKIP: received packet without ExtIV flag from %pM\n",
hdr->addr2);
return -2;
}
keyidx >>= 6;
if (tkey->key_idx != keyidx) {
printk(KERN_DEBUG "TKIP: RX tkey->key_idx=%d frame "
"keyidx=%d priv=%p\n", tkey->key_idx, keyidx, priv);
return -6;
}
if (!tkey->key_set) {
net_dbg_ratelimited("TKIP: received packet from %pM with keyid=%d that does not have a configured key\n",
hdr->addr2, keyidx);
return -3;
}
iv16 = (pos[0] << 8) | pos[2];
iv32 = pos[4] | (pos[5] << 8) | (pos[6] << 16) | (pos[7] << 24);
pos += TKIP_HDR_LEN;
if (tkip_replay_check(iv32, iv16, tkey->rx_iv32, tkey->rx_iv16)) {
#ifdef CONFIG_LIB80211_DEBUG
net_dbg_ratelimited("TKIP: replay detected: STA=%pM previous TSC %08x%04x received TSC %08x%04x\n",
hdr->addr2, tkey->rx_iv32, tkey->rx_iv16,
iv32, iv16);
#endif
tkey->dot11RSNAStatsTKIPReplays++;
return -4;
}
if (iv32 != tkey->rx_iv32 || !tkey->rx_phase1_done) {
tkip_mixing_phase1(tkey->rx_ttak, tkey->key, hdr->addr2, iv32);
tkey->rx_phase1_done = 1;
}
tkip_mixing_phase2(rc4key, tkey->key, tkey->rx_ttak, iv16);
plen = skb->len - hdr_len - 12;
crypto_blkcipher_setkey(tkey->rx_tfm_arc4, rc4key, 16);
sg_init_one(&sg, pos, plen + 4);
if (crypto_blkcipher_decrypt(&desc, &sg, &sg, plen + 4)) {
net_dbg_ratelimited("TKIP: failed to decrypt received packet from %pM\n",
hdr->addr2);
return -7;
}
crc = ~crc32_le(~0, pos, plen);
icv[0] = crc;
icv[1] = crc >> 8;
icv[2] = crc >> 16;
icv[3] = crc >> 24;
if (memcmp(icv, pos + plen, 4) != 0) {
if (iv32 != tkey->rx_iv32) {
/* Previously cached Phase1 result was already lost, so
* it needs to be recalculated for the next packet. */
tkey->rx_phase1_done = 0;
}
#ifdef CONFIG_LIB80211_DEBUG
net_dbg_ratelimited("TKIP: ICV error detected: STA=%pM\n",
hdr->addr2);
#endif
tkey->dot11RSNAStatsTKIPICVErrors++;
return -5;
}
/* Update real counters only after Michael MIC verification has
* completed */
tkey->rx_iv32_new = iv32;
tkey->rx_iv16_new = iv16;
/* Remove IV and ICV */
memmove(skb->data + TKIP_HDR_LEN, skb->data, hdr_len);
skb_pull(skb, TKIP_HDR_LEN);
skb_trim(skb, skb->len - 4);
return keyidx;
}
static int michael_mic(struct crypto_hash *tfm_michael, u8 * key, u8 * hdr,
u8 * data, size_t data_len, u8 * mic)
{
struct hash_desc desc;
struct scatterlist sg[2];
if (tfm_michael == NULL) {
pr_warn("%s(): tfm_michael == NULL\n", __func__);
return -1;
}
sg_init_table(sg, 2);
sg_set_buf(&sg[0], hdr, 16);
sg_set_buf(&sg[1], data, data_len);
if (crypto_hash_setkey(tfm_michael, key, 8))
return -1;
desc.tfm = tfm_michael;
desc.flags = 0;
return crypto_hash_digest(&desc, sg, data_len + 16, mic);
}
static void michael_mic_hdr(struct sk_buff *skb, u8 * hdr)
{
struct ieee80211_hdr *hdr11;
hdr11 = (struct ieee80211_hdr *)skb->data;
switch (le16_to_cpu(hdr11->frame_control) &
(IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS)) {
case IEEE80211_FCTL_TODS:
memcpy(hdr, hdr11->addr3, ETH_ALEN); /* DA */
memcpy(hdr + ETH_ALEN, hdr11->addr2, ETH_ALEN); /* SA */
break;
case IEEE80211_FCTL_FROMDS:
memcpy(hdr, hdr11->addr1, ETH_ALEN); /* DA */
memcpy(hdr + ETH_ALEN, hdr11->addr3, ETH_ALEN); /* SA */
break;
case IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS:
memcpy(hdr, hdr11->addr3, ETH_ALEN); /* DA */
memcpy(hdr + ETH_ALEN, hdr11->addr4, ETH_ALEN); /* SA */
break;
case 0:
memcpy(hdr, hdr11->addr1, ETH_ALEN); /* DA */
memcpy(hdr + ETH_ALEN, hdr11->addr2, ETH_ALEN); /* SA */
break;
}
if (ieee80211_is_data_qos(hdr11->frame_control)) {
hdr[12] = le16_to_cpu(*((__le16 *)ieee80211_get_qos_ctl(hdr11)))
& IEEE80211_QOS_CTL_TID_MASK;
} else
hdr[12] = 0; /* priority */
hdr[13] = hdr[14] = hdr[15] = 0; /* reserved */
}
static int lib80211_michael_mic_add(struct sk_buff *skb, int hdr_len,
void *priv)
{
struct lib80211_tkip_data *tkey = priv;
u8 *pos;
if (skb_tailroom(skb) < 8 || skb->len < hdr_len) {
printk(KERN_DEBUG "Invalid packet for Michael MIC add "
"(tailroom=%d hdr_len=%d skb->len=%d)\n",
skb_tailroom(skb), hdr_len, skb->len);
return -1;
}
michael_mic_hdr(skb, tkey->tx_hdr);
pos = skb_put(skb, 8);
if (michael_mic(tkey->tx_tfm_michael, &tkey->key[16], tkey->tx_hdr,
skb->data + hdr_len, skb->len - 8 - hdr_len, pos))
return -1;
return 0;
}
static void lib80211_michael_mic_failure(struct net_device *dev,
struct ieee80211_hdr *hdr,
int keyidx)
{
union iwreq_data wrqu;
struct iw_michaelmicfailure ev;
/* TODO: needed parameters: count, keyid, key type, TSC */
memset(&ev, 0, sizeof(ev));
ev.flags = keyidx & IW_MICFAILURE_KEY_ID;
if (hdr->addr1[0] & 0x01)
ev.flags |= IW_MICFAILURE_GROUP;
else
ev.flags |= IW_MICFAILURE_PAIRWISE;
ev.src_addr.sa_family = ARPHRD_ETHER;
memcpy(ev.src_addr.sa_data, hdr->addr2, ETH_ALEN);
memset(&wrqu, 0, sizeof(wrqu));
wrqu.data.length = sizeof(ev);
wireless_send_event(dev, IWEVMICHAELMICFAILURE, &wrqu, (char *)&ev);
}
static int lib80211_michael_mic_verify(struct sk_buff *skb, int keyidx,
int hdr_len, void *priv)
{
struct lib80211_tkip_data *tkey = priv;
u8 mic[8];
if (!tkey->key_set)
return -1;
michael_mic_hdr(skb, tkey->rx_hdr);
if (michael_mic(tkey->rx_tfm_michael, &tkey->key[24], tkey->rx_hdr,
skb->data + hdr_len, skb->len - 8 - hdr_len, mic))
return -1;
if (memcmp(mic, skb->data + skb->len - 8, 8) != 0) {
struct ieee80211_hdr *hdr;
hdr = (struct ieee80211_hdr *)skb->data;
printk(KERN_DEBUG "%s: Michael MIC verification failed for "
"MSDU from %pM keyidx=%d\n",
skb->dev ? skb->dev->name : "N/A", hdr->addr2,
keyidx);
if (skb->dev)
lib80211_michael_mic_failure(skb->dev, hdr, keyidx);
tkey->dot11RSNAStatsTKIPLocalMICFailures++;
return -1;
}
/* Update TSC counters for RX now that the packet verification has
* completed. */
tkey->rx_iv32 = tkey->rx_iv32_new;
tkey->rx_iv16 = tkey->rx_iv16_new;
skb_trim(skb, skb->len - 8);
return 0;
}
static int lib80211_tkip_set_key(void *key, int len, u8 * seq, void *priv)
{
struct lib80211_tkip_data *tkey = priv;
int keyidx;
struct crypto_hash *tfm = tkey->tx_tfm_michael;
struct crypto_blkcipher *tfm2 = tkey->tx_tfm_arc4;
struct crypto_hash *tfm3 = tkey->rx_tfm_michael;
struct crypto_blkcipher *tfm4 = tkey->rx_tfm_arc4;
keyidx = tkey->key_idx;
memset(tkey, 0, sizeof(*tkey));
tkey->key_idx = keyidx;
tkey->tx_tfm_michael = tfm;
tkey->tx_tfm_arc4 = tfm2;
tkey->rx_tfm_michael = tfm3;
tkey->rx_tfm_arc4 = tfm4;
if (len == TKIP_KEY_LEN) {
memcpy(tkey->key, key, TKIP_KEY_LEN);
tkey->key_set = 1;
tkey->tx_iv16 = 1; /* TSC is initialized to 1 */
if (seq) {
tkey->rx_iv32 = (seq[5] << 24) | (seq[4] << 16) |
(seq[3] << 8) | seq[2];
tkey->rx_iv16 = (seq[1] << 8) | seq[0];
}
} else if (len == 0)
tkey->key_set = 0;
else
return -1;
return 0;
}
static int lib80211_tkip_get_key(void *key, int len, u8 * seq, void *priv)
{
struct lib80211_tkip_data *tkey = priv;
if (len < TKIP_KEY_LEN)
return -1;
if (!tkey->key_set)
return 0;
memcpy(key, tkey->key, TKIP_KEY_LEN);
if (seq) {
/* Return the sequence number of the last transmitted frame. */
u16 iv16 = tkey->tx_iv16;
u32 iv32 = tkey->tx_iv32;
if (iv16 == 0)
iv32--;
iv16--;
seq[0] = tkey->tx_iv16;
seq[1] = tkey->tx_iv16 >> 8;
seq[2] = tkey->tx_iv32;
seq[3] = tkey->tx_iv32 >> 8;
seq[4] = tkey->tx_iv32 >> 16;
seq[5] = tkey->tx_iv32 >> 24;
}
return TKIP_KEY_LEN;
}
static void lib80211_tkip_print_stats(struct seq_file *m, void *priv)
{
struct lib80211_tkip_data *tkip = priv;
seq_printf(m,
"key[%d] alg=TKIP key_set=%d "
"tx_pn=%02x%02x%02x%02x%02x%02x "
"rx_pn=%02x%02x%02x%02x%02x%02x "
"replays=%d icv_errors=%d local_mic_failures=%d\n",
tkip->key_idx, tkip->key_set,
(tkip->tx_iv32 >> 24) & 0xff,
(tkip->tx_iv32 >> 16) & 0xff,
(tkip->tx_iv32 >> 8) & 0xff,
tkip->tx_iv32 & 0xff,
(tkip->tx_iv16 >> 8) & 0xff,
tkip->tx_iv16 & 0xff,
(tkip->rx_iv32 >> 24) & 0xff,
(tkip->rx_iv32 >> 16) & 0xff,
(tkip->rx_iv32 >> 8) & 0xff,
tkip->rx_iv32 & 0xff,
(tkip->rx_iv16 >> 8) & 0xff,
tkip->rx_iv16 & 0xff,
tkip->dot11RSNAStatsTKIPReplays,
tkip->dot11RSNAStatsTKIPICVErrors,
tkip->dot11RSNAStatsTKIPLocalMICFailures);
}
static struct lib80211_crypto_ops lib80211_crypt_tkip = {
.name = "TKIP",
.init = lib80211_tkip_init,
.deinit = lib80211_tkip_deinit,
.encrypt_mpdu = lib80211_tkip_encrypt,
.decrypt_mpdu = lib80211_tkip_decrypt,
.encrypt_msdu = lib80211_michael_mic_add,
.decrypt_msdu = lib80211_michael_mic_verify,
.set_key = lib80211_tkip_set_key,
.get_key = lib80211_tkip_get_key,
.print_stats = lib80211_tkip_print_stats,
.extra_mpdu_prefix_len = 4 + 4, /* IV + ExtIV */
.extra_mpdu_postfix_len = 4, /* ICV */
.extra_msdu_postfix_len = 8, /* MIC */
.get_flags = lib80211_tkip_get_flags,
.set_flags = lib80211_tkip_set_flags,
.owner = THIS_MODULE,
};
static int __init lib80211_crypto_tkip_init(void)
{
return lib80211_register_crypto_ops(&lib80211_crypt_tkip);
}
static void __exit lib80211_crypto_tkip_exit(void)
{
lib80211_unregister_crypto_ops(&lib80211_crypt_tkip);
}
module_init(lib80211_crypto_tkip_init);
module_exit(lib80211_crypto_tkip_exit);
| gpl-2.0 |
lenghonglin/LU6200_Android_JB_LU620186_00_Kernel | drivers/media/video/tw9910.c | 4863 | 23030 | /*
* tw9910 Video Driver
*
* Copyright (C) 2008 Renesas Solutions Corp.
* Kuninori Morimoto <morimoto.kuninori@renesas.com>
*
* Based on ov772x driver,
*
* Copyright (C) 2008 Kuninori Morimoto <morimoto.kuninori@renesas.com>
* Copyright 2006-7 Jonathan Corbet <corbet@lwn.net>
* Copyright (C) 2008 Magnus Damm
* Copyright (C) 2008, Guennadi Liakhovetski <kernel@pengutronix.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/v4l2-mediabus.h>
#include <linux/videodev2.h>
#include <media/soc_camera.h>
#include <media/tw9910.h>
#include <media/v4l2-chip-ident.h>
#include <media/v4l2-subdev.h>
#define GET_ID(val) ((val & 0xF8) >> 3)
#define GET_REV(val) (val & 0x07)
/*
* register offset
*/
#define ID 0x00 /* Product ID Code Register */
#define STATUS1 0x01 /* Chip Status Register I */
#define INFORM 0x02 /* Input Format */
#define OPFORM 0x03 /* Output Format Control Register */
#define DLYCTR 0x04 /* Hysteresis and HSYNC Delay Control */
#define OUTCTR1 0x05 /* Output Control I */
#define ACNTL1 0x06 /* Analog Control Register 1 */
#define CROP_HI 0x07 /* Cropping Register, High */
#define VDELAY_LO 0x08 /* Vertical Delay Register, Low */
#define VACTIVE_LO 0x09 /* Vertical Active Register, Low */
#define HDELAY_LO 0x0A /* Horizontal Delay Register, Low */
#define HACTIVE_LO 0x0B /* Horizontal Active Register, Low */
#define CNTRL1 0x0C /* Control Register I */
#define VSCALE_LO 0x0D /* Vertical Scaling Register, Low */
#define SCALE_HI 0x0E /* Scaling Register, High */
#define HSCALE_LO 0x0F /* Horizontal Scaling Register, Low */
#define BRIGHT 0x10 /* BRIGHTNESS Control Register */
#define CONTRAST 0x11 /* CONTRAST Control Register */
#define SHARPNESS 0x12 /* SHARPNESS Control Register I */
#define SAT_U 0x13 /* Chroma (U) Gain Register */
#define SAT_V 0x14 /* Chroma (V) Gain Register */
#define HUE 0x15 /* Hue Control Register */
#define CORING1 0x17
#define CORING2 0x18 /* Coring and IF compensation */
#define VBICNTL 0x19 /* VBI Control Register */
#define ACNTL2 0x1A /* Analog Control 2 */
#define OUTCTR2 0x1B /* Output Control 2 */
#define SDT 0x1C /* Standard Selection */
#define SDTR 0x1D /* Standard Recognition */
#define TEST 0x1F /* Test Control Register */
#define CLMPG 0x20 /* Clamping Gain */
#define IAGC 0x21 /* Individual AGC Gain */
#define AGCGAIN 0x22 /* AGC Gain */
#define PEAKWT 0x23 /* White Peak Threshold */
#define CLMPL 0x24 /* Clamp level */
#define SYNCT 0x25 /* Sync Amplitude */
#define MISSCNT 0x26 /* Sync Miss Count Register */
#define PCLAMP 0x27 /* Clamp Position Register */
#define VCNTL1 0x28 /* Vertical Control I */
#define VCNTL2 0x29 /* Vertical Control II */
#define CKILL 0x2A /* Color Killer Level Control */
#define COMB 0x2B /* Comb Filter Control */
#define LDLY 0x2C /* Luma Delay and H Filter Control */
#define MISC1 0x2D /* Miscellaneous Control I */
#define LOOP 0x2E /* LOOP Control Register */
#define MISC2 0x2F /* Miscellaneous Control II */
#define MVSN 0x30 /* Macrovision Detection */
#define STATUS2 0x31 /* Chip STATUS II */
#define HFREF 0x32 /* H monitor */
#define CLMD 0x33 /* CLAMP MODE */
#define IDCNTL 0x34 /* ID Detection Control */
#define CLCNTL1 0x35 /* Clamp Control I */
#define ANAPLLCTL 0x4C
#define VBIMIN 0x4D
#define HSLOWCTL 0x4E
#define WSS3 0x4F
#define FILLDATA 0x50
#define SDID 0x51
#define DID 0x52
#define WSS1 0x53
#define WSS2 0x54
#define VVBI 0x55
#define LCTL6 0x56
#define LCTL7 0x57
#define LCTL8 0x58
#define LCTL9 0x59
#define LCTL10 0x5A
#define LCTL11 0x5B
#define LCTL12 0x5C
#define LCTL13 0x5D
#define LCTL14 0x5E
#define LCTL15 0x5F
#define LCTL16 0x60
#define LCTL17 0x61
#define LCTL18 0x62
#define LCTL19 0x63
#define LCTL20 0x64
#define LCTL21 0x65
#define LCTL22 0x66
#define LCTL23 0x67
#define LCTL24 0x68
#define LCTL25 0x69
#define LCTL26 0x6A
#define HSBEGIN 0x6B
#define HSEND 0x6C
#define OVSDLY 0x6D
#define OVSEND 0x6E
#define VBIDELAY 0x6F
/*
* register detail
*/
/* INFORM */
#define FC27_ON 0x40 /* 1 : Input crystal clock frequency is 27MHz */
#define FC27_FF 0x00 /* 0 : Square pixel mode. */
/* Must use 24.54MHz for 60Hz field rate */
/* source or 29.5MHz for 50Hz field rate */
#define IFSEL_S 0x10 /* 01 : S-video decoding */
#define IFSEL_C 0x00 /* 00 : Composite video decoding */
/* Y input video selection */
#define YSEL_M0 0x00 /* 00 : Mux0 selected */
#define YSEL_M1 0x04 /* 01 : Mux1 selected */
#define YSEL_M2 0x08 /* 10 : Mux2 selected */
#define YSEL_M3 0x10 /* 11 : Mux3 selected */
/* OPFORM */
#define MODE 0x80 /* 0 : CCIR601 compatible YCrCb 4:2:2 format */
/* 1 : ITU-R-656 compatible data sequence format */
#define LEN 0x40 /* 0 : 8-bit YCrCb 4:2:2 output format */
/* 1 : 16-bit YCrCb 4:2:2 output format.*/
#define LLCMODE 0x20 /* 1 : LLC output mode. */
/* 0 : free-run output mode */
#define AINC 0x10 /* Serial interface auto-indexing control */
/* 0 : auto-increment */
/* 1 : non-auto */
#define VSCTL 0x08 /* 1 : Vertical out ctrl by DVALID */
/* 0 : Vertical out ctrl by HACTIVE and DVALID */
#define OEN_TRI_SEL_MASK 0x07
#define OEN_TRI_SEL_ALL_ON 0x00 /* Enable output for Rev0/Rev1 */
#define OEN_TRI_SEL_ALL_OFF_r0 0x06 /* All tri-stated for Rev0 */
#define OEN_TRI_SEL_ALL_OFF_r1 0x07 /* All tri-stated for Rev1 */
/* OUTCTR1 */
#define VSP_LO 0x00 /* 0 : VS pin output polarity is active low */
#define VSP_HI 0x80 /* 1 : VS pin output polarity is active high. */
/* VS pin output control */
#define VSSL_VSYNC 0x00 /* 0 : VSYNC */
#define VSSL_VACT 0x10 /* 1 : VACT */
#define VSSL_FIELD 0x20 /* 2 : FIELD */
#define VSSL_VVALID 0x30 /* 3 : VVALID */
#define VSSL_ZERO 0x70 /* 7 : 0 */
#define HSP_LOW 0x00 /* 0 : HS pin output polarity is active low */
#define HSP_HI 0x08 /* 1 : HS pin output polarity is active high.*/
/* HS pin output control */
#define HSSL_HACT 0x00 /* 0 : HACT */
#define HSSL_HSYNC 0x01 /* 1 : HSYNC */
#define HSSL_DVALID 0x02 /* 2 : DVALID */
#define HSSL_HLOCK 0x03 /* 3 : HLOCK */
#define HSSL_ASYNCW 0x04 /* 4 : ASYNCW */
#define HSSL_ZERO 0x07 /* 7 : 0 */
/* ACNTL1 */
#define SRESET 0x80 /* resets the device to its default state
* but all register content remain unchanged.
* This bit is self-resetting.
*/
#define ACNTL1_PDN_MASK 0x0e
#define CLK_PDN 0x08 /* system clock power down */
#define Y_PDN 0x04 /* Luma ADC power down */
#define C_PDN 0x02 /* Chroma ADC power down */
/* ACNTL2 */
#define ACNTL2_PDN_MASK 0x40
#define PLL_PDN 0x40 /* PLL power down */
/* VBICNTL */
/* RTSEL : control the real time signal output from the MPOUT pin */
#define RTSEL_MASK 0x07
#define RTSEL_VLOSS 0x00 /* 0000 = Video loss */
#define RTSEL_HLOCK 0x01 /* 0001 = H-lock */
#define RTSEL_SLOCK 0x02 /* 0010 = S-lock */
#define RTSEL_VLOCK 0x03 /* 0011 = V-lock */
#define RTSEL_MONO 0x04 /* 0100 = MONO */
#define RTSEL_DET50 0x05 /* 0101 = DET50 */
#define RTSEL_FIELD 0x06 /* 0110 = FIELD */
#define RTSEL_RTCO 0x07 /* 0111 = RTCO ( Real Time Control ) */
/* HSYNC start and end are constant for now */
#define HSYNC_START 0x0260
#define HSYNC_END 0x0300
/*
* structure
*/
struct regval_list {
unsigned char reg_num;
unsigned char value;
};
struct tw9910_scale_ctrl {
char *name;
unsigned short width;
unsigned short height;
u16 hscale;
u16 vscale;
};
struct tw9910_priv {
struct v4l2_subdev subdev;
struct tw9910_video_info *info;
const struct tw9910_scale_ctrl *scale;
v4l2_std_id norm;
u32 revision;
};
static const struct tw9910_scale_ctrl tw9910_ntsc_scales[] = {
{
.name = "NTSC SQ",
.width = 640,
.height = 480,
.hscale = 0x0100,
.vscale = 0x0100,
},
{
.name = "NTSC CCIR601",
.width = 720,
.height = 480,
.hscale = 0x0100,
.vscale = 0x0100,
},
{
.name = "NTSC SQ (CIF)",
.width = 320,
.height = 240,
.hscale = 0x0200,
.vscale = 0x0200,
},
{
.name = "NTSC CCIR601 (CIF)",
.width = 360,
.height = 240,
.hscale = 0x0200,
.vscale = 0x0200,
},
{
.name = "NTSC SQ (QCIF)",
.width = 160,
.height = 120,
.hscale = 0x0400,
.vscale = 0x0400,
},
{
.name = "NTSC CCIR601 (QCIF)",
.width = 180,
.height = 120,
.hscale = 0x0400,
.vscale = 0x0400,
},
};
static const struct tw9910_scale_ctrl tw9910_pal_scales[] = {
{
.name = "PAL SQ",
.width = 768,
.height = 576,
.hscale = 0x0100,
.vscale = 0x0100,
},
{
.name = "PAL CCIR601",
.width = 720,
.height = 576,
.hscale = 0x0100,
.vscale = 0x0100,
},
{
.name = "PAL SQ (CIF)",
.width = 384,
.height = 288,
.hscale = 0x0200,
.vscale = 0x0200,
},
{
.name = "PAL CCIR601 (CIF)",
.width = 360,
.height = 288,
.hscale = 0x0200,
.vscale = 0x0200,
},
{
.name = "PAL SQ (QCIF)",
.width = 192,
.height = 144,
.hscale = 0x0400,
.vscale = 0x0400,
},
{
.name = "PAL CCIR601 (QCIF)",
.width = 180,
.height = 144,
.hscale = 0x0400,
.vscale = 0x0400,
},
};
/*
* general function
*/
static struct tw9910_priv *to_tw9910(const struct i2c_client *client)
{
return container_of(i2c_get_clientdata(client), struct tw9910_priv,
subdev);
}
static int tw9910_mask_set(struct i2c_client *client, u8 command,
u8 mask, u8 set)
{
s32 val = i2c_smbus_read_byte_data(client, command);
if (val < 0)
return val;
val &= ~mask;
val |= set & mask;
return i2c_smbus_write_byte_data(client, command, val);
}
static int tw9910_set_scale(struct i2c_client *client,
const struct tw9910_scale_ctrl *scale)
{
int ret;
ret = i2c_smbus_write_byte_data(client, SCALE_HI,
(scale->vscale & 0x0F00) >> 4 |
(scale->hscale & 0x0F00) >> 8);
if (ret < 0)
return ret;
ret = i2c_smbus_write_byte_data(client, HSCALE_LO,
scale->hscale & 0x00FF);
if (ret < 0)
return ret;
ret = i2c_smbus_write_byte_data(client, VSCALE_LO,
scale->vscale & 0x00FF);
return ret;
}
static int tw9910_set_hsync(struct i2c_client *client)
{
struct tw9910_priv *priv = to_tw9910(client);
int ret;
/* bit 10 - 3 */
ret = i2c_smbus_write_byte_data(client, HSBEGIN,
(HSYNC_START & 0x07F8) >> 3);
if (ret < 0)
return ret;
/* bit 10 - 3 */
ret = i2c_smbus_write_byte_data(client, HSEND,
(HSYNC_END & 0x07F8) >> 3);
if (ret < 0)
return ret;
/* So far only revisions 0 and 1 have been seen */
/* bit 2 - 0 */
if (1 == priv->revision)
ret = tw9910_mask_set(client, HSLOWCTL, 0x77,
(HSYNC_START & 0x0007) << 4 |
(HSYNC_END & 0x0007));
return ret;
}
static void tw9910_reset(struct i2c_client *client)
{
tw9910_mask_set(client, ACNTL1, SRESET, SRESET);
msleep(1);
}
static int tw9910_power(struct i2c_client *client, int enable)
{
int ret;
u8 acntl1;
u8 acntl2;
if (enable) {
acntl1 = 0;
acntl2 = 0;
} else {
acntl1 = CLK_PDN | Y_PDN | C_PDN;
acntl2 = PLL_PDN;
}
ret = tw9910_mask_set(client, ACNTL1, ACNTL1_PDN_MASK, acntl1);
if (ret < 0)
return ret;
return tw9910_mask_set(client, ACNTL2, ACNTL2_PDN_MASK, acntl2);
}
static const struct tw9910_scale_ctrl *tw9910_select_norm(v4l2_std_id norm,
u32 width, u32 height)
{
const struct tw9910_scale_ctrl *scale;
const struct tw9910_scale_ctrl *ret = NULL;
__u32 diff = 0xffffffff, tmp;
int size, i;
if (norm & V4L2_STD_NTSC) {
scale = tw9910_ntsc_scales;
size = ARRAY_SIZE(tw9910_ntsc_scales);
} else if (norm & V4L2_STD_PAL) {
scale = tw9910_pal_scales;
size = ARRAY_SIZE(tw9910_pal_scales);
} else {
return NULL;
}
for (i = 0; i < size; i++) {
tmp = abs(width - scale[i].width) +
abs(height - scale[i].height);
if (tmp < diff) {
diff = tmp;
ret = scale + i;
}
}
return ret;
}
/*
* subdevice operations
*/
static int tw9910_s_stream(struct v4l2_subdev *sd, int enable)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct tw9910_priv *priv = to_tw9910(client);
u8 val;
int ret;
if (!enable) {
switch (priv->revision) {
case 0:
val = OEN_TRI_SEL_ALL_OFF_r0;
break;
case 1:
val = OEN_TRI_SEL_ALL_OFF_r1;
break;
default:
dev_err(&client->dev, "un-supported revision\n");
return -EINVAL;
}
} else {
val = OEN_TRI_SEL_ALL_ON;
if (!priv->scale) {
dev_err(&client->dev, "norm select error\n");
return -EPERM;
}
dev_dbg(&client->dev, "%s %dx%d\n",
priv->scale->name,
priv->scale->width,
priv->scale->height);
}
ret = tw9910_mask_set(client, OPFORM, OEN_TRI_SEL_MASK, val);
if (ret < 0)
return ret;
return tw9910_power(client, enable);
}
static int tw9910_g_std(struct v4l2_subdev *sd, v4l2_std_id *norm)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct tw9910_priv *priv = to_tw9910(client);
*norm = priv->norm;
return 0;
}
static int tw9910_s_std(struct v4l2_subdev *sd, v4l2_std_id norm)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct tw9910_priv *priv = to_tw9910(client);
if (!(norm & (V4L2_STD_NTSC | V4L2_STD_PAL)))
return -EINVAL;
priv->norm = norm;
return 0;
}
static int tw9910_g_chip_ident(struct v4l2_subdev *sd,
struct v4l2_dbg_chip_ident *id)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct tw9910_priv *priv = to_tw9910(client);
id->ident = V4L2_IDENT_TW9910;
id->revision = priv->revision;
return 0;
}
#ifdef CONFIG_VIDEO_ADV_DEBUG
static int tw9910_g_register(struct v4l2_subdev *sd,
struct v4l2_dbg_register *reg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
int ret;
if (reg->reg > 0xff)
return -EINVAL;
ret = i2c_smbus_read_byte_data(client, reg->reg);
if (ret < 0)
return ret;
/*
* ret = int
* reg->val = __u64
*/
reg->val = (__u64)ret;
return 0;
}
static int tw9910_s_register(struct v4l2_subdev *sd,
struct v4l2_dbg_register *reg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
if (reg->reg > 0xff ||
reg->val > 0xff)
return -EINVAL;
return i2c_smbus_write_byte_data(client, reg->reg, reg->val);
}
#endif
static int tw9910_set_frame(struct v4l2_subdev *sd, u32 *width, u32 *height)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct tw9910_priv *priv = to_tw9910(client);
int ret = -EINVAL;
u8 val;
/*
* select suitable norm
*/
priv->scale = tw9910_select_norm(priv->norm, *width, *height);
if (!priv->scale)
goto tw9910_set_fmt_error;
/*
* reset hardware
*/
tw9910_reset(client);
/*
* set bus width
*/
val = 0x00;
if (SOCAM_DATAWIDTH_16 == priv->info->buswidth)
val = LEN;
ret = tw9910_mask_set(client, OPFORM, LEN, val);
if (ret < 0)
goto tw9910_set_fmt_error;
/*
* select MPOUT behavior
*/
switch (priv->info->mpout) {
case TW9910_MPO_VLOSS:
val = RTSEL_VLOSS; break;
case TW9910_MPO_HLOCK:
val = RTSEL_HLOCK; break;
case TW9910_MPO_SLOCK:
val = RTSEL_SLOCK; break;
case TW9910_MPO_VLOCK:
val = RTSEL_VLOCK; break;
case TW9910_MPO_MONO:
val = RTSEL_MONO; break;
case TW9910_MPO_DET50:
val = RTSEL_DET50; break;
case TW9910_MPO_FIELD:
val = RTSEL_FIELD; break;
case TW9910_MPO_RTCO:
val = RTSEL_RTCO; break;
default:
val = 0;
}
ret = tw9910_mask_set(client, VBICNTL, RTSEL_MASK, val);
if (ret < 0)
goto tw9910_set_fmt_error;
/*
* set scale
*/
ret = tw9910_set_scale(client, priv->scale);
if (ret < 0)
goto tw9910_set_fmt_error;
/*
* set hsync
*/
ret = tw9910_set_hsync(client);
if (ret < 0)
goto tw9910_set_fmt_error;
*width = priv->scale->width;
*height = priv->scale->height;
return ret;
tw9910_set_fmt_error:
tw9910_reset(client);
priv->scale = NULL;
return ret;
}
static int tw9910_g_crop(struct v4l2_subdev *sd, struct v4l2_crop *a)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct tw9910_priv *priv = to_tw9910(client);
a->c.left = 0;
a->c.top = 0;
if (priv->norm & V4L2_STD_NTSC) {
a->c.width = 640;
a->c.height = 480;
} else {
a->c.width = 768;
a->c.height = 576;
}
a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
return 0;
}
static int tw9910_cropcap(struct v4l2_subdev *sd, struct v4l2_cropcap *a)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct tw9910_priv *priv = to_tw9910(client);
a->bounds.left = 0;
a->bounds.top = 0;
if (priv->norm & V4L2_STD_NTSC) {
a->bounds.width = 640;
a->bounds.height = 480;
} else {
a->bounds.width = 768;
a->bounds.height = 576;
}
a->defrect = a->bounds;
a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
a->pixelaspect.numerator = 1;
a->pixelaspect.denominator = 1;
return 0;
}
static int tw9910_g_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *mf)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct tw9910_priv *priv = to_tw9910(client);
if (!priv->scale) {
int ret;
u32 width = 640, height = 480;
ret = tw9910_set_frame(sd, &width, &height);
if (ret < 0)
return ret;
}
mf->width = priv->scale->width;
mf->height = priv->scale->height;
mf->code = V4L2_MBUS_FMT_UYVY8_2X8;
mf->colorspace = V4L2_COLORSPACE_JPEG;
mf->field = V4L2_FIELD_INTERLACED_BT;
return 0;
}
static int tw9910_s_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *mf)
{
u32 width = mf->width, height = mf->height;
int ret;
WARN_ON(mf->field != V4L2_FIELD_ANY &&
mf->field != V4L2_FIELD_INTERLACED_BT);
/*
* check color format
*/
if (mf->code != V4L2_MBUS_FMT_UYVY8_2X8)
return -EINVAL;
mf->colorspace = V4L2_COLORSPACE_JPEG;
ret = tw9910_set_frame(sd, &width, &height);
if (!ret) {
mf->width = width;
mf->height = height;
}
return ret;
}
static int tw9910_try_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *mf)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct tw9910_priv *priv = to_tw9910(client);
const struct tw9910_scale_ctrl *scale;
if (V4L2_FIELD_ANY == mf->field) {
mf->field = V4L2_FIELD_INTERLACED_BT;
} else if (V4L2_FIELD_INTERLACED_BT != mf->field) {
dev_err(&client->dev, "Field type %d invalid.\n", mf->field);
return -EINVAL;
}
mf->code = V4L2_MBUS_FMT_UYVY8_2X8;
mf->colorspace = V4L2_COLORSPACE_JPEG;
/*
* select suitable norm
*/
scale = tw9910_select_norm(priv->norm, mf->width, mf->height);
if (!scale)
return -EINVAL;
mf->width = scale->width;
mf->height = scale->height;
return 0;
}
static int tw9910_video_probe(struct i2c_client *client)
{
struct tw9910_priv *priv = to_tw9910(client);
s32 id;
/*
* tw9910 only use 8 or 16 bit bus width
*/
if (SOCAM_DATAWIDTH_16 != priv->info->buswidth &&
SOCAM_DATAWIDTH_8 != priv->info->buswidth) {
dev_err(&client->dev, "bus width error\n");
return -ENODEV;
}
/*
* check and show Product ID
* So far only revisions 0 and 1 have been seen
*/
id = i2c_smbus_read_byte_data(client, ID);
priv->revision = GET_REV(id);
id = GET_ID(id);
if (0x0B != id ||
0x01 < priv->revision) {
dev_err(&client->dev,
"Product ID error %x:%x\n",
id, priv->revision);
return -ENODEV;
}
dev_info(&client->dev,
"tw9910 Product ID %0x:%0x\n", id, priv->revision);
priv->norm = V4L2_STD_NTSC;
return 0;
}
static struct v4l2_subdev_core_ops tw9910_subdev_core_ops = {
.g_chip_ident = tw9910_g_chip_ident,
.s_std = tw9910_s_std,
.g_std = tw9910_g_std,
#ifdef CONFIG_VIDEO_ADV_DEBUG
.g_register = tw9910_g_register,
.s_register = tw9910_s_register,
#endif
};
static int tw9910_enum_fmt(struct v4l2_subdev *sd, unsigned int index,
enum v4l2_mbus_pixelcode *code)
{
if (index)
return -EINVAL;
*code = V4L2_MBUS_FMT_UYVY8_2X8;
return 0;
}
static int tw9910_g_mbus_config(struct v4l2_subdev *sd,
struct v4l2_mbus_config *cfg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct soc_camera_link *icl = soc_camera_i2c_to_link(client);
cfg->flags = V4L2_MBUS_PCLK_SAMPLE_RISING | V4L2_MBUS_MASTER |
V4L2_MBUS_VSYNC_ACTIVE_HIGH | V4L2_MBUS_VSYNC_ACTIVE_LOW |
V4L2_MBUS_HSYNC_ACTIVE_HIGH | V4L2_MBUS_HSYNC_ACTIVE_LOW |
V4L2_MBUS_DATA_ACTIVE_HIGH;
cfg->type = V4L2_MBUS_PARALLEL;
cfg->flags = soc_camera_apply_board_flags(icl, cfg);
return 0;
}
static int tw9910_s_mbus_config(struct v4l2_subdev *sd,
const struct v4l2_mbus_config *cfg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct soc_camera_link *icl = soc_camera_i2c_to_link(client);
u8 val = VSSL_VVALID | HSSL_DVALID;
unsigned long flags = soc_camera_apply_board_flags(icl, cfg);
/*
* set OUTCTR1
*
* We use VVALID and DVALID signals to control VSYNC and HSYNC
* outputs, in this mode their polarity is inverted.
*/
if (flags & V4L2_MBUS_HSYNC_ACTIVE_LOW)
val |= HSP_HI;
if (flags & V4L2_MBUS_VSYNC_ACTIVE_LOW)
val |= VSP_HI;
return i2c_smbus_write_byte_data(client, OUTCTR1, val);
}
static struct v4l2_subdev_video_ops tw9910_subdev_video_ops = {
.s_stream = tw9910_s_stream,
.g_mbus_fmt = tw9910_g_fmt,
.s_mbus_fmt = tw9910_s_fmt,
.try_mbus_fmt = tw9910_try_fmt,
.cropcap = tw9910_cropcap,
.g_crop = tw9910_g_crop,
.enum_mbus_fmt = tw9910_enum_fmt,
.g_mbus_config = tw9910_g_mbus_config,
.s_mbus_config = tw9910_s_mbus_config,
};
static struct v4l2_subdev_ops tw9910_subdev_ops = {
.core = &tw9910_subdev_core_ops,
.video = &tw9910_subdev_video_ops,
};
/*
* i2c_driver function
*/
static int tw9910_probe(struct i2c_client *client,
const struct i2c_device_id *did)
{
struct tw9910_priv *priv;
struct tw9910_video_info *info;
struct i2c_adapter *adapter =
to_i2c_adapter(client->dev.parent);
struct soc_camera_link *icl = soc_camera_i2c_to_link(client);
int ret;
if (!icl || !icl->priv) {
dev_err(&client->dev, "TW9910: missing platform data!\n");
return -EINVAL;
}
info = icl->priv;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA)) {
dev_err(&client->dev,
"I2C-Adapter doesn't support "
"I2C_FUNC_SMBUS_BYTE_DATA\n");
return -EIO;
}
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->info = info;
v4l2_i2c_subdev_init(&priv->subdev, client, &tw9910_subdev_ops);
ret = tw9910_video_probe(client);
if (ret)
kfree(priv);
return ret;
}
static int tw9910_remove(struct i2c_client *client)
{
struct tw9910_priv *priv = to_tw9910(client);
kfree(priv);
return 0;
}
static const struct i2c_device_id tw9910_id[] = {
{ "tw9910", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, tw9910_id);
static struct i2c_driver tw9910_i2c_driver = {
.driver = {
.name = "tw9910",
},
.probe = tw9910_probe,
.remove = tw9910_remove,
.id_table = tw9910_id,
};
module_i2c_driver(tw9910_i2c_driver);
MODULE_DESCRIPTION("SoC Camera driver for tw9910");
MODULE_AUTHOR("Kuninori Morimoto");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
gamerman123x/kernel_oneplus_msm8974 | drivers/media/video/ov2640.c | 4863 | 31605 | /*
* ov2640 Camera Driver
*
* Copyright (C) 2010 Alberto Panizzo <maramaopercheseimorto@gmail.com>
*
* Based on ov772x, ov9640 drivers and previous non merged implementations.
*
* Copyright 2005-2009 Freescale Semiconductor, Inc. All Rights Reserved.
* Copyright (C) 2006, OmniVision
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/v4l2-mediabus.h>
#include <linux/videodev2.h>
#include <media/soc_camera.h>
#include <media/v4l2-chip-ident.h>
#include <media/v4l2-subdev.h>
#include <media/v4l2-ctrls.h>
#define VAL_SET(x, mask, rshift, lshift) \
((((x) >> rshift) & mask) << lshift)
/*
* DSP registers
* register offset for BANK_SEL == BANK_SEL_DSP
*/
#define R_BYPASS 0x05 /* Bypass DSP */
#define R_BYPASS_DSP_BYPAS 0x01 /* Bypass DSP, sensor out directly */
#define R_BYPASS_USE_DSP 0x00 /* Use the internal DSP */
#define QS 0x44 /* Quantization Scale Factor */
#define CTRLI 0x50
#define CTRLI_LP_DP 0x80
#define CTRLI_ROUND 0x40
#define CTRLI_V_DIV_SET(x) VAL_SET(x, 0x3, 0, 3)
#define CTRLI_H_DIV_SET(x) VAL_SET(x, 0x3, 0, 0)
#define HSIZE 0x51 /* H_SIZE[7:0] (real/4) */
#define HSIZE_SET(x) VAL_SET(x, 0xFF, 2, 0)
#define VSIZE 0x52 /* V_SIZE[7:0] (real/4) */
#define VSIZE_SET(x) VAL_SET(x, 0xFF, 2, 0)
#define XOFFL 0x53 /* OFFSET_X[7:0] */
#define XOFFL_SET(x) VAL_SET(x, 0xFF, 0, 0)
#define YOFFL 0x54 /* OFFSET_Y[7:0] */
#define YOFFL_SET(x) VAL_SET(x, 0xFF, 0, 0)
#define VHYX 0x55 /* Offset and size completion */
#define VHYX_VSIZE_SET(x) VAL_SET(x, 0x1, (8+2), 7)
#define VHYX_HSIZE_SET(x) VAL_SET(x, 0x1, (8+2), 3)
#define VHYX_YOFF_SET(x) VAL_SET(x, 0x3, 8, 4)
#define VHYX_XOFF_SET(x) VAL_SET(x, 0x3, 8, 0)
#define DPRP 0x56
#define TEST 0x57 /* Horizontal size completion */
#define TEST_HSIZE_SET(x) VAL_SET(x, 0x1, (9+2), 7)
#define ZMOW 0x5A /* Zoom: Out Width OUTW[7:0] (real/4) */
#define ZMOW_OUTW_SET(x) VAL_SET(x, 0xFF, 2, 0)
#define ZMOH 0x5B /* Zoom: Out Height OUTH[7:0] (real/4) */
#define ZMOH_OUTH_SET(x) VAL_SET(x, 0xFF, 2, 0)
#define ZMHH 0x5C /* Zoom: Speed and H&W completion */
#define ZMHH_ZSPEED_SET(x) VAL_SET(x, 0x0F, 0, 4)
#define ZMHH_OUTH_SET(x) VAL_SET(x, 0x1, (8+2), 2)
#define ZMHH_OUTW_SET(x) VAL_SET(x, 0x3, (8+2), 0)
#define BPADDR 0x7C /* SDE Indirect Register Access: Address */
#define BPDATA 0x7D /* SDE Indirect Register Access: Data */
#define CTRL2 0x86 /* DSP Module enable 2 */
#define CTRL2_DCW_EN 0x20
#define CTRL2_SDE_EN 0x10
#define CTRL2_UV_ADJ_EN 0x08
#define CTRL2_UV_AVG_EN 0x04
#define CTRL2_CMX_EN 0x01
#define CTRL3 0x87 /* DSP Module enable 3 */
#define CTRL3_BPC_EN 0x80
#define CTRL3_WPC_EN 0x40
#define SIZEL 0x8C /* Image Size Completion */
#define SIZEL_HSIZE8_11_SET(x) VAL_SET(x, 0x1, 11, 6)
#define SIZEL_HSIZE8_SET(x) VAL_SET(x, 0x7, 0, 3)
#define SIZEL_VSIZE8_SET(x) VAL_SET(x, 0x7, 0, 0)
#define HSIZE8 0xC0 /* Image Horizontal Size HSIZE[10:3] */
#define HSIZE8_SET(x) VAL_SET(x, 0xFF, 3, 0)
#define VSIZE8 0xC1 /* Image Vertical Size VSIZE[10:3] */
#define VSIZE8_SET(x) VAL_SET(x, 0xFF, 3, 0)
#define CTRL0 0xC2 /* DSP Module enable 0 */
#define CTRL0_AEC_EN 0x80
#define CTRL0_AEC_SEL 0x40
#define CTRL0_STAT_SEL 0x20
#define CTRL0_VFIRST 0x10
#define CTRL0_YUV422 0x08
#define CTRL0_YUV_EN 0x04
#define CTRL0_RGB_EN 0x02
#define CTRL0_RAW_EN 0x01
#define CTRL1 0xC3 /* DSP Module enable 1 */
#define CTRL1_CIP 0x80
#define CTRL1_DMY 0x40
#define CTRL1_RAW_GMA 0x20
#define CTRL1_DG 0x10
#define CTRL1_AWB 0x08
#define CTRL1_AWB_GAIN 0x04
#define CTRL1_LENC 0x02
#define CTRL1_PRE 0x01
#define R_DVP_SP 0xD3 /* DVP output speed control */
#define R_DVP_SP_AUTO_MODE 0x80
#define R_DVP_SP_DVP_MASK 0x3F /* DVP PCLK = sysclk (48)/[6:0] (YUV0);
* = sysclk (48)/(2*[6:0]) (RAW);*/
#define IMAGE_MODE 0xDA /* Image Output Format Select */
#define IMAGE_MODE_Y8_DVP_EN 0x40
#define IMAGE_MODE_JPEG_EN 0x10
#define IMAGE_MODE_YUV422 0x00
#define IMAGE_MODE_RAW10 0x04 /* (DVP) */
#define IMAGE_MODE_RGB565 0x08
#define IMAGE_MODE_HREF_VSYNC 0x02 /* HREF timing select in DVP JPEG output
* mode (0 for HREF is same as sensor) */
#define IMAGE_MODE_LBYTE_FIRST 0x01 /* Byte swap enable for DVP
* 1: Low byte first UYVY (C2[4] =0)
* VYUY (C2[4] =1)
* 0: High byte first YUYV (C2[4]=0)
* YVYU (C2[4] = 1) */
#define RESET 0xE0 /* Reset */
#define RESET_MICROC 0x40
#define RESET_SCCB 0x20
#define RESET_JPEG 0x10
#define RESET_DVP 0x04
#define RESET_IPU 0x02
#define RESET_CIF 0x01
#define REGED 0xED /* Register ED */
#define REGED_CLK_OUT_DIS 0x10
#define MS_SP 0xF0 /* SCCB Master Speed */
#define SS_ID 0xF7 /* SCCB Slave ID */
#define SS_CTRL 0xF8 /* SCCB Slave Control */
#define SS_CTRL_ADD_AUTO_INC 0x20
#define SS_CTRL_EN 0x08
#define SS_CTRL_DELAY_CLK 0x04
#define SS_CTRL_ACC_EN 0x02
#define SS_CTRL_SEN_PASS_THR 0x01
#define MC_BIST 0xF9 /* Microcontroller misc register */
#define MC_BIST_RESET 0x80 /* Microcontroller Reset */
#define MC_BIST_BOOT_ROM_SEL 0x40
#define MC_BIST_12KB_SEL 0x20
#define MC_BIST_12KB_MASK 0x30
#define MC_BIST_512KB_SEL 0x08
#define MC_BIST_512KB_MASK 0x0C
#define MC_BIST_BUSY_BIT_R 0x02
#define MC_BIST_MC_RES_ONE_SH_W 0x02
#define MC_BIST_LAUNCH 0x01
#define BANK_SEL 0xFF /* Register Bank Select */
#define BANK_SEL_DSP 0x00
#define BANK_SEL_SENS 0x01
/*
* Sensor registers
* register offset for BANK_SEL == BANK_SEL_SENS
*/
#define GAIN 0x00 /* AGC - Gain control gain setting */
#define COM1 0x03 /* Common control 1 */
#define COM1_1_DUMMY_FR 0x40
#define COM1_3_DUMMY_FR 0x80
#define COM1_7_DUMMY_FR 0xC0
#define COM1_VWIN_LSB_UXGA 0x0F
#define COM1_VWIN_LSB_SVGA 0x0A
#define COM1_VWIN_LSB_CIF 0x06
#define REG04 0x04 /* Register 04 */
#define REG04_DEF 0x20 /* Always set */
#define REG04_HFLIP_IMG 0x80 /* Horizontal mirror image ON/OFF */
#define REG04_VFLIP_IMG 0x40 /* Vertical flip image ON/OFF */
#define REG04_VREF_EN 0x10
#define REG04_HREF_EN 0x08
#define REG04_AEC_SET(x) VAL_SET(x, 0x3, 0, 0)
#define REG08 0x08 /* Frame Exposure One-pin Control Pre-charge Row Num */
#define COM2 0x09 /* Common control 2 */
#define COM2_SOFT_SLEEP_MODE 0x10 /* Soft sleep mode */
/* Output drive capability */
#define COM2_OCAP_Nx_SET(N) (((N) - 1) & 0x03) /* N = [1x .. 4x] */
#define PID 0x0A /* Product ID Number MSB */
#define VER 0x0B /* Product ID Number LSB */
#define COM3 0x0C /* Common control 3 */
#define COM3_BAND_50H 0x04 /* 0 For Banding at 60H */
#define COM3_BAND_AUTO 0x02 /* Auto Banding */
#define COM3_SING_FR_SNAPSH 0x01 /* 0 For enable live video output after the
* snapshot sequence*/
#define AEC 0x10 /* AEC[9:2] Exposure Value */
#define CLKRC 0x11 /* Internal clock */
#define CLKRC_EN 0x80
#define CLKRC_DIV_SET(x) (((x) - 1) & 0x1F) /* CLK = XVCLK/(x) */
#define COM7 0x12 /* Common control 7 */
#define COM7_SRST 0x80 /* Initiates system reset. All registers are
* set to factory default values after which
* the chip resumes normal operation */
#define COM7_RES_UXGA 0x00 /* Resolution selectors for UXGA */
#define COM7_RES_SVGA 0x40 /* SVGA */
#define COM7_RES_CIF 0x20 /* CIF */
#define COM7_ZOOM_EN 0x04 /* Enable Zoom mode */
#define COM7_COLOR_BAR_TEST 0x02 /* Enable Color Bar Test Pattern */
#define COM8 0x13 /* Common control 8 */
#define COM8_DEF 0xC0 /* Banding filter ON/OFF */
#define COM8_BNDF_EN 0x20 /* Banding filter ON/OFF */
#define COM8_AGC_EN 0x04 /* AGC Auto/Manual control selection */
#define COM8_AEC_EN 0x01 /* Auto/Manual Exposure control */
#define COM9 0x14 /* Common control 9
* Automatic gain ceiling - maximum AGC value [7:5]*/
#define COM9_AGC_GAIN_2x 0x00 /* 000 : 2x */
#define COM9_AGC_GAIN_4x 0x20 /* 001 : 4x */
#define COM9_AGC_GAIN_8x 0x40 /* 010 : 8x */
#define COM9_AGC_GAIN_16x 0x60 /* 011 : 16x */
#define COM9_AGC_GAIN_32x 0x80 /* 100 : 32x */
#define COM9_AGC_GAIN_64x 0xA0 /* 101 : 64x */
#define COM9_AGC_GAIN_128x 0xC0 /* 110 : 128x */
#define COM10 0x15 /* Common control 10 */
#define COM10_PCLK_HREF 0x20 /* PCLK output qualified by HREF */
#define COM10_PCLK_RISE 0x10 /* Data is updated at the rising edge of
* PCLK (user can latch data at the next
* falling edge of PCLK).
* 0 otherwise. */
#define COM10_HREF_INV 0x08 /* Invert HREF polarity:
* HREF negative for valid data*/
#define COM10_VSINC_INV 0x02 /* Invert VSYNC polarity */
#define HSTART 0x17 /* Horizontal Window start MSB 8 bit */
#define HEND 0x18 /* Horizontal Window end MSB 8 bit */
#define VSTART 0x19 /* Vertical Window start MSB 8 bit */
#define VEND 0x1A /* Vertical Window end MSB 8 bit */
#define MIDH 0x1C /* Manufacturer ID byte - high */
#define MIDL 0x1D /* Manufacturer ID byte - low */
#define AEW 0x24 /* AGC/AEC - Stable operating region (upper limit) */
#define AEB 0x25 /* AGC/AEC - Stable operating region (lower limit) */
#define VV 0x26 /* AGC/AEC Fast mode operating region */
#define VV_HIGH_TH_SET(x) VAL_SET(x, 0xF, 0, 4)
#define VV_LOW_TH_SET(x) VAL_SET(x, 0xF, 0, 0)
#define REG2A 0x2A /* Dummy pixel insert MSB */
#define FRARL 0x2B /* Dummy pixel insert LSB */
#define ADDVFL 0x2D /* LSB of insert dummy lines in Vertical direction */
#define ADDVFH 0x2E /* MSB of insert dummy lines in Vertical direction */
#define YAVG 0x2F /* Y/G Channel Average value */
#define REG32 0x32 /* Common Control 32 */
#define REG32_PCLK_DIV_2 0x80 /* PCLK freq divided by 2 */
#define REG32_PCLK_DIV_4 0xC0 /* PCLK freq divided by 4 */
#define ARCOM2 0x34 /* Zoom: Horizontal start point */
#define REG45 0x45 /* Register 45 */
#define FLL 0x46 /* Frame Length Adjustment LSBs */
#define FLH 0x47 /* Frame Length Adjustment MSBs */
#define COM19 0x48 /* Zoom: Vertical start point */
#define ZOOMS 0x49 /* Zoom: Vertical start point */
#define COM22 0x4B /* Flash light control */
#define COM25 0x4E /* For Banding operations */
#define BD50 0x4F /* 50Hz Banding AEC 8 LSBs */
#define BD60 0x50 /* 60Hz Banding AEC 8 LSBs */
#define REG5D 0x5D /* AVGsel[7:0], 16-zone average weight option */
#define REG5E 0x5E /* AVGsel[15:8], 16-zone average weight option */
#define REG5F 0x5F /* AVGsel[23:16], 16-zone average weight option */
#define REG60 0x60 /* AVGsel[31:24], 16-zone average weight option */
#define HISTO_LOW 0x61 /* Histogram Algorithm Low Level */
#define HISTO_HIGH 0x62 /* Histogram Algorithm High Level */
/*
* ID
*/
#define MANUFACTURER_ID 0x7FA2
#define PID_OV2640 0x2642
#define VERSION(pid, ver) ((pid << 8) | (ver & 0xFF))
/*
* Struct
*/
struct regval_list {
u8 reg_num;
u8 value;
};
/* Supported resolutions */
enum ov2640_width {
W_QCIF = 176,
W_QVGA = 320,
W_CIF = 352,
W_VGA = 640,
W_SVGA = 800,
W_XGA = 1024,
W_SXGA = 1280,
W_UXGA = 1600,
};
enum ov2640_height {
H_QCIF = 144,
H_QVGA = 240,
H_CIF = 288,
H_VGA = 480,
H_SVGA = 600,
H_XGA = 768,
H_SXGA = 1024,
H_UXGA = 1200,
};
struct ov2640_win_size {
char *name;
enum ov2640_width width;
enum ov2640_height height;
const struct regval_list *regs;
};
struct ov2640_priv {
struct v4l2_subdev subdev;
struct v4l2_ctrl_handler hdl;
enum v4l2_mbus_pixelcode cfmt_code;
const struct ov2640_win_size *win;
int model;
};
/*
* Registers settings
*/
#define ENDMARKER { 0xff, 0xff }
static const struct regval_list ov2640_init_regs[] = {
{ BANK_SEL, BANK_SEL_DSP },
{ 0x2c, 0xff },
{ 0x2e, 0xdf },
{ BANK_SEL, BANK_SEL_SENS },
{ 0x3c, 0x32 },
{ CLKRC, CLKRC_DIV_SET(1) },
{ COM2, COM2_OCAP_Nx_SET(3) },
{ REG04, REG04_DEF | REG04_HREF_EN },
{ COM8, COM8_DEF | COM8_BNDF_EN | COM8_AGC_EN | COM8_AEC_EN },
{ COM9, COM9_AGC_GAIN_8x | 0x08},
{ 0x2c, 0x0c },
{ 0x33, 0x78 },
{ 0x3a, 0x33 },
{ 0x3b, 0xfb },
{ 0x3e, 0x00 },
{ 0x43, 0x11 },
{ 0x16, 0x10 },
{ 0x39, 0x02 },
{ 0x35, 0x88 },
{ 0x22, 0x0a },
{ 0x37, 0x40 },
{ 0x23, 0x00 },
{ ARCOM2, 0xa0 },
{ 0x06, 0x02 },
{ 0x06, 0x88 },
{ 0x07, 0xc0 },
{ 0x0d, 0xb7 },
{ 0x0e, 0x01 },
{ 0x4c, 0x00 },
{ 0x4a, 0x81 },
{ 0x21, 0x99 },
{ AEW, 0x40 },
{ AEB, 0x38 },
{ VV, VV_HIGH_TH_SET(0x08) | VV_LOW_TH_SET(0x02) },
{ 0x5c, 0x00 },
{ 0x63, 0x00 },
{ FLL, 0x22 },
{ COM3, 0x38 | COM3_BAND_AUTO },
{ REG5D, 0x55 },
{ REG5E, 0x7d },
{ REG5F, 0x7d },
{ REG60, 0x55 },
{ HISTO_LOW, 0x70 },
{ HISTO_HIGH, 0x80 },
{ 0x7c, 0x05 },
{ 0x20, 0x80 },
{ 0x28, 0x30 },
{ 0x6c, 0x00 },
{ 0x6d, 0x80 },
{ 0x6e, 0x00 },
{ 0x70, 0x02 },
{ 0x71, 0x94 },
{ 0x73, 0xc1 },
{ 0x3d, 0x34 },
{ COM7, COM7_RES_UXGA | COM7_ZOOM_EN },
{ 0x5a, 0x57 },
{ BD50, 0xbb },
{ BD60, 0x9c },
{ BANK_SEL, BANK_SEL_DSP },
{ 0xe5, 0x7f },
{ MC_BIST, MC_BIST_RESET | MC_BIST_BOOT_ROM_SEL },
{ 0x41, 0x24 },
{ RESET, RESET_JPEG | RESET_DVP },
{ 0x76, 0xff },
{ 0x33, 0xa0 },
{ 0x42, 0x20 },
{ 0x43, 0x18 },
{ 0x4c, 0x00 },
{ CTRL3, CTRL3_BPC_EN | CTRL3_WPC_EN | 0x10 },
{ 0x88, 0x3f },
{ 0xd7, 0x03 },
{ 0xd9, 0x10 },
{ R_DVP_SP , R_DVP_SP_AUTO_MODE | 0x2 },
{ 0xc8, 0x08 },
{ 0xc9, 0x80 },
{ BPADDR, 0x00 },
{ BPDATA, 0x00 },
{ BPADDR, 0x03 },
{ BPDATA, 0x48 },
{ BPDATA, 0x48 },
{ BPADDR, 0x08 },
{ BPDATA, 0x20 },
{ BPDATA, 0x10 },
{ BPDATA, 0x0e },
{ 0x90, 0x00 },
{ 0x91, 0x0e },
{ 0x91, 0x1a },
{ 0x91, 0x31 },
{ 0x91, 0x5a },
{ 0x91, 0x69 },
{ 0x91, 0x75 },
{ 0x91, 0x7e },
{ 0x91, 0x88 },
{ 0x91, 0x8f },
{ 0x91, 0x96 },
{ 0x91, 0xa3 },
{ 0x91, 0xaf },
{ 0x91, 0xc4 },
{ 0x91, 0xd7 },
{ 0x91, 0xe8 },
{ 0x91, 0x20 },
{ 0x92, 0x00 },
{ 0x93, 0x06 },
{ 0x93, 0xe3 },
{ 0x93, 0x03 },
{ 0x93, 0x03 },
{ 0x93, 0x00 },
{ 0x93, 0x02 },
{ 0x93, 0x00 },
{ 0x93, 0x00 },
{ 0x93, 0x00 },
{ 0x93, 0x00 },
{ 0x93, 0x00 },
{ 0x93, 0x00 },
{ 0x93, 0x00 },
{ 0x96, 0x00 },
{ 0x97, 0x08 },
{ 0x97, 0x19 },
{ 0x97, 0x02 },
{ 0x97, 0x0c },
{ 0x97, 0x24 },
{ 0x97, 0x30 },
{ 0x97, 0x28 },
{ 0x97, 0x26 },
{ 0x97, 0x02 },
{ 0x97, 0x98 },
{ 0x97, 0x80 },
{ 0x97, 0x00 },
{ 0x97, 0x00 },
{ 0xa4, 0x00 },
{ 0xa8, 0x00 },
{ 0xc5, 0x11 },
{ 0xc6, 0x51 },
{ 0xbf, 0x80 },
{ 0xc7, 0x10 },
{ 0xb6, 0x66 },
{ 0xb8, 0xA5 },
{ 0xb7, 0x64 },
{ 0xb9, 0x7C },
{ 0xb3, 0xaf },
{ 0xb4, 0x97 },
{ 0xb5, 0xFF },
{ 0xb0, 0xC5 },
{ 0xb1, 0x94 },
{ 0xb2, 0x0f },
{ 0xc4, 0x5c },
{ 0xa6, 0x00 },
{ 0xa7, 0x20 },
{ 0xa7, 0xd8 },
{ 0xa7, 0x1b },
{ 0xa7, 0x31 },
{ 0xa7, 0x00 },
{ 0xa7, 0x18 },
{ 0xa7, 0x20 },
{ 0xa7, 0xd8 },
{ 0xa7, 0x19 },
{ 0xa7, 0x31 },
{ 0xa7, 0x00 },
{ 0xa7, 0x18 },
{ 0xa7, 0x20 },
{ 0xa7, 0xd8 },
{ 0xa7, 0x19 },
{ 0xa7, 0x31 },
{ 0xa7, 0x00 },
{ 0xa7, 0x18 },
{ 0x7f, 0x00 },
{ 0xe5, 0x1f },
{ 0xe1, 0x77 },
{ 0xdd, 0x7f },
{ CTRL0, CTRL0_YUV422 | CTRL0_YUV_EN | CTRL0_RGB_EN },
ENDMARKER,
};
/*
* Register settings for window size
* The preamble, setup the internal DSP to input an UXGA (1600x1200) image.
* Then the different zooming configurations will setup the output image size.
*/
static const struct regval_list ov2640_size_change_preamble_regs[] = {
{ BANK_SEL, BANK_SEL_DSP },
{ RESET, RESET_DVP },
{ HSIZE8, HSIZE8_SET(W_UXGA) },
{ VSIZE8, VSIZE8_SET(H_UXGA) },
{ CTRL2, CTRL2_DCW_EN | CTRL2_SDE_EN |
CTRL2_UV_AVG_EN | CTRL2_CMX_EN | CTRL2_UV_ADJ_EN },
{ HSIZE, HSIZE_SET(W_UXGA) },
{ VSIZE, VSIZE_SET(H_UXGA) },
{ XOFFL, XOFFL_SET(0) },
{ YOFFL, YOFFL_SET(0) },
{ VHYX, VHYX_HSIZE_SET(W_UXGA) | VHYX_VSIZE_SET(H_UXGA) |
VHYX_XOFF_SET(0) | VHYX_YOFF_SET(0)},
{ TEST, TEST_HSIZE_SET(W_UXGA) },
ENDMARKER,
};
#define PER_SIZE_REG_SEQ(x, y, v_div, h_div, pclk_div) \
{ CTRLI, CTRLI_LP_DP | CTRLI_V_DIV_SET(v_div) | \
CTRLI_H_DIV_SET(h_div)}, \
{ ZMOW, ZMOW_OUTW_SET(x) }, \
{ ZMOH, ZMOH_OUTH_SET(y) }, \
{ ZMHH, ZMHH_OUTW_SET(x) | ZMHH_OUTH_SET(y) }, \
{ R_DVP_SP, pclk_div }, \
{ RESET, 0x00}
static const struct regval_list ov2640_qcif_regs[] = {
PER_SIZE_REG_SEQ(W_QCIF, H_QCIF, 3, 3, 4),
ENDMARKER,
};
static const struct regval_list ov2640_qvga_regs[] = {
PER_SIZE_REG_SEQ(W_QVGA, H_QVGA, 2, 2, 4),
ENDMARKER,
};
static const struct regval_list ov2640_cif_regs[] = {
PER_SIZE_REG_SEQ(W_CIF, H_CIF, 2, 2, 8),
ENDMARKER,
};
static const struct regval_list ov2640_vga_regs[] = {
PER_SIZE_REG_SEQ(W_VGA, H_VGA, 0, 0, 2),
ENDMARKER,
};
static const struct regval_list ov2640_svga_regs[] = {
PER_SIZE_REG_SEQ(W_SVGA, H_SVGA, 1, 1, 2),
ENDMARKER,
};
static const struct regval_list ov2640_xga_regs[] = {
PER_SIZE_REG_SEQ(W_XGA, H_XGA, 0, 0, 2),
{ CTRLI, 0x00},
ENDMARKER,
};
static const struct regval_list ov2640_sxga_regs[] = {
PER_SIZE_REG_SEQ(W_SXGA, H_SXGA, 0, 0, 2),
{ CTRLI, 0x00},
{ R_DVP_SP, 2 | R_DVP_SP_AUTO_MODE },
ENDMARKER,
};
static const struct regval_list ov2640_uxga_regs[] = {
PER_SIZE_REG_SEQ(W_UXGA, H_UXGA, 0, 0, 0),
{ CTRLI, 0x00},
{ R_DVP_SP, 0 | R_DVP_SP_AUTO_MODE },
ENDMARKER,
};
#define OV2640_SIZE(n, w, h, r) \
{.name = n, .width = w , .height = h, .regs = r }
static const struct ov2640_win_size ov2640_supported_win_sizes[] = {
OV2640_SIZE("QCIF", W_QCIF, H_QCIF, ov2640_qcif_regs),
OV2640_SIZE("QVGA", W_QVGA, H_QVGA, ov2640_qvga_regs),
OV2640_SIZE("CIF", W_CIF, H_CIF, ov2640_cif_regs),
OV2640_SIZE("VGA", W_VGA, H_VGA, ov2640_vga_regs),
OV2640_SIZE("SVGA", W_SVGA, H_SVGA, ov2640_svga_regs),
OV2640_SIZE("XGA", W_XGA, H_XGA, ov2640_xga_regs),
OV2640_SIZE("SXGA", W_SXGA, H_SXGA, ov2640_sxga_regs),
OV2640_SIZE("UXGA", W_UXGA, H_UXGA, ov2640_uxga_regs),
};
/*
* Register settings for pixel formats
*/
static const struct regval_list ov2640_format_change_preamble_regs[] = {
{ BANK_SEL, BANK_SEL_DSP },
{ R_BYPASS, R_BYPASS_USE_DSP },
ENDMARKER,
};
static const struct regval_list ov2640_yuv422_regs[] = {
{ IMAGE_MODE, IMAGE_MODE_LBYTE_FIRST | IMAGE_MODE_YUV422 },
{ 0xD7, 0x01 },
{ 0x33, 0xa0 },
{ 0xe1, 0x67 },
{ RESET, 0x00 },
{ R_BYPASS, R_BYPASS_USE_DSP },
ENDMARKER,
};
static const struct regval_list ov2640_rgb565_regs[] = {
{ IMAGE_MODE, IMAGE_MODE_LBYTE_FIRST | IMAGE_MODE_RGB565 },
{ 0xd7, 0x03 },
{ RESET, 0x00 },
{ R_BYPASS, R_BYPASS_USE_DSP },
ENDMARKER,
};
static enum v4l2_mbus_pixelcode ov2640_codes[] = {
V4L2_MBUS_FMT_UYVY8_2X8,
V4L2_MBUS_FMT_RGB565_2X8_LE,
};
/*
* General functions
*/
static struct ov2640_priv *to_ov2640(const struct i2c_client *client)
{
return container_of(i2c_get_clientdata(client), struct ov2640_priv,
subdev);
}
static int ov2640_write_array(struct i2c_client *client,
const struct regval_list *vals)
{
int ret;
while ((vals->reg_num != 0xff) || (vals->value != 0xff)) {
ret = i2c_smbus_write_byte_data(client,
vals->reg_num, vals->value);
dev_vdbg(&client->dev, "array: 0x%02x, 0x%02x",
vals->reg_num, vals->value);
if (ret < 0)
return ret;
vals++;
}
return 0;
}
static int ov2640_mask_set(struct i2c_client *client,
u8 reg, u8 mask, u8 set)
{
s32 val = i2c_smbus_read_byte_data(client, reg);
if (val < 0)
return val;
val &= ~mask;
val |= set & mask;
dev_vdbg(&client->dev, "masks: 0x%02x, 0x%02x", reg, val);
return i2c_smbus_write_byte_data(client, reg, val);
}
static int ov2640_reset(struct i2c_client *client)
{
int ret;
const struct regval_list reset_seq[] = {
{BANK_SEL, BANK_SEL_SENS},
{COM7, COM7_SRST},
ENDMARKER,
};
ret = ov2640_write_array(client, reset_seq);
if (ret)
goto err;
msleep(5);
err:
dev_dbg(&client->dev, "%s: (ret %d)", __func__, ret);
return ret;
}
/*
* soc_camera_ops functions
*/
static int ov2640_s_stream(struct v4l2_subdev *sd, int enable)
{
return 0;
}
static int ov2640_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct v4l2_subdev *sd =
&container_of(ctrl->handler, struct ov2640_priv, hdl)->subdev;
struct i2c_client *client = v4l2_get_subdevdata(sd);
u8 val;
switch (ctrl->id) {
case V4L2_CID_VFLIP:
val = ctrl->val ? REG04_VFLIP_IMG : 0x00;
return ov2640_mask_set(client, REG04, REG04_VFLIP_IMG, val);
case V4L2_CID_HFLIP:
val = ctrl->val ? REG04_HFLIP_IMG : 0x00;
return ov2640_mask_set(client, REG04, REG04_HFLIP_IMG, val);
}
return -EINVAL;
}
static int ov2640_g_chip_ident(struct v4l2_subdev *sd,
struct v4l2_dbg_chip_ident *id)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct ov2640_priv *priv = to_ov2640(client);
id->ident = priv->model;
id->revision = 0;
return 0;
}
#ifdef CONFIG_VIDEO_ADV_DEBUG
static int ov2640_g_register(struct v4l2_subdev *sd,
struct v4l2_dbg_register *reg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
int ret;
reg->size = 1;
if (reg->reg > 0xff)
return -EINVAL;
ret = i2c_smbus_read_byte_data(client, reg->reg);
if (ret < 0)
return ret;
reg->val = ret;
return 0;
}
static int ov2640_s_register(struct v4l2_subdev *sd,
struct v4l2_dbg_register *reg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
if (reg->reg > 0xff ||
reg->val > 0xff)
return -EINVAL;
return i2c_smbus_write_byte_data(client, reg->reg, reg->val);
}
#endif
/* Select the nearest higher resolution for capture */
static const struct ov2640_win_size *ov2640_select_win(u32 *width, u32 *height)
{
int i, default_size = ARRAY_SIZE(ov2640_supported_win_sizes) - 1;
for (i = 0; i < ARRAY_SIZE(ov2640_supported_win_sizes); i++) {
if (ov2640_supported_win_sizes[i].width >= *width &&
ov2640_supported_win_sizes[i].height >= *height) {
*width = ov2640_supported_win_sizes[i].width;
*height = ov2640_supported_win_sizes[i].height;
return &ov2640_supported_win_sizes[i];
}
}
*width = ov2640_supported_win_sizes[default_size].width;
*height = ov2640_supported_win_sizes[default_size].height;
return &ov2640_supported_win_sizes[default_size];
}
static int ov2640_set_params(struct i2c_client *client, u32 *width, u32 *height,
enum v4l2_mbus_pixelcode code)
{
struct ov2640_priv *priv = to_ov2640(client);
const struct regval_list *selected_cfmt_regs;
int ret;
/* select win */
priv->win = ov2640_select_win(width, height);
/* select format */
priv->cfmt_code = 0;
switch (code) {
case V4L2_MBUS_FMT_RGB565_2X8_LE:
dev_dbg(&client->dev, "%s: Selected cfmt RGB565", __func__);
selected_cfmt_regs = ov2640_rgb565_regs;
break;
default:
case V4L2_MBUS_FMT_UYVY8_2X8:
dev_dbg(&client->dev, "%s: Selected cfmt YUV422", __func__);
selected_cfmt_regs = ov2640_yuv422_regs;
}
/* reset hardware */
ov2640_reset(client);
/* initialize the sensor with default data */
dev_dbg(&client->dev, "%s: Init default", __func__);
ret = ov2640_write_array(client, ov2640_init_regs);
if (ret < 0)
goto err;
/* select preamble */
dev_dbg(&client->dev, "%s: Set size to %s", __func__, priv->win->name);
ret = ov2640_write_array(client, ov2640_size_change_preamble_regs);
if (ret < 0)
goto err;
/* set size win */
ret = ov2640_write_array(client, priv->win->regs);
if (ret < 0)
goto err;
/* cfmt preamble */
dev_dbg(&client->dev, "%s: Set cfmt", __func__);
ret = ov2640_write_array(client, ov2640_format_change_preamble_regs);
if (ret < 0)
goto err;
/* set cfmt */
ret = ov2640_write_array(client, selected_cfmt_regs);
if (ret < 0)
goto err;
priv->cfmt_code = code;
*width = priv->win->width;
*height = priv->win->height;
return 0;
err:
dev_err(&client->dev, "%s: Error %d", __func__, ret);
ov2640_reset(client);
priv->win = NULL;
return ret;
}
static int ov2640_g_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *mf)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct ov2640_priv *priv = to_ov2640(client);
if (!priv->win) {
u32 width = W_SVGA, height = H_SVGA;
int ret = ov2640_set_params(client, &width, &height,
V4L2_MBUS_FMT_UYVY8_2X8);
if (ret < 0)
return ret;
}
mf->width = priv->win->width;
mf->height = priv->win->height;
mf->code = priv->cfmt_code;
switch (mf->code) {
case V4L2_MBUS_FMT_RGB565_2X8_LE:
mf->colorspace = V4L2_COLORSPACE_SRGB;
break;
default:
case V4L2_MBUS_FMT_UYVY8_2X8:
mf->colorspace = V4L2_COLORSPACE_JPEG;
}
mf->field = V4L2_FIELD_NONE;
return 0;
}
static int ov2640_s_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *mf)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
int ret;
switch (mf->code) {
case V4L2_MBUS_FMT_RGB565_2X8_LE:
mf->colorspace = V4L2_COLORSPACE_SRGB;
break;
default:
mf->code = V4L2_MBUS_FMT_UYVY8_2X8;
case V4L2_MBUS_FMT_UYVY8_2X8:
mf->colorspace = V4L2_COLORSPACE_JPEG;
}
ret = ov2640_set_params(client, &mf->width, &mf->height, mf->code);
return ret;
}
static int ov2640_try_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *mf)
{
const struct ov2640_win_size *win;
/*
* select suitable win
*/
win = ov2640_select_win(&mf->width, &mf->height);
mf->field = V4L2_FIELD_NONE;
switch (mf->code) {
case V4L2_MBUS_FMT_RGB565_2X8_LE:
mf->colorspace = V4L2_COLORSPACE_SRGB;
break;
default:
mf->code = V4L2_MBUS_FMT_UYVY8_2X8;
case V4L2_MBUS_FMT_UYVY8_2X8:
mf->colorspace = V4L2_COLORSPACE_JPEG;
}
return 0;
}
static int ov2640_enum_fmt(struct v4l2_subdev *sd, unsigned int index,
enum v4l2_mbus_pixelcode *code)
{
if (index >= ARRAY_SIZE(ov2640_codes))
return -EINVAL;
*code = ov2640_codes[index];
return 0;
}
static int ov2640_g_crop(struct v4l2_subdev *sd, struct v4l2_crop *a)
{
a->c.left = 0;
a->c.top = 0;
a->c.width = W_UXGA;
a->c.height = H_UXGA;
a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
return 0;
}
static int ov2640_cropcap(struct v4l2_subdev *sd, struct v4l2_cropcap *a)
{
a->bounds.left = 0;
a->bounds.top = 0;
a->bounds.width = W_UXGA;
a->bounds.height = H_UXGA;
a->defrect = a->bounds;
a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
a->pixelaspect.numerator = 1;
a->pixelaspect.denominator = 1;
return 0;
}
static int ov2640_video_probe(struct i2c_client *client)
{
struct ov2640_priv *priv = to_ov2640(client);
u8 pid, ver, midh, midl;
const char *devname;
int ret;
/*
* check and show product ID and manufacturer ID
*/
i2c_smbus_write_byte_data(client, BANK_SEL, BANK_SEL_SENS);
pid = i2c_smbus_read_byte_data(client, PID);
ver = i2c_smbus_read_byte_data(client, VER);
midh = i2c_smbus_read_byte_data(client, MIDH);
midl = i2c_smbus_read_byte_data(client, MIDL);
switch (VERSION(pid, ver)) {
case PID_OV2640:
devname = "ov2640";
priv->model = V4L2_IDENT_OV2640;
break;
default:
dev_err(&client->dev,
"Product ID error %x:%x\n", pid, ver);
ret = -ENODEV;
goto err;
}
dev_info(&client->dev,
"%s Product ID %0x:%0x Manufacturer ID %x:%x\n",
devname, pid, ver, midh, midl);
return v4l2_ctrl_handler_setup(&priv->hdl);
err:
return ret;
}
static const struct v4l2_ctrl_ops ov2640_ctrl_ops = {
.s_ctrl = ov2640_s_ctrl,
};
static struct v4l2_subdev_core_ops ov2640_subdev_core_ops = {
.g_chip_ident = ov2640_g_chip_ident,
#ifdef CONFIG_VIDEO_ADV_DEBUG
.g_register = ov2640_g_register,
.s_register = ov2640_s_register,
#endif
};
static int ov2640_g_mbus_config(struct v4l2_subdev *sd,
struct v4l2_mbus_config *cfg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct soc_camera_link *icl = soc_camera_i2c_to_link(client);
cfg->flags = V4L2_MBUS_PCLK_SAMPLE_RISING | V4L2_MBUS_MASTER |
V4L2_MBUS_VSYNC_ACTIVE_HIGH | V4L2_MBUS_HSYNC_ACTIVE_HIGH |
V4L2_MBUS_DATA_ACTIVE_HIGH;
cfg->type = V4L2_MBUS_PARALLEL;
cfg->flags = soc_camera_apply_board_flags(icl, cfg);
return 0;
}
static struct v4l2_subdev_video_ops ov2640_subdev_video_ops = {
.s_stream = ov2640_s_stream,
.g_mbus_fmt = ov2640_g_fmt,
.s_mbus_fmt = ov2640_s_fmt,
.try_mbus_fmt = ov2640_try_fmt,
.cropcap = ov2640_cropcap,
.g_crop = ov2640_g_crop,
.enum_mbus_fmt = ov2640_enum_fmt,
.g_mbus_config = ov2640_g_mbus_config,
};
static struct v4l2_subdev_ops ov2640_subdev_ops = {
.core = &ov2640_subdev_core_ops,
.video = &ov2640_subdev_video_ops,
};
/*
* i2c_driver functions
*/
static int ov2640_probe(struct i2c_client *client,
const struct i2c_device_id *did)
{
struct ov2640_priv *priv;
struct soc_camera_link *icl = soc_camera_i2c_to_link(client);
struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent);
int ret;
if (!icl) {
dev_err(&adapter->dev,
"OV2640: Missing platform_data for driver\n");
return -EINVAL;
}
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA)) {
dev_err(&adapter->dev,
"OV2640: I2C-Adapter doesn't support SMBUS\n");
return -EIO;
}
priv = kzalloc(sizeof(struct ov2640_priv), GFP_KERNEL);
if (!priv) {
dev_err(&adapter->dev,
"Failed to allocate memory for private data!\n");
return -ENOMEM;
}
v4l2_i2c_subdev_init(&priv->subdev, client, &ov2640_subdev_ops);
v4l2_ctrl_handler_init(&priv->hdl, 2);
v4l2_ctrl_new_std(&priv->hdl, &ov2640_ctrl_ops,
V4L2_CID_VFLIP, 0, 1, 1, 0);
v4l2_ctrl_new_std(&priv->hdl, &ov2640_ctrl_ops,
V4L2_CID_HFLIP, 0, 1, 1, 0);
priv->subdev.ctrl_handler = &priv->hdl;
if (priv->hdl.error) {
int err = priv->hdl.error;
kfree(priv);
return err;
}
ret = ov2640_video_probe(client);
if (ret) {
v4l2_ctrl_handler_free(&priv->hdl);
kfree(priv);
} else {
dev_info(&adapter->dev, "OV2640 Probed\n");
}
return ret;
}
static int ov2640_remove(struct i2c_client *client)
{
struct ov2640_priv *priv = to_ov2640(client);
v4l2_device_unregister_subdev(&priv->subdev);
v4l2_ctrl_handler_free(&priv->hdl);
kfree(priv);
return 0;
}
static const struct i2c_device_id ov2640_id[] = {
{ "ov2640", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, ov2640_id);
static struct i2c_driver ov2640_i2c_driver = {
.driver = {
.name = "ov2640",
},
.probe = ov2640_probe,
.remove = ov2640_remove,
.id_table = ov2640_id,
};
module_i2c_driver(ov2640_i2c_driver);
MODULE_DESCRIPTION("SoC Camera driver for Omni Vision 2640 sensor");
MODULE_AUTHOR("Alberto Panizzo");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
kundancool/android_kernel_xiaomi_msm8974 | drivers/media/video/tvaudio.c | 4863 | 63582 | /*
* Driver for simple i2c audio chips.
*
* Copyright (c) 2000 Gerd Knorr
* based on code by:
* Eric Sandeen (eric_sandeen@bigfoot.com)
* Steve VanDeBogart (vandebo@uclink.berkeley.edu)
* Greg Alexander (galexand@acm.org)
*
* Copyright(c) 2005-2008 Mauro Carvalho Chehab
* - Some cleanups, code fixes, etc
* - Convert it to V4L2 API
*
* This code is placed under the terms of the GNU General Public License
*
* OPTIONS:
* debug - set to 1 if you'd like to see debug messages
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/videodev2.h>
#include <linux/i2c.h>
#include <linux/init.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <media/tvaudio.h>
#include <media/v4l2-device.h>
#include <media/v4l2-chip-ident.h>
#include <media/i2c-addr.h>
/* ---------------------------------------------------------------------- */
/* insmod args */
static int debug; /* insmod parameter */
module_param(debug, int, 0644);
MODULE_DESCRIPTION("device driver for various i2c TV sound decoder / audiomux chips");
MODULE_AUTHOR("Eric Sandeen, Steve VanDeBogart, Greg Alexander, Gerd Knorr");
MODULE_LICENSE("GPL");
#define UNSET (-1U)
/* ---------------------------------------------------------------------- */
/* our structs */
#define MAXREGS 256
struct CHIPSTATE;
typedef int (*getvalue)(int);
typedef int (*checkit)(struct CHIPSTATE*);
typedef int (*initialize)(struct CHIPSTATE*);
typedef int (*getmode)(struct CHIPSTATE*);
typedef void (*setmode)(struct CHIPSTATE*, int mode);
/* i2c command */
typedef struct AUDIOCMD {
int count; /* # of bytes to send */
unsigned char bytes[MAXREGS+1]; /* addr, data, data, ... */
} audiocmd;
/* chip description */
struct CHIPDESC {
char *name; /* chip name */
int addr_lo, addr_hi; /* i2c address range */
int registers; /* # of registers */
int *insmodopt;
checkit checkit;
initialize initialize;
int flags;
#define CHIP_HAS_VOLUME 1
#define CHIP_HAS_BASSTREBLE 2
#define CHIP_HAS_INPUTSEL 4
#define CHIP_NEED_CHECKMODE 8
/* various i2c command sequences */
audiocmd init;
/* which register has which value */
int leftreg,rightreg,treblereg,bassreg;
/* initialize with (defaults to 65535/65535/32768/32768 */
int leftinit,rightinit,trebleinit,bassinit;
/* functions to convert the values (v4l -> chip) */
getvalue volfunc,treblefunc,bassfunc;
/* get/set mode */
getmode getmode;
setmode setmode;
/* input switch register + values for v4l inputs */
int inputreg;
int inputmap[4];
int inputmute;
int inputmask;
};
/* current state of the chip */
struct CHIPSTATE {
struct v4l2_subdev sd;
/* chip-specific description - should point to
an entry at CHIPDESC table */
struct CHIPDESC *desc;
/* shadow register set */
audiocmd shadow;
/* current settings */
__u16 left,right,treble,bass,muted,mode;
int prevmode;
int radio;
int input;
/* thread */
struct task_struct *thread;
struct timer_list wt;
int watch_stereo;
int audmode;
};
static inline struct CHIPSTATE *to_state(struct v4l2_subdev *sd)
{
return container_of(sd, struct CHIPSTATE, sd);
}
/* ---------------------------------------------------------------------- */
/* i2c I/O functions */
static int chip_write(struct CHIPSTATE *chip, int subaddr, int val)
{
struct v4l2_subdev *sd = &chip->sd;
struct i2c_client *c = v4l2_get_subdevdata(sd);
unsigned char buffer[2];
if (subaddr < 0) {
v4l2_dbg(1, debug, sd, "chip_write: 0x%x\n", val);
chip->shadow.bytes[1] = val;
buffer[0] = val;
if (1 != i2c_master_send(c, buffer, 1)) {
v4l2_warn(sd, "I/O error (write 0x%x)\n", val);
return -1;
}
} else {
if (subaddr + 1 >= ARRAY_SIZE(chip->shadow.bytes)) {
v4l2_info(sd,
"Tried to access a non-existent register: %d\n",
subaddr);
return -EINVAL;
}
v4l2_dbg(1, debug, sd, "chip_write: reg%d=0x%x\n",
subaddr, val);
chip->shadow.bytes[subaddr+1] = val;
buffer[0] = subaddr;
buffer[1] = val;
if (2 != i2c_master_send(c, buffer, 2)) {
v4l2_warn(sd, "I/O error (write reg%d=0x%x)\n",
subaddr, val);
return -1;
}
}
return 0;
}
static int chip_write_masked(struct CHIPSTATE *chip,
int subaddr, int val, int mask)
{
struct v4l2_subdev *sd = &chip->sd;
if (mask != 0) {
if (subaddr < 0) {
val = (chip->shadow.bytes[1] & ~mask) | (val & mask);
} else {
if (subaddr + 1 >= ARRAY_SIZE(chip->shadow.bytes)) {
v4l2_info(sd,
"Tried to access a non-existent register: %d\n",
subaddr);
return -EINVAL;
}
val = (chip->shadow.bytes[subaddr+1] & ~mask) | (val & mask);
}
}
return chip_write(chip, subaddr, val);
}
static int chip_read(struct CHIPSTATE *chip)
{
struct v4l2_subdev *sd = &chip->sd;
struct i2c_client *c = v4l2_get_subdevdata(sd);
unsigned char buffer;
if (1 != i2c_master_recv(c, &buffer, 1)) {
v4l2_warn(sd, "I/O error (read)\n");
return -1;
}
v4l2_dbg(1, debug, sd, "chip_read: 0x%x\n", buffer);
return buffer;
}
static int chip_read2(struct CHIPSTATE *chip, int subaddr)
{
struct v4l2_subdev *sd = &chip->sd;
struct i2c_client *c = v4l2_get_subdevdata(sd);
unsigned char write[1];
unsigned char read[1];
struct i2c_msg msgs[2] = {
{ c->addr, 0, 1, write },
{ c->addr, I2C_M_RD, 1, read }
};
write[0] = subaddr;
if (2 != i2c_transfer(c->adapter, msgs, 2)) {
v4l2_warn(sd, "I/O error (read2)\n");
return -1;
}
v4l2_dbg(1, debug, sd, "chip_read2: reg%d=0x%x\n",
subaddr, read[0]);
return read[0];
}
static int chip_cmd(struct CHIPSTATE *chip, char *name, audiocmd *cmd)
{
struct v4l2_subdev *sd = &chip->sd;
struct i2c_client *c = v4l2_get_subdevdata(sd);
int i;
if (0 == cmd->count)
return 0;
if (cmd->count + cmd->bytes[0] - 1 >= ARRAY_SIZE(chip->shadow.bytes)) {
v4l2_info(sd,
"Tried to access a non-existent register range: %d to %d\n",
cmd->bytes[0] + 1, cmd->bytes[0] + cmd->count - 1);
return -EINVAL;
}
/* FIXME: it seems that the shadow bytes are wrong bellow !*/
/* update our shadow register set; print bytes if (debug > 0) */
v4l2_dbg(1, debug, sd, "chip_cmd(%s): reg=%d, data:",
name, cmd->bytes[0]);
for (i = 1; i < cmd->count; i++) {
if (debug)
printk(KERN_CONT " 0x%x", cmd->bytes[i]);
chip->shadow.bytes[i+cmd->bytes[0]] = cmd->bytes[i];
}
if (debug)
printk(KERN_CONT "\n");
/* send data to the chip */
if (cmd->count != i2c_master_send(c, cmd->bytes, cmd->count)) {
v4l2_warn(sd, "I/O error (%s)\n", name);
return -1;
}
return 0;
}
/* ---------------------------------------------------------------------- */
/* kernel thread for doing i2c stuff asyncronly
* right now it is used only to check the audio mode (mono/stereo/whatever)
* some time after switching to another TV channel, then turn on stereo
* if available, ...
*/
static void chip_thread_wake(unsigned long data)
{
struct CHIPSTATE *chip = (struct CHIPSTATE*)data;
wake_up_process(chip->thread);
}
static int chip_thread(void *data)
{
struct CHIPSTATE *chip = data;
struct CHIPDESC *desc = chip->desc;
struct v4l2_subdev *sd = &chip->sd;
int mode;
v4l2_dbg(1, debug, sd, "thread started\n");
set_freezable();
for (;;) {
set_current_state(TASK_INTERRUPTIBLE);
if (!kthread_should_stop())
schedule();
set_current_state(TASK_RUNNING);
try_to_freeze();
if (kthread_should_stop())
break;
v4l2_dbg(1, debug, sd, "thread wakeup\n");
/* don't do anything for radio or if mode != auto */
if (chip->radio || chip->mode != 0)
continue;
/* have a look what's going on */
mode = desc->getmode(chip);
if (mode == chip->prevmode)
continue;
/* chip detected a new audio mode - set it */
v4l2_dbg(1, debug, sd, "thread checkmode\n");
chip->prevmode = mode;
if (mode & V4L2_TUNER_MODE_STEREO)
desc->setmode(chip, V4L2_TUNER_MODE_STEREO);
if (mode & V4L2_TUNER_MODE_LANG1_LANG2)
desc->setmode(chip, V4L2_TUNER_MODE_STEREO);
else if (mode & V4L2_TUNER_MODE_LANG1)
desc->setmode(chip, V4L2_TUNER_MODE_LANG1);
else if (mode & V4L2_TUNER_MODE_LANG2)
desc->setmode(chip, V4L2_TUNER_MODE_LANG2);
else
desc->setmode(chip, V4L2_TUNER_MODE_MONO);
/* schedule next check */
mod_timer(&chip->wt, jiffies+msecs_to_jiffies(2000));
}
v4l2_dbg(1, debug, sd, "thread exiting\n");
return 0;
}
/* ---------------------------------------------------------------------- */
/* audio chip descriptions - defines+functions for tda9840 */
#define TDA9840_SW 0x00
#define TDA9840_LVADJ 0x02
#define TDA9840_STADJ 0x03
#define TDA9840_TEST 0x04
#define TDA9840_MONO 0x10
#define TDA9840_STEREO 0x2a
#define TDA9840_DUALA 0x12
#define TDA9840_DUALB 0x1e
#define TDA9840_DUALAB 0x1a
#define TDA9840_DUALBA 0x16
#define TDA9840_EXTERNAL 0x7a
#define TDA9840_DS_DUAL 0x20 /* Dual sound identified */
#define TDA9840_ST_STEREO 0x40 /* Stereo sound identified */
#define TDA9840_PONRES 0x80 /* Power-on reset detected if = 1 */
#define TDA9840_TEST_INT1SN 0x1 /* Integration time 0.5s when set */
#define TDA9840_TEST_INTFU 0x02 /* Disables integrator function */
static int tda9840_getmode(struct CHIPSTATE *chip)
{
struct v4l2_subdev *sd = &chip->sd;
int val, mode;
val = chip_read(chip);
mode = V4L2_TUNER_MODE_MONO;
if (val & TDA9840_DS_DUAL)
mode |= V4L2_TUNER_MODE_LANG1 | V4L2_TUNER_MODE_LANG2;
if (val & TDA9840_ST_STEREO)
mode |= V4L2_TUNER_MODE_STEREO;
v4l2_dbg(1, debug, sd, "tda9840_getmode(): raw chip read: %d, return: %d\n",
val, mode);
return mode;
}
static void tda9840_setmode(struct CHIPSTATE *chip, int mode)
{
int update = 1;
int t = chip->shadow.bytes[TDA9840_SW + 1] & ~0x7e;
switch (mode) {
case V4L2_TUNER_MODE_MONO:
t |= TDA9840_MONO;
break;
case V4L2_TUNER_MODE_STEREO:
t |= TDA9840_STEREO;
break;
case V4L2_TUNER_MODE_LANG1:
t |= TDA9840_DUALA;
break;
case V4L2_TUNER_MODE_LANG2:
t |= TDA9840_DUALB;
break;
default:
update = 0;
}
if (update)
chip_write(chip, TDA9840_SW, t);
}
static int tda9840_checkit(struct CHIPSTATE *chip)
{
int rc;
rc = chip_read(chip);
/* lower 5 bits should be 0 */
return ((rc & 0x1f) == 0) ? 1 : 0;
}
/* ---------------------------------------------------------------------- */
/* audio chip descriptions - defines+functions for tda985x */
/* subaddresses for TDA9855 */
#define TDA9855_VR 0x00 /* Volume, right */
#define TDA9855_VL 0x01 /* Volume, left */
#define TDA9855_BA 0x02 /* Bass */
#define TDA9855_TR 0x03 /* Treble */
#define TDA9855_SW 0x04 /* Subwoofer - not connected on DTV2000 */
/* subaddresses for TDA9850 */
#define TDA9850_C4 0x04 /* Control 1 for TDA9850 */
/* subaddesses for both chips */
#define TDA985x_C5 0x05 /* Control 2 for TDA9850, Control 1 for TDA9855 */
#define TDA985x_C6 0x06 /* Control 3 for TDA9850, Control 2 for TDA9855 */
#define TDA985x_C7 0x07 /* Control 4 for TDA9850, Control 3 for TDA9855 */
#define TDA985x_A1 0x08 /* Alignment 1 for both chips */
#define TDA985x_A2 0x09 /* Alignment 2 for both chips */
#define TDA985x_A3 0x0a /* Alignment 3 for both chips */
/* Masks for bits in TDA9855 subaddresses */
/* 0x00 - VR in TDA9855 */
/* 0x01 - VL in TDA9855 */
/* lower 7 bits control gain from -71dB (0x28) to 16dB (0x7f)
* in 1dB steps - mute is 0x27 */
/* 0x02 - BA in TDA9855 */
/* lower 5 bits control bass gain from -12dB (0x06) to 16.5dB (0x19)
* in .5dB steps - 0 is 0x0E */
/* 0x03 - TR in TDA9855 */
/* 4 bits << 1 control treble gain from -12dB (0x3) to 12dB (0xb)
* in 3dB steps - 0 is 0x7 */
/* Masks for bits in both chips' subaddresses */
/* 0x04 - SW in TDA9855, C4/Control 1 in TDA9850 */
/* Unique to TDA9855: */
/* 4 bits << 2 control subwoofer/surround gain from -14db (0x1) to 14db (0xf)
* in 3dB steps - mute is 0x0 */
/* Unique to TDA9850: */
/* lower 4 bits control stereo noise threshold, over which stereo turns off
* set to values of 0x00 through 0x0f for Ster1 through Ster16 */
/* 0x05 - C5 - Control 1 in TDA9855 , Control 2 in TDA9850*/
/* Unique to TDA9855: */
#define TDA9855_MUTE 1<<7 /* GMU, Mute at outputs */
#define TDA9855_AVL 1<<6 /* AVL, Automatic Volume Level */
#define TDA9855_LOUD 1<<5 /* Loudness, 1==off */
#define TDA9855_SUR 1<<3 /* Surround / Subwoofer 1==.5(L-R) 0==.5(L+R) */
/* Bits 0 to 3 select various combinations
* of line in and line out, only the
* interesting ones are defined */
#define TDA9855_EXT 1<<2 /* Selects inputs LIR and LIL. Pins 41 & 12 */
#define TDA9855_INT 0 /* Selects inputs LOR and LOL. (internal) */
/* Unique to TDA9850: */
/* lower 4 bits contol SAP noise threshold, over which SAP turns off
* set to values of 0x00 through 0x0f for SAP1 through SAP16 */
/* 0x06 - C6 - Control 2 in TDA9855, Control 3 in TDA9850 */
/* Common to TDA9855 and TDA9850: */
#define TDA985x_SAP 3<<6 /* Selects SAP output, mute if not received */
#define TDA985x_STEREO 1<<6 /* Selects Stereo ouput, mono if not received */
#define TDA985x_MONO 0 /* Forces Mono output */
#define TDA985x_LMU 1<<3 /* Mute (LOR/LOL for 9855, OUTL/OUTR for 9850) */
/* Unique to TDA9855: */
#define TDA9855_TZCM 1<<5 /* If set, don't mute till zero crossing */
#define TDA9855_VZCM 1<<4 /* If set, don't change volume till zero crossing*/
#define TDA9855_LINEAR 0 /* Linear Stereo */
#define TDA9855_PSEUDO 1 /* Pseudo Stereo */
#define TDA9855_SPAT_30 2 /* Spatial Stereo, 30% anti-phase crosstalk */
#define TDA9855_SPAT_50 3 /* Spatial Stereo, 52% anti-phase crosstalk */
#define TDA9855_E_MONO 7 /* Forced mono - mono select elseware, so useless*/
/* 0x07 - C7 - Control 3 in TDA9855, Control 4 in TDA9850 */
/* Common to both TDA9855 and TDA9850: */
/* lower 4 bits control input gain from -3.5dB (0x0) to 4dB (0xF)
* in .5dB steps - 0dB is 0x7 */
/* 0x08, 0x09 - A1 and A2 (read/write) */
/* Common to both TDA9855 and TDA9850: */
/* lower 5 bites are wideband and spectral expander alignment
* from 0x00 to 0x1f - nominal at 0x0f and 0x10 (read/write) */
#define TDA985x_STP 1<<5 /* Stereo Pilot/detect (read-only) */
#define TDA985x_SAPP 1<<6 /* SAP Pilot/detect (read-only) */
#define TDA985x_STS 1<<7 /* Stereo trigger 1= <35mV 0= <30mV (write-only)*/
/* 0x0a - A3 */
/* Common to both TDA9855 and TDA9850: */
/* lower 3 bits control timing current for alignment: -30% (0x0), -20% (0x1),
* -10% (0x2), nominal (0x3), +10% (0x6), +20% (0x5), +30% (0x4) */
#define TDA985x_ADJ 1<<7 /* Stereo adjust on/off (wideband and spectral */
static int tda9855_volume(int val) { return val/0x2e8+0x27; }
static int tda9855_bass(int val) { return val/0xccc+0x06; }
static int tda9855_treble(int val) { return (val/0x1c71+0x3)<<1; }
static int tda985x_getmode(struct CHIPSTATE *chip)
{
int mode;
mode = ((TDA985x_STP | TDA985x_SAPP) &
chip_read(chip)) >> 4;
/* Add mono mode regardless of SAP and stereo */
/* Allows forced mono */
return mode | V4L2_TUNER_MODE_MONO;
}
static void tda985x_setmode(struct CHIPSTATE *chip, int mode)
{
int update = 1;
int c6 = chip->shadow.bytes[TDA985x_C6+1] & 0x3f;
switch (mode) {
case V4L2_TUNER_MODE_MONO:
c6 |= TDA985x_MONO;
break;
case V4L2_TUNER_MODE_STEREO:
c6 |= TDA985x_STEREO;
break;
case V4L2_TUNER_MODE_LANG1:
c6 |= TDA985x_SAP;
break;
default:
update = 0;
}
if (update)
chip_write(chip,TDA985x_C6,c6);
}
/* ---------------------------------------------------------------------- */
/* audio chip descriptions - defines+functions for tda9873h */
/* Subaddresses for TDA9873H */
#define TDA9873_SW 0x00 /* Switching */
#define TDA9873_AD 0x01 /* Adjust */
#define TDA9873_PT 0x02 /* Port */
/* Subaddress 0x00: Switching Data
* B7..B0:
*
* B1, B0: Input source selection
* 0, 0 internal
* 1, 0 external stereo
* 0, 1 external mono
*/
#define TDA9873_INP_MASK 3
#define TDA9873_INTERNAL 0
#define TDA9873_EXT_STEREO 2
#define TDA9873_EXT_MONO 1
/* B3, B2: output signal select
* B4 : transmission mode
* 0, 0, 1 Mono
* 1, 0, 0 Stereo
* 1, 1, 1 Stereo (reversed channel)
* 0, 0, 0 Dual AB
* 0, 0, 1 Dual AA
* 0, 1, 0 Dual BB
* 0, 1, 1 Dual BA
*/
#define TDA9873_TR_MASK (7 << 2)
#define TDA9873_TR_MONO 4
#define TDA9873_TR_STEREO 1 << 4
#define TDA9873_TR_REVERSE (1 << 3) & (1 << 2)
#define TDA9873_TR_DUALA 1 << 2
#define TDA9873_TR_DUALB 1 << 3
/* output level controls
* B5: output level switch (0 = reduced gain, 1 = normal gain)
* B6: mute (1 = muted)
* B7: auto-mute (1 = auto-mute enabled)
*/
#define TDA9873_GAIN_NORMAL 1 << 5
#define TDA9873_MUTE 1 << 6
#define TDA9873_AUTOMUTE 1 << 7
/* Subaddress 0x01: Adjust/standard */
/* Lower 4 bits (C3..C0) control stereo adjustment on R channel (-0.6 - +0.7 dB)
* Recommended value is +0 dB
*/
#define TDA9873_STEREO_ADJ 0x06 /* 0dB gain */
/* Bits C6..C4 control FM stantard
* C6, C5, C4
* 0, 0, 0 B/G (PAL FM)
* 0, 0, 1 M
* 0, 1, 0 D/K(1)
* 0, 1, 1 D/K(2)
* 1, 0, 0 D/K(3)
* 1, 0, 1 I
*/
#define TDA9873_BG 0
#define TDA9873_M 1
#define TDA9873_DK1 2
#define TDA9873_DK2 3
#define TDA9873_DK3 4
#define TDA9873_I 5
/* C7 controls identification response time (1=fast/0=normal)
*/
#define TDA9873_IDR_NORM 0
#define TDA9873_IDR_FAST 1 << 7
/* Subaddress 0x02: Port data */
/* E1, E0 free programmable ports P1/P2
0, 0 both ports low
0, 1 P1 high
1, 0 P2 high
1, 1 both ports high
*/
#define TDA9873_PORTS 3
/* E2: test port */
#define TDA9873_TST_PORT 1 << 2
/* E5..E3 control mono output channel (together with transmission mode bit B4)
*
* E5 E4 E3 B4 OUTM
* 0 0 0 0 mono
* 0 0 1 0 DUAL B
* 0 1 0 1 mono (from stereo decoder)
*/
#define TDA9873_MOUT_MONO 0
#define TDA9873_MOUT_FMONO 0
#define TDA9873_MOUT_DUALA 0
#define TDA9873_MOUT_DUALB 1 << 3
#define TDA9873_MOUT_ST 1 << 4
#define TDA9873_MOUT_EXTM (1 << 4 ) & (1 << 3)
#define TDA9873_MOUT_EXTL 1 << 5
#define TDA9873_MOUT_EXTR (1 << 5 ) & (1 << 3)
#define TDA9873_MOUT_EXTLR (1 << 5 ) & (1 << 4)
#define TDA9873_MOUT_MUTE (1 << 5 ) & (1 << 4) & (1 << 3)
/* Status bits: (chip read) */
#define TDA9873_PONR 0 /* Power-on reset detected if = 1 */
#define TDA9873_STEREO 2 /* Stereo sound is identified */
#define TDA9873_DUAL 4 /* Dual sound is identified */
static int tda9873_getmode(struct CHIPSTATE *chip)
{
struct v4l2_subdev *sd = &chip->sd;
int val,mode;
val = chip_read(chip);
mode = V4L2_TUNER_MODE_MONO;
if (val & TDA9873_STEREO)
mode |= V4L2_TUNER_MODE_STEREO;
if (val & TDA9873_DUAL)
mode |= V4L2_TUNER_MODE_LANG1 | V4L2_TUNER_MODE_LANG2;
v4l2_dbg(1, debug, sd, "tda9873_getmode(): raw chip read: %d, return: %d\n",
val, mode);
return mode;
}
static void tda9873_setmode(struct CHIPSTATE *chip, int mode)
{
struct v4l2_subdev *sd = &chip->sd;
int sw_data = chip->shadow.bytes[TDA9873_SW+1] & ~ TDA9873_TR_MASK;
/* int adj_data = chip->shadow.bytes[TDA9873_AD+1] ; */
if ((sw_data & TDA9873_INP_MASK) != TDA9873_INTERNAL) {
v4l2_dbg(1, debug, sd, "tda9873_setmode(): external input\n");
return;
}
v4l2_dbg(1, debug, sd, "tda9873_setmode(): chip->shadow.bytes[%d] = %d\n", TDA9873_SW+1, chip->shadow.bytes[TDA9873_SW+1]);
v4l2_dbg(1, debug, sd, "tda9873_setmode(): sw_data = %d\n", sw_data);
switch (mode) {
case V4L2_TUNER_MODE_MONO:
sw_data |= TDA9873_TR_MONO;
break;
case V4L2_TUNER_MODE_STEREO:
sw_data |= TDA9873_TR_STEREO;
break;
case V4L2_TUNER_MODE_LANG1:
sw_data |= TDA9873_TR_DUALA;
break;
case V4L2_TUNER_MODE_LANG2:
sw_data |= TDA9873_TR_DUALB;
break;
default:
chip->mode = 0;
return;
}
chip_write(chip, TDA9873_SW, sw_data);
v4l2_dbg(1, debug, sd, "tda9873_setmode(): req. mode %d; chip_write: %d\n",
mode, sw_data);
}
static int tda9873_checkit(struct CHIPSTATE *chip)
{
int rc;
if (-1 == (rc = chip_read2(chip,254)))
return 0;
return (rc & ~0x1f) == 0x80;
}
/* ---------------------------------------------------------------------- */
/* audio chip description - defines+functions for tda9874h and tda9874a */
/* Dariusz Kowalewski <darekk@automex.pl> */
/* Subaddresses for TDA9874H and TDA9874A (slave rx) */
#define TDA9874A_AGCGR 0x00 /* AGC gain */
#define TDA9874A_GCONR 0x01 /* general config */
#define TDA9874A_MSR 0x02 /* monitor select */
#define TDA9874A_C1FRA 0x03 /* carrier 1 freq. */
#define TDA9874A_C1FRB 0x04 /* carrier 1 freq. */
#define TDA9874A_C1FRC 0x05 /* carrier 1 freq. */
#define TDA9874A_C2FRA 0x06 /* carrier 2 freq. */
#define TDA9874A_C2FRB 0x07 /* carrier 2 freq. */
#define TDA9874A_C2FRC 0x08 /* carrier 2 freq. */
#define TDA9874A_DCR 0x09 /* demodulator config */
#define TDA9874A_FMER 0x0a /* FM de-emphasis */
#define TDA9874A_FMMR 0x0b /* FM dematrix */
#define TDA9874A_C1OLAR 0x0c /* ch.1 output level adj. */
#define TDA9874A_C2OLAR 0x0d /* ch.2 output level adj. */
#define TDA9874A_NCONR 0x0e /* NICAM config */
#define TDA9874A_NOLAR 0x0f /* NICAM output level adj. */
#define TDA9874A_NLELR 0x10 /* NICAM lower error limit */
#define TDA9874A_NUELR 0x11 /* NICAM upper error limit */
#define TDA9874A_AMCONR 0x12 /* audio mute control */
#define TDA9874A_SDACOSR 0x13 /* stereo DAC output select */
#define TDA9874A_AOSR 0x14 /* analog output select */
#define TDA9874A_DAICONR 0x15 /* digital audio interface config */
#define TDA9874A_I2SOSR 0x16 /* I2S-bus output select */
#define TDA9874A_I2SOLAR 0x17 /* I2S-bus output level adj. */
#define TDA9874A_MDACOSR 0x18 /* mono DAC output select (tda9874a) */
#define TDA9874A_ESP 0xFF /* easy standard progr. (tda9874a) */
/* Subaddresses for TDA9874H and TDA9874A (slave tx) */
#define TDA9874A_DSR 0x00 /* device status */
#define TDA9874A_NSR 0x01 /* NICAM status */
#define TDA9874A_NECR 0x02 /* NICAM error count */
#define TDA9874A_DR1 0x03 /* add. data LSB */
#define TDA9874A_DR2 0x04 /* add. data MSB */
#define TDA9874A_LLRA 0x05 /* monitor level read-out LSB */
#define TDA9874A_LLRB 0x06 /* monitor level read-out MSB */
#define TDA9874A_SIFLR 0x07 /* SIF level */
#define TDA9874A_TR2 252 /* test reg. 2 */
#define TDA9874A_TR1 253 /* test reg. 1 */
#define TDA9874A_DIC 254 /* device id. code */
#define TDA9874A_SIC 255 /* software id. code */
static int tda9874a_mode = 1; /* 0: A2, 1: NICAM */
static int tda9874a_GCONR = 0xc0; /* default config. input pin: SIFSEL=0 */
static int tda9874a_NCONR = 0x01; /* default NICAM config.: AMSEL=0,AMUTE=1 */
static int tda9874a_ESP = 0x07; /* default standard: NICAM D/K */
static int tda9874a_dic = -1; /* device id. code */
/* insmod options for tda9874a */
static unsigned int tda9874a_SIF = UNSET;
static unsigned int tda9874a_AMSEL = UNSET;
static unsigned int tda9874a_STD = UNSET;
module_param(tda9874a_SIF, int, 0444);
module_param(tda9874a_AMSEL, int, 0444);
module_param(tda9874a_STD, int, 0444);
/*
* initialization table for tda9874 decoder:
* - carrier 1 freq. registers (3 bytes)
* - carrier 2 freq. registers (3 bytes)
* - demudulator config register
* - FM de-emphasis register (slow identification mode)
* Note: frequency registers must be written in single i2c transfer.
*/
static struct tda9874a_MODES {
char *name;
audiocmd cmd;
} tda9874a_modelist[9] = {
{ "A2, B/G", /* default */
{ 9, { TDA9874A_C1FRA, 0x72,0x95,0x55, 0x77,0xA0,0x00, 0x00,0x00 }} },
{ "A2, M (Korea)",
{ 9, { TDA9874A_C1FRA, 0x5D,0xC0,0x00, 0x62,0x6A,0xAA, 0x20,0x22 }} },
{ "A2, D/K (1)",
{ 9, { TDA9874A_C1FRA, 0x87,0x6A,0xAA, 0x82,0x60,0x00, 0x00,0x00 }} },
{ "A2, D/K (2)",
{ 9, { TDA9874A_C1FRA, 0x87,0x6A,0xAA, 0x8C,0x75,0x55, 0x00,0x00 }} },
{ "A2, D/K (3)",
{ 9, { TDA9874A_C1FRA, 0x87,0x6A,0xAA, 0x77,0xA0,0x00, 0x00,0x00 }} },
{ "NICAM, I",
{ 9, { TDA9874A_C1FRA, 0x7D,0x00,0x00, 0x88,0x8A,0xAA, 0x08,0x33 }} },
{ "NICAM, B/G",
{ 9, { TDA9874A_C1FRA, 0x72,0x95,0x55, 0x79,0xEA,0xAA, 0x08,0x33 }} },
{ "NICAM, D/K",
{ 9, { TDA9874A_C1FRA, 0x87,0x6A,0xAA, 0x79,0xEA,0xAA, 0x08,0x33 }} },
{ "NICAM, L",
{ 9, { TDA9874A_C1FRA, 0x87,0x6A,0xAA, 0x79,0xEA,0xAA, 0x09,0x33 }} }
};
static int tda9874a_setup(struct CHIPSTATE *chip)
{
struct v4l2_subdev *sd = &chip->sd;
chip_write(chip, TDA9874A_AGCGR, 0x00); /* 0 dB */
chip_write(chip, TDA9874A_GCONR, tda9874a_GCONR);
chip_write(chip, TDA9874A_MSR, (tda9874a_mode) ? 0x03:0x02);
if(tda9874a_dic == 0x11) {
chip_write(chip, TDA9874A_FMMR, 0x80);
} else { /* dic == 0x07 */
chip_cmd(chip,"tda9874_modelist",&tda9874a_modelist[tda9874a_STD].cmd);
chip_write(chip, TDA9874A_FMMR, 0x00);
}
chip_write(chip, TDA9874A_C1OLAR, 0x00); /* 0 dB */
chip_write(chip, TDA9874A_C2OLAR, 0x00); /* 0 dB */
chip_write(chip, TDA9874A_NCONR, tda9874a_NCONR);
chip_write(chip, TDA9874A_NOLAR, 0x00); /* 0 dB */
/* Note: If signal quality is poor you may want to change NICAM */
/* error limit registers (NLELR and NUELR) to some greater values. */
/* Then the sound would remain stereo, but won't be so clear. */
chip_write(chip, TDA9874A_NLELR, 0x14); /* default */
chip_write(chip, TDA9874A_NUELR, 0x50); /* default */
if(tda9874a_dic == 0x11) {
chip_write(chip, TDA9874A_AMCONR, 0xf9);
chip_write(chip, TDA9874A_SDACOSR, (tda9874a_mode) ? 0x81:0x80);
chip_write(chip, TDA9874A_AOSR, 0x80);
chip_write(chip, TDA9874A_MDACOSR, (tda9874a_mode) ? 0x82:0x80);
chip_write(chip, TDA9874A_ESP, tda9874a_ESP);
} else { /* dic == 0x07 */
chip_write(chip, TDA9874A_AMCONR, 0xfb);
chip_write(chip, TDA9874A_SDACOSR, (tda9874a_mode) ? 0x81:0x80);
chip_write(chip, TDA9874A_AOSR, 0x00); /* or 0x10 */
}
v4l2_dbg(1, debug, sd, "tda9874a_setup(): %s [0x%02X].\n",
tda9874a_modelist[tda9874a_STD].name,tda9874a_STD);
return 1;
}
static int tda9874a_getmode(struct CHIPSTATE *chip)
{
struct v4l2_subdev *sd = &chip->sd;
int dsr,nsr,mode;
int necr; /* just for debugging */
mode = V4L2_TUNER_MODE_MONO;
if(-1 == (dsr = chip_read2(chip,TDA9874A_DSR)))
return mode;
if(-1 == (nsr = chip_read2(chip,TDA9874A_NSR)))
return mode;
if(-1 == (necr = chip_read2(chip,TDA9874A_NECR)))
return mode;
/* need to store dsr/nsr somewhere */
chip->shadow.bytes[MAXREGS-2] = dsr;
chip->shadow.bytes[MAXREGS-1] = nsr;
if(tda9874a_mode) {
/* Note: DSR.RSSF and DSR.AMSTAT bits are also checked.
* If NICAM auto-muting is enabled, DSR.AMSTAT=1 indicates
* that sound has (temporarily) switched from NICAM to
* mono FM (or AM) on 1st sound carrier due to high NICAM bit
* error count. So in fact there is no stereo in this case :-(
* But changing the mode to V4L2_TUNER_MODE_MONO would switch
* external 4052 multiplexer in audio_hook().
*/
if(nsr & 0x02) /* NSR.S/MB=1 */
mode |= V4L2_TUNER_MODE_STEREO;
if(nsr & 0x01) /* NSR.D/SB=1 */
mode |= V4L2_TUNER_MODE_LANG1 | V4L2_TUNER_MODE_LANG2;
} else {
if(dsr & 0x02) /* DSR.IDSTE=1 */
mode |= V4L2_TUNER_MODE_STEREO;
if(dsr & 0x04) /* DSR.IDDUA=1 */
mode |= V4L2_TUNER_MODE_LANG1 | V4L2_TUNER_MODE_LANG2;
}
v4l2_dbg(1, debug, sd, "tda9874a_getmode(): DSR=0x%X, NSR=0x%X, NECR=0x%X, return: %d.\n",
dsr, nsr, necr, mode);
return mode;
}
static void tda9874a_setmode(struct CHIPSTATE *chip, int mode)
{
struct v4l2_subdev *sd = &chip->sd;
/* Disable/enable NICAM auto-muting (based on DSR.RSSF status bit). */
/* If auto-muting is disabled, we can hear a signal of degrading quality. */
if (tda9874a_mode) {
if(chip->shadow.bytes[MAXREGS-2] & 0x20) /* DSR.RSSF=1 */
tda9874a_NCONR &= 0xfe; /* enable */
else
tda9874a_NCONR |= 0x01; /* disable */
chip_write(chip, TDA9874A_NCONR, tda9874a_NCONR);
}
/* Note: TDA9874A supports automatic FM dematrixing (FMMR register)
* and has auto-select function for audio output (AOSR register).
* Old TDA9874H doesn't support these features.
* TDA9874A also has additional mono output pin (OUTM), which
* on same (all?) tv-cards is not used, anyway (as well as MONOIN).
*/
if(tda9874a_dic == 0x11) {
int aosr = 0x80;
int mdacosr = (tda9874a_mode) ? 0x82:0x80;
switch(mode) {
case V4L2_TUNER_MODE_MONO:
case V4L2_TUNER_MODE_STEREO:
break;
case V4L2_TUNER_MODE_LANG1:
aosr = 0x80; /* auto-select, dual A/A */
mdacosr = (tda9874a_mode) ? 0x82:0x80;
break;
case V4L2_TUNER_MODE_LANG2:
aosr = 0xa0; /* auto-select, dual B/B */
mdacosr = (tda9874a_mode) ? 0x83:0x81;
break;
default:
chip->mode = 0;
return;
}
chip_write(chip, TDA9874A_AOSR, aosr);
chip_write(chip, TDA9874A_MDACOSR, mdacosr);
v4l2_dbg(1, debug, sd, "tda9874a_setmode(): req. mode %d; AOSR=0x%X, MDACOSR=0x%X.\n",
mode, aosr, mdacosr);
} else { /* dic == 0x07 */
int fmmr,aosr;
switch(mode) {
case V4L2_TUNER_MODE_MONO:
fmmr = 0x00; /* mono */
aosr = 0x10; /* A/A */
break;
case V4L2_TUNER_MODE_STEREO:
if(tda9874a_mode) {
fmmr = 0x00;
aosr = 0x00; /* handled by NICAM auto-mute */
} else {
fmmr = (tda9874a_ESP == 1) ? 0x05 : 0x04; /* stereo */
aosr = 0x00;
}
break;
case V4L2_TUNER_MODE_LANG1:
fmmr = 0x02; /* dual */
aosr = 0x10; /* dual A/A */
break;
case V4L2_TUNER_MODE_LANG2:
fmmr = 0x02; /* dual */
aosr = 0x20; /* dual B/B */
break;
default:
chip->mode = 0;
return;
}
chip_write(chip, TDA9874A_FMMR, fmmr);
chip_write(chip, TDA9874A_AOSR, aosr);
v4l2_dbg(1, debug, sd, "tda9874a_setmode(): req. mode %d; FMMR=0x%X, AOSR=0x%X.\n",
mode, fmmr, aosr);
}
}
static int tda9874a_checkit(struct CHIPSTATE *chip)
{
struct v4l2_subdev *sd = &chip->sd;
int dic,sic; /* device id. and software id. codes */
if(-1 == (dic = chip_read2(chip,TDA9874A_DIC)))
return 0;
if(-1 == (sic = chip_read2(chip,TDA9874A_SIC)))
return 0;
v4l2_dbg(1, debug, sd, "tda9874a_checkit(): DIC=0x%X, SIC=0x%X.\n", dic, sic);
if((dic == 0x11)||(dic == 0x07)) {
v4l2_info(sd, "found tda9874%s.\n", (dic == 0x11) ? "a" : "h");
tda9874a_dic = dic; /* remember device id. */
return 1;
}
return 0; /* not found */
}
static int tda9874a_initialize(struct CHIPSTATE *chip)
{
if (tda9874a_SIF > 2)
tda9874a_SIF = 1;
if (tda9874a_STD >= ARRAY_SIZE(tda9874a_modelist))
tda9874a_STD = 0;
if(tda9874a_AMSEL > 1)
tda9874a_AMSEL = 0;
if(tda9874a_SIF == 1)
tda9874a_GCONR = 0xc0; /* sound IF input 1 */
else
tda9874a_GCONR = 0xc1; /* sound IF input 2 */
tda9874a_ESP = tda9874a_STD;
tda9874a_mode = (tda9874a_STD < 5) ? 0 : 1;
if(tda9874a_AMSEL == 0)
tda9874a_NCONR = 0x01; /* auto-mute: analog mono input */
else
tda9874a_NCONR = 0x05; /* auto-mute: 1st carrier FM or AM */
tda9874a_setup(chip);
return 0;
}
/* ---------------------------------------------------------------------- */
/* audio chip description - defines+functions for tda9875 */
/* The TDA9875 is made by Philips Semiconductor
* http://www.semiconductors.philips.com
* TDA9875: I2C-bus controlled DSP audio processor, FM demodulator
*
*/
/* subaddresses for TDA9875 */
#define TDA9875_MUT 0x12 /*General mute (value --> 0b11001100*/
#define TDA9875_CFG 0x01 /* Config register (value --> 0b00000000 */
#define TDA9875_DACOS 0x13 /*DAC i/o select (ADC) 0b0000100*/
#define TDA9875_LOSR 0x16 /*Line output select regirter 0b0100 0001*/
#define TDA9875_CH1V 0x0c /*Channel 1 volume (mute)*/
#define TDA9875_CH2V 0x0d /*Channel 2 volume (mute)*/
#define TDA9875_SC1 0x14 /*SCART 1 in (mono)*/
#define TDA9875_SC2 0x15 /*SCART 2 in (mono)*/
#define TDA9875_ADCIS 0x17 /*ADC input select (mono) 0b0110 000*/
#define TDA9875_AER 0x19 /*Audio effect (AVL+Pseudo) 0b0000 0110*/
#define TDA9875_MCS 0x18 /*Main channel select (DAC) 0b0000100*/
#define TDA9875_MVL 0x1a /* Main volume gauche */
#define TDA9875_MVR 0x1b /* Main volume droite */
#define TDA9875_MBA 0x1d /* Main Basse */
#define TDA9875_MTR 0x1e /* Main treble */
#define TDA9875_ACS 0x1f /* Auxiliary channel select (FM) 0b0000000*/
#define TDA9875_AVL 0x20 /* Auxiliary volume gauche */
#define TDA9875_AVR 0x21 /* Auxiliary volume droite */
#define TDA9875_ABA 0x22 /* Auxiliary Basse */
#define TDA9875_ATR 0x23 /* Auxiliary treble */
#define TDA9875_MSR 0x02 /* Monitor select register */
#define TDA9875_C1MSB 0x03 /* Carrier 1 (FM) frequency register MSB */
#define TDA9875_C1MIB 0x04 /* Carrier 1 (FM) frequency register (16-8]b */
#define TDA9875_C1LSB 0x05 /* Carrier 1 (FM) frequency register LSB */
#define TDA9875_C2MSB 0x06 /* Carrier 2 (nicam) frequency register MSB */
#define TDA9875_C2MIB 0x07 /* Carrier 2 (nicam) frequency register (16-8]b */
#define TDA9875_C2LSB 0x08 /* Carrier 2 (nicam) frequency register LSB */
#define TDA9875_DCR 0x09 /* Demodulateur configuration regirter*/
#define TDA9875_DEEM 0x0a /* FM de-emphasis regirter*/
#define TDA9875_FMAT 0x0b /* FM Matrix regirter*/
/* values */
#define TDA9875_MUTE_ON 0xff /* general mute */
#define TDA9875_MUTE_OFF 0xcc /* general no mute */
static int tda9875_initialize(struct CHIPSTATE *chip)
{
chip_write(chip, TDA9875_CFG, 0xd0); /*reg de config 0 (reset)*/
chip_write(chip, TDA9875_MSR, 0x03); /* Monitor 0b00000XXX*/
chip_write(chip, TDA9875_C1MSB, 0x00); /*Car1(FM) MSB XMHz*/
chip_write(chip, TDA9875_C1MIB, 0x00); /*Car1(FM) MIB XMHz*/
chip_write(chip, TDA9875_C1LSB, 0x00); /*Car1(FM) LSB XMHz*/
chip_write(chip, TDA9875_C2MSB, 0x00); /*Car2(NICAM) MSB XMHz*/
chip_write(chip, TDA9875_C2MIB, 0x00); /*Car2(NICAM) MIB XMHz*/
chip_write(chip, TDA9875_C2LSB, 0x00); /*Car2(NICAM) LSB XMHz*/
chip_write(chip, TDA9875_DCR, 0x00); /*Demod config 0x00*/
chip_write(chip, TDA9875_DEEM, 0x44); /*DE-Emph 0b0100 0100*/
chip_write(chip, TDA9875_FMAT, 0x00); /*FM Matrix reg 0x00*/
chip_write(chip, TDA9875_SC1, 0x00); /* SCART 1 (SC1)*/
chip_write(chip, TDA9875_SC2, 0x01); /* SCART 2 (sc2)*/
chip_write(chip, TDA9875_CH1V, 0x10); /* Channel volume 1 mute*/
chip_write(chip, TDA9875_CH2V, 0x10); /* Channel volume 2 mute */
chip_write(chip, TDA9875_DACOS, 0x02); /* sig DAC i/o(in:nicam)*/
chip_write(chip, TDA9875_ADCIS, 0x6f); /* sig ADC input(in:mono)*/
chip_write(chip, TDA9875_LOSR, 0x00); /* line out (in:mono)*/
chip_write(chip, TDA9875_AER, 0x00); /*06 Effect (AVL+PSEUDO) */
chip_write(chip, TDA9875_MCS, 0x44); /* Main ch select (DAC) */
chip_write(chip, TDA9875_MVL, 0x03); /* Vol Main left 10dB */
chip_write(chip, TDA9875_MVR, 0x03); /* Vol Main right 10dB*/
chip_write(chip, TDA9875_MBA, 0x00); /* Main Bass Main 0dB*/
chip_write(chip, TDA9875_MTR, 0x00); /* Main Treble Main 0dB*/
chip_write(chip, TDA9875_ACS, 0x44); /* Aux chan select (dac)*/
chip_write(chip, TDA9875_AVL, 0x00); /* Vol Aux left 0dB*/
chip_write(chip, TDA9875_AVR, 0x00); /* Vol Aux right 0dB*/
chip_write(chip, TDA9875_ABA, 0x00); /* Aux Bass Main 0dB*/
chip_write(chip, TDA9875_ATR, 0x00); /* Aux Aigus Main 0dB*/
chip_write(chip, TDA9875_MUT, 0xcc); /* General mute */
return 0;
}
static int tda9875_volume(int val) { return (unsigned char)(val / 602 - 84); }
static int tda9875_bass(int val) { return (unsigned char)(max(-12, val / 2115 - 15)); }
static int tda9875_treble(int val) { return (unsigned char)(val / 2622 - 12); }
/* ----------------------------------------------------------------------- */
/* *********************** *
* i2c interface functions *
* *********************** */
static int tda9875_checkit(struct CHIPSTATE *chip)
{
struct v4l2_subdev *sd = &chip->sd;
int dic, rev;
dic = chip_read2(chip, 254);
rev = chip_read2(chip, 255);
if (dic == 0 || dic == 2) { /* tda9875 and tda9875A */
v4l2_info(sd, "found tda9875%s rev. %d.\n",
dic == 0 ? "" : "A", rev);
return 1;
}
return 0;
}
/* ---------------------------------------------------------------------- */
/* audio chip descriptions - defines+functions for tea6420 */
#define TEA6300_VL 0x00 /* volume left */
#define TEA6300_VR 0x01 /* volume right */
#define TEA6300_BA 0x02 /* bass */
#define TEA6300_TR 0x03 /* treble */
#define TEA6300_FA 0x04 /* fader control */
#define TEA6300_S 0x05 /* switch register */
/* values for those registers: */
#define TEA6300_S_SA 0x01 /* stereo A input */
#define TEA6300_S_SB 0x02 /* stereo B */
#define TEA6300_S_SC 0x04 /* stereo C */
#define TEA6300_S_GMU 0x80 /* general mute */
#define TEA6320_V 0x00 /* volume (0-5)/loudness off (6)/zero crossing mute(7) */
#define TEA6320_FFR 0x01 /* fader front right (0-5) */
#define TEA6320_FFL 0x02 /* fader front left (0-5) */
#define TEA6320_FRR 0x03 /* fader rear right (0-5) */
#define TEA6320_FRL 0x04 /* fader rear left (0-5) */
#define TEA6320_BA 0x05 /* bass (0-4) */
#define TEA6320_TR 0x06 /* treble (0-4) */
#define TEA6320_S 0x07 /* switch register */
/* values for those registers: */
#define TEA6320_S_SA 0x07 /* stereo A input */
#define TEA6320_S_SB 0x06 /* stereo B */
#define TEA6320_S_SC 0x05 /* stereo C */
#define TEA6320_S_SD 0x04 /* stereo D */
#define TEA6320_S_GMU 0x80 /* general mute */
#define TEA6420_S_SA 0x00 /* stereo A input */
#define TEA6420_S_SB 0x01 /* stereo B */
#define TEA6420_S_SC 0x02 /* stereo C */
#define TEA6420_S_SD 0x03 /* stereo D */
#define TEA6420_S_SE 0x04 /* stereo E */
#define TEA6420_S_GMU 0x05 /* general mute */
static int tea6300_shift10(int val) { return val >> 10; }
static int tea6300_shift12(int val) { return val >> 12; }
/* Assumes 16bit input (values 0x3f to 0x0c are unique, values less than */
/* 0x0c mirror those immediately higher) */
static int tea6320_volume(int val) { return (val / (65535/(63-12)) + 12) & 0x3f; }
static int tea6320_shift11(int val) { return val >> 11; }
static int tea6320_initialize(struct CHIPSTATE * chip)
{
chip_write(chip, TEA6320_FFR, 0x3f);
chip_write(chip, TEA6320_FFL, 0x3f);
chip_write(chip, TEA6320_FRR, 0x3f);
chip_write(chip, TEA6320_FRL, 0x3f);
return 0;
}
/* ---------------------------------------------------------------------- */
/* audio chip descriptions - defines+functions for tda8425 */
#define TDA8425_VL 0x00 /* volume left */
#define TDA8425_VR 0x01 /* volume right */
#define TDA8425_BA 0x02 /* bass */
#define TDA8425_TR 0x03 /* treble */
#define TDA8425_S1 0x08 /* switch functions */
/* values for those registers: */
#define TDA8425_S1_OFF 0xEE /* audio off (mute on) */
#define TDA8425_S1_CH1 0xCE /* audio channel 1 (mute off) - "linear stereo" mode */
#define TDA8425_S1_CH2 0xCF /* audio channel 2 (mute off) - "linear stereo" mode */
#define TDA8425_S1_MU 0x20 /* mute bit */
#define TDA8425_S1_STEREO 0x18 /* stereo bits */
#define TDA8425_S1_STEREO_SPATIAL 0x18 /* spatial stereo */
#define TDA8425_S1_STEREO_LINEAR 0x08 /* linear stereo */
#define TDA8425_S1_STEREO_PSEUDO 0x10 /* pseudo stereo */
#define TDA8425_S1_STEREO_MONO 0x00 /* forced mono */
#define TDA8425_S1_ML 0x06 /* language selector */
#define TDA8425_S1_ML_SOUND_A 0x02 /* sound a */
#define TDA8425_S1_ML_SOUND_B 0x04 /* sound b */
#define TDA8425_S1_ML_STEREO 0x06 /* stereo */
#define TDA8425_S1_IS 0x01 /* channel selector */
static int tda8425_shift10(int val) { return (val >> 10) | 0xc0; }
static int tda8425_shift12(int val) { return (val >> 12) | 0xf0; }
static void tda8425_setmode(struct CHIPSTATE *chip, int mode)
{
int s1 = chip->shadow.bytes[TDA8425_S1+1] & 0xe1;
if (mode & V4L2_TUNER_MODE_LANG1) {
s1 |= TDA8425_S1_ML_SOUND_A;
s1 |= TDA8425_S1_STEREO_PSEUDO;
} else if (mode & V4L2_TUNER_MODE_LANG2) {
s1 |= TDA8425_S1_ML_SOUND_B;
s1 |= TDA8425_S1_STEREO_PSEUDO;
} else {
s1 |= TDA8425_S1_ML_STEREO;
if (mode & V4L2_TUNER_MODE_MONO)
s1 |= TDA8425_S1_STEREO_MONO;
if (mode & V4L2_TUNER_MODE_STEREO)
s1 |= TDA8425_S1_STEREO_SPATIAL;
}
chip_write(chip,TDA8425_S1,s1);
}
/* ---------------------------------------------------------------------- */
/* audio chip descriptions - defines+functions for pic16c54 (PV951) */
/* the registers of 16C54, I2C sub address. */
#define PIC16C54_REG_KEY_CODE 0x01 /* Not use. */
#define PIC16C54_REG_MISC 0x02
/* bit definition of the RESET register, I2C data. */
#define PIC16C54_MISC_RESET_REMOTE_CTL 0x01 /* bit 0, Reset to receive the key */
/* code of remote controller */
#define PIC16C54_MISC_MTS_MAIN 0x02 /* bit 1 */
#define PIC16C54_MISC_MTS_SAP 0x04 /* bit 2 */
#define PIC16C54_MISC_MTS_BOTH 0x08 /* bit 3 */
#define PIC16C54_MISC_SND_MUTE 0x10 /* bit 4, Mute Audio(Line-in and Tuner) */
#define PIC16C54_MISC_SND_NOTMUTE 0x20 /* bit 5 */
#define PIC16C54_MISC_SWITCH_TUNER 0x40 /* bit 6 , Switch to Line-in */
#define PIC16C54_MISC_SWITCH_LINE 0x80 /* bit 7 , Switch to Tuner */
/* ---------------------------------------------------------------------- */
/* audio chip descriptions - defines+functions for TA8874Z */
/* write 1st byte */
#define TA8874Z_LED_STE 0x80
#define TA8874Z_LED_BIL 0x40
#define TA8874Z_LED_EXT 0x20
#define TA8874Z_MONO_SET 0x10
#define TA8874Z_MUTE 0x08
#define TA8874Z_F_MONO 0x04
#define TA8874Z_MODE_SUB 0x02
#define TA8874Z_MODE_MAIN 0x01
/* write 2nd byte */
/*#define TA8874Z_TI 0x80 */ /* test mode */
#define TA8874Z_SEPARATION 0x3f
#define TA8874Z_SEPARATION_DEFAULT 0x10
/* read */
#define TA8874Z_B1 0x80
#define TA8874Z_B0 0x40
#define TA8874Z_CHAG_FLAG 0x20
/*
* B1 B0
* mono L H
* stereo L L
* BIL H L
*/
static int ta8874z_getmode(struct CHIPSTATE *chip)
{
int val, mode;
val = chip_read(chip);
mode = V4L2_TUNER_MODE_MONO;
if (val & TA8874Z_B1){
mode |= V4L2_TUNER_MODE_LANG1 | V4L2_TUNER_MODE_LANG2;
}else if (!(val & TA8874Z_B0)){
mode |= V4L2_TUNER_MODE_STEREO;
}
/* v4l_dbg(1, debug, chip->c, "ta8874z_getmode(): raw chip read: 0x%02x, return: 0x%02x\n", val, mode); */
return mode;
}
static audiocmd ta8874z_stereo = { 2, {0, TA8874Z_SEPARATION_DEFAULT}};
static audiocmd ta8874z_mono = {2, { TA8874Z_MONO_SET, TA8874Z_SEPARATION_DEFAULT}};
static audiocmd ta8874z_main = {2, { 0, TA8874Z_SEPARATION_DEFAULT}};
static audiocmd ta8874z_sub = {2, { TA8874Z_MODE_SUB, TA8874Z_SEPARATION_DEFAULT}};
static void ta8874z_setmode(struct CHIPSTATE *chip, int mode)
{
struct v4l2_subdev *sd = &chip->sd;
int update = 1;
audiocmd *t = NULL;
v4l2_dbg(1, debug, sd, "ta8874z_setmode(): mode: 0x%02x\n", mode);
switch(mode){
case V4L2_TUNER_MODE_MONO:
t = &ta8874z_mono;
break;
case V4L2_TUNER_MODE_STEREO:
t = &ta8874z_stereo;
break;
case V4L2_TUNER_MODE_LANG1:
t = &ta8874z_main;
break;
case V4L2_TUNER_MODE_LANG2:
t = &ta8874z_sub;
break;
default:
update = 0;
}
if(update)
chip_cmd(chip, "TA8874Z", t);
}
static int ta8874z_checkit(struct CHIPSTATE *chip)
{
int rc;
rc = chip_read(chip);
return ((rc & 0x1f) == 0x1f) ? 1 : 0;
}
/* ---------------------------------------------------------------------- */
/* audio chip descriptions - struct CHIPDESC */
/* insmod options to enable/disable individual audio chips */
static int tda8425 = 1;
static int tda9840 = 1;
static int tda9850 = 1;
static int tda9855 = 1;
static int tda9873 = 1;
static int tda9874a = 1;
static int tda9875 = 1;
static int tea6300; /* default 0 - address clash with msp34xx */
static int tea6320; /* default 0 - address clash with msp34xx */
static int tea6420 = 1;
static int pic16c54 = 1;
static int ta8874z; /* default 0 - address clash with tda9840 */
module_param(tda8425, int, 0444);
module_param(tda9840, int, 0444);
module_param(tda9850, int, 0444);
module_param(tda9855, int, 0444);
module_param(tda9873, int, 0444);
module_param(tda9874a, int, 0444);
module_param(tda9875, int, 0444);
module_param(tea6300, int, 0444);
module_param(tea6320, int, 0444);
module_param(tea6420, int, 0444);
module_param(pic16c54, int, 0444);
module_param(ta8874z, int, 0444);
static struct CHIPDESC chiplist[] = {
{
.name = "tda9840",
.insmodopt = &tda9840,
.addr_lo = I2C_ADDR_TDA9840 >> 1,
.addr_hi = I2C_ADDR_TDA9840 >> 1,
.registers = 5,
.flags = CHIP_NEED_CHECKMODE,
/* callbacks */
.checkit = tda9840_checkit,
.getmode = tda9840_getmode,
.setmode = tda9840_setmode,
.init = { 2, { TDA9840_TEST, TDA9840_TEST_INT1SN
/* ,TDA9840_SW, TDA9840_MONO */} }
},
{
.name = "tda9873h",
.insmodopt = &tda9873,
.addr_lo = I2C_ADDR_TDA985x_L >> 1,
.addr_hi = I2C_ADDR_TDA985x_H >> 1,
.registers = 3,
.flags = CHIP_HAS_INPUTSEL | CHIP_NEED_CHECKMODE,
/* callbacks */
.checkit = tda9873_checkit,
.getmode = tda9873_getmode,
.setmode = tda9873_setmode,
.init = { 4, { TDA9873_SW, 0xa4, 0x06, 0x03 } },
.inputreg = TDA9873_SW,
.inputmute = TDA9873_MUTE | TDA9873_AUTOMUTE,
.inputmap = {0xa0, 0xa2, 0xa0, 0xa0},
.inputmask = TDA9873_INP_MASK|TDA9873_MUTE|TDA9873_AUTOMUTE,
},
{
.name = "tda9874h/a",
.insmodopt = &tda9874a,
.addr_lo = I2C_ADDR_TDA9874 >> 1,
.addr_hi = I2C_ADDR_TDA9874 >> 1,
.flags = CHIP_NEED_CHECKMODE,
/* callbacks */
.initialize = tda9874a_initialize,
.checkit = tda9874a_checkit,
.getmode = tda9874a_getmode,
.setmode = tda9874a_setmode,
},
{
.name = "tda9875",
.insmodopt = &tda9875,
.addr_lo = I2C_ADDR_TDA9875 >> 1,
.addr_hi = I2C_ADDR_TDA9875 >> 1,
.flags = CHIP_HAS_VOLUME | CHIP_HAS_BASSTREBLE,
/* callbacks */
.initialize = tda9875_initialize,
.checkit = tda9875_checkit,
.volfunc = tda9875_volume,
.bassfunc = tda9875_bass,
.treblefunc = tda9875_treble,
.leftreg = TDA9875_MVL,
.rightreg = TDA9875_MVR,
.bassreg = TDA9875_MBA,
.treblereg = TDA9875_MTR,
.leftinit = 58880,
.rightinit = 58880,
},
{
.name = "tda9850",
.insmodopt = &tda9850,
.addr_lo = I2C_ADDR_TDA985x_L >> 1,
.addr_hi = I2C_ADDR_TDA985x_H >> 1,
.registers = 11,
.getmode = tda985x_getmode,
.setmode = tda985x_setmode,
.init = { 8, { TDA9850_C4, 0x08, 0x08, TDA985x_STEREO, 0x07, 0x10, 0x10, 0x03 } }
},
{
.name = "tda9855",
.insmodopt = &tda9855,
.addr_lo = I2C_ADDR_TDA985x_L >> 1,
.addr_hi = I2C_ADDR_TDA985x_H >> 1,
.registers = 11,
.flags = CHIP_HAS_VOLUME | CHIP_HAS_BASSTREBLE,
.leftreg = TDA9855_VL,
.rightreg = TDA9855_VR,
.bassreg = TDA9855_BA,
.treblereg = TDA9855_TR,
/* callbacks */
.volfunc = tda9855_volume,
.bassfunc = tda9855_bass,
.treblefunc = tda9855_treble,
.getmode = tda985x_getmode,
.setmode = tda985x_setmode,
.init = { 12, { 0, 0x6f, 0x6f, 0x0e, 0x07<<1, 0x8<<2,
TDA9855_MUTE | TDA9855_AVL | TDA9855_LOUD | TDA9855_INT,
TDA985x_STEREO | TDA9855_LINEAR | TDA9855_TZCM | TDA9855_VZCM,
0x07, 0x10, 0x10, 0x03 }}
},
{
.name = "tea6300",
.insmodopt = &tea6300,
.addr_lo = I2C_ADDR_TEA6300 >> 1,
.addr_hi = I2C_ADDR_TEA6300 >> 1,
.registers = 6,
.flags = CHIP_HAS_VOLUME | CHIP_HAS_BASSTREBLE | CHIP_HAS_INPUTSEL,
.leftreg = TEA6300_VR,
.rightreg = TEA6300_VL,
.bassreg = TEA6300_BA,
.treblereg = TEA6300_TR,
/* callbacks */
.volfunc = tea6300_shift10,
.bassfunc = tea6300_shift12,
.treblefunc = tea6300_shift12,
.inputreg = TEA6300_S,
.inputmap = { TEA6300_S_SA, TEA6300_S_SB, TEA6300_S_SC },
.inputmute = TEA6300_S_GMU,
},
{
.name = "tea6320",
.insmodopt = &tea6320,
.addr_lo = I2C_ADDR_TEA6300 >> 1,
.addr_hi = I2C_ADDR_TEA6300 >> 1,
.registers = 8,
.flags = CHIP_HAS_VOLUME | CHIP_HAS_BASSTREBLE | CHIP_HAS_INPUTSEL,
.leftreg = TEA6320_V,
.rightreg = TEA6320_V,
.bassreg = TEA6320_BA,
.treblereg = TEA6320_TR,
/* callbacks */
.initialize = tea6320_initialize,
.volfunc = tea6320_volume,
.bassfunc = tea6320_shift11,
.treblefunc = tea6320_shift11,
.inputreg = TEA6320_S,
.inputmap = { TEA6320_S_SA, TEA6420_S_SB, TEA6300_S_SC, TEA6320_S_SD },
.inputmute = TEA6300_S_GMU,
},
{
.name = "tea6420",
.insmodopt = &tea6420,
.addr_lo = I2C_ADDR_TEA6420 >> 1,
.addr_hi = I2C_ADDR_TEA6420 >> 1,
.registers = 1,
.flags = CHIP_HAS_INPUTSEL,
.inputreg = -1,
.inputmap = { TEA6420_S_SA, TEA6420_S_SB, TEA6420_S_SC },
.inputmute = TEA6300_S_GMU,
},
{
.name = "tda8425",
.insmodopt = &tda8425,
.addr_lo = I2C_ADDR_TDA8425 >> 1,
.addr_hi = I2C_ADDR_TDA8425 >> 1,
.registers = 9,
.flags = CHIP_HAS_VOLUME | CHIP_HAS_BASSTREBLE | CHIP_HAS_INPUTSEL,
.leftreg = TDA8425_VL,
.rightreg = TDA8425_VR,
.bassreg = TDA8425_BA,
.treblereg = TDA8425_TR,
/* callbacks */
.volfunc = tda8425_shift10,
.bassfunc = tda8425_shift12,
.treblefunc = tda8425_shift12,
.setmode = tda8425_setmode,
.inputreg = TDA8425_S1,
.inputmap = { TDA8425_S1_CH1, TDA8425_S1_CH1, TDA8425_S1_CH1 },
.inputmute = TDA8425_S1_OFF,
},
{
.name = "pic16c54 (PV951)",
.insmodopt = &pic16c54,
.addr_lo = I2C_ADDR_PIC16C54 >> 1,
.addr_hi = I2C_ADDR_PIC16C54>> 1,
.registers = 2,
.flags = CHIP_HAS_INPUTSEL,
.inputreg = PIC16C54_REG_MISC,
.inputmap = {PIC16C54_MISC_SND_NOTMUTE|PIC16C54_MISC_SWITCH_TUNER,
PIC16C54_MISC_SND_NOTMUTE|PIC16C54_MISC_SWITCH_LINE,
PIC16C54_MISC_SND_NOTMUTE|PIC16C54_MISC_SWITCH_LINE,
PIC16C54_MISC_SND_MUTE},
.inputmute = PIC16C54_MISC_SND_MUTE,
},
{
.name = "ta8874z",
.checkit = ta8874z_checkit,
.insmodopt = &ta8874z,
.addr_lo = I2C_ADDR_TDA9840 >> 1,
.addr_hi = I2C_ADDR_TDA9840 >> 1,
.registers = 2,
.flags = CHIP_NEED_CHECKMODE,
/* callbacks */
.getmode = ta8874z_getmode,
.setmode = ta8874z_setmode,
.init = {2, { TA8874Z_MONO_SET, TA8874Z_SEPARATION_DEFAULT}},
},
{ .name = NULL } /* EOF */
};
/* ---------------------------------------------------------------------- */
static int tvaudio_g_ctrl(struct v4l2_subdev *sd,
struct v4l2_control *ctrl)
{
struct CHIPSTATE *chip = to_state(sd);
struct CHIPDESC *desc = chip->desc;
switch (ctrl->id) {
case V4L2_CID_AUDIO_MUTE:
if (!(desc->flags & CHIP_HAS_INPUTSEL))
break;
ctrl->value=chip->muted;
return 0;
case V4L2_CID_AUDIO_VOLUME:
if (!(desc->flags & CHIP_HAS_VOLUME))
break;
ctrl->value = max(chip->left,chip->right);
return 0;
case V4L2_CID_AUDIO_BALANCE:
{
int volume;
if (!(desc->flags & CHIP_HAS_VOLUME))
break;
volume = max(chip->left,chip->right);
if (volume)
ctrl->value=(32768*min(chip->left,chip->right))/volume;
else
ctrl->value=32768;
return 0;
}
case V4L2_CID_AUDIO_BASS:
if (!(desc->flags & CHIP_HAS_BASSTREBLE))
break;
ctrl->value = chip->bass;
return 0;
case V4L2_CID_AUDIO_TREBLE:
if (!(desc->flags & CHIP_HAS_BASSTREBLE))
break;
ctrl->value = chip->treble;
return 0;
}
return -EINVAL;
}
static int tvaudio_s_ctrl(struct v4l2_subdev *sd,
struct v4l2_control *ctrl)
{
struct CHIPSTATE *chip = to_state(sd);
struct CHIPDESC *desc = chip->desc;
switch (ctrl->id) {
case V4L2_CID_AUDIO_MUTE:
if (!(desc->flags & CHIP_HAS_INPUTSEL))
break;
if (ctrl->value < 0 || ctrl->value >= 2)
return -ERANGE;
chip->muted = ctrl->value;
if (chip->muted)
chip_write_masked(chip,desc->inputreg,desc->inputmute,desc->inputmask);
else
chip_write_masked(chip,desc->inputreg,
desc->inputmap[chip->input],desc->inputmask);
return 0;
case V4L2_CID_AUDIO_VOLUME:
{
int volume,balance;
if (!(desc->flags & CHIP_HAS_VOLUME))
break;
volume = max(chip->left,chip->right);
if (volume)
balance=(32768*min(chip->left,chip->right))/volume;
else
balance=32768;
volume=ctrl->value;
chip->left = (min(65536 - balance,32768) * volume) / 32768;
chip->right = (min(balance,volume *(__u16)32768)) / 32768;
chip_write(chip,desc->leftreg,desc->volfunc(chip->left));
chip_write(chip,desc->rightreg,desc->volfunc(chip->right));
return 0;
}
case V4L2_CID_AUDIO_BALANCE:
{
int volume, balance;
if (!(desc->flags & CHIP_HAS_VOLUME))
break;
volume = max(chip->left, chip->right);
balance = ctrl->value;
chip->left = (min(65536 - balance, 32768) * volume) / 32768;
chip->right = (min(balance, volume * (__u16)32768)) / 32768;
chip_write(chip, desc->leftreg, desc->volfunc(chip->left));
chip_write(chip, desc->rightreg, desc->volfunc(chip->right));
return 0;
}
case V4L2_CID_AUDIO_BASS:
if (!(desc->flags & CHIP_HAS_BASSTREBLE))
break;
chip->bass = ctrl->value;
chip_write(chip,desc->bassreg,desc->bassfunc(chip->bass));
return 0;
case V4L2_CID_AUDIO_TREBLE:
if (!(desc->flags & CHIP_HAS_BASSTREBLE))
break;
chip->treble = ctrl->value;
chip_write(chip,desc->treblereg,desc->treblefunc(chip->treble));
return 0;
}
return -EINVAL;
}
/* ---------------------------------------------------------------------- */
/* video4linux interface */
static int tvaudio_s_radio(struct v4l2_subdev *sd)
{
struct CHIPSTATE *chip = to_state(sd);
chip->radio = 1;
chip->watch_stereo = 0;
/* del_timer(&chip->wt); */
return 0;
}
static int tvaudio_queryctrl(struct v4l2_subdev *sd, struct v4l2_queryctrl *qc)
{
struct CHIPSTATE *chip = to_state(sd);
struct CHIPDESC *desc = chip->desc;
switch (qc->id) {
case V4L2_CID_AUDIO_MUTE:
if (desc->flags & CHIP_HAS_INPUTSEL)
return v4l2_ctrl_query_fill(qc, 0, 1, 1, 0);
break;
case V4L2_CID_AUDIO_VOLUME:
if (desc->flags & CHIP_HAS_VOLUME)
return v4l2_ctrl_query_fill(qc, 0, 65535, 65535 / 100, 58880);
break;
case V4L2_CID_AUDIO_BALANCE:
if (desc->flags & CHIP_HAS_VOLUME)
return v4l2_ctrl_query_fill(qc, 0, 65535, 65535 / 100, 32768);
break;
case V4L2_CID_AUDIO_BASS:
case V4L2_CID_AUDIO_TREBLE:
if (desc->flags & CHIP_HAS_BASSTREBLE)
return v4l2_ctrl_query_fill(qc, 0, 65535, 65535 / 100, 32768);
break;
default:
break;
}
return -EINVAL;
}
static int tvaudio_s_routing(struct v4l2_subdev *sd,
u32 input, u32 output, u32 config)
{
struct CHIPSTATE *chip = to_state(sd);
struct CHIPDESC *desc = chip->desc;
if (!(desc->flags & CHIP_HAS_INPUTSEL))
return 0;
if (input >= 4)
return -EINVAL;
/* There are four inputs: tuner, radio, extern and intern. */
chip->input = input;
if (chip->muted)
return 0;
chip_write_masked(chip, desc->inputreg,
desc->inputmap[chip->input], desc->inputmask);
return 0;
}
static int tvaudio_s_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *vt)
{
struct CHIPSTATE *chip = to_state(sd);
struct CHIPDESC *desc = chip->desc;
int mode = 0;
if (!desc->setmode)
return 0;
if (chip->radio)
return 0;
switch (vt->audmode) {
case V4L2_TUNER_MODE_MONO:
case V4L2_TUNER_MODE_STEREO:
case V4L2_TUNER_MODE_LANG1:
case V4L2_TUNER_MODE_LANG2:
mode = vt->audmode;
break;
case V4L2_TUNER_MODE_LANG1_LANG2:
mode = V4L2_TUNER_MODE_STEREO;
break;
default:
return -EINVAL;
}
chip->audmode = vt->audmode;
if (mode) {
chip->watch_stereo = 0;
/* del_timer(&chip->wt); */
chip->mode = mode;
desc->setmode(chip, mode);
}
return 0;
}
static int tvaudio_g_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *vt)
{
struct CHIPSTATE *chip = to_state(sd);
struct CHIPDESC *desc = chip->desc;
int mode = V4L2_TUNER_MODE_MONO;
if (!desc->getmode)
return 0;
if (chip->radio)
return 0;
vt->audmode = chip->audmode;
vt->rxsubchans = 0;
vt->capability = V4L2_TUNER_CAP_STEREO |
V4L2_TUNER_CAP_LANG1 | V4L2_TUNER_CAP_LANG2;
mode = desc->getmode(chip);
if (mode & V4L2_TUNER_MODE_MONO)
vt->rxsubchans |= V4L2_TUNER_SUB_MONO;
if (mode & V4L2_TUNER_MODE_STEREO)
vt->rxsubchans |= V4L2_TUNER_SUB_STEREO;
/* Note: for SAP it should be mono/lang2 or stereo/lang2.
When this module is converted fully to v4l2, then this
should change for those chips that can detect SAP. */
if (mode & V4L2_TUNER_MODE_LANG1)
vt->rxsubchans = V4L2_TUNER_SUB_LANG1 |
V4L2_TUNER_SUB_LANG2;
return 0;
}
static int tvaudio_s_std(struct v4l2_subdev *sd, v4l2_std_id std)
{
struct CHIPSTATE *chip = to_state(sd);
chip->radio = 0;
return 0;
}
static int tvaudio_s_frequency(struct v4l2_subdev *sd, struct v4l2_frequency *freq)
{
struct CHIPSTATE *chip = to_state(sd);
struct CHIPDESC *desc = chip->desc;
chip->mode = 0; /* automatic */
/* For chips that provide getmode and setmode, and doesn't
automatically follows the stereo carrier, a kthread is
created to set the audio standard. In this case, when then
the video channel is changed, tvaudio starts on MONO mode.
After waiting for 2 seconds, the kernel thread is called,
to follow whatever audio standard is pointed by the
audio carrier.
*/
if (chip->thread) {
desc->setmode(chip, V4L2_TUNER_MODE_MONO);
if (chip->prevmode != V4L2_TUNER_MODE_MONO)
chip->prevmode = -1; /* reset previous mode */
mod_timer(&chip->wt, jiffies+msecs_to_jiffies(2000));
}
return 0;
}
static int tvaudio_g_chip_ident(struct v4l2_subdev *sd, struct v4l2_dbg_chip_ident *chip)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
return v4l2_chip_ident_i2c_client(client, chip, V4L2_IDENT_TVAUDIO, 0);
}
/* ----------------------------------------------------------------------- */
static const struct v4l2_subdev_core_ops tvaudio_core_ops = {
.g_chip_ident = tvaudio_g_chip_ident,
.queryctrl = tvaudio_queryctrl,
.g_ctrl = tvaudio_g_ctrl,
.s_ctrl = tvaudio_s_ctrl,
.s_std = tvaudio_s_std,
};
static const struct v4l2_subdev_tuner_ops tvaudio_tuner_ops = {
.s_radio = tvaudio_s_radio,
.s_frequency = tvaudio_s_frequency,
.s_tuner = tvaudio_s_tuner,
.g_tuner = tvaudio_g_tuner,
};
static const struct v4l2_subdev_audio_ops tvaudio_audio_ops = {
.s_routing = tvaudio_s_routing,
};
static const struct v4l2_subdev_ops tvaudio_ops = {
.core = &tvaudio_core_ops,
.tuner = &tvaudio_tuner_ops,
.audio = &tvaudio_audio_ops,
};
/* ----------------------------------------------------------------------- */
/* i2c registration */
static int tvaudio_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
struct CHIPSTATE *chip;
struct CHIPDESC *desc;
struct v4l2_subdev *sd;
if (debug) {
printk(KERN_INFO "tvaudio: TV audio decoder + audio/video mux driver\n");
printk(KERN_INFO "tvaudio: known chips: ");
for (desc = chiplist; desc->name != NULL; desc++)
printk("%s%s", (desc == chiplist) ? "" : ", ", desc->name);
printk("\n");
}
chip = kzalloc(sizeof(*chip), GFP_KERNEL);
if (!chip)
return -ENOMEM;
sd = &chip->sd;
v4l2_i2c_subdev_init(sd, client, &tvaudio_ops);
/* find description for the chip */
v4l2_dbg(1, debug, sd, "chip found @ 0x%x\n", client->addr<<1);
for (desc = chiplist; desc->name != NULL; desc++) {
if (0 == *(desc->insmodopt))
continue;
if (client->addr < desc->addr_lo ||
client->addr > desc->addr_hi)
continue;
if (desc->checkit && !desc->checkit(chip))
continue;
break;
}
if (desc->name == NULL) {
v4l2_dbg(1, debug, sd, "no matching chip description found\n");
kfree(chip);
return -EIO;
}
v4l2_info(sd, "%s found @ 0x%x (%s)\n", desc->name, client->addr<<1, client->adapter->name);
if (desc->flags) {
v4l2_dbg(1, debug, sd, "matches:%s%s%s.\n",
(desc->flags & CHIP_HAS_VOLUME) ? " volume" : "",
(desc->flags & CHIP_HAS_BASSTREBLE) ? " bass/treble" : "",
(desc->flags & CHIP_HAS_INPUTSEL) ? " audiomux" : "");
}
/* fill required data structures */
if (!id)
strlcpy(client->name, desc->name, I2C_NAME_SIZE);
chip->desc = desc;
chip->shadow.count = desc->registers+1;
chip->prevmode = -1;
chip->audmode = V4L2_TUNER_MODE_LANG1;
/* initialization */
if (desc->initialize != NULL)
desc->initialize(chip);
else
chip_cmd(chip, "init", &desc->init);
if (desc->flags & CHIP_HAS_VOLUME) {
if (!desc->volfunc) {
/* This shouldn't be happen. Warn user, but keep working
without volume controls
*/
v4l2_info(sd, "volume callback undefined!\n");
desc->flags &= ~CHIP_HAS_VOLUME;
} else {
chip->left = desc->leftinit ? desc->leftinit : 65535;
chip->right = desc->rightinit ? desc->rightinit : 65535;
chip_write(chip, desc->leftreg,
desc->volfunc(chip->left));
chip_write(chip, desc->rightreg,
desc->volfunc(chip->right));
}
}
if (desc->flags & CHIP_HAS_BASSTREBLE) {
if (!desc->bassfunc || !desc->treblefunc) {
/* This shouldn't be happen. Warn user, but keep working
without bass/treble controls
*/
v4l2_info(sd, "bass/treble callbacks undefined!\n");
desc->flags &= ~CHIP_HAS_BASSTREBLE;
} else {
chip->treble = desc->trebleinit ?
desc->trebleinit : 32768;
chip->bass = desc->bassinit ?
desc->bassinit : 32768;
chip_write(chip, desc->bassreg,
desc->bassfunc(chip->bass));
chip_write(chip, desc->treblereg,
desc->treblefunc(chip->treble));
}
}
chip->thread = NULL;
init_timer(&chip->wt);
if (desc->flags & CHIP_NEED_CHECKMODE) {
if (!desc->getmode || !desc->setmode) {
/* This shouldn't be happen. Warn user, but keep working
without kthread
*/
v4l2_info(sd, "set/get mode callbacks undefined!\n");
return 0;
}
/* start async thread */
chip->wt.function = chip_thread_wake;
chip->wt.data = (unsigned long)chip;
chip->thread = kthread_run(chip_thread, chip, client->name);
if (IS_ERR(chip->thread)) {
v4l2_warn(sd, "failed to create kthread\n");
chip->thread = NULL;
}
}
return 0;
}
static int tvaudio_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
struct CHIPSTATE *chip = to_state(sd);
del_timer_sync(&chip->wt);
if (chip->thread) {
/* shutdown async thread */
kthread_stop(chip->thread);
chip->thread = NULL;
}
v4l2_device_unregister_subdev(sd);
kfree(chip);
return 0;
}
/* This driver supports many devices and the idea is to let the driver
detect which device is present. So rather than listing all supported
devices here, we pretend to support a single, fake device type. */
static const struct i2c_device_id tvaudio_id[] = {
{ "tvaudio", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, tvaudio_id);
static struct i2c_driver tvaudio_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "tvaudio",
},
.probe = tvaudio_probe,
.remove = tvaudio_remove,
.id_table = tvaudio_id,
};
module_i2c_driver(tvaudio_driver);
| gpl-2.0 |
AOSP-JF/platform_kernel_samsung_jf | arch/arm/mach-pxa/palmz72.c | 4863 | 10261 | /*
* Hardware definitions for Palm Zire72
*
* Authors:
* Vladimir "Farcaller" Pouzanov <farcaller@gmail.com>
* Sergey Lapin <slapin@ossfans.org>
* Alex Osborne <bobofdoom@gmail.com>
* Jan Herman <2hp@seznam.cz>
*
* Rewrite for mainline:
* Marek Vasut <marek.vasut@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* (find more info at www.hackndev.com)
*
*/
#include <linux/platform_device.h>
#include <linux/syscore_ops.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <linux/gpio_keys.h>
#include <linux/input.h>
#include <linux/pda_power.h>
#include <linux/pwm_backlight.h>
#include <linux/gpio.h>
#include <linux/wm97xx.h>
#include <linux/power_supply.h>
#include <linux/usb/gpio_vbus.h>
#include <linux/i2c-gpio.h>
#include <asm/mach-types.h>
#include <asm/suspend.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <mach/pxa27x.h>
#include <mach/audio.h>
#include <mach/palmz72.h>
#include <mach/mmc.h>
#include <mach/pxafb.h>
#include <mach/irda.h>
#include <plat/pxa27x_keypad.h>
#include <mach/udc.h>
#include <mach/palmasoc.h>
#include <mach/palm27x.h>
#include <mach/pm.h>
#include <mach/camera.h>
#include <media/soc_camera.h>
#include "generic.h"
#include "devices.h"
/******************************************************************************
* Pin configuration
******************************************************************************/
static unsigned long palmz72_pin_config[] __initdata = {
/* MMC */
GPIO32_MMC_CLK,
GPIO92_MMC_DAT_0,
GPIO109_MMC_DAT_1,
GPIO110_MMC_DAT_2,
GPIO111_MMC_DAT_3,
GPIO112_MMC_CMD,
GPIO14_GPIO, /* SD detect */
GPIO115_GPIO, /* SD RO */
GPIO98_GPIO, /* SD power */
/* AC97 */
GPIO28_AC97_BITCLK,
GPIO29_AC97_SDATA_IN_0,
GPIO30_AC97_SDATA_OUT,
GPIO31_AC97_SYNC,
GPIO89_AC97_SYSCLK,
GPIO113_AC97_nRESET,
/* IrDA */
GPIO49_GPIO, /* ir disable */
GPIO46_FICP_RXD,
GPIO47_FICP_TXD,
/* PWM */
GPIO16_PWM0_OUT,
/* USB */
GPIO15_GPIO, /* usb detect */
GPIO95_GPIO, /* usb pullup */
/* Matrix keypad */
GPIO100_KP_MKIN_0 | WAKEUP_ON_LEVEL_HIGH,
GPIO101_KP_MKIN_1 | WAKEUP_ON_LEVEL_HIGH,
GPIO102_KP_MKIN_2 | WAKEUP_ON_LEVEL_HIGH,
GPIO97_KP_MKIN_3 | WAKEUP_ON_LEVEL_HIGH,
GPIO103_KP_MKOUT_0,
GPIO104_KP_MKOUT_1,
GPIO105_KP_MKOUT_2,
/* LCD */
GPIOxx_LCD_TFT_16BPP,
GPIO20_GPIO, /* bl power */
GPIO21_GPIO, /* LCD border switch */
GPIO22_GPIO, /* LCD border color */
GPIO96_GPIO, /* lcd power */
/* PXA Camera */
GPIO81_CIF_DD_0,
GPIO48_CIF_DD_5,
GPIO50_CIF_DD_3,
GPIO51_CIF_DD_2,
GPIO52_CIF_DD_4,
GPIO53_CIF_MCLK,
GPIO54_CIF_PCLK,
GPIO55_CIF_DD_1,
GPIO84_CIF_FV,
GPIO85_CIF_LV,
GPIO93_CIF_DD_6,
GPIO108_CIF_DD_7,
GPIO56_GPIO, /* OV9640 Powerdown */
GPIO57_GPIO, /* OV9640 Reset */
GPIO91_GPIO, /* OV9640 Power */
/* I2C */
GPIO117_GPIO, /* I2C_SCL */
GPIO118_GPIO, /* I2C_SDA */
/* Misc. */
GPIO0_GPIO | WAKEUP_ON_LEVEL_HIGH, /* power detect */
GPIO88_GPIO, /* green led */
GPIO27_GPIO, /* WM9712 IRQ */
};
/******************************************************************************
* GPIO keyboard
******************************************************************************/
#if defined(CONFIG_KEYBOARD_PXA27x) || defined(CONFIG_KEYBOARD_PXA27x_MODULE)
static unsigned int palmz72_matrix_keys[] = {
KEY(0, 0, KEY_POWER),
KEY(0, 1, KEY_F1),
KEY(0, 2, KEY_ENTER),
KEY(1, 0, KEY_F2),
KEY(1, 1, KEY_F3),
KEY(1, 2, KEY_F4),
KEY(2, 0, KEY_UP),
KEY(2, 2, KEY_DOWN),
KEY(3, 0, KEY_RIGHT),
KEY(3, 2, KEY_LEFT),
};
static struct pxa27x_keypad_platform_data palmz72_keypad_platform_data = {
.matrix_key_rows = 4,
.matrix_key_cols = 3,
.matrix_key_map = palmz72_matrix_keys,
.matrix_key_map_size = ARRAY_SIZE(palmz72_matrix_keys),
.debounce_interval = 30,
};
static void __init palmz72_kpc_init(void)
{
pxa_set_keypad_info(&palmz72_keypad_platform_data);
}
#else
static inline void palmz72_kpc_init(void) {}
#endif
/******************************************************************************
* LEDs
******************************************************************************/
#if defined(CONFIG_LEDS_GPIO) || defined(CONFIG_LEDS_GPIO_MODULE)
static struct gpio_led gpio_leds[] = {
{
.name = "palmz72:green:led",
.default_trigger = "none",
.gpio = GPIO_NR_PALMZ72_LED_GREEN,
},
};
static struct gpio_led_platform_data gpio_led_info = {
.leds = gpio_leds,
.num_leds = ARRAY_SIZE(gpio_leds),
};
static struct platform_device palmz72_leds = {
.name = "leds-gpio",
.id = -1,
.dev = {
.platform_data = &gpio_led_info,
}
};
static void __init palmz72_leds_init(void)
{
platform_device_register(&palmz72_leds);
}
#else
static inline void palmz72_leds_init(void) {}
#endif
#ifdef CONFIG_PM
/* We have some black magic here
* PalmOS ROM on recover expects special struct physical address
* to be transferred via PSPR. Using this struct PalmOS restores
* its state after sleep. As for Linux, we need to setup it the
* same way. More than that, PalmOS ROM changes some values in memory.
* For now only one location is found, which needs special treatment.
* Thanks to Alex Osborne, Andrzej Zaborowski, and lots of other people
* for reading backtraces for me :)
*/
#define PALMZ72_SAVE_DWORD ((unsigned long *)0xc0000050)
static struct palmz72_resume_info palmz72_resume_info = {
.magic0 = 0xb4e6,
.magic1 = 1,
/* reset state, MMU off etc */
.arm_control = 0,
.aux_control = 0,
.ttb = 0,
.domain_access = 0,
.process_id = 0,
};
static unsigned long store_ptr;
/* syscore_ops for Palm Zire 72 PM */
static int palmz72_pm_suspend(void)
{
/* setup the resume_info struct for the original bootloader */
palmz72_resume_info.resume_addr = (u32) cpu_resume;
/* Storing memory touched by ROM */
store_ptr = *PALMZ72_SAVE_DWORD;
/* Setting PSPR to a proper value */
PSPR = virt_to_phys(&palmz72_resume_info);
return 0;
}
static void palmz72_pm_resume(void)
{
*PALMZ72_SAVE_DWORD = store_ptr;
}
static struct syscore_ops palmz72_pm_syscore_ops = {
.suspend = palmz72_pm_suspend,
.resume = palmz72_pm_resume,
};
static int __init palmz72_pm_init(void)
{
if (machine_is_palmz72()) {
register_syscore_ops(&palmz72_pm_syscore_ops);
return 0;
}
return -ENODEV;
}
device_initcall(palmz72_pm_init);
#endif
/******************************************************************************
* SoC Camera
******************************************************************************/
#if defined(CONFIG_SOC_CAMERA_OV9640) || \
defined(CONFIG_SOC_CAMERA_OV9640_MODULE)
static struct pxacamera_platform_data palmz72_pxacamera_platform_data = {
.flags = PXA_CAMERA_MASTER | PXA_CAMERA_DATAWIDTH_8 |
PXA_CAMERA_PCLK_EN | PXA_CAMERA_MCLK_EN,
.mclk_10khz = 2600,
};
/* Board I2C devices. */
static struct i2c_board_info palmz72_i2c_device[] = {
{
I2C_BOARD_INFO("ov9640", 0x30),
}
};
static int palmz72_camera_power(struct device *dev, int power)
{
gpio_set_value(GPIO_NR_PALMZ72_CAM_PWDN, !power);
mdelay(50);
return 0;
}
static int palmz72_camera_reset(struct device *dev)
{
gpio_set_value(GPIO_NR_PALMZ72_CAM_RESET, 1);
mdelay(50);
gpio_set_value(GPIO_NR_PALMZ72_CAM_RESET, 0);
mdelay(50);
return 0;
}
static struct soc_camera_link palmz72_iclink = {
.bus_id = 0, /* Match id in pxa27x_device_camera in device.c */
.board_info = &palmz72_i2c_device[0],
.i2c_adapter_id = 0,
.module_name = "ov96xx",
.power = &palmz72_camera_power,
.reset = &palmz72_camera_reset,
.flags = SOCAM_DATAWIDTH_8,
};
static struct i2c_gpio_platform_data palmz72_i2c_bus_data = {
.sda_pin = 118,
.scl_pin = 117,
.udelay = 10,
.timeout = 100,
};
static struct platform_device palmz72_i2c_bus_device = {
.name = "i2c-gpio",
.id = 0, /* we use this as a replacement for i2c-pxa */
.dev = {
.platform_data = &palmz72_i2c_bus_data,
}
};
static struct platform_device palmz72_camera = {
.name = "soc-camera-pdrv",
.id = -1,
.dev = {
.platform_data = &palmz72_iclink,
},
};
/* Here we request the camera GPIOs and configure them. We power up the camera
* module, deassert the reset pin, but put it into powerdown (low to no power
* consumption) mode. This allows us to later bring the module up fast. */
static struct gpio palmz72_camera_gpios[] = {
{ GPIO_NR_PALMZ72_CAM_POWER, GPIOF_INIT_HIGH,"Camera DVDD" },
{ GPIO_NR_PALMZ72_CAM_RESET, GPIOF_INIT_LOW, "Camera RESET" },
{ GPIO_NR_PALMZ72_CAM_PWDN, GPIOF_INIT_LOW, "Camera PWDN" },
};
static inline void __init palmz72_cam_gpio_init(void)
{
int ret;
ret = gpio_request_array(ARRAY_AND_SIZE(palmz72_camera_gpios));
if (!ret)
gpio_free_array(ARRAY_AND_SIZE(palmz72_camera_gpios));
else
printk(KERN_ERR "Camera GPIO init failed!\n");
return;
}
static void __init palmz72_camera_init(void)
{
palmz72_cam_gpio_init();
pxa_set_camera_info(&palmz72_pxacamera_platform_data);
platform_device_register(&palmz72_i2c_bus_device);
platform_device_register(&palmz72_camera);
}
#else
static inline void palmz72_camera_init(void) {}
#endif
/******************************************************************************
* Machine init
******************************************************************************/
static void __init palmz72_init(void)
{
pxa2xx_mfp_config(ARRAY_AND_SIZE(palmz72_pin_config));
pxa_set_ffuart_info(NULL);
pxa_set_btuart_info(NULL);
pxa_set_stuart_info(NULL);
palm27x_mmc_init(GPIO_NR_PALMZ72_SD_DETECT_N, GPIO_NR_PALMZ72_SD_RO,
GPIO_NR_PALMZ72_SD_POWER_N, 1);
palm27x_lcd_init(-1, &palm_320x320_lcd_mode);
palm27x_udc_init(GPIO_NR_PALMZ72_USB_DETECT_N,
GPIO_NR_PALMZ72_USB_PULLUP, 0);
palm27x_irda_init(GPIO_NR_PALMZ72_IR_DISABLE);
palm27x_ac97_init(PALMZ72_BAT_MIN_VOLTAGE, PALMZ72_BAT_MAX_VOLTAGE,
-1, 113);
palm27x_pwm_init(-1, -1);
palm27x_power_init(-1, -1);
palm27x_pmic_init();
palmz72_kpc_init();
palmz72_leds_init();
palmz72_camera_init();
}
MACHINE_START(PALMZ72, "Palm Zire72")
.atag_offset = 0x100,
.map_io = pxa27x_map_io,
.nr_irqs = PXA_NR_IRQS,
.init_irq = pxa27x_init_irq,
.handle_irq = pxa27x_handle_irq,
.timer = &pxa_timer,
.init_machine = palmz72_init,
.restart = pxa_restart,
MACHINE_END
| gpl-2.0 |
Red--Code/mt6589_kernel_3.4.67 | arch/arm/kernel/kprobes-test-thumb.c | 7935 | 44841 | /*
* arch/arm/kernel/kprobes-test-thumb.c
*
* Copyright (C) 2011 Jon Medhurst <tixy@yxit.co.uk>.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include "kprobes-test.h"
#define TEST_ISA "16"
#define DONT_TEST_IN_ITBLOCK(tests) \
kprobe_test_flags |= TEST_FLAG_NO_ITBLOCK; \
tests \
kprobe_test_flags &= ~TEST_FLAG_NO_ITBLOCK;
#define CONDITION_INSTRUCTIONS(cc_pos, tests) \
kprobe_test_cc_position = cc_pos; \
DONT_TEST_IN_ITBLOCK(tests) \
kprobe_test_cc_position = 0;
#define TEST_ITBLOCK(code) \
kprobe_test_flags |= TEST_FLAG_FULL_ITBLOCK; \
TESTCASE_START(code) \
TEST_ARG_END("") \
"50: nop \n\t" \
"1: "code" \n\t" \
" mov r1, #0x11 \n\t" \
" mov r2, #0x22 \n\t" \
" mov r3, #0x33 \n\t" \
"2: nop \n\t" \
TESTCASE_END \
kprobe_test_flags &= ~TEST_FLAG_FULL_ITBLOCK;
#define TEST_THUMB_TO_ARM_INTERWORK_P(code1, reg, val, code2) \
TESTCASE_START(code1 #reg code2) \
TEST_ARG_PTR(reg, val) \
TEST_ARG_REG(14, 99f+1) \
TEST_ARG_MEM(15, 3f) \
TEST_ARG_END("") \
" nop \n\t" /* To align 1f */ \
"50: nop \n\t" \
"1: "code1 #reg code2" \n\t" \
" bx lr \n\t" \
".arm \n\t" \
"3: adr lr, 2f+1 \n\t" \
" bx lr \n\t" \
".thumb \n\t" \
"2: nop \n\t" \
TESTCASE_END
void kprobe_thumb16_test_cases(void)
{
kprobe_test_flags = TEST_FLAG_NARROW_INSTR;
TEST_GROUP("Shift (immediate), add, subtract, move, and compare")
TEST_R( "lsls r7, r",0,VAL1,", #5")
TEST_R( "lsls r0, r",7,VAL2,", #11")
TEST_R( "lsrs r7, r",0,VAL1,", #5")
TEST_R( "lsrs r0, r",7,VAL2,", #11")
TEST_R( "asrs r7, r",0,VAL1,", #5")
TEST_R( "asrs r0, r",7,VAL2,", #11")
TEST_RR( "adds r2, r",0,VAL1,", r",7,VAL2,"")
TEST_RR( "adds r5, r",7,VAL2,", r",0,VAL2,"")
TEST_RR( "subs r2, r",0,VAL1,", r",7,VAL2,"")
TEST_RR( "subs r5, r",7,VAL2,", r",0,VAL2,"")
TEST_R( "adds r7, r",0,VAL1,", #5")
TEST_R( "adds r0, r",7,VAL2,", #2")
TEST_R( "subs r7, r",0,VAL1,", #5")
TEST_R( "subs r0, r",7,VAL2,", #2")
TEST( "movs.n r0, #0x5f")
TEST( "movs.n r7, #0xa0")
TEST_R( "cmp.n r",0,0x5e, ", #0x5f")
TEST_R( "cmp.n r",5,0x15f,", #0x5f")
TEST_R( "cmp.n r",7,0xa0, ", #0xa0")
TEST_R( "adds.n r",0,VAL1,", #0x5f")
TEST_R( "adds.n r",7,VAL2,", #0xa0")
TEST_R( "subs.n r",0,VAL1,", #0x5f")
TEST_R( "subs.n r",7,VAL2,", #0xa0")
TEST_GROUP("16-bit Thumb data-processing instructions")
#define DATA_PROCESSING16(op,val) \
TEST_RR( op" r",0,VAL1,", r",7,val,"") \
TEST_RR( op" r",7,VAL2,", r",0,val,"")
DATA_PROCESSING16("ands",0xf00f00ff)
DATA_PROCESSING16("eors",0xf00f00ff)
DATA_PROCESSING16("lsls",11)
DATA_PROCESSING16("lsrs",11)
DATA_PROCESSING16("asrs",11)
DATA_PROCESSING16("adcs",VAL2)
DATA_PROCESSING16("sbcs",VAL2)
DATA_PROCESSING16("rors",11)
DATA_PROCESSING16("tst",0xf00f00ff)
TEST_R("rsbs r",0,VAL1,", #0")
TEST_R("rsbs r",7,VAL2,", #0")
DATA_PROCESSING16("cmp",0xf00f00ff)
DATA_PROCESSING16("cmn",0xf00f00ff)
DATA_PROCESSING16("orrs",0xf00f00ff)
DATA_PROCESSING16("muls",VAL2)
DATA_PROCESSING16("bics",0xf00f00ff)
DATA_PROCESSING16("mvns",VAL2)
TEST_GROUP("Special data instructions and branch and exchange")
TEST_RR( "add r",0, VAL1,", r",7,VAL2,"")
TEST_RR( "add r",3, VAL2,", r",8,VAL3,"")
TEST_RR( "add r",8, VAL3,", r",0,VAL1,"")
TEST_R( "add sp" ", r",8,-8, "")
TEST_R( "add r",14,VAL1,", pc")
TEST_BF_R("add pc" ", r",0,2f-1f-8,"")
TEST_UNSUPPORTED(".short 0x44ff @ add pc, pc")
TEST_RR( "cmp r",3,VAL1,", r",8,VAL2,"")
TEST_RR( "cmp r",8,VAL2,", r",0,VAL1,"")
TEST_R( "cmp sp" ", r",8,-8, "")
TEST_R( "mov r0, r",7,VAL2,"")
TEST_R( "mov r3, r",8,VAL3,"")
TEST_R( "mov r8, r",0,VAL1,"")
TEST_P( "mov sp, r",8,-8, "")
TEST( "mov lr, pc")
TEST_BF_R("mov pc, r",0,2f, "")
TEST_BF_R("bx r",0, 2f+1,"")
TEST_BF_R("bx r",14,2f+1,"")
TESTCASE_START("bx pc")
TEST_ARG_REG(14, 99f+1)
TEST_ARG_END("")
" nop \n\t" /* To align the bx pc*/
"50: nop \n\t"
"1: bx pc \n\t"
" bx lr \n\t"
".arm \n\t"
" adr lr, 2f+1 \n\t"
" bx lr \n\t"
".thumb \n\t"
"2: nop \n\t"
TESTCASE_END
TEST_BF_R("blx r",0, 2f+1,"")
TEST_BB_R("blx r",14,2f+1,"")
TEST_UNSUPPORTED(".short 0x47f8 @ blx pc")
TEST_GROUP("Load from Literal Pool")
TEST_X( "ldr r0, 3f",
".align \n\t"
"3: .word "__stringify(VAL1))
TEST_X( "ldr r7, 3f",
".space 128 \n\t"
".align \n\t"
"3: .word "__stringify(VAL2))
TEST_GROUP("16-bit Thumb Load/store instructions")
TEST_RPR("str r",0, VAL1,", [r",1, 24,", r",2, 48,"]")
TEST_RPR("str r",7, VAL2,", [r",6, 24,", r",5, 48,"]")
TEST_RPR("strh r",0, VAL1,", [r",1, 24,", r",2, 48,"]")
TEST_RPR("strh r",7, VAL2,", [r",6, 24,", r",5, 48,"]")
TEST_RPR("strb r",0, VAL1,", [r",1, 24,", r",2, 48,"]")
TEST_RPR("strb r",7, VAL2,", [r",6, 24,", r",5, 48,"]")
TEST_PR( "ldrsb r0, [r",1, 24,", r",2, 48,"]")
TEST_PR( "ldrsb r7, [r",6, 24,", r",5, 50,"]")
TEST_PR( "ldr r0, [r",1, 24,", r",2, 48,"]")
TEST_PR( "ldr r7, [r",6, 24,", r",5, 48,"]")
TEST_PR( "ldrh r0, [r",1, 24,", r",2, 48,"]")
TEST_PR( "ldrh r7, [r",6, 24,", r",5, 50,"]")
TEST_PR( "ldrb r0, [r",1, 24,", r",2, 48,"]")
TEST_PR( "ldrb r7, [r",6, 24,", r",5, 50,"]")
TEST_PR( "ldrsh r0, [r",1, 24,", r",2, 48,"]")
TEST_PR( "ldrsh r7, [r",6, 24,", r",5, 50,"]")
TEST_RP("str r",0, VAL1,", [r",1, 24,", #120]")
TEST_RP("str r",7, VAL2,", [r",6, 24,", #120]")
TEST_P( "ldr r0, [r",1, 24,", #120]")
TEST_P( "ldr r7, [r",6, 24,", #120]")
TEST_RP("strb r",0, VAL1,", [r",1, 24,", #30]")
TEST_RP("strb r",7, VAL2,", [r",6, 24,", #30]")
TEST_P( "ldrb r0, [r",1, 24,", #30]")
TEST_P( "ldrb r7, [r",6, 24,", #30]")
TEST_RP("strh r",0, VAL1,", [r",1, 24,", #60]")
TEST_RP("strh r",7, VAL2,", [r",6, 24,", #60]")
TEST_P( "ldrh r0, [r",1, 24,", #60]")
TEST_P( "ldrh r7, [r",6, 24,", #60]")
TEST_R( "str r",0, VAL1,", [sp, #0]")
TEST_R( "str r",7, VAL2,", [sp, #160]")
TEST( "ldr r0, [sp, #0]")
TEST( "ldr r7, [sp, #160]")
TEST_RP("str r",0, VAL1,", [r",0, 24,"]")
TEST_P( "ldr r0, [r",0, 24,"]")
TEST_GROUP("Generate PC-/SP-relative address")
TEST("add r0, pc, #4")
TEST("add r7, pc, #1020")
TEST("add r0, sp, #4")
TEST("add r7, sp, #1020")
TEST_GROUP("Miscellaneous 16-bit instructions")
TEST_UNSUPPORTED( "cpsie i")
TEST_UNSUPPORTED( "cpsid i")
TEST_UNSUPPORTED( "setend le")
TEST_UNSUPPORTED( "setend be")
TEST("add sp, #"__stringify(TEST_MEMORY_SIZE)) /* Assumes TEST_MEMORY_SIZE < 0x400 */
TEST("sub sp, #0x7f*4")
DONT_TEST_IN_ITBLOCK(
TEST_BF_R( "cbnz r",0,0, ", 2f")
TEST_BF_R( "cbz r",2,-1,", 2f")
TEST_BF_RX( "cbnz r",4,1, ", 2f", SPACE_0x20)
TEST_BF_RX( "cbz r",7,0, ", 2f", SPACE_0x40)
)
TEST_R("sxth r0, r",7, HH1,"")
TEST_R("sxth r7, r",0, HH2,"")
TEST_R("sxtb r0, r",7, HH1,"")
TEST_R("sxtb r7, r",0, HH2,"")
TEST_R("uxth r0, r",7, HH1,"")
TEST_R("uxth r7, r",0, HH2,"")
TEST_R("uxtb r0, r",7, HH1,"")
TEST_R("uxtb r7, r",0, HH2,"")
TEST_R("rev r0, r",7, VAL1,"")
TEST_R("rev r7, r",0, VAL2,"")
TEST_R("rev16 r0, r",7, VAL1,"")
TEST_R("rev16 r7, r",0, VAL2,"")
TEST_UNSUPPORTED(".short 0xba80")
TEST_UNSUPPORTED(".short 0xbabf")
TEST_R("revsh r0, r",7, VAL1,"")
TEST_R("revsh r7, r",0, VAL2,"")
#define TEST_POPPC(code, offset) \
TESTCASE_START(code) \
TEST_ARG_PTR(13, offset) \
TEST_ARG_END("") \
TEST_BRANCH_F(code) \
TESTCASE_END
TEST("push {r0}")
TEST("push {r7}")
TEST("push {r14}")
TEST("push {r0-r7,r14}")
TEST("push {r0,r2,r4,r6,r14}")
TEST("push {r1,r3,r5,r7}")
TEST("pop {r0}")
TEST("pop {r7}")
TEST("pop {r0,r2,r4,r6}")
TEST_POPPC("pop {pc}",15*4)
TEST_POPPC("pop {r0-r7,pc}",7*4)
TEST_POPPC("pop {r1,r3,r5,r7,pc}",11*4)
TEST_THUMB_TO_ARM_INTERWORK_P("pop {pc} @ ",13,15*4,"")
TEST_THUMB_TO_ARM_INTERWORK_P("pop {r0-r7,pc} @ ",13,7*4,"")
TEST_UNSUPPORTED("bkpt.n 0")
TEST_UNSUPPORTED("bkpt.n 255")
TEST_SUPPORTED("yield")
TEST("sev")
TEST("nop")
TEST("wfi")
TEST_SUPPORTED("wfe")
TEST_UNSUPPORTED(".short 0xbf50") /* Unassigned hints */
TEST_UNSUPPORTED(".short 0xbff0") /* Unassigned hints */
#define TEST_IT(code, code2) \
TESTCASE_START(code) \
TEST_ARG_END("") \
"50: nop \n\t" \
"1: "code" \n\t" \
" "code2" \n\t" \
"2: nop \n\t" \
TESTCASE_END
DONT_TEST_IN_ITBLOCK(
TEST_IT("it eq","moveq r0,#0")
TEST_IT("it vc","movvc r0,#0")
TEST_IT("it le","movle r0,#0")
TEST_IT("ite eq","moveq r0,#0\n\t movne r1,#1")
TEST_IT("itet vc","movvc r0,#0\n\t movvs r1,#1\n\t movvc r2,#2")
TEST_IT("itete le","movle r0,#0\n\t movgt r1,#1\n\t movle r2,#2\n\t movgt r3,#3")
TEST_IT("itttt le","movle r0,#0\n\t movle r1,#1\n\t movle r2,#2\n\t movle r3,#3")
TEST_IT("iteee le","movle r0,#0\n\t movgt r1,#1\n\t movgt r2,#2\n\t movgt r3,#3")
)
TEST_GROUP("Load and store multiple")
TEST_P("ldmia r",4, 16*4,"!, {r0,r7}")
TEST_P("ldmia r",7, 16*4,"!, {r0-r6}")
TEST_P("stmia r",4, 16*4,"!, {r0,r7}")
TEST_P("stmia r",0, 16*4,"!, {r0-r7}")
TEST_GROUP("Conditional branch and Supervisor Call instructions")
CONDITION_INSTRUCTIONS(8,
TEST_BF("beq 2f")
TEST_BB("bne 2b")
TEST_BF("bgt 2f")
TEST_BB("blt 2b")
)
TEST_UNSUPPORTED(".short 0xde00")
TEST_UNSUPPORTED(".short 0xdeff")
TEST_UNSUPPORTED("svc #0x00")
TEST_UNSUPPORTED("svc #0xff")
TEST_GROUP("Unconditional branch")
TEST_BF( "b 2f")
TEST_BB( "b 2b")
TEST_BF_X("b 2f", SPACE_0x400)
TEST_BB_X("b 2b", SPACE_0x400)
TEST_GROUP("Testing instructions in IT blocks")
TEST_ITBLOCK("subs.n r0, r0")
verbose("\n");
}
void kprobe_thumb32_test_cases(void)
{
kprobe_test_flags = 0;
TEST_GROUP("Load/store multiple")
TEST_UNSUPPORTED("rfedb sp")
TEST_UNSUPPORTED("rfeia sp")
TEST_UNSUPPORTED("rfedb sp!")
TEST_UNSUPPORTED("rfeia sp!")
TEST_P( "stmia r",0, 16*4,", {r0,r8}")
TEST_P( "stmia r",4, 16*4,", {r0-r12,r14}")
TEST_P( "stmia r",7, 16*4,"!, {r8-r12,r14}")
TEST_P( "stmia r",12,16*4,"!, {r1,r3,r5,r7,r8-r11,r14}")
TEST_P( "ldmia r",0, 16*4,", {r0,r8}")
TEST_P( "ldmia r",4, 0, ", {r0-r12,r14}")
TEST_BF_P("ldmia r",5, 8*4, "!, {r6-r12,r15}")
TEST_P( "ldmia r",12,16*4,"!, {r1,r3,r5,r7,r8-r11,r14}")
TEST_BF_P("ldmia r",14,14*4,"!, {r4,pc}")
TEST_P( "stmdb r",0, 16*4,", {r0,r8}")
TEST_P( "stmdb r",4, 16*4,", {r0-r12,r14}")
TEST_P( "stmdb r",5, 16*4,"!, {r8-r12,r14}")
TEST_P( "stmdb r",12,16*4,"!, {r1,r3,r5,r7,r8-r11,r14}")
TEST_P( "ldmdb r",0, 16*4,", {r0,r8}")
TEST_P( "ldmdb r",4, 16*4,", {r0-r12,r14}")
TEST_BF_P("ldmdb r",5, 16*4,"!, {r6-r12,r15}")
TEST_P( "ldmdb r",12,16*4,"!, {r1,r3,r5,r7,r8-r11,r14}")
TEST_BF_P("ldmdb r",14,16*4,"!, {r4,pc}")
TEST_P( "stmdb r",13,16*4,"!, {r3-r12,lr}")
TEST_P( "stmdb r",13,16*4,"!, {r3-r12}")
TEST_P( "stmdb r",2, 16*4,", {r3-r12,lr}")
TEST_P( "stmdb r",13,16*4,"!, {r2-r12,lr}")
TEST_P( "stmdb r",0, 16*4,", {r0-r12}")
TEST_P( "stmdb r",0, 16*4,", {r0-r12,lr}")
TEST_BF_P("ldmia r",13,5*4, "!, {r3-r12,pc}")
TEST_P( "ldmia r",13,5*4, "!, {r3-r12}")
TEST_BF_P("ldmia r",2, 5*4, "!, {r3-r12,pc}")
TEST_BF_P("ldmia r",13,4*4, "!, {r2-r12,pc}")
TEST_P( "ldmia r",0, 16*4,", {r0-r12}")
TEST_P( "ldmia r",0, 16*4,", {r0-r12,lr}")
TEST_THUMB_TO_ARM_INTERWORK_P("ldmia r",0,14*4,", {r12,pc}")
TEST_THUMB_TO_ARM_INTERWORK_P("ldmia r",13,2*4,", {r0-r12,pc}")
TEST_UNSUPPORTED(".short 0xe88f,0x0101 @ stmia pc, {r0,r8}")
TEST_UNSUPPORTED(".short 0xe92f,0x5f00 @ stmdb pc!, {r8-r12,r14}")
TEST_UNSUPPORTED(".short 0xe8bd,0xc000 @ ldmia r13!, {r14,pc}")
TEST_UNSUPPORTED(".short 0xe93e,0xc000 @ ldmdb r14!, {r14,pc}")
TEST_UNSUPPORTED(".short 0xe8a7,0x3f00 @ stmia r7!, {r8-r12,sp}")
TEST_UNSUPPORTED(".short 0xe8a7,0x9f00 @ stmia r7!, {r8-r12,pc}")
TEST_UNSUPPORTED(".short 0xe93e,0x2010 @ ldmdb r14!, {r4,sp}")
TEST_GROUP("Load/store double or exclusive, table branch")
TEST_P( "ldrd r0, r1, [r",1, 24,", #-16]")
TEST( "ldrd r12, r14, [sp, #16]")
TEST_P( "ldrd r1, r0, [r",7, 24,", #-16]!")
TEST( "ldrd r14, r12, [sp, #16]!")
TEST_P( "ldrd r1, r0, [r",7, 24,"], #16")
TEST( "ldrd r7, r8, [sp], #-16")
TEST_X( "ldrd r12, r14, 3f",
".align 3 \n\t"
"3: .word "__stringify(VAL1)" \n\t"
" .word "__stringify(VAL2))
TEST_UNSUPPORTED(".short 0xe9ff,0xec04 @ ldrd r14, r12, [pc, #16]!")
TEST_UNSUPPORTED(".short 0xe8ff,0xec04 @ ldrd r14, r12, [pc], #16")
TEST_UNSUPPORTED(".short 0xe9d4,0xd800 @ ldrd sp, r8, [r4]")
TEST_UNSUPPORTED(".short 0xe9d4,0xf800 @ ldrd pc, r8, [r4]")
TEST_UNSUPPORTED(".short 0xe9d4,0x7d00 @ ldrd r7, sp, [r4]")
TEST_UNSUPPORTED(".short 0xe9d4,0x7f00 @ ldrd r7, pc, [r4]")
TEST_RRP("strd r",0, VAL1,", r",1, VAL2,", [r",1, 24,", #-16]")
TEST_RR( "strd r",12,VAL2,", r",14,VAL1,", [sp, #16]")
TEST_RRP("strd r",1, VAL1,", r",0, VAL2,", [r",7, 24,", #-16]!")
TEST_RR( "strd r",14,VAL2,", r",12,VAL1,", [sp, #16]!")
TEST_RRP("strd r",1, VAL1,", r",0, VAL2,", [r",7, 24,"], #16")
TEST_RR( "strd r",7, VAL2,", r",8, VAL1,", [sp], #-16")
TEST_UNSUPPORTED(".short 0xe9ef,0xec04 @ strd r14, r12, [pc, #16]!")
TEST_UNSUPPORTED(".short 0xe8ef,0xec04 @ strd r14, r12, [pc], #16")
TEST_RX("tbb [pc, r",0, (9f-(1f+4)),"]",
"9: \n\t"
".byte (2f-1b-4)>>1 \n\t"
".byte (3f-1b-4)>>1 \n\t"
"3: mvn r0, r0 \n\t"
"2: nop \n\t")
TEST_RX("tbb [pc, r",4, (9f-(1f+4)+1),"]",
"9: \n\t"
".byte (2f-1b-4)>>1 \n\t"
".byte (3f-1b-4)>>1 \n\t"
"3: mvn r0, r0 \n\t"
"2: nop \n\t")
TEST_RRX("tbb [r",1,9f,", r",2,0,"]",
"9: \n\t"
".byte (2f-1b-4)>>1 \n\t"
".byte (3f-1b-4)>>1 \n\t"
"3: mvn r0, r0 \n\t"
"2: nop \n\t")
TEST_RX("tbh [pc, r",7, (9f-(1f+4))>>1,"]",
"9: \n\t"
".short (2f-1b-4)>>1 \n\t"
".short (3f-1b-4)>>1 \n\t"
"3: mvn r0, r0 \n\t"
"2: nop \n\t")
TEST_RX("tbh [pc, r",12, ((9f-(1f+4))>>1)+1,"]",
"9: \n\t"
".short (2f-1b-4)>>1 \n\t"
".short (3f-1b-4)>>1 \n\t"
"3: mvn r0, r0 \n\t"
"2: nop \n\t")
TEST_RRX("tbh [r",1,9f, ", r",14,1,"]",
"9: \n\t"
".short (2f-1b-4)>>1 \n\t"
".short (3f-1b-4)>>1 \n\t"
"3: mvn r0, r0 \n\t"
"2: nop \n\t")
TEST_UNSUPPORTED(".short 0xe8d1,0xf01f @ tbh [r1, pc]")
TEST_UNSUPPORTED(".short 0xe8d1,0xf01d @ tbh [r1, sp]")
TEST_UNSUPPORTED(".short 0xe8dd,0xf012 @ tbh [sp, r2]")
TEST_UNSUPPORTED("strexb r0, r1, [r2]")
TEST_UNSUPPORTED("strexh r0, r1, [r2]")
TEST_UNSUPPORTED("strexd r0, r1, [r2]")
TEST_UNSUPPORTED("ldrexb r0, [r1]")
TEST_UNSUPPORTED("ldrexh r0, [r1]")
TEST_UNSUPPORTED("ldrexd r0, [r1]")
TEST_GROUP("Data-processing (shifted register) and (modified immediate)")
#define _DATA_PROCESSING32_DNM(op,s,val) \
TEST_RR(op s".w r0, r",1, VAL1,", r",2, val, "") \
TEST_RR(op s" r1, r",1, VAL1,", r",2, val, ", lsl #3") \
TEST_RR(op s" r2, r",3, VAL1,", r",2, val, ", lsr #4") \
TEST_RR(op s" r3, r",3, VAL1,", r",2, val, ", asr #5") \
TEST_RR(op s" r4, r",5, VAL1,", r",2, N(val),", asr #6") \
TEST_RR(op s" r5, r",5, VAL1,", r",2, val, ", ror #7") \
TEST_RR(op s" r8, r",9, VAL1,", r",10,val, ", rrx") \
TEST_R( op s" r0, r",11,VAL1,", #0x00010001") \
TEST_R( op s" r11, r",0, VAL1,", #0xf5000000") \
TEST_R( op s" r7, r",8, VAL2,", #0x000af000")
#define DATA_PROCESSING32_DNM(op,val) \
_DATA_PROCESSING32_DNM(op,"",val) \
_DATA_PROCESSING32_DNM(op,"s",val)
#define DATA_PROCESSING32_NM(op,val) \
TEST_RR(op".w r",1, VAL1,", r",2, val, "") \
TEST_RR(op" r",1, VAL1,", r",2, val, ", lsl #3") \
TEST_RR(op" r",3, VAL1,", r",2, val, ", lsr #4") \
TEST_RR(op" r",3, VAL1,", r",2, val, ", asr #5") \
TEST_RR(op" r",5, VAL1,", r",2, N(val),", asr #6") \
TEST_RR(op" r",5, VAL1,", r",2, val, ", ror #7") \
TEST_RR(op" r",9, VAL1,", r",10,val, ", rrx") \
TEST_R( op" r",11,VAL1,", #0x00010001") \
TEST_R( op" r",0, VAL1,", #0xf5000000") \
TEST_R( op" r",8, VAL2,", #0x000af000")
#define _DATA_PROCESSING32_DM(op,s,val) \
TEST_R( op s".w r0, r",14, val, "") \
TEST_R( op s" r1, r",12, val, ", lsl #3") \
TEST_R( op s" r2, r",11, val, ", lsr #4") \
TEST_R( op s" r3, r",10, val, ", asr #5") \
TEST_R( op s" r4, r",9, N(val),", asr #6") \
TEST_R( op s" r5, r",8, val, ", ror #7") \
TEST_R( op s" r8, r",7,val, ", rrx") \
TEST( op s" r0, #0x00010001") \
TEST( op s" r11, #0xf5000000") \
TEST( op s" r7, #0x000af000") \
TEST( op s" r4, #0x00005a00")
#define DATA_PROCESSING32_DM(op,val) \
_DATA_PROCESSING32_DM(op,"",val) \
_DATA_PROCESSING32_DM(op,"s",val)
DATA_PROCESSING32_DNM("and",0xf00f00ff)
DATA_PROCESSING32_NM("tst",0xf00f00ff)
DATA_PROCESSING32_DNM("bic",0xf00f00ff)
DATA_PROCESSING32_DNM("orr",0xf00f00ff)
DATA_PROCESSING32_DM("mov",VAL2)
DATA_PROCESSING32_DNM("orn",0xf00f00ff)
DATA_PROCESSING32_DM("mvn",VAL2)
DATA_PROCESSING32_DNM("eor",0xf00f00ff)
DATA_PROCESSING32_NM("teq",0xf00f00ff)
DATA_PROCESSING32_DNM("add",VAL2)
DATA_PROCESSING32_NM("cmn",VAL2)
DATA_PROCESSING32_DNM("adc",VAL2)
DATA_PROCESSING32_DNM("sbc",VAL2)
DATA_PROCESSING32_DNM("sub",VAL2)
DATA_PROCESSING32_NM("cmp",VAL2)
DATA_PROCESSING32_DNM("rsb",VAL2)
TEST_RR("pkhbt r0, r",0, HH1,", r",1, HH2,"")
TEST_RR("pkhbt r14,r",12, HH1,", r",10,HH2,", lsl #2")
TEST_RR("pkhtb r0, r",0, HH1,", r",1, HH2,"")
TEST_RR("pkhtb r14,r",12, HH1,", r",10,HH2,", asr #2")
TEST_UNSUPPORTED(".short 0xea17,0x0f0d @ tst.w r7, sp")
TEST_UNSUPPORTED(".short 0xea17,0x0f0f @ tst.w r7, pc")
TEST_UNSUPPORTED(".short 0xea1d,0x0f07 @ tst.w sp, r7")
TEST_UNSUPPORTED(".short 0xea1f,0x0f07 @ tst.w pc, r7")
TEST_UNSUPPORTED(".short 0xf01d,0x1f08 @ tst sp, #0x00080008")
TEST_UNSUPPORTED(".short 0xf01f,0x1f08 @ tst pc, #0x00080008")
TEST_UNSUPPORTED(".short 0xea97,0x0f0d @ teq.w r7, sp")
TEST_UNSUPPORTED(".short 0xea97,0x0f0f @ teq.w r7, pc")
TEST_UNSUPPORTED(".short 0xea9d,0x0f07 @ teq.w sp, r7")
TEST_UNSUPPORTED(".short 0xea9f,0x0f07 @ teq.w pc, r7")
TEST_UNSUPPORTED(".short 0xf09d,0x1f08 @ tst sp, #0x00080008")
TEST_UNSUPPORTED(".short 0xf09f,0x1f08 @ tst pc, #0x00080008")
TEST_UNSUPPORTED(".short 0xeb17,0x0f0d @ cmn.w r7, sp")
TEST_UNSUPPORTED(".short 0xeb17,0x0f0f @ cmn.w r7, pc")
TEST_P("cmn.w sp, r",7,0,"")
TEST_UNSUPPORTED(".short 0xeb1f,0x0f07 @ cmn.w pc, r7")
TEST( "cmn sp, #0x00080008")
TEST_UNSUPPORTED(".short 0xf11f,0x1f08 @ cmn pc, #0x00080008")
TEST_UNSUPPORTED(".short 0xebb7,0x0f0d @ cmp.w r7, sp")
TEST_UNSUPPORTED(".short 0xebb7,0x0f0f @ cmp.w r7, pc")
TEST_P("cmp.w sp, r",7,0,"")
TEST_UNSUPPORTED(".short 0xebbf,0x0f07 @ cmp.w pc, r7")
TEST( "cmp sp, #0x00080008")
TEST_UNSUPPORTED(".short 0xf1bf,0x1f08 @ cmp pc, #0x00080008")
TEST_UNSUPPORTED(".short 0xea5f,0x070d @ movs.w r7, sp")
TEST_UNSUPPORTED(".short 0xea5f,0x070f @ movs.w r7, pc")
TEST_UNSUPPORTED(".short 0xea5f,0x0d07 @ movs.w sp, r7")
TEST_UNSUPPORTED(".short 0xea4f,0x0f07 @ mov.w pc, r7")
TEST_UNSUPPORTED(".short 0xf04f,0x1d08 @ mov sp, #0x00080008")
TEST_UNSUPPORTED(".short 0xf04f,0x1f08 @ mov pc, #0x00080008")
TEST_R("add.w r0, sp, r",1, 4,"")
TEST_R("adds r0, sp, r",1, 4,", asl #3")
TEST_R("add r0, sp, r",1, 4,", asl #4")
TEST_R("add r0, sp, r",1, 16,", ror #1")
TEST_R("add.w sp, sp, r",1, 4,"")
TEST_R("add sp, sp, r",1, 4,", asl #3")
TEST_UNSUPPORTED(".short 0xeb0d,0x1d01 @ add sp, sp, r1, asl #4")
TEST_UNSUPPORTED(".short 0xeb0d,0x0d71 @ add sp, sp, r1, ror #1")
TEST( "add.w r0, sp, #24")
TEST( "add.w sp, sp, #24")
TEST_UNSUPPORTED(".short 0xeb0d,0x0f01 @ add pc, sp, r1")
TEST_UNSUPPORTED(".short 0xeb0d,0x000f @ add r0, sp, pc")
TEST_UNSUPPORTED(".short 0xeb0d,0x000d @ add r0, sp, sp")
TEST_UNSUPPORTED(".short 0xeb0d,0x0d0f @ add sp, sp, pc")
TEST_UNSUPPORTED(".short 0xeb0d,0x0d0d @ add sp, sp, sp")
TEST_R("sub.w r0, sp, r",1, 4,"")
TEST_R("subs r0, sp, r",1, 4,", asl #3")
TEST_R("sub r0, sp, r",1, 4,", asl #4")
TEST_R("sub r0, sp, r",1, 16,", ror #1")
TEST_R("sub.w sp, sp, r",1, 4,"")
TEST_R("sub sp, sp, r",1, 4,", asl #3")
TEST_UNSUPPORTED(".short 0xebad,0x1d01 @ sub sp, sp, r1, asl #4")
TEST_UNSUPPORTED(".short 0xebad,0x0d71 @ sub sp, sp, r1, ror #1")
TEST_UNSUPPORTED(".short 0xebad,0x0f01 @ sub pc, sp, r1")
TEST( "sub.w r0, sp, #24")
TEST( "sub.w sp, sp, #24")
TEST_UNSUPPORTED(".short 0xea02,0x010f @ and r1, r2, pc")
TEST_UNSUPPORTED(".short 0xea0f,0x0103 @ and r1, pc, r3")
TEST_UNSUPPORTED(".short 0xea02,0x0f03 @ and pc, r2, r3")
TEST_UNSUPPORTED(".short 0xea02,0x010d @ and r1, r2, sp")
TEST_UNSUPPORTED(".short 0xea0d,0x0103 @ and r1, sp, r3")
TEST_UNSUPPORTED(".short 0xea02,0x0d03 @ and sp, r2, r3")
TEST_UNSUPPORTED(".short 0xf00d,0x1108 @ and r1, sp, #0x00080008")
TEST_UNSUPPORTED(".short 0xf00f,0x1108 @ and r1, pc, #0x00080008")
TEST_UNSUPPORTED(".short 0xf002,0x1d08 @ and sp, r8, #0x00080008")
TEST_UNSUPPORTED(".short 0xf002,0x1f08 @ and pc, r8, #0x00080008")
TEST_UNSUPPORTED(".short 0xeb02,0x010f @ add r1, r2, pc")
TEST_UNSUPPORTED(".short 0xeb0f,0x0103 @ add r1, pc, r3")
TEST_UNSUPPORTED(".short 0xeb02,0x0f03 @ add pc, r2, r3")
TEST_UNSUPPORTED(".short 0xeb02,0x010d @ add r1, r2, sp")
TEST_SUPPORTED( ".short 0xeb0d,0x0103 @ add r1, sp, r3")
TEST_UNSUPPORTED(".short 0xeb02,0x0d03 @ add sp, r2, r3")
TEST_SUPPORTED( ".short 0xf10d,0x1108 @ add r1, sp, #0x00080008")
TEST_UNSUPPORTED(".short 0xf10d,0x1f08 @ add pc, sp, #0x00080008")
TEST_UNSUPPORTED(".short 0xf10f,0x1108 @ add r1, pc, #0x00080008")
TEST_UNSUPPORTED(".short 0xf102,0x1d08 @ add sp, r8, #0x00080008")
TEST_UNSUPPORTED(".short 0xf102,0x1f08 @ add pc, r8, #0x00080008")
TEST_UNSUPPORTED(".short 0xeaa0,0x0000")
TEST_UNSUPPORTED(".short 0xeaf0,0x0000")
TEST_UNSUPPORTED(".short 0xeb20,0x0000")
TEST_UNSUPPORTED(".short 0xeb80,0x0000")
TEST_UNSUPPORTED(".short 0xebe0,0x0000")
TEST_UNSUPPORTED(".short 0xf0a0,0x0000")
TEST_UNSUPPORTED(".short 0xf0c0,0x0000")
TEST_UNSUPPORTED(".short 0xf0f0,0x0000")
TEST_UNSUPPORTED(".short 0xf120,0x0000")
TEST_UNSUPPORTED(".short 0xf180,0x0000")
TEST_UNSUPPORTED(".short 0xf1e0,0x0000")
TEST_GROUP("Coprocessor instructions")
TEST_UNSUPPORTED(".short 0xec00,0x0000")
TEST_UNSUPPORTED(".short 0xeff0,0x0000")
TEST_UNSUPPORTED(".short 0xfc00,0x0000")
TEST_UNSUPPORTED(".short 0xfff0,0x0000")
TEST_GROUP("Data-processing (plain binary immediate)")
TEST_R("addw r0, r",1, VAL1,", #0x123")
TEST( "addw r14, sp, #0xf5a")
TEST( "addw sp, sp, #0x20")
TEST( "addw r7, pc, #0x888")
TEST_UNSUPPORTED(".short 0xf20f,0x1f20 @ addw pc, pc, #0x120")
TEST_UNSUPPORTED(".short 0xf20d,0x1f20 @ addw pc, sp, #0x120")
TEST_UNSUPPORTED(".short 0xf20f,0x1d20 @ addw sp, pc, #0x120")
TEST_UNSUPPORTED(".short 0xf200,0x1d20 @ addw sp, r0, #0x120")
TEST_R("subw r0, r",1, VAL1,", #0x123")
TEST( "subw r14, sp, #0xf5a")
TEST( "subw sp, sp, #0x20")
TEST( "subw r7, pc, #0x888")
TEST_UNSUPPORTED(".short 0xf2af,0x1f20 @ subw pc, pc, #0x120")
TEST_UNSUPPORTED(".short 0xf2ad,0x1f20 @ subw pc, sp, #0x120")
TEST_UNSUPPORTED(".short 0xf2af,0x1d20 @ subw sp, pc, #0x120")
TEST_UNSUPPORTED(".short 0xf2a0,0x1d20 @ subw sp, r0, #0x120")
TEST("movw r0, #0")
TEST("movw r0, #0xffff")
TEST("movw lr, #0xffff")
TEST_UNSUPPORTED(".short 0xf240,0x0d00 @ movw sp, #0")
TEST_UNSUPPORTED(".short 0xf240,0x0f00 @ movw pc, #0")
TEST_R("movt r",0, VAL1,", #0")
TEST_R("movt r",0, VAL2,", #0xffff")
TEST_R("movt r",14,VAL1,", #0xffff")
TEST_UNSUPPORTED(".short 0xf2c0,0x0d00 @ movt sp, #0")
TEST_UNSUPPORTED(".short 0xf2c0,0x0f00 @ movt pc, #0")
TEST_R( "ssat r0, #24, r",0, VAL1,"")
TEST_R( "ssat r14, #24, r",12, VAL2,"")
TEST_R( "ssat r0, #24, r",0, VAL1,", lsl #8")
TEST_R( "ssat r14, #24, r",12, VAL2,", asr #8")
TEST_UNSUPPORTED(".short 0xf30c,0x0d17 @ ssat sp, #24, r12")
TEST_UNSUPPORTED(".short 0xf30c,0x0f17 @ ssat pc, #24, r12")
TEST_UNSUPPORTED(".short 0xf30d,0x0c17 @ ssat r12, #24, sp")
TEST_UNSUPPORTED(".short 0xf30f,0x0c17 @ ssat r12, #24, pc")
TEST_R( "usat r0, #24, r",0, VAL1,"")
TEST_R( "usat r14, #24, r",12, VAL2,"")
TEST_R( "usat r0, #24, r",0, VAL1,", lsl #8")
TEST_R( "usat r14, #24, r",12, VAL2,", asr #8")
TEST_UNSUPPORTED(".short 0xf38c,0x0d17 @ usat sp, #24, r12")
TEST_UNSUPPORTED(".short 0xf38c,0x0f17 @ usat pc, #24, r12")
TEST_UNSUPPORTED(".short 0xf38d,0x0c17 @ usat r12, #24, sp")
TEST_UNSUPPORTED(".short 0xf38f,0x0c17 @ usat r12, #24, pc")
TEST_R( "ssat16 r0, #12, r",0, HH1,"")
TEST_R( "ssat16 r14, #12, r",12, HH2,"")
TEST_UNSUPPORTED(".short 0xf32c,0x0d0b @ ssat16 sp, #12, r12")
TEST_UNSUPPORTED(".short 0xf32c,0x0f0b @ ssat16 pc, #12, r12")
TEST_UNSUPPORTED(".short 0xf32d,0x0c0b @ ssat16 r12, #12, sp")
TEST_UNSUPPORTED(".short 0xf32f,0x0c0b @ ssat16 r12, #12, pc")
TEST_R( "usat16 r0, #12, r",0, HH1,"")
TEST_R( "usat16 r14, #12, r",12, HH2,"")
TEST_UNSUPPORTED(".short 0xf3ac,0x0d0b @ usat16 sp, #12, r12")
TEST_UNSUPPORTED(".short 0xf3ac,0x0f0b @ usat16 pc, #12, r12")
TEST_UNSUPPORTED(".short 0xf3ad,0x0c0b @ usat16 r12, #12, sp")
TEST_UNSUPPORTED(".short 0xf3af,0x0c0b @ usat16 r12, #12, pc")
TEST_R( "sbfx r0, r",0 , VAL1,", #0, #31")
TEST_R( "sbfx r14, r",12, VAL2,", #8, #16")
TEST_R( "sbfx r4, r",10, VAL1,", #16, #15")
TEST_UNSUPPORTED(".short 0xf34c,0x2d0f @ sbfx sp, r12, #8, #16")
TEST_UNSUPPORTED(".short 0xf34c,0x2f0f @ sbfx pc, r12, #8, #16")
TEST_UNSUPPORTED(".short 0xf34d,0x2c0f @ sbfx r12, sp, #8, #16")
TEST_UNSUPPORTED(".short 0xf34f,0x2c0f @ sbfx r12, pc, #8, #16")
TEST_R( "ubfx r0, r",0 , VAL1,", #0, #31")
TEST_R( "ubfx r14, r",12, VAL2,", #8, #16")
TEST_R( "ubfx r4, r",10, VAL1,", #16, #15")
TEST_UNSUPPORTED(".short 0xf3cc,0x2d0f @ ubfx sp, r12, #8, #16")
TEST_UNSUPPORTED(".short 0xf3cc,0x2f0f @ ubfx pc, r12, #8, #16")
TEST_UNSUPPORTED(".short 0xf3cd,0x2c0f @ ubfx r12, sp, #8, #16")
TEST_UNSUPPORTED(".short 0xf3cf,0x2c0f @ ubfx r12, pc, #8, #16")
TEST_R( "bfc r",0, VAL1,", #4, #20")
TEST_R( "bfc r",14,VAL2,", #4, #20")
TEST_R( "bfc r",7, VAL1,", #0, #31")
TEST_R( "bfc r",8, VAL2,", #0, #31")
TEST_UNSUPPORTED(".short 0xf36f,0x0d1e @ bfc sp, #0, #31")
TEST_UNSUPPORTED(".short 0xf36f,0x0f1e @ bfc pc, #0, #31")
TEST_RR( "bfi r",0, VAL1,", r",0 , VAL2,", #0, #31")
TEST_RR( "bfi r",12,VAL1,", r",14 , VAL2,", #4, #20")
TEST_UNSUPPORTED(".short 0xf36e,0x1d17 @ bfi sp, r14, #4, #20")
TEST_UNSUPPORTED(".short 0xf36e,0x1f17 @ bfi pc, r14, #4, #20")
TEST_UNSUPPORTED(".short 0xf36d,0x1e17 @ bfi r14, sp, #4, #20")
TEST_GROUP("Branches and miscellaneous control")
CONDITION_INSTRUCTIONS(22,
TEST_BF("beq.w 2f")
TEST_BB("bne.w 2b")
TEST_BF("bgt.w 2f")
TEST_BB("blt.w 2b")
TEST_BF_X("bpl.w 2f", SPACE_0x1000)
)
TEST_UNSUPPORTED("msr cpsr, r0")
TEST_UNSUPPORTED("msr cpsr_f, r1")
TEST_UNSUPPORTED("msr spsr, r2")
TEST_UNSUPPORTED("cpsie.w i")
TEST_UNSUPPORTED("cpsid.w i")
TEST_UNSUPPORTED("cps 0x13")
TEST_SUPPORTED("yield.w")
TEST("sev.w")
TEST("nop.w")
TEST("wfi.w")
TEST_SUPPORTED("wfe.w")
TEST_UNSUPPORTED("dbg.w #0")
TEST_UNSUPPORTED("clrex")
TEST_UNSUPPORTED("dsb")
TEST_UNSUPPORTED("dmb")
TEST_UNSUPPORTED("isb")
TEST_UNSUPPORTED("bxj r0")
TEST_UNSUPPORTED("subs pc, lr, #4")
TEST("mrs r0, cpsr")
TEST("mrs r14, cpsr")
TEST_UNSUPPORTED(".short 0xf3ef,0x8d00 @ mrs sp, spsr")
TEST_UNSUPPORTED(".short 0xf3ef,0x8f00 @ mrs pc, spsr")
TEST_UNSUPPORTED("mrs r0, spsr")
TEST_UNSUPPORTED("mrs lr, spsr")
TEST_UNSUPPORTED(".short 0xf7f0,0x8000 @ smc #0")
TEST_UNSUPPORTED(".short 0xf7f0,0xa000 @ undefeined")
TEST_BF( "b.w 2f")
TEST_BB( "b.w 2b")
TEST_BF_X("b.w 2f", SPACE_0x1000)
TEST_BF( "bl.w 2f")
TEST_BB( "bl.w 2b")
TEST_BB_X("bl.w 2b", SPACE_0x1000)
TEST_X( "blx __dummy_arm_subroutine",
".arm \n\t"
".align \n\t"
".type __dummy_arm_subroutine, %%function \n\t"
"__dummy_arm_subroutine: \n\t"
"mov r0, pc \n\t"
"bx lr \n\t"
".thumb \n\t"
)
TEST( "blx __dummy_arm_subroutine")
TEST_GROUP("Store single data item")
#define SINGLE_STORE(size) \
TEST_RP( "str"size" r",0, VAL1,", [r",11,-1024,", #1024]") \
TEST_RP( "str"size" r",14,VAL2,", [r",1, -1024,", #1080]") \
TEST_RP( "str"size" r",0, VAL1,", [r",11,256, ", #-120]") \
TEST_RP( "str"size" r",14,VAL2,", [r",1, 256, ", #-128]") \
TEST_RP( "str"size" r",0, VAL1,", [r",11,24, "], #120") \
TEST_RP( "str"size" r",14,VAL2,", [r",1, 24, "], #128") \
TEST_RP( "str"size" r",0, VAL1,", [r",11,24, "], #-120") \
TEST_RP( "str"size" r",14,VAL2,", [r",1, 24, "], #-128") \
TEST_RP( "str"size" r",0, VAL1,", [r",11,24, ", #120]!") \
TEST_RP( "str"size" r",14,VAL2,", [r",1, 24, ", #128]!") \
TEST_RP( "str"size" r",0, VAL1,", [r",11,256, ", #-120]!") \
TEST_RP( "str"size" r",14,VAL2,", [r",1, 256, ", #-128]!") \
TEST_RPR("str"size".w r",0, VAL1,", [r",1, 0,", r",2, 4,"]") \
TEST_RPR("str"size" r",14,VAL2,", [r",10,0,", r",11,4,", lsl #1]") \
TEST_R( "str"size".w r",7, VAL1,", [sp, #24]") \
TEST_RP( "str"size".w r",0, VAL2,", [r",0,0, "]") \
TEST_UNSUPPORTED("str"size"t r0, [r1, #4]")
SINGLE_STORE("b")
SINGLE_STORE("h")
SINGLE_STORE("")
TEST("str sp, [sp]")
TEST_UNSUPPORTED(".short 0xf8cf,0xe000 @ str r14, [pc]")
TEST_UNSUPPORTED(".short 0xf8ce,0xf000 @ str pc, [r14]")
TEST_GROUP("Advanced SIMD element or structure load/store instructions")
TEST_UNSUPPORTED(".short 0xf900,0x0000")
TEST_UNSUPPORTED(".short 0xf92f,0xffff")
TEST_UNSUPPORTED(".short 0xf980,0x0000")
TEST_UNSUPPORTED(".short 0xf9ef,0xffff")
TEST_GROUP("Load single data item and memory hints")
#define SINGLE_LOAD(size) \
TEST_P( "ldr"size" r0, [r",11,-1024, ", #1024]") \
TEST_P( "ldr"size" r14, [r",1, -1024,", #1080]") \
TEST_P( "ldr"size" r0, [r",11,256, ", #-120]") \
TEST_P( "ldr"size" r14, [r",1, 256, ", #-128]") \
TEST_P( "ldr"size" r0, [r",11,24, "], #120") \
TEST_P( "ldr"size" r14, [r",1, 24, "], #128") \
TEST_P( "ldr"size" r0, [r",11,24, "], #-120") \
TEST_P( "ldr"size" r14, [r",1,24, "], #-128") \
TEST_P( "ldr"size" r0, [r",11,24, ", #120]!") \
TEST_P( "ldr"size" r14, [r",1, 24, ", #128]!") \
TEST_P( "ldr"size" r0, [r",11,256, ", #-120]!") \
TEST_P( "ldr"size" r14, [r",1, 256, ", #-128]!") \
TEST_PR("ldr"size".w r0, [r",1, 0,", r",2, 4,"]") \
TEST_PR("ldr"size" r14, [r",10,0,", r",11,4,", lsl #1]") \
TEST_X( "ldr"size".w r0, 3f", \
".align 3 \n\t" \
"3: .word "__stringify(VAL1)) \
TEST_X( "ldr"size".w r14, 3f", \
".align 3 \n\t" \
"3: .word "__stringify(VAL2)) \
TEST( "ldr"size".w r7, 3b") \
TEST( "ldr"size".w r7, [sp, #24]") \
TEST_P( "ldr"size".w r0, [r",0,0, "]") \
TEST_UNSUPPORTED("ldr"size"t r0, [r1, #4]")
SINGLE_LOAD("b")
SINGLE_LOAD("sb")
SINGLE_LOAD("h")
SINGLE_LOAD("sh")
SINGLE_LOAD("")
TEST_BF_P("ldr pc, [r",14, 15*4,"]")
TEST_P( "ldr sp, [r",14, 13*4,"]")
TEST_BF_R("ldr pc, [sp, r",14, 15*4,"]")
TEST_R( "ldr sp, [sp, r",14, 13*4,"]")
TEST_THUMB_TO_ARM_INTERWORK_P("ldr pc, [r",0,0,", #15*4]")
TEST_SUPPORTED("ldr sp, 99f")
TEST_SUPPORTED("ldr pc, 99f")
TEST_UNSUPPORTED(".short 0xf854,0x700d @ ldr r7, [r4, sp]")
TEST_UNSUPPORTED(".short 0xf854,0x700f @ ldr r7, [r4, pc]")
TEST_UNSUPPORTED(".short 0xf814,0x700d @ ldrb r7, [r4, sp]")
TEST_UNSUPPORTED(".short 0xf814,0x700f @ ldrb r7, [r4, pc]")
TEST_UNSUPPORTED(".short 0xf89f,0xd004 @ ldrb sp, 99f")
TEST_UNSUPPORTED(".short 0xf814,0xd008 @ ldrb sp, [r4, r8]")
TEST_UNSUPPORTED(".short 0xf894,0xd000 @ ldrb sp, [r4]")
TEST_UNSUPPORTED(".short 0xf860,0x0000") /* Unallocated space */
TEST_UNSUPPORTED(".short 0xf9ff,0xffff") /* Unallocated space */
TEST_UNSUPPORTED(".short 0xf950,0x0000") /* Unallocated space */
TEST_UNSUPPORTED(".short 0xf95f,0xffff") /* Unallocated space */
TEST_UNSUPPORTED(".short 0xf800,0x0800") /* Unallocated space */
TEST_UNSUPPORTED(".short 0xf97f,0xfaff") /* Unallocated space */
TEST( "pli [pc, #4]")
TEST( "pli [pc, #-4]")
TEST( "pld [pc, #4]")
TEST( "pld [pc, #-4]")
TEST_P( "pld [r",0,-1024,", #1024]")
TEST( ".short 0xf8b0,0xf400 @ pldw [r0, #1024]")
TEST_P( "pli [r",4, 0b,", #1024]")
TEST_P( "pld [r",7, 120,", #-120]")
TEST( ".short 0xf837,0xfc78 @ pldw [r7, #-120]")
TEST_P( "pli [r",11,120,", #-120]")
TEST( "pld [sp, #0]")
TEST_PR("pld [r",7, 24, ", r",0, 16,"]")
TEST_PR("pld [r",8, 24, ", r",12,16,", lsl #3]")
TEST_SUPPORTED(".short 0xf837,0xf000 @ pldw [r7, r0]")
TEST_SUPPORTED(".short 0xf838,0xf03c @ pldw [r8, r12, lsl #3]");
TEST_RR("pli [r",12,0b,", r",0, 16,"]")
TEST_RR("pli [r",0, 0b,", r",12,16,", lsl #3]")
TEST_R( "pld [sp, r",1, 16,"]")
TEST_UNSUPPORTED(".short 0xf817,0xf00d @pld [r7, sp]")
TEST_UNSUPPORTED(".short 0xf817,0xf00f @pld [r7, pc]")
TEST_GROUP("Data-processing (register)")
#define SHIFTS32(op) \
TEST_RR(op" r0, r",1, VAL1,", r",2, 3, "") \
TEST_RR(op" r14, r",12,VAL2,", r",11,10,"")
SHIFTS32("lsl")
SHIFTS32("lsls")
SHIFTS32("lsr")
SHIFTS32("lsrs")
SHIFTS32("asr")
SHIFTS32("asrs")
SHIFTS32("ror")
SHIFTS32("rors")
TEST_UNSUPPORTED(".short 0xfa01,0xff02 @ lsl pc, r1, r2")
TEST_UNSUPPORTED(".short 0xfa01,0xfd02 @ lsl sp, r1, r2")
TEST_UNSUPPORTED(".short 0xfa0f,0xf002 @ lsl r0, pc, r2")
TEST_UNSUPPORTED(".short 0xfa0d,0xf002 @ lsl r0, sp, r2")
TEST_UNSUPPORTED(".short 0xfa01,0xf00f @ lsl r0, r1, pc")
TEST_UNSUPPORTED(".short 0xfa01,0xf00d @ lsl r0, r1, sp")
TEST_RR( "sxtah r0, r",0, HH1,", r",1, HH2,"")
TEST_RR( "sxtah r14,r",12, HH2,", r",10,HH1,", ror #8")
TEST_R( "sxth r8, r",7, HH1,"")
TEST_UNSUPPORTED(".short 0xfa0f,0xff87 @ sxth pc, r7");
TEST_UNSUPPORTED(".short 0xfa0f,0xfd87 @ sxth sp, r7");
TEST_UNSUPPORTED(".short 0xfa0f,0xf88f @ sxth r8, pc");
TEST_UNSUPPORTED(".short 0xfa0f,0xf88d @ sxth r8, sp");
TEST_RR( "uxtah r0, r",0, HH1,", r",1, HH2,"")
TEST_RR( "uxtah r14,r",12, HH2,", r",10,HH1,", ror #8")
TEST_R( "uxth r8, r",7, HH1,"")
TEST_RR( "sxtab16 r0, r",0, HH1,", r",1, HH2,"")
TEST_RR( "sxtab16 r14,r",12, HH2,", r",10,HH1,", ror #8")
TEST_R( "sxtb16 r8, r",7, HH1,"")
TEST_RR( "uxtab16 r0, r",0, HH1,", r",1, HH2,"")
TEST_RR( "uxtab16 r14,r",12, HH2,", r",10,HH1,", ror #8")
TEST_R( "uxtb16 r8, r",7, HH1,"")
TEST_RR( "sxtab r0, r",0, HH1,", r",1, HH2,"")
TEST_RR( "sxtab r14,r",12, HH2,", r",10,HH1,", ror #8")
TEST_R( "sxtb r8, r",7, HH1,"")
TEST_RR( "uxtab r0, r",0, HH1,", r",1, HH2,"")
TEST_RR( "uxtab r14,r",12, HH2,", r",10,HH1,", ror #8")
TEST_R( "uxtb r8, r",7, HH1,"")
TEST_UNSUPPORTED(".short 0xfa60,0x00f0")
TEST_UNSUPPORTED(".short 0xfa7f,0xffff")
#define PARALLEL_ADD_SUB(op) \
TEST_RR( op"add16 r0, r",0, HH1,", r",1, HH2,"") \
TEST_RR( op"add16 r14, r",12,HH2,", r",10,HH1,"") \
TEST_RR( op"asx r0, r",0, HH1,", r",1, HH2,"") \
TEST_RR( op"asx r14, r",12,HH2,", r",10,HH1,"") \
TEST_RR( op"sax r0, r",0, HH1,", r",1, HH2,"") \
TEST_RR( op"sax r14, r",12,HH2,", r",10,HH1,"") \
TEST_RR( op"sub16 r0, r",0, HH1,", r",1, HH2,"") \
TEST_RR( op"sub16 r14, r",12,HH2,", r",10,HH1,"") \
TEST_RR( op"add8 r0, r",0, HH1,", r",1, HH2,"") \
TEST_RR( op"add8 r14, r",12,HH2,", r",10,HH1,"") \
TEST_RR( op"sub8 r0, r",0, HH1,", r",1, HH2,"") \
TEST_RR( op"sub8 r14, r",12,HH2,", r",10,HH1,"")
TEST_GROUP("Parallel addition and subtraction, signed")
PARALLEL_ADD_SUB("s")
PARALLEL_ADD_SUB("q")
PARALLEL_ADD_SUB("sh")
TEST_GROUP("Parallel addition and subtraction, unsigned")
PARALLEL_ADD_SUB("u")
PARALLEL_ADD_SUB("uq")
PARALLEL_ADD_SUB("uh")
TEST_GROUP("Miscellaneous operations")
TEST_RR("qadd r0, r",1, VAL1,", r",2, VAL2,"")
TEST_RR("qadd lr, r",9, VAL2,", r",8, VAL1,"")
TEST_RR("qsub r0, r",1, VAL1,", r",2, VAL2,"")
TEST_RR("qsub lr, r",9, VAL2,", r",8, VAL1,"")
TEST_RR("qdadd r0, r",1, VAL1,", r",2, VAL2,"")
TEST_RR("qdadd lr, r",9, VAL2,", r",8, VAL1,"")
TEST_RR("qdsub r0, r",1, VAL1,", r",2, VAL2,"")
TEST_RR("qdsub lr, r",9, VAL2,", r",8, VAL1,"")
TEST_R("rev.w r0, r",0, VAL1,"")
TEST_R("rev r14, r",12, VAL2,"")
TEST_R("rev16.w r0, r",0, VAL1,"")
TEST_R("rev16 r14, r",12, VAL2,"")
TEST_R("rbit r0, r",0, VAL1,"")
TEST_R("rbit r14, r",12, VAL2,"")
TEST_R("revsh.w r0, r",0, VAL1,"")
TEST_R("revsh r14, r",12, VAL2,"")
TEST_UNSUPPORTED(".short 0xfa9c,0xff8c @ rev pc, r12");
TEST_UNSUPPORTED(".short 0xfa9c,0xfd8c @ rev sp, r12");
TEST_UNSUPPORTED(".short 0xfa9f,0xfe8f @ rev r14, pc");
TEST_UNSUPPORTED(".short 0xfa9d,0xfe8d @ rev r14, sp");
TEST_RR("sel r0, r",0, VAL1,", r",1, VAL2,"")
TEST_RR("sel r14, r",12,VAL1,", r",10, VAL2,"")
TEST_R("clz r0, r",0, 0x0,"")
TEST_R("clz r7, r",14,0x1,"")
TEST_R("clz lr, r",7, 0xffffffff,"")
TEST_UNSUPPORTED(".short 0xfa80,0xf030") /* Unallocated space */
TEST_UNSUPPORTED(".short 0xfaff,0xff7f") /* Unallocated space */
TEST_UNSUPPORTED(".short 0xfab0,0xf000") /* Unallocated space */
TEST_UNSUPPORTED(".short 0xfaff,0xff7f") /* Unallocated space */
TEST_GROUP("Multiply, multiply accumulate, and absolute difference operations")
TEST_RR( "mul r0, r",1, VAL1,", r",2, VAL2,"")
TEST_RR( "mul r7, r",8, VAL2,", r",9, VAL2,"")
TEST_UNSUPPORTED(".short 0xfb08,0xff09 @ mul pc, r8, r9")
TEST_UNSUPPORTED(".short 0xfb08,0xfd09 @ mul sp, r8, r9")
TEST_UNSUPPORTED(".short 0xfb0f,0xf709 @ mul r7, pc, r9")
TEST_UNSUPPORTED(".short 0xfb0d,0xf709 @ mul r7, sp, r9")
TEST_UNSUPPORTED(".short 0xfb08,0xf70f @ mul r7, r8, pc")
TEST_UNSUPPORTED(".short 0xfb08,0xf70d @ mul r7, r8, sp")
TEST_RRR( "mla r0, r",1, VAL1,", r",2, VAL2,", r",3, VAL3,"")
TEST_RRR( "mla r7, r",8, VAL3,", r",9, VAL1,", r",10, VAL2,"")
TEST_UNSUPPORTED(".short 0xfb08,0xaf09 @ mla pc, r8, r9, r10");
TEST_UNSUPPORTED(".short 0xfb08,0xad09 @ mla sp, r8, r9, r10");
TEST_UNSUPPORTED(".short 0xfb0f,0xa709 @ mla r7, pc, r9, r10");
TEST_UNSUPPORTED(".short 0xfb0d,0xa709 @ mla r7, sp, r9, r10");
TEST_UNSUPPORTED(".short 0xfb08,0xa70f @ mla r7, r8, pc, r10");
TEST_UNSUPPORTED(".short 0xfb08,0xa70d @ mla r7, r8, sp, r10");
TEST_UNSUPPORTED(".short 0xfb08,0xd709 @ mla r7, r8, r9, sp");
TEST_RRR( "mls r0, r",1, VAL1,", r",2, VAL2,", r",3, VAL3,"")
TEST_RRR( "mls r7, r",8, VAL3,", r",9, VAL1,", r",10, VAL2,"")
TEST_RRR( "smlabb r0, r",1, VAL1,", r",2, VAL2,", r",3, VAL3,"")
TEST_RRR( "smlabb r7, r",8, VAL3,", r",9, VAL1,", r",10, VAL2,"")
TEST_RRR( "smlatb r0, r",1, VAL1,", r",2, VAL2,", r",3, VAL3,"")
TEST_RRR( "smlatb r7, r",8, VAL3,", r",9, VAL1,", r",10, VAL2,"")
TEST_RRR( "smlabt r0, r",1, VAL1,", r",2, VAL2,", r",3, VAL3,"")
TEST_RRR( "smlabt r7, r",8, VAL3,", r",9, VAL1,", r",10, VAL2,"")
TEST_RRR( "smlatt r0, r",1, VAL1,", r",2, VAL2,", r",3, VAL3,"")
TEST_RRR( "smlatt r7, r",8, VAL3,", r",9, VAL1,", r",10, VAL2,"")
TEST_RR( "smulbb r0, r",1, VAL1,", r",2, VAL2,"")
TEST_RR( "smulbb r7, r",8, VAL3,", r",9, VAL1,"")
TEST_RR( "smultb r0, r",1, VAL1,", r",2, VAL2,"")
TEST_RR( "smultb r7, r",8, VAL3,", r",9, VAL1,"")
TEST_RR( "smulbt r0, r",1, VAL1,", r",2, VAL2,"")
TEST_RR( "smulbt r7, r",8, VAL3,", r",9, VAL1,"")
TEST_RR( "smultt r0, r",1, VAL1,", r",2, VAL2,"")
TEST_RR( "smultt r7, r",8, VAL3,", r",9, VAL1,"")
TEST_RRR( "smlad r0, r",0, HH1,", r",1, HH2,", r",2, VAL1,"")
TEST_RRR( "smlad r14, r",12,HH2,", r",10,HH1,", r",8, VAL2,"")
TEST_RRR( "smladx r0, r",0, HH1,", r",1, HH2,", r",2, VAL1,"")
TEST_RRR( "smladx r14, r",12,HH2,", r",10,HH1,", r",8, VAL2,"")
TEST_RR( "smuad r0, r",0, HH1,", r",1, HH2,"")
TEST_RR( "smuad r14, r",12,HH2,", r",10,HH1,"")
TEST_RR( "smuadx r0, r",0, HH1,", r",1, HH2,"")
TEST_RR( "smuadx r14, r",12,HH2,", r",10,HH1,"")
TEST_RRR( "smlawb r0, r",1, VAL1,", r",2, VAL2,", r",3, VAL3,"")
TEST_RRR( "smlawb r7, r",8, VAL3,", r",9, VAL1,", r",10, VAL2,"")
TEST_RRR( "smlawt r0, r",1, VAL1,", r",2, VAL2,", r",3, VAL3,"")
TEST_RRR( "smlawt r7, r",8, VAL3,", r",9, VAL1,", r",10, VAL2,"")
TEST_RR( "smulwb r0, r",1, VAL1,", r",2, VAL2,"")
TEST_RR( "smulwb r7, r",8, VAL3,", r",9, VAL1,"")
TEST_RR( "smulwt r0, r",1, VAL1,", r",2, VAL2,"")
TEST_RR( "smulwt r7, r",8, VAL3,", r",9, VAL1,"")
TEST_RRR( "smlsd r0, r",0, HH1,", r",1, HH2,", r",2, VAL1,"")
TEST_RRR( "smlsd r14, r",12,HH2,", r",10,HH1,", r",8, VAL2,"")
TEST_RRR( "smlsdx r0, r",0, HH1,", r",1, HH2,", r",2, VAL1,"")
TEST_RRR( "smlsdx r14, r",12,HH2,", r",10,HH1,", r",8, VAL2,"")
TEST_RR( "smusd r0, r",0, HH1,", r",1, HH2,"")
TEST_RR( "smusd r14, r",12,HH2,", r",10,HH1,"")
TEST_RR( "smusdx r0, r",0, HH1,", r",1, HH2,"")
TEST_RR( "smusdx r14, r",12,HH2,", r",10,HH1,"")
TEST_RRR( "smmla r0, r",0, VAL1,", r",1, VAL2,", r",2, VAL1,"")
TEST_RRR( "smmla r14, r",12,VAL2,", r",10,VAL1,", r",8, VAL2,"")
TEST_RRR( "smmlar r0, r",0, VAL1,", r",1, VAL2,", r",2, VAL1,"")
TEST_RRR( "smmlar r14, r",12,VAL2,", r",10,VAL1,", r",8, VAL2,"")
TEST_RR( "smmul r0, r",0, VAL1,", r",1, VAL2,"")
TEST_RR( "smmul r14, r",12,VAL2,", r",10,VAL1,"")
TEST_RR( "smmulr r0, r",0, VAL1,", r",1, VAL2,"")
TEST_RR( "smmulr r14, r",12,VAL2,", r",10,VAL1,"")
TEST_RRR( "smmls r0, r",0, VAL1,", r",1, VAL2,", r",2, VAL1,"")
TEST_RRR( "smmls r14, r",12,VAL2,", r",10,VAL1,", r",8, VAL2,"")
TEST_RRR( "smmlsr r0, r",0, VAL1,", r",1, VAL2,", r",2, VAL1,"")
TEST_RRR( "smmlsr r14, r",12,VAL2,", r",10,VAL1,", r",8, VAL2,"")
TEST_RRR( "usada8 r0, r",0, VAL1,", r",1, VAL2,", r",2, VAL3,"")
TEST_RRR( "usada8 r14, r",12,VAL2,", r",10,VAL1,", r",8, VAL3,"")
TEST_RR( "usad8 r0, r",0, VAL1,", r",1, VAL2,"")
TEST_RR( "usad8 r14, r",12,VAL2,", r",10,VAL1,"")
TEST_UNSUPPORTED(".short 0xfb00,0xf010") /* Unallocated space */
TEST_UNSUPPORTED(".short 0xfb0f,0xff1f") /* Unallocated space */
TEST_UNSUPPORTED(".short 0xfb70,0xf010") /* Unallocated space */
TEST_UNSUPPORTED(".short 0xfb7f,0xff1f") /* Unallocated space */
TEST_UNSUPPORTED(".short 0xfb70,0x0010") /* Unallocated space */
TEST_UNSUPPORTED(".short 0xfb7f,0xff1f") /* Unallocated space */
TEST_GROUP("Long multiply, long multiply accumulate, and divide")
TEST_RR( "smull r0, r1, r",2, VAL1,", r",3, VAL2,"")
TEST_RR( "smull r7, r8, r",9, VAL2,", r",10, VAL1,"")
TEST_UNSUPPORTED(".short 0xfb89,0xf80a @ smull pc, r8, r9, r10");
TEST_UNSUPPORTED(".short 0xfb89,0xd80a @ smull sp, r8, r9, r10");
TEST_UNSUPPORTED(".short 0xfb89,0x7f0a @ smull r7, pc, r9, r10");
TEST_UNSUPPORTED(".short 0xfb89,0x7d0a @ smull r7, sp, r9, r10");
TEST_UNSUPPORTED(".short 0xfb8f,0x780a @ smull r7, r8, pc, r10");
TEST_UNSUPPORTED(".short 0xfb8d,0x780a @ smull r7, r8, sp, r10");
TEST_UNSUPPORTED(".short 0xfb89,0x780f @ smull r7, r8, r9, pc");
TEST_UNSUPPORTED(".short 0xfb89,0x780d @ smull r7, r8, r9, sp");
TEST_RR( "umull r0, r1, r",2, VAL1,", r",3, VAL2,"")
TEST_RR( "umull r7, r8, r",9, VAL2,", r",10, VAL1,"")
TEST_RRRR( "smlal r",0, VAL1,", r",1, VAL2,", r",2, VAL3,", r",3, VAL4)
TEST_RRRR( "smlal r",8, VAL4,", r",9, VAL1,", r",10,VAL2,", r",11,VAL3)
TEST_RRRR( "smlalbb r",0, VAL1,", r",1, VAL2,", r",2, VAL3,", r",3, VAL4)
TEST_RRRR( "smlalbb r",8, VAL4,", r",9, VAL1,", r",10,VAL2,", r",11,VAL3)
TEST_RRRR( "smlalbt r",0, VAL1,", r",1, VAL2,", r",2, VAL3,", r",3, VAL4)
TEST_RRRR( "smlalbt r",8, VAL4,", r",9, VAL1,", r",10,VAL2,", r",11,VAL3)
TEST_RRRR( "smlaltb r",0, VAL1,", r",1, VAL2,", r",2, VAL3,", r",3, VAL4)
TEST_RRRR( "smlaltb r",8, VAL4,", r",9, VAL1,", r",10,VAL2,", r",11,VAL3)
TEST_RRRR( "smlaltt r",0, VAL1,", r",1, VAL2,", r",2, VAL3,", r",3, VAL4)
TEST_RRRR( "smlaltt r",8, VAL4,", r",9, VAL1,", r",10,VAL2,", r",11,VAL3)
TEST_RRRR( "smlald r",0, VAL1,", r",1, VAL2, ", r",0, HH1,", r",1, HH2)
TEST_RRRR( "smlald r",11,VAL2,", r",10,VAL1, ", r",9, HH2,", r",8, HH1)
TEST_RRRR( "smlaldx r",0, VAL1,", r",1, VAL2, ", r",0, HH1,", r",1, HH2)
TEST_RRRR( "smlaldx r",11,VAL2,", r",10,VAL1, ", r",9, HH2,", r",8, HH1)
TEST_RRRR( "smlsld r",0, VAL1,", r",1, VAL2, ", r",0, HH1,", r",1, HH2)
TEST_RRRR( "smlsld r",11,VAL2,", r",10,VAL1, ", r",9, HH2,", r",8, HH1)
TEST_RRRR( "smlsldx r",0, VAL1,", r",1, VAL2, ", r",0, HH1,", r",1, HH2)
TEST_RRRR( "smlsldx r",11,VAL2,", r",10,VAL1, ", r",9, HH2,", r",8, HH1)
TEST_RRRR( "umlal r",0, VAL1,", r",1, VAL2,", r",2, VAL3,", r",3, VAL4)
TEST_RRRR( "umlal r",8, VAL4,", r",9, VAL1,", r",10,VAL2,", r",11,VAL3)
TEST_RRRR( "umaal r",0, VAL1,", r",1, VAL2,", r",2, VAL3,", r",3, VAL4)
TEST_RRRR( "umaal r",8, VAL4,", r",9, VAL1,", r",10,VAL2,", r",11,VAL3)
TEST_GROUP("Coprocessor instructions")
TEST_UNSUPPORTED(".short 0xfc00,0x0000")
TEST_UNSUPPORTED(".short 0xffff,0xffff")
TEST_GROUP("Testing instructions in IT blocks")
TEST_ITBLOCK("sub.w r0, r0")
verbose("\n");
}
| gpl-2.0 |
tweez/kernel-msm | net/rxrpc/ar-connevent.c | 12287 | 9243 | /* connection-level event handling
*
* Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* 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.
*/
#include <linux/module.h>
#include <linux/net.h>
#include <linux/skbuff.h>
#include <linux/errqueue.h>
#include <linux/udp.h>
#include <linux/in.h>
#include <linux/in6.h>
#include <linux/icmp.h>
#include <net/sock.h>
#include <net/af_rxrpc.h>
#include <net/ip.h>
#include "ar-internal.h"
/*
* pass a connection-level abort onto all calls on that connection
*/
static void rxrpc_abort_calls(struct rxrpc_connection *conn, int state,
u32 abort_code)
{
struct rxrpc_call *call;
struct rb_node *p;
_enter("{%d},%x", conn->debug_id, abort_code);
read_lock_bh(&conn->lock);
for (p = rb_first(&conn->calls); p; p = rb_next(p)) {
call = rb_entry(p, struct rxrpc_call, conn_node);
write_lock(&call->state_lock);
if (call->state <= RXRPC_CALL_COMPLETE) {
call->state = state;
call->abort_code = abort_code;
if (state == RXRPC_CALL_LOCALLY_ABORTED)
set_bit(RXRPC_CALL_CONN_ABORT, &call->events);
else
set_bit(RXRPC_CALL_RCVD_ABORT, &call->events);
rxrpc_queue_call(call);
}
write_unlock(&call->state_lock);
}
read_unlock_bh(&conn->lock);
_leave("");
}
/*
* generate a connection-level abort
*/
static int rxrpc_abort_connection(struct rxrpc_connection *conn,
u32 error, u32 abort_code)
{
struct rxrpc_header hdr;
struct msghdr msg;
struct kvec iov[2];
__be32 word;
size_t len;
int ret;
_enter("%d,,%u,%u", conn->debug_id, error, abort_code);
/* generate a connection-level abort */
spin_lock_bh(&conn->state_lock);
if (conn->state < RXRPC_CONN_REMOTELY_ABORTED) {
conn->state = RXRPC_CONN_LOCALLY_ABORTED;
conn->error = error;
spin_unlock_bh(&conn->state_lock);
} else {
spin_unlock_bh(&conn->state_lock);
_leave(" = 0 [already dead]");
return 0;
}
rxrpc_abort_calls(conn, RXRPC_CALL_LOCALLY_ABORTED, abort_code);
msg.msg_name = &conn->trans->peer->srx.transport.sin;
msg.msg_namelen = sizeof(conn->trans->peer->srx.transport.sin);
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_flags = 0;
hdr.epoch = conn->epoch;
hdr.cid = conn->cid;
hdr.callNumber = 0;
hdr.seq = 0;
hdr.type = RXRPC_PACKET_TYPE_ABORT;
hdr.flags = conn->out_clientflag;
hdr.userStatus = 0;
hdr.securityIndex = conn->security_ix;
hdr._rsvd = 0;
hdr.serviceId = conn->service_id;
word = htonl(abort_code);
iov[0].iov_base = &hdr;
iov[0].iov_len = sizeof(hdr);
iov[1].iov_base = &word;
iov[1].iov_len = sizeof(word);
len = iov[0].iov_len + iov[1].iov_len;
hdr.serial = htonl(atomic_inc_return(&conn->serial));
_proto("Tx CONN ABORT %%%u { %d }", ntohl(hdr.serial), abort_code);
ret = kernel_sendmsg(conn->trans->local->socket, &msg, iov, 2, len);
if (ret < 0) {
_debug("sendmsg failed: %d", ret);
return -EAGAIN;
}
_leave(" = 0");
return 0;
}
/*
* mark a call as being on a now-secured channel
* - must be called with softirqs disabled
*/
static void rxrpc_call_is_secure(struct rxrpc_call *call)
{
_enter("%p", call);
if (call) {
read_lock(&call->state_lock);
if (call->state < RXRPC_CALL_COMPLETE &&
!test_and_set_bit(RXRPC_CALL_SECURED, &call->events))
rxrpc_queue_call(call);
read_unlock(&call->state_lock);
}
}
/*
* connection-level Rx packet processor
*/
static int rxrpc_process_event(struct rxrpc_connection *conn,
struct sk_buff *skb,
u32 *_abort_code)
{
struct rxrpc_skb_priv *sp = rxrpc_skb(skb);
__be32 tmp;
u32 serial;
int loop, ret;
if (conn->state >= RXRPC_CONN_REMOTELY_ABORTED) {
kleave(" = -ECONNABORTED [%u]", conn->state);
return -ECONNABORTED;
}
serial = ntohl(sp->hdr.serial);
_enter("{%d},{%u,%%%u},", conn->debug_id, sp->hdr.type, serial);
switch (sp->hdr.type) {
case RXRPC_PACKET_TYPE_ABORT:
if (skb_copy_bits(skb, 0, &tmp, sizeof(tmp)) < 0)
return -EPROTO;
_proto("Rx ABORT %%%u { ac=%d }", serial, ntohl(tmp));
conn->state = RXRPC_CONN_REMOTELY_ABORTED;
rxrpc_abort_calls(conn, RXRPC_CALL_REMOTELY_ABORTED,
ntohl(tmp));
return -ECONNABORTED;
case RXRPC_PACKET_TYPE_CHALLENGE:
if (conn->security)
return conn->security->respond_to_challenge(
conn, skb, _abort_code);
return -EPROTO;
case RXRPC_PACKET_TYPE_RESPONSE:
if (!conn->security)
return -EPROTO;
ret = conn->security->verify_response(conn, skb, _abort_code);
if (ret < 0)
return ret;
ret = conn->security->init_connection_security(conn);
if (ret < 0)
return ret;
conn->security->prime_packet_security(conn);
read_lock_bh(&conn->lock);
spin_lock(&conn->state_lock);
if (conn->state == RXRPC_CONN_SERVER_CHALLENGING) {
conn->state = RXRPC_CONN_SERVER;
for (loop = 0; loop < RXRPC_MAXCALLS; loop++)
rxrpc_call_is_secure(conn->channels[loop]);
}
spin_unlock(&conn->state_lock);
read_unlock_bh(&conn->lock);
return 0;
default:
_leave(" = -EPROTO [%u]", sp->hdr.type);
return -EPROTO;
}
}
/*
* set up security and issue a challenge
*/
static void rxrpc_secure_connection(struct rxrpc_connection *conn)
{
u32 abort_code;
int ret;
_enter("{%d}", conn->debug_id);
ASSERT(conn->security_ix != 0);
if (!conn->key) {
_debug("set up security");
ret = rxrpc_init_server_conn_security(conn);
switch (ret) {
case 0:
break;
case -ENOENT:
abort_code = RX_CALL_DEAD;
goto abort;
default:
abort_code = RXKADNOAUTH;
goto abort;
}
}
ASSERT(conn->security != NULL);
if (conn->security->issue_challenge(conn) < 0) {
abort_code = RX_CALL_DEAD;
ret = -ENOMEM;
goto abort;
}
_leave("");
return;
abort:
_debug("abort %d, %d", ret, abort_code);
rxrpc_abort_connection(conn, -ret, abort_code);
_leave(" [aborted]");
}
/*
* connection-level event processor
*/
void rxrpc_process_connection(struct work_struct *work)
{
struct rxrpc_connection *conn =
container_of(work, struct rxrpc_connection, processor);
struct sk_buff *skb;
u32 abort_code = RX_PROTOCOL_ERROR;
int ret;
_enter("{%d}", conn->debug_id);
atomic_inc(&conn->usage);
if (test_and_clear_bit(RXRPC_CONN_CHALLENGE, &conn->events)) {
rxrpc_secure_connection(conn);
rxrpc_put_connection(conn);
}
/* go through the conn-level event packets, releasing the ref on this
* connection that each one has when we've finished with it */
while ((skb = skb_dequeue(&conn->rx_queue))) {
ret = rxrpc_process_event(conn, skb, &abort_code);
switch (ret) {
case -EPROTO:
case -EKEYEXPIRED:
case -EKEYREJECTED:
goto protocol_error;
case -EAGAIN:
goto requeue_and_leave;
case -ECONNABORTED:
default:
rxrpc_put_connection(conn);
rxrpc_free_skb(skb);
break;
}
}
out:
rxrpc_put_connection(conn);
_leave("");
return;
requeue_and_leave:
skb_queue_head(&conn->rx_queue, skb);
goto out;
protocol_error:
if (rxrpc_abort_connection(conn, -ret, abort_code) < 0)
goto requeue_and_leave;
rxrpc_put_connection(conn);
rxrpc_free_skb(skb);
_leave(" [EPROTO]");
goto out;
}
/*
* put a packet up for transport-level abort
*/
void rxrpc_reject_packet(struct rxrpc_local *local, struct sk_buff *skb)
{
CHECK_SLAB_OKAY(&local->usage);
if (!atomic_inc_not_zero(&local->usage)) {
printk("resurrected on reject\n");
BUG();
}
skb_queue_tail(&local->reject_queue, skb);
rxrpc_queue_work(&local->rejecter);
}
/*
* reject packets through the local endpoint
*/
void rxrpc_reject_packets(struct work_struct *work)
{
union {
struct sockaddr sa;
struct sockaddr_in sin;
} sa;
struct rxrpc_skb_priv *sp;
struct rxrpc_header hdr;
struct rxrpc_local *local;
struct sk_buff *skb;
struct msghdr msg;
struct kvec iov[2];
size_t size;
__be32 code;
local = container_of(work, struct rxrpc_local, rejecter);
rxrpc_get_local(local);
_enter("%d", local->debug_id);
iov[0].iov_base = &hdr;
iov[0].iov_len = sizeof(hdr);
iov[1].iov_base = &code;
iov[1].iov_len = sizeof(code);
size = sizeof(hdr) + sizeof(code);
msg.msg_name = &sa;
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_flags = 0;
memset(&sa, 0, sizeof(sa));
sa.sa.sa_family = local->srx.transport.family;
switch (sa.sa.sa_family) {
case AF_INET:
msg.msg_namelen = sizeof(sa.sin);
break;
default:
msg.msg_namelen = 0;
break;
}
memset(&hdr, 0, sizeof(hdr));
hdr.type = RXRPC_PACKET_TYPE_ABORT;
while ((skb = skb_dequeue(&local->reject_queue))) {
sp = rxrpc_skb(skb);
switch (sa.sa.sa_family) {
case AF_INET:
sa.sin.sin_port = udp_hdr(skb)->source;
sa.sin.sin_addr.s_addr = ip_hdr(skb)->saddr;
code = htonl(skb->priority);
hdr.epoch = sp->hdr.epoch;
hdr.cid = sp->hdr.cid;
hdr.callNumber = sp->hdr.callNumber;
hdr.serviceId = sp->hdr.serviceId;
hdr.flags = sp->hdr.flags;
hdr.flags ^= RXRPC_CLIENT_INITIATED;
hdr.flags &= RXRPC_CLIENT_INITIATED;
kernel_sendmsg(local->socket, &msg, iov, 2, size);
break;
default:
break;
}
rxrpc_free_skb(skb);
rxrpc_put_local(local);
}
rxrpc_put_local(local);
_leave("");
}
| gpl-2.0 |
Lenovo-Kraft-A6000/android_kernel_lenovo_msm8916 | arch/sh/boards/mach-rsk/devices-rsk7203.c | 12287 | 3199 | /*
* Renesas Technology Europe RSK+ 7203 Support.
*
* Copyright (C) 2008 - 2010 Paul Mundt
*
* 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.
*/
#include <linux/init.h>
#include <linux/types.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/smsc911x.h>
#include <linux/input.h>
#include <linux/gpio.h>
#include <linux/gpio_keys.h>
#include <linux/leds.h>
#include <asm/machvec.h>
#include <asm/io.h>
#include <cpu/sh7203.h>
static struct smsc911x_platform_config smsc911x_config = {
.phy_interface = PHY_INTERFACE_MODE_MII,
.irq_polarity = SMSC911X_IRQ_POLARITY_ACTIVE_LOW,
.irq_type = SMSC911X_IRQ_TYPE_OPEN_DRAIN,
.flags = SMSC911X_USE_32BIT | SMSC911X_SWAP_FIFO,
};
static struct resource smsc911x_resources[] = {
[0] = {
.start = 0x24000000,
.end = 0x240000ff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 64,
.end = 64,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device smsc911x_device = {
.name = "smsc911x",
.id = -1,
.num_resources = ARRAY_SIZE(smsc911x_resources),
.resource = smsc911x_resources,
.dev = {
.platform_data = &smsc911x_config,
},
};
static struct gpio_led rsk7203_gpio_leds[] = {
{
.name = "green",
.gpio = GPIO_PE10,
.active_low = 1,
}, {
.name = "orange",
.default_trigger = "nand-disk",
.gpio = GPIO_PE12,
.active_low = 1,
}, {
.name = "red:timer",
.default_trigger = "timer",
.gpio = GPIO_PC14,
.active_low = 1,
}, {
.name = "red:heartbeat",
.default_trigger = "heartbeat",
.gpio = GPIO_PE11,
.active_low = 1,
},
};
static struct gpio_led_platform_data rsk7203_gpio_leds_info = {
.leds = rsk7203_gpio_leds,
.num_leds = ARRAY_SIZE(rsk7203_gpio_leds),
};
static struct platform_device led_device = {
.name = "leds-gpio",
.id = -1,
.dev = {
.platform_data = &rsk7203_gpio_leds_info,
},
};
static struct gpio_keys_button rsk7203_gpio_keys_table[] = {
{
.code = BTN_0,
.gpio = GPIO_PB0,
.active_low = 1,
.desc = "SW1",
}, {
.code = BTN_1,
.gpio = GPIO_PB1,
.active_low = 1,
.desc = "SW2",
}, {
.code = BTN_2,
.gpio = GPIO_PB2,
.active_low = 1,
.desc = "SW3",
},
};
static struct gpio_keys_platform_data rsk7203_gpio_keys_info = {
.buttons = rsk7203_gpio_keys_table,
.nbuttons = ARRAY_SIZE(rsk7203_gpio_keys_table),
.poll_interval = 50, /* default to 50ms */
};
static struct platform_device keys_device = {
.name = "gpio-keys-polled",
.dev = {
.platform_data = &rsk7203_gpio_keys_info,
},
};
static struct platform_device *rsk7203_devices[] __initdata = {
&smsc911x_device,
&led_device,
&keys_device,
};
static int __init rsk7203_devices_setup(void)
{
/* Select pins for SCIF0 */
gpio_request(GPIO_FN_TXD0, NULL);
gpio_request(GPIO_FN_RXD0, NULL);
/* Setup LAN9118: CS1 in 16-bit Big Endian Mode, IRQ0 at Port B */
__raw_writel(0x36db0400, 0xfffc0008); /* CS1BCR */
gpio_request(GPIO_FN_IRQ0_PB, NULL);
return platform_add_devices(rsk7203_devices,
ARRAY_SIZE(rsk7203_devices));
}
device_initcall(rsk7203_devices_setup);
| gpl-2.0 |
SM-G920P-MM/G920P-MM | arch/sh/boards/mach-landisk/irq.c | 12287 | 1647 | /*
* arch/sh/boards/mach-landisk/irq.c
*
* I-O DATA Device, Inc. LANDISK Support
*
* Copyright (C) 2005-2007 kogiidena
* Copyright (C) 2011 Nobuhiro Iwamatsu
*
* Copyright (C) 2001 Ian da Silva, Jeremy Siegel
* Based largely on io_se.c.
*
* 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.
*/
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <mach-landisk/mach/iodata_landisk.h>
enum {
UNUSED = 0,
PCI_INTA, /* PCI int A */
PCI_INTB, /* PCI int B */
PCI_INTC, /* PCI int C */
PCI_INTD, /* PCI int D */
ATA, /* ATA */
FATA, /* CF */
POWER, /* Power swtich */
BUTTON, /* Button swtich */
};
/* Vectors for LANDISK */
static struct intc_vect vectors_landisk[] __initdata = {
INTC_IRQ(PCI_INTA, IRQ_PCIINTA),
INTC_IRQ(PCI_INTB, IRQ_PCIINTB),
INTC_IRQ(PCI_INTC, IRQ_PCIINTC),
INTC_IRQ(PCI_INTD, IRQ_PCIINTD),
INTC_IRQ(ATA, IRQ_ATA),
INTC_IRQ(FATA, IRQ_FATA),
INTC_IRQ(POWER, IRQ_POWER),
INTC_IRQ(BUTTON, IRQ_BUTTON),
};
/* IRLMSK mask register layout for LANDISK */
static struct intc_mask_reg mask_registers_landisk[] __initdata = {
{ PA_IMASK, 0, 8, /* IRLMSK */
{ BUTTON, POWER, FATA, ATA,
PCI_INTD, PCI_INTC, PCI_INTB, PCI_INTA,
}
},
};
static DECLARE_INTC_DESC(intc_desc_landisk, "landisk", vectors_landisk, NULL,
mask_registers_landisk, NULL, NULL);
/*
* Initialize IRQ setting
*/
void __init init_landisk_IRQ(void)
{
register_intc_controller(&intc_desc_landisk);
__raw_writeb(0x00, PA_PWRINT_CLR);
}
| gpl-2.0 |
MoKee/android_kernel_motorola_olympus | sound/drivers/vx/vx_uer.c | 12799 | 7857 | /*
* Driver for Digigram VX soundcards
*
* IEC958 stuff
*
* Copyright (c) 2002 by Takashi Iwai <tiwai@suse.de>
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/delay.h>
#include <sound/core.h>
#include <sound/vx_core.h>
#include "vx_cmd.h"
/*
* vx_modify_board_clock - tell the board that its clock has been modified
* @sync: DSP needs to resynchronize its FIFO
*/
static int vx_modify_board_clock(struct vx_core *chip, int sync)
{
struct vx_rmh rmh;
vx_init_rmh(&rmh, CMD_MODIFY_CLOCK);
/* Ask the DSP to resynchronize its FIFO. */
if (sync)
rmh.Cmd[0] |= CMD_MODIFY_CLOCK_S_BIT;
return vx_send_msg(chip, &rmh);
}
/*
* vx_modify_board_inputs - resync audio inputs
*/
static int vx_modify_board_inputs(struct vx_core *chip)
{
struct vx_rmh rmh;
vx_init_rmh(&rmh, CMD_RESYNC_AUDIO_INPUTS);
rmh.Cmd[0] |= 1 << 0; /* reference: AUDIO 0 */
return vx_send_msg(chip, &rmh);
}
/*
* vx_read_one_cbit - read one bit from UER config
* @index: the bit index
* returns 0 or 1.
*/
static int vx_read_one_cbit(struct vx_core *chip, int index)
{
unsigned long flags;
int val;
spin_lock_irqsave(&chip->lock, flags);
if (chip->type >= VX_TYPE_VXPOCKET) {
vx_outb(chip, CSUER, 1); /* read */
vx_outb(chip, RUER, index & XX_UER_CBITS_OFFSET_MASK);
val = (vx_inb(chip, RUER) >> 7) & 0x01;
} else {
vx_outl(chip, CSUER, 1); /* read */
vx_outl(chip, RUER, index & XX_UER_CBITS_OFFSET_MASK);
val = (vx_inl(chip, RUER) >> 7) & 0x01;
}
spin_unlock_irqrestore(&chip->lock, flags);
return val;
}
/*
* vx_write_one_cbit - write one bit to UER config
* @index: the bit index
* @val: bit value, 0 or 1
*/
static void vx_write_one_cbit(struct vx_core *chip, int index, int val)
{
unsigned long flags;
val = !!val; /* 0 or 1 */
spin_lock_irqsave(&chip->lock, flags);
if (vx_is_pcmcia(chip)) {
vx_outb(chip, CSUER, 0); /* write */
vx_outb(chip, RUER, (val << 7) | (index & XX_UER_CBITS_OFFSET_MASK));
} else {
vx_outl(chip, CSUER, 0); /* write */
vx_outl(chip, RUER, (val << 7) | (index & XX_UER_CBITS_OFFSET_MASK));
}
spin_unlock_irqrestore(&chip->lock, flags);
}
/*
* vx_read_uer_status - read the current UER status
* @mode: pointer to store the UER mode, VX_UER_MODE_XXX
*
* returns the frequency of UER, or 0 if not sync,
* or a negative error code.
*/
static int vx_read_uer_status(struct vx_core *chip, unsigned int *mode)
{
int val, freq;
/* Default values */
freq = 0;
/* Read UER status */
if (vx_is_pcmcia(chip))
val = vx_inb(chip, CSUER);
else
val = vx_inl(chip, CSUER);
if (val < 0)
return val;
/* If clock is present, read frequency */
if (val & VX_SUER_CLOCK_PRESENT_MASK) {
switch (val & VX_SUER_FREQ_MASK) {
case VX_SUER_FREQ_32KHz_MASK:
freq = 32000;
break;
case VX_SUER_FREQ_44KHz_MASK:
freq = 44100;
break;
case VX_SUER_FREQ_48KHz_MASK:
freq = 48000;
break;
}
}
if (val & VX_SUER_DATA_PRESENT_MASK)
/* bit 0 corresponds to consumer/professional bit */
*mode = vx_read_one_cbit(chip, 0) ?
VX_UER_MODE_PROFESSIONAL : VX_UER_MODE_CONSUMER;
else
*mode = VX_UER_MODE_NOT_PRESENT;
return freq;
}
/*
* compute the sample clock value from frequency
*
* The formula is as follows:
*
* HexFreq = (dword) ((double) ((double) 28224000 / (double) Frequency))
* switch ( HexFreq & 0x00000F00 )
* case 0x00000100: ;
* case 0x00000200:
* case 0x00000300: HexFreq -= 0x00000201 ;
* case 0x00000400:
* case 0x00000500:
* case 0x00000600:
* case 0x00000700: HexFreq = (dword) (((double) 28224000 / (double) (Frequency*2)) - 1)
* default : HexFreq = (dword) ((double) 28224000 / (double) (Frequency*4)) - 0x000001FF
*/
static int vx_calc_clock_from_freq(struct vx_core *chip, int freq)
{
int hexfreq;
if (snd_BUG_ON(freq <= 0))
return 0;
hexfreq = (28224000 * 10) / freq;
hexfreq = (hexfreq + 5) / 10;
/* max freq = 55125 Hz */
if (snd_BUG_ON(hexfreq <= 0x00000200))
return 0;
if (hexfreq <= 0x03ff)
return hexfreq - 0x00000201;
if (hexfreq <= 0x07ff)
return (hexfreq / 2) - 1;
if (hexfreq <= 0x0fff)
return (hexfreq / 4) + 0x000001ff;
return 0x5fe; /* min freq = 6893 Hz */
}
/*
* vx_change_clock_source - change the clock source
* @source: the new source
*/
static void vx_change_clock_source(struct vx_core *chip, int source)
{
unsigned long flags;
/* we mute DAC to prevent clicks */
vx_toggle_dac_mute(chip, 1);
spin_lock_irqsave(&chip->lock, flags);
chip->ops->set_clock_source(chip, source);
chip->clock_source = source;
spin_unlock_irqrestore(&chip->lock, flags);
/* unmute */
vx_toggle_dac_mute(chip, 0);
}
/*
* set the internal clock
*/
void vx_set_internal_clock(struct vx_core *chip, unsigned int freq)
{
int clock;
unsigned long flags;
/* Get real clock value */
clock = vx_calc_clock_from_freq(chip, freq);
snd_printdd(KERN_DEBUG "set internal clock to 0x%x from freq %d\n", clock, freq);
spin_lock_irqsave(&chip->lock, flags);
if (vx_is_pcmcia(chip)) {
vx_outb(chip, HIFREQ, (clock >> 8) & 0x0f);
vx_outb(chip, LOFREQ, clock & 0xff);
} else {
vx_outl(chip, HIFREQ, (clock >> 8) & 0x0f);
vx_outl(chip, LOFREQ, clock & 0xff);
}
spin_unlock_irqrestore(&chip->lock, flags);
}
/*
* set the iec958 status bits
* @bits: 32-bit status bits
*/
void vx_set_iec958_status(struct vx_core *chip, unsigned int bits)
{
int i;
if (chip->chip_status & VX_STAT_IS_STALE)
return;
for (i = 0; i < 32; i++)
vx_write_one_cbit(chip, i, bits & (1 << i));
}
/*
* vx_set_clock - change the clock and audio source if necessary
*/
int vx_set_clock(struct vx_core *chip, unsigned int freq)
{
int src_changed = 0;
if (chip->chip_status & VX_STAT_IS_STALE)
return 0;
/* change the audio source if possible */
vx_sync_audio_source(chip);
if (chip->clock_mode == VX_CLOCK_MODE_EXTERNAL ||
(chip->clock_mode == VX_CLOCK_MODE_AUTO &&
chip->audio_source == VX_AUDIO_SRC_DIGITAL)) {
if (chip->clock_source != UER_SYNC) {
vx_change_clock_source(chip, UER_SYNC);
mdelay(6);
src_changed = 1;
}
} else if (chip->clock_mode == VX_CLOCK_MODE_INTERNAL ||
(chip->clock_mode == VX_CLOCK_MODE_AUTO &&
chip->audio_source != VX_AUDIO_SRC_DIGITAL)) {
if (chip->clock_source != INTERNAL_QUARTZ) {
vx_change_clock_source(chip, INTERNAL_QUARTZ);
src_changed = 1;
}
if (chip->freq == freq)
return 0;
vx_set_internal_clock(chip, freq);
if (src_changed)
vx_modify_board_inputs(chip);
}
if (chip->freq == freq)
return 0;
chip->freq = freq;
vx_modify_board_clock(chip, 1);
return 0;
}
/*
* vx_change_frequency - called from interrupt handler
*/
int vx_change_frequency(struct vx_core *chip)
{
int freq;
if (chip->chip_status & VX_STAT_IS_STALE)
return 0;
if (chip->clock_source == INTERNAL_QUARTZ)
return 0;
/*
* Read the real UER board frequency
*/
freq = vx_read_uer_status(chip, &chip->uer_detected);
if (freq < 0)
return freq;
/*
* The frequency computed by the DSP is good and
* is different from the previous computed.
*/
if (freq == 48000 || freq == 44100 || freq == 32000)
chip->freq_detected = freq;
return 0;
}
| gpl-2.0 |
Kick-Buttowski/samsung-stock-kernel | drivers/block/paride/paride.c | 13823 | 8755 | /*
paride.c (c) 1997-8 Grant R. Guenther <grant@torque.net>
Under the terms of the GNU General Public License.
This is the base module for the family of device drivers
that support parallel port IDE devices.
*/
/* Changes:
1.01 GRG 1998.05.03 Use spinlocks
1.02 GRG 1998.05.05 init_proto, release_proto, ktti
1.03 GRG 1998.08.15 eliminate compiler warning
1.04 GRG 1998.11.28 added support for FRIQ
1.05 TMW 2000.06.06 use parport_find_number instead of
parport_enumerate
1.06 TMW 2001.03.26 more sane parport-or-not resource management
*/
#define PI_VERSION "1.06"
#include <linux/module.h>
#include <linux/kmod.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/ioport.h>
#include <linux/string.h>
#include <linux/spinlock.h>
#include <linux/wait.h>
#include <linux/sched.h> /* TASK_* */
#include <linux/parport.h>
#include "paride.h"
MODULE_LICENSE("GPL");
#define MAX_PROTOS 32
static struct pi_protocol *protocols[MAX_PROTOS];
static DEFINE_SPINLOCK(pi_spinlock);
void pi_write_regr(PIA * pi, int cont, int regr, int val)
{
pi->proto->write_regr(pi, cont, regr, val);
}
EXPORT_SYMBOL(pi_write_regr);
int pi_read_regr(PIA * pi, int cont, int regr)
{
return pi->proto->read_regr(pi, cont, regr);
}
EXPORT_SYMBOL(pi_read_regr);
void pi_write_block(PIA * pi, char *buf, int count)
{
pi->proto->write_block(pi, buf, count);
}
EXPORT_SYMBOL(pi_write_block);
void pi_read_block(PIA * pi, char *buf, int count)
{
pi->proto->read_block(pi, buf, count);
}
EXPORT_SYMBOL(pi_read_block);
static void pi_wake_up(void *p)
{
PIA *pi = (PIA *) p;
unsigned long flags;
void (*cont) (void) = NULL;
spin_lock_irqsave(&pi_spinlock, flags);
if (pi->claim_cont && !parport_claim(pi->pardev)) {
cont = pi->claim_cont;
pi->claim_cont = NULL;
pi->claimed = 1;
}
spin_unlock_irqrestore(&pi_spinlock, flags);
wake_up(&(pi->parq));
if (cont)
cont();
}
int pi_schedule_claimed(PIA * pi, void (*cont) (void))
{
unsigned long flags;
spin_lock_irqsave(&pi_spinlock, flags);
if (pi->pardev && parport_claim(pi->pardev)) {
pi->claim_cont = cont;
spin_unlock_irqrestore(&pi_spinlock, flags);
return 0;
}
pi->claimed = 1;
spin_unlock_irqrestore(&pi_spinlock, flags);
return 1;
}
EXPORT_SYMBOL(pi_schedule_claimed);
void pi_do_claimed(PIA * pi, void (*cont) (void))
{
if (pi_schedule_claimed(pi, cont))
cont();
}
EXPORT_SYMBOL(pi_do_claimed);
static void pi_claim(PIA * pi)
{
if (pi->claimed)
return;
pi->claimed = 1;
if (pi->pardev)
wait_event(pi->parq,
!parport_claim((struct pardevice *) pi->pardev));
}
static void pi_unclaim(PIA * pi)
{
pi->claimed = 0;
if (pi->pardev)
parport_release((struct pardevice *) (pi->pardev));
}
void pi_connect(PIA * pi)
{
pi_claim(pi);
pi->proto->connect(pi);
}
EXPORT_SYMBOL(pi_connect);
void pi_disconnect(PIA * pi)
{
pi->proto->disconnect(pi);
pi_unclaim(pi);
}
EXPORT_SYMBOL(pi_disconnect);
static void pi_unregister_parport(PIA * pi)
{
if (pi->pardev) {
parport_unregister_device((struct pardevice *) (pi->pardev));
pi->pardev = NULL;
}
}
void pi_release(PIA * pi)
{
pi_unregister_parport(pi);
if (pi->proto->release_proto)
pi->proto->release_proto(pi);
module_put(pi->proto->owner);
}
EXPORT_SYMBOL(pi_release);
static int default_test_proto(PIA * pi, char *scratch, int verbose)
{
int j, k;
int e[2] = { 0, 0 };
pi->proto->connect(pi);
for (j = 0; j < 2; j++) {
pi_write_regr(pi, 0, 6, 0xa0 + j * 0x10);
for (k = 0; k < 256; k++) {
pi_write_regr(pi, 0, 2, k ^ 0xaa);
pi_write_regr(pi, 0, 3, k ^ 0x55);
if (pi_read_regr(pi, 0, 2) != (k ^ 0xaa))
e[j]++;
}
}
pi->proto->disconnect(pi);
if (verbose)
printk("%s: %s: port 0x%x, mode %d, test=(%d,%d)\n",
pi->device, pi->proto->name, pi->port,
pi->mode, e[0], e[1]);
return (e[0] && e[1]); /* not here if both > 0 */
}
static int pi_test_proto(PIA * pi, char *scratch, int verbose)
{
int res;
pi_claim(pi);
if (pi->proto->test_proto)
res = pi->proto->test_proto(pi, scratch, verbose);
else
res = default_test_proto(pi, scratch, verbose);
pi_unclaim(pi);
return res;
}
int paride_register(PIP * pr)
{
int k;
for (k = 0; k < MAX_PROTOS; k++)
if (protocols[k] && !strcmp(pr->name, protocols[k]->name)) {
printk("paride: %s protocol already registered\n",
pr->name);
return -1;
}
k = 0;
while ((k < MAX_PROTOS) && (protocols[k]))
k++;
if (k == MAX_PROTOS) {
printk("paride: protocol table full\n");
return -1;
}
protocols[k] = pr;
pr->index = k;
printk("paride: %s registered as protocol %d\n", pr->name, k);
return 0;
}
EXPORT_SYMBOL(paride_register);
void paride_unregister(PIP * pr)
{
if (!pr)
return;
if (protocols[pr->index] != pr) {
printk("paride: %s not registered\n", pr->name);
return;
}
protocols[pr->index] = NULL;
}
EXPORT_SYMBOL(paride_unregister);
static int pi_register_parport(PIA * pi, int verbose)
{
struct parport *port;
port = parport_find_base(pi->port);
if (!port)
return 0;
pi->pardev = parport_register_device(port,
pi->device, NULL,
pi_wake_up, NULL, 0, (void *) pi);
parport_put_port(port);
if (!pi->pardev)
return 0;
init_waitqueue_head(&pi->parq);
if (verbose)
printk("%s: 0x%x is %s\n", pi->device, pi->port, port->name);
pi->parname = (char *) port->name;
return 1;
}
static int pi_probe_mode(PIA * pi, int max, char *scratch, int verbose)
{
int best, range;
if (pi->mode != -1) {
if (pi->mode >= max)
return 0;
range = 3;
if (pi->mode >= pi->proto->epp_first)
range = 8;
if ((range == 8) && (pi->port % 8))
return 0;
pi->reserved = range;
return (!pi_test_proto(pi, scratch, verbose));
}
best = -1;
for (pi->mode = 0; pi->mode < max; pi->mode++) {
range = 3;
if (pi->mode >= pi->proto->epp_first)
range = 8;
if ((range == 8) && (pi->port % 8))
break;
pi->reserved = range;
if (!pi_test_proto(pi, scratch, verbose))
best = pi->mode;
}
pi->mode = best;
return (best > -1);
}
static int pi_probe_unit(PIA * pi, int unit, char *scratch, int verbose)
{
int max, s, e;
s = unit;
e = s + 1;
if (s == -1) {
s = 0;
e = pi->proto->max_units;
}
if (!pi_register_parport(pi, verbose))
return 0;
if (pi->proto->test_port) {
pi_claim(pi);
max = pi->proto->test_port(pi);
pi_unclaim(pi);
} else
max = pi->proto->max_mode;
if (pi->proto->probe_unit) {
pi_claim(pi);
for (pi->unit = s; pi->unit < e; pi->unit++)
if (pi->proto->probe_unit(pi)) {
pi_unclaim(pi);
if (pi_probe_mode(pi, max, scratch, verbose))
return 1;
pi_unregister_parport(pi);
return 0;
}
pi_unclaim(pi);
pi_unregister_parport(pi);
return 0;
}
if (!pi_probe_mode(pi, max, scratch, verbose)) {
pi_unregister_parport(pi);
return 0;
}
return 1;
}
int pi_init(PIA * pi, int autoprobe, int port, int mode,
int unit, int protocol, int delay, char *scratch,
int devtype, int verbose, char *device)
{
int p, k, s, e;
int lpts[7] = { 0x3bc, 0x378, 0x278, 0x268, 0x27c, 0x26c, 0 };
s = protocol;
e = s + 1;
if (!protocols[0])
request_module("paride_protocol");
if (autoprobe) {
s = 0;
e = MAX_PROTOS;
} else if ((s < 0) || (s >= MAX_PROTOS) || (port <= 0) ||
(!protocols[s]) || (unit < 0) ||
(unit >= protocols[s]->max_units)) {
printk("%s: Invalid parameters\n", device);
return 0;
}
for (p = s; p < e; p++) {
struct pi_protocol *proto = protocols[p];
if (!proto)
continue;
/* still racy */
if (!try_module_get(proto->owner))
continue;
pi->proto = proto;
pi->private = 0;
if (proto->init_proto && proto->init_proto(pi) < 0) {
pi->proto = NULL;
module_put(proto->owner);
continue;
}
if (delay == -1)
pi->delay = pi->proto->default_delay;
else
pi->delay = delay;
pi->devtype = devtype;
pi->device = device;
pi->parname = NULL;
pi->pardev = NULL;
init_waitqueue_head(&pi->parq);
pi->claimed = 0;
pi->claim_cont = NULL;
pi->mode = mode;
if (port != -1) {
pi->port = port;
if (pi_probe_unit(pi, unit, scratch, verbose))
break;
pi->port = 0;
} else {
k = 0;
while ((pi->port = lpts[k++]))
if (pi_probe_unit
(pi, unit, scratch, verbose))
break;
if (pi->port)
break;
}
if (pi->proto->release_proto)
pi->proto->release_proto(pi);
module_put(proto->owner);
}
if (!pi->port) {
if (autoprobe)
printk("%s: Autoprobe failed\n", device);
else
printk("%s: Adapter not found\n", device);
return 0;
}
if (pi->parname)
printk("%s: Sharing %s at 0x%x\n", pi->device,
pi->parname, pi->port);
pi->proto->log_adapter(pi, scratch, verbose);
return 1;
}
EXPORT_SYMBOL(pi_init);
| gpl-2.0 |
RobertBeckebans/Sikkpin-Feedback | neo/tools/radiant/DlgEvent.cpp | 1 | 2463 | /*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?).
Doom 3 Source Code 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 3 of the License, or
(at your option) any later version.
Doom 3 Source Code 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 Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "../../idlib/precompiled.h"
#pragma hdrstop
#include "qe3.h"
#include "DlgEvent.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CDlgEvent dialog
CDlgEvent::CDlgEvent( CWnd* pParent /*=NULL*/ )
: CDialog( CDlgEvent::IDD, pParent )
{
//{{AFX_DATA_INIT(CDlgEvent)
m_strParm = _T( "" );
m_event = 0;
//}}AFX_DATA_INIT
}
void CDlgEvent::DoDataExchange( CDataExchange* pDX )
{
CDialog::DoDataExchange( pDX );
//{{AFX_DATA_MAP(CDlgEvent)
DDX_Text( pDX, IDC_EDIT_PARAM, m_strParm );
DDX_Radio( pDX, IDC_RADIO_EVENT, m_event );
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP( CDlgEvent, CDialog )
//{{AFX_MSG_MAP(CDlgEvent)
// NOTE: the ClassWizard will add message map macros here
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDlgEvent message handlers
| gpl-3.0 |
7pri2/shmupgine | src/destructor.cpp | 1 | 3314 | #include "destructor.h"
#include "entity.h"
#include "scene.h"
#include "graphicrenderer.h"
destructor::destructor() : attribute() {
f_when_out_of_bounds = false;
m_destruction_requested = false;
}
destructor::destructor(entity* parent) : attribute(parent) {
f_when_out_of_bounds = false;
m_destruction_requested = false;
}
destructor::~destructor() {
}
void destructor::run() {
scene* parent_scene = parent->parent;
if(!m_destruction_requested) { // Optimisation
if(f_when_out_of_bounds)
if( parent->get_position().x > shmupgine::w_width || parent->get_position().x < 0
|| parent->get_position().y > shmupgine::w_height || parent->get_position().y < 0 ) {
parent_scene->remove_entity(parent);
}
for(std::list<entity*>::iterator it = m_entities.begin(); it != m_entities.end(); ++it) {
if( parent_scene->entity_exists(*it)
&& parent->get_attribute<graphicrenderer>() != NULL
&& (*it)->get_attribute<graphicrenderer>() != NULL
&& parent->get_attribute<graphicrenderer>()->m_sprite.getGlobalBounds().intersects((*it)->get_attribute<graphicrenderer>()->m_sprite.getGlobalBounds())) {
destroy();
}
}
for(std::list<std::string>::iterator g_it = m_groups.begin(); g_it != m_groups.end(); ++g_it) {
std::list<entity*> current_group = parent_scene->m_groups[*g_it];
for(std::list<entity*>::iterator it = current_group.begin(); it != current_group.end(); ++it) {
if( parent_scene->entity_exists(*it)
&& parent->get_attribute<graphicrenderer>() != NULL
&& (*it)->get_attribute<graphicrenderer>() != NULL
&& parent->get_attribute<graphicrenderer>()->m_sprite.getGlobalBounds().intersects((*it)->get_attribute<graphicrenderer>()->m_sprite.getGlobalBounds())) {
destroy();
}
}
}
}
}
void destructor::add_collision_entity(entity* en) {
m_entities.push_back(en);
}
void destructor::add_collision_group(std::string group) {
m_groups.push_back(group);
}
bool destructor::is_out_of_bounds() {
return parent->get_position().x > shmupgine::w_width
|| parent->get_position().x < 0
|| parent->get_position().y > shmupgine::w_height
|| parent->get_position().y < 0;
}
bool destructor::collides(entity* en) {
if( //!m_destruction_requested
parent->get_attribute<graphicrenderer>() != NULL
&& en->get_attribute<graphicrenderer>() != NULL
&& parent->get_attribute<graphicrenderer>()->m_sprite.getGlobalBounds().intersects(en->get_attribute<graphicrenderer>()->m_sprite.getGlobalBounds())) {
return true;
} else return false;
}
bool destructor::collides_something() {
if(!m_destruction_requested)
for(std::list<entity*>::iterator it = m_entities.begin(); it != m_entities.end(); ++it)
if(parent->parent->entity_exists(*it)
&& parent->get_attribute<graphicrenderer>() != NULL
&& (*it)->get_attribute<graphicrenderer>() != NULL
&& parent->get_attribute<graphicrenderer>()->m_sprite.getGlobalBounds().intersects((*it)->get_attribute<graphicrenderer>()->m_sprite.getGlobalBounds()))
return true;
return false;
}
void destructor::destroy() {
if(!m_destruction_requested) {
m_destruction_requested = true;
parent->parent->remove_entity(parent);
}
}
destructor* destructor::make_copy(entity* newparent) {
destructor* ptr = new destructor(*this);
ptr->parent = newparent;
return ptr;
}
| gpl-3.0 |
p01arst0rm/decorum-linux | _resources/kernels/xnu-arm/bsd/dev/i386/dtrace_isa.c | 1 | 21179 | /*
* Copyright (c) 2005-2006 Apple Computer, Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
#define MACH__POSIX_C_SOURCE_PRIVATE 1 /* pulls in suitable savearea from mach/ppc/thread_status.h */
#include <kern/thread.h>
#include <mach/thread_status.h>
typedef x86_saved_state_t savearea_t;
#include <stdarg.h>
#include <string.h>
#include <sys/malloc.h>
#include <sys/time.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/proc_internal.h>
#include <sys/kauth.h>
#include <sys/dtrace.h>
#include <sys/dtrace_impl.h>
#include <libkern/OSAtomic.h>
#include <kern/thread_call.h>
#include <kern/task.h>
#include <kern/sched_prim.h>
#include <miscfs/devfs/devfs.h>
#include <mach/vm_param.h>
#include <machine/pal_routines.h>
#include <i386/mp.h>
/*
* APPLE NOTE: The regmap is used to decode which 64bit uregs[] register
* is being accessed when passed the 32bit uregs[] constant (based on
* the reg.d translator file). The dtrace_getreg() is smart enough to handle
* the register mappings. The register set definitions are the same as
* those used by the fasttrap_getreg code.
*/
#include "fasttrap_regset.h"
static const uint8_t regmap[19] = {
REG_GS, /* GS */
REG_FS, /* FS */
REG_ES, /* ES */
REG_DS, /* DS */
REG_RDI, /* EDI */
REG_RSI, /* ESI */
REG_RBP, /* EBP, REG_FP */
REG_RSP, /* ESP */
REG_RBX, /* EBX */
REG_RDX, /* EDX, REG_R1 */
REG_RCX, /* ECX */
REG_RAX, /* EAX, REG_R0 */
REG_TRAPNO, /* TRAPNO */
REG_ERR, /* ERR */
REG_RIP, /* EIP, REG_PC */
REG_CS, /* CS */
REG_RFL, /* EFL, REG_PS */
REG_RSP, /* UESP, REG_SP */
REG_SS /* SS */
};
extern dtrace_id_t dtrace_probeid_error; /* special ERROR probe */
void
dtrace_probe_error(dtrace_state_t *state, dtrace_epid_t epid, int which,
int fltoffs, int fault, uint64_t illval)
{
/*
* For the case of the error probe firing lets
* stash away "illval" here, and special-case retrieving it in DIF_VARIABLE_ARG.
*/
state->dts_arg_error_illval = illval;
dtrace_probe( dtrace_probeid_error, (uint64_t)(uintptr_t)state, epid, which, fltoffs, fault );
}
/*
* Atomicity and synchronization
*/
void
dtrace_membar_producer(void)
{
__asm__ volatile("sfence");
}
void
dtrace_membar_consumer(void)
{
__asm__ volatile("lfence");
}
/*
* Interrupt manipulation
* XXX dtrace_getipl() can be called from probe context.
*/
int
dtrace_getipl(void)
{
/*
* XXX Drat, get_interrupt_level is MACH_KERNEL_PRIVATE
* in osfmk/kern/cpu_data.h
*/
/* return get_interrupt_level(); */
return (ml_at_interrupt_context() ? 1: 0);
}
/*
* MP coordination
*/
typedef struct xcArg {
processorid_t cpu;
dtrace_xcall_t f;
void *arg;
} xcArg_t;
static void
xcRemote( void *foo )
{
xcArg_t *pArg = (xcArg_t *)foo;
if ( pArg->cpu == CPU->cpu_id || pArg->cpu == DTRACE_CPUALL ) {
(pArg->f)(pArg->arg);
}
}
/*
* dtrace_xcall() is not called from probe context.
*/
void
dtrace_xcall(processorid_t cpu, dtrace_xcall_t f, void *arg)
{
xcArg_t xcArg;
xcArg.cpu = cpu;
xcArg.f = f;
xcArg.arg = arg;
if (cpu == DTRACE_CPUALL) {
mp_cpus_call (CPUMASK_ALL, SYNC, xcRemote, (void*)&xcArg);
}
else {
mp_cpus_call (cpu_to_cpumask((cpu_t)cpu), SYNC, xcRemote, (void*)&xcArg);
}
}
/*
* Initialization
*/
void
dtrace_isa_init(void)
{
return;
}
/*
* Runtime and ABI
*/
uint64_t
dtrace_getreg(struct regs *savearea, uint_t reg)
{
boolean_t is64Bit = proc_is64bit(current_proc());
x86_saved_state_t *regs = (x86_saved_state_t *)savearea;
if (is64Bit) {
if (reg <= SS) {
reg = regmap[reg];
} else {
reg -= (SS + 1);
}
switch (reg) {
case REG_RDI:
return (uint64_t)(regs->ss_64.rdi);
case REG_RSI:
return (uint64_t)(regs->ss_64.rsi);
case REG_RDX:
return (uint64_t)(regs->ss_64.rdx);
case REG_RCX:
return (uint64_t)(regs->ss_64.rcx);
case REG_R8:
return (uint64_t)(regs->ss_64.r8);
case REG_R9:
return (uint64_t)(regs->ss_64.r9);
case REG_RAX:
return (uint64_t)(regs->ss_64.rax);
case REG_RBX:
return (uint64_t)(regs->ss_64.rbx);
case REG_RBP:
return (uint64_t)(regs->ss_64.rbp);
case REG_R10:
return (uint64_t)(regs->ss_64.r10);
case REG_R11:
return (uint64_t)(regs->ss_64.r11);
case REG_R12:
return (uint64_t)(regs->ss_64.r12);
case REG_R13:
return (uint64_t)(regs->ss_64.r13);
case REG_R14:
return (uint64_t)(regs->ss_64.r14);
case REG_R15:
return (uint64_t)(regs->ss_64.r15);
case REG_FS:
return (uint64_t)(regs->ss_64.fs);
case REG_GS:
return (uint64_t)(regs->ss_64.gs);
case REG_TRAPNO:
return (uint64_t)(regs->ss_64.isf.trapno);
case REG_ERR:
return (uint64_t)(regs->ss_64.isf.err);
case REG_RIP:
return (uint64_t)(regs->ss_64.isf.rip);
case REG_CS:
return (uint64_t)(regs->ss_64.isf.cs);
case REG_SS:
return (uint64_t)(regs->ss_64.isf.ss);
case REG_RFL:
return (uint64_t)(regs->ss_64.isf.rflags);
case REG_RSP:
return (uint64_t)(regs->ss_64.isf.rsp);
case REG_DS:
case REG_ES:
default:
DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
return (0);
}
} else { /* is 32bit user */
/* beyond register SS */
if (reg > x86_SAVED_STATE32_COUNT - 1) {
DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
return (0);
}
return (uint64_t)((unsigned int *)(&(regs->ss_32.gs)))[reg];
}
}
#define RETURN_OFFSET 4
#define RETURN_OFFSET64 8
static int
dtrace_getustack_common(uint64_t *pcstack, int pcstack_limit, user_addr_t pc,
user_addr_t sp)
{
#if 0
volatile uint16_t *flags =
(volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
uintptr_t oldcontext = lwp->lwp_oldcontext; /* XXX signal stack crawl */
size_t s1, s2;
#endif
int ret = 0;
boolean_t is64Bit = proc_is64bit(current_proc());
ASSERT(pcstack == NULL || pcstack_limit > 0);
#if 0 /* XXX signal stack crawl */
if (p->p_model == DATAMODEL_NATIVE) {
s1 = sizeof (struct frame) + 2 * sizeof (long);
s2 = s1 + sizeof (siginfo_t);
} else {
s1 = sizeof (struct frame32) + 3 * sizeof (int);
s2 = s1 + sizeof (siginfo32_t);
}
#endif
while (pc != 0) {
ret++;
if (pcstack != NULL) {
*pcstack++ = (uint64_t)pc;
pcstack_limit--;
if (pcstack_limit <= 0)
break;
}
if (sp == 0)
break;
#if 0 /* XXX signal stack crawl */
if (oldcontext == sp + s1 || oldcontext == sp + s2) {
if (p->p_model == DATAMODEL_NATIVE) {
ucontext_t *ucp = (ucontext_t *)oldcontext;
greg_t *gregs = ucp->uc_mcontext.gregs;
sp = dtrace_fulword(&gregs[REG_FP]);
pc = dtrace_fulword(&gregs[REG_PC]);
oldcontext = dtrace_fulword(&ucp->uc_link);
} else {
ucontext32_t *ucp = (ucontext32_t *)oldcontext;
greg32_t *gregs = ucp->uc_mcontext.gregs;
sp = dtrace_fuword32(&gregs[EBP]);
pc = dtrace_fuword32(&gregs[EIP]);
oldcontext = dtrace_fuword32(&ucp->uc_link);
}
}
else
#endif
{
if (is64Bit) {
pc = dtrace_fuword64((sp + RETURN_OFFSET64));
sp = dtrace_fuword64(sp);
} else {
pc = dtrace_fuword32((sp + RETURN_OFFSET));
sp = dtrace_fuword32(sp);
}
}
#if 0 /* XXX */
/*
* This is totally bogus: if we faulted, we're going to clear
* the fault and break. This is to deal with the apparently
* broken Java stacks on x86.
*/
if (*flags & CPU_DTRACE_FAULT) {
*flags &= ~CPU_DTRACE_FAULT;
break;
}
#endif
}
return (ret);
}
/*
* The return value indicates if we've modified the stack.
*/
static int
dtrace_adjust_stack(uint64_t **pcstack, int *pcstack_limit, user_addr_t *pc,
user_addr_t sp)
{
int64_t missing_tos;
int rc = 0;
boolean_t is64Bit = proc_is64bit(current_proc());
ASSERT(pc != NULL);
if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_ENTRY)) {
/*
* If we found ourselves in an entry probe, the frame pointer has not
* yet been pushed (that happens in the
* function prologue). The best approach is to
* add the current pc as a missing top of stack,
* and back the pc up to the caller, which is stored at the
* current stack pointer address since the call
* instruction puts it there right before
* the branch.
*/
missing_tos = *pc;
if (is64Bit)
*pc = dtrace_fuword64(sp);
else
*pc = dtrace_fuword32(sp);
} else {
/*
* We might have a top of stack override, in which case we just
* add that frame without question to the top. This
* happens in return probes where you have a valid
* frame pointer, but it's for the callers frame
* and you'd like to add the pc of the return site
* to the frame.
*/
missing_tos = cpu_core[CPU->cpu_id].cpuc_missing_tos;
}
if (missing_tos != 0) {
if (pcstack != NULL && pcstack_limit != NULL) {
/*
* If the missing top of stack has been filled out, then
* we add it and adjust the size.
*/
*(*pcstack)++ = missing_tos;
(*pcstack_limit)--;
}
/*
* return 1 because we would have changed the
* stack whether or not it was passed in. This
* ensures the stack count is correct
*/
rc = 1;
}
return rc;
}
void
dtrace_getupcstack(uint64_t *pcstack, int pcstack_limit)
{
thread_t thread = current_thread();
x86_saved_state_t *regs;
user_addr_t pc, sp, fp;
volatile uint16_t *flags =
(volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
int n;
boolean_t is64Bit = proc_is64bit(current_proc());
if (*flags & CPU_DTRACE_FAULT)
return;
if (pcstack_limit <= 0)
return;
/*
* If there's no user context we still need to zero the stack.
*/
if (thread == NULL)
goto zero;
pal_register_cache_state(thread, VALID);
regs = (x86_saved_state_t *)find_user_regs(thread);
if (regs == NULL)
goto zero;
*pcstack++ = (uint64_t)proc_selfpid();
pcstack_limit--;
if (pcstack_limit <= 0)
return;
if (is64Bit) {
pc = regs->ss_64.isf.rip;
sp = regs->ss_64.isf.rsp;
fp = regs->ss_64.rbp;
} else {
pc = regs->ss_32.eip;
sp = regs->ss_32.uesp;
fp = regs->ss_32.ebp;
}
/*
* The return value indicates if we've modified the stack.
* Since there is nothing else to fix up in either case,
* we can safely ignore it here.
*/
(void)dtrace_adjust_stack(&pcstack, &pcstack_limit, &pc, sp);
if(pcstack_limit <= 0)
return;
/*
* Note that unlike ppc, the x86 code does not use
* CPU_DTRACE_USTACK_FP. This is because x86 always
* traces from the fp, even in syscall/profile/fbt
* providers.
*/
n = dtrace_getustack_common(pcstack, pcstack_limit, pc, fp);
ASSERT(n >= 0);
ASSERT(n <= pcstack_limit);
pcstack += n;
pcstack_limit -= n;
zero:
while (pcstack_limit-- > 0)
*pcstack++ = 0;
}
int
dtrace_getustackdepth(void)
{
thread_t thread = current_thread();
x86_saved_state_t *regs;
user_addr_t pc, sp, fp;
int n = 0;
boolean_t is64Bit = proc_is64bit(current_proc());
if (thread == NULL)
return 0;
if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
return (-1);
pal_register_cache_state(thread, VALID);
regs = (x86_saved_state_t *)find_user_regs(thread);
if (regs == NULL)
return 0;
if (is64Bit) {
pc = regs->ss_64.isf.rip;
sp = regs->ss_64.isf.rsp;
fp = regs->ss_64.rbp;
} else {
pc = regs->ss_32.eip;
sp = regs->ss_32.uesp;
fp = regs->ss_32.ebp;
}
if (dtrace_adjust_stack(NULL, NULL, &pc, sp) == 1) {
/*
* we would have adjusted the stack if we had
* supplied one (that is what rc == 1 means).
* Also, as a side effect, the pc might have
* been fixed up, which is good for calling
* in to dtrace_getustack_common.
*/
n++;
}
/*
* Note that unlike ppc, the x86 code does not use
* CPU_DTRACE_USTACK_FP. This is because x86 always
* traces from the fp, even in syscall/profile/fbt
* providers.
*/
n += dtrace_getustack_common(NULL, 0, pc, fp);
return (n);
}
void
dtrace_getufpstack(uint64_t *pcstack, uint64_t *fpstack, int pcstack_limit)
{
thread_t thread = current_thread();
savearea_t *regs;
user_addr_t pc, sp;
volatile uint16_t *flags =
(volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
#if 0
uintptr_t oldcontext;
size_t s1, s2;
#endif
boolean_t is64Bit = proc_is64bit(current_proc());
if (*flags & CPU_DTRACE_FAULT)
return;
if (pcstack_limit <= 0)
return;
/*
* If there's no user context we still need to zero the stack.
*/
if (thread == NULL)
goto zero;
regs = (savearea_t *)find_user_regs(thread);
if (regs == NULL)
goto zero;
*pcstack++ = (uint64_t)proc_selfpid();
pcstack_limit--;
if (pcstack_limit <= 0)
return;
pc = regs->ss_32.eip;
sp = regs->ss_32.ebp;
#if 0 /* XXX signal stack crawl */
oldcontext = lwp->lwp_oldcontext;
if (p->p_model == DATAMODEL_NATIVE) {
s1 = sizeof (struct frame) + 2 * sizeof (long);
s2 = s1 + sizeof (siginfo_t);
} else {
s1 = sizeof (struct frame32) + 3 * sizeof (int);
s2 = s1 + sizeof (siginfo32_t);
}
#endif
if(dtrace_adjust_stack(&pcstack, &pcstack_limit, &pc, sp) == 1) {
/*
* we made a change.
*/
*fpstack++ = 0;
if (pcstack_limit <= 0)
return;
}
while (pc != 0) {
*pcstack++ = (uint64_t)pc;
*fpstack++ = sp;
pcstack_limit--;
if (pcstack_limit <= 0)
break;
if (sp == 0)
break;
#if 0 /* XXX signal stack crawl */
if (oldcontext == sp + s1 || oldcontext == sp + s2) {
if (p->p_model == DATAMODEL_NATIVE) {
ucontext_t *ucp = (ucontext_t *)oldcontext;
greg_t *gregs = ucp->uc_mcontext.gregs;
sp = dtrace_fulword(&gregs[REG_FP]);
pc = dtrace_fulword(&gregs[REG_PC]);
oldcontext = dtrace_fulword(&ucp->uc_link);
} else {
ucontext_t *ucp = (ucontext_t *)oldcontext;
greg_t *gregs = ucp->uc_mcontext.gregs;
sp = dtrace_fuword32(&gregs[EBP]);
pc = dtrace_fuword32(&gregs[EIP]);
oldcontext = dtrace_fuword32(&ucp->uc_link);
}
}
else
#endif
{
if (is64Bit) {
pc = dtrace_fuword64((sp + RETURN_OFFSET64));
sp = dtrace_fuword64(sp);
} else {
pc = dtrace_fuword32((sp + RETURN_OFFSET));
sp = dtrace_fuword32(sp);
}
}
#if 0 /* XXX */
/*
* This is totally bogus: if we faulted, we're going to clear
* the fault and break. This is to deal with the apparently
* broken Java stacks on x86.
*/
if (*flags & CPU_DTRACE_FAULT) {
*flags &= ~CPU_DTRACE_FAULT;
break;
}
#endif
}
zero:
while (pcstack_limit-- > 0)
*pcstack++ = 0;
}
void
dtrace_getpcstack(pc_t *pcstack, int pcstack_limit, int aframes,
uint32_t *intrpc)
{
struct frame *fp = (struct frame *)__builtin_frame_address(0);
struct frame *nextfp, *minfp, *stacktop;
int depth = 0;
int last = 0;
uintptr_t pc;
uintptr_t caller = CPU->cpu_dtrace_caller;
int on_intr;
if ((on_intr = CPU_ON_INTR(CPU)) != 0)
stacktop = (struct frame *)dtrace_get_cpu_int_stack_top();
else
stacktop = (struct frame *)(dtrace_get_kernel_stack(current_thread()) + kernel_stack_size);
minfp = fp;
aframes++;
if (intrpc != NULL && depth < pcstack_limit)
pcstack[depth++] = (pc_t)intrpc;
while (depth < pcstack_limit) {
nextfp = *(struct frame **)fp;
#if defined(__x86_64__)
pc = *(uintptr_t *)(((uintptr_t)fp) + RETURN_OFFSET64);
#else
pc = *(uintptr_t *)(((uintptr_t)fp) + RETURN_OFFSET);
#endif
if (nextfp <= minfp || nextfp >= stacktop) {
if (on_intr) {
/*
* Hop from interrupt stack to thread stack.
*/
vm_offset_t kstack_base = dtrace_get_kernel_stack(current_thread());
minfp = (struct frame *)kstack_base;
stacktop = (struct frame *)(kstack_base + kernel_stack_size);
on_intr = 0;
continue;
}
/*
* This is the last frame we can process; indicate
* that we should return after processing this frame.
*/
last = 1;
}
if (aframes > 0) {
if (--aframes == 0 && caller != 0) {
/*
* We've just run out of artificial frames,
* and we have a valid caller -- fill it in
* now.
*/
ASSERT(depth < pcstack_limit);
pcstack[depth++] = (pc_t)caller;
caller = 0;
}
} else {
if (depth < pcstack_limit)
pcstack[depth++] = (pc_t)pc;
}
if (last) {
while (depth < pcstack_limit)
pcstack[depth++] = 0;
return;
}
fp = nextfp;
minfp = fp;
}
}
struct frame {
struct frame *backchain;
uintptr_t retaddr;
};
uint64_t
dtrace_getarg(int arg, int aframes)
{
uint64_t val;
struct frame *fp = (struct frame *)__builtin_frame_address(0);
uintptr_t *stack;
uintptr_t pc;
int i;
#if defined(__x86_64__)
/*
* A total of 6 arguments are passed via registers; any argument with
* index of 5 or lower is therefore in a register.
*/
int inreg = 5;
#endif
for (i = 1; i <= aframes; i++) {
fp = fp->backchain;
pc = fp->retaddr;
if (dtrace_invop_callsite_pre != NULL
&& pc > (uintptr_t)dtrace_invop_callsite_pre
&& pc <= (uintptr_t)dtrace_invop_callsite_post) {
#if defined(__i386__)
/*
* If we pass through the invalid op handler, we will
* use the pointer that it passed to the stack as the
* second argument to dtrace_invop() as the pointer to
* the frame we're hunting for.
*/
stack = (uintptr_t *)&fp[1]; /* Find marshalled arguments */
fp = (struct frame *)stack[1]; /* Grab *second* argument */
stack = (uintptr_t *)&fp[1]; /* Find marshalled arguments */
#elif defined(__x86_64__)
/*
* In the case of x86_64, we will use the pointer to the
* save area structure that was pushed when we took the
* trap. To get this structure, we must increment
* beyond the frame structure. If the
* argument that we're seeking is passed on the stack,
* we'll pull the true stack pointer out of the saved
* registers and decrement our argument by the number
* of arguments passed in registers; if the argument
* we're seeking is passed in regsiters, we can just
* load it directly.
*/
/* fp points to frame of dtrace_invop() activation. */
fp = fp->backchain; /* to fbt_perfcallback() activation. */
fp = fp->backchain; /* to kernel_trap() activation. */
fp = fp->backchain; /* to trap_from_kernel() activation. */
x86_saved_state_t *tagged_regs = (x86_saved_state_t *)&fp[1];
x86_saved_state64_t *saved_state = saved_state64(tagged_regs);
if (arg <= inreg) {
stack = (uintptr_t *)&saved_state->rdi;
} else {
fp = (struct frame *)(saved_state->isf.rsp);
stack = (uintptr_t *)&fp[1]; /* Find marshalled
arguments */
arg -= inreg + 1;
}
#else
#error Unknown arch
#endif
goto load;
}
}
/*
* We know that we did not come through a trap to get into
* dtrace_probe() -- We arrive here when the provider has
* called dtrace_probe() directly.
* The probe ID is the first argument to dtrace_probe().
* We must advance beyond that to get the argX.
*/
arg++; /* Advance past probeID */
#if defined(__x86_64__)
if (arg <= inreg) {
/*
* This shouldn't happen. If the argument is passed in a
* register then it should have been, well, passed in a
* register...
*/
DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
return (0);
}
arg -= (inreg + 1);
#endif
stack = (uintptr_t *)&fp[1]; /* Find marshalled arguments */
load:
DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
/* dtrace_probe arguments arg0 ... arg4 are 64bits wide */
val = (uint64_t)(*(((uintptr_t *)stack) + arg));
DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
return (val);
}
/*
* Load/Store Safety
*/
void
dtrace_toxic_ranges(void (*func)(uintptr_t base, uintptr_t limit))
{
/*
* "base" is the smallest toxic address in the range, "limit" is the first
* VALID address greater than "base".
*/
func(0x0, VM_MIN_KERNEL_AND_KEXT_ADDRESS);
if (VM_MAX_KERNEL_ADDRESS < ~(uintptr_t)0)
func(VM_MAX_KERNEL_ADDRESS + 1, ~(uintptr_t)0);
}
| gpl-3.0 |
jonan/freedom-to-smash | bullet/BulletCollision/CollisionShapes/btShapeHull.cpp | 1 | 6317 | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express 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.
*/
//btShapeHull was implemented by John McCutchan.
#include "btShapeHull.h"
#include "LinearMath/btConvexHull.h"
#define NUM_UNITSPHERE_POINTS 42
btShapeHull::btShapeHull (const btConvexShape* shape)
{
m_shape = shape;
m_vertices.clear ();
m_indices.clear();
m_numIndices = 0;
}
btShapeHull::~btShapeHull ()
{
m_indices.clear();
m_vertices.clear ();
}
bool
btShapeHull::buildHull (btScalar /*margin*/)
{
int numSampleDirections = NUM_UNITSPHERE_POINTS;
{
int numPDA = m_shape->getNumPreferredPenetrationDirections();
if (numPDA)
{
for (int i=0;i<numPDA;i++)
{
btVector3 norm;
m_shape->getPreferredPenetrationDirection(i,norm);
getUnitSpherePoints()[numSampleDirections] = norm;
numSampleDirections++;
}
}
}
btVector3 supportPoints[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2];
int i;
for (i = 0; i < numSampleDirections; i++)
{
supportPoints[i] = m_shape->localGetSupportingVertex(getUnitSpherePoints()[i]);
}
HullDesc hd;
hd.mFlags = QF_TRIANGLES;
hd.mVcount = static_cast<unsigned int>(numSampleDirections);
#ifdef BT_USE_DOUBLE_PRECISION
hd.mVertices = &supportPoints[0];
hd.mVertexStride = sizeof(btVector3);
#else
hd.mVertices = &supportPoints[0];
hd.mVertexStride = sizeof (btVector3);
#endif
HullLibrary hl;
HullResult hr;
if (hl.CreateConvexHull (hd, hr) == QE_FAIL)
{
return false;
}
m_vertices.resize (static_cast<int>(hr.mNumOutputVertices));
for (i = 0; i < static_cast<int>(hr.mNumOutputVertices); i++)
{
m_vertices[i] = hr.m_OutputVertices[i];
}
m_numIndices = hr.mNumIndices;
m_indices.resize(static_cast<int>(m_numIndices));
for (i = 0; i < static_cast<int>(m_numIndices); i++)
{
m_indices[i] = hr.m_Indices[i];
}
// free temporary hull result that we just copied
hl.ReleaseResult (hr);
return true;
}
int
btShapeHull::numTriangles () const
{
return static_cast<int>(m_numIndices / 3);
}
int
btShapeHull::numVertices () const
{
return m_vertices.size ();
}
int
btShapeHull::numIndices () const
{
return static_cast<int>(m_numIndices);
}
btVector3* btShapeHull::getUnitSpherePoints()
{
static btVector3 sUnitSpherePoints[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2] =
{
btVector3(btScalar(0.000000) , btScalar(-0.000000),btScalar(-1.000000)),
btVector3(btScalar(0.723608) , btScalar(-0.525725),btScalar(-0.447219)),
btVector3(btScalar(-0.276388) , btScalar(-0.850649),btScalar(-0.447219)),
btVector3(btScalar(-0.894426) , btScalar(-0.000000),btScalar(-0.447216)),
btVector3(btScalar(-0.276388) , btScalar(0.850649),btScalar(-0.447220)),
btVector3(btScalar(0.723608) , btScalar(0.525725),btScalar(-0.447219)),
btVector3(btScalar(0.276388) , btScalar(-0.850649),btScalar(0.447220)),
btVector3(btScalar(-0.723608) , btScalar(-0.525725),btScalar(0.447219)),
btVector3(btScalar(-0.723608) , btScalar(0.525725),btScalar(0.447219)),
btVector3(btScalar(0.276388) , btScalar(0.850649),btScalar(0.447219)),
btVector3(btScalar(0.894426) , btScalar(0.000000),btScalar(0.447216)),
btVector3(btScalar(-0.000000) , btScalar(0.000000),btScalar(1.000000)),
btVector3(btScalar(0.425323) , btScalar(-0.309011),btScalar(-0.850654)),
btVector3(btScalar(-0.162456) , btScalar(-0.499995),btScalar(-0.850654)),
btVector3(btScalar(0.262869) , btScalar(-0.809012),btScalar(-0.525738)),
btVector3(btScalar(0.425323) , btScalar(0.309011),btScalar(-0.850654)),
btVector3(btScalar(0.850648) , btScalar(-0.000000),btScalar(-0.525736)),
btVector3(btScalar(-0.525730) , btScalar(-0.000000),btScalar(-0.850652)),
btVector3(btScalar(-0.688190) , btScalar(-0.499997),btScalar(-0.525736)),
btVector3(btScalar(-0.162456) , btScalar(0.499995),btScalar(-0.850654)),
btVector3(btScalar(-0.688190) , btScalar(0.499997),btScalar(-0.525736)),
btVector3(btScalar(0.262869) , btScalar(0.809012),btScalar(-0.525738)),
btVector3(btScalar(0.951058) , btScalar(0.309013),btScalar(0.000000)),
btVector3(btScalar(0.951058) , btScalar(-0.309013),btScalar(0.000000)),
btVector3(btScalar(0.587786) , btScalar(-0.809017),btScalar(0.000000)),
btVector3(btScalar(0.000000) , btScalar(-1.000000),btScalar(0.000000)),
btVector3(btScalar(-0.587786) , btScalar(-0.809017),btScalar(0.000000)),
btVector3(btScalar(-0.951058) , btScalar(-0.309013),btScalar(-0.000000)),
btVector3(btScalar(-0.951058) , btScalar(0.309013),btScalar(-0.000000)),
btVector3(btScalar(-0.587786) , btScalar(0.809017),btScalar(-0.000000)),
btVector3(btScalar(-0.000000) , btScalar(1.000000),btScalar(-0.000000)),
btVector3(btScalar(0.587786) , btScalar(0.809017),btScalar(-0.000000)),
btVector3(btScalar(0.688190) , btScalar(-0.499997),btScalar(0.525736)),
btVector3(btScalar(-0.262869) , btScalar(-0.809012),btScalar(0.525738)),
btVector3(btScalar(-0.850648) , btScalar(0.000000),btScalar(0.525736)),
btVector3(btScalar(-0.262869) , btScalar(0.809012),btScalar(0.525738)),
btVector3(btScalar(0.688190) , btScalar(0.499997),btScalar(0.525736)),
btVector3(btScalar(0.525730) , btScalar(0.000000),btScalar(0.850652)),
btVector3(btScalar(0.162456) , btScalar(-0.499995),btScalar(0.850654)),
btVector3(btScalar(-0.425323) , btScalar(-0.309011),btScalar(0.850654)),
btVector3(btScalar(-0.425323) , btScalar(0.309011),btScalar(0.850654)),
btVector3(btScalar(0.162456) , btScalar(0.499995),btScalar(0.850654))
};
return sUnitSpherePoints;
}
| gpl-3.0 |
coapp-packages/processhacker | KProcessHacker/qrydrv.c | 1 | 7465 | /*
* KProcessHacker
*
* Copyright (C) 2010-2011 wj32
*
* This file is part of Process Hacker.
*
* Process Hacker 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 3 of the License, or
* (at your option) any later version.
*
* Process Hacker 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 Process Hacker. If not, see <http://www.gnu.org/licenses/>.
*/
#include <kph.h>
VOID KphpCopyInfoUnicodeString(
__out PVOID Information,
__in_opt PUNICODE_STRING UnicodeString
);
#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, KpiOpenDriver)
#pragma alloc_text(PAGE, KpiQueryInformationDriver)
#pragma alloc_text(PAGE, KphpCopyInfoUnicodeString)
#endif
NTSTATUS KpiOpenDriver(
__out PHANDLE DriverHandle,
__in POBJECT_ATTRIBUTES ObjectAttributes,
__in KPROCESSOR_MODE AccessMode
)
{
PAGED_CODE();
return KphOpenNamedObject(
DriverHandle,
0,
ObjectAttributes,
*IoDriverObjectType,
AccessMode
);
}
NTSTATUS KpiQueryInformationDriver(
__in HANDLE DriverHandle,
__in DRIVER_INFORMATION_CLASS DriverInformationClass,
__out_bcount(DriverInformationLength) PVOID DriverInformation,
__in ULONG DriverInformationLength,
__out_opt PULONG ReturnLength,
__in KPROCESSOR_MODE AccessMode
)
{
NTSTATUS status = STATUS_SUCCESS;
PDRIVER_OBJECT driverObject;
PAGED_CODE();
if (AccessMode != KernelMode)
{
__try
{
ProbeForWrite(DriverInformation, DriverInformationLength, 1);
if (ReturnLength)
ProbeForWrite(ReturnLength, sizeof(ULONG), 1);
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
return GetExceptionCode();
}
}
status = ObReferenceObjectByHandle(
DriverHandle,
0,
*IoDriverObjectType,
AccessMode,
&driverObject,
NULL
);
if (!NT_SUCCESS(status))
return status;
__try
{
switch (DriverInformationClass)
{
// Basic information such as flags, driver base and driver size.
case DriverBasicInformation:
{
if (DriverInformationLength == sizeof(DRIVER_BASIC_INFORMATION))
{
PDRIVER_BASIC_INFORMATION basicInfo;
basicInfo = (PDRIVER_BASIC_INFORMATION)DriverInformation;
basicInfo->Flags = driverObject->Flags;
basicInfo->DriverStart = driverObject->DriverStart;
basicInfo->DriverSize = driverObject->DriverSize;
}
else
{
status = STATUS_INFO_LENGTH_MISMATCH;
}
if (ReturnLength)
*ReturnLength = sizeof(DRIVER_BASIC_INFORMATION);
}
break;
// The name of the driver - e.g. \Driver\KProcessHacker2.
case DriverNameInformation:
{
if (DriverInformation)
{
/* Check buffer length. */
if (
sizeof(UNICODE_STRING) +
driverObject->DriverName.Length <=
DriverInformationLength
)
{
KphpCopyInfoUnicodeString(
DriverInformation,
&driverObject->DriverName
);
}
else
{
status = STATUS_BUFFER_TOO_SMALL;
}
}
if (ReturnLength)
*ReturnLength = sizeof(UNICODE_STRING) + driverObject->DriverName.Length;
}
break;
// The name of the driver's service key - e.g. \REGISTRY\...
case DriverServiceKeyNameInformation:
{
if (driverObject->DriverExtension)
{
if (DriverInformation)
{
if (
sizeof(UNICODE_STRING) +
driverObject->DriverExtension->ServiceKeyName.Length <=
DriverInformationLength
)
{
KphpCopyInfoUnicodeString(
DriverInformation,
&driverObject->DriverExtension->ServiceKeyName
);
}
else
{
status = STATUS_BUFFER_TOO_SMALL;
}
}
if (ReturnLength)
*ReturnLength = sizeof(UNICODE_STRING) +
driverObject->DriverExtension->ServiceKeyName.Length;
}
else
{
if (DriverInformation)
{
if (sizeof(UNICODE_STRING) <= DriverInformationLength)
{
// Zero the information buffer.
KphpCopyInfoUnicodeString(
DriverInformation,
NULL
);
}
else
{
status = STATUS_BUFFER_TOO_SMALL;
}
}
if (ReturnLength)
*ReturnLength = sizeof(UNICODE_STRING);
}
}
break;
default:
{
status = STATUS_INVALID_INFO_CLASS;
}
}
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
status = GetExceptionCode();
}
ObDereferenceObject(driverObject);
return status;
}
VOID KphpCopyInfoUnicodeString(
__out PVOID Information,
__in_opt PUNICODE_STRING UnicodeString
)
{
PUNICODE_STRING targetUnicodeString = (PUNICODE_STRING)Information;
PAGED_CODE();
if (UnicodeString)
{
targetUnicodeString->Length = UnicodeString->Length;
targetUnicodeString->MaximumLength = targetUnicodeString->Length;
targetUnicodeString->Buffer = (PWSTR)((PCHAR)Information + sizeof(UNICODE_STRING));
memcpy(
targetUnicodeString->Buffer,
UnicodeString->Buffer,
targetUnicodeString->Length
);
}
else
{
targetUnicodeString->Length = 0;
targetUnicodeString->MaximumLength = 0;
targetUnicodeString->Buffer = NULL;
}
}
| gpl-3.0 |
OpenCTR/libctr | src/sdmc.c | 1 | 6220 | /*
*******************************************************************************
* libctr - Library for Nintendo 3DS homebrew.
*
* Copyright (C) 2015, OpenCTR Contributors.
*
* This file is part of libctr.
*
* libctr is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3 as published by
* the Free Software Foundation.
*
* libctr 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 libctr. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************
*/
#include "ctr/base_private.h"
#include "ctr/sys_private.h"
#include "ctr/error_private.h"
#include "ctr/fs_private.h"
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <sys/dirent.h>
#include <sys/iosupport.h>
#include <sys/param.h>
#include <unistd.h>
#if 0
static char __cwd[PATH_MAX+1] = "/";
static char __fixedpath[PATH_MAX+1];
static uint16_t __utf16path[PATH_MAX+1];
/*
* Originally from ctrulib.
*/
static ssize_t decode_utf8(uint32_t* out, const uint8_t* in) {
uint8_t code1;
uint8_t code2;
uint8_t code3;
uint8_t code4;
code1 = *in++;
if(code1 < 0x80) {
/* 1-byte sequence */
*out = code1;
return 1;
} else if(code1 < 0xC2) {
return -1;
} else if(code1 < 0xE0) {
/* 2-byte sequence */
code2 = *in++;
if((code2 & 0xC0) != 0x80) {
return -1;
}
*out = (code1 << 6) + code2 - 0x3080;
return 2;
} else if(code1 < 0xF0) {
/* 3-byte sequence */
code2 = *in++;
if((code2 & 0xC0) != 0x80) {
return -1;
} else if(code1 == 0xE0 && code2 < 0xA0) {
return -1;
}
code3 = *in++;
if((code3 & 0xC0) != 0x80) {
return -1;
}
*out = (code1 << 12) + (code2 << 6) + code3 - 0xE2080;
return 3;
} else if(code1 < 0xF5) {
/* 4-byte sequence */
code2 = *in++;
if((code2 & 0xC0) != 0x80) {
return -1;
} else if(code1 == 0xF0 && code2 < 0x90) {
return -1;
} else if(code1 == 0xF4 && code2 >= 0x90) {
return -1;
}
code3 = *in++;
if((code3 & 0xC0) != 0x80) {
return -1;
}
code4 = *in++;
if((code4 & 0xC0) != 0x80) {
return -1;
}
*out = (code1 << 18) + (code2 << 12) + (code3 << 6) + code4 - 0x3C82080;
return 4;
}
return -1;
}
static const char* sdmc_fixpath(struct _reent* r, const char* path) {
size_t units;
uint32_t code;
const uint8_t* p = NULL;
p = (const uint8_t*)path;
/* Move the path pointer to the start of the actual path. */
do {
units = decode_utf8(&code, p);
if(units == (size_t)-1) {
r->_errno = EILSEQ;
return NULL;
}
p += units;
} while(code != ':' && code != 0);
/* We found a colon -- p points to the actual path. */
if(code == ':') {
path = (const char*)p;
}
/*
* Make sure there are no more colons and that the
* remainder of the filename is valid UTF-8.
*/
p = (const uint8_t*)path;
do {
units = decode_utf8(&code, p);
if(units == (size_t)-1) {
r->_errno = EILSEQ;
return NULL;
} else if(code == ':') {
r->_errno = EINVAL;
return NULL;
}
p += units;
} while(code != 0);
if(path[0] == '/') {
strncpy(__fixedpath, path, PATH_MAX+1);
} else {
strncpy(__fixedpath, __cwd, PATH_MAX+1);
strncat(__fixedpath, path, PATH_MAX+1);
}
if(__fixedpath[PATH_MAX] != 0) {
__fixedpath[PATH_MAX] = 0;
r->_errno = ENAMETOOLONG;
return NULL;
}
return __fixedpath;
}
#endif
/**
* @brief Open a file.
* @param[in,out] r Newlib reentrancy struct.
* @param[out] fileStruct Pointer to file struct to fill in.
* @param[in] path Path to open.
* @param[in] flags Open flags from open(2)
* @param[in] mode Permissions to set on create.
* @return 0 for success, -1 for error.
*/
static int sdmc_open(struct _reent* r,
int* fd,
const char* path,
int flags,
int mode) {
int ret;
uint32_t sdmc_flags = 0;
CtrFsContextData* context = NULL;
context = (CtrFsContextData*)(GetDeviceOpTab("sdmc")->deviceData);
if(context == NULL) {
r->_errno = EIO;
return -1;
}
/* Check access mode. */
switch(flags & O_ACCMODE) {
case O_RDONLY:
sdmc_flags = CTR_FS_O_RDONLY;
if(flags & O_APPEND) {
r->_errno = EINVAL;
return -1;
}
break;
case O_WRONLY:
sdmc_flags = CTR_FS_O_WRONLY;
break;
case O_RDWR:
sdmc_flags = CTR_FS_O_RDWR;
break;
default:
r->_errno = EINVAL;
return -1;
}
/* Create file */
if(flags & O_CREAT) {
sdmc_flags |= CTR_FS_O_CREAT;
#if 0
if(flags & O_EXCL) {
ret = FSUSER_CreateFile(NULL, sdmcArchive, fs_path, 0);
if(ret != 0) {
r->_errno = sdmc_translate_error(rc);
return -1;
}
}
#endif
}
/* Open the file */
ret = ctrFsOpen(context, fd, path, sdmc_flags);
if(ret != 0) {
#if 0
r->_errno = sdmc_translate_error(cerrno());
#endif
return -1;
}
#if 0
if((flags & O_ACCMODE) != O_RDONLY && (flags & O_TRUNC)) {
ret = FSFILE_SetSize(fd, 0);
if(ret != 0) {
FSFILE_Close(fd);
r->_errno = sdmc_translate_error(rc);
return -1;
}
}
#endif
return 0;
}
| gpl-3.0 |
GuillemFP/DoubleDragon3 | ModuleDebug.cpp | 1 | 4629 | #include "Application.h"
#include "ModuleEntities.h"
#include "ModuleInput.h"
#include "ModuleRender.h"
#include "ModuleFonts.h"
#include "ModuleCollision.h"
#include "ModuleUI.h"
#include "ModuleDebug.h"
#include "ModuleWindow.h"
#include "JsonHandler.h"
#include "Player.h"
ModuleDebug::ModuleDebug() : Module(MODULE_DEBUG)
{
number_string = new char[5];
}
ModuleDebug::~ModuleDebug()
{
RELEASE_ARRAY(number_string);
}
bool ModuleDebug::Start()
{
if (App->parser->LoadObject(DEBUG_SECTION))
{
number_keys = App->parser->GetInt("FunctionKeyNumber");
fkey_strings = new const char*[number_keys];
fkey_positions = new iPoint[number_keys];
App->parser->LoadArrayInObject("FunctionKeys");
for (int i = 0; i < number_keys; i++)
fkey_strings[i] = App->parser->GetStringFromArray(i);
App->parser->LoadArrayInObject("FunctionPositions");
for (int i = 0; i < number_keys; i++)
{
fkey_positions[i].x = App->parser->GetIntFromArrayInArray(i, 0);
fkey_positions[i].y = App->parser->GetIntFromArrayInArray(i, 1);
}
App->parser->GetPoint(position_letter, "Letter_Init");
App->parser->GetPoint(position_number, "Number_Init");
x_increment = App->parser->GetInt("XIncrement");
unactivated_font = App->parser->GetInt("UnactivatedFontId");
activated_font = App->parser->GetInt("ActivatedFontId");
App->parser->UnloadObject();
}
return true;
}
bool ModuleDebug::CleanUp()
{
RELEASE_ARRAY(fkey_positions);
RELEASE_ARRAY(fkey_strings);
return true;
}
update_status ModuleDebug::Update()
{
if (App->input->GetKey(SDL_SCANCODE_F12) == KEY_DOWN)
bdebug_mode = !bdebug_mode;
if (bdebug_mode)
{
if (App->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN)
bdebug_colliders = !bdebug_colliders;
if (App->input->GetKey(SDL_SCANCODE_F2) == KEY_DOWN)
{
bdebug_camera = !bdebug_camera;
App->renderer->bCenterCamera = !App->renderer->bCenterCamera;
}
if (App->input->GetKey(SDL_SCANCODE_F3) == KEY_DOWN)
bdebug_positions = !bdebug_positions;
if (App->input->GetKey(SDL_SCANCODE_F4) == KEY_DOWN)
{
bdebug_god = !bdebug_god;
int number_players = App->entities->GetNumberPlayers();
for (int i = 0; i < number_players; i++)
{
Player* player = App->entities->GetPlayerByNumber(i);
if (bdebug_god == true)
player->immunity_after_attack->SetMaxTime(0);
else
{
player->immunity_after_attack->SetMaxTime((Uint32)(player->immunity_seconds * 1000.0f));
player->immunity_after_attack->Start();
}
}
}
if (bdebug_colliders)
{
App->collision->DebugDraw();
App->fonts->Blit(activated_font, fkey_positions[0], fkey_strings[0], 0.0f);
}
else
App->fonts->Blit(unactivated_font, fkey_positions[0], fkey_strings[0], 0.0f);
if (bdebug_camera)
{
App->renderer->DebugCamera();
App->fonts->Blit(activated_font, fkey_positions[1], fkey_strings[1], 0.0f);
}
else
App->fonts->Blit(unactivated_font, fkey_positions[1], fkey_strings[1], 0.0f);
if (bdebug_positions)
{
int num_players = App->user_interface->GetNumberOfUIs();
num_players = (num_players > 2) ? 2 : num_players;
int shift = 0;
for (int i = 0; i < num_players; i++)
{
Player* player = App->entities->GetPlayerByNumber(i);
if (player->active)
{
App->fonts->Blit(activated_font, { position_letter.x + shift, position_letter.y }, "x", 0.0f);
App->fonts->Blit(activated_font, { position_letter.x + x_increment + shift, position_letter.y }, "y", 0.0f);
App->fonts->Blit(activated_font, { position_letter.x + 2 * x_increment + shift, position_letter.y }, "z", 0.0f);
App->user_interface->IntToString(player->position.x, number_string);
App->fonts->BlitFromRight(activated_font, { position_number.x + shift, position_number.y }, number_string);
App->user_interface->IntToString(player->position.y, number_string);
App->fonts->BlitFromRight(activated_font, { position_number.x + x_increment + shift, position_number.y }, number_string);
App->user_interface->IntToString(player->position.z, number_string);
App->fonts->BlitFromRight(activated_font, { position_number.x + 2 * x_increment + shift, position_number.y }, number_string);
}
shift += App->window->GetScreenWidth() / 2;
}
App->fonts->Blit(activated_font, fkey_positions[2], fkey_strings[2], 0.0f);
}
else
App->fonts->Blit(unactivated_font, fkey_positions[2], fkey_strings[2], 0.0f);
if (bdebug_god)
App->fonts->Blit(activated_font, fkey_positions[3], fkey_strings[3], 0.0f);
else
App->fonts->Blit(unactivated_font, fkey_positions[3], fkey_strings[3], 0.0f);
}
return UPDATE_CONTINUE;
}
| gpl-3.0 |
Greedysky/TTKMusicplayer | TTKModule/TTKWidget/musicWidgetKits/musicqualitychoicepopwidget.cpp | 1 | 5677 | #include "musicqualitychoicepopwidget.h"
#include "musicqualitywidgetuiobject.h"
#include "musicitemdelegate.h"
#include "musicrightareawidget.h"
#include <QBoxLayout>
#define HOVER_COLOR QColor(255, 255, 255)
#define PREVIOUS_COLOR QColor(187, 187, 187)
MusicQualityChoiceTableWidget::MusicQualityChoiceTableWidget(QWidget *parent)
: MusicAbstractTableWidget(parent)
{
QHeaderView *headerview = horizontalHeader();
headerview->resizeSection(0, 60);
headerview->resizeSection(1, 25);
headerview->resizeSection(2, 25);
setStyleSheet(MusicUIObject::MQSSTableWidgetStyle03 + MusicUIObject::MQSSTableWidgetStyle04);
MusicUtils::Widget::setTransparent(this, 0);
#if defined Q_OS_UNIX && !TTK_QT_VERSION_CHECK(5,7,0) //Fix linux selection-background-color stylesheet bug
MusicUtils::Widget::setTransparent(this, QColor(50, 50, 50));
#endif
MusicCheckBoxDelegate *delegate = new MusicCheckBoxDelegate(this);
delegate->setStyleSheet(MusicUIObject::MQSSCheckBoxStyle02);
setItemDelegateForColumn(2, delegate);
m_previousClickRow = 0;
createItems();
}
MusicQualityChoiceTableWidget::~MusicQualityChoiceTableWidget()
{
clear();
}
void MusicQualityChoiceTableWidget::createItems()
{
setRowCount(4);
QTableWidgetItem *item = new QTableWidgetItem(tr("SD"));
QtItemSetForegroundColor(item, PREVIOUS_COLOR);
QtItemSetTextAlignment(item, Qt::AlignCenter);
setItem(0, 0, item);
item = new QTableWidgetItem(tr("HQ"));
QtItemSetForegroundColor(item, PREVIOUS_COLOR);
QtItemSetTextAlignment(item, Qt::AlignCenter);
setItem(1, 0, item);
item = new QTableWidgetItem(tr("SQ"));
QtItemSetForegroundColor(item, PREVIOUS_COLOR);
QtItemSetTextAlignment(item, Qt::AlignCenter);
setItem(2, 0, item);
item = new QTableWidgetItem(tr("CD"));
QtItemSetForegroundColor(item, PREVIOUS_COLOR);
QtItemSetTextAlignment(item, Qt::AlignCenter);
setItem(3, 0, item);
item = new QTableWidgetItem;
item->setIcon(QIcon(":/quality/lb_sd_quality"));
setItem(0, 1, item);
item = new QTableWidgetItem;
item->setIcon(QIcon(":/quality/lb_hd_quality"));
setItem(1, 1, item);
item = new QTableWidgetItem;
item->setIcon(QIcon(":/quality/lb_sq_quality"));
setItem(2, 1, item);
item = new QTableWidgetItem;
item->setIcon(QIcon(":/quality/lb_cd_quality"));
setItem(3, 1, item);
item = new QTableWidgetItem;
item->setData(MUSIC_CHECK_ROLE, Qt::Checked);
setItem(0, 2, item);
item = new QTableWidgetItem;
item->setData(MUSIC_CHECK_ROLE, Qt::Unchecked);
setItem(1, 2, item);
item = new QTableWidgetItem;
item->setData(MUSIC_CHECK_ROLE, Qt::Unchecked);
setItem(2, 2, item);
item = new QTableWidgetItem;
item->setData(MUSIC_CHECK_ROLE, Qt::Unchecked);
setItem(3, 2, item);
}
void MusicQualityChoiceTableWidget::itemCellEntered(int row, int column)
{
QTableWidgetItem *it = item(m_previousColorRow, 0);
if(it)
{
QtItemSetForegroundColor(it, PREVIOUS_COLOR);
}
MusicAbstractTableWidget::itemCellEntered(row, column);
it = item(row, 0);
if(it)
{
setRowColor(row, QColor(20, 20, 20, 200));
QtItemSetForegroundColor(it, HOVER_COLOR);
}
}
void MusicQualityChoiceTableWidget::itemCellClicked(int row, int)
{
if(m_previousClickRow != -1)
{
item(m_previousClickRow, 2)->setData(MUSIC_CHECK_ROLE, Qt::Unchecked);
}
m_previousClickRow = row;
item(row, 2)->setData(MUSIC_CHECK_ROLE, Qt::Checked);
}
MusicQualityChoicePopWidget::MusicQualityChoicePopWidget(QWidget *parent)
: MusicToolMenuWidget(parent)
{
setToolTip(tr("Quality Choice"));
setFixedSize(48, 20);
initialize();
setStyleSheet(MusicUIObject::MQSSToolButtonStyle05 + MusicUIObject::MQSSBtnQuality + "QToolButton{ margin-left:-48px; }");
}
void MusicQualityChoicePopWidget::initialize()
{
setTranslucentBackground();
m_menu->setStyleSheet(MusicUIObject::MQSSMenuStyle04);
QHBoxLayout *layout = new QHBoxLayout(m_containWidget);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
MusicQualityChoiceTableWidget *table = new MusicQualityChoiceTableWidget(m_containWidget);
connect(table, SIGNAL(cellClicked(int ,int)), SLOT(itemCellClicked(int)));
layout->addWidget(table);
m_containWidget->setFixedSize(110, 120);
m_containWidget->setLayout(layout);
}
void MusicQualityChoicePopWidget::itemCellClicked(int row)
{
m_menu->close();
QString style;
MusicObject::QueryQuality quality = MusicObject::QueryQuality::Standard;
switch(row)
{
case 0:
{
style = "QToolButton{ margin-left:-0px; }";
quality = MusicObject::QueryQuality::Standard;
break;
}
case 1:
{
style = "QToolButton{ margin-left:-48px; }";
quality = MusicObject::QueryQuality::High;
break;
}
case 2:
{
style = "QToolButton{ margin-left:-96px; }";
quality = MusicObject::QueryQuality::Super;
break;
}
case 3:
{
style = "QToolButton{ margin-left:-144px; }";
quality = MusicObject::QueryQuality::Lossless;
break;
}
default: break;
}
setStyleSheet(styleSheet() + style);
MusicRightAreaWidget::instance()->researchQueryByQuality(quality);
}
| gpl-3.0 |
danielrothmann/Roth-AIR | JuceLibraryCode/modules/juce_audio_plugin_client/VST3/juce_VST3_Wrapper.cpp | 1 | 127811 | /*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
End User License Agreement: www.juce.com/juce-6-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
#include <juce_core/system/juce_CompilerWarnings.h>
#include <juce_core/system/juce_TargetPlatform.h>
//==============================================================================
#if JucePlugin_Build_VST3 && (JUCE_MAC || JUCE_WINDOWS || JUCE_LINUX)
#if JUCE_PLUGINHOST_VST3
#if JUCE_MAC
#include <CoreFoundation/CoreFoundation.h>
#endif
#undef JUCE_VST3HEADERS_INCLUDE_HEADERS_ONLY
#define JUCE_VST3HEADERS_INCLUDE_HEADERS_ONLY 1
#endif
#include <juce_audio_processors/format_types/juce_VST3Headers.h>
#undef JUCE_VST3HEADERS_INCLUDE_HEADERS_ONLY
#define JUCE_GUI_BASICS_INCLUDE_XHEADERS 1
#include "../utility/juce_CheckSettingMacros.h"
#include "../utility/juce_IncludeSystemHeaders.h"
#include "../utility/juce_IncludeModuleHeaders.h"
#include "../utility/juce_WindowsHooks.h"
#include "../utility/juce_FakeMouseMoveGenerator.h"
#include <juce_audio_processors/format_types/juce_LegacyAudioParameter.cpp>
#include <juce_audio_processors/format_types/juce_VST3Common.h>
#ifndef JUCE_VST3_CAN_REPLACE_VST2
#define JUCE_VST3_CAN_REPLACE_VST2 1
#endif
#if JUCE_VST3_CAN_REPLACE_VST2
#if ! JUCE_MSVC
#define __cdecl
#endif
namespace Vst2
{
#include "pluginterfaces/vst2.x/vstfxstore.h"
}
#endif
#ifndef JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
#if JucePlugin_WantsMidiInput
#define JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS 1
#endif
#endif
#if JUCE_LINUX
#include <unordered_map>
std::vector<std::pair<int, std::function<void (int)>>> getFdReadCallbacks();
#endif
namespace juce
{
using namespace Steinberg;
//==============================================================================
#if JUCE_MAC
extern void initialiseMacVST();
#if ! JUCE_64BIT
extern void updateEditorCompBoundsVST (Component*);
#endif
extern JUCE_API void* attachComponentToWindowRefVST (Component*, void* parentWindowOrView, bool isNSView);
extern JUCE_API void detachComponentFromWindowRefVST (Component*, void* nsWindow, bool isNSView);
#endif
#if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
extern JUCE_API double getScaleFactorForWindow (HWND);
#endif
//==============================================================================
class JuceAudioProcessor : public Vst::IUnitInfo
{
public:
JuceAudioProcessor (AudioProcessor* source) noexcept
: audioProcessor (source)
{
setupParameters();
}
virtual ~JuceAudioProcessor() {}
AudioProcessor* get() const noexcept { return audioProcessor.get(); }
JUCE_DECLARE_VST3_COM_QUERY_METHODS
JUCE_DECLARE_VST3_COM_REF_METHODS
//==============================================================================
enum InternalParameters
{
paramPreset = 0x70727374, // 'prst'
paramMidiControllerOffset = 0x6d636d00, // 'mdm*'
paramBypass = 0x62797073 // 'byps'
};
//==============================================================================
Steinberg::int32 PLUGIN_API getUnitCount() override
{
return parameterGroups.size() + 1;
}
tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override
{
if (unitIndex == 0)
{
info.id = Vst::kRootUnitId;
info.parentUnitId = Vst::kNoParentUnitId;
info.programListId = Vst::kNoProgramListId;
toString128 (info.name, TRANS("Root Unit"));
return kResultTrue;
}
if (auto* group = parameterGroups[unitIndex - 1])
{
info.id = JuceAudioProcessor::getUnitID (group);
info.parentUnitId = JuceAudioProcessor::getUnitID (group->getParent());
info.programListId = Vst::kNoProgramListId;
toString128 (info.name, group->getName());
return kResultTrue;
}
return kResultFalse;
}
Steinberg::int32 PLUGIN_API getProgramListCount() override
{
if (audioProcessor->getNumPrograms() > 0)
return 1;
return 0;
}
tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override
{
if (listIndex == 0)
{
info.id = paramPreset;
info.programCount = (Steinberg::int32) audioProcessor->getNumPrograms();
toString128 (info.name, TRANS("Factory Presets"));
return kResultTrue;
}
jassertfalse;
zerostruct (info);
return kResultFalse;
}
tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override
{
if (listId == paramPreset
&& isPositiveAndBelow ((int) programIndex, audioProcessor->getNumPrograms()))
{
toString128 (name, audioProcessor->getProgramName ((int) programIndex));
return kResultTrue;
}
jassertfalse;
toString128 (name, juce::String());
return kResultFalse;
}
tresult PLUGIN_API getProgramInfo (Vst::ProgramListID, Steinberg::int32, Vst::CString, Vst::String128) override { return kNotImplemented; }
tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID, Steinberg::int32) override { return kNotImplemented; }
tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID, Steinberg::int32, Steinberg::int16, Vst::String128) override { return kNotImplemented; }
tresult PLUGIN_API selectUnit (Vst::UnitID) override { return kNotImplemented; }
tresult PLUGIN_API setUnitProgramData (Steinberg::int32, Steinberg::int32, IBStream*) override { return kNotImplemented; }
Vst::UnitID PLUGIN_API getSelectedUnit() override { return Vst::kRootUnitId; }
tresult PLUGIN_API getUnitByBus (Vst::MediaType, Vst::BusDirection, Steinberg::int32, Steinberg::int32, Vst::UnitID& unitId) override
{
zerostruct (unitId);
return kNotImplemented;
}
//==============================================================================
inline Vst::ParamID getVSTParamIDForIndex (int paramIndex) const noexcept
{
#if JUCE_FORCE_USE_LEGACY_PARAM_IDS
return static_cast<Vst::ParamID> (paramIndex);
#else
return vstParamIDs.getReference (paramIndex);
#endif
}
AudioProcessorParameter* getParamForVSTParamID (Vst::ParamID paramID) const noexcept
{
return paramMap[static_cast<int32> (paramID)];
}
AudioProcessorParameter* getBypassParameter() const noexcept
{
return getParamForVSTParamID (bypassParamID);
}
static Vst::UnitID getUnitID (const AudioProcessorParameterGroup* group)
{
return group == nullptr ? Vst::kRootUnitId : group->getID().hashCode();
}
int getNumParameters() const noexcept { return vstParamIDs.size(); }
bool isUsingManagedParameters() const noexcept { return juceParameters.isUsingManagedParameters(); }
//==============================================================================
static const FUID iid;
Array<Vst::ParamID> vstParamIDs;
Vst::ParamID bypassParamID = 0;
bool bypassIsRegularParameter = false;
private:
//==============================================================================
bool isBypassPartOfRegularParemeters() const
{
int n = juceParameters.getNumParameters();
if (auto* bypassParam = audioProcessor->getBypassParameter())
for (int i = 0; i < n; ++i)
if (juceParameters.getParamForIndex (i) == bypassParam)
return true;
return false;
}
void setupParameters()
{
parameterGroups = audioProcessor->getParameterTree().getSubgroups (true);
#if JUCE_FORCE_USE_LEGACY_PARAM_IDS
const bool forceLegacyParamIDs = true;
#else
const bool forceLegacyParamIDs = false;
#endif
juceParameters.update (*audioProcessor, forceLegacyParamIDs);
auto numParameters = juceParameters.getNumParameters();
bool vst3WrapperProvidedBypassParam = false;
auto* bypassParameter = audioProcessor->getBypassParameter();
if (bypassParameter == nullptr)
{
vst3WrapperProvidedBypassParam = true;
ownedBypassParameter.reset (new AudioParameterBool ("byps", "Bypass", false, {}, {}, {}));
bypassParameter = ownedBypassParameter.get();
}
// if the bypass parameter is not part of the exported parameters that the plug-in supports
// then add it to the end of the list as VST3 requires the bypass parameter to be exported!
bypassIsRegularParameter = isBypassPartOfRegularParemeters();
if (! bypassIsRegularParameter)
juceParameters.params.add (bypassParameter);
int i = 0;
for (auto* juceParam : juceParameters.params)
{
bool isBypassParameter = (juceParam == bypassParameter);
Vst::ParamID vstParamID = forceLegacyParamIDs ? static_cast<Vst::ParamID> (i++)
: generateVSTParamIDForParam (juceParam);
if (isBypassParameter)
{
// we need to remain backward compatible with the old bypass id
if (vst3WrapperProvidedBypassParam)
vstParamID = static_cast<Vst::ParamID> ((isUsingManagedParameters() && ! forceLegacyParamIDs) ? paramBypass : numParameters);
bypassParamID = vstParamID;
}
vstParamIDs.add (vstParamID);
paramMap.set (static_cast<int32> (vstParamID), juceParam);
}
}
Vst::ParamID generateVSTParamIDForParam (AudioProcessorParameter* param)
{
auto juceParamID = LegacyAudioParameter::getParamID (param, false);
#if JUCE_FORCE_USE_LEGACY_PARAM_IDS
return static_cast<Vst::ParamID> (juceParamID.getIntValue());
#else
auto paramHash = static_cast<Vst::ParamID> (juceParamID.hashCode());
#if JUCE_USE_STUDIO_ONE_COMPATIBLE_PARAMETERS
// studio one doesn't like negative parameters
paramHash &= ~(((Vst::ParamID) 1) << (sizeof (Vst::ParamID) * 8 - 1));
#endif
return paramHash;
#endif
}
//==============================================================================
std::atomic<int> refCount { 0 };
std::unique_ptr<AudioProcessor> audioProcessor;
//==============================================================================
LegacyAudioParametersWrapper juceParameters;
HashMap<int32, AudioProcessorParameter*> paramMap;
std::unique_ptr<AudioProcessorParameter> ownedBypassParameter;
Array<const AudioProcessorParameterGroup*> parameterGroups;
JuceAudioProcessor() = delete;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceAudioProcessor)
};
class JuceVST3Component;
static ThreadLocalValue<bool> inParameterChangedCallback;
//==============================================================================
class JuceVST3EditController : public Vst::EditController,
public Vst::IMidiMapping,
public Vst::IUnitInfo,
public Vst::ChannelContext::IInfoListener,
public AudioProcessorListener,
private AudioProcessorParameter::Listener
{
public:
JuceVST3EditController (Vst::IHostApplication* host)
{
if (host != nullptr)
host->queryInterface (FUnknown::iid, (void**) &hostContext);
}
//==============================================================================
static const FUID iid;
//==============================================================================
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Winconsistent-missing-override")
REFCOUNT_METHODS (ComponentBase)
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
{
TEST_FOR_AND_RETURN_IF_VALID (targetIID, FObject)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3EditController)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IEditController)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IEditController2)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IMidiMapping)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IUnitInfo)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::ChannelContext::IInfoListener)
TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, IPluginBase, Vst::IEditController)
TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, IDependent, Vst::IEditController)
TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IEditController)
if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
{
audioProcessor->addRef();
*obj = audioProcessor;
return kResultOk;
}
*obj = nullptr;
return kNoInterface;
}
//==============================================================================
tresult PLUGIN_API initialize (FUnknown* context) override
{
if (hostContext != context)
{
if (hostContext != nullptr)
hostContext->release();
hostContext = context;
if (hostContext != nullptr)
hostContext->addRef();
}
return kResultTrue;
}
tresult PLUGIN_API terminate() override
{
if (auto* pluginInstance = getPluginInstance())
pluginInstance->removeListener (this);
audioProcessor = nullptr;
return EditController::terminate();
}
//==============================================================================
struct Param : public Vst::Parameter
{
Param (JuceVST3EditController& editController, AudioProcessorParameter& p,
Vst::ParamID vstParamID, Vst::UnitID vstUnitID,
bool isBypassParameter)
: owner (editController), param (p)
{
info.id = vstParamID;
info.unitId = vstUnitID;
updateParameterInfo();
info.stepCount = (Steinberg::int32) 0;
#if ! JUCE_FORCE_LEGACY_PARAMETER_AUTOMATION_TYPE
if (param.isDiscrete())
#endif
{
const int numSteps = param.getNumSteps();
info.stepCount = (Steinberg::int32) (numSteps > 0 && numSteps < 0x7fffffff ? numSteps - 1 : 0);
}
info.defaultNormalizedValue = param.getDefaultValue();
jassert (info.defaultNormalizedValue >= 0 && info.defaultNormalizedValue <= 1.0f);
// Is this a meter?
if ((((unsigned int) param.getCategory() & 0xffff0000) >> 16) == 2)
info.flags = Vst::ParameterInfo::kIsReadOnly;
else
info.flags = param.isAutomatable() ? Vst::ParameterInfo::kCanAutomate : 0;
if (isBypassParameter)
info.flags |= Vst::ParameterInfo::kIsBypass;
valueNormalized = info.defaultNormalizedValue;
}
virtual ~Param() override = default;
bool updateParameterInfo()
{
auto updateParamIfChanged = [] (Vst::String128& paramToUpdate, const String& newValue)
{
if (juce::toString (paramToUpdate) == newValue)
return false;
toString128 (paramToUpdate, newValue);
return true;
};
auto anyUpdated = updateParamIfChanged (info.title, param.getName (128));
anyUpdated |= updateParamIfChanged (info.shortTitle, param.getName (8));
anyUpdated |= updateParamIfChanged (info.units, param.getLabel());
return anyUpdated;
}
bool setNormalized (Vst::ParamValue v) override
{
v = jlimit (0.0, 1.0, v);
if (v != valueNormalized)
{
valueNormalized = v;
// Only update the AudioProcessor here if we're not playing,
// otherwise we get parallel streams of parameter value updates
// during playback
if (! owner.vst3IsPlaying)
{
auto value = static_cast<float> (v);
param.setValue (value);
inParameterChangedCallback = true;
param.sendValueChangedMessageToListeners (value);
}
changed();
return true;
}
return false;
}
void toString (Vst::ParamValue value, Vst::String128 result) const override
{
if (LegacyAudioParameter::isLegacy (¶m))
// remain backward-compatible with old JUCE code
toString128 (result, param.getCurrentValueAsText());
else
toString128 (result, param.getText ((float) value, 128));
}
bool fromString (const Vst::TChar* text, Vst::ParamValue& outValueNormalized) const override
{
if (! LegacyAudioParameter::isLegacy (¶m))
{
outValueNormalized = param.getValueForText (getStringFromVstTChars (text));
return true;
}
return false;
}
static String getStringFromVstTChars (const Vst::TChar* text)
{
return juce::String (juce::CharPointer_UTF16 (reinterpret_cast<const juce::CharPointer_UTF16::CharType*> (text)));
}
Vst::ParamValue toPlain (Vst::ParamValue v) const override { return v; }
Vst::ParamValue toNormalized (Vst::ParamValue v) const override { return v; }
private:
JuceVST3EditController& owner;
AudioProcessorParameter& param;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Param)
};
//==============================================================================
struct ProgramChangeParameter : public Vst::Parameter
{
ProgramChangeParameter (AudioProcessor& p) : owner (p)
{
jassert (owner.getNumPrograms() > 1);
info.id = JuceAudioProcessor::paramPreset;
toString128 (info.title, "Program");
toString128 (info.shortTitle, "Program");
toString128 (info.units, "");
info.stepCount = owner.getNumPrograms() - 1;
info.defaultNormalizedValue = static_cast<Vst::ParamValue> (owner.getCurrentProgram())
/ static_cast<Vst::ParamValue> (info.stepCount);
info.unitId = Vst::kRootUnitId;
info.flags = Vst::ParameterInfo::kIsProgramChange | Vst::ParameterInfo::kCanAutomate;
}
virtual ~ProgramChangeParameter() override = default;
bool setNormalized (Vst::ParamValue v) override
{
Vst::ParamValue program = v * info.stepCount;
if (! isPositiveAndBelow ((int) program, owner.getNumPrograms()))
return false;
if (valueNormalized != v)
{
valueNormalized = v;
changed();
return true;
}
return false;
}
void toString (Vst::ParamValue value, Vst::String128 result) const override
{
toString128 (result, owner.getProgramName (roundToInt (value * info.stepCount)));
}
bool fromString (const Vst::TChar* text, Vst::ParamValue& outValueNormalized) const override
{
auto paramValueString = getStringFromVstTChars (text);
auto n = owner.getNumPrograms();
for (int i = 0; i < n; ++i)
{
if (paramValueString == owner.getProgramName (i))
{
outValueNormalized = static_cast<Vst::ParamValue> (i) / info.stepCount;
return true;
}
}
return false;
}
static String getStringFromVstTChars (const Vst::TChar* text)
{
return String (CharPointer_UTF16 (reinterpret_cast<const CharPointer_UTF16::CharType*> (text)));
}
Vst::ParamValue toPlain (Vst::ParamValue v) const override { return v * info.stepCount; }
Vst::ParamValue toNormalized (Vst::ParamValue v) const override { return v / info.stepCount; }
private:
AudioProcessor& owner;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProgramChangeParameter)
};
//==============================================================================
tresult PLUGIN_API setChannelContextInfos (Vst::IAttributeList* list) override
{
if (auto* instance = getPluginInstance())
{
if (list != nullptr)
{
AudioProcessor::TrackProperties trackProperties;
{
Vst::String128 channelName;
if (list->getString (Vst::ChannelContext::kChannelNameKey, channelName, sizeof (channelName)) == kResultTrue)
trackProperties.name = toString (channelName);
}
{
int64 colour;
if (list->getInt (Vst::ChannelContext::kChannelColorKey, colour) == kResultTrue)
trackProperties.colour = Colour (Vst::ChannelContext::GetRed ((uint32) colour), Vst::ChannelContext::GetGreen ((uint32) colour),
Vst::ChannelContext::GetBlue ((uint32) colour), Vst::ChannelContext::GetAlpha ((uint32) colour));
}
if (MessageManager::getInstance()->isThisTheMessageThread())
instance->updateTrackProperties (trackProperties);
else
MessageManager::callAsync ([trackProperties, instance]
{ instance->updateTrackProperties (trackProperties); });
}
}
return kResultOk;
}
//==============================================================================
tresult PLUGIN_API setComponentState (IBStream* stream) override
{
// Cubase and Nuendo need to inform the host of the current parameter values
if (auto* pluginInstance = getPluginInstance())
{
for (auto vstParamId : audioProcessor->vstParamIDs)
setParamNormalized (vstParamId, audioProcessor->getParamForVSTParamID (vstParamId)->getValue());
auto numPrograms = pluginInstance->getNumPrograms();
if (numPrograms > 1)
setParamNormalized (JuceAudioProcessor::paramPreset, static_cast<Vst::ParamValue> (pluginInstance->getCurrentProgram())
/ static_cast<Vst::ParamValue> (numPrograms - 1));
}
if (auto* handler = getComponentHandler())
handler->restartComponent (Vst::kParamValuesChanged);
return Vst::EditController::setComponentState (stream);
}
void setAudioProcessor (JuceAudioProcessor* audioProc)
{
if (audioProcessor != audioProc)
{
audioProcessor = audioProc;
setupParameters();
}
}
tresult PLUGIN_API connect (IConnectionPoint* other) override
{
if (other != nullptr && audioProcessor == nullptr)
{
auto result = ComponentBase::connect (other);
if (! audioProcessor.loadFrom (other))
sendIntMessage ("JuceVST3EditController", (Steinberg::int64) (pointer_sized_int) this);
else
setupParameters();
return result;
}
jassertfalse;
return kResultFalse;
}
//==============================================================================
tresult PLUGIN_API getMidiControllerAssignment (Steinberg::int32 /*busIndex*/, Steinberg::int16 channel,
Vst::CtrlNumber midiControllerNumber, Vst::ParamID& resultID) override
{
#if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
resultID = midiControllerToParameter[channel][midiControllerNumber];
return kResultTrue; // Returning false makes some hosts stop asking for further MIDI Controller Assignments
#else
ignoreUnused (channel, midiControllerNumber, resultID);
return kResultFalse;
#endif
}
// Converts an incoming parameter index to a MIDI controller:
bool getMidiControllerForParameter (Vst::ParamID index, int& channel, int& ctrlNumber)
{
auto mappedIndex = static_cast<int> (index - parameterToMidiControllerOffset);
if (isPositiveAndBelow (mappedIndex, numElementsInArray (parameterToMidiController)))
{
auto& mc = parameterToMidiController[mappedIndex];
if (mc.channel != -1 && mc.ctrlNumber != -1)
{
channel = jlimit (1, 16, mc.channel + 1);
ctrlNumber = mc.ctrlNumber;
return true;
}
}
return false;
}
inline bool isMidiControllerParamID (Vst::ParamID paramID) const noexcept
{
return (paramID >= parameterToMidiControllerOffset
&& isPositiveAndBelow (paramID - parameterToMidiControllerOffset,
static_cast<Vst::ParamID> (numElementsInArray (parameterToMidiController))));
}
//==============================================================================
Steinberg::int32 PLUGIN_API getUnitCount() override
{
if (audioProcessor != nullptr)
return audioProcessor->getUnitCount();
jassertfalse;
return 1;
}
tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override
{
if (audioProcessor != nullptr)
return audioProcessor->getUnitInfo (unitIndex, info);
if (unitIndex == 0)
{
info.id = Vst::kRootUnitId;
info.parentUnitId = Vst::kNoParentUnitId;
info.programListId = Vst::kNoProgramListId;
toString128 (info.name, TRANS("Root Unit"));
return kResultTrue;
}
jassertfalse;
zerostruct (info);
return kResultFalse;
}
Steinberg::int32 PLUGIN_API getProgramListCount() override
{
if (audioProcessor != nullptr)
return audioProcessor->getProgramListCount();
jassertfalse;
return 0;
}
tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override
{
if (audioProcessor != nullptr)
return audioProcessor->getProgramListInfo (listIndex, info);
jassertfalse;
zerostruct (info);
return kResultFalse;
}
tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override
{
if (audioProcessor != nullptr)
return audioProcessor->getProgramName (listId, programIndex, name);
jassertfalse;
toString128 (name, juce::String());
return kResultFalse;
}
tresult PLUGIN_API getProgramInfo (Vst::ProgramListID listId, Steinberg::int32 programIndex,
Vst::CString attributeId, Vst::String128 attributeValue) override
{
if (audioProcessor != nullptr)
return audioProcessor->getProgramInfo (listId, programIndex, attributeId, attributeValue);
jassertfalse;
return kResultFalse;
}
tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID listId, Steinberg::int32 programIndex) override
{
if (audioProcessor != nullptr)
return audioProcessor->hasProgramPitchNames (listId, programIndex);
jassertfalse;
return kResultFalse;
}
tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID listId, Steinberg::int32 programIndex,
Steinberg::int16 midiPitch, Vst::String128 name) override
{
if (audioProcessor != nullptr)
return audioProcessor->getProgramPitchName (listId, programIndex, midiPitch, name);
jassertfalse;
return kResultFalse;
}
tresult PLUGIN_API selectUnit (Vst::UnitID unitId) override
{
if (audioProcessor != nullptr)
return audioProcessor->selectUnit (unitId);
jassertfalse;
return kResultFalse;
}
tresult PLUGIN_API setUnitProgramData (Steinberg::int32 listOrUnitId, Steinberg::int32 programIndex,
Steinberg::IBStream* data) override
{
if (audioProcessor != nullptr)
return audioProcessor->setUnitProgramData (listOrUnitId, programIndex, data);
jassertfalse;
return kResultFalse;
}
Vst::UnitID PLUGIN_API getSelectedUnit() override
{
if (audioProcessor != nullptr)
return audioProcessor->getSelectedUnit();
jassertfalse;
return kResultFalse;
}
tresult PLUGIN_API getUnitByBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 busIndex,
Steinberg::int32 channel, Vst::UnitID& unitId) override
{
if (audioProcessor != nullptr)
return audioProcessor->getUnitByBus (type, dir, busIndex, channel, unitId);
jassertfalse;
return kResultFalse;
}
//==============================================================================
IPlugView* PLUGIN_API createView (const char* name) override
{
if (auto* pluginInstance = getPluginInstance())
{
if (pluginInstance->hasEditor() && name != nullptr
&& strcmp (name, Vst::ViewType::kEditor) == 0)
{
return new JuceVST3Editor (*this, *pluginInstance);
}
}
return nullptr;
}
//==============================================================================
void paramChanged (Vst::ParamID vstParamId, float newValue)
{
if (inParameterChangedCallback.get())
{
inParameterChangedCallback = false;
return;
}
// NB: Cubase has problems if performEdit is called without setParamNormalized
EditController::setParamNormalized (vstParamId, (double) newValue);
performEdit (vstParamId, (double) newValue);
}
//==============================================================================
void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index) override { beginEdit (audioProcessor->getVSTParamIDForIndex (index)); }
void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index) override { endEdit (audioProcessor->getVSTParamIDForIndex (index)); }
void audioProcessorParameterChanged (AudioProcessor*, int index, float newValue) override
{
paramChanged (audioProcessor->getVSTParamIDForIndex (index), newValue);
}
void audioProcessorChanged (AudioProcessor*) override
{
int32 flags = 0;
for (int32 i = 0; i < parameters.getParameterCount(); ++i)
if (auto* param = dynamic_cast<Param*> (parameters.getParameterByIndex (i)))
if (param->updateParameterInfo() && (flags & Vst::kParamTitlesChanged) == 0)
flags |= Vst::kParamTitlesChanged;
if (auto* pluginInstance = getPluginInstance())
{
auto newNumPrograms = pluginInstance->getNumPrograms();
if (newNumPrograms != lastNumPrograms)
{
if (newNumPrograms > 1)
{
auto paramValue = static_cast<Vst::ParamValue> (pluginInstance->getCurrentProgram())
/ static_cast<Vst::ParamValue> (pluginInstance->getNumPrograms() - 1);
EditController::setParamNormalized (JuceAudioProcessor::paramPreset, paramValue);
flags |= Vst::kParamValuesChanged;
}
lastNumPrograms = newNumPrograms;
}
auto newLatencySamples = pluginInstance->getLatencySamples();
if (newLatencySamples != lastLatencySamples)
{
flags |= Vst::kLatencyChanged;
lastLatencySamples = newLatencySamples;
}
}
if (flags != 0 && componentHandler != nullptr && ! inSetupProcessing)
componentHandler->restartComponent (flags);
}
void parameterValueChanged (int, float newValue) override
{
// this can only come from the bypass parameter
paramChanged (audioProcessor->bypassParamID, newValue);
}
void parameterGestureChanged (int, bool gestureIsStarting) override
{
// this can only come from the bypass parameter
if (gestureIsStarting) beginEdit (audioProcessor->bypassParamID);
else endEdit (audioProcessor->bypassParamID);
}
//==============================================================================
AudioProcessor* getPluginInstance() const noexcept
{
if (audioProcessor != nullptr)
return audioProcessor->get();
return nullptr;
}
private:
friend class JuceVST3Component;
friend struct Param;
//==============================================================================
ComSmartPtr<JuceAudioProcessor> audioProcessor;
struct MidiController
{
int channel = -1, ctrlNumber = -1;
};
enum { numMIDIChannels = 16 };
Vst::ParamID parameterToMidiControllerOffset;
MidiController parameterToMidiController[(int) numMIDIChannels * (int) Vst::kCountCtrlNumber];
Vst::ParamID midiControllerToParameter[numMIDIChannels][Vst::kCountCtrlNumber];
//==============================================================================
std::atomic<bool> vst3IsPlaying { false },
inSetupProcessing { false };
int lastNumPrograms = 0, lastLatencySamples = 0;
#if ! JUCE_MAC
float lastScaleFactorReceived = 1.0f;
#endif
void setupParameters()
{
if (auto* pluginInstance = getPluginInstance())
{
pluginInstance->addListener (this);
// as the bypass is not part of the regular parameters
// we need to listen for it explicitly
if (! audioProcessor->bypassIsRegularParameter)
audioProcessor->getBypassParameter()->addListener (this);
if (parameters.getParameterCount() <= 0)
{
auto n = audioProcessor->getNumParameters();
for (int i = 0; i < n; ++i)
{
auto vstParamID = audioProcessor->getVSTParamIDForIndex (i);
auto* juceParam = audioProcessor->getParamForVSTParamID (vstParamID);
auto* parameterGroup = pluginInstance->getParameterTree().getGroupsForParameter (juceParam).getLast();
auto unitID = JuceAudioProcessor::getUnitID (parameterGroup);
parameters.addParameter (new Param (*this, *juceParam, vstParamID, unitID,
(vstParamID == audioProcessor->bypassParamID)));
}
if (pluginInstance->getNumPrograms() > 1)
parameters.addParameter (new ProgramChangeParameter (*pluginInstance));
}
#if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
parameterToMidiControllerOffset = static_cast<Vst::ParamID> (audioProcessor->isUsingManagedParameters() ? JuceAudioProcessor::paramMidiControllerOffset
: parameters.getParameterCount());
initialiseMidiControllerMappings();
#endif
audioProcessorChanged (pluginInstance);
}
}
void initialiseMidiControllerMappings()
{
for (int c = 0, p = 0; c < numMIDIChannels; ++c)
{
for (int i = 0; i < Vst::kCountCtrlNumber; ++i, ++p)
{
midiControllerToParameter[c][i] = static_cast<Vst::ParamID> (p) + parameterToMidiControllerOffset;
parameterToMidiController[p].channel = c;
parameterToMidiController[p].ctrlNumber = i;
parameters.addParameter (new Vst::Parameter (toString ("MIDI CC " + String (c) + "|" + String (i)),
static_cast<Vst::ParamID> (p) + parameterToMidiControllerOffset, nullptr, 0, 0,
0, Vst::kRootUnitId));
}
}
}
void sendIntMessage (const char* idTag, const Steinberg::int64 value)
{
jassert (hostContext != nullptr);
if (auto* message = allocateMessage())
{
const FReleaser releaser (message);
message->setMessageID (idTag);
message->getAttributes()->setInt (idTag, value);
sendMessage (message);
}
}
//==============================================================================
class JuceVST3Editor : public Vst::EditorView,
public Steinberg::IPlugViewContentScaleSupport,
#if JUCE_LINUX
public Steinberg::Linux::IEventHandler,
#endif
private Timer
{
public:
JuceVST3Editor (JuceVST3EditController& ec, AudioProcessor& p)
: Vst::EditorView (&ec, nullptr),
owner (&ec), pluginInstance (p)
{
createContentWrapperComponentIfNeeded();
#if JUCE_MAC
if (getHostType().type == PluginHostType::SteinbergCubase10)
cubase10Workaround.reset (new Cubase10WindowResizeWorkaround (*this));
#else
if (! approximatelyEqual (editorScaleFactor, ec.lastScaleFactorReceived))
setContentScaleFactor (ec.lastScaleFactorReceived);
#endif
}
tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
{
TEST_FOR_AND_RETURN_IF_VALID (targetIID, Steinberg::IPlugViewContentScaleSupport)
return Vst::EditorView::queryInterface (targetIID, obj);
}
REFCOUNT_METHODS (Vst::EditorView)
//==============================================================================
#if JUCE_LINUX
void PLUGIN_API onFDIsSet (Steinberg::Linux::FileDescriptor fd) override
{
if (plugFrame != nullptr)
{
auto it = fdCallbackMap.find (fd);
if (it != fdCallbackMap.end())
it->second (fd);
}
}
#endif
//==============================================================================
tresult PLUGIN_API isPlatformTypeSupported (FIDString type) override
{
if (type != nullptr && pluginInstance.hasEditor())
{
#if JUCE_WINDOWS
if (strcmp (type, kPlatformTypeHWND) == 0)
#elif JUCE_MAC
if (strcmp (type, kPlatformTypeNSView) == 0 || strcmp (type, kPlatformTypeHIView) == 0)
#elif JUCE_LINUX
if (strcmp (type, kPlatformTypeX11EmbedWindowID) == 0)
#endif
return kResultTrue;
}
return kResultFalse;
}
tresult PLUGIN_API attached (void* parent, FIDString type) override
{
if (parent == nullptr || isPlatformTypeSupported (type) == kResultFalse)
return kResultFalse;
systemWindow = parent;
createContentWrapperComponentIfNeeded();
#if JUCE_WINDOWS || JUCE_LINUX
component->addToDesktop (0, parent);
component->setOpaque (true);
component->setVisible (true);
#if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
component->checkHostWindowScaleFactor();
component->startTimer (500);
#endif
#if JUCE_LINUX
if (auto* runLoop = getHostRunLoop())
{
for (auto& cb : getFdReadCallbacks())
{
fdCallbackMap[cb.first] = cb.second;
runLoop->registerEventHandler (this, cb.first);
}
}
#endif
#else
isNSView = (strcmp (type, kPlatformTypeNSView) == 0);
macHostWindow = juce::attachComponentToWindowRefVST (component.get(), parent, isNSView);
#endif
component->resizeHostWindow();
attachedToParent();
// Life's too short to faff around with wave lab
if (getHostType().isWavelab())
startTimer (200);
return kResultTrue;
}
tresult PLUGIN_API removed() override
{
if (component != nullptr)
{
#if JUCE_WINDOWS
component->removeFromDesktop();
#elif JUCE_LINUX
fdCallbackMap.clear();
if (auto* runLoop = getHostRunLoop())
runLoop->unregisterEventHandler (this);
#else
if (macHostWindow != nullptr)
{
juce::detachComponentFromWindowRefVST (component.get(), macHostWindow, isNSView);
macHostWindow = nullptr;
}
#endif
component = nullptr;
}
return CPluginView::removed();
}
tresult PLUGIN_API onSize (ViewRect* newSize) override
{
if (newSize != nullptr)
{
rect = convertFromHostBounds (*newSize);
if (component != nullptr)
{
auto w = rect.getWidth();
auto h = rect.getHeight();
component->setSize (w, h);
#if JUCE_MAC
if (cubase10Workaround != nullptr)
{
cubase10Workaround->triggerAsyncUpdate();
}
else
#endif
{
if (auto* peer = component->getPeer())
peer->updateBounds();
}
}
return kResultTrue;
}
jassertfalse;
return kResultFalse;
}
tresult PLUGIN_API getSize (ViewRect* size) override
{
if (size != nullptr && component != nullptr)
{
auto editorBounds = component->getSizeToContainChild();
*size = convertToHostBounds ({ 0, 0, editorBounds.getWidth(), editorBounds.getHeight() });
return kResultTrue;
}
return kResultFalse;
}
tresult PLUGIN_API canResize() override
{
if (component != nullptr)
if (auto* editor = component->pluginEditor.get())
if (editor->isResizable())
return kResultTrue;
return kResultFalse;
}
tresult PLUGIN_API checkSizeConstraint (ViewRect* rectToCheck) override
{
if (rectToCheck != nullptr && component != nullptr)
{
if (auto* editor = component->pluginEditor.get())
{
if (auto* constrainer = editor->getConstrainer())
{
*rectToCheck = convertFromHostBounds (*rectToCheck);
auto transformScale = std::sqrt (std::abs (editor->getTransform().getDeterminant()));
auto minW = (double) ((float) constrainer->getMinimumWidth() * transformScale);
auto maxW = (double) ((float) constrainer->getMaximumWidth() * transformScale);
auto minH = (double) ((float) constrainer->getMinimumHeight() * transformScale);
auto maxH = (double) ((float) constrainer->getMaximumHeight() * transformScale);
auto width = (double) (rectToCheck->right - rectToCheck->left);
auto height = (double) (rectToCheck->bottom - rectToCheck->top);
width = jlimit (minW, maxW, width);
height = jlimit (minH, maxH, height);
auto aspectRatio = constrainer->getFixedAspectRatio();
if (aspectRatio != 0.0)
{
bool adjustWidth = (width / height > aspectRatio);
if (getHostType().type == PluginHostType::SteinbergCubase9)
{
if (editor->getWidth() == width && editor->getHeight() != height)
adjustWidth = true;
else if (editor->getHeight() == height && editor->getWidth() != width)
adjustWidth = false;
}
if (adjustWidth)
{
width = height * aspectRatio;
if (width > maxW || width < minW)
{
width = jlimit (minW, maxW, width);
height = width / aspectRatio;
}
}
else
{
height = width / aspectRatio;
if (height > maxH || height < minH)
{
height = jlimit (minH, maxH, height);
width = height * aspectRatio;
}
}
}
rectToCheck->right = rectToCheck->left + roundToInt (width);
rectToCheck->bottom = rectToCheck->top + roundToInt (height);
*rectToCheck = convertToHostBounds (*rectToCheck);
}
}
return kResultTrue;
}
jassertfalse;
return kResultFalse;
}
tresult PLUGIN_API setContentScaleFactor (Steinberg::IPlugViewContentScaleSupport::ScaleFactor factor) override
{
#if ! JUCE_MAC
if (! approximatelyEqual ((float) factor, editorScaleFactor))
{
#if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
// Cubase 10 only sends integer scale factors, so correct this for fractional scales
if (getHostType().type == PluginHostType::SteinbergCubase10)
{
auto hostWindowScale = (Steinberg::IPlugViewContentScaleSupport::ScaleFactor) getScaleFactorForWindow ((HWND) systemWindow);
if (hostWindowScale > 0.0 && ! approximatelyEqual (factor, hostWindowScale))
factor = hostWindowScale;
}
#endif
editorScaleFactor = (float) factor;
if (owner != nullptr)
owner->lastScaleFactorReceived = editorScaleFactor;
if (component != nullptr)
{
if (auto* editor = component->pluginEditor.get())
{
editor->setScaleFactor (editorScaleFactor);
component->resizeHostWindow();
component->setTopLeftPosition (0, 0);
component->repaint();
}
}
}
return kResultTrue;
#else
ignoreUnused (factor);
return kResultFalse;
#endif
}
private:
void timerCallback() override
{
stopTimer();
ViewRect viewRect;
getSize (&viewRect);
onSize (&viewRect);
}
static ViewRect convertToHostBounds (ViewRect pluginRect)
{
auto desktopScale = Desktop::getInstance().getGlobalScaleFactor();
if (approximatelyEqual (desktopScale, 1.0f))
return pluginRect;
return { roundToInt ((float) pluginRect.left * desktopScale),
roundToInt ((float) pluginRect.top * desktopScale),
roundToInt ((float) pluginRect.right * desktopScale),
roundToInt ((float) pluginRect.bottom * desktopScale) };
}
static ViewRect convertFromHostBounds (ViewRect hostRect)
{
auto desktopScale = Desktop::getInstance().getGlobalScaleFactor();
if (approximatelyEqual (desktopScale, 1.0f))
return hostRect;
return { roundToInt ((float) hostRect.left / desktopScale),
roundToInt ((float) hostRect.top / desktopScale),
roundToInt ((float) hostRect.right / desktopScale),
roundToInt ((float) hostRect.bottom / desktopScale) };
}
//==============================================================================
struct ContentWrapperComponent : public Component
#if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
, public Timer
#endif
{
ContentWrapperComponent (JuceVST3Editor& editor) : owner (editor)
{
setOpaque (true);
setBroughtToFrontOnMouseClick (true);
ignoreUnused (fakeMouseGenerator);
}
~ContentWrapperComponent() override
{
if (pluginEditor != nullptr)
{
PopupMenu::dismissAllActiveMenus();
pluginEditor->processor.editorBeingDeleted (pluginEditor.get());
}
}
void createEditor (AudioProcessor& plugin)
{
pluginEditor.reset (plugin.createEditorIfNeeded());
if (pluginEditor != nullptr)
{
addAndMakeVisible (pluginEditor.get());
pluginEditor->setTopLeftPosition (0, 0);
lastBounds = getSizeToContainChild();
{
const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
setBounds (lastBounds);
}
resizeHostWindow();
}
else
{
// if hasEditor() returns true then createEditorIfNeeded has to return a valid editor
jassertfalse;
}
}
void paint (Graphics& g) override
{
g.fillAll (Colours::black);
}
juce::Rectangle<int> getSizeToContainChild()
{
if (pluginEditor != nullptr)
return getLocalArea (pluginEditor.get(), pluginEditor->getLocalBounds());
return {};
}
void childBoundsChanged (Component*) override
{
if (resizingChild)
return;
auto b = getSizeToContainChild();
if (lastBounds != b)
{
lastBounds = b;
const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
resizeHostWindow();
}
}
void resized() override
{
if (pluginEditor != nullptr)
{
if (! resizingParent)
{
auto newBounds = getLocalBounds();
#if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
if (! lastBounds.isEmpty() && isWithin (newBounds.toDouble().getAspectRatio(), lastBounds.toDouble().getAspectRatio(), 0.1))
return;
#endif
lastBounds = newBounds;
const ScopedValueSetter<bool> resizingChildSetter (resizingChild, true);
if (auto* constrainer = pluginEditor->getConstrainer())
{
auto aspectRatio = constrainer->getFixedAspectRatio();
if (aspectRatio != 0)
{
auto width = (double) lastBounds.getWidth();
auto height = (double) lastBounds.getHeight();
if (width / height > aspectRatio)
setBounds ({ 0, 0, roundToInt (height * aspectRatio), lastBounds.getHeight() });
else
setBounds ({ 0, 0, lastBounds.getWidth(), roundToInt (width / aspectRatio) });
}
}
pluginEditor->setTopLeftPosition (0, 0);
pluginEditor->setBounds (pluginEditor->getLocalArea (this, getLocalBounds()));
}
}
}
void parentSizeChanged() override
{
if (pluginEditor != nullptr)
{
resizeHostWindow();
pluginEditor->repaint();
}
}
void resizeHostWindow()
{
if (pluginEditor != nullptr)
{
auto b = getSizeToContainChild();
auto w = b.getWidth();
auto h = b.getHeight();
auto host = getHostType();
#if JUCE_WINDOWS
setSize (w, h);
#endif
if (owner.plugFrame != nullptr)
{
auto newSize = convertToHostBounds ({ 0, 0, b.getWidth(), b.getHeight() });
{
const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
owner.plugFrame->resizeView (&owner, &newSize);
}
#if JUCE_MAC
if (host.isWavelab() || host.isReaper())
#else
if (host.isWavelab() || host.isAbletonLive() || host.isBitwigStudio())
#endif
setBounds (0, 0, w, h);
}
}
}
#if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
void checkHostWindowScaleFactor()
{
auto hostWindowScale = (float) getScaleFactorForWindow ((HWND) owner.systemWindow);
if (hostWindowScale > 0.0 && ! approximatelyEqual (hostWindowScale, owner.editorScaleFactor))
owner.setContentScaleFactor (hostWindowScale);
}
void timerCallback() override
{
checkHostWindowScaleFactor();
}
#endif
std::unique_ptr<AudioProcessorEditor> pluginEditor;
private:
JuceVST3Editor& owner;
FakeMouseMoveGenerator fakeMouseGenerator;
Rectangle<int> lastBounds;
bool resizingChild = false, resizingParent = false;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentWrapperComponent)
};
void createContentWrapperComponentIfNeeded()
{
if (component == nullptr)
{
component.reset (new ContentWrapperComponent (*this));
component->createEditor (pluginInstance);
}
}
//==============================================================================
ScopedJuceInitialiser_GUI libraryInitialiser;
ComSmartPtr<JuceVST3EditController> owner;
AudioProcessor& pluginInstance;
std::unique_ptr<ContentWrapperComponent> component;
friend struct ContentWrapperComponent;
#if JUCE_MAC
void* macHostWindow = nullptr;
bool isNSView = false;
// On macOS Cubase 10 resizes the host window after calling onSize() resulting in the peer
// bounds being a step behind the plug-in. Calling updateBounds() asynchronously seems to fix things...
struct Cubase10WindowResizeWorkaround : public AsyncUpdater
{
Cubase10WindowResizeWorkaround (JuceVST3Editor& o) : owner (o) {}
void handleAsyncUpdate() override
{
if (owner.component != nullptr)
if (auto* peer = owner.component->getPeer())
peer->updateBounds();
}
JuceVST3Editor& owner;
};
std::unique_ptr<Cubase10WindowResizeWorkaround> cubase10Workaround;
#else
float editorScaleFactor = 1.0f;
#if JUCE_WINDOWS
WindowsHooks hooks;
#elif JUCE_LINUX
std::unordered_map<int, std::function<void (int)>> fdCallbackMap;
::Display* display = XWindowSystem::getInstance()->getDisplay();
Steinberg::Linux::IRunLoop* getHostRunLoop()
{
Steinberg::Linux::IRunLoop* runLoop = nullptr;
if (plugFrame != nullptr)
plugFrame->queryInterface (Steinberg::Linux::IRunLoop::iid, (void**) &runLoop);
return runLoop;
}
#endif
#endif
//==============================================================================
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Editor)
};
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3EditController)
};
namespace
{
template <typename FloatType> struct AudioBusPointerHelper {};
template <> struct AudioBusPointerHelper<float> { static float** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers32; } };
template <> struct AudioBusPointerHelper<double> { static double** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers64; } };
template <typename FloatType> struct ChooseBufferHelper {};
template <> struct ChooseBufferHelper<float> { static AudioBuffer<float>& impl (AudioBuffer<float>& f, AudioBuffer<double>& ) noexcept { return f; } };
template <> struct ChooseBufferHelper<double> { static AudioBuffer<double>& impl (AudioBuffer<float>& , AudioBuffer<double>& d) noexcept { return d; } };
}
//==============================================================================
class JuceVST3Component : public Vst::IComponent,
public Vst::IAudioProcessor,
public Vst::IUnitInfo,
public Vst::IConnectionPoint,
public AudioPlayHead
{
public:
JuceVST3Component (Vst::IHostApplication* h)
: pluginInstance (createPluginFilterOfType (AudioProcessor::wrapperType_VST3)),
host (h)
{
inParameterChangedCallback = false;
#ifdef JucePlugin_PreferredChannelConfigurations
short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
const int numConfigs = sizeof (configs) / sizeof (short[2]);
ignoreUnused (numConfigs);
jassert (numConfigs > 0 && (configs[0][0] > 0 || configs[0][1] > 0));
pluginInstance->setPlayConfigDetails (configs[0][0], configs[0][1], 44100.0, 1024);
#endif
// VST-3 requires your default layout to be non-discrete!
// For example, your default layout must be mono, stereo, quadrophonic
// and not AudioChannelSet::discreteChannels (2) etc.
jassert (checkBusFormatsAreNotDiscrete());
comPluginInstance = new JuceAudioProcessor (pluginInstance);
zerostruct (processContext);
processSetup.maxSamplesPerBlock = 1024;
processSetup.processMode = Vst::kRealtime;
processSetup.sampleRate = 44100.0;
processSetup.symbolicSampleSize = Vst::kSample32;
pluginInstance->setPlayHead (this);
}
~JuceVST3Component() override
{
if (juceVST3EditController != nullptr)
juceVST3EditController->vst3IsPlaying = false;
if (pluginInstance != nullptr)
if (pluginInstance->getPlayHead() == this)
pluginInstance->setPlayHead (nullptr);
}
//==============================================================================
AudioProcessor& getPluginInstance() const noexcept { return *pluginInstance; }
//==============================================================================
static const FUID iid;
JUCE_DECLARE_VST3_COM_REF_METHODS
tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
{
TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginBase)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3Component)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IComponent)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IAudioProcessor)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IUnitInfo)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IComponent)
if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
{
comPluginInstance->addRef();
*obj = comPluginInstance;
return kResultOk;
}
*obj = nullptr;
return kNoInterface;
}
//==============================================================================
tresult PLUGIN_API initialize (FUnknown* hostContext) override
{
if (host != hostContext)
host.loadFrom (hostContext);
processContext.sampleRate = processSetup.sampleRate;
preparePlugin (processSetup.sampleRate, (int) processSetup.maxSamplesPerBlock);
return kResultTrue;
}
tresult PLUGIN_API terminate() override
{
getPluginInstance().releaseResources();
return kResultTrue;
}
//==============================================================================
tresult PLUGIN_API connect (IConnectionPoint* other) override
{
if (other != nullptr && juceVST3EditController == nullptr)
juceVST3EditController.loadFrom (other);
return kResultTrue;
}
tresult PLUGIN_API disconnect (IConnectionPoint*) override
{
if (juceVST3EditController != nullptr)
juceVST3EditController->vst3IsPlaying = false;
juceVST3EditController = nullptr;
return kResultTrue;
}
tresult PLUGIN_API notify (Vst::IMessage* message) override
{
if (message != nullptr && juceVST3EditController == nullptr)
{
Steinberg::int64 value = 0;
if (message->getAttributes()->getInt ("JuceVST3EditController", value) == kResultTrue)
{
juceVST3EditController = (JuceVST3EditController*) (pointer_sized_int) value;
if (juceVST3EditController != nullptr)
juceVST3EditController->setAudioProcessor (comPluginInstance);
else
jassertfalse;
}
}
return kResultTrue;
}
tresult PLUGIN_API getControllerClassId (TUID classID) override
{
memcpy (classID, JuceVST3EditController::iid, sizeof (TUID));
return kResultTrue;
}
//==============================================================================
tresult PLUGIN_API setActive (TBool state) override
{
if (! state)
{
getPluginInstance().releaseResources();
deallocateChannelListAndBuffers (channelListFloat, emptyBufferFloat);
deallocateChannelListAndBuffers (channelListDouble, emptyBufferDouble);
}
else
{
auto sampleRate = getPluginInstance().getSampleRate();
auto bufferSize = getPluginInstance().getBlockSize();
sampleRate = processSetup.sampleRate > 0.0
? processSetup.sampleRate
: sampleRate;
bufferSize = processSetup.maxSamplesPerBlock > 0
? (int) processSetup.maxSamplesPerBlock
: bufferSize;
allocateChannelListAndBuffers (channelListFloat, emptyBufferFloat);
allocateChannelListAndBuffers (channelListDouble, emptyBufferDouble);
preparePlugin (sampleRate, bufferSize);
}
return kResultOk;
}
tresult PLUGIN_API setIoMode (Vst::IoMode) override { return kNotImplemented; }
tresult PLUGIN_API getRoutingInfo (Vst::RoutingInfo&, Vst::RoutingInfo&) override { return kNotImplemented; }
//==============================================================================
bool isBypassed()
{
if (auto* bypassParam = comPluginInstance->getBypassParameter())
return (bypassParam->getValue() != 0.0f);
return false;
}
void setBypassed (bool shouldBeBypassed)
{
if (auto* bypassParam = comPluginInstance->getBypassParameter())
{
auto floatValue = (shouldBeBypassed ? 1.0f : 0.0f);
bypassParam->setValue (floatValue);
inParameterChangedCallback = true;
bypassParam->sendValueChangedMessageToListeners (floatValue);
}
}
//==============================================================================
void writeJucePrivateStateInformation (MemoryOutputStream& out)
{
if (pluginInstance->getBypassParameter() == nullptr)
{
ValueTree privateData (kJucePrivateDataIdentifier);
// for now we only store the bypass value
privateData.setProperty ("Bypass", var (isBypassed()), nullptr);
privateData.writeToStream (out);
}
}
void setJucePrivateStateInformation (const void* data, int sizeInBytes)
{
if (pluginInstance->getBypassParameter() == nullptr)
{
if (comPluginInstance->getBypassParameter() != nullptr)
{
auto privateData = ValueTree::readFromData (data, static_cast<size_t> (sizeInBytes));
setBypassed (static_cast<bool> (privateData.getProperty ("Bypass", var (false))));
}
}
}
void getStateInformation (MemoryBlock& destData)
{
pluginInstance->getStateInformation (destData);
// With bypass support, JUCE now needs to store private state data.
// Put this at the end of the plug-in state and add a few null characters
// so that plug-ins built with older versions of JUCE will hopefully ignore
// this data. Additionally, we need to add some sort of magic identifier
// at the very end of the private data so that JUCE has some sort of
// way to figure out if the data was stored with a newer JUCE version.
MemoryOutputStream extraData;
extraData.writeInt64 (0);
writeJucePrivateStateInformation (extraData);
auto privateDataSize = (int64) (extraData.getDataSize() - sizeof (int64));
extraData.writeInt64 (privateDataSize);
extraData << kJucePrivateDataIdentifier;
// write magic string
destData.append (extraData.getData(), extraData.getDataSize());
}
void setStateInformation (const void* data, int sizeAsInt)
{
auto size = (uint64) sizeAsInt;
// Check if this data was written with a newer JUCE version
// and if it has the JUCE private data magic code at the end
auto jucePrivDataIdentifierSize = std::strlen (kJucePrivateDataIdentifier);
if ((size_t) size >= jucePrivDataIdentifierSize + sizeof (int64))
{
auto buffer = static_cast<const char*> (data);
String magic (CharPointer_UTF8 (buffer + size - jucePrivDataIdentifierSize),
CharPointer_UTF8 (buffer + size));
if (magic == kJucePrivateDataIdentifier)
{
// found a JUCE private data section
uint64 privateDataSize;
std::memcpy (&privateDataSize,
buffer + ((size_t) size - jucePrivDataIdentifierSize - sizeof (uint64)),
sizeof (uint64));
privateDataSize = ByteOrder::swapIfBigEndian (privateDataSize);
size -= privateDataSize + jucePrivDataIdentifierSize + sizeof (uint64);
if (privateDataSize > 0)
setJucePrivateStateInformation (buffer + size, static_cast<int> (privateDataSize));
size -= sizeof (uint64);
}
}
if (size > 0)
pluginInstance->setStateInformation (data, static_cast<int> (size));
}
//==============================================================================
#if JUCE_VST3_CAN_REPLACE_VST2
bool loadVST2VstWBlock (const char* data, int size)
{
jassert (ByteOrder::bigEndianInt ("VstW") == htonl ((uint32) readUnaligned<int32> (data)));
jassert (1 == htonl ((uint32) readUnaligned<int32> (data + 8))); // version should be 1 according to Steinberg's docs
auto headerLen = (int) htonl ((uint32) readUnaligned<int32> (data + 4)) + 8;
return loadVST2CcnKBlock (data + headerLen, size - headerLen);
}
bool loadVST2CcnKBlock (const char* data, int size)
{
auto* bank = reinterpret_cast<const Vst2::fxBank*> (data);
jassert (ByteOrder::bigEndianInt ("CcnK") == htonl ((uint32) bank->chunkMagic));
jassert (ByteOrder::bigEndianInt ("FBCh") == htonl ((uint32) bank->fxMagic));
jassert (htonl ((uint32) bank->version) == 1 || htonl ((uint32) bank->version) == 2);
jassert (JucePlugin_VSTUniqueID == htonl ((uint32) bank->fxID));
setStateInformation (bank->content.data.chunk,
jmin ((int) (size - (bank->content.data.chunk - data)),
(int) htonl ((uint32) bank->content.data.size)));
return true;
}
bool loadVST3PresetFile (const char* data, int size)
{
if (size < 48)
return false;
// At offset 4 there's a little-endian version number which seems to typically be 1
// At offset 8 there's 32 bytes the SDK calls "ASCII-encoded class id"
auto chunkListOffset = (int) ByteOrder::littleEndianInt (data + 40);
jassert (memcmp (data + chunkListOffset, "List", 4) == 0);
auto entryCount = (int) ByteOrder::littleEndianInt (data + chunkListOffset + 4);
jassert (entryCount > 0);
for (int i = 0; i < entryCount; ++i)
{
auto entryOffset = chunkListOffset + 8 + 20 * i;
if (entryOffset + 20 > size)
return false;
if (memcmp (data + entryOffset, "Comp", 4) == 0)
{
// "Comp" entries seem to contain the data.
auto chunkOffset = ByteOrder::littleEndianInt64 (data + entryOffset + 4);
auto chunkSize = ByteOrder::littleEndianInt64 (data + entryOffset + 12);
if (static_cast<uint64> (chunkOffset + chunkSize) > static_cast<uint64> (size))
{
jassertfalse;
return false;
}
loadVST2VstWBlock (data + chunkOffset, (int) chunkSize);
}
}
return true;
}
bool loadVST2CompatibleState (const char* data, int size)
{
if (size < 4)
return false;
auto header = htonl ((uint32) readUnaligned<int32> (data));
if (header == ByteOrder::bigEndianInt ("VstW"))
return loadVST2VstWBlock (data, size);
if (header == ByteOrder::bigEndianInt ("CcnK"))
return loadVST2CcnKBlock (data, size);
if (memcmp (data, "VST3", 4) == 0)
{
// In Cubase 5, when loading VST3 .vstpreset files,
// we get the whole content of the files to load.
// In Cubase 7 we get just the contents within and
// we go directly to the loadVST2VstW codepath instead.
return loadVST3PresetFile (data, size);
}
return false;
}
#endif
void loadStateData (const void* data, int size)
{
#if JUCE_VST3_CAN_REPLACE_VST2
if (loadVST2CompatibleState ((const char*) data, size))
return;
#endif
setStateInformation (data, size);
}
bool readFromMemoryStream (IBStream* state)
{
FUnknownPtr<ISizeableStream> s (state);
Steinberg::int64 size = 0;
if (s != nullptr
&& s->getStreamSize (size) == kResultOk
&& size > 0
&& size < 1024 * 1024 * 100) // (some hosts seem to return junk for the size)
{
MemoryBlock block (static_cast<size_t> (size));
// turns out that Cubase 9 might give you the incorrect stream size :-(
Steinberg::int32 bytesRead = 1;
int len;
for (len = 0; bytesRead > 0 && len < static_cast<int> (block.getSize()); len += bytesRead)
if (state->read (block.getData(), static_cast<int32> (block.getSize()), &bytesRead) != kResultOk)
break;
if (len == 0)
return false;
block.setSize (static_cast<size_t> (len));
// Adobe Audition CS6 hack to avoid trying to use corrupted streams:
if (getHostType().isAdobeAudition())
if (block.getSize() >= 5 && memcmp (block.getData(), "VC2!E", 5) == 0)
return false;
loadStateData (block.getData(), (int) block.getSize());
return true;
}
return false;
}
bool readFromUnknownStream (IBStream* state)
{
MemoryOutputStream allData;
{
const size_t bytesPerBlock = 4096;
HeapBlock<char> buffer (bytesPerBlock);
for (;;)
{
Steinberg::int32 bytesRead = 0;
auto status = state->read (buffer, (Steinberg::int32) bytesPerBlock, &bytesRead);
if (bytesRead <= 0 || (status != kResultTrue && ! getHostType().isWavelab()))
break;
allData.write (buffer, static_cast<size_t> (bytesRead));
}
}
const size_t dataSize = allData.getDataSize();
if (dataSize <= 0 || dataSize >= 0x7fffffff)
return false;
loadStateData (allData.getData(), (int) dataSize);
return true;
}
tresult PLUGIN_API setState (IBStream* state) override
{
if (state == nullptr)
return kInvalidArgument;
FUnknownPtr<IBStream> stateRefHolder (state); // just in case the caller hasn't properly ref-counted the stream object
if (state->seek (0, IBStream::kIBSeekSet, nullptr) == kResultTrue)
{
if (! getHostType().isFruityLoops() && readFromMemoryStream (state))
return kResultTrue;
if (readFromUnknownStream (state))
return kResultTrue;
}
return kResultFalse;
}
#if JUCE_VST3_CAN_REPLACE_VST2
static tresult writeVST2Header (IBStream* state, bool bypassed)
{
auto writeVST2IntToState = [state] (uint32 n)
{
auto t = (int32) htonl (n);
return state->write (&t, 4);
};
auto status = writeVST2IntToState (ByteOrder::bigEndianInt ("VstW"));
if (status == kResultOk) status = writeVST2IntToState (8); // header size
if (status == kResultOk) status = writeVST2IntToState (1); // version
if (status == kResultOk) status = writeVST2IntToState (bypassed ? 1 : 0); // bypass
return status;
}
#endif
tresult PLUGIN_API getState (IBStream* state) override
{
if (state == nullptr)
return kInvalidArgument;
MemoryBlock mem;
getStateInformation (mem);
#if JUCE_VST3_CAN_REPLACE_VST2
tresult status = writeVST2Header (state, isBypassed());
if (status != kResultOk)
return status;
const int bankBlockSize = 160;
Vst2::fxBank bank;
zerostruct (bank);
bank.chunkMagic = (int32) htonl (ByteOrder::bigEndianInt ("CcnK"));
bank.byteSize = (int32) htonl (bankBlockSize - 8 + (unsigned int) mem.getSize());
bank.fxMagic = (int32) htonl (ByteOrder::bigEndianInt ("FBCh"));
bank.version = (int32) htonl (2);
bank.fxID = (int32) htonl (JucePlugin_VSTUniqueID);
bank.fxVersion = (int32) htonl (JucePlugin_VersionCode);
bank.content.data.size = (int32) htonl ((unsigned int) mem.getSize());
status = state->write (&bank, bankBlockSize);
if (status != kResultOk)
return status;
#endif
return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
}
//==============================================================================
Steinberg::int32 PLUGIN_API getUnitCount() override { return comPluginInstance->getUnitCount(); }
tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override { return comPluginInstance->getUnitInfo (unitIndex, info); }
Steinberg::int32 PLUGIN_API getProgramListCount() override { return comPluginInstance->getProgramListCount(); }
tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override { return comPluginInstance->getProgramListInfo (listIndex, info); }
tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override { return comPluginInstance->getProgramName (listId, programIndex, name); }
tresult PLUGIN_API getProgramInfo (Vst::ProgramListID listId, Steinberg::int32 programIndex,
Vst::CString attributeId, Vst::String128 attributeValue) override { return comPluginInstance->getProgramInfo (listId, programIndex, attributeId, attributeValue); }
tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID listId, Steinberg::int32 programIndex) override { return comPluginInstance->hasProgramPitchNames (listId, programIndex); }
tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID listId, Steinberg::int32 programIndex,
Steinberg::int16 midiPitch, Vst::String128 name) override { return comPluginInstance->getProgramPitchName (listId, programIndex, midiPitch, name); }
tresult PLUGIN_API selectUnit (Vst::UnitID unitId) override { return comPluginInstance->selectUnit (unitId); }
tresult PLUGIN_API setUnitProgramData (Steinberg::int32 listOrUnitId, Steinberg::int32 programIndex,
Steinberg::IBStream* data) override { return comPluginInstance->setUnitProgramData (listOrUnitId, programIndex, data); }
Vst::UnitID PLUGIN_API getSelectedUnit() override { return comPluginInstance->getSelectedUnit(); }
tresult PLUGIN_API getUnitByBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 busIndex,
Steinberg::int32 channel, Vst::UnitID& unitId) override { return comPluginInstance->getUnitByBus (type, dir, busIndex, channel, unitId); }
//==============================================================================
bool getCurrentPosition (CurrentPositionInfo& info) override
{
info.timeInSamples = jmax ((juce::int64) 0, processContext.projectTimeSamples);
info.timeInSeconds = static_cast<double> (info.timeInSamples) / processContext.sampleRate;
info.bpm = jmax (1.0, processContext.tempo);
info.timeSigNumerator = jmax (1, (int) processContext.timeSigNumerator);
info.timeSigDenominator = jmax (1, (int) processContext.timeSigDenominator);
info.ppqPositionOfLastBarStart = processContext.barPositionMusic;
info.ppqPosition = processContext.projectTimeMusic;
info.ppqLoopStart = processContext.cycleStartMusic;
info.ppqLoopEnd = processContext.cycleEndMusic;
info.isRecording = (processContext.state & Vst::ProcessContext::kRecording) != 0;
info.isPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
info.isLooping = (processContext.state & Vst::ProcessContext::kCycleActive) != 0;
info.editOriginTime = 0.0;
info.frameRate = AudioPlayHead::fpsUnknown;
if ((processContext.state & Vst::ProcessContext::kSmpteValid) != 0)
{
switch (processContext.frameRate.framesPerSecond)
{
case 24:
{
if ((processContext.frameRate.flags & Vst::FrameRate::kPullDownRate) != 0)
info.frameRate = AudioPlayHead::fps23976;
else
info.frameRate = AudioPlayHead::fps24;
}
break;
case 25: info.frameRate = AudioPlayHead::fps25; break;
case 29: info.frameRate = AudioPlayHead::fps30drop; break;
case 30:
{
if ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
info.frameRate = AudioPlayHead::fps30drop;
else
info.frameRate = AudioPlayHead::fps30;
}
break;
default: break;
}
}
return true;
}
//==============================================================================
int getNumAudioBuses (bool isInput) const
{
int busCount = pluginInstance->getBusCount (isInput);
#ifdef JucePlugin_PreferredChannelConfigurations
short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
const int numConfigs = sizeof (configs) / sizeof (short[2]);
bool hasOnlyZeroChannels = true;
for (int i = 0; i < numConfigs && hasOnlyZeroChannels == true; ++i)
if (configs[i][isInput ? 0 : 1] != 0)
hasOnlyZeroChannels = false;
busCount = jmin (busCount, hasOnlyZeroChannels ? 0 : 1);
#endif
return busCount;
}
//==============================================================================
Steinberg::int32 PLUGIN_API getBusCount (Vst::MediaType type, Vst::BusDirection dir) override
{
if (type == Vst::kAudio)
return getNumAudioBuses (dir == Vst::kInput);
if (type == Vst::kEvent)
{
#if JucePlugin_WantsMidiInput
if (dir == Vst::kInput)
return 1;
#endif
#if JucePlugin_ProducesMidiOutput
if (dir == Vst::kOutput)
return 1;
#endif
}
return 0;
}
tresult PLUGIN_API getBusInfo (Vst::MediaType type, Vst::BusDirection dir,
Steinberg::int32 index, Vst::BusInfo& info) override
{
if (type == Vst::kAudio)
{
if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
return kResultFalse;
if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
{
info.mediaType = Vst::kAudio;
info.direction = dir;
info.channelCount = bus->getLastEnabledLayout().size();
toString128 (info.name, bus->getName());
#if JucePlugin_IsSynth
info.busType = (dir == Vst::kInput && index > 0 ? Vst::kAux : Vst::kMain);
#else
info.busType = (index == 0 ? Vst::kMain : Vst::kAux);
#endif
info.flags = (bus->isEnabledByDefault()) ? Vst::BusInfo::kDefaultActive : 0;
return kResultTrue;
}
}
if (type == Vst::kEvent)
{
info.flags = Vst::BusInfo::kDefaultActive;
#if JucePlugin_WantsMidiInput
if (dir == Vst::kInput && index == 0)
{
info.mediaType = Vst::kEvent;
info.direction = dir;
#ifdef JucePlugin_VSTNumMidiInputs
info.channelCount = JucePlugin_VSTNumMidiInputs;
#else
info.channelCount = 16;
#endif
toString128 (info.name, TRANS("MIDI Input"));
info.busType = Vst::kMain;
return kResultTrue;
}
#endif
#if JucePlugin_ProducesMidiOutput
if (dir == Vst::kOutput && index == 0)
{
info.mediaType = Vst::kEvent;
info.direction = dir;
#ifdef JucePlugin_VSTNumMidiOutputs
info.channelCount = JucePlugin_VSTNumMidiOutputs;
#else
info.channelCount = 16;
#endif
toString128 (info.name, TRANS("MIDI Output"));
info.busType = Vst::kMain;
return kResultTrue;
}
#endif
}
zerostruct (info);
return kResultFalse;
}
tresult PLUGIN_API activateBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 index, TBool state) override
{
if (type == Vst::kEvent)
{
#if JucePlugin_WantsMidiInput
if (index == 0 && dir == Vst::kInput)
{
isMidiInputBusEnabled = (state != 0);
return kResultTrue;
}
#endif
#if JucePlugin_ProducesMidiOutput
if (index == 0 && dir == Vst::kOutput)
{
isMidiOutputBusEnabled = (state != 0);
return kResultTrue;
}
#endif
return kResultFalse;
}
if (type == Vst::kAudio)
{
if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
return kResultFalse;
if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
{
#ifdef JucePlugin_PreferredChannelConfigurations
auto newLayout = pluginInstance->getBusesLayout();
auto targetLayout = (state != 0 ? bus->getLastEnabledLayout() : AudioChannelSet::disabled());
(dir == Vst::kInput ? newLayout.inputBuses : newLayout.outputBuses).getReference (index) = targetLayout;
short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
auto compLayout = pluginInstance->getNextBestLayoutInLayoutList (newLayout, configs);
if ((dir == Vst::kInput ? compLayout.inputBuses : compLayout.outputBuses).getReference (index) != targetLayout)
return kResultFalse;
#endif
return bus->enable (state != 0) ? kResultTrue : kResultFalse;
}
}
return kResultFalse;
}
bool checkBusFormatsAreNotDiscrete()
{
auto numInputBuses = pluginInstance->getBusCount (true);
auto numOutputBuses = pluginInstance->getBusCount (false);
for (int i = 0; i < numInputBuses; ++i)
{
auto layout = pluginInstance->getChannelLayoutOfBus (true, i);
if (layout.isDiscreteLayout() && ! layout.isDisabled())
return false;
}
for (int i = 0; i < numOutputBuses; ++i)
{
auto layout = pluginInstance->getChannelLayoutOfBus (false, i);
if (layout.isDiscreteLayout() && ! layout.isDisabled())
return false;
}
return true;
}
tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
{
auto numInputBuses = pluginInstance->getBusCount (true);
auto numOutputBuses = pluginInstance->getBusCount (false);
if (numIns > numInputBuses || numOuts > numOutputBuses)
return false;
auto requested = pluginInstance->getBusesLayout();
for (int i = 0; i < numIns; ++i)
requested.getChannelSet (true, i) = getChannelSetForSpeakerArrangement (inputs[i]);
for (int i = 0; i < numOuts; ++i)
requested.getChannelSet (false, i) = getChannelSetForSpeakerArrangement (outputs[i]);
#ifdef JucePlugin_PreferredChannelConfigurations
short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
if (! AudioProcessor::containsLayout (requested, configs))
return kResultFalse;
#endif
return pluginInstance->setBusesLayoutWithoutEnabling (requested) ? kResultTrue : kResultFalse;
}
tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
{
if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
{
arr = getVst3SpeakerArrangement (bus->getLastEnabledLayout());
return kResultTrue;
}
return kResultFalse;
}
//==============================================================================
tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
{
return (symbolicSampleSize == Vst::kSample32
|| (getPluginInstance().supportsDoublePrecisionProcessing()
&& symbolicSampleSize == Vst::kSample64)) ? kResultTrue : kResultFalse;
}
Steinberg::uint32 PLUGIN_API getLatencySamples() override
{
return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
}
tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
{
ScopedInSetupProcessingSetter inSetupProcessingSetter (juceVST3EditController);
if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
return kResultFalse;
processSetup = newSetup;
processContext.sampleRate = processSetup.sampleRate;
getPluginInstance().setProcessingPrecision (newSetup.symbolicSampleSize == Vst::kSample64
? AudioProcessor::doublePrecision
: AudioProcessor::singlePrecision);
getPluginInstance().setNonRealtime (newSetup.processMode == Vst::kOffline);
preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
return kResultTrue;
}
tresult PLUGIN_API setProcessing (TBool state) override
{
if (! state)
getPluginInstance().reset();
return kResultTrue;
}
Steinberg::uint32 PLUGIN_API getTailSamples() override
{
auto tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
if (tailLengthSeconds <= 0.0 || processSetup.sampleRate <= 0.0)
return Vst::kNoTail;
if (tailLengthSeconds == std::numeric_limits<double>::infinity())
return Vst::kInfiniteTail;
return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
}
//==============================================================================
void processParameterChanges (Vst::IParameterChanges& paramChanges)
{
jassert (pluginInstance != nullptr);
auto numParamsChanged = paramChanges.getParameterCount();
for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
{
if (auto* paramQueue = paramChanges.getParameterData (i))
{
auto numPoints = paramQueue->getPointCount();
Steinberg::int32 offsetSamples = 0;
double value = 0.0;
if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
{
auto vstParamID = paramQueue->getParameterId();
if (vstParamID == JuceAudioProcessor::paramPreset)
{
auto numPrograms = pluginInstance->getNumPrograms();
auto programValue = roundToInt (value * (jmax (0, numPrograms - 1)));
if (numPrograms > 1 && isPositiveAndBelow (programValue, numPrograms)
&& programValue != pluginInstance->getCurrentProgram())
pluginInstance->setCurrentProgram (programValue);
}
#if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
else if (juceVST3EditController != nullptr && juceVST3EditController->isMidiControllerParamID (vstParamID))
addParameterChangeToMidiBuffer (offsetSamples, vstParamID, value);
#endif
else
{
auto floatValue = static_cast<float> (value);
if (auto* param = comPluginInstance->getParamForVSTParamID (vstParamID))
{
param->setValue (floatValue);
inParameterChangedCallback = true;
param->sendValueChangedMessageToListeners (floatValue);
}
}
}
}
}
}
void addParameterChangeToMidiBuffer (const Steinberg::int32 offsetSamples, const Vst::ParamID id, const double value)
{
// If the parameter is mapped to a MIDI CC message then insert it into the midiBuffer.
int channel, ctrlNumber;
if (juceVST3EditController->getMidiControllerForParameter (id, channel, ctrlNumber))
{
if (ctrlNumber == Vst::kAfterTouch)
midiBuffer.addEvent (MidiMessage::channelPressureChange (channel,
jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
else if (ctrlNumber == Vst::kPitchBend)
midiBuffer.addEvent (MidiMessage::pitchWheel (channel,
jlimit (0, 0x3fff, (int) (value * 0x4000))), offsetSamples);
else
midiBuffer.addEvent (MidiMessage::controllerEvent (channel,
jlimit (0, 127, ctrlNumber),
jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
}
}
tresult PLUGIN_API process (Vst::ProcessData& data) override
{
if (pluginInstance == nullptr)
return kResultFalse;
if ((processSetup.symbolicSampleSize == Vst::kSample64) != pluginInstance->isUsingDoublePrecision())
return kResultFalse;
if (data.processContext != nullptr)
{
processContext = *data.processContext;
if (juceVST3EditController != nullptr)
juceVST3EditController->vst3IsPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
}
else
{
zerostruct (processContext);
if (juceVST3EditController != nullptr)
juceVST3EditController->vst3IsPlaying = false;
}
midiBuffer.clear();
if (data.inputParameterChanges != nullptr)
processParameterChanges (*data.inputParameterChanges);
#if JucePlugin_WantsMidiInput
if (isMidiInputBusEnabled && data.inputEvents != nullptr)
MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
#endif
if (getHostType().isWavelab())
{
const int numInputChans = (data.inputs != nullptr && data.inputs[0].channelBuffers32 != nullptr) ? (int) data.inputs[0].numChannels : 0;
const int numOutputChans = (data.outputs != nullptr && data.outputs[0].channelBuffers32 != nullptr) ? (int) data.outputs[0].numChannels : 0;
if ((pluginInstance->getTotalNumInputChannels() + pluginInstance->getTotalNumOutputChannels()) > 0
&& (numInputChans + numOutputChans) == 0)
return kResultFalse;
}
if (processSetup.symbolicSampleSize == Vst::kSample32) processAudio<float> (data, channelListFloat);
else if (processSetup.symbolicSampleSize == Vst::kSample64) processAudio<double> (data, channelListDouble);
else jassertfalse;
#if JucePlugin_ProducesMidiOutput
if (isMidiOutputBusEnabled && data.outputEvents != nullptr)
MidiEventList::pluginToHostEventList (*data.outputEvents, midiBuffer);
#endif
return kResultTrue;
}
private:
//==============================================================================
struct ScopedInSetupProcessingSetter
{
ScopedInSetupProcessingSetter (JuceVST3EditController* c)
: controller (c)
{
if (controller != nullptr)
controller->inSetupProcessing = true;
}
~ScopedInSetupProcessingSetter()
{
if (controller != nullptr)
controller->inSetupProcessing = false;
}
private:
JuceVST3EditController* controller = nullptr;
};
//==============================================================================
template <typename FloatType>
void processAudio (Vst::ProcessData& data, Array<FloatType*>& channelList)
{
int totalInputChans = 0, totalOutputChans = 0;
bool tmpBufferNeedsClearing = false;
auto plugInInputChannels = pluginInstance->getTotalNumInputChannels();
auto plugInOutputChannels = pluginInstance->getTotalNumOutputChannels();
// Wavelab workaround: wave-lab lies on the number of inputs/outputs so re-count here
const auto countValidChannels = [] (Vst::AudioBusBuffers* buffers, int32 num)
{
return int (std::distance (buffers, std::find_if (buffers, buffers + num, [] (Vst::AudioBusBuffers& buf)
{
return getPointerForAudioBus<FloatType> (buf) == nullptr && buf.numChannels > 0;
})));
};
const auto vstInputs = countValidChannels (data.inputs, data.numInputs);
const auto vstOutputs = countValidChannels (data.outputs, data.numOutputs);
{
auto n = jmax (vstOutputs, getNumAudioBuses (false));
for (int bus = 0; bus < n && totalOutputChans < plugInOutputChannels; ++bus)
{
if (auto* busObject = pluginInstance->getBus (false, bus))
if (! busObject->isEnabled())
continue;
if (bus < vstOutputs)
{
if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.outputs[bus]))
{
auto numChans = jmin ((int) data.outputs[bus].numChannels, plugInOutputChannels - totalOutputChans);
for (int i = 0; i < numChans; ++i)
{
if (auto dst = busChannels[i])
{
if (totalOutputChans >= plugInInputChannels)
FloatVectorOperations::clear (dst, (int) data.numSamples);
channelList.set (totalOutputChans++, busChannels[i]);
}
}
}
}
else
{
const int numChans = jmin (pluginInstance->getChannelCountOfBus (false, bus), plugInOutputChannels - totalOutputChans);
for (int i = 0; i < numChans; ++i)
{
if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalOutputChans, data.numSamples))\
{
tmpBufferNeedsClearing = true;
channelList.set (totalOutputChans++, tmpBuffer);
}
else
return;
}
}
}
}
{
auto n = jmax (vstInputs, getNumAudioBuses (true));
for (int bus = 0; bus < n && totalInputChans < plugInInputChannels; ++bus)
{
if (auto* busObject = pluginInstance->getBus (true, bus))
if (! busObject->isEnabled())
continue;
if (bus < vstInputs)
{
if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.inputs[bus]))
{
const int numChans = jmin ((int) data.inputs[bus].numChannels, plugInInputChannels - totalInputChans);
for (int i = 0; i < numChans; ++i)
{
if (busChannels[i] != nullptr)
{
if (totalInputChans >= totalOutputChans)
channelList.set (totalInputChans, busChannels[i]);
else
{
auto* dst = channelList.getReference (totalInputChans);
auto* src = busChannels[i];
if (dst != src)
FloatVectorOperations::copy (dst, src, (int) data.numSamples);
}
}
++totalInputChans;
}
}
}
else
{
auto numChans = jmin (pluginInstance->getChannelCountOfBus (true, bus), plugInInputChannels - totalInputChans);
for (int i = 0; i < numChans; ++i)
{
if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalInputChans, data.numSamples))
{
tmpBufferNeedsClearing = true;
channelList.set (totalInputChans++, tmpBuffer);
}
else
return;
}
}
}
}
if (tmpBufferNeedsClearing)
ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble).clear();
AudioBuffer<FloatType> buffer;
if (int totalChans = jmax (totalOutputChans, totalInputChans))
buffer.setDataToReferTo (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
{
const ScopedLock sl (pluginInstance->getCallbackLock());
pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
#if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
const int numMidiEventsComingIn = midiBuffer.getNumEvents();
#endif
if (pluginInstance->isSuspended())
{
buffer.clear();
}
else
{
if (totalInputChans == pluginInstance->getTotalNumInputChannels()
&& totalOutputChans == pluginInstance->getTotalNumOutputChannels())
{
if (isBypassed())
pluginInstance->processBlockBypassed (buffer, midiBuffer);
else
pluginInstance->processBlock (buffer, midiBuffer);
}
}
#if JUCE_DEBUG && (! JucePlugin_ProducesMidiOutput)
/* This assertion is caused when you've added some events to the
midiMessages array in your processBlock() method, which usually means
that you're trying to send them somewhere. But in this case they're
getting thrown away.
If your plugin does want to send MIDI messages, you'll need to set
the JucePlugin_ProducesMidiOutput macro to 1 in your
JucePluginCharacteristics.h file.
If you don't want to produce any MIDI output, then you should clear the
midiMessages array at the end of your processBlock() method, to
indicate that you don't want any of the events to be passed through
to the output.
*/
jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
#endif
}
}
//==============================================================================
template <typename FloatType>
void allocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
{
channelList.clearQuick();
channelList.insertMultiple (0, nullptr, 128);
auto& p = getPluginInstance();
buffer.setSize (jmax (p.getTotalNumInputChannels(), p.getTotalNumOutputChannels()), p.getBlockSize() * 4);
buffer.clear();
}
template <typename FloatType>
void deallocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
{
channelList.clearQuick();
channelList.resize (0);
buffer.setSize (0, 0);
}
template <typename FloatType>
static FloatType** getPointerForAudioBus (Vst::AudioBusBuffers& data) noexcept
{
return AudioBusPointerHelper<FloatType>::impl (data);
}
template <typename FloatType>
FloatType* getTmpBufferForChannel (int channel, int numSamples) noexcept
{
auto& buffer = ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble);
// we can't do anything if the host requests to render many more samples than the
// block size, we need to bail out
if (numSamples > buffer.getNumSamples() || channel >= buffer.getNumChannels())
return nullptr;
return buffer.getWritePointer (channel);
}
void preparePlugin (double sampleRate, int bufferSize)
{
auto& p = getPluginInstance();
p.setRateAndBufferSizeDetails (sampleRate, bufferSize);
p.prepareToPlay (sampleRate, bufferSize);
midiBuffer.ensureSize (2048);
midiBuffer.clear();
}
//==============================================================================
ScopedJuceInitialiser_GUI libraryInitialiser;
std::atomic<int> refCount { 1 };
AudioProcessor* pluginInstance;
ComSmartPtr<Vst::IHostApplication> host;
ComSmartPtr<JuceAudioProcessor> comPluginInstance;
ComSmartPtr<JuceVST3EditController> juceVST3EditController;
/**
Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
this object needs to be copied on every call to process() to be up-to-date...
*/
Vst::ProcessContext processContext;
Vst::ProcessSetup processSetup;
MidiBuffer midiBuffer;
Array<float*> channelListFloat;
Array<double*> channelListDouble;
AudioBuffer<float> emptyBufferFloat;
AudioBuffer<double> emptyBufferDouble;
#if JucePlugin_WantsMidiInput
std::atomic<bool> isMidiInputBusEnabled { true };
#endif
#if JucePlugin_ProducesMidiOutput
std::atomic<bool> isMidiOutputBusEnabled { true };
#endif
static const char* kJucePrivateDataIdentifier;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
};
const char* JuceVST3Component::kJucePrivateDataIdentifier = "JUCEPrivateData";
//==============================================================================
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4310)
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wall")
DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
DEF_CLASS_IID (JuceAudioProcessor)
#if JUCE_VST3_CAN_REPLACE_VST2
FUID getFUIDForVST2ID (bool forControllerUID)
{
TUID uuid;
extern JUCE_API void getUUIDForVST2ID (bool, uint8[16]);
getUUIDForVST2ID (forControllerUID, (uint8*) uuid);
return FUID (uuid);
}
const Steinberg::FUID JuceVST3Component ::iid (getFUIDForVST2ID (false));
const Steinberg::FUID JuceVST3EditController::iid (getFUIDForVST2ID (true));
#else
DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
DEF_CLASS_IID (JuceVST3EditController)
DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
DEF_CLASS_IID (JuceVST3Component)
#endif
JUCE_END_IGNORE_WARNINGS_MSVC
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
//==============================================================================
bool initModule();
bool initModule()
{
#if JUCE_MAC
initialiseMacVST();
#endif
return true;
}
bool shutdownModule();
bool shutdownModule()
{
return true;
}
#undef JUCE_EXPORTED_FUNCTION
#if JUCE_WINDOWS
#define JUCE_EXPORTED_FUNCTION
#else
#define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility("default")))
#endif
#if JUCE_WINDOWS
extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
#elif JUCE_LINUX
void* moduleHandle = nullptr;
int moduleEntryCounter = 0;
JUCE_EXPORTED_FUNCTION bool ModuleEntry (void* sharedLibraryHandle);
JUCE_EXPORTED_FUNCTION bool ModuleEntry (void* sharedLibraryHandle)
{
if (++moduleEntryCounter == 1)
{
moduleHandle = sharedLibraryHandle;
return initModule();
}
return true;
}
JUCE_EXPORTED_FUNCTION bool ModuleExit();
JUCE_EXPORTED_FUNCTION bool ModuleExit()
{
if (--moduleEntryCounter == 0)
{
moduleHandle = nullptr;
return shutdownModule();
}
return true;
}
#elif JUCE_MAC
CFBundleRef globalBundleInstance = nullptr;
juce::uint32 numBundleRefs = 0;
juce::Array<CFBundleRef> bundleRefs;
enum { MaxPathLength = 2048 };
char modulePath[MaxPathLength] = { 0 };
void* moduleHandle = nullptr;
JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref);
JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
{
if (ref != nullptr)
{
++numBundleRefs;
CFRetain (ref);
bundleRefs.add (ref);
if (moduleHandle == nullptr)
{
globalBundleInstance = ref;
moduleHandle = ref;
CFURLRef tempURL = CFBundleCopyBundleURL (ref);
CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*) modulePath, MaxPathLength);
CFRelease (tempURL);
}
}
return initModule();
}
JUCE_EXPORTED_FUNCTION bool bundleExit();
JUCE_EXPORTED_FUNCTION bool bundleExit()
{
if (shutdownModule())
{
if (--numBundleRefs == 0)
{
for (int i = 0; i < bundleRefs.size(); ++i)
CFRelease (bundleRefs.getUnchecked (i));
bundleRefs.clear();
}
return true;
}
return false;
}
#endif
//==============================================================================
/** This typedef represents VST3's createInstance() function signature */
using CreateFunction = FUnknown* (*)(Vst::IHostApplication*);
static FUnknown* createComponentInstance (Vst::IHostApplication* host)
{
return static_cast<Vst::IAudioProcessor*> (new JuceVST3Component (host));
}
static FUnknown* createControllerInstance (Vst::IHostApplication* host)
{
return static_cast<Vst::IEditController*> (new JuceVST3EditController (host));
}
//==============================================================================
struct JucePluginFactory;
static JucePluginFactory* globalFactory = nullptr;
//==============================================================================
struct JucePluginFactory : public IPluginFactory3
{
JucePluginFactory()
: factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
{
}
virtual ~JucePluginFactory()
{
if (globalFactory == this)
globalFactory = nullptr;
}
//==============================================================================
bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
{
if (createFunction == nullptr)
{
jassertfalse;
return false;
}
auto entry = std::make_unique<ClassEntry> (info, createFunction);
entry->infoW.fromAscii (info);
classes.push_back (std::move (entry));
return true;
}
//==============================================================================
JUCE_DECLARE_VST3_COM_REF_METHODS
tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
{
TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory3)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory2)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, FUnknown)
jassertfalse; // Something new?
*obj = nullptr;
return kNotImplemented;
}
//==============================================================================
Steinberg::int32 PLUGIN_API countClasses() override
{
return (Steinberg::int32) classes.size();
}
tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
{
if (info == nullptr)
return kInvalidArgument;
memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
return kResultOk;
}
tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
{
return getPClassInfo<PClassInfo> (index, info);
}
tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
{
return getPClassInfo<PClassInfo2> (index, info);
}
tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
{
if (info != nullptr)
{
if (auto& entry = classes[(size_t) index])
{
memcpy (info, &entry->infoW, sizeof (PClassInfoW));
return kResultOk;
}
}
return kInvalidArgument;
}
tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
{
ScopedJuceInitialiser_GUI libraryInitialiser;
*obj = nullptr;
TUID tuid;
memcpy (tuid, sourceIid, sizeof (TUID));
#if VST_VERSION >= 0x030608
auto sourceFuid = FUID::fromTUID (tuid);
#else
FUID sourceFuid;
sourceFuid = tuid;
#endif
if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
{
jassertfalse; // The host you're running in has severe implementation issues!
return kInvalidArgument;
}
TUID iidToQuery;
sourceFuid.toTUID (iidToQuery);
for (auto& entry : classes)
{
if (doUIDsMatch (entry->infoW.cid, cid))
{
if (auto* instance = entry->createFunction (host))
{
const FReleaser releaser (instance);
if (instance->queryInterface (iidToQuery, obj) == kResultOk)
return kResultOk;
}
break;
}
}
return kNoInterface;
}
tresult PLUGIN_API setHostContext (FUnknown* context) override
{
host.loadFrom (context);
if (host != nullptr)
{
Vst::String128 name;
host->getName (name);
return kResultTrue;
}
return kNotImplemented;
}
private:
//==============================================================================
std::atomic<int> refCount { 1 };
const PFactoryInfo factoryInfo;
ComSmartPtr<Vst::IHostApplication> host;
//==============================================================================
struct ClassEntry
{
ClassEntry() noexcept {}
ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
: info2 (info), createFunction (fn) {}
PClassInfo2 info2;
PClassInfoW infoW;
CreateFunction createFunction = {};
bool isUnicode = false;
private:
JUCE_DECLARE_NON_COPYABLE (ClassEntry)
};
std::vector<std::unique_ptr<ClassEntry>> classes;
//==============================================================================
template<class PClassInfoType>
tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
{
if (info != nullptr)
{
zerostruct (*info);
if (auto& entry = classes[(size_t) index])
{
if (entry->isUnicode)
return kResultFalse;
memcpy (info, (PClassInfoType*) &entry->info2, sizeof (PClassInfoType));
return kResultOk;
}
}
jassertfalse;
return kInvalidArgument;
}
//==============================================================================
// no leak detector here to prevent it firing on shutdown when running in hosts that
// don't release the factory object correctly...
JUCE_DECLARE_NON_COPYABLE (JucePluginFactory)
};
} // juce namespace
//==============================================================================
#ifndef JucePlugin_Vst3ComponentFlags
#if JucePlugin_IsSynth
#define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
#else
#define JucePlugin_Vst3ComponentFlags 0
#endif
#endif
#ifndef JucePlugin_Vst3Category
#if JucePlugin_IsSynth
#define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
#else
#define JucePlugin_Vst3Category Vst::PlugType::kFx
#endif
#endif
using namespace juce;
//==============================================================================
// The VST3 plugin entry point.
JUCE_EXPORTED_FUNCTION IPluginFactory* PLUGIN_API GetPluginFactory()
{
PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST3;
#if JUCE_MSVC || (JUCE_WINDOWS && JUCE_CLANG)
// Cunning trick to force this function to be exported. Life's too short to
// faff around creating .def files for this kind of thing.
#if JUCE_32BIT
#pragma comment(linker, "/EXPORT:GetPluginFactory=_GetPluginFactory@0")
#else
#pragma comment(linker, "/EXPORT:GetPluginFactory=GetPluginFactory")
#endif
#endif
if (globalFactory == nullptr)
{
globalFactory = new JucePluginFactory();
static const PClassInfo2 componentClass (JuceVST3Component::iid,
PClassInfo::kManyInstances,
kVstAudioEffectClass,
JucePlugin_Name,
JucePlugin_Vst3ComponentFlags,
JucePlugin_Vst3Category,
JucePlugin_Manufacturer,
JucePlugin_VersionString,
kVstVersionString);
globalFactory->registerClass (componentClass, createComponentInstance);
static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
PClassInfo::kManyInstances,
kVstComponentControllerClass,
JucePlugin_Name,
JucePlugin_Vst3ComponentFlags,
JucePlugin_Vst3Category,
JucePlugin_Manufacturer,
JucePlugin_VersionString,
kVstVersionString);
globalFactory->registerClass (controllerClass, createControllerInstance);
}
else
{
globalFactory->addRef();
}
return dynamic_cast<IPluginFactory*> (globalFactory);
}
//==============================================================================
#if JUCE_WINDOWS
extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID) { if (reason == DLL_PROCESS_ATTACH) Process::setCurrentModuleInstanceHandle (instance); return true; }
#endif
#endif //JucePlugin_Build_VST3
| gpl-3.0 |
Entropy-Soldier/ges-legacy-code | game/ges/client/VGUI/ge_updatechecker.cpp | 1 | 5492 | ///////////// Copyright © 2010 LodleNet. All rights reserved. /////////////
//
// Project : Client
// File : ge_updatechecker.cpp
// Description :
// [TODO: Write the purpose of ge_updatechecker.cpp.]
//
// Created On: 3/6/2010 4:44:17 PM
// Created By: Mark Chandler <mailto:mark@moddb.com>
////////////////////////////////////////////////////////////////////////////
#include "cbase.h"
#include "ge_updatechecker.h"
#include "ge_shareddefs.h"
#include "ge_utils.h"
#include <vgui/ISurface.h>
#include "vgui_controls/Controls.h"
#include <vgui_controls/PanelListPanel.h>
#include <vgui_controls/URLLabel.h>
#include <vgui/IVGui.h>
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
static GameUI<CGEUpdateChecker> g_GEUpdateChecker;
CGEUpdateChecker::CGEUpdateChecker( vgui::VPANEL parent ) : BaseClass( NULL, GetName() )
{
m_pWebRequest = NULL;
SetParent( parent );
SetScheme( vgui::scheme()->LoadSchemeFromFile("resource/SourceScheme.res", "SourceScheme") );
SetProportional( true );
LoadControlSettings("resource/GESUpdateTool.res");
InvalidateLayout();
MakePopup();
SetSizeable( false );
SetPaintBackgroundEnabled( true );
SetPaintBorderEnabled( true );
SetMouseInputEnabled(true);
SetKeyBoardInputEnabled(true);
// Add tick signal to allow for background movies to play
vgui::ivgui()->AddTickSignal( GetVPanel() );
}
CGEUpdateChecker::~CGEUpdateChecker()
{
if ( m_pWebRequest )
m_pWebRequest->Destroy();
}
void CGEUpdateChecker::ApplySchemeSettings( vgui::IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
SetBgColor( pScheme->GetColor("UpdateBGColor", Color(123,146,156,255)) );
vgui::PanelListPanel *pLinkList = dynamic_cast<vgui::PanelListPanel*>(FindChildByName("linklist"));
if ( pLinkList )
{
pLinkList->SetFirstColumnWidth(0);
pLinkList->SetVerticalBufferPixels( YRES(4) );
}
vgui::Panel *pPanel = FindChildByName("changelisturl");
pPanel->SetBorder( pScheme->GetBorder("RaisedBorder") );
}
void CGEUpdateChecker::PostInit()
{
m_pWebRequest = new CGEWebRequest( GES_VERSION_URL );
}
void CGEUpdateChecker::OnTick()
{
if ( m_pWebRequest && m_pWebRequest->IsFinished() )
{
if ( m_pWebRequest->HadError() )
{
Warning( "Failed update check: %s\n", m_pWebRequest->GetError() );
}
else
{
processUpdate( m_pWebRequest->GetResult() );
}
delete m_pWebRequest;
m_pWebRequest = NULL;
vgui::ivgui()->RemoveTickSignal( GetVPanel() );
}
}
void CGEUpdateChecker::processUpdate( const char* data )
{
KeyValues *kv = new KeyValues("update");
if ( !kv->LoadFromBuffer( "update", data ) )
{
Warning( "Failed update check: Corrupt KeyValues Data\n" );
return;
}
string_t ges_version_text;
int ges_major_version, ges_minor_version, ges_client_version, ges_server_version;
if ( !GEUTIL_GetVersion( ges_version_text, ges_major_version, ges_minor_version, ges_client_version, ges_server_version ) )
{
Warning( "Failed loading version.txt, your installation may be corrupt!\n" );
return;
}
CUtlVector<char*> version;
Q_SplitString( kv->GetString("version"), ".", version );
vgui::IScheme *pScheme = vgui::scheme()->GetIScheme( GetScheme() );
if (version.Count() < 3)
return; // Didn't get proper version info from web server, can't check for updates!
// Makes the comparison really simple and lets us avoid complex conditional expressions which have caused mistakes in the past.
// As long as we don't need to release GE:S version 6.1001.0 anytime soon this should work well enough.
// (2^31 - 1)/1000000 ~= 2000 so we've got a lot of major version releases before this becomes a problem.
int ourVersionValue = ges_major_version * 1000000 + ges_minor_version * 1000 + ges_client_version;
int newestVersionValue = atoi(version[0]) * 1000000 + atoi(version[1]) * 1000 + atoi(version[2]);
// We only need to update if our version number is less than the current version number.
if (ourVersionValue < newestVersionValue)
{
// We have differing version strings, notify the client
// Setup the version labels
vgui::Panel *pVersion = FindChildByName( "yourversion" );
if ( pVersion )
PostMessage( pVersion, new KeyValues( "SetText", "text", ges_version_text ) );
pVersion = FindChildByName( "currversion" );
if ( pVersion )
PostMessage( pVersion, new KeyValues( "SetText", "text", kv->GetString("version") ) );
vgui::URLLabel *pChangeList = dynamic_cast<vgui::URLLabel*>( FindChildByName( "changelisturl" ) );
if ( pChangeList )
pChangeList->SetURL( kv->GetString( "changelist", "" ) );
// Setup the list of links
vgui::PanelListPanel *pLinkList = dynamic_cast<vgui::PanelListPanel*>( FindChildByName( "linklist" ) );
vgui::URLLabel *pURL;
if ( pLinkList )
{
pLinkList->DeleteAllItems();
KeyValues *mirrors = kv->FindKey( "client_mirrors" );
if ( mirrors )
{
KeyValues *url = mirrors->GetFirstSubKey();
while( url )
{
pURL = new vgui::URLLabel( NULL, "", url->GetString(), url->GetString() );
pLinkList->AddItem( NULL, pURL );
url = url->GetNextKey();
}
}
}
// Show the update panel
SetVisible( true );
SetZPos( 5 );
RequestFocus();
MoveToFront();
// Make sure our background is correct
SetBgColor( pScheme->GetColor( "UpdateBGColor", Color(123,146,156,255) ) );
}
}
#ifdef _DEBUG
CON_COMMAND( ge_show_updatechecker, "Show the update checker" )
{
g_GEUpdateChecker.GetNativePanel()->SetVisible( true );
}
#endif | gpl-3.0 |
geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtbase/tests/auto/cmake/test_multiple_find_package/main.cpp | 1 | 1432 | /****************************************************************************
**
** Copyright (C) 2013 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Stephen Kelly <stephen.kelly@kdab.com>
** Contact: https://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/QString>
int main(int,char**)
{
return 0;
}
| gpl-3.0 |
babesyoung/c-learning | chapter9/magic_matrix.c | 1 | 1631 | /*
* name: magic_matrix.c
* purpose: printf magic_matrix
* author: babes young
*/
#include <stdio.h>
#define DIM 99
void create_magic_matrix(int, int [DIM][DIM]);
void print_magic_matrix(int, int [DIM][DIM]);
int main(void)
{
int dimension;
printf("this program creates a magic square of a specified size\n");
printf("an odd number between 1-99\n");
printf("enter size of magic square: ");
scanf("%d", &dimension);
int magic_matrix[DIM][DIM] = {{0}};
create_magic_matrix(dimension, magic_matrix);
print_magic_matrix(dimension, magic_matrix);
return 0;
}
void create_magic_matrix(int dimension, int magic_matrix[][DIM])
{
int arrow = 0, column = dimension / 2,
arrow_cache, column_cache,
number = 1;
magic_matrix[arrow][column] = number;
for (int i = 1; i < (dimension * dimension); i++) {
arrow_cache = arrow;
column_cache = column;
arrow -= 1;
column += 1;
if (arrow == -1) {
arrow = dimension - 1;
}
if (column == dimension) {
column = 0;
}
number++;
if (magic_matrix[arrow][column] == 0) {
magic_matrix[arrow][column] = number;
} else {
arrow = arrow_cache + 1;
column = column_cache;
magic_matrix[arrow][column] = number;
}
}
}
void print_magic_matrix(int dimension, int magic_matrix[][DIM])
{
for (int i = 0; i < dimension; i++) {
for (int j = 0; j < dimension; j++) {
printf("%5d", magic_matrix[i][j]);
}
printf("\n");
}
}
| gpl-3.0 |
jaredmoore/ROS-Gazebo-Examples | ros_gazebo_step_ws_w_timing/src/world_step/ros_get_world_time.cpp | 1 | 1377 | #include <math.h>
#include <boost/thread.hpp>
#include <boost/algorithm/string.hpp>
#include <gazebo/gazebo.hh>
#include <gazebo/common/Plugin.hh>
#include <gazebo/msgs/msgs.hh>
#include <gazebo/transport/transport.hh>
#include <ros/ros.h>
#include <ros/subscribe_options.h>
int main(int argc, char** argv)
{
gazebo::setupClient(argc,argv);
ros::init(argc, argv, "get_world_time_test");
// Gazebo WorldControl Topic
gazebo::transport::NodePtr node(new gazebo::transport::Node());
node->Init();
// Initialize the ROSNode
ros::NodeHandle* rosnode = new ros::NodeHandle();
gazebo::transport::PublisherPtr pub = node->Advertise<gazebo::msgs::WorldControl>("~/world_control");
// Waits for simulation time update.
ros::Time last_ros_time_;
bool wait = true;
while (wait)
{
last_ros_time_ = ros::Time::now();
std::cout << "\t\t\t Attempted getting sim time: " << last_ros_time_ << std::endl;
if (last_ros_time_.toSec() > 0)
//wait = false;
std::cout << "Current Simulation Time: " << last_ros_time_ << std::endl;
// Publish the step message for the simulation.
gazebo::msgs::WorldControl msg;
msg.set_step(1);
pub->Publish(msg);
// Wait for 1 second and allow ROS to complete as well.
gazebo::common::Time::MSleep(1000);
ros::spinOnce();
}
gazebo::shutdown();
return 0;
}
| gpl-3.0 |
IMP-Engine/Engine | external/tbb/src/test/test_yield.cpp | 1 | 2161 | /*
Copyright (c) 2005-2016 Intel 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.
*/
// Test that __TBB_Yield works.
// On Red Hat EL4 U1, it does not work, because sched_yield is broken.
#define HARNESS_DEFAULT_MIN_THREADS 4
#define HARNESS_DEFAULT_MAX_THREADS 8
#include "tbb/tbb_machine.h"
#include "tbb/tick_count.h"
#include "harness.h"
static volatile long CyclicCounter;
static volatile bool Quit;
double SingleThreadTime;
struct RoundRobin: NoAssign {
const int number_of_threads;
RoundRobin( long p ) : number_of_threads(p) {}
void operator()( long k ) const {
tbb::tick_count t0 = tbb::tick_count::now();
for( long i=0; i<10000; ++i ) {
// Wait for previous thread to notify us
for( int j=0; CyclicCounter!=k && !Quit; ++j ) {
__TBB_Yield();
if( j%100==0 ) {
tbb::tick_count t1 = tbb::tick_count::now();
if( (t1-t0).seconds()>=1.0*number_of_threads ) {
REPORT("Warning: __TBB_Yield failing to yield with %d threads (or system is heavily loaded)\n",number_of_threads);
Quit = true;
return;
}
}
}
// Notify next thread that it can run
CyclicCounter = (k+1)%number_of_threads;
}
}
};
int TestMain () {
for( int p=MinThread; p<=MaxThread; ++p ) {
REMARK("testing with %d threads\n", p );
CyclicCounter = 0;
Quit = false;
NativeParallelFor( long(p), RoundRobin(p) );
}
return Harness::Done;
}
| gpl-3.0 |
frichote/replop | CL_code/code/src/lapack/dnrm2.c | 1 | 2198 |
/* -- translated by f2c (version 19940927).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
#include "f2c.h"
doublereal dnrm2_(integer * n, doublereal * x, integer * incx)
{
/* System generated locals */
doublereal ret_val, d__1;
/* Builtin functions */
double sqrt(doublereal);
/* Local variables */
static doublereal norm, scale, absxi;
static integer ix;
static doublereal ssq;
/* DNRM2 returns the euclidean norm of a vector via the function
name, so that
DNRM2 := sqrt( x'*x )
-- This version written on 25-October-1982.
Modified on 14-October-1993 to inline the call to DLASSQ.
Sven Hammarling, Nag Ltd.
Parameter adjustments
Function Body */
#define X(I) x[(I)-1]
if (*n < 1 || *incx < 1) {
norm = 0.;
} else if (*n == 1) {
norm = abs(X(1));
} else {
scale = 0.;
ssq = 1.;
/* The following loop is equivalent to this call to the LAPACK
auxiliary routine:
CALL DLASSQ( N, X, INCX, SCALE, SSQ ) */
for (ix = 1;
*incx < 0 ? ix >= (*n - 1) ** incx + 1 : ix <=
(*n - 1) ** incx + 1; ix += *incx) {
if (X(ix) != 0.) {
absxi = (d__1 = X(ix), abs(d__1));
if (scale < absxi) {
/* Computing 2nd power */
d__1 = scale / absxi;
ssq = ssq * (d__1 * d__1) + 1.;
scale = absxi;
} else {
/* Computing 2nd power */
d__1 = absxi / scale;
ssq += d__1 * d__1;
}
}
/* L10: */
}
norm = scale * sqrt(ssq);
}
ret_val = norm;
return ret_val;
/* End of DNRM2. */
} /* dnrm2_ */
| gpl-3.0 |
foxblock/penjin | NumberUtility.cpp | 1 | 2395 | /*
Penjin is Copyright (c)2005, 2006, 2007, 2008, 2009, 2010 Kevin Winfield-Pantoja
This file is part of Penjin.
Penjin 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.
Penjin 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 Penjin. If not, see <http://www.gnu.org/licenses/>.
*/
#include "NumberUtility.h"
///----------------------
/// Analysis
///----------------------
#ifdef PENJIN_FIXED
Fixed NumberUtility::linearInterpolate(CRint x, CRint y, CRFixed step)
{
Fixed temp = x + step;
if(temp < y)
return temp;
return Fixed(y);
}
#else
float NumberUtility::linearInterpolate(CRint x, CRint y, CRfloat step)
{
float temp = x + step;
if(temp < y)
return temp;
return (float)y;
}
#endif
int NumberUtility::digitSum(CRuint value)
{
int result = 0;
int temp = value;
while (temp != 0)
{
result += temp % 10;
temp /= 10;
}
return result;
}
double NumberUtility::fact(CRuint value)
{
double result=1;
for (int I=value; I > 1; --I)
{
result *= I;
}
return result;
}
bool NumberUtility::isEven(CRint value){return (value%2 == 0);}
bool NumberUtility::isMultiple(CRint x,CRint y){return (x%y == 0);}
bool NumberUtility::isOdd(CRint value){return !(value%2 ==0);}
bool NumberUtility::isPowerOfTwo(CRint x){return ((x != 0) && !(x & (x - 1)));}
int NumberUtility::nextPowerOfTwo(CRint x)
{
double logbase2 = log(x) / log(2);
return (int)round(pow(2,ceil(logbase2)));
}
bool NumberUtility::isPrime(CRuint value)
{
for (int I = 2; I <= int(value/2); I++)
if (value % I == 0)
return false;
return true;
}
///----------------------
/// Angles
///----------------------
float NumberUtility::degToRad(CRfloat a)
{
return a * 0.017453292f;
}
float NumberUtility::radToDeg(CRfloat a)
{
return a * 57.29578f;
}
| gpl-3.0 |
ec1oud/uradmonitor_kit1 | code/lcd/5110.cpp | 1 | 12586 | /**
* File: 5110.cpp
* Version: 1.0
* Date: 2013
* License: GPL v3
* Description: unbuffered driver for Nokia 3110 / 5110 LCD
* Project: uRADMonitor KIT1, a hackable digital sensor monitoring tool with network interface
*
* Copyright 2007 by Tony Myatt
* Copyright 2013 by Radu Motisan, radu.motisan@gmail.com
* Copyright 2016 by Magnasci SRL, www.magnasci.com
*
* 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 3 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 <stdio.h>
#include <avr/pgmspace.h>
#include "5110.h"
// Alphabet lookup font
// we are actually using 6x8 pixels, but the last are for border
// this means in 84x48 we have 14x6 characters
// the list is ordonated by the ASCII codes
const uint8_t PROGMEM font5x7 [][CHAR_WIDTH - 1] = {
{ 0x00, 0x00, 0x00, 0x00, 0x00 }, // sp
{ 0x00, 0x00, 0x2f, 0x00, 0x00 }, // !
{ 0x00, 0x07, 0x00, 0x07, 0x00 }, // "
{ 0x14, 0x7f, 0x14, 0x7f, 0x14 }, // #
{ 0x24, 0x2a, 0x7f, 0x2a, 0x12 }, // $
{ 0x32, 0x34, 0x08, 0x16, 0x26 }, // %
{ 0x36, 0x49, 0x55, 0x22, 0x50 }, // &
{ 0x00, 0x05, 0x03, 0x00, 0x00 }, // '
{ 0x00, 0x1c, 0x22, 0x41, 0x00 }, // (
{ 0x00, 0x41, 0x22, 0x1c, 0x00 }, // )
{ 0x14, 0x08, 0x3E, 0x08, 0x14 }, // *
{ 0x08, 0x08, 0x3E, 0x08, 0x08 }, // +
{ 0x00, 0x00, 0x50, 0x30, 0x00 }, // ,
{ 0x10, 0x10, 0x10, 0x10, 0x10 }, // -
{ 0x00, 0x60, 0x60, 0x00, 0x00 }, // .
{ 0x20, 0x10, 0x08, 0x04, 0x02 }, // /
{ 0x3E, 0x51, 0x49, 0x45, 0x3E }, // 0
{ 0x00, 0x42, 0x7F, 0x40, 0x00 }, // 1
{ 0x42, 0x61, 0x51, 0x49, 0x46 }, // 2
{ 0x21, 0x41, 0x45, 0x4B, 0x31 }, // 3
{ 0x18, 0x14, 0x12, 0x7F, 0x10 }, // 4
{ 0x27, 0x45, 0x45, 0x45, 0x39 }, // 5
{ 0x3C, 0x4A, 0x49, 0x49, 0x30 }, // 6
{ 0x01, 0x71, 0x09, 0x05, 0x03 }, // 7
{ 0x36, 0x49, 0x49, 0x49, 0x36 }, // 8
{ 0x06, 0x49, 0x49, 0x29, 0x1E }, // 9
{ 0x00, 0x36, 0x36, 0x00, 0x00 }, // :
{ 0x00, 0x56, 0x36, 0x00, 0x00 }, // ;
{ 0x08, 0x14, 0x22, 0x41, 0x00 }, // <
{ 0x14, 0x14, 0x14, 0x14, 0x14 }, // =
{ 0x00, 0x41, 0x22, 0x14, 0x08 }, // >
{ 0x02, 0x01, 0x51, 0x09, 0x06 }, // ?
{ 0x32, 0x49, 0x59, 0x51, 0x3E }, // @
{ 0x7E, 0x11, 0x11, 0x11, 0x7E }, // A
{ 0x7F, 0x49, 0x49, 0x49, 0x36 }, // B
{ 0x3E, 0x41, 0x41, 0x41, 0x22 }, // C
{ 0x7F, 0x41, 0x41, 0x22, 0x1C }, // D
{ 0x7F, 0x49, 0x49, 0x49, 0x41 }, // E
{ 0x7F, 0x09, 0x09, 0x09, 0x01 }, // F
{ 0x3E, 0x41, 0x49, 0x49, 0x7A }, // G
{ 0x7F, 0x08, 0x08, 0x08, 0x7F }, // H
{ 0x00, 0x41, 0x7F, 0x41, 0x00 }, // I
{ 0x20, 0x40, 0x41, 0x3F, 0x01 }, // J
{ 0x7F, 0x08, 0x14, 0x22, 0x41 }, // K
{ 0x7F, 0x40, 0x40, 0x40, 0x40 }, // L
{ 0x7F, 0x02, 0x0C, 0x02, 0x7F }, // M
{ 0x7F, 0x04, 0x08, 0x10, 0x7F }, // N
{ 0x3E, 0x41, 0x41, 0x41, 0x3E }, // O
{ 0x7F, 0x09, 0x09, 0x09, 0x06 }, // P
{ 0x3E, 0x41, 0x51, 0x21, 0x5E }, // Q
{ 0x7F, 0x09, 0x19, 0x29, 0x46 }, // R
{ 0x46, 0x49, 0x49, 0x49, 0x31 }, // S
{ 0x01, 0x01, 0x7F, 0x01, 0x01 }, // T
{ 0x3F, 0x40, 0x40, 0x3F, 0x00 }, // U
{ 0x1F, 0x20, 0x40, 0x20, 0x1F }, // V
{ 0x3F, 0x40, 0x38, 0x40, 0x3F }, // W
{ 0x63, 0x14, 0x08, 0x14, 0x63 }, // X
{ 0x07, 0x08, 0x70, 0x08, 0x07 }, // Y
{ 0x61, 0x51, 0x49, 0x45, 0x43 }, // Z
{ 0x00, 0x7F, 0x41, 0x41, 0x00 }, // [
{ 0x55, 0x2A, 0x55, 0x2A, 0x55 }, // 55 /
{ 0x00, 0x41, 0x41, 0x7F, 0x00 }, // ]
{ 0x04, 0x02, 0x01, 0x02, 0x04 }, // ^
{ 0x40, 0x40, 0x40, 0x40, 0x40 }, // _
{ 0x00, 0x01, 0x02, 0x04, 0x00 }, // '
{ 0x20, 0x54, 0x54, 0x54, 0x78 }, // a
{ 0x7F, 0x48, 0x44, 0x44, 0x38 }, // b
{ 0x38, 0x44, 0x44, 0x44, 0x20 }, // c
{ 0x38, 0x44, 0x44, 0x48, 0x7F }, // d
{ 0x38, 0x54, 0x54, 0x54, 0x18 }, // e
{ 0x08, 0x7E, 0x09, 0x01, 0x02 }, // f
{ 0x0C, 0x52, 0x52, 0x52, 0x3E }, // g
{ 0x7F, 0x08, 0x04, 0x04, 0x78 }, // h
{ 0x00, 0x44, 0x7D, 0x40, 0x00 }, // i
{ 0x20, 0x40, 0x44, 0x3D, 0x00 }, // j
{ 0x7F, 0x10, 0x28, 0x44, 0x00 }, // k
{ 0x00, 0x41, 0x7F, 0x40, 0x00 }, // l
{ 0x7C, 0x04, 0x18, 0x04, 0x78 }, // m
{ 0x7C, 0x08, 0x04, 0x04, 0x78 }, // n
{ 0x38, 0x44, 0x44, 0x44, 0x38 }, // o
{ 0x7C, 0x14, 0x14, 0x14, 0x08 }, // p
{ 0x08, 0x14, 0x14, 0x18, 0x7C }, // q
{ 0x7C, 0x08, 0x04, 0x04, 0x08 }, // r
{ 0x48, 0x54, 0x54, 0x54, 0x20 }, // s
{ 0x04, 0x3F, 0x44, 0x40, 0x20 }, // t
{ 0x3C, 0x40, 0x40, 0x20, 0x7C }, // u
{ 0x1C, 0x20, 0x40, 0x20, 0x1C }, // v
{ 0x3C, 0x40, 0x30, 0x40, 0x3C }, // w
{ 0x44, 0x28, 0x10, 0x28, 0x44 }, // x
{ 0x0C, 0x50, 0x50, 0x50, 0x3C }, // y
{ 0x44, 0x64, 0x54, 0x4C, 0x44 }, // z 0x7A
{ 0x00, 0x7F, 0x3E, 0x1C, 0x08 }, // > Filled {
{ 0x08, 0x1C, 0x3E, 0x7F, 0x00 }, // < Filled |
{ 0x08, 0x7C, 0x7E, 0x7C, 0x08 }, // Arrow up }
{ 0x10, 0x3E, 0x7E, 0x3E, 0x10 }, // Arrow down ~
{ 0x3E, 0x3E, 0x3E, 0x3E, 0x3E }, // Stop 0x7F
{ 0x00, 0x7F, 0x3E, 0x1C, 0x08 }, // Play 0x80
/*{ 0x7F, 0x7F, 0x7F, 0x7F, 0x7F }, // bat 1 0x81
{ 0x77, 0x7B, 0x41, 0x7B, 0x77 }, // bat 2 0x82
{ 0x7F, 0x7F, 0x7F, 0x1C, 0x1C }, // bat 3 0x83*/
{ 0x7F, 0x41, 0x5D, 0x55, 0x55 }, // bat 1 0x81
{ 0x49, 0x49, 0x49, 0x5D, 0x49 }, // bat 1 0x82 //charging
{ 0x41, 0x41, 0x41, 0x7F, 0x1C }, // bat 1 0x83
{ 0x7F, 0x41, 0x5D, 0x5D, 0x5D }, // bat 2 0x84
{ 0x5D, 0x5D, 0x5D, 0x5D, 0x5D }, // bat 2 0x85 //full
{ 0x5D, 0x5D, 0x41, 0x7F, 0x1C }, // bat 2 0x86
{ 0x7F, 0x41, 0x5D, 0x5D, 0x5D }, // bat 3 0x87
{ 0x5D, 0x5D, 0x59, 0x51, 0x41 }, // bat 3 0x88 //half
{ 0x41, 0x41, 0x41, 0x7F, 0x1C }, // bat 3 0x89
{ 0x7F, 0x41, 0x5D, 0x59, 0x51 }, // bat 4 0x8A
{ 0x41, 0x41, 0x41, 0x41, 0x41 }, // bat 4 0x8B //empty
{ 0x41, 0x41, 0x41, 0x7F, 0x1C }, // bat 4 0x8C
{ 0x40, 0x3C, 0x10, 0x1C, 0x00 }, // micro 0x8D
{ 0x04, 0x26, 0x38, 0x26, 0x04 }, // radsign 0x8E
{ 0x67, 0x15, 0x60, 0x17, 0x63 }, // CPM sign 0x8F
{ 0x7C, 0x7C, 0x0C, 0x0C, 0x0C }, // sign 0x90
{ 0x0C, 0x0C, 0x0C, 0x7C, 0x7C }, // sign 0x91
{ 0x7F, 0x7F, 0x00, 0x00, 0x00 }, // sign 0x92
{ 0x00, 0x00, 0x00, 0x7F, 0x7F }, // sign 0x93
{ 0x0C, 0x0C, 0x0C, 0x0C, 0x0C }, // sign 0x94
{ 0x0F, 0x0F, 0x0C, 0x0C, 0x0C }, // sign 0x95
{ 0x0C, 0x0C, 0x0C, 0x0F, 0x0F }, // sign 0x96
{ 0x1C, 0x1C, 0x3E, 0x7F, 0x00 }, // speaker on 0x97
{ 0x1A, 0x14, 0x2E, 0x5F, 0x20 }, // speaker off 0x98
{ 0x07, 0x75, 0x5D, 0x57, 0x70 }, // lan on 0x99
{ 0x05, 0x72, 0x5D, 0x50, 0x70 }, // lan off 0x9A
{ 0x00, 0x07, 0x05, 0x07, 0x00 }, // degrees 0x9B
{ 0x1F, 0x05, 0x72, 0x28, 0x70 } // Pascals 0x9C
};
LCD_5110::LCD_5110(DigitalPin *rst, DigitalPin *ce, DigitalPin *dc, DigitalPin *data, DigitalPin *clk, DigitalPin *backlight) {
lcdCacheIdx = 0;
m_rst = rst;
m_ce = ce;
m_dc = dc;
m_data = data;
m_clk = clk;
m_backlight = backlight;
}
/* Performs IO & LCD controller initialization */
void LCD_5110::init() {
// Pull-up on reset pin
*m_rst = 1;
// Wait after VCC high for reset (max 30ms)
_delay_ms(15);
// Toggle display reset pin
*m_rst = 0;
_delay_ms(64);
*m_rst = 1;
// Disable LCD controller
*m_ce = 0;
send(LCD_EXTENDED_COMMANDS, LCD_CMD);
send(LCD_VOP, LCD_CMD);
send(LCD_TEMP, LCD_CMD);
send(LCD_BIAS_MODE, LCD_CMD);
send(LCD_HOR_ADDRESSING, LCD_CMD);
send(LCD_NORMAL_MODE, LCD_CMD);
// Clear lcd
clear();
// Set display contrast. Note: No change is visible at ambient temperature
int contrast = 0x40;
send(LCD_EXTENDED_COMMANDS, LCD_CMD); // LCD Extended Commands
send(0x80 | contrast, LCD_CMD); // Set LCD Vop(Contrast)
send(LCD_HOR_ADDRESSING, LCD_CMD); // LCD std cmds, hori addr mode
}
// Clears the display
void LCD_5110::clear(void) {
lcdCacheIdx = 0;
base_addr(lcdCacheIdx);
// Set the entire cache to zero and write 0s to lcd
int size = ((LCD_WIDTH * LCD_HEIGHT) / CHAR_HEIGHT);
for(int i=0;i<size;i++) send(0, LCD_DATA);
}
// Clears an area on a line
void LCD_5110::clear_area(uint8_t line, uint8_t startX, uint8_t endX) {
// Start and end positions of line
int start = line * LCD_WIDTH + startX;
int end = line * LCD_WIDTH + endX;
base_addr(start);
// Clear all data in range from cache
for(uint16_t i = start; i < end; i++) send(0, LCD_DATA);
}
// Clears an entire text block. (rows of 8 pixels on the lcd)
void LCD_5110::clear_line(uint8_t line) {
clear_area(line, 0, LCD_WIDTH);
}
// Sets cursor location to xy location corresponding to basic font size
void LCD_5110::goto_xy(uint8_t x, uint8_t y) {
lcdCacheIdx = x*CHAR_WIDTH + y * LCD_WIDTH;
}
// Sets cursor location to exact xy pixel location on the lcd
void LCD_5110::goto_xy_exact(uint8_t x, uint8_t y) {
lcdCacheIdx = x + y * LCD_WIDTH;
}
// Sends data to display controller : a line of 8 pixels, as defined by data
void LCD_5110::send(uint8_t byte, Type cd) {
// Enable display controller (active low)
*m_ce = 0;
// Either command or data
*m_dc = (cd == LCD_DATA);
for(uint8_t i=0;i<8;i++) {
// Set the DATA pin value:8 bits in a row
*m_data = (byte >> (7-i)) & 0x01;
// Toggle the clock after each data bit
*m_clk = 1;
*m_clk = 0;
}
// Disable display controller
*m_ce = 1;
}
// Displays a character at current cursor location or moves to new line if enter char is given
void LCD_5110::send(char chr) {
if (chr == '\n') {
// move to next line and first column
lcdCacheIdx = lcdCacheIdx + LCD_WIDTH - lcdCacheIdx % LCD_WIDTH; //next line and x=0
} else {
base_addr(lcdCacheIdx);
// 5 pixel wide characters and add space
for(uint8_t i=0; i < CHAR_WIDTH - 1; i++)
send(pgm_read_byte(&font5x7[chr-32][i]) << 1, LCD_DATA);
send(0, LCD_DATA); // right empty separator line of 8 vertical pixels
lcdCacheIdx += CHAR_WIDTH;
}
}
// Displays null terminated string at current cursor location and increment cursor location
void LCD_5110::send(char *str) {
while(*str) send(*str++);
}
void LCD_5110::send(const char *str) {
while(pgm_read_byte(str)) send(pgm_read_byte(str++));
}
// displays a formated string, similar to printf
void LCD_5110::send(char *buffer, uint16_t len, const char *szFormat, ...) {
va_list pArgs;
va_start(pArgs, szFormat);
vsnprintf_P(buffer, len, szFormat, pArgs);
va_end(pArgs);
send(buffer);
}
// Set the base address of the lcd
void LCD_5110::base_addr(uint16_t addr) {
send(LCD_SETXADDR |(addr % LCD_WIDTH), LCD_CMD);
send(LCD_SETYADDR |(addr / LCD_WIDTH), LCD_CMD);
}
void LCD_5110::col(char chr) {
base_addr(lcdCacheIdx);
send(chr, LCD_DATA);
lcdCacheIdx++;
}
// It goes back the cursor on LCD for a single step
void LCD_5110::pixelBack(void) {
lcdCacheIdx--;
}
// Prints on LCD a hex based picture, A hex picture can be produced from the "LCDAssistant.exe" windows based software.
void LCD_5110::printPictureOnLCD ( const uint8_t *data) {
uint16_t pixel_cols = LCD_WIDTH * (LCD_HEIGHT / CHAR_HEIGHT); //<6> means 6 lines on LCD.
goto_xy(0, 0);
for(int i=0;i<pixel_cols;i++) col(pgm_read_byte(data++));
}
// the most basic function, set a single pixel
void LCD_5110::drawPixel(uint8_t x, uint8_t y, int color) {
uint16_t pixel_addr = x + y/CHAR_HEIGHT * LCD_WIDTH;
send(LCD_SETXADDR |(pixel_addr % LCD_WIDTH), LCD_CMD);
send(LCD_SETYADDR |(pixel_addr / LCD_WIDTH), LCD_CMD);
if (color)
send(1<<(y % CHAR_HEIGHT), LCD_DATA); //"black pixel"
else
send(0, LCD_DATA); //"remove black pixel"
}
void LCD_5110::setBacklight(bool mode) {
*m_backlight = mode;
}
| gpl-3.0 |
yyang-even/algorithms | mathematics/arithmetics/factorial/count_divisors_of_factorial.cpp | 1 | 1127 | #include "common_header.h"
#include "mathematics/numbers/prime/largest_power_of_p_divides_factorial_n.h"
#include "mathematics/numbers/prime/primes_below_n.h"
namespace {
/**
* @reference Count Divisors of Factorial
* https://www.geeksforgeeks.org/count-divisors-of-factorial/
*
* Given a number n, count total number of divisors of n!.
*/
unsigned long long CountDivisorsOfFactorial(const unsigned n) {
if (n == 0) {
return 0;
}
auto primes_below_n_plus_1 = PrimesBelowN(n + 1);
unsigned long long count = 1;
for (const auto prime : primes_below_n_plus_1) {
//The 1 is for p^0
count *= (LargestPowerOfPDividesFactorialN(prime, n) + 1);
}
return count;
}
}//namespace
constexpr unsigned LOWER = 0;
THE_BENCHMARK(CountDivisorsOfFactorial, LOWER);
SIMPLE_TEST(CountDivisorsOfFactorial, TestSAMPLE1, 0, LOWER);
SIMPLE_TEST(CountDivisorsOfFactorial, TestSAMPLE2, 1, 1);
SIMPLE_TEST(CountDivisorsOfFactorial, TestSAMPLE3, 8, 4);
SIMPLE_TEST(CountDivisorsOfFactorial, TestSAMPLE4, 16, 5);
SIMPLE_TEST(CountDivisorsOfFactorial, TestSAMPLE5, 30, 6);
| gpl-3.0 |
lordsergioinspa/FreeNOS | server/filesystem/tmp/TmpFileSystem.cpp | 1 | 1199 | /*
* Copyright (C) 2009 Niek Linnenbank
*
* 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 3 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 <File.h>
#include <PseudoFile.h>
#include <Directory.h>
#include "TmpFileSystem.h"
TmpFileSystem::TmpFileSystem(const char *path)
: FileSystem(path)
{
setRoot(new Directory);
}
File * TmpFileSystem::createFile(FileType type, DeviceID deviceID)
{
// Create the appropriate file type
switch (type)
{
case RegularFile:
return new PseudoFile;
case DirectoryFile:
return new Directory;
default:
return ZERO;
}
}
| gpl-3.0 |
heuripedes/RetroArch | gfx/drivers/d3d9.c | 1 | 54290 | /* RetroArch - A frontend for libretro.
* Copyright (C) 2010-2014 - Hans-Kristian Arntzen
* Copyright (C) 2011-2017 - Daniel De Matteis
* Copyright (C) 2012-2014 - OV2
*
* RetroArch 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 Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* RetroArch 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 RetroArch.
* If not, see <http://www.gnu.org/licenses/>.
*/
#define CINTERFACE
#ifdef _XBOX
#include <xtl.h>
#include <xgraphics.h>
#endif
#include <formats/image.h>
#include <compat/strl.h>
#include <compat/posix_string.h>
#include <file/file_path.h>
#include <string/stdstring.h>
#include <retro_math.h>
#include <d3d9.h>
#ifdef HAVE_CONFIG_H
#include "../../config.h"
#endif
#include "../../defines/d3d_defines.h"
#include "../common/d3d_common.h"
#include "../common/d3d9_common.h"
#include "../video_coord_array.h"
#include "../../configuration.h"
#include "../../dynamic.h"
#include "../../ui/ui_companion_driver.h"
#include "../../frontend/frontend_driver.h"
#ifdef HAVE_THREADS
#include "../video_thread_wrapper.h"
#endif
#include "../common/win32_common.h"
#ifdef _XBOX
#define D3D9_PRESENTATIONINTERVAL D3DRS_PRESENTINTERVAL
#endif
#define FS_PRESENTINTERVAL(pp) ((pp)->PresentationInterval)
#ifdef HAVE_MENU
#include "../../menu/menu_driver.h"
#endif
#ifdef HAVE_GFX_WIDGETS
#include "../gfx_widgets.h"
#endif
#include "../font_driver.h"
#include "../../core.h"
#include "../../verbosity.h"
#include "../../retroarch.h"
#ifdef __WINRT__
#error "UWP does not support D3D9"
#endif
/* Temporary workaround for d3d9 not being able to poll flags during init */
static gfx_ctx_driver_t d3d9_fake_context;
static uint32_t d3d9_get_flags(void *data);
static bool d3d9_set_shader(void *data,
enum rarch_shader_type type, const char *path);
static LPDIRECT3D9 g_pD3D9;
static enum rarch_shader_type supported_shader_type = RARCH_SHADER_NONE;
void *dinput;
static bool d3d9_set_resize(d3d9_video_t *d3d,
unsigned new_width, unsigned new_height)
{
/* No changes? */
if ( (new_width == d3d->video_info.width)
&& (new_height == d3d->video_info.height))
return false;
RARCH_LOG("[D3D9]: Resize %ux%u.\n", new_width, new_height);
d3d->video_info.width = new_width;
d3d->video_info.height = new_height;
video_driver_set_size(new_width, new_height);
return true;
}
extern d3d9_renderchain_driver_t cg_d3d9_renderchain;
extern d3d9_renderchain_driver_t hlsl_d3d9_renderchain;
static bool renderchain_d3d_init_first(
enum gfx_ctx_api api,
const d3d9_renderchain_driver_t **renderchain_driver,
void **renderchain_handle)
{
switch (api)
{
case GFX_CTX_DIRECT3D9_API:
{
static const d3d9_renderchain_driver_t *renderchain_d3d_drivers[] =
{
#if defined(_WIN32) && defined(HAVE_CG)
&cg_d3d9_renderchain,
#endif
#if defined(_WIN32) && defined(HAVE_HLSL)
&hlsl_d3d9_renderchain,
#endif
NULL
};
unsigned i;
for (i = 0; renderchain_d3d_drivers[i]; i++)
{
void *data = renderchain_d3d_drivers[i]->chain_new();
if (!data)
continue;
*renderchain_driver = renderchain_d3d_drivers[i];
*renderchain_handle = data;
if (string_is_equal(renderchain_d3d_drivers[i]->ident, "cg_d3d9"))
supported_shader_type = RARCH_SHADER_CG;
else if (string_is_equal(renderchain_d3d_drivers[i]->ident, "hlsl_d3d9"))
supported_shader_type = RARCH_SHADER_HLSL;
return true;
}
}
break;
case GFX_CTX_NONE:
default:
break;
}
return false;
}
static void d3d9_log_info(const struct LinkInfo *info)
{
RARCH_LOG("[D3D9]: Render pass info:\n");
RARCH_LOG("\tTexture width: %u\n", info->tex_w);
RARCH_LOG("\tTexture height: %u\n", info->tex_h);
RARCH_LOG("\tScale type (X): ");
switch (info->pass->fbo.type_x)
{
case RARCH_SCALE_INPUT:
RARCH_LOG("Relative @ %fx\n", info->pass->fbo.scale_x);
break;
case RARCH_SCALE_VIEWPORT:
RARCH_LOG("Viewport @ %fx\n", info->pass->fbo.scale_x);
break;
case RARCH_SCALE_ABSOLUTE:
RARCH_LOG("Absolute @ %u px\n", info->pass->fbo.abs_x);
break;
}
RARCH_LOG("\tScale type (Y): ");
switch (info->pass->fbo.type_y)
{
case RARCH_SCALE_INPUT:
RARCH_LOG("Relative @ %fx\n", info->pass->fbo.scale_y);
break;
case RARCH_SCALE_VIEWPORT:
RARCH_LOG("Viewport @ %fx\n", info->pass->fbo.scale_y);
break;
case RARCH_SCALE_ABSOLUTE:
RARCH_LOG("Absolute @ %u px\n", info->pass->fbo.abs_y);
break;
}
RARCH_LOG("\tBilinear filter: %s\n",
info->pass->filter == RARCH_FILTER_LINEAR ? "true" : "false");
}
static bool d3d9_init_chain(d3d9_video_t *d3d,
unsigned input_scale,
bool rgb32)
{
unsigned i = 0;
struct LinkInfo link_info;
unsigned current_width, current_height, out_width, out_height;
/* Setup information for first pass. */
link_info.pass = NULL;
link_info.tex_w = input_scale * RARCH_SCALE_BASE;
link_info.tex_h = input_scale * RARCH_SCALE_BASE;
link_info.pass = &d3d->shader.pass[0];
if (!renderchain_d3d_init_first(GFX_CTX_DIRECT3D9_API,
&d3d->renderchain_driver,
&d3d->renderchain_data))
{
RARCH_ERR("[D3D9]: Renderchain could not be initialized.\n");
return false;
}
if (!d3d->renderchain_driver || !d3d->renderchain_data)
return false;
if (
!d3d->renderchain_driver->init(
d3d,
d3d->dev, &d3d->final_viewport, &link_info,
rgb32)
)
{
RARCH_ERR("[D3D9]: Failed to init render chain.\n");
return false;
}
RARCH_LOG("[D3D9]: Renderchain driver: %s\n", d3d->renderchain_driver->ident);
d3d9_log_info(&link_info);
#ifndef _XBOX
current_width = link_info.tex_w;
current_height = link_info.tex_h;
out_width = 0;
out_height = 0;
for (i = 1; i < d3d->shader.passes; i++)
{
d3d9_convert_geometry(
&link_info,
&out_width, &out_height,
current_width, current_height, &d3d->final_viewport);
link_info.pass = &d3d->shader.pass[i];
link_info.tex_w = next_pow2(out_width);
link_info.tex_h = next_pow2(out_height);
current_width = out_width;
current_height = out_height;
if (!d3d->renderchain_driver->add_pass(
d3d->renderchain_data, &link_info))
{
RARCH_ERR("[D3D9]: Failed to add pass.\n");
return false;
}
d3d9_log_info(&link_info);
}
#endif
if (d3d->renderchain_driver)
{
if (d3d->renderchain_driver->add_lut)
{
unsigned i;
settings_t *settings = config_get_ptr();
bool video_smooth = settings->bools.video_smooth;
for (i = 0; i < d3d->shader.luts; i++)
{
if (!d3d->renderchain_driver->add_lut(
d3d->renderchain_data,
d3d->shader.lut[i].id, d3d->shader.lut[i].path,
d3d->shader.lut[i].filter == RARCH_FILTER_UNSPEC
? video_smooth
: (d3d->shader.lut[i].filter == RARCH_FILTER_LINEAR)))
{
RARCH_ERR("[D3D9]: Failed to init LUTs.\n");
return false;
}
}
}
}
return true;
}
static bool d3d9_init_singlepass(d3d9_video_t *d3d)
{
struct video_shader_pass *pass = NULL;
if (!d3d)
return false;
memset(&d3d->shader, 0, sizeof(d3d->shader));
d3d->shader.passes = 1;
pass = (struct video_shader_pass*)
&d3d->shader.pass[0];
pass->fbo.valid = true;
pass->fbo.scale_y = 1.0;
pass->fbo.type_y = RARCH_SCALE_VIEWPORT;
pass->fbo.scale_x = pass->fbo.scale_y;
pass->fbo.type_x = pass->fbo.type_y;
if (!string_is_empty(d3d->shader_path))
strlcpy(pass->source.path, d3d->shader_path,
sizeof(pass->source.path));
return true;
}
static bool d3d9_init_multipass(d3d9_video_t *d3d, const char *shader_path)
{
unsigned i;
bool use_extra_pass = false;
struct video_shader_pass *pass = NULL;
config_file_t *conf = video_shader_read_preset(shader_path);
if (!conf)
{
RARCH_ERR("[D3D9]: Failed to load preset.\n");
return false;
}
memset(&d3d->shader, 0, sizeof(d3d->shader));
if (!video_shader_read_conf_preset(conf, &d3d->shader))
{
config_file_free(conf);
RARCH_ERR("[D3D9]: Failed to parse shader preset.\n");
return false;
}
config_file_free(conf);
RARCH_LOG("[D3D9]: Found %u shaders.\n", d3d->shader.passes);
for (i = 0; i < d3d->shader.passes; i++)
{
if (d3d->shader.pass[i].fbo.valid)
continue;
d3d->shader.pass[i].fbo.scale_y = 1.0f;
d3d->shader.pass[i].fbo.scale_x = 1.0f;
d3d->shader.pass[i].fbo.type_x = RARCH_SCALE_INPUT;
d3d->shader.pass[i].fbo.type_y = RARCH_SCALE_INPUT;
}
use_extra_pass = d3d->shader.passes < GFX_MAX_SHADERS &&
d3d->shader.pass[d3d->shader.passes - 1].fbo.valid;
if (use_extra_pass)
{
d3d->shader.passes++;
pass = (struct video_shader_pass*)
&d3d->shader.pass[d3d->shader.passes - 1];
pass->fbo.scale_x = 1.0f;
pass->fbo.scale_y = 1.0f;
pass->fbo.type_x = RARCH_SCALE_VIEWPORT;
pass->fbo.type_y = RARCH_SCALE_VIEWPORT;
pass->filter = RARCH_FILTER_UNSPEC;
}
else
{
pass = (struct video_shader_pass*)
&d3d->shader.pass[d3d->shader.passes - 1];
pass->fbo.scale_x = 1.0f;
pass->fbo.scale_y = 1.0f;
pass->fbo.type_x = RARCH_SCALE_VIEWPORT;
pass->fbo.type_y = RARCH_SCALE_VIEWPORT;
}
return true;
}
static bool d3d9_process_shader(d3d9_video_t *d3d)
{
const char *shader_path = d3d->shader_path;
if (d3d && !string_is_empty(shader_path))
return d3d9_init_multipass(d3d, shader_path);
return d3d9_init_singlepass(d3d);
}
static void d3d9_viewport_info(void *data, struct video_viewport *vp)
{
unsigned width, height;
d3d9_video_t *d3d = (d3d9_video_t*)data;
if (!vp)
return;
video_driver_get_size(&width, &height);
vp->x = d3d->final_viewport.X;
vp->y = d3d->final_viewport.Y;
vp->width = d3d->final_viewport.Width;
vp->height = d3d->final_viewport.Height;
vp->full_width = width;
vp->full_height = height;
}
void d3d9_set_mvp(void *data, const void *mat_data)
{
LPDIRECT3DDEVICE9 dev = (LPDIRECT3DDEVICE9)data;
d3d9_set_vertex_shader_constantf(dev, 0, (const float*)mat_data, 4);
}
#if defined(HAVE_MENU) || defined(HAVE_OVERLAY)
static void d3d9_overlay_render(d3d9_video_t *d3d,
unsigned width,
unsigned height,
overlay_t *overlay, bool force_linear)
{
D3DTEXTUREFILTERTYPE filter_type;
LPDIRECT3DVERTEXDECLARATION9 vertex_decl;
LPDIRECT3DDEVICE9 dev;
struct video_viewport vp;
void *verts;
unsigned i;
Vertex vert[4];
D3DVERTEXELEMENT9 vElems[4] = {
{0, offsetof(Vertex, x), D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT,
D3DDECLUSAGE_POSITION, 0},
{0, offsetof(Vertex, u), D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT,
D3DDECLUSAGE_TEXCOORD, 0},
{0, offsetof(Vertex, color), D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
D3DDECLUSAGE_COLOR, 0},
D3DDECL_END()
};
if (!d3d || !overlay || !overlay->tex)
return;
dev = d3d->dev;
if (!overlay->vert_buf)
{
overlay->vert_buf = d3d9_vertex_buffer_new(
dev, sizeof(vert), D3DUSAGE_WRITEONLY,
#ifdef _XBOX
0,
#else
D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1,
#endif
D3DPOOL_MANAGED, NULL);
if (!overlay->vert_buf)
return;
}
for (i = 0; i < 4; i++)
{
vert[i].z = 0.5f;
vert[i].color = (((uint32_t)(overlay->alpha_mod * 0xFF)) << 24) | 0xFFFFFF;
}
d3d9_viewport_info(d3d, &vp);
vert[0].x = overlay->vert_coords[0];
vert[1].x = overlay->vert_coords[0] + overlay->vert_coords[2];
vert[2].x = overlay->vert_coords[0];
vert[3].x = overlay->vert_coords[0] + overlay->vert_coords[2];
vert[0].y = overlay->vert_coords[1];
vert[1].y = overlay->vert_coords[1];
vert[2].y = overlay->vert_coords[1] + overlay->vert_coords[3];
vert[3].y = overlay->vert_coords[1] + overlay->vert_coords[3];
vert[0].u = overlay->tex_coords[0];
vert[1].u = overlay->tex_coords[0] + overlay->tex_coords[2];
vert[2].u = overlay->tex_coords[0];
vert[3].u = overlay->tex_coords[0] + overlay->tex_coords[2];
vert[0].v = overlay->tex_coords[1];
vert[1].v = overlay->tex_coords[1];
vert[2].v = overlay->tex_coords[1] + overlay->tex_coords[3];
vert[3].v = overlay->tex_coords[1] + overlay->tex_coords[3];
verts = d3d9_vertex_buffer_lock((LPDIRECT3DVERTEXBUFFER9)overlay->vert_buf);
memcpy(verts, vert, sizeof(vert));
d3d9_vertex_buffer_unlock((LPDIRECT3DVERTEXBUFFER9)overlay->vert_buf);
d3d9_enable_blend_func(d3d->dev);
/* set vertex declaration for overlay. */
d3d9_vertex_declaration_new(dev, &vElems, (void**)&vertex_decl);
d3d9_set_vertex_declaration(dev, vertex_decl);
d3d9_vertex_declaration_free(vertex_decl);
d3d9_set_stream_source(dev, 0, (LPDIRECT3DVERTEXBUFFER9)overlay->vert_buf,
0, sizeof(*vert));
if (overlay->fullscreen)
{
D3DVIEWPORT9 vp_full;
vp_full.X = 0;
vp_full.Y = 0;
vp_full.Width = width;
vp_full.Height = height;
vp_full.MinZ = 0.0f;
vp_full.MaxZ = 1.0f;
d3d9_set_viewports(dev, &vp_full);
}
filter_type = D3DTEXF_LINEAR;
if (!force_linear)
{
settings_t *settings = config_get_ptr();
bool menu_linear_filter = settings->bools.menu_linear_filter;
if (!menu_linear_filter)
filter_type = D3DTEXF_POINT;
}
/* Render overlay. */
d3d9_set_texture(dev, 0, (LPDIRECT3DTEXTURE9)overlay->tex);
d3d9_set_sampler_address_u(dev, 0, D3DTADDRESS_BORDER);
d3d9_set_sampler_address_v(dev, 0, D3DTADDRESS_BORDER);
d3d9_set_sampler_minfilter(dev, 0, filter_type);
d3d9_set_sampler_magfilter(dev, 0, filter_type);
d3d9_draw_primitive(dev, D3DPT_TRIANGLESTRIP, 0, 2);
/* Restore previous state. */
d3d9_disable_blend_func(dev);
d3d9_set_viewports(dev, &d3d->final_viewport);
}
#endif
static void d3d9_free_overlay(d3d9_video_t *d3d, overlay_t *overlay)
{
if (!d3d)
return;
d3d9_texture_free((LPDIRECT3DTEXTURE9)overlay->tex);
d3d9_vertex_buffer_free(overlay->vert_buf, NULL);
}
static void d3d9_deinit_chain(d3d9_video_t *d3d)
{
if (!d3d || !d3d->renderchain_driver)
return;
if (d3d->renderchain_driver->chain_free)
d3d->renderchain_driver->chain_free(d3d->renderchain_data);
d3d->renderchain_driver = NULL;
d3d->renderchain_data = NULL;
}
static void d3d9_deinitialize(d3d9_video_t *d3d)
{
if (!d3d)
return;
font_driver_free_osd();
d3d9_deinit_chain(d3d);
d3d9_vertex_buffer_free(d3d->menu_display.buffer, d3d->menu_display.decl);
d3d->menu_display.buffer = NULL;
d3d->menu_display.decl = NULL;
}
static D3DFORMAT d3d9_get_color_format_backbuffer(bool rgb32, bool windowed)
{
D3DFORMAT fmt = D3DFMT_X8R8G8B8;
#ifdef _XBOX
if (!rgb32)
fmt = d3d9_get_rgb565_format();
#else
if (windowed)
{
D3DDISPLAYMODE display_mode;
if (d3d9_get_adapter_display_mode(g_pD3D9, 0, &display_mode))
fmt = display_mode.Format;
}
#endif
return fmt;
}
#ifdef _XBOX
static D3DFORMAT d3d9_get_color_format_front_buffer(void)
{
return D3DFMT_LE_X8R8G8B8;
}
#endif
static bool d3d9_is_windowed_enable(bool info_fullscreen)
{
#ifndef _XBOX
settings_t *settings = config_get_ptr();
if (!info_fullscreen)
return true;
if (settings)
return settings->bools.video_windowed_fullscreen;
#endif
return false;
}
#ifdef _XBOX
static void d3d9_get_video_size(d3d9_video_t *d3d,
unsigned *width, unsigned *height)
{
XVIDEO_MODE video_mode;
XGetVideoMode(&video_mode);
*width = video_mode.dwDisplayWidth;
*height = video_mode.dwDisplayHeight;
d3d->resolution_hd_enable = false;
if(video_mode.fIsHiDef)
{
*width = 1280;
*height = 720;
d3d->resolution_hd_enable = true;
}
else
{
*width = 640;
*height = 480;
}
d3d->widescreen_mode = video_mode.fIsWideScreen;
}
#endif
void d3d9_make_d3dpp(void *data,
const video_info_t *info, void *_d3dpp)
{
d3d9_video_t *d3d = (d3d9_video_t*)data;
D3DPRESENT_PARAMETERS *d3dpp = (D3DPRESENT_PARAMETERS*)_d3dpp;
#ifdef _XBOX
/* TODO/FIXME - get rid of global state dependencies. */
global_t *global = global_get_ptr();
bool gamma_enable = global ?
global->console.screen.gamma_correction : false;
#endif
bool windowed_enable = d3d9_is_windowed_enable(info->fullscreen);
memset(d3dpp, 0, sizeof(*d3dpp));
d3dpp->Windowed = windowed_enable;
FS_PRESENTINTERVAL(d3dpp) = D3DPRESENT_INTERVAL_IMMEDIATE;
if (info->vsync)
{
settings_t *settings = config_get_ptr();
unsigned video_swap_interval = settings->uints.video_swap_interval;
switch (video_swap_interval)
{
default:
case 1:
FS_PRESENTINTERVAL(d3dpp) = D3DPRESENT_INTERVAL_ONE;
break;
case 2:
FS_PRESENTINTERVAL(d3dpp) = D3DPRESENT_INTERVAL_TWO;
break;
case 3:
FS_PRESENTINTERVAL(d3dpp) = D3DPRESENT_INTERVAL_THREE;
break;
case 4:
FS_PRESENTINTERVAL(d3dpp) = D3DPRESENT_INTERVAL_FOUR;
break;
}
}
d3dpp->SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp->BackBufferCount = 2;
d3dpp->BackBufferFormat = d3d9_get_color_format_backbuffer(
info->rgb32, windowed_enable);
#ifdef _XBOX
d3dpp->FrontBufferFormat = d3d9_get_color_format_front_buffer();
if (gamma_enable)
{
d3dpp->BackBufferFormat = (D3DFORMAT)MAKESRGBFMT(
d3dpp->BackBufferFormat);
d3dpp->FrontBufferFormat = (D3DFORMAT)MAKESRGBFMT(
d3dpp->FrontBufferFormat);
}
#else
d3dpp->hDeviceWindow = win32_get_window();
#endif
if (!windowed_enable)
{
#ifdef _XBOX
unsigned width = 0;
unsigned height = 0;
d3d9_get_video_size(d3d, &width, &height);
video_driver_set_size(width, height);
#endif
video_driver_get_size(&d3dpp->BackBufferWidth,
&d3dpp->BackBufferHeight);
}
#ifdef _XBOX
d3dpp->MultiSampleType = D3DMULTISAMPLE_NONE;
d3dpp->EnableAutoDepthStencil = FALSE;
if (!d3d->widescreen_mode)
d3dpp->Flags |= D3DPRESENTFLAG_NO_LETTERBOX;
d3dpp->MultiSampleQuality = 0;
#endif
}
static bool d3d9_init_base(void *data, const video_info_t *info)
{
D3DPRESENT_PARAMETERS d3dpp;
HWND focus_window = NULL;
d3d9_video_t *d3d = (d3d9_video_t*)data;
#ifndef _XBOX
focus_window = win32_get_window();
#endif
memset(&d3dpp, 0, sizeof(d3dpp));
g_pD3D9 = (LPDIRECT3D9)d3d9_create();
/* this needs g_pD3D9 created first */
d3d9_make_d3dpp(d3d, info, &d3dpp);
if (!g_pD3D9)
{
RARCH_ERR("[D3D9]: Failed to create D3D interface.\n");
return false;
}
if (!d3d9_create_device(&d3d->dev, &d3dpp,
g_pD3D9,
focus_window,
d3d->cur_mon_id)
)
{
RARCH_ERR("[D3D9]: Failed to initialize device.\n");
return false;
}
return true;
}
static void d3d9_calculate_rect(void *data,
unsigned *width, unsigned *height,
int *x, int *y,
bool force_full,
bool allow_rotate)
{
float device_aspect = (float)*width / *height;
d3d9_video_t *d3d = (d3d9_video_t*)data;
settings_t *settings = config_get_ptr();
bool scale_integer = settings->bools.video_scale_integer;
video_driver_get_size(width, height);
*x = 0;
*y = 0;
if (scale_integer && !force_full)
{
struct video_viewport vp;
vp.x = 0;
vp.y = 0;
vp.width = 0;
vp.height = 0;
vp.full_width = 0;
vp.full_height = 0;
video_viewport_get_scaled_integer(&vp,
*width,
*height,
video_driver_get_aspect_ratio(),
d3d->keep_aspect);
*x = vp.x;
*y = vp.y;
*width = vp.width;
*height = vp.height;
}
else if (d3d->keep_aspect && !force_full)
{
float desired_aspect = video_driver_get_aspect_ratio();
#if defined(HAVE_MENU)
if (settings->uints.video_aspect_ratio_idx == ASPECT_RATIO_CUSTOM)
{
video_viewport_t *custom = video_viewport_get_custom();
*x = custom->x;
*y = custom->y;
*width = custom->width;
*height = custom->height;
}
else
#endif
{
float delta;
if (fabsf(device_aspect - desired_aspect) < 0.0001f)
{
/* If the aspect ratios of screen and desired aspect
* ratio are sufficiently equal (floating point stuff),
* assume they are actually equal.
*/
}
else if (device_aspect > desired_aspect)
{
delta = (desired_aspect / device_aspect - 1.0f) / 2.0f + 0.5f;
*x = (int)(roundf(*width * (0.5f - delta)));
*width = (unsigned)(roundf(2.0f * (*width) * delta));
}
else
{
delta = (device_aspect / desired_aspect - 1.0f) / 2.0f + 0.5f;
*y = (int)(roundf(*height * (0.5f - delta)));
*height = (unsigned)(roundf(2.0f * (*height) * delta));
}
}
}
}
static void d3d9_set_font_rect(
d3d9_video_t *d3d,
const struct font_params *params)
{
settings_t *settings = config_get_ptr();
float pos_x = settings->floats.video_msg_pos_x;
float pos_y = settings->floats.video_msg_pos_y;
float font_size = settings->floats.video_font_size;
if (params)
{
pos_x = params->x;
pos_y = params->y;
font_size *= params->scale;
}
if (!d3d)
return;
d3d->font_rect.left = d3d->video_info.width * pos_x;
d3d->font_rect.right = d3d->video_info.width;
d3d->font_rect.top = (1.0f - pos_y) * d3d->video_info.height - font_size;
d3d->font_rect.bottom = d3d->video_info.height;
d3d->font_rect_shifted = d3d->font_rect;
d3d->font_rect_shifted.left -= 2;
d3d->font_rect_shifted.right -= 2;
d3d->font_rect_shifted.top += 2;
d3d->font_rect_shifted.bottom += 2;
}
static void d3d9_set_viewport(void *data,
unsigned width, unsigned height,
bool force_full,
bool allow_rotate)
{
int x = 0;
int y = 0;
d3d9_video_t *d3d = (d3d9_video_t*)data;
d3d9_calculate_rect(data, &width, &height, &x, &y,
force_full, allow_rotate);
/* D3D doesn't support negative X/Y viewports ... */
if (x < 0)
x = 0;
if (y < 0)
y = 0;
d3d->final_viewport.X = x;
d3d->final_viewport.Y = y;
d3d->final_viewport.Width = width;
d3d->final_viewport.Height = height;
d3d->final_viewport.MinZ = 0.0f;
d3d->final_viewport.MaxZ = 1.0f;
d3d9_set_font_rect(d3d, NULL);
}
static bool d3d9_initialize(d3d9_video_t *d3d, const video_info_t *info)
{
unsigned width, height;
bool ret = true;
settings_t *settings = config_get_ptr();
if (!d3d)
return false;
if (!g_pD3D9)
ret = d3d9_init_base(d3d, info);
else if (d3d->needs_restore)
{
D3DPRESENT_PARAMETERS d3dpp;
d3d9_make_d3dpp(d3d, info, &d3dpp);
/* the D3DX font driver uses POOL_DEFAULT resources
* and will prevent a clean reset here
* another approach would be to keep track of all created D3D
* font objects and free/realloc them around the d3d_reset call */
#ifdef HAVE_MENU
menu_driver_ctl(RARCH_MENU_CTL_DEINIT, NULL);
#endif
if (!d3d9_reset(d3d->dev, &d3dpp))
{
d3d9_deinitialize(d3d);
d3d9_device_free(NULL, g_pD3D9);
g_pD3D9 = NULL;
ret = d3d9_init_base(d3d, info);
if (ret)
RARCH_LOG("[D3D9]: Recovered from dead state.\n");
}
#ifdef HAVE_MENU
menu_driver_init(info->is_threaded);
#endif
}
if (!ret)
return ret;
if (!d3d9_init_chain(d3d, info->input_scale, info->rgb32))
{
RARCH_ERR("[D3D9]: Failed to initialize render chain.\n");
return false;
}
video_driver_get_size(&width, &height);
d3d9_set_viewport(d3d,
width, height, false, true);
font_driver_init_osd(d3d, info,
false,
info->is_threaded,
FONT_DRIVER_RENDER_D3D9_API);
{
static const D3DVERTEXELEMENT9 VertexElements[4] = {
{0, offsetof(Vertex, x), D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT,
D3DDECLUSAGE_POSITION, 0},
{0, offsetof(Vertex, u), D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT,
D3DDECLUSAGE_TEXCOORD, 0},
{0, offsetof(Vertex, color), D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
D3DDECLUSAGE_COLOR, 0},
D3DDECL_END()
};
if (!d3d9_vertex_declaration_new(d3d->dev,
(void*)VertexElements, (void**)&d3d->menu_display.decl))
return false;
}
d3d->menu_display.offset = 0;
d3d->menu_display.size = 1024;
d3d->menu_display.buffer = d3d9_vertex_buffer_new(
d3d->dev, d3d->menu_display.size * sizeof(Vertex),
D3DUSAGE_WRITEONLY,
#ifdef _XBOX
0,
#else
D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1,
#endif
D3DPOOL_DEFAULT,
NULL);
if (!d3d->menu_display.buffer)
return false;
d3d_matrix_ortho_off_center_lh(&d3d->mvp_transposed, 0, 1, 0, 1, 0, 1);
d3d_matrix_transpose(&d3d->mvp, &d3d->mvp_transposed);
d3d9_set_render_state(d3d->dev, D3DRS_CULLMODE, D3DCULL_NONE);
d3d9_set_render_state(d3d->dev, D3DRS_SCISSORTESTENABLE, TRUE);
return true;
}
static bool d3d9_restore(void *data)
{
d3d9_video_t *d3d = (d3d9_video_t*)data;
if (!d3d)
return false;
d3d9_deinitialize(d3d);
if (!d3d9_initialize(d3d, &d3d->video_info))
{
RARCH_ERR("[D3D9]: Restore error.\n");
return false;
}
d3d->needs_restore = false;
return true;
}
static void d3d9_set_nonblock_state(void *data, bool state,
bool adaptive_vsync_enabled,
unsigned swap_interval)
{
#ifdef _XBOX
int interval = 0;
#endif
d3d9_video_t *d3d = (d3d9_video_t*)data;
if (!d3d)
return;
#ifdef _XBOX
if (!state)
interval = 1;
#endif
d3d->video_info.vsync = !state;
#ifdef _XBOX
d3d9_set_render_state(d3d->dev,
D3D9_PRESENTATIONINTERVAL,
interval ?
D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE
);
#else
d3d->needs_restore = true;
d3d9_restore(d3d);
#endif
}
static bool d3d9_alive(void *data)
{
unsigned temp_width = 0;
unsigned temp_height = 0;
bool ret = false;
bool quit = false;
bool resize = false;
d3d9_video_t *d3d = (d3d9_video_t*)data;
/* Needed because some context drivers don't track their sizes */
video_driver_get_size(&temp_width, &temp_height);
#ifndef _XBOX
win32_check_window(&quit, &resize, &temp_width, &temp_height);
#endif
if (quit)
d3d->quitting = quit;
if (resize)
{
d3d->should_resize = true;
d3d9_set_resize(d3d, temp_width, temp_height);
d3d9_restore(d3d);
}
ret = !quit;
if ( temp_width != 0 &&
temp_height != 0)
video_driver_set_size(temp_width, temp_height);
return ret;
}
static bool d3d9_suppress_screensaver(void *data, bool enable)
{
#ifdef _XBOX
return true;
#else
return win32_suppress_screensaver(data, enable);
#endif
}
static void d3d9_set_aspect_ratio(void *data, unsigned aspect_ratio_idx)
{
d3d9_video_t *d3d = (d3d9_video_t*)data;
if (!d3d)
return;
d3d->keep_aspect = true;
d3d->should_resize = true;
}
static void d3d9_apply_state_changes(void *data)
{
d3d9_video_t *d3d = (d3d9_video_t*)data;
if (d3d)
d3d->should_resize = true;
}
static void d3d9_set_osd_msg(void *data,
const char *msg,
const void *params, void *font)
{
d3d9_video_t *d3d = (d3d9_video_t*)data;
LPDIRECT3DDEVICE9 dev = d3d->dev;
const struct font_params *d3d_font_params = (const
struct font_params*)params;
d3d9_set_font_rect(d3d, d3d_font_params);
d3d9_begin_scene(dev);
font_driver_render_msg(d3d,
msg, d3d_font_params, font);
d3d9_end_scene(dev);
}
static bool d3d9_init_internal(d3d9_video_t *d3d,
const video_info_t *info, input_driver_t **input,
void **input_data)
{
#ifdef HAVE_MONITOR
bool windowed_full;
RECT mon_rect;
MONITORINFOEX current_mon;
HMONITOR hm_to_use;
#endif
#ifdef HAVE_WINDOW
DWORD style;
unsigned win_width = 0;
unsigned win_height = 0;
RECT rect = {0};
#endif
unsigned full_x = 0;
unsigned full_y = 0;
settings_t *settings = config_get_ptr();
overlay_t *menu = (overlay_t*)calloc(1, sizeof(*menu));
if (!menu)
return false;
d3d->menu = menu;
d3d->cur_mon_id = 0;
d3d->menu->tex_coords[0] = 0;
d3d->menu->tex_coords[1] = 0;
d3d->menu->tex_coords[2] = 1;
d3d->menu->tex_coords[3] = 1;
d3d->menu->vert_coords[0] = 0;
d3d->menu->vert_coords[1] = 1;
d3d->menu->vert_coords[2] = 1;
d3d->menu->vert_coords[3] = -1;
#ifdef HAVE_WINDOW
memset(&d3d->windowClass, 0, sizeof(d3d->windowClass));
d3d->windowClass.lpfnWndProc = WndProcD3D;
win32_window_init(&d3d->windowClass, true, NULL);
#endif
#ifdef HAVE_MONITOR
win32_monitor_info(¤t_mon, &hm_to_use, &d3d->cur_mon_id);
mon_rect = current_mon.rcMonitor;
g_win32_resize_width = info->width;
g_win32_resize_height = info->height;
windowed_full = settings->bools.video_windowed_fullscreen;
full_x = (windowed_full || info->width == 0) ?
(mon_rect.right - mon_rect.left) : info->width;
full_y = (windowed_full || info->height == 0) ?
(mon_rect.bottom - mon_rect.top) : info->height;
RARCH_LOG("[D3D9]: Monitor size: %dx%d.\n",
(int)(mon_rect.right - mon_rect.left),
(int)(mon_rect.bottom - mon_rect.top));
#else
{
d3d9_get_video_size(d3d, &full_x, &full_y);
}
#endif
{
unsigned new_width = info->fullscreen ? full_x : info->width;
unsigned new_height = info->fullscreen ? full_y : info->height;
video_driver_set_size(new_width, new_height);
}
#ifdef HAVE_WINDOW
video_driver_get_size(&win_width, &win_height);
win32_set_style(¤t_mon, &hm_to_use, &win_width, &win_height,
info->fullscreen, windowed_full, &rect, &mon_rect, &style);
win32_window_create(d3d, style, &mon_rect, win_width,
win_height, info->fullscreen);
win32_set_window(&win_width, &win_height, info->fullscreen,
windowed_full, &rect);
#endif
d3d->video_info = *info;
if (!d3d9_initialize(d3d, &d3d->video_info))
return false;
d3d9_fake_context.get_flags = d3d9_get_flags;
#ifndef _XBOX_
d3d9_fake_context.get_metrics = win32_get_metrics;
#endif
video_context_driver_set(&d3d9_fake_context);
#if defined(HAVE_CG) || defined(HAVE_HLSL)
{
const char *shader_preset = retroarch_get_shader_preset();
enum rarch_shader_type type = video_shader_parse_type(shader_preset);
d3d9_set_shader(d3d, type, shader_preset);
}
#endif
d3d_input_driver(settings->arrays.input_joypad_driver,
settings->arrays.input_joypad_driver, input, input_data);
{
char version_str[128];
D3DADAPTER_IDENTIFIER9 ident = {0};
IDirect3D9_GetAdapterIdentifier(g_pD3D9, 0, 0, &ident);
version_str[0] = '\0';
snprintf(version_str, sizeof(version_str), "%u.%u.%u.%u", HIWORD(ident.DriverVersion.HighPart), LOWORD(ident.DriverVersion.HighPart), HIWORD(ident.DriverVersion.LowPart), LOWORD(ident.DriverVersion.LowPart));
RARCH_LOG("[D3D9]: Using GPU: %s\n", ident.Description);
RARCH_LOG("[D3D9]: GPU API Version: %s\n", version_str);
video_driver_set_gpu_device_string(ident.Description);
video_driver_set_gpu_api_version_string(version_str);
}
RARCH_LOG("[D3D9]: Init complete.\n");
return true;
}
static void d3d9_set_rotation(void *data, unsigned rot)
{
d3d9_video_t *d3d = (d3d9_video_t*)data;
struct video_ortho ortho = {0, 1, 0, 1, -1, 1};
if (!d3d)
return;
d3d->dev_rotation = rot;
}
static void *d3d9_init(const video_info_t *info,
input_driver_t **input, void **input_data)
{
d3d9_video_t *d3d = (d3d9_video_t*)calloc(1, sizeof(*d3d));
if (!d3d)
return NULL;
if (!d3d9_initialize_symbols(GFX_CTX_DIRECT3D9_API))
{
free(d3d);
return NULL;
}
#ifndef _XBOX
win32_window_reset();
win32_monitor_init();
#endif
/* Default values */
d3d->dev = NULL;
d3d->dev_rotation = 0;
d3d->needs_restore = false;
#ifdef HAVE_OVERLAY
d3d->overlays_enabled = false;
#endif
d3d->should_resize = false;
d3d->menu = NULL;
if (!d3d9_init_internal(d3d, info, input, input_data))
{
RARCH_ERR("[D3D9]: Failed to init D3D.\n");
free(d3d);
return NULL;
}
d3d->keep_aspect = info->force_aspect;
return d3d;
}
#ifdef HAVE_OVERLAY
static void d3d9_free_overlays(d3d9_video_t *d3d)
{
unsigned i;
if (!d3d)
return;
for (i = 0; i < d3d->overlays_size; i++)
d3d9_free_overlay(d3d, &d3d->overlays[i]);
free(d3d->overlays);
d3d->overlays = NULL;
d3d->overlays_size = 0;
}
#endif
static void d3d9_free(void *data)
{
d3d9_video_t *d3d = (d3d9_video_t*)data;
if (!d3d)
return;
#ifdef HAVE_OVERLAY
d3d9_free_overlays(d3d);
if (d3d->overlays)
free(d3d->overlays);
d3d->overlays = NULL;
d3d->overlays_size = 0;
#endif
d3d9_free_overlay(d3d, d3d->menu);
if (d3d->menu)
free(d3d->menu);
d3d->menu = NULL;
d3d9_deinitialize(d3d);
if (!string_is_empty(d3d->shader_path))
free(d3d->shader_path);
d3d->shader_path = NULL;
d3d9_device_free(d3d->dev, g_pD3D9);
d3d->dev = NULL;
g_pD3D9 = NULL;
d3d9_deinitialize_symbols();
#ifndef _XBOX
win32_monitor_from_window();
win32_destroy_window();
#endif
free(d3d);
}
#ifdef HAVE_OVERLAY
static void d3d9_overlay_tex_geom(
void *data,
unsigned index,
float x, float y,
float w, float h)
{
d3d9_video_t *d3d = (d3d9_video_t*)data;
if (!d3d)
return;
d3d->overlays[index].tex_coords[0] = x;
d3d->overlays[index].tex_coords[1] = y;
d3d->overlays[index].tex_coords[2] = w;
d3d->overlays[index].tex_coords[3] = h;
}
static void d3d9_overlay_vertex_geom(
void *data,
unsigned index,
float x, float y,
float w, float h)
{
d3d9_video_t *d3d = (d3d9_video_t*)data;
if (!d3d)
return;
y = 1.0f - y;
h = -h;
d3d->overlays[index].vert_coords[0] = x;
d3d->overlays[index].vert_coords[1] = y;
d3d->overlays[index].vert_coords[2] = w;
d3d->overlays[index].vert_coords[3] = h;
}
static bool d3d9_overlay_load(void *data,
const void *image_data, unsigned num_images)
{
unsigned i, y;
overlay_t *new_overlays = NULL;
d3d9_video_t *d3d = (d3d9_video_t*)data;
const struct texture_image *images = (const struct texture_image*)
image_data;
if (!d3d)
return false;
d3d9_free_overlays(d3d);
d3d->overlays = (overlay_t*)calloc(num_images, sizeof(*d3d->overlays));
d3d->overlays_size = num_images;
for (i = 0; i < num_images; i++)
{
D3DLOCKED_RECT d3dlr;
unsigned width = images[i].width;
unsigned height = images[i].height;
overlay_t *overlay = (overlay_t*)&d3d->overlays[i];
overlay->tex = d3d9_texture_new(d3d->dev, NULL,
width, height, 1,
0,
d3d9_get_argb8888_format(),
D3DPOOL_MANAGED, 0, 0, 0,
NULL, NULL, false);
if (!overlay->tex)
{
RARCH_ERR("[D3D9]: Failed to create overlay texture\n");
return false;
}
if (d3d9_lock_rectangle((LPDIRECT3DTEXTURE9)overlay->tex, 0, &d3dlr,
NULL, 0, D3DLOCK_NOSYSLOCK))
{
uint32_t *dst = (uint32_t*)(d3dlr.pBits);
const uint32_t *src = images[i].pixels;
unsigned pitch = d3dlr.Pitch >> 2;
for (y = 0; y < height; y++, dst += pitch, src += width)
memcpy(dst, src, width << 2);
d3d9_unlock_rectangle((LPDIRECT3DTEXTURE9)overlay->tex);
}
overlay->tex_w = width;
overlay->tex_h = height;
/* Default. Stretch to whole screen. */
d3d9_overlay_tex_geom(d3d, i, 0, 0, 1, 1);
d3d9_overlay_vertex_geom(d3d, i, 0, 0, 1, 1);
}
return true;
}
static void d3d9_overlay_enable(void *data, bool state)
{
unsigned i;
d3d9_video_t *d3d = (d3d9_video_t*)data;
if (!d3d)
return;
for (i = 0; i < d3d->overlays_size; i++)
d3d->overlays_enabled = state;
#ifndef XBOX
win32_show_cursor(d3d, state);
#endif
}
static void d3d9_overlay_full_screen(void *data, bool enable)
{
unsigned i;
d3d9_video_t *d3d = (d3d9_video_t*)data;
for (i = 0; i < d3d->overlays_size; i++)
d3d->overlays[i].fullscreen = enable;
}
static void d3d9_overlay_set_alpha(void *data, unsigned index, float mod)
{
d3d9_video_t *d3d = (d3d9_video_t*)data;
if (d3d)
d3d->overlays[index].alpha_mod = mod;
}
static const video_overlay_interface_t d3d9_overlay_interface = {
d3d9_overlay_enable,
d3d9_overlay_load,
d3d9_overlay_tex_geom,
d3d9_overlay_vertex_geom,
d3d9_overlay_full_screen,
d3d9_overlay_set_alpha,
};
static void d3d9_get_overlay_interface(void *data,
const video_overlay_interface_t **iface)
{
(void)data;
*iface = &d3d9_overlay_interface;
}
#endif
static void d3d9_update_title(void)
{
#ifndef _XBOX
const ui_window_t *window = ui_companion_driver_get_window_ptr();
if (window)
{
char title[128];
title[0] = '\0';
video_driver_get_window_title(title, sizeof(title));
if (title[0])
window->set_title(&main_window, title);
}
#endif
}
static bool d3d9_frame(void *data, const void *frame,
unsigned frame_width, unsigned frame_height,
uint64_t frame_count, unsigned pitch,
const char *msg, video_frame_info_t *video_info)
{
D3DVIEWPORT9 screen_vp;
unsigned i = 0;
d3d9_video_t *d3d = (d3d9_video_t*)data;
unsigned width = video_info->width;
unsigned height = video_info->height;
bool statistics_show = video_info->statistics_show;
bool black_frame_insertion = video_info->black_frame_insertion;
struct font_params *osd_params = (struct font_params*)
&video_info->osd_stat_params;
const char *stat_text = video_info->stat_text;
if (!frame)
return true;
/* We cannot recover in fullscreen. */
if (d3d->needs_restore)
{
#ifndef _XBOX
HWND window = win32_get_window();
if (IsIconic(window))
return true;
#endif
if (!d3d9_restore(d3d))
{
RARCH_ERR("[D3D9]: Failed to restore.\n");
return false;
}
}
if (d3d->should_resize)
{
d3d9_set_viewport(d3d, width, height, false, true);
if (d3d->renderchain_driver->set_final_viewport)
d3d->renderchain_driver->set_final_viewport(d3d,
d3d->renderchain_data, &d3d->final_viewport);
d3d->should_resize = false;
}
/* render_chain() only clears out viewport,
* clear out everything. */
screen_vp.X = 0;
screen_vp.Y = 0;
screen_vp.MinZ = 0;
screen_vp.MaxZ = 1;
screen_vp.Width = width;
screen_vp.Height = height;
d3d9_set_viewports(d3d->dev, &screen_vp);
d3d9_clear(d3d->dev, 0, 0, D3DCLEAR_TARGET, 0, 1, 0);
/* Insert black frame first, so we
* can screenshot, etc. */
if (black_frame_insertion)
{
if (!d3d9_swap(d3d, d3d->dev) || d3d->needs_restore)
return true;
d3d9_clear(d3d->dev, 0, 0, D3DCLEAR_TARGET, 0, 1, 0);
}
if (!d3d->renderchain_driver->render(
d3d, frame, frame_width, frame_height,
pitch, d3d->dev_rotation))
{
RARCH_ERR("[D3D9]: Failed to render scene.\n");
return false;
}
#ifdef HAVE_MENU
if (d3d->menu && d3d->menu->enabled)
{
d3d9_set_mvp(d3d->dev, &d3d->mvp);
d3d9_overlay_render(d3d, width, height, d3d->menu, false);
d3d->menu_display.offset = 0;
d3d9_set_vertex_declaration(d3d->dev, (LPDIRECT3DVERTEXDECLARATION9)d3d->menu_display.decl);
d3d9_set_stream_source(d3d->dev, 0, (LPDIRECT3DVERTEXBUFFER9)d3d->menu_display.buffer, 0, sizeof(Vertex));
d3d9_set_viewports(d3d->dev, &screen_vp);
menu_driver_frame(video_info);
}
else if (statistics_show)
{
if (osd_params)
{
d3d9_set_viewports(d3d->dev, &screen_vp);
d3d9_begin_scene(d3d->dev);
font_driver_render_msg(d3d, stat_text,
(const struct font_params*)osd_params, NULL);
d3d9_end_scene(d3d->dev);
}
}
#endif
#ifdef HAVE_OVERLAY
if (d3d->overlays_enabled)
{
d3d9_set_mvp(d3d->dev, &d3d->mvp);
for (i = 0; i < d3d->overlays_size; i++)
d3d9_overlay_render(d3d, width, height, &d3d->overlays[i], true);
}
#endif
#ifdef HAVE_GFX_WIDGETS
gfx_widgets_frame(video_info);
#endif
if (msg && *msg)
{
d3d9_set_viewports(d3d->dev, &screen_vp);
d3d9_begin_scene(d3d->dev);
font_driver_render_msg(d3d, msg, NULL, NULL);
d3d9_end_scene(d3d->dev);
}
d3d9_update_title();
d3d9_swap(d3d, d3d->dev);
return true;
}
static bool d3d9_read_viewport(void *data, uint8_t *buffer, bool is_idle)
{
unsigned width, height;
D3DLOCKED_RECT rect;
LPDIRECT3DSURFACE9 target = NULL;
LPDIRECT3DSURFACE9 dest = NULL;
bool ret = true;
d3d9_video_t *d3d = (d3d9_video_t*)data;
LPDIRECT3DDEVICE9 d3dr = d3d->dev;
video_driver_get_size(&width, &height);
if (
!d3d9_device_get_render_target(d3dr, 0, (void**)&target) ||
!d3d9_device_create_offscreen_plain_surface(d3dr, width, height,
d3d9_get_xrgb8888_format(),
D3DPOOL_SYSTEMMEM, (void**)&dest, NULL) ||
!d3d9_device_get_render_target_data(d3dr, target, dest)
)
{
ret = false;
goto end;
}
if (d3d9_surface_lock_rect(dest, &rect))
{
unsigned x, y;
unsigned pitchpix = rect.Pitch / 4;
const uint32_t *pixels = (const uint32_t*)rect.pBits;
pixels += d3d->final_viewport.X;
pixels += (d3d->final_viewport.Height - 1) * pitchpix;
pixels -= d3d->final_viewport.Y * pitchpix;
for (y = 0; y < d3d->final_viewport.Height; y++, pixels -= pitchpix)
{
for (x = 0; x < d3d->final_viewport.Width; x++)
{
*buffer++ = (pixels[x] >> 0) & 0xff;
*buffer++ = (pixels[x] >> 8) & 0xff;
*buffer++ = (pixels[x] >> 16) & 0xff;
}
}
d3d9_surface_unlock_rect(dest);
}
else
ret = false;
end:
if (target)
d3d9_surface_free(target);
if (dest)
d3d9_surface_free(dest);
return ret;
}
static bool d3d9_set_shader(void *data,
enum rarch_shader_type type, const char *path)
{
#if defined(HAVE_CG) || defined(HAVE_HLSL)
d3d9_video_t *d3d = (d3d9_video_t*)data;
if (!d3d)
return false;
if (!string_is_empty(d3d->shader_path))
free(d3d->shader_path);
d3d->shader_path = NULL;
switch (type)
{
case RARCH_SHADER_CG:
case RARCH_SHADER_HLSL:
if (type != supported_shader_type)
{
RARCH_WARN("[D3D9]: Shader preset %s is using unsupported shader type %s, falling back to stock %s.\n",
path, video_shader_to_str(type), video_shader_to_str(supported_shader_type));
break;
}
if (!string_is_empty(path))
d3d->shader_path = strdup(path);
break;
case RARCH_SHADER_NONE:
break;
default:
RARCH_WARN("[D3D9]: Only Cg shaders are supported. Falling back to stock.\n");
}
if (!d3d9_process_shader(d3d) || !d3d9_restore(d3d))
{
RARCH_ERR("[D3D9]: Failed to set shader.\n");
return false;
}
return true;
#else
return false;
#endif
}
static void d3d9_set_menu_texture_frame(void *data,
const void *frame, bool rgb32, unsigned width, unsigned height,
float alpha)
{
D3DLOCKED_RECT d3dlr;
d3d9_video_t *d3d = (d3d9_video_t*)data;
(void)d3dlr;
(void)frame;
(void)rgb32;
(void)width;
(void)height;
(void)alpha;
if (!d3d || !d3d->menu)
return;
if ( !d3d->menu->tex ||
d3d->menu->tex_w != width ||
d3d->menu->tex_h != height)
{
d3d9_texture_free((LPDIRECT3DTEXTURE9)d3d->menu->tex);
d3d->menu->tex = d3d9_texture_new(d3d->dev, NULL,
width, height, 1,
0, d3d9_get_argb8888_format(),
D3DPOOL_MANAGED, 0, 0, 0, NULL, NULL, false);
if (!d3d->menu->tex)
{
RARCH_ERR("[D3D9]: Failed to create menu texture.\n");
return;
}
d3d->menu->tex_w = width;
d3d->menu->tex_h = height;
}
d3d->menu->alpha_mod = alpha;
if (d3d9_lock_rectangle((LPDIRECT3DTEXTURE9)d3d->menu->tex, 0, &d3dlr,
NULL, 0, D3DLOCK_NOSYSLOCK))
{
unsigned h, w;
if (rgb32)
{
uint8_t *dst = (uint8_t*)d3dlr.pBits;
const uint32_t *src = (const uint32_t*)frame;
for (h = 0; h < height; h++, dst += d3dlr.Pitch, src += width)
{
memcpy(dst, src, width * sizeof(uint32_t));
memset(dst + width * sizeof(uint32_t), 0,
d3dlr.Pitch - width * sizeof(uint32_t));
}
}
else
{
uint32_t *dst = (uint32_t*)d3dlr.pBits;
const uint16_t *src = (const uint16_t*)frame;
for (h = 0; h < height; h++, dst += d3dlr.Pitch >> 2, src += width)
{
for (w = 0; w < width; w++)
{
uint16_t c = src[w];
uint32_t r = (c >> 12) & 0xf;
uint32_t g = (c >> 8) & 0xf;
uint32_t b = (c >> 4) & 0xf;
uint32_t a = (c >> 0) & 0xf;
r = ((r << 4) | r) << 16;
g = ((g << 4) | g) << 8;
b = ((b << 4) | b) << 0;
a = ((a << 4) | a) << 24;
dst[w] = r | g | b | a;
}
}
}
if (d3d->menu)
d3d9_unlock_rectangle((LPDIRECT3DTEXTURE9)d3d->menu->tex);
}
}
static void d3d9_set_menu_texture_enable(void *data,
bool state, bool full_screen)
{
d3d9_video_t *d3d = (d3d9_video_t*)data;
if (!d3d || !d3d->menu)
return;
d3d->menu->enabled = state;
d3d->menu->fullscreen = full_screen;
}
struct d3d9_texture_info
{
void *userdata;
void *data;
enum texture_filter_type type;
};
static void d3d9_video_texture_load_d3d(
struct d3d9_texture_info *info,
uintptr_t *id)
{
D3DLOCKED_RECT d3dlr;
LPDIRECT3DTEXTURE9 tex = NULL;
unsigned usage = 0;
bool want_mipmap = false;
d3d9_video_t *d3d = (d3d9_video_t*)info->userdata;
struct texture_image *ti = (struct texture_image*)info->data;
if (!ti)
return;
if((info->type == TEXTURE_FILTER_MIPMAP_LINEAR) ||
(info->type == TEXTURE_FILTER_MIPMAP_NEAREST))
want_mipmap = true;
tex = (LPDIRECT3DTEXTURE9)d3d9_texture_new(d3d->dev, NULL,
ti->width, ti->height, 0,
usage, d3d9_get_argb8888_format(),
D3DPOOL_MANAGED, 0, 0, 0,
NULL, NULL, want_mipmap);
if (!tex)
{
RARCH_ERR("[D3D9]: Failed to create texture\n");
return;
}
if (d3d9_lock_rectangle(tex, 0, &d3dlr,
NULL, 0, D3DLOCK_NOSYSLOCK))
{
unsigned i;
uint32_t *dst = (uint32_t*)(d3dlr.pBits);
const uint32_t *src = ti->pixels;
unsigned pitch = d3dlr.Pitch >> 2;
for (i = 0; i < ti->height; i++, dst += pitch, src += ti->width)
memcpy(dst, src, ti->width << 2);
d3d9_unlock_rectangle(tex);
}
*id = (uintptr_t)tex;
}
#ifdef HAVE_THREADS
static int d3d9_video_texture_load_wrap_d3d(void *data)
{
uintptr_t id = 0;
struct d3d9_texture_info *info = (struct d3d9_texture_info*)data;
if (!info)
return 0;
d3d9_video_texture_load_d3d(info, &id);
return id;
}
#endif
static uintptr_t d3d9_load_texture(void *video_data, void *data,
bool threaded, enum texture_filter_type filter_type)
{
uintptr_t id = 0;
struct d3d9_texture_info info;
info.userdata = video_data;
info.data = data;
info.type = filter_type;
#ifdef HAVE_THREADS
if (threaded)
return video_thread_texture_load(&info,
d3d9_video_texture_load_wrap_d3d);
#endif
d3d9_video_texture_load_d3d(&info, &id);
return id;
}
static void d3d9_unload_texture(void *data, uintptr_t id)
{
LPDIRECT3DTEXTURE9 texid;
if (!id)
return;
texid = (LPDIRECT3DTEXTURE9)id;
d3d9_texture_free(texid);
}
static void d3d9_set_video_mode(void *data,
unsigned width, unsigned height,
bool fullscreen)
{
#ifndef _XBOX
win32_show_cursor(data, !fullscreen);
#endif
}
static uint32_t d3d9_get_flags(void *data)
{
uint32_t flags = 0;
BIT32_SET(flags, GFX_CTX_FLAGS_BLACK_FRAME_INSERTION);
BIT32_SET(flags, GFX_CTX_FLAGS_MENU_FRAME_FILTERING);
if (supported_shader_type == RARCH_SHADER_CG)
BIT32_SET(flags, GFX_CTX_FLAGS_SHADERS_CG);
else if (supported_shader_type == RARCH_SHADER_HLSL)
BIT32_SET(flags, GFX_CTX_FLAGS_SHADERS_HLSL);
return flags;
}
static const video_poke_interface_t d3d9_poke_interface = {
d3d9_get_flags,
d3d9_load_texture,
d3d9_unload_texture,
d3d9_set_video_mode,
#if defined(_XBOX) || defined(__WINRT__)
NULL,
#else
/* UWP does not expose this information easily */
win32_get_refresh_rate,
#endif
NULL,
NULL, /* get_video_output_size */
NULL, /* get_video_output_prev */
NULL, /* get_video_output_next */
NULL, /* get_current_framebuffer */
NULL, /* get_proc_address */
d3d9_set_aspect_ratio,
d3d9_apply_state_changes,
d3d9_set_menu_texture_frame,
d3d9_set_menu_texture_enable,
d3d9_set_osd_msg,
win32_show_cursor,
NULL, /* grab_mouse_toggle */
NULL, /* get_current_shader */
NULL, /* get_current_software_framebuffer */
NULL /* get_hw_render_interface */
};
static void d3d9_get_poke_interface(void *data,
const video_poke_interface_t **iface)
{
(void)data;
*iface = &d3d9_poke_interface;
}
static bool d3d9_has_windowed(void *data)
{
#ifdef _XBOX
return false;
#else
return true;
#endif
}
#ifdef HAVE_GFX_WIDGETS
static bool d3d9_gfx_widgets_enabled(void *data)
{
(void)data;
return false; /* currently disabled due to memory issues */
}
#endif
video_driver_t video_d3d9 = {
d3d9_init,
d3d9_frame,
d3d9_set_nonblock_state,
d3d9_alive,
NULL, /* focus */
d3d9_suppress_screensaver,
d3d9_has_windowed,
d3d9_set_shader,
d3d9_free,
"d3d9",
d3d9_set_viewport,
d3d9_set_rotation,
d3d9_viewport_info,
d3d9_read_viewport,
NULL, /* read_frame_raw */
#ifdef HAVE_OVERLAY
d3d9_get_overlay_interface,
#endif
#ifdef HAVE_VIDEO_LAYOUT
NULL,
#endif
d3d9_get_poke_interface,
NULL, /* wrap_type_to_enum */
#ifdef HAVE_GFX_WIDGETS
d3d9_gfx_widgets_enabled
#endif
};
| gpl-3.0 |
trbocode/Luma3DS | k11_extension/source/svc/SetWifiEnabled.c | 1 | 1392 | /*
* This file is part of Luma3DS
* Copyright (C) 2016-2018 Aurora Wright, TuxSH
*
* 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 3 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/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "svc/SetWifiEnabled.h"
Result SetWifiEnabled(bool enable)
{
if(enable)
CFG11_WIFICNT |= 1;
else
CFG11_WIFICNT &= ~1;
return 0;
}
| gpl-3.0 |
eggplantbren/NSCopying | code/Utils.cpp | 1 | 1617 | #include "Utils.h"
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
double mod(double y, double x)
{
if(x <= 0)
cerr<<"Warning in mod(double, double) (Utils.cpp)"<<endl;
return (y/x - floor(y/x))*x;
}
void wrap(double& x, double min, double max)
{
x = mod(x - min, max - min) + min;
}
int mod(int y, int x)
{
if(x <= 0)
cerr<<"Warning in mod(int, int) (Utils.cpp)"<<endl;
if(y >= 0)
return y - (y/x)*x;
else
return (x-1) - mod(-y-1, x);
}
double logsumexp(double* logv, int n)
{
if(n<=1)
cerr<<"Warning in logsumexp"<<endl;
double max = logv[0];
for(int i=1; i<n; i++)
if(logv[i] > max)
max = logv[i];
double answer = 0;
// log(sum(exp(logf)) = log(sum(exp(logf - max(logf) + max(logf)))
// = max(logf) + log(sum(exp(logf - max(logf)))
for(int i=0; i<n; i++)
answer += exp(logv[i] - max);
answer = max + log(answer);
return answer;
}
double logsumexp(const vector<double>& logv)
{
int n = static_cast<int>(logv.size());
//if(n<=1)
// cout<<"Warning in logsumexp"<<endl;
double max = *max_element(logv.begin(), logv.end());
double answer = 0;
// log(sum(exp(logf)) = log(sum(exp(logf - max(logf) + max(logf)))
// = max(logf) + log(sum(exp(logf - max(logf)))
for(int i=0; i<n; i++)
answer += exp(logv[i] - max);
answer = max + log(answer);
return answer;
}
double logsumexp(double a, double b)
{
double x[2] = {a,b};
return logsumexp(x, 2);
}
double logdiffexp(double a, double b)
{
if(a <= b)
cerr<<"# Error in logdiffexp."<<endl;
double biggest = a;
a -= biggest;
b -= biggest;
return log(exp(a) - exp(b)) + biggest;
}
| gpl-3.0 |
sumatrapdfreader/sumatrapdf | mupdf/source/fitz/draw-unpack.c | 1 | 12267 | // Copyright (C) 2004-2021 Artifex Software, Inc.
//
// This file is part of MuPDF.
//
// MuPDF is free software: you can redistribute it and/or modify it under the
// terms of the GNU Affero General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// MuPDF 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 Affero General Public License for more
// details.
//
// You should have received a copy of the GNU Affero General Public License
// along with MuPDF. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>
//
// Alternative licensing terms are available from the licensor.
// For commercial licensing, see <https://www.artifex.com/> or contact
// Artifex Software, Inc., 1305 Grant Avenue - Suite 200, Novato,
// CA 94945, U.S.A., +1(415)492-9861, for further information.
#include "mupdf/fitz.h"
#include "draw-imp.h"
#include <string.h>
/* Unpack image samples and optionally pad pixels with opaque alpha */
#define get1(buf,x) ((buf[x >> 3] >> ( 7 - (x & 7) ) ) & 1 )
#define get2(buf,x) ((buf[x >> 2] >> ( ( 3 - (x & 3) ) << 1 ) ) & 3 )
#define get4(buf,x) ((buf[x >> 1] >> ( ( 1 - (x & 1) ) << 2 ) ) & 15 )
#define get8(buf,x) (buf[x])
#define get16(buf,x) (buf[x << 1])
#define get24(buf,x) (buf[(x << 1) + x])
#define get32(buf,x) (buf[x << 2])
static unsigned char get1_tab_1[256][8];
static unsigned char get1_tab_1p[256][16];
static unsigned char get1_tab_255[256][8];
static unsigned char get1_tab_255p[256][16];
/*
Bug 697012 shows that the unpacking code can confuse valgrind due
to the use of undefined bits in the padding at the end of lines.
We unpack from bits to bytes by copying from a lookup table.
Valgrind is not capable of understanding that it doesn't matter
what the undefined bits are, as the bytes we copy that correspond
to the defined bits will always agree regardless of these
undefined bits by construction of the table.
We therefore have a VGMASK macro that explicitly masks off these
bits in PACIFY_VALGRIND builds.
*/
#ifdef PACIFY_VALGRIND
static const unsigned char mask[9] = { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
#define VGMASK(v,m) (v & mask[(m)])
#else
#define VGMASK(v,m) (v)
#endif
static void
init_get1_tables(void)
{
static int once = 0;
unsigned char bits[1];
int i, k, x;
/* TODO: mutex lock here */
if (once)
return;
for (i = 0; i < 256; i++)
{
bits[0] = i;
for (k = 0; k < 8; k++)
{
x = get1(bits, k);
get1_tab_1[i][k] = x;
get1_tab_1p[i][k * 2] = x;
get1_tab_1p[i][k * 2 + 1] = 255;
get1_tab_255[i][k] = x * 255;
get1_tab_255p[i][k * 2] = x * 255;
get1_tab_255p[i][k * 2 + 1] = 255;
}
}
once = 1;
}
static void
fz_unpack_mono_line_unscaled(unsigned char *dp, unsigned char *sp, int w, int n, int depth, int scale, int pad, int skip)
{
int w3 = w >> 3;
int x;
for (x = 0; x < w3; x++)
{
memcpy(dp, get1_tab_1[*sp++], 8);
dp += 8;
}
x = x << 3;
if (x < w)
memcpy(dp, get1_tab_1[VGMASK(*sp, w - x)], w - x);
}
static void
fz_unpack_mono_line_scaled(unsigned char *dp, unsigned char *sp, int w, int n, int depth, int scale, int pad, int skip)
{
int w3 = w >> 3;
int x;
for (x = 0; x < w3; x++)
{
memcpy(dp, get1_tab_255[*sp++], 8);
dp += 8;
}
x = x << 3;
if (x < w)
memcpy(dp, get1_tab_255[VGMASK(*sp, w - x)], w - x);
}
static void
fz_unpack_mono_line_unscaled_with_padding(unsigned char *dp, unsigned char *sp, int w, int n, int depth, int scale, int pad, int skip)
{
int w3 = w >> 3;
int x;
for (x = 0; x < w3; x++)
{
memcpy(dp, get1_tab_1p[*sp++], 16);
dp += 16;
}
x = x << 3;
if (x < w)
memcpy(dp, get1_tab_1p[VGMASK(*sp, w - x)], (w - x) << 1);
}
static void
fz_unpack_mono_line_scaled_with_padding(unsigned char *dp, unsigned char *sp, int w, int n, int depth, int scale, int pad, int skip)
{
int w3 = w >> 3;
int x;
for (x = 0; x < w3; x++)
{
memcpy(dp, get1_tab_255p[*sp++], 16);
dp += 16;
}
x = x << 3;
if (x < w)
memcpy(dp, get1_tab_255p[VGMASK(*sp, w - x)], (w - x) << 1);
}
static void
fz_unpack_line(unsigned char *dp, unsigned char *sp, int w, int n, int depth, int scale, int pad, int skip)
{
int len = w * n;
while (len--)
*dp++ = *sp++;
}
static void
fz_unpack_line_with_padding(unsigned char *dp, unsigned char *sp, int w, int n, int depth, int scale, int pad, int skip)
{
int x, k;
for (x = 0; x < w; x++)
{
for (k = 0; k < n; k++)
*dp++ = *sp++;
*dp++ = 255;
}
}
static void
fz_unpack_any_l2depth(unsigned char *dp, unsigned char *sp, int w, int n, int depth, int scale, int pad, int skip)
{
unsigned char *p = dp;
int b = 0;
int x, k;
for (x = 0; x < w; x++)
{
for (k = 0; k < n; k++)
{
switch (depth)
{
case 1: *p++ = get1(sp, b) * scale; break;
case 2: *p++ = get2(sp, b) * scale; break;
case 4: *p++ = get4(sp, b) * scale; break;
case 8: *p++ = get8(sp, b); break;
case 16: *p++ = get16(sp, b); break;
case 24: *p++ = get24(sp, b); break;
case 32: *p++ = get32(sp, b); break;
}
b++;
}
b += skip;
if (pad)
*p++ = 255;
}
}
typedef void (*fz_unpack_line_fn)(unsigned char *dp, unsigned char *sp, int w, int n, int depth, int scale, int pad, int skip);
void
fz_unpack_tile(fz_context *ctx, fz_pixmap *dst, unsigned char *src, int n, int depth, size_t stride, int scale)
{
unsigned char *sp = src;
unsigned char *dp = dst->samples;
fz_unpack_line_fn unpack_line = NULL;
int pad, y, skip;
int w = dst->w;
int h = dst->h;
pad = 0;
skip = 0;
if (dst->n > n)
pad = 255;
if (dst->n < n)
{
skip = n - dst->n;
n = dst->n;
}
if (depth == 1)
init_get1_tables();
if (scale == 0)
{
switch (depth)
{
case 1: scale = 255; break;
case 2: scale = 85; break;
case 4: scale = 17; break;
}
}
if (n == 1 && depth == 1 && scale == 1 && !pad && !skip)
unpack_line = fz_unpack_mono_line_unscaled;
else if (n == 1 && depth == 1 && scale == 255 && !pad && !skip)
unpack_line = fz_unpack_mono_line_scaled;
else if (n == 1 && depth == 1 && scale == 1 && pad && !skip)
unpack_line = fz_unpack_mono_line_unscaled_with_padding;
else if (n == 1 && depth == 1 && scale == 255 && pad && !skip)
unpack_line = fz_unpack_mono_line_scaled_with_padding;
else if (depth == 8 && !pad && !skip)
unpack_line = fz_unpack_line;
else if (depth == 8 && pad && !skip)
unpack_line = fz_unpack_line_with_padding;
else if (depth == 1 || depth == 2 || depth == 4 || depth == 8 || depth == 16 || depth == 24 || depth == 32)
unpack_line = fz_unpack_any_l2depth;
if (unpack_line)
{
for (y = 0; y < h; y++, sp += stride, dp += dst->stride)
unpack_line(dp, sp, w, n, depth, scale, pad, skip);
}
else if (depth > 0 && depth <= 8 * (int)sizeof(int))
{
fz_stream *stm;
int x, k;
size_t skipbits = 8 * stride - (size_t)w * n * depth;
if (skipbits > 32)
fz_throw(ctx, FZ_ERROR_GENERIC, "Inappropriate stride!");
stm = fz_open_memory(ctx, sp, h * stride);
fz_try(ctx)
{
for (y = 0; y < h; y++)
{
for (x = 0; x < w; x++)
{
for (k = 0; k < n; k++)
{
if (depth <= 8)
*dp++ = fz_read_bits(ctx, stm, depth) << (8 - depth);
else
*dp++ = fz_read_bits(ctx, stm, depth) >> (depth - 8);
}
if (pad)
*dp++ = 255;
}
dp += dst->stride - (size_t)w * (n + (pad > 0));
(void) fz_read_bits(ctx, stm, (int)skipbits);
}
}
fz_always(ctx)
fz_drop_stream(ctx, stm);
fz_catch(ctx)
fz_rethrow(ctx);
}
else
fz_throw(ctx, FZ_ERROR_GENERIC, "cannot unpack tile with %d bits per component", depth);
}
/* Apply decode array */
void
fz_decode_indexed_tile(fz_context *ctx, fz_pixmap *pix, const float *decode, int maxval)
{
int add[FZ_MAX_COLORS];
int mul[FZ_MAX_COLORS];
unsigned char *p = pix->samples;
size_t stride = pix->stride - pix->w * (size_t)pix->n;
int len;
int pn = pix->n;
int n = pn - pix->alpha;
int needed;
int k;
int h;
needed = 0;
for (k = 0; k < n; k++)
{
int min = decode[k * 2] * 256;
int max = decode[k * 2 + 1] * 256;
add[k] = min;
mul[k] = (max - min) / maxval;
needed |= min != 0 || max != maxval * 256;
}
if (!needed)
return;
h = pix->h;
while (h--)
{
len = pix->w;
while (len--)
{
for (k = 0; k < n; k++)
{
int value = (add[k] + (((p[k] << 8) * mul[k]) >> 8)) >> 8;
p[k] = fz_clampi(value, 0, 255);
}
p += pn;
}
p += stride;
}
}
void
fz_decode_tile(fz_context *ctx, fz_pixmap *pix, const float *decode)
{
int add[FZ_MAX_COLORS];
int mul[FZ_MAX_COLORS];
unsigned char *p = pix->samples;
size_t stride = pix->stride - pix->w * (size_t)pix->n;
int len;
int n = fz_maxi(1, pix->n - pix->alpha);
int k;
int h;
for (k = 0; k < n; k++)
{
int min = decode[k * 2] * 255;
int max = decode[k * 2 + 1] * 255;
add[k] = min;
mul[k] = max - min;
}
h = pix->h;
while (h--)
{
len = pix->w;
while (len--)
{
for (k = 0; k < n; k++)
{
int value = add[k] + fz_mul255(p[k], mul[k]);
p[k] = fz_clampi(value, 0, 255);
}
p += pix->n;
}
p += stride;
}
}
typedef struct
{
fz_stream *src;
int depth;
int w;
int h;
int n;
int skip;
int pad;
int scale;
int src_stride;
int dst_stride;
fz_unpack_line_fn unpack;
unsigned char buf[1];
} unpack_state;
static int
unpack_next(fz_context *ctx, fz_stream *stm, size_t max)
{
unpack_state *state = (unpack_state *)stm->state;
size_t n = state->src_stride;
stm->rp = state->buf;
do
{
size_t a = fz_available(ctx, state->src, n);
if (a == 0)
return EOF;
if (a > n)
a = n;
memcpy(stm->rp, state->src->rp, a);
stm->rp += a;
state->src->rp += a;
n -= a;
}
while (n);
state->h--;
stm->pos += state->dst_stride;
stm->wp = stm->rp + state->dst_stride;
state->unpack(stm->rp, state->buf, state->w, state->n, state->depth, state->scale, state->pad, state->skip);
return *stm->rp++;
}
static void
unpack_drop(fz_context *ctx, void *state)
{
fz_free(ctx, state);
}
fz_stream *
fz_unpack_stream(fz_context *ctx, fz_stream *src, int depth, int w, int h, int n, int indexed, int pad, int skip)
{
int src_stride = (w*depth*n+7)>>3;
int dst_stride;
unpack_state *state;
fz_unpack_line_fn unpack_line = NULL;
int scale = 1;
if (depth == 1)
init_get1_tables();
if (!indexed)
switch (depth)
{
case 1: scale = 255; break;
case 2: scale = 85; break;
case 4: scale = 17; break;
}
dst_stride = w * (n + !!pad);
if (n == 1 && depth == 1 && scale == 1 && !pad && !skip)
unpack_line = fz_unpack_mono_line_unscaled;
else if (n == 1 && depth == 1 && scale == 255 && !pad && !skip)
unpack_line = fz_unpack_mono_line_scaled;
else if (n == 1 && depth == 1 && scale == 1 && pad && !skip)
unpack_line = fz_unpack_mono_line_unscaled_with_padding;
else if (n == 1 && depth == 1 && scale == 255 && pad && !skip)
unpack_line = fz_unpack_mono_line_scaled_with_padding;
else if (depth == 8 && !pad && !skip)
unpack_line = fz_unpack_line;
else if (depth == 8 && pad && !skip)
unpack_line = fz_unpack_line_with_padding;
else if (depth == 1 || depth == 2 || depth == 4 || depth == 8 || depth == 16 || depth == 24 || depth == 32)
unpack_line = fz_unpack_any_l2depth;
else
fz_throw(ctx, FZ_ERROR_GENERIC, "Unsupported combination in fz_unpack_stream");
state = fz_malloc(ctx, sizeof(unpack_state) + dst_stride + src_stride);
state->src = src;
state->depth = depth;
state->w = w;
state->h = h;
state->n = n;
state->skip = skip;
state->pad = pad;
state->scale = scale;
state->unpack = unpack_line;
state->src_stride = src_stride;
state->dst_stride = dst_stride;
return fz_new_stream(ctx, state, unpack_next, unpack_drop);
}
| gpl-3.0 |
lubgr/tsym | unit-tests/testprinter.cpp | 1 | 16133 |
#include "constant.h"
#include "fixtures.h"
#include "numeric.h"
#include "plaintextprintengine.h"
#include "power.h"
#include "printer.h"
#include "product.h"
#include "sum.h"
#include "symbol.h"
#include "trigonometric.h"
#include "tsymtests.h"
using namespace tsym;
struct PrinterFixture : public AbcFixture {
std::stringstream stream;
template <class Engine, class T> std::string print(Engine& engine, const T& toBePrinted)
{
tsym::print(engine, toBePrinted);
return stream.str();
}
template <class T> std::string print(const T& toBePrinted)
{
PlaintextPrintEngine engine(stream);
return print(engine, toBePrinted);
}
std::string printDebug(const BasePtr& toBePrinted)
{
PlaintextPrintEngine engine(stream);
tsym::printDebug(engine, *toBePrinted);
return stream.str();
}
};
BOOST_FIXTURE_TEST_SUITE(TestPrinter, PrinterFixture)
BOOST_AUTO_TEST_CASE(positiveIntNumber)
{
BOOST_CHECK_EQUAL("5", print(*five));
}
BOOST_AUTO_TEST_CASE(negativeIntNumber)
{
BOOST_CHECK_EQUAL("-5", print(-5));
}
BOOST_AUTO_TEST_CASE(doubleNumber)
{
BOOST_CHECK_EQUAL("0.123456", print(0.123456));
}
BOOST_AUTO_TEST_CASE(fractionNumber)
{
BOOST_CHECK_EQUAL("2/33", print(Number(2, 33)));
}
BOOST_AUTO_TEST_CASE(operatorWithNumber)
{
const Number frac(-4, 17);
stream << frac;
BOOST_CHECK_EQUAL("-4/17", stream.str());
}
BOOST_AUTO_TEST_CASE(piUnicode)
{
const std::string expected =
#ifndef TSYM_ASCII_ONLY
"\u03c0";
#else
"pi";
#endif
BOOST_CHECK_EQUAL(expected, print(*pi));
}
BOOST_AUTO_TEST_CASE(piAscii)
{
PlaintextPrintEngine engine(stream, PlaintextPrintEngine::CharSet::ASCII);
BOOST_CHECK_EQUAL("pi", print(engine, *pi));
}
BOOST_AUTO_TEST_CASE(euler)
{
BOOST_CHECK_EQUAL("e", print(*Constant::createE()));
}
BOOST_AUTO_TEST_CASE(function)
{
BOOST_CHECK_EQUAL("sin(a)", print(*Trigonometric::createSin(a)));
}
BOOST_AUTO_TEST_CASE(functionWithMoreThanOneArgument)
{
const BasePtr atan2 = Trigonometric::createAtan2(Product::create(two, a), b);
BOOST_CHECK_EQUAL("atan2(2*a, b)", print(*atan2));
}
BOOST_AUTO_TEST_CASE(symbol)
{
const std::string name("abcde");
BOOST_CHECK_EQUAL(name, print(*Symbol::create(name)));
}
BOOST_AUTO_TEST_CASE(positiveSymbol)
{
const BasePtr aPos = Symbol::createPositive("a");
BOOST_CHECK_EQUAL("a", print(*aPos));
}
BOOST_AUTO_TEST_CASE(positiveSymbolWithSubAndSuperscript)
{
const std::string expected = "a_b^c";
const Name name{"a", "b", "c"};
const BasePtr aPos = Symbol::createPositive(name);
BOOST_CHECK_EQUAL(expected, print(*aPos));
}
BOOST_AUTO_TEST_CASE(positiveSymbolAsciiCharset)
{
PlaintextPrintEngine engine(stream, PlaintextPrintEngine::CharSet::ASCII);
const BasePtr aPos = Symbol::createPositive("a");
BOOST_CHECK_EQUAL("a", print(engine, *aPos));
}
BOOST_AUTO_TEST_CASE(symbolGreekLetterWithoutUnicode)
{
const std::string name("omega");
const BasePtr omega = Symbol::create(name);
PlaintextPrintEngine engine(stream, PlaintextPrintEngine::CharSet::ASCII);
BOOST_CHECK_EQUAL(name, print(engine, *omega));
}
BOOST_AUTO_TEST_CASE(symbolGreekLetterWithUnicode)
{
const std::string expected =
#ifndef TSYM_ASCII_ONLY
"\u03C9";
#else
"omega";
#endif
const BasePtr omega = Symbol::create("omega");
BOOST_CHECK_EQUAL(expected, print(*omega));
}
BOOST_AUTO_TEST_CASE(capitalOmega)
{
const std::string expected =
#ifndef TSYM_ASCII_ONLY
"\u03a9";
#else
"Omega";
#endif
const BasePtr omega = Symbol::create("Omega");
BOOST_CHECK_EQUAL(expected, print(*omega));
}
BOOST_AUTO_TEST_CASE(lowerCaseAlpha)
{
const std::string expected =
#ifndef TSYM_ASCII_ONLY
"\u03B1";
#else
"alpha";
#endif
const BasePtr alpha = Symbol::create("alpha");
BOOST_CHECK_EQUAL(expected, print(*alpha));
}
BOOST_AUTO_TEST_CASE(upperCaseAlpha)
{
const std::string expected =
#ifndef TSYM_ASCII_ONLY
"\u0391";
#else
"Alpha";
#endif
const BasePtr capitalAlpha = Symbol::create("Alpha");
BOOST_CHECK_EQUAL(expected, print(*capitalAlpha));
}
BOOST_AUTO_TEST_CASE(sumWithFunction)
{
const BasePtr sum = Sum::create(a, Trigonometric::createTan(c), Trigonometric::createAcos(b));
BOOST_CHECK_EQUAL("a + acos(b) + tan(c)", print(*sum));
}
BOOST_AUTO_TEST_CASE(product)
{
const BasePtr product = Product::create(a, b, c, d);
BOOST_CHECK_EQUAL("a*b*c*d", print(*product));
}
BOOST_AUTO_TEST_CASE(negSymbolAsProduct)
{
BOOST_CHECK_EQUAL("-a", print(*Product::minus(a)));
}
BOOST_AUTO_TEST_CASE(powerOfSymbolAndPositiveInteger)
{
const BasePtr pow = Power::create(a, two);
BOOST_CHECK_EQUAL("a^2", print(*pow));
}
BOOST_AUTO_TEST_CASE(powerOfSymbolAndNegInt)
{
const BasePtr pow = Power::create(a, Numeric::create(-3));
BOOST_CHECK_EQUAL("1/a^3", print(*pow));
}
BOOST_AUTO_TEST_CASE(powerOfSymbolAndMinusOne)
{
const BasePtr pow = Power::create(a, Numeric::mOne());
BOOST_CHECK_EQUAL("1/a", print(*pow));
}
BOOST_AUTO_TEST_CASE(powerOfSymbolAndMinusOneDebugPrint)
{
const BasePtr pow = Power::create(a, Numeric::mOne());
BOOST_CHECK_EQUAL("a^(-1)", printDebug(pow));
}
BOOST_AUTO_TEST_CASE(powerOfProductAndMinusOne)
{
const BasePtr pow = Power::create(Product::create(two, a, b), Numeric::mOne());
BOOST_CHECK_EQUAL("1/(2*a*b)", print(*pow));
}
BOOST_AUTO_TEST_CASE(powerOfPowerOfPowerOfPower)
{
const BasePtr pow1 = Power::create(a, b);
const BasePtr pow2 = Power::create(pow1, c);
const BasePtr pow3 = Power::create(pow2, Product::create(Numeric::create(-1, 4), a));
const BasePtr pow4 = Power::create(pow3, d);
BOOST_CHECK_EQUAL("(((a^b)^c)^(-1/4*a))^d", print(*pow4));
}
BOOST_AUTO_TEST_CASE(omitFirstNumeratorFactorIfOne)
{
const BasePtr product = Product::create(c, Power::create(Product::create(two, a, b), Numeric::mOne()));
BOOST_CHECK_EQUAL("c/(2*a*b)", print(*product));
}
BOOST_AUTO_TEST_CASE(omitFirstNumeratorFactorIfMinusOne)
{
const BasePtr product = Product::minus(c, Power::create(Product::create(two, a, b), Numeric::mOne()));
BOOST_CHECK_EQUAL("-c/(2*a*b)", print(*product));
}
BOOST_AUTO_TEST_CASE(powerOfSymbolAndPosFrac)
{
const BasePtr pow = Power::create(a, Numeric::fourth());
BOOST_CHECK_EQUAL("a^(1/4)", print(*pow));
}
BOOST_AUTO_TEST_CASE(sqrtPower)
{
const BasePtr pow = Power::sqrt(Product::create(a, b));
BOOST_CHECK_EQUAL("sqrt(a*b)", print(*pow));
}
BOOST_AUTO_TEST_CASE(oneOverSqrtPowerDebugPrint)
{
const BasePtr exp = Numeric::create(-1, 2);
const BasePtr product = Product::create(Power::create(a, exp), Power::create(b, exp));
BOOST_CHECK_EQUAL("a^(-1/2)*b^(-1/2)", printDebug(product));
}
BOOST_AUTO_TEST_CASE(oneOverSqrtPower)
{
const BasePtr exp = Numeric::create(-1, 2);
const BasePtr product = Product::create(Power::create(a, exp), Power::create(b, exp));
BOOST_CHECK_EQUAL("1/(sqrt(a)*sqrt(b))", print(*product));
}
BOOST_AUTO_TEST_CASE(powerOfSymbolAndNegFracDebugPrint)
{
const BasePtr pow = Power::create(a, Numeric::create(-2, 3));
BOOST_CHECK_EQUAL("a^(-2/3)", printDebug(pow));
}
BOOST_AUTO_TEST_CASE(powerOfSymbolAndNegFrac)
{
const BasePtr pow = Power::create(a, Numeric::create(-2, 3));
BOOST_CHECK_EQUAL("1/a^(2/3)", print(*pow));
}
BOOST_AUTO_TEST_CASE(powerOfFraction)
{
const BasePtr n = Numeric::create(5, 7);
const BasePtr pow = Power::create(n, a);
BOOST_CHECK_EQUAL("(5/7)^a", print(*pow));
}
BOOST_AUTO_TEST_CASE(powerWithPiBase)
{
const std::string expected =
#ifndef TSYM_ASCII_ONLY
"\u03c0^(a + b)";
#else
"pi^(a + b)";
#endif
const BasePtr pow = Power::create(pi, Sum::create(a, b));
BOOST_CHECK_EQUAL(expected, print(*pow));
}
BOOST_AUTO_TEST_CASE(powerWithPiExp)
{
const std::string expected =
#ifndef TSYM_ASCII_ONLY
"(a + b)^\u03c0";
#else
"(a + b)^pi";
#endif
const BasePtr pow = Power::create(Sum::create(a, b), pi);
BOOST_CHECK_EQUAL(expected, print(*pow));
}
BOOST_AUTO_TEST_CASE(powerOfSymbolAndSymbol)
{
const BasePtr pow = Power::create(a, b);
BOOST_CHECK_EQUAL("a^b", print(*pow));
}
BOOST_AUTO_TEST_CASE(powerOfSumAndNumber)
{
const BasePtr sum = Sum::create(a, b);
const BasePtr pow = Power::create(sum, two);
BOOST_CHECK_EQUAL("(a + b)^2", print(*pow));
}
BOOST_AUTO_TEST_CASE(powerOfNumberAndSum)
{
const BasePtr sum = Sum::create(a, b);
const BasePtr pow = Power::create(two, sum);
BOOST_CHECK_EQUAL("2^(a + b)", print(*pow));
}
BOOST_AUTO_TEST_CASE(powerOfFunctionAndNumber)
{
const BasePtr pow = Power::create(Trigonometric::createSin(a), two);
BOOST_CHECK_EQUAL("sin(a)^2", print(*pow));
}
BOOST_AUTO_TEST_CASE(powerOfSumAndFunction)
{
const BasePtr sum = Sum::create(two, b, Trigonometric::createSin(a));
const BasePtr pow = Power::create(sum, Trigonometric::createAsin(Numeric::create(1, 5)));
BOOST_CHECK_EQUAL("(2 + b + sin(a))^asin(1/5)", print(*pow));
}
BOOST_AUTO_TEST_CASE(powerOfProductAndNumber)
{
const BasePtr product = Product::create(a, b);
const BasePtr pow = Power::create(product, two);
BOOST_CHECK_EQUAL("a^2*b^2", print(*pow));
}
BOOST_AUTO_TEST_CASE(powerOfProductAndNegNumber)
{
const BasePtr product = Product::create(a, b);
const BasePtr pow = Power::create(product, Numeric::create(-2));
BOOST_CHECK_EQUAL("1/(a^2*b^2)", print(*pow));
}
BOOST_AUTO_TEST_CASE(powerOfProductAndNegNumberDebugPrint)
{
const BasePtr product = Product::create(a, b);
const BasePtr pow = Power::create(product, Numeric::create(-4));
BOOST_CHECK_EQUAL("a^(-4)*b^(-4)", printDebug(pow));
}
BOOST_AUTO_TEST_CASE(largeProductOfPowers)
{
const BasePtr product = Product::create(
{a, b, Sum::create(a, c), Power::create(f, a), Power::oneOver(d), Power::create(e, Numeric::create(-2))});
BOOST_CHECK_EQUAL("a*b*(a + c)*f^a/(d*e^2)", print(*product));
}
BOOST_AUTO_TEST_CASE(largeProductOfPowersDebugPrint)
{
const BasePtr product = Product::create(
{a, b, Sum::create(a, c), Power::create(f, a), Power::oneOver(d), Power::create(e, Numeric::create(-2))});
BOOST_CHECK_EQUAL("a*b*(a + c)*d^(-1)*e^(-2)*f^a", printDebug(product));
}
BOOST_AUTO_TEST_CASE(simpleDivisionOfSymbols)
{
const BasePtr product = Product::create(a, Power::oneOver(b));
BOOST_CHECK_EQUAL("a/b", print(*product));
}
BOOST_AUTO_TEST_CASE(simpleDivisionOfSymbolsDebugPrint)
{
const BasePtr product = Product::create(a, Power::oneOver(b));
BOOST_CHECK_EQUAL("a*b^(-1)", printDebug(product));
}
BOOST_AUTO_TEST_CASE(negProductFactorMinusOne)
{
const BasePtr product = Product::minus(a, b);
BOOST_CHECK_EQUAL("-a*b", print(*product));
}
BOOST_AUTO_TEST_CASE(negProductNonTrivialFactor)
{
const BasePtr product = Product::create(a, b, Numeric::create(-2));
BOOST_CHECK_EQUAL("-2*a*b", print(*product));
}
BOOST_AUTO_TEST_CASE(productWithConstantPi)
{
const std::string expected =
#ifndef TSYM_ASCII_ONLY
"-2*\u03c0*a*b";
#else
"-2*pi*a*b";
#endif
const BasePtr product = Product::create({Numeric::create(-2), a, b, pi});
BOOST_CHECK_EQUAL(expected, print(*product));
}
BOOST_AUTO_TEST_CASE(productOfEqualExpPowers)
{
const BasePtr product = Product::create(Power::sqrt(a), Power::sqrt(b));
BOOST_CHECK_EQUAL("sqrt(a)*sqrt(b)", print(*product));
}
BOOST_AUTO_TEST_CASE(negProductOfEqualExpPowers)
{
const BasePtr exp = Numeric::create(2, 3);
const BasePtr product = Product::create({Numeric::mOne(), Power::create(a, exp), Power::create(b, exp)});
BOOST_CHECK_EQUAL("-a^(2/3)*b^(2/3)", print(*product));
}
BOOST_AUTO_TEST_CASE(productOfFunctions)
{
BasePtrList fac;
fac.push_back(a);
fac.push_back(Trigonometric::createAtan(Power::create(Numeric::create(17), Numeric::create(-1, 2))));
fac.push_back(Trigonometric::createCos(Product::create(c, d)));
fac.push_back(Power::create(Trigonometric::createSin(Product::create(a, b)), two));
fac.push_back(Trigonometric::createTan(Product::create(a, b)));
const BasePtr product = Product::create(fac);
BOOST_CHECK_EQUAL("a*atan(1/sqrt(17))*cos(c*d)*sin(a*b)^3/cos(a*b)", print(*product));
}
BOOST_AUTO_TEST_CASE(productOfFunctionsDebugPrint)
{
BasePtrList fac;
fac.push_back(a);
fac.push_back(Trigonometric::createAtan(Power::create(Numeric::create(17), Numeric::create(-1, 2))));
fac.push_back(Trigonometric::createCos(Product::create(c, d)));
fac.push_back(Power::create(Trigonometric::createSin(Product::create(a, b)), two));
fac.push_back(Trigonometric::createTan(Product::create(a, b)));
const BasePtr product = Product::create(fac);
BOOST_CHECK_EQUAL("a*atan(17^(-1/2))*cos(a*b)^(-1)*cos(c*d)*sin(a*b)^3", printDebug(product));
}
BOOST_AUTO_TEST_CASE(fracOfSumAndProduct)
{
const BasePtr sum = Sum::create(a, b);
const BasePtr product = Product::create(c, d);
const BasePtr frac = Product::create(sum, Power::oneOver(product));
BOOST_CHECK_EQUAL("(a + b)/(c*d)", print(*frac));
}
BOOST_AUTO_TEST_CASE(fracOfTwoProducts)
{
const BasePtr prod1 = Product::create(a, b);
const BasePtr prod2 = Product::create(c, d);
const BasePtr frac = Product::create(prod1, Power::oneOver(prod2));
BOOST_CHECK_EQUAL("a*b/(c*d)", print(*frac));
}
BOOST_AUTO_TEST_CASE(fracOfPowerAndSum)
{
const BasePtr pow = Power::create(a, b);
const BasePtr sum = Sum::create(c, d);
const BasePtr frac = Product::create(pow, Power::oneOver(sum));
BOOST_CHECK_EQUAL("a^b/(c + d)", print(*frac));
}
BOOST_AUTO_TEST_CASE(negTermsInSum)
{
const BasePtr sum = Sum::create(a, Product::minus(b));
BOOST_CHECK_EQUAL("a - b", print(*sum));
}
BOOST_AUTO_TEST_CASE(posProductInSum)
{
const BasePtr sum = Sum::create(a, Product::create(b, c));
BOOST_CHECK_EQUAL("a + b*c", print(*sum));
}
BOOST_AUTO_TEST_CASE(negSumInProduct)
{
const BasePtr product = Product::create(a, Sum::create(b, c));
BOOST_CHECK_EQUAL("a*(b + c)", print(*product));
}
BOOST_AUTO_TEST_CASE(posSumInProduct)
{
const BasePtr product = Product::create(a, Sum::create(Product::minus(b), c));
BOOST_CHECK_EQUAL("a*(-b + c)", print(*product));
}
BOOST_AUTO_TEST_CASE(negativePowerWithConstantBase)
{
const BasePtr exp = Numeric::create(-123);
const BasePtr product = Product::minus(Power::create(Constant::createE(), exp));
const std::string result = print(*product);
BOOST_CHECK_EQUAL("-1/e^123", result);
}
BOOST_AUTO_TEST_CASE(negativePowerWithConstantBaseDebug)
{
const BasePtr exp = Numeric::create(-123);
const BasePtr product = Product::minus(Power::create(Constant::createE(), exp));
BOOST_CHECK_EQUAL("-e^(-123)", printDebug(product));
}
BOOST_AUTO_TEST_CASE(parenthesesInPosProductWithNegSumFactor)
{
const BasePtr product = Product::create(c, Sum::create(Product::minus(a), Numeric::create(-3)));
const std::string result = print(*product);
BOOST_CHECK_EQUAL("(-3 - a)*c", result);
}
BOOST_AUTO_TEST_CASE(parenthesesInNegProductWithSumFactor)
{
const BasePtr product = Product::minus(c, Sum::create(Product::minus(a), Numeric::create(-3)));
const std::string result = print(*product);
BOOST_CHECK_EQUAL("-(-3 - a)*c", result);
}
BOOST_AUTO_TEST_CASE(parenthesesInNegProductWithSumFactorInsideSum)
{
const BasePtr sum = Sum::create(a, Product::minus(c, Sum::create(Product::minus(a), Numeric::create(-3))));
const std::string result = print(*sum);
BOOST_CHECK_EQUAL("a - (-3 - a)*c", result);
}
BOOST_AUTO_TEST_CASE(parenthesesInNegProductWithSumFactorInsideLargerSum)
{
const BasePtr mThree = Numeric::create(-3);
const BasePtr sum = Sum::create(b, Product::create(mThree, c), Product::minus(a, c),
Product::create(Numeric::mOne(), Sum::create(mThree, Product::minus(a)), c));
const std::string result = print(*sum);
BOOST_CHECK_EQUAL("b - 3*c - a*c - (-3 - a)*c", result);
}
BOOST_AUTO_TEST_SUITE_END()
| gpl-3.0 |
guillermofarina/lognotify | lognotifyserv/src/lognotifyserv.cpp | 1 | 4464 | /*
* Lognotify - Monitorización de ficheros de registro en GNU/Linux con notificaciones de escritorio
* Autor: Guillermo Fariña Arroyo
* C++11 (ISO/IEC 14882:2011)
*/
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <regex>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "servidor_de_notificaciones.h"
using namespace std;
using namespace lognotify;
/**
* Punto de entrada de la aplicación servidora de Lognotify
* @param argc Número de parámetros pasados por línea de comandos al ejecutar la aplicación
* @param argv Lista de parámetros pasados por línea de comandos al ejecutar la aplicación
*/
int main (int argc, char** argv)
{
//Se inicializan los valores por defecto de las opciones de ejecución
bool demonio = false;
unsigned short puerto = 0;
string ruta_ficheros = "$HOME/.lognotify";
string ruta_registro = "/var/log";
bool mostrar_ayuda = false;
bool error_parametros = false;
//Se procesan los parámetros de línea de comandos
opterr = 0;
int opcion = 0;
while ((opcion = getopt(argc, argv, "dp:f:w:h")) != -1)
{
switch (opcion)
{
case 'd':
demonio = true;
break;
case 'p':
if ((atoi(optarg) > 0) && (atoi(optarg) < USHRT_MAX)) puerto = (unsigned short) atoi(optarg);
else error_parametros = true;
break;
case 'f':
ruta_ficheros = optarg;
break;
case 'w':
ruta_registro = optarg;
break;
case 'h':
mostrar_ayuda = true;
break;
case '?':
error_parametros = true;
break;
case ':':
error_parametros = true;
break;
default:
return -1;
}
}
if (optind < argc) error_parametros = true;
if (puerto == 0) error_parametros = true;
//Si ha habido errores o se ha pedido la ayuda, se muestra en pantalla y se termina
if (error_parametros) cout << "El formato de los parámetros es incorrecto" << endl;
if (error_parametros || mostrar_ayuda)
{
cout << "La aplicación lognotifyserv soporta los siguientes parámetros:" << endl;
cout << "-p Especificar puerto TCP (este parámetro es necesario para ejecutar)" << endl;
cout << "-d Ejecutar lognotifyserv como demonio" << endl;
cout << "-f Especificar ruta alternativa a $HOME/.lognotify (ej. -f /mis/ficheros)" << endl;
cout << "-w Especificar ruta alternativa a /var/log (ej. -w /mis/logs)" << endl;
cout << "-h Mostrar ayuda de ejecución de lognotifyserv (no se ejecutará el programa)" << endl;
return 0;
}
//Si se ha pedido ejecutar el programa como demonio, se realiza el proceso correspondiente
if (demonio)
{
pid_t pid, sid;
//Fork del proceso padre
pid = fork();
if (pid < 0) return -1;
//Se termina el proceso padre
if (pid > 0) return 0;
//Se cambia la máscara de ficheros
umask(0);
//Se crea un nuevo ID de sesión para el proceso
sid = setsid();
if (sid < 0) return -1;
//Se cambia el directorio activo
if ((chdir("/")) < 0) return -1;
//Se cierran los descriptores de fichero estándar
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
}
//Se carga la lista de ficheros a monitorizar del fichero indicado
vector<string> ficheros;
ifstream fichero_ficheros_registro;
string linea;
fichero_ficheros_registro.open(ruta_ficheros + "/ficheros");
if(!fichero_ficheros_registro.is_open())
{
if (!demonio) cout << "No se ha podido inicializar Lognotify. No se ha encontrado \'ficheros\' en la ubicación indicada, o ha sido imposible abrirlo";
return -1;
}
while (getline(fichero_ficheros_registro, linea))
{
//Si la linea contiene un fragmento de texto, se interpreta como el nombre de un fichero y se guarda
if (regex_match(linea, regex("[\\s\\t]*[^\\s\\t]+.*")))
{
ficheros.push_back(linea);
}
}
fichero_ficheros_registro.close();
//Se crea e inicializa una instancia de ServidorDeNotificaciones, poniéndola a hacer su función
ServidorDeNotificaciones servidor;
if (!servidor.inicializar(puerto, ruta_registro, ficheros))
{
if (!demonio) cout << "No se ha podido inicializar Lognotify. Es posible que no se haya proporcionado una lista de 1+ ficheros de registro que monitorizar en el fichero \"ficheros\" o que ninguno sea válido" << endl;
return -1;
}
servidor.darServicio();
return 0;
} | gpl-3.0 |
shakil113/Uva-onlineJudge-solve | UVA10465.c | 1 | 2281 | /*******************************************************************************
* Author: Nguyen Truong Duy
********************************************************************************/
/* Methodology:
* + We can solve this using Dynamic Programming
*
* + Let f(m, n, t) = the maximum number of burgers Hormer can eat without wasting
* any time if it takes m minutes to eat a burger of type I and n minutes
* to eat a burger of type II
* + Recurrence relation:
* f(m, n, t) = 0 if f(m, n, t - m) = f(m, n, t - n ) = 0
* f(m, n, t) = 1 + max(f(m, n, t - m), f(m, n, t - n))
* + Base case:
* f(m, n, m) = f(m, n, n) = 1
* f(m, n, t) = 0 if t <= 0
*
* + In this problem, if f(m, n, t) = 0, we must find the nearest x < t such that
* f(m, n, x) > 0. And the drinking time will be t - x.
* This can be done by a linear scan from t backwards.
*
* + Time complexity: O(T) where T is the total time.
*/
#include <stdio.h>
#define MAX_TIME 10000
void findMaxNumBurger(int totalTime, int timeTypeOne, int timeTypeTwo, int * maxNumBurger, int * drinkTime);
int main(void)
{
int totalTime, timeTypeOne, timeTypeTwo, drinkTime, maxNumBurger;
while(scanf("%d %d %d", &timeTypeOne, &timeTypeTwo, &totalTime) > 0)
{
findMaxNumBurger(totalTime, timeTypeOne, timeTypeTwo, &maxNumBurger, &drinkTime);
printf("%d", maxNumBurger);
if(drinkTime)
printf(" %d", drinkTime);
printf("\n");
}
return 0;
}
void findMaxNumBurger(int totalTime, int timeTypeOne, int timeTypeTwo, int * maxNumBurger, int * drinkTime)
{
int numBurger[MAX_TIME + 1] = {0};
numBurger[timeTypeOne] = 1;
numBurger[timeTypeTwo] = 1;
int time;
int maxPrevNumBurger;
for(time = 1; time <= totalTime; time++)
{
maxPrevNumBurger = 0;
if(time - timeTypeOne >= 0)
maxPrevNumBurger = numBurger[time - timeTypeOne];
if(time - timeTypeTwo >= 0 && maxPrevNumBurger < numBurger[time - timeTypeTwo])
maxPrevNumBurger = numBurger[time - timeTypeTwo];
if(maxPrevNumBurger)
numBurger[time] = 1 + maxPrevNumBurger;
}
for(time = totalTime; time >= 0; time--)
if(numBurger[time])
{
*maxNumBurger = numBurger[time];
*drinkTime = totalTime - time;
return;
}
/* In case he cannot eat any burger */
*maxNumBurger = 0;
*drinkTime = totalTime;
}
| gpl-3.0 |
pa23/biblref | sources/main.cpp | 1 | 1063 | /*
biblref
Creation of bibliographic references.
File: main.cpp
Copyright (C) 2012-2014 Artem Petrov <pa2311@gmail.com>
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 3 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 <QApplication>
#include <QTextCodec>
#include "mainwindow.h"
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
MainWindow w;
w.show();
return a.exec();
}
| gpl-3.0 |
ezc/m4 | lib/spawn_faction_adddup2.c | 1 | 1885 | /* Copyright (C) 2000 Free Software Foundation, Inc.
This file is part of the GNU C Library.
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 3 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 <config.h>
/* Specification. */
#include <spawn.h>
#include <errno.h>
#include <unistd.h>
#if !_LIBC
# define __sysconf(open_max) getdtablesize ()
#endif
#include "spawn_int.h"
/* Add an action to FILE-ACTIONS which tells the implementation to call
`dup2' for the given file descriptors during the `spawn' call. */
int
posix_spawn_file_actions_adddup2 (posix_spawn_file_actions_t *file_actions,
int fd, int newfd)
{
int maxfd = __sysconf (_SC_OPEN_MAX);
struct __spawn_action *rec;
/* Test for the validity of the file descriptor. */
if (fd < 0 || newfd < 0 || fd >= maxfd || newfd >= maxfd)
return EBADF;
/* Allocate more memory if needed. */
if (file_actions->_used == file_actions->_allocated
&& __posix_spawn_file_actions_realloc (file_actions) != 0)
/* This can only mean we ran out of memory. */
return ENOMEM;
/* Add the new value. */
rec = &file_actions->_actions[file_actions->_used];
rec->tag = spawn_do_dup2;
rec->action.dup2_action.fd = fd;
rec->action.dup2_action.newfd = newfd;
/* Account for the new entry. */
++file_actions->_used;
return 0;
}
| gpl-3.0 |
dcf21/meteor-pi | archive/20150309_observe/src/observe.c | 2 | 15880 | // observe.c
// $Id$
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <unistd.h>
#include "asciidouble.h"
#include "v4l2uvc.h"
#include "tools.h"
#include "color.h"
#include "error.h"
#include "JulianDate.h"
#include "settings.h"
// When testTrigger detects a meteor, this string is set to a filename stub with time stamp of the time when the camera triggered
static char triggerstub[4096];
// Generate a filename stub with a timestamp. Warning: not thread safe. Returns a pointer to static string
char *fNameGenerate(char *tag)
{
static char path[4096], output[4096];
const int t = time(NULL);
const double JD = t / 86400.0 + 2440587.5;
int year,month,day,hour,min,status; double sec;
InvJulianDay(JD-0.5,&year,&month,&day,&hour,&min,&sec,&status,output); // Subtract 0.5 from Julian Day as we want days to start at noon, not midnight
sprintf(path,"%s/%04d%02d%02d", OUTPUT_PATH, year, month, day);
sprintf(output, "mkdir -p %s", path); status=system(output);
InvJulianDay(JD,&year,&month,&day,&hour,&min,&sec,&status,output);
sprintf(output,"%s/%04d%02d%02d%02d%02d%02d_%s", path, year, month, day, hour, min, (int)sec, tag);
return output;
}
// Used by testTrigger. When blocks idOld and idNew are determined to be connected, their pixels counts are added together.
inline void triggerBlocksMerge(int *triggerBlock, int *triggerMap, int len, int idOld, int idNew)
{
int i;
if (idOld==idNew) return;
for (i=0;i<len;i++) if (triggerMap[i]==idOld) triggerMap[i]=idNew;
triggerBlock[idNew]+=triggerBlock[idOld];
return;
}
// Test stacked images B and A, to see if pixels have brightened in B versus A. Image arrays contain the sum of <coAddedFrames> frames.
int testTrigger(const int width, const int height, const int *imageB, const int *imageA, const int coAddedFrames)
{
int x,y,d;
int output=0;
const int marginL=12; // Ignore pixels within this distance of the edge
const int marginR=19;
const int marginT= 8;
const int marginB=19;
const int Npixels=30; // To trigger this number of pixels connected together must have brightened
const int radius=8; // Pixel must be brighter than test pixels this distance away
const int threshold=13*coAddedFrames; // Pixel must have brightened by at least 8.
const int frameSize=width*height;
int *triggerMap = calloc(1,frameSize*sizeof(int)); // triggerMap is a 2D array of ints used to mark out pixels which have brightened suspiciously.
int *triggerBlock = calloc(1,frameSize*sizeof(int)); // triggerBlock is a count of how many pixels are in each numbered connected block
unsigned char *triggerR = calloc(1,frameSize);
unsigned char *triggerG = calloc(1,frameSize); // These arrays are used to produce diagnostic images when the camera triggers
unsigned char *triggerB = calloc(1,frameSize);
int blockNum = 1;
for (y=marginB; y<height-marginT; y++)
for (x=marginR;x<width-marginL; x++)
{
const int o=x+y*width;
triggerR[o] = CLIP256( 128+(imageB[o]-imageA[o])*256/threshold ); // RED channel - difference between images B and A
triggerG[o] = CLIP256( imageB[o] / coAddedFrames ); // GRN channel - a copy of image B
if (imageB[o]-imageA[o]>threshold) // Search for pixels which have brightened by more than threshold since past image
{
int i,j,c=0; // Make a 3x3 grid of pixels of pixels at a spacing of radius pixels. This pixel must be brighter than 6/9 of these pixels were
for (i=-1;i<=1;i++) for (j=-1;j<=1;j++) if (imageB[o]-imageA[o+(j+i*width)*radius]>threshold) c++;
if (c>7)
{
int i,j,c=0; // Make a 3x3 grid of pixels of pixels at a spacing of radius pixels. This pixel must be brighter than 6/9 of these pixels were
for (i=-1;i<=1;i++) for (j=-1;j<=1;j++) if (imageB[o]-imageB[o+(j+i*width)*radius]>threshold) c++;
if (c>6)
{
// Put triggering pixel on map. Wait till be have <Npixels> connected pixels.
triggerB[o] = 128;
int blockId=0;
if (triggerMap[o-1 ]) { if (!blockId) { blockId=triggerMap[o-1 ]; } else { triggerBlocksMerge(triggerBlock, triggerMap+(y-1)*width, width*2, triggerMap[o-1 ], blockId); } }
if (triggerMap[o+1-width]) { if (!blockId) { blockId=triggerMap[o+1-width]; } else { triggerBlocksMerge(triggerBlock, triggerMap+(y-1)*width, width*2, triggerMap[o+1-width], blockId); } }
if (triggerMap[o-width ]) { if (!blockId) { blockId=triggerMap[o-width ]; } else { triggerBlocksMerge(triggerBlock, triggerMap+(y-1)*width, width*2, triggerMap[o-width ], blockId); } }
if (triggerMap[o-1-width]) { if (!blockId) { blockId=triggerMap[o-1-width]; } else { triggerBlocksMerge(triggerBlock, triggerMap+(y-1)*width, width*2, triggerMap[o-1-width], blockId); } }
if (blockId==0 ) blockId=blockNum++;
triggerBlock[blockId]++;
triggerMap[o] = blockId;
if (triggerBlock[blockId]>Npixels)
{
triggerB[o]=255;
if (DEBUG && !output) { sprintf(temp_err_string, "Camera has triggered at (%d,%d).",width-x,height-y); gnom_log(temp_err_string); }
output=1; // We have triggered!
}
}
}
}
}
// If we have triggered, produce a diagnostic map of why. NB: This step is also necessary to set <triggerstub>.
if (output)
{
strcpy(triggerstub, fNameGenerate("trigger"));
char fname[4096];
sprintf(fname, "%s%s",triggerstub,"_MAP.rgb");
dumpFrameRGB(width, height, triggerR, triggerG, triggerB, fname);
}
free(triggerMap); free(triggerBlock); free(triggerR); free(triggerG); free(triggerB);
return output;
}
// Read enough video (1 second) to create the stacks used to test for triggers
void readShortBuffer(struct vdIn *videoIn, int nfr, int width, int height, unsigned char *buffer, int *stack1, int *stack2, unsigned char *maxMap, unsigned char *medianWorkspace)
{
const int frameSize = width*height;
int i,j;
for (i=0; i<frameSize; i++) stack1[i]=0;
for (i=0; i<frameSize; i++) maxMap[i]=0;
for (j=0;j<nfr;j++)
{
unsigned char *tmpc = buffer+j*frameSize;
if (uvcGrab(videoIn) < 0) { printf("Error grabbing\n"); break; }
Pyuv422toMono(videoIn->framebuffer, tmpc, videoIn->width, videoIn->height);
for (i=0; i<frameSize; i++) stack1[i]+=tmpc[i]; // Stack1 is wiped prior to each call to this function
if (stack2) for (i=0; i<frameSize; i++) stack2[i]+=tmpc[i]; // Stack2 can stack output of many calls to this function
for (i=0; i<frameSize; i++) if (maxMap[i]<tmpc[i]) maxMap[i]=tmpc[i];
}
// Add the pixel values in this stack into the histogram in medianWorkspace
for (i=0; i<frameSize; i++)
{
int d, pixelVal = CLIP256(stack1[i]/nfr);
medianWorkspace[i + pixelVal*frameSize]++;
}
}
int main(int argc, char *argv[])
{
if (argc!=3)
{
sprintf(temp_err_string, "ERROR: Need to specify UTC clock offset and observe run stop time on commandline, e.g. 'observe 1234 567'."); gnom_fatal(__FILE__,__LINE__,temp_err_string);
}
char line[4096];
const int utcoffset = (int)GetFloat(argv[1],NULL);
const int tstart = time(NULL) + utcoffset;
const int tstop = (int)GetFloat(argv[2],NULL);
if (DEBUG) { sprintf(line, "Starting observing run at %s.", StrStrip(FriendlyTimestring(tstart),temp_err_string)); gnom_log(line); }
if (DEBUG) { sprintf(line, "Observing run will end at %s.", StrStrip(FriendlyTimestring(tstop ),temp_err_string)); gnom_log(line); }
struct vdIn *videoIn;
const char *videodevice=VIDEO_DEV;
const float fps = VIDEO_FPS; // Requested frame rate
const int format = V4L2_PIX_FMT_YUYV;
const int grabmethod = 1;
const int queryformats = 0;
char *avifilename = argv[1];
videoIn = (struct vdIn *) calloc(1, sizeof(struct vdIn));
if (queryformats)
{
check_videoIn(videoIn,(char *) videodevice);
free(videoIn);
exit(1);
}
// Fetch the dimensions of the video stream as returned by V4L (which may differ from what we requested)
if (init_videoIn(videoIn, (char *) videodevice, VIDEO_WIDTH, VIDEO_HEIGHT, fps, format, grabmethod, avifilename) < 0) exit(1);
const int width = videoIn->width;
const int height= videoIn->height;
const int frameSize = width * height;
// Trigger buffers. These are used to store 1 second of video for comparison with the next
const double secondsTriggerBuff = 0.5;
const int nfrt = fps * secondsTriggerBuff;
const int btlen = nfrt*frameSize;
unsigned char *bufferA = malloc(btlen); // Two buffers, A and B, each hold alternate seconds of video data which we compare to see if anything has happened
unsigned char *bufferB = malloc(btlen);
int *stackA = malloc(frameSize*sizeof(int)); // A stacked version of the video data in buffers A and B
int *stackB = malloc(frameSize*sizeof(int));
unsigned char *maxA = malloc(frameSize); // Maximum recorded pixel intensity
unsigned char *maxB = malloc(frameSize);
// Timelapse buffers
int frameNextTargetTime = floor(time(NULL)/60+1)*60; // Store exposures once a minute, on the minute
const double secondsTimelapseBuff = 15;
const int nfrtl = fps * secondsTimelapseBuff;
int *stackT = malloc(frameSize*sizeof(int));
// Long buffer. Used to store a video after the camera has triggered
const double secondsLongBuff = 9;
const int nfrl = fps * secondsLongBuff;
const int bllen = nfrl*frameSize;
unsigned char *bufferL = malloc(bllen); // A long buffer, used to record 10 seconds of video after we trigger
int *stackL = malloc(frameSize*sizeof(int));
unsigned char *maxL = malloc(frameSize);
// Median maps are used for background subtraction. Maps A and B are used alternately and contain the median value of each pixel.
unsigned char *medianMapA = calloc(1,frameSize); // The median value of each pixel, sampled over 255 stacked images
unsigned char *medianMapB = calloc(1,frameSize);
unsigned char *medianWorkspace = calloc(1,frameSize*256); // Workspace which counts the number of times any given pixel has a particular value over 255 images
if ((!bufferA)||(!bufferB)||(!bufferL) || (!stackA)||(!stackB)||(!stackT)||(!stackL) || (!maxA)||(!maxB)||(!maxL) || (!medianMapA)||(!medianMapB)||(!medianWorkspace)) { sprintf(temp_err_string, "ERROR: malloc fail in observe."); gnom_fatal(__FILE__,__LINE__,temp_err_string); }
initLut();
int bufferNum = 0; // Flag for whether we're using trigger buffer A or B
int medianNum = 0; // Flag for whether we're using median map A or B
int medianCount = 0; // Count frames from 0 to 255 until we're ready to make a new median map
int recording =-1; // Count how many seconds we've been recording for. A value of -1 means we're not recording
int timelapseCount =-1; // Count used to add up <secondsTimelapseBuff> seconds of data when stacking timelapse frames
int framesSinceLastTrigger = -260; // Let the camera run for 260 seconds before triggering, as it takes this long to make first median map
while (1)
{
int t = time(NULL) - utcoffset;
if (t>=tstop) break; // Check how we're doing for time; if we've reached the time to stop, stop now!
// Work out where we're going to read next second of video to. Either bufferA / bufferB, or the long buffer if we're recording
unsigned char *buffer = bufferNum?bufferB:bufferA;
if (recording>-1) buffer = bufferL + frameSize*nfrt*recording;
// Read the next second of video
readShortBuffer(videoIn, nfrt, width, height, buffer, bufferNum?stackB:stackA, (timelapseCount>=0)?stackT:NULL, bufferNum?maxB:maxA, medianWorkspace);
framesSinceLastTrigger++;
if (DEBUG) if (framesSinceLastTrigger==3) { sprintf(line, "Camera is now able to trigger."); gnom_log(line); }
// If we've stacked 255 frames since we last made a median map, make a new median map
medianCount++;
if (medianCount==255) { medianNum=!medianNum; medianCalculate(width, height, medianWorkspace, medianNum?medianMapB:medianMapA); medianCount=0; }
// If we're recording, test whether we're ready to stop recording
if (recording>-1)
{
int i;
unsigned char *maxbuf = bufferNum?maxB:maxA;
int *stackbuf = bufferNum?stackB:stackA;
recording++;
for (i=0; i<frameSize; i++) if (maxbuf[i]>maxL[i]) maxL[i]=maxbuf[i];
for (i=0; i<frameSize; i++) stackL[i]+=stackbuf[i];
if (recording>=nfrl/nfrt)
{
char fname[4096];
sprintf(fname, "%s%s",triggerstub,"3_MAX.img");
dumpFrame(width, height, maxL, fname);
sprintf(fname, "%s%s",triggerstub,"3_BS0.img");
dumpFrameFromInts(width, height, stackL, nfrt+nfrl, 1, fname);
sprintf(fname, "%s%s",triggerstub,"3_BS1.img");
dumpFrameFromISub(width, height, stackL, nfrt+nfrl, STACK_GAIN, medianNum?medianMapB:medianMapA, fname);
sprintf(fname, "%s%s",triggerstub,".vid");
dumpVideo(nfrt, nfrl, width, height, bufferNum?bufferA:bufferB, bufferNum?bufferB:bufferA, bufferL, fname);
recording=-1; framesSinceLastTrigger=0;
} }
// Once a minute, dump create a stacked exposure lasting for <secondsTimelapseBuff> seconds
if (timelapseCount>=0)
{ timelapseCount++; }
else if (time(NULL)>frameNextTargetTime)
{
int i; for (i=0; i<frameSize; i++) stackT[i]=0;
timelapseCount=0;
}
if (timelapseCount>=nfrtl/nfrt)
{
char fstub[4096], fname[4096]; strcpy(fstub, fNameGenerate("frame_"));
sprintf(fname, "%s%s",fstub,"BS0.img");
dumpFrameFromInts(width, height, stackT, nfrtl, 1, fname);
sprintf(fname, "%s%s",fstub,"BS1.img");
dumpFrameFromISub(width, height, stackT, nfrtl, STACK_GAIN, medianNum?medianMapB:medianMapA, fname);
frameNextTargetTime+=60;
timelapseCount=-1;
}
// If we're not recording, and have not stopped recording within past 2 seconds, test whether motion sensor has triggered
if ( (recording<0) && (framesSinceLastTrigger>2) )
{
if (testTrigger( width , height , bufferNum?stackB:stackA , bufferNum?stackA:stackB , nfrt ))
{
char fname[4096];
// if (DEBUG) { sprintf(line, "Camera has triggered."); gnom_log(line); }
sprintf(fname, "%s%s",triggerstub,"2_BS0.img");
dumpFrameFromInts(width, height, bufferNum?stackB:stackA, nfrt, 1, fname);
sprintf(fname, "%s%s",triggerstub,"2_BS1.img");
dumpFrameFromISub(width, height, bufferNum?stackB:stackA, nfrt, STACK_GAIN, medianNum?medianMapB:medianMapA, fname);
sprintf(fname, "%s%s",triggerstub,"2_MAX.img");
dumpFrame (width, height, bufferNum?maxB:maxA, fname);
sprintf(fname, "%s%s",triggerstub,"1_BS0.img");
dumpFrameFromInts(width, height, bufferNum?stackA:stackB, nfrt, 1, fname);
sprintf(fname, "%s%s",triggerstub,"1_BS1.img");
dumpFrameFromISub(width, height, bufferNum?stackA:stackB, nfrt, STACK_GAIN, medianNum?medianMapB:medianMapA, fname);
sprintf(fname, "%s%s",triggerstub,"1_MAX.img");
dumpFrame (width, height, bufferNum?maxA:maxB, fname);
memcpy(maxL , bufferNum?maxB:maxA , frameSize);
memcpy(stackL, bufferNum?stackB:stackA, frameSize*sizeof(int));
recording=0;
}
}
// If we're not recording, flip buffer numbers. If we are recording, don't do this; keep buffer number pointing at buffer with first second of video
if (recording<0) bufferNum=!bufferNum;
}
free(bufferA); free(bufferB); free(bufferL); free(stackA); free(stackB); free(medianMapA); free(medianMapB); free(medianWorkspace);
return 0;
}
| gpl-3.0 |
r0mai/metashell | 3rd/templight/clang/test/SemaCXX/recovery-expr-type.cpp | 2 | 4376 | // RUN: %clang_cc1 -triple=x86_64-unknown-unknown -frecovery-ast -frecovery-ast-type -o - %s -fsyntax-only -verify
namespace test0 {
struct Indestructible {
// Indestructible();
~Indestructible() = delete; // expected-note 2{{deleted}}
};
Indestructible make_indestructible();
void test() {
// no crash.
int s = sizeof(make_indestructible()); // expected-error {{deleted}}
constexpr int ss = sizeof(make_indestructible()); // expected-error {{deleted}}
static_assert(ss, "");
int array[ss];
}
}
namespace test1 {
constexpr int foo() { return 1; } // expected-note {{candidate function not viable}}
// verify the "not an integral constant expression" diagnostic is suppressed.
static_assert(1 == foo(1), ""); // expected-error {{no matching function}}
}
namespace test2 {
void foo(); // expected-note 3{{requires 0 arguments}}
void func() {
// verify that "field has incomplete type" diagnostic is suppressed.
typeof(foo(42)) var; // expected-error {{no matching function}}
// FIXME: suppress the "cannot initialize a variable" diagnostic.
int a = foo(1); // expected-error {{no matching function}} \
// expected-error {{cannot initialize a variable of type}}
// FIXME: suppress the "invalid application" diagnostic.
int s = sizeof(foo(42)); // expected-error {{no matching function}} \
// expected-error {{invalid application of 'sizeof'}}
};
}
namespace test3 {
template <int N>
constexpr int templated() __attribute__((enable_if(N, ""))) { // expected-note {{candidate disabled}}
return 1;
}
// verify that "constexpr variable must be initialized" diagnostic is suppressed.
constexpr int A = templated<0>(); // expected-error{{no matching function}}
template <typename T>
struct AA {
template <typename U>
static constexpr int getB() { // expected-note{{candidate template ignored}}
return 2;
}
static constexpr int foo2() {
return AA<T>::getB(); // expected-error{{no matching function for call to 'getB'}}
}
};
// FIXME: should we suppress the "be initialized by a constant expression" diagnostic?
constexpr auto x2 = AA<int>::foo2(); // expected-error {{be initialized by a constant expression}} \
// expected-note {{in instantiation of member function}}
}
// verify no assertion failure on violating value category.
namespace test4 {
int &&f(int); // expected-note {{candidate function not viable}}
int &&k = f(); // expected-error {{no matching function for call}}
}
// verify that "type 'double' cannot bind to a value of unrelated type 'int'" diagnostic is suppressed.
namespace test5 {
template<typename T> using U = T; // expected-note {{template parameter is declared here}}
template<typename...Ts> U<Ts...>& f(); // expected-error {{pack expansion used as argument for non-pack parameter of alias template}}
double &s1 = f(); // expected-error {{no matching function}}
}
namespace test6 {
struct T {
T() = delete; // expected-note {{has been explicitly marked deleted here}}
};
void func() {
// verify that no -Wunused-value diagnostic.
(T(T())); // expected-error {{call to deleted constructor}}
}
}
// verify the secondary diagnostic "no matching function" is emitted.
namespace test7 {
struct C {
C() = delete; // expected-note {{has been explicitly marked deleted}}
};
void f(C &); // expected-note {{candidate function not viable: expects an lvalue for 1st argument}}
void test() {
f(C()); // expected-error {{call to deleted constructor}} \
expected-error {{no matching function for call}}
}
}
// verify the secondary diagnostic "cannot initialize" is emitted.
namespace test8 {
typedef int arr[];
int v = arr(); // expected-error {{array types cannot be value-initialized}} \
expected-error {{cannot initialize a variable of type 'int' with an rvalue of type 'test8::arr'}}
}
namespace test9 {
auto f(); // expected-note {{candidate function not viable}}
// verify no crash on evaluating the size of undeduced auto type.
static_assert(sizeof(f(1)), ""); // expected-error {{no matching function for call to 'f'}}
}
namespace test10 {
// Ensure we don't assert here.
int f(); // expected-note {{candidate}}
template<typename T> const int k = f(T()); // expected-error {{no matching function}}
static_assert(k<int> == 1, ""); // expected-note {{instantiation of}}
}
| gpl-3.0 |
ShawnKoo/avplayer-1 | third_party/android/ffmpeg_2.0/jni/ffmpeg/libavdevice/fbdev.c | 3 | 9127 | /*
* Copyright (c) 2011 Stefano Sabatini
* Copyright (c) 2009 Giliard B. de Freitas <giliarde@gmail.com>
* Copyright (C) 2002 Gunnar Monell <gmo@linux.nu>
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* Linux framebuffer input device,
* inspired by code from fbgrab.c by Gunnar Monell.
* @see http://linux-fbdev.sourceforge.net/
*/
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <time.h>
#include <linux/fb.h>
#include "libavutil/log.h"
#include "libavutil/mem.h"
#include "libavutil/opt.h"
#include "libavutil/time.h"
#include "libavutil/parseutils.h"
#include "libavutil/pixdesc.h"
#include "avdevice.h"
#include "libavformat/internal.h"
struct rgb_pixfmt_map_entry {
int bits_per_pixel;
int red_offset, green_offset, blue_offset, alpha_offset;
enum AVPixelFormat pixfmt;
};
static const struct rgb_pixfmt_map_entry rgb_pixfmt_map[] = {
// bpp, red_offset, green_offset, blue_offset, alpha_offset, pixfmt
{ 32, 0, 8, 16, 24, AV_PIX_FMT_RGBA },
{ 32, 16, 8, 0, 24, AV_PIX_FMT_BGRA },
{ 32, 8, 16, 24, 0, AV_PIX_FMT_ARGB },
{ 32, 3, 2, 8, 0, AV_PIX_FMT_ABGR },
{ 24, 0, 8, 16, 0, AV_PIX_FMT_RGB24 },
{ 24, 16, 8, 0, 0, AV_PIX_FMT_BGR24 },
{ 16, 11, 5, 0, 16, AV_PIX_FMT_RGB565 },
};
static enum AVPixelFormat get_pixfmt_from_fb_varinfo(struct fb_var_screeninfo *varinfo)
{
int i;
for (i = 0; i < FF_ARRAY_ELEMS(rgb_pixfmt_map); i++) {
const struct rgb_pixfmt_map_entry *entry = &rgb_pixfmt_map[i];
if (entry->bits_per_pixel == varinfo->bits_per_pixel &&
entry->red_offset == varinfo->red.offset &&
entry->green_offset == varinfo->green.offset &&
entry->blue_offset == varinfo->blue.offset)
return entry->pixfmt;
}
return AV_PIX_FMT_NONE;
}
typedef struct {
AVClass *class; ///< class for private options
int frame_size; ///< size in bytes of a grabbed frame
AVRational framerate_q; ///< framerate
int64_t time_frame; ///< time for the next frame to output (in 1/1000000 units)
int fd; ///< framebuffer device file descriptor
int width, height; ///< assumed frame resolution
int frame_linesize; ///< linesize of the output frame, it is assumed to be constant
int bytes_per_pixel;
struct fb_var_screeninfo varinfo; ///< variable info;
struct fb_fix_screeninfo fixinfo; ///< fixed info;
uint8_t *data; ///< framebuffer data
} FBDevContext;
static av_cold int fbdev_read_header(AVFormatContext *avctx)
{
FBDevContext *fbdev = avctx->priv_data;
AVStream *st = NULL;
enum AVPixelFormat pix_fmt;
int ret, flags = O_RDONLY;
if (!(st = avformat_new_stream(avctx, NULL)))
return AVERROR(ENOMEM);
avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in microseconds */
/* NONBLOCK is ignored by the fbdev driver, only set for consistency */
if (avctx->flags & AVFMT_FLAG_NONBLOCK)
flags |= O_NONBLOCK;
if ((fbdev->fd = open(avctx->filename, flags)) == -1) {
ret = AVERROR(errno);
av_log(avctx, AV_LOG_ERROR,
"Could not open framebuffer device '%s': %s\n",
avctx->filename, strerror(ret));
return ret;
}
if (ioctl(fbdev->fd, FBIOGET_VSCREENINFO, &fbdev->varinfo) < 0) {
ret = AVERROR(errno);
av_log(avctx, AV_LOG_ERROR,
"FBIOGET_VSCREENINFO: %s\n", strerror(errno));
goto fail;
}
if (ioctl(fbdev->fd, FBIOGET_FSCREENINFO, &fbdev->fixinfo) < 0) {
ret = AVERROR(errno);
av_log(avctx, AV_LOG_ERROR,
"FBIOGET_FSCREENINFO: %s\n", strerror(errno));
goto fail;
}
pix_fmt = get_pixfmt_from_fb_varinfo(&fbdev->varinfo);
if (pix_fmt == AV_PIX_FMT_NONE) {
ret = AVERROR(EINVAL);
av_log(avctx, AV_LOG_ERROR,
"Framebuffer pixel format not supported.\n");
goto fail;
}
fbdev->width = fbdev->varinfo.xres;
fbdev->height = fbdev->varinfo.yres;
fbdev->bytes_per_pixel = (fbdev->varinfo.bits_per_pixel + 7) >> 3;
fbdev->frame_linesize = fbdev->width * fbdev->bytes_per_pixel;
fbdev->frame_size = fbdev->frame_linesize * fbdev->height;
fbdev->time_frame = AV_NOPTS_VALUE;
fbdev->data = mmap(NULL, fbdev->fixinfo.smem_len, PROT_READ, MAP_SHARED, fbdev->fd, 0);
if (fbdev->data == MAP_FAILED) {
ret = AVERROR(errno);
av_log(avctx, AV_LOG_ERROR, "Error in mmap(): %s\n", strerror(errno));
goto fail;
}
st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
st->codec->width = fbdev->width;
st->codec->height = fbdev->height;
st->codec->pix_fmt = pix_fmt;
st->codec->time_base = av_inv_q(fbdev->framerate_q);
st->codec->bit_rate =
fbdev->width * fbdev->height * fbdev->bytes_per_pixel * av_q2d(fbdev->framerate_q) * 8;
av_log(avctx, AV_LOG_INFO,
"w:%d h:%d bpp:%d pixfmt:%s fps:%d/%d bit_rate:%d\n",
fbdev->width, fbdev->height, fbdev->varinfo.bits_per_pixel,
av_get_pix_fmt_name(pix_fmt),
fbdev->framerate_q.num, fbdev->framerate_q.den,
st->codec->bit_rate);
return 0;
fail:
close(fbdev->fd);
return ret;
}
static int fbdev_read_packet(AVFormatContext *avctx, AVPacket *pkt)
{
FBDevContext *fbdev = avctx->priv_data;
int64_t curtime, delay;
struct timespec ts;
int i, ret;
uint8_t *pin, *pout;
if (fbdev->time_frame == AV_NOPTS_VALUE)
fbdev->time_frame = av_gettime();
/* wait based on the frame rate */
while (1) {
curtime = av_gettime();
delay = fbdev->time_frame - curtime;
av_dlog(avctx,
"time_frame:%"PRId64" curtime:%"PRId64" delay:%"PRId64"\n",
fbdev->time_frame, curtime, delay);
if (delay <= 0) {
fbdev->time_frame += INT64_C(1000000) / av_q2d(fbdev->framerate_q);
break;
}
if (avctx->flags & AVFMT_FLAG_NONBLOCK)
return AVERROR(EAGAIN);
ts.tv_sec = delay / 1000000;
ts.tv_nsec = (delay % 1000000) * 1000;
while (nanosleep(&ts, &ts) < 0 && errno == EINTR);
}
if ((ret = av_new_packet(pkt, fbdev->frame_size)) < 0)
return ret;
/* refresh fbdev->varinfo, visible data position may change at each call */
if (ioctl(fbdev->fd, FBIOGET_VSCREENINFO, &fbdev->varinfo) < 0)
av_log(avctx, AV_LOG_WARNING,
"Error refreshing variable info: %s\n", strerror(errno));
pkt->pts = curtime;
/* compute visible data offset */
pin = fbdev->data + fbdev->bytes_per_pixel * fbdev->varinfo.xoffset +
fbdev->varinfo.yoffset * fbdev->fixinfo.line_length;
pout = pkt->data;
for (i = 0; i < fbdev->height; i++) {
memcpy(pout, pin, fbdev->frame_linesize);
pin += fbdev->fixinfo.line_length;
pout += fbdev->frame_linesize;
}
return fbdev->frame_size;
}
static av_cold int fbdev_read_close(AVFormatContext *avctx)
{
FBDevContext *fbdev = avctx->priv_data;
munmap(fbdev->data, fbdev->frame_size);
close(fbdev->fd);
return 0;
}
#define OFFSET(x) offsetof(FBDevContext, x)
#define DEC AV_OPT_FLAG_DECODING_PARAM
static const AVOption options[] = {
{ "framerate","", OFFSET(framerate_q), AV_OPT_TYPE_VIDEO_RATE, {.str = "25"}, 0, 0, DEC },
{ NULL },
};
static const AVClass fbdev_class = {
.class_name = "fbdev indev",
.item_name = av_default_item_name,
.option = options,
.version = LIBAVUTIL_VERSION_INT,
};
AVInputFormat ff_fbdev_demuxer = {
.name = "fbdev",
.long_name = NULL_IF_CONFIG_SMALL("Linux framebuffer"),
.priv_data_size = sizeof(FBDevContext),
.read_header = fbdev_read_header,
.read_packet = fbdev_read_packet,
.read_close = fbdev_read_close,
.flags = AVFMT_NOFILE,
.priv_class = &fbdev_class,
};
| gpl-3.0 |
Distrotech/radius | gnulib/lib/check-version.c | 3 | 1575 | /* check-version.h --- Check version string compatibility.
Copyright (C) 1998-2006, 2008-2013 Free Software Foundation, Inc.
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, 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/>. */
/* Written by Simon Josefsson. This interface is influenced by
gcry_check_version from Werner Koch's Libgcrypt. Paul Eggert
suggested the use of strverscmp to simplify implementation. */
#include <config.h>
#include <stddef.h>
#include <string.h>
/* Get specification. */
#include "check-version.h"
/* Check that the version of the library (i.e., the CPP symbol VERSION)
* is at minimum the requested one in REQ_VERSION (typically found in
* a header file) and return the version string. Return NULL if the
* condition is not satisfied. If a NULL is passed to this function,
* no check is done, but the version string is simply returned.
*/
const char *
check_version (const char *req_version)
{
if (!req_version || strverscmp (req_version, VERSION) <= 0)
return VERSION;
return NULL;
}
| gpl-3.0 |
kumanna/itpp | itpp/base/bessel/struve.cpp | 3 | 5007 | /*!
* \file
* \brief Implementation of struve function
* \author Tony Ottosson
*
* -------------------------------------------------------------------------
*
* Copyright (C) 1995-2010 (see AUTHORS file for a list of contributors)
*
* This file is part of IT++ - a C++ library of mathematical, signal
* processing, speech processing, and communications classes and functions.
*
* IT++ 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 3 of the License, or (at your option) any
* later version.
*
* IT++ 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 IT++. If not, see <http://www.gnu.org/licenses/>.
*
* -------------------------------------------------------------------------
*
* This is slightly modified routine from the Cephes library:
* http://www.netlib.org/cephes/
*/
#include <itpp/base/bessel/bessel_internal.h>
#include <itpp/base/itcompat.h>
/*
* Struve function
*
* double v, x, y, struve();
*
* y = struve( v, x );
*
* DESCRIPTION:
*
* Computes the Struve function Hv(x) of order v, argument x.
* Negative x is rejected unless v is an integer.
*
* This module also contains the hypergeometric functions 1F2
* and 3F0 and a routine for the Bessel function Yv(x) with
* noninteger v.
*
* ACCURACY:
*
* Not accurately characterized, but spot checked against tables.
*/
/*
Cephes Math Library Release 2.81: June, 2000
Copyright 1984, 1987, 1989, 2000 by Stephen L. Moshier
*/
static double stop = 1.37e-17;
#define MACHEP 1.11022302462515654042E-16 /* 2**-53 */
double onef2(double a, double b, double c, double x, double *err)
{
double n, a0, sum, t;
double an, bn, cn, max, z;
an = a;
bn = b;
cn = c;
a0 = 1.0;
sum = 1.0;
n = 1.0;
t = 1.0;
max = 0.0;
do {
if (an == 0)
goto done;
if (bn == 0)
goto error;
if (cn == 0)
goto error;
if ((a0 > 1.0e34) || (n > 200))
goto error;
a0 *= (an * x) / (bn * cn * n);
sum += a0;
an += 1.0;
bn += 1.0;
cn += 1.0;
n += 1.0;
z = fabs(a0);
if (z > max)
max = z;
if (sum != 0)
t = fabs(a0 / sum);
else
t = z;
}
while (t > stop);
done:
*err = fabs(MACHEP * max / sum);
goto xit;
error:
*err = 1.0e38;
xit:
return(sum);
}
double threef0(double a, double b, double c, double x, double *err)
{
double n, a0, sum, t, conv, conv1;
double an, bn, cn, max, z;
an = a;
bn = b;
cn = c;
a0 = 1.0;
sum = 1.0;
n = 1.0;
t = 1.0;
max = 0.0;
conv = 1.0e38;
conv1 = conv;
do {
if (an == 0.0)
goto done;
if (bn == 0.0)
goto done;
if (cn == 0.0)
goto done;
if ((a0 > 1.0e34) || (n > 200))
goto error;
a0 *= (an * bn * cn * x) / n;
an += 1.0;
bn += 1.0;
cn += 1.0;
n += 1.0;
z = fabs(a0);
if (z > max)
max = z;
if (z >= conv) {
if ((z < max) && (z > conv1))
goto done;
}
conv1 = conv;
conv = z;
sum += a0;
if (sum != 0)
t = fabs(a0 / sum);
else
t = z;
}
while (t > stop);
done:
t = fabs(MACHEP * max / sum);
max = fabs(conv / sum);
if (max > t)
t = max;
goto xit;
error:
t = 1.0e38;
xit:
*err = t;
return(sum);
}
#define PI 3.14159265358979323846 /* pi */
double struve(double v, double x)
{
double y, ya, f, g, h, t;
double onef2err, threef0err;
f = floor(v);
if ((v < 0) && (v - f == 0.5)) {
y = jv(-v, x);
f = 1.0 - f;
g = 2.0 * floor(f / 2.0);
if (g != f)
y = -y;
return(y);
}
t = 0.25 * x * x;
f = fabs(x);
g = 1.5 * fabs(v);
if ((f > 30.0) && (f > g)) {
onef2err = 1.0e38;
y = 0.0;
}
else {
y = onef2(1.0, 1.5, 1.5 + v, -t, &onef2err);
}
if ((f < 18.0) || (x < 0.0)) {
threef0err = 1.0e38;
ya = 0.0;
}
else {
ya = threef0(1.0, 0.5, 0.5 - v, -1.0 / t, &threef0err);
}
f = sqrt(PI);
h = pow(0.5 * x, v - 1.0);
if (onef2err <= threef0err) {
g = gam(v + 1.5);
y = y * h * t / (0.5 * f * g);
return(y);
}
else {
g = gam(v + 0.5);
ya = ya * h / (f * g);
ya = ya + yv(v, x);
return(ya);
}
}
/*
* Bessel function of noninteger order
*/
double yv(double v, double x)
{
double y, t;
int n;
y = floor(v);
if (y == v) {
n = int(v);
y = yn(n, x);
return(y);
}
t = PI * v;
y = (cos(t) * jv(v, x) - jv(-v, x)) / sin(t);
return(y);
}
/* Crossover points between ascending series and asymptotic series
* for Struve function
*
* v x
*
* 0 19.2
* 1 18.95
* 2 19.15
* 3 19.3
* 5 19.7
* 10 21.35
* 20 26.35
* 30 32.31
* 40 40.0
*/
| gpl-3.0 |
brotzeit/remacs | src/xmenu.c | 3 | 39678 | /* X Communication module for terminals which understand the X protocol.
Copyright (C) 1986, 1988, 1993-1994, 1996, 1999-2018 Free Software
Foundation, Inc.
Author: Jon Arnold
Roman Budzianowski
Robert Krawitz
This file is part of GNU Emacs.
GNU Emacs 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 3 of the License, or (at
your option) any later version.
GNU Emacs 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 GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
/* X pop-up deck-of-cards menu facility for GNU Emacs.
*
*/
/* Modified by Fred Pierresteguy on December 93
to make the popup menus and menubar use the Xt. */
/* Rewritten for clarity and GC protection by rms in Feb 94. */
#include <config.h>
#include <stdio.h>
#include "lisp.h"
#include "keyboard.h"
#include "frame.h"
#include "systime.h"
#include "termhooks.h"
#include "window.h"
#include "blockinput.h"
#include "buffer.h"
#include "coding.h"
#include "sysselect.h"
/* This may include sys/types.h, and that somehow loses
if this is not done before the other system files. */
#include "xterm.h"
/* Load sys/types.h if not already loaded.
In some systems loading it twice is suicidal. */
#ifndef makedev
#include <sys/types.h>
#endif
/* Defining HAVE_MULTILINGUAL_MENU would mean that the toolkit menu
code accepts the Emacs internal encoding. */
#undef HAVE_MULTILINGUAL_MENU
#include "gtkutil.h"
#ifdef HAVE_GTK3
#include "xgselect.h"
#endif
#include "menu.h"
/* Flag which when set indicates a dialog or menu has been posted by
Xt on behalf of one of the widget sets. */
static int popup_activated_flag;
/* Set menu_items_inuse so no other popup menu or dialog is created. */
void
x_menu_set_in_use (bool in_use)
{
Lisp_Object frames, frame;
menu_items_inuse = in_use ? Qt : Qnil;
popup_activated_flag = in_use;
/* Don't let frames in `above' z-group obscure popups. */
FOR_EACH_FRAME (frames, frame)
{
struct frame *f = XFRAME (frame);
if (in_use && FRAME_Z_GROUP_ABOVE (f))
x_set_z_group (f, Qabove_suspended, Qabove);
else if (!in_use && FRAME_Z_GROUP_ABOVE_SUSPENDED (f))
x_set_z_group (f, Qabove, Qabove_suspended);
}
}
/* Wait for an X event to arrive or for a timer to expire. */
void
x_menu_wait_for_event (void *data)
{
/* Another way to do this is to register a timer callback, that can be
done in GTK and Xt. But we have to do it like this when using only X
anyway, and with callbacks we would have three variants for timer handling
instead of the small ifdefs below. */
while (
! gtk_events_pending ()
)
{
struct timespec next_time = timer_check (), *ntp;
fd_set read_fds;
struct x_display_info *dpyinfo;
int n = 0;
FD_ZERO (&read_fds);
for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
{
int fd = ConnectionNumber (dpyinfo->display);
FD_SET (fd, &read_fds);
if (fd > n) n = fd;
XFlush (dpyinfo->display);
}
if (! timespec_valid_p (next_time))
ntp = 0;
else
ntp = &next_time;
#if defined HAVE_GTK3
/* Gtk3 have arrows on menus when they don't fit. When the
pointer is over an arrow, a timeout scrolls it a bit. Use
xg_select so that timeout gets triggered. */
xg_select (n + 1, &read_fds, NULL, NULL, ntp, NULL);
#else
pselect (n + 1, &read_fds, NULL, NULL, ntp, NULL);
#endif
}
}
DEFUN ("x-menu-bar-open-internal", Fx_menu_bar_open_internal, Sx_menu_bar_open_internal, 0, 1, "i",
doc: /* Start key navigation of the menu bar in FRAME.
This initially opens the first menu bar item and you can then navigate with the
arrow keys, select a menu entry with the return key or cancel with the
escape key. If FRAME has no menu bar this function does nothing.
If FRAME is nil or not given, use the selected frame. */)
(Lisp_Object frame)
{
GtkWidget *menubar;
struct frame *f;
block_input ();
f = decode_window_system_frame (frame);
if (FRAME_EXTERNAL_MENU_BAR (f))
set_frame_menubar (f, false, true);
menubar = FRAME_X_OUTPUT (f)->menubar_widget;
if (menubar)
{
/* Activate the first menu. */
GList *children = gtk_container_get_children (GTK_CONTAINER (menubar));
if (children)
{
g_signal_emit_by_name (children->data, "activate_item");
popup_activated_flag = 1;
g_list_free (children);
}
}
unblock_input ();
return Qnil;
}
/* Loop util popup_activated_flag is set to zero in a callback.
Used for popup menus and dialogs. */
static void
popup_widget_loop (bool do_timers, GtkWidget *widget)
{
++popup_activated_flag;
/* Process events in the Gtk event loop until done. */
while (popup_activated_flag)
{
if (do_timers) x_menu_wait_for_event (0);
gtk_main_iteration ();
}
}
/* Activate the menu bar of frame F.
This is called from keyboard.c when it gets the
MENU_BAR_ACTIVATE_EVENT out of the Emacs event queue.
To activate the menu bar, we use the X button-press event
that was saved in saved_menu_event.
That makes the toolkit do its thing.
But first we recompute the menu bar contents (the whole tree).
The reason for saving the button event until here, instead of
passing it to the toolkit right away, is that we can safely
execute Lisp code. */
void
x_activate_menubar (struct frame *f)
{
eassert (FRAME_X_P (f));
if (!f->output_data.x->saved_menu_event->type)
return;
if (! xg_win_to_widget (FRAME_X_DISPLAY (f),
f->output_data.x->saved_menu_event->xany.window))
return;
set_frame_menubar (f, false, true);
block_input ();
popup_activated_flag = 1;
XPutBackEvent (f->output_data.x->display_info->display,
f->output_data.x->saved_menu_event);
unblock_input ();
/* Ignore this if we get it a second time. */
f->output_data.x->saved_menu_event->type = 0;
}
/* This callback is invoked when a dialog or menu is finished being
used and has been unposted. */
static void
popup_deactivate_callback (
GtkWidget *widget, gpointer client_data
)
{
popup_activated_flag = 0;
}
/* Function that finds the frame for WIDGET and shows the HELP text
for that widget.
F is the frame if known, or NULL if not known. */
static void
show_help_event (struct frame *f, xt_or_gtk_widget widget, Lisp_Object help)
{
Lisp_Object frame;
if (f)
{
XSETFRAME (frame, f);
kbd_buffer_store_help_event (frame, help);
}
else
show_help_echo (help, Qnil, Qnil, Qnil);
}
/* Callback called when menu items are highlighted/unhighlighted
while moving the mouse over them. WIDGET is the menu bar or menu
popup widget. ID is its LWLIB_ID. CALL_DATA contains a pointer to
the data structure for the menu item, or null in case of
unhighlighting. */
static void
menu_highlight_callback (GtkWidget *widget, gpointer call_data)
{
xg_menu_item_cb_data *cb_data;
Lisp_Object help;
cb_data = g_object_get_data (G_OBJECT (widget), XG_ITEM_DATA);
if (! cb_data) return;
help = call_data ? cb_data->help : Qnil;
/* If popup_activated_flag is greater than 1 we are in a popup menu.
Don't pass the frame to show_help_event for those.
Passing frame creates an Emacs event. As we are looping in
popup_widget_loop, it won't be handled. Passing NULL shows the tip
directly without using an Emacs event. This is what the Lucid code
does below. */
show_help_event (popup_activated_flag <= 1 ? cb_data->cl_data->f : NULL,
widget, help);
}
/* Gtk calls callbacks just because we tell it what item should be
selected in a radio group. If this variable is set to a non-zero
value, we are creating menus and don't want callbacks right now.
*/
static bool xg_crazy_callback_abort;
/* This callback is called from the menu bar pulldown menu
when the user makes a selection.
Figure out what the user chose
and put the appropriate events into the keyboard buffer. */
static void
menubar_selection_callback (GtkWidget *widget, gpointer client_data)
{
xg_menu_item_cb_data *cb_data = client_data;
if (xg_crazy_callback_abort)
return;
if (! cb_data || ! cb_data->cl_data || ! cb_data->cl_data->f)
return;
/* For a group of radio buttons, GTK calls the selection callback first
for the item that was active before the selection and then for the one that
is active after the selection. For C-h k this means we get the help on
the deselected item and then the selected item is executed. Prevent that
by ignoring the non-active item. */
if (GTK_IS_RADIO_MENU_ITEM (widget)
&& ! gtk_check_menu_item_get_active (GTK_CHECK_MENU_ITEM (widget)))
return;
/* When a menu is popped down, X generates a focus event (i.e. focus
goes back to the frame below the menu). Since GTK buffers events,
we force it out here before the menu selection event. Otherwise
sit-for will exit at once if the focus event follows the menu selection
event. */
block_input ();
while (gtk_events_pending ())
gtk_main_iteration ();
unblock_input ();
find_and_call_menu_selection (cb_data->cl_data->f,
cb_data->cl_data->menu_bar_items_used,
cb_data->cl_data->menu_bar_vector,
cb_data->call_data);
}
/* Recompute all the widgets of frame F, when the menu bar has been
changed. */
static void
update_frame_menubar (struct frame *f)
{
xg_update_frame_menubar (f);
}
/* Set the contents of the menubar widgets of frame F.
The argument FIRST_TIME is currently ignored;
it is set the first time this is called, from initialize_frame_menubar. */
void
set_frame_menubar (struct frame *f, bool first_time, bool deep_p)
{
xt_or_gtk_widget menubar_widget, old_widget;
Lisp_Object items;
widget_value *wv, *first_wv, *prev_wv = 0;
int i;
int *submenu_start, *submenu_end;
bool *submenu_top_level_items;
int *submenu_n_panes;
eassert (FRAME_X_P (f));
menubar_widget = old_widget = f->output_data.x->menubar_widget;
XSETFRAME (Vmenu_updating_frame, f);
if (! menubar_widget)
deep_p = true;
/* Make the first call for any given frame always go deep. */
else if (!f->output_data.x->saved_menu_event && !deep_p)
{
deep_p = true;
f->output_data.x->saved_menu_event = xmalloc (sizeof (XEvent));
f->output_data.x->saved_menu_event->type = 0;
}
if (deep_p)
{
/* Make a widget-value tree representing the entire menu trees. */
struct buffer *prev = current_buffer;
Lisp_Object buffer;
ptrdiff_t specpdl_count = SPECPDL_INDEX ();
int previous_menu_items_used = f->menu_bar_items_used;
Lisp_Object *previous_items
= alloca (previous_menu_items_used * sizeof *previous_items);
int subitems;
/* If we are making a new widget, its contents are empty,
do always reinitialize them. */
if (! menubar_widget)
previous_menu_items_used = 0;
buffer = XWINDOW (FRAME_SELECTED_WINDOW (f))->contents;
specbind (Qinhibit_quit, Qt);
/* Don't let the debugger step into this code
because it is not reentrant. */
specbind (Qdebug_on_next_call, Qnil);
record_unwind_save_match_data ();
if (NILP (Voverriding_local_map_menu_flag))
{
specbind (Qoverriding_terminal_local_map, Qnil);
specbind (Qoverriding_local_map, Qnil);
}
set_buffer_internal_1 (XBUFFER (buffer));
/* Run the Lucid hook. */
safe_run_hooks (Qactivate_menubar_hook);
/* If it has changed current-menubar from previous value,
really recompute the menubar from the value. */
if (! NILP (Vlucid_menu_bar_dirty_flag))
call0 (Qrecompute_lucid_menubar);
safe_run_hooks (Qmenu_bar_update_hook);
fset_menu_bar_items (f, menu_bar_items (FRAME_MENU_BAR_ITEMS (f)));
items = FRAME_MENU_BAR_ITEMS (f);
/* Save the frame's previous menu bar contents data. */
if (previous_menu_items_used)
memcpy (previous_items, XVECTOR (f->menu_bar_vector)->contents,
previous_menu_items_used * word_size);
/* Fill in menu_items with the current menu bar contents.
This can evaluate Lisp code. */
save_menu_items ();
menu_items = f->menu_bar_vector;
menu_items_allocated = VECTORP (menu_items) ? ASIZE (menu_items) : 0;
subitems = ASIZE (items) / 4;
submenu_start = alloca ((subitems + 1) * sizeof *submenu_start);
submenu_end = alloca (subitems * sizeof *submenu_end);
submenu_n_panes = alloca (subitems * sizeof *submenu_n_panes);
submenu_top_level_items = alloca (subitems
* sizeof *submenu_top_level_items);
init_menu_items ();
for (i = 0; i < subitems; i++)
{
Lisp_Object key, string, maps;
key = AREF (items, 4 * i);
string = AREF (items, 4 * i + 1);
maps = AREF (items, 4 * i + 2);
if (NILP (string))
break;
submenu_start[i] = menu_items_used;
menu_items_n_panes = 0;
submenu_top_level_items[i]
= parse_single_submenu (key, string, maps);
submenu_n_panes[i] = menu_items_n_panes;
submenu_end[i] = menu_items_used;
}
submenu_start[i] = -1;
finish_menu_items ();
/* Convert menu_items into widget_value trees
to display the menu. This cannot evaluate Lisp code. */
wv = make_widget_value ("menubar", NULL, true, Qnil);
wv->button_type = BUTTON_TYPE_NONE;
first_wv = wv;
for (i = 0; submenu_start[i] >= 0; i++)
{
menu_items_n_panes = submenu_n_panes[i];
wv = digest_single_submenu (submenu_start[i], submenu_end[i],
submenu_top_level_items[i]);
if (prev_wv)
prev_wv->next = wv;
else
first_wv->contents = wv;
/* Don't set wv->name here; GC during the loop might relocate it. */
wv->enabled = true;
wv->button_type = BUTTON_TYPE_NONE;
prev_wv = wv;
}
set_buffer_internal_1 (prev);
/* If there has been no change in the Lisp-level contents
of the menu bar, skip redisplaying it. Just exit. */
/* Compare the new menu items with the ones computed last time. */
for (i = 0; i < previous_menu_items_used; i++)
if (menu_items_used == i
|| (!EQ (previous_items[i], AREF (menu_items, i))))
break;
if (i == menu_items_used && i == previous_menu_items_used && i != 0)
{
/* The menu items have not changed. Don't bother updating
the menus in any form, since it would be a no-op. */
free_menubar_widget_value_tree (first_wv);
discard_menu_items ();
unbind_to (specpdl_count, Qnil);
return;
}
/* The menu items are different, so store them in the frame. */
fset_menu_bar_vector (f, menu_items);
f->menu_bar_items_used = menu_items_used;
/* This undoes save_menu_items. */
unbind_to (specpdl_count, Qnil);
/* Now GC cannot happen during the lifetime of the widget_value,
so it's safe to store data from a Lisp_String. */
wv = first_wv->contents;
for (i = 0; i < ASIZE (items); i += 4)
{
Lisp_Object string;
string = AREF (items, i + 1);
if (NILP (string))
break;
wv->name = SSDATA (string);
update_submenu_strings (wv->contents);
wv = wv->next;
}
}
else
{
/* Make a widget-value tree containing
just the top level menu bar strings. */
wv = make_widget_value ("menubar", NULL, true, Qnil);
wv->button_type = BUTTON_TYPE_NONE;
first_wv = wv;
items = FRAME_MENU_BAR_ITEMS (f);
for (i = 0; i < ASIZE (items); i += 4)
{
Lisp_Object string;
string = AREF (items, i + 1);
if (NILP (string))
break;
wv = make_widget_value (SSDATA (string), NULL, true, Qnil);
wv->button_type = BUTTON_TYPE_NONE;
/* This prevents lwlib from assuming this
menu item is really supposed to be empty. */
/* The intptr_t cast avoids a warning.
This value just has to be different from small integers. */
wv->call_data = (void *) (intptr_t) (-1);
if (prev_wv)
prev_wv->next = wv;
else
first_wv->contents = wv;
prev_wv = wv;
}
/* Forget what we thought we knew about what is in the
detailed contents of the menu bar menus.
Changing the top level always destroys the contents. */
f->menu_bar_items_used = 0;
}
/* Create or update the menu bar widget. */
block_input ();
xg_crazy_callback_abort = true;
if (menubar_widget)
{
/* The fourth arg is DEEP_P, which says to consider the entire
menu trees we supply, rather than just the menu bar item names. */
xg_modify_menubar_widgets (menubar_widget,
f,
first_wv,
deep_p,
G_CALLBACK (menubar_selection_callback),
G_CALLBACK (popup_deactivate_callback),
G_CALLBACK (menu_highlight_callback));
}
else
{
menubar_widget
= xg_create_widget ("menubar", "menubar", f, first_wv,
G_CALLBACK (menubar_selection_callback),
G_CALLBACK (popup_deactivate_callback),
G_CALLBACK (menu_highlight_callback));
f->output_data.x->menubar_widget = menubar_widget;
}
free_menubar_widget_value_tree (first_wv);
update_frame_menubar (f);
xg_crazy_callback_abort = false;
unblock_input ();
}
/* Called from Fx_create_frame to create the initial menubar of a frame
before it is mapped, so that the window is mapped with the menubar already
there instead of us tacking it on later and thrashing the window after it
is visible. */
void
initialize_frame_menubar (struct frame *f)
{
/* This function is called before the first chance to redisplay
the frame. It has to be, so the frame will have the right size. */
fset_menu_bar_items (f, menu_bar_items (FRAME_MENU_BAR_ITEMS (f)));
set_frame_menubar (f, true, true);
}
/* Get rid of the menu bar of frame F, and free its storage.
This is used when deleting a frame, and when turning off the menu bar.
For GTK this function is in gtkutil.c. */
/* x_menu_show actually displays a menu using the panes and items in menu_items
and returns the value selected from it.
There are two versions of x_menu_show, one for Xt and one for Xlib.
Both assume input is blocked by the caller. */
/* F is the frame the menu is for.
X and Y are the frame-relative specified position,
relative to the inside upper left corner of the frame F.
Bitfield MENUFLAGS bits are:
MENU_FOR_CLICK is set if this menu was invoked for a mouse click.
MENU_KEYMAPS is set if this menu was specified with keymaps;
in that case, we return a list containing the chosen item's value
and perhaps also the pane's prefix.
TITLE is the specified menu title.
ERROR is a place to store an error message string in case of failure.
(We return nil on failure, but the value doesn't actually matter.) */
/* The item selected in the popup menu. */
static Lisp_Object *volatile menu_item_selection;
/* Used when position a popup menu. See menu_position_func and
create_and_show_popup_menu below. */
struct next_popup_x_y
{
struct frame *f;
int x;
int y;
};
/* The menu position function to use if we are not putting a popup
menu where the pointer is.
MENU is the menu to pop up.
X and Y shall on exit contain x/y where the menu shall pop up.
PUSH_IN is not documented in the GTK manual.
USER_DATA is any data passed in when calling gtk_menu_popup.
Here it points to a struct next_popup_x_y where the coordinates
to store in *X and *Y are as well as the frame for the popup.
Here only X and Y are used. */
static void
menu_position_func (GtkMenu *menu, gint *x, gint *y, gboolean *push_in, gpointer user_data)
{
struct next_popup_x_y *data = user_data;
GtkRequisition req;
int max_x = -1;
int max_y = -1;
Lisp_Object frame, workarea;
XSETFRAME (frame, data->f);
/* TODO: Get the monitor workarea directly without calculating other
items in x-display-monitor-attributes-list. */
workarea = call3 (Qframe_monitor_workarea,
Qnil,
make_number (data->x),
make_number (data->y));
if (CONSP (workarea))
{
int min_x, min_y;
min_x = XINT (XCAR (workarea));
min_y = XINT (Fnth (make_number (1), workarea));
max_x = min_x + XINT (Fnth (make_number (2), workarea));
max_y = min_y + XINT (Fnth (make_number (3), workarea));
}
if (max_x < 0 || max_y < 0)
{
struct x_display_info *dpyinfo = FRAME_DISPLAY_INFO (data->f);
max_x = x_display_pixel_width (dpyinfo);
max_y = x_display_pixel_height (dpyinfo);
}
*x = data->x;
*y = data->y;
/* Check if there is room for the menu. If not, adjust x/y so that
the menu is fully visible. */
gtk_widget_get_preferred_size (GTK_WIDGET (menu), NULL, &req);
if (data->x + req.width > max_x)
*x -= data->x + req.width - max_x;
if (data->y + req.height > max_y)
*y -= data->y + req.height - max_y;
}
static void
popup_selection_callback (GtkWidget *widget, gpointer client_data)
{
xg_menu_item_cb_data *cb_data = client_data;
if (xg_crazy_callback_abort) return;
if (cb_data) menu_item_selection = cb_data->call_data;
}
static void
pop_down_menu (void *arg)
{
popup_activated_flag = 0;
block_input ();
gtk_widget_destroy (GTK_WIDGET (arg));
unblock_input ();
}
/* Pop up the menu for frame F defined by FIRST_WV at X/Y and loop until the
menu pops down.
menu_item_selection will be set to the selection. */
static void
create_and_show_popup_menu (struct frame *f, widget_value *first_wv,
int x, int y, bool for_click)
{
int i;
GtkWidget *menu;
GtkMenuPositionFunc pos_func = 0; /* Pop up at pointer. */
struct next_popup_x_y popup_x_y;
ptrdiff_t specpdl_count = SPECPDL_INDEX ();
bool use_pos_func = ! for_click;
#ifdef HAVE_GTK3
/* Always use position function for Gtk3. Otherwise menus may become
too small to show anything. */
use_pos_func = true;
#endif
eassert (FRAME_X_P (f));
xg_crazy_callback_abort = true;
menu = xg_create_widget ("popup", first_wv->name, f, first_wv,
G_CALLBACK (popup_selection_callback),
G_CALLBACK (popup_deactivate_callback),
G_CALLBACK (menu_highlight_callback));
xg_crazy_callback_abort = false;
if (use_pos_func)
{
Window dummy_window;
/* Not invoked by a click. pop up at x/y. */
pos_func = menu_position_func;
/* Adjust coordinates to be root-window-relative. */
block_input ();
XTranslateCoordinates (FRAME_X_DISPLAY (f),
/* From-window, to-window. */
FRAME_X_WINDOW (f),
FRAME_DISPLAY_INFO (f)->root_window,
/* From-position, to-position. */
x, y, &x, &y,
/* Child of win. */
&dummy_window);
#ifdef HAVE_GTK3
/* Use window scaling factor to adjust position for hidpi screens. */
x /= xg_get_scale (f);
y /= xg_get_scale (f);
#endif
unblock_input ();
popup_x_y.x = x;
popup_x_y.y = y;
popup_x_y.f = f;
i = 0; /* gtk_menu_popup needs this to be 0 for a non-button popup. */
}
if (for_click)
{
for (i = 0; i < 5; i++)
if (FRAME_DISPLAY_INFO (f)->grabbed & (1 << i))
break;
/* If keys aren't grabbed (i.e., a mouse up event), use 0. */
if (i == 5) i = 0;
}
/* Display the menu. */
gtk_widget_show_all (menu);
gtk_menu_popup (GTK_MENU (menu), 0, 0, pos_func, &popup_x_y, i,
FRAME_DISPLAY_INFO (f)->last_user_time);
record_unwind_protect_ptr (pop_down_menu, menu);
if (gtk_widget_get_mapped (menu))
{
/* Set this to one. popup_widget_loop increases it by one, so it becomes
two. show_help_echo uses this to detect popup menus. */
popup_activated_flag = 1;
/* Process events that apply to the menu. */
popup_widget_loop (true, menu);
}
unbind_to (specpdl_count, Qnil);
/* Must reset this manually because the button release event is not passed
to Emacs event loop. */
FRAME_DISPLAY_INFO (f)->grabbed = 0;
}
static void
cleanup_widget_value_tree (void *arg)
{
free_menubar_widget_value_tree (arg);
}
Lisp_Object
x_menu_show (struct frame *f, int x, int y, int menuflags,
Lisp_Object title, const char **error_name)
{
int i;
widget_value *wv, *save_wv = 0, *first_wv = 0, *prev_wv = 0;
widget_value **submenu_stack
= alloca (menu_items_used * sizeof *submenu_stack);
Lisp_Object *subprefix_stack
= alloca (menu_items_used * sizeof *subprefix_stack);
int submenu_depth = 0;
ptrdiff_t specpdl_count = SPECPDL_INDEX ();
eassert (FRAME_X_P (f));
*error_name = NULL;
if (menu_items_used <= MENU_ITEMS_PANE_LENGTH)
{
*error_name = "Empty menu";
return Qnil;
}
block_input ();
/* Create a tree of widget_value objects
representing the panes and their items. */
wv = make_widget_value ("menu", NULL, true, Qnil);
wv->button_type = BUTTON_TYPE_NONE;
first_wv = wv;
bool first_pane = true;
/* Loop over all panes and items, filling in the tree. */
i = 0;
while (i < menu_items_used)
{
if (EQ (AREF (menu_items, i), Qnil))
{
submenu_stack[submenu_depth++] = save_wv;
save_wv = prev_wv;
prev_wv = 0;
first_pane = true;
i++;
}
else if (EQ (AREF (menu_items, i), Qlambda))
{
prev_wv = save_wv;
save_wv = submenu_stack[--submenu_depth];
first_pane = false;
i++;
}
else if (EQ (AREF (menu_items, i), Qt)
&& submenu_depth != 0)
i += MENU_ITEMS_PANE_LENGTH;
/* Ignore a nil in the item list.
It's meaningful only for dialog boxes. */
else if (EQ (AREF (menu_items, i), Qquote))
i += 1;
else if (EQ (AREF (menu_items, i), Qt))
{
/* Create a new pane. */
Lisp_Object pane_name, prefix;
const char *pane_string;
pane_name = AREF (menu_items, i + MENU_ITEMS_PANE_NAME);
prefix = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
#ifndef HAVE_MULTILINGUAL_MENU
if (STRINGP (pane_name) && STRING_MULTIBYTE (pane_name))
{
pane_name = ENCODE_MENU_STRING (pane_name);
ASET (menu_items, i + MENU_ITEMS_PANE_NAME, pane_name);
}
#endif
pane_string = (NILP (pane_name)
? "" : SSDATA (pane_name));
/* If there is just one top-level pane, put all its items directly
under the top-level menu. */
if (menu_items_n_panes == 1)
pane_string = "";
/* If the pane has a meaningful name,
make the pane a top-level menu item
with its items as a submenu beneath it. */
if (!(menuflags & MENU_KEYMAPS) && strcmp (pane_string, ""))
{
wv = make_widget_value (pane_string, NULL, true, Qnil);
if (save_wv)
save_wv->next = wv;
else
first_wv->contents = wv;
if ((menuflags & MENU_KEYMAPS) && !NILP (prefix))
wv->name++;
wv->button_type = BUTTON_TYPE_NONE;
save_wv = wv;
prev_wv = 0;
}
else if (first_pane)
{
save_wv = wv;
prev_wv = 0;
}
first_pane = false;
i += MENU_ITEMS_PANE_LENGTH;
}
else
{
/* Create a new item within current pane. */
Lisp_Object item_name, enable, descrip, def, type, selected, help;
item_name = AREF (menu_items, i + MENU_ITEMS_ITEM_NAME);
enable = AREF (menu_items, i + MENU_ITEMS_ITEM_ENABLE);
descrip = AREF (menu_items, i + MENU_ITEMS_ITEM_EQUIV_KEY);
def = AREF (menu_items, i + MENU_ITEMS_ITEM_DEFINITION);
type = AREF (menu_items, i + MENU_ITEMS_ITEM_TYPE);
selected = AREF (menu_items, i + MENU_ITEMS_ITEM_SELECTED);
help = AREF (menu_items, i + MENU_ITEMS_ITEM_HELP);
#ifndef HAVE_MULTILINGUAL_MENU
if (STRINGP (item_name) && STRING_MULTIBYTE (item_name))
{
item_name = ENCODE_MENU_STRING (item_name);
ASET (menu_items, i + MENU_ITEMS_ITEM_NAME, item_name);
}
if (STRINGP (descrip) && STRING_MULTIBYTE (descrip))
{
descrip = ENCODE_MENU_STRING (descrip);
ASET (menu_items, i + MENU_ITEMS_ITEM_EQUIV_KEY, descrip);
}
#endif /* not HAVE_MULTILINGUAL_MENU */
wv = make_widget_value (SSDATA (item_name), NULL, !NILP (enable),
STRINGP (help) ? help : Qnil);
if (prev_wv)
prev_wv->next = wv;
else
save_wv->contents = wv;
if (!NILP (descrip))
wv->key = SSDATA (descrip);
/* If this item has a null value,
make the call_data null so that it won't display a box
when the mouse is on it. */
wv->call_data = !NILP (def) ? aref_addr (menu_items, i) : 0;
if (NILP (type))
wv->button_type = BUTTON_TYPE_NONE;
else if (EQ (type, QCtoggle))
wv->button_type = BUTTON_TYPE_TOGGLE;
else if (EQ (type, QCradio))
wv->button_type = BUTTON_TYPE_RADIO;
else
emacs_abort ();
wv->selected = !NILP (selected);
prev_wv = wv;
i += MENU_ITEMS_ITEM_LENGTH;
}
}
/* Deal with the title, if it is non-nil. */
if (!NILP (title))
{
widget_value *wv_title;
widget_value *wv_sep1 = make_widget_value ("--", NULL, false, Qnil);
widget_value *wv_sep2 = make_widget_value ("--", NULL, false, Qnil);
wv_sep2->next = first_wv->contents;
wv_sep1->next = wv_sep2;
#ifndef HAVE_MULTILINGUAL_MENU
if (STRING_MULTIBYTE (title))
title = ENCODE_MENU_STRING (title);
#endif
wv_title = make_widget_value (SSDATA (title), NULL, true, Qnil);
wv_title->button_type = BUTTON_TYPE_NONE;
wv_title->next = wv_sep1;
first_wv->contents = wv_title;
}
/* No selection has been chosen yet. */
menu_item_selection = 0;
/* Make sure to free the widget_value objects we used to specify the
contents even with longjmp. */
record_unwind_protect_ptr (cleanup_widget_value_tree, first_wv);
/* Actually create and show the menu until popped down. */
create_and_show_popup_menu (f, first_wv, x, y,
menuflags & MENU_FOR_CLICK);
unbind_to (specpdl_count, Qnil);
/* Find the selected item, and its pane, to return
the proper value. */
if (menu_item_selection != 0)
{
Lisp_Object prefix, entry;
prefix = entry = Qnil;
i = 0;
while (i < menu_items_used)
{
if (EQ (AREF (menu_items, i), Qnil))
{
subprefix_stack[submenu_depth++] = prefix;
prefix = entry;
i++;
}
else if (EQ (AREF (menu_items, i), Qlambda))
{
prefix = subprefix_stack[--submenu_depth];
i++;
}
else if (EQ (AREF (menu_items, i), Qt))
{
prefix
= AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
i += MENU_ITEMS_PANE_LENGTH;
}
/* Ignore a nil in the item list.
It's meaningful only for dialog boxes. */
else if (EQ (AREF (menu_items, i), Qquote))
i += 1;
else
{
entry
= AREF (menu_items, i + MENU_ITEMS_ITEM_VALUE);
if (menu_item_selection == aref_addr (menu_items, i))
{
if (menuflags & MENU_KEYMAPS)
{
int j;
entry = list1 (entry);
if (!NILP (prefix))
entry = Fcons (prefix, entry);
for (j = submenu_depth - 1; j >= 0; j--)
if (!NILP (subprefix_stack[j]))
entry = Fcons (subprefix_stack[j], entry);
}
unblock_input ();
return entry;
}
i += MENU_ITEMS_ITEM_LENGTH;
}
}
}
else if (!(menuflags & MENU_FOR_CLICK))
{
unblock_input ();
/* Make "Cancel" equivalent to C-g. */
quit ();
}
unblock_input ();
return Qnil;
}
static void
dialog_selection_callback (GtkWidget *widget, gpointer client_data)
{
/* Treat the pointer as an integer. There's no problem
as long as pointers have enough bits to hold small integers. */
if ((intptr_t) client_data != -1)
menu_item_selection = client_data;
popup_activated_flag = 0;
}
/* Pop up the dialog for frame F defined by FIRST_WV and loop until the
dialog pops down.
menu_item_selection will be set to the selection. */
static void
create_and_show_dialog (struct frame *f, widget_value *first_wv)
{
GtkWidget *menu;
eassert (FRAME_X_P (f));
menu = xg_create_widget ("dialog", first_wv->name, f, first_wv,
G_CALLBACK (dialog_selection_callback),
G_CALLBACK (popup_deactivate_callback),
0);
if (menu)
{
ptrdiff_t specpdl_count = SPECPDL_INDEX ();
record_unwind_protect_ptr (pop_down_menu, menu);
/* Display the menu. */
gtk_widget_show_all (menu);
/* Process events that apply to the menu. */
popup_widget_loop (true, menu);
unbind_to (specpdl_count, Qnil);
}
}
static const char * button_names [] = {
"button1", "button2", "button3", "button4", "button5",
"button6", "button7", "button8", "button9", "button10" };
static Lisp_Object
x_dialog_show (struct frame *f, Lisp_Object title,
Lisp_Object header, const char **error_name)
{
int i, nb_buttons=0;
char dialog_name[6];
widget_value *wv, *first_wv = 0, *prev_wv = 0;
/* Number of elements seen so far, before boundary. */
int left_count = 0;
/* Whether we've seen the boundary between left-hand elts and right-hand. */
bool boundary_seen = false;
ptrdiff_t specpdl_count = SPECPDL_INDEX ();
eassert (FRAME_X_P (f));
*error_name = NULL;
if (menu_items_n_panes > 1)
{
*error_name = "Multiple panes in dialog box";
return Qnil;
}
/* Create a tree of widget_value objects
representing the text label and buttons. */
{
Lisp_Object pane_name;
const char *pane_string;
pane_name = AREF (menu_items, MENU_ITEMS_PANE_NAME);
pane_string = (NILP (pane_name)
? "" : SSDATA (pane_name));
prev_wv = make_widget_value ("message", (char *) pane_string, true, Qnil);
first_wv = prev_wv;
/* Loop over all panes and items, filling in the tree. */
i = MENU_ITEMS_PANE_LENGTH;
while (i < menu_items_used)
{
/* Create a new item within current pane. */
Lisp_Object item_name, enable, descrip;
item_name = AREF (menu_items, i + MENU_ITEMS_ITEM_NAME);
enable = AREF (menu_items, i + MENU_ITEMS_ITEM_ENABLE);
descrip
= AREF (menu_items, i + MENU_ITEMS_ITEM_EQUIV_KEY);
if (NILP (item_name))
{
free_menubar_widget_value_tree (first_wv);
*error_name = "Submenu in dialog items";
return Qnil;
}
if (EQ (item_name, Qquote))
{
/* This is the boundary between left-side elts
and right-side elts. Stop incrementing right_count. */
boundary_seen = true;
i++;
continue;
}
if (nb_buttons >= 9)
{
free_menubar_widget_value_tree (first_wv);
*error_name = "Too many dialog items";
return Qnil;
}
wv = make_widget_value (button_names[nb_buttons],
SSDATA (item_name),
!NILP (enable), Qnil);
prev_wv->next = wv;
if (!NILP (descrip))
wv->key = SSDATA (descrip);
wv->call_data = aref_addr (menu_items, i);
prev_wv = wv;
if (! boundary_seen)
left_count++;
nb_buttons++;
i += MENU_ITEMS_ITEM_LENGTH;
}
/* If the boundary was not specified,
by default put half on the left and half on the right. */
if (! boundary_seen)
left_count = nb_buttons - nb_buttons / 2;
wv = make_widget_value (dialog_name, NULL, false, Qnil);
/* Frame title: 'Q' = Question, 'I' = Information.
Can also have 'E' = Error if, one day, we want
a popup for errors. */
if (NILP (header))
dialog_name[0] = 'Q';
else
dialog_name[0] = 'I';
/* Dialog boxes use a really stupid name encoding
which specifies how many buttons to use
and how many buttons are on the right. */
dialog_name[1] = '0' + nb_buttons;
dialog_name[2] = 'B';
dialog_name[3] = 'R';
/* Number of buttons to put on the right. */
dialog_name[4] = '0' + nb_buttons - left_count;
dialog_name[5] = 0;
wv->contents = first_wv;
first_wv = wv;
}
/* No selection has been chosen yet. */
menu_item_selection = 0;
/* Make sure to free the widget_value objects we used to specify the
contents even with longjmp. */
record_unwind_protect_ptr (cleanup_widget_value_tree, first_wv);
/* Actually create and show the dialog. */
create_and_show_dialog (f, first_wv);
unbind_to (specpdl_count, Qnil);
/* Find the selected item, and its pane, to return
the proper value. */
if (menu_item_selection != 0)
{
i = 0;
while (i < menu_items_used)
{
Lisp_Object entry;
if (EQ (AREF (menu_items, i), Qt))
i += MENU_ITEMS_PANE_LENGTH;
else if (EQ (AREF (menu_items, i), Qquote))
{
/* This is the boundary between left-side elts and
right-side elts. */
++i;
}
else
{
entry
= AREF (menu_items, i + MENU_ITEMS_ITEM_VALUE);
if (menu_item_selection == aref_addr (menu_items, i))
return entry;
i += MENU_ITEMS_ITEM_LENGTH;
}
}
}
else
/* Make "Cancel" equivalent to C-g. */
quit ();
return Qnil;
}
Lisp_Object
xw_popup_dialog (struct frame *f, Lisp_Object header, Lisp_Object contents)
{
Lisp_Object title;
const char *error_name;
Lisp_Object selection;
ptrdiff_t specpdl_count = SPECPDL_INDEX ();
check_window_system (f);
/* Decode the dialog items from what was specified. */
title = Fcar (contents);
CHECK_STRING (title);
record_unwind_protect_void (unuse_menu_items);
if (NILP (Fcar (Fcdr (contents))))
/* No buttons specified, add an "Ok" button so users can pop down
the dialog. Also, the lesstif/motif version crashes if there are
no buttons. */
contents = list2 (title, Fcons (build_string ("Ok"), Qt));
list_of_panes (list1 (contents));
/* Display them in a dialog box. */
block_input ();
selection = x_dialog_show (f, title, header, &error_name);
unblock_input ();
unbind_to (specpdl_count, Qnil);
discard_menu_items ();
if (error_name) error ("%s", error_name);
return selection;
}
/* Detect if a dialog or menu has been posted. */
int
popup_activated (void)
{
return popup_activated_flag;
}
/* The following is used by delayed window autoselection. */
DEFUN ("menu-or-popup-active-p", Fmenu_or_popup_active_p, Smenu_or_popup_active_p, 0, 0, 0,
doc: /* Return t if a menu or popup dialog is active.
\(On MS Windows, this refers to the selected frame.) */)
(void)
{
return (popup_activated ()) ? Qt : Qnil;
}
void
syms_of_xmenu (void)
{
DEFSYM (Qdebug_on_next_call, "debug-on-next-call");
defsubr (&Smenu_or_popup_active_p);
DEFSYM (Qframe_monitor_workarea, "frame-monitor-workarea");
defsubr (&Sx_menu_bar_open_internal);
Ffset (intern_c_string ("accelerate-menu"),
intern_c_string (Sx_menu_bar_open_internal.symbol_name));
}
| gpl-3.0 |
janisozaur/OpenRCT2 | src/openrct2/scripting/HookEngine.cpp | 4 | 5308 | /*****************************************************************************
* Copyright (c) 2014-2020 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
#ifdef ENABLE_SCRIPTING
# include "HookEngine.h"
# include "../core/EnumMap.hpp"
# include "ScriptEngine.h"
# include <unordered_map>
using namespace OpenRCT2::Scripting;
static const EnumMap<HOOK_TYPE> HooksLookupTable({
{ "action.query", HOOK_TYPE::ACTION_QUERY },
{ "action.execute", HOOK_TYPE::ACTION_EXECUTE },
{ "interval.tick", HOOK_TYPE::INTERVAL_TICK },
{ "interval.day", HOOK_TYPE::INTERVAL_DAY },
{ "network.chat", HOOK_TYPE::NETWORK_CHAT },
{ "network.authenticate", HOOK_TYPE::NETWORK_AUTHENTICATE },
{ "network.join", HOOK_TYPE::NETWORK_JOIN },
{ "network.leave", HOOK_TYPE::NETWORK_LEAVE },
{ "ride.ratings.calculate", HOOK_TYPE::RIDE_RATINGS_CALCULATE },
{ "action.location", HOOK_TYPE::ACTION_LOCATION },
{ "guest.generation", HOOK_TYPE::GUEST_GENERATION },
{ "vehicle.crash", HOOK_TYPE::VEHICLE_CRASH },
{ "map.change", HOOK_TYPE::MAP_CHANGE },
{ "map.changed", HOOK_TYPE::MAP_CHANGED },
{ "map.save", HOOK_TYPE::MAP_SAVE },
});
HOOK_TYPE OpenRCT2::Scripting::GetHookType(const std::string& name)
{
auto result = HooksLookupTable.find(name);
return (result != HooksLookupTable.end()) ? result->second : HOOK_TYPE::UNDEFINED;
}
HookEngine::HookEngine(ScriptEngine& scriptEngine)
: _scriptEngine(scriptEngine)
{
_hookMap.resize(NUM_HOOK_TYPES);
for (size_t i = 0; i < NUM_HOOK_TYPES; i++)
{
_hookMap[i].Type = static_cast<HOOK_TYPE>(i);
}
}
uint32_t HookEngine::Subscribe(HOOK_TYPE type, std::shared_ptr<Plugin> owner, const DukValue& function)
{
auto& hookList = GetHookList(type);
auto cookie = _nextCookie++;
hookList.Hooks.emplace_back(cookie, owner, function);
return cookie;
}
void HookEngine::Unsubscribe(HOOK_TYPE type, uint32_t cookie)
{
auto& hookList = GetHookList(type);
auto& hooks = hookList.Hooks;
for (auto it = hooks.begin(); it != hooks.end(); it++)
{
if (it->Cookie == cookie)
{
hooks.erase(it);
break;
}
}
}
void HookEngine::UnsubscribeAll(std::shared_ptr<const Plugin> owner)
{
for (auto& hookList : _hookMap)
{
auto& hooks = hookList.Hooks;
auto isOwner = [&](auto& obj) { return obj.Owner == owner; };
hooks.erase(std::remove_if(hooks.begin(), hooks.end(), isOwner), hooks.end());
}
}
void HookEngine::UnsubscribeAll()
{
for (auto& hookList : _hookMap)
{
auto& hooks = hookList.Hooks;
hooks.clear();
}
}
bool HookEngine::HasSubscriptions(HOOK_TYPE type) const
{
auto& hookList = GetHookList(type);
return !hookList.Hooks.empty();
}
bool HookEngine::IsValidHookForPlugin(HOOK_TYPE type, Plugin& plugin) const
{
if (type == HOOK_TYPE::MAP_CHANGED && plugin.GetMetadata().Type != PluginType::Intransient)
{
return false;
}
return true;
}
void HookEngine::Call(HOOK_TYPE type, bool isGameStateMutable)
{
auto& hookList = GetHookList(type);
for (auto& hook : hookList.Hooks)
{
_scriptEngine.ExecutePluginCall(hook.Owner, hook.Function, {}, isGameStateMutable);
}
}
void HookEngine::Call(HOOK_TYPE type, const DukValue& arg, bool isGameStateMutable)
{
auto& hookList = GetHookList(type);
for (auto& hook : hookList.Hooks)
{
_scriptEngine.ExecutePluginCall(hook.Owner, hook.Function, { arg }, isGameStateMutable);
}
}
void HookEngine::Call(
HOOK_TYPE type, const std::initializer_list<std::pair<std::string_view, std::any>>& args, bool isGameStateMutable)
{
auto& hookList = GetHookList(type);
for (auto& hook : hookList.Hooks)
{
auto ctx = _scriptEngine.GetContext();
// Convert key/value pairs into an object
auto objIdx = duk_push_object(ctx);
for (const auto& arg : args)
{
if (arg.second.type() == typeid(int32_t))
{
auto val = std::any_cast<int32_t>(arg.second);
duk_push_int(ctx, val);
}
else if (arg.second.type() == typeid(std::string))
{
const auto& val = std::any_cast<std::string>(arg.second);
duk_push_string(ctx, val.c_str());
}
else
{
throw std::runtime_error("Not implemented");
}
duk_put_prop_string(ctx, objIdx, arg.first.data());
}
std::vector<DukValue> dukArgs;
dukArgs.push_back(DukValue::take_from_stack(ctx));
_scriptEngine.ExecutePluginCall(hook.Owner, hook.Function, dukArgs, isGameStateMutable);
}
}
HookList& HookEngine::GetHookList(HOOK_TYPE type)
{
auto index = static_cast<size_t>(type);
return _hookMap[index];
}
const HookList& HookEngine::GetHookList(HOOK_TYPE type) const
{
auto index = static_cast<size_t>(type);
return _hookMap[index];
}
#endif
| gpl-3.0 |
chyh1990/FreeImage | Source/LibRawLite/dcraw/dcraw.c | 4 | 512762 | #ifndef IGNOREALL
/*
dcraw.c -- Dave Coffin's raw photo decoder
Copyright 1997-2015 by Dave Coffin, dcoffin a cybercom o net
This is a command-line ANSI C program to convert raw photos from
any digital camera on any computer running any operating system.
No license is required to download and use dcraw.c. However,
to lawfully redistribute dcraw, you must either (a) offer, at
no extra charge, full source code* for all executable files
containing RESTRICTED functions, (b) distribute this code under
the GPL Version 2 or later, (c) remove all RESTRICTED functions,
re-implement them, or copy them from an earlier, unrestricted
Revision of dcraw.c, or (d) purchase a license from the author.
The functions that process Foveon images have been RESTRICTED
since Revision 1.237. All other code remains free for all uses.
*If you have not modified dcraw.c in any way, a link to my
homepage qualifies as "full source code".
$Revision: 1.44 $
$Date: 2015/03/08 19:19:51 $
make -f Makefile.devel
git commit -a -m "v.102"
git push
*/
/*@out DEFINES
#ifndef USE_JPEG
#define NO_JPEG
#endif
#ifndef USE_JASPER
#define NO_JASPER
#endif
@end DEFINES */
#define NO_LCMS
#define DCRAW_VERBOSE
//@out DEFINES
#define DCRAW_VERSION "9.24"
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#define _USE_MATH_DEFINES
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
//@end DEFINES
#if defined(DJGPP) || defined(__MINGW32__)
#define fseeko fseek
#define ftello ftell
#else
#define fgetc getc_unlocked
#endif
//@out DEFINES
#ifdef __CYGWIN__
#include <io.h>
#endif
#ifdef WIN32
#include <sys/utime.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#define snprintf _snprintf
#define strcasecmp stricmp
#define strncasecmp strnicmp
//@end DEFINES
typedef __int64 INT64;
typedef unsigned __int64 UINT64;
//@out DEFINES
#else
#include <unistd.h>
#include <utime.h>
#include <netinet/in.h>
typedef long long INT64;
typedef unsigned long long UINT64;
#endif
#ifdef NODEPS
#define NO_JASPER
#define NO_JPEG
#define NO_LCMS
#endif
#ifndef NO_JASPER
#include <jasper/jasper.h> /* Decode Red camera movies */
#endif
#ifndef NO_JPEG
#include <jpeglib.h> /* Decode compressed Kodak DC120 photos */
#endif /* and Adobe Lossy DNGs */
#ifndef NO_LCMS
#ifdef USE_LCMS
#include <lcms.h> /* Support color profiles */
#else
#include <lcms2.h> /* Support color profiles */
#endif
#endif
#ifdef LOCALEDIR
#include <libintl.h>
#define _(String) gettext(String)
#else
#define _(String) (String)
#endif
#ifdef LJPEG_DECODE
#error Please compile dcraw.c by itself.
#error Do not link it with ljpeg_decode.
#endif
#ifndef LONG_BIT
#define LONG_BIT (8 * sizeof (long))
#endif
//@end DEFINES
#if !defined(uchar)
#define uchar unsigned char
#endif
#if !defined(ushort)
#define ushort unsigned short
#endif
/*
All global variables are defined here, and all functions that
access them are prefixed with "CLASS". Note that a thread-safe
C++ class cannot have non-const static local variables.
*/
FILE *ifp, *ofp;
short order;
const char *ifname;
char *meta_data, xtrans[6][6], xtrans_abs[6][6];
char cdesc[5], desc[512], make[64], model[64], model2[64], artist[64],software[64];
float flash_used, canon_ev, iso_speed, shutter, aperture, focal_len;
time_t timestamp;
off_t strip_offset, data_offset;
off_t thumb_offset, meta_offset, profile_offset;
unsigned shot_order, kodak_cbpp, exif_cfa, unique_id;
unsigned thumb_length, meta_length, profile_length;
unsigned thumb_misc, *oprof, fuji_layout, shot_select=0, multi_out=0;
unsigned tiff_nifds, tiff_samples, tiff_bps, tiff_compress;
unsigned black, maximum, mix_green, raw_color, zero_is_bad;
unsigned zero_after_ff, is_raw, dng_version, is_foveon, data_error;
unsigned tile_width, tile_length, gpsdata[32], load_flags;
unsigned flip, tiff_flip, filters, colors;
ushort raw_height, raw_width, height, width, top_margin, left_margin;
ushort shrink, iheight, iwidth, fuji_width, thumb_width, thumb_height;
ushort *raw_image, (*image)[4], cblack[4102];
ushort white[8][8], curve[0x10000], cr2_slice[3], sraw_mul[4];
double pixel_aspect, aber[4]={1,1,1,1}, gamm[6]={ 0.45,4.5,0,0,0,0 };
float bright=1, user_mul[4]={0,0,0,0}, threshold=0;
int mask[8][4];
int half_size=0, four_color_rgb=0, document_mode=0, highlight=0;
int verbose=0, use_auto_wb=0, use_camera_wb=0, use_camera_matrix=1;
int output_color=1, output_bps=8, output_tiff=0, med_passes=0;
int no_auto_bright=0;
unsigned greybox[4] = { 0, 0, UINT_MAX, UINT_MAX };
float cam_mul[4], pre_mul[4], cmatrix[3][4], rgb_cam[3][4];
const double xyz_rgb[3][3] = { /* XYZ from RGB */
{ 0.412453, 0.357580, 0.180423 },
{ 0.212671, 0.715160, 0.072169 },
{ 0.019334, 0.119193, 0.950227 } };
const float d65_white[3] = { 0.950456, 1, 1.088754 };
int histogram[4][0x2000];
void (*write_thumb)(), (*write_fun)();
void (*load_raw)(), (*thumb_load_raw)();
jmp_buf failure;
struct decode {
struct decode *branch[2];
int leaf;
} first_decode[2048], *second_decode, *free_decode;
struct tiff_ifd {
int t_width, t_height, bps, comp, phint, offset, t_flip, samples, bytes;
int t_tile_width, t_tile_length;
} tiff_ifd[10];
struct ph1 {
int format, key_off, tag_21a;
int t_black, split_col, black_col, split_row, black_row;
float tag_210;
} ph1;
#define CLASS
//@out DEFINES
#define FORC(cnt) for (c=0; c < cnt; c++)
#define FORC3 FORC(3)
#define FORC4 FORC(4)
#define FORCC FORC(colors)
#define SQR(x) ((x)*(x))
#define ABS(x) (((int)(x) ^ ((int)(x) >> 31)) - ((int)(x) >> 31))
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define LIM(x,min,max) MAX(min,MIN(x,max))
#define ULIM(x,y,z) ((y) < (z) ? LIM(x,y,z) : LIM(x,z,y))
#define CLIP(x) LIM(x,0,65535)
#define SWAP(a,b) { a=a+b; b=a-b; a=a-b; }
#define my_swap(type, i, j) {type t = i; i = j; j = t;}
/*
In order to inline this calculation, I make the risky
assumption that all filter patterns can be described
by a repeating pattern of eight rows and two columns
Do not use the FC or BAYER macros with the Leaf CatchLight,
because its pattern is 16x16, not 2x8.
Return values are either 0/1/2/3 = G/M/C/Y or 0/1/2/3 = R/G1/B/G2
PowerShot 600 PowerShot A50 PowerShot Pro70 Pro90 & G1
0xe1e4e1e4: 0x1b4e4b1e: 0x1e4b4e1b: 0xb4b4b4b4:
0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5
0 G M G M G M 0 C Y C Y C Y 0 Y C Y C Y C 0 G M G M G M
1 C Y C Y C Y 1 M G M G M G 1 M G M G M G 1 Y C Y C Y C
2 M G M G M G 2 Y C Y C Y C 2 C Y C Y C Y
3 C Y C Y C Y 3 G M G M G M 3 G M G M G M
4 C Y C Y C Y 4 Y C Y C Y C
PowerShot A5 5 G M G M G M 5 G M G M G M
0x1e4e1e4e: 6 Y C Y C Y C 6 C Y C Y C Y
7 M G M G M G 7 M G M G M G
0 1 2 3 4 5
0 C Y C Y C Y
1 G M G M G M
2 C Y C Y C Y
3 M G M G M G
All RGB cameras use one of these Bayer grids:
0x16161616: 0x61616161: 0x49494949: 0x94949494:
0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5
0 B G B G B G 0 G R G R G R 0 G B G B G B 0 R G R G R G
1 G R G R G R 1 B G B G B G 1 R G R G R G 1 G B G B G B
2 B G B G B G 2 G R G R G R 2 G B G B G B 2 R G R G R G
3 G R G R G R 3 B G B G B G 3 R G R G R G 3 G B G B G B
*/
#define RAW(row,col) \
raw_image[(row)*raw_width+(col)]
//@end DEFINES
#define FC(row,col) \
(filters >> ((((row) << 1 & 14) + ((col) & 1)) << 1) & 3)
//@out DEFINES
#define BAYER(row,col) \
image[((row) >> shrink)*iwidth + ((col) >> shrink)][FC(row,col)]
#define BAYER2(row,col) \
image[((row) >> shrink)*iwidth + ((col) >> shrink)][fcol(row,col)]
//@end DEFINES
/* @out COMMON
#include <math.h>
#define CLASS LibRaw::
#include "libraw/libraw_types.h"
#define LIBRAW_LIBRARY_BUILD
#define LIBRAW_IO_REDEFINED
#include "libraw/libraw.h"
#include "internal/defines.h"
#include "internal/var_defines.h"
@end COMMON */
//@out COMMON
int CLASS fcol (int row, int col)
{
static const char filter[16][16] =
{ { 2,1,1,3,2,3,2,0,3,2,3,0,1,2,1,0 },
{ 0,3,0,2,0,1,3,1,0,1,1,2,0,3,3,2 },
{ 2,3,3,2,3,1,1,3,3,1,2,1,2,0,0,3 },
{ 0,1,0,1,0,2,0,2,2,0,3,0,1,3,2,1 },
{ 3,1,1,2,0,1,0,2,1,3,1,3,0,1,3,0 },
{ 2,0,0,3,3,2,3,1,2,0,2,0,3,2,2,1 },
{ 2,3,3,1,2,1,2,1,2,1,1,2,3,0,0,1 },
{ 1,0,0,2,3,0,0,3,0,3,0,3,2,1,2,3 },
{ 2,3,3,1,1,2,1,0,3,2,3,0,2,3,1,3 },
{ 1,0,2,0,3,0,3,2,0,1,1,2,0,1,0,2 },
{ 0,1,1,3,3,2,2,1,1,3,3,0,2,1,3,2 },
{ 2,3,2,0,0,1,3,0,2,0,1,2,3,0,1,0 },
{ 1,3,1,2,3,2,3,2,0,2,0,1,1,0,3,0 },
{ 0,2,0,3,1,0,0,1,1,3,3,2,3,2,2,1 },
{ 2,1,3,2,3,1,2,1,0,3,0,2,0,2,0,2 },
{ 0,3,1,0,0,2,0,3,2,1,3,1,1,3,1,3 } };
if (filters == 1) return filter[(row+top_margin)&15][(col+left_margin)&15];
if (filters == 9) return xtrans[(row+6) % 6][(col+6) % 6];
return FC(row,col);
}
#ifndef __GLIBC__
char *my_memmem (char *haystack, size_t haystacklen,
char *needle, size_t needlelen)
{
char *c;
for (c = haystack; c <= haystack + haystacklen - needlelen; c++)
if (!memcmp (c, needle, needlelen))
return c;
return 0;
}
#define memmem my_memmem
char *my_strcasestr (char *haystack, const char *needle)
{
char *c;
for (c = haystack; *c; c++)
if (!strncasecmp(c, needle, strlen(needle)))
return c;
return 0;
}
#define strcasestr my_strcasestr
#endif
//@end COMMON
void CLASS merror (void *ptr, const char *where)
{
if (ptr) return;
fprintf (stderr,_("%s: Out of memory in %s\n"), ifname, where);
longjmp (failure, 1);
}
void CLASS derror()
{
if (!data_error) {
fprintf (stderr, "%s: ", ifname);
if (feof(ifp))
fprintf (stderr,_("Unexpected end of file\n"));
else
fprintf (stderr,_("Corrupt data near 0x%llx\n"), (INT64) ftello(ifp));
}
data_error++;
}
//@out COMMON
ushort CLASS sget2 (uchar *s)
{
if (order == 0x4949) /* "II" means little-endian */
return s[0] | s[1] << 8;
else /* "MM" means big-endian */
return s[0] << 8 | s[1];
}
// DNG was written by:
#define CameraDNG 1
#define AdobeDNG 2
#ifdef LIBRAW_LIBRARY_BUILD
static ushort saneSonyCameraInfo(uchar a, uchar b, uchar c, uchar d, uchar e, uchar f){
if ((a >> 4) > 9) return 0;
else if ((a & 0x0f) > 9) return 0;
else if ((b >> 4) > 9) return 0;
else if ((b & 0x0f) > 9) return 0;
else if ((c >> 4) > 9) return 0;
else if ((c & 0x0f) > 9) return 0;
else if ((d >> 4) > 9) return 0;
else if ((d & 0x0f) > 9) return 0;
else if ((e >> 4) > 9) return 0;
else if ((e & 0x0f) > 9) return 0;
else if ((f >> 4) > 9) return 0;
else if ((f & 0x0f) > 9) return 0;
return 1;
}
static ushort bcd2dec(uchar data){
if ((data >> 4) > 9) return 0;
else if ((data & 0x0f) > 9) return 0;
else return (data >> 4) * 10 + (data & 0x0f);
}
static uchar SonySubstitution[257] = "\x00\x01\x32\xb1\x0a\x0e\x87\x28\x02\xcc\xca\xad\x1b\xdc\x08\xed\x64\x86\xf0\x4f\x8c\x6c\xb8\xcb\x69\xc4\x2c\x03\x97\xb6\x93\x7c\x14\xf3\xe2\x3e\x30\x8e\xd7\x60\x1c\xa1\xab\x37\xec\x75\xbe\x23\x15\x6a\x59\x3f\xd0\xb9\x96\xb5\x50\x27\x88\xe3\x81\x94\xe0\xc0\x04\x5c\xc6\xe8\x5f\x4b\x70\x38\x9f\x82\x80\x51\x2b\xc5\x45\x49\x9b\x21\x52\x53\x54\x85\x0b\x5d\x61\xda\x7b\x55\x26\x24\x07\x6e\x36\x5b\x47\xb7\xd9\x4a\xa2\xdf\xbf\x12\x25\xbc\x1e\x7f\x56\xea\x10\xe6\xcf\x67\x4d\x3c\x91\x83\xe1\x31\xb3\x6f\xf4\x05\x8a\x46\xc8\x18\x76\x68\xbd\xac\x92\x2a\x13\xe9\x0f\xa3\x7a\xdb\x3d\xd4\xe7\x3a\x1a\x57\xaf\x20\x42\xb2\x9e\xc3\x8b\xf2\xd5\xd3\xa4\x7e\x1f\x98\x9c\xee\x74\xa5\xa6\xa7\xd8\x5e\xb0\xb4\x34\xce\xa8\x79\x77\x5a\xc1\x89\xae\x9a\x11\x33\x9d\xf5\x39\x19\x65\x78\x16\x71\xd2\xa9\x44\x63\x40\x29\xba\xa0\x8f\xe4\xd6\x3b\x84\x0d\xc2\x4e\x58\xdd\x99\x22\x6b\xc9\xbb\x17\x06\xe5\x7d\x66\x43\x62\xf6\xcd\x35\x90\x2e\x41\x8d\x6d\xaa\x09\x73\x95\x0c\xf1\x1d\xde\x4c\x2f\x2d\xf7\xd1\x72\xeb\xef\x48\xc7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff";
ushort CLASS sget2Rev(uchar *s) // specific to some Canon Makernotes fields, where they have endian in reverse
{
if (order == 0x4d4d) /* "II" means little-endian, and we reverse to "MM" - big endian */
return s[0] | s[1] << 8;
else /* "MM" means big-endian... */
return s[0] << 8 | s[1];
}
#endif
ushort CLASS get2()
{
uchar str[2] = { 0xff,0xff };
fread (str, 1, 2, ifp);
return sget2(str);
}
unsigned CLASS sget4 (uchar *s)
{
if (order == 0x4949)
return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24;
else
return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3];
}
#define sget4(s) sget4((uchar *)s)
unsigned CLASS get4()
{
uchar str[4] = { 0xff,0xff,0xff,0xff };
fread (str, 1, 4, ifp);
return sget4(str);
}
unsigned CLASS getint (int type)
{
return type == 3 ? get2() : get4();
}
float CLASS int_to_float (int i)
{
union { int i; float f; } u;
u.i = i;
return u.f;
}
double CLASS getreal (int type)
{
union { char c[8]; double d; } u,v;
int i, rev;
switch (type) {
case 3: return (unsigned short) get2();
case 4: return (unsigned int) get4();
case 5:
u.d = (unsigned int) get4();
v.d = (unsigned int)get4();
return u.d / (v.d ? v.d : 1);
case 8: return (signed short) get2();
case 9: return (signed int) get4();
case 10:
u.d = (signed int) get4();
v.d = (signed int)get4();
return u.d / (v.d?v.d:1);
case 11: return int_to_float (get4());
case 12:
rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234));
for (i=0; i < 8; i++)
u.c[i ^ rev] = fgetc(ifp);
return u.d;
default: return fgetc(ifp);
}
}
void CLASS read_shorts (ushort *pixel, int count)
{
if (fread (pixel, 2, count, ifp) < count) derror();
if ((order == 0x4949) == (ntohs(0x1234) == 0x1234))
swab ((char*)pixel, (char*)pixel, count*2);
}
void CLASS cubic_spline (const int *x_, const int *y_, const int len)
{
float **A, *b, *c, *d, *x, *y;
int i, j;
A = (float **) calloc (((2*len + 4)*sizeof **A + sizeof *A), 2*len);
if (!A) return;
A[0] = (float *) (A + 2*len);
for (i = 1; i < 2*len; i++)
A[i] = A[0] + 2*len*i;
y = len + (x = i + (d = i + (c = i + (b = A[0] + i*i))));
for (i = 0; i < len; i++) {
x[i] = x_[i] / 65535.0;
y[i] = y_[i] / 65535.0;
}
for (i = len-1; i > 0; i--) {
b[i] = (y[i] - y[i-1]) / (x[i] - x[i-1]);
d[i-1] = x[i] - x[i-1];
}
for (i = 1; i < len-1; i++) {
A[i][i] = 2 * (d[i-1] + d[i]);
if (i > 1) {
A[i][i-1] = d[i-1];
A[i-1][i] = d[i-1];
}
A[i][len-1] = 6 * (b[i+1] - b[i]);
}
for(i = 1; i < len-2; i++) {
float v = A[i+1][i] / A[i][i];
for(j = 1; j <= len-1; j++)
A[i+1][j] -= v * A[i][j];
}
for(i = len-2; i > 0; i--) {
float acc = 0;
for(j = i; j <= len-2; j++)
acc += A[i][j]*c[j];
c[i] = (A[i][len-1] - acc) / A[i][i];
}
for (i = 0; i < 0x10000; i++) {
float x_out = (float)(i / 65535.0);
float y_out = 0;
for (j = 0; j < len-1; j++) {
if (x[j] <= x_out && x_out <= x[j+1]) {
float v = x_out - x[j];
y_out = y[j] +
((y[j+1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j+1] * d[j])/6) * v
+ (c[j] * 0.5) * v*v + ((c[j+1] - c[j]) / (6 * d[j])) * v*v*v;
}
}
curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 :
(ushort)(y_out * 65535.0 + 0.5));
}
free (A);
}
void CLASS canon_600_fixed_wb (int temp)
{
static const short mul[4][5] = {
{ 667, 358,397,565,452 },
{ 731, 390,367,499,517 },
{ 1119, 396,348,448,537 },
{ 1399, 485,431,508,688 } };
int lo, hi, i;
float frac=0;
for (lo=4; --lo; )
if (*mul[lo] <= temp) break;
for (hi=0; hi < 3; hi++)
if (*mul[hi] >= temp) break;
if (lo != hi)
frac = (float) (temp - *mul[lo]) / (*mul[hi] - *mul[lo]);
for (i=1; i < 5; i++)
pre_mul[i-1] = 1 / (frac * mul[hi][i] + (1-frac) * mul[lo][i]);
}
/* Return values: 0 = white 1 = near white 2 = not white */
int CLASS canon_600_color (int ratio[2], int mar)
{
int clipped=0, target, miss;
if (flash_used) {
if (ratio[1] < -104)
{ ratio[1] = -104; clipped = 1; }
if (ratio[1] > 12)
{ ratio[1] = 12; clipped = 1; }
} else {
if (ratio[1] < -264 || ratio[1] > 461) return 2;
if (ratio[1] < -50)
{ ratio[1] = -50; clipped = 1; }
if (ratio[1] > 307)
{ ratio[1] = 307; clipped = 1; }
}
target = flash_used || ratio[1] < 197
? -38 - (398 * ratio[1] >> 10)
: -123 + (48 * ratio[1] >> 10);
if (target - mar <= ratio[0] &&
target + 20 >= ratio[0] && !clipped) return 0;
miss = target - ratio[0];
if (abs(miss) >= mar*4) return 2;
if (miss < -20) miss = -20;
if (miss > mar) miss = mar;
ratio[0] = target - miss;
return 1;
}
void CLASS canon_600_auto_wb()
{
int mar, row, col, i, j, st, count[] = { 0,0 };
int test[8], total[2][8], ratio[2][2], stat[2];
memset (&total, 0, sizeof total);
i = canon_ev + 0.5;
if (i < 10) mar = 150;
else if (i > 12) mar = 20;
else mar = 280 - 20 * i;
if (flash_used) mar = 80;
for (row=14; row < height-14; row+=4)
for (col=10; col < width; col+=2) {
for (i=0; i < 8; i++)
test[(i & 4) + FC(row+(i >> 1),col+(i & 1))] =
BAYER(row+(i >> 1),col+(i & 1));
for (i=0; i < 8; i++)
if (test[i] < 150 || test[i] > 1500) goto next;
for (i=0; i < 4; i++)
if (abs(test[i] - test[i+4]) > 50) goto next;
for (i=0; i < 2; i++) {
for (j=0; j < 4; j+=2)
ratio[i][j >> 1] = ((test[i*4+j+1]-test[i*4+j]) << 10) / test[i*4+j];
stat[i] = canon_600_color (ratio[i], mar);
}
if ((st = stat[0] | stat[1]) > 1) goto next;
for (i=0; i < 2; i++)
if (stat[i])
for (j=0; j < 2; j++)
test[i*4+j*2+1] = test[i*4+j*2] * (0x400 + ratio[i][j]) >> 10;
for (i=0; i < 8; i++)
total[st][i] += test[i];
count[st]++;
next: ;
}
if (count[0] | count[1]) {
st = count[0]*200 < count[1];
for (i=0; i < 4; i++)
pre_mul[i] = 1.0 / (total[st][i] + total[st][i+4]);
}
}
void CLASS canon_600_coeff()
{
static const short table[6][12] = {
{ -190,702,-1878,2390, 1861,-1349,905,-393, -432,944,2617,-2105 },
{ -1203,1715,-1136,1648, 1388,-876,267,245, -1641,2153,3921,-3409 },
{ -615,1127,-1563,2075, 1437,-925,509,3, -756,1268,2519,-2007 },
{ -190,702,-1886,2398, 2153,-1641,763,-251, -452,964,3040,-2528 },
{ -190,702,-1878,2390, 1861,-1349,905,-393, -432,944,2617,-2105 },
{ -807,1319,-1785,2297, 1388,-876,769,-257, -230,742,2067,-1555 } };
int t=0, i, c;
float mc, yc;
mc = pre_mul[1] / pre_mul[2];
yc = pre_mul[3] / pre_mul[2];
if (mc > 1 && mc <= 1.28 && yc < 0.8789) t=1;
if (mc > 1.28 && mc <= 2) {
if (yc < 0.8789) t=3;
else if (yc <= 2) t=4;
}
if (flash_used) t=5;
for (raw_color = i=0; i < 3; i++)
FORCC rgb_cam[i][c] = table[t][i*4 + c] / 1024.0;
}
void CLASS canon_600_load_raw()
{
uchar data[1120], *dp;
ushort *pix;
int irow, row;
for (irow=row=0; irow < height; irow++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread (data, 1, 1120, ifp) < 1120) derror();
pix = raw_image + row*raw_width;
for (dp=data; dp < data+1120; dp+=10, pix+=8) {
pix[0] = (dp[0] << 2) + (dp[1] >> 6 );
pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3);
pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3);
pix[3] = (dp[4] << 2) + (dp[1] & 3);
pix[4] = (dp[5] << 2) + (dp[9] & 3);
pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3);
pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3);
pix[7] = (dp[8] << 2) + (dp[9] >> 6 );
}
if ((row+=2) > height) row = 1;
}
}
void CLASS canon_600_correct()
{
int row, col, val;
static const short mul[4][2] =
{ { 1141,1145 }, { 1128,1109 }, { 1178,1149 }, { 1128,1109 } };
for (row=0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col++) {
if ((val = BAYER(row,col) - black) < 0) val = 0;
val = val * mul[row & 3][col & 1] >> 9;
BAYER(row,col) = val;
}
}
canon_600_fixed_wb(1311);
canon_600_auto_wb();
canon_600_coeff();
maximum = (0x3ff - black) * 1109 >> 9;
black = 0;
}
int CLASS canon_s2is()
{
unsigned row;
for (row=0; row < 100; row++) {
fseek (ifp, row*3340 + 3284, SEEK_SET);
if (getc(ifp) > 15) return 1;
}
return 0;
}
unsigned CLASS getbithuff (int nbits, ushort *huff)
{
#ifdef LIBRAW_NOTHREADS
static unsigned bitbuf=0;
static int vbits=0, reset=0;
#else
#define bitbuf tls->getbits.bitbuf
#define vbits tls->getbits.vbits
#define reset tls->getbits.reset
#endif
unsigned c;
if (nbits > 25) return 0;
if (nbits < 0)
return bitbuf = vbits = reset = 0;
if (nbits == 0 || vbits < 0) return 0;
while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF &&
!(reset = zero_after_ff && c == 0xff && fgetc(ifp))) {
bitbuf = (bitbuf << 8) + (uchar) c;
vbits += 8;
}
c = bitbuf << (32-vbits) >> (32-nbits);
if (huff) {
vbits -= huff[c] >> 8;
c = (uchar) huff[c];
} else
vbits -= nbits;
if (vbits < 0) derror();
return c;
#ifndef LIBRAW_NOTHREADS
#undef bitbuf
#undef vbits
#undef reset
#endif
}
#define getbits(n) getbithuff(n,0)
#define gethuff(h) getbithuff(*h,h+1)
/*
Construct a decode tree according the specification in *source.
The first 16 bytes specify how many codes should be 1-bit, 2-bit
3-bit, etc. Bytes after that are the leaf values.
For example, if the source is
{ 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff },
then the code is
00 0x04
010 0x03
011 0x05
100 0x06
101 0x02
1100 0x07
1101 0x01
11100 0x08
11101 0x09
11110 0x00
111110 0x0a
1111110 0x0b
1111111 0xff
*/
ushort * CLASS make_decoder_ref (const uchar **source)
{
int max, len, h, i, j;
const uchar *count;
ushort *huff;
count = (*source += 16) - 17;
for (max=16; max && !count[max]; max--);
huff = (ushort *) calloc (1 + (1 << max), sizeof *huff);
merror (huff, "make_decoder()");
huff[0] = max;
for (h=len=1; len <= max; len++)
for (i=0; i < count[len]; i++, ++*source)
for (j=0; j < 1 << (max-len); j++)
if (h <= 1 << max)
huff[h++] = len << 8 | **source;
return huff;
}
ushort * CLASS make_decoder (const uchar *source)
{
return make_decoder_ref (&source);
}
void CLASS crw_init_tables (unsigned table, ushort *huff[2])
{
static const uchar first_tree[3][29] = {
{ 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff },
{ 0,2,2,3,1,1,1,1,2,0,0,0,0,0,0,0,
0x03,0x02,0x04,0x01,0x05,0x00,0x06,0x07,0x09,0x08,0x0a,0x0b,0xff },
{ 0,0,6,3,1,1,2,0,0,0,0,0,0,0,0,0,
0x06,0x05,0x07,0x04,0x08,0x03,0x09,0x02,0x00,0x0a,0x01,0x0b,0xff },
};
static const uchar second_tree[3][180] = {
{ 0,2,2,2,1,4,2,1,2,5,1,1,0,0,0,139,
0x03,0x04,0x02,0x05,0x01,0x06,0x07,0x08,
0x12,0x13,0x11,0x14,0x09,0x15,0x22,0x00,0x21,0x16,0x0a,0xf0,
0x23,0x17,0x24,0x31,0x32,0x18,0x19,0x33,0x25,0x41,0x34,0x42,
0x35,0x51,0x36,0x37,0x38,0x29,0x79,0x26,0x1a,0x39,0x56,0x57,
0x28,0x27,0x52,0x55,0x58,0x43,0x76,0x59,0x77,0x54,0x61,0xf9,
0x71,0x78,0x75,0x96,0x97,0x49,0xb7,0x53,0xd7,0x74,0xb6,0x98,
0x47,0x48,0x95,0x69,0x99,0x91,0xfa,0xb8,0x68,0xb5,0xb9,0xd6,
0xf7,0xd8,0x67,0x46,0x45,0x94,0x89,0xf8,0x81,0xd5,0xf6,0xb4,
0x88,0xb1,0x2a,0x44,0x72,0xd9,0x87,0x66,0xd4,0xf5,0x3a,0xa7,
0x73,0xa9,0xa8,0x86,0x62,0xc7,0x65,0xc8,0xc9,0xa1,0xf4,0xd1,
0xe9,0x5a,0x92,0x85,0xa6,0xe7,0x93,0xe8,0xc1,0xc6,0x7a,0x64,
0xe1,0x4a,0x6a,0xe6,0xb3,0xf1,0xd3,0xa5,0x8a,0xb2,0x9a,0xba,
0x84,0xa4,0x63,0xe5,0xc5,0xf3,0xd2,0xc4,0x82,0xaa,0xda,0xe4,
0xf2,0xca,0x83,0xa3,0xa2,0xc3,0xea,0xc2,0xe2,0xe3,0xff,0xff },
{ 0,2,2,1,4,1,4,1,3,3,1,0,0,0,0,140,
0x02,0x03,0x01,0x04,0x05,0x12,0x11,0x06,
0x13,0x07,0x08,0x14,0x22,0x09,0x21,0x00,0x23,0x15,0x31,0x32,
0x0a,0x16,0xf0,0x24,0x33,0x41,0x42,0x19,0x17,0x25,0x18,0x51,
0x34,0x43,0x52,0x29,0x35,0x61,0x39,0x71,0x62,0x36,0x53,0x26,
0x38,0x1a,0x37,0x81,0x27,0x91,0x79,0x55,0x45,0x28,0x72,0x59,
0xa1,0xb1,0x44,0x69,0x54,0x58,0xd1,0xfa,0x57,0xe1,0xf1,0xb9,
0x49,0x47,0x63,0x6a,0xf9,0x56,0x46,0xa8,0x2a,0x4a,0x78,0x99,
0x3a,0x75,0x74,0x86,0x65,0xc1,0x76,0xb6,0x96,0xd6,0x89,0x85,
0xc9,0xf5,0x95,0xb4,0xc7,0xf7,0x8a,0x97,0xb8,0x73,0xb7,0xd8,
0xd9,0x87,0xa7,0x7a,0x48,0x82,0x84,0xea,0xf4,0xa6,0xc5,0x5a,
0x94,0xa4,0xc6,0x92,0xc3,0x68,0xb5,0xc8,0xe4,0xe5,0xe6,0xe9,
0xa2,0xa3,0xe3,0xc2,0x66,0x67,0x93,0xaa,0xd4,0xd5,0xe7,0xf8,
0x88,0x9a,0xd7,0x77,0xc4,0x64,0xe2,0x98,0xa5,0xca,0xda,0xe8,
0xf3,0xf6,0xa9,0xb2,0xb3,0xf2,0xd2,0x83,0xba,0xd3,0xff,0xff },
{ 0,0,6,2,1,3,3,2,5,1,2,2,8,10,0,117,
0x04,0x05,0x03,0x06,0x02,0x07,0x01,0x08,
0x09,0x12,0x13,0x14,0x11,0x15,0x0a,0x16,0x17,0xf0,0x00,0x22,
0x21,0x18,0x23,0x19,0x24,0x32,0x31,0x25,0x33,0x38,0x37,0x34,
0x35,0x36,0x39,0x79,0x57,0x58,0x59,0x28,0x56,0x78,0x27,0x41,
0x29,0x77,0x26,0x42,0x76,0x99,0x1a,0x55,0x98,0x97,0xf9,0x48,
0x54,0x96,0x89,0x47,0xb7,0x49,0xfa,0x75,0x68,0xb6,0x67,0x69,
0xb9,0xb8,0xd8,0x52,0xd7,0x88,0xb5,0x74,0x51,0x46,0xd9,0xf8,
0x3a,0xd6,0x87,0x45,0x7a,0x95,0xd5,0xf6,0x86,0xb4,0xa9,0x94,
0x53,0x2a,0xa8,0x43,0xf5,0xf7,0xd4,0x66,0xa7,0x5a,0x44,0x8a,
0xc9,0xe8,0xc8,0xe7,0x9a,0x6a,0x73,0x4a,0x61,0xc7,0xf4,0xc6,
0x65,0xe9,0x72,0xe6,0x71,0x91,0x93,0xa6,0xda,0x92,0x85,0x62,
0xf3,0xc5,0xb2,0xa4,0x84,0xba,0x64,0xa5,0xb3,0xd2,0x81,0xe5,
0xd3,0xaa,0xc4,0xca,0xf2,0xb1,0xe4,0xd1,0x83,0x63,0xea,0xc3,
0xe2,0x82,0xf1,0xa3,0xc2,0xa1,0xc1,0xe3,0xa2,0xe1,0xff,0xff }
};
if (table > 2) table = 2;
huff[0] = make_decoder ( first_tree[table]);
huff[1] = make_decoder (second_tree[table]);
}
/*
Return 0 if the image starts with compressed data,
1 if it starts with uncompressed low-order bits.
In Canon compressed data, 0xff is always followed by 0x00.
*/
int CLASS canon_has_lowbits()
{
uchar test[0x4000];
int ret=1, i;
fseek (ifp, 0, SEEK_SET);
fread (test, 1, sizeof test, ifp);
for (i=540; i < sizeof test - 1; i++)
if (test[i] == 0xff) {
if (test[i+1]) return 1;
ret=0;
}
return ret;
}
void CLASS canon_load_raw()
{
ushort *pixel, *prow, *huff[2];
int nblocks, lowbits, i, c, row, r, save, val;
int block, diffbuf[64], leaf, len, diff, carry=0, pnum=0, base[2];
crw_init_tables (tiff_compress, huff);
lowbits = canon_has_lowbits();
if (!lowbits) maximum = 0x3ff;
fseek (ifp, 540 + lowbits*raw_height*raw_width/4, SEEK_SET);
zero_after_ff = 1;
getbits(-1);
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (row=0; row < raw_height; row+=8) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
pixel = raw_image + row*raw_width;
nblocks = MIN (8, raw_height-row) * raw_width >> 6;
for (block=0; block < nblocks; block++) {
memset (diffbuf, 0, sizeof diffbuf);
for (i=0; i < 64; i++ ) {
leaf = gethuff(huff[i > 0]);
if (leaf == 0 && i) break;
if (leaf == 0xff) continue;
i += leaf >> 4;
len = leaf & 15;
if (len == 0) continue;
diff = getbits(len);
if ((diff & (1 << (len-1))) == 0)
diff -= (1 << len) - 1;
if (i < 64) diffbuf[i] = diff;
}
diffbuf[0] += carry;
carry = diffbuf[0];
for (i=0; i < 64; i++ ) {
if (pnum++ % raw_width == 0)
base[0] = base[1] = 512;
if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10)
derror();
}
}
if (lowbits) {
save = ftell(ifp);
fseek (ifp, 26 + row*raw_width/4, SEEK_SET);
for (prow=pixel, i=0; i < raw_width*2; i++) {
c = fgetc(ifp);
for (r=0; r < 8; r+=2, prow++) {
val = (*prow << 2) + ((c >> r) & 3);
if (raw_width == 2672 && val < 512) val += 2;
*prow = val;
}
}
fseek (ifp, save, SEEK_SET);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...) {
FORC(2) free (huff[c]);
throw;
}
#endif
FORC(2) free (huff[c]);
}
//@end COMMON
/*
Not a full implementation of Lossless JPEG, just
enough to decode Canon, Kodak and Adobe DNG images.
*/
struct jhead {
int bits, high, wide, clrs, sraw, psv, restart, vpred[6];
ushort *huff[6], *free[4], *row;
};
//@out COMMON
int CLASS ljpeg_start (struct jhead *jh, int info_only)
{
int c, tag, len;
uchar data[0x10000];
const uchar *dp;
memset (jh, 0, sizeof *jh);
jh->restart = INT_MAX;
fread (data, 2, 1, ifp);
if (data[1] != 0xd8) return 0;
do {
fread (data, 2, 2, ifp);
tag = data[0] << 8 | data[1];
len = (data[2] << 8 | data[3]) - 2;
// printf ("\n*** ljpeg_start pos= %llx tag= %x, len= %d", ftell(ifp)-4, tag, len);
if (tag <= 0xff00) return 0;
fread (data, 1, len, ifp);
switch (tag) {
case 0xffc3: // start of frame; lossless, Huffman
jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;
// printf ("\n*** %x: startraw= %d", tag, jh->sraw);
case 0xffc0: // start of frame; baseline jpeg
jh->bits = data[0];
jh->high = data[1] << 8 | data[2];
jh->wide = data[3] << 8 | data[4];
jh->clrs = data[5] + jh->sraw;
if (!strcmp(model, "EOS 5DS"))
{
jh->wide = data[1] << 8 | data[2];
jh->high = data[3] << 8 | data[4];
}
// printf ("\n*** %x: bits= %d; high= %d; wide= %d; clrs= %d",
// tag, jh->bits, jh->high, jh->wide, jh->clrs);
if (len == 9 && !dng_version) getc(ifp);
break;
case 0xffc4: // define Huffman tables
if (info_only) break;
for (dp = data; dp < data+len && (c = *dp++) < 4; )
jh->free[c] = jh->huff[c] = make_decoder_ref (&dp);
break;
case 0xffda: // start of scan
jh->psv = data[1+data[0]*2];
jh->bits -= data[3+data[0]*2] & 15;
break;
case 0xffdd: // define restart interval
jh->restart = data[0] << 8 | data[1];
}
} while (tag != 0xffda);
// printf ("\n");
if (info_only) return 1;
if (jh->clrs > 6 || !jh->huff[0]) return 0;
FORC(5) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c];
if (jh->sraw) {
FORC(4) jh->huff[2+c] = jh->huff[1];
FORC(jh->sraw) jh->huff[1+c] = jh->huff[0];
}
jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4);
merror (jh->row, "ljpeg_start()");
return zero_after_ff = 1;
}
void CLASS ljpeg_end (struct jhead *jh)
{
int c;
FORC4 if (jh->free[c]) free (jh->free[c]);
free (jh->row);
}
int CLASS ljpeg_diff (ushort *huff)
{
int len, diff;
if(!huff)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp (failure, 2);
#endif
len = gethuff(huff);
if (len == 16 && (!dng_version || dng_version >= 0x1010000))
return -32768;
diff = getbits(len);
if ((diff & (1 << (len-1))) == 0)
diff -= (1 << len) - 1;
return diff;
}
ushort * CLASS ljpeg_row (int jrow, struct jhead *jh)
{
int col, c, diff, pred, spred=0;
ushort mark=0, *row[3];
if (jrow * jh->wide % jh->restart == 0) {
FORC(6) jh->vpred[c] = 1 << (jh->bits-1);
if (jrow) {
fseek (ifp, -2, SEEK_CUR);
do mark = (mark << 8) + (c = fgetc(ifp));
while (c != EOF && mark >> 4 != 0xffd);
}
getbits(-1);
}
FORC3 row[c] = jh->row + jh->wide*jh->clrs*((jrow+c) & 1);
for (col=0; col < jh->wide; col++)
FORC(jh->clrs) {
diff = ljpeg_diff (jh->huff[c]);
if (jh->sraw && c <= jh->sraw && (col | c))
pred = spred;
else if (col) pred = row[0][-jh->clrs];
else pred = (jh->vpred[c] += diff) - diff;
if (jrow && col) switch (jh->psv) {
case 1: break;
case 2: pred = row[1][0]; break;
case 3: pred = row[1][-jh->clrs]; break;
case 4: pred = pred + row[1][0] - row[1][-jh->clrs]; break;
case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1); break;
case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1); break;
case 7: pred = (pred + row[1][0]) >> 1; break;
default: pred = 0;
}
if ((**row = pred + diff) >> jh->bits) derror();
if (c <= jh->sraw) spred = **row;
row[0]++; row[1]++;
}
return row[2];
}
void CLASS lossless_jpeg_load_raw()
{
int jwide, jrow, jcol, val, jidx, i, j, row=0, col=0;
struct jhead jh;
ushort *rp;
// printf ("\n*** lossless_jpeg_load_raw\n");
if (!ljpeg_start (&jh, 0)) return;
if(jh.wide<1 || jh.high<1 || jh.clrs<1 || jh.bits <1)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp (failure, 2);
#endif
jwide = jh.wide * jh.clrs;
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (jrow=0; jrow < jh.high; jrow++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
rp = ljpeg_row (jrow, &jh);
if (load_flags & 1)
row = jrow & 1 ? height-1-jrow/2 : jrow/2;
for (jcol=0; jcol < jwide; jcol++) {
val = curve[*rp++];
if (cr2_slice[0]) {
jidx = jrow*jwide + jcol;
i = jidx / (cr2_slice[1]*jh.high);
if ((j = i >= cr2_slice[0]))
i = cr2_slice[0];
jidx -= i * (cr2_slice[1]*jh.high);
row = jidx / cr2_slice[1+j];
col = jidx % cr2_slice[1+j] + i*cr2_slice[1];
}
if (raw_width == 3984 && (col -= 2) < 0)
col += (row--,raw_width);
if(row>raw_height)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp (failure, 3);
#endif
if ((unsigned) row < raw_height) RAW(row,col) = val;
if (++col >= raw_width)
col = (row++,0);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...) {
ljpeg_end (&jh);
throw;
}
#endif
ljpeg_end (&jh);
}
void CLASS canon_sraw_load_raw()
{
struct jhead jh;
short *rp=0, (*ip)[4];
int jwide, slice, scol, ecol, row, col, jrow=0, jcol=0, pix[3], c;
int v[3]={0,0,0}, ver, hue;
char *cp;
if (!ljpeg_start (&jh, 0) || jh.clrs < 4) return;
jwide = (jh.wide >>= 1) * jh.clrs;
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (ecol=slice=0; slice <= cr2_slice[0]; slice++) {
scol = ecol;
ecol += cr2_slice[1] * 2 / jh.clrs;
if (!cr2_slice[0] || ecol > raw_width-1) ecol = raw_width & -2;
for (row=0; row < height; row += (jh.clrs >> 1) - 1) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
ip = (short (*)[4]) image + row*width;
for (col=scol; col < ecol; col+=2, jcol+=jh.clrs) {
if ((jcol %= jwide) == 0)
rp = (short *) ljpeg_row (jrow++, &jh);
if (col >= width) continue;
#ifdef LIBRAW_LIBRARY_BUILD
if(imgdata.params.sraw_ycc>=2)
{
FORC (jh.clrs-2)
{
ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c];
ip[col + (c >> 1)*width + (c & 1)][1] = ip[col + (c >> 1)*width + (c & 1)][2] = 8192;
}
ip[col][1] = rp[jcol+jh.clrs-2] - 8192;
ip[col][2] = rp[jcol+jh.clrs-1] - 8192;
}
else if(imgdata.params.sraw_ycc)
{
FORC (jh.clrs-2)
ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c];
ip[col][1] = rp[jcol+jh.clrs-2] - 8192;
ip[col][2] = rp[jcol+jh.clrs-1] - 8192;
}
else
#endif
{
FORC (jh.clrs-2)
ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c];
ip[col][1] = rp[jcol+jh.clrs-2] - 16384;
ip[col][2] = rp[jcol+jh.clrs-1] - 16384;
}
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...) {
ljpeg_end (&jh);
throw ;
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
if(imgdata.params.sraw_ycc>=2)
{
ljpeg_end (&jh);
maximum = 0x3fff;
return;
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (cp=model2; *cp && !isdigit(*cp); cp++);
sscanf (cp, "%d.%d.%d", v, v+1, v+2);
ver = (v[0]*1000 + v[1])*1000 + v[2];
hue = (jh.sraw+1) << 2;
if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006))
hue = jh.sraw << 1;
ip = (short (*)[4]) image;
rp = ip[0];
for (row=0; row < height; row++, ip+=width) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (row & (jh.sraw >> 1))
for (col=0; col < width; col+=2)
for (c=1; c < 3; c++)
if (row == height-1)
ip[col][c] = ip[col-width][c];
else ip[col][c] = (ip[col-width][c] + ip[col+width][c] + 1) >> 1;
for (col=1; col < width; col+=2)
for (c=1; c < 3; c++)
if (col == width-1)
ip[col][c] = ip[col-1][c];
else ip[col][c] = (ip[col-1][c] + ip[col+1][c] + 1) >> 1;
}
#ifdef LIBRAW_LIBRARY_BUILD
if(!imgdata.params.sraw_ycc)
#endif
for ( ; rp < ip[0]; rp+=4) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (unique_id == 0x80000218 ||
unique_id == 0x80000250 ||
unique_id == 0x80000261 ||
unique_id == 0x80000281 ||
unique_id == 0x80000287) {
rp[1] = (rp[1] << 2) + hue;
rp[2] = (rp[2] << 2) + hue;
pix[0] = rp[0] + (( 50*rp[1] + 22929*rp[2]) >> 14);
pix[1] = rp[0] + ((-5640*rp[1] - 11751*rp[2]) >> 14);
pix[2] = rp[0] + ((29040*rp[1] - 101*rp[2]) >> 14);
} else {
if (unique_id < 0x80000218) rp[0] -= 512;
pix[0] = rp[0] + rp[2];
pix[2] = rp[0] + rp[1];
pix[1] = rp[0] + ((-778*rp[1] - (rp[2] << 11)) >> 12);
}
FORC3 rp[c] = CLIP(pix[c] * sraw_mul[c] >> 10);
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...) {
ljpeg_end (&jh);
throw ;
}
#endif
ljpeg_end (&jh);
maximum = 0x3fff;
}
void CLASS adobe_copy_pixel (unsigned row, unsigned col, ushort **rp)
{
int c;
if (is_raw == 2 && shot_select) (*rp)++;
if (raw_image) {
if (row < raw_height && col < raw_width)
RAW(row,col) = curve[**rp];
*rp += is_raw;
} else {
if (row < height && col < width)
FORC(tiff_samples)
image[row*width+col][c] = curve[(*rp)[c]];
*rp += tiff_samples;
}
if (is_raw == 2 && shot_select) (*rp)--;
}
void CLASS lossless_dng_load_raw()
{
unsigned save, trow=0, tcol=0, jwide, jrow, jcol, row, col;
struct jhead jh;
ushort *rp;
while (trow < raw_height) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
save = ftell(ifp);
if (tile_length < INT_MAX)
fseek (ifp, get4(), SEEK_SET);
if (!ljpeg_start (&jh, 0)) break;
jwide = jh.wide;
if (filters) jwide *= jh.clrs;
jwide /= is_raw;
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (row=col=jrow=0; jrow < jh.high; jrow++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
rp = ljpeg_row (jrow, &jh);
for (jcol=0; jcol < jwide; jcol++) {
adobe_copy_pixel (trow+row, tcol+col, &rp);
if (++col >= tile_width || col >= raw_width)
row += 1 + (col = 0);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...) {
ljpeg_end (&jh);
throw ;
}
#endif
fseek (ifp, save+4, SEEK_SET);
if ((tcol += tile_width) >= raw_width)
trow += tile_length + (tcol = 0);
ljpeg_end (&jh);
}
}
void CLASS packed_dng_load_raw()
{
ushort *pixel, *rp;
int row, col;
pixel = (ushort *) calloc (raw_width, tiff_samples*sizeof *pixel);
merror (pixel, "packed_dng_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (row=0; row < raw_height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (tiff_bps == 16)
read_shorts (pixel, raw_width * tiff_samples);
else {
getbits(-1);
for (col=0; col < raw_width * tiff_samples; col++)
pixel[col] = getbits(tiff_bps);
}
for (rp=pixel, col=0; col < raw_width; col++)
adobe_copy_pixel (row, col, &rp);
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...) {
free (pixel);
throw ;
}
#endif
free (pixel);
}
void CLASS pentax_load_raw()
{
ushort bit[2][15], huff[4097];
int dep, row, col, diff, c, i;
ushort vpred[2][2] = {{0,0},{0,0}}, hpred[2];
fseek (ifp, meta_offset, SEEK_SET);
dep = (get2() + 12) & 15;
fseek (ifp, 12, SEEK_CUR);
FORC(dep) bit[0][c] = get2();
FORC(dep) bit[1][c] = fgetc(ifp);
FORC(dep)
for (i=bit[0][c]; i <= ((bit[0][c]+(4096 >> bit[1][c])-1) & 4095); )
huff[++i] = bit[1][c] << 8 | c;
huff[0] = 12;
fseek (ifp, data_offset, SEEK_SET);
getbits(-1);
for (row=0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < raw_width; col++) {
diff = ljpeg_diff (huff);
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
RAW(row,col) = hpred[col & 1];
if (hpred[col & 1] >> tiff_bps) derror();
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS nikon_coolscan_load_raw()
{
int bufsize = width*3*tiff_bps/8;
if(tiff_bps <= 8)
gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,255);
else
gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,65535);
fseek (ifp, data_offset, SEEK_SET);
unsigned char *buf = (unsigned char*)malloc(bufsize);
unsigned short *ubuf = (unsigned short *)buf;
for(int row = 0; row < raw_height; row++)
{
int red = fread (buf, 1, bufsize, ifp);
unsigned short (*ip)[4] = (unsigned short (*)[4]) image + row*width;
if(tiff_bps <= 8)
for(int col=0; col<width;col++)
{
ip[col][0] = curve[buf[col*3]];
ip[col][1] = curve[buf[col*3+1]];
ip[col][2] = curve[buf[col*3+2]];
ip[col][3]=0;
}
else
for(int col=0; col<width;col++)
{
ip[col][0] = curve[ubuf[col*3]];
ip[col][1] = curve[ubuf[col*3+1]];
ip[col][2] = curve[ubuf[col*3+2]];
ip[col][3]=0;
}
}
free(buf);
}
#endif
void CLASS nikon_load_raw()
{
static const uchar nikon_tree[][32] = {
{ 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy */
5,4,3,6,2,7,1,0,8,9,11,10,12 },
{ 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy after split */
0x39,0x5a,0x38,0x27,0x16,5,4,3,2,1,0,11,12,12 },
{ 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, /* 12-bit lossless */
5,4,6,3,7,2,8,1,9,0,10,11,12 },
{ 0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0, /* 14-bit lossy */
5,6,4,7,8,3,9,2,1,0,10,11,12,13,14 },
{ 0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0, /* 14-bit lossy after split */
8,0x5c,0x4b,0x3a,0x29,7,6,5,4,3,2,1,0,13,14 },
{ 0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0, /* 14-bit lossless */
7,6,8,5,9,4,10,3,11,12,2,0,1,13,14 } };
ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize;
int i, min, max, step=0, tree=0, split=0, row, col, len, shl, diff;
fseek (ifp, meta_offset, SEEK_SET);
ver0 = fgetc(ifp);
ver1 = fgetc(ifp);
if (ver0 == 0x49 || ver1 == 0x58)
fseek (ifp, 2110, SEEK_CUR);
if (ver0 == 0x46) tree = 2;
if (tiff_bps == 14) tree += 3;
read_shorts (vpred[0], 4);
max = 1 << tiff_bps & 0x7fff;
if ((csize = get2()) > 1)
step = max / (csize-1);
if (ver0 == 0x44 && ver1 == 0x20 && step > 0) {
for (i=0; i < csize; i++)
curve[i*step] = get2();
for (i=0; i < max; i++)
curve[i] = ( curve[i-i%step]*(step-i%step) +
curve[i-i%step+step]*(i%step) ) / step;
fseek (ifp, meta_offset+562, SEEK_SET);
split = get2();
} else if (ver0 != 0x46 && csize <= 0x4001)
read_shorts (curve, max=csize);
while (curve[max-2] == curve[max-1]) max--;
huff = make_decoder (nikon_tree[tree]);
fseek (ifp, data_offset, SEEK_SET);
getbits(-1);
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (min=row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (split && row == split) {
free (huff);
huff = make_decoder (nikon_tree[tree+1]);
max += (min = 16) << 1;
}
for (col=0; col < raw_width; col++) {
i = gethuff(huff);
len = i & 15;
shl = i >> 4;
diff = ((getbits(len-shl) << 1) + 1) << shl >> 1;
if ((diff & (1 << (len-1))) == 0)
diff -= (1 << len) - !shl;
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
if ((ushort)(hpred[col & 1] + min) >= max) derror();
RAW(row,col) = curve[LIM((short)hpred[col & 1],0,0x3fff)];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...) {
free (huff);
throw;
}
#endif
free (huff);
}
void CLASS nikon_yuv_load_raw()
{
int row, col, yuv[4], rgb[3], b, c;
UINT64 bitbuf=0;
for (row=0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < raw_width; col++) {
if (!(b = col & 1)) {
bitbuf = 0;
FORC(6) bitbuf |= (UINT64) fgetc(ifp) << c*8;
FORC(4) yuv[c] = (bitbuf >> c*12 & 0xfff) - (c >> 1 << 11);
}
rgb[0] = yuv[b] + 1.370705*yuv[3];
rgb[1] = yuv[b] - 0.337633*yuv[2] - 0.698001*yuv[3];
rgb[2] = yuv[b] + 1.732446*yuv[2];
FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,0xfff)] / cam_mul[c];
}
}
}
/*
Returns 1 for a Coolpix 995, 0 for anything else.
*/
int CLASS nikon_e995()
{
int i, histo[256];
const uchar often[] = { 0x00, 0x55, 0xaa, 0xff };
memset (histo, 0, sizeof histo);
fseek (ifp, -2000, SEEK_END);
for (i=0; i < 2000; i++)
histo[fgetc(ifp)]++;
for (i=0; i < 4; i++)
if (histo[often[i]] < 200)
return 0;
return 1;
}
/*
Returns 1 for a Coolpix 2100, 0 for anything else.
*/
int CLASS nikon_e2100()
{
uchar t[12];
int i;
fseek (ifp, 0, SEEK_SET);
for (i=0; i < 1024; i++) {
fread (t, 1, 12, ifp);
if (((t[2] & t[4] & t[7] & t[9]) >> 4
& t[1] & t[6] & t[8] & t[11] & 3) != 3)
return 0;
}
return 1;
}
void CLASS nikon_3700()
{
int bits, i;
uchar dp[24];
static const struct {
int bits;
char t_make[12], t_model[15];
} table[] = {
{ 0x00, "Pentax", "Optio 33WR" },
{ 0x03, "Nikon", "E3200" },
{ 0x32, "Nikon", "E3700" },
{ 0x33, "Olympus", "C740UZ" } };
fseek (ifp, 3072, SEEK_SET);
fread (dp, 1, 24, ifp);
bits = (dp[8] & 3) << 4 | (dp[20] & 3);
for (i=0; i < sizeof table / sizeof *table; i++)
if (bits == table[i].bits) {
strcpy (make, table[i].t_make );
strcpy (model, table[i].t_model);
}
}
/*
Separates a Minolta DiMAGE Z2 from a Nikon E4300.
*/
int CLASS minolta_z2()
{
int i, nz;
char tail[424];
fseek (ifp, -sizeof tail, SEEK_END);
fread (tail, 1, sizeof tail, ifp);
for (nz=i=0; i < sizeof tail; i++)
if (tail[i]) nz++;
return nz > 20;
}
//@end COMMON
void CLASS jpeg_thumb();
//@out COMMON
void CLASS ppm_thumb()
{
char *thumb;
thumb_length = thumb_width*thumb_height*3;
thumb = (char *) malloc (thumb_length);
merror (thumb, "ppm_thumb()");
fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
fread (thumb, 1, thumb_length, ifp);
fwrite (thumb, 1, thumb_length, ofp);
free (thumb);
}
void CLASS ppm16_thumb()
{
int i;
char *thumb;
thumb_length = thumb_width*thumb_height*3;
thumb = (char *) calloc (thumb_length, 2);
merror (thumb, "ppm16_thumb()");
read_shorts ((ushort *) thumb, thumb_length);
for (i=0; i < thumb_length; i++)
thumb[i] = ((ushort *) thumb)[i] >> 8;
fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
fwrite (thumb, 1, thumb_length, ofp);
free (thumb);
}
void CLASS layer_thumb()
{
int i, c;
char *thumb, map[][4] = { "012","102" };
colors = thumb_misc >> 5 & 7;
thumb_length = thumb_width*thumb_height;
thumb = (char *) calloc (colors, thumb_length);
merror (thumb, "layer_thumb()");
fprintf (ofp, "P%d\n%d %d\n255\n",
5 + (colors >> 1), thumb_width, thumb_height);
fread (thumb, thumb_length, colors, ifp);
for (i=0; i < thumb_length; i++)
FORCC putc (thumb[i+thumb_length*(map[thumb_misc >> 8][c]-'0')], ofp);
free (thumb);
}
void CLASS rollei_thumb()
{
unsigned i;
ushort *thumb;
thumb_length = thumb_width * thumb_height;
thumb = (ushort *) calloc (thumb_length, 2);
merror (thumb, "rollei_thumb()");
fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
read_shorts (thumb, thumb_length);
for (i=0; i < thumb_length; i++) {
putc (thumb[i] << 3, ofp);
putc (thumb[i] >> 5 << 2, ofp);
putc (thumb[i] >> 11 << 3, ofp);
}
free (thumb);
}
void CLASS rollei_load_raw()
{
uchar pixel[10];
unsigned iten=0, isix, i, buffer=0, todo[16];
isix = raw_width * raw_height * 5 / 8;
while (fread (pixel, 1, 10, ifp) == 10) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (i=0; i < 10; i+=2) {
todo[i] = iten++;
todo[i+1] = pixel[i] << 8 | pixel[i+1];
buffer = pixel[i] >> 2 | buffer << 6;
}
for ( ; i < 16; i+=2) {
todo[i] = isix++;
todo[i+1] = buffer >> (14-i)*5;
}
for (i=0; i < 16; i+=2)
raw_image[todo[i]] = (todo[i+1] & 0x3ff);
}
maximum = 0x3ff;
}
int CLASS raw (unsigned row, unsigned col)
{
return (row < raw_height && col < raw_width) ? RAW(row,col) : 0;
}
void CLASS phase_one_flat_field (int is_float, int nc)
{
ushort head[8];
unsigned wide, high, y, x, c, rend, cend, row, col;
float *mrow, num, mult[4];
read_shorts (head, 8);
if (head[2] * head[3] * head[4] * head[5] == 0) return;
wide = head[2] / head[4] + (head[2] % head[4] != 0);
high = head[3] / head[5] + (head[3] % head[5] != 0);
mrow = (float *) calloc (nc*wide, sizeof *mrow);
merror (mrow, "phase_one_flat_field()");
for (y=0; y < high; y++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (x=0; x < wide; x++)
for (c=0; c < nc; c+=2) {
num = is_float ? getreal(11) : get2()/32768.0;
if (y==0) mrow[c*wide+x] = num;
else mrow[(c+1)*wide+x] = (num - mrow[c*wide+x]) / head[5];
}
if (y==0) continue;
rend = head[1] + y*head[5];
for (row = rend-head[5];
row < raw_height && row < rend &&
row < head[1]+head[3]-head[5]; row++) {
for (x=1; x < wide; x++) {
for (c=0; c < nc; c+=2) {
mult[c] = mrow[c*wide+x-1];
mult[c+1] = (mrow[c*wide+x] - mult[c]) / head[4];
}
cend = head[0] + x*head[4];
for (col = cend-head[4];
col < raw_width &&
col < cend && col < head[0]+head[2]-head[4]; col++) {
c = nc > 2 ? FC(row-top_margin,col-left_margin) : 0;
if (!(c & 1)) {
c = RAW(row,col) * mult[c];
RAW(row,col) = LIM(c,0,65535);
}
for (c=0; c < nc; c+=2)
mult[c] += mult[c+1];
}
}
for (x=0; x < wide; x++)
for (c=0; c < nc; c+=2)
mrow[c*wide+x] += mrow[(c+1)*wide+x];
}
}
free (mrow);
}
int CLASS phase_one_correct()
{
unsigned entries, tag, data, save, col, row, type;
int len, i, j, k, cip, val[4], dev[4], sum, max;
int head[9], diff, mindiff=INT_MAX, off_412=0;
static const signed char dir[12][2] =
{ {-1,-1}, {-1,1}, {1,-1}, {1,1}, {-2,0}, {0,-2}, {0,2}, {2,0},
{-2,-2}, {-2,2}, {2,-2}, {2,2} };
float poly[8], num, cfrac, frac, mult[2], *yval[2];
ushort *xval[2];
int qmult_applied = 0, qlin_applied = 0;
if (half_size || !meta_length) return 0;
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr,_("Phase One correction...\n"));
#endif
fseek (ifp, meta_offset, SEEK_SET);
order = get2();
fseek (ifp, 6, SEEK_CUR);
fseek (ifp, meta_offset+get4(), SEEK_SET);
entries = get4(); get4();
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
while (entries--) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
tag = get4();
len = get4();
data = get4();
save = ftell(ifp);
fseek (ifp, meta_offset+data, SEEK_SET);
if (tag == 0x419) { /* Polynomial curve */
for (get4(), i=0; i < 8; i++)
poly[i] = getreal(11);
poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1;
for (i=0; i < 0x10000; i++) {
num = (poly[5]*i + poly[3])*i + poly[1];
curve[i] = LIM(num,0,65535);
} goto apply; /* apply to right half */
} else if (tag == 0x41a) { /* Polynomial curve */
for (i=0; i < 4; i++)
poly[i] = getreal(11);
for (i=0; i < 0x10000; i++) {
for (num=0, j=4; j--; )
num = num * i + poly[j];
curve[i] = LIM(num+i,0,65535);
} apply: /* apply to whole image */
for (row=0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = (tag & 1)*ph1.split_col; col < raw_width; col++)
RAW(row,col) = curve[RAW(row,col)];
}
} else if (tag == 0x400) { /* Sensor defects */
while ((len -= 8) >= 0) {
col = get2();
row = get2();
type = get2(); get2();
if (col >= raw_width) continue;
if (type == 131 || type == 137) /* Bad column */
for (row=0; row < raw_height; row++)
if (FC(row-top_margin,col-left_margin) == 1) {
for (sum=i=0; i < 4; i++)
sum += val[i] = raw (row+dir[i][0], col+dir[i][1]);
for (max=i=0; i < 4; i++) {
dev[i] = abs((val[i] << 2) - sum);
if (dev[max] < dev[i]) max = i;
}
RAW(row,col) = (sum - val[max])/3.0 + 0.5;
} else {
for (sum=0, i=8; i < 12; i++)
sum += raw (row+dir[i][0], col+dir[i][1]);
RAW(row,col) = 0.5 + sum * 0.0732233 +
(raw(row,col-2) + raw(row,col+2)) * 0.3535534;
}
else if (type == 129) { /* Bad pixel */
if (row >= raw_height) continue;
j = (FC(row-top_margin,col-left_margin) != 1) * 4;
for (sum=0, i=j; i < j+8; i++)
sum += raw (row+dir[i][0], col+dir[i][1]);
RAW(row,col) = (sum + 4) >> 3;
}
}
} else if (tag == 0x401) { /* All-color flat fields */
phase_one_flat_field (1, 2);
} else if (tag == 0x416 || tag == 0x410) {
phase_one_flat_field (0, 2);
} else if (tag == 0x40b) { /* Red+blue flat field */
phase_one_flat_field (0, 4);
} else if (tag == 0x412) {
fseek (ifp, 36, SEEK_CUR);
diff = abs (get2() - ph1.tag_21a);
if (mindiff > diff) {
mindiff = diff;
off_412 = ftell(ifp) - 38;
}
} else if (tag == 0x41f && !qlin_applied) { /* Quadrant linearization */
ushort lc[2][2][16], ref[16];
int qr, qc;
for (qr = 0; qr < 2; qr++)
for (qc = 0; qc < 2; qc++)
for (i = 0; i < 16; i++)
lc[qr][qc][i] = (ushort)get4();
for (i = 0; i < 16; i++) {
int v = 0;
for (qr = 0; qr < 2; qr++)
for (qc = 0; qc < 2; qc++)
v += lc[qr][qc][i];
ref[i] = (v + 2) >> 2;
}
for (qr = 0; qr < 2; qr++) {
for (qc = 0; qc < 2; qc++) {
int cx[19], cf[19];
for (i = 0; i < 16; i++) {
cx[1+i] = lc[qr][qc][i];
cf[1+i] = ref[i];
}
cx[0] = cf[0] = 0;
cx[17] = cf[17] = ((unsigned int)ref[15] * 65535) / lc[qr][qc][15];
cf[18] = cx[18] = 65535;
cubic_spline(cx, cf, 19);
for (row = (qr ? ph1.split_row : 0);
row < (qr ? raw_height : ph1.split_row); row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = (qc ? ph1.split_col : 0);
col < (qc ? raw_width : ph1.split_col); col++)
RAW(row,col) = curve[RAW(row,col)];
}
}
}
qlin_applied = 1;
} else if (tag == 0x41e && !qmult_applied) { /* Quadrant multipliers */
float qmult[2][2] = { { 1, 1 }, { 1, 1 } };
get4(); get4(); get4(); get4();
qmult[0][0] = 1.0 + getreal(11);
get4(); get4(); get4(); get4(); get4();
qmult[0][1] = 1.0 + getreal(11);
get4(); get4(); get4();
qmult[1][0] = 1.0 + getreal(11);
get4(); get4(); get4();
qmult[1][1] = 1.0 + getreal(11);
for (row=0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < raw_width; col++) {
i = qmult[row >= ph1.split_row][col >= ph1.split_col] * RAW(row,col);
RAW(row,col) = LIM(i,0,65535);
}
}
qmult_applied = 1;
} else if (tag == 0x431 && !qmult_applied) { /* Quadrant combined */
ushort lc[2][2][7], ref[7];
int qr, qc;
for (i = 0; i < 7; i++)
ref[i] = (ushort)get4();
for (qr = 0; qr < 2; qr++)
for (qc = 0; qc < 2; qc++)
for (i = 0; i < 7; i++)
lc[qr][qc][i] = (ushort)get4();
for (qr = 0; qr < 2; qr++) {
for (qc = 0; qc < 2; qc++) {
int cx[9], cf[9];
for (i = 0; i < 7; i++) {
cx[1+i] = ref[i];
cf[1+i] = ((unsigned int)ref[i] * lc[qr][qc][i]) / 10000;
}
cx[0] = cf[0] = 0;
cx[8] = cf[8] = 65535;
cubic_spline(cx, cf, 9);
for (row = (qr ? ph1.split_row : 0);
row < (qr ? raw_height : ph1.split_row); row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = (qc ? ph1.split_col : 0);
col < (qc ? raw_width : ph1.split_col); col++)
RAW(row,col) = curve[RAW(row,col)];
}
}
}
qmult_applied = 1;
qlin_applied = 1;
}
fseek (ifp, save, SEEK_SET);
}
if (off_412) {
fseek (ifp, off_412, SEEK_SET);
for (i=0; i < 9; i++) head[i] = get4() & 0x7fff;
yval[0] = (float *) calloc (head[1]*head[3] + head[2]*head[4], 6);
merror (yval[0], "phase_one_correct()");
yval[1] = (float *) (yval[0] + head[1]*head[3]);
xval[0] = (ushort *) (yval[1] + head[2]*head[4]);
xval[1] = (ushort *) (xval[0] + head[1]*head[3]);
get2();
for (i=0; i < 2; i++)
for (j=0; j < head[i+1]*head[i+3]; j++)
yval[i][j] = getreal(11);
for (i=0; i < 2; i++)
for (j=0; j < head[i+1]*head[i+3]; j++)
xval[i][j] = get2();
for (row=0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < raw_width; col++) {
cfrac = (float) col * head[3] / raw_width;
cfrac -= cip = cfrac;
num = RAW(row,col) * 0.5;
for (i=cip; i < cip+2; i++) {
for (k=j=0; j < head[1]; j++)
if (num < xval[0][k = head[1]*i+j]) break;
frac = (j == 0 || j == head[1]) ? 0 :
(xval[0][k] - num) / (xval[0][k] - xval[0][k-1]);
mult[i-cip] = yval[0][k-1] * frac + yval[0][k] * (1-frac);
}
i = ((mult[0] * (1-cfrac) + mult[1] * cfrac) * row + num) * 2;
RAW(row,col) = LIM(i,0,65535);
}
}
free (yval[0]);
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
return LIBRAW_CANCELLED_BY_CALLBACK;
}
#endif
}
void CLASS phase_one_load_raw()
{
int a, b, i;
ushort akey, bkey, t_mask;
fseek (ifp, ph1.key_off, SEEK_SET);
akey = get2();
bkey = get2();
t_mask = ph1.format == 1 ? 0x5555:0x1354;
#ifdef LIBRAW_LIBRARY_BUILD
if (ph1.black_col || ph1.black_row )
{
imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height*2,sizeof(ushort));
merror(imgdata.rawdata.ph1_cblack,"phase_one_load_raw()");
imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width*2,sizeof(ushort));
merror(imgdata.rawdata.ph1_rblack,"phase_one_load_raw()");
if (ph1.black_col)
{
fseek (ifp, ph1.black_col, SEEK_SET);
read_shorts ((ushort *)imgdata.rawdata.ph1_cblack[0], raw_height*2);
}
if (ph1.black_row)
{
fseek (ifp, ph1.black_row, SEEK_SET);
read_shorts ((ushort *) imgdata.rawdata.ph1_rblack[0], raw_width*2);
}
}
#endif
fseek (ifp, data_offset, SEEK_SET);
read_shorts (raw_image, raw_width*raw_height);
if (ph1.format)
for (i=0; i < raw_width*raw_height; i+=2) {
a = raw_image[i+0] ^ akey;
b = raw_image[i+1] ^ bkey;
raw_image[i+0] = (a & t_mask) | (b & ~t_mask);
raw_image[i+1] = (b & t_mask) | (a & ~t_mask);
}
}
unsigned CLASS ph1_bithuff (int nbits, ushort *huff)
{
#ifndef LIBRAW_NOTHREADS
#define bitbuf tls->ph1_bits.bitbuf
#define vbits tls->ph1_bits.vbits
#else
static UINT64 bitbuf=0;
static int vbits=0;
#endif
unsigned c;
if (nbits == -1)
return bitbuf = vbits = 0;
if (nbits == 0) return 0;
if (vbits < nbits) {
bitbuf = bitbuf << 32 | get4();
vbits += 32;
}
c = bitbuf << (64-vbits) >> (64-nbits);
if (huff) {
vbits -= huff[c] >> 8;
return (uchar) huff[c];
}
vbits -= nbits;
return c;
#ifndef LIBRAW_NOTHREADS
#undef bitbuf
#undef vbits
#endif
}
#define ph1_bits(n) ph1_bithuff(n,0)
#define ph1_huff(h) ph1_bithuff(*h,h+1)
void CLASS phase_one_load_raw_c()
{
static const int length[] = { 8,7,6,9,11,10,5,12,14,13 };
int *offset, len[2], pred[2], row, col, i, j;
ushort *pixel;
short (*c_black)[2], (*r_black)[2];
#ifdef LIBRAW_LIBRARY_BUILD
if(ph1.format == 6)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
pixel = (ushort *) calloc (raw_width*3 + raw_height*4, 2);
merror (pixel, "phase_one_load_raw_c()");
offset = (int *) (pixel + raw_width);
fseek (ifp, strip_offset, SEEK_SET);
for (row=0; row < raw_height; row++)
offset[row] = get4();
c_black = (short (*)[2]) (offset + raw_height);
fseek (ifp, ph1.black_col, SEEK_SET);
if (ph1.black_col)
read_shorts ((ushort *) c_black[0], raw_height*2);
r_black = c_black + raw_height;
fseek (ifp, ph1.black_row, SEEK_SET);
if (ph1.black_row)
read_shorts ((ushort *) r_black[0], raw_width*2);
#ifdef LIBRAW_LIBRARY_BUILD
// Copy data to internal copy (ever if not read)
if (ph1.black_col || ph1.black_row )
{
imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height*2,sizeof(ushort));
merror(imgdata.rawdata.ph1_cblack,"phase_one_load_raw_c()");
memmove(imgdata.rawdata.ph1_cblack,(ushort*)c_black[0],raw_height*2*sizeof(ushort));
imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width*2,sizeof(ushort));
merror(imgdata.rawdata.ph1_rblack,"phase_one_load_raw_c()");
memmove(imgdata.rawdata.ph1_rblack,(ushort*)r_black[0],raw_width*2*sizeof(ushort));
}
#endif
for (i=0; i < 256; i++)
curve[i] = i*i / 3.969 + 0.5;
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (row=0; row < raw_height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
fseek (ifp, data_offset + offset[row], SEEK_SET);
ph1_bits(-1);
pred[0] = pred[1] = 0;
for (col=0; col < raw_width; col++) {
if (col >= (raw_width & -8))
len[0] = len[1] = 14;
else if ((col & 7) == 0)
for (i=0; i < 2; i++) {
for (j=0; j < 5 && !ph1_bits(1); j++);
if (j--) len[i] = length[j*2 + ph1_bits(1)];
}
if ((i = len[col & 1]) == 14)
pixel[col] = pred[col & 1] = ph1_bits(16);
else
pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1));
if (pred[col & 1] >> 16) derror();
if (ph1.format == 5 && pixel[col] < 256)
pixel[col] = curve[pixel[col]];
}
for (col=0; col < raw_width; col++) {
#ifndef LIBRAW_LIBRARY_BUILD
i = (pixel[col] << 2) - ph1.t_black
+ c_black[row][col >= ph1.split_col]
+ r_black[col][row >= ph1.split_row];
if (i > 0) RAW(row,col) = i;
#else
RAW(row,col) = pixel[col] << 2;
#endif
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch(...) {
free (pixel);
throw;
}
#endif
free (pixel);
maximum = 0xfffc - ph1.t_black;
}
void CLASS hasselblad_load_raw()
{
struct jhead jh;
int shot, row, col, *back[5], len[2], diff[12], pred, sh, f, s, c;
unsigned upix, urow, ucol;
ushort *ip;
if (!ljpeg_start (&jh, 0)) return;
order = 0x4949;
ph1_bits(-1);
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
back[4] = (int *) calloc (raw_width, 3*sizeof **back);
merror (back[4], "hasselblad_load_raw()");
FORC3 back[c] = back[4] + c*raw_width;
cblack[6] >>= sh = tiff_samples > 1;
shot = LIM(shot_select, 1, tiff_samples) - 1;
for (row=0; row < raw_height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
FORC4 back[(c+3) & 3] = back[c];
for (col=0; col < raw_width; col+=2) {
for (s=0; s < tiff_samples*2; s+=2) {
FORC(2) len[c] = ph1_huff(jh.huff[0]);
FORC(2) {
diff[s+c] = ph1_bits(len[c]);
if ((diff[s+c] & (1 << (len[c]-1))) == 0)
diff[s+c] -= (1 << len[c]) - 1;
if (diff[s+c] == 65535) diff[s+c] = -32768;
}
}
for (s=col; s < col+2; s++) {
pred = 0x8000 + load_flags;
if (col) pred = back[2][s-2];
if (col && row > 1) switch (jh.psv) {
case 11: pred += back[0][s]/2 - back[0][s-2]/2; break;
}
f = (row & 1)*3 ^ ((col+s) & 1);
FORC (tiff_samples) {
pred += diff[(s & 1)*tiff_samples+c];
upix = pred >> sh & 0xffff;
if (raw_image && c == shot)
RAW(row,s) = upix;
if (image) {
urow = row-top_margin + (c & 1);
ucol = col-left_margin - ((c >> 1) & 1);
ip = &image[urow*width+ucol][f];
if (urow < height && ucol < width)
*ip = c < 4 ? upix : (*ip + upix) >> 1;
}
}
back[2][s] = pred;
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...){
free (back[4]);
ljpeg_end (&jh);
throw;
}
#endif
free (back[4]);
ljpeg_end (&jh);
if (image) mix_green = 1;
}
void CLASS leaf_hdr_load_raw()
{
ushort *pixel=0;
unsigned tile=0, r, c, row, col;
if (!filters) {
pixel = (ushort *) calloc (raw_width, sizeof *pixel);
merror (pixel, "leaf_hdr_load_raw()");
}
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
FORC(tiff_samples)
for (r=0; r < raw_height; r++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (r % tile_length == 0) {
fseek (ifp, data_offset + 4*tile++, SEEK_SET);
fseek (ifp, get4(), SEEK_SET);
}
if (filters && c != shot_select) continue;
if (filters) pixel = raw_image + r*raw_width;
read_shorts (pixel, raw_width);
if (!filters && (row = r - top_margin) < height)
for (col=0; col < width; col++)
image[row*width+col][c] = pixel[col+left_margin];
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...) {
if(!filters) free(pixel);
throw;
}
#endif
if (!filters) {
maximum = 0xffff;
raw_color = 1;
free (pixel);
}
}
void CLASS unpacked_load_raw()
{
int row, col, bits=0;
while (1 << ++bits < maximum);
read_shorts (raw_image, raw_width*raw_height);
for (row=0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < raw_width; col++)
if ((RAW(row,col) >>= load_flags) >> bits
&& (unsigned) (row-top_margin) < height
&& (unsigned) (col-left_margin) < width) derror();
}
}
void CLASS sinar_4shot_load_raw()
{
ushort *pixel;
unsigned shot, row, col, r, c;
if (raw_image) {
shot = LIM (shot_select, 1, 4) - 1;
fseek (ifp, data_offset + shot*4, SEEK_SET);
fseek (ifp, get4(), SEEK_SET);
unpacked_load_raw();
return;
}
pixel = (ushort *) calloc (raw_width, sizeof *pixel);
merror (pixel, "sinar_4shot_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (shot=0; shot < 4; shot++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
fseek (ifp, data_offset + shot*4, SEEK_SET);
fseek (ifp, get4(), SEEK_SET);
for (row=0; row < raw_height; row++) {
read_shorts (pixel, raw_width);
if ((r = row-top_margin - (shot >> 1 & 1)) >= height) continue;
for (col=0; col < raw_width; col++) {
if ((c = col-left_margin - (shot & 1)) >= width) continue;
image[r*width+c][(row & 1)*3 ^ (~col & 1)] = pixel[col];
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...) {
free(pixel);
throw;
}
#endif
free (pixel);
mix_green = 1;
}
void CLASS imacon_full_load_raw()
{
int row, col;
if (!image) return;
#ifdef LIBRAW_LIBRARY_BUILD
unsigned short *buf = (unsigned short *)malloc(width*3*sizeof(unsigned short));
merror(buf,"imacon_full_load_raw");
#endif
for (row=0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
read_shorts(buf,width*3);
unsigned short (*rowp)[4] = &image[row*width];
for (col=0; col < width; col++)
{
rowp[col][0]=buf[col*3];
rowp[col][1]=buf[col*3+1];
rowp[col][2]=buf[col*3+2];
rowp[col][3]=0;
}
#else
for (col=0; col < width; col++)
read_shorts (image[row*width+col], 3);
#endif
}
#ifdef LIBRAW_LIBRARY_BUILD
free(buf);
#endif
}
void CLASS packed_load_raw()
{
int vbits=0, bwide, rbits, bite, half, irow, row, col, val, i;
UINT64 bitbuf=0;
bwide = raw_width * tiff_bps / 8;
bwide += bwide & load_flags >> 7;
rbits = bwide * 8 - raw_width * tiff_bps;
if (load_flags & 1) bwide = bwide * 16 / 15;
bite = 8 + (load_flags & 24);
half = (raw_height+1) >> 1;
for (irow=0; irow < raw_height; irow++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
row = irow;
if (load_flags & 2 &&
(row = irow % half * 2 + irow / half) == 1 &&
load_flags & 4) {
if (vbits=0, tiff_compress)
fseek (ifp, data_offset - (-half*bwide & -2048), SEEK_SET);
else {
fseek (ifp, 0, SEEK_END);
fseek (ifp, ftell(ifp) >> 3 << 2, SEEK_SET);
}
}
for (col=0; col < raw_width; col++) {
for (vbits -= tiff_bps; vbits < 0; vbits += bite) {
bitbuf <<= bite;
for (i=0; i < bite; i+=8)
bitbuf |= (unsigned) (fgetc(ifp) << i);
}
val = bitbuf << (64-tiff_bps-vbits) >> (64-tiff_bps);
RAW(row,col ^ (load_flags >> 6 & 1)) = val;
if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) &&
row < height+top_margin && col < width+left_margin) derror();
}
vbits -= rbits;
}
}
void CLASS nokia_load_raw()
{
uchar *data, *dp;
int rev, dwide, row, col, c;
double sum[]={0,0};
rev = 3 * (order == 0x4949);
dwide = (raw_width * 5 + 1) / 4;
data = (uchar *) malloc (dwide*2);
merror (data, "nokia_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (row=0; row < raw_height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread (data+dwide, 1, dwide, ifp) < dwide) derror();
FORC(dwide) data[c] = data[dwide+(c ^ rev)];
for (dp=data, col=0; col < raw_width; dp+=5, col+=4)
FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3);
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...){
free (data);
throw;
}
#endif
free (data);
maximum = 0x3ff;
if (strcmp(make,"OmniVision")) return;
row = raw_height/2;
FORC(width-1) {
sum[ c & 1] += SQR(RAW(row,c)-RAW(row+1,c+1));
sum[~c & 1] += SQR(RAW(row+1,c)-RAW(row,c+1));
}
if (sum[1] > sum[0]) filters = 0x4b4b4b4b;
}
void CLASS android_tight_load_raw()
{
uchar *data, *dp;
int bwide, row, col, c;
bwide = -(-5*raw_width >> 5) << 3;
data = (uchar *) malloc (bwide);
merror (data, "android_tight_load_raw()");
for (row=0; row < raw_height; row++) {
if (fread (data, 1, bwide, ifp) < bwide) derror();
for (dp=data, col=0; col < raw_width; dp+=5, col+=4)
FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3);
}
free (data);
}
void CLASS android_loose_load_raw()
{
uchar *data, *dp;
int bwide, row, col, c;
UINT64 bitbuf=0;
bwide = (raw_width+5)/6 << 3;
data = (uchar *) malloc (bwide);
merror (data, "android_loose_load_raw()");
for (row=0; row < raw_height; row++) {
if (fread (data, 1, bwide, ifp) < bwide) derror();
for (dp=data, col=0; col < raw_width; dp+=8, col+=6) {
FORC(8) bitbuf = (bitbuf << 8) | dp[c^7];
FORC(6) RAW(row,col+c) = (bitbuf >> c*10) & 0x3ff;
}
}
free (data);
}
void CLASS canon_rmf_load_raw()
{
int row, col, bits, orow, ocol, c;
#ifdef LIBRAW_LIBRARY_BUILD
int *words = (int*)malloc(sizeof(int)*(raw_width/3+1));
merror(words,"canon_rmf_load_raw");
#endif
for (row=0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
fread(words,sizeof(int),raw_width/3,ifp);
for (col=0; col < raw_width-2; col+=3)
{
bits = words[col/3];
FORC3 {
orow = row;
if ((ocol = col+c-4) < 0)
{
ocol += raw_width;
if ((orow -= 2) < 0)
orow += raw_height;
}
RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff];
}
}
#else
for (col=0; col < raw_width-2; col+=3) {
bits = get4();
FORC3 {
orow = row;
if ((ocol = col+c-4) < 0) {
ocol += raw_width;
if ((orow -= 2) < 0)
orow += raw_height;
}
RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff];
}
}
#endif
}
#ifdef LIBRAW_LIBRARY_BUILD
free(words);
#endif
maximum = curve[0x3ff];
}
unsigned CLASS pana_bits (int nbits)
{
#ifndef LIBRAW_NOTHREADS
#define buf tls->pana_bits.buf
#define vbits tls->pana_bits.vbits
#else
static uchar buf[0x4000];
static int vbits;
#endif
int byte;
if (!nbits) return vbits=0;
if (!vbits) {
fread (buf+load_flags, 1, 0x4000-load_flags, ifp);
fread (buf, 1, load_flags, ifp);
}
vbits = (vbits - nbits) & 0x1ffff;
byte = vbits >> 3 ^ 0x3ff0;
return (buf[byte] | buf[byte+1] << 8) >> (vbits & 7) & ~((~0u) << nbits);
#ifndef LIBRAW_NOTHREADS
#undef buf
#undef vbits
#endif
}
void CLASS panasonic_load_raw()
{
int row, col, i, j, sh=0, pred[2], nonz[2];
pana_bits(0);
for (row=0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < raw_width; col++) {
if ((i = col % 14) == 0)
pred[0] = pred[1] = nonz[0] = nonz[1] = 0;
if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2));
if (nonz[i & 1]) {
if ((j = pana_bits(8))) {
if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4)
pred[i & 1] &= ~((~0u) << sh);
pred[i & 1] += j << sh;
}
} else if ((nonz[i & 1] = pana_bits(8)) || i > 11)
pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4);
if ((RAW(row,col) = pred[col & 1]) > 4098 && col < width) derror();
}
}
}
void CLASS olympus_load_raw()
{
ushort huff[4096];
int row, col, nbits, sign, low, high, i, c, w, n, nw;
int acarry[2][3], *carry, pred, diff;
huff[n=0] = 0xc0c;
for (i=12; i--; )
FORC(2048 >> i) huff[++n] = (i+1) << 8 | i;
fseek (ifp, 7, SEEK_CUR);
getbits(-1);
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
memset (acarry, 0, sizeof acarry);
for (col=0; col < raw_width; col++) {
carry = acarry[col & 1];
i = 2 * (carry[2] < 3);
for (nbits=2+i; (ushort) carry[0] >> (nbits+i); nbits++);
low = (sign = getbits(3)) & 3;
sign = sign << 29 >> 31;
if ((high = getbithuff(12,huff)) == 12)
high = getbits(16-nbits) >> 1;
carry[0] = (high << nbits) | getbits(nbits);
diff = (carry[0] ^ sign) + carry[1];
carry[1] = (diff*3 + carry[1]) >> 5;
carry[2] = carry[0] > 16 ? 0 : carry[2]+1;
if (col >= width) continue;
if (row < 2 && col < 2) pred = 0;
else if (row < 2) pred = RAW(row,col-2);
else if (col < 2) pred = RAW(row-2,col);
else {
w = RAW(row,col-2);
n = RAW(row-2,col);
nw = RAW(row-2,col-2);
if ((w < nw && nw < n) || (n < nw && nw < w)) {
if (ABS(w-nw) > 32 || ABS(n-nw) > 32)
pred = w + n - nw;
else pred = (w + n) >> 1;
} else pred = ABS(w-nw) > ABS(n-nw) ? w : n;
}
if ((RAW(row,col) = pred + ((diff << 2) | low)) >> 12) derror();
}
}
}
void CLASS minolta_rd175_load_raw()
{
uchar pixel[768];
unsigned irow, box, row, col;
for (irow=0; irow < 1481; irow++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread (pixel, 1, 768, ifp) < 768) derror();
box = irow / 82;
row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box-12)*2);
switch (irow) {
case 1477: case 1479: continue;
case 1476: row = 984; break;
case 1480: row = 985; break;
case 1478: row = 985; box = 1;
}
if ((box < 12) && (box & 1)) {
for (col=0; col < 1533; col++, row ^= 1)
if (col != 1) RAW(row,col) = (col+1) & 2 ?
pixel[col/2-1] + pixel[col/2+1] : pixel[col/2] << 1;
RAW(row,1) = pixel[1] << 1;
RAW(row,1533) = pixel[765] << 1;
} else
for (col=row & 1; col < 1534; col+=2)
RAW(row,col) = pixel[col/2] << 1;
}
maximum = 0xff << 1;
}
void CLASS quicktake_100_load_raw()
{
uchar pixel[484][644];
static const short gstep[16] =
{ -89,-60,-44,-32,-22,-15,-8,-2,2,8,15,22,32,44,60,89 };
static const short rstep[6][4] =
{ { -3,-1,1,3 }, { -5,-1,1,5 }, { -8,-2,2,8 },
{ -13,-3,3,13 }, { -19,-4,4,19 }, { -28,-6,6,28 } };
static const short t_curve[256] =
{ 0,1,2,3,4,5,6,7,8,9,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,
28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,53,
54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78,
79,80,81,82,83,84,86,88,90,92,94,97,99,101,103,105,107,110,112,114,116,
118,120,123,125,127,129,131,134,136,138,140,142,144,147,149,151,153,155,
158,160,162,164,166,168,171,173,175,177,179,181,184,186,188,190,192,195,
197,199,201,203,205,208,210,212,214,216,218,221,223,226,230,235,239,244,
248,252,257,261,265,270,274,278,283,287,291,296,300,305,309,313,318,322,
326,331,335,339,344,348,352,357,361,365,370,374,379,383,387,392,396,400,
405,409,413,418,422,426,431,435,440,444,448,453,457,461,466,470,474,479,
483,487,492,496,500,508,519,531,542,553,564,575,587,598,609,620,631,643,
654,665,676,687,698,710,721,732,743,754,766,777,788,799,810,822,833,844,
855,866,878,889,900,911,922,933,945,956,967,978,989,1001,1012,1023 };
int rb, row, col, sharp, val=0;
getbits(-1);
memset (pixel, 0x80, sizeof pixel);
for (row=2; row < height+2; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=2+(row & 1); col < width+2; col+=2) {
val = ((pixel[row-1][col-1] + 2*pixel[row-1][col+1] +
pixel[row][col-2]) >> 2) + gstep[getbits(4)];
pixel[row][col] = val = LIM(val,0,255);
if (col < 4)
pixel[row][col-2] = pixel[row+1][~row & 1] = val;
if (row == 2)
pixel[row-1][col+1] = pixel[row-1][col+3] = val;
}
pixel[row][col] = val;
}
for (rb=0; rb < 2; rb++)
for (row=2+rb; row < height+2; row+=2)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=3-(row & 1); col < width+2; col+=2) {
if (row < 4 || col < 4) sharp = 2;
else {
val = ABS(pixel[row-2][col] - pixel[row][col-2])
+ ABS(pixel[row-2][col] - pixel[row-2][col-2])
+ ABS(pixel[row][col-2] - pixel[row-2][col-2]);
sharp = val < 4 ? 0 : val < 8 ? 1 : val < 16 ? 2 :
val < 32 ? 3 : val < 48 ? 4 : 5;
}
val = ((pixel[row-2][col] + pixel[row][col-2]) >> 1)
+ rstep[sharp][getbits(2)];
pixel[row][col] = val = LIM(val,0,255);
if (row < 4) pixel[row-2][col+2] = val;
if (col < 4) pixel[row+2][col-2] = val;
}
}
for (row=2; row < height+2; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=3-(row & 1); col < width+2; col+=2) {
val = ((pixel[row][col-1] + (pixel[row][col] << 2) +
pixel[row][col+1]) >> 1) - 0x100;
pixel[row][col] = LIM(val,0,255);
}
}
for (row=0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col++)
RAW(row,col) = t_curve[pixel[row+2][col+2]];
}
maximum = 0x3ff;
}
#define radc_token(tree) ((signed char) getbithuff(8,huff[tree]))
#define FORYX for (y=1; y < 3; y++) for (x=col+1; x >= col; x--)
#define PREDICTOR (c ? (buf[c][y-1][x] + buf[c][y][x+1]) / 2 \
: (buf[c][y-1][x+1] + 2*buf[c][y-1][x] + buf[c][y][x+1]) / 4)
#ifdef __GNUC__
# if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
# pragma GCC optimize("no-aggressive-loop-optimizations")
# endif
#endif
void CLASS kodak_radc_load_raw()
{
static const char src[] = {
1,1, 2,3, 3,4, 4,2, 5,7, 6,5, 7,6, 7,8,
1,0, 2,1, 3,3, 4,4, 5,2, 6,7, 7,6, 8,5, 8,8,
2,1, 2,3, 3,0, 3,2, 3,4, 4,6, 5,5, 6,7, 6,8,
2,0, 2,1, 2,3, 3,2, 4,4, 5,6, 6,7, 7,5, 7,8,
2,1, 2,4, 3,0, 3,2, 3,3, 4,7, 5,5, 6,6, 6,8,
2,3, 3,1, 3,2, 3,4, 3,5, 3,6, 4,7, 5,0, 5,8,
2,3, 2,6, 3,0, 3,1, 4,4, 4,5, 4,7, 5,2, 5,8,
2,4, 2,7, 3,3, 3,6, 4,1, 4,2, 4,5, 5,0, 5,8,
2,6, 3,1, 3,3, 3,5, 3,7, 3,8, 4,0, 5,2, 5,4,
2,0, 2,1, 3,2, 3,3, 4,4, 4,5, 5,6, 5,7, 4,8,
1,0, 2,2, 2,-2,
1,-3, 1,3,
2,-17, 2,-5, 2,5, 2,17,
2,-7, 2,2, 2,9, 2,18,
2,-18, 2,-9, 2,-2, 2,7,
2,-28, 2,28, 3,-49, 3,-9, 3,9, 4,49, 5,-79, 5,79,
2,-1, 2,13, 2,26, 3,39, 4,-16, 5,55, 6,-37, 6,76,
2,-26, 2,-13, 2,1, 3,-39, 4,16, 5,-55, 6,-76, 6,37
};
ushort huff[19][256];
int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val;
short last[3] = { 16,16,16 }, mul[3], buf[3][3][386];
static const ushort pt[] =
{ 0,0, 1280,1344, 2320,3616, 3328,8000, 4095,16383, 65535,16383 };
for (i=2; i < 12; i+=2)
for (c=pt[i-2]; c <= pt[i]; c++)
curve[c] = (float)
(c-pt[i-2]) / (pt[i]-pt[i-2]) * (pt[i+1]-pt[i-1]) + pt[i-1] + 0.5;
for (s=i=0; i < sizeof src; i+=2)
FORC(256 >> src[i])
huff[0][s++] = src[i] << 8 | (uchar) src[i+1];
s = kodak_cbpp == 243 ? 2 : 3;
FORC(256) huff[18][c] = (8-s) << 8 | c >> s << s | 1 << (s-1);
getbits(-1);
for (i=0; i < sizeof(buf)/sizeof(short); i++)
buf[0][0][i] = 2048;
for (row=0; row < height; row+=4) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
FORC3 mul[c] = getbits(6);
FORC3 {
val = ((0x1000000/last[c] + 0x7ff) >> 12) * mul[c];
s = val > 65564 ? 10:12;
x = ~((~0u) << (s-1));
val <<= 12-s;
for (i=0; i < sizeof(buf[0])/sizeof(short); i++)
buf[c][0][i] = (buf[c][0][i] * val + x) >> s;
last[c] = mul[c];
for (r=0; r <= !c; r++) {
buf[c][1][width/2] = buf[c][2][width/2] = mul[c] << 7;
for (tree=1, col=width/2; col > 0; ) {
if ((tree = radc_token(tree))) {
col -= 2;
if (tree == 8)
FORYX buf[c][y][x] = (uchar) radc_token(18) * mul[c];
else
FORYX buf[c][y][x] = radc_token(tree+10) * 16 + PREDICTOR;
} else
do {
nreps = (col > 2) ? radc_token(9) + 1 : 1;
for (rep=0; rep < 8 && rep < nreps && col > 0; rep++) {
col -= 2;
FORYX buf[c][y][x] = PREDICTOR;
if (rep & 1) {
step = radc_token(10) << 4;
FORYX buf[c][y][x] += step;
}
}
} while (nreps == 9);
}
for (y=0; y < 2; y++)
for (x=0; x < width/2; x++) {
val = (buf[c][y+1][x] << 4) / mul[c];
if (val < 0) val = 0;
if (c) RAW(row+y*2+c-1,x*2+2-c) = val;
else RAW(row+r*2+y,x*2+y) = val;
}
memcpy (buf[c][0]+!c, buf[c][2], sizeof buf[c][0]-2*!c);
}
}
for (y=row; y < row+4; y++)
for (x=0; x < width; x++)
if ((x+y) & 1) {
r = x ? x-1 : x+1;
s = x+1 < width ? x+1 : x-1;
val = (RAW(y,x)-2048)*2 + (RAW(y,r)+RAW(y,s))/2;
if (val < 0) val = 0;
RAW(y,x) = val;
}
}
for (i=0; i < height*width; i++)
raw_image[i] = curve[raw_image[i]];
maximum = 0x3fff;
}
#undef FORYX
#undef PREDICTOR
#ifdef NO_JPEG
void CLASS kodak_jpeg_load_raw() {}
void CLASS lossy_dng_load_raw() {}
#else
#ifndef LIBRAW_LIBRARY_BUILD
METHODDEF(boolean)
fill_input_buffer (j_decompress_ptr cinfo)
{
static uchar jpeg_buffer[4096];
size_t nbytes;
nbytes = fread (jpeg_buffer, 1, 4096, ifp);
swab (jpeg_buffer, jpeg_buffer, nbytes);
cinfo->src->next_input_byte = jpeg_buffer;
cinfo->src->bytes_in_buffer = nbytes;
return TRUE;
}
void CLASS kodak_jpeg_load_raw()
{
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
JSAMPARRAY buf;
JSAMPLE (*pixel)[3];
int row, col;
cinfo.err = jpeg_std_error (&jerr);
jpeg_create_decompress (&cinfo);
jpeg_stdio_src (&cinfo, ifp);
cinfo.src->fill_input_buffer = fill_input_buffer;
jpeg_read_header (&cinfo, TRUE);
jpeg_start_decompress (&cinfo);
if ((cinfo.output_width != width ) ||
(cinfo.output_height*2 != height ) ||
(cinfo.output_components != 3 )) {
fprintf (stderr,_("%s: incorrect JPEG dimensions\n"), ifname);
jpeg_destroy_decompress (&cinfo);
longjmp (failure, 3);
}
buf = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE, width*3, 1);
while (cinfo.output_scanline < cinfo.output_height) {
row = cinfo.output_scanline * 2;
jpeg_read_scanlines (&cinfo, buf, 1);
pixel = (JSAMPLE (*)[3]) buf[0];
for (col=0; col < width; col+=2) {
RAW(row+0,col+0) = pixel[col+0][1] << 1;
RAW(row+1,col+1) = pixel[col+1][1] << 1;
RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0];
RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2];
}
}
jpeg_finish_decompress (&cinfo);
jpeg_destroy_decompress (&cinfo);
maximum = 0xff << 1;
}
#else
struct jpegErrorManager {
struct jpeg_error_mgr pub;
};
static void jpegErrorExit (j_common_ptr cinfo)
{
jpegErrorManager* myerr = (jpegErrorManager*) cinfo->err;
throw LIBRAW_EXCEPTION_DECODE_JPEG;
}
// LibRaw's Kodak_jpeg_load_raw
void CLASS kodak_jpeg_load_raw()
{
if(data_size < 1)
throw LIBRAW_EXCEPTION_DECODE_JPEG;
int row, col;
jpegErrorManager jerr;
struct jpeg_decompress_struct cinfo;
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = jpegErrorExit;
unsigned char *jpg_buf = (unsigned char *)malloc(data_size);
merror(jpg_buf,"kodak_jpeg_load_raw");
unsigned char *pixel_buf = (unsigned char*) malloc(width*3);
jpeg_create_decompress (&cinfo);
merror(pixel_buf,"kodak_jpeg_load_raw");
fread(jpg_buf,data_size,1,ifp);
swab ((char*)jpg_buf, (char*)jpg_buf, data_size);
try
{
jpeg_mem_src(&cinfo, jpg_buf, data_size);
int rc = jpeg_read_header(&cinfo, TRUE);
if(rc!=1)
throw LIBRAW_EXCEPTION_DECODE_JPEG;
jpeg_start_decompress (&cinfo);
if ((cinfo.output_width != width ) ||
(cinfo.output_height*2 != height ) ||
(cinfo.output_components != 3 ))
{
throw LIBRAW_EXCEPTION_DECODE_JPEG;
}
unsigned char *buf[1];
buf[0] = pixel_buf;
while (cinfo.output_scanline < cinfo.output_height)
{
checkCancel();
row = cinfo.output_scanline * 2;
jpeg_read_scanlines (&cinfo, buf, 1);
unsigned char (*pixel)[3] = (unsigned char (*)[3]) buf[0];
for (col=0; col < width; col+=2) {
RAW(row+0,col+0) = pixel[col+0][1] << 1;
RAW(row+1,col+1) = pixel[col+1][1] << 1;
RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0];
RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2];
}
}
}
catch (...)
{
jpeg_finish_decompress (&cinfo);
jpeg_destroy_decompress (&cinfo);
free(jpg_buf);
free(pixel_buf);
throw;
}
jpeg_finish_decompress (&cinfo);
jpeg_destroy_decompress (&cinfo);
free(jpg_buf);
free(pixel_buf);
maximum = 0xff << 1;
}
#endif
#ifndef LIBRAW_LIBRARY_BUILD
void CLASS gamma_curve (double pwr, double ts, int mode, int imax);
#endif
void CLASS lossy_dng_load_raw()
{
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
JSAMPARRAY buf;
JSAMPLE (*pixel)[3];
unsigned sorder=order, ntags, opcode, deg, i, j, c;
unsigned save=data_offset-4, trow=0, tcol=0, row, col;
ushort cur[3][256];
double coeff[9], tot;
if (meta_offset) {
fseek (ifp, meta_offset, SEEK_SET);
order = 0x4d4d;
ntags = get4();
while (ntags--) {
opcode = get4(); get4(); get4();
if (opcode != 8)
{ fseek (ifp, get4(), SEEK_CUR); continue; }
fseek (ifp, 20, SEEK_CUR);
if ((c = get4()) > 2) break;
fseek (ifp, 12, SEEK_CUR);
if ((deg = get4()) > 8) break;
for (i=0; i <= deg && i < 9; i++)
coeff[i] = getreal(12);
for (i=0; i < 256; i++) {
for (tot=j=0; j <= deg; j++)
tot += coeff[j] * pow(i/255.0, (int)j);
cur[c][i] = tot*0xffff;
}
}
order = sorder;
} else {
gamma_curve (1/2.4, 12.92, 1, 255);
FORC3 memcpy (cur[c], curve, sizeof cur[0]);
}
cinfo.err = jpeg_std_error (&jerr);
jpeg_create_decompress (&cinfo);
while (trow < raw_height) {
fseek (ifp, save+=4, SEEK_SET);
if (tile_length < INT_MAX)
fseek (ifp, get4(), SEEK_SET);
#ifdef LIBRAW_LIBRARY_BUILD
if(libraw_internal_data.internal_data.input->jpeg_src(&cinfo) == -1)
{
jpeg_destroy_decompress(&cinfo);
throw LIBRAW_EXCEPTION_DECODE_JPEG;
}
#else
jpeg_stdio_src (&cinfo, ifp);
#endif
jpeg_read_header (&cinfo, TRUE);
jpeg_start_decompress (&cinfo);
buf = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.output_width*3, 1);
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
while (cinfo.output_scanline < cinfo.output_height &&
(row = trow + cinfo.output_scanline) < height) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
jpeg_read_scanlines (&cinfo, buf, 1);
pixel = (JSAMPLE (*)[3]) buf[0];
for (col=0; col < cinfo.output_width && tcol+col < width; col++) {
FORC3 image[row*width+tcol+col][c] = cur[c][pixel[col][c]];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch(...) {
jpeg_destroy_decompress (&cinfo);
throw;
}
#endif
jpeg_abort_decompress (&cinfo);
if ((tcol += tile_width) >= raw_width)
trow += tile_length + (tcol = 0);
}
jpeg_destroy_decompress (&cinfo);
maximum = 0xffff;
}
#endif
void CLASS kodak_dc120_load_raw()
{
static const int mul[4] = { 162, 192, 187, 92 };
static const int add[4] = { 0, 636, 424, 212 };
uchar pixel[848];
int row, shift, col;
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread (pixel, 1, 848, ifp) < 848) derror();
shift = row * mul[row & 3] + add[row & 3];
for (col=0; col < width; col++)
RAW(row,col) = (ushort) pixel[(col + shift) % 848];
}
maximum = 0xff;
}
void CLASS eight_bit_load_raw()
{
uchar *pixel;
unsigned row, col;
pixel = (uchar *) calloc (raw_width, sizeof *pixel);
merror (pixel, "eight_bit_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (row=0; row < raw_height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread (pixel, 1, raw_width, ifp) < raw_width) derror();
for (col=0; col < raw_width; col++)
RAW(row,col) = curve[pixel[col]];
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch(...) {
free (pixel);
throw;
}
#endif
free (pixel);
maximum = curve[0xff];
}
void CLASS kodak_c330_load_raw()
{
uchar *pixel;
int row, col, y, cb, cr, rgb[3], c;
pixel = (uchar *) calloc (raw_width, 2*sizeof *pixel);
merror (pixel, "kodak_c330_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread (pixel, raw_width, 2, ifp) < 2) derror();
if (load_flags && (row & 31) == 31)
fseek (ifp, raw_width*32, SEEK_CUR);
for (col=0; col < width; col++) {
y = pixel[col*2];
cb = pixel[(col*2 & -4) | 1] - 128;
cr = pixel[(col*2 & -4) | 3] - 128;
rgb[1] = y - ((cb + cr + 2) >> 2);
rgb[2] = rgb[1] + cb;
rgb[0] = rgb[1] + cr;
FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch(...) {
free (pixel);
throw;
}
#endif
free (pixel);
maximum = curve[0xff];
}
void CLASS kodak_c603_load_raw()
{
uchar *pixel;
int row, col, y, cb, cr, rgb[3], c;
pixel = (uchar *) calloc (raw_width, 3*sizeof *pixel);
merror (pixel, "kodak_c603_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (~row & 1)
if (fread (pixel, raw_width, 3, ifp) < 3) derror();
for (col=0; col < width; col++) {
y = pixel[width*2*(row & 1) + col];
cb = pixel[width + (col & -2)] - 128;
cr = pixel[width + (col & -2)+1] - 128;
rgb[1] = y - ((cb + cr + 2) >> 2);
rgb[2] = rgb[1] + cb;
rgb[0] = rgb[1] + cr;
FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch(...) {
free (pixel);
throw;
}
#endif
free (pixel);
maximum = curve[0xff];
}
void CLASS kodak_262_load_raw()
{
static const uchar kodak_tree[2][26] =
{ { 0,1,5,1,1,2,0,0,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 },
{ 0,3,1,1,1,1,1,2,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 } };
ushort *huff[2];
uchar *pixel;
int *strip, ns, c, row, col, chess, pi=0, pi1, pi2, pred, val;
FORC(2) huff[c] = make_decoder (kodak_tree[c]);
ns = (raw_height+63) >> 5;
pixel = (uchar *) malloc (raw_width*32 + ns*4);
merror (pixel, "kodak_262_load_raw()");
strip = (int *) (pixel + raw_width*32);
order = 0x4d4d;
FORC(ns) strip[c] = get4();
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (row=0; row < raw_height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if ((row & 31) == 0) {
fseek (ifp, strip[row >> 5], SEEK_SET);
getbits(-1);
pi = 0;
}
for (col=0; col < raw_width; col++) {
chess = (row + col) & 1;
pi1 = chess ? pi-2 : pi-raw_width-1;
pi2 = chess ? pi-2*raw_width : pi-raw_width+1;
if (col <= chess) pi1 = -1;
if (pi1 < 0) pi1 = pi2;
if (pi2 < 0) pi2 = pi1;
if (pi1 < 0 && col > 1) pi1 = pi2 = pi-2;
pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1;
pixel[pi] = val = pred + ljpeg_diff (huff[chess]);
if (val >> 8) derror();
val = curve[pixel[pi++]];
RAW(row,col) = val;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch(...) {
free (pixel);
throw;
}
#endif
free (pixel);
FORC(2) free (huff[c]);
}
int CLASS kodak_65000_decode (short *out, int bsize)
{
uchar c, blen[768];
ushort raw[6];
INT64 bitbuf=0;
int save, bits=0, i, j, len, diff;
save = ftell(ifp);
bsize = (bsize + 3) & -4;
for (i=0; i < bsize; i+=2) {
c = fgetc(ifp);
if ((blen[i ] = c & 15) > 12 ||
(blen[i+1] = c >> 4) > 12 ) {
fseek (ifp, save, SEEK_SET);
for (i=0; i < bsize; i+=8) {
read_shorts (raw, 6);
out[i ] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12;
out[i+1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12;
for (j=0; j < 6; j++)
out[i+2+j] = raw[j] & 0xfff;
}
return 1;
}
}
if ((bsize & 7) == 4) {
bitbuf = fgetc(ifp) << 8;
bitbuf += fgetc(ifp);
bits = 16;
}
for (i=0; i < bsize; i++) {
len = blen[i];
if (bits < len) {
for (j=0; j < 32; j+=8)
bitbuf += (INT64) fgetc(ifp) << (bits+(j^8));
bits += 32;
}
diff = bitbuf & (0xffff >> (16-len));
bitbuf >>= len;
bits -= len;
if ((diff & (1 << (len-1))) == 0)
diff -= (1 << len) - 1;
out[i] = diff;
}
return 0;
}
void CLASS kodak_65000_load_raw()
{
short buf[256];
int row, col, len, pred[2], ret, i;
for (row=0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col+=256) {
pred[0] = pred[1] = 0;
len = MIN (256, width-col);
ret = kodak_65000_decode (buf, len);
for (i=0; i < len; i++)
if ((RAW(row,col+i) = curve[ret ? buf[i] :
(pred[i & 1] += buf[i])]) >> 12) derror();
}
}
}
void CLASS kodak_ycbcr_load_raw()
{
short buf[384], *bp;
int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3];
ushort *ip;
if (!image) return;
unsigned int bits = (load_flags && load_flags > 9 && load_flags < 17)?load_flags:10;
for (row=0; row < height; row+=2)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col+=128) {
len = MIN (128, width-col);
kodak_65000_decode (buf, len*3);
y[0][1] = y[1][1] = cb = cr = 0;
for (bp=buf, i=0; i < len; i+=2, bp+=2) {
cb += bp[4];
cr += bp[5];
rgb[1] = -((cb + cr + 2) >> 2);
rgb[2] = rgb[1] + cb;
rgb[0] = rgb[1] + cr;
for (j=0; j < 2; j++)
for (k=0; k < 2; k++) {
if ((y[j][k] = y[j][k^1] + *bp++) >> bits) derror();
ip = image[(row+j)*width + col+i+k];
FORC3 ip[c] = curve[LIM(y[j][k]+rgb[c], 0, 0xfff)];
}
}
}
}
}
void CLASS kodak_rgb_load_raw()
{
short buf[768], *bp;
int row, col, len, c, i, rgb[3],ret;
ushort *ip=image[0];
for (row=0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col+=256) {
len = MIN (256, width-col);
ret = kodak_65000_decode (buf, len*3);
memset (rgb, 0, sizeof rgb);
for (bp=buf, i=0; i < len; i++, ip+=4)
#ifdef LIBRAW_LIBRARY_BUILD
if(load_flags == 12)
{
FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++);
}
else
#endif
FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror();
}
}
}
void CLASS kodak_thumb_load_raw()
{
int row, col;
colors = thumb_misc >> 5;
for (row=0; row < height; row++)
for (col=0; col < width; col++)
read_shorts (image[row*width+col], colors);
maximum = (1 << (thumb_misc & 31)) - 1;
}
void CLASS sony_decrypt (unsigned *data, int len, int start, int key)
{
#ifndef LIBRAW_NOTHREADS
#define pad tls->sony_decrypt.pad
#define p tls->sony_decrypt.p
#else
static unsigned pad[128], p;
#endif
if (start) {
for (p=0; p < 4; p++)
pad[p] = key = key * 48828125 + 1;
pad[3] = pad[3] << 1 | (pad[0]^pad[2]) >> 31;
for (p=4; p < 127; p++)
pad[p] = (pad[p-4]^pad[p-2]) << 1 | (pad[p-3]^pad[p-1]) >> 31;
for (p=0; p < 127; p++)
pad[p] = htonl(pad[p]);
}
while (len--)
{
*data++ ^= pad[p & 127] = pad[(p+1) & 127] ^ pad[(p+65) & 127];
p++;
}
#ifndef LIBRAW_NOTHREADS
#undef pad
#undef p
#endif
}
void CLASS sony_load_raw()
{
uchar head[40];
ushort *pixel;
unsigned i, key, row, col;
fseek (ifp, 200896, SEEK_SET);
fseek (ifp, (unsigned) fgetc(ifp)*4 - 1, SEEK_CUR);
order = 0x4d4d;
key = get4();
fseek (ifp, 164600, SEEK_SET);
fread (head, 1, 40, ifp);
sony_decrypt ((unsigned int *) head, 10, 1, key);
for (i=26; i-- > 22; )
key = key << 8 | head[i];
fseek (ifp, data_offset, SEEK_SET);
for (row=0; row < raw_height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
pixel = raw_image + row*raw_width;
if (fread (pixel, 2, raw_width, ifp) < raw_width) derror();
sony_decrypt ((unsigned int *) pixel, raw_width/2, !row, key);
for (col=0; col < raw_width; col++)
if ((pixel[col] = ntohs(pixel[col])) >> 14) derror();
}
maximum = 0x3ff0;
}
void CLASS sony_arw_load_raw()
{
ushort huff[32770];
static const ushort tab[18] =
{ 0xf11,0xf10,0xe0f,0xd0e,0xc0d,0xb0c,0xa0b,0x90a,0x809,
0x708,0x607,0x506,0x405,0x304,0x303,0x300,0x202,0x201 };
int i, c, n, col, row, sum=0;
huff[0] = 15;
for (n=i=0; i < 18; i++)
FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i];
getbits(-1);
for (col = raw_width; col--; )
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (row=0; row < raw_height+1; row+=2) {
if (row == raw_height) row = 1;
if ((sum += ljpeg_diff(huff)) >> 12) derror();
if (row < height) RAW(row,col) = sum;
}
}
}
void CLASS sony_arw2_load_raw()
{
uchar *data, *dp;
ushort pix[16];
int row, col, val, max, min, imax, imin, sh, bit, i;
data = (uchar *) malloc (raw_width+1);
merror (data, "sony_arw2_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
fread (data, 1, raw_width, ifp);
for (dp=data, col=0; col < raw_width-30; dp+=16) {
max = 0x7ff & (val = sget4(dp));
min = 0x7ff & val >> 11;
imax = 0x0f & val >> 22;
imin = 0x0f & val >> 26;
for (sh=0; sh < 4 && 0x80 << sh <= max-min; sh++);
#ifdef LIBRAW_LIBRARY_BUILD
/* flag checks if outside of loop */
if(imgdata.params.sony_arw2_options == LIBRAW_SONYARW2_NONE
|| imgdata.params.sony_arw2_options == LIBRAW_SONYARW2_DELTATOVALUE
)
{
for (bit=30, i=0; i < 16; i++)
if (i == imax) pix[i] = max;
else if (i == imin) pix[i] = min;
else {
pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min;
if (pix[i] > 0x7ff) pix[i] = 0x7ff;
bit += 7;
}
}
else if(imgdata.params.sony_arw2_options == LIBRAW_SONYARW2_BASEONLY)
{
for (bit=30, i=0; i < 16; i++)
if (i == imax) pix[i] = max;
else if (i == imin) pix[i] = min;
else pix[i]=0;
}
else if(imgdata.params.sony_arw2_options == LIBRAW_SONYARW2_DELTAONLY)
{
for (bit=30, i=0; i < 16; i++)
if (i == imax) pix[i] = 0;
else if (i == imin) pix[i] = 0;
else {
pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min;
if (pix[i] > 0x7ff) pix[i] = 0x7ff;
bit += 7;
}
}
else if(imgdata.params.sony_arw2_options == LIBRAW_SONYARW2_DELTAZEROBASE)
{
for (bit=30, i=0; i < 16; i++)
if (i == imax) pix[i] = 0;
else if (i == imin) pix[i] = 0;
else {
pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh);
if (pix[i] > 0x7ff) pix[i] = 0x7ff;
bit += 7;
}
}
#else
/* unaltered dcraw processing */
for (bit=30, i=0; i < 16; i++)
if (i == imax) pix[i] = max;
else if (i == imin) pix[i] = min;
else {
pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min;
if (pix[i] > 0x7ff) pix[i] = 0x7ff;
bit += 7;
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
if(imgdata.params.sony_arw2_options == LIBRAW_SONYARW2_DELTATOVALUE)
{
for (i=0; i < 16; i++, col+=2)
{
unsigned slope = pix[i] < 1001? 2 : curve[pix[i]<<1]-curve[(pix[i]<<1)-2];
unsigned step = 1 << sh;
RAW(row,col)=curve[pix[i]<<1]>black+imgdata.params.sony_arw2_posterization_thr?
LIM(((slope*step*1000)/(curve[pix[i]<<1]-black)),0,10000):0;
}
}
else
{
for (i=0; i < 16; i++, col+=2)
RAW(row,col) = curve[pix[i] << 1];
}
#else
for (i=0; i < 16; i++, col+=2)
RAW(row,col) = curve[pix[i] << 1] >> 2;
#endif
col -= col & 1 ? 1:31;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch(...) {
free (data);
throw;
}
if(imgdata.params.sony_arw2_options == LIBRAW_SONYARW2_DELTATOVALUE)
maximum=10000;
#endif
free (data);
}
void CLASS samsung_load_raw()
{
int row, col, c, i, dir, op[4], len[4];
order = 0x4949;
for (row=0; row < raw_height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
fseek (ifp, strip_offset+row*4, SEEK_SET);
fseek (ifp, data_offset+get4(), SEEK_SET);
ph1_bits(-1);
FORC4 len[c] = row < 2 ? 7:4;
for (col=0; col < raw_width; col+=16) {
dir = ph1_bits(1);
FORC4 op[c] = ph1_bits(2);
FORC4 switch (op[c]) {
case 3: len[c] = ph1_bits(4); break;
case 2: len[c]--; break;
case 1: len[c]++;
}
for (c=0; c < 16; c+=2) {
i = len[((c & 1) << 1) | (c >> 3)];
RAW(row,col+c) = ((signed) ph1_bits(i) << (32-i) >> (32-i)) +
(dir ? RAW(row+(~c | -2),col+c) : col ? RAW(row,col+(c | -2)) : 128);
if (c == 14) c = -1;
}
}
}
for (row=0; row < raw_height-1; row+=2)
for (col=0; col < raw_width-1; col+=2)
SWAP (RAW(row,col+1), RAW(row+1,col));
}
void CLASS samsung2_load_raw()
{
static const ushort tab[14] =
{ 0x304,0x307,0x206,0x205,0x403,0x600,0x709,
0x80a,0x90b,0xa0c,0xa0d,0x501,0x408,0x402 };
ushort huff[1026], vpred[2][2] = {{0,0},{0,0}}, hpred[2];
int i, c, n, row, col, diff;
huff[0] = 10;
for (n=i=0; i < 14; i++)
FORC(1024 >> (tab[i] >> 8)) huff[++n] = tab[i];
getbits(-1);
for (row=0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < raw_width; col++) {
diff = ljpeg_diff (huff);
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
RAW(row,col) = hpred[col & 1];
if (hpred[col & 1] >> tiff_bps) derror();
}
}
}
void CLASS samsung3_load_raw()
{
int opt, init, mag, pmode, row, tab, col, pred, diff, i, c;
ushort lent[3][2], len[4], *prow[2];
order = 0x4949;
fseek (ifp, 9, SEEK_CUR);
opt = fgetc(ifp);
init = (get2(),get2());
for (row=0; row < raw_height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
fseek (ifp, (data_offset-ftell(ifp)) & 15, SEEK_CUR);
ph1_bits(-1);
mag = 0; pmode = 7;
FORC(6) lent[0][c] = row < 2 ? 7:4;
prow[ row & 1] = &RAW(row-1,1-((row & 1) << 1)); // green
prow[~row & 1] = &RAW(row-2,0); // red and blue
for (tab=0; tab+15 < raw_width; tab+=16) {
if (~opt & 4 && !(tab & 63)) {
i = ph1_bits(2);
mag = i < 3 ? mag-'2'+"204"[i] : ph1_bits(12);
}
if (opt & 2)
pmode = 7 - 4*ph1_bits(1);
else if (!ph1_bits(1))
pmode = ph1_bits(3);
if (opt & 1 || !ph1_bits(1)) {
FORC4 len[c] = ph1_bits(2);
FORC4 {
i = ((row & 1) << 1 | (c & 1)) % 3;
len[c] = len[c] < 3 ? lent[i][0]-'1'+"120"[len[c]] : ph1_bits(4);
lent[i][0] = lent[i][1];
lent[i][1] = len[c];
}
}
FORC(16) {
col = tab + (((c & 7) << 1)^(c >> 3)^(row & 1));
pred = (pmode == 7 || row < 2)
? (tab ? RAW(row,tab-2+(col & 1)) : init)
: (prow[col & 1][col-'4'+"0224468"[pmode]] +
prow[col & 1][col-'4'+"0244668"[pmode]] + 1) >> 1;
diff = ph1_bits (i = len[c >> 2]);
if (diff >> (i-1)) diff -= 1 << i;
diff = diff * (mag*2+1) + mag;
RAW(row,col) = pred + diff;
}
}
}
}
#define HOLE(row) ((holes >> (((row) - raw_height) & 7)) & 1)
/* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */
void CLASS smal_decode_segment (unsigned seg[2][2], int holes)
{
uchar hist[3][13] = {
{ 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 },
{ 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 },
{ 3, 3, 0, 0, 63, 47, 31, 15, 0 } };
int low, high=0xff, carry=0, nbits=8;
int pix, s, count, bin, next, i, sym[3];
uchar diff, pred[]={0,0};
ushort data=0, range=0;
fseek (ifp, seg[0][1]+1, SEEK_SET);
getbits(-1);
for (pix=seg[0][0]; pix < seg[1][0]; pix++) {
for (s=0; s < 3; s++) {
data = data << nbits | getbits(nbits);
if (carry < 0)
carry = (nbits += carry+1) < 1 ? nbits-1 : 0;
while (--nbits >= 0)
if ((data >> nbits & 0xff) == 0xff) break;
if (nbits > 0)
data = ((data & ((1 << (nbits-1)) - 1)) << 1) |
((data + (((data & (1 << (nbits-1)))) << 1)) & ((~0u) << nbits));
if (nbits >= 0) {
data += getbits(1);
carry = nbits - 8;
}
count = ((((data-range+1) & 0xffff) << 2) - 1) / (high >> 4);
for (bin=0; hist[s][bin+5] > count; bin++);
low = hist[s][bin+5] * (high >> 4) >> 2;
if (bin) high = hist[s][bin+4] * (high >> 4) >> 2;
high -= low;
for (nbits=0; high << nbits < 128; nbits++);
range = (range+low) << nbits;
high <<= nbits;
next = hist[s][1];
if (++hist[s][2] > hist[s][3]) {
next = (next+1) & hist[s][0];
hist[s][3] = (hist[s][next+4] - hist[s][next+5]) >> 2;
hist[s][2] = 1;
}
if (hist[s][hist[s][1]+4] - hist[s][hist[s][1]+5] > 1) {
if (bin < hist[s][1])
for (i=bin; i < hist[s][1]; i++) hist[s][i+5]--;
else if (next <= bin)
for (i=hist[s][1]; i < bin; i++) hist[s][i+5]++;
}
hist[s][1] = next;
sym[s] = bin;
}
diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3);
if (sym[0] & 4)
diff = diff ? -diff : 0x80;
if (ftell(ifp) + 12 >= seg[1][1])
diff = 0;
raw_image[pix] = pred[pix & 1] += diff;
if (!(pix & 1) && HOLE(pix / raw_width)) pix += 2;
}
maximum = 0xff;
}
void CLASS smal_v6_load_raw()
{
unsigned seg[2][2];
fseek (ifp, 16, SEEK_SET);
seg[0][0] = 0;
seg[0][1] = get2();
seg[1][0] = raw_width * raw_height;
seg[1][1] = INT_MAX;
smal_decode_segment (seg, 0);
}
int CLASS median4 (int *p)
{
int min, max, sum, i;
min = max = sum = p[0];
for (i=1; i < 4; i++) {
sum += p[i];
if (min > p[i]) min = p[i];
if (max < p[i]) max = p[i];
}
return (sum - min - max) >> 1;
}
void CLASS fill_holes (int holes)
{
int row, col, val[4];
for (row=2; row < height-2; row++) {
if (!HOLE(row)) continue;
for (col=1; col < width-1; col+=4) {
val[0] = RAW(row-1,col-1);
val[1] = RAW(row-1,col+1);
val[2] = RAW(row+1,col-1);
val[3] = RAW(row+1,col+1);
RAW(row,col) = median4(val);
}
for (col=2; col < width-2; col+=4)
if (HOLE(row-2) || HOLE(row+2))
RAW(row,col) = (RAW(row,col-2) + RAW(row,col+2)) >> 1;
else {
val[0] = RAW(row,col-2);
val[1] = RAW(row,col+2);
val[2] = RAW(row-2,col);
val[3] = RAW(row+2,col);
RAW(row,col) = median4(val);
}
}
}
void CLASS smal_v9_load_raw()
{
unsigned seg[256][2], offset, nseg, holes, i;
fseek (ifp, 67, SEEK_SET);
offset = get4();
nseg = fgetc(ifp);
fseek (ifp, offset, SEEK_SET);
for (i=0; i < nseg*2; i++)
seg[0][i] = get4() + data_offset*(i & 1);
fseek (ifp, 78, SEEK_SET);
holes = fgetc(ifp);
fseek (ifp, 88, SEEK_SET);
seg[nseg][0] = raw_height * raw_width;
seg[nseg][1] = get4() + data_offset;
for (i=0; i < nseg; i++)
smal_decode_segment (seg+i, holes);
if (holes) fill_holes (holes);
}
void CLASS redcine_load_raw()
{
#ifndef NO_JASPER
int c, row, col;
jas_stream_t *in;
jas_image_t *jimg;
jas_matrix_t *jmat;
jas_seqent_t *data;
ushort *img, *pix;
jas_init();
#ifndef LIBRAW_LIBRARY_BUILD
in = jas_stream_fopen (ifname, "rb");
#else
in = (jas_stream_t*)ifp->make_jas_stream();
if(!in)
throw LIBRAW_EXCEPTION_DECODE_JPEG2000;
#endif
jas_stream_seek (in, data_offset+20, SEEK_SET);
jimg = jas_image_decode (in, -1, 0);
#ifndef LIBRAW_LIBRARY_BUILD
if (!jimg) longjmp (failure, 3);
#else
if(!jimg)
{
jas_stream_close (in);
throw LIBRAW_EXCEPTION_DECODE_JPEG2000;
}
#endif
jmat = jas_matrix_create (height/2, width/2);
merror (jmat, "redcine_load_raw()");
img = (ushort *) calloc ((height+2), (width+2)*2);
merror (img, "redcine_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
bool fastexitflag = false;
try {
#endif
FORC4 {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
jas_image_readcmpt (jimg, c, 0, 0, width/2, height/2, jmat);
data = jas_matrix_getref (jmat, 0, 0);
for (row = c >> 1; row < height; row+=2)
for (col = c & 1; col < width; col+=2)
img[(row+1)*(width+2)+col+1] = data[(row/2)*(width/2)+col/2];
}
for (col=1; col <= width; col++) {
img[col] = img[2*(width+2)+col];
img[(height+1)*(width+2)+col] = img[(height-1)*(width+2)+col];
}
for (row=0; row < height+2; row++) {
img[row*(width+2)] = img[row*(width+2)+2];
img[(row+1)*(width+2)-1] = img[(row+1)*(width+2)-3];
}
for (row=1; row <= height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
pix = img + row*(width+2) + (col = 1 + (FC(row,1) & 1));
for ( ; col <= width; col+=2, pix+=2) {
c = (((pix[0] - 0x800) << 3) +
pix[-(width+2)] + pix[width+2] + pix[-1] + pix[1]) >> 2;
pix[0] = LIM(c,0,4095);
}
}
for (row=0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col++)
RAW(row,col) = curve[img[(row+1)*(width+2)+col+1]];
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...) {
fastexitflag=true;
}
#endif
free (img);
jas_matrix_destroy (jmat);
jas_image_destroy (jimg);
jas_stream_close (in);
#ifdef LIBRAW_LIBRARY_BUILD
if(fastexitflag)
throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK;
#endif
#endif
}
//@end COMMON
/* RESTRICTED code starts here */
void CLASS foveon_decoder (unsigned size, unsigned code)
{
static unsigned huff[1024];
struct decode *cur;
int i, len;
if (!code) {
for (i=0; i < size; i++)
huff[i] = get4();
memset (first_decode, 0, sizeof first_decode);
free_decode = first_decode;
}
cur = free_decode++;
if (free_decode > first_decode+2048) {
fprintf (stderr,_("%s: decoder table overflow\n"), ifname);
longjmp (failure, 2);
}
if (code)
for (i=0; i < size; i++)
if (huff[i] == code) {
cur->leaf = i;
return;
}
if ((len = code >> 27) > 26) return;
code = (len+1) << 27 | (code & 0x3ffffff) << 1;
cur->branch[0] = free_decode;
foveon_decoder (size, code);
cur->branch[1] = free_decode;
foveon_decoder (size, code+1);
}
void CLASS foveon_thumb()
{
unsigned bwide, row, col, bitbuf=0, bit=1, c, i;
char *buf;
struct decode *dindex;
short pred[3];
bwide = get4();
fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
if (bwide > 0) {
if (bwide < thumb_width*3) return;
buf = (char *) malloc (bwide);
merror (buf, "foveon_thumb()");
for (row=0; row < thumb_height; row++) {
fread (buf, 1, bwide, ifp);
fwrite (buf, 3, thumb_width, ofp);
}
free (buf);
return;
}
foveon_decoder (256, 0);
for (row=0; row < thumb_height; row++) {
memset (pred, 0, sizeof pred);
if (!bit) get4();
for (bit=col=0; col < thumb_width; col++)
FORC3 {
for (dindex=first_decode; dindex->branch[0]; ) {
if ((bit = (bit-1) & 31) == 31)
for (i=0; i < 4; i++)
bitbuf = (bitbuf << 8) + fgetc(ifp);
dindex = dindex->branch[bitbuf >> bit & 1];
}
pred[c] += dindex->leaf;
fputc (pred[c], ofp);
}
}
}
void CLASS foveon_sd_load_raw()
{
struct decode *dindex;
short diff[1024];
unsigned bitbuf=0;
int pred[3], row, col, bit=-1, c, i;
read_shorts ((ushort *) diff, 1024);
if (!load_flags) foveon_decoder (1024, 0);
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
memset (pred, 0, sizeof pred);
if (!bit && !load_flags && atoi(model+2) < 14) get4();
for (col=bit=0; col < width; col++) {
if (load_flags) {
bitbuf = get4();
FORC3 pred[2-c] += diff[bitbuf >> c*10 & 0x3ff];
}
else FORC3 {
for (dindex=first_decode; dindex->branch[0]; ) {
if ((bit = (bit-1) & 31) == 31)
for (i=0; i < 4; i++)
bitbuf = (bitbuf << 8) + fgetc(ifp);
dindex = dindex->branch[bitbuf >> bit & 1];
}
pred[c] += diff[dindex->leaf];
if (pred[c] >> 16 && ~pred[c] >> 16) derror();
}
FORC3 image[row*width+col][c] = pred[c];
}
}
}
void CLASS foveon_huff (ushort *huff)
{
int i, j, clen, code;
huff[0] = 8;
for (i=0; i < 13; i++) {
clen = getc(ifp);
code = getc(ifp);
for (j=0; j < 256 >> clen; )
huff[code+ ++j] = clen << 8 | i;
}
get2();
}
void CLASS foveon_dp_load_raw()
{
unsigned c, roff[4], row, col, diff;
ushort huff[512], vpred[2][2], hpred[2];
fseek (ifp, 8, SEEK_CUR);
foveon_huff (huff);
roff[0] = 48;
FORC3 roff[c+1] = -(-(roff[c] + get4()) & -16);
FORC3 {
fseek (ifp, data_offset+roff[c], SEEK_SET);
getbits(-1);
vpred[0][0] = vpred[0][1] = vpred[1][0] = vpred[1][1] = 512;
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col++) {
diff = ljpeg_diff(huff);
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
image[row*width+col][c] = hpred[col & 1];
}
}
}
}
void CLASS foveon_load_camf()
{
unsigned type, wide, high, i, j, row, col, diff;
ushort huff[258], vpred[2][2] = {{512,512},{512,512}}, hpred[2];
fseek (ifp, meta_offset, SEEK_SET);
type = get4(); get4(); get4();
wide = get4();
high = get4();
if (type == 2) {
fread (meta_data, 1, meta_length, ifp);
for (i=0; i < meta_length; i++) {
high = (high * 1597 + 51749) % 244944;
wide = high * (INT64) 301593171 >> 24;
meta_data[i] ^= ((((high << 8) - wide) >> 1) + wide) >> 17;
}
} else if (type == 4) {
free (meta_data);
meta_data = (char *) malloc (meta_length = wide*high*3/2);
merror (meta_data, "foveon_load_camf()");
foveon_huff (huff);
get4();
getbits(-1);
for (j=row=0; row < high; row++) {
for (col=0; col < wide; col++) {
diff = ljpeg_diff(huff);
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
if (col & 1) {
meta_data[j++] = hpred[0] >> 4;
meta_data[j++] = hpred[0] << 4 | hpred[1] >> 8;
meta_data[j++] = hpred[1];
}
}
}
}
#ifdef DCRAW_VERBOSE
else
fprintf (stderr,_("%s has unknown CAMF type %d.\n"), ifname, type);
#endif
}
const char * CLASS foveon_camf_param (const char *block, const char *param)
{
unsigned idx, num;
char *pos, *cp, *dp;
for (idx=0; idx < meta_length; idx += sget4(pos+8)) {
pos = meta_data + idx;
if (strncmp (pos, "CMb", 3)) break;
if (pos[3] != 'P') continue;
if (strcmp (block, pos+sget4(pos+12))) continue;
cp = pos + sget4(pos+16);
num = sget4(cp);
dp = pos + sget4(cp+4);
while (num--) {
cp += 8;
if (!strcmp (param, dp+sget4(cp)))
return dp+sget4(cp+4);
}
}
return 0;
}
void * CLASS foveon_camf_matrix (unsigned dim[3], const char *name)
{
unsigned i, idx, type, ndim, size, *mat;
char *pos, *cp, *dp;
double dsize;
for (idx=0; idx < meta_length; idx += sget4(pos+8)) {
pos = meta_data + idx;
if (strncmp (pos, "CMb", 3)) break;
if (pos[3] != 'M') continue;
if (strcmp (name, pos+sget4(pos+12))) continue;
dim[0] = dim[1] = dim[2] = 1;
cp = pos + sget4(pos+16);
type = sget4(cp);
if ((ndim = sget4(cp+4)) > 3) break;
dp = pos + sget4(cp+8);
for (i=ndim; i--; ) {
cp += 12;
dim[i] = sget4(cp);
}
if ((dsize = (double) dim[0]*dim[1]*dim[2]) > meta_length/4) break;
mat = (unsigned *) malloc ((size = dsize) * 4);
merror (mat, "foveon_camf_matrix()");
for (i=0; i < size; i++)
if (type && type != 6)
mat[i] = sget4(dp + i*4);
else
mat[i] = sget4(dp + i*2) & 0xffff;
return mat;
}
#ifdef DCRAW_VERBOSE
fprintf (stderr,_("%s: \"%s\" matrix not found!\n"), ifname, name);
#endif
return 0;
}
int CLASS foveon_fixed (void *ptr, int size, const char *name)
{
void *dp;
unsigned dim[3];
if (!name) return 0;
dp = foveon_camf_matrix (dim, name);
if (!dp) return 0;
memcpy (ptr, dp, size*4);
free (dp);
return 1;
}
float CLASS foveon_avg (short *pix, int range[2], float cfilt)
{
int i;
float val, min=FLT_MAX, max=-FLT_MAX, sum=0;
for (i=range[0]; i <= range[1]; i++) {
sum += val = pix[i*4] + (pix[i*4]-pix[(i-1)*4]) * cfilt;
if (min > val) min = val;
if (max < val) max = val;
}
if (range[1] - range[0] == 1) return sum/2;
return (sum - min - max) / (range[1] - range[0] - 1);
}
short * CLASS foveon_make_curve (double max, double mul, double filt)
{
short *curve;
unsigned i, size;
double x;
if (!filt) filt = 0.8;
size = 4*M_PI*max / filt;
if (size == UINT_MAX) size--;
curve = (short *) calloc (size+1, sizeof *curve);
merror (curve, "foveon_make_curve()");
curve[0] = size;
for (i=0; i < size; i++) {
x = i*filt/max/4;
curve[i+1] = (cos(x)+1)/2 * tanh(i*filt/mul) * mul + 0.5;
}
return curve;
}
void CLASS foveon_make_curves
(short **curvep, float dq[3], float div[3], float filt)
{
double mul[3], max=0;
int c;
FORC3 mul[c] = dq[c]/div[c];
FORC3 if (max < mul[c]) max = mul[c];
FORC3 curvep[c] = foveon_make_curve (max, mul[c], filt);
}
int CLASS foveon_apply_curve (short *curve, int i)
{
if (abs(i) >= curve[0]) return 0;
return i < 0 ? -curve[1-i] : curve[1+i];
}
#define image ((short (*)[4]) image)
void CLASS foveon_interpolate()
{
static const short hood[] = { -1,-1, -1,0, -1,1, 0,-1, 0,1, 1,-1, 1,0, 1,1 };
short *pix, prev[3], *curve[8], (*shrink)[3];
float cfilt=0, ddft[3][3][2], ppm[3][3][3];
float cam_xyz[3][3], correct[3][3], last[3][3], trans[3][3];
float chroma_dq[3], color_dq[3], diag[3][3], div[3];
float (*black)[3], (*sgain)[3], (*sgrow)[3];
float fsum[3], val, frow, num;
int row, col, c, i, j, diff, sgx, irow, sum, min, max, limit;
int dscr[2][2], dstb[4], (*smrow[7])[3], total[4], ipix[3];
int work[3][3], smlast, smred, smred_p=0, dev[3];
int satlev[3], keep[4], active[4];
unsigned dim[3], *badpix;
double dsum=0, trsum[3];
char str[128];
const char* cp;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf (stderr,_("Foveon interpolation...\n"));
#endif
foveon_load_camf();
foveon_fixed (dscr, 4, "DarkShieldColRange");
foveon_fixed (ppm[0][0], 27, "PostPolyMatrix");
foveon_fixed (satlev, 3, "SaturationLevel");
foveon_fixed (keep, 4, "KeepImageArea");
foveon_fixed (active, 4, "ActiveImageArea");
foveon_fixed (chroma_dq, 3, "ChromaDQ");
foveon_fixed (color_dq, 3,
foveon_camf_param ("IncludeBlocks", "ColorDQ") ?
"ColorDQ" : "ColorDQCamRGB");
if (foveon_camf_param ("IncludeBlocks", "ColumnFilter"))
foveon_fixed (&cfilt, 1, "ColumnFilter");
memset (ddft, 0, sizeof ddft);
if (!foveon_camf_param ("IncludeBlocks", "DarkDrift")
|| !foveon_fixed (ddft[1][0], 12, "DarkDrift"))
for (i=0; i < 2; i++) {
foveon_fixed (dstb, 4, i ? "DarkShieldBottom":"DarkShieldTop");
for (row = dstb[1]; row <= dstb[3]; row++)
for (col = dstb[0]; col <= dstb[2]; col++)
FORC3 ddft[i+1][c][1] += (short) image[row*width+col][c];
FORC3 ddft[i+1][c][1] /= (dstb[3]-dstb[1]+1) * (dstb[2]-dstb[0]+1);
}
if (!(cp = foveon_camf_param ("WhiteBalanceIlluminants", model2)))
{
#ifdef DCRAW_VERBOSE
fprintf (stderr,_("%s: Invalid white balance \"%s\"\n"), ifname, model2);
#endif
return; }
foveon_fixed (cam_xyz, 9, cp);
foveon_fixed (correct, 9,
foveon_camf_param ("WhiteBalanceCorrections", model2));
memset (last, 0, sizeof last);
for (i=0; i < 3; i++)
for (j=0; j < 3; j++)
FORC3 last[i][j] += correct[i][c] * cam_xyz[c][j];
#define LAST(x,y) last[(i+x)%3][(c+y)%3]
for (i=0; i < 3; i++)
FORC3 diag[c][i] = LAST(1,1)*LAST(2,2) - LAST(1,2)*LAST(2,1);
#undef LAST
FORC3 div[c] = diag[c][0]*0.3127 + diag[c][1]*0.329 + diag[c][2]*0.3583;
sprintf (str, "%sRGBNeutral", model2);
if (foveon_camf_param ("IncludeBlocks", str))
foveon_fixed (div, 3, str);
num = 0;
FORC3 if (num < div[c]) num = div[c];
FORC3 div[c] /= num;
memset (trans, 0, sizeof trans);
for (i=0; i < 3; i++)
for (j=0; j < 3; j++)
FORC3 trans[i][j] += rgb_cam[i][c] * last[c][j] * div[j];
FORC3 trsum[c] = trans[c][0] + trans[c][1] + trans[c][2];
dsum = (6*trsum[0] + 11*trsum[1] + 3*trsum[2]) / 20;
for (i=0; i < 3; i++)
FORC3 last[i][c] = trans[i][c] * dsum / trsum[i];
memset (trans, 0, sizeof trans);
for (i=0; i < 3; i++)
for (j=0; j < 3; j++)
FORC3 trans[i][j] += (i==c ? 32 : -1) * last[c][j] / 30;
foveon_make_curves (curve, color_dq, div, cfilt);
FORC3 chroma_dq[c] /= 3;
foveon_make_curves (curve+3, chroma_dq, div, cfilt);
FORC3 dsum += chroma_dq[c] / div[c];
curve[6] = foveon_make_curve (dsum, dsum, cfilt);
curve[7] = foveon_make_curve (dsum*2, dsum*2, cfilt);
sgain = (float (*)[3]) foveon_camf_matrix (dim, "SpatialGain");
if (!sgain) return;
sgrow = (float (*)[3]) calloc (dim[1], sizeof *sgrow);
sgx = (width + dim[1]-2) / (dim[1]-1);
black = (float (*)[3]) calloc (height, sizeof *black);
for (row=0; row < height; row++) {
for (i=0; i < 6; i++)
ddft[0][0][i] = ddft[1][0][i] +
row / (height-1.0) * (ddft[2][0][i] - ddft[1][0][i]);
FORC3 black[row][c] =
( foveon_avg (image[row*width]+c, dscr[0], cfilt) +
foveon_avg (image[row*width]+c, dscr[1], cfilt) * 3
- ddft[0][c][0] ) / 4 - ddft[0][c][1];
}
memcpy (black, black+8, sizeof *black*8);
memcpy (black+height-11, black+height-22, 11*sizeof *black);
memcpy (last, black, sizeof last);
for (row=1; row < height-1; row++) {
FORC3 if (last[1][c] > last[0][c]) {
if (last[1][c] > last[2][c])
black[row][c] = (last[0][c] > last[2][c]) ? last[0][c]:last[2][c];
} else
if (last[1][c] < last[2][c])
black[row][c] = (last[0][c] < last[2][c]) ? last[0][c]:last[2][c];
memmove (last, last+1, 2*sizeof last[0]);
memcpy (last[2], black[row+1], sizeof last[2]);
}
FORC3 black[row][c] = (last[0][c] + last[1][c])/2;
FORC3 black[0][c] = (black[1][c] + black[3][c])/2;
val = 1 - exp(-1/24.0);
memcpy (fsum, black, sizeof fsum);
for (row=1; row < height; row++)
FORC3 fsum[c] += black[row][c] =
(black[row][c] - black[row-1][c])*val + black[row-1][c];
memcpy (last[0], black[height-1], sizeof last[0]);
FORC3 fsum[c] /= height;
for (row = height; row--; )
FORC3 last[0][c] = black[row][c] =
(black[row][c] - fsum[c] - last[0][c])*val + last[0][c];
memset (total, 0, sizeof total);
for (row=2; row < height; row+=4)
for (col=2; col < width; col+=4) {
FORC3 total[c] += (short) image[row*width+col][c];
total[3]++;
}
for (row=0; row < height; row++)
FORC3 black[row][c] += fsum[c]/2 + total[c]/(total[3]*100.0);
for (row=0; row < height; row++) {
for (i=0; i < 6; i++)
ddft[0][0][i] = ddft[1][0][i] +
row / (height-1.0) * (ddft[2][0][i] - ddft[1][0][i]);
pix = image[row*width];
memcpy (prev, pix, sizeof prev);
frow = row / (height-1.0) * (dim[2]-1);
if ((irow = frow) == dim[2]-1) irow--;
frow -= irow;
for (i=0; i < dim[1]; i++)
FORC3 sgrow[i][c] = sgain[ irow *dim[1]+i][c] * (1-frow) +
sgain[(irow+1)*dim[1]+i][c] * frow;
for (col=0; col < width; col++) {
FORC3 {
diff = pix[c] - prev[c];
prev[c] = pix[c];
ipix[c] = pix[c] + floor ((diff + (diff*diff >> 14)) * cfilt
- ddft[0][c][1] - ddft[0][c][0] * ((float) col/width - 0.5)
- black[row][c] );
}
FORC3 {
work[0][c] = ipix[c] * ipix[c] >> 14;
work[2][c] = ipix[c] * work[0][c] >> 14;
work[1][2-c] = ipix[(c+1) % 3] * ipix[(c+2) % 3] >> 14;
}
FORC3 {
for (val=i=0; i < 3; i++)
for ( j=0; j < 3; j++)
val += ppm[c][i][j] * work[i][j];
ipix[c] = floor ((ipix[c] + floor(val)) *
( sgrow[col/sgx ][c] * (sgx - col%sgx) +
sgrow[col/sgx+1][c] * (col%sgx) ) / sgx / div[c]);
if (ipix[c] > 32000) ipix[c] = 32000;
pix[c] = ipix[c];
}
pix += 4;
}
}
free (black);
free (sgrow);
free (sgain);
if ((badpix = (unsigned int *) foveon_camf_matrix (dim, "BadPixels"))) {
for (i=0; i < dim[0]; i++) {
col = (badpix[i] >> 8 & 0xfff) - keep[0];
row = (badpix[i] >> 20 ) - keep[1];
if ((unsigned)(row-1) > height-3 || (unsigned)(col-1) > width-3)
continue;
memset (fsum, 0, sizeof fsum);
for (sum=j=0; j < 8; j++)
if (badpix[i] & (1 << j)) {
FORC3 fsum[c] += (short)
image[(row+hood[j*2])*width+col+hood[j*2+1]][c];
sum++;
}
if (sum) FORC3 image[row*width+col][c] = fsum[c]/sum;
}
free (badpix);
}
/* Array for 5x5 Gaussian averaging of red values */
smrow[6] = (int (*)[3]) calloc (width*5, sizeof **smrow);
merror (smrow[6], "foveon_interpolate()");
for (i=0; i < 5; i++)
smrow[i] = smrow[6] + i*width;
/* Sharpen the reds against these Gaussian averages */
for (smlast=-1, row=2; row < height-2; row++) {
while (smlast < row+2) {
for (i=0; i < 6; i++)
smrow[(i+5) % 6] = smrow[i];
pix = image[++smlast*width+2];
for (col=2; col < width-2; col++) {
smrow[4][col][0] =
(pix[0]*6 + (pix[-4]+pix[4])*4 + pix[-8]+pix[8] + 8) >> 4;
pix += 4;
}
}
pix = image[row*width+2];
for (col=2; col < width-2; col++) {
smred = ( 6 * smrow[2][col][0]
+ 4 * (smrow[1][col][0] + smrow[3][col][0])
+ smrow[0][col][0] + smrow[4][col][0] + 8 ) >> 4;
if (col == 2)
smred_p = smred;
i = pix[0] + ((pix[0] - ((smred*7 + smred_p) >> 3)) >> 3);
if (i > 32000) i = 32000;
pix[0] = i;
smred_p = smred;
pix += 4;
}
}
/* Adjust the brighter pixels for better linearity */
min = 0xffff;
FORC3 {
i = satlev[c] / div[c];
if (min > i) min = i;
}
limit = min * 9 >> 4;
for (pix=image[0]; pix < image[height*width]; pix+=4) {
if (pix[0] <= limit || pix[1] <= limit || pix[2] <= limit)
continue;
min = max = pix[0];
for (c=1; c < 3; c++) {
if (min > pix[c]) min = pix[c];
if (max < pix[c]) max = pix[c];
}
if (min >= limit*2) {
pix[0] = pix[1] = pix[2] = max;
} else {
i = 0x4000 - ((min - limit) << 14) / limit;
i = 0x4000 - (i*i >> 14);
i = i*i >> 14;
FORC3 pix[c] += (max - pix[c]) * i >> 14;
}
}
/*
Because photons that miss one detector often hit another,
the sum R+G+B is much less noisy than the individual colors.
So smooth the hues without smoothing the total.
*/
for (smlast=-1, row=2; row < height-2; row++) {
while (smlast < row+2) {
for (i=0; i < 6; i++)
smrow[(i+5) % 6] = smrow[i];
pix = image[++smlast*width+2];
for (col=2; col < width-2; col++) {
FORC3 smrow[4][col][c] = (pix[c-4]+2*pix[c]+pix[c+4]+2) >> 2;
pix += 4;
}
}
pix = image[row*width+2];
for (col=2; col < width-2; col++) {
FORC3 dev[c] = -foveon_apply_curve (curve[7], pix[c] -
((smrow[1][col][c] + 2*smrow[2][col][c] + smrow[3][col][c]) >> 2));
sum = (dev[0] + dev[1] + dev[2]) >> 3;
FORC3 pix[c] += dev[c] - sum;
pix += 4;
}
}
for (smlast=-1, row=2; row < height-2; row++) {
while (smlast < row+2) {
for (i=0; i < 6; i++)
smrow[(i+5) % 6] = smrow[i];
pix = image[++smlast*width+2];
for (col=2; col < width-2; col++) {
FORC3 smrow[4][col][c] =
(pix[c-8]+pix[c-4]+pix[c]+pix[c+4]+pix[c+8]+2) >> 2;
pix += 4;
}
}
pix = image[row*width+2];
for (col=2; col < width-2; col++) {
for (total[3]=375, sum=60, c=0; c < 3; c++) {
for (total[c]=i=0; i < 5; i++)
total[c] += smrow[i][col][c];
total[3] += total[c];
sum += pix[c];
}
if (sum < 0) sum = 0;
j = total[3] > 375 ? (sum << 16) / total[3] : sum * 174;
FORC3 pix[c] += foveon_apply_curve (curve[6],
((j*total[c] + 0x8000) >> 16) - pix[c]);
pix += 4;
}
}
/* Transform the image to a different colorspace */
for (pix=image[0]; pix < image[height*width]; pix+=4) {
FORC3 pix[c] -= foveon_apply_curve (curve[c], pix[c]);
sum = (pix[0]+pix[1]+pix[1]+pix[2]) >> 2;
FORC3 pix[c] -= foveon_apply_curve (curve[c], pix[c]-sum);
FORC3 {
for (dsum=i=0; i < 3; i++)
dsum += trans[c][i] * pix[i];
if (dsum < 0) dsum = 0;
if (dsum > 24000) dsum = 24000;
ipix[c] = dsum + 0.5;
}
FORC3 pix[c] = ipix[c];
}
/* Smooth the image bottom-to-top and save at 1/4 scale */
shrink = (short (*)[3]) calloc ((height/4), (width/4)*sizeof *shrink);
merror (shrink, "foveon_interpolate()");
for (row = height/4; row--; )
for (col=0; col < width/4; col++) {
ipix[0] = ipix[1] = ipix[2] = 0;
for (i=0; i < 4; i++)
for (j=0; j < 4; j++)
FORC3 ipix[c] += image[(row*4+i)*width+col*4+j][c];
FORC3
if (row+2 > height/4)
shrink[row*(width/4)+col][c] = ipix[c] >> 4;
else
shrink[row*(width/4)+col][c] =
(shrink[(row+1)*(width/4)+col][c]*1840 + ipix[c]*141 + 2048) >> 12;
}
/* From the 1/4-scale image, smooth right-to-left */
for (row=0; row < (height & ~3); row++) {
ipix[0] = ipix[1] = ipix[2] = 0;
if ((row & 3) == 0)
for (col = width & ~3 ; col--; )
FORC3 smrow[0][col][c] = ipix[c] =
(shrink[(row/4)*(width/4)+col/4][c]*1485 + ipix[c]*6707 + 4096) >> 13;
/* Then smooth left-to-right */
ipix[0] = ipix[1] = ipix[2] = 0;
for (col=0; col < (width & ~3); col++)
FORC3 smrow[1][col][c] = ipix[c] =
(smrow[0][col][c]*1485 + ipix[c]*6707 + 4096) >> 13;
/* Smooth top-to-bottom */
if (row == 0)
memcpy (smrow[2], smrow[1], sizeof **smrow * width);
else
for (col=0; col < (width & ~3); col++)
FORC3 smrow[2][col][c] =
(smrow[2][col][c]*6707 + smrow[1][col][c]*1485 + 4096) >> 13;
/* Adjust the chroma toward the smooth values */
for (col=0; col < (width & ~3); col++) {
for (i=j=30, c=0; c < 3; c++) {
i += smrow[2][col][c];
j += image[row*width+col][c];
}
j = (j << 16) / i;
for (sum=c=0; c < 3; c++) {
ipix[c] = foveon_apply_curve (curve[c+3],
((smrow[2][col][c] * j + 0x8000) >> 16) - image[row*width+col][c]);
sum += ipix[c];
}
sum >>= 3;
FORC3 {
i = image[row*width+col][c] + ipix[c] - sum;
if (i < 0) i = 0;
image[row*width+col][c] = i;
}
}
}
free (shrink);
free (smrow[6]);
for (i=0; i < 8; i++)
free (curve[i]);
/* Trim off the black border */
active[1] -= keep[1];
active[3] -= 2;
i = active[2] - active[0];
for (row=0; row < active[3]-active[1]; row++)
memcpy (image[row*i], image[(row+active[1])*width+active[0]],
i * sizeof *image);
width = i;
height = row;
}
#undef image
/* RESTRICTED code ends here */
//@out COMMON
void CLASS crop_masked_pixels()
{
int row, col;
unsigned
#ifndef LIBRAW_LIBRARY_BUILD
r, raw_pitch = raw_width*2,
c, m, mblack[8], zero, val;
#else
c, m, zero, val;
#define mblack imgdata.color.black_stat
#endif
#ifndef LIBRAW_LIBRARY_BUILD
if (load_raw == &CLASS phase_one_load_raw ||
load_raw == &CLASS phase_one_load_raw_c)
phase_one_correct();
if (fuji_width) {
for (row=0; row < raw_height-top_margin*2; row++) {
for (col=0; col < fuji_width << !fuji_layout; col++) {
if (fuji_layout) {
r = fuji_width - 1 - col + (row >> 1);
c = col + ((row+1) >> 1);
} else {
r = fuji_width - 1 + row - (col >> 1);
c = row + ((col+1) >> 1);
}
if (r < height && c < width)
BAYER(r,c) = RAW(row+top_margin,col+left_margin);
}
}
} else {
for (row=0; row < height; row++)
for (col=0; col < width; col++)
BAYER2(row,col) = RAW(row+top_margin,col+left_margin);
}
#endif
if (mask[0][3] > 0) goto mask_set;
if (load_raw == &CLASS canon_load_raw ||
load_raw == &CLASS lossless_jpeg_load_raw) {
mask[0][1] = mask[1][1] += 2;
mask[0][3] -= 2;
goto sides;
}
if (load_raw == &CLASS canon_600_load_raw ||
load_raw == &CLASS sony_load_raw ||
(load_raw == &CLASS eight_bit_load_raw && strncmp(model,"DC2",3)) ||
load_raw == &CLASS kodak_262_load_raw ||
(load_raw == &CLASS packed_load_raw && (load_flags & 32))) {
sides:
mask[0][0] = mask[1][0] = top_margin;
mask[0][2] = mask[1][2] = top_margin+height;
mask[0][3] += left_margin;
mask[1][1] += left_margin+width;
mask[1][3] += raw_width;
}
if (load_raw == &CLASS nokia_load_raw) {
mask[0][2] = top_margin;
mask[0][3] = width;
}
mask_set:
memset (mblack, 0, sizeof mblack);
for (zero=m=0; m < 8; m++)
for (row=MAX(mask[m][0],0); row < MIN(mask[m][2],raw_height); row++)
for (col=MAX(mask[m][1],0); col < MIN(mask[m][3],raw_width); col++) {
c = FC(row-top_margin,col-left_margin);
mblack[c] += val = raw_image[(row)*raw_pitch/2+(col)];
mblack[4+c]++;
zero += !val;
}
if (load_raw == &CLASS canon_600_load_raw && width < raw_width) {
black = (mblack[0]+mblack[1]+mblack[2]+mblack[3]) /
(mblack[4]+mblack[5]+mblack[6]+mblack[7]) - 4;
#ifndef LIBRAW_LIBRARY_BUILD
canon_600_correct();
#endif
} else if (zero < mblack[4] && mblack[5] && mblack[6] && mblack[7]) {
FORC4 cblack[c] = mblack[c] / mblack[4+c];
cblack[4] = cblack[5] = cblack[6] = 0;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
#undef mblack
#endif
void CLASS remove_zeroes()
{
unsigned row, col, tot, n, r, c;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,0,2);
#endif
for (row=0; row < height; row++)
for (col=0; col < width; col++)
if (BAYER(row,col) == 0) {
tot = n = 0;
for (r = row-2; r <= row+2; r++)
for (c = col-2; c <= col+2; c++)
if (r < height && c < width &&
FC(r,c) == FC(row,col) && BAYER(r,c))
tot += (n++,BAYER(r,c));
if (n) BAYER(row,col) = tot/n;
}
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,1,2);
#endif
}
//@end COMMON
/* @out FILEIO
#include <math.h>
#define CLASS LibRaw::
#include "libraw/libraw_types.h"
#define LIBRAW_LIBRARY_BUILD
#include "libraw/libraw.h"
#include "internal/defines.h"
#include "internal/var_defines.h"
@end FILEIO */
// @out FILEIO
/*
Seach from the current directory up to the root looking for
a ".badpixels" file, and fix those pixels now.
*/
void CLASS bad_pixels (const char *cfname)
{
FILE *fp=NULL;
#ifndef LIBRAW_LIBRARY_BUILD
char *fname, *cp, line[128];
int len, time, row, col, r, c, rad, tot, n, fixed=0;
#else
char *cp, line[128];
int time, row, col, r, c, rad, tot, n;
#ifdef DCRAW_VERBOSE
int fixed = 0;
#endif
#endif
if (!filters) return;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS,0,2);
#endif
if (cfname)
fp = fopen (cfname, "r");
// @end FILEIO
else {
for (len=32 ; ; len *= 2) {
fname = (char *) malloc (len);
if (!fname) return;
if (getcwd (fname, len-16)) break;
free (fname);
if (errno != ERANGE) return;
}
#if defined(WIN32) || defined(DJGPP)
if (fname[1] == ':')
memmove (fname, fname+2, len-2);
for (cp=fname; *cp; cp++)
if (*cp == '\\') *cp = '/';
#endif
cp = fname + strlen(fname);
if (cp[-1] == '/') cp--;
while (*fname == '/') {
strcpy (cp, "/.badpixels");
if ((fp = fopen (fname, "r"))) break;
if (cp == fname) break;
while (*--cp != '/');
}
free (fname);
}
// @out FILEIO
if (!fp)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_BADPIXELMAP;
#endif
return;
}
while (fgets (line, 128, fp)) {
cp = strchr (line, '#');
if (cp) *cp = 0;
if (sscanf (line, "%d %d %d", &col, &row, &time) != 3) continue;
if ((unsigned) col >= width || (unsigned) row >= height) continue;
if (time > timestamp) continue;
for (tot=n=0, rad=1; rad < 3 && n==0; rad++)
for (r = row-rad; r <= row+rad; r++)
for (c = col-rad; c <= col+rad; c++)
if ((unsigned) r < height && (unsigned) c < width &&
(r != row || c != col) && fcol(r,c) == fcol(row,col)) {
tot += BAYER2(r,c);
n++;
}
BAYER2(row,col) = tot/n;
#ifdef DCRAW_VERBOSE
if (verbose) {
if (!fixed++)
fprintf (stderr,_("Fixed dead pixels at:"));
fprintf (stderr, " %d,%d", col, row);
}
#endif
}
#ifdef DCRAW_VERBOSE
if (fixed) fputc ('\n', stderr);
#endif
fclose (fp);
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS,1,2);
#endif
}
void CLASS subtract (const char *fname)
{
FILE *fp;
int dim[3]={0,0,0}, comment=0, number=0, error=0, nd=0, c, row, col;
ushort *pixel;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_DARK_FRAME,0,2);
#endif
if (!(fp = fopen (fname, "rb"))) {
#ifdef DCRAW_VERBOSE
perror (fname);
#endif
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_BAD_DARKFRAME_FILE;
#endif
return;
}
if (fgetc(fp) != 'P' || fgetc(fp) != '5') error = 1;
while (!error && nd < 3 && (c = fgetc(fp)) != EOF) {
if (c == '#') comment = 1;
if (c == '\n') comment = 0;
if (comment) continue;
if (isdigit(c)) number = 1;
if (number) {
if (isdigit(c)) dim[nd] = dim[nd]*10 + c -'0';
else if (isspace(c)) {
number = 0; nd++;
} else error = 1;
}
}
if (error || nd < 3) {
#ifdef DCRAW_VERBOSE
fprintf (stderr,_("%s is not a valid PGM file!\n"), fname);
#endif
fclose (fp); return;
} else if (dim[0] != width || dim[1] != height || dim[2] != 65535) {
#ifdef DCRAW_VERBOSE
fprintf (stderr,_("%s has the wrong dimensions!\n"), fname);
#endif
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_BAD_DARKFRAME_DIM;
#endif
fclose (fp); return;
}
pixel = (ushort *) calloc (width, sizeof *pixel);
merror (pixel, "subtract()");
for (row=0; row < height; row++) {
fread (pixel, 2, width, fp);
for (col=0; col < width; col++)
BAYER(row,col) = MAX (BAYER(row,col) - ntohs(pixel[col]), 0);
}
free (pixel);
fclose (fp);
memset (cblack, 0, sizeof cblack);
black = 0;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_DARK_FRAME,1,2);
#endif
}
//@end FILEIO
//@out COMMON
static const uchar xlat[2][256] = {
{ 0xc1,0xbf,0x6d,0x0d,0x59,0xc5,0x13,0x9d,0x83,0x61,0x6b,0x4f,0xc7,0x7f,0x3d,0x3d,
0x53,0x59,0xe3,0xc7,0xe9,0x2f,0x95,0xa7,0x95,0x1f,0xdf,0x7f,0x2b,0x29,0xc7,0x0d,
0xdf,0x07,0xef,0x71,0x89,0x3d,0x13,0x3d,0x3b,0x13,0xfb,0x0d,0x89,0xc1,0x65,0x1f,
0xb3,0x0d,0x6b,0x29,0xe3,0xfb,0xef,0xa3,0x6b,0x47,0x7f,0x95,0x35,0xa7,0x47,0x4f,
0xc7,0xf1,0x59,0x95,0x35,0x11,0x29,0x61,0xf1,0x3d,0xb3,0x2b,0x0d,0x43,0x89,0xc1,
0x9d,0x9d,0x89,0x65,0xf1,0xe9,0xdf,0xbf,0x3d,0x7f,0x53,0x97,0xe5,0xe9,0x95,0x17,
0x1d,0x3d,0x8b,0xfb,0xc7,0xe3,0x67,0xa7,0x07,0xf1,0x71,0xa7,0x53,0xb5,0x29,0x89,
0xe5,0x2b,0xa7,0x17,0x29,0xe9,0x4f,0xc5,0x65,0x6d,0x6b,0xef,0x0d,0x89,0x49,0x2f,
0xb3,0x43,0x53,0x65,0x1d,0x49,0xa3,0x13,0x89,0x59,0xef,0x6b,0xef,0x65,0x1d,0x0b,
0x59,0x13,0xe3,0x4f,0x9d,0xb3,0x29,0x43,0x2b,0x07,0x1d,0x95,0x59,0x59,0x47,0xfb,
0xe5,0xe9,0x61,0x47,0x2f,0x35,0x7f,0x17,0x7f,0xef,0x7f,0x95,0x95,0x71,0xd3,0xa3,
0x0b,0x71,0xa3,0xad,0x0b,0x3b,0xb5,0xfb,0xa3,0xbf,0x4f,0x83,0x1d,0xad,0xe9,0x2f,
0x71,0x65,0xa3,0xe5,0x07,0x35,0x3d,0x0d,0xb5,0xe9,0xe5,0x47,0x3b,0x9d,0xef,0x35,
0xa3,0xbf,0xb3,0xdf,0x53,0xd3,0x97,0x53,0x49,0x71,0x07,0x35,0x61,0x71,0x2f,0x43,
0x2f,0x11,0xdf,0x17,0x97,0xfb,0x95,0x3b,0x7f,0x6b,0xd3,0x25,0xbf,0xad,0xc7,0xc5,
0xc5,0xb5,0x8b,0xef,0x2f,0xd3,0x07,0x6b,0x25,0x49,0x95,0x25,0x49,0x6d,0x71,0xc7 },
{ 0xa7,0xbc,0xc9,0xad,0x91,0xdf,0x85,0xe5,0xd4,0x78,0xd5,0x17,0x46,0x7c,0x29,0x4c,
0x4d,0x03,0xe9,0x25,0x68,0x11,0x86,0xb3,0xbd,0xf7,0x6f,0x61,0x22,0xa2,0x26,0x34,
0x2a,0xbe,0x1e,0x46,0x14,0x68,0x9d,0x44,0x18,0xc2,0x40,0xf4,0x7e,0x5f,0x1b,0xad,
0x0b,0x94,0xb6,0x67,0xb4,0x0b,0xe1,0xea,0x95,0x9c,0x66,0xdc,0xe7,0x5d,0x6c,0x05,
0xda,0xd5,0xdf,0x7a,0xef,0xf6,0xdb,0x1f,0x82,0x4c,0xc0,0x68,0x47,0xa1,0xbd,0xee,
0x39,0x50,0x56,0x4a,0xdd,0xdf,0xa5,0xf8,0xc6,0xda,0xca,0x90,0xca,0x01,0x42,0x9d,
0x8b,0x0c,0x73,0x43,0x75,0x05,0x94,0xde,0x24,0xb3,0x80,0x34,0xe5,0x2c,0xdc,0x9b,
0x3f,0xca,0x33,0x45,0xd0,0xdb,0x5f,0xf5,0x52,0xc3,0x21,0xda,0xe2,0x22,0x72,0x6b,
0x3e,0xd0,0x5b,0xa8,0x87,0x8c,0x06,0x5d,0x0f,0xdd,0x09,0x19,0x93,0xd0,0xb9,0xfc,
0x8b,0x0f,0x84,0x60,0x33,0x1c,0x9b,0x45,0xf1,0xf0,0xa3,0x94,0x3a,0x12,0x77,0x33,
0x4d,0x44,0x78,0x28,0x3c,0x9e,0xfd,0x65,0x57,0x16,0x94,0x6b,0xfb,0x59,0xd0,0xc8,
0x22,0x36,0xdb,0xd2,0x63,0x98,0x43,0xa1,0x04,0x87,0x86,0xf7,0xa6,0x26,0xbb,0xd6,
0x59,0x4d,0xbf,0x6a,0x2e,0xaa,0x2b,0xef,0xe6,0x78,0xb6,0x4e,0xe0,0x2f,0xdc,0x7c,
0xbe,0x57,0x19,0x32,0x7e,0x2a,0xd0,0xb8,0xba,0x29,0x00,0x3c,0x52,0x7d,0xa8,0x49,
0x3b,0x2d,0xeb,0x25,0x49,0xfa,0xa3,0xaa,0x39,0xa7,0xc5,0xa7,0x50,0x11,0x36,0xfb,
0xc6,0x67,0x4a,0xf5,0xa5,0x12,0x65,0x7e,0xb0,0xdf,0xaf,0x4e,0xb3,0x61,0x7f,0x2f } };
void CLASS gamma_curve (double pwr, double ts, int mode, int imax)
{
int i;
double g[6], bnd[2]={0,0}, r;
g[0] = pwr;
g[1] = ts;
g[2] = g[3] = g[4] = 0;
bnd[g[1] >= 1] = 1;
if (g[1] && (g[1]-1)*(g[0]-1) <= 0) {
for (i=0; i < 48; i++) {
g[2] = (bnd[0] + bnd[1])/2;
if (g[0]) bnd[(pow(g[2]/g[1],-g[0]) - 1)/g[0] - 1/g[2] > -1] = g[2];
else bnd[g[2]/exp(1-1/g[2]) < g[1]] = g[2];
}
g[3] = g[2] / g[1];
if (g[0]) g[4] = g[2] * (1/g[0] - 1);
}
if (g[0]) g[5] = 1 / (g[1]*SQR(g[3])/2 - g[4]*(1 - g[3]) +
(1 - pow(g[3],1+g[0]))*(1 + g[4])/(1 + g[0])) - 1;
else g[5] = 1 / (g[1]*SQR(g[3])/2 + 1
- g[2] - g[3] - g[2]*g[3]*(log(g[3]) - 1)) - 1;
if (!mode--) {
memcpy (gamm, g, sizeof gamm);
return;
}
for (i=0; i < 0x10000; i++) {
curve[i] = 0xffff;
if ((r = (double) i / imax) < 1)
curve[i] = 0x10000 * ( mode
? (r < g[3] ? r*g[1] : (g[0] ? pow( r,g[0])*(1+g[4])-g[4] : log(r)*g[2]+1))
: (r < g[2] ? r/g[1] : (g[0] ? pow((r+g[4])/(1+g[4]),1/g[0]) : exp((r-1)/g[2]))));
}
}
void CLASS pseudoinverse (double (*in)[3], double (*out)[3], int size)
{
double work[3][6], num;
int i, j, k;
for (i=0; i < 3; i++) {
for (j=0; j < 6; j++)
work[i][j] = j == i+3;
for (j=0; j < 3; j++)
for (k=0; k < size; k++)
work[i][j] += in[k][i] * in[k][j];
}
for (i=0; i < 3; i++) {
num = work[i][i];
for (j=0; j < 6; j++)
work[i][j] /= num;
for (k=0; k < 3; k++) {
if (k==i) continue;
num = work[k][i];
for (j=0; j < 6; j++)
work[k][j] -= work[i][j] * num;
}
}
for (i=0; i < size; i++)
for (j=0; j < 3; j++)
for (out[i][j]=k=0; k < 3; k++)
out[i][j] += work[j][k+3] * in[i][k];
}
void CLASS cam_xyz_coeff (float _rgb_cam[3][4], double cam_xyz[4][3])
{
double cam_rgb[4][3], inverse[4][3], num;
int i, j, k;
for (i=0; i < colors; i++) /* Multiply out XYZ colorspace */
for (j=0; j < 3; j++)
for (cam_rgb[i][j] = k=0; k < 3; k++)
cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j];
for (i=0; i < colors; i++) { /* Normalize cam_rgb so that */
for (num=j=0; j < 3; j++) /* cam_rgb * (1,1,1) is (1,1,1,1) */
num += cam_rgb[i][j];
if(num > 0.00001)
{
for (j=0; j < 3; j++)
cam_rgb[i][j] /= num;
pre_mul[i] = 1 / num;
}
else
{
for (j=0; j < 3; j++)
cam_rgb[i][j] = 0.0;
pre_mul[i] = 1.0;
}
}
pseudoinverse (cam_rgb, inverse, colors);
for (i=0; i < 3; i++)
for (j=0; j < colors; j++)
_rgb_cam[i][j] = inverse[j][i];
}
#ifdef COLORCHECK
void CLASS colorcheck()
{
#define NSQ 24
// Coordinates of the GretagMacbeth ColorChecker squares
// width, height, 1st_column, 1st_row
int cut[NSQ][4]; // you must set these
// ColorChecker Chart under 6500-kelvin illumination
static const double gmb_xyY[NSQ][3] = {
{ 0.400, 0.350, 10.1 }, // Dark Skin
{ 0.377, 0.345, 35.8 }, // Light Skin
{ 0.247, 0.251, 19.3 }, // Blue Sky
{ 0.337, 0.422, 13.3 }, // Foliage
{ 0.265, 0.240, 24.3 }, // Blue Flower
{ 0.261, 0.343, 43.1 }, // Bluish Green
{ 0.506, 0.407, 30.1 }, // Orange
{ 0.211, 0.175, 12.0 }, // Purplish Blue
{ 0.453, 0.306, 19.8 }, // Moderate Red
{ 0.285, 0.202, 6.6 }, // Purple
{ 0.380, 0.489, 44.3 }, // Yellow Green
{ 0.473, 0.438, 43.1 }, // Orange Yellow
{ 0.187, 0.129, 6.1 }, // Blue
{ 0.305, 0.478, 23.4 }, // Green
{ 0.539, 0.313, 12.0 }, // Red
{ 0.448, 0.470, 59.1 }, // Yellow
{ 0.364, 0.233, 19.8 }, // Magenta
{ 0.196, 0.252, 19.8 }, // Cyan
{ 0.310, 0.316, 90.0 }, // White
{ 0.310, 0.316, 59.1 }, // Neutral 8
{ 0.310, 0.316, 36.2 }, // Neutral 6.5
{ 0.310, 0.316, 19.8 }, // Neutral 5
{ 0.310, 0.316, 9.0 }, // Neutral 3.5
{ 0.310, 0.316, 3.1 } }; // Black
double gmb_cam[NSQ][4], gmb_xyz[NSQ][3];
double inverse[NSQ][3], cam_xyz[4][3], balance[4], num;
int c, i, j, k, sq, row, col, pass, count[4];
memset (gmb_cam, 0, sizeof gmb_cam);
for (sq=0; sq < NSQ; sq++) {
FORCC count[c] = 0;
for (row=cut[sq][3]; row < cut[sq][3]+cut[sq][1]; row++)
for (col=cut[sq][2]; col < cut[sq][2]+cut[sq][0]; col++) {
c = FC(row,col);
if (c >= colors) c -= 2;
gmb_cam[sq][c] += BAYER2(row,col);
BAYER2(row,col) = black + (BAYER2(row,col)-black)/2;
count[c]++;
}
FORCC gmb_cam[sq][c] = gmb_cam[sq][c]/count[c] - black;
gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1];
gmb_xyz[sq][1] = gmb_xyY[sq][2];
gmb_xyz[sq][2] = gmb_xyY[sq][2] *
(1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1];
}
pseudoinverse (gmb_xyz, inverse, NSQ);
for (pass=0; pass < 2; pass++) {
for (raw_color = i=0; i < colors; i++)
for (j=0; j < 3; j++)
for (cam_xyz[i][j] = k=0; k < NSQ; k++)
cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j];
cam_xyz_coeff (rgb_cam, cam_xyz);
FORCC balance[c] = pre_mul[c] * gmb_cam[20][c];
for (sq=0; sq < NSQ; sq++)
FORCC gmb_cam[sq][c] *= balance[c];
}
if (verbose) {
printf (" { \"%s %s\", %d,\n\t{", make, model, black);
num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]);
FORCC for (j=0; j < 3; j++)
printf ("%c%d", (c | j) ? ',':' ', (int) (cam_xyz[c][j] * num + 0.5));
puts (" } },");
}
#undef NSQ
}
#endif
void CLASS hat_transform (float *temp, float *base, int st, int size, int sc)
{
int i;
for (i=0; i < sc; i++)
temp[i] = 2*base[st*i] + base[st*(sc-i)] + base[st*(i+sc)];
for (; i+sc < size; i++)
temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(i+sc)];
for (; i < size; i++)
temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(2*size-2-(i+sc))];
}
#if !defined(LIBRAW_USE_OPENMP)
void CLASS wavelet_denoise()
{
float *fimg=0, *temp, thold, mul[2], avg, diff;
int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2];
ushort *window[4];
static const float noise[] =
{ 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 };
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr,_("Wavelet denoising...\n"));
#endif
while (maximum << scale < 0x10000) scale++;
maximum <<= --scale;
black <<= scale;
FORC4 cblack[c] <<= scale;
if ((size = iheight*iwidth) < 0x15550000)
fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg);
merror (fimg, "wavelet_denoise()");
temp = fimg + size*3;
if ((nc = colors) == 3 && filters) nc++;
FORC(nc) { /* denoise R,G1,B,G3 individually */
for (i=0; i < size; i++)
fimg[i] = 256 * sqrt((double)(image[i][c] << scale));
for (hpass=lev=0; lev < 5; lev++) {
lpass = size*((lev & 1)+1);
for (row=0; row < iheight; row++) {
hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev);
for (col=0; col < iwidth; col++)
fimg[lpass + row*iwidth + col] = temp[col] * 0.25;
}
for (col=0; col < iwidth; col++) {
hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev);
for (row=0; row < iheight; row++)
fimg[lpass + row*iwidth + col] = temp[row] * 0.25;
}
thold = threshold * noise[lev];
for (i=0; i < size; i++) {
fimg[hpass+i] -= fimg[lpass+i];
if (fimg[hpass+i] < -thold) fimg[hpass+i] += thold;
else if (fimg[hpass+i] > thold) fimg[hpass+i] -= thold;
else fimg[hpass+i] = 0;
if (hpass) fimg[i] += fimg[hpass+i];
}
hpass = lpass;
}
for (i=0; i < size; i++)
image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000);
}
if (filters && colors == 3) { /* pull G1 and G3 closer together */
for (row=0; row < 2; row++) {
mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1];
blk[row] = cblack[FC(row,0) | 1];
}
for (i=0; i < 4; i++)
window[i] = (ushort *) fimg + width*i;
for (wlast=-1, row=1; row < height-1; row++) {
while (wlast < row+1) {
for (wlast++, i=0; i < 4; i++)
window[(i+3) & 3] = window[i];
for (col = FC(wlast,1) & 1; col < width; col+=2)
window[2][col] = BAYER(wlast,col);
}
thold = threshold/512;
for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) {
avg = ( window[0][col-1] + window[0][col+1] +
window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 )
* mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5;
avg = avg < 0 ? 0 : sqrt(avg);
diff = sqrt((double)BAYER(row,col)) - avg;
if (diff < -thold) diff += thold;
else if (diff > thold) diff -= thold;
else diff = 0;
BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5);
}
}
}
free (fimg);
}
#else /* LIBRAW_USE_OPENMP */
void CLASS wavelet_denoise()
{
float *fimg=0, *temp, thold, mul[2], avg, diff;
int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2];
ushort *window[4];
static const float noise[] =
{ 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 };
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr,_("Wavelet denoising...\n"));
#endif
while (maximum << scale < 0x10000) scale++;
maximum <<= --scale;
black <<= scale;
FORC4 cblack[c] <<= scale;
if ((size = iheight*iwidth) < 0x15550000)
fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg);
merror (fimg, "wavelet_denoise()");
temp = fimg + size*3;
if ((nc = colors) == 3 && filters) nc++;
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp parallel default(shared) private(i,col,row,thold,lev,lpass,hpass,temp,c) firstprivate(scale,size)
#endif
{
temp = (float*)malloc( (iheight + iwidth) * sizeof *fimg);
FORC(nc) { /* denoise R,G1,B,G3 individually */
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp for
#endif
for (i=0; i < size; i++)
fimg[i] = 256 * sqrt((double)(image[i][c] << scale));
for (hpass=lev=0; lev < 5; lev++) {
lpass = size*((lev & 1)+1);
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp for
#endif
for (row=0; row < iheight; row++) {
hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev);
for (col=0; col < iwidth; col++)
fimg[lpass + row*iwidth + col] = temp[col] * 0.25;
}
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp for
#endif
for (col=0; col < iwidth; col++) {
hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev);
for (row=0; row < iheight; row++)
fimg[lpass + row*iwidth + col] = temp[row] * 0.25;
}
thold = threshold * noise[lev];
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp for
#endif
for (i=0; i < size; i++) {
fimg[hpass+i] -= fimg[lpass+i];
if (fimg[hpass+i] < -thold) fimg[hpass+i] += thold;
else if (fimg[hpass+i] > thold) fimg[hpass+i] -= thold;
else fimg[hpass+i] = 0;
if (hpass) fimg[i] += fimg[hpass+i];
}
hpass = lpass;
}
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp for
#endif
for (i=0; i < size; i++)
image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000);
}
free(temp);
} /* end omp parallel */
/* the following loops are hard to parallize, no idea yes,
* problem is wlast which is carrying dependency
* second part should be easyer, but did not yet get it right.
*/
if (filters && colors == 3) { /* pull G1 and G3 closer together */
for (row=0; row < 2; row++){
mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1];
blk[row] = cblack[FC(row,0) | 1];
}
for (i=0; i < 4; i++)
window[i] = (ushort *) fimg + width*i;
for (wlast=-1, row=1; row < height-1; row++) {
while (wlast < row+1) {
for (wlast++, i=0; i < 4; i++)
window[(i+3) & 3] = window[i];
for (col = FC(wlast,1) & 1; col < width; col+=2)
window[2][col] = BAYER(wlast,col);
}
thold = threshold/512;
for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) {
avg = ( window[0][col-1] + window[0][col+1] +
window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 )
* mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5;
avg = avg < 0 ? 0 : sqrt(avg);
diff = sqrt((double)BAYER(row,col)) - avg;
if (diff < -thold) diff += thold;
else if (diff > thold) diff -= thold;
else diff = 0;
BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5);
}
}
}
free (fimg);
}
#endif
// green equilibration
void CLASS green_matching()
{
int i,j;
double m1,m2,c1,c2;
int o1_1,o1_2,o1_3,o1_4;
int o2_1,o2_2,o2_3,o2_4;
ushort (*img)[4];
const int margin = 3;
int oj = 2, oi = 2;
float f;
const float thr = 0.01f;
if(half_size || shrink) return;
if(FC(oj, oi) != 3) oj++;
if(FC(oj, oi) != 3) oi++;
if(FC(oj, oi) != 3) oj--;
img = (ushort (*)[4]) calloc (height*width, sizeof *image);
merror (img, "green_matching()");
memcpy(img,image,height*width*sizeof *image);
for(j=oj;j<height-margin;j+=2)
for(i=oi;i<width-margin;i+=2){
o1_1=img[(j-1)*width+i-1][1];
o1_2=img[(j-1)*width+i+1][1];
o1_3=img[(j+1)*width+i-1][1];
o1_4=img[(j+1)*width+i+1][1];
o2_1=img[(j-2)*width+i][3];
o2_2=img[(j+2)*width+i][3];
o2_3=img[j*width+i-2][3];
o2_4=img[j*width+i+2][3];
m1=(o1_1+o1_2+o1_3+o1_4)/4.0;
m2=(o2_1+o2_2+o2_3+o2_4)/4.0;
c1=(abs(o1_1-o1_2)+abs(o1_1-o1_3)+abs(o1_1-o1_4)+abs(o1_2-o1_3)+abs(o1_3-o1_4)+abs(o1_2-o1_4))/6.0;
c2=(abs(o2_1-o2_2)+abs(o2_1-o2_3)+abs(o2_1-o2_4)+abs(o2_2-o2_3)+abs(o2_3-o2_4)+abs(o2_2-o2_4))/6.0;
if((img[j*width+i][3]<maximum*0.95)&&(c1<maximum*thr)&&(c2<maximum*thr))
{
f = image[j*width+i][3]*m1/m2;
image[j*width+i][3]=f>0xffff?0xffff:f;
}
}
free(img);
}
void CLASS scale_colors()
{
unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8];
int val, dark, sat;
double dsum[8], dmin, dmax;
float scale_mul[4], fr, fc;
ushort *img=0, *pix;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS,0,2);
#endif
if (user_mul[0])
memcpy (pre_mul, user_mul, sizeof pre_mul);
if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) {
memset (dsum, 0, sizeof dsum);
bottom = MIN (greybox[1]+greybox[3], height);
right = MIN (greybox[0]+greybox[2], width);
for (row=greybox[1]; row < bottom; row += 8)
for (col=greybox[0]; col < right; col += 8) {
memset (sum, 0, sizeof sum);
for (y=row; y < row+8 && y < bottom; y++)
for (x=col; x < col+8 && x < right; x++)
FORC4 {
if (filters) {
c = fcol(y,x);
val = BAYER2(y,x);
} else
val = image[y*width+x][c];
if (val > maximum-25) goto skip_block;
if ((val -= cblack[c]) < 0) val = 0;
sum[c] += val;
sum[c+4]++;
if (filters) break;
}
FORC(8) dsum[c] += sum[c];
skip_block: ;
}
FORC4 if (dsum[c]) pre_mul[c] = dsum[c+4] / dsum[c];
}
if (use_camera_wb && cam_mul[0] != -1) {
memset (sum, 0, sizeof sum);
for (row=0; row < 8; row++)
for (col=0; col < 8; col++) {
c = FC(row,col);
if ((val = white[row][col] - cblack[c]) > 0)
sum[c] += val;
sum[c+4]++;
}
#ifdef LIBRAW_LIBRARY_BUILD
if(load_raw == &LibRaw::nikon_load_sraw)
{
// Nikon sRAW: camera WB already applied:
pre_mul[0]=pre_mul[1]=pre_mul[2]=pre_mul[3]=1.0;
}
else
#endif
if (sum[0] && sum[1] && sum[2] && sum[3])
FORC4 pre_mul[c] = (float) sum[c+4] / sum[c];
else if (cam_mul[0] && cam_mul[2])
memcpy (pre_mul, cam_mul, sizeof pre_mul);
else
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_BAD_CAMERA_WB;
#endif
#ifdef DCRAW_VERBOSE
fprintf (stderr,_("%s: Cannot use camera white balance.\n"), ifname);
#endif
}
}
#ifdef LIBRAW_LIBRARY_BUILD
// Nikon sRAW, daylight
if (load_raw == &LibRaw::nikon_load_sraw
&& !use_camera_wb && !use_auto_wb
&& cam_mul[0] > 0.001f && cam_mul[1] > 0.001f && cam_mul[2] > 0.001f )
{
for(c=0;c<3;c++)
pre_mul[c]/=cam_mul[c];
}
#endif
if (pre_mul[1] == 0) pre_mul[1] = 1;
if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1;
dark = black;
sat = maximum;
if (threshold) wavelet_denoise();
maximum -= black;
for (dmin=DBL_MAX, dmax=c=0; c < 4; c++) {
if (dmin > pre_mul[c])
dmin = pre_mul[c];
if (dmax < pre_mul[c])
dmax = pre_mul[c];
}
if (!highlight) dmax = dmin;
FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum;
#ifdef DCRAW_VERBOSE
if (verbose) {
fprintf (stderr,
_("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat);
FORC4 fprintf (stderr, " %f", pre_mul[c]);
fputc ('\n', stderr);
}
#endif
if (filters > 1000 && (cblack[4]+1)/2 == 1 && (cblack[5]+1)/2 == 1) {
FORC4 cblack[FC(c/2,c%2)] +=
cblack[6 + c/2 % cblack[4] * cblack[5] + c%2 % cblack[5]];
cblack[4] = cblack[5] = 0;
}
size = iheight*iwidth;
#ifdef LIBRAW_LIBRARY_BUILD
scale_colors_loop(scale_mul);
#else
for (i=0; i < size*4; i++) {
if (!(val = image[0][i])) continue;
if (cblack[4] && cblack[5])
val -= cblack[6 + i/4 / iwidth % cblack[4] * cblack[5] +
i/4 % iwidth % cblack[5]];
val -= cblack[i & 3];
val *= scale_mul[i & 3];
image[0][i] = CLIP(val);
}
#endif
if ((aber[0] != 1 || aber[2] != 1) && colors == 3) {
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf (stderr,_("Correcting chromatic aberration...\n"));
#endif
for (c=0; c < 4; c+=2) {
if (aber[c] == 1) continue;
img = (ushort *) malloc (size * sizeof *img);
merror (img, "scale_colors()");
for (i=0; i < size; i++)
img[i] = image[i][c];
for (row=0; row < iheight; row++) {
ur = fr = (row - iheight*0.5) * aber[c] + iheight*0.5;
if (ur > iheight-2) continue;
fr -= ur;
for (col=0; col < iwidth; col++) {
uc = fc = (col - iwidth*0.5) * aber[c] + iwidth*0.5;
if (uc > iwidth-2) continue;
fc -= uc;
pix = img + ur*iwidth + uc;
image[row*iwidth+col][c] =
(pix[ 0]*(1-fc) + pix[ 1]*fc) * (1-fr) +
(pix[iwidth]*(1-fc) + pix[iwidth+1]*fc) * fr;
}
}
free(img);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS,1,2);
#endif
}
void CLASS pre_interpolate()
{
ushort (*img)[4];
int row, col, c;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE,0,2);
#endif
if (shrink) {
if (half_size) {
height = iheight;
width = iwidth;
if (filters == 9) {
for (row=0; row < 3; row++)
for (col=1; col < 4; col++)
if (!(image[row*width+col][0] | image[row*width+col][2]))
goto break2; break2:
for ( ; row < height; row+=3)
for (col=(col-1)%3+1; col < width-1; col+=3) {
img = image + row*width+col;
for (c=0; c < 3; c+=2)
img[0][c] = (img[-1][c] + img[1][c]) >> 1;
}
}
} else {
img = (ushort (*)[4]) calloc (height, width*sizeof *img);
merror (img, "pre_interpolate()");
for (row=0; row < height; row++)
for (col=0; col < width; col++) {
c = fcol(row,col);
img[row*width+col][c] = image[(row >> 1)*iwidth+(col >> 1)][c];
}
free (image);
image = img;
shrink = 0;
}
}
if (filters > 1000 && colors == 3) {
mix_green = four_color_rgb ^ half_size;
if (four_color_rgb | half_size) colors++;
else {
for (row = FC(1,0) >> 1; row < height; row+=2)
for (col = FC(row,1) & 1; col < width; col+=2)
image[row*width+col][1] = image[row*width+col][3];
filters &= ~((filters & 0x55555555) << 1);
}
}
if (half_size) filters = 0;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE,1,2);
#endif
}
void CLASS border_interpolate (int border)
{
unsigned row, col, y, x, f, c, sum[8];
for (row=0; row < height; row++)
for (col=0; col < width; col++) {
if (col==border && row >= border && row < height-border)
col = width-border;
memset (sum, 0, sizeof sum);
for (y=row-1; y != row+2; y++)
for (x=col-1; x != col+2; x++)
if (y < height && x < width) {
f = fcol(y,x);
sum[f] += image[y*width+x][f];
sum[f+4]++;
}
f = fcol(row,col);
FORCC if (c != f && sum[c+4])
image[row*width+col][c] = sum[c] / sum[c+4];
}
}
void CLASS lin_interpolate_loop(int code[16][16][32],int size)
{
int row;
for (row=1; row < height-1; row++)
{
int col,*ip;
ushort *pix;
for (col=1; col < width-1; col++) {
int i;
int sum[4];
pix = image[row*width+col];
ip = code[row % size][col % size];
memset (sum, 0, sizeof sum);
for (i=*ip++; i--; ip+=3)
sum[ip[2]] += pix[ip[0]] << ip[1];
for (i=colors; --i; ip+=2)
pix[ip[0]] = sum[ip[0]] * ip[1] >> 8;
}
}
}
void CLASS lin_interpolate()
{
int code[16][16][32], size=16, *ip, sum[4];
int f, c, x, y, row, col, shift, color;
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr,_("Bilinear interpolation...\n"));
#endif
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,0,3);
#endif
if (filters == 9) size = 6;
border_interpolate(1);
for (row=0; row < size; row++)
for (col=0; col < size; col++) {
ip = code[row][col]+1;
f = fcol(row,col);
memset (sum, 0, sizeof sum);
for (y=-1; y <= 1; y++)
for (x=-1; x <= 1; x++) {
shift = (y==0) + (x==0);
color = fcol(row+y,col+x);
if (color == f) continue;
*ip++ = (width*y + x)*4 + color;
*ip++ = shift;
*ip++ = color;
sum[color] += 1 << shift;
}
code[row][col][0] = (ip - code[row][col]) / 3;
FORCC
if (c != f) {
*ip++ = c;
*ip++ = sum[c]>0?256 / sum[c]:0;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,1,3);
#endif
lin_interpolate_loop(code,size);
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,2,3);
#endif
}
/*
This algorithm is officially called:
"Interpolation using a Threshold-based variable number of gradients"
described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html
I've extended the basic idea to work with non-Bayer filter arrays.
Gradients are numbered clockwise from NW=0 to W=7.
*/
void CLASS vng_interpolate()
{
static const signed char *cp, terms[] = {
-2,-2,+0,-1,0,0x01, -2,-2,+0,+0,1,0x01, -2,-1,-1,+0,0,0x01,
-2,-1,+0,-1,0,0x02, -2,-1,+0,+0,0,0x03, -2,-1,+0,+1,1,0x01,
-2,+0,+0,-1,0,0x06, -2,+0,+0,+0,1,0x02, -2,+0,+0,+1,0,0x03,
-2,+1,-1,+0,0,0x04, -2,+1,+0,-1,1,0x04, -2,+1,+0,+0,0,0x06,
-2,+1,+0,+1,0,0x02, -2,+2,+0,+0,1,0x04, -2,+2,+0,+1,0,0x04,
-1,-2,-1,+0,0,0x80, -1,-2,+0,-1,0,0x01, -1,-2,+1,-1,0,0x01,
-1,-2,+1,+0,1,0x01, -1,-1,-1,+1,0,0x88, -1,-1,+1,-2,0,0x40,
-1,-1,+1,-1,0,0x22, -1,-1,+1,+0,0,0x33, -1,-1,+1,+1,1,0x11,
-1,+0,-1,+2,0,0x08, -1,+0,+0,-1,0,0x44, -1,+0,+0,+1,0,0x11,
-1,+0,+1,-2,1,0x40, -1,+0,+1,-1,0,0x66, -1,+0,+1,+0,1,0x22,
-1,+0,+1,+1,0,0x33, -1,+0,+1,+2,1,0x10, -1,+1,+1,-1,1,0x44,
-1,+1,+1,+0,0,0x66, -1,+1,+1,+1,0,0x22, -1,+1,+1,+2,0,0x10,
-1,+2,+0,+1,0,0x04, -1,+2,+1,+0,1,0x04, -1,+2,+1,+1,0,0x04,
+0,-2,+0,+0,1,0x80, +0,-1,+0,+1,1,0x88, +0,-1,+1,-2,0,0x40,
+0,-1,+1,+0,0,0x11, +0,-1,+2,-2,0,0x40, +0,-1,+2,-1,0,0x20,
+0,-1,+2,+0,0,0x30, +0,-1,+2,+1,1,0x10, +0,+0,+0,+2,1,0x08,
+0,+0,+2,-2,1,0x40, +0,+0,+2,-1,0,0x60, +0,+0,+2,+0,1,0x20,
+0,+0,+2,+1,0,0x30, +0,+0,+2,+2,1,0x10, +0,+1,+1,+0,0,0x44,
+0,+1,+1,+2,0,0x10, +0,+1,+2,-1,1,0x40, +0,+1,+2,+0,0,0x60,
+0,+1,+2,+1,0,0x20, +0,+1,+2,+2,0,0x10, +1,-2,+1,+0,0,0x80,
+1,-1,+1,+1,0,0x88, +1,+0,+1,+2,0,0x08, +1,+0,+2,-1,0,0x40,
+1,+0,+2,+1,0,0x10
}, chood[] = { -1,-1, -1,0, -1,+1, 0,+1, +1,+1, +1,0, +1,-1, 0,-1 };
ushort (*brow[5])[4], *pix;
int prow=8, pcol=2, *ip, *code[16][16], gval[8], gmin, gmax, sum[4];
int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag;
int g, diff, thold, num, c;
lin_interpolate();
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr,_("VNG interpolation...\n"));
#endif
if (filters == 1) prow = pcol = 16;
if (filters == 9) prow = pcol = 6;
ip = (int *) calloc (prow*pcol, 1280);
merror (ip, "vng_interpolate()");
for (row=0; row < prow; row++) /* Precalculate for VNG */
for (col=0; col < pcol; col++) {
code[row][col] = ip;
for (cp=terms, t=0; t < 64; t++) {
y1 = *cp++; x1 = *cp++;
y2 = *cp++; x2 = *cp++;
weight = *cp++;
grads = *cp++;
color = fcol(row+y1,col+x1);
if (fcol(row+y2,col+x2) != color) continue;
diag = (fcol(row,col+1) == color && fcol(row+1,col) == color) ? 2:1;
if (abs(y1-y2) == diag && abs(x1-x2) == diag) continue;
*ip++ = (y1*width + x1)*4 + color;
*ip++ = (y2*width + x2)*4 + color;
*ip++ = weight;
for (g=0; g < 8; g++)
if (grads & 1<<g) *ip++ = g;
*ip++ = -1;
}
*ip++ = INT_MAX;
for (cp=chood, g=0; g < 8; g++) {
y = *cp++; x = *cp++;
*ip++ = (y*width + x) * 4;
color = fcol(row,col);
if (fcol(row+y,col+x) != color && fcol(row+y*2,col+x*2) == color)
*ip++ = (y*width + x) * 8 + color;
else
*ip++ = 0;
}
}
brow[4] = (ushort (*)[4]) calloc (width*3, sizeof **brow);
merror (brow[4], "vng_interpolate()");
for (row=0; row < 3; row++)
brow[row] = brow[4] + row*width;
for (row=2; row < height-2; row++) { /* Do VNG interpolation */
#ifdef LIBRAW_LIBRARY_BUILD
if(!((row-2)%256))RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,(row-2)/256+1,((height-3)/256)+1);
#endif
for (col=2; col < width-2; col++) {
pix = image[row*width+col];
ip = code[row % prow][col % pcol];
memset (gval, 0, sizeof gval);
while ((g = ip[0]) != INT_MAX) { /* Calculate gradients */
diff = ABS(pix[g] - pix[ip[1]]) << ip[2];
gval[ip[3]] += diff;
ip += 5;
if ((g = ip[-1]) == -1) continue;
gval[g] += diff;
while ((g = *ip++) != -1)
gval[g] += diff;
}
ip++;
gmin = gmax = gval[0]; /* Choose a threshold */
for (g=1; g < 8; g++) {
if (gmin > gval[g]) gmin = gval[g];
if (gmax < gval[g]) gmax = gval[g];
}
if (gmax == 0) {
memcpy (brow[2][col], pix, sizeof *image);
continue;
}
thold = gmin + (gmax >> 1);
memset (sum, 0, sizeof sum);
color = fcol(row,col);
for (num=g=0; g < 8; g++,ip+=2) { /* Average the neighbors */
if (gval[g] <= thold) {
FORCC
if (c == color && ip[1])
sum[c] += (pix[c] + pix[ip[1]]) >> 1;
else
sum[c] += pix[ip[0] + c];
num++;
}
}
FORCC { /* Save to buffer */
t = pix[color];
if (c != color)
t += (sum[c] - sum[color]) / num;
brow[2][col][c] = CLIP(t);
}
}
if (row > 3) /* Write buffer to image */
memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image);
for (g=0; g < 4; g++)
brow[(g-1) & 3] = brow[g];
}
memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image);
memcpy (image[(row-1)*width+2], brow[1]+2, (width-4)*sizeof *image);
free (brow[4]);
free (code[0][0]);
}
/*
Patterned Pixel Grouping Interpolation by Alain Desbiolles
*/
void CLASS ppg_interpolate()
{
int dir[5] = { 1, width, -1, -width, 1 };
int row, col, diff[2], guess[2], c, d, i;
ushort (*pix)[4];
border_interpolate(3);
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr,_("PPG interpolation...\n"));
#endif
/* Fill in the green layer with gradients and pattern recognition: */
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,0,3);
#ifdef LIBRAW_USE_OPENMP
#pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static)
#endif
#endif
for (row=3; row < height-3; row++)
for (col=3+(FC(row,3) & 1), c=FC(row,col); col < width-3; col+=2) {
pix = image + row*width+col;
for (i=0; (d=dir[i]) > 0; i++) {
guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2
- pix[-2*d][c] - pix[2*d][c];
diff[i] = ( ABS(pix[-2*d][c] - pix[ 0][c]) +
ABS(pix[ 2*d][c] - pix[ 0][c]) +
ABS(pix[ -d][1] - pix[ d][1]) ) * 3 +
( ABS(pix[ 3*d][1] - pix[ d][1]) +
ABS(pix[-3*d][1] - pix[-d][1]) ) * 2;
}
d = dir[i = diff[0] > diff[1]];
pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]);
}
/* Calculate red and blue for each green pixel: */
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,1,3);
#ifdef LIBRAW_USE_OPENMP
#pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static)
#endif
#endif
for (row=1; row < height-1; row++)
for (col=1+(FC(row,2) & 1), c=FC(row,col+1); col < width-1; col+=2) {
pix = image + row*width+col;
for (i=0; (d=dir[i]) > 0; c=2-c, i++)
pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2*pix[0][1]
- pix[-d][1] - pix[d][1]) >> 1);
}
/* Calculate blue for red pixels and vice versa: */
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,2,3);
#ifdef LIBRAW_USE_OPENMP
#pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static)
#endif
#endif
for (row=1; row < height-1; row++)
for (col=1+(FC(row,1) & 1), c=2-FC(row,col); col < width-1; col+=2) {
pix = image + row*width+col;
for (i=0; (d=dir[i]+dir[i+1]) > 0; i++) {
diff[i] = ABS(pix[-d][c] - pix[d][c]) +
ABS(pix[-d][1] - pix[0][1]) +
ABS(pix[ d][1] - pix[0][1]);
guess[i] = pix[-d][c] + pix[d][c] + 2*pix[0][1]
- pix[-d][1] - pix[d][1];
}
if (diff[0] != diff[1])
pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1);
else
pix[0][c] = CLIP((guess[0]+guess[1]) >> 2);
}
}
void CLASS cielab (ushort rgb[3], short lab[3])
{
int c, i, j, k;
float r, xyz[3];
#ifdef LIBRAW_NOTHREADS
static float cbrt[0x10000], xyz_cam[3][4];
#else
#define cbrt tls->ahd_data.cbrt
#define xyz_cam tls->ahd_data.xyz_cam
#endif
if (!rgb) {
#ifndef LIBRAW_NOTHREADS
if(cbrt[0] < -1.0f)
#endif
for (i=0; i < 0x10000; i++) {
r = i / 65535.0;
cbrt[i] = r > 0.008856 ? pow(r,1.f/3.0f) : 7.787f*r + 16.f/116.0f;
}
for (i=0; i < 3; i++)
for (j=0; j < colors; j++)
for (xyz_cam[i][j] = k=0; k < 3; k++)
xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i];
return;
}
xyz[0] = xyz[1] = xyz[2] = 0.5;
FORCC {
xyz[0] += xyz_cam[0][c] * rgb[c];
xyz[1] += xyz_cam[1][c] * rgb[c];
xyz[2] += xyz_cam[2][c] * rgb[c];
}
xyz[0] = cbrt[CLIP((int) xyz[0])];
xyz[1] = cbrt[CLIP((int) xyz[1])];
xyz[2] = cbrt[CLIP((int) xyz[2])];
lab[0] = 64 * (116 * xyz[1] - 16);
lab[1] = 64 * 500 * (xyz[0] - xyz[1]);
lab[2] = 64 * 200 * (xyz[1] - xyz[2]);
#ifndef LIBRAW_NOTHREADS
#undef cbrt
#undef xyz_cam
#endif
}
#define TS 512 /* Tile Size */
#define fcol(row,col) xtrans[(row+6) % 6][(col+6) % 6]
/*
Frank Markesteijn's algorithm for Fuji X-Trans sensors
*/
void CLASS xtrans_interpolate (int passes)
{
int c, d, f, g, h, i, v, ng, row, col, top, left, mrow, mcol;
int val, ndir, pass, hm[8], avg[4], color[3][8];
static const short orth[12] = { 1,0,0,1,-1,0,0,-1,1,0,0,1 },
patt[2][16] = { { 0,1,0,-1,2,0,-1,0,1,1,1,-1,0,0,0,0 },
{ 0,1,0,-2,1,0,-2,0,1,1,-2,-2,1,-1,-1,1 } },
dir[4] = { 1,TS,TS+1,TS-1 };
short allhex[3][3][2][8], *hex;
ushort min, max, sgrow, sgcol;
ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4];
short (*lab) [TS][3], (*lix)[3];
float (*drv)[TS][TS], diff[6], tr;
char (*homo)[TS][TS], *buffer;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf (stderr,_("%d-pass X-Trans interpolation...\n"), passes);
#endif
cielab (0,0);
ndir = 4 << (passes > 1);
buffer = (char *) malloc (TS*TS*(ndir*11+6));
merror (buffer, "xtrans_interpolate()");
rgb = (ushort(*)[TS][TS][3]) buffer;
lab = (short (*) [TS][3])(buffer + TS*TS*(ndir*6));
drv = (float (*)[TS][TS]) (buffer + TS*TS*(ndir*6+6));
homo = (char (*)[TS][TS]) (buffer + TS*TS*(ndir*10+6));
/* Map a green hexagon around each non-green pixel and vice versa: */
for (row=0; row < 3; row++)
for (col=0; col < 3; col++)
for (ng=d=0; d < 10; d+=2) {
g = fcol(row,col) == 1;
if (fcol(row+orth[d],col+orth[d+2]) == 1) ng=0; else ng++;
if (ng == 4) { sgrow = row; sgcol = col; }
if (ng == g+1) FORC(8) {
v = orth[d ]*patt[g][c*2] + orth[d+1]*patt[g][c*2+1];
h = orth[d+2]*patt[g][c*2] + orth[d+3]*patt[g][c*2+1];
allhex[row][col][0][c^(g*2 & d)] = h + v*width;
allhex[row][col][1][c^(g*2 & d)] = h + v*TS;
}
}
/* Set green1 and green3 to the minimum and maximum allowed values: */
for (row=2; row < height-2; row++)
for (min=~(max=0), col=2; col < width-2; col++) {
if (fcol(row,col) == 1 && (min=~(max=0))) continue;
pix = image + row*width + col;
hex = allhex[row % 3][col % 3][0];
if (!max) FORC(6) {
val = pix[hex[c]][1];
if (min > val) min = val;
if (max < val) max = val;
}
pix[0][1] = min;
pix[0][3] = max;
switch ((row-sgrow) % 3) {
case 1: if (row < height-3) { row++; col--; } break;
case 2: if ((min=~(max=0)) && (col+=2) < width-3 && row > 2) row--;
}
}
for (top=3; top < height-19; top += TS-16)
for (left=3; left < width-19; left += TS-16) {
mrow = MIN (top+TS, height-3);
mcol = MIN (left+TS, width-3);
for (row=top; row < mrow; row++)
for (col=left; col < mcol; col++)
memcpy (rgb[0][row-top][col-left], image[row*width+col], 6);
FORC3 memcpy (rgb[c+1], rgb[0], sizeof *rgb);
/* Interpolate green horizontally, vertically, and along both diagonals: */
for (row=top; row < mrow; row++)
for (col=left; col < mcol; col++) {
if ((f = fcol(row,col)) == 1) continue;
pix = image + row*width + col;
hex = allhex[row % 3][col % 3][0];
color[1][0] = 174 * (pix[ hex[1]][1] + pix[ hex[0]][1]) -
46 * (pix[2*hex[1]][1] + pix[2*hex[0]][1]);
color[1][1] = 223 * pix[ hex[3]][1] + pix[ hex[2]][1] * 33 +
92 * (pix[ 0 ][f] - pix[ -hex[2]][f]);
FORC(2) color[1][2+c] =
164 * pix[hex[4+c]][1] + 92 * pix[-2*hex[4+c]][1] + 33 *
(2*pix[0][f] - pix[3*hex[4+c]][f] - pix[-3*hex[4+c]][f]);
FORC4 rgb[c^!((row-sgrow) % 3)][row-top][col-left][1] =
LIM(color[1][c] >> 8,pix[0][1],pix[0][3]);
}
for (pass=0; pass < passes; pass++) {
if (pass == 1)
memcpy (rgb+=4, buffer, 4*sizeof *rgb);
/* Recalculate green from interpolated values of closer pixels: */
if (pass) {
for (row=top+2; row < mrow-2; row++)
for (col=left+2; col < mcol-2; col++) {
if ((f = fcol(row,col)) == 1) continue;
pix = image + row*width + col;
hex = allhex[row % 3][col % 3][1];
for (d=3; d < 6; d++) {
rix = &rgb[(d-2)^!((row-sgrow) % 3)][row-top][col-left];
val = rix[-2*hex[d]][1] + 2*rix[hex[d]][1]
- rix[-2*hex[d]][f] - 2*rix[hex[d]][f] + 3*rix[0][f];
rix[0][1] = LIM(val/3,pix[0][1],pix[0][3]);
}
}
}
/* Interpolate red and blue values for solitary green pixels: */
for (row=(top-sgrow+4)/3*3+sgrow; row < mrow-2; row+=3)
for (col=(left-sgcol+4)/3*3+sgcol; col < mcol-2; col+=3) {
rix = &rgb[0][row-top][col-left];
h = fcol(row,col+1);
memset (diff, 0, sizeof diff);
for (i=1, d=0; d < 6; d++, i^=TS^1, h^=2) {
for (c=0; c < 2; c++, h^=2) {
g = 2*rix[0][1] - rix[i<<c][1] - rix[-i<<c][1];
color[h][d] = g + rix[i<<c][h] + rix[-i<<c][h];
if (d > 1)
diff[d] += SQR (rix[i<<c][1] - rix[-i<<c][1]
- rix[i<<c][h] + rix[-i<<c][h]) + SQR(g);
}
if (d > 1 && (d & 1))
if (diff[d-1] < diff[d])
FORC(2) color[c*2][d] = color[c*2][d-1];
if (d < 2 || (d & 1)) {
FORC(2) rix[0][c*2] = CLIP(color[c*2][d]/2);
rix += TS*TS;
}
}
}
/* Interpolate red for blue pixels and vice versa: */
for (row=top+3; row < mrow-3; row++)
for (col=left+3; col < mcol-3; col++) {
if ((f = 2-fcol(row,col)) == 1) continue;
rix = &rgb[0][row-top][col-left];
c = (row-sgrow) % 3 ? TS:1;
h = 3 * (c ^ TS ^ 1);
for (d=0; d < 4; d++, rix += TS*TS) {
i = d > 1 || ((d ^ c) & 1) ||
((ABS(rix[0][1]-rix[c][1])+ABS(rix[0][1]-rix[-c][1])) <
2*(ABS(rix[0][1]-rix[h][1])+ABS(rix[0][1]-rix[-h][1]))) ? c:h;
rix[0][f] = CLIP((rix[i][f] + rix[-i][f] +
2*rix[0][1] - rix[i][1] - rix[-i][1])/2);
}
}
/* Fill in red and blue for 2x2 blocks of green: */
for (row=top+2; row < mrow-2; row++) if ((row-sgrow) % 3)
for (col=left+2; col < mcol-2; col++) if ((col-sgcol) % 3) {
rix = &rgb[0][row-top][col-left];
hex = allhex[row % 3][col % 3][1];
for (d=0; d < ndir; d+=2, rix += TS*TS)
if (hex[d] + hex[d+1]) {
g = 3*rix[0][1] - 2*rix[hex[d]][1] - rix[hex[d+1]][1];
for (c=0; c < 4; c+=2) rix[0][c] =
CLIP((g + 2*rix[hex[d]][c] + rix[hex[d+1]][c])/3);
} else {
g = 2*rix[0][1] - rix[hex[d]][1] - rix[hex[d+1]][1];
for (c=0; c < 4; c+=2) rix[0][c] =
CLIP((g + rix[hex[d]][c] + rix[hex[d+1]][c])/2);
}
}
}
rgb = (ushort(*)[TS][TS][3]) buffer;
mrow -= top;
mcol -= left;
/* Convert to CIELab and differentiate in all directions: */
for (d=0; d < ndir; d++) {
for (row=2; row < mrow-2; row++)
for (col=2; col < mcol-2; col++)
cielab (rgb[d][row][col], lab[row][col]);
for (f=dir[d & 3],row=3; row < mrow-3; row++)
for (col=3; col < mcol-3; col++) {
lix = &lab[row][col];
g = 2*lix[0][0] - lix[f][0] - lix[-f][0];
drv[d][row][col] = SQR(g)
+ SQR((2*lix[0][1] - lix[f][1] - lix[-f][1] + g*500/232))
+ SQR((2*lix[0][2] - lix[f][2] - lix[-f][2] - g*500/580));
}
}
/* Build homogeneity maps from the derivatives: */
memset(homo, 0, ndir*TS*TS);
for (row=4; row < mrow-4; row++)
for (col=4; col < mcol-4; col++) {
for (tr=FLT_MAX, d=0; d < ndir; d++)
if (tr > drv[d][row][col])
tr = drv[d][row][col];
tr *= 8;
for (d=0; d < ndir; d++)
for (v=-1; v <= 1; v++)
for (h=-1; h <= 1; h++)
if (drv[d][row+v][col+h] <= tr)
homo[d][row][col]++;
}
/* Average the most homogenous pixels for the final result: */
if (height-top < TS+4) mrow = height-top+2;
if (width-left < TS+4) mcol = width-left+2;
for (row = MIN(top,8); row < mrow-8; row++)
for (col = MIN(left,8); col < mcol-8; col++) {
for (d=0; d < ndir; d++)
for (hm[d]=0, v=-2; v <= 2; v++)
for (h=-2; h <= 2; h++)
hm[d] += homo[d][row+v][col+h];
for (d=0; d < ndir-4; d++)
if (hm[d] < hm[d+4]) hm[d ] = 0; else
if (hm[d] > hm[d+4]) hm[d+4] = 0;
for (max=hm[0],d=1; d < ndir; d++)
if (max < hm[d]) max = hm[d];
max -= max >> 3;
memset (avg, 0, sizeof avg);
for (d=0; d < ndir; d++)
if (hm[d] >= max) {
FORC3 avg[c] += rgb[d][row][col][c];
avg[3]++;
}
FORC3 image[(row+top)*width+col+left][c] = avg[c]/avg[3];
}
}
free(buffer);
border_interpolate(8);
}
#undef fcol
/*
Adaptive Homogeneity-Directed interpolation is based on
the work of Keigo Hirakawa, Thomas Parks, and Paul Lee.
*/
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS ahd_interpolate_green_h_and_v(int top, int left, ushort (*out_rgb)[TS][TS][3])
{
int row, col;
int c, val;
ushort (*pix)[4];
const int rowlimit = MIN(top+TS, height-2);
const int collimit = MIN(left+TS, width-2);
for (row = top; row < rowlimit; row++) {
col = left + (FC(row,left) & 1);
for (c = FC(row,col); col < collimit; col+=2) {
pix = image + row*width+col;
val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2
- pix[-2][c] - pix[2][c]) >> 2;
out_rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]);
val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2
- pix[-2*width][c] - pix[2*width][c]) >> 2;
out_rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]);
}
}
}
void CLASS ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][3], short (*out_lab)[TS][3])
{
unsigned row, col;
int c, val;
ushort (*pix)[4];
ushort (*rix)[3];
short (*lix)[3];
float xyz[3];
const unsigned num_pix_per_row = 4*width;
const unsigned rowlimit = MIN(top+TS-1, height-3);
const unsigned collimit = MIN(left+TS-1, width-3);
ushort *pix_above;
ushort *pix_below;
int t1, t2;
for (row = top+1; row < rowlimit; row++) {
pix = image + row*width + left;
rix = &inout_rgb[row-top][0];
lix = &out_lab[row-top][0];
for (col = left+1; col < collimit; col++) {
pix++;
pix_above = &pix[0][0] - num_pix_per_row;
pix_below = &pix[0][0] + num_pix_per_row;
rix++;
lix++;
c = 2 - FC(row, col);
if (c == 1) {
c = FC(row+1,col);
t1 = 2-c;
val = pix[0][1] + (( pix[-1][t1] + pix[1][t1]
- rix[-1][1] - rix[1][1] ) >> 1);
rix[0][t1] = CLIP(val);
val = pix[0][1] + (( pix_above[c] + pix_below[c]
- rix[-TS][1] - rix[TS][1] ) >> 1);
} else {
t1 = -4+c; /* -4+c: pixel of color c to the left */
t2 = 4+c; /* 4+c: pixel of color c to the right */
val = rix[0][1] + (( pix_above[t1] + pix_above[t2]
+ pix_below[t1] + pix_below[t2]
- rix[-TS-1][1] - rix[-TS+1][1]
- rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2);
}
rix[0][c] = CLIP(val);
c = FC(row,col);
rix[0][c] = pix[0][c];
cielab(rix[0],lix[0]);
}
}
}
void CLASS ahd_interpolate_r_and_b_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][TS][3], short (*out_lab)[TS][TS][3])
{
int direction;
for (direction = 0; direction < 2; direction++) {
ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(top, left, inout_rgb[direction], out_lab[direction]);
}
}
void CLASS ahd_interpolate_build_homogeneity_map(int top, int left, short (*lab)[TS][TS][3], char (*out_homogeneity_map)[TS][2])
{
int row, col;
int tr, tc;
int direction;
int i;
short (*lix)[3];
short (*lixs[2])[3];
short *adjacent_lix;
unsigned ldiff[2][4], abdiff[2][4], leps, abeps;
static const int dir[4] = { -1, 1, -TS, TS };
const int rowlimit = MIN(top+TS-2, height-4);
const int collimit = MIN(left+TS-2, width-4);
int homogeneity;
char (*homogeneity_map_p)[2];
memset (out_homogeneity_map, 0, 2*TS*TS);
for (row=top+2; row < rowlimit; row++) {
tr = row-top;
homogeneity_map_p = &out_homogeneity_map[tr][1];
for (direction=0; direction < 2; direction++) {
lixs[direction] = &lab[direction][tr][1];
}
for (col=left+2; col < collimit; col++) {
tc = col-left;
homogeneity_map_p++;
for (direction=0; direction < 2; direction++) {
lix = ++lixs[direction];
for (i=0; i < 4; i++) {
adjacent_lix = lix[dir[i]];
ldiff[direction][i] = ABS(lix[0][0]-adjacent_lix[0]);
abdiff[direction][i] = SQR(lix[0][1]-adjacent_lix[1])
+ SQR(lix[0][2]-adjacent_lix[2]);
}
}
leps = MIN(MAX(ldiff[0][0],ldiff[0][1]),
MAX(ldiff[1][2],ldiff[1][3]));
abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]),
MAX(abdiff[1][2],abdiff[1][3]));
for (direction=0; direction < 2; direction++) {
homogeneity = 0;
for (i=0; i < 4; i++) {
if (ldiff[direction][i] <= leps && abdiff[direction][i] <= abeps) {
homogeneity++;
}
}
homogeneity_map_p[0][direction] = homogeneity;
}
}
}
}
void CLASS ahd_interpolate_combine_homogeneous_pixels(int top, int left, ushort (*rgb)[TS][TS][3], char (*homogeneity_map)[TS][2])
{
int row, col;
int tr, tc;
int i, j;
int direction;
int hm[2];
int c;
const int rowlimit = MIN(top+TS-3, height-5);
const int collimit = MIN(left+TS-3, width-5);
ushort (*pix)[4];
ushort (*rix[2])[3];
for (row=top+3; row < rowlimit; row++) {
tr = row-top;
pix = &image[row*width+left+2];
for (direction = 0; direction < 2; direction++) {
rix[direction] = &rgb[direction][tr][2];
}
for (col=left+3; col < collimit; col++) {
tc = col-left;
pix++;
for (direction = 0; direction < 2; direction++) {
rix[direction]++;
}
for (direction=0; direction < 2; direction++) {
hm[direction] = 0;
for (i=tr-1; i <= tr+1; i++) {
for (j=tc-1; j <= tc+1; j++) {
hm[direction] += homogeneity_map[i][j][direction];
}
}
}
if (hm[0] != hm[1]) {
memcpy(pix[0], rix[hm[1] > hm[0]][0], 3 * sizeof(ushort));
} else {
FORC3 {
pix[0][c] = (rix[0][0][c] + rix[1][0][c]) >> 1;
}
}
}
}
}
void CLASS ahd_interpolate()
{
int i, j, k, top, left;
float xyz_cam[3][4],r;
char *buffer;
ushort (*rgb)[TS][TS][3];
short (*lab)[TS][TS][3];
char (*homo)[TS][2];
int terminate_flag = 0;
cielab(0,0);
border_interpolate(5);
#ifdef LIBRAW_LIBRARY_BUILD
#ifdef LIBRAW_USE_OPENMP
#pragma omp parallel private(buffer,rgb,lab,homo,top,left,i,j,k) shared(xyz_cam,terminate_flag)
#endif
#endif
{
buffer = (char *) malloc (26*TS*TS); /* 1664 kB */
merror (buffer, "ahd_interpolate()");
rgb = (ushort(*)[TS][TS][3]) buffer;
lab = (short (*)[TS][TS][3])(buffer + 12*TS*TS);
homo = (char (*)[TS][2]) (buffer + 24*TS*TS);
#ifdef LIBRAW_LIBRARY_BUILD
#ifdef LIBRAW_USE_OPENMP
#pragma omp for schedule(dynamic)
#endif
#endif
for (top=2; top < height-5; top += TS-6){
#ifdef LIBRAW_LIBRARY_BUILD
#ifdef LIBRAW_USE_OPENMP
if(0== omp_get_thread_num())
#endif
if(callbacks.progress_cb) {
int rr = (*callbacks.progress_cb)(callbacks.progresscb_data,LIBRAW_PROGRESS_INTERPOLATE,top-2,height-7);
if(rr)
terminate_flag = 1;
}
#endif
for (left=2; !terminate_flag && (left < width-5); left += TS-6) {
ahd_interpolate_green_h_and_v(top, left, rgb);
ahd_interpolate_r_and_b_and_convert_to_cielab(top, left, rgb, lab);
ahd_interpolate_build_homogeneity_map(top, left, lab, homo);
ahd_interpolate_combine_homogeneous_pixels(top, left, rgb, homo);
}
}
free (buffer);
}
#ifdef LIBRAW_LIBRARY_BUILD
if(terminate_flag)
throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK;
#endif
}
#else
void CLASS ahd_interpolate()
{
int i, j, top, left, row, col, tr, tc, c, d, val, hm[2];
static const int dir[4] = { -1, 1, -TS, TS };
unsigned ldiff[2][4], abdiff[2][4], leps, abeps;
ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4];
short (*lab)[TS][TS][3], (*lix)[3];
char (*homo)[TS][TS], *buffer;
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr,_("AHD interpolation...\n"));
#endif
cielab (0,0);
border_interpolate(5);
buffer = (char *) malloc (26*TS*TS);
merror (buffer, "ahd_interpolate()");
rgb = (ushort(*)[TS][TS][3]) buffer;
lab = (short (*)[TS][TS][3])(buffer + 12*TS*TS);
homo = (char (*)[TS][TS]) (buffer + 24*TS*TS);
for (top=2; top < height-5; top += TS-6)
for (left=2; left < width-5; left += TS-6) {
/* Interpolate green horizontally and vertically: */
for (row=top; row < top+TS && row < height-2; row++) {
col = left + (FC(row,left) & 1);
for (c = FC(row,col); col < left+TS && col < width-2; col+=2) {
pix = image + row*width+col;
val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2
- pix[-2][c] - pix[2][c]) >> 2;
rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]);
val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2
- pix[-2*width][c] - pix[2*width][c]) >> 2;
rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]);
}
}
/* Interpolate red and blue, and convert to CIELab: */
for (d=0; d < 2; d++)
for (row=top+1; row < top+TS-1 && row < height-3; row++)
for (col=left+1; col < left+TS-1 && col < width-3; col++) {
pix = image + row*width+col;
rix = &rgb[d][row-top][col-left];
lix = &lab[d][row-top][col-left];
if ((c = 2 - FC(row,col)) == 1) {
c = FC(row+1,col);
val = pix[0][1] + (( pix[-1][2-c] + pix[1][2-c]
- rix[-1][1] - rix[1][1] ) >> 1);
rix[0][2-c] = CLIP(val);
val = pix[0][1] + (( pix[-width][c] + pix[width][c]
- rix[-TS][1] - rix[TS][1] ) >> 1);
} else
val = rix[0][1] + (( pix[-width-1][c] + pix[-width+1][c]
+ pix[+width-1][c] + pix[+width+1][c]
- rix[-TS-1][1] - rix[-TS+1][1]
- rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2);
rix[0][c] = CLIP(val);
c = FC(row,col);
rix[0][c] = pix[0][c];
cielab (rix[0],lix[0]);
}
/* Build homogeneity maps from the CIELab images: */
memset (homo, 0, 2*TS*TS);
for (row=top+2; row < top+TS-2 && row < height-4; row++) {
tr = row-top;
for (col=left+2; col < left+TS-2 && col < width-4; col++) {
tc = col-left;
for (d=0; d < 2; d++) {
lix = &lab[d][tr][tc];
for (i=0; i < 4; i++) {
ldiff[d][i] = ABS(lix[0][0]-lix[dir[i]][0]);
abdiff[d][i] = SQR(lix[0][1]-lix[dir[i]][1])
+ SQR(lix[0][2]-lix[dir[i]][2]);
}
}
leps = MIN(MAX(ldiff[0][0],ldiff[0][1]),
MAX(ldiff[1][2],ldiff[1][3]));
abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]),
MAX(abdiff[1][2],abdiff[1][3]));
for (d=0; d < 2; d++)
for (i=0; i < 4; i++)
if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps)
homo[d][tr][tc]++;
}
}
/* Combine the most homogenous pixels for the final result: */
for (row=top+3; row < top+TS-3 && row < height-5; row++) {
tr = row-top;
for (col=left+3; col < left+TS-3 && col < width-5; col++) {
tc = col-left;
for (d=0; d < 2; d++)
for (hm[d]=0, i=tr-1; i <= tr+1; i++)
for (j=tc-1; j <= tc+1; j++)
hm[d] += homo[d][i][j];
if (hm[0] != hm[1])
FORC3 image[row*width+col][c] = rgb[hm[1] > hm[0]][tr][tc][c];
else
FORC3 image[row*width+col][c] =
(rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1;
}
}
}
free (buffer);
}
#endif
#undef TS
void CLASS median_filter()
{
ushort (*pix)[4];
int pass, c, i, j, k, med[9];
static const uchar opt[] = /* Optimal 9-element median search */
{ 1,2, 4,5, 7,8, 0,1, 3,4, 6,7, 1,2, 4,5, 7,8,
0,3, 5,8, 4,7, 3,6, 1,4, 2,5, 4,7, 4,2, 6,4, 4,2 };
for (pass=1; pass <= med_passes; pass++) {
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_MEDIAN_FILTER,pass-1,med_passes);
#endif
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf (stderr,_("Median filter pass %d...\n"), pass);
#endif
for (c=0; c < 3; c+=2) {
for (pix = image; pix < image+width*height; pix++)
pix[0][3] = pix[0][c];
for (pix = image+width; pix < image+width*(height-1); pix++) {
if ((pix-image+1) % width < 2) continue;
for (k=0, i = -width; i <= width; i += width)
for (j = i-1; j <= i+1; j++)
med[k++] = pix[j][3] - pix[j][1];
for (i=0; i < sizeof opt; i+=2)
if (med[opt[i]] > med[opt[i+1]])
SWAP (med[opt[i]] , med[opt[i+1]]);
pix[0][c] = CLIP(med[4] + pix[0][1]);
}
}
}
}
void CLASS blend_highlights()
{
int clip=INT_MAX, row, col, c, i, j;
static const float trans[2][4][4] =
{ { { 1,1,1 }, { 1.7320508,-1.7320508,0 }, { -1,-1,2 } },
{ { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } };
static const float itrans[2][4][4] =
{ { { 1,0.8660254,-0.5 }, { 1,-0.8660254,-0.5 }, { 1,0,1 } },
{ { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } };
float cam[2][4], lab[2][4], sum[2], chratio;
if ((unsigned) (colors-3) > 1) return;
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr,_("Blending highlights...\n"));
#endif
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,0,2);
#endif
FORCC if (clip > (i = 65535*pre_mul[c])) clip = i;
for (row=0; row < height; row++)
for (col=0; col < width; col++) {
FORCC if (image[row*width+col][c] > clip) break;
if (c == colors) continue;
FORCC {
cam[0][c] = image[row*width+col][c];
cam[1][c] = MIN(cam[0][c],clip);
}
for (i=0; i < 2; i++) {
FORCC for (lab[i][c]=j=0; j < colors; j++)
lab[i][c] += trans[colors-3][c][j] * cam[i][j];
for (sum[i]=0,c=1; c < colors; c++)
sum[i] += SQR(lab[i][c]);
}
chratio = sqrt(sum[1]/sum[0]);
for (c=1; c < colors; c++)
lab[0][c] *= chratio;
FORCC for (cam[0][c]=j=0; j < colors; j++)
cam[0][c] += itrans[colors-3][c][j] * lab[0][j];
FORCC image[row*width+col][c] = cam[0][c] / colors;
}
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,1,2);
#endif
}
#define SCALE (4 >> shrink)
void CLASS recover_highlights()
{
float *map, sum, wgt, grow;
int hsat[4], count, spread, change, val, i;
unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x;
ushort *pixel;
static const signed char dir[8][2] =
{ {-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1} };
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr,_("Rebuilding highlights...\n"));
#endif
grow = pow (2.0, 4-highlight);
FORCC hsat[c] = 32000 * pre_mul[c];
for (kc=0, c=1; c < colors; c++)
if (pre_mul[kc] < pre_mul[c]) kc = c;
high = height / SCALE;
wide = width / SCALE;
map = (float *) calloc (high, wide*sizeof *map);
merror (map, "recover_highlights()");
FORCC if (c != kc) {
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,c-1,colors-1);
#endif
memset (map, 0, high*wide*sizeof *map);
for (mrow=0; mrow < high; mrow++)
for (mcol=0; mcol < wide; mcol++) {
sum = wgt = count = 0;
for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++)
for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) {
pixel = image[row*width+col];
if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) {
sum += pixel[c];
wgt += pixel[kc];
count++;
}
}
if (count == SCALE*SCALE)
map[mrow*wide+mcol] = sum / wgt;
}
for (spread = 32/grow; spread--; ) {
for (mrow=0; mrow < high; mrow++)
for (mcol=0; mcol < wide; mcol++) {
if (map[mrow*wide+mcol]) continue;
sum = count = 0;
for (d=0; d < 8; d++) {
y = mrow + dir[d][0];
x = mcol + dir[d][1];
if (y < high && x < wide && map[y*wide+x] > 0) {
sum += (1 + (d & 1)) * map[y*wide+x];
count += 1 + (d & 1);
}
}
if (count > 3)
map[mrow*wide+mcol] = - (sum+grow) / (count+grow);
}
for (change=i=0; i < high*wide; i++)
if (map[i] < 0) {
map[i] = -map[i];
change = 1;
}
if (!change) break;
}
for (i=0; i < high*wide; i++)
if (map[i] == 0) map[i] = 1;
for (mrow=0; mrow < high; mrow++)
for (mcol=0; mcol < wide; mcol++) {
for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++)
for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) {
pixel = image[row*width+col];
if (pixel[c] / hsat[c] > 1) {
val = pixel[kc] * map[mrow*wide+mcol];
if (pixel[c] < val) pixel[c] = CLIP(val);
}
}
}
}
free (map);
}
#undef SCALE
void CLASS tiff_get (unsigned base,
unsigned *tag, unsigned *type, unsigned *len, unsigned *save)
{
*tag = get2();
*type = get2();
*len = get4();
*save = ftell(ifp) + 4;
if (*len * ("11124811248484"[*type < 14 ? *type:0]-'0') > 4)
fseek (ifp, get4()+base, SEEK_SET);
}
void CLASS parse_thumb_note (int base, unsigned toff, unsigned tlen)
{
unsigned entries, tag, type, len, save;
entries = get2();
while (entries--) {
tiff_get (base, &tag, &type, &len, &save);
if (tag == toff) thumb_offset = get4()+base;
if (tag == tlen) thumb_length = get4();
fseek (ifp, save, SEEK_SET);
}
}
//@end COMMON
int CLASS parse_tiff_ifd (int base);
//@out COMMON
static float powf_lim(float a, float b, float limup)
{
return (b>limup || b < -limup)?0.f:powf(a,b);
}
static float powf64(float a, float b)
{
return powf_lim(a,b,64.f);
}
#ifdef LIBRAW_LIBRARY_BUILD
static float my_roundf(float x) {
float t;
if (x >= 0.0) {
t = ceilf(x);
if (t - x > 0.5) t -= 1.0;
return t;
} else {
t = ceilf(-x);
if (t + x > 0.5) t -= 1.0;
return -t;
}
}
static float _CanonConvert2EV(short in)
{
float frac1;
short val = in, sign = 1, frac;
if (val < 0) { val = -val; sign = -1; }
frac = (val & 0x1f);
val -= frac;
if (frac == 0x0c) frac1 = 32.0f / 3.0f;
else if (frac == 0x14) frac1 = 64.0f / 3.0f;
else frac1 = (float)frac;
return (float)sign * ((float)val + frac1) / 32.0f;
}
static float _CanonConvertAperture(short in)
{
if (in == (short)0xffe0) return 0.0f;
else return powf64(2.0f, _CanonConvert2EV(in) / 2.0f);
}
void CLASS setCanonBodyFeatures (unsigned id)
{
imgdata.lens.makernotes.CamID = id;
if (
(id == 0x80000001) || // 1D
(id == 0x80000174) || // 1D2
(id == 0x80000232) || // 1D2N
(id == 0x80000169) || // 1D3
(id == 0x80000281) // 1D4
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
}
else
if (
(id == 0x80000167) || // 1Ds
(id == 0x80000188) || // 1Ds2
(id == 0x80000215) || // 1Ds3
(id == 0x80000213) || // 5D
(id == 0x80000218) || // 5D2
(id == 0x80000285) || // 5D3
(id == 0x80000302) || // 6D
(id == 0x80000269) || // 1DX
(id == 0x80000324) || // 1DC
(id == 0x80000382) || // 5DS
(id == 0x80000401) // 5DS R
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
}
else
if (
(id == 0x80000331) || // M
(id == 0x80000355) // M2
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M;
}
else
if (
(id == 0x01140000) || // D30
(id == 0x01668000) || // D60
(id > 0x80000000)
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
return;
}
void CLASS processCanonCameraInfo (unsigned id, uchar *CameraInfo)
{
ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0, iCanonFocalType = 0;
CameraInfo[0] = 0;
CameraInfo[1] = 0;
switch (id) {
case 0x80000001: // 1D
case 0x80000167: // 1DS
iCanonCurFocal = 10;
iCanonLensID = 13;
iCanonMinFocal = 14;
iCanonMaxFocal = 16;
if (!imgdata.lens.makernotes.CurFocal)
imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal);
if (!imgdata.lens.makernotes.MinFocal)
imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal);
if (!imgdata.lens.makernotes.MaxFocal)
imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal);
break;
case 0x80000174: // 1DMkII
case 0x80000188: // 1DsMkII
iCanonCurFocal = 9;
iCanonLensID = 12;
iCanonMinFocal = 17;
iCanonMaxFocal = 19;
iCanonFocalType = 45;
break;
case 0x80000232: // 1DMkII N
iCanonCurFocal = 9;
iCanonLensID = 12;
iCanonMinFocal = 17;
iCanonMaxFocal = 19;
break;
case 0x80000169: // 1DMkIII
case 0x80000215: // 1DsMkIII
iCanonCurFocal = 29;
iCanonLensID = 273;
iCanonMinFocal = 275;
iCanonMaxFocal = 277;
break;
case 0x80000281: // 1DMkIV
iCanonCurFocal = 30;
iCanonLensID = 335;
iCanonMinFocal = 337;
iCanonMaxFocal = 339;
break;
case 0x80000269: // 1D X
iCanonCurFocal = 35;
iCanonLensID = 423;
iCanonMinFocal = 425;
iCanonMaxFocal = 427;
break;
case 0x80000213: // 5D
iCanonCurFocal = 40;
if (!sget2Rev(CameraInfo + 12)) iCanonLensID = 151;
else iCanonLensID = 12;
iCanonMinFocal = 147;
iCanonMaxFocal = 149;
break;
case 0x80000218: // 5DMkII
iCanonCurFocal = 30;
iCanonLensID = 230;
iCanonMinFocal = 232;
iCanonMaxFocal = 234;
break;
case 0x80000285: // 5DMkIII
iCanonCurFocal = 35;
iCanonLensID = 339;
iCanonMinFocal = 341;
iCanonMaxFocal = 343;
break;
case 0x80000302: // 6D
iCanonCurFocal = 35;
iCanonLensID = 353;
iCanonMinFocal = 355;
iCanonMaxFocal = 357;
break;
case 0x80000250: // 7D
iCanonCurFocal = 30;
iCanonLensID = 274;
iCanonMinFocal = 276;
iCanonMaxFocal = 278;
break;
case 0x80000190: // 40D
iCanonCurFocal = 29;
iCanonLensID = 214;
iCanonMinFocal = 216;
iCanonMaxFocal = 218;
iCanonLens = 2347;
break;
case 0x80000261: // 50D
iCanonCurFocal = 30;
iCanonLensID = 234;
iCanonMinFocal = 236;
iCanonMaxFocal = 238;
break;
case 0x80000287: // 60D
iCanonCurFocal = 30;
iCanonLensID = 232;
iCanonMinFocal = 234;
iCanonMaxFocal = 236;
break;
case 0x80000325: // 70D
iCanonCurFocal = 35;
iCanonLensID = 358;
iCanonMinFocal = 360;
iCanonMaxFocal = 362;
break;
case 0x80000176: // 450D
iCanonCurFocal = 29;
iCanonLensID = 222;
iCanonLens = 2355;
break;
case 0x80000252: // 500D
iCanonCurFocal = 30;
iCanonLensID = 246;
iCanonMinFocal = 248;
iCanonMaxFocal = 250;
break;
case 0x80000270: // 550D
iCanonCurFocal = 30;
iCanonLensID = 255;
iCanonMinFocal = 257;
iCanonMaxFocal = 259;
break;
case 0x80000286: // 600D
case 0x80000288: // 1100D
iCanonCurFocal = 30;
iCanonLensID = 234;
iCanonMinFocal = 236;
iCanonMaxFocal = 238;
break;
case 0x80000301: // 650D
case 0x80000326: // 700D
iCanonCurFocal = 35;
iCanonLensID = 295;
iCanonMinFocal = 297;
iCanonMaxFocal = 299;
break;
case 0x80000254: // 1000D
iCanonCurFocal = 29;
iCanonLensID = 226;
iCanonMinFocal = 228;
iCanonMaxFocal = 230;
iCanonLens = 2359;
break;
}
if (iCanonFocalType)
{
imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType];
if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1'
imgdata.lens.makernotes.FocalType = 1;
}
if (!imgdata.lens.makernotes.CurFocal)
imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal);
if (!imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID);
if (!imgdata.lens.makernotes.MinFocal)
imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal);
if (!imgdata.lens.makernotes.MaxFocal)
imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal);
if (!imgdata.lens.makernotes.Lens[0] && iCanonLens) {
if (CameraInfo[iCanonLens] < 65) // non-Canon lens
memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64);
else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4)) {
memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4)) {
memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4)) {
memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4)) {
memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else {
memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
imgdata.lens.makernotes.Lens[2] = 32;
memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62);
}
}
free(CameraInfo);
return;
}
void CLASS processNikonLensData (uchar *LensData, unsigned len)
{
ushort i;
if (len < 20) {
switch (len) {
case 9:
i = 2;
break;
case 15:
i = 7;
break;
case 16:
i = 8;
break;
}
imgdata.lens.nikon.NikonLensIDNumber = LensData[i];
imgdata.lens.nikon.NikonLensFStops = LensData[i + 1];
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f;
imgdata.lens.makernotes.MinFocal = 5.0f * powf64(2.0f, (float)LensData[i + 2] / 24.0f);
imgdata.lens.makernotes.MaxFocal = 5.0f * powf64(2.0f, (float)LensData[i + 3] / 24.0f);
imgdata.lens.makernotes.MaxAp4MinFocal = powf64(2.0f, (float)LensData[i + 4] / 24.0f);
imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(2.0f, (float)LensData[i + 5] / 24.0f);
imgdata.lens.nikon.NikonMCUVersion = LensData[i + 6];
if (i != 2)
{
imgdata.lens.makernotes.CurFocal = 5.0f * powf64(2.0f, (float)LensData[i - 1] / 24.0f);
imgdata.lens.nikon.NikonEffectiveMaxAp = powf64(2.0f, (float)LensData[i + 7] / 24.0f);
}
imgdata.lens.makernotes.LensID =
(unsigned long long) LensData[i] << 56 |
(unsigned long long) LensData[i + 1] << 48 |
(unsigned long long) LensData[i + 2] << 40 |
(unsigned long long) LensData[i + 3] << 32 |
(unsigned long long) LensData[i + 4] << 24 |
(unsigned long long) LensData[i + 5] << 16 |
(unsigned long long) LensData[i + 6] << 8 |
(unsigned long long) imgdata.lens.nikon.NikonLensType;
}
else if ((len == 459) || (len == 590))
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64);
}
else if (len == 509)
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64);
}
else if (len == 879)
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64);
}
free (LensData);
return;
}
void CLASS setOlympusBodyFeatures (unsigned long id)
{
imgdata.lens.makernotes.CamID = id;
if ((id == 0x4434303430) ||
(id == 0x4434303431) ||
((id >= 0x5330303030) && (id <= 0x5330303939)))
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT;
}
else
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
if ((id == 0x4434303430) ||
(id == 0x4434303431) ||
((id >= 0x5330303033) && (id <= 0x5330303138)) ||
(id == 0x5330303233) ||
(id == 0x5330303239) ||
(id == 0x5330303330) ||
(id == 0x5330303333))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT;
}
else if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT;
}
return;
}
void CLASS setPentaxBodyFeatures (unsigned id)
{
imgdata.lens.makernotes.CamID = id;
switch (id) {
case 0x12994:
case 0x12aa2:
case 0x12b1a:
case 0x12b60:
case 0x12b7e:
case 0x12b80:
case 0x12b9c:
case 0x12b9d:
case 0x12ba2:
case 0x12c1e:
case 0x12c20:
case 0x12cd2:
case 0x12cd4:
case 0x12cfa:
case 0x12d72:
case 0x12d73:
case 0x12db8:
case 0x12dfe:
case 0x12e6c:
case 0x12e76:
case 0x12ef8:
case 0x12f52:
case 0x12f70:
case 0x12f71:
case 0x12fb6:
case 0x12fc0:
case 0x12fca:
case 0x1301a:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
break;
case 0x12e08:
case 0x13010:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_645;
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_MF;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_645;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_MF;
break;
case 0x12ee4:
case 0x12f66:
case 0x12f7a:
case 0x1302e:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_Q;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_Q;
break;
default:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
return;
}
void CLASS setPhaseOneFeatures (unsigned id) {
ushort i;
static const struct {
ushort id;
char t_model[32];
} p1_unique[] = {
// Phase One section:
{1, "Hasselblad V"},
{10, "PhaseOne/Mamiya"},
{12, "Contax 645"},
{16, "Hasselblad V"},
{17, "Hasselblad V"},
{18, "Contax 645"},
{19, "PhaseOne/Mamiya"},
{20, "Hasselblad V"},
{21, "Contax 645"},
{22, "PhaseOne/Mamiya"},
{23, "Hasselblad V"},
{24, "Hasselblad H"},
{25, "PhaseOne/Mamiya"},
{32, "Contax 645"},
{34, "Hasselblad V"},
{35, "Hasselblad V"},
{36, "Hasselblad H"},
{37, "Contax 645"},
{38, "PhaseOne/Mamiya"},
{39, "Hasselblad V"},
{40, "Hasselblad H"},
{41, "Contax 645"},
{42, "PhaseOne/Mamiya"},
{44, "Hasselblad V"},
{45, "Hasselblad H"},
{46, "Contax 645"},
{47, "PhaseOne/Mamiya"},
{48, "Hasselblad V"},
{49, "Hasselblad H"},
{50, "Contax 645"},
{51, "PhaseOne/Mamiya"},
{52, "Hasselblad V"},
{53, "Hasselblad H"},
{54, "Contax 645"},
{55, "PhaseOne/Mamiya"},
{67, "Hasselblad V"},
{68, "Hasselblad H"},
{69, "Contax 645"},
{70, "PhaseOne/Mamiya"},
{71, "Hasselblad V"},
{72, "Hasselblad H"},
{73, "Contax 645"},
{74, "PhaseOne/Mamiya"},
{76, "Hasselblad V"},
{77, "Hasselblad H"},
{78, "Contax 645"},
{79, "PhaseOne/Mamiya"},
{80, "Hasselblad V"},
{81, "Hasselblad H"},
{82, "Contax 645"},
{83, "PhaseOne/Mamiya"},
{84, "Hasselblad V"},
{85, "Hasselblad H"},
{86, "Contax 645"},
{87, "PhaseOne/Mamiya"},
{99, "Hasselblad V"},
{100, "Hasselblad H"},
{101, "Contax 645"},
{102, "PhaseOne/Mamiya"},
{103, "Hasselblad V"},
{104, "Hasselblad H"},
{105, "PhaseOne/Mamiya"},
{106, "Contax 645"},
{112, "Hasselblad V"},
{113, "Hasselblad H"},
{114, "Contax 645"},
{115, "PhaseOne/Mamiya"},
{131, "Hasselblad V"},
{132, "Hasselblad H"},
{133, "Contax 645"},
{134, "PhaseOne/Mamiya"},
{135, "Hasselblad V"},
{136, "Hasselblad H"},
{137, "Contax 645"},
{138, "PhaseOne/Mamiya"},
{140, "Hasselblad V"},
{141, "Hasselblad H"},
{142, "Contax 645"},
{143, "PhaseOne/Mamiya"},
{148, "Hasselblad V"},
{149, "Hasselblad H"},
{150, "Contax 645"},
{151, "PhaseOne/Mamiya"},
{160, "A-250"},
{161, "A-260"},
{162, "A-280"},
{167, "Hasselblad V"},
{168, "Hasselblad H"},
{169, "Contax 645"},
{170, "PhaseOne/Mamiya"},
{172, "Hasselblad V"},
{173, "Hasselblad H"},
{174, "Contax 645"},
{175, "PhaseOne/Mamiya"},
{176, "Hasselblad V"},
{177, "Hasselblad H"},
{178, "Contax 645"},
{179, "PhaseOne/Mamiya"},
{180, "Hasselblad V"},
{181, "Hasselblad H"},
{182, "Contax 645"},
{183, "PhaseOne/Mamiya"},
{208, "Hasselblad V"},
{211, "PhaseOne/Mamiya"},
{448, "Phase One 645AF"},
{457, "Phase One 645DF"},
{471, "Phase One 645DF+"},
{704, "Phase One iXA"},
{705, "Phase One iXA - R"},
{706, "Phase One iXU 150"},
{707, "Phase One iXU 150 - NIR"},
{708, "Phase One iXU 180"},
{721, "Phase One iXR"},
// Leaf section:
{333,"Mamiya"},
{329,"Universal"},
{330,"Hasselblad H1/H2"},
{332,"Contax"},
{336,"AFi"},
{327,"Mamiya"},
{324,"Universal"},
{325,"Hasselblad H1/H2"},
{326,"Contax"},
{335,"AFi"},
{340,"Mamiya"},
{337,"Universal"},
{338,"Hasselblad H1/H2"},
{339,"Contax"},
{323,"Mamiya"},
{320,"Universal"},
{322,"Hasselblad H1/H2"},
{321,"Contax"},
{334,"AFi"},
{369,"Universal"},
{370,"Mamiya"},
{371,"Hasselblad H1/H2"},
{372,"Contax"},
{373,"Afi"},
};
imgdata.lens.makernotes.CamID = id;
if (id && !imgdata.lens.makernotes.body[0]) {
for (i=0; i < sizeof p1_unique / sizeof *p1_unique; i++)
if (id == p1_unique[i].id) {
strcpy(imgdata.lens.makernotes.body,p1_unique[i].t_model);
}
}
return;
}
void CLASS setSonyBodyFeatures (unsigned id) {
imgdata.lens.makernotes.CamID = id;
if ( // FF cameras
(id == 257) || // a900
(id == 269) || // a850
(id == 340) || // ILCE-7M2
(id == 318) || // ILCE-7S
(id == 311) || // ILCE-7R
(id == 306) || // ILCE-7
(id == 298) || // DSC-RX1
(id == 299) || // NEX-VG900
(id == 310) || // DSC-RX1R
(id == 294) // SLT-99, Hasselblad HV
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
}
else
{
if ((id != 002) && // DSC-R1
(id != 297) && // DSC-RX100
(id != 308) && // DSC-RX100M2
(id != 309) && // DSC-RX10
(id != 317)) // DSC-RX100M3
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
}
if ( // E-mount cameras
// ILCE:
(id == 302) ||
(id == 306) ||
(id == 311) ||
(id == 312) ||
(id == 313) ||
(id == 318) ||
(id == 339) ||
(id == 340) ||
(id == 346) ||
// NEX:
(id == 278) ||
(id == 279) ||
(id == 284) ||
(id == 288) ||
(id == 289) ||
(id == 290) ||
(id == 293) ||
(id == 295) ||
(id == 296) ||
(id == 299) ||
(id == 300) ||
(id == 305) ||
(id == 307)
)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E;
}
else if ( // A-mount cameras
// DSLR:
(id == 256) ||
(id == 257) ||
(id == 258) ||
(id == 259) ||
(id == 260) ||
(id == 261) ||
(id == 262) ||
(id == 263) ||
(id == 264) ||
(id == 265) ||
(id == 266) ||
(id == 269) ||
(id == 270) ||
(id == 273) ||
(id == 274) ||
(id == 275) ||
(id == 282) ||
(id == 283) ||
// SLT:
(id == 280) ||
(id == 281) ||
(id == 285) ||
(id == 286) ||
(id == 287) ||
(id == 291) ||
(id == 292) ||
(id == 294) ||
(id == 303) ||
// ILCA:
(id == 319)
)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A;
}
else if ( // DSC
(id == 002) || // DSC-R1
(id == 297) || // DSC-RX100
(id == 298) || // DSC-RX1
(id == 308) || // DSC-RX100M2
(id == 309) || // DSC-RX10
(id == 310) || // DSC-RX1R
(id == 317) // DSC-RX100M3
)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
return;
}
void CLASS parseSonyLensType2 (uchar a, uchar b) {
ushort lid2;
lid2 = (((ushort)a)<<8) | ((ushort)b);
if (!lid2) return;
if (lid2 < 0x100)
{
imgdata.lens.makernotes.AdapterID = lid2;
switch (lid2) {
case 1:
case 2:
case 3:
case 6:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
break;
case 44:
case 78:
case 239:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
break;
}
}
else
imgdata.lens.makernotes.LensID = lid2;
return;
}
void CLASS parseSonyLensFeatures (uchar a, uchar b) {
ushort features;
features = (((ushort)a)<<8) | ((ushort)b);
if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) || !features)
return;
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
imgdata.lens.makernotes.LensFeatures_pre[0] = 0;
imgdata.lens.makernotes.LensFeatures_suf[0] = 0;
if ((features & 0x0200) && (features & 0x0100)) {
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E");
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
} else if (features & 0x0200) {
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE");
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
} else if (features & 0x0100) {
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT");
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
}
if (features & 0x4000)
strncat(imgdata.lens.makernotes.LensFeatures_pre, " PZ", sizeof(imgdata.lens.makernotes.LensFeatures_pre));
if (features & 0x0008)
strncat(imgdata.lens.makernotes.LensFeatures_suf, " G", sizeof(imgdata.lens.makernotes.LensFeatures_suf));
else if (features & 0x0004)
strncat(imgdata.lens.makernotes.LensFeatures_suf, " ZA", sizeof(imgdata.lens.makernotes.LensFeatures_suf));
if ((features & 0x0020) && (features & 0x0040))
strncat(imgdata.lens.makernotes.LensFeatures_suf, " Macro", sizeof(imgdata.lens.makernotes.LensFeatures_suf));
else if (features & 0x0020)
strncat(imgdata.lens.makernotes.LensFeatures_suf, " STF", sizeof(imgdata.lens.makernotes.LensFeatures_suf));
else if (features & 0x0040)
strncat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex", sizeof(imgdata.lens.makernotes.LensFeatures_suf));
else if (features & 0x0080)
strncat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye", sizeof(imgdata.lens.makernotes.LensFeatures_suf));
if (features & 0x0001)
strncat(imgdata.lens.makernotes.LensFeatures_suf, " SSM", sizeof(imgdata.lens.makernotes.LensFeatures_suf));
else if (features & 0x0002)
strncat(imgdata.lens.makernotes.LensFeatures_suf, " SAM", sizeof(imgdata.lens.makernotes.LensFeatures_suf));
if (features & 0x8000)
strncat(imgdata.lens.makernotes.LensFeatures_suf, " OSS", sizeof(imgdata.lens.makernotes.LensFeatures_suf));
if (features & 0x2000)
strncat(imgdata.lens.makernotes.LensFeatures_suf, " LE", sizeof(imgdata.lens.makernotes.LensFeatures_suf));
if (features & 0x0800)
strncat(imgdata.lens.makernotes.LensFeatures_suf, " II", sizeof(imgdata.lens.makernotes.LensFeatures_suf));
if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ')
memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf+1, strlen(imgdata.lens.makernotes.LensFeatures_suf));
return;
}
void CLASS process_Sony_0x940c (uchar * buf)
{
ushort lid2;
if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF)
{
switch (SonySubstitution[buf[0x0008]]) {
case 1:
case 5:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
break;
case 4:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
break;
}
}
lid2 = (((ushort)SonySubstitution[buf[0x000a]])<<8) |
((ushort)SonySubstitution[buf[0x0009]]);
if ((lid2 > 0) && (lid2 < 32784))
parseSonyLensType2 (SonySubstitution[buf[0x000a]], // LensType2 - Sony lens ids
SonySubstitution[buf[0x0009]]);
return;
}
void CLASS process_Sony_0x9050 (uchar * buf, unsigned id)
{
ushort lid;
if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) &&
(imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens))
{
if (buf[0])
imgdata.lens.makernotes.MaxAp =
my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[0]] / 8.0 - 1.06f) / 2.0f)*10.0f) / 10.0f;
if (buf[1])
imgdata.lens.makernotes.MinAp =
my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[1]] / 8.0 - 1.06f) / 2.0f)*10.0f) / 10.0f;
}
if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)
{
if (buf[0x3d] | buf[0x3c])
{
lid = SonySubstitution[buf[0x3d]] << 8 |
SonySubstitution[buf[0x3c]];
imgdata.lens.makernotes.CurAp =
powf64(2.0f, ((float)lid/256.0f - 16.0f) / 2.0f);
}
if (buf[0x105] && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF))
imgdata.lens.makernotes.LensMount =
SonySubstitution[buf[0x105]];
if (buf[0x106])
imgdata.lens.makernotes.LensFormat =
SonySubstitution[buf[0x106]];
}
if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)
{
parseSonyLensType2 (SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids
SonySubstitution[buf[0x0107]]);
}
if ((imgdata.lens.makernotes.LensID == -1) &&
(imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) &&
(buf[0x010a] | buf[0x0109]))
{
imgdata.lens.makernotes.LensID = // LensType - Minolta/Sony lens ids
SonySubstitution[buf[0x010a]] << 8 |
SonySubstitution[buf[0x0109]];
if ((imgdata.lens.makernotes.LensID > 61184) &&
(imgdata.lens.makernotes.LensID < 65535))
{
imgdata.lens.makernotes.LensID -= 61184;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
}
}
if ((id >= 286) && (id <= 293))
// "SLT-A65", "SLT-A77", "NEX-7", "NEX-VG20E",
// "SLT-A37", "SLT-A57", "NEX-F3", "Lunar"
parseSonyLensFeatures (SonySubstitution[buf[0x115]],
SonySubstitution[buf[0x116]]);
else if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)
parseSonyLensFeatures (SonySubstitution[buf[0x116]],
SonySubstitution[buf[0x117]]);
return;
}
void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer)
{
unsigned offset = 0, entries, tag, type, len, save, c;
unsigned i;
uchar NikonKey, ci, cj, ck;
unsigned serial = 0;
unsigned NikonLensDataVersion = 0;
unsigned lenNikonLensData = 0;
uchar *CanonCameraInfo;
unsigned lenCanonCameraInfo = 0;
uchar *table_buf;
uchar *table_buf_0x9050;
ushort table_buf_0x9050_present = 0;
uchar *table_buf_0x940c;
ushort table_buf_0x940c_present = 0;
short morder, sorder = order;
char buf[10];
fread(buf, 1, 10, ifp);
if (!strcmp(buf, "Nikon")) {
base = ftell(ifp);
order = get2();
if (get2() != 42) goto quit;
offset = get4();
fseek(ifp, offset - 8, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMPUS") ||
!strcmp(buf, "PENTAX ") ||
(!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) {
base = ftell(ifp) - 10;
fseek(ifp, -2, SEEK_CUR);
order = get2();
if (buf[0] == 'O') get2();
}
else if (!strncmp(buf, "SONY", 4) ||
!strcmp(buf, "Panasonic")) {
goto nf;
}
else if (!strncmp(buf, "FUJIFILM", 8)) {
base = ftell(ifp) - 10;
nf: order = 0x4949;
fseek(ifp, 2, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMP") ||
!strcmp(buf, "LEICA") ||
!strcmp(buf, "Ricoh") ||
!strcmp(buf, "EPSON"))
fseek(ifp, -2, SEEK_CUR);
else if (!strcmp(buf, "AOC") ||
!strcmp(buf, "QVC"))
fseek(ifp, -4, SEEK_CUR);
else {
fseek(ifp, -10, SEEK_CUR);
if ((!strncmp(make, "SAMSUNG", 7) &&
(dng_writer == AdobeDNG)))
base = ftell(ifp);
}
entries = get2();
// if (dng_writer == AdobeDNG)
// printf("\n*** parse_makernote_0xc634: AdobeDNG");
// else if (dng_writer == CameraDNG)
// printf("\n*** parse_makernote_0xc634: CameraDNG");
// printf ("\n\tbuf =%s=\n\tmake =%s=\n\tmodel =%s=\n\tbase: 0x%x\n\tentries: %d\n",
// buf, make, model, base, entries);
if (entries > 1000) return;
morder = order;
while (entries--) {
order = morder;
tiff_get(base, &tag, &type, &len, &save);
tag |= uptag << 16;
// printf ("\n\tbase: 0x%x tag: 0x%04x type: 0x%x len: 0x%x pos: 0x%llx",
// base, tag, type, len, ftell(ifp));
if (!strcmp(make, "Canon"))
{
if (tag == 0x0001) // camera settings
{
fseek(ifp, 44, SEEK_CUR);
imgdata.lens.makernotes.LensID = get2();
imgdata.lens.makernotes.MaxFocal = get2();
imgdata.lens.makernotes.MinFocal = get2();
imgdata.lens.makernotes.CanonFocalUnits = get2();
if (imgdata.lens.makernotes.CanonFocalUnits != 1)
{
imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2());
imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2());
}
else if (tag == 0x0002) // focal length
{
imgdata.lens.makernotes.FocalType = get2();
imgdata.lens.makernotes.CurFocal = get2();
if ((imgdata.lens.makernotes.CanonFocalUnits != 1) &&
imgdata.lens.makernotes.CanonFocalUnits)
{
imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
}
else if (tag == 0x0004) // shot info
{
fseek(ifp, 42, SEEK_CUR);
imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2());
}
else if (tag == 0x000d) // camera info
{
CanonCameraInfo = (uchar*)malloc(len);
fread(CanonCameraInfo, len, 1, ifp);
lenCanonCameraInfo = len;
}
else if (tag == 0x10) // Canon ModelID
{
unique_id = get4();
setCanonBodyFeatures(unique_id);
if (lenCanonCameraInfo) processCanonCameraInfo(unique_id, CanonCameraInfo);
}
else if (tag == 0x0095 && // lens model tag
!imgdata.lens.makernotes.Lens[0])
{
fread(imgdata.lens.makernotes.Lens, 2, 1, ifp);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
if (imgdata.lens.makernotes.Lens[0] < 65) // non-Canon lens
fread(imgdata.lens.makernotes.Lens + 2, 62, 1, ifp);
else
{
char efs[2];
imgdata.lens.makernotes.LensFeatures_pre[0] = imgdata.lens.makernotes.Lens[0];
imgdata.lens.makernotes.LensFeatures_pre[1] = imgdata.lens.makernotes.Lens[1];
fread(efs, 2, 1, ifp);
if (efs[0] == 45 && (efs[1] == 83 || efs[1] == 69 || efs[1] == 77))
{ // "EF-S, TS-E, MP-E, EF-M" lenses
imgdata.lens.makernotes.Lens[2] = imgdata.lens.makernotes.LensFeatures_pre[2] = efs[0];
imgdata.lens.makernotes.Lens[3] = imgdata.lens.makernotes.LensFeatures_pre[3] = efs[1];
imgdata.lens.makernotes.Lens[4] = 32;
if (efs[1] == 83)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S;
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
}
else if (efs[1] == 77)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M;
}
}
else
{ // "EF" lenses
imgdata.lens.makernotes.Lens[2] = 32;
imgdata.lens.makernotes.Lens[3] = efs[0];
imgdata.lens.makernotes.Lens[4] = efs[1];
}
fread(imgdata.lens.makernotes.Lens + 5, 58, 1, ifp);
}
}
}
else if (!strncmp(make, "FUJI", 4))
switch (tag) {
case 0x1404: imgdata.lens.makernotes.MinFocal = getreal(type); break;
case 0x1405: imgdata.lens.makernotes.MaxFocal = getreal(type); break;
case 0x1406: imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); break;
case 0x1407: imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); break;
}
else if (!strncasecmp(make, "LEICA", 5))
{
if ((tag == 0x0303) && (type != 4))
{
fread(imgdata.lens.makernotes.Lens, len, 1, ifp);
}
if ((tag == 0x3405) ||
(tag == 0x0310) ||
(tag == 0x34003405))
{
imgdata.lens.makernotes.LensID = get4();
imgdata.lens.makernotes.LensID =
((imgdata.lens.makernotes.LensID>>2)<<8) |
(imgdata.lens.makernotes.LensID & 0x3);
if (imgdata.lens.makernotes.LensID != -1)
{
if ((model[0] == 'M') ||
!strncasecmp (model, "LEICA M", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M;
}
else if ((model[0] == 'S') ||
!strncasecmp (model, "LEICA S", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S;
}
}
}
else if (
((tag == 0x0313) || (tag == 0x34003406)) &&
(fabs(imgdata.lens.makernotes.CurAp) < 0.17f) &&
((type == 10) || (type == 5))
)
{
imgdata.lens.makernotes.CurAp = getreal(type);
if (imgdata.lens.makernotes.CurAp > 126.3)
imgdata.lens.makernotes.CurAp = 0.0f;
}
else if (tag == 0x3400)
{
parse_makernote (base, 0x3400);
}
}
else if (!strncmp(make, "NIKON", 5))
{
if (tag == 0x1d) // serial number
while ((c = fgetc(ifp)) && c != EOF)
serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10);
else if (tag == 0x0082) // lens attachment
{
fread(imgdata.lens.makernotes.Attachment, len, 1, ifp);
}
else if (tag == 0x0083) // lens type
{
imgdata.lens.nikon.NikonLensType = fgetc(ifp);
if (!(imgdata.lens.nikon.NikonLensType & 0x01))
{
imgdata.lens.makernotes.LensFeatures_pre[0] = 'A';
imgdata.lens.makernotes.LensFeatures_pre[1] = 'F';
}
if (imgdata.lens.nikon.NikonLensType & 0x02)
{
if (imgdata.lens.nikon.NikonLensType & 0x04)
imgdata.lens.makernotes.LensFeatures_suf[0] = 'G';
else
imgdata.lens.makernotes.LensFeatures_suf[0] = 'D';
imgdata.lens.makernotes.LensFeatures_suf[1] = ' ';
}
if (imgdata.lens.nikon.NikonLensType & 0x08)
{
imgdata.lens.makernotes.LensFeatures_suf[2] = 'V';
imgdata.lens.makernotes.LensFeatures_suf[3] = 'R';
}
if (imgdata.lens.nikon.NikonLensType & 0x10)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_CX;
}
if (imgdata.lens.nikon.NikonLensType & 0x20)
{
strcpy(imgdata.lens.makernotes.Adapter, "FT-1");
}
imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf;
}
else if (tag == 0x0084) // lens
{
imgdata.lens.makernotes.MinFocal = getreal(type);
imgdata.lens.makernotes.MaxFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type);
}
else if (tag == 0x008b) // lens f-stops
{
uchar a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
{
imgdata.lens.nikon.NikonLensFStops = a*b*(12/c);
imgdata.lens.makernotes.LensFStops =
(float)imgdata.lens.nikon.NikonLensFStops /12.0f;
}
}
else if (tag == 0x0098) // contains lens data
{
for (i = 0; i < 4; i++)
{
NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0';
}
switch (NikonLensDataVersion)
{
case 100: lenNikonLensData = 9; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; break;
case 101:
case 201: // encrypted, starting from v.201
case 202:
case 203: lenNikonLensData = 15; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; break;
case 204: lenNikonLensData = 16; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; break;
case 400: lenNikonLensData = 459; break;
case 401: lenNikonLensData = 590; break;
case 402: lenNikonLensData = 509; break;
case 403: lenNikonLensData = 879; break;
}
table_buf = (uchar*)malloc(lenNikonLensData);
fread(table_buf, lenNikonLensData, 1, ifp);
if ((NikonLensDataVersion < 201) && lenNikonLensData)
{
processNikonLensData(table_buf, lenNikonLensData);
lenNikonLensData = 0;
}
}
else if (tag == 0xa7) // shutter count
{
NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp);
if ((NikonLensDataVersion > 200) && lenNikonLensData)
{
ci = xlat[0][serial & 0xff];
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < lenNikonLensData; i++)
table_buf[i] ^= (cj += ci * ck++);
processNikonLensData(table_buf, lenNikonLensData);
lenNikonLensData = 0;
}
}
else if (tag == 37 && (!iso_speed || iso_speed == 65535))
{
unsigned char cc;
fread(&cc, 1, 1, ifp);
iso_speed = (int)(100.0 * powf64(2.0, (double)(cc) / 12.0 - 5.0));
break;
}
}
else if (!strncmp(make, "OLYMPUS", 7))
{
if (tag == 0x2010)
{
fseek(ifp, save - 4, SEEK_SET);
fseek(ifp, base + get4(), SEEK_SET);
parse_makernote_0xc634(base, 0x2010, dng_writer);
}
switch (tag) {
case 0x0207:
case 0x20100100:
{
uchar sOlyID[7];
long unsigned OlyID;
fread (sOlyID, len, 1, ifp);
OlyID = sOlyID[0];
i = 1;
while (sOlyID[i])
{
OlyID = OlyID << 8 | sOlyID[i];
i++;
}
setOlympusBodyFeatures(OlyID);
}
break;
case 0x1002:
imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type)/2);
break;
case 0x20100201:
imgdata.lens.makernotes.LensID =
(unsigned long long)fgetc(ifp)<<16 |
(unsigned long long)(fgetc(ifp), fgetc(ifp))<<8 |
(unsigned long long)fgetc(ifp);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT;
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT;
if (((imgdata.lens.makernotes.LensID < 0x20000) ||
(imgdata.lens.makernotes.LensID > 0x4ffff)) &&
(imgdata.lens.makernotes.LensID & 0x10))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT;
}
break;
case 0x20100203:
fread(imgdata.lens.makernotes.Lens, len, 1, ifp);
break;
case 0x20100205:
imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100206:
imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100207:
imgdata.lens.makernotes.MinFocal = (float)get2();
break;
case 0x20100208:
imgdata.lens.makernotes.MaxFocal = (float)get2();
if (imgdata.lens.makernotes.MaxFocal > 1000.0f)
imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal;
break;
case 0x2010020a:
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100301:
imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8;
fgetc(ifp);
imgdata.lens.makernotes.TeleconverterID =
imgdata.lens.makernotes.TeleconverterID | fgetc(ifp);
break;
case 0x20100303:
fread(imgdata.lens.makernotes.Teleconverter, len, 1, ifp);
break;
case 0x20100403:
fread(imgdata.lens.makernotes.Attachment, len, 1, ifp);
break;
}
}
else if (!strncmp(make, "PENTAX", 6) ||
!strncmp(model, "PENTAX", 6) ||
(!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG)))
{
if (tag == 0x0005)
{
unique_id = get4();
setPentaxBodyFeatures(unique_id);
if (
(dng_writer == CameraDNG) &&
(
(unique_id == 0x12f66) || // Q10
(unique_id == 0x12f7a) || // Q7
(unique_id == 0x12ee4) // Q
)
)
base += 10;
}
else if (tag == 0x0013)
{
imgdata.lens.makernotes.CurAp = (float)get2()/10.0f;
}
else if (tag == 0x001d)
{
imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f;
}
else if (tag == 0x003f)
{
imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp);
}
else if (tag == 0x0207)
{
ushort iLensData = 0;
table_buf = (uchar*)malloc(len);
fread(table_buf, len, 1, ifp);
if ((imgdata.lens.makernotes.CamID < 0x12b9c) ||
((imgdata.lens.makernotes.CamID == 0x12b9c) || // K100D
(imgdata.lens.makernotes.CamID == 0x12b9d) || // K110D
(imgdata.lens.makernotes.CamID == 0x12ba2) && // K100D Super
(!table_buf[20] || (table_buf[20] == 0xff))))
{
iLensData = 3;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID =
(((unsigned)table_buf[0]) << 8) + table_buf[1];
}
else switch (len)
{
case 90: // LensInfo3
iLensData = 13;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID =
((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4];
break;
case 91: // LensInfo4
iLensData = 12;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID =
((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4];
break;
case 80: // LensInfo5
case 128:
iLensData = 15;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID =
((unsigned)((table_buf[1] & 0x0f) + table_buf[4]) <<8) + table_buf[5];
break;
default:
if (imgdata.lens.makernotes.CamID >= 0x12b9c) // LensInfo2
{
iLensData = 4;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID =
((unsigned)((table_buf[0] & 0x0f) + table_buf[2]) <<8) + table_buf[3];
}
}
if (iLensData)
{
if (table_buf[iLensData+9] &&
(fabs(imgdata.lens.makernotes.CurFocal) < 0.1f))
imgdata.lens.makernotes.CurFocal =
10*(table_buf[iLensData+9]>>2) * powf64(4, (table_buf[iLensData+9] & 0x03)-2);
if (table_buf[iLensData+10] & 0xf0)
imgdata.lens.makernotes.MaxAp4CurFocal =
powf64(2.0f, (float)((table_buf[iLensData+10] & 0xf0) >>4)/4.0f);
if (table_buf[iLensData+10] & 0x0f)
imgdata.lens.makernotes.MinAp4CurFocal =
powf64(2.0f, (float)((table_buf[iLensData+10] & 0x0f) + 10)/4.0f);
if (
(imgdata.lens.makernotes.CamID != 0x12e6c) && // K-r
(imgdata.lens.makernotes.CamID != 0x12e76) && // K-5
(imgdata.lens.makernotes.CamID != 0x12f70) // K-5 II
// (imgdata.lens.makernotes.CamID != 0x12f71) // K-5 II s
)
{
switch (table_buf[iLensData] & 0x06)
{
case 0: imgdata.lens.makernotes.MinAp4MinFocal = 22.0f; break;
case 2: imgdata.lens.makernotes.MinAp4MinFocal = 32.0f; break;
case 4: imgdata.lens.makernotes.MinAp4MinFocal = 45.0f; break;
case 6: imgdata.lens.makernotes.MinAp4MinFocal = 16.0f; break;
}
if (table_buf[iLensData] & 0x70)
imgdata.lens.makernotes.LensFStops =
((float)(((table_buf[iLensData] & 0x70) >> 4) ^ 0x07)) / 2.0f + 5.0f;
if ((table_buf[iLensData+14] > 1) &&
(fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f))
imgdata.lens.makernotes.MaxAp4CurFocal =
powf64(2.0f, (float)((table_buf[iLensData+14] & 0x7f) -1)/32.0f);
}
else if ((imgdata.lens.makernotes.CamID != 0x12e76) && // K-5
(table_buf[iLensData+15] > 1) &&
(fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f))
{
imgdata.lens.makernotes.MaxAp4CurFocal =
powf64(2.0f, (float)((table_buf[iLensData+15] & 0x7f) -1)/32.0f);
}
}
free(table_buf);
}
else if (tag == 0x0239) // Q-series lens info (LensInfoQ)
{
char LensInfo [20];
fseek (ifp, 2, SEEK_CUR);
fread(imgdata.lens.makernotes.Lens, 30, 1, ifp);
strcat(imgdata.lens.makernotes.Lens, " ");
fread(LensInfo, 20, 1, ifp);
strcat(imgdata.lens.makernotes.Lens, LensInfo);
}
}
else if (!strncmp(make, "SAMSUNG", 7) &&
(dng_writer == AdobeDNG))
{
if (tag == 0x0002)
{
if(get4() == 0x2000)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (!strncmp(model, "NX mini", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0003)
{
imgdata.lens.makernotes.CamID = unique_id = get4();
}
else if (tag == 0xa003)
{
imgdata.lens.makernotes.LensID = get2();
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (tag == 0xa019)
{
imgdata.lens.makernotes.CurAp = getreal(type);
}
else if (tag == 0xa01a)
{
imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f;
if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f)
imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f;
}
}
else if (!strncasecmp(make, "SONY", 4) ||
!strncasecmp(make, "Konica", 6) ||
!strncasecmp(make, "Minolta", 7) ||
(!strncasecmp(make, "Hasselblad", 10) &&
(!strncasecmp(model, "Stellar", 7) ||
!strncasecmp(model, "Lunar", 5) ||
!strncasecmp(model, "HV",2))))
{
ushort lid;
if (tag == 0xb001) // Sony ModelID
{
unique_id = get2();
setSonyBodyFeatures(unique_id);
if (table_buf_0x9050_present)
{
process_Sony_0x9050(table_buf_0x9050, unique_id);
free (table_buf_0x9050);
table_buf_0x9050_present = 0;
}
if (table_buf_0x940c_present)
{
if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)
{
process_Sony_0x940c(table_buf_0x940c);
}
free (table_buf_0x940c);
table_buf_0x940c_present = 0;
}
}
else if ((tag == 0x0010) && // CameraInfo
strncasecmp(model, "DSLR-A100", 9) &&
strncasecmp(model, "NEX-5C", 6) &&
!strncasecmp(make, "SONY", 4) &&
((len == 368) || // a700
(len == 5478) || // a850, a900
(len == 5506) || // a200, a300, a350
(len == 6118) || // a230, a290, a330, a380, a390
// a450, a500, a550, a560, a580
// a33, a35, a55
// NEX3, NEX5, NEX5C, NEXC3, VG10E
(len == 15360))
)
{
table_buf = (uchar*)malloc(len);
fread(table_buf, len, 1, ifp);
if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) &&
memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8))
{
switch (len) {
case 368:
case 5478:
// a700, a850, a900: CameraInfo
if (saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7]))
{
if (table_buf[0] | table_buf[3])
imgdata.lens.makernotes.MinFocal =
bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]);
if (table_buf[2] | table_buf[5])
imgdata.lens.makernotes.MaxFocal =
bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]);
if (table_buf[4])
imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f;
if (table_buf[4])
imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f;
parseSonyLensFeatures(table_buf[1], table_buf[6]);
}
break;
default:
// CameraInfo2 & 3
if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6]))
{
if (table_buf[1] | table_buf[2])
imgdata.lens.makernotes.MinFocal =
bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]);
if (table_buf[3] | table_buf[4])
imgdata.lens.makernotes.MaxFocal =
bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]);
if (table_buf[5])
imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f;
if (table_buf[6])
imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f;
parseSonyLensFeatures(table_buf[0], table_buf[7]);
}
}
}
free(table_buf);
}
else if (tag == 0x0105) // Teleconverter
{
imgdata.lens.makernotes.TeleconverterID = get2();
}
else if (tag == 0x0114) // CameraSettings
{
table_buf = (uchar*)malloc(len);
fread(table_buf, len, 1, ifp);
switch (len) {
case 280:
case 364:
case 332:
// CameraSettings and CameraSettings2 are big endian
if (table_buf[2] | table_buf[3])
{
lid = (((ushort)table_buf[2])<<8) |
((ushort)table_buf[3]);
imgdata.lens.makernotes.CurAp =
powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f);
}
break;
case 1536:
case 2048:
// CameraSettings3 are little endian
parseSonyLensType2(table_buf[1016], table_buf[1015]);
if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF)
{
switch (table_buf[153]) {
case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break;
case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break;
}
}
break;
}
free(table_buf);
}
else if (tag == 0x9050) // little endian
{
table_buf_0x9050 = (uchar*)malloc(len);
table_buf_0x9050_present = 1;
fread(table_buf_0x9050, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID);
free (table_buf_0x9050);
table_buf_0x9050_present = 0;
}
}
else if (tag == 0x940c)
{
table_buf_0x940c = (uchar*)malloc(len);
table_buf_0x940c_present = 1;
fread(table_buf_0x940c, len, 1, ifp);
if ((imgdata.lens.makernotes.CamID) &&
(imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E))
{
process_Sony_0x940c(table_buf_0x940c);
free(table_buf_0x940c);
table_buf_0x940c_present = 0;
}
}
else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1))
{
imgdata.lens.makernotes.LensID = get4();
if ((imgdata.lens.makernotes.LensID > 61184) &&
(imgdata.lens.makernotes.LensID < 65535))
{
imgdata.lens.makernotes.LensID -= 61184;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
}
if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A;
}
else if (tag == 0xb02a) // Sony LensSpec
{
table_buf = (uchar*)malloc(len);
fread(table_buf, len, 1, ifp);
if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6]))
{
if (table_buf[1] | table_buf[2])
imgdata.lens.makernotes.MinFocal =
bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]);
if (table_buf[3] | table_buf[4])
imgdata.lens.makernotes.MaxFocal =
bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]);
if (table_buf[5])
imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f;
if (table_buf[6])
imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f;
parseSonyLensFeatures(table_buf[0], table_buf[7]);
}
free(table_buf);
}
}
next:
fseek (ifp, save, SEEK_SET);
}
quit:
order = sorder;
}
#else
void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer)
{
/*placeholder */
}
#endif
void CLASS parse_makernote (int base, int uptag)
{
unsigned offset=0, entries, tag, type, len, save, c;
unsigned ver97=0, serial=0, i, wbi=0, wb[4]={0,0,0,0};
uchar buf97[324], ci, cj, ck;
short morder, sorder=order;
char buf[10];
unsigned SamsungKey[11];
static const double rgb_adobe[3][3] = // inv(sRGB2XYZ_D65) * AdobeRGB2XYZ_D65
{{ 1.398283396477404, -0.398283116703571, 4.427165001263944E-08},
{-1.233904514232401E-07, 0.999999995196570, 3.126724276714121e-08},
{ 4.561487232726535E-08, -0.042938290466635, 1.042938250416105 }};
float adobe_cam [3][3];
uchar NikonKey;
#ifdef LIBRAW_LIBRARY_BUILD
unsigned NikonLensDataVersion = 0;
unsigned lenNikonLensData = 0;
uchar *CanonCameraInfo;
unsigned lenCanonCameraInfo = 0;
uchar *table_buf;
uchar *table_buf_0x9050;
ushort table_buf_0x9050_present = 0;
uchar *table_buf_0x940c;
ushort table_buf_0x940c_present = 0;
#endif
/*
The MakerNote might have its own TIFF header (possibly with
its own byte-order!), or it might just be a table.
*/
if (!strcmp(make,"Nokia")) return;
fread (buf, 1, 10, ifp);
if (!strncmp (buf,"KDK" ,3) || /* these aren't TIFF tables */
!strncmp (buf,"VER" ,3) ||
!strncmp (buf,"IIII",4) ||
!strncmp (buf,"MMMM",4)) return;
if (!strncmp (buf,"KC" ,2) || /* Konica KD-400Z, KD-510Z */
!strncmp (buf,"MLY" ,3)) { /* Minolta DiMAGE G series */
order = 0x4d4d;
while ((i=ftell(ifp)) < data_offset && i < 16384) {
wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3];
wb[3] = get2();
if (wb[1] == 256 && wb[3] == 256 &&
wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640)
FORC4 cam_mul[c] = wb[c];
}
goto quit;
}
if (!strcmp (buf,"Nikon")) {
base = ftell(ifp);
order = get2();
if (get2() != 42) goto quit;
offset = get4();
fseek (ifp, offset-8, SEEK_CUR);
} else if (!strcmp (buf,"OLYMPUS") ||
!strcmp (buf,"PENTAX ")) {
base = ftell(ifp)-10;
fseek (ifp, -2, SEEK_CUR);
order = get2();
if (buf[0] == 'O') get2();
} else if (!strncmp (buf,"SONY",4) ||
!strcmp (buf,"Panasonic")) {
goto nf;
} else if (!strncmp (buf,"FUJIFILM",8)) {
base = ftell(ifp)-10;
nf: order = 0x4949;
fseek (ifp, 2, SEEK_CUR);
} else if (!strcmp (buf,"OLYMP") ||
!strcmp (buf,"LEICA") ||
!strcmp (buf,"Ricoh") ||
!strcmp (buf,"EPSON"))
fseek (ifp, -2, SEEK_CUR);
else if (!strcmp (buf,"AOC") ||
!strcmp (buf,"QVC"))
fseek (ifp, -4, SEEK_CUR);
else {
fseek (ifp, -10, SEEK_CUR);
if (!strncmp(make,"SAMSUNG",7))
base = ftell(ifp);
}
// adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400
if (!strncasecmp(make, "LEICA", 5))
{
if (!strncmp(model, "M8", 2) ||
!strncasecmp(model, "Leica M8", 8) ||
!strncasecmp(model, "LEICA X", 7))
{
base = ftell(ifp)-8;
}
else if (!strncasecmp(model, "LEICA M (Typ 240)", 17))
{
base = 0;
}
else if (!strncmp(model, "M9", 2) ||
!strncasecmp(model, "Leica M9", 8) ||
!strncasecmp(model, "M Monochrom", 11) ||
!strncasecmp(model, "Leica M Monochrom", 11))
{
if (!uptag)
{
base = ftell(ifp) - 10;
fseek (ifp, 8, SEEK_CUR);
}
else if (uptag == 0x3400)
{
fseek (ifp, 10, SEEK_CUR);
base += 10;
}
}
else if (!strncasecmp(model, "LEICA T", 7))
{
base = ftell(ifp)-8;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T;
#endif
}
}
entries = get2();
// printf("\n*** parse_makernote\n\tmake =%s=\n\tmodel =%s= \n\tentries: %d\n\tpos: 0x%llx\n",
// make, model, entries, ftell(ifp));
if (entries > 1000) return;
morder = order;
while (entries--) {
order = morder;
tiff_get (base, &tag, &type, &len, &save);
tag |= uptag << 16;
// printf ("\n\tbase: 0x%x tag: 0x%04x type: 0x%x len: 0x%x pos: 0x%llx",
// base, tag, type, len, ftell(ifp));
#ifdef LIBRAW_LIBRARY_BUILD
if (!strcmp(make, "Canon"))
{
if (tag == 0x0001) // camera settings
{
fseek(ifp, 44, SEEK_CUR);
imgdata.lens.makernotes.LensID = get2();
imgdata.lens.makernotes.MaxFocal = get2();
imgdata.lens.makernotes.MinFocal = get2();
imgdata.lens.makernotes.CanonFocalUnits = get2();
if (imgdata.lens.makernotes.CanonFocalUnits != 1)
{
imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2());
imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2());
}
else if (tag == 0x0002) // focal length
{
imgdata.lens.makernotes.FocalType = get2();
imgdata.lens.makernotes.CurFocal = get2();
if ((imgdata.lens.makernotes.CanonFocalUnits != 1) &&
imgdata.lens.makernotes.CanonFocalUnits)
{
imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
}
else if (tag == 0x0004) // shot info
{
fseek(ifp, 42, SEEK_CUR);
imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2());
}
else if (tag == 0x000d) // camera info
{
CanonCameraInfo = (uchar*)malloc(len);
fread(CanonCameraInfo, len, 1, ifp);
lenCanonCameraInfo = len;
}
else if (tag == 0x0095 && // lens model tag
!imgdata.lens.makernotes.Lens[0])
{
fread(imgdata.lens.makernotes.Lens, 2, 1, ifp);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
if (imgdata.lens.makernotes.Lens[0] < 65) // non-Canon lens
fread(imgdata.lens.makernotes.Lens + 2, 62, 1, ifp);
else
{
char efs[2];
imgdata.lens.makernotes.LensFeatures_pre[0] = imgdata.lens.makernotes.Lens[0];
imgdata.lens.makernotes.LensFeatures_pre[1] = imgdata.lens.makernotes.Lens[1];
fread(efs, 2, 1, ifp);
if (efs[0] == 45 && (efs[1] == 83 || efs[1] == 69 || efs[1] == 77))
{ // "EF-S, TS-E, MP-E, EF-M" lenses
imgdata.lens.makernotes.Lens[2] = imgdata.lens.makernotes.LensFeatures_pre[2] = efs[0];
imgdata.lens.makernotes.Lens[3] = imgdata.lens.makernotes.LensFeatures_pre[3] = efs[1];
imgdata.lens.makernotes.Lens[4] = 32;
if (efs[1] == 83)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S;
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
}
else if (efs[1] == 77)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M;
}
}
else
{ // "EF" lenses
imgdata.lens.makernotes.Lens[2] = 32;
imgdata.lens.makernotes.Lens[3] = efs[0];
imgdata.lens.makernotes.Lens[4] = efs[1];
}
fread(imgdata.lens.makernotes.Lens + 5, 58, 1, ifp);
}
}
}
else if (!strncmp(make, "FUJI", 4))
switch (tag) {
case 0x1404: imgdata.lens.makernotes.MinFocal = getreal(type); break;
case 0x1405: imgdata.lens.makernotes.MaxFocal = getreal(type); break;
case 0x1406: imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); break;
case 0x1407: imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); break;
}
else if (!strncasecmp(make, "LEICA", 5))
{
if ((tag == 0x0303) && (type != 4))
{
fread(imgdata.lens.makernotes.Lens, len, 1, ifp);
}
if ((tag == 0x3405) ||
(tag == 0x0310) ||
(tag == 0x34003405))
{
imgdata.lens.makernotes.LensID = get4();
imgdata.lens.makernotes.LensID =
((imgdata.lens.makernotes.LensID>>2)<<8) |
(imgdata.lens.makernotes.LensID & 0x3);
if (imgdata.lens.makernotes.LensID != -1)
{
if ((model[0] == 'M') ||
!strncasecmp (model, "LEICA M", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M;
}
else if ((model[0] == 'S') ||
!strncasecmp (model, "LEICA S", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S;
}
}
}
else if (
((tag == 0x0313) || (tag == 0x34003406)) &&
(fabs(imgdata.lens.makernotes.CurAp) < 0.17f) &&
((type == 10) || (type == 5))
)
{
imgdata.lens.makernotes.CurAp = getreal(type);
if (imgdata.lens.makernotes.CurAp > 126.3)
imgdata.lens.makernotes.CurAp = 0.0f;
}
else if (tag == 0x3400)
{
parse_makernote (base, 0x3400);
}
}
else if (!strncmp(make, "NIKON",5))
{
if (tag == 0x0082) // lens attachment
{
fread(imgdata.lens.makernotes.Attachment, len, 1, ifp);
}
else if (tag == 0x0083) // lens type
{
imgdata.lens.nikon.NikonLensType = fgetc(ifp);
if (!(imgdata.lens.nikon.NikonLensType & 0x01))
{
imgdata.lens.makernotes.LensFeatures_pre[0] = 'A';
imgdata.lens.makernotes.LensFeatures_pre[1] = 'F';
}
if (imgdata.lens.nikon.NikonLensType & 0x02)
{
if (imgdata.lens.nikon.NikonLensType & 0x04)
imgdata.lens.makernotes.LensFeatures_suf[0] = 'G';
else
imgdata.lens.makernotes.LensFeatures_suf[0] = 'D';
imgdata.lens.makernotes.LensFeatures_suf[1] = ' ';
}
if (imgdata.lens.nikon.NikonLensType & 0x08)
{
imgdata.lens.makernotes.LensFeatures_suf[2] = 'V';
imgdata.lens.makernotes.LensFeatures_suf[3] = 'R';
}
if (imgdata.lens.nikon.NikonLensType & 0x10)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_CX;
}
if (imgdata.lens.nikon.NikonLensType & 0x20)
{
strcpy(imgdata.lens.makernotes.Adapter, "FT-1");
}
imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf;
}
else if (tag == 0x0084) // lens
{
imgdata.lens.makernotes.MinFocal = getreal(type);
imgdata.lens.makernotes.MaxFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type);
}
else if (tag == 0x008b) // lens f-stops
{
uchar a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
{
imgdata.lens.nikon.NikonLensFStops = a*b*(12/c);
imgdata.lens.makernotes.LensFStops =
(float)imgdata.lens.nikon.NikonLensFStops /12.0f;
}
}
else if (tag == 0x0098) // contains lens data
{
for (i = 0; i < 4; i++)
{
NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0';
}
switch (NikonLensDataVersion)
{
case 100: lenNikonLensData = 9; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; break;
case 101:
case 201: // encrypted, starting from v.201
case 202:
case 203: lenNikonLensData = 15; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; break;
case 204: lenNikonLensData = 16; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; break;
case 400: lenNikonLensData = 459; break;
case 401: lenNikonLensData = 590; break;
case 402: lenNikonLensData = 509; break;
case 403: lenNikonLensData = 879; break;
}
table_buf = (uchar*)malloc(lenNikonLensData);
fread(table_buf, lenNikonLensData, 1, ifp);
if ((NikonLensDataVersion < 201) && lenNikonLensData)
{
processNikonLensData(table_buf, lenNikonLensData);
lenNikonLensData = 0;
}
}
}
else if (!strncmp(make, "OLYMPUS", 7))
{
switch (tag) {
case 0x0207:
case 0x20100100:
{
uchar sOlyID[7];
long unsigned OlyID;
fread (sOlyID, len, 1, ifp);
OlyID = sOlyID[0];
i = 1;
while (sOlyID[i])
{
OlyID = OlyID << 8 | sOlyID[i];
i++;
}
setOlympusBodyFeatures(OlyID);
}
break;
case 0x1002:
imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type)/2);
break;
case 0x20100201:
imgdata.lens.makernotes.LensID =
(unsigned long long)fgetc(ifp)<<16 |
(unsigned long long)(fgetc(ifp), fgetc(ifp))<<8 |
(unsigned long long)fgetc(ifp);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT;
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT;
if (((imgdata.lens.makernotes.LensID < 0x20000) ||
(imgdata.lens.makernotes.LensID > 0x4ffff)) &&
(imgdata.lens.makernotes.LensID & 0x10))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT;
}
break;
case 0x20100203:
fread(imgdata.lens.makernotes.Lens, len, 1, ifp);
break;
case 0x20100205:
imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100206:
imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100207:
imgdata.lens.makernotes.MinFocal = (float)get2();
break;
case 0x20100208:
imgdata.lens.makernotes.MaxFocal = (float)get2();
if (imgdata.lens.makernotes.MaxFocal > 1000.0f)
imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal;
break;
case 0x2010020a:
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100301:
imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8;
fgetc(ifp);
imgdata.lens.makernotes.TeleconverterID =
imgdata.lens.makernotes.TeleconverterID | fgetc(ifp);
break;
case 0x20100303:
fread(imgdata.lens.makernotes.Teleconverter, len, 1, ifp);
break;
case 0x20100403:
fread(imgdata.lens.makernotes.Attachment, len, 1, ifp);
break;
}
}
else if (!strncmp(make, "PENTAX", 6) &&
!strncmp(model, "GR", 2))
{
if ((tag == 0x1001) && (type == 3))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensID = -1;
imgdata.lens.makernotes.FocalType = 1;
}
else if ((tag == 0x1017) && (get2() == 2))
{
strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter");
}
else if (tag == 0x1500)
{
imgdata.lens.makernotes.CurFocal = getreal(type);
}
}
else if (!strncmp(make, "RICOH", 5) &&
strncmp(model, "PENTAX", 6))
{
if ((tag == 0x1017) && (get2() == 2))
{
strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter");
}
else if (tag == 0x1500)
{
imgdata.lens.makernotes.CurFocal = getreal(type);
}
else if (tag == 0x2001)
{
short ntags, cur_tag;
fseek(ifp, 20, SEEK_CUR);
ntags = get2();
cur_tag = get2();
while (cur_tag != 0x002c)
{
fseek(ifp, 10, SEEK_CUR);
cur_tag = get2();
}
fseek(ifp, 6, SEEK_CUR);
fseek(ifp, get4()+34, SEEK_SET);
imgdata.lens.makernotes.LensID = getc(ifp) - '0';
switch(imgdata.lens.makernotes.LensID)
{
case 1:
case 2:
case 3:
case 5:
case 6:
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule;
break;
case 8:
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensID = -1;
break;
default:
imgdata.lens.makernotes.LensID = -1;
}
}
}
else if (!strncmp(make, "PENTAX", 6) ||
!strncmp(model, "PENTAX", 6) ||
(!strncmp(make, "SAMSUNG", 7) && dng_version) &&
strncmp(model, "GR", 2))
{
if (tag == 0x0005)
{
unique_id = get4();
setPentaxBodyFeatures(unique_id);
}
else if (tag == 0x0013)
{
imgdata.lens.makernotes.CurAp = (float)get2()/10.0f;
}
else if (tag == 0x001d)
{
imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f;
}
else if (tag == 0x003f)
{
imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp);
}
else if (tag == 0x0207)
{
ushort iLensData = 0;
table_buf = (uchar*)malloc(len);
fread(table_buf, len, 1, ifp);
if ((imgdata.lens.makernotes.CamID < 0x12b9c) ||
((imgdata.lens.makernotes.CamID == 0x12b9c) || // K100D
(imgdata.lens.makernotes.CamID == 0x12b9d) || // K110D
(imgdata.lens.makernotes.CamID == 0x12ba2) && // K100D Super
(!table_buf[20] || (table_buf[20] == 0xff))))
{
iLensData = 3;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID =
(((unsigned)table_buf[0]) << 8) + table_buf[1];
}
else switch (len)
{
case 90: // LensInfo3
iLensData = 13;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID =
((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4];
break;
case 91: // LensInfo4
iLensData = 12;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID =
((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4];
break;
case 80: // LensInfo5
case 128:
iLensData = 15;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID =
((unsigned)((table_buf[1] & 0x0f) + table_buf[4]) <<8) + table_buf[5];
break;
default:
if (imgdata.lens.makernotes.CamID >= 0x12b9c) // LensInfo2
{
iLensData = 4;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID =
((unsigned)((table_buf[0] & 0x0f) + table_buf[2]) <<8) + table_buf[3];
}
}
if (iLensData)
{
if (table_buf[iLensData+9] && (fabs(imgdata.lens.makernotes.CurFocal) < 0.1f))
imgdata.lens.makernotes.CurFocal =
10*(table_buf[iLensData+9]>>2) * powf64(4, (table_buf[iLensData+9] & 0x03)-2);
if (table_buf[iLensData+10] & 0xf0)
imgdata.lens.makernotes.MaxAp4CurFocal =
powf64(2.0f, (float)((table_buf[iLensData+10] & 0xf0) >>4)/4.0f);
if (table_buf[iLensData+10] & 0x0f)
imgdata.lens.makernotes.MinAp4CurFocal =
powf64(2.0f, (float)((table_buf[iLensData+10] & 0x0f) + 10)/4.0f);
if (
(imgdata.lens.makernotes.CamID != 0x12e6c) && // K-r
(imgdata.lens.makernotes.CamID != 0x12e76) && // K-5
(imgdata.lens.makernotes.CamID != 0x12f70) // K-5 II
// (imgdata.lens.makernotes.CamID != 0x12f71) // K-5 II s
)
{
switch (table_buf[iLensData] & 0x06)
{
case 0: imgdata.lens.makernotes.MinAp4MinFocal = 22.0f; break;
case 2: imgdata.lens.makernotes.MinAp4MinFocal = 32.0f; break;
case 4: imgdata.lens.makernotes.MinAp4MinFocal = 45.0f; break;
case 6: imgdata.lens.makernotes.MinAp4MinFocal = 16.0f; break;
}
if (table_buf[iLensData] & 0x70)
imgdata.lens.makernotes.LensFStops =
((float)(((table_buf[iLensData] & 0x70) >> 4) ^ 0x07)) / 2.0f + 5.0f;
if ((table_buf[iLensData+14] > 1) &&
(fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f))
imgdata.lens.makernotes.MaxAp4CurFocal =
powf64(2.0f, (float)((table_buf[iLensData+14] & 0x7f) -1)/32.0f);
}
else if ((imgdata.lens.makernotes.CamID != 0x12e76) && // K-5
(table_buf[iLensData+15] > 1) &&
(fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f))
{
imgdata.lens.makernotes.MaxAp4CurFocal =
powf64(2.0f, (float)((table_buf[iLensData+15] & 0x7f) -1)/32.0f);
}
}
free(table_buf);
}
else if (tag == 0x0239) // Q-series lens info (LensInfoQ)
{
char LensInfo [20];
fseek (ifp, 2, SEEK_CUR);
fread(imgdata.lens.makernotes.Lens, 30, 1, ifp);
strcat(imgdata.lens.makernotes.Lens, " ");
fread(LensInfo, 20, 1, ifp);
strcat(imgdata.lens.makernotes.Lens, LensInfo);
}
}
else if (!strncmp(make, "SAMSUNG", 7))
{
if (tag == 0x0002)
{
if(get4() == 0x2000)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (!strncmp(model, "NX mini", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0003)
{
unique_id = imgdata.lens.makernotes.CamID = get4();
}
else if (tag == 0xa003)
{
imgdata.lens.makernotes.LensID = get2();
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (tag == 0xa019)
{
imgdata.lens.makernotes.CurAp = getreal(type);
}
else if (tag == 0xa01a)
{
imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f;
if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f)
imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f;
}
}
else if (!strncasecmp(make, "SONY", 4) ||
!strncasecmp(make, "Konica", 6) ||
!strncasecmp(make, "Minolta", 7) ||
(!strncasecmp(make, "Hasselblad", 10) &&
(!strncasecmp(model, "Stellar", 7) ||
!strncasecmp(model, "Lunar", 5) ||
!strncasecmp(model, "HV",2))))
{
ushort lid;
if (tag == 0xb001) // Sony ModelID
{
unique_id = get2();
setSonyBodyFeatures(unique_id);
if (table_buf_0x9050_present)
{
process_Sony_0x9050(table_buf_0x9050, unique_id);
free (table_buf_0x9050);
table_buf_0x9050_present = 0;
}
if (table_buf_0x940c_present)
{
if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)
{
process_Sony_0x940c(table_buf_0x940c);
}
free (table_buf_0x940c);
table_buf_0x940c_present = 0;
}
}
else if ((tag == 0x0010) && // CameraInfo
strncasecmp(model, "DSLR-A100", 9) &&
strncasecmp(model, "NEX-5C", 6) &&
!strncasecmp(make, "SONY", 4) &&
((len == 368) || // a700
(len == 5478) || // a850, a900
(len == 5506) || // a200, a300, a350
(len == 6118) || // a230, a290, a330, a380, a390
// a450, a500, a550, a560, a580
// a33, a35, a55
// NEX3, NEX5, NEX5C, NEXC3, VG10E
(len == 15360))
)
{
table_buf = (uchar*)malloc(len);
fread(table_buf, len, 1, ifp);
if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) &&
memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8))
{
switch (len)
{
case 368:
case 5478:
// a700, a850, a900: CameraInfo
if (table_buf[0] | table_buf[3])
imgdata.lens.makernotes.MinFocal =
bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]);
if (table_buf[2] | table_buf[5])
imgdata.lens.makernotes.MaxFocal =
bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]);
if (table_buf[4])
imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f;
if (table_buf[4])
imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f;
parseSonyLensFeatures(table_buf[1], table_buf[6]);
break;
default:
// CameraInfo2 & 3
if (table_buf[1] | table_buf[2])
imgdata.lens.makernotes.MinFocal =
bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]);
if (table_buf[3] | table_buf[4])
imgdata.lens.makernotes.MaxFocal =
bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]);
if (table_buf[5])
imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f;
if (table_buf[6])
imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f;
parseSonyLensFeatures(table_buf[0], table_buf[7]);
}
}
free(table_buf);
}
else if (tag == 0x0105) // Teleconverter
{
imgdata.lens.makernotes.TeleconverterID = get2();
}
else if (tag == 0x0114) // CameraSettings
{
table_buf = (uchar*)malloc(len);
fread(table_buf, len, 1, ifp);
switch (len) {
case 280:
case 364:
case 332:
// CameraSettings and CameraSettings2 are big endian
if (table_buf[2] | table_buf[3])
{
lid = (((ushort)table_buf[2])<<8) |
((ushort)table_buf[3]);
imgdata.lens.makernotes.CurAp =
powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f);
}
break;
case 1536:
case 2048:
// CameraSettings3 are little endian
parseSonyLensType2(table_buf[1016], table_buf[1015]);
if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF)
{
switch (table_buf[153]) {
case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break;
case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break;
}
}
break;
}
free(table_buf);
}
else if (tag == 0x9050) // little endian
{
table_buf_0x9050 = (uchar*)malloc(len);
table_buf_0x9050_present = 1;
fread(table_buf_0x9050, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID);
free (table_buf_0x9050);
table_buf_0x9050_present = 0;
}
}
else if (tag == 0x940c)
{
table_buf_0x940c = (uchar*)malloc(len);
table_buf_0x940c_present = 1;
fread(table_buf_0x940c, len, 1, ifp);
if ((imgdata.lens.makernotes.CamID) &&
(imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E))
{
process_Sony_0x940c(table_buf_0x940c);
free(table_buf_0x940c);
table_buf_0x940c_present = 0;
}
}
else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1))
{
imgdata.lens.makernotes.LensID = get4();
if ((imgdata.lens.makernotes.LensID > 61184) &&
(imgdata.lens.makernotes.LensID < 65535))
{
imgdata.lens.makernotes.LensID -= 61184;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
}
if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A;
}
else if (tag == 0xb02a) // Sony LensSpec
{
table_buf = (uchar*)malloc(len);
fread(table_buf, len, 1, ifp);
if (table_buf[1] | table_buf[2])
imgdata.lens.makernotes.MinFocal =
bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]);
if (table_buf[3] | table_buf[4])
imgdata.lens.makernotes.MaxFocal =
bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]);
if (table_buf[5])
imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f;
if (table_buf[6])
imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f;
parseSonyLensFeatures(table_buf[0], table_buf[7]);
free(table_buf);
}
}
#endif
if (tag == 2 && strstr(make,"NIKON") && !iso_speed)
iso_speed = (get2(),get2());
if (tag == 37 && strstr(make,"NIKON") && (!iso_speed || iso_speed == 65535))
{
unsigned char cc;
fread(&cc,1,1,ifp);
iso_speed = int(100.0 * powf64(2.0f,float(cc)/12.0-5.0));
}
if (tag == 4 && len > 26 && len < 35) {
if ((i=(get4(),get2())) != 0x7fff && (!iso_speed || iso_speed == 65535))
iso_speed = 50 * powf64(2.0, i/32.0 - 4);
if ((i=(get2(),get2())) != 0x7fff && !aperture)
aperture = powf64(2.0, i/64.0);
if ((i=get2()) != 0xffff && !shutter)
shutter = powf64(2.0, (short) i/-32.0);
wbi = (get2(),get2());
shot_order = (get2(),get2());
}
if ((tag == 4 || tag == 0x114) && !strncmp(make,"KONICA",6)) {
fseek (ifp, tag == 4 ? 140:160, SEEK_CUR);
switch (get2()) {
case 72: flip = 0; break;
case 76: flip = 6; break;
case 82: flip = 5; break;
}
}
if (tag == 7 && type == 2 && len > 20)
fgets (model2, 64, ifp);
if (tag == 8 && type == 4)
shot_order = get4();
if (tag == 9 && !strcmp(make,"Canon"))
fread (artist, 64, 1, ifp);
if (tag == 0xc && len == 4)
FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type);
if (tag == 0xd && type == 7 && get2() == 0xaaaa) {
for (c=i=2; (ushort) c != 0xbbbb && i < len; i++)
c = c << 8 | fgetc(ifp);
while ((i+=4) < len-5)
if (get4() == 257 && (i=len) && (c = (get4(),fgetc(ifp))) < 3)
flip = "065"[c]-'0';
}
if (tag == 0x10 && type == 4)
{
unique_id = get4();
#ifdef LIBRAW_LIBRARY_BUILD
setCanonBodyFeatures(unique_id);
if (lenCanonCameraInfo) processCanonCameraInfo(unique_id, CanonCameraInfo);
#endif
}
#ifdef LIBRAW_LIBRARY_BUILD
if(tag == 0x20400805 && len == 2 && !strncasecmp(make,"Olympus",7))
{
imgdata.color.OlympusSensorCalibration[0]=getreal(type);
imgdata.color.OlympusSensorCalibration[1]=getreal(type);
}
if (tag == 0x4001 && len > 500 && !strcasecmp(make,"Canon"))
{
long int save1 = ftell(ifp);
switch (len)
{
case 582:
imgdata.color.canon_makernotes.CanonColorDataVer = 1; // 20D / 350D
break;
case 653:
imgdata.color.canon_makernotes.CanonColorDataVer = 2; // 1Dmk2 / 1DsMK2
break;
case 796:
imgdata.color.canon_makernotes.CanonColorDataVer = 3; // 1DmkIIN / 5D / 30D / 400D
// 1DmkIII / 1DSmkIII / 1DmkIV / 5DmkII
// 7D / 40D / 50D / 60D / 450D / 500D
// 550D / 1000D / 1100D
case 674: case 692: case 702: case 1227: case 1250:
case 1251: case 1337: case 1338: case 1346:
imgdata.color.canon_makernotes.CanonColorDataVer = 4;
imgdata.color.canon_makernotes.CanonColorDataSubVer = get2();
{
fseek (ifp, save1+(0x0e7<<1), SEEK_SET); // offset 231 short
int bls=0;
FORC4 bls+=get2();
imgdata.color.canon_makernotes.AverageBlackLevel = bls/4;
}
if ((imgdata.color.canon_makernotes.CanonColorDataSubVer == 4)
|| (imgdata.color.canon_makernotes.CanonColorDataSubVer == 5))
{
fseek (ifp, save1+(0x2b9<<1), SEEK_SET); // offset 697 shorts
imgdata.color.canon_makernotes.SpecularWhiteLevel = get2();
}
else if ((imgdata.color.canon_makernotes.CanonColorDataSubVer == 6) ||
(imgdata.color.canon_makernotes.CanonColorDataSubVer == 7))
{
fseek (ifp, save1+(0x2d0<<1), SEEK_SET); // offset 720 shorts
imgdata.color.canon_makernotes.SpecularWhiteLevel = get2();
}
else if (imgdata.color.canon_makernotes.CanonColorDataSubVer == 9)
{
fseek (ifp, save1+(0x2d4<<1), SEEK_SET); // offset 724 shorts
imgdata.color.canon_makernotes.SpecularWhiteLevel = get2();
}
break;
case 5120:
imgdata.color.canon_makernotes.CanonColorDataVer = 5; // PowerSot G10
break;
case 1273: case 1275:
imgdata.color.canon_makernotes.CanonColorDataVer = 6; // 600D / 1200D
imgdata.color.canon_makernotes.CanonColorDataSubVer = get2();
{
fseek (ifp, save1+(0x0fb<<1), SEEK_SET); // offset 251 short
int bls=0;
FORC4 bls+=get2();
imgdata.color.canon_makernotes.AverageBlackLevel = bls/4;
}
fseek (ifp, save1+(0x1e4<<1), SEEK_SET); // offset 484 shorts
imgdata.color.canon_makernotes.SpecularWhiteLevel = get2();
break;
// 1DX / 5DmkIII / 6D / 100D / 650D / 700D / M / 7DmkII / 750D / 760D
case 1312: case 1313: case 1316: case 1506:
imgdata.color.canon_makernotes.CanonColorDataVer = 7;
imgdata.color.canon_makernotes.CanonColorDataSubVer = get2();
{
fseek (ifp, save1+(0x114<<1), SEEK_SET); // offset 276 shorts
int bls=0;
FORC4 bls+=get2();
imgdata.color.canon_makernotes.AverageBlackLevel = bls/4;
}
if (imgdata.color.canon_makernotes.CanonColorDataSubVer == 10)
{
fseek (ifp, save1+(0x1fd<<1), SEEK_SET); // offset 509 shorts
imgdata.color.canon_makernotes.SpecularWhiteLevel = get2();
} else if (imgdata.color.canon_makernotes.CanonColorDataSubVer == 11)
{
fseek (ifp, save1+(0x2dd<<1), SEEK_SET); // offset 733 shorts
imgdata.color.canon_makernotes.SpecularWhiteLevel = get2();
}
break;
}
fseek (ifp, save1, SEEK_SET);
}
#endif
if (tag == 0x11 && is_raw && !strncmp(make,"NIKON",5)) {
fseek (ifp, get4()+base, SEEK_SET);
parse_tiff_ifd (base);
}
if (tag == 0x14 && type == 7) {
if (len == 2560) {
fseek (ifp, 1248, SEEK_CUR);
goto get2_256;
}
fread (buf, 1, 10, ifp);
if (!strncmp(buf,"NRW ",4)) {
fseek (ifp, strcmp(buf+4,"0100") ? 46:1546, SEEK_CUR);
cam_mul[0] = get4() << 2;
cam_mul[1] = get4() + get4();
cam_mul[2] = get4() << 2;
}
}
if (tag == 0x15 && type == 2 && is_raw)
fread (model, 64, 1, ifp);
if (strstr(make,"PENTAX")) {
if (tag == 0x1b) tag = 0x1018;
if (tag == 0x1c) tag = 0x1017;
}
if (tag == 0x1d)
while ((c = fgetc(ifp)) && c != EOF)
serial = serial*10 + (isdigit(c) ? c - '0' : c % 10);
if (tag == 0x29 && type == 1) { // Canon PowerShot G9
c = wbi < 18 ? "012347800000005896"[wbi]-'0' : 0;
fseek (ifp, 8 + c*32, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4();
}
#ifndef LIBRAW_LIBRARY_BUILD
// works for some files, but not all
if (tag == 0x3d && type == 3 && len == 4)
FORC4 cblack[c ^ c >> 1] = get2() >> (14-tiff_ifd[2].bps);
#endif
if (tag == 0x81 && type == 4) {
data_offset = get4();
fseek (ifp, data_offset + 41, SEEK_SET);
raw_height = get2() * 2;
raw_width = get2();
filters = 0x61616161;
}
if ((tag == 0x81 && type == 7) ||
(tag == 0x100 && type == 7) ||
(tag == 0x280 && type == 1)) {
thumb_offset = ftell(ifp);
thumb_length = len;
}
if (tag == 0x88 && type == 4 && (thumb_offset = get4()))
thumb_offset += base;
if (tag == 0x89 && type == 4)
thumb_length = get4();
if (tag == 0x8c || tag == 0x96)
meta_offset = ftell(ifp);
if (tag == 0x97) {
for (i=0; i < 4; i++)
ver97 = ver97 * 10 + fgetc(ifp)-'0';
switch (ver97) {
case 100:
fseek (ifp, 68, SEEK_CUR);
FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2();
break;
case 102:
fseek (ifp, 6, SEEK_CUR);
goto get2_rggb;
case 103:
fseek (ifp, 16, SEEK_CUR);
FORC4 cam_mul[c] = get2();
}
if (ver97 >= 200) {
if (ver97 != 205) fseek (ifp, 280, SEEK_CUR);
fread (buf97, 324, 1, ifp);
}
}
if (tag == 0xa1 && type == 7) {
order = 0x4949;
fseek (ifp, 140, SEEK_CUR);
FORC3 cam_mul[c] = get4();
}
if (tag == 0xa4 && type == 3) {
fseek (ifp, wbi*48, SEEK_CUR);
FORC3 cam_mul[c] = get2();
}
if (tag == 0xa7) { // shutter count
NikonKey = fgetc(ifp)^fgetc(ifp)^fgetc(ifp)^fgetc(ifp);
if ( (unsigned) (ver97-200) < 17) {
ci = xlat[0][serial & 0xff];
cj = xlat[1][NikonKey];
ck = 0x60;
for (i=0; i < 324; i++)
buf97[i] ^= (cj += ci * ck++);
i = "66666>666;6A;:;55"[ver97-200] - '0';
FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] =
sget2 (buf97 + (i & -2) + c*2);
}
#ifdef LIBRAW_LIBRARY_BUILD
if ((NikonLensDataVersion > 200) && lenNikonLensData)
{
ci = xlat[0][serial & 0xff];
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < lenNikonLensData; i++)
table_buf[i] ^= (cj += ci * ck++);
processNikonLensData(table_buf, lenNikonLensData);
lenNikonLensData = 0;
}
#endif
}
if(tag == 0xb001 && type == 3) // Sony ModelID
{
unique_id = get2();
}
if (tag == 0x200 && len == 3)
shot_order = (get4(),get4());
if (tag == 0x200 && len == 4)
FORC4 cblack[c ^ c >> 1] = get2();
if (tag == 0x201 && len == 4)
goto get2_rggb;
if (tag == 0x220 && type == 7)
meta_offset = ftell(ifp);
if (tag == 0x401 && type == 4 && len == 4)
FORC4 cblack[c ^ c >> 1] = get4();
#ifdef LIBRAW_LIBRARY_BUILD
// not corrected for file bitcount, to be patched in open_datastream
if (tag == 0x03d && strstr(make,"NIKON") && len == 4)
{
FORC4 cblack[c ^ c >> 1] = get2();
i = cblack[3];
FORC3 if(i>cblack[c]) i = cblack[c];
FORC4 cblack[c]-=i;
black += i;
}
#endif
if (tag == 0xe01) { /* Nikon Capture Note */
order = 0x4949;
fseek (ifp, 22, SEEK_CUR);
for (offset=22; offset+22 < len; offset += 22+i) {
tag = get4();
fseek (ifp, 14, SEEK_CUR);
i = get4()-4;
if (tag == 0x76a43207) flip = get2();
else fseek (ifp, i, SEEK_CUR);
}
}
if (tag == 0xe80 && len == 256 && type == 7) {
fseek (ifp, 48, SEEK_CUR);
cam_mul[0] = get2() * 508 * 1.078 / 0x10000;
cam_mul[2] = get2() * 382 * 1.173 / 0x10000;
}
if (tag == 0xf00 && type == 7) {
if (len == 614)
fseek (ifp, 176, SEEK_CUR);
else if (len == 734 || len == 1502)
fseek (ifp, 148, SEEK_CUR);
else goto next;
goto get2_256;
}
if ((tag == 0x1011 && len == 9) || tag == 0x20400200)
{
if(!strncasecmp(make,"Olympus", 7))
{
int j,k;
for (i=0; i < 3; i++)
FORC3 adobe_cam[i][c] = ((short) get2()) / 256.0;
for (i=0; i < 3; i++)
for (j=0; j < 3; j++)
for (cmatrix[i][j] = k=0; k < 3; k++)
cmatrix[i][j] += rgb_adobe[i][k] * adobe_cam[k][j];
}
else
for (i=0; i < 3; i++)
FORC3 cmatrix[i][c] = ((short) get2()) / 256.0;
}
if ((tag == 0x1012 || tag == 0x20400600) && len == 4)
FORC4 cblack[c ^ c >> 1] = get2();
if (tag == 0x1017 || tag == 0x20400100)
cam_mul[0] = get2() / 256.0;
if (tag == 0x1018 || tag == 0x20400100)
cam_mul[2] = get2() / 256.0;
if (tag == 0x2011 && len == 2) {
get2_256:
order = 0x4d4d;
cam_mul[0] = get2() / 256.0;
cam_mul[2] = get2() / 256.0;
}
if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13))
fseek (ifp, get4()+base, SEEK_SET);
if (tag == 0x2020)
parse_thumb_note (base, 257, 258);
if (tag == 0x2040)
parse_makernote (base, 0x2040);
#ifdef LIBRAW_LIBRARY_BUILD
// IB start
if (tag == 0x2010)
{
parse_makernote(base, 0x2010);
}
// IB end
#endif
if (tag == 0xb028) {
fseek (ifp, get4()+base, SEEK_SET);
parse_thumb_note (base, 136, 137);
}
if (tag == 0x4001 && len > 500) {
i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126;
fseek (ifp, i, SEEK_CUR);
get2_rggb:
FORC4 cam_mul[c ^ (c >> 1)] = get2();
i = len >> 3 == 164 || len == 1506 ? 112:22;
fseek (ifp, i, SEEK_CUR);
FORC4 sraw_mul[c ^ (c >> 1)] = get2();
}
if(!strcasecmp(make,"Samsung"))
{
if (tag == 0xa020) // get the full Samsung encryption key
for (i=0; i<11; i++) SamsungKey[i] = get4();
if (tag == 0xa021) // get and decode Samsung cam_mul array
FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c];
if (tag == 0xa030 && len == 9) // get and decode Samsung color matrix
for (i=0; i < 3; i++)
FORC3 cmatrix[i][c] = (short)((get4() + SamsungKey[i*3+c]))/256.0;
if (tag == 0xa028)
FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c];
}
else
{
// Somebody else use 0xa021 and 0xa028?
if (tag == 0xa021)
FORC4 cam_mul[c ^ (c >> 1)] = get4();
if (tag == 0xa028)
FORC4 cam_mul[c ^ (c >> 1)] -= get4();
}
if (tag == 0x4021 && get4() && get4())
FORC4 cam_mul[c] = 1024;
next:
fseek (ifp, save, SEEK_SET);
}
quit:
order = sorder;
}
/*
Since the TIFF DateTime string has no timezone information,
assume that the camera's clock was set to Universal Time.
*/
void CLASS get_timestamp (int reversed)
{
struct tm t;
char str[20];
int i;
str[19] = 0;
if (reversed)
for (i=19; i--; ) str[i] = fgetc(ifp);
else
fread (str, 19, 1, ifp);
memset (&t, 0, sizeof t);
if (sscanf (str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon,
&t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6)
return;
t.tm_year -= 1900;
t.tm_mon -= 1;
t.tm_isdst = -1;
if (mktime(&t) > 0)
timestamp = mktime(&t);
}
void CLASS parse_exif (int base)
{
unsigned kodak, entries, tag, type, len, save, c;
double expo,ape;
kodak = !strncmp(make,"EASTMAN",7) && tiff_nifds < 3;
entries = get2();
if(!strcmp(make,"Hasselblad") && (tiff_nifds > 3) && (entries > 512)) return;
// printf("\n*** in parse_exif, make: =%s= model: =%s=", make, model);
while (entries--) {
tiff_get (base, &tag, &type, &len, &save);
// printf("\n\ttag: %x", tag);
#ifdef LIBRAW_LIBRARY_BUILD
if(callbacks.exif_cb)
{
int savepos = ftell(ifp);
callbacks.exif_cb(callbacks.exifparser_data,tag,type,len,order,ifp);
fseek(ifp,savepos,SEEK_SET);
}
#endif
switch (tag) {
#ifdef LIBRAW_LIBRARY_BUILD
case 0xa405: // FocalLengthIn35mmFormat
imgdata.lens.FocalLengthIn35mmFormat = get2();
break;
case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard
imgdata.lens.dng.MinFocal = getreal(type);
imgdata.lens.dng.MaxFocal = getreal(type);
imgdata.lens.dng.MaxAp4MinFocal = getreal(type);
imgdata.lens.dng.MaxAp4MaxFocal = getreal(type);
break;
case 0xa433: // LensMake
fread(imgdata.lens.LensMake, MIN(len,sizeof(imgdata.lens.LensMake)), 1, ifp);
break;
case 0xa434: // LensModel
fread(imgdata.lens.Lens, MIN(len, sizeof(imgdata.lens.LensMake)), 1, ifp);
if (!strncmp(imgdata.lens.Lens, "----", 4))
imgdata.lens.Lens[0] = 0;
break;
case 0x9205:
imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f));
break;
#endif
case 33434: shutter = getreal(type); break;
case 33437: aperture = getreal(type); break;
case 34855: iso_speed = get2(); break;
case 34866:
if (iso_speed == 0xffff && (!strcasecmp(make, "SONY") || !strcasecmp(make, "CANON")))
iso_speed = getreal(type);
break;
case 36867:
case 36868: get_timestamp(0); break;
case 37377: if ((expo = -getreal(type)) < 128 && shutter == 0.)
shutter = powf64(2.0, expo); break;
case 37378:
if (fabs(ape = getreal(type))<256.0)
aperture = powf64(2.0, ape/2);
break;
case 37385: flash_used = getreal(type); break;
case 37386: focal_len = getreal(type); break;
case 37500: parse_makernote (base, 0); break; // tag 0x927c
case 40962: if (kodak) raw_width = get4(); break;
case 40963: if (kodak) raw_height = get4(); break;
case 41730:
if (get4() == 0x20002)
for (exif_cfa=c=0; c < 8; c+=2)
exif_cfa |= fgetc(ifp) * 0x01010101 << c;
}
fseek (ifp, save, SEEK_SET);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS parse_gps_libraw(int base)
{
unsigned entries, tag, type, len, save, c;
entries = get2();
if (entries > 0)
imgdata.other.parsed_gps.gpsparsed = 1;
while (entries--) {
tiff_get(base, &tag, &type, &len, &save);
switch (tag) {
case 1: imgdata.other.parsed_gps.latref = getc(ifp); break;
case 3: imgdata.other.parsed_gps.longref = getc(ifp); break;
case 5: imgdata.other.parsed_gps.altref = getc(ifp); break;
case 2:
if (len == 3)
FORC(3) imgdata.other.parsed_gps.latitude[c] = getreal(type);
break;
case 4:
if (len == 3)
FORC(3) imgdata.other.parsed_gps.longtitude[c] = getreal(type);
break;
case 7:
if (len == 3)
FORC(3) imgdata.other.parsed_gps.gpstimestamp[c] = getreal(type);
break;
case 6:
imgdata.other.parsed_gps.altitude = getreal(type);
break;
case 9: imgdata.other.parsed_gps.gpsstatus = getc(ifp); break;
}
fseek(ifp, save, SEEK_SET);
}
}
#endif
void CLASS parse_gps (int base)
{
unsigned entries, tag, type, len, save, c;
entries = get2();
while (entries--) {
tiff_get (base, &tag, &type, &len, &save);
switch (tag) {
case 1: case 3: case 5:
gpsdata[29+tag/2] = getc(ifp); break;
case 2: case 4: case 7:
FORC(6) gpsdata[tag/3*6+c] = get4(); break;
case 6:
FORC(2) gpsdata[18+c] = get4(); break;
case 18: case 29:
fgets ((char *) (gpsdata+14+tag/3), MIN(len,12), ifp);
}
fseek (ifp, save, SEEK_SET);
}
}
void CLASS romm_coeff (float romm_cam[3][3])
{
static const float rgb_romm[3][3] = /* ROMM == Kodak ProPhoto */
{ { 2.034193, -0.727420, -0.306766 },
{ -0.228811, 1.231729, -0.002922 },
{ -0.008565, -0.153273, 1.161839 } };
int i, j, k;
for (i=0; i < 3; i++)
for (j=0; j < 3; j++)
for (cmatrix[i][j] = k=0; k < 3; k++)
cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j];
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.color.digitalBack_color=1;
#endif
}
void CLASS parse_mos (int offset)
{
char data[40];
int skip, from, i, c, neut[4], planes=0, frot=0;
static const char *mod[] =
{ "","DCB2","Volare","Cantare","CMost","Valeo 6","Valeo 11","Valeo 22",
"Valeo 11p","Valeo 17","","Aptus 17","Aptus 22","Aptus 75","Aptus 65",
"Aptus 54S","Aptus 65S","Aptus 75S","AFi 5","AFi 6","AFi 7",
"Aptus-II 7","","","Aptus-II 6","","","Aptus-II 10","Aptus-II 5",
"","","","","Aptus-II 10R","Aptus-II 8","","Aptus-II 12","","AFi-II 12" };
float romm_cam[3][3];
fseek (ifp, offset, SEEK_SET);
while (1) {
if (get4() != 0x504b5453) break;
get4();
fread (data, 1, 40, ifp);
skip = get4();
from = ftell(ifp);
// IB start
#ifdef LIBRAW_LIBRARY_BUILD
if (!strcmp(data,"CameraObj_camera_type")) {
fread(imgdata.lens.makernotes.body, skip, 1, ifp);
}
#endif
// IB end
if (!strcmp(data,"JPEG_preview_data")) {
thumb_offset = from;
thumb_length = skip;
}
if (!strcmp(data,"icc_camera_profile")) {
profile_offset = from;
profile_length = skip;
}
if (!strcmp(data,"ShootObj_back_type")) {
fscanf (ifp, "%d", &i);
if ((unsigned) i < sizeof mod / sizeof (*mod))
strcpy (model, mod[i]);
}
if (!strcmp(data,"icc_camera_to_tone_matrix")) {
for (i=0; i < 9; i++)
romm_cam[0][i] = int_to_float(get4());
romm_coeff (romm_cam);
}
if (!strcmp(data,"CaptProf_color_matrix")) {
for (i=0; i < 9; i++)
fscanf (ifp, "%f", &romm_cam[0][i]);
romm_coeff (romm_cam);
}
if (!strcmp(data,"CaptProf_number_of_planes"))
fscanf (ifp, "%d", &planes);
if (!strcmp(data,"CaptProf_raw_data_rotation"))
fscanf (ifp, "%d", &flip);
if (!strcmp(data,"CaptProf_mosaic_pattern"))
FORC4 {
fscanf (ifp, "%d", &i);
if (i == 1) frot = c ^ (c >> 1);
}
if (!strcmp(data,"ImgProf_rotation_angle")) {
fscanf (ifp, "%d", &i);
flip = i - flip;
}
if (!strcmp(data,"NeutObj_neutrals") && !cam_mul[0]) {
FORC4 fscanf (ifp, "%d", neut+c);
FORC3 cam_mul[c] = (float) neut[0] / neut[c+1];
}
if (!strcmp(data,"Rows_data"))
load_flags = get4();
parse_mos (from);
fseek (ifp, skip+from, SEEK_SET);
}
if (planes)
filters = (planes == 1) * 0x01010101 *
(uchar) "\x94\x61\x16\x49"[(flip/90 + frot) & 3];
}
void CLASS linear_table (unsigned len)
{
int i;
if (len > 0x10000) len = 0x10000;
read_shorts (curve, len);
for (i=len; i < 0x10000; i++)
curve[i] = curve[i-1];
maximum = curve[len<0x1000?0xfff:len-1];
}
#ifdef LIBRAW_LIBRARY_BUILD
/* Thanks to Alexey Danilchenko for wb as-shot parsing code */
void CLASS parse_kodak_ifd (int base)
{
unsigned entries, tag, type, len, save;
int i, c, wbi=-2;
float mul[3]={1,1,1}, num;
static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 };
entries = get2();
if (entries > 1024) return;
while (entries--) {
tiff_get (base, &tag, &type, &len, &save);
#ifdef LIBRAW_LIBRARY_BUILD
if(callbacks.exif_cb)
{
int savepos = ftell(ifp);
callbacks.exif_cb(callbacks.exifparser_data,tag | 0x20000,type,len,order,ifp);
fseek(ifp,savepos,SEEK_SET);
}
#endif
if (tag == 1020) wbi = getint(type);
if (tag == 1021 && len == 72) { /* WB set in software */
fseek (ifp, 40, SEEK_CUR);
FORC3 cam_mul[c] = 2048.0 / get2();
wbi = -2;
}
if (tag == 2120 + wbi ||
(wbi<0 && tag == 2125)) /* use Auto WB if illuminant index is not set */
{
FORC3 mul[c] = (num=getreal(type))==0 ? 1 : num;
FORC3 cam_mul[c] = mul[1] / mul[c]; /* normalise against green */
}
if (tag == 2317) linear_table (len);
if (tag == 0x903) iso_speed = getreal(type);
//if (tag == 6020) iso_speed = getint(type);
if (tag == 64013) wbi = fgetc(ifp);
if ((unsigned) wbi < 7 && tag == wbtag[wbi])
FORC3 cam_mul[c] = get4();
if (tag == 64019) width = getint(type);
if (tag == 64020) height = (getint(type)+1) & -2;
fseek (ifp, save, SEEK_SET);
}
}
#else
void CLASS parse_kodak_ifd (int base)
{
unsigned entries, tag, type, len, save;
int i, c, wbi=-2, wbtemp=6500;
float mul[3]={1,1,1}, num;
static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 };
entries = get2();
if (entries > 1024) return;
while (entries--) {
tiff_get (base, &tag, &type, &len, &save);
if (tag == 1020) wbi = getint(type);
if (tag == 1021 && len == 72) { /* WB set in software */
fseek (ifp, 40, SEEK_CUR);
FORC3 cam_mul[c] = 2048.0 / get2();
wbi = -2;
}
if (tag == 2118) wbtemp = getint(type);
if (tag == 2120 + wbi && wbi >= 0)
FORC3 cam_mul[c] = 2048.0 / getreal(type);
if (tag == 2130 + wbi)
FORC3 mul[c] = getreal(type);
if (tag == 2140 + wbi && wbi >= 0)
FORC3 {
for (num=i=0; i < 4; i++)
num += getreal(type) * pow (wbtemp/100.0, i);
cam_mul[c] = 2048 / (num * mul[c]);
}
if (tag == 2317) linear_table (len);
if (tag == 6020) iso_speed = getint(type);
if (tag == 64013) wbi = fgetc(ifp);
if ((unsigned) wbi < 7 && tag == wbtag[wbi])
FORC3 cam_mul[c] = get4();
if (tag == 64019) width = getint(type);
if (tag == 64020) height = (getint(type)+1) & -2;
fseek (ifp, save, SEEK_SET);
}
}
#endif
//@end COMMON
void CLASS parse_minolta (int base);
int CLASS parse_tiff (int base);
//@out COMMON
int CLASS parse_tiff_ifd (int base)
{
unsigned entries, tag, type, len, plen=16, save;
int ifd, use_cm=0, cfa, i, j, c, ima_len=0;
char *cbuf, *cp;
uchar cfa_pat[16], cfa_pc[] = { 0,1,2,3 }, tab[256];
double cc[4][4], cm[4][3], cam_xyz[4][3], num;
double ab[]={ 1,1,1,1 }, asn[] = { 0,0,0,0 }, xyz[] = { 1,1,1 };
unsigned sony_curve[] = { 0,0,0,0,0,4095 };
unsigned *buf, sony_offset=0, sony_length=0, sony_key=0;
struct jhead jh;
int pana_raw = 0;
#ifndef LIBRAW_LIBRARY_BUILD
FILE *sfp;
#endif
if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0])
return 1;
ifd = tiff_nifds++;
for (j=0; j < 4; j++)
for (i=0; i < 4; i++)
cc[j][i] = i == j;
entries = get2();
if (entries > 512) return 1;
while (entries--) {
tiff_get (base, &tag, &type, &len, &save);
// printf ("\n*** parse_tiff_ifd tag: 0x%04x", tag);
#ifdef LIBRAW_LIBRARY_BUILD
if(callbacks.exif_cb)
{
int savepos = ftell(ifp);
callbacks.exif_cb(callbacks.exifparser_data,tag|(pana_raw?0x30000:0),type,len,order,ifp);
fseek(ifp,savepos,SEEK_SET);
}
#endif
switch (tag) {
case 1: if(len==4) pana_raw = get4(); break;
case 5: width = get2(); break;
case 6: height = get2(); break;
case 7: width += get2(); break;
case 9: if ((i = get2())) filters = i;
#ifdef LIBRAW_LIBRARY_BUILD
if(pana_raw && len == 1 && type ==3)
pana_black[3]+=i;
#endif
break;
case 8:
case 10:
#ifdef LIBRAW_LIBRARY_BUILD
if(pana_raw && len == 1 && type ==3)
pana_black[3]+=get2();
#endif
break;
case 17: case 18:
if (type == 3 && len == 1)
cam_mul[(tag-17)*2] = get2() / 256.0;
break;
case 23:
if (type == 3) iso_speed = get2();
break;
case 28: case 29: case 30:
#ifdef LIBRAW_LIBRARY_BUILD
if(pana_raw && len == 1 && type ==3)
{
pana_black[tag-28] = get2();
}
else
#endif
{
cblack[tag-28] = get2();
cblack[3] = cblack[1];
}
break;
case 36: case 37: case 38:
cam_mul[tag-36] = get2();
break;
case 39:
if (len < 50 || cam_mul[0]) break;
fseek (ifp, 12, SEEK_CUR);
FORC3 cam_mul[c] = get2();
break;
case 46:
if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break;
thumb_offset = ftell(ifp) - 2;
thumb_length = len;
break;
case 61440: /* Fuji HS10 table */
fseek (ifp, get4()+base, SEEK_SET);
parse_tiff_ifd (base);
break;
case 2: case 256: case 61441: /* ImageWidth */
tiff_ifd[ifd].t_width = getint(type);
break;
case 3: case 257: case 61442: /* ImageHeight */
tiff_ifd[ifd].t_height = getint(type);
break;
case 258: /* BitsPerSample */
case 61443:
tiff_ifd[ifd].samples = len & 7;
tiff_ifd[ifd].bps = getint(type);
break;
case 61446:
raw_height = 0;
if (tiff_ifd[ifd].bps > 12) break;
load_raw = &CLASS packed_load_raw;
load_flags = get4() ? 24:80;
break;
case 259: /* Compression */
tiff_ifd[ifd].comp = getint(type);
break;
case 262: /* PhotometricInterpretation */
tiff_ifd[ifd].phint = get2();
break;
case 270: /* ImageDescription */
fread (desc, 512, 1, ifp);
break;
case 271: /* Make */
fgets (make, 64, ifp);
break;
case 272: /* Model */
fgets (model, 64, ifp);
break;
case 280: /* Panasonic RW2 offset */
if (type != 4) break;
load_raw = &CLASS panasonic_load_raw;
load_flags = 0x2008;
case 273: /* StripOffset */
case 513: /* JpegIFOffset */
case 61447:
tiff_ifd[ifd].offset = get4()+base;
if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) {
fseek (ifp, tiff_ifd[ifd].offset, SEEK_SET);
if (ljpeg_start (&jh, 1)) {
tiff_ifd[ifd].comp = 6;
tiff_ifd[ifd].t_width = jh.wide;
tiff_ifd[ifd].t_height = jh.high;
tiff_ifd[ifd].bps = jh.bits;
tiff_ifd[ifd].samples = jh.clrs;
if (!(jh.sraw || (jh.clrs & 1)))
tiff_ifd[ifd].t_width *= jh.clrs;
i = order;
parse_tiff (tiff_ifd[ifd].offset + 12);
order = i;
}
}
break;
case 274: /* Orientation */
tiff_ifd[ifd].t_flip = "50132467"[get2() & 7]-'0';
break;
case 277: /* SamplesPerPixel */
tiff_ifd[ifd].samples = getint(type) & 7;
break;
case 279: /* StripByteCounts */
case 514:
case 61448:
tiff_ifd[ifd].bytes = get4();
break;
case 61454:
FORC3 cam_mul[(4-c) % 3] = getint(type);
break;
case 305: case 11: /* Software */
fgets (software, 64, ifp);
if (!strncmp(software,"Adobe",5) ||
!strncmp(software,"dcraw",5) ||
!strncmp(software,"UFRaw",5) ||
!strncmp(software,"Bibble",6) ||
!strcmp (software,"Digital Photo Professional"))
is_raw = 0;
break;
case 306: /* DateTime */
get_timestamp(0);
break;
case 315: /* Artist */
fread (artist, 64, 1, ifp);
break;
case 322: /* TileWidth */
tiff_ifd[ifd].t_tile_width = getint(type);
break;
case 323: /* TileLength */
tiff_ifd[ifd].t_tile_length = getint(type);
break;
case 324: /* TileOffsets */
tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4();
if (len == 1)
tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0;
if (len == 4) {
load_raw = &CLASS sinar_4shot_load_raw;
is_raw = 5;
}
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 325: /* TileByteCount */
tiff_ifd[ifd].tile_maxbytes = 0;
for(int jj=0;jj<len;jj++)
{
int s = get4();
if(s > tiff_ifd[ifd].tile_maxbytes) tiff_ifd[ifd].tile_maxbytes=s;
}
break;
#endif
case 330: /* SubIFDs */
if (!strcmp(model,"DSLR-A100") && tiff_ifd[ifd].t_width == 3872) {
load_raw = &CLASS sony_arw_load_raw;
data_offset = get4()+base;
ifd++; break;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!strcmp(make,"Hasselblad") && libraw_internal_data.unpacker_data.hasselblad_parser_flag) {
fseek (ifp, ftell(ifp)+4, SEEK_SET);
fseek (ifp, get4()+base, SEEK_SET);
parse_tiff_ifd (base);
break;
}
#endif
if(len > 1000) len=1000; /* 1000 SubIFDs is enough */
while (len--) {
i = ftell(ifp);
fseek (ifp, get4()+base, SEEK_SET);
if (parse_tiff_ifd (base)) break;
fseek (ifp, i+4, SEEK_SET);
}
break;
case 400:
strcpy (make, "Sarnoff");
maximum = 0xfff;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 700:
if((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000)
{
xmpdata = (char*)malloc(xmplen = len+1);
fread(xmpdata,len,1,ifp);
xmpdata[len]=0;
}
break;
#endif
case 28688:
FORC4 sony_curve[c+1] = get2() >> 2 & 0xfff;
for (i=0; i < 5; i++)
for (j = sony_curve[i]+1; j <= sony_curve[i+1]; j++)
curve[j] = curve[j-1] + (1 << i);
break;
case 29184: sony_offset = get4(); break;
case 29185: sony_length = get4(); break;
case 29217: sony_key = get4(); break;
case 29264:
parse_minolta (ftell(ifp));
raw_width = 0;
break;
case 29443:
FORC4 cam_mul[c ^ (c < 2)] = get2();
break;
case 29459:
FORC4 cam_mul[c] = get2();
i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1;
SWAP (cam_mul[i],cam_mul[i+1])
break;
case 30720: // Sony matrix, Sony_SR2SubIFD_0x7800
for (i=0; i < 3; i++)
FORC3 cmatrix[i][c] = ((short) get2()) / 1024.0;
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr, _(" Sony matrix:\n%f %f %f\n%f %f %f\n%f %f %f\n"), cmatrix[0][0], cmatrix[0][1], cmatrix[0][2], cmatrix[1][0], cmatrix[1][1], cmatrix[1][2], cmatrix[2][0], cmatrix[2][1], cmatrix[2][2]);
#endif
break;
case 29456: // Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4
FORC4 cblack[c ^ c >> 1] = get2();
i = cblack[3];
FORC3 if(i>cblack[c]) i = cblack[c];
FORC4 cblack[c]-=i;
black = i;
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr, _("...Sony black: %u cblack: %u %u %u %u\n"),black, cblack[0],cblack[1],cblack[2], cblack[3]);
#endif
break;
case 33405: /* Model2 */
fgets (model2, 64, ifp);
break;
case 33421: /* CFARepeatPatternDim */
if (get2() == 6 && get2() == 6)
filters = 9;
break;
case 33422: /* CFAPattern */
if (filters == 9) {
FORC(36) xtrans[0][c] = fgetc(ifp) & 3;
break;
}
case 64777: /* Kodak P-series */
if(len == 36)
{
filters = 9;
colors = 3;
FORC(36) xtrans[0][c] = fgetc(ifp) & 3;
}
else
{
if ((plen=len) > 16) plen = 16;
fread (cfa_pat, 1, plen, ifp);
for (colors=cfa=i=0; i < plen && colors < 4; i++) {
colors += !(cfa & (1 << cfa_pat[i]));
cfa |= 1 << cfa_pat[i];
}
if (cfa == 070) memcpy (cfa_pc,"\003\004\005",3); /* CMY */
if (cfa == 072) memcpy (cfa_pc,"\005\003\004\001",4); /* GMCY */
goto guess_cfa_pc;
}
break;
case 33424:
case 65024:
fseek (ifp, get4()+base, SEEK_SET);
parse_kodak_ifd (base);
break;
case 33434: /* ExposureTime */
shutter = getreal(type);
break;
case 33437: /* FNumber */
aperture = getreal(type);
break;
#ifdef LIBRAW_LIBRARY_BUILD
// IB start
case 0xa405: // FocalLengthIn35mmFormat
imgdata.lens.FocalLengthIn35mmFormat = get2();
break;
case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa433: // LensMake
fread(imgdata.lens.LensMake, MIN(len, sizeof(imgdata.lens.LensMake)), 1, ifp);
break;
case 0xa434: // LensModel
fread(imgdata.lens.Lens, MIN(len, sizeof(imgdata.lens.Lens)), 1, ifp);
if (!strncmp(imgdata.lens.Lens, "----", 4))
imgdata.lens.Lens[0] = 0;
break;
case 0x9205:
imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f));
break;
// IB end
#endif
case 34306: /* Leaf white balance */
FORC4 cam_mul[c ^ 1] = 4096.0 / get2();
break;
case 34307: /* Leaf CatchLight color matrix */
fread (software, 1, 7, ifp);
if (strncmp(software,"MATRIX",6)) break;
colors = 4;
for (raw_color = i=0; i < 3; i++) {
FORC4 fscanf (ifp, "%f", &rgb_cam[i][c^1]);
if (!use_camera_wb) continue;
num = 0;
FORC4 num += rgb_cam[i][c];
FORC4 rgb_cam[i][c] /= num;
}
break;
case 34310: /* Leaf metadata */
parse_mos (ftell(ifp));
case 34303:
strcpy (make, "Leaf");
break;
case 34665: /* EXIF tag */
fseek (ifp, get4()+base, SEEK_SET);
parse_exif (base);
break;
case 34853: /* GPSInfo tag */
{
unsigned pos;
fseek(ifp, pos = (get4() + base), SEEK_SET);
parse_gps(base);
#ifdef LIBRAW_LIBRARY_BUILD
fseek(ifp, pos, SEEK_SET);
parse_gps_libraw(base);
#endif
}
break;
case 34675: /* InterColorProfile */
case 50831: /* AsShotICCProfile */
profile_offset = ftell(ifp);
profile_length = len;
break;
case 37122: /* CompressedBitsPerPixel */
kodak_cbpp = get4();
break;
case 37386: /* FocalLength */
focal_len = getreal(type);
break;
case 37393: /* ImageNumber */
shot_order = getint(type);
break;
case 37400: /* old Kodak KDC tag */
for (raw_color = i=0; i < 3; i++) {
getreal(type);
FORC3 rgb_cam[i][c] = getreal(type);
}
break;
case 40976:
strip_offset = get4();
switch (tiff_ifd[ifd].comp) {
case 32770: load_raw = &CLASS samsung_load_raw; break;
case 32772: load_raw = &CLASS samsung2_load_raw; break;
case 32773: load_raw = &CLASS samsung3_load_raw; break;
}
break;
case 46275: /* Imacon tags */
strcpy (make, "Imacon");
data_offset = ftell(ifp);
ima_len = len;
break;
case 46279:
if (!ima_len) break;
fseek (ifp, 38, SEEK_CUR);
case 46274:
fseek (ifp, 40, SEEK_CUR);
raw_width = get4();
raw_height = get4();
left_margin = get4() & 7;
width = raw_width - left_margin - (get4() & 7);
top_margin = get4() & 7;
height = raw_height - top_margin - (get4() & 7);
if (raw_width == 7262 && ima_len == 234317952 ) {
height = 5412;
width = 7216;
left_margin = 7;
filters=0;
} else if (raw_width == 7262) {
height = 5444;
width = 7244;
left_margin = 7;
}
fseek (ifp, 52, SEEK_CUR);
FORC3 cam_mul[c] = getreal(11);
fseek (ifp, 114, SEEK_CUR);
flip = (get2() >> 7) * 90;
if (width * height * 6 == ima_len) {
if (flip % 180 == 90) SWAP(width,height);
raw_width = width;
raw_height = height;
left_margin = top_margin = filters = flip = 0;
}
sprintf (model, "Ixpress %d-Mp", height*width/1000000);
load_raw = &CLASS imacon_full_load_raw;
if (filters) {
if (left_margin & 1) filters = 0x61616161;
load_raw = &CLASS unpacked_load_raw;
}
maximum = 0xffff;
break;
case 50454: /* Sinar tag */
case 50455:
if (!(cbuf = (char *) malloc(len))) break;
fread (cbuf, 1, len, ifp);
for (cp = cbuf-1; cp && cp < cbuf+len; cp = strchr(cp,'\n'))
if (!strncmp (++cp,"Neutral ",8))
sscanf (cp+8, "%f %f %f", cam_mul, cam_mul+1, cam_mul+2);
free (cbuf);
break;
case 50458:
if (!make[0]) strcpy (make, "Hasselblad");
break;
case 50459: /* Hasselblad tag */
#ifdef LIBRAW_LIBRARY_BUILD
libraw_internal_data.unpacker_data.hasselblad_parser_flag=1;
#endif
i = order;
j = ftell(ifp);
c = tiff_nifds;
order = get2();
fseek (ifp, j+(get2(),get4()), SEEK_SET);
parse_tiff_ifd (j);
maximum = 0xffff;
tiff_nifds = c;
order = i;
break;
case 50706: /* DNGVersion */
FORC4 dng_version = (dng_version << 8) + fgetc(ifp);
if (!make[0]) strcpy (make, "DNG");
is_raw = 1;
break;
case 50710: /* CFAPlaneColor */
if (filters == 9) break;
if (len > 4) len = 4;
colors = len;
fread (cfa_pc, 1, colors, ifp);
guess_cfa_pc:
FORCC tab[cfa_pc[c]] = c;
cdesc[c] = 0;
for (i=16; i--; )
filters = filters << 2 | tab[cfa_pat[i % plen]];
filters -= !filters;
break;
case 50711: /* CFALayout */
if (get2() == 2) {
fuji_width = 1;
filters = 0x49494949;
}
break;
case 291:
case 50712: /* LinearizationTable */
linear_table (len);
break;
case 50713: /* BlackLevelRepeatDim */
cblack[4] = get2();
cblack[5] = get2();
if (cblack[4] * cblack[5] > (sizeof(cblack) / sizeof (cblack[0]) - 6))
cblack[4] = cblack[5] = 1;
break;
case 61450:
cblack[4] = cblack[5] = MIN(sqrt((double)len),64);
case 50714: /* BlackLevel */
if((cblack[4] * cblack[5] < 2) && len == 1)
{
black = getreal(type);
}
else if(cblack[4] * cblack[5] <= len)
{
FORC (cblack[4] * cblack[5])
cblack[6+c] = getreal(type);
black = 0;
}
break;
case 50715: /* BlackLevelDeltaH */
case 50716: /* BlackLevelDeltaV */
for (num=i=0; i < len && i < 65536; i++)
num += getreal(type);
black += num/len + 0.5;
break;
case 50717: /* WhiteLevel */
maximum = getint(type);
break;
case 50718: /* DefaultScale */
pixel_aspect = getreal(type);
pixel_aspect /= getreal(type);
if(pixel_aspect > 0.995 && pixel_aspect < 1.005)
pixel_aspect = 1.0;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 50778:
imgdata.color.dng_color[0].illuminant = get2();
break;
case 50779:
imgdata.color.dng_color[1].illuminant = get2();
break;
#endif
case 50721: /* ColorMatrix1 */
case 50722: /* ColorMatrix2 */
#ifdef LIBRAW_LIBRARY_BUILD
i = tag == 50721?0:1;
#endif
FORCC for (j=0; j < 3; j++)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.color.dng_color[i].colormatrix[c][j]=
#endif
cm[c][j] = getreal(type);
}
use_cm = 1;
break;
case 50723: /* CameraCalibration1 */
case 50724: /* CameraCalibration2 */
#ifdef LIBRAW_LIBRARY_BUILD
j = tag == 50723?0:1;
#endif
for (i=0; i < colors; i++)
FORCC
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.color.dng_color[j].calibration[i][c]=
#endif
cc[i][c] = getreal(type);
}
break;
case 50727: /* AnalogBalance */
FORCC ab[c] = getreal(type);
break;
case 50728: /* AsShotNeutral */
FORCC asn[c] = getreal(type);
break;
case 50729: /* AsShotWhiteXY */
xyz[0] = getreal(type);
xyz[1] = getreal(type);
xyz[2] = 1 - xyz[0] - xyz[1];
FORC3 xyz[c] /= d65_white[c];
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 50730: /* DNG: Baseline Exposure */
baseline_exposure = getreal(type);
break;
#endif
// IB start
case 50740: /* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private */
{
char mbuf[64];
unsigned short makernote_found = 0;
unsigned curr_pos, start_pos = ftell(ifp);
unsigned MakN_order, m_sorder = order;
unsigned MakN_length;
unsigned pos_in_original_raw;
fread(mbuf, 1, 6, ifp);
if (!strcmp(mbuf, "Adobe")) {
order = 0x4d4d; // Adobe header is always in "MM" / big endian
curr_pos = start_pos + 6;
while (curr_pos + 8 - start_pos <= len)
{
fread(mbuf, 1, 4, ifp);
curr_pos += 8;
if (!strncmp(mbuf, "MakN", 4)) {
makernote_found = 1;
MakN_length = get4();
MakN_order = get2();
pos_in_original_raw = get4();
order = MakN_order;
parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG);
break;
}
}
}
else {
fread(mbuf + 6, 1, 2, ifp);
if (!strcmp(mbuf, "PENTAX ") ||
!strcmp(mbuf, "SAMSUNG"))
{
makernote_found = 1;
fseek(ifp, start_pos, SEEK_SET);
parse_makernote_0xc634(base, 0, CameraDNG);
}
}
if (!makernote_found) fseek(ifp, start_pos, SEEK_SET);
order = m_sorder;
}
// IB end
if (dng_version) break;
parse_minolta (j = get4()+base);
fseek (ifp, j, SEEK_SET);
parse_tiff_ifd (base);
break;
case 50752:
read_shorts (cr2_slice, 3);
break;
case 50829: /* ActiveArea */
top_margin = getint(type);
left_margin = getint(type);
height = getint(type) - top_margin;
width = getint(type) - left_margin;
break;
case 50830: /* MaskedAreas */
for (i=0; i < len && i < 32; i++)
mask[0][i] = getint(type);
black = 0;
break;
case 51009: /* OpcodeList2 */
meta_offset = ftell(ifp);
break;
case 64772: /* Kodak P-series */
if (len < 13) break;
fseek (ifp, 16, SEEK_CUR);
data_offset = get4();
fseek (ifp, 28, SEEK_CUR);
data_offset += get4();
load_raw = &CLASS packed_load_raw;
break;
case 65026:
if (type == 2) fgets (model2, 64, ifp);
}
fseek (ifp, save, SEEK_SET);
}
if (sony_length && (buf = (unsigned *) malloc(sony_length))) {
fseek (ifp, sony_offset, SEEK_SET);
fread (buf, sony_length, 1, ifp);
sony_decrypt (buf, sony_length/4, 1, sony_key);
#ifndef LIBRAW_LIBRARY_BUILD
sfp = ifp;
if ((ifp = tmpfile())) {
fwrite (buf, sony_length, 1, ifp);
fseek (ifp, 0, SEEK_SET);
parse_tiff_ifd (-sony_offset);
fclose (ifp);
}
ifp = sfp;
#else
if( !ifp->tempbuffer_open(buf,sony_length))
{
parse_tiff_ifd(-sony_offset);
ifp->tempbuffer_close();
}
#endif
free (buf);
}
for (i=0; i < colors; i++)
FORCC cc[i][c] *= ab[i];
if (use_cm) {
FORCC for (i=0; i < 3; i++)
for (cam_xyz[c][i]=j=0; j < colors; j++)
cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i];
cam_xyz_coeff (cmatrix, cam_xyz);
}
if (asn[0]) {
cam_mul[3] = 0;
FORCC cam_mul[c] = 1 / asn[c];
}
if (!use_cm)
FORCC pre_mul[c] /= cc[c][c];
return 0;
}
int CLASS parse_tiff (int base)
{
int doff;
fseek (ifp, base, SEEK_SET);
order = get2();
if (order != 0x4949 && order != 0x4d4d) return 0;
get2();
while ((doff = get4())) {
fseek (ifp, doff+base, SEEK_SET);
if (parse_tiff_ifd (base)) break;
}
return 1;
}
void CLASS apply_tiff()
{
int max_samp=0, raw=-1, thm=-1, i;
struct jhead jh;
thumb_misc = 16;
if (thumb_offset) {
fseek (ifp, thumb_offset, SEEK_SET);
if (ljpeg_start (&jh, 1)) {
if((unsigned)jh.bits<17 && (unsigned)jh.wide < 0x10000 && (unsigned)jh.high < 0x10000)
{
thumb_misc = jh.bits;
thumb_width = jh.wide;
thumb_height = jh.high;
}
}
}
for (i=0; i < tiff_nifds; i++) {
if (max_samp < tiff_ifd[i].samples)
max_samp = tiff_ifd[i].samples;
if (max_samp > 3) max_samp = 3;
if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) &&
unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 &&
(unsigned)tiff_ifd[i].bps < 33 && (unsigned)tiff_ifd[i].samples < 13 &&
tiff_ifd[i].t_width*tiff_ifd[i].t_height > raw_width*raw_height) {
raw_width = tiff_ifd[i].t_width;
raw_height = tiff_ifd[i].t_height;
tiff_bps = tiff_ifd[i].bps;
tiff_compress = tiff_ifd[i].comp;
data_offset = tiff_ifd[i].offset;
tiff_flip = tiff_ifd[i].t_flip;
tiff_samples = tiff_ifd[i].samples;
tile_width = tiff_ifd[i].t_tile_width;
tile_length = tiff_ifd[i].t_tile_length;
#ifdef LIBRAW_LIBRARY_BUILD
data_size = tile_length < INT_MAX && tile_length>0 ? tiff_ifd[i].tile_maxbytes: tiff_ifd[i].bytes;
#endif
raw = i;
}
}
if (!tile_width ) tile_width = INT_MAX;
if (!tile_length) tile_length = INT_MAX;
for (i=tiff_nifds; i--; )
if (tiff_ifd[i].t_flip) tiff_flip = tiff_ifd[i].t_flip;
if (raw >= 0 && !load_raw)
switch (tiff_compress) {
case 32767:
if (tiff_ifd[raw].bytes == raw_width*raw_height) {
tiff_bps = 12;
load_raw = &CLASS sony_arw2_load_raw; break;
}
if (tiff_ifd[raw].bytes*8 != raw_width*raw_height*tiff_bps) {
raw_height += 8;
load_raw = &CLASS sony_arw_load_raw; break;
}
load_flags = 79;
case 32769:
load_flags++;
case 32770:
case 32773: goto slr;
case 0: case 1:
#ifdef LIBRAW_LIBRARY_BUILD
if(!strcasecmp(make,"Nikon") && !strncmp(software,"Nikon Scan",10))
{
load_raw = &CLASS nikon_coolscan_load_raw;
raw_color = 1;
filters = 0;
break;
}
#endif
if (!strncmp(make,"OLYMPUS",7) &&
tiff_ifd[raw].bytes*2 == raw_width*raw_height*3)
load_flags = 24;
if (tiff_ifd[raw].bytes*5 == raw_width*raw_height*8) {
load_flags = 81;
tiff_bps = 12;
} slr:
switch (tiff_bps) {
case 8: load_raw = &CLASS eight_bit_load_raw; break;
case 12: if (tiff_ifd[raw].phint == 2)
load_flags = 6;
load_raw = &CLASS packed_load_raw; break;
case 14: load_flags = 0;
case 16: load_raw = &CLASS unpacked_load_raw;
if (!strncmp(make,"OLYMPUS",7) &&
tiff_ifd[raw].bytes*7 > raw_width*raw_height)
load_raw = &CLASS olympus_load_raw;
}
break;
case 6: case 7: case 99:
load_raw = &CLASS lossless_jpeg_load_raw; break;
case 262:
load_raw = &CLASS kodak_262_load_raw; break;
case 34713:
if ((raw_width+9)/10*16*raw_height == tiff_ifd[raw].bytes) {
load_raw = &CLASS packed_load_raw;
load_flags = 1;
} else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes*2) {
load_raw = &CLASS packed_load_raw;
if (model[0] == 'N') load_flags = 80;
} else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes) {
load_raw = &CLASS nikon_yuv_load_raw;
gamma_curve (1/2.4, 12.92, 1, 4095);
memset (cblack, 0, sizeof cblack);
filters = 0;
} else if (raw_width*raw_height*2 == tiff_ifd[raw].bytes) {
load_raw = &CLASS unpacked_load_raw;
load_flags = 4;
order = 0x4d4d;
} else
#ifdef LIBRAW_LIBRARY_BUILD
if(raw_width*raw_height*3 == tiff_ifd[raw].bytes*2)
{
load_raw = &CLASS packed_load_raw;
load_flags=80;
}
else
#endif
load_raw = &CLASS nikon_load_raw; break;
case 65535:
load_raw = &CLASS pentax_load_raw; break;
case 65000:
switch (tiff_ifd[raw].phint) {
case 2: load_raw = &CLASS kodak_rgb_load_raw; filters = 0; break;
case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0; break;
case 32803: load_raw = &CLASS kodak_65000_load_raw;
}
case 32867: case 34892: break;
default: is_raw = 0;
}
if (!dng_version)
if ( ((tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 &&
(tiff_compress & -16) != 32768)
|| (tiff_bps == 8 && !strcasestr(make,"Kodak") &&
!strstr(model2,"DEBUG RAW")))
&& strncmp(software,"Nikon Scan",10))
is_raw = 0;
for (i=0; i < tiff_nifds; i++)
if (i != raw && tiff_ifd[i].samples == max_samp &&
tiff_ifd[i].bps>0 && tiff_ifd[i].bps < 33 &&
unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 &&
tiff_ifd[i].t_width * tiff_ifd[i].t_height / (SQR(tiff_ifd[i].bps)+1) >
thumb_width * thumb_height / (SQR(thumb_misc)+1)
&& tiff_ifd[i].comp != 34892) {
thumb_width = tiff_ifd[i].t_width;
thumb_height = tiff_ifd[i].t_height;
thumb_offset = tiff_ifd[i].offset;
thumb_length = tiff_ifd[i].bytes;
thumb_misc = tiff_ifd[i].bps;
thm = i;
}
if (thm >= 0) {
thumb_misc |= tiff_ifd[thm].samples << 5;
switch (tiff_ifd[thm].comp) {
case 0:
write_thumb = &CLASS layer_thumb;
break;
case 1:
if (tiff_ifd[thm].bps <= 8)
write_thumb = &CLASS ppm_thumb;
else if (!strcmp(make,"Imacon"))
write_thumb = &CLASS ppm16_thumb;
else
thumb_load_raw = &CLASS kodak_thumb_load_raw;
break;
case 65000:
thumb_load_raw = tiff_ifd[thm].phint == 6 ?
&CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw;
}
}
}
void CLASS parse_minolta (int base)
{
int save, tag, len, offset, high=0, wide=0, i, c;
short sorder=order;
fseek (ifp, base, SEEK_SET);
if (fgetc(ifp) || fgetc(ifp)-'M' || fgetc(ifp)-'R') return;
order = fgetc(ifp) * 0x101;
offset = base + get4() + 8;
while ((save=ftell(ifp)) < offset) {
for (tag=i=0; i < 4; i++)
tag = tag << 8 | fgetc(ifp);
len = get4();
switch (tag) {
case 0x505244: /* PRD */
fseek (ifp, 8, SEEK_CUR);
high = get2();
wide = get2();
break;
case 0x574247: /* WBG */
get4();
i = strcmp(model,"DiMAGE A200") ? 0:3;
FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2();
break;
case 0x545457: /* TTW */
parse_tiff (ftell(ifp));
data_offset = offset;
}
fseek (ifp, save+len+8, SEEK_SET);
}
raw_height = high;
raw_width = wide;
order = sorder;
}
/*
Many cameras have a "debug mode" that writes JPEG and raw
at the same time. The raw file has no header, so try to
to open the matching JPEG file and read its metadata.
*/
void CLASS parse_external_jpeg()
{
const char *file, *ext;
char *jname, *jfile, *jext;
#ifndef LIBRAW_LIBRARY_BUILD
FILE *save=ifp;
#else
#if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310)
if(ifp->wfname())
{
std::wstring rawfile(ifp->wfname());
rawfile.replace(rawfile.length()-3,3,L"JPG");
if(!ifp->subfile_open(rawfile.c_str()))
{
parse_tiff (12);
thumb_offset = 0;
is_raw = 1;
ifp->subfile_close();
}
else
imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ;
return;
}
#endif
if(!ifp->fname())
{
imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ;
return;
}
#endif
ext = strrchr (ifname, '.');
file = strrchr (ifname, '/');
if (!file) file = strrchr (ifname, '\\');
#ifndef LIBRAW_LIBRARY_BUILD
if (!file) file = ifname-1;
#else
if (!file) file = (char*)ifname-1;
#endif
file++;
if (!ext || strlen(ext) != 4 || ext-file != 8) return;
jname = (char *) malloc (strlen(ifname) + 1);
merror (jname, "parse_external_jpeg()");
strcpy (jname, ifname);
jfile = file - ifname + jname;
jext = ext - ifname + jname;
if (strcasecmp (ext, ".jpg")) {
strcpy (jext, isupper(ext[1]) ? ".JPG":".jpg");
if (isdigit(*file)) {
memcpy (jfile, file+4, 4);
memcpy (jfile+4, file, 4);
}
} else
while (isdigit(*--jext)) {
if (*jext != '9') {
(*jext)++;
break;
}
*jext = '0';
}
#ifndef LIBRAW_LIBRARY_BUILD
if (strcmp (jname, ifname)) {
if ((ifp = fopen (jname, "rb"))) {
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf (stderr,_("Reading metadata from %s ...\n"), jname);
#endif
parse_tiff (12);
thumb_offset = 0;
is_raw = 1;
fclose (ifp);
}
}
#else
if (strcmp (jname, ifname))
{
if(!ifp->subfile_open(jname))
{
parse_tiff (12);
thumb_offset = 0;
is_raw = 1;
ifp->subfile_close();
}
else
imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ;
}
#endif
if (!timestamp)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ;
#endif
#ifdef DCRAW_VERBOSE
fprintf (stderr,_("Failed to read metadata from %s\n"), jname);
#endif
}
free (jname);
#ifndef LIBRAW_LIBRARY_BUILD
ifp = save;
#endif
}
/*
CIFF block 0x1030 contains an 8x8 white sample.
Load this into white[][] for use in scale_colors().
*/
void CLASS ciff_block_1030()
{
static const ushort key[] = { 0x410, 0x45f3 };
int i, bpp, row, col, vbits=0;
unsigned long bitbuf=0;
if ((get2(),get4()) != 0x80008 || !get4()) return;
bpp = get2();
if (bpp != 10 && bpp != 12) return;
for (i=row=0; row < 8; row++)
for (col=0; col < 8; col++) {
if (vbits < bpp) {
bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]);
vbits += 16;
}
white[row][col] =
bitbuf << (LONG_BIT - vbits) >> (LONG_BIT - bpp);
vbits -= bpp;
}
}
/*
Parse a CIFF file, better known as Canon CRW format.
*/
void CLASS parse_ciff (int offset, int length, int depth)
{
int tboff, nrecs, c, type, len, save, wbi=-1;
ushort key[] = { 0x410, 0x45f3 };
fseek (ifp, offset+length-4, SEEK_SET);
tboff = get4() + offset;
fseek (ifp, tboff, SEEK_SET);
nrecs = get2();
if ((nrecs | depth) > 127) return;
while (nrecs--) {
type = get2();
len = get4();
// printf ("\n*** type: 0x%04x len: 0x%04x", type, len);
save = ftell(ifp) + 4;
fseek (ifp, offset+get4(), SEEK_SET);
if ((((type >> 8) + 8) | 8) == 0x38) {
parse_ciff (ftell(ifp), len, depth+1); /* Parse a sub-table */
}
if (type == 0x0810)
fread (artist, 64, 1, ifp);
if (type == 0x080a) {
fread (make, 64, 1, ifp);
fseek (ifp, strlen(make) - 63, SEEK_CUR);
fread (model, 64, 1, ifp);
}
if (type == 0x1810) {
width = get4();
height = get4();
pixel_aspect = int_to_float(get4());
flip = get4();
}
if (type == 0x1835) /* Get the decoder table */
tiff_compress = get4();
if (type == 0x2007) {
thumb_offset = ftell(ifp);
thumb_length = len;
}
if (type == 0x1818) {
shutter = powf64(2.0f, -int_to_float((get4(),get4())));
aperture = powf64(2.0f, int_to_float(get4())/2);
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CurAp = aperture;
#endif
}
if (type == 0x102a) {
// iso_speed = pow (2.0, (get4(),get2())/32.0 - 4) * 50;
iso_speed = powf64(2.0f, ((get2(),get2()) + get2())/32.0f - 5.0f) * 100.0f;
#ifdef LIBRAW_LIBRARY_BUILD
aperture = _CanonConvertAperture((get2(),get2()));
imgdata.lens.makernotes.CurAp = aperture;
#else
aperture = powf64(2.0, (get2(),(short)get2())/64.0);
#endif
shutter = powf64(2.0,-((short)get2())/32.0);
wbi = (get2(),get2());
if (wbi > 17) wbi = 0;
fseek (ifp, 32, SEEK_CUR);
if (shutter > 1e6) shutter = get2()/10.0;
}
if (type == 0x102c) {
if (get2() > 512) { /* Pro90, G1 */
fseek (ifp, 118, SEEK_CUR);
FORC4 cam_mul[c ^ 2] = get2();
} else { /* G2, S30, S40 */
fseek (ifp, 98, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2();
}
}
#ifdef LIBRAW_LIBRARY_BUILD
if (type == 0x102d) {
fseek(ifp, 44, SEEK_CUR);
imgdata.lens.makernotes.LensID = get2();
imgdata.lens.makernotes.MaxFocal = get2();
imgdata.lens.makernotes.MinFocal = get2();
imgdata.lens.makernotes.CanonFocalUnits = get2();
if (imgdata.lens.makernotes.CanonFocalUnits != 1)
{
imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2());
imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2());
}
#endif
if (type == 0x0032) {
if (len == 768) { /* EOS D30 */
fseek (ifp, 72, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = 1024.0 / get2();
if (!wbi) cam_mul[0] = -1; /* use my auto white balance */
} else if (!cam_mul[0]) {
if (get2() == key[0]) /* Pro1, G6, S60, S70 */
c = (strstr(model,"Pro1") ?
"012346000000000000":"01345:000000006008")[wbi]-'0'+ 2;
else { /* G3, G5, S45, S50 */
c = "023457000000006000"[wbi]-'0';
key[0] = key[1] = 0;
}
fseek (ifp, 78 + c*8, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1];
if (!wbi) cam_mul[0] = -1;
}
}
if (type == 0x10a9) { /* D60, 10D, 300D, and clones */
if (len > 66) wbi = "0134567028"[wbi]-'0';
fseek (ifp, 2 + wbi*8, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
}
if (type == 0x1030 && (0x18040 >> wbi & 1))
ciff_block_1030(); /* all that don't have 0x10a9 */
if (type == 0x1031) {
raw_width = (get2(),get2());
raw_height = get2();
}
if (type == 0x501c) {
iso_speed = len & 0xffff;
}
if (type == 0x5029) {
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CurFocal = len >> 16;
imgdata.lens.makernotes.FocalType = len & 0xffff;
if (imgdata.lens.makernotes.FocalType == 2) {
imgdata.lens.makernotes.CanonFocalUnits = 32;
imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
focal_len = imgdata.lens.makernotes.CurFocal;
#else
focal_len = len >> 16;
if ((len & 0xffff) == 2) focal_len /= 32;
#endif
}
if (type == 0x5813) flash_used = int_to_float(len);
if (type == 0x5814) canon_ev = int_to_float(len);
if (type == 0x5817) shot_order = len;
if (type == 0x5834)
{
unique_id = len;
#ifdef LIBRAW_LIBRARY_BUILD
setCanonBodyFeatures(unique_id);
#endif
}
if (type == 0x580e) timestamp = len;
if (type == 0x180e) timestamp = get4();
#ifdef LOCALTIME
if ((type | 0x4000) == 0x580e)
timestamp = mktime (gmtime (×tamp));
#endif
fseek (ifp, save, SEEK_SET);
}
}
void CLASS parse_rollei()
{
char line[128], *val;
struct tm t;
fseek (ifp, 0, SEEK_SET);
memset (&t, 0, sizeof t);
do {
fgets (line, 128, ifp);
if ((val = strchr(line,'=')))
*val++ = 0;
else
val = line + strlen(line);
if (!strcmp(line,"DAT"))
sscanf (val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year);
if (!strcmp(line,"TIM"))
sscanf (val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec);
if (!strcmp(line,"HDR"))
thumb_offset = atoi(val);
if (!strcmp(line,"X "))
raw_width = atoi(val);
if (!strcmp(line,"Y "))
raw_height = atoi(val);
if (!strcmp(line,"TX "))
thumb_width = atoi(val);
if (!strcmp(line,"TY "))
thumb_height = atoi(val);
} while (strncmp(line,"EOHD",4));
data_offset = thumb_offset + thumb_width * thumb_height * 2;
t.tm_year -= 1900;
t.tm_mon -= 1;
if (mktime(&t) > 0)
timestamp = mktime(&t);
strcpy (make, "Rollei");
strcpy (model,"d530flex");
write_thumb = &CLASS rollei_thumb;
}
void CLASS parse_sinar_ia()
{
int entries, off;
char str[8], *cp;
order = 0x4949;
fseek (ifp, 4, SEEK_SET);
entries = get4();
fseek (ifp, get4(), SEEK_SET);
while (entries--) {
off = get4(); get4();
fread (str, 8, 1, ifp);
if (!strcmp(str,"META")) meta_offset = off;
if (!strcmp(str,"THUMB")) thumb_offset = off;
if (!strcmp(str,"RAW0")) data_offset = off;
}
fseek (ifp, meta_offset+20, SEEK_SET);
fread (make, 64, 1, ifp);
make[63] = 0;
if ((cp = strchr(make,' '))) {
strcpy (model, cp+1);
*cp = 0;
}
raw_width = get2();
raw_height = get2();
load_raw = &CLASS unpacked_load_raw;
thumb_width = (get4(),get2());
thumb_height = get2();
write_thumb = &CLASS ppm_thumb;
maximum = 0x3fff;
}
void CLASS parse_phase_one (int base)
{
unsigned entries, tag, type, len, data, save, i, c;
float romm_cam[3][3];
char *cp;
#ifdef LIBRAW_LIBRARY_BUILD
char body_id[3];
body_id[0] = 0;
#endif
memset (&ph1, 0, sizeof ph1);
fseek (ifp, base, SEEK_SET);
order = get4() & 0xffff;
if (get4() >> 8 != 0x526177) return; /* "Raw" */
fseek (ifp, get4()+base, SEEK_SET);
entries = get4();
get4();
while (entries--) {
tag = get4();
type = get4();
len = get4();
data = get4();
save = ftell(ifp);
fseek (ifp, base+data, SEEK_SET);
switch (tag) {
#ifdef LIBRAW_LIBRARY_BUILD
case 0x0102:
fread(body_id, 1, 3, ifp);
if ((body_id[0] == 0x4c) && (body_id[1] == 0x49)) {
body_id[1] = body_id[2];
}
unique_id = (((body_id[0] & 0x3f) << 5) | (body_id[1] & 0x3f)) - 0x41;
setPhaseOneFeatures(unique_id);
break;
case 0x0401:
if (type == 4) imgdata.lens.makernotes.CurAp = powf64(2.0f, (int_to_float(data)/2.0f));
else imgdata.lens.makernotes.CurAp = powf64(2.0f, (getreal(type)/2.0f));
break;
case 0x0403:
if (type == 4) imgdata.lens.makernotes.CurFocal = int_to_float(data);
else imgdata.lens.makernotes.CurFocal = getreal(type);
break;
case 0x0410:
fread(imgdata.lens.makernotes.body, 1, len, ifp);
break;
case 0x0412:
fread(imgdata.lens.makernotes.Lens, 1, len, ifp);
break;
case 0x0414:
if (type == 4) {
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (int_to_float(data)/2.0f));
} else {
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f));
}
break;
case 0x0415:
if (type == 4) {
imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (int_to_float(data)/2.0f));
} else {
imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f));
}
break;
case 0x0416:
if (type == 4) {
imgdata.lens.makernotes.MinFocal = int_to_float(data);
} else {
imgdata.lens.makernotes.MinFocal = getreal(type);
}
if (imgdata.lens.makernotes.MinFocal > 1000.0f)
{
imgdata.lens.makernotes.MinFocal = 0.0f;
}
break;
case 0x0417:
if (type == 4) {
imgdata.lens.makernotes.MaxFocal = int_to_float(data);
} else {
imgdata.lens.makernotes.MaxFocal = getreal(type);
}
break;
#endif
case 0x100: flip = "0653"[data & 3]-'0'; break;
case 0x106:
for (i=0; i < 9; i++)
romm_cam[0][i] = getreal(11);
romm_coeff (romm_cam);
break;
case 0x107:
FORC3 cam_mul[c] = getreal(11);
break;
case 0x108: raw_width = data; break;
case 0x109: raw_height = data; break;
case 0x10a: left_margin = data; break;
case 0x10b: top_margin = data; break;
case 0x10c: width = data; break;
case 0x10d: height = data; break;
case 0x10e: ph1.format = data; break;
case 0x10f: data_offset = data+base; break;
case 0x110: meta_offset = data+base;
meta_length = len; break;
case 0x112: ph1.key_off = save - 4; break;
case 0x210: ph1.tag_210 = int_to_float(data); break;
case 0x21a: ph1.tag_21a = data; break;
case 0x21c: strip_offset = data+base; break;
case 0x21d: ph1.t_black = data; break;
case 0x222: ph1.split_col = data; break;
case 0x223: ph1.black_col = data+base; break;
case 0x224: ph1.split_row = data; break;
case 0x225: ph1.black_row = data+base; break;
case 0x301:
model[63] = 0;
fread (model, 1, 63, ifp);
if ((cp = strstr(model," camera"))) *cp = 0;
}
fseek (ifp, save, SEEK_SET);
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!imgdata.lens.makernotes.body[0] && !body_id[0]) {
fseek (ifp, meta_offset, SEEK_SET);
order = get2();
fseek (ifp, 6, SEEK_CUR);
fseek (ifp, meta_offset+get4(), SEEK_SET);
entries = get4(); get4();
while (entries--) {
tag = get4();
len = get4();
data = get4();
save = ftell(ifp);
fseek (ifp, meta_offset+data, SEEK_SET);
if (tag == 0x0407) {
fread(body_id, 1, 3, ifp);
if ((body_id[0] == 0x4c) && (body_id[1] == 0x49)) {
body_id[1] = body_id[2];
}
unique_id = (((body_id[0] & 0x3f) << 5) | (body_id[1] & 0x3f)) - 0x41;
setPhaseOneFeatures(unique_id);
}
fseek (ifp, save, SEEK_SET);
}
}
#endif
load_raw = ph1.format < 3 ?
&CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c;
maximum = 0xffff;
strcpy (make, "Phase One");
if (model[0]) return;
switch (raw_height) {
case 2060: strcpy (model,"LightPhase"); break;
case 2682: strcpy (model,"H 10"); break;
case 4128: strcpy (model,"H 20"); break;
case 5488: strcpy (model,"H 25"); break;
}
}
void CLASS parse_fuji (int offset)
{
unsigned entries, tag, len, save, c;
fseek (ifp, offset, SEEK_SET);
entries = get4();
if (entries > 255) return;
while (entries--) {
tag = get2();
len = get2();
save = ftell(ifp);
if (tag == 0x100) {
raw_height = get2();
raw_width = get2();
} else if (tag == 0x121) {
height = get2();
if ((width = get2()) == 4284) width += 3;
} else if (tag == 0x130) {
fuji_layout = fgetc(ifp) >> 7;
fuji_width = !(fgetc(ifp) & 8);
} else if (tag == 0x131) {
filters = 9;
FORC(36) xtrans_abs[0][35-c] = fgetc(ifp) & 3;
} else if (tag == 0x2ff0) {
FORC4 cam_mul[c ^ 1] = get2();
} else if (tag == 0xc000) {
c = order;
order = 0x4949;
if ((tag = get4()) > 10000) tag = get4();
width = tag;
height = get4();
order = c;
}
fseek (ifp, save+len, SEEK_SET);
}
height <<= fuji_layout;
width >>= fuji_layout;
}
int CLASS parse_jpeg (int offset)
{
int len, save, hlen, mark;
fseek (ifp, offset, SEEK_SET);
if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0;
while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) {
order = 0x4d4d;
len = get2() - 2;
save = ftell(ifp);
if (mark == 0xc0 || mark == 0xc3) {
fgetc(ifp);
raw_height = get2();
raw_width = get2();
}
order = get2();
hlen = get4();
if (get4() == 0x48454150) /* "HEAP" */
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
#endif
parse_ciff (save+hlen, len-hlen, 0);
}
if (parse_tiff (save+6)) apply_tiff();
fseek (ifp, save+len, SEEK_SET);
}
return 1;
}
void CLASS parse_riff()
{
unsigned i, size, end;
char tag[4], date[64], month[64];
static const char mon[12][4] =
{ "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" };
struct tm t;
order = 0x4949;
fread (tag, 4, 1, ifp);
size = get4();
end = ftell(ifp) + size;
if (!memcmp(tag,"RIFF",4) || !memcmp(tag,"LIST",4)) {
int maxloop = 1000;
get4();
while (ftell(ifp)+7 < end && !feof(ifp) && maxloop--)
parse_riff();
} else if (!memcmp(tag,"nctg",4)) {
while (ftell(ifp)+7 < end) {
i = get2();
size = get2();
if ((i+1) >> 1 == 10 && size == 20)
get_timestamp(0);
else fseek (ifp, size, SEEK_CUR);
}
} else if (!memcmp(tag,"IDIT",4) && size < 64) {
fread (date, 64, 1, ifp);
date[size] = 0;
memset (&t, 0, sizeof t);
if (sscanf (date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday,
&t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) {
for (i=0; i < 12 && strcasecmp(mon[i],month); i++);
t.tm_mon = i;
t.tm_year -= 1900;
if (mktime(&t) > 0)
timestamp = mktime(&t);
}
} else
fseek (ifp, size, SEEK_CUR);
}
void CLASS parse_qt (int end)
{
unsigned save, size;
char tag[4];
order = 0x4d4d;
while (ftell(ifp)+7 < end) {
save = ftell(ifp);
if ((size = get4()) < 8) return;
fread (tag, 4, 1, ifp);
if (!memcmp(tag,"moov",4) ||
!memcmp(tag,"udta",4) ||
!memcmp(tag,"CNTH",4))
parse_qt (save+size);
if (!memcmp(tag,"CNDA",4))
parse_jpeg (ftell(ifp));
fseek (ifp, save+size, SEEK_SET);
}
}
void CLASS parse_smal (int offset, int fsize)
{
int ver;
fseek (ifp, offset+2, SEEK_SET);
order = 0x4949;
ver = fgetc(ifp);
if (ver == 6)
fseek (ifp, 5, SEEK_CUR);
if (get4() != fsize) return;
if (ver > 6) data_offset = get4();
raw_height = height = get2();
raw_width = width = get2();
strcpy (make, "SMaL");
sprintf (model, "v%d %dx%d", ver, width, height);
if (ver == 6) load_raw = &CLASS smal_v6_load_raw;
if (ver == 9) load_raw = &CLASS smal_v9_load_raw;
}
void CLASS parse_cine()
{
unsigned off_head, off_setup, off_image, i;
order = 0x4949;
fseek (ifp, 4, SEEK_SET);
is_raw = get2() == 2;
fseek (ifp, 14, SEEK_CUR);
is_raw *= get4();
off_head = get4();
off_setup = get4();
off_image = get4();
timestamp = get4();
if ((i = get4())) timestamp = i;
fseek (ifp, off_head+4, SEEK_SET);
raw_width = get4();
raw_height = get4();
switch (get2(),get2()) {
case 8: load_raw = &CLASS eight_bit_load_raw; break;
case 16: load_raw = &CLASS unpacked_load_raw;
}
fseek (ifp, off_setup+792, SEEK_SET);
strcpy (make, "CINE");
sprintf (model, "%d", get4());
fseek (ifp, 12, SEEK_CUR);
switch ((i=get4()) & 0xffffff) {
case 3: filters = 0x94949494; break;
case 4: filters = 0x49494949; break;
default: is_raw = 0;
}
fseek (ifp, 72, SEEK_CUR);
switch ((get4()+3600) % 360) {
case 270: flip = 4; break;
case 180: flip = 1; break;
case 90: flip = 7; break;
case 0: flip = 2;
}
cam_mul[0] = getreal(11);
cam_mul[2] = getreal(11);
maximum = ~((~0u) << get4());
fseek (ifp, 668, SEEK_CUR);
shutter = get4()/1000000000.0;
fseek (ifp, off_image, SEEK_SET);
if (shot_select < is_raw)
fseek (ifp, shot_select*8, SEEK_CUR);
data_offset = (INT64) get4() + 8;
data_offset += (INT64) get4() << 32;
}
void CLASS parse_redcine()
{
unsigned i, len, rdvo;
order = 0x4d4d;
is_raw = 0;
fseek (ifp, 52, SEEK_SET);
width = get4();
height = get4();
fseek (ifp, 0, SEEK_END);
fseek (ifp, -(i = ftello(ifp) & 511), SEEK_CUR);
if (get4() != i || get4() != 0x52454f42) {
#ifdef DCRAW_VERBOSE
fprintf (stderr,_("%s: Tail is missing, parsing from head...\n"), ifname);
#endif
fseek (ifp, 0, SEEK_SET);
while ((len = get4()) != EOF) {
if (get4() == 0x52454456)
if (is_raw++ == shot_select)
data_offset = ftello(ifp) - 8;
fseek (ifp, len-8, SEEK_CUR);
}
} else {
rdvo = get4();
fseek (ifp, 12, SEEK_CUR);
is_raw = get4();
fseeko (ifp, rdvo+8 + shot_select*4, SEEK_SET);
data_offset = get4();
}
}
//@end COMMON
char * CLASS foveon_gets (int offset, char *str, int len)
{
int i;
fseek (ifp, offset, SEEK_SET);
for (i=0; i < len-1; i++)
if ((str[i] = get2()) == 0) break;
str[i] = 0;
return str;
}
void CLASS parse_foveon()
{
int entries, img=0, off, len, tag, save, i, wide, high, pent, poff[256][2];
char name[64], value[64];
order = 0x4949; /* Little-endian */
fseek (ifp, 36, SEEK_SET);
flip = get4();
fseek (ifp, -4, SEEK_END);
fseek (ifp, get4(), SEEK_SET);
if (get4() != 0x64434553) return; /* SECd */
entries = (get4(),get4());
while (entries--) {
off = get4();
len = get4();
tag = get4();
save = ftell(ifp);
fseek (ifp, off, SEEK_SET);
if (get4() != (0x20434553 | (tag << 24))) return;
switch (tag) {
case 0x47414d49: /* IMAG */
case 0x32414d49: /* IMA2 */
fseek (ifp, 8, SEEK_CUR);
pent = get4();
wide = get4();
high = get4();
if (wide > raw_width && high > raw_height) {
switch (pent) {
case 5: load_flags = 1;
case 6: load_raw = &CLASS foveon_sd_load_raw; break;
case 30: load_raw = &CLASS foveon_dp_load_raw; break;
default: load_raw = 0;
}
raw_width = wide;
raw_height = high;
data_offset = off+28;
is_foveon = 1;
}
fseek (ifp, off+28, SEEK_SET);
if (fgetc(ifp) == 0xff && fgetc(ifp) == 0xd8
&& thumb_length < len-28) {
thumb_offset = off+28;
thumb_length = len-28;
write_thumb = &CLASS jpeg_thumb;
}
if (++img == 2 && !thumb_length) {
thumb_offset = off+24;
thumb_width = wide;
thumb_height = high;
write_thumb = &CLASS foveon_thumb;
}
break;
case 0x464d4143: /* CAMF */
meta_offset = off+8;
meta_length = len-28;
break;
case 0x504f5250: /* PROP */
pent = (get4(),get4());
fseek (ifp, 12, SEEK_CUR);
off += pent*8 + 24;
if ((unsigned) pent > 256) pent=256;
for (i=0; i < pent*2; i++)
poff[0][i] = off + get4()*2;
for (i=0; i < pent; i++) {
foveon_gets (poff[i][0], name, 64);
foveon_gets (poff[i][1], value, 64);
if (!strcmp (name, "ISO"))
iso_speed = atoi(value);
if (!strcmp (name, "CAMMANUF"))
strcpy (make, value);
if (!strcmp (name, "CAMMODEL"))
strcpy (model, value);
if (!strcmp (name, "WB_DESC"))
strcpy (model2, value);
if (!strcmp (name, "TIME"))
timestamp = atoi(value);
if (!strcmp (name, "EXPTIME"))
shutter = atoi(value) / 1000000.0;
if (!strcmp (name, "APERTURE"))
aperture = atof(value);
if (!strcmp (name, "FLENGTH"))
focal_len = atof(value);
#ifdef LIBRAW_LIBRARY_BUILD
if (!strcmp (name, "FLEQ35MM"))
imgdata.lens.makernotes.FocalLengthIn35mmFormat = atof(value);
if (!strcmp (name, "LENSARANGE"))
{
char *sp;
imgdata.lens.makernotes.MaxAp4CurFocal = imgdata.lens.makernotes.MinAp4CurFocal = atof(value);
sp = strrchr (value, ' ');
if (sp)
{
imgdata.lens.makernotes.MinAp4CurFocal = atof(sp);
if (imgdata.lens.makernotes.MaxAp4CurFocal > imgdata.lens.makernotes.MinAp4CurFocal)
my_swap (float, imgdata.lens.makernotes.MaxAp4CurFocal, imgdata.lens.makernotes.MinAp4CurFocal);
}
}
if (!strcmp (name, "LENSFRANGE"))
{
char *sp;
imgdata.lens.makernotes.MinFocal = imgdata.lens.makernotes.MaxFocal = atof(value);
sp = strrchr (value, ' ');
if (sp)
{
imgdata.lens.makernotes.MaxFocal = atof(sp);
if ((imgdata.lens.makernotes.MaxFocal + 0.17f) < imgdata.lens.makernotes.MinFocal)
my_swap (float, imgdata.lens.makernotes.MaxFocal, imgdata.lens.makernotes.MinFocal);
}
}
if (!strcmp (name, "LENSMODEL"))
{
imgdata.lens.makernotes.LensID = atoi(value);
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = Sigma_X3F;
}
}
#endif
}
#ifdef LOCALTIME
timestamp = mktime (gmtime (×tamp));
#endif
}
fseek (ifp, save, SEEK_SET);
}
}
//@out COMMON
/*
All matrices are from Adobe DNG Converter unless otherwise noted.
*/
void CLASS adobe_coeff (const char *t_make, const char *t_model
#ifdef LIBRAW_LIBRARY_BUILD
,int internal_only
#endif
)
{
static const struct {
const char *prefix;
int t_black, t_maximum, trans[12];
} table[] = {
{ "AgfaPhoto DC-833m", 0, 0, /* DJC */
{ 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } },
{ "Apple QuickTake", 0, 0, /* DJC */
{ 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } },
{ "Canon EOS D2000", 0, 0,
{ 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } },
{ "Canon EOS D6000", 0, 0,
{ 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } },
{ "Canon EOS D30", 0, 0,
{ 9805,-2689,-1312,-5803,13064,3068,-2438,3075,8775 } },
{ "Canon EOS D60", 0, 0xfa0,
{ 6188,-1341,-890,-7168,14489,2937,-2640,3228,8483 } },
{ "Canon EOS 5D Mark III", 0, 0x3c80,
{ 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } },
{ "Canon EOS 5D Mark II", 0, 0x3cf0,
{ 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } },
{ "Canon EOS 5D", 0, 0xe6c,
{ 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } },
{ "Canon EOS 6D", 0, 0x3c82,
{ 8621,-2197,-787,-3150,11358,912,-1161,2400,4836 } },
{ "Canon EOS 7D Mark II", 0, 0x3510,
{ 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } },
{ "Canon EOS 7D", 0, 0x3510,
{ 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } },
{ "Canon EOS 10D", 0, 0xfa0,
{ 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } },
{ "Canon EOS 20Da", 0, 0,
{ 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } },
{ "Canon EOS 20D", 0, 0xfff,
{ 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } },
{ "Canon EOS 30D", 0, 0,
{ 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } },
{ "Canon EOS 40D", 0, 0x3f60,
{ 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } },
{ "Canon EOS 50D", 0, 0x3d93,
{ 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } },
{ "Canon EOS 60D", 0, 0x2ff7,
{ 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } },
{ "Canon EOS 70D", 0, 0x3bc7,
{ 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } },
{ "Canon EOS 100D", 0, 0x350f,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 300D", 0, 0xfa0,
{ 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } },
{ "Canon EOS 350D", 0, 0xfff,
{ 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } },
{ "Canon EOS 400D", 0, 0xe8e,
{ 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } },
{ "Canon EOS 450D", 0, 0x390d,
{ 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } },
{ "Canon EOS 500D", 0, 0x3479,
{ 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } },
{ "Canon EOS 550D", 0, 0x3dd7,
{ 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } },
{ "Canon EOS 600D", 0, 0x3510,
{ 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } },
{ "Canon EOS 650D", 0, 0x354d,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 700D", 0, 0x3c00,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 1000D", 0, 0xe43,
{ 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } },
{ "Canon EOS 1100D", 0, 0x3510,
{ 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } },
{ "Canon EOS 1200D", 0, 0x37c2,
{ 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } },
{ "Canon EOS M", 0, 0,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS-1Ds Mark III", 0, 0x3bb0,
{ 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } },
{ "Canon EOS-1Ds Mark II", 0, 0xe80,
{ 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } },
{ "Canon EOS-1D Mark IV", 0, 0x3bb0,
{ 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } },
{ "Canon EOS-1D Mark III", 0, 0x3bb0,
{ 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } },
{ "Canon EOS-1D Mark II N", 0, 0xe80,
{ 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } },
{ "Canon EOS-1D Mark II", 0, 0xe80,
{ 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } },
{ "Canon EOS-1DS", 0, 0xe20,
{ 4374,3631,-1743,-7520,15212,2472,-2892,3632,8161 } },
{ "Canon EOS-1D C", 0, 0x3c4e,
{ 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } },
{ "Canon EOS-1D X", 0, 0x3c4e,
{ 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } },
{ "Canon EOS-1D", 0, 0xe20,
{ 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } },
{ "Canon EOS C500", 853, 0, /* DJC */
{ 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } },
{ "Canon PowerShot A530", 0, 0,
{ 0 } }, /* don't want the A5 matrix */
{ "Canon PowerShot A50", 0, 0,
{ -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } },
{ "Canon PowerShot A5", 0, 0,
{ -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } },
{ "Canon PowerShot G10", 0, 0,
{ 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } },
{ "Canon PowerShot G11", 0, 0,
{ 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } },
{ "Canon PowerShot G12", 0, 0,
{ 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } },
{ "Canon PowerShot G15", 0, 0,
{ 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } },
{ "Canon PowerShot G16", 0, 0,
{ 14130,-8071,127,2199,6528,1551,3402,-1721,4960 } },
{ "Canon PowerShot G1 X Mark II", 0, 0,
{ 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } },
{ "Canon PowerShot G1 X", 0, 0,
{ 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } },
{ "Canon PowerShot G1", 0, 0,
{ -4778,9467,2172,4743,-1141,4344,-5146,9908,6077,-1566,11051,557 } },
{ "Canon PowerShot G2", 0, 0,
{ 9087,-2693,-1049,-6715,14382,2537,-2291,2819,7790 } },
{ "Canon PowerShot G3", 0, 0,
{ 9212,-2781,-1073,-6573,14189,2605,-2300,2844,7664 } },
{ "Canon PowerShot G5", 0, 0,
{ 9757,-2872,-933,-5972,13861,2301,-1622,2328,7212 } },
{ "Canon PowerShot G6", 0, 0,
{ 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } },
{ "Canon PowerShot G7 X", 0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G9", 0, 0,
{ 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } },
{ "Canon PowerShot Pro1", 0, 0,
{ 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } },
{ "Canon PowerShot Pro70", 34, 0,
{ -4155,9818,1529,3939,-25,4522,-5521,9870,6610,-2238,10873,1342 } },
{ "Canon PowerShot Pro90", 0, 0,
{ -4963,9896,2235,4642,-987,4294,-5162,10011,5859,-1770,11230,577 } },
{ "Canon PowerShot S30", 0, 0,
{ 10566,-3652,-1129,-6552,14662,2006,-2197,2581,7670 } },
{ "Canon PowerShot S40", 0, 0,
{ 8510,-2487,-940,-6869,14231,2900,-2318,2829,9013 } },
{ "Canon PowerShot S45", 0, 0,
{ 8163,-2333,-955,-6682,14174,2751,-2077,2597,8041 } },
{ "Canon PowerShot S50", 0, 0,
{ 8882,-2571,-863,-6348,14234,2288,-1516,2172,6569 } },
{ "Canon PowerShot S60", 0, 0,
{ 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } },
{ "Canon PowerShot S70", 0, 0,
{ 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } },
{ "Canon PowerShot S90", 0, 0,
{ 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } },
{ "Canon PowerShot S95", 0, 0,
{ 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } },
{ "Canon PowerShot S120", 0, 0, /* LibRaw */
{ 10800,-4782,-628,-2057,10783,1176,-802,2091,4739 } },
{ "Canon PowerShot S110", 0, 0,
{ 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } },
{ "Canon PowerShot S100", 0, 0,
{ 7968,-2565,-636,-2873,10697,2513,180,667,4211 } },
{ "Canon PowerShot SX1 IS", 0, 0,
{ 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } },
{ "Canon PowerShot SX50 HS", 0, 0,
{ 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } },
{ "Canon PowerShot SX60 HS", 0, 0,
{ 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } },
{ "Canon PowerShot A3300", 0, 0, /* DJC */
{ 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } },
{ "Canon PowerShot A470", 0, 0, /* DJC */
{ 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } },
{ "Canon PowerShot A610", 0, 0, /* DJC */
{ 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } },
{ "Canon PowerShot A620", 0, 0, /* DJC */
{ 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } },
{ "Canon PowerShot A630", 0, 0, /* DJC */
{ 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } },
{ "Canon PowerShot A640", 0, 0, /* DJC */
{ 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } },
{ "Canon PowerShot A650", 0, 0, /* DJC */
{ 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } },
{ "Canon PowerShot A720", 0, 0, /* DJC */
{ 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } },
{ "Canon PowerShot S3 IS", 0, 0, /* DJC */
{ 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } },
{ "Canon PowerShot SX110 IS", 0, 0, /* DJC */
{ 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } },
{ "Canon PowerShot SX220", 0, 0, /* DJC */
{ 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } },
{ "Casio EX-S20", 0, 0, /* DJC */
{ 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } },
{ "Casio EX-Z750", 0, 0, /* DJC */
{ 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } },
{ "Casio EX-Z10", 128, 0xfff, /* DJC */
{ 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } },
{ "CINE 650", 0, 0,
{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
{ "CINE 660", 0, 0,
{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
{ "CINE", 0, 0,
{ 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } },
{ "Contax N Digital", 0, 0xf1e,
{ 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } },
{ "Epson R-D1", 0, 0,
{ 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } },
{ "Fujifilm E550", 0, 0,
{ 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } },
{ "Fujifilm E900", 0, 0,
{ 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } },
{ "Fujifilm F5", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F6", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F77", 0, 0xfe9,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F7", 0, 0,
{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
{ "Fujifilm F8", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm S100FS", 514, 0,
{ 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } },
{ "Fujifilm S1", 0, 0,
{ 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } },
{ "Fujifilm S20Pro", 0, 0,
{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
{ "Fujifilm S20", 512, 0x3fff,
{ 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } },
{ "Fujifilm S2Pro", 128, 0,
{ 12492,-4690,-1402,-7033,15423,1647,-1507,2111,7697 } },
{ "Fujifilm S3Pro", 0, 0,
{ 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } },
{ "Fujifilm S5Pro", 0, 0,
{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
{ "Fujifilm S5000", 0, 0,
{ 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } },
{ "Fujifilm S5100", 0, 0,
{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
{ "Fujifilm S5500", 0, 0,
{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
{ "Fujifilm S5200", 0, 0,
{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
{ "Fujifilm S5600", 0, 0,
{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
{ "Fujifilm S6", 0, 0,
{ 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } },
{ "Fujifilm S7000", 0, 0,
{ 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } },
{ "Fujifilm S9000", 0, 0,
{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
{ "Fujifilm S9500", 0, 0,
{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
{ "Fujifilm S9100", 0, 0,
{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
{ "Fujifilm S9600", 0, 0,
{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
{ "Fujifilm SL1000", 0, 0,
{ 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } },
{ "Fujifilm IS-1", 0, 0,
{ 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } },
{ "Fujifilm IS Pro", 0, 0,
{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
{ "Fujifilm HS10 HS11", 0, 0xf68,
{ 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } },
{ "Fujifilm HS2", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm HS3", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm HS50EXR", 0, 0,
{ 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } },
{ "Fujifilm F900EXR", 0, 0,
{ 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } },
{ "Fujifilm X100S", 0, 0,
{ 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } },
{ "Fujifilm X100T", 0, 0,
{ 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } },
{ "Fujifilm X100", 0, 0,
{ 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } },
{ "Fujifilm X10", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X20", 0, 0,
{ 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } },
{ "Fujifilm X30", 0, 0,
{ 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } },
{ "Fujifilm X-Pro1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-A1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-E1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-E2", 0, 0,
{ 12066,-5927,-367,-1969,9878,1503,-721,2034,5453 } },
{ "Fujifilm XF1", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X-M1", 0, 0,
{ 13193,-6685,-425,-2229,10458,1534,-878,1763,5217 } },
{ "Fujifilm X-S1", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X-T1", 0, 0, /* LibRaw */
{ 12066,-5927,-367,-1969,9878,1503,-721,2034,5453 } },
{ "Fujifilm XQ1", 0, 0,
{ 14305,-7365,-687,-3117,12383,432,-287,1660,4361 } },
{ "Hasselblad Lunar", -512, 0,
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Hasselblad Stellar", -800, 0,
{ 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } },
{ "Hasselblad CFV", 0, 0, /* Adobe */
{ 8519, -3260, -280, -5081, 13459, 1738, -1449, 2960, 7809, } },
{ "Hasselblad H-16MP", 0, 0, /* LibRaw */
{ 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } },
{ "Hasselblad H-22MP", 0, 0, /* LibRaw */
{ 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } },
{"Hasselblad H-31MP",0, 0, /* LibRaw */
{ 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } },
{"Hasselblad H-39MP",0, 0, /* Adobe */
{3857,452, -46, -6008, 14477, 1596, -2627, 4481, 5718}},
{ "Hasselblad H3D-50", 0, 0, /* Adobe */
{3857,452, -46, -6008, 14477, 1596, -2627, 4481, 5718}},
{"Hasselblad H4D-40",0, 0, /* LibRaw */
{ 6325,-860,-957,-6559,15945,266,167,770,5936 } },
{"Hasselblad H4D-50",0, 0, /* LibRaw */
{ 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } },
{"Hasselblad H4D-60",0, 0, /* Adobe */
{9662, -684, -279, -4903, 12293, 2950, -344, 1669, 6024}},
{"Hasselblad H5D-50c",0, 0, /* Adobe */
{4932, -835, 141, -4878, 11868, 3437, -1138, 1961, 7067}},
{"Hasselblad H5D-50",0, 0, /* Adobe */
{5656, -659, -346, -3923, 12306, 1791, -1602, 3509, 5442}},
{ "Imacon Ixpress", 0, 0, /* DJC */
{ 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } },
{ "Kodak NC2000", 0, 0,
{ 13891,-6055,-803,-465,9919,642,2121,82,1291 } },
{ "Kodak DCS315C", -8, 0,
{ 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } },
{ "Kodak DCS330C", -8, 0,
{ 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } },
{ "Kodak DCS420", 0, 0,
{ 10868,-1852,-644,-1537,11083,484,2343,628,2216 } },
{ "Kodak DCS460", 0, 0,
{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
{ "Kodak EOSDCS1", 0, 0,
{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
{ "Kodak EOSDCS3B", 0, 0,
{ 9898,-2700,-940,-2478,12219,206,1985,634,1031 } },
{ "Kodak DCS520C", -178, 0,
{ 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } },
{ "Kodak DCS560C", -177, 0,
{ 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } },
{ "Kodak DCS620C", -177, 0,
{ 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } },
{ "Kodak DCS620X", -176, 0,
{ 13095,-6231,154,12221,-21,-2137,895,4602,2258 } },
{ "Kodak DCS660C", -173, 0,
{ 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } },
{ "Kodak DCS720X", 0, 0,
{ 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } },
{ "Kodak DCS760C", 0, 0,
{ 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } },
{ "Kodak DCS Pro SLR", 0, 0,
{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
{ "Kodak DCS Pro 14nx", 0, 0,
{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
{ "Kodak DCS Pro 14", 0, 0,
{ 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } },
{ "Kodak ProBack645", 0, 0,
{ 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } },
{ "Kodak ProBack", 0, 0,
{ 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } },
{ "Kodak P712", 0, 0,
{ 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } },
{ "Kodak P850", 0, 0xf7c,
{ 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } },
{ "Kodak P880", 0, 0xfff,
{ 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } },
{ "Kodak EasyShare Z980", 0, 0,
{ 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } },
{ "Kodak EasyShare Z981", 0, 0,
{ 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } },
{ "Kodak EasyShare Z990", 0, 0xfed,
{ 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } },
{ "Kodak EASYSHARE Z1015", 0, 0xef1,
{ 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } },
{ "Leaf CMost", 0, 0,
{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
{ "Leaf Valeo 6", 0, 0,
{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
{ "Leaf Aptus 54S", 0, 0,
{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
{ "Leaf Aptus 65", 0, 0,
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Aptus 75", 0, 0,
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Credo 40", 0, 0,
{ 8035, 435, -962, -6001, 13872, 2320, -1159, 3065, 5434 } },
{ "Leaf Credo 50", 0, 0,
{ 3984, 0, 0, 0, 10000, 0, 0, 0, 7666 } },
{ "Leaf Credo 60", 0, 0,
{ 8035, 435, -962, -6001, 13872,2320,-1159,3065,5434} },
{ "Leaf Credo 80", 0, 0,
{ 6294, 686, -712, -5435, 13417, 2211, -1006, 2435, 5042} },
{ "Leaf", 0, 0,
{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
{ "Mamiya ZD", 0, 0,
{ 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } },
{ "Micron 2010", 110, 0, /* DJC */
{ 16695,-3761,-2151,155,9682,163,3433,951,4904 } },
{ "Minolta DiMAGE 5", 0, 0xf7d,
{ 8983,-2942,-963,-6556,14476,2237,-2426,2887,8014 } },
{ "Minolta DiMAGE 7Hi", 0, 0xf7d,
{ 11368,-3894,-1242,-6521,14358,2339,-2475,3056,7285 } },
{ "Minolta DiMAGE 7", 0, 0xf7d,
{ 9144,-2777,-998,-6676,14556,2281,-2470,3019,7744 } },
{ "Minolta DiMAGE A1", 0, 0xf8b,
{ 9274,-2547,-1167,-8220,16323,1943,-2273,2720,8340 } },
{ "Minolta DiMAGE A200", 0, 0,
{ 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } },
{ "Minolta DiMAGE A2", 0, 0xf8f,
{ 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } },
{ "Minolta DiMAGE Z2", 0, 0, /* DJC */
{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
{ "Minolta DYNAX 5", 0, 0xffb,
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta DYNAX 7", 0, 0xffb,
{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
{ "Motorola PIXL", 0, 0, /* DJC */
{ 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } },
{ "Nikon D100", 0, 0,
{ 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } },
{ "Nikon D1H", 0, 0,
{ 7577,-2166,-926,-7454,15592,1934,-2377,2808,8606 } },
{ "Nikon D1X", 0, 0,
{ 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } },
{ "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */
{ 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } },
{ "Nikon D200", 0, 0xfbc,
{ 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } },
{ "Nikon D2H", 0, 0,
{ 5710,-901,-615,-8594,16617,2024,-2975,4120,6830 } },
{ "Nikon D2X", 0, 0,
{ 10231,-2769,-1255,-8301,15900,2552,-797,680,7148 } },
{ "Nikon D3000", 0, 0,
{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
{ "Nikon D3100", 0, 0,
{ 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } },
{ "Nikon D3200", 0, 0xfb9,
{ 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } },
{ "Nikon D3300", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D300", 0, 0,
{ 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } },
{ "Nikon D3X", 0, 0,
{ 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } },
{ "Nikon D3S", 0, 0,
{ 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } },
{ "Nikon D3", 0, 0,
{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
{ "Nikon D40X", 0, 0,
{ 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } },
{ "Nikon D40", 0, 0,
{ 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } },
{ "Nikon D4S", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon D4", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon Df", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon D5000", 0, 0xf00,
{ 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } },
{ "Nikon D5100", 0, 0x3de6,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon D5200", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D5300", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D5500", 0, 0, /* DJC */
{ 5765,-2176,184,-3736,9072,4664,-1028,2213,9259 } },
{ "Nikon D50", 0, 0,
{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
{ "Nikon D600", 0, 0x3e07,
{ 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } },
{"Nikon D610",0, 0,
{ 10426,-4005,-444,-3565,11764,1403,-1206,2266,6549 } },
{ "Nikon D60", 0, 0,
{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
{ "Nikon D7000", 0, 0,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon D7100", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D750", 0, 0,
{ 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } },
{ "Nikon D700", 0, 0,
{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
{ "Nikon D70", 0, 0,
{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
{ "Nikon D810", 0, 0,
{ 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } },
{ "Nikon D800", 0, 0,
{ 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } },
{ "Nikon D80", 0, 0,
{ 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } },
{ "Nikon D90", 0, 0xf00,
{ 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } },
{ "Nikon E700", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E800", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E950", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E995", 0, 0, /* copied from E5000 */
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E2100", 0, 0, /* copied from Z2, new white balance */
{ 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711} },
{ "Nikon E2500", 0, 0,
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E3200", 0, 0, /* DJC */
{ 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } },
{ "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */
{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
{ "Nikon E4500", 0, 0,
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E5000", 0, 0,
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E5400", 0, 0,
{ 9349,-2987,-1001,-7919,15766,2266,-2098,2680,6839 } },
{ "Nikon E5700", 0, 0,
{ -5368,11478,2368,5537,-113,3148,-4969,10021,5782,778,9028,211 } },
{ "Nikon E8400", 0, 0,
{ 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } },
{ "Nikon E8700", 0, 0,
{ 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
{ "Nikon E8800", 0, 0,
{ 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } },
{ "Nikon COOLPIX A", 0, 0,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon COOLPIX P330", -200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P340", -200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P6000", 0, 0,
{ 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } },
{ "Nikon COOLPIX P7000", 0, 0,
{ 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } },
{ "Nikon COOLPIX P7100", 0, 0,
{ 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } },
{ "Nikon COOLPIX P7700", -3200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P7800", -3200, 0, /* LibRaw */
{ 13443,-6418,-673,-1309,10025,1131,-462,1827,4782 } },
{ "Nikon 1 V3", -200, 0,
{ 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } },
{ "Nikon 1 J4", 0, 0,
{ 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } },
{ "Nikon 1 S2", 200, 0,
{ 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } },
{ "Nikon 1 V2", 0, 0,
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 J3", 0, 0,
{ 8144,-2671,-473,-1740,9834,1601,-58,1971,4296 } },
{ "Nikon 1 AW1", 0, 0,
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */
{ 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } },
{ "Olympus C5050", 0, 0,
{ 10508,-3124,-1273,-6079,14294,1901,-1653,2306,6237 } },
{ "Olympus C5060", 0, 0,
{ 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } },
{ "Olympus C7070", 0, 0,
{ 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } },
{ "Olympus C70", 0, 0,
{ 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } },
{ "Olympus C80", 0, 0,
{ 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } },
{ "Olympus E-10", 0, 0xffc,
{ 12745,-4500,-1416,-6062,14542,1580,-1934,2256,6603 } },
{ "Olympus E-1", 0, 0,
{ 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } },
{ "Olympus E-20", 0, 0xffc,
{ 13173,-4732,-1499,-5807,14036,1895,-2045,2452,7142 } },
{ "Olympus E-300", 0, 0,
{ 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } },
{ "Olympus E-330", 0, 0,
{ 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } },
{ "Olympus E-30", 0, 0xfbc,
{ 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } },
{ "Olympus E-3", 0, 0xf99,
{ 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } },
{ "Olympus E-400", 0, 0,
{ 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } },
{ "Olympus E-410", 0, 0xf6a,
{ 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } },
{ "Olympus E-420", 0, 0xfd7,
{ 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } },
{ "Olympus E-450", 0, 0xfd2,
{ 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } },
{ "Olympus E-500", 0, 0,
{ 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } },
{ "Olympus E-510", 0, 0xf6a,
{ 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } },
{ "Olympus E-520", 0, 0xfd2,
{ 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } },
{ "Olympus E-5", 0, 0xeec,
{ 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } },
{ "Olympus E-600", 0, 0xfaf,
{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
{ "Olympus E-620", 0, 0xfaf,
{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
{ "Olympus E-P1", 0, 0xffd,
{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
{ "Olympus E-P2", 0, 0xffd,
{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
{ "Olympus E-P3", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-P5", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL1s", 0, 0,
{ 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } },
{ "Olympus E-PL1", 0, 0,
{ 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } },
{ "Olympus E-PL2", 0, 0xcf3,
{ 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } },
{ "Olympus E-PL3", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-PL5", 0, 0xfcb,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL6", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL7", 0, 0,
{ 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } },
{ "Olympus E-PM1", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-PM2", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-M10", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-M1", 0, 0,
{ 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } },
{ "Olympus E-M5MarkII", 0, 0, /* DJC */
{ 6617,-2589,139,-2917,8499,4419,-884,1913,6829 } },
{ "Olympus E-M5", 0, 0xfe1,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus SP350", 0, 0,
{ 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } },
{ "Olympus SP3", 0, 0,
{ 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } },
{ "Olympus SP500UZ", 0, 0xfff,
{ 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } },
{ "Olympus SP510UZ", 0, 0xffe,
{ 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } },
{ "Olympus SP550UZ", 0, 0xffe,
{ 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } },
{ "Olympus SP560UZ", 0, 0xff9,
{ 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } },
{ "Olympus SP570UZ", 0, 0,
{ 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } },
{"Olympus STYLUS1",0, 0,
{ 11976,-5518,-545,-1419,10472,846,-475,1766,4524 } },
{ "Olympus XZ-10", 0, 0,
{ 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } },
{ "Olympus XZ-1", 0, 0,
{ 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } },
{ "Olympus XZ-2", 0, 0,
{ 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } },
{ "OmniVision", 0, 0, /* DJC */
{ 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } },
{ "Pentax *ist DL2", 0, 0,
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Pentax *ist DL", 0, 0,
{ 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } },
{ "Pentax *ist DS2", 0, 0,
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Pentax *ist DS", 0, 0,
{ 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } },
{ "Pentax *ist D", 0, 0,
{ 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } },
{ "Pentax K10D", 0, 0,
{ 9566,-2863,-803,-7170,15172,2112,-818,803,9705 } },
{ "Pentax K1", 0, 0,
{ 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } },
{ "Pentax K20D", 0, 0,
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Pentax K200D", 0, 0,
{ 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } },
{ "Pentax K2000", 0, 0,
{ 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } },
{ "Pentax K-m", 0, 0,
{ 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } },
{ "Pentax K-x", 0, 0,
{ 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } },
{ "Pentax K-r", 0, 0,
{ 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } },
{ "Pentax K-3", 0, 0,
{ 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } },
{ "Pentax K-5 II", 0, 0,
{ 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } },
{ "Pentax K-5", 0, 0,
{ 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } },
{ "Pentax K-7", 0, 0,
{ 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } },
{ "Pentax K-S1", 0, 0,
{ 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } },
{ "Pentax MX-1", 0, 0,
{ 8804,-2523,-1238,-2423,11627,860,-682,1774,4753 } },
{ "Pentax Q10", 0, 0,
{ 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } },
{ "Pentax 645D", 0, 0x3e00,
{ 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } },
{ "Panasonic DMC-CM1", -15, 0,
{ 8770, -3194,-820,-2871,11281,1803,-513,1552,4434} },
{ "Panasonic DMC-FZ8", 0, 0xf7f,
{ 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } },
{ "Panasonic DMC-FZ18", 0, 0,
{ 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } },
{ "Panasonic DMC-FZ28", -15, 0xf96,
{ 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } },
{ "Panasonic DMC-FZ30", 0, 0xf94,
{ 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } },
{ "Panasonic DMC-FZ3", -15, 0,
{ 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } },
{ "Panasonic DMC-FZ4", -15, 0,
{ 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } },
{ "Panasonic DMC-FZ50", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Panasonic DMC-FZ7", -15, 0,
{ 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } },
{ "Leica V-LUX1", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Panasonic DMC-L10", -15, 0xf96,
{ 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } },
{ "Panasonic DMC-L1", 0, 0xf7f,
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Leica DIGILUX 3", 0, 0xf7f,
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Panasonic DMC-LC1", 0, 0,
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Leica DIGILUX 2", 0, 0,
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Panasonic DMC-LX100", -15, 0,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Leica D-LUX (Typ 109)", -15, 0,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Panasonic DMC-LF1", -15, 0,
{ 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } },
{ "Leica C (Typ 112)", -15, 0,
{ 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } },
{ "Panasonic DMC-LX1", 0, 0xf7f,
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Leica D-Lux (Typ 109)", 0, 0xf7f, /* LibRaw */
{ 10031,-4555,-456,-3024,11520,1091,-1342,2611,4752 } },
{ "Leica D-LUX2", 0, 0xf7f,
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Panasonic DMC-LX2", 0, 0,
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Leica D-LUX3", 0, 0,
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Panasonic DMC-LX3", -15, 0,
{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
{ "Leica D-LUX 4", -15, 0,
{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
{ "Panasonic DMC-LX5", -15, 0,
{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
{ "Leica D-LUX 5", -15, 0,
{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
{ "Panasonic DMC-LX7", -15, 0,
{ 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } },
{ "Leica D-LUX 6", -15, 0,
{ 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } },
{ "Panasonic DMC-FZ1000", -15, 0,
{ 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } },
{ "Leica V-LUX (Typ 114)", 15, 0,
{ 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } },
{ "Panasonic DMC-FZ100", -15, 0xfff,
{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
{ "Leica V-LUX 2", -15, 0xfff,
{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
{ "Panasonic DMC-FZ150", -15, 0xfff,
{ 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } },
{ "Leica V-LUX 3", -15, 0xfff,
{ 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } },
{ "Panasonic DMC-FZ200", -15, 0xfff,
{ 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } },
{ "Leica V-LUX 4", -15, 0xfff,
{ 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } },
{ "Panasonic DMC-FX150", -15, 0xfff,
{ 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } },
{ "Panasonic DMC-G10", 0, 0,
{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
{ "Panasonic DMC-G1", -15, 0xf94,
{ 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } },
{ "Panasonic DMC-G2", -15, 0xf3c,
{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
{ "Panasonic DMC-G3", -15, 0xfff,
{ 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } },
{ "Panasonic DMC-G5", -15, 0xfff,
{ 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } },
{ "Panasonic DMC-G6", -15, 0xfff,
{ 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } },
{ "Panasonic DMC-GF1", -15, 0xf92,
{ 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } },
{ "Panasonic DMC-GF2", -15, 0xfff,
{ 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } },
{ "Panasonic DMC-GF3", -15, 0xfff,
{ 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } },
{ "Panasonic DMC-GF5", -15, 0xfff,
{ 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } },
{ "Panasonic DMC-GF6", -15, 0,
{ 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } },
{ "Panasonic DMC-GF7", -15, 0, /* DJC */
{ 6086,-2691,-18,-4207,9767,4441,-1486,2640,7441 } },
{ "Panasonic DMC-GH1", -15, 0xf92,
{ 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } },
{ "Panasonic DMC-GH2", -15, 0xf95,
{ 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } },
{ "Panasonic DMC-GH3", -15, 0,
{ 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } },
{ "Panasonic DMC-GH4", -15, 0,
{ 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } },
{ "Panasonic DMC-GM1", -15, 0,
{ 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 } },
{ "Panasonic DMC-GM5", -15, 0,
{ 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 } },
{ "Panasonic DMC-GX1", -15, 0,
{ 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } },
{"Panasonic DMC-GX7", -15,0, /* LibRaw */
{7541,-2355,-591,-3163,10598,1894,-933,2109,5006}},
{"Panasonic DMC-TZ6",-15, 0,
{ 15964,-8332,-389,1756,7198,383,862,784,1995 } },
{"Panasonic DMC-ZS4",-15, 0,
{ 15964,-8332,-389,1756,7198,383,862,784,1995 } },
{ "Panasonic DMC-TZ7",-15, 0,
{ 7901,-2472,-600,-3298,10720,2210,-864,2205,5064 } },
{ "Panasonic DMC-ZS5",-15, 0, /* same ID as Panasonic DMC-TZ70 */
{ 7901,-2472,-600,-3298,10720,2210,-864,2205,5064 } },
{ "Phase One H 20", 0, 0, /* DJC */
{ 1313,1855,-109,-6715,15908,808,-327,1840,6020 } },
{ "Phase One H 25", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{"Phase One IQ250",0, 0,
{ 4396,-153,-249,-5267,12249,2657,-1397,2323,6014 } },
{ "Phase One P 2", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One P 30", 0, 0,
{ 4516,-245,-37,-7020,14976,2173,-3206,4671,7087 } },
{ "Phase One P 45", 0, 0,
{ 5053,-24,-117,-5684,14076,1702,-2619,4492,5849 } },
{ "Phase One P40", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P65", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Red One", 704, 0xffff, /* DJC */
{ 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } },
{ "Samsung EK-GN120", 0, 0, /* Adobe; Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EX1", 0, 0x3e00,
{ 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } },
{ "Samsung EX2F", 0, 0x7ff,
{ 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } },
{ "Samsung NX mini", 0, 0,
{ 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } },
{ "Samsung NX3000", 0, 0,
{ 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } },
{ "Samsung NX30", 0, 0, /* NX30, NX300, NX300M */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX2000", 0, 0,
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX2", 0, 0xfff, /* NX20, NX200, NX210 */
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX1000", 0, 0,
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX1100", 0, 0,
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX11", 0, 0,
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX10", 0, 0, /* also NX100 */
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX5", 0, 0,
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX1", -128, 0,
{ 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } },
{ "Samsung WB2000", 0, 0xfff,
{ 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } },
{ "Samsung GX-1", 0, 0,
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Samsung GX20", 0, 0, /* copied from Pentax K20D */
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Samsung S85", 0, 0, /* DJC */
{ 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } },
// Foveon: LibRaw color data
{"Sigma dp1 Quattro",2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{"Sigma dp2 Quattro",2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma SD9", 15, 4095, /* LibRaw */
{ 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } },
{ "Sigma SD10", 15, 16383, /* LibRaw */
{ 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } },
{ "Sigma SD14", 15, 16383, /* LibRaw */
{ 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } },
{ "Sigma SD15", 15, 4095, /* LibRaw */
{ 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } },
// Merills + SD1
{ "Sigma SD1", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP1 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP2 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP3 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
// Sigma DP (non-Merill Versions)
{ "Sigma DP", 0, 4095, /* LibRaw */
// { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } },
{ 13100,-3638,-847,6855,2369,580,2723,3218,3251 } },
{ "Sinar", 0, 0, /* DJC */
{ 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } },
{ "Sony DSC-F828", 0, 0,
{ 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } },
{ "Sony DSC-R1", -512, 0,
{ 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } },
{ "Sony DSC-V3", 0, 0,
{ 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } },
{ "Sony DSC-RX100M", -800, 0, /* M2 and M3 */
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Sony DSC-RX100", -800, 0,
{ 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } },
{"Sony DSC-RX10",0, 0,
{ 8562,-3595,-385,-2715,11089,1128,-1023,2081,4400 } },
{ "Sony DSC-RX1R", -512, 0,
{ 8195,-2800,-422,-4261,12273,1709,-1505,2400,5624 } },
{ "Sony DSC-RX1", -512, 0,
{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
{ "Sony DSLR-A100", 0, 0xfeb,
{ 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } },
{ "Sony DSLR-A290", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A2", 0, 0,
{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
{ "Sony DSLR-A300", 0, 0,
{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
{ "Sony DSLR-A330", 0, 0,
{ 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } },
{ "Sony DSLR-A350", 0, 0xffc,
{ 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } },
{ "Sony DSLR-A380", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A390", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A450", -512, 0xfeb,
{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
{ "Sony DSLR-A580", -512, 0xfeb,
{ 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } },
{ "Sony DSLR-A500", -512, 0xfeb,
{ 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } },
{ "Sony DSLR-A5", -512, 0xfeb,
{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
{ "Sony DSLR-A700", -512, 0,
{ 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } },
{ "Sony DSLR-A850", -512, 0,
{ 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } },
{ "Sony DSLR-A900", -512, 0,
{ 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } },
{ "Sony ILCA-77M2", -512, 0,
{ 5991,-1732,-443,-4100,11989,2381,-704,1467,5992 } },
{ "Sony ILCE-7M2", -512, 0,
{ 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } },
{ "Sony ILCE-7S", -512, 0,
{ 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } },
{ "Sony ILCE-7R", -512, 0,
{ 4913,-541,-202,-6130,13513,2906,-1564,2151,7183 } },
{ "Sony ILCE-7", -512, 0,
{ 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } },
{ "Sony ILCE", -512, 0, /* 3000, 5000, 5100, 6000, and QX1 */
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony NEX-5N", -512, 0,
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony NEX-5R", -512, 0,
{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
{ "Sony NEX-5T", -512, 0,
{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
{ "Sony NEX-3N", -512, 0,
{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
{ "Sony NEX-3", -512, 0, /* Adobe */
{ 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } },
{ "Sony NEX-5", -512, 0, /* Adobe */
{ 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } },
{ "Sony NEX-6", -512, 0,
{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
{ "Sony NEX-7", -512, 0,
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Sony NEX", -512, 0, /* NEX-C3, NEX-F3 */
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony SLT-A33", -512, 0,
{ 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } },
{ "Sony SLT-A35", -512, 0,
{ 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } },
{ "Sony SLT-A37", -512, 0,
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony SLT-A55", -512, 0,
{ 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } },
{ "Sony SLT-A57", -512, 0,
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony SLT-A58", -512, 0,
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony SLT-A65", -512, 0,
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Sony SLT-A77", -512, 0,
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Sony SLT-A99", -512, 0,
{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
};
double cam_xyz[4][3];
char name[130];
int i, j;
int bl4=(cblack[0]+cblack[1]+cblack[2]+cblack[3])/4,bl64=0;
if(cblack[4]*cblack[5]>0)
{
for (unsigned c = 0; c < 4096 && c < cblack[4]*cblack[5]; c++)
bl64+=cblack[c+6];
bl64 /= cblack[4]*cblack[5];
}
int rblack = black+bl4+bl64;
sprintf (name, "%s %s", t_make, t_model);
for (i=0; i < sizeof table / sizeof *table; i++)
if (!strncasecmp(name, table[i].prefix, strlen(table[i].prefix))) {
if (table[i].t_black>0)
{
black = (ushort) table[i].t_black;
memset(cblack,0,sizeof(cblack));
}
else if(table[i].t_black <0 && rblack == 0 )
{
black = (ushort) (-table[i].t_black);
memset(cblack,0,sizeof(cblack));
}
if (table[i].t_maximum) maximum = (ushort) table[i].t_maximum;
if (table[i].trans[0]) {
for (raw_color = j=0; j < 12; j++)
#ifdef LIBRAW_LIBRARY_BUILD
if(internal_only)
imgdata.color.cam_xyz[0][j] = table[i].trans[j] / 10000.0;
else
imgdata.color.cam_xyz[0][j] =
#endif
cam_xyz[0][j] = table[i].trans[j] / 10000.0;
#ifdef LIBRAW_LIBRARY_BUILD
if(!internal_only)
#endif
cam_xyz_coeff (rgb_cam, cam_xyz);
}
break;
}
}
void CLASS simple_coeff (int index)
{
static const float table[][12] = {
/* index 0 -- all Foveon cameras */
{ 1.4032,-0.2231,-0.1016,-0.5263,1.4816,0.017,-0.0112,0.0183,0.9113 },
/* index 1 -- Kodak DC20 and DC25 */
{ 2.25,0.75,-1.75,-0.25,-0.25,0.75,0.75,-0.25,-0.25,-1.75,0.75,2.25 },
/* index 2 -- Logitech Fotoman Pixtura */
{ 1.893,-0.418,-0.476,-0.495,1.773,-0.278,-1.017,-0.655,2.672 },
/* index 3 -- Nikon E880, E900, and E990 */
{ -1.936280, 1.800443, -1.448486, 2.584324,
1.405365, -0.524955, -0.289090, 0.408680,
-1.204965, 1.082304, 2.941367, -1.818705 }
};
int i, c;
for (raw_color = i=0; i < 3; i++)
FORCC rgb_cam[i][c] = table[index][i*colors+c];
}
short CLASS guess_byte_order (int words)
{
uchar test[4][2];
int t=2, msb;
double diff, sum[2] = {0,0};
fread (test[0], 2, 2, ifp);
for (words-=2; words--; ) {
fread (test[t], 2, 1, ifp);
for (msb=0; msb < 2; msb++) {
diff = (test[t^2][msb] << 8 | test[t^2][!msb])
- (test[t ][msb] << 8 | test[t ][!msb]);
sum[msb] += diff*diff;
}
t = (t+1) & 3;
}
return sum[0] < sum[1] ? 0x4d4d : 0x4949;
}
float CLASS find_green (int bps, int bite, int off0, int off1)
{
UINT64 bitbuf=0;
int vbits, col, i, c;
ushort img[2][2064];
double sum[]={0,0};
FORC(2) {
fseek (ifp, c ? off1:off0, SEEK_SET);
for (vbits=col=0; col < width; col++) {
for (vbits -= bps; vbits < 0; vbits += bite) {
bitbuf <<= bite;
for (i=0; i < bite; i+=8)
bitbuf |= (unsigned) (fgetc(ifp) << i);
}
img[c][col] = bitbuf << (64-bps-vbits) >> (64-bps);
}
}
FORC(width-1) {
sum[ c & 1] += ABS(img[0][c]-img[1][c+1]);
sum[~c & 1] += ABS(img[1][c]-img[0][c+1]);
}
return 100 * log(sum[0]/sum[1]);
}
/*
Identify which camera created this file, and set global variables
accordingly.
*/
void CLASS identify()
{
static const short pana[][6] = {
{ 3130, 1743, 4, 0, -6, 0 },
{ 3130, 2055, 4, 0, -6, 0 },
{ 3130, 2319, 4, 0, -6, 0 },
{ 3170, 2103, 18, 0,-42, 20 },
{ 3170, 2367, 18, 13,-42,-21 },
{ 3177, 2367, 0, 0, -1, 0 },
{ 3304, 2458, 0, 0, -1, 0 },
{ 3330, 2463, 9, 0, -5, 0 },
{ 3330, 2479, 9, 0,-17, 4 },
{ 3370, 1899, 15, 0,-44, 20 },
{ 3370, 2235, 15, 0,-44, 20 },
{ 3370, 2511, 15, 10,-44,-21 },
{ 3690, 2751, 3, 0, -8, -3 },
{ 3710, 2751, 0, 0, -3, 0 },
{ 3724, 2450, 0, 0, 0, -2 },
{ 3770, 2487, 17, 0,-44, 19 },
{ 3770, 2799, 17, 15,-44,-19 },
{ 3880, 2170, 6, 0, -6, 0 },
{ 4060, 3018, 0, 0, 0, -2 },
{ 4290, 2391, 3, 0, -8, -1 },
{ 4330, 2439, 17, 15,-44,-19 },
{ 4508, 2962, 0, 0, -3, -4 },
{ 4508, 3330, 0, 0, -3, -6 },
};
static const ushort canon[][11] = {
{ 1944, 1416, 0, 0, 48, 0 },
{ 2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25 },
{ 2224, 1456, 48, 6, 0, 2 },
{ 2376, 1728, 12, 6, 52, 2 },
{ 2672, 1968, 12, 6, 44, 2 },
{ 3152, 2068, 64, 12, 0, 0, 16 },
{ 3160, 2344, 44, 12, 4, 4 },
{ 3344, 2484, 4, 6, 52, 6 },
{ 3516, 2328, 42, 14, 0, 0 },
{ 3596, 2360, 74, 12, 0, 0 },
{ 3744, 2784, 52, 12, 8, 12 },
{ 3944, 2622, 30, 18, 6, 2 },
{ 3948, 2622, 42, 18, 0, 2 },
{ 3984, 2622, 76, 20, 0, 2, 14 },
{ 4104, 3048, 48, 12, 24, 12 },
{ 4116, 2178, 4, 2, 0, 0 },
{ 4152, 2772, 192, 12, 0, 0 },
{ 4160, 3124, 104, 11, 8, 65 },
{ 4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49 },
{ 4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49 },
{ 4312, 2876, 22, 18, 0, 2 },
{ 4352, 2874, 62, 18, 0, 0 },
{ 4476, 2954, 90, 34, 0, 0 },
{ 4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49 },
{ 4480, 3366, 80, 50, 0, 0 },
{ 4496, 3366, 80, 50, 12, 0 },
{ 4768, 3516, 96, 16, 0, 0, 0, 16 },
{ 4832, 3204, 62, 26, 0, 0 },
{ 4832, 3228, 62, 51, 0, 0 },
{ 5108, 3349, 98, 13, 0, 0 },
{ 5120, 3318, 142, 45, 62, 0 },
{ 5280, 3528, 72, 52, 0, 0 },
{ 5344, 3516, 142, 51, 0, 0 },
{ 5344, 3584, 126,100, 0, 2 },
{ 5360, 3516, 158, 51, 0, 0 },
{ 5568, 3708, 72, 38, 0, 0 },
{ 5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49 },
{ 5712, 3774, 62, 20, 10, 2 },
{ 5792, 3804, 158, 51, 0, 0 },
{ 5920, 3950, 122, 80, 2, 0 },
};
static const struct {
ushort id;
char t_model[20];
} unique[] = {
{ 0x001, "EOS-1D" },
{ 0x167, "EOS-1DS" },
{ 0x168, "EOS 10D" },
{ 0x169, "EOS-1D Mark III" },
{ 0x170, "EOS 300D" },
{ 0x174, "EOS-1D Mark II" },
{ 0x175, "EOS 20D" },
{ 0x176, "EOS 450D" },
{ 0x188, "EOS-1Ds Mark II" },
{ 0x189, "EOS 350D" },
{ 0x190, "EOS 40D" },
{ 0x213, "EOS 5D" },
{ 0x215, "EOS-1Ds Mark III" },
{ 0x218, "EOS 5D Mark II" },
{ 0x232, "EOS-1D Mark II N" },
{ 0x234, "EOS 30D" },
{ 0x236, "EOS 400D" },
{ 0x250, "EOS 7D" },
{ 0x252, "EOS 500D" },
{ 0x254, "EOS 1000D" },
{ 0x261, "EOS 50D" },
{ 0x269, "EOS-1D X" },
{ 0x270, "EOS 550D" },
{ 0x281, "EOS-1D Mark IV" },
{ 0x285, "EOS 5D Mark III" },
{ 0x286, "EOS 600D" },
{ 0x287, "EOS 60D" },
{ 0x288, "EOS 1100D" },
{ 0x289, "EOS 7D Mark II" },
{ 0x301, "EOS 650D" },
{ 0x302, "EOS 6D" },
{ 0x324, "EOS-1D C" },
{ 0x325, "EOS 70D" },
{ 0x326, "EOS 700D" },
{ 0x327, "EOS 1200D" },
{ 0x331, "EOS M" },
{ 0x335, "EOS M2" },
{ 0x346, "EOS 100D" },
{ 0x347, "EOS 760D" },
{ 0x382, "EOS 5DS" },
{ 0x393, "EOS 750D" },
{ 0x401, "EOS 5DS R" },
}, sonique[] = {
{ 0x002, "DSC-R1" }, { 0x100, "DSLR-A100" },
{ 0x101, "DSLR-A900" }, { 0x102, "DSLR-A700" },
{ 0x103, "DSLR-A200" }, { 0x104, "DSLR-A350" },
{ 0x105, "DSLR-A300" },
{262,"DSLR-A900"},
{263,"DSLR-A380"},
{ 0x108, "DSLR-A330" },
{ 0x109, "DSLR-A230" }, { 0x10a, "DSLR-A290" },
{ 0x10d, "DSLR-A850" },
{270,"DSLR-A850"},
{ 0x111, "DSLR-A550" },
{ 0x112, "DSLR-A500" }, { 0x113, "DSLR-A450" },
{ 0x116, "NEX-5" }, { 0x117, "NEX-3" },
{ 0x118, "SLT-A33" }, { 0x119, "SLT-A55V" },
{ 0x11a, "DSLR-A560" }, { 0x11b, "DSLR-A580" },
{ 0x11c, "NEX-C3" }, { 0x11d, "SLT-A35" },
{ 0x11e, "SLT-A65V" }, { 0x11f, "SLT-A77V" },
{ 0x120, "NEX-5N" }, { 0x121, "NEX-7" },
{290,"NEX-VG20E"},
{ 0x123, "SLT-A37" }, { 0x124, "SLT-A57" },
{ 0x125, "NEX-F3" }, { 0x126, "SLT-A99V" },
{ 0x127, "NEX-6" }, { 0x128, "NEX-5R" },
{ 0x129, "DSC-RX100" }, { 0x12a, "DSC-RX1" },
{299,"NEX-VG900"},
{300,"NEX-VG30E"},
{ 0x12e, "ILCE-3000" }, { 0x12f, "SLT-A58" },
{ 0x131, "NEX-3N" }, { 0x132, "ILCE-7" },
{ 0x133, "NEX-5T" }, { 0x134, "DSC-RX100M2" },
{ 0x135, "DSC-RX10" }, { 0x136, "DSC-RX1R" },
{ 0x137, "ILCE-7R" }, { 0x138, "ILCE-6000" },
{ 0x139, "ILCE-5000" }, { 0x13d, "DSC-RX100M3" },
{ 0x13e, "ILCE-7S" }, { 0x13f, "ILCA-77M2" },
{ 0x153, "ILCE-5100" }, { 0x154, "ILCE-7M2" },
{ 0x15a, "ILCE-QX1" },
};
static const struct {
unsigned fsize;
ushort rw, rh;
uchar lm, tm, rm, bm, lf, cf, max, flags;
char t_make[10], t_model[20];
ushort offset;
} table[] = {
{ 786432,1024, 768, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-080C" },
{ 1447680,1392,1040, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-145C" },
{ 1920000,1600,1200, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-201C" },
{ 5067304,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C" },
{ 5067316,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C",12 },
{ 10134608,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C" },
{ 10134620,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C",12 },
{ 16157136,3272,2469, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-810C" },
{ 15980544,3264,2448, 0, 0, 0, 0, 8,0x61,0,1,"AgfaPhoto","DC-833m" },
{ 9631728,2532,1902, 0, 0, 0, 0,96,0x61,0,0,"Alcatel","5035D" },
// Android Raw dumps id start
// File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb
{ 16424960,4208,3120, 0, 0, 0, 0, 1,0x16,0,0,"Sony","IMX135-mipi 13mp" },
{ 17522688,4212,3120, 0, 0, 0, 0, 0,0x16,0,0,"Sony","IMX135-QCOM" },
{ 10223360,2608,1960, 0, 0, 0, 0, 1,0x94,0,0,"Sony","IMX072-mipi" },
{ 5107712,2688,1520, 0, 0, 0, 0, 1,0x61,0,0,"HTC","UltraPixel" },
{ 1540857,2688,1520, 0, 0, 0, 0, 1,0x61,0,0,"Samsung","S3" },
{ 10223363,2688,1520, 0, 0, 0, 0, 1,0x61,0,0,"Samsung","GalaxyNexus" },
// Android Raw dumps id end
{ 2868726,1384,1036, 0, 0, 0, 0,64,0x49,0,8,"Baumer","TXG14",1078 },
{ 5298000,2400,1766,12,12,44, 2,40,0x94,0,2,"Canon","PowerShot SD300" },
{ 6553440,2664,1968, 4, 4,44, 4,40,0x94,0,2,"Canon","PowerShot A460" },
{ 6573120,2672,1968,12, 8,44, 0,40,0x94,0,2,"Canon","PowerShot A610" },
{ 6653280,2672,1992,10, 6,42, 2,40,0x94,0,2,"Canon","PowerShot A530" },
{ 7710960,2888,2136,44, 8, 4, 0,40,0x94,0,2,"Canon","PowerShot S3 IS" },
{ 9219600,3152,2340,36,12, 4, 0,40,0x94,0,2,"Canon","PowerShot A620" },
{ 9243240,3152,2346,12, 7,44,13,40,0x49,0,2,"Canon","PowerShot A470" },
{ 10341600,3336,2480, 6, 5,32, 3,40,0x94,0,2,"Canon","PowerShot A720 IS" },
{ 10383120,3344,2484,12, 6,44, 6,40,0x94,0,2,"Canon","PowerShot A630" },
{ 12945240,3736,2772,12, 6,52, 6,40,0x94,0,2,"Canon","PowerShot A640" },
{ 15636240,4104,3048,48,12,24,12,40,0x94,0,2,"Canon","PowerShot A650" },
{ 15467760,3720,2772, 6,12,30, 0,40,0x94,0,2,"Canon","PowerShot SX110 IS" },
{ 15534576,3728,2778,12, 9,44, 9,40,0x94,0,2,"Canon","PowerShot SX120 IS" },
{ 18653760,4080,3048,24,12,24,12,40,0x94,0,2,"Canon","PowerShot SX20 IS" },
{ 19131120,4168,3060,92,16, 4, 1,40,0x94,0,2,"Canon","PowerShot SX220 HS" },
{ 21936096,4464,3276,25,10,73,12,40,0x16,0,2,"Canon","PowerShot SX30 IS" },
{ 24724224,4704,3504, 8,16,56, 8,40,0x49,0,2,"Canon","PowerShot A3300 IS" },
{ 1976352,1632,1211, 0, 2, 0, 1, 0,0x94,0,1,"Casio","QV-2000UX" },
{ 3217760,2080,1547, 0, 0,10, 1, 0,0x94,0,1,"Casio","QV-3*00EX" },
{ 6218368,2585,1924, 0, 0, 9, 0, 0,0x94,0,1,"Casio","QV-5700" },
{ 7816704,2867,2181, 0, 0,34,36, 0,0x16,0,1,"Casio","EX-Z60" },
{ 2937856,1621,1208, 0, 0, 1, 0, 0,0x94,7,13,"Casio","EX-S20" },
{ 4948608,2090,1578, 0, 0,32,34, 0,0x94,7,1,"Casio","EX-S100" },
{ 6054400,2346,1720, 2, 0,32, 0, 0,0x94,7,1,"Casio","QV-R41" },
{ 7426656,2568,1928, 0, 0, 0, 0, 0,0x94,0,1,"Casio","EX-P505" },
{ 7530816,2602,1929, 0, 0,22, 0, 0,0x94,7,1,"Casio","QV-R51" },
{ 7542528,2602,1932, 0, 0,32, 0, 0,0x94,7,1,"Casio","EX-Z50" },
{ 7562048,2602,1937, 0, 0,25, 0, 0,0x16,7,1,"Casio","EX-Z500" },
{ 7753344,2602,1986, 0, 0,32,26, 0,0x94,7,1,"Casio","EX-Z55" },
{ 9313536,2858,2172, 0, 0,14,30, 0,0x94,7,1,"Casio","EX-P600" },
{ 10834368,3114,2319, 0, 0,27, 0, 0,0x94,0,1,"Casio","EX-Z750" },
{ 10843712,3114,2321, 0, 0,25, 0, 0,0x94,0,1,"Casio","EX-Z75" },
{ 10979200,3114,2350, 0, 0,32,32, 0,0x94,7,1,"Casio","EX-P700" },
{ 12310144,3285,2498, 0, 0, 6,30, 0,0x94,0,1,"Casio","EX-Z850" },
{ 12489984,3328,2502, 0, 0,47,35, 0,0x94,0,1,"Casio","EX-Z8" },
{ 15499264,3754,2752, 0, 0,82, 0, 0,0x94,0,1,"Casio","EX-Z1050" },
{ 18702336,4096,3044, 0, 0,24, 0,80,0x94,7,1,"Casio","EX-ZR100" },
{ 7684000,2260,1700, 0, 0, 0, 0,13,0x94,0,1,"Casio","QV-4000" },
{ 787456,1024, 769, 0, 1, 0, 0, 0,0x49,0,0,"Creative","PC-CAM 600" },
{ 28829184,4384,3288, 0, 0, 0, 0,36,0x61,0,0,"DJI" },
{ 15151104,4608,3288, 0, 0, 0, 0, 0,0x94,0,0,"Matrix" },
{ 3840000,1600,1200, 0, 0, 0, 0,65,0x49,0,0,"Foculus","531C" },
{ 307200, 640, 480, 0, 0, 0, 0, 0,0x94,0,0,"Generic" },
{ 62464, 256, 244, 1, 1, 6, 1, 0,0x8d,0,0,"Kodak","DC20" },
{ 124928, 512, 244, 1, 1,10, 1, 0,0x8d,0,0,"Kodak","DC20" },
{ 1652736,1536,1076, 0,52, 0, 0, 0,0x61,0,0,"Kodak","DCS200" },
{ 4159302,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330" },
{ 4162462,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330",3160 },
{ 2247168,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" },
{ 3370752,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" },
{ 6163328,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603" },
{ 6166488,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603",3160 },
{ 460800, 640, 480, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" },
{ 9116448,2848,2134, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" },
{ 12241200,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP" },
{ 12272756,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP",31556 },
{ 18000000,4000,3000, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","12MP" },
{ 614400, 640, 480, 0, 3, 0, 0,64,0x94,0,0,"Kodak","KAI-0340" },
{ 15360000,3200,2400, 0, 0, 0, 0,96,0x16,0,0,"Lenovo","A820" },
{ 3884928,1608,1207, 0, 0, 0, 0,96,0x16,0,0,"Micron","2010",3212 },
{ 1138688,1534, 986, 0, 0, 0, 0, 0,0x61,0,0,"Minolta","RD175",513 },
{ 1581060,1305, 969, 0, 0,18, 6, 6,0x1e,4,1,"Nikon","E900" },
{ 2465792,1638,1204, 0, 0,22, 1, 6,0x4b,5,1,"Nikon","E950" },
{ 2940928,1616,1213, 0, 0, 0, 7,30,0x94,0,1,"Nikon","E2100" },
{ 4771840,2064,1541, 0, 0, 0, 1, 6,0xe1,0,1,"Nikon","E990" },
{ 4775936,2064,1542, 0, 0, 0, 0,30,0x94,0,1,"Nikon","E3700" },
{ 5865472,2288,1709, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E4500" },
{ 5869568,2288,1710, 0, 0, 0, 0, 6,0x16,0,1,"Nikon","E4300" },
{ 7438336,2576,1925, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E5000" },
{ 8998912,2832,2118, 0, 0, 0, 0,30,0x94,7,1,"Nikon","COOLPIX S6" },
{ 5939200,2304,1718, 0, 0, 0, 0,30,0x16,0,0,"Olympus","C770UZ" },
{ 3178560,2064,1540, 0, 0, 0, 0, 0,0x94,0,1,"Pentax","Optio S" },
{ 4841984,2090,1544, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S" },
{ 6114240,2346,1737, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S4" },
{ 10702848,3072,2322, 0, 0, 0,21,30,0x94,0,1,"Pentax","Optio 750Z" },
{ 13248000,2208,3000, 0, 0, 0, 0,13,0x61,0,0,"Pixelink","A782" },
{ 6291456,2048,1536, 0, 0, 0, 0,96,0x61,0,0,"RoverShot","3320AF" },
{ 311696, 644, 484, 0, 0, 0, 0, 0,0x16,0,8,"ST Micro","STV680 VGA" },
{ 16098048,3288,2448, 0, 0,24, 0, 9,0x94,0,1,"Samsung","S85" },
{ 16215552,3312,2448, 0, 0,48, 0, 9,0x94,0,1,"Samsung","S85" },
{ 20487168,3648,2808, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" },
{ 24000000,4000,3000, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" },
{ 12582980,3072,2048, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 },
{ 33292868,4080,4080, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 },
{ 44390468,4080,5440, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 },
{ 1409024,1376,1024, 0, 0, 1, 0, 0,0x49,0,0,"Sony","XCD-SX910CR" },
{ 2818048,1376,1024, 0, 0, 1, 0,97,0x49,0,0,"Sony","XCD-SX910CR" },
};
static const char *corp[] =
{ "AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm",
"Mamiya", "Minolta", "Motorola", "Kodak", "Konica", "Leica",
"Nikon", "Nokia", "Olympus", "Pentax", "Phase One", "Ricoh",
"Samsung", "Sigma", "Sinar", "Sony" };
char head[32], *cp;
int hlen, flen, fsize, zero_fsize=1, i, c;
struct jhead jh;
tiff_flip = flip = filters = UINT_MAX; /* unknown */
raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0;
maximum = height = width = top_margin = left_margin = 0;
cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0;
iso_speed = shutter = aperture = focal_len = unique_id = 0;
tiff_nifds = 0;
memset (tiff_ifd, 0, sizeof tiff_ifd);
memset (gpsdata, 0, sizeof gpsdata);
memset (cblack, 0, sizeof cblack);
memset (white, 0, sizeof white);
memset (mask, 0, sizeof mask);
thumb_offset = thumb_length = thumb_width = thumb_height = 0;
load_raw = thumb_load_raw = 0;
write_thumb = &CLASS jpeg_thumb;
data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0;
kodak_cbpp = zero_after_ff = dng_version = load_flags = 0;
timestamp = shot_order = tiff_samples = black = is_foveon = 0;
mix_green = profile_length = data_error = zero_is_bad = 0;
pixel_aspect = is_raw = raw_color = 1;
tile_width = tile_length = 0;
for (i=0; i < 4; i++) {
cam_mul[i] = i == 1;
pre_mul[i] = i < 3;
FORC3 cmatrix[c][i] = 0;
FORC3 rgb_cam[c][i] = c == i;
}
colors = 3;
for (i=0; i < 0x10000; i++) curve[i] = i;
order = get2();
hlen = get4();
fseek (ifp, 0, SEEK_SET);
fread (head, 1, 32, ifp);
fseek (ifp, 0, SEEK_END);
flen = fsize = ftell(ifp);
if ((cp = (char *) memmem (head, 32, (char*)"MMMM", 4)) ||
(cp = (char *) memmem (head, 32, (char*)"IIII", 4))) {
parse_phase_one (cp-head);
if (cp-head && parse_tiff(0)) apply_tiff();
} else if (order == 0x4949 || order == 0x4d4d) {
if (!memcmp (head+6,"HEAPCCDR",8)) {
data_offset = hlen;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
#endif
parse_ciff (hlen, flen-hlen, 0);
load_raw = &CLASS canon_load_raw;
} else if (parse_tiff(0)) apply_tiff();
} else if (!memcmp (head,"\xff\xd8\xff\xe1",4) &&
!memcmp (head+6,"Exif",4)) {
fseek (ifp, 4, SEEK_SET);
data_offset = 4 + get2();
fseek (ifp, data_offset, SEEK_SET);
if (fgetc(ifp) != 0xff)
parse_tiff(12);
thumb_offset = 0;
} else if (!memcmp (head+25,"ARECOYK",7)) {
strcpy (make, "Contax");
strcpy (model,"N Digital");
fseek (ifp, 33, SEEK_SET);
get_timestamp(1);
fseek (ifp, 52, SEEK_SET);
switch (get4()) {
case 7: iso_speed = 25; break;
case 8: iso_speed = 32; break;
case 9: iso_speed = 40; break;
case 10: iso_speed = 50; break;
case 11: iso_speed = 64; break;
case 12: iso_speed = 80; break;
case 13: iso_speed = 100; break;
case 14: iso_speed = 125; break;
case 15: iso_speed = 160; break;
case 16: iso_speed = 200; break;
case 17: iso_speed = 250; break;
case 18: iso_speed = 320; break;
case 19: iso_speed = 400; break;
}
shutter = powf64(2.0f, (((float)get4())/8.0f)) / 16000.0f;
FORC4 cam_mul[c ^ (c >> 1)] = get4();
fseek (ifp, 88, SEEK_SET);
aperture = powf64(2.0f, ((float)get4())/16.0f);
fseek (ifp, 112, SEEK_SET);
focal_len = get4();
#ifdef LIBRAW_LIBRARY_BUILD
fseek (ifp, 104, SEEK_SET);
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, ((float)get4())/16.0f);
fseek (ifp, 124, SEEK_SET);
fread(imgdata.lens.makernotes.Lens, 32, 1, ifp);
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Contax_N;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Contax_N;
#endif
} else if (!strcmp (head, "PXN")) {
strcpy (make, "Logitech");
strcpy (model,"Fotoman Pixtura");
} else if (!strcmp (head, "qktk")) {
strcpy (make, "Apple");
strcpy (model,"QuickTake 100");
load_raw = &CLASS quicktake_100_load_raw;
} else if (!strcmp (head, "qktn")) {
strcpy (make, "Apple");
strcpy (model,"QuickTake 150");
load_raw = &CLASS kodak_radc_load_raw;
} else if (!memcmp (head,"FUJIFILM",8)) {
fseek (ifp, 84, SEEK_SET);
thumb_offset = get4();
thumb_length = get4();
fseek (ifp, 92, SEEK_SET);
parse_fuji (get4());
if (thumb_offset > 120) {
fseek (ifp, 120, SEEK_SET);
is_raw += (i = get4()) && 1;
if (is_raw == 2 && shot_select)
parse_fuji (i);
}
load_raw = &CLASS unpacked_load_raw;
fseek (ifp, 100+28*(shot_select > 0), SEEK_SET);
parse_tiff (data_offset = get4());
parse_tiff (thumb_offset+12);
apply_tiff();
} else if (!memcmp (head,"RIFF",4)) {
fseek (ifp, 0, SEEK_SET);
parse_riff();
} else if (!memcmp (head+4,"ftypqt ",9)) {
fseek (ifp, 0, SEEK_SET);
parse_qt (fsize);
is_raw = 0;
} else if (!memcmp (head,"\0\001\0\001\0@",6)) {
fseek (ifp, 6, SEEK_SET);
fread (make, 1, 8, ifp);
fread (model, 1, 8, ifp);
fread (model2, 1, 16, ifp);
data_offset = get2();
get2();
raw_width = get2();
raw_height = get2();
load_raw = &CLASS nokia_load_raw;
filters = 0x61616161;
} else if (!memcmp (head,"NOKIARAW",8)) {
strcpy (make, "NOKIA");
order = 0x4949;
fseek (ifp, 300, SEEK_SET);
data_offset = get4();
i = get4();
width = get2();
height = get2();
switch (tiff_bps = i*8 / (width * height)) {
case 8: load_raw = &CLASS eight_bit_load_raw; break;
case 10: load_raw = &CLASS nokia_load_raw;
}
raw_height = height + (top_margin = i / (width * tiff_bps/8) - height);
mask[0][3] = 1;
filters = 0x61616161;
} else if (!memcmp (head,"ARRI",4)) {
order = 0x4949;
fseek (ifp, 20, SEEK_SET);
width = get4();
height = get4();
strcpy (make, "ARRI");
fseek (ifp, 668, SEEK_SET);
fread (model, 1, 64, ifp);
data_offset = 4096;
load_raw = &CLASS packed_load_raw;
load_flags = 88;
filters = 0x61616161;
} else if (!memcmp (head,"XPDS",4)) {
order = 0x4949;
fseek (ifp, 0x800, SEEK_SET);
fread (make, 1, 41, ifp);
raw_height = get2();
raw_width = get2();
fseek (ifp, 56, SEEK_CUR);
fread (model, 1, 30, ifp);
data_offset = 0x10000;
load_raw = &CLASS canon_rmf_load_raw;
gamma_curve (0, 12.25, 1, 1023);
} else if (!memcmp (head+4,"RED1",4)) {
strcpy (make, "Red");
strcpy (model,"One");
parse_redcine();
load_raw = &CLASS redcine_load_raw;
gamma_curve (1/2.4, 12.92, 1, 4095);
filters = 0x49494949;
} else if (!memcmp (head,"DSC-Image",9))
parse_rollei();
else if (!memcmp (head,"PWAD",4))
parse_sinar_ia();
else if (!memcmp (head,"\0MRM",4))
parse_minolta(0);
else if (!memcmp (head,"FOVb",4))
{
#ifdef LIBRAW_LIBRARY_BUILD
#ifdef LIBRAW_DEMOSAIC_PACK_GPL2
if(!imgdata.params.force_foveon_x3f)
parse_foveon();
else
#endif
parse_x3f();
#else
#ifdef LIBRAW_DEMOSAIC_PACK_GPL2
parse_foveon();
#endif
#endif
}
else if (!memcmp (head,"CI",2))
parse_cine();
else
for (zero_fsize=i=0; i < sizeof table / sizeof *table; i++)
if (fsize == table[i].fsize) {
strcpy (make, table[i].t_make );
#ifdef LIBRAW_LIBRARY_BUILD
if (!strcmp(make, "Canon"))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
#endif
strcpy (model, table[i].t_model);
flip = table[i].flags >> 2;
zero_is_bad = table[i].flags & 2;
if (table[i].flags & 1)
parse_external_jpeg();
data_offset = table[i].offset;
raw_width = table[i].rw;
raw_height = table[i].rh;
left_margin = table[i].lm;
top_margin = table[i].tm;
width = raw_width - left_margin - table[i].rm;
height = raw_height - top_margin - table[i].bm;
filters = 0x1010101 * table[i].cf;
colors = 4 - !((filters & filters >> 1) & 0x5555);
load_flags = table[i].lf;
switch (tiff_bps = (fsize-data_offset)*8 / (raw_width*raw_height)) {
case 6:
load_raw = &CLASS minolta_rd175_load_raw; break;
case 8:
load_raw = &CLASS eight_bit_load_raw; break;
case 10:
if ((fsize-data_offset)/raw_height*3 >= raw_width*4) {
load_raw = &CLASS android_loose_load_raw; break;
} else if (load_flags & 1) {
load_raw = &CLASS android_tight_load_raw; break;
}
case 12:
load_flags |= 128;
load_raw = &CLASS packed_load_raw; break;
case 16:
order = 0x4949 | 0x404 * (load_flags & 1);
tiff_bps -= load_flags >> 4;
tiff_bps -= load_flags = load_flags >> 1 & 7;
load_raw = &CLASS unpacked_load_raw;
}
maximum = (1 << tiff_bps) - (1 << table[i].max);
}
if (zero_fsize) fsize = 0;
if (make[0] == 0) parse_smal (0, flen);
if (make[0] == 0) {
parse_jpeg(0);
fseek(ifp,0,SEEK_END);
int sz = ftell(ifp);
if (!(strncmp(model,"ov",2) && strncmp(model,"RP_OV",5)) && sz>=6404096 &&
!fseek (ifp, -6404096, SEEK_END) &&
fread (head, 1, 32, ifp) && !strcmp(head,"BRCMn")) {
strcpy (make, "OmniVision");
data_offset = ftell(ifp) + 0x8000-32;
width = raw_width;
raw_width = 2611;
load_raw = &CLASS nokia_load_raw;
filters = 0x16161616;
} else is_raw = 0;
}
for (i=0; i < sizeof corp / sizeof *corp; i++)
if (strcasestr (make, corp[i])) /* Simplify company names */
strcpy (make, corp[i]);
if ((!strcmp(make,"Kodak") || !strcmp(make,"Leica")) &&
((cp = strcasestr(model," DIGITAL CAMERA")) ||
(cp = strstr(model,"FILE VERSION"))))
*cp = 0;
if (!strncasecmp(model,"PENTAX",6))
strcpy (make, "Pentax");
cp = make + strlen(make); /* Remove trailing spaces */
while (*--cp == ' ') *cp = 0;
cp = model + strlen(model);
while (*--cp == ' ') *cp = 0;
i = strlen(make); /* Remove make from model */
if (!strncasecmp (model, make, i) && model[i++] == ' ')
memmove (model, model+i, 64-i);
if (!strncmp (model,"FinePix ",8))
strcpy (model, model+8);
if (!strncmp (model,"Digital Camera ",15))
strcpy (model, model+15);
desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0;
if (!is_raw) goto notraw;
if (!height) height = raw_height;
if (!width) width = raw_width;
if (height == 2624 && width == 3936) /* Pentax K10D and Samsung GX10 */
{ height = 2616; width = 3896; }
if (height == 3136 && width == 4864) /* Pentax K20D and Samsung GX20 */
{ height = 3124; width = 4688; filters = 0x16161616; }
if (width == 4352 && (!strcmp(model,"K-r") || !strcmp(model,"K-x")))
{ width = 4309; filters = 0x16161616; }
if (width >= 4960 && !strncmp(model,"K-5",3))
{ left_margin = 10; width = 4950; filters = 0x16161616; }
if (width == 4736 && !strcmp(model,"K-7"))
{ height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; }
if (width == 6080 && !strcmp(model,"K-3"))
{ left_margin = 4; width = 6040; }
if (width == 7424 && !strcmp(model,"645D"))
{ height = 5502; width = 7328; filters = 0x61616161; top_margin = 29;
left_margin = 48; }
if (height == 3014 && width == 4096) /* Ricoh GX200 */
width = 4014;
if (dng_version) {
if (filters == UINT_MAX) filters = 0;
if (filters) is_raw = tiff_samples;
else colors = tiff_samples;
switch (tiff_compress) {
case 0: /* Compression not set, assuming uncompressed */
case 1: load_raw = &CLASS packed_dng_load_raw; break;
case 7: load_raw = &CLASS lossless_dng_load_raw; break;
case 34892: load_raw = &CLASS lossy_dng_load_raw; break;
default: load_raw = 0;
}
if (!strcmp(make, "Canon") && unique_id)
{
for (i = 0; i < sizeof unique / sizeof *unique; i++)
if (unique_id == 0x80000000 + unique[i].id)
{
strcpy(model, unique[i].t_model);
break;
}
}
if (!strcasecmp(make, "Sony") && unique_id)
{
for (i = 0; i < sizeof sonique / sizeof *sonique; i++)
if (unique_id == sonique[i].id)
{
strcpy(model, sonique[i].t_model);
break;
}
}
goto dng_skip;
}
if (!strcmp(make,"Canon") && !fsize && tiff_bps != 15) {
if (!load_raw)
load_raw = &CLASS lossless_jpeg_load_raw;
for (i=0; i < sizeof canon / sizeof *canon; i++)
if (raw_width == canon[i][0] && raw_height == canon[i][1]) {
width = raw_width - (left_margin = canon[i][2]);
height = raw_height - (top_margin = canon[i][3]);
width -= canon[i][4];
height -= canon[i][5];
mask[0][1] = canon[i][6];
mask[0][3] = -canon[i][7];
mask[1][1] = canon[i][8];
mask[1][3] = -canon[i][9];
if (canon[i][10]) filters = canon[i][10] * 0x01010101;
}
if ((unique_id | 0x20000) == 0x2720000) {
left_margin = 8;
top_margin = 16;
}
}
if (!strcmp(make,"Canon") && unique_id)
{
for (i=0; i < sizeof unique / sizeof *unique; i++)
if (unique_id == 0x80000000 + unique[i].id)
{
adobe_coeff ("Canon", unique[i].t_model);
strcpy(model,unique[i].t_model);
}
}
if (!strcasecmp(make,"Sony") && unique_id)
{
for (i=0; i < sizeof sonique / sizeof *sonique; i++)
if (unique_id == sonique[i].id)
{
adobe_coeff ("Sony", sonique[i].t_model);
strcpy(model,sonique[i].t_model);
}
}
if (!strcmp(make,"Nikon")) {
if (!load_raw)
load_raw = &CLASS packed_load_raw;
if (model[0] == 'E')
load_flags |= !data_offset << 2 | 2;
}
/* Set parameters based on camera name (for non-DNG files). */
if (!strcmp(model,"KAI-0340")
&& find_green (16, 16, 3840, 5120) < 25) {
height = 480;
top_margin = filters = 0;
strcpy (model,"C603");
}
if (is_foveon) {
if (height*2 < width) pixel_aspect = 0.5;
if (height > width) pixel_aspect = 2;
filters = 0;
#ifdef LIBRAW_DEMOSAIC_PACK_GPL2
if(!imgdata.params.force_foveon_x3f)
simple_coeff(0);
#endif
} else if (!strcmp(make,"Canon") && tiff_bps == 15) {
switch (width) {
case 3344: width -= 66;
case 3872: width -= 6;
}
if (height > width) SWAP(height,width);
filters = 0;
tiff_samples = colors = 3;
load_raw = &CLASS canon_sraw_load_raw;
} else if (!strcmp(model,"PowerShot 600")) {
height = 613;
width = 854;
raw_width = 896;
colors = 4;
filters = 0xe1e4e1e4;
load_raw = &CLASS canon_600_load_raw;
} else if (!strcmp(model,"PowerShot A5") ||
!strcmp(model,"PowerShot A5 Zoom")) {
height = 773;
width = 960;
raw_width = 992;
pixel_aspect = 256/235.0;
filters = 0x1e4e1e4e;
goto canon_a5;
} else if (!strcmp(model,"PowerShot A50")) {
height = 968;
width = 1290;
raw_width = 1320;
filters = 0x1b4e4b1e;
goto canon_a5;
} else if (!strcmp(model,"PowerShot Pro70")) {
height = 1024;
width = 1552;
filters = 0x1e4b4e1b;
canon_a5:
colors = 4;
tiff_bps = 10;
load_raw = &CLASS packed_load_raw;
load_flags = 40;
} else if (!strcmp(model,"PowerShot Pro90 IS") ||
!strcmp(model,"PowerShot G1")) {
colors = 4;
filters = 0xb4b4b4b4;
} else if (!strcmp(model,"PowerShot A610")) {
if (canon_s2is()) strcpy (model+10, "S2 IS");
} else if (!strcmp(model,"PowerShot SX220 HS")) {
mask[1][3] = -4;
top_margin=16;
left_margin = 92;
} else if (!strcmp(model,"PowerShot S120")) {
raw_width = 4192;
raw_height = 3062;
width = 4022;
height = 3016;
mask[0][0] = top_margin = 31;
mask[0][2] = top_margin + height;
left_margin = 120;
mask[0][1] = 23;
mask[0][3] = 72;
} else if (!strcmp(model,"PowerShot G16")) {
mask[0][0] = 0;
mask[0][2] = 80;
mask[0][1] = 0;
mask[0][3] = 16;
top_margin = 29;
left_margin = 120;
width = raw_width-left_margin-48;
height = raw_height-top_margin-14;
} else if (!strcmp(model,"PowerShot SX50 HS")) {
top_margin = 17;
} else if (!strcmp(model,"EOS D2000C")) {
filters = 0x61616161;
black = curve[200];
} else if (!strcmp(model,"D1")) {
cam_mul[0] *= 256/527.0;
cam_mul[2] *= 256/317.0;
} else if (!strcmp(model,"D1X")) {
width -= 4;
pixel_aspect = 0.5;
} else if (!strcmp(model,"D40X") ||
!strcmp(model,"D60") ||
!strcmp(model,"D80") ||
!strcmp(model,"D3000")) {
height -= 3;
width -= 4;
} else if (!strcmp(model,"D3") ||
!strcmp(model,"D3S") ||
!strcmp(model,"D700")) {
width -= 4;
left_margin = 2;
} else if (!strcmp(model,"D3100")) {
width -= 28;
left_margin = 6;
} else if (!strcmp(model,"D5000") ||
!strcmp(model,"D90")) {
width -= 42;
} else if (!strcmp(model,"D5100") ||
!strcmp(model,"D7000") ||
!strcmp(model,"COOLPIX A")) {
width -= 44;
} else if (!strcmp(model,"D3200") ||
!strncmp(model,"D6",2) ||
!strncmp(model,"D800",4)) {
width -= 46;
} else if (!strcmp(model,"D4") ||
!strcmp(model,"Df")) {
width -= 52;
left_margin = 2;
} else if (!strncmp(model,"D40",3) ||
!strncmp(model,"D50",3) ||
!strncmp(model,"D70",3)) {
width--;
} else if (!strcmp(model,"D100")) {
if (load_flags)
raw_width = (width += 3) + 3;
} else if (!strcmp(model,"D200")) {
left_margin = 1;
width -= 4;
filters = 0x94949494;
} else if (!strncmp(model,"D2H",3)) {
left_margin = 6;
width -= 14;
} else if (!strncmp(model,"D2X",3)) {
if (width == 3264) width -= 32;
else width -= 8;
} else if (!strncmp(model,"D300",4)) {
width -= 32;
} else if (!strcmp(make,"Nikon") && raw_width == 4032) {
if(!strcmp(model,"COOLPIX P7700"))
{
adobe_coeff ("Nikon","COOLPIX P7700");
maximum = 65504;
load_flags = 0;
}
else if(!strcmp(model,"COOLPIX P7800"))
{
adobe_coeff ("Nikon","COOLPIX P7800");
maximum = 65504;
load_flags = 0;
}
else if(!strcmp(model,"COOLPIX P340"))
load_flags=0;
} else if (!strncmp(model,"COOLPIX P",9) && raw_width != 4032) {
load_flags = 24;
filters = 0x94949494;
if (model[9] == '7' && iso_speed >= 400)
black = 255;
} else if (!strncmp(model,"1 ",2)) {
height -= 2;
} else if (fsize == 1581060) {
simple_coeff(3);
pre_mul[0] = 1.2085;
pre_mul[1] = 1.0943;
pre_mul[3] = 1.1103;
} else if (fsize == 3178560) {
cam_mul[0] *= 4;
cam_mul[2] *= 4;
} else if (fsize == 4771840) {
if (!timestamp && nikon_e995())
strcpy (model, "E995");
if (strcmp(model,"E995")) {
filters = 0xb4b4b4b4;
simple_coeff(3);
pre_mul[0] = 1.196;
pre_mul[1] = 1.246;
pre_mul[2] = 1.018;
}
} else if (fsize == 2940928) {
if (!timestamp && !nikon_e2100())
strcpy (model,"E2500");
if (!strcmp(model,"E2500")) {
height -= 2;
load_flags = 6;
colors = 4;
filters = 0x4b4b4b4b;
}
} else if (fsize == 4775936) {
if (!timestamp) nikon_3700();
if (model[0] == 'E' && atoi(model+1) < 3700)
filters = 0x49494949;
if (!strcmp(model,"Optio 33WR")) {
flip = 1;
filters = 0x16161616;
}
if (make[0] == 'O') {
i = find_green (12, 32, 1188864, 3576832);
c = find_green (12, 32, 2383920, 2387016);
if (abs(i) < abs(c)) {
SWAP(i,c);
load_flags = 24;
}
if (i < 0) filters = 0x61616161;
}
} else if (fsize == 5869568) {
if (!timestamp && minolta_z2()) {
strcpy (make, "Minolta");
strcpy (model,"DiMAGE Z2");
}
load_flags = 6 + 24*(make[0] == 'M');
} else if (fsize == 6291456) {
fseek (ifp, 0x300000, SEEK_SET);
if ((order = guess_byte_order(0x10000)) == 0x4d4d) {
height -= (top_margin = 16);
width -= (left_margin = 28);
maximum = 0xf5c0;
strcpy (make, "ISG");
model[0] = 0;
}
} else if (!strcmp(make,"Fujifilm")) {
if (!strcmp(model+7,"S2Pro")) {
strcpy (model,"S2Pro");
height = 2144;
width = 2880;
flip = 6;
} else if (load_raw != &CLASS packed_load_raw)
maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00;
top_margin = (raw_height - height) >> 2 << 1;
left_margin = (raw_width - width ) >> 2 << 1;
if (width == 2848 || width == 3664) filters = 0x16161616;
if (width == 4032 || width == 4952) left_margin = 0;
if (width == 3328 && (width -= 66)) left_margin = 34;
if (width == 4936) left_margin = 4;
if (!strcmp(model,"HS50EXR") ||
!strcmp(model,"F900EXR")) {
width += 2;
left_margin = 0;
filters = 0x16161616;
}
if(!strcmp(model,"S5500"))
{
height -= (top_margin=6);
}
if (fuji_layout) raw_width *= is_raw;
if (filters == 9)
FORC(36) xtrans[0][c] =
xtrans_abs[(c/6+top_margin) % 6][(c+left_margin) % 6];
} else if (!strcmp(model,"KD-400Z")) {
height = 1712;
width = 2312;
raw_width = 2336;
goto konica_400z;
} else if (!strcmp(model,"KD-510Z")) {
goto konica_510z;
} else if (!strcasecmp(make,"Minolta")) {
if (!load_raw && (maximum = 0xfff))
load_raw = &CLASS unpacked_load_raw;
if (!strncmp(model,"DiMAGE A",8)) {
if (!strcmp(model,"DiMAGE A200"))
filters = 0x49494949;
tiff_bps = 12;
load_raw = &CLASS packed_load_raw;
} else if (!strncmp(model,"ALPHA",5) ||
!strncmp(model,"DYNAX",5) ||
!strncmp(model,"MAXXUM",6)) {
sprintf (model+20, "DYNAX %-10s", model+6+(model[0]=='M'));
adobe_coeff (make, model+20);
load_raw = &CLASS packed_load_raw;
} else if (!strncmp(model,"DiMAGE G",8)) {
if (model[8] == '4') {
height = 1716;
width = 2304;
} else if (model[8] == '5') {
konica_510z:
height = 1956;
width = 2607;
raw_width = 2624;
} else if (model[8] == '6') {
height = 2136;
width = 2848;
}
data_offset += 14;
filters = 0x61616161;
konica_400z:
load_raw = &CLASS unpacked_load_raw;
maximum = 0x3df;
order = 0x4d4d;
}
} else if (!strcmp(model,"*ist D")) {
load_raw = &CLASS unpacked_load_raw;
data_error = -1;
} else if (!strcmp(model,"*ist DS")) {
height -= 2;
} else if (!strcmp(make,"Samsung") && raw_width == 4704) {
height -= top_margin = 8;
width -= 2 * (left_margin = 8);
load_flags = 32;
} else if (!strcmp(make,"Samsung") && !strcmp(model,"NX3000")) {
top_margin = 24;
left_margin = 64;
width = 5472;
height = 3648;
filters = 0x61616161;
colors = 3;
} else if (!strcmp(make,"Samsung") && raw_height == 3714) {
height -= top_margin = 18;
left_margin = raw_width - (width = 5536);
if (raw_width != 5600)
left_margin = top_margin = 0;
filters = 0x61616161;
colors = 3;
} else if (!strcmp(make,"Samsung") && raw_width == 5632) {
order = 0x4949;
height = 3694;
top_margin = 2;
width = 5574 - (left_margin = 32 + tiff_bps);
if (tiff_bps == 12) load_flags = 80;
} else if (!strcmp(make,"Samsung") && raw_width == 5664) {
height -= top_margin = 17;
left_margin = 96;
width = 5544;
filters = 0x49494949;
} else if (!strcmp(make,"Samsung") && raw_width == 6496) {
filters = 0x61616161;
} else if (!strcmp(model,"EX1")) {
order = 0x4949;
height -= 20;
top_margin = 2;
if ((width -= 6) > 3682) {
height -= 10;
width -= 46;
top_margin = 8;
}
} else if (!strcmp(model,"WB2000")) {
order = 0x4949;
height -= 3;
top_margin = 2;
if ((width -= 10) > 3718) {
height -= 28;
width -= 56;
top_margin = 8;
}
} else if (strstr(model,"WB550")) {
strcpy (model, "WB550");
} else if (!strcmp(model,"EX2F")) {
height = 3045;
width = 4070;
top_margin = 3;
order = 0x4949;
filters = 0x49494949;
load_raw = &CLASS unpacked_load_raw;
} else if (!strcmp(model,"STV680 VGA")) {
black = 16;
} else if (!strcmp(model,"N95")) {
height = raw_height - (top_margin = 2);
} else if (!strcmp(model,"640x480")) {
gamma_curve (0.45, 4.5, 1, 255);
} else if (!strcmp(make,"Hasselblad")) {
if (load_raw == &CLASS lossless_jpeg_load_raw)
load_raw = &CLASS hasselblad_load_raw;
if (raw_width == 7262) {
height = 5444;
width = 7248;
top_margin = 4;
left_margin = 7;
filters = 0x61616161;
if(!strcasecmp(model,"H3D"))
{
adobe_coeff("Hasselblad","H3DII-39");
strcpy(model,"H3DII-39");
}
} else if (raw_width == 7410 || raw_width == 8282) {
height -= 84;
width -= 82;
top_margin = 4;
left_margin = 41;
filters = 0x61616161;
adobe_coeff("Hasselblad","H4D-40");
strcpy(model,"H4D-40");
} else if (raw_width == 9044) {
if(black > 500)
{
top_margin = 12;
left_margin = 44;
width = 8956;
height = 6708;
memset(cblack,0,sizeof(cblack));
adobe_coeff("Hasselblad","H4D-60");
strcpy(model,"H4D-60");
black = 512;
}
else
{
height = 6716;
width = 8964;
top_margin = 8;
left_margin = 40;
black += load_flags = 256;
maximum = 0x8101;
strcpy(model,"H3DII-60");
}
} else if (raw_width == 4090) {
strcpy (model, "V96C");
height -= (top_margin = 6);
width -= (left_margin = 3) + 7;
filters = 0x61616161;
} else if (raw_width == 8282 && raw_height == 6240) {
if(!strcasecmp(model,"H5D"))
{
/* H5D 50*/
left_margin = 54;
top_margin = 16;
width = 8176;
height = 6132;
black = 256;
strcpy(model,"H5D-50");
}
else if(!strcasecmp(model,"H3D"))
{
black=0;
left_margin = 54;
top_margin = 16;
width = 8176;
height = 6132;
memset(cblack,0,sizeof(cblack));
adobe_coeff("Hasselblad","H3D-50");
strcpy(model,"H3D-50");
}
} else if (raw_width == 8374 && raw_height == 6304) {
/* H5D 50c*/
left_margin = 52;
top_margin = 100;
width = 8272;
height = 6200;
black = 256;
strcpy(model,"H5D-50c");
}
if (tiff_samples > 1) {
is_raw = tiff_samples+1;
if (!shot_select && !half_size) filters = 0;
}
} else if (!strcmp(make,"Sinar")) {
if (!load_raw) load_raw = &CLASS unpacked_load_raw;
if (is_raw > 1 && !shot_select && !half_size) filters = 0;
maximum = 0x3fff;
} else if (!strcmp(make,"Leaf")) {
maximum = 0x3fff;
fseek (ifp, data_offset, SEEK_SET);
if (ljpeg_start (&jh, 1) && jh.bits == 15)
maximum = 0x1fff;
if (tiff_samples > 1) filters = 0;
if (tiff_samples > 1 || tile_length < raw_height) {
load_raw = &CLASS leaf_hdr_load_raw;
raw_width = tile_width;
}
if ((width | height) == 2048) {
if (tiff_samples == 1) {
filters = 1;
strcpy (cdesc, "RBTG");
strcpy (model, "CatchLight");
top_margin = 8; left_margin = 18; height = 2032; width = 2016;
} else {
strcpy (model, "DCB2");
top_margin = 10; left_margin = 16; height = 2028; width = 2022;
}
} else if (width+height == 3144+2060) {
if (!model[0]) strcpy (model, "Cantare");
if (width > height) {
top_margin = 6; left_margin = 32; height = 2048; width = 3072;
filters = 0x61616161;
} else {
left_margin = 6; top_margin = 32; width = 2048; height = 3072;
filters = 0x16161616;
}
if (!cam_mul[0] || model[0] == 'V') filters = 0;
else is_raw = tiff_samples;
} else if (width == 2116) {
strcpy (model, "Valeo 6");
height -= 2 * (top_margin = 30);
width -= 2 * (left_margin = 55);
filters = 0x49494949;
} else if (width == 3171) {
strcpy (model, "Valeo 6");
height -= 2 * (top_margin = 24);
width -= 2 * (left_margin = 24);
filters = 0x16161616;
}
} else if (!strcmp(make,"Leica") || !strcmp(make,"Panasonic")) {
if ((flen - data_offset) / (raw_width*8/7) == raw_height)
load_raw = &CLASS panasonic_load_raw;
if (!load_raw) {
load_raw = &CLASS unpacked_load_raw;
load_flags = 4;
}
zero_is_bad = 1;
if ((height += 12) > raw_height) height = raw_height;
for (i=0; i < sizeof pana / sizeof *pana; i++)
if (raw_width == pana[i][0] && raw_height == pana[i][1]) {
left_margin = pana[i][2];
top_margin = pana[i][3];
width += pana[i][4];
height += pana[i][5];
}
filters = 0x01010101 * (uchar) "\x94\x61\x49\x16"
[((filters-1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3];
} else if (!strcmp(model,"C770UZ")) {
height = 1718;
width = 2304;
filters = 0x16161616;
load_raw = &CLASS packed_load_raw;
load_flags = 30;
} else if (!strcmp(make,"Olympus")) {
height += height & 1;
if (exif_cfa) filters = exif_cfa;
if (width == 4100) width -= 4;
if (width == 4080) width -= 24;
if (width == 9280) { width -= 6; height -= 6; }
if (load_raw == &CLASS unpacked_load_raw)
load_flags = 4;
tiff_bps = 12;
if (!strcmp(model,"E-300") ||
!strcmp(model,"E-500")) {
width -= 20;
if (load_raw == &CLASS unpacked_load_raw) {
maximum = 0xfc3;
memset (cblack, 0, sizeof cblack);
}
} else if (!strcmp(model,"STYLUS1")) {
width -= 14;
maximum = 0xfff;
} else if (!strcmp(model,"E-330")) {
width -= 30;
if (load_raw == &CLASS unpacked_load_raw)
maximum = 0xf79;
} else if (!strcmp(model,"SP550UZ")) {
thumb_length = flen - (thumb_offset = 0xa39800);
thumb_height = 480;
thumb_width = 640;
}
} else if (!strcmp(model,"N Digital")) {
height = 2047;
width = 3072;
filters = 0x61616161;
data_offset = 0x1a00;
load_raw = &CLASS packed_load_raw;
} else if (!strcmp(model,"DSC-F828")) {
width = 3288;
left_margin = 5;
mask[1][3] = -17;
data_offset = 862144;
load_raw = &CLASS sony_load_raw;
filters = 0x9c9c9c9c;
colors = 4;
strcpy (cdesc, "RGBE");
} else if (!strcmp(model,"DSC-V3")) {
width = 3109;
left_margin = 59;
mask[0][1] = 9;
data_offset = 787392;
load_raw = &CLASS sony_load_raw;
} else if (!strcmp(make,"Sony") && raw_width == 3984) {
width = 3925;
order = 0x4d4d;
} else if (!strcmp(make,"Sony") && raw_width == 4288) {
width -= 32;
} else if (!strcmp(make,"Sony") && raw_width == 4928) {
if (height < 3280) width -= 8;
} else if (!strcmp(make,"Sony") && raw_width == 5504) { // ILCE-3000//5000
width -= height > 3664 ? 8 : 32;
} else if (!strcmp(make,"Sony") && raw_width == 6048) {
width -= 24;
if (strstr(model,"RX1") || strstr(model,"A99"))
width -= 6;
} else if (!strcmp(make,"Sony") && raw_width == 7392) {
width -= 30;
} else if (!strcmp(model,"DSLR-A100")) {
if (width == 3880) {
height--;
width = ++raw_width;
} else {
height -= 4;
width -= 4;
order = 0x4d4d;
load_flags = 2;
}
filters = 0x61616161;
} else if (!strcmp(model,"DSLR-A350")) {
height -= 4;
} else if (!strcmp(model,"PIXL")) {
height -= top_margin = 4;
width -= left_margin = 32;
gamma_curve (0, 7, 1, 255);
} else if (!strcmp(model,"C603") || !strcmp(model,"C330")
|| !strcmp(model,"12MP")) {
order = 0x4949;
if (filters && data_offset) {
fseek (ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET);
read_shorts (curve, 256);
} else gamma_curve (0, 3.875, 1, 255);
load_raw = filters ? &CLASS eight_bit_load_raw :
strcmp(model,"C330") ? &CLASS kodak_c603_load_raw :
&CLASS kodak_c330_load_raw;
load_flags = tiff_bps > 16;
tiff_bps = 8;
} else if (!strncasecmp(model,"EasyShare",9)) {
data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000;
load_raw = &CLASS packed_load_raw;
} else if (!strcasecmp(make,"Kodak")) {
if (filters == UINT_MAX) filters = 0x61616161;
if (!strncmp(model,"NC2000",6) ||
!strncmp(model,"EOSDCS",6) ||
!strncmp(model,"DCS4",4)) {
width -= 4;
left_margin = 2;
if (model[6] == ' ') model[6] = 0;
if (!strcmp(model,"DCS460A")) goto bw;
} else if (!strcmp(model,"DCS660M")) {
black = 214;
goto bw;
} else if (!strcmp(model,"DCS760M")) {
bw: colors = 1;
filters = 0;
}
if (!strcmp(model+4,"20X"))
strcpy (cdesc, "MYCY");
if (strstr(model,"DC25")) {
strcpy (model, "DC25");
data_offset = 15424;
}
if (!strncmp(model,"DC2",3)) {
raw_height = 2 + (height = 242);
if (!strncmp(model, "DC290", 5))
iso_speed = 100;
if (!strncmp(model, "DC280", 5))
iso_speed = 70;
if (flen < 100000) {
raw_width = 256; width = 249;
pixel_aspect = (4.0*height) / (3.0*width);
} else {
raw_width = 512; width = 501;
pixel_aspect = (493.0*height) / (373.0*width);
}
top_margin = left_margin = 1;
colors = 4;
filters = 0x8d8d8d8d;
simple_coeff(1);
pre_mul[1] = 1.179;
pre_mul[2] = 1.209;
pre_mul[3] = 1.036;
load_raw = &CLASS eight_bit_load_raw;
} else if (!strcmp(model,"40")) {
strcpy (model, "DC40");
height = 512;
width = 768;
data_offset = 1152;
load_raw = &CLASS kodak_radc_load_raw;
} else if (strstr(model,"DC50")) {
strcpy (model, "DC50");
height = 512;
width = 768;
iso_speed=84;
data_offset = 19712;
load_raw = &CLASS kodak_radc_load_raw;
} else if (strstr(model,"DC120")) {
strcpy (model, "DC120");
height = 976;
width = 848;
iso_speed=160;
pixel_aspect = height/0.75/width;
load_raw = tiff_compress == 7 ?
&CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw;
} else if (!strcmp(model,"DCS200")) {
thumb_height = 128;
thumb_width = 192;
thumb_offset = 6144;
thumb_misc = 360;
iso_speed=140;
write_thumb = &CLASS layer_thumb;
black = 17;
}
} else if (!strcmp(model,"Fotoman Pixtura")) {
height = 512;
width = 768;
data_offset = 3632;
load_raw = &CLASS kodak_radc_load_raw;
filters = 0x61616161;
simple_coeff(2);
} else if (!strncmp(model,"QuickTake",9)) {
if (head[5]) strcpy (model+10, "200");
fseek (ifp, 544, SEEK_SET);
height = get2();
width = get2();
data_offset = (get4(),get2()) == 30 ? 738:736;
if (height > width) {
SWAP(height,width);
fseek (ifp, data_offset-6, SEEK_SET);
flip = ~get2() & 3 ? 5:6;
}
filters = 0x61616161;
} else if (!strcmp(make,"Rollei") && !load_raw) {
switch (raw_width) {
case 1316:
height = 1030;
width = 1300;
top_margin = 1;
left_margin = 6;
break;
case 2568:
height = 1960;
width = 2560;
top_margin = 2;
left_margin = 8;
}
filters = 0x16161616;
load_raw = &CLASS rollei_load_raw;
}
else if (!strcmp(model,"GRAS-50S5C")) {
height = 2048;
width = 2440;
load_raw = &CLASS unpacked_load_raw;
data_offset = 0;
filters = 0x49494949;
order = 0x4949;
maximum = 0xfffC;
} else if (!strcmp(model,"BB-500CL")) {
height = 2058;
width = 2448;
load_raw = &CLASS unpacked_load_raw;
data_offset = 0;
filters = 0x94949494;
order = 0x4949;
maximum = 0x3fff;
} else if (!strcmp(model,"BB-500GE")) {
height = 2058;
width = 2456;
load_raw = &CLASS unpacked_load_raw;
data_offset = 0;
filters = 0x94949494;
order = 0x4949;
maximum = 0x3fff;
} else if (!strcmp(model,"SVS625CL")) {
height = 2050;
width = 2448;
load_raw = &CLASS unpacked_load_raw;
data_offset = 0;
filters = 0x94949494;
order = 0x4949;
maximum = 0x0fff;
}
/* Early reject for damaged images */
if (!load_raw || height < 22 || width < 22 ||
tiff_bps > 16 || tiff_samples > 4 || colors > 4 || colors < 1)
{
is_raw = 0;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2);
#endif
return;
}
if (!model[0])
sprintf (model, "%dx%d", width, height);
if (filters == UINT_MAX) filters = 0x94949494;
if (thumb_offset && !thumb_height) {
fseek (ifp, thumb_offset, SEEK_SET);
if (ljpeg_start (&jh, 1)) {
thumb_width = jh.wide;
thumb_height = jh.high;
}
}
dng_skip:
if ((use_camera_matrix & (use_camera_wb || dng_version))
&& cmatrix[0][0] > 0.125) {
memcpy (rgb_cam, cmatrix, sizeof cmatrix);
raw_color = 0;
}
if (raw_color) adobe_coeff (make, model);
#ifdef LIBRAW_LIBRARY_BUILD
else if(imgdata.color.cam_xyz[0][0]<0.01)
adobe_coeff (make, model,1);
#endif
if (load_raw == &CLASS kodak_radc_load_raw)
if (raw_color) adobe_coeff ("Apple","Quicktake");
if (fuji_width) {
fuji_width = width >> !fuji_layout;
if (~fuji_width & 1) filters = 0x49494949;
width = (height >> fuji_layout) + fuji_width;
height = width - 1;
pixel_aspect = 1;
} else {
if (raw_height < height) raw_height = height;
if (raw_width < width ) raw_width = width;
}
if (!tiff_bps) tiff_bps = 12;
if (!maximum)
{
maximum = (1 << tiff_bps) - 1;
if(maximum < 0x10000 && curve[maximum]>0 && load_raw == &CLASS sony_arw2_load_raw)
maximum = curve[maximum];
}
if (!load_raw || height < 22 || width < 22 ||
tiff_bps > 16 || tiff_samples > 6 || colors > 4)
is_raw = 0;
#ifdef NO_JASPER
if (load_raw == &CLASS redcine_load_raw) {
#ifdef DCRAW_VERBOSE
fprintf (stderr,_("%s: You must link dcraw with %s!!\n"),
ifname, "libjasper");
#endif
is_raw = 0;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER;
#endif
}
#endif
#ifdef NO_JPEG
if (load_raw == &CLASS kodak_jpeg_load_raw ||
load_raw == &CLASS lossy_dng_load_raw) {
#ifdef DCRAW_VERBOSE
fprintf (stderr,_("%s: You must link dcraw with %s!!\n"),
ifname, "libjpeg");
#endif
is_raw = 0;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB;
#endif
}
#endif
if (!cdesc[0])
strcpy (cdesc, colors == 3 ? "RGBG":"GMCY");
if (!raw_height) raw_height = height;
if (!raw_width ) raw_width = width;
if (filters > 999 && colors == 3)
filters |= ((filters >> 2 & 0x22222222) |
(filters << 2 & 0x88888888)) & filters << 1;
notraw:
if (flip == UINT_MAX) flip = tiff_flip;
if (flip == UINT_MAX) flip = 0;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2);
#endif
}
//@end COMMON
//@out FILEIO
#ifndef NO_LCMS
void CLASS apply_profile (const char *input, const char *output)
{
char *prof;
cmsHPROFILE hInProfile=0, hOutProfile=0;
cmsHTRANSFORM hTransform;
FILE *fp;
unsigned size;
if (strcmp (input, "embed"))
hInProfile = cmsOpenProfileFromFile (input, "r");
else if (profile_length) {
#ifndef LIBRAW_LIBRARY_BUILD
prof = (char *) malloc (profile_length);
merror (prof, "apply_profile()");
fseek (ifp, profile_offset, SEEK_SET);
fread (prof, 1, profile_length, ifp);
hInProfile = cmsOpenProfileFromMem (prof, profile_length);
free (prof);
#else
hInProfile = cmsOpenProfileFromMem (imgdata.color.profile, profile_length);
#endif
} else
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_EMBEDDED_PROFILE;
#endif
#ifdef DCRAW_VERBOSE
fprintf (stderr,_("%s has no embedded profile.\n"), ifname);
#endif
}
if (!hInProfile)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_INPUT_PROFILE;
#endif
return;
}
if (!output)
hOutProfile = cmsCreate_sRGBProfile();
else if ((fp = fopen (output, "rb"))) {
fread (&size, 4, 1, fp);
fseek (fp, 0, SEEK_SET);
oprof = (unsigned *) malloc (size = ntohl(size));
merror (oprof, "apply_profile()");
fread (oprof, 1, size, fp);
fclose (fp);
if (!(hOutProfile = cmsOpenProfileFromMem (oprof, size))) {
free (oprof);
oprof = 0;
}
}
#ifdef DCRAW_VERBOSE
else
fprintf (stderr,_("Cannot open file %s!\n"), output);
#endif
if (!hOutProfile)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_BAD_OUTPUT_PROFILE;
#endif
goto quit;
}
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf (stderr,_("Applying color profile...\n"));
#endif
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_APPLY_PROFILE,0,2);
#endif
hTransform = cmsCreateTransform (hInProfile, TYPE_RGBA_16,
hOutProfile, TYPE_RGBA_16, INTENT_PERCEPTUAL, 0);
cmsDoTransform (hTransform, image, image, width*height);
raw_color = 1; /* Don't use rgb_cam with a profile */
cmsDeleteTransform (hTransform);
cmsCloseProfile (hOutProfile);
quit:
cmsCloseProfile (hInProfile);
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_APPLY_PROFILE,1,2);
#endif
}
#endif
//@end FILEIO
//@out COMMON
void CLASS convert_to_rgb()
{
#ifndef LIBRAW_LIBRARY_BUILD
int row, col, c;
#endif
int i, j, k;
#ifndef LIBRAW_LIBRARY_BUILD
ushort *img;
float out[3];
#endif
float out_cam[3][4];
double num, inverse[3][3];
static const double xyzd50_srgb[3][3] =
{ { 0.436083, 0.385083, 0.143055 },
{ 0.222507, 0.716888, 0.060608 },
{ 0.013930, 0.097097, 0.714022 } };
static const double rgb_rgb[3][3] =
{ { 1,0,0 }, { 0,1,0 }, { 0,0,1 } };
static const double adobe_rgb[3][3] =
{ { 0.715146, 0.284856, 0.000000 },
{ 0.000000, 1.000000, 0.000000 },
{ 0.000000, 0.041166, 0.958839 } };
static const double wide_rgb[3][3] =
{ { 0.593087, 0.404710, 0.002206 },
{ 0.095413, 0.843149, 0.061439 },
{ 0.011621, 0.069091, 0.919288 } };
static const double prophoto_rgb[3][3] =
{ { 0.529317, 0.330092, 0.140588 },
{ 0.098368, 0.873465, 0.028169 },
{ 0.016879, 0.117663, 0.865457 } };
static const double (*out_rgb[])[3] =
{ rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb };
static const char *name[] =
{ "sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ" };
static const unsigned phead[] =
{ 1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0, 0, 0,
0x61637370, 0, 0, 0x6e6f6e65, 0, 0, 0, 0, 0xf6d6, 0x10000, 0xd32d };
unsigned pbody[] =
{ 10, 0x63707274, 0, 36, /* cprt */
0x64657363, 0, 40, /* desc */
0x77747074, 0, 20, /* wtpt */
0x626b7074, 0, 20, /* bkpt */
0x72545243, 0, 14, /* rTRC */
0x67545243, 0, 14, /* gTRC */
0x62545243, 0, 14, /* bTRC */
0x7258595a, 0, 20, /* rXYZ */
0x6758595a, 0, 20, /* gXYZ */
0x6258595a, 0, 20 }; /* bXYZ */
static const unsigned pwhite[] = { 0xf351, 0x10000, 0x116cc };
unsigned pcurve[] = { 0x63757276, 0, 1, 0x1000000 };
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB,0,2);
#endif
gamma_curve (gamm[0], gamm[1], 0, 0);
memcpy (out_cam, rgb_cam, sizeof out_cam);
#ifndef LIBRAW_LIBRARY_BUILD
raw_color |= colors == 1 || document_mode ||
output_color < 1 || output_color > 5;
#else
raw_color |= colors == 1 ||
output_color < 1 || output_color > 5;
#endif
if (!raw_color) {
oprof = (unsigned *) calloc (phead[0], 1);
merror (oprof, "convert_to_rgb()");
memcpy (oprof, phead, sizeof phead);
if (output_color == 5) oprof[4] = oprof[5];
oprof[0] = 132 + 12*pbody[0];
for (i=0; i < pbody[0]; i++) {
oprof[oprof[0]/4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874;
pbody[i*3+2] = oprof[0];
oprof[0] += (pbody[i*3+3] + 3) & -4;
}
memcpy (oprof+32, pbody, sizeof pbody);
oprof[pbody[5]/4+2] = strlen(name[output_color-1]) + 1;
memcpy ((char *)oprof+pbody[8]+8, pwhite, sizeof pwhite);
pcurve[3] = (short)(256/gamm[5]+0.5) << 16;
for (i=4; i < 7; i++)
memcpy ((char *)oprof+pbody[i*3+2], pcurve, sizeof pcurve);
pseudoinverse ((double (*)[3]) out_rgb[output_color-1], inverse, 3);
for (i=0; i < 3; i++)
for (j=0; j < 3; j++) {
for (num = k=0; k < 3; k++)
num += xyzd50_srgb[i][k] * inverse[j][k];
oprof[pbody[j*3+23]/4+i+2] = num * 0x10000 + 0.5;
}
for (i=0; i < phead[0]/4; i++)
oprof[i] = htonl(oprof[i]);
strcpy ((char *)oprof+pbody[2]+8, "auto-generated by dcraw");
strcpy ((char *)oprof+pbody[5]+12, name[output_color-1]);
for (i=0; i < 3; i++)
for (j=0; j < colors; j++)
for (out_cam[i][j] = k=0; k < 3; k++)
out_cam[i][j] += out_rgb[output_color-1][i][k] * rgb_cam[k][j];
}
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf (stderr, raw_color ? _("Building histograms...\n") :
_("Converting to %s colorspace...\n"), name[output_color-1]);
#endif
#ifdef LIBRAW_LIBRARY_BUILD
convert_to_rgb_loop(out_cam);
#else
memset (histogram, 0, sizeof histogram);
for (img=image[0], row=0; row < height; row++)
for (col=0; col < width; col++, img+=4) {
if (!raw_color) {
out[0] = out[1] = out[2] = 0;
FORCC {
out[0] += out_cam[0][c] * img[c];
out[1] += out_cam[1][c] * img[c];
out[2] += out_cam[2][c] * img[c];
}
FORC3 img[c] = CLIP((int) out[c]);
}
else if (document_mode)
img[0] = img[fcol(row,col)];
FORCC histogram[c][img[c] >> 3]++;
}
#endif
if (colors == 4 && output_color) colors = 3;
#ifndef LIBRAW_LIBRARY_BUILD
if (document_mode && filters) colors = 1;
#endif
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB,1,2);
#endif
}
void CLASS fuji_rotate()
{
int i, row, col;
double step;
float r, c, fr, fc;
unsigned ur, uc;
ushort wide, high, (*img)[4], (*pix)[4];
if (!fuji_width) return;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf (stderr,_("Rotating image 45 degrees...\n"));
#endif
fuji_width = (fuji_width - 1 + shrink) >> shrink;
step = sqrt(0.5);
wide = fuji_width / step;
high = (height - fuji_width) / step;
img = (ushort (*)[4]) calloc (high, wide*sizeof *img);
merror (img, "fuji_rotate()");
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE,0,2);
#endif
for (row=0; row < high; row++)
for (col=0; col < wide; col++) {
ur = r = fuji_width + (row-col)*step;
uc = c = (row+col)*step;
if (ur > height-2 || uc > width-2) continue;
fr = r - ur;
fc = c - uc;
pix = image + ur*width + uc;
for (i=0; i < colors; i++)
img[row*wide+col][i] =
(pix[ 0][i]*(1-fc) + pix[ 1][i]*fc) * (1-fr) +
(pix[width][i]*(1-fc) + pix[width+1][i]*fc) * fr;
}
free (image);
width = wide;
height = high;
image = img;
fuji_width = 0;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE,1,2);
#endif
}
void CLASS stretch()
{
ushort newdim, (*img)[4], *pix0, *pix1;
int row, col, c;
double rc, frac;
if (pixel_aspect == 1) return;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH,0,2);
#endif
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr,_("Stretching the image...\n"));
#endif
if (pixel_aspect < 1) {
newdim = height / pixel_aspect + 0.5;
img = (ushort (*)[4]) calloc (width, newdim*sizeof *img);
merror (img, "stretch()");
for (rc=row=0; row < newdim; row++, rc+=pixel_aspect) {
frac = rc - (c = rc);
pix0 = pix1 = image[c*width];
if (c+1 < height) pix1 += width*4;
for (col=0; col < width; col++, pix0+=4, pix1+=4)
FORCC img[row*width+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5;
}
height = newdim;
} else {
newdim = width * pixel_aspect + 0.5;
img = (ushort (*)[4]) calloc (height, newdim*sizeof *img);
merror (img, "stretch()");
for (rc=col=0; col < newdim; col++, rc+=1/pixel_aspect) {
frac = rc - (c = rc);
pix0 = pix1 = image[c];
if (c+1 < width) pix1 += 4;
for (row=0; row < height; row++, pix0+=width*4, pix1+=width*4)
FORCC img[row*newdim+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5;
}
width = newdim;
}
free (image);
image = img;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH,1,2);
#endif
}
int CLASS flip_index (int row, int col)
{
if (flip & 4) SWAP(row,col);
if (flip & 2) row = iheight - 1 - row;
if (flip & 1) col = iwidth - 1 - col;
return row * iwidth + col;
}
//@end COMMON
struct tiff_tag {
ushort tag, type;
int count;
union { char c[4]; short s[2]; int i; } val;
};
struct tiff_hdr {
ushort t_order, magic;
int ifd;
ushort pad, ntag;
struct tiff_tag tag[23];
int nextifd;
ushort pad2, nexif;
struct tiff_tag exif[4];
ushort pad3, ngps;
struct tiff_tag gpst[10];
short bps[4];
int rat[10];
unsigned gps[26];
char t_desc[512], t_make[64], t_model[64], soft[32], date[20], t_artist[64];
};
//@out COMMON
void CLASS tiff_set (ushort *ntag,
ushort tag, ushort type, int count, int val)
{
struct tiff_tag *tt;
int c;
tt = (struct tiff_tag *)(ntag+1) + (*ntag)++;
tt->tag = tag;
tt->type = type;
tt->count = count;
if (type < 3 && count <= 4)
FORC(4) tt->val.c[c] = val >> (c << 3);
else if (type == 3 && count <= 2)
FORC(2) tt->val.s[c] = val >> (c << 4);
else tt->val.i = val;
}
#define TOFF(ptr) ((char *)(&(ptr)) - (char *)th)
void CLASS tiff_head (struct tiff_hdr *th, int full)
{
int c, psize=0;
struct tm *t;
memset (th, 0, sizeof *th);
th->t_order = htonl(0x4d4d4949) >> 16;
th->magic = 42;
th->ifd = 10;
if (full) {
tiff_set (&th->ntag, 254, 4, 1, 0);
tiff_set (&th->ntag, 256, 4, 1, width);
tiff_set (&th->ntag, 257, 4, 1, height);
tiff_set (&th->ntag, 258, 3, colors, output_bps);
if (colors > 2)
th->tag[th->ntag-1].val.i = TOFF(th->bps);
FORC4 th->bps[c] = output_bps;
tiff_set (&th->ntag, 259, 3, 1, 1);
tiff_set (&th->ntag, 262, 3, 1, 1 + (colors > 1));
}
tiff_set (&th->ntag, 270, 2, 512, TOFF(th->t_desc));
tiff_set (&th->ntag, 271, 2, 64, TOFF(th->t_make));
tiff_set (&th->ntag, 272, 2, 64, TOFF(th->t_model));
if (full) {
if (oprof) psize = ntohl(oprof[0]);
tiff_set (&th->ntag, 273, 4, 1, sizeof *th + psize);
tiff_set (&th->ntag, 277, 3, 1, colors);
tiff_set (&th->ntag, 278, 4, 1, height);
tiff_set (&th->ntag, 279, 4, 1, height*width*colors*output_bps/8);
} else
tiff_set (&th->ntag, 274, 3, 1, "12435867"[flip]-'0');
tiff_set (&th->ntag, 282, 5, 1, TOFF(th->rat[0]));
tiff_set (&th->ntag, 283, 5, 1, TOFF(th->rat[2]));
tiff_set (&th->ntag, 284, 3, 1, 1);
tiff_set (&th->ntag, 296, 3, 1, 2);
tiff_set (&th->ntag, 305, 2, 32, TOFF(th->soft));
tiff_set (&th->ntag, 306, 2, 20, TOFF(th->date));
tiff_set (&th->ntag, 315, 2, 64, TOFF(th->t_artist));
tiff_set (&th->ntag, 34665, 4, 1, TOFF(th->nexif));
if (psize) tiff_set (&th->ntag, 34675, 7, psize, sizeof *th);
tiff_set (&th->nexif, 33434, 5, 1, TOFF(th->rat[4]));
tiff_set (&th->nexif, 33437, 5, 1, TOFF(th->rat[6]));
tiff_set (&th->nexif, 34855, 3, 1, iso_speed);
tiff_set (&th->nexif, 37386, 5, 1, TOFF(th->rat[8]));
if (gpsdata[1]) {
tiff_set (&th->ntag, 34853, 4, 1, TOFF(th->ngps));
tiff_set (&th->ngps, 0, 1, 4, 0x202);
tiff_set (&th->ngps, 1, 2, 2, gpsdata[29]);
tiff_set (&th->ngps, 2, 5, 3, TOFF(th->gps[0]));
tiff_set (&th->ngps, 3, 2, 2, gpsdata[30]);
tiff_set (&th->ngps, 4, 5, 3, TOFF(th->gps[6]));
tiff_set (&th->ngps, 5, 1, 1, gpsdata[31]);
tiff_set (&th->ngps, 6, 5, 1, TOFF(th->gps[18]));
tiff_set (&th->ngps, 7, 5, 3, TOFF(th->gps[12]));
tiff_set (&th->ngps, 18, 2, 12, TOFF(th->gps[20]));
tiff_set (&th->ngps, 29, 2, 12, TOFF(th->gps[23]));
memcpy (th->gps, gpsdata, sizeof th->gps);
}
th->rat[0] = th->rat[2] = 300;
th->rat[1] = th->rat[3] = 1;
FORC(6) th->rat[4+c] = 1000000;
th->rat[4] *= shutter;
th->rat[6] *= aperture;
th->rat[8] *= focal_len;
strncpy (th->t_desc, desc, 512);
strncpy (th->t_make, make, 64);
strncpy (th->t_model, model, 64);
strcpy (th->soft, "dcraw v" DCRAW_VERSION);
t = localtime (×tamp);
sprintf (th->date, "%04d:%02d:%02d %02d:%02d:%02d",
t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);
strncpy (th->t_artist, artist, 64);
}
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS jpeg_thumb_writer (FILE *tfp,char *t_humb,int t_humb_length)
{
ushort exif[5];
struct tiff_hdr th;
fputc (0xff, tfp);
fputc (0xd8, tfp);
if (strcmp (t_humb+6, "Exif")) {
memcpy (exif, "\xff\xe1 Exif\0\0", 10);
exif[1] = htons (8 + sizeof th);
fwrite (exif, 1, sizeof exif, tfp);
tiff_head (&th, 0);
fwrite (&th, 1, sizeof th, tfp);
}
fwrite (t_humb+2, 1, t_humb_length-2, tfp);
}
void CLASS jpeg_thumb()
{
char *thumb;
thumb = (char *) malloc (thumb_length);
merror (thumb, "jpeg_thumb()");
fread (thumb, 1, thumb_length, ifp);
jpeg_thumb_writer(ofp,thumb,thumb_length);
free (thumb);
}
#else
void CLASS jpeg_thumb()
{
char *thumb;
ushort exif[5];
struct tiff_hdr th;
thumb = (char *) malloc (thumb_length);
merror (thumb, "jpeg_thumb()");
fread (thumb, 1, thumb_length, ifp);
fputc (0xff, ofp);
fputc (0xd8, ofp);
if (strcmp (thumb+6, "Exif")) {
memcpy (exif, "\xff\xe1 Exif\0\0", 10);
exif[1] = htons (8 + sizeof th);
fwrite (exif, 1, sizeof exif, ofp);
tiff_head (&th, 0);
fwrite (&th, 1, sizeof th, ofp);
}
fwrite (thumb+2, 1, thumb_length-2, ofp);
free (thumb);
}
#endif
void CLASS write_ppm_tiff()
{
struct tiff_hdr th;
uchar *ppm;
ushort *ppm2;
int c, row, col, soff, rstep, cstep;
int perc, val, total, t_white=0x2000;
#ifdef LIBRAW_LIBRARY_BUILD
perc = width * height * auto_bright_thr;
#else
perc = width * height * 0.01; /* 99th percentile white level */
#endif
if (fuji_width) perc /= 2;
if (!((highlight & ~2) || no_auto_bright))
for (t_white=c=0; c < colors; c++) {
for (val=0x2000, total=0; --val > 32; )
if ((total += histogram[c][val]) > perc) break;
if (t_white < val) t_white = val;
}
gamma_curve (gamm[0], gamm[1], 2, (t_white << 3)/bright);
iheight = height;
iwidth = width;
if (flip & 4) SWAP(height,width);
ppm = (uchar *) calloc (width, colors*output_bps/8);
ppm2 = (ushort *) ppm;
merror (ppm, "write_ppm_tiff()");
if (output_tiff) {
tiff_head (&th, 1);
fwrite (&th, sizeof th, 1, ofp);
if (oprof)
fwrite (oprof, ntohl(oprof[0]), 1, ofp);
} else if (colors > 3)
fprintf (ofp,
"P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n",
width, height, colors, (1 << output_bps)-1, cdesc);
else
fprintf (ofp, "P%d\n%d %d\n%d\n",
colors/2+5, width, height, (1 << output_bps)-1);
soff = flip_index (0, 0);
cstep = flip_index (0, 1) - soff;
rstep = flip_index (1, 0) - flip_index (0, width);
for (row=0; row < height; row++, soff += rstep) {
for (col=0; col < width; col++, soff += cstep)
if (output_bps == 8)
FORCC ppm [col*colors+c] = curve[image[soff][c]] >> 8;
else FORCC ppm2[col*colors+c] = curve[image[soff][c]];
if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa)
swab ((char*)ppm2, (char*)ppm2, width*colors*2);
fwrite (ppm, colors*output_bps/8, width, ofp);
}
free (ppm);
}
//@end COMMON
int CLASS main (int argc, const char **argv)
{
int arg, status=0, quality, i, c;
int timestamp_only=0, thumbnail_only=0, identify_only=0;
int user_qual=-1, user_black=-1, user_sat=-1, user_flip=-1;
int use_fuji_rotate=1, write_to_stdout=0, read_from_stdin=0;
const char *sp, *bpfile=0, *dark_frame=0, *write_ext;
char opm, opt, *ofname, *cp;
struct utimbuf ut;
#ifndef NO_LCMS
const char *cam_profile=0, *out_profile=0;
#endif
#ifndef LOCALTIME
putenv ((char *) "TZ=UTC");
#endif
#ifdef LOCALEDIR
setlocale (LC_CTYPE, "");
setlocale (LC_MESSAGES, "");
bindtextdomain ("dcraw", LOCALEDIR);
textdomain ("dcraw");
#endif
if (argc == 1) {
printf(_("\nRaw photo decoder \"dcraw\" v%s"), DCRAW_VERSION);
printf(_("\nby Dave Coffin, dcoffin a cybercom o net\n"));
printf(_("\nUsage: %s [OPTION]... [FILE]...\n\n"), argv[0]);
puts(_("-v Print verbose messages"));
puts(_("-c Write image data to standard output"));
puts(_("-e Extract embedded thumbnail image"));
puts(_("-i Identify files without decoding them"));
puts(_("-i -v Identify files and show metadata"));
puts(_("-z Change file dates to camera timestamp"));
puts(_("-w Use camera white balance, if possible"));
puts(_("-a Average the whole image for white balance"));
puts(_("-A <x y w h> Average a grey box for white balance"));
puts(_("-r <r g b g> Set custom white balance"));
puts(_("+M/-M Use/don't use an embedded color matrix"));
puts(_("-C <r b> Correct chromatic aberration"));
puts(_("-P <file> Fix the dead pixels listed in this file"));
puts(_("-K <file> Subtract dark frame (16-bit raw PGM)"));
puts(_("-k <num> Set the darkness level"));
puts(_("-S <num> Set the saturation level"));
puts(_("-n <num> Set threshold for wavelet denoising"));
puts(_("-H [0-9] Highlight mode (0=clip, 1=unclip, 2=blend, 3+=rebuild)"));
puts(_("-t [0-7] Flip image (0=none, 3=180, 5=90CCW, 6=90CW)"));
puts(_("-o [0-5] Output colorspace (raw,sRGB,Adobe,Wide,ProPhoto,XYZ)"));
#ifndef NO_LCMS
puts(_("-o <file> Apply output ICC profile from file"));
puts(_("-p <file> Apply camera ICC profile from file or \"embed\""));
#endif
puts(_("-d Document mode (no color, no interpolation)"));
puts(_("-D Document mode without scaling (totally raw)"));
puts(_("-j Don't stretch or rotate raw pixels"));
puts(_("-W Don't automatically brighten the image"));
puts(_("-b <num> Adjust brightness (default = 1.0)"));
puts(_("-g <p ts> Set custom gamma curve (default = 2.222 4.5)"));
puts(_("-q [0-3] Set the interpolation quality"));
puts(_("-h Half-size color image (twice as fast as \"-q 0\")"));
puts(_("-f Interpolate RGGB as four colors"));
puts(_("-m <num> Apply a 3x3 median filter to R-G and B-G"));
puts(_("-s [0..N-1] Select one raw image or \"all\" from each file"));
puts(_("-6 Write 16-bit instead of 8-bit"));
puts(_("-4 Linear 16-bit, same as \"-6 -W -g 1 1\""));
puts(_("-T Write TIFF instead of PPM"));
puts("");
return 1;
}
argv[argc] = "";
for (arg=1; (((opm = argv[arg][0]) - 2) | 2) == '+'; ) {
opt = argv[arg++][1];
if ((cp = (char *) strchr (sp="nbrkStqmHACg", opt)))
for (i=0; i < "114111111422"[cp-sp]-'0'; i++)
if (!isdigit(argv[arg+i][0])) {
fprintf (stderr,_("Non-numeric argument to \"-%c\"\n"), opt);
return 1;
}
switch (opt) {
case 'n': threshold = atof(argv[arg++]); break;
case 'b': bright = atof(argv[arg++]); break;
case 'r':
FORC4 user_mul[c] = atof(argv[arg++]); break;
case 'C': aber[0] = 1 / atof(argv[arg++]);
aber[2] = 1 / atof(argv[arg++]); break;
case 'g': gamm[0] = atof(argv[arg++]);
gamm[1] = atof(argv[arg++]);
if (gamm[0]) gamm[0] = 1/gamm[0]; break;
case 'k': user_black = atoi(argv[arg++]); break;
case 'S': user_sat = atoi(argv[arg++]); break;
case 't': user_flip = atoi(argv[arg++]); break;
case 'q': user_qual = atoi(argv[arg++]); break;
case 'm': med_passes = atoi(argv[arg++]); break;
case 'H': highlight = atoi(argv[arg++]); break;
case 's':
shot_select = abs(atoi(argv[arg]));
multi_out = !strcmp(argv[arg++],"all");
break;
case 'o':
if (isdigit(argv[arg][0]) && !argv[arg][1])
output_color = atoi(argv[arg++]);
#ifndef NO_LCMS
else out_profile = argv[arg++];
break;
case 'p': cam_profile = argv[arg++];
#endif
break;
case 'P': bpfile = argv[arg++]; break;
case 'K': dark_frame = argv[arg++]; break;
case 'z': timestamp_only = 1; break;
case 'e': thumbnail_only = 1; break;
case 'i': identify_only = 1; break;
case 'c': write_to_stdout = 1; break;
case 'v': verbose = 1; break;
case 'h': half_size = 1; break;
case 'f': four_color_rgb = 1; break;
case 'A': FORC4 greybox[c] = atoi(argv[arg++]);
case 'a': use_auto_wb = 1; break;
case 'w': use_camera_wb = 1; break;
case 'M': use_camera_matrix = 3 * (opm == '+'); break;
case 'I': read_from_stdin = 1; break;
case 'E': document_mode++;
case 'D': document_mode++;
case 'd': document_mode++;
case 'j': use_fuji_rotate = 0; break;
case 'W': no_auto_bright = 1; break;
case 'T': output_tiff = 1; break;
case '4': gamm[0] = gamm[1] =
no_auto_bright = 1;
case '6': output_bps = 16; break;
default:
fprintf (stderr,_("Unknown option \"-%c\".\n"), opt);
return 1;
}
}
if (arg == argc) {
fprintf (stderr,_("No files to process.\n"));
return 1;
}
if (write_to_stdout) {
if (isatty(1)) {
fprintf (stderr,_("Will not write an image to the terminal!\n"));
return 1;
}
#if defined(WIN32) || defined(DJGPP) || defined(__CYGWIN__)
if (setmode(1,O_BINARY) < 0) {
perror ("setmode()");
return 1;
}
#endif
}
for ( ; arg < argc; arg++) {
status = 1;
raw_image = 0;
image = 0;
oprof = 0;
meta_data = ofname = 0;
ofp = stdout;
if (setjmp (failure)) {
if (fileno(ifp) > 2) fclose(ifp);
if (fileno(ofp) > 2) fclose(ofp);
status = 1;
goto cleanup;
}
ifname = argv[arg];
if (!(ifp = fopen (ifname, "rb"))) {
perror (ifname);
continue;
}
status = (identify(),!is_raw);
if (user_flip >= 0)
flip = user_flip;
switch ((flip+3600) % 360) {
case 270: flip = 5; break;
case 180: flip = 3; break;
case 90: flip = 6;
}
if (timestamp_only) {
if ((status = !timestamp))
fprintf (stderr,_("%s has no timestamp.\n"), ifname);
else if (identify_only)
printf ("%10ld%10d %s\n", (long) timestamp, shot_order, ifname);
else {
if (verbose)
fprintf (stderr,_("%s time set to %d.\n"), ifname, (int) timestamp);
ut.actime = ut.modtime = timestamp;
utime (ifname, &ut);
}
goto next;
}
write_fun = &CLASS write_ppm_tiff;
if (thumbnail_only) {
if ((status = !thumb_offset)) {
fprintf (stderr,_("%s has no thumbnail.\n"), ifname);
goto next;
} else if (thumb_load_raw) {
load_raw = thumb_load_raw;
data_offset = thumb_offset;
height = thumb_height;
width = thumb_width;
filters = 0;
colors = 3;
} else {
fseek (ifp, thumb_offset, SEEK_SET);
write_fun = write_thumb;
goto thumbnail;
}
}
if (load_raw == &CLASS kodak_ycbcr_load_raw) {
height += height & 1;
width += width & 1;
}
if (identify_only && verbose && make[0]) {
printf (_("\nFilename: %s\n"), ifname);
printf (_("Timestamp: %s"), ctime(×tamp));
printf (_("Camera: %s %s\n"), make, model);
if (artist[0])
printf (_("Owner: %s\n"), artist);
if (dng_version) {
printf (_("DNG Version: "));
for (i=24; i >= 0; i -= 8)
printf ("%d%c", dng_version >> i & 255, i ? '.':'\n');
}
printf (_("ISO speed: %d\n"), (int) iso_speed);
printf (_("Shutter: "));
if (shutter > 0 && shutter < 1)
shutter = (printf ("1/"), 1 / shutter);
printf (_("%0.1f sec\n"), shutter);
printf (_("Aperture: f/%0.1f\n"), aperture);
printf (_("Focal length: %0.1f mm\n"), focal_len);
printf (_("Embedded ICC profile: %s\n"), profile_length ? _("yes"):_("no"));
printf (_("Number of raw images: %d\n"), is_raw);
if (pixel_aspect != 1)
printf (_("Pixel Aspect Ratio: %0.6f\n"), pixel_aspect);
if (thumb_offset)
printf (_("Thumb size: %4d x %d\n"), thumb_width, thumb_height);
printf (_("Full size: %4d x %d\n"), raw_width, raw_height);
} else if (!is_raw)
fprintf (stderr,_("Cannot decode file %s\n"), ifname);
if (!is_raw) goto next;
shrink = filters && (half_size || (!identify_only &&
(threshold || aber[0] != 1 || aber[2] != 1)));
iheight = (height + shrink) >> shrink;
iwidth = (width + shrink) >> shrink;
if (identify_only) {
if (verbose) {
if (document_mode == 3) {
top_margin = left_margin = fuji_width = 0;
height = raw_height;
width = raw_width;
}
iheight = (height + shrink) >> shrink;
iwidth = (width + shrink) >> shrink;
if (use_fuji_rotate) {
if (fuji_width) {
fuji_width = (fuji_width - 1 + shrink) >> shrink;
iwidth = fuji_width / sqrt(0.5);
iheight = (iheight - fuji_width) / sqrt(0.5);
} else {
if (pixel_aspect < 1) iheight = iheight / pixel_aspect + 0.5;
if (pixel_aspect > 1) iwidth = iwidth * pixel_aspect + 0.5;
}
}
if (flip & 4)
SWAP(iheight,iwidth);
printf (_("Image size: %4d x %d\n"), width, height);
printf (_("Output size: %4d x %d\n"), iwidth, iheight);
printf (_("Raw colors: %d"), colors);
if (filters) {
int fhigh = 2, fwide = 2;
if ((filters ^ (filters >> 8)) & 0xff) fhigh = 4;
if ((filters ^ (filters >> 16)) & 0xffff) fhigh = 8;
if (filters == 1) fhigh = fwide = 16;
if (filters == 9) fhigh = fwide = 6;
printf (_("\nFilter pattern: "));
for (i=0; i < fhigh; i++)
for (c = i && putchar('/') && 0; c < fwide; c++)
putchar (cdesc[fcol(i,c)]);
}
printf (_("\nDaylight multipliers:"));
FORCC printf (" %f", pre_mul[c]);
if (cam_mul[0] > 0) {
printf (_("\nCamera multipliers:"));
FORC4 printf (" %f", cam_mul[c]);
}
putchar ('\n');
} else
printf (_("%s is a %s %s image.\n"), ifname, make, model);
next:
fclose(ifp);
continue;
}
if (meta_length) {
meta_data = (char *) malloc (meta_length);
merror (meta_data, "main()");
}
if (filters || colors == 1) {
raw_image = (ushort *) calloc ((raw_height+7), raw_width*2);
merror (raw_image, "main()");
} else {
image = (ushort (*)[4]) calloc (iheight, iwidth*sizeof *image);
merror (image, "main()");
}
if (verbose)
fprintf (stderr,_("Loading %s %s image from %s ...\n"),
make, model, ifname);
if (shot_select >= is_raw)
fprintf (stderr,_("%s: \"-s %d\" requests a nonexistent image!\n"),
ifname, shot_select);
fseeko (ifp, data_offset, SEEK_SET);
if (raw_image && read_from_stdin)
fread (raw_image, 2, raw_height*raw_width, stdin);
else (*load_raw)();
if (document_mode == 3) {
top_margin = left_margin = fuji_width = 0;
height = raw_height;
width = raw_width;
}
iheight = (height + shrink) >> shrink;
iwidth = (width + shrink) >> shrink;
if (raw_image) {
image = (ushort (*)[4]) calloc (iheight, iwidth*sizeof *image);
merror (image, "main()");
crop_masked_pixels();
free (raw_image);
}
if (zero_is_bad) remove_zeroes();
bad_pixels (bpfile);
if (dark_frame) subtract (dark_frame);
quality = 2 + !fuji_width;
if (user_qual >= 0) quality = user_qual;
i = cblack[3];
FORC3 if (i > cblack[c]) i = cblack[c];
FORC4 cblack[c] -= i;
black += i;
i = cblack[6];
FORC (cblack[4] * cblack[5])
if (i > cblack[6+c]) i = cblack[6+c];
FORC (cblack[4] * cblack[5])
cblack[6+c] -= i;
black += i;
if (user_black >= 0) black = user_black;
FORC4 cblack[c] += black;
if (user_sat > 0) maximum = user_sat;
#ifdef COLORCHECK
colorcheck();
#endif
if (is_foveon) {
if (document_mode || load_raw == &CLASS foveon_dp_load_raw) {
for (i=0; i < height*width*4; i++)
if ((short) image[0][i] < 0) image[0][i] = 0;
} else foveon_interpolate();
} else if (document_mode < 2)
scale_colors();
pre_interpolate();
if (filters && !document_mode) {
if (quality == 0)
lin_interpolate();
else if (quality == 1 || colors > 3)
vng_interpolate();
else if (quality == 2 && filters > 1000)
ppg_interpolate();
else if (filters == 9)
xtrans_interpolate (quality*2-3);
else
ahd_interpolate();
}
if (mix_green)
for (colors=3, i=0; i < height*width; i++)
image[i][1] = (image[i][1] + image[i][3]) >> 1;
if (!is_foveon && colors == 3) median_filter();
if (!is_foveon && highlight == 2) blend_highlights();
if (!is_foveon && highlight > 2) recover_highlights();
if (use_fuji_rotate) fuji_rotate();
#ifndef NO_LCMS
if (cam_profile) apply_profile (cam_profile, out_profile);
#endif
convert_to_rgb();
if (use_fuji_rotate) stretch();
thumbnail:
if (write_fun == &CLASS jpeg_thumb)
write_ext = ".jpg";
else if (output_tiff && write_fun == &CLASS write_ppm_tiff)
write_ext = ".tiff";
else
write_ext = ".pgm\0.ppm\0.ppm\0.pam" + colors*5-5;
ofname = (char *) malloc (strlen(ifname) + 64);
merror (ofname, "main()");
if (write_to_stdout)
strcpy (ofname,_("standard output"));
else {
strcpy (ofname, ifname);
if ((cp = strrchr (ofname, '.'))) *cp = 0;
if (multi_out)
sprintf (ofname+strlen(ofname), "_%0*d",
snprintf(0,0,"%d",is_raw-1), shot_select);
if (thumbnail_only)
strcat (ofname, ".thumb");
strcat (ofname, write_ext);
ofp = fopen (ofname, "wb");
if (!ofp) {
status = 1;
perror (ofname);
goto cleanup;
}
}
if (verbose)
fprintf (stderr,_("Writing data to %s ...\n"), ofname);
(*write_fun)();
fclose(ifp);
if (ofp != stdout) fclose(ofp);
cleanup:
if (meta_data) free (meta_data);
if (ofname) free (ofname);
if (oprof) free (oprof);
if (image) free (image);
if (multi_out) {
if (++shot_select < is_raw) arg--;
else shot_select = 0;
}
}
return status;
}
#endif
| gpl-3.0 |
bert/src-highlite | lib/srchilite/sourcehighlighter.cpp | 4 | 7811 | //
// Author: Lorenzo Bettini <http://www.lorenzobettini.it>, (C) 2004-2008
//
// Copyright: See COPYING file that comes with this distribution
//
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "sourcehighlighter.h"
#include "highlighttoken.h"
#include "matchingparameters.h"
#include "highlightrule.h"
#include "formattermanager.h"
#include "highlightevent.h"
#include "highlighteventlistener.h"
#include "formatterparams.h"
using namespace std;
namespace srchilite {
/// represents highlighting as default
static HighlightToken defaultHighlightToken;
static HighlightEvent defaultHighlightEvent(defaultHighlightToken,
HighlightEvent::FORMATDEFAULT);
/// avoid generate an event if there's no one listening
#define GENERATE_EVENT(token, type) if (hasListeners()) notify(HighlightEvent(token, type));
#define GENERATE_DEFAULT_EVENT(s) \
if (hasListeners()) { \
defaultHighlightToken.clearMatched(); \
defaultHighlightToken.addMatched("default", s); \
notify(defaultHighlightEvent); \
}
#define UPDATE_START_IN_FORMATTER_PARAMS(start_index) if (formatterParams) formatterParams->start = start_index;
SourceHighlighter::SourceHighlighter(HighlightStatePtr mainState) :
mainHighlightState(mainState), currentHighlightState(mainState),
stateStack(HighlightStateStackPtr(new HighlightStateStack)),
formatterManager(0), optimize(false), suspended(false),
formatterParams(0) {
}
SourceHighlighter::~SourceHighlighter() {
}
void SourceHighlighter::highlightParagraph(const std::string ¶graph) {
std::string::const_iterator start = paragraph.begin();
std::string::const_iterator end = paragraph.end();
bool matched = true;
HighlightToken token;
MatchingParameters params;
// we're at the beginning
UPDATE_START_IN_FORMATTER_PARAMS(0);
// note that we go on even if the string is empty, since it is crucial
// to try to match also the end of buffer (some rules rely on that)
while (matched) {
matched = currentHighlightState->findBestMatch(start, end, token,
params);
if (matched) {
if (token.prefix.size()) {
// this is the index in the paragraph of the matched part
UPDATE_START_IN_FORMATTER_PARAMS((std::distance(paragraph.begin(), start)));
// format non matched part with the current state's default element
format(currentHighlightState->getDefaultElement(), token.prefix);
GENERATE_DEFAULT_EVENT(token.prefix);
}
// the length of the previous matched string in the matched elem list
int prevLen = 0;
// now format the matched strings
for (MatchedElements::const_iterator it = token.matched.begin(); it
!= token.matched.end(); ++it) {
// this is the index in the paragraph of the matched part
UPDATE_START_IN_FORMATTER_PARAMS((std::distance(paragraph.begin(), start) + token.prefix.size() + prevLen));
format(it->first, it->second);
GENERATE_EVENT(token, HighlightEvent::FORMAT);
prevLen += it->second.size();
}
// now we're not at the beginning of line anymore, if we matched some chars
if (token.matchedSize)
params.beginningOfLine = false;
// check whether we must enter a new state
HighlightStatePtr nextState = getNextState(token);
if (nextState.get()) {
enterState(nextState);
GENERATE_EVENT(token, HighlightEvent::ENTERSTATE);
} else if (token.rule->getExitLevel()) {
// the rule requires to exit some states
if (token.rule->getExitLevel() < 0) {
exitAll();
} else {
exitState(token.rule->getExitLevel());
}
GENERATE_EVENT(token, HighlightEvent::EXITSTATE);
}
// advance in the string, so that the part not matched
// can be highlighted in the next loop
start += (token.prefix.size() + token.matchedSize);
} else {
// no rule matched, so we highlight it with the current state's default element
// provided the string is not empty (if it is empty this is really useless)
if (start != end) {
// this is the index in the paragraph of the matched part
UPDATE_START_IN_FORMATTER_PARAMS((std::distance(paragraph.begin(), start)));
const string s(start, end);
format(currentHighlightState->getDefaultElement(), s);
GENERATE_DEFAULT_EVENT(s);
}
}
}
if (optimize)
flush(); // flush what we have buffered
}
HighlightStatePtr SourceHighlighter::getNextState(const HighlightToken &token) {
HighlightStatePtr nextState = token.rule->getNextState();
if (token.rule->isNested()) {
// we must enter another instance of the current state
nextState = currentHighlightState;
}
if (nextState.get() && nextState->getNeedsReferenceReplacement()) {
// perform replacement for the next state
// in case use the original state
if (nextState->getOriginalState().get()) {
// in case we had already performed replacements on the next state
nextState = nextState->getOriginalState();
}
HighlightStatePtr copyState = HighlightStatePtr(new HighlightState(
*nextState));
copyState->setOriginalState(nextState);
copyState->replaceReferences(token.matchedSubExps);
return copyState;
}
return nextState;
}
void SourceHighlighter::enterState(HighlightStatePtr state) {
stateStack->push(currentHighlightState);
currentHighlightState = state;
}
/**
* Exits level states (-1 means exit all states)
* @param level
*/
void SourceHighlighter::exitState(int level) {
// remove additional levels
for (int l = 1; l < level; ++l)
stateStack->pop();
currentHighlightState = stateStack->top();
stateStack->pop();
}
void SourceHighlighter::exitAll() {
currentHighlightState = mainHighlightState;
clearStateStack();
}
void SourceHighlighter::clearStateStack() {
while (!stateStack->empty())
stateStack->pop();
}
void SourceHighlighter::format(const std::string &elem, const std::string &s) {
if (suspended)
return;
if (!s.size())
return;
// the formatter is allowed to be null
if (formatterManager) {
if (!optimize) {
formatterManager->getFormatter(elem)->format(s, formatterParams);
} else {
// otherwise we optmize output generation: delay formatting a specific
// element until we deal with another element; this way strings that belong
// to the same element are formatted using only one tag: e.g.,
// <comment>/* mycomment */</comment>
// instead of
// <comment>/*</comment><comment>mycomment</comment><comment>*/</comment>
if (elem != currentElement) {
if (currentElement.size())
flush();
}
currentElement = elem;
currentElementBuffer << s;
}
}
}
void SourceHighlighter::flush() {
if (formatterManager) {
// flush the buffer for the current element
formatterManager->getFormatter(currentElement)->format(
currentElementBuffer.str(), formatterParams);
// reset current element information
currentElement = "";
currentElementBuffer.str("");
}
}
}
| gpl-3.0 |
Mkaysi/weechat | src/gui/curses/gui-curses-main.c | 4 | 13270 | /*
* gui-curses-main.c - main loop for Curses GUI
*
* Copyright (C) 2003-2015 Sébastien Helleu <flashcode@flashtux.org>
*
* This file is part of WeeChat, the extensible chat client.
*
* WeeChat 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 3 of the License, or
* (at your option) any later version.
*
* WeeChat 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 WeeChat. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <time.h>
#include "../../core/weechat.h"
#include "../../core/wee-command.h"
#include "../../core/wee-config.h"
#include "../../core/wee-hook.h"
#include "../../core/wee-log.h"
#include "../../core/wee-string.h"
#include "../../core/wee-utf8.h"
#include "../../core/wee-util.h"
#include "../../core/wee-version.h"
#include "../../plugins/plugin.h"
#include "../gui-main.h"
#include "../gui-bar.h"
#include "../gui-bar-item.h"
#include "../gui-bar-window.h"
#include "../gui-buffer.h"
#include "../gui-chat.h"
#include "../gui-color.h"
#include "../gui-cursor.h"
#include "../gui-filter.h"
#include "../gui-hotlist.h"
#include "../gui-input.h"
#include "../gui-layout.h"
#include "../gui-line.h"
#include "../gui-history.h"
#include "../gui-mouse.h"
#include "../gui-nicklist.h"
#include "../gui-window.h"
#include "gui-curses.h"
int gui_signal_sigwinch_received = 0; /* sigwinch signal (term resized) */
int gui_term_cols = 0; /* number of columns in terminal */
int gui_term_lines = 0; /* number of lines in terminal */
/*
* Gets a password from user (called on startup, when GUI is not initialized).
*
* The result is stored in "password" with max "size" bytes (including the
* final '\0').
*/
void
gui_main_get_password (const char **prompt, char *password, int size)
{
int line, i, ch;
initscr ();
cbreak ();
noecho ();
raw ();
clear();
line = 0;
while (prompt[line])
{
mvaddstr (line, 0, prompt[line]);
line++;
}
mvaddstr (line, 0, "=> ");
refresh ();
memset (password, '\0', size);
i = 0;
while (i < size - 1)
{
ch = getch ();
/* enter */
if (ch == '\n')
break;
/* ctrl-C */
if (ch == 3)
{
password[0] = 3;
i = 1;
break;
}
if (ch == 127)
{
if (i > 0)
{
i--;
password[i] = '\0';
mvaddstr (line, 3 + i, " ");
move (line, 3 + i);
}
}
else
{
password[i] = ch;
mvaddstr (line, 3 + i, "*");
i++;
}
refresh ();
}
password[i] = '\0';
refresh ();
endwin ();
}
/*
* Initializes GUI.
*/
void
gui_main_init ()
{
struct t_gui_buffer *ptr_buffer;
struct t_gui_bar *ptr_bar;
struct t_gui_bar_window *ptr_bar_win;
char title[256];
initscr ();
if (CONFIG_BOOLEAN(config_look_eat_newline_glitch))
gui_term_set_eat_newline_glitch (0);
curs_set (1);
noecho ();
nodelay (stdscr, TRUE);
raw ();
gui_color_alloc ();
/* build prefixes according to configuration */
gui_chat_prefix_build ();
refresh ();
gui_term_cols = COLS;
gui_term_lines = LINES;
gui_window_read_terminal_size ();
/* init clipboard buffer */
gui_input_clipboard = NULL;
/* get time length */
gui_chat_time_length = gui_chat_get_time_length ();
/* init bar items */
gui_bar_item_init ();
gui_init_ok = 0;
/* create core buffer */
ptr_buffer = gui_buffer_new (NULL, GUI_BUFFER_MAIN,
NULL, NULL, NULL, NULL);
if (ptr_buffer)
{
gui_init_ok = 1;
ptr_buffer->num_displayed = 1;
/* set short name */
if (!ptr_buffer->short_name)
ptr_buffer->short_name = strdup (GUI_BUFFER_MAIN);
/* set title for core buffer */
snprintf (title, sizeof (title), "WeeChat %s %s - %s",
version_get_version (),
WEECHAT_COPYRIGHT_DATE,
WEECHAT_WEBSITE);
gui_buffer_set_title (ptr_buffer, title);
/* create main window (using full space) */
if (gui_window_new (NULL, ptr_buffer, 0, 0,
gui_term_cols, gui_term_lines, 100, 100))
{
gui_current_window = gui_windows;
if (CONFIG_STRING(config_look_window_title)
&& CONFIG_STRING(config_look_window_title)[0])
{
gui_window_set_title (CONFIG_STRING(config_look_window_title));
}
}
/*
* create bar windows for root bars (they were read from config,
* but no window was created, GUI was not initialized)
*/
for (ptr_bar = gui_bars; ptr_bar; ptr_bar = ptr_bar->next_bar)
{
if ((CONFIG_INTEGER(ptr_bar->options[GUI_BAR_OPTION_TYPE]) == GUI_BAR_TYPE_ROOT)
&& (!ptr_bar->bar_window))
{
gui_bar_window_new (ptr_bar, NULL);
}
}
for (ptr_bar_win = gui_windows->bar_windows;
ptr_bar_win; ptr_bar_win = ptr_bar_win->next_bar_window)
{
gui_bar_window_calculate_pos_size (ptr_bar_win, gui_windows);
gui_bar_window_create_win (ptr_bar_win);
}
}
if (CONFIG_BOOLEAN(config_look_mouse))
gui_mouse_enable ();
else
gui_mouse_disable ();
gui_window_set_bracketed_paste_mode (CONFIG_BOOLEAN(config_look_paste_bracketed));
}
/*
* Callback for system signal SIGWINCH: refreshes screen.
*/
void
gui_main_signal_sigwinch ()
{
gui_signal_sigwinch_received = 1;
gui_window_ask_refresh (2);
}
/*
* Displays infos about ncurses lib.
*/
void
gui_main_debug_libs ()
{
#if defined(NCURSES_VERSION) && defined(NCURSES_VERSION_PATCH)
gui_chat_printf (NULL, " ncurses: %s (patch %d)",
NCURSES_VERSION, NCURSES_VERSION_PATCH);
#else
gui_chat_printf (NULL, " ncurses: (?)");
#endif /* defined(NCURSES_VERSION) && defined(NCURSES_VERSION_PATCH) */
}
/*
* Refreshs for windows, buffers, bars.
*/
void
gui_main_refreshs ()
{
struct t_gui_window *ptr_win;
struct t_gui_buffer *ptr_buffer;
struct t_gui_bar *ptr_bar;
/* refresh color buffer if needed */
if (gui_color_buffer_refresh_needed)
{
gui_color_buffer_display ();
gui_color_buffer_refresh_needed = 0;
}
/* compute max length for prefix/buffer if needed */
for (ptr_buffer = gui_buffers; ptr_buffer;
ptr_buffer = ptr_buffer->next_buffer)
{
/* compute buffer/prefix max length for own_lines */
if (ptr_buffer->own_lines)
{
if (ptr_buffer->own_lines->buffer_max_length_refresh)
{
gui_line_compute_buffer_max_length (ptr_buffer,
ptr_buffer->own_lines);
}
if (ptr_buffer->own_lines->prefix_max_length_refresh)
gui_line_compute_prefix_max_length (ptr_buffer->own_lines);
}
/* compute buffer/prefix max length for mixed_lines */
if (ptr_buffer->mixed_lines)
{
if (ptr_buffer->mixed_lines->buffer_max_length_refresh)
{
gui_line_compute_buffer_max_length (ptr_buffer,
ptr_buffer->mixed_lines);
}
if (ptr_buffer->mixed_lines->prefix_max_length_refresh)
gui_line_compute_prefix_max_length (ptr_buffer->mixed_lines);
}
}
/* refresh window if needed */
if (gui_window_refresh_needed)
{
gui_window_refresh_screen ((gui_window_refresh_needed > 1) ? 1 : 0);
gui_window_refresh_needed = 0;
}
/* refresh bars if needed */
for (ptr_bar = gui_bars; ptr_bar; ptr_bar = ptr_bar->next_bar)
{
if (ptr_bar->bar_refresh_needed)
gui_bar_draw (ptr_bar);
}
/* refresh window if needed (if asked during refresh of bars) */
if (gui_window_refresh_needed)
{
gui_window_refresh_screen ((gui_window_refresh_needed > 1) ? 1 : 0);
gui_window_refresh_needed = 0;
}
/* refresh windows if needed */
for (ptr_win = gui_windows; ptr_win; ptr_win = ptr_win->next_window)
{
if (ptr_win->refresh_needed)
{
gui_window_switch_to_buffer (ptr_win, ptr_win->buffer, 0);
gui_chat_draw (ptr_win->buffer, 1);
ptr_win->refresh_needed = 0;
}
}
/* refresh chat buffers if needed */
for (ptr_buffer = gui_buffers; ptr_buffer;
ptr_buffer = ptr_buffer->next_buffer)
{
if (ptr_buffer->chat_refresh_needed)
{
gui_chat_draw (ptr_buffer,
(ptr_buffer->chat_refresh_needed) > 1 ? 1 : 0);
}
}
if (!gui_window_bare_display)
{
/* refresh bars if needed */
for (ptr_bar = gui_bars; ptr_bar; ptr_bar = ptr_bar->next_bar)
{
if (ptr_bar->bar_refresh_needed)
{
gui_bar_draw (ptr_bar);
}
}
/* move cursor (for cursor mode) */
if (gui_cursor_mode)
gui_window_move_cursor ();
}
}
/*
* Main loop for WeeChat with ncurses GUI.
*/
void
gui_main_loop ()
{
struct t_hook *hook_fd_keyboard;
/* catch SIGWINCH signal: redraw screen */
util_catch_signal (SIGWINCH, &gui_main_signal_sigwinch);
/* hook stdin (read keyboard) */
hook_fd_keyboard = hook_fd (NULL, STDIN_FILENO, 1, 0, 0,
&gui_key_read_cb, NULL);
gui_window_ask_refresh (1);
while (!weechat_quit)
{
/* execute timer hooks */
hook_timer_exec ();
/* auto reset of color pairs */
if (gui_color_pairs_auto_reset)
{
gui_color_reset_pairs ();
gui_color_pairs_auto_reset_last = time (NULL);
gui_color_pairs_auto_reset = 0;
gui_color_pairs_auto_reset_pending = 1;
}
gui_main_refreshs ();
if (gui_window_refresh_needed && !gui_window_bare_display)
gui_main_refreshs ();
if (gui_signal_sigwinch_received)
{
(void) hook_signal_send ("signal_sigwinch",
WEECHAT_HOOK_SIGNAL_STRING, NULL);
gui_signal_sigwinch_received = 0;
}
gui_color_pairs_auto_reset_pending = 0;
/* execute fd hooks */
hook_fd_exec ();
}
/* remove keyboard hook */
unhook (hook_fd_keyboard);
}
/*
* Ends GUI.
*
* Argument "clean_exit" is 0 when WeeChat is crashing (we don't clean objects
* because WeeChat can crash again during this cleanup...).
*/
void
gui_main_end (int clean_exit)
{
if (clean_exit)
{
/*
* final refreshs, to see messages just before exiting
* (if we are upgrading, don't refresh anything!)
*/
if (!weechat_upgrading)
{
gui_main_refreshs ();
if (gui_window_refresh_needed)
gui_main_refreshs ();
}
/* disable bracketed paste mode */
gui_window_set_bracketed_paste_mode (0);
/* disable mouse */
gui_mouse_disable ();
/* remove bar items and bars */
gui_bar_item_end ();
gui_bar_free_all ();
/* remove filters */
gui_filter_free_all ();
/* free clipboard buffer */
if (gui_input_clipboard)
free (gui_input_clipboard);
/* delete layouts */
gui_layout_remove_all ();
/* delete all windows */
while (gui_windows)
{
gui_window_free (gui_windows);
}
gui_window_tree_free (&gui_windows_tree);
/* delete all buffers */
while (gui_buffers)
{
gui_buffer_close (gui_buffers);
}
gui_init_ok = 0;
/* delete global history */
gui_history_global_free ();
/* reset title */
if (CONFIG_STRING(config_look_window_title)
&& CONFIG_STRING(config_look_window_title)[0])
{
gui_window_set_title (NULL);
}
/* end color */
gui_color_end ();
/* free some variables used for chat area */
gui_chat_end ();
/* free some variables used for nicklist */
gui_nicklist_end ();
/* free some variables used for hotlist */
gui_hotlist_end ();
}
/* end of Curses output */
refresh ();
endwin ();
}
| gpl-3.0 |
daydaygit/flrelse | linux-3.0.1/arch/arm/plat-samsung/dev-keypad.c | 4 | 1329 | /*
* linux/arch/arm/plat-samsung/dev-keypad.c
*
* Copyright (C) 2010 Samsung Electronics Co.Ltd
* Author: Joonyoung Shim <jy0922.shim@samsung.com>
*
* 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.
*
*/
#include <linux/platform_device.h>
#include <mach/irqs.h>
#include <mach/map.h>
#include <plat/cpu.h>
#include <plat/devs.h>
#include <plat/keypad.h>
static struct resource samsung_keypad_resources[] = {
[0] = {
.start = SAMSUNG_PA_KEYPAD,
.end = SAMSUNG_PA_KEYPAD + 0x20 - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_KEYPAD,
.end = IRQ_KEYPAD,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device samsung_device_keypad = {
.name = "s3c-keypad",
.id = -1,
.num_resources = ARRAY_SIZE(samsung_keypad_resources),
.resource = samsung_keypad_resources,
};
EXPORT_SYMBOL(samsung_device_keypad);
void __init samsung_keypad_set_platdata(struct samsung_keypad_platdata *pd)
{
struct samsung_keypad_platdata *npd;
npd = s3c_set_platdata(pd, sizeof(struct samsung_keypad_platdata),
&samsung_device_keypad);
if (!npd->cfg_gpio)
npd->cfg_gpio = samsung_keypad_cfg_gpio;
}
| gpl-3.0 |
libretro/bsnes-mercury | phoenix/qt/widget/radio-button.cpp | 5 | 2476 | namespace phoenix {
Size pRadioButton::minimumSize() {
Size size = pFont::size(qtWidget->font(), radioButton.state.text);
if(radioButton.state.orientation == Orientation::Horizontal) {
size.width += radioButton.state.image.width;
size.height = max(radioButton.state.image.height, size.height);
}
if(radioButton.state.orientation == Orientation::Vertical) {
size.width = max(radioButton.state.image.width, size.width);
size.height += radioButton.state.image.height;
}
return {size.width + 20, size.height + 12};
}
void pRadioButton::setChecked() {
parent().locked = true;
for(auto& item : radioButton.state.group) {
bool checked = &item.p == this;
item.p.qtRadioButton->setChecked(item.state.checked = checked);
}
parent().locked = false;
}
void pRadioButton::setGroup(const group<RadioButton>& group) {
parent().locked = true;
for(auto& item : radioButton.state.group) {
item.p.qtRadioButton->setChecked(item.state.checked);
}
parent().locked = false;
}
void pRadioButton::setImage(const image& image, Orientation orientation) {
qtRadioButton->setIconSize(QSize(image.width, image.height));
qtRadioButton->setIcon(CreateIcon(image));
qtRadioButton->setStyleSheet("text-align: top;");
switch(orientation) {
case Orientation::Horizontal: qtRadioButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); break;
case Orientation::Vertical: qtRadioButton->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); break;
}
}
void pRadioButton::setText(string text) {
qtRadioButton->setText(QString::fromUtf8(text));
}
pRadioButton& pRadioButton::parent() {
if(radioButton.state.group.size()) return radioButton.state.group.first().p;
return *this;
}
void pRadioButton::constructor() {
qtWidget = qtRadioButton = new QToolButton;
qtRadioButton->setCheckable(true);
qtRadioButton->setToolButtonStyle(Qt::ToolButtonTextOnly);
connect(qtRadioButton, SIGNAL(toggled(bool)), SLOT(onActivate()));
pWidget::synchronizeState();
setGroup(radioButton.state.group);
setText(radioButton.state.text);
}
void pRadioButton::destructor() {
if(qtRadioButton) delete qtRadioButton;
qtWidget = qtRadioButton = nullptr;
}
void pRadioButton::orphan() {
destructor();
constructor();
}
void pRadioButton::onActivate() {
if(parent().locked) return;
bool wasChecked = radioButton.state.checked;
setChecked();
if(!wasChecked) {
if(radioButton.onActivate) radioButton.onActivate();
}
}
}
| gpl-3.0 |
zero-ui/miniblink49 | node/v8_inspector/platform/v8_inspector/V8DebuggerAgentImpl.cpp | 5 | 48706 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "platform/v8_inspector/V8DebuggerAgentImpl.h"
#include "platform/inspector_protocol/Parser.h"
#include "platform/inspector_protocol/String16.h"
#include "platform/inspector_protocol/Values.h"
#include "platform/v8_inspector/InjectedScript.h"
#include "platform/v8_inspector/InspectedContext.h"
#include "platform/v8_inspector/JavaScriptCallFrame.h"
#include "platform/v8_inspector/RemoteObjectId.h"
#include "platform/v8_inspector/ScriptBreakpoint.h"
#include "platform/v8_inspector/V8Debugger.h"
#include "platform/v8_inspector/V8DebuggerScript.h"
#include "platform/v8_inspector/V8InspectorImpl.h"
#include "platform/v8_inspector/V8InspectorSessionImpl.h"
#include "platform/v8_inspector/V8Regex.h"
#include "platform/v8_inspector/V8RuntimeAgentImpl.h"
#include "platform/v8_inspector/V8StackTraceImpl.h"
#include "platform/v8_inspector/V8StringUtil.h"
#include "platform/v8_inspector/public/V8InspectorClient.h"
#include <algorithm>
using blink::protocol::Array;
using blink::protocol::Maybe;
using blink::protocol::Debugger::BreakpointId;
using blink::protocol::Debugger::CallFrame;
using blink::protocol::Runtime::ExceptionDetails;
using blink::protocol::Runtime::ScriptId;
using blink::protocol::Runtime::StackTrace;
using blink::protocol::Runtime::RemoteObject;
namespace blink {
namespace DebuggerAgentState {
static const char javaScriptBreakpoints[] = "javaScriptBreakopints";
static const char pauseOnExceptionsState[] = "pauseOnExceptionsState";
static const char asyncCallStackDepth[] = "asyncCallStackDepth";
static const char blackboxPattern[] = "blackboxPattern";
static const char debuggerEnabled[] = "debuggerEnabled";
// Breakpoint properties.
static const char url[] = "url";
static const char isRegex[] = "isRegex";
static const char lineNumber[] = "lineNumber";
static const char columnNumber[] = "columnNumber";
static const char condition[] = "condition";
static const char skipAllPauses[] = "skipAllPauses";
} // namespace DebuggerAgentState;
static const int maxSkipStepFrameCount = 128;
static const char backtraceObjectGroup[] = "backtrace";
static String16 breakpointIdSuffix(V8DebuggerAgentImpl::BreakpointSource source)
{
switch (source) {
case V8DebuggerAgentImpl::UserBreakpointSource:
break;
case V8DebuggerAgentImpl::DebugCommandBreakpointSource:
return ":debug";
case V8DebuggerAgentImpl::MonitorCommandBreakpointSource:
return ":monitor";
}
return String16();
}
static String16 generateBreakpointId(const String16& scriptId, int lineNumber, int columnNumber, V8DebuggerAgentImpl::BreakpointSource source)
{
return scriptId + ":" + String16::fromInteger(lineNumber) + ":" + String16::fromInteger(columnNumber) + breakpointIdSuffix(source);
}
static bool positionComparator(const std::pair<int, int>& a, const std::pair<int, int>& b)
{
if (a.first != b.first)
return a.first < b.first;
return a.second < b.second;
}
static bool hasInternalError(ErrorString* errorString, bool hasError)
{
if (hasError)
*errorString = "Internal error";
return hasError;
}
static std::unique_ptr<protocol::Debugger::Location> buildProtocolLocation(const String16& scriptId, int lineNumber, int columnNumber)
{
return protocol::Debugger::Location::create()
.setScriptId(scriptId)
.setLineNumber(lineNumber)
.setColumnNumber(columnNumber).build();
}
V8DebuggerAgentImpl::V8DebuggerAgentImpl(V8InspectorSessionImpl* session, protocol::FrontendChannel* frontendChannel, protocol::DictionaryValue* state)
: m_inspector(session->inspector())
, m_debugger(m_inspector->debugger())
, m_session(session)
, m_enabled(false)
, m_state(state)
, m_frontend(frontendChannel)
, m_isolate(m_inspector->isolate())
, m_breakReason(protocol::Debugger::Paused::ReasonEnum::Other)
, m_scheduledDebuggerStep(NoStep)
, m_skipNextDebuggerStepOut(false)
, m_javaScriptPauseScheduled(false)
, m_steppingFromFramework(false)
, m_pausingOnNativeEvent(false)
, m_skippedStepFrameCount(0)
, m_recursionLevelForStepOut(0)
, m_recursionLevelForStepFrame(0)
, m_skipAllPauses(false)
{
clearBreakDetails();
}
V8DebuggerAgentImpl::~V8DebuggerAgentImpl()
{
}
bool V8DebuggerAgentImpl::checkEnabled(ErrorString* errorString)
{
if (enabled())
return true;
*errorString = "Debugger agent is not enabled";
return false;
}
void V8DebuggerAgentImpl::enable()
{
// m_inspector->addListener may result in reporting all parsed scripts to
// the agent so it should already be in enabled state by then.
m_enabled = true;
m_state->setBoolean(DebuggerAgentState::debuggerEnabled, true);
m_debugger->enable();
std::vector<std::unique_ptr<V8DebuggerScript>> compiledScripts;
m_debugger->getCompiledScripts(m_session->contextGroupId(), compiledScripts);
for (size_t i = 0; i < compiledScripts.size(); i++)
didParseSource(std::move(compiledScripts[i]), true);
// FIXME(WK44513): breakpoints activated flag should be synchronized between all front-ends
m_debugger->setBreakpointsActivated(true);
}
bool V8DebuggerAgentImpl::enabled()
{
return m_enabled;
}
void V8DebuggerAgentImpl::enable(ErrorString* errorString)
{
if (enabled())
return;
if (!m_inspector->client()->canExecuteScripts(m_session->contextGroupId())) {
*errorString = "Script execution is prohibited";
return;
}
enable();
}
void V8DebuggerAgentImpl::disable(ErrorString*)
{
if (!enabled())
return;
m_state->setObject(DebuggerAgentState::javaScriptBreakpoints, protocol::DictionaryValue::create());
m_state->setInteger(DebuggerAgentState::pauseOnExceptionsState, V8Debugger::DontPauseOnExceptions);
m_state->setInteger(DebuggerAgentState::asyncCallStackDepth, 0);
if (!m_pausedContext.IsEmpty())
m_debugger->continueProgram();
m_debugger->disable();
m_pausedContext.Reset();
JavaScriptCallFrames emptyCallFrames;
m_pausedCallFrames.swap(emptyCallFrames);
m_scripts.clear();
m_blackboxedPositions.clear();
m_breakpointIdToDebuggerBreakpointIds.clear();
m_debugger->setAsyncCallStackDepth(this, 0);
m_continueToLocationBreakpointId = String16();
clearBreakDetails();
m_scheduledDebuggerStep = NoStep;
m_skipNextDebuggerStepOut = false;
m_javaScriptPauseScheduled = false;
m_steppingFromFramework = false;
m_pausingOnNativeEvent = false;
m_skippedStepFrameCount = 0;
m_recursionLevelForStepFrame = 0;
m_skipAllPauses = false;
m_blackboxPattern = nullptr;
m_state->remove(DebuggerAgentState::blackboxPattern);
m_enabled = false;
m_state->setBoolean(DebuggerAgentState::debuggerEnabled, false);
}
void V8DebuggerAgentImpl::restore()
{
DCHECK(!m_enabled);
if (!m_state->booleanProperty(DebuggerAgentState::debuggerEnabled, false))
return;
if (!m_inspector->client()->canExecuteScripts(m_session->contextGroupId()))
return;
enable();
ErrorString error;
int pauseState = V8Debugger::DontPauseOnExceptions;
m_state->getInteger(DebuggerAgentState::pauseOnExceptionsState, &pauseState);
setPauseOnExceptionsImpl(&error, pauseState);
DCHECK(error.isEmpty());
m_skipAllPauses = m_state->booleanProperty(DebuggerAgentState::skipAllPauses, false);
int asyncCallStackDepth = 0;
m_state->getInteger(DebuggerAgentState::asyncCallStackDepth, &asyncCallStackDepth);
m_debugger->setAsyncCallStackDepth(this, asyncCallStackDepth);
String16 blackboxPattern;
if (m_state->getString(DebuggerAgentState::blackboxPattern, &blackboxPattern)) {
if (!setBlackboxPattern(&error, blackboxPattern))
NOTREACHED();
}
}
void V8DebuggerAgentImpl::setBreakpointsActive(ErrorString* errorString, bool active)
{
if (!checkEnabled(errorString))
return;
m_debugger->setBreakpointsActivated(active);
}
void V8DebuggerAgentImpl::setSkipAllPauses(ErrorString*, bool skipped)
{
m_skipAllPauses = skipped;
m_state->setBoolean(DebuggerAgentState::skipAllPauses, m_skipAllPauses);
}
static std::unique_ptr<protocol::DictionaryValue> buildObjectForBreakpointCookie(const String16& url, int lineNumber, int columnNumber, const String16& condition, bool isRegex)
{
std::unique_ptr<protocol::DictionaryValue> breakpointObject = protocol::DictionaryValue::create();
breakpointObject->setString(DebuggerAgentState::url, url);
breakpointObject->setInteger(DebuggerAgentState::lineNumber, lineNumber);
breakpointObject->setInteger(DebuggerAgentState::columnNumber, columnNumber);
breakpointObject->setString(DebuggerAgentState::condition, condition);
breakpointObject->setBoolean(DebuggerAgentState::isRegex, isRegex);
return breakpointObject;
}
static bool matches(V8InspectorImpl* inspector, const String16& url, const String16& pattern, bool isRegex)
{
if (isRegex) {
V8Regex regex(inspector, pattern, true);
return regex.match(url) != -1;
}
return url == pattern;
}
void V8DebuggerAgentImpl::setBreakpointByUrl(ErrorString* errorString,
int lineNumber,
const Maybe<String16>& optionalURL,
const Maybe<String16>& optionalURLRegex,
const Maybe<int>& optionalColumnNumber,
const Maybe<String16>& optionalCondition,
String16* outBreakpointId,
std::unique_ptr<protocol::Array<protocol::Debugger::Location>>* locations)
{
*locations = Array<protocol::Debugger::Location>::create();
if (optionalURL.isJust() == optionalURLRegex.isJust()) {
*errorString = "Either url or urlRegex must be specified.";
return;
}
String16 url = optionalURL.isJust() ? optionalURL.fromJust() : optionalURLRegex.fromJust();
int columnNumber = 0;
if (optionalColumnNumber.isJust()) {
columnNumber = optionalColumnNumber.fromJust();
if (columnNumber < 0) {
*errorString = "Incorrect column number";
return;
}
}
String16 condition = optionalCondition.fromMaybe("");
bool isRegex = optionalURLRegex.isJust();
String16 breakpointId = (isRegex ? "/" + url + "/" : url) + ":" + String16::fromInteger(lineNumber) + ":" + String16::fromInteger(columnNumber);
protocol::DictionaryValue* breakpointsCookie = m_state->getObject(DebuggerAgentState::javaScriptBreakpoints);
if (!breakpointsCookie) {
std::unique_ptr<protocol::DictionaryValue> newValue = protocol::DictionaryValue::create();
breakpointsCookie = newValue.get();
m_state->setObject(DebuggerAgentState::javaScriptBreakpoints, std::move(newValue));
}
if (breakpointsCookie->get(breakpointId)) {
*errorString = "Breakpoint at specified location already exists.";
return;
}
breakpointsCookie->setObject(breakpointId, buildObjectForBreakpointCookie(url, lineNumber, columnNumber, condition, isRegex));
ScriptBreakpoint breakpoint(lineNumber, columnNumber, condition);
for (const auto& script : m_scripts) {
if (!matches(m_inspector, script.second->sourceURL(), url, isRegex))
continue;
std::unique_ptr<protocol::Debugger::Location> location = resolveBreakpoint(breakpointId, script.first, breakpoint, UserBreakpointSource);
if (location)
(*locations)->addItem(std::move(location));
}
*outBreakpointId = breakpointId;
}
static bool parseLocation(ErrorString* errorString, std::unique_ptr<protocol::Debugger::Location> location, String16* scriptId, int* lineNumber, int* columnNumber)
{
*scriptId = location->getScriptId();
*lineNumber = location->getLineNumber();
*columnNumber = location->getColumnNumber(0);
return true;
}
void V8DebuggerAgentImpl::setBreakpoint(ErrorString* errorString,
std::unique_ptr<protocol::Debugger::Location> location,
const Maybe<String16>& optionalCondition,
String16* outBreakpointId,
std::unique_ptr<protocol::Debugger::Location>* actualLocation)
{
String16 scriptId;
int lineNumber;
int columnNumber;
if (!parseLocation(errorString, std::move(location), &scriptId, &lineNumber, &columnNumber))
return;
String16 condition = optionalCondition.fromMaybe("");
String16 breakpointId = generateBreakpointId(scriptId, lineNumber, columnNumber, UserBreakpointSource);
if (m_breakpointIdToDebuggerBreakpointIds.find(breakpointId) != m_breakpointIdToDebuggerBreakpointIds.end()) {
*errorString = "Breakpoint at specified location already exists.";
return;
}
ScriptBreakpoint breakpoint(lineNumber, columnNumber, condition);
*actualLocation = resolveBreakpoint(breakpointId, scriptId, breakpoint, UserBreakpointSource);
if (*actualLocation)
*outBreakpointId = breakpointId;
else
*errorString = "Could not resolve breakpoint";
}
void V8DebuggerAgentImpl::removeBreakpoint(ErrorString* errorString, const String16& breakpointId)
{
if (!checkEnabled(errorString))
return;
protocol::DictionaryValue* breakpointsCookie = m_state->getObject(DebuggerAgentState::javaScriptBreakpoints);
if (breakpointsCookie)
breakpointsCookie->remove(breakpointId);
removeBreakpoint(breakpointId);
}
void V8DebuggerAgentImpl::removeBreakpoint(const String16& breakpointId)
{
DCHECK(enabled());
BreakpointIdToDebuggerBreakpointIdsMap::iterator debuggerBreakpointIdsIterator = m_breakpointIdToDebuggerBreakpointIds.find(breakpointId);
if (debuggerBreakpointIdsIterator == m_breakpointIdToDebuggerBreakpointIds.end())
return;
const std::vector<String16>& ids = debuggerBreakpointIdsIterator->second;
for (size_t i = 0; i < ids.size(); ++i) {
const String16& debuggerBreakpointId = ids[i];
m_debugger->removeBreakpoint(debuggerBreakpointId);
m_serverBreakpoints.erase(debuggerBreakpointId);
}
m_breakpointIdToDebuggerBreakpointIds.erase(breakpointId);
}
void V8DebuggerAgentImpl::continueToLocation(ErrorString* errorString,
std::unique_ptr<protocol::Debugger::Location> location,
const protocol::Maybe<bool>& interstateLocationOpt)
{
if (!checkEnabled(errorString))
return;
if (!m_continueToLocationBreakpointId.isEmpty()) {
m_debugger->removeBreakpoint(m_continueToLocationBreakpointId);
m_continueToLocationBreakpointId = "";
}
String16 scriptId;
int lineNumber;
int columnNumber;
if (!parseLocation(errorString, std::move(location), &scriptId, &lineNumber, &columnNumber))
return;
ScriptBreakpoint breakpoint(lineNumber, columnNumber, "");
m_continueToLocationBreakpointId = m_debugger->setBreakpoint(scriptId, breakpoint, &lineNumber, &columnNumber, interstateLocationOpt.fromMaybe(false));
resume(errorString);
}
void V8DebuggerAgentImpl::getBacktrace(ErrorString* errorString, std::unique_ptr<Array<CallFrame>>* callFrames, Maybe<StackTrace>* asyncStackTrace)
{
if (!assertPaused(errorString))
return;
JavaScriptCallFrames frames = m_debugger->currentCallFrames();
m_pausedCallFrames.swap(frames);
*callFrames = currentCallFrames(errorString);
if (!*callFrames)
return;
*asyncStackTrace = currentAsyncStackTrace();
}
bool V8DebuggerAgentImpl::isCurrentCallStackEmptyOrBlackboxed()
{
DCHECK(enabled());
JavaScriptCallFrames callFrames = m_debugger->currentCallFrames();
for (size_t index = 0; index < callFrames.size(); ++index) {
if (!isCallFrameWithUnknownScriptOrBlackboxed(callFrames[index].get()))
return false;
}
return true;
}
bool V8DebuggerAgentImpl::isTopPausedCallFrameBlackboxed()
{
DCHECK(enabled());
JavaScriptCallFrame* frame = m_pausedCallFrames.size() ? m_pausedCallFrames[0].get() : nullptr;
return isCallFrameWithUnknownScriptOrBlackboxed(frame);
}
bool V8DebuggerAgentImpl::isCallFrameWithUnknownScriptOrBlackboxed(JavaScriptCallFrame* frame)
{
if (!frame)
return true;
ScriptsMap::iterator it = m_scripts.find(String16::fromInteger(frame->sourceID()));
if (it == m_scripts.end()) {
// Unknown scripts are blackboxed.
return true;
}
if (m_blackboxPattern) {
const String16& scriptSourceURL = it->second->sourceURL();
if (!scriptSourceURL.isEmpty() && m_blackboxPattern->match(scriptSourceURL) != -1)
return true;
}
auto itBlackboxedPositions = m_blackboxedPositions.find(String16::fromInteger(frame->sourceID()));
if (itBlackboxedPositions == m_blackboxedPositions.end())
return false;
const std::vector<std::pair<int, int>>& ranges = itBlackboxedPositions->second;
auto itRange = std::lower_bound(ranges.begin(), ranges.end(),
std::make_pair(frame->line(), frame->column()), positionComparator);
// Ranges array contains positions in script where blackbox state is changed.
// [(0,0) ... ranges[0]) isn't blackboxed, [ranges[0] ... ranges[1]) is blackboxed...
return std::distance(ranges.begin(), itRange) % 2;
}
V8DebuggerAgentImpl::SkipPauseRequest V8DebuggerAgentImpl::shouldSkipExceptionPause(JavaScriptCallFrame* topCallFrame)
{
if (m_steppingFromFramework)
return RequestNoSkip;
if (isCallFrameWithUnknownScriptOrBlackboxed(topCallFrame))
return RequestContinue;
return RequestNoSkip;
}
V8DebuggerAgentImpl::SkipPauseRequest V8DebuggerAgentImpl::shouldSkipStepPause(JavaScriptCallFrame* topCallFrame)
{
if (m_steppingFromFramework)
return RequestNoSkip;
if (m_skipNextDebuggerStepOut) {
m_skipNextDebuggerStepOut = false;
if (m_scheduledDebuggerStep == StepOut)
return RequestStepOut;
}
if (!isCallFrameWithUnknownScriptOrBlackboxed(topCallFrame))
return RequestNoSkip;
if (m_skippedStepFrameCount >= maxSkipStepFrameCount)
return RequestStepOut;
if (!m_skippedStepFrameCount)
m_recursionLevelForStepFrame = 1;
++m_skippedStepFrameCount;
return RequestStepFrame;
}
std::unique_ptr<protocol::Debugger::Location> V8DebuggerAgentImpl::resolveBreakpoint(const String16& breakpointId, const String16& scriptId, const ScriptBreakpoint& breakpoint, BreakpointSource source)
{
DCHECK(enabled());
// FIXME: remove these checks once crbug.com/520702 is resolved.
CHECK(!breakpointId.isEmpty());
CHECK(!scriptId.isEmpty());
ScriptsMap::iterator scriptIterator = m_scripts.find(scriptId);
if (scriptIterator == m_scripts.end())
return nullptr;
if (breakpoint.lineNumber < scriptIterator->second->startLine() || scriptIterator->second->endLine() < breakpoint.lineNumber)
return nullptr;
int actualLineNumber;
int actualColumnNumber;
String16 debuggerBreakpointId = m_debugger->setBreakpoint(scriptId, breakpoint, &actualLineNumber, &actualColumnNumber, false);
if (debuggerBreakpointId.isEmpty())
return nullptr;
m_serverBreakpoints[debuggerBreakpointId] = std::make_pair(breakpointId, source);
CHECK(!breakpointId.isEmpty());
m_breakpointIdToDebuggerBreakpointIds[breakpointId].push_back(debuggerBreakpointId);
return buildProtocolLocation(scriptId, actualLineNumber, actualColumnNumber);
}
void V8DebuggerAgentImpl::searchInContent(ErrorString* error, const String16& scriptId, const String16& query,
const Maybe<bool>& optionalCaseSensitive,
const Maybe<bool>& optionalIsRegex,
std::unique_ptr<Array<protocol::Debugger::SearchMatch>>* results)
{
v8::HandleScope handles(m_isolate);
ScriptsMap::iterator it = m_scripts.find(scriptId);
if (it == m_scripts.end()) {
*error = String16("No script for id: " + scriptId);
return;
}
std::vector<std::unique_ptr<protocol::Debugger::SearchMatch>> matches = searchInTextByLinesImpl(m_session, toProtocolString(it->second->source(m_isolate)), query, optionalCaseSensitive.fromMaybe(false), optionalIsRegex.fromMaybe(false));
*results = protocol::Array<protocol::Debugger::SearchMatch>::create();
for (size_t i = 0; i < matches.size(); ++i)
(*results)->addItem(std::move(matches[i]));
}
void V8DebuggerAgentImpl::setScriptSource(ErrorString* errorString,
const String16& scriptId,
const String16& newContent,
const Maybe<bool>& preview,
Maybe<protocol::Array<protocol::Debugger::CallFrame>>* newCallFrames,
Maybe<bool>* stackChanged,
Maybe<StackTrace>* asyncStackTrace,
Maybe<protocol::Runtime::ExceptionDetails>* optOutCompileError)
{
if (!checkEnabled(errorString))
return;
v8::HandleScope handles(m_isolate);
v8::Local<v8::String> newSource = toV8String(m_isolate, newContent);
if (!m_debugger->setScriptSource(scriptId, newSource, preview.fromMaybe(false), errorString, optOutCompileError, &m_pausedCallFrames, stackChanged))
return;
ScriptsMap::iterator it = m_scripts.find(scriptId);
if (it != m_scripts.end())
it->second->setSource(m_isolate, newSource);
std::unique_ptr<Array<CallFrame>> callFrames = currentCallFrames(errorString);
if (!callFrames)
return;
*newCallFrames = std::move(callFrames);
*asyncStackTrace = currentAsyncStackTrace();
}
void V8DebuggerAgentImpl::restartFrame(ErrorString* errorString,
const String16& callFrameId,
std::unique_ptr<Array<CallFrame>>* newCallFrames,
Maybe<StackTrace>* asyncStackTrace)
{
if (!assertPaused(errorString))
return;
InjectedScript::CallFrameScope scope(errorString, m_inspector, m_session->contextGroupId(), callFrameId);
if (!scope.initialize())
return;
if (scope.frameOrdinal() >= m_pausedCallFrames.size()) {
*errorString = "Could not find call frame with given id";
return;
}
v8::Local<v8::Value> resultValue;
v8::Local<v8::Boolean> result;
if (!m_pausedCallFrames[scope.frameOrdinal()]->restart().ToLocal(&resultValue) || scope.tryCatch().HasCaught() || !resultValue->ToBoolean(scope.context()).ToLocal(&result) || !result->Value()) {
*errorString = "Internal error";
return;
}
JavaScriptCallFrames frames = m_debugger->currentCallFrames();
m_pausedCallFrames.swap(frames);
*newCallFrames = currentCallFrames(errorString);
if (!*newCallFrames)
return;
*asyncStackTrace = currentAsyncStackTrace();
}
void V8DebuggerAgentImpl::getScriptSource(ErrorString* error, const String16& scriptId, String16* scriptSource)
{
if (!checkEnabled(error))
return;
ScriptsMap::iterator it = m_scripts.find(scriptId);
if (it == m_scripts.end()) {
*error = "No script for id: " + scriptId;
return;
}
v8::HandleScope handles(m_isolate);
*scriptSource = toProtocolString(it->second->source(m_isolate));
}
void V8DebuggerAgentImpl::schedulePauseOnNextStatement(const String16& breakReason, std::unique_ptr<protocol::DictionaryValue> data)
{
if (!enabled() || m_scheduledDebuggerStep == StepInto || m_javaScriptPauseScheduled || m_debugger->isPaused() || !m_debugger->breakpointsActivated())
return;
m_breakReason = breakReason;
m_breakAuxData = std::move(data);
m_pausingOnNativeEvent = true;
m_skipNextDebuggerStepOut = false;
m_debugger->setPauseOnNextStatement(true);
}
void V8DebuggerAgentImpl::schedulePauseOnNextStatementIfSteppingInto()
{
DCHECK(enabled());
if (m_scheduledDebuggerStep != StepInto || m_javaScriptPauseScheduled || m_debugger->isPaused())
return;
clearBreakDetails();
m_pausingOnNativeEvent = false;
m_skippedStepFrameCount = 0;
m_recursionLevelForStepFrame = 0;
m_debugger->setPauseOnNextStatement(true);
}
void V8DebuggerAgentImpl::cancelPauseOnNextStatement()
{
if (m_javaScriptPauseScheduled || m_debugger->isPaused())
return;
clearBreakDetails();
m_pausingOnNativeEvent = false;
m_debugger->setPauseOnNextStatement(false);
}
void V8DebuggerAgentImpl::pause(ErrorString* errorString)
{
if (!checkEnabled(errorString))
return;
if (m_javaScriptPauseScheduled || m_debugger->isPaused())
return;
clearBreakDetails();
m_javaScriptPauseScheduled = true;
m_scheduledDebuggerStep = NoStep;
m_skippedStepFrameCount = 0;
m_steppingFromFramework = false;
m_debugger->setPauseOnNextStatement(true);
}
void V8DebuggerAgentImpl::resume(ErrorString* errorString)
{
if (!assertPaused(errorString))
return;
m_scheduledDebuggerStep = NoStep;
m_steppingFromFramework = false;
m_session->releaseObjectGroup(backtraceObjectGroup);
m_debugger->continueProgram();
}
void V8DebuggerAgentImpl::stepOver(ErrorString* errorString)
{
if (!assertPaused(errorString))
return;
// StepOver at function return point should fallback to StepInto.
JavaScriptCallFrame* frame = !m_pausedCallFrames.empty() ? m_pausedCallFrames[0].get() : nullptr;
if (frame && frame->isAtReturn()) {
stepInto(errorString);
return;
}
m_scheduledDebuggerStep = StepOver;
m_steppingFromFramework = isTopPausedCallFrameBlackboxed();
m_session->releaseObjectGroup(backtraceObjectGroup);
m_debugger->stepOverStatement();
}
void V8DebuggerAgentImpl::stepInto(ErrorString* errorString)
{
if (!assertPaused(errorString))
return;
m_scheduledDebuggerStep = StepInto;
m_steppingFromFramework = isTopPausedCallFrameBlackboxed();
m_session->releaseObjectGroup(backtraceObjectGroup);
m_debugger->stepIntoStatement();
}
void V8DebuggerAgentImpl::stepOut(ErrorString* errorString)
{
if (!assertPaused(errorString))
return;
m_scheduledDebuggerStep = StepOut;
m_skipNextDebuggerStepOut = false;
m_recursionLevelForStepOut = 1;
m_steppingFromFramework = isTopPausedCallFrameBlackboxed();
m_session->releaseObjectGroup(backtraceObjectGroup);
m_debugger->stepOutOfFunction();
}
void V8DebuggerAgentImpl::setPauseOnExceptions(ErrorString* errorString, const String16& stringPauseState)
{
if (!checkEnabled(errorString))
return;
V8Debugger::PauseOnExceptionsState pauseState;
if (stringPauseState == "none") {
pauseState = V8Debugger::DontPauseOnExceptions;
} else if (stringPauseState == "all") {
pauseState = V8Debugger::PauseOnAllExceptions;
} else if (stringPauseState == "uncaught") {
pauseState = V8Debugger::PauseOnUncaughtExceptions;
} else {
*errorString = "Unknown pause on exceptions mode: " + stringPauseState;
return;
}
setPauseOnExceptionsImpl(errorString, pauseState);
}
void V8DebuggerAgentImpl::setPauseOnExceptionsImpl(ErrorString* errorString, int pauseState)
{
m_debugger->setPauseOnExceptionsState(static_cast<V8Debugger::PauseOnExceptionsState>(pauseState));
if (m_debugger->getPauseOnExceptionsState() != pauseState)
*errorString = "Internal error. Could not change pause on exceptions state";
else
m_state->setInteger(DebuggerAgentState::pauseOnExceptionsState, pauseState);
}
void V8DebuggerAgentImpl::evaluateOnCallFrame(ErrorString* errorString,
const String16& callFrameId,
const String16& expression,
const Maybe<String16>& objectGroup,
const Maybe<bool>& includeCommandLineAPI,
const Maybe<bool>& doNotPauseOnExceptionsAndMuteConsole,
const Maybe<bool>& returnByValue,
const Maybe<bool>& generatePreview,
std::unique_ptr<RemoteObject>* result,
Maybe<bool>* wasThrown,
Maybe<protocol::Runtime::ExceptionDetails>* exceptionDetails)
{
if (!assertPaused(errorString))
return;
InjectedScript::CallFrameScope scope(errorString, m_inspector, m_session->contextGroupId(), callFrameId);
if (!scope.initialize())
return;
if (scope.frameOrdinal() >= m_pausedCallFrames.size()) {
*errorString = "Could not find call frame with given id";
return;
}
if (includeCommandLineAPI.fromMaybe(false) && !scope.installCommandLineAPI())
return;
if (doNotPauseOnExceptionsAndMuteConsole.fromMaybe(false))
scope.ignoreExceptionsAndMuteConsole();
v8::MaybeLocal<v8::Value> maybeResultValue = m_pausedCallFrames[scope.frameOrdinal()]->evaluate(toV8String(m_isolate, expression));
// Re-initialize after running client's code, as it could have destroyed context or session.
if (!scope.initialize())
return;
scope.injectedScript()->wrapEvaluateResult(errorString,
maybeResultValue,
scope.tryCatch(),
objectGroup.fromMaybe(""),
returnByValue.fromMaybe(false),
generatePreview.fromMaybe(false),
result,
wasThrown,
exceptionDetails);
}
void V8DebuggerAgentImpl::setVariableValue(ErrorString* errorString,
int scopeNumber,
const String16& variableName,
std::unique_ptr<protocol::Runtime::CallArgument> newValueArgument,
const String16& callFrameId)
{
if (!checkEnabled(errorString))
return;
if (!assertPaused(errorString))
return;
InjectedScript::CallFrameScope scope(errorString, m_inspector, m_session->contextGroupId(), callFrameId);
if (!scope.initialize())
return;
v8::Local<v8::Value> newValue;
if (!scope.injectedScript()->resolveCallArgument(errorString, newValueArgument.get()).ToLocal(&newValue))
return;
if (scope.frameOrdinal() >= m_pausedCallFrames.size()) {
*errorString = "Could not find call frame with given id";
return;
}
v8::MaybeLocal<v8::Value> result = m_pausedCallFrames[scope.frameOrdinal()]->setVariableValue(scopeNumber, toV8String(m_isolate, variableName), newValue);
if (scope.tryCatch().HasCaught() || result.IsEmpty()) {
*errorString = "Internal error";
return;
}
}
void V8DebuggerAgentImpl::setAsyncCallStackDepth(ErrorString* errorString, int depth)
{
if (!checkEnabled(errorString))
return;
m_state->setInteger(DebuggerAgentState::asyncCallStackDepth, depth);
m_debugger->setAsyncCallStackDepth(this, depth);
}
void V8DebuggerAgentImpl::setBlackboxPatterns(ErrorString* errorString, std::unique_ptr<protocol::Array<String16>> patterns)
{
if (!patterns->length()) {
m_blackboxPattern = nullptr;
m_state->remove(DebuggerAgentState::blackboxPattern);
return;
}
String16Builder patternBuilder;
patternBuilder.append('(');
for (size_t i = 0; i < patterns->length() - 1; ++i) {
patternBuilder.append(patterns->get(i));
patternBuilder.append("|");
}
patternBuilder.append(patterns->get(patterns->length() - 1));
patternBuilder.append(')');
String16 pattern = patternBuilder.toString();
if (!setBlackboxPattern(errorString, pattern))
return;
m_state->setString(DebuggerAgentState::blackboxPattern, pattern);
}
bool V8DebuggerAgentImpl::setBlackboxPattern(ErrorString* errorString, const String16& pattern)
{
std::unique_ptr<V8Regex> regex(new V8Regex(m_inspector, pattern, true /** caseSensitive */, false /** multiline */));
if (!regex->isValid()) {
*errorString = "Pattern parser error: " + regex->errorMessage();
return false;
}
m_blackboxPattern = std::move(regex);
return true;
}
void V8DebuggerAgentImpl::setBlackboxedRanges(ErrorString* error, const String16& scriptId,
std::unique_ptr<protocol::Array<protocol::Debugger::ScriptPosition>> inPositions)
{
if (m_scripts.find(scriptId) == m_scripts.end()) {
*error = "No script with passed id.";
return;
}
if (!inPositions->length()) {
m_blackboxedPositions.erase(scriptId);
return;
}
std::vector<std::pair<int, int>> positions;
positions.reserve(inPositions->length());
for (size_t i = 0; i < inPositions->length(); ++i) {
protocol::Debugger::ScriptPosition* position = inPositions->get(i);
if (position->getLineNumber() < 0) {
*error = "Position missing 'line' or 'line' < 0.";
return;
}
if (position->getColumnNumber() < 0) {
*error = "Position missing 'column' or 'column' < 0.";
return;
}
positions.push_back(std::make_pair(position->getLineNumber(), position->getColumnNumber()));
}
for (size_t i = 1; i < positions.size(); ++i) {
if (positions[i - 1].first < positions[i].first)
continue;
if (positions[i - 1].first == positions[i].first && positions[i - 1].second < positions[i].second)
continue;
*error = "Input positions array is not sorted or contains duplicate values.";
return;
}
m_blackboxedPositions[scriptId] = positions;
}
void V8DebuggerAgentImpl::willExecuteScript(int scriptId)
{
changeJavaScriptRecursionLevel(+1);
// Fast return.
if (m_scheduledDebuggerStep != StepInto)
return;
schedulePauseOnNextStatementIfSteppingInto();
}
void V8DebuggerAgentImpl::didExecuteScript()
{
changeJavaScriptRecursionLevel(-1);
}
void V8DebuggerAgentImpl::changeJavaScriptRecursionLevel(int step)
{
if (m_javaScriptPauseScheduled && !m_skipAllPauses && !m_debugger->isPaused()) {
// Do not ever loose user's pause request until we have actually paused.
m_debugger->setPauseOnNextStatement(true);
}
if (m_scheduledDebuggerStep == StepOut) {
m_recursionLevelForStepOut += step;
if (!m_recursionLevelForStepOut) {
// When StepOut crosses a task boundary (i.e. js -> blink_c++) from where it was requested,
// switch stepping to step into a next JS task, as if we exited to a blackboxed framework.
m_scheduledDebuggerStep = StepInto;
m_skipNextDebuggerStepOut = false;
}
}
if (m_recursionLevelForStepFrame) {
m_recursionLevelForStepFrame += step;
if (!m_recursionLevelForStepFrame) {
// We have walked through a blackboxed framework and got back to where we started.
// If there was no stepping scheduled, we should cancel the stepping explicitly,
// since there may be a scheduled StepFrame left.
// Otherwise, if we were stepping in/over, the StepFrame will stop at the right location,
// whereas if we were stepping out, we should continue doing so after debugger pauses
// from the old StepFrame.
m_skippedStepFrameCount = 0;
if (m_scheduledDebuggerStep == NoStep)
m_debugger->clearStepping();
else if (m_scheduledDebuggerStep == StepOut)
m_skipNextDebuggerStepOut = true;
}
}
}
std::unique_ptr<Array<CallFrame>> V8DebuggerAgentImpl::currentCallFrames(ErrorString* errorString)
{
if (m_pausedContext.IsEmpty() || !m_pausedCallFrames.size())
return Array<CallFrame>::create();
ErrorString ignored;
v8::HandleScope handles(m_isolate);
v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext(m_isolate);
v8::Context::Scope contextScope(debuggerContext);
v8::Local<v8::Array> objects = v8::Array::New(m_isolate);
for (size_t frameOrdinal = 0; frameOrdinal < m_pausedCallFrames.size(); ++frameOrdinal) {
const std::unique_ptr<JavaScriptCallFrame>& currentCallFrame = m_pausedCallFrames[frameOrdinal];
v8::Local<v8::Object> details = currentCallFrame->details();
if (hasInternalError(errorString, details.IsEmpty()))
return Array<CallFrame>::create();
int contextId = currentCallFrame->contextId();
InjectedScript* injectedScript = contextId ? m_session->findInjectedScript(&ignored, contextId) : nullptr;
String16 callFrameId = RemoteCallFrameId::serialize(contextId, frameOrdinal);
if (hasInternalError(errorString, !details->Set(debuggerContext, toV8StringInternalized(m_isolate, "callFrameId"), toV8String(m_isolate, callFrameId)).FromMaybe(false)))
return Array<CallFrame>::create();
if (injectedScript) {
v8::Local<v8::Value> scopeChain;
if (hasInternalError(errorString, !details->Get(debuggerContext, toV8StringInternalized(m_isolate, "scopeChain")).ToLocal(&scopeChain) || !scopeChain->IsArray()))
return Array<CallFrame>::create();
v8::Local<v8::Array> scopeChainArray = scopeChain.As<v8::Array>();
if (!injectedScript->wrapPropertyInArray(errorString, scopeChainArray, toV8StringInternalized(m_isolate, "object"), backtraceObjectGroup))
return Array<CallFrame>::create();
if (!injectedScript->wrapObjectProperty(errorString, details, toV8StringInternalized(m_isolate, "this"), backtraceObjectGroup))
return Array<CallFrame>::create();
if (details->Has(debuggerContext, toV8StringInternalized(m_isolate, "returnValue")).FromMaybe(false)) {
if (!injectedScript->wrapObjectProperty(errorString, details, toV8StringInternalized(m_isolate, "returnValue"), backtraceObjectGroup))
return Array<CallFrame>::create();
}
} else {
if (hasInternalError(errorString, !details->Set(debuggerContext, toV8StringInternalized(m_isolate, "scopeChain"), v8::Array::New(m_isolate, 0)).FromMaybe(false)))
return Array<CallFrame>::create();
v8::Local<v8::Object> remoteObject = v8::Object::New(m_isolate);
if (hasInternalError(errorString, !remoteObject->Set(debuggerContext, toV8StringInternalized(m_isolate, "type"), toV8StringInternalized(m_isolate, "undefined")).FromMaybe(false)))
return Array<CallFrame>::create();
if (hasInternalError(errorString, !details->Set(debuggerContext, toV8StringInternalized(m_isolate, "this"), remoteObject).FromMaybe(false)))
return Array<CallFrame>::create();
if (hasInternalError(errorString, !details->Delete(debuggerContext, toV8StringInternalized(m_isolate, "returnValue")).FromMaybe(false)))
return Array<CallFrame>::create();
}
if (hasInternalError(errorString, !objects->Set(debuggerContext, frameOrdinal, details).FromMaybe(false)))
return Array<CallFrame>::create();
}
protocol::ErrorSupport errorSupport;
std::unique_ptr<Array<CallFrame>> callFrames = Array<CallFrame>::parse(toProtocolValue(debuggerContext, objects).get(), &errorSupport);
if (hasInternalError(errorString, !callFrames))
return Array<CallFrame>::create();
return callFrames;
}
std::unique_ptr<StackTrace> V8DebuggerAgentImpl::currentAsyncStackTrace()
{
if (m_pausedContext.IsEmpty())
return nullptr;
V8StackTraceImpl* stackTrace = m_debugger->currentAsyncCallChain();
return stackTrace ? stackTrace->buildInspectorObjectForTail(m_debugger) : nullptr;
}
void V8DebuggerAgentImpl::didParseSource(std::unique_ptr<V8DebuggerScript> script, bool success)
{
v8::HandleScope handles(m_isolate);
String16 scriptSource = toProtocolString(script->source(m_isolate));
bool isDeprecatedSourceURL = false;
if (!success)
script->setSourceURL(findSourceURL(scriptSource, false, &isDeprecatedSourceURL));
else if (script->hasSourceURL())
findSourceURL(scriptSource, false, &isDeprecatedSourceURL);
bool isDeprecatedSourceMappingURL = false;
if (!success)
script->setSourceMappingURL(findSourceMapURL(scriptSource, false, &isDeprecatedSourceMappingURL));
else if (!script->sourceMappingURL().isEmpty())
findSourceMapURL(scriptSource, false, &isDeprecatedSourceMappingURL);
std::unique_ptr<protocol::DictionaryValue> executionContextAuxData;
if (!script->executionContextAuxData().isEmpty())
executionContextAuxData = protocol::DictionaryValue::cast(parseJSON(script->executionContextAuxData()));
bool isInternalScript = script->isInternalScript();
bool isLiveEdit = script->isLiveEdit();
bool hasSourceURL = script->hasSourceURL();
String16 scriptId = script->scriptId();
String16 scriptURL = script->sourceURL();
bool deprecatedCommentWasUsed = isDeprecatedSourceURL || isDeprecatedSourceMappingURL;
const Maybe<String16>& sourceMapURLParam = script->sourceMappingURL();
const Maybe<protocol::DictionaryValue>& executionContextAuxDataParam(std::move(executionContextAuxData));
const bool* isInternalScriptParam = isInternalScript ? &isInternalScript : nullptr;
const bool* isLiveEditParam = isLiveEdit ? &isLiveEdit : nullptr;
const bool* hasSourceURLParam = hasSourceURL ? &hasSourceURL : nullptr;
const bool* deprecatedCommentWasUsedParam = deprecatedCommentWasUsed ? &deprecatedCommentWasUsed : nullptr;
if (success)
m_frontend.scriptParsed(scriptId, scriptURL, script->startLine(), script->startColumn(), script->endLine(), script->endColumn(), script->executionContextId(), script->hash(), executionContextAuxDataParam, isInternalScriptParam, isLiveEditParam, sourceMapURLParam, hasSourceURLParam, deprecatedCommentWasUsedParam);
else
m_frontend.scriptFailedToParse(scriptId, scriptURL, script->startLine(), script->startColumn(), script->endLine(), script->endColumn(), script->executionContextId(), script->hash(), executionContextAuxDataParam, isInternalScriptParam, sourceMapURLParam, hasSourceURLParam, deprecatedCommentWasUsedParam);
m_scripts[scriptId] = std::move(script);
if (scriptURL.isEmpty() || !success)
return;
protocol::DictionaryValue* breakpointsCookie = m_state->getObject(DebuggerAgentState::javaScriptBreakpoints);
if (!breakpointsCookie)
return;
for (size_t i = 0; i < breakpointsCookie->size(); ++i) {
auto cookie = breakpointsCookie->at(i);
protocol::DictionaryValue* breakpointObject = protocol::DictionaryValue::cast(cookie.second);
bool isRegex;
breakpointObject->getBoolean(DebuggerAgentState::isRegex, &isRegex);
String16 url;
breakpointObject->getString(DebuggerAgentState::url, &url);
if (!matches(m_inspector, scriptURL, url, isRegex))
continue;
ScriptBreakpoint breakpoint;
breakpointObject->getInteger(DebuggerAgentState::lineNumber, &breakpoint.lineNumber);
breakpointObject->getInteger(DebuggerAgentState::columnNumber, &breakpoint.columnNumber);
breakpointObject->getString(DebuggerAgentState::condition, &breakpoint.condition);
std::unique_ptr<protocol::Debugger::Location> location = resolveBreakpoint(cookie.first, scriptId, breakpoint, UserBreakpointSource);
if (location)
m_frontend.breakpointResolved(cookie.first, std::move(location));
}
}
V8DebuggerAgentImpl::SkipPauseRequest V8DebuggerAgentImpl::didPause(v8::Local<v8::Context> context, v8::Local<v8::Value> exception, const std::vector<String16>& hitBreakpoints, bool isPromiseRejection)
{
JavaScriptCallFrames callFrames = m_debugger->currentCallFrames(1);
JavaScriptCallFrame* topCallFrame = !callFrames.empty() ? callFrames.begin()->get() : nullptr;
// Skip pause in internal scripts (e.g. InjectedScriptSource.js).
if (topCallFrame) {
ScriptsMap::iterator it = m_scripts.find(String16::fromInteger(topCallFrame->sourceID()));
if (it != m_scripts.end() && it->second->isInternalScript())
return RequestStepFrame;
}
V8DebuggerAgentImpl::SkipPauseRequest result;
if (m_skipAllPauses)
result = RequestContinue;
else if (!hitBreakpoints.empty())
result = RequestNoSkip; // Don't skip explicit breakpoints even if set in frameworks.
else if (!exception.IsEmpty())
result = shouldSkipExceptionPause(topCallFrame);
else if (m_scheduledDebuggerStep != NoStep || m_javaScriptPauseScheduled || m_pausingOnNativeEvent)
result = shouldSkipStepPause(topCallFrame);
else
result = RequestNoSkip;
m_skipNextDebuggerStepOut = false;
if (result != RequestNoSkip)
return result;
// Skip pauses inside V8 internal scripts and on syntax errors.
if (!topCallFrame)
return RequestContinue;
DCHECK(m_pausedContext.IsEmpty());
JavaScriptCallFrames frames = m_debugger->currentCallFrames();
m_pausedCallFrames.swap(frames);
m_pausedContext.Reset(m_isolate, context);
v8::HandleScope handles(m_isolate);
if (!exception.IsEmpty()) {
ErrorString ignored;
InjectedScript* injectedScript = m_session->findInjectedScript(&ignored, V8Debugger::contextId(context));
if (injectedScript) {
m_breakReason = isPromiseRejection ? protocol::Debugger::Paused::ReasonEnum::PromiseRejection : protocol::Debugger::Paused::ReasonEnum::Exception;
ErrorString errorString;
auto obj = injectedScript->wrapObject(&errorString, exception, backtraceObjectGroup);
m_breakAuxData = obj ? obj->serialize() : nullptr;
// m_breakAuxData might be null after this.
}
}
std::unique_ptr<Array<String16>> hitBreakpointIds = Array<String16>::create();
for (const auto& point : hitBreakpoints) {
DebugServerBreakpointToBreakpointIdAndSourceMap::iterator breakpointIterator = m_serverBreakpoints.find(point);
if (breakpointIterator != m_serverBreakpoints.end()) {
const String16& localId = breakpointIterator->second.first;
hitBreakpointIds->addItem(localId);
BreakpointSource source = breakpointIterator->second.second;
if (m_breakReason == protocol::Debugger::Paused::ReasonEnum::Other && source == DebugCommandBreakpointSource)
m_breakReason = protocol::Debugger::Paused::ReasonEnum::DebugCommand;
}
}
ErrorString errorString;
m_frontend.paused(currentCallFrames(&errorString), m_breakReason, std::move(m_breakAuxData), std::move(hitBreakpointIds), currentAsyncStackTrace());
m_scheduledDebuggerStep = NoStep;
m_javaScriptPauseScheduled = false;
m_steppingFromFramework = false;
m_pausingOnNativeEvent = false;
m_skippedStepFrameCount = 0;
m_recursionLevelForStepFrame = 0;
if (!m_continueToLocationBreakpointId.isEmpty()) {
m_debugger->removeBreakpoint(m_continueToLocationBreakpointId);
m_continueToLocationBreakpointId = "";
}
return result;
}
void V8DebuggerAgentImpl::didContinue()
{
m_pausedContext.Reset();
JavaScriptCallFrames emptyCallFrames;
m_pausedCallFrames.swap(emptyCallFrames);
clearBreakDetails();
m_frontend.resumed();
}
void V8DebuggerAgentImpl::breakProgram(const String16& breakReason, std::unique_ptr<protocol::DictionaryValue> data)
{
if (!enabled() || m_skipAllPauses || !m_pausedContext.IsEmpty() || isCurrentCallStackEmptyOrBlackboxed() || !m_debugger->breakpointsActivated())
return;
m_breakReason = breakReason;
m_breakAuxData = std::move(data);
m_scheduledDebuggerStep = NoStep;
m_steppingFromFramework = false;
m_pausingOnNativeEvent = false;
m_debugger->breakProgram();
}
void V8DebuggerAgentImpl::breakProgramOnException(const String16& breakReason, std::unique_ptr<protocol::DictionaryValue> data)
{
if (!enabled() || m_debugger->getPauseOnExceptionsState() == V8Debugger::DontPauseOnExceptions)
return;
breakProgram(breakReason, std::move(data));
}
bool V8DebuggerAgentImpl::assertPaused(ErrorString* errorString)
{
if (m_pausedContext.IsEmpty()) {
*errorString = "Can only perform operation while paused.";
return false;
}
return true;
}
void V8DebuggerAgentImpl::clearBreakDetails()
{
m_breakReason = protocol::Debugger::Paused::ReasonEnum::Other;
m_breakAuxData = nullptr;
}
void V8DebuggerAgentImpl::setBreakpointAt(const String16& scriptId, int lineNumber, int columnNumber, BreakpointSource source, const String16& condition)
{
String16 breakpointId = generateBreakpointId(scriptId, lineNumber, columnNumber, source);
ScriptBreakpoint breakpoint(lineNumber, columnNumber, condition);
resolveBreakpoint(breakpointId, scriptId, breakpoint, source);
}
void V8DebuggerAgentImpl::removeBreakpointAt(const String16& scriptId, int lineNumber, int columnNumber, BreakpointSource source)
{
removeBreakpoint(generateBreakpointId(scriptId, lineNumber, columnNumber, source));
}
void V8DebuggerAgentImpl::reset()
{
if (!enabled())
return;
m_scheduledDebuggerStep = NoStep;
m_scripts.clear();
m_blackboxedPositions.clear();
m_breakpointIdToDebuggerBreakpointIds.clear();
}
} // namespace blink
| gpl-3.0 |
qinyuhang/shadowsocks-libev | libcork/core/timestamp.c | 5 | 5015 | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2011-2013, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include "libcork/core/timestamp.h"
#include "libcork/core/types.h"
#include "libcork/helpers/errors.h"
void
cork_timestamp_init_now(cork_timestamp *ts)
{
struct timeval tp;
gettimeofday(&tp, NULL);
cork_timestamp_init_usec(ts, tp.tv_sec, tp.tv_usec);
}
#define is_digit(ch) ((ch) >= '0' && (ch) <= '9')
static uint64_t
power_of_10(unsigned int width)
{
uint64_t accumulator = 10;
uint64_t result = 1;
while (width != 0) {
if ((width % 2) == 1) {
result *= accumulator;
width--;
}
accumulator *= accumulator;
width /= 2;
}
return result;
}
static int
append_fractional(const cork_timestamp ts, unsigned int width,
struct cork_buffer *dest)
{
if (CORK_UNLIKELY(width == 0 || width > 9)) {
cork_error_set_printf
(EINVAL,
"Invalid width %u for fractional cork_timestamp", width);
return -1;
} else {
uint64_t denom = power_of_10(width);
uint64_t frac = cork_timestamp_gsec_to_units(ts, denom);
cork_buffer_append_printf(dest, "%0*" PRIu64, width, frac);
return 0;
}
}
static int
cork_timestamp_format_parts(const cork_timestamp ts, struct tm *tm,
const char *format, struct cork_buffer *dest)
{
const char *next_percent;
while ((next_percent = strchr(format, '%')) != NULL) {
const char *spec = next_percent + 1;
unsigned int width = 0;
/* First append any text in between the previous format specifier and
* this one. */
cork_buffer_append(dest, format, next_percent - format);
/* Then parse the format specifier */
while (is_digit(*spec)) {
width *= 10;
width += (*spec++ - '0');
}
switch (*spec) {
case '\0':
cork_error_set_string
(EINVAL,
"Trailing %% at end of cork_timestamp format string");
return -1;
case '%':
cork_buffer_append(dest, "%", 1);
break;
case 'Y':
cork_buffer_append_printf(dest, "%04d", tm->tm_year + 1900);
break;
case 'm':
cork_buffer_append_printf(dest, "%02d", tm->tm_mon + 1);
break;
case 'd':
cork_buffer_append_printf(dest, "%02d", tm->tm_mday);
break;
case 'H':
cork_buffer_append_printf(dest, "%02d", tm->tm_hour);
break;
case 'M':
cork_buffer_append_printf(dest, "%02d", tm->tm_min);
break;
case 'S':
cork_buffer_append_printf(dest, "%02d", tm->tm_sec);
break;
case 's':
cork_buffer_append_printf
(dest, "%" PRIu32, cork_timestamp_sec(ts));
break;
case 'f':
rii_check(append_fractional(ts, width, dest));
break;
default:
cork_error_set_printf
(EINVAL,
"Unknown cork_timestamp format specifier %%%c", *spec);
return -1;
}
format = spec + 1;
}
/* When we fall through, there is some additional content after the final
* format specifier. */
cork_buffer_append_string(dest, format);
return 0;
}
#ifdef __MINGW32__
static struct tm *__cdecl gmtime_r(const time_t *_Time, struct tm *_Tm)
{
struct tm *p = gmtime(_Time);
if (!p)
return NULL;
if (_Tm) {
memcpy(_Tm, p, sizeof(struct tm));
return _Tm;
} else
return p;
}
static struct tm *__cdecl localtime_r(const time_t *_Time, struct tm *_Tm)
{
struct tm *p = localtime(_Time);
if (!p)
return NULL;
if (_Tm) {
memcpy(_Tm, p, sizeof(struct tm));
return _Tm;
} else
return p;
}
#endif
int
cork_timestamp_format_utc(const cork_timestamp ts, const char *format,
struct cork_buffer *dest)
{
time_t clock;
struct tm tm;
clock = cork_timestamp_sec(ts);
gmtime_r(&clock, &tm);
return cork_timestamp_format_parts(ts, &tm, format, dest);
}
int
cork_timestamp_format_local(const cork_timestamp ts, const char *format,
struct cork_buffer *dest)
{
time_t clock;
struct tm tm;
clock = cork_timestamp_sec(ts);
localtime_r(&clock, &tm);
return cork_timestamp_format_parts(ts, &tm, format, dest);
}
| gpl-3.0 |
don-willingham/Sonoff-Tasmota | lib/lib_basic/IRremoteESP8266/IRremoteESP8266/src/ir_Pronto.cpp | 5 | 4221 | // Copyright 2017 David Conran
/// @file
/// @brief Pronto code message generation
/// @see http://www.etcwiki.org/wiki/Pronto_Infrared_Format
/// @see http://www.remotecentral.com/features/irdisp2.htm
/// @see http://harctoolbox.org/Glossary.html#ProntoSemantics
/// @see https://irdb.globalcache.com/
// Supports:
// Brand: Pronto, Model: Pronto Hex
#include <algorithm>
#include "IRsend.h"
// Constants
const float kProntoFreqFactor = 0.241246;
const uint16_t kProntoTypeOffset = 0;
const uint16_t kProntoFreqOffset = 1;
const uint16_t kProntoSeq1LenOffset = 2;
const uint16_t kProntoSeq2LenOffset = 3;
const uint16_t kProntoDataOffset = 4;
#if SEND_PRONTO
/// Send a Pronto Code formatted message.
/// Status: STABLE / Known working.
/// @param[in] data An array of uint16_t containing the pronto codes.
/// @param[in] len Nr. of entries in the data[] array.
/// @param[in] repeat Nr. of times to repeat the message.
/// @note Pronto codes are typically represented in hexadecimal.
/// You will need to convert the code to an array of integers, and calculate
/// it's length.
/// e.g.
/// @code
/// A Sony 20 bit DVD remote command.
/// "0000 0067 0000 0015 0060 0018 0018 0018 0030 0018 0030 0018 0030 0018
/// 0018 0018 0030 0018 0018 0018 0018 0018 0030 0018 0018 0018 0030 0018
/// 0030 0018 0030 0018 0018 0018 0018 0018 0030 0018 0018 0018 0018 0018
/// 0030 0018 0018 03f6"
/// @endcode
/// converts to:
/// @code{.cpp}
/// uint16_t prontoCode[46] = {
/// 0x0000, 0x0067, 0x0000, 0x0015,
/// 0x0060, 0x0018, 0x0018, 0x0018, 0x0030, 0x0018, 0x0030, 0x0018,
/// 0x0030, 0x0018, 0x0018, 0x0018, 0x0030, 0x0018, 0x0018, 0x0018,
/// 0x0018, 0x0018, 0x0030, 0x0018, 0x0018, 0x0018, 0x0030, 0x0018,
/// 0x0030, 0x0018, 0x0030, 0x0018, 0x0018, 0x0018, 0x0018, 0x0018,
/// 0x0030, 0x0018, 0x0018, 0x0018, 0x0018, 0x0018, 0x0030, 0x0018,
/// 0x0018, 0x03f6};
/// // Send the Pronto(Sony) code. Repeat twice as Sony's require that.
/// sendPronto(prontoCode, 46, kSonyMinRepeat);
/// @endcode
/// @see http://www.etcwiki.org/wiki/Pronto_Infrared_Format
/// @see http://www.remotecentral.com/features/irdisp2.htm
void IRsend::sendPronto(uint16_t data[], uint16_t len, uint16_t repeat) {
// Check we have enough data to work out what to send.
if (len < kProntoMinLength) return;
// We only know how to deal with 'raw' pronto codes types. Reject all others.
if (data[kProntoTypeOffset] != 0) return;
// Pronto frequency is in Hz.
uint16_t hz =
(uint16_t)(1000000U / (data[kProntoFreqOffset] * kProntoFreqFactor));
enableIROut(hz);
// Grab the length of the two sequences.
uint16_t seq_1_len = data[kProntoSeq1LenOffset] * 2;
uint16_t seq_2_len = data[kProntoSeq2LenOffset] * 2;
// Calculate where each sequence starts in the buffer.
uint16_t seq_1_start = kProntoDataOffset;
uint16_t seq_2_start = kProntoDataOffset + seq_1_len;
uint32_t periodic_time_x10 = calcUSecPeriod(hz / 10, false);
// Normal (1st sequence) case.
// Is there a first (normal) sequence to send?
if (seq_1_len > 0) {
// Check we have enough data to send the complete first sequence.
if (seq_1_len + seq_1_start > len) return;
// Send the contents of the 1st sequence.
for (uint16_t i = seq_1_start; i < seq_1_start + seq_1_len; i += 2) {
mark((data[i] * periodic_time_x10) / 10);
space((data[i + 1] * periodic_time_x10) / 10);
}
} else {
// There was no first sequence to send, it is implied that we have to send
// the 2nd/repeat sequence an additional time. i.e. At least once.
repeat++;
}
// Repeat (2nd sequence) case.
// Is there a second (repeat) sequence to be sent?
if (seq_2_len > 0) {
// Check we have enough data to send the complete second sequence.
if (seq_2_len + seq_2_start > len) return;
// Send the contents of the 2nd sequence.
for (uint16_t r = 0; r < repeat; r++)
for (uint16_t i = seq_2_start; i < seq_2_start + seq_2_len; i += 2) {
mark((data[i] * periodic_time_x10) / 10);
space((data[i + 1] * periodic_time_x10) / 10);
}
}
}
#endif // SEND_PRONTO
| gpl-3.0 |
anthonygp/igoat | iGoat/sqlcipher/src/main.c | 5 | 131869 | /*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** Main file for the SQLite library. The routines in this file
** implement the programmer interface to the library. Routines in
** other files are for internal use by SQLite and should not be
** accessed by users of the library.
*/
#include "sqliteInt.h"
#ifdef SQLITE_ENABLE_FTS3
# include "fts3.h"
#endif
#ifdef SQLITE_ENABLE_RTREE
# include "rtree.h"
#endif
#ifdef SQLITE_ENABLE_ICU
# include "sqliteicu.h"
#endif
#ifdef SQLITE_ENABLE_JSON1
int sqlite3Json1Init(sqlite3*);
#endif
#ifdef SQLITE_ENABLE_FTS5
int sqlite3Fts5Init(sqlite3*);
#endif
#ifndef SQLITE_AMALGAMATION
/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
** contains the text of SQLITE_VERSION macro.
*/
const char sqlite3_version[] = SQLITE_VERSION;
#endif
/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
** a pointer to the to the sqlite3_version[] string constant.
*/
const char *sqlite3_libversion(void){ return sqlite3_version; }
/* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
** pointer to a string constant whose value is the same as the
** SQLITE_SOURCE_ID C preprocessor macro.
*/
const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
** returns an integer equal to SQLITE_VERSION_NUMBER.
*/
int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
** zero if and only if SQLite was compiled with mutexing code omitted due to
** the SQLITE_THREADSAFE compile-time option being set to 0.
*/
int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
/*
** When compiling the test fixture or with debugging enabled (on Win32),
** this variable being set to non-zero will cause OSTRACE macros to emit
** extra diagnostic information.
*/
#ifdef SQLITE_HAVE_OS_TRACE
# ifndef SQLITE_DEBUG_OS_TRACE
# define SQLITE_DEBUG_OS_TRACE 0
# endif
int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
#endif
#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
/*
** If the following function pointer is not NULL and if
** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
** I/O active are written using this function. These messages
** are intended for debugging activity only.
*/
SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
#endif
/*
** If the following global variable points to a string which is the
** name of a directory, then that directory will be used to store
** temporary files.
**
** See also the "PRAGMA temp_store_directory" SQL command.
*/
char *sqlite3_temp_directory = 0;
/*
** If the following global variable points to a string which is the
** name of a directory, then that directory will be used to store
** all database files specified with a relative pathname.
**
** See also the "PRAGMA data_store_directory" SQL command.
*/
char *sqlite3_data_directory = 0;
/*
** Initialize SQLite.
**
** This routine must be called to initialize the memory allocation,
** VFS, and mutex subsystems prior to doing any serious work with
** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
** this routine will be called automatically by key routines such as
** sqlite3_open().
**
** This routine is a no-op except on its very first call for the process,
** or for the first call after a call to sqlite3_shutdown.
**
** The first thread to call this routine runs the initialization to
** completion. If subsequent threads call this routine before the first
** thread has finished the initialization process, then the subsequent
** threads must block until the first thread finishes with the initialization.
**
** The first thread might call this routine recursively. Recursive
** calls to this routine should not block, of course. Otherwise the
** initialization process would never complete.
**
** Let X be the first thread to enter this routine. Let Y be some other
** thread. Then while the initial invocation of this routine by X is
** incomplete, it is required that:
**
** * Calls to this routine from Y must block until the outer-most
** call by X completes.
**
** * Recursive calls to this routine from thread X return immediately
** without blocking.
*/
int sqlite3_initialize(void){
MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
int rc; /* Result code */
#ifdef SQLITE_EXTRA_INIT
int bRunExtraInit = 0; /* Extra initialization needed */
#endif
#ifdef SQLITE_OMIT_WSD
rc = sqlite3_wsd_init(4096, 24);
if( rc!=SQLITE_OK ){
return rc;
}
#endif
/* If the following assert() fails on some obscure processor/compiler
** combination, the work-around is to set the correct pointer
** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
assert( SQLITE_PTRSIZE==sizeof(char*) );
/* If SQLite is already completely initialized, then this call
** to sqlite3_initialize() should be a no-op. But the initialization
** must be complete. So isInit must not be set until the very end
** of this routine.
*/
if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
/* Make sure the mutex subsystem is initialized. If unable to
** initialize the mutex subsystem, return early with the error.
** If the system is so sick that we are unable to allocate a mutex,
** there is not much SQLite is going to be able to do.
**
** The mutex subsystem must take care of serializing its own
** initialization.
*/
rc = sqlite3MutexInit();
if( rc ) return rc;
/* Initialize the malloc() system and the recursive pInitMutex mutex.
** This operation is protected by the STATIC_MASTER mutex. Note that
** MutexAlloc() is called for a static mutex prior to initializing the
** malloc subsystem - this implies that the allocation of a static
** mutex must not require support from the malloc subsystem.
*/
MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
sqlite3_mutex_enter(pMaster);
sqlite3GlobalConfig.isMutexInit = 1;
if( !sqlite3GlobalConfig.isMallocInit ){
rc = sqlite3MallocInit();
}
if( rc==SQLITE_OK ){
sqlite3GlobalConfig.isMallocInit = 1;
if( !sqlite3GlobalConfig.pInitMutex ){
sqlite3GlobalConfig.pInitMutex =
sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
rc = SQLITE_NOMEM_BKPT;
}
}
}
if( rc==SQLITE_OK ){
sqlite3GlobalConfig.nRefInitMutex++;
}
sqlite3_mutex_leave(pMaster);
/* If rc is not SQLITE_OK at this point, then either the malloc
** subsystem could not be initialized or the system failed to allocate
** the pInitMutex mutex. Return an error in either case. */
if( rc!=SQLITE_OK ){
return rc;
}
/* Do the rest of the initialization under the recursive mutex so
** that we will be able to handle recursive calls into
** sqlite3_initialize(). The recursive calls normally come through
** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
** recursive calls might also be possible.
**
** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
** to the xInit method, so the xInit method need not be threadsafe.
**
** The following mutex is what serializes access to the appdef pcache xInit
** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
** call to sqlite3PcacheInitialize().
*/
sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
sqlite3GlobalConfig.inProgress = 1;
#ifdef SQLITE_ENABLE_SQLLOG
{
extern void sqlite3_init_sqllog(void);
sqlite3_init_sqllog();
}
#endif
memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
sqlite3RegisterBuiltinFunctions();
if( sqlite3GlobalConfig.isPCacheInit==0 ){
rc = sqlite3PcacheInitialize();
}
if( rc==SQLITE_OK ){
sqlite3GlobalConfig.isPCacheInit = 1;
rc = sqlite3OsInit();
}
if( rc==SQLITE_OK ){
sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
sqlite3GlobalConfig.isInit = 1;
#ifdef SQLITE_EXTRA_INIT
bRunExtraInit = 1;
#endif
}
sqlite3GlobalConfig.inProgress = 0;
}
sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
/* Go back under the static mutex and clean up the recursive
** mutex to prevent a resource leak.
*/
sqlite3_mutex_enter(pMaster);
sqlite3GlobalConfig.nRefInitMutex--;
if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
assert( sqlite3GlobalConfig.nRefInitMutex==0 );
sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
sqlite3GlobalConfig.pInitMutex = 0;
}
sqlite3_mutex_leave(pMaster);
/* The following is just a sanity check to make sure SQLite has
** been compiled correctly. It is important to run this code, but
** we don't want to run it too often and soak up CPU cycles for no
** reason. So we run it once during initialization.
*/
#ifndef NDEBUG
#ifndef SQLITE_OMIT_FLOATING_POINT
/* This section of code's only "output" is via assert() statements. */
if ( rc==SQLITE_OK ){
u64 x = (((u64)1)<<63)-1;
double y;
assert(sizeof(x)==8);
assert(sizeof(x)==sizeof(y));
memcpy(&y, &x, 8);
assert( sqlite3IsNaN(y) );
}
#endif
#endif
/* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
** compile-time option.
*/
#ifdef SQLITE_EXTRA_INIT
if( bRunExtraInit ){
int SQLITE_EXTRA_INIT(const char*);
rc = SQLITE_EXTRA_INIT(0);
}
#endif
return rc;
}
/*
** Undo the effects of sqlite3_initialize(). Must not be called while
** there are outstanding database connections or memory allocations or
** while any part of SQLite is otherwise in use in any thread. This
** routine is not threadsafe. But it is safe to invoke this routine
** on when SQLite is already shut down. If SQLite is already shut down
** when this routine is invoked, then this routine is a harmless no-op.
*/
int sqlite3_shutdown(void){
#ifdef SQLITE_OMIT_WSD
int rc = sqlite3_wsd_init(4096, 24);
if( rc!=SQLITE_OK ){
return rc;
}
#endif
if( sqlite3GlobalConfig.isInit ){
#ifdef SQLITE_EXTRA_SHUTDOWN
void SQLITE_EXTRA_SHUTDOWN(void);
SQLITE_EXTRA_SHUTDOWN();
#endif
sqlite3_os_end();
sqlite3_reset_auto_extension();
sqlite3GlobalConfig.isInit = 0;
}
if( sqlite3GlobalConfig.isPCacheInit ){
sqlite3PcacheShutdown();
sqlite3GlobalConfig.isPCacheInit = 0;
}
if( sqlite3GlobalConfig.isMallocInit ){
sqlite3MallocEnd();
sqlite3GlobalConfig.isMallocInit = 0;
#ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
/* The heap subsystem has now been shutdown and these values are supposed
** to be NULL or point to memory that was obtained from sqlite3_malloc(),
** which would rely on that heap subsystem; therefore, make sure these
** values cannot refer to heap memory that was just invalidated when the
** heap subsystem was shutdown. This is only done if the current call to
** this function resulted in the heap subsystem actually being shutdown.
*/
sqlite3_data_directory = 0;
sqlite3_temp_directory = 0;
#endif
}
if( sqlite3GlobalConfig.isMutexInit ){
sqlite3MutexEnd();
sqlite3GlobalConfig.isMutexInit = 0;
}
return SQLITE_OK;
}
/*
** This API allows applications to modify the global configuration of
** the SQLite library at run-time.
**
** This routine should only be called when there are no outstanding
** database connections or memory allocations. This routine is not
** threadsafe. Failure to heed these warnings can lead to unpredictable
** behavior.
*/
int sqlite3_config(int op, ...){
va_list ap;
int rc = SQLITE_OK;
/* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
** the SQLite library is in use. */
if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
va_start(ap, op);
switch( op ){
/* Mutex configuration options are only available in a threadsafe
** compile.
*/
#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
case SQLITE_CONFIG_SINGLETHREAD: {
/* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
** Single-thread. */
sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
break;
}
#endif
#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
case SQLITE_CONFIG_MULTITHREAD: {
/* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
** Multi-thread. */
sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
break;
}
#endif
#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
case SQLITE_CONFIG_SERIALIZED: {
/* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
** Serialized. */
sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
break;
}
#endif
#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
case SQLITE_CONFIG_MUTEX: {
/* Specify an alternative mutex implementation */
sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
break;
}
#endif
#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
case SQLITE_CONFIG_GETMUTEX: {
/* Retrieve the current mutex implementation */
*va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
break;
}
#endif
case SQLITE_CONFIG_MALLOC: {
/* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
** single argument which is a pointer to an instance of the
** sqlite3_mem_methods structure. The argument specifies alternative
** low-level memory allocation routines to be used in place of the memory
** allocation routines built into SQLite. */
sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
break;
}
case SQLITE_CONFIG_GETMALLOC: {
/* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
** single argument which is a pointer to an instance of the
** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
** filled with the currently defined memory allocation routines. */
if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
*va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
break;
}
case SQLITE_CONFIG_MEMSTATUS: {
/* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
** single argument of type int, interpreted as a boolean, which enables
** or disables the collection of memory allocation statistics. */
sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
break;
}
case SQLITE_CONFIG_SCRATCH: {
/* EVIDENCE-OF: R-08404-60887 There are three arguments to
** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
** which the scratch allocations will be drawn, the size of each scratch
** allocation (sz), and the maximum number of scratch allocations (N). */
sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
sqlite3GlobalConfig.szScratch = va_arg(ap, int);
sqlite3GlobalConfig.nScratch = va_arg(ap, int);
break;
}
case SQLITE_CONFIG_PAGECACHE: {
/* EVIDENCE-OF: R-18761-36601 There are three arguments to
** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
** the size of each page cache line (sz), and the number of cache lines
** (N). */
sqlite3GlobalConfig.pPage = va_arg(ap, void*);
sqlite3GlobalConfig.szPage = va_arg(ap, int);
sqlite3GlobalConfig.nPage = va_arg(ap, int);
break;
}
case SQLITE_CONFIG_PCACHE_HDRSZ: {
/* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
** a single parameter which is a pointer to an integer and writes into
** that integer the number of extra bytes per page required for each page
** in SQLITE_CONFIG_PAGECACHE. */
*va_arg(ap, int*) =
sqlite3HeaderSizeBtree() +
sqlite3HeaderSizePcache() +
sqlite3HeaderSizePcache1();
break;
}
case SQLITE_CONFIG_PCACHE: {
/* no-op */
break;
}
case SQLITE_CONFIG_GETPCACHE: {
/* now an error */
rc = SQLITE_ERROR;
break;
}
case SQLITE_CONFIG_PCACHE2: {
/* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
** single argument which is a pointer to an sqlite3_pcache_methods2
** object. This object specifies the interface to a custom page cache
** implementation. */
sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
break;
}
case SQLITE_CONFIG_GETPCACHE2: {
/* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
** single argument which is a pointer to an sqlite3_pcache_methods2
** object. SQLite copies of the current page cache implementation into
** that object. */
if( sqlite3GlobalConfig.pcache2.xInit==0 ){
sqlite3PCacheSetDefault();
}
*va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
break;
}
/* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
case SQLITE_CONFIG_HEAP: {
/* EVIDENCE-OF: R-19854-42126 There are three arguments to
** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
** number of bytes in the memory buffer, and the minimum allocation size.
*/
sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
sqlite3GlobalConfig.nHeap = va_arg(ap, int);
sqlite3GlobalConfig.mnReq = va_arg(ap, int);
if( sqlite3GlobalConfig.mnReq<1 ){
sqlite3GlobalConfig.mnReq = 1;
}else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
/* cap min request size at 2^12 */
sqlite3GlobalConfig.mnReq = (1<<12);
}
if( sqlite3GlobalConfig.pHeap==0 ){
/* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
** is NULL, then SQLite reverts to using its default memory allocator
** (the system malloc() implementation), undoing any prior invocation of
** SQLITE_CONFIG_MALLOC.
**
** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
** revert to its default implementation when sqlite3_initialize() is run
*/
memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
}else{
/* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
** alternative memory allocator is engaged to handle all of SQLites
** memory allocation needs. */
#ifdef SQLITE_ENABLE_MEMSYS3
sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
#endif
#ifdef SQLITE_ENABLE_MEMSYS5
sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
#endif
}
break;
}
#endif
case SQLITE_CONFIG_LOOKASIDE: {
sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
break;
}
/* Record a pointer to the logger function and its first argument.
** The default is NULL. Logging is disabled if the function pointer is
** NULL.
*/
case SQLITE_CONFIG_LOG: {
/* MSVC is picky about pulling func ptrs from va lists.
** http://support.microsoft.com/kb/47961
** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
*/
typedef void(*LOGFUNC_t)(void*,int,const char*);
sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
break;
}
/* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
** can be changed at start-time using the
** sqlite3_config(SQLITE_CONFIG_URI,1) or
** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
*/
case SQLITE_CONFIG_URI: {
/* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
** argument of type int. If non-zero, then URI handling is globally
** enabled. If the parameter is zero, then URI handling is globally
** disabled. */
sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
break;
}
case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
/* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
** option takes a single integer argument which is interpreted as a
** boolean in order to enable or disable the use of covering indices for
** full table scans in the query optimizer. */
sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
break;
}
#ifdef SQLITE_ENABLE_SQLLOG
case SQLITE_CONFIG_SQLLOG: {
typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
break;
}
#endif
case SQLITE_CONFIG_MMAP_SIZE: {
/* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
** integer (sqlite3_int64) values that are the default mmap size limit
** (the default setting for PRAGMA mmap_size) and the maximum allowed
** mmap size limit. */
sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
/* EVIDENCE-OF: R-53367-43190 If either argument to this option is
** negative, then that argument is changed to its compile-time default.
**
** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
** silently truncated if necessary so that it does not exceed the
** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
** compile-time option.
*/
if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
mxMmap = SQLITE_MAX_MMAP_SIZE;
}
if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
if( szMmap>mxMmap) szMmap = mxMmap;
sqlite3GlobalConfig.mxMmap = mxMmap;
sqlite3GlobalConfig.szMmap = szMmap;
break;
}
#if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
case SQLITE_CONFIG_WIN32_HEAPSIZE: {
/* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
** unsigned integer value that specifies the maximum size of the created
** heap. */
sqlite3GlobalConfig.nHeap = va_arg(ap, int);
break;
}
#endif
case SQLITE_CONFIG_PMASZ: {
sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
break;
}
case SQLITE_CONFIG_STMTJRNL_SPILL: {
sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
break;
}
default: {
rc = SQLITE_ERROR;
break;
}
}
va_end(ap);
return rc;
}
/*
** Set up the lookaside buffers for a database connection.
** Return SQLITE_OK on success.
** If lookaside is already active, return SQLITE_BUSY.
**
** The sz parameter is the number of bytes in each lookaside slot.
** The cnt parameter is the number of slots. If pStart is NULL the
** space for the lookaside memory is obtained from sqlite3_malloc().
** If pStart is not NULL then it is sz*cnt bytes of memory to use for
** the lookaside memory.
*/
static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
#ifndef SQLITE_OMIT_LOOKASIDE
void *pStart;
if( db->lookaside.nOut ){
return SQLITE_BUSY;
}
/* Free any existing lookaside buffer for this handle before
** allocating a new one so we don't have to have space for
** both at the same time.
*/
if( db->lookaside.bMalloced ){
sqlite3_free(db->lookaside.pStart);
}
/* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
** than a pointer to be useful.
*/
sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
if( cnt<0 ) cnt = 0;
if( sz==0 || cnt==0 ){
sz = 0;
pStart = 0;
}else if( pBuf==0 ){
sqlite3BeginBenignMalloc();
pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
sqlite3EndBenignMalloc();
if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
}else{
pStart = pBuf;
}
db->lookaside.pStart = pStart;
db->lookaside.pFree = 0;
db->lookaside.sz = (u16)sz;
if( pStart ){
int i;
LookasideSlot *p;
assert( sz > (int)sizeof(LookasideSlot*) );
p = (LookasideSlot*)pStart;
for(i=cnt-1; i>=0; i--){
p->pNext = db->lookaside.pFree;
db->lookaside.pFree = p;
p = (LookasideSlot*)&((u8*)p)[sz];
}
db->lookaside.pEnd = p;
db->lookaside.bDisable = 0;
db->lookaside.bMalloced = pBuf==0 ?1:0;
}else{
db->lookaside.pStart = db;
db->lookaside.pEnd = db;
db->lookaside.bDisable = 1;
db->lookaside.bMalloced = 0;
}
#endif /* SQLITE_OMIT_LOOKASIDE */
return SQLITE_OK;
}
/*
** Return the mutex associated with a database connection.
*/
sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ){
(void)SQLITE_MISUSE_BKPT;
return 0;
}
#endif
return db->mutex;
}
/*
** Free up as much memory as we can from the given database
** connection.
*/
int sqlite3_db_release_memory(sqlite3 *db){
int i;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
#endif
sqlite3_mutex_enter(db->mutex);
sqlite3BtreeEnterAll(db);
for(i=0; i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( pBt ){
Pager *pPager = sqlite3BtreePager(pBt);
sqlite3PagerShrink(pPager);
}
}
sqlite3BtreeLeaveAll(db);
sqlite3_mutex_leave(db->mutex);
return SQLITE_OK;
}
/*
** Flush any dirty pages in the pager-cache for any attached database
** to disk.
*/
int sqlite3_db_cacheflush(sqlite3 *db){
int i;
int rc = SQLITE_OK;
int bSeenBusy = 0;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
#endif
sqlite3_mutex_enter(db->mutex);
sqlite3BtreeEnterAll(db);
for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( pBt && sqlite3BtreeIsInTrans(pBt) ){
Pager *pPager = sqlite3BtreePager(pBt);
rc = sqlite3PagerFlush(pPager);
if( rc==SQLITE_BUSY ){
bSeenBusy = 1;
rc = SQLITE_OK;
}
}
}
sqlite3BtreeLeaveAll(db);
sqlite3_mutex_leave(db->mutex);
return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
}
/*
** Configuration settings for an individual database connection
*/
int sqlite3_db_config(sqlite3 *db, int op, ...){
va_list ap;
int rc;
va_start(ap, op);
switch( op ){
case SQLITE_DBCONFIG_MAINDBNAME: {
db->aDb[0].zDbSName = va_arg(ap,char*);
rc = SQLITE_OK;
break;
}
case SQLITE_DBCONFIG_LOOKASIDE: {
void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
rc = setupLookaside(db, pBuf, sz, cnt);
break;
}
default: {
static const struct {
int op; /* The opcode */
u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
} aFlagOp[] = {
{ SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
{ SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
{ SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
{ SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension },
};
unsigned int i;
rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
for(i=0; i<ArraySize(aFlagOp); i++){
if( aFlagOp[i].op==op ){
int onoff = va_arg(ap, int);
int *pRes = va_arg(ap, int*);
int oldFlags = db->flags;
if( onoff>0 ){
db->flags |= aFlagOp[i].mask;
}else if( onoff==0 ){
db->flags &= ~aFlagOp[i].mask;
}
if( oldFlags!=db->flags ){
sqlite3ExpirePreparedStatements(db);
}
if( pRes ){
*pRes = (db->flags & aFlagOp[i].mask)!=0;
}
rc = SQLITE_OK;
break;
}
}
break;
}
}
va_end(ap);
return rc;
}
/*
** Return true if the buffer z[0..n-1] contains all spaces.
*/
static int allSpaces(const char *z, int n){
while( n>0 && z[n-1]==' ' ){ n--; }
return n==0;
}
/*
** This is the default collating function named "BINARY" which is always
** available.
**
** If the padFlag argument is not NULL then space padding at the end
** of strings is ignored. This implements the RTRIM collation.
*/
static int binCollFunc(
void *padFlag,
int nKey1, const void *pKey1,
int nKey2, const void *pKey2
){
int rc, n;
n = nKey1<nKey2 ? nKey1 : nKey2;
/* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
** strings byte by byte using the memcmp() function from the standard C
** library. */
rc = memcmp(pKey1, pKey2, n);
if( rc==0 ){
if( padFlag
&& allSpaces(((char*)pKey1)+n, nKey1-n)
&& allSpaces(((char*)pKey2)+n, nKey2-n)
){
/* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
** spaces at the end of either string do not change the result. In other
** words, strings will compare equal to one another as long as they
** differ only in the number of spaces at the end.
*/
}else{
rc = nKey1 - nKey2;
}
}
return rc;
}
/*
** Another built-in collating sequence: NOCASE.
**
** This collating sequence is intended to be used for "case independent
** comparison". SQLite's knowledge of upper and lower case equivalents
** extends only to the 26 characters used in the English language.
**
** At the moment there is only a UTF-8 implementation.
*/
static int nocaseCollatingFunc(
void *NotUsed,
int nKey1, const void *pKey1,
int nKey2, const void *pKey2
){
int r = sqlite3StrNICmp(
(const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
UNUSED_PARAMETER(NotUsed);
if( 0==r ){
r = nKey1-nKey2;
}
return r;
}
/*
** Return the ROWID of the most recent insert
*/
sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ){
(void)SQLITE_MISUSE_BKPT;
return 0;
}
#endif
return db->lastRowid;
}
/*
** Return the number of changes in the most recent call to sqlite3_exec().
*/
int sqlite3_changes(sqlite3 *db){
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ){
(void)SQLITE_MISUSE_BKPT;
return 0;
}
#endif
return db->nChange;
}
/*
** Return the number of changes since the database handle was opened.
*/
int sqlite3_total_changes(sqlite3 *db){
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ){
(void)SQLITE_MISUSE_BKPT;
return 0;
}
#endif
return db->nTotalChange;
}
/*
** Close all open savepoints. This function only manipulates fields of the
** database handle object, it does not close any savepoints that may be open
** at the b-tree/pager level.
*/
void sqlite3CloseSavepoints(sqlite3 *db){
while( db->pSavepoint ){
Savepoint *pTmp = db->pSavepoint;
db->pSavepoint = pTmp->pNext;
sqlite3DbFree(db, pTmp);
}
db->nSavepoint = 0;
db->nStatement = 0;
db->isTransactionSavepoint = 0;
}
/*
** Invoke the destructor function associated with FuncDef p, if any. Except,
** if this is not the last copy of the function, do not invoke it. Multiple
** copies of a single function are created when create_function() is called
** with SQLITE_ANY as the encoding.
*/
static void functionDestroy(sqlite3 *db, FuncDef *p){
FuncDestructor *pDestructor = p->u.pDestructor;
if( pDestructor ){
pDestructor->nRef--;
if( pDestructor->nRef==0 ){
pDestructor->xDestroy(pDestructor->pUserData);
sqlite3DbFree(db, pDestructor);
}
}
}
/*
** Disconnect all sqlite3_vtab objects that belong to database connection
** db. This is called when db is being closed.
*/
static void disconnectAllVtab(sqlite3 *db){
#ifndef SQLITE_OMIT_VIRTUALTABLE
int i;
HashElem *p;
sqlite3BtreeEnterAll(db);
for(i=0; i<db->nDb; i++){
Schema *pSchema = db->aDb[i].pSchema;
if( db->aDb[i].pSchema ){
for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
Table *pTab = (Table *)sqliteHashData(p);
if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
}
}
}
for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
Module *pMod = (Module *)sqliteHashData(p);
if( pMod->pEpoTab ){
sqlite3VtabDisconnect(db, pMod->pEpoTab);
}
}
sqlite3VtabUnlockList(db);
sqlite3BtreeLeaveAll(db);
#else
UNUSED_PARAMETER(db);
#endif
}
/*
** Return TRUE if database connection db has unfinalized prepared
** statements or unfinished sqlite3_backup objects.
*/
static int connectionIsBusy(sqlite3 *db){
int j;
assert( sqlite3_mutex_held(db->mutex) );
if( db->pVdbe ) return 1;
for(j=0; j<db->nDb; j++){
Btree *pBt = db->aDb[j].pBt;
if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
}
return 0;
}
/*
** Close an existing SQLite database
*/
static int sqlite3Close(sqlite3 *db, int forceZombie){
if( !db ){
/* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
return SQLITE_OK;
}
if( !sqlite3SafetyCheckSickOrOk(db) ){
return SQLITE_MISUSE_BKPT;
}
sqlite3_mutex_enter(db->mutex);
if( db->mTrace & SQLITE_TRACE_CLOSE ){
db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
}
/* Force xDisconnect calls on all virtual tables */
disconnectAllVtab(db);
/* If a transaction is open, the disconnectAllVtab() call above
** will not have called the xDisconnect() method on any virtual
** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
** call will do so. We need to do this before the check for active
** SQL statements below, as the v-table implementation may be storing
** some prepared statements internally.
*/
sqlite3VtabRollback(db);
/* Legacy behavior (sqlite3_close() behavior) is to return
** SQLITE_BUSY if the connection can not be closed immediately.
*/
if( !forceZombie && connectionIsBusy(db) ){
sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
"statements or unfinished backups");
sqlite3_mutex_leave(db->mutex);
return SQLITE_BUSY;
}
#ifdef SQLITE_ENABLE_SQLLOG
if( sqlite3GlobalConfig.xSqllog ){
/* Closing the handle. Fourth parameter is passed the value 2. */
sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
}
#endif
/* Convert the connection into a zombie and then close it.
*/
db->magic = SQLITE_MAGIC_ZOMBIE;
sqlite3LeaveMutexAndCloseZombie(db);
return SQLITE_OK;
}
/*
** Two variations on the public interface for closing a database
** connection. The sqlite3_close() version returns SQLITE_BUSY and
** leaves the connection option if there are unfinalized prepared
** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
** version forces the connection to become a zombie if there are
** unclosed resources, and arranges for deallocation when the last
** prepare statement or sqlite3_backup closes.
*/
int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
/*
** Close the mutex on database connection db.
**
** Furthermore, if database connection db is a zombie (meaning that there
** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
** every sqlite3_stmt has now been finalized and every sqlite3_backup has
** finished, then free all resources.
*/
void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
HashElem *i; /* Hash table iterator */
int j;
/* If there are outstanding sqlite3_stmt or sqlite3_backup objects
** or if the connection has not yet been closed by sqlite3_close_v2(),
** then just leave the mutex and return.
*/
if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
sqlite3_mutex_leave(db->mutex);
return;
}
/* If we reach this point, it means that the database connection has
** closed all sqlite3_stmt and sqlite3_backup objects and has been
** passed to sqlite3_close (meaning that it is a zombie). Therefore,
** go ahead and free all resources.
*/
/* If a transaction is open, roll it back. This also ensures that if
** any database schemas have been modified by an uncommitted transaction
** they are reset. And that the required b-tree mutex is held to make
** the pager rollback and schema reset an atomic operation. */
sqlite3RollbackAll(db, SQLITE_OK);
/* Free any outstanding Savepoint structures. */
sqlite3CloseSavepoints(db);
/* Close all database connections */
for(j=0; j<db->nDb; j++){
struct Db *pDb = &db->aDb[j];
if( pDb->pBt ){
sqlite3BtreeClose(pDb->pBt);
pDb->pBt = 0;
if( j!=1 ){
pDb->pSchema = 0;
}
}
}
/* Clear the TEMP schema separately and last */
if( db->aDb[1].pSchema ){
sqlite3SchemaClear(db->aDb[1].pSchema);
}
sqlite3VtabUnlockList(db);
/* Free up the array of auxiliary databases */
sqlite3CollapseDatabaseArray(db);
assert( db->nDb<=2 );
assert( db->aDb==db->aDbStatic );
/* Tell the code in notify.c that the connection no longer holds any
** locks and does not require any further unlock-notify callbacks.
*/
sqlite3ConnectionClosed(db);
for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
FuncDef *pNext, *p;
p = sqliteHashData(i);
do{
functionDestroy(db, p);
pNext = p->pNext;
sqlite3DbFree(db, p);
p = pNext;
}while( p );
}
sqlite3HashClear(&db->aFunc);
for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
CollSeq *pColl = (CollSeq *)sqliteHashData(i);
/* Invoke any destructors registered for collation sequence user data. */
for(j=0; j<3; j++){
if( pColl[j].xDel ){
pColl[j].xDel(pColl[j].pUser);
}
}
sqlite3DbFree(db, pColl);
}
sqlite3HashClear(&db->aCollSeq);
#ifndef SQLITE_OMIT_VIRTUALTABLE
for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
Module *pMod = (Module *)sqliteHashData(i);
if( pMod->xDestroy ){
pMod->xDestroy(pMod->pAux);
}
sqlite3VtabEponymousTableClear(db, pMod);
sqlite3DbFree(db, pMod);
}
sqlite3HashClear(&db->aModule);
#endif
sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
sqlite3ValueFree(db->pErr);
sqlite3CloseExtensions(db);
#if SQLITE_USER_AUTHENTICATION
sqlite3_free(db->auth.zAuthUser);
sqlite3_free(db->auth.zAuthPW);
#endif
db->magic = SQLITE_MAGIC_ERROR;
/* The temp-database schema is allocated differently from the other schema
** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
** So it needs to be freed here. Todo: Why not roll the temp schema into
** the same sqliteMalloc() as the one that allocates the database
** structure?
*/
sqlite3DbFree(db, db->aDb[1].pSchema);
sqlite3_mutex_leave(db->mutex);
db->magic = SQLITE_MAGIC_CLOSED;
sqlite3_mutex_free(db->mutex);
assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
if( db->lookaside.bMalloced ){
sqlite3_free(db->lookaside.pStart);
}
sqlite3_free(db);
}
/*
** Rollback all database files. If tripCode is not SQLITE_OK, then
** any write cursors are invalidated ("tripped" - as in "tripping a circuit
** breaker") and made to return tripCode if there are any further
** attempts to use that cursor. Read cursors remain open and valid
** but are "saved" in case the table pages are moved around.
*/
void sqlite3RollbackAll(sqlite3 *db, int tripCode){
int i;
int inTrans = 0;
int schemaChange;
assert( sqlite3_mutex_held(db->mutex) );
sqlite3BeginBenignMalloc();
/* Obtain all b-tree mutexes before making any calls to BtreeRollback().
** This is important in case the transaction being rolled back has
** modified the database schema. If the b-tree mutexes are not taken
** here, then another shared-cache connection might sneak in between
** the database rollback and schema reset, which can cause false
** corruption reports in some cases. */
sqlite3BtreeEnterAll(db);
schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
for(i=0; i<db->nDb; i++){
Btree *p = db->aDb[i].pBt;
if( p ){
if( sqlite3BtreeIsInTrans(p) ){
inTrans = 1;
}
sqlite3BtreeRollback(p, tripCode, !schemaChange);
}
}
sqlite3VtabRollback(db);
sqlite3EndBenignMalloc();
if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
sqlite3ExpirePreparedStatements(db);
sqlite3ResetAllSchemasOfConnection(db);
}
sqlite3BtreeLeaveAll(db);
/* Any deferred constraint violations have now been resolved. */
db->nDeferredCons = 0;
db->nDeferredImmCons = 0;
db->flags &= ~SQLITE_DeferFKs;
/* If one has been configured, invoke the rollback-hook callback */
if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
db->xRollbackCallback(db->pRollbackArg);
}
}
/*
** Return a static string containing the name corresponding to the error code
** specified in the argument.
*/
#if defined(SQLITE_NEED_ERR_NAME)
const char *sqlite3ErrName(int rc){
const char *zName = 0;
int i, origRc = rc;
for(i=0; i<2 && zName==0; i++, rc &= 0xff){
switch( rc ){
case SQLITE_OK: zName = "SQLITE_OK"; break;
case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
case SQLITE_PERM: zName = "SQLITE_PERM"; break;
case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
case SQLITE_IOERR_CHECKRESERVEDLOCK:
zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
case SQLITE_FULL: zName = "SQLITE_FULL"; break;
case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
case SQLITE_CONSTRAINT_FOREIGNKEY:
zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
case SQLITE_CONSTRAINT_PRIMARYKEY:
zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
case SQLITE_CONSTRAINT_COMMITHOOK:
zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
case SQLITE_CONSTRAINT_FUNCTION:
zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
case SQLITE_ROW: zName = "SQLITE_ROW"; break;
case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
case SQLITE_NOTICE_RECOVER_ROLLBACK:
zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
case SQLITE_DONE: zName = "SQLITE_DONE"; break;
}
}
if( zName==0 ){
static char zBuf[50];
sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
zName = zBuf;
}
return zName;
}
#endif
/*
** Return a static string that describes the kind of error specified in the
** argument.
*/
const char *sqlite3ErrStr(int rc){
static const char* const aMsg[] = {
/* SQLITE_OK */ "not an error",
/* SQLITE_ERROR */ "SQL logic error or missing database",
/* SQLITE_INTERNAL */ 0,
/* SQLITE_PERM */ "access permission denied",
/* SQLITE_ABORT */ "callback requested query abort",
/* SQLITE_BUSY */ "database is locked",
/* SQLITE_LOCKED */ "database table is locked",
/* SQLITE_NOMEM */ "out of memory",
/* SQLITE_READONLY */ "attempt to write a readonly database",
/* SQLITE_INTERRUPT */ "interrupted",
/* SQLITE_IOERR */ "disk I/O error",
/* SQLITE_CORRUPT */ "database disk image is malformed",
/* SQLITE_NOTFOUND */ "unknown operation",
/* SQLITE_FULL */ "database or disk is full",
/* SQLITE_CANTOPEN */ "unable to open database file",
/* SQLITE_PROTOCOL */ "locking protocol",
/* SQLITE_EMPTY */ "table contains no data",
/* SQLITE_SCHEMA */ "database schema has changed",
/* SQLITE_TOOBIG */ "string or blob too big",
/* SQLITE_CONSTRAINT */ "constraint failed",
/* SQLITE_MISMATCH */ "datatype mismatch",
/* SQLITE_MISUSE */ "library routine called out of sequence",
/* SQLITE_NOLFS */ "large file support is disabled",
/* SQLITE_AUTH */ "authorization denied",
/* SQLITE_FORMAT */ "auxiliary database format error",
/* SQLITE_RANGE */ "bind or column index out of range",
/* SQLITE_NOTADB */ "file is encrypted or is not a database",
};
const char *zErr = "unknown error";
switch( rc ){
case SQLITE_ABORT_ROLLBACK: {
zErr = "abort due to ROLLBACK";
break;
}
default: {
rc &= 0xff;
if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
zErr = aMsg[rc];
}
break;
}
}
return zErr;
}
/*
** This routine implements a busy callback that sleeps and tries
** again until a timeout value is reached. The timeout value is
** an integer number of milliseconds passed in as the first
** argument.
*/
static int sqliteDefaultBusyCallback(
void *ptr, /* Database connection */
int count /* Number of times table has been busy */
){
#if SQLITE_OS_WIN || HAVE_USLEEP
static const u8 delays[] =
{ 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
static const u8 totals[] =
{ 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
# define NDELAY ArraySize(delays)
sqlite3 *db = (sqlite3 *)ptr;
int timeout = db->busyTimeout;
int delay, prior;
assert( count>=0 );
if( count < NDELAY ){
delay = delays[count];
prior = totals[count];
}else{
delay = delays[NDELAY-1];
prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
}
if( prior + delay > timeout ){
delay = timeout - prior;
if( delay<=0 ) return 0;
}
sqlite3OsSleep(db->pVfs, delay*1000);
return 1;
#else
sqlite3 *db = (sqlite3 *)ptr;
int timeout = ((sqlite3 *)ptr)->busyTimeout;
if( (count+1)*1000 > timeout ){
return 0;
}
sqlite3OsSleep(db->pVfs, 1000000);
return 1;
#endif
}
/*
** Invoke the given busy handler.
**
** This routine is called when an operation failed with a lock.
** If this routine returns non-zero, the lock is retried. If it
** returns 0, the operation aborts with an SQLITE_BUSY error.
*/
int sqlite3InvokeBusyHandler(BusyHandler *p){
int rc;
if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
rc = p->xFunc(p->pArg, p->nBusy);
if( rc==0 ){
p->nBusy = -1;
}else{
p->nBusy++;
}
return rc;
}
/*
** This routine sets the busy callback for an Sqlite database to the
** given callback function with the given argument.
*/
int sqlite3_busy_handler(
sqlite3 *db,
int (*xBusy)(void*,int),
void *pArg
){
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
#endif
sqlite3_mutex_enter(db->mutex);
db->busyHandler.xFunc = xBusy;
db->busyHandler.pArg = pArg;
db->busyHandler.nBusy = 0;
db->busyTimeout = 0;
sqlite3_mutex_leave(db->mutex);
return SQLITE_OK;
}
#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
/*
** This routine sets the progress callback for an Sqlite database to the
** given callback function with the given argument. The progress callback will
** be invoked every nOps opcodes.
*/
void sqlite3_progress_handler(
sqlite3 *db,
int nOps,
int (*xProgress)(void*),
void *pArg
){
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ){
(void)SQLITE_MISUSE_BKPT;
return;
}
#endif
sqlite3_mutex_enter(db->mutex);
if( nOps>0 ){
db->xProgress = xProgress;
db->nProgressOps = (unsigned)nOps;
db->pProgressArg = pArg;
}else{
db->xProgress = 0;
db->nProgressOps = 0;
db->pProgressArg = 0;
}
sqlite3_mutex_leave(db->mutex);
}
#endif
/*
** This routine installs a default busy handler that waits for the
** specified number of milliseconds before returning 0.
*/
int sqlite3_busy_timeout(sqlite3 *db, int ms){
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
#endif
if( ms>0 ){
sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
db->busyTimeout = ms;
}else{
sqlite3_busy_handler(db, 0, 0);
}
return SQLITE_OK;
}
/*
** Cause any pending operation to stop at its earliest opportunity.
*/
void sqlite3_interrupt(sqlite3 *db){
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ){
(void)SQLITE_MISUSE_BKPT;
return;
}
#endif
db->u1.isInterrupted = 1;
}
/*
** This function is exactly the same as sqlite3_create_function(), except
** that it is designed to be called by internal code. The difference is
** that if a malloc() fails in sqlite3_create_function(), an error code
** is returned and the mallocFailed flag cleared.
*/
int sqlite3CreateFunc(
sqlite3 *db,
const char *zFunctionName,
int nArg,
int enc,
void *pUserData,
void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
void (*xStep)(sqlite3_context*,int,sqlite3_value **),
void (*xFinal)(sqlite3_context*),
FuncDestructor *pDestructor
){
FuncDef *p;
int nName;
int extraFlags;
assert( sqlite3_mutex_held(db->mutex) );
if( zFunctionName==0 ||
(xSFunc && (xFinal || xStep)) ||
(!xSFunc && (xFinal && !xStep)) ||
(!xSFunc && (!xFinal && xStep)) ||
(nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
(255<(nName = sqlite3Strlen30( zFunctionName))) ){
return SQLITE_MISUSE_BKPT;
}
assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
extraFlags = enc & SQLITE_DETERMINISTIC;
enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
#ifndef SQLITE_OMIT_UTF16
/* If SQLITE_UTF16 is specified as the encoding type, transform this
** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
**
** If SQLITE_ANY is specified, add three versions of the function
** to the hash table.
*/
if( enc==SQLITE_UTF16 ){
enc = SQLITE_UTF16NATIVE;
}else if( enc==SQLITE_ANY ){
int rc;
rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
pUserData, xSFunc, xStep, xFinal, pDestructor);
if( rc==SQLITE_OK ){
rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
pUserData, xSFunc, xStep, xFinal, pDestructor);
}
if( rc!=SQLITE_OK ){
return rc;
}
enc = SQLITE_UTF16BE;
}
#else
enc = SQLITE_UTF8;
#endif
/* Check if an existing function is being overridden or deleted. If so,
** and there are active VMs, then return SQLITE_BUSY. If a function
** is being overridden/deleted but there are no active VMs, allow the
** operation to continue but invalidate all precompiled statements.
*/
p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
if( db->nVdbeActive ){
sqlite3ErrorWithMsg(db, SQLITE_BUSY,
"unable to delete/modify user-function due to active statements");
assert( !db->mallocFailed );
return SQLITE_BUSY;
}else{
sqlite3ExpirePreparedStatements(db);
}
}
p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
assert(p || db->mallocFailed);
if( !p ){
return SQLITE_NOMEM_BKPT;
}
/* If an older version of the function with a configured destructor is
** being replaced invoke the destructor function here. */
functionDestroy(db, p);
if( pDestructor ){
pDestructor->nRef++;
}
p->u.pDestructor = pDestructor;
p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
testcase( p->funcFlags & SQLITE_DETERMINISTIC );
p->xSFunc = xSFunc ? xSFunc : xStep;
p->xFinalize = xFinal;
p->pUserData = pUserData;
p->nArg = (u16)nArg;
return SQLITE_OK;
}
/*
** Create new user functions.
*/
int sqlite3_create_function(
sqlite3 *db,
const char *zFunc,
int nArg,
int enc,
void *p,
void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
void (*xStep)(sqlite3_context*,int,sqlite3_value **),
void (*xFinal)(sqlite3_context*)
){
return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep,
xFinal, 0);
}
int sqlite3_create_function_v2(
sqlite3 *db,
const char *zFunc,
int nArg,
int enc,
void *p,
void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
void (*xStep)(sqlite3_context*,int,sqlite3_value **),
void (*xFinal)(sqlite3_context*),
void (*xDestroy)(void *)
){
int rc = SQLITE_ERROR;
FuncDestructor *pArg = 0;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ){
return SQLITE_MISUSE_BKPT;
}
#endif
sqlite3_mutex_enter(db->mutex);
if( xDestroy ){
pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
if( !pArg ){
xDestroy(p);
goto out;
}
pArg->xDestroy = xDestroy;
pArg->pUserData = p;
}
rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
if( pArg && pArg->nRef==0 ){
assert( rc!=SQLITE_OK );
xDestroy(p);
sqlite3DbFree(db, pArg);
}
out:
rc = sqlite3ApiExit(db, rc);
sqlite3_mutex_leave(db->mutex);
return rc;
}
#ifndef SQLITE_OMIT_UTF16
int sqlite3_create_function16(
sqlite3 *db,
const void *zFunctionName,
int nArg,
int eTextRep,
void *p,
void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
void (*xStep)(sqlite3_context*,int,sqlite3_value**),
void (*xFinal)(sqlite3_context*)
){
int rc;
char *zFunc8;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
#endif
sqlite3_mutex_enter(db->mutex);
assert( !db->mallocFailed );
zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0);
sqlite3DbFree(db, zFunc8);
rc = sqlite3ApiExit(db, rc);
sqlite3_mutex_leave(db->mutex);
return rc;
}
#endif
/*
** Declare that a function has been overloaded by a virtual table.
**
** If the function already exists as a regular global function, then
** this routine is a no-op. If the function does not exist, then create
** a new one that always throws a run-time error.
**
** When virtual tables intend to provide an overloaded function, they
** should call this routine to make sure the global function exists.
** A global function must exist in order for name resolution to work
** properly.
*/
int sqlite3_overload_function(
sqlite3 *db,
const char *zName,
int nArg
){
int rc = SQLITE_OK;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
return SQLITE_MISUSE_BKPT;
}
#endif
sqlite3_mutex_enter(db->mutex);
if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){
rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
0, sqlite3InvalidFunction, 0, 0, 0);
}
rc = sqlite3ApiExit(db, rc);
sqlite3_mutex_leave(db->mutex);
return rc;
}
#ifndef SQLITE_OMIT_TRACE
/*
** Register a trace function. The pArg from the previously registered trace
** is returned.
**
** A NULL trace function means that no tracing is executes. A non-NULL
** trace is a pointer to a function that is invoked at the start of each
** SQL statement.
*/
#ifndef SQLITE_OMIT_DEPRECATED
void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
void *pOld;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ){
(void)SQLITE_MISUSE_BKPT;
return 0;
}
#endif
sqlite3_mutex_enter(db->mutex);
pOld = db->pTraceArg;
db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
db->pTraceArg = pArg;
sqlite3_mutex_leave(db->mutex);
return pOld;
}
#endif /* SQLITE_OMIT_DEPRECATED */
/* Register a trace callback using the version-2 interface.
*/
int sqlite3_trace_v2(
sqlite3 *db, /* Trace this connection */
unsigned mTrace, /* Mask of events to be traced */
int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */
void *pArg /* Context */
){
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ){
return SQLITE_MISUSE_BKPT;
}
#endif
sqlite3_mutex_enter(db->mutex);
if( mTrace==0 ) xTrace = 0;
if( xTrace==0 ) mTrace = 0;
db->mTrace = mTrace;
db->xTrace = xTrace;
db->pTraceArg = pArg;
sqlite3_mutex_leave(db->mutex);
return SQLITE_OK;
}
#ifndef SQLITE_OMIT_DEPRECATED
/*
** Register a profile function. The pArg from the previously registered
** profile function is returned.
**
** A NULL profile function means that no profiling is executes. A non-NULL
** profile is a pointer to a function that is invoked at the conclusion of
** each SQL statement that is run.
*/
void *sqlite3_profile(
sqlite3 *db,
void (*xProfile)(void*,const char*,sqlite_uint64),
void *pArg
){
void *pOld;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ){
(void)SQLITE_MISUSE_BKPT;
return 0;
}
#endif
sqlite3_mutex_enter(db->mutex);
pOld = db->pProfileArg;
db->xProfile = xProfile;
db->pProfileArg = pArg;
sqlite3_mutex_leave(db->mutex);
return pOld;
}
#endif /* SQLITE_OMIT_DEPRECATED */
#endif /* SQLITE_OMIT_TRACE */
/*
** Register a function to be invoked when a transaction commits.
** If the invoked function returns non-zero, then the commit becomes a
** rollback.
*/
void *sqlite3_commit_hook(
sqlite3 *db, /* Attach the hook to this database */
int (*xCallback)(void*), /* Function to invoke on each commit */
void *pArg /* Argument to the function */
){
void *pOld;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ){
(void)SQLITE_MISUSE_BKPT;
return 0;
}
#endif
sqlite3_mutex_enter(db->mutex);
pOld = db->pCommitArg;
db->xCommitCallback = xCallback;
db->pCommitArg = pArg;
sqlite3_mutex_leave(db->mutex);
return pOld;
}
/*
** Register a callback to be invoked each time a row is updated,
** inserted or deleted using this database connection.
*/
void *sqlite3_update_hook(
sqlite3 *db, /* Attach the hook to this database */
void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
void *pArg /* Argument to the function */
){
void *pRet;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ){
(void)SQLITE_MISUSE_BKPT;
return 0;
}
#endif
sqlite3_mutex_enter(db->mutex);
pRet = db->pUpdateArg;
db->xUpdateCallback = xCallback;
db->pUpdateArg = pArg;
sqlite3_mutex_leave(db->mutex);
return pRet;
}
/*
** Register a callback to be invoked each time a transaction is rolled
** back by this database connection.
*/
void *sqlite3_rollback_hook(
sqlite3 *db, /* Attach the hook to this database */
void (*xCallback)(void*), /* Callback function */
void *pArg /* Argument to the function */
){
void *pRet;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ){
(void)SQLITE_MISUSE_BKPT;
return 0;
}
#endif
sqlite3_mutex_enter(db->mutex);
pRet = db->pRollbackArg;
db->xRollbackCallback = xCallback;
db->pRollbackArg = pArg;
sqlite3_mutex_leave(db->mutex);
return pRet;
}
#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
/*
** Register a callback to be invoked each time a row is updated,
** inserted or deleted using this database connection.
*/
void *sqlite3_preupdate_hook(
sqlite3 *db, /* Attach the hook to this database */
void(*xCallback)( /* Callback function */
void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
void *pArg /* First callback argument */
){
void *pRet;
sqlite3_mutex_enter(db->mutex);
pRet = db->pPreUpdateArg;
db->xPreUpdateCallback = xCallback;
db->pPreUpdateArg = pArg;
sqlite3_mutex_leave(db->mutex);
return pRet;
}
#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
#ifndef SQLITE_OMIT_WAL
/*
** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
** is greater than sqlite3.pWalArg cast to an integer (the value configured by
** wal_autocheckpoint()).
*/
int sqlite3WalDefaultHook(
void *pClientData, /* Argument */
sqlite3 *db, /* Connection */
const char *zDb, /* Database */
int nFrame /* Size of WAL */
){
if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
sqlite3BeginBenignMalloc();
sqlite3_wal_checkpoint(db, zDb);
sqlite3EndBenignMalloc();
}
return SQLITE_OK;
}
#endif /* SQLITE_OMIT_WAL */
/*
** Configure an sqlite3_wal_hook() callback to automatically checkpoint
** a database after committing a transaction if there are nFrame or
** more frames in the log file. Passing zero or a negative value as the
** nFrame parameter disables automatic checkpoints entirely.
**
** The callback registered by this function replaces any existing callback
** registered using sqlite3_wal_hook(). Likewise, registering a callback
** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
** configured by this function.
*/
int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
#ifdef SQLITE_OMIT_WAL
UNUSED_PARAMETER(db);
UNUSED_PARAMETER(nFrame);
#else
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
#endif
if( nFrame>0 ){
sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
}else{
sqlite3_wal_hook(db, 0, 0);
}
#endif
return SQLITE_OK;
}
/*
** Register a callback to be invoked each time a transaction is written
** into the write-ahead-log by this database connection.
*/
void *sqlite3_wal_hook(
sqlite3 *db, /* Attach the hook to this db handle */
int(*xCallback)(void *, sqlite3*, const char*, int),
void *pArg /* First argument passed to xCallback() */
){
#ifndef SQLITE_OMIT_WAL
void *pRet;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ){
(void)SQLITE_MISUSE_BKPT;
return 0;
}
#endif
sqlite3_mutex_enter(db->mutex);
pRet = db->pWalArg;
db->xWalCallback = xCallback;
db->pWalArg = pArg;
sqlite3_mutex_leave(db->mutex);
return pRet;
#else
return 0;
#endif
}
/*
** Checkpoint database zDb.
*/
int sqlite3_wal_checkpoint_v2(
sqlite3 *db, /* Database handle */
const char *zDb, /* Name of attached database (or NULL) */
int eMode, /* SQLITE_CHECKPOINT_* value */
int *pnLog, /* OUT: Size of WAL log in frames */
int *pnCkpt /* OUT: Total number of frames checkpointed */
){
#ifdef SQLITE_OMIT_WAL
return SQLITE_OK;
#else
int rc; /* Return code */
int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
#endif
/* Initialize the output variables to -1 in case an error occurs. */
if( pnLog ) *pnLog = -1;
if( pnCkpt ) *pnCkpt = -1;
assert( SQLITE_CHECKPOINT_PASSIVE==0 );
assert( SQLITE_CHECKPOINT_FULL==1 );
assert( SQLITE_CHECKPOINT_RESTART==2 );
assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
/* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
** mode: */
return SQLITE_MISUSE;
}
sqlite3_mutex_enter(db->mutex);
if( zDb && zDb[0] ){
iDb = sqlite3FindDbName(db, zDb);
}
if( iDb<0 ){
rc = SQLITE_ERROR;
sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
}else{
db->busyHandler.nBusy = 0;
rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
sqlite3Error(db, rc);
}
rc = sqlite3ApiExit(db, rc);
sqlite3_mutex_leave(db->mutex);
return rc;
#endif
}
/*
** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
** to contains a zero-length string, all attached databases are
** checkpointed.
*/
int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
/* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
}
#ifndef SQLITE_OMIT_WAL
/*
** Run a checkpoint on database iDb. This is a no-op if database iDb is
** not currently open in WAL mode.
**
** If a transaction is open on the database being checkpointed, this
** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
** an error occurs while running the checkpoint, an SQLite error code is
** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
**
** The mutex on database handle db should be held by the caller. The mutex
** associated with the specific b-tree being checkpointed is taken by
** this function while the checkpoint is running.
**
** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
** checkpointed. If an error is encountered it is returned immediately -
** no attempt is made to checkpoint any remaining databases.
**
** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
*/
int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
int rc = SQLITE_OK; /* Return code */
int i; /* Used to iterate through attached dbs */
int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
assert( sqlite3_mutex_held(db->mutex) );
assert( !pnLog || *pnLog==-1 );
assert( !pnCkpt || *pnCkpt==-1 );
for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
pnLog = 0;
pnCkpt = 0;
if( rc==SQLITE_BUSY ){
bBusy = 1;
rc = SQLITE_OK;
}
}
}
return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
}
#endif /* SQLITE_OMIT_WAL */
/*
** This function returns true if main-memory should be used instead of
** a temporary file for transient pager files and statement journals.
** The value returned depends on the value of db->temp_store (runtime
** parameter) and the compile time value of SQLITE_TEMP_STORE. The
** following table describes the relationship between these two values
** and this functions return value.
**
** SQLITE_TEMP_STORE db->temp_store Location of temporary database
** ----------------- -------------- ------------------------------
** 0 any file (return 0)
** 1 1 file (return 0)
** 1 2 memory (return 1)
** 1 0 file (return 0)
** 2 1 file (return 0)
** 2 2 memory (return 1)
** 2 0 memory (return 1)
** 3 any memory (return 1)
*/
int sqlite3TempInMemory(const sqlite3 *db){
#if SQLITE_TEMP_STORE==1
return ( db->temp_store==2 );
#endif
#if SQLITE_TEMP_STORE==2
return ( db->temp_store!=1 );
#endif
#if SQLITE_TEMP_STORE==3
UNUSED_PARAMETER(db);
return 1;
#endif
#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
UNUSED_PARAMETER(db);
return 0;
#endif
}
/*
** Return UTF-8 encoded English language explanation of the most recent
** error.
*/
const char *sqlite3_errmsg(sqlite3 *db){
const char *z;
if( !db ){
return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
}
if( !sqlite3SafetyCheckSickOrOk(db) ){
return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
}
sqlite3_mutex_enter(db->mutex);
if( db->mallocFailed ){
z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
}else{
testcase( db->pErr==0 );
z = (char*)sqlite3_value_text(db->pErr);
assert( !db->mallocFailed );
if( z==0 ){
z = sqlite3ErrStr(db->errCode);
}
}
sqlite3_mutex_leave(db->mutex);
return z;
}
#ifndef SQLITE_OMIT_UTF16
/*
** Return UTF-16 encoded English language explanation of the most recent
** error.
*/
const void *sqlite3_errmsg16(sqlite3 *db){
static const u16 outOfMem[] = {
'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
};
static const u16 misuse[] = {
'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
'c', 'a', 'l', 'l', 'e', 'd', ' ',
'o', 'u', 't', ' ',
'o', 'f', ' ',
's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
};
const void *z;
if( !db ){
return (void *)outOfMem;
}
if( !sqlite3SafetyCheckSickOrOk(db) ){
return (void *)misuse;
}
sqlite3_mutex_enter(db->mutex);
if( db->mallocFailed ){
z = (void *)outOfMem;
}else{
z = sqlite3_value_text16(db->pErr);
if( z==0 ){
sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
z = sqlite3_value_text16(db->pErr);
}
/* A malloc() may have failed within the call to sqlite3_value_text16()
** above. If this is the case, then the db->mallocFailed flag needs to
** be cleared before returning. Do this directly, instead of via
** sqlite3ApiExit(), to avoid setting the database handle error message.
*/
sqlite3OomClear(db);
}
sqlite3_mutex_leave(db->mutex);
return z;
}
#endif /* SQLITE_OMIT_UTF16 */
/*
** Return the most recent error code generated by an SQLite routine. If NULL is
** passed to this function, we assume a malloc() failed during sqlite3_open().
*/
int sqlite3_errcode(sqlite3 *db){
if( db && !sqlite3SafetyCheckSickOrOk(db) ){
return SQLITE_MISUSE_BKPT;
}
if( !db || db->mallocFailed ){
return SQLITE_NOMEM_BKPT;
}
return db->errCode & db->errMask;
}
int sqlite3_extended_errcode(sqlite3 *db){
if( db && !sqlite3SafetyCheckSickOrOk(db) ){
return SQLITE_MISUSE_BKPT;
}
if( !db || db->mallocFailed ){
return SQLITE_NOMEM_BKPT;
}
return db->errCode;
}
int sqlite3_system_errno(sqlite3 *db){
return db ? db->iSysErrno : 0;
}
/*
** Return a string that describes the kind of error specified in the
** argument. For now, this simply calls the internal sqlite3ErrStr()
** function.
*/
const char *sqlite3_errstr(int rc){
return sqlite3ErrStr(rc);
}
/*
** Create a new collating function for database "db". The name is zName
** and the encoding is enc.
*/
static int createCollation(
sqlite3* db,
const char *zName,
u8 enc,
void* pCtx,
int(*xCompare)(void*,int,const void*,int,const void*),
void(*xDel)(void*)
){
CollSeq *pColl;
int enc2;
assert( sqlite3_mutex_held(db->mutex) );
/* If SQLITE_UTF16 is specified as the encoding type, transform this
** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
*/
enc2 = enc;
testcase( enc2==SQLITE_UTF16 );
testcase( enc2==SQLITE_UTF16_ALIGNED );
if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
enc2 = SQLITE_UTF16NATIVE;
}
if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
return SQLITE_MISUSE_BKPT;
}
/* Check if this call is removing or replacing an existing collation
** sequence. If so, and there are active VMs, return busy. If there
** are no active VMs, invalidate any pre-compiled statements.
*/
pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
if( pColl && pColl->xCmp ){
if( db->nVdbeActive ){
sqlite3ErrorWithMsg(db, SQLITE_BUSY,
"unable to delete/modify collation sequence due to active statements");
return SQLITE_BUSY;
}
sqlite3ExpirePreparedStatements(db);
/* If collation sequence pColl was created directly by a call to
** sqlite3_create_collation, and not generated by synthCollSeq(),
** then any copies made by synthCollSeq() need to be invalidated.
** Also, collation destructor - CollSeq.xDel() - function may need
** to be called.
*/
if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
int j;
for(j=0; j<3; j++){
CollSeq *p = &aColl[j];
if( p->enc==pColl->enc ){
if( p->xDel ){
p->xDel(p->pUser);
}
p->xCmp = 0;
}
}
}
}
pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
if( pColl==0 ) return SQLITE_NOMEM_BKPT;
pColl->xCmp = xCompare;
pColl->pUser = pCtx;
pColl->xDel = xDel;
pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
sqlite3Error(db, SQLITE_OK);
return SQLITE_OK;
}
/*
** This array defines hard upper bounds on limit values. The
** initializer must be kept in sync with the SQLITE_LIMIT_*
** #defines in sqlite3.h.
*/
static const int aHardLimit[] = {
SQLITE_MAX_LENGTH,
SQLITE_MAX_SQL_LENGTH,
SQLITE_MAX_COLUMN,
SQLITE_MAX_EXPR_DEPTH,
SQLITE_MAX_COMPOUND_SELECT,
SQLITE_MAX_VDBE_OP,
SQLITE_MAX_FUNCTION_ARG,
SQLITE_MAX_ATTACHED,
SQLITE_MAX_LIKE_PATTERN_LENGTH,
SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
SQLITE_MAX_TRIGGER_DEPTH,
SQLITE_MAX_WORKER_THREADS,
};
/*
** Make sure the hard limits are set to reasonable values
*/
#if SQLITE_MAX_LENGTH<100
# error SQLITE_MAX_LENGTH must be at least 100
#endif
#if SQLITE_MAX_SQL_LENGTH<100
# error SQLITE_MAX_SQL_LENGTH must be at least 100
#endif
#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
#endif
#if SQLITE_MAX_COMPOUND_SELECT<2
# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
#endif
#if SQLITE_MAX_VDBE_OP<40
# error SQLITE_MAX_VDBE_OP must be at least 40
#endif
#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
#endif
#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
# error SQLITE_MAX_ATTACHED must be between 0 and 125
#endif
#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
#endif
#if SQLITE_MAX_COLUMN>32767
# error SQLITE_MAX_COLUMN must not exceed 32767
#endif
#if SQLITE_MAX_TRIGGER_DEPTH<1
# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
#endif
#if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
# error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
#endif
/*
** Change the value of a limit. Report the old value.
** If an invalid limit index is supplied, report -1.
** Make no changes but still report the old value if the
** new limit is negative.
**
** A new lower limit does not shrink existing constructs.
** It merely prevents new constructs that exceed the limit
** from forming.
*/
int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
int oldLimit;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ){
(void)SQLITE_MISUSE_BKPT;
return -1;
}
#endif
/* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
** there is a hard upper bound set at compile-time by a C preprocessor
** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
** "_MAX_".)
*/
assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
SQLITE_MAX_LIKE_PATTERN_LENGTH );
assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
return -1;
}
oldLimit = db->aLimit[limitId];
if( newLimit>=0 ){ /* IMP: R-52476-28732 */
if( newLimit>aHardLimit[limitId] ){
newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
}
db->aLimit[limitId] = newLimit;
}
return oldLimit; /* IMP: R-53341-35419 */
}
/*
** This function is used to parse both URIs and non-URI filenames passed by the
** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
** URIs specified as part of ATTACH statements.
**
** The first argument to this function is the name of the VFS to use (or
** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
** query parameter. The second argument contains the URI (or non-URI filename)
** itself. When this function is called the *pFlags variable should contain
** the default flags to open the database handle with. The value stored in
** *pFlags may be updated before returning if the URI filename contains
** "cache=xxx" or "mode=xxx" query parameters.
**
** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
** the VFS that should be used to open the database file. *pzFile is set to
** point to a buffer containing the name of the file to open. It is the
** responsibility of the caller to eventually call sqlite3_free() to release
** this buffer.
**
** If an error occurs, then an SQLite error code is returned and *pzErrMsg
** may be set to point to a buffer containing an English language error
** message. It is the responsibility of the caller to eventually release
** this buffer by calling sqlite3_free().
*/
int sqlite3ParseUri(
const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
const char *zUri, /* Nul-terminated URI to parse */
unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
sqlite3_vfs **ppVfs, /* OUT: VFS to use */
char **pzFile, /* OUT: Filename component of URI */
char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
){
int rc = SQLITE_OK;
unsigned int flags = *pFlags;
const char *zVfs = zDefaultVfs;
char *zFile;
char c;
int nUri = sqlite3Strlen30(zUri);
assert( *pzErrMsg==0 );
if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
|| sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
&& nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
){
char *zOpt;
int eState; /* Parser state when parsing URI */
int iIn; /* Input character index */
int iOut = 0; /* Output character index */
u64 nByte = nUri+2; /* Bytes of space to allocate */
/* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
** method that there may be extra parameters following the file-name. */
flags |= SQLITE_OPEN_URI;
for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
zFile = sqlite3_malloc64(nByte);
if( !zFile ) return SQLITE_NOMEM_BKPT;
iIn = 5;
#ifdef SQLITE_ALLOW_URI_AUTHORITY
if( strncmp(zUri+5, "///", 3)==0 ){
iIn = 7;
/* The following condition causes URIs with five leading / characters
** like file://///host/path to be converted into UNCs like //host/path.
** The correct URI for that UNC has only two or four leading / characters
** file://host/path or file:////host/path. But 5 leading slashes is a
** common error, we are told, so we handle it as a special case. */
if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
}else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
iIn = 16;
}
#else
/* Discard the scheme and authority segments of the URI. */
if( zUri[5]=='/' && zUri[6]=='/' ){
iIn = 7;
while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
*pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
iIn-7, &zUri[7]);
rc = SQLITE_ERROR;
goto parse_uri_out;
}
}
#endif
/* Copy the filename and any query parameters into the zFile buffer.
** Decode %HH escape codes along the way.
**
** Within this loop, variable eState may be set to 0, 1 or 2, depending
** on the parsing context. As follows:
**
** 0: Parsing file-name.
** 1: Parsing name section of a name=value query parameter.
** 2: Parsing value section of a name=value query parameter.
*/
eState = 0;
while( (c = zUri[iIn])!=0 && c!='#' ){
iIn++;
if( c=='%'
&& sqlite3Isxdigit(zUri[iIn])
&& sqlite3Isxdigit(zUri[iIn+1])
){
int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
octet += sqlite3HexToInt(zUri[iIn++]);
assert( octet>=0 && octet<256 );
if( octet==0 ){
/* This branch is taken when "%00" appears within the URI. In this
** case we ignore all text in the remainder of the path, name or
** value currently being parsed. So ignore the current character
** and skip to the next "?", "=" or "&", as appropriate. */
while( (c = zUri[iIn])!=0 && c!='#'
&& (eState!=0 || c!='?')
&& (eState!=1 || (c!='=' && c!='&'))
&& (eState!=2 || c!='&')
){
iIn++;
}
continue;
}
c = octet;
}else if( eState==1 && (c=='&' || c=='=') ){
if( zFile[iOut-1]==0 ){
/* An empty option name. Ignore this option altogether. */
while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
continue;
}
if( c=='&' ){
zFile[iOut++] = '\0';
}else{
eState = 2;
}
c = 0;
}else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
c = 0;
eState = 1;
}
zFile[iOut++] = c;
}
if( eState==1 ) zFile[iOut++] = '\0';
zFile[iOut++] = '\0';
zFile[iOut++] = '\0';
/* Check if there were any options specified that should be interpreted
** here. Options that are interpreted here include "vfs" and those that
** correspond to flags that may be passed to the sqlite3_open_v2()
** method. */
zOpt = &zFile[sqlite3Strlen30(zFile)+1];
while( zOpt[0] ){
int nOpt = sqlite3Strlen30(zOpt);
char *zVal = &zOpt[nOpt+1];
int nVal = sqlite3Strlen30(zVal);
if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
zVfs = zVal;
}else{
struct OpenMode {
const char *z;
int mode;
} *aMode = 0;
char *zModeType = 0;
int mask = 0;
int limit = 0;
if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
static struct OpenMode aCacheMode[] = {
{ "shared", SQLITE_OPEN_SHAREDCACHE },
{ "private", SQLITE_OPEN_PRIVATECACHE },
{ 0, 0 }
};
mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
aMode = aCacheMode;
limit = mask;
zModeType = "cache";
}
if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
static struct OpenMode aOpenMode[] = {
{ "ro", SQLITE_OPEN_READONLY },
{ "rw", SQLITE_OPEN_READWRITE },
{ "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
{ "memory", SQLITE_OPEN_MEMORY },
{ 0, 0 }
};
mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
aMode = aOpenMode;
limit = mask & flags;
zModeType = "access";
}
if( aMode ){
int i;
int mode = 0;
for(i=0; aMode[i].z; i++){
const char *z = aMode[i].z;
if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
mode = aMode[i].mode;
break;
}
}
if( mode==0 ){
*pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
rc = SQLITE_ERROR;
goto parse_uri_out;
}
if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
*pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
zModeType, zVal);
rc = SQLITE_PERM;
goto parse_uri_out;
}
flags = (flags & ~mask) | mode;
}
}
zOpt = &zVal[nVal+1];
}
}else{
zFile = sqlite3_malloc64(nUri+2);
if( !zFile ) return SQLITE_NOMEM_BKPT;
memcpy(zFile, zUri, nUri);
zFile[nUri] = '\0';
zFile[nUri+1] = '\0';
flags &= ~SQLITE_OPEN_URI;
}
*ppVfs = sqlite3_vfs_find(zVfs);
if( *ppVfs==0 ){
*pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
rc = SQLITE_ERROR;
}
parse_uri_out:
if( rc!=SQLITE_OK ){
sqlite3_free(zFile);
zFile = 0;
}
*pFlags = flags;
*pzFile = zFile;
return rc;
}
/*
** This routine does the work of opening a database on behalf of
** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
** is UTF-8 encoded.
*/
static int openDatabase(
const char *zFilename, /* Database filename UTF-8 encoded */
sqlite3 **ppDb, /* OUT: Returned database handle */
unsigned int flags, /* Operational flags */
const char *zVfs /* Name of the VFS to use */
){
sqlite3 *db; /* Store allocated handle here */
int rc; /* Return code */
int isThreadsafe; /* True for threadsafe connections */
char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
#ifdef SQLITE_ENABLE_API_ARMOR
if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
#endif
*ppDb = 0;
#ifndef SQLITE_OMIT_AUTOINIT
rc = sqlite3_initialize();
if( rc ) return rc;
#endif
/* Only allow sensible combinations of bits in the flags argument.
** Throw an error if any non-sense combination is used. If we
** do not block illegal combinations here, it could trigger
** assert() statements in deeper layers. Sensible combinations
** are:
**
** 1: SQLITE_OPEN_READONLY
** 2: SQLITE_OPEN_READWRITE
** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
*/
assert( SQLITE_OPEN_READONLY == 0x01 );
assert( SQLITE_OPEN_READWRITE == 0x02 );
assert( SQLITE_OPEN_CREATE == 0x04 );
testcase( (1<<(flags&7))==0x02 ); /* READONLY */
testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
if( ((1<<(flags&7)) & 0x46)==0 ){
return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
}
if( sqlite3GlobalConfig.bCoreMutex==0 ){
isThreadsafe = 0;
}else if( flags & SQLITE_OPEN_NOMUTEX ){
isThreadsafe = 0;
}else if( flags & SQLITE_OPEN_FULLMUTEX ){
isThreadsafe = 1;
}else{
isThreadsafe = sqlite3GlobalConfig.bFullMutex;
}
if( flags & SQLITE_OPEN_PRIVATECACHE ){
flags &= ~SQLITE_OPEN_SHAREDCACHE;
}else if( sqlite3GlobalConfig.sharedCacheEnabled ){
flags |= SQLITE_OPEN_SHAREDCACHE;
}
/* Remove harmful bits from the flags parameter
**
** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
** dealt with in the previous code block. Besides these, the only
** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
** off all other flags.
*/
flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
SQLITE_OPEN_EXCLUSIVE |
SQLITE_OPEN_MAIN_DB |
SQLITE_OPEN_TEMP_DB |
SQLITE_OPEN_TRANSIENT_DB |
SQLITE_OPEN_MAIN_JOURNAL |
SQLITE_OPEN_TEMP_JOURNAL |
SQLITE_OPEN_SUBJOURNAL |
SQLITE_OPEN_MASTER_JOURNAL |
SQLITE_OPEN_NOMUTEX |
SQLITE_OPEN_FULLMUTEX |
SQLITE_OPEN_WAL
);
/* Allocate the sqlite data structure */
db = sqlite3MallocZero( sizeof(sqlite3) );
if( db==0 ) goto opendb_out;
if( isThreadsafe ){
db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
if( db->mutex==0 ){
sqlite3_free(db);
db = 0;
goto opendb_out;
}
}
sqlite3_mutex_enter(db->mutex);
db->errMask = 0xff;
db->nDb = 2;
db->magic = SQLITE_MAGIC_BUSY;
db->aDb = db->aDbStatic;
assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
db->autoCommit = 1;
db->nextAutovac = -1;
db->szMmap = sqlite3GlobalConfig.szMmap;
db->nextPagesize = 0;
db->nMaxSorterMmap = 0x7FFFFFFF;
db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
#if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
| SQLITE_AutoIndex
#endif
#if SQLITE_DEFAULT_CKPTFULLFSYNC
| SQLITE_CkptFullFSync
#endif
#if SQLITE_DEFAULT_FILE_FORMAT<4
| SQLITE_LegacyFileFmt
#endif
#ifdef SQLITE_ENABLE_LOAD_EXTENSION
| SQLITE_LoadExtension
#endif
#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
| SQLITE_RecTriggers
#endif
#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
| SQLITE_ForeignKeys
#endif
#if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
| SQLITE_ReverseOrder
#endif
#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
| SQLITE_CellSizeCk
#endif
#if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
| SQLITE_Fts3Tokenizer
#endif
;
sqlite3HashInit(&db->aCollSeq);
#ifndef SQLITE_OMIT_VIRTUALTABLE
sqlite3HashInit(&db->aModule);
#endif
/* Add the default collation sequence BINARY. BINARY works for both UTF-8
** and UTF-16, so add a version for each to avoid any unnecessary
** conversions. The only error that can occur here is a malloc() failure.
**
** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
** functions:
*/
createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
if( db->mallocFailed ){
goto opendb_out;
}
/* EVIDENCE-OF: R-08308-17224 The default collating function for all
** strings is BINARY.
*/
db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
assert( db->pDfltColl!=0 );
/* Parse the filename/URI argument. */
db->openFlags = flags;
rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
if( rc!=SQLITE_OK ){
if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
sqlite3_free(zErrMsg);
goto opendb_out;
}
/* Open the backend database driver */
rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
flags | SQLITE_OPEN_MAIN_DB);
if( rc!=SQLITE_OK ){
if( rc==SQLITE_IOERR_NOMEM ){
rc = SQLITE_NOMEM_BKPT;
}
sqlite3Error(db, rc);
goto opendb_out;
}
sqlite3BtreeEnter(db->aDb[0].pBt);
db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
sqlite3BtreeLeave(db->aDb[0].pBt);
db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
/* The default safety_level for the main database is FULL; for the temp
** database it is OFF. This matches the pager layer defaults.
*/
db->aDb[0].zDbSName = "main";
db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
db->aDb[1].zDbSName = "temp";
db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
db->magic = SQLITE_MAGIC_OPEN;
if( db->mallocFailed ){
goto opendb_out;
}
/* Register all built-in functions, but do not attempt to read the
** database schema yet. This is delayed until the first time the database
** is accessed.
*/
sqlite3Error(db, SQLITE_OK);
sqlite3RegisterPerConnectionBuiltinFunctions(db);
rc = sqlite3_errcode(db);
#ifdef SQLITE_ENABLE_FTS5
/* Register any built-in FTS5 module before loading the automatic
** extensions. This allows automatic extensions to register FTS5
** tokenizers and auxiliary functions. */
if( !db->mallocFailed && rc==SQLITE_OK ){
rc = sqlite3Fts5Init(db);
}
#endif
/* Load automatic extensions - extensions that have been registered
** using the sqlite3_automatic_extension() API.
*/
if( rc==SQLITE_OK ){
sqlite3AutoLoadExtensions(db);
rc = sqlite3_errcode(db);
if( rc!=SQLITE_OK ){
goto opendb_out;
}
}
#ifdef SQLITE_ENABLE_FTS1
if( !db->mallocFailed ){
extern int sqlite3Fts1Init(sqlite3*);
rc = sqlite3Fts1Init(db);
}
#endif
#ifdef SQLITE_ENABLE_FTS2
if( !db->mallocFailed && rc==SQLITE_OK ){
extern int sqlite3Fts2Init(sqlite3*);
rc = sqlite3Fts2Init(db);
}
#endif
#ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
if( !db->mallocFailed && rc==SQLITE_OK ){
rc = sqlite3Fts3Init(db);
}
#endif
#ifdef SQLITE_ENABLE_ICU
if( !db->mallocFailed && rc==SQLITE_OK ){
rc = sqlite3IcuInit(db);
}
#endif
#ifdef SQLITE_ENABLE_RTREE
if( !db->mallocFailed && rc==SQLITE_OK){
rc = sqlite3RtreeInit(db);
}
#endif
#ifdef SQLITE_ENABLE_DBSTAT_VTAB
if( !db->mallocFailed && rc==SQLITE_OK){
rc = sqlite3DbstatRegister(db);
}
#endif
#ifdef SQLITE_ENABLE_JSON1
if( !db->mallocFailed && rc==SQLITE_OK){
rc = sqlite3Json1Init(db);
}
#endif
/* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
** mode. Doing nothing at all also makes NORMAL the default.
*/
#ifdef SQLITE_DEFAULT_LOCKING_MODE
db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
SQLITE_DEFAULT_LOCKING_MODE);
#endif
if( rc ) sqlite3Error(db, rc);
/* Enable the lookaside-malloc subsystem */
setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
sqlite3GlobalConfig.nLookaside);
sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
opendb_out:
if( db ){
assert( db->mutex!=0 || isThreadsafe==0
|| sqlite3GlobalConfig.bFullMutex==0 );
sqlite3_mutex_leave(db->mutex);
}
rc = sqlite3_errcode(db);
assert( db!=0 || rc==SQLITE_NOMEM );
if( rc==SQLITE_NOMEM ){
sqlite3_close(db);
db = 0;
}else if( rc!=SQLITE_OK ){
db->magic = SQLITE_MAGIC_SICK;
}
*ppDb = db;
#ifdef SQLITE_ENABLE_SQLLOG
if( sqlite3GlobalConfig.xSqllog ){
/* Opening a db handle. Fourth parameter is passed 0. */
void *pArg = sqlite3GlobalConfig.pSqllogArg;
sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
}
#endif
#if defined(SQLITE_HAS_CODEC)
if( rc==SQLITE_OK ){
const char *zHexKey = sqlite3_uri_parameter(zOpen, "hexkey");
if( zHexKey && zHexKey[0] ){
u8 iByte;
int i;
char zKey[40];
for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zHexKey[i]); i++){
iByte = (iByte<<4) + sqlite3HexToInt(zHexKey[i]);
if( (i&1)!=0 ) zKey[i/2] = iByte;
}
sqlite3_key_v2(db, 0, zKey, i/2);
}
}
#endif
sqlite3_free(zOpen);
return rc & 0xff;
}
/*
** Open a new database handle.
*/
int sqlite3_open(
const char *zFilename,
sqlite3 **ppDb
){
return openDatabase(zFilename, ppDb,
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
}
int sqlite3_open_v2(
const char *filename, /* Database filename (UTF-8) */
sqlite3 **ppDb, /* OUT: SQLite db handle */
int flags, /* Flags */
const char *zVfs /* Name of VFS module to use */
){
return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
}
#ifndef SQLITE_OMIT_UTF16
/*
** Open a new database handle.
*/
int sqlite3_open16(
const void *zFilename,
sqlite3 **ppDb
){
char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
sqlite3_value *pVal;
int rc;
#ifdef SQLITE_ENABLE_API_ARMOR
if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
#endif
*ppDb = 0;
#ifndef SQLITE_OMIT_AUTOINIT
rc = sqlite3_initialize();
if( rc ) return rc;
#endif
if( zFilename==0 ) zFilename = "\000\000";
pVal = sqlite3ValueNew(0);
sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
if( zFilename8 ){
rc = openDatabase(zFilename8, ppDb,
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
assert( *ppDb || rc==SQLITE_NOMEM );
if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
}
}else{
rc = SQLITE_NOMEM_BKPT;
}
sqlite3ValueFree(pVal);
return rc & 0xff;
}
#endif /* SQLITE_OMIT_UTF16 */
/*
** Register a new collation sequence with the database handle db.
*/
int sqlite3_create_collation(
sqlite3* db,
const char *zName,
int enc,
void* pCtx,
int(*xCompare)(void*,int,const void*,int,const void*)
){
return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
}
/*
** Register a new collation sequence with the database handle db.
*/
int sqlite3_create_collation_v2(
sqlite3* db,
const char *zName,
int enc,
void* pCtx,
int(*xCompare)(void*,int,const void*,int,const void*),
void(*xDel)(void*)
){
int rc;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
#endif
sqlite3_mutex_enter(db->mutex);
assert( !db->mallocFailed );
rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
rc = sqlite3ApiExit(db, rc);
sqlite3_mutex_leave(db->mutex);
return rc;
}
#ifndef SQLITE_OMIT_UTF16
/*
** Register a new collation sequence with the database handle db.
*/
int sqlite3_create_collation16(
sqlite3* db,
const void *zName,
int enc,
void* pCtx,
int(*xCompare)(void*,int,const void*,int,const void*)
){
int rc = SQLITE_OK;
char *zName8;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
#endif
sqlite3_mutex_enter(db->mutex);
assert( !db->mallocFailed );
zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
if( zName8 ){
rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
sqlite3DbFree(db, zName8);
}
rc = sqlite3ApiExit(db, rc);
sqlite3_mutex_leave(db->mutex);
return rc;
}
#endif /* SQLITE_OMIT_UTF16 */
/*
** Register a collation sequence factory callback with the database handle
** db. Replace any previously installed collation sequence factory.
*/
int sqlite3_collation_needed(
sqlite3 *db,
void *pCollNeededArg,
void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
){
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
#endif
sqlite3_mutex_enter(db->mutex);
db->xCollNeeded = xCollNeeded;
db->xCollNeeded16 = 0;
db->pCollNeededArg = pCollNeededArg;
sqlite3_mutex_leave(db->mutex);
return SQLITE_OK;
}
#ifndef SQLITE_OMIT_UTF16
/*
** Register a collation sequence factory callback with the database handle
** db. Replace any previously installed collation sequence factory.
*/
int sqlite3_collation_needed16(
sqlite3 *db,
void *pCollNeededArg,
void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
){
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
#endif
sqlite3_mutex_enter(db->mutex);
db->xCollNeeded = 0;
db->xCollNeeded16 = xCollNeeded16;
db->pCollNeededArg = pCollNeededArg;
sqlite3_mutex_leave(db->mutex);
return SQLITE_OK;
}
#endif /* SQLITE_OMIT_UTF16 */
#ifndef SQLITE_OMIT_DEPRECATED
/*
** This function is now an anachronism. It used to be used to recover from a
** malloc() failure, but SQLite now does this automatically.
*/
int sqlite3_global_recover(void){
return SQLITE_OK;
}
#endif
/*
** Test to see whether or not the database connection is in autocommit
** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
** by default. Autocommit is disabled by a BEGIN statement and reenabled
** by the next COMMIT or ROLLBACK.
*/
int sqlite3_get_autocommit(sqlite3 *db){
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ){
(void)SQLITE_MISUSE_BKPT;
return 0;
}
#endif
return db->autoCommit;
}
/*
** The following routines are substitutes for constants SQLITE_CORRUPT,
** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
** constants. They serve two purposes:
**
** 1. Serve as a convenient place to set a breakpoint in a debugger
** to detect when version error conditions occurs.
**
** 2. Invoke sqlite3_log() to provide the source code location where
** a low-level error is first detected.
*/
static int reportError(int iErr, int lineno, const char *zType){
sqlite3_log(iErr, "%s at line %d of [%.10s]",
zType, lineno, 20+sqlite3_sourceid());
return iErr;
}
int sqlite3CorruptError(int lineno){
testcase( sqlite3GlobalConfig.xLog!=0 );
return reportError(SQLITE_CORRUPT, lineno, "database corruption");
}
int sqlite3MisuseError(int lineno){
testcase( sqlite3GlobalConfig.xLog!=0 );
return reportError(SQLITE_MISUSE, lineno, "misuse");
}
int sqlite3CantopenError(int lineno){
testcase( sqlite3GlobalConfig.xLog!=0 );
return reportError(SQLITE_CANTOPEN, lineno, "cannot open file");
}
#ifdef SQLITE_DEBUG
int sqlite3NomemError(int lineno){
testcase( sqlite3GlobalConfig.xLog!=0 );
return reportError(SQLITE_NOMEM, lineno, "OOM");
}
int sqlite3IoerrnomemError(int lineno){
testcase( sqlite3GlobalConfig.xLog!=0 );
return reportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
}
#endif
#ifndef SQLITE_OMIT_DEPRECATED
/*
** This is a convenience routine that makes sure that all thread-specific
** data for this thread has been deallocated.
**
** SQLite no longer uses thread-specific data so this routine is now a
** no-op. It is retained for historical compatibility.
*/
void sqlite3_thread_cleanup(void){
}
#endif
/*
** Return meta information about a specific column of a database table.
** See comment in sqlite3.h (sqlite.h.in) for details.
*/
int sqlite3_table_column_metadata(
sqlite3 *db, /* Connection handle */
const char *zDbName, /* Database name or NULL */
const char *zTableName, /* Table name */
const char *zColumnName, /* Column name */
char const **pzDataType, /* OUTPUT: Declared data type */
char const **pzCollSeq, /* OUTPUT: Collation sequence name */
int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
int *pPrimaryKey, /* OUTPUT: True if column part of PK */
int *pAutoinc /* OUTPUT: True if column is auto-increment */
){
int rc;
char *zErrMsg = 0;
Table *pTab = 0;
Column *pCol = 0;
int iCol = 0;
char const *zDataType = 0;
char const *zCollSeq = 0;
int notnull = 0;
int primarykey = 0;
int autoinc = 0;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
return SQLITE_MISUSE_BKPT;
}
#endif
/* Ensure the database schema has been loaded */
sqlite3_mutex_enter(db->mutex);
sqlite3BtreeEnterAll(db);
rc = sqlite3Init(db, &zErrMsg);
if( SQLITE_OK!=rc ){
goto error_out;
}
/* Locate the table in question */
pTab = sqlite3FindTable(db, zTableName, zDbName);
if( !pTab || pTab->pSelect ){
pTab = 0;
goto error_out;
}
/* Find the column for which info is requested */
if( zColumnName==0 ){
/* Query for existance of table only */
}else{
for(iCol=0; iCol<pTab->nCol; iCol++){
pCol = &pTab->aCol[iCol];
if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
break;
}
}
if( iCol==pTab->nCol ){
if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
iCol = pTab->iPKey;
pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
}else{
pTab = 0;
goto error_out;
}
}
}
/* The following block stores the meta information that will be returned
** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
** and autoinc. At this point there are two possibilities:
**
** 1. The specified column name was rowid", "oid" or "_rowid_"
** and there is no explicitly declared IPK column.
**
** 2. The table is not a view and the column name identified an
** explicitly declared column. Copy meta information from *pCol.
*/
if( pCol ){
zDataType = sqlite3ColumnType(pCol,0);
zCollSeq = pCol->zColl;
notnull = pCol->notNull!=0;
primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
}else{
zDataType = "INTEGER";
primarykey = 1;
}
if( !zCollSeq ){
zCollSeq = sqlite3StrBINARY;
}
error_out:
sqlite3BtreeLeaveAll(db);
/* Whether the function call succeeded or failed, set the output parameters
** to whatever their local counterparts contain. If an error did occur,
** this has the effect of zeroing all output parameters.
*/
if( pzDataType ) *pzDataType = zDataType;
if( pzCollSeq ) *pzCollSeq = zCollSeq;
if( pNotNull ) *pNotNull = notnull;
if( pPrimaryKey ) *pPrimaryKey = primarykey;
if( pAutoinc ) *pAutoinc = autoinc;
if( SQLITE_OK==rc && !pTab ){
sqlite3DbFree(db, zErrMsg);
zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
zColumnName);
rc = SQLITE_ERROR;
}
sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
sqlite3DbFree(db, zErrMsg);
rc = sqlite3ApiExit(db, rc);
sqlite3_mutex_leave(db->mutex);
return rc;
}
/*
** Sleep for a little while. Return the amount of time slept.
*/
int sqlite3_sleep(int ms){
sqlite3_vfs *pVfs;
int rc;
pVfs = sqlite3_vfs_find(0);
if( pVfs==0 ) return 0;
/* This function works in milliseconds, but the underlying OsSleep()
** API uses microseconds. Hence the 1000's.
*/
rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
return rc;
}
/*
** Enable or disable the extended result codes.
*/
int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
#endif
sqlite3_mutex_enter(db->mutex);
db->errMask = onoff ? 0xffffffff : 0xff;
sqlite3_mutex_leave(db->mutex);
return SQLITE_OK;
}
/*
** Invoke the xFileControl method on a particular database.
*/
int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
int rc = SQLITE_ERROR;
Btree *pBtree;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
#endif
sqlite3_mutex_enter(db->mutex);
pBtree = sqlite3DbNameToBtree(db, zDbName);
if( pBtree ){
Pager *pPager;
sqlite3_file *fd;
sqlite3BtreeEnter(pBtree);
pPager = sqlite3BtreePager(pBtree);
assert( pPager!=0 );
fd = sqlite3PagerFile(pPager);
assert( fd!=0 );
if( op==SQLITE_FCNTL_FILE_POINTER ){
*(sqlite3_file**)pArg = fd;
rc = SQLITE_OK;
}else if( op==SQLITE_FCNTL_VFS_POINTER ){
*(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
rc = SQLITE_OK;
}else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
*(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
rc = SQLITE_OK;
}else if( fd->pMethods ){
rc = sqlite3OsFileControl(fd, op, pArg);
}else{
rc = SQLITE_NOTFOUND;
}
sqlite3BtreeLeave(pBtree);
}
sqlite3_mutex_leave(db->mutex);
return rc;
}
/*
** Interface to the testing logic.
*/
int sqlite3_test_control(int op, ...){
int rc = 0;
#ifdef SQLITE_OMIT_BUILTIN_TEST
UNUSED_PARAMETER(op);
#else
va_list ap;
va_start(ap, op);
switch( op ){
/*
** Save the current state of the PRNG.
*/
case SQLITE_TESTCTRL_PRNG_SAVE: {
sqlite3PrngSaveState();
break;
}
/*
** Restore the state of the PRNG to the last state saved using
** PRNG_SAVE. If PRNG_SAVE has never before been called, then
** this verb acts like PRNG_RESET.
*/
case SQLITE_TESTCTRL_PRNG_RESTORE: {
sqlite3PrngRestoreState();
break;
}
/*
** Reset the PRNG back to its uninitialized state. The next call
** to sqlite3_randomness() will reseed the PRNG using a single call
** to the xRandomness method of the default VFS.
*/
case SQLITE_TESTCTRL_PRNG_RESET: {
sqlite3_randomness(0,0);
break;
}
/*
** sqlite3_test_control(BITVEC_TEST, size, program)
**
** Run a test against a Bitvec object of size. The program argument
** is an array of integers that defines the test. Return -1 on a
** memory allocation error, 0 on success, or non-zero for an error.
** See the sqlite3BitvecBuiltinTest() for additional information.
*/
case SQLITE_TESTCTRL_BITVEC_TEST: {
int sz = va_arg(ap, int);
int *aProg = va_arg(ap, int*);
rc = sqlite3BitvecBuiltinTest(sz, aProg);
break;
}
/*
** sqlite3_test_control(FAULT_INSTALL, xCallback)
**
** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
** if xCallback is not NULL.
**
** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
** is called immediately after installing the new callback and the return
** value from sqlite3FaultSim(0) becomes the return from
** sqlite3_test_control().
*/
case SQLITE_TESTCTRL_FAULT_INSTALL: {
/* MSVC is picky about pulling func ptrs from va lists.
** http://support.microsoft.com/kb/47961
** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
*/
typedef int(*TESTCALLBACKFUNC_t)(int);
sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
rc = sqlite3FaultSim(0);
break;
}
/*
** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
**
** Register hooks to call to indicate which malloc() failures
** are benign.
*/
case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
typedef void (*void_function)(void);
void_function xBenignBegin;
void_function xBenignEnd;
xBenignBegin = va_arg(ap, void_function);
xBenignEnd = va_arg(ap, void_function);
sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
break;
}
/*
** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
**
** Set the PENDING byte to the value in the argument, if X>0.
** Make no changes if X==0. Return the value of the pending byte
** as it existing before this routine was called.
**
** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
** an incompatible database file format. Changing the PENDING byte
** while any database connection is open results in undefined and
** deleterious behavior.
*/
case SQLITE_TESTCTRL_PENDING_BYTE: {
rc = PENDING_BYTE;
#ifndef SQLITE_OMIT_WSD
{
unsigned int newVal = va_arg(ap, unsigned int);
if( newVal ) sqlite3PendingByte = newVal;
}
#endif
break;
}
/*
** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
**
** This action provides a run-time test to see whether or not
** assert() was enabled at compile-time. If X is true and assert()
** is enabled, then the return value is true. If X is true and
** assert() is disabled, then the return value is zero. If X is
** false and assert() is enabled, then the assertion fires and the
** process aborts. If X is false and assert() is disabled, then the
** return value is zero.
*/
case SQLITE_TESTCTRL_ASSERT: {
volatile int x = 0;
assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
rc = x;
break;
}
/*
** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
**
** This action provides a run-time test to see how the ALWAYS and
** NEVER macros were defined at compile-time.
**
** The return value is ALWAYS(X).
**
** The recommended test is X==2. If the return value is 2, that means
** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
** default setting. If the return value is 1, then ALWAYS() is either
** hard-coded to true or else it asserts if its argument is false.
** The first behavior (hard-coded to true) is the case if
** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
** behavior (assert if the argument to ALWAYS() is false) is the case if
** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
**
** The run-time test procedure might look something like this:
**
** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
** // ALWAYS() and NEVER() are no-op pass-through macros
** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
** }else{
** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
** }
*/
case SQLITE_TESTCTRL_ALWAYS: {
int x = va_arg(ap,int);
rc = ALWAYS(x);
break;
}
/*
** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
**
** The integer returned reveals the byte-order of the computer on which
** SQLite is running:
**
** 1 big-endian, determined at run-time
** 10 little-endian, determined at run-time
** 432101 big-endian, determined at compile-time
** 123410 little-endian, determined at compile-time
*/
case SQLITE_TESTCTRL_BYTEORDER: {
rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
break;
}
/* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
**
** Set the nReserve size to N for the main database on the database
** connection db.
*/
case SQLITE_TESTCTRL_RESERVE: {
sqlite3 *db = va_arg(ap, sqlite3*);
int x = va_arg(ap,int);
sqlite3_mutex_enter(db->mutex);
sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
sqlite3_mutex_leave(db->mutex);
break;
}
/* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
**
** Enable or disable various optimizations for testing purposes. The
** argument N is a bitmask of optimizations to be disabled. For normal
** operation N should be 0. The idea is that a test program (like the
** SQL Logic Test or SLT test module) can run the same SQL multiple times
** with various optimizations disabled to verify that the same answer
** is obtained in every case.
*/
case SQLITE_TESTCTRL_OPTIMIZATIONS: {
sqlite3 *db = va_arg(ap, sqlite3*);
db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
break;
}
#ifdef SQLITE_N_KEYWORD
/* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
**
** If zWord is a keyword recognized by the parser, then return the
** number of keywords. Or if zWord is not a keyword, return 0.
**
** This test feature is only available in the amalgamation since
** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
** is built using separate source files.
*/
case SQLITE_TESTCTRL_ISKEYWORD: {
const char *zWord = va_arg(ap, const char*);
int n = sqlite3Strlen30(zWord);
rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
break;
}
#endif
/* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
**
** Pass pFree into sqlite3ScratchFree().
** If sz>0 then allocate a scratch buffer into pNew.
*/
case SQLITE_TESTCTRL_SCRATCHMALLOC: {
void *pFree, **ppNew;
int sz;
sz = va_arg(ap, int);
ppNew = va_arg(ap, void**);
pFree = va_arg(ap, void*);
if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
sqlite3ScratchFree(pFree);
break;
}
/* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
**
** If parameter onoff is non-zero, configure the wrappers so that all
** subsequent calls to localtime() and variants fail. If onoff is zero,
** undo this setting.
*/
case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
break;
}
/* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
**
** Set or clear a flag that indicates that the database file is always well-
** formed and never corrupt. This flag is clear by default, indicating that
** database files might have arbitrary corruption. Setting the flag during
** testing causes certain assert() statements in the code to be activated
** that demonstrat invariants on well-formed database files.
*/
case SQLITE_TESTCTRL_NEVER_CORRUPT: {
sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
break;
}
/* Set the threshold at which OP_Once counters reset back to zero.
** By default this is 0x7ffffffe (over 2 billion), but that value is
** too big to test in a reasonable amount of time, so this control is
** provided to set a small and easily reachable reset value.
*/
case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
break;
}
/* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
**
** Set the VDBE coverage callback function to xCallback with context
** pointer ptr.
*/
case SQLITE_TESTCTRL_VDBE_COVERAGE: {
#ifdef SQLITE_VDBE_COVERAGE
typedef void (*branch_callback)(void*,int,u8,u8);
sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
#endif
break;
}
/* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
case SQLITE_TESTCTRL_SORTER_MMAP: {
sqlite3 *db = va_arg(ap, sqlite3*);
db->nMaxSorterMmap = va_arg(ap, int);
break;
}
/* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
**
** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
** not.
*/
case SQLITE_TESTCTRL_ISINIT: {
if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
break;
}
/* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
**
** This test control is used to create imposter tables. "db" is a pointer
** to the database connection. dbName is the database name (ex: "main" or
** "temp") which will receive the imposter. "onOff" turns imposter mode on
** or off. "tnum" is the root page of the b-tree to which the imposter
** table should connect.
**
** Enable imposter mode only when the schema has already been parsed. Then
** run a single CREATE TABLE statement to construct the imposter table in
** the parsed schema. Then turn imposter mode back off again.
**
** If onOff==0 and tnum>0 then reset the schema for all databases, causing
** the schema to be reparsed the next time it is needed. This has the
** effect of erasing all imposter tables.
*/
case SQLITE_TESTCTRL_IMPOSTER: {
sqlite3 *db = va_arg(ap, sqlite3*);
sqlite3_mutex_enter(db->mutex);
db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
db->init.busy = db->init.imposterTable = va_arg(ap,int);
db->init.newTnum = va_arg(ap,int);
if( db->init.busy==0 && db->init.newTnum>0 ){
sqlite3ResetAllSchemasOfConnection(db);
}
sqlite3_mutex_leave(db->mutex);
break;
}
}
va_end(ap);
#endif /* SQLITE_OMIT_BUILTIN_TEST */
return rc;
}
/*
** This is a utility routine, useful to VFS implementations, that checks
** to see if a database file was a URI that contained a specific query
** parameter, and if so obtains the value of the query parameter.
**
** The zFilename argument is the filename pointer passed into the xOpen()
** method of a VFS implementation. The zParam argument is the name of the
** query parameter we seek. This routine returns the value of the zParam
** parameter if it exists. If the parameter does not exist, this routine
** returns a NULL pointer.
*/
const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
if( zFilename==0 || zParam==0 ) return 0;
zFilename += sqlite3Strlen30(zFilename) + 1;
while( zFilename[0] ){
int x = strcmp(zFilename, zParam);
zFilename += sqlite3Strlen30(zFilename) + 1;
if( x==0 ) return zFilename;
zFilename += sqlite3Strlen30(zFilename) + 1;
}
return 0;
}
/*
** Return a boolean value for a query parameter.
*/
int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
const char *z = sqlite3_uri_parameter(zFilename, zParam);
bDflt = bDflt!=0;
return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
}
/*
** Return a 64-bit integer value for a query parameter.
*/
sqlite3_int64 sqlite3_uri_int64(
const char *zFilename, /* Filename as passed to xOpen */
const char *zParam, /* URI parameter sought */
sqlite3_int64 bDflt /* return if parameter is missing */
){
const char *z = sqlite3_uri_parameter(zFilename, zParam);
sqlite3_int64 v;
if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
bDflt = v;
}
return bDflt;
}
/*
** Return the Btree pointer identified by zDbName. Return NULL if not found.
*/
Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
int i;
for(i=0; i<db->nDb; i++){
if( db->aDb[i].pBt
&& (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zDbSName)==0)
){
return db->aDb[i].pBt;
}
}
return 0;
}
/*
** Return the filename of the database associated with a database
** connection.
*/
const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
Btree *pBt;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ){
(void)SQLITE_MISUSE_BKPT;
return 0;
}
#endif
pBt = sqlite3DbNameToBtree(db, zDbName);
return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
}
/*
** Return 1 if database is read-only or 0 if read/write. Return -1 if
** no such database exists.
*/
int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
Btree *pBt;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ){
(void)SQLITE_MISUSE_BKPT;
return -1;
}
#endif
pBt = sqlite3DbNameToBtree(db, zDbName);
return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
}
#ifdef SQLITE_ENABLE_SNAPSHOT
/*
** Obtain a snapshot handle for the snapshot of database zDb currently
** being read by handle db.
*/
int sqlite3_snapshot_get(
sqlite3 *db,
const char *zDb,
sqlite3_snapshot **ppSnapshot
){
int rc = SQLITE_ERROR;
#ifndef SQLITE_OMIT_WAL
int iDb;
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ){
return SQLITE_MISUSE_BKPT;
}
#endif
sqlite3_mutex_enter(db->mutex);
iDb = sqlite3FindDbName(db, zDb);
if( iDb==0 || iDb>1 ){
Btree *pBt = db->aDb[iDb].pBt;
if( 0==sqlite3BtreeIsInTrans(pBt) ){
rc = sqlite3BtreeBeginTrans(pBt, 0);
if( rc==SQLITE_OK ){
rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
}
}
}
sqlite3_mutex_leave(db->mutex);
#endif /* SQLITE_OMIT_WAL */
return rc;
}
/*
** Open a read-transaction on the snapshot idendified by pSnapshot.
*/
int sqlite3_snapshot_open(
sqlite3 *db,
const char *zDb,
sqlite3_snapshot *pSnapshot
){
int rc = SQLITE_ERROR;
#ifndef SQLITE_OMIT_WAL
#ifdef SQLITE_ENABLE_API_ARMOR
if( !sqlite3SafetyCheckOk(db) ){
return SQLITE_MISUSE_BKPT;
}
#endif
sqlite3_mutex_enter(db->mutex);
if( db->autoCommit==0 ){
int iDb;
iDb = sqlite3FindDbName(db, zDb);
if( iDb==0 || iDb>1 ){
Btree *pBt = db->aDb[iDb].pBt;
if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
if( rc==SQLITE_OK ){
rc = sqlite3BtreeBeginTrans(pBt, 0);
sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
}
}
}
}
sqlite3_mutex_leave(db->mutex);
#endif /* SQLITE_OMIT_WAL */
return rc;
}
/*
** Free a snapshot handle obtained from sqlite3_snapshot_get().
*/
void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
sqlite3_free(pSnapshot);
}
#endif /* SQLITE_ENABLE_SNAPSHOT */
| gpl-3.0 |
Bugex/SkyFireEMU | src/server/game/Battlegrounds/ArenaTeam.cpp | 6 | 32105 | /*
* Copyright (C) 2011-2012 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2012 MaNGOS <http://getmangos.com/>
*
* 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 3 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 "ObjectMgr.h"
#include "WorldPacket.h"
#include "ArenaTeam.h"
#include "World.h"
#include "Group.h"
#include "ArenaTeamMgr.h"
ArenaTeam::ArenaTeam()
{
TeamId = 0;
Type = 0;
TeamName = "";
CaptainGuid = 0;
BackgroundColor = 0;
EmblemStyle = 0;
EmblemColor = 0;
BorderStyle = 0;
BorderColor = 0;
Stats.WeekGames = 0;
Stats.SeasonGames = 0;
Stats.Rank = 0;
Stats.Rating = sWorld->getIntConfig(CONFIG_ARENA_START_RATING);
Stats.WeekWins = 0;
Stats.SeasonWins = 0;
}
ArenaTeam::~ArenaTeam() {}
bool ArenaTeam::Create(uint64 captainGuid, uint8 type, std::string teamName, uint32 backgroundColor, uint8 emblemStyle, uint32 emblemColor, uint8 borderStyle, uint32 borderColor)
{
// Check if captain is present
if (!ObjectAccessor::FindPlayer(captainGuid))
return false;
// Check if arena team name is already taken
if (sArenaTeamMgr->GetArenaTeamByName(TeamName))
return false;
// Generate new arena team id
TeamId = sArenaTeamMgr->GenerateArenaTeamId();
// Assign member variables
CaptainGuid = captainGuid;
Type = type;
TeamName = teamName;
BackgroundColor = backgroundColor;
EmblemStyle = emblemStyle;
EmblemColor = emblemColor;
BorderStyle = borderStyle;
BorderColor = borderColor;
uint32 captainLowGuid = GUID_LOPART(captainGuid);
// Save arena team to db
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_ADD_ARENA_TEAM);
stmt->setUInt32(0, TeamId);
stmt->setString(1, TeamName);
stmt->setUInt32(2, captainLowGuid);
stmt->setUInt8(3, Type);
stmt->setUInt16(4, Stats.Rating);
stmt->setUInt32(5, BackgroundColor);
stmt->setUInt8(6, EmblemStyle);
stmt->setUInt32(7, EmblemColor);
stmt->setUInt8(8, BorderStyle);
stmt->setUInt32(9, BorderColor);
CharacterDatabase.Execute(stmt);
// Add captain as member
AddMember(CaptainGuid);
sLog->outArena("New ArenaTeam created [Id: %u] [Type: %u] [Captain low GUID: %u]", GetId(), GetType(), captainLowGuid);
return true;
}
bool ArenaTeam::AddMember(uint64 playerGuid)
{
std::string playerName;
uint8 playerClass;
// Check if arena team is full (Can't have more than type * 2 players)
if (GetMembersSize() >= GetType() * 2)
return false;
// Get player name and class either from db or ObjectMgr
Player* player = ObjectAccessor::FindPlayer(playerGuid);
if (player)
{
playerClass = player->getClass();
playerName = player->GetName();
}
else
{
// 0 1
// SELECT name, class FROM characters WHERE guid = ?
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_LOAD_PLAYER_NAME_CLASS);
stmt->setUInt32(0, GUID_LOPART(playerGuid));
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (!result)
return false;
playerName = (*result)[0].GetString();
playerClass = (*result)[1].GetUInt8();
}
// Check if player is already in a similar arena team
if ((player && player->GetArenaTeamId(GetSlot())) || Player::GetArenaTeamIdFromDB(playerGuid, GetType()) != 0)
{
sLog->outError("Arena: Player %s (guid: %u) already has an arena team of type %u", playerName.c_str(), GUID_LOPART(playerGuid), GetType());
return false;
}
// Set player's personal rating
uint32 personalRating = 0;
if (sWorld->getIntConfig(CONFIG_ARENA_START_PERSONAL_RATING) >= 0)
personalRating = sWorld->getIntConfig(CONFIG_ARENA_START_PERSONAL_RATING);
else if (GetRating() >= 1000)
personalRating = 1000;
// Try to get player's match maker rating from db and fall back to config setting if not found
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_LOAD_MATCH_MAKER_RATING);
stmt->setUInt32(0, GUID_LOPART(playerGuid));
stmt->setUInt8(1, GetSlot());
PreparedQueryResult result = CharacterDatabase.Query(stmt);
uint32 matchMakerRating;
if (result)
matchMakerRating = (*result)[0].GetUInt32();
else
matchMakerRating = sWorld->getIntConfig(CONFIG_ARENA_START_MATCHMAKER_RATING);
// Remove all player signatures from other petitions
// This will prevent player from joining too many arena teams and corrupt arena team data integrity
Player::RemovePetitionsAndSigns(playerGuid, GetType());
// Feed data to the struct
ArenaTeamMember newmember;
newmember.Name = playerName;
newmember.Guid = playerGuid;
newmember.Class = playerClass;
newmember.SeasonGames = 0;
newmember.WeekGames = 0;
newmember.SeasonWins = 0;
newmember.WeekWins = 0;
newmember.PersonalRating = personalRating;
newmember.MatchMakerRating = matchMakerRating;
Members.push_back(newmember);
// Save player's arena team membership to db
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SET_ARENA_TEAM_MEMBER);
stmt->setUInt32(0, TeamId);
stmt->setUInt32(1, GUID_LOPART(playerGuid));
CharacterDatabase.Execute(stmt);
// Inform player if online
if (player)
{
player->SetInArenaTeam(TeamId, GetSlot(), GetType());
player->SetArenaTeamIdInvited(0);
// Hide promote/remove buttons
if (CaptainGuid != playerGuid)
player->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_MEMBER, 1);
}
sLog->outArena("Player: %s [GUID: %u] joined arena team type: %u [Id: %u].", playerName.c_str(), GUID_LOPART(playerGuid), GetType(), GetId());
return true;
}
bool ArenaTeam::LoadArenaTeamFromDB(QueryResult result)
{
if (!result)
return false;
Field* fields = result->Fetch();
TeamId = fields[0].GetUInt32();
TeamName = fields[1].GetString();
CaptainGuid = MAKE_NEW_GUID(fields[2].GetUInt32(), 0, HIGHGUID_PLAYER);
Type = fields[3].GetUInt8();
BackgroundColor = fields[4].GetUInt32();
EmblemStyle = fields[5].GetUInt8();
EmblemColor = fields[6].GetUInt32();
BorderStyle = fields[7].GetUInt8();
BorderColor = fields[8].GetUInt32();
Stats.Rating = fields[9].GetUInt16();
Stats.WeekGames = fields[10].GetUInt16();
Stats.WeekWins = fields[11].GetUInt16();
Stats.SeasonGames = fields[12].GetUInt16();
Stats.SeasonWins = fields[13].GetUInt16();
Stats.Rank = fields[14].GetUInt32();
return true;
}
bool ArenaTeam::LoadMembersFromDB(QueryResult result)
{
if (!result)
return false;
bool captainPresentInTeam = false;
do
{
Field* fields = result->Fetch();
// Prevent crash if db records are broken when all members in result are already processed and current team doesn't have any members
if (!fields)
break;
uint32 arenaTeamId = fields[0].GetUInt32();
// We loaded all members for this arena_team already, break cycle
if (arenaTeamId > TeamId)
break;
ArenaTeamMember newMember;
newMember.Guid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_PLAYER);
newMember.WeekGames = fields[2].GetUInt16();
newMember.WeekWins = fields[3].GetUInt16();
newMember.SeasonGames = fields[4].GetUInt16();
newMember.SeasonWins = fields[5].GetUInt16();
newMember.Name = fields[6].GetString();
newMember.Class = fields[7].GetUInt8();
newMember.PersonalRating = fields[8].GetUInt16();
newMember.MatchMakerRating = fields[9].GetUInt16() > 0 ? fields[9].GetUInt16() : 1500;
// Delete member if character information is missing
if (newMember.Name.empty())
{
sLog->outErrorDb("ArenaTeam %u has member with empty name - probably player %u doesn't exist, deleting him from memberlist!", arenaTeamId, GUID_LOPART(newMember.Guid));
this->DelMember(newMember.Guid, true);
continue;
}
// Check if team team has a valid captain
if (newMember.Guid == GetCaptain())
captainPresentInTeam = true;
// Put the player in the team
Members.push_back(newMember);
}
while (result->NextRow());
if (Empty() || !captainPresentInTeam)
{
// Arena team is empty or captain is not in team, delete from db
sLog->outErrorDb("ArenaTeam %u does not have any members or its captain is not in team, disbanding it...", TeamId);
return false;
}
return true;
}
void ArenaTeam::SetCaptain(uint64 guid)
{
// Disable remove/promote buttons
Player* oldCaptain = ObjectAccessor::FindPlayer(GetCaptain());
if (oldCaptain)
oldCaptain->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_MEMBER, 1);
// Set new captain
CaptainGuid = guid;
// Update database
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPDATE_ARENA_TEAM_CAPTAIN);
stmt->setUInt32(0, GUID_LOPART(guid));
stmt->setUInt32(1, GetId());
CharacterDatabase.Execute(stmt);
// Enable remove/promote buttons
Player* newCaptain = ObjectAccessor::FindPlayer(guid);
if (newCaptain)
{
newCaptain->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_MEMBER, 0);
char const* oldCaptainName = oldCaptain ? oldCaptain->GetName() : "";
uint32 oldCaptainLowGuid = oldCaptain ? oldCaptain->GetGUIDLow() : 0;
sLog->outArena("Player: %s [GUID: %u] promoted player: %s [GUID: %u] to leader of arena team [Id: %u] [Type: %u].",
oldCaptainName, oldCaptainLowGuid, newCaptain->GetName(), newCaptain->GetGUIDLow(), GetId(), GetType());
}
}
void ArenaTeam::DelMember(uint64 guid, bool cleanDb)
{
// Remove member from team
for (MemberList::iterator itr = Members.begin(); itr != Members.end(); ++itr)
if (itr->Guid == guid)
{
Members.erase(itr);
break;
}
// Inform player and remove arena team info from player data
if (Player* player = ObjectAccessor::FindPlayer(guid))
{
player->GetSession()->SendArenaTeamCommandResult(ERR_ARENA_TEAM_QUIT_S, GetName(), "", 0);
// delete all info regarding this team
for (uint32 i = 0; i < ARENA_TEAM_END; ++i)
player->SetArenaTeamInfoField(GetSlot(), ArenaTeamInfoType(i), 0);
sLog->outArena("Player: %s [GUID: %u] left arena team type: %u [Id: %u].", player->GetName(), player->GetGUIDLow(), GetType(), GetId());
}
// Only used for single member deletion, for arena team disband we use a single query for more efficiency
if (cleanDb)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ARENA_TEAM_MEMBER);
stmt->setUInt32(0, GetId());
stmt->setUInt32(1, GUID_LOPART(guid));
CharacterDatabase.Execute(stmt);
}
}
void ArenaTeam::Disband(WorldSession* session)
{
// Remove all members from arena team
while (!Members.empty())
DelMember(Members.front().Guid, false);
// Broadcast update
if (session)
{
BroadcastEvent(ERR_ARENA_TEAM_DISBANDED_S, 0, 2, session->GetPlayerName(), GetName(), "");
if (Player* player = session->GetPlayer())
sLog->outArena("Player: %s [GUID: %u] disbanded arena team type: %u [Id: %u].", player->GetName(), player->GetGUIDLow(), GetType(), GetId());
}
// Update database
SQLTransaction trans = CharacterDatabase.BeginTransaction();
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ARENA_TEAM);
stmt->setUInt32(0, TeamId);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ARENA_TEAM_MEMBERS);
stmt->setUInt32(0, TeamId);
trans->Append(stmt);
CharacterDatabase.CommitTransaction(trans);
// Remove arena team from ObjectMgr
sArenaTeamMgr->RemoveArenaTeam(TeamId);
}
void ArenaTeam::Roster(WorldSession* session)
{
Player* player = NULL;
uint8 unk308 = 0;
WorldPacket data(SMSG_ARENA_TEAM_ROSTER, 100);
data << uint32(GetId()); // team id
data << uint8(unk308); // 308 unknown value but affect packet structure
data << uint32(GetMembersSize()); // members count
data << uint32(GetType()); // arena team type?
for (MemberList::const_iterator itr = Members.begin(); itr != Members.end(); ++itr)
{
player = ObjectAccessor::FindPlayer(itr->Guid);
data << uint64(itr->Guid); // guid
data << uint8((player ? 1 : 0)); // online flag
data << itr->Name; // member name
data << uint32((itr->Guid == GetCaptain() ? 0 : 1));// captain flag 0 captain 1 member
data << uint8((player ? player->getLevel() : 0)); // unknown, level?
data << uint8(itr->Class); // class
data << uint32(itr->WeekGames); // played this week
data << uint32(itr->WeekWins); // wins this week
data << uint32(itr->SeasonGames); // played this season
data << uint32(itr->SeasonWins); // wins this season
data << uint32(itr->PersonalRating); // personal rating
if (unk308)
{
data << float(0.0f); // 308 unk
data << float(0.0f); // 308 unk
}
}
session->SendPacket(&data);
sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_ARENA_TEAM_ROSTER");
}
void ArenaTeam::Query(WorldSession* session)
{
WorldPacket data(SMSG_ARENA_TEAM_QUERY_RESPONSE, 4*7+GetName().size()+1);
data << uint32(GetId()); // team id
data << GetName(); // team name
data << uint32(GetType()); // arena team type (2=2x2, 3=3x3 or 5=5x5)
data << uint32(BackgroundColor); // background color
data << uint32(EmblemStyle); // emblem style
data << uint32(EmblemColor); // emblem color
data << uint32(BorderStyle); // border style
data << uint32(BorderColor); // border color
session->SendPacket(&data);
sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_ARENA_TEAM_QUERY_RESPONSE");
}
void ArenaTeam::SendStats(WorldSession* session)
{
WorldPacket data(SMSG_ARENA_TEAM_STATS, 4*7);
data << uint32(GetId()); // team id
data << uint32(Stats.Rating); // rating
data << uint32(Stats.WeekGames); // games this week
data << uint32(Stats.WeekWins); // wins this week
data << uint32(Stats.SeasonGames); // played this season
data << uint32(Stats.SeasonWins); // wins this season
data << uint32(Stats.Rank); // rank
session->SendPacket(&data);
}
void ArenaTeam::NotifyStatsChanged()
{
// This is called after a rated match ended
// Updates arena team stats for every member of the team (not only the ones who participated!)
for (MemberList::const_iterator itr = Members.begin(); itr != Members.end(); ++itr)
if (Player* player = ObjectAccessor::FindPlayer(itr->Guid))
SendStats(player->GetSession());
}
void ArenaTeam::Inspect(WorldSession* session, uint64 guid)
{
ArenaTeamMember* member = GetMember(guid);
if (!member)
return;
WorldPacket data(MSG_INSPECT_ARENA_TEAMS, 8+1+4*6);
data << uint64(guid); // player guid
data << uint8(GetSlot()); // slot (0...2)
data << uint32(GetId()); // arena team id
data << uint32(Stats.Rating); // rating
data << uint32(Stats.SeasonGames); // season played
data << uint32(Stats.SeasonWins); // season wins
data << uint32(member->SeasonGames); // played (count of all games, that the inspected member participated...)
data << uint32(member->PersonalRating); // personal rating
session->SendPacket(&data);
}
void ArenaTeamMember::ModifyPersonalRating(Player* player, int32 mod, uint32 type)
{
if (int32(PersonalRating) + mod < 0)
PersonalRating = 0;
else
PersonalRating += mod;
if (player)
{
player->SetArenaTeamInfoField(ArenaTeam::GetSlotByType(type), ARENA_TEAM_PERSONAL_RATING, PersonalRating);
player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING, PersonalRating, type);
}
}
void ArenaTeamMember::ModifyMatchmakerRating(int32 mod, uint32 /*slot*/)
{
if (int32(MatchMakerRating) + mod < 0)
MatchMakerRating = 0;
else
MatchMakerRating += mod;
}
void ArenaTeam::BroadcastPacket(WorldPacket* packet)
{
for (MemberList::const_iterator itr = Members.begin(); itr != Members.end(); ++itr)
if (Player* player = ObjectAccessor::FindPlayer(itr->Guid))
player->GetSession()->SendPacket(packet);
}
void ArenaTeam::BroadcastEvent(ArenaTeamEvents event, uint64 guid, uint8 strCount, std::string str1, std::string str2, std::string str3)
{
WorldPacket data(SMSG_ARENA_TEAM_EVENT, 1+1+1);
data << uint8(event);
data << uint8(strCount);
switch (strCount)
{
case 0:
break;
case 1:
data << str1;
break;
case 2:
data << str1 << str2;
break;
case 3:
data << str1 << str2 << str3;
break;
default:
sLog->outError("Unhandled strCount %u in ArenaTeam::BroadcastEvent", strCount);
return;
}
if (guid)
data << uint64(guid);
BroadcastPacket(&data);
sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_ARENA_TEAM_EVENT");
}
uint8 ArenaTeam::GetSlotByType(uint32 type)
{
switch (type)
{
case ARENA_TEAM_2v2: return 0;
case ARENA_TEAM_3v3: return 1;
case ARENA_TEAM_5v5: return 2;
default:
break;
}
sLog->outError("FATAL: Unknown arena team type %u for some arena team", type);
return 0xFF;
}
bool ArenaTeam::IsMember(uint64 guid) const
{
for (MemberList::const_iterator itr = Members.begin(); itr != Members.end(); ++itr)
if (itr->Guid == guid)
return true;
return false;
}
uint32 ArenaTeam::GetPoints(uint32 memberRating)
{
// Returns how many points would be awarded with this team type with this rating
float points;
uint32 rating = memberRating + 150 < Stats.Rating ? memberRating : Stats.Rating;
if (rating <= 1500)
{
if (sWorld->getIntConfig(CONFIG_ARENA_SEASON_ID) < 6)
points = (float)rating * 0.22f + 14.0f;
else
points = 344;
}
else
points = 1511.26f / (1.0f + 1639.28f * exp(-0.00412f * (float)rating));
// Type penalties for teams < 5v5
if (Type == ARENA_TEAM_2v2)
points *= 0.76f;
else if (Type == ARENA_TEAM_3v3)
points *= 0.88f;
return (uint32) points;
}
uint32 ArenaTeam::GetAverageMMR(Group* group) const
{
if (!group)
return 0;
uint32 matchMakerRating = 0;
uint32 playerDivider = 0;
for (MemberList::const_iterator itr = Members.begin(); itr != Members.end(); ++itr)
{
// Skip if player is not online
if (!ObjectAccessor::FindPlayer(itr->Guid))
continue;
// Skip if player is not member of group
if (!group->IsMember(itr->Guid))
continue;
matchMakerRating += itr->MatchMakerRating;
++playerDivider;
}
// x/0 = crash
if (playerDivider == 0)
playerDivider = 1;
matchMakerRating /= playerDivider;
return matchMakerRating;
}
float ArenaTeam::GetChanceAgainst(uint32 ownRating, uint32 opponentRating)
{
// Returns the chance to win against a team with the given rating, used in the rating adjustment calculation
// ELO system
return 1.0f / (1.0f + exp(log(10.0f) * (float)((float)opponentRating - (float)ownRating) / 650.0f));
}
int32 ArenaTeam::GetMatchmakerRatingMod(uint32 ownRating, uint32 opponentRating, bool won /*, float& confidence_factor*/)
{
// 'Chance' calculation - to beat the opponent
// This is a simulation. Not much info on how it really works
float chance = GetChanceAgainst(ownRating, opponentRating);
float won_mod = (won) ? 1.0f : 0.0f;
float mod = won_mod - chance;
// Work in progress:
/*
// This is a simulation, as there is not much info on how it really works
float confidence_mod = min(1.0f - fabs(mod), 0.5f);
// Apply confidence factor to the mod:
mod *= confidence_factor
// And only after that update the new confidence factor
confidence_factor -= ((confidence_factor - 1.0f) * confidence_mod) / confidence_factor;
*/
// Real rating modification
mod *= 24.0f;
return (int32)ceil(mod);
}
int32 ArenaTeam::GetRatingMod(uint32 ownRating, uint32 opponentRating, bool won /*, float confidence_factor*/)
{
// 'Chance' calculation - to beat the opponent
// This is a simulation. Not much info on how it really works
float chance = GetChanceAgainst(ownRating, opponentRating);
float won_mod = (won) ? 1.0f : 0.0f;
// Calculate the rating modification
float mod;
// TODO: Replace this hack with using the confidence factor (limiting the factor to 2.0f)
if (won && ownRating < 1300)
{
if (ownRating < 1000)
mod = 48.0f * (won_mod - chance);
else
mod = (24.0f + (24.0f * (1300.0f - float(ownRating)) / 300.0f)) * (won_mod - chance);
}
else
mod = 24.0f * (won_mod - chance);
return (int32)ceil(mod);
}
void ArenaTeam::FinishGame(int32 mod)
{
// Rating can only drop to 0
if (int32(Stats.Rating) + mod < 0)
Stats.Rating = 0;
else
{
Stats.Rating += mod;
// Check if rating related achivements are met
for (MemberList::iterator itr = Members.begin(); itr != Members.end(); ++itr)
if (Player* member = ObjectAccessor::FindPlayer(itr->Guid))
member->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING, Stats.Rating, Type);
}
// Update number of games played per season or week
Stats.WeekGames += 1;
Stats.SeasonGames += 1;
// Update team's rank, start with rank 1 and increase until no team with more rating was found
Stats.Rank = 1;
ArenaTeamMgr::ArenaTeamContainer::const_iterator i = sArenaTeamMgr->GetArenaTeamMapBegin();
for (; i != sArenaTeamMgr->GetArenaTeamMapEnd(); ++i)
{
if (i->second->GetType() == Type && i->second->GetStats().Rating > Stats.Rating)
++Stats.Rank;
}
}
int32 ArenaTeam::WonAgainst(uint32 Own_MMRating, uint32 Opponent_MMRating, int32& rating_change)
{
// Called when the team has won
// Change in Matchmaker rating
int32 mod = GetMatchmakerRatingMod(Own_MMRating, Opponent_MMRating, true);
// Change in Team Rating
rating_change = GetRatingMod(Stats.Rating, Opponent_MMRating, true);
// Modify the team stats accordingly
FinishGame(rating_change);
// Update number of wins per season and week
Stats.WeekWins += 1;
Stats.SeasonWins += 1;
// Return the rating change, used to display it on the results screen
return mod;
}
int32 ArenaTeam::LostAgainst(uint32 Own_MMRating, uint32 Opponent_MMRating, int32& rating_change)
{
// Called when the team has lost
// Change in Matchmaker Rating
int32 mod = GetMatchmakerRatingMod(Own_MMRating, Opponent_MMRating, false);
// Change in Team Rating
rating_change = GetRatingMod(Stats.Rating, Opponent_MMRating, false);
// Modify the team stats accordingly
FinishGame(rating_change);
// return the rating change, used to display it on the results screen
return mod;
}
void ArenaTeam::MemberLost(Player* player, uint32 againstMatchmakerRating, int32 MatchmakerRatingChange)
{
// Called for each participant of a match after losing
for (MemberList::iterator itr = Members.begin(); itr != Members.end(); ++itr)
{
if (itr->Guid == player->GetGUID())
{
// Update personal rating
int32 mod = GetRatingMod(itr->PersonalRating, againstMatchmakerRating, false);
itr->ModifyPersonalRating(player, mod, GetType());
// Update matchmaker rating
itr->ModifyMatchmakerRating(MatchmakerRatingChange, GetSlot());
// Update personal played stats
itr->WeekGames +=1;
itr->SeasonGames +=1;
// update the unit fields
player->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_GAMES_WEEK, itr->WeekGames);
player->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_GAMES_SEASON, itr->SeasonGames);
return;
}
}
}
void ArenaTeam::OfflineMemberLost(uint64 guid, uint32 againstMatchmakerRating, int32 MatchmakerRatingChange)
{
// Called for offline player after ending rated arena match!
for (MemberList::iterator itr = Members.begin(); itr != Members.end(); ++itr)
{
if (itr->Guid == guid)
{
// update personal rating
int32 mod = GetRatingMod(itr->PersonalRating, againstMatchmakerRating, false);
itr->ModifyPersonalRating(NULL, mod, GetType());
// update matchmaker rating
itr->ModifyMatchmakerRating(MatchmakerRatingChange, GetSlot());
// update personal played stats
itr->WeekGames += 1;
itr->SeasonGames += 1;
return;
}
}
}
void ArenaTeam::MemberWon(Player* player, uint32 againstMatchmakerRating, int32 MatchmakerRatingChange)
{
// called for each participant after winning a match
for (MemberList::iterator itr = Members.begin(); itr != Members.end(); ++itr)
{
if (itr->Guid == player->GetGUID())
{
// update personal rating
int32 mod = GetRatingMod(itr->PersonalRating, againstMatchmakerRating, true);
itr->ModifyPersonalRating(player, mod, GetType());
// update matchmaker rating
itr->ModifyMatchmakerRating(MatchmakerRatingChange, GetSlot());
// update personal stats
itr->WeekGames +=1;
itr->SeasonGames +=1;
itr->SeasonWins += 1;
itr->WeekWins += 1;
// update unit fields
player->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_GAMES_WEEK, itr->WeekGames);
player->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_GAMES_SEASON, itr->SeasonGames);
return;
}
}
}
void ArenaTeam::UpdateArenaPointsHelper(std::map<uint32, uint32>& playerPoints)
{
// Called after a match has ended and the stats are already modified
// Helper function for arena point distribution (this way, when distributing, no actual calculation is required, just a few comparisons)
// 10 played games per week is a minimum
if (Stats.WeekGames < 10)
return;
// To get points, a player has to participate in at least 30% of the matches
uint32 requiredGames = (uint32)ceil(Stats.WeekGames * 0.3f);
for (MemberList::const_iterator itr = Members.begin(); itr != Members.end(); ++itr)
{
// The player participated in enough games, update his points
uint32 pointsToAdd = 0;
if (itr->WeekGames >= requiredGames)
pointsToAdd = GetPoints(itr->PersonalRating);
std::map<uint32, uint32>::iterator player_itr = playerPoints.find(GUID_LOPART(itr->Guid));
if (player_itr != playerPoints.end())
{
// Check if there is already more points
if (player_itr->second < pointsToAdd)
playerPoints[GUID_LOPART(itr->Guid)] = pointsToAdd;
}
else
playerPoints[GUID_LOPART(itr->Guid)] = pointsToAdd;
}
}
void ArenaTeam::SaveToDB()
{
// Save team and member stats to db
// Called after a match has ended or when calculating arena_points
SQLTransaction trans = CharacterDatabase.BeginTransaction();
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPDATE_ARENA_TEAM_STATS);
stmt->setUInt16(0, Stats.Rating);
stmt->setUInt16(1, Stats.WeekGames);
stmt->setUInt16(2, Stats.WeekWins);
stmt->setUInt16(3, Stats.SeasonGames);
stmt->setUInt16(4, Stats.SeasonWins);
stmt->setUInt32(5, Stats.Rank);
stmt->setUInt32(6, GetId());
trans->Append(stmt);
for (MemberList::const_iterator itr = Members.begin(); itr != Members.end(); ++itr)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPDATE_ARENA_TEAM_MEMBER);
stmt->setUInt16(0, itr->PersonalRating);
stmt->setUInt16(1, itr->WeekGames);
stmt->setUInt16(2, itr->WeekWins);
stmt->setUInt16(3, itr->SeasonGames);
stmt->setUInt16(4, itr->SeasonWins);
stmt->setUInt32(5, GetId());
stmt->setUInt32(6, GUID_LOPART(itr->Guid));
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPDATE_CHARACTER_ARENA_STATS);
stmt->setUInt32(0, GUID_LOPART(itr->Guid));
stmt->setUInt8(1, GetSlot());
stmt->setUInt16(2, itr->MatchMakerRating);
trans->Append(stmt);
}
CharacterDatabase.CommitTransaction(trans);
}
void ArenaTeam::FinishWeek()
{
// Reset team stats
Stats.WeekGames = 0;
Stats.WeekWins = 0;
// Reset member stats
for (MemberList::iterator itr = Members.begin(); itr != Members.end(); ++itr)
{
itr->WeekGames = 0;
itr->WeekWins = 0;
}
}
bool ArenaTeam::IsFighting() const
{
for (MemberList::const_iterator itr = Members.begin(); itr != Members.end(); ++itr)
if (Player* player = ObjectAccessor::FindPlayer(itr->Guid))
if (player->GetMap()->IsBattleArena())
return true;
return false;
}
ArenaTeamMember* ArenaTeam::GetMember(const std::string& name)
{
for (MemberList::iterator itr = Members.begin(); itr != Members.end(); ++itr)
if (itr->Name == name)
return &(*itr);
return NULL;
}
ArenaTeamMember* ArenaTeam::GetMember(uint64 guid)
{
for (MemberList::iterator itr = Members.begin(); itr != Members.end(); ++itr)
if (itr->Guid == guid)
return &(*itr);
return NULL;
}
| gpl-3.0 |
GenaSG/ET | src/curl-7.12.2/lib/hostip.c | 6 | 14554 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2004, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* $Id: hostip.c,v 1.163 2004/10/10 03:32:01 bagder Exp $
***************************************************************************/
#include "setup.h"
#include <string.h>
#include <errno.h>
#define _REENTRANT
#if defined( WIN32 ) && !defined( __GNUC__ ) || defined( __MINGW32__ )
#include <malloc.h>
#else
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h> /* required for free() prototypes */
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h> /* for the close() proto */
#endif
#ifdef VMS
#include <in.h>
#include <inet.h>
#include <stdlib.h>
#endif
#endif
#ifdef HAVE_SETJMP_H
#include <setjmp.h>
#endif
#ifdef WIN32
#include <process.h>
#endif
#if ( defined( NETWARE ) && defined( __NOVELL_LIBC__ ) )
#undef in_addr_t
#define in_addr_t unsigned long
#endif
#include "urldata.h"
#include "sendf.h"
#include "hostip.h"
#include "hash.h"
#include "share.h"
#include "strerror.h"
#include "url.h"
#include "inet_ntop.h"
#define _MPRINTF_REPLACE /* use our functions only */
#include <curl/mprintf.h>
#if defined( HAVE_INET_NTOA_R ) && !defined( HAVE_INET_NTOA_R_DECL )
#include "inet_ntoa_r.h"
#endif
#include "memory.h"
/* The last #include file should be: */
#include "memdebug.h"
/*
* hostip.c explained
* ==================
*
* The main COMPILE-TIME DEFINES to keep in mind when reading the host*.c
* source file are these:
*
* CURLRES_IPV6 - this host has getaddrinfo() and family, and thus we use
* that. The host may not be able to resolve IPv6, but we don't really have to
* take that into account. Hosts that aren't IPv6-enabled have CURLRES_IPV4
* defined.
*
* CURLRES_ARES - is defined if libcurl is built to use c-ares for
* asynchronous name resolves. It cannot have ENABLE_IPV6 defined at the same
* time, as c-ares has no ipv6 support. This can be Windows or *nix.
*
* CURLRES_THREADED - is defined if libcurl is built to run under (native)
* Windows, and then the name resolve will be done in a new thread, and the
* supported API will be the same as for ares-builds.
*
* If any of the two previous are defined, CURLRES_ASYNCH is defined too. If
* libcurl is not built to use an asynchronous resolver, CURLRES_SYNCH is
* defined.
*
* The host*.c sources files are split up like this:
*
* hostip.c - method-independent resolver functions and utility functions
* hostasyn.c - functions for asynchronous name resolves
* hostsyn.c - functions for synchronous name resolves
* hostares.c - functions for ares-using name resolves
* hostthre.c - functions for threaded name resolves
* hostip4.c - ipv4-specific functions
* hostip6.c - ipv6-specific functions
*
* The hostip.h is the united header file for all this. It defines the
* CURLRES_* defines based on the config*.h and setup.h defines.
*/
/* These two symbols are for the global DNS cache */
static curl_hash hostname_cache;
static int host_cache_initialized;
static void freednsentry( void *freethis );
/*
* Curl_global_host_cache_init() initializes and sets up a global DNS cache.
* Global DNS cache is general badness. Do not use. This will be removed in
* a future version. Use the share interface instead!
*/
void Curl_global_host_cache_init( void ) {
if ( !host_cache_initialized ) {
Curl_hash_init( &hostname_cache, 7, freednsentry );
host_cache_initialized = 1;
}
}
/*
* Return a pointer to the global cache
*/
curl_hash *Curl_global_host_cache_get( void ) {
return &hostname_cache;
}
/*
* Destroy and cleanup the global DNS cache
*/
void Curl_global_host_cache_dtor( void ) {
if ( host_cache_initialized ) {
Curl_hash_clean( &hostname_cache );
host_cache_initialized = 0;
}
}
/*
* Return # of adresses in a Curl_addrinfo struct
*/
int Curl_num_addresses( const Curl_addrinfo *addr ) {
int i;
for ( i = 0; addr; addr = addr->ai_next, i++ ) ;
return i;
}
/*
* Curl_printable_address() returns a printable version of the 1st address
* given in the 'ip' argument. The result will be stored in the buf that is
* bufsize bytes big.
*
* If the conversion fails, it returns NULL.
*/
const char *Curl_printable_address( const Curl_addrinfo *ip,
char *buf, size_t bufsize ) {
const void *ip4 = &( (const struct sockaddr_in*)ip->ai_addr )->sin_addr;
int af = ip->ai_family;
#ifdef CURLRES_IPV6
const void *ip6 = &( (const struct sockaddr_in6*)ip->ai_addr )->sin6_addr;
#else
const void *ip6 = NULL;
#endif
return Curl_inet_ntop( af, af == AF_INET ? ip4 : ip6, buf, bufsize );
}
/*
* Return a hostcache id string for the providing host + port, to be used by
* the DNS caching.
*/
static char *
create_hostcache_id( char *server, int port ) {
/* create and return the new allocated entry */
return aprintf( "%s:%d", server, port );
}
struct hostcache_prune_data {
int cache_timeout;
time_t now;
};
/*
* This function is set as a callback to be called for every entry in the DNS
* cache when we want to prune old unused entries.
*
* Returning non-zero means remove the entry, return 0 to keep it in the
* cache.
*/
static int
hostcache_timestamp_remove( void *datap, void *hc ) {
struct hostcache_prune_data *data =
(struct hostcache_prune_data *) datap;
struct Curl_dns_entry *c = (struct Curl_dns_entry *) hc;
if ( ( data->now - c->timestamp < data->cache_timeout ) ||
c->inuse ) {
/* please don't remove */
return 0;
}
/* fine, remove */
return 1;
}
/*
* Prune the DNS cache. This assumes that a lock has already been taken.
*/
static void
hostcache_prune( curl_hash *hostcache, int cache_timeout, time_t now ) {
struct hostcache_prune_data user;
user.cache_timeout = cache_timeout;
user.now = now;
Curl_hash_clean_with_criterium( hostcache,
(void *) &user,
hostcache_timestamp_remove );
}
/*
* Library-wide function for pruning the DNS cache. This function takes and
* returns the appropriate locks.
*/
void Curl_hostcache_prune( struct SessionHandle *data ) {
time_t now;
if ( ( data->set.dns_cache_timeout == -1 ) || !data->hostcache ) {
/* cache forever means never prune, and NULL hostcache means
we can't do it */
return;
}
if ( data->share ) {
Curl_share_lock( data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE );
}
time( &now );
/* Remove outdated and unused entries from the hostcache */
hostcache_prune( data->hostcache,
data->set.dns_cache_timeout,
now );
if ( data->share ) {
Curl_share_unlock( data, CURL_LOCK_DATA_DNS );
}
}
#ifdef HAVE_SIGSETJMP
/* Beware this is a global and unique instance. This is used to store the
return address that we can jump back to from inside a signal handler. This
is not thread-safe stuff. */
sigjmp_buf curl_jmpenv;
#endif
/*
* Curl_cache_addr() stores a 'Curl_addrinfo' struct in the DNS cache.
*
* When calling Curl_resolv() has resulted in a response with a returned
* address, we call this function to store the information in the dns
* cache etc
*
* Returns the Curl_dns_entry entry pointer or NULL if the storage failed.
*/
struct Curl_dns_entry *
Curl_cache_addr( struct SessionHandle *data,
Curl_addrinfo *addr,
char *hostname,
int port ) {
char *entry_id;
size_t entry_len;
struct Curl_dns_entry *dns;
struct Curl_dns_entry *dns2;
time_t now;
/* Create an entry id, based upon the hostname and port */
entry_id = create_hostcache_id( hostname, port );
/* If we can't create the entry id, fail */
if ( !entry_id ) {
return NULL;
}
entry_len = strlen( entry_id );
/* Create a new cache entry */
dns = (struct Curl_dns_entry *) malloc( sizeof( struct Curl_dns_entry ) );
if ( !dns ) {
free( entry_id );
return NULL;
}
dns->inuse = 0; /* init to not used */
dns->addr = addr; /* this is the address(es) */
/* Store the resolved data in our DNS cache. This function may return a
pointer to an existing struct already present in the hash, and it may
return the same argument we pass in. Make no assumptions. */
dns2 = Curl_hash_add( data->hostcache, entry_id, entry_len + 1, (void *)dns );
if ( !dns2 ) {
/* Major badness, run away. */
free( dns );
free( entry_id );
return NULL;
}
time( &now );
dns = dns2;
dns->timestamp = now; /* used now */
dns->inuse++; /* mark entry as in-use */
/* free the allocated entry_id again */
free( entry_id );
return dns;
}
/*
* Curl_resolv() is the main name resolve function within libcurl. It resolves
* a name and returns a pointer to the entry in the 'entry' argument (if one
* is provided). This function might return immediately if we're using asynch
* resolves. See the return codes.
*
* The cache entry we return will get its 'inuse' counter increased when this
* function is used. You MUST call Curl_resolv_unlock() later (when you're
* done using this struct) to decrease the counter again.
*
* Return codes:
*
* CURLRESOLV_ERROR (-1) = error, no pointer
* CURLRESOLV_RESOLVED (0) = OK, pointer provided
* CURLRESOLV_PENDING (1) = waiting for response, no pointer
*/
int Curl_resolv( struct connectdata *conn,
char *hostname,
int port,
struct Curl_dns_entry **entry ) {
char *entry_id = NULL;
struct Curl_dns_entry *dns = NULL;
size_t entry_len;
int wait;
struct SessionHandle *data = conn->data;
CURLcode result;
int rc;
*entry = NULL;
#ifdef HAVE_SIGSETJMP
/* this allows us to time-out from the name resolver, as the timeout
will generate a signal and we will siglongjmp() from that here */
if ( !data->set.no_signal && sigsetjmp( curl_jmpenv, 1 ) ) {
/* this is coming from a siglongjmp() */
failf( data, "name lookup timed out" );
return CURLRESOLV_ERROR;
}
#endif
/* Create an entry id, based upon the hostname and port */
entry_id = create_hostcache_id( hostname, port );
/* If we can't create the entry id, fail */
if ( !entry_id ) {
return CURLRESOLV_ERROR;
}
entry_len = strlen( entry_id );
if ( data->share ) {
Curl_share_lock( data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE );
}
/* See if its already in our dns cache */
dns = Curl_hash_pick( data->hostcache, entry_id, entry_len + 1 );
if ( data->share ) {
Curl_share_unlock( data, CURL_LOCK_DATA_DNS );
}
/* free the allocated entry_id again */
free( entry_id );
rc = CURLRESOLV_ERROR; /* default to failure */
if ( !dns ) {
/* The entry was not in the cache. Resolve it to IP address */
Curl_addrinfo *addr;
/* Check what IP specifics the app has requested and if we can provide it.
* If not, bail out. */
if ( !Curl_ipvalid( data ) ) {
return CURLRESOLV_ERROR;
}
/* If Curl_getaddrinfo() returns NULL, 'wait' might be set to a non-zero
value indicating that we need to wait for the response to the resolve
call */
addr = Curl_getaddrinfo( conn, hostname, port, &wait );
if ( !addr ) {
if ( wait ) {
/* the response to our resolve call will come asynchronously at
a later time, good or bad */
/* First, check that we haven't received the info by now */
result = Curl_is_resolved( conn, &dns );
if ( result ) { /* error detected */
return CURLRESOLV_ERROR;
}
if ( dns ) {
rc = CURLRESOLV_RESOLVED; /* pointer provided */
} else {
rc = CURLRESOLV_PENDING; /* no info yet */
}
}
} else {
if ( data->share ) {
Curl_share_lock( data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE );
}
/* we got a response, store it in the cache */
dns = Curl_cache_addr( data, addr, hostname, port );
if ( data->share ) {
Curl_share_unlock( data, CURL_LOCK_DATA_DNS );
}
if ( !dns ) {
/* returned failure, bail out nicely */
Curl_freeaddrinfo( addr );
} else {
rc = CURLRESOLV_RESOLVED;
}
}
} else {
if ( data->share ) {
Curl_share_lock( data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE );
}
dns->inuse++; /* we use it! */
if ( data->share ) {
Curl_share_unlock( data, CURL_LOCK_DATA_DNS );
}
rc = CURLRESOLV_RESOLVED;
}
*entry = dns;
return rc;
}
/*
* Curl_resolv_unlock() unlocks the given cached DNS entry. When this has been
* made, the struct may be destroyed due to pruning. It is important that only
* one unlock is made for each Curl_resolv() call.
*/
void Curl_resolv_unlock( struct SessionHandle *data, struct Curl_dns_entry *dns ) {
curlassert( dns && ( dns->inuse > 0 ) );
if ( data->share ) {
Curl_share_lock( data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE );
}
dns->inuse--;
if ( data->share ) {
Curl_share_unlock( data, CURL_LOCK_DATA_DNS );
}
}
/*
* File-internal: free a cache dns entry.
*/
static void freednsentry( void *freethis ) {
struct Curl_dns_entry *p = (struct Curl_dns_entry *) freethis;
Curl_freeaddrinfo( p->addr );
free( p );
}
/*
* Curl_mk_dnscache() creates a new DNS cache and returns the handle for it.
*/
curl_hash *Curl_mk_dnscache( void ) {
return Curl_hash_alloc( 7, freednsentry );
}
#ifdef CURLRES_ADDRINFO_COPY
/* align on even 64bit boundaries */
#define MEMALIGN( x ) ( ( x ) + ( 8 - ( ( (unsigned long)( x ) )& 0x7 ) ) )
/*
* Curl_addrinfo_copy() performs a "deep" copy of a hostent into a buffer and
* returns a pointer to the malloc()ed copy. You need to call free() on the
* returned buffer when you're done with it.
*/
Curl_addrinfo *Curl_addrinfo_copy( void *org, int port ) {
struct hostent *orig = org;
return Curl_he2ai( orig, port );
}
#endif /* CURLRES_ADDRINFO_COPY */
| gpl-3.0 |
Serabass/vice-players | Server/CPlayer.cpp | 6 | 17202 | //----------------------------------------------------
//
// VC:MP Multiplayer Modification For GTA:VC
// Copyright 2004-2005 SA:MP team
//
// File Author(s): kyeman
// License: See LICENSE in root directory
//
//----------------------------------------------------
#include "StdInc.h"
extern CNetworkManager *pNetowkManager;
extern CScripts *pScripts;
using namespace RakNet;
//----------------------------------------------------
void DecompressVector1(VECTOR_PAD * vec, C_VECTOR1 * c1)
{
vec->X = (float)c1->X;
vec->X = (float)((double)vec->X / 10000.0);
vec->Y = (float)c1->Y;
vec->Y = (float)((double)vec->Y / 10000.0);
vec->Z = (float)c1->Z;
vec->Z = (float)((double)vec->Z / 10000.0);
}
//----------------------------------------------------
CPlayer::CPlayer()
{
m_byteUpdateFromNetwork = UPDATE_TYPE_NONE;
m_bytePlayerID = INVALID_ENTITY_ID;
m_bIsActive = FALSE;
m_bIsWasted = FALSE;
m_vehicleID = 0;
m_iMoney = 0;
float m_iGravity = 0.008f;
m_bHasAim = false;
}
//----------------------------------------------------
void CPlayer::Process()
{
if(m_bIsActive)
{
if(m_byteUpdateFromNetwork != UPDATE_TYPE_NONE)
{
if(ValidateSyncData()) {
BroadcastSyncData();
}
m_byteUpdateFromNetwork = UPDATE_TYPE_NONE;
}
}
}
//----------------------------------------------------
// thx CKY.BAM <g>
BOOL CPlayer::ValidateSyncData()
{
if(m_vecPos.X > 2500.0f || m_vecPos.X < -2500.0f) {
return FALSE;
}
if(m_vecPos.Y > 2500.0f || m_vecPos.Y < -2500.0f) {
return FALSE;
}
if(m_vecPos.Z > 300.0f || m_vecPos.Z < 0.0f) {
return FALSE;
}
return TRUE;
}
//----------------------------------------------------
void CPlayer::BroadcastSyncData()
{
RakNet::BitStream bsSync;
if(m_byteUpdateFromNetwork == UPDATE_TYPE_FULL_ONFOOT)
{
PLAYER_SYNC_DATA playerSyncData;
bsSync.Write((MessageID)ID_PLAYER_SYNC);
bsSync.Write(m_bytePlayerID);
playerSyncData.wKeys = m_wKeys;
memcpy(&playerSyncData.vecPos, &m_vecPos, sizeof(Vector3));
playerSyncData.fRotation = m_fRotation;
playerSyncData.byteCurrentWeapon = m_byteCurrentWeapon;
playerSyncData.byteShootingFlags = m_byteShootingFlags;
playerSyncData.byteHealth = m_byteHealth;
playerSyncData.byteArmour = m_byteArmour;
bsSync.Write((char *)&playerSyncData, sizeof(PLAYER_SYNC_DATA));
if(m_bHasAim)
{
bsSync.Write1();
bsSync.Write((char *)&m_Aiming, sizeof(S_CAMERA_AIM));
m_bHasAim = false;
}
else
{
bsSync.Write0();
}
pNetowkManager->BroadcastData(&bsSync,HIGH_PRIORITY,UNRELIABLE_SEQUENCED,0,m_bytePlayerID);
}
else if(m_byteUpdateFromNetwork == UPDATE_TYPE_FULL_INCAR)
{
VEHICLE_SYNC_DATA vehicleSyncData;
bsSync.Write((MessageID)ID_VEHICLE_SYNC);
bsSync.Write(m_bytePlayerID);
vehicleSyncData.vehicleID = m_vehicleID;
vehicleSyncData.wKeys = m_wKeys;
memcpy(&vehicleSyncData.vecRoll, &m_vecRoll, sizeof(Vector3));
memcpy(&vehicleSyncData.vecDirection, &m_vecDirection, sizeof(Vector3));
memcpy(&vehicleSyncData.vecPos, &m_vecPos, sizeof(Vector3));
memcpy(&vehicleSyncData.vecMoveSpeed, &m_vecMoveSpeed, sizeof(Vector3));
memcpy(&vehicleSyncData.vecTurnSpeed, &m_vecTurnSpeed, sizeof(Vector3));
vehicleSyncData.byteVehicleHealth = PACK_VEHICLE_HEALTH(m_fVehicleHealth);
vehicleSyncData.bytePlayerHealth = m_byteHealth;
vehicleSyncData.bytePlayerArmour = m_byteArmour;
bsSync.Write((char *)&vehicleSyncData, sizeof(VEHICLE_SYNC_DATA));
pNetowkManager->BroadcastData(&bsSync,HIGH_PRIORITY,UNRELIABLE_SEQUENCED,0,m_bytePlayerID);
}
}
//----------------------------------------------------
void CPlayer::StoreOnFootFullSyncData(PLAYER_SYNC_DATA * pPlayerSyncData)
{
if(m_vehicleID != 0) {
pNetowkManager->GetVehicleManager()->GetAt(m_vehicleID)->SetDriverId(INVALID_ENTITY_ID);
m_vehicleID = 0;
}
// update player data
m_wKeys = pPlayerSyncData->wKeys;
memcpy(&m_vecPos, &pPlayerSyncData->vecPos, sizeof(Vector3));
m_fRotation = pPlayerSyncData->fRotation;
m_byteCurrentWeapon = pPlayerSyncData->byteCurrentWeapon;
m_byteShootingFlags = pPlayerSyncData->byteShootingFlags;
// note: should do something like this for armour too (or add armour to this callback)?
if(GetHealth() != pPlayerSyncData->byteHealth) {
pScripts->onPlayerDamage(m_bytePlayerID, GetHealth(), pPlayerSyncData->byteHealth);
}
m_byteHealth = pPlayerSyncData->byteHealth;
m_byteArmour = pPlayerSyncData->byteArmour;
// update network update type
m_byteUpdateFromNetwork = UPDATE_TYPE_FULL_ONFOOT;
// call onPlayerSync scripting callback
pScripts->onPlayerSync(m_bytePlayerID);
}
//----------------------------------------------------
void CPlayer::StoreAimSyncData(S_CAMERA_AIM * pAim)
{
m_bHasAim = true;
memcpy(&m_Aiming, pAim, sizeof(S_CAMERA_AIM));
}
//----------------------------------------------------
void CPlayer::StoreInCarFullSyncData(VEHICLE_SYNC_DATA * pVehicleSyncData)
{
// get the vehicle pointer
CVehicle * pVehicle = pNetowkManager->GetVehicleManager()->GetAt(pVehicleSyncData->vehicleID);
// make sure vehicle is valid
if(!pVehicle)
{
// sending vehicle sync data for invalid vehicle
return;
}
// update player data
m_vehicleID = pVehicleSyncData->vehicleID;
m_wKeys = pVehicleSyncData->wKeys;
memcpy(&m_vecRoll, &pVehicleSyncData->vecRoll, sizeof(Vector3));
memcpy(&m_vecDirection, &pVehicleSyncData->vecDirection, sizeof(Vector3));
//memcpy(&m_cvecRoll, &pVehicleSyncData->cvecRoll, sizeof(C_VECTOR1));
//memcpy(&m_cvecDirection, &pVehicleSyncData->cvecDirection, sizeof(C_VECTOR1));
memcpy(&m_vecPos, &pVehicleSyncData->vecPos, sizeof(Vector3));
memcpy(&m_vecMoveSpeed, &pVehicleSyncData->vecMoveSpeed, sizeof(Vector3));
memcpy(&m_vecTurnSpeed, &pVehicleSyncData->vecTurnSpeed, sizeof(Vector3));
m_fVehicleHealth = UNPACK_VEHICLE_HEALTH(pVehicleSyncData->byteVehicleHealth);
m_byteHealth = pVehicleSyncData->bytePlayerHealth;
m_byteArmour = pVehicleSyncData->bytePlayerArmour;
m_bIsInVehicle = TRUE;
m_bIsAPassenger = FALSE;
// update network update type
m_byteUpdateFromNetwork = UPDATE_TYPE_FULL_INCAR;
// call onPlayerSync scripting callback
pScripts->onPlayerSync(m_bytePlayerID);
MATRIX4X4 matWorld;
// copy the roll and direction vectors into the new matrix
memcpy(&matWorld.vLookRight, &pVehicleSyncData->vecRoll, sizeof(Vector3));
memcpy(&matWorld.vLookUp, &pVehicleSyncData->vecDirection, sizeof(Vector3));
// decompress the roll and direction vectors into the new vehicle matrix
//DecompressVector1(&matWorld.vLookRight, pVehicleSyncData->cvecRoll);
//DecompressVector1(&matWorld.vLookUp, pVehicleSyncData->cvecDirection);
// copy the vehicle pos into the new vehicle matrix
memcpy(&matWorld.vPos, &pVehicleSyncData->vecPos, sizeof(Vector3));
// update the vehicle data
pVehicle->Update(m_bytePlayerID, &matWorld, &pVehicleSyncData->vecMoveSpeed, &pVehicleSyncData->vecTurnSpeed, m_fVehicleHealth);
}
//----------------------------------------------------
void CPlayer::Say(PCHAR szText, BYTE byteTextLength)
{
}
//----------------------------------------------------
void CPlayer::HandleDeath(BYTE byteReason, BYTE byteWhoWasResponsible)
{
RakNet::BitStream bsPlayerDeath;
SystemAddress playerid = pNetowkManager->GetRakPeer()->GetSystemAddressFromIndex(m_bytePlayerID);
m_bIsActive = FALSE;
m_bIsWasted = TRUE;
BYTE byteScoringModifier;
byteScoringModifier =
pNetowkManager->GetPlayerManager()->AddResponsibleDeath(byteWhoWasResponsible,m_bytePlayerID);
bsPlayerDeath.Write(m_bytePlayerID);
bsPlayerDeath.Write(byteReason);
bsPlayerDeath.Write(byteWhoWasResponsible);
bsPlayerDeath.Write(byteScoringModifier);
// Broadcast it
pNetowkManager->GetRPC4()->Call("Death", &bsPlayerDeath,HIGH_PRIORITY,RELIABLE,0,playerid,true);
logprintf("<%s> died",
pNetowkManager->GetPlayerManager()->GetPlayerName(m_bytePlayerID),
byteReason,byteWhoWasResponsible,byteScoringModifier);
}
//----------------------------------------------------
void CPlayer::SetSpawnInfo(BYTE byteTeam, BYTE byteSkin, Vector3 * vecPos, float fRotation,
int iSpawnWeapon1, int iSpawnWeapon1Ammo, int iSpawnWeapon2, int iSpawnWeapon2Ammo,
int iSpawnWeapon3, int iSpawnWeapon3Ammo)
{
m_SpawnInfo.byteTeam = byteTeam;
m_SpawnInfo.byteSkin = byteSkin;
m_SpawnInfo.vecPos.X = vecPos->X;
m_SpawnInfo.vecPos.Y = vecPos->Y;
m_SpawnInfo.vecPos.Z = vecPos->Z;
m_SpawnInfo.fRotation = fRotation;
m_SpawnInfo.iSpawnWeapons[0] = iSpawnWeapon1;
m_SpawnInfo.iSpawnWeapons[1] = iSpawnWeapon2;
m_SpawnInfo.iSpawnWeapons[2] = iSpawnWeapon3;
m_SpawnInfo.iSpawnWeaponsAmmo[0] = iSpawnWeapon1Ammo;
m_SpawnInfo.iSpawnWeaponsAmmo[1] = iSpawnWeapon2Ammo;
m_SpawnInfo.iSpawnWeaponsAmmo[2] = iSpawnWeapon3Ammo;
m_bHasSpawnInfo = TRUE;
}
//----------------------------------------------------
void CPlayer::Spawn()
{
if(m_bHasSpawnInfo) {
// Reset all their sync attributes.
m_vecPos.X = m_SpawnInfo.vecPos.X;
m_vecPos.Y = m_SpawnInfo.vecPos.Y;
m_vecPos.Z = m_SpawnInfo.vecPos.Z;
m_fRotation = m_SpawnInfo.fRotation;
memset(&m_vecMoveSpeed,0,sizeof(Vector3));
memset(&m_vecTurnSpeed,0,sizeof(Vector3));
m_fRotation = 0.0f;
m_bIsInVehicle=FALSE;
m_bIsAPassenger=FALSE;
m_vehicleID=0;
SpawnForWorld(m_SpawnInfo.byteTeam,m_SpawnInfo.byteSkin,&m_SpawnInfo.vecPos,m_SpawnInfo.fRotation);
}
}
//----------------------------------------------------
// This is the method used for respawning.
void CPlayer::SpawnForWorld( BYTE byteTeam, BYTE byteSkin, Vector3 * vecPos,
float fRotation )
{
RakNet::BitStream bsPlayerSpawn;
SystemAddress playerid = pNetowkManager->GetRakPeer()->GetSystemAddressFromIndex(m_bytePlayerID);
bsPlayerSpawn.Write(m_bytePlayerID);
bsPlayerSpawn.Write(byteTeam);
bsPlayerSpawn.Write(byteSkin);
bsPlayerSpawn.Write(vecPos->X);
bsPlayerSpawn.Write(vecPos->Y);
bsPlayerSpawn.Write(vecPos->Z);
bsPlayerSpawn.Write(fRotation);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeapons[0]);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeaponsAmmo[0]);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeapons[1]);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeaponsAmmo[1]);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeapons[2]);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeaponsAmmo[2]);
pNetowkManager->GetRPC4()->Call("Spawn", &bsPlayerSpawn,HIGH_PRIORITY,RELIABLE_ORDERED,0,playerid,true);
m_bIsActive = TRUE;
m_bIsWasted = FALSE;
// Set their initial sync position to their spawn position.
m_vecPos.X = vecPos->X;
m_vecPos.Y = vecPos->Y;
m_vecPos.Z = vecPos->Z;
m_byteShootingFlags = 1;
}
//----------------------------------------------------
// This is the method used for spawning players that
// already exist in the world when the client connects.
void CPlayer::SpawnForPlayer(BYTE byteForSystemAddress)
{
RakNet::BitStream bsPlayerSpawn;
bsPlayerSpawn.Write(m_bytePlayerID);
bsPlayerSpawn.Write(m_SpawnInfo.byteTeam);
bsPlayerSpawn.Write(m_SpawnInfo.byteSkin);
bsPlayerSpawn.Write(m_vecPos.X);
bsPlayerSpawn.Write(m_vecPos.Y);
bsPlayerSpawn.Write(m_vecPos.Z);
bsPlayerSpawn.Write(m_fRotation);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeapons[0]);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeaponsAmmo[0]);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeapons[1]);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeaponsAmmo[1]);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeapons[2]);
bsPlayerSpawn.Write(m_SpawnInfo.iSpawnWeaponsAmmo[2]);
pNetowkManager->GetRPC4()->Call("Spawn", &bsPlayerSpawn,HIGH_PRIORITY,RELIABLE_ORDERED,0,pNetowkManager->GetRakPeer()->GetSystemAddressFromIndex(byteForSystemAddress),false);
}
//----------------------------------------------------
void CPlayer::EnterVehicle(EntityId vehicleID, BYTE bytePassenger)
{
RakNet::BitStream bsVehicle;
SystemAddress playerid = pNetowkManager->GetRakPeer()->GetSystemAddressFromIndex(m_bytePlayerID);
bsVehicle.Write(m_bytePlayerID);
bsVehicle.Write(vehicleID);
bsVehicle.Write(bytePassenger);
pNetowkManager->GetRPC4()->Call("EnterVehicle", &bsVehicle,HIGH_PRIORITY,RELIABLE_ORDERED,0,playerid,true);
}
//----------------------------------------------------
void CPlayer::ExitVehicle(EntityId vehicleID)
{
RakNet::BitStream bsVehicle;
SystemAddress playerid = pNetowkManager->GetRakPeer()->GetSystemAddressFromIndex(m_bytePlayerID);
bsVehicle.Write(m_bytePlayerID);
bsVehicle.Write(vehicleID);
pNetowkManager->GetRPC4()->Call("ExitVehicle", &bsVehicle,HIGH_PRIORITY,RELIABLE_ORDERED,0,playerid,true);
}
//----------------------------------------------------
WORD CPlayer::GetKeys()
{
return m_wKeys;
}
//----------------------------------------------------
void CPlayer::GetPosition(Vector3 * vecPosition)
{
memcpy(vecPosition, &m_vecPos, sizeof(Vector3));
}
//----------------------------------------------------
void CPlayer::GetMoveSpeed(Vector3 * vecMoveSpeed)
{
memcpy(vecMoveSpeed, &m_vecMoveSpeed, sizeof(Vector3));
}
//----------------------------------------------------
void CPlayer::GetTurnSpeed(Vector3 * vecTurnSpeed)
{
memcpy(vecTurnSpeed, &m_vecTurnSpeed, sizeof(Vector3));
}
//----------------------------------------------------
float CPlayer::GetRotation()
{
return m_fRotation;
}
//----------------------------------------------------
BYTE CPlayer::GetHealth()
{
return m_byteHealth;
}
//----------------------------------------------------
BYTE CPlayer::GetArmour()
{
return m_byteArmour;
}
//----------------------------------------------------
BYTE CPlayer::GetCurrentWeapon()
{
return m_byteCurrentWeapon;
}
//----------------------------------------------------
BYTE CPlayer::GetAction()
{
return m_byteShootingFlags;
}
//----------------------------------------------------
BOOL CPlayer::IsAPassenger()
{
return m_bIsAPassenger;
}
//----------------------------------------------------
BYTE CPlayer::GetVehicleID()
{
return m_vehicleID;
}
//----------------------------------------------------
void CPlayer::SetGameTime(BYTE hours, BYTE minutes)
{
RakNet::BitStream bsTime;
SystemAddress playerid = pNetowkManager->GetRakPeer()->GetSystemAddressFromIndex(m_bytePlayerID);
bsTime.Write(hours);
bsTime.Write(minutes);
pNetowkManager->GetRPC4()->Call("SetGameTime", &bsTime,HIGH_PRIORITY,RELIABLE_ORDERED,0,playerid,false);
}
//----------------------------------------------------
void CPlayer::SetCameraPos(Vector3 vPos)
{
RakNet::BitStream bsSend;
SystemAddress playerid = pNetowkManager->GetRakPeer()->GetSystemAddressFromIndex(m_bytePlayerID);
bsSend.Write(vPos.X);
bsSend.Write(vPos.Y);
bsSend.Write(vPos.Z);
pNetowkManager->GetRPC4()->Call("SetCameraPosition", &bsSend,HIGH_PRIORITY,RELIABLE_ORDERED,0,playerid,false);
}
//----------------------------------------------------
void CPlayer::SetCameraRot(Vector3 vRot)
{
RakNet::BitStream bsSend;
SystemAddress playerid = pNetowkManager->GetRakPeer()->GetSystemAddressFromIndex(m_bytePlayerID);
bsSend.Write(vRot.X);
bsSend.Write(vRot.Y);
bsSend.Write(vRot.Z);
pNetowkManager->GetRPC4()->Call("SetCameraRotation", &bsSend,HIGH_PRIORITY,RELIABLE_ORDERED,0,playerid,false);
}
//----------------------------------------------------
void CPlayer::SetCameraLookAt(Vector3 vPoint)
{
RakNet::BitStream bsSend;
SystemAddress playerid = pNetowkManager->GetRakPeer()->GetSystemAddressFromIndex(m_bytePlayerID);
bsSend.Write(vPoint.X);
bsSend.Write(vPoint.Y);
bsSend.Write(vPoint.Z);
pNetowkManager->GetRPC4()->Call("SetCameraLookAt", &bsSend,HIGH_PRIORITY,RELIABLE_ORDERED,0,playerid,false);
}
//----------------------------------------------------
void CPlayer::SetCameraBehindPlayer()
{
SystemAddress playerid = pNetowkManager->GetRakPeer()->GetSystemAddressFromIndex(m_bytePlayerID);
pNetowkManager->GetRPC4()->Call("SetCameraBehindPlayer", NULL,HIGH_PRIORITY,RELIABLE_ORDERED,0,playerid,false);
}
//----------------------------------------------------
void CPlayer::SetCash(int Cash)
{
BitStream bsSend;
bsSend.Write(Cash);
SystemAddress playerid = pNetowkManager->GetRakPeer()->GetSystemAddressFromIndex(m_bytePlayerID);
pNetowkManager->GetRPC4()->Call("Script_SetPlayerCash",&bsSend,HIGH_PRIORITY,RELIABLE_ORDERED,0,playerid,false);
m_iMoney = Cash;
}
//----------------------------------------------------
int CPlayer::GetCash()
{
return m_iMoney;
}
float CPlayer::GetGravity()
{
return m_iGravity;
}
//----------------------------------------------------
void CPlayer::SetGravity(float amount)
{
BitStream bsSend;
bsSend.Write(amount);
SystemAddress playerid = pNetowkManager->GetRakPeer()->GetSystemAddressFromIndex(m_bytePlayerID);
m_iGravity = amount;
pNetowkManager->GetRPC4()->Call("Script_SetPlayerGravity",&bsSend,HIGH_PRIORITY,RELIABLE_ORDERED,0,playerid,false);
}
| gpl-3.0 |
Yawgmoth90/pykep | src/third_party/cspice/nearpt.c | 7 | 68823 | /* nearpt.f -- translated by f2c (version 19980913).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
#include "f2c.h"
/* Table of constant values */
static integer c__3 = 3;
static doublereal c_b36 = 2.;
static integer c__2048 = 2048;
static doublereal c_b108 = 1e-16;
/* $Procedure NEARPT ( Nearest point on an ellipsoid ) */
/* Subroutine */ int nearpt_(doublereal *positn, doublereal *a, doublereal *b,
doublereal *c__, doublereal *npoint, doublereal *alt)
{
/* Initialized data */
static char mssg[80*7] = "Axis A was nonpositive. ? "
" " "Axis B was nonpositive. ? "
" " "Axes A a"
"nd B were nonpositive. ? "
" " "Axis C was nonpositive. ? "
" " "Axes A and C were nonpositive. ? "
" " "Axes B and C we"
"re nonpositive. ? "
"All three axes were nonpositive. ? "
" ";
/* System generated locals */
integer i__1, i__2, i__3, i__4, i__5, i__6;
doublereal d__1, d__2, d__3, d__4, d__5;
/* Builtin functions */
integer s_rnge(char *, integer, char *, integer);
double sqrt(doublereal), pow_dd(doublereal *, doublereal *);
/* Local variables */
extern /* Subroutine */ int vadd_(doublereal *, doublereal *, doublereal *
);
doublereal sign, axis[3], temp, term[3], errp[3], copy[3];
logical trim;
extern /* Subroutine */ int vequ_(doublereal *, doublereal *);
integer i__;
doublereal q, scale;
extern /* Subroutine */ int chkin_(char *, ftnlen);
doublereal denom;
extern /* Subroutine */ int errch_(char *, char *, ftnlen, ftnlen);
extern doublereal dpmax_(void);
extern /* Subroutine */ int errdp_(char *, doublereal *, ftnlen);
logical extra;
doublereal lower;
extern doublereal vdist_(doublereal *, doublereal *);
doublereal point[3], pnorm, upper;
extern /* Subroutine */ int vperp_(doublereal *, doublereal *, doublereal
*);
extern doublereal vnorm_(doublereal *);
doublereal denom2, denom3, lambda, tlambd[3], height;
extern doublereal brcktd_(doublereal *, doublereal *, doublereal *);
logical inside;
doublereal factor;
extern /* Subroutine */ int orderd_(doublereal *, integer *, integer *),
reordd_(integer *, integer *, doublereal *);
doublereal toobig;
integer iorder[3];
extern doublereal touchd_(doublereal *);
doublereal olderr, normal[3], bestht, orignl[3], prodct;
extern /* Subroutine */ int sigerr_(char *, ftnlen);
doublereal epoint[3];
extern /* Subroutine */ int chkout_(char *, ftnlen), vsclip_(doublereal *,
doublereal *);
doublereal bestpt[3], newerr;
extern /* Subroutine */ int setmsg_(char *, ftnlen);
doublereal axisqr[3];
extern logical approx_(doublereal *, doublereal *, doublereal *);
doublereal qlower;
integer snglpt;
doublereal qupper, spoint[3];
extern logical return_(void);
logical solvng;
extern /* Subroutine */ int errint_(char *, integer *, ftnlen), surfnm_(
doublereal *, doublereal *, doublereal *, doublereal *,
doublereal *);
integer solutn, bad;
doublereal err[3];
integer itr;
/* $ Abstract */
/* This routine locates the point on the surface of an ellipsoid */
/* that is nearest to a specified position. It also returns the */
/* altitude of the position above the ellipsoid. */
/* $ Disclaimer */
/* THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE */
/* CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */
/* GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */
/* ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */
/* PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */
/* TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY */
/* WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */
/* PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */
/* SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */
/* SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */
/* IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */
/* BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */
/* LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */
/* INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */
/* REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */
/* REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */
/* RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */
/* THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */
/* CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */
/* ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */
/* $ Required_Reading */
/* None. */
/* $ Keywords */
/* ALTITUDE */
/* ELLIPSOID */
/* GEOMETRY */
/* $ Declarations */
/* $ Brief_I/O */
/* VARIABLE I/O DESCRIPTION */
/* -------- --- -------------------------------------------------- */
/* POSITN I Position of a point in body-fixed frame. */
/* A I Length of semi-axis parallel to x-axis. */
/* B I Length of semi-axis parallel to y-axis. */
/* C I Length on semi-axis parallel to z-axis. */
/* NPOINT O Point on the ellipsoid closest to POSITN. */
/* ALT O Altitude of POSITN above the ellipsoid. */
/* $ Detailed_Input */
/* POSITN 3-vector giving the position of a point with respect */
/* to the center of an ellipsoid. The vector is expressed */
/* in a body-fixed reference frame. The semi-axes of the */
/* ellipsoid are aligned with the x, y, and z-axes of the */
/* body-fixed frame. */
/* A Length of the semi-axis of the ellipsoid that is */
/* parallel to the x-axis of the body-fixed reference */
/* frame. */
/* B Length of the semi-axis of the ellipsoid that is */
/* parallel to the y-axis of the body-fixed reference */
/* frame. */
/* C Length of the semi-axis of the ellipsoid that is */
/* parallel to the z-axis of the body-fixed reference */
/* frame. */
/* $ Detailed_Output */
/* NPOINT is the nearest point on the ellipsoid to POSITN. */
/* NPOINT is a 3-vector expressed in the body-fixed */
/* reference frame. */
/* ALT is the altitude of POSITN above the ellipsoid. If */
/* POSITN is inside the ellipsoid, ALT will be negative */
/* and have magnitude equal to the distance between */
/* NPOINT and POSITN. */
/* $ Parameters */
/* None. */
/* $ Exceptions */
/* 1) If any of the axis lengths A, B or C are non-positive, the */
/* error SPICE(BADAXISLENGTH) will be signaled. */
/* 2) If the ratio of the longest to the shortest ellipsoid axis */
/* is large enough so that arithmetic expressions involving its */
/* squared value may overflow, the error SPICE(BADAXISLENGTH) */
/* will be signaled. */
/* 3) If any of the expressions */
/* A * ABS( POSITN(1) ) / m**2 */
/* B * ABS( POSITN(2) ) / m**2 */
/* C * ABS( POSITN(3) ) / m**2 */
/* where m is the minimum of { A, B, C }, is large enough so */
/* that arithmetic expressions involving these sub-expressions */
/* may overflow, the error SPICE(INPUTSTOOLARGE) is signaled. */
/* 4) If the axes of the ellipsoid have radically different */
/* magnitudes, for example if the ratios of the axis lengths vary */
/* by 10 orders of magnitude, the results may have poor */
/* precision. No error checks are done to identify this problem. */
/* 5) If the axes of the ellipsoid and the input point POSITN have */
/* radically different magnitudes, for example if the ratio of */
/* the magnitude of POSITN to the length of the shortest axis is */
/* 1.E25, the results may have poor precision. No error checks */
/* are done to identify this problem. */
/* $ Files */
/* None. */
/* $ Particulars */
/* Many applications of this routine are more easily performed */
/* using the higher-level SPICELIB routine SUBPNT. This routine */
/* is the mathematical workhorse on which SUBPNT relies. */
/* $ Examples */
/* Example 1. */
/* The code fragment below illustrates how you can use SPICELIB to */
/* compute the apparent sub-earth point on the moon. */
/* C */
/* C Load the ephemeris, leapseconds and physical constants */
/* C files first. We assume the names of these files are */
/* C stored in the character variables SPK, LSK and */
/* C PCK. */
/* C */
/* CALL FURNSH ( SPK ) */
/* CALL FURNSH ( LSK ) */
/* CALL FURNSH ( PCK ) */
/* C */
/* C Get the apparent position of the moon as seen from the */
/* C earth. Look up this position vector in the moon */
/* C body-fixed frame IAU_MOON. The orientation of the */
/* C IAU_MOON frame will be computed at epoch ET-LT. */
/* C */
/* CALL SPKPOS ( 'moon', ET, 'IAU_MOON', 'LT+S', */
/* . 'earth', TRGPOS, LT ) */
/* C */
/* C Negate the moon's apparent position to obtain the */
/* C position of the earth in the moon's body-fixed frame. */
/* C */
/* CALL VMINUS ( TRGPOS, EVEC ) */
/* C */
/* C Get the lengths of the principal axes of the moon. */
/* C Transfer the elements of the array RADII to the */
/* C variables A, B, C to enhance readability. */
/* C */
/* CALL BODVRD ( 'MOON', 'RADII', DIM, RADII ) */
/* CALL VUPACK ( RADII, A, B, C ) */
/* C */
/* C Finally get the point SUBPNT on the surface of the */
/* C moon closest to the earth --- the sub-earth point. */
/* C SUBPNT is expressed in the IAU_MOON reference frame. */
/* C */
/* CALL NEARPT ( EVEC, A, B, C, SUBPNT, ALT ) */
/* Example 2. */
/* One can use this routine to define a generalization of GEODETIC */
/* coordinates called GAUSSIAN coordinates of a triaxial body. (The */
/* name is derived from the famous Gauss-map of classical */
/* differential geometry). The coordinates are longitude, */
/* latitude, and altitude. */
/* We let the x-axis of the body fixed coordinate system point */
/* along the longest axis of the triaxial body. The y-axis points */
/* along the middle axis and the z-axis points along the shortest */
/* axis. */
/* Given a point P, there is a point on the ellipsoid that is */
/* closest to P, call it Q. The latitude and longitude of P */
/* are determined by constructing the outward pointing unit normal */
/* to the ellipsoid at Q. Latitude of P is the latitude that the */
/* normal points toward in the body-fixed frame. Longitude is */
/* the longitude the normal points to in the body-fixed frame. */
/* The altitude is the signed distance from P to Q, positive if P */
/* is outside the ellipsoid, negative if P is inside. */
/* (the mapping of the point Q to the unit normal at Q is the */
/* Gauss-map of Q). */
/* To obtain the Gaussian coordinates of a point whose position */
/* in body-fixed rectangular coordinates is given by a vector P, */
/* the code fragment below will suffice. */
/* CALL NEARPT ( P, A, B, C, Q, ALT ) */
/* CALL SURFNM ( A, B, C Q, NRML ) */
/* CALL RECLAT ( NRML, R, LONG, LAT ) */
/* The Gaussian coordinates are LONG, LAT, and ALT. */
/* $ Restrictions */
/* See the Exceptions header section above. */
/* $ Literature_References */
/* None. */
/* $ Author_and_Institution */
/* C.H. Acton (JPL) */
/* N.J. Bachman (JPL) */
/* W.L. Taber (JPL) */
/* E.D. Wright (JPL) */
/* $ Version */
/* - SPICELIB Version 1.4.0, 27-JUN-2013 (NJB) */
/* Updated in-line comments. */
/* Last update was 04-MAR-2013 (NJB) */
/* Bug fix: now correctly computes off-axis solution for */
/* the case of a prolate ellipsoid and a viewing point */
/* on the interior long axis. */
/* - SPICELIB Version 1.3.1, 07-FEB-2008 (NJB) */
/* Header update: header now refers to SUBPNT rather */
/* than deprecated routine SUBPT. */
/* - SPICELIB Version 1.3.0, 07-AUG-2006 (NJB) */
/* Bug fix: added initialization of variable SNGLPT to support */
/* operation under the Macintosh Intel Fortran */
/* compiler. Note that this bug did not affect */
/* operation of this routine on other platforms. */
/* - SPICELIB Version 1.2.0, 15-NOV-2005 (EDW) (NJB) */
/* Various changes were made to ensure that all loops terminate. */
/* Bug fix: scale of transverse component of error vector */
/* was corrected for the exterior point case. */
/* Bug fix: non-standard use of duplicate arguments in VSCL */
/* calls was corrected. */
/* Error checking was added to screen out inputs that might */
/* cause numeric overflow. */
/* Replaced BODVAR call in examples to BODVRD. */
/* - SPICELIB Version 1.1.1, 28-JUL-2003 (NJB) (CHA) */
/* Various header corrections were made. */
/* - SPICELIB Version 1.1.0, 27-NOV-1990 (WLT) */
/* The routine was substantially rewritten to achieve */
/* more robust behavior and document the mathematics */
/* of the routine. */
/* - SPICELIB Version 1.0.1, 10-MAR-1992 (WLT) */
/* Comment section for permuted index source lines was added */
/* following the header. */
/* - SPICELIB Version 1.0.0, 31-JAN-1990 (WLT) */
/* -& */
/* $ Index_Entries */
/* distance from point to ellipsoid */
/* nearest point on an ellipsoid */
/* -& */
/* $ Revisions */
/* - SPICELIB Version 1.1.0, 07-AUG-2006 (NJB) */
/* Bug fix: added initialization of variable SNGLPT to support */
/* operation under the Macintosh Intel Fortran */
/* compiler. Note that this bug did not affect */
/* operation of this routine on other platforms. The */
/* statement referencing the uninitialized variable */
/* was: */
/* IF ( INSIDE .AND. ( SNGLPT .EQ. 2 */
/* . .OR. SNGLPT .EQ. 3 ) ) THEN */
/* SNGLPT is uninitialized only if INSIDE is .FALSE., */
/* so the value of the logical expression is not affected by */
/* the uninitialized value of SNGLPT. */
/* However, the Intel Fortran compiler for the Mac flags a runtime */
/* error when the above code is exercised. So SNGLPT is now */
/* initialized prior to the above IF statement. */
/* - SPICELIB Version 1.2.0, 15-NOV-2005 (EDW) (NJB) */
/* Bug fix: scale of transverse component of error vector */
/* was corrected for the exterior point case. */
/* Replaced BODVAR call in examples to BODVRD. */
/* Bug fix: non-standard use of duplicate arguments in VSCL */
/* calls was corrected. */
/* Various changes were made to ensure that all loops terminate. */
/* Error checking was added to screen out inputs that might */
/* cause numeric overflow. */
/* Removed secant solution branch from root-finding loop. */
/* Although the secant solution sped up some root searches, */
/* it caused large numbers of unnecessary iterations in others. */
/* Changed the expression: */
/* IF ( LAMBDA .EQ. LOWER */
/* . .OR. LAMBDA .EQ. UPPER ) THEN */
/* to */
/* IF ( APPROX( LAMBDA, LOWER, CNVTOL ) */
/* . .OR. APPROX( LAMBDA, UPPER, CNVTOL ) ) THEN */
/* Use of APPROX eliminates the possibility of an infinite loop */
/* when LAMBDA approaches to within epsilon of, but does not */
/* equate to UPPER or LOWER. Infinite loops occurred under some */
/* compiler's optimizations. */
/* The loop also includes a check on number of iterations, */
/* signaling an error if the bisection loop uses more than */
/* MAXITR passes. */
/* TOUCHD is now used to defeat extended-register usage in */
/* cases where such usage may cause logic problems. */
/* Some minor code changes were made to ensure that various */
/* variables remain in their expected ranges. */
/* A few code changes were made to enhance clarity. */
/* - SPICELIB Version 1.1.0, 27-NOV-1990 */
/* The routine was nearly rewritten so that points */
/* near the coordinate planes in the interior of the ellipsoid */
/* could be handled without fear of floating point overflow */
/* or divide by zero. */
/* While the mathematical ideas involved in the original routine */
/* are retained, the code is for the most part new. In addition, */
/* the new code has been documented far more extensively than was */
/* NEARPT 1.0.0. */
/* - Beta Version 2.0.0, 9-JAN-1989 (WLT) */
/* Error handling added has been added for bad axes values. */
/* The algorithm did not work correctly for some points inside */
/* the ellipsoid lying on the plane orthogonal to the shortest */
/* axis of the ellipsoid. The problem was corrected. */
/* Finally the algorithm was made slightly more robust and clearer */
/* by use of SPICELIB routines and by normalizing the inputs. */
/* Add an example to the header section. */
/* -& */
/* SPICELIB functions */
/* Parameters */
/* The convergence tolerance CNVTOL is used to terminate the */
/* bisection loop when the solution interval is very small but */
/* hasn't converged to length zero. This situation can occur when */
/* the root is extremely close to zero. */
/* Various potentially large numbers we'll compute must not */
/* exceed DPMAX()/MARGIN: */
/* The parameter MAXSOL determines the maximum number of */
/* iterations that will be performed in locating the */
/* near point. This must be at least 3. To get strong */
/* robustness in the routine, MAXSOL should be at least 4. */
/* MAXITR defines the maximum number of iterations allowed in */
/* the bisection loop used to find LAMBDA. If this loop requires */
/* more than MAXITR iterations to achieve convergence, NEARPT */
/* will signal an error. */
/* On a PC/Linux/g77 platform, it has been observed that each */
/* bisection loop normally completes in fewer than 70 iterations. */
/* MAXITR is used as a "backstop" to prevent infinite looping in */
/* case the normal loop termination conditions don't take effect. */
/* The value selected is based on the range of exponents for IEEE */
/* double precision floating point numbers. */
/* Length of lines in message buffer. */
/* Local Variables */
/* Saved variables */
/* Initial values */
/* Here's what you can expect to find in the routine below. */
/* Chapter 1. Error and Exception Handling. */
/* Chapter 2. Mathematical background for the solution---the */
/* lambda equation. */
/* Chapter 3. Initializations for the main processing loop. */
/* Chapter 4. Mathematical Solution of the lambda equation. */
/* Section 4.1 Avoiding numerical difficulties. */
/* Section 4.2 Bracketing the root of the lambda */
/* equation. */
/* Section 4.3 Refining the estimate of lambda. */
/* Section 4.4 Handling points on the central plane. */
/* Chapter 5. Decisions and initializations for sharpening */
/* the solution. */
/* Chapter 6. Clean up. */
/* Error and Exception Handling. */
/* ================================================================ */
/* ---------------------------------------------------------------- */
if (return_()) {
return 0;
} else {
chkin_("NEARPT", (ftnlen)6);
}
/* Check the axes to make sure that none of them is less than or */
/* equal to zero. If one is, signal an error and return. */
bad = 0;
if (*a <= 0.) {
++bad;
}
if (*b <= 0.) {
bad += 2;
}
if (*c__ <= 0.) {
bad += 4;
}
if (bad > 0) {
setmsg_(mssg + ((i__1 = bad - 1) < 7 && 0 <= i__1 ? i__1 : s_rnge(
"mssg", i__1, "nearpt_", (ftnlen)591)) * 80, (ftnlen)80);
errch_("?", "The A,B, and C axes were #, #, and # respectively.", (
ftnlen)1, (ftnlen)50);
errdp_("#", a, (ftnlen)1);
errdp_("#", b, (ftnlen)1);
errdp_("#", c__, (ftnlen)1);
sigerr_("SPICE(BADAXISLENGTH)", (ftnlen)20);
chkout_("NEARPT", (ftnlen)6);
return 0;
}
/* Mathematical background for the solution---the lambda equation. */
/* ================================================================ */
/* ---------------------------------------------------------------- */
/* Here is the background and general outline of how this problem is */
/* going to be solved. */
/* We want to find a point on the ellipsoid */
/* X**2 Y**2 Z**2 */
/* ------ + ------ + ------ = 1 */
/* A**2 B**2 C**2 */
/* that is closest to the input point POSITN. */
/* If one cares about the gory details, we know that such a */
/* point must exist because the ellipsoid is a compact subset of */
/* Euclidean 3-space and the distance function between the input */
/* point and the ellipsoid is continuous. Since any continuous */
/* function on a compact set actually achieves its minimum at */
/* some point of the compact set, we are guaranteed that a */
/* closest point exists. The closest point may not be unique if */
/* the input point is inside the ellipsoid. */
/* If we let NPOINT be a closest point to POSITN, then the line */
/* segment joining POSITN to NPOINT is parallel to the normal to the */
/* ellipsoid at NPOINT. Moreover, suppose we let SEGMENT(P) be the */
/* line segment that connects an arbitrary point P with POSITN. It */
/* can be shown that there is only one point P on the ellipsoid in */
/* the same octant at POSITN such that the normal at P is parallel */
/* to SEGMENT(P). */
/* More gory details: A normal to a point (X,Y,Z) */
/* on the ellipsoid is given by */
/* (X/A**2, Y/B**2, Z/C**2) */
/* Given a fixed LAMBDA, and allowing (X,Y,Z) to */
/* range over all points on the ellipsoid, the set */
/* of points */
/* LAMBDA*X LAMBDA*Y LAMBDA*Z */
/* ( X + --------, Y + --------, Z + -------- ) */
/* A**2 B**2 C**2 */
/* describes another ellipsoid with axes having lengths */
/* LAMBDA LAMBDA LAMBDA */
/* A + ------ , B + ------ , C + ------ . */
/* A B C */
/* Moreover, as long as LAMBDA > - MIN( A**2, B**2, C**2 ) */
/* none of these ellipsoids intersect. Thus, as long as */
/* the normal lines are not allowed to cross the coordinate plane */
/* orthogonal to the smallest axis (called the central plane) */
/* they do not intersect. */
/* Finally every point that does not lie on the central plane */
/* lies on one of the "lambda" ellipsoids described above. */
/* Consequently, for each point, P, not on the central plane */
/* there is a unique point, NPOINT, on the ellipsoid, such that */
/* the normal line at NPOINT also contains P and does not cross */
/* the central plane. */
/* From the above discussion we see that we can mathematically */
/* solve the near point problem by finding a point NPOINT */
/* on the ellipsoid given by the equation: */
/* X**2 Y**2 Z**2 */
/* ------ + ------ + ------ = 1 */
/* A**2 B**2 C**2 */
/* such that for some value of LAMBDA */
/* POSITN = NPOINT + LAMBDA*NORMAL(NPOINT). */
/* Moreover, if POSITN = (X_o,Y_o,Z_o) then LAMBDA must satisfy */
/* the equation: */
/* 2 2 2 */
/* X_o Y_o Z_o */
/* ----------------- + ------------------ + ------------------ = 1 */
/* 2 2 2 */
/* ( A + LAMBDA/A ) ( B + LAMBDA/B ) ( C + LAMBDA/C ) */
/* and LAMBDA must be greater than -MIN(A**2,B**2,C**2) */
/* Once LAMBDA is known, NPOINT can be computed from the equation: */
/* POSITN = NPOINT + LAMBDA*NORMAL(NPOINT). */
/* The process of solving for LAMBDA can be viewed as selecting */
/* that ellipsoid */
/* 2 2 2 */
/* x y z */
/* --------------- + ---------------- + --------------- = 1 */
/* 2 2 2 */
/* (a + lambda/a) ( b + lambda/b) (c + lambda/c) */
/* that contains the input point POSITN. For lambda = 0, this */
/* ellipsoid is just the input ellipsoid. When we increase */
/* lambda we get a larger "inflated" ellipsoid. When we */
/* decrease lambda we get a smaller "deflated" ellipsoid. Thus, */
/* the search for lambda can be viewed as inflating or deflating */
/* the input ellipsoid (in a specially prescribed manner) until */
/* the resulting ellipsoid contains the input point POSITN. */
/* The mathematical solution laid out above, has some numeric */
/* flaws. However, it is robust enough so that if it is applied */
/* repeatedly, we can converge to a good solution of the near point */
/* problem. */
/* In the code that follows, we will first solve the lambda equation */
/* using the original input point. However, for points near the */
/* central plane the solution we obtain may not lie on the */
/* ellipsoid. But, it should lie along the correct normal line. */
/* Using this first candidate solution, we find the closest point */
/* to it on the ellipsoid. This second iteration always produces */
/* a point that is as close as you can get to the ellipsoid. */
/* However, the normal at this second solution may not come as close */
/* as desired to pointing toward the input position. To overcome */
/* this deficiency we sharpen the second solution. */
/* To sharpen a solution we use the computed near point, the */
/* computed altitude of POSITN and the normal at the near point to */
/* approximate POSITN. The difference between the approximated */
/* position of POSITN and the input value of POSITN is called the */
/* error vector. To get a sharpened solution we translate the */
/* computed near point in the direction of the component of the */
/* error vector orthogonal to the normal. We then find the */
/* mathematical near point to our translated solution. */
/* The sharpening process is repeated until it no longer produces */
/* an "improved" near point. */
/* At each step of this procedure, we must compute a solution to */
/* the "lambda" equation in order to produce our next estimate of */
/* the near point. If it were possible to create a "private" */
/* routine in FORTRAN that only this routine could access, we */
/* would do it. However, things being what they are, we have to */
/* compute the lambda solution in a loop. We keep track of which */
/* refinement we are working on by counting the number of */
/* lambda solutions that are computed. */
/* Initializations for the main processing loop */
/* ================================================================ */
/* ---------------------------------------------------------------- */
/* Let the game begin! */
/* First order the axes of the ellipsoid and corresponding */
/* component of POSITN by the size of lengths of axes. Knowing */
/* which axes are smallest will simplify our task of computing */
/* lambda when the time comes. */
axis[0] = *a;
axis[1] = *b;
axis[2] = *c__;
vequ_(positn, point);
orderd_(axis, &c__3, iorder);
reordd_(iorder, &c__3, axis);
reordd_(iorder, &c__3, point);
/* Rescale everything so as to avoid underflows when squaring */
/* quantities and copy the original starting point. */
/* Be sure that this is UNDONE at the end of the routine. */
scale = 1. / axis[0];
vsclip_(&scale, axis);
vsclip_(&scale, point);
vequ_(point, orignl);
/* Save the norm of the scaled input point. */
pnorm = vnorm_(point);
/* The scaled axis lengths must be small enough so they can */
/* be squared. */
toobig = sqrt(dpmax_() / 100.);
/* Note the first axis has length 1.D0, so we don't check it. */
for (i__ = 2; i__ <= 3; ++i__) {
if (axis[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 : s_rnge("axis",
i__1, "nearpt_", (ftnlen)818)] > toobig) {
setmsg_("Ratio of length of axis #* to length of axis #* is *; t"
"his value may cause numeric overflow.", (ftnlen)92);
errint_("*", &iorder[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 :
s_rnge("iorder", i__1, "nearpt_", (ftnlen)823)], (ftnlen)
1);
errint_("*", iorder, (ftnlen)1);
errdp_("*", &axis[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 :
s_rnge("axis", i__1, "nearpt_", (ftnlen)825)], (ftnlen)1);
sigerr_("SPICE(BADAXISLENGTH)", (ftnlen)20);
chkout_("NEARPT", (ftnlen)6);
return 0;
}
}
/* We also must limit the size of the products */
/* AXIS(I)*POINT(I), I = 1, 3 */
/* We can safely check these by comparing the products of */
/* the square roots of the factors to TOOBIG. */
for (i__ = 1; i__ <= 3; ++i__) {
prodct = sqrt(axis[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 : s_rnge(
"axis", i__1, "nearpt_", (ftnlen)844)]) * sqrt((d__1 = point[(
i__2 = i__ - 1) < 3 && 0 <= i__2 ? i__2 : s_rnge("point",
i__2, "nearpt_", (ftnlen)844)], abs(d__1)));
if (prodct > toobig) {
setmsg_("Product of length of scaled axis #* and size of corresp"
"onding scaled component of POSITN is > *; these values m"
"ay cause numeric overflow.", (ftnlen)137);
errint_("*", &iorder[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 :
s_rnge("iorder", i__1, "nearpt_", (ftnlen)852)], (ftnlen)
1);
d__1 = pow_dd(&toobig, &c_b36);
errdp_("*", &d__1, (ftnlen)1);
sigerr_("SPICE(INPUTSTOOLARGE)", (ftnlen)21);
chkout_("NEARPT", (ftnlen)6);
return 0;
}
}
/* Compute the squared lengths of the scaled axes. */
axisqr[0] = axis[0] * axis[0];
axisqr[1] = axis[1] * axis[1];
axisqr[2] = axis[2] * axis[2];
/* We will need to "solve" for the NEARPT at least 3 times. */
/* SOLUTN is the counter that keeps track of how many times */
/* we have actually solved for a near point. SOLVNG indicates */
/* whether we should continue solving for NEARPT. */
snglpt = 4;
solutn = 1;
solvng = TRUE_;
while(solvng) {
/* Mathematical solution of the lambda equation. */
/* ================================================================ */
/* ---------------------------------------------------------------- */
/* Make a stab at solving the mathematical problem of finding the */
/* near point. In other words, solve the lambda equation. */
/* Avoiding Numerical difficulties */
/* ------------------------------- */
/* First make a copy of POINT, then to avoid numerical */
/* difficulties later on, we will assume that any component of */
/* POINT that is not sufficiently different from zero to */
/* contribute to an addition to the corresponding component */
/* of AXIS, is in fact zero. */
vequ_(point, copy);
for (i__ = 1; i__ <= 3; ++i__) {
if (point[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 : s_rnge("poi"
"nt", i__1, "nearpt_", (ftnlen)903)] * .5 + axis[(i__2 =
i__ - 1) < 3 && 0 <= i__2 ? i__2 : s_rnge("axis", i__2,
"nearpt_", (ftnlen)903)] == axis[(i__3 = i__ - 1) < 3 &&
0 <= i__3 ? i__3 : s_rnge("axis", i__3, "nearpt_", (
ftnlen)903)] || point[(i__4 = i__ - 1) < 3 && 0 <= i__4 ?
i__4 : s_rnge("point", i__4, "nearpt_", (ftnlen)903)] *
.5 - axis[(i__5 = i__ - 1) < 3 && 0 <= i__5 ? i__5 :
s_rnge("axis", i__5, "nearpt_", (ftnlen)903)] == -axis[(
i__6 = i__ - 1) < 3 && 0 <= i__6 ? i__6 : s_rnge("axis",
i__6, "nearpt_", (ftnlen)903)]) {
point[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 : s_rnge("poi"
"nt", i__1, "nearpt_", (ftnlen)906)] = 0.;
}
}
/* OK. Next we set up the logical that indicates whether */
/* the current point is inside the ellipsoid. */
inside = FALSE_;
/* Bracketing the root of the lambda equation. */
/* ------------------------------------------- */
/* Let (x,y,z) stand for (POINT(1), POINT(2), POINT(3)) and */
/* let (a,b,c) stand for (AXIS(1), AXIS(2), AXIS(3)). */
/* The main step in finding the near point is to find the */
/* root of the lambda equation: */
/* 2 2 2 */
/* x y z */
/* 0 = --------------- + ---------------- + --------------- - 1 */
/* 2 2 2 */
/* (a + lambda/a) ( b + lambda/b) (c + lambda/c) */
/* We let Q(lambda) be the right hand side of this equation. */
/* To find the roots of the equation we determine */
/* values of lambda that make Q greater than 0 and less than 0. */
/* An obvious value to check is lambda = 0. */
/* Computing 2nd power */
d__1 = point[0] / axis[0];
/* Computing 2nd power */
d__2 = point[1] / axis[1];
/* Computing 2nd power */
d__3 = point[2] / axis[2];
q = d__1 * d__1 + d__2 * d__2 + d__3 * d__3 - 1.;
/* On the first solution pass, we will determine the sign of */
/* the altitude of the input POSITN */
if (solutn == 1) {
if (q >= 0.) {
sign = 1.;
} else {
sign = -1.;
}
}
/* OK. Now for the stuff we will have to do on every solution */
/* pass. */
/* Below, LOWER and UPPER are the bounds on our independent */
/* variable LAMBDA. QLOWER and QUPPER are the values of Q */
/* evaluated at LOWER and UPPER, respectively. The root we */
/* seek lies in the interval */
/* [ LOWER, UPPER ] */
/* At all points in the algorithm, we have, since Q is a */
/* decreasing function to the right of the first non-removable */
/* singularity, */
/* QLOWER > 0 */
/* - */
/* QUPPER < 0 */
/* - */
/* We'll use bracketing to ensure that round-off errors don't */
/* violate these inequalities. */
/* The logical flag INSIDE indicates whether the point is */
/* strictly inside the interior of the ellipsoid. Points on the */
/* surface are not considered to be inside. */
if (q == 0.) {
/* In this case the point is already on the ellipsoid */
/* (pretty lucky eh?) We simply set our bracketing values, */
/* QLOWER and QUPPER, to zero so that that bisection */
/* loop won't ever get executed. */
qlower = 0.;
qupper = 0.;
lower = 0.;
upper = 0.;
lambda = 0.;
inside = FALSE_;
} else if (q > 0.) {
/* The input point is outside the ellipsoid (we expect that */
/* this is the usual case). We want to choose our lower */
/* bracketing value so that the bracketing values for lambda */
/* aren't too far apart. So we just make sure that the largest */
/* term of the expression for Q isn't bigger than 4. */
for (i__ = 1; i__ <= 3; ++i__) {
tlambd[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 : s_rnge(
"tlambd", i__1, "nearpt_", (ftnlen)1011)] = ((d__1 =
point[(i__2 = i__ - 1) < 3 && 0 <= i__2 ? i__2 :
s_rnge("point", i__2, "nearpt_", (ftnlen)1011)], abs(
d__1)) * .5 - axis[(i__3 = i__ - 1) < 3 && 0 <= i__3 ?
i__3 : s_rnge("axis", i__3, "nearpt_", (ftnlen)1011)]
) * axis[(i__4 = i__ - 1) < 3 && 0 <= i__4 ? i__4 :
s_rnge("axis", i__4, "nearpt_", (ftnlen)1011)];
}
/* Computing MAX */
d__1 = max(0.,tlambd[0]), d__1 = max(d__1,tlambd[1]);
lower = max(d__1,tlambd[2]);
/* Choose the next value of lambda so that the largest term */
/* of Q will be no more than 1/4. */
/* Computing MAX */
d__4 = (d__1 = axis[0] * point[0], abs(d__1)), d__5 = (d__2 =
axis[1] * point[1], abs(d__2)), d__4 = max(d__4,d__5),
d__5 = (d__3 = axis[2] * point[2], abs(d__3));
upper = max(d__4,d__5) * 2.;
lambda = upper;
inside = FALSE_;
} else {
/* In this case the point POSITN is inside the ellipsoid. */
inside = TRUE_;
/* This case is a bit of a nuisance. To solve the lambda */
/* equation we have to find upper and lower bounds on */
/* lambda such that one makes Q greater than 0, the other */
/* makes Q less than 0. Once the root has been bracketed */
/* in this way it is a straightforward problem to find */
/* the value of LAMBDA that is closest to the root we */
/* seek. We already know that for LAMBDA = 0, Q is negative. */
/* So we only need to find a value of LAMBDA that makes */
/* Q positive. But... the expression for Q has singularities */
/* at LAMBDA = -a**2, -b**2, and -c**2. */
/* These singularities are not necessarily to be avoided. */
/* If the numerator of one of the terms for Q is zero, we */
/* can simply compute Q ignoring that particular term. We */
/* say that a singularity corresponding to a term whose */
/* numerator is zero is a viable singularity. By being */
/* careful in our computation of Q, we can assign LAMBDA to */
/* the value of the singularity. A singularity that is not */
/* viable is called a true singularity. */
/* By choosing LAMBDA just slightly greater than the largest */
/* true singularity, we can bracket the root we seek. */
/* First we must decide which singularity is the first true */
/* one. */
snglpt = 4;
for (i__ = 3; i__ >= 1; --i__) {
if (point[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 : s_rnge(
"point", i__1, "nearpt_", (ftnlen)1065)] != 0.) {
snglpt = i__;
}
}
/* If there is a singular point, compute LAMBDA so that the */
/* largest term of Q is equal to 4. */
if (snglpt <= 3) {
for (i__ = 1; i__ <= 3; ++i__) {
if (point[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 :
s_rnge("point", i__1, "nearpt_", (ftnlen)1079)] ==
0.) {
tlambd[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 :
s_rnge("tlambd", i__1, "nearpt_", (ftnlen)
1080)] = -axisqr[2];
} else {
tlambd[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 :
s_rnge("tlambd", i__1, "nearpt_", (ftnlen)
1082)] = axis[(i__2 = i__ - 1) < 3 && 0 <=
i__2 ? i__2 : s_rnge("axis", i__2, "nearpt_",
(ftnlen)1082)] * ((d__1 = point[(i__3 = i__ -
1) < 3 && 0 <= i__3 ? i__3 : s_rnge("point",
i__3, "nearpt_", (ftnlen)1082)], abs(d__1)) *
.5 - axis[(i__4 = i__ - 1) < 3 && 0 <= i__4 ?
i__4 : s_rnge("axis", i__4, "nearpt_", (
ftnlen)1082)]);
}
}
/* Computing MAX */
d__1 = max(tlambd[0],tlambd[1]);
lambda = max(d__1,tlambd[2]);
lower = lambda;
upper = max(lower,0.);
} else {
/* The point must be at the origin. In this case */
/* we know where the closest point is. WE DON'T have */
/* to compute anything. It's just at the end of the */
/* shortest semi-major axis. However, since we */
/* may have done some rounding off, we will make */
/* sure that we pick the side of the shortest axis */
/* that has the same sign as COPY(1). */
/* We are going to be a bit sneaky here. We know */
/* where the closest point is so we are going to */
/* simply make POINT and COPY equal to that point */
/* and set the upper and lower bracketing bounds */
/* to zero so that we won't have to deal with any */
/* special cases later on. */
if (copy[0] < 0.) {
point[0] = -axis[0];
copy[0] = -axis[0];
} else {
point[0] = axis[0];
copy[0] = axis[0];
}
copy[1] = 0.;
copy[2] = 0.;
upper = 0.;
lower = 0.;
lambda = 0.;
q = 0.;
inside = FALSE_;
}
}
/* OK. Now compute the value of Q at the two bracketing */
/* values of LAMBDA. */
for (i__ = 1; i__ <= 3; ++i__) {
if (point[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 : s_rnge("poi"
"nt", i__1, "nearpt_", (ftnlen)1139)] == 0.) {
term[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 : s_rnge("term",
i__1, "nearpt_", (ftnlen)1141)] = 0.;
} else {
/* We have to be a bit careful for points inside the */
/* ellipsoid. The denominator of the factor we are going to */
/* compute is ( AXIS + LAMBDA/AXIS ). Numerically this may */
/* be too close to zero for us to actually divide POINT by */
/* it. However, since our solution algorithm for lambda */
/* does not depend upon the differentiability of Q---in */
/* fact it depends only on Q having the correct sign---we */
/* can simply truncate its individual terms when we are in */
/* danger of division overflows. */
denom = axis[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 :
s_rnge("axis", i__1, "nearpt_", (ftnlen)1155)] +
lambda / axis[(i__2 = i__ - 1) < 3 && 0 <= i__2 ?
i__2 : s_rnge("axis", i__2, "nearpt_", (ftnlen)1155)];
trim = (d__1 = point[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1
: s_rnge("point", i__1, "nearpt_", (ftnlen)1157)],
abs(d__1)) * .5 > denom;
if (inside && trim) {
factor = 2.;
} else {
/* We don't expect DENOM to be zero here, but we'll */
/* check anyway. */
if (denom == 0.) {
setmsg_("AXIS(#) + LAMBDA/AXIS(#) is zero.", (ftnlen)
33);
errint_("#", &i__, (ftnlen)1);
errint_("#", &i__, (ftnlen)1);
sigerr_("SPICE(BUG)", (ftnlen)10);
chkout_("NEARPT", (ftnlen)6);
return 0;
}
factor = point[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 :
s_rnge("point", i__1, "nearpt_", (ftnlen)1179)] /
denom;
}
term[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 : s_rnge("term",
i__1, "nearpt_", (ftnlen)1183)] = factor * factor;
}
}
if (! inside) {
qlower = q;
qupper = term[0] + term[1] + term[2] - 1.;
} else {
qupper = q;
qlower = term[0] + term[1] + term[2] - 1.;
}
/* Bracket QLOWER and QUPPER. */
qlower = max(0.,qlower);
qupper = min(0.,qupper);
lambda = upper;
q = qupper;
/* Refining the estimate of lambda */
/* ------------------------------- */
/* Now find the root of Q by bisection. */
itr = 0;
/* Throughout this loop we'll use TOUCHD to avoid logic problems */
/* that may be caused by extended precision register usage by */
/* some compilers. */
for(;;) { /* while(complicated condition) */
d__1 = upper - lower;
if (!(touchd_(&d__1) > 0.))
break;
++itr;
if (itr > 2048) {
setmsg_("Iteration limit # exceeded in NEARPT. A, B, C = # #"
" #; POSITN = ( #, #, # ). LOWER = #; UPPER = #; UPPE"
"R-LOWER = #. Solution pass number = #. This event s"
"hould never occur. Contact NAIF.", (ftnlen)187);
errint_("#", &c__2048, (ftnlen)1);
errdp_("#", a, (ftnlen)1);
errdp_("#", b, (ftnlen)1);
errdp_("#", c__, (ftnlen)1);
errdp_("#", positn, (ftnlen)1);
errdp_("#", &positn[1], (ftnlen)1);
errdp_("#", &positn[2], (ftnlen)1);
errdp_("#", &lower, (ftnlen)1);
errdp_("#", &upper, (ftnlen)1);
d__1 = upper - lower;
errdp_("#", &d__1, (ftnlen)1);
sigerr_("SPICE(BUG)", (ftnlen)10);
chkout_("NEARPT", (ftnlen)6);
return 0;
}
/* Bracket LOWER, QLOWER, and QUPPER. */
lower = min(lower,upper);
qlower = max(0.,qlower);
qupper = min(0.,qupper);
/* Depending upon how Q compares with Q at the */
/* bracketing endpoints we adjust the endpoints */
/* of the bracketing interval */
if (q == 0.) {
/* We've found the root. */
lower = lambda;
upper = lambda;
} else {
if (q < 0.) {
upper = lambda;
qupper = q;
} else {
/* We have Q > 0 */
lower = lambda;
qlower = q;
}
/* Update LAMBDA. */
lambda = lower * .5 + upper * .5;
/* It's quite possible as we get close to the root for Q */
/* that round off errors in the computation of the next */
/* value of LAMBDA will push it outside of the current */
/* bracketing interval. Force it back in to the current */
/* interval. */
lambda = brcktd_(&lambda, &lower, &upper);
}
/* At this point, it's guaranteed that */
/* LOWER < LAMBDA < UPPER */
/* - - */
/* If we didn't find a root, we've set LAMBDA to the midpoint */
/* of the previous values of LOWER and UPPER, and we've moved */
/* either LOWER or UPPER to the old value of LAMBDA, thereby */
/* halving the distance between LOWER and UPPER. */
/* If we are still at an endpoint, we might as well cash in */
/* our chips. We aren't going to be able to get away from the */
/* endpoints. Set LOWER and UPPER equal so that the loop will */
/* finally terminate. */
if (approx_(&lambda, &lower, &c_b108) || approx_(&lambda, &upper,
&c_b108)) {
/* Make the decision as to which way to push */
/* the boundaries, by selecting that endpoint */
/* at which Q is closest to zero. */
if (abs(qlower) < abs(qupper)) {
upper = lower;
} else {
lower = upper;
}
/* Since LOWER is equal to UPPER, the loop will terminate. */
}
/* If LOWER and UPPER aren't the same, we compute the */
/* value of Q at our new guess for LAMBDA. */
d__1 = upper - lower;
if (touchd_(&d__1) > 0.) {
for (i__ = 1; i__ <= 3; ++i__) {
if (point[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 :
s_rnge("point", i__1, "nearpt_", (ftnlen)1337)] ==
0.) {
term[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 :
s_rnge("term", i__1, "nearpt_", (ftnlen)1339)]
= 0.;
} else {
denom = axis[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1
: s_rnge("axis", i__1, "nearpt_", (ftnlen)
1343)] + lambda / axis[(i__2 = i__ - 1) < 3 &&
0 <= i__2 ? i__2 : s_rnge("axis", i__2,
"nearpt_", (ftnlen)1343)];
trim = (d__1 = point[(i__1 = i__ - 1) < 3 && 0 <=
i__1 ? i__1 : s_rnge("point", i__1, "nearpt_",
(ftnlen)1345)], abs(d__1)) * .5 > denom;
if (inside && trim) {
factor = 2.;
} else {
/* We don't expect DENOM to be zero here, but we'll */
/* check anyway. */
if (denom == 0.) {
setmsg_("AXIS(#) + LAMBDA/AXIS(#) is zero.", (
ftnlen)33);
errint_("#", &i__, (ftnlen)1);
errint_("#", &i__, (ftnlen)1);
sigerr_("SPICE(BUG)", (ftnlen)10);
chkout_("NEARPT", (ftnlen)6);
return 0;
}
factor = point[(i__1 = i__ - 1) < 3 && 0 <= i__1 ?
i__1 : s_rnge("point", i__1, "nearpt_", (
ftnlen)1368)] / denom;
}
term[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 :
s_rnge("term", i__1, "nearpt_", (ftnlen)1372)]
= factor * factor;
}
}
d__1 = term[0] + term[1] + term[2] - 1.;
q = touchd_(&d__1);
}
/* Q(LAMBDA) has been set unless we've already found */
/* a solution. */
/* Loop back through the bracketing refinement code. */
}
/* Now we have LAMBDA, compute the nearest point based upon */
/* this value. */
lambda = lower;
for (i__ = 1; i__ <= 3; ++i__) {
if (point[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 : s_rnge("poi"
"nt", i__1, "nearpt_", (ftnlen)1398)] == 0.) {
spoint[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 : s_rnge(
"spoint", i__1, "nearpt_", (ftnlen)1400)] = 0.;
} else {
denom = lambda / axisqr[(i__1 = i__ - 1) < 3 && 0 <= i__1 ?
i__1 : s_rnge("axisqr", i__1, "nearpt_", (ftnlen)1404)
] + 1.;
/* We don't expect that DENOM will be non-positive, but we */
/* check for this case anyway. */
if (denom <= 0.) {
setmsg_("Denominator in expression for SPOINT(#) is #.", (
ftnlen)45);
errint_("#", &i__, (ftnlen)1);
errdp_("#", &denom, (ftnlen)1);
sigerr_("SPICE(BUG)", (ftnlen)10);
chkout_("NEARPT", (ftnlen)6);
return 0;
}
spoint[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 : s_rnge(
"spoint", i__1, "nearpt_", (ftnlen)1421)] = copy[(
i__2 = i__ - 1) < 3 && 0 <= i__2 ? i__2 : s_rnge(
"copy", i__2, "nearpt_", (ftnlen)1421)] / denom;
}
}
/* Handling points on the central plane. */
/* ------------------------------------- */
/* I suppose you thought you were done at this point. Not */
/* necessarily. If POINT is INSIDE the ellipsoid and happens to */
/* lie in the Y-Z plane, there is a possibility (perhaps even */
/* likelihood) that the nearest point on the ellipsoid is NOT in */
/* the Y-Z plane. we must consider this possibility next. */
if (inside && (snglpt == 2 || snglpt == 3)) {
/* There are two ways to get here. SNGLPT = 2 or SNGLPT = 3. */
/* Fortunately these two cases can be handled simultaneously by */
/* code. However, they are most easily understood if explained */
/* separately. */
/* Case 1. SNGLPT = 2 */
/* The input to the lambda solution POINT lies in the Y-Z plane. */
/* We have already detected one critical point of the */
/* distance function to POINT restricted to the ellipsoid. */
/* This point also lies in the Y-Z plane. However, when */
/* POINT lies on the Y-Z plane close to the center of the */
/* ellipsoid, there may be a point that is nearest that does */
/* not lie in the Y-Z plane. Assuming the existence of such a */
/* point, (x,y,z) it must satisfy the equations */
/* lambda*x */
/* x + -------- = POINT(1) = 0 */
/* a*a */
/* lambda*y */
/* y + -------- = POINT(2) */
/* b*b */
/* lambda*z */
/* z + -------- = POINT(3) */
/* c*c */
/* Since we are assuming that this undetected solution (x,y,z) */
/* does not have x equal to 0, it must be the case that */
/* lambda = -a*a. */
/* Because of this, we must have */
/* y = POINT(2) / ( 1 - (a**2/b**2) ) */
/* z = POINT(3) / ( 1 - (a**2/c**2) ) */
/* The value of x is obtained by forcing */
/* (x/a)**2 + (y/b)**2 + (z/c)**2 = 1. */
/* This assumes of course that a and b are not equal. If a and */
/* b are the same, then since POINT(2) is not zero, the */
/* solution we found above by deflating the original ellipsoid */
/* will find the near point. */
/* (If a and b are equal, the ellipsoid deflates to a */
/* segment on the z-axis when lambda = -a**2. Since */
/* POINT(2) is not zero, the deflating ellipsoid must pass */
/* through POINT before it collapses to a segment.) */
/* Case 2. SNGLPT = 3 */
/* The input to the lambda solution POINT lies on the Z-axis. */
/* The solution obtained in the generic case above will */
/* locate the critical point of the distance function */
/* that lies on the Z. However, there will also be */
/* critical points in the X-Z plane and Y-Z plane. The point */
/* in the X-Z plane is the one to examine. Why? We are looking */
/* for the point on the ellipsoid closest to POINT. It must */
/* lie in one of these two planes. But the ellipse of */
/* intersection with the X-Z plane fits inside the ellipse */
/* of intersection with the Y-Z plane. Therefore the closest */
/* point on the Y-Z ellipse must be at a greater distance than */
/* the closest point on the X-Z ellipse. Thus, in solving */
/* the equations */
/* lambda*x */
/* x + -------- = POINT(1) = 0 */
/* a*a */
/* lambda*y */
/* y + -------- = POINT(2) = 0 */
/* b*b */
/* lambda*z */
/* z + -------- = POINT(3) */
/* c*c */
/* We have */
/* lambda = -a*a, */
/* y = 0, */
/* z = POINT(3) / ( 1 - (a**2/c**2) ) */
/* The value of x is obtained by forcing */
/* (x/a)**2 + (y/b)**2 + (z/c)**2 = 1. */
/* This assumes that a and c are not equal. If */
/* a and c are the same, then the solution we found above */
/* by deflating the original ellipsoid, will find the */
/* near point. */
/* ( If a = c, then the input ellipsoid is a sphere. */
/* The ellipsoid will deflate to the center of the */
/* sphere. Since our point is NOT at the center, */
/* the deflating sphere will cross through */
/* (x,y,z) before it collapses to a point ) */
/* We begin by assuming this extra point doesn't exist. */
extra = FALSE_;
/* Next let's note a few simple tests we can apply to */
/* eliminate searching for an extra point. */
/* First of all the smallest axis must be different from */
/* the axis associated with the first true singularity. */
/* Next, whatever point we find, it must be true that */
/* |y| < b, |z| < c */
/* because of the condition on the absolute values, we must */
/* have: */
/* | POINT(2) | <= b - a*(a/b) */
/* | POINT(3) | <= c - a*(a/c) */
if (axis[0] != axis[(i__1 = snglpt - 1) < 3 && 0 <= i__1 ? i__1 :
s_rnge("axis", i__1, "nearpt_", (ftnlen)1575)] && abs(
point[1]) <= axis[1] - axisqr[0] / axis[1] && abs(point[2]
) <= axis[2] - axisqr[0] / axis[2]) {
/* What happens next depends on whether the ellipsoid is */
/* prolate or triaxial. */
if (axis[0] == axis[1]) {
/* This is the prolate case; we need to compute the */
/* z component of the solution. */
denom3 = 1. - axisqr[0] / axisqr[2];
if (denom3 > 0.) {
epoint[1] = 0.;
/* Concerning the safety of the following division: */
/* - A divide-by-zero check has been done above. */
/* - The numerator can be squared without exceeding */
/* DPMAX(). This was checked near the start of the */
/* routine. */
/* - The denominator was computed as the difference */
/* of 1.D0 and another number. The smallest */
/* possible magnitude of a non-zero value of the */
/* denominator is roughly 1.D-16, assuming IEEE */
/* double precision numeric representation. */
epoint[2] = point[2] / denom3;
/* See if these components can even be on the */
/* ellipsoid... */
/* Computing 2nd power */
d__1 = epoint[1] / axis[1];
/* Computing 2nd power */
d__2 = epoint[2] / axis[2];
temp = 1. - d__1 * d__1 - d__2 * d__2;
if (temp > 0.) {
/* ...and compute the x component of the point. */
epoint[0] = axis[0] * sqrt((max(0.,temp)));
extra = TRUE_;
}
}
} else {
/* This is the triaxial case. */
/* Compute the y and z components (2 and 3) of the extra */
/* point. */
denom2 = 1. - axisqr[0] / axisqr[1];
denom3 = 1. - axisqr[0] / axisqr[2];
/* We expect DENOM2 and DENOM3 will always be positive. */
/* Nonetheless, we check to make sure this is the case. */
/* If not, we don't compute the extra point. */
if (denom2 > 0. && denom3 > 0.) {
/* Concerning the safety of the following divisions: */
/* - Divide-by-zero checks have been done above. */
/* - The numerators can be squared without exceeding */
/* DPMAX(). This was checked near the start of the */
/* routine. */
/* - Each denominator was computed as the difference */
/* of 1.D0 and another number. The smallest */
/* possible magnitude of a non-zero value of */
/* either denominator is roughly 1.D-16, assuming */
/* IEEE double precision numeric representation. */
epoint[1] = point[1] / denom2;
epoint[2] = point[2] / denom3;
/* See if these components can even be on the */
/* ellipsoid... */
/* Computing 2nd power */
d__1 = epoint[1] / axis[1];
/* Computing 2nd power */
d__2 = epoint[2] / axis[2];
temp = 1. - d__1 * d__1 - d__2 * d__2;
if (temp > 0.) {
/* ...and compute the x component of the point. */
epoint[0] = axis[0] * sqrt(temp);
extra = TRUE_;
}
}
}
}
/* Ok. If an extra point is possible, check and see if it */
/* is the one we are searching for. */
if (extra) {
if (vdist_(epoint, point) < vdist_(spoint, point)) {
vequ_(epoint, spoint);
}
}
}
/* Decisions and initializations for sharpening the solution. */
/* ================================================================ */
/* ---------------------------------------------------------------- */
if (solutn == 1) {
/* The first solution for the nearest point may not be */
/* very close to being on the ellipsoid. To */
/* take care of this case, we next find the point on the */
/* ellipsoid, closest to our first solution point. */
/* (Ideally the normal line at this second point should */
/* contain both the current solution point and the */
/* original point). */
vequ_(spoint, point);
vequ_(spoint, bestpt);
bestht = vdist_(bestpt, orignl);
} else if (solutn == 2) {
/* The current solution point will be very close to lying */
/* on the ellipsoid. However, the normal at this solution */
/* may not actually point toward the input point. */
/* With the current solution we can predict */
/* the location of the input point. The difference between */
/* this predicted point and the actual point can be used */
/* to sharpen our estimate of the solution. */
/* The sharpening is performed by */
/* 1) Compute the vector ERR that gives the difference */
/* between the input point (POSITN) and the point */
/* computed using the solution point, normal and */
/* altitude. */
/* 2) Find the component of ERR that is orthogonal to the */
/* normal at the current solution point. If the point */
/* is outside the ellipsoid, scale this component to */
/* the approximate scale of the near point. We use */
/* the scale factor */
/* ||near point|| / ||input point|| */
/* Call this scaled component ERRP. */
/* 3) Translate the solution point by ERRP to get POINT. */
/* 4) Find the point on the ellipsoid closest to POINT. */
/* (step 4 is handled by the solution loop above). */
/* First we need to compute the altitude */
height = sign * vdist_(spoint, orignl);
/* Next compute the difference between the input point and */
/* the one we get by moving out along the normal at our */
/* solution point by the computed altitude. */
surfnm_(axis, &axis[1], &axis[2], spoint, normal);
for (i__ = 1; i__ <= 3; ++i__) {
err[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 : s_rnge("err",
i__1, "nearpt_", (ftnlen)1774)] = orignl[(i__2 = i__
- 1) < 3 && 0 <= i__2 ? i__2 : s_rnge("orignl", i__2,
"nearpt_", (ftnlen)1774)] - spoint[(i__3 = i__ - 1) <
3 && 0 <= i__3 ? i__3 : s_rnge("spoint", i__3, "near"
"pt_", (ftnlen)1774)] - height * normal[(i__4 = i__ -
1) < 3 && 0 <= i__4 ? i__4 : s_rnge("normal", i__4,
"nearpt_", (ftnlen)1774)];
}
/* Find the component of the error vector that is */
/* perpendicular to the normal, and shift our solution */
/* point by this component. */
vperp_(err, normal, errp);
/* The sign of the original point's altitude tells */
/* us whether the point is outside the ellipsoid. */
if (sign >= 0.) {
/* Scale the transverse component down to the local radius */
/* of the surface point. */
if (pnorm == 0.) {
/* Since the point is outside of the scaled ellipsoid, */
/* we don't expect to arrive here. This is a backstop */
/* check. */
setmsg_("Norm of scaled point is 0. POSITN = ( #, #, # )",
(ftnlen)47);
errdp_("#", positn, (ftnlen)1);
errdp_("#", &positn[1], (ftnlen)1);
errdp_("#", &positn[2], (ftnlen)1);
sigerr_("SPICE(BUG)", (ftnlen)10);
chkout_("NEARPT", (ftnlen)6);
return 0;
}
d__1 = vnorm_(spoint) / pnorm;
vsclip_(&d__1, errp);
}
vadd_(spoint, errp, point);
olderr = vnorm_(err);
bestht = height;
/* Finally store the current solution point, so that if */
/* this sharpening doesn't improve our estimate of the */
/* near point, we can just return our current best guess. */
vequ_(spoint, bestpt);
} else if (solutn > 2) {
/* This branch exists for the purpose of testing our */
/* "sharpened" solution and setting up for another sharpening */
/* pass. */
/* We have already stored our best guess so far in BESTPT and */
/* the vector ERR is the difference */
/* ORIGNL - ( BESTPT + BESTHT*NORMAL ) */
/* We have just computed a new candidate "best" near point. */
/* SPOINT. */
/* If the error vector */
/* ORIGNL - ( SPOINT + HEIGHT*NORMAL) */
/* is shorter than our previous error, we will make SPOINT */
/* our best guess and try to sharpen our estimate again. */
/* If our sharpening method hasn't improved things, we just */
/* call it quits and go with our current best guess. */
/* First compute the altitude, */
height = sign * vdist_(spoint, orignl);
/* ... compute the difference */
/* ORIGNL - SPOINT - HEIGHT*NORMAL, */
surfnm_(axis, &axis[1], &axis[2], spoint, normal);
for (i__ = 1; i__ <= 3; ++i__) {
err[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 : s_rnge("err",
i__1, "nearpt_", (ftnlen)1867)] = orignl[(i__2 = i__
- 1) < 3 && 0 <= i__2 ? i__2 : s_rnge("orignl", i__2,
"nearpt_", (ftnlen)1867)] - spoint[(i__3 = i__ - 1) <
3 && 0 <= i__3 ? i__3 : s_rnge("spoint", i__3, "near"
"pt_", (ftnlen)1867)] - height * normal[(i__4 = i__ -
1) < 3 && 0 <= i__4 ? i__4 : s_rnge("normal", i__4,
"nearpt_", (ftnlen)1867)];
}
/* ...and determine the magnitude of the error due to our */
/* sharpened estimate. */
newerr = vnorm_(err);
/* If the sharpened estimate yields a smaller error ... */
if (newerr < olderr) {
/* ...our current value of SPOINT becomes our new */
/* best point and the current altitude becomes our */
/* new altitude. */
olderr = newerr;
bestht = height;
vequ_(spoint, bestpt);
/* Next, if we haven't passed the limit on the number of */
/* iterations allowed we prepare the initial point for our */
/* "sharpening" estimate. */
if (solutn <= 6) {
vperp_(err, normal, errp);
/* The sign of the original point's altitude tells */
/* us whether the point is outside the ellipsoid. */
if (sign >= 0.) {
/* Scale the transverse component down to the local */
/* radius of the surface point. */
if (pnorm == 0.) {
/* Since the point is outside of the scaled */
/* ellipsoid, we don't expect to arrive here. */
/* This is a backstop check. */
setmsg_("Norm of scaled point is 0. POSITN = ( #"
", #, # )", (ftnlen)47);
errdp_("#", positn, (ftnlen)1);
errdp_("#", &positn[1], (ftnlen)1);
errdp_("#", &positn[2], (ftnlen)1);
sigerr_("SPICE(BUG)", (ftnlen)10);
chkout_("NEARPT", (ftnlen)6);
return 0;
}
d__1 = vnorm_(spoint) / pnorm;
vsclip_(&d__1, errp);
}
vadd_(spoint, errp, point);
}
} else {
/* If things didn't get better, there is no point in */
/* going on. Just set the SOLVNG flag to .FALSE. to */
/* terminate the outer loop. */
solvng = FALSE_;
}
}
/* Increment the solution counter so that eventually this */
/* loop will terminate. */
++solutn;
solvng = solvng && solutn <= 6;
}
/* Clean up. */
/* ================================================================== */
/* ------------------------------------------------------------------ */
/* Re-scale and re-order the components of our solution point. Scale */
/* and copy the value of BESTHT into the output argument. */
d__1 = 1. / scale;
vsclip_(&d__1, bestpt);
for (i__ = 1; i__ <= 3; ++i__) {
npoint[(i__2 = iorder[(i__1 = i__ - 1) < 3 && 0 <= i__1 ? i__1 :
s_rnge("iorder", i__1, "nearpt_", (ftnlen)1966)] - 1) < 3 &&
0 <= i__2 ? i__2 : s_rnge("npoint", i__2, "nearpt_", (ftnlen)
1966)] = bestpt[(i__3 = i__ - 1) < 3 && 0 <= i__3 ? i__3 :
s_rnge("bestpt", i__3, "nearpt_", (ftnlen)1966)];
}
*alt = bestht / scale;
chkout_("NEARPT", (ftnlen)6);
return 0;
} /* nearpt_ */
| gpl-3.0 |
ppelleti/gnutls | tests/suite/ecore/src/lib/eina_lalloc.c | 9 | 3985 | /* EINA - EFL data type library
* Copyright (C) 2007-2008 Jorge Luis Zapata Muga
*
* This 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.
*
* 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 library;
* if not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <stdlib.h>
#include "eina_config.h"
#include "eina_private.h"
/* undefs EINA_ARG_NONULL() so NULL checks are not compiled out! */
#include "eina_safety_checks.h"
#include "eina_lalloc.h"
/*============================================================================*
* Local *
*============================================================================*/
/**
* @cond LOCAL
*/
struct _Eina_Lalloc
{
void *data;
int num_allocated;
int num_elements;
int acc;
Eina_Lalloc_Alloc alloc_cb;
Eina_Lalloc_Free free_cb;
};
/**
* @endcond
*/
/*============================================================================*
* Global *
*============================================================================*/
/*============================================================================*
* API *
*============================================================================*/
/**
* @addtogroup Eina_Lalloc_Group Lazy allocator
*
* @{
*/
EAPI Eina_Lalloc *eina_lalloc_new(void *data,
Eina_Lalloc_Alloc alloc_cb,
Eina_Lalloc_Free free_cb,
int num_init)
{
Eina_Lalloc *a;
EINA_SAFETY_ON_NULL_RETURN_VAL(alloc_cb, NULL);
EINA_SAFETY_ON_NULL_RETURN_VAL(free_cb, NULL);
a = calloc(1, sizeof(Eina_Lalloc));
a->data = data;
a->alloc_cb = alloc_cb;
a->free_cb = free_cb;
if (num_init > 0)
{
a->num_allocated = num_init;
a->alloc_cb(a->data, a->num_allocated);
}
return a;
}
EAPI void eina_lalloc_free(Eina_Lalloc *a)
{
EINA_SAFETY_ON_NULL_RETURN(a);
EINA_SAFETY_ON_NULL_RETURN(a->free_cb);
a->free_cb(a->data);
free(a);
}
EAPI Eina_Bool eina_lalloc_element_add(Eina_Lalloc *a)
{
EINA_SAFETY_ON_NULL_RETURN_VAL(a, EINA_FALSE);
EINA_SAFETY_ON_NULL_RETURN_VAL(a->alloc_cb, EINA_FALSE);
if (a->num_elements == a->num_allocated)
{
if (a->alloc_cb(a->data, (1 << a->acc)) == EINA_TRUE)
{
a->num_allocated = (1 << a->acc);
a->acc++;
}
else
return EINA_FALSE;
}
a->num_elements++;
return EINA_TRUE;
}
EAPI Eina_Bool eina_lalloc_elements_add(Eina_Lalloc *a, int num)
{
int tmp;
EINA_SAFETY_ON_NULL_RETURN_VAL(a, EINA_FALSE);
EINA_SAFETY_ON_NULL_RETURN_VAL(a->alloc_cb, EINA_FALSE);
tmp = a->num_elements + num;
if (tmp > a->num_allocated)
{
int allocated;
int acc;
allocated = a->num_allocated;
acc = a->acc;
while (tmp > allocated)
{
allocated = (1 << acc);
acc++;
}
if (a->alloc_cb(a->data, allocated) == EINA_TRUE)
{
a->num_allocated = allocated;
a->acc = acc;
}
else
return EINA_FALSE;
}
a->num_elements += num;
return EINA_TRUE;
}
/**
* @}
*/
| gpl-3.0 |
mwcampbell/mpfr | src/dump.c | 10 | 1137 | /* mpfr_dump -- Dump a float to stdout.
Copyright 1999, 2001, 2004, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
Contributed by the AriC and Caramel projects, INRIA.
This file is part of the GNU MPFR Library.
The GNU MPFR 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 3 of the License, or (at your
option) any later version.
The GNU MPFR 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 MPFR Library; see the file COPYING.LESSER. If not, see
http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */
#include "mpfr-impl.h"
void
mpfr_dump (mpfr_srcptr u)
{
mpfr_print_binary(u);
putchar('\n');
}
| gpl-3.0 |
grueni75/GeoDiscoverer | Source/Platform/Target/Android/core/src/main/jni/openssl-1.1.0c/crypto/x509/x509_obj.c | 10 | 5108 | /*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (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 <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/lhash.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
#include <openssl/buffer.h>
#include "internal/x509_int.h"
/*
* Limit to ensure we don't overflow: much greater than
* anything encountered in practice.
*/
#define NAME_ONELINE_MAX (1024 * 1024)
char *X509_NAME_oneline(const X509_NAME *a, char *buf, int len)
{
const X509_NAME_ENTRY *ne;
int i;
int n, lold, l, l1, l2, num, j, type;
const char *s;
char *p;
unsigned char *q;
BUF_MEM *b = NULL;
static const char hex[17] = "0123456789ABCDEF";
int gs_doit[4];
char tmp_buf[80];
#ifdef CHARSET_EBCDIC
unsigned char ebcdic_buf[1024];
#endif
if (buf == NULL) {
if ((b = BUF_MEM_new()) == NULL)
goto err;
if (!BUF_MEM_grow(b, 200))
goto err;
b->data[0] = '\0';
len = 200;
} else if (len == 0) {
return NULL;
}
if (a == NULL) {
if (b) {
buf = b->data;
OPENSSL_free(b);
}
strncpy(buf, "NO X509_NAME", len);
buf[len - 1] = '\0';
return buf;
}
len--; /* space for '\0' */
l = 0;
for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
ne = sk_X509_NAME_ENTRY_value(a->entries, i);
n = OBJ_obj2nid(ne->object);
if ((n == NID_undef) || ((s = OBJ_nid2sn(n)) == NULL)) {
i2t_ASN1_OBJECT(tmp_buf, sizeof(tmp_buf), ne->object);
s = tmp_buf;
}
l1 = strlen(s);
type = ne->value->type;
num = ne->value->length;
if (num > NAME_ONELINE_MAX) {
X509err(X509_F_X509_NAME_ONELINE, X509_R_NAME_TOO_LONG);
goto end;
}
q = ne->value->data;
#ifdef CHARSET_EBCDIC
if (type == V_ASN1_GENERALSTRING ||
type == V_ASN1_VISIBLESTRING ||
type == V_ASN1_PRINTABLESTRING ||
type == V_ASN1_TELETEXSTRING ||
type == V_ASN1_IA5STRING) {
if (num > (int)sizeof(ebcdic_buf))
num = sizeof(ebcdic_buf);
ascii2ebcdic(ebcdic_buf, q, num);
q = ebcdic_buf;
}
#endif
if ((type == V_ASN1_GENERALSTRING) && ((num % 4) == 0)) {
gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 0;
for (j = 0; j < num; j++)
if (q[j] != 0)
gs_doit[j & 3] = 1;
if (gs_doit[0] | gs_doit[1] | gs_doit[2])
gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 1;
else {
gs_doit[0] = gs_doit[1] = gs_doit[2] = 0;
gs_doit[3] = 1;
}
} else
gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 1;
for (l2 = j = 0; j < num; j++) {
if (!gs_doit[j & 3])
continue;
l2++;
#ifndef CHARSET_EBCDIC
if ((q[j] < ' ') || (q[j] > '~'))
l2 += 3;
#else
if ((os_toascii[q[j]] < os_toascii[' ']) ||
(os_toascii[q[j]] > os_toascii['~']))
l2 += 3;
#endif
}
lold = l;
l += 1 + l1 + 1 + l2;
if (l > NAME_ONELINE_MAX) {
X509err(X509_F_X509_NAME_ONELINE, X509_R_NAME_TOO_LONG);
goto end;
}
if (b != NULL) {
if (!BUF_MEM_grow(b, l + 1))
goto err;
p = &(b->data[lold]);
} else if (l > len) {
break;
} else
p = &(buf[lold]);
*(p++) = '/';
memcpy(p, s, (unsigned int)l1);
p += l1;
*(p++) = '=';
#ifndef CHARSET_EBCDIC /* q was assigned above already. */
q = ne->value->data;
#endif
for (j = 0; j < num; j++) {
if (!gs_doit[j & 3])
continue;
#ifndef CHARSET_EBCDIC
n = q[j];
if ((n < ' ') || (n > '~')) {
*(p++) = '\\';
*(p++) = 'x';
*(p++) = hex[(n >> 4) & 0x0f];
*(p++) = hex[n & 0x0f];
} else
*(p++) = n;
#else
n = os_toascii[q[j]];
if ((n < os_toascii[' ']) || (n > os_toascii['~'])) {
*(p++) = '\\';
*(p++) = 'x';
*(p++) = hex[(n >> 4) & 0x0f];
*(p++) = hex[n & 0x0f];
} else
*(p++) = q[j];
#endif
}
*p = '\0';
}
if (b != NULL) {
p = b->data;
OPENSSL_free(b);
} else
p = buf;
if (i == 0)
*p = '\0';
return (p);
err:
X509err(X509_F_X509_NAME_ONELINE, ERR_R_MALLOC_FAILURE);
end:
BUF_MEM_free(b);
return (NULL);
}
| gpl-3.0 |
aagallag/nexmon | utilities/glib/glib/gtranslit.c | 11 | 10598 | /*
* Copyright © 2014 Canonical Limited
*
* This 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 of the licence, or (at your option) any later version.
*
* 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 library; if not, see <http://www.gnu.org/licenses/>.
*
* Author: Ryan Lortie <desrt@desrt.ca>
*/
#include <config.h>
#include "gstrfuncs.h"
#include <glib.h>
#include <locale.h>
#include <stdlib.h>
#include <string.h>
struct mapping_entry
{
guint16 src;
guint16 ascii;
};
struct mapping_range
{
guint16 start;
guint16 length;
};
struct locale_entry
{
guint8 name_offset;
guint8 item_id;
};
#include "gtranslit-data.h"
#define get_src_char(array, encoded, index) ((encoded & 0x8000) ? (array)[((encoded) & 0xfff) + index] : encoded)
#define get_length(encoded) ((encoded & 0x8000) ? ((encoded & 0x7000) >> 12) : 1)
#if G_BYTE_ORDER == G_BIG_ENDIAN
#define get_ascii_item(array, encoded) ((encoded & 0x8000) ? &(array)[(encoded) & 0xfff] : (gpointer) (((char *) &(encoded)) + 1))
#else
#define get_ascii_item(array, encoded) ((encoded & 0x8000) ? &(array)[(encoded) & 0xfff] : (gpointer) &(encoded))
#endif
static const gchar * lookup_in_item (guint item_id,
const gunichar *key,
gint *result_len,
gint *key_consumed);
static gint
compare_mapping_entry (gconstpointer user_data,
gconstpointer data)
{
const struct mapping_entry *entry = data;
const gunichar *key = user_data;
gunichar src_0;
G_STATIC_ASSERT(MAX_KEY_SIZE == 2);
src_0 = get_src_char (src_table, entry->src, 0);
if (key[0] > src_0)
return 1;
else if (key[0] < src_0)
return -1;
if (get_length (entry->src) > 1)
{
gunichar src_1;
src_1 = get_src_char (src_table, entry->src, 1);
if (key[1] > src_1)
return 1;
else if (key[1] < src_1)
return -1;
}
else if (key[1])
return 1;
return 0;
}
static const gchar *
lookup_in_mapping (const struct mapping_entry *mapping,
gint mapping_size,
const gunichar *key,
gint *result_len,
gint *key_consumed)
{
const struct mapping_entry *hit;
hit = bsearch (key, mapping, mapping_size, sizeof (struct mapping_entry), compare_mapping_entry);
if (hit == NULL)
return NULL;
*key_consumed = get_length (hit->src);
*result_len = get_length (hit->ascii);
return get_ascii_item(ascii_table, hit->ascii);
}
static const gchar *
lookup_in_chain (const guint8 *chain,
const gunichar *key,
gint *result_len,
gint *key_consumed)
{
const gchar *result;
while (*chain != 0xff)
{
result = lookup_in_item (*chain, key, result_len, key_consumed);
if (result)
return result;
chain++;
}
return NULL;
}
static const gchar *
lookup_in_item (guint item_id,
const gunichar *key,
gint *result_len,
gint *key_consumed)
{
if (item_id & 0x80)
{
const guint8 *chain = chains_table + chain_starts[item_id & 0x7f];
return lookup_in_chain (chain, key, result_len, key_consumed);
}
else
{
const struct mapping_range *range = &mapping_ranges[item_id];
return lookup_in_mapping (mappings_table + range->start, range->length, key, result_len, key_consumed);
}
}
static gint
compare_locale_entry (gconstpointer user_data,
gconstpointer data)
{
const struct locale_entry *entry = data;
const gchar *key = user_data;
return strcmp (key, &locale_names[entry->name_offset]);
}
static gboolean
lookup_item_id_for_one_locale (const gchar *key,
guint *item_id)
{
const struct locale_entry *hit;
hit = bsearch (key, locale_index, G_N_ELEMENTS (locale_index), sizeof (struct locale_entry), compare_locale_entry);
if (hit == NULL)
return FALSE;
*item_id = hit->item_id;
return TRUE;
}
static guint
lookup_item_id_for_locale (const gchar *locale)
{
gchar key[MAX_LOCALE_NAME + 1];
const gchar *language;
guint language_len;
const gchar *territory = NULL;
guint territory_len = 0;
const gchar *modifier = NULL;
guint modifier_len = 0;
const gchar *next_char;
guint id;
/* As per POSIX, a valid locale looks like:
*
* language[_territory][.codeset][@modifier]
*/
language = locale;
language_len = strcspn (language, "_.@");
next_char = language + language_len;
if (*next_char == '_')
{
territory = next_char;
territory_len = strcspn (territory + 1, "_.@") + 1;
next_char = territory + territory_len;
}
if (*next_char == '.')
{
const gchar *codeset;
guint codeset_len;
codeset = next_char;
codeset_len = strcspn (codeset + 1, "_.@") + 1;
next_char = codeset + codeset_len;
}
if (*next_char == '@')
{
modifier = next_char;
modifier_len = strcspn (modifier + 1, "_.@") + 1;
next_char = modifier + modifier_len;
}
/* What madness is this? */
if (language_len == 0 || *next_char)
return default_item_id;
/* We are not interested in codeset.
*
* For this locale:
*
* aa_BB@cc
*
* try in this order:
*
* Note: we have no locales of the form aa_BB@cc in the database.
*
* 1. aa@cc
* 2. aa_BB
* 3. aa
*/
/* 1. */
if (modifier_len && language_len + modifier_len <= MAX_LOCALE_NAME)
{
memcpy (key, language, language_len);
memcpy (key + language_len, modifier, modifier_len);
key[language_len + modifier_len] = '\0';
if (lookup_item_id_for_one_locale (key, &id))
return id;
}
/* 2. */
if (territory_len && language_len + territory_len <= MAX_LOCALE_NAME)
{
memcpy (key, language, language_len);
memcpy (key + language_len, territory, territory_len);
key[language_len + territory_len] = '\0';
if (lookup_item_id_for_one_locale (key, &id))
return id;
}
/* 3. */
if (language_len <= MAX_LOCALE_NAME)
{
memcpy (key, language, language_len);
key[language_len] = '\0';
if (lookup_item_id_for_one_locale (key, &id))
return id;
}
return default_item_id;
}
static guint
get_default_item_id (void)
{
static guint item_id;
static gboolean done;
/* Doesn't need to be locked -- no harm in doing it twice. */
if (!done)
{
const gchar *locale;
locale = setlocale (LC_CTYPE, NULL);
item_id = lookup_item_id_for_locale (locale);
done = TRUE;
}
return item_id;
}
/**
* g_str_to_ascii:
* @str: a string, in UTF-8
* @from_locale: (allow-none): the source locale, if known
*
* Transliterate @str to plain ASCII.
*
* For best results, @str should be in composed normalised form.
*
* This function performs a reasonably good set of character
* replacements. The particular set of replacements that is done may
* change by version or even by runtime environment.
*
* If the source language of @str is known, it can used to improve the
* accuracy of the translation by passing it as @from_locale. It should
* be a valid POSIX locale string (of the form
* "language[_territory][.codeset][@modifier]").
*
* If @from_locale is %NULL then the current locale is used.
*
* If you want to do translation for no specific locale, and you want it
* to be done independently of the currently locale, specify "C" for
* @from_locale.
*
* Returns: a string in plain ASCII
*
* Since: 2.40
**/
gchar *
g_str_to_ascii (const gchar *str,
const gchar *from_locale)
{
GString *result;
guint item_id;
g_return_val_if_fail (str != NULL, NULL);
if (g_str_is_ascii (str))
return g_strdup (str);
if (from_locale)
item_id = lookup_item_id_for_locale (from_locale);
else
item_id = get_default_item_id ();
result = g_string_sized_new (strlen (str));
while (*str)
{
/* We only need to transliterate non-ASCII values... */
if (*str & 0x80)
{
gunichar key[MAX_KEY_SIZE];
const gchar *r;
gint consumed;
gint r_len;
gunichar c;
G_STATIC_ASSERT(MAX_KEY_SIZE == 2);
c = g_utf8_get_char (str);
/* This is where it gets evil...
*
* We know that MAX_KEY_SIZE is 2. We also know that we
* only want to try another character if it's non-ascii.
*/
str = g_utf8_next_char (str);
key[0] = c;
if (*str & 0x80)
key[1] = g_utf8_get_char (str);
else
key[1] = 0;
r = lookup_in_item (item_id, key, &r_len, &consumed);
/* If we failed to map two characters, try again with one.
*
* gconv behaviour is a bit weird here -- it seems to
* depend in the randomness of the binary search and the
* size of the input buffer as to what result we get here.
*
* Doing it this way is more work, but should be
* more-correct.
*/
if (r == NULL && key[1])
{
key[1] = 0;
r = lookup_in_item (item_id, key, &r_len, &consumed);
}
if (r != NULL)
{
g_string_append_len (result, r, r_len);
if (consumed == 2)
/* If it took both then skip again */
str = g_utf8_next_char (str);
}
else /* no match found */
g_string_append_c (result, '?');
}
else if (*str & 0x80) /* Out-of-range non-ASCII case */
{
g_string_append_c (result, '?');
str = g_utf8_next_char (str);
}
else /* ASCII case */
g_string_append_c (result, *str++);
}
return g_string_free (result, FALSE);
}
| gpl-3.0 |
rsn8887/scummvm | engines/illusions/sequenceopcodes.cpp | 11 | 14033 | /* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* 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 3 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 "illusions/illusions.h"
#include "illusions/sequenceopcodes.h"
#include "illusions/actor.h"
#include "illusions/dictionary.h"
#include "illusions/resources/actorresource.h"
#include "illusions/screen.h"
#include "illusions/scriptopcodes.h"
#include "illusions/sound.h"
namespace Illusions {
// SequenceOpcodes
SequenceOpcodes::SequenceOpcodes(IllusionsEngine *vm)
: _vm(vm) {
initOpcodes();
}
SequenceOpcodes::~SequenceOpcodes() {
freeOpcodes();
}
void SequenceOpcodes::execOpcode(Control *control, OpCall &opCall) {
if (!_opcodes[opCall._op])
error("SequenceOpcodes::execOpcode() Unimplemented opcode %d", opCall._op);
debug(3, "execSequenceOpcode(%d) %s objectID: %08X", opCall._op, _opcodeNames[opCall._op].c_str(), control->_objectId);
(*_opcodes[opCall._op])(control, opCall);
}
typedef Common::Functor2Mem<Control*, OpCall&, void, SequenceOpcodes> SequenceOpcodeI;
#define OPCODE(op, func) \
_opcodes[op] = new SequenceOpcodeI(this, &SequenceOpcodes::func); \
_opcodeNames[op] = #func;
void SequenceOpcodes::initOpcodes() {
// First clear everything
for (uint i = 0; i < 256; ++i) {
_opcodes[i] = nullptr;
}
// Register opcodes
OPCODE(1, opYield);
OPCODE(2, opSetFrameIndex);
OPCODE(3, opEndSequence);
OPCODE(4, opIncFrameDelay);
OPCODE(5, opSetRandomFrameDelay);
OPCODE(6, opSetFrameSpeed);
OPCODE(7, opJump);
OPCODE(8, opJumpRandom);
OPCODE(9, opGotoSequence);
OPCODE(10, opStartForeignSequence);
OPCODE(11, opBeginLoop);
OPCODE(12, opNextLoop);
OPCODE(13, opSetActorIndex);
OPCODE(14, opSwitchActorIndex);
OPCODE(15, opSwitchFacing);
OPCODE(16, opAppearActor);
OPCODE(17, opDisappearActor);
OPCODE(18, opAppearForeignActor);
OPCODE(19, opDisappearForeignActor);
OPCODE(20, opSetNamedPointPosition);
OPCODE(21, opMoveDelta);
// 22-24 unused in Duckman, CHECKME BBDOU
OPCODE(25, opFaceActor);
// 26-27 unused in Duckman, CHECKME BBDOU
OPCODE(28, opNotifyThreadId1);
OPCODE(29, opSetPathCtrY);
// 30-31 unused in Duckman, CHECKME BBDOU
OPCODE(32, opDisablePathWalkPoints);
OPCODE(33, opSetPathWalkPoints);
OPCODE(34, opDisableAutoScale);
OPCODE(35, opSetScale);
OPCODE(36, opSetScaleLayer);
OPCODE(37, opDeactivatePathWalkRects);
OPCODE(38, opSetPathWalkRects);
OPCODE(39, opSetPriority);
OPCODE(40, opSetPriorityLayer);
OPCODE(41, opDisableAutoRegionLayer);
OPCODE(42, opSetRegionLayer);
// 43-47 unused in Duckman, CHECKME BBDOU
OPCODE(48, opSetPalette);
OPCODE(49, opShiftPalette);
OPCODE(50, opPlaySound);
OPCODE(51, opStopSound);
OPCODE(52, opStartScriptThread);
OPCODE(53, opPlaceSubActor);
OPCODE(54, opStartSubSequence);
OPCODE(55, opStopSubSequence);
}
#undef OPCODE
void SequenceOpcodes::freeOpcodes() {
for (uint i = 0; i < 256; ++i) {
delete _opcodes[i];
}
}
// Opcodes
void SequenceOpcodes::opYield(Control *control, OpCall &opCall) {
opCall._result = 2;
}
void SequenceOpcodes::opSetFrameIndex(Control *control, OpCall &opCall) {
ARG_INT16(frameIndex);
if (control->_actor->_flags & Illusions::ACTOR_FLAG_80) {
int16 frameIncr = READ_LE_UINT16(control->_actor->_entryTblPtr);
if (frameIncr) {
frameIndex += frameIncr - 1;
control->_actor->_entryTblPtr += 2;
} else {
control->_actor->_flags &= ~Illusions::ACTOR_FLAG_80;
control->_actor->_entryTblPtr = nullptr;
control->_actor->_notifyThreadId2 = 0;
_vm->notifyThreadId(control->_actor->_notifyThreadId1);
opCall._result = 1;
}
}
control->_actor->_flags &= ~Illusions::ACTOR_FLAG_100;
if (control->_actor->_flags & Illusions::ACTOR_FLAG_8000) {
control->appearActor();
control->_actor->_flags &= ~Illusions::ACTOR_FLAG_8000;
}
control->_actor->_newFrameIndex = frameIndex;
}
void SequenceOpcodes::opEndSequence(Control *control, OpCall &opCall) {
control->_actor->_seqCodeIp = nullptr;
if (control->_actor->_flags & Illusions::ACTOR_FLAG_800) {
control->_actor->_flags &= ~Illusions::ACTOR_FLAG_800;
control->_actor->_frames = nullptr;
control->_actor->_frameIndex = 0;
control->_actor->_newFrameIndex = 0;
_vm->_resSys->unloadResourceById(control->_actor->_sequenceId);
}
_vm->notifyThreadId(control->_actor->_notifyThreadId1);
opCall._result = 1;
}
void SequenceOpcodes::opIncFrameDelay(Control *control, OpCall &opCall) {
ARG_INT16(frameDelayIncr);
control->_actor->_seqCodeValue3 += frameDelayIncr;
opCall._result = 2;
}
void SequenceOpcodes::opSetRandomFrameDelay(Control *control, OpCall &opCall) {
ARG_INT16(minFrameDelay);
ARG_INT16(maxFrameDelay);
control->_actor->_seqCodeValue3 += minFrameDelay + _vm->getRandom(maxFrameDelay);
opCall._result = 2;
}
void SequenceOpcodes::opSetFrameSpeed(Control *control, OpCall &opCall) {
ARG_INT16(frameSpeed);
control->_actor->_seqCodeValue2 = frameSpeed;
}
void SequenceOpcodes::opJump(Control *control, OpCall &opCall) {
ARG_INT16(jumpOffs);
opCall._deltaOfs += jumpOffs;
}
void SequenceOpcodes::opJumpRandom(Control *control, OpCall &opCall) {
ARG_INT16(count);
ARG_SKIP(_vm->getRandom(count) * 2);
ARG_INT16(jumpOffs);
opCall._deltaOfs += jumpOffs;
}
void SequenceOpcodes::opGotoSequence(Control *control, OpCall &opCall) {
ARG_SKIP(2);
ARG_UINT32(nextSequenceId);
uint32 notifyThreadId1 = control->_actor->_notifyThreadId1;
control->clearNotifyThreadId1();
if (control->_actor->_pathNode) {
control->startSequenceActor(nextSequenceId, 1, notifyThreadId1);
} else {
control->startSequenceActor(nextSequenceId, 2, notifyThreadId1);
}
opCall._deltaOfs = 0;
}
void SequenceOpcodes::opStartForeignSequence(Control *control, OpCall &opCall) {
ARG_INT16(foreignObjectNum);
ARG_UINT32(sequenceId);
Control *foreignControl = _vm->_dict->getObjectControl(foreignObjectNum | 0x40000);
foreignControl->startSequenceActor(sequenceId, 2, 0);
}
void SequenceOpcodes::opBeginLoop(Control *control, OpCall &opCall) {
ARG_INT16(loopCount);
control->_actor->pushSequenceStack(loopCount);
}
void SequenceOpcodes::opNextLoop(Control *control, OpCall &opCall) {
ARG_INT16(jumpOffs);
int16 currLoopCount = control->_actor->popSequenceStack();
if (currLoopCount > 0) {
control->_actor->pushSequenceStack(currLoopCount - 1);
opCall._deltaOfs = -jumpOffs;
}
}
void SequenceOpcodes::opSetActorIndex(Control *control, OpCall &opCall) {
ARG_BYTE(actorIndex);
control->setActorIndex(actorIndex);
}
void SequenceOpcodes::opSwitchActorIndex(Control *control, OpCall &opCall) {
ARG_INT16(actorIndex);
ARG_INT16(jumpOffs);
if (control->_actor->_actorIndex != actorIndex)
opCall._deltaOfs += jumpOffs;
}
void SequenceOpcodes::opSwitchFacing(Control *control, OpCall &opCall) {
ARG_INT16(facing);
ARG_INT16(jumpOffs);
if (!(control->_actor->_facing & facing))
opCall._deltaOfs += jumpOffs;
}
void SequenceOpcodes::opAppearActor(Control *control, OpCall &opCall) {
control->appearActor();
}
void SequenceOpcodes::opDisappearActor(Control *control, OpCall &opCall) {
control->disappearActor();
control->_actor->_newFrameIndex = 0;
}
void SequenceOpcodes::opAppearForeignActor(Control *control, OpCall &opCall) {
ARG_INT16(foreignObjectNum);
Control *foreignControl = _vm->_dict->getObjectControl(foreignObjectNum | 0x40000);
if (!foreignControl) {
Common::Point pos = _vm->getNamedPointPosition(_vm->getGameId() == kGameIdDuckman ? 0x00070001 : 0x00070023);
_vm->_controls->placeActor(0x00050001, pos, 0x00060001, foreignObjectNum | 0x40000, 0);
foreignControl = _vm->_dict->getObjectControl(foreignObjectNum | 0x40000);
}
foreignControl->appearActor();
}
void SequenceOpcodes::opDisappearForeignActor(Control *control, OpCall &opCall) {
ARG_INT16(foreignObjectNum);
Control *foreignControl = _vm->_dict->getObjectControl(foreignObjectNum | 0x40000);
foreignControl->disappearActor();
}
void SequenceOpcodes::opSetNamedPointPosition(Control *control, OpCall &opCall) {
ARG_SKIP(2);
ARG_UINT32(namedPointId);
control->_actor->_position = _vm->getNamedPointPosition(namedPointId);
}
void SequenceOpcodes::opMoveDelta(Control *control, OpCall &opCall) {
ARG_SKIP(2);
ARG_INT16(deltaX);
ARG_INT16(deltaY);
control->_actor->_position.x += deltaX;
control->_actor->_position.y += deltaY;
}
void SequenceOpcodes::opFaceActor(Control *control, OpCall &opCall) {
ARG_INT16(facing);
control->_actor->_facing = facing;
}
void SequenceOpcodes::opNotifyThreadId1(Control *control, OpCall &opCall) {
_vm->notifyThreadId(control->_actor->_notifyThreadId1);
}
void SequenceOpcodes::opSetPathCtrY(Control *control, OpCall &opCall) {
ARG_INT16(pathCtrY);
control->_actor->_pathCtrY = pathCtrY;
}
void SequenceOpcodes::opDisablePathWalkPoints(Control *control, OpCall &opCall) {
control->_actor->_flags &= ~Illusions::ACTOR_FLAG_HAS_WALK_POINTS;
}
void SequenceOpcodes::opSetPathWalkPoints(Control *control, OpCall &opCall) {
ARG_INT16(pathWalkPointsIndex);
BackgroundResource *bgRes = _vm->_backgroundInstances->getActiveBgResource();
control->_actor->_flags |= Illusions::ACTOR_FLAG_HAS_WALK_POINTS;
control->_actor->_pathWalkPoints = bgRes->getPathWalkPoints(pathWalkPointsIndex - 1);
}
void SequenceOpcodes::opDisableAutoScale(Control *control, OpCall &opCall) {
// Keep current scale but don't autoscale
control->_actor->_flags &= ~Illusions::ACTOR_FLAG_SCALED;
}
void SequenceOpcodes::opSetScale(Control *control, OpCall &opCall) {
ARG_INT16(scale);
control->_actor->_flags &= ~Illusions::ACTOR_FLAG_SCALED;
control->setActorScale(scale);
}
void SequenceOpcodes::opSetScaleLayer(Control *control, OpCall &opCall) {
ARG_INT16(scaleLayerIndex);
BackgroundResource *bgRes = _vm->_backgroundInstances->getActiveBgResource();
control->_actor->_flags |= Illusions::ACTOR_FLAG_SCALED;
control->_actor->_scaleLayer = bgRes->getScaleLayer(scaleLayerIndex - 1);
int scale = control->_actor->_scaleLayer->getScale(control->_actor->_position);
control->setActorScale(scale);
}
void SequenceOpcodes::opDeactivatePathWalkRects(Control *control, OpCall &opCall) {
control->_actor->_flags &= ~Illusions::ACTOR_FLAG_HAS_WALK_RECTS;
}
void SequenceOpcodes::opSetPathWalkRects(Control *control, OpCall &opCall) {
ARG_INT16(pathWalkRectsIndex);
BackgroundResource *bgRes = _vm->_backgroundInstances->getActiveBgResource();
control->_actor->_flags |= Illusions::ACTOR_FLAG_HAS_WALK_RECTS;
control->_actor->_pathWalkRects = bgRes->getPathWalkRects(pathWalkRectsIndex - 1);
}
void SequenceOpcodes::opSetPriority(Control *control, OpCall &opCall) {
ARG_INT16(priority);
control->_actor->_flags &= ~Illusions::ACTOR_FLAG_PRIORITY;
control->setPriority(priority);
}
void SequenceOpcodes::opSetPriorityLayer(Control *control, OpCall &opCall) {
ARG_INT16(priorityLayerIndex);
BackgroundResource *bgRes = _vm->_backgroundInstances->getActiveBgResource();
control->_actor->_flags |= Illusions::ACTOR_FLAG_PRIORITY;
control->_actor->_priorityLayer = bgRes->getPriorityLayer(priorityLayerIndex - 1);
int priority = control->_actor->_priorityLayer->getPriority(control->_actor->_position);
control->setPriority(priority);
}
void SequenceOpcodes::opDisableAutoRegionLayer(Control *control, OpCall &opCall) {
control->_actor->_flags &= ~Illusions::ACTOR_FLAG_REGION;
}
void SequenceOpcodes::opSetRegionLayer(Control *control, OpCall &opCall) {
ARG_INT16(regionLayerIndex);
BackgroundResource *bgRes = _vm->_backgroundInstances->getActiveBgResource();
control->_actor->_flags |= Illusions::ACTOR_FLAG_REGION;
control->_actor->_regionLayer = bgRes->getRegionLayer(regionLayerIndex - 1);
}
void SequenceOpcodes::opSetPalette(Control *control, OpCall &opCall) {
ARG_INT16(paletteIndex);
ARG_BYTE(fromIndex);
BackgroundResource *bgRes = _vm->_backgroundInstances->getActiveBgResource();
Palette *palette = bgRes->getPalette(paletteIndex - 1);
_vm->_screenPalette->setPalette(palette->_palette, fromIndex, palette->_count);
}
void SequenceOpcodes::opShiftPalette(Control *control, OpCall &opCall) {
ARG_INT16(fromIndex);
ARG_INT16(toIndex);
_vm->_screenPalette->shiftPalette(fromIndex, toIndex);
}
void SequenceOpcodes::opPlaySound(Control *control, OpCall &opCall) {
ARG_INT16(flags);
ARG_INT16(volume);
ARG_INT16(pan);
ARG_UINT32(soundEffectId);
if (!(flags & 1))
volume = 255;
if (!(flags & 2))
pan = _vm->convertPanXCoord(control->_actor->_position.x);
_vm->_soundMan->playSound(soundEffectId, volume, pan);
}
void SequenceOpcodes::opStopSound(Control *control, OpCall &opCall) {
ARG_UINT32(soundEffectId);
_vm->_soundMan->stopSound(soundEffectId);
}
void SequenceOpcodes::opStartScriptThread(Control *control, OpCall &opCall) {
ARG_SKIP(2);
ARG_UINT32(threadId);
_vm->startScriptThreadSimple(threadId, 0);
}
void SequenceOpcodes::opPlaceSubActor(Control *control, OpCall &opCall) {
ARG_INT16(linkIndex);
ARG_UINT32(actorTypeId);
ARG_UINT32(sequenceId);
_vm->_controls->placeSubActor(control->_objectId, linkIndex, actorTypeId, sequenceId);
}
void SequenceOpcodes::opStartSubSequence(Control *control, OpCall &opCall) {
ARG_INT16(linkIndex);
ARG_UINT32(sequenceId);
control->startSubSequence(linkIndex, sequenceId);
}
void SequenceOpcodes::opStopSubSequence(Control *control, OpCall &opCall) {
ARG_INT16(linkIndex);
control->stopSubSequence(linkIndex);
}
} // End of namespace Illusions
| gpl-3.0 |
DGA-MI-SSI/YaCo | deps/libssh2-1.8.0/src/keepalive.c | 12 | 3502 | /* Copyright (C) 2010 Simon Josefsson
* Author: Simon Josefsson
*
* 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.
*
* Neither the name of the copyright holder nor the names
* of any other 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 OWNER 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 "libssh2_priv.h"
#include "transport.h" /* _libssh2_transport_write */
/* Keep-alive stuff. */
LIBSSH2_API void
libssh2_keepalive_config (LIBSSH2_SESSION *session,
int want_reply,
unsigned interval)
{
if (interval == 1)
session->keepalive_interval = 2;
else
session->keepalive_interval = interval;
session->keepalive_want_reply = want_reply ? 1 : 0;
}
LIBSSH2_API int
libssh2_keepalive_send (LIBSSH2_SESSION *session,
int *seconds_to_next)
{
time_t now;
if (!session->keepalive_interval) {
if (seconds_to_next)
*seconds_to_next = 0;
return 0;
}
now = time (NULL);
if (session->keepalive_last_sent + session->keepalive_interval <= now) {
/* Format is
"SSH_MSG_GLOBAL_REQUEST || 4-byte len || str || want-reply". */
unsigned char keepalive_data[]
= "\x50\x00\x00\x00\x15keepalive@libssh2.orgW";
size_t len = sizeof (keepalive_data) - 1;
int rc;
keepalive_data[len - 1] =
(unsigned char)session->keepalive_want_reply;
rc = _libssh2_transport_send(session, keepalive_data, len, NULL, 0);
/* Silently ignore PACKET_EAGAIN here: if the write buffer is
already full, sending another keepalive is not useful. */
if (rc && rc != LIBSSH2_ERROR_EAGAIN) {
_libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND,
"Unable to send keepalive message");
return rc;
}
session->keepalive_last_sent = now;
if (seconds_to_next)
*seconds_to_next = session->keepalive_interval;
} else if (seconds_to_next) {
*seconds_to_next = (int) (session->keepalive_last_sent - now)
+ session->keepalive_interval;
}
return 0;
}
| gpl-3.0 |
ClaudioNahmad/Servicio-Social | Parametros/CosmoMC/prerrequisitos/plc-2.0/build/cfitsio/iter_var.c | 13 | 3319 | #include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "fitsio.h"
/*
This program illustrates how to use the CFITSIO iterator function.
It reads and modifies the input 'iter_a.fit' file by computing a
value for the 'rate' column as a function of the values in the other
'counts' and 'time' columns.
*/
main()
{
extern flux_rate(); /* external work function is passed to the iterator */
fitsfile *fptr;
iteratorCol cols[3]; /* structure used by the iterator function */
int n_cols;
long rows_per_loop, offset;
int status, nkeys, keypos, hdutype, ii, jj;
char filename[] = "vari.fits"; /* name of rate FITS file */
status = 0;
fits_open_file(&fptr, filename, READWRITE, &status); /* open file */
/* move to the desired binary table extension */
if (fits_movnam_hdu(fptr, BINARY_TBL, "COMPRESSED_IMAGE", 0, &status) )
fits_report_error(stderr, status); /* print out error messages */
n_cols = 1; /* number of columns */
/* define input column structure members for the iterator function */
fits_iter_set_by_name(&cols[0], fptr, "COMPRESSED_DATA", 0, InputCol);
rows_per_loop = 0; /* use default optimum number of rows */
offset = 0; /* process all the rows */
/* apply the rate function to each row of the table */
printf("Calling iterator function...%d\n", status);
fits_iterate_data(n_cols, cols, offset, rows_per_loop,
flux_rate, 0L, &status);
fits_close_file(fptr, &status); /* all done */
if (status)
fits_report_error(stderr, status); /* print out error messages */
return(status);
}
/*--------------------------------------------------------------------------*/
int flux_rate(long totalrows, long offset, long firstrow, long nrows,
int ncols, iteratorCol *cols, void *user_strct )
/*
Sample iterator function that calculates the output flux 'rate' column
by dividing the input 'counts' by the 'time' column.
It also applies a constant deadtime correction factor if the 'deadtime'
keyword exists. Finally, this creates or updates the 'LIVETIME'
keyword with the sum of all the individual integration times.
*/
{
int ii, status = 0;
long repeat;
/* declare variables static to preserve their values between calls */
static unsigned char *counts;
/*--------------------------------------------------------*/
/* Initialization procedures: execute on the first call */
/*--------------------------------------------------------*/
if (firstrow == 1)
{
printf("Datatype of column = %d\n",fits_iter_get_datatype(&cols[0]));
/* assign the input pointers to the appropriate arrays and null ptrs*/
counts = (long *) fits_iter_get_array(&cols[0]);
}
/*--------------------------------------------*/
/* Main loop: process all the rows of data */
/*--------------------------------------------*/
/* NOTE: 1st element of array is the null pixel value! */
/* Loop from 1 to nrows, not 0 to nrows - 1. */
for (ii = 1; ii <= nrows; ii++)
{
repeat = fits_iter_get_repeat(&cols[0]);
printf ("repeat = %d, %d\n",repeat, counts[1]);
}
return(0); /* return successful status */
}
| gpl-3.0 |
oascigil/ndnSIM | NFD/websocketpp/examples/broadcast_server/broadcast_server.cpp | 13 | 4373 | #include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
#include <iostream>
#include <set>
/*#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>*/
#include <websocketpp/common/thread.hpp>
typedef websocketpp::server<websocketpp::config::asio> server;
using websocketpp::connection_hdl;
using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;
using websocketpp::lib::thread;
using websocketpp::lib::mutex;
using websocketpp::lib::unique_lock;
using websocketpp::lib::condition_variable;
/* on_open insert connection_hdl into channel
* on_close remove connection_hdl from channel
* on_message queue send to all channels
*/
enum action_type {
SUBSCRIBE,
UNSUBSCRIBE,
MESSAGE
};
struct action {
action(action_type t, connection_hdl h) : type(t), hdl(h) {}
action(action_type t, connection_hdl h, server::message_ptr m)
: type(t), hdl(h), msg(m) {}
action_type type;
websocketpp::connection_hdl hdl;
server::message_ptr msg;
};
class broadcast_server {
public:
broadcast_server() {
// Initialize Asio Transport
m_server.init_asio();
// Register handler callbacks
m_server.set_open_handler(bind(&broadcast_server::on_open,this,::_1));
m_server.set_close_handler(bind(&broadcast_server::on_close,this,::_1));
m_server.set_message_handler(bind(&broadcast_server::on_message,this,::_1,::_2));
}
void run(uint16_t port) {
// listen on specified port
m_server.listen(port);
// Start the server accept loop
m_server.start_accept();
// Start the ASIO io_service run loop
try {
m_server.run();
} catch (const std::exception & e) {
std::cout << e.what() << std::endl;
}
}
void on_open(connection_hdl hdl) {
unique_lock<mutex> lock(m_action_lock);
//std::cout << "on_open" << std::endl;
m_actions.push(action(SUBSCRIBE,hdl));
lock.unlock();
m_action_cond.notify_one();
}
void on_close(connection_hdl hdl) {
unique_lock<mutex> lock(m_action_lock);
//std::cout << "on_close" << std::endl;
m_actions.push(action(UNSUBSCRIBE,hdl));
lock.unlock();
m_action_cond.notify_one();
}
void on_message(connection_hdl hdl, server::message_ptr msg) {
// queue message up for sending by processing thread
unique_lock<mutex> lock(m_action_lock);
//std::cout << "on_message" << std::endl;
m_actions.push(action(MESSAGE,hdl,msg));
lock.unlock();
m_action_cond.notify_one();
}
void process_messages() {
while(1) {
unique_lock<mutex> lock(m_action_lock);
while(m_actions.empty()) {
m_action_cond.wait(lock);
}
action a = m_actions.front();
m_actions.pop();
lock.unlock();
if (a.type == SUBSCRIBE) {
unique_lock<mutex> con_lock(m_connection_lock);
m_connections.insert(a.hdl);
} else if (a.type == UNSUBSCRIBE) {
unique_lock<mutex> con_lock(m_connection_lock);
m_connections.erase(a.hdl);
} else if (a.type == MESSAGE) {
unique_lock<mutex> con_lock(m_connection_lock);
con_list::iterator it;
for (it = m_connections.begin(); it != m_connections.end(); ++it) {
m_server.send(*it,a.msg);
}
} else {
// undefined.
}
}
}
private:
typedef std::set<connection_hdl,std::owner_less<connection_hdl> > con_list;
server m_server;
con_list m_connections;
std::queue<action> m_actions;
mutex m_action_lock;
mutex m_connection_lock;
condition_variable m_action_cond;
};
int main() {
try {
broadcast_server server_instance;
// Start a thread to run the processing loop
thread t(bind(&broadcast_server::process_messages,&server_instance));
// Run the asio loop with the main thread
server_instance.run(9002);
t.join();
} catch (websocketpp::exception const & e) {
std::cout << e.what() << std::endl;
}
}
| gpl-3.0 |
haililihai/ATPP_GUI | ffcall-1.10/vacall/vacall-m88k.c | 14 | 3651 | /* vacall function for m88k CPU */
/*
* Copyright 1995-2004 Bruno Haible, <bruno@clisp.org>
*
* This is free software distributed under the GNU General Public Licence
* described in the file COPYING. Contact the author if you don't have this
* or can't live with it. There is ABSOLUTELY NO WARRANTY, explicit or implied,
* on this software.
*/
#ifndef REENTRANT
#include "vacall.h.in"
#else /* REENTRANT */
#include "vacall_r.h.in"
#endif
#ifdef REENTRANT
#define __vacall __vacall_r
register struct { void (*vacall_function) (void*,va_alist); void* arg; }
* env __asm__("r11");
#endif
register __vaword* sret __asm__("r12");
register int iret __asm__("r2");
register int iret2 __asm__("r3");
register float fret __asm__("r2");
register double dret __asm__("r2");
void /* the return type is variable, not void! */
__vacall (__vaword word1, __vaword word2, __vaword word3, __vaword word4,
__vaword word5, __vaword word6, __vaword word7, __vaword word8,
__vaword firstword)
{
__va_alist list;
/* gcc-2.6.3 source says: When a parameter is passed in a register,
* stack space is still allocated for it.
*/
/* Move the arguments passed in registers to their stack locations. */
/*
* Is this correct?? I think struct arguments among the first 8 words
* are passed on the stack, not in registers, and we shouldn't overwrite
* them.
*/
(&firstword)[-8] = word1;
(&firstword)[-7] = word2;
(&firstword)[-6] = word3;
(&firstword)[-5] = word4;
(&firstword)[-4] = word5;
(&firstword)[-3] = word6;
(&firstword)[-2] = word7;
(&firstword)[-1] = word8;
/* Prepare the va_alist. */
list.flags = 0;
list.aptr = (long)&firstword;
list.raddr = (void*)0;
list.rtype = __VAvoid;
list.structraddr = sret;
/* Call vacall_function. The macros do all the rest. */
#ifndef REENTRANT
(*vacall_function) (&list);
#else /* REENTRANT */
(*env->vacall_function) (env->arg,&list);
#endif
/* Put return value into proper register. */
if (list.rtype == __VAvoid) {
} else
if (list.rtype == __VAchar) {
iret = list.tmp._char;
} else
if (list.rtype == __VAschar) {
iret = list.tmp._schar;
} else
if (list.rtype == __VAuchar) {
iret = list.tmp._uchar;
} else
if (list.rtype == __VAshort) {
iret = list.tmp._short;
} else
if (list.rtype == __VAushort) {
iret = list.tmp._ushort;
} else
if (list.rtype == __VAint) {
iret = list.tmp._int;
} else
if (list.rtype == __VAuint) {
iret = list.tmp._uint;
} else
if (list.rtype == __VAlong) {
iret = list.tmp._long;
} else
if (list.rtype == __VAulong) {
iret = list.tmp._ulong;
} else
if (list.rtype == __VAlonglong || list.rtype == __VAulonglong) {
iret = ((__vaword *) &list.tmp._longlong)[0];
iret2 = ((__vaword *) &list.tmp._longlong)[1];
} else
if (list.rtype == __VAfloat) {
fret = list.tmp._float;
} else
if (list.rtype == __VAdouble) {
dret = list.tmp._double;
} else
if (list.rtype == __VAvoidp) {
iret = (long)list.tmp._ptr;
} else
if (list.rtype == __VAstruct) {
if (list.flags & __VA_PCC_STRUCT_RETURN) {
/* pcc struct return convention */
iret = (long) list.raddr;
} else {
/* normal struct return convention */
if (list.flags & __VA_SMALL_STRUCT_RETURN) {
if (list.rsize == sizeof(char)) {
iret = *(unsigned char *) list.raddr;
} else
if (list.rsize == sizeof(short)) {
iret = *(unsigned short *) list.raddr;
} else
if (list.rsize == sizeof(int)) {
iret = *(unsigned int *) list.raddr;
}
}
}
}
}
| gpl-3.0 |
selmentdev/selment-toolchain | source/binutils-latest/bfd/vms-alpha.c | 15 | 282697 | /* vms.c -- BFD back-end for EVAX (openVMS/Alpha) files.
Copyright (C) 1996-2015 Free Software Foundation, Inc.
Initial version written by Klaus Kaempf (kkaempf@rmi.de)
Major rewrite by Adacore.
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 3 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. */
/* TODO:
o overlayed sections
o PIC
o Generation of shared image
o Relocation optimizations
o EISD for the stack
o Vectors isect
o 64 bits sections
o Entry point
o LIB$INITIALIZE
o protected sections (for messages)
...
*/
#include "sysdep.h"
#include "bfd.h"
#include "bfdlink.h"
#include "libbfd.h"
#include "bfdver.h"
#include "vms.h"
#include "vms/eihd.h"
#include "vms/eiha.h"
#include "vms/eihi.h"
#include "vms/eihs.h"
#include "vms/eisd.h"
#include "vms/dmt.h"
#include "vms/dst.h"
#include "vms/eihvn.h"
#include "vms/eobjrec.h"
#include "vms/egsd.h"
#include "vms/egps.h"
#include "vms/esgps.h"
#include "vms/eeom.h"
#include "vms/emh.h"
#include "vms/eiaf.h"
#include "vms/shl.h"
#include "vms/eicp.h"
#include "vms/etir.h"
#include "vms/egsy.h"
#include "vms/esdf.h"
#include "vms/esdfm.h"
#include "vms/esdfv.h"
#include "vms/esrf.h"
#include "vms/egst.h"
#include "vms/eidc.h"
#include "vms/dsc.h"
#include "vms/prt.h"
#include "vms/internal.h"
#define MIN(a,b) ((a) < (b) ? (a) : (b))
/* The r_type field in a reloc is one of the following values. */
#define ALPHA_R_IGNORE 0
#define ALPHA_R_REFQUAD 1
#define ALPHA_R_BRADDR 2
#define ALPHA_R_HINT 3
#define ALPHA_R_SREL16 4
#define ALPHA_R_SREL32 5
#define ALPHA_R_SREL64 6
#define ALPHA_R_OP_PUSH 7
#define ALPHA_R_OP_STORE 8
#define ALPHA_R_OP_PSUB 9
#define ALPHA_R_OP_PRSHIFT 10
#define ALPHA_R_LINKAGE 11
#define ALPHA_R_REFLONG 12
#define ALPHA_R_CODEADDR 13
#define ALPHA_R_NOP 14
#define ALPHA_R_BSR 15
#define ALPHA_R_LDA 16
#define ALPHA_R_BOH 17
/* These are used with DST_S_C_LINE_NUM. */
#define DST_S_C_LINE_NUM_HEADER_SIZE 4
/* These are used with DST_S_C_SOURCE */
#define DST_S_B_PCLINE_UNSBYTE 1
#define DST_S_W_PCLINE_UNSWORD 1
#define DST_S_L_PCLINE_UNSLONG 1
#define DST_S_B_MODBEG_NAME 14
#define DST_S_L_RTNBEG_ADDRESS 5
#define DST_S_B_RTNBEG_NAME 13
#define DST_S_L_RTNEND_SIZE 5
/* These are used with DST_S_C_SOURCE. */
#define DST_S_C_SOURCE_HEADER_SIZE 4
#define DST_S_B_SRC_DF_LENGTH 1
#define DST_S_W_SRC_DF_FILEID 3
#define DST_S_B_SRC_DF_FILENAME 20
#define DST_S_B_SRC_UNSBYTE 1
#define DST_S_W_SRC_UNSWORD 1
#define DST_S_L_SRC_UNSLONG 1
/* Debugger symbol definitions. */
#define DBG_S_L_DMT_MODBEG 0
#define DBG_S_L_DST_SIZE 4
#define DBG_S_W_DMT_PSECT_COUNT 8
#define DBG_S_C_DMT_HEADER_SIZE 12
#define DBG_S_L_DMT_PSECT_START 0
#define DBG_S_L_DMT_PSECT_LENGTH 4
#define DBG_S_C_DMT_PSECT_SIZE 8
/* VMS module header. */
struct hdr_struct
{
char hdr_b_strlvl;
int hdr_l_arch1;
int hdr_l_arch2;
int hdr_l_recsiz;
char *hdr_t_name;
char *hdr_t_version;
char *hdr_t_date;
char *hdr_c_lnm;
char *hdr_c_src;
char *hdr_c_ttl;
};
#define EMH_DATE_LENGTH 17
/* VMS End-Of-Module records (EOM/EEOM). */
struct eom_struct
{
unsigned int eom_l_total_lps;
unsigned short eom_w_comcod;
bfd_boolean eom_has_transfer;
unsigned char eom_b_tfrflg;
unsigned int eom_l_psindx;
unsigned int eom_l_tfradr;
};
struct vms_symbol_entry
{
bfd *owner;
/* Common fields. */
unsigned char typ;
unsigned char data_type;
unsigned short flags;
/* Section and offset/value of the symbol. */
unsigned int value;
asection *section;
/* Section and offset/value for the entry point (only for subprg). */
asection *code_section;
unsigned int code_value;
/* Symbol vector offset. */
unsigned int symbol_vector;
/* Length of the name. */
unsigned char namelen;
char name[1];
};
/* Stack value for push/pop commands. */
struct stack_struct
{
bfd_vma value;
unsigned int reloc;
};
#define STACKSIZE 128
/* A minimal decoding of DST compilation units. We only decode
what's needed to get to the line number information. */
struct fileinfo
{
char *name;
unsigned int srec;
};
struct srecinfo
{
struct srecinfo *next;
unsigned int line;
unsigned int sfile;
unsigned int srec;
};
struct lineinfo
{
struct lineinfo *next;
bfd_vma address;
unsigned int line;
};
struct funcinfo
{
struct funcinfo *next;
char *name;
bfd_vma low;
bfd_vma high;
};
struct module
{
/* Chain the previously read compilation unit. */
struct module *next;
/* The module name. */
char *name;
/* The start offset and size of debug info in the DST section. */
unsigned int modbeg;
unsigned int size;
/* The lowest and highest addresses contained in this compilation
unit as specified in the compilation unit header. */
bfd_vma low;
bfd_vma high;
/* The listing line table. */
struct lineinfo *line_table;
/* The source record table. */
struct srecinfo *srec_table;
/* A list of the functions found in this module. */
struct funcinfo *func_table;
/* Current allocation of file_table. */
unsigned int file_table_count;
/* An array of the files making up this module. */
struct fileinfo *file_table;
};
/* BFD private data for alpha-vms. */
struct vms_private_data_struct
{
/* If true, relocs have been read. */
bfd_boolean reloc_done;
/* Record input buffer. */
struct vms_rec_rd recrd;
struct vms_rec_wr recwr;
struct hdr_struct hdr_data; /* data from HDR/EMH record */
struct eom_struct eom_data; /* data from EOM/EEOM record */
/* Transfer addresses (entry points). */
bfd_vma transfer_address[4];
/* Array of GSD sections to get the correspond BFD one. */
unsigned int section_max; /* Size of the sections array. */
unsigned int section_count; /* Number of GSD sections. */
asection **sections;
/* Array of raw symbols. */
struct vms_symbol_entry **syms;
/* Canonicalized symbols. */
asymbol **csymbols;
/* Number of symbols. */
unsigned int gsd_sym_count;
/* Size of the syms array. */
unsigned int max_sym_count;
/* Number of procedure symbols. */
unsigned int norm_sym_count;
/* Stack used to evaluate TIR/ETIR commands. */
struct stack_struct *stack;
int stackptr;
/* Content reading. */
asection *image_section; /* section for image_ptr */
file_ptr image_offset; /* Offset for image_ptr. */
struct module *modules; /* list of all compilation units */
/* The DST section. */
asection *dst_section;
unsigned int dst_ptr_offsets_count; /* # of offsets in following array */
unsigned int *dst_ptr_offsets; /* array of saved image_ptr offsets */
/* Shared library support */
bfd_vma symvva; /* relative virtual address of symbol vector */
unsigned int ident;
unsigned char matchctl;
/* Shared library index. This is used for input bfd while linking. */
unsigned int shr_index;
/* Used to place structures in the file. */
file_ptr file_pos;
/* Simply linked list of eisd. */
struct vms_internal_eisd_map *eisd_head;
struct vms_internal_eisd_map *eisd_tail;
/* Simply linked list of eisd for shared libraries. */
struct vms_internal_eisd_map *gbl_eisd_head;
struct vms_internal_eisd_map *gbl_eisd_tail;
/* linkage index counter used by conditional store commands */
unsigned int vms_linkage_index;
};
#define PRIV2(abfd, name) \
(((struct vms_private_data_struct *)(abfd)->tdata.any)->name)
#define PRIV(name) PRIV2(abfd,name)
/* Used to keep extra VMS specific information for a given section.
reloc_size holds the size of the relocation stream, note this
is very different from the number of relocations as VMS relocations
are variable length.
reloc_stream is the actual stream of relocation entries. */
struct vms_section_data_struct
{
/* Maximnum number of entries in sec->relocation. */
unsigned reloc_max;
/* Corresponding eisd. Used only while generating executables. */
struct vms_internal_eisd_map *eisd;
/* PSC flags to be clear. */
flagword no_flags;
/* PSC flags to be set. */
flagword flags;
};
#define vms_section_data(sec) \
((struct vms_section_data_struct *)sec->used_by_bfd)
/* To be called from the debugger. */
struct vms_private_data_struct *bfd_vms_get_data (bfd *);
static int vms_get_remaining_object_record (bfd *, unsigned int);
static bfd_boolean _bfd_vms_slurp_object_records (bfd * abfd);
static void alpha_vms_add_fixup_lp (struct bfd_link_info *, bfd *, bfd *);
static void alpha_vms_add_fixup_ca (struct bfd_link_info *, bfd *, bfd *);
static void alpha_vms_add_fixup_qr (struct bfd_link_info *, bfd *, bfd *,
bfd_vma);
static void alpha_vms_add_fixup_lr (struct bfd_link_info *, unsigned int,
bfd_vma);
static void alpha_vms_add_lw_reloc (struct bfd_link_info *);
static void alpha_vms_add_qw_reloc (struct bfd_link_info *);
struct vector_type
{
unsigned int max_el;
unsigned int nbr_el;
void *els;
};
/* Number of elements in VEC. */
#define VEC_COUNT(VEC) ((VEC).nbr_el)
/* Get the address of the Nth element. */
#define VEC_EL(VEC, TYPE, N) (((TYPE *)((VEC).els))[N])
#define VEC_INIT(VEC) \
do { \
(VEC).max_el = 0; \
(VEC).nbr_el = 0; \
(VEC).els = NULL; \
} while (0)
/* Be sure there is room for a new element. */
static void vector_grow1 (struct vector_type *vec, size_t elsz);
/* Allocate room for a new element and return its address. */
#define VEC_APPEND(VEC, TYPE) \
(vector_grow1 (&VEC, sizeof (TYPE)), &VEC_EL(VEC, TYPE, (VEC).nbr_el++))
/* Append an element. */
#define VEC_APPEND_EL(VEC, TYPE, EL) \
(*(VEC_APPEND (VEC, TYPE)) = EL)
struct alpha_vms_vma_ref
{
bfd_vma vma; /* Vma in the output. */
bfd_vma ref; /* Reference in the input. */
};
struct alpha_vms_shlib_el
{
bfd *abfd;
bfd_boolean has_fixups;
struct vector_type lp; /* Vector of bfd_vma. */
struct vector_type ca; /* Vector of bfd_vma. */
struct vector_type qr; /* Vector of struct alpha_vms_vma_ref. */
};
/* Alpha VMS linker hash table. */
struct alpha_vms_link_hash_table
{
struct bfd_link_hash_table root;
/* Vector of shared libraries. */
struct vector_type shrlibs;
/* Fixup section. */
asection *fixup;
/* Base address. Used by fixups. */
bfd_vma base_addr;
};
#define alpha_vms_link_hash(INFO) \
((struct alpha_vms_link_hash_table *)(INFO->hash))
/* Alpha VMS linker hash table entry. */
struct alpha_vms_link_hash_entry
{
struct bfd_link_hash_entry root;
/* Pointer to the original vms symbol. */
struct vms_symbol_entry *sym;
};
/* Image reading. */
/* Read & process EIHD record.
Return TRUE on success, FALSE on error. */
static bfd_boolean
_bfd_vms_slurp_eihd (bfd *abfd, unsigned int *eisd_offset,
unsigned int *eihs_offset)
{
unsigned int imgtype, size;
bfd_vma symvva;
struct vms_eihd *eihd = (struct vms_eihd *)PRIV (recrd.rec);
vms_debug2 ((8, "_bfd_vms_slurp_eihd\n"));
size = bfd_getl32 (eihd->size);
imgtype = bfd_getl32 (eihd->imgtype);
if (imgtype == EIHD__K_EXE || imgtype == EIHD__K_LIM)
abfd->flags |= EXEC_P;
symvva = bfd_getl64 (eihd->symvva);
if (symvva != 0)
{
PRIV (symvva) = symvva;
abfd->flags |= DYNAMIC;
}
PRIV (ident) = bfd_getl32 (eihd->ident);
PRIV (matchctl) = eihd->matchctl;
*eisd_offset = bfd_getl32 (eihd->isdoff);
*eihs_offset = bfd_getl32 (eihd->symdbgoff);
vms_debug2 ((4, "EIHD size %d imgtype %d symvva 0x%lx eisd %d eihs %d\n",
size, imgtype, (unsigned long)symvva,
*eisd_offset, *eihs_offset));
return TRUE;
}
/* Read & process EISD record.
Return TRUE on success, FALSE on error. */
static bfd_boolean
_bfd_vms_slurp_eisd (bfd *abfd, unsigned int offset)
{
int section_count = 0;
vms_debug2 ((8, "_bfd_vms_slurp_eisd\n"));
while (1)
{
struct vms_eisd *eisd;
unsigned int rec_size;
unsigned int size;
unsigned long long vaddr;
unsigned int flags;
unsigned int vbn;
char *name = NULL;
asection *section;
flagword bfd_flags;
/* PR 17512: file: 3d9e9fe9. */
if (offset >= PRIV (recrd.rec_size))
return FALSE;
eisd = (struct vms_eisd *)(PRIV (recrd.rec) + offset);
rec_size = bfd_getl32 (eisd->eisdsize);
if (rec_size == 0)
break;
/* Skip to next block if pad. */
if (rec_size == 0xffffffff)
{
offset = (offset + VMS_BLOCK_SIZE) & ~(VMS_BLOCK_SIZE - 1);
continue;
}
else
offset += rec_size;
size = bfd_getl32 (eisd->secsize);
vaddr = bfd_getl64 (eisd->virt_addr);
flags = bfd_getl32 (eisd->flags);
vbn = bfd_getl32 (eisd->vbn);
vms_debug2 ((4, "EISD at 0x%x size 0x%x addr 0x%lx flags 0x%x blk %d\n",
offset, size, (unsigned long)vaddr, flags, vbn));
/* VMS combines psects from .obj files into isects in the .exe. This
process doesn't preserve enough information to reliably determine
what's in each section without examining the data. This is
especially true of DWARF debug sections. */
bfd_flags = SEC_ALLOC;
if (vbn != 0)
bfd_flags |= SEC_HAS_CONTENTS | SEC_LOAD;
if (flags & EISD__M_EXE)
bfd_flags |= SEC_CODE;
if (flags & EISD__M_NONSHRADR)
bfd_flags |= SEC_DATA;
if (!(flags & EISD__M_WRT))
bfd_flags |= SEC_READONLY;
if (flags & EISD__M_DZRO)
bfd_flags |= SEC_DATA;
if (flags & EISD__M_FIXUPVEC)
bfd_flags |= SEC_DATA;
if (flags & EISD__M_CRF)
bfd_flags |= SEC_DATA;
if (flags & EISD__M_GBL)
{
name = _bfd_vms_save_counted_string (eisd->gblnam);
bfd_flags |= SEC_COFF_SHARED_LIBRARY;
bfd_flags &= ~(SEC_ALLOC | SEC_LOAD);
}
else if (flags & EISD__M_FIXUPVEC)
name = "$FIXUPVEC$";
else if (eisd->type == EISD__K_USRSTACK)
name = "$STACK$";
else
{
const char *pfx;
name = (char*) bfd_alloc (abfd, 32);
if (flags & EISD__M_DZRO)
pfx = "BSS";
else if (flags & EISD__M_EXE)
pfx = "CODE";
else if (!(flags & EISD__M_WRT))
pfx = "RO";
else
pfx = "LOCAL";
BFD_ASSERT (section_count < 999);
sprintf (name, "$%s_%03d$", pfx, section_count++);
}
section = bfd_make_section (abfd, name);
if (!section)
return FALSE;
section->filepos = vbn ? VMS_BLOCK_SIZE * (vbn - 1) : 0;
section->size = size;
section->vma = vaddr;
if (!bfd_set_section_flags (abfd, section, bfd_flags))
return FALSE;
}
return TRUE;
}
/* Read & process EIHS record.
Return TRUE on success, FALSE on error. */
static bfd_boolean
_bfd_vms_slurp_eihs (bfd *abfd, unsigned int offset)
{
unsigned char *p = PRIV (recrd.rec) + offset;
unsigned int gstvbn = bfd_getl32 (p + EIHS__L_GSTVBN);
unsigned int gstsize ATTRIBUTE_UNUSED = bfd_getl32 (p + EIHS__L_GSTSIZE);
unsigned int dstvbn = bfd_getl32 (p + EIHS__L_DSTVBN);
unsigned int dstsize = bfd_getl32 (p + EIHS__L_DSTSIZE);
unsigned int dmtvbn = bfd_getl32 (p + EIHS__L_DMTVBN);
unsigned int dmtbytes = bfd_getl32 (p + EIHS__L_DMTBYTES);
asection *section;
#if VMS_DEBUG
vms_debug (8, "_bfd_vms_slurp_ihs\n");
vms_debug (4, "EIHS record gstvbn %d gstsize %d dstvbn %d dstsize %d dmtvbn %d dmtbytes %d\n",
gstvbn, gstsize, dstvbn, dstsize, dmtvbn, dmtbytes);
#endif
if (dstvbn)
{
flagword bfd_flags = SEC_HAS_CONTENTS | SEC_DEBUGGING;
section = bfd_make_section (abfd, "$DST$");
if (!section)
return FALSE;
section->size = dstsize;
section->filepos = VMS_BLOCK_SIZE * (dstvbn - 1);
if (!bfd_set_section_flags (abfd, section, bfd_flags))
return FALSE;
PRIV (dst_section) = section;
abfd->flags |= (HAS_DEBUG | HAS_LINENO);
}
if (dmtvbn)
{
flagword bfd_flags = SEC_HAS_CONTENTS | SEC_DEBUGGING;
section = bfd_make_section (abfd, "$DMT$");
if (!section)
return FALSE;
section->size = dmtbytes;
section->filepos = VMS_BLOCK_SIZE * (dmtvbn - 1);
if (!bfd_set_section_flags (abfd, section, bfd_flags))
return FALSE;
}
if (gstvbn)
{
if (bfd_seek (abfd, VMS_BLOCK_SIZE * (gstvbn - 1), SEEK_SET))
{
bfd_set_error (bfd_error_file_truncated);
return FALSE;
}
if (_bfd_vms_slurp_object_records (abfd) != TRUE)
return FALSE;
abfd->flags |= HAS_SYMS;
}
return TRUE;
}
/* Object file reading. */
/* Object file input functions. */
/* Get next record from object file to vms_buf.
Set PRIV(buf_size) and return it
This is a little tricky since it should be portable.
The openVMS object file has 'variable length' which means that
read() returns data in chunks of (hopefully) correct and expected
size. The linker (and other tools on VMS) depend on that. Unix
doesn't know about 'formatted' files, so reading and writing such
an object file in a Unix environment is not trivial.
With the tool 'file' (available on all VMS FTP sites), one
can view and change the attributes of a file. Changing from
'variable length' to 'fixed length, 512 bytes' reveals the
record size at the first 2 bytes of every record. The same
may happen during the transfer of object files from VMS to Unix,
at least with UCX, the DEC implementation of TCP/IP.
The VMS format repeats the size at bytes 2 & 3 of every record.
On the first call (file_format == FF_UNKNOWN) we check if
the first and the third byte pair (!) of the record match.
If they do it's an object file in an Unix environment or with
wrong attributes (FF_FOREIGN), else we should be in a VMS
environment where read() returns the record size (FF_NATIVE).
Reading is always done in 2 steps:
1. first just the record header is read and the size extracted,
2. then the read buffer is adjusted and the remaining bytes are
read in.
All file I/O is done on even file positions. */
#define VMS_OBJECT_ADJUSTMENT 2
static void
maybe_adjust_record_pointer_for_object (bfd *abfd)
{
/* Set the file format once for all on the first invocation. */
if (PRIV (recrd.file_format) == FF_UNKNOWN)
{
if (PRIV (recrd.rec)[0] == PRIV (recrd.rec)[4]
&& PRIV (recrd.rec)[1] == PRIV (recrd.rec)[5])
PRIV (recrd.file_format) = FF_FOREIGN;
else
PRIV (recrd.file_format) = FF_NATIVE;
}
/* The adjustment is needed only in an Unix environment. */
if (PRIV (recrd.file_format) == FF_FOREIGN)
PRIV (recrd.rec) += VMS_OBJECT_ADJUSTMENT;
}
/* Implement step #1 of the object record reading procedure.
Return the record type or -1 on failure. */
static int
_bfd_vms_get_object_record (bfd *abfd)
{
unsigned int test_len = 6;
int type;
vms_debug2 ((8, "_bfd_vms_get_obj_record\n"));
/* Skip alignment byte if the current position is odd. */
if (PRIV (recrd.file_format) == FF_FOREIGN && (bfd_tell (abfd) & 1))
{
if (bfd_bread (PRIV (recrd.buf), 1, abfd) != 1)
{
bfd_set_error (bfd_error_file_truncated);
return -1;
}
}
/* Read the record header */
if (bfd_bread (PRIV (recrd.buf), test_len, abfd) != test_len)
{
bfd_set_error (bfd_error_file_truncated);
return -1;
}
/* Reset the record pointer. */
PRIV (recrd.rec) = PRIV (recrd.buf);
maybe_adjust_record_pointer_for_object (abfd);
if (vms_get_remaining_object_record (abfd, test_len) <= 0)
return -1;
type = bfd_getl16 (PRIV (recrd.rec));
vms_debug2 ((8, "_bfd_vms_get_obj_record: rec %p, size %d, type %d\n",
PRIV (recrd.rec), PRIV (recrd.rec_size), type));
return type;
}
/* Implement step #2 of the object record reading procedure.
Return the size of the record or 0 on failure. */
static int
vms_get_remaining_object_record (bfd *abfd, unsigned int read_so_far)
{
unsigned int to_read;
vms_debug2 ((8, "vms_get_remaining_obj_record\n"));
/* Extract record size. */
PRIV (recrd.rec_size) = bfd_getl16 (PRIV (recrd.rec) + 2);
if (PRIV (recrd.rec_size) == 0)
{
bfd_set_error (bfd_error_file_truncated);
return 0;
}
/* That's what the linker manual says. */
if (PRIV (recrd.rec_size) > EOBJ__C_MAXRECSIZ)
{
bfd_set_error (bfd_error_file_truncated);
return 0;
}
/* Take into account object adjustment. */
to_read = PRIV (recrd.rec_size);
if (PRIV (recrd.file_format) == FF_FOREIGN)
to_read += VMS_OBJECT_ADJUSTMENT;
/* Adjust the buffer. */
if (to_read > PRIV (recrd.buf_size))
{
PRIV (recrd.buf)
= (unsigned char *) bfd_realloc (PRIV (recrd.buf), to_read);
if (PRIV (recrd.buf) == NULL)
return 0;
PRIV (recrd.buf_size) = to_read;
}
/* PR 17512: file: 025-1974-0.004. */
else if (to_read <= read_so_far)
return 0;
/* Read the remaining record. */
to_read -= read_so_far;
vms_debug2 ((8, "vms_get_remaining_obj_record: to_read %d\n", to_read));
if (bfd_bread (PRIV (recrd.buf) + read_so_far, to_read, abfd) != to_read)
{
bfd_set_error (bfd_error_file_truncated);
return 0;
}
/* Reset the record pointer. */
PRIV (recrd.rec) = PRIV (recrd.buf);
maybe_adjust_record_pointer_for_object (abfd);
vms_debug2 ((8, "vms_get_remaining_obj_record: size %d\n",
PRIV (recrd.rec_size)));
return PRIV (recrd.rec_size);
}
/* Read and process emh record.
Return TRUE on success, FALSE on error. */
static bfd_boolean
_bfd_vms_slurp_ehdr (bfd *abfd)
{
unsigned char *ptr;
unsigned char *vms_rec;
unsigned char *end;
int subtype;
vms_rec = PRIV (recrd.rec);
/* PR 17512: file: 62736583. */
end = PRIV (recrd.buf) + PRIV (recrd.buf_size);
vms_debug2 ((2, "HDR/EMH\n"));
subtype = bfd_getl16 (vms_rec + 4);
vms_debug2 ((3, "subtype %d\n", subtype));
switch (subtype)
{
case EMH__C_MHD:
/* Module header. */
if (vms_rec + 21 >= end)
goto fail;
PRIV (hdr_data).hdr_b_strlvl = vms_rec[6];
PRIV (hdr_data).hdr_l_arch1 = bfd_getl32 (vms_rec + 8);
PRIV (hdr_data).hdr_l_arch2 = bfd_getl32 (vms_rec + 12);
PRIV (hdr_data).hdr_l_recsiz = bfd_getl32 (vms_rec + 16);
if ((vms_rec + 20 + vms_rec[20] + 1) >= end)
goto fail;
PRIV (hdr_data).hdr_t_name = _bfd_vms_save_counted_string (vms_rec + 20);
ptr = vms_rec + 20 + vms_rec[20] + 1;
if ((ptr + *ptr + 1) >= end)
goto fail;
PRIV (hdr_data).hdr_t_version =_bfd_vms_save_counted_string (ptr);
ptr += *ptr + 1;
if (ptr + 17 >= end)
goto fail;
PRIV (hdr_data).hdr_t_date = _bfd_vms_save_sized_string (ptr, 17);
break;
case EMH__C_LNM:
if (vms_rec + PRIV (recrd.rec_size - 6) > end)
goto fail;
PRIV (hdr_data).hdr_c_lnm =
_bfd_vms_save_sized_string (vms_rec, PRIV (recrd.rec_size - 6));
break;
case EMH__C_SRC:
if (vms_rec + PRIV (recrd.rec_size - 6) > end)
goto fail;
PRIV (hdr_data).hdr_c_src =
_bfd_vms_save_sized_string (vms_rec, PRIV (recrd.rec_size - 6));
break;
case EMH__C_TTL:
if (vms_rec + PRIV (recrd.rec_size - 6) > end)
goto fail;
PRIV (hdr_data).hdr_c_ttl =
_bfd_vms_save_sized_string (vms_rec, PRIV (recrd.rec_size - 6));
break;
case EMH__C_CPR:
case EMH__C_MTC:
case EMH__C_GTX:
break;
default:
fail:
bfd_set_error (bfd_error_wrong_format);
return FALSE;
}
return TRUE;
}
/* Typical sections for evax object files. */
#define EVAX_ABS_NAME "$ABS$"
#define EVAX_CODE_NAME "$CODE$"
#define EVAX_LINK_NAME "$LINK$"
#define EVAX_DATA_NAME "$DATA$"
#define EVAX_BSS_NAME "$BSS$"
#define EVAX_READONLYADDR_NAME "$READONLY_ADDR$"
#define EVAX_READONLY_NAME "$READONLY$"
#define EVAX_LITERAL_NAME "$LITERAL$"
#define EVAX_LITERALS_NAME "$LITERALS"
#define EVAX_COMMON_NAME "$COMMON$"
#define EVAX_LOCAL_NAME "$LOCAL$"
struct sec_flags_struct
{
const char *name; /* Name of section. */
int vflags_always;
flagword flags_always; /* Flags we set always. */
int vflags_hassize;
flagword flags_hassize; /* Flags we set if the section has a size > 0. */
};
/* These flags are deccrtl/vaxcrtl (openVMS 6.2 Alpha) compatible. */
static const struct sec_flags_struct evax_section_flags[] =
{
{ EVAX_ABS_NAME,
EGPS__V_SHR,
0,
EGPS__V_SHR,
0 },
{ EVAX_CODE_NAME,
EGPS__V_PIC | EGPS__V_REL | EGPS__V_SHR | EGPS__V_EXE,
SEC_CODE | SEC_READONLY,
EGPS__V_PIC | EGPS__V_REL | EGPS__V_SHR | EGPS__V_EXE,
SEC_CODE | SEC_READONLY | SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD },
{ EVAX_LITERAL_NAME,
EGPS__V_PIC | EGPS__V_REL | EGPS__V_SHR | EGPS__V_RD | EGPS__V_NOMOD,
SEC_DATA | SEC_READONLY,
EGPS__V_PIC | EGPS__V_REL | EGPS__V_SHR | EGPS__V_RD,
SEC_DATA | SEC_READONLY | SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD },
{ EVAX_LINK_NAME,
EGPS__V_REL | EGPS__V_RD,
SEC_DATA | SEC_READONLY,
EGPS__V_REL | EGPS__V_RD,
SEC_DATA | SEC_READONLY | SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD },
{ EVAX_DATA_NAME,
EGPS__V_REL | EGPS__V_RD | EGPS__V_WRT | EGPS__V_NOMOD,
SEC_DATA,
EGPS__V_REL | EGPS__V_RD | EGPS__V_WRT,
SEC_DATA | SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD },
{ EVAX_BSS_NAME,
EGPS__V_REL | EGPS__V_RD | EGPS__V_WRT | EGPS__V_NOMOD,
SEC_NO_FLAGS,
EGPS__V_REL | EGPS__V_RD | EGPS__V_WRT | EGPS__V_NOMOD,
SEC_ALLOC },
{ EVAX_READONLYADDR_NAME,
EGPS__V_PIC | EGPS__V_REL | EGPS__V_RD,
SEC_DATA | SEC_READONLY,
EGPS__V_PIC | EGPS__V_REL | EGPS__V_RD,
SEC_DATA | SEC_READONLY | SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD },
{ EVAX_READONLY_NAME,
EGPS__V_PIC | EGPS__V_REL | EGPS__V_SHR | EGPS__V_RD | EGPS__V_NOMOD,
SEC_DATA | SEC_READONLY,
EGPS__V_PIC | EGPS__V_REL | EGPS__V_SHR | EGPS__V_RD,
SEC_DATA | SEC_READONLY | SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD },
{ EVAX_LOCAL_NAME,
EGPS__V_REL | EGPS__V_RD | EGPS__V_WRT,
SEC_DATA,
EGPS__V_REL | EGPS__V_RD | EGPS__V_WRT,
SEC_DATA | SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD },
{ EVAX_LITERALS_NAME,
EGPS__V_PIC | EGPS__V_OVR,
SEC_DATA | SEC_READONLY,
EGPS__V_PIC | EGPS__V_OVR,
SEC_DATA | SEC_READONLY | SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD },
{ NULL,
EGPS__V_REL | EGPS__V_RD | EGPS__V_WRT,
SEC_DATA,
EGPS__V_REL | EGPS__V_RD | EGPS__V_WRT,
SEC_DATA | SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD }
};
/* Retrieve BFD section flags by name and size. */
static flagword
vms_secflag_by_name (const struct sec_flags_struct *section_flags,
const char *name,
int hassize)
{
int i = 0;
while (section_flags[i].name != NULL)
{
if (strcmp (name, section_flags[i].name) == 0)
{
if (hassize)
return section_flags[i].flags_hassize;
else
return section_flags[i].flags_always;
}
i++;
}
if (hassize)
return section_flags[i].flags_hassize;
return section_flags[i].flags_always;
}
/* Retrieve VMS section flags by name and size. */
static flagword
vms_esecflag_by_name (const struct sec_flags_struct *section_flags,
const char *name,
int hassize)
{
int i = 0;
while (section_flags[i].name != NULL)
{
if (strcmp (name, section_flags[i].name) == 0)
{
if (hassize)
return section_flags[i].vflags_hassize;
else
return section_flags[i].vflags_always;
}
i++;
}
if (hassize)
return section_flags[i].vflags_hassize;
return section_flags[i].vflags_always;
}
/* Add SYM to the symbol table of ABFD.
Return FALSE in case of error. */
static bfd_boolean
add_symbol_entry (bfd *abfd, struct vms_symbol_entry *sym)
{
if (PRIV (gsd_sym_count) >= PRIV (max_sym_count))
{
if (PRIV (max_sym_count) == 0)
{
PRIV (max_sym_count) = 128;
PRIV (syms) = bfd_malloc
(PRIV (max_sym_count) * sizeof (struct vms_symbol_entry *));
}
else
{
PRIV (max_sym_count) *= 2;
PRIV (syms) = bfd_realloc
(PRIV (syms),
(PRIV (max_sym_count) * sizeof (struct vms_symbol_entry *)));
}
if (PRIV (syms) == NULL)
return FALSE;
}
PRIV (syms)[PRIV (gsd_sym_count)++] = sym;
return TRUE;
}
/* Create a symbol whose name is ASCIC and add it to ABFD.
Return NULL in case of error. */
static struct vms_symbol_entry *
add_symbol (bfd *abfd, const unsigned char *ascic)
{
struct vms_symbol_entry *entry;
int len;
len = *ascic++;
entry = (struct vms_symbol_entry *)bfd_zalloc (abfd, sizeof (*entry) + len);
if (entry == NULL)
return NULL;
entry->namelen = len;
memcpy (entry->name, ascic, len);
entry->name[len] = 0;
entry->owner = abfd;
if (!add_symbol_entry (abfd, entry))
return NULL;
return entry;
}
/* Read and process EGSD. Return FALSE on failure. */
static bfd_boolean
_bfd_vms_slurp_egsd (bfd *abfd)
{
int gsd_type, gsd_size;
unsigned char *vms_rec;
unsigned long base_addr;
vms_debug2 ((2, "EGSD\n"));
PRIV (recrd.rec) += 8; /* Skip type, size, align pad. */
PRIV (recrd.rec_size) -= 8;
/* Calculate base address for each section. */
base_addr = 0L;
while (PRIV (recrd.rec_size) > 0)
{
vms_rec = PRIV (recrd.rec);
gsd_type = bfd_getl16 (vms_rec);
gsd_size = bfd_getl16 (vms_rec + 2);
vms_debug2 ((3, "egsd_type %d\n", gsd_type));
switch (gsd_type)
{
case EGSD__C_PSC:
/* Program section definition. */
{
struct vms_egps *egps = (struct vms_egps *)vms_rec;
flagword new_flags, vms_flags;
asection *section;
vms_flags = bfd_getl16 (egps->flags);
if ((vms_flags & EGPS__V_REL) == 0)
{
/* Use the global absolute section for all
absolute sections. */
section = bfd_abs_section_ptr;
}
else
{
char *name;
unsigned long align_addr;
name = _bfd_vms_save_counted_string (&egps->namlng);
section = bfd_make_section (abfd, name);
if (!section)
return FALSE;
section->filepos = 0;
section->size = bfd_getl32 (egps->alloc);
section->alignment_power = egps->align;
vms_section_data (section)->flags = vms_flags;
vms_section_data (section)->no_flags = 0;
new_flags = vms_secflag_by_name (evax_section_flags, name,
section->size > 0);
if (section->size > 0)
new_flags |= SEC_LOAD;
if (!(vms_flags & EGPS__V_NOMOD) && section->size > 0)
{
/* Set RELOC and HAS_CONTENTS if the section is not
demand-zero and not empty. */
new_flags |= SEC_HAS_CONTENTS;
if (vms_flags & EGPS__V_REL)
new_flags |= SEC_RELOC;
}
if (vms_flags & EGPS__V_EXE)
{
/* Set CODE if section is executable. */
new_flags |= SEC_CODE;
new_flags &= ~SEC_DATA;
}
if (!bfd_set_section_flags (abfd, section, new_flags))
return FALSE;
/* Give a non-overlapping vma to non absolute sections. */
align_addr = (1 << section->alignment_power);
if ((base_addr % align_addr) != 0)
base_addr += (align_addr - (base_addr % align_addr));
section->vma = (bfd_vma)base_addr;
base_addr += section->size;
}
/* Append it to the section array. */
if (PRIV (section_count) >= PRIV (section_max))
{
if (PRIV (section_max) == 0)
PRIV (section_max) = 16;
else
PRIV (section_max) *= 2;
PRIV (sections) = bfd_realloc_or_free
(PRIV (sections), PRIV (section_max) * sizeof (asection *));
if (PRIV (sections) == NULL)
return FALSE;
}
PRIV (sections)[PRIV (section_count)] = section;
PRIV (section_count)++;
}
break;
case EGSD__C_SYM:
{
int nameoff;
struct vms_symbol_entry *entry;
struct vms_egsy *egsy = (struct vms_egsy *) vms_rec;
flagword old_flags;
old_flags = bfd_getl16 (egsy->flags);
if (old_flags & EGSY__V_DEF)
nameoff = ESDF__B_NAMLNG;
else
nameoff = ESRF__B_NAMLNG;
entry = add_symbol (abfd, vms_rec + nameoff);
if (entry == NULL)
return FALSE;
/* Allow only duplicate reference. */
if ((entry->flags & EGSY__V_DEF) && (old_flags & EGSY__V_DEF))
abort ();
if (entry->typ == 0)
{
entry->typ = gsd_type;
entry->data_type = egsy->datyp;
entry->flags = old_flags;
}
if (old_flags & EGSY__V_DEF)
{
struct vms_esdf *esdf = (struct vms_esdf *)vms_rec;
entry->value = bfd_getl64 (esdf->value);
entry->section = PRIV (sections)[bfd_getl32 (esdf->psindx)];
if (old_flags & EGSY__V_NORM)
{
PRIV (norm_sym_count)++;
entry->code_value = bfd_getl64 (esdf->code_address);
entry->code_section =
PRIV (sections)[bfd_getl32 (esdf->ca_psindx)];
}
}
}
break;
case EGSD__C_SYMG:
{
struct vms_symbol_entry *entry;
struct vms_egst *egst = (struct vms_egst *)vms_rec;
flagword old_flags;
old_flags = bfd_getl16 (egst->header.flags);
entry = add_symbol (abfd, &egst->namlng);
if (entry == NULL)
return FALSE;
entry->typ = gsd_type;
entry->data_type = egst->header.datyp;
entry->flags = old_flags;
entry->symbol_vector = bfd_getl32 (egst->value);
if (old_flags & EGSY__V_REL)
entry->section = PRIV (sections)[bfd_getl32 (egst->psindx)];
else
entry->section = bfd_abs_section_ptr;
entry->value = bfd_getl64 (egst->lp_2);
if (old_flags & EGSY__V_NORM)
{
PRIV (norm_sym_count)++;
entry->code_value = bfd_getl64 (egst->lp_1);
entry->code_section = bfd_abs_section_ptr;
}
}
break;
case EGSD__C_SPSC:
case EGSD__C_IDC:
/* Currently ignored. */
break;
case EGSD__C_SYMM:
case EGSD__C_SYMV:
default:
(*_bfd_error_handler) (_("Unknown EGSD subtype %d"), gsd_type);
bfd_set_error (bfd_error_bad_value);
return FALSE;
}
PRIV (recrd.rec_size) -= gsd_size;
PRIV (recrd.rec) += gsd_size;
}
if (PRIV (gsd_sym_count) > 0)
abfd->flags |= HAS_SYMS;
return TRUE;
}
/* Stack routines for vms ETIR commands. */
/* Push value and section index. */
static void
_bfd_vms_push (bfd *abfd, bfd_vma val, unsigned int reloc)
{
vms_debug2 ((4, "<push %08lx (0x%08x) at %d>\n",
(unsigned long)val, reloc, PRIV (stackptr)));
PRIV (stack[PRIV (stackptr)]).value = val;
PRIV (stack[PRIV (stackptr)]).reloc = reloc;
PRIV (stackptr)++;
if (PRIV (stackptr) >= STACKSIZE)
{
bfd_set_error (bfd_error_bad_value);
(*_bfd_error_handler) (_("Stack overflow (%d) in _bfd_vms_push"), PRIV (stackptr));
exit (1);
}
}
/* Pop value and section index. */
static void
_bfd_vms_pop (bfd *abfd, bfd_vma *val, unsigned int *rel)
{
if (PRIV (stackptr) == 0)
{
bfd_set_error (bfd_error_bad_value);
(*_bfd_error_handler) (_("Stack underflow in _bfd_vms_pop"));
exit (1);
}
PRIV (stackptr)--;
*val = PRIV (stack[PRIV (stackptr)]).value;
*rel = PRIV (stack[PRIV (stackptr)]).reloc;
vms_debug2 ((4, "<pop %08lx (0x%08x)>\n", (unsigned long)*val, *rel));
}
/* Routines to fill sections contents during tir/etir read. */
/* Initialize image buffer pointer to be filled. */
static void
image_set_ptr (bfd *abfd, bfd_vma vma, int sect, struct bfd_link_info *info)
{
asection *sec;
vms_debug2 ((4, "image_set_ptr (0x%08x, sect=%d)\n", (unsigned)vma, sect));
sec = PRIV (sections)[sect];
if (info)
{
/* Reading contents to an output bfd. */
if (sec->output_section == NULL)
{
/* Section discarded. */
vms_debug2 ((5, " section %s discarded\n", sec->name));
/* This is not used. */
PRIV (image_section) = NULL;
PRIV (image_offset) = 0;
return;
}
PRIV (image_offset) = sec->output_offset + vma;
PRIV (image_section) = sec->output_section;
}
else
{
PRIV (image_offset) = vma;
PRIV (image_section) = sec;
}
}
/* Increment image buffer pointer by offset. */
static void
image_inc_ptr (bfd *abfd, bfd_vma offset)
{
vms_debug2 ((4, "image_inc_ptr (%u)\n", (unsigned)offset));
PRIV (image_offset) += offset;
}
/* Save current DST location counter under specified index. */
static void
dst_define_location (bfd *abfd, unsigned int loc)
{
vms_debug2 ((4, "dst_define_location (%d)\n", (int)loc));
/* Grow the ptr offset table if necessary. */
if (loc + 1 > PRIV (dst_ptr_offsets_count))
{
PRIV (dst_ptr_offsets) = bfd_realloc (PRIV (dst_ptr_offsets),
(loc + 1) * sizeof (unsigned int));
PRIV (dst_ptr_offsets_count) = loc + 1;
}
PRIV (dst_ptr_offsets)[loc] = PRIV (image_offset);
}
/* Restore saved DST location counter from specified index. */
static void
dst_restore_location (bfd *abfd, unsigned int loc)
{
vms_debug2 ((4, "dst_restore_location (%d)\n", (int)loc));
PRIV (image_offset) = PRIV (dst_ptr_offsets)[loc];
}
/* Retrieve saved DST location counter from specified index. */
static unsigned int
dst_retrieve_location (bfd *abfd, unsigned int loc)
{
vms_debug2 ((4, "dst_retrieve_location (%d)\n", (int)loc));
return PRIV (dst_ptr_offsets)[loc];
}
/* Write multiple bytes to section image. */
static bfd_boolean
image_write (bfd *abfd, unsigned char *ptr, int size)
{
#if VMS_DEBUG
_bfd_vms_debug (8, "image_write from (%p, %d) to (%ld)\n", ptr, size,
(long)PRIV (image_offset));
_bfd_hexdump (9, ptr, size, 0);
#endif
if (PRIV (image_section)->contents != NULL)
{
asection *sec = PRIV (image_section);
file_ptr off = PRIV (image_offset);
/* Check bounds. */
if (off > (file_ptr)sec->size
|| size > (file_ptr)sec->size
|| off + size > (file_ptr)sec->size)
{
bfd_set_error (bfd_error_bad_value);
return FALSE;
}
memcpy (sec->contents + off, ptr, size);
}
PRIV (image_offset) += size;
return TRUE;
}
/* Write byte to section image. */
static bfd_boolean
image_write_b (bfd * abfd, unsigned int value)
{
unsigned char data[1];
vms_debug2 ((6, "image_write_b (%02x)\n", (int) value));
*data = value;
return image_write (abfd, data, sizeof (data));
}
/* Write 2-byte word to image. */
static bfd_boolean
image_write_w (bfd * abfd, unsigned int value)
{
unsigned char data[2];
vms_debug2 ((6, "image_write_w (%04x)\n", (int) value));
bfd_putl16 (value, data);
return image_write (abfd, data, sizeof (data));
}
/* Write 4-byte long to image. */
static bfd_boolean
image_write_l (bfd * abfd, unsigned long value)
{
unsigned char data[4];
vms_debug2 ((6, "image_write_l (%08lx)\n", value));
bfd_putl32 (value, data);
return image_write (abfd, data, sizeof (data));
}
/* Write 8-byte quad to image. */
static bfd_boolean
image_write_q (bfd * abfd, bfd_vma value)
{
unsigned char data[8];
vms_debug2 ((6, "image_write_q (%08lx)\n", (unsigned long)value));
bfd_putl64 (value, data);
return image_write (abfd, data, sizeof (data));
}
static const char *
_bfd_vms_etir_name (int cmd)
{
switch (cmd)
{
case ETIR__C_STA_GBL: return "ETIR__C_STA_GBL";
case ETIR__C_STA_LW: return "ETIR__C_STA_LW";
case ETIR__C_STA_QW: return "ETIR__C_STA_QW";
case ETIR__C_STA_PQ: return "ETIR__C_STA_PQ";
case ETIR__C_STA_LI: return "ETIR__C_STA_LI";
case ETIR__C_STA_MOD: return "ETIR__C_STA_MOD";
case ETIR__C_STA_CKARG: return "ETIR__C_STA_CKARG";
case ETIR__C_STO_B: return "ETIR__C_STO_B";
case ETIR__C_STO_W: return "ETIR__C_STO_W";
case ETIR__C_STO_GBL: return "ETIR__C_STO_GBL";
case ETIR__C_STO_CA: return "ETIR__C_STO_CA";
case ETIR__C_STO_RB: return "ETIR__C_STO_RB";
case ETIR__C_STO_AB: return "ETIR__C_STO_AB";
case ETIR__C_STO_OFF: return "ETIR__C_STO_OFF";
case ETIR__C_STO_IMM: return "ETIR__C_STO_IMM";
case ETIR__C_STO_IMMR: return "ETIR__C_STO_IMMR";
case ETIR__C_STO_LW: return "ETIR__C_STO_LW";
case ETIR__C_STO_QW: return "ETIR__C_STO_QW";
case ETIR__C_STO_GBL_LW: return "ETIR__C_STO_GBL_LW";
case ETIR__C_STO_LP_PSB: return "ETIR__C_STO_LP_PSB";
case ETIR__C_STO_HINT_GBL: return "ETIR__C_STO_HINT_GBL";
case ETIR__C_STO_HINT_PS: return "ETIR__C_STO_HINT_PS";
case ETIR__C_OPR_ADD: return "ETIR__C_OPR_ADD";
case ETIR__C_OPR_SUB: return "ETIR__C_OPR_SUB";
case ETIR__C_OPR_INSV: return "ETIR__C_OPR_INSV";
case ETIR__C_OPR_USH: return "ETIR__C_OPR_USH";
case ETIR__C_OPR_ROT: return "ETIR__C_OPR_ROT";
case ETIR__C_OPR_REDEF: return "ETIR__C_OPR_REDEF";
case ETIR__C_OPR_DFLIT: return "ETIR__C_OPR_DFLIT";
case ETIR__C_STC_LP: return "ETIR__C_STC_LP";
case ETIR__C_STC_GBL: return "ETIR__C_STC_GBL";
case ETIR__C_STC_GCA: return "ETIR__C_STC_GCA";
case ETIR__C_STC_PS: return "ETIR__C_STC_PS";
case ETIR__C_STC_NBH_PS: return "ETIR__C_STC_NBH_PS";
case ETIR__C_STC_NOP_GBL: return "ETIR__C_STC_NOP_GBL";
case ETIR__C_STC_NOP_PS: return "ETIR__C_STC_NOP_PS";
case ETIR__C_STC_BSR_GBL: return "ETIR__C_STC_BSR_GBL";
case ETIR__C_STC_BSR_PS: return "ETIR__C_STC_BSR_PS";
case ETIR__C_STC_LDA_GBL: return "ETIR__C_STC_LDA_GBL";
case ETIR__C_STC_LDA_PS: return "ETIR__C_STC_LDA_PS";
case ETIR__C_STC_BOH_GBL: return "ETIR__C_STC_BOH_GBL";
case ETIR__C_STC_BOH_PS: return "ETIR__C_STC_BOH_PS";
case ETIR__C_STC_NBH_GBL: return "ETIR__C_STC_NBH_GBL";
case ETIR__C_STC_LP_PSB: return "ETIR__C_STC_LP_PSB";
case ETIR__C_CTL_SETRB: return "ETIR__C_CTL_SETRB";
case ETIR__C_CTL_AUGRB: return "ETIR__C_CTL_AUGRB";
case ETIR__C_CTL_DFLOC: return "ETIR__C_CTL_DFLOC";
case ETIR__C_CTL_STLOC: return "ETIR__C_CTL_STLOC";
case ETIR__C_CTL_STKDL: return "ETIR__C_CTL_STKDL";
default:
/* These names have not yet been added to this switch statement. */
(*_bfd_error_handler) (_("unknown ETIR command %d"), cmd);
}
return NULL;
}
#define HIGHBIT(op) ((op & 0x80000000L) == 0x80000000L)
static void
_bfd_vms_get_value (bfd *abfd, const unsigned char *ascic,
struct bfd_link_info *info,
bfd_vma *vma,
struct alpha_vms_link_hash_entry **hp)
{
char name[257];
int len;
int i;
struct alpha_vms_link_hash_entry *h;
/* Not linking. Do not try to resolve the symbol. */
if (info == NULL)
{
*vma = 0;
*hp = NULL;
return;
}
len = *ascic;
for (i = 0; i < len; i++)
name[i] = ascic[i + 1];
name[i] = 0;
h = (struct alpha_vms_link_hash_entry *)
bfd_link_hash_lookup (info->hash, name, FALSE, FALSE, TRUE);
*hp = h;
if (h != NULL
&& (h->root.type == bfd_link_hash_defined
|| h->root.type == bfd_link_hash_defweak))
*vma = h->root.u.def.value
+ h->root.u.def.section->output_offset
+ h->root.u.def.section->output_section->vma;
else if (h && h->root.type == bfd_link_hash_undefweak)
*vma = 0;
else
{
if (!(*info->callbacks->undefined_symbol)
(info, name, abfd, PRIV (image_section), PRIV (image_offset), TRUE))
abort ();
*vma = 0;
}
}
#define RELC_NONE 0
#define RELC_REL 1
#define RELC_SHR_BASE 0x10000
#define RELC_SEC_BASE 0x20000
#define RELC_MASK 0x0ffff
static unsigned int
alpha_vms_sym_to_ctxt (struct alpha_vms_link_hash_entry *h)
{
/* Handle undefined symbols. */
if (h == NULL || h->sym == NULL)
return RELC_NONE;
if (h->sym->typ == EGSD__C_SYMG)
{
if (h->sym->flags & EGSY__V_REL)
return RELC_SHR_BASE + PRIV2 (h->sym->owner, shr_index);
else
{
/* Can this happen (non-relocatable symg) ? I'd like to see
an example. */
abort ();
}
}
if (h->sym->typ == EGSD__C_SYM)
{
if (h->sym->flags & EGSY__V_REL)
return RELC_REL;
else
return RELC_NONE;
}
abort ();
}
static bfd_vma
alpha_vms_get_sym_value (asection *sect, bfd_vma addr)
{
return sect->output_section->vma + sect->output_offset + addr;
}
static bfd_vma
alpha_vms_fix_sec_rel (bfd *abfd, struct bfd_link_info *info,
unsigned int rel, bfd_vma vma)
{
asection *sec = PRIV (sections)[rel & RELC_MASK];
if (info)
{
if (sec->output_section == NULL)
abort ();
return vma + sec->output_section->vma + sec->output_offset;
}
else
return vma + sec->vma;
}
/* Read an ETIR record from ABFD. If INFO is not null, put the content into
the output section (used during linking).
Return FALSE in case of error. */
static bfd_boolean
_bfd_vms_slurp_etir (bfd *abfd, struct bfd_link_info *info)
{
unsigned char *ptr;
unsigned int length;
unsigned char *maxptr;
bfd_vma op1;
bfd_vma op2;
unsigned int rel1;
unsigned int rel2;
struct alpha_vms_link_hash_entry *h;
PRIV (recrd.rec) += ETIR__C_HEADER_SIZE;
PRIV (recrd.rec_size) -= ETIR__C_HEADER_SIZE;
ptr = PRIV (recrd.rec);
length = PRIV (recrd.rec_size);
maxptr = ptr + length;
vms_debug2 ((2, "ETIR: %d bytes\n", length));
while (ptr < maxptr)
{
int cmd = bfd_getl16 (ptr);
int cmd_length = bfd_getl16 (ptr + 2);
ptr += 4;
#if VMS_DEBUG
_bfd_vms_debug (4, "etir: %s(%d)\n",
_bfd_vms_etir_name (cmd), cmd);
_bfd_hexdump (8, ptr, cmd_length - 4, 0);
#endif
switch (cmd)
{
/* Stack global
arg: cs symbol name
stack 32 bit value of symbol (high bits set to 0). */
case ETIR__C_STA_GBL:
_bfd_vms_get_value (abfd, ptr, info, &op1, &h);
_bfd_vms_push (abfd, op1, alpha_vms_sym_to_ctxt (h));
break;
/* Stack longword
arg: lw value
stack 32 bit value, sign extend to 64 bit. */
case ETIR__C_STA_LW:
_bfd_vms_push (abfd, bfd_getl32 (ptr), RELC_NONE);
break;
/* Stack quadword
arg: qw value
stack 64 bit value of symbol. */
case ETIR__C_STA_QW:
_bfd_vms_push (abfd, bfd_getl64 (ptr), RELC_NONE);
break;
/* Stack psect base plus quadword offset
arg: lw section index
qw signed quadword offset (low 32 bits)
Stack qw argument and section index
(see ETIR__C_STO_OFF, ETIR__C_CTL_SETRB). */
case ETIR__C_STA_PQ:
{
int psect;
psect = bfd_getl32 (ptr);
if ((unsigned int) psect >= PRIV (section_count))
{
(*_bfd_error_handler) (_("bad section index in %s"),
_bfd_vms_etir_name (cmd));
bfd_set_error (bfd_error_bad_value);
return FALSE;
}
op1 = bfd_getl64 (ptr + 4);
_bfd_vms_push (abfd, op1, psect | RELC_SEC_BASE);
}
break;
case ETIR__C_STA_LI:
case ETIR__C_STA_MOD:
case ETIR__C_STA_CKARG:
(*_bfd_error_handler) (_("unsupported STA cmd %s"),
_bfd_vms_etir_name (cmd));
return FALSE;
break;
/* Store byte: pop stack, write byte
arg: -. */
case ETIR__C_STO_B:
_bfd_vms_pop (abfd, &op1, &rel1);
if (rel1 != RELC_NONE)
goto bad_context;
image_write_b (abfd, (unsigned int) op1 & 0xff);
break;
/* Store word: pop stack, write word
arg: -. */
case ETIR__C_STO_W:
_bfd_vms_pop (abfd, &op1, &rel1);
if (rel1 != RELC_NONE)
goto bad_context;
image_write_w (abfd, (unsigned int) op1 & 0xffff);
break;
/* Store longword: pop stack, write longword
arg: -. */
case ETIR__C_STO_LW:
_bfd_vms_pop (abfd, &op1, &rel1);
if (rel1 & RELC_SEC_BASE)
{
op1 = alpha_vms_fix_sec_rel (abfd, info, rel1, op1);
rel1 = RELC_REL;
}
else if (rel1 & RELC_SHR_BASE)
{
alpha_vms_add_fixup_lr (info, rel1 & RELC_MASK, op1);
rel1 = RELC_NONE;
}
if (rel1 != RELC_NONE)
{
if (rel1 != RELC_REL)
abort ();
alpha_vms_add_lw_reloc (info);
}
image_write_l (abfd, op1);
break;
/* Store quadword: pop stack, write quadword
arg: -. */
case ETIR__C_STO_QW:
_bfd_vms_pop (abfd, &op1, &rel1);
if (rel1 & RELC_SEC_BASE)
{
op1 = alpha_vms_fix_sec_rel (abfd, info, rel1, op1);
rel1 = RELC_REL;
}
else if (rel1 & RELC_SHR_BASE)
abort ();
if (rel1 != RELC_NONE)
{
if (rel1 != RELC_REL)
abort ();
alpha_vms_add_qw_reloc (info);
}
image_write_q (abfd, op1);
break;
/* Store immediate repeated: pop stack for repeat count
arg: lw byte count
da data. */
case ETIR__C_STO_IMMR:
{
int size;
size = bfd_getl32 (ptr);
_bfd_vms_pop (abfd, &op1, &rel1);
if (rel1 != RELC_NONE)
goto bad_context;
while (op1-- > 0)
image_write (abfd, ptr + 4, size);
}
break;
/* Store global: write symbol value
arg: cs global symbol name. */
case ETIR__C_STO_GBL:
_bfd_vms_get_value (abfd, ptr, info, &op1, &h);
if (h && h->sym)
{
if (h->sym->typ == EGSD__C_SYMG)
{
alpha_vms_add_fixup_qr
(info, abfd, h->sym->owner, h->sym->symbol_vector);
op1 = 0;
}
else
{
op1 = alpha_vms_get_sym_value (h->sym->section,
h->sym->value);
alpha_vms_add_qw_reloc (info);
}
}
image_write_q (abfd, op1);
break;
/* Store code address: write address of entry point
arg: cs global symbol name (procedure). */
case ETIR__C_STO_CA:
_bfd_vms_get_value (abfd, ptr, info, &op1, &h);
if (h && h->sym)
{
if (h->sym->flags & EGSY__V_NORM)
{
/* That's really a procedure. */
if (h->sym->typ == EGSD__C_SYMG)
{
alpha_vms_add_fixup_ca (info, abfd, h->sym->owner);
op1 = h->sym->symbol_vector;
}
else
{
op1 = alpha_vms_get_sym_value (h->sym->code_section,
h->sym->code_value);
alpha_vms_add_qw_reloc (info);
}
}
else
{
/* Symbol is not a procedure. */
abort ();
}
}
image_write_q (abfd, op1);
break;
/* Store offset to psect: pop stack, add low 32 bits to base of psect
arg: none. */
case ETIR__C_STO_OFF:
_bfd_vms_pop (abfd, &op1, &rel1);
if (!(rel1 & RELC_SEC_BASE))
abort ();
op1 = alpha_vms_fix_sec_rel (abfd, info, rel1, op1);
rel1 = RELC_REL;
image_write_q (abfd, op1);
break;
/* Store immediate
arg: lw count of bytes
da data. */
case ETIR__C_STO_IMM:
{
int size;
size = bfd_getl32 (ptr);
image_write (abfd, ptr + 4, size);
}
break;
/* This code is 'reserved to digital' according to the openVMS
linker manual, however it is generated by the DEC C compiler
and defined in the include file.
FIXME, since the following is just a guess
store global longword: store 32bit value of symbol
arg: cs symbol name. */
case ETIR__C_STO_GBL_LW:
_bfd_vms_get_value (abfd, ptr, info, &op1, &h);
#if 0
abort ();
#endif
image_write_l (abfd, op1);
break;
case ETIR__C_STO_RB:
case ETIR__C_STO_AB:
case ETIR__C_STO_LP_PSB:
(*_bfd_error_handler) (_("%s: not supported"),
_bfd_vms_etir_name (cmd));
return FALSE;
break;
case ETIR__C_STO_HINT_GBL:
case ETIR__C_STO_HINT_PS:
(*_bfd_error_handler) (_("%s: not implemented"),
_bfd_vms_etir_name (cmd));
return FALSE;
break;
/* 200 Store-conditional Linkage Pair
arg: none. */
case ETIR__C_STC_LP:
/* 202 Store-conditional Address at global address
lw linkage index
cs global name. */
case ETIR__C_STC_GBL:
/* 203 Store-conditional Code Address at global address
lw linkage index
cs procedure name. */
case ETIR__C_STC_GCA:
/* 204 Store-conditional Address at psect + offset
lw linkage index
lw psect index
qw offset. */
case ETIR__C_STC_PS:
(*_bfd_error_handler) (_("%s: not supported"),
_bfd_vms_etir_name (cmd));
return FALSE;
break;
/* 201 Store-conditional Linkage Pair with Procedure Signature
lw linkage index
cs procedure name
by signature length
da signature. */
case ETIR__C_STC_LP_PSB:
_bfd_vms_get_value (abfd, ptr + 4, info, &op1, &h);
if (h && h->sym)
{
if (h->sym->typ == EGSD__C_SYMG)
{
alpha_vms_add_fixup_lp (info, abfd, h->sym->owner);
op1 = h->sym->symbol_vector;
op2 = 0;
}
else
{
op1 = alpha_vms_get_sym_value (h->sym->code_section,
h->sym->code_value);
op2 = alpha_vms_get_sym_value (h->sym->section,
h->sym->value);
}
}
else
{
/* Undefined symbol. */
op1 = 0;
op2 = 0;
}
image_write_q (abfd, op1);
image_write_q (abfd, op2);
break;
/* 205 Store-conditional NOP at address of global
arg: none. */
case ETIR__C_STC_NOP_GBL:
/* ALPHA_R_NOP */
/* 207 Store-conditional BSR at global address
arg: none. */
case ETIR__C_STC_BSR_GBL:
/* ALPHA_R_BSR */
/* 209 Store-conditional LDA at global address
arg: none. */
case ETIR__C_STC_LDA_GBL:
/* ALPHA_R_LDA */
/* 211 Store-conditional BSR or Hint at global address
arg: none. */
case ETIR__C_STC_BOH_GBL:
/* Currentl ignored. */
break;
/* 213 Store-conditional NOP,BSR or HINT at global address
arg: none. */
case ETIR__C_STC_NBH_GBL:
/* 206 Store-conditional NOP at pect + offset
arg: none. */
case ETIR__C_STC_NOP_PS:
/* 208 Store-conditional BSR at pect + offset
arg: none. */
case ETIR__C_STC_BSR_PS:
/* 210 Store-conditional LDA at psect + offset
arg: none. */
case ETIR__C_STC_LDA_PS:
/* 212 Store-conditional BSR or Hint at pect + offset
arg: none. */
case ETIR__C_STC_BOH_PS:
/* 214 Store-conditional NOP, BSR or HINT at psect + offset
arg: none. */
case ETIR__C_STC_NBH_PS:
(*_bfd_error_handler) ("%s: not supported",
_bfd_vms_etir_name (cmd));
return FALSE;
break;
/* Det relocation base: pop stack, set image location counter
arg: none. */
case ETIR__C_CTL_SETRB:
_bfd_vms_pop (abfd, &op1, &rel1);
if (!(rel1 & RELC_SEC_BASE))
abort ();
image_set_ptr (abfd, op1, rel1 & RELC_MASK, info);
break;
/* Augment relocation base: increment image location counter by offset
arg: lw offset value. */
case ETIR__C_CTL_AUGRB:
op1 = bfd_getl32 (ptr);
image_inc_ptr (abfd, op1);
break;
/* Define location: pop index, save location counter under index
arg: none. */
case ETIR__C_CTL_DFLOC:
_bfd_vms_pop (abfd, &op1, &rel1);
if (rel1 != RELC_NONE)
goto bad_context;
dst_define_location (abfd, op1);
break;
/* Set location: pop index, restore location counter from index
arg: none. */
case ETIR__C_CTL_STLOC:
_bfd_vms_pop (abfd, &op1, &rel1);
if (rel1 != RELC_NONE)
goto bad_context;
dst_restore_location (abfd, op1);
break;
/* Stack defined location: pop index, push location counter from index
arg: none. */
case ETIR__C_CTL_STKDL:
_bfd_vms_pop (abfd, &op1, &rel1);
if (rel1 != RELC_NONE)
goto bad_context;
_bfd_vms_push (abfd, dst_retrieve_location (abfd, op1), RELC_NONE);
break;
case ETIR__C_OPR_NOP: /* No-op. */
break;
case ETIR__C_OPR_ADD: /* Add. */
_bfd_vms_pop (abfd, &op1, &rel1);
_bfd_vms_pop (abfd, &op2, &rel2);
if (rel1 == RELC_NONE && rel2 != RELC_NONE)
rel1 = rel2;
else if (rel1 != RELC_NONE && rel2 != RELC_NONE)
goto bad_context;
_bfd_vms_push (abfd, op1 + op2, rel1);
break;
case ETIR__C_OPR_SUB: /* Subtract. */
_bfd_vms_pop (abfd, &op1, &rel1);
_bfd_vms_pop (abfd, &op2, &rel2);
if (rel1 == RELC_NONE && rel2 != RELC_NONE)
rel1 = rel2;
else if ((rel1 & RELC_SEC_BASE) && (rel2 & RELC_SEC_BASE))
{
op1 = alpha_vms_fix_sec_rel (abfd, info, rel1, op1);
op2 = alpha_vms_fix_sec_rel (abfd, info, rel2, op2);
rel1 = RELC_NONE;
}
else if (rel1 != RELC_NONE && rel2 != RELC_NONE)
goto bad_context;
_bfd_vms_push (abfd, op2 - op1, rel1);
break;
case ETIR__C_OPR_MUL: /* Multiply. */
_bfd_vms_pop (abfd, &op1, &rel1);
_bfd_vms_pop (abfd, &op2, &rel2);
if (rel1 != RELC_NONE || rel2 != RELC_NONE)
goto bad_context;
_bfd_vms_push (abfd, op1 * op2, RELC_NONE);
break;
case ETIR__C_OPR_DIV: /* Divide. */
_bfd_vms_pop (abfd, &op1, &rel1);
_bfd_vms_pop (abfd, &op2, &rel2);
if (rel1 != RELC_NONE || rel2 != RELC_NONE)
goto bad_context;
if (op2 == 0)
_bfd_vms_push (abfd, 0, RELC_NONE);
else
_bfd_vms_push (abfd, op2 / op1, RELC_NONE);
break;
case ETIR__C_OPR_AND: /* Logical AND. */
_bfd_vms_pop (abfd, &op1, &rel1);
_bfd_vms_pop (abfd, &op2, &rel2);
if (rel1 != RELC_NONE || rel2 != RELC_NONE)
goto bad_context;
_bfd_vms_push (abfd, op1 & op2, RELC_NONE);
break;
case ETIR__C_OPR_IOR: /* Logical inclusive OR. */
_bfd_vms_pop (abfd, &op1, &rel1);
_bfd_vms_pop (abfd, &op2, &rel2);
if (rel1 != RELC_NONE || rel2 != RELC_NONE)
goto bad_context;
_bfd_vms_push (abfd, op1 | op2, RELC_NONE);
break;
case ETIR__C_OPR_EOR: /* Logical exclusive OR. */
_bfd_vms_pop (abfd, &op1, &rel1);
_bfd_vms_pop (abfd, &op2, &rel2);
if (rel1 != RELC_NONE || rel2 != RELC_NONE)
goto bad_context;
_bfd_vms_push (abfd, op1 ^ op2, RELC_NONE);
break;
case ETIR__C_OPR_NEG: /* Negate. */
_bfd_vms_pop (abfd, &op1, &rel1);
if (rel1 != RELC_NONE)
goto bad_context;
_bfd_vms_push (abfd, -op1, RELC_NONE);
break;
case ETIR__C_OPR_COM: /* Complement. */
_bfd_vms_pop (abfd, &op1, &rel1);
if (rel1 != RELC_NONE)
goto bad_context;
_bfd_vms_push (abfd, ~op1, RELC_NONE);
break;
case ETIR__C_OPR_ASH: /* Arithmetic shift. */
_bfd_vms_pop (abfd, &op1, &rel1);
_bfd_vms_pop (abfd, &op2, &rel2);
if (rel1 != RELC_NONE || rel2 != RELC_NONE)
{
bad_context:
(*_bfd_error_handler) (_("invalid use of %s with contexts"),
_bfd_vms_etir_name (cmd));
return FALSE;
}
if ((int)op2 < 0) /* Shift right. */
op1 >>= -(int)op2;
else /* Shift left. */
op1 <<= (int)op2;
_bfd_vms_push (abfd, op1, RELC_NONE); /* FIXME: sym. */
break;
case ETIR__C_OPR_INSV: /* Insert field. */
case ETIR__C_OPR_USH: /* Unsigned shift. */
case ETIR__C_OPR_ROT: /* Rotate. */
case ETIR__C_OPR_REDEF: /* Redefine symbol to current location. */
case ETIR__C_OPR_DFLIT: /* Define a literal. */
(*_bfd_error_handler) (_("%s: not supported"),
_bfd_vms_etir_name (cmd));
return FALSE;
break;
case ETIR__C_OPR_SEL: /* Select. */
_bfd_vms_pop (abfd, &op1, &rel1);
if (op1 & 0x01L)
_bfd_vms_pop (abfd, &op1, &rel1);
else
{
_bfd_vms_pop (abfd, &op1, &rel1);
_bfd_vms_pop (abfd, &op2, &rel2);
_bfd_vms_push (abfd, op1, rel1);
}
break;
default:
(*_bfd_error_handler) (_("reserved cmd %d"), cmd);
return FALSE;
break;
}
ptr += cmd_length - 4;
}
return TRUE;
}
/* Process EDBG/ETBT record.
Return TRUE on success, FALSE on error */
static bfd_boolean
vms_slurp_debug (bfd *abfd)
{
asection *section = PRIV (dst_section);
if (section == NULL)
{
/* We have no way to find out beforehand how much debug info there
is in an object file, so pick an initial amount and grow it as
needed later. */
flagword flags = SEC_HAS_CONTENTS | SEC_DEBUGGING | SEC_RELOC
| SEC_IN_MEMORY;
section = bfd_make_section (abfd, "$DST$");
if (!section)
return FALSE;
if (!bfd_set_section_flags (abfd, section, flags))
return FALSE;
PRIV (dst_section) = section;
}
PRIV (image_section) = section;
PRIV (image_offset) = section->size;
if (!_bfd_vms_slurp_etir (abfd, NULL))
return FALSE;
section->size = PRIV (image_offset);
return TRUE;
}
/* Process EDBG record.
Return TRUE on success, FALSE on error. */
static bfd_boolean
_bfd_vms_slurp_edbg (bfd *abfd)
{
vms_debug2 ((2, "EDBG\n"));
abfd->flags |= HAS_DEBUG | HAS_LINENO;
return vms_slurp_debug (abfd);
}
/* Process ETBT record.
Return TRUE on success, FALSE on error. */
static bfd_boolean
_bfd_vms_slurp_etbt (bfd *abfd)
{
vms_debug2 ((2, "ETBT\n"));
abfd->flags |= HAS_LINENO;
return vms_slurp_debug (abfd);
}
/* Process EEOM record.
Return TRUE on success, FALSE on error. */
static bfd_boolean
_bfd_vms_slurp_eeom (bfd *abfd)
{
struct vms_eeom *eeom = (struct vms_eeom *) PRIV (recrd.rec);
vms_debug2 ((2, "EEOM\n"));
PRIV (eom_data).eom_l_total_lps = bfd_getl32 (eeom->total_lps);
PRIV (eom_data).eom_w_comcod = bfd_getl16 (eeom->comcod);
if (PRIV (eom_data).eom_w_comcod > 1)
{
(*_bfd_error_handler) (_("Object module NOT error-free !\n"));
bfd_set_error (bfd_error_bad_value);
return FALSE;
}
PRIV (eom_data).eom_has_transfer = FALSE;
if (PRIV (recrd.rec_size) > 10)
{
PRIV (eom_data).eom_has_transfer = TRUE;
PRIV (eom_data).eom_b_tfrflg = eeom->tfrflg;
PRIV (eom_data).eom_l_psindx = bfd_getl32 (eeom->psindx);
PRIV (eom_data).eom_l_tfradr = bfd_getl32 (eeom->tfradr);
abfd->start_address = PRIV (eom_data).eom_l_tfradr;
}
return TRUE;
}
/* Slurp an ordered set of VMS object records. Return FALSE on error. */
static bfd_boolean
_bfd_vms_slurp_object_records (bfd * abfd)
{
bfd_boolean err;
int type;
do
{
vms_debug2 ((7, "reading at %08lx\n", (unsigned long)bfd_tell (abfd)));
type = _bfd_vms_get_object_record (abfd);
if (type < 0)
{
vms_debug2 ((2, "next_record failed\n"));
return FALSE;
}
switch (type)
{
case EOBJ__C_EMH:
err = _bfd_vms_slurp_ehdr (abfd);
break;
case EOBJ__C_EEOM:
err = _bfd_vms_slurp_eeom (abfd);
break;
case EOBJ__C_EGSD:
err = _bfd_vms_slurp_egsd (abfd);
break;
case EOBJ__C_ETIR:
err = TRUE; /* _bfd_vms_slurp_etir (abfd); */
break;
case EOBJ__C_EDBG:
err = _bfd_vms_slurp_edbg (abfd);
break;
case EOBJ__C_ETBT:
err = _bfd_vms_slurp_etbt (abfd);
break;
default:
err = FALSE;
}
if (err != TRUE)
{
vms_debug2 ((2, "slurp type %d failed\n", type));
return FALSE;
}
}
while (type != EOBJ__C_EEOM);
return TRUE;
}
/* Initialize private data */
static bfd_boolean
vms_initialize (bfd * abfd)
{
bfd_size_type amt;
amt = sizeof (struct vms_private_data_struct);
abfd->tdata.any = bfd_zalloc (abfd, amt);
if (abfd->tdata.any == NULL)
return FALSE;
PRIV (recrd.file_format) = FF_UNKNOWN;
amt = sizeof (struct stack_struct) * STACKSIZE;
PRIV (stack) = bfd_alloc (abfd, amt);
if (PRIV (stack) == NULL)
goto error_ret1;
return TRUE;
error_ret1:
bfd_release (abfd, abfd->tdata.any);
abfd->tdata.any = NULL;
return FALSE;
}
/* Check the format for a file being read.
Return a (bfd_target *) if it's an object file or zero if not. */
static const struct bfd_target *
alpha_vms_object_p (bfd *abfd)
{
void *tdata_save = abfd->tdata.any;
unsigned int test_len;
unsigned char *buf;
vms_debug2 ((1, "vms_object_p(%p)\n", abfd));
/* Allocate alpha-vms specific data. */
if (!vms_initialize (abfd))
goto error_ret;
if (bfd_seek (abfd, (file_ptr) 0, SEEK_SET))
goto err_wrong_format;
/* The first challenge with VMS is to discover the kind of the file.
Image files (executable or shared images) are stored as a raw
stream of bytes (like on UNIX), but there is no magic number.
Object files are written with RMS (record management service), ie
each records are preceeded by its length (on a word - 2 bytes), and
padded for word-alignment. That would be simple but when files
are transfered to a UNIX filesystem (using ftp), records are lost.
Only the raw content of the records are transfered. Fortunately,
the Alpha Object file format also store the length of the record
in the records. Is that clear ? */
/* Minimum is 6 bytes for objects (2 bytes size, 2 bytes record id,
2 bytes size repeated) and 12 bytes for images (4 bytes major id,
4 bytes minor id, 4 bytes length). */
test_len = 12;
/* Size the main buffer. */
buf = (unsigned char *) bfd_malloc (test_len);
if (buf == NULL)
goto error_ret;
PRIV (recrd.buf) = buf;
PRIV (recrd.buf_size) = test_len;
/* Initialize the record pointer. */
PRIV (recrd.rec) = buf;
if (bfd_bread (buf, test_len, abfd) != test_len)
goto err_wrong_format;
/* Is it an image? */
if ((bfd_getl32 (buf) == EIHD__K_MAJORID)
&& (bfd_getl32 (buf + 4) == EIHD__K_MINORID))
{
unsigned int to_read;
unsigned int read_so_far;
unsigned int remaining;
unsigned int eisd_offset, eihs_offset;
/* Extract the header size. */
PRIV (recrd.rec_size) = bfd_getl32 (buf + EIHD__L_SIZE);
/* The header size is 0 for DSF files. */
if (PRIV (recrd.rec_size) == 0)
PRIV (recrd.rec_size) = sizeof (struct vms_eihd);
if (PRIV (recrd.rec_size) > PRIV (recrd.buf_size))
{
buf = bfd_realloc_or_free (buf, PRIV (recrd.rec_size));
if (buf == NULL)
{
PRIV (recrd.buf) = NULL;
goto error_ret;
}
PRIV (recrd.buf) = buf;
PRIV (recrd.buf_size) = PRIV (recrd.rec_size);
}
/* Read the remaining record. */
remaining = PRIV (recrd.rec_size) - test_len;
to_read = MIN (VMS_BLOCK_SIZE - test_len, remaining);
read_so_far = test_len;
while (remaining > 0)
{
if (bfd_bread (buf + read_so_far, to_read, abfd) != to_read)
goto err_wrong_format;
read_so_far += to_read;
remaining -= to_read;
to_read = MIN (VMS_BLOCK_SIZE, remaining);
}
/* Reset the record pointer. */
PRIV (recrd.rec) = buf;
/* PR 17512: file: 7d7c57c2. */
if (PRIV (recrd.rec_size) < sizeof (struct vms_eihd))
goto error_ret;
vms_debug2 ((2, "file type is image\n"));
if (_bfd_vms_slurp_eihd (abfd, &eisd_offset, &eihs_offset) != TRUE)
goto err_wrong_format;
if (_bfd_vms_slurp_eisd (abfd, eisd_offset) != TRUE)
goto err_wrong_format;
/* EIHS is optional. */
if (eihs_offset != 0 && _bfd_vms_slurp_eihs (abfd, eihs_offset) != TRUE)
goto err_wrong_format;
}
else
{
int type;
/* Assume it's a module and adjust record pointer if necessary. */
maybe_adjust_record_pointer_for_object (abfd);
/* But is it really a module? */
if (bfd_getl16 (PRIV (recrd.rec)) <= EOBJ__C_MAXRECTYP
&& bfd_getl16 (PRIV (recrd.rec) + 2) <= EOBJ__C_MAXRECSIZ)
{
if (vms_get_remaining_object_record (abfd, test_len) <= 0)
goto err_wrong_format;
vms_debug2 ((2, "file type is module\n"));
type = bfd_getl16 (PRIV (recrd.rec));
if (type != EOBJ__C_EMH || _bfd_vms_slurp_ehdr (abfd) != TRUE)
goto err_wrong_format;
if (_bfd_vms_slurp_object_records (abfd) != TRUE)
goto err_wrong_format;
}
else
goto err_wrong_format;
}
/* Set arch_info to alpha. */
if (! bfd_default_set_arch_mach (abfd, bfd_arch_alpha, 0))
goto err_wrong_format;
return abfd->xvec;
err_wrong_format:
bfd_set_error (bfd_error_wrong_format);
error_ret:
if (PRIV (recrd.buf))
free (PRIV (recrd.buf));
if (abfd->tdata.any != tdata_save && abfd->tdata.any != NULL)
bfd_release (abfd, abfd->tdata.any);
abfd->tdata.any = tdata_save;
return NULL;
}
/* Image write. */
/* Write an EMH/MHD record. */
static void
_bfd_vms_write_emh (bfd *abfd)
{
struct vms_rec_wr *recwr = &PRIV (recwr);
_bfd_vms_output_alignment (recwr, 2);
/* EMH. */
_bfd_vms_output_begin (recwr, EOBJ__C_EMH);
_bfd_vms_output_short (recwr, EMH__C_MHD);
_bfd_vms_output_short (recwr, EOBJ__C_STRLVL);
_bfd_vms_output_long (recwr, 0);
_bfd_vms_output_long (recwr, 0);
_bfd_vms_output_long (recwr, MAX_OUTREC_SIZE);
/* Create module name from filename. */
if (bfd_get_filename (abfd) != 0)
{
char *module = vms_get_module_name (bfd_get_filename (abfd), TRUE);
_bfd_vms_output_counted (recwr, module);
free (module);
}
else
_bfd_vms_output_counted (recwr, "NONAME");
_bfd_vms_output_counted (recwr, BFD_VERSION_STRING);
_bfd_vms_output_dump (recwr, get_vms_time_string (), EMH_DATE_LENGTH);
_bfd_vms_output_fill (recwr, 0, EMH_DATE_LENGTH);
_bfd_vms_output_end (abfd, recwr);
}
/* Write an EMH/LMN record. */
static void
_bfd_vms_write_lmn (bfd *abfd, const char *name)
{
char version [64];
struct vms_rec_wr *recwr = &PRIV (recwr);
unsigned int ver = BFD_VERSION / 10000;
/* LMN. */
_bfd_vms_output_begin (recwr, EOBJ__C_EMH);
_bfd_vms_output_short (recwr, EMH__C_LNM);
snprintf (version, sizeof (version), "%s %d.%d.%d", name,
ver / 10000, (ver / 100) % 100, ver % 100);
_bfd_vms_output_dump (recwr, (unsigned char *)version, strlen (version));
_bfd_vms_output_end (abfd, recwr);
}
/* Write eom record for bfd abfd. Return FALSE on error. */
static bfd_boolean
_bfd_vms_write_eeom (bfd *abfd)
{
struct vms_rec_wr *recwr = &PRIV (recwr);
vms_debug2 ((2, "vms_write_eeom\n"));
_bfd_vms_output_alignment (recwr, 2);
_bfd_vms_output_begin (recwr, EOBJ__C_EEOM);
_bfd_vms_output_long (recwr, PRIV (vms_linkage_index + 1) >> 1);
_bfd_vms_output_byte (recwr, 0); /* Completion code. */
_bfd_vms_output_byte (recwr, 0); /* Fill byte. */
if ((abfd->flags & EXEC_P) == 0
&& bfd_get_start_address (abfd) != (bfd_vma)-1)
{
asection *section;
section = bfd_get_section_by_name (abfd, ".link");
if (section == 0)
{
bfd_set_error (bfd_error_nonrepresentable_section);
return FALSE;
}
_bfd_vms_output_short (recwr, 0);
_bfd_vms_output_long (recwr, (unsigned long) section->target_index);
_bfd_vms_output_long (recwr,
(unsigned long) bfd_get_start_address (abfd));
_bfd_vms_output_long (recwr, 0);
}
_bfd_vms_output_end (abfd, recwr);
return TRUE;
}
static void
vector_grow1 (struct vector_type *vec, size_t elsz)
{
if (vec->nbr_el + 1 < vec->max_el)
return;
if (vec->max_el == 0)
{
vec->max_el = 16;
vec->els = bfd_malloc2 (vec->max_el, elsz);
}
else
{
vec->max_el *= 2;
vec->els = bfd_realloc2 (vec->els, vec->max_el, elsz);
}
}
/* Bump ABFD file position to next block. */
static void
alpha_vms_file_position_block (bfd *abfd)
{
/* Next block. */
PRIV (file_pos) += VMS_BLOCK_SIZE - 1;
PRIV (file_pos) -= (PRIV (file_pos) % VMS_BLOCK_SIZE);
}
/* Convert from internal structure SRC to external structure DST. */
static void
alpha_vms_swap_eisd_out (struct vms_internal_eisd_map *src,
struct vms_eisd *dst)
{
bfd_putl32 (src->u.eisd.majorid, dst->majorid);
bfd_putl32 (src->u.eisd.minorid, dst->minorid);
bfd_putl32 (src->u.eisd.eisdsize, dst->eisdsize);
if (src->u.eisd.eisdsize <= EISD__K_LENEND)
return;
bfd_putl32 (src->u.eisd.secsize, dst->secsize);
bfd_putl64 (src->u.eisd.virt_addr, dst->virt_addr);
bfd_putl32 (src->u.eisd.flags, dst->flags);
bfd_putl32 (src->u.eisd.vbn, dst->vbn);
dst->pfc = src->u.eisd.pfc;
dst->matchctl = src->u.eisd.matchctl;
dst->type = src->u.eisd.type;
dst->fill_1 = 0;
if (src->u.eisd.flags & EISD__M_GBL)
{
bfd_putl32 (src->u.gbl_eisd.ident, dst->ident);
memcpy (dst->gblnam, src->u.gbl_eisd.gblnam,
src->u.gbl_eisd.gblnam[0] + 1);
}
}
/* Append EISD to the list of extra eisd for ABFD. */
static void
alpha_vms_append_extra_eisd (bfd *abfd, struct vms_internal_eisd_map *eisd)
{
eisd->next = NULL;
if (PRIV (gbl_eisd_head) == NULL)
PRIV (gbl_eisd_head) = eisd;
else
PRIV (gbl_eisd_tail)->next = eisd;
PRIV (gbl_eisd_tail) = eisd;
}
/* Create an EISD for shared image SHRIMG.
Return FALSE in case of error. */
static bfd_boolean
alpha_vms_create_eisd_for_shared (bfd *abfd, bfd *shrimg)
{
struct vms_internal_eisd_map *eisd;
int namlen;
namlen = strlen (PRIV2 (shrimg, hdr_data.hdr_t_name));
if (namlen + 5 > EISD__K_GBLNAMLEN)
{
/* Won't fit. */
return FALSE;
}
eisd = bfd_alloc (abfd, sizeof (*eisd));
if (eisd == NULL)
return FALSE;
/* Fill the fields. */
eisd->u.gbl_eisd.common.majorid = EISD__K_MAJORID;
eisd->u.gbl_eisd.common.minorid = EISD__K_MINORID;
eisd->u.gbl_eisd.common.eisdsize = (EISD__K_LEN + 4 + namlen + 5 + 3) & ~3;
eisd->u.gbl_eisd.common.secsize = VMS_BLOCK_SIZE; /* Must not be 0. */
eisd->u.gbl_eisd.common.virt_addr = 0;
eisd->u.gbl_eisd.common.flags = EISD__M_GBL;
eisd->u.gbl_eisd.common.vbn = 0;
eisd->u.gbl_eisd.common.pfc = 0;
eisd->u.gbl_eisd.common.matchctl = PRIV2 (shrimg, matchctl);
eisd->u.gbl_eisd.common.type = EISD__K_SHRPIC;
eisd->u.gbl_eisd.ident = PRIV2 (shrimg, ident);
eisd->u.gbl_eisd.gblnam[0] = namlen + 4;
memcpy (eisd->u.gbl_eisd.gblnam + 1, PRIV2 (shrimg, hdr_data.hdr_t_name),
namlen);
memcpy (eisd->u.gbl_eisd.gblnam + 1 + namlen, "_001", 4);
/* Append it to the list. */
alpha_vms_append_extra_eisd (abfd, eisd);
return TRUE;
}
/* Create an EISD for section SEC.
Return FALSE in case of failure. */
static bfd_boolean
alpha_vms_create_eisd_for_section (bfd *abfd, asection *sec)
{
struct vms_internal_eisd_map *eisd;
/* Only for allocating section. */
if (!(sec->flags & SEC_ALLOC))
return TRUE;
BFD_ASSERT (vms_section_data (sec)->eisd == NULL);
eisd = bfd_alloc (abfd, sizeof (*eisd));
if (eisd == NULL)
return FALSE;
vms_section_data (sec)->eisd = eisd;
/* Fill the fields. */
eisd->u.eisd.majorid = EISD__K_MAJORID;
eisd->u.eisd.minorid = EISD__K_MINORID;
eisd->u.eisd.eisdsize = EISD__K_LEN;
eisd->u.eisd.secsize =
(sec->size + VMS_BLOCK_SIZE - 1) & ~(VMS_BLOCK_SIZE - 1);
eisd->u.eisd.virt_addr = sec->vma;
eisd->u.eisd.flags = 0;
eisd->u.eisd.vbn = 0; /* To be later defined. */
eisd->u.eisd.pfc = 0; /* Default. */
eisd->u.eisd.matchctl = EISD__K_MATALL;
eisd->u.eisd.type = EISD__K_NORMAL;
if (sec->flags & SEC_CODE)
eisd->u.eisd.flags |= EISD__M_EXE;
if (!(sec->flags & SEC_READONLY))
eisd->u.eisd.flags |= EISD__M_WRT | EISD__M_CRF;
/* If relocations or fixup will be applied, make this isect writeable. */
if (sec->flags & SEC_RELOC)
eisd->u.eisd.flags |= EISD__M_WRT | EISD__M_CRF;
if (!(sec->flags & SEC_HAS_CONTENTS))
{
eisd->u.eisd.flags |= EISD__M_DZRO;
eisd->u.eisd.flags &= ~EISD__M_CRF;
}
if (sec->flags & SEC_LINKER_CREATED)
{
if (strcmp (sec->name, "$FIXUP$") == 0)
eisd->u.eisd.flags |= EISD__M_FIXUPVEC;
}
/* Append it to the list. */
eisd->next = NULL;
if (PRIV (eisd_head) == NULL)
PRIV (eisd_head) = eisd;
else
PRIV (eisd_tail)->next = eisd;
PRIV (eisd_tail) = eisd;
return TRUE;
}
/* Layout executable ABFD and write it to the disk.
Return FALSE in case of failure. */
static bfd_boolean
alpha_vms_write_exec (bfd *abfd)
{
struct vms_eihd eihd;
struct vms_eiha *eiha;
struct vms_eihi *eihi;
struct vms_eihs *eihs = NULL;
asection *sec;
struct vms_internal_eisd_map *first_eisd;
struct vms_internal_eisd_map *eisd;
asection *dst;
asection *dmt;
file_ptr gst_filepos = 0;
unsigned int lnkflags = 0;
/* Build the EIHD. */
PRIV (file_pos) = EIHD__C_LENGTH;
memset (&eihd, 0, sizeof (eihd));
memset (eihd.fill_2, 0xff, sizeof (eihd.fill_2));
bfd_putl32 (EIHD__K_MAJORID, eihd.majorid);
bfd_putl32 (EIHD__K_MINORID, eihd.minorid);
bfd_putl32 (sizeof (eihd), eihd.size);
bfd_putl32 (0, eihd.isdoff);
bfd_putl32 (0, eihd.activoff);
bfd_putl32 (0, eihd.symdbgoff);
bfd_putl32 (0, eihd.imgidoff);
bfd_putl32 (0, eihd.patchoff);
bfd_putl64 (0, eihd.iafva);
bfd_putl32 (0, eihd.version_array_off);
bfd_putl32 (EIHD__K_EXE, eihd.imgtype);
bfd_putl32 (0, eihd.subtype);
bfd_putl32 (0, eihd.imgiocnt);
bfd_putl32 (-1, eihd.privreqs);
bfd_putl32 (-1, eihd.privreqs + 4);
bfd_putl32 ((sizeof (eihd) + VMS_BLOCK_SIZE - 1) / VMS_BLOCK_SIZE,
eihd.hdrblkcnt);
bfd_putl32 (0, eihd.ident);
bfd_putl32 (0, eihd.sysver);
eihd.matchctl = 0;
bfd_putl32 (0, eihd.symvect_size);
bfd_putl32 (16, eihd.virt_mem_block_size);
bfd_putl32 (0, eihd.ext_fixup_off);
bfd_putl32 (0, eihd.noopt_psect_off);
bfd_putl32 (-1, eihd.alias);
/* Alloc EIHA. */
eiha = (struct vms_eiha *)((char *) &eihd + PRIV (file_pos));
bfd_putl32 (PRIV (file_pos), eihd.activoff);
PRIV (file_pos) += sizeof (struct vms_eiha);
bfd_putl32 (sizeof (struct vms_eiha), eiha->size);
bfd_putl32 (0, eiha->spare);
bfd_putl64 (PRIV (transfer_address[0]), eiha->tfradr1);
bfd_putl64 (PRIV (transfer_address[1]), eiha->tfradr2);
bfd_putl64 (PRIV (transfer_address[2]), eiha->tfradr3);
bfd_putl64 (PRIV (transfer_address[3]), eiha->tfradr4);
bfd_putl64 (0, eiha->inishr);
/* Alloc EIHI. */
eihi = (struct vms_eihi *)((char *) &eihd + PRIV (file_pos));
bfd_putl32 (PRIV (file_pos), eihd.imgidoff);
PRIV (file_pos) += sizeof (struct vms_eihi);
bfd_putl32 (EIHI__K_MAJORID, eihi->majorid);
bfd_putl32 (EIHI__K_MINORID, eihi->minorid);
{
char *module;
unsigned int len;
/* Set module name. */
module = vms_get_module_name (bfd_get_filename (abfd), TRUE);
len = strlen (module);
if (len > sizeof (eihi->imgnam) - 1)
len = sizeof (eihi->imgnam) - 1;
eihi->imgnam[0] = len;
memcpy (eihi->imgnam + 1, module, len);
free (module);
}
{
unsigned int lo;
unsigned int hi;
/* Set time. */
vms_get_time (&hi, &lo);
bfd_putl32 (lo, eihi->linktime + 0);
bfd_putl32 (hi, eihi->linktime + 4);
}
eihi->imgid[0] = 0;
eihi->linkid[0] = 0;
eihi->imgbid[0] = 0;
/* Alloc EIHS. */
dst = PRIV (dst_section);
dmt = bfd_get_section_by_name (abfd, "$DMT$");
if (dst != NULL && dst->size != 0)
{
eihs = (struct vms_eihs *)((char *) &eihd + PRIV (file_pos));
bfd_putl32 (PRIV (file_pos), eihd.symdbgoff);
PRIV (file_pos) += sizeof (struct vms_eihs);
bfd_putl32 (EIHS__K_MAJORID, eihs->majorid);
bfd_putl32 (EIHS__K_MINORID, eihs->minorid);
bfd_putl32 (0, eihs->dstvbn);
bfd_putl32 (0, eihs->dstsize);
bfd_putl32 (0, eihs->gstvbn);
bfd_putl32 (0, eihs->gstsize);
bfd_putl32 (0, eihs->dmtvbn);
bfd_putl32 (0, eihs->dmtsize);
}
/* One EISD per section. */
for (sec = abfd->sections; sec; sec = sec->next)
{
if (!alpha_vms_create_eisd_for_section (abfd, sec))
return FALSE;
}
/* Merge section EIDS which extra ones. */
if (PRIV (eisd_tail))
PRIV (eisd_tail)->next = PRIV (gbl_eisd_head);
else
PRIV (eisd_head) = PRIV (gbl_eisd_head);
if (PRIV (gbl_eisd_tail))
PRIV (eisd_tail) = PRIV (gbl_eisd_tail);
first_eisd = PRIV (eisd_head);
/* Add end of eisd. */
if (first_eisd)
{
eisd = bfd_zalloc (abfd, sizeof (*eisd));
if (eisd == NULL)
return FALSE;
eisd->u.eisd.majorid = 0;
eisd->u.eisd.minorid = 0;
eisd->u.eisd.eisdsize = 0;
alpha_vms_append_extra_eisd (abfd, eisd);
}
/* Place EISD in the file. */
for (eisd = first_eisd; eisd; eisd = eisd->next)
{
file_ptr room = VMS_BLOCK_SIZE - (PRIV (file_pos) % VMS_BLOCK_SIZE);
/* First block is a little bit special: there is a word at the end. */
if (PRIV (file_pos) < VMS_BLOCK_SIZE && room > 2)
room -= 2;
if (room < eisd->u.eisd.eisdsize + EISD__K_LENEND)
alpha_vms_file_position_block (abfd);
eisd->file_pos = PRIV (file_pos);
PRIV (file_pos) += eisd->u.eisd.eisdsize;
if (eisd->u.eisd.flags & EISD__M_FIXUPVEC)
bfd_putl64 (eisd->u.eisd.virt_addr, eihd.iafva);
}
if (first_eisd != NULL)
{
bfd_putl32 (first_eisd->file_pos, eihd.isdoff);
/* Real size of end of eisd marker. */
PRIV (file_pos) += EISD__K_LENEND;
}
bfd_putl32 (PRIV (file_pos), eihd.size);
bfd_putl32 ((PRIV (file_pos) + VMS_BLOCK_SIZE - 1) / VMS_BLOCK_SIZE,
eihd.hdrblkcnt);
/* Place sections. */
for (sec = abfd->sections; sec; sec = sec->next)
{
if (!(sec->flags & SEC_HAS_CONTENTS))
continue;
eisd = vms_section_data (sec)->eisd;
/* Align on a block. */
alpha_vms_file_position_block (abfd);
sec->filepos = PRIV (file_pos);
if (eisd != NULL)
eisd->u.eisd.vbn = (sec->filepos / VMS_BLOCK_SIZE) + 1;
PRIV (file_pos) += sec->size;
}
/* Update EIHS. */
if (eihs != NULL && dst != NULL)
{
bfd_putl32 ((dst->filepos / VMS_BLOCK_SIZE) + 1, eihs->dstvbn);
bfd_putl32 (dst->size, eihs->dstsize);
if (dmt != NULL)
{
lnkflags |= EIHD__M_DBGDMT;
bfd_putl32 ((dmt->filepos / VMS_BLOCK_SIZE) + 1, eihs->dmtvbn);
bfd_putl32 (dmt->size, eihs->dmtsize);
}
if (PRIV (gsd_sym_count) != 0)
{
alpha_vms_file_position_block (abfd);
gst_filepos = PRIV (file_pos);
bfd_putl32 ((gst_filepos / VMS_BLOCK_SIZE) + 1, eihs->gstvbn);
bfd_putl32 ((PRIV (gsd_sym_count) + 4) / 5 + 4, eihs->gstsize);
}
}
/* Write EISD in hdr. */
for (eisd = first_eisd; eisd && eisd->file_pos < VMS_BLOCK_SIZE;
eisd = eisd->next)
alpha_vms_swap_eisd_out
(eisd, (struct vms_eisd *)((char *)&eihd + eisd->file_pos));
/* Write first block. */
bfd_putl32 (lnkflags, eihd.lnkflags);
if (bfd_bwrite (&eihd, sizeof (eihd), abfd) != sizeof (eihd))
return FALSE;
/* Write remaining eisd. */
if (eisd != NULL)
{
unsigned char blk[VMS_BLOCK_SIZE];
struct vms_internal_eisd_map *next_eisd;
memset (blk, 0xff, sizeof (blk));
while (eisd != NULL)
{
alpha_vms_swap_eisd_out
(eisd,
(struct vms_eisd *)(blk + (eisd->file_pos % VMS_BLOCK_SIZE)));
next_eisd = eisd->next;
if (next_eisd == NULL
|| (next_eisd->file_pos / VMS_BLOCK_SIZE
!= eisd->file_pos / VMS_BLOCK_SIZE))
{
if (bfd_bwrite (blk, sizeof (blk), abfd) != sizeof (blk))
return FALSE;
memset (blk, 0xff, sizeof (blk));
}
eisd = next_eisd;
}
}
/* Write sections. */
for (sec = abfd->sections; sec; sec = sec->next)
{
unsigned char blk[VMS_BLOCK_SIZE];
bfd_size_type len;
if (sec->size == 0 || !(sec->flags & SEC_HAS_CONTENTS))
continue;
if (bfd_bwrite (sec->contents, sec->size, abfd) != sec->size)
return FALSE;
/* Pad. */
len = VMS_BLOCK_SIZE - sec->size % VMS_BLOCK_SIZE;
if (len != VMS_BLOCK_SIZE)
{
memset (blk, 0, len);
if (bfd_bwrite (blk, len, abfd) != len)
return FALSE;
}
}
/* Write GST. */
if (gst_filepos != 0)
{
struct vms_rec_wr *recwr = &PRIV (recwr);
unsigned int i;
_bfd_vms_write_emh (abfd);
_bfd_vms_write_lmn (abfd, "GNU LD");
/* PSC for the absolute section. */
_bfd_vms_output_begin (recwr, EOBJ__C_EGSD);
_bfd_vms_output_long (recwr, 0);
_bfd_vms_output_begin_subrec (recwr, EGSD__C_PSC);
_bfd_vms_output_short (recwr, 0);
_bfd_vms_output_short (recwr, EGPS__V_PIC | EGPS__V_LIB | EGPS__V_RD);
_bfd_vms_output_long (recwr, 0);
_bfd_vms_output_counted (recwr, ".$$ABS$$.");
_bfd_vms_output_end_subrec (recwr);
_bfd_vms_output_end (abfd, recwr);
for (i = 0; i < PRIV (gsd_sym_count); i++)
{
struct vms_symbol_entry *sym = PRIV (syms)[i];
bfd_vma val;
bfd_vma ep;
if ((i % 5) == 0)
{
_bfd_vms_output_alignment (recwr, 8);
_bfd_vms_output_begin (recwr, EOBJ__C_EGSD);
_bfd_vms_output_long (recwr, 0);
}
_bfd_vms_output_begin_subrec (recwr, EGSD__C_SYMG);
_bfd_vms_output_short (recwr, 0); /* Data type, alignment. */
_bfd_vms_output_short (recwr, sym->flags);
if (sym->code_section)
ep = alpha_vms_get_sym_value (sym->code_section, sym->code_value);
else
{
BFD_ASSERT (sym->code_value == 0);
ep = 0;
}
val = alpha_vms_get_sym_value (sym->section, sym->value);
_bfd_vms_output_quad
(recwr, sym->typ == EGSD__C_SYMG ? sym->symbol_vector : val);
_bfd_vms_output_quad (recwr, ep);
_bfd_vms_output_quad (recwr, val);
_bfd_vms_output_long (recwr, 0);
_bfd_vms_output_counted (recwr, sym->name);
_bfd_vms_output_end_subrec (recwr);
if ((i % 5) == 4)
_bfd_vms_output_end (abfd, recwr);
}
if ((i % 5) != 0)
_bfd_vms_output_end (abfd, recwr);
if (!_bfd_vms_write_eeom (abfd))
return FALSE;
}
return TRUE;
}
/* Object write. */
/* Write section and symbol directory of bfd abfd. Return FALSE on error. */
static bfd_boolean
_bfd_vms_write_egsd (bfd *abfd)
{
asection *section;
asymbol *symbol;
unsigned int symnum;
const char *sname;
flagword new_flags, old_flags;
int abs_section_index = -1;
unsigned int target_index = 0;
struct vms_rec_wr *recwr = &PRIV (recwr);
vms_debug2 ((2, "vms_write_egsd\n"));
/* Egsd is quadword aligned. */
_bfd_vms_output_alignment (recwr, 8);
_bfd_vms_output_begin (recwr, EOBJ__C_EGSD);
_bfd_vms_output_long (recwr, 0);
/* Number sections. */
for (section = abfd->sections; section != NULL; section = section->next)
{
if (section->flags & SEC_DEBUGGING)
continue;
if (!strcmp (section->name, ".vmsdebug"))
{
section->flags |= SEC_DEBUGGING;
continue;
}
section->target_index = target_index++;
}
for (section = abfd->sections; section != NULL; section = section->next)
{
vms_debug2 ((3, "Section #%d %s, %d bytes\n",
section->target_index, section->name, (int)section->size));
/* Don't write out the VMS debug info section since it is in the
ETBT and EDBG sections in etir. */
if (section->flags & SEC_DEBUGGING)
continue;
/* 13 bytes egsd, max 31 chars name -> should be 44 bytes. */
if (_bfd_vms_output_check (recwr, 64) < 0)
{
_bfd_vms_output_end (abfd, recwr);
_bfd_vms_output_begin (recwr, EOBJ__C_EGSD);
_bfd_vms_output_long (recwr, 0);
}
/* Don't know if this is necessary for the linker but for now it keeps
vms_slurp_gsd happy. */
sname = section->name;
if (*sname == '.')
{
/* Remove leading dot. */
sname++;
if ((*sname == 't') && (strcmp (sname, "text") == 0))
sname = EVAX_CODE_NAME;
else if ((*sname == 'd') && (strcmp (sname, "data") == 0))
sname = EVAX_DATA_NAME;
else if ((*sname == 'b') && (strcmp (sname, "bss") == 0))
sname = EVAX_BSS_NAME;
else if ((*sname == 'l') && (strcmp (sname, "link") == 0))
sname = EVAX_LINK_NAME;
else if ((*sname == 'r') && (strcmp (sname, "rdata") == 0))
sname = EVAX_READONLY_NAME;
else if ((*sname == 'l') && (strcmp (sname, "literal") == 0))
sname = EVAX_LITERAL_NAME;
else if ((*sname == 'l') && (strcmp (sname, "literals") == 0))
sname = EVAX_LITERALS_NAME;
else if ((*sname == 'c') && (strcmp (sname, "comm") == 0))
sname = EVAX_COMMON_NAME;
else if ((*sname == 'l') && (strcmp (sname, "lcomm") == 0))
sname = EVAX_LOCAL_NAME;
}
if (bfd_is_com_section (section))
new_flags = (EGPS__V_OVR | EGPS__V_REL | EGPS__V_GBL | EGPS__V_RD
| EGPS__V_WRT | EGPS__V_NOMOD | EGPS__V_COM);
else
new_flags = vms_esecflag_by_name (evax_section_flags, sname,
section->size > 0);
/* Modify them as directed. */
if (section->flags & SEC_READONLY)
new_flags &= ~EGPS__V_WRT;
new_flags &= ~vms_section_data (section)->no_flags;
new_flags |= vms_section_data (section)->flags;
vms_debug2 ((3, "sec flags %x\n", section->flags));
vms_debug2 ((3, "new_flags %x, _raw_size %lu\n",
new_flags, (unsigned long)section->size));
_bfd_vms_output_begin_subrec (recwr, EGSD__C_PSC);
_bfd_vms_output_short (recwr, section->alignment_power & 0xff);
_bfd_vms_output_short (recwr, new_flags);
_bfd_vms_output_long (recwr, (unsigned long) section->size);
_bfd_vms_output_counted (recwr, sname);
_bfd_vms_output_end_subrec (recwr);
/* If the section is an obsolute one, remind its index as it will be
used later for absolute symbols. */
if ((new_flags & EGPS__V_REL) == 0 && abs_section_index < 0)
abs_section_index = section->target_index;
}
/* Output symbols. */
vms_debug2 ((3, "%d symbols found\n", abfd->symcount));
bfd_set_start_address (abfd, (bfd_vma) -1);
for (symnum = 0; symnum < abfd->symcount; symnum++)
{
symbol = abfd->outsymbols[symnum];
old_flags = symbol->flags;
/* Work-around a missing feature: consider __main as the main entry
point. */
if (symbol->name[0] == '_' && strcmp (symbol->name, "__main") == 0)
bfd_set_start_address (abfd, (bfd_vma)symbol->value);
/* Only put in the GSD the global and the undefined symbols. */
if (old_flags & BSF_FILE)
continue;
if ((old_flags & BSF_GLOBAL) == 0 && !bfd_is_und_section (symbol->section))
{
/* If the LIB$INITIIALIZE section is present, add a reference to
LIB$INITIALIZE symbol. FIXME: this should be done explicitely
in the assembly file. */
if (!((old_flags & BSF_SECTION_SYM) != 0
&& strcmp (symbol->section->name, "LIB$INITIALIZE") == 0))
continue;
}
/* 13 bytes egsd, max 64 chars name -> should be 77 bytes. Add 16 more
bytes for a possible ABS section. */
if (_bfd_vms_output_check (recwr, 80 + 16) < 0)
{
_bfd_vms_output_end (abfd, recwr);
_bfd_vms_output_begin (recwr, EOBJ__C_EGSD);
_bfd_vms_output_long (recwr, 0);
}
if ((old_flags & BSF_GLOBAL) != 0
&& bfd_is_abs_section (symbol->section)
&& abs_section_index <= 0)
{
/* Create an absolute section if none was defined. It is highly
unlikely that the name $ABS$ clashes with a user defined
non-absolute section name. */
_bfd_vms_output_begin_subrec (recwr, EGSD__C_PSC);
_bfd_vms_output_short (recwr, 4);
_bfd_vms_output_short (recwr, EGPS__V_SHR);
_bfd_vms_output_long (recwr, 0);
_bfd_vms_output_counted (recwr, "$ABS$");
_bfd_vms_output_end_subrec (recwr);
abs_section_index = target_index++;
}
_bfd_vms_output_begin_subrec (recwr, EGSD__C_SYM);
/* Data type, alignment. */
_bfd_vms_output_short (recwr, 0);
new_flags = 0;
if (old_flags & BSF_WEAK)
new_flags |= EGSY__V_WEAK;
if (bfd_is_com_section (symbol->section)) /* .comm */
new_flags |= (EGSY__V_WEAK | EGSY__V_COMM);
if (old_flags & BSF_FUNCTION)
{
new_flags |= EGSY__V_NORM;
new_flags |= EGSY__V_REL;
}
if (old_flags & BSF_GLOBAL)
{
new_flags |= EGSY__V_DEF;
if (!bfd_is_abs_section (symbol->section))
new_flags |= EGSY__V_REL;
}
_bfd_vms_output_short (recwr, new_flags);
if (old_flags & BSF_GLOBAL)
{
/* Symbol definition. */
bfd_vma code_address = 0;
unsigned long ca_psindx = 0;
unsigned long psindx;
if ((old_flags & BSF_FUNCTION) && symbol->udata.p != NULL)
{
asymbol *sym;
sym =
((struct evax_private_udata_struct *)symbol->udata.p)->enbsym;
code_address = sym->value;
ca_psindx = sym->section->target_index;
}
if (bfd_is_abs_section (symbol->section))
psindx = abs_section_index;
else
psindx = symbol->section->target_index;
_bfd_vms_output_quad (recwr, symbol->value);
_bfd_vms_output_quad (recwr, code_address);
_bfd_vms_output_long (recwr, ca_psindx);
_bfd_vms_output_long (recwr, psindx);
}
_bfd_vms_output_counted (recwr, symbol->name);
_bfd_vms_output_end_subrec (recwr);
}
_bfd_vms_output_alignment (recwr, 8);
_bfd_vms_output_end (abfd, recwr);
return TRUE;
}
/* Write object header for bfd abfd. Return FALSE on error. */
static bfd_boolean
_bfd_vms_write_ehdr (bfd *abfd)
{
asymbol *symbol;
unsigned int symnum;
struct vms_rec_wr *recwr = &PRIV (recwr);
vms_debug2 ((2, "vms_write_ehdr (%p)\n", abfd));
_bfd_vms_output_alignment (recwr, 2);
_bfd_vms_write_emh (abfd);
_bfd_vms_write_lmn (abfd, "GNU AS");
/* SRC. */
_bfd_vms_output_begin (recwr, EOBJ__C_EMH);
_bfd_vms_output_short (recwr, EMH__C_SRC);
for (symnum = 0; symnum < abfd->symcount; symnum++)
{
symbol = abfd->outsymbols[symnum];
if (symbol->flags & BSF_FILE)
{
_bfd_vms_output_dump (recwr, (unsigned char *) symbol->name,
(int) strlen (symbol->name));
break;
}
}
if (symnum == abfd->symcount)
_bfd_vms_output_dump (recwr, (unsigned char *) STRING_COMMA_LEN ("noname"));
_bfd_vms_output_end (abfd, recwr);
/* TTL. */
_bfd_vms_output_begin (recwr, EOBJ__C_EMH);
_bfd_vms_output_short (recwr, EMH__C_TTL);
_bfd_vms_output_dump (recwr, (unsigned char *) STRING_COMMA_LEN ("TTL"));
_bfd_vms_output_end (abfd, recwr);
/* CPR. */
_bfd_vms_output_begin (recwr, EOBJ__C_EMH);
_bfd_vms_output_short (recwr, EMH__C_CPR);
_bfd_vms_output_dump (recwr,
(unsigned char *)"GNU BFD ported by Klaus Kämpf 1994-1996",
39);
_bfd_vms_output_end (abfd, recwr);
return TRUE;
}
/* Part 4.6, relocations. */
/* WRITE ETIR SECTION
This is still under construction and therefore not documented. */
/* Close the etir/etbt record. */
static void
end_etir_record (bfd * abfd)
{
struct vms_rec_wr *recwr = &PRIV (recwr);
_bfd_vms_output_end (abfd, recwr);
}
static void
start_etir_or_etbt_record (bfd *abfd, asection *section, bfd_vma offset)
{
struct vms_rec_wr *recwr = &PRIV (recwr);
if (section->flags & SEC_DEBUGGING)
{
_bfd_vms_output_begin (recwr, EOBJ__C_ETBT);
if (offset == 0)
{
/* Push start offset. */
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STA_LW);
_bfd_vms_output_long (recwr, (unsigned long) 0);
_bfd_vms_output_end_subrec (recwr);
/* Set location. */
_bfd_vms_output_begin_subrec (recwr, ETIR__C_CTL_DFLOC);
_bfd_vms_output_end_subrec (recwr);
}
}
else
{
_bfd_vms_output_begin (recwr, EOBJ__C_ETIR);
if (offset == 0)
{
/* Push start offset. */
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STA_PQ);
_bfd_vms_output_long (recwr, (unsigned long) section->target_index);
_bfd_vms_output_quad (recwr, offset);
_bfd_vms_output_end_subrec (recwr);
/* Start = pop (). */
_bfd_vms_output_begin_subrec (recwr, ETIR__C_CTL_SETRB);
_bfd_vms_output_end_subrec (recwr);
}
}
}
/* Output a STO_IMM command for SSIZE bytes of data from CPR at virtual
address VADDR in section specified by SEC_INDEX and NAME. */
static void
sto_imm (bfd *abfd, asection *section,
bfd_size_type ssize, unsigned char *cptr, bfd_vma vaddr)
{
bfd_size_type size;
struct vms_rec_wr *recwr = &PRIV (recwr);
#if VMS_DEBUG
_bfd_vms_debug (8, "sto_imm %d bytes\n", (int) ssize);
_bfd_hexdump (9, cptr, (int) ssize, (int) vaddr);
#endif
while (ssize > 0)
{
/* Try all the rest. */
size = ssize;
if (_bfd_vms_output_check (recwr, size) < 0)
{
/* Doesn't fit, split ! */
end_etir_record (abfd);
start_etir_or_etbt_record (abfd, section, vaddr);
size = _bfd_vms_output_check (recwr, 0); /* get max size */
if (size > ssize) /* more than what's left ? */
size = ssize;
}
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STO_IMM);
_bfd_vms_output_long (recwr, (unsigned long) (size));
_bfd_vms_output_dump (recwr, cptr, size);
_bfd_vms_output_end_subrec (recwr);
#if VMS_DEBUG
_bfd_vms_debug (10, "dumped %d bytes\n", (int) size);
_bfd_hexdump (10, cptr, (int) size, (int) vaddr);
#endif
vaddr += size;
cptr += size;
ssize -= size;
}
}
static void
etir_output_check (bfd *abfd, asection *section, bfd_vma vaddr, int checklen)
{
if (_bfd_vms_output_check (&PRIV (recwr), checklen) < 0)
{
/* Not enough room in this record. Close it and open a new one. */
end_etir_record (abfd);
start_etir_or_etbt_record (abfd, section, vaddr);
}
}
/* Return whether RELOC must be deferred till the end. */
static bfd_boolean
defer_reloc_p (arelent *reloc)
{
switch (reloc->howto->type)
{
case ALPHA_R_NOP:
case ALPHA_R_LDA:
case ALPHA_R_BSR:
case ALPHA_R_BOH:
return TRUE;
default:
return FALSE;
}
}
/* Write section contents for bfd abfd. Return FALSE on error. */
static bfd_boolean
_bfd_vms_write_etir (bfd * abfd, int objtype ATTRIBUTE_UNUSED)
{
asection *section;
struct vms_rec_wr *recwr = &PRIV (recwr);
vms_debug2 ((2, "vms_write_tir (%p, %d)\n", abfd, objtype));
_bfd_vms_output_alignment (recwr, 4);
PRIV (vms_linkage_index) = 0;
for (section = abfd->sections; section; section = section->next)
{
vms_debug2 ((4, "writing %d. section '%s' (%d bytes)\n",
section->target_index, section->name, (int) (section->size)));
if (!(section->flags & SEC_HAS_CONTENTS)
|| bfd_is_com_section (section))
continue;
if (!section->contents)
{
bfd_set_error (bfd_error_no_contents);
return FALSE;
}
start_etir_or_etbt_record (abfd, section, 0);
if (section->flags & SEC_RELOC)
{
bfd_vma curr_addr = 0;
unsigned char *curr_data = section->contents;
bfd_size_type size;
int pass2_needed = 0;
int pass2_in_progress = 0;
unsigned int irel;
if (section->reloc_count == 0)
(*_bfd_error_handler)
(_("SEC_RELOC with no relocs in section %s"), section->name);
#if VMS_DEBUG
else
{
int i = section->reloc_count;
arelent **rptr = section->orelocation;
_bfd_vms_debug (4, "%d relocations:\n", i);
while (i-- > 0)
{
_bfd_vms_debug (4, "sym %s in sec %s, value %08lx, "
"addr %08lx, off %08lx, len %d: %s\n",
(*(*rptr)->sym_ptr_ptr)->name,
(*(*rptr)->sym_ptr_ptr)->section->name,
(long) (*(*rptr)->sym_ptr_ptr)->value,
(unsigned long)(*rptr)->address,
(unsigned long)(*rptr)->addend,
bfd_get_reloc_size ((*rptr)->howto),
( *rptr)->howto->name);
rptr++;
}
}
#endif
new_pass:
for (irel = 0; irel < section->reloc_count; irel++)
{
struct evax_private_udata_struct *udata;
arelent *rptr = section->orelocation [irel];
bfd_vma addr = rptr->address;
asymbol *sym = *rptr->sym_ptr_ptr;
asection *sec = sym->section;
bfd_boolean defer = defer_reloc_p (rptr);
unsigned int slen;
if (pass2_in_progress)
{
/* Non-deferred relocs have already been output. */
if (!defer)
continue;
}
else
{
/* Deferred relocs must be output at the very end. */
if (defer)
{
pass2_needed = 1;
continue;
}
/* Regular relocs are intertwined with binary data. */
if (curr_addr > addr)
(*_bfd_error_handler) (_("Size error in section %s"),
section->name);
size = addr - curr_addr;
sto_imm (abfd, section, size, curr_data, curr_addr);
curr_data += size;
curr_addr += size;
}
size = bfd_get_reloc_size (rptr->howto);
switch (rptr->howto->type)
{
case ALPHA_R_IGNORE:
break;
case ALPHA_R_REFLONG:
if (bfd_is_und_section (sym->section))
{
bfd_vma addend = rptr->addend;
slen = strlen ((char *) sym->name);
etir_output_check (abfd, section, curr_addr, slen);
if (addend)
{
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STA_GBL);
_bfd_vms_output_counted (recwr, sym->name);
_bfd_vms_output_end_subrec (recwr);
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STA_LW);
_bfd_vms_output_long (recwr, (unsigned long) addend);
_bfd_vms_output_end_subrec (recwr);
_bfd_vms_output_begin_subrec (recwr, ETIR__C_OPR_ADD);
_bfd_vms_output_end_subrec (recwr);
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STO_LW);
_bfd_vms_output_end_subrec (recwr);
}
else
{
_bfd_vms_output_begin_subrec
(recwr, ETIR__C_STO_GBL_LW);
_bfd_vms_output_counted (recwr, sym->name);
_bfd_vms_output_end_subrec (recwr);
}
}
else if (bfd_is_abs_section (sym->section))
{
etir_output_check (abfd, section, curr_addr, 16);
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STA_LW);
_bfd_vms_output_long (recwr, (unsigned long) sym->value);
_bfd_vms_output_end_subrec (recwr);
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STO_LW);
_bfd_vms_output_end_subrec (recwr);
}
else
{
etir_output_check (abfd, section, curr_addr, 32);
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STA_PQ);
_bfd_vms_output_long (recwr,
(unsigned long) sec->target_index);
_bfd_vms_output_quad (recwr, rptr->addend + sym->value);
_bfd_vms_output_end_subrec (recwr);
/* ??? Table B-8 of the OpenVMS Linker Utilily Manual
says that we should have a ETIR__C_STO_OFF here.
But the relocation would not be BFD_RELOC_32 then.
This case is very likely unreachable. */
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STO_LW);
_bfd_vms_output_end_subrec (recwr);
}
break;
case ALPHA_R_REFQUAD:
if (bfd_is_und_section (sym->section))
{
bfd_vma addend = rptr->addend;
slen = strlen ((char *) sym->name);
etir_output_check (abfd, section, curr_addr, slen);
if (addend)
{
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STA_GBL);
_bfd_vms_output_counted (recwr, sym->name);
_bfd_vms_output_end_subrec (recwr);
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STA_QW);
_bfd_vms_output_quad (recwr, addend);
_bfd_vms_output_end_subrec (recwr);
_bfd_vms_output_begin_subrec (recwr, ETIR__C_OPR_ADD);
_bfd_vms_output_end_subrec (recwr);
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STO_QW);
_bfd_vms_output_end_subrec (recwr);
}
else
{
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STO_GBL);
_bfd_vms_output_counted (recwr, sym->name);
_bfd_vms_output_end_subrec (recwr);
}
}
else if (bfd_is_abs_section (sym->section))
{
etir_output_check (abfd, section, curr_addr, 16);
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STA_QW);
_bfd_vms_output_quad (recwr, sym->value);
_bfd_vms_output_end_subrec (recwr);
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STO_QW);
_bfd_vms_output_end_subrec (recwr);
}
else
{
etir_output_check (abfd, section, curr_addr, 32);
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STA_PQ);
_bfd_vms_output_long (recwr,
(unsigned long) sec->target_index);
_bfd_vms_output_quad (recwr, rptr->addend + sym->value);
_bfd_vms_output_end_subrec (recwr);
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STO_OFF);
_bfd_vms_output_end_subrec (recwr);
}
break;
case ALPHA_R_HINT:
sto_imm (abfd, section, size, curr_data, curr_addr);
break;
case ALPHA_R_LINKAGE:
etir_output_check (abfd, section, curr_addr, 64);
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STC_LP_PSB);
_bfd_vms_output_long
(recwr, (unsigned long) rptr->addend);
if (rptr->addend > PRIV (vms_linkage_index))
PRIV (vms_linkage_index) = rptr->addend;
_bfd_vms_output_counted (recwr, sym->name);
_bfd_vms_output_byte (recwr, 0);
_bfd_vms_output_end_subrec (recwr);
break;
case ALPHA_R_CODEADDR:
slen = strlen ((char *) sym->name);
etir_output_check (abfd, section, curr_addr, slen);
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STO_CA);
_bfd_vms_output_counted (recwr, sym->name);
_bfd_vms_output_end_subrec (recwr);
break;
case ALPHA_R_NOP:
udata
= (struct evax_private_udata_struct *) rptr->sym_ptr_ptr;
etir_output_check (abfd, section, curr_addr,
32 + 1 + strlen (udata->origname));
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STC_NOP_GBL);
_bfd_vms_output_long (recwr, (unsigned long) udata->lkindex);
_bfd_vms_output_long
(recwr, (unsigned long) section->target_index);
_bfd_vms_output_quad (recwr, rptr->address);
_bfd_vms_output_long (recwr, (unsigned long) 0x47ff041f);
_bfd_vms_output_long
(recwr, (unsigned long) section->target_index);
_bfd_vms_output_quad (recwr, rptr->addend);
_bfd_vms_output_counted (recwr, udata->origname);
_bfd_vms_output_end_subrec (recwr);
break;
case ALPHA_R_BSR:
(*_bfd_error_handler) (_("Spurious ALPHA_R_BSR reloc"));
break;
case ALPHA_R_LDA:
udata
= (struct evax_private_udata_struct *) rptr->sym_ptr_ptr;
etir_output_check (abfd, section, curr_addr,
32 + 1 + strlen (udata->origname));
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STC_LDA_GBL);
_bfd_vms_output_long
(recwr, (unsigned long) udata->lkindex + 1);
_bfd_vms_output_long
(recwr, (unsigned long) section->target_index);
_bfd_vms_output_quad (recwr, rptr->address);
_bfd_vms_output_long (recwr, (unsigned long) 0x237B0000);
_bfd_vms_output_long
(recwr, (unsigned long) udata->bsym->section->target_index);
_bfd_vms_output_quad (recwr, rptr->addend);
_bfd_vms_output_counted (recwr, udata->origname);
_bfd_vms_output_end_subrec (recwr);
break;
case ALPHA_R_BOH:
udata
= (struct evax_private_udata_struct *) rptr->sym_ptr_ptr;
etir_output_check (abfd, section, curr_addr,
32 + 1 + strlen (udata->origname));
_bfd_vms_output_begin_subrec (recwr, ETIR__C_STC_BOH_GBL);
_bfd_vms_output_long (recwr, (unsigned long) udata->lkindex);
_bfd_vms_output_long
(recwr, (unsigned long) section->target_index);
_bfd_vms_output_quad (recwr, rptr->address);
_bfd_vms_output_long (recwr, (unsigned long) 0xD3400000);
_bfd_vms_output_long
(recwr, (unsigned long) section->target_index);
_bfd_vms_output_quad (recwr, rptr->addend);
_bfd_vms_output_counted (recwr, udata->origname);
_bfd_vms_output_end_subrec (recwr);
break;
default:
(*_bfd_error_handler) (_("Unhandled relocation %s"),
rptr->howto->name);
break;
}
curr_data += size;
curr_addr += size;
} /* End of relocs loop. */
if (!pass2_in_progress)
{
/* Output rest of section. */
if (curr_addr > section->size)
(*_bfd_error_handler) (_("Size error in section %s"),
section->name);
size = section->size - curr_addr;
sto_imm (abfd, section, size, curr_data, curr_addr);
curr_data += size;
curr_addr += size;
if (pass2_needed)
{
pass2_in_progress = 1;
goto new_pass;
}
}
}
else /* (section->flags & SEC_RELOC) */
sto_imm (abfd, section, section->size, section->contents, 0);
end_etir_record (abfd);
}
_bfd_vms_output_alignment (recwr, 2);
return TRUE;
}
/* Write cached information into a file being written, at bfd_close. */
static bfd_boolean
alpha_vms_write_object_contents (bfd *abfd)
{
vms_debug2 ((1, "vms_write_object_contents (%p)\n", abfd));
if (abfd->flags & (EXEC_P | DYNAMIC))
{
return alpha_vms_write_exec (abfd);
}
else
{
if (abfd->section_count > 0) /* we have sections */
{
if (_bfd_vms_write_ehdr (abfd) != TRUE)
return FALSE;
if (_bfd_vms_write_egsd (abfd) != TRUE)
return FALSE;
if (_bfd_vms_write_etir (abfd, EOBJ__C_ETIR) != TRUE)
return FALSE;
if (_bfd_vms_write_eeom (abfd) != TRUE)
return FALSE;
}
}
return TRUE;
}
/* Debug stuff: nearest line. */
#define SET_MODULE_PARSED(m) \
do { if ((m)->name == NULL) (m)->name = ""; } while (0)
#define IS_MODULE_PARSED(m) ((m)->name != NULL)
/* Build a new module for the specified BFD. */
static struct module *
new_module (bfd *abfd)
{
struct module *module
= (struct module *) bfd_zalloc (abfd, sizeof (struct module));
module->file_table_count = 16; /* Arbitrary. */
module->file_table
= bfd_malloc (module->file_table_count * sizeof (struct fileinfo));
return module;
}
/* Parse debug info for a module and internalize it. */
static void
parse_module (bfd *abfd, struct module *module, unsigned char *ptr,
int length)
{
unsigned char *maxptr = ptr + length;
unsigned char *src_ptr, *pcl_ptr;
unsigned int prev_linum = 0, curr_linenum = 0;
bfd_vma prev_pc = 0, curr_pc = 0;
struct srecinfo *curr_srec, *srec;
struct lineinfo *curr_line, *line;
struct funcinfo *funcinfo;
/* Initialize tables with zero element. */
curr_srec = (struct srecinfo *) bfd_zalloc (abfd, sizeof (struct srecinfo));
module->srec_table = curr_srec;
curr_line = (struct lineinfo *) bfd_zalloc (abfd, sizeof (struct lineinfo));
module->line_table = curr_line;
while (length == -1 || ptr < maxptr)
{
/* The first byte is not counted in the recorded length. */
int rec_length = bfd_getl16 (ptr) + 1;
int rec_type = bfd_getl16 (ptr + 2);
vms_debug2 ((2, "DST record: leng %d, type %d\n", rec_length, rec_type));
if (length == -1 && rec_type == DST__K_MODEND)
break;
switch (rec_type)
{
case DST__K_MODBEG:
module->name
= _bfd_vms_save_counted_string (ptr + DST_S_B_MODBEG_NAME);
curr_pc = 0;
prev_pc = 0;
curr_linenum = 0;
prev_linum = 0;
vms_debug2 ((3, "module: %s\n", module->name));
break;
case DST__K_MODEND:
break;
case DST__K_RTNBEG:
funcinfo = (struct funcinfo *)
bfd_zalloc (abfd, sizeof (struct funcinfo));
funcinfo->name
= _bfd_vms_save_counted_string (ptr + DST_S_B_RTNBEG_NAME);
funcinfo->low = bfd_getl32 (ptr + DST_S_L_RTNBEG_ADDRESS);
funcinfo->next = module->func_table;
module->func_table = funcinfo;
vms_debug2 ((3, "routine: %s at 0x%lx\n",
funcinfo->name, (unsigned long) funcinfo->low));
break;
case DST__K_RTNEND:
module->func_table->high = module->func_table->low
+ bfd_getl32 (ptr + DST_S_L_RTNEND_SIZE) - 1;
if (module->func_table->high > module->high)
module->high = module->func_table->high;
vms_debug2 ((3, "end routine\n"));
break;
case DST__K_PROLOG:
vms_debug2 ((3, "prologue\n"));
break;
case DST__K_EPILOG:
vms_debug2 ((3, "epilog\n"));
break;
case DST__K_BLKBEG:
vms_debug2 ((3, "block\n"));
break;
case DST__K_BLKEND:
vms_debug2 ((3, "end block\n"));
break;
case DST__K_SOURCE:
src_ptr = ptr + DST_S_C_SOURCE_HEADER_SIZE;
vms_debug2 ((3, "source info\n"));
while (src_ptr < ptr + rec_length)
{
int cmd = src_ptr[0], cmd_length, data;
switch (cmd)
{
case DST__K_SRC_DECLFILE:
{
unsigned int fileid
= bfd_getl16 (src_ptr + DST_S_W_SRC_DF_FILEID);
char *filename
= _bfd_vms_save_counted_string (src_ptr
+ DST_S_B_SRC_DF_FILENAME);
while (fileid >= module->file_table_count)
{
module->file_table_count *= 2;
module->file_table
= bfd_realloc (module->file_table,
module->file_table_count
* sizeof (struct fileinfo));
}
module->file_table [fileid].name = filename;
module->file_table [fileid].srec = 1;
cmd_length = src_ptr[DST_S_B_SRC_DF_LENGTH] + 2;
vms_debug2 ((4, "DST_S_C_SRC_DECLFILE: %d, %s\n",
fileid, module->file_table [fileid].name));
}
break;
case DST__K_SRC_DEFLINES_B:
/* Perform the association and set the next higher index
to the limit. */
data = src_ptr[DST_S_B_SRC_UNSBYTE];
srec = (struct srecinfo *)
bfd_zalloc (abfd, sizeof (struct srecinfo));
srec->line = curr_srec->line + data;
srec->srec = curr_srec->srec + data;
srec->sfile = curr_srec->sfile;
curr_srec->next = srec;
curr_srec = srec;
cmd_length = 2;
vms_debug2 ((4, "DST_S_C_SRC_DEFLINES_B: %d\n", data));
break;
case DST__K_SRC_DEFLINES_W:
/* Perform the association and set the next higher index
to the limit. */
data = bfd_getl16 (src_ptr + DST_S_W_SRC_UNSWORD);
srec = (struct srecinfo *)
bfd_zalloc (abfd, sizeof (struct srecinfo));
srec->line = curr_srec->line + data;
srec->srec = curr_srec->srec + data,
srec->sfile = curr_srec->sfile;
curr_srec->next = srec;
curr_srec = srec;
cmd_length = 3;
vms_debug2 ((4, "DST_S_C_SRC_DEFLINES_W: %d\n", data));
break;
case DST__K_SRC_INCRLNUM_B:
data = src_ptr[DST_S_B_SRC_UNSBYTE];
curr_srec->line += data;
cmd_length = 2;
vms_debug2 ((4, "DST_S_C_SRC_INCRLNUM_B: %d\n", data));
break;
case DST__K_SRC_SETFILE:
data = bfd_getl16 (src_ptr + DST_S_W_SRC_UNSWORD);
curr_srec->sfile = data;
curr_srec->srec = module->file_table[data].srec;
cmd_length = 3;
vms_debug2 ((4, "DST_S_C_SRC_SETFILE: %d\n", data));
break;
case DST__K_SRC_SETLNUM_L:
data = bfd_getl32 (src_ptr + DST_S_L_SRC_UNSLONG);
curr_srec->line = data;
cmd_length = 5;
vms_debug2 ((4, "DST_S_C_SRC_SETLNUM_L: %d\n", data));
break;
case DST__K_SRC_SETLNUM_W:
data = bfd_getl16 (src_ptr + DST_S_W_SRC_UNSWORD);
curr_srec->line = data;
cmd_length = 3;
vms_debug2 ((4, "DST_S_C_SRC_SETLNUM_W: %d\n", data));
break;
case DST__K_SRC_SETREC_L:
data = bfd_getl32 (src_ptr + DST_S_L_SRC_UNSLONG);
curr_srec->srec = data;
module->file_table[curr_srec->sfile].srec = data;
cmd_length = 5;
vms_debug2 ((4, "DST_S_C_SRC_SETREC_L: %d\n", data));
break;
case DST__K_SRC_SETREC_W:
data = bfd_getl16 (src_ptr + DST_S_W_SRC_UNSWORD);
curr_srec->srec = data;
module->file_table[curr_srec->sfile].srec = data;
cmd_length = 3;
vms_debug2 ((4, "DST_S_C_SRC_SETREC_W: %d\n", data));
break;
case DST__K_SRC_FORMFEED:
cmd_length = 1;
vms_debug2 ((4, "DST_S_C_SRC_FORMFEED\n"));
break;
default:
(*_bfd_error_handler) (_("unknown source command %d"),
cmd);
cmd_length = 2;
break;
}
src_ptr += cmd_length;
}
break;
case DST__K_LINE_NUM:
pcl_ptr = ptr + DST_S_C_LINE_NUM_HEADER_SIZE;
vms_debug2 ((3, "line info\n"));
while (pcl_ptr < ptr + rec_length)
{
/* The command byte is signed so we must sign-extend it. */
int cmd = ((signed char *)pcl_ptr)[0], cmd_length, data;
switch (cmd)
{
case DST__K_DELTA_PC_W:
data = bfd_getl16 (pcl_ptr + DST_S_W_PCLINE_UNSWORD);
curr_pc += data;
curr_linenum += 1;
cmd_length = 3;
vms_debug2 ((4, "DST__K_DELTA_PC_W: %d\n", data));
break;
case DST__K_DELTA_PC_L:
data = bfd_getl32 (pcl_ptr + DST_S_L_PCLINE_UNSLONG);
curr_pc += data;
curr_linenum += 1;
cmd_length = 5;
vms_debug2 ((4, "DST__K_DELTA_PC_L: %d\n", data));
break;
case DST__K_INCR_LINUM:
data = pcl_ptr[DST_S_B_PCLINE_UNSBYTE];
curr_linenum += data;
cmd_length = 2;
vms_debug2 ((4, "DST__K_INCR_LINUM: %d\n", data));
break;
case DST__K_INCR_LINUM_W:
data = bfd_getl16 (pcl_ptr + DST_S_W_PCLINE_UNSWORD);
curr_linenum += data;
cmd_length = 3;
vms_debug2 ((4, "DST__K_INCR_LINUM_W: %d\n", data));
break;
case DST__K_INCR_LINUM_L:
data = bfd_getl32 (pcl_ptr + DST_S_L_PCLINE_UNSLONG);
curr_linenum += data;
cmd_length = 5;
vms_debug2 ((4, "DST__K_INCR_LINUM_L: %d\n", data));
break;
case DST__K_SET_LINUM_INCR:
(*_bfd_error_handler)
(_("DST__K_SET_LINUM_INCR not implemented"));
cmd_length = 2;
break;
case DST__K_SET_LINUM_INCR_W:
(*_bfd_error_handler)
(_("DST__K_SET_LINUM_INCR_W not implemented"));
cmd_length = 3;
break;
case DST__K_RESET_LINUM_INCR:
(*_bfd_error_handler)
(_("DST__K_RESET_LINUM_INCR not implemented"));
cmd_length = 1;
break;
case DST__K_BEG_STMT_MODE:
(*_bfd_error_handler)
(_("DST__K_BEG_STMT_MODE not implemented"));
cmd_length = 1;
break;
case DST__K_END_STMT_MODE:
(*_bfd_error_handler)
(_("DST__K_END_STMT_MODE not implemented"));
cmd_length = 1;
break;
case DST__K_SET_LINUM_B:
data = pcl_ptr[DST_S_B_PCLINE_UNSBYTE];
curr_linenum = data;
cmd_length = 2;
vms_debug2 ((4, "DST__K_SET_LINUM_B: %d\n", data));
break;
case DST__K_SET_LINUM:
data = bfd_getl16 (pcl_ptr + DST_S_W_PCLINE_UNSWORD);
curr_linenum = data;
cmd_length = 3;
vms_debug2 ((4, "DST__K_SET_LINE_NUM: %d\n", data));
break;
case DST__K_SET_LINUM_L:
data = bfd_getl32 (pcl_ptr + DST_S_L_PCLINE_UNSLONG);
curr_linenum = data;
cmd_length = 5;
vms_debug2 ((4, "DST__K_SET_LINUM_L: %d\n", data));
break;
case DST__K_SET_PC:
(*_bfd_error_handler)
(_("DST__K_SET_PC not implemented"));
cmd_length = 2;
break;
case DST__K_SET_PC_W:
(*_bfd_error_handler)
(_("DST__K_SET_PC_W not implemented"));
cmd_length = 3;
break;
case DST__K_SET_PC_L:
(*_bfd_error_handler)
(_("DST__K_SET_PC_L not implemented"));
cmd_length = 5;
break;
case DST__K_SET_STMTNUM:
(*_bfd_error_handler)
(_("DST__K_SET_STMTNUM not implemented"));
cmd_length = 2;
break;
case DST__K_TERM:
data = pcl_ptr[DST_S_B_PCLINE_UNSBYTE];
curr_pc += data;
cmd_length = 2;
vms_debug2 ((4, "DST__K_TERM: %d\n", data));
break;
case DST__K_TERM_W:
data = bfd_getl16 (pcl_ptr + DST_S_W_PCLINE_UNSWORD);
curr_pc += data;
cmd_length = 3;
vms_debug2 ((4, "DST__K_TERM_W: %d\n", data));
break;
case DST__K_TERM_L:
data = bfd_getl32 (pcl_ptr + DST_S_L_PCLINE_UNSLONG);
curr_pc += data;
cmd_length = 5;
vms_debug2 ((4, "DST__K_TERM_L: %d\n", data));
break;
case DST__K_SET_ABS_PC:
data = bfd_getl32 (pcl_ptr + DST_S_L_PCLINE_UNSLONG);
curr_pc = data;
cmd_length = 5;
vms_debug2 ((4, "DST__K_SET_ABS_PC: 0x%x\n", data));
break;
default:
if (cmd <= 0)
{
curr_pc -= cmd;
curr_linenum += 1;
cmd_length = 1;
vms_debug2 ((4, "bump pc to 0x%lx and line to %d\n",
(unsigned long)curr_pc, curr_linenum));
}
else
{
(*_bfd_error_handler) (_("unknown line command %d"),
cmd);
cmd_length = 2;
}
break;
}
if ((curr_linenum != prev_linum && curr_pc != prev_pc)
|| cmd <= 0
|| cmd == DST__K_DELTA_PC_L
|| cmd == DST__K_DELTA_PC_W)
{
line = (struct lineinfo *)
bfd_zalloc (abfd, sizeof (struct lineinfo));
line->address = curr_pc;
line->line = curr_linenum;
curr_line->next = line;
curr_line = line;
prev_linum = curr_linenum;
prev_pc = curr_pc;
vms_debug2 ((4, "-> correlate pc 0x%lx with line %d\n",
(unsigned long)curr_pc, curr_linenum));
}
pcl_ptr += cmd_length;
}
break;
case 0x17: /* Undocumented type used by DEC C to declare equates. */
vms_debug2 ((3, "undocumented type 0x17\n"));
break;
default:
vms_debug2 ((3, "ignoring record\n"));
break;
}
ptr += rec_length;
}
/* Finalize tables with EOL marker. */
srec = (struct srecinfo *) bfd_zalloc (abfd, sizeof (struct srecinfo));
srec->line = (unsigned int) -1;
srec->srec = (unsigned int) -1;
curr_srec->next = srec;
line = (struct lineinfo *) bfd_zalloc (abfd, sizeof (struct lineinfo));
line->line = (unsigned int) -1;
line->address = (bfd_vma) -1;
curr_line->next = line;
/* Advertise that this module has been parsed. This is needed
because parsing can be either performed at module creation
or deferred until debug info is consumed. */
SET_MODULE_PARSED (module);
}
/* Build the list of modules for the specified BFD. */
static struct module *
build_module_list (bfd *abfd)
{
struct module *module, *list = NULL;
asection *dmt;
if ((dmt = bfd_get_section_by_name (abfd, "$DMT$")))
{
/* We have a DMT section so this must be an image. Parse the
section and build the list of modules. This is sufficient
since we can compute the start address and the end address
of every module from the section contents. */
bfd_size_type size = bfd_get_section_size (dmt);
unsigned char *ptr, *end;
ptr = (unsigned char *) bfd_alloc (abfd, size);
if (! ptr)
return NULL;
if (! bfd_get_section_contents (abfd, dmt, ptr, 0, size))
return NULL;
vms_debug2 ((2, "DMT\n"));
end = ptr + size;
while (ptr < end)
{
/* Each header declares a module with its start offset and size
of debug info in the DST section, as well as the count of
program sections (i.e. address spans) it contains. */
int modbeg = bfd_getl32 (ptr + DBG_S_L_DMT_MODBEG);
int msize = bfd_getl32 (ptr + DBG_S_L_DST_SIZE);
int count = bfd_getl16 (ptr + DBG_S_W_DMT_PSECT_COUNT);
ptr += DBG_S_C_DMT_HEADER_SIZE;
vms_debug2 ((3, "module: modbeg = %d, size = %d, count = %d\n",
modbeg, msize, count));
/* We create a 'module' structure for each program section since
we only support contiguous addresses in a 'module' structure.
As a consequence, the actual debug info in the DST section is
shared and can be parsed multiple times; that doesn't seem to
cause problems in practice. */
while (count-- > 0)
{
int start = bfd_getl32 (ptr + DBG_S_L_DMT_PSECT_START);
int length = bfd_getl32 (ptr + DBG_S_L_DMT_PSECT_LENGTH);
module = new_module (abfd);
module->modbeg = modbeg;
module->size = msize;
module->low = start;
module->high = start + length;
module->next = list;
list = module;
ptr += DBG_S_C_DMT_PSECT_SIZE;
vms_debug2 ((4, "section: start = 0x%x, length = %d\n",
start, length));
}
}
}
else
{
/* We don't have a DMT section so this must be an object. Parse
the module right now in order to compute its start address and
end address. */
void *dst = PRIV (dst_section)->contents;
if (dst == NULL)
return NULL;
module = new_module (abfd);
parse_module (abfd, module, PRIV (dst_section)->contents, -1);
list = module;
}
return list;
}
/* Calculate and return the name of the source file and the line nearest
to the wanted location in the specified module. */
static bfd_boolean
module_find_nearest_line (bfd *abfd, struct module *module, bfd_vma addr,
const char **file, const char **func,
unsigned int *line)
{
struct funcinfo *funcinfo;
struct lineinfo *lineinfo;
struct srecinfo *srecinfo;
bfd_boolean ret = FALSE;
/* Parse this module if that was not done at module creation. */
if (! IS_MODULE_PARSED (module))
{
unsigned int size = module->size;
unsigned int modbeg = PRIV (dst_section)->filepos + module->modbeg;
unsigned char *buffer = (unsigned char *) bfd_malloc (module->size);
if (bfd_seek (abfd, modbeg, SEEK_SET) != 0
|| bfd_bread (buffer, size, abfd) != size)
{
bfd_set_error (bfd_error_no_debug_section);
return FALSE;
}
parse_module (abfd, module, buffer, size);
free (buffer);
}
/* Find out the function (if any) that contains the address. */
for (funcinfo = module->func_table; funcinfo; funcinfo = funcinfo->next)
if (addr >= funcinfo->low && addr <= funcinfo->high)
{
*func = funcinfo->name;
ret = TRUE;
break;
}
/* Find out the source file and the line nearest to the address. */
for (lineinfo = module->line_table; lineinfo; lineinfo = lineinfo->next)
if (lineinfo->next && addr < lineinfo->next->address)
{
for (srecinfo = module->srec_table; srecinfo; srecinfo = srecinfo->next)
if (srecinfo->next && lineinfo->line < srecinfo->next->line)
{
if (srecinfo->sfile > 0)
{
*file = module->file_table[srecinfo->sfile].name;
*line = srecinfo->srec + lineinfo->line - srecinfo->line;
}
else
{
*file = module->name;
*line = lineinfo->line;
}
return TRUE;
}
break;
}
return ret;
}
/* Provided a BFD, a section and an offset into the section, calculate and
return the name of the source file and the line nearest to the wanted
location. */
static bfd_boolean
_bfd_vms_find_nearest_line (bfd *abfd,
asymbol **symbols ATTRIBUTE_UNUSED,
asection *section,
bfd_vma offset,
const char **file,
const char **func,
unsigned int *line,
unsigned int *discriminator)
{
struct module *module;
/* What address are we looking for? */
bfd_vma addr = section->vma + offset;
*file = NULL;
*func = NULL;
*line = 0;
if (discriminator)
*discriminator = 0;
/* We can't do anything if there is no DST (debug symbol table). */
if (PRIV (dst_section) == NULL)
return FALSE;
/* Create the module list - if not already done. */
if (PRIV (modules) == NULL)
{
PRIV (modules) = build_module_list (abfd);
if (PRIV (modules) == NULL)
return FALSE;
}
for (module = PRIV (modules); module; module = module->next)
if (addr >= module->low && addr <= module->high)
return module_find_nearest_line (abfd, module, addr, file, func, line);
return FALSE;
}
/* Canonicalizations. */
/* Set name, value, section and flags of SYM from E. */
static bfd_boolean
alpha_vms_convert_symbol (bfd *abfd, struct vms_symbol_entry *e, asymbol *sym)
{
flagword flags;
symvalue value;
asection *sec;
const char *name;
name = e->name;
value = 0;
flags = BSF_NO_FLAGS;
sec = NULL;
switch (e->typ)
{
case EGSD__C_SYM:
if (e->flags & EGSY__V_WEAK)
flags |= BSF_WEAK;
if (e->flags & EGSY__V_DEF)
{
/* Symbol definition. */
flags |= BSF_GLOBAL;
if (e->flags & EGSY__V_NORM)
flags |= BSF_FUNCTION;
value = e->value;
sec = e->section;
}
else
{
/* Symbol reference. */
sec = bfd_und_section_ptr;
}
break;
case EGSD__C_SYMG:
/* A universal symbol is by definition global... */
flags |= BSF_GLOBAL;
/* ...and dynamic in shared libraries. */
if (abfd->flags & DYNAMIC)
flags |= BSF_DYNAMIC;
if (e->flags & EGSY__V_WEAK)
flags |= BSF_WEAK;
if (!(e->flags & EGSY__V_DEF))
abort ();
if (e->flags & EGSY__V_NORM)
flags |= BSF_FUNCTION;
value = e->value;
/* sec = e->section; */
sec = bfd_abs_section_ptr;
break;
default:
return FALSE;
}
sym->name = name;
sym->section = sec;
sym->flags = flags;
sym->value = value;
return TRUE;
}
/* Return the number of bytes required to store a vector of pointers
to asymbols for all the symbols in the BFD abfd, including a
terminal NULL pointer. If there are no symbols in the BFD,
then return 0. If an error occurs, return -1. */
static long
alpha_vms_get_symtab_upper_bound (bfd *abfd)
{
vms_debug2 ((1, "alpha_vms_get_symtab_upper_bound (%p), %d symbols\n",
abfd, PRIV (gsd_sym_count)));
return (PRIV (gsd_sym_count) + 1) * sizeof (asymbol *);
}
/* Read the symbols from the BFD abfd, and fills in the vector
location with pointers to the symbols and a trailing NULL.
Return number of symbols read. */
static long
alpha_vms_canonicalize_symtab (bfd *abfd, asymbol **symbols)
{
unsigned int i;
vms_debug2 ((1, "alpha_vms_canonicalize_symtab (%p, <ret>)\n", abfd));
if (PRIV (csymbols) == NULL)
{
PRIV (csymbols) = (asymbol **) bfd_alloc
(abfd, PRIV (gsd_sym_count) * sizeof (asymbol *));
/* Traverse table and fill symbols vector. */
for (i = 0; i < PRIV (gsd_sym_count); i++)
{
struct vms_symbol_entry *e = PRIV (syms)[i];
asymbol *sym;
sym = bfd_make_empty_symbol (abfd);
if (sym == NULL || !alpha_vms_convert_symbol (abfd, e, sym))
{
bfd_release (abfd, PRIV (csymbols));
PRIV (csymbols) = NULL;
return -1;
}
PRIV (csymbols)[i] = sym;
}
}
if (symbols != NULL)
{
for (i = 0; i < PRIV (gsd_sym_count); i++)
symbols[i] = PRIV (csymbols)[i];
symbols[i] = NULL;
}
return PRIV (gsd_sym_count);
}
/* Read and convert relocations from ETIR. We do it once for all sections. */
static bfd_boolean
alpha_vms_slurp_relocs (bfd *abfd)
{
int cur_psect = -1;
vms_debug2 ((3, "alpha_vms_slurp_relocs\n"));
/* We slurp relocs only once, for all sections. */
if (PRIV (reloc_done))
return TRUE;
PRIV (reloc_done) = TRUE;
if (alpha_vms_canonicalize_symtab (abfd, NULL) < 0)
return FALSE;
if (bfd_seek (abfd, 0, SEEK_SET) != 0)
return FALSE;
while (1)
{
unsigned char *begin;
unsigned char *end;
unsigned char *ptr;
bfd_reloc_code_real_type reloc_code;
int type;
bfd_vma vaddr = 0;
int length;
bfd_vma cur_address;
int cur_psidx = -1;
unsigned char *cur_sym = NULL;
int prev_cmd = -1;
bfd_vma cur_addend = 0;
/* Skip non-ETIR records. */
type = _bfd_vms_get_object_record (abfd);
if (type == EOBJ__C_EEOM)
break;
if (type != EOBJ__C_ETIR)
continue;
begin = PRIV (recrd.rec) + 4;
end = PRIV (recrd.rec) + PRIV (recrd.rec_size);
for (ptr = begin; ptr < end; ptr += length)
{
int cmd;
cmd = bfd_getl16 (ptr);
length = bfd_getl16 (ptr + 2);
cur_address = vaddr;
vms_debug2 ((4, "alpha_vms_slurp_relocs: etir %s\n",
_bfd_vms_etir_name (cmd)));
switch (cmd)
{
case ETIR__C_STA_GBL: /* ALPHA_R_REFLONG und_section, step 1 */
/* ALPHA_R_REFQUAD und_section, step 1 */
cur_sym = ptr + 4;
prev_cmd = cmd;
continue;
case ETIR__C_STA_PQ: /* ALPHA_R_REF{LONG|QUAD}, others part 1 */
cur_psidx = bfd_getl32 (ptr + 4);
cur_addend = bfd_getl64 (ptr + 8);
prev_cmd = cmd;
continue;
case ETIR__C_CTL_SETRB:
if (prev_cmd != ETIR__C_STA_PQ)
{
(*_bfd_error_handler)
(_("Unknown reloc %s + %s"), _bfd_vms_etir_name (prev_cmd),
_bfd_vms_etir_name (cmd));
return FALSE;
}
cur_psect = cur_psidx;
vaddr = cur_addend;
cur_psidx = -1;
cur_addend = 0;
continue;
case ETIR__C_STA_LW: /* ALPHA_R_REFLONG abs_section, step 1 */
/* ALPHA_R_REFLONG und_section, step 2 */
if (prev_cmd != -1)
{
if (prev_cmd != ETIR__C_STA_GBL)
{
(*_bfd_error_handler)
(_("Unknown reloc %s + %s"), _bfd_vms_etir_name (cmd),
_bfd_vms_etir_name (ETIR__C_STA_LW));
return FALSE;
}
}
cur_addend = bfd_getl32 (ptr + 4);
prev_cmd = cmd;
continue;
case ETIR__C_STA_QW: /* ALPHA_R_REFQUAD abs_section, step 1 */
/* ALPHA_R_REFQUAD und_section, step 2 */
if (prev_cmd != -1 && prev_cmd != ETIR__C_STA_GBL)
{
(*_bfd_error_handler)
(_("Unknown reloc %s + %s"), _bfd_vms_etir_name (cmd),
_bfd_vms_etir_name (ETIR__C_STA_QW));
return FALSE;
}
cur_addend = bfd_getl64 (ptr + 4);
prev_cmd = cmd;
continue;
case ETIR__C_STO_LW: /* ALPHA_R_REFLONG und_section, step 4 */
/* ALPHA_R_REFLONG abs_section, step 2 */
/* ALPHA_R_REFLONG others, step 2 */
if (prev_cmd != ETIR__C_OPR_ADD
&& prev_cmd != ETIR__C_STA_LW
&& prev_cmd != ETIR__C_STA_PQ)
{
(*_bfd_error_handler) (_("Unknown reloc %s + %s"),
_bfd_vms_etir_name (prev_cmd),
_bfd_vms_etir_name (ETIR__C_STO_LW));
return FALSE;
}
reloc_code = BFD_RELOC_32;
break;
case ETIR__C_STO_QW: /* ALPHA_R_REFQUAD und_section, step 4 */
/* ALPHA_R_REFQUAD abs_section, step 2 */
if (prev_cmd != ETIR__C_OPR_ADD && prev_cmd != ETIR__C_STA_QW)
{
(*_bfd_error_handler) (_("Unknown reloc %s + %s"),
_bfd_vms_etir_name (prev_cmd),
_bfd_vms_etir_name (ETIR__C_STO_QW));
return FALSE;
}
reloc_code = BFD_RELOC_64;
break;
case ETIR__C_STO_OFF: /* ALPHA_R_REFQUAD others, step 2 */
if (prev_cmd != ETIR__C_STA_PQ)
{
(*_bfd_error_handler) (_("Unknown reloc %s + %s"),
_bfd_vms_etir_name (prev_cmd),
_bfd_vms_etir_name (ETIR__C_STO_OFF));
return FALSE;
}
reloc_code = BFD_RELOC_64;
break;
case ETIR__C_OPR_ADD: /* ALPHA_R_REFLONG und_section, step 3 */
/* ALPHA_R_REFQUAD und_section, step 3 */
if (prev_cmd != ETIR__C_STA_LW && prev_cmd != ETIR__C_STA_QW)
{
(*_bfd_error_handler) (_("Unknown reloc %s + %s"),
_bfd_vms_etir_name (prev_cmd),
_bfd_vms_etir_name (ETIR__C_OPR_ADD));
return FALSE;
}
prev_cmd = ETIR__C_OPR_ADD;
continue;
case ETIR__C_STO_CA: /* ALPHA_R_CODEADDR */
reloc_code = BFD_RELOC_ALPHA_CODEADDR;
cur_sym = ptr + 4;
break;
case ETIR__C_STO_GBL: /* ALPHA_R_REFQUAD und_section */
reloc_code = BFD_RELOC_64;
cur_sym = ptr + 4;
break;
case ETIR__C_STO_GBL_LW: /* ALPHA_R_REFLONG und_section */
reloc_code = BFD_RELOC_32;
cur_sym = ptr + 4;
break;
case ETIR__C_STC_LP_PSB: /* ALPHA_R_LINKAGE */
reloc_code = BFD_RELOC_ALPHA_LINKAGE;
cur_sym = ptr + 8;
break;
case ETIR__C_STC_NOP_GBL: /* ALPHA_R_NOP */
reloc_code = BFD_RELOC_ALPHA_NOP;
goto call_reloc;
case ETIR__C_STC_BSR_GBL: /* ALPHA_R_BSR */
reloc_code = BFD_RELOC_ALPHA_BSR;
goto call_reloc;
case ETIR__C_STC_LDA_GBL: /* ALPHA_R_LDA */
reloc_code = BFD_RELOC_ALPHA_LDA;
goto call_reloc;
case ETIR__C_STC_BOH_GBL: /* ALPHA_R_BOH */
reloc_code = BFD_RELOC_ALPHA_BOH;
goto call_reloc;
call_reloc:
cur_sym = ptr + 4 + 32;
cur_address = bfd_getl64 (ptr + 4 + 8);
cur_addend = bfd_getl64 (ptr + 4 + 24);
break;
case ETIR__C_STO_IMM:
vaddr += bfd_getl32 (ptr + 4);
continue;
default:
(*_bfd_error_handler) (_("Unknown reloc %s"),
_bfd_vms_etir_name (cmd));
return FALSE;
}
{
asection *sec;
struct vms_section_data_struct *vms_sec;
arelent *reloc;
/* Get section to which the relocation applies. */
if (cur_psect < 0 || cur_psect > (int)PRIV (section_count))
{
(*_bfd_error_handler) (_("Invalid section index in ETIR"));
return FALSE;
}
sec = PRIV (sections)[cur_psect];
if (sec == bfd_abs_section_ptr)
{
(*_bfd_error_handler) (_("Relocation for non-REL psect"));
return FALSE;
}
vms_sec = vms_section_data (sec);
/* Allocate a reloc entry. */
if (sec->reloc_count >= vms_sec->reloc_max)
{
if (vms_sec->reloc_max == 0)
{
vms_sec->reloc_max = 64;
sec->relocation = bfd_zmalloc
(vms_sec->reloc_max * sizeof (arelent));
}
else
{
vms_sec->reloc_max *= 2;
sec->relocation = bfd_realloc
(sec->relocation, vms_sec->reloc_max * sizeof (arelent));
}
}
reloc = &sec->relocation[sec->reloc_count];
sec->reloc_count++;
reloc->howto = bfd_reloc_type_lookup (abfd, reloc_code);
if (cur_sym != NULL)
{
unsigned int j;
unsigned int symlen = *cur_sym;
asymbol **sym;
/* Linear search. */
symlen = *cur_sym;
cur_sym++;
sym = NULL;
for (j = 0; j < PRIV (gsd_sym_count); j++)
if (PRIV (syms)[j]->namelen == symlen
&& memcmp (PRIV (syms)[j]->name, cur_sym, symlen) == 0)
{
sym = &PRIV (csymbols)[j];
break;
}
if (sym == NULL)
{
(*_bfd_error_handler) (_("Unknown symbol in command %s"),
_bfd_vms_etir_name (cmd));
reloc->sym_ptr_ptr = NULL;
}
else
reloc->sym_ptr_ptr = sym;
}
else if (cur_psidx >= 0)
reloc->sym_ptr_ptr =
PRIV (sections)[cur_psidx]->symbol_ptr_ptr;
else
reloc->sym_ptr_ptr = NULL;
reloc->address = cur_address;
reloc->addend = cur_addend;
vaddr += bfd_get_reloc_size (reloc->howto);
}
cur_addend = 0;
prev_cmd = -1;
cur_sym = NULL;
cur_psidx = -1;
}
}
vms_debug2 ((3, "alpha_vms_slurp_relocs: result = TRUE\n"));
return TRUE;
}
/* Return the number of bytes required to store the relocation
information associated with the given section. */
static long
alpha_vms_get_reloc_upper_bound (bfd *abfd ATTRIBUTE_UNUSED, asection *section)
{
alpha_vms_slurp_relocs (abfd);
return (section->reloc_count + 1) * sizeof (arelent *);
}
/* Convert relocations from VMS (external) form into BFD internal
form. Return the number of relocations. */
static long
alpha_vms_canonicalize_reloc (bfd *abfd, asection *section, arelent **relptr,
asymbol **symbols ATTRIBUTE_UNUSED)
{
arelent *tblptr;
int count;
if (!alpha_vms_slurp_relocs (abfd))
return -1;
count = section->reloc_count;
tblptr = section->relocation;
while (count--)
*relptr++ = tblptr++;
*relptr = (arelent *) NULL;
return section->reloc_count;
}
/* This is just copied from ecoff-alpha, needs to be fixed probably. */
/* How to process the various reloc types. */
static bfd_reloc_status_type
reloc_nil (bfd * abfd ATTRIBUTE_UNUSED,
arelent *reloc ATTRIBUTE_UNUSED,
asymbol *sym ATTRIBUTE_UNUSED,
void * data ATTRIBUTE_UNUSED,
asection *sec ATTRIBUTE_UNUSED,
bfd *output_bfd ATTRIBUTE_UNUSED,
char **error_message ATTRIBUTE_UNUSED)
{
#if VMS_DEBUG
vms_debug (1, "reloc_nil (abfd %p, output_bfd %p)\n", abfd, output_bfd);
vms_debug (2, "In section %s, symbol %s\n",
sec->name, sym->name);
vms_debug (2, "reloc sym %s, addr %08lx, addend %08lx, reloc is a %s\n",
reloc->sym_ptr_ptr[0]->name,
(unsigned long)reloc->address,
(unsigned long)reloc->addend, reloc->howto->name);
vms_debug (2, "data at %p\n", data);
/* _bfd_hexdump (2, data, bfd_get_reloc_size (reloc->howto), 0); */
#endif
return bfd_reloc_ok;
}
/* In case we're on a 32-bit machine, construct a 64-bit "-1" value
from smaller values. Start with zero, widen, *then* decrement. */
#define MINUS_ONE (((bfd_vma)0) - 1)
static reloc_howto_type alpha_howto_table[] =
{
HOWTO (ALPHA_R_IGNORE, /* Type. */
0, /* Rightshift. */
0, /* Size (0 = byte, 1 = short, 2 = long). */
8, /* Bitsize. */
TRUE, /* PC relative. */
0, /* Bitpos. */
complain_overflow_dont,/* Complain_on_overflow. */
reloc_nil, /* Special_function. */
"IGNORE", /* Name. */
TRUE, /* Partial_inplace. */
0, /* Source mask */
0, /* Dest mask. */
TRUE), /* PC rel offset. */
/* A 64 bit reference to a symbol. */
HOWTO (ALPHA_R_REFQUAD, /* Type. */
0, /* Rightshift. */
4, /* Size (0 = byte, 1 = short, 2 = long). */
64, /* Bitsize. */
FALSE, /* PC relative. */
0, /* Bitpos. */
complain_overflow_bitfield, /* Complain_on_overflow. */
reloc_nil, /* Special_function. */
"REFQUAD", /* Name. */
TRUE, /* Partial_inplace. */
MINUS_ONE, /* Source mask. */
MINUS_ONE, /* Dest mask. */
FALSE), /* PC rel offset. */
/* A 21 bit branch. The native assembler generates these for
branches within the text segment, and also fills in the PC
relative offset in the instruction. */
HOWTO (ALPHA_R_BRADDR, /* Type. */
2, /* Rightshift. */
2, /* Size (0 = byte, 1 = short, 2 = long). */
21, /* Bitsize. */
TRUE, /* PC relative. */
0, /* Bitpos. */
complain_overflow_signed, /* Complain_on_overflow. */
reloc_nil, /* Special_function. */
"BRADDR", /* Name. */
TRUE, /* Partial_inplace. */
0x1fffff, /* Source mask. */
0x1fffff, /* Dest mask. */
FALSE), /* PC rel offset. */
/* A hint for a jump to a register. */
HOWTO (ALPHA_R_HINT, /* Type. */
2, /* Rightshift. */
1, /* Size (0 = byte, 1 = short, 2 = long). */
14, /* Bitsize. */
TRUE, /* PC relative. */
0, /* Bitpos. */
complain_overflow_dont,/* Complain_on_overflow. */
reloc_nil, /* Special_function. */
"HINT", /* Name. */
TRUE, /* Partial_inplace. */
0x3fff, /* Source mask. */
0x3fff, /* Dest mask. */
FALSE), /* PC rel offset. */
/* 16 bit PC relative offset. */
HOWTO (ALPHA_R_SREL16, /* Type. */
0, /* Rightshift. */
1, /* Size (0 = byte, 1 = short, 2 = long). */
16, /* Bitsize. */
TRUE, /* PC relative. */
0, /* Bitpos. */
complain_overflow_signed, /* Complain_on_overflow. */
reloc_nil, /* Special_function. */
"SREL16", /* Name. */
TRUE, /* Partial_inplace. */
0xffff, /* Source mask. */
0xffff, /* Dest mask. */
FALSE), /* PC rel offset. */
/* 32 bit PC relative offset. */
HOWTO (ALPHA_R_SREL32, /* Type. */
0, /* Rightshift. */
2, /* Size (0 = byte, 1 = short, 2 = long). */
32, /* Bitsize. */
TRUE, /* PC relative. */
0, /* Bitpos. */
complain_overflow_signed, /* Complain_on_overflow. */
reloc_nil, /* Special_function. */
"SREL32", /* Name. */
TRUE, /* Partial_inplace. */
0xffffffff, /* Source mask. */
0xffffffff, /* Dest mask. */
FALSE), /* PC rel offset. */
/* A 64 bit PC relative offset. */
HOWTO (ALPHA_R_SREL64, /* Type. */
0, /* Rightshift. */
4, /* Size (0 = byte, 1 = short, 2 = long). */
64, /* Bitsize. */
TRUE, /* PC relative. */
0, /* Bitpos. */
complain_overflow_signed, /* Complain_on_overflow. */
reloc_nil, /* Special_function. */
"SREL64", /* Name. */
TRUE, /* Partial_inplace. */
MINUS_ONE, /* Source mask. */
MINUS_ONE, /* Dest mask. */
FALSE), /* PC rel offset. */
/* Push a value on the reloc evaluation stack. */
HOWTO (ALPHA_R_OP_PUSH, /* Type. */
0, /* Rightshift. */
0, /* Size (0 = byte, 1 = short, 2 = long). */
0, /* Bitsize. */
FALSE, /* PC relative. */
0, /* Bitpos. */
complain_overflow_dont,/* Complain_on_overflow. */
reloc_nil, /* Special_function. */
"OP_PUSH", /* Name. */
FALSE, /* Partial_inplace. */
0, /* Source mask. */
0, /* Dest mask. */
FALSE), /* PC rel offset. */
/* Store the value from the stack at the given address. Store it in
a bitfield of size r_size starting at bit position r_offset. */
HOWTO (ALPHA_R_OP_STORE, /* Type. */
0, /* Rightshift. */
4, /* Size (0 = byte, 1 = short, 2 = long). */
64, /* Bitsize. */
FALSE, /* PC relative. */
0, /* Bitpos. */
complain_overflow_dont,/* Complain_on_overflow. */
reloc_nil, /* Special_function. */
"OP_STORE", /* Name. */
FALSE, /* Partial_inplace. */
0, /* Source mask. */
MINUS_ONE, /* Dest mask. */
FALSE), /* PC rel offset. */
/* Subtract the reloc address from the value on the top of the
relocation stack. */
HOWTO (ALPHA_R_OP_PSUB, /* Type. */
0, /* Rightshift. */
0, /* Size (0 = byte, 1 = short, 2 = long). */
0, /* Bitsize. */
FALSE, /* PC relative. */
0, /* Bitpos. */
complain_overflow_dont,/* Complain_on_overflow. */
reloc_nil, /* Special_function. */
"OP_PSUB", /* Name. */
FALSE, /* Partial_inplace. */
0, /* Source mask. */
0, /* Dest mask. */
FALSE), /* PC rel offset. */
/* Shift the value on the top of the relocation stack right by the
given value. */
HOWTO (ALPHA_R_OP_PRSHIFT, /* Type. */
0, /* Rightshift. */
0, /* Size (0 = byte, 1 = short, 2 = long). */
0, /* Bitsize. */
FALSE, /* PC relative. */
0, /* Bitpos. */
complain_overflow_dont,/* Complain_on_overflow. */
reloc_nil, /* Special_function. */
"OP_PRSHIFT", /* Name. */
FALSE, /* Partial_inplace. */
0, /* Source mask. */
0, /* Dest mask. */
FALSE), /* PC rel offset. */
/* Hack. Linkage is done by linker. */
HOWTO (ALPHA_R_LINKAGE, /* Type. */
0, /* Rightshift. */
8, /* Size (0 = byte, 1 = short, 2 = long). */
256, /* Bitsize. */
FALSE, /* PC relative. */
0, /* Bitpos. */
complain_overflow_dont,/* Complain_on_overflow. */
reloc_nil, /* Special_function. */
"LINKAGE", /* Name. */
FALSE, /* Partial_inplace. */
0, /* Source mask. */
0, /* Dest mask. */
FALSE), /* PC rel offset. */
/* A 32 bit reference to a symbol. */
HOWTO (ALPHA_R_REFLONG, /* Type. */
0, /* Rightshift. */
2, /* Size (0 = byte, 1 = short, 2 = long). */
32, /* Bitsize. */
FALSE, /* PC relative. */
0, /* Bitpos. */
complain_overflow_bitfield, /* Complain_on_overflow. */
reloc_nil, /* Special_function. */
"REFLONG", /* Name. */
TRUE, /* Partial_inplace. */
0xffffffff, /* Source mask. */
0xffffffff, /* Dest mask. */
FALSE), /* PC rel offset. */
/* A 64 bit reference to a procedure, written as 32 bit value. */
HOWTO (ALPHA_R_CODEADDR, /* Type. */
0, /* Rightshift. */
4, /* Size (0 = byte, 1 = short, 2 = long). */
64, /* Bitsize. */
FALSE, /* PC relative. */
0, /* Bitpos. */
complain_overflow_signed,/* Complain_on_overflow. */
reloc_nil, /* Special_function. */
"CODEADDR", /* Name. */
FALSE, /* Partial_inplace. */
0xffffffff, /* Source mask. */
0xffffffff, /* Dest mask. */
FALSE), /* PC rel offset. */
HOWTO (ALPHA_R_NOP, /* Type. */
0, /* Rightshift. */
3, /* Size (0 = byte, 1 = short, 2 = long). */
0, /* Bitsize. */
/* The following value must match that of ALPHA_R_BSR/ALPHA_R_BOH
because the calculations for the 3 relocations are the same.
See B.4.5.2 of the OpenVMS Linker Utility Manual. */
TRUE, /* PC relative. */
0, /* Bitpos. */
complain_overflow_dont,/* Complain_on_overflow. */
reloc_nil, /* Special_function. */
"NOP", /* Name. */
FALSE, /* Partial_inplace. */
0xffffffff, /* Source mask. */
0xffffffff, /* Dest mask. */
FALSE), /* PC rel offset. */
HOWTO (ALPHA_R_BSR, /* Type. */
0, /* Rightshift. */
3, /* Size (0 = byte, 1 = short, 2 = long). */
0, /* Bitsize. */
TRUE, /* PC relative. */
0, /* Bitpos. */
complain_overflow_dont,/* Complain_on_overflow. */
reloc_nil, /* Special_function. */
"BSR", /* Name. */
FALSE, /* Partial_inplace. */
0xffffffff, /* Source mask. */
0xffffffff, /* Dest mask. */
FALSE), /* PC rel offset. */
HOWTO (ALPHA_R_LDA, /* Type. */
0, /* Rightshift. */
3, /* Size (0 = byte, 1 = short, 2 = long). */
0, /* Bitsize. */
FALSE, /* PC relative. */
0, /* Bitpos. */
complain_overflow_dont,/* Complain_on_overflow. */
reloc_nil, /* Special_function. */
"LDA", /* Name. */
FALSE, /* Partial_inplace. */
0xffffffff, /* Source mask. */
0xffffffff, /* Dest mask. */
FALSE), /* PC rel offset. */
HOWTO (ALPHA_R_BOH, /* Type. */
0, /* Rightshift. */
3, /* Size (0 = byte, 1 = short, 2 = long, 3 = nil). */
0, /* Bitsize. */
TRUE, /* PC relative. */
0, /* Bitpos. */
complain_overflow_dont,/* Complain_on_overflow. */
reloc_nil, /* Special_function. */
"BOH", /* Name. */
FALSE, /* Partial_inplace. */
0xffffffff, /* Source mask. */
0xffffffff, /* Dest mask. */
FALSE), /* PC rel offset. */
};
/* Return a pointer to a howto structure which, when invoked, will perform
the relocation code on data from the architecture noted. */
static const struct reloc_howto_struct *
alpha_vms_bfd_reloc_type_lookup (bfd * abfd ATTRIBUTE_UNUSED,
bfd_reloc_code_real_type code)
{
int alpha_type;
vms_debug2 ((1, "vms_bfd_reloc_type_lookup (%p, %d)\t", abfd, code));
switch (code)
{
case BFD_RELOC_16: alpha_type = ALPHA_R_SREL16; break;
case BFD_RELOC_32: alpha_type = ALPHA_R_REFLONG; break;
case BFD_RELOC_64: alpha_type = ALPHA_R_REFQUAD; break;
case BFD_RELOC_CTOR: alpha_type = ALPHA_R_REFQUAD; break;
case BFD_RELOC_23_PCREL_S2: alpha_type = ALPHA_R_BRADDR; break;
case BFD_RELOC_ALPHA_HINT: alpha_type = ALPHA_R_HINT; break;
case BFD_RELOC_16_PCREL: alpha_type = ALPHA_R_SREL16; break;
case BFD_RELOC_32_PCREL: alpha_type = ALPHA_R_SREL32; break;
case BFD_RELOC_64_PCREL: alpha_type = ALPHA_R_SREL64; break;
case BFD_RELOC_ALPHA_LINKAGE: alpha_type = ALPHA_R_LINKAGE; break;
case BFD_RELOC_ALPHA_CODEADDR: alpha_type = ALPHA_R_CODEADDR; break;
case BFD_RELOC_ALPHA_NOP: alpha_type = ALPHA_R_NOP; break;
case BFD_RELOC_ALPHA_BSR: alpha_type = ALPHA_R_BSR; break;
case BFD_RELOC_ALPHA_LDA: alpha_type = ALPHA_R_LDA; break;
case BFD_RELOC_ALPHA_BOH: alpha_type = ALPHA_R_BOH; break;
default:
(*_bfd_error_handler) ("reloc (%d) is *UNKNOWN*", code);
return NULL;
}
vms_debug2 ((2, "reloc is %s\n", alpha_howto_table[alpha_type].name));
return & alpha_howto_table[alpha_type];
}
static reloc_howto_type *
alpha_vms_bfd_reloc_name_lookup (bfd *abfd ATTRIBUTE_UNUSED,
const char *r_name)
{
unsigned int i;
for (i = 0;
i < sizeof (alpha_howto_table) / sizeof (alpha_howto_table[0]);
i++)
if (alpha_howto_table[i].name != NULL
&& strcasecmp (alpha_howto_table[i].name, r_name) == 0)
return &alpha_howto_table[i];
return NULL;
}
static long
alpha_vms_get_synthetic_symtab (bfd *abfd,
long symcount ATTRIBUTE_UNUSED,
asymbol **usyms ATTRIBUTE_UNUSED,
long dynsymcount ATTRIBUTE_UNUSED,
asymbol **dynsyms ATTRIBUTE_UNUSED,
asymbol **ret)
{
asymbol *syms;
unsigned int i;
unsigned int n = 0;
syms = (asymbol *) bfd_malloc (PRIV (norm_sym_count) * sizeof (asymbol));
*ret = syms;
if (syms == NULL)
return -1;
for (i = 0; i < PRIV (gsd_sym_count); i++)
{
struct vms_symbol_entry *e = PRIV (syms)[i];
asymbol *sym;
flagword flags;
symvalue value;
asection *sec;
const char *name;
char *sname;
int l;
name = e->name;
value = 0;
flags = BSF_LOCAL | BSF_SYNTHETIC;
sec = NULL;
switch (e->typ)
{
case EGSD__C_SYM:
case EGSD__C_SYMG:
if ((e->flags & EGSY__V_DEF) && (e->flags & EGSY__V_NORM))
{
value = e->code_value;
sec = e->code_section;
}
else
continue;
break;
default:
continue;
}
l = strlen (name);
sname = bfd_alloc (abfd, l + 5);
if (sname == NULL)
return FALSE;
memcpy (sname, name, l);
memcpy (sname + l, "..en", 5);
sym = &syms[n++];
sym->name = sname;
sym->section = sec;
sym->flags = flags;
sym->value = value;
sym->udata.p = NULL;
}
return n;
}
/* Private dump. */
static const char *
vms_time_to_str (unsigned char *buf)
{
time_t t = vms_rawtime_to_time_t (buf);
char *res = ctime (&t);
if (!res)
res = "*invalid time*";
else
res[24] = 0;
return res;
}
static void
evax_bfd_print_emh (FILE *file, unsigned char *rec, unsigned int rec_len)
{
struct vms_emh_common *emh = (struct vms_emh_common *)rec;
unsigned int subtype;
subtype = (unsigned)bfd_getl16 (emh->subtyp);
fprintf (file, _(" EMH %u (len=%u): "), subtype, rec_len);
switch (subtype)
{
case EMH__C_MHD:
{
struct vms_emh_mhd *mhd = (struct vms_emh_mhd *)rec;
const char *name;
fprintf (file, _("Module header\n"));
fprintf (file, _(" structure level: %u\n"), mhd->strlvl);
fprintf (file, _(" max record size: %u\n"),
(unsigned)bfd_getl32 (mhd->recsiz));
name = (char *)(mhd + 1);
fprintf (file, _(" module name : %.*s\n"), name[0], name + 1);
name += name[0] + 1;
fprintf (file, _(" module version : %.*s\n"), name[0], name + 1);
name += name[0] + 1;
fprintf (file, _(" compile date : %.17s\n"), name);
}
break;
case EMH__C_LNM:
{
fprintf (file, _("Language Processor Name\n"));
fprintf (file, _(" language name: %.*s\n"),
(int)(rec_len - sizeof (struct vms_emh_common)),
(char *)rec + sizeof (struct vms_emh_common));
}
break;
case EMH__C_SRC:
{
fprintf (file, _("Source Files Header\n"));
fprintf (file, _(" file: %.*s\n"),
(int)(rec_len - sizeof (struct vms_emh_common)),
(char *)rec + sizeof (struct vms_emh_common));
}
break;
case EMH__C_TTL:
{
fprintf (file, _("Title Text Header\n"));
fprintf (file, _(" title: %.*s\n"),
(int)(rec_len - sizeof (struct vms_emh_common)),
(char *)rec + sizeof (struct vms_emh_common));
}
break;
case EMH__C_CPR:
{
fprintf (file, _("Copyright Header\n"));
fprintf (file, _(" copyright: %.*s\n"),
(int)(rec_len - sizeof (struct vms_emh_common)),
(char *)rec + sizeof (struct vms_emh_common));
}
break;
default:
fprintf (file, _("unhandled emh subtype %u\n"), subtype);
break;
}
}
static void
evax_bfd_print_eeom (FILE *file, unsigned char *rec, unsigned int rec_len)
{
struct vms_eeom *eeom = (struct vms_eeom *)rec;
fprintf (file, _(" EEOM (len=%u):\n"), rec_len);
fprintf (file, _(" number of cond linkage pairs: %u\n"),
(unsigned)bfd_getl32 (eeom->total_lps));
fprintf (file, _(" completion code: %u\n"),
(unsigned)bfd_getl16 (eeom->comcod));
if (rec_len > 10)
{
fprintf (file, _(" transfer addr flags: 0x%02x\n"), eeom->tfrflg);
fprintf (file, _(" transfer addr psect: %u\n"),
(unsigned)bfd_getl32 (eeom->psindx));
fprintf (file, _(" transfer address : 0x%08x\n"),
(unsigned)bfd_getl32 (eeom->tfradr));
}
}
static void
exav_bfd_print_egsy_flags (unsigned int flags, FILE *file)
{
if (flags & EGSY__V_WEAK)
fputs (_(" WEAK"), file);
if (flags & EGSY__V_DEF)
fputs (_(" DEF"), file);
if (flags & EGSY__V_UNI)
fputs (_(" UNI"), file);
if (flags & EGSY__V_REL)
fputs (_(" REL"), file);
if (flags & EGSY__V_COMM)
fputs (_(" COMM"), file);
if (flags & EGSY__V_VECEP)
fputs (_(" VECEP"), file);
if (flags & EGSY__V_NORM)
fputs (_(" NORM"), file);
if (flags & EGSY__V_QUAD_VAL)
fputs (_(" QVAL"), file);
}
static void
evax_bfd_print_egsd_flags (FILE *file, unsigned int flags)
{
if (flags & EGPS__V_PIC)
fputs (_(" PIC"), file);
if (flags & EGPS__V_LIB)
fputs (_(" LIB"), file);
if (flags & EGPS__V_OVR)
fputs (_(" OVR"), file);
if (flags & EGPS__V_REL)
fputs (_(" REL"), file);
if (flags & EGPS__V_GBL)
fputs (_(" GBL"), file);
if (flags & EGPS__V_SHR)
fputs (_(" SHR"), file);
if (flags & EGPS__V_EXE)
fputs (_(" EXE"), file);
if (flags & EGPS__V_RD)
fputs (_(" RD"), file);
if (flags & EGPS__V_WRT)
fputs (_(" WRT"), file);
if (flags & EGPS__V_VEC)
fputs (_(" VEC"), file);
if (flags & EGPS__V_NOMOD)
fputs (_(" NOMOD"), file);
if (flags & EGPS__V_COM)
fputs (_(" COM"), file);
if (flags & EGPS__V_ALLOC_64BIT)
fputs (_(" 64B"), file);
}
static void
evax_bfd_print_egsd (FILE *file, unsigned char *rec, unsigned int rec_len)
{
unsigned int off = sizeof (struct vms_egsd);
unsigned int n;
fprintf (file, _(" EGSD (len=%u):\n"), rec_len);
n = 0;
for (off = sizeof (struct vms_egsd); off < rec_len; )
{
struct vms_egsd_entry *e = (struct vms_egsd_entry *)(rec + off);
unsigned int type;
unsigned int len;
type = (unsigned)bfd_getl16 (e->gsdtyp);
len = (unsigned)bfd_getl16 (e->gsdsiz);
fprintf (file, _(" EGSD entry %2u (type: %u, len: %u): "),
n, type, len);
n++;
switch (type)
{
case EGSD__C_PSC:
{
struct vms_egps *egps = (struct vms_egps *)e;
unsigned int flags = bfd_getl16 (egps->flags);
unsigned int l;
fprintf (file, _("PSC - Program section definition\n"));
fprintf (file, _(" alignment : 2**%u\n"), egps->align);
fprintf (file, _(" flags : 0x%04x"), flags);
evax_bfd_print_egsd_flags (file, flags);
fputc ('\n', file);
l = bfd_getl32 (egps->alloc);
fprintf (file, _(" alloc (len): %u (0x%08x)\n"), l, l);
fprintf (file, _(" name : %.*s\n"),
egps->namlng, egps->name);
}
break;
case EGSD__C_SPSC:
{
struct vms_esgps *esgps = (struct vms_esgps *)e;
unsigned int flags = bfd_getl16 (esgps->flags);
unsigned int l;
fprintf (file, _("SPSC - Shared Image Program section def\n"));
fprintf (file, _(" alignment : 2**%u\n"), esgps->align);
fprintf (file, _(" flags : 0x%04x"), flags);
evax_bfd_print_egsd_flags (file, flags);
fputc ('\n', file);
l = bfd_getl32 (esgps->alloc);
fprintf (file, _(" alloc (len) : %u (0x%08x)\n"), l, l);
fprintf (file, _(" image offset : 0x%08x\n"),
(unsigned int)bfd_getl32 (esgps->base));
fprintf (file, _(" symvec offset : 0x%08x\n"),
(unsigned int)bfd_getl32 (esgps->value));
fprintf (file, _(" name : %.*s\n"),
esgps->namlng, esgps->name);
}
break;
case EGSD__C_SYM:
{
struct vms_egsy *egsy = (struct vms_egsy *)e;
unsigned int flags = bfd_getl16 (egsy->flags);
if (flags & EGSY__V_DEF)
{
struct vms_esdf *esdf = (struct vms_esdf *)e;
fprintf (file, _("SYM - Global symbol definition\n"));
fprintf (file, _(" flags: 0x%04x"), flags);
exav_bfd_print_egsy_flags (flags, file);
fputc ('\n', file);
fprintf (file, _(" psect offset: 0x%08x\n"),
(unsigned)bfd_getl32 (esdf->value));
if (flags & EGSY__V_NORM)
{
fprintf (file, _(" code address: 0x%08x\n"),
(unsigned)bfd_getl32 (esdf->code_address));
fprintf (file, _(" psect index for entry point : %u\n"),
(unsigned)bfd_getl32 (esdf->ca_psindx));
}
fprintf (file, _(" psect index : %u\n"),
(unsigned)bfd_getl32 (esdf->psindx));
fprintf (file, _(" name : %.*s\n"),
esdf->namlng, esdf->name);
}
else
{
struct vms_esrf *esrf = (struct vms_esrf *)e;
fprintf (file, _("SYM - Global symbol reference\n"));
fprintf (file, _(" name : %.*s\n"),
esrf->namlng, esrf->name);
}
}
break;
case EGSD__C_IDC:
{
struct vms_eidc *eidc = (struct vms_eidc *)e;
unsigned int flags = bfd_getl32 (eidc->flags);
unsigned char *p;
fprintf (file, _("IDC - Ident Consistency check\n"));
fprintf (file, _(" flags : 0x%08x"), flags);
if (flags & EIDC__V_BINIDENT)
fputs (" BINDENT", file);
fputc ('\n', file);
fprintf (file, _(" id match : %x\n"),
(flags >> EIDC__V_IDMATCH_SH) & EIDC__V_IDMATCH_MASK);
fprintf (file, _(" error severity: %x\n"),
(flags >> EIDC__V_ERRSEV_SH) & EIDC__V_ERRSEV_MASK);
p = eidc->name;
fprintf (file, _(" entity name : %.*s\n"), p[0], p + 1);
p += 1 + p[0];
fprintf (file, _(" object name : %.*s\n"), p[0], p + 1);
p += 1 + p[0];
if (flags & EIDC__V_BINIDENT)
fprintf (file, _(" binary ident : 0x%08x\n"),
(unsigned)bfd_getl32 (p + 1));
else
fprintf (file, _(" ascii ident : %.*s\n"), p[0], p + 1);
}
break;
case EGSD__C_SYMG:
{
struct vms_egst *egst = (struct vms_egst *)e;
unsigned int flags = bfd_getl16 (egst->header.flags);
fprintf (file, _("SYMG - Universal symbol definition\n"));
fprintf (file, _(" flags: 0x%04x"), flags);
exav_bfd_print_egsy_flags (flags, file);
fputc ('\n', file);
fprintf (file, _(" symbol vector offset: 0x%08x\n"),
(unsigned)bfd_getl32 (egst->value));
fprintf (file, _(" entry point: 0x%08x\n"),
(unsigned)bfd_getl32 (egst->lp_1));
fprintf (file, _(" proc descr : 0x%08x\n"),
(unsigned)bfd_getl32 (egst->lp_2));
fprintf (file, _(" psect index: %u\n"),
(unsigned)bfd_getl32 (egst->psindx));
fprintf (file, _(" name : %.*s\n"),
egst->namlng, egst->name);
}
break;
case EGSD__C_SYMV:
{
struct vms_esdfv *esdfv = (struct vms_esdfv *)e;
unsigned int flags = bfd_getl16 (esdfv->flags);
fprintf (file, _("SYMV - Vectored symbol definition\n"));
fprintf (file, _(" flags: 0x%04x"), flags);
exav_bfd_print_egsy_flags (flags, file);
fputc ('\n', file);
fprintf (file, _(" vector : 0x%08x\n"),
(unsigned)bfd_getl32 (esdfv->vector));
fprintf (file, _(" psect offset: %u\n"),
(unsigned)bfd_getl32 (esdfv->value));
fprintf (file, _(" psect index : %u\n"),
(unsigned)bfd_getl32 (esdfv->psindx));
fprintf (file, _(" name : %.*s\n"),
esdfv->namlng, esdfv->name);
}
break;
case EGSD__C_SYMM:
{
struct vms_esdfm *esdfm = (struct vms_esdfm *)e;
unsigned int flags = bfd_getl16 (esdfm->flags);
fprintf (file, _("SYMM - Global symbol definition with version\n"));
fprintf (file, _(" flags: 0x%04x"), flags);
exav_bfd_print_egsy_flags (flags, file);
fputc ('\n', file);
fprintf (file, _(" version mask: 0x%08x\n"),
(unsigned)bfd_getl32 (esdfm->version_mask));
fprintf (file, _(" psect offset: %u\n"),
(unsigned)bfd_getl32 (esdfm->value));
fprintf (file, _(" psect index : %u\n"),
(unsigned)bfd_getl32 (esdfm->psindx));
fprintf (file, _(" name : %.*s\n"),
esdfm->namlng, esdfm->name);
}
break;
default:
fprintf (file, _("unhandled egsd entry type %u\n"), type);
break;
}
off += len;
}
}
static void
evax_bfd_print_hex (FILE *file, const char *pfx,
const unsigned char *buf, unsigned int len)
{
unsigned int i;
unsigned int n;
n = 0;
for (i = 0; i < len; i++)
{
if (n == 0)
fputs (pfx, file);
fprintf (file, " %02x", buf[i]);
n++;
if (n == 16)
{
n = 0;
fputc ('\n', file);
}
}
if (n != 0)
fputc ('\n', file);
}
static void
evax_bfd_print_etir_stc_ir (FILE *file, const unsigned char *buf, int is_ps)
{
fprintf (file, _(" linkage index: %u, replacement insn: 0x%08x\n"),
(unsigned)bfd_getl32 (buf),
(unsigned)bfd_getl32 (buf + 16));
fprintf (file, _(" psect idx 1: %u, offset 1: 0x%08x %08x\n"),
(unsigned)bfd_getl32 (buf + 4),
(unsigned)bfd_getl32 (buf + 12),
(unsigned)bfd_getl32 (buf + 8));
fprintf (file, _(" psect idx 2: %u, offset 2: 0x%08x %08x\n"),
(unsigned)bfd_getl32 (buf + 20),
(unsigned)bfd_getl32 (buf + 28),
(unsigned)bfd_getl32 (buf + 24));
if (is_ps)
fprintf (file, _(" psect idx 3: %u, offset 3: 0x%08x %08x\n"),
(unsigned)bfd_getl32 (buf + 32),
(unsigned)bfd_getl32 (buf + 40),
(unsigned)bfd_getl32 (buf + 36));
else
fprintf (file, _(" global name: %.*s\n"), buf[32], buf + 33);
}
static void
evax_bfd_print_etir (FILE *file, const char *name,
unsigned char *rec, unsigned int rec_len)
{
unsigned int off = sizeof (struct vms_egsd);
unsigned int sec_len = 0;
fprintf (file, _(" %s (len=%u+%u):\n"), name,
(unsigned)(rec_len - sizeof (struct vms_eobjrec)),
(unsigned)sizeof (struct vms_eobjrec));
for (off = sizeof (struct vms_eobjrec); off < rec_len; )
{
struct vms_etir *etir = (struct vms_etir *)(rec + off);
unsigned char *buf;
unsigned int type;
unsigned int size;
type = bfd_getl16 (etir->rectyp);
size = bfd_getl16 (etir->size);
buf = rec + off + sizeof (struct vms_etir);
fprintf (file, _(" (type: %3u, size: 4+%3u): "), type, size - 4);
switch (type)
{
case ETIR__C_STA_GBL:
fprintf (file, _("STA_GBL (stack global) %.*s\n"),
buf[0], buf + 1);
break;
case ETIR__C_STA_LW:
fprintf (file, _("STA_LW (stack longword) 0x%08x\n"),
(unsigned)bfd_getl32 (buf));
break;
case ETIR__C_STA_QW:
fprintf (file, _("STA_QW (stack quadword) 0x%08x %08x\n"),
(unsigned)bfd_getl32 (buf + 4),
(unsigned)bfd_getl32 (buf + 0));
break;
case ETIR__C_STA_PQ:
fprintf (file, _("STA_PQ (stack psect base + offset)\n"));
fprintf (file, _(" psect: %u, offset: 0x%08x %08x\n"),
(unsigned)bfd_getl32 (buf + 0),
(unsigned)bfd_getl32 (buf + 8),
(unsigned)bfd_getl32 (buf + 4));
break;
case ETIR__C_STA_LI:
fprintf (file, _("STA_LI (stack literal)\n"));
break;
case ETIR__C_STA_MOD:
fprintf (file, _("STA_MOD (stack module)\n"));
break;
case ETIR__C_STA_CKARG:
fprintf (file, _("STA_CKARG (compare procedure argument)\n"));
break;
case ETIR__C_STO_B:
fprintf (file, _("STO_B (store byte)\n"));
break;
case ETIR__C_STO_W:
fprintf (file, _("STO_W (store word)\n"));
break;
case ETIR__C_STO_LW:
fprintf (file, _("STO_LW (store longword)\n"));
break;
case ETIR__C_STO_QW:
fprintf (file, _("STO_QW (store quadword)\n"));
break;
case ETIR__C_STO_IMMR:
{
unsigned int len = bfd_getl32 (buf);
fprintf (file,
_("STO_IMMR (store immediate repeat) %u bytes\n"),
len);
evax_bfd_print_hex (file, " ", buf + 4, len);
sec_len += len;
}
break;
case ETIR__C_STO_GBL:
fprintf (file, _("STO_GBL (store global) %.*s\n"),
buf[0], buf + 1);
break;
case ETIR__C_STO_CA:
fprintf (file, _("STO_CA (store code address) %.*s\n"),
buf[0], buf + 1);
break;
case ETIR__C_STO_RB:
fprintf (file, _("STO_RB (store relative branch)\n"));
break;
case ETIR__C_STO_AB:
fprintf (file, _("STO_AB (store absolute branch)\n"));
break;
case ETIR__C_STO_OFF:
fprintf (file, _("STO_OFF (store offset to psect)\n"));
break;
case ETIR__C_STO_IMM:
{
unsigned int len = bfd_getl32 (buf);
fprintf (file,
_("STO_IMM (store immediate) %u bytes\n"),
len);
evax_bfd_print_hex (file, " ", buf + 4, len);
sec_len += len;
}
break;
case ETIR__C_STO_GBL_LW:
fprintf (file, _("STO_GBL_LW (store global longword) %.*s\n"),
buf[0], buf + 1);
break;
case ETIR__C_STO_LP_PSB:
fprintf (file, _("STO_OFF (store LP with procedure signature)\n"));
break;
case ETIR__C_STO_HINT_GBL:
fprintf (file, _("STO_BR_GBL (store branch global) *todo*\n"));
break;
case ETIR__C_STO_HINT_PS:
fprintf (file, _("STO_BR_PS (store branch psect + offset) *todo*\n"));
break;
case ETIR__C_OPR_NOP:
fprintf (file, _("OPR_NOP (no-operation)\n"));
break;
case ETIR__C_OPR_ADD:
fprintf (file, _("OPR_ADD (add)\n"));
break;
case ETIR__C_OPR_SUB:
fprintf (file, _("OPR_SUB (substract)\n"));
break;
case ETIR__C_OPR_MUL:
fprintf (file, _("OPR_MUL (multiply)\n"));
break;
case ETIR__C_OPR_DIV:
fprintf (file, _("OPR_DIV (divide)\n"));
break;
case ETIR__C_OPR_AND:
fprintf (file, _("OPR_AND (logical and)\n"));
break;
case ETIR__C_OPR_IOR:
fprintf (file, _("OPR_IOR (logical inclusive or)\n"));
break;
case ETIR__C_OPR_EOR:
fprintf (file, _("OPR_EOR (logical exclusive or)\n"));
break;
case ETIR__C_OPR_NEG:
fprintf (file, _("OPR_NEG (negate)\n"));
break;
case ETIR__C_OPR_COM:
fprintf (file, _("OPR_COM (complement)\n"));
break;
case ETIR__C_OPR_INSV:
fprintf (file, _("OPR_INSV (insert field)\n"));
break;
case ETIR__C_OPR_ASH:
fprintf (file, _("OPR_ASH (arithmetic shift)\n"));
break;
case ETIR__C_OPR_USH:
fprintf (file, _("OPR_USH (unsigned shift)\n"));
break;
case ETIR__C_OPR_ROT:
fprintf (file, _("OPR_ROT (rotate)\n"));
break;
case ETIR__C_OPR_SEL:
fprintf (file, _("OPR_SEL (select)\n"));
break;
case ETIR__C_OPR_REDEF:
fprintf (file, _("OPR_REDEF (redefine symbol to curr location)\n"));
break;
case ETIR__C_OPR_DFLIT:
fprintf (file, _("OPR_REDEF (define a literal)\n"));
break;
case ETIR__C_STC_LP:
fprintf (file, _("STC_LP (store cond linkage pair)\n"));
break;
case ETIR__C_STC_LP_PSB:
fprintf (file,
_("STC_LP_PSB (store cond linkage pair + signature)\n"));
fprintf (file, _(" linkage index: %u, procedure: %.*s\n"),
(unsigned)bfd_getl32 (buf), buf[4], buf + 5);
buf += 4 + 1 + buf[4];
fprintf (file, _(" signature: %.*s\n"), buf[0], buf + 1);
break;
case ETIR__C_STC_GBL:
fprintf (file, _("STC_GBL (store cond global)\n"));
fprintf (file, _(" linkage index: %u, global: %.*s\n"),
(unsigned)bfd_getl32 (buf), buf[4], buf + 5);
break;
case ETIR__C_STC_GCA:
fprintf (file, _("STC_GCA (store cond code address)\n"));
fprintf (file, _(" linkage index: %u, procedure name: %.*s\n"),
(unsigned)bfd_getl32 (buf), buf[4], buf + 5);
break;
case ETIR__C_STC_PS:
fprintf (file, _("STC_PS (store cond psect + offset)\n"));
fprintf (file,
_(" linkage index: %u, psect: %u, offset: 0x%08x %08x\n"),
(unsigned)bfd_getl32 (buf),
(unsigned)bfd_getl32 (buf + 4),
(unsigned)bfd_getl32 (buf + 12),
(unsigned)bfd_getl32 (buf + 8));
break;
case ETIR__C_STC_NOP_GBL:
fprintf (file, _("STC_NOP_GBL (store cond NOP at global addr)\n"));
evax_bfd_print_etir_stc_ir (file, buf, 0);
break;
case ETIR__C_STC_NOP_PS:
fprintf (file, _("STC_NOP_PS (store cond NOP at psect + offset)\n"));
evax_bfd_print_etir_stc_ir (file, buf, 1);
break;
case ETIR__C_STC_BSR_GBL:
fprintf (file, _("STC_BSR_GBL (store cond BSR at global addr)\n"));
evax_bfd_print_etir_stc_ir (file, buf, 0);
break;
case ETIR__C_STC_BSR_PS:
fprintf (file, _("STC_BSR_PS (store cond BSR at psect + offset)\n"));
evax_bfd_print_etir_stc_ir (file, buf, 1);
break;
case ETIR__C_STC_LDA_GBL:
fprintf (file, _("STC_LDA_GBL (store cond LDA at global addr)\n"));
evax_bfd_print_etir_stc_ir (file, buf, 0);
break;
case ETIR__C_STC_LDA_PS:
fprintf (file, _("STC_LDA_PS (store cond LDA at psect + offset)\n"));
evax_bfd_print_etir_stc_ir (file, buf, 1);
break;
case ETIR__C_STC_BOH_GBL:
fprintf (file, _("STC_BOH_GBL (store cond BOH at global addr)\n"));
evax_bfd_print_etir_stc_ir (file, buf, 0);
break;
case ETIR__C_STC_BOH_PS:
fprintf (file, _("STC_BOH_PS (store cond BOH at psect + offset)\n"));
evax_bfd_print_etir_stc_ir (file, buf, 1);
break;
case ETIR__C_STC_NBH_GBL:
fprintf (file,
_("STC_NBH_GBL (store cond or hint at global addr)\n"));
break;
case ETIR__C_STC_NBH_PS:
fprintf (file,
_("STC_NBH_PS (store cond or hint at psect + offset)\n"));
break;
case ETIR__C_CTL_SETRB:
fprintf (file, _("CTL_SETRB (set relocation base)\n"));
sec_len += 4;
break;
case ETIR__C_CTL_AUGRB:
{
unsigned int val = bfd_getl32 (buf);
fprintf (file, _("CTL_AUGRB (augment relocation base) %u\n"), val);
}
break;
case ETIR__C_CTL_DFLOC:
fprintf (file, _("CTL_DFLOC (define location)\n"));
break;
case ETIR__C_CTL_STLOC:
fprintf (file, _("CTL_STLOC (set location)\n"));
break;
case ETIR__C_CTL_STKDL:
fprintf (file, _("CTL_STKDL (stack defined location)\n"));
break;
default:
fprintf (file, _("*unhandled*\n"));
break;
}
off += size;
}
}
static void
evax_bfd_print_eobj (struct bfd *abfd, FILE *file)
{
bfd_boolean is_first = TRUE;
bfd_boolean has_records = FALSE;
while (1)
{
unsigned int rec_len;
unsigned int pad_len;
unsigned char *rec;
unsigned int hdr_size;
unsigned int type;
if (is_first)
{
unsigned char buf[6];
is_first = FALSE;
/* Read 6 bytes. */
if (bfd_bread (buf, sizeof (buf), abfd) != sizeof (buf))
{
fprintf (file, _("cannot read GST record length\n"));
return;
}
rec_len = bfd_getl16 (buf + 0);
if (rec_len == bfd_getl16 (buf + 4)
&& bfd_getl16 (buf + 2) == EOBJ__C_EMH)
{
/* The format is raw: record-size, type, record-size. */
has_records = TRUE;
pad_len = (rec_len + 1) & ~1U;
hdr_size = 4;
}
else if (rec_len == EOBJ__C_EMH)
{
has_records = FALSE;
pad_len = bfd_getl16 (buf + 2);
hdr_size = 6;
}
else
{
/* Ill-formed. */
fprintf (file, _("cannot find EMH in first GST record\n"));
return;
}
rec = bfd_malloc (pad_len);
memcpy (rec, buf + sizeof (buf) - hdr_size, hdr_size);
}
else
{
unsigned int rec_len2 = 0;
unsigned char hdr[4];
if (has_records)
{
unsigned char buf_len[2];
if (bfd_bread (buf_len, sizeof (buf_len), abfd)
!= sizeof (buf_len))
{
fprintf (file, _("cannot read GST record length\n"));
return;
}
rec_len2 = (unsigned)bfd_getl16 (buf_len);
}
if (bfd_bread (hdr, sizeof (hdr), abfd) != sizeof (hdr))
{
fprintf (file, _("cannot read GST record header\n"));
return;
}
rec_len = (unsigned)bfd_getl16 (hdr + 2);
if (has_records)
pad_len = (rec_len + 1) & ~1U;
else
pad_len = rec_len;
rec = bfd_malloc (pad_len);
memcpy (rec, hdr, sizeof (hdr));
hdr_size = sizeof (hdr);
if (has_records && rec_len2 != rec_len)
{
fprintf (file, _(" corrupted GST\n"));
break;
}
}
if (bfd_bread (rec + hdr_size, pad_len - hdr_size, abfd)
!= pad_len - hdr_size)
{
fprintf (file, _("cannot read GST record\n"));
return;
}
type = (unsigned)bfd_getl16 (rec);
switch (type)
{
case EOBJ__C_EMH:
evax_bfd_print_emh (file, rec, rec_len);
break;
case EOBJ__C_EGSD:
evax_bfd_print_egsd (file, rec, rec_len);
break;
case EOBJ__C_EEOM:
evax_bfd_print_eeom (file, rec, rec_len);
free (rec);
return;
break;
case EOBJ__C_ETIR:
evax_bfd_print_etir (file, "ETIR", rec, rec_len);
break;
case EOBJ__C_EDBG:
evax_bfd_print_etir (file, "EDBG", rec, rec_len);
break;
case EOBJ__C_ETBT:
evax_bfd_print_etir (file, "ETBT", rec, rec_len);
break;
default:
fprintf (file, _(" unhandled EOBJ record type %u\n"), type);
break;
}
free (rec);
}
}
static void
evax_bfd_print_relocation_records (FILE *file, const unsigned char *rel,
unsigned int stride)
{
while (1)
{
unsigned int base;
unsigned int count;
unsigned int j;
count = bfd_getl32 (rel + 0);
if (count == 0)
break;
base = bfd_getl32 (rel + 4);
fprintf (file, _(" bitcount: %u, base addr: 0x%08x\n"),
count, base);
rel += 8;
for (j = 0; count > 0; j += 4, count -= 32)
{
unsigned int k;
unsigned int n = 0;
unsigned int val;
val = bfd_getl32 (rel);
rel += 4;
fprintf (file, _(" bitmap: 0x%08x (count: %u):\n"), val, count);
for (k = 0; k < 32; k++)
if (val & (1 << k))
{
if (n == 0)
fputs (" ", file);
fprintf (file, _(" %08x"), base + (j * 8 + k) * stride);
n++;
if (n == 8)
{
fputs ("\n", file);
n = 0;
}
}
if (n)
fputs ("\n", file);
}
}
}
static void
evax_bfd_print_address_fixups (FILE *file, const unsigned char *rel)
{
while (1)
{
unsigned int j;
unsigned int count;
count = bfd_getl32 (rel + 0);
if (count == 0)
return;
fprintf (file, _(" image %u (%u entries)\n"),
(unsigned)bfd_getl32 (rel + 4), count);
rel += 8;
for (j = 0; j < count; j++)
{
fprintf (file, _(" offset: 0x%08x, val: 0x%08x\n"),
(unsigned)bfd_getl32 (rel + 0),
(unsigned)bfd_getl32 (rel + 4));
rel += 8;
}
}
}
static void
evax_bfd_print_reference_fixups (FILE *file, const unsigned char *rel)
{
unsigned int count;
while (1)
{
unsigned int j;
unsigned int n = 0;
count = bfd_getl32 (rel + 0);
if (count == 0)
break;
fprintf (file, _(" image %u (%u entries), offsets:\n"),
(unsigned)bfd_getl32 (rel + 4), count);
rel += 8;
for (j = 0; j < count; j++)
{
if (n == 0)
fputs (" ", file);
fprintf (file, _(" 0x%08x"), (unsigned)bfd_getl32 (rel));
n++;
if (n == 7)
{
fputs ("\n", file);
n = 0;
}
rel += 4;
}
if (n)
fputs ("\n", file);
}
}
static void
evax_bfd_print_indent (int indent, FILE *file)
{
for (; indent; indent--)
fputc (' ', file);
}
static const char *
evax_bfd_get_dsc_name (unsigned int v)
{
switch (v)
{
case DSC__K_DTYPE_Z:
return "Z (Unspecified)";
case DSC__K_DTYPE_V:
return "V (Bit)";
case DSC__K_DTYPE_BU:
return "BU (Byte logical)";
case DSC__K_DTYPE_WU:
return "WU (Word logical)";
case DSC__K_DTYPE_LU:
return "LU (Longword logical)";
case DSC__K_DTYPE_QU:
return "QU (Quadword logical)";
case DSC__K_DTYPE_B:
return "B (Byte integer)";
case DSC__K_DTYPE_W:
return "W (Word integer)";
case DSC__K_DTYPE_L:
return "L (Longword integer)";
case DSC__K_DTYPE_Q:
return "Q (Quadword integer)";
case DSC__K_DTYPE_F:
return "F (Single-precision floating)";
case DSC__K_DTYPE_D:
return "D (Double-precision floating)";
case DSC__K_DTYPE_FC:
return "FC (Complex)";
case DSC__K_DTYPE_DC:
return "DC (Double-precision Complex)";
case DSC__K_DTYPE_T:
return "T (ASCII text string)";
case DSC__K_DTYPE_NU:
return "NU (Numeric string, unsigned)";
case DSC__K_DTYPE_NL:
return "NL (Numeric string, left separate sign)";
case DSC__K_DTYPE_NLO:
return "NLO (Numeric string, left overpunched sign)";
case DSC__K_DTYPE_NR:
return "NR (Numeric string, right separate sign)";
case DSC__K_DTYPE_NRO:
return "NRO (Numeric string, right overpunched sig)";
case DSC__K_DTYPE_NZ:
return "NZ (Numeric string, zoned sign)";
case DSC__K_DTYPE_P:
return "P (Packed decimal string)";
case DSC__K_DTYPE_ZI:
return "ZI (Sequence of instructions)";
case DSC__K_DTYPE_ZEM:
return "ZEM (Procedure entry mask)";
case DSC__K_DTYPE_DSC:
return "DSC (Descriptor, used for arrays of dyn strings)";
case DSC__K_DTYPE_OU:
return "OU (Octaword logical)";
case DSC__K_DTYPE_O:
return "O (Octaword integer)";
case DSC__K_DTYPE_G:
return "G (Double precision G floating, 64 bit)";
case DSC__K_DTYPE_H:
return "H (Quadruple precision floating, 128 bit)";
case DSC__K_DTYPE_GC:
return "GC (Double precision complex, G floating)";
case DSC__K_DTYPE_HC:
return "HC (Quadruple precision complex, H floating)";
case DSC__K_DTYPE_CIT:
return "CIT (COBOL intermediate temporary)";
case DSC__K_DTYPE_BPV:
return "BPV (Bound Procedure Value)";
case DSC__K_DTYPE_BLV:
return "BLV (Bound Label Value)";
case DSC__K_DTYPE_VU:
return "VU (Bit Unaligned)";
case DSC__K_DTYPE_ADT:
return "ADT (Absolute Date-Time)";
case DSC__K_DTYPE_VT:
return "VT (Varying Text)";
case DSC__K_DTYPE_T2:
return "T2 (16-bit char)";
case DSC__K_DTYPE_VT2:
return "VT2 (16-bit varying char)";
default:
return "?? (unknown)";
}
}
static void
evax_bfd_print_desc (const unsigned char *buf, int indent, FILE *file)
{
unsigned char bclass = buf[3];
unsigned char dtype = buf[2];
unsigned int len = (unsigned)bfd_getl16 (buf);
unsigned int pointer = (unsigned)bfd_getl32 (buf + 4);
evax_bfd_print_indent (indent, file);
if (len == 1 && pointer == 0xffffffffUL)
{
/* 64 bits. */
fprintf (file, _("64 bits *unhandled*\n"));
}
else
{
fprintf (file, _("class: %u, dtype: %u, length: %u, pointer: 0x%08x\n"),
bclass, dtype, len, pointer);
switch (bclass)
{
case DSC__K_CLASS_NCA:
{
const struct vms_dsc_nca *dsc = (const void *)buf;
unsigned int i;
const unsigned char *b;
evax_bfd_print_indent (indent, file);
fprintf (file, _("non-contiguous array of %s\n"),
evax_bfd_get_dsc_name (dsc->dtype));
evax_bfd_print_indent (indent + 1, file);
fprintf (file,
_("dimct: %u, aflags: 0x%02x, digits: %u, scale: %u\n"),
dsc->dimct, dsc->aflags, dsc->digits, dsc->scale);
evax_bfd_print_indent (indent + 1, file);
fprintf (file,
_("arsize: %u, a0: 0x%08x\n"),
(unsigned)bfd_getl32 (dsc->arsize),
(unsigned)bfd_getl32 (dsc->a0));
evax_bfd_print_indent (indent + 1, file);
fprintf (file, _("Strides:\n"));
b = buf + sizeof (*dsc);
for (i = 0; i < dsc->dimct; i++)
{
evax_bfd_print_indent (indent + 2, file);
fprintf (file, _("[%u]: %u\n"), i + 1,
(unsigned)bfd_getl32 (b));
b += 4;
}
evax_bfd_print_indent (indent + 1, file);
fprintf (file, _("Bounds:\n"));
b = buf + sizeof (*dsc);
for (i = 0; i < dsc->dimct; i++)
{
evax_bfd_print_indent (indent + 2, file);
fprintf (file, _("[%u]: Lower: %u, upper: %u\n"), i + 1,
(unsigned)bfd_getl32 (b + 0),
(unsigned)bfd_getl32 (b + 4));
b += 8;
}
}
break;
case DSC__K_CLASS_UBS:
{
const struct vms_dsc_ubs *ubs = (const void *)buf;
evax_bfd_print_indent (indent, file);
fprintf (file, _("unaligned bit-string of %s\n"),
evax_bfd_get_dsc_name (ubs->dtype));
evax_bfd_print_indent (indent + 1, file);
fprintf (file,
_("base: %u, pos: %u\n"),
(unsigned)bfd_getl32 (ubs->base),
(unsigned)bfd_getl32 (ubs->pos));
}
break;
default:
fprintf (file, _("*unhandled*\n"));
break;
}
}
}
static unsigned int
evax_bfd_print_valspec (const unsigned char *buf, int indent, FILE *file)
{
unsigned int vflags = buf[0];
unsigned int value = (unsigned)bfd_getl32 (buf + 1);
unsigned int len = 5;
evax_bfd_print_indent (indent, file);
fprintf (file, _("vflags: 0x%02x, value: 0x%08x "), vflags, value);
buf += 5;
switch (vflags)
{
case DST__K_VFLAGS_NOVAL:
fprintf (file, _("(no value)\n"));
break;
case DST__K_VFLAGS_NOTACTIVE:
fprintf (file, _("(not active)\n"));
break;
case DST__K_VFLAGS_UNALLOC:
fprintf (file, _("(not allocated)\n"));
break;
case DST__K_VFLAGS_DSC:
fprintf (file, _("(descriptor)\n"));
evax_bfd_print_desc (buf + value, indent + 1, file);
break;
case DST__K_VFLAGS_TVS:
fprintf (file, _("(trailing value)\n"));
break;
case DST__K_VS_FOLLOWS:
fprintf (file, _("(value spec follows)\n"));
break;
case DST__K_VFLAGS_BITOFFS:
fprintf (file, _("(at bit offset %u)\n"), value);
break;
default:
fprintf (file, _("(reg: %u, disp: %u, indir: %u, kind: "),
(vflags & DST__K_REGNUM_MASK) >> DST__K_REGNUM_SHIFT,
vflags & DST__K_DISP ? 1 : 0,
vflags & DST__K_INDIR ? 1 : 0);
switch (vflags & DST__K_VALKIND_MASK)
{
case DST__K_VALKIND_LITERAL:
fputs (_("literal"), file);
break;
case DST__K_VALKIND_ADDR:
fputs (_("address"), file);
break;
case DST__K_VALKIND_DESC:
fputs (_("desc"), file);
break;
case DST__K_VALKIND_REG:
fputs (_("reg"), file);
break;
}
fputs (")\n", file);
break;
}
return len;
}
static void
evax_bfd_print_typspec (const unsigned char *buf, int indent, FILE *file)
{
unsigned char kind = buf[2];
unsigned int len = (unsigned)bfd_getl16 (buf);
evax_bfd_print_indent (indent, file);
fprintf (file, ("len: %2u, kind: %2u "), len, kind);
buf += 3;
switch (kind)
{
case DST__K_TS_ATOM:
fprintf (file, ("atomic, type=0x%02x %s\n"),
buf[0], evax_bfd_get_dsc_name (buf[0]));
break;
case DST__K_TS_IND:
fprintf (file, ("indirect, defined at 0x%08x\n"),
(unsigned)bfd_getl32 (buf));
break;
case DST__K_TS_TPTR:
fprintf (file, ("typed pointer\n"));
evax_bfd_print_typspec (buf, indent + 1, file);
break;
case DST__K_TS_PTR:
fprintf (file, ("pointer\n"));
break;
case DST__K_TS_ARRAY:
{
const unsigned char *vs;
unsigned int vec_len;
unsigned int i;
fprintf (file, ("array, dim: %u, bitmap: "), buf[0]);
vec_len = (buf[0] + 1 + 7) / 8;
for (i = 0; i < vec_len; i++)
fprintf (file, " %02x", buf[i + 1]);
fputc ('\n', file);
vs = buf + 1 + vec_len;
evax_bfd_print_indent (indent, file);
fprintf (file, ("array descriptor:\n"));
vs += evax_bfd_print_valspec (vs, indent + 1, file);
for (i = 0; i < buf[0] + 1U; i++)
if (buf[1 + i / 8] & (1 << (i % 8)))
{
evax_bfd_print_indent (indent, file);
if (i == 0)
fprintf (file, ("type spec for element:\n"));
else
fprintf (file, ("type spec for subscript %u:\n"), i);
evax_bfd_print_typspec (vs, indent + 1, file);
vs += bfd_getl16 (vs);
}
}
break;
default:
fprintf (file, ("*unhandled*\n"));
}
}
static void
evax_bfd_print_dst (struct bfd *abfd, unsigned int dst_size, FILE *file)
{
unsigned int off = 0;
unsigned int pc = 0;
unsigned int line = 0;
fprintf (file, _("Debug symbol table:\n"));
while (dst_size > 0)
{
struct vms_dst_header dsth;
unsigned int len;
unsigned int type;
unsigned char *buf;
if (bfd_bread (&dsth, sizeof (dsth), abfd) != sizeof (dsth))
{
fprintf (file, _("cannot read DST header\n"));
return;
}
len = bfd_getl16 (dsth.length);
type = bfd_getl16 (dsth.type);
fprintf (file, _(" type: %3u, len: %3u (at 0x%08x): "),
type, len, off);
if (len == 0)
{
fputc ('\n', file);
break;
}
len++;
dst_size -= len;
off += len;
len -= sizeof (dsth);
buf = bfd_malloc (len);
if (bfd_bread (buf, len, abfd) != len)
{
fprintf (file, _("cannot read DST symbol\n"));
return;
}
switch (type)
{
case DSC__K_DTYPE_V:
case DSC__K_DTYPE_BU:
case DSC__K_DTYPE_WU:
case DSC__K_DTYPE_LU:
case DSC__K_DTYPE_QU:
case DSC__K_DTYPE_B:
case DSC__K_DTYPE_W:
case DSC__K_DTYPE_L:
case DSC__K_DTYPE_Q:
case DSC__K_DTYPE_F:
case DSC__K_DTYPE_D:
case DSC__K_DTYPE_FC:
case DSC__K_DTYPE_DC:
case DSC__K_DTYPE_T:
case DSC__K_DTYPE_NU:
case DSC__K_DTYPE_NL:
case DSC__K_DTYPE_NLO:
case DSC__K_DTYPE_NR:
case DSC__K_DTYPE_NRO:
case DSC__K_DTYPE_NZ:
case DSC__K_DTYPE_P:
case DSC__K_DTYPE_ZI:
case DSC__K_DTYPE_ZEM:
case DSC__K_DTYPE_DSC:
case DSC__K_DTYPE_OU:
case DSC__K_DTYPE_O:
case DSC__K_DTYPE_G:
case DSC__K_DTYPE_H:
case DSC__K_DTYPE_GC:
case DSC__K_DTYPE_HC:
case DSC__K_DTYPE_CIT:
case DSC__K_DTYPE_BPV:
case DSC__K_DTYPE_BLV:
case DSC__K_DTYPE_VU:
case DSC__K_DTYPE_ADT:
case DSC__K_DTYPE_VT:
case DSC__K_DTYPE_T2:
case DSC__K_DTYPE_VT2:
fprintf (file, _("standard data: %s\n"),
evax_bfd_get_dsc_name (type));
evax_bfd_print_valspec (buf, 4, file);
fprintf (file, _(" name: %.*s\n"), buf[5], buf + 6);
break;
case DST__K_MODBEG:
{
struct vms_dst_modbeg *dst = (void *)buf;
const char *name = (const char *)buf + sizeof (*dst);
fprintf (file, _("modbeg\n"));
fprintf (file, _(" flags: %d, language: %u, "
"major: %u, minor: %u\n"),
dst->flags,
(unsigned)bfd_getl32 (dst->language),
(unsigned)bfd_getl16 (dst->major),
(unsigned)bfd_getl16 (dst->minor));
fprintf (file, _(" module name: %.*s\n"),
name[0], name + 1);
name += name[0] + 1;
fprintf (file, _(" compiler : %.*s\n"),
name[0], name + 1);
}
break;
case DST__K_MODEND:
fprintf (file, _("modend\n"));
break;
case DST__K_RTNBEG:
{
struct vms_dst_rtnbeg *dst = (void *)buf;
const char *name = (const char *)buf + sizeof (*dst);
fputs (_("rtnbeg\n"), file);
fprintf (file, _(" flags: %u, address: 0x%08x, "
"pd-address: 0x%08x\n"),
dst->flags,
(unsigned)bfd_getl32 (dst->address),
(unsigned)bfd_getl32 (dst->pd_address));
fprintf (file, _(" routine name: %.*s\n"),
name[0], name + 1);
}
break;
case DST__K_RTNEND:
{
struct vms_dst_rtnend *dst = (void *)buf;
fprintf (file, _("rtnend: size 0x%08x\n"),
(unsigned)bfd_getl32 (dst->size));
}
break;
case DST__K_PROLOG:
{
struct vms_dst_prolog *dst = (void *)buf;
fprintf (file, _("prolog: bkpt address 0x%08x\n"),
(unsigned)bfd_getl32 (dst->bkpt_addr));
}
break;
case DST__K_EPILOG:
{
struct vms_dst_epilog *dst = (void *)buf;
fprintf (file, _("epilog: flags: %u, count: %u\n"),
dst->flags, (unsigned)bfd_getl32 (dst->count));
}
break;
case DST__K_BLKBEG:
{
struct vms_dst_blkbeg *dst = (void *)buf;
const char *name = (const char *)buf + sizeof (*dst);
fprintf (file, _("blkbeg: address: 0x%08x, name: %.*s\n"),
(unsigned)bfd_getl32 (dst->address),
name[0], name + 1);
}
break;
case DST__K_BLKEND:
{
struct vms_dst_blkend *dst = (void *)buf;
fprintf (file, _("blkend: size: 0x%08x\n"),
(unsigned)bfd_getl32 (dst->size));
}
break;
case DST__K_TYPSPEC:
{
fprintf (file, _("typspec (len: %u)\n"), len);
fprintf (file, _(" name: %.*s\n"), buf[0], buf + 1);
evax_bfd_print_typspec (buf + 1 + buf[0], 5, file);
}
break;
case DST__K_SEPTYP:
{
fprintf (file, _("septyp, name: %.*s\n"), buf[5], buf + 6);
evax_bfd_print_valspec (buf, 4, file);
}
break;
case DST__K_RECBEG:
{
struct vms_dst_recbeg *recbeg = (void *)buf;
const char *name = (const char *)buf + sizeof (*recbeg);
fprintf (file, _("recbeg: name: %.*s\n"), name[0], name + 1);
evax_bfd_print_valspec (buf, 4, file);
fprintf (file, (" len: %u bits\n"),
(unsigned)bfd_getl32 (name + 1 + name[0]));
}
break;
case DST__K_RECEND:
fprintf (file, _("recend\n"));
break;
case DST__K_ENUMBEG:
fprintf (file, _("enumbeg, len: %u, name: %.*s\n"),
buf[0], buf[1], buf + 2);
break;
case DST__K_ENUMELT:
fprintf (file, _("enumelt, name: %.*s\n"), buf[5], buf + 6);
evax_bfd_print_valspec (buf, 4, file);
break;
case DST__K_ENUMEND:
fprintf (file, _("enumend\n"));
break;
case DST__K_LABEL:
{
struct vms_dst_label *lab = (void *)buf;
fprintf (file, ("label, name: %.*s\n"),
lab->name[0], lab->name + 1);
fprintf (file, (" address: 0x%08x\n"),
(unsigned)bfd_getl32 (lab->value));
}
break;
case DST__K_DIS_RANGE:
{
unsigned int cnt = bfd_getl32 (buf);
unsigned char *rng = buf + 4;
unsigned int i;
fprintf (file, _("discontiguous range (nbr: %u)\n"), cnt);
for (i = 0; i < cnt; i++, rng += 8)
fprintf (file, _(" address: 0x%08x, size: %u\n"),
(unsigned)bfd_getl32 (rng),
(unsigned)bfd_getl32 (rng + 4));
}
break;
case DST__K_LINE_NUM:
{
unsigned char *buf_orig = buf;
fprintf (file, _("line num (len: %u)\n"), len);
while (len > 0)
{
signed char cmd;
unsigned char cmdlen;
unsigned int val;
cmd = buf[0];
cmdlen = 0;
fputs (" ", file);
switch (cmd)
{
case DST__K_DELTA_PC_W:
val = bfd_getl16 (buf + 1);
fprintf (file, _("delta_pc_w %u\n"), val);
pc += val;
line++;
cmdlen = 3;
break;
case DST__K_INCR_LINUM:
val = buf[1];
fprintf (file, _("incr_linum(b): +%u\n"), val);
line += val;
cmdlen = 2;
break;
case DST__K_INCR_LINUM_W:
val = bfd_getl16 (buf + 1);
fprintf (file, _("incr_linum_w: +%u\n"), val);
line += val;
cmdlen = 3;
break;
case DST__K_INCR_LINUM_L:
val = bfd_getl32 (buf + 1);
fprintf (file, _("incr_linum_l: +%u\n"), val);
line += val;
cmdlen = 5;
break;
case DST__K_SET_LINUM:
line = bfd_getl16 (buf + 1);
fprintf (file, _("set_line_num(w) %u\n"), line);
cmdlen = 3;
break;
case DST__K_SET_LINUM_B:
line = buf[1];
fprintf (file, _("set_line_num_b %u\n"), line);
cmdlen = 2;
break;
case DST__K_SET_LINUM_L:
line = bfd_getl32 (buf + 1);
fprintf (file, _("set_line_num_l %u\n"), line);
cmdlen = 5;
break;
case DST__K_SET_ABS_PC:
pc = bfd_getl32 (buf + 1);
fprintf (file, _("set_abs_pc: 0x%08x\n"), pc);
cmdlen = 5;
break;
case DST__K_DELTA_PC_L:
fprintf (file, _("delta_pc_l: +0x%08x\n"),
(unsigned)bfd_getl32 (buf + 1));
cmdlen = 5;
break;
case DST__K_TERM:
fprintf (file, _("term(b): 0x%02x"), buf[1]);
pc += buf[1];
fprintf (file, _(" pc: 0x%08x\n"), pc);
cmdlen = 2;
break;
case DST__K_TERM_W:
val = bfd_getl16 (buf + 1);
fprintf (file, _("term_w: 0x%04x"), val);
pc += val;
fprintf (file, _(" pc: 0x%08x\n"), pc);
cmdlen = 3;
break;
default:
if (cmd <= 0)
{
fprintf (file, _("delta pc +%-4d"), -cmd);
line++; /* FIXME: curr increment. */
pc += -cmd;
fprintf (file, _(" pc: 0x%08x line: %5u\n"),
pc, line);
cmdlen = 1;
}
else
fprintf (file, _(" *unhandled* cmd %u\n"), cmd);
break;
}
if (cmdlen == 0)
break;
len -= cmdlen;
buf += cmdlen;
}
buf = buf_orig;
}
break;
case DST__K_SOURCE:
{
unsigned char *buf_orig = buf;
fprintf (file, _("source (len: %u)\n"), len);
while (len > 0)
{
signed char cmd = buf[0];
unsigned char cmdlen = 0;
switch (cmd)
{
case DST__K_SRC_DECLFILE:
{
struct vms_dst_src_decl_src *src = (void *)(buf + 1);
const char *name;
fprintf (file, _(" declfile: len: %u, flags: %u, "
"fileid: %u\n"),
src->length, src->flags,
(unsigned)bfd_getl16 (src->fileid));
fprintf (file, _(" rms: cdt: 0x%08x %08x, "
"ebk: 0x%08x, ffb: 0x%04x, "
"rfo: %u\n"),
(unsigned)bfd_getl32 (src->rms_cdt + 4),
(unsigned)bfd_getl32 (src->rms_cdt + 0),
(unsigned)bfd_getl32 (src->rms_ebk),
(unsigned)bfd_getl16 (src->rms_ffb),
src->rms_rfo);
name = (const char *)buf + 1 + sizeof (*src);
fprintf (file, _(" filename : %.*s\n"),
name[0], name + 1);
name += name[0] + 1;
fprintf (file, _(" module name: %.*s\n"),
name[0], name + 1);
cmdlen = 2 + src->length;
}
break;
case DST__K_SRC_SETFILE:
fprintf (file, _(" setfile %u\n"),
(unsigned)bfd_getl16 (buf + 1));
cmdlen = 3;
break;
case DST__K_SRC_SETREC_W:
fprintf (file, _(" setrec %u\n"),
(unsigned)bfd_getl16 (buf + 1));
cmdlen = 3;
break;
case DST__K_SRC_SETREC_L:
fprintf (file, _(" setrec %u\n"),
(unsigned)bfd_getl32 (buf + 1));
cmdlen = 5;
break;
case DST__K_SRC_SETLNUM_W:
fprintf (file, _(" setlnum %u\n"),
(unsigned)bfd_getl16 (buf + 1));
cmdlen = 3;
break;
case DST__K_SRC_SETLNUM_L:
fprintf (file, _(" setlnum %u\n"),
(unsigned)bfd_getl32 (buf + 1));
cmdlen = 5;
break;
case DST__K_SRC_DEFLINES_W:
fprintf (file, _(" deflines %u\n"),
(unsigned)bfd_getl16 (buf + 1));
cmdlen = 3;
break;
case DST__K_SRC_DEFLINES_B:
fprintf (file, _(" deflines %u\n"), buf[1]);
cmdlen = 2;
break;
case DST__K_SRC_FORMFEED:
fprintf (file, _(" formfeed\n"));
cmdlen = 1;
break;
default:
fprintf (file, _(" *unhandled* cmd %u\n"), cmd);
break;
}
if (cmdlen == 0)
break;
len -= cmdlen;
buf += cmdlen;
}
buf = buf_orig;
}
break;
default:
fprintf (file, _("*unhandled* dst type %u\n"), type);
break;
}
free (buf);
}
}
static void
evax_bfd_print_image (bfd *abfd, FILE *file)
{
struct vms_eihd eihd;
const char *name;
unsigned int val;
unsigned int eiha_off;
unsigned int eihi_off;
unsigned int eihs_off;
unsigned int eisd_off;
unsigned int eihef_off = 0;
unsigned int eihnp_off = 0;
unsigned int dmt_vbn = 0;
unsigned int dmt_size = 0;
unsigned int dst_vbn = 0;
unsigned int dst_size = 0;
unsigned int gst_vbn = 0;
unsigned int gst_size = 0;
unsigned int eiaf_vbn = 0;
unsigned int eiaf_size = 0;
unsigned int eihvn_off;
if (bfd_seek (abfd, (file_ptr) 0, SEEK_SET)
|| bfd_bread (&eihd, sizeof (eihd), abfd) != sizeof (eihd))
{
fprintf (file, _("cannot read EIHD\n"));
return;
}
fprintf (file, _("EIHD: (size: %u, nbr blocks: %u)\n"),
(unsigned)bfd_getl32 (eihd.size),
(unsigned)bfd_getl32 (eihd.hdrblkcnt));
fprintf (file, _(" majorid: %u, minorid: %u\n"),
(unsigned)bfd_getl32 (eihd.majorid),
(unsigned)bfd_getl32 (eihd.minorid));
val = (unsigned)bfd_getl32 (eihd.imgtype);
switch (val)
{
case EIHD__K_EXE:
name = _("executable");
break;
case EIHD__K_LIM:
name = _("linkable image");
break;
default:
name = _("unknown");
break;
}
fprintf (file, _(" image type: %u (%s)"), val, name);
val = (unsigned)bfd_getl32 (eihd.subtype);
switch (val)
{
case EIHD__C_NATIVE:
name = _("native");
break;
case EIHD__C_CLI:
name = _("CLI");
break;
default:
name = _("unknown");
break;
}
fprintf (file, _(", subtype: %u (%s)\n"), val, name);
eisd_off = bfd_getl32 (eihd.isdoff);
eiha_off = bfd_getl32 (eihd.activoff);
eihi_off = bfd_getl32 (eihd.imgidoff);
eihs_off = bfd_getl32 (eihd.symdbgoff);
fprintf (file, _(" offsets: isd: %u, activ: %u, symdbg: %u, "
"imgid: %u, patch: %u\n"),
eisd_off, eiha_off, eihs_off, eihi_off,
(unsigned)bfd_getl32 (eihd.patchoff));
fprintf (file, _(" fixup info rva: "));
bfd_fprintf_vma (abfd, file, bfd_getl64 (eihd.iafva));
fprintf (file, _(", symbol vector rva: "));
bfd_fprintf_vma (abfd, file, bfd_getl64 (eihd.symvva));
eihvn_off = bfd_getl32 (eihd.version_array_off);
fprintf (file, _("\n"
" version array off: %u\n"),
eihvn_off);
fprintf (file,
_(" img I/O count: %u, nbr channels: %u, req pri: %08x%08x\n"),
(unsigned)bfd_getl32 (eihd.imgiocnt),
(unsigned)bfd_getl32 (eihd.iochancnt),
(unsigned)bfd_getl32 (eihd.privreqs + 4),
(unsigned)bfd_getl32 (eihd.privreqs + 0));
val = (unsigned)bfd_getl32 (eihd.lnkflags);
fprintf (file, _(" linker flags: %08x:"), val);
if (val & EIHD__M_LNKDEBUG)
fprintf (file, " LNKDEBUG");
if (val & EIHD__M_LNKNOTFR)
fprintf (file, " LNKNOTFR");
if (val & EIHD__M_NOP0BUFS)
fprintf (file, " NOP0BUFS");
if (val & EIHD__M_PICIMG)
fprintf (file, " PICIMG");
if (val & EIHD__M_P0IMAGE)
fprintf (file, " P0IMAGE");
if (val & EIHD__M_DBGDMT)
fprintf (file, " DBGDMT");
if (val & EIHD__M_INISHR)
fprintf (file, " INISHR");
if (val & EIHD__M_XLATED)
fprintf (file, " XLATED");
if (val & EIHD__M_BIND_CODE_SEC)
fprintf (file, " BIND_CODE_SEC");
if (val & EIHD__M_BIND_DATA_SEC)
fprintf (file, " BIND_DATA_SEC");
if (val & EIHD__M_MKTHREADS)
fprintf (file, " MKTHREADS");
if (val & EIHD__M_UPCALLS)
fprintf (file, " UPCALLS");
if (val & EIHD__M_OMV_READY)
fprintf (file, " OMV_READY");
if (val & EIHD__M_EXT_BIND_SECT)
fprintf (file, " EXT_BIND_SECT");
fprintf (file, "\n");
fprintf (file, _(" ident: 0x%08x, sysver: 0x%08x, "
"match ctrl: %u, symvect_size: %u\n"),
(unsigned)bfd_getl32 (eihd.ident),
(unsigned)bfd_getl32 (eihd.sysver),
eihd.matchctl,
(unsigned)bfd_getl32 (eihd.symvect_size));
fprintf (file, _(" BPAGE: %u"),
(unsigned)bfd_getl32 (eihd.virt_mem_block_size));
if (val & (EIHD__M_OMV_READY | EIHD__M_EXT_BIND_SECT))
{
eihef_off = bfd_getl32 (eihd.ext_fixup_off);
eihnp_off = bfd_getl32 (eihd.noopt_psect_off);
fprintf (file, _(", ext fixup offset: %u, no_opt psect off: %u"),
eihef_off, eihnp_off);
}
fprintf (file, _(", alias: %u\n"), (unsigned)bfd_getl16 (eihd.alias));
if (eihvn_off != 0)
{
struct vms_eihvn eihvn;
unsigned int mask;
unsigned int j;
fprintf (file, _("system version array information:\n"));
if (bfd_seek (abfd, (file_ptr) eihvn_off, SEEK_SET)
|| bfd_bread (&eihvn, sizeof (eihvn), abfd) != sizeof (eihvn))
{
fprintf (file, _("cannot read EIHVN header\n"));
return;
}
mask = bfd_getl32 (eihvn.subsystem_mask);
for (j = 0; j < 32; j++)
if (mask & (1 << j))
{
struct vms_eihvn_subversion ver;
if (bfd_bread (&ver, sizeof (ver), abfd) != sizeof (ver))
{
fprintf (file, _("cannot read EIHVN version\n"));
return;
}
fprintf (file, _(" %02u "), j);
switch (j)
{
case EIHVN__BASE_IMAGE_BIT:
fputs (_("BASE_IMAGE "), file);
break;
case EIHVN__MEMORY_MANAGEMENT_BIT:
fputs (_("MEMORY_MANAGEMENT"), file);
break;
case EIHVN__IO_BIT:
fputs (_("IO "), file);
break;
case EIHVN__FILES_VOLUMES_BIT:
fputs (_("FILES_VOLUMES "), file);
break;
case EIHVN__PROCESS_SCHED_BIT:
fputs (_("PROCESS_SCHED "), file);
break;
case EIHVN__SYSGEN_BIT:
fputs (_("SYSGEN "), file);
break;
case EIHVN__CLUSTERS_LOCKMGR_BIT:
fputs (_("CLUSTERS_LOCKMGR "), file);
break;
case EIHVN__LOGICAL_NAMES_BIT:
fputs (_("LOGICAL_NAMES "), file);
break;
case EIHVN__SECURITY_BIT:
fputs (_("SECURITY "), file);
break;
case EIHVN__IMAGE_ACTIVATOR_BIT:
fputs (_("IMAGE_ACTIVATOR "), file);
break;
case EIHVN__NETWORKS_BIT:
fputs (_("NETWORKS "), file);
break;
case EIHVN__COUNTERS_BIT:
fputs (_("COUNTERS "), file);
break;
case EIHVN__STABLE_BIT:
fputs (_("STABLE "), file);
break;
case EIHVN__MISC_BIT:
fputs (_("MISC "), file);
break;
case EIHVN__CPU_BIT:
fputs (_("CPU "), file);
break;
case EIHVN__VOLATILE_BIT:
fputs (_("VOLATILE "), file);
break;
case EIHVN__SHELL_BIT:
fputs (_("SHELL "), file);
break;
case EIHVN__POSIX_BIT:
fputs (_("POSIX "), file);
break;
case EIHVN__MULTI_PROCESSING_BIT:
fputs (_("MULTI_PROCESSING "), file);
break;
case EIHVN__GALAXY_BIT:
fputs (_("GALAXY "), file);
break;
default:
fputs (_("*unknown* "), file);
break;
}
fprintf (file, _(": %u.%u\n"),
(unsigned)bfd_getl16 (ver.major),
(unsigned)bfd_getl16 (ver.minor));
}
}
if (eiha_off != 0)
{
struct vms_eiha eiha;
if (bfd_seek (abfd, (file_ptr) eiha_off, SEEK_SET)
|| bfd_bread (&eiha, sizeof (eiha), abfd) != sizeof (eiha))
{
fprintf (file, _("cannot read EIHA\n"));
return;
}
fprintf (file, _("Image activation: (size=%u)\n"),
(unsigned)bfd_getl32 (eiha.size));
fprintf (file, _(" First address : 0x%08x 0x%08x\n"),
(unsigned)bfd_getl32 (eiha.tfradr1_h),
(unsigned)bfd_getl32 (eiha.tfradr1));
fprintf (file, _(" Second address: 0x%08x 0x%08x\n"),
(unsigned)bfd_getl32 (eiha.tfradr2_h),
(unsigned)bfd_getl32 (eiha.tfradr2));
fprintf (file, _(" Third address : 0x%08x 0x%08x\n"),
(unsigned)bfd_getl32 (eiha.tfradr3_h),
(unsigned)bfd_getl32 (eiha.tfradr3));
fprintf (file, _(" Fourth address: 0x%08x 0x%08x\n"),
(unsigned)bfd_getl32 (eiha.tfradr4_h),
(unsigned)bfd_getl32 (eiha.tfradr4));
fprintf (file, _(" Shared image : 0x%08x 0x%08x\n"),
(unsigned)bfd_getl32 (eiha.inishr_h),
(unsigned)bfd_getl32 (eiha.inishr));
}
if (eihi_off != 0)
{
struct vms_eihi eihi;
if (bfd_seek (abfd, (file_ptr) eihi_off, SEEK_SET)
|| bfd_bread (&eihi, sizeof (eihi), abfd) != sizeof (eihi))
{
fprintf (file, _("cannot read EIHI\n"));
return;
}
fprintf (file, _("Image identification: (major: %u, minor: %u)\n"),
(unsigned)bfd_getl32 (eihi.majorid),
(unsigned)bfd_getl32 (eihi.minorid));
fprintf (file, _(" image name : %.*s\n"),
eihi.imgnam[0], eihi.imgnam + 1);
fprintf (file, _(" link time : %s\n"),
vms_time_to_str (eihi.linktime));
fprintf (file, _(" image ident : %.*s\n"),
eihi.imgid[0], eihi.imgid + 1);
fprintf (file, _(" linker ident : %.*s\n"),
eihi.linkid[0], eihi.linkid + 1);
fprintf (file, _(" image build ident: %.*s\n"),
eihi.imgbid[0], eihi.imgbid + 1);
}
if (eihs_off != 0)
{
struct vms_eihs eihs;
if (bfd_seek (abfd, (file_ptr) eihs_off, SEEK_SET)
|| bfd_bread (&eihs, sizeof (eihs), abfd) != sizeof (eihs))
{
fprintf (file, _("cannot read EIHS\n"));
return;
}
fprintf (file, _("Image symbol & debug table: (major: %u, minor: %u)\n"),
(unsigned)bfd_getl32 (eihs.majorid),
(unsigned)bfd_getl32 (eihs.minorid));
dst_vbn = bfd_getl32 (eihs.dstvbn);
dst_size = bfd_getl32 (eihs.dstsize);
fprintf (file, _(" debug symbol table : vbn: %u, size: %u (0x%x)\n"),
dst_vbn, dst_size, dst_size);
gst_vbn = bfd_getl32 (eihs.gstvbn);
gst_size = bfd_getl32 (eihs.gstsize);
fprintf (file, _(" global symbol table: vbn: %u, records: %u\n"),
gst_vbn, gst_size);
dmt_vbn = bfd_getl32 (eihs.dmtvbn);
dmt_size = bfd_getl32 (eihs.dmtsize);
fprintf (file, _(" debug module table : vbn: %u, size: %u\n"),
dmt_vbn, dmt_size);
}
while (eisd_off != 0)
{
struct vms_eisd eisd;
unsigned int len;
while (1)
{
if (bfd_seek (abfd, (file_ptr) eisd_off, SEEK_SET)
|| bfd_bread (&eisd, sizeof (eisd), abfd) != sizeof (eisd))
{
fprintf (file, _("cannot read EISD\n"));
return;
}
len = (unsigned)bfd_getl32 (eisd.eisdsize);
if (len != (unsigned)-1)
break;
/* Next block. */
eisd_off = (eisd_off + VMS_BLOCK_SIZE) & ~(VMS_BLOCK_SIZE - 1);
}
fprintf (file, _("Image section descriptor: (major: %u, minor: %u, "
"size: %u, offset: %u)\n"),
(unsigned)bfd_getl32 (eisd.majorid),
(unsigned)bfd_getl32 (eisd.minorid),
len, eisd_off);
if (len == 0)
break;
fprintf (file, _(" section: base: 0x%08x%08x size: 0x%08x\n"),
(unsigned)bfd_getl32 (eisd.virt_addr + 4),
(unsigned)bfd_getl32 (eisd.virt_addr + 0),
(unsigned)bfd_getl32 (eisd.secsize));
val = (unsigned)bfd_getl32 (eisd.flags);
fprintf (file, _(" flags: 0x%04x"), val);
if (val & EISD__M_GBL)
fprintf (file, " GBL");
if (val & EISD__M_CRF)
fprintf (file, " CRF");
if (val & EISD__M_DZRO)
fprintf (file, " DZRO");
if (val & EISD__M_WRT)
fprintf (file, " WRT");
if (val & EISD__M_INITALCODE)
fprintf (file, " INITALCODE");
if (val & EISD__M_BASED)
fprintf (file, " BASED");
if (val & EISD__M_FIXUPVEC)
fprintf (file, " FIXUPVEC");
if (val & EISD__M_RESIDENT)
fprintf (file, " RESIDENT");
if (val & EISD__M_VECTOR)
fprintf (file, " VECTOR");
if (val & EISD__M_PROTECT)
fprintf (file, " PROTECT");
if (val & EISD__M_LASTCLU)
fprintf (file, " LASTCLU");
if (val & EISD__M_EXE)
fprintf (file, " EXE");
if (val & EISD__M_NONSHRADR)
fprintf (file, " NONSHRADR");
if (val & EISD__M_QUAD_LENGTH)
fprintf (file, " QUAD_LENGTH");
if (val & EISD__M_ALLOC_64BIT)
fprintf (file, " ALLOC_64BIT");
fprintf (file, "\n");
if (val & EISD__M_FIXUPVEC)
{
eiaf_vbn = bfd_getl32 (eisd.vbn);
eiaf_size = bfd_getl32 (eisd.secsize);
}
fprintf (file, _(" vbn: %u, pfc: %u, matchctl: %u type: %u ("),
(unsigned)bfd_getl32 (eisd.vbn),
eisd.pfc, eisd.matchctl, eisd.type);
switch (eisd.type)
{
case EISD__K_NORMAL:
fputs (_("NORMAL"), file);
break;
case EISD__K_SHRFXD:
fputs (_("SHRFXD"), file);
break;
case EISD__K_PRVFXD:
fputs (_("PRVFXD"), file);
break;
case EISD__K_SHRPIC:
fputs (_("SHRPIC"), file);
break;
case EISD__K_PRVPIC:
fputs (_("PRVPIC"), file);
break;
case EISD__K_USRSTACK:
fputs (_("USRSTACK"), file);
break;
default:
fputs (_("*unknown*"), file);
break;
}
fputs (_(")\n"), file);
if (val & EISD__M_GBL)
fprintf (file, _(" ident: 0x%08x, name: %.*s\n"),
(unsigned)bfd_getl32 (eisd.ident),
eisd.gblnam[0], eisd.gblnam + 1);
eisd_off += len;
}
if (dmt_vbn != 0)
{
if (bfd_seek (abfd, (file_ptr) (dmt_vbn - 1) * VMS_BLOCK_SIZE, SEEK_SET))
{
fprintf (file, _("cannot read DMT\n"));
return;
}
fprintf (file, _("Debug module table:\n"));
while (dmt_size > 0)
{
struct vms_dmt_header dmth;
unsigned int count;
if (bfd_bread (&dmth, sizeof (dmth), abfd) != sizeof (dmth))
{
fprintf (file, _("cannot read DMT header\n"));
return;
}
count = bfd_getl16 (dmth.psect_count);
fprintf (file,
_(" module offset: 0x%08x, size: 0x%08x, (%u psects)\n"),
(unsigned)bfd_getl32 (dmth.modbeg),
(unsigned)bfd_getl32 (dmth.size), count);
dmt_size -= sizeof (dmth);
while (count > 0)
{
struct vms_dmt_psect dmtp;
if (bfd_bread (&dmtp, sizeof (dmtp), abfd) != sizeof (dmtp))
{
fprintf (file, _("cannot read DMT psect\n"));
return;
}
fprintf (file, _(" psect start: 0x%08x, length: %u\n"),
(unsigned)bfd_getl32 (dmtp.start),
(unsigned)bfd_getl32 (dmtp.length));
count--;
dmt_size -= sizeof (dmtp);
}
}
}
if (dst_vbn != 0)
{
if (bfd_seek (abfd, (file_ptr) (dst_vbn - 1) * VMS_BLOCK_SIZE, SEEK_SET))
{
fprintf (file, _("cannot read DST\n"));
return;
}
evax_bfd_print_dst (abfd, dst_size, file);
}
if (gst_vbn != 0)
{
if (bfd_seek (abfd, (file_ptr) (gst_vbn - 1) * VMS_BLOCK_SIZE, SEEK_SET))
{
fprintf (file, _("cannot read GST\n"));
return;
}
fprintf (file, _("Global symbol table:\n"));
evax_bfd_print_eobj (abfd, file);
}
if (eiaf_vbn != 0)
{
unsigned char *buf;
struct vms_eiaf *eiaf;
unsigned int qrelfixoff;
unsigned int lrelfixoff;
unsigned int qdotadroff;
unsigned int ldotadroff;
unsigned int shrimgcnt;
unsigned int shlstoff;
unsigned int codeadroff;
unsigned int lpfixoff;
unsigned int chgprtoff;
buf = bfd_malloc (eiaf_size);
if (bfd_seek (abfd, (file_ptr) (eiaf_vbn - 1) * VMS_BLOCK_SIZE, SEEK_SET)
|| bfd_bread (buf, eiaf_size, abfd) != eiaf_size)
{
fprintf (file, _("cannot read EIHA\n"));
free (buf);
return;
}
eiaf = (struct vms_eiaf *)buf;
fprintf (file,
_("Image activator fixup: (major: %u, minor: %u)\n"),
(unsigned)bfd_getl32 (eiaf->majorid),
(unsigned)bfd_getl32 (eiaf->minorid));
fprintf (file, _(" iaflink : 0x%08x %08x\n"),
(unsigned)bfd_getl32 (eiaf->iaflink + 0),
(unsigned)bfd_getl32 (eiaf->iaflink + 4));
fprintf (file, _(" fixuplnk: 0x%08x %08x\n"),
(unsigned)bfd_getl32 (eiaf->fixuplnk + 0),
(unsigned)bfd_getl32 (eiaf->fixuplnk + 4));
fprintf (file, _(" size : %u\n"),
(unsigned)bfd_getl32 (eiaf->size));
fprintf (file, _(" flags: 0x%08x\n"),
(unsigned)bfd_getl32 (eiaf->flags));
qrelfixoff = bfd_getl32 (eiaf->qrelfixoff);
lrelfixoff = bfd_getl32 (eiaf->lrelfixoff);
fprintf (file, _(" qrelfixoff: %5u, lrelfixoff: %5u\n"),
qrelfixoff, lrelfixoff);
qdotadroff = bfd_getl32 (eiaf->qdotadroff);
ldotadroff = bfd_getl32 (eiaf->ldotadroff);
fprintf (file, _(" qdotadroff: %5u, ldotadroff: %5u\n"),
qdotadroff, ldotadroff);
codeadroff = bfd_getl32 (eiaf->codeadroff);
lpfixoff = bfd_getl32 (eiaf->lpfixoff);
fprintf (file, _(" codeadroff: %5u, lpfixoff : %5u\n"),
codeadroff, lpfixoff);
chgprtoff = bfd_getl32 (eiaf->chgprtoff);
fprintf (file, _(" chgprtoff : %5u\n"), chgprtoff);
shrimgcnt = bfd_getl32 (eiaf->shrimgcnt);
shlstoff = bfd_getl32 (eiaf->shlstoff);
fprintf (file, _(" shlstoff : %5u, shrimgcnt : %5u\n"),
shlstoff, shrimgcnt);
fprintf (file, _(" shlextra : %5u, permctx : %5u\n"),
(unsigned)bfd_getl32 (eiaf->shlextra),
(unsigned)bfd_getl32 (eiaf->permctx));
fprintf (file, _(" base_va : 0x%08x\n"),
(unsigned)bfd_getl32 (eiaf->base_va));
fprintf (file, _(" lppsbfixoff: %5u\n"),
(unsigned)bfd_getl32 (eiaf->lppsbfixoff));
if (shlstoff)
{
struct vms_shl *shl = (struct vms_shl *)(buf + shlstoff);
unsigned int j;
fprintf (file, _(" Shareable images:\n"));
for (j = 0; j < shrimgcnt; j++, shl++)
{
fprintf (file,
_(" %u: size: %u, flags: 0x%02x, name: %.*s\n"),
j, shl->size, shl->flags,
shl->imgnam[0], shl->imgnam + 1);
}
}
if (qrelfixoff != 0)
{
fprintf (file, _(" quad-word relocation fixups:\n"));
evax_bfd_print_relocation_records (file, buf + qrelfixoff, 8);
}
if (lrelfixoff != 0)
{
fprintf (file, _(" long-word relocation fixups:\n"));
evax_bfd_print_relocation_records (file, buf + lrelfixoff, 4);
}
if (qdotadroff != 0)
{
fprintf (file, _(" quad-word .address reference fixups:\n"));
evax_bfd_print_address_fixups (file, buf + qdotadroff);
}
if (ldotadroff != 0)
{
fprintf (file, _(" long-word .address reference fixups:\n"));
evax_bfd_print_address_fixups (file, buf + ldotadroff);
}
if (codeadroff != 0)
{
fprintf (file, _(" Code Address Reference Fixups:\n"));
evax_bfd_print_reference_fixups (file, buf + codeadroff);
}
if (lpfixoff != 0)
{
fprintf (file, _(" Linkage Pairs Reference Fixups:\n"));
evax_bfd_print_reference_fixups (file, buf + lpfixoff);
}
if (chgprtoff)
{
unsigned int count = (unsigned)bfd_getl32 (buf + chgprtoff);
struct vms_eicp *eicp = (struct vms_eicp *)(buf + chgprtoff + 4);
unsigned int j;
fprintf (file, _(" Change Protection (%u entries):\n"), count);
for (j = 0; j < count; j++, eicp++)
{
unsigned int prot = bfd_getl32 (eicp->newprt);
fprintf (file,
_(" base: 0x%08x %08x, size: 0x%08x, prot: 0x%08x "),
(unsigned)bfd_getl32 (eicp->baseva + 4),
(unsigned)bfd_getl32 (eicp->baseva + 0),
(unsigned)bfd_getl32 (eicp->size),
(unsigned)bfd_getl32 (eicp->newprt));
switch (prot)
{
case PRT__C_NA:
fprintf (file, "NA");
break;
case PRT__C_RESERVED:
fprintf (file, "RES");
break;
case PRT__C_KW:
fprintf (file, "KW");
break;
case PRT__C_KR:
fprintf (file, "KR");
break;
case PRT__C_UW:
fprintf (file, "UW");
break;
case PRT__C_EW:
fprintf (file, "EW");
break;
case PRT__C_ERKW:
fprintf (file, "ERKW");
break;
case PRT__C_ER:
fprintf (file, "ER");
break;
case PRT__C_SW:
fprintf (file, "SW");
break;
case PRT__C_SREW:
fprintf (file, "SREW");
break;
case PRT__C_SRKW:
fprintf (file, "SRKW");
break;
case PRT__C_SR:
fprintf (file, "SR");
break;
case PRT__C_URSW:
fprintf (file, "URSW");
break;
case PRT__C_UREW:
fprintf (file, "UREW");
break;
case PRT__C_URKW:
fprintf (file, "URKW");
break;
case PRT__C_UR:
fprintf (file, "UR");
break;
default:
fputs ("??", file);
break;
}
fputc ('\n', file);
}
}
free (buf);
}
}
static bfd_boolean
vms_bfd_print_private_bfd_data (bfd *abfd, void *ptr)
{
FILE *file = (FILE *)ptr;
if (bfd_get_file_flags (abfd) & (EXEC_P | DYNAMIC))
evax_bfd_print_image (abfd, file);
else
{
if (bfd_seek (abfd, 0, SEEK_SET))
return FALSE;
evax_bfd_print_eobj (abfd, file);
}
return TRUE;
}
/* Linking. */
/* Slurp ETIR/EDBG/ETBT VMS object records. */
static bfd_boolean
alpha_vms_read_sections_content (bfd *abfd, struct bfd_link_info *info)
{
asection *cur_section;
file_ptr cur_offset;
asection *dst_section;
file_ptr dst_offset;
if (bfd_seek (abfd, 0, SEEK_SET) != 0)
return FALSE;
cur_section = NULL;
cur_offset = 0;
dst_section = PRIV (dst_section);
dst_offset = 0;
if (info)
{
if (info->strip == strip_all || info->strip == strip_debugger)
{
/* Discard the DST section. */
dst_offset = 0;
dst_section = NULL;
}
else if (dst_section)
{
dst_offset = dst_section->output_offset;
dst_section = dst_section->output_section;
}
}
while (1)
{
int type;
bfd_boolean res;
type = _bfd_vms_get_object_record (abfd);
if (type < 0)
{
vms_debug2 ((2, "next_record failed\n"));
return FALSE;
}
switch (type)
{
case EOBJ__C_ETIR:
PRIV (image_section) = cur_section;
PRIV (image_offset) = cur_offset;
res = _bfd_vms_slurp_etir (abfd, info);
cur_section = PRIV (image_section);
cur_offset = PRIV (image_offset);
break;
case EOBJ__C_EDBG:
case EOBJ__C_ETBT:
if (dst_section == NULL)
continue;
PRIV (image_section) = dst_section;
PRIV (image_offset) = dst_offset;
res = _bfd_vms_slurp_etir (abfd, info);
dst_offset = PRIV (image_offset);
break;
case EOBJ__C_EEOM:
return TRUE;
default:
continue;
}
if (!res)
{
vms_debug2 ((2, "slurp eobj type %d failed\n", type));
return FALSE;
}
}
}
static int
alpha_vms_sizeof_headers (bfd *abfd ATTRIBUTE_UNUSED,
struct bfd_link_info *info ATTRIBUTE_UNUSED)
{
return 0;
}
/* Add a linkage pair fixup at address SECT + OFFSET to SHLIB. */
static void
alpha_vms_add_fixup_lp (struct bfd_link_info *info, bfd *src, bfd *shlib)
{
struct alpha_vms_shlib_el *sl;
asection *sect = PRIV2 (src, image_section);
file_ptr offset = PRIV2 (src, image_offset);
sl = &VEC_EL (alpha_vms_link_hash (info)->shrlibs,
struct alpha_vms_shlib_el, PRIV2 (shlib, shr_index));
sl->has_fixups = TRUE;
VEC_APPEND_EL (sl->lp, bfd_vma,
sect->output_section->vma + sect->output_offset + offset);
sect->output_section->flags |= SEC_RELOC;
}
/* Add a code address fixup at address SECT + OFFSET to SHLIB. */
static void
alpha_vms_add_fixup_ca (struct bfd_link_info *info, bfd *src, bfd *shlib)
{
struct alpha_vms_shlib_el *sl;
asection *sect = PRIV2 (src, image_section);
file_ptr offset = PRIV2 (src, image_offset);
sl = &VEC_EL (alpha_vms_link_hash (info)->shrlibs,
struct alpha_vms_shlib_el, PRIV2 (shlib, shr_index));
sl->has_fixups = TRUE;
VEC_APPEND_EL (sl->ca, bfd_vma,
sect->output_section->vma + sect->output_offset + offset);
sect->output_section->flags |= SEC_RELOC;
}
/* Add a quad word relocation fixup at address SECT + OFFSET to SHLIB. */
static void
alpha_vms_add_fixup_qr (struct bfd_link_info *info, bfd *src,
bfd *shlib, bfd_vma vec)
{
struct alpha_vms_shlib_el *sl;
struct alpha_vms_vma_ref *r;
asection *sect = PRIV2 (src, image_section);
file_ptr offset = PRIV2 (src, image_offset);
sl = &VEC_EL (alpha_vms_link_hash (info)->shrlibs,
struct alpha_vms_shlib_el, PRIV2 (shlib, shr_index));
sl->has_fixups = TRUE;
r = VEC_APPEND (sl->qr, struct alpha_vms_vma_ref);
r->vma = sect->output_section->vma + sect->output_offset + offset;
r->ref = vec;
sect->output_section->flags |= SEC_RELOC;
}
static void
alpha_vms_add_fixup_lr (struct bfd_link_info *info ATTRIBUTE_UNUSED,
unsigned int shr ATTRIBUTE_UNUSED,
bfd_vma vec ATTRIBUTE_UNUSED)
{
/* Not yet supported. */
abort ();
}
/* Add relocation. FIXME: Not yet emitted. */
static void
alpha_vms_add_lw_reloc (struct bfd_link_info *info ATTRIBUTE_UNUSED)
{
}
static void
alpha_vms_add_qw_reloc (struct bfd_link_info *info ATTRIBUTE_UNUSED)
{
}
static struct bfd_hash_entry *
alpha_vms_link_hash_newfunc (struct bfd_hash_entry *entry,
struct bfd_hash_table *table,
const char *string)
{
struct alpha_vms_link_hash_entry *ret =
(struct alpha_vms_link_hash_entry *) entry;
/* Allocate the structure if it has not already been allocated by a
subclass. */
if (ret == NULL)
ret = ((struct alpha_vms_link_hash_entry *)
bfd_hash_allocate (table,
sizeof (struct alpha_vms_link_hash_entry)));
if (ret == NULL)
return NULL;
/* Call the allocation method of the superclass. */
ret = ((struct alpha_vms_link_hash_entry *)
_bfd_link_hash_newfunc ((struct bfd_hash_entry *) ret,
table, string));
ret->sym = NULL;
return (struct bfd_hash_entry *) ret;
}
/* Create an Alpha/VMS link hash table. */
static struct bfd_link_hash_table *
alpha_vms_bfd_link_hash_table_create (bfd *abfd)
{
struct alpha_vms_link_hash_table *ret;
bfd_size_type amt = sizeof (struct alpha_vms_link_hash_table);
ret = (struct alpha_vms_link_hash_table *) bfd_malloc (amt);
if (ret == NULL)
return NULL;
if (!_bfd_link_hash_table_init (&ret->root, abfd,
alpha_vms_link_hash_newfunc,
sizeof (struct alpha_vms_link_hash_entry)))
{
free (ret);
return NULL;
}
VEC_INIT (ret->shrlibs);
ret->fixup = NULL;
return &ret->root;
}
static bfd_boolean
alpha_vms_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
{
unsigned int i;
for (i = 0; i < PRIV (gsd_sym_count); i++)
{
struct vms_symbol_entry *e = PRIV (syms)[i];
struct alpha_vms_link_hash_entry *h;
struct bfd_link_hash_entry *h_root;
asymbol sym;
if (!alpha_vms_convert_symbol (abfd, e, &sym))
return FALSE;
if ((e->flags & EGSY__V_DEF) && abfd->selective_search)
{
/* In selective_search mode, only add definition that are
required. */
h = (struct alpha_vms_link_hash_entry *)bfd_link_hash_lookup
(info->hash, sym.name, FALSE, FALSE, FALSE);
if (h == NULL || h->root.type != bfd_link_hash_undefined)
continue;
}
else
h = NULL;
h_root = (struct bfd_link_hash_entry *) h;
if (_bfd_generic_link_add_one_symbol
(info, abfd, sym.name, sym.flags, sym.section, sym.value,
NULL, FALSE, FALSE, &h_root) == FALSE)
return FALSE;
h = (struct alpha_vms_link_hash_entry *) h_root;
if ((e->flags & EGSY__V_DEF)
&& h->sym == NULL
&& abfd->xvec == info->output_bfd->xvec)
h->sym = e;
}
if (abfd->flags & DYNAMIC)
{
struct alpha_vms_shlib_el *shlib;
/* We do not want to include any of the sections in a dynamic
object in the output file. See comment in elflink.c. */
bfd_section_list_clear (abfd);
shlib = VEC_APPEND (alpha_vms_link_hash (info)->shrlibs,
struct alpha_vms_shlib_el);
shlib->abfd = abfd;
VEC_INIT (shlib->ca);
VEC_INIT (shlib->lp);
VEC_INIT (shlib->qr);
PRIV (shr_index) = VEC_COUNT (alpha_vms_link_hash (info)->shrlibs) - 1;
}
return TRUE;
}
static bfd_boolean
alpha_vms_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
{
int pass;
struct bfd_link_hash_entry **pundef;
struct bfd_link_hash_entry **next_pundef;
/* We only accept VMS libraries. */
if (info->output_bfd->xvec != abfd->xvec)
{
bfd_set_error (bfd_error_wrong_format);
return FALSE;
}
/* The archive_pass field in the archive itself is used to
initialize PASS, since we may search the same archive multiple
times. */
pass = ++abfd->archive_pass;
/* Look through the list of undefined symbols. */
for (pundef = &info->hash->undefs; *pundef != NULL; pundef = next_pundef)
{
struct bfd_link_hash_entry *h;
symindex symidx;
bfd *element;
bfd *orig_element;
h = *pundef;
next_pundef = &(*pundef)->u.undef.next;
/* When a symbol is defined, it is not necessarily removed from
the list. */
if (h->type != bfd_link_hash_undefined
&& h->type != bfd_link_hash_common)
{
/* Remove this entry from the list, for general cleanliness
and because we are going to look through the list again
if we search any more libraries. We can't remove the
entry if it is the tail, because that would lose any
entries we add to the list later on. */
if (*pundef != info->hash->undefs_tail)
{
*pundef = *next_pundef;
next_pundef = pundef;
}
continue;
}
/* Look for this symbol in the archive hash table. */
symidx = _bfd_vms_lib_find_symbol (abfd, h->root.string);
if (symidx == BFD_NO_MORE_SYMBOLS)
{
/* Nothing in this slot. */
continue;
}
element = bfd_get_elt_at_index (abfd, symidx);
if (element == NULL)
return FALSE;
if (element->archive_pass == -1 || element->archive_pass == pass)
{
/* Next symbol if this archive is wrong or already handled. */
continue;
}
if (! bfd_check_format (element, bfd_object))
{
element->archive_pass = -1;
return FALSE;
}
orig_element = element;
if (bfd_is_thin_archive (abfd))
{
element = _bfd_vms_lib_get_imagelib_file (element);
if (element == NULL || !bfd_check_format (element, bfd_object))
{
orig_element->archive_pass = -1;
return FALSE;
}
}
/* Unlike the generic linker, we know that this element provides
a definition for an undefined symbol and we know that we want
to include it. We don't need to check anything. */
if (!(*info->callbacks
->add_archive_element) (info, element, h->root.string, &element))
return FALSE;
if (!alpha_vms_link_add_object_symbols (element, info))
return FALSE;
orig_element->archive_pass = pass;
}
return TRUE;
}
static bfd_boolean
alpha_vms_bfd_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
{
switch (bfd_get_format (abfd))
{
case bfd_object:
vms_debug2 ((2, "vms_link_add_symbols for object %s\n",
abfd->filename));
return alpha_vms_link_add_object_symbols (abfd, info);
break;
case bfd_archive:
vms_debug2 ((2, "vms_link_add_symbols for archive %s\n",
abfd->filename));
return alpha_vms_link_add_archive_symbols (abfd, info);
break;
default:
bfd_set_error (bfd_error_wrong_format);
return FALSE;
}
}
static bfd_boolean
alpha_vms_build_fixups (struct bfd_link_info *info)
{
struct alpha_vms_link_hash_table *t = alpha_vms_link_hash (info);
unsigned char *content;
unsigned int i;
unsigned int sz = 0;
unsigned int lp_sz = 0;
unsigned int ca_sz = 0;
unsigned int qr_sz = 0;
unsigned int shrimg_cnt = 0;
unsigned int chgprt_num = 0;
unsigned int chgprt_sz = 0;
struct vms_eiaf *eiaf;
unsigned int off;
asection *sec;
/* Shared libraries. */
for (i = 0; i < VEC_COUNT (t->shrlibs); i++)
{
struct alpha_vms_shlib_el *shlib;
shlib = &VEC_EL (t->shrlibs, struct alpha_vms_shlib_el, i);
if (!shlib->has_fixups)
continue;
shrimg_cnt++;
if (VEC_COUNT (shlib->ca) > 0)
{
/* Header + entries. */
ca_sz += 8;
ca_sz += VEC_COUNT (shlib->ca) * 4;
}
if (VEC_COUNT (shlib->lp) > 0)
{
/* Header + entries. */
lp_sz += 8;
lp_sz += VEC_COUNT (shlib->lp) * 4;
}
if (VEC_COUNT (shlib->qr) > 0)
{
/* Header + entries. */
qr_sz += 8;
qr_sz += VEC_COUNT (shlib->qr) * 8;
}
}
/* Add markers. */
if (ca_sz > 0)
ca_sz += 8;
if (lp_sz > 0)
lp_sz += 8;
if (qr_sz > 0)
qr_sz += 8;
/* Finish now if there is no content. */
if (ca_sz + lp_sz + qr_sz == 0)
return TRUE;
/* Add an eicp entry for the fixup itself. */
chgprt_num = 1;
for (sec = info->output_bfd->sections; sec != NULL; sec = sec->next)
{
/* This isect could be made RO or EXE after relocations are applied. */
if ((sec->flags & SEC_RELOC) != 0
&& (sec->flags & (SEC_CODE | SEC_READONLY)) != 0)
chgprt_num++;
}
chgprt_sz = 4 + chgprt_num * sizeof (struct vms_eicp);
/* Allocate section content (round-up size) */
sz = sizeof (struct vms_eiaf) + shrimg_cnt * sizeof (struct vms_shl)
+ ca_sz + lp_sz + qr_sz + chgprt_sz;
sz = (sz + VMS_BLOCK_SIZE - 1) & ~(VMS_BLOCK_SIZE - 1);
content = bfd_zalloc (info->output_bfd, sz);
if (content == NULL)
return FALSE;
sec = alpha_vms_link_hash (info)->fixup;
sec->contents = content;
sec->size = sz;
eiaf = (struct vms_eiaf *)content;
off = sizeof (struct vms_eiaf);
bfd_putl32 (0, eiaf->majorid);
bfd_putl32 (0, eiaf->minorid);
bfd_putl32 (0, eiaf->iaflink);
bfd_putl32 (0, eiaf->fixuplnk);
bfd_putl32 (sizeof (struct vms_eiaf), eiaf->size);
bfd_putl32 (0, eiaf->flags);
bfd_putl32 (0, eiaf->qrelfixoff);
bfd_putl32 (0, eiaf->lrelfixoff);
bfd_putl32 (0, eiaf->qdotadroff);
bfd_putl32 (0, eiaf->ldotadroff);
bfd_putl32 (0, eiaf->codeadroff);
bfd_putl32 (0, eiaf->lpfixoff);
bfd_putl32 (0, eiaf->chgprtoff);
bfd_putl32 (shrimg_cnt ? off : 0, eiaf->shlstoff);
bfd_putl32 (shrimg_cnt, eiaf->shrimgcnt);
bfd_putl32 (0, eiaf->shlextra);
bfd_putl32 (0, eiaf->permctx);
bfd_putl32 (0, eiaf->base_va);
bfd_putl32 (0, eiaf->lppsbfixoff);
if (shrimg_cnt)
{
shrimg_cnt = 0;
/* Write shl. */
for (i = 0; i < VEC_COUNT (t->shrlibs); i++)
{
struct alpha_vms_shlib_el *shlib;
struct vms_shl *shl;
shlib = &VEC_EL (t->shrlibs, struct alpha_vms_shlib_el, i);
if (!shlib->has_fixups)
continue;
/* Renumber shared images. */
PRIV2 (shlib->abfd, shr_index) = shrimg_cnt++;
shl = (struct vms_shl *)(content + off);
bfd_putl32 (0, shl->baseva);
bfd_putl32 (0, shl->shlptr);
bfd_putl32 (0, shl->ident);
bfd_putl32 (0, shl->permctx);
shl->size = sizeof (struct vms_shl);
bfd_putl16 (0, shl->fill_1);
shl->flags = 0;
bfd_putl32 (0, shl->icb);
shl->imgnam[0] = strlen (PRIV2 (shlib->abfd, hdr_data.hdr_t_name));
memcpy (shl->imgnam + 1, PRIV2 (shlib->abfd, hdr_data.hdr_t_name),
shl->imgnam[0]);
off += sizeof (struct vms_shl);
}
/* CA fixups. */
if (ca_sz != 0)
{
bfd_putl32 (off, eiaf->codeadroff);
for (i = 0; i < VEC_COUNT (t->shrlibs); i++)
{
struct alpha_vms_shlib_el *shlib;
unsigned int j;
shlib = &VEC_EL (t->shrlibs, struct alpha_vms_shlib_el, i);
if (VEC_COUNT (shlib->ca) == 0)
continue;
bfd_putl32 (VEC_COUNT (shlib->ca), content + off);
bfd_putl32 (PRIV2 (shlib->abfd, shr_index), content + off + 4);
off += 8;
for (j = 0; j < VEC_COUNT (shlib->ca); j++)
{
bfd_putl32 (VEC_EL (shlib->ca, bfd_vma, j) - t->base_addr,
content + off);
off += 4;
}
}
bfd_putl32 (0, content + off);
bfd_putl32 (0, content + off + 4);
off += 8;
}
/* LP fixups. */
if (lp_sz != 0)
{
bfd_putl32 (off, eiaf->lpfixoff);
for (i = 0; i < VEC_COUNT (t->shrlibs); i++)
{
struct alpha_vms_shlib_el *shlib;
unsigned int j;
shlib = &VEC_EL (t->shrlibs, struct alpha_vms_shlib_el, i);
if (VEC_COUNT (shlib->lp) == 0)
continue;
bfd_putl32 (VEC_COUNT (shlib->lp), content + off);
bfd_putl32 (PRIV2 (shlib->abfd, shr_index), content + off + 4);
off += 8;
for (j = 0; j < VEC_COUNT (shlib->lp); j++)
{
bfd_putl32 (VEC_EL (shlib->lp, bfd_vma, j) - t->base_addr,
content + off);
off += 4;
}
}
bfd_putl32 (0, content + off);
bfd_putl32 (0, content + off + 4);
off += 8;
}
/* QR fixups. */
if (qr_sz != 0)
{
bfd_putl32 (off, eiaf->qdotadroff);
for (i = 0; i < VEC_COUNT (t->shrlibs); i++)
{
struct alpha_vms_shlib_el *shlib;
unsigned int j;
shlib = &VEC_EL (t->shrlibs, struct alpha_vms_shlib_el, i);
if (VEC_COUNT (shlib->qr) == 0)
continue;
bfd_putl32 (VEC_COUNT (shlib->qr), content + off);
bfd_putl32 (PRIV2 (shlib->abfd, shr_index), content + off + 4);
off += 8;
for (j = 0; j < VEC_COUNT (shlib->qr); j++)
{
struct alpha_vms_vma_ref *r;
r = &VEC_EL (shlib->qr, struct alpha_vms_vma_ref, j);
bfd_putl32 (r->vma - t->base_addr, content + off);
bfd_putl32 (r->ref, content + off + 4);
off += 8;
}
}
bfd_putl32 (0, content + off);
bfd_putl32 (0, content + off + 4);
off += 8;
}
}
/* Write the change protection table. */
bfd_putl32 (off, eiaf->chgprtoff);
bfd_putl32 (chgprt_num, content + off);
off += 4;
for (sec = info->output_bfd->sections; sec != NULL; sec = sec->next)
{
struct vms_eicp *eicp;
unsigned int prot;
if ((sec->flags & SEC_LINKER_CREATED) != 0 &&
strcmp (sec->name, "$FIXUP$") == 0)
prot = PRT__C_UREW;
else if ((sec->flags & SEC_RELOC) != 0
&& (sec->flags & (SEC_CODE | SEC_READONLY)) != 0)
prot = PRT__C_UR;
else
continue;
eicp = (struct vms_eicp *)(content + off);
bfd_putl64 (sec->vma - t->base_addr, eicp->baseva);
bfd_putl32 ((sec->size + VMS_BLOCK_SIZE - 1) & ~(VMS_BLOCK_SIZE - 1),
eicp->size);
bfd_putl32 (prot, eicp->newprt);
off += sizeof (struct vms_eicp);
}
return TRUE;
}
/* Called by bfd_hash_traverse to fill the symbol table.
Return FALSE in case of failure. */
static bfd_boolean
alpha_vms_link_output_symbol (struct bfd_hash_entry *bh, void *infov)
{
struct bfd_link_hash_entry *hc = (struct bfd_link_hash_entry *) bh;
struct bfd_link_info *info = (struct bfd_link_info *)infov;
struct alpha_vms_link_hash_entry *h;
struct vms_symbol_entry *sym;
if (hc->type == bfd_link_hash_warning)
{
hc = hc->u.i.link;
if (hc->type == bfd_link_hash_new)
return TRUE;
}
h = (struct alpha_vms_link_hash_entry *) hc;
switch (h->root.type)
{
case bfd_link_hash_undefined:
return TRUE;
case bfd_link_hash_new:
case bfd_link_hash_warning:
abort ();
case bfd_link_hash_undefweak:
return TRUE;
case bfd_link_hash_defined:
case bfd_link_hash_defweak:
{
asection *sec = h->root.u.def.section;
/* FIXME: this is certainly a symbol from a dynamic library. */
if (bfd_is_abs_section (sec))
return TRUE;
if (sec->owner->flags & DYNAMIC)
return TRUE;
}
break;
case bfd_link_hash_common:
break;
case bfd_link_hash_indirect:
return TRUE;
}
/* Do not write not kept symbols. */
if (info->strip == strip_some
&& bfd_hash_lookup (info->keep_hash, h->root.root.string,
FALSE, FALSE) != NULL)
return TRUE;
if (h->sym == NULL)
{
/* This symbol doesn't come from a VMS object. So we suppose it is
a data. */
int len = strlen (h->root.root.string);
sym = (struct vms_symbol_entry *)bfd_zalloc (info->output_bfd,
sizeof (*sym) + len);
if (sym == NULL)
abort ();
sym->namelen = len;
memcpy (sym->name, h->root.root.string, len);
sym->name[len] = 0;
sym->owner = info->output_bfd;
sym->typ = EGSD__C_SYMG;
sym->data_type = 0;
sym->flags = EGSY__V_DEF | EGSY__V_REL;
sym->symbol_vector = h->root.u.def.value;
sym->section = h->root.u.def.section;
sym->value = h->root.u.def.value;
}
else
sym = h->sym;
if (!add_symbol_entry (info->output_bfd, sym))
return FALSE;
return TRUE;
}
static bfd_boolean
alpha_vms_bfd_final_link (bfd *abfd, struct bfd_link_info *info)
{
asection *o;
struct bfd_link_order *p;
bfd *sub;
asection *fixupsec;
bfd_vma base_addr;
bfd_vma last_addr;
asection *dst;
asection *dmt;
if (bfd_link_relocatable (info))
{
/* FIXME: we do not yet support relocatable link. It is not obvious
how to do it for debug infos. */
(*info->callbacks->einfo)(_("%P: relocatable link is not supported\n"));
return FALSE;
}
bfd_get_outsymbols (abfd) = NULL;
bfd_get_symcount (abfd) = 0;
/* Mark all sections which will be included in the output file. */
for (o = abfd->sections; o != NULL; o = o->next)
for (p = o->map_head.link_order; p != NULL; p = p->next)
if (p->type == bfd_indirect_link_order)
p->u.indirect.section->linker_mark = TRUE;
#if 0
/* Handle all the link order information for the sections. */
for (o = abfd->sections; o != NULL; o = o->next)
{
printf ("For section %s (at 0x%08x, flags=0x%08x):\n",
o->name, (unsigned)o->vma, (unsigned)o->flags);
for (p = o->map_head.link_order; p != NULL; p = p->next)
{
printf (" at 0x%08x - 0x%08x: ",
(unsigned)p->offset, (unsigned)(p->offset + p->size - 1));
switch (p->type)
{
case bfd_section_reloc_link_order:
case bfd_symbol_reloc_link_order:
printf (" section/symbol reloc\n");
break;
case bfd_indirect_link_order:
printf (" section %s of %s\n",
p->u.indirect.section->name,
p->u.indirect.section->owner->filename);
break;
case bfd_data_link_order:
printf (" explicit data\n");
break;
default:
printf (" *unknown* type %u\n", p->type);
break;
}
}
}
#endif
/* Generate the symbol table. */
BFD_ASSERT (PRIV (syms) == NULL);
if (info->strip != strip_all)
bfd_hash_traverse (&info->hash->table, alpha_vms_link_output_symbol, info);
/* Find the entry point. */
if (bfd_get_start_address (abfd) == 0)
{
bfd *startbfd = NULL;
for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
{
/* Consider only VMS object files. */
if (sub->xvec != abfd->xvec)
continue;
if (!PRIV2 (sub, eom_data).eom_has_transfer)
continue;
if ((PRIV2 (sub, eom_data).eom_b_tfrflg & EEOM__M_WKTFR) && startbfd)
continue;
if (startbfd != NULL
&& !(PRIV2 (sub, eom_data).eom_b_tfrflg & EEOM__M_WKTFR))
{
(*info->callbacks->einfo)
(_("%P: multiple entry points: in modules %B and %B\n"),
startbfd, sub);
continue;
}
startbfd = sub;
}
if (startbfd)
{
unsigned int ps_idx = PRIV2 (startbfd, eom_data).eom_l_psindx;
bfd_vma tfradr = PRIV2 (startbfd, eom_data).eom_l_tfradr;
asection *sec;
sec = PRIV2 (startbfd, sections)[ps_idx];
bfd_set_start_address
(abfd, sec->output_section->vma + sec->output_offset + tfradr);
}
}
/* Set transfer addresses. */
{
int i;
struct bfd_link_hash_entry *h;
i = 0;
PRIV (transfer_address[i++]) = 0xffffffff00000340ULL; /* SYS$IMGACT */
h = bfd_link_hash_lookup (info->hash, "LIB$INITIALIZE", FALSE, FALSE, TRUE);
if (h != NULL && h->type == bfd_link_hash_defined)
PRIV (transfer_address[i++]) =
alpha_vms_get_sym_value (h->u.def.section, h->u.def.value);
PRIV (transfer_address[i++]) = bfd_get_start_address (abfd);
while (i < 4)
PRIV (transfer_address[i++]) = 0;
}
/* Allocate contents.
Also compute the virtual base address. */
base_addr = (bfd_vma)-1;
last_addr = 0;
for (o = abfd->sections; o != NULL; o = o->next)
{
if (o->flags & SEC_HAS_CONTENTS)
{
o->contents = bfd_alloc (abfd, o->size);
if (o->contents == NULL)
return FALSE;
}
if (o->flags & SEC_LOAD)
{
if (o->vma < base_addr)
base_addr = o->vma;
if (o->vma + o->size > last_addr)
last_addr = o->vma + o->size;
}
/* Clear the RELOC flags. Currently we don't support incremental
linking. We use the RELOC flag for computing the eicp entries. */
o->flags &= ~SEC_RELOC;
}
/* Create the fixup section. */
fixupsec = bfd_make_section_anyway_with_flags
(info->output_bfd, "$FIXUP$",
SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_LINKER_CREATED);
if (fixupsec == NULL)
return FALSE;
last_addr = (last_addr + 0xffff) & ~0xffff;
fixupsec->vma = last_addr;
alpha_vms_link_hash (info)->fixup = fixupsec;
alpha_vms_link_hash (info)->base_addr = base_addr;
/* Create the DMT section, if necessary. */
BFD_ASSERT (PRIV (dst_section) == NULL);
dst = bfd_get_section_by_name (abfd, "$DST$");
if (dst != NULL && dst->size == 0)
dst = NULL;
if (dst != NULL)
{
PRIV (dst_section) = dst;
dmt = bfd_make_section_anyway_with_flags
(info->output_bfd, "$DMT$",
SEC_DEBUGGING | SEC_HAS_CONTENTS | SEC_LINKER_CREATED);
if (dmt == NULL)
return FALSE;
}
else
dmt = NULL;
/* Read all sections from the inputs. */
for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
{
if (sub->flags & DYNAMIC)
{
alpha_vms_create_eisd_for_shared (abfd, sub);
continue;
}
if (!alpha_vms_read_sections_content (sub, info))
return FALSE;
}
/* Handle all the link order information for the sections.
Note: past this point, it is not possible to create new sections. */
for (o = abfd->sections; o != NULL; o = o->next)
{
for (p = o->map_head.link_order; p != NULL; p = p->next)
{
switch (p->type)
{
case bfd_section_reloc_link_order:
case bfd_symbol_reloc_link_order:
abort ();
return FALSE;
case bfd_indirect_link_order:
/* Already done. */
break;
default:
if (! _bfd_default_link_order (abfd, info, o, p))
return FALSE;
break;
}
}
}
/* Compute fixups. */
if (!alpha_vms_build_fixups (info))
return FALSE;
/* Compute the DMT. */
if (dmt != NULL)
{
int pass;
unsigned char *contents = NULL;
/* In pass 1, compute the size. In pass 2, write the DMT contents. */
for (pass = 0; pass < 2; pass++)
{
unsigned int off = 0;
/* For each object file (ie for each module). */
for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
{
asection *sub_dst;
struct vms_dmt_header *dmth = NULL;
unsigned int psect_count;
/* Skip this module if it has no DST. */
sub_dst = PRIV2 (sub, dst_section);
if (sub_dst == NULL || sub_dst->size == 0)
continue;
if (pass == 1)
{
/* Write the header. */
dmth = (struct vms_dmt_header *)(contents + off);
bfd_putl32 (sub_dst->output_offset, dmth->modbeg);
bfd_putl32 (sub_dst->size, dmth->size);
}
off += sizeof (struct vms_dmt_header);
psect_count = 0;
/* For each section (ie for each psect). */
for (o = sub->sections; o != NULL; o = o->next)
{
/* Only consider interesting sections. */
if (!(o->flags & SEC_ALLOC))
continue;
if (o->flags & SEC_LINKER_CREATED)
continue;
if (pass == 1)
{
/* Write an entry. */
struct vms_dmt_psect *dmtp;
dmtp = (struct vms_dmt_psect *)(contents + off);
bfd_putl32 (o->output_offset + o->output_section->vma,
dmtp->start);
bfd_putl32 (o->size, dmtp->length);
psect_count++;
}
off += sizeof (struct vms_dmt_psect);
}
if (pass == 1)
bfd_putl32 (psect_count, dmth->psect_count);
}
if (pass == 0)
{
contents = bfd_zalloc (info->output_bfd, off);
if (contents == NULL)
return FALSE;
dmt->contents = contents;
dmt->size = off;
}
else
{
BFD_ASSERT (off == dmt->size);
}
}
}
return TRUE;
}
/* Read the contents of a section.
buf points to a buffer of buf_size bytes to be filled with
section data (starting at offset into section) */
static bfd_boolean
alpha_vms_get_section_contents (bfd *abfd, asection *section,
void *buf, file_ptr offset,
bfd_size_type count)
{
asection *sec;
/* Image are easy. */
if (bfd_get_file_flags (abfd) & (EXEC_P | DYNAMIC))
return _bfd_generic_get_section_contents (abfd, section,
buf, offset, count);
/* Safety check. */
if (offset + count < count
|| offset + count > section->size)
{
bfd_set_error (bfd_error_invalid_operation);
return FALSE;
}
/* If the section is already in memory, just copy it. */
if (section->flags & SEC_IN_MEMORY)
{
BFD_ASSERT (section->contents != NULL);
memcpy (buf, section->contents + offset, count);
return TRUE;
}
if (section->size == 0)
return TRUE;
/* Alloc in memory and read ETIRs. */
for (sec = abfd->sections; sec; sec = sec->next)
{
BFD_ASSERT (sec->contents == NULL);
if (sec->size != 0 && (sec->flags & SEC_HAS_CONTENTS))
{
sec->contents = bfd_alloc (abfd, sec->size);
if (sec->contents == NULL)
return FALSE;
}
}
if (!alpha_vms_read_sections_content (abfd, NULL))
return FALSE;
for (sec = abfd->sections; sec; sec = sec->next)
if (sec->contents)
sec->flags |= SEC_IN_MEMORY;
memcpy (buf, section->contents + offset, count);
return TRUE;
}
/* Set the format of a file being written. */
static bfd_boolean
alpha_vms_mkobject (bfd * abfd)
{
const bfd_arch_info_type *arch;
vms_debug2 ((1, "alpha_vms_mkobject (%p)\n", abfd));
if (!vms_initialize (abfd))
return FALSE;
PRIV (recwr.buf) = bfd_alloc (abfd, MAX_OUTREC_SIZE);
if (PRIV (recwr.buf) == NULL)
return FALSE;
arch = bfd_scan_arch ("alpha");
if (arch == 0)
{
bfd_set_error (bfd_error_wrong_format);
return FALSE;
}
abfd->arch_info = arch;
return TRUE;
}
/* 4.1, generic. */
/* Called when the BFD is being closed to do any necessary cleanup. */
static bfd_boolean
vms_close_and_cleanup (bfd * abfd)
{
vms_debug2 ((1, "vms_close_and_cleanup (%p)\n", abfd));
if (abfd == NULL || abfd->tdata.any == NULL)
return TRUE;
if (abfd->format == bfd_archive)
{
bfd_release (abfd, abfd->tdata.any);
abfd->tdata.any = NULL;
return TRUE;
}
if (PRIV (recrd.buf) != NULL)
free (PRIV (recrd.buf));
if (PRIV (sections) != NULL)
free (PRIV (sections));
bfd_release (abfd, abfd->tdata.any);
abfd->tdata.any = NULL;
#ifdef VMS
if (abfd->direction == write_direction)
{
/* Last step on VMS is to convert the file to variable record length
format. */
if (bfd_cache_close (abfd) != TRUE)
return FALSE;
if (_bfd_vms_convert_to_var_unix_filename (abfd->filename) != TRUE)
return FALSE;
}
#endif
return TRUE;
}
/* Called when a new section is created. */
static bfd_boolean
vms_new_section_hook (bfd * abfd, asection *section)
{
bfd_size_type amt;
vms_debug2 ((1, "vms_new_section_hook (%p, [%u]%s)\n",
abfd, section->index, section->name));
if (! bfd_set_section_alignment (abfd, section, 0))
return FALSE;
vms_debug2 ((7, "%u: %s\n", section->index, section->name));
amt = sizeof (struct vms_section_data_struct);
section->used_by_bfd = bfd_zalloc (abfd, amt);
if (section->used_by_bfd == NULL)
return FALSE;
/* Create the section symbol. */
return _bfd_generic_new_section_hook (abfd, section);
}
/* Part 4.5, symbols. */
/* Print symbol to file according to how. how is one of
bfd_print_symbol_name just print the name
bfd_print_symbol_more print more (???)
bfd_print_symbol_all print all we know, which is not much right now :-). */
static void
vms_print_symbol (bfd * abfd,
void * file,
asymbol *symbol,
bfd_print_symbol_type how)
{
vms_debug2 ((1, "vms_print_symbol (%p, %p, %p, %d)\n",
abfd, file, symbol, how));
switch (how)
{
case bfd_print_symbol_name:
case bfd_print_symbol_more:
fprintf ((FILE *)file," %s", symbol->name);
break;
case bfd_print_symbol_all:
{
const char *section_name = symbol->section->name;
bfd_print_symbol_vandf (abfd, file, symbol);
fprintf ((FILE *) file," %-8s %s", section_name, symbol->name);
}
break;
}
}
/* Return information about symbol in ret.
fill type, value and name
type:
A absolute
B bss segment symbol
C common symbol
D data segment symbol
f filename
t a static function symbol
T text segment symbol
U undefined
- debug. */
static void
vms_get_symbol_info (bfd * abfd ATTRIBUTE_UNUSED,
asymbol *symbol,
symbol_info *ret)
{
asection *sec;
vms_debug2 ((1, "vms_get_symbol_info (%p, %p, %p)\n", abfd, symbol, ret));
sec = symbol->section;
if (ret == NULL)
return;
if (sec == NULL)
ret->type = 'U';
else if (bfd_is_com_section (sec))
ret->type = 'C';
else if (bfd_is_abs_section (sec))
ret->type = 'A';
else if (bfd_is_und_section (sec))
ret->type = 'U';
else if (bfd_is_ind_section (sec))
ret->type = 'I';
else if ((symbol->flags & BSF_FUNCTION)
|| (bfd_get_section_flags (abfd, sec) & SEC_CODE))
ret->type = 'T';
else if (bfd_get_section_flags (abfd, sec) & SEC_DATA)
ret->type = 'D';
else if (bfd_get_section_flags (abfd, sec) & SEC_ALLOC)
ret->type = 'B';
else
ret->type = '?';
if (ret->type != 'U')
ret->value = symbol->value + symbol->section->vma;
else
ret->value = 0;
ret->name = symbol->name;
}
/* Return TRUE if the given symbol sym in the BFD abfd is
a compiler generated local label, else return FALSE. */
static bfd_boolean
vms_bfd_is_local_label_name (bfd * abfd ATTRIBUTE_UNUSED,
const char *name)
{
return name[0] == '$';
}
/* Part 4.7, writing an object file. */
/* Sets the contents of the section section in BFD abfd to the data starting
in memory at LOCATION. The data is written to the output section starting
at offset offset for count bytes.
Normally TRUE is returned, else FALSE. Possible error returns are:
o bfd_error_no_contents - The output section does not have the
SEC_HAS_CONTENTS attribute, so nothing can be written to it.
o and some more too */
static bfd_boolean
_bfd_vms_set_section_contents (bfd * abfd,
asection *section,
const void * location,
file_ptr offset,
bfd_size_type count)
{
if (section->contents == NULL)
{
section->contents = bfd_alloc (abfd, section->size);
if (section->contents == NULL)
return FALSE;
memcpy (section->contents + offset, location, (size_t) count);
}
return TRUE;
}
/* Set the architecture and machine type in BFD abfd to arch and mach.
Find the correct pointer to a structure and insert it into the arch_info
pointer. */
static bfd_boolean
alpha_vms_set_arch_mach (bfd *abfd,
enum bfd_architecture arch, unsigned long mach)
{
if (arch != bfd_arch_alpha
&& arch != bfd_arch_unknown)
return FALSE;
return bfd_default_set_arch_mach (abfd, arch, mach);
}
/* Set section VMS flags. Clear NO_FLAGS and set FLAGS. */
void
bfd_vms_set_section_flags (bfd *abfd ATTRIBUTE_UNUSED,
asection *sec, flagword no_flags, flagword flags)
{
vms_section_data (sec)->no_flags = no_flags;
vms_section_data (sec)->flags = flags;
}
struct vms_private_data_struct *
bfd_vms_get_data (bfd *abfd)
{
return (struct vms_private_data_struct *)abfd->tdata.any;
}
#define vms_bfd_is_target_special_symbol ((bfd_boolean (*) (bfd *, asymbol *)) bfd_false)
#define vms_bfd_link_just_syms _bfd_generic_link_just_syms
#define vms_bfd_copy_link_hash_symbol_type \
_bfd_generic_copy_link_hash_symbol_type
#define vms_bfd_is_group_section bfd_generic_is_group_section
#define vms_bfd_discard_group bfd_generic_discard_group
#define vms_section_already_linked _bfd_generic_section_already_linked
#define vms_bfd_define_common_symbol bfd_generic_define_common_symbol
#define vms_bfd_copy_private_header_data _bfd_generic_bfd_copy_private_header_data
#define vms_bfd_copy_private_bfd_data _bfd_generic_bfd_copy_private_bfd_data
#define vms_bfd_free_cached_info _bfd_generic_bfd_free_cached_info
#define vms_bfd_copy_private_section_data _bfd_generic_bfd_copy_private_section_data
#define vms_bfd_copy_private_symbol_data _bfd_generic_bfd_copy_private_symbol_data
#define vms_bfd_set_private_flags _bfd_generic_bfd_set_private_flags
#define vms_bfd_merge_private_bfd_data _bfd_generic_bfd_merge_private_bfd_data
/* Symbols table. */
#define alpha_vms_make_empty_symbol _bfd_generic_make_empty_symbol
#define alpha_vms_bfd_is_target_special_symbol \
((bfd_boolean (*) (bfd *, asymbol *)) bfd_false)
#define alpha_vms_print_symbol vms_print_symbol
#define alpha_vms_get_symbol_info vms_get_symbol_info
#define alpha_vms_get_symbol_version_string \
_bfd_nosymbols_get_symbol_version_string
#define alpha_vms_read_minisymbols _bfd_generic_read_minisymbols
#define alpha_vms_minisymbol_to_symbol _bfd_generic_minisymbol_to_symbol
#define alpha_vms_get_lineno _bfd_nosymbols_get_lineno
#define alpha_vms_find_inliner_info _bfd_nosymbols_find_inliner_info
#define alpha_vms_bfd_make_debug_symbol _bfd_nosymbols_bfd_make_debug_symbol
#define alpha_vms_find_nearest_line _bfd_vms_find_nearest_line
#define alpha_vms_find_line _bfd_nosymbols_find_line
#define alpha_vms_bfd_is_local_label_name vms_bfd_is_local_label_name
/* Generic table. */
#define alpha_vms_close_and_cleanup vms_close_and_cleanup
#define alpha_vms_bfd_free_cached_info vms_bfd_free_cached_info
#define alpha_vms_new_section_hook vms_new_section_hook
#define alpha_vms_set_section_contents _bfd_vms_set_section_contents
#define alpha_vms_get_section_contents_in_window _bfd_generic_get_section_contents_in_window
#define alpha_vms_bfd_get_relocated_section_contents \
bfd_generic_get_relocated_section_contents
#define alpha_vms_bfd_relax_section bfd_generic_relax_section
#define alpha_vms_bfd_gc_sections bfd_generic_gc_sections
#define alpha_vms_bfd_lookup_section_flags bfd_generic_lookup_section_flags
#define alpha_vms_bfd_merge_sections bfd_generic_merge_sections
#define alpha_vms_bfd_is_group_section bfd_generic_is_group_section
#define alpha_vms_bfd_discard_group bfd_generic_discard_group
#define alpha_vms_section_already_linked \
_bfd_generic_section_already_linked
#define alpha_vms_bfd_define_common_symbol bfd_generic_define_common_symbol
#define alpha_vms_bfd_link_just_syms _bfd_generic_link_just_syms
#define alpha_vms_bfd_copy_link_hash_symbol_type \
_bfd_generic_copy_link_hash_symbol_type
#define alpha_vms_bfd_link_split_section _bfd_generic_link_split_section
#define alpha_vms_get_dynamic_symtab_upper_bound \
_bfd_nodynamic_get_dynamic_symtab_upper_bound
#define alpha_vms_canonicalize_dynamic_symtab \
_bfd_nodynamic_canonicalize_dynamic_symtab
#define alpha_vms_get_dynamic_reloc_upper_bound \
_bfd_nodynamic_get_dynamic_reloc_upper_bound
#define alpha_vms_canonicalize_dynamic_reloc \
_bfd_nodynamic_canonicalize_dynamic_reloc
const bfd_target alpha_vms_vec =
{
"vms-alpha", /* Name. */
bfd_target_evax_flavour,
BFD_ENDIAN_LITTLE, /* Data byte order is little. */
BFD_ENDIAN_LITTLE, /* Header byte order is little. */
(HAS_RELOC | EXEC_P | HAS_LINENO | HAS_DEBUG | HAS_SYMS | HAS_LOCALS
| WP_TEXT | D_PAGED), /* Object flags. */
(SEC_ALLOC | SEC_LOAD | SEC_RELOC
| SEC_READONLY | SEC_CODE | SEC_DATA
| SEC_HAS_CONTENTS | SEC_IN_MEMORY), /* Sect flags. */
0, /* symbol_leading_char. */
' ', /* ar_pad_char. */
15, /* ar_max_namelen. */
0, /* match priority. */
bfd_getl64, bfd_getl_signed_64, bfd_putl64,
bfd_getl32, bfd_getl_signed_32, bfd_putl32,
bfd_getl16, bfd_getl_signed_16, bfd_putl16,
bfd_getl64, bfd_getl_signed_64, bfd_putl64,
bfd_getl32, bfd_getl_signed_32, bfd_putl32,
bfd_getl16, bfd_getl_signed_16, bfd_putl16,
{_bfd_dummy_target, alpha_vms_object_p, /* bfd_check_format. */
_bfd_vms_lib_alpha_archive_p, _bfd_dummy_target},
{bfd_false, alpha_vms_mkobject, /* bfd_set_format. */
_bfd_vms_lib_alpha_mkarchive, bfd_false},
{bfd_false, alpha_vms_write_object_contents, /* bfd_write_contents. */
_bfd_vms_lib_write_archive_contents, bfd_false},
BFD_JUMP_TABLE_GENERIC (alpha_vms),
BFD_JUMP_TABLE_COPY (vms),
BFD_JUMP_TABLE_CORE (_bfd_nocore),
BFD_JUMP_TABLE_ARCHIVE (_bfd_vms_lib),
BFD_JUMP_TABLE_SYMBOLS (alpha_vms),
BFD_JUMP_TABLE_RELOCS (alpha_vms),
BFD_JUMP_TABLE_WRITE (alpha_vms),
BFD_JUMP_TABLE_LINK (alpha_vms),
BFD_JUMP_TABLE_DYNAMIC (alpha_vms),
NULL,
NULL
};
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.