text
stringlengths
2
100k
meta
dict
/* i2c-stub.c - I2C/SMBus chip emulator Copyright (c) 2004 Mark M. Hoffman <mhoffman@lightlink.com> Copyright (C) 2007-2014 Jean Delvare <jdelvare@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. */ #define DEBUG 1 #include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/errno.h> #include <linux/i2c.h> #include <linux/list.h> #define MAX_CHIPS 10 /* * Support for I2C_FUNC_SMBUS_BLOCK_DATA is disabled by default and must * be enabled explicitly by setting the I2C_FUNC_SMBUS_BLOCK_DATA bits * in the 'functionality' module parameter. */ #define STUB_FUNC_DEFAULT \ (I2C_FUNC_SMBUS_QUICK | I2C_FUNC_SMBUS_BYTE | \ I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_WORD_DATA | \ I2C_FUNC_SMBUS_I2C_BLOCK) #define STUB_FUNC_ALL \ (STUB_FUNC_DEFAULT | I2C_FUNC_SMBUS_BLOCK_DATA) static unsigned short chip_addr[MAX_CHIPS]; module_param_array(chip_addr, ushort, NULL, S_IRUGO); MODULE_PARM_DESC(chip_addr, "Chip addresses (up to 10, between 0x03 and 0x77)"); static unsigned long functionality = STUB_FUNC_DEFAULT; module_param(functionality, ulong, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(functionality, "Override functionality bitfield"); /* Some chips have banked register ranges */ static u8 bank_reg[MAX_CHIPS]; module_param_array(bank_reg, byte, NULL, S_IRUGO); MODULE_PARM_DESC(bank_reg, "Bank register"); static u8 bank_mask[MAX_CHIPS]; module_param_array(bank_mask, byte, NULL, S_IRUGO); MODULE_PARM_DESC(bank_mask, "Bank value mask"); static u8 bank_start[MAX_CHIPS]; module_param_array(bank_start, byte, NULL, S_IRUGO); MODULE_PARM_DESC(bank_start, "First banked register"); static u8 bank_end[MAX_CHIPS]; module_param_array(bank_end, byte, NULL, S_IRUGO); MODULE_PARM_DESC(bank_end, "Last banked register"); struct smbus_block_data { struct list_head node; u8 command; u8 len; u8 block[I2C_SMBUS_BLOCK_MAX]; }; struct stub_chip { u8 pointer; u16 words[256]; /* Byte operations use the LSB as per SMBus specification */ struct list_head smbus_blocks; /* For chips with banks, extra registers are allocated dynamically */ u8 bank_reg; u8 bank_shift; u8 bank_mask; u8 bank_sel; /* Currently selected bank */ u8 bank_start; u8 bank_end; u16 bank_size; u16 *bank_words; /* Room for bank_mask * bank_size registers */ }; static struct stub_chip *stub_chips; static int stub_chips_nr; static struct smbus_block_data *stub_find_block(struct device *dev, struct stub_chip *chip, u8 command, bool create) { struct smbus_block_data *b, *rb = NULL; list_for_each_entry(b, &chip->smbus_blocks, node) { if (b->command == command) { rb = b; break; } } if (rb == NULL && create) { rb = devm_kzalloc(dev, sizeof(*rb), GFP_KERNEL); if (rb == NULL) return rb; rb->command = command; list_add(&rb->node, &chip->smbus_blocks); } return rb; } static u16 *stub_get_wordp(struct stub_chip *chip, u8 offset) { if (chip->bank_sel && offset >= chip->bank_start && offset <= chip->bank_end) return chip->bank_words + (chip->bank_sel - 1) * chip->bank_size + offset - chip->bank_start; else return chip->words + offset; } /* Return negative errno on error. */ static s32 stub_xfer(struct i2c_adapter *adap, u16 addr, unsigned short flags, char read_write, u8 command, int size, union i2c_smbus_data *data) { s32 ret; int i, len; struct stub_chip *chip = NULL; struct smbus_block_data *b; u16 *wordp; /* Search for the right chip */ for (i = 0; i < stub_chips_nr; i++) { if (addr == chip_addr[i]) { chip = stub_chips + i; break; } } if (!chip) return -ENODEV; switch (size) { case I2C_SMBUS_QUICK: dev_dbg(&adap->dev, "smbus quick - addr 0x%02x\n", addr); ret = 0; break; case I2C_SMBUS_BYTE: if (read_write == I2C_SMBUS_WRITE) { chip->pointer = command; dev_dbg(&adap->dev, "smbus byte - addr 0x%02x, wrote 0x%02x.\n", addr, command); } else { wordp = stub_get_wordp(chip, chip->pointer++); data->byte = *wordp & 0xff; dev_dbg(&adap->dev, "smbus byte - addr 0x%02x, read 0x%02x.\n", addr, data->byte); } ret = 0; break; case I2C_SMBUS_BYTE_DATA: wordp = stub_get_wordp(chip, command); if (read_write == I2C_SMBUS_WRITE) { *wordp &= 0xff00; *wordp |= data->byte; dev_dbg(&adap->dev, "smbus byte data - addr 0x%02x, wrote 0x%02x at 0x%02x.\n", addr, data->byte, command); /* Set the bank as needed */ if (chip->bank_words && command == chip->bank_reg) { chip->bank_sel = (data->byte >> chip->bank_shift) & chip->bank_mask; dev_dbg(&adap->dev, "switching to bank %u.\n", chip->bank_sel); } } else { data->byte = *wordp & 0xff; dev_dbg(&adap->dev, "smbus byte data - addr 0x%02x, read 0x%02x at 0x%02x.\n", addr, data->byte, command); } chip->pointer = command + 1; ret = 0; break; case I2C_SMBUS_WORD_DATA: wordp = stub_get_wordp(chip, command); if (read_write == I2C_SMBUS_WRITE) { *wordp = data->word; dev_dbg(&adap->dev, "smbus word data - addr 0x%02x, wrote 0x%04x at 0x%02x.\n", addr, data->word, command); } else { data->word = *wordp; dev_dbg(&adap->dev, "smbus word data - addr 0x%02x, read 0x%04x at 0x%02x.\n", addr, data->word, command); } ret = 0; break; case I2C_SMBUS_I2C_BLOCK_DATA: /* * We ignore banks here, because banked chips don't use I2C * block transfers */ if (data->block[0] > 256 - command) /* Avoid overrun */ data->block[0] = 256 - command; len = data->block[0]; if (read_write == I2C_SMBUS_WRITE) { for (i = 0; i < len; i++) { chip->words[command + i] &= 0xff00; chip->words[command + i] |= data->block[1 + i]; } dev_dbg(&adap->dev, "i2c block data - addr 0x%02x, wrote %d bytes at 0x%02x.\n", addr, len, command); } else { for (i = 0; i < len; i++) { data->block[1 + i] = chip->words[command + i] & 0xff; } dev_dbg(&adap->dev, "i2c block data - addr 0x%02x, read %d bytes at 0x%02x.\n", addr, len, command); } ret = 0; break; case I2C_SMBUS_BLOCK_DATA: /* * We ignore banks here, because chips typically don't use both * banks and SMBus block transfers */ b = stub_find_block(&adap->dev, chip, command, false); if (read_write == I2C_SMBUS_WRITE) { len = data->block[0]; if (len == 0 || len > I2C_SMBUS_BLOCK_MAX) { ret = -EINVAL; break; } if (b == NULL) { b = stub_find_block(&adap->dev, chip, command, true); if (b == NULL) { ret = -ENOMEM; break; } } /* Largest write sets read block length */ if (len > b->len) b->len = len; for (i = 0; i < len; i++) b->block[i] = data->block[i + 1]; /* update for byte and word commands */ chip->words[command] = (b->block[0] << 8) | b->len; dev_dbg(&adap->dev, "smbus block data - addr 0x%02x, wrote %d bytes at 0x%02x.\n", addr, len, command); } else { if (b == NULL) { dev_dbg(&adap->dev, "SMBus block read command without prior block write not supported\n"); ret = -EOPNOTSUPP; break; } len = b->len; data->block[0] = len; for (i = 0; i < len; i++) data->block[i + 1] = b->block[i]; dev_dbg(&adap->dev, "smbus block data - addr 0x%02x, read %d bytes at 0x%02x.\n", addr, len, command); } ret = 0; break; default: dev_dbg(&adap->dev, "Unsupported I2C/SMBus command\n"); ret = -EOPNOTSUPP; break; } /* switch (size) */ return ret; } static u32 stub_func(struct i2c_adapter *adapter) { return STUB_FUNC_ALL & functionality; } static const struct i2c_algorithm smbus_algorithm = { .functionality = stub_func, .smbus_xfer = stub_xfer, }; static struct i2c_adapter stub_adapter = { .owner = THIS_MODULE, .class = I2C_CLASS_HWMON | I2C_CLASS_SPD, .algo = &smbus_algorithm, .name = "SMBus stub driver", }; static int __init i2c_stub_allocate_banks(int i) { struct stub_chip *chip = stub_chips + i; chip->bank_reg = bank_reg[i]; chip->bank_start = bank_start[i]; chip->bank_end = bank_end[i]; chip->bank_size = bank_end[i] - bank_start[i] + 1; /* We assume that all bits in the mask are contiguous */ chip->bank_mask = bank_mask[i]; while (!(chip->bank_mask & 1)) { chip->bank_shift++; chip->bank_mask >>= 1; } chip->bank_words = kzalloc(chip->bank_mask * chip->bank_size * sizeof(u16), GFP_KERNEL); if (!chip->bank_words) return -ENOMEM; pr_debug("i2c-stub: Allocated %u banks of %u words each (registers 0x%02x to 0x%02x)\n", chip->bank_mask, chip->bank_size, chip->bank_start, chip->bank_end); return 0; } static void i2c_stub_free(void) { int i; for (i = 0; i < stub_chips_nr; i++) kfree(stub_chips[i].bank_words); kfree(stub_chips); } static int __init i2c_stub_init(void) { int i, ret; if (!chip_addr[0]) { pr_err("i2c-stub: Please specify a chip address\n"); return -ENODEV; } for (i = 0; i < MAX_CHIPS && chip_addr[i]; i++) { if (chip_addr[i] < 0x03 || chip_addr[i] > 0x77) { pr_err("i2c-stub: Invalid chip address 0x%02x\n", chip_addr[i]); return -EINVAL; } pr_info("i2c-stub: Virtual chip at 0x%02x\n", chip_addr[i]); } /* Allocate memory for all chips at once */ stub_chips_nr = i; stub_chips = kcalloc(stub_chips_nr, sizeof(struct stub_chip), GFP_KERNEL); if (!stub_chips) { pr_err("i2c-stub: Out of memory\n"); return -ENOMEM; } for (i = 0; i < stub_chips_nr; i++) { INIT_LIST_HEAD(&stub_chips[i].smbus_blocks); /* Allocate extra memory for banked register ranges */ if (bank_mask[i]) { ret = i2c_stub_allocate_banks(i); if (ret) goto fail_free; } } ret = i2c_add_adapter(&stub_adapter); if (ret) goto fail_free; return 0; fail_free: i2c_stub_free(); return ret; } static void __exit i2c_stub_exit(void) { i2c_del_adapter(&stub_adapter); i2c_stub_free(); } MODULE_AUTHOR("Mark M. Hoffman <mhoffman@lightlink.com>"); MODULE_DESCRIPTION("I2C stub driver"); MODULE_LICENSE("GPL"); module_init(i2c_stub_init); module_exit(i2c_stub_exit);
{ "language": "C" }
/* * Author: Jon Trulson <jtrulson@ics.com> * Copyright (c) 2016 Intel Corporation. * * This program and the accompanying materials are made available under the * terms of the The MIT License which is available at * https://opensource.org/licenses/MIT. * * SPDX-License-Identifier: MIT */ #include <unistd.h> #include <stdio.h> #include <signal.h> #include <upm_utilities.h> #include <my9221.h> int shouldRun = true; void sig_handler(int signo) { if (signo == SIGINT) shouldRun = false; } int main () { signal(SIGINT, sig_handler); //! [Interesting] // Instantiate a GroveLEDBar, we use D8 for the data, and D9 for the // clock. We only use a single instance. my9221_context leds = my9221_init(8, 9, 1); if (!leds) { printf("my9221_init() failed\n"); return 1; } while (shouldRun) { // count up printf("Counting up: "); for (int i=0; i<my9221_get_max_leds(leds); i++) { printf("%d ", i); my9221_clear_all(leds); my9221_set_led(leds, i, true); upm_delay_ms(100); } printf("\n"); upm_delay_ms(100); // count down printf("Counting down: "); for (int i=my9221_get_max_leds(leds) - 1; i>=0; i--) { printf("%d ", i); my9221_clear_all(leds); my9221_set_led(leds, i, true); upm_delay_ms(100); } printf("\n"); upm_delay_ms(100); } printf("Exiting...\n"); my9221_close(leds); //! [Interesting] return 0; }
{ "language": "C" }
/* * QLogic Fibre Channel HBA Driver * Copyright (c) 2003-2014 QLogic Corporation * * See LICENSE.qla2xxx for copyright and licensing details. */ #include "qla_def.h" #include "qla_target.h" #include <linux/kthread.h> #include <linux/vmalloc.h> #include <linux/slab.h> #include <linux/delay.h> static int qla24xx_vport_disable(struct fc_vport *, bool); /* SYSFS attributes --------------------------------------------------------- */ static ssize_t qla2x00_sysfs_read_fw_dump(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct scsi_qla_host *vha = shost_priv(dev_to_shost(container_of(kobj, struct device, kobj))); struct qla_hw_data *ha = vha->hw; int rval = 0; if (!(ha->fw_dump_reading || ha->mctp_dump_reading)) return 0; if (IS_P3P_TYPE(ha)) { if (off < ha->md_template_size) { rval = memory_read_from_buffer(buf, count, &off, ha->md_tmplt_hdr, ha->md_template_size); return rval; } off -= ha->md_template_size; rval = memory_read_from_buffer(buf, count, &off, ha->md_dump, ha->md_dump_size); return rval; } else if (ha->mctp_dumped && ha->mctp_dump_reading) return memory_read_from_buffer(buf, count, &off, ha->mctp_dump, MCTP_DUMP_SIZE); else if (ha->fw_dump_reading) return memory_read_from_buffer(buf, count, &off, ha->fw_dump, ha->fw_dump_len); else return 0; } static ssize_t qla2x00_sysfs_write_fw_dump(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct scsi_qla_host *vha = shost_priv(dev_to_shost(container_of(kobj, struct device, kobj))); struct qla_hw_data *ha = vha->hw; int reading; if (off != 0) return (0); reading = simple_strtol(buf, NULL, 10); switch (reading) { case 0: if (!ha->fw_dump_reading) break; ql_log(ql_log_info, vha, 0x705d, "Firmware dump cleared on (%ld).\n", vha->host_no); if (IS_P3P_TYPE(ha)) { qla82xx_md_free(vha); qla82xx_md_prep(vha); } ha->fw_dump_reading = 0; ha->fw_dumped = 0; break; case 1: if (ha->fw_dumped && !ha->fw_dump_reading) { ha->fw_dump_reading = 1; ql_log(ql_log_info, vha, 0x705e, "Raw firmware dump ready for read on (%ld).\n", vha->host_no); } break; case 2: qla2x00_alloc_fw_dump(vha); break; case 3: if (IS_QLA82XX(ha)) { qla82xx_idc_lock(ha); qla82xx_set_reset_owner(vha); qla82xx_idc_unlock(ha); } else if (IS_QLA8044(ha)) { qla8044_idc_lock(ha); qla82xx_set_reset_owner(vha); qla8044_idc_unlock(ha); } else qla2x00_system_error(vha); break; case 4: if (IS_P3P_TYPE(ha)) { if (ha->md_tmplt_hdr) ql_dbg(ql_dbg_user, vha, 0x705b, "MiniDump supported with this firmware.\n"); else ql_dbg(ql_dbg_user, vha, 0x709d, "MiniDump not supported with this firmware.\n"); } break; case 5: if (IS_P3P_TYPE(ha)) set_bit(ISP_ABORT_NEEDED, &vha->dpc_flags); break; case 6: if (!ha->mctp_dump_reading) break; ql_log(ql_log_info, vha, 0x70c1, "MCTP dump cleared on (%ld).\n", vha->host_no); ha->mctp_dump_reading = 0; ha->mctp_dumped = 0; break; case 7: if (ha->mctp_dumped && !ha->mctp_dump_reading) { ha->mctp_dump_reading = 1; ql_log(ql_log_info, vha, 0x70c2, "Raw mctp dump ready for read on (%ld).\n", vha->host_no); } break; } return count; } static struct bin_attribute sysfs_fw_dump_attr = { .attr = { .name = "fw_dump", .mode = S_IRUSR | S_IWUSR, }, .size = 0, .read = qla2x00_sysfs_read_fw_dump, .write = qla2x00_sysfs_write_fw_dump, }; static ssize_t qla2x00_sysfs_read_fw_dump_template(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct scsi_qla_host *vha = shost_priv(dev_to_shost(container_of(kobj, struct device, kobj))); struct qla_hw_data *ha = vha->hw; if (!ha->fw_dump_template || !ha->fw_dump_template_len) return 0; ql_dbg(ql_dbg_user, vha, 0x70e2, "chunk <- off=%llx count=%zx\n", off, count); return memory_read_from_buffer(buf, count, &off, ha->fw_dump_template, ha->fw_dump_template_len); } static ssize_t qla2x00_sysfs_write_fw_dump_template(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct scsi_qla_host *vha = shost_priv(dev_to_shost(container_of(kobj, struct device, kobj))); struct qla_hw_data *ha = vha->hw; uint32_t size; if (off == 0) { if (ha->fw_dump) vfree(ha->fw_dump); if (ha->fw_dump_template) vfree(ha->fw_dump_template); ha->fw_dump = NULL; ha->fw_dump_len = 0; ha->fw_dump_template = NULL; ha->fw_dump_template_len = 0; size = qla27xx_fwdt_template_size(buf); ql_dbg(ql_dbg_user, vha, 0x70d1, "-> allocating fwdt (%x bytes)...\n", size); ha->fw_dump_template = vmalloc(size); if (!ha->fw_dump_template) { ql_log(ql_log_warn, vha, 0x70d2, "Failed allocate fwdt (%x bytes).\n", size); return -ENOMEM; } ha->fw_dump_template_len = size; } if (off + count > ha->fw_dump_template_len) { count = ha->fw_dump_template_len - off; ql_dbg(ql_dbg_user, vha, 0x70d3, "chunk -> truncating to %zx bytes.\n", count); } ql_dbg(ql_dbg_user, vha, 0x70d4, "chunk -> off=%llx count=%zx\n", off, count); memcpy(ha->fw_dump_template + off, buf, count); if (off + count == ha->fw_dump_template_len) { size = qla27xx_fwdt_calculate_dump_size(vha); ql_dbg(ql_dbg_user, vha, 0x70d5, "-> allocating fwdump (%x bytes)...\n", size); ha->fw_dump = vmalloc(size); if (!ha->fw_dump) { ql_log(ql_log_warn, vha, 0x70d6, "Failed allocate fwdump (%x bytes).\n", size); return -ENOMEM; } ha->fw_dump_len = size; } return count; } static struct bin_attribute sysfs_fw_dump_template_attr = { .attr = { .name = "fw_dump_template", .mode = S_IRUSR | S_IWUSR, }, .size = 0, .read = qla2x00_sysfs_read_fw_dump_template, .write = qla2x00_sysfs_write_fw_dump_template, }; static ssize_t qla2x00_sysfs_read_nvram(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct scsi_qla_host *vha = shost_priv(dev_to_shost(container_of(kobj, struct device, kobj))); struct qla_hw_data *ha = vha->hw; if (!capable(CAP_SYS_ADMIN)) return 0; if (IS_NOCACHE_VPD_TYPE(ha)) ha->isp_ops->read_optrom(vha, ha->nvram, ha->flt_region_nvram << 2, ha->nvram_size); return memory_read_from_buffer(buf, count, &off, ha->nvram, ha->nvram_size); } static ssize_t qla2x00_sysfs_write_nvram(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct scsi_qla_host *vha = shost_priv(dev_to_shost(container_of(kobj, struct device, kobj))); struct qla_hw_data *ha = vha->hw; uint16_t cnt; if (!capable(CAP_SYS_ADMIN) || off != 0 || count != ha->nvram_size || !ha->isp_ops->write_nvram) return -EINVAL; /* Checksum NVRAM. */ if (IS_FWI2_CAPABLE(ha)) { uint32_t *iter; uint32_t chksum; iter = (uint32_t *)buf; chksum = 0; for (cnt = 0; cnt < ((count >> 2) - 1); cnt++) chksum += le32_to_cpu(*iter++); chksum = ~chksum + 1; *iter = cpu_to_le32(chksum); } else { uint8_t *iter; uint8_t chksum; iter = (uint8_t *)buf; chksum = 0; for (cnt = 0; cnt < count - 1; cnt++) chksum += *iter++; chksum = ~chksum + 1; *iter = chksum; } if (qla2x00_wait_for_hba_online(vha) != QLA_SUCCESS) { ql_log(ql_log_warn, vha, 0x705f, "HBA not online, failing NVRAM update.\n"); return -EAGAIN; } /* Write NVRAM. */ ha->isp_ops->write_nvram(vha, (uint8_t *)buf, ha->nvram_base, count); ha->isp_ops->read_nvram(vha, (uint8_t *)ha->nvram, ha->nvram_base, count); ql_dbg(ql_dbg_user, vha, 0x7060, "Setting ISP_ABORT_NEEDED\n"); /* NVRAM settings take effect immediately. */ set_bit(ISP_ABORT_NEEDED, &vha->dpc_flags); qla2xxx_wake_dpc(vha); qla2x00_wait_for_chip_reset(vha); return count; } static struct bin_attribute sysfs_nvram_attr = { .attr = { .name = "nvram", .mode = S_IRUSR | S_IWUSR, }, .size = 512, .read = qla2x00_sysfs_read_nvram, .write = qla2x00_sysfs_write_nvram, }; static ssize_t qla2x00_sysfs_read_optrom(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct scsi_qla_host *vha = shost_priv(dev_to_shost(container_of(kobj, struct device, kobj))); struct qla_hw_data *ha = vha->hw; ssize_t rval = 0; mutex_lock(&ha->optrom_mutex); if (ha->optrom_state != QLA_SREADING) goto out; rval = memory_read_from_buffer(buf, count, &off, ha->optrom_buffer, ha->optrom_region_size); out: mutex_unlock(&ha->optrom_mutex); return rval; } static ssize_t qla2x00_sysfs_write_optrom(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct scsi_qla_host *vha = shost_priv(dev_to_shost(container_of(kobj, struct device, kobj))); struct qla_hw_data *ha = vha->hw; mutex_lock(&ha->optrom_mutex); if (ha->optrom_state != QLA_SWRITING) { mutex_unlock(&ha->optrom_mutex); return -EINVAL; } if (off > ha->optrom_region_size) { mutex_unlock(&ha->optrom_mutex); return -ERANGE; } if (off + count > ha->optrom_region_size) count = ha->optrom_region_size - off; memcpy(&ha->optrom_buffer[off], buf, count); mutex_unlock(&ha->optrom_mutex); return count; } static struct bin_attribute sysfs_optrom_attr = { .attr = { .name = "optrom", .mode = S_IRUSR | S_IWUSR, }, .size = 0, .read = qla2x00_sysfs_read_optrom, .write = qla2x00_sysfs_write_optrom, }; static ssize_t qla2x00_sysfs_write_optrom_ctl(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct scsi_qla_host *vha = shost_priv(dev_to_shost(container_of(kobj, struct device, kobj))); struct qla_hw_data *ha = vha->hw; uint32_t start = 0; uint32_t size = ha->optrom_size; int val, valid; ssize_t rval = count; if (off) return -EINVAL; if (unlikely(pci_channel_offline(ha->pdev))) return -EAGAIN; if (sscanf(buf, "%d:%x:%x", &val, &start, &size) < 1) return -EINVAL; if (start > ha->optrom_size) return -EINVAL; if (size > ha->optrom_size - start) size = ha->optrom_size - start; mutex_lock(&ha->optrom_mutex); switch (val) { case 0: if (ha->optrom_state != QLA_SREADING && ha->optrom_state != QLA_SWRITING) { rval = -EINVAL; goto out; } ha->optrom_state = QLA_SWAITING; ql_dbg(ql_dbg_user, vha, 0x7061, "Freeing flash region allocation -- 0x%x bytes.\n", ha->optrom_region_size); vfree(ha->optrom_buffer); ha->optrom_buffer = NULL; break; case 1: if (ha->optrom_state != QLA_SWAITING) { rval = -EINVAL; goto out; } ha->optrom_region_start = start; ha->optrom_region_size = size; ha->optrom_state = QLA_SREADING; ha->optrom_buffer = vmalloc(ha->optrom_region_size); if (ha->optrom_buffer == NULL) { ql_log(ql_log_warn, vha, 0x7062, "Unable to allocate memory for optrom retrieval " "(%x).\n", ha->optrom_region_size); ha->optrom_state = QLA_SWAITING; rval = -ENOMEM; goto out; } if (qla2x00_wait_for_hba_online(vha) != QLA_SUCCESS) { ql_log(ql_log_warn, vha, 0x7063, "HBA not online, failing NVRAM update.\n"); rval = -EAGAIN; goto out; } ql_dbg(ql_dbg_user, vha, 0x7064, "Reading flash region -- 0x%x/0x%x.\n", ha->optrom_region_start, ha->optrom_region_size); memset(ha->optrom_buffer, 0, ha->optrom_region_size); ha->isp_ops->read_optrom(vha, ha->optrom_buffer, ha->optrom_region_start, ha->optrom_region_size); break; case 2: if (ha->optrom_state != QLA_SWAITING) { rval = -EINVAL; goto out; } /* * We need to be more restrictive on which FLASH regions are * allowed to be updated via user-space. Regions accessible * via this method include: * * ISP21xx/ISP22xx/ISP23xx type boards: * * 0x000000 -> 0x020000 -- Boot code. * * ISP2322/ISP24xx type boards: * * 0x000000 -> 0x07ffff -- Boot code. * 0x080000 -> 0x0fffff -- Firmware. * * ISP25xx type boards: * * 0x000000 -> 0x07ffff -- Boot code. * 0x080000 -> 0x0fffff -- Firmware. * 0x120000 -> 0x12ffff -- VPD and HBA parameters. */ valid = 0; if (ha->optrom_size == OPTROM_SIZE_2300 && start == 0) valid = 1; else if (start == (ha->flt_region_boot * 4) || start == (ha->flt_region_fw * 4)) valid = 1; else if (IS_QLA24XX_TYPE(ha) || IS_QLA25XX(ha) || IS_CNA_CAPABLE(ha) || IS_QLA2031(ha) || IS_QLA27XX(ha)) valid = 1; if (!valid) { ql_log(ql_log_warn, vha, 0x7065, "Invalid start region 0x%x/0x%x.\n", start, size); rval = -EINVAL; goto out; } ha->optrom_region_start = start; ha->optrom_region_size = size; ha->optrom_state = QLA_SWRITING; ha->optrom_buffer = vmalloc(ha->optrom_region_size); if (ha->optrom_buffer == NULL) { ql_log(ql_log_warn, vha, 0x7066, "Unable to allocate memory for optrom update " "(%x)\n", ha->optrom_region_size); ha->optrom_state = QLA_SWAITING; rval = -ENOMEM; goto out; } ql_dbg(ql_dbg_user, vha, 0x7067, "Staging flash region write -- 0x%x/0x%x.\n", ha->optrom_region_start, ha->optrom_region_size); memset(ha->optrom_buffer, 0, ha->optrom_region_size); break; case 3: if (ha->optrom_state != QLA_SWRITING) { rval = -EINVAL; goto out; } if (qla2x00_wait_for_hba_online(vha) != QLA_SUCCESS) { ql_log(ql_log_warn, vha, 0x7068, "HBA not online, failing flash update.\n"); rval = -EAGAIN; goto out; } ql_dbg(ql_dbg_user, vha, 0x7069, "Writing flash region -- 0x%x/0x%x.\n", ha->optrom_region_start, ha->optrom_region_size); ha->isp_ops->write_optrom(vha, ha->optrom_buffer, ha->optrom_region_start, ha->optrom_region_size); break; default: rval = -EINVAL; } out: mutex_unlock(&ha->optrom_mutex); return rval; } static struct bin_attribute sysfs_optrom_ctl_attr = { .attr = { .name = "optrom_ctl", .mode = S_IWUSR, }, .size = 0, .write = qla2x00_sysfs_write_optrom_ctl, }; static ssize_t qla2x00_sysfs_read_vpd(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct scsi_qla_host *vha = shost_priv(dev_to_shost(container_of(kobj, struct device, kobj))); struct qla_hw_data *ha = vha->hw; if (unlikely(pci_channel_offline(ha->pdev))) return -EAGAIN; if (!capable(CAP_SYS_ADMIN)) return -EINVAL; if (IS_NOCACHE_VPD_TYPE(ha)) ha->isp_ops->read_optrom(vha, ha->vpd, ha->flt_region_vpd << 2, ha->vpd_size); return memory_read_from_buffer(buf, count, &off, ha->vpd, ha->vpd_size); } static ssize_t qla2x00_sysfs_write_vpd(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct scsi_qla_host *vha = shost_priv(dev_to_shost(container_of(kobj, struct device, kobj))); struct qla_hw_data *ha = vha->hw; uint8_t *tmp_data; if (unlikely(pci_channel_offline(ha->pdev))) return 0; if (!capable(CAP_SYS_ADMIN) || off != 0 || count != ha->vpd_size || !ha->isp_ops->write_nvram) return 0; if (qla2x00_wait_for_hba_online(vha) != QLA_SUCCESS) { ql_log(ql_log_warn, vha, 0x706a, "HBA not online, failing VPD update.\n"); return -EAGAIN; } /* Write NVRAM. */ ha->isp_ops->write_nvram(vha, (uint8_t *)buf, ha->vpd_base, count); ha->isp_ops->read_nvram(vha, (uint8_t *)ha->vpd, ha->vpd_base, count); /* Update flash version information for 4Gb & above. */ if (!IS_FWI2_CAPABLE(ha)) return -EINVAL; tmp_data = vmalloc(256); if (!tmp_data) { ql_log(ql_log_warn, vha, 0x706b, "Unable to allocate memory for VPD information update.\n"); return -ENOMEM; } ha->isp_ops->get_flash_version(vha, tmp_data); vfree(tmp_data); return count; } static struct bin_attribute sysfs_vpd_attr = { .attr = { .name = "vpd", .mode = S_IRUSR | S_IWUSR, }, .size = 0, .read = qla2x00_sysfs_read_vpd, .write = qla2x00_sysfs_write_vpd, }; static ssize_t qla2x00_sysfs_read_sfp(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct scsi_qla_host *vha = shost_priv(dev_to_shost(container_of(kobj, struct device, kobj))); struct qla_hw_data *ha = vha->hw; uint16_t iter, addr, offset; int rval; if (!capable(CAP_SYS_ADMIN) || off != 0 || count != SFP_DEV_SIZE * 2) return 0; if (ha->sfp_data) goto do_read; ha->sfp_data = dma_pool_alloc(ha->s_dma_pool, GFP_KERNEL, &ha->sfp_data_dma); if (!ha->sfp_data) { ql_log(ql_log_warn, vha, 0x706c, "Unable to allocate memory for SFP read-data.\n"); return 0; } do_read: memset(ha->sfp_data, 0, SFP_BLOCK_SIZE); addr = 0xa0; for (iter = 0, offset = 0; iter < (SFP_DEV_SIZE * 2) / SFP_BLOCK_SIZE; iter++, offset += SFP_BLOCK_SIZE) { if (iter == 4) { /* Skip to next device address. */ addr = 0xa2; offset = 0; } rval = qla2x00_read_sfp(vha, ha->sfp_data_dma, ha->sfp_data, addr, offset, SFP_BLOCK_SIZE, BIT_1); if (rval != QLA_SUCCESS) { ql_log(ql_log_warn, vha, 0x706d, "Unable to read SFP data (%x/%x/%x).\n", rval, addr, offset); return -EIO; } memcpy(buf, ha->sfp_data, SFP_BLOCK_SIZE); buf += SFP_BLOCK_SIZE; } return count; } static struct bin_attribute sysfs_sfp_attr = { .attr = { .name = "sfp", .mode = S_IRUSR | S_IWUSR, }, .size = SFP_DEV_SIZE * 2, .read = qla2x00_sysfs_read_sfp, }; static ssize_t qla2x00_sysfs_write_reset(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct scsi_qla_host *vha = shost_priv(dev_to_shost(container_of(kobj, struct device, kobj))); struct qla_hw_data *ha = vha->hw; struct scsi_qla_host *base_vha = pci_get_drvdata(ha->pdev); int type; uint32_t idc_control; uint8_t *tmp_data = NULL; if (off != 0) return -EINVAL; type = simple_strtol(buf, NULL, 10); switch (type) { case 0x2025c: ql_log(ql_log_info, vha, 0x706e, "Issuing ISP reset.\n"); scsi_block_requests(vha->host); if (IS_QLA82XX(ha)) { ha->flags.isp82xx_no_md_cap = 1; qla82xx_idc_lock(ha); qla82xx_set_reset_owner(vha); qla82xx_idc_unlock(ha); } else if (IS_QLA8044(ha)) { qla8044_idc_lock(ha); idc_control = qla8044_rd_reg(ha, QLA8044_IDC_DRV_CTRL); qla8044_wr_reg(ha, QLA8044_IDC_DRV_CTRL, (idc_control | GRACEFUL_RESET_BIT1)); qla82xx_set_reset_owner(vha); qla8044_idc_unlock(ha); } else { set_bit(ISP_ABORT_NEEDED, &vha->dpc_flags); qla2xxx_wake_dpc(vha); } qla2x00_wait_for_chip_reset(vha); scsi_unblock_requests(vha->host); break; case 0x2025d: if (!IS_QLA81XX(ha) && !IS_QLA83XX(ha)) return -EPERM; ql_log(ql_log_info, vha, 0x706f, "Issuing MPI reset.\n"); if (IS_QLA83XX(ha) || IS_QLA27XX(ha)) { uint32_t idc_control; qla83xx_idc_lock(vha, 0); __qla83xx_get_idc_control(vha, &idc_control); idc_control |= QLA83XX_IDC_GRACEFUL_RESET; __qla83xx_set_idc_control(vha, idc_control); qla83xx_wr_reg(vha, QLA83XX_IDC_DEV_STATE, QLA8XXX_DEV_NEED_RESET); qla83xx_idc_audit(vha, IDC_AUDIT_TIMESTAMP); qla83xx_idc_unlock(vha, 0); break; } else { /* Make sure FC side is not in reset */ WARN_ON_ONCE(qla2x00_wait_for_hba_online(vha) != QLA_SUCCESS); /* Issue MPI reset */ scsi_block_requests(vha->host); if (qla81xx_restart_mpi_firmware(vha) != QLA_SUCCESS) ql_log(ql_log_warn, vha, 0x7070, "MPI reset failed.\n"); scsi_unblock_requests(vha->host); break; } case 0x2025e: if (!IS_P3P_TYPE(ha) || vha != base_vha) { ql_log(ql_log_info, vha, 0x7071, "FCoE ctx reset no supported.\n"); return -EPERM; } ql_log(ql_log_info, vha, 0x7072, "Issuing FCoE ctx reset.\n"); set_bit(FCOE_CTX_RESET_NEEDED, &vha->dpc_flags); qla2xxx_wake_dpc(vha); qla2x00_wait_for_fcoe_ctx_reset(vha); break; case 0x2025f: if (!IS_QLA8031(ha)) return -EPERM; ql_log(ql_log_info, vha, 0x70bc, "Disabling Reset by IDC control\n"); qla83xx_idc_lock(vha, 0); __qla83xx_get_idc_control(vha, &idc_control); idc_control |= QLA83XX_IDC_RESET_DISABLED; __qla83xx_set_idc_control(vha, idc_control); qla83xx_idc_unlock(vha, 0); break; case 0x20260: if (!IS_QLA8031(ha)) return -EPERM; ql_log(ql_log_info, vha, 0x70bd, "Enabling Reset by IDC control\n"); qla83xx_idc_lock(vha, 0); __qla83xx_get_idc_control(vha, &idc_control); idc_control &= ~QLA83XX_IDC_RESET_DISABLED; __qla83xx_set_idc_control(vha, idc_control); qla83xx_idc_unlock(vha, 0); break; case 0x20261: ql_dbg(ql_dbg_user, vha, 0x70e0, "Updating cache versions without reset "); tmp_data = vmalloc(256); if (!tmp_data) { ql_log(ql_log_warn, vha, 0x70e1, "Unable to allocate memory for VPD information update.\n"); return -ENOMEM; } ha->isp_ops->get_flash_version(vha, tmp_data); vfree(tmp_data); break; } return count; } static struct bin_attribute sysfs_reset_attr = { .attr = { .name = "reset", .mode = S_IWUSR, }, .size = 0, .write = qla2x00_sysfs_write_reset, }; static ssize_t qla2x00_sysfs_read_xgmac_stats(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct scsi_qla_host *vha = shost_priv(dev_to_shost(container_of(kobj, struct device, kobj))); struct qla_hw_data *ha = vha->hw; int rval; uint16_t actual_size; if (!capable(CAP_SYS_ADMIN) || off != 0 || count > XGMAC_DATA_SIZE) return 0; if (ha->xgmac_data) goto do_read; ha->xgmac_data = dma_alloc_coherent(&ha->pdev->dev, XGMAC_DATA_SIZE, &ha->xgmac_data_dma, GFP_KERNEL); if (!ha->xgmac_data) { ql_log(ql_log_warn, vha, 0x7076, "Unable to allocate memory for XGMAC read-data.\n"); return 0; } do_read: actual_size = 0; memset(ha->xgmac_data, 0, XGMAC_DATA_SIZE); rval = qla2x00_get_xgmac_stats(vha, ha->xgmac_data_dma, XGMAC_DATA_SIZE, &actual_size); if (rval != QLA_SUCCESS) { ql_log(ql_log_warn, vha, 0x7077, "Unable to read XGMAC data (%x).\n", rval); count = 0; } count = actual_size > count ? count: actual_size; memcpy(buf, ha->xgmac_data, count); return count; } static struct bin_attribute sysfs_xgmac_stats_attr = { .attr = { .name = "xgmac_stats", .mode = S_IRUSR, }, .size = 0, .read = qla2x00_sysfs_read_xgmac_stats, }; static ssize_t qla2x00_sysfs_read_dcbx_tlv(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct scsi_qla_host *vha = shost_priv(dev_to_shost(container_of(kobj, struct device, kobj))); struct qla_hw_data *ha = vha->hw; int rval; if (!capable(CAP_SYS_ADMIN) || off != 0 || count > DCBX_TLV_DATA_SIZE) return 0; if (ha->dcbx_tlv) goto do_read; ha->dcbx_tlv = dma_alloc_coherent(&ha->pdev->dev, DCBX_TLV_DATA_SIZE, &ha->dcbx_tlv_dma, GFP_KERNEL); if (!ha->dcbx_tlv) { ql_log(ql_log_warn, vha, 0x7078, "Unable to allocate memory for DCBX TLV read-data.\n"); return -ENOMEM; } do_read: memset(ha->dcbx_tlv, 0, DCBX_TLV_DATA_SIZE); rval = qla2x00_get_dcbx_params(vha, ha->dcbx_tlv_dma, DCBX_TLV_DATA_SIZE); if (rval != QLA_SUCCESS) { ql_log(ql_log_warn, vha, 0x7079, "Unable to read DCBX TLV (%x).\n", rval); return -EIO; } memcpy(buf, ha->dcbx_tlv, count); return count; } static struct bin_attribute sysfs_dcbx_tlv_attr = { .attr = { .name = "dcbx_tlv", .mode = S_IRUSR, }, .size = 0, .read = qla2x00_sysfs_read_dcbx_tlv, }; static struct sysfs_entry { char *name; struct bin_attribute *attr; int is4GBp_only; } bin_file_entries[] = { { "fw_dump", &sysfs_fw_dump_attr, }, { "fw_dump_template", &sysfs_fw_dump_template_attr, 0x27 }, { "nvram", &sysfs_nvram_attr, }, { "optrom", &sysfs_optrom_attr, }, { "optrom_ctl", &sysfs_optrom_ctl_attr, }, { "vpd", &sysfs_vpd_attr, 1 }, { "sfp", &sysfs_sfp_attr, 1 }, { "reset", &sysfs_reset_attr, }, { "xgmac_stats", &sysfs_xgmac_stats_attr, 3 }, { "dcbx_tlv", &sysfs_dcbx_tlv_attr, 3 }, { NULL }, }; void qla2x00_alloc_sysfs_attr(scsi_qla_host_t *vha) { struct Scsi_Host *host = vha->host; struct sysfs_entry *iter; int ret; for (iter = bin_file_entries; iter->name; iter++) { if (iter->is4GBp_only && !IS_FWI2_CAPABLE(vha->hw)) continue; if (iter->is4GBp_only == 2 && !IS_QLA25XX(vha->hw)) continue; if (iter->is4GBp_only == 3 && !(IS_CNA_CAPABLE(vha->hw))) continue; if (iter->is4GBp_only == 0x27 && !IS_QLA27XX(vha->hw)) continue; ret = sysfs_create_bin_file(&host->shost_gendev.kobj, iter->attr); if (ret) ql_log(ql_log_warn, vha, 0x00f3, "Unable to create sysfs %s binary attribute (%d).\n", iter->name, ret); else ql_dbg(ql_dbg_init, vha, 0x00f4, "Successfully created sysfs %s binary attribure.\n", iter->name); } } void qla2x00_free_sysfs_attr(scsi_qla_host_t *vha, bool stop_beacon) { struct Scsi_Host *host = vha->host; struct sysfs_entry *iter; struct qla_hw_data *ha = vha->hw; for (iter = bin_file_entries; iter->name; iter++) { if (iter->is4GBp_only && !IS_FWI2_CAPABLE(ha)) continue; if (iter->is4GBp_only == 2 && !IS_QLA25XX(ha)) continue; if (iter->is4GBp_only == 3 && !(IS_CNA_CAPABLE(vha->hw))) continue; if (iter->is4GBp_only == 0x27 && !IS_QLA27XX(vha->hw)) continue; sysfs_remove_bin_file(&host->shost_gendev.kobj, iter->attr); } if (stop_beacon && ha->beacon_blink_led == 1) ha->isp_ops->beacon_off(vha); } /* Scsi_Host attributes. */ static ssize_t qla2x00_drvr_version_show(struct device *dev, struct device_attribute *attr, char *buf) { return scnprintf(buf, PAGE_SIZE, "%s\n", qla2x00_version_str); } static ssize_t qla2x00_fw_version_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); struct qla_hw_data *ha = vha->hw; char fw_str[128]; return scnprintf(buf, PAGE_SIZE, "%s\n", ha->isp_ops->fw_version_str(vha, fw_str, sizeof(fw_str))); } static ssize_t qla2x00_serial_num_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); struct qla_hw_data *ha = vha->hw; uint32_t sn; if (IS_QLAFX00(vha->hw)) { return scnprintf(buf, PAGE_SIZE, "%s\n", vha->hw->mr.serial_num); } else if (IS_FWI2_CAPABLE(ha)) { qla2xxx_get_vpd_field(vha, "SN", buf, PAGE_SIZE - 1); return strlen(strcat(buf, "\n")); } sn = ((ha->serial0 & 0x1f) << 16) | (ha->serial2 << 8) | ha->serial1; return scnprintf(buf, PAGE_SIZE, "%c%05d\n", 'A' + sn / 100000, sn % 100000); } static ssize_t qla2x00_isp_name_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); return scnprintf(buf, PAGE_SIZE, "ISP%04X\n", vha->hw->pdev->device); } static ssize_t qla2x00_isp_id_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); struct qla_hw_data *ha = vha->hw; if (IS_QLAFX00(vha->hw)) return scnprintf(buf, PAGE_SIZE, "%s\n", vha->hw->mr.hw_version); return scnprintf(buf, PAGE_SIZE, "%04x %04x %04x %04x\n", ha->product_id[0], ha->product_id[1], ha->product_id[2], ha->product_id[3]); } static ssize_t qla2x00_model_name_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); return scnprintf(buf, PAGE_SIZE, "%s\n", vha->hw->model_number); } static ssize_t qla2x00_model_desc_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); return scnprintf(buf, PAGE_SIZE, "%s\n", vha->hw->model_desc); } static ssize_t qla2x00_pci_info_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); char pci_info[30]; return scnprintf(buf, PAGE_SIZE, "%s\n", vha->hw->isp_ops->pci_info_str(vha, pci_info)); } static ssize_t qla2x00_link_state_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); struct qla_hw_data *ha = vha->hw; int len = 0; if (atomic_read(&vha->loop_state) == LOOP_DOWN || atomic_read(&vha->loop_state) == LOOP_DEAD || vha->device_flags & DFLG_NO_CABLE) len = scnprintf(buf, PAGE_SIZE, "Link Down\n"); else if (atomic_read(&vha->loop_state) != LOOP_READY || qla2x00_reset_active(vha)) len = scnprintf(buf, PAGE_SIZE, "Unknown Link State\n"); else { len = scnprintf(buf, PAGE_SIZE, "Link Up - "); switch (ha->current_topology) { case ISP_CFG_NL: len += scnprintf(buf + len, PAGE_SIZE-len, "Loop\n"); break; case ISP_CFG_FL: len += scnprintf(buf + len, PAGE_SIZE-len, "FL_Port\n"); break; case ISP_CFG_N: len += scnprintf(buf + len, PAGE_SIZE-len, "N_Port to N_Port\n"); break; case ISP_CFG_F: len += scnprintf(buf + len, PAGE_SIZE-len, "F_Port\n"); break; default: len += scnprintf(buf + len, PAGE_SIZE-len, "Loop\n"); break; } } return len; } static ssize_t qla2x00_zio_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); int len = 0; switch (vha->hw->zio_mode) { case QLA_ZIO_MODE_6: len += scnprintf(buf + len, PAGE_SIZE-len, "Mode 6\n"); break; case QLA_ZIO_DISABLED: len += scnprintf(buf + len, PAGE_SIZE-len, "Disabled\n"); break; } return len; } static ssize_t qla2x00_zio_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); struct qla_hw_data *ha = vha->hw; int val = 0; uint16_t zio_mode; if (!IS_ZIO_SUPPORTED(ha)) return -ENOTSUPP; if (sscanf(buf, "%d", &val) != 1) return -EINVAL; if (val) zio_mode = QLA_ZIO_MODE_6; else zio_mode = QLA_ZIO_DISABLED; /* Update per-hba values and queue a reset. */ if (zio_mode != QLA_ZIO_DISABLED || ha->zio_mode != QLA_ZIO_DISABLED) { ha->zio_mode = zio_mode; set_bit(ISP_ABORT_NEEDED, &vha->dpc_flags); } return strlen(buf); } static ssize_t qla2x00_zio_timer_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); return scnprintf(buf, PAGE_SIZE, "%d us\n", vha->hw->zio_timer * 100); } static ssize_t qla2x00_zio_timer_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); int val = 0; uint16_t zio_timer; if (sscanf(buf, "%d", &val) != 1) return -EINVAL; if (val > 25500 || val < 100) return -ERANGE; zio_timer = (uint16_t)(val / 100); vha->hw->zio_timer = zio_timer; return strlen(buf); } static ssize_t qla2x00_beacon_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); int len = 0; if (vha->hw->beacon_blink_led) len += scnprintf(buf + len, PAGE_SIZE-len, "Enabled\n"); else len += scnprintf(buf + len, PAGE_SIZE-len, "Disabled\n"); return len; } static ssize_t qla2x00_beacon_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); struct qla_hw_data *ha = vha->hw; int val = 0; int rval; if (IS_QLA2100(ha) || IS_QLA2200(ha)) return -EPERM; if (test_bit(ABORT_ISP_ACTIVE, &vha->dpc_flags)) { ql_log(ql_log_warn, vha, 0x707a, "Abort ISP active -- ignoring beacon request.\n"); return -EBUSY; } if (sscanf(buf, "%d", &val) != 1) return -EINVAL; if (val) rval = ha->isp_ops->beacon_on(vha); else rval = ha->isp_ops->beacon_off(vha); if (rval != QLA_SUCCESS) count = 0; return count; } static ssize_t qla2x00_optrom_bios_version_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); struct qla_hw_data *ha = vha->hw; return scnprintf(buf, PAGE_SIZE, "%d.%02d\n", ha->bios_revision[1], ha->bios_revision[0]); } static ssize_t qla2x00_optrom_efi_version_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); struct qla_hw_data *ha = vha->hw; return scnprintf(buf, PAGE_SIZE, "%d.%02d\n", ha->efi_revision[1], ha->efi_revision[0]); } static ssize_t qla2x00_optrom_fcode_version_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); struct qla_hw_data *ha = vha->hw; return scnprintf(buf, PAGE_SIZE, "%d.%02d\n", ha->fcode_revision[1], ha->fcode_revision[0]); } static ssize_t qla2x00_optrom_fw_version_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); struct qla_hw_data *ha = vha->hw; return scnprintf(buf, PAGE_SIZE, "%d.%02d.%02d %d\n", ha->fw_revision[0], ha->fw_revision[1], ha->fw_revision[2], ha->fw_revision[3]); } static ssize_t qla2x00_optrom_gold_fw_version_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); struct qla_hw_data *ha = vha->hw; if (!IS_QLA81XX(ha) && !IS_QLA83XX(ha) && !IS_QLA27XX(ha)) return scnprintf(buf, PAGE_SIZE, "\n"); return scnprintf(buf, PAGE_SIZE, "%d.%02d.%02d (%d)\n", ha->gold_fw_version[0], ha->gold_fw_version[1], ha->gold_fw_version[2], ha->gold_fw_version[3]); } static ssize_t qla2x00_total_isp_aborts_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); return scnprintf(buf, PAGE_SIZE, "%d\n", vha->qla_stats.total_isp_aborts); } static ssize_t qla24xx_84xx_fw_version_show(struct device *dev, struct device_attribute *attr, char *buf) { int rval = QLA_SUCCESS; uint16_t status[2] = {0, 0}; scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); struct qla_hw_data *ha = vha->hw; if (!IS_QLA84XX(ha)) return scnprintf(buf, PAGE_SIZE, "\n"); if (ha->cs84xx->op_fw_version == 0) rval = qla84xx_verify_chip(vha, status); if ((rval == QLA_SUCCESS) && (status[0] == 0)) return scnprintf(buf, PAGE_SIZE, "%u\n", (uint32_t)ha->cs84xx->op_fw_version); return scnprintf(buf, PAGE_SIZE, "\n"); } static ssize_t qla2x00_mpi_version_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); struct qla_hw_data *ha = vha->hw; if (!IS_QLA81XX(ha) && !IS_QLA8031(ha) && !IS_QLA8044(ha) && !IS_QLA27XX(ha)) return scnprintf(buf, PAGE_SIZE, "\n"); return scnprintf(buf, PAGE_SIZE, "%d.%02d.%02d (%x)\n", ha->mpi_version[0], ha->mpi_version[1], ha->mpi_version[2], ha->mpi_capabilities); } static ssize_t qla2x00_phy_version_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); struct qla_hw_data *ha = vha->hw; if (!IS_QLA81XX(ha) && !IS_QLA8031(ha)) return scnprintf(buf, PAGE_SIZE, "\n"); return scnprintf(buf, PAGE_SIZE, "%d.%02d.%02d\n", ha->phy_version[0], ha->phy_version[1], ha->phy_version[2]); } static ssize_t qla2x00_flash_block_size_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); struct qla_hw_data *ha = vha->hw; return scnprintf(buf, PAGE_SIZE, "0x%x\n", ha->fdt_block_size); } static ssize_t qla2x00_vlan_id_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); if (!IS_CNA_CAPABLE(vha->hw)) return scnprintf(buf, PAGE_SIZE, "\n"); return scnprintf(buf, PAGE_SIZE, "%d\n", vha->fcoe_vlan_id); } static ssize_t qla2x00_vn_port_mac_address_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); if (!IS_CNA_CAPABLE(vha->hw)) return scnprintf(buf, PAGE_SIZE, "\n"); return scnprintf(buf, PAGE_SIZE, "%pMR\n", vha->fcoe_vn_port_mac); } static ssize_t qla2x00_fabric_param_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); return scnprintf(buf, PAGE_SIZE, "%d\n", vha->hw->switch_cap); } static ssize_t qla2x00_thermal_temp_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); uint16_t temp = 0; if (qla2x00_reset_active(vha)) { ql_log(ql_log_warn, vha, 0x70dc, "ISP reset active.\n"); goto done; } if (vha->hw->flags.eeh_busy) { ql_log(ql_log_warn, vha, 0x70dd, "PCI EEH busy.\n"); goto done; } if (qla2x00_get_thermal_temp(vha, &temp) == QLA_SUCCESS) return scnprintf(buf, PAGE_SIZE, "%d\n", temp); done: return scnprintf(buf, PAGE_SIZE, "\n"); } static ssize_t qla2x00_fw_state_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); int rval = QLA_FUNCTION_FAILED; uint16_t state[6]; uint32_t pstate; if (IS_QLAFX00(vha->hw)) { pstate = qlafx00_fw_state_show(dev, attr, buf); return scnprintf(buf, PAGE_SIZE, "0x%x\n", pstate); } if (qla2x00_reset_active(vha)) ql_log(ql_log_warn, vha, 0x707c, "ISP reset active.\n"); else if (!vha->hw->flags.eeh_busy) rval = qla2x00_get_firmware_state(vha, state); if (rval != QLA_SUCCESS) memset(state, -1, sizeof(state)); return scnprintf(buf, PAGE_SIZE, "0x%x 0x%x 0x%x 0x%x 0x%x 0x%x\n", state[0], state[1], state[2], state[3], state[4], state[5]); } static ssize_t qla2x00_diag_requests_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); if (!IS_BIDI_CAPABLE(vha->hw)) return scnprintf(buf, PAGE_SIZE, "\n"); return scnprintf(buf, PAGE_SIZE, "%llu\n", vha->bidi_stats.io_count); } static ssize_t qla2x00_diag_megabytes_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); if (!IS_BIDI_CAPABLE(vha->hw)) return scnprintf(buf, PAGE_SIZE, "\n"); return scnprintf(buf, PAGE_SIZE, "%llu\n", vha->bidi_stats.transfer_bytes >> 20); } static ssize_t qla2x00_fw_dump_size_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); struct qla_hw_data *ha = vha->hw; uint32_t size; if (!ha->fw_dumped) size = 0; else if (IS_P3P_TYPE(ha)) size = ha->md_template_size + ha->md_dump_size; else size = ha->fw_dump_len; return scnprintf(buf, PAGE_SIZE, "%d\n", size); } static ssize_t qla2x00_allow_cna_fw_dump_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); if (!IS_P3P_TYPE(vha->hw)) return scnprintf(buf, PAGE_SIZE, "\n"); else return scnprintf(buf, PAGE_SIZE, "%s\n", vha->hw->allow_cna_fw_dump ? "true" : "false"); } static ssize_t qla2x00_allow_cna_fw_dump_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); int val = 0; if (!IS_P3P_TYPE(vha->hw)) return -EINVAL; if (sscanf(buf, "%d", &val) != 1) return -EINVAL; vha->hw->allow_cna_fw_dump = val != 0; return strlen(buf); } static ssize_t qla2x00_pep_version_show(struct device *dev, struct device_attribute *attr, char *buf) { scsi_qla_host_t *vha = shost_priv(class_to_shost(dev)); struct qla_hw_data *ha = vha->hw; if (!IS_QLA27XX(ha)) return scnprintf(buf, PAGE_SIZE, "\n"); return scnprintf(buf, PAGE_SIZE, "%d.%02d.%02d\n", ha->pep_version[0], ha->pep_version[1], ha->pep_version[2]); } static DEVICE_ATTR(driver_version, S_IRUGO, qla2x00_drvr_version_show, NULL); static DEVICE_ATTR(fw_version, S_IRUGO, qla2x00_fw_version_show, NULL); static DEVICE_ATTR(serial_num, S_IRUGO, qla2x00_serial_num_show, NULL); static DEVICE_ATTR(isp_name, S_IRUGO, qla2x00_isp_name_show, NULL); static DEVICE_ATTR(isp_id, S_IRUGO, qla2x00_isp_id_show, NULL); static DEVICE_ATTR(model_name, S_IRUGO, qla2x00_model_name_show, NULL); static DEVICE_ATTR(model_desc, S_IRUGO, qla2x00_model_desc_show, NULL); static DEVICE_ATTR(pci_info, S_IRUGO, qla2x00_pci_info_show, NULL); static DEVICE_ATTR(link_state, S_IRUGO, qla2x00_link_state_show, NULL); static DEVICE_ATTR(zio, S_IRUGO | S_IWUSR, qla2x00_zio_show, qla2x00_zio_store); static DEVICE_ATTR(zio_timer, S_IRUGO | S_IWUSR, qla2x00_zio_timer_show, qla2x00_zio_timer_store); static DEVICE_ATTR(beacon, S_IRUGO | S_IWUSR, qla2x00_beacon_show, qla2x00_beacon_store); static DEVICE_ATTR(optrom_bios_version, S_IRUGO, qla2x00_optrom_bios_version_show, NULL); static DEVICE_ATTR(optrom_efi_version, S_IRUGO, qla2x00_optrom_efi_version_show, NULL); static DEVICE_ATTR(optrom_fcode_version, S_IRUGO, qla2x00_optrom_fcode_version_show, NULL); static DEVICE_ATTR(optrom_fw_version, S_IRUGO, qla2x00_optrom_fw_version_show, NULL); static DEVICE_ATTR(optrom_gold_fw_version, S_IRUGO, qla2x00_optrom_gold_fw_version_show, NULL); static DEVICE_ATTR(84xx_fw_version, S_IRUGO, qla24xx_84xx_fw_version_show, NULL); static DEVICE_ATTR(total_isp_aborts, S_IRUGO, qla2x00_total_isp_aborts_show, NULL); static DEVICE_ATTR(mpi_version, S_IRUGO, qla2x00_mpi_version_show, NULL); static DEVICE_ATTR(phy_version, S_IRUGO, qla2x00_phy_version_show, NULL); static DEVICE_ATTR(flash_block_size, S_IRUGO, qla2x00_flash_block_size_show, NULL); static DEVICE_ATTR(vlan_id, S_IRUGO, qla2x00_vlan_id_show, NULL); static DEVICE_ATTR(vn_port_mac_address, S_IRUGO, qla2x00_vn_port_mac_address_show, NULL); static DEVICE_ATTR(fabric_param, S_IRUGO, qla2x00_fabric_param_show, NULL); static DEVICE_ATTR(fw_state, S_IRUGO, qla2x00_fw_state_show, NULL); static DEVICE_ATTR(thermal_temp, S_IRUGO, qla2x00_thermal_temp_show, NULL); static DEVICE_ATTR(diag_requests, S_IRUGO, qla2x00_diag_requests_show, NULL); static DEVICE_ATTR(diag_megabytes, S_IRUGO, qla2x00_diag_megabytes_show, NULL); static DEVICE_ATTR(fw_dump_size, S_IRUGO, qla2x00_fw_dump_size_show, NULL); static DEVICE_ATTR(allow_cna_fw_dump, S_IRUGO | S_IWUSR, qla2x00_allow_cna_fw_dump_show, qla2x00_allow_cna_fw_dump_store); static DEVICE_ATTR(pep_version, S_IRUGO, qla2x00_pep_version_show, NULL); struct device_attribute *qla2x00_host_attrs[] = { &dev_attr_driver_version, &dev_attr_fw_version, &dev_attr_serial_num, &dev_attr_isp_name, &dev_attr_isp_id, &dev_attr_model_name, &dev_attr_model_desc, &dev_attr_pci_info, &dev_attr_link_state, &dev_attr_zio, &dev_attr_zio_timer, &dev_attr_beacon, &dev_attr_optrom_bios_version, &dev_attr_optrom_efi_version, &dev_attr_optrom_fcode_version, &dev_attr_optrom_fw_version, &dev_attr_84xx_fw_version, &dev_attr_total_isp_aborts, &dev_attr_mpi_version, &dev_attr_phy_version, &dev_attr_flash_block_size, &dev_attr_vlan_id, &dev_attr_vn_port_mac_address, &dev_attr_fabric_param, &dev_attr_fw_state, &dev_attr_optrom_gold_fw_version, &dev_attr_thermal_temp, &dev_attr_diag_requests, &dev_attr_diag_megabytes, &dev_attr_fw_dump_size, &dev_attr_allow_cna_fw_dump, &dev_attr_pep_version, NULL, }; /* Host attributes. */ static void qla2x00_get_host_port_id(struct Scsi_Host *shost) { scsi_qla_host_t *vha = shost_priv(shost); fc_host_port_id(shost) = vha->d_id.b.domain << 16 | vha->d_id.b.area << 8 | vha->d_id.b.al_pa; } static void qla2x00_get_host_speed(struct Scsi_Host *shost) { struct qla_hw_data *ha = ((struct scsi_qla_host *) (shost_priv(shost)))->hw; u32 speed = FC_PORTSPEED_UNKNOWN; if (IS_QLAFX00(ha)) { qlafx00_get_host_speed(shost); return; } switch (ha->link_data_rate) { case PORT_SPEED_1GB: speed = FC_PORTSPEED_1GBIT; break; case PORT_SPEED_2GB: speed = FC_PORTSPEED_2GBIT; break; case PORT_SPEED_4GB: speed = FC_PORTSPEED_4GBIT; break; case PORT_SPEED_8GB: speed = FC_PORTSPEED_8GBIT; break; case PORT_SPEED_10GB: speed = FC_PORTSPEED_10GBIT; break; case PORT_SPEED_16GB: speed = FC_PORTSPEED_16GBIT; break; case PORT_SPEED_32GB: speed = FC_PORTSPEED_32GBIT; break; } fc_host_speed(shost) = speed; } static void qla2x00_get_host_port_type(struct Scsi_Host *shost) { scsi_qla_host_t *vha = shost_priv(shost); uint32_t port_type = FC_PORTTYPE_UNKNOWN; if (vha->vp_idx) { fc_host_port_type(shost) = FC_PORTTYPE_NPIV; return; } switch (vha->hw->current_topology) { case ISP_CFG_NL: port_type = FC_PORTTYPE_LPORT; break; case ISP_CFG_FL: port_type = FC_PORTTYPE_NLPORT; break; case ISP_CFG_N: port_type = FC_PORTTYPE_PTP; break; case ISP_CFG_F: port_type = FC_PORTTYPE_NPORT; break; } fc_host_port_type(shost) = port_type; } static void qla2x00_get_starget_node_name(struct scsi_target *starget) { struct Scsi_Host *host = dev_to_shost(starget->dev.parent); scsi_qla_host_t *vha = shost_priv(host); fc_port_t *fcport; u64 node_name = 0; list_for_each_entry(fcport, &vha->vp_fcports, list) { if (fcport->rport && starget->id == fcport->rport->scsi_target_id) { node_name = wwn_to_u64(fcport->node_name); break; } } fc_starget_node_name(starget) = node_name; } static void qla2x00_get_starget_port_name(struct scsi_target *starget) { struct Scsi_Host *host = dev_to_shost(starget->dev.parent); scsi_qla_host_t *vha = shost_priv(host); fc_port_t *fcport; u64 port_name = 0; list_for_each_entry(fcport, &vha->vp_fcports, list) { if (fcport->rport && starget->id == fcport->rport->scsi_target_id) { port_name = wwn_to_u64(fcport->port_name); break; } } fc_starget_port_name(starget) = port_name; } static void qla2x00_get_starget_port_id(struct scsi_target *starget) { struct Scsi_Host *host = dev_to_shost(starget->dev.parent); scsi_qla_host_t *vha = shost_priv(host); fc_port_t *fcport; uint32_t port_id = ~0U; list_for_each_entry(fcport, &vha->vp_fcports, list) { if (fcport->rport && starget->id == fcport->rport->scsi_target_id) { port_id = fcport->d_id.b.domain << 16 | fcport->d_id.b.area << 8 | fcport->d_id.b.al_pa; break; } } fc_starget_port_id(starget) = port_id; } static void qla2x00_set_rport_loss_tmo(struct fc_rport *rport, uint32_t timeout) { if (timeout) rport->dev_loss_tmo = timeout; else rport->dev_loss_tmo = 1; } static void qla2x00_dev_loss_tmo_callbk(struct fc_rport *rport) { struct Scsi_Host *host = rport_to_shost(rport); fc_port_t *fcport = *(fc_port_t **)rport->dd_data; unsigned long flags; if (!fcport) return; /* Now that the rport has been deleted, set the fcport state to FCS_DEVICE_DEAD */ qla2x00_set_fcport_state(fcport, FCS_DEVICE_DEAD); /* * Transport has effectively 'deleted' the rport, clear * all local references. */ spin_lock_irqsave(host->host_lock, flags); fcport->rport = fcport->drport = NULL; *((fc_port_t **)rport->dd_data) = NULL; spin_unlock_irqrestore(host->host_lock, flags); if (test_bit(ABORT_ISP_ACTIVE, &fcport->vha->dpc_flags)) return; if (unlikely(pci_channel_offline(fcport->vha->hw->pdev))) { qla2x00_abort_all_cmds(fcport->vha, DID_NO_CONNECT << 16); return; } } static void qla2x00_terminate_rport_io(struct fc_rport *rport) { fc_port_t *fcport = *(fc_port_t **)rport->dd_data; if (!fcport) return; if (test_bit(ABORT_ISP_ACTIVE, &fcport->vha->dpc_flags)) return; if (unlikely(pci_channel_offline(fcport->vha->hw->pdev))) { qla2x00_abort_all_cmds(fcport->vha, DID_NO_CONNECT << 16); return; } /* * At this point all fcport's software-states are cleared. Perform any * final cleanup of firmware resources (PCBs and XCBs). */ if (fcport->loop_id != FC_NO_LOOP_ID) { if (IS_FWI2_CAPABLE(fcport->vha->hw)) fcport->vha->hw->isp_ops->fabric_logout(fcport->vha, fcport->loop_id, fcport->d_id.b.domain, fcport->d_id.b.area, fcport->d_id.b.al_pa); else qla2x00_port_logout(fcport->vha, fcport); } } static int qla2x00_issue_lip(struct Scsi_Host *shost) { scsi_qla_host_t *vha = shost_priv(shost); if (IS_QLAFX00(vha->hw)) return 0; qla2x00_loop_reset(vha); return 0; } static struct fc_host_statistics * qla2x00_get_fc_host_stats(struct Scsi_Host *shost) { scsi_qla_host_t *vha = shost_priv(shost); struct qla_hw_data *ha = vha->hw; struct scsi_qla_host *base_vha = pci_get_drvdata(ha->pdev); int rval; struct link_statistics *stats; dma_addr_t stats_dma; struct fc_host_statistics *pfc_host_stat; pfc_host_stat = &vha->fc_host_stat; memset(pfc_host_stat, -1, sizeof(struct fc_host_statistics)); if (IS_QLAFX00(vha->hw)) goto done; if (test_bit(UNLOADING, &vha->dpc_flags)) goto done; if (unlikely(pci_channel_offline(ha->pdev))) goto done; if (qla2x00_reset_active(vha)) goto done; stats = dma_pool_alloc(ha->s_dma_pool, GFP_KERNEL, &stats_dma); if (stats == NULL) { ql_log(ql_log_warn, vha, 0x707d, "Failed to allocate memory for stats.\n"); goto done; } memset(stats, 0, DMA_POOL_SIZE); rval = QLA_FUNCTION_FAILED; if (IS_FWI2_CAPABLE(ha)) { rval = qla24xx_get_isp_stats(base_vha, stats, stats_dma); } else if (atomic_read(&base_vha->loop_state) == LOOP_READY && !ha->dpc_active) { /* Must be in a 'READY' state for statistics retrieval. */ rval = qla2x00_get_link_status(base_vha, base_vha->loop_id, stats, stats_dma); } if (rval != QLA_SUCCESS) goto done_free; pfc_host_stat->link_failure_count = stats->link_fail_cnt; pfc_host_stat->loss_of_sync_count = stats->loss_sync_cnt; pfc_host_stat->loss_of_signal_count = stats->loss_sig_cnt; pfc_host_stat->prim_seq_protocol_err_count = stats->prim_seq_err_cnt; pfc_host_stat->invalid_tx_word_count = stats->inval_xmit_word_cnt; pfc_host_stat->invalid_crc_count = stats->inval_crc_cnt; if (IS_FWI2_CAPABLE(ha)) { pfc_host_stat->lip_count = stats->lip_cnt; pfc_host_stat->tx_frames = stats->tx_frames; pfc_host_stat->rx_frames = stats->rx_frames; pfc_host_stat->dumped_frames = stats->discarded_frames; pfc_host_stat->nos_count = stats->nos_rcvd; pfc_host_stat->error_frames = stats->dropped_frames + stats->discarded_frames; pfc_host_stat->rx_words = vha->qla_stats.input_bytes; pfc_host_stat->tx_words = vha->qla_stats.output_bytes; } pfc_host_stat->fcp_control_requests = vha->qla_stats.control_requests; pfc_host_stat->fcp_input_requests = vha->qla_stats.input_requests; pfc_host_stat->fcp_output_requests = vha->qla_stats.output_requests; pfc_host_stat->fcp_input_megabytes = vha->qla_stats.input_bytes >> 20; pfc_host_stat->fcp_output_megabytes = vha->qla_stats.output_bytes >> 20; pfc_host_stat->seconds_since_last_reset = get_jiffies_64() - vha->qla_stats.jiffies_at_last_reset; do_div(pfc_host_stat->seconds_since_last_reset, HZ); done_free: dma_pool_free(ha->s_dma_pool, stats, stats_dma); done: return pfc_host_stat; } static void qla2x00_reset_host_stats(struct Scsi_Host *shost) { scsi_qla_host_t *vha = shost_priv(shost); memset(&vha->fc_host_stat, 0, sizeof(vha->fc_host_stat)); vha->qla_stats.jiffies_at_last_reset = get_jiffies_64(); } static void qla2x00_get_host_symbolic_name(struct Scsi_Host *shost) { scsi_qla_host_t *vha = shost_priv(shost); qla2x00_get_sym_node_name(vha, fc_host_symbolic_name(shost), sizeof(fc_host_symbolic_name(shost))); } static void qla2x00_set_host_system_hostname(struct Scsi_Host *shost) { scsi_qla_host_t *vha = shost_priv(shost); set_bit(REGISTER_FDMI_NEEDED, &vha->dpc_flags); } static void qla2x00_get_host_fabric_name(struct Scsi_Host *shost) { scsi_qla_host_t *vha = shost_priv(shost); uint8_t node_name[WWN_SIZE] = { 0xFF, 0xFF, 0xFF, 0xFF, \ 0xFF, 0xFF, 0xFF, 0xFF}; u64 fabric_name = wwn_to_u64(node_name); if (vha->device_flags & SWITCH_FOUND) fabric_name = wwn_to_u64(vha->fabric_node_name); fc_host_fabric_name(shost) = fabric_name; } static void qla2x00_get_host_port_state(struct Scsi_Host *shost) { scsi_qla_host_t *vha = shost_priv(shost); struct scsi_qla_host *base_vha = pci_get_drvdata(vha->hw->pdev); if (!base_vha->flags.online) { fc_host_port_state(shost) = FC_PORTSTATE_OFFLINE; return; } switch (atomic_read(&base_vha->loop_state)) { case LOOP_UPDATE: fc_host_port_state(shost) = FC_PORTSTATE_DIAGNOSTICS; break; case LOOP_DOWN: if (test_bit(LOOP_RESYNC_NEEDED, &base_vha->dpc_flags)) fc_host_port_state(shost) = FC_PORTSTATE_DIAGNOSTICS; else fc_host_port_state(shost) = FC_PORTSTATE_LINKDOWN; break; case LOOP_DEAD: fc_host_port_state(shost) = FC_PORTSTATE_LINKDOWN; break; case LOOP_READY: fc_host_port_state(shost) = FC_PORTSTATE_ONLINE; break; default: fc_host_port_state(shost) = FC_PORTSTATE_UNKNOWN; break; } } static int qla24xx_vport_create(struct fc_vport *fc_vport, bool disable) { int ret = 0; uint8_t qos = 0; scsi_qla_host_t *base_vha = shost_priv(fc_vport->shost); scsi_qla_host_t *vha = NULL; struct qla_hw_data *ha = base_vha->hw; uint16_t options = 0; int cnt; struct req_que *req = ha->req_q_map[0]; ret = qla24xx_vport_create_req_sanity_check(fc_vport); if (ret) { ql_log(ql_log_warn, vha, 0x707e, "Vport sanity check failed, status %x\n", ret); return (ret); } vha = qla24xx_create_vhost(fc_vport); if (vha == NULL) { ql_log(ql_log_warn, vha, 0x707f, "Vport create host failed.\n"); return FC_VPORT_FAILED; } if (disable) { atomic_set(&vha->vp_state, VP_OFFLINE); fc_vport_set_state(fc_vport, FC_VPORT_DISABLED); } else atomic_set(&vha->vp_state, VP_FAILED); /* ready to create vport */ ql_log(ql_log_info, vha, 0x7080, "VP entry id %d assigned.\n", vha->vp_idx); /* initialized vport states */ atomic_set(&vha->loop_state, LOOP_DOWN); vha->vp_err_state= VP_ERR_PORTDWN; vha->vp_prev_err_state= VP_ERR_UNKWN; /* Check if physical ha port is Up */ if (atomic_read(&base_vha->loop_state) == LOOP_DOWN || atomic_read(&base_vha->loop_state) == LOOP_DEAD) { /* Don't retry or attempt login of this virtual port */ ql_dbg(ql_dbg_user, vha, 0x7081, "Vport loop state is not UP.\n"); atomic_set(&vha->loop_state, LOOP_DEAD); if (!disable) fc_vport_set_state(fc_vport, FC_VPORT_LINKDOWN); } if (IS_T10_PI_CAPABLE(ha) && ql2xenabledif) { if (ha->fw_attributes & BIT_4) { int prot = 0, guard; vha->flags.difdix_supported = 1; ql_dbg(ql_dbg_user, vha, 0x7082, "Registered for DIF/DIX type 1 and 3 protection.\n"); if (ql2xenabledif == 1) prot = SHOST_DIX_TYPE0_PROTECTION; scsi_host_set_prot(vha->host, prot | SHOST_DIF_TYPE1_PROTECTION | SHOST_DIF_TYPE2_PROTECTION | SHOST_DIF_TYPE3_PROTECTION | SHOST_DIX_TYPE1_PROTECTION | SHOST_DIX_TYPE2_PROTECTION | SHOST_DIX_TYPE3_PROTECTION); guard = SHOST_DIX_GUARD_CRC; if (IS_PI_IPGUARD_CAPABLE(ha) && (ql2xenabledif > 1 || IS_PI_DIFB_DIX0_CAPABLE(ha))) guard |= SHOST_DIX_GUARD_IP; scsi_host_set_guard(vha->host, guard); } else vha->flags.difdix_supported = 0; } if (scsi_add_host_with_dma(vha->host, &fc_vport->dev, &ha->pdev->dev)) { ql_dbg(ql_dbg_user, vha, 0x7083, "scsi_add_host failure for VP[%d].\n", vha->vp_idx); goto vport_create_failed_2; } /* initialize attributes */ fc_host_dev_loss_tmo(vha->host) = ha->port_down_retry_count; fc_host_node_name(vha->host) = wwn_to_u64(vha->node_name); fc_host_port_name(vha->host) = wwn_to_u64(vha->port_name); fc_host_supported_classes(vha->host) = fc_host_supported_classes(base_vha->host); fc_host_supported_speeds(vha->host) = fc_host_supported_speeds(base_vha->host); qlt_vport_create(vha, ha); qla24xx_vport_disable(fc_vport, disable); if (ha->flags.cpu_affinity_enabled) { req = ha->req_q_map[1]; ql_dbg(ql_dbg_multiq, vha, 0xc000, "Request queue %p attached with " "VP[%d], cpu affinity =%d\n", req, vha->vp_idx, ha->flags.cpu_affinity_enabled); goto vport_queue; } else if (ql2xmaxqueues == 1 || !ha->npiv_info) goto vport_queue; /* Create a request queue in QoS mode for the vport */ for (cnt = 0; cnt < ha->nvram_npiv_size; cnt++) { if (memcmp(ha->npiv_info[cnt].port_name, vha->port_name, 8) == 0 && memcmp(ha->npiv_info[cnt].node_name, vha->node_name, 8) == 0) { qos = ha->npiv_info[cnt].q_qos; break; } } if (qos) { ret = qla25xx_create_req_que(ha, options, vha->vp_idx, 0, 0, qos); if (!ret) ql_log(ql_log_warn, vha, 0x7084, "Can't create request queue for VP[%d]\n", vha->vp_idx); else { ql_dbg(ql_dbg_multiq, vha, 0xc001, "Request Que:%d Q0s: %d) created for VP[%d]\n", ret, qos, vha->vp_idx); ql_dbg(ql_dbg_user, vha, 0x7085, "Request Que:%d Q0s: %d) created for VP[%d]\n", ret, qos, vha->vp_idx); req = ha->req_q_map[ret]; } } vport_queue: vha->req = req; return 0; vport_create_failed_2: qla24xx_disable_vp(vha); qla24xx_deallocate_vp_id(vha); scsi_host_put(vha->host); return FC_VPORT_FAILED; } static int qla24xx_vport_delete(struct fc_vport *fc_vport) { scsi_qla_host_t *vha = fc_vport->dd_data; struct qla_hw_data *ha = vha->hw; uint16_t id = vha->vp_idx; while (test_bit(LOOP_RESYNC_ACTIVE, &vha->dpc_flags) || test_bit(FCPORT_UPDATE_NEEDED, &vha->dpc_flags)) msleep(1000); qla24xx_disable_vp(vha); vha->flags.delete_progress = 1; qlt_remove_target(ha, vha); fc_remove_host(vha->host); scsi_remove_host(vha->host); /* Allow timer to run to drain queued items, when removing vp */ qla24xx_deallocate_vp_id(vha); if (vha->timer_active) { qla2x00_vp_stop_timer(vha); ql_dbg(ql_dbg_user, vha, 0x7086, "Timer for the VP[%d] has stopped\n", vha->vp_idx); } BUG_ON(atomic_read(&vha->vref_count)); qla2x00_free_fcports(vha); mutex_lock(&ha->vport_lock); ha->cur_vport_count--; clear_bit(vha->vp_idx, ha->vp_idx_map); mutex_unlock(&ha->vport_lock); if (vha->req->id && !ha->flags.cpu_affinity_enabled) { if (qla25xx_delete_req_que(vha, vha->req) != QLA_SUCCESS) ql_log(ql_log_warn, vha, 0x7087, "Queue delete failed.\n"); } ql_log(ql_log_info, vha, 0x7088, "VP[%d] deleted.\n", id); scsi_host_put(vha->host); return 0; } static int qla24xx_vport_disable(struct fc_vport *fc_vport, bool disable) { scsi_qla_host_t *vha = fc_vport->dd_data; if (disable) qla24xx_disable_vp(vha); else qla24xx_enable_vp(vha); return 0; } struct fc_function_template qla2xxx_transport_functions = { .show_host_node_name = 1, .show_host_port_name = 1, .show_host_supported_classes = 1, .show_host_supported_speeds = 1, .get_host_port_id = qla2x00_get_host_port_id, .show_host_port_id = 1, .get_host_speed = qla2x00_get_host_speed, .show_host_speed = 1, .get_host_port_type = qla2x00_get_host_port_type, .show_host_port_type = 1, .get_host_symbolic_name = qla2x00_get_host_symbolic_name, .show_host_symbolic_name = 1, .set_host_system_hostname = qla2x00_set_host_system_hostname, .show_host_system_hostname = 1, .get_host_fabric_name = qla2x00_get_host_fabric_name, .show_host_fabric_name = 1, .get_host_port_state = qla2x00_get_host_port_state, .show_host_port_state = 1, .dd_fcrport_size = sizeof(struct fc_port *), .show_rport_supported_classes = 1, .get_starget_node_name = qla2x00_get_starget_node_name, .show_starget_node_name = 1, .get_starget_port_name = qla2x00_get_starget_port_name, .show_starget_port_name = 1, .get_starget_port_id = qla2x00_get_starget_port_id, .show_starget_port_id = 1, .set_rport_dev_loss_tmo = qla2x00_set_rport_loss_tmo, .show_rport_dev_loss_tmo = 1, .issue_fc_host_lip = qla2x00_issue_lip, .dev_loss_tmo_callbk = qla2x00_dev_loss_tmo_callbk, .terminate_rport_io = qla2x00_terminate_rport_io, .get_fc_host_stats = qla2x00_get_fc_host_stats, .reset_fc_host_stats = qla2x00_reset_host_stats, .vport_create = qla24xx_vport_create, .vport_disable = qla24xx_vport_disable, .vport_delete = qla24xx_vport_delete, .bsg_request = qla24xx_bsg_request, .bsg_timeout = qla24xx_bsg_timeout, }; struct fc_function_template qla2xxx_transport_vport_functions = { .show_host_node_name = 1, .show_host_port_name = 1, .show_host_supported_classes = 1, .get_host_port_id = qla2x00_get_host_port_id, .show_host_port_id = 1, .get_host_speed = qla2x00_get_host_speed, .show_host_speed = 1, .get_host_port_type = qla2x00_get_host_port_type, .show_host_port_type = 1, .get_host_symbolic_name = qla2x00_get_host_symbolic_name, .show_host_symbolic_name = 1, .set_host_system_hostname = qla2x00_set_host_system_hostname, .show_host_system_hostname = 1, .get_host_fabric_name = qla2x00_get_host_fabric_name, .show_host_fabric_name = 1, .get_host_port_state = qla2x00_get_host_port_state, .show_host_port_state = 1, .dd_fcrport_size = sizeof(struct fc_port *), .show_rport_supported_classes = 1, .get_starget_node_name = qla2x00_get_starget_node_name, .show_starget_node_name = 1, .get_starget_port_name = qla2x00_get_starget_port_name, .show_starget_port_name = 1, .get_starget_port_id = qla2x00_get_starget_port_id, .show_starget_port_id = 1, .set_rport_dev_loss_tmo = qla2x00_set_rport_loss_tmo, .show_rport_dev_loss_tmo = 1, .issue_fc_host_lip = qla2x00_issue_lip, .dev_loss_tmo_callbk = qla2x00_dev_loss_tmo_callbk, .terminate_rport_io = qla2x00_terminate_rport_io, .get_fc_host_stats = qla2x00_get_fc_host_stats, .reset_fc_host_stats = qla2x00_reset_host_stats, .bsg_request = qla24xx_bsg_request, .bsg_timeout = qla24xx_bsg_timeout, }; void qla2x00_init_host_attr(scsi_qla_host_t *vha) { struct qla_hw_data *ha = vha->hw; u32 speed = FC_PORTSPEED_UNKNOWN; fc_host_dev_loss_tmo(vha->host) = ha->port_down_retry_count; fc_host_node_name(vha->host) = wwn_to_u64(vha->node_name); fc_host_port_name(vha->host) = wwn_to_u64(vha->port_name); fc_host_supported_classes(vha->host) = ha->tgt.enable_class_2 ? (FC_COS_CLASS2|FC_COS_CLASS3) : FC_COS_CLASS3; fc_host_max_npiv_vports(vha->host) = ha->max_npiv_vports; fc_host_npiv_vports_inuse(vha->host) = ha->cur_vport_count; if (IS_CNA_CAPABLE(ha)) speed = FC_PORTSPEED_10GBIT; else if (IS_QLA2031(ha)) speed = FC_PORTSPEED_16GBIT | FC_PORTSPEED_8GBIT | FC_PORTSPEED_4GBIT; else if (IS_QLA25XX(ha)) speed = FC_PORTSPEED_8GBIT | FC_PORTSPEED_4GBIT | FC_PORTSPEED_2GBIT | FC_PORTSPEED_1GBIT; else if (IS_QLA24XX_TYPE(ha)) speed = FC_PORTSPEED_4GBIT | FC_PORTSPEED_2GBIT | FC_PORTSPEED_1GBIT; else if (IS_QLA23XX(ha)) speed = FC_PORTSPEED_2GBIT | FC_PORTSPEED_1GBIT; else if (IS_QLAFX00(ha)) speed = FC_PORTSPEED_8GBIT | FC_PORTSPEED_4GBIT | FC_PORTSPEED_2GBIT | FC_PORTSPEED_1GBIT; else if (IS_QLA27XX(ha)) speed = FC_PORTSPEED_32GBIT | FC_PORTSPEED_16GBIT | FC_PORTSPEED_8GBIT; else speed = FC_PORTSPEED_1GBIT; fc_host_supported_speeds(vha->host) = speed; }
{ "language": "C" }
/* * Copyright (C) 2014 Felix Fietkau <nbd@openwrt.org> * Copyright (C) 2015 Jakub Kicinski <kubakici@wp.pl> * * 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 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> #ifndef __CHECKER__ #define CREATE_TRACE_POINTS #include "trace.h" #endif
{ "language": "C" }
name: duk_insert proto: | void duk_insert(duk_context *ctx, duk_idx_t to_idx); stack: | [ ... old(to_idx)! ... val! ] -> [ ... val(to_idx)! old! ... ] summary: | <p>Insert a value at <code>to_idx</code> with a value popped from the stack top. The previous value at <code>to_idx</code> and any values above it are moved up the stack by a step. If <code>to_idx</code> is an invalid index, throws an error.</p> <div class="note"> Negative indices are evaluated prior to popping the value at the stack top. This is also illustrated by the example. </div> example: | duk_push_int(ctx, 123); duk_push_int(ctx, 234); duk_push_int(ctx, 345); /* -> [ 123 234 345 ] */ duk_push_string(ctx, "foo"); /* -> [ 123 234 345 "foo" ] */ duk_insert(ctx, -3); /* -> [ 123 "foo" 234 345 ] */ tags: - stack seealso: - duk_pull - duk_replace introduced: 1.0.0
{ "language": "C" }
/* * 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 */ #ifndef HEADER_MDC2_H # define HEADER_MDC2_H # include <openssl/opensslconf.h> #ifndef OPENSSL_NO_MDC2 # include <stdlib.h> # include <openssl/des.h> # ifdef __cplusplus extern "C" { # endif # define MDC2_BLOCK 8 # define MDC2_DIGEST_LENGTH 16 typedef struct mdc2_ctx_st { unsigned int num; unsigned char data[MDC2_BLOCK]; DES_cblock h, hh; int pad_type; /* either 1 or 2, default 1 */ } MDC2_CTX; int MDC2_Init(MDC2_CTX *c); int MDC2_Update(MDC2_CTX *c, const unsigned char *data, size_t len); int MDC2_Final(unsigned char *md, MDC2_CTX *c); unsigned char *MDC2(const unsigned char *d, size_t n, unsigned char *md); # ifdef __cplusplus } # endif # endif #endif
{ "language": "C" }
/* * Copyright 2009 Freescale Semiconductor. * * (C) Copyright 2002 Scott McNutt <smcnutt@artesyncp.com> * * See file CREDITS for list of people who contributed to this * project. * * 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 <common.h> #include <hwconfig.h> #include <pci.h> #include <asm/processor.h> #include <asm/mmu.h> #include <asm/immap_85xx.h> #include <asm/fsl_pci.h> #include <asm/fsl_ddr_sdram.h> #include <asm/io.h> #include <spd_sdram.h> #include <i2c.h> #include <ioports.h> #include <libfdt.h> #include <fdt_support.h> #include <fsl_esdhc.h> #include "bcsr.h" #if defined(CONFIG_PQ_MDS_PIB) #include "../common/pq-mds-pib.h" #endif phys_size_t fixed_sdram(void); const qe_iop_conf_t qe_iop_conf_tab[] = { /* QE_MUX_MDC */ {2, 31, 1, 0, 1}, /* QE_MUX_MDC */ /* QE_MUX_MDIO */ {2, 30, 3, 0, 2}, /* QE_MUX_MDIO */ #if defined(CONFIG_SYS_UCC_RGMII_MODE) /* UCC_1_RGMII */ {2, 11, 2, 0, 1}, /* CLK12 */ {0, 0, 1, 0, 3}, /* ENET1_TXD0_SER1_TXD0 */ {0, 1, 1, 0, 3}, /* ENET1_TXD1_SER1_TXD1 */ {0, 2, 1, 0, 1}, /* ENET1_TXD2_SER1_TXD2 */ {0, 3, 1, 0, 2}, /* ENET1_TXD3_SER1_TXD3 */ {0, 6, 2, 0, 3}, /* ENET1_RXD0_SER1_RXD0 */ {0, 7, 2, 0, 1}, /* ENET1_RXD1_SER1_RXD1 */ {0, 8, 2, 0, 2}, /* ENET1_RXD2_SER1_RXD2 */ {0, 9, 2, 0, 2}, /* ENET1_RXD3_SER1_RXD3 */ {0, 4, 1, 0, 2}, /* ENET1_TX_EN_SER1_RTS_B */ {0, 12, 2, 0, 3}, /* ENET1_RX_DV_SER1_CTS_B */ {2, 8, 2, 0, 1}, /* ENET1_GRXCLK */ {2, 20, 1, 0, 2}, /* ENET1_GTXCLK */ /* UCC_2_RGMII */ {2, 16, 2, 0, 3}, /* CLK17 */ {0, 14, 1, 0, 2}, /* ENET2_TXD0_SER2_TXD0 */ {0, 15, 1, 0, 2}, /* ENET2_TXD1_SER2_TXD1 */ {0, 16, 1, 0, 1}, /* ENET2_TXD2_SER2_TXD2 */ {0, 17, 1, 0, 1}, /* ENET2_TXD3_SER2_TXD3 */ {0, 20, 2, 0, 2}, /* ENET2_RXD0_SER2_RXD0 */ {0, 21, 2, 0, 1}, /* ENET2_RXD1_SER2_RXD1 */ {0, 22, 2, 0, 1}, /* ENET2_RXD2_SER2_RXD2 */ {0, 23, 2, 0, 1}, /* ENET2_RXD3_SER2_RXD3 */ {0, 18, 1, 0, 2}, /* ENET2_TX_EN_SER2_RTS_B */ {0, 26, 2, 0, 3}, /* ENET2_RX_DV_SER2_CTS_B */ {2, 3, 2, 0, 1}, /* ENET2_GRXCLK */ {2, 2, 1, 0, 2}, /* ENET2_GTXCLK */ /* UCC_3_RGMII */ {2, 11, 2, 0, 1}, /* CLK12 */ {0, 29, 1, 0, 2}, /* ENET3_TXD0_SER3_TXD0 */ {0, 30, 1, 0, 3}, /* ENET3_TXD1_SER3_TXD1 */ {0, 31, 1, 0, 2}, /* ENET3_TXD2_SER3_TXD2 */ {1, 0, 1, 0, 3}, /* ENET3_TXD3_SER3_TXD3 */ {1, 3, 2, 0, 3}, /* ENET3_RXD0_SER3_RXD0 */ {1, 4, 2, 0, 1}, /* ENET3_RXD1_SER3_RXD1 */ {1, 5, 2, 0, 2}, /* ENET3_RXD2_SER3_RXD2 */ {1, 6, 2, 0, 3}, /* ENET3_RXD3_SER3_RXD3 */ {1, 1, 1, 0, 1}, /* ENET3_TX_EN_SER3_RTS_B */ {1, 9, 2, 0, 3}, /* ENET3_RX_DV_SER3_CTS_B */ {2, 9, 2, 0, 2}, /* ENET3_GRXCLK */ {2, 25, 1, 0, 2}, /* ENET3_GTXCLK */ /* UCC_4_RGMII */ {2, 16, 2, 0, 3}, /* CLK17 */ {1, 12, 1, 0, 2}, /* ENET4_TXD0_SER4_TXD0 */ {1, 13, 1, 0, 2}, /* ENET4_TXD1_SER4_TXD1 */ {1, 14, 1, 0, 1}, /* ENET4_TXD2_SER4_TXD2 */ {1, 15, 1, 0, 2}, /* ENET4_TXD3_SER4_TXD3 */ {1, 18, 2, 0, 2}, /* ENET4_RXD0_SER4_RXD0 */ {1, 19, 2, 0, 1}, /* ENET4_RXD1_SER4_RXD1 */ {1, 20, 2, 0, 1}, /* ENET4_RXD2_SER4_RXD2 */ {1, 21, 2, 0, 2}, /* ENET4_RXD3_SER4_RXD3 */ {1, 16, 1, 0, 2}, /* ENET4_TX_EN_SER4_RTS_B */ {1, 24, 2, 0, 3}, /* ENET4_RX_DV_SER4_CTS_B */ {2, 17, 2, 0, 2}, /* ENET4_GRXCLK */ {2, 24, 1, 0, 2}, /* ENET4_GTXCLK */ #elif defined(CONFIG_SYS_UCC_RMII_MODE) /* UCC_1_RMII */ {2, 15, 2, 0, 1}, /* CLK16 */ {0, 0, 1, 0, 3}, /* ENET1_TXD0_SER1_TXD0 */ {0, 1, 1, 0, 3}, /* ENET1_TXD1_SER1_TXD1 */ {0, 6, 2, 0, 3}, /* ENET1_RXD0_SER1_RXD0 */ {0, 7, 2, 0, 1}, /* ENET1_RXD1_SER1_RXD1 */ {0, 4, 1, 0, 2}, /* ENET1_TX_EN_SER1_RTS_B */ {0, 12, 2, 0, 3}, /* ENET1_RX_DV_SER1_CTS_B */ /* UCC_2_RMII */ {2, 15, 2, 0, 1}, /* CLK16 */ {0, 14, 1, 0, 2}, /* ENET2_TXD0_SER2_TXD0 */ {0, 15, 1, 0, 2}, /* ENET2_TXD1_SER2_TXD1 */ {0, 20, 2, 0, 2}, /* ENET2_RXD0_SER2_RXD0 */ {0, 21, 2, 0, 1}, /* ENET2_RXD1_SER2_RXD1 */ {0, 18, 1, 0, 2}, /* ENET2_TX_EN_SER2_RTS_B */ {0, 26, 2, 0, 3}, /* ENET2_RX_DV_SER2_CTS_B */ /* UCC_3_RMII */ {2, 15, 2, 0, 1}, /* CLK16 */ {0, 29, 1, 0, 2}, /* ENET3_TXD0_SER3_TXD0 */ {0, 30, 1, 0, 3}, /* ENET3_TXD1_SER3_TXD1 */ {1, 3, 2, 0, 3}, /* ENET3_RXD0_SER3_RXD0 */ {1, 4, 2, 0, 1}, /* ENET3_RXD1_SER3_RXD1 */ {1, 1, 1, 0, 1}, /* ENET3_TX_EN_SER3_RTS_B */ {1, 9, 2, 0, 3}, /* ENET3_RX_DV_SER3_CTS_B */ /* UCC_4_RMII */ {2, 15, 2, 0, 1}, /* CLK16 */ {1, 12, 1, 0, 2}, /* ENET4_TXD0_SER4_TXD0 */ {1, 13, 1, 0, 2}, /* ENET4_TXD1_SER4_TXD1 */ {1, 18, 2, 0, 2}, /* ENET4_RXD0_SER4_RXD0 */ {1, 19, 2, 0, 1}, /* ENET4_RXD1_SER4_RXD1 */ {1, 16, 1, 0, 2}, /* ENET4_TX_EN_SER4_RTS_B */ {1, 24, 2, 0, 3}, /* ENET4_RX_DV_SER4_CTS_B */ #endif /* UART1 is muxed with QE PortF bit [9-12].*/ {5, 12, 2, 0, 3}, /* UART1_SIN */ {5, 9, 1, 0, 3}, /* UART1_SOUT */ {5, 10, 2, 0, 3}, /* UART1_CTS_B */ {5, 11, 1, 0, 2}, /* UART1_RTS_B */ /* QE UART */ {0, 19, 1, 0, 2}, /* QEUART_TX */ {1, 17, 2, 0, 3}, /* QEUART_RX */ {0, 25, 1, 0, 1}, /* QEUART_RTS */ {1, 23, 2, 0, 1}, /* QEUART_CTS */ /* QE USB */ {5, 3, 1, 0, 1}, /* USB_OE */ {5, 4, 1, 0, 2}, /* USB_TP */ {5, 5, 1, 0, 2}, /* USB_TN */ {5, 6, 2, 0, 2}, /* USB_RP */ {5, 7, 2, 0, 1}, /* USB_RX */ {5, 8, 2, 0, 1}, /* USB_RN */ {2, 4, 2, 0, 2}, /* CLK5 */ /* SPI Flash, M25P40 */ {4, 27, 3, 0, 1}, /* SPI_MOSI */ {4, 28, 3, 0, 1}, /* SPI_MISO */ {4, 29, 3, 0, 1}, /* SPI_CLK */ {4, 30, 1, 0, 0}, /* SPI_SEL, GPIO */ {0, 0, 0, 0, QE_IOP_TAB_END} /* END of table */ }; void local_bus_init(void); int board_early_init_f (void) { /* * Initialize local bus. */ local_bus_init (); enable_8569mds_flash_write(); #ifdef CONFIG_QE enable_8569mds_qe_uec(); #endif #if CONFIG_SYS_I2C2_OFFSET /* Enable I2C2 signals instead of SD signals */ volatile struct ccsr_gur *gur; gur = (struct ccsr_gur *)(CONFIG_SYS_IMMR + 0xe0000); gur->plppar1 &= ~PLPPAR1_I2C_BIT_MASK; gur->plppar1 |= PLPPAR1_I2C2_VAL; gur->plpdir1 &= ~PLPDIR1_I2C_BIT_MASK; gur->plpdir1 |= PLPDIR1_I2C2_VAL; disable_8569mds_brd_eeprom_write_protect(); #endif return 0; } int checkboard (void) { printf ("Board: 8569 MDS\n"); return 0; } phys_size_t initdram(int board_type) { long dram_size = 0; puts("Initializing\n"); #if defined(CONFIG_DDR_DLL) /* * Work around to stabilize DDR DLL MSYNC_IN. * Errata DDR9 seems to have been fixed. * This is now the workaround for Errata DDR11: * Override DLL = 1, Course Adj = 1, Tap Select = 0 */ volatile ccsr_gur_t *gur = (void *)(CONFIG_SYS_MPC85xx_GUTS_ADDR); out_be32(&gur->ddrdllcr, 0x81000000); udelay(200); #endif #ifdef CONFIG_SPD_EEPROM dram_size = fsl_ddr_sdram(); #else dram_size = fixed_sdram(); #endif dram_size = setup_ddr_tlbs(dram_size / 0x100000); dram_size *= 0x100000; puts(" DDR: "); return dram_size; } #if !defined(CONFIG_SPD_EEPROM) phys_size_t fixed_sdram(void) { volatile ccsr_ddr_t *ddr = (ccsr_ddr_t *)CONFIG_SYS_MPC85xx_DDR_ADDR; uint d_init; out_be32(&ddr->cs0_bnds, CONFIG_SYS_DDR_CS0_BNDS); out_be32(&ddr->cs0_config, CONFIG_SYS_DDR_CS0_CONFIG); out_be32(&ddr->timing_cfg_3, CONFIG_SYS_DDR_TIMING_3); out_be32(&ddr->timing_cfg_0, CONFIG_SYS_DDR_TIMING_0); out_be32(&ddr->timing_cfg_1, CONFIG_SYS_DDR_TIMING_1); out_be32(&ddr->timing_cfg_2, CONFIG_SYS_DDR_TIMING_2); out_be32(&ddr->sdram_cfg, CONFIG_SYS_DDR_SDRAM_CFG); out_be32(&ddr->sdram_cfg_2, CONFIG_SYS_DDR_SDRAM_CFG_2); out_be32(&ddr->sdram_mode, CONFIG_SYS_DDR_SDRAM_MODE); out_be32(&ddr->sdram_mode_2, CONFIG_SYS_DDR_SDRAM_MODE_2); out_be32(&ddr->sdram_interval, CONFIG_SYS_DDR_SDRAM_INTERVAL); out_be32(&ddr->sdram_data_init, CONFIG_SYS_DDR_DATA_INIT); out_be32(&ddr->sdram_clk_cntl, CONFIG_SYS_DDR_SDRAM_CLK_CNTL); out_be32(&ddr->timing_cfg_4, CONFIG_SYS_DDR_TIMING_4); out_be32(&ddr->timing_cfg_5, CONFIG_SYS_DDR_TIMING_5); out_be32(&ddr->ddr_zq_cntl, CONFIG_SYS_DDR_ZQ_CNTL); out_be32(&ddr->ddr_wrlvl_cntl, CONFIG_SYS_DDR_WRLVL_CNTL); out_be32(&ddr->sdram_cfg_2, CONFIG_SYS_DDR_SDRAM_CFG_2); #if defined (CONFIG_DDR_ECC) out_be32(&ddr->err_int_en, CONFIG_SYS_DDR_ERR_INT_EN); out_be32(&ddr->err_disable, CONFIG_SYS_DDR_ERR_DIS); out_be32(&ddr->err_sbe, CONFIG_SYS_DDR_SBE); #endif udelay(500); out_be32(&ddr->sdram_cfg, CONFIG_SYS_DDR_CONTROL); #if defined(CONFIG_ECC_INIT_VIA_DDRCONTROLLER) d_init = 1; debug("DDR - 1st controller: memory initializing\n"); /* * Poll until memory is initialized. * 512 Meg at 400 might hit this 200 times or so. */ while ((ddr->sdram_cfg_2 & (d_init << 4)) != 0) { udelay(1000); } debug("DDR: memory initialized\n\n"); udelay(500); #endif return CONFIG_SYS_SDRAM_SIZE * 1024 * 1024; } #endif /* * Initialize Local Bus */ void local_bus_init(void) { volatile ccsr_gur_t *gur = (void *)(CONFIG_SYS_MPC85xx_GUTS_ADDR); volatile ccsr_lbc_t *lbc = (void *)(CONFIG_SYS_MPC85xx_LBC_ADDR); uint clkdiv; uint lbc_hz; sys_info_t sysinfo; get_sys_info(&sysinfo); clkdiv = (lbc->lcrr & LCRR_CLKDIV) * 2; lbc_hz = sysinfo.freqSystemBus / 1000000 / clkdiv; out_be32(&gur->lbiuiplldcr1, 0x00078080); if (clkdiv == 16) out_be32(&gur->lbiuiplldcr0, 0x7c0f1bf0); else if (clkdiv == 8) out_be32(&gur->lbiuiplldcr0, 0x6c0f1bf0); else if (clkdiv == 4) out_be32(&gur->lbiuiplldcr0, 0x5c0f1bf0); out_be32(&lbc->lcrr, (u32)in_be32(&lbc->lcrr)| 0x00030000); } static void fdt_board_disable_serial(void *blob, bd_t *bd, const char *alias) { const char *status = "disabled"; int off; int err; off = fdt_path_offset(blob, alias); if (off < 0) { printf("WARNING: could not find %s alias: %s.\n", alias, fdt_strerror(off)); return; } err = fdt_setprop(blob, off, "status", status, strlen(status) + 1); if (err) { printf("WARNING: could not set status for serial0: %s.\n", fdt_strerror(err)); return; } } /* * Because of an erratum in prototype boards it is impossible to use eSDHC * without disabling UART0 (which makes it quite easy to 'brick' the board * by simply issung 'setenv hwconfig esdhc', and not able to interact with * U-Boot anylonger). * * So, but default we assume that the board is a prototype, which is a most * safe assumption. There is no way to determine board revision from a * register, so we use hwconfig. */ static int prototype_board(void) { if (hwconfig_subarg("board", "rev", NULL)) return hwconfig_subarg_cmp("board", "rev", "prototype"); return 1; } static int esdhc_disables_uart0(void) { return prototype_board() || hwconfig_subarg_cmp("esdhc", "mode", "4-bits"); } static void fdt_board_fixup_qe_uart(void *blob, bd_t *bd) { u8 *bcsr = (u8 *)CONFIG_SYS_BCSR_BASE; const char *devtype = "serial"; const char *compat = "ucc_uart"; const char *clk = "brg9"; u32 portnum = 0; int off = -1; if (!hwconfig("qe_uart")) return; if (hwconfig("esdhc") && esdhc_disables_uart0()) { printf("QE UART: won't enable with esdhc.\n"); return; } fdt_board_disable_serial(blob, bd, "serial1"); while (1) { const u32 *idx; int len; off = fdt_node_offset_by_compatible(blob, off, "ucc_geth"); if (off < 0) { printf("WARNING: unable to fixup device tree for " "QE UART\n"); return; } idx = fdt_getprop(blob, off, "cell-index", &len); if (!idx || len != sizeof(*idx) || *idx != fdt32_to_cpu(2)) continue; break; } fdt_setprop(blob, off, "device_type", devtype, strlen(devtype) + 1); fdt_setprop(blob, off, "compatible", compat, strlen(compat) + 1); fdt_setprop(blob, off, "tx-clock-name", clk, strlen(clk) + 1); fdt_setprop(blob, off, "rx-clock-name", clk, strlen(clk) + 1); fdt_setprop(blob, off, "port-number", &portnum, sizeof(portnum)); setbits_8(&bcsr[15], BCSR15_QEUART_EN); } #ifdef CONFIG_FSL_ESDHC int board_mmc_init(bd_t *bd) { struct ccsr_gur *gur = (struct ccsr_gur *)CONFIG_SYS_MPC85xx_GUTS_ADDR; u8 *bcsr = (u8 *)CONFIG_SYS_BCSR_BASE; u8 bcsr6 = BCSR6_SD_CARD_1BIT; if (!hwconfig("esdhc")) return 0; printf("Enabling eSDHC...\n" " For eSDHC to function, I2C2 "); if (esdhc_disables_uart0()) { printf("and UART0 should be disabled.\n"); printf(" Redirecting stderr, stdout and stdin to UART1...\n"); console_assign(stderr, "eserial1"); console_assign(stdout, "eserial1"); console_assign(stdin, "eserial1"); printf("Switched to UART1 (initial log has been printed to " "UART0).\n"); clrsetbits_be32(&gur->plppar1, PLPPAR1_UART0_BIT_MASK, PLPPAR1_ESDHC_4BITS_VAL); clrsetbits_be32(&gur->plpdir1, PLPDIR1_UART0_BIT_MASK, PLPDIR1_ESDHC_4BITS_VAL); bcsr6 |= BCSR6_SD_CARD_4BITS; } else { printf("should be disabled.\n"); } /* Assign I2C2 signals to eSDHC. */ clrsetbits_be32(&gur->plppar1, PLPPAR1_I2C_BIT_MASK, PLPPAR1_ESDHC_VAL); clrsetbits_be32(&gur->plpdir1, PLPDIR1_I2C_BIT_MASK, PLPDIR1_ESDHC_VAL); /* Mux I2C2 (and optionally UART0) signals to eSDHC. */ setbits_8(&bcsr[6], bcsr6); return fsl_esdhc_mmc_init(bd); } static void fdt_board_fixup_esdhc(void *blob, bd_t *bd) { const char *status = "disabled"; int off = -1; if (!hwconfig("esdhc")) return; if (esdhc_disables_uart0()) fdt_board_disable_serial(blob, bd, "serial0"); while (1) { const u32 *idx; int len; off = fdt_node_offset_by_compatible(blob, off, "fsl-i2c"); if (off < 0) break; idx = fdt_getprop(blob, off, "cell-index", &len); if (!idx || len != sizeof(*idx)) continue; if (*idx == 1) { fdt_setprop(blob, off, "status", status, strlen(status) + 1); break; } } if (hwconfig_subarg_cmp("esdhc", "mode", "4-bits")) { off = fdt_node_offset_by_compatible(blob, -1, "fsl,esdhc"); if (off < 0) { printf("WARNING: could not find esdhc node\n"); return; } fdt_delprop(blob, off, "sdhci,1-bit-only"); } } #else static inline void fdt_board_fixup_esdhc(void *blob, bd_t *bd) {} #endif static void fdt_board_fixup_qe_usb(void *blob, bd_t *bd) { u8 *bcsr = (u8 *)CONFIG_SYS_BCSR_BASE; if (hwconfig_subarg_cmp("qe_usb", "speed", "low")) clrbits_8(&bcsr[17], BCSR17_nUSBLOWSPD); else setbits_8(&bcsr[17], BCSR17_nUSBLOWSPD); if (hwconfig_subarg_cmp("qe_usb", "mode", "peripheral")) { clrbits_8(&bcsr[17], BCSR17_USBVCC); clrbits_8(&bcsr[17], BCSR17_USBMODE); do_fixup_by_compat(blob, "fsl,mpc8569-qe-usb", "mode", "peripheral", sizeof("peripheral"), 1); } else { setbits_8(&bcsr[17], BCSR17_USBVCC); setbits_8(&bcsr[17], BCSR17_USBMODE); } clrbits_8(&bcsr[17], BCSR17_nUSBEN); } #ifdef CONFIG_PCIE1 static struct pci_controller pcie1_hose; #endif /* CONFIG_PCIE1 */ #ifdef CONFIG_PCI void pci_init_board(void) { volatile ccsr_gur_t *gur = (void *)(CONFIG_SYS_MPC85xx_GUTS_ADDR); struct fsl_pci_info pci_info[1]; u32 devdisr, pordevsr, io_sel; int first_free_busno = 0; int num = 0; int pcie_ep, pcie_configured; devdisr = in_be32(&gur->devdisr); pordevsr = in_be32(&gur->pordevsr); io_sel = (pordevsr & MPC85xx_PORDEVSR_IO_SEL) >> 19; debug (" pci_init_board: devdisr=%x, io_sel=%x\n", devdisr, io_sel); #if defined(CONFIG_PQ_MDS_PIB) pib_init(); #endif #ifdef CONFIG_PCIE1 pcie_configured = is_fsl_pci_cfg(LAW_TRGT_IF_PCIE_1, io_sel); if (pcie_configured && !(devdisr & MPC85xx_DEVDISR_PCIE)){ SET_STD_PCIE_INFO(pci_info[num], 1); pcie_ep = fsl_setup_hose(&pcie1_hose, pci_info[num].regs); printf (" PCIE1 connected to Slot as %s (base addr %lx)\n", pcie_ep ? "Endpoint" : "Root Complex", pci_info[num].regs); first_free_busno = fsl_pci_init_port(&pci_info[num++], &pcie1_hose, first_free_busno); } else { printf (" PCIE1: disabled\n"); } puts("\n"); #else setbits_be32(&gur->devdisr, MPC85xx_DEVDISR_PCIE); /* disable */ #endif } #endif /* CONFIG_PCI */ #if defined(CONFIG_OF_BOARD_SETUP) void ft_board_setup(void *blob, bd_t *bd) { #if defined(CONFIG_SYS_UCC_RMII_MODE) int nodeoff, off, err; unsigned int val; const u32 *ph; const u32 *index; /* fixup device tree for supporting rmii mode */ nodeoff = -1; while ((nodeoff = fdt_node_offset_by_compatible(blob, nodeoff, "ucc_geth")) >= 0) { err = fdt_setprop_string(blob, nodeoff, "tx-clock-name", "clk16"); if (err < 0) { printf("WARNING: could not set tx-clock-name %s.\n", fdt_strerror(err)); break; } err = fdt_setprop_string(blob, nodeoff, "phy-connection-type", "rmii"); if (err < 0) { printf("WARNING: could not set phy-connection-type " "%s.\n", fdt_strerror(err)); break; } index = fdt_getprop(blob, nodeoff, "cell-index", 0); if (index == NULL) { printf("WARNING: could not get cell-index of ucc\n"); break; } ph = fdt_getprop(blob, nodeoff, "phy-handle", 0); if (ph == NULL) { printf("WARNING: could not get phy-handle of ucc\n"); break; } off = fdt_node_offset_by_phandle(blob, *ph); if (off < 0) { printf("WARNING: could not get phy node %s.\n", fdt_strerror(err)); break; } val = 0x7 + *index; /* RMII phy address starts from 0x8 */ err = fdt_setprop(blob, off, "reg", &val, sizeof(u32)); if (err < 0) { printf("WARNING: could not set reg for phy-handle " "%s.\n", fdt_strerror(err)); break; } } #endif ft_cpu_setup(blob, bd); #ifdef CONFIG_PCIE1 ft_fsl_pci_setup(blob, "pci1", &pcie1_hose); #endif fdt_board_fixup_esdhc(blob, bd); fdt_board_fixup_qe_uart(blob, bd); fdt_board_fixup_qe_usb(blob, bd); } #endif
{ "language": "C" }
/* Copyright (C) 2014, The University of Texas at Austin This file is part of libflame and is available under the 3-Clause BSD license, which can be found in the LICENSE file at the top-level directory, or at http://opensource.org/licenses/BSD-3-Clause */ #include "FLAME.h" #define FLA_ALG_REFERENCE 0 #define FLA_ALG_FRONT 1 FLA_Error REF_Her2k( FLA_Uplo uplo, FLA_Trans trans, FLA_Obj alpha, FLA_Obj A, FLA_Obj B, FLA_Obj beta, FLA_Obj C ); void time_Her2k( int param_combo, int type, int nrepeats, int m, int k, FLA_Obj A, FLA_Obj B, FLA_Obj C, FLA_Obj C_ref, double *dtime, double *diff, double *gflops ); void time_Her2k( int param_combo, int type, int nrepeats, int m, int k, FLA_Obj A, FLA_Obj B, FLA_Obj C, FLA_Obj C_ref, double *dtime, double *diff, double *gflops ) { int irep; double dtime_old = 1.0e9; FLA_Obj C_old, A_flat, B_flat, C_flat; FLASH_Obj_create_conf_to( FLA_NO_TRANSPOSE, C, &C_old ); FLASH_Obj_create_flat_conf_to_hier( FLA_NO_TRANSPOSE, A, &A_flat ); FLASH_Obj_create_flat_conf_to_hier( FLA_NO_TRANSPOSE, B, &B_flat ); FLASH_Obj_create_flat_conf_to_hier( FLA_NO_TRANSPOSE, C, &C_flat ); FLASH_Copy( C, C_old ); for ( irep = 0 ; irep < nrepeats; irep++ ) { FLASH_Copy( C_old, C ); FLASH_Obj_flatten( A, A_flat ); FLASH_Obj_flatten( B, B_flat ); FLASH_Obj_flatten( C, C_flat ); *dtime = FLA_Clock(); switch( param_combo ){ // Time parameter combination 0 case 0:{ switch( type ){ case FLA_ALG_REFERENCE: REF_Her2k( FLA_LOWER_TRIANGULAR, FLA_CONJ_TRANSPOSE, FLA_ONE, A_flat, B_flat, FLA_ZERO, C_flat ); break; case FLA_ALG_FRONT: FLASH_Her2k( FLA_LOWER_TRIANGULAR, FLA_CONJ_TRANSPOSE, FLA_ONE, A, B, FLA_ZERO, C ); break; default: printf("trouble\n"); } break; } // Time parameter combination 1 case 1:{ switch( type ){ case FLA_ALG_REFERENCE: REF_Her2k( FLA_LOWER_TRIANGULAR, FLA_NO_TRANSPOSE, FLA_ONE, A_flat, B_flat, FLA_ZERO, C_flat ); break; case FLA_ALG_FRONT: FLASH_Her2k( FLA_LOWER_TRIANGULAR, FLA_NO_TRANSPOSE, FLA_ONE, A, B, FLA_ZERO, C ); break; default: printf("trouble\n"); } break; } // Time parameter combination 2 case 2:{ switch( type ){ case FLA_ALG_REFERENCE: REF_Her2k( FLA_UPPER_TRIANGULAR, FLA_CONJ_TRANSPOSE, FLA_ONE, A_flat, B_flat, FLA_ZERO, C_flat ); break; case FLA_ALG_FRONT: FLASH_Her2k( FLA_UPPER_TRIANGULAR, FLA_CONJ_TRANSPOSE, FLA_ONE, A, B, FLA_ZERO, C ); break; default: printf("trouble\n"); } break; } // Time parameter combination 3 case 3:{ switch( type ){ case FLA_ALG_REFERENCE: REF_Her2k( FLA_UPPER_TRIANGULAR, FLA_NO_TRANSPOSE, FLA_ONE, A_flat, B_flat, FLA_ZERO, C_flat ); break; case FLA_ALG_FRONT: FLASH_Her2k( FLA_UPPER_TRIANGULAR, FLA_NO_TRANSPOSE, FLA_ONE, A, B, FLA_ZERO, C ); break; default: printf("trouble\n"); } break; } } *dtime = FLA_Clock() - *dtime; dtime_old = min( *dtime, dtime_old ); } if ( type == FLA_ALG_REFERENCE ) { FLASH_Obj_hierarchify( C_flat, C_ref ); *diff = 0.0; } else { *diff = FLASH_Max_elemwise_diff( C, C_ref ); } *gflops = 4.0 * 2.0 * m * m * k / dtime_old / 1.0e9; *dtime = dtime_old; FLASH_Copy( C_old, C ); FLASH_Obj_free( &C_old ); FLASH_Obj_free( &A_flat ); FLASH_Obj_free( &B_flat ); FLASH_Obj_free( &C_flat ); }
{ "language": "C" }
/** * $Id$ * Copyright (C) 2008 - 2014 Nils Asmussen * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #pragma once #include <sys/common.h> #if defined(__cplusplus) extern "C" { #endif enum { CT_NUMERIC = 1, CT_LOWER = 2, CT_UPPER = 4, CT_SPACE = 8, CT_HEX = 16, CT_PUNCT = 32, CT_CTRL = 64, CT_BLANK = 128, }; /** * @param c the character * @return non-zero if its argument is a numeric digit or a letter of the alphabet. * Otherwise, zero is returned. */ int isalnum(int c); /** * @param c the character * @return non-zero if its argument is a letter of the alphabet. Otherwise, zero is returned. */ int isalpha(int c); /** * @param c the character * @return non-zero if its argument is ' ' or '\t'. Otherwise, zero is returned. */ int isblank(int c); /** * @param c the character * @return non-zero if its argument is a control-character ( < 0x20 ) */ int iscntrl(int c); /** * @param c the character * @return non-zero if its argument is a digit between 0 and 9. Otherwise, zero is returned. */ int isdigit(int c); /** * @param c the character * @return non-zero if its argument has a graphical representation. Otherwise, zero is returned. */ int isgraph(int c); /** * @param c the character * @return non-zero if its argument is a lowercase letter. Otherwise, zero is returned. */ int islower(int c); /** * @param c the character * @return non-zero if its argument is a printable character */ int isprint(int c); /** * @param c the character * @return non-zero if its argument is a punctuation character */ int ispunct(int c); /** * @param c the character * @return non-zero if its argument is some sort of space (i.e. single space, tab, * vertical tab, form feed, carriage return, or newline). Otherwise, zero is returned. */ int isspace(int c); /** * @param c the character * @return non-zero if its argument is an uppercase letter. Otherwise, zero is returned. */ int isupper(int c); /** * * @param c the character * @return non-zero if its argument is a hexadecimal digit */ int isxdigit(int c); /** * @param ch the char * @return the lowercase version of the character ch. */ int tolower(int ch); /** * @param ch the char * @return the uppercase version of the character ch. */ int toupper(int ch); #if defined(__cplusplus) } #endif
{ "language": "C" }
/* gspawn.c - Process launching * * Copyright 2000 Red Hat, Inc. * g_execvpe implementation based on GNU libc execvp: * Copyright 1991, 92, 95, 96, 97, 98, 99 Free Software Foundation, Inc. * * GLib 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 * License, or (at your option) any later version. * * GLib 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 GLib; see the file COPYING.LIB. If not, write * to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "config.h" #include <time.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <signal.h> #include <string.h> #include <stdlib.h> /* for fdwalk */ #include <dirent.h> #ifdef HAVE_SYS_SELECT_H #include <sys/select.h> #endif /* HAVE_SYS_SELECT_H */ #ifdef HAVE_SYS_RESOURCE_H #include <sys/resource.h> #endif /* HAVE_SYS_RESOURCE_H */ #include "gspawn.h" #include "gmem.h" #include "gshell.h" #include "gstring.h" #include "gstrfuncs.h" #include "gtestutils.h" #include "gutils.h" #include "glibintl.h" static gint g_execute (const gchar *file, gchar **argv, gchar **envp, gboolean search_path); static gboolean make_pipe (gint p[2], GError **error); static gboolean fork_exec_with_pipes (gboolean intermediate_child, const gchar *working_directory, gchar **argv, gchar **envp, gboolean close_descriptors, gboolean search_path, gboolean stdout_to_null, gboolean stderr_to_null, gboolean child_inherits_stdin, gboolean file_and_argv_zero, GSpawnChildSetupFunc child_setup, gpointer user_data, GPid *child_pid, gint *standard_input, gint *standard_output, gint *standard_error, GError **error); GQuark g_spawn_error_quark (void) { return g_quark_from_static_string ("g-exec-error-quark"); } /** * g_spawn_async: * @working_directory: child's current working directory, or %NULL to inherit parent's * @argv: child's argument vector * @envp: child's environment, or %NULL to inherit parent's * @flags: flags from #GSpawnFlags * @child_setup: function to run in the child just before exec() * @user_data: user data for @child_setup * @child_pid: return location for child process reference, or %NULL * @error: return location for error * * See g_spawn_async_with_pipes() for a full description; this function * simply calls the g_spawn_async_with_pipes() without any pipes. * * You should call g_spawn_close_pid() on the returned child process * reference when you don't need it any more. * * <note><para> * If you are writing a GTK+ application, and the program you * are spawning is a graphical application, too, then you may * want to use gdk_spawn_on_screen() instead to ensure that * the spawned program opens its windows on the right screen. * </para></note> * * <note><para> Note that the returned @child_pid on Windows is a * handle to the child process and not its identifier. Process handles * and process identifiers are different concepts on Windows. * </para></note> * * Return value: %TRUE on success, %FALSE if error is set **/ gboolean g_spawn_async (const gchar *working_directory, gchar **argv, gchar **envp, GSpawnFlags flags, GSpawnChildSetupFunc child_setup, gpointer user_data, GPid *child_pid, GError **error) { g_return_val_if_fail (argv != NULL, FALSE); return g_spawn_async_with_pipes (working_directory, argv, envp, flags, child_setup, user_data, child_pid, NULL, NULL, NULL, error); } /* Avoids a danger in threaded situations (calling close() * on a file descriptor twice, and another thread has * re-opened it since the first close) */ static gint close_and_invalidate (gint *fd) { gint ret; if (*fd < 0) return -1; else { ret = close (*fd); *fd = -1; } return ret; } /* Some versions of OS X define READ_OK in public headers */ #undef READ_OK typedef enum { READ_FAILED = 0, /* FALSE */ READ_OK, READ_EOF } ReadResult; static ReadResult read_data (GString *str, gint fd, GError **error) { gssize bytes; gchar buf[4096]; again: bytes = read (fd, buf, 4096); if (bytes == 0) return READ_EOF; else if (bytes > 0) { g_string_append_len (str, buf, bytes); return READ_OK; } else if (bytes < 0 && errno == EINTR) goto again; else if (bytes < 0) { int errsv = errno; g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_READ, _("Failed to read data from child process (%s)"), g_strerror (errsv)); return READ_FAILED; } else return READ_OK; } /** * g_spawn_sync: * @working_directory: child's current working directory, or %NULL to inherit parent's * @argv: child's argument vector * @envp: child's environment, or %NULL to inherit parent's * @flags: flags from #GSpawnFlags * @child_setup: function to run in the child just before exec() * @user_data: user data for @child_setup * @standard_output: return location for child output, or %NULL * @standard_error: return location for child error messages, or %NULL * @exit_status: return location for child exit status, as returned by waitpid(), or %NULL * @error: return location for error, or %NULL * * Executes a child synchronously (waits for the child to exit before returning). * All output from the child is stored in @standard_output and @standard_error, * if those parameters are non-%NULL. Note that you must set the * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when * passing %NULL for @standard_output and @standard_error. * If @exit_status is non-%NULL, the exit status of the child is stored * there as it would be returned by waitpid(); standard UNIX macros such * as WIFEXITED() and WEXITSTATUS() must be used to evaluate the exit status. * Note that this function call waitpid() even if @exit_status is %NULL, and * does not accept the %G_SPAWN_DO_NOT_REAP_CHILD flag. * If an error occurs, no data is returned in @standard_output, * @standard_error, or @exit_status. * * This function calls g_spawn_async_with_pipes() internally; see that * function for full details on the other parameters and details on * how these functions work on Windows. * * Return value: %TRUE on success, %FALSE if an error was set. **/ gboolean g_spawn_sync (const gchar *working_directory, gchar **argv, gchar **envp, GSpawnFlags flags, GSpawnChildSetupFunc child_setup, gpointer user_data, gchar **standard_output, gchar **standard_error, gint *exit_status, GError **error) { gint outpipe = -1; gint errpipe = -1; GPid pid; fd_set fds; gint ret; GString *outstr = NULL; GString *errstr = NULL; gboolean failed; gint status; g_return_val_if_fail (argv != NULL, FALSE); g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE); g_return_val_if_fail (standard_output == NULL || !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE); g_return_val_if_fail (standard_error == NULL || !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE); /* Just to ensure segfaults if callers try to use * these when an error is reported. */ if (standard_output) *standard_output = NULL; if (standard_error) *standard_error = NULL; if (!fork_exec_with_pipes (FALSE, working_directory, argv, envp, !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN), (flags & G_SPAWN_SEARCH_PATH) != 0, (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0, (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0, (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0, (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0, child_setup, user_data, &pid, NULL, standard_output ? &outpipe : NULL, standard_error ? &errpipe : NULL, error)) return FALSE; /* Read data from child. */ failed = FALSE; if (outpipe >= 0) { outstr = g_string_new (NULL); } if (errpipe >= 0) { errstr = g_string_new (NULL); } /* Read data until we get EOF on both pipes. */ while (!failed && (outpipe >= 0 || errpipe >= 0)) { ret = 0; FD_ZERO (&fds); if (outpipe >= 0) FD_SET (outpipe, &fds); if (errpipe >= 0) FD_SET (errpipe, &fds); ret = select (MAX (outpipe, errpipe) + 1, &fds, NULL, NULL, NULL /* no timeout */); if (ret < 0 && errno != EINTR) { int errsv = errno; failed = TRUE; g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_READ, _("Unexpected error in select() reading data from a child process (%s)"), g_strerror (errsv)); break; } if (outpipe >= 0 && FD_ISSET (outpipe, &fds)) { switch (read_data (outstr, outpipe, error)) { case READ_FAILED: failed = TRUE; break; case READ_EOF: close_and_invalidate (&outpipe); outpipe = -1; break; default: break; } if (failed) break; } if (errpipe >= 0 && FD_ISSET (errpipe, &fds)) { switch (read_data (errstr, errpipe, error)) { case READ_FAILED: failed = TRUE; break; case READ_EOF: close_and_invalidate (&errpipe); errpipe = -1; break; default: break; } if (failed) break; } } /* These should only be open still if we had an error. */ if (outpipe >= 0) close_and_invalidate (&outpipe); if (errpipe >= 0) close_and_invalidate (&errpipe); /* Wait for child to exit, even if we have * an error pending. */ again: ret = waitpid (pid, &status, 0); if (ret < 0) { if (errno == EINTR) goto again; else if (errno == ECHILD) { if (exit_status) { g_warning ("In call to g_spawn_sync(), exit status of a child process was requested but SIGCHLD action was set to SIG_IGN and ECHILD was received by waitpid(), so exit status can't be returned. This is a bug in the program calling g_spawn_sync(); either don't request the exit status, or don't set the SIGCHLD action."); } else { /* We don't need the exit status. */ } } else { if (!failed) /* avoid error pileups */ { int errsv = errno; failed = TRUE; g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_READ, _("Unexpected error in waitpid() (%s)"), g_strerror (errsv)); } } } if (failed) { if (outstr) g_string_free (outstr, TRUE); if (errstr) g_string_free (errstr, TRUE); return FALSE; } else { if (exit_status) *exit_status = status; if (standard_output) *standard_output = g_string_free (outstr, FALSE); if (standard_error) *standard_error = g_string_free (errstr, FALSE); return TRUE; } } /** * g_spawn_async_with_pipes: * @working_directory: child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding * @argv: child's argument vector, in the GLib file name encoding * @envp: child's environment, or %NULL to inherit parent's, in the GLib file name encoding * @flags: flags from #GSpawnFlags * @child_setup: function to run in the child just before exec() * @user_data: user data for @child_setup * @child_pid: return location for child process ID, or %NULL * @standard_input: return location for file descriptor to write to child's stdin, or %NULL * @standard_output: return location for file descriptor to read child's stdout, or %NULL * @standard_error: return location for file descriptor to read child's stderr, or %NULL * @error: return location for error * * Executes a child program asynchronously (your program will not * block waiting for the child to exit). The child program is * specified by the only argument that must be provided, @argv. @argv * should be a %NULL-terminated array of strings, to be passed as the * argument vector for the child. The first string in @argv is of * course the name of the program to execute. By default, the name of * the program must be a full path; the <envar>PATH</envar> shell variable * will only be searched if you pass the %G_SPAWN_SEARCH_PATH flag. * * On Windows, note that all the string or string vector arguments to * this function and the other g_spawn*() functions are in UTF-8, the * GLib file name encoding. Unicode characters that are not part of * the system codepage passed in these arguments will be correctly * available in the spawned program only if it uses wide character API * to retrieve its command line. For C programs built with Microsoft's * tools it is enough to make the program have a wmain() instead of * main(). wmain() has a wide character argument vector as parameter. * * At least currently, mingw doesn't support wmain(), so if you use * mingw to develop the spawned program, it will have to call the * undocumented function __wgetmainargs() to get the wide character * argument vector and environment. See gspawn-win32-helper.c in the * GLib sources or init.c in the mingw runtime sources for a prototype * for that function. Alternatively, you can retrieve the Win32 system * level wide character command line passed to the spawned program * using the GetCommandLineW() function. * * On Windows the low-level child process creation API * <function>CreateProcess()</function> doesn't use argument vectors, * but a command line. The C runtime library's * <function>spawn*()</function> family of functions (which * g_spawn_async_with_pipes() eventually calls) paste the argument * vector elements together into a command line, and the C runtime startup code * does a corresponding reconstruction of an argument vector from the * command line, to be passed to main(). Complications arise when you have * argument vector elements that contain spaces of double quotes. The * <function>spawn*()</function> functions don't do any quoting or * escaping, but on the other hand the startup code does do unquoting * and unescaping in order to enable receiving arguments with embedded * spaces or double quotes. To work around this asymmetry, * g_spawn_async_with_pipes() will do quoting and escaping on argument * vector elements that need it before calling the C runtime * spawn() function. * * The returned @child_pid on Windows is a handle to the child * process, not its identifier. Process handles and process * identifiers are different concepts on Windows. * * @envp is a %NULL-terminated array of strings, where each string * has the form <literal>KEY=VALUE</literal>. This will become * the child's environment. If @envp is %NULL, the child inherits its * parent's environment. * * @flags should be the bitwise OR of any flags you want to affect the * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that * the child will not automatically be reaped; you must use a * #GChildWatch source to be notified about the death of the child * process. Eventually you must call g_spawn_close_pid() on the * @child_pid, in order to free resources which may be associated * with the child process. (On Unix, using a #GChildWatch source is * equivalent to calling waitpid() or handling the %SIGCHLD signal * manually. On Windows, calling g_spawn_close_pid() is equivalent * to calling CloseHandle() on the process handle returned in * @child_pid). * * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file * descriptors will be inherited by the child; otherwise all * descriptors except stdin/stdout/stderr will be closed before * calling exec() in the child. %G_SPAWN_SEARCH_PATH * means that <literal>argv[0]</literal> need not be an absolute path, it * will be looked for in the user's <envar>PATH</envar>. * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will * be discarded, instead of going to the same location as the parent's * standard output. If you use this flag, @standard_output must be %NULL. * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error * will be discarded, instead of going to the same location as the parent's * standard error. If you use this flag, @standard_error must be %NULL. * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's * standard input (by default, the child's standard input is attached to * /dev/null). If you use this flag, @standard_input must be %NULL. * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is * the file to execute, while the remaining elements are the * actual argument vector to pass to the file. Normally * g_spawn_async_with_pipes() uses @argv[0] as the file to execute, and * passes all of @argv to the child. * * @child_setup and @user_data are a function and user data. On POSIX * platforms, the function is called in the child after GLib has * performed all the setup it plans to perform (including creating * pipes, closing file descriptors, etc.) but before calling * exec(). That is, @child_setup is called just * before calling exec() in the child. Obviously * actions taken in this function will only affect the child, not the * parent. * * On Windows, there is no separate fork() and exec() * functionality. Child processes are created and run with a single * API call, CreateProcess(). There is no sensible thing @child_setup * could be used for on Windows so it is ignored and not called. * * If non-%NULL, @child_pid will on Unix be filled with the child's * process ID. You can use the process ID to send signals to the * child, or to use g_child_watch_add() (or waitpid()) if you specified the * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be * filled with a handle to the child process only if you specified the * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child * process using the Win32 API, for example wait for its termination * with the <function>WaitFor*()</function> functions, or examine its * exit code with GetExitCodeProcess(). You should close the handle * with CloseHandle() or g_spawn_close_pid() when you no longer need it. * * If non-%NULL, the @standard_input, @standard_output, @standard_error * locations will be filled with file descriptors for writing to the child's * standard input or reading from its standard output or standard error. * The caller of g_spawn_async_with_pipes() must close these file descriptors * when they are no longer in use. If these parameters are %NULL, the corresponding * pipe won't be created. * * If @standard_input is NULL, the child's standard input is attached to * /dev/null unless %G_SPAWN_CHILD_INHERITS_STDIN is set. * * If @standard_error is NULL, the child's standard error goes to the same * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL * is set. * * If @standard_output is NULL, the child's standard output goes to the same * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL * is set. * * @error can be %NULL to ignore errors, or non-%NULL to report errors. * If an error is set, the function returns %FALSE. Errors * are reported even if they occur in the child (for example if the * executable in <literal>argv[0]</literal> is not found). Typically * the <literal>message</literal> field of returned errors should be displayed * to users. Possible errors are those from the #G_SPAWN_ERROR domain. * * If an error occurs, @child_pid, @standard_input, @standard_output, * and @standard_error will not be filled with valid values. * * If @child_pid is not %NULL and an error does not occur then the returned * process reference must be closed using g_spawn_close_pid(). * * <note><para> * If you are writing a GTK+ application, and the program you * are spawning is a graphical application, too, then you may * want to use gdk_spawn_on_screen_with_pipes() instead to ensure that * the spawned program opens its windows on the right screen. * </para></note> * * Return value: %TRUE on success, %FALSE if an error was set **/ gboolean g_spawn_async_with_pipes (const gchar *working_directory, gchar **argv, gchar **envp, GSpawnFlags flags, GSpawnChildSetupFunc child_setup, gpointer user_data, GPid *child_pid, gint *standard_input, gint *standard_output, gint *standard_error, GError **error) { g_return_val_if_fail (argv != NULL, FALSE); g_return_val_if_fail (standard_output == NULL || !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE); g_return_val_if_fail (standard_error == NULL || !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE); /* can't inherit stdin if we have an input pipe. */ g_return_val_if_fail (standard_input == NULL || !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE); return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), working_directory, argv, envp, !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN), (flags & G_SPAWN_SEARCH_PATH) != 0, (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0, (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0, (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0, (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0, child_setup, user_data, child_pid, standard_input, standard_output, standard_error, error); } /** * g_spawn_command_line_sync: * @command_line: a command line * @standard_output: return location for child output * @standard_error: return location for child errors * @exit_status: return location for child exit status, as returned by waitpid() * @error: return location for errors * * A simple version of g_spawn_sync() with little-used parameters * removed, taking a command line instead of an argument vector. See * g_spawn_sync() for full details. @command_line will be parsed by * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security * implications, so consider using g_spawn_sync() directly if * appropriate. Possible errors are those from g_spawn_sync() and those * from g_shell_parse_argv(). * * If @exit_status is non-%NULL, the exit status of the child is stored there as * it would be returned by waitpid(); standard UNIX macros such as WIFEXITED() * and WEXITSTATUS() must be used to evaluate the exit status. * * On Windows, please note the implications of g_shell_parse_argv() * parsing @command_line. Parsing is done according to Unix shell rules, not * Windows command interpreter rules. * Space is a separator, and backslashes are * special. Thus you cannot simply pass a @command_line containing * canonical Windows paths, like "c:\\program files\\app\\app.exe", as * the backslashes will be eaten, and the space will act as a * separator. You need to enclose such paths with single quotes, like * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'". * * Return value: %TRUE on success, %FALSE if an error was set **/ gboolean g_spawn_command_line_sync (const gchar *command_line, gchar **standard_output, gchar **standard_error, gint *exit_status, GError **error) { gboolean retval; gchar **argv = NULL; g_return_val_if_fail (command_line != NULL, FALSE); if (!g_shell_parse_argv (command_line, NULL, &argv, error)) return FALSE; retval = g_spawn_sync (NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, standard_output, standard_error, exit_status, error); g_strfreev (argv); return retval; } /** * g_spawn_command_line_async: * @command_line: a command line * @error: return location for errors * * A simple version of g_spawn_async() that parses a command line with * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a * command line in the background. Unlike g_spawn_async(), the * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note * that %G_SPAWN_SEARCH_PATH can have security implications, so * consider using g_spawn_async() directly if appropriate. Possible * errors are those from g_shell_parse_argv() and g_spawn_async(). * * The same concerns on Windows apply as for g_spawn_command_line_sync(). * * Return value: %TRUE on success, %FALSE if error is set. **/ gboolean g_spawn_command_line_async (const gchar *command_line, GError **error) { gboolean retval; gchar **argv = NULL; g_return_val_if_fail (command_line != NULL, FALSE); if (!g_shell_parse_argv (command_line, NULL, &argv, error)) return FALSE; retval = g_spawn_async (NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, error); g_strfreev (argv); return retval; } static gint exec_err_to_g_error (gint en) { switch (en) { #ifdef EACCES case EACCES: return G_SPAWN_ERROR_ACCES; break; #endif #ifdef EPERM case EPERM: return G_SPAWN_ERROR_PERM; break; #endif #ifdef E2BIG case E2BIG: return G_SPAWN_ERROR_2BIG; break; #endif #ifdef ENOEXEC case ENOEXEC: return G_SPAWN_ERROR_NOEXEC; break; #endif #ifdef ENAMETOOLONG case ENAMETOOLONG: return G_SPAWN_ERROR_NAMETOOLONG; break; #endif #ifdef ENOENT case ENOENT: return G_SPAWN_ERROR_NOENT; break; #endif #ifdef ENOMEM case ENOMEM: return G_SPAWN_ERROR_NOMEM; break; #endif #ifdef ENOTDIR case ENOTDIR: return G_SPAWN_ERROR_NOTDIR; break; #endif #ifdef ELOOP case ELOOP: return G_SPAWN_ERROR_LOOP; break; #endif #ifdef ETXTBUSY case ETXTBUSY: return G_SPAWN_ERROR_TXTBUSY; break; #endif #ifdef EIO case EIO: return G_SPAWN_ERROR_IO; break; #endif #ifdef ENFILE case ENFILE: return G_SPAWN_ERROR_NFILE; break; #endif #ifdef EMFILE case EMFILE: return G_SPAWN_ERROR_MFILE; break; #endif #ifdef EINVAL case EINVAL: return G_SPAWN_ERROR_INVAL; break; #endif #ifdef EISDIR case EISDIR: return G_SPAWN_ERROR_ISDIR; break; #endif #ifdef ELIBBAD case ELIBBAD: return G_SPAWN_ERROR_LIBBAD; break; #endif default: return G_SPAWN_ERROR_FAILED; break; } } static gssize write_all (gint fd, gconstpointer vbuf, gsize to_write) { gchar *buf = (gchar *) vbuf; while (to_write > 0) { gssize count = write (fd, buf, to_write); if (count < 0) { if (errno != EINTR) return FALSE; } else { to_write -= count; buf += count; } } return TRUE; } G_GNUC_NORETURN static void write_err_and_exit (gint fd, gint msg) { gint en = errno; write_all (fd, &msg, sizeof(msg)); write_all (fd, &en, sizeof(en)); _exit (1); } static int set_cloexec (void *data, gint fd) { if (fd >= GPOINTER_TO_INT (data)) fcntl (fd, F_SETFD, FD_CLOEXEC); return 0; } #ifndef HAVE_FDWALK static int fdwalk (int (*cb)(void *data, int fd), void *data) { gint open_max; gint fd; gint res = 0; #ifdef HAVE_SYS_RESOURCE_H struct rlimit rl; #endif #ifdef __linux__ DIR *d; if ((d = opendir("/proc/self/fd"))) { struct dirent *de; while ((de = readdir(d))) { glong l; gchar *e = NULL; if (de->d_name[0] == '.') continue; errno = 0; l = strtol(de->d_name, &e, 10); if (errno != 0 || !e || *e) continue; fd = (gint) l; if ((glong) fd != l) continue; if (fd == dirfd(d)) continue; if ((res = cb (data, fd)) != 0) break; } closedir(d); return res; } /* If /proc is not mounted or not accessible we fall back to the old * rlimit trick */ #endif #ifdef HAVE_SYS_RESOURCE_H if (getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY) open_max = rl.rlim_max; else #endif open_max = sysconf (_SC_OPEN_MAX); for (fd = 0; fd < open_max; fd++) if ((res = cb (data, fd)) != 0) break; return res; } #endif static gint sane_dup2 (gint fd1, gint fd2) { gint ret; retry: ret = dup2 (fd1, fd2); if (ret < 0 && errno == EINTR) goto retry; return ret; } enum { CHILD_CHDIR_FAILED, CHILD_EXEC_FAILED, CHILD_DUP2_FAILED, CHILD_FORK_FAILED }; static void do_exec (gint child_err_report_fd, gint stdin_fd, gint stdout_fd, gint stderr_fd, const gchar *working_directory, gchar **argv, gchar **envp, gboolean close_descriptors, gboolean search_path, gboolean stdout_to_null, gboolean stderr_to_null, gboolean child_inherits_stdin, gboolean file_and_argv_zero, GSpawnChildSetupFunc child_setup, gpointer user_data) { if (working_directory && chdir (working_directory) < 0) write_err_and_exit (child_err_report_fd, CHILD_CHDIR_FAILED); /* Close all file descriptors but stdin stdout and stderr as * soon as we exec. Note that this includes * child_err_report_fd, which keeps the parent from blocking * forever on the other end of that pipe. */ if (close_descriptors) { fdwalk (set_cloexec, GINT_TO_POINTER(3)); } else { /* We need to do child_err_report_fd anyway */ set_cloexec (GINT_TO_POINTER(0), child_err_report_fd); } /* Redirect pipes as required */ if (stdin_fd >= 0) { /* dup2 can't actually fail here I don't think */ if (sane_dup2 (stdin_fd, 0) < 0) write_err_and_exit (child_err_report_fd, CHILD_DUP2_FAILED); /* ignore this if it doesn't work */ close_and_invalidate (&stdin_fd); } else if (!child_inherits_stdin) { /* Keep process from blocking on a read of stdin */ gint read_null = open ("/dev/null", O_RDONLY); sane_dup2 (read_null, 0); close_and_invalidate (&read_null); } if (stdout_fd >= 0) { /* dup2 can't actually fail here I don't think */ if (sane_dup2 (stdout_fd, 1) < 0) write_err_and_exit (child_err_report_fd, CHILD_DUP2_FAILED); /* ignore this if it doesn't work */ close_and_invalidate (&stdout_fd); } else if (stdout_to_null) { gint write_null = open ("/dev/null", O_WRONLY); sane_dup2 (write_null, 1); close_and_invalidate (&write_null); } if (stderr_fd >= 0) { /* dup2 can't actually fail here I don't think */ if (sane_dup2 (stderr_fd, 2) < 0) write_err_and_exit (child_err_report_fd, CHILD_DUP2_FAILED); /* ignore this if it doesn't work */ close_and_invalidate (&stderr_fd); } else if (stderr_to_null) { gint write_null = open ("/dev/null", O_WRONLY); sane_dup2 (write_null, 2); close_and_invalidate (&write_null); } /* Call user function just before we exec */ if (child_setup) { (* child_setup) (user_data); } g_execute (argv[0], file_and_argv_zero ? argv + 1 : argv, envp, search_path); /* Exec failed */ write_err_and_exit (child_err_report_fd, CHILD_EXEC_FAILED); } static gboolean read_ints (int fd, gint* buf, gint n_ints_in_buf, gint *n_ints_read, GError **error) { gsize bytes = 0; while (TRUE) { gssize chunk; if (bytes >= sizeof(gint)*2) break; /* give up, who knows what happened, should not be * possible. */ again: chunk = read (fd, ((gchar*)buf) + bytes, sizeof(gint) * n_ints_in_buf - bytes); if (chunk < 0 && errno == EINTR) goto again; if (chunk < 0) { int errsv = errno; /* Some weird shit happened, bail out */ g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED, _("Failed to read from child pipe (%s)"), g_strerror (errsv)); return FALSE; } else if (chunk == 0) break; /* EOF */ else /* chunk > 0 */ bytes += chunk; } *n_ints_read = (gint)(bytes / sizeof(gint)); return TRUE; } static gboolean fork_exec_with_pipes (gboolean intermediate_child, const gchar *working_directory, gchar **argv, gchar **envp, gboolean close_descriptors, gboolean search_path, gboolean stdout_to_null, gboolean stderr_to_null, gboolean child_inherits_stdin, gboolean file_and_argv_zero, GSpawnChildSetupFunc child_setup, gpointer user_data, GPid *child_pid, gint *standard_input, gint *standard_output, gint *standard_error, GError **error) { GPid pid = -1; gint stdin_pipe[2] = { -1, -1 }; gint stdout_pipe[2] = { -1, -1 }; gint stderr_pipe[2] = { -1, -1 }; gint child_err_report_pipe[2] = { -1, -1 }; gint child_pid_report_pipe[2] = { -1, -1 }; gint status; if (!make_pipe (child_err_report_pipe, error)) return FALSE; if (intermediate_child && !make_pipe (child_pid_report_pipe, error)) goto cleanup_and_fail; if (standard_input && !make_pipe (stdin_pipe, error)) goto cleanup_and_fail; if (standard_output && !make_pipe (stdout_pipe, error)) goto cleanup_and_fail; if (standard_error && !make_pipe (stderr_pipe, error)) goto cleanup_and_fail; pid = fork (); if (pid < 0) { int errsv = errno; g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FORK, _("Failed to fork (%s)"), g_strerror (errsv)); goto cleanup_and_fail; } else if (pid == 0) { /* Immediate child. This may or may not be the child that * actually execs the new process. */ /* Be sure we crash if the parent exits * and we write to the err_report_pipe */ signal (SIGPIPE, SIG_DFL); /* Close the parent's end of the pipes; * not needed in the close_descriptors case, * though */ close_and_invalidate (&child_err_report_pipe[0]); close_and_invalidate (&child_pid_report_pipe[0]); close_and_invalidate (&stdin_pipe[1]); close_and_invalidate (&stdout_pipe[0]); close_and_invalidate (&stderr_pipe[0]); if (intermediate_child) { /* We need to fork an intermediate child that launches the * final child. The purpose of the intermediate child * is to exit, so we can waitpid() it immediately. * Then the grandchild will not become a zombie. */ GPid grandchild_pid; grandchild_pid = fork (); if (grandchild_pid < 0) { /* report -1 as child PID */ write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid)); write_err_and_exit (child_err_report_pipe[1], CHILD_FORK_FAILED); } else if (grandchild_pid == 0) { do_exec (child_err_report_pipe[1], stdin_pipe[0], stdout_pipe[1], stderr_pipe[1], working_directory, argv, envp, close_descriptors, search_path, stdout_to_null, stderr_to_null, child_inherits_stdin, file_and_argv_zero, child_setup, user_data); } else { write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid)); close_and_invalidate (&child_pid_report_pipe[1]); _exit (0); } } else { /* Just run the child. */ do_exec (child_err_report_pipe[1], stdin_pipe[0], stdout_pipe[1], stderr_pipe[1], working_directory, argv, envp, close_descriptors, search_path, stdout_to_null, stderr_to_null, child_inherits_stdin, file_and_argv_zero, child_setup, user_data); } } else { /* Parent */ gint buf[2]; gint n_ints = 0; /* Close the uncared-about ends of the pipes */ close_and_invalidate (&child_err_report_pipe[1]); close_and_invalidate (&child_pid_report_pipe[1]); close_and_invalidate (&stdin_pipe[0]); close_and_invalidate (&stdout_pipe[1]); close_and_invalidate (&stderr_pipe[1]); /* If we had an intermediate child, reap it */ if (intermediate_child) { wait_again: if (waitpid (pid, &status, 0) < 0) { if (errno == EINTR) goto wait_again; else if (errno == ECHILD) ; /* do nothing, child already reaped */ else g_warning ("waitpid() should not fail in " "'fork_exec_with_pipes'"); } } if (!read_ints (child_err_report_pipe[0], buf, 2, &n_ints, error)) goto cleanup_and_fail; if (n_ints >= 2) { /* Error from the child. */ switch (buf[0]) { case CHILD_CHDIR_FAILED: g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_CHDIR, _("Failed to change to directory '%s' (%s)"), working_directory, g_strerror (buf[1])); break; case CHILD_EXEC_FAILED: g_set_error (error, G_SPAWN_ERROR, exec_err_to_g_error (buf[1]), _("Failed to execute child process \"%s\" (%s)"), argv[0], g_strerror (buf[1])); break; case CHILD_DUP2_FAILED: g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED, _("Failed to redirect output or input of child process (%s)"), g_strerror (buf[1])); break; case CHILD_FORK_FAILED: g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FORK, _("Failed to fork child process (%s)"), g_strerror (buf[1])); break; default: g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED, _("Unknown error executing child process \"%s\""), argv[0]); break; } goto cleanup_and_fail; } /* Get child pid from intermediate child pipe. */ if (intermediate_child) { n_ints = 0; if (!read_ints (child_pid_report_pipe[0], buf, 1, &n_ints, error)) goto cleanup_and_fail; if (n_ints < 1) { int errsv = errno; g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED, _("Failed to read enough data from child pid pipe (%s)"), g_strerror (errsv)); goto cleanup_and_fail; } else { /* we have the child pid */ pid = buf[0]; } } /* Success against all odds! return the information */ close_and_invalidate (&child_err_report_pipe[0]); close_and_invalidate (&child_pid_report_pipe[0]); if (child_pid) *child_pid = pid; if (standard_input) *standard_input = stdin_pipe[1]; if (standard_output) *standard_output = stdout_pipe[0]; if (standard_error) *standard_error = stderr_pipe[0]; return TRUE; } cleanup_and_fail: /* There was an error from the Child, reap the child to avoid it being a zombie. */ if (pid > 0) { wait_failed: if (waitpid (pid, NULL, 0) < 0) { if (errno == EINTR) goto wait_failed; else if (errno == ECHILD) ; /* do nothing, child already reaped */ else g_warning ("waitpid() should not fail in " "'fork_exec_with_pipes'"); } } close_and_invalidate (&child_err_report_pipe[0]); close_and_invalidate (&child_err_report_pipe[1]); close_and_invalidate (&child_pid_report_pipe[0]); close_and_invalidate (&child_pid_report_pipe[1]); close_and_invalidate (&stdin_pipe[0]); close_and_invalidate (&stdin_pipe[1]); close_and_invalidate (&stdout_pipe[0]); close_and_invalidate (&stdout_pipe[1]); close_and_invalidate (&stderr_pipe[0]); close_and_invalidate (&stderr_pipe[1]); return FALSE; } static gboolean make_pipe (gint p[2], GError **error) { if (pipe (p) < 0) { gint errsv = errno; g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED, _("Failed to create pipe for communicating with child process (%s)"), g_strerror (errsv)); return FALSE; } else return TRUE; } /* Based on execvp from GNU C Library */ static void script_execute (const gchar *file, gchar **argv, gchar **envp, gboolean search_path) { /* Count the arguments. */ int argc = 0; while (argv[argc]) ++argc; /* Construct an argument list for the shell. */ { gchar **new_argv; new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */ new_argv[0] = (char *) "/bin/sh"; new_argv[1] = (char *) file; while (argc > 0) { new_argv[argc + 1] = argv[argc]; --argc; } /* Execute the shell. */ if (envp) execve (new_argv[0], new_argv, envp); else execv (new_argv[0], new_argv); g_free (new_argv); } } static gchar* my_strchrnul (const gchar *str, gchar c) { gchar *p = (gchar*) str; while (*p && (*p != c)) ++p; return p; } static gint g_execute (const gchar *file, gchar **argv, gchar **envp, gboolean search_path) { if (*file == '\0') { /* We check the simple case first. */ errno = ENOENT; return -1; } if (!search_path || strchr (file, '/') != NULL) { /* Don't search when it contains a slash. */ if (envp) execve (file, argv, envp); else execv (file, argv); if (errno == ENOEXEC) script_execute (file, argv, envp, FALSE); } else { gboolean got_eacces = 0; const gchar *path, *p; gchar *name, *freeme; gsize len; gsize pathlen; path = g_getenv ("PATH"); if (path == NULL) { /* There is no `PATH' in the environment. The default * search path in libc is the current directory followed by * the path `confstr' returns for `_CS_PATH'. */ /* In GLib we put . last, for security, and don't use the * unportable confstr(); UNIX98 does not actually specify * what to search if PATH is unset. POSIX may, dunno. */ path = "/bin:/usr/bin:."; } len = strlen (file) + 1; pathlen = strlen (path); freeme = name = g_malloc (pathlen + len + 1); /* Copy the file name at the top, including '\0' */ memcpy (name + pathlen + 1, file, len); name = name + pathlen; /* And add the slash before the filename */ *name = '/'; p = path; do { char *startp; path = p; p = my_strchrnul (path, ':'); if (p == path) /* Two adjacent colons, or a colon at the beginning or the end * of `PATH' means to search the current directory. */ startp = name + 1; else startp = memcpy (name - (p - path), path, p - path); /* Try to execute this name. If it works, execv will not return. */ if (envp) execve (startp, argv, envp); else execv (startp, argv); if (errno == ENOEXEC) script_execute (startp, argv, envp, search_path); switch (errno) { case EACCES: /* Record the we got a `Permission denied' error. If we end * up finding no executable we can use, we want to diagnose * that we did find one but were denied access. */ got_eacces = TRUE; /* FALL THRU */ case ENOENT: #ifdef ESTALE case ESTALE: #endif #ifdef ENOTDIR case ENOTDIR: #endif /* Those errors indicate the file is missing or not executable * by us, in which case we want to just try the next path * directory. */ break; default: /* Some other error means we found an executable file, but * something went wrong executing it; return the error to our * caller. */ g_free (freeme); return -1; } } while (*p++ != '\0'); /* We tried every element and none of them worked. */ if (got_eacces) /* At least one failure was due to permissions, so report that * error. */ errno = EACCES; g_free (freeme); } /* Return the error from the last attempt (probably ENOENT). */ return -1; } /** * g_spawn_close_pid: * @pid: The process reference to close * * On some platforms, notably Windows, the #GPid type represents a resource * which must be closed to prevent resource leaking. g_spawn_close_pid() * is provided for this purpose. It should be used on all platforms, even * though it doesn't do anything under UNIX. **/ void g_spawn_close_pid (GPid pid) { }
{ "language": "C" }
#ifndef __NVIF_IOCTL_H__ #define __NVIF_IOCTL_H__ #define NVIF_VERSION_LATEST 0x0000000000000000ULL struct nvif_ioctl_v0 { __u8 version; #define NVIF_IOCTL_V0_NOP 0x00 #define NVIF_IOCTL_V0_SCLASS 0x01 #define NVIF_IOCTL_V0_NEW 0x02 #define NVIF_IOCTL_V0_DEL 0x03 #define NVIF_IOCTL_V0_MTHD 0x04 #define NVIF_IOCTL_V0_RD 0x05 #define NVIF_IOCTL_V0_WR 0x06 #define NVIF_IOCTL_V0_MAP 0x07 #define NVIF_IOCTL_V0_UNMAP 0x08 #define NVIF_IOCTL_V0_NTFY_NEW 0x09 #define NVIF_IOCTL_V0_NTFY_DEL 0x0a #define NVIF_IOCTL_V0_NTFY_GET 0x0b #define NVIF_IOCTL_V0_NTFY_PUT 0x0c __u8 type; __u8 pad02[4]; #define NVIF_IOCTL_V0_OWNER_NVIF 0x00 #define NVIF_IOCTL_V0_OWNER_ANY 0xff __u8 owner; #define NVIF_IOCTL_V0_ROUTE_NVIF 0x00 #define NVIF_IOCTL_V0_ROUTE_HIDDEN 0xff __u8 route; __u64 token; __u64 object; __u8 data[]; /* ioctl data (below) */ }; struct nvif_ioctl_nop_v0 { __u64 version; }; struct nvif_ioctl_sclass_v0 { /* nvif_ioctl ... */ __u8 version; __u8 count; __u8 pad02[6]; struct nvif_ioctl_sclass_oclass_v0 { __s32 oclass; __s16 minver; __s16 maxver; } oclass[]; }; struct nvif_ioctl_new_v0 { /* nvif_ioctl ... */ __u8 version; __u8 pad01[6]; __u8 route; __u64 token; __u64 object; __u32 handle; __s32 oclass; __u8 data[]; /* class data (class.h) */ }; struct nvif_ioctl_del { }; struct nvif_ioctl_rd_v0 { /* nvif_ioctl ... */ __u8 version; __u8 size; __u8 pad02[2]; __u32 data; __u64 addr; }; struct nvif_ioctl_wr_v0 { /* nvif_ioctl ... */ __u8 version; __u8 size; __u8 pad02[2]; __u32 data; __u64 addr; }; struct nvif_ioctl_map_v0 { /* nvif_ioctl ... */ __u8 version; __u8 pad01[3]; __u32 length; __u64 handle; }; struct nvif_ioctl_unmap { }; struct nvif_ioctl_ntfy_new_v0 { /* nvif_ioctl ... */ __u8 version; __u8 event; __u8 index; __u8 pad03[5]; __u8 data[]; /* event request data (event.h) */ }; struct nvif_ioctl_ntfy_del_v0 { /* nvif_ioctl ... */ __u8 version; __u8 index; __u8 pad02[6]; }; struct nvif_ioctl_ntfy_get_v0 { /* nvif_ioctl ... */ __u8 version; __u8 index; __u8 pad02[6]; }; struct nvif_ioctl_ntfy_put_v0 { /* nvif_ioctl ... */ __u8 version; __u8 index; __u8 pad02[6]; }; struct nvif_ioctl_mthd_v0 { /* nvif_ioctl ... */ __u8 version; __u8 method; __u8 pad02[6]; __u8 data[]; /* method data (class.h) */ }; #endif
{ "language": "C" }
#include "vterm_internal.h" #include <stdio.h> #include <string.h> #define strneq(a,b,n) (strncmp(a,b,n)==0) #include "utf8.h" #ifdef DEBUG # define DEBUG_GLYPH_COMBINE #endif #define MOUSE_WANT_DRAG 0x01 #define MOUSE_WANT_MOVE 0x02 /* Some convenient wrappers to make callback functions easier */ static void putglyph(VTermState *state, const uint32_t chars[], int width, VTermPos pos) { if(state->callbacks && state->callbacks->putglyph) if((*state->callbacks->putglyph)(chars, width, pos, state->cbdata)) return; //fprintf(stderr, "libvterm: Unhandled putglyph U+%04x at (%d,%d)\n", chars[0], pos.col, pos.row); } static void updatecursor(VTermState *state, VTermPos *oldpos, int cancel_phantom) { if(state->pos.col == oldpos->col && state->pos.row == oldpos->row) return; if(cancel_phantom) state->at_phantom = 0; if(state->callbacks && state->callbacks->movecursor) if((*state->callbacks->movecursor)(state->pos, *oldpos, state->mode.cursor_visible, state->cbdata)) return; } static void erase(VTermState *state, VTermRect rect) { if(state->callbacks && state->callbacks->erase) (*state->callbacks->erase)(rect, state->cbdata); if(state->backup_callbacks && state->backup_callbacks->erase) (*state->backup_callbacks->erase)(rect, state->backup_cbdata); // return; } static VTermState *vterm_state_new(VTerm *vt) { VTermState *state = vterm_allocator_malloc(vt, sizeof(VTermState)); state->vt = vt; state->rows = vt->rows; state->cols = vt->cols; // 90% grey so that pure white is brighter state->default_fg.red = state->default_fg.green = state->default_fg.blue = 240; state->default_bg.red = state->default_bg.green = state->default_bg.blue = 0; state->bold_is_highbright = 0; return state; } void vterm_state_free(VTermState *state) { vterm_allocator_free(state->vt, state->combine_chars); vterm_allocator_free(state->vt, state); } static void scroll(VTermState *state, VTermRect rect, int downward, int rightward) { if(!downward && !rightward) return; if(state->callbacks && state->callbacks->scrollrect) if((*state->callbacks->scrollrect)(rect, downward, rightward, state->cbdata)) return; if(state->callbacks) vterm_scroll_rect(rect, downward, rightward, state->callbacks->moverect, state->callbacks->erase, state->cbdata); } static void linefeed(VTermState *state) { if(state->pos.row == SCROLLREGION_END(state) - 1) { VTermRect rect = { .start_row = state->scrollregion_start, .end_row = SCROLLREGION_END(state), .start_col = 0, .end_col = state->cols, }; scroll(state, rect, 1, 0); } else if(state->pos.row < state->rows-1) state->pos.row++; } static void grow_combine_buffer(VTermState *state) { size_t new_size = state->combine_chars_size * 2; uint32_t *new_chars = vterm_allocator_malloc(state->vt, new_size * sizeof(new_chars[0])); memcpy(new_chars, state->combine_chars, state->combine_chars_size * sizeof(new_chars[0])); vterm_allocator_free(state->vt, state->combine_chars); state->combine_chars = new_chars; } static void set_col_tabstop(VTermState *state, int col) { unsigned char mask = 1 << (col & 7); state->tabstops[col >> 3] |= mask; } static void clear_col_tabstop(VTermState *state, int col) { unsigned char mask = 1 << (col & 7); state->tabstops[col >> 3] &= ~mask; } static int is_col_tabstop(VTermState *state, int col) { unsigned char mask = 1 << (col & 7); return state->tabstops[col >> 3] & mask; } static void tab(VTermState *state, int count, int direction) { while(count--) while(state->pos.col >= 0 && state->pos.col < state->cols-1) { state->pos.col += direction; if(is_col_tabstop(state, state->pos.col)) break; } } static int on_text(const char bytes[], size_t len, void *user) { VTermState *state = user; VTermPos oldpos = state->pos; // We'll have at most len codepoints uint32_t codepoints[len]; for(int n=0;n<len;n++) codepoints[n]=0;//for some reason it's possible for codepoints to be used with being initialised, discovered during fuzz testing+valgrind. This at least makes it deterministic. int npoints = 0; size_t eaten = 0; VTermEncodingInstance *encoding = !(bytes[eaten] & 0x80) ? &state->encoding[state->gl_set] : state->vt->is_utf8 ? &state->encoding_utf8 : &state->encoding[state->gr_set]; (*encoding->enc->decode)(encoding->enc, encoding->data, codepoints, &npoints, len, bytes, &eaten, len); int i = 0; /* This is a combining char. that needs to be merged with the previous * glyph output */ if(vterm_unicode_is_combining(codepoints[i])) { /* See if the cursor has moved since */ if(state->pos.row == state->combine_pos.row && state->pos.col == state->combine_pos.col + state->combine_width) { #ifdef DEBUG_GLYPH_COMBINE int printpos; printf("DEBUG: COMBINING SPLIT GLYPH of chars {"); for(printpos = 0; state->combine_chars[printpos]; printpos++) printf("U+%04x ", state->combine_chars[printpos]); printf("} + {"); #endif /* Find where we need to append these combining chars */ int saved_i = 0; while(state->combine_chars[saved_i]) saved_i++; /* Add extra ones */ while(i < npoints && vterm_unicode_is_combining(codepoints[i])) { if(saved_i >= state->combine_chars_size) grow_combine_buffer(state); state->combine_chars[saved_i++] = codepoints[i++]; } if(saved_i >= state->combine_chars_size) grow_combine_buffer(state); state->combine_chars[saved_i] = 0; #ifdef DEBUG_GLYPH_COMBINE for(; state->combine_chars[printpos]; printpos++) printf("U+%04x ", state->combine_chars[printpos]); printf("}\n"); #endif /* Now render it */ putglyph(state, state->combine_chars, state->combine_width, state->combine_pos); } else { fprintf(stderr, "libvterm: TODO: Skip over split char+combining\n"); } } for(; i < npoints; i++) { // Try to find combining characters following this int glyph_starts = i; int glyph_ends; for(glyph_ends = i + 1; glyph_ends < npoints; glyph_ends++) if(!vterm_unicode_is_combining(codepoints[glyph_ends])) break; int width = 0; uint32_t chars[glyph_ends - glyph_starts + 1]; for( ; i < glyph_ends; i++) { chars[i - glyph_starts] = codepoints[i]; width += vterm_unicode_width(codepoints[i]); } chars[glyph_ends - glyph_starts] = 0; i--; #ifdef DEBUG_GLYPH_COMBINE int printpos; printf("DEBUG: COMBINED GLYPH of %d chars {", glyph_ends - glyph_starts); for(printpos = 0; printpos < glyph_ends - glyph_starts; printpos++) printf("U+%04x ", chars[printpos]); printf("}, onscreen width %d\n", width); #endif if(state->at_phantom) { linefeed(state); state->pos.col = 0; state->at_phantom = 0; } if(state->mode.insert) { /* TODO: This will be a little inefficient for large bodies of text, as * it'll have to 'ICH' effectively before every glyph. We should scan * ahead and ICH as many times as required */ VTermRect rect = { .start_row = state->pos.row, .end_row = state->pos.row + 1, .start_col = state->pos.col, .end_col = state->cols, }; scroll(state, rect, 0, -1); } putglyph(state, chars, width, state->pos); if(i == npoints - 1) { /* End of the buffer. Save the chars in case we have to combine with * more on the next call */ int save_i; for(save_i = 0; chars[save_i]; save_i++) { if(save_i >= state->combine_chars_size) grow_combine_buffer(state); state->combine_chars[save_i] = chars[save_i]; } if(save_i >= state->combine_chars_size) grow_combine_buffer(state); state->combine_chars[save_i] = 0; state->combine_width = width; state->combine_pos = state->pos; } if(state->pos.col + width >= state->cols) { if(state->mode.autowrap) state->at_phantom = 1; } else { state->pos.col += width; } } updatecursor(state, &oldpos, 0); return eaten; } static int on_control(unsigned char control, void *user) { VTermState *state = user; VTermPos oldpos = state->pos; switch(control) { case 0x07: // BEL - ECMA-48 8.3.3 if(state->callbacks && state->callbacks->bell) (*state->callbacks->bell)(state->cbdata); break; case 0x08: // BS - ECMA-48 8.3.5 if(state->pos.col > 0) state->pos.col--; break; case 0x09: // HT - ECMA-48 8.3.60 tab(state, 1, +1); break; case 0x0a: // LF - ECMA-48 8.3.74 case 0x0b: // VT case 0x0c: // FF linefeed(state); if(state->mode.newline) state->pos.col = 0; break; case 0x0d: // CR - ECMA-48 8.3.15 state->pos.col = 0; break; case 0x0e: // LS1 - ECMA-48 8.3.76 state->gl_set = 1; break; case 0x0f: // LS0 - ECMA-48 8.3.75 state->gl_set = 0; break; case 0x84: // IND - DEPRECATED but implemented for completeness linefeed(state); break; case 0x85: // NEL - ECMA-48 8.3.86 linefeed(state); state->pos.col = 0; break; case 0x88: // HTS - ECMA-48 8.3.62 set_col_tabstop(state, state->pos.col); break; case 0x8d: // RI - ECMA-48 8.3.104 if(state->pos.row == state->scrollregion_start) { VTermRect rect = { .start_row = state->scrollregion_start, .end_row = SCROLLREGION_END(state), .start_col = 0, .end_col = state->cols, }; scroll(state, rect, -1, 0); } else if(state->pos.row > 0) state->pos.row--; break; default: return 0; } updatecursor(state, &oldpos, 1); return 1; } static void output_mouse(VTermState *state, int code, int pressed, int modifiers, int col, int row) { modifiers <<= 2; switch(state->mouse_protocol) { case MOUSE_X10: if(col + 0x21 > 0xff) col = 0xff - 0x21; if(row + 0x21 > 0xff) row = 0xff - 0x21; if(!pressed) code = 3; vterm_push_output_sprintf(state->vt, "\e[M%c%c%c", (code | modifiers) + 0x20, col + 0x21, row + 0x21); break; case MOUSE_UTF8: { char utf8[18]; size_t len = 0; if(!pressed) code = 3; len += fill_utf8((code | modifiers) + 0x20, utf8 + len); len += fill_utf8(col + 0x21, utf8 + len); len += fill_utf8(row + 0x21, utf8 + len); vterm_push_output_sprintf(state->vt, "\e[M%s", utf8); } break; case MOUSE_SGR: vterm_push_output_sprintf(state->vt, "\e[<%d;%d;%d%c", code | modifiers, col + 1, row + 1, pressed ? 'M' : 'm'); break; case MOUSE_RXVT: if(!pressed) code = 3; vterm_push_output_sprintf(state->vt, "\e[%d;%d;%dM", code | modifiers, col + 1, row + 1); break; } } static void mousefunc(int col, int row, int button, int pressed, int modifiers, void *data) { VTermState *state = data; int old_col = state->mouse_col; int old_row = state->mouse_row; int old_buttons = state->mouse_buttons; state->mouse_col = col; state->mouse_row = row; if(button > 0 && button <= 3) { if(pressed) state->mouse_buttons |= (1 << (button-1)); else state->mouse_buttons &= ~(1 << (button-1)); } modifiers &= 0x7; /* Most of the time we don't get button releases from 4/5 */ if(state->mouse_buttons != old_buttons || button >= 4) { if(button < 4) { output_mouse(state, button-1, pressed, modifiers, col, row); } else if(button < 6) { output_mouse(state, button-4 + 0x40, pressed, modifiers, col, row); } } else if(col != old_col || row != old_row) { if((state->mouse_flags & MOUSE_WANT_DRAG && state->mouse_buttons) || (state->mouse_flags & MOUSE_WANT_MOVE)) { int button = state->mouse_buttons & 0x01 ? 1 : state->mouse_buttons & 0x02 ? 2 : state->mouse_buttons & 0x04 ? 3 : 4; output_mouse(state, button-1 + 0x20, 1, modifiers, col, row); } } } static int settermprop_bool(VTermState *state, VTermProp prop, int v) { VTermValue val; val.boolean = v; #ifdef DEBUG if(VTERM_VALUETYPE_BOOL != vterm_get_prop_type(prop)) { fprintf(stderr, "Cannot set prop %d as it has type %d, not type BOOL\n", prop, vterm_get_prop_type(prop)); return; } #endif if(state->callbacks && state->callbacks->settermprop) if((*state->callbacks->settermprop)(prop, &val, state->cbdata)) return 1; return 0; } static int settermprop_int(VTermState *state, VTermProp prop, int v) { VTermValue val; val.number = v; #ifdef DEBUG if(VTERM_VALUETYPE_INT != vterm_get_prop_type(prop)) { fprintf(stderr, "Cannot set prop %d as it has type %d, not type int\n", prop, vterm_get_prop_type(prop)); return; } #endif if(state->callbacks && state->callbacks->settermprop) if((*state->callbacks->settermprop)(prop, &val, state->cbdata)) return 1; return 0; } static int settermprop_string(VTermState *state, VTermProp prop, const char *str, size_t len) { char strvalue[len+1]; strncpy(strvalue, str, len); strvalue[len] = 0; VTermValue val; val.string = strvalue; #ifdef DEBUG if(VTERM_VALUETYPE_STRING != vterm_get_prop_type(prop)) { fprintf(stderr, "Cannot set prop %d as it has type %d, not type STRING\n", prop, vterm_get_prop_type(prop)); return; } #endif if(state->callbacks && state->callbacks->settermprop) if((*state->callbacks->settermprop)(prop, &val, state->cbdata)) return 1; return 0; } static void savecursor(VTermState *state, int save) { if(save) { state->saved.pos = state->pos; state->saved.mode.cursor_visible = state->mode.cursor_visible; state->saved.mode.cursor_blink = state->mode.cursor_blink; state->saved.mode.cursor_shape = state->mode.cursor_shape; vterm_state_savepen(state, 1); } else { VTermPos oldpos = state->pos; state->pos = state->saved.pos; state->mode.cursor_visible = state->saved.mode.cursor_visible; state->mode.cursor_blink = state->saved.mode.cursor_blink; state->mode.cursor_shape = state->saved.mode.cursor_shape; settermprop_bool(state, VTERM_PROP_CURSORVISIBLE, state->mode.cursor_visible); settermprop_bool(state, VTERM_PROP_CURSORBLINK, state->mode.cursor_blink); settermprop_int (state, VTERM_PROP_CURSORSHAPE, state->mode.cursor_shape); vterm_state_savepen(state, 0); updatecursor(state, &oldpos, 1); } } static void altscreen(VTermState *state, int alt) { /* Only store that we're on the alternate screen if the usercode said it * switched */ if(!settermprop_bool(state, VTERM_PROP_ALTSCREEN, alt)) return; state->mode.alt_screen = alt; if(alt) { VTermRect rect = { .start_row = 0, .start_col = 0, .end_row = state->rows, .end_col = state->cols, }; erase(state, rect); } } static int on_escape(const char *bytes, size_t len, void *user) { VTermState *state = user; /* Easier to decode this from the first byte, even though the final * byte terminates it */ switch(bytes[0]) { case '#': if(len != 2) return 0; switch(bytes[1]) { case '8': // DECALN { VTermPos pos; uint32_t E[] = { 'E', 0 }; for(pos.row = 0; pos.row < state->rows; pos.row++) for(pos.col = 0; pos.col < state->cols; pos.col++) putglyph(state, E, 1, pos); break; } default: return 0; } return 2; case '(': case ')': case '*': case '+': // SCS if(len != 2) return 0; { int setnum = bytes[0] - 0x28; VTermEncoding *newenc = vterm_lookup_encoding(ENC_SINGLE_94, bytes[1]); if(newenc) { state->encoding[setnum].enc = newenc; if(newenc->init) (*newenc->init)(newenc, state->encoding[setnum].data); } } return 2; case '7': // DECSC savecursor(state, 1); return 1; case '8': // DECRC savecursor(state, 0); return 1; case '=': // DECKPAM state->mode.keypad = 1; return 1; case '>': // DECKPNM state->mode.keypad = 0; return 1; case 'c': // RIS - ECMA-48 8.3.105 { VTermPos oldpos = state->pos; vterm_state_reset(state, 1); if(state->callbacks && state->callbacks->movecursor) (*state->callbacks->movecursor)(state->pos, oldpos, state->mode.cursor_visible, state->cbdata); return 1; } case 'n': // LS2 - ECMA-48 8.3.78 state->gl_set = 2; return 1; case 'o': // LS3 - ECMA-48 8.3.80 state->gl_set = 3; return 1; default: return 0; } } static void set_mode(VTermState *state, int num, int val) { switch(num) { case 4: // IRM - ECMA-48 7.2.10 state->mode.insert = val; break; case 20: // LNM - ANSI X3.4-1977 state->mode.newline = val; break; default: fprintf(stderr, "libvterm: Unknown mode %d\n", num); return; } } static void set_dec_mode(VTermState *state, int num, int val) { switch(num) { case 1: state->mode.cursor = val; break; case 5: settermprop_bool(state, VTERM_PROP_REVERSE, val); break; case 6: // DECOM - origin mode { VTermPos oldpos = state->pos; state->mode.origin = val; state->pos.row = state->mode.origin ? state->scrollregion_start : 0; state->pos.col = 0; updatecursor(state, &oldpos, 1); } break; case 7: state->mode.autowrap = val; break; case 12: state->mode.cursor_blink = val; settermprop_bool(state, VTERM_PROP_CURSORBLINK, val); break; case 25: state->mode.cursor_visible = val; settermprop_bool(state, VTERM_PROP_CURSORVISIBLE, val); break; case 1000: case 1002: case 1003: if(val) { state->mouse_col = 0; state->mouse_row = 0; state->mouse_buttons = 0; state->mouse_flags = 0; state->mouse_protocol = MOUSE_X10; if(num == 1002) state->mouse_flags |= MOUSE_WANT_DRAG; if(num == 1003) state->mouse_flags |= MOUSE_WANT_MOVE; } if(state->callbacks && state->callbacks->setmousefunc) (*state->callbacks->setmousefunc)(val ? mousefunc : NULL, state, state->cbdata); break; case 1005: state->mouse_protocol = val ? MOUSE_UTF8 : MOUSE_X10; break; case 1006: state->mouse_protocol = val ? MOUSE_SGR : MOUSE_X10; break; case 1015: state->mouse_protocol = val ? MOUSE_RXVT : MOUSE_X10; break; case 1047: altscreen(state, val); break; case 1048: savecursor(state, val); break; case 1049: altscreen(state, val); savecursor(state, val); break; default: fprintf(stderr, "libvterm: Unknown DEC mode %d\n", num); return; } } static int on_csi(const char *leader, const long args[], int argcount, const char *intermed, char command, void *user) { VTermState *state = user; int leader_byte = 0; int intermed_byte = 0; if(leader && leader[0]) { if(leader[1]) // longer than 1 char return 0; switch(leader[0]) { case '?': case '>': leader_byte = leader[0]; break; default: return 0; } } if(intermed && intermed[0]) { if(intermed[1]) // longer than 1 char return 0; switch(intermed[0]) { case ' ': intermed_byte = intermed[0]; break; default: return 0; } } VTermPos oldpos = state->pos; // Some temporaries for later code int count, val; int row, col; VTermRect rect; #define LEADER(l,b) ((l << 8) | b) #define INTERMED(i,b) ((i << 16) | b) switch(intermed_byte << 16 | leader_byte << 8 | command) { case 0x40: // ICH - ECMA-48 8.3.64 count = CSI_ARG_COUNT(args[0]); rect.start_row = state->pos.row; rect.end_row = state->pos.row + 1; rect.start_col = state->pos.col; rect.end_col = state->cols; scroll(state, rect, 0, -count); break; case 0x41: // CUU - ECMA-48 8.3.22 count = CSI_ARG_COUNT(args[0]); state->pos.row -= count; state->at_phantom = 0; break; case 0x42: // CUD - ECMA-48 8.3.19 count = CSI_ARG_COUNT(args[0]); state->pos.row += count; state->at_phantom = 0; break; case 0x43: // CUF - ECMA-48 8.3.20 count = CSI_ARG_COUNT(args[0]); state->pos.col += count; state->at_phantom = 0; break; case 0x44: // CUB - ECMA-48 8.3.18 count = CSI_ARG_COUNT(args[0]); state->pos.col -= count; state->at_phantom = 0; break; case 0x45: // CNL - ECMA-48 8.3.12 count = CSI_ARG_COUNT(args[0]); state->pos.col = 0; state->pos.row += count; state->at_phantom = 0; break; case 0x46: // CPL - ECMA-48 8.3.13 count = CSI_ARG_COUNT(args[0]); state->pos.col = 0; state->pos.row -= count; state->at_phantom = 0; break; case 0x47: // CHA - ECMA-48 8.3.9 val = CSI_ARG_OR(args[0], 1); state->pos.col = val-1; state->at_phantom = 0; break; case 0x48: // CUP - ECMA-48 8.3.21 row = CSI_ARG_OR(args[0], 1); col = argcount < 2 || CSI_ARG_IS_MISSING(args[1]) ? 1 : CSI_ARG(args[1]); // zero-based state->pos.row = row-1; state->pos.col = col-1; if(state->mode.origin) state->pos.row += state->scrollregion_start; state->at_phantom = 0; break; case 0x49: // CHT - ECMA-48 8.3.10 count = CSI_ARG_COUNT(args[0]); tab(state, count, +1); break; case 0x4a: // ED - ECMA-48 8.3.39 switch(CSI_ARG(args[0])) { case CSI_ARG_MISSING: case 0: rect.start_row = state->pos.row; rect.end_row = state->pos.row + 1; rect.start_col = state->pos.col; rect.end_col = state->cols; if(rect.end_col > rect.start_col) erase(state, rect); rect.start_row = state->pos.row + 1; rect.end_row = state->rows; rect.start_col = 0; if(rect.end_row > rect.start_row) erase(state, rect); break; case 1: rect.start_row = 0; rect.end_row = state->pos.row; rect.start_col = 0; rect.end_col = state->cols; if(rect.end_col > rect.start_col) erase(state, rect); rect.start_row = state->pos.row; rect.end_row = state->pos.row + 1; rect.end_col = state->pos.col + 1; if(rect.end_row > rect.start_row) erase(state, rect); break; case 2: rect.start_row = 0; rect.end_row = state->rows; rect.start_col = 0; rect.end_col = state->cols; erase(state, rect); break; } break; case 0x4b: // EL - ECMA-48 8.3.41 rect.start_row = state->pos.row; rect.end_row = state->pos.row + 1; switch(CSI_ARG(args[0])) { case CSI_ARG_MISSING: case 0: rect.start_col = state->pos.col; rect.end_col = state->cols; break; case 1: rect.start_col = 0; rect.end_col = state->pos.col + 1; break; case 2: rect.start_col = 0; rect.end_col = state->cols; break; default: return 0; } if(rect.end_col > rect.start_col) erase(state, rect); break; case 0x4c: // IL - ECMA-48 8.3.67 count = CSI_ARG_COUNT(args[0]); rect.start_row = state->pos.row; rect.end_row = SCROLLREGION_END(state); rect.start_col = 0; rect.end_col = state->cols; scroll(state, rect, -count, 0); break; case 0x4d: // DL - ECMA-48 8.3.32 count = CSI_ARG_COUNT(args[0]); rect.start_row = state->pos.row; rect.end_row = SCROLLREGION_END(state); rect.start_col = 0; rect.end_col = state->cols; scroll(state, rect, count, 0); break; case 0x50: // DCH - ECMA-48 8.3.26 count = CSI_ARG_COUNT(args[0]); rect.start_row = state->pos.row; rect.end_row = state->pos.row + 1; rect.start_col = state->pos.col; rect.end_col = state->cols; scroll(state, rect, 0, count); break; case 0x53: // SU - ECMA-48 8.3.147 count = CSI_ARG_COUNT(args[0]); rect.start_row = state->scrollregion_start; rect.end_row = SCROLLREGION_END(state); rect.start_col = 0; rect.end_col = state->cols; scroll(state, rect, count, 0); break; case 0x54: // SD - ECMA-48 8.3.113 count = CSI_ARG_COUNT(args[0]); rect.start_row = state->scrollregion_start; rect.end_row = SCROLLREGION_END(state); rect.start_col = 0; rect.end_col = state->cols; scroll(state, rect, -count, 0); break; case 0x58: // ECH - ECMA-48 8.3.38 count = CSI_ARG_COUNT(args[0]); rect.start_row = state->pos.row; rect.end_row = state->pos.row + 1; rect.start_col = state->pos.col; rect.end_col = state->pos.col + count; erase(state, rect); break; case 0x5a: // CBT - ECMA-48 8.3.7 count = CSI_ARG_COUNT(args[0]); tab(state, count, -1); break; case 0x60: // HPA - ECMA-48 8.3.57 col = CSI_ARG_OR(args[0], 1); state->pos.col = col-1; state->at_phantom = 0; break; case 0x61: // HPR - ECMA-48 8.3.59 count = CSI_ARG_COUNT(args[0]); state->pos.col += count; state->at_phantom = 0; break; case 0x63: // DA - ECMA-48 8.3.24 val = CSI_ARG_OR(args[0], 0); if(val == 0) // DEC VT100 response vterm_push_output_sprintf(state->vt, "\e[?1;2c"); break; case LEADER('>', 0x63): // DEC secondary Device Attributes vterm_push_output_sprintf(state->vt, "\e[>%d;%d;%dc", 0, 100, 0); break; case 0x64: // VPA - ECMA-48 8.3.158 row = CSI_ARG_OR(args[0], 1); state->pos.row = row-1; if(state->mode.origin) state->pos.row += state->scrollregion_start; state->at_phantom = 0; break; case 0x65: // VPR - ECMA-48 8.3.160 count = CSI_ARG_COUNT(args[0]); state->pos.row += count; state->at_phantom = 0; break; case 0x66: // HVP - ECMA-48 8.3.63 row = CSI_ARG_OR(args[0], 1); col = argcount < 2 || CSI_ARG_IS_MISSING(args[1]) ? 1 : CSI_ARG(args[1]); // zero-based state->pos.row = row-1; state->pos.col = col-1; if(state->mode.origin) state->pos.row += state->scrollregion_start; state->at_phantom = 0; break; case 0x67: // TBC - ECMA-48 8.3.154 val = CSI_ARG_OR(args[0], 0); switch(val) { case 0: clear_col_tabstop(state, state->pos.col); break; case 3: case 5: for(col = 0; col < state->cols; col++) clear_col_tabstop(state, col); break; case 1: case 2: case 4: break; /* TODO: 1, 2 and 4 aren't meaningful yet without line tab stops */ default: return 0; } break; case 0x68: // SM - ECMA-48 8.3.125 if(!CSI_ARG_IS_MISSING(args[0])) set_mode(state, CSI_ARG(args[0]), 1); break; case LEADER('?', 0x68): // DEC private mode set if(!CSI_ARG_IS_MISSING(args[0])) set_dec_mode(state, CSI_ARG(args[0]), 1); break; case 0x6a: // HPB - ECMA-48 8.3.58 count = CSI_ARG_COUNT(args[0]); state->pos.col -= count; state->at_phantom = 0; break; case 0x6b: // VPB - ECMA-48 8.3.159 count = CSI_ARG_COUNT(args[0]); state->pos.row -= count; state->at_phantom = 0; break; case 0x6c: // RM - ECMA-48 8.3.106 if(!CSI_ARG_IS_MISSING(args[0])) set_mode(state, CSI_ARG(args[0]), 0); break; case LEADER('?', 0x6c): // DEC private mode reset if(!CSI_ARG_IS_MISSING(args[0])) set_dec_mode(state, CSI_ARG(args[0]), 0); break; case 0x6d: // SGR - ECMA-48 8.3.117 vterm_state_setpen(state, args, argcount); break; case 0x6e: // DSR - ECMA-48 8.3.35 val = CSI_ARG_OR(args[0], 0); switch(val) { case 0: case 1: case 2: case 3: case 4: // ignore - these are replies break; case 5: vterm_push_output_sprintf(state->vt, "\e[0n"); break; case 6: vterm_push_output_sprintf(state->vt, "\e[%d;%dR", state->pos.row + 1, state->pos.col + 1); break; } break; case LEADER('!', 0x70): // DECSTR - DEC soft terminal reset vterm_state_reset(state, 0); break; case INTERMED(' ', 0x71): // DECSCUSR - DEC set cursor shape val = CSI_ARG_OR(args[0], 1); switch(val) { case 0: case 1: state->mode.cursor_blink = 1; state->mode.cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK; break; case 2: state->mode.cursor_blink = 0; state->mode.cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK; break; case 3: state->mode.cursor_blink = 1; state->mode.cursor_shape = VTERM_PROP_CURSORSHAPE_UNDERLINE; break; case 4: state->mode.cursor_blink = 0; state->mode.cursor_shape = VTERM_PROP_CURSORSHAPE_UNDERLINE; break; } settermprop_bool(state, VTERM_PROP_CURSORBLINK, state->mode.cursor_blink); settermprop_int (state, VTERM_PROP_CURSORSHAPE, state->mode.cursor_shape); break; case 0x72: // DECSTBM - DEC custom state->scrollregion_start = CSI_ARG_OR(args[0], 1) - 1; state->scrollregion_end = argcount < 2 || CSI_ARG_IS_MISSING(args[1]) ? -1 : CSI_ARG(args[1]); if(state->scrollregion_start == 0 && state->scrollregion_end == state->rows) state->scrollregion_end = -1; break; case 0x73: // ANSI SAVE savecursor(state, 1); break; case 0x75: // ANSI RESTORE savecursor(state, 0); break; default: return 0; } #define LBOUND(v,min) if((v) < (min)) (v) = (min) #define UBOUND(v,max) if((v) > (max)) (v) = (max) LBOUND(state->pos.col, 0); UBOUND(state->pos.col, state->cols-1); if(state->mode.origin) { LBOUND(state->pos.row, state->scrollregion_start); UBOUND(state->pos.row, state->scrollregion_end-1); } else { LBOUND(state->pos.row, 0); UBOUND(state->pos.row, state->rows-1); } updatecursor(state, &oldpos, 1); return 1; } static int on_osc(const char *command, size_t cmdlen, void *user) { VTermState *state = user; if(cmdlen < 2) return 0; if(strneq(command, "0;", 2)) { settermprop_string(state, VTERM_PROP_ICONNAME, command + 2, cmdlen - 2); settermprop_string(state, VTERM_PROP_TITLE, command + 2, cmdlen - 2); return 1; } else if(strneq(command, "1;", 2)) { settermprop_string(state, VTERM_PROP_ICONNAME, command + 2, cmdlen - 2); return 1; } else if(strneq(command, "2;", 2)) { settermprop_string(state, VTERM_PROP_TITLE, command + 2, cmdlen - 2); return 1; } return 0; } static void request_status_string(VTermState *state, const char *command, size_t cmdlen) { if(cmdlen == 1) switch(command[0]) { case 'r': // Query DECSTBM vterm_push_output_sprintf(state->vt, "\eP1$r%d;%dr\e\\", state->scrollregion_start+1, SCROLLREGION_END(state)); return; } if(cmdlen == 2) if(strneq(command, " q", 2)) { int reply; switch(state->mode.cursor_shape) { case VTERM_PROP_CURSORSHAPE_BLOCK: reply = 2; break; case VTERM_PROP_CURSORSHAPE_UNDERLINE: reply = 4; break; } if(state->mode.cursor_blink) reply--; vterm_push_output_sprintf(state->vt, "\eP1$r%d q\e\\", reply); return; } vterm_push_output_sprintf(state->vt, "\eP0$r%.s\e\\", (int)cmdlen, command); } static int on_dcs(const char *command, size_t cmdlen, void *user) { VTermState *state = user; if(cmdlen >= 2 && strneq(command, "$q", 2)) { request_status_string(state, command+2, cmdlen-2); return 1; } return 0; } static int on_resize(int rows, int cols, void *user) { VTermState *state = user; VTermPos oldpos = state->pos; if(cols != state->cols) { unsigned char *newtabstops = vterm_allocator_malloc(state->vt, (cols + 7) / 8); /* TODO: This can all be done much more efficiently bytewise */ int col; for(col = 0; col < state->cols && col < cols; col++) { unsigned char mask = 1 << (col & 7); if(state->tabstops[col >> 3] & mask) newtabstops[col >> 3] |= mask; else newtabstops[col >> 3] &= ~mask; } for( ; col < cols; col++) { unsigned char mask = 1 << (col & 7); if(col % 8 == 0) newtabstops[col >> 3] |= mask; else newtabstops[col >> 3] &= ~mask; } vterm_allocator_free(state->vt, state->tabstops); state->tabstops = newtabstops; } state->rows = rows; state->cols = cols; if(state->pos.row >= rows) state->pos.row = rows - 1; if(state->pos.col >= cols) state->pos.col = cols - 1; if(state->at_phantom && state->pos.col < cols-1) { state->at_phantom = 0; state->pos.col++; } if(state->callbacks && state->callbacks->resize) (*state->callbacks->resize)(rows, cols, state->cbdata); updatecursor(state, &oldpos, 1); return 1; } static const VTermParserCallbacks parser_callbacks = { .text = on_text, .control = on_control, .escape = on_escape, .csi = on_csi, .osc = on_osc, .dcs = on_dcs, .resize = on_resize, }; VTermState *vterm_obtain_state(VTerm *vt) { if(vt->state) return vt->state; VTermState *state = vterm_state_new(vt); vt->state = state; state->combine_chars_size = 16; state->combine_chars = vterm_allocator_malloc(state->vt, state->combine_chars_size * sizeof(state->combine_chars[0])); state->tabstops = vterm_allocator_malloc(state->vt, (state->cols + 7) / 8); state->encoding_utf8.enc = vterm_lookup_encoding(ENC_UTF8, 'u'); if(*state->encoding_utf8.enc->init) (*state->encoding_utf8.enc->init)(state->encoding_utf8.enc, state->encoding_utf8.data); vterm_set_parser_callbacks(vt, &parser_callbacks, state); return state; } void vterm_state_reset(VTermState *state, int hard) { state->scrollregion_start = 0; state->scrollregion_end = -1; state->mode.keypad = 0; state->mode.cursor = 0; state->mode.autowrap = 1; state->mode.insert = 0; state->mode.newline = 0; state->mode.cursor_visible = 1; state->mode.cursor_blink = 1; state->mode.cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK; state->mode.alt_screen = 0; state->mode.origin = 0; for(int col = 0; col < state->cols; col++) if(col % 8 == 0) set_col_tabstop(state, col); else clear_col_tabstop(state, col); if(state->callbacks && state->callbacks->initpen) (*state->callbacks->initpen)(state->cbdata); vterm_state_resetpen(state); VTermEncoding *default_enc = state->vt->is_utf8 ? vterm_lookup_encoding(ENC_UTF8, 'u') : vterm_lookup_encoding(ENC_SINGLE_94, 'B'); for(int i = 0; i < 4; i++) { state->encoding[i].enc = default_enc; if(default_enc->init) (*default_enc->init)(default_enc, state->encoding[i].data); } state->gl_set = 0; state->gr_set = 0; // Initialise the props settermprop_bool(state, VTERM_PROP_CURSORVISIBLE, state->mode.cursor_visible); settermprop_bool(state, VTERM_PROP_CURSORBLINK, state->mode.cursor_blink); settermprop_int (state, VTERM_PROP_CURSORSHAPE, state->mode.cursor_shape); if(hard) { state->pos.row = 0; state->pos.col = 0; state->at_phantom = 0; VTermRect rect = { 0, state->rows, 0, state->cols }; erase(state, rect); } } void vterm_state_get_cursorpos(VTermState *state, VTermPos *cursorpos) { *cursorpos = state->pos; } void vterm_state_set_callbacks(VTermState *state, const VTermStateCallbacks *callbacks, void *user) { if(callbacks) { state->callbacks = callbacks; state->cbdata = user; if(state->callbacks && state->callbacks->initpen) (*state->callbacks->initpen)(state->cbdata); } else { state->callbacks = NULL; state->cbdata = NULL; } } void vterm_state_set_backup_callbacks(VTermState *state, const VTermStateCallbacks *callbacks, void *user) { if(callbacks) { state->backup_callbacks = callbacks; state->backup_cbdata = user; if(state->backup_callbacks && state->backup_callbacks->initpen) (*state->backup_callbacks->initpen)(state->backup_cbdata); } else { state->backup_callbacks = NULL; state->backup_cbdata = NULL; } }
{ "language": "C" }
%{ #define ATSCODEFORMAT "txt" #if (ATSCODEFORMAT == "txt") #include "utils/atsdoc/HATS/postiatsatxt.hats" #endif // end of [ATSCCODEFORMAT] val _thisfilename = atext_strcst"char.dats" val () = theAtextMap_insert_str ("thisfilename", _thisfilename) %}\ \ #atscode_banner() #atscode_copyright_GPL() #atscode_separator() (* ** Source: ** $PATSHOME/prelude/DATS/CODEGEN/char.atxt ** Time of generation: #timestamp() *) #atscode_separator() #atscode_author("Hongwei Xi") #atscode_authoremail("hwxi AT cs DOT bu DOT edu") #atscode_start_time("Feburary, 2012") #atscode_separator() \#define ATS_DYNLOADFLAG 0 // no dynloading at run-time #atscode_separator() staload UN = "prelude/SATS/unsafe.sats" #atscode_separator() implement{tk} g0int_of_char (c) = __cast (c) where { extern castfn __cast (c: char):<> g0int (tk) } // end of [g0int_of_char] implement{tk} g0int_of_schar (c) = __cast (c) where { extern castfn __cast (c: schar):<> g0int (tk) } // end of [g0int_of_schar] implement{tk} g0int_of_uchar (c) = __cast (c) where { extern castfn __cast (c: uchar):<> g0int (tk) } // end of [g0int_of_uchar] implement{tk} g0uint_of_uchar (c) = __cast (c) where { extern castfn __cast (c: uchar):<> g0uint (tk) } // end of [g0uint_of_uchar] #atscode_separator() implement{tk} g1int_of_char1 {c} (c) = __cast (c) where { extern castfn __cast (c: char c):<> g1int (tk, c) } // end of [g1int_of_char1] implement{tk} g1int_of_schar1 {c} (c) = __cast (c) where { extern castfn __cast (c: schar c):<> g1int (tk, c) } // end of [g1int_of_schar1] implement{tk} g1int_of_uchar1 {c} (c) = __cast (c) where { extern castfn __cast (c: uchar c):<> g1int (tk, c) } // end of [g1int_of_uchar1] implement{tk} g1uint_of_uchar1 {c} (c) = __cast (c) where { extern castfn __cast (c: uchar c):<> g1uint (tk, c) } // end of [g1uint_of_uchar1] #atscode_separator() implement {}(*tmp*) char2string(c) = $effmask_wrt ( $UN.castvwtp0{string}(char2strptr(c)) ) (* end of [char2string] *) implement {}(*tmp*) char2strptr(c) = let // \#define BSZ 16 // typedef cstring = $extype"atstype_string" // var buf = @[byte][BSZ]() val bufp = $UN.cast{cstring}(addr@buf) // val _(*int*) = $extfcall(ssize_t, "snprintf", bufp, BSZ, "%c", c) // in $UN.castvwtp0{Strptr1}(string0_copy($UN.cast{string}(bufp))) end // end of [char2strptr] #atscode_separator() // implement fprint_val<char> = fprint_char implement fprint_val<uchar> = fprint_uchar implement fprint_val<schar> = fprint_schar // #atscode_separator() #atscode_eof_strsub("\#thisfilename$")\ %{ implement main (argc, argv) = fprint_filsub (stdout_ref, "char_atxt.txt") %}\
{ "language": "C" }
/* * Copyright 2018-2020 Redis Labs Ltd. and Contributors * * This file is available under the Redis Labs Source Available License Agreement */ #include "decode_graph.h" #include "current/v7/decode_v7.h" GraphContext *RdbLoadGraph(RedisModuleIO *rdb) { return RdbLoadGraph_v7(rdb); }
{ "language": "C" }
/* * drivers/display/lcd/lcd_extern/i2c_T5800Q.c * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the named License, * or 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 <common.h> #include <malloc.h> #include <asm/arch/gpio.h> #ifdef CONFIG_OF_LIBFDT #include <libfdt.h> #endif #include <amlogic/aml_lcd.h> #include <amlogic/aml_lcd_extern.h> #include "lcd_extern.h" #include "../aml_lcd_common.h" #include "../aml_lcd_reg.h" #define LCD_EXTERN_NAME "i2c_T5800Q" #define LCD_EXTERN_TYPE LCD_EXTERN_I2C #define LCD_EXTERN_I2C_ADDR (0x38 >> 1) //7bit address //#define LCD_EXT_I2C_PORT_INIT /* no need init i2c port default */ static struct lcd_extern_config_s *ext_config; #define LCD_EXTERN_CMD_SIZE LCD_EXT_CMD_SIZE_DYNAMIC static unsigned char init_on_table[] = { //QFHD 50/60Hz 1 division Video Mode : 0xc0, 7, 0x20, 0x01, 0x02, 0x00, 0x40, 0xFF, 0x00, 0xc0, 7, 0x80, 0x02, 0x00, 0x40, 0x62, 0x51, 0x73, 0xc0, 7, 0x61, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 7, 0xC1, 0x05, 0x0F, 0x00, 0x08, 0x70, 0x00, 0xc0, 7, 0x13, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 7, 0x3D, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, //Color Engine Bypass Enable 0xc0, 7, 0xED, 0x0D, 0x01, 0x00, 0x00, 0x00, 0x00, //Mute only when starting 0xc0, 7, 0x23, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, //MEMC off 0xfd, 1, 10, /* delay 10ms */ 0xff, 0, /* ending */ }; static unsigned char init_off_table[] = { 0xff, 0, //ending }; static int lcd_extern_reg_read(unsigned char reg, unsigned char *buf) { int ret = 0; return ret; } static int lcd_extern_reg_write(unsigned char reg, unsigned char value) { int ret = 0; return ret; } static int lcd_extern_power_cmd_dynamic_size(unsigned char *table, int flag) { int i = 0, j = 0, max_len = 0, step = 0; unsigned char type, cmd_size; int delay_ms, ret = 0; if (flag) max_len = ext_config->table_init_on_cnt; else max_len = ext_config->table_init_off_cnt; while ((i + 1) < max_len) { type = table[i]; if (type == LCD_EXT_CMD_TYPE_END) break; if (lcd_debug_print_flag) { EXTPR("%s: step %d: type=0x%02x, cmd_size=%d\n", __func__, step, type, table[i+1]); } cmd_size = table[i+1]; if (cmd_size == 0) goto power_cmd_dynamic_next; if ((i + 2 + cmd_size) > max_len) break; if (type == LCD_EXT_CMD_TYPE_NONE) { /* do nothing */ } else if (type == LCD_EXT_CMD_TYPE_GPIO) { if (cmd_size < 2) { EXTERR("step %d: invalid cmd_size %d for GPIO\n", step, cmd_size); goto power_cmd_dynamic_next; } aml_lcd_extern_gpio_set(table[i+2], table[i+3]); if (cmd_size > 2) { if (table[i+4] > 0) mdelay(table[i+4]); } } else if (type == LCD_EXT_CMD_TYPE_DELAY) { delay_ms = 0; for (j = 0; j < cmd_size; j++) delay_ms += table[i+2+j]; if (delay_ms > 0) mdelay(delay_ms); } else if (type == LCD_EXT_CMD_TYPE_CMD) { ret = aml_lcd_extern_i2c_write(ext_config->i2c_bus, ext_config->i2c_addr, &table[i+2], cmd_size); } else if (type == LCD_EXT_CMD_TYPE_CMD_DELAY) { ret = aml_lcd_extern_i2c_write(ext_config->i2c_bus, ext_config->i2c_addr, &table[i+2], (cmd_size-1)); if (table[i+1+cmd_size] > 0) mdelay(table[i+1+cmd_size]); } else { EXTERR("%s: %s(%d): type 0x%02x invalid\n", __func__, ext_config->name, ext_config->index, type); } power_cmd_dynamic_next: i += (cmd_size + 2); step++; } return ret; } static int lcd_extern_power_cmd_fixed_size(unsigned char *table, int flag) { int i = 0, j, max_len, step = 0; unsigned char type, cmd_size; int delay_ms, ret = 0; cmd_size = ext_config->cmd_size; if (cmd_size < 2) { EXTERR("%s: invalid cmd_size %d\n", __func__, cmd_size); return -1; } if (flag) max_len = ext_config->table_init_on_cnt; else max_len = ext_config->table_init_off_cnt; while ((i + cmd_size) <= max_len) { type = table[i]; if (type == LCD_EXT_CMD_TYPE_END) break; if (lcd_debug_print_flag) { EXTPR("%s: step %d: type=0x%02x, cmd_size=%d\n", __func__, step, type, cmd_size); } if (type == LCD_EXT_CMD_TYPE_NONE) { /* do nothing */ } else if (type == LCD_EXT_CMD_TYPE_GPIO) { aml_lcd_extern_gpio_set(table[i+1], table[i+2]); if (cmd_size > 3) { if (table[i+3] > 0) mdelay(table[i+3]); } } else if (type == LCD_EXT_CMD_TYPE_DELAY) { delay_ms = 0; for (j = 0; j < (cmd_size - 1); j++) delay_ms += table[i+1+j]; if (delay_ms > 0) mdelay(delay_ms); } else if (type == LCD_EXT_CMD_TYPE_CMD) { ret = aml_lcd_extern_i2c_write(ext_config->i2c_bus, ext_config->i2c_addr, &table[i+1], (cmd_size-1)); } else if (type == LCD_EXT_CMD_TYPE_CMD_DELAY) { ret = aml_lcd_extern_i2c_write(ext_config->i2c_bus, ext_config->i2c_addr, &table[i+1], (cmd_size-2)); if (table[i+cmd_size-1] > 0) mdelay(table[i+cmd_size-1]); } else { EXTERR("%s: %s(%d: pwoer_type 0x%02x is invalid\n", __func__, ext_config->name, ext_config->index, type); } i += cmd_size; step++; } return ret; } static int lcd_extern_power_ctrl(int flag) { unsigned char *table; unsigned char cmd_size; int ret = 0; /* step 1: power prepare */ #ifdef LCD_EXT_I2C_PORT_INIT aml_lcd_extern_i2c_bus_change(ext_config->i2c_bus); #endif /* step 2: power cmd */ cmd_size = ext_config->cmd_size; if (flag) table = ext_config->table_init_on; else table = ext_config->table_init_off; if (cmd_size < 1) { EXTERR("%s: cmd_size %d is invalid\n", __func__, cmd_size); ret = -1; goto power_ctrl_next; } if (table == NULL) { EXTERR("%s: init_table %d is NULL\n", __func__, flag); ret = -1; goto power_ctrl_next; } if (cmd_size == LCD_EXT_CMD_SIZE_DYNAMIC) ret = lcd_extern_power_cmd_dynamic_size(table, flag); else ret = lcd_extern_power_cmd_fixed_size(table, flag); power_ctrl_next: /* step 3: power finish */ #ifdef LCD_EXT_I2C_PORT_INIT aml_lcd_extern_i2c_bus_recovery(); #endif if (ret) { EXTERR("%s: %s(%d): %d\n", __func__, ext_config->name, ext_config->index, flag); } else { EXTPR("%s: %s(%d): %d\n", __func__, ext_config->name, ext_config->index, flag); } return ret; } static int lcd_extern_power_on(void) { int ret; aml_lcd_extern_pinmux_set(1); ret = lcd_extern_power_ctrl(1); return ret; } static int lcd_extern_power_off(void) { int ret; ret = lcd_extern_power_ctrl(0); aml_lcd_extern_pinmux_set(0); return ret; } static int lcd_extern_driver_update(struct aml_lcd_extern_driver_s *ext_drv) { if (ext_drv == NULL) { EXTERR("%s driver is null\n", LCD_EXTERN_NAME); return -1; } if (ext_drv->config->table_init_loaded == 0) { ext_drv->config->cmd_size = LCD_EXTERN_CMD_SIZE; ext_drv->config->table_init_on = init_on_table; ext_config->table_init_on_cnt = sizeof(init_on_table); ext_drv->config->table_init_off = init_off_table; ext_config->table_init_off_cnt = sizeof(init_off_table); } ext_drv->reg_read = lcd_extern_reg_read; ext_drv->reg_write = lcd_extern_reg_write; ext_drv->power_on = lcd_extern_power_on; ext_drv->power_off = lcd_extern_power_off; return 0; } int aml_lcd_extern_i2c_T5800Q_probe(struct aml_lcd_extern_driver_s *ext_drv) { int ret = 0; ext_config = ext_drv->config; ret = lcd_extern_driver_update(ext_drv); if (lcd_debug_print_flag) EXTPR("%s: %d\n", __func__, ret); return ret; }
{ "language": "C" }
/* * Copyright 2018 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 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) OR AUTHOR(S) 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. * */ #ifndef __AMDGPU_JOB_H__ #define __AMDGPU_JOB_H__ /* bit set means command submit involves a preamble IB */ #define AMDGPU_PREAMBLE_IB_PRESENT (1 << 0) /* bit set means preamble IB is first presented in belonging context */ #define AMDGPU_PREAMBLE_IB_PRESENT_FIRST (1 << 1) /* bit set means context switch occured */ #define AMDGPU_HAVE_CTX_SWITCH (1 << 2) /* bit set means IB is preempted */ #define AMDGPU_IB_PREEMPTED (1 << 3) #define to_amdgpu_job(sched_job) \ container_of((sched_job), struct amdgpu_job, base) #define AMDGPU_JOB_GET_VMID(job) ((job) ? (job)->vmid : 0) struct amdgpu_fence; enum amdgpu_ib_pool_type; struct amdgpu_job { struct drm_sched_job base; struct amdgpu_vm *vm; struct amdgpu_sync sync; struct amdgpu_sync sched_sync; struct amdgpu_ib *ibs; struct dma_fence *fence; /* the hw fence */ uint32_t preamble_status; uint32_t preemption_status; uint32_t num_ibs; bool vm_needs_flush; uint64_t vm_pd_addr; unsigned vmid; unsigned pasid; uint32_t gds_base, gds_size; uint32_t gws_base, gws_size; uint32_t oa_base, oa_size; uint32_t vram_lost_counter; /* user fence handling */ uint64_t uf_addr; uint64_t uf_sequence; }; int amdgpu_job_alloc(struct amdgpu_device *adev, unsigned num_ibs, struct amdgpu_job **job, struct amdgpu_vm *vm); int amdgpu_job_alloc_with_ib(struct amdgpu_device *adev, unsigned size, enum amdgpu_ib_pool_type pool, struct amdgpu_job **job); void amdgpu_job_free_resources(struct amdgpu_job *job); void amdgpu_job_free(struct amdgpu_job *job); int amdgpu_job_submit(struct amdgpu_job *job, struct drm_sched_entity *entity, void *owner, struct dma_fence **f); int amdgpu_job_submit_direct(struct amdgpu_job *job, struct amdgpu_ring *ring, struct dma_fence **fence); void amdgpu_job_stop_all_jobs_on_sched(struct drm_gpu_scheduler *sched); #endif
{ "language": "C" }
/****************************************************************************** * $Id: ogrgeomfielddefn.cpp 28806 2015-03-28 14:37:47Z rouault $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: The OGRGeomFieldDefn class implementation. * Author: Even Rouault, <even dot rouault at mines dash paris dot org> * ****************************************************************************** * Copyright (c) 2013, Even Rouault <even dot rouault at mines-paris dot org> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "ogr_feature.h" #include "ogr_api.h" #include "ogr_p.h" #include "ograpispy.h" CPL_CVSID("$Id: ogrgeomfielddefn.cpp 28806 2015-03-28 14:37:47Z rouault $"); /************************************************************************/ /* OGRGeomFieldDefn() */ /************************************************************************/ /** * \brief Constructor. * * @param pszNameIn the name of the new field. * @param eGeomTypeIn the type of the new field. * * @since GDAL 1.11 */ OGRGeomFieldDefn::OGRGeomFieldDefn( const char * pszNameIn, OGRwkbGeometryType eGeomTypeIn ) { Initialize( pszNameIn, eGeomTypeIn ); } /************************************************************************/ /* OGRGeomFieldDefn() */ /************************************************************************/ /** * \brief Constructor. * * Create by cloning an existing geometry field definition. * * @param poPrototype the geometry field definition to clone. * * @since GDAL 1.11 */ OGRGeomFieldDefn::OGRGeomFieldDefn( OGRGeomFieldDefn *poPrototype ) { Initialize( poPrototype->GetNameRef(), poPrototype->GetType() ); SetSpatialRef( poPrototype->GetSpatialRef() ); SetNullable( poPrototype->IsNullable() ); } /************************************************************************/ /* OGR_GFld_Create() */ /************************************************************************/ /** * \brief Create a new field geometry definition. * * This function is the same as the CPP method OGRGeomFieldDefn::OGRGeomFieldDefn(). * * @param pszName the name of the new field definition. * @param eType the type of the new field definition. * @return handle to the new field definition. * * @since GDAL 1.11 */ OGRGeomFieldDefnH OGR_GFld_Create( const char *pszName, OGRwkbGeometryType eType ) { return (OGRGeomFieldDefnH) (new OGRGeomFieldDefn(pszName,eType)); } /************************************************************************/ /* Initialize() */ /************************************************************************/ void OGRGeomFieldDefn::Initialize( const char * pszNameIn, OGRwkbGeometryType eTypeIn ) { pszName = CPLStrdup( pszNameIn ); eGeomType = eTypeIn; poSRS = NULL; bIgnore = FALSE; bNullable = TRUE; } /************************************************************************/ /* ~OGRGeomFieldDefn() */ /************************************************************************/ OGRGeomFieldDefn::~OGRGeomFieldDefn() { CPLFree( pszName ); if( NULL != poSRS ) poSRS->Release(); } /************************************************************************/ /* OGR_GFld_Destroy() */ /************************************************************************/ /** * \brief Destroy a geometry field definition. * * @param hDefn handle to the geometry field definition to destroy. * * @since GDAL 1.11 */ void OGR_GFld_Destroy( OGRGeomFieldDefnH hDefn ) { VALIDATE_POINTER0( hDefn, "OGR_GFld_Destroy" ); delete (OGRGeomFieldDefn *) hDefn; } /************************************************************************/ /* SetName() */ /************************************************************************/ /** * \brief Reset the name of this field. * * This method is the same as the C function OGR_GFld_SetName(). * * @param pszNameIn the new name to apply. * * @since GDAL 1.11 */ void OGRGeomFieldDefn::SetName( const char * pszNameIn ) { CPLFree( pszName ); pszName = CPLStrdup( pszNameIn ); } /************************************************************************/ /* OGR_GFld_SetName() */ /************************************************************************/ /** * \brief Reset the name of this field. * * This function is the same as the CPP method OGRGeomFieldDefn::SetName(). * * @param hDefn handle to the geometry field definition to apply the new name to. * @param pszName the new name to apply. * * @since GDAL 1.11 */ void OGR_GFld_SetName( OGRGeomFieldDefnH hDefn, const char *pszName ) { VALIDATE_POINTER0( hDefn, "OGR_GFld_SetName" ); ((OGRGeomFieldDefn *) hDefn)->SetName( pszName ); } /************************************************************************/ /* GetNameRef() */ /************************************************************************/ /** * \fn const char *OGRGeomFieldDefn::GetNameRef(); * * \brief Fetch name of this field. * * This method is the same as the C function OGR_GFld_GetNameRef(). * * @return pointer to an internal name string that should not be freed or * modified. * * @since GDAL 1.11 */ /************************************************************************/ /* OGR_GFld_GetNameRef() */ /************************************************************************/ /** * \brief Fetch name of this field. * * This function is the same as the CPP method OGRGeomFieldDefn::GetNameRef(). * * @param hDefn handle to the geometry field definition. * @return the name of the geometry field definition. * * @since GDAL 1.11 */ const char *OGR_GFld_GetNameRef( OGRGeomFieldDefnH hDefn ) { VALIDATE_POINTER1( hDefn, "OGR_GFld_GetNameRef", "" ); #ifdef OGRAPISPY_ENABLED if( bOGRAPISpyEnabled ) OGRAPISpy_GFld_GetXXXX(hDefn, "GetNameRef"); #endif return ((OGRGeomFieldDefn *) hDefn)->GetNameRef(); } /************************************************************************/ /* GetType() */ /************************************************************************/ /** * \fn OGRwkbGeometryType OGRGeomFieldDefn::GetType(); * * \brief Fetch geometry type of this field. * * This method is the same as the C function OGR_GFld_GetType(). * * @return field geometry type. * * @since GDAL 1.11 */ /************************************************************************/ /* OGR_GFld_GetType() */ /************************************************************************/ /** * \brief Fetch geometry type of this field. * * This function is the same as the CPP method OGRGeomFieldDefn::GetType(). * * @param hDefn handle to the geometry field definition to get type from. * @return field geometry type. * * @since GDAL 1.11 */ OGRwkbGeometryType OGR_GFld_GetType( OGRGeomFieldDefnH hDefn ) { VALIDATE_POINTER1( hDefn, "OGR_GFld_GetType", wkbUnknown ); #ifdef OGRAPISPY_ENABLED if( bOGRAPISpyEnabled ) OGRAPISpy_GFld_GetXXXX(hDefn, "GetType"); #endif OGRwkbGeometryType eType = ((OGRGeomFieldDefn *) hDefn)->GetType(); if( OGR_GT_IsNonLinear(eType) && !OGRGetNonLinearGeometriesEnabledFlag() ) { eType = OGR_GT_GetLinear(eType); } return eType; } /************************************************************************/ /* SetType() */ /************************************************************************/ /** * \fn void OGRGeomFieldDefn::SetType( OGRwkbGeometryType eType ); * * \brief Set the geometry type of this field. * This should never be done to an OGRGeomFieldDefn * that is already part of an OGRFeatureDefn. * * This method is the same as the C function OGR_GFld_SetType(). * * @param eType the new field geometry type. * * @since GDAL 1.11 */ void OGRGeomFieldDefn::SetType( OGRwkbGeometryType eTypeIn ) { eGeomType = eTypeIn; } /************************************************************************/ /* OGR_GFld_SetType() */ /************************************************************************/ /** * \brief Set the geometry type of this field. * This should never be done to an OGRGeomFieldDefn * that is already part of an OGRFeatureDefn. * * This function is the same as the CPP method OGRGeomFieldDefn::SetType(). * * @param hDefn handle to the geometry field definition to set type to. * @param eType the new field geometry type. * * @since GDAL 1.11 */ void OGR_GFld_SetType( OGRGeomFieldDefnH hDefn, OGRwkbGeometryType eType ) { VALIDATE_POINTER0( hDefn, "OGR_GFld_SetType" ); ((OGRGeomFieldDefn *) hDefn)->SetType( eType ); } /************************************************************************/ /* IsIgnored() */ /************************************************************************/ /** * \fn int OGRGeomFieldDefn::IsIgnored(); * * \brief Return whether this field should be omitted when fetching features * * This method is the same as the C function OGR_GFld_IsIgnored(). * * @return ignore state * * @since GDAL 1.11 */ /************************************************************************/ /* OGR_GFld_IsIgnored() */ /************************************************************************/ /** * \brief Return whether this field should be omitted when fetching features * * This method is the same as the C++ method OGRGeomFieldDefn::IsIgnored(). * * @param hDefn handle to the geometry field definition * @return ignore state * * @since GDAL 1.11 */ int OGR_GFld_IsIgnored( OGRGeomFieldDefnH hDefn ) { VALIDATE_POINTER1( hDefn, "OGR_GFld_IsIgnored", FALSE ); return ((OGRGeomFieldDefn *) hDefn)->IsIgnored(); } /************************************************************************/ /* SetIgnored() */ /************************************************************************/ /** * \fn void OGRGeomFieldDefn::SetIgnored( int ignore ); * * \brief Set whether this field should be omitted when fetching features * * This method is the same as the C function OGR_GFld_SetIgnored(). * * @param ignore ignore state * * @since GDAL 1.11 */ /************************************************************************/ /* OGR_GFld_SetIgnored() */ /************************************************************************/ /** * \brief Set whether this field should be omitted when fetching features * * This method is the same as the C++ method OGRGeomFieldDefn::SetIgnored(). * * @param hDefn handle to the geometry field definition * @param ignore ignore state * * @since GDAL 1.11 */ void OGR_GFld_SetIgnored( OGRGeomFieldDefnH hDefn, int ignore ) { VALIDATE_POINTER0( hDefn, "OGR_GFld_SetIgnored" ); ((OGRGeomFieldDefn *) hDefn)->SetIgnored( ignore ); } /************************************************************************/ /* GetSpatialRef() */ /************************************************************************/ /** * \brief Fetch spatial reference system of this field. * * This method is the same as the C function OGR_GFld_GetSpatialRef(). * * @return field spatial reference system. * * @since GDAL 1.11 */ OGRSpatialReference* OGRGeomFieldDefn::GetSpatialRef() { return poSRS; } /************************************************************************/ /* OGR_GFld_GetSpatialRef() */ /************************************************************************/ /** * \brief Fetch spatial reference system of this field. * * This function is the same as the C++ method OGRGeomFieldDefn::GetSpatialRef(). * * @param hDefn handle to the geometry field definition * * @return field spatial reference system. * * @since GDAL 1.11 */ OGRSpatialReferenceH OGR_GFld_GetSpatialRef( OGRGeomFieldDefnH hDefn ) { VALIDATE_POINTER1( hDefn, "OGR_GFld_GetSpatialRef", NULL ); #ifdef OGRAPISPY_ENABLED if( bOGRAPISpyEnabled ) OGRAPISpy_GFld_GetXXXX(hDefn, "GetSpatialRef"); #endif return (OGRSpatialReferenceH) ((OGRGeomFieldDefn *) hDefn)->GetSpatialRef(); } /************************************************************************/ /* SetSpatialRef() */ /************************************************************************/ /** * \brief Set the spatial reference of this field. * * This method is the same as the C function OGR_GFld_SetSpatialRef(). * * This method drops the reference of the previously set SRS object and * acquires a new reference on the passed object (if non-NULL). * * @param poSRSIn the new SRS to apply. * * @since GDAL 1.11 */ void OGRGeomFieldDefn::SetSpatialRef(OGRSpatialReference* poSRSIn) { if( poSRS != NULL ) poSRS->Release(); poSRS = poSRSIn; if( poSRS != NULL ) poSRS->Reference(); } /************************************************************************/ /* OGR_GFld_SetSpatialRef() */ /************************************************************************/ /** * \brief Set the spatial reference of this field. * * This function is the same as the C++ method OGRGeomFieldDefn::SetSpatialRef(). * * This function drops the reference of the previously set SRS object and * acquires a new reference on the passed object (if non-NULL). * * @param hDefn handle to the geometry field definition * @param hSRS the new SRS to apply. * * @since GDAL 1.11 */ void OGR_GFld_SetSpatialRef( OGRGeomFieldDefnH hDefn, OGRSpatialReferenceH hSRS ) { VALIDATE_POINTER0( hDefn, "OGR_GFld_SetSpatialRef" ); ((OGRGeomFieldDefn *) hDefn)->SetSpatialRef( (OGRSpatialReference*) hSRS ); } /************************************************************************/ /* IsSame() */ /************************************************************************/ /** * \brief Test if the geometry field definition is identical to the other one. * * @param poOtherFieldDefn the other field definition to compare to. * @return TRUE if the geometry field definition is identical to the other one. * * @since GDAL 1.11 */ int OGRGeomFieldDefn::IsSame( OGRGeomFieldDefn * poOtherFieldDefn ) { if( !(strcmp(GetNameRef(), poOtherFieldDefn->GetNameRef()) == 0 && GetType() == poOtherFieldDefn->GetType() && IsNullable() == poOtherFieldDefn->IsNullable()) ) return FALSE; OGRSpatialReference* poMySRS = GetSpatialRef(); OGRSpatialReference* poOtherSRS = poOtherFieldDefn->GetSpatialRef(); return ((poMySRS == poOtherSRS) || (poMySRS != NULL && poOtherSRS != NULL && poMySRS->IsSame(poOtherSRS))); } /************************************************************************/ /* IsNullable() */ /************************************************************************/ /** * \fn int OGRGeomFieldDefn::IsNullable() const * * \brief Return whether this geometry field can receive null values. * * By default, fields are nullable. * * Even if this method returns FALSE (i.e not-nullable field), it doesn't mean * that OGRFeature::IsFieldSet() will necessary return TRUE, as fields can be * temporary unset and null/not-null validation is usually done when * OGRLayer::CreateFeature()/SetFeature() is called. * * Note that not-nullable geometry fields might also contain 'empty' geometries. * * This method is the same as the C function OGR_GFld_IsNullable(). * * @return TRUE if the field is authorized to be null. * @since GDAL 2.0 */ /************************************************************************/ /* OGR_GFld_IsNullable() */ /************************************************************************/ /** * \brief Return whether this geometry field can receive null values. * * By default, fields are nullable. * * Even if this method returns FALSE (i.e not-nullable field), it doesn't mean * that OGRFeature::IsFieldSet() will necessary return TRUE, as fields can be * temporary unset and null/not-null validation is usually done when * OGRLayer::CreateFeature()/SetFeature() is called. * * Note that not-nullable geometry fields might also contain 'empty' geometries. * * This method is the same as the C++ method OGRGeomFieldDefn::IsNullable(). * * @param hDefn handle to the field definition * @return TRUE if the field is authorized to be null. * @since GDAL 2.0 */ int OGR_GFld_IsNullable( OGRGeomFieldDefnH hDefn ) { return ((OGRGeomFieldDefn *) hDefn)->IsNullable(); } /************************************************************************/ /* SetNullable() */ /************************************************************************/ /** * \fn void OGRGeomFieldDefn::SetNullable( int bNullableIn ); * * \brief Set whether this geometry field can receive null values. * * By default, fields are nullable, so this method is generally called with FALSE * to set a not-null constraint. * * Drivers that support writing not-null constraint will advertize the * GDAL_DCAP_NOTNULL_GEOMFIELDS driver metadata item. * * This method is the same as the C function OGR_GFld_SetNullable(). * * @param bNullableIn FALSE if the field must have a not-null constraint. * @since GDAL 2.0 */ /************************************************************************/ /* OGR_GFld_SetNullable() */ /************************************************************************/ /** * \brief Set whether this geometry field can receive null values. * * By default, fields are nullable, so this method is generally called with FALSE * to set a not-null constraint. * * Drivers that support writing not-null constraint will advertize the * GDAL_DCAP_NOTNULL_GEOMFIELDS driver metadata item. * * This method is the same as the C++ method OGRGeomFieldDefn::SetNullable(). * * @param hDefn handle to the field definition * @param bNullableIn FALSE if the field must have a not-null constraint. * @since GDAL 2.0 */ void OGR_GFld_SetNullable( OGRGeomFieldDefnH hDefn, int bNullableIn ) { ((OGRGeomFieldDefn *) hDefn)->SetNullable( bNullableIn ); }
{ "language": "C" }
/*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef OPENCV_FLANN_SIMPLEX_DOWNHILL_H_ #define OPENCV_FLANN_SIMPLEX_DOWNHILL_H_ namespace cvflann { /** Adds val to array vals (and point to array points) and keeping the arrays sorted by vals. */ template <typename T> void addValue(int pos, float val, float* vals, T* point, T* points, int n) { vals[pos] = val; for (int i=0; i<n; ++i) { points[pos*n+i] = point[i]; } // bubble down int j=pos; while (j>0 && vals[j]<vals[j-1]) { swap(vals[j],vals[j-1]); for (int i=0; i<n; ++i) { swap(points[j*n+i],points[(j-1)*n+i]); } --j; } } /** Simplex downhill optimization function. Preconditions: points is a 2D mattrix of size (n+1) x n func is the cost function taking n an array of n params and returning float vals is the cost function in the n+1 simplex points, if NULL it will be computed Postcondition: returns optimum value and points[0..n] are the optimum parameters */ template <typename T, typename F> float optimizeSimplexDownhill(T* points, int n, F func, float* vals = NULL ) { const int MAX_ITERATIONS = 10; assert(n>0); T* p_o = new T[n]; T* p_r = new T[n]; T* p_e = new T[n]; int alpha = 1; int iterations = 0; bool ownVals = false; if (vals == NULL) { ownVals = true; vals = new float[n+1]; for (int i=0; i<n+1; ++i) { float val = func(points+i*n); addValue(i, val, vals, points+i*n, points, n); } } int nn = n*n; while (true) { if (iterations++ > MAX_ITERATIONS) break; // compute average of simplex points (except the highest point) for (int j=0; j<n; ++j) { p_o[j] = 0; for (int i=0; i<n; ++i) { p_o[i] += points[j*n+i]; } } for (int i=0; i<n; ++i) { p_o[i] /= n; } bool converged = true; for (int i=0; i<n; ++i) { if (p_o[i] != points[nn+i]) { converged = false; } } if (converged) break; // trying a reflection for (int i=0; i<n; ++i) { p_r[i] = p_o[i] + alpha*(p_o[i]-points[nn+i]); } float val_r = func(p_r); if ((val_r>=vals[0])&&(val_r<vals[n])) { // reflection between second highest and lowest // add it to the simplex Logger::info("Choosing reflection\n"); addValue(n, val_r,vals, p_r, points, n); continue; } if (val_r<vals[0]) { // value is smaller than smalest in simplex // expand some more to see if it drops further for (int i=0; i<n; ++i) { p_e[i] = 2*p_r[i]-p_o[i]; } float val_e = func(p_e); if (val_e<val_r) { Logger::info("Choosing reflection and expansion\n"); addValue(n, val_e,vals,p_e,points,n); } else { Logger::info("Choosing reflection\n"); addValue(n, val_r,vals,p_r,points,n); } continue; } if (val_r>=vals[n]) { for (int i=0; i<n; ++i) { p_e[i] = (p_o[i]+points[nn+i])/2; } float val_e = func(p_e); if (val_e<vals[n]) { Logger::info("Choosing contraction\n"); addValue(n,val_e,vals,p_e,points,n); continue; } } { Logger::info("Full contraction\n"); for (int j=1; j<=n; ++j) { for (int i=0; i<n; ++i) { points[j*n+i] = (points[j*n+i]+points[i])/2; } float val = func(points+j*n); addValue(j,val,vals,points+j*n,points,n); } } } float bestVal = vals[0]; delete[] p_r; delete[] p_o; delete[] p_e; if (ownVals) delete[] vals; return bestVal; } } #endif //OPENCV_FLANN_SIMPLEX_DOWNHILL_H_
{ "language": "C" }
/****************************************************************************** * * Module Name: dsargs - Support for execution of dynamic arguments for static * objects (regions, fields, buffer fields, etc.) * *****************************************************************************/ /* * Copyright (C) 2000 - 2011, Intel Corp. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * * NO WARRANTY * 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 MERCHANTIBILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES. */ #define __DSARGS_C__ #include <contrib/dev/acpica/include/acpi.h> #include <contrib/dev/acpica/include/accommon.h> #include <contrib/dev/acpica/include/acparser.h> #include <contrib/dev/acpica/include/amlcode.h> #include <contrib/dev/acpica/include/acdispat.h> #include <contrib/dev/acpica/include/acnamesp.h> #define _COMPONENT ACPI_DISPATCHER ACPI_MODULE_NAME ("dsargs") /* Local prototypes */ static ACPI_STATUS AcpiDsExecuteArguments ( ACPI_NAMESPACE_NODE *Node, ACPI_NAMESPACE_NODE *ScopeNode, UINT32 AmlLength, UINT8 *AmlStart); /******************************************************************************* * * FUNCTION: AcpiDsExecuteArguments * * PARAMETERS: Node - Object NS node * ScopeNode - Parent NS node * AmlLength - Length of executable AML * AmlStart - Pointer to the AML * * RETURN: Status. * * DESCRIPTION: Late (deferred) execution of region or field arguments * ******************************************************************************/ static ACPI_STATUS AcpiDsExecuteArguments ( ACPI_NAMESPACE_NODE *Node, ACPI_NAMESPACE_NODE *ScopeNode, UINT32 AmlLength, UINT8 *AmlStart) { ACPI_STATUS Status; ACPI_PARSE_OBJECT *Op; ACPI_WALK_STATE *WalkState; ACPI_FUNCTION_TRACE (DsExecuteArguments); /* Allocate a new parser op to be the root of the parsed tree */ Op = AcpiPsAllocOp (AML_INT_EVAL_SUBTREE_OP); if (!Op) { return_ACPI_STATUS (AE_NO_MEMORY); } /* Save the Node for use in AcpiPsParseAml */ Op->Common.Node = ScopeNode; /* Create and initialize a new parser state */ WalkState = AcpiDsCreateWalkState (0, NULL, NULL, NULL); if (!WalkState) { Status = AE_NO_MEMORY; goto Cleanup; } Status = AcpiDsInitAmlWalk (WalkState, Op, NULL, AmlStart, AmlLength, NULL, ACPI_IMODE_LOAD_PASS1); if (ACPI_FAILURE (Status)) { AcpiDsDeleteWalkState (WalkState); goto Cleanup; } /* Mark this parse as a deferred opcode */ WalkState->ParseFlags = ACPI_PARSE_DEFERRED_OP; WalkState->DeferredNode = Node; /* Pass1: Parse the entire declaration */ Status = AcpiPsParseAml (WalkState); if (ACPI_FAILURE (Status)) { goto Cleanup; } /* Get and init the Op created above */ Op->Common.Node = Node; AcpiPsDeleteParseTree (Op); /* Evaluate the deferred arguments */ Op = AcpiPsAllocOp (AML_INT_EVAL_SUBTREE_OP); if (!Op) { return_ACPI_STATUS (AE_NO_MEMORY); } Op->Common.Node = ScopeNode; /* Create and initialize a new parser state */ WalkState = AcpiDsCreateWalkState (0, NULL, NULL, NULL); if (!WalkState) { Status = AE_NO_MEMORY; goto Cleanup; } /* Execute the opcode and arguments */ Status = AcpiDsInitAmlWalk (WalkState, Op, NULL, AmlStart, AmlLength, NULL, ACPI_IMODE_EXECUTE); if (ACPI_FAILURE (Status)) { AcpiDsDeleteWalkState (WalkState); goto Cleanup; } /* Mark this execution as a deferred opcode */ WalkState->DeferredNode = Node; Status = AcpiPsParseAml (WalkState); Cleanup: AcpiPsDeleteParseTree (Op); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsGetBufferFieldArguments * * PARAMETERS: ObjDesc - A valid BufferField object * * RETURN: Status. * * DESCRIPTION: Get BufferField Buffer and Index. This implements the late * evaluation of these field attributes. * ******************************************************************************/ ACPI_STATUS AcpiDsGetBufferFieldArguments ( ACPI_OPERAND_OBJECT *ObjDesc) { ACPI_OPERAND_OBJECT *ExtraDesc; ACPI_NAMESPACE_NODE *Node; ACPI_STATUS Status; ACPI_FUNCTION_TRACE_PTR (DsGetBufferFieldArguments, ObjDesc); if (ObjDesc->Common.Flags & AOPOBJ_DATA_VALID) { return_ACPI_STATUS (AE_OK); } /* Get the AML pointer (method object) and BufferField node */ ExtraDesc = AcpiNsGetSecondaryObject (ObjDesc); Node = ObjDesc->BufferField.Node; ACPI_DEBUG_EXEC (AcpiUtDisplayInitPathname (ACPI_TYPE_BUFFER_FIELD, Node, NULL)); ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "[%4.4s] BufferField Arg Init\n", AcpiUtGetNodeName (Node))); /* Execute the AML code for the TermArg arguments */ Status = AcpiDsExecuteArguments (Node, Node->Parent, ExtraDesc->Extra.AmlLength, ExtraDesc->Extra.AmlStart); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsGetBankFieldArguments * * PARAMETERS: ObjDesc - A valid BankField object * * RETURN: Status. * * DESCRIPTION: Get BankField BankValue. This implements the late * evaluation of these field attributes. * ******************************************************************************/ ACPI_STATUS AcpiDsGetBankFieldArguments ( ACPI_OPERAND_OBJECT *ObjDesc) { ACPI_OPERAND_OBJECT *ExtraDesc; ACPI_NAMESPACE_NODE *Node; ACPI_STATUS Status; ACPI_FUNCTION_TRACE_PTR (DsGetBankFieldArguments, ObjDesc); if (ObjDesc->Common.Flags & AOPOBJ_DATA_VALID) { return_ACPI_STATUS (AE_OK); } /* Get the AML pointer (method object) and BankField node */ ExtraDesc = AcpiNsGetSecondaryObject (ObjDesc); Node = ObjDesc->BankField.Node; ACPI_DEBUG_EXEC (AcpiUtDisplayInitPathname (ACPI_TYPE_LOCAL_BANK_FIELD, Node, NULL)); ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "[%4.4s] BankField Arg Init\n", AcpiUtGetNodeName (Node))); /* Execute the AML code for the TermArg arguments */ Status = AcpiDsExecuteArguments (Node, Node->Parent, ExtraDesc->Extra.AmlLength, ExtraDesc->Extra.AmlStart); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsGetBufferArguments * * PARAMETERS: ObjDesc - A valid Buffer object * * RETURN: Status. * * DESCRIPTION: Get Buffer length and initializer byte list. This implements * the late evaluation of these attributes. * ******************************************************************************/ ACPI_STATUS AcpiDsGetBufferArguments ( ACPI_OPERAND_OBJECT *ObjDesc) { ACPI_NAMESPACE_NODE *Node; ACPI_STATUS Status; ACPI_FUNCTION_TRACE_PTR (DsGetBufferArguments, ObjDesc); if (ObjDesc->Common.Flags & AOPOBJ_DATA_VALID) { return_ACPI_STATUS (AE_OK); } /* Get the Buffer node */ Node = ObjDesc->Buffer.Node; if (!Node) { ACPI_ERROR ((AE_INFO, "No pointer back to namespace node in buffer object %p", ObjDesc)); return_ACPI_STATUS (AE_AML_INTERNAL); } ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Buffer Arg Init\n")); /* Execute the AML code for the TermArg arguments */ Status = AcpiDsExecuteArguments (Node, Node, ObjDesc->Buffer.AmlLength, ObjDesc->Buffer.AmlStart); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsGetPackageArguments * * PARAMETERS: ObjDesc - A valid Package object * * RETURN: Status. * * DESCRIPTION: Get Package length and initializer byte list. This implements * the late evaluation of these attributes. * ******************************************************************************/ ACPI_STATUS AcpiDsGetPackageArguments ( ACPI_OPERAND_OBJECT *ObjDesc) { ACPI_NAMESPACE_NODE *Node; ACPI_STATUS Status; ACPI_FUNCTION_TRACE_PTR (DsGetPackageArguments, ObjDesc); if (ObjDesc->Common.Flags & AOPOBJ_DATA_VALID) { return_ACPI_STATUS (AE_OK); } /* Get the Package node */ Node = ObjDesc->Package.Node; if (!Node) { ACPI_ERROR ((AE_INFO, "No pointer back to namespace node in package %p", ObjDesc)); return_ACPI_STATUS (AE_AML_INTERNAL); } ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Package Arg Init\n")); /* Execute the AML code for the TermArg arguments */ Status = AcpiDsExecuteArguments (Node, Node, ObjDesc->Package.AmlLength, ObjDesc->Package.AmlStart); return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsGetRegionArguments * * PARAMETERS: ObjDesc - A valid region object * * RETURN: Status. * * DESCRIPTION: Get region address and length. This implements the late * evaluation of these region attributes. * ******************************************************************************/ ACPI_STATUS AcpiDsGetRegionArguments ( ACPI_OPERAND_OBJECT *ObjDesc) { ACPI_NAMESPACE_NODE *Node; ACPI_STATUS Status; ACPI_OPERAND_OBJECT *ExtraDesc; ACPI_FUNCTION_TRACE_PTR (DsGetRegionArguments, ObjDesc); if (ObjDesc->Region.Flags & AOPOBJ_DATA_VALID) { return_ACPI_STATUS (AE_OK); } ExtraDesc = AcpiNsGetSecondaryObject (ObjDesc); if (!ExtraDesc) { return_ACPI_STATUS (AE_NOT_EXIST); } /* Get the Region node */ Node = ObjDesc->Region.Node; ACPI_DEBUG_EXEC (AcpiUtDisplayInitPathname (ACPI_TYPE_REGION, Node, NULL)); ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "[%4.4s] OpRegion Arg Init at AML %p\n", AcpiUtGetNodeName (Node), ExtraDesc->Extra.AmlStart)); /* Execute the argument AML */ Status = AcpiDsExecuteArguments (Node, Node->Parent, ExtraDesc->Extra.AmlLength, ExtraDesc->Extra.AmlStart); return_ACPI_STATUS (Status); }
{ "language": "C" }
/* * Simple SRAM allocator * * Copyright (C) 2008 Atmel Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef __ASM_AVR32_ARCH_SRAM_H #define __ASM_AVR32_ARCH_SRAM_H #include <linux/genalloc.h> extern struct gen_pool *sram_pool; static inline unsigned long sram_alloc(size_t len) { if (!sram_pool) return 0UL; return gen_pool_alloc(sram_pool, len); } static inline void sram_free(unsigned long addr, size_t len) { return gen_pool_free(sram_pool, addr, len); } #endif /* __ASM_AVR32_ARCH_SRAM_H */
{ "language": "C" }
#define _GNU_SOURCE #include <strings.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/queue.h> #include <stdio.h> #include <event2/event.h> #include <event2/buffer.h> #include <event2/http.h> #include <event2/dns.h> #include <event2/http_struct.h> #include <event2/bufferevent.h> #include <event2/keyvalq_struct.h> #include <lwip/tcp.h> #include "http/http.h" #include "evhttp_extra.h" #ifndef LIBEVENT_TEST #include "util/lwipevbuf_bev_join.h" #include "util/lwipevbuf.h" #else #include "bufferevent_join.h" #endif #ifndef PACKAGE #define PACKAGE "util/libevent-http" #endif #ifndef VERSION #define VERSION "0.1" #endif struct evhttp_proxy_request { #ifndef LIBEVENT_TEST struct lwipevbuf *server_bev; #else struct bufferevent *server_bev; #endif struct evhttp_request *server_req; struct evhttp_request *client_req; }; struct http_proxy { #ifdef LIBEVENT_TEST struct evdns_base *dnsbase; #endif struct evhttp *evh; int keep_alive; }; static void client_send_error(struct evhttp_request *req, int error, const char *format, ...) { struct evbuffer *buf = evbuffer_new(); va_list args; evhttp_response_code_(req, error, NULL); evbuffer_add_printf(buf, "<html><head><title>%d %s</title></head><body>", error, req->response_code_line); va_start(args, format); evbuffer_add_vprintf(buf, format, args); va_end(args); evbuffer_add_printf(buf, "</body></html>"); evhttp_send_page_(req, buf); evbuffer_free(buf); } static void client_req_eof(struct bufferevent *bev, void *ctx) { struct evhttp_connection *evcon = ctx; evhttp_connection_free(evcon); } static void proxy_req_join(struct evhttp_proxy_request *proxy_req) { struct evhttp_connection *client_evcon = proxy_req->client_req->evcon; struct bufferevent *client_bev = evhttp_connection_get_bufferevent(client_evcon); evhttp_connection_set_closecb(client_evcon, NULL, NULL); #ifndef LIBEVENT_TEST lwipevbuf_bev_join(client_bev, proxy_req->server_bev, 256*1024, client_req_eof, client_evcon, NULL, NULL, NULL, NULL); #else bufferevent_join(client_bev, proxy_req->server_bev, 256*1024, client_req_eof, client_evcon, NULL, NULL, NULL, NULL); #endif if (proxy_req->server_req) evhttp_request_free(proxy_req->server_req); free(proxy_req); } static void remove_headers(struct evkeyvalq *headers, const char *key) { const char *val; char *s, *n, *sdup; /* remove connection headers */ val = evhttp_find_header(headers, key); if (!val) return; sdup = strdup(val); for (n = sdup, s = sdup; n; s = n + 1) { n = strpbrk(s, "()<>@,;:\\\"/[]?={} \t"); if (n) *n = '\0'; if (*s) evhttp_remove_header(headers, s); } free(sdup); evhttp_remove_header(headers, key); } static int proxy_req_server_headers_done(struct evhttp_proxy_request *proxy_req) { struct evhttp_request *client_req = proxy_req->client_req; struct bufferevent *client_bev; struct evhttp_connection *client_evcon; struct evhttp_request *server_req = proxy_req->server_req; struct evbuffer *client_output; struct evkeyval *header; const char *via; const char *hostname = "unknown"; evhttp_response_code_(client_req, server_req->response_code, server_req->response_code_line); client_evcon = evhttp_request_get_connection(client_req); client_bev = evhttp_connection_get_bufferevent(client_evcon); client_output = bufferevent_get_output(client_bev); evbuffer_add_printf(client_output, "HTTP/%d.%d %d %s\r\n", client_req->major, client_req->minor, client_req->response_code, client_req->response_code_line); remove_headers(client_req->input_headers, "connection"); remove_headers(client_req->input_headers, "proxy-connection"); evhttp_remove_header(server_req->input_headers, "keep-alive"); evhttp_remove_header(server_req->input_headers, "proxy-authenticate"); evhttp_remove_header(server_req->input_headers, "proxy-authorization"); /* Add our via header */ via = evhttp_find_header(server_req->input_headers, "via"); if (via) { evbuffer_add_printf(client_output, "Via: %s, ", via); evhttp_remove_header(server_req->input_headers, "via"); } else evbuffer_add_printf(client_output, "Via: "); evbuffer_add_printf(client_output, "%d.%d %s (%s/%s)\r\n", server_req->major, server_req->minor, hostname, PACKAGE, VERSION); TAILQ_FOREACH(header, server_req->input_headers, next) { evbuffer_add_printf(client_output, "%s: %s\r\n", header->key, header->value); } evbuffer_add(client_output, "\r\n", 2); /* Queue any data the server already sent */ bufferevent_write_buffer(client_bev, evhttp_request_get_input_buffer(server_req)); proxy_req_join(proxy_req); return 0; } static void proxy_req_client_closecb(struct evhttp_connection *evcon, void *ctx) { struct evhttp_proxy_request *proxy_req = ctx; #ifndef LIBEVENT_TEST lwipevbuf_free(proxy_req->server_bev); #else bufferevent_free(proxy_req->server_bev); #endif if (proxy_req->server_req) evhttp_request_free(proxy_req->server_req); free(proxy_req); } static void proxy_req_free(struct evhttp_proxy_request *proxy_req) { struct evhttp_connection *client_evcon; #ifndef LIBEVENT_TEST lwipevbuf_free(proxy_req->server_bev); #else bufferevent_free(proxy_req->server_bev); #endif if (proxy_req->server_req) evhttp_request_free(proxy_req->server_req); client_evcon = evhttp_request_get_connection(proxy_req->client_req); evhttp_connection_set_closecb(client_evcon, NULL, NULL); if (!proxy_req->client_req->userdone) evhttp_connection_free(client_evcon); free(proxy_req); } static void #ifndef LIBEVENT_TEST proxy_req_eventcb(struct lwipevbuf *bev, short what, void *ctx) #else proxy_req_eventcb(struct bufferevent *bev, short what, void *ctx) #endif { struct evhttp_proxy_request *proxy_req = ctx; struct evhttp_request *client_req = proxy_req->client_req; if (what & BEV_EVENT_TIMEOUT) { client_send_error(client_req, 403, "Server communication timed out"); } else if (what & BEV_EVENT_ERROR) { const char *str; #ifndef LIBEVENT_TEST str = evutil_socket_error_to_string(EVUTIL_SOCKET_ERROR()); #elif defined(LWIP_DEBUG) str = lwip_strerr(bev->tcp_err); #else str = "unspecified"; #endif if (what & BEV_EVENT_READING) { client_send_error(client_req, 503, "Error reading data from server: %s", str); } else { client_send_error(client_req, 503, "Error writing data to server: %s", str); } } else if (what & BEV_EVENT_EOF) { client_send_error(client_req, 500, "EOF while establishing communication with server"); } proxy_req_free(proxy_req); } static void #ifndef LIBEVENT_TEST proxy_req_read_header(struct lwipevbuf *bufev, void *arg) #else proxy_req_read_header(struct bufferevent *bufev, void *arg) #endif { enum message_read_status res; struct evhttp_proxy_request *proxy_req = arg; struct evhttp_request *req = proxy_req->server_req; struct evhttp_request *client_req = proxy_req->client_req; struct evbuffer *input; #ifndef LIBEVENT_TEST input = bufev->input_buffer; #else input = bufferevent_get_input(bufev); #endif res = evhttp_parse_headers_(req, input); if (res == DATA_CORRUPTED) { client_send_error(client_req, 503, "Error parsing HTTP headers from server"); proxy_req_free(proxy_req); return; } else if (res == DATA_TOO_LONG) { /* Error while reading, terminate */ client_send_error(client_req, 503, "HTTP headers from server too long"); proxy_req_free(proxy_req); return; } else if (res == MORE_DATA_EXPECTED) { /* Need more header lines */ return; } proxy_req_server_headers_done(proxy_req); } static void #ifndef LIBEVENT_TEST proxy_req_read_firstline(struct lwipevbuf *bufev, void *arg) #else proxy_req_read_firstline(struct bufferevent *bufev, void *arg) #endif { enum message_read_status res; struct evhttp_proxy_request *proxy_req = arg; struct evhttp_request *req = proxy_req->server_req; struct evhttp_request *client_req = proxy_req->client_req; struct evbuffer *input; #ifndef LIBEVENT_TEST input = bufev->input_buffer; #else input = bufferevent_get_input(bufev); #endif res = evhttp_parse_firstline_(req, input); if (res == DATA_CORRUPTED) { client_send_error(client_req, 503, "Error parsing response line from server"); proxy_req_free(proxy_req); return; } else if (res == DATA_TOO_LONG) { client_send_error(client_req, 503, "Response line from server too long"); proxy_req_free(proxy_req); return; } else if (res == MORE_DATA_EXPECTED) { /* Need more header lines */ return; } #ifndef LIBEVENT_TEST lwipevbuf_setcb(bufev, proxy_req_read_header, NULL, proxy_req_eventcb, proxy_req); #else bufferevent_setcb(bufev, proxy_req_read_header, NULL, proxy_req_eventcb, proxy_req); #endif proxy_req_read_header(bufev, arg); } static void proxy_req_connected(struct evhttp_proxy_request *proxy_req) { #ifndef LIBEVENT_TEST struct lwipevbuf *server_bev = proxy_req->server_bev; struct evbuffer *server_output = server_bev->output_buffer; #else struct bufferevent *server_bev = proxy_req->server_bev; struct evbuffer *server_output = bufferevent_get_output(server_bev); #endif struct evhttp_request *client_req = proxy_req->client_req; struct evhttp_connection *client_evcon; client_evcon = evhttp_request_get_connection(client_req); if (client_req->type != EVHTTP_REQ_CONNECT) { struct evhttp_request *server_req; struct evkeyval *header; const char *hostname = "unknown"; const char *via; const char *url; const char *host; host = evhttp_request_get_host(client_req); url = evhttp_request_get_uri(client_req); server_req = evhttp_request_new(NULL, NULL); server_req->kind = EVHTTP_RESPONSE; server_req->type = client_req->type; server_req->uri = strdup(url); server_req->major = client_req->major; server_req->minor = client_req->minor; server_req->evcon = client_evcon; /* For max header length */ evbuffer_add_printf(server_output, "%s %s HTTP/%d.%d\r\n", evhttp_method(client_req->type), url, client_req->major, client_req->minor); /* remove connection headers */ remove_headers(client_req->input_headers, "connection"); remove_headers(client_req->input_headers, "proxy-connection"); /* remove headers we shouldn't forward */ evhttp_remove_header(client_req->input_headers, "util/host"); evhttp_remove_header(client_req->input_headers, "keep-alive"); evhttp_remove_header(client_req->input_headers, "te"); evhttp_remove_header(client_req->input_headers, "trailers"); /* Add our via header */ via = evhttp_find_header(client_req->input_headers, "via"); if (via) { evbuffer_add_printf(server_output, "Via: %s, ", via); evhttp_remove_header(client_req->input_headers, "via"); } else evbuffer_add_printf(server_output, "Via: "); evbuffer_add_printf(server_output, "%d.%d %s (%s/%s)\r\n", client_req->major, client_req->minor, hostname, PACKAGE, VERSION); TAILQ_FOREACH(header, client_req->input_headers, next) { evbuffer_add_printf(server_output, "%s: %s\r\n", header->key, header->value); } evbuffer_add_printf(server_output, "Host: %s\r\n", host); evbuffer_add_printf(server_output, "Connection: %s\r\n", "close"); evbuffer_add(server_output, "\r\n", 2); #ifndef LIBEVENT_TEST lwipevbuf_output(server_bev); #endif proxy_req->server_req = server_req; #ifdef LIBEVENT_TEST bufferevent_setcb(server_bev, proxy_req_read_firstline, NULL, proxy_req_eventcb, proxy_req); #else lwipevbuf_setcb(server_bev, proxy_req_read_firstline, NULL, proxy_req_eventcb, proxy_req); #endif /* Queue any data the client already sent */ evbuffer_add_buffer(server_output, evhttp_request_get_input_buffer(client_req)); } else { struct bufferevent *client_bev; struct evbuffer *client_output; client_bev = evhttp_connection_get_bufferevent(client_evcon); client_output = bufferevent_get_output(client_bev); evbuffer_add_printf(client_output, "HTTP/1.0 200 Connection established\r\n"); evbuffer_add_printf(client_output, "Proxy-agent: %s/%s\r\n", PACKAGE, VERSION); evbuffer_add(client_output, "\r\n", 2); /* Queue any data the client already sent */ evbuffer_add_buffer(server_output, evhttp_request_get_input_buffer(client_req)); proxy_req_join(proxy_req); } } static void #ifndef LIBEVENT_TEST proxy_req_connectcb(struct lwipevbuf *bev, short what, void *ctx) #else proxy_req_connectcb(struct bufferevent *bev, short what, void *ctx) #endif { struct evhttp_proxy_request *proxy_req = ctx; struct evhttp_request *client_req = proxy_req->client_req; if (what & BEV_EVENT_CONNECTED) { proxy_req_connected(proxy_req); return; } if (what & BEV_EVENT_TIMEOUT) { client_send_error(client_req, 403, "Server communication timed out"); } else if (what & BEV_EVENT_ERROR) { int err; const char *str; #ifndef LIBEVENT_TEST err = bev->host_err; #else err = bufferevent_socket_get_dns_error(bev); #endif if (err) { #ifdef LIBEVENT_TEST str = evutil_gai_strerror(err); #elif defined(LWIP_DEBUG) str = lwip_strerr(bev->tcp_err); #else str = "unspecified"; #endif client_send_error(client_req, 500, "DNS lookup failed: %s"); } else { #ifndef LIBEVENT_TEST err = EVUTIL_SOCKET_ERROR(); str = evutil_socket_error_to_string(err); #elif defined(LWIP_DEBUG) str = lwip_strerr(bev->tcp_err); #else str = "unspecified"; #endif client_send_error(client_req, 500, "Connect failed: %s", str); } } proxy_req_free(proxy_req); } static void client_request_cb(struct evhttp_request *client_req, void *ctx) { struct http_proxy *http = ctx; const char *scheme; const char *host; struct evhttp_connection *client_evcon; #ifndef LIBEVENT_TEST struct lwipevbuf *server_bev; #else struct bufferevent *server_bev; struct event_base *base; #endif int port; struct evhttp_proxy_request *proxy_req; #ifdef LIBEVENT_TEST base = evhttp_connection_get_base(client_req->evcon); #endif scheme = evhttp_uri_get_scheme(client_req->uri_elems); client_evcon = evhttp_request_get_connection(client_req); port = evhttp_uri_get_port(client_req->uri_elems); if (scheme && !strcasecmp(scheme, "http")) { host = evhttp_request_get_host(client_req); if (port == -1) port = 80; } else if (client_req->type == EVHTTP_REQ_CONNECT) { /* libevent 2.1.8-stable and below do not handle authority strings correctly */ if (!evhttp_uri_get_host(client_req->uri_elems)) { char *auth; if (asprintf(&auth, "//%s/", client_req->uri)) { } evhttp_uri_free(client_req->uri_elems); client_req->uri_elems = evhttp_uri_parse(auth); free(auth); if (client_req->host_cache != NULL) { free(client_req->host_cache); client_req->host_cache = NULL; } } host = evhttp_request_get_host(client_req); if (port == -1) port = 443; } else { client_send_error(client_req, 501, "Method not implemented: %s", evhttp_method(client_req->type)); return; } #ifndef LIBEVENT_TEST server_bev = lwipevbuf_new(NULL); if (http->keep_alive) { server_bev->pcb->so_options |= SOF_KEEPALIVE; server_bev->pcb->keep_intvl = http->keep_alive; server_bev->pcb->keep_idle = http->keep_alive; } lwipevbuf_connect_hostname(server_bev, AF_UNSPEC, host, port); #else server_bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE); bufferevent_socket_connect_hostname(server_bev, http->dnsbase, AF_UNSPEC, host, port); bufferevent_enable(server_bev, EV_WRITE|EV_READ); #endif proxy_req = calloc(1, sizeof(*proxy_req)); proxy_req->server_bev = server_bev; proxy_req->client_req = client_req; evhttp_connection_set_closecb(client_evcon, proxy_req_client_closecb, proxy_req); #ifndef LIBEVENT_TEST lwipevbuf_setcb(server_bev, NULL, NULL, proxy_req_connectcb, proxy_req); #else bufferevent_setcb(server_bev, NULL, NULL, proxy_req_connectcb, proxy_req); #endif } int http_listen(struct event_base *base, const char *host, const char *port_str, int keep_alive) { struct http_proxy *http; char *endptr; int port; int ret; port = strtoul(port_str, &endptr, 0); if (*endptr) return -1; http = calloc(1, sizeof(*http)); http->evh = evhttp_new(base); http->keep_alive = keep_alive; evhttp_set_max_headers_size(http->evh, 16*1024); /* evhttp_set_timeout(http->evh, 3); */ evhttp_set_allowed_methods(http->evh, EVHTTP_REQ_GET | EVHTTP_REQ_POST | EVHTTP_REQ_HEAD | EVHTTP_REQ_PUT | EVHTTP_REQ_DELETE | EVHTTP_REQ_OPTIONS | EVHTTP_REQ_TRACE | EVHTTP_REQ_CONNECT | EVHTTP_REQ_PATCH); evhttp_set_gencb(http->evh, client_request_cb, http); ret = evhttp_bind_socket(http->evh, host, port); if (ret < 0) { evhttp_free(http->evh); #ifdef LIBEVENT_TEST evdns_free(http->dnsbase); #endif free(http); } return ret; } #ifdef LIBEVENT_TEST int main(void) { struct event_base *base; int ret; int port = 8555; base = event_base_new(); ret = http_listen(base, port); if (ret < 0) return 1; event_base_dispatch(base); return 0; } #endif
{ "language": "C" }
/***************************************************************************/ /* */ /* gxvopbd.c */ /* */ /* TrueTypeGX/AAT opbd table validation (body). */ /* */ /* Copyright 2004-2018 by */ /* suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #include "gxvalid.h" #include "gxvcommn.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvopbd /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** Data and Types *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ typedef struct GXV_opbd_DataRec_ { FT_UShort format; FT_UShort valueOffset_min; } GXV_opbd_DataRec, *GXV_opbd_Data; #define GXV_OPBD_DATA( FIELD ) GXV_TABLE_DATA( opbd, FIELD ) /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** UTILITY FUNCTIONS *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ static void gxv_opbd_LookupValue_validate( FT_UShort glyph, GXV_LookupValueCPtr value_p, GXV_Validator gxvalid ) { /* offset in LookupTable is measured from the head of opbd table */ FT_Bytes p = gxvalid->root->base + value_p->u; FT_Bytes limit = gxvalid->root->limit; FT_Short delta_value; int i; if ( value_p->u < GXV_OPBD_DATA( valueOffset_min ) ) GXV_OPBD_DATA( valueOffset_min ) = value_p->u; for ( i = 0; i < 4; i++ ) { GXV_LIMIT_CHECK( 2 ); delta_value = FT_NEXT_SHORT( p ); if ( GXV_OPBD_DATA( format ) ) /* format 1, value is ctrl pt. */ { if ( delta_value == -1 ) continue; gxv_ctlPoint_validate( glyph, (FT_UShort)delta_value, gxvalid ); } else /* format 0, value is distance */ continue; } } /* opbd ---------------------+ | +===============+ | | lookup header | | +===============+ | | BinSrchHeader | | +===============+ | | lastGlyph[0] | | +---------------+ | | firstGlyph[0] | | head of opbd sfnt table +---------------+ | + | offset[0] | -> | offset [byte] +===============+ | + | lastGlyph[1] | | (glyphID - firstGlyph) * 4 * sizeof(FT_Short) [byte] +---------------+ | | firstGlyph[1] | | +---------------+ | | offset[1] | | +===============+ | | .... | | 48bit value array | +===============+ | | value | <-------+ | | | | | | +---------------+ .... */ static GXV_LookupValueDesc gxv_opbd_LookupFmt4_transit( FT_UShort relative_gindex, GXV_LookupValueCPtr base_value_p, FT_Bytes lookuptbl_limit, GXV_Validator gxvalid ) { GXV_LookupValueDesc value; FT_UNUSED( lookuptbl_limit ); FT_UNUSED( gxvalid ); /* XXX: check range? */ value.u = (FT_UShort)( base_value_p->u + relative_gindex * 4 * sizeof ( FT_Short ) ); return value; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** opbd TABLE *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL_DEF( void ) gxv_opbd_validate( FT_Bytes table, FT_Face face, FT_Validator ftvalid ) { GXV_ValidatorRec gxvalidrec; GXV_Validator gxvalid = &gxvalidrec; GXV_opbd_DataRec opbdrec; GXV_opbd_Data opbd = &opbdrec; FT_Bytes p = table; FT_Bytes limit = 0; FT_ULong version; gxvalid->root = ftvalid; gxvalid->table_data = opbd; gxvalid->face = face; FT_TRACE3(( "validating `opbd' table\n" )); GXV_INIT; GXV_OPBD_DATA( valueOffset_min ) = 0xFFFFU; GXV_LIMIT_CHECK( 4 + 2 ); version = FT_NEXT_ULONG( p ); GXV_OPBD_DATA( format ) = FT_NEXT_USHORT( p ); /* only 0x00010000 is defined (1996) */ GXV_TRACE(( "(version=0x%08x)\n", version )); if ( 0x00010000UL != version ) FT_INVALID_FORMAT; /* only values 0 and 1 are defined (1996) */ GXV_TRACE(( "(format=0x%04x)\n", GXV_OPBD_DATA( format ) )); if ( 0x0001 < GXV_OPBD_DATA( format ) ) FT_INVALID_FORMAT; gxvalid->lookupval_sign = GXV_LOOKUPVALUE_UNSIGNED; gxvalid->lookupval_func = gxv_opbd_LookupValue_validate; gxvalid->lookupfmt4_trans = gxv_opbd_LookupFmt4_transit; gxv_LookupTable_validate( p, limit, gxvalid ); p += gxvalid->subtable_length; if ( p > table + GXV_OPBD_DATA( valueOffset_min ) ) { GXV_TRACE(( "found overlap between LookupTable and opbd_value array\n" )); FT_INVALID_OFFSET; } FT_TRACE4(( "\n" )); } /* END */
{ "language": "C" }
/* * Copyright (c) 2011-2015 CrystaX. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY CrystaX ''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 CrystaX OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of CrystaX. */ #ifndef __CRYSTAX_INCLUDE_CRYSTAX_SYS_CTYPE_H_8A8879F902CA401B82590EC64295C390 #define __CRYSTAX_INCLUDE_CRYSTAX_SYS_CTYPE_H_8A8879F902CA401B82590EC64295C390 #ifndef _CTYPE_H_ #error This file must be included from ctype.h only #endif #include <crystax/id.h> #include <xlocale.h> #define __LIBCRYSTAX_CTYPE_H_XLOCALE_H_INCLUDED 1 #endif /* __CRYSTAX_INCLUDE_CRYSTAX_SYS_CTYPE_H_8A8879F902CA401B82590EC64295C390 */
{ "language": "C" }
/* * wiiuse * * Written By: * Michael Laforest < para > * Email: < thepara (--AT--) g m a i l [--DOT--] com > * * Copyright 2006-2007 * * This file is part of wiiuse. * * 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/>. * * $Header$ * */ /** * @file * @brief Handles the dynamics of the wiimote. * * The file includes functions that handle the dynamics * of the wiimote. Such dynamics include orientation and * motion sensing. */ #pragma once #include "wiiuse_internal.h" #ifdef __cplusplus extern "C" { #endif void calculate_orientation(struct accel_t* ac, struct vec3b_t* accel, struct orient_t* orient, int smooth); void calculate_gforce(struct accel_t* ac, struct vec3b_t* accel, struct gforce_t* gforce); void calc_joystick_state(struct joystick_t* js, float x, float y); void apply_smoothing(struct accel_t* ac, struct orient_t* orient, int type); #ifdef __cplusplus } #endif
{ "language": "C" }
/* Copyright (c) 2007-2008 Michael G Schwern This software originally derived from Paul Sheer's pivotal_gmtime_r.c. The MIT License: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Origin: http://code.google.com/p/y2038 Modified for Bionic by the Android Open Source Project */ #ifndef TIME64_H #define TIME64_H #if defined(__LP64__) #error Your time_t is already 64-bit. #else /* Legacy cruft for LP32 where time_t was 32-bit. */ #include <sys/cdefs.h> #include <time.h> #include <stdint.h> __BEGIN_DECLS typedef int64_t time64_t; char* asctime64(const struct tm*); char* asctime64_r(const struct tm*, char*); char* ctime64(const time64_t*); char* ctime64_r(const time64_t*, char*); struct tm* gmtime64(const time64_t*); struct tm* gmtime64_r(const time64_t*, struct tm*); struct tm* localtime64(const time64_t*); struct tm* localtime64_r(const time64_t*, struct tm*); time64_t mktime64(const struct tm*); time64_t timegm64(const struct tm*); time64_t timelocal64(const struct tm*); __END_DECLS #endif #endif /* TIME64_H */
{ "language": "C" }
/* ======================================== * * Copyright YOUR COMPANY, THE YEAR * All Rights Reserved * UNPUBLISHED, LICENSED SOFTWARE. * * CONFIDENTIAL AND PROPRIETARY INFORMATION * WHICH IS THE PROPERTY OF your company. * * ======================================== */ #include "main.h" uint16 I2CReadDataCharHandle = 0; /* Handle for the I2CRead characteristic */ uint16 I2CWriteDataCharHandle = 0; /* Handle for the I2CWrite characteristic */ uint16 I2CReadDataDescHandle = 0; /* Handle for the I2CRead_Data characteristic descriptor */ uint16 I2CReadServiceHandle = 0; /* Handle for the I2CRead service */ uint16 I2CReadServiceEndHandle = 0; /* End handle for the I2CRead service */ uint16 I2CWriteServiceHandle = 0; /* Handle for the I2CWrite service */ uint16 I2CWriteServiceEndHandle = 0; /* End handle for the I2CWrite service */ uint16 mtuSize = CYBLE_GATT_MTU; /* MTU size to be used by Client and Server after MTU exchange */ uint8 connectionInit = 1; /* flag to check if its the first iteration after connection */ const uint8 enableNotificationParam[2] = {0x01, 0x00}; volatile static bool peerDeviceFound = false; volatile static bool notificationEnabled = false; static INFO_EXCHANGE_STATE_T infoExchangeState = INFO_EXCHANGE_START; CYBLE_GATT_ATTR_HANDLE_RANGE_T attrHandleRange; CYBLE_GATTC_FIND_INFO_REQ_T charDescHandleRange; /* structure to be passed for the enable notification request */ CYBLE_GATTC_WRITE_REQ_T enableNotificationReqParam = { {(uint8*)enableNotificationParam, 2, 2}, 0 }; /* I2C Read service UUID*/ const uint8 I2CReadUUID[16] = { 0x00u, 0x00u, 0xFBu, 0x34u, 0x9Bu, 0x5Fu, 0x80u, 0x00u, \ 0x00u, 0x80u, 0x00u, 0x10u, 0x01u, 0x00u, 0x0Au, 0x00u \ }; /* I2C_Read_data charcteristic UUID */ const uint8 I2CReadDataUUID[16]={ 0x00u, 0xFBu, 0x34u, 0x9Bu, 0x5Fu, 0x80u, 0x00u, 0x00u, \ 0x80u, 0x00u, 0x10u, 0x00u, 0x02u, 0x00u, 0x0Au, 0x00u \ }; /* I2C_Write service UUID */ const uint8 I2CWriteUUID[16] = { 0x00u, 0xFBu, 0x34u, 0x9Bu, 0x5Fu, 0x80u, 0x00u, 0x00u, \ 0x80u, 0x00u, 0x10u, 0x00u, 0x03u, 0x00u, 0x0Au, 0x00u \ }; /* I2C_Write_data charcteristic UUID */ const uint8 I2CWriteDataUUID[16] ={ 0x00u, 0xFBu, 0x34u, 0x9Bu, 0x5Fu, 0x80u, 0x00u, 0x00u, \ 0x80u, 0x00u, 0x10u, 0x00u, 0x04u, 0x00u, 0x0Au, 0x00u \ }; /* structure to be passed for discovering service by UUID */ const CYBLE_GATT_VALUE_T I2CReadServiceUuidInfo = { (uint8 *) I2CReadUUID, \ CYBLE_GATT_128_BIT_UUID_SIZE,\ CYBLE_GATT_128_BIT_UUID_SIZE \ }; /* structure to be passed for discovering service by UUID */ const CYBLE_GATT_VALUE_T I2CWriteServiceUuidInfo = { (uint8 *) I2CWriteUUID, \ CYBLE_GATT_128_BIT_UUID_SIZE,\ CYBLE_GATT_128_BIT_UUID_SIZE \ }; static CYBLE_GAP_BD_ADDR_T peer_addr; /******************************************************************************* * Function Name: HandleBleProcessing ******************************************************************************** * Summary: * Function which updates the LED status , scans and connect to peripheral * based on the BLE component state machine * * Parameters: * void * * Return: * void * *******************************************************************************/ void HandleBleProcessing(void) { switch (cyBle_state) { case CYBLE_STATE_SCANNING: { #ifdef LED_INDICATION SCAN_LED_ON(); #endif /* LED_INDICATION */ if(peerDeviceFound) { CyBle_GapcStopScan(); #ifdef LED_INDICATION ALL_LED_OFF(); #endif /* LED_INDICATION */ } break; } case CYBLE_STATE_CONNECTED: { if(connectionInit) { connectionInit = 0; #ifdef LED_INDICATION CONNECT_LED_ON(); #endif /* LED_INDICATION */ #ifdef ENABLE_I2C_ONLY_WHEN_CONNECTED /* Start I2C Slave operation */ I2C_Start(); /* Initialize I2C write buffer */ I2C_I2CSlaveInitWriteBuf((uint8 *) wrBuf, I2C_WRITE_BUFFER_SIZE); /* Initialize I2C read buffer */ I2C_I2CSlaveInitReadBuf((uint8 *) rdBuf, I2C_READ_BUFFER_SIZE); #endif } /* if Client does not has all the information about attribute handles * call procedure for getting it */ if((I2C_WRITE_DATA_ATTR_HANDLE_FOUND != infoExchangeState)) { attrHandleInit(); } /* enable notifications if not enabled already */ else if(false == notificationEnabled) { enableNotifications(); } #ifdef ENABLE_I2C_ONLY_WHEN_CONNECTED /* if client has all required info and stack is free, handle I2C traffic */ else if(CyBle_GattGetBusStatus() != CYBLE_STACK_STATE_BUSY) { HandleI2CTraffic(); } #endif break; } case CYBLE_STATE_DISCONNECTED: { if(peerDeviceFound) { apiResult = CyBle_GapcConnectDevice(&peer_addr); if(CYBLE_ERROR_OK == apiResult) { peerDeviceFound = false; } } else { #ifdef LED_INDICATION DISCON_LED_ON(); CyDelay(3000); #endif /* LED_INDICATION */ CyBle_GapcStartScan(CYBLE_SCANNING_FAST); } break; } case CYBLE_STATE_CONNECTING: case CYBLE_STATE_INITIALIZING: case CYBLE_STATE_STOPPED: default: break; } } /******************************************************************************* * Function Name: AppCallBack ******************************************************************************** * Summary: * Call back event function to handle varios events from BLE stack * * Parameters: * event: event returned * eventParam: link to value of the events returned * * Return: * void * *******************************************************************************/ void AppCallBack(uint32 event, void *eventParam) { CYBLE_GATTC_READ_BY_TYPE_RSP_PARAM_T *readResponse; CYBLE_GAPC_ADV_REPORT_T *advReport; CYBLE_GATTC_FIND_BY_TYPE_RSP_PARAM_T *findResponse; CYBLE_GATTC_FIND_INFO_RSP_PARAM_T *findInfoResponse; switch (event) { case CYBLE_EVT_STACK_ON: CyBle_GapcStartScan(CYBLE_SCANNING_FAST); break; case CYBLE_EVT_GAPC_SCAN_PROGRESS_RESULT: advReport = (CYBLE_GAPC_ADV_REPORT_T *) eventParam; if((advReport->eventType == CYBLE_GAPC_SCAN_RSP) && (advReport->data[1] == 0xff) && (advReport->data[2] == 0x31) && (advReport->data[3] == 0x01) && (advReport->data[4] == 'I') && (advReport->data[5] == '2') && (advReport->data[6] == 'C') ) { peerDeviceFound = true; memcpy(peer_addr.bdAddr, advReport->peerBdAddr, sizeof(peer_addr.bdAddr)); peer_addr.type = advReport->peerAddrType; } break; case CYBLE_EVT_GAP_DEVICE_DISCONNECTED: /* RESET all flags */ peerDeviceFound = false; notificationEnabled = false; infoExchangeState = INFO_EXCHANGE_START; connectionInit = 1; #ifdef ENABLE_I2C_ONLY_WHEN_CONNECTED I2C_Stop(); #endif break; case CYBLE_EVT_GATTC_READ_BY_TYPE_RSP: readResponse = (CYBLE_GATTC_READ_BY_TYPE_RSP_PARAM_T *) eventParam; if(0 == memcmp((uint8 *)&(readResponse->attrData.attrValue[5]), (uint8 *)I2CReadDataUUID, 16)) { I2CReadDataCharHandle = readResponse->attrData.attrValue[3]; I2CReadDataCharHandle |= (readResponse->attrData.attrValue[4] << 8); infoExchangeState = I2C_READ_DATA_ATTR_HANDLE_FOUND; } else if(0 == memcmp((uint8 *)&(readResponse->attrData.attrValue[5]), (uint8 *)I2CWriteDataUUID, 16)) { I2CWriteDataCharHandle = readResponse->attrData.attrValue[3]; I2CWriteDataCharHandle |= (readResponse->attrData.attrValue[4] << 8); infoExchangeState = I2C_WRITE_DATA_ATTR_HANDLE_FOUND; } break; case CYBLE_EVT_GATTC_FIND_INFO_RSP: findInfoResponse = (CYBLE_GATTC_FIND_INFO_RSP_PARAM_T *) eventParam; if((0x29 == findInfoResponse->handleValueList.list[3]) && \ (0x02 == findInfoResponse->handleValueList.list[2])) { I2CReadDataDescHandle = findInfoResponse->handleValueList.list[0]; I2CReadDataDescHandle |= findInfoResponse->handleValueList.list[1] << 8; infoExchangeState = I2C_READ_DATA_CCCD_HANDLE_FOUND; } break; case CYBLE_EVT_GATTC_HANDLE_VALUE_NTF: HandleI2CNotifications((CYBLE_GATTC_HANDLE_VALUE_NTF_PARAM_T *)eventParam); break; case CYBLE_EVT_GATTC_FIND_BY_TYPE_VALUE_RSP: findResponse = (CYBLE_GATTC_FIND_BY_TYPE_RSP_PARAM_T *) eventParam; if(infoExchangeState == INFO_EXCHANGE_START) { I2CReadServiceHandle = findResponse->range->startHandle; I2CReadServiceEndHandle = findResponse->range->endHandle; infoExchangeState = I2C_READ_SERVICE_HANDLE_FOUND; } else if(infoExchangeState == I2C_READ_DATA_CCCD_HANDLE_FOUND) { I2CWriteServiceHandle = findResponse->range->startHandle; I2CWriteServiceEndHandle = findResponse->range->endHandle; infoExchangeState = I2C_WRITE_SERVICE_HANDLE_FOUND; } break; case CYBLE_EVT_GATTC_WRITE_RSP: notificationEnabled = true; break; default: break; } } /******************************************************************************* * Function Name: attrHandleInit ******************************************************************************** * * Summary: * This function gathhers all the information like attribute handles and MTU size * from the server. * * Parameters: * None. * * Return: * None. * *******************************************************************************/ void attrHandleInit() { switch(infoExchangeState) { case INFO_EXCHANGE_START: CyBle_GattcDiscoverPrimaryServiceByUuid(cyBle_connHandle, I2CReadServiceUuidInfo); break; case I2C_READ_SERVICE_HANDLE_FOUND: attrHandleRange.startHandle = I2CReadServiceHandle; attrHandleRange.endHandle = I2CReadServiceEndHandle; CyBle_GattcDiscoverAllCharacteristics(cyBle_connHandle, attrHandleRange); break; case I2C_READ_DATA_ATTR_HANDLE_FOUND: charDescHandleRange.startHandle = I2CReadDataCharHandle + 1; charDescHandleRange.endHandle = I2CReadServiceEndHandle; CyBle_GattcDiscoverAllCharacteristicDescriptors(cyBle_connHandle, &charDescHandleRange); break; case I2C_READ_DATA_CCCD_HANDLE_FOUND: CyBle_GattcDiscoverPrimaryServiceByUuid(cyBle_connHandle, I2CWriteServiceUuidInfo); break; case I2C_WRITE_SERVICE_HANDLE_FOUND: attrHandleRange.startHandle = I2CWriteServiceHandle; attrHandleRange.endHandle = I2CWriteServiceEndHandle; CyBle_GattcDiscoverAllCharacteristics(cyBle_connHandle, attrHandleRange); break; default: break; } CyBle_ProcessEvents(); } /******************************************************************************* * Function Name: enableNotifications ******************************************************************************** * * Summary: * This function enables notfications from servers. * * Parameters: * None. * * Return: * None. * *******************************************************************************/ void enableNotifications() { enableNotificationReqParam.attrHandle = I2CReadDataDescHandle; CyBle_GattcWriteCharacteristicDescriptors(cyBle_connHandle, (CYBLE_GATTC_WRITE_REQ_T *)(&enableNotificationReqParam)); } /* [] END OF FILE */
{ "language": "C" }
/* This project 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. Deviation 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 Deviation. If not, see <http://www.gnu.org/licenses/>. */ /* This code is based upon code from: http://www.rcgroups.com/forums/showthread.php?t=1564343 Author : Ferenc Szili (kile at the rcgroups.net forum) */ #include "common.h" #include "interface.h" #include "mixer.h" #include "config/model.h" #include "telemetry.h" #ifdef PROTO_HAS_NRF24L01 #include "iface_nrf24l01.h" //////////////////////////////////////////////////////////// /////////////////////// // register bits /////////////////////// // CONFIG #define MASK_RX_DR 6 #define MASK_TX_DS 5 #define MASK_MAX_RT 4 #define EN_CRC 3 #define CRCO 2 #define PWR_UP 1 #define PRIM_RX 0 // EN_AA #define ENAA_P5 5 #define ENAA_P4 4 #define ENAA_P3 3 #define ENAA_P2 2 #define ENAA_P1 1 #define ENAA_P0 0 // EN_RXADDR #define ERX_P5 5 #define ERX_P4 4 #define ERX_P3 3 #define ERX_P2 2 #define ERX_P1 1 #define ERX_P0 0 // RF_SETUP #define CONT_WAVE 7 #define RF_DR_LOW 5 #define PLL_LOCK 4 #define RF_DR_HIGH 3 #define RF_PWR_HIGH 2 #define RF_PWR_LOW 1 #define LNA_HCURR 0 // obsolete in nRF24L01+ // STATUS #define RX_DR 6 #define TX_DS 5 #define MAX_RT 4 #define TX_FULL 0 // FIFO_STATUS #define TX_REUSE 6 #define FIFO_TX_FULL 5 #define TX_EMPTY 4 #define RX_FULL 1 #define RX_EMPTY 0 /////////////////////// // register bit values /////////////////////// // CONFIG #define vMASK_RX_DR (1<<(MASK_RX_DR)) #define vMASK_TX_DS (1<<(MASK_TX_DS)) #define vMASK_MAX_RT (1<<(MASK_MAX_RT)) #define vEN_CRC (1<<(EN_CRC)) #define vCRCO (1<<(CRCO)) #define vPWR_UP (1<<(PWR_UP)) #define vPRIM_RX (1<<(PRIM_RX)) // EN_AA #define vENAA_P5 (1<<(ENAA_P5)) #define vENAA_P4 (1<<(ENAA_P4)) #define vENAA_P3 (1<<(ENAA_P3)) #define vENAA_P2 (1<<(ENAA_P2)) #define vENAA_P1 (1<<(ENAA_P1)) #define vENAA_P0 (1<<(ENAA_P0)) // EN_RXADDR #define vERX_P5 (1<<(ERX_P5)) #define vERX_P4 (1<<(ERX_P4)) #define vERX_P3 (1<<(ERX_P3)) #define vERX_P2 (1<<(ERX_P2)) #define vERX_P1 (1<<(ERX_P1)) #define vERX_P0 (1<<(ERX_P0)) // SETUP_AW -- address widths in bytes #define vAW_3 1 #define vAW_4 2 #define vAW_5 3 // RF_SETUP #define vCONT_WAVE (1<<(CONT_WAVE)) #define vRF_DR_LOW (1<<(RF_DR_LOW)) #define vPLL_LOCK (1<<(PLL_LOCK)) #define vRF_DR_HIGH (1<<(RF_DR_HIGH)) #define vRF_PWR_HIGH (1<<(RF_PWR_HIGH)) #define vRF_PWR_LOW (1<<(RF_PWR_LOW)) #define vLNA_HCURR (1<<(LNA_HCURR)) // obsolete in nRF24L01+ #define vRF_DR_1MBPS 0 #define vRF_DR_2MBPS (1<<(RF_DR_HIGH)) #define vRF_DR_250KBPS (1<<(RF_DR_LOW)) #define vRF_PWR_M18DBM 0x00 #define vRF_PWR_M12DBM 0x02 #define vRF_PWR_M6DBM 0x04 #define vRF_PWR_0DBM 0x06 #define vARD_250us 0x00 #define vARD_500us 0x10 #define vARD_750us 0x20 #define vARD_1000us 0x30 #define vARD_1250us 0x40 #define vARD_1500us 0x50 #define vARD_1750us 0x60 #define vARD_2000us 0x70 #define vARD_2250us 0x80 #define vARD_2500us 0x90 #define vARD_2750us 0xA0 #define vARD_3000us 0xB0 #define vARD_3250us 0xC0 #define vARD_3500us 0xD0 #define vARD_3750us 0xE0 #define vARD_4000us 0xF0 // STATUS #define vRX_DR (1<<(RX_DR)) #define vTX_DS (1<<(TX_DS)) #define vMAX_RT (1<<(MAX_RT)) #define vTX_FULL (1<<(TX_FULL)) #define RX_P_NO(stat) ((stat >> 1) & 7) #define HAS_RX_PAYLOAD(stat) ((stat & 0b1110) < 0b1100) // FIFO_STATUS #define vTX_REUSE (1<<(TX_REUSE)) #define vTX_FULL (1<<(TX_FULL)) #define vTX_EMPTY (1<<(TX_EMPTY)) #define vRX_FULL (1<<(RX_FULL)) #define vRX_EMPTY (1<<(RX_EMPTY)) //////////////////////////////////////////////////////////// uint8_t neChannel = 10; uint8_t neChannelOffset = 0; #define PACKET_LENGTH 7 static u8 packet[20]; static u32 state; static u32 bind_count; static u16 model_id = 0xA04A; const uint8_t NEAddr[] = {0x34, 0x43, 0x10, 0x10, 0x01}; enum { NE260_BINDTX, NE260_BINDRX, NE260_DATA1, NE260_DATA2, NE260_DATA3, }; static void ne260_init() { NRF24L01_Initialize(); NRF24L01_WriteRegisterMulti(NRF24L01_10_TX_ADDR, NEAddr, 5); // write the address NRF24L01_WriteRegisterMulti(NRF24L01_0A_RX_ADDR_P0, NEAddr, 5); NRF24L01_WriteReg(NRF24L01_01_EN_AA, vENAA_P0); // enable auto acknoledge NRF24L01_WriteReg(NRF24L01_04_SETUP_RETR, vARD_500us); // ARD=500us, ARC=disabled NRF24L01_WriteReg(NRF24L01_06_RF_SETUP, vRF_DR_250KBPS | vLNA_HCURR | vRF_PWR_0DBM); // data rate, output power and noise cancel NRF24L01_WriteReg(NRF24L01_11_RX_PW_P0, PACKET_LENGTH); // RX payload length NRF24L01_WriteReg(NRF24L01_02_EN_RXADDR, vERX_P0); // enable RX address NRF24L01_WriteReg(NRF24L01_07_STATUS, vRX_DR | vTX_DS | vMAX_RT); // reset the IRQ flags } static void send_data_packet() { for(int i = 0; i < 4; i++) { s32 value = (s32)Channels[i] * 0x40 / CHAN_MAX_VALUE + 0x40; if (value > 0x7f) value = 0x7f; else if(value < 0) value = 0; packet[i] = value; } packet[4] = 0x55; packet[5] = model_id & 0xff; packet[6] = (model_id >> 8) & 0xff; NRF24L01_FlushTx(); NRF24L01_WriteReg(NRF24L01_07_STATUS, vMAX_RT); NRF24L01_WriteReg(NRF24L01_05_RF_CH, neChannel + neChannelOffset); NRF24L01_WriteReg(NRF24L01_00_CONFIG, vEN_CRC | vCRCO | vPWR_UP); // send a fresh packet to the nRF NRF24L01_WritePayload((uint8_t*) packet, PACKET_LENGTH); } static void send_bind_packet() { packet[0] = 0xAA; //throttle packet[1] = 0xAA; //rudder packet[2] = 0xAA; //elevator packet[3] = 0xAA; //aileron packet[4] = 0xAA; //command packet[5] = model_id & 0xff; packet[6] = (model_id >> 8) & 0xff; NRF24L01_WriteReg(NRF24L01_07_STATUS, vRX_DR | vTX_DS | vMAX_RT); // reset the status flags NRF24L01_WriteReg(NRF24L01_05_RF_CH, neChannel + neChannelOffset); NRF24L01_FlushTx(); NRF24L01_WritePayload((uint8_t*) &packet, PACKET_LENGTH); // send the bind packet } static u16 ne260_cb() { if (state == NE260_BINDTX) { // do we have a packet? if ((NRF24L01_ReadReg(NRF24L01_07_STATUS) & vRX_DR) != 0) { // read the packet contents NRF24L01_ReadPayload(packet, PACKET_LENGTH); // is this the bind response packet? if (strncmp("\x55\x55\x55\x55\x55", (char*) (packet + 1), 5) == 0 && *((uint16_t*)(packet + 6)) == model_id) { // exit the bind loop state = NE260_DATA1; NRF24L01_FlushTx(); NRF24L01_FlushRx(); NRF24L01_SetTxRxMode(TX_EN); return 2000; } } NRF24L01_SetTxRxMode(TX_EN); send_bind_packet(); state = NE260_BINDRX; return 500; } else if (state == NE260_BINDRX) { // switch to RX mode while (!(NRF24L01_ReadReg(NRF24L01_07_STATUS) & (vMAX_RT | vTX_DS))) ; NRF24L01_WriteReg(NRF24L01_07_STATUS, vTX_DS); NRF24L01_SetTxRxMode(RX_EN); NRF24L01_FlushRx(); state = NE260_BINDTX; return 2000; } else if (state == NE260_DATA1) { neChannel = 10; state = NE260_DATA2; } else if (state == NE260_DATA2) { neChannel = 30; state = NE260_DATA3; } else if (state == NE260_DATA3) { neChannel = 50; state = NE260_DATA1; } send_data_packet(); return 2500; } static void initialize() { CLOCK_StopTimer(); ne260_init(); bind_count = 10000; state = NE260_BINDTX; CLOCK_StartTimer(10000, ne260_cb); } uintptr_t NE260_Cmds(enum ProtoCmds cmd) { switch(cmd) { case PROTOCMD_INIT: initialize(); return 0; case PROTOCMD_DEINIT: case PROTOCMD_RESET: CLOCK_StopTimer(); return (NRF24L01_Reset() ? 1 : -1); case PROTOCMD_CHECK_AUTOBIND: return 1; // Never Autobind case PROTOCMD_BIND: initialize(); return 0; case PROTOCMD_NUMCHAN: return 4; case PROTOCMD_DEFAULT_NUMCHAN: return 4; case PROTOCMD_CURRENT_ID: return Model.fixed_id; case PROTOCMD_TELEMETRYSTATE: return PROTO_TELEM_UNSUPPORTED; case PROTOCMD_CHANNELMAP: return AETRG; default: break; } return 0; } #endif
{ "language": "C" }
/* * Copyright (C) 2011 Ahmad Amarullah ( http://amarullz.com/ ) * * 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. */ /* * Descriptions: * ------------- * AROMA UI: CONSOLE * */ #include "../aroma.h" /* Internal representation of the screen */ #define ESC_BUF_SIZ 256 #define ESC_ARG_SIZ 16 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b)) #define DEFAULT(a, b) (a) = (a) ? (a) : (b) #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x) enum escape_state { ESC_START = 1, ESC_CSI = 2, ESC_OSC = 4, ESC_TITLE = 8, ESC_ALTCHARSET = 16 }; typedef struct { char buf[ESC_BUF_SIZ]; /* raw string */ int len; /* raw string length */ char priv; int arg[ESC_ARG_SIZ]; int narg; /* nb of args */ char mode; } AESCAPE, * AESCAPEP; typedef struct { CANVAS cv; char ** history; byte active; byte iscursor; int cv_x; int cv_y; int fw; /* Font Width */ int fh; /* Font Height */ int col; /* Column Size */ int row; /* Line Size */ int cx; int cy; /* CONSOLE DATA */ AESCAPE escseq; int esc; int savex; /* Save X */ int savey; /* Save X */ int bg; /* Background */ int fg; /* Foreground */ int def_bg; int def_fg; byte bold; byte underline; byte reserve; byte nextwrap; byte clrf; word colorset[256]; byte beep; } ACONSOLE, * ACONSOLEP; /* d->bg=d->def_bg; d->fg=d->def_fg; d->bold=0; d->underline=0; */ /** CONSOLE HANDLER **/ int aconsole_isescape(ACONTROLP ctl) { ACONSOLEP d = (ACONSOLEP) ctl->d; return d->esc; } void aconsole_initcolors(ACONSOLEP d) { int i, r, g, b; byte red, green, blue; /* 16colorset */ d->colorset[0] = 0x0000; d->colorset[1] = ag_rgb(0xFF, 0, 0); d->colorset[2] = ag_rgb(0, 0xFF, 0); d->colorset[3] = ag_rgb(0xFF, 0xFF, 0); d->colorset[4] = ag_rgb(0, 0, 0xFF); d->colorset[5] = ag_rgb(0xFF, 0, 0xFF); d->colorset[6] = ag_rgb(0, 0xFF, 0xFF); d->colorset[7] = ag_rgb(0xCC, 0xCC, 0xCC); d->colorset[8] = ag_rgb(0x66, 0x66, 0x66); d->colorset[9] = ag_rgb(0xFF, 0x5C, 0x5C); d->colorset[10] = ag_rgb(0x5C, 0xFF, 0x5C); d->colorset[11] = ag_rgb(0xFF, 0xFF, 0x5C); d->colorset[12] = ag_rgb(0x5C, 0x5C, 0xFF); d->colorset[13] = ag_rgb(0xFF, 0x5C, 0xFF); d->colorset[14] = ag_rgb(0x5C, 0xFF, 0xFF); d->colorset[15] = 0xffff; /* load colors [16-255] ; same colors as xterm */ for (i = 16, r = 0; r < 6; r++) { for (g = 0; g < 6; g++) { for (b = 0; b < 6; b++) { red = 42 * r; green = 42 * g; blue = 42 * b; d->colorset[i] = ag_rgb(red, green, blue); i++; } } } for (r = 0; r < 24; r++, i++) { red = green = blue = 10 * r; d->colorset[i] = ag_rgb(red, green, blue); } } word getbg(ACONSOLEP d) { return d->colorset[(d->reserve ? d->fg : d->bg)]; } word getfg(ACONSOLEP d) { return d->colorset[(d->reserve ? d->bg : d->fg)]; } void csireset(ACONTROLP ctl) { ACONSOLEP d = (ACONSOLEP) ctl->d; memset(&d->escseq, 0, sizeof(d->escseq)); } void tclearregion(ACONTROLP ctl, int x1, int y1, int x2, int y2) { ACONSOLEP d = (ACONSOLEP) ctl->d; int x, y, temp; if (x1 > x2) { temp = x1, x1 = x2, x2 = temp; } if (y1 > y2) { temp = y1, y1 = y2, y2 = temp; } LIMIT(x1, 0, d->col - 1); LIMIT(x2, 0, d->col - 1); LIMIT(y1, 0, d->row - 1); LIMIT(y2, 0, d->row - 1); /* Draw */ ag_rect( &d->cv, x1 * d->fw, y1 * d->fh, ((x2 - x1) + 1) * d->fw, ((y2 - y1) + 1) * d->fh, getbg(d) ); } void treset(ACONTROLP ctl) { ACONSOLEP d = (ACONSOLEP) ctl->d; d->bg = d->def_bg; d->fg = d->def_fg; d->bold = 0; d->underline = 0; d->reserve = 0; d->cx = 0; d->cy = 0; d->clrf = 0; tclearregion(ctl, 0, 0, d->col - 1, d->row - 1); } void tscrolldown(ACONTROLP ctl, int orig, int n) { ACONSOLEP d = (ACONSOLEP) ctl->d; LIMIT(n, 0, d->row - orig); int height = d->fh * n; ag_draw(&d->cv, &d->cv, 0, height); tclearregion(ctl, 0, orig, d->col - 1, orig + n - 1); //printf("SCROLLDN\n"); } void tscrollup(ACONTROLP ctl, int orig, int n) { ACONSOLEP d = (ACONSOLEP) ctl->d; LIMIT(n, 0, d->row - orig); int height = d->fh * n; ag_draw(&d->cv, &d->cv, 0, -height); tclearregion(ctl, 0, d->row - n, d->col - 1, d->row - 1); //printf("SCROLLUP\n"); } void tmoveto(ACONTROLP ctl, int x, int y) { ACONSOLEP d = (ACONSOLEP) ctl->d; LIMIT(x, 0, d->col - 1); LIMIT(y, 0, d->row - 1); d->cx = x; d->cy = y; d->nextwrap = 0; } void tnewline(ACONTROLP ctl, int first_col) { ACONSOLEP d = (ACONSOLEP) ctl->d; int y = d->cy; if (y == d->row - 1) { tscrollup(ctl, 0, 1); } else { y++; } tmoveto(ctl, first_col ? 0 : d->cx, y); } void tsetchar(ACONTROLP ctl, char c) { ACONSOLEP d = (ACONSOLEP) ctl->d; tclearregion(ctl, d->cx, d->cy, d->cx, d->cy); if (c != ' ') { ag_drawchar_ex2( &d->cv, d->cx * d->fw, d->cy * d->fh, c, getfg(d), 2, d->underline, d->bold, 0, 0 ); } } void tdeletechar(ACONTROLP ctl, int n) { ACONSOLEP d = (ACONSOLEP) ctl->d; int src = d->cx + n; int dst = d->cx; int size = d->col - src; if (src >= d->col) { tclearregion(ctl, d->cx, d->cy, d->col - 1, d->cy); return; } ag_draw_ex(&d->cv, &d->cv, dst * d->fw, d->cy * d->fh, src * d->fw, d->cy * d->fh, size * d->fw, d->fh ); tclearregion(ctl, d->col - n, d->cy, d->col - 1, d->cy); //printf("tdeletechar : %i, %i, %i, %i\n", d->col-n, d->cy, d->col-1, d->cy); } void tinsertblank(ACONTROLP ctl, int n) { ACONSOLEP d = (ACONSOLEP) ctl->d; int src = d->cx; int dst = src + n; int size = d->col - dst; if (dst >= d->col) { tclearregion(ctl, d->cx, d->cy, d->col - 1, d->cy); return; } /* Move Create Temporary Canvas */ CANVAS tmpcanvas; ag_canvas(&tmpcanvas, size * d->fw, d->fh); ag_draw_ex( &tmpcanvas, &d->cv, 0, 0, src * d->fw, d->cy * d->fh, size * d->fw, d->fh ); ag_draw( &d->cv, &tmpcanvas, dst * d->fw, d->cy * d->fh ); ag_ccanvas(&tmpcanvas); /* ag_draw_ex( &d->cv,&d->cv, dst*d->fw, d->cy*d->fh, src*d->fw, d->cy*d->fh, size*d->fw, d->fh ); */ tclearregion(ctl, src, d->cy, dst - 1, d->cy); //printf("INSERT BLANK : %i, %i, %i, %i\n", src, d->cy, dst - 1, d->cy); } void tinsertblankline(ACONTROLP ctl, int n) { ACONSOLEP d = (ACONSOLEP) ctl->d; if ((d->cy < 0) || (d->cy >= d->row)) { return; } tscrolldown(ctl, d->cy, n); } void tdeleteline(ACONTROLP ctl, int n) { ACONSOLEP d = (ACONSOLEP) ctl->d; if ((d->cy < 0) || (d->cy >= d->row)) { return; } tscrollup(ctl, d->cy, n); } void tsetattr(ACONTROLP ctl, int * attr, int l) { ACONSOLEP d = (ACONSOLEP) ctl->d; int i; for (i = 0; i < l; i++) { switch (attr[i]) { case 0: { d->bg = d->def_bg; d->fg = d->def_fg; d->bold = 0; d->underline = 0; d->reserve = 0; } break; case 1: d->bold = 1; break; case 4: d->underline = 1; break; case 7: d->reserve = 1; break; case 22: d->bold = 0; break; case 24: d->underline = 0; break; case 27: d->reserve = 0; break; case 38: { if ((i + 2 < l) && (attr[i + 1] == 5)) { i += 2; if (BETWEEN(attr[i], 0, 255)) { d->fg = attr[i]; } } } break; case 39: d->fg = d->def_fg; break; case 48: { if (i + 2 < l && attr[i + 1] == 5) { i += 2; if (BETWEEN(attr[i], 0, 255)) { d->bg = attr[i]; } } } break; case 49: d->bg = d->def_bg; break; default: { if (BETWEEN(attr[i], 30, 37)) { d->fg = attr[i] - 30; } else if (BETWEEN(attr[i], 40, 47)) { d->bg = attr[i] - 40; } else if (BETWEEN(attr[i], 90, 97)) { d->fg = attr[i] - 90 + 8; } else if (BETWEEN(attr[i], 100, 107)) { d->fg = attr[i] - 100 + 8; } } break; } } } void tputtab(ACONTROLP ctl) { ACONSOLEP d = (ACONSOLEP) ctl->d; int space = 8 - d->cx % 8; tmoveto(ctl, d->cx + space, d->cy); } void csiparse(ACONTROLP ctl) { ACONSOLEP d = (ACONSOLEP) ctl->d; char * p = d->escseq.buf; d->escseq.narg = 0; if (*p == '?') { d->escseq.priv = 1, p++; } while (p < d->escseq.buf + d->escseq.len) { while (isdigit(*p)) { d->escseq.arg[d->escseq.narg] *= 10; d->escseq.arg[d->escseq.narg] += *p++ - '0'/*, noarg = 0 */; } if (*p == ';' && d->escseq.narg + 1 < ESC_ARG_SIZ) { d->escseq.narg++, p++; } else { d->escseq.mode = *p; d->escseq.narg++; return; } } } void csihandle(ACONTROLP ctl) { ACONSOLEP d = (ACONSOLEP) ctl->d; switch (d->escseq.mode) { case '@': /* ICH -- Insert <n> blank char */ DEFAULT(d->escseq.arg[0], 1); tinsertblank(ctl, d->escseq.arg[0]); break; case 'A': /* CUU -- Cursor <n> Up */ case 'e': DEFAULT(d->escseq.arg[0], 1); tmoveto(ctl, d->cx, d->cy - d->escseq.arg[0]); break; case 'B': /* CUD -- Cursor <n> Down */ DEFAULT(d->escseq.arg[0], 1); tmoveto(ctl, d->cx, d->cy + d->escseq.arg[0]); break; case 'C': /* CUF -- Cursor <n> Forward */ case 'a': DEFAULT(d->escseq.arg[0], 1); tmoveto(ctl, d->cx + d->escseq.arg[0], d->cy); break; case 'D': /* CUB -- Cursor <n> Backward */ DEFAULT(d->escseq.arg[0], 1); tmoveto(ctl, d->cx - d->escseq.arg[0], d->cy); break; case 'E': /* CNL -- Cursor <n> Down and first col */ DEFAULT(d->escseq.arg[0], 1); tmoveto(ctl, 0, d->cy + d->escseq.arg[0]); break; case 'F': /* CPL -- Cursor <n> Up and first col */ DEFAULT(d->escseq.arg[0], 1); tmoveto(ctl, 0, d->cy - d->escseq.arg[0]); break; case 'G': /* CHA -- Move to <col> */ case '`': /* XXX: HPA -- same? */ DEFAULT(d->escseq.arg[0], 1); tmoveto(ctl, d->escseq.arg[0] - 1, d->cy); break; case 'H': /* CUP -- Move to <row> <col> */ case 'f': /* XXX: HVP -- same? */ DEFAULT(d->escseq.arg[0], 1); DEFAULT(d->escseq.arg[1], 1); tmoveto(ctl, d->escseq.arg[1] - 1, d->escseq.arg[0] - 1); break; /* XXX: (CSI n I) CHT -- Cursor Forward Tabulation <n> tab stops */ case 'J': { /* ED -- Clear screen */ switch (d->escseq.arg[0]) { case 0: { /* below */ tclearregion(ctl, d->cx, d->cy, d->col - 1, d->cy); if (d->cy < d->row - 1) { tclearregion(ctl, 0, d->cy + 1, d->col - 1, d->row - 1); } } break; case 1: { /* above */ if (d->cy > 1) { tclearregion(ctl, 0, 0, d->col - 1, d->cy - 1); } tclearregion(ctl, 0, d->cy, d->cx, d->cy); } break; case 2: /* all */ tclearregion(ctl, 0, 0, d->col - 1, d->row - 1); break; } } break; case 'K': { /* EL -- Clear line */ switch (d->escseq.arg[0]) { case 0: /* right */ tclearregion(ctl, d->cx, d->cy, d->col - 1, d->cy); break; case 1: /* left */ tclearregion(ctl, 0, d->cy, d->cx, d->cy); break; case 2: /* all */ tclearregion(ctl, 0, d->cy, d->col - 1, d->cy); break; } } break; case 'S': { /* SU -- Scroll <n> line up */ DEFAULT(d->escseq.arg[0], 1); tscrollup(ctl, 0, d->escseq.arg[0]); } break; case 'T': { /* SD -- Scroll <n> line down */ DEFAULT(d->escseq.arg[0], 1); tscrolldown(ctl, 0, d->escseq.arg[0]); } break; case 'L': { /* IL -- Insert <n> blank lines */ DEFAULT(d->escseq.arg[0], 1); tinsertblankline(ctl, d->escseq.arg[0]); } break; case 'l': { /* RM -- Reset Mode */ if (d->escseq.priv) { switch (d->escseq.arg[0]) { case 5: /* DECSCNM -- Remove reverse video */ d->reserve = 0; break; case 20: //printf("CLRF OFF\n"); d->clrf = 0; break; case 1048: { d->cx = d->savex; d->cy = d->savey; } break; } } } break; case 'M': /* DL -- Delete <n> lines */ DEFAULT(d->escseq.arg[0], 1); tdeleteline(ctl, d->escseq.arg[0]); break; case 'X': /* ECH -- Erase <n> char */ DEFAULT(d->escseq.arg[0], 1); tclearregion(ctl, d->cx, d->cy, d->cx + d->escseq.arg[0], d->cy); break; case 'P': /* DCH -- Delete <n> char */ DEFAULT(d->escseq.arg[0], 1); tdeletechar(ctl, d->escseq.arg[0]); break; /* XXX: (CSI n Z) CBT -- Cursor Backward Tabulation <n> tab stops */ case 'd': /* VPA -- Move to <row> */ DEFAULT(d->escseq.arg[0], 1); tmoveto(ctl, d->cx, d->escseq.arg[0] - 1); break; case 'h': { /* SM -- Set terminal mode */ if (d->escseq.priv) { switch (d->escseq.arg[0]) { case 5: /* DECSCNM -- Reverve video */ d->reserve = 1; break; case 20: //printf("CLRF ON\n"); d->clrf = 1; break; case 1048: d->savex = d->cx; d->savey = d->cy; break; } } } break; case 'm': /* SGR -- Terminal attribute (color) */ tsetattr(ctl, d->escseq.arg, d->escseq.narg); break; case 's': /* DECSC -- Save cursor position (ANSI.SYS) */ d->savex = d->cx; d->savey = d->cy; break; case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */ d->cx = d->savex; d->cy = d->savey; break; } } /** CONTROLS **/ void aconsole_setwindowsize(void * x, int fd) { ACONTROLP ctl = (ACONTROLP) x; ACONSOLEP d = (ACONSOLEP) ctl->d; struct winsize w; w.ws_row = d->row; w.ws_col = d->col; w.ws_xpixel = w.ws_ypixel = 0; if (ioctl(fd, TIOCSWINSZ, &w) < 0) { //printf("\n\n::: CANNOT RESIZE WINDOW :::\n\n"); } } dword aconsole_oninput(void * x, int action, ATEV * atev) { return 0; } void aconsole_ondraw(void * x) { ACONTROLP ctl = (ACONTROLP) x; ACONSOLEP d = (ACONSOLEP) ctl->d; CANVAS * pc = &ctl->win->c; ag_rect(pc, ctl->x, ctl->y, ctl->w, ctl->h, getbg(d) ); ag_draw(pc, &d->cv, ctl->x + d->cv_x, ctl->y + d->cv_y); if (d->iscursor) { int x, y; int xp = d->cx * d->fw + ctl->x + d->cv_x; int yp = d->cy * d->fh + ctl->y + d->cv_y; word fgcl = (d->beep) ? ag_rgb(255, 50, 50) : getfg(d); word bgcl = getbg(d); byte ir = ag_r(fgcl); byte ig = ag_g(fgcl); byte ib = ag_b(fgcl); byte gr = 255 - ag_r(bgcl); byte gg = 255 - ag_r(bgcl); byte gb = 255 - ag_r(bgcl); for (y = 0; y < d->fh; y++) { for (x = 0; x < d->fw; x++) { word * p = agxy(pc, xp + x, yp + y); if (p) { byte r = (byte) (((int) (gr - ag_r(*p)) * ir) >> 8); byte g = (byte) (((int) (gg - ag_g(*p)) * ig) >> 8); byte b = (byte) (((int) (gb - ag_b(*p)) * ib) >> 8); *p = ag_rgb(r, g, b); } } } /* ag_rect(pc, d->cx*d->fw + ctl->x + d->cv_x, d->cy*d->fh + ctl->y + d->cv_y, d->fw,d->fh, getfg(d) ); */ } aw_draw(ctl->win); } static void * aconsole_drawer(void * cookie) { ACONTROLP ctl = (ACONTROLP) cookie; ACONSOLEP d = (ACONSOLEP) ctl->d; while (d->active) { d->iscursor = d->iscursor ? 0 : 1; aconsole_ondraw(ctl); usleep(250000); } return NULL; } void aconsole_ondestroy(void * x) { ACONTROLP ctl = (ACONTROLP) x; ACONSOLEP d = (ACONSOLEP) ctl->d; d->active = 0; usleep(600000); ag_ccanvas(&d->cv); free(ctl->d); } void aconsole_onblur(void * x) { } byte aconsole_onfocus(void * x) { return 1; } void aconsole_escape_handler(ACONTROLP ctl, char ascii) { ACONSOLEP d = (ACONSOLEP) ctl->d; if (d->esc & ESC_CSI) { d->escseq.buf[d->escseq.len++] = ascii; if (BETWEEN(ascii, 0x40, 0x7E) || d->escseq.len >= ESC_BUF_SIZ) { d->esc = 0; csiparse(ctl); csihandle(ctl); } } else if (d->esc & ESC_OSC) { if (ascii == ';') { d->esc = ESC_START | ESC_TITLE; } } else if (d->esc & ESC_TITLE) { if (ascii == '\a') { d->esc = 0; } } else if (d->esc & ESC_ALTCHARSET) { d->esc = 0; } else { switch (ascii) { case '[': d->esc |= ESC_CSI; break; case ']': d->esc |= ESC_OSC; break; case '(': d->esc |= ESC_ALTCHARSET; break; case 'D': { if (d->cy == d->row - 1) { tscrollup(ctl, 0, 1); } else { tmoveto(ctl, d->cx, d->cy + 1); } d->esc = 0; } break; case 'E': { tnewline(ctl, 1); d->esc = 0; } break; case 'M': { if (d->cy == 0) { tscrolldown(ctl, 0, 1); } else { tmoveto(ctl, d->cx, d->cy - 1); } d->esc = 0; } break; case 'c': { /* RIS -- Reset to inital state */ treset(ctl); d->esc = 0; } break; case '7': /* DECSC -- Save Cursor */ d->savex = d->cx; d->savey = d->cy; d->esc = 0; break; case '8': /* DECRC -- Restore Cursor */ d->cx = d->savex; d->cy = d->savey; d->esc = 0; break; default: d->esc = 0; } } } void aconsole_add(void * x, int c) { ACONTROLP ctl = (ACONTROLP) x; ACONSOLEP d = (ACONSOLEP) ctl->d; if (d->esc & ESC_START) { aconsole_escape_handler(ctl, c); return; } else if (c == '\033') { /* ESCAPE */ csireset(ctl); d->esc = ESC_START; return; } byte redrawit = 0; if (c == 7) { /* BEEP */ d->beep = 1; vibrate(50); aconsole_ondraw(ctl); return; } else if (d->beep) { d->beep = 0; redrawit = 1; } /* Normal Char Handler */ int chr = 0; switch (c) { case '\t': tputtab(ctl); break; case '\b': tmoveto(ctl, d->cx - 1, d->cy); break; case '\r': tmoveto(ctl, 0, d->cy); break; case '\f': case '\v': case '\n': tnewline(ctl, d->clrf); break; default: { if (d->nextwrap) { tnewline(ctl, 1); } tsetchar(ctl, c); if (d->cx + 1 < d->col) { tmoveto(ctl, d->cx + 1, d->cy); } else { d->nextwrap = 1; } } } if (redrawit) { aconsole_ondraw(ctl); } } byte aconsole_isclrf(ACONTROLP ctl) { ACONSOLEP d = (ACONSOLEP) ctl->d; return d->clrf; } ACONTROLP aconsole(AWINDOWP win, int x, int y, int w, int h) { //-- Console Data ACONSOLEP d = (ACONSOLEP) malloc(sizeof(ACONSOLE)); memset(d, 0, sizeof(ACONSOLE)); //-- Set Data // d->history = aStack(); d->fw = ag_fontwidth('A', 2); d->fh = ag_fontheight(2); d->col = w / d->fw; d->row = h / d->fh; d->cx = 0; d->cy = 0; d->active = 1; d->iscursor = 0; d->clrf = 0; //-- Console Info d->def_bg = 0; d->def_fg = 7; d->bg = d->def_bg; d->fg = d->def_fg; d->bold = 0; d->underline = 0; d->reserve = 0; d->nextwrap = 0; d->beep = 0; int cvw = d->col * d->fw; int cvh = d->row * d->fh; d->cv_x = (w / 2) - (cvw / 2); d->cv_y = (h / 2) - (cvh / 2); //-- Init Colorset aconsole_initcolors(d); //-- Initializing Canvas ag_canvas(&d->cv, cvw, cvh); ag_rect(&d->cv, 0, 0, w, h, getbg(d)); //-- Initializing Control ACONTROLP ctl = malloc(sizeof(ACONTROL)); ctl->ondestroy = &aconsole_ondestroy; ctl->oninput = &aconsole_oninput; ctl->ondraw = &aconsole_ondraw; ctl->onblur = &aconsole_onblur; ctl->onfocus = &aconsole_onfocus; ctl->win = win; ctl->x = x; ctl->y = y; ctl->w = w; ctl->h = h; ctl->forceNS = 0; ctl->d = (void *) d; aw_add(win, ctl); pthread_t rth; pthread_create(&rth, NULL, aconsole_drawer, (void *) ctl); pthread_detach(rth); return ctl; }
{ "language": "C" }
#include <string.h> #include <time.h> #include "auth.h" #include "obfsutil.h" #include "crc32.h" #include "base64.h" #include "encrypt.h" uint32_t g_endian_test = 1; typedef struct shift128plus_ctx { uint64_t v[2]; }shift128plus_ctx; void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; } //https://zh.wikipedia.org/wiki/%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F void quick_sort_recursive(int arr[], int start, int end) { if (start >= end) return;//這是為了防止宣告堆疊陣列時當機 int mid = arr[end]; int left = start, right = end - 1; while (left < right) { while (arr[left] < mid && left < right) left++; while (arr[right] >= mid && left < right) right--; swap(&arr[left], &arr[right]); } if (arr[left] >= arr[end]) swap(&arr[left], &arr[end]); else left++; if (left) { quick_sort_recursive(arr, start, left - 1); } quick_sort_recursive(arr, left + 1, end); } void quick_sort(int arr[], int len) { quick_sort_recursive(arr, 0, len - 1); } int array_bin_search(int start, int end, int array[], int value) { int mid = (start + end) / 2; if(start > end) { if (value > array[start]) { return start + 1; } else { return start; } } if(array[mid] > value) { return array_bin_search(start, mid - 1, array, value); } else { return array_bin_search(mid + 1, end, array, value); } } uint64_t shift128plus_next(shift128plus_ctx* ctx) { uint64_t x = ctx->v[0]; uint64_t y = ctx->v[1]; ctx->v[0] = y; x ^= x << 23; x ^= (y ^ (x >> 17) ^ (y >> 26)); ctx->v[1] = x; return x + y; } void i64_memcpy(uint8_t* target, uint8_t* source) { for (int i = 0; i < 8; ++i) target[i] = source[7 - i]; } void shift128plus_init_from_bin(shift128plus_ctx* ctx, uint8_t* bin, int bin_size) { uint8_t fill_bin[16] = {0}; memcpy(fill_bin, bin, bin_size); if (*(uint8_t*)&g_endian_test == 1) { memcpy(ctx, fill_bin, 16); } else { i64_memcpy((uint8_t*)ctx, fill_bin); i64_memcpy((uint8_t*)ctx + 8, fill_bin + 8); } } void shift128plus_init_from_bin_datalen(shift128plus_ctx* ctx, uint8_t* bin, int bin_size, int datalen) { uint8_t fill_bin[16] = {0}; memcpy(fill_bin, bin, bin_size); fill_bin[0] = datalen; fill_bin[1] = datalen >> 8; if (*(uint8_t*)&g_endian_test == 1) { memcpy(ctx, fill_bin, 16); } else { i64_memcpy((uint8_t*)ctx, fill_bin); i64_memcpy((uint8_t*)ctx + 8, fill_bin + 8); } for (int i = 0; i < 4; ++i) { shift128plus_next(ctx); } } typedef struct auth_chain_global_data { uint8_t local_client_id[4]; uint32_t connection_id; }auth_chain_global_data; typedef unsigned int (*rnd_func)(int datalength, shift128plus_ctx* random, uint8_t* last_hash, int data_size_list[], int data_size_list_len, int data_size_list2[], int data_size_list2_len, int overhead); typedef struct auth_chain_local_data { int has_sent_header; char * recv_buffer; int recv_buffer_size; uint32_t recv_id; uint32_t pack_id; char * salt; uint8_t * user_key; char uid[4]; int user_key_len; int last_data_len; uint8_t last_client_hash[16]; uint8_t last_server_hash[16]; shift128plus_ctx random_client; shift128plus_ctx random_server; int cipher_init_flag; cipher_env_t cipher; enc_ctx_t* cipher_client_ctx; enc_ctx_t* cipher_server_ctx; int *data_size_list; int data_size_list_len; rnd_func rnd; int *data_size_list2; int data_size_list2_len; }auth_chain_local_data; void auth_chain_local_data_init(auth_chain_local_data* local) { local->has_sent_header = 0; local->recv_buffer = (char*)malloc(16384); local->recv_buffer_size = 0; local->recv_id = 1; local->pack_id = 1; local->salt = ""; local->user_key = 0; local->user_key_len = 0; local->cipher_init_flag = 0; local->cipher_client_ctx = 0; local->cipher_server_ctx = 0; local->rnd = 0; local->data_size_list = NULL; local->data_size_list_len = 0; local->data_size_list2 = NULL; local->data_size_list2_len = 0;//Thanks to @hiboy } void * auth_chain_a_init_data() { auth_chain_global_data *global = (auth_chain_global_data*)malloc(sizeof(auth_chain_global_data)); rand_bytes(global->local_client_id, 4); rand_bytes((uint8_t*)&global->connection_id, 4); global->connection_id &= 0xFFFFFF; return global; } unsigned int auth_chain_a_get_rand_len(int datalength, shift128plus_ctx* random, uint8_t* last_hash, int data_size_list[], int data_size_list_len, int data_size_list2[], int data_size_list2_len, int overhead) { if (datalength > 1440) return 0; shift128plus_init_from_bin_datalen(random, last_hash, 16, datalength); if (datalength > 1300) return shift128plus_next(random) % 31; if (datalength > 900) return shift128plus_next(random) % 127; if (datalength > 400) return shift128plus_next(random) % 521; return shift128plus_next(random) % 1021; } obfs * auth_chain_a_new_obfs() { obfs * self = new_obfs(); self->l_data = malloc(sizeof(auth_chain_local_data)); auth_chain_local_data_init((auth_chain_local_data*)self->l_data); ((auth_chain_local_data*)self->l_data)->salt = "auth_chain_a"; ((auth_chain_local_data*)self->l_data)->rnd = auth_chain_a_get_rand_len; return self; } int auth_chain_a_get_overhead(obfs *self) { return 4; } void auth_chain_a_dispose(obfs *self) { auth_chain_local_data *local = (auth_chain_local_data*)self->l_data; if (local->recv_buffer != NULL) { free(local->recv_buffer); local->recv_buffer = NULL; } if (local->user_key != NULL) { free(local->user_key); local->user_key = NULL; } if (local->cipher_init_flag) { if (local->cipher_client_ctx) { enc_ctx_release(&local->cipher, local->cipher_client_ctx); } if (local->cipher_server_ctx) { enc_ctx_release(&local->cipher, local->cipher_server_ctx); } enc_release(&local->cipher); local->cipher_init_flag = 0; } if(local->data_size_list != NULL) { free(local->data_size_list); } if(local->data_size_list2 != NULL) { free(local->data_size_list2); } free(local); self->l_data = NULL; dispose_obfs(self); } void auth_chain_set_server_info(obfs *self, server_info *server) { server->overhead = 4; memmove(&self->server, server, sizeof(server_info)); } unsigned int udp_get_rand_len(shift128plus_ctx* random, uint8_t* last_hash) { shift128plus_init_from_bin(random, last_hash, 16); return shift128plus_next(random) % 127; } unsigned int get_rand_start_pos(int rand_len, shift128plus_ctx* random) { if (rand_len > 0) return shift128plus_next(random) % 8589934609 % rand_len; return 0; } unsigned int get_client_rand_len(auth_chain_local_data *local, int datalength, int overhead) { return local->rnd(datalength, &local->random_client, local->last_client_hash, local->data_size_list, local->data_size_list_len, local->data_size_list2, local->data_size_list2_len, overhead); } unsigned int get_server_rand_len(auth_chain_local_data *local, int datalength, int overhead) { return local->rnd(datalength, &local->random_server, local->last_server_hash, local->data_size_list, local->data_size_list_len, local->data_size_list2, local->data_size_list2_len, overhead); } int auth_chain_a_pack_data(char *data, int datalength, char *outdata, auth_chain_local_data *local, server_info *server) { unsigned int rand_len = get_client_rand_len(local, datalength, server->overhead); int out_size = (int)rand_len + datalength + 2; outdata[0] = (char)((uint8_t)datalength ^ local->last_client_hash[14]); outdata[1] = (char)((uint8_t)(datalength >> 8) ^ local->last_client_hash[15]); { uint8_t rnd_data[rand_len]; rand_bytes(rnd_data, (int)rand_len); if (datalength > 0) { int start_pos = get_rand_start_pos(rand_len, &local->random_client); size_t out_len; ss_encrypt_buffer(&local->cipher, local->cipher_client_ctx, data, datalength, &outdata[2 + start_pos], &out_len); memcpy(outdata + 2, rnd_data, start_pos); memcpy(outdata + 2 + start_pos + datalength, rnd_data + start_pos, rand_len - start_pos); } else { memcpy(outdata + 2, rnd_data, rand_len); } } uint8_t key_len = (uint8_t)(local->user_key_len + 4); uint8_t key[key_len]; memcpy(key, local->user_key, local->user_key_len); memintcopy_lt(key + key_len - 4, local->pack_id); ++local->pack_id; ss_md5_hmac_with_key((char*)local->last_client_hash, outdata, out_size, key, key_len); memcpy(outdata + out_size, local->last_client_hash, 2); return out_size + 2; } int auth_chain_a_pack_auth_data(auth_chain_global_data *global, server_info *server, auth_chain_local_data *local, char *data, int datalength, char *outdata) { const int authhead_len = 4 + 8 + 4 + 16 + 4; const char* salt = local->salt; int out_size = authhead_len; ++global->connection_id; if (global->connection_id > 0xFF000000) { rand_bytes(global->local_client_id, 8); rand_bytes((uint8_t*)&global->connection_id, 4); global->connection_id &= 0xFFFFFF; } char encrypt[20]; uint8_t key[server->iv_len + server->key_len]; uint8_t key_len = (uint8_t)(server->iv_len + server->key_len); memcpy(key, server->iv, server->iv_len); memcpy(key + server->iv_len, server->key, server->key_len); time_t t = time(NULL); memintcopy_lt(encrypt, (uint32_t)t); memcpy(encrypt + 4, global->local_client_id, 4); memintcopy_lt(encrypt + 8, global->connection_id); encrypt[12] = (char)server->overhead; encrypt[13] = (char)(server->overhead >> 8); encrypt[14] = 0; encrypt[15] = 0; // first 12 bytes { rand_bytes((uint8_t*)outdata, 4); ss_md5_hmac_with_key((char*)local->last_client_hash, (char*)outdata, 4, key, key_len); memcpy(outdata + 4, local->last_client_hash, 8); } // uid & 16 bytes auth data { uint8_t uid[4]; if (local->user_key == NULL) { if(server->param != NULL && server->param[0] != 0) { char *param = server->param; char *delim = strchr(param, ':'); if(delim != NULL) { char uid_str[16] = {}; strncpy(uid_str, param, delim - param); char key_str[128]; strcpy(key_str, delim + 1); long uid_long = strtol(uid_str, NULL, 10); memintcopy_lt((char*)local->uid, (uint32_t)uid_long); local->user_key_len = (int)strlen(key_str); local->user_key = (uint8_t*)malloc((size_t)local->user_key_len); memcpy(local->user_key, key_str, local->user_key_len); } } if (local->user_key == NULL) { rand_bytes((uint8_t*)local->uid, 4); local->user_key_len = (int)server->key_len; local->user_key = (uint8_t*)malloc((size_t)local->user_key_len); memcpy(local->user_key, server->key, local->user_key_len); } } for (int i = 0; i < 4; ++i) { uid[i] = local->uid[i] ^ local->last_client_hash[8 + i]; } char encrypt_key_base64[256] = {0}; unsigned char encrypt_key[local->user_key_len]; memcpy(encrypt_key, local->user_key, local->user_key_len); base64_encode(encrypt_key, (unsigned int)local->user_key_len, encrypt_key_base64); int salt_len = strlen(salt); int base64_len = (local->user_key_len + 2) / 3 * 4; memcpy(encrypt_key_base64 + base64_len, salt, salt_len); char enc_key[16]; int enc_key_len = base64_len + salt_len; bytes_to_key_with_size(encrypt_key_base64, (size_t)enc_key_len, (uint8_t*)enc_key, 16); char encrypt_data[16]; ss_aes_128_cbc(encrypt, encrypt_data, enc_key); memcpy(encrypt, uid, 4); memcpy(encrypt + 4, encrypt_data, 16); } // final HMAC { ss_md5_hmac_with_key((char*)local->last_server_hash, encrypt, 20, local->user_key, local->user_key_len); memcpy(outdata + 12, encrypt, 20); memcpy(outdata + 12 + 20, local->last_server_hash, 4); } char password[256] = {0}; base64_encode(local->user_key, local->user_key_len, password); base64_encode(local->last_client_hash, 16, password + strlen(password)); local->cipher_init_flag = 1; enc_init(&local->cipher, password, "rc4"); local->cipher_client_ctx = malloc(sizeof(enc_ctx_t)); local->cipher_server_ctx = malloc(sizeof(enc_ctx_t)); enc_ctx_init(&local->cipher, local->cipher_client_ctx, 1); enc_ctx_init(&local->cipher, local->cipher_server_ctx, 0); out_size += auth_chain_a_pack_data(data, datalength, outdata + out_size, local, server); return out_size; } int auth_chain_a_client_pre_encrypt(obfs *self, char **pplaindata, int datalength, size_t* capacity) { char *plaindata = *pplaindata; server_info *server = (server_info*)&self->server; auth_chain_local_data *local = (auth_chain_local_data*)self->l_data; char * out_buffer = (char*)malloc((size_t)(datalength * 2 + 4096)); char * buffer = out_buffer; char * data = plaindata; int len = datalength; int pack_len; if (len > 0 && local->has_sent_header == 0) { int head_size = 1200; if (head_size > datalength) head_size = datalength; pack_len = auth_chain_a_pack_auth_data((auth_chain_global_data *)self->server.g_data, &self->server, local, data, head_size, buffer); buffer += pack_len; data += head_size; len -= head_size; local->has_sent_header = 1; } int unit_size = server->tcp_mss - server->overhead; while ( len > unit_size ) { pack_len = auth_chain_a_pack_data(data, unit_size, buffer, local, &self->server); buffer += pack_len; data += unit_size; len -= unit_size; } if (len > 0) { pack_len = auth_chain_a_pack_data(data, len, buffer, local, &self->server); buffer += pack_len; } len = (int)(buffer - out_buffer); if ((int)*capacity < len) { *pplaindata = (char*)realloc(*pplaindata, *capacity = (size_t)(len * 2)); plaindata = *pplaindata; } local->last_data_len = datalength; memmove(plaindata, out_buffer, len); free(out_buffer); return len; } int auth_chain_a_client_post_decrypt(obfs *self, char **pplaindata, int datalength, size_t* capacity) { char *plaindata = *pplaindata; auth_chain_local_data *local = (auth_chain_local_data*)self->l_data; server_info *server = (server_info*)&self->server; uint8_t * recv_buffer = (uint8_t *)local->recv_buffer; if (local->recv_buffer_size + datalength > 16384) return -1; memmove(recv_buffer + local->recv_buffer_size, plaindata, datalength); local->recv_buffer_size += datalength; int key_len = local->user_key_len + 4; uint8_t *key = (uint8_t*)malloc((size_t)key_len); memcpy(key, local->user_key, local->user_key_len); char * out_buffer = (char*)malloc((size_t)local->recv_buffer_size); char * buffer = out_buffer; char error = 0; while (local->recv_buffer_size > 4) { memintcopy_lt(key + key_len - 4, local->recv_id); int data_len = (int)(((unsigned)(recv_buffer[1] ^ local->last_server_hash[15]) << 8) + (recv_buffer[0] ^ local->last_server_hash[14])); int rand_len = get_server_rand_len(local, data_len, server->overhead); int len = rand_len + data_len; if (len >= 4096) { local->recv_buffer_size = 0; error = 1; break; } if ((len += 4) > local->recv_buffer_size) break; char hash[16]; ss_md5_hmac_with_key(hash, (char*)recv_buffer, len - 2, key, key_len); if (memcmp(hash, recv_buffer + len - 2, 2)) { local->recv_buffer_size = 0; error = 1; break; } int pos; if (data_len > 0 && rand_len > 0) { pos = 2 + get_rand_start_pos(rand_len, &local->random_server); } else { pos = 2; } size_t out_len; ss_decrypt_buffer(&local->cipher, local->cipher_server_ctx, (char*)recv_buffer + pos, data_len, buffer, &out_len); if (local->recv_id == 1) { server->tcp_mss = (uint8_t)buffer[0] | ((uint8_t)buffer[1] << 8); memmove(buffer, buffer + 2, out_len -= 2); } memcpy(local->last_server_hash, hash, 16); ++local->recv_id; buffer += out_len; memmove(recv_buffer, recv_buffer + len, local->recv_buffer_size -= len); } int len; if (error == 0) { len = (int)(buffer - out_buffer); if ((int)*capacity < len) { *pplaindata = (char*)realloc(*pplaindata, *capacity = (size_t)(len * 2)); plaindata = *pplaindata; } memmove(plaindata, out_buffer, len); } else { len = -1; } free(out_buffer); free(key); return len; } int auth_chain_a_client_udp_pre_encrypt(obfs *self, char **pplaindata, int datalength, size_t* capacity) { char *plaindata = *pplaindata; server_info *server = (server_info*)&self->server; auth_chain_local_data *local = (auth_chain_local_data*)self->l_data; char out_buffer[datalength + 1024]; if (local->user_key == NULL) { if(self->server.param != NULL && self->server.param[0] != 0) { char *param = self->server.param; char *delim = strchr(param, ':'); if(delim != NULL) { char uid_str[16] = {}; strncpy(uid_str, param, delim - param); char key_str[128]; strcpy(key_str, delim + 1); long uid_long = strtol(uid_str, NULL, 10); memintcopy_lt(local->uid, (uint32_t)uid_long); local->user_key_len = (int)strlen(key_str); local->user_key = (uint8_t*)malloc((size_t)local->user_key_len); memcpy(local->user_key, key_str, local->user_key_len); } } if (local->user_key == NULL) { rand_bytes((uint8_t *)local->uid, 4); local->user_key_len = (int)self->server.key_len; local->user_key = (uint8_t*)malloc((size_t)local->user_key_len); memcpy(local->user_key, self->server.key, local->user_key_len); } } char auth_data[3]; uint8_t hash[16]; ss_md5_hmac_with_key((char*)hash, auth_data, 3, server->key, server->key_len); int rand_len = udp_get_rand_len(&local->random_client, hash); uint8_t rnd_data[rand_len]; rand_bytes(rnd_data, (int)rand_len); int outlength = datalength + rand_len + 8; char password[256] = {0}; base64_encode(local->user_key, local->user_key_len, password); base64_encode(hash, 16, password + strlen(password)); { enc_init(&local->cipher, password, "rc4"); enc_ctx_t ctx; enc_ctx_init(&local->cipher, &ctx, 1); size_t out_len; ss_encrypt_buffer(&local->cipher, &ctx, plaindata, datalength, out_buffer, &out_len); enc_ctx_release(&local->cipher, &ctx); enc_release(&local->cipher); } uint8_t uid[4]; for (int i = 0; i < 4; ++i) { uid[i] = local->uid[i] ^ hash[i]; } memmove(out_buffer + datalength, rnd_data, rand_len); memmove(out_buffer + outlength - 8, auth_data, 3); memmove(out_buffer + outlength - 5, uid, 4); ss_md5_hmac_with_key((char*)hash, out_buffer, outlength - 1, local->user_key, local->user_key_len); memmove(out_buffer + outlength - 1, hash, 1); if ((int)*capacity < outlength) { *pplaindata = (char*)realloc(*pplaindata, *capacity = (size_t)(outlength * 2)); plaindata = *pplaindata; } memmove(plaindata, out_buffer, outlength); return outlength; } int auth_chain_a_client_udp_post_decrypt(obfs *self, char **pplaindata, int datalength, size_t* capacity) { if (datalength <= 8) return 0; char *plaindata = *pplaindata; server_info *server = (server_info*)&self->server; auth_chain_local_data *local = (auth_chain_local_data*)self->l_data; uint8_t hash[16]; ss_md5_hmac_with_key((char*)hash, plaindata, datalength - 1, local->user_key, local->user_key_len); if (*hash != ((uint8_t*)plaindata)[datalength - 1]) return 0; ss_md5_hmac_with_key((char*)hash, plaindata + datalength - 8, 7, server->key, server->key_len); int rand_len = udp_get_rand_len(&local->random_server, hash); int outlength = datalength - rand_len - 8; char password[256] = {0}; base64_encode(local->user_key, local->user_key_len, password); base64_encode(hash, 16, password + strlen(password)); { enc_init(&local->cipher, password, "rc4"); enc_ctx_t ctx; enc_ctx_init(&local->cipher, &ctx, 0); size_t out_len; ss_decrypt_buffer(&local->cipher, &ctx, plaindata, outlength, plaindata, &out_len); enc_ctx_release(&local->cipher, &ctx); enc_release(&local->cipher); } return outlength; } //auth_chain_b void auth_chain_b_set_server_info(obfs *self, server_info *server) { memmove(&self->server, server, sizeof(server_info)); auth_chain_local_data *local = (auth_chain_local_data*)self->l_data; shift128plus_ctx* random = &(local->random_server); shift128plus_init_from_bin(random, server->key, 16); local->data_size_list_len = shift128plus_next(random) % 8 + 4; local->data_size_list = (int*)malloc(local->data_size_list_len * sizeof(int)); int i; for(i = 0; i < local->data_size_list_len; i++) { local->data_size_list[i] = shift128plus_next(random) % 2340 % 2040 % 1440; } quick_sort(local->data_size_list, local->data_size_list_len); local->data_size_list2_len = shift128plus_next(random) % 16 + 8; local->data_size_list2 = (int*)malloc(local->data_size_list2_len * sizeof(int)); //Thanks to anonymous for(i = 0; i < local->data_size_list2_len; i++) { local->data_size_list2[i] = shift128plus_next(random) % 2340 % 2040 % 1440; } quick_sort(local->data_size_list2, local->data_size_list2_len); } unsigned int auth_chain_b_get_rand_len(int datalength, shift128plus_ctx* random, uint8_t* last_hash, int data_size_list[], int data_size_list_len, int data_size_list2[], int data_size_list2_len, int overhead) { if (datalength > 1440) return 0; shift128plus_init_from_bin_datalen(random, last_hash, 16, datalength); int pos = array_bin_search(0, data_size_list_len - 1, data_size_list, datalength + overhead); int final_pos = pos + shift128plus_next(random) % data_size_list_len; if(final_pos < data_size_list_len) { return data_size_list[final_pos] - datalength - overhead; } pos = array_bin_search(0, data_size_list2_len - 1, data_size_list2, datalength + overhead); final_pos = pos + shift128plus_next(random) % data_size_list2_len; if(final_pos < data_size_list2_len) { return data_size_list2[final_pos] - datalength - overhead; } if(final_pos < pos + data_size_list2_len - 1) { return 0; } if (datalength > 1300) return shift128plus_next(random) % 31; if (datalength > 900) return shift128plus_next(random) % 127; if (datalength > 400) return shift128plus_next(random) % 521; return shift128plus_next(random) % 1021; } obfs * auth_chain_b_new_obfs() { obfs * self = new_obfs(); self->l_data = malloc(sizeof(auth_chain_local_data)); auth_chain_local_data_init((auth_chain_local_data*)self->l_data); ((auth_chain_local_data*)self->l_data)->salt = "auth_chain_b"; ((auth_chain_local_data*)self->l_data)->rnd = auth_chain_b_get_rand_len; return self; }
{ "language": "C" }
/* * Filter graphs to bad ASCII-art * Copyright (c) 2012 Nicolas George * * 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 */ #include <string.h> #include "libavutil/channel_layout.h" #include "libavutil/bprint.h" #include "libavutil/pixdesc.h" #include "avfilter.h" #include "avfiltergraph.h" #include "internal.h" static int print_link_prop(AVBPrint *buf, AVFilterLink *link) { char *format; char layout[64]; AVBPrint dummy_buffer = { 0 }; if (!buf) buf = &dummy_buffer; switch (link->type) { case AVMEDIA_TYPE_VIDEO: format = av_x_if_null(av_get_pix_fmt_name(link->format), "?"); av_bprintf(buf, "[%dx%d %d:%d %s]", link->w, link->h, link->sample_aspect_ratio.num, link->sample_aspect_ratio.den, format); break; case AVMEDIA_TYPE_AUDIO: av_get_channel_layout_string(layout, sizeof(layout), link->channels, link->channel_layout); format = av_x_if_null(av_get_sample_fmt_name(link->format), "?"); av_bprintf(buf, "[%dHz %s:%s]", (int)link->sample_rate, format, layout); break; default: av_bprintf(buf, "?"); break; } return buf->len; } static void avfilter_graph_dump_to_buf(AVBPrint *buf, AVFilterGraph *graph) { unsigned i, j, x, e; for (i = 0; i < graph->nb_filters; i++) { AVFilterContext *filter = graph->filters[i]; unsigned max_src_name = 0, max_dst_name = 0; unsigned max_in_name = 0, max_out_name = 0; unsigned max_in_fmt = 0, max_out_fmt = 0; unsigned width, height, in_indent; unsigned lname = strlen(filter->name); unsigned ltype = strlen(filter->filter->name); for (j = 0; j < filter->nb_inputs; j++) { AVFilterLink *l = filter->inputs[j]; unsigned ln = strlen(l->src->name) + 1 + strlen(l->srcpad->name); max_src_name = FFMAX(max_src_name, ln); max_in_name = FFMAX(max_in_name, strlen(l->dstpad->name)); max_in_fmt = FFMAX(max_in_fmt, print_link_prop(NULL, l)); } for (j = 0; j < filter->nb_outputs; j++) { AVFilterLink *l = filter->outputs[j]; unsigned ln = strlen(l->dst->name) + 1 + strlen(l->dstpad->name); max_dst_name = FFMAX(max_dst_name, ln); max_out_name = FFMAX(max_out_name, strlen(l->srcpad->name)); max_out_fmt = FFMAX(max_out_fmt, print_link_prop(NULL, l)); } in_indent = max_src_name + max_in_name + max_in_fmt; in_indent += in_indent ? 4 : 0; width = FFMAX(lname + 2, ltype + 4); height = FFMAX3(2, filter->nb_inputs, filter->nb_outputs); av_bprint_chars(buf, ' ', in_indent); av_bprintf(buf, "+"); av_bprint_chars(buf, '-', width); av_bprintf(buf, "+\n"); for (j = 0; j < height; j++) { unsigned in_no = j - (height - filter->nb_inputs ) / 2; unsigned out_no = j - (height - filter->nb_outputs) / 2; /* Input link */ if (in_no < filter->nb_inputs) { AVFilterLink *l = filter->inputs[in_no]; e = buf->len + max_src_name + 2; av_bprintf(buf, "%s:%s", l->src->name, l->srcpad->name); av_bprint_chars(buf, '-', e - buf->len); e = buf->len + max_in_fmt + 2 + max_in_name - strlen(l->dstpad->name); print_link_prop(buf, l); av_bprint_chars(buf, '-', e - buf->len); av_bprintf(buf, "%s", l->dstpad->name); } else { av_bprint_chars(buf, ' ', in_indent); } /* Filter */ av_bprintf(buf, "|"); if (j == (height - 2) / 2) { x = (width - lname) / 2; av_bprintf(buf, "%*s%-*s", x, "", width - x, filter->name); } else if (j == (height - 2) / 2 + 1) { x = (width - ltype - 2) / 2; av_bprintf(buf, "%*s(%s)%*s", x, "", filter->filter->name, width - ltype - 2 - x, ""); } else { av_bprint_chars(buf, ' ', width); } av_bprintf(buf, "|"); /* Output link */ if (out_no < filter->nb_outputs) { AVFilterLink *l = filter->outputs[out_no]; unsigned ln = strlen(l->dst->name) + 1 + strlen(l->dstpad->name); e = buf->len + max_out_name + 2; av_bprintf(buf, "%s", l->srcpad->name); av_bprint_chars(buf, '-', e - buf->len); e = buf->len + max_out_fmt + 2 + max_dst_name - ln; print_link_prop(buf, l); av_bprint_chars(buf, '-', e - buf->len); av_bprintf(buf, "%s:%s", l->dst->name, l->dstpad->name); } av_bprintf(buf, "\n"); } av_bprint_chars(buf, ' ', in_indent); av_bprintf(buf, "+"); av_bprint_chars(buf, '-', width); av_bprintf(buf, "+\n"); av_bprintf(buf, "\n"); } } char *avfilter_graph_dump(AVFilterGraph *graph, const char *options) { AVBPrint buf; char *dump; av_bprint_init(&buf, 0, 0); avfilter_graph_dump_to_buf(&buf, graph); av_bprint_init(&buf, buf.len + 1, buf.len + 1); avfilter_graph_dump_to_buf(&buf, graph); av_bprint_finalize(&buf, &dump); return dump; }
{ "language": "C" }
/* pnglibconf.h - library build configuration */ /* libpng version 1.5.7 - December 15, 2011 */ /* Copyright (c) 1998-2011 Glenn Randers-Pehrson */ /* This code is released under the libpng license. */ /* For conditions of distribution and use, see the disclaimer */ /* and license in png.h */ /* pnglibconf.h */ /* Machine generated file: DO NOT EDIT */ /* Derived from: scripts/pnglibconf.dfa */ #ifndef PNGLCONF_H #define PNGLCONF_H /* settings */ #define PNG_USER_HEIGHT_MAX 1000000 #define PNG_USER_CHUNK_MALLOC_MAX 0 #define PNG_COST_SHIFT 3 #define PNG_GAMMA_THRESHOLD_FIXED 5000 #define PNG_QUANTIZE_BLUE_BITS 5 #define PNG_WEIGHT_SHIFT 8 #define PNG_API_RULE 0 #define PNG_CALLOC_SUPPORTED #define PNG_ZBUF_SIZE 8192 #define PNG_QUANTIZE_GREEN_BITS 5 #define PNG_sCAL_PRECISION 5 #define PNG_USER_WIDTH_MAX 1000000 #define PNG_QUANTIZE_RED_BITS 5 #define PNG_DEFAULT_READ_MACROS 1 #define PNG_MAX_GAMMA_8 11 #define PNG_USER_CHUNK_CACHE_MAX 0 /* end of settings */ /* options */ #define PNG_IO_STATE_SUPPORTED #define PNG_BENIGN_ERRORS_SUPPORTED /* #define PNG_WRITE_SUPPORTED */ #define PNG_EASY_ACCESS_SUPPORTED #define PNG_INFO_IMAGE_SUPPORTED #define PNG_TIME_RFC1123_SUPPORTED #define PNG_WRITE_FILTER_SUPPORTED #define PNG_FIXED_POINT_SUPPORTED #define PNG_READ_SUPPORTED #define PNG_WRITE_OPTIMIZE_CMF_SUPPORTED #define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED #define PNG_WRITE_FLUSH_SUPPORTED #define PNG_WRITE_INTERLACING_SUPPORTED #define PNG_USER_LIMITS_SUPPORTED #define PNG_WRITE_TRANSFORMS_SUPPORTED #define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED #define PNG_SET_USER_LIMITS_SUPPORTED #define PNG_INCH_CONVERSIONS_SUPPORTED #define PNG_USER_MEM_SUPPORTED #define PNG_SETJMP_SUPPORTED #define PNG_WARNINGS_SUPPORTED #define PNG_FLOATING_POINT_SUPPORTED #define PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED #define PNG_READ_QUANTIZE_SUPPORTED #define PNG_READ_16BIT_SUPPORTED #define PNG_SET_CHUNK_MALLOC_LIMIT_SUPPORTED #define PNG_ALIGN_MEMORY_SUPPORTED /*#undef PNG_ERROR_NUMBERS_SUPPORTED*/ #define PNG_SEQUENTIAL_READ_SUPPORTED #define PNG_BUILD_GRAYSCALE_PALETTE_SUPPORTED #define PNG_WRITE_SHIFT_SUPPORTED #define PNG_ERROR_TEXT_SUPPORTED #define PNG_WRITE_FILLER_SUPPORTED #define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED #define PNG_WRITE_16BIT_SUPPORTED #define PNG_WRITE_SWAP_ALPHA_SUPPORTED #define PNG_POINTER_INDEXING_SUPPORTED #define PNG_FLOATING_ARITHMETIC_SUPPORTED #define PNG_MNG_FEATURES_SUPPORTED #define PNG_STDIO_SUPPORTED #define PNG_WRITE_INT_FUNCTIONS_SUPPORTED #define PNG_WRITE_PACKSWAP_SUPPORTED #define PNG_READ_INTERLACING_SUPPORTED #define PNG_READ_COMPOSITE_NODIV_SUPPORTED #define PNG_PROGRESSIVE_READ_SUPPORTED #define PNG_READ_INT_FUNCTIONS_SUPPORTED #define PNG_HANDLE_AS_UNKNOWN_SUPPORTED #define PNG_WRITE_INVERT_SUPPORTED #define PNG_WRITE_PACK_SUPPORTED #define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED #define PNG_16BIT_SUPPORTED #define PNG_WRITE_cHRM_SUPPORTED #define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED #define PNG_WRITE_BGR_SUPPORTED #define PNG_SET_CHUNK_CACHE_LIMIT_SUPPORTED #define PNG_WRITE_sBIT_SUPPORTED #define PNG_READ_sBIT_SUPPORTED #define PNG_READ_TRANSFORMS_SUPPORTED #define PNG_READ_EXPAND_16_SUPPORTED #define PNG_WRITE_SWAP_SUPPORTED #define PNG_READ_SWAP_SUPPORTED #define PNG_WRITE_oFFs_SUPPORTED #define PNG_READ_oFFs_SUPPORTED #define PNG_WRITE_USER_TRANSFORM_SUPPORTED #define PNG_WRITE_tIME_SUPPORTED #define PNG_WRITE_INVERT_ALPHA_SUPPORTED #define PNG_READ_tIME_SUPPORTED #define PNG_READ_PACKSWAP_SUPPORTED #define PNG_READ_GRAY_TO_RGB_SUPPORTED #define PNG_READ_STRIP_16_TO_8_SUPPORTED #define PNG_READ_SCALE_16_TO_8_SUPPORTED #define PNG_READ_USER_CHUNKS_SUPPORTED #define PNG_READ_OPT_PLTE_SUPPORTED #define PNG_UNKNOWN_CHUNKS_SUPPORTED #define PNG_WRITE_gAMA_SUPPORTED #define PNG_WRITE_iCCP_SUPPORTED #define PNG_READ_iCCP_SUPPORTED #define PNG_READ_SHIFT_SUPPORTED #define PNG_READ_EXPAND_SUPPORTED #define PNG_WRITE_iTXt_SUPPORTED #define PNG_READ_iTXt_SUPPORTED #define PNG_READ_SWAP_ALPHA_SUPPORTED #define PNG_CONSOLE_IO_SUPPORTED #define PNG_sBIT_SUPPORTED #define PNG_WRITE_sRGB_SUPPORTED #define PNG_READ_sRGB_SUPPORTED #define PNG_READ_ALPHA_MODE_SUPPORTED #define PNG_WRITE_sCAL_SUPPORTED #define PNG_READ_sCAL_SUPPORTED #define PNG_USER_CHUNKS_SUPPORTED #define PNG_oFFs_SUPPORTED #define PNG_READ_GAMMA_SUPPORTED #define PNG_WRITE_pHYs_SUPPORTED #define PNG_WRITE_tRNS_SUPPORTED #define PNG_READ_pHYs_SUPPORTED #define PNG_READ_tRNS_SUPPORTED #define PNG_READ_RGB_TO_GRAY_SUPPORTED #define PNG_tIME_SUPPORTED #define PNG_WRITE_bKGD_SUPPORTED #define PNG_READ_bKGD_SUPPORTED #define PNG_WRITE_zTXt_SUPPORTED #define PNG_WRITE_pCAL_SUPPORTED #define PNG_READ_zTXt_SUPPORTED #define PNG_READ_pCAL_SUPPORTED #define PNG_WRITE_hIST_SUPPORTED #define PNG_READ_hIST_SUPPORTED #define PNG_WRITE_sPLT_SUPPORTED #define PNG_READ_sPLT_SUPPORTED #define PNG_READ_INVERT_ALPHA_SUPPORTED #define PNG_iCCP_SUPPORTED #define PNG_CONVERT_tIME_SUPPORTED #define PNG_READ_FILLER_SUPPORTED #define PNG_READ_USER_TRANSFORM_SUPPORTED #define PNG_READ_PACK_SUPPORTED #define PNG_READ_BACKGROUND_SUPPORTED #define PNG_iTXt_SUPPORTED #define PNG_READ_cHRM_SUPPORTED #define PNG_USER_TRANSFORM_INFO_SUPPORTED #define PNG_sRGB_SUPPORTED #define PNG_USER_TRANSFORM_PTR_SUPPORTED #define PNG_sCAL_SUPPORTED #define PNG_READ_BGR_SUPPORTED #define PNG_READ_INVERT_SUPPORTED #define PNG_READ_COMPRESSED_TEXT_SUPPORTED #define PNG_pHYs_SUPPORTED #define PNG_tRNS_SUPPORTED #define PNG_bKGD_SUPPORTED #define PNG_pCAL_SUPPORTED #define PNG_zTXt_SUPPORTED #define PNG_READ_TEXT_SUPPORTED #define PNG_hIST_SUPPORTED #define PNG_READ_STRIP_ALPHA_SUPPORTED #define PNG_WRITE_COMPRESSED_TEXT_SUPPORTED #define PNG_sPLT_SUPPORTED #define PNG_READ_gAMA_SUPPORTED #define PNG_SAVE_INT_32_SUPPORTED #define PNG_cHRM_SUPPORTED #define PNG_CHECK_cHRM_SUPPORTED #define PNG_gAMA_SUPPORTED #define PNG_READ_tEXt_SUPPORTED #define PNG_WRITE_TEXT_SUPPORTED #define PNG_TEXT_SUPPORTED #define PNG_WRITE_tEXt_SUPPORTED #define PNG_tEXt_SUPPORTED /* end of options */ #endif /* PNGLCONF_H */
{ "language": "C" }
/* * Header file for sonic.c * * (C) Waldorf Electronics, Germany * Written by Andreas Busse * * NOTE: most of the structure definitions here are endian dependent. * If you want to use this driver on big endian machines, the data * and pad structure members must be exchanged. Also, the structures * need to be changed accordingly to the bus size. * * 981229 MSch: did just that for the 68k Mac port (32 bit, big endian) * * 990611 David Huggins-Daines <dhd@debian.org>: This machine abstraction * does not cope with 16-bit bus sizes very well. Therefore I have * rewritten it with ugly macros and evil inlines. * * 050625 Finn Thain: introduced more 32-bit cards and dhd's support * for 16-bit cards (from the mac68k project). */ #ifndef SONIC_H #define SONIC_H /* * SONIC register offsets */ #define SONIC_CMD 0x00 #define SONIC_DCR 0x01 #define SONIC_RCR 0x02 #define SONIC_TCR 0x03 #define SONIC_IMR 0x04 #define SONIC_ISR 0x05 #define SONIC_UTDA 0x06 #define SONIC_CTDA 0x07 #define SONIC_URDA 0x0d #define SONIC_CRDA 0x0e #define SONIC_EOBC 0x13 #define SONIC_URRA 0x14 #define SONIC_RSA 0x15 #define SONIC_REA 0x16 #define SONIC_RRP 0x17 #define SONIC_RWP 0x18 #define SONIC_RSC 0x2b #define SONIC_CEP 0x21 #define SONIC_CAP2 0x22 #define SONIC_CAP1 0x23 #define SONIC_CAP0 0x24 #define SONIC_CE 0x25 #define SONIC_CDP 0x26 #define SONIC_CDC 0x27 #define SONIC_WT0 0x29 #define SONIC_WT1 0x2a #define SONIC_SR 0x28 /* test-only registers */ #define SONIC_TPS 0x08 #define SONIC_TFC 0x09 #define SONIC_TSA0 0x0a #define SONIC_TSA1 0x0b #define SONIC_TFS 0x0c #define SONIC_CRBA0 0x0f #define SONIC_CRBA1 0x10 #define SONIC_RBWC0 0x11 #define SONIC_RBWC1 0x12 #define SONIC_TTDA 0x20 #define SONIC_MDT 0x2f #define SONIC_TRBA0 0x19 #define SONIC_TRBA1 0x1a #define SONIC_TBWC0 0x1b #define SONIC_TBWC1 0x1c #define SONIC_LLFA 0x1f #define SONIC_ADDR0 0x1d #define SONIC_ADDR1 0x1e /* * Error counters */ #define SONIC_CRCT 0x2c #define SONIC_FAET 0x2d #define SONIC_MPT 0x2e #define SONIC_DCR2 0x3f /* * SONIC command bits */ #define SONIC_CR_LCAM 0x0200 #define SONIC_CR_RRRA 0x0100 #define SONIC_CR_RST 0x0080 #define SONIC_CR_ST 0x0020 #define SONIC_CR_STP 0x0010 #define SONIC_CR_RXEN 0x0008 #define SONIC_CR_RXDIS 0x0004 #define SONIC_CR_TXP 0x0002 #define SONIC_CR_HTX 0x0001 /* * SONIC data configuration bits */ #define SONIC_DCR_EXBUS 0x8000 #define SONIC_DCR_LBR 0x2000 #define SONIC_DCR_PO1 0x1000 #define SONIC_DCR_PO0 0x0800 #define SONIC_DCR_SBUS 0x0400 #define SONIC_DCR_USR1 0x0200 #define SONIC_DCR_USR0 0x0100 #define SONIC_DCR_WC1 0x0080 #define SONIC_DCR_WC0 0x0040 #define SONIC_DCR_DW 0x0020 #define SONIC_DCR_BMS 0x0010 #define SONIC_DCR_RFT1 0x0008 #define SONIC_DCR_RFT0 0x0004 #define SONIC_DCR_TFT1 0x0002 #define SONIC_DCR_TFT0 0x0001 /* * Constants for the SONIC receive control register. */ #define SONIC_RCR_ERR 0x8000 #define SONIC_RCR_RNT 0x4000 #define SONIC_RCR_BRD 0x2000 #define SONIC_RCR_PRO 0x1000 #define SONIC_RCR_AMC 0x0800 #define SONIC_RCR_LB1 0x0400 #define SONIC_RCR_LB0 0x0200 #define SONIC_RCR_MC 0x0100 #define SONIC_RCR_BC 0x0080 #define SONIC_RCR_LPKT 0x0040 #define SONIC_RCR_CRS 0x0020 #define SONIC_RCR_COL 0x0010 #define SONIC_RCR_CRCR 0x0008 #define SONIC_RCR_FAER 0x0004 #define SONIC_RCR_LBK 0x0002 #define SONIC_RCR_PRX 0x0001 #define SONIC_RCR_LB_OFF 0 #define SONIC_RCR_LB_MAC SONIC_RCR_LB0 #define SONIC_RCR_LB_ENDEC SONIC_RCR_LB1 #define SONIC_RCR_LB_TRANS (SONIC_RCR_LB0 | SONIC_RCR_LB1) /* default RCR setup */ #define SONIC_RCR_DEFAULT (SONIC_RCR_BRD) /* * SONIC Transmit Control register bits */ #define SONIC_TCR_PINTR 0x8000 #define SONIC_TCR_POWC 0x4000 #define SONIC_TCR_CRCI 0x2000 #define SONIC_TCR_EXDIS 0x1000 #define SONIC_TCR_EXD 0x0400 #define SONIC_TCR_DEF 0x0200 #define SONIC_TCR_NCRS 0x0100 #define SONIC_TCR_CRLS 0x0080 #define SONIC_TCR_EXC 0x0040 #define SONIC_TCR_PMB 0x0008 #define SONIC_TCR_FU 0x0004 #define SONIC_TCR_BCM 0x0002 #define SONIC_TCR_PTX 0x0001 #define SONIC_TCR_DEFAULT 0x0000 /* * Constants for the SONIC_INTERRUPT_MASK and * SONIC_INTERRUPT_STATUS registers. */ #define SONIC_INT_BR 0x4000 #define SONIC_INT_HBL 0x2000 #define SONIC_INT_LCD 0x1000 #define SONIC_INT_PINT 0x0800 #define SONIC_INT_PKTRX 0x0400 #define SONIC_INT_TXDN 0x0200 #define SONIC_INT_TXER 0x0100 #define SONIC_INT_TC 0x0080 #define SONIC_INT_RDE 0x0040 #define SONIC_INT_RBE 0x0020 #define SONIC_INT_RBAE 0x0010 #define SONIC_INT_CRC 0x0008 #define SONIC_INT_FAE 0x0004 #define SONIC_INT_MP 0x0002 #define SONIC_INT_RFO 0x0001 /* * The interrupts we allow. */ #define SONIC_IMR_DEFAULT ( SONIC_INT_BR | \ SONIC_INT_LCD | \ SONIC_INT_RFO | \ SONIC_INT_PKTRX | \ SONIC_INT_TXDN | \ SONIC_INT_TXER | \ SONIC_INT_RDE | \ SONIC_INT_RBAE | \ SONIC_INT_CRC | \ SONIC_INT_FAE | \ SONIC_INT_MP) #define SONIC_EOL 0x0001 #define CAM_DESCRIPTORS 16 /* Offsets in the various DMA buffers accessed by the SONIC */ #define SONIC_BITMODE16 0 #define SONIC_BITMODE32 1 #define SONIC_BUS_SCALE(bitmode) ((bitmode) ? 4 : 2) /* Note! These are all measured in bus-size units, so use SONIC_BUS_SCALE */ #define SIZEOF_SONIC_RR 4 #define SONIC_RR_BUFADR_L 0 #define SONIC_RR_BUFADR_H 1 #define SONIC_RR_BUFSIZE_L 2 #define SONIC_RR_BUFSIZE_H 3 #define SIZEOF_SONIC_RD 7 #define SONIC_RD_STATUS 0 #define SONIC_RD_PKTLEN 1 #define SONIC_RD_PKTPTR_L 2 #define SONIC_RD_PKTPTR_H 3 #define SONIC_RD_SEQNO 4 #define SONIC_RD_LINK 5 #define SONIC_RD_IN_USE 6 #define SIZEOF_SONIC_TD 8 #define SONIC_TD_STATUS 0 #define SONIC_TD_CONFIG 1 #define SONIC_TD_PKTSIZE 2 #define SONIC_TD_FRAG_COUNT 3 #define SONIC_TD_FRAG_PTR_L 4 #define SONIC_TD_FRAG_PTR_H 5 #define SONIC_TD_FRAG_SIZE 6 #define SONIC_TD_LINK 7 #define SIZEOF_SONIC_CD 4 #define SONIC_CD_ENTRY_POINTER 0 #define SONIC_CD_CAP0 1 #define SONIC_CD_CAP1 2 #define SONIC_CD_CAP2 3 #define SIZEOF_SONIC_CDA ((CAM_DESCRIPTORS * SIZEOF_SONIC_CD) + 1) #define SONIC_CDA_CAM_ENABLE (CAM_DESCRIPTORS * SIZEOF_SONIC_CD) /* * Some tunables for the buffer areas. Power of 2 is required * the current driver uses one receive buffer for each descriptor. * * MSch: use more buffer space for the slow m68k Macs! */ #define SONIC_NUM_RRS 16 /* number of receive resources */ #define SONIC_NUM_RDS SONIC_NUM_RRS /* number of receive descriptors */ #define SONIC_NUM_TDS 16 /* number of transmit descriptors */ #define SONIC_RDS_MASK (SONIC_NUM_RDS-1) #define SONIC_TDS_MASK (SONIC_NUM_TDS-1) #define SONIC_RBSIZE 1520 /* size of one resource buffer */ /* Again, measured in bus size units! */ #define SIZEOF_SONIC_DESC (SIZEOF_SONIC_CDA \ + (SIZEOF_SONIC_TD * SONIC_NUM_TDS) \ + (SIZEOF_SONIC_RD * SONIC_NUM_RDS) \ + (SIZEOF_SONIC_RR * SONIC_NUM_RRS)) /* Information that need to be kept for each board. */ struct sonic_local { /* Bus size. 0 == 16 bits, 1 == 32 bits. */ int dma_bitmode; /* Register offset within the longword (independent of endianness, and varies from one type of Macintosh SONIC to another (Aarrgh)) */ int reg_offset; void *descriptors; /* Crud. These areas have to be within the same 64K. Therefore we allocate a desriptors page, and point these to places within it. */ void *cda; /* CAM descriptor area */ void *tda; /* Transmit descriptor area */ void *rra; /* Receive resource area */ void *rda; /* Receive descriptor area */ struct sk_buff* volatile rx_skb[SONIC_NUM_RRS]; /* packets to be received */ struct sk_buff* volatile tx_skb[SONIC_NUM_TDS]; /* packets to be transmitted */ unsigned int tx_len[SONIC_NUM_TDS]; /* lengths of tx DMA mappings */ /* Logical DMA addresses on MIPS, bus addresses on m68k * (so "laddr" is a bit misleading) */ dma_addr_t descriptors_laddr; u32 cda_laddr; /* logical DMA address of CDA */ u32 tda_laddr; /* logical DMA address of TDA */ u32 rra_laddr; /* logical DMA address of RRA */ u32 rda_laddr; /* logical DMA address of RDA */ dma_addr_t rx_laddr[SONIC_NUM_RRS]; /* logical DMA addresses of rx skbuffs */ dma_addr_t tx_laddr[SONIC_NUM_TDS]; /* logical DMA addresses of tx skbuffs */ unsigned int rra_end; unsigned int cur_rwp; unsigned int cur_rx; unsigned int cur_tx; /* first unacked transmit packet */ unsigned int eol_rx; unsigned int eol_tx; /* last unacked transmit packet */ unsigned int next_tx; /* next free TD */ struct device *device; /* generic device */ struct net_device_stats stats; }; #define TX_TIMEOUT (3 * HZ) /* Index to functions, as function prototypes. */ static int sonic_open(struct net_device *dev); static int sonic_send_packet(struct sk_buff *skb, struct net_device *dev); static irqreturn_t sonic_interrupt(int irq, void *dev_id); static void sonic_rx(struct net_device *dev); static int sonic_close(struct net_device *dev); static struct net_device_stats *sonic_get_stats(struct net_device *dev); static void sonic_multicast_list(struct net_device *dev); static int sonic_init(struct net_device *dev); static void sonic_tx_timeout(struct net_device *dev); /* Internal inlines for reading/writing DMA buffers. Note that bus size and endianness matter here, whereas they don't for registers, as far as we can tell. */ /* OpenBSD calls this "SWO". I'd like to think that sonic_buf_put() is a much better name. */ static inline void sonic_buf_put(void* base, int bitmode, int offset, __u16 val) { if (bitmode) #ifdef __BIG_ENDIAN ((__u16 *) base + (offset*2))[1] = val; #else ((__u16 *) base + (offset*2))[0] = val; #endif else ((__u16 *) base)[offset] = val; } static inline __u16 sonic_buf_get(void* base, int bitmode, int offset) { if (bitmode) #ifdef __BIG_ENDIAN return ((volatile __u16 *) base + (offset*2))[1]; #else return ((volatile __u16 *) base + (offset*2))[0]; #endif else return ((volatile __u16 *) base)[offset]; } /* Inlines that you should actually use for reading/writing DMA buffers */ static inline void sonic_cda_put(struct net_device* dev, int entry, int offset, __u16 val) { struct sonic_local *lp = netdev_priv(dev); sonic_buf_put(lp->cda, lp->dma_bitmode, (entry * SIZEOF_SONIC_CD) + offset, val); } static inline __u16 sonic_cda_get(struct net_device* dev, int entry, int offset) { struct sonic_local *lp = netdev_priv(dev); return sonic_buf_get(lp->cda, lp->dma_bitmode, (entry * SIZEOF_SONIC_CD) + offset); } static inline void sonic_set_cam_enable(struct net_device* dev, __u16 val) { struct sonic_local *lp = netdev_priv(dev); sonic_buf_put(lp->cda, lp->dma_bitmode, SONIC_CDA_CAM_ENABLE, val); } static inline __u16 sonic_get_cam_enable(struct net_device* dev) { struct sonic_local *lp = netdev_priv(dev); return sonic_buf_get(lp->cda, lp->dma_bitmode, SONIC_CDA_CAM_ENABLE); } static inline void sonic_tda_put(struct net_device* dev, int entry, int offset, __u16 val) { struct sonic_local *lp = netdev_priv(dev); sonic_buf_put(lp->tda, lp->dma_bitmode, (entry * SIZEOF_SONIC_TD) + offset, val); } static inline __u16 sonic_tda_get(struct net_device* dev, int entry, int offset) { struct sonic_local *lp = netdev_priv(dev); return sonic_buf_get(lp->tda, lp->dma_bitmode, (entry * SIZEOF_SONIC_TD) + offset); } static inline void sonic_rda_put(struct net_device* dev, int entry, int offset, __u16 val) { struct sonic_local *lp = netdev_priv(dev); sonic_buf_put(lp->rda, lp->dma_bitmode, (entry * SIZEOF_SONIC_RD) + offset, val); } static inline __u16 sonic_rda_get(struct net_device* dev, int entry, int offset) { struct sonic_local *lp = netdev_priv(dev); return sonic_buf_get(lp->rda, lp->dma_bitmode, (entry * SIZEOF_SONIC_RD) + offset); } static inline void sonic_rra_put(struct net_device* dev, int entry, int offset, __u16 val) { struct sonic_local *lp = netdev_priv(dev); sonic_buf_put(lp->rra, lp->dma_bitmode, (entry * SIZEOF_SONIC_RR) + offset, val); } static inline __u16 sonic_rra_get(struct net_device* dev, int entry, int offset) { struct sonic_local *lp = netdev_priv(dev); return sonic_buf_get(lp->rra, lp->dma_bitmode, (entry * SIZEOF_SONIC_RR) + offset); } static const char *version = "sonic.c:v0.92 20.9.98 tsbogend@alpha.franken.de\n"; #endif /* SONIC_H */
{ "language": "C" }
/* Alloc.c -- Memory allocation functions 2018-04-27 : Igor Pavlov : Public domain */ #include "Precomp.h" #include <stdio.h> #ifdef _WIN32 #include <windows.h> #endif #include <stdlib.h> #include "Alloc.h" /* #define _SZ_ALLOC_DEBUG */ /* use _SZ_ALLOC_DEBUG to debug alloc/free operations */ #ifdef _SZ_ALLOC_DEBUG #include <stdio.h> int g_allocCount = 0; int g_allocCountMid = 0; int g_allocCountBig = 0; #define CONVERT_INT_TO_STR(charType, tempSize) \ unsigned char temp[tempSize]; unsigned i = 0; \ while (val >= 10) { temp[i++] = (unsigned char)('0' + (unsigned)(val % 10)); val /= 10; } \ *s++ = (charType)('0' + (unsigned)val); \ while (i != 0) { i--; *s++ = temp[i]; } \ *s = 0; static void ConvertUInt64ToString(UInt64 val, char *s) { CONVERT_INT_TO_STR(char, 24); } #define GET_HEX_CHAR(t) ((char)(((t < 10) ? ('0' + t) : ('A' + (t - 10))))) static void ConvertUInt64ToHex(UInt64 val, char *s) { UInt64 v = val; unsigned i; for (i = 1;; i++) { v >>= 4; if (v == 0) break; } s[i] = 0; do { unsigned t = (unsigned)(val & 0xF); val >>= 4; s[--i] = GET_HEX_CHAR(t); } while (i); } #define DEBUG_OUT_STREAM stderr static void Print(const char *s) { fputs(s, DEBUG_OUT_STREAM); } static void PrintAligned(const char *s, size_t align) { size_t len = strlen(s); for(;;) { fputc(' ', DEBUG_OUT_STREAM); if (len >= align) break; ++len; } Print(s); } static void PrintLn() { Print("\n"); } static void PrintHex(UInt64 v, size_t align) { char s[32]; ConvertUInt64ToHex(v, s); PrintAligned(s, align); } static void PrintDec(UInt64 v, size_t align) { char s[32]; ConvertUInt64ToString(v, s); PrintAligned(s, align); } static void PrintAddr(void *p) { PrintHex((UInt64)(size_t)(ptrdiff_t)p, 12); } #define PRINT_ALLOC(name, cnt, size, ptr) \ Print(name " "); \ PrintDec(cnt++, 10); \ PrintHex(size, 10); \ PrintAddr(ptr); \ PrintLn(); #define PRINT_FREE(name, cnt, ptr) if (ptr) { \ Print(name " "); \ PrintDec(--cnt, 10); \ PrintAddr(ptr); \ PrintLn(); } #else #define PRINT_ALLOC(name, cnt, size, ptr) #define PRINT_FREE(name, cnt, ptr) #define Print(s) #define PrintLn() #define PrintHex(v, align) #define PrintDec(v, align) #define PrintAddr(p) #endif void *MyAlloc(size_t size) { if (size == 0) return NULL; #ifdef _SZ_ALLOC_DEBUG { void *p = malloc(size); PRINT_ALLOC("Alloc ", g_allocCount, size, p); return p; } #else return malloc(size); #endif } void MyFree(void *address) { PRINT_FREE("Free ", g_allocCount, address); free(address); } #ifdef _WIN32 void *MidAlloc(size_t size) { if (size == 0) return NULL; PRINT_ALLOC("Alloc-Mid", g_allocCountMid, size, NULL); return VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE); } void MidFree(void *address) { PRINT_FREE("Free-Mid", g_allocCountMid, address); if (!address) return; VirtualFree(address, 0, MEM_RELEASE); } #ifndef MEM_LARGE_PAGES #undef _7ZIP_LARGE_PAGES #endif #ifdef _7ZIP_LARGE_PAGES SIZE_T g_LargePageSize = 0; typedef SIZE_T (WINAPI *GetLargePageMinimumP)(); #endif void SetLargePageSize() { #ifdef _7ZIP_LARGE_PAGES SIZE_T size; GetLargePageMinimumP largePageMinimum = (GetLargePageMinimumP) GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetLargePageMinimum"); if (!largePageMinimum) return; size = largePageMinimum(); if (size == 0 || (size & (size - 1)) != 0) return; g_LargePageSize = size; #endif } void *BigAlloc(size_t size) { if (size == 0) return NULL; PRINT_ALLOC("Alloc-Big", g_allocCountBig, size, NULL); #ifdef _7ZIP_LARGE_PAGES { SIZE_T ps = g_LargePageSize; if (ps != 0 && ps <= (1 << 30) && size > (ps / 2)) { size_t size2; ps--; size2 = (size + ps) & ~ps; if (size2 >= size) { void *res = VirtualAlloc(NULL, size2, MEM_COMMIT | MEM_LARGE_PAGES, PAGE_READWRITE); if (res) return res; } } } #endif return VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE); } void BigFree(void *address) { PRINT_FREE("Free-Big", g_allocCountBig, address); if (!address) return; VirtualFree(address, 0, MEM_RELEASE); } #endif static void *SzAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p); return MyAlloc(size); } static void SzFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p); MyFree(address); } const ISzAlloc g_Alloc = { SzAlloc, SzFree }; static void *SzMidAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p); return MidAlloc(size); } static void SzMidFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p); MidFree(address); } const ISzAlloc g_MidAlloc = { SzMidAlloc, SzMidFree }; static void *SzBigAlloc(ISzAllocPtr p, size_t size) { UNUSED_VAR(p); return BigAlloc(size); } static void SzBigFree(ISzAllocPtr p, void *address) { UNUSED_VAR(p); BigFree(address); } const ISzAlloc g_BigAlloc = { SzBigAlloc, SzBigFree }; /* uintptr_t : <stdint.h> C99 (optional) : unsupported in VS6 */ #ifdef _WIN32 typedef UINT_PTR UIntPtr; #else /* typedef uintptr_t UIntPtr; */ typedef ptrdiff_t UIntPtr; #endif #define ADJUST_ALLOC_SIZE 0 /* #define ADJUST_ALLOC_SIZE (sizeof(void *) - 1) */ /* Use (ADJUST_ALLOC_SIZE = (sizeof(void *) - 1)), if MyAlloc() can return address that is NOT multiple of sizeof(void *). */ /* #define MY_ALIGN_PTR_DOWN(p, align) ((void *)((char *)(p) - ((size_t)(UIntPtr)(p) & ((align) - 1)))) */ #define MY_ALIGN_PTR_DOWN(p, align) ((void *)((((UIntPtr)(p)) & ~((UIntPtr)(align) - 1)))) #define MY_ALIGN_PTR_UP_PLUS(p, align) MY_ALIGN_PTR_DOWN(((char *)(p) + (align) + ADJUST_ALLOC_SIZE), align) #if (_POSIX_C_SOURCE >= 200112L) && !defined(_WIN32) #define USE_posix_memalign #endif /* This posix_memalign() is for test purposes only. We also need special Free() function instead of free(), if this posix_memalign() is used. */ /* static int posix_memalign(void **ptr, size_t align, size_t size) { size_t newSize = size + align; void *p; void *pAligned; *ptr = NULL; if (newSize < size) return 12; // ENOMEM p = MyAlloc(newSize); if (!p) return 12; // ENOMEM pAligned = MY_ALIGN_PTR_UP_PLUS(p, align); ((void **)pAligned)[-1] = p; *ptr = pAligned; return 0; } */ /* ALLOC_ALIGN_SIZE >= sizeof(void *) ALLOC_ALIGN_SIZE >= cache_line_size */ #define ALLOC_ALIGN_SIZE ((size_t)1 << 7) static void *SzAlignedAlloc(ISzAllocPtr pp, size_t size) { #ifndef USE_posix_memalign void *p; void *pAligned; size_t newSize; UNUSED_VAR(pp); /* also we can allocate additional dummy ALLOC_ALIGN_SIZE bytes after aligned block to prevent cache line sharing with another allocated blocks */ newSize = size + ALLOC_ALIGN_SIZE * 1 + ADJUST_ALLOC_SIZE; if (newSize < size) return NULL; p = MyAlloc(newSize); if (!p) return NULL; pAligned = MY_ALIGN_PTR_UP_PLUS(p, ALLOC_ALIGN_SIZE); Print(" size="); PrintHex(size, 8); Print(" a_size="); PrintHex(newSize, 8); Print(" ptr="); PrintAddr(p); Print(" a_ptr="); PrintAddr(pAligned); PrintLn(); ((void **)pAligned)[-1] = p; return pAligned; #else void *p; UNUSED_VAR(pp); if (posix_memalign(&p, ALLOC_ALIGN_SIZE, size)) return NULL; Print(" posix_memalign="); PrintAddr(p); PrintLn(); return p; #endif } static void SzAlignedFree(ISzAllocPtr pp, void *address) { UNUSED_VAR(pp); #ifndef USE_posix_memalign if (address) MyFree(((void **)address)[-1]); #else free(address); #endif } const ISzAlloc g_AlignedAlloc = { SzAlignedAlloc, SzAlignedFree }; #define MY_ALIGN_PTR_DOWN_1(p) MY_ALIGN_PTR_DOWN(p, sizeof(void *)) /* we align ptr to support cases where CAlignOffsetAlloc::offset is not multiply of sizeof(void *) */ #define REAL_BLOCK_PTR_VAR(p) ((void **)MY_ALIGN_PTR_DOWN_1(p))[-1] /* #define REAL_BLOCK_PTR_VAR(p) ((void **)(p))[-1] */ static void *AlignOffsetAlloc_Alloc(ISzAllocPtr pp, size_t size) { CAlignOffsetAlloc *p = CONTAINER_FROM_VTBL(pp, CAlignOffsetAlloc, vt); void *adr; void *pAligned; size_t newSize; size_t extra; size_t alignSize = (size_t)1 << p->numAlignBits; if (alignSize < sizeof(void *)) alignSize = sizeof(void *); if (p->offset >= alignSize) return NULL; /* also we can allocate additional dummy ALLOC_ALIGN_SIZE bytes after aligned block to prevent cache line sharing with another allocated blocks */ extra = p->offset & (sizeof(void *) - 1); newSize = size + alignSize + extra + ADJUST_ALLOC_SIZE; if (newSize < size) return NULL; adr = ISzAlloc_Alloc(p->baseAlloc, newSize); if (!adr) return NULL; pAligned = (char *)MY_ALIGN_PTR_DOWN((char *)adr + alignSize - p->offset + extra + ADJUST_ALLOC_SIZE, alignSize) + p->offset; PrintLn(); Print("- Aligned: "); Print(" size="); PrintHex(size, 8); Print(" a_size="); PrintHex(newSize, 8); Print(" ptr="); PrintAddr(adr); Print(" a_ptr="); PrintAddr(pAligned); PrintLn(); REAL_BLOCK_PTR_VAR(pAligned) = adr; return pAligned; } static void AlignOffsetAlloc_Free(ISzAllocPtr pp, void *address) { if (address) { CAlignOffsetAlloc *p = CONTAINER_FROM_VTBL(pp, CAlignOffsetAlloc, vt); PrintLn(); Print("- Aligned Free: "); PrintLn(); ISzAlloc_Free(p->baseAlloc, REAL_BLOCK_PTR_VAR(address)); } } void AlignOffsetAlloc_CreateVTable(CAlignOffsetAlloc *p) { p->vt.Alloc = AlignOffsetAlloc_Alloc; p->vt.Free = AlignOffsetAlloc_Free; }
{ "language": "C" }
/* * write.c * * Copyright 2000 Alistair Riddoch * ajr@ecs.soton.ac.uk * * This file may be distributed under the terms of the GNU General Public * License v2, or at your option any later version. */ /* * This is a small version of write for use in the ELKS project. */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <unistd.h> #include <pwd.h> #include <utmp.h> #include <fcntl.h> #include <string.h> #define TTYPREFIX "/dev/" void write_usage(char ** argv) { fprintf(stderr, "%s user [ttyname]\n", argv[0]); exit(1); } int write_main(int argc, char ** argv) { char ttyname[12]; struct passwd * pwdent; int ofd = -1; char buf[255]; int n; if ((argc > 3) || (argc < 2)) { usage(argv); } if ((pwdent = getpwnam(argv[1])) == NULL) { fprintf(stderr, "%s: No such user %s\n", argv[0], argv[1]); exit(1); } if (argc == 3) { struct stat sbuf; strncpy(ttyname, TTYPREFIX, 6); strncat(ttyname, argv[2], 6); ttyname[11] = '\0'; if (stat(ttyname, &sbuf) != 0) { fprintf(stderr, "%s: No such tty %s\n", argv[0], ttyname); exit(1); } if (pwdent->pw_uid != sbuf.st_uid) { fprintf(stderr, "%s: User %s is not logged onto %s\n", argv[0], argv[1], argv[2]); exit(1); } if ((ofd = open(ttyname, O_WRONLY)) < 0) { fprintf(stderr, "%s: %s has messages disabled on %s\n", argv[0], argv[1], argv[2]); exit(1); } } else { /* argc == 2 */ struct utmp * utmp; setutent(); while ((utmp = getutent()) != NULL) { if ((strcmp(pwdent->pw_name, utmp->ut_user) == 0) && (utmp->ut_type == USER_PROCESS)) { strncpy(ttyname, TTYPREFIX, 6); strncat(ttyname, utmp->ut_line, 6); ttyname[11] = '\0'; if ((ofd = open(ttyname, O_WRONLY)) >= 0) { break; } } } if (ofd < 0) { fprintf(stderr, "%s: User %s not logged in, or has messages disabled\n", argv[0], argv[1]); exit(1); } } if ((pwdent = getpwnam(argv[1])) == NULL) { fprintf(stderr, "%s: Who are you?\n", argv[0]); exit(1); } write(ofd, "Message from ", 13); write(ofd, pwdent->pw_name, strlen(pwdent->pw_name)); write(ofd, "\n", 1); while ((n = read(STDIN_FILENO, buf, 254)) > 0) { buf[254] = '\0'; write(ofd, buf, n); } write(ofd, "EOF\n", 4); exit(0); }
{ "language": "C" }
#include "license_pbs.h" /* See here for the software license */ #include <pbs_config.h> /* the master config generated by configure */ #include <assert.h> #include <ctype.h> #include <memory.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> /* LONG_MIN, LONG_MAX */ #include "pbs_ifl.h" #include "list_link.h" #include "attribute.h" #include "pbs_error.h" #include "pbs_helper.h" /* * This file contains functions for manipulating attributes of type * Long integer, where "Long" is defined as the largest integer * available. * * Each set has functions for: * Decoding the value string to the machine representation. * Encoding the internal pbs_attribute to external form * Setting the value by =, + or - operators. * Comparing a (decoded) value with the pbs_attribute value. * * Some or all of the functions for an pbs_attribute type may be shared with * other pbs_attribute types. * * The prototypes are declared in "attribute.h" * * -------------------------------------------------- * The Set of pbs_Attribute Functions for attributes with * value type "Long" (_ll) * -------------------------------------------------- */ /* * decode_ll - decode Long integer into pbs_attribute structure * Unlike decode_long, this function will decode octal (leading zero) and * hex (leading 0x or 0X) data as well as decimal * * Returns: 0 if ok * >0 error number if error * *patr elements set */ int decode_ll( pbs_attribute *patr, const char * UNUSED(name), /* pbs_attribute name */ const char * UNUSED(rescn), /* resource name, unused here */ const char *val, /* pbs_attribute value */ int UNUSED(perm)) /* only used for resources */ { if ((val != (char *)0) && (strlen(val) != 0)) { patr->at_val.at_ll = atoL(val); if ((patr->at_val.at_ll == LONG_MIN) || (patr->at_val.at_ll == LONG_MAX)) return (PBSE_BADATVAL); /* invalid string */ patr->at_flags |= ATR_VFLAG_SET | ATR_VFLAG_MODIFY; } else { patr->at_flags = (patr->at_flags & ~ATR_VFLAG_SET) | ATR_VFLAG_MODIFY; patr->at_val.at_ll = 0; } return (0); } /* * encode_ll - encode pbs_attribute of type Long into attr_extern * * Returns: >0 if ok * =0 if no value, no attrlist link added * <0 if error */ /*ARGSUSED*/ int encode_ll( pbs_attribute *attr, /* ptr to pbs_attribute */ tlist_head *phead, /* head of attrlist list */ const char *atname, /* pbs_attribute name */ const char *rsname, /* resource name or null */ int UNUSED(mode), /* encode mode, unused here */ int UNUSED(perm)) /* only used for resources */ { size_t ct; char cvn[MAXLONGLEN+1]; svrattrl *pal; if (!attr) return (-1); if (!(attr->at_flags & ATR_VFLAG_SET)) return (0); snprintf(cvn, MAXLONGLEN, LLD, attr->at_val.at_ll); ct = strlen(cvn); if ((pal = attrlist_create(atname, rsname, ct + 1)) == NULL) return (-1); memcpy(pal->al_value, cvn, ct); pal->al_flags = attr->at_flags; append_link(phead, &pal->al_link, pal); return (1); } /* * set_ll - set pbs_attribute A to pbs_attribute B, * either A=B, A += B, or A -= B * * Returns: 0 if ok * >0 if error */ int set_ll( pbs_attribute *attr, pbs_attribute *new_attr, enum batch_op op) { assert(attr && new_attr && (new_attr->at_flags & ATR_VFLAG_SET)); switch (op) { case SET: attr->at_val.at_ll = new_attr->at_val.at_ll; break; case INCR: attr->at_val.at_ll += new_attr->at_val.at_ll; break; case DECR: attr->at_val.at_ll -= new_attr->at_val.at_ll; break; default: return (PBSE_INTERNAL); } attr->at_flags |= ATR_VFLAG_SET | ATR_VFLAG_MODIFY; return (0); } /* * comp_ll - compare two attributes of type Long * * Returns: +1 if 1st > 2nd * 0 if 1st == 2nd * -1 if 1st < 2nd */ int comp_ll( pbs_attribute *attr, pbs_attribute *with) { if (!attr || !with) return (-1); if (attr->at_val.at_ll < with->at_val.at_ll) return (-1); else if (attr->at_val.at_ll > with->at_val.at_ll) return (1); else return (0); } /* * free_ll - use free_null to (not) free space */
{ "language": "C" }
/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2009 * * by the Xiph.Org Foundation http://www.xiph.org/ * * * ******************************************************************** function: stdio-based convenience library for opening/seeking/decoding last mod: $Id: vorbisfile.c 17573 2010-10-27 14:53:59Z xiphmont $ ********************************************************************/ #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <math.h> #include "vorbis/codec.h" /* we don't need or want the static callback symbols here */ #define OV_EXCLUDE_STATIC_CALLBACKS #include "vorbis/vorbisfile.h" #include "os.h" #include "misc.h" /* A 'chained bitstream' is a Vorbis bitstream that contains more than one logical bitstream arranged end to end (the only form of Ogg multiplexing allowed in a Vorbis bitstream; grouping [parallel multiplexing] is not allowed in Vorbis) */ /* A Vorbis file can be played beginning to end (streamed) without worrying ahead of time about chaining (see decoder_example.c). If we have the whole file, however, and want random access (seeking/scrubbing) or desire to know the total length/time of a file, we need to account for the possibility of chaining. */ /* We can handle things a number of ways; we can determine the entire bitstream structure right off the bat, or find pieces on demand. This example determines and caches structure for the entire bitstream, but builds a virtual decoder on the fly when moving between links in the chain. */ /* There are also different ways to implement seeking. Enough information exists in an Ogg bitstream to seek to sample-granularity positions in the output. Or, one can seek by picking some portion of the stream roughly in the desired area if we only want coarse navigation through the stream. */ /************************************************************************* * Many, many internal helpers. The intention is not to be confusing; * rampant duplication and monolithic function implementation would be * harder to understand anyway. The high level functions are last. Begin * grokking near the end of the file */ /* read a little more data from the file/pipe into the ogg_sync framer */ #define CHUNKSIZE 65536 /* greater-than-page-size granularity seeking */ #define READSIZE 2048 /* a smaller read size is needed for low-rate streaming. */ static long _get_data(OggVorbis_File *vf){ errno=0; if(!(vf->callbacks.read_func))return(-1); if(vf->datasource){ char *buffer=ogg_sync_buffer(&vf->oy,READSIZE); long bytes=(vf->callbacks.read_func)(buffer,1,READSIZE,vf->datasource); if(bytes>0)ogg_sync_wrote(&vf->oy,bytes); if(bytes==0 && errno)return(-1); return(bytes); }else return(0); } /* save a tiny smidge of verbosity to make the code more readable */ static int _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){ if(vf->datasource){ if(!(vf->callbacks.seek_func)|| (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET) == -1) return OV_EREAD; vf->offset=offset; ogg_sync_reset(&vf->oy); }else{ /* shouldn't happen unless someone writes a broken callback */ return OV_EFAULT; } return 0; } /* The read/seek functions track absolute position within the stream */ /* from the head of the stream, get the next page. boundary specifies if the function is allowed to fetch more data from the stream (and how much) or only use internally buffered data. boundary: -1) unbounded search 0) read no additional data; use cached only n) search for a new page beginning for n bytes return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD) n) found a page at absolute offset n */ static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og, ogg_int64_t boundary){ if(boundary>0)boundary+=vf->offset; while(1){ long more; if(boundary>0 && vf->offset>=boundary)return(OV_FALSE); more=ogg_sync_pageseek(&vf->oy,og); if(more<0){ /* skipped n bytes */ vf->offset-=more; }else{ if(more==0){ /* send more paramedics */ if(!boundary)return(OV_FALSE); { long ret=_get_data(vf); if(ret==0)return(OV_EOF); if(ret<0)return(OV_EREAD); } }else{ /* got a page. Return the offset at the page beginning, advance the internal offset past the page end */ ogg_int64_t ret=vf->offset; vf->offset+=more; return(ret); } } } } /* find the latest page beginning before the current stream cursor position. Much dirtier than the above as Ogg doesn't have any backward search linkage. no 'readp' as it will certainly have to read. */ /* returns offset or OV_EREAD, OV_FAULT */ static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){ ogg_int64_t begin=vf->offset; ogg_int64_t end=begin; ogg_int64_t ret; ogg_int64_t offset=-1; while(offset==-1){ begin-=CHUNKSIZE; if(begin<0) begin=0; ret=_seek_helper(vf,begin); if(ret)return(ret); while(vf->offset<end){ memset(og,0,sizeof(*og)); ret=_get_next_page(vf,og,end-vf->offset); if(ret==OV_EREAD)return(OV_EREAD); if(ret<0){ break; }else{ offset=ret; } } } /* In a fully compliant, non-multiplexed stream, we'll still be holding the last page. In multiplexed (or noncompliant streams), we will probably have to re-read the last page we saw */ if(og->header_len==0){ ret=_seek_helper(vf,offset); if(ret)return(ret); ret=_get_next_page(vf,og,CHUNKSIZE); if(ret<0) /* this shouldn't be possible */ return(OV_EFAULT); } return(offset); } static void _add_serialno(ogg_page *og,long **serialno_list, int *n){ long s = ogg_page_serialno(og); (*n)++; if(*serialno_list){ *serialno_list = _ogg_realloc(*serialno_list, sizeof(**serialno_list)*(*n)); }else{ *serialno_list = _ogg_malloc(sizeof(**serialno_list)); } (*serialno_list)[(*n)-1] = s; } /* returns nonzero if found */ static int _lookup_serialno(long s, long *serialno_list, int n){ if(serialno_list){ while(n--){ if(*serialno_list == s) return 1; serialno_list++; } } return 0; } static int _lookup_page_serialno(ogg_page *og, long *serialno_list, int n){ long s = ogg_page_serialno(og); return _lookup_serialno(s,serialno_list,n); } /* performs the same search as _get_prev_page, but prefers pages of the specified serial number. If a page of the specified serialno is spotted during the seek-back-and-read-forward, it will return the info of last page of the matching serial number instead of the very last page. If no page of the specified serialno is seen, it will return the info of last page and alter *serialno. */ static ogg_int64_t _get_prev_page_serial(OggVorbis_File *vf, long *serial_list, int serial_n, int *serialno, ogg_int64_t *granpos){ ogg_page og; ogg_int64_t begin=vf->offset; ogg_int64_t end=begin; ogg_int64_t ret; ogg_int64_t prefoffset=-1; ogg_int64_t offset=-1; ogg_int64_t ret_serialno=-1; ogg_int64_t ret_gran=-1; while(offset==-1){ begin-=CHUNKSIZE; if(begin<0) begin=0; ret=_seek_helper(vf,begin); if(ret)return(ret); while(vf->offset<end){ ret=_get_next_page(vf,&og,end-vf->offset); if(ret==OV_EREAD)return(OV_EREAD); if(ret<0){ break; }else{ ret_serialno=ogg_page_serialno(&og); ret_gran=ogg_page_granulepos(&og); offset=ret; if(ret_serialno == *serialno){ prefoffset=ret; *granpos=ret_gran; } if(!_lookup_serialno(ret_serialno,serial_list,serial_n)){ /* we fell off the end of the link, which means we seeked back too far and shouldn't have been looking in that link to begin with. If we found the preferred serial number, forget that we saw it. */ prefoffset=-1; } } } } /* we're not interested in the page... just the serialno and granpos. */ if(prefoffset>=0)return(prefoffset); *serialno = ret_serialno; *granpos = ret_gran; return(offset); } /* uses the local ogg_stream storage in vf; this is important for non-streaming input sources */ static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc, long **serialno_list, int *serialno_n, ogg_page *og_ptr){ ogg_page og; ogg_packet op; int i,ret; int allbos=0; if(!og_ptr){ ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE); if(llret==OV_EREAD)return(OV_EREAD); if(llret<0)return(OV_ENOTVORBIS); og_ptr=&og; } vorbis_info_init(vi); vorbis_comment_init(vc); vf->ready_state=OPENED; /* extract the serialnos of all BOS pages + the first set of vorbis headers we see in the link */ while(ogg_page_bos(og_ptr)){ if(serialno_list){ if(_lookup_page_serialno(og_ptr,*serialno_list,*serialno_n)){ /* a dupe serialnumber in an initial header packet set == invalid stream */ if(*serialno_list)_ogg_free(*serialno_list); *serialno_list=0; *serialno_n=0; ret=OV_EBADHEADER; goto bail_header; } _add_serialno(og_ptr,serialno_list,serialno_n); } if(vf->ready_state<STREAMSET){ /* we don't have a vorbis stream in this link yet, so begin prospective stream setup. We need a stream to get packets */ ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr)); ogg_stream_pagein(&vf->os,og_ptr); if(ogg_stream_packetout(&vf->os,&op) > 0 && vorbis_synthesis_idheader(&op)){ /* vorbis header; continue setup */ vf->ready_state=STREAMSET; if((ret=vorbis_synthesis_headerin(vi,vc,&op))){ ret=OV_EBADHEADER; goto bail_header; } } } /* get next page */ { ogg_int64_t llret=_get_next_page(vf,og_ptr,CHUNKSIZE); if(llret==OV_EREAD){ ret=OV_EREAD; goto bail_header; } if(llret<0){ ret=OV_ENOTVORBIS; goto bail_header; } /* if this page also belongs to our vorbis stream, submit it and break */ if(vf->ready_state==STREAMSET && vf->os.serialno == ogg_page_serialno(og_ptr)){ ogg_stream_pagein(&vf->os,og_ptr); break; } } } if(vf->ready_state!=STREAMSET){ ret = OV_ENOTVORBIS; goto bail_header; } while(1){ i=0; while(i<2){ /* get a page loop */ while(i<2){ /* get a packet loop */ int result=ogg_stream_packetout(&vf->os,&op); if(result==0)break; if(result==-1){ ret=OV_EBADHEADER; goto bail_header; } if((ret=vorbis_synthesis_headerin(vi,vc,&op))) goto bail_header; i++; } while(i<2){ if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){ ret=OV_EBADHEADER; goto bail_header; } /* if this page belongs to the correct stream, go parse it */ if(vf->os.serialno == ogg_page_serialno(og_ptr)){ ogg_stream_pagein(&vf->os,og_ptr); break; } /* if we never see the final vorbis headers before the link ends, abort */ if(ogg_page_bos(og_ptr)){ if(allbos){ ret = OV_EBADHEADER; goto bail_header; }else allbos=1; } /* otherwise, keep looking */ } } return 0; } bail_header: vorbis_info_clear(vi); vorbis_comment_clear(vc); vf->ready_state=OPENED; return ret; } /* Starting from current cursor position, get initial PCM offset of next page. Consumes the page in the process without decoding audio, however this is only called during stream parsing upon seekable open. */ static ogg_int64_t _initial_pcmoffset(OggVorbis_File *vf, vorbis_info *vi){ ogg_page og; ogg_int64_t accumulated=0; long lastblock=-1; int result; int serialno = vf->os.serialno; while(1){ ogg_packet op; if(_get_next_page(vf,&og,-1)<0) break; /* should not be possible unless the file is truncated/mangled */ if(ogg_page_bos(&og)) break; if(ogg_page_serialno(&og)!=serialno) continue; /* count blocksizes of all frames in the page */ ogg_stream_pagein(&vf->os,&og); while((result=ogg_stream_packetout(&vf->os,&op))){ if(result>0){ /* ignore holes */ long thisblock=vorbis_packet_blocksize(vi,&op); if(lastblock!=-1) accumulated+=(lastblock+thisblock)>>2; lastblock=thisblock; } } if(ogg_page_granulepos(&og)!=-1){ /* pcm offset of last packet on the first audio page */ accumulated= ogg_page_granulepos(&og)-accumulated; break; } } /* less than zero? Either a corrupt file or a stream with samples trimmed off the beginning, a normal occurrence; in both cases set the offset to zero */ if(accumulated<0)accumulated=0; return accumulated; } /* finds each bitstream link one at a time using a bisection search (has to begin by knowing the offset of the lb's initial page). Recurses for each link so it can alloc the link storage after finding them all, then unroll and fill the cache at the same time */ static int _bisect_forward_serialno(OggVorbis_File *vf, ogg_int64_t begin, ogg_int64_t searched, ogg_int64_t end, ogg_int64_t endgran, int endserial, long *currentno_list, int currentnos, long m){ ogg_int64_t pcmoffset; ogg_int64_t dataoffset=searched; ogg_int64_t endsearched=end; ogg_int64_t next=end; ogg_int64_t searchgran=-1; ogg_page og; ogg_int64_t ret,last; int serialno = vf->os.serialno; /* invariants: we have the headers and serialnos for the link beginning at 'begin' we have the offset and granpos of the last page in the file (potentially not a page we care about) */ /* Is the last page in our list of current serialnumbers? */ if(_lookup_serialno(endserial,currentno_list,currentnos)){ /* last page is in the starting serialno list, so we've bisected down to (or just started with) a single link. Now we need to find the last vorbis page belonging to the first vorbis stream for this link. */ while(endserial != serialno){ endserial = serialno; vf->offset=_get_prev_page_serial(vf,currentno_list,currentnos,&endserial,&endgran); } vf->links=m+1; if(vf->offsets)_ogg_free(vf->offsets); if(vf->serialnos)_ogg_free(vf->serialnos); if(vf->dataoffsets)_ogg_free(vf->dataoffsets); vf->offsets=_ogg_malloc((vf->links+1)*sizeof(*vf->offsets)); vf->vi=_ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi)); vf->vc=_ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc)); vf->serialnos=_ogg_malloc(vf->links*sizeof(*vf->serialnos)); vf->dataoffsets=_ogg_malloc(vf->links*sizeof(*vf->dataoffsets)); vf->pcmlengths=_ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths)); vf->offsets[m+1]=end; vf->offsets[m]=begin; vf->pcmlengths[m*2+1]=(endgran<0?0:endgran); }else{ long *next_serialno_list=NULL; int next_serialnos=0; vorbis_info vi; vorbis_comment vc; /* the below guards against garbage seperating the last and first pages of two links. */ while(searched<endsearched){ ogg_int64_t bisect; if(endsearched-searched<CHUNKSIZE){ bisect=searched; }else{ bisect=(searched+endsearched)/2; } if(bisect != vf->offset){ ret=_seek_helper(vf,bisect); if(ret)return(ret); } last=_get_next_page(vf,&og,-1); if(last==OV_EREAD)return(OV_EREAD); if(last<0 || !_lookup_page_serialno(&og,currentno_list,currentnos)){ endsearched=bisect; if(last>=0)next=last; }else{ searched=vf->offset; } } /* Bisection point found */ /* for the time being, fetch end PCM offset the simple way */ { int testserial = serialno+1; vf->offset = next; while(testserial != serialno){ testserial = serialno; vf->offset=_get_prev_page_serial(vf,currentno_list,currentnos,&testserial,&searchgran); } } if(vf->offset!=next){ ret=_seek_helper(vf,next); if(ret)return(ret); } ret=_fetch_headers(vf,&vi,&vc,&next_serialno_list,&next_serialnos,NULL); if(ret)return(ret); serialno = vf->os.serialno; dataoffset = vf->offset; /* this will consume a page, however the next bistection always starts with a raw seek */ pcmoffset = _initial_pcmoffset(vf,&vi); ret=_bisect_forward_serialno(vf,next,vf->offset,end,endgran,endserial, next_serialno_list,next_serialnos,m+1); if(ret)return(ret); if(next_serialno_list)_ogg_free(next_serialno_list); vf->offsets[m+1]=next; vf->serialnos[m+1]=serialno; vf->dataoffsets[m+1]=dataoffset; vf->vi[m+1]=vi; vf->vc[m+1]=vc; vf->pcmlengths[m*2+1]=searchgran; vf->pcmlengths[m*2+2]=pcmoffset; vf->pcmlengths[m*2+3]-=pcmoffset; if(vf->pcmlengths[m*2+3]<0)vf->pcmlengths[m*2+3]=0; } return(0); } static int _make_decode_ready(OggVorbis_File *vf){ if(vf->ready_state>STREAMSET)return 0; if(vf->ready_state<STREAMSET)return OV_EFAULT; if(vf->seekable){ if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link)) return OV_EBADLINK; }else{ if(vorbis_synthesis_init(&vf->vd,vf->vi)) return OV_EBADLINK; } vorbis_block_init(&vf->vd,&vf->vb); vf->ready_state=INITSET; vf->bittrack=0.f; vf->samptrack=0.f; return 0; } static int _open_seekable2(OggVorbis_File *vf){ ogg_int64_t dataoffset=vf->dataoffsets[0],end,endgran=-1; int endserial=vf->os.serialno; int serialno=vf->os.serialno; /* we're partially open and have a first link header state in storage in vf */ /* fetch initial PCM offset */ ogg_int64_t pcmoffset = _initial_pcmoffset(vf,vf->vi); /* we can seek, so set out learning all about this file */ if(vf->callbacks.seek_func && vf->callbacks.tell_func){ (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END); vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource); }else{ vf->offset=vf->end=-1; } /* If seek_func is implemented, tell_func must also be implemented */ if(vf->end==-1) return(OV_EINVAL); /* Get the offset of the last page of the physical bitstream, or, if we're lucky the last vorbis page of this link as most OggVorbis files will contain a single logical bitstream */ end=_get_prev_page_serial(vf,vf->serialnos+2,vf->serialnos[1],&endserial,&endgran); if(end<0)return(end); /* now determine bitstream structure recursively */ if(_bisect_forward_serialno(vf,0,dataoffset,vf->offset,endgran,endserial, vf->serialnos+2,vf->serialnos[1],0)<0)return(OV_EREAD); vf->offsets[0]=0; vf->serialnos[0]=serialno; vf->dataoffsets[0]=dataoffset; vf->pcmlengths[0]=pcmoffset; vf->pcmlengths[1]-=pcmoffset; if(vf->pcmlengths[1]<0)vf->pcmlengths[1]=0; return(ov_raw_seek(vf,dataoffset)); } /* clear out the current logical bitstream decoder */ static void _decode_clear(OggVorbis_File *vf){ vorbis_dsp_clear(&vf->vd); vorbis_block_clear(&vf->vb); vf->ready_state=OPENED; } /* fetch and process a packet. Handles the case where we're at a bitstream boundary and dumps the decoding machine. If the decoding machine is unloaded, it loads it. It also keeps pcm_offset up to date (seek and read both use this. seek uses a special hack with readp). return: <0) error, OV_HOLE (lost packet) or OV_EOF 0) need more data (only if readp==0) 1) got a packet */ static int _fetch_and_process_packet(OggVorbis_File *vf, ogg_packet *op_in, int readp, int spanp){ ogg_page og; /* handle one packet. Try to fetch it from current stream state */ /* extract packets from page */ while(1){ if(vf->ready_state==STREAMSET){ int ret=_make_decode_ready(vf); if(ret<0)return ret; } /* process a packet if we can. */ if(vf->ready_state==INITSET){ int hs=vorbis_synthesis_halfrate_p(vf->vi); while(1) { ogg_packet op; ogg_packet *op_ptr=(op_in?op_in:&op); int result=ogg_stream_packetout(&vf->os,op_ptr); ogg_int64_t granulepos; op_in=NULL; if(result==-1)return(OV_HOLE); /* hole in the data. */ if(result>0){ /* got a packet. process it */ granulepos=op_ptr->granulepos; if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy header handling. The header packets aren't audio, so if/when we submit them, vorbis_synthesis will reject them */ /* suck in the synthesis data and track bitrate */ { int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL); /* for proper use of libvorbis within libvorbisfile, oldsamples will always be zero. */ if(oldsamples)return(OV_EFAULT); vorbis_synthesis_blockin(&vf->vd,&vf->vb); vf->samptrack+=(vorbis_synthesis_pcmout(&vf->vd,NULL)<<hs); vf->bittrack+=op_ptr->bytes*8; } /* update the pcm offset. */ if(granulepos!=-1 && !op_ptr->e_o_s){ int link=(vf->seekable?vf->current_link:0); int i,samples; /* this packet has a pcm_offset on it (the last packet completed on a page carries the offset) After processing (above), we know the pcm position of the *last* sample ready to be returned. Find the offset of the *first* As an aside, this trick is inaccurate if we begin reading anew right at the last page; the end-of-stream granulepos declares the last frame in the stream, and the last packet of the last page may be a partial frame. So, we need a previous granulepos from an in-sequence page to have a reference point. Thus the !op_ptr->e_o_s clause above */ if(vf->seekable && link>0) granulepos-=vf->pcmlengths[link*2]; if(granulepos<0)granulepos=0; /* actually, this shouldn't be possible here unless the stream is very broken */ samples=(vorbis_synthesis_pcmout(&vf->vd,NULL)<<hs); granulepos-=samples; for(i=0;i<link;i++) granulepos+=vf->pcmlengths[i*2+1]; vf->pcm_offset=granulepos; } return(1); } } else break; } } if(vf->ready_state>=OPENED){ ogg_int64_t ret; while(1){ /* the loop is not strictly necessary, but there's no sense in doing the extra checks of the larger loop for the common case in a multiplexed bistream where the page is simply part of a different logical bitstream; keep reading until we get one with the correct serialno */ if(!readp)return(0); if((ret=_get_next_page(vf,&og,-1))<0){ return(OV_EOF); /* eof. leave unitialized */ } /* bitrate tracking; add the header's bytes here, the body bytes are done by packet above */ vf->bittrack+=og.header_len*8; if(vf->ready_state==INITSET){ if(vf->current_serialno!=ogg_page_serialno(&og)){ /* two possibilities: 1) our decoding just traversed a bitstream boundary 2) another stream is multiplexed into this logical section */ if(ogg_page_bos(&og)){ /* boundary case */ if(!spanp) return(OV_EOF); _decode_clear(vf); if(!vf->seekable){ vorbis_info_clear(vf->vi); vorbis_comment_clear(vf->vc); } break; }else continue; /* possibility #2 */ } } break; } } /* Do we need to load a new machine before submitting the page? */ /* This is different in the seekable and non-seekable cases. In the seekable case, we already have all the header information loaded and cached; we just initialize the machine with it and continue on our merry way. In the non-seekable (streaming) case, we'll only be at a boundary if we just left the previous logical bitstream and we're now nominally at the header of the next bitstream */ if(vf->ready_state!=INITSET){ int link; if(vf->ready_state<STREAMSET){ if(vf->seekable){ long serialno = ogg_page_serialno(&og); /* match the serialno to bitstream section. We use this rather than offset positions to avoid problems near logical bitstream boundaries */ for(link=0;link<vf->links;link++) if(vf->serialnos[link]==serialno)break; if(link==vf->links) continue; /* not the desired Vorbis bitstream section; keep trying */ vf->current_serialno=serialno; vf->current_link=link; ogg_stream_reset_serialno(&vf->os,vf->current_serialno); vf->ready_state=STREAMSET; }else{ /* we're streaming */ /* fetch the three header packets, build the info struct */ int ret=_fetch_headers(vf,vf->vi,vf->vc,NULL,NULL,&og); if(ret)return(ret); vf->current_serialno=vf->os.serialno; vf->current_link++; link=0; } } } /* the buffered page is the data we want, and we're ready for it; add it to the stream state */ ogg_stream_pagein(&vf->os,&og); } } /* if, eg, 64 bit stdio is configured by default, this will build with fseek64 */ static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){ if(f==NULL)return(-1); return fseek(f,off,whence); } static int _ov_open1(void *f,OggVorbis_File *vf,const char *initial, long ibytes, ov_callbacks callbacks){ int offsettest=((f && callbacks.seek_func)?callbacks.seek_func(f,0,SEEK_CUR):-1); long *serialno_list=NULL; int serialno_list_size=0; int ret; memset(vf,0,sizeof(*vf)); vf->datasource=f; vf->callbacks = callbacks; /* init the framing state */ ogg_sync_init(&vf->oy); /* perhaps some data was previously read into a buffer for testing against other stream types. Allow initialization from this previously read data (especially as we may be reading from a non-seekable stream) */ if(initial){ char *buffer=ogg_sync_buffer(&vf->oy,ibytes); memcpy(buffer,initial,ibytes); ogg_sync_wrote(&vf->oy,ibytes); } /* can we seek? Stevens suggests the seek test was portable */ if(offsettest!=-1)vf->seekable=1; /* No seeking yet; Set up a 'single' (current) logical bitstream entry for partial open */ vf->links=1; vf->vi=_ogg_calloc(vf->links,sizeof(*vf->vi)); vf->vc=_ogg_calloc(vf->links,sizeof(*vf->vc)); ogg_stream_init(&vf->os,-1); /* fill in the serialno later */ /* Fetch all BOS pages, store the vorbis header and all seen serial numbers, load subsequent vorbis setup headers */ if((ret=_fetch_headers(vf,vf->vi,vf->vc,&serialno_list,&serialno_list_size,NULL))<0){ vf->datasource=NULL; ov_clear(vf); }else{ /* serial number list for first link needs to be held somewhere for second stage of seekable stream open; this saves having to seek/reread first link's serialnumber data then. */ vf->serialnos=_ogg_calloc(serialno_list_size+2,sizeof(*vf->serialnos)); vf->serialnos[0]=vf->current_serialno=vf->os.serialno; vf->serialnos[1]=serialno_list_size; memcpy(vf->serialnos+2,serialno_list,serialno_list_size*sizeof(*vf->serialnos)); vf->offsets=_ogg_calloc(1,sizeof(*vf->offsets)); vf->dataoffsets=_ogg_calloc(1,sizeof(*vf->dataoffsets)); vf->offsets[0]=0; vf->dataoffsets[0]=vf->offset; vf->ready_state=PARTOPEN; } if(serialno_list)_ogg_free(serialno_list); return(ret); } static int _ov_open2(OggVorbis_File *vf){ if(vf->ready_state != PARTOPEN) return OV_EINVAL; vf->ready_state=OPENED; if(vf->seekable){ int ret=_open_seekable2(vf); if(ret){ vf->datasource=NULL; ov_clear(vf); } return(ret); }else vf->ready_state=STREAMSET; return 0; } /* clear out the OggVorbis_File struct */ int ov_clear(OggVorbis_File *vf){ if(vf){ vorbis_block_clear(&vf->vb); vorbis_dsp_clear(&vf->vd); ogg_stream_clear(&vf->os); if(vf->vi && vf->links){ int i; for(i=0;i<vf->links;i++){ vorbis_info_clear(vf->vi+i); vorbis_comment_clear(vf->vc+i); } _ogg_free(vf->vi); _ogg_free(vf->vc); } if(vf->dataoffsets)_ogg_free(vf->dataoffsets); if(vf->pcmlengths)_ogg_free(vf->pcmlengths); if(vf->serialnos)_ogg_free(vf->serialnos); if(vf->offsets)_ogg_free(vf->offsets); ogg_sync_clear(&vf->oy); if(vf->datasource && vf->callbacks.close_func) (vf->callbacks.close_func)(vf->datasource); memset(vf,0,sizeof(*vf)); } #ifdef DEBUG_LEAKS _VDBG_dump(); #endif return(0); } /* inspects the OggVorbis file and finds/documents all the logical bitstreams contained in it. Tries to be tolerant of logical bitstream sections that are truncated/woogie. return: -1) error 0) OK */ int ov_open_callbacks(void *f,OggVorbis_File *vf, const char *initial,long ibytes,ov_callbacks callbacks){ int ret=_ov_open1(f,vf,initial,ibytes,callbacks); if(ret)return ret; return _ov_open2(vf); } int ov_open(FILE *f,OggVorbis_File *vf,const char *initial,long ibytes){ ov_callbacks callbacks = { (size_t (*)(void *, size_t, size_t, void *)) fread, (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap, (int (*)(void *)) fclose, (long (*)(void *)) ftell }; return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks); } int ov_fopen(const char *path,OggVorbis_File *vf){ int ret; FILE *f = fopen(path,"rb"); if(!f) return -1; ret = ov_open(f,vf,NULL,0); if(ret) fclose(f); return ret; } /* cheap hack for game usage where downsampling is desirable; there's no need for SRC as we can just do it cheaply in libvorbis. */ int ov_halfrate(OggVorbis_File *vf,int flag){ int i; if(vf->vi==NULL)return OV_EINVAL; if(vf->ready_state>STREAMSET){ /* clear out stream state; dumping the decode machine is needed to reinit the MDCT lookups. */ vorbis_dsp_clear(&vf->vd); vorbis_block_clear(&vf->vb); vf->ready_state=STREAMSET; if(vf->pcm_offset>=0){ ogg_int64_t pos=vf->pcm_offset; vf->pcm_offset=-1; /* make sure the pos is dumped if unseekable */ ov_pcm_seek(vf,pos); } } for(i=0;i<vf->links;i++){ if(vorbis_synthesis_halfrate(vf->vi+i,flag)){ if(flag) ov_halfrate(vf,0); return OV_EINVAL; } } return 0; } int ov_halfrate_p(OggVorbis_File *vf){ if(vf->vi==NULL)return OV_EINVAL; return vorbis_synthesis_halfrate_p(vf->vi); } /* Only partially open the vorbis file; test for Vorbisness, and load the headers for the first chain. Do not seek (although test for seekability). Use ov_test_open to finish opening the file, else ov_clear to close/free it. Same return codes as open. */ int ov_test_callbacks(void *f,OggVorbis_File *vf, const char *initial,long ibytes,ov_callbacks callbacks) { return _ov_open1(f,vf,initial,ibytes,callbacks); } int ov_test(FILE *f,OggVorbis_File *vf,const char *initial,long ibytes){ ov_callbacks callbacks = { (size_t (*)(void *, size_t, size_t, void *)) fread, (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap, (int (*)(void *)) fclose, (long (*)(void *)) ftell }; return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks); } int ov_test_open(OggVorbis_File *vf){ if(vf->ready_state!=PARTOPEN)return(OV_EINVAL); return _ov_open2(vf); } /* How many logical bitstreams in this physical bitstream? */ long ov_streams(OggVorbis_File *vf){ return vf->links; } /* Is the FILE * associated with vf seekable? */ long ov_seekable(OggVorbis_File *vf){ return vf->seekable; } /* returns the bitrate for a given logical bitstream or the entire physical bitstream. If the file is open for random access, it will find the *actual* average bitrate. If the file is streaming, it returns the nominal bitrate (if set) else the average of the upper/lower bounds (if set) else -1 (unset). If you want the actual bitrate field settings, get them from the vorbis_info structs */ long ov_bitrate(OggVorbis_File *vf,int i){ if(vf->ready_state<OPENED)return(OV_EINVAL); if(i>=vf->links)return(OV_EINVAL); if(!vf->seekable && i!=0)return(ov_bitrate(vf,0)); if(i<0){ ogg_int64_t bits=0; int i; float br; for(i=0;i<vf->links;i++) bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8; /* This once read: return(rint(bits/ov_time_total(vf,-1))); * gcc 3.x on x86 miscompiled this at optimisation level 2 and above, * so this is slightly transformed to make it work. */ br = bits/ov_time_total(vf,-1); return(rint(br)); }else{ if(vf->seekable){ /* return the actual bitrate */ return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i))); }else{ /* return nominal if set */ if(vf->vi[i].bitrate_nominal>0){ return vf->vi[i].bitrate_nominal; }else{ if(vf->vi[i].bitrate_upper>0){ if(vf->vi[i].bitrate_lower>0){ return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2; }else{ return vf->vi[i].bitrate_upper; } } return(OV_FALSE); } } } } /* returns the actual bitrate since last call. returns -1 if no additional data to offer since last call (or at beginning of stream), EINVAL if stream is only partially open */ long ov_bitrate_instant(OggVorbis_File *vf){ int link=(vf->seekable?vf->current_link:0); long ret; if(vf->ready_state<OPENED)return(OV_EINVAL); if(vf->samptrack==0)return(OV_FALSE); ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5; vf->bittrack=0.f; vf->samptrack=0.f; return(ret); } /* Guess */ long ov_serialnumber(OggVorbis_File *vf,int i){ if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1)); if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1)); if(i<0){ return(vf->current_serialno); }else{ return(vf->serialnos[i]); } } /* returns: total raw (compressed) length of content if i==-1 raw (compressed) length of that logical bitstream for i==0 to n OV_EINVAL if the stream is not seekable (we can't know the length) or if stream is only partially open */ ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){ if(vf->ready_state<OPENED)return(OV_EINVAL); if(!vf->seekable || i>=vf->links)return(OV_EINVAL); if(i<0){ ogg_int64_t acc=0; int i; for(i=0;i<vf->links;i++) acc+=ov_raw_total(vf,i); return(acc); }else{ return(vf->offsets[i+1]-vf->offsets[i]); } } /* returns: total PCM length (samples) of content if i==-1 PCM length (samples) of that logical bitstream for i==0 to n OV_EINVAL if the stream is not seekable (we can't know the length) or only partially open */ ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){ if(vf->ready_state<OPENED)return(OV_EINVAL); if(!vf->seekable || i>=vf->links)return(OV_EINVAL); if(i<0){ ogg_int64_t acc=0; int i; for(i=0;i<vf->links;i++) acc+=ov_pcm_total(vf,i); return(acc); }else{ return(vf->pcmlengths[i*2+1]); } } /* returns: total seconds of content if i==-1 seconds in that logical bitstream for i==0 to n OV_EINVAL if the stream is not seekable (we can't know the length) or only partially open */ double ov_time_total(OggVorbis_File *vf,int i){ if(vf->ready_state<OPENED)return(OV_EINVAL); if(!vf->seekable || i>=vf->links)return(OV_EINVAL); if(i<0){ double acc=0; int i; for(i=0;i<vf->links;i++) acc+=ov_time_total(vf,i); return(acc); }else{ return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate); } } /* seek to an offset relative to the *compressed* data. This also scans packets to update the PCM cursor. It will cross a logical bitstream boundary, but only if it can't get any packets out of the tail of the bitstream we seek to (so no surprises). returns zero on success, nonzero on failure */ int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){ ogg_stream_state work_os; int ret; if(vf->ready_state<OPENED)return(OV_EINVAL); if(!vf->seekable) return(OV_ENOSEEK); /* don't dump machine if we can't seek */ if(pos<0 || pos>vf->end)return(OV_EINVAL); /* is the seek position outside our current link [if any]? */ if(vf->ready_state>=STREAMSET){ if(pos<vf->offsets[vf->current_link] || pos>=vf->offsets[vf->current_link+1]) _decode_clear(vf); /* clear out stream state */ } /* don't yet clear out decoding machine (if it's initialized), in the case we're in the same link. Restart the decode lapping, and let _fetch_and_process_packet deal with a potential bitstream boundary */ vf->pcm_offset=-1; ogg_stream_reset_serialno(&vf->os, vf->current_serialno); /* must set serialno */ vorbis_synthesis_restart(&vf->vd); ret=_seek_helper(vf,pos); if(ret)goto seek_error; /* we need to make sure the pcm_offset is set, but we don't want to advance the raw cursor past good packets just to get to the first with a granulepos. That's not equivalent behavior to beginning decoding as immediately after the seek position as possible. So, a hack. We use two stream states; a local scratch state and the shared vf->os stream state. We use the local state to scan, and the shared state as a buffer for later decode. Unfortuantely, on the last page we still advance to last packet because the granulepos on the last page is not necessarily on a packet boundary, and we need to make sure the granpos is correct. */ { ogg_page og; ogg_packet op; int lastblock=0; int accblock=0; int thisblock=0; int lastflag=0; int firstflag=0; ogg_int64_t pagepos=-1; ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */ ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE return from not necessarily starting from the beginning */ while(1){ if(vf->ready_state>=STREAMSET){ /* snarf/scan a packet if we can */ int result=ogg_stream_packetout(&work_os,&op); if(result>0){ if(vf->vi[vf->current_link].codec_setup){ thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op); if(thisblock<0){ ogg_stream_packetout(&vf->os,NULL); thisblock=0; }else{ /* We can't get a guaranteed correct pcm position out of the last page in a stream because it might have a 'short' granpos, which can only be detected in the presence of a preceding page. However, if the last page is also the first page, the granpos rules of a first page take precedence. Not only that, but for first==last, the EOS page must be treated as if its a normal first page for the stream to open/play. */ if(lastflag && !firstflag) ogg_stream_packetout(&vf->os,NULL); else if(lastblock)accblock+=(lastblock+thisblock)>>2; } if(op.granulepos!=-1){ int i,link=vf->current_link; ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2]; if(granulepos<0)granulepos=0; for(i=0;i<link;i++) granulepos+=vf->pcmlengths[i*2+1]; vf->pcm_offset=granulepos-accblock; if(vf->pcm_offset<0)vf->pcm_offset=0; break; } lastblock=thisblock; continue; }else ogg_stream_packetout(&vf->os,NULL); } } if(!lastblock){ pagepos=_get_next_page(vf,&og,-1); if(pagepos<0){ vf->pcm_offset=ov_pcm_total(vf,-1); break; } }else{ /* huh? Bogus stream with packets but no granulepos */ vf->pcm_offset=-1; break; } /* has our decoding just traversed a bitstream boundary? */ if(vf->ready_state>=STREAMSET){ if(vf->current_serialno!=ogg_page_serialno(&og)){ /* two possibilities: 1) our decoding just traversed a bitstream boundary 2) another stream is multiplexed into this logical section? */ if(ogg_page_bos(&og)){ /* we traversed */ _decode_clear(vf); /* clear out stream state */ ogg_stream_clear(&work_os); } /* else, do nothing; next loop will scoop another page */ } } if(vf->ready_state<STREAMSET){ int link; long serialno = ogg_page_serialno(&og); for(link=0;link<vf->links;link++) if(vf->serialnos[link]==serialno)break; if(link==vf->links) continue; /* not the desired Vorbis bitstream section; keep trying */ vf->current_link=link; vf->current_serialno=serialno; ogg_stream_reset_serialno(&vf->os,serialno); ogg_stream_reset_serialno(&work_os,serialno); vf->ready_state=STREAMSET; firstflag=(pagepos<=vf->dataoffsets[link]); } ogg_stream_pagein(&vf->os,&og); ogg_stream_pagein(&work_os,&og); lastflag=ogg_page_eos(&og); } } ogg_stream_clear(&work_os); vf->bittrack=0.f; vf->samptrack=0.f; return(0); seek_error: /* dump the machine so we're in a known state */ vf->pcm_offset=-1; ogg_stream_clear(&work_os); _decode_clear(vf); return OV_EBADLINK; } /* Page granularity seek (faster than sample granularity because we don't do the last bit of decode to find a specific sample). Seek to the last [granule marked] page preceding the specified pos location, such that decoding past the returned point will quickly arrive at the requested position. */ int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){ int link=-1; ogg_int64_t result=0; ogg_int64_t total=ov_pcm_total(vf,-1); if(vf->ready_state<OPENED)return(OV_EINVAL); if(!vf->seekable)return(OV_ENOSEEK); if(pos<0 || pos>total)return(OV_EINVAL); /* which bitstream section does this pcm offset occur in? */ for(link=vf->links-1;link>=0;link--){ total-=vf->pcmlengths[link*2+1]; if(pos>=total)break; } /* search within the logical bitstream for the page with the highest pcm_pos preceding (or equal to) pos. There is a danger here; missing pages or incorrect frame number information in the bitstream could make our task impossible. Account for that (it would be an error condition) */ /* new search algorithm by HB (Nicholas Vinen) */ { ogg_int64_t end=vf->offsets[link+1]; ogg_int64_t begin=vf->offsets[link]; ogg_int64_t begintime = vf->pcmlengths[link*2]; ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime; ogg_int64_t target=pos-total+begintime; ogg_int64_t best=begin; ogg_page og; while(begin<end){ ogg_int64_t bisect; if(end-begin<CHUNKSIZE){ bisect=begin; }else{ /* take a (pretty decent) guess. */ bisect=begin + (ogg_int64_t)((double)(target-begintime)*(end-begin)/(endtime-begintime)) - CHUNKSIZE; if(bisect<begin+CHUNKSIZE) bisect=begin; } if(bisect!=vf->offset){ result=_seek_helper(vf,bisect); if(result) goto seek_error; } while(begin<end){ result=_get_next_page(vf,&og,end-vf->offset); if(result==OV_EREAD) goto seek_error; if(result<0){ if(bisect<=begin+1) end=begin; /* found it */ else{ if(bisect==0) goto seek_error; bisect-=CHUNKSIZE; if(bisect<=begin)bisect=begin+1; result=_seek_helper(vf,bisect); if(result) goto seek_error; } }else{ ogg_int64_t granulepos; if(ogg_page_serialno(&og)!=vf->serialnos[link]) continue; granulepos=ogg_page_granulepos(&og); if(granulepos==-1)continue; if(granulepos<target){ best=result; /* raw offset of packet with granulepos */ begin=vf->offset; /* raw offset of next page */ begintime=granulepos; if(target-begintime>44100)break; bisect=begin; /* *not* begin + 1 */ }else{ if(bisect<=begin+1) end=begin; /* found it */ else{ if(end==vf->offset){ /* we're pretty close - we'd be stuck in */ end=result; bisect-=CHUNKSIZE; /* an endless loop otherwise. */ if(bisect<=begin)bisect=begin+1; result=_seek_helper(vf,bisect); if(result) goto seek_error; }else{ end=bisect; endtime=granulepos; break; } } } } } } /* found our page. seek to it, update pcm offset. Easier case than raw_seek, don't keep packets preceding granulepos. */ { ogg_page og; ogg_packet op; /* seek */ result=_seek_helper(vf,best); vf->pcm_offset=-1; if(result) goto seek_error; result=_get_next_page(vf,&og,-1); if(result<0) goto seek_error; if(link!=vf->current_link){ /* Different link; dump entire decode machine */ _decode_clear(vf); vf->current_link=link; vf->current_serialno=vf->serialnos[link]; vf->ready_state=STREAMSET; }else{ vorbis_synthesis_restart(&vf->vd); } ogg_stream_reset_serialno(&vf->os,vf->current_serialno); ogg_stream_pagein(&vf->os,&og); /* pull out all but last packet; the one with granulepos */ while(1){ result=ogg_stream_packetpeek(&vf->os,&op); if(result==0){ /* !!! the packet finishing this page originated on a preceding page. Keep fetching previous pages until we get one with a granulepos or without the 'continued' flag set. Then just use raw_seek for simplicity. */ result=_seek_helper(vf,best); if(result<0) goto seek_error; while(1){ result=_get_prev_page(vf,&og); if(result<0) goto seek_error; if(ogg_page_serialno(&og)==vf->current_serialno && (ogg_page_granulepos(&og)>-1 || !ogg_page_continued(&og))){ return ov_raw_seek(vf,result); } vf->offset=result; } } if(result<0){ result = OV_EBADPACKET; goto seek_error; } if(op.granulepos!=-1){ vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2]; if(vf->pcm_offset<0)vf->pcm_offset=0; vf->pcm_offset+=total; break; }else result=ogg_stream_packetout(&vf->os,NULL); } } } /* verify result */ if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){ result=OV_EFAULT; goto seek_error; } vf->bittrack=0.f; vf->samptrack=0.f; return(0); seek_error: /* dump machine so we're in a known state */ vf->pcm_offset=-1; _decode_clear(vf); return (int)result; } /* seek to a sample offset relative to the decompressed pcm stream returns zero on success, nonzero on failure */ int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){ int thisblock,lastblock=0; int ret=ov_pcm_seek_page(vf,pos); if(ret<0)return(ret); if((ret=_make_decode_ready(vf)))return ret; /* discard leading packets we don't need for the lapping of the position we want; don't decode them */ while(1){ ogg_packet op; ogg_page og; int ret=ogg_stream_packetpeek(&vf->os,&op); if(ret>0){ thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op); if(thisblock<0){ ogg_stream_packetout(&vf->os,NULL); continue; /* non audio packet */ } if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2; if(vf->pcm_offset+((thisblock+ vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break; /* remove the packet from packet queue and track its granulepos */ ogg_stream_packetout(&vf->os,NULL); vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with only tracking, no pcm_decode */ vorbis_synthesis_blockin(&vf->vd,&vf->vb); /* end of logical stream case is hard, especially with exact length positioning. */ if(op.granulepos>-1){ int i; /* always believe the stream markers */ vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2]; if(vf->pcm_offset<0)vf->pcm_offset=0; for(i=0;i<vf->current_link;i++) vf->pcm_offset+=vf->pcmlengths[i*2+1]; } lastblock=thisblock; }else{ if(ret<0 && ret!=OV_HOLE)break; /* suck in a new page */ if(_get_next_page(vf,&og,-1)<0)break; if(ogg_page_bos(&og))_decode_clear(vf); if(vf->ready_state<STREAMSET){ long serialno=ogg_page_serialno(&og); int link; for(link=0;link<vf->links;link++) if(vf->serialnos[link]==serialno)break; if(link==vf->links) continue; vf->current_link=link; vf->ready_state=STREAMSET; vf->current_serialno=ogg_page_serialno(&og); ogg_stream_reset_serialno(&vf->os,serialno); ret=_make_decode_ready(vf); if(ret)return ret; lastblock=0; } ogg_stream_pagein(&vf->os,&og); } } vf->bittrack=0.f; vf->samptrack=0.f; /* discard samples until we reach the desired position. Crossing a logical bitstream boundary with abandon is OK. */ { /* note that halfrate could be set differently in each link, but vorbisfile encoforces all links are set or unset */ int hs=vorbis_synthesis_halfrate_p(vf->vi); while(vf->pcm_offset<((pos>>hs)<<hs)){ ogg_int64_t target=(pos-vf->pcm_offset)>>hs; long samples=vorbis_synthesis_pcmout(&vf->vd,NULL); if(samples>target)samples=target; vorbis_synthesis_read(&vf->vd,samples); vf->pcm_offset+=samples<<hs; if(samples<target) if(_fetch_and_process_packet(vf,NULL,1,1)<=0) vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */ } } return 0; } /* seek to a playback time relative to the decompressed pcm stream returns zero on success, nonzero on failure */ int ov_time_seek(OggVorbis_File *vf,double seconds){ /* translate time to PCM position and call ov_pcm_seek */ int link=-1; ogg_int64_t pcm_total=0; double time_total=0.; if(vf->ready_state<OPENED)return(OV_EINVAL); if(!vf->seekable)return(OV_ENOSEEK); if(seconds<0)return(OV_EINVAL); /* which bitstream section does this time offset occur in? */ for(link=0;link<vf->links;link++){ double addsec = ov_time_total(vf,link); if(seconds<time_total+addsec)break; time_total+=addsec; pcm_total+=vf->pcmlengths[link*2+1]; } if(link==vf->links)return(OV_EINVAL); /* enough information to convert time offset to pcm offset */ { ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate; return(ov_pcm_seek(vf,target)); } } /* page-granularity version of ov_time_seek returns zero on success, nonzero on failure */ int ov_time_seek_page(OggVorbis_File *vf,double seconds){ /* translate time to PCM position and call ov_pcm_seek */ int link=-1; ogg_int64_t pcm_total=0; double time_total=0.; if(vf->ready_state<OPENED)return(OV_EINVAL); if(!vf->seekable)return(OV_ENOSEEK); if(seconds<0)return(OV_EINVAL); /* which bitstream section does this time offset occur in? */ for(link=0;link<vf->links;link++){ double addsec = ov_time_total(vf,link); if(seconds<time_total+addsec)break; time_total+=addsec; pcm_total+=vf->pcmlengths[link*2+1]; } if(link==vf->links)return(OV_EINVAL); /* enough information to convert time offset to pcm offset */ { ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate; return(ov_pcm_seek_page(vf,target)); } } /* tell the current stream offset cursor. Note that seek followed by tell will likely not give the set offset due to caching */ ogg_int64_t ov_raw_tell(OggVorbis_File *vf){ if(vf->ready_state<OPENED)return(OV_EINVAL); return(vf->offset); } /* return PCM offset (sample) of next PCM sample to be read */ ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){ if(vf->ready_state<OPENED)return(OV_EINVAL); return(vf->pcm_offset); } /* return time offset (seconds) of next PCM sample to be read */ double ov_time_tell(OggVorbis_File *vf){ int link=0; ogg_int64_t pcm_total=0; double time_total=0.f; if(vf->ready_state<OPENED)return(OV_EINVAL); if(vf->seekable){ pcm_total=ov_pcm_total(vf,-1); time_total=ov_time_total(vf,-1); /* which bitstream section does this time offset occur in? */ for(link=vf->links-1;link>=0;link--){ pcm_total-=vf->pcmlengths[link*2+1]; time_total-=ov_time_total(vf,link); if(vf->pcm_offset>=pcm_total)break; } } return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate); } /* link: -1) return the vorbis_info struct for the bitstream section currently being decoded 0-n) to request information for a specific bitstream section In the case of a non-seekable bitstream, any call returns the current bitstream. NULL in the case that the machine is not initialized */ vorbis_info *ov_info(OggVorbis_File *vf,int link){ if(vf->seekable){ if(link<0) if(vf->ready_state>=STREAMSET) return vf->vi+vf->current_link; else return vf->vi; else if(link>=vf->links) return NULL; else return vf->vi+link; }else{ return vf->vi; } } /* grr, strong typing, grr, no templates/inheritence, grr */ vorbis_comment *ov_comment(OggVorbis_File *vf,int link){ if(vf->seekable){ if(link<0) if(vf->ready_state>=STREAMSET) return vf->vc+vf->current_link; else return vf->vc; else if(link>=vf->links) return NULL; else return vf->vc+link; }else{ return vf->vc; } } static int host_is_big_endian() { ogg_int32_t pattern = 0xfeedface; /* deadbeef */ unsigned char *bytewise = (unsigned char *)&pattern; if (bytewise[0] == 0xfe) return 1; return 0; } /* up to this point, everything could more or less hide the multiple logical bitstream nature of chaining from the toplevel application if the toplevel application didn't particularly care. However, at the point that we actually read audio back, the multiple-section nature must surface: Multiple bitstream sections do not necessarily have to have the same number of channels or sampling rate. ov_read returns the sequential logical bitstream number currently being decoded along with the PCM data in order that the toplevel application can take action on channel/sample rate changes. This number will be incremented even for streamed (non-seekable) streams (for seekable streams, it represents the actual logical bitstream index within the physical bitstream. Note that the accessor functions above are aware of this dichotomy). ov_read_filter is exactly the same as ov_read except that it processes the decoded audio data through a filter before packing it into the requested format. This gives greater accuracy than applying a filter after the audio has been converted into integral PCM. input values: buffer) a buffer to hold packed PCM data for return length) the byte length requested to be placed into buffer bigendianp) should the data be packed LSB first (0) or MSB first (1) word) word size for output. currently 1 (byte) or 2 (16 bit short) return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL) 0) EOF n) number of bytes of PCM actually returned. The below works on a packet-by-packet basis, so the return length is not related to the 'length' passed in, just guaranteed to fit. *section) set to the logical bitstream number */ long ov_read_filter(OggVorbis_File *vf,char *buffer,int length, int bigendianp,int word,int sgned,int *bitstream, void (*filter)(float **pcm,long channels,long samples,void *filter_param),void *filter_param){ int i,j; int host_endian = host_is_big_endian(); int hs; float **pcm; long samples; if(vf->ready_state<OPENED)return(OV_EINVAL); while(1){ if(vf->ready_state==INITSET){ samples=vorbis_synthesis_pcmout(&vf->vd,&pcm); if(samples)break; } /* suck in another packet */ { int ret=_fetch_and_process_packet(vf,NULL,1,1); if(ret==OV_EOF) return(0); if(ret<=0) return(ret); } } if(samples>0){ /* yay! proceed to pack data into the byte buffer */ long channels=ov_info(vf,-1)->channels; long bytespersample=word * channels; vorbis_fpu_control fpu; if(samples>length/bytespersample)samples=length/bytespersample; if(samples <= 0) return OV_EINVAL; /* Here. */ if(filter) filter(pcm,channels,samples,filter_param); /* a tight loop to pack each size */ { int val; if(word==1){ int off=(sgned?0:128); vorbis_fpu_setround(&fpu); for(j=0;j<samples;j++) for(i=0;i<channels;i++){ val=vorbis_ftoi(pcm[i][j]*128.f); if(val>127)val=127; else if(val<-128)val=-128; *buffer++=val+off; } vorbis_fpu_restore(fpu); }else{ int off=(sgned?0:32768); if(host_endian==bigendianp){ if(sgned){ vorbis_fpu_setround(&fpu); for(i=0;i<channels;i++) { /* It's faster in this order */ float *src=pcm[i]; short *dest=((short *)buffer)+i; for(j=0;j<samples;j++) { val=vorbis_ftoi(src[j]*32768.f); if(val>32767)val=32767; else if(val<-32768)val=-32768; *dest=val; dest+=channels; } } vorbis_fpu_restore(fpu); }else{ vorbis_fpu_setround(&fpu); for(i=0;i<channels;i++) { float *src=pcm[i]; short *dest=((short *)buffer)+i; for(j=0;j<samples;j++) { val=vorbis_ftoi(src[j]*32768.f); if(val>32767)val=32767; else if(val<-32768)val=-32768; *dest=val+off; dest+=channels; } } vorbis_fpu_restore(fpu); } }else if(bigendianp){ vorbis_fpu_setround(&fpu); for(j=0;j<samples;j++) for(i=0;i<channels;i++){ val=vorbis_ftoi(pcm[i][j]*32768.f); if(val>32767)val=32767; else if(val<-32768)val=-32768; val+=off; *buffer++=(val>>8); *buffer++=(val&0xff); } vorbis_fpu_restore(fpu); }else{ int val; vorbis_fpu_setround(&fpu); for(j=0;j<samples;j++) for(i=0;i<channels;i++){ val=vorbis_ftoi(pcm[i][j]*32768.f); if(val>32767)val=32767; else if(val<-32768)val=-32768; val+=off; *buffer++=(val&0xff); *buffer++=(val>>8); } vorbis_fpu_restore(fpu); } } } vorbis_synthesis_read(&vf->vd,samples); hs=vorbis_synthesis_halfrate_p(vf->vi); vf->pcm_offset+=(samples<<hs); if(bitstream)*bitstream=vf->current_link; return(samples*bytespersample); }else{ return(samples); } } long ov_read(OggVorbis_File *vf,char *buffer,int length, int bigendianp,int word,int sgned,int *bitstream){ return ov_read_filter(vf, buffer, length, bigendianp, word, sgned, bitstream, NULL, NULL); } /* input values: pcm_channels) a float vector per channel of output length) the sample length being read by the app return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL) 0) EOF n) number of samples of PCM actually returned. The below works on a packet-by-packet basis, so the return length is not related to the 'length' passed in, just guaranteed to fit. *section) set to the logical bitstream number */ long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length, int *bitstream){ if(vf->ready_state<OPENED)return(OV_EINVAL); while(1){ if(vf->ready_state==INITSET){ float **pcm; long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm); if(samples){ int hs=vorbis_synthesis_halfrate_p(vf->vi); if(pcm_channels)*pcm_channels=pcm; if(samples>length)samples=length; vorbis_synthesis_read(&vf->vd,samples); vf->pcm_offset+=samples<<hs; if(bitstream)*bitstream=vf->current_link; return samples; } } /* suck in another packet */ { int ret=_fetch_and_process_packet(vf,NULL,1,1); if(ret==OV_EOF)return(0); if(ret<=0)return(ret); } } } extern float *vorbis_window(vorbis_dsp_state *v,int W); static void _ov_splice(float **pcm,float **lappcm, int n1, int n2, int ch1, int ch2, float *w1, float *w2){ int i,j; float *w=w1; int n=n1; if(n1>n2){ n=n2; w=w2; } /* splice */ for(j=0;j<ch1 && j<ch2;j++){ float *s=lappcm[j]; float *d=pcm[j]; for(i=0;i<n;i++){ float wd=w[i]*w[i]; float ws=1.-wd; d[i]=d[i]*wd + s[i]*ws; } } /* window from zero */ for(;j<ch2;j++){ float *d=pcm[j]; for(i=0;i<n;i++){ float wd=w[i]*w[i]; d[i]=d[i]*wd; } } } /* make sure vf is INITSET */ static int _ov_initset(OggVorbis_File *vf){ while(1){ if(vf->ready_state==INITSET)break; /* suck in another packet */ { int ret=_fetch_and_process_packet(vf,NULL,1,0); if(ret<0 && ret!=OV_HOLE)return(ret); } } return 0; } /* make sure vf is INITSET and that we have a primed buffer; if we're crosslapping at a stream section boundary, this also makes sure we're sanity checking against the right stream information */ static int _ov_initprime(OggVorbis_File *vf){ vorbis_dsp_state *vd=&vf->vd; while(1){ if(vf->ready_state==INITSET) if(vorbis_synthesis_pcmout(vd,NULL))break; /* suck in another packet */ { int ret=_fetch_and_process_packet(vf,NULL,1,0); if(ret<0 && ret!=OV_HOLE)return(ret); } } return 0; } /* grab enough data for lapping from vf; this may be in the form of unreturned, already-decoded pcm, remaining PCM we will need to decode, or synthetic postextrapolation from last packets. */ static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd, float **lappcm,int lapsize){ int lapcount=0,i; float **pcm; /* try first to decode the lapping data */ while(lapcount<lapsize){ int samples=vorbis_synthesis_pcmout(vd,&pcm); if(samples){ if(samples>lapsize-lapcount)samples=lapsize-lapcount; for(i=0;i<vi->channels;i++) memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples); lapcount+=samples; vorbis_synthesis_read(vd,samples); }else{ /* suck in another packet */ int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */ if(ret==OV_EOF)break; } } if(lapcount<lapsize){ /* failed to get lapping data from normal decode; pry it from the postextrapolation buffering, or the second half of the MDCT from the last packet */ int samples=vorbis_synthesis_lapout(&vf->vd,&pcm); if(samples==0){ for(i=0;i<vi->channels;i++) memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount); lapcount=lapsize; }else{ if(samples>lapsize-lapcount)samples=lapsize-lapcount; for(i=0;i<vi->channels;i++) memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples); lapcount+=samples; } } } /* this sets up crosslapping of a sample by using trailing data from sample 1 and lapping it into the windowing buffer of sample 2 */ int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){ vorbis_info *vi1,*vi2; float **lappcm; float **pcm; float *w1,*w2; int n1,n2,i,ret,hs1,hs2; if(vf1==vf2)return(0); /* degenerate case */ if(vf1->ready_state<OPENED)return(OV_EINVAL); if(vf2->ready_state<OPENED)return(OV_EINVAL); /* the relevant overlap buffers must be pre-checked and pre-primed before looking at settings in the event that priming would cross a bitstream boundary. So, do it now */ ret=_ov_initset(vf1); if(ret)return(ret); ret=_ov_initprime(vf2); if(ret)return(ret); vi1=ov_info(vf1,-1); vi2=ov_info(vf2,-1); hs1=ov_halfrate_p(vf1); hs2=ov_halfrate_p(vf2); lappcm=alloca(sizeof(*lappcm)*vi1->channels); n1=vorbis_info_blocksize(vi1,0)>>(1+hs1); n2=vorbis_info_blocksize(vi2,0)>>(1+hs2); w1=vorbis_window(&vf1->vd,0); w2=vorbis_window(&vf2->vd,0); for(i=0;i<vi1->channels;i++) lappcm[i]=alloca(sizeof(**lappcm)*n1); _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1); /* have a lapping buffer from vf1; now to splice it into the lapping buffer of vf2 */ /* consolidate and expose the buffer. */ vorbis_synthesis_lapout(&vf2->vd,&pcm); #if 0 _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0); _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0); #endif /* splice */ _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2); /* done */ return(0); } static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos, int (*localseek)(OggVorbis_File *,ogg_int64_t)){ vorbis_info *vi; float **lappcm; float **pcm; float *w1,*w2; int n1,n2,ch1,ch2,hs; int i,ret; if(vf->ready_state<OPENED)return(OV_EINVAL); ret=_ov_initset(vf); if(ret)return(ret); vi=ov_info(vf,-1); hs=ov_halfrate_p(vf); ch1=vi->channels; n1=vorbis_info_blocksize(vi,0)>>(1+hs); w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are persistent; even if the decode state from this link gets dumped, this window array continues to exist */ lappcm=alloca(sizeof(*lappcm)*ch1); for(i=0;i<ch1;i++) lappcm[i]=alloca(sizeof(**lappcm)*n1); _ov_getlap(vf,vi,&vf->vd,lappcm,n1); /* have lapping data; seek and prime the buffer */ ret=localseek(vf,pos); if(ret)return ret; ret=_ov_initprime(vf); if(ret)return(ret); /* Guard against cross-link changes; they're perfectly legal */ vi=ov_info(vf,-1); ch2=vi->channels; n2=vorbis_info_blocksize(vi,0)>>(1+hs); w2=vorbis_window(&vf->vd,0); /* consolidate and expose the buffer. */ vorbis_synthesis_lapout(&vf->vd,&pcm); /* splice */ _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2); /* done */ return(0); } int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){ return _ov_64_seek_lap(vf,pos,ov_raw_seek); } int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){ return _ov_64_seek_lap(vf,pos,ov_pcm_seek); } int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){ return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page); } static int _ov_d_seek_lap(OggVorbis_File *vf,double pos, int (*localseek)(OggVorbis_File *,double)){ vorbis_info *vi; float **lappcm; float **pcm; float *w1,*w2; int n1,n2,ch1,ch2,hs; int i,ret; if(vf->ready_state<OPENED)return(OV_EINVAL); ret=_ov_initset(vf); if(ret)return(ret); vi=ov_info(vf,-1); hs=ov_halfrate_p(vf); ch1=vi->channels; n1=vorbis_info_blocksize(vi,0)>>(1+hs); w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are persistent; even if the decode state from this link gets dumped, this window array continues to exist */ lappcm=alloca(sizeof(*lappcm)*ch1); for(i=0;i<ch1;i++) lappcm[i]=alloca(sizeof(**lappcm)*n1); _ov_getlap(vf,vi,&vf->vd,lappcm,n1); /* have lapping data; seek and prime the buffer */ ret=localseek(vf,pos); if(ret)return ret; ret=_ov_initprime(vf); if(ret)return(ret); /* Guard against cross-link changes; they're perfectly legal */ vi=ov_info(vf,-1); ch2=vi->channels; n2=vorbis_info_blocksize(vi,0)>>(1+hs); w2=vorbis_window(&vf->vd,0); /* consolidate and expose the buffer. */ vorbis_synthesis_lapout(&vf->vd,&pcm); /* splice */ _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2); /* done */ return(0); } int ov_time_seek_lap(OggVorbis_File *vf,double pos){ return _ov_d_seek_lap(vf,pos,ov_time_seek); } int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){ return _ov_d_seek_lap(vf,pos,ov_time_seek_page); }
{ "language": "C" }
/* Samsung S5H1411 VSB/QAM demodulator driver Copyright (C) 2008 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/init.h> #include <linux/module.h> #include <linux/string.h> #include <linux/slab.h> #include <linux/delay.h> #include "dvb_frontend.h" #include "s5h1411.h" struct s5h1411_state { struct i2c_adapter *i2c; /* configuration settings */ const struct s5h1411_config *config; struct dvb_frontend frontend; fe_modulation_t current_modulation; unsigned int first_tune:1; u32 current_frequency; int if_freq; u8 inversion; }; static int debug; #define dprintk(arg...) do { \ if (debug) \ printk(arg); \ } while (0) /* Register values to initialise the demod, defaults to VSB */ static struct init_tab { u8 addr; u8 reg; u16 data; } init_tab[] = { { S5H1411_I2C_TOP_ADDR, 0x00, 0x0071, }, { S5H1411_I2C_TOP_ADDR, 0x08, 0x0047, }, { S5H1411_I2C_TOP_ADDR, 0x1c, 0x0400, }, { S5H1411_I2C_TOP_ADDR, 0x1e, 0x0370, }, { S5H1411_I2C_TOP_ADDR, 0x1f, 0x342c, }, { S5H1411_I2C_TOP_ADDR, 0x24, 0x0231, }, { S5H1411_I2C_TOP_ADDR, 0x25, 0x1011, }, { S5H1411_I2C_TOP_ADDR, 0x26, 0x0f07, }, { S5H1411_I2C_TOP_ADDR, 0x27, 0x0f04, }, { S5H1411_I2C_TOP_ADDR, 0x28, 0x070f, }, { S5H1411_I2C_TOP_ADDR, 0x29, 0x2820, }, { S5H1411_I2C_TOP_ADDR, 0x2a, 0x102e, }, { S5H1411_I2C_TOP_ADDR, 0x2b, 0x0220, }, { S5H1411_I2C_TOP_ADDR, 0x2e, 0x0d0e, }, { S5H1411_I2C_TOP_ADDR, 0x2f, 0x1013, }, { S5H1411_I2C_TOP_ADDR, 0x31, 0x171b, }, { S5H1411_I2C_TOP_ADDR, 0x32, 0x0e0f, }, { S5H1411_I2C_TOP_ADDR, 0x33, 0x0f10, }, { S5H1411_I2C_TOP_ADDR, 0x34, 0x170e, }, { S5H1411_I2C_TOP_ADDR, 0x35, 0x4b10, }, { S5H1411_I2C_TOP_ADDR, 0x36, 0x0f17, }, { S5H1411_I2C_TOP_ADDR, 0x3c, 0x1577, }, { S5H1411_I2C_TOP_ADDR, 0x3d, 0x081a, }, { S5H1411_I2C_TOP_ADDR, 0x3e, 0x77ee, }, { S5H1411_I2C_TOP_ADDR, 0x40, 0x1e09, }, { S5H1411_I2C_TOP_ADDR, 0x41, 0x0f0c, }, { S5H1411_I2C_TOP_ADDR, 0x42, 0x1f10, }, { S5H1411_I2C_TOP_ADDR, 0x4d, 0x0509, }, { S5H1411_I2C_TOP_ADDR, 0x4e, 0x0a00, }, { S5H1411_I2C_TOP_ADDR, 0x50, 0x0000, }, { S5H1411_I2C_TOP_ADDR, 0x5b, 0x0000, }, { S5H1411_I2C_TOP_ADDR, 0x5c, 0x0008, }, { S5H1411_I2C_TOP_ADDR, 0x57, 0x1101, }, { S5H1411_I2C_TOP_ADDR, 0x65, 0x007c, }, { S5H1411_I2C_TOP_ADDR, 0x68, 0x0512, }, { S5H1411_I2C_TOP_ADDR, 0x69, 0x0258, }, { S5H1411_I2C_TOP_ADDR, 0x70, 0x0004, }, { S5H1411_I2C_TOP_ADDR, 0x71, 0x0007, }, { S5H1411_I2C_TOP_ADDR, 0x76, 0x00a9, }, { S5H1411_I2C_TOP_ADDR, 0x78, 0x3141, }, { S5H1411_I2C_TOP_ADDR, 0x7a, 0x3141, }, { S5H1411_I2C_TOP_ADDR, 0xb3, 0x8003, }, { S5H1411_I2C_TOP_ADDR, 0xb5, 0xa6bb, }, { S5H1411_I2C_TOP_ADDR, 0xb6, 0x0609, }, { S5H1411_I2C_TOP_ADDR, 0xb7, 0x2f06, }, { S5H1411_I2C_TOP_ADDR, 0xb8, 0x003f, }, { S5H1411_I2C_TOP_ADDR, 0xb9, 0x2700, }, { S5H1411_I2C_TOP_ADDR, 0xba, 0xfac8, }, { S5H1411_I2C_TOP_ADDR, 0xbe, 0x1003, }, { S5H1411_I2C_TOP_ADDR, 0xbf, 0x103f, }, { S5H1411_I2C_TOP_ADDR, 0xce, 0x2000, }, { S5H1411_I2C_TOP_ADDR, 0xcf, 0x0800, }, { S5H1411_I2C_TOP_ADDR, 0xd0, 0x0800, }, { S5H1411_I2C_TOP_ADDR, 0xd1, 0x0400, }, { S5H1411_I2C_TOP_ADDR, 0xd2, 0x0800, }, { S5H1411_I2C_TOP_ADDR, 0xd3, 0x2000, }, { S5H1411_I2C_TOP_ADDR, 0xd4, 0x3000, }, { S5H1411_I2C_TOP_ADDR, 0xdb, 0x4a9b, }, { S5H1411_I2C_TOP_ADDR, 0xdc, 0x1000, }, { S5H1411_I2C_TOP_ADDR, 0xde, 0x0001, }, { S5H1411_I2C_TOP_ADDR, 0xdf, 0x0000, }, { S5H1411_I2C_TOP_ADDR, 0xe3, 0x0301, }, { S5H1411_I2C_QAM_ADDR, 0xf3, 0x0000, }, { S5H1411_I2C_QAM_ADDR, 0xf3, 0x0001, }, { S5H1411_I2C_QAM_ADDR, 0x08, 0x0600, }, { S5H1411_I2C_QAM_ADDR, 0x18, 0x4201, }, { S5H1411_I2C_QAM_ADDR, 0x1e, 0x6476, }, { S5H1411_I2C_QAM_ADDR, 0x21, 0x0830, }, { S5H1411_I2C_QAM_ADDR, 0x0c, 0x5679, }, { S5H1411_I2C_QAM_ADDR, 0x0d, 0x579b, }, { S5H1411_I2C_QAM_ADDR, 0x24, 0x0102, }, { S5H1411_I2C_QAM_ADDR, 0x31, 0x7488, }, { S5H1411_I2C_QAM_ADDR, 0x32, 0x0a08, }, { S5H1411_I2C_QAM_ADDR, 0x3d, 0x8689, }, { S5H1411_I2C_QAM_ADDR, 0x49, 0x0048, }, { S5H1411_I2C_QAM_ADDR, 0x57, 0x2012, }, { S5H1411_I2C_QAM_ADDR, 0x5d, 0x7676, }, { S5H1411_I2C_QAM_ADDR, 0x04, 0x0400, }, { S5H1411_I2C_QAM_ADDR, 0x58, 0x00c0, }, { S5H1411_I2C_QAM_ADDR, 0x5b, 0x0100, }, }; /* VSB SNR lookup table */ static struct vsb_snr_tab { u16 val; u16 data; } vsb_snr_tab[] = { { 0x39f, 300, }, { 0x39b, 295, }, { 0x397, 290, }, { 0x394, 285, }, { 0x38f, 280, }, { 0x38b, 275, }, { 0x387, 270, }, { 0x382, 265, }, { 0x37d, 260, }, { 0x377, 255, }, { 0x370, 250, }, { 0x36a, 245, }, { 0x364, 240, }, { 0x35b, 235, }, { 0x353, 230, }, { 0x349, 225, }, { 0x340, 320, }, { 0x337, 215, }, { 0x327, 210, }, { 0x31b, 205, }, { 0x310, 200, }, { 0x302, 195, }, { 0x2f3, 190, }, { 0x2e4, 185, }, { 0x2d7, 180, }, { 0x2cd, 175, }, { 0x2bb, 170, }, { 0x2a9, 165, }, { 0x29e, 160, }, { 0x284, 155, }, { 0x27a, 150, }, { 0x260, 145, }, { 0x23a, 140, }, { 0x224, 135, }, { 0x213, 130, }, { 0x204, 125, }, { 0x1fe, 120, }, { 0, 0, }, }; /* QAM64 SNR lookup table */ static struct qam64_snr_tab { u16 val; u16 data; } qam64_snr_tab[] = { { 0x0001, 0, }, { 0x0af0, 300, }, { 0x0d80, 290, }, { 0x10a0, 280, }, { 0x14b5, 270, }, { 0x1590, 268, }, { 0x1680, 266, }, { 0x17b0, 264, }, { 0x18c0, 262, }, { 0x19b0, 260, }, { 0x1ad0, 258, }, { 0x1d00, 256, }, { 0x1da0, 254, }, { 0x1ef0, 252, }, { 0x2050, 250, }, { 0x20f0, 249, }, { 0x21d0, 248, }, { 0x22b0, 247, }, { 0x23a0, 246, }, { 0x2470, 245, }, { 0x24f0, 244, }, { 0x25a0, 243, }, { 0x26c0, 242, }, { 0x27b0, 241, }, { 0x28d0, 240, }, { 0x29b0, 239, }, { 0x2ad0, 238, }, { 0x2ba0, 237, }, { 0x2c80, 236, }, { 0x2d20, 235, }, { 0x2e00, 234, }, { 0x2f10, 233, }, { 0x3050, 232, }, { 0x3190, 231, }, { 0x3300, 230, }, { 0x3340, 229, }, { 0x3200, 228, }, { 0x3550, 227, }, { 0x3610, 226, }, { 0x3600, 225, }, { 0x3700, 224, }, { 0x3800, 223, }, { 0x3920, 222, }, { 0x3a20, 221, }, { 0x3b30, 220, }, { 0x3d00, 219, }, { 0x3e00, 218, }, { 0x4000, 217, }, { 0x4100, 216, }, { 0x4300, 215, }, { 0x4400, 214, }, { 0x4600, 213, }, { 0x4700, 212, }, { 0x4800, 211, }, { 0x4a00, 210, }, { 0x4b00, 209, }, { 0x4d00, 208, }, { 0x4f00, 207, }, { 0x5050, 206, }, { 0x5200, 205, }, { 0x53c0, 204, }, { 0x5450, 203, }, { 0x5650, 202, }, { 0x5820, 201, }, { 0x6000, 200, }, { 0xffff, 0, }, }; /* QAM256 SNR lookup table */ static struct qam256_snr_tab { u16 val; u16 data; } qam256_snr_tab[] = { { 0x0001, 0, }, { 0x0970, 400, }, { 0x0a90, 390, }, { 0x0b90, 380, }, { 0x0d90, 370, }, { 0x0ff0, 360, }, { 0x1240, 350, }, { 0x1345, 348, }, { 0x13c0, 346, }, { 0x14c0, 344, }, { 0x1500, 342, }, { 0x1610, 340, }, { 0x1700, 338, }, { 0x1800, 336, }, { 0x18b0, 334, }, { 0x1900, 332, }, { 0x1ab0, 330, }, { 0x1bc0, 328, }, { 0x1cb0, 326, }, { 0x1db0, 324, }, { 0x1eb0, 322, }, { 0x2030, 320, }, { 0x2200, 318, }, { 0x2280, 316, }, { 0x2410, 314, }, { 0x25b0, 312, }, { 0x27a0, 310, }, { 0x2840, 308, }, { 0x29d0, 306, }, { 0x2b10, 304, }, { 0x2d30, 302, }, { 0x2f20, 300, }, { 0x30c0, 298, }, { 0x3260, 297, }, { 0x32c0, 296, }, { 0x3300, 295, }, { 0x33b0, 294, }, { 0x34b0, 293, }, { 0x35a0, 292, }, { 0x3650, 291, }, { 0x3800, 290, }, { 0x3900, 289, }, { 0x3a50, 288, }, { 0x3b30, 287, }, { 0x3cb0, 286, }, { 0x3e20, 285, }, { 0x3fa0, 284, }, { 0x40a0, 283, }, { 0x41c0, 282, }, { 0x42f0, 281, }, { 0x44a0, 280, }, { 0x4600, 279, }, { 0x47b0, 278, }, { 0x4900, 277, }, { 0x4a00, 276, }, { 0x4ba0, 275, }, { 0x4d00, 274, }, { 0x4f00, 273, }, { 0x5000, 272, }, { 0x51f0, 272, }, { 0x53a0, 270, }, { 0x5520, 269, }, { 0x5700, 268, }, { 0x5800, 267, }, { 0x5a00, 266, }, { 0x5c00, 265, }, { 0x5d00, 264, }, { 0x5f00, 263, }, { 0x6000, 262, }, { 0x6200, 261, }, { 0x6400, 260, }, { 0xffff, 0, }, }; /* 8 bit registers, 16 bit values */ static int s5h1411_writereg(struct s5h1411_state *state, u8 addr, u8 reg, u16 data) { int ret; u8 buf[] = { reg, data >> 8, data & 0xff }; struct i2c_msg msg = { .addr = addr, .flags = 0, .buf = buf, .len = 3 }; ret = i2c_transfer(state->i2c, &msg, 1); if (ret != 1) printk(KERN_ERR "%s: writereg error 0x%02x 0x%02x 0x%04x, " "ret == %i)\n", __func__, addr, reg, data, ret); return (ret != 1) ? -1 : 0; } static u16 s5h1411_readreg(struct s5h1411_state *state, u8 addr, u8 reg) { int ret; u8 b0[] = { reg }; u8 b1[] = { 0, 0 }; struct i2c_msg msg[] = { { .addr = addr, .flags = 0, .buf = b0, .len = 1 }, { .addr = addr, .flags = I2C_M_RD, .buf = b1, .len = 2 } }; ret = i2c_transfer(state->i2c, msg, 2); if (ret != 2) printk(KERN_ERR "%s: readreg error (ret == %i)\n", __func__, ret); return (b1[0] << 8) | b1[1]; } static int s5h1411_softreset(struct dvb_frontend *fe) { struct s5h1411_state *state = fe->demodulator_priv; dprintk("%s()\n", __func__); s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0xf7, 0); s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0xf7, 1); return 0; } static int s5h1411_set_if_freq(struct dvb_frontend *fe, int KHz) { struct s5h1411_state *state = fe->demodulator_priv; dprintk("%s(%d KHz)\n", __func__, KHz); switch (KHz) { case 3250: s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0x38, 0x10d5); s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0x39, 0x5342); s5h1411_writereg(state, S5H1411_I2C_QAM_ADDR, 0x2c, 0x10d9); break; case 3500: s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0x38, 0x1225); s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0x39, 0x1e96); s5h1411_writereg(state, S5H1411_I2C_QAM_ADDR, 0x2c, 0x1225); break; case 4000: s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0x38, 0x14bc); s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0x39, 0xb53e); s5h1411_writereg(state, S5H1411_I2C_QAM_ADDR, 0x2c, 0x14bd); break; default: dprintk("%s(%d KHz) Invalid, defaulting to 5380\n", __func__, KHz); /* no break, need to continue */ case 5380: case 44000: s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0x38, 0x1be4); s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0x39, 0x3655); s5h1411_writereg(state, S5H1411_I2C_QAM_ADDR, 0x2c, 0x1be4); break; } state->if_freq = KHz; return 0; } static int s5h1411_set_mpeg_timing(struct dvb_frontend *fe, int mode) { struct s5h1411_state *state = fe->demodulator_priv; u16 val; dprintk("%s(%d)\n", __func__, mode); val = s5h1411_readreg(state, S5H1411_I2C_TOP_ADDR, 0xbe) & 0xcfff; switch (mode) { case S5H1411_MPEGTIMING_CONTINOUS_INVERTING_CLOCK: val |= 0x0000; break; case S5H1411_MPEGTIMING_CONTINOUS_NONINVERTING_CLOCK: dprintk("%s(%d) Mode1 or Defaulting\n", __func__, mode); val |= 0x1000; break; case S5H1411_MPEGTIMING_NONCONTINOUS_INVERTING_CLOCK: val |= 0x2000; break; case S5H1411_MPEGTIMING_NONCONTINOUS_NONINVERTING_CLOCK: val |= 0x3000; break; default: return -EINVAL; } /* Configure MPEG Signal Timing charactistics */ return s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0xbe, val); } static int s5h1411_set_spectralinversion(struct dvb_frontend *fe, int inversion) { struct s5h1411_state *state = fe->demodulator_priv; u16 val; dprintk("%s(%d)\n", __func__, inversion); val = s5h1411_readreg(state, S5H1411_I2C_TOP_ADDR, 0x24) & ~0x1000; if (inversion == 1) val |= 0x1000; /* Inverted */ state->inversion = inversion; return s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0x24, val); } static int s5h1411_set_serialmode(struct dvb_frontend *fe, int serial) { struct s5h1411_state *state = fe->demodulator_priv; u16 val; dprintk("%s(%d)\n", __func__, serial); val = s5h1411_readreg(state, S5H1411_I2C_TOP_ADDR, 0xbd) & ~0x100; if (serial == 1) val |= 0x100; return s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0xbd, val); } static int s5h1411_enable_modulation(struct dvb_frontend *fe, fe_modulation_t m) { struct s5h1411_state *state = fe->demodulator_priv; dprintk("%s(0x%08x)\n", __func__, m); if ((state->first_tune == 0) && (m == state->current_modulation)) { dprintk("%s() Already at desired modulation. Skipping...\n", __func__); return 0; } switch (m) { case VSB_8: dprintk("%s() VSB_8\n", __func__); s5h1411_set_if_freq(fe, state->config->vsb_if); s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0x00, 0x71); s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0xf6, 0x00); s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0xcd, 0xf1); break; case QAM_64: case QAM_256: case QAM_AUTO: dprintk("%s() QAM_AUTO (64/256)\n", __func__); s5h1411_set_if_freq(fe, state->config->qam_if); s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0x00, 0x0171); s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0xf6, 0x0001); s5h1411_writereg(state, S5H1411_I2C_QAM_ADDR, 0x16, 0x1101); s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0xcd, 0x00f0); break; default: dprintk("%s() Invalid modulation\n", __func__); return -EINVAL; } state->current_modulation = m; state->first_tune = 0; s5h1411_softreset(fe); return 0; } static int s5h1411_i2c_gate_ctrl(struct dvb_frontend *fe, int enable) { struct s5h1411_state *state = fe->demodulator_priv; dprintk("%s(%d)\n", __func__, enable); if (enable) return s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0xf5, 1); else return s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0xf5, 0); } static int s5h1411_set_gpio(struct dvb_frontend *fe, int enable) { struct s5h1411_state *state = fe->demodulator_priv; u16 val; dprintk("%s(%d)\n", __func__, enable); val = s5h1411_readreg(state, S5H1411_I2C_TOP_ADDR, 0xe0) & ~0x02; if (enable) return s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0xe0, val | 0x02); else return s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0xe0, val); } static int s5h1411_set_powerstate(struct dvb_frontend *fe, int enable) { struct s5h1411_state *state = fe->demodulator_priv; dprintk("%s(%d)\n", __func__, enable); if (enable) s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0xf4, 1); else { s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0xf4, 0); s5h1411_softreset(fe); } return 0; } static int s5h1411_sleep(struct dvb_frontend *fe) { return s5h1411_set_powerstate(fe, 1); } static int s5h1411_register_reset(struct dvb_frontend *fe) { struct s5h1411_state *state = fe->demodulator_priv; dprintk("%s()\n", __func__); return s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0xf3, 0); } /* Talk to the demod, set the FEC, GUARD, QAM settings etc */ static int s5h1411_set_frontend(struct dvb_frontend *fe, struct dvb_frontend_parameters *p) { struct s5h1411_state *state = fe->demodulator_priv; dprintk("%s(frequency=%d)\n", __func__, p->frequency); s5h1411_softreset(fe); state->current_frequency = p->frequency; s5h1411_enable_modulation(fe, p->u.vsb.modulation); if (fe->ops.tuner_ops.set_params) { if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); fe->ops.tuner_ops.set_params(fe, p); if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); } /* Issue a reset to the demod so it knows to resync against the newly tuned frequency */ s5h1411_softreset(fe); return 0; } /* Reset the demod hardware and reset all of the configuration registers to a default state. */ static int s5h1411_init(struct dvb_frontend *fe) { struct s5h1411_state *state = fe->demodulator_priv; int i; dprintk("%s()\n", __func__); s5h1411_set_powerstate(fe, 0); s5h1411_register_reset(fe); for (i = 0; i < ARRAY_SIZE(init_tab); i++) s5h1411_writereg(state, init_tab[i].addr, init_tab[i].reg, init_tab[i].data); /* The datasheet says that after initialisation, VSB is default */ state->current_modulation = VSB_8; /* Although the datasheet says it's in VSB, empirical evidence shows problems getting lock on the first tuning request. Make sure we call enable_modulation the first time around */ state->first_tune = 1; if (state->config->output_mode == S5H1411_SERIAL_OUTPUT) /* Serial */ s5h1411_set_serialmode(fe, 1); else /* Parallel */ s5h1411_set_serialmode(fe, 0); s5h1411_set_spectralinversion(fe, state->config->inversion); s5h1411_set_if_freq(fe, state->config->vsb_if); s5h1411_set_gpio(fe, state->config->gpio); s5h1411_set_mpeg_timing(fe, state->config->mpeg_timing); s5h1411_softreset(fe); /* Note: Leaving the I2C gate closed. */ s5h1411_i2c_gate_ctrl(fe, 0); return 0; } static int s5h1411_read_status(struct dvb_frontend *fe, fe_status_t *status) { struct s5h1411_state *state = fe->demodulator_priv; u16 reg; u32 tuner_status = 0; *status = 0; /* Register F2 bit 15 = Master Lock, removed */ switch (state->current_modulation) { case QAM_64: case QAM_256: reg = s5h1411_readreg(state, S5H1411_I2C_TOP_ADDR, 0xf0); if (reg & 0x10) /* QAM FEC Lock */ *status |= FE_HAS_SYNC | FE_HAS_LOCK; if (reg & 0x100) /* QAM EQ Lock */ *status |= FE_HAS_VITERBI | FE_HAS_CARRIER | FE_HAS_SIGNAL; break; case VSB_8: reg = s5h1411_readreg(state, S5H1411_I2C_TOP_ADDR, 0xf2); if (reg & 0x1000) /* FEC Lock */ *status |= FE_HAS_SYNC | FE_HAS_LOCK; if (reg & 0x2000) /* EQ Lock */ *status |= FE_HAS_VITERBI | FE_HAS_CARRIER | FE_HAS_SIGNAL; reg = s5h1411_readreg(state, S5H1411_I2C_TOP_ADDR, 0x53); if (reg & 0x1) /* AFC Lock */ *status |= FE_HAS_SIGNAL; break; default: return -EINVAL; } switch (state->config->status_mode) { case S5H1411_DEMODLOCKING: if (*status & FE_HAS_VITERBI) *status |= FE_HAS_CARRIER | FE_HAS_SIGNAL; break; case S5H1411_TUNERLOCKING: /* Get the tuner status */ if (fe->ops.tuner_ops.get_status) { if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); fe->ops.tuner_ops.get_status(fe, &tuner_status); if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); } if (tuner_status) *status |= FE_HAS_CARRIER | FE_HAS_SIGNAL; break; } dprintk("%s() status 0x%08x\n", __func__, *status); return 0; } static int s5h1411_qam256_lookup_snr(struct dvb_frontend *fe, u16 *snr, u16 v) { int i, ret = -EINVAL; dprintk("%s()\n", __func__); for (i = 0; i < ARRAY_SIZE(qam256_snr_tab); i++) { if (v < qam256_snr_tab[i].val) { *snr = qam256_snr_tab[i].data; ret = 0; break; } } return ret; } static int s5h1411_qam64_lookup_snr(struct dvb_frontend *fe, u16 *snr, u16 v) { int i, ret = -EINVAL; dprintk("%s()\n", __func__); for (i = 0; i < ARRAY_SIZE(qam64_snr_tab); i++) { if (v < qam64_snr_tab[i].val) { *snr = qam64_snr_tab[i].data; ret = 0; break; } } return ret; } static int s5h1411_vsb_lookup_snr(struct dvb_frontend *fe, u16 *snr, u16 v) { int i, ret = -EINVAL; dprintk("%s()\n", __func__); for (i = 0; i < ARRAY_SIZE(vsb_snr_tab); i++) { if (v > vsb_snr_tab[i].val) { *snr = vsb_snr_tab[i].data; ret = 0; break; } } dprintk("%s() snr=%d\n", __func__, *snr); return ret; } static int s5h1411_read_snr(struct dvb_frontend *fe, u16 *snr) { struct s5h1411_state *state = fe->demodulator_priv; u16 reg; dprintk("%s()\n", __func__); switch (state->current_modulation) { case QAM_64: reg = s5h1411_readreg(state, S5H1411_I2C_TOP_ADDR, 0xf1); return s5h1411_qam64_lookup_snr(fe, snr, reg); case QAM_256: reg = s5h1411_readreg(state, S5H1411_I2C_TOP_ADDR, 0xf1); return s5h1411_qam256_lookup_snr(fe, snr, reg); case VSB_8: reg = s5h1411_readreg(state, S5H1411_I2C_TOP_ADDR, 0xf2) & 0x3ff; return s5h1411_vsb_lookup_snr(fe, snr, reg); default: break; } return -EINVAL; } static int s5h1411_read_signal_strength(struct dvb_frontend *fe, u16 *signal_strength) { return s5h1411_read_snr(fe, signal_strength); } static int s5h1411_read_ucblocks(struct dvb_frontend *fe, u32 *ucblocks) { struct s5h1411_state *state = fe->demodulator_priv; *ucblocks = s5h1411_readreg(state, S5H1411_I2C_TOP_ADDR, 0xc9); return 0; } static int s5h1411_read_ber(struct dvb_frontend *fe, u32 *ber) { return s5h1411_read_ucblocks(fe, ber); } static int s5h1411_get_frontend(struct dvb_frontend *fe, struct dvb_frontend_parameters *p) { struct s5h1411_state *state = fe->demodulator_priv; p->frequency = state->current_frequency; p->u.vsb.modulation = state->current_modulation; return 0; } static int s5h1411_get_tune_settings(struct dvb_frontend *fe, struct dvb_frontend_tune_settings *tune) { tune->min_delay_ms = 1000; return 0; } static void s5h1411_release(struct dvb_frontend *fe) { struct s5h1411_state *state = fe->demodulator_priv; kfree(state); } static struct dvb_frontend_ops s5h1411_ops; struct dvb_frontend *s5h1411_attach(const struct s5h1411_config *config, struct i2c_adapter *i2c) { struct s5h1411_state *state = NULL; u16 reg; /* allocate memory for the internal state */ state = kzalloc(sizeof(struct s5h1411_state), GFP_KERNEL); if (state == NULL) goto error; /* setup the state */ state->config = config; state->i2c = i2c; state->current_modulation = VSB_8; state->inversion = state->config->inversion; /* check if the demod exists */ reg = s5h1411_readreg(state, S5H1411_I2C_TOP_ADDR, 0x05); if (reg != 0x0066) goto error; /* create dvb_frontend */ memcpy(&state->frontend.ops, &s5h1411_ops, sizeof(struct dvb_frontend_ops)); state->frontend.demodulator_priv = state; if (s5h1411_init(&state->frontend) != 0) { printk(KERN_ERR "%s: Failed to initialize correctly\n", __func__); goto error; } /* Note: Leaving the I2C gate open here. */ s5h1411_writereg(state, S5H1411_I2C_TOP_ADDR, 0xf5, 1); /* Put the device into low-power mode until first use */ s5h1411_set_powerstate(&state->frontend, 1); return &state->frontend; error: kfree(state); return NULL; } EXPORT_SYMBOL(s5h1411_attach); static struct dvb_frontend_ops s5h1411_ops = { .info = { .name = "Samsung S5H1411 QAM/8VSB Frontend", .type = FE_ATSC, .frequency_min = 54000000, .frequency_max = 858000000, .frequency_stepsize = 62500, .caps = FE_CAN_QAM_64 | FE_CAN_QAM_256 | FE_CAN_8VSB }, .init = s5h1411_init, .sleep = s5h1411_sleep, .i2c_gate_ctrl = s5h1411_i2c_gate_ctrl, .set_frontend = s5h1411_set_frontend, .get_frontend = s5h1411_get_frontend, .get_tune_settings = s5h1411_get_tune_settings, .read_status = s5h1411_read_status, .read_ber = s5h1411_read_ber, .read_signal_strength = s5h1411_read_signal_strength, .read_snr = s5h1411_read_snr, .read_ucblocks = s5h1411_read_ucblocks, .release = s5h1411_release, }; module_param(debug, int, 0644); MODULE_PARM_DESC(debug, "Enable verbose debug messages"); MODULE_DESCRIPTION("Samsung S5H1411 QAM-B/ATSC Demodulator driver"); MODULE_AUTHOR("Steven Toth"); MODULE_LICENSE("GPL"); /* * Local variables: * c-basic-offset: 8 */
{ "language": "C" }
/* * Copyright (c) 2010-2011 Atheros Communications, Inc. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef AR9003_PHY_H #define AR9003_PHY_H /* * Channel Register Map */ #define AR_CHAN_BASE 0x9800 #define AR_PHY_TIMING1 (AR_CHAN_BASE + 0x0) #define AR_PHY_TIMING2 (AR_CHAN_BASE + 0x4) #define AR_PHY_TIMING3 (AR_CHAN_BASE + 0x8) #define AR_PHY_TIMING4 (AR_CHAN_BASE + 0xc) #define AR_PHY_TIMING5 (AR_CHAN_BASE + 0x10) #define AR_PHY_TIMING6 (AR_CHAN_BASE + 0x14) #define AR_PHY_TIMING11 (AR_CHAN_BASE + 0x18) #define AR_PHY_SPUR_REG (AR_CHAN_BASE + 0x1c) #define AR_PHY_RX_IQCAL_CORR_B0 (AR_CHAN_BASE + 0xdc) #define AR_PHY_TX_IQCAL_CONTROL_3 (AR_CHAN_BASE + 0xb0) #define AR_PHY_TIMING_CONTROL4_DO_GAIN_DC_IQ_CAL_SHIFT 16 #define AR_PHY_TIMING11_SPUR_FREQ_SD 0x3FF00000 #define AR_PHY_TIMING11_SPUR_FREQ_SD_S 20 #define AR_PHY_TIMING11_SPUR_DELTA_PHASE 0x000FFFFF #define AR_PHY_TIMING11_SPUR_DELTA_PHASE_S 0 #define AR_PHY_TIMING11_USE_SPUR_FILTER_IN_AGC 0x40000000 #define AR_PHY_TIMING11_USE_SPUR_FILTER_IN_AGC_S 30 #define AR_PHY_TIMING11_USE_SPUR_FILTER_IN_SELFCOR 0x80000000 #define AR_PHY_TIMING11_USE_SPUR_FILTER_IN_SELFCOR_S 31 #define AR_PHY_SPUR_REG_ENABLE_NF_RSSI_SPUR_MIT 0x4000000 #define AR_PHY_SPUR_REG_ENABLE_NF_RSSI_SPUR_MIT_S 26 #define AR_PHY_SPUR_REG_ENABLE_MASK_PPM 0x20000 /* bins move with freq offset */ #define AR_PHY_SPUR_REG_ENABLE_MASK_PPM_S 17 #define AR_PHY_SPUR_REG_SPUR_RSSI_THRESH 0x000000FF #define AR_PHY_SPUR_REG_SPUR_RSSI_THRESH_S 0 #define AR_PHY_SPUR_REG_EN_VIT_SPUR_RSSI 0x00000100 #define AR_PHY_SPUR_REG_EN_VIT_SPUR_RSSI_S 8 #define AR_PHY_SPUR_REG_MASK_RATE_CNTL 0x03FC0000 #define AR_PHY_SPUR_REG_MASK_RATE_CNTL_S 18 #define AR_PHY_RX_IQCAL_CORR_B0_LOOPBACK_IQCORR_EN 0x20000000 #define AR_PHY_RX_IQCAL_CORR_B0_LOOPBACK_IQCORR_EN_S 29 #define AR_PHY_TX_IQCAL_CONTROL_3_IQCORR_EN 0x80000000 #define AR_PHY_TX_IQCAL_CONTROL_3_IQCORR_EN_S 31 #define AR_PHY_FIND_SIG_LOW (AR_CHAN_BASE + 0x20) #define AR_PHY_SFCORR (AR_CHAN_BASE + 0x24) #define AR_PHY_SFCORR_LOW (AR_CHAN_BASE + 0x28) #define AR_PHY_SFCORR_EXT (AR_CHAN_BASE + 0x2c) #define AR_PHY_EXT_CCA (AR_CHAN_BASE + 0x30) #define AR_PHY_RADAR_0 (AR_CHAN_BASE + 0x34) #define AR_PHY_RADAR_1 (AR_CHAN_BASE + 0x38) #define AR_PHY_RADAR_EXT (AR_CHAN_BASE + 0x3c) #define AR_PHY_MULTICHAIN_CTRL (AR_CHAN_BASE + 0x80) #define AR_PHY_PERCHAIN_CSD (AR_CHAN_BASE + 0x84) #define AR_PHY_TX_PHASE_RAMP_0 (AR_CHAN_BASE + 0xd0) #define AR_PHY_ADC_GAIN_DC_CORR_0 (AR_CHAN_BASE + 0xd4) #define AR_PHY_IQ_ADC_MEAS_0_B0 (AR_CHAN_BASE + 0xc0) #define AR_PHY_IQ_ADC_MEAS_1_B0 (AR_CHAN_BASE + 0xc4) #define AR_PHY_IQ_ADC_MEAS_2_B0 (AR_CHAN_BASE + 0xc8) #define AR_PHY_IQ_ADC_MEAS_3_B0 (AR_CHAN_BASE + 0xcc) /* The following registers changed position from AR9300 1.0 to AR9300 2.0 */ #define AR_PHY_TX_PHASE_RAMP_0_9300_10 (AR_CHAN_BASE + 0xd0 - 0x10) #define AR_PHY_ADC_GAIN_DC_CORR_0_9300_10 (AR_CHAN_BASE + 0xd4 - 0x10) #define AR_PHY_IQ_ADC_MEAS_0_B0_9300_10 (AR_CHAN_BASE + 0xc0 + 0x8) #define AR_PHY_IQ_ADC_MEAS_1_B0_9300_10 (AR_CHAN_BASE + 0xc4 + 0x8) #define AR_PHY_IQ_ADC_MEAS_2_B0_9300_10 (AR_CHAN_BASE + 0xc8 + 0x8) #define AR_PHY_IQ_ADC_MEAS_3_B0_9300_10 (AR_CHAN_BASE + 0xcc + 0x8) #define AR_PHY_TX_CRC (AR_CHAN_BASE + 0xa0) #define AR_PHY_TST_DAC_CONST (AR_CHAN_BASE + 0xa4) #define AR_PHY_SPUR_REPORT_0 (AR_CHAN_BASE + 0xa8) #define AR_PHY_CHAN_INFO_TAB_0 (AR_CHAN_BASE + 0x300) /* * Channel Field Definitions */ #define AR_PHY_TIMING2_USE_FORCE_PPM 0x00001000 #define AR_PHY_TIMING2_FORCE_PPM_VAL 0x00000fff #define AR_PHY_TIMING3_DSC_MAN 0xFFFE0000 #define AR_PHY_TIMING3_DSC_MAN_S 17 #define AR_PHY_TIMING3_DSC_EXP 0x0001E000 #define AR_PHY_TIMING3_DSC_EXP_S 13 #define AR_PHY_TIMING4_IQCAL_LOG_COUNT_MAX 0xF000 #define AR_PHY_TIMING4_IQCAL_LOG_COUNT_MAX_S 12 #define AR_PHY_TIMING4_DO_CAL 0x10000 #define AR_PHY_TIMING4_ENABLE_PILOT_MASK 0x10000000 #define AR_PHY_TIMING4_ENABLE_PILOT_MASK_S 28 #define AR_PHY_TIMING4_ENABLE_CHAN_MASK 0x20000000 #define AR_PHY_TIMING4_ENABLE_CHAN_MASK_S 29 #define AR_PHY_TIMING4_ENABLE_SPUR_FILTER 0x40000000 #define AR_PHY_TIMING4_ENABLE_SPUR_FILTER_S 30 #define AR_PHY_TIMING4_ENABLE_SPUR_RSSI 0x80000000 #define AR_PHY_TIMING4_ENABLE_SPUR_RSSI_S 31 #define AR_PHY_NEW_ADC_GAIN_CORR_ENABLE 0x40000000 #define AR_PHY_NEW_ADC_DC_OFFSET_CORR_ENABLE 0x80000000 #define AR_PHY_SFCORR_LOW_USE_SELF_CORR_LOW 0x00000001 #define AR_PHY_SFCORR_LOW_M2COUNT_THR_LOW 0x00003F00 #define AR_PHY_SFCORR_LOW_M2COUNT_THR_LOW_S 8 #define AR_PHY_SFCORR_LOW_M1_THRESH_LOW 0x001FC000 #define AR_PHY_SFCORR_LOW_M1_THRESH_LOW_S 14 #define AR_PHY_SFCORR_LOW_M2_THRESH_LOW 0x0FE00000 #define AR_PHY_SFCORR_LOW_M2_THRESH_LOW_S 21 #define AR_PHY_SFCORR_M2COUNT_THR 0x0000001F #define AR_PHY_SFCORR_M2COUNT_THR_S 0 #define AR_PHY_SFCORR_M1_THRESH 0x00FE0000 #define AR_PHY_SFCORR_M1_THRESH_S 17 #define AR_PHY_SFCORR_M2_THRESH 0x7F000000 #define AR_PHY_SFCORR_M2_THRESH_S 24 #define AR_PHY_SFCORR_EXT_M1_THRESH 0x0000007F #define AR_PHY_SFCORR_EXT_M1_THRESH_S 0 #define AR_PHY_SFCORR_EXT_M2_THRESH 0x00003F80 #define AR_PHY_SFCORR_EXT_M2_THRESH_S 7 #define AR_PHY_SFCORR_EXT_M1_THRESH_LOW 0x001FC000 #define AR_PHY_SFCORR_EXT_M1_THRESH_LOW_S 14 #define AR_PHY_SFCORR_EXT_M2_THRESH_LOW 0x0FE00000 #define AR_PHY_SFCORR_EXT_M2_THRESH_LOW_S 21 #define AR_PHY_SFCORR_EXT_SPUR_SUBCHANNEL_SD 0x10000000 #define AR_PHY_SFCORR_EXT_SPUR_SUBCHANNEL_SD_S 28 #define AR_PHY_SFCORR_SPUR_SUBCHNL_SD_S 28 #define AR_PHY_EXT_CCA_THRESH62 0x007F0000 #define AR_PHY_EXT_CCA_THRESH62_S 16 #define AR_PHY_EXTCHN_PWRTHR1_ANT_DIV_ALT_ANT_MINGAINIDX 0x0000FF00 #define AR_PHY_EXTCHN_PWRTHR1_ANT_DIV_ALT_ANT_MINGAINIDX_S 8 #define AR_PHY_EXT_MINCCA_PWR 0x01FF0000 #define AR_PHY_EXT_MINCCA_PWR_S 16 #define AR_PHY_EXT_CYCPWR_THR1 0x0000FE00L #define AR_PHY_EXT_CYCPWR_THR1_S 9 #define AR_PHY_TIMING5_CYCPWR_THR1 0x000000FE #define AR_PHY_TIMING5_CYCPWR_THR1_S 1 #define AR_PHY_TIMING5_CYCPWR_THR1_ENABLE 0x00000001 #define AR_PHY_TIMING5_CYCPWR_THR1_ENABLE_S 0 #define AR_PHY_TIMING5_CYCPWR_THR1A 0x007F0000 #define AR_PHY_TIMING5_CYCPWR_THR1A_S 16 #define AR_PHY_TIMING5_RSSI_THR1A (0x7F << 16) #define AR_PHY_TIMING5_RSSI_THR1A_S 16 #define AR_PHY_TIMING5_RSSI_THR1A_ENA (0x1 << 15) #define AR_PHY_RADAR_0_ENA 0x00000001 #define AR_PHY_RADAR_0_FFT_ENA 0x80000000 #define AR_PHY_RADAR_0_INBAND 0x0000003e #define AR_PHY_RADAR_0_INBAND_S 1 #define AR_PHY_RADAR_0_PRSSI 0x00000FC0 #define AR_PHY_RADAR_0_PRSSI_S 6 #define AR_PHY_RADAR_0_HEIGHT 0x0003F000 #define AR_PHY_RADAR_0_HEIGHT_S 12 #define AR_PHY_RADAR_0_RRSSI 0x00FC0000 #define AR_PHY_RADAR_0_RRSSI_S 18 #define AR_PHY_RADAR_0_FIRPWR 0x7F000000 #define AR_PHY_RADAR_0_FIRPWR_S 24 #define AR_PHY_RADAR_1_RELPWR_ENA 0x00800000 #define AR_PHY_RADAR_1_USE_FIR128 0x00400000 #define AR_PHY_RADAR_1_RELPWR_THRESH 0x003F0000 #define AR_PHY_RADAR_1_RELPWR_THRESH_S 16 #define AR_PHY_RADAR_1_BLOCK_CHECK 0x00008000 #define AR_PHY_RADAR_1_MAX_RRSSI 0x00004000 #define AR_PHY_RADAR_1_RELSTEP_CHECK 0x00002000 #define AR_PHY_RADAR_1_RELSTEP_THRESH 0x00001F00 #define AR_PHY_RADAR_1_RELSTEP_THRESH_S 8 #define AR_PHY_RADAR_1_MAXLEN 0x000000FF #define AR_PHY_RADAR_1_MAXLEN_S 0 #define AR_PHY_RADAR_EXT_ENA 0x00004000 #define AR_PHY_RADAR_DC_PWR_THRESH 0x007f8000 #define AR_PHY_RADAR_DC_PWR_THRESH_S 15 #define AR_PHY_RADAR_LB_DC_CAP 0x7f800000 #define AR_PHY_RADAR_LB_DC_CAP_S 23 #define AR_PHY_FIND_SIG_LOW_FIRSTEP_LOW (0x3f << 6) #define AR_PHY_FIND_SIG_LOW_FIRSTEP_LOW_S 6 #define AR_PHY_FIND_SIG_LOW_FIRPWR (0x7f << 12) #define AR_PHY_FIND_SIG_LOW_FIRPWR_S 12 #define AR_PHY_FIND_SIG_LOW_FIRPWR_SIGN_BIT 19 #define AR_PHY_FIND_SIG_LOW_RELSTEP 0x1f #define AR_PHY_FIND_SIG_LOW_RELSTEP_S 0 #define AR_PHY_FIND_SIG_LOW_RELSTEP_SIGN_BIT 5 #define AR_PHY_CHAN_INFO_TAB_S2_READ 0x00000008 #define AR_PHY_CHAN_INFO_TAB_S2_READ_S 3 #define AR_PHY_RX_IQCAL_CORR_IQCORR_Q_Q_COFF 0x0000007F #define AR_PHY_RX_IQCAL_CORR_IQCORR_Q_Q_COFF_S 0 #define AR_PHY_RX_IQCAL_CORR_IQCORR_Q_I_COFF 0x00003F80 #define AR_PHY_RX_IQCAL_CORR_IQCORR_Q_I_COFF_S 7 #define AR_PHY_RX_IQCAL_CORR_IQCORR_ENABLE 0x00004000 #define AR_PHY_RX_IQCAL_CORR_LOOPBACK_IQCORR_Q_Q_COFF 0x003f8000 #define AR_PHY_RX_IQCAL_CORR_LOOPBACK_IQCORR_Q_Q_COFF_S 15 #define AR_PHY_RX_IQCAL_CORR_LOOPBACK_IQCORR_Q_I_COFF 0x1fc00000 #define AR_PHY_RX_IQCAL_CORR_LOOPBACK_IQCORR_Q_I_COFF_S 22 /* * MRC Register Map */ #define AR_MRC_BASE 0x9c00 #define AR_PHY_TIMING_3A (AR_MRC_BASE + 0x0) #define AR_PHY_LDPC_CNTL1 (AR_MRC_BASE + 0x4) #define AR_PHY_LDPC_CNTL2 (AR_MRC_BASE + 0x8) #define AR_PHY_PILOT_SPUR_MASK (AR_MRC_BASE + 0xc) #define AR_PHY_CHAN_SPUR_MASK (AR_MRC_BASE + 0x10) #define AR_PHY_SGI_DELTA (AR_MRC_BASE + 0x14) #define AR_PHY_ML_CNTL_1 (AR_MRC_BASE + 0x18) #define AR_PHY_ML_CNTL_2 (AR_MRC_BASE + 0x1c) #define AR_PHY_TST_ADC (AR_MRC_BASE + 0x20) #define AR_PHY_PILOT_SPUR_MASK_CF_PILOT_MASK_IDX_A 0x00000FE0 #define AR_PHY_PILOT_SPUR_MASK_CF_PILOT_MASK_IDX_A_S 5 #define AR_PHY_PILOT_SPUR_MASK_CF_PILOT_MASK_A 0x1F #define AR_PHY_PILOT_SPUR_MASK_CF_PILOT_MASK_A_S 0 #define AR_PHY_PILOT_SPUR_MASK_CF_PILOT_MASK_IDX_B 0x00FE0000 #define AR_PHY_PILOT_SPUR_MASK_CF_PILOT_MASK_IDX_B_S 17 #define AR_PHY_PILOT_SPUR_MASK_CF_PILOT_MASK_B 0x0001F000 #define AR_PHY_PILOT_SPUR_MASK_CF_PILOT_MASK_B_S 12 #define AR_PHY_CHAN_SPUR_MASK_CF_CHAN_MASK_IDX_A 0x00000FE0 #define AR_PHY_CHAN_SPUR_MASK_CF_CHAN_MASK_IDX_A_S 5 #define AR_PHY_CHAN_SPUR_MASK_CF_CHAN_MASK_A 0x1F #define AR_PHY_CHAN_SPUR_MASK_CF_CHAN_MASK_A_S 0 #define AR_PHY_CHAN_SPUR_MASK_CF_CHAN_MASK_IDX_B 0x00FE0000 #define AR_PHY_CHAN_SPUR_MASK_CF_CHAN_MASK_IDX_B_S 17 #define AR_PHY_CHAN_SPUR_MASK_CF_CHAN_MASK_B 0x0001F000 #define AR_PHY_CHAN_SPUR_MASK_CF_CHAN_MASK_B_S 12 /* * MRC Feild Definitions */ #define AR_PHY_SGI_DSC_MAN 0x0007FFF0 #define AR_PHY_SGI_DSC_MAN_S 4 #define AR_PHY_SGI_DSC_EXP 0x0000000F #define AR_PHY_SGI_DSC_EXP_S 0 /* * BBB Register Map */ #define AR_BBB_BASE 0x9d00 /* * AGC Register Map */ #define AR_AGC_BASE 0x9e00 #define AR_PHY_SETTLING (AR_AGC_BASE + 0x0) #define AR_PHY_FORCEMAX_GAINS_0 (AR_AGC_BASE + 0x4) #define AR_PHY_GAINS_MINOFF0 (AR_AGC_BASE + 0x8) #define AR_PHY_DESIRED_SZ (AR_AGC_BASE + 0xc) #define AR_PHY_FIND_SIG (AR_AGC_BASE + 0x10) #define AR_PHY_AGC (AR_AGC_BASE + 0x14) #define AR_PHY_EXT_ATTEN_CTL_0 (AR_AGC_BASE + 0x18) #define AR_PHY_CCA_0 (AR_AGC_BASE + 0x1c) #define AR_PHY_CCA_CTRL_0 (AR_AGC_BASE + 0x20) #define AR_PHY_RESTART (AR_AGC_BASE + 0x24) /* * Antenna Diversity settings */ #define AR_PHY_MC_GAIN_CTRL (AR_AGC_BASE + 0x28) #define AR_ANT_DIV_CTRL_ALL 0x7e000000 #define AR_ANT_DIV_CTRL_ALL_S 25 #define AR_ANT_DIV_ENABLE 0x1000000 #define AR_ANT_DIV_ENABLE_S 24 #define AR_PHY_ANT_FAST_DIV_BIAS 0x00007e00 #define AR_PHY_ANT_FAST_DIV_BIAS_S 9 #define AR_PHY_ANT_SW_RX_PROT 0x00800000 #define AR_PHY_ANT_SW_RX_PROT_S 23 #define AR_PHY_ANT_DIV_LNADIV 0x01000000 #define AR_PHY_ANT_DIV_LNADIV_S 24 #define AR_PHY_ANT_DIV_ALT_LNACONF 0x06000000 #define AR_PHY_ANT_DIV_ALT_LNACONF_S 25 #define AR_PHY_ANT_DIV_MAIN_LNACONF 0x18000000 #define AR_PHY_ANT_DIV_MAIN_LNACONF_S 27 #define AR_PHY_ANT_DIV_ALT_GAINTB 0x20000000 #define AR_PHY_ANT_DIV_ALT_GAINTB_S 29 #define AR_PHY_ANT_DIV_MAIN_GAINTB 0x40000000 #define AR_PHY_ANT_DIV_MAIN_GAINTB_S 30 #define AR_PHY_EXTCHN_PWRTHR1 (AR_AGC_BASE + 0x2c) #define AR_PHY_EXT_CHN_WIN (AR_AGC_BASE + 0x30) #define AR_PHY_20_40_DET_THR (AR_AGC_BASE + 0x34) #define AR_PHY_RIFS_SRCH (AR_AGC_BASE + 0x38) #define AR_PHY_PEAK_DET_CTRL_1 (AR_AGC_BASE + 0x3c) #define AR_PHY_PEAK_DET_CTRL_2 (AR_AGC_BASE + 0x40) #define AR_PHY_RX_GAIN_BOUNDS_1 (AR_AGC_BASE + 0x44) #define AR_PHY_RX_GAIN_BOUNDS_2 (AR_AGC_BASE + 0x48) #define AR_PHY_RSSI_0 (AR_AGC_BASE + 0x180) #define AR_PHY_SPUR_CCK_REP0 (AR_AGC_BASE + 0x184) #define AR_PHY_CCK_DETECT (AR_AGC_BASE + 0x1c0) #define AR_FAST_DIV_ENABLE 0x2000 #define AR_FAST_DIV_ENABLE_S 13 #define AR_PHY_DAG_CTRLCCK (AR_AGC_BASE + 0x1c4) #define AR_PHY_IQCORR_CTRL_CCK (AR_AGC_BASE + 0x1c8) #define AR_PHY_CCK_SPUR_MIT (AR_AGC_BASE + 0x1cc) #define AR_PHY_CCK_SPUR_MIT_SPUR_RSSI_THR 0x000001fe #define AR_PHY_CCK_SPUR_MIT_SPUR_RSSI_THR_S 1 #define AR_PHY_CCK_SPUR_MIT_SPUR_FILTER_TYPE 0x60000000 #define AR_PHY_CCK_SPUR_MIT_SPUR_FILTER_TYPE_S 29 #define AR_PHY_CCK_SPUR_MIT_USE_CCK_SPUR_MIT 0x00000001 #define AR_PHY_CCK_SPUR_MIT_USE_CCK_SPUR_MIT_S 0 #define AR_PHY_CCK_SPUR_MIT_CCK_SPUR_FREQ 0x1ffffe00 #define AR_PHY_CCK_SPUR_MIT_CCK_SPUR_FREQ_S 9 #define AR_PHY_MRC_CCK_CTRL (AR_AGC_BASE + 0x1d0) #define AR_PHY_MRC_CCK_ENABLE 0x00000001 #define AR_PHY_MRC_CCK_ENABLE_S 0 #define AR_PHY_MRC_CCK_MUX_REG 0x00000002 #define AR_PHY_MRC_CCK_MUX_REG_S 1 #define AR_PHY_RX_OCGAIN (AR_AGC_BASE + 0x200) #define AR_PHY_CCA_NOM_VAL_9300_2GHZ -110 #define AR_PHY_CCA_NOM_VAL_9300_5GHZ -115 #define AR_PHY_CCA_MIN_GOOD_VAL_9300_2GHZ -125 #define AR_PHY_CCA_MIN_GOOD_VAL_9300_5GHZ -125 #define AR_PHY_CCA_MAX_GOOD_VAL_9300_2GHZ -60 #define AR_PHY_CCA_MAX_GOOD_VAL_9300_5GHZ -60 #define AR_PHY_CCA_MAX_GOOD_VAL_9300_FCC_2GHZ -95 #define AR_PHY_CCA_MAX_GOOD_VAL_9300_FCC_5GHZ -100 #define AR_PHY_CCA_NOM_VAL_9462_2GHZ -127 #define AR_PHY_CCA_MIN_GOOD_VAL_9462_2GHZ -127 #define AR_PHY_CCA_MAX_GOOD_VAL_9462_2GHZ -60 #define AR_PHY_CCA_NOM_VAL_9462_5GHZ -127 #define AR_PHY_CCA_MIN_GOOD_VAL_9462_5GHZ -127 #define AR_PHY_CCA_MAX_GOOD_VAL_9462_5GHZ -60 #define AR_PHY_CCA_NOM_VAL_9330_2GHZ -118 #define AR9300_EXT_LNA_CTL_GPIO_AR9485 9 /* * AGC Field Definitions */ #define AR_PHY_EXT_ATTEN_CTL_RXTX_MARGIN 0x00FC0000 #define AR_PHY_EXT_ATTEN_CTL_RXTX_MARGIN_S 18 #define AR_PHY_EXT_ATTEN_CTL_BSW_MARGIN 0x00003C00 #define AR_PHY_EXT_ATTEN_CTL_BSW_MARGIN_S 10 #define AR_PHY_EXT_ATTEN_CTL_BSW_ATTEN 0x0000001F #define AR_PHY_EXT_ATTEN_CTL_BSW_ATTEN_S 0 #define AR_PHY_EXT_ATTEN_CTL_XATTEN2_MARGIN 0x003E0000 #define AR_PHY_EXT_ATTEN_CTL_XATTEN2_MARGIN_S 17 #define AR_PHY_EXT_ATTEN_CTL_XATTEN1_MARGIN 0x0001F000 #define AR_PHY_EXT_ATTEN_CTL_XATTEN1_MARGIN_S 12 #define AR_PHY_EXT_ATTEN_CTL_XATTEN2_DB 0x00000FC0 #define AR_PHY_EXT_ATTEN_CTL_XATTEN2_DB_S 6 #define AR_PHY_EXT_ATTEN_CTL_XATTEN1_DB 0x0000003F #define AR_PHY_EXT_ATTEN_CTL_XATTEN1_DB_S 0 #define AR_PHY_RXGAIN_TXRX_ATTEN 0x0003F000 #define AR_PHY_RXGAIN_TXRX_ATTEN_S 12 #define AR_PHY_RXGAIN_TXRX_RF_MAX 0x007C0000 #define AR_PHY_RXGAIN_TXRX_RF_MAX_S 18 #define AR9280_PHY_RXGAIN_TXRX_ATTEN 0x00003F80 #define AR9280_PHY_RXGAIN_TXRX_ATTEN_S 7 #define AR9280_PHY_RXGAIN_TXRX_MARGIN 0x001FC000 #define AR9280_PHY_RXGAIN_TXRX_MARGIN_S 14 #define AR_PHY_SETTLING_SWITCH 0x00003F80 #define AR_PHY_SETTLING_SWITCH_S 7 #define AR_PHY_DESIRED_SZ_ADC 0x000000FF #define AR_PHY_DESIRED_SZ_ADC_S 0 #define AR_PHY_DESIRED_SZ_PGA 0x0000FF00 #define AR_PHY_DESIRED_SZ_PGA_S 8 #define AR_PHY_DESIRED_SZ_TOT_DES 0x0FF00000 #define AR_PHY_DESIRED_SZ_TOT_DES_S 20 #define AR_PHY_MINCCA_PWR 0x1FF00000 #define AR_PHY_MINCCA_PWR_S 20 #define AR_PHY_CCA_THRESH62 0x0007F000 #define AR_PHY_CCA_THRESH62_S 12 #define AR9280_PHY_MINCCA_PWR 0x1FF00000 #define AR9280_PHY_MINCCA_PWR_S 20 #define AR9280_PHY_CCA_THRESH62 0x000FF000 #define AR9280_PHY_CCA_THRESH62_S 12 #define AR_PHY_EXT_CCA0_THRESH62 0x000000FF #define AR_PHY_EXT_CCA0_THRESH62_S 0 #define AR_PHY_EXT_CCA0_THRESH62_1 0x000001FF #define AR_PHY_EXT_CCA0_THRESH62_1_S 0 #define AR_PHY_CCK_DETECT_WEAK_SIG_THR_CCK 0x0000003F #define AR_PHY_CCK_DETECT_WEAK_SIG_THR_CCK_S 0 #define AR_PHY_CCK_DETECT_ANT_SWITCH_TIME 0x00001FC0 #define AR_PHY_CCK_DETECT_ANT_SWITCH_TIME_S 6 #define AR_PHY_CCK_DETECT_BB_ENABLE_ANT_FAST_DIV 0x2000 #define AR_PHY_DAG_CTRLCCK_EN_RSSI_THR 0x00000200 #define AR_PHY_DAG_CTRLCCK_EN_RSSI_THR_S 9 #define AR_PHY_DAG_CTRLCCK_RSSI_THR 0x0001FC00 #define AR_PHY_DAG_CTRLCCK_RSSI_THR_S 10 #define AR_PHY_RIFS_INIT_DELAY 0x3ff0000 #define AR_PHY_AGC_QUICK_DROP 0x03c00000 #define AR_PHY_AGC_QUICK_DROP_S 22 #define AR_PHY_AGC_COARSE_LOW 0x00007F80 #define AR_PHY_AGC_COARSE_LOW_S 7 #define AR_PHY_AGC_COARSE_HIGH 0x003F8000 #define AR_PHY_AGC_COARSE_HIGH_S 15 #define AR_PHY_AGC_COARSE_PWR_CONST 0x0000007F #define AR_PHY_AGC_COARSE_PWR_CONST_S 0 #define AR_PHY_FIND_SIG_FIRSTEP 0x0003F000 #define AR_PHY_FIND_SIG_FIRSTEP_S 12 #define AR_PHY_FIND_SIG_FIRPWR 0x03FC0000 #define AR_PHY_FIND_SIG_FIRPWR_S 18 #define AR_PHY_FIND_SIG_FIRPWR_SIGN_BIT 25 #define AR_PHY_FIND_SIG_RELPWR (0x1f << 6) #define AR_PHY_FIND_SIG_RELPWR_S 6 #define AR_PHY_FIND_SIG_RELPWR_SIGN_BIT 11 #define AR_PHY_FIND_SIG_RELSTEP 0x1f #define AR_PHY_FIND_SIG_RELSTEP_S 0 #define AR_PHY_FIND_SIG_RELSTEP_SIGN_BIT 5 #define AR_PHY_RESTART_ENABLE_DIV_M2FLAG 0x00200000 #define AR_PHY_RESTART_ENABLE_DIV_M2FLAG_S 21 #define AR_PHY_RESTART_DIV_GC 0x001C0000 #define AR_PHY_RESTART_DIV_GC_S 18 #define AR_PHY_RESTART_ENA 0x01 #define AR_PHY_DC_RESTART_DIS 0x40000000 #define AR_PHY_TPC_OLPC_GAIN_DELTA_PAL_ON 0xFF000000 #define AR_PHY_TPC_OLPC_GAIN_DELTA_PAL_ON_S 24 #define AR_PHY_TPC_OLPC_GAIN_DELTA 0x00FF0000 #define AR_PHY_TPC_OLPC_GAIN_DELTA_S 16 #define AR_PHY_TPC_6_ERROR_EST_MODE 0x03000000 #define AR_PHY_TPC_6_ERROR_EST_MODE_S 24 /* * SM Register Map */ #define AR_SM_BASE 0xa200 #define AR_PHY_D2_CHIP_ID (AR_SM_BASE + 0x0) #define AR_PHY_GEN_CTRL (AR_SM_BASE + 0x4) #define AR_PHY_MODE (AR_SM_BASE + 0x8) #define AR_PHY_ACTIVE (AR_SM_BASE + 0xc) #define AR_PHY_SPUR_MASK_A (AR_SM_BASE + (AR_SREV_9561(ah) ? 0x18 : 0x20)) #define AR_PHY_SPUR_MASK_B (AR_SM_BASE + (AR_SREV_9561(ah) ? 0x1c : 0x24)) #define AR_PHY_SPECTRAL_SCAN (AR_SM_BASE + 0x28) #define AR_PHY_RADAR_BW_FILTER (AR_SM_BASE + 0x2c) #define AR_PHY_SEARCH_START_DELAY (AR_SM_BASE + 0x30) #define AR_PHY_MAX_RX_LEN (AR_SM_BASE + 0x34) #define AR_PHY_FRAME_CTL (AR_SM_BASE + 0x38) #define AR_PHY_RFBUS_REQ (AR_SM_BASE + 0x3c) #define AR_PHY_RFBUS_GRANT (AR_SM_BASE + 0x40) #define AR_PHY_RIFS (AR_SM_BASE + 0x44) #define AR_PHY_RX_CLR_DELAY (AR_SM_BASE + 0x50) #define AR_PHY_RX_DELAY (AR_SM_BASE + 0x54) #define AR_PHY_XPA_TIMING_CTL (AR_SM_BASE + 0x64) #define AR_PHY_MISC_PA_CTL (AR_SM_BASE + 0x80) #define AR_PHY_SWITCH_CHAIN_0 (AR_SM_BASE + 0x84) #define AR_PHY_SWITCH_COM (AR_SM_BASE + 0x88) #define AR_PHY_SWITCH_COM_2 (AR_SM_BASE + 0x8c) #define AR_PHY_RX_CHAINMASK (AR_SM_BASE + 0xa0) #define AR_PHY_CAL_CHAINMASK (AR_SM_BASE + 0xc0) #define AR_PHY_CALMODE (AR_SM_BASE + 0xc8) #define AR_PHY_FCAL_1 (AR_SM_BASE + 0xcc) #define AR_PHY_FCAL_2_0 (AR_SM_BASE + 0xd0) #define AR_PHY_DFT_TONE_CTL_0 (AR_SM_BASE + 0xd4) #define AR_PHY_CL_CAL_CTL (AR_SM_BASE + 0xd8) #define AR_PHY_CL_TAB_0 (AR_SM_BASE + 0x100) #define AR_PHY_SYNTH_CONTROL (AR_SM_BASE + 0x140) #define AR_PHY_ADDAC_CLK_SEL (AR_SM_BASE + 0x144) #define AR_PHY_PLL_CTL (AR_SM_BASE + 0x148) #define AR_PHY_ANALOG_SWAP (AR_SM_BASE + 0x14c) #define AR_PHY_ADDAC_PARA_CTL (AR_SM_BASE + 0x150) #define AR_PHY_XPA_CFG (AR_SM_BASE + 0x158) #define AR_PHY_FLC_PWR_THRESH 7 #define AR_PHY_FLC_PWR_THRESH_S 0 #define AR_PHY_FRAME_CTL_CF_OVERLAP_WINDOW 3 #define AR_PHY_FRAME_CTL_CF_OVERLAP_WINDOW_S 0 #define AR_PHY_SPUR_MASK_A_CF_PUNC_MASK_IDX_A 0x0001FC00 #define AR_PHY_SPUR_MASK_A_CF_PUNC_MASK_IDX_A_S 10 #define AR_PHY_SPUR_MASK_A_CF_PUNC_MASK_A 0x3FF #define AR_PHY_SPUR_MASK_A_CF_PUNC_MASK_A_S 0 #define AR_PHY_TEST (AR_SM_BASE + (AR_SREV_9561(ah) ? 0x15c : 0x160)) #define AR_PHY_TEST_BBB_OBS_SEL 0x780000 #define AR_PHY_TEST_BBB_OBS_SEL_S 19 #define AR_PHY_TEST_RX_OBS_SEL_BIT5_S 23 #define AR_PHY_TEST_RX_OBS_SEL_BIT5 (1 << AR_PHY_TEST_RX_OBS_SEL_BIT5_S) #define AR_PHY_TEST_CHAIN_SEL 0xC0000000 #define AR_PHY_TEST_CHAIN_SEL_S 30 #define AR_PHY_TEST_CTL_STATUS (AR_SM_BASE + (AR_SREV_9561(ah) ? 0x160 : 0x164)) #define AR_PHY_TEST_CTL_TSTDAC_EN 0x1 #define AR_PHY_TEST_CTL_TSTDAC_EN_S 0 #define AR_PHY_TEST_CTL_TX_OBS_SEL 0x1C #define AR_PHY_TEST_CTL_TX_OBS_SEL_S 2 #define AR_PHY_TEST_CTL_TX_OBS_MUX_SEL 0x60 #define AR_PHY_TEST_CTL_TX_OBS_MUX_SEL_S 5 #define AR_PHY_TEST_CTL_TSTADC_EN 0x100 #define AR_PHY_TEST_CTL_TSTADC_EN_S 8 #define AR_PHY_TEST_CTL_RX_OBS_SEL 0x3C00 #define AR_PHY_TEST_CTL_RX_OBS_SEL_S 10 #define AR_PHY_TEST_CTL_DEBUGPORT_SEL 0xe0000000 #define AR_PHY_TEST_CTL_DEBUGPORT_SEL_S 29 #define AR_PHY_TSTDAC (AR_SM_BASE + (AR_SREV_9561(ah) ? 0x164 : 0x168)) #define AR_PHY_CHAN_STATUS (AR_SM_BASE + (AR_SREV_9561(ah) ? 0x168 : 0x16c)) #define AR_PHY_CHAN_INFO_MEMORY (AR_SM_BASE + (AR_SREV_9561(ah) ? 0x16c : 0x170)) #define AR_PHY_CHAN_INFO_MEMORY_CHANINFOMEM_S2_READ 0x00000008 #define AR_PHY_CHAN_INFO_MEMORY_CHANINFOMEM_S2_READ_S 3 #define AR_PHY_CHNINFO_NOISEPWR (AR_SM_BASE + (AR_SREV_9561(ah) ? 0x170 : 0x174)) #define AR_PHY_CHNINFO_GAINDIFF (AR_SM_BASE + (AR_SREV_9561(ah) ? 0x174 : 0x178)) #define AR_PHY_CHNINFO_FINETIM (AR_SM_BASE + (AR_SREV_9561(ah) ? 0x178 : 0x17c)) #define AR_PHY_CHAN_INFO_GAIN_0 (AR_SM_BASE + (AR_SREV_9561(ah) ? 0x17c : 0x180)) #define AR_PHY_SCRAMBLER_SEED (AR_SM_BASE + (AR_SREV_9561(ah) ? 0x184 : 0x190)) #define AR_PHY_CCK_TX_CTRL (AR_SM_BASE + (AR_SREV_9561(ah) ? 0x188 : 0x194)) #define AR_PHY_HEAVYCLIP_CTL (AR_SM_BASE + (AR_SREV_9561(ah) ? 0x198 : 0x1a4)) #define AR_PHY_HEAVYCLIP_20 (AR_SM_BASE + 0x1a8) #define AR_PHY_HEAVYCLIP_40 (AR_SM_BASE + 0x1ac) #define AR_PHY_HEAVYCLIP_1 (AR_SM_BASE + 0x19c) #define AR_PHY_HEAVYCLIP_2 (AR_SM_BASE + 0x1a0) #define AR_PHY_HEAVYCLIP_3 (AR_SM_BASE + 0x1a4) #define AR_PHY_HEAVYCLIP_4 (AR_SM_BASE + 0x1a8) #define AR_PHY_HEAVYCLIP_5 (AR_SM_BASE + 0x1ac) #define AR_PHY_ILLEGAL_TXRATE (AR_SM_BASE + 0x1b0) #define AR_PHY_POWER_TX_RATE(_d) (AR_SM_BASE + 0x1c0 + ((_d) << 2)) #define AR_PHY_PWRTX_MAX (AR_SM_BASE + 0x1f0) #define AR_PHY_POWER_TX_SUB (AR_SM_BASE + 0x1f4) #define AR_PHY_TPC_1 (AR_SM_BASE + 0x1f8) #define AR_PHY_TPC_1_FORCED_DAC_GAIN 0x0000003e #define AR_PHY_TPC_1_FORCED_DAC_GAIN_S 1 #define AR_PHY_TPC_1_FORCE_DAC_GAIN 0x00000001 #define AR_PHY_TPC_1_FORCE_DAC_GAIN_S 0 #define AR_PHY_TPC_4_B0 (AR_SM_BASE + 0x204) #define AR_PHY_TPC_5_B0 (AR_SM_BASE + 0x208) #define AR_PHY_TPC_6_B0 (AR_SM_BASE + 0x20c) #define AR_PHY_TPC_11_B0 (AR_SM_BASE + 0x220) #define AR_PHY_TPC_11_B1 (AR_SM1_BASE + 0x220) #define AR_PHY_TPC_11_B2 (AR_SM2_BASE + 0x220) #define AR_PHY_TPC_11_OLPC_GAIN_DELTA 0x00ff0000 #define AR_PHY_TPC_11_OLPC_GAIN_DELTA_S 16 #define AR_PHY_TPC_12 (AR_SM_BASE + 0x224) #define AR_PHY_TPC_12_DESIRED_SCALE_HT40_5 0x3e000000 #define AR_PHY_TPC_12_DESIRED_SCALE_HT40_5_S 25 #define AR_PHY_TPC_18 (AR_SM_BASE + 0x23c) #define AR_PHY_TPC_18_THERM_CAL_VALUE 0x000000ff #define AR_PHY_TPC_18_THERM_CAL_VALUE_S 0 #define AR_PHY_TPC_18_VOLT_CAL_VALUE 0x0000ff00 #define AR_PHY_TPC_18_VOLT_CAL_VALUE_S 8 #define AR_PHY_TPC_19 (AR_SM_BASE + 0x240) #define AR_PHY_TPC_19_ALPHA_VOLT 0x001f0000 #define AR_PHY_TPC_19_ALPHA_VOLT_S 16 #define AR_PHY_TPC_19_ALPHA_THERM 0xff #define AR_PHY_TPC_19_ALPHA_THERM_S 0 #define AR_PHY_TX_FORCED_GAIN (AR_SM_BASE + 0x258) #define AR_PHY_TX_FORCED_GAIN_FORCE_TX_GAIN 0x00000001 #define AR_PHY_TX_FORCED_GAIN_FORCE_TX_GAIN_S 0 #define AR_PHY_TX_FORCED_GAIN_FORCED_TXBB1DBGAIN 0x0000000e #define AR_PHY_TX_FORCED_GAIN_FORCED_TXBB1DBGAIN_S 1 #define AR_PHY_TX_FORCED_GAIN_FORCED_TXBB6DBGAIN 0x00000030 #define AR_PHY_TX_FORCED_GAIN_FORCED_TXBB6DBGAIN_S 4 #define AR_PHY_TX_FORCED_GAIN_FORCED_TXMXRGAIN 0x000003c0 #define AR_PHY_TX_FORCED_GAIN_FORCED_TXMXRGAIN_S 6 #define AR_PHY_TX_FORCED_GAIN_FORCED_PADRVGNA 0x00003c00 #define AR_PHY_TX_FORCED_GAIN_FORCED_PADRVGNA_S 10 #define AR_PHY_TX_FORCED_GAIN_FORCED_PADRVGNB 0x0003c000 #define AR_PHY_TX_FORCED_GAIN_FORCED_PADRVGNB_S 14 #define AR_PHY_TX_FORCED_GAIN_FORCED_PADRVGNC 0x003c0000 #define AR_PHY_TX_FORCED_GAIN_FORCED_PADRVGNC_S 18 #define AR_PHY_TX_FORCED_GAIN_FORCED_PADRVGND 0x00c00000 #define AR_PHY_TX_FORCED_GAIN_FORCED_PADRVGND_S 22 #define AR_PHY_TX_FORCED_GAIN_FORCED_ENABLE_PAL 0x01000000 #define AR_PHY_TX_FORCED_GAIN_FORCED_ENABLE_PAL_S 24 #define AR_PHY_PDADC_TAB_0 (AR_SM_BASE + 0x280) #define AR_PHY_TXGAIN_TABLE (AR_SM_BASE + 0x300) #define AR_PHY_TX_IQCAL_CONTROL_0 (AR_SM_BASE + (AR_SREV_9485(ah) ? \ 0x3c4 : 0x444)) #define AR_PHY_TX_IQCAL_CONTROL_1 (AR_SM_BASE + (AR_SREV_9485(ah) ? \ 0x3c8 : 0x448)) #define AR_PHY_TX_IQCAL_START (AR_SM_BASE + (AR_SREV_9485(ah) ? \ 0x3c4 : 0x440)) #define AR_PHY_TX_IQCAL_STATUS_B0 (AR_SM_BASE + (AR_SREV_9485(ah) ? \ 0x3f0 : 0x48c)) #define AR_PHY_TX_IQCAL_CORR_COEFF_B0(_i) (AR_SM_BASE + \ (AR_SREV_9485(ah) ? \ 0x3d0 : 0x450) + ((_i) << 2)) #define AR_PHY_RTT_CTRL (AR_SM_BASE + 0x380) #define AR_PHY_WATCHDOG_STATUS (AR_SM_BASE + 0x5c0) #define AR_PHY_WATCHDOG_CTL_1 (AR_SM_BASE + 0x5c4) #define AR_PHY_WATCHDOG_CTL_2 (AR_SM_BASE + 0x5c8) #define AR_PHY_WATCHDOG_CTL (AR_SM_BASE + 0x5cc) #define AR_PHY_ONLY_WARMRESET (AR_SM_BASE + 0x5d0) #define AR_PHY_ONLY_CTL (AR_SM_BASE + 0x5d4) #define AR_PHY_ECO_CTRL (AR_SM_BASE + 0x5dc) #define AR_PHY_BB_THERM_ADC_1 (AR_SM_BASE + 0x248) #define AR_PHY_BB_THERM_ADC_1_INIT_THERM 0x000000ff #define AR_PHY_BB_THERM_ADC_1_INIT_THERM_S 0 #define AR_PHY_BB_THERM_ADC_3 (AR_SM_BASE + 0x250) #define AR_PHY_BB_THERM_ADC_3_THERM_ADC_SCALE_GAIN 0x0001ff00 #define AR_PHY_BB_THERM_ADC_3_THERM_ADC_SCALE_GAIN_S 8 #define AR_PHY_BB_THERM_ADC_3_THERM_ADC_OFFSET 0x000000ff #define AR_PHY_BB_THERM_ADC_3_THERM_ADC_OFFSET_S 0 #define AR_PHY_BB_THERM_ADC_4 (AR_SM_BASE + 0x254) #define AR_PHY_BB_THERM_ADC_4_LATEST_THERM_VALUE 0x000000ff #define AR_PHY_BB_THERM_ADC_4_LATEST_THERM_VALUE_S 0 #define AR_PHY_BB_THERM_ADC_4_LATEST_VOLT_VALUE 0x0000ff00 #define AR_PHY_BB_THERM_ADC_4_LATEST_VOLT_VALUE_S 8 #define AR_PHY_65NM_CH0_TXRF3 0x16048 #define AR_PHY_65NM_CH0_TXRF3_CAPDIV2G 0x0000001e #define AR_PHY_65NM_CH0_TXRF3_CAPDIV2G_S 1 #define AR_PHY_65NM_CH0_SYNTH4 0x1608c #define AR_PHY_SYNTH4_LONG_SHIFT_SELECT ((AR_SREV_9462(ah) || AR_SREV_9565(ah)) ? 0x00000001 : 0x00000002) #define AR_PHY_SYNTH4_LONG_SHIFT_SELECT_S ((AR_SREV_9462(ah) || AR_SREV_9565(ah)) ? 0 : 1) #define AR_PHY_65NM_CH0_SYNTH7 0x16098 #define AR_PHY_65NM_CH0_SYNTH12 0x160ac #define AR_PHY_65NM_CH0_BIAS1 0x160c0 #define AR_PHY_65NM_CH0_BIAS2 0x160c4 #define AR_PHY_65NM_CH0_BIAS4 0x160cc #define AR_PHY_65NM_CH0_RXTX2 0x16104 #define AR_PHY_65NM_CH1_RXTX2 0x16504 #define AR_PHY_65NM_CH2_RXTX2 0x16904 #define AR_PHY_65NM_CH0_RXTX4 0x1610c #define AR_PHY_65NM_CH1_RXTX4 0x1650c #define AR_PHY_65NM_CH2_RXTX4 0x1690c #define AR_PHY_65NM_CH0_BB1 0x16140 #define AR_PHY_65NM_CH0_BB2 0x16144 #define AR_PHY_65NM_CH0_BB3 0x16148 #define AR_PHY_65NM_CH1_BB1 0x16540 #define AR_PHY_65NM_CH1_BB2 0x16544 #define AR_PHY_65NM_CH1_BB3 0x16548 #define AR_PHY_65NM_CH2_BB1 0x16940 #define AR_PHY_65NM_CH2_BB2 0x16944 #define AR_PHY_65NM_CH2_BB3 0x16948 #define AR_PHY_65NM_CH0_SYNTH12_VREFMUL3 0x00780000 #define AR_PHY_65NM_CH0_SYNTH12_VREFMUL3_S 19 #define AR_PHY_65NM_CH0_RXTX2_SYNTHON_MASK 0x00000004 #define AR_PHY_65NM_CH0_RXTX2_SYNTHON_MASK_S 2 #define AR_PHY_65NM_CH0_RXTX2_SYNTHOVR_MASK 0x00000008 #define AR_PHY_65NM_CH0_RXTX2_SYNTHOVR_MASK_S 3 #define AR_CH0_TOP (AR_SREV_9300(ah) ? 0x16288 : \ (((AR_SREV_9462(ah) || AR_SREV_9565(ah)) ? 0x1628c : 0x16280))) #define AR_CH0_TOP_XPABIASLVL (AR_SREV_9550(ah) ? 0x3c0 : 0x300) #define AR_CH0_TOP_XPABIASLVL_S (AR_SREV_9550(ah) ? 6 : 8) #define AR_SWITCH_TABLE_COM_ALL (0xffff) #define AR_SWITCH_TABLE_COM_ALL_S (0) #define AR_SWITCH_TABLE_COM_AR9462_ALL (0xffffff) #define AR_SWITCH_TABLE_COM_AR9462_ALL_S (0) #define AR_SWITCH_TABLE_COM_AR9550_ALL (0xffffff) #define AR_SWITCH_TABLE_COM_AR9550_ALL_S (0) #define AR_SWITCH_TABLE_COM_SPDT (0x00f00000) #define AR_SWITCH_TABLE_COM_SPDT_ALL (0x0000fff0) #define AR_SWITCH_TABLE_COM_SPDT_ALL_S (4) #define AR_SWITCH_TABLE_COM2_ALL (0xffffff) #define AR_SWITCH_TABLE_COM2_ALL_S (0) #define AR_SWITCH_TABLE_ALL (0xfff) #define AR_SWITCH_TABLE_ALL_S (0) #define AR_CH0_THERM (AR_SREV_9300(ah) ? 0x16290 :\ ((AR_SREV_9462(ah) || AR_SREV_9565(ah)) ? 0x16294 : 0x1628c)) #define AR_CH0_THERM_XPABIASLVL_MSB 0x3 #define AR_CH0_THERM_XPABIASLVL_MSB_S 0 #define AR_CH0_THERM_XPASHORT2GND 0x4 #define AR_CH0_THERM_XPASHORT2GND_S 2 #define AR_CH0_THERM_LOCAL 0x80000000 #define AR_CH0_THERM_START 0x20000000 #define AR_CH0_THERM_SAR_ADC_OUT 0x0000ff00 #define AR_CH0_THERM_SAR_ADC_OUT_S 8 #define AR_CH0_TOP2 (AR_SREV_9300(ah) ? 0x1628c : \ (AR_SREV_9462(ah) ? 0x16290 : 0x16284)) #define AR_CH0_TOP2_XPABIASLVL (AR_SREV_9561(ah) ? 0x1e00 : 0xf000) #define AR_CH0_TOP2_XPABIASLVL_S 12 #define AR_CH0_XTAL (AR_SREV_9300(ah) ? 0x16294 : \ ((AR_SREV_9462(ah) || AR_SREV_9565(ah)) ? 0x16298 : \ (AR_SREV_9561(ah) ? 0x162c0 : 0x16290))) #define AR_CH0_XTAL_CAPINDAC 0x7f000000 #define AR_CH0_XTAL_CAPINDAC_S 24 #define AR_CH0_XTAL_CAPOUTDAC 0x00fe0000 #define AR_CH0_XTAL_CAPOUTDAC_S 17 #define AR_PHY_PMU1 ((AR_SREV_9462(ah) || AR_SREV_9565(ah)) ? 0x16340 : \ (AR_SREV_9561(ah) ? 0x16cc0 : 0x16c40)) #define AR_PHY_PMU1_PWD 0x1 #define AR_PHY_PMU1_PWD_S 0 #define AR_PHY_PMU2 ((AR_SREV_9462(ah) || AR_SREV_9565(ah)) ? 0x16344 : \ (AR_SREV_9561(ah) ? 0x16cc4 : 0x16c44)) #define AR_PHY_PMU2_PGM 0x00200000 #define AR_PHY_PMU2_PGM_S 21 #define AR_PHY_RX1DB_BIQUAD_LONG_SHIFT 0x00380000 #define AR_PHY_RX1DB_BIQUAD_LONG_SHIFT_S 19 #define AR_PHY_RX6DB_BIQUAD_LONG_SHIFT 0x00c00000 #define AR_PHY_RX6DB_BIQUAD_LONG_SHIFT_S 22 #define AR_PHY_LNAGAIN_LONG_SHIFT 0xe0000000 #define AR_PHY_LNAGAIN_LONG_SHIFT_S 29 #define AR_PHY_MXRGAIN_LONG_SHIFT 0x03000000 #define AR_PHY_MXRGAIN_LONG_SHIFT_S 24 #define AR_PHY_VGAGAIN_LONG_SHIFT 0x1c000000 #define AR_PHY_VGAGAIN_LONG_SHIFT_S 26 #define AR_PHY_SCFIR_GAIN_LONG_SHIFT 0x00000001 #define AR_PHY_SCFIR_GAIN_LONG_SHIFT_S 0 #define AR_PHY_MANRXGAIN_LONG_SHIFT 0x00000002 #define AR_PHY_MANRXGAIN_LONG_SHIFT_S 1 /* * SM Field Definitions */ #define AR_PHY_CL_CAL_ENABLE 0x00000002 #define AR_PHY_PARALLEL_CAL_ENABLE 0x00000001 #define AR_PHY_TPCRG1_PD_CAL_ENABLE 0x00400000 #define AR_PHY_TPCRG1_PD_CAL_ENABLE_S 22 #define AR_PHY_ADDAC_PARACTL_OFF_PWDADC 0x00008000 #define AR_PHY_FCAL20_CAP_STATUS_0 0x01f00000 #define AR_PHY_FCAL20_CAP_STATUS_0_S 20 #define AR_PHY_RFBUS_REQ_EN 0x00000001 /* request for RF bus */ #define AR_PHY_RFBUS_GRANT_EN 0x00000001 /* RF bus granted */ #define AR_PHY_GC_TURBO_MODE 0x00000001 /* set turbo mode bits */ #define AR_PHY_GC_TURBO_SHORT 0x00000002 /* set short symbols to turbo mode setting */ #define AR_PHY_GC_DYN2040_EN 0x00000004 /* enable dyn 20/40 mode */ #define AR_PHY_GC_DYN2040_PRI_ONLY 0x00000008 /* dyn 20/40 - primary only */ #define AR_PHY_GC_DYN2040_PRI_CH 0x00000010 /* dyn 20/40 - primary ch offset (0=+10MHz, 1=-10MHz)*/ #define AR_PHY_GC_DYN2040_PRI_CH_S 4 #define AR_PHY_GC_DYN2040_EXT_CH 0x00000020 /* dyn 20/40 - ext ch spacing (0=20MHz/ 1=25MHz) */ #define AR_PHY_GC_HT_EN 0x00000040 /* ht enable */ #define AR_PHY_GC_SHORT_GI_40 0x00000080 /* allow short GI for HT 40 */ #define AR_PHY_GC_WALSH 0x00000100 /* walsh spatial spreading for 2 chains,2 streams TX */ #define AR_PHY_GC_SINGLE_HT_LTF1 0x00000200 /* single length (4us) 1st HT long training symbol */ #define AR_PHY_GC_GF_DETECT_EN 0x00000400 /* enable Green Field detection. Only affects rx, not tx */ #define AR_PHY_GC_ENABLE_DAC_FIFO 0x00000800 /* fifo between bb and dac */ #define AR_PHY_RX_DELAY_DELAY 0x00003FFF /* delay from wakeup to rx ena */ #define AR_PHY_CALMODE_IQ 0x00000000 #define AR_PHY_CALMODE_ADC_GAIN 0x00000001 #define AR_PHY_CALMODE_ADC_DC_PER 0x00000002 #define AR_PHY_CALMODE_ADC_DC_INIT 0x00000003 #define AR_PHY_SWAP_ALT_CHAIN 0x00000040 #define AR_PHY_MODE_OFDM 0x00000000 #define AR_PHY_MODE_CCK 0x00000001 #define AR_PHY_MODE_DYNAMIC 0x00000004 #define AR_PHY_MODE_DYNAMIC_S 2 #define AR_PHY_MODE_HALF 0x00000020 #define AR_PHY_MODE_QUARTER 0x00000040 #define AR_PHY_MAC_CLK_MODE 0x00000080 #define AR_PHY_MODE_DYN_CCK_DISABLE 0x00000100 #define AR_PHY_MODE_SVD_HALF 0x00000200 #define AR_PHY_ACTIVE_EN 0x00000001 #define AR_PHY_ACTIVE_DIS 0x00000000 #define AR_PHY_FORCE_XPA_CFG 0x000000001 #define AR_PHY_FORCE_XPA_CFG_S 0 #define AR_PHY_XPA_TIMING_CTL_TX_END_XPAB_OFF 0xFF000000 #define AR_PHY_XPA_TIMING_CTL_TX_END_XPAB_OFF_S 24 #define AR_PHY_XPA_TIMING_CTL_TX_END_XPAA_OFF 0x00FF0000 #define AR_PHY_XPA_TIMING_CTL_TX_END_XPAA_OFF_S 16 #define AR_PHY_XPA_TIMING_CTL_FRAME_XPAB_ON 0x0000FF00 #define AR_PHY_XPA_TIMING_CTL_FRAME_XPAB_ON_S 8 #define AR_PHY_XPA_TIMING_CTL_FRAME_XPAA_ON 0x000000FF #define AR_PHY_XPA_TIMING_CTL_FRAME_XPAA_ON_S 0 #define AR_PHY_TX_END_TO_A2_RX_ON 0x00FF0000 #define AR_PHY_TX_END_TO_A2_RX_ON_S 16 #define AR_PHY_TX_END_DATA_START 0x000000FF #define AR_PHY_TX_END_DATA_START_S 0 #define AR_PHY_TX_END_PA_ON 0x0000FF00 #define AR_PHY_TX_END_PA_ON_S 8 #define AR_PHY_TPCRG5_PD_GAIN_OVERLAP 0x0000000F #define AR_PHY_TPCRG5_PD_GAIN_OVERLAP_S 0 #define AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_1 0x000003F0 #define AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_1_S 4 #define AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_2 0x0000FC00 #define AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_2_S 10 #define AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_3 0x003F0000 #define AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_3_S 16 #define AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_4 0x0FC00000 #define AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_4_S 22 #define AR_PHY_TPCRG1_NUM_PD_GAIN 0x0000c000 #define AR_PHY_TPCRG1_NUM_PD_GAIN_S 14 #define AR_PHY_TPCRG1_PD_GAIN_1 0x00030000 #define AR_PHY_TPCRG1_PD_GAIN_1_S 16 #define AR_PHY_TPCRG1_PD_GAIN_2 0x000C0000 #define AR_PHY_TPCRG1_PD_GAIN_2_S 18 #define AR_PHY_TPCRG1_PD_GAIN_3 0x00300000 #define AR_PHY_TPCRG1_PD_GAIN_3_S 20 #define AR_PHY_TPCGR1_FORCED_DAC_GAIN 0x0000003e #define AR_PHY_TPCGR1_FORCED_DAC_GAIN_S 1 #define AR_PHY_TPCGR1_FORCE_DAC_GAIN 0x00000001 #define AR_PHY_TXGAIN_FORCE 0x00000001 #define AR_PHY_TXGAIN_FORCE_S 0 #define AR_PHY_TXGAIN_FORCED_PADVGNRA 0x00003c00 #define AR_PHY_TXGAIN_FORCED_PADVGNRA_S 10 #define AR_PHY_TXGAIN_FORCED_PADVGNRB 0x0003c000 #define AR_PHY_TXGAIN_FORCED_PADVGNRB_S 14 #define AR_PHY_TXGAIN_FORCED_PADVGNRD 0x00c00000 #define AR_PHY_TXGAIN_FORCED_PADVGNRD_S 22 #define AR_PHY_TXGAIN_FORCED_TXMXRGAIN 0x000003c0 #define AR_PHY_TXGAIN_FORCED_TXMXRGAIN_S 6 #define AR_PHY_TXGAIN_FORCED_TXBB1DBGAIN 0x0000000e #define AR_PHY_TXGAIN_FORCED_TXBB1DBGAIN_S 1 #define AR_PHY_POWER_TX_RATE1 0x9934 #define AR_PHY_POWER_TX_RATE2 0x9938 #define AR_PHY_POWER_TX_RATE_MAX 0x993c #define AR_PHY_POWER_TX_RATE_MAX_TPC_ENABLE 0x00000040 #define PHY_AGC_CLR 0x10000000 #define RFSILENT_BB 0x00002000 #define AR_PHY_CHAN_INFO_GAIN_DIFF_PPM_MASK 0xFFF #define AR_PHY_CHAN_INFO_GAIN_DIFF_PPM_SIGNED_BIT 0x800 #define AR_PHY_CHAN_INFO_GAIN_DIFF_UPPER_LIMIT 320 #define AR_PHY_CHAN_INFO_MEMORY_CAPTURE_MASK 0x0001 #define AR_PHY_RX_DELAY_DELAY 0x00003FFF #define AR_PHY_CCK_TX_CTRL_JAPAN 0x00000010 #define AR_PHY_SPECTRAL_SCAN_ENABLE 0x00000001 #define AR_PHY_SPECTRAL_SCAN_ENABLE_S 0 #define AR_PHY_SPECTRAL_SCAN_ACTIVE 0x00000002 #define AR_PHY_SPECTRAL_SCAN_ACTIVE_S 1 #define AR_PHY_SPECTRAL_SCAN_FFT_PERIOD 0x000000F0 #define AR_PHY_SPECTRAL_SCAN_FFT_PERIOD_S 4 #define AR_PHY_SPECTRAL_SCAN_PERIOD 0x0000FF00 #define AR_PHY_SPECTRAL_SCAN_PERIOD_S 8 #define AR_PHY_SPECTRAL_SCAN_COUNT 0x0FFF0000 #define AR_PHY_SPECTRAL_SCAN_COUNT_S 16 #define AR_PHY_SPECTRAL_SCAN_SHORT_REPEAT 0x10000000 #define AR_PHY_SPECTRAL_SCAN_SHORT_REPEAT_S 28 #define AR_PHY_SPECTRAL_SCAN_PRIORITY 0x20000000 #define AR_PHY_SPECTRAL_SCAN_PRIORITY_S 29 #define AR_PHY_SPECTRAL_SCAN_USE_ERR5 0x40000000 #define AR_PHY_SPECTRAL_SCAN_USE_ERR5_S 30 #define AR_PHY_SPECTRAL_SCAN_COMPRESSED_RPT 0x80000000 #define AR_PHY_SPECTRAL_SCAN_COMPRESSED_RPT_S 31 #define AR_PHY_CHANNEL_STATUS_RX_CLEAR 0x00000004 #define AR_PHY_RTT_CTRL_ENA_RADIO_RETENTION 0x00000001 #define AR_PHY_RTT_CTRL_ENA_RADIO_RETENTION_S 0 #define AR_PHY_RTT_CTRL_RESTORE_MASK 0x0000007E #define AR_PHY_RTT_CTRL_RESTORE_MASK_S 1 #define AR_PHY_RTT_CTRL_FORCE_RADIO_RESTORE 0x00000080 #define AR_PHY_RTT_CTRL_FORCE_RADIO_RESTORE_S 7 #define AR_PHY_RTT_SW_RTT_TABLE_ACCESS 0x00000001 #define AR_PHY_RTT_SW_RTT_TABLE_ACCESS_S 0 #define AR_PHY_RTT_SW_RTT_TABLE_WRITE 0x00000002 #define AR_PHY_RTT_SW_RTT_TABLE_WRITE_S 1 #define AR_PHY_RTT_SW_RTT_TABLE_ADDR 0x0000001C #define AR_PHY_RTT_SW_RTT_TABLE_ADDR_S 2 #define AR_PHY_RTT_SW_RTT_TABLE_DATA 0xFFFFFFF0 #define AR_PHY_RTT_SW_RTT_TABLE_DATA_S 4 #define AR_PHY_TX_IQCAL_CONTROL_0_ENABLE_TXIQ_CAL 0x80000000 #define AR_PHY_TX_IQCAL_CONTROL_0_ENABLE_TXIQ_CAL_S 31 #define AR_PHY_TX_IQCAL_CONTROL_1_IQCORR_I_Q_COFF_DELPT 0x01fc0000 #define AR_PHY_TX_IQCAL_CONTROL_1_IQCORR_I_Q_COFF_DELPT_S 18 #define AR_PHY_TX_IQCAL_START_DO_CAL 0x00000001 #define AR_PHY_TX_IQCAL_START_DO_CAL_S 0 #define AR_PHY_TX_IQCAL_STATUS_FAILED 0x00000001 #define AR_PHY_CALIBRATED_GAINS_0 0x3e #define AR_PHY_CALIBRATED_GAINS_0_S 1 #define AR_PHY_TX_IQCAL_CORR_COEFF_00_COEFF_TABLE 0x00003fff #define AR_PHY_TX_IQCAL_CORR_COEFF_00_COEFF_TABLE_S 0 #define AR_PHY_TX_IQCAL_CORR_COEFF_01_COEFF_TABLE 0x0fffc000 #define AR_PHY_TX_IQCAL_CORR_COEFF_01_COEFF_TABLE_S 14 #define AR_PHY_65NM_CH0_RXTX4_THERM_ON 0x10000000 #define AR_PHY_65NM_CH0_RXTX4_THERM_ON_S 28 #define AR_PHY_65NM_CH0_RXTX4_THERM_ON_OVR 0x20000000 #define AR_PHY_65NM_CH0_RXTX4_THERM_ON_OVR_S 29 #define AR_PHY_65NM_RXTX4_XLNA_BIAS 0xC0000000 #define AR_PHY_65NM_RXTX4_XLNA_BIAS_S 30 /* * Channel 1 Register Map */ #define AR_CHAN1_BASE 0xa800 #define AR_PHY_EXT_CCA_1 (AR_CHAN1_BASE + 0x30) #define AR_PHY_TX_PHASE_RAMP_1 (AR_CHAN1_BASE + 0xd0) #define AR_PHY_ADC_GAIN_DC_CORR_1 (AR_CHAN1_BASE + 0xd4) #define AR_PHY_SPUR_REPORT_1 (AR_CHAN1_BASE + 0xa8) #define AR_PHY_CHAN_INFO_TAB_1 (AR_CHAN1_BASE + 0x300) #define AR_PHY_RX_IQCAL_CORR_B1 (AR_CHAN1_BASE + 0xdc) /* * Channel 1 Field Definitions */ #define AR_PHY_CH1_EXT_MINCCA_PWR 0x01FF0000 #define AR_PHY_CH1_EXT_MINCCA_PWR_S 16 /* * AGC 1 Register Map */ #define AR_AGC1_BASE 0xae00 #define AR_PHY_FORCEMAX_GAINS_1 (AR_AGC1_BASE + 0x4) #define AR_PHY_EXT_ATTEN_CTL_1 (AR_AGC1_BASE + 0x18) #define AR_PHY_CCA_1 (AR_AGC1_BASE + 0x1c) #define AR_PHY_CCA_CTRL_1 (AR_AGC1_BASE + 0x20) #define AR_PHY_RSSI_1 (AR_AGC1_BASE + 0x180) #define AR_PHY_SPUR_CCK_REP_1 (AR_AGC1_BASE + 0x184) #define AR_PHY_RX_OCGAIN_2 (AR_AGC1_BASE + 0x200) /* * AGC 1 Field Definitions */ #define AR_PHY_CH1_MINCCA_PWR 0x1FF00000 #define AR_PHY_CH1_MINCCA_PWR_S 20 /* * SM 1 Register Map */ #define AR_SM1_BASE 0xb200 #define AR_PHY_SWITCH_CHAIN_1 (AR_SM1_BASE + 0x84) #define AR_PHY_FCAL_2_1 (AR_SM1_BASE + 0xd0) #define AR_PHY_DFT_TONE_CTL_1 (AR_SM1_BASE + 0xd4) #define AR_PHY_CL_TAB_1 (AR_SM1_BASE + 0x100) #define AR_PHY_CHAN_INFO_GAIN_1 (AR_SM1_BASE + 0x180) #define AR_PHY_TPC_4_B1 (AR_SM1_BASE + 0x204) #define AR_PHY_TPC_5_B1 (AR_SM1_BASE + 0x208) #define AR_PHY_TPC_6_B1 (AR_SM1_BASE + 0x20c) #define AR_PHY_TPC_11_B1 (AR_SM1_BASE + 0x220) #define AR_PHY_PDADC_TAB_1 (AR_SM1_BASE + (AR_SREV_9462_20_OR_LATER(ah) ? \ 0x280 : 0x240)) #define AR_PHY_TPC_19_B1 (AR_SM1_BASE + 0x240) #define AR_PHY_TPC_19_B1_ALPHA_THERM 0xff #define AR_PHY_TPC_19_B1_ALPHA_THERM_S 0 #define AR_PHY_TX_IQCAL_STATUS_B1 (AR_SM1_BASE + 0x48c) #define AR_PHY_TX_IQCAL_CORR_COEFF_B1(_i) (AR_SM1_BASE + 0x450 + ((_i) << 2)) #define AR_PHY_RTT_TABLE_SW_INTF_B(i) (0x384 + ((i) ? \ AR_SM1_BASE : AR_SM_BASE)) #define AR_PHY_RTT_TABLE_SW_INTF_1_B(i) (0x388 + ((i) ? \ AR_SM1_BASE : AR_SM_BASE)) /* * Channel 2 Register Map */ #define AR_CHAN2_BASE 0xb800 #define AR_PHY_EXT_CCA_2 (AR_CHAN2_BASE + 0x30) #define AR_PHY_TX_PHASE_RAMP_2 (AR_CHAN2_BASE + 0xd0) #define AR_PHY_ADC_GAIN_DC_CORR_2 (AR_CHAN2_BASE + 0xd4) #define AR_PHY_SPUR_REPORT_2 (AR_CHAN2_BASE + 0xa8) #define AR_PHY_CHAN_INFO_TAB_2 (AR_CHAN2_BASE + 0x300) #define AR_PHY_RX_IQCAL_CORR_B2 (AR_CHAN2_BASE + 0xdc) /* * Channel 2 Field Definitions */ #define AR_PHY_CH2_EXT_MINCCA_PWR 0x01FF0000 #define AR_PHY_CH2_EXT_MINCCA_PWR_S 16 /* * AGC 2 Register Map */ #define AR_AGC2_BASE 0xbe00 #define AR_PHY_FORCEMAX_GAINS_2 (AR_AGC2_BASE + 0x4) #define AR_PHY_EXT_ATTEN_CTL_2 (AR_AGC2_BASE + 0x18) #define AR_PHY_CCA_2 (AR_AGC2_BASE + 0x1c) #define AR_PHY_CCA_CTRL_2 (AR_AGC2_BASE + 0x20) #define AR_PHY_RSSI_2 (AR_AGC2_BASE + 0x180) /* * AGC 2 Field Definitions */ #define AR_PHY_CH2_MINCCA_PWR 0x1FF00000 #define AR_PHY_CH2_MINCCA_PWR_S 20 /* * SM 2 Register Map */ #define AR_SM2_BASE 0xc200 #define AR_PHY_SWITCH_CHAIN_2 (AR_SM2_BASE + 0x84) #define AR_PHY_FCAL_2_2 (AR_SM2_BASE + 0xd0) #define AR_PHY_DFT_TONE_CTL_2 (AR_SM2_BASE + 0xd4) #define AR_PHY_CL_TAB_2 (AR_SM2_BASE + 0x100) #define AR_PHY_CHAN_INFO_GAIN_2 (AR_SM2_BASE + 0x180) #define AR_PHY_TPC_4_B2 (AR_SM2_BASE + 0x204) #define AR_PHY_TPC_5_B2 (AR_SM2_BASE + 0x208) #define AR_PHY_TPC_6_B2 (AR_SM2_BASE + 0x20c) #define AR_PHY_TPC_11_B2 (AR_SM2_BASE + 0x220) #define AR_PHY_TPC_19_B2 (AR_SM2_BASE + 0x240) #define AR_PHY_TX_IQCAL_STATUS_B2 (AR_SM2_BASE + 0x48c) #define AR_PHY_TX_IQCAL_CORR_COEFF_B2(_i) (AR_SM2_BASE + 0x450 + ((_i) << 2)) #define AR_PHY_TX_IQCAL_STATUS_B2_FAILED 0x00000001 /* * AGC 3 Register Map */ #define AR_AGC3_BASE 0xce00 #define AR_PHY_RSSI_3 (AR_AGC3_BASE + 0x180) /* GLB Registers */ #define AR_GLB_BASE 0x20000 #define AR_GLB_GPIO_CONTROL (AR_GLB_BASE) #define AR_PHY_GLB_CONTROL (AR_GLB_BASE + 0x44) #define AR_GLB_SCRATCH(_ah) (AR_GLB_BASE + \ (AR_SREV_9462_20_OR_LATER(_ah) ? 0x4c : 0x50)) #define AR_GLB_STATUS (AR_GLB_BASE + 0x48) /* * Misc helper defines */ #define AR_PHY_CHAIN_OFFSET (AR_CHAN1_BASE - AR_CHAN_BASE) #define AR_PHY_NEW_ADC_DC_GAIN_CORR(_i) (AR_PHY_ADC_GAIN_DC_CORR_0 + (AR_PHY_CHAIN_OFFSET * (_i))) #define AR_PHY_NEW_ADC_DC_GAIN_CORR_9300_10(_i) (AR_PHY_ADC_GAIN_DC_CORR_0_9300_10 + (AR_PHY_CHAIN_OFFSET * (_i))) #define AR_PHY_SWITCH_CHAIN(_i) (AR_PHY_SWITCH_CHAIN_0 + (AR_PHY_CHAIN_OFFSET * (_i))) #define AR_PHY_EXT_ATTEN_CTL(_i) (AR_PHY_EXT_ATTEN_CTL_0 + (AR_PHY_CHAIN_OFFSET * (_i))) #define AR_PHY_RXGAIN(_i) (AR_PHY_FORCEMAX_GAINS_0 + (AR_PHY_CHAIN_OFFSET * (_i))) #define AR_PHY_TPCRG5(_i) (AR_PHY_TPC_5_B0 + (AR_PHY_CHAIN_OFFSET * (_i))) #define AR_PHY_PDADC_TAB(_i) (AR_PHY_PDADC_TAB_0 + (AR_PHY_CHAIN_OFFSET * (_i))) #define AR_PHY_CAL_MEAS_0(_i) (AR_PHY_IQ_ADC_MEAS_0_B0 + (AR_PHY_CHAIN_OFFSET * (_i))) #define AR_PHY_CAL_MEAS_1(_i) (AR_PHY_IQ_ADC_MEAS_1_B0 + (AR_PHY_CHAIN_OFFSET * (_i))) #define AR_PHY_CAL_MEAS_2(_i) (AR_PHY_IQ_ADC_MEAS_2_B0 + (AR_PHY_CHAIN_OFFSET * (_i))) #define AR_PHY_CAL_MEAS_3(_i) (AR_PHY_IQ_ADC_MEAS_3_B0 + (AR_PHY_CHAIN_OFFSET * (_i))) #define AR_PHY_CAL_MEAS_0_9300_10(_i) (AR_PHY_IQ_ADC_MEAS_0_B0_9300_10 + (AR_PHY_CHAIN_OFFSET * (_i))) #define AR_PHY_CAL_MEAS_1_9300_10(_i) (AR_PHY_IQ_ADC_MEAS_1_B0_9300_10 + (AR_PHY_CHAIN_OFFSET * (_i))) #define AR_PHY_CAL_MEAS_2_9300_10(_i) (AR_PHY_IQ_ADC_MEAS_2_B0_9300_10 + (AR_PHY_CHAIN_OFFSET * (_i))) #define AR_PHY_CAL_MEAS_3_9300_10(_i) (AR_PHY_IQ_ADC_MEAS_3_B0_9300_10 + (AR_PHY_CHAIN_OFFSET * (_i))) #define AR_PHY_WATCHDOG_NON_IDLE_ENABLE 0x00000001 #define AR_PHY_WATCHDOG_IDLE_ENABLE 0x00000002 #define AR_PHY_WATCHDOG_IDLE_MASK 0xFFFF0000 #define AR_PHY_WATCHDOG_NON_IDLE_MASK 0x0000FFFC #define AR_PHY_WATCHDOG_RST_ENABLE 0x00000002 #define AR_PHY_WATCHDOG_IRQ_ENABLE 0x00000004 #define AR_PHY_WATCHDOG_CNTL2_MASK 0xFFFFFFF9 #define AR_PHY_WATCHDOG_INFO 0x00000007 #define AR_PHY_WATCHDOG_INFO_S 0 #define AR_PHY_WATCHDOG_DET_HANG 0x00000008 #define AR_PHY_WATCHDOG_DET_HANG_S 3 #define AR_PHY_WATCHDOG_RADAR_SM 0x000000F0 #define AR_PHY_WATCHDOG_RADAR_SM_S 4 #define AR_PHY_WATCHDOG_RX_OFDM_SM 0x00000F00 #define AR_PHY_WATCHDOG_RX_OFDM_SM_S 8 #define AR_PHY_WATCHDOG_RX_CCK_SM 0x0000F000 #define AR_PHY_WATCHDOG_RX_CCK_SM_S 12 #define AR_PHY_WATCHDOG_TX_OFDM_SM 0x000F0000 #define AR_PHY_WATCHDOG_TX_OFDM_SM_S 16 #define AR_PHY_WATCHDOG_TX_CCK_SM 0x00F00000 #define AR_PHY_WATCHDOG_TX_CCK_SM_S 20 #define AR_PHY_WATCHDOG_AGC_SM 0x0F000000 #define AR_PHY_WATCHDOG_AGC_SM_S 24 #define AR_PHY_WATCHDOG_SRCH_SM 0xF0000000 #define AR_PHY_WATCHDOG_SRCH_SM_S 28 #define AR_PHY_WATCHDOG_STATUS_CLR 0x00000008 /* * PAPRD registers */ #define AR_PHY_XPA_TIMING_CTL (AR_SM_BASE + 0x64) #define AR_PHY_PAPRD_AM2AM (AR_CHAN_BASE + 0xe4) #define AR_PHY_PAPRD_AM2AM_MASK 0x01ffffff #define AR_PHY_PAPRD_AM2AM_MASK_S 0 #define AR_PHY_PAPRD_AM2PM (AR_CHAN_BASE + 0xe8) #define AR_PHY_PAPRD_AM2PM_MASK 0x01ffffff #define AR_PHY_PAPRD_AM2PM_MASK_S 0 #define AR_PHY_PAPRD_HT40 (AR_CHAN_BASE + 0xec) #define AR_PHY_PAPRD_HT40_MASK 0x01ffffff #define AR_PHY_PAPRD_HT40_MASK_S 0 #define AR_PHY_PAPRD_CTRL0_B0 (AR_CHAN_BASE + 0xf0) #define AR_PHY_PAPRD_CTRL0_B1 (AR_CHAN1_BASE + 0xf0) #define AR_PHY_PAPRD_CTRL0_B2 (AR_CHAN2_BASE + 0xf0) #define AR_PHY_PAPRD_CTRL0_PAPRD_ENABLE 0x00000001 #define AR_PHY_PAPRD_CTRL0_PAPRD_ENABLE_S 0 #define AR_PHY_PAPRD_CTRL0_USE_SINGLE_TABLE_MASK 0x00000002 #define AR_PHY_PAPRD_CTRL0_USE_SINGLE_TABLE_MASK_S 1 #define AR_PHY_PAPRD_CTRL0_PAPRD_MAG_THRSH 0xf8000000 #define AR_PHY_PAPRD_CTRL0_PAPRD_MAG_THRSH_S 27 #define AR_PHY_PAPRD_CTRL1_B0 (AR_CHAN_BASE + 0xf4) #define AR_PHY_PAPRD_CTRL1_B1 (AR_CHAN1_BASE + 0xf4) #define AR_PHY_PAPRD_CTRL1_B2 (AR_CHAN2_BASE + 0xf4) #define AR_PHY_PAPRD_CTRL1_ADAPTIVE_SCALING_ENA 0x00000001 #define AR_PHY_PAPRD_CTRL1_ADAPTIVE_SCALING_ENA_S 0 #define AR_PHY_PAPRD_CTRL1_ADAPTIVE_AM2AM_ENABLE 0x00000002 #define AR_PHY_PAPRD_CTRL1_ADAPTIVE_AM2AM_ENABLE_S 1 #define AR_PHY_PAPRD_CTRL1_ADAPTIVE_AM2PM_ENABLE 0x00000004 #define AR_PHY_PAPRD_CTRL1_ADAPTIVE_AM2PM_ENABLE_S 2 #define AR_PHY_PAPRD_CTRL1_PAPRD_POWER_AT_AM2AM_CAL 0x000001f8 #define AR_PHY_PAPRD_CTRL1_PAPRD_POWER_AT_AM2AM_CAL_S 3 #define AR_PHY_PAPRD_CTRL1_PA_GAIN_SCALE_FACT_MASK 0x0001fe00 #define AR_PHY_PAPRD_CTRL1_PA_GAIN_SCALE_FACT_MASK_S 9 #define AR_PHY_PAPRD_CTRL1_PAPRD_MAG_SCALE_FACT 0x0ffe0000 #define AR_PHY_PAPRD_CTRL1_PAPRD_MAG_SCALE_FACT_S 17 #define AR_PHY_PAPRD_TRAINER_CNTL1 (AR_SM_BASE + (AR_SREV_9485(ah) ? 0x580 : 0x490)) #define AR_PHY_PAPRD_TRAINER_CNTL1_CF_CF_PAPRD_TRAIN_ENABLE 0x00000001 #define AR_PHY_PAPRD_TRAINER_CNTL1_CF_CF_PAPRD_TRAIN_ENABLE_S 0 #define AR_PHY_PAPRD_TRAINER_CNTL1_CF_PAPRD_AGC2_SETTLING 0x0000007e #define AR_PHY_PAPRD_TRAINER_CNTL1_CF_PAPRD_AGC2_SETTLING_S 1 #define AR_PHY_PAPRD_TRAINER_CNTL1_CF_PAPRD_IQCORR_ENABLE 0x00000100 #define AR_PHY_PAPRD_TRAINER_CNTL1_CF_PAPRD_IQCORR_ENABLE_S 8 #define AR_PHY_PAPRD_TRAINER_CNTL1_CF_PAPRD_RX_BB_GAIN_FORCE 0x00000200 #define AR_PHY_PAPRD_TRAINER_CNTL1_CF_PAPRD_RX_BB_GAIN_FORCE_S 9 #define AR_PHY_PAPRD_TRAINER_CNTL1_CF_PAPRD_TX_GAIN_FORCE 0x00000400 #define AR_PHY_PAPRD_TRAINER_CNTL1_CF_PAPRD_TX_GAIN_FORCE_S 10 #define AR_PHY_PAPRD_TRAINER_CNTL1_CF_PAPRD_LB_ENABLE 0x00000800 #define AR_PHY_PAPRD_TRAINER_CNTL1_CF_PAPRD_LB_ENABLE_S 11 #define AR_PHY_PAPRD_TRAINER_CNTL1_CF_PAPRD_LB_SKIP 0x0003f000 #define AR_PHY_PAPRD_TRAINER_CNTL1_CF_PAPRD_LB_SKIP_S 12 #define AR_PHY_PAPRD_TRAINER_CNTL2 (AR_SM_BASE + (AR_SREV_9485(ah) ? 0x584 : 0x494)) #define AR_PHY_PAPRD_TRAINER_CNTL2_CF_PAPRD_INIT_RX_BB_GAIN 0xFFFFFFFF #define AR_PHY_PAPRD_TRAINER_CNTL2_CF_PAPRD_INIT_RX_BB_GAIN_S 0 #define AR_PHY_PAPRD_TRAINER_CNTL3 (AR_SM_BASE + (AR_SREV_9485(ah) ? 0x588 : 0x498)) #define AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_ADC_DESIRED_SIZE 0x0000003f #define AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_ADC_DESIRED_SIZE_S 0 #define AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_QUICK_DROP 0x00000fc0 #define AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_QUICK_DROP_S 6 #define AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_MIN_LOOPBACK_DEL 0x0001f000 #define AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_MIN_LOOPBACK_DEL_S 12 #define AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_NUM_CORR_STAGES 0x000e0000 #define AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_NUM_CORR_STAGES_S 17 #define AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_COARSE_CORR_LEN 0x00f00000 #define AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_COARSE_CORR_LEN_S 20 #define AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_FINE_CORR_LEN 0x0f000000 #define AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_FINE_CORR_LEN_S 24 #define AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_BBTXMIX_DISABLE 0x20000000 #define AR_PHY_PAPRD_TRAINER_CNTL3_CF_PAPRD_BBTXMIX_DISABLE_S 29 #define AR_PHY_PAPRD_TRAINER_CNTL4 (AR_SM_BASE + (AR_SREV_9485(ah) ? 0x58c : 0x49c)) #define AR_PHY_PAPRD_TRAINER_CNTL4_CF_PAPRD_NUM_TRAIN_SAMPLES 0x03ff0000 #define AR_PHY_PAPRD_TRAINER_CNTL4_CF_PAPRD_NUM_TRAIN_SAMPLES_S 16 #define AR_PHY_PAPRD_TRAINER_CNTL4_CF_PAPRD_SAFETY_DELTA 0x0000f000 #define AR_PHY_PAPRD_TRAINER_CNTL4_CF_PAPRD_SAFETY_DELTA_S 12 #define AR_PHY_PAPRD_TRAINER_CNTL4_CF_PAPRD_MIN_CORR 0x00000fff #define AR_PHY_PAPRD_TRAINER_CNTL4_CF_PAPRD_MIN_CORR_S 0 #define AR_PHY_PAPRD_PRE_POST_SCALE_0_B0 (AR_CHAN_BASE + 0x100) #define AR_PHY_PAPRD_PRE_POST_SCALE_1_B0 (AR_CHAN_BASE + 0x104) #define AR_PHY_PAPRD_PRE_POST_SCALE_2_B0 (AR_CHAN_BASE + 0x108) #define AR_PHY_PAPRD_PRE_POST_SCALE_3_B0 (AR_CHAN_BASE + 0x10c) #define AR_PHY_PAPRD_PRE_POST_SCALE_4_B0 (AR_CHAN_BASE + 0x110) #define AR_PHY_PAPRD_PRE_POST_SCALE_5_B0 (AR_CHAN_BASE + 0x114) #define AR_PHY_PAPRD_PRE_POST_SCALE_6_B0 (AR_CHAN_BASE + 0x118) #define AR_PHY_PAPRD_PRE_POST_SCALE_7_B0 (AR_CHAN_BASE + 0x11c) #define AR_PHY_PAPRD_PRE_POST_SCALING 0x3FFFF #define AR_PHY_PAPRD_PRE_POST_SCALING_S 0 #define AR_PHY_PAPRD_TRAINER_STAT1 (AR_SM_BASE + (AR_SREV_9485(ah) ? 0x590 : 0x4a0)) #define AR_PHY_PAPRD_TRAINER_STAT1_PAPRD_TRAIN_DONE 0x00000001 #define AR_PHY_PAPRD_TRAINER_STAT1_PAPRD_TRAIN_DONE_S 0 #define AR_PHY_PAPRD_TRAINER_STAT1_PAPRD_TRAIN_INCOMPLETE 0x00000002 #define AR_PHY_PAPRD_TRAINER_STAT1_PAPRD_TRAIN_INCOMPLETE_S 1 #define AR_PHY_PAPRD_TRAINER_STAT1_PAPRD_CORR_ERR 0x00000004 #define AR_PHY_PAPRD_TRAINER_STAT1_PAPRD_CORR_ERR_S 2 #define AR_PHY_PAPRD_TRAINER_STAT1_PAPRD_TRAIN_ACTIVE 0x00000008 #define AR_PHY_PAPRD_TRAINER_STAT1_PAPRD_TRAIN_ACTIVE_S 3 #define AR_PHY_PAPRD_TRAINER_STAT1_PAPRD_RX_GAIN_IDX 0x000001f0 #define AR_PHY_PAPRD_TRAINER_STAT1_PAPRD_RX_GAIN_IDX_S 4 #define AR_PHY_PAPRD_TRAINER_STAT1_PAPRD_AGC2_PWR 0x0001fe00 #define AR_PHY_PAPRD_TRAINER_STAT1_PAPRD_AGC2_PWR_S 9 #define AR_PHY_PAPRD_TRAINER_STAT2 (AR_SM_BASE + (AR_SREV_9485(ah) ? 0x594 : 0x4a4)) #define AR_PHY_PAPRD_TRAINER_STAT2_PAPRD_FINE_VAL 0x0000ffff #define AR_PHY_PAPRD_TRAINER_STAT2_PAPRD_FINE_VAL_S 0 #define AR_PHY_PAPRD_TRAINER_STAT2_PAPRD_COARSE_IDX 0x001f0000 #define AR_PHY_PAPRD_TRAINER_STAT2_PAPRD_COARSE_IDX_S 16 #define AR_PHY_PAPRD_TRAINER_STAT2_PAPRD_FINE_IDX 0x00600000 #define AR_PHY_PAPRD_TRAINER_STAT2_PAPRD_FINE_IDX_S 21 #define AR_PHY_PAPRD_TRAINER_STAT3 (AR_SM_BASE + (AR_SREV_9485(ah) ? 0x598 : 0x4a8)) #define AR_PHY_PAPRD_TRAINER_STAT3_PAPRD_TRAIN_SAMPLES_CNT 0x000fffff #define AR_PHY_PAPRD_TRAINER_STAT3_PAPRD_TRAIN_SAMPLES_CNT_S 0 #define AR_PHY_PAPRD_MEM_TAB_B0 (AR_CHAN_BASE + 0x120) #define AR_PHY_PAPRD_MEM_TAB_B1 (AR_CHAN1_BASE + 0x120) #define AR_PHY_PAPRD_MEM_TAB_B2 (AR_CHAN2_BASE + 0x120) #define AR_PHY_PA_GAIN123_B0 (AR_CHAN_BASE + 0xf8) #define AR_PHY_PA_GAIN123_B1 (AR_CHAN1_BASE + 0xf8) #define AR_PHY_PA_GAIN123_B2 (AR_CHAN2_BASE + 0xf8) #define AR_PHY_PA_GAIN123_PA_GAIN1 0x3FF #define AR_PHY_PA_GAIN123_PA_GAIN1_S 0 #define AR_PHY_POWERTX_RATE5 (AR_SM_BASE + 0x1d0) #define AR_PHY_POWERTX_RATE5_POWERTXHT20_0 0x3F #define AR_PHY_POWERTX_RATE5_POWERTXHT20_0_S 0 #define AR_PHY_POWERTX_RATE6 (AR_SM_BASE + 0x1d4) #define AR_PHY_POWERTX_RATE6_POWERTXHT20_5 0x3F00 #define AR_PHY_POWERTX_RATE6_POWERTXHT20_5_S 8 #define AR_PHY_POWERTX_RATE8 (AR_SM_BASE + 0x1dc) #define AR_PHY_POWERTX_RATE8_POWERTXHT40_5 0x3F00 #define AR_PHY_POWERTX_RATE8_POWERTXHT40_5_S 8 #define AR_PHY_CL_TAB_CL_GAIN_MOD 0x1f #define AR_PHY_CL_TAB_CL_GAIN_MOD_S 0 #define AR_BTCOEX_WL_LNADIV 0x1a64 #define AR_BTCOEX_WL_LNADIV_PREDICTED_PERIOD 0x00003FFF #define AR_BTCOEX_WL_LNADIV_PREDICTED_PERIOD_S 0 #define AR_BTCOEX_WL_LNADIV_DPDT_IGNORE_PRIORITY 0x00004000 #define AR_BTCOEX_WL_LNADIV_DPDT_IGNORE_PRIORITY_S 14 #define AR_BTCOEX_WL_LNADIV_FORCE_ON 0x00008000 #define AR_BTCOEX_WL_LNADIV_FORCE_ON_S 15 #define AR_BTCOEX_WL_LNADIV_MODE_OPTION 0x00030000 #define AR_BTCOEX_WL_LNADIV_MODE_OPTION_S 16 #define AR_BTCOEX_WL_LNADIV_MODE 0x007c0000 #define AR_BTCOEX_WL_LNADIV_MODE_S 18 #define AR_BTCOEX_WL_LNADIV_ALLOWED_TX_ANTDIV_WL_TX_REQ 0x00800000 #define AR_BTCOEX_WL_LNADIV_ALLOWED_TX_ANTDIV_WL_TX_REQ_S 23 #define AR_BTCOEX_WL_LNADIV_DISABLE_TX_ANTDIV_ENABLE 0x01000000 #define AR_BTCOEX_WL_LNADIV_DISABLE_TX_ANTDIV_ENABLE_S 24 #define AR_BTCOEX_WL_LNADIV_CONTINUOUS_BT_ACTIVE_PROTECT 0x02000000 #define AR_BTCOEX_WL_LNADIV_CONTINUOUS_BT_ACTIVE_PROTECT_S 25 #define AR_BTCOEX_WL_LNADIV_BT_INACTIVE_THRESHOLD 0xFC000000 #define AR_BTCOEX_WL_LNADIV_BT_INACTIVE_THRESHOLD_S 26 /* Manual Peak detector calibration */ #define AR_PHY_65NM_BASE 0x16000 #define AR_PHY_65NM_RXRF_GAINSTAGES(i) (AR_PHY_65NM_BASE + \ (i * 0x400) + 0x8) #define AR_PHY_65NM_RXRF_GAINSTAGES_RX_OVERRIDE 0x80000000 #define AR_PHY_65NM_RXRF_GAINSTAGES_RX_OVERRIDE_S 31 #define AR_PHY_65NM_RXRF_GAINSTAGES_LNAON_CALDC 0x00000002 #define AR_PHY_65NM_RXRF_GAINSTAGES_LNAON_CALDC_S 1 #define AR_PHY_65NM_RXRF_GAINSTAGES_LNA2G_GAIN_OVR 0x70000000 #define AR_PHY_65NM_RXRF_GAINSTAGES_LNA2G_GAIN_OVR_S 28 #define AR_PHY_65NM_RXRF_GAINSTAGES_LNA5G_GAIN_OVR 0x03800000 #define AR_PHY_65NM_RXRF_GAINSTAGES_LNA5G_GAIN_OVR_S 23 #define AR_PHY_65NM_RXTX2(i) (AR_PHY_65NM_BASE + \ (i * 0x400) + 0x104) #define AR_PHY_65NM_RXTX2_RXON_OVR 0x00001000 #define AR_PHY_65NM_RXTX2_RXON_OVR_S 12 #define AR_PHY_65NM_RXTX2_RXON 0x00000800 #define AR_PHY_65NM_RXTX2_RXON_S 11 #define AR_PHY_65NM_RXRF_AGC(i) (AR_PHY_65NM_BASE + \ (i * 0x400) + 0xc) #define AR_PHY_65NM_RXRF_AGC_AGC_OVERRIDE 0x80000000 #define AR_PHY_65NM_RXRF_AGC_AGC_OVERRIDE_S 31 #define AR_PHY_65NM_RXRF_AGC_AGC_ON_OVR 0x40000000 #define AR_PHY_65NM_RXRF_AGC_AGC_ON_OVR_S 30 #define AR_PHY_65NM_RXRF_AGC_AGC_CAL_OVR 0x20000000 #define AR_PHY_65NM_RXRF_AGC_AGC_CAL_OVR_S 29 #define AR_PHY_65NM_RXRF_AGC_AGC2G_DBDAC_OVR 0x1E000000 #define AR_PHY_65NM_RXRF_AGC_AGC2G_DBDAC_OVR_S 25 #define AR_PHY_65NM_RXRF_AGC_AGC5G_DBDAC_OVR 0x00078000 #define AR_PHY_65NM_RXRF_AGC_AGC5G_DBDAC_OVR_S 15 #define AR_PHY_65NM_RXRF_AGC_AGC2G_CALDAC_OVR 0x01F80000 #define AR_PHY_65NM_RXRF_AGC_AGC2G_CALDAC_OVR_S 19 #define AR_PHY_65NM_RXRF_AGC_AGC5G_CALDAC_OVR 0x00007e00 #define AR_PHY_65NM_RXRF_AGC_AGC5G_CALDAC_OVR_S 9 #define AR_PHY_65NM_RXRF_AGC_AGC_OUT 0x00000004 #define AR_PHY_65NM_RXRF_AGC_AGC_OUT_S 2 #define AR9300_DFS_FIRPWR -28 #endif /* AR9003_PHY_H */
{ "language": "C" }
/* * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * Authors: * Ravindra (rkumar@novell.com) * Sebastien Pouliot <sebastien@ximian.com> * * Copyright (C) 2004, 2007 Novell, Inc (http://www.novell.com) */ #ifndef __SOLIDBRUSH_H__ #define __SOLIDBRUSH_H__ #include "brush.h" GpStatus WINGDIPAPI GdipCreateSolidFill (ARGB color, GpSolidFill **brush); GpStatus WINGDIPAPI GdipGetSolidFillColor (GpSolidFill *brush, ARGB *color); GpStatus WINGDIPAPI GdipSetSolidFillColor (GpSolidFill *brush, ARGB color); #endif
{ "language": "C" }
/* * QDict Module * * Copyright (C) 2009 Red Hat Inc. * * Authors: * Luiz Capitulino <lcapitulino@redhat.com> * * This work is licensed under the terms of the GNU LGPL, version 2.1 or later. * See the COPYING.LIB file in the top-level directory. */ #include "qapi/qmp/qint.h" #include "qapi/qmp/qfloat.h" #include "qapi/qmp/qdict.h" #include "qapi/qmp/qbool.h" #include "qapi/qmp/qstring.h" #include "qapi/qmp/qobject.h" #include "qemu/queue.h" #include "qemu-common.h" static void qdict_destroy_obj(QObject *obj); static const QType qdict_type = { QTYPE_QDICT, qdict_destroy_obj, }; /** * qdict_new(): Create a new QDict * * Return strong reference. */ QDict *qdict_new(void) { QDict *qdict; qdict = g_malloc0(sizeof(*qdict)); QOBJECT_INIT(qdict, &qdict_type); return qdict; } /** * qobject_to_qdict(): Convert a QObject into a QDict */ QDict *qobject_to_qdict(const QObject *obj) { if (qobject_type(obj) != QTYPE_QDICT) return NULL; return container_of(obj, QDict, base); } /** * tdb_hash(): based on the hash agorithm from gdbm, via tdb * (from module-init-tools) */ static unsigned int tdb_hash(const char *name) { unsigned value; /* Used to compute the hash value. */ unsigned i; /* Used to cycle through random values. */ /* Set the initial value from the key size. */ for (value = 0x238F13AF * strlen(name), i=0; name[i]; i++) value = (value + (((const unsigned char *)name)[i] << (i*5 % 24))); return (1103515243 * value + 12345); } /** * alloc_entry(): allocate a new QDictEntry */ static QDictEntry *alloc_entry(const char *key, QObject *value) { QDictEntry *entry; entry = g_malloc0(sizeof(*entry)); entry->key = g_strdup(key); entry->value = value; return entry; } /** * qdict_entry_value(): Return qdict entry value * * Return weak reference. */ QObject *qdict_entry_value(const QDictEntry *entry) { return entry->value; } /** * qdict_entry_key(): Return qdict entry key * * Return a *pointer* to the string, it has to be duplicated before being * stored. */ const char *qdict_entry_key(const QDictEntry *entry) { return entry->key; } /** * qdict_find(): List lookup function */ static QDictEntry *qdict_find(const QDict *qdict, const char *key, unsigned int bucket) { QDictEntry *entry; QLIST_FOREACH(entry, &qdict->table[bucket], next) if (!strcmp(entry->key, key)) return entry; return NULL; } /** * qdict_put_obj(): Put a new QObject into the dictionary * * Insert the pair 'key:value' into 'qdict', if 'key' already exists * its 'value' will be replaced. * * This is done by freeing the reference to the stored QObject and * storing the new one in the same entry. * * NOTE: ownership of 'value' is transferred to the QDict */ void qdict_put_obj(QDict *qdict, const char *key, QObject *value) { unsigned int bucket; QDictEntry *entry; bucket = tdb_hash(key) % QDICT_BUCKET_MAX; entry = qdict_find(qdict, key, bucket); if (entry) { /* replace key's value */ qobject_decref(entry->value); entry->value = value; } else { /* allocate a new entry */ entry = alloc_entry(key, value); QLIST_INSERT_HEAD(&qdict->table[bucket], entry, next); qdict->size++; } } /** * qdict_get(): Lookup for a given 'key' * * Return a weak reference to the QObject associated with 'key' if * 'key' is present in the dictionary, NULL otherwise. */ QObject *qdict_get(const QDict *qdict, const char *key) { QDictEntry *entry; entry = qdict_find(qdict, key, tdb_hash(key) % QDICT_BUCKET_MAX); return (entry == NULL ? NULL : entry->value); } /** * qdict_haskey(): Check if 'key' exists * * Return 1 if 'key' exists in the dict, 0 otherwise */ int qdict_haskey(const QDict *qdict, const char *key) { unsigned int bucket = tdb_hash(key) % QDICT_BUCKET_MAX; return (qdict_find(qdict, key, bucket) == NULL ? 0 : 1); } /** * qdict_size(): Return the size of the dictionary */ size_t qdict_size(const QDict *qdict) { return qdict->size; } /** * qdict_get_obj(): Get a QObject of a specific type */ static QObject *qdict_get_obj(const QDict *qdict, const char *key, qtype_code type) { QObject *obj; obj = qdict_get(qdict, key); assert(obj != NULL); assert(qobject_type(obj) == type); return obj; } /** * qdict_get_double(): Get an number mapped by 'key' * * This function assumes that 'key' exists and it stores a * QFloat or QInt object. * * Return number mapped by 'key'. */ double qdict_get_double(const QDict *qdict, const char *key) { QObject *obj = qdict_get(qdict, key); assert(obj); switch (qobject_type(obj)) { case QTYPE_QFLOAT: return qfloat_get_double(qobject_to_qfloat(obj)); case QTYPE_QINT: return (double)qint_get_int(qobject_to_qint(obj)); default: abort(); } } /** * qdict_get_int(): Get an integer mapped by 'key' * * This function assumes that 'key' exists and it stores a * QInt object. * * Return integer mapped by 'key'. */ int64_t qdict_get_int(const QDict *qdict, const char *key) { QObject *obj = qdict_get_obj(qdict, key, QTYPE_QINT); return qint_get_int(qobject_to_qint(obj)); } /** * qdict_get_bool(): Get a bool mapped by 'key' * * This function assumes that 'key' exists and it stores a * QBool object. * * Return bool mapped by 'key'. */ int qdict_get_bool(const QDict *qdict, const char *key) { QObject *obj = qdict_get_obj(qdict, key, QTYPE_QBOOL); return qbool_get_int(qobject_to_qbool(obj)); } /** * qdict_get_qlist(): Get the QList mapped by 'key' * * This function assumes that 'key' exists and it stores a * QList object. * * Return QList mapped by 'key'. */ QList *qdict_get_qlist(const QDict *qdict, const char *key) { return qobject_to_qlist(qdict_get_obj(qdict, key, QTYPE_QLIST)); } /** * qdict_get_qdict(): Get the QDict mapped by 'key' * * This function assumes that 'key' exists and it stores a * QDict object. * * Return QDict mapped by 'key'. */ QDict *qdict_get_qdict(const QDict *qdict, const char *key) { return qobject_to_qdict(qdict_get_obj(qdict, key, QTYPE_QDICT)); } /** * qdict_get_str(): Get a pointer to the stored string mapped * by 'key' * * This function assumes that 'key' exists and it stores a * QString object. * * Return pointer to the string mapped by 'key'. */ const char *qdict_get_str(const QDict *qdict, const char *key) { QObject *obj = qdict_get_obj(qdict, key, QTYPE_QSTRING); return qstring_get_str(qobject_to_qstring(obj)); } /** * qdict_get_try_int(): Try to get integer mapped by 'key' * * Return integer mapped by 'key', if it is not present in * the dictionary or if the stored object is not of QInt type * 'def_value' will be returned. */ int64_t qdict_get_try_int(const QDict *qdict, const char *key, int64_t def_value) { QObject *obj; obj = qdict_get(qdict, key); if (!obj || qobject_type(obj) != QTYPE_QINT) return def_value; return qint_get_int(qobject_to_qint(obj)); } /** * qdict_get_try_bool(): Try to get a bool mapped by 'key' * * Return bool mapped by 'key', if it is not present in the * dictionary or if the stored object is not of QBool type * 'def_value' will be returned. */ int qdict_get_try_bool(const QDict *qdict, const char *key, int def_value) { QObject *obj; obj = qdict_get(qdict, key); if (!obj || qobject_type(obj) != QTYPE_QBOOL) return def_value; return qbool_get_int(qobject_to_qbool(obj)); } /** * qdict_get_try_str(): Try to get a pointer to the stored string * mapped by 'key' * * Return a pointer to the string mapped by 'key', if it is not present * in the dictionary or if the stored object is not of QString type * NULL will be returned. */ const char *qdict_get_try_str(const QDict *qdict, const char *key) { QObject *obj; obj = qdict_get(qdict, key); if (!obj || qobject_type(obj) != QTYPE_QSTRING) return NULL; return qstring_get_str(qobject_to_qstring(obj)); } /** * qdict_iter(): Iterate over all the dictionary's stored values. * * This function allows the user to provide an iterator, which will be * called for each stored value in the dictionary. */ void qdict_iter(const QDict *qdict, void (*iter)(const char *key, QObject *obj, void *opaque), void *opaque) { int i; QDictEntry *entry; for (i = 0; i < QDICT_BUCKET_MAX; i++) { QLIST_FOREACH(entry, &qdict->table[i], next) iter(entry->key, entry->value, opaque); } } static QDictEntry *qdict_next_entry(const QDict *qdict, int first_bucket) { int i; for (i = first_bucket; i < QDICT_BUCKET_MAX; i++) { if (!QLIST_EMPTY(&qdict->table[i])) { return QLIST_FIRST(&qdict->table[i]); } } return NULL; } /** * qdict_first(): Return first qdict entry for iteration. */ const QDictEntry *qdict_first(const QDict *qdict) { return qdict_next_entry(qdict, 0); } /** * qdict_next(): Return next qdict entry in an iteration. */ const QDictEntry *qdict_next(const QDict *qdict, const QDictEntry *entry) { QDictEntry *ret; ret = QLIST_NEXT(entry, next); if (!ret) { unsigned int bucket = tdb_hash(entry->key) % QDICT_BUCKET_MAX; ret = qdict_next_entry(qdict, bucket + 1); } return ret; } /** * qdict_clone_shallow(): Clones a given QDict. Its entries are not copied, but * another reference is added. */ QDict *qdict_clone_shallow(const QDict *src) { QDict *dest; QDictEntry *entry; int i; dest = qdict_new(); for (i = 0; i < QDICT_BUCKET_MAX; i++) { QLIST_FOREACH(entry, &src->table[i], next) { qobject_incref(entry->value); qdict_put_obj(dest, entry->key, entry->value); } } return dest; } /** * qentry_destroy(): Free all the memory allocated by a QDictEntry */ static void qentry_destroy(QDictEntry *e) { assert(e != NULL); assert(e->key != NULL); assert(e->value != NULL); qobject_decref(e->value); g_free(e->key); g_free(e); } /** * qdict_del(): Delete a 'key:value' pair from the dictionary * * This will destroy all data allocated by this entry. */ void qdict_del(QDict *qdict, const char *key) { QDictEntry *entry; entry = qdict_find(qdict, key, tdb_hash(key) % QDICT_BUCKET_MAX); if (entry) { QLIST_REMOVE(entry, next); qentry_destroy(entry); qdict->size--; } } /** * qdict_destroy_obj(): Free all the memory allocated by a QDict */ static void qdict_destroy_obj(QObject *obj) { int i; QDict *qdict; assert(obj != NULL); qdict = qobject_to_qdict(obj); for (i = 0; i < QDICT_BUCKET_MAX; i++) { QDictEntry *entry = QLIST_FIRST(&qdict->table[i]); while (entry) { QDictEntry *tmp = QLIST_NEXT(entry, next); QLIST_REMOVE(entry, next); qentry_destroy(entry); entry = tmp; } } g_free(qdict); } static void qdict_flatten_qdict(QDict *qdict, QDict *target, const char *prefix); static void qdict_flatten_qlist(QList *qlist, QDict *target, const char *prefix) { QObject *value; const QListEntry *entry; char *new_key; int i; /* This function is never called with prefix == NULL, i.e., it is always * called from within qdict_flatten_q(list|dict)(). Therefore, it does not * need to remove list entries during the iteration (the whole list will be * deleted eventually anyway from qdict_flatten_qdict()). */ assert(prefix); entry = qlist_first(qlist); for (i = 0; entry; entry = qlist_next(entry), i++) { value = qlist_entry_obj(entry); new_key = g_strdup_printf("%s.%i", prefix, i); if (qobject_type(value) == QTYPE_QDICT) { qdict_flatten_qdict(qobject_to_qdict(value), target, new_key); } else if (qobject_type(value) == QTYPE_QLIST) { qdict_flatten_qlist(qobject_to_qlist(value), target, new_key); } else { /* All other types are moved to the target unchanged. */ qobject_incref(value); qdict_put_obj(target, new_key, value); } g_free(new_key); } } static void qdict_flatten_qdict(QDict *qdict, QDict *target, const char *prefix) { QObject *value; const QDictEntry *entry, *next; char *new_key; bool delete; entry = qdict_first(qdict); while (entry != NULL) { next = qdict_next(qdict, entry); value = qdict_entry_value(entry); new_key = NULL; delete = false; if (prefix) { new_key = g_strdup_printf("%s.%s", prefix, entry->key); } if (qobject_type(value) == QTYPE_QDICT) { /* Entries of QDicts are processed recursively, the QDict object * itself disappears. */ qdict_flatten_qdict(qobject_to_qdict(value), target, new_key ? new_key : entry->key); delete = true; } else if (qobject_type(value) == QTYPE_QLIST) { qdict_flatten_qlist(qobject_to_qlist(value), target, new_key ? new_key : entry->key); delete = true; } else if (prefix) { /* All other objects are moved to the target unchanged. */ qobject_incref(value); qdict_put_obj(target, new_key, value); delete = true; } g_free(new_key); if (delete) { qdict_del(qdict, entry->key); /* Restart loop after modifying the iterated QDict */ entry = qdict_first(qdict); continue; } entry = next; } } /** * qdict_flatten(): For each nested QDict with key x, all fields with key y * are moved to this QDict and their key is renamed to "x.y". For each nested * QList with key x, the field at index y is moved to this QDict with the key * "x.y" (i.e., the reverse of what qdict_array_split() does). * This operation is applied recursively for nested QDicts and QLists. */ void qdict_flatten(QDict *qdict) { qdict_flatten_qdict(qdict, qdict, NULL); } /* extract all the src QDict entries starting by start into dst */ void qdict_extract_subqdict(QDict *src, QDict **dst, const char *start) { const QDictEntry *entry, *next; const char *p; *dst = qdict_new(); entry = qdict_first(src); while (entry != NULL) { next = qdict_next(src, entry); if (strstart(entry->key, start, &p)) { qobject_incref(entry->value); qdict_put_obj(*dst, p, entry->value); qdict_del(src, entry->key); } entry = next; } } static bool qdict_has_prefixed_entries(const QDict *src, const char *start) { const QDictEntry *entry; for (entry = qdict_first(src); entry; entry = qdict_next(src, entry)) { if (strstart(entry->key, start, NULL)) { return true; } } return false; } /** * qdict_array_split(): This function moves array-like elements of a QDict into * a new QList. Every entry in the original QDict with a key "%u" or one * prefixed "%u.", where %u designates an unsigned integer starting at 0 and * incrementally counting up, will be moved to a new QDict at index %u in the * output QList with the key prefix removed, if that prefix is "%u.". If the * whole key is just "%u", the whole QObject will be moved unchanged without * creating a new QDict. The function terminates when there is no entry in the * QDict with a prefix directly (incrementally) following the last one; it also * returns if there are both entries with "%u" and "%u." for the same index %u. * Example: {"0.a": 42, "0.b": 23, "1.x": 0, "4.y": 1, "o.o": 7, "2": 66} * (or {"1.x": 0, "4.y": 1, "0.a": 42, "o.o": 7, "0.b": 23, "2": 66}) * => [{"a": 42, "b": 23}, {"x": 0}, 66] * and {"4.y": 1, "o.o": 7} (remainder of the old QDict) */ void qdict_array_split(QDict *src, QList **dst) { unsigned i; *dst = qlist_new(); for (i = 0; i < UINT_MAX; i++) { QObject *subqobj; bool is_subqdict; QDict *subqdict; char indexstr[32], prefix[32]; size_t snprintf_ret; snprintf_ret = snprintf(indexstr, 32, "%u", i); assert(snprintf_ret < 32); subqobj = qdict_get(src, indexstr); snprintf_ret = snprintf(prefix, 32, "%u.", i); assert(snprintf_ret < 32); is_subqdict = qdict_has_prefixed_entries(src, prefix); // There may be either a single subordinate object (named "%u") or // multiple objects (each with a key prefixed "%u."), but not both. if (!subqobj == !is_subqdict) { break; } if (is_subqdict) { qdict_extract_subqdict(src, &subqdict, prefix); assert(qdict_size(subqdict) > 0); } else { qobject_incref(subqobj); qdict_del(src, indexstr); } qlist_append_obj(*dst, (subqobj!=NULL) ? subqobj : QOBJECT(subqdict)); } } /** * qdict_join(): Absorb the src QDict into the dest QDict, that is, move all * elements from src to dest. * * If an element from src has a key already present in dest, it will not be * moved unless overwrite is true. * * If overwrite is true, the conflicting values in dest will be discarded and * replaced by the corresponding values from src. * * Therefore, with overwrite being true, the src QDict will always be empty when * this function returns. If overwrite is false, the src QDict will be empty * iff there were no conflicts. */ void qdict_join(QDict *dest, QDict *src, bool overwrite) { const QDictEntry *entry, *next; entry = qdict_first(src); while (entry) { next = qdict_next(src, entry); if (overwrite || !qdict_haskey(dest, entry->key)) { qobject_incref(entry->value); qdict_put_obj(dest, entry->key, entry->value); qdict_del(src, entry->key); } entry = next; } }
{ "language": "C" }
/* * BLEAddress.h * * Created on: Jul 2, 2017 * Author: kolban */ #ifndef COMPONENTS_CPP_UTILS_BLEADDRESS_H_ #define COMPONENTS_CPP_UTILS_BLEADDRESS_H_ #include "sdkconfig.h" #if defined(CONFIG_BT_ENABLED) #include <esp_gap_ble_api.h> // ESP32 BLE #include <string> /** * @brief A %BLE device address. * * Every %BLE device has a unique address which can be used to identify it and form connections. */ class BLEAddress { public: BLEAddress(esp_bd_addr_t address); BLEAddress(std::string stringAddress); bool equals(BLEAddress otherAddress); esp_bd_addr_t* getNative(); std::string toString(); private: esp_bd_addr_t m_address; }; #endif /* CONFIG_BT_ENABLED */ #endif /* COMPONENTS_CPP_UTILS_BLEADDRESS_H_ */
{ "language": "C" }
/* LUFA Library Copyright (C) Dean Camera, 2011. dean [at] fourwalledcubicle [dot] com www.lufa-lib.org */ /* Copyright 2011 Dean Camera (dean [at] fourwalledcubicle [dot] com) Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name of the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. The author disclaim all warranties with regard to this software, including all implied warranties of merchantability and fitness. In no event shall the author be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of this software. */ /** \file * \brief Board specific LED driver header for the Sparkfun ATMEGA8U2 breakout board. * \copydetails Group_LEDs_SPARKFUN8U2 * * \note This file should not be included directly. It is automatically included as needed by the LEDs driver * dispatch header located in LUFA/Drivers/Board/LEDs.h. */ /** \ingroup Group_LEDs * \defgroup Group_LEDs_SPARKFUN8U2 SPARKFUN8U2 * \brief Board specific LED driver header for the Sparkfun ATMEGA8U2 breakout board. * * Board specific LED driver header for the Sparkfun ATMEGA8U2 breakout board (http://www.sparkfun.com/products/10277). * * @{ */ #ifndef __LEDS_SPARKFUN8U2_H__ #define __LEDS_SPARKFUN8U2_H__ /* Includes: */ #include "../../../Common/Common.h" /* Enable C linkage for C++ Compilers: */ #if defined(__cplusplus) extern "C" { #endif /* Preprocessor Checks: */ #if !defined(__INCLUDE_FROM_LEDS_H) #error Do not include this file directly. Include LUFA/Drivers/Board/LEDS.h instead. #endif /* Public Interface - May be used in end-application: */ /* Macros: */ /** LED mask for the first LED on the board. */ #define LEDS_LED1 (1 << 4) /** LED mask for all the LEDs on the board. */ #define LEDS_ALL_LEDS LEDS_LED1 /** LED mask for none of the board LEDs. */ #define LEDS_NO_LEDS 0 /* Inline Functions: */ #if !defined(__DOXYGEN__) static inline void LEDs_Init(void) { DDRB |= LEDS_ALL_LEDS; PORTB |= LEDS_ALL_LEDS; } static inline void LEDs_TurnOnLEDs(const uint8_t LEDMask) { PORTB &= ~LEDMask; } static inline void LEDs_TurnOffLEDs(const uint8_t LEDMask) { PORTB |= LEDMask; } static inline void LEDs_SetAllLEDs(const uint8_t LEDMask) { PORTB = ((PORTB | LEDS_ALL_LEDS) & ~LEDMask); } static inline void LEDs_ChangeLEDs(const uint8_t LEDMask, const uint8_t ActiveMask) { PORTB = ((PORTB | LEDMask) & ~ActiveMask); } static inline void LEDs_ToggleLEDs(const uint8_t LEDMask) { PORTB ^= LEDMask; } static inline uint8_t LEDs_GetLEDs(void) ATTR_WARN_UNUSED_RESULT; static inline uint8_t LEDs_GetLEDs(void) { return (~PORTB & LEDS_ALL_LEDS); } #endif /* Disable C linkage for C++ Compilers: */ #if defined(__cplusplus) } #endif #endif /** @} */
{ "language": "C" }
/* * Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #undef _LARGEFILE64_SOURCE #define _LARGEFILE64_SOURCE 1 #include "jni.h" #include "jvm.h" #include "jvm_md.h" #include "jni_util.h" #include "io_util.h" /* * Platform-specific support for java.lang.Process */ #include <assert.h> #include <stddef.h> #include <stdlib.h> #include <sys/types.h> #include <ctype.h> #include <sys/wait.h> #include <signal.h> #include <string.h> #if defined(__solaris__) || defined(_ALLBSD_SOURCE) || defined(_AIX) #include <spawn.h> #endif #include "childproc.h" /* * There are 4 possible strategies we might use to "fork": * * - fork(2). Very portable and reliable but subject to * failure due to overcommit (see the documentation on * /proc/sys/vm/overcommit_memory in Linux proc(5)). * This is the ancient problem of spurious failure whenever a large * process starts a small subprocess. * * - vfork(). Using this is scary because all relevant man pages * contain dire warnings, e.g. Linux vfork(2). But at least it's * documented in the glibc docs and is standardized by XPG4. * http://www.opengroup.org/onlinepubs/000095399/functions/vfork.html * On Linux, one might think that vfork() would be implemented using * the clone system call with flag CLONE_VFORK, but in fact vfork is * a separate system call (which is a good sign, suggesting that * vfork will continue to be supported at least on Linux). * Another good sign is that glibc implements posix_spawn using * vfork whenever possible. Note that we cannot use posix_spawn * ourselves because there's no reliable way to close all inherited * file descriptors. * * - clone() with flags CLONE_VM but not CLONE_THREAD. clone() is * Linux-specific, but this ought to work - at least the glibc * sources contain code to handle different combinations of CLONE_VM * and CLONE_THREAD. However, when this was implemented, it * appeared to fail on 32-bit i386 (but not 64-bit x86_64) Linux with * the simple program * Runtime.getRuntime().exec("/bin/true").waitFor(); * with: * # Internal Error (os_linux_x86.cpp:683), pid=19940, tid=2934639536 * # Error: pthread_getattr_np failed with errno = 3 (ESRCH) * We believe this is a glibc bug, reported here: * http://sources.redhat.com/bugzilla/show_bug.cgi?id=10311 * but the glibc maintainers closed it as WONTFIX. * * - posix_spawn(). While posix_spawn() is a fairly elaborate and * complicated system call, it can't quite do everything that the old * fork()/exec() combination can do, so the only feasible way to do * this, is to use posix_spawn to launch a new helper executable * "jprochelper", which in turn execs the target (after cleaning * up file-descriptors etc.) The end result is the same as before, * a child process linked to the parent in the same way, but it * avoids the problem of duplicating the parent (VM) process * address space temporarily, before launching the target command. * * Based on the above analysis, we are currently using vfork() on * Linux and posix_spawn() on other Unix systems. */ static void setSIGCHLDHandler(JNIEnv *env) { /* There is a subtle difference between having the signal handler * for SIGCHLD be SIG_DFL and SIG_IGN. We cannot obtain process * termination information for child processes if the signal * handler is SIG_IGN. It must be SIG_DFL. * * We used to set the SIGCHLD handler only on Linux, but it's * safest to set it unconditionally. * * Consider what happens if java's parent process sets the SIGCHLD * handler to SIG_IGN. Normally signal handlers are inherited by * children, but SIGCHLD is a controversial case. Solaris appears * to always reset it to SIG_DFL, but this behavior may be * non-standard-compliant, and we shouldn't rely on it. * * References: * http://www.opengroup.org/onlinepubs/7908799/xsh/exec.html * http://www.pasc.org/interps/unofficial/db/p1003.1/pasc-1003.1-132.html */ struct sigaction sa; sa.sa_handler = SIG_DFL; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_NOCLDSTOP | SA_RESTART; if (sigaction(SIGCHLD, &sa, NULL) < 0) JNU_ThrowInternalError(env, "Can't set SIGCHLD handler"); } static void* xmalloc(JNIEnv *env, size_t size) { void *p = malloc(size); if (p == NULL) JNU_ThrowOutOfMemoryError(env, NULL); return p; } #define NEW(type, n) ((type *) xmalloc(env, (n) * sizeof(type))) /** * If PATH is not defined, the OS provides some default value. * Unfortunately, there's no portable way to get this value. * Fortunately, it's only needed if the child has PATH while we do not. */ static const char* defaultPath(void) { #ifdef __solaris__ /* These really are the Solaris defaults! */ return (geteuid() == 0 || getuid() == 0) ? "/usr/xpg4/bin:/usr/bin:/opt/SUNWspro/bin:/usr/sbin" : "/usr/xpg4/bin:/usr/bin:/opt/SUNWspro/bin:"; #else return ":/bin:/usr/bin"; /* glibc */ #endif } static const char* effectivePath(void) { const char *s = getenv("PATH"); return (s != NULL) ? s : defaultPath(); } static int countOccurrences(const char *s, char c) { int count; for (count = 0; *s != '\0'; s++) count += (*s == c); return count; } static const char * const * effectivePathv(JNIEnv *env) { char *p; int i; const char *path = effectivePath(); int count = countOccurrences(path, ':') + 1; size_t pathvsize = sizeof(const char *) * (count+1); size_t pathsize = strlen(path) + 1; const char **pathv = (const char **) xmalloc(env, pathvsize + pathsize); if (pathv == NULL) return NULL; p = (char *) pathv + pathvsize; memcpy(p, path, pathsize); /* split PATH by replacing ':' with NULs; empty components => "." */ for (i = 0; i < count; i++) { char *q = p + strcspn(p, ":"); pathv[i] = (p == q) ? "." : p; *q = '\0'; p = q + 1; } pathv[count] = NULL; return pathv; } JNIEXPORT void JNICALL Java_java_lang_ProcessImpl_init(JNIEnv *env, jclass clazz) { parentPathv = effectivePathv(env); CHECK_NULL(parentPathv); setSIGCHLDHandler(env); } #ifndef WIFEXITED #define WIFEXITED(status) (((status)&0xFF) == 0) #endif #ifndef WEXITSTATUS #define WEXITSTATUS(status) (((status)>>8)&0xFF) #endif #ifndef WIFSIGNALED #define WIFSIGNALED(status) (((status)&0xFF) > 0 && ((status)&0xFF00) == 0) #endif #ifndef WTERMSIG #define WTERMSIG(status) ((status)&0x7F) #endif static const char * getBytes(JNIEnv *env, jbyteArray arr) { return arr == NULL ? NULL : (const char*) (*env)->GetByteArrayElements(env, arr, NULL); } static void releaseBytes(JNIEnv *env, jbyteArray arr, const char* parr) { if (parr != NULL) (*env)->ReleaseByteArrayElements(env, arr, (jbyte*) parr, JNI_ABORT); } #define IOE_FORMAT "error=%d, %s" static void throwIOException(JNIEnv *env, int errnum, const char *defaultDetail) { const char *detail = defaultDetail; char *errmsg; size_t fmtsize; char tmpbuf[1024]; jstring s; if (errnum != 0) { int ret = getErrorString(errnum, tmpbuf, sizeof(tmpbuf)); if (ret != EINVAL) detail = tmpbuf; } /* ASCII Decimal representation uses 2.4 times as many bits as binary. */ fmtsize = sizeof(IOE_FORMAT) + strlen(detail) + 3 * sizeof(errnum); errmsg = NEW(char, fmtsize); if (errmsg == NULL) return; snprintf(errmsg, fmtsize, IOE_FORMAT, errnum, detail); s = JNU_NewStringPlatform(env, errmsg); if (s != NULL) { jobject x = JNU_NewObjectByName(env, "java/io/IOException", "(Ljava/lang/String;)V", s); if (x != NULL) (*env)->Throw(env, x); } free(errmsg); } #ifdef DEBUG_PROCESS /* Debugging process code is difficult; where to write debug output? */ static void debugPrint(char *format, ...) { FILE *tty = fopen("/dev/tty", "w"); va_list ap; va_start(ap, format); vfprintf(tty, format, ap); va_end(ap); fclose(tty); } #endif /* DEBUG_PROCESS */ static void copyPipe(int from[2], int to[2]) { to[0] = from[0]; to[1] = from[1]; } /* arg is an array of pointers to 0 terminated strings. array is terminated * by a null element. * * *nelems and *nbytes receive the number of elements of array (incl 0) * and total number of bytes (incl. 0) * Note. An empty array will have one null element * But if arg is null, then *nelems set to 0, and *nbytes to 0 */ static void arraysize(const char * const *arg, int *nelems, int *nbytes) { int i, bytes, count; const char * const *a = arg; char *p; int *q; if (arg == 0) { *nelems = 0; *nbytes = 0; return; } /* count the array elements and number of bytes */ for (count=0, bytes=0; *a != 0; count++, a++) { bytes += strlen(*a)+1; } *nbytes = bytes; *nelems = count+1; } /* copy the strings from arg[] into buf, starting at given offset * return new offset to next free byte */ static int copystrings(char *buf, int offset, const char * const *arg) { char *p; const char * const *a; int count=0; if (arg == 0) { return offset; } for (p=buf+offset, a=arg; *a != 0; a++) { int len = strlen(*a) +1; memcpy(p, *a, len); p += len; count += len; } return offset+count; } /** * We are unusually paranoid; use of vfork is * especially likely to tickle gcc/glibc bugs. */ #ifdef __attribute_noinline__ /* See: sys/cdefs.h */ __attribute_noinline__ #endif /* vfork(2) is deprecated on Solaris */ #ifndef __solaris__ static pid_t vforkChild(ChildStuff *c) { volatile pid_t resultPid; /* * We separate the call to vfork into a separate function to make * very sure to keep stack of child from corrupting stack of parent, * as suggested by the scary gcc warning: * warning: variable 'foo' might be clobbered by 'longjmp' or 'vfork' */ resultPid = vfork(); if (resultPid == 0) { childProcess(c); } assert(resultPid != 0); /* childProcess never returns */ return resultPid; } #endif static pid_t forkChild(ChildStuff *c) { pid_t resultPid; /* * From Solaris fork(2): In Solaris 10, a call to fork() is * identical to a call to fork1(); only the calling thread is * replicated in the child process. This is the POSIX-specified * behavior for fork(). */ resultPid = fork(); if (resultPid == 0) { childProcess(c); } assert(resultPid != 0); /* childProcess never returns */ return resultPid; } #if defined(__solaris__) || defined(_ALLBSD_SOURCE) || defined(_AIX) static pid_t spawnChild(JNIEnv *env, jobject process, ChildStuff *c, const char *helperpath) { pid_t resultPid; jboolean isCopy; int i, offset, rval, bufsize, magic; char *buf, buf1[16]; char *hlpargs[2]; SpawnInfo sp; /* need to tell helper which fd is for receiving the childstuff * and which fd to send response back on */ snprintf(buf1, sizeof(buf1), "%d:%d", c->childenv[0], c->fail[1]); /* put the fd string as argument to the helper cmd */ hlpargs[0] = buf1; hlpargs[1] = 0; /* Following items are sent down the pipe to the helper * after it is spawned. * All strings are null terminated. All arrays of strings * have an empty string for termination. * - the ChildStuff struct * - the SpawnInfo struct * - the argv strings array * - the envv strings array * - the home directory string * - the parentPath string * - the parentPathv array */ /* First calculate the sizes */ arraysize(c->argv, &sp.nargv, &sp.argvBytes); bufsize = sp.argvBytes; arraysize(c->envv, &sp.nenvv, &sp.envvBytes); bufsize += sp.envvBytes; sp.dirlen = c->pdir == 0 ? 0 : strlen(c->pdir)+1; bufsize += sp.dirlen; arraysize(parentPathv, &sp.nparentPathv, &sp.parentPathvBytes); bufsize += sp.parentPathvBytes; /* We need to clear FD_CLOEXEC if set in the fds[]. * Files are created FD_CLOEXEC in Java. * Otherwise, they will be closed when the target gets exec'd */ for (i=0; i<3; i++) { if (c->fds[i] != -1) { int flags = fcntl(c->fds[i], F_GETFD); if (flags & FD_CLOEXEC) { fcntl(c->fds[i], F_SETFD, flags & (~1)); } } } rval = posix_spawn(&resultPid, helperpath, 0, 0, (char * const *) hlpargs, environ); if (rval != 0) { return -1; } /* now the lengths are known, copy the data */ buf = NEW(char, bufsize); if (buf == 0) { return -1; } offset = copystrings(buf, 0, &c->argv[0]); offset = copystrings(buf, offset, &c->envv[0]); memcpy(buf+offset, c->pdir, sp.dirlen); offset += sp.dirlen; offset = copystrings(buf, offset, parentPathv); assert(offset == bufsize); magic = magicNumber(); /* write the two structs and the data buffer */ write(c->childenv[1], (char *)&magic, sizeof(magic)); // magic number first write(c->childenv[1], (char *)c, sizeof(*c)); write(c->childenv[1], (char *)&sp, sizeof(sp)); write(c->childenv[1], buf, bufsize); free(buf); /* In this mode an external main() in invoked which calls back into * childProcess() in this file, rather than directly * via the statement below */ return resultPid; } #endif /* * Start a child process running function childProcess. * This function only returns in the parent. */ static pid_t startChild(JNIEnv *env, jobject process, ChildStuff *c, const char *helperpath) { switch (c->mode) { /* vfork(2) is deprecated on Solaris */ #ifndef __solaris__ case MODE_VFORK: return vforkChild(c); #endif case MODE_FORK: return forkChild(c); #if defined(__solaris__) || defined(_ALLBSD_SOURCE) || defined(_AIX) case MODE_POSIX_SPAWN: return spawnChild(env, process, c, helperpath); #endif default: return -1; } } JNIEXPORT jint JNICALL Java_java_lang_ProcessImpl_forkAndExec(JNIEnv *env, jobject process, jint mode, jbyteArray helperpath, jbyteArray prog, jbyteArray argBlock, jint argc, jbyteArray envBlock, jint envc, jbyteArray dir, jintArray std_fds, jboolean redirectErrorStream) { int errnum; int resultPid = -1; int in[2], out[2], err[2], fail[2], childenv[2]; jint *fds = NULL; const char *phelperpath = NULL; const char *pprog = NULL; const char *pargBlock = NULL; const char *penvBlock = NULL; ChildStuff *c; in[0] = in[1] = out[0] = out[1] = err[0] = err[1] = fail[0] = fail[1] = -1; childenv[0] = childenv[1] = -1; if ((c = NEW(ChildStuff, 1)) == NULL) return -1; c->argv = NULL; c->envv = NULL; c->pdir = NULL; /* Convert prog + argBlock into a char ** argv. * Add one word room for expansion of argv for use by * execve_as_traditional_shell_script. * This word is also used when using posix_spawn mode */ assert(prog != NULL && argBlock != NULL); if ((phelperpath = getBytes(env, helperpath)) == NULL) goto Catch; if ((pprog = getBytes(env, prog)) == NULL) goto Catch; if ((pargBlock = getBytes(env, argBlock)) == NULL) goto Catch; if ((c->argv = NEW(const char *, argc + 3)) == NULL) goto Catch; c->argv[0] = pprog; c->argc = argc + 2; initVectorFromBlock(c->argv+1, pargBlock, argc); if (envBlock != NULL) { /* Convert envBlock into a char ** envv */ if ((penvBlock = getBytes(env, envBlock)) == NULL) goto Catch; if ((c->envv = NEW(const char *, envc + 1)) == NULL) goto Catch; initVectorFromBlock(c->envv, penvBlock, envc); } if (dir != NULL) { if ((c->pdir = getBytes(env, dir)) == NULL) goto Catch; } assert(std_fds != NULL); fds = (*env)->GetIntArrayElements(env, std_fds, NULL); if (fds == NULL) goto Catch; if ((fds[0] == -1 && pipe(in) < 0) || (fds[1] == -1 && pipe(out) < 0) || (fds[2] == -1 && pipe(err) < 0) || (pipe(childenv) < 0) || (pipe(fail) < 0)) { throwIOException(env, errno, "Bad file descriptor"); goto Catch; } c->fds[0] = fds[0]; c->fds[1] = fds[1]; c->fds[2] = fds[2]; copyPipe(in, c->in); copyPipe(out, c->out); copyPipe(err, c->err); copyPipe(fail, c->fail); copyPipe(childenv, c->childenv); c->redirectErrorStream = redirectErrorStream; c->mode = mode; resultPid = startChild(env, process, c, phelperpath); assert(resultPid != 0); if (resultPid < 0) { switch (c->mode) { case MODE_VFORK: throwIOException(env, errno, "vfork failed"); break; case MODE_FORK: throwIOException(env, errno, "fork failed"); break; case MODE_POSIX_SPAWN: throwIOException(env, errno, "posix_spawn failed"); break; } goto Catch; } close(fail[1]); fail[1] = -1; /* See: WhyCantJohnnyExec (childproc.c) */ switch (readFully(fail[0], &errnum, sizeof(errnum))) { case 0: break; /* Exec succeeded */ case sizeof(errnum): waitpid(resultPid, NULL, 0); throwIOException(env, errnum, "Exec failed"); goto Catch; default: throwIOException(env, errno, "Read failed"); goto Catch; } fds[0] = (in [1] != -1) ? in [1] : -1; fds[1] = (out[0] != -1) ? out[0] : -1; fds[2] = (err[0] != -1) ? err[0] : -1; Finally: /* Always clean up the child's side of the pipes */ closeSafely(in [0]); closeSafely(out[1]); closeSafely(err[1]); /* Always clean up fail and childEnv descriptors */ closeSafely(fail[0]); closeSafely(fail[1]); closeSafely(childenv[0]); closeSafely(childenv[1]); releaseBytes(env, helperpath, phelperpath); releaseBytes(env, prog, pprog); releaseBytes(env, argBlock, pargBlock); releaseBytes(env, envBlock, penvBlock); releaseBytes(env, dir, c->pdir); free(c->argv); free(c->envv); free(c); if (fds != NULL) (*env)->ReleaseIntArrayElements(env, std_fds, fds, 0); return resultPid; Catch: /* Clean up the parent's side of the pipes in case of failure only */ closeSafely(in [1]); in[1] = -1; closeSafely(out[0]); out[0] = -1; closeSafely(err[0]); err[0] = -1; goto Finally; }
{ "language": "C" }
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2016 Blender Foundation. * All rights reserved. */ /** \file * \ingroup spaction */ #include <string.h> #include <stdio.h> #include <math.h> #include <float.h> #include "DNA_anim_types.h" #include "DNA_object_types.h" #include "DNA_scene_types.h" #include "MEM_guardedalloc.h" #include "BLI_utildefines.h" #include "BLT_translation.h" #include "BKE_context.h" #include "BKE_curve.h" #include "BKE_fcurve.h" #include "BKE_screen.h" #include "BKE_unit.h" #include "WM_api.h" #include "WM_types.h" #include "RNA_access.h" #include "ED_anim_api.h" #include "ED_keyframing.h" #include "ED_screen.h" #include "UI_interface.h" #include "UI_resources.h" #include "action_intern.h" // own include /* ******************* action editor space & buttons ************** */ /* ******************* general ******************************** */ void action_buttons_register(ARegionType *UNUSED(art)) { #if 0 PanelType *pt; // TODO: AnimData / Actions List pt = MEM_callocN(sizeof(PanelType), "spacetype action panel properties"); strcpy(pt->idname, "ACTION_PT_properties"); strcpy(pt->label, N_("Active F-Curve")); strcpy(pt->translation_context, BLT_I18NCONTEXT_DEFAULT_BPYRNA); pt->draw = action_anim_panel_properties; pt->poll = action_anim_panel_poll; BLI_addtail(&art->paneltypes, pt); pt = MEM_callocN(sizeof(PanelType), "spacetype action panel properties"); strcpy(pt->idname, "ACTION_PT_key_properties"); strcpy(pt->label, N_("Active Keyframe")); strcpy(pt->translation_context, BLT_I18NCONTEXT_DEFAULT_BPYRNA); pt->draw = action_anim_panel_key_properties; pt->poll = action_anim_panel_poll; BLI_addtail(&art->paneltypes, pt); pt = MEM_callocN(sizeof(PanelType), "spacetype action panel modifiers"); strcpy(pt->idname, "ACTION_PT_modifiers"); strcpy(pt->label, N_("Modifiers")); strcpy(pt->translation_context, BLT_I18NCONTEXT_DEFAULT_BPYRNA); pt->draw = action_anim_panel_modifiers; pt->poll = action_anim_panel_poll; BLI_addtail(&art->paneltypes, pt); #endif }
{ "language": "C" }
#include <sparc-ifunc.h> #define __sha256_process_block __sha256_process_block_generic extern void __sha256_process_block_generic (const void *buffer, size_t len, struct sha256_ctx *ctx); #include <crypt/sha256-block.c> #undef __sha256_process_block extern void __sha256_process_block_crop (const void *buffer, size_t len, struct sha256_ctx *ctx); static bool cpu_supports_sha256(int hwcap) { unsigned long cfr; if (!(hwcap & HWCAP_SPARC_CRYPTO)) return false; __asm__ ("rd %%asr26, %0" : "=r" (cfr)); if (cfr & (1 << 6)) return true; return false; } extern void __sha256_process_block (const void *buffer, size_t len, struct sha256_ctx *ctx); sparc_libc_ifunc (__sha256_process_block, cpu_supports_sha256(hwcap) ? __sha256_process_block_crop : __sha256_process_block_generic);
{ "language": "C" }
// Copyright 2011 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_STRINGS_UNICODE_H_ #define V8_STRINGS_UNICODE_H_ #include <sys/types.h> #include "src/base/bit-field.h" #include "src/common/globals.h" #include "src/third_party/utf8-decoder/utf8-decoder.h" /** * \file * Definitions and convenience functions for working with unicode. */ namespace unibrow { using uchar = unsigned int; using byte = unsigned char; /** * The max length of the result of converting the case of a single * character. */ const int kMaxMappingSize = 4; #ifndef V8_INTL_SUPPORT template <class T, int size = 256> class Predicate { public: inline Predicate() = default; inline bool get(uchar c); private: friend class Test; bool CalculateValue(uchar c); class CacheEntry { public: inline CacheEntry() : bit_field_(CodePointField::encode(0) | ValueField::encode(0)) {} inline CacheEntry(uchar code_point, bool value) : bit_field_( CodePointField::encode(CodePointField::kMask & code_point) | ValueField::encode(value)) { DCHECK_IMPLIES((CodePointField::kMask & code_point) != code_point, code_point == static_cast<uchar>(-1)); } uchar code_point() const { return CodePointField::decode(bit_field_); } bool value() const { return ValueField::decode(bit_field_); } private: using CodePointField = v8::base::BitField<uchar, 0, 21>; using ValueField = v8::base::BitField<bool, 21, 1>; uint32_t bit_field_; }; static const int kSize = size; static const int kMask = kSize - 1; CacheEntry entries_[kSize]; }; // A cache used in case conversion. It caches the value for characters // that either have no mapping or map to a single character independent // of context. Characters that map to more than one character or that // map differently depending on context are always looked up. template <class T, int size = 256> class Mapping { public: inline Mapping() = default; inline int get(uchar c, uchar n, uchar* result); private: friend class Test; int CalculateValue(uchar c, uchar n, uchar* result); struct CacheEntry { inline CacheEntry() : code_point_(kNoChar), offset_(0) {} inline CacheEntry(uchar code_point, signed offset) : code_point_(code_point), offset_(offset) {} uchar code_point_; signed offset_; static const int kNoChar = (1 << 21) - 1; }; static const int kSize = size; static const int kMask = kSize - 1; CacheEntry entries_[kSize]; }; class UnicodeData { private: friend class Test; static int GetByteCount(); static const uchar kMaxCodePoint; }; #endif // !V8_INTL_SUPPORT class Utf16 { public: static const int kNoPreviousCharacter = -1; static inline bool IsSurrogatePair(int lead, int trail) { return IsLeadSurrogate(lead) && IsTrailSurrogate(trail); } static inline bool IsLeadSurrogate(int code) { return (code & 0xfc00) == 0xd800; } static inline bool IsTrailSurrogate(int code) { return (code & 0xfc00) == 0xdc00; } static inline int CombineSurrogatePair(uchar lead, uchar trail) { return 0x10000 + ((lead & 0x3ff) << 10) + (trail & 0x3ff); } static const uchar kMaxNonSurrogateCharCode = 0xffff; // Encoding a single UTF-16 code unit will produce 1, 2 or 3 bytes // of UTF-8 data. The special case where the unit is a surrogate // trail produces 1 byte net, because the encoding of the pair is // 4 bytes and the 3 bytes that were used to encode the lead surrogate // can be reclaimed. static const int kMaxExtraUtf8BytesForOneUtf16CodeUnit = 3; // One UTF-16 surrogate is endoded (illegally) as 3 UTF-8 bytes. // The illegality stems from the surrogate not being part of a pair. static const int kUtf8BytesToCodeASurrogate = 3; static inline uint16_t LeadSurrogate(uint32_t char_code) { return 0xd800 + (((char_code - 0x10000) >> 10) & 0x3ff); } static inline uint16_t TrailSurrogate(uint32_t char_code) { return 0xdc00 + (char_code & 0x3ff); } }; class Latin1 { public: static const uint16_t kMaxChar = 0xff; // Convert the character to Latin-1 case equivalent if possible. static inline uint16_t TryConvertToLatin1(uint16_t c) { switch (c) { // This are equivalent characters in unicode. case 0x39c: case 0x3bc: return 0xb5; // This is an uppercase of a Latin-1 character // outside of Latin-1. case 0x178: return 0xff; } return c; } }; class V8_EXPORT_PRIVATE Utf8 { public: using State = Utf8DfaDecoder::State; static inline uchar Length(uchar chr, int previous); static inline unsigned EncodeOneByte(char* out, uint8_t c); static inline unsigned Encode(char* out, uchar c, int previous, bool replace_invalid = false); static uchar CalculateValue(const byte* str, size_t length, size_t* cursor); // The unicode replacement character, used to signal invalid unicode // sequences (e.g. an orphan surrogate) when converting to a UTF-8 encoding. static const uchar kBadChar = 0xFFFD; static const uchar kBufferEmpty = 0x0; static const uchar kIncomplete = 0xFFFFFFFC; // any non-valid code point. static const unsigned kMaxEncodedSize = 4; static const unsigned kMaxOneByteChar = 0x7f; static const unsigned kMaxTwoByteChar = 0x7ff; static const unsigned kMaxThreeByteChar = 0xffff; static const unsigned kMaxFourByteChar = 0x1fffff; // A single surrogate is coded as a 3 byte UTF-8 sequence, but two together // that match are coded as a 4 byte UTF-8 sequence. static const unsigned kBytesSavedByCombiningSurrogates = 2; static const unsigned kSizeOfUnmatchedSurrogate = 3; // The maximum size a single UTF-16 code unit may take up when encoded as // UTF-8. static const unsigned kMax16BitCodeUnitSize = 3; static inline uchar ValueOf(const byte* str, size_t length, size_t* cursor); using Utf8IncrementalBuffer = uint32_t; static inline uchar ValueOfIncremental(const byte** cursor, State* state, Utf8IncrementalBuffer* buffer); static uchar ValueOfIncrementalFinish(State* state); // Excludes non-characters from the set of valid code points. static inline bool IsValidCharacter(uchar c); // Validate if the input has a valid utf-8 encoding. Unlike JS source code // this validation function will accept any unicode code point, including // kBadChar and BOMs. // // This method checks for: // - valid utf-8 endcoding (e.g. no over-long encodings), // - absence of surrogates, // - valid code point range. static bool ValidateEncoding(const byte* str, size_t length); }; struct Uppercase { static bool Is(uchar c); }; struct Letter { static bool Is(uchar c); }; #ifndef V8_INTL_SUPPORT struct V8_EXPORT_PRIVATE ID_Start { static bool Is(uchar c); }; struct V8_EXPORT_PRIVATE ID_Continue { static bool Is(uchar c); }; struct V8_EXPORT_PRIVATE WhiteSpace { static bool Is(uchar c); }; #endif // !V8_INTL_SUPPORT // LineTerminator: 'JS_Line_Terminator' in point.properties // ES#sec-line-terminators lists exactly 4 code points: // LF (U+000A), CR (U+000D), LS(U+2028), PS(U+2029) V8_INLINE bool IsLineTerminator(uchar c) { return c == 0x000A || c == 0x000D || c == 0x2028 || c == 0x2029; } V8_INLINE bool IsStringLiteralLineTerminator(uchar c) { return c == 0x000A || c == 0x000D; } #ifndef V8_INTL_SUPPORT struct V8_EXPORT_PRIVATE ToLowercase { static const int kMaxWidth = 3; static const bool kIsToLower = true; static int Convert(uchar c, uchar n, uchar* result, bool* allow_caching_ptr); }; struct V8_EXPORT_PRIVATE ToUppercase { static const int kMaxWidth = 3; static const bool kIsToLower = false; static int Convert(uchar c, uchar n, uchar* result, bool* allow_caching_ptr); }; struct V8_EXPORT_PRIVATE Ecma262Canonicalize { static const int kMaxWidth = 1; static int Convert(uchar c, uchar n, uchar* result, bool* allow_caching_ptr); }; struct V8_EXPORT_PRIVATE Ecma262UnCanonicalize { static const int kMaxWidth = 4; static int Convert(uchar c, uchar n, uchar* result, bool* allow_caching_ptr); }; struct V8_EXPORT_PRIVATE CanonicalizationRange { static const int kMaxWidth = 1; static int Convert(uchar c, uchar n, uchar* result, bool* allow_caching_ptr); }; #endif // !V8_INTL_SUPPORT } // namespace unibrow #endif // V8_STRINGS_UNICODE_H_
{ "language": "C" }
#ifndef _IME_SOCKET_H__ #define _IME_SOCKET_H__ #include <winsock.h> #include <string> using std::string; void connect_ime_server(); bool init_ime_socket(); string sock_error(); string ime_recv_line(); void ime_write_line(const string& line); #endif //_IME_SOCKET_H__
{ "language": "C" }
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class com_libmailcore_IMAPFolder */ #ifndef _Included_com_libmailcore_IMAPFolder #define _Included_com_libmailcore_IMAPFolder #ifdef __cplusplus extern "C" { #endif #undef com_libmailcore_IMAPFolder_serialVersionUID #define com_libmailcore_IMAPFolder_serialVersionUID 1LL /* * Class: com_libmailcore_IMAPFolder * Method: setPath * Signature: (Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_com_libmailcore_IMAPFolder_setPath (JNIEnv *, jobject, jstring); /* * Class: com_libmailcore_IMAPFolder * Method: path * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_com_libmailcore_IMAPFolder_path (JNIEnv *, jobject); /* * Class: com_libmailcore_IMAPFolder * Method: setDelimiter * Signature: (C)V */ JNIEXPORT void JNICALL Java_com_libmailcore_IMAPFolder_setDelimiter (JNIEnv *, jobject, jchar); /* * Class: com_libmailcore_IMAPFolder * Method: delimiter * Signature: ()C */ JNIEXPORT jchar JNICALL Java_com_libmailcore_IMAPFolder_delimiter (JNIEnv *, jobject); /* * Class: com_libmailcore_IMAPFolder * Method: setFlags * Signature: (I)V */ JNIEXPORT void JNICALL Java_com_libmailcore_IMAPFolder_setFlags (JNIEnv *, jobject, jint); /* * Class: com_libmailcore_IMAPFolder * Method: flags * Signature: ()I */ JNIEXPORT jint JNICALL Java_com_libmailcore_IMAPFolder_flags (JNIEnv *, jobject); /* * Class: com_libmailcore_IMAPFolder * Method: setupNative * Signature: ()V */ JNIEXPORT void JNICALL Java_com_libmailcore_IMAPFolder_setupNative (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif
{ "language": "C" }
/* $Xorg: SelectionI.h,v 1.4 2001/02/09 02:03:58 xorgcvs Exp $ */ /*********************************************************** Copyright 1987, 1988, 1994, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP 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. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. Copyright 1987, 1988 by Digital Equipment Corporation, Maynard, Massachusetts. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Digital not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ #ifndef _XtselectionI_h #define _XtselectionI_h #include "Intrinsic.h" typedef struct _RequestRec *Request; typedef struct _SelectRec *Select; typedef struct _RequestRec { Select ctx; /* logical owner */ Widget widget; /* widget actually receiving Selection events */ Window requestor; Atom property; Atom target; Atom type; int format; XtPointer value; unsigned long bytelength; unsigned long offset; XtIntervalId timeout; XSelectionRequestEvent event; /* for XtGetSelectionRequest */ Boolean allSent; } RequestRec; typedef struct { Atom prop; Boolean avail; } SelectionPropRec, *SelectionProp; typedef struct { Display *dpy; Atom incr_atom, indirect_atom, timestamp_atom; int propCount; SelectionProp list; } PropListRec, *PropList; typedef struct _SelectRec { Atom selection; /* constant */ Display *dpy; /* constant */ Widget widget; Time time; unsigned long serial; XtConvertSelectionProc convert; XtLoseSelectionProc loses; XtSelectionDoneProc notify; XtCancelConvertSelectionProc owner_cancel; XtPointer owner_closure; PropList prop_list; Request req; /* state for local non-incr xfer */ int ref_count; /* of active transfers */ unsigned int incremental:1; unsigned int free_when_done:1; unsigned int was_disowned:1; } SelectRec; typedef struct _ParamRec { Atom selection; Atom param; } ParamRec, *Param; typedef struct _ParamInfoRec { unsigned int count; Param paramlist; } ParamInfoRec, *ParamInfo; typedef struct _QueuedRequestRec { Atom selection; Atom target; Atom param; XtSelectionCallbackProc callback; XtPointer closure; Time time; Boolean incremental; } QueuedRequestRec, *QueuedRequest; typedef struct _QueuedRequestInfoRec { int count; Atom *selections; QueuedRequest *requests; } QueuedRequestInfoRec, *QueuedRequestInfo; typedef struct { XtSelectionCallbackProc *callbacks; XtPointer *req_closure; Atom property; Atom *target; Atom type; int format; char *value; int bytelength; int offset; XtIntervalId timeout; XtEventHandler proc; Widget widget; Time time; Select ctx; Boolean *incremental; int current; } CallBackInfoRec, *CallBackInfo; typedef struct { Atom target; Atom property; } IndirectPair; #define IndirectPairWordSize 2 typedef struct { int active_transfer_count; } RequestWindowRec; #define MAX_SELECTION_INCR(dpy) (((65536 < XMaxRequestSize(dpy)) ? \ (65536 << 2) : (XMaxRequestSize(dpy) << 2))-100) #define MATCH_SELECT(event, info) ((event->time == info->time) && \ (event->requestor == XtWindow(info->widget)) && \ (event->selection == info->ctx->selection) && \ (event->target == *info->target)) #endif /* _XtselectionI_h */ /* DON'T ADD STUFF AFTER THIS #endif */
{ "language": "C" }
// SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) /* Copyright (C) 2020 Facebook */ #include <errno.h> #include <net/if.h> #include <stdio.h> #include <unistd.h> #include <bpf/bpf.h> #include "json_writer.h" #include "main.h" static const char * const link_type_name[] = { [BPF_LINK_TYPE_UNSPEC] = "unspec", [BPF_LINK_TYPE_RAW_TRACEPOINT] = "raw_tracepoint", [BPF_LINK_TYPE_TRACING] = "tracing", [BPF_LINK_TYPE_CGROUP] = "cgroup", [BPF_LINK_TYPE_ITER] = "iter", [BPF_LINK_TYPE_NETNS] = "netns", }; static int link_parse_fd(int *argc, char ***argv) { int fd; if (is_prefix(**argv, "id")) { unsigned int id; char *endptr; NEXT_ARGP(); id = strtoul(**argv, &endptr, 0); if (*endptr) { p_err("can't parse %s as ID", **argv); return -1; } NEXT_ARGP(); fd = bpf_link_get_fd_by_id(id); if (fd < 0) p_err("failed to get link with ID %d: %s", id, strerror(errno)); return fd; } else if (is_prefix(**argv, "pinned")) { char *path; NEXT_ARGP(); path = **argv; NEXT_ARGP(); return open_obj_pinned_any(path, BPF_OBJ_LINK); } p_err("expected 'id' or 'pinned', got: '%s'?", **argv); return -1; } static void show_link_header_json(struct bpf_link_info *info, json_writer_t *wtr) { jsonw_uint_field(wtr, "id", info->id); if (info->type < ARRAY_SIZE(link_type_name)) jsonw_string_field(wtr, "type", link_type_name[info->type]); else jsonw_uint_field(wtr, "type", info->type); jsonw_uint_field(json_wtr, "prog_id", info->prog_id); } static void show_link_attach_type_json(__u32 attach_type, json_writer_t *wtr) { if (attach_type < ARRAY_SIZE(attach_type_name)) jsonw_string_field(wtr, "attach_type", attach_type_name[attach_type]); else jsonw_uint_field(wtr, "attach_type", attach_type); } static int get_prog_info(int prog_id, struct bpf_prog_info *info) { __u32 len = sizeof(*info); int err, prog_fd; prog_fd = bpf_prog_get_fd_by_id(prog_id); if (prog_fd < 0) return prog_fd; memset(info, 0, sizeof(*info)); err = bpf_obj_get_info_by_fd(prog_fd, info, &len); if (err) p_err("can't get prog info: %s", strerror(errno)); close(prog_fd); return err; } static int show_link_close_json(int fd, struct bpf_link_info *info) { struct bpf_prog_info prog_info; int err; jsonw_start_object(json_wtr); show_link_header_json(info, json_wtr); switch (info->type) { case BPF_LINK_TYPE_RAW_TRACEPOINT: jsonw_string_field(json_wtr, "tp_name", u64_to_ptr(info->raw_tracepoint.tp_name)); break; case BPF_LINK_TYPE_TRACING: err = get_prog_info(info->prog_id, &prog_info); if (err) return err; if (prog_info.type < prog_type_name_size) jsonw_string_field(json_wtr, "prog_type", prog_type_name[prog_info.type]); else jsonw_uint_field(json_wtr, "prog_type", prog_info.type); show_link_attach_type_json(info->tracing.attach_type, json_wtr); break; case BPF_LINK_TYPE_CGROUP: jsonw_lluint_field(json_wtr, "cgroup_id", info->cgroup.cgroup_id); show_link_attach_type_json(info->cgroup.attach_type, json_wtr); break; case BPF_LINK_TYPE_NETNS: jsonw_uint_field(json_wtr, "netns_ino", info->netns.netns_ino); show_link_attach_type_json(info->netns.attach_type, json_wtr); break; default: break; } if (!hash_empty(link_table.table)) { struct pinned_obj *obj; jsonw_name(json_wtr, "pinned"); jsonw_start_array(json_wtr); hash_for_each_possible(link_table.table, obj, hash, info->id) { if (obj->id == info->id) jsonw_string(json_wtr, obj->path); } jsonw_end_array(json_wtr); } emit_obj_refs_json(&refs_table, info->id, json_wtr); jsonw_end_object(json_wtr); return 0; } static void show_link_header_plain(struct bpf_link_info *info) { printf("%u: ", info->id); if (info->type < ARRAY_SIZE(link_type_name)) printf("%s ", link_type_name[info->type]); else printf("type %u ", info->type); printf("prog %u ", info->prog_id); } static void show_link_attach_type_plain(__u32 attach_type) { if (attach_type < ARRAY_SIZE(attach_type_name)) printf("attach_type %s ", attach_type_name[attach_type]); else printf("attach_type %u ", attach_type); } static int show_link_close_plain(int fd, struct bpf_link_info *info) { struct bpf_prog_info prog_info; int err; show_link_header_plain(info); switch (info->type) { case BPF_LINK_TYPE_RAW_TRACEPOINT: printf("\n\ttp '%s' ", (const char *)u64_to_ptr(info->raw_tracepoint.tp_name)); break; case BPF_LINK_TYPE_TRACING: err = get_prog_info(info->prog_id, &prog_info); if (err) return err; if (prog_info.type < prog_type_name_size) printf("\n\tprog_type %s ", prog_type_name[prog_info.type]); else printf("\n\tprog_type %u ", prog_info.type); show_link_attach_type_plain(info->tracing.attach_type); break; case BPF_LINK_TYPE_CGROUP: printf("\n\tcgroup_id %zu ", (size_t)info->cgroup.cgroup_id); show_link_attach_type_plain(info->cgroup.attach_type); break; case BPF_LINK_TYPE_NETNS: printf("\n\tnetns_ino %u ", info->netns.netns_ino); show_link_attach_type_plain(info->netns.attach_type); break; default: break; } if (!hash_empty(link_table.table)) { struct pinned_obj *obj; hash_for_each_possible(link_table.table, obj, hash, info->id) { if (obj->id == info->id) printf("\n\tpinned %s", obj->path); } } emit_obj_refs_plain(&refs_table, info->id, "\n\tpids "); printf("\n"); return 0; } static int do_show_link(int fd) { struct bpf_link_info info; __u32 len = sizeof(info); char raw_tp_name[256]; int err; memset(&info, 0, sizeof(info)); again: err = bpf_obj_get_info_by_fd(fd, &info, &len); if (err) { p_err("can't get link info: %s", strerror(errno)); close(fd); return err; } if (info.type == BPF_LINK_TYPE_RAW_TRACEPOINT && !info.raw_tracepoint.tp_name) { info.raw_tracepoint.tp_name = (unsigned long)&raw_tp_name; info.raw_tracepoint.tp_name_len = sizeof(raw_tp_name); goto again; } if (json_output) show_link_close_json(fd, &info); else show_link_close_plain(fd, &info); close(fd); return 0; } static int do_show(int argc, char **argv) { __u32 id = 0; int err, fd; if (show_pinned) build_pinned_obj_table(&link_table, BPF_OBJ_LINK); build_obj_refs_table(&refs_table, BPF_OBJ_LINK); if (argc == 2) { fd = link_parse_fd(&argc, &argv); if (fd < 0) return fd; return do_show_link(fd); } if (argc) return BAD_ARG(); if (json_output) jsonw_start_array(json_wtr); while (true) { err = bpf_link_get_next_id(id, &id); if (err) { if (errno == ENOENT) break; p_err("can't get next link: %s%s", strerror(errno), errno == EINVAL ? " -- kernel too old?" : ""); break; } fd = bpf_link_get_fd_by_id(id); if (fd < 0) { if (errno == ENOENT) continue; p_err("can't get link by id (%u): %s", id, strerror(errno)); break; } err = do_show_link(fd); if (err) break; } if (json_output) jsonw_end_array(json_wtr); delete_obj_refs_table(&refs_table); return errno == ENOENT ? 0 : -1; } static int do_pin(int argc, char **argv) { int err; err = do_pin_any(argc, argv, link_parse_fd); if (!err && json_output) jsonw_null(json_wtr); return err; } static int do_detach(int argc, char **argv) { int err, fd; if (argc != 2) { p_err("link specifier is invalid or missing\n"); return 1; } fd = link_parse_fd(&argc, &argv); if (fd < 0) return 1; err = bpf_link_detach(fd); if (err) err = -errno; close(fd); if (err) { p_err("failed link detach: %s", strerror(-err)); return 1; } if (json_output) jsonw_null(json_wtr); return 0; } static int do_help(int argc, char **argv) { if (json_output) { jsonw_null(json_wtr); return 0; } fprintf(stderr, "Usage: %1$s %2$s { show | list } [LINK]\n" " %1$s %2$s pin LINK FILE\n" " %1$s %2$s detach LINK\n" " %1$s %2$s help\n" "\n" " " HELP_SPEC_LINK "\n" " " HELP_SPEC_OPTIONS "\n" "", bin_name, argv[-2]); return 0; } static const struct cmd cmds[] = { { "show", do_show }, { "list", do_show }, { "help", do_help }, { "pin", do_pin }, { "detach", do_detach }, { 0 } }; int do_link(int argc, char **argv) { return cmd_select(cmds, argc, argv, do_help); }
{ "language": "C" }
/* * fs/bfs/dir.c * BFS directory operations. * Copyright (C) 1999,2000 Tigran Aivazian <tigran@veritas.com> * Made endianness-clean by Andrew Stribblehill <ads@wompom.org> 2005 */ #include <linux/time.h> #include <linux/string.h> #include <linux/fs.h> #include <linux/buffer_head.h> #include <linux/sched.h> #include "bfs.h" #undef DEBUG #ifdef DEBUG #define dprintf(x...) printf(x) #else #define dprintf(x...) #endif static int bfs_add_entry(struct inode *dir, const unsigned char *name, int namelen, int ino); static struct buffer_head *bfs_find_entry(struct inode *dir, const unsigned char *name, int namelen, struct bfs_dirent **res_dir); static int bfs_readdir(struct file *f, struct dir_context *ctx) { struct inode *dir = file_inode(f); struct buffer_head *bh; struct bfs_dirent *de; unsigned int offset; int block; if (ctx->pos & (BFS_DIRENT_SIZE - 1)) { printf("Bad f_pos=%08lx for %s:%08lx\n", (unsigned long)ctx->pos, dir->i_sb->s_id, dir->i_ino); return -EINVAL; } while (ctx->pos < dir->i_size) { offset = ctx->pos & (BFS_BSIZE - 1); block = BFS_I(dir)->i_sblock + (ctx->pos >> BFS_BSIZE_BITS); bh = sb_bread(dir->i_sb, block); if (!bh) { ctx->pos += BFS_BSIZE - offset; continue; } do { de = (struct bfs_dirent *)(bh->b_data + offset); if (de->ino) { int size = strnlen(de->name, BFS_NAMELEN); if (!dir_emit(ctx, de->name, size, le16_to_cpu(de->ino), DT_UNKNOWN)) { brelse(bh); return 0; } } offset += BFS_DIRENT_SIZE; ctx->pos += BFS_DIRENT_SIZE; } while ((offset < BFS_BSIZE) && (ctx->pos < dir->i_size)); brelse(bh); } return 0; } const struct file_operations bfs_dir_operations = { .read = generic_read_dir, .iterate_shared = bfs_readdir, .fsync = generic_file_fsync, .llseek = generic_file_llseek, }; static int bfs_create(struct inode *dir, struct dentry *dentry, umode_t mode, bool excl) { int err; struct inode *inode; struct super_block *s = dir->i_sb; struct bfs_sb_info *info = BFS_SB(s); unsigned long ino; inode = new_inode(s); if (!inode) return -ENOMEM; mutex_lock(&info->bfs_lock); ino = find_first_zero_bit(info->si_imap, info->si_lasti + 1); if (ino > info->si_lasti) { mutex_unlock(&info->bfs_lock); iput(inode); return -ENOSPC; } set_bit(ino, info->si_imap); info->si_freei--; inode_init_owner(inode, dir, mode); inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME_SEC; inode->i_blocks = 0; inode->i_op = &bfs_file_inops; inode->i_fop = &bfs_file_operations; inode->i_mapping->a_ops = &bfs_aops; inode->i_ino = ino; BFS_I(inode)->i_dsk_ino = ino; BFS_I(inode)->i_sblock = 0; BFS_I(inode)->i_eblock = 0; insert_inode_hash(inode); mark_inode_dirty(inode); bfs_dump_imap("create", s); err = bfs_add_entry(dir, dentry->d_name.name, dentry->d_name.len, inode->i_ino); if (err) { inode_dec_link_count(inode); mutex_unlock(&info->bfs_lock); iput(inode); return err; } mutex_unlock(&info->bfs_lock); d_instantiate(dentry, inode); return 0; } static struct dentry *bfs_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags) { struct inode *inode = NULL; struct buffer_head *bh; struct bfs_dirent *de; struct bfs_sb_info *info = BFS_SB(dir->i_sb); if (dentry->d_name.len > BFS_NAMELEN) return ERR_PTR(-ENAMETOOLONG); mutex_lock(&info->bfs_lock); bh = bfs_find_entry(dir, dentry->d_name.name, dentry->d_name.len, &de); if (bh) { unsigned long ino = (unsigned long)le16_to_cpu(de->ino); brelse(bh); inode = bfs_iget(dir->i_sb, ino); if (IS_ERR(inode)) { mutex_unlock(&info->bfs_lock); return ERR_CAST(inode); } } mutex_unlock(&info->bfs_lock); d_add(dentry, inode); return NULL; } static int bfs_link(struct dentry *old, struct inode *dir, struct dentry *new) { struct inode *inode = d_inode(old); struct bfs_sb_info *info = BFS_SB(inode->i_sb); int err; mutex_lock(&info->bfs_lock); err = bfs_add_entry(dir, new->d_name.name, new->d_name.len, inode->i_ino); if (err) { mutex_unlock(&info->bfs_lock); return err; } inc_nlink(inode); inode->i_ctime = CURRENT_TIME_SEC; mark_inode_dirty(inode); ihold(inode); d_instantiate(new, inode); mutex_unlock(&info->bfs_lock); return 0; } static int bfs_unlink(struct inode *dir, struct dentry *dentry) { int error = -ENOENT; struct inode *inode = d_inode(dentry); struct buffer_head *bh; struct bfs_dirent *de; struct bfs_sb_info *info = BFS_SB(inode->i_sb); mutex_lock(&info->bfs_lock); bh = bfs_find_entry(dir, dentry->d_name.name, dentry->d_name.len, &de); if (!bh || (le16_to_cpu(de->ino) != inode->i_ino)) goto out_brelse; if (!inode->i_nlink) { printf("unlinking non-existent file %s:%lu (nlink=%d)\n", inode->i_sb->s_id, inode->i_ino, inode->i_nlink); set_nlink(inode, 1); } de->ino = 0; mark_buffer_dirty_inode(bh, dir); dir->i_ctime = dir->i_mtime = CURRENT_TIME_SEC; mark_inode_dirty(dir); inode->i_ctime = dir->i_ctime; inode_dec_link_count(inode); error = 0; out_brelse: brelse(bh); mutex_unlock(&info->bfs_lock); return error; } static int bfs_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry) { struct inode *old_inode, *new_inode; struct buffer_head *old_bh, *new_bh; struct bfs_dirent *old_de, *new_de; struct bfs_sb_info *info; int error = -ENOENT; old_bh = new_bh = NULL; old_inode = d_inode(old_dentry); if (S_ISDIR(old_inode->i_mode)) return -EINVAL; info = BFS_SB(old_inode->i_sb); mutex_lock(&info->bfs_lock); old_bh = bfs_find_entry(old_dir, old_dentry->d_name.name, old_dentry->d_name.len, &old_de); if (!old_bh || (le16_to_cpu(old_de->ino) != old_inode->i_ino)) goto end_rename; error = -EPERM; new_inode = d_inode(new_dentry); new_bh = bfs_find_entry(new_dir, new_dentry->d_name.name, new_dentry->d_name.len, &new_de); if (new_bh && !new_inode) { brelse(new_bh); new_bh = NULL; } if (!new_bh) { error = bfs_add_entry(new_dir, new_dentry->d_name.name, new_dentry->d_name.len, old_inode->i_ino); if (error) goto end_rename; } old_de->ino = 0; old_dir->i_ctime = old_dir->i_mtime = CURRENT_TIME_SEC; mark_inode_dirty(old_dir); if (new_inode) { new_inode->i_ctime = CURRENT_TIME_SEC; inode_dec_link_count(new_inode); } mark_buffer_dirty_inode(old_bh, old_dir); error = 0; end_rename: mutex_unlock(&info->bfs_lock); brelse(old_bh); brelse(new_bh); return error; } const struct inode_operations bfs_dir_inops = { .create = bfs_create, .lookup = bfs_lookup, .link = bfs_link, .unlink = bfs_unlink, .rename = bfs_rename, }; static int bfs_add_entry(struct inode *dir, const unsigned char *name, int namelen, int ino) { struct buffer_head *bh; struct bfs_dirent *de; int block, sblock, eblock, off, pos; int i; dprintf("name=%s, namelen=%d\n", name, namelen); if (!namelen) return -ENOENT; if (namelen > BFS_NAMELEN) return -ENAMETOOLONG; sblock = BFS_I(dir)->i_sblock; eblock = BFS_I(dir)->i_eblock; for (block = sblock; block <= eblock; block++) { bh = sb_bread(dir->i_sb, block); if (!bh) return -EIO; for (off = 0; off < BFS_BSIZE; off += BFS_DIRENT_SIZE) { de = (struct bfs_dirent *)(bh->b_data + off); if (!de->ino) { pos = (block - sblock) * BFS_BSIZE + off; if (pos >= dir->i_size) { dir->i_size += BFS_DIRENT_SIZE; dir->i_ctime = CURRENT_TIME_SEC; } dir->i_mtime = CURRENT_TIME_SEC; mark_inode_dirty(dir); de->ino = cpu_to_le16((u16)ino); for (i = 0; i < BFS_NAMELEN; i++) de->name[i] = (i < namelen) ? name[i] : 0; mark_buffer_dirty_inode(bh, dir); brelse(bh); return 0; } } brelse(bh); } return -ENOSPC; } static inline int bfs_namecmp(int len, const unsigned char *name, const char *buffer) { if ((len < BFS_NAMELEN) && buffer[len]) return 0; return !memcmp(name, buffer, len); } static struct buffer_head *bfs_find_entry(struct inode *dir, const unsigned char *name, int namelen, struct bfs_dirent **res_dir) { unsigned long block = 0, offset = 0; struct buffer_head *bh = NULL; struct bfs_dirent *de; *res_dir = NULL; if (namelen > BFS_NAMELEN) return NULL; while (block * BFS_BSIZE + offset < dir->i_size) { if (!bh) { bh = sb_bread(dir->i_sb, BFS_I(dir)->i_sblock + block); if (!bh) { block++; continue; } } de = (struct bfs_dirent *)(bh->b_data + offset); offset += BFS_DIRENT_SIZE; if (le16_to_cpu(de->ino) && bfs_namecmp(namelen, name, de->name)) { *res_dir = de; return bh; } if (offset < bh->b_size) continue; brelse(bh); bh = NULL; offset = 0; block++; } brelse(bh); return NULL; }
{ "language": "C" }
/** * Mandelbulber v2, a 3D fractal generator _%}}i*<. ____ _______ * Copyright (C) 2020 Mandelbulber Team _>]|=||i=i<, / __ \___ ___ ___ / ___/ / * \><||i|=>>%) / /_/ / _ \/ -_) _ \/ /__/ /__ * This file is part of Mandelbulber. )<=i=]=|=i<> \____/ .__/\__/_//_/\___/____/ * The project is licensed under GPLv3, -<>>=|><|||` /_/ * see also COPYING file in this folder. ~+{i%+++ * * DIFSHextgrid2Iteration fragmentarium code, mdifs by knighty (jan 2012) * and darkbeams optimized verion @reference * http://www.fractalforums.com/mandelbulb-3d/custom-formulas-and-transforms-release-t17106/ * "Beautiful iso-surface made of a hexagonal grid of tubes. * Taken from K3DSurf forum, posted by user abdelhamid belaid." * This file has been autogenerated by tools/populateUiInformation.php * from the file "fractal_difs_hextgrid2.cpp" in the folder formula/definition * D O N O T E D I T T H I S F I L E ! */ REAL4 DIFSHextgrid2Iteration(REAL4 z, __constant sFractalCl *fractal, sExtendedAuxCl *aux) { REAL colorAdd = 0.0f; // sphere inversion if (fractal->transformCommon.sphereInversionEnabledFalse && aux->i >= fractal->transformCommon.startIterationsX && aux->i < fractal->transformCommon.stopIterations1) { z += fractal->transformCommon.offset000; REAL rr = dot(z, z); z *= fractal->transformCommon.scaleG1 / rr; aux->DE *= (fractal->transformCommon.scaleG1 / rr); z += fractal->transformCommon.additionConstant000 - fractal->transformCommon.offset000; z *= fractal->transformCommon.scaleA1; aux->DE *= fractal->transformCommon.scaleA1; } if (fractal->transformCommon.functionEnabledCFalse && aux->i >= fractal->transformCommon.startIterationsC && aux->i < fractal->transformCommon.stopIterationsC1) { REAL Tp = fractal->transformCommon.offset2; z.x = fmod(fabs(z.x) + Tp, 2.0f * Tp) - Tp; Tp = fractal->transformCommon.offsetA2; z.y = fmod(fabs(z.y) + Tp, 2.0f * Tp) - Tp; } // scale if (aux->i >= fractal->transformCommon.startIterationsS && aux->i < fractal->transformCommon.stopIterationsS) { REAL useScale = aux->actualScaleA + fractal->transformCommon.scale2; z *= useScale; aux->DE = aux->DE * fabs(useScale); // scale vary if (fractal->transformCommon.functionEnabledKFalse && aux->i >= fractal->transformCommon.startIterationsK && aux->i < fractal->transformCommon.stopIterationsK) { // update actualScaleA for next iteration REAL vary = fractal->transformCommon.scaleVary0 * (fabs(aux->actualScaleA) - fractal->transformCommon.scaleC1); aux->actualScaleA -= vary; } } // offset z += fractal->transformCommon.offset001; // rotation if (fractal->transformCommon.functionEnabledRFalse && aux->i >= fractal->transformCommon.startIterationsR && aux->i < fractal->transformCommon.stopIterationsR) { z = Matrix33MulFloat4(fractal->transformCommon.rotationMatrix, z); } // DE REAL colorDist = aux->dist; REAL4 zc = z; // Hextgrid2 if (aux->i >= fractal->transformCommon.startIterations && aux->i < fractal->transformCommon.stopIterations) { REAL size = fractal->transformCommon.scale1; REAL hexD = 0.0f; zc.z /= fractal->transformCommon.scaleF1; REAL cosPi6 = native_cos(M_PI_F / 6.0f); REAL yFloor = fabs(zc.y - size * floor(zc.y / size + 0.5f)); REAL xFloor = fabs(zc.x - size * 1.5f / cosPi6 * floor(zc.x / size / 1.5f * cosPi6 + 0.5f)); REAL gridMax = max(yFloor, xFloor * cosPi6 + yFloor * native_sin(M_PI_F / 6.0f)); REAL gridMin = min(gridMax - size * 0.5f, yFloor); if (!fractal->transformCommon.functionEnabledJFalse) hexD = native_sqrt(gridMin * gridMin + zc.z * zc.z); else hexD = max(fabs(gridMin), fabs(zc.z)); hexD -= fractal->transformCommon.offset0005; aux->dist = min(aux->dist, hexD / (aux->DE + 1.0f)); } // aux->color if (fractal->foldColor.auxColorEnabled) { if (fractal->foldColor.auxColorEnabledFalse) { colorAdd += fractal->foldColor.difs0000.x * fabs(z.x * z.y); colorAdd += fractal->foldColor.difs0000.y * max(z.x, z.y); } colorAdd += fractal->foldColor.difs1; if (fractal->foldColor.auxColorEnabledA) { if (colorDist != aux->dist) aux->color += colorAdd; } else aux->color += colorAdd; } return z; }
{ "language": "C" }
/* * Copyright(c) 1997-2001 id Software, Inc. * Copyright(c) 2002 The Quakeforge Project. * Copyright(c) 2006 Quetoo. * * 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 <signal.h> #include <SDL_thread.h> #include "mem.h" #if defined(SUPER_MEMORY_CHECKS) #define MAX_MEMORY_STACK 32 #if defined(WIN32) #include <DbgHelp.h> #endif #endif #define MEM_MAGIC 0x69696969 typedef uint32_t mem_magic_t; typedef struct mem_block_s { mem_magic_t magic; mem_tag_t tag; // for group free struct mem_block_s *parent; GSList *children; size_t size; #if defined(SUPER_MEMORY_CHECKS) void *stack[MAX_MEMORY_STACK]; #endif } mem_block_t; typedef struct { mem_magic_t magic; } mem_footer_t; typedef struct { GHashTable *blocks; size_t size; SDL_mutex *lock; } mem_state_t; static mem_state_t mem_state; #if defined(SUPER_MEMORY_CHECKS) /** * @brief */ static void Mem_SetStack(mem_block_t *block) { #if defined(WIN32) CaptureStackBackTrace(0, MAX_MEMORY_STACK, block->stack, NULL); #elif HAVE_EXECINFO backtrace(block->stack, MAX_MEMORY_STACK); #endif } /** * @brief */ static void Mem_Print(const mem_block_t *block, const char *why) { #if defined(WIN32) && defined(SUPER_MEMORY_PRINTS) static char str[MAX_STRING_CHARS]; g_snprintf(str, sizeof(str), "%s block 0x%" PRIXPTR " tag %i\n", why, (ULONG64) (block + 1), block->tag); OutputDebugString(str); for (int32_t i = 3; i < 5; i++) { if (!block->stack[i]) { break; } g_snprintf(str, sizeof(str), " [0x%" PRIXPTR "]\n", (ULONG64) (block->stack[i])); OutputDebugString(str); } #else #endif } #endif /** * @brief Throws a fatal error if the specified memory block is non-NULL but * not owned by the memory subsystem. */ static mem_block_t *Mem_CheckMagic(void *p) { mem_block_t *b = NULL; if (p) { b = ((mem_block_t *) p) - 1; if (b->magic != MEM_MAGIC) { fprintf(stderr, "Invalid magic (%d) for %p\n", b->magic, p); raise(SIGABRT); } mem_footer_t *footer = (mem_footer_t *) (((byte *) p) + b->size); if (footer->magic != (MEM_MAGIC + b->size)) { fprintf(stderr, "Invalid footer magic (%d) for %p\n", b->magic, p); raise(SIGABRT); } } return b; } /** * @brief */ void Mem_Check(void *p) { Mem_CheckMagic(p); } /** * @brief Recursively frees linked managed memory. */ static void Mem_Free_(mem_block_t *b) { #if defined(SUPER_MEMORY_CHECKS) Mem_Print(b, "Freeing"); #endif // recurse down the tree, freeing children if (b->children) { g_slist_free_full(b->children, (GDestroyNotify) Mem_Free_); } // decrement the pool size and free the memory mem_state.size -= b->size; free(b); } /** * @brief Free an allocation of managed memory. Any child objects are * automatically freed as well. */ void Mem_Free(void *p) { if (p) { mem_block_t *b = Mem_CheckMagic(p); SDL_mutexP(mem_state.lock); if (b->parent) { b->parent->children = g_slist_remove(b->parent->children, b); } else { g_hash_table_remove(mem_state.blocks, (gconstpointer) b); } Mem_Free_(b); SDL_mutexV(mem_state.lock); } } /** * @brief Free all managed items allocated with the specified tag. */ void Mem_FreeTag(mem_tag_t tag) { GHashTableIter it; gpointer key, value; SDL_mutexP(mem_state.lock); g_hash_table_iter_init(&it, mem_state.blocks); while (g_hash_table_iter_next(&it, &key, &value)) { mem_block_t *b = (mem_block_t *) key; if (tag == MEM_TAG_ALL || b->tag == tag) { g_hash_table_iter_remove(&it); Mem_Free_(b); } } SDL_mutexV(mem_state.lock); } /** * @brief Returns the total size of a memory block. */ static size_t Mem_BlockSize(const size_t size) { return size + sizeof(mem_block_t) + sizeof(mem_footer_t); } /** * @brief Performs the grunt work of allocating a mem_block_t and inserting it * into the managed memory structures. Note that parent should be a pointer to * a previously allocated structure, and not to a mem_block_t. * * @param size The number of bytes to allocate. * @param tag The tag to allocate with (e.g. MEM_TAG_DEFAULT). * @param parent The parent to link this allocation to. * * @return A block of managed memory initialized to 0x0. */ static void *Mem_Malloc_(size_t size, mem_tag_t tag, void *parent) { mem_block_t *b, *p = Mem_CheckMagic(parent); // allocate the block plus the desired size const size_t s = Mem_BlockSize(size); if (!(b = calloc(s, 1))) { fprintf(stderr, "Failed to allocate %u bytes\n", (uint32_t) s); raise(SIGABRT); return NULL; } b->magic = MEM_MAGIC; b->tag = tag; b->parent = p; b->size = size; void *data = (void *) (b + 1); mem_footer_t *footer = (mem_footer_t *) (((byte *) data) + size); footer->magic = (mem_magic_t) (MEM_MAGIC + b->size); // insert it into the managed memory structures SDL_mutexP(mem_state.lock); if (b->parent) { b->parent->children = g_slist_prepend(b->parent->children, b); } else { g_hash_table_add(mem_state.blocks, b); } mem_state.size += size; #if defined(SUPER_MEMORY_CHECKS) Mem_SetStack(b); #endif SDL_mutexV(mem_state.lock); // return the address in front of the block return data; } /** * @brief Allocates a block of managed memory with the specified tag. * * @param size The number of bytes to allocate. * @param tag Tags allow related objects to be freed in bulk e.g. when a * subsystem quits. * * @return A block of managed memory initialized to 0x0. */ void *Mem_TagMalloc(size_t size, mem_tag_t tag) { return Mem_Malloc_(size, tag, NULL); } /** * @brief Allocates a block of managed memory with the specified parent. * * @param size The number of bytes to allocate. * @param parent The parent block previously allocated through Mem_Malloc / * Mem_TagMalloc. The returned block will automatically be released when the * parent is freed through Mem_Free. * * @return A block of managed memory initialized to 0x0. */ void *Mem_LinkMalloc(size_t size, void *parent) { return Mem_Malloc_(size, MEM_TAG_DEFAULT, parent); } /** * @brief Allocates a block of managed memory. All managed memory is freed when * the game exits, but may be explicitly freed with Mem_Free. * * @return A block of memory initialized to 0x0. */ void *Mem_Malloc(size_t size) { return Mem_Malloc_(size, MEM_TAG_DEFAULT, NULL); } /** * @brief Reallocates a block of memory with a new size. * * @return The new pointer to the resized memory. Do not try to write to p after * calling this function, the results are undefined! */ void *Mem_Realloc(void *p, size_t size) { if (!p) { return Mem_Malloc(size); } mem_block_t *b = Mem_CheckMagic(p), *new_b; // no change to size if (b->size == size) { return (void *) (b + 1); } // allocate the block plus the desired size const size_t old_size = b->size; const size_t s = Mem_BlockSize(size); b->size = size; #if defined(SUPER_MEMORY_PRINTS) Mem_Print(b, "Reallocating"); #endif if (!(new_b = realloc(b, s))) { fprintf(stderr, "Failed to re-allocate %u bytes\n", (uint32_t) s); raise(SIGABRT); return NULL; } void *data = (void *) (new_b + 1); mem_footer_t *footer = (mem_footer_t *) (((byte *) data) + size); footer->magic = (mem_magic_t) (MEM_MAGIC + new_b->size); SDL_mutexP(mem_state.lock); // re-seat us in our parent or in global hash list if (new_b->parent) { new_b->parent->children = g_slist_remove(new_b->parent->children, b); new_b->parent->children = g_slist_prepend(new_b->parent->children, new_b); } else { g_hash_table_remove(mem_state.blocks, b); g_hash_table_add(mem_state.blocks, new_b); } // change our childrens' parent pointers if (new_b->children) { for (GSList *children = new_b->children; children; children = children->next) { mem_block_t *child = (mem_block_t *) children->data; child->parent = new_b; } } mem_state.size -= old_size; mem_state.size += size; #if defined(SUPER_MEMORY_CHECKS) Mem_SetStack(new_b); #if defined(SUPER_MEMORY_PRINTS) Mem_Print(new_b, "Reallocated"); #endif #endif SDL_mutexV(mem_state.lock); return data; } /** * @brief Links the specified child to the given parent. The child will * subsequently be freed with the parent. * * @param child The child object, previously allocated with Mem_Malloc. * @param parent The parent object, previously allocated with Mem_Malloc. * * @return The child, for convenience. */ void *Mem_Link(void *child, void *parent) { mem_block_t *c = Mem_CheckMagic(child); mem_block_t *p = Mem_CheckMagic(parent); SDL_mutexP(mem_state.lock); if (c->parent) { c->parent->children = g_slist_remove(c->parent->children, c); } else { g_hash_table_remove(mem_state.blocks, c); } c->parent = p; p->children = g_slist_prepend(p->children, c); SDL_mutexV(mem_state.lock); return child; } /** * @return The current size (user bytes) of the zone allocation pool. */ size_t Mem_Size(void) { return mem_state.size; } /** * @brief Allocates and returns a copy of the specified string. */ char *Mem_TagCopyString(const char *in, mem_tag_t tag) { char *out; out = Mem_TagMalloc(strlen(in) + 1, tag); strcpy(out, in); return out; } /** * @brief Allocates and returns a copy of the specified string. */ char *Mem_CopyString(const char *in) { return Mem_TagCopyString(in, MEM_TAG_DEFAULT); } /** * @brief */ static gint Mem_Stats_Sort(gconstpointer a, gconstpointer b) { return (gint) (((const mem_stat_t *) b)->size - ((const mem_stat_t *) a)->size); } /** * @brief */ static size_t Mem_CalculateBlockSize(const mem_block_t *b) { size_t size = b->size; for (GSList *child = b->children; child; child = child->next) { size += Mem_CalculateBlockSize((const mem_block_t *) child->data); } return size; } /** * @brief Fetches stats about allocated memory to the console. */ GArray *Mem_Stats(void) { GHashTableIter it; gpointer key, value; SDL_mutexP(mem_state.lock); GArray *stat_array = g_array_new(false, true, sizeof(mem_stat_t)); stat_array = g_array_append_vals(stat_array, &(const mem_stat_t) { .tag = -1, .size = mem_state.size, .count = 0 }, 1); g_hash_table_iter_init(&it, mem_state.blocks); while (g_hash_table_iter_next(&it, &key, &value)) { const mem_block_t *b = (const mem_block_t *) key; mem_stat_t *stats = NULL; for (size_t i = 0; i < stat_array->len; i++) { mem_stat_t *stat_i = &g_array_index(stat_array, mem_stat_t, i); if (stat_i->tag == b->tag) { stats = stat_i; break; } } if (stats == NULL) { stat_array = g_array_append_vals(stat_array, &(const mem_stat_t) { .tag = b->tag, .size = Mem_CalculateBlockSize(b), .count = 1 }, 1); } else { stats->size += Mem_CalculateBlockSize(b); stats->count++; } } SDL_mutexV(mem_state.lock); g_array_sort(stat_array, Mem_Stats_Sort); return stat_array; } /** * @brief Initializes the managed memory subsystem. This should be one of the first * subsystems initialized by Quetoo. */ void Mem_Init(void) { memset(&mem_state, 0, sizeof(mem_state)); mem_state.blocks = g_hash_table_new(g_direct_hash, g_direct_equal); mem_state.lock = SDL_CreateMutex(); } /** * @brief Shuts down the managed memory subsystem. This should be one of the last * subsystems brought down by Quetoo. */ void Mem_Shutdown(void) { Mem_FreeTag(MEM_TAG_ALL); g_hash_table_destroy(mem_state.blocks); SDL_DestroyMutex(mem_state.lock); }
{ "language": "C" }
/* * linux/fs/nls/nls_koi8-u.c * * Charset koi8-u translation tables. * The Unicode to charset table has only exact mappings. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/nls.h> #include <linux/errno.h> static const wchar_t charset2uni[256] = { /* 0x00*/ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, /* 0x10*/ 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, /* 0x20*/ 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, /* 0x30*/ 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, /* 0x40*/ 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, /* 0x50*/ 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, /* 0x60*/ 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, /* 0x70*/ 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f, /* 0x80*/ 0x2500, 0x2502, 0x250c, 0x2510, 0x2514, 0x2518, 0x251c, 0x2524, 0x252c, 0x2534, 0x253c, 0x2580, 0x2584, 0x2588, 0x258c, 0x2590, /* 0x90*/ 0x2591, 0x2592, 0x2593, 0x2320, 0x25a0, 0x2219, 0x221a, 0x2248, 0x2264, 0x2265, 0x00a0, 0x2321, 0x00b0, 0x00b2, 0x00b7, 0x00f7, /* 0xa0*/ 0x2550, 0x2551, 0x2552, 0x0451, 0x0454, 0x2554, 0x0456, 0x0457, 0x2557, 0x2558, 0x2559, 0x255a, 0x255b, 0x0491, 0x255d, 0x255e, /* 0xb0*/ 0x255f, 0x2560, 0x2561, 0x0401, 0x0404, 0x2563, 0x0406, 0x0407, 0x2566, 0x2567, 0x2568, 0x2569, 0x256a, 0x0490, 0x256c, 0x00a9, /* 0xc0*/ 0x044e, 0x0430, 0x0431, 0x0446, 0x0434, 0x0435, 0x0444, 0x0433, 0x0445, 0x0438, 0x0439, 0x043a, 0x043b, 0x043c, 0x043d, 0x043e, /* 0xd0*/ 0x043f, 0x044f, 0x0440, 0x0441, 0x0442, 0x0443, 0x0436, 0x0432, 0x044c, 0x044b, 0x0437, 0x0448, 0x044d, 0x0449, 0x0447, 0x044a, /* 0xe0*/ 0x042e, 0x0410, 0x0411, 0x0426, 0x0414, 0x0415, 0x0424, 0x0413, 0x0425, 0x0418, 0x0419, 0x041a, 0x041b, 0x041c, 0x041d, 0x041e, /* 0xf0*/ 0x041f, 0x042f, 0x0420, 0x0421, 0x0422, 0x0423, 0x0416, 0x0412, 0x042c, 0x042b, 0x0417, 0x0428, 0x042d, 0x0429, 0x0427, 0x042a, }; static const unsigned char page00[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */ 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */ 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */ 0x9a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */ 0x00, 0xbf, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa8-0xaf */ 0x9c, 0x00, 0x9d, 0x00, 0x00, 0x00, 0x00, 0x9e, /* 0xb0-0xb7 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb8-0xbf */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc0-0xc7 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc8-0xcf */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd0-0xd7 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd8-0xdf */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe0-0xe7 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe8-0xef */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9f, /* 0xf0-0xf7 */ }; static const unsigned char page04[256] = { 0x00, 0xb3, 0x00, 0x00, 0xb4, 0x00, 0xb6, 0xb7, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0xe1, 0xe2, 0xf7, 0xe7, 0xe4, 0xe5, 0xf6, 0xfa, /* 0x10-0x17 */ 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, /* 0x18-0x1f */ 0xf2, 0xf3, 0xf4, 0xf5, 0xe6, 0xe8, 0xe3, 0xfe, /* 0x20-0x27 */ 0xfb, 0xfd, 0xff, 0xf9, 0xf8, 0xfc, 0xe0, 0xf1, /* 0x28-0x2f */ 0xc1, 0xc2, 0xd7, 0xc7, 0xc4, 0xc5, 0xd6, 0xda, /* 0x30-0x37 */ 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, /* 0x38-0x3f */ 0xd2, 0xd3, 0xd4, 0xd5, 0xc6, 0xc8, 0xc3, 0xde, /* 0x40-0x47 */ 0xdb, 0xdd, 0xdf, 0xd9, 0xd8, 0xdc, 0xc0, 0xd1, /* 0x48-0x4f */ 0x00, 0xa3, 0x00, 0x00, 0xa4, 0x00, 0xa6, 0xa7, /* 0x50-0x57 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0xbd, 0xad, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ }; static const unsigned char page22[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x00, 0x95, 0x96, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0x97, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */ 0x00, 0x00, 0x00, 0x00, 0x98, 0x99, 0x00, 0x00, /* 0x60-0x67 */ }; static const unsigned char page23[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x93, 0x9b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */ }; static const unsigned char page25[256] = { 0x80, 0x00, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x82, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x83, 0x00, 0x00, 0x00, 0x84, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x85, 0x00, 0x00, 0x00, 0x86, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0x87, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0x88, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0x89, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0x8a, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0xa0, 0xa1, 0xa2, 0x00, 0xa5, 0x00, 0x00, 0xa8, /* 0x50-0x57 */ 0xa9, 0xaa, 0xab, 0xac, 0x00, 0xae, 0xaf, 0xb0, /* 0x58-0x5f */ 0xb1, 0xb2, 0x00, 0xb5, 0x00, 0x00, 0xb8, 0xb9, /* 0x60-0x67 */ 0xba, 0xbb, 0xbc, 0x00, 0xbe, 0x00, 0x00, 0x00, /* 0x68-0x6f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */ 0x8b, 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0x8d, 0x00, 0x00, 0x00, 0x8e, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0x8f, 0x90, 0x91, 0x92, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */ 0x94, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */ }; static const unsigned char *const page_uni2charset[256] = { page00, NULL, NULL, NULL, page04, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, page22, page23, NULL, page25, NULL, NULL, }; static const unsigned char charset2lower[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x40-0x47 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x48-0x4f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x50-0x57 */ 0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */ 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */ 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */ 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */ 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */ 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */ 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */ 0xb0, 0xb1, 0xb2, 0xa3, 0xa4, 0xb5, 0xa6, 0xa7, /* 0xb0-0xb7 */ 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xad, 0xbe, 0xbf, /* 0xb8-0xbf */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */ 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */ 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xe0-0xe7 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xe8-0xef */ 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xf0-0xf7 */ 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xf8-0xff */ }; static const unsigned char charset2upper[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */ 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */ 0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */ 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */ 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */ 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */ 0xa0, 0xa1, 0xa2, 0xb3, 0xb4, 0xa5, 0xb6, 0xb7, /* 0xa0-0xa7 */ 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xbd, 0xae, 0xaf, /* 0xa8-0xaf */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */ 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */ 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0xc0-0xc7 */ 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xc8-0xcf */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xd0-0xd7 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xd8-0xdf */ 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0xe0-0xe7 */ 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xe8-0xef */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */ }; static int uni2char(wchar_t uni, unsigned char *out, int boundlen) { const unsigned char *uni2charset; unsigned char cl = uni & 0x00ff; unsigned char ch = (uni & 0xff00) >> 8; if (boundlen <= 0) return -ENAMETOOLONG; uni2charset = page_uni2charset[ch]; if (uni2charset && uni2charset[cl]) out[0] = uni2charset[cl]; else return -EINVAL; return 1; } static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni) { *uni = charset2uni[*rawstring]; if (*uni == 0x0000) return -EINVAL; return 1; } static struct nls_table table = { .charset = "koi8-u", .uni2char = uni2char, .char2uni = char2uni, .charset2lower = charset2lower, .charset2upper = charset2upper, .owner = THIS_MODULE, }; static int __init init_nls_koi8_u(void) { return register_nls(&table); } static void __exit exit_nls_koi8_u(void) { unregister_nls(&table); } module_init(init_nls_koi8_u) module_exit(exit_nls_koi8_u) MODULE_LICENSE("Dual BSD/GPL");
{ "language": "C" }
diff -rupN a/drivers/media/usb/em28xx/em28xx-cards.c b/drivers/media/usb/em28xx/em28xx-cards.c --- a/drivers/media/usb/em28xx/em28xx-cards.c 2015-02-23 14:54:18.000000000 +0100 +++ b/drivers/media/usb/em28xx/em28xx-cards.c 2015-02-12 16:46:54.000000000 +0100 @@ -448,6 +448,18 @@ static struct em28xx_reg_seq speedlink_v { -1, -1, -1, -1}, }; +static struct em28xx_reg_seq pctv_292e[] = { + {EM2874_R80_GPIO_P0_CTRL, 0xff, 0xff, 0}, + {0x0d, 0xff, 0xff, 950}, + {EM2874_R80_GPIO_P0_CTRL, 0xbd, 0xff, 100}, + {EM2874_R80_GPIO_P0_CTRL, 0xfd, 0xff, 410}, + {EM2874_R80_GPIO_P0_CTRL, 0x7d, 0xff, 300}, + {EM2874_R80_GPIO_P0_CTRL, 0x7c, 0xff, 60}, + {0x0d, 0x42, 0xff, 50}, + {EM2874_R5F_TS_ENABLE, 0x85, 0xff, 0}, + {-1, -1, -1, -1}, +}; + /* * Button definitions */ @@ -2157,6 +2169,17 @@ struct em28xx_board em28xx_boards[] = { .has_dvb = 1, .ir_codes = RC_MAP_PINNACLE_PCTV_HD, }, + /* 2013:025f PCTV tripleStick (292e). + * Empia EM28178, Silicon Labs Si2168, Silicon Labs Si2157 */ + [EM28178_BOARD_PCTV_292E] = { + .name = "PCTV tripleStick (292e)", + .def_i2c_bus = 1, + .i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE | EM28XX_I2C_FREQ_400_KHZ, + .tuner_type = TUNER_ABSENT, + .tuner_gpio = pctv_292e, + .has_dvb = 1, + .ir_codes = RC_MAP_PINNACLE_PCTV_HD, + }, }; EXPORT_SYMBOL_GPL(em28xx_boards); @@ -2330,6 +2353,8 @@ struct usb_device_id em28xx_id_table[] = .driver_info = EM2765_BOARD_SPEEDLINK_VAD_LAPLACE }, { USB_DEVICE(0x2013, 0x0258), .driver_info = EM28178_BOARD_PCTV_461E }, + { USB_DEVICE(0x2013, 0x025f), + .driver_info = EM28178_BOARD_PCTV_292E }, { }, }; MODULE_DEVICE_TABLE(usb, em28xx_id_table); diff -rupN a/drivers/media/usb/em28xx/em28xx-dvb.c b/drivers/media/usb/em28xx/em28xx-dvb.c --- a/drivers/media/usb/em28xx/em28xx-dvb.c 2014-11-02 14:07:11.000000000 +0100 +++ b/drivers/media/usb/em28xx/em28xx-dvb.c 2015-02-24 16:39:35.000000000 +0100 @@ -53,6 +53,8 @@ #include "mb86a20s.h" #include "m88ds3103.h" #include "m88ts2022.h" +#include "si2168.h" +#include "si2157.h" MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@infradead.org>"); MODULE_LICENSE("GPL"); @@ -91,6 +93,7 @@ struct em28xx_dvb { struct semaphore pll_mutex; bool dont_attach_fe1; int lna_gpio; + struct i2c_client *i2c_client_demod; struct i2c_client *i2c_client_tuner; }; @@ -719,6 +722,21 @@ static int em28xx_pctv_290e_set_lna(stru #endif } +static int em28xx_pctv_292e_set_lna(struct dvb_frontend *fe) +{ + struct dtv_frontend_properties *c = &fe->dtv_property_cache; + struct em28xx_i2c_bus *i2c_bus = fe->dvb->priv; + struct em28xx *dev = i2c_bus->dev; + u8 lna; + + if (c->lna == 1) + lna = 0x01; + else + lna = 0x00; + + return em28xx_write_reg_bits(dev, EM2874_R80_GPIO_P0_CTRL, lna, 0x01); +} + static int em28xx_mt352_terratec_xs_init(struct dvb_frontend *fe) { /* Values extracted from a USB trace of the Terratec Windows driver */ @@ -1413,6 +1431,66 @@ static int em28xx_dvb_init(struct em28xx } } break; + case EM28178_BOARD_PCTV_292E: + { + struct i2c_adapter *adapter; + struct i2c_client *client; + struct i2c_board_info info; + struct si2168_config si2168_config; + struct si2157_config si2157_config; + + /* attach demod */ + memset(&si2168_config, 0, sizeof(si2168_config)); + si2168_config.i2c_adapter = &adapter; + si2168_config.fe = &dvb->fe[0]; + si2168_config.ts_mode = SI2168_TS_PARALLEL; + memset(&info, 0, sizeof(struct i2c_board_info)); + strlcpy(info.type, "si2168", I2C_NAME_SIZE); + info.addr = 0x64; + info.platform_data = &si2168_config; + request_module(info.type); + client = i2c_new_device(&dev->i2c_adap[dev->def_i2c_bus], &info); + if (client == NULL || client->dev.driver == NULL) { + result = -ENODEV; + goto out_free; + } + + if (!try_module_get(client->dev.driver->owner)) { + i2c_unregister_device(client); + result = -ENODEV; + goto out_free; + } + + dvb->i2c_client_demod = client; + + /* attach tuner */ + memset(&si2157_config, 0, sizeof(si2157_config)); + si2157_config.fe = dvb->fe[0]; + memset(&info, 0, sizeof(struct i2c_board_info)); + strlcpy(info.type, "si2157", I2C_NAME_SIZE); + info.addr = 0x60; + info.platform_data = &si2157_config; + request_module(info.type); + client = i2c_new_device(adapter, &info); + if (client == NULL || client->dev.driver == NULL) { + module_put(dvb->i2c_client_demod->dev.driver->owner); + i2c_unregister_device(dvb->i2c_client_demod); + result = -ENODEV; + goto out_free; + } + + if (!try_module_get(client->dev.driver->owner)) { + i2c_unregister_device(client); + module_put(dvb->i2c_client_demod->dev.driver->owner); + i2c_unregister_device(dvb->i2c_client_demod); + result = -ENODEV; + goto out_free; + } + + dvb->i2c_client_tuner = client; + dvb->fe[0]->ops.set_lna = em28xx_pctv_292e_set_lna; + } + break; default: em28xx_errdev("/2: The frontend of your DVB/ATSC card" " isn't supported yet\n"); @@ -1485,6 +1563,10 @@ static int em28xx_dvb_fini(struct em28xx } i2c_release_client(dvb->i2c_client_tuner); + /* remove I2C demod */ + if (dvb->i2c_client_demod) { + i2c_unregister_device(dvb->i2c_client_demod); + } em28xx_unregister_dvb(dvb); kfree(dvb); dev->dvb = NULL; diff -rupN a/drivers/media/usb/em28xx/em28xx.h b/drivers/media/usb/em28xx/em28xx.h --- a/drivers/media/usb/em28xx/em28xx.h 2014-11-02 14:07:11.000000000 +0100 +++ b/drivers/media/usb/em28xx/em28xx.h 2015-02-23 15:28:11.000000000 +0100 @@ -137,6 +137,7 @@ #define EM2874_BOARD_KWORLD_UB435Q_V2 90 #define EM2765_BOARD_SPEEDLINK_VAD_LAPLACE 91 #define EM28178_BOARD_PCTV_461E 92 +#define EM28178_BOARD_PCTV_292E 94 /* Limits minimum and default number of buffers */ #define EM28XX_MIN_BUF 4 diff -rupN a/drivers/media/usb/em28xx/Kconfig b/drivers/media/usb/em28xx/Kconfig --- a/drivers/media/usb/em28xx/Kconfig 2014-11-02 14:07:11.000000000 +0100 +++ b/drivers/media/usb/em28xx/Kconfig 2015-02-12 16:46:54.000000000 +0100 @@ -55,6 +55,8 @@ config VIDEO_EM28XX_DVB select MEDIA_TUNER_TDA18271 if MEDIA_SUBDRV_AUTOSELECT select DVB_M88DS3103 if MEDIA_SUBDRV_AUTOSELECT select MEDIA_TUNER_M88TS2022 if MEDIA_SUBDRV_AUTOSELECT + select DVB_SI2168 if MEDIA_SUBDRV_AUTOSELECT + select MEDIA_TUNER_SI2157 if MEDIA_SUBDRV_AUTOSELECT ---help--- This adds support for DVB cards based on the Empiatech em28xx chips.
{ "language": "C" }
/**************************************************************************** * Driver for Solarflare network controllers and boards * Copyright 2015 Solarflare Communications 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, incorporated herein by reference. */ #include <linux/etherdevice.h> #include <linux/pci.h> #include <linux/module.h> #include "net_driver.h" #include "ef10_sriov.h" #include "efx.h" #include "nic.h" #include "mcdi_pcol.h" static int efx_ef10_evb_port_assign(struct efx_nic *efx, unsigned int port_id, unsigned int vf_fn) { MCDI_DECLARE_BUF(inbuf, MC_CMD_EVB_PORT_ASSIGN_IN_LEN); struct efx_ef10_nic_data *nic_data = efx->nic_data; MCDI_SET_DWORD(inbuf, EVB_PORT_ASSIGN_IN_PORT_ID, port_id); MCDI_POPULATE_DWORD_2(inbuf, EVB_PORT_ASSIGN_IN_FUNCTION, EVB_PORT_ASSIGN_IN_PF, nic_data->pf_index, EVB_PORT_ASSIGN_IN_VF, vf_fn); return efx_mcdi_rpc(efx, MC_CMD_EVB_PORT_ASSIGN, inbuf, sizeof(inbuf), NULL, 0, NULL); } static int efx_ef10_vswitch_alloc(struct efx_nic *efx, unsigned int port_id, unsigned int vswitch_type) { MCDI_DECLARE_BUF(inbuf, MC_CMD_VSWITCH_ALLOC_IN_LEN); int rc; MCDI_SET_DWORD(inbuf, VSWITCH_ALLOC_IN_UPSTREAM_PORT_ID, port_id); MCDI_SET_DWORD(inbuf, VSWITCH_ALLOC_IN_TYPE, vswitch_type); MCDI_SET_DWORD(inbuf, VSWITCH_ALLOC_IN_NUM_VLAN_TAGS, 2); MCDI_POPULATE_DWORD_1(inbuf, VSWITCH_ALLOC_IN_FLAGS, VSWITCH_ALLOC_IN_FLAG_AUTO_PORT, 0); /* Quietly try to allocate 2 VLAN tags */ rc = efx_mcdi_rpc_quiet(efx, MC_CMD_VSWITCH_ALLOC, inbuf, sizeof(inbuf), NULL, 0, NULL); /* If 2 VLAN tags is too many, revert to trying with 1 VLAN tags */ if (rc == -EPROTO) { MCDI_SET_DWORD(inbuf, VSWITCH_ALLOC_IN_NUM_VLAN_TAGS, 1); rc = efx_mcdi_rpc(efx, MC_CMD_VSWITCH_ALLOC, inbuf, sizeof(inbuf), NULL, 0, NULL); } else if (rc) { efx_mcdi_display_error(efx, MC_CMD_VSWITCH_ALLOC, MC_CMD_VSWITCH_ALLOC_IN_LEN, NULL, 0, rc); } return rc; } static int efx_ef10_vswitch_free(struct efx_nic *efx, unsigned int port_id) { MCDI_DECLARE_BUF(inbuf, MC_CMD_VSWITCH_FREE_IN_LEN); MCDI_SET_DWORD(inbuf, VSWITCH_FREE_IN_UPSTREAM_PORT_ID, port_id); return efx_mcdi_rpc(efx, MC_CMD_VSWITCH_FREE, inbuf, sizeof(inbuf), NULL, 0, NULL); } static int efx_ef10_vport_alloc(struct efx_nic *efx, unsigned int port_id_in, unsigned int vport_type, u16 vlan, unsigned int *port_id_out) { MCDI_DECLARE_BUF(inbuf, MC_CMD_VPORT_ALLOC_IN_LEN); MCDI_DECLARE_BUF(outbuf, MC_CMD_VPORT_ALLOC_OUT_LEN); size_t outlen; int rc; EFX_WARN_ON_PARANOID(!port_id_out); MCDI_SET_DWORD(inbuf, VPORT_ALLOC_IN_UPSTREAM_PORT_ID, port_id_in); MCDI_SET_DWORD(inbuf, VPORT_ALLOC_IN_TYPE, vport_type); MCDI_SET_DWORD(inbuf, VPORT_ALLOC_IN_NUM_VLAN_TAGS, (vlan != EFX_EF10_NO_VLAN)); MCDI_POPULATE_DWORD_1(inbuf, VPORT_ALLOC_IN_FLAGS, VPORT_ALLOC_IN_FLAG_AUTO_PORT, 0); if (vlan != EFX_EF10_NO_VLAN) MCDI_POPULATE_DWORD_1(inbuf, VPORT_ALLOC_IN_VLAN_TAGS, VPORT_ALLOC_IN_VLAN_TAG_0, vlan); rc = efx_mcdi_rpc(efx, MC_CMD_VPORT_ALLOC, inbuf, sizeof(inbuf), outbuf, sizeof(outbuf), &outlen); if (rc) return rc; if (outlen < MC_CMD_VPORT_ALLOC_OUT_LEN) return -EIO; *port_id_out = MCDI_DWORD(outbuf, VPORT_ALLOC_OUT_VPORT_ID); return 0; } static int efx_ef10_vport_free(struct efx_nic *efx, unsigned int port_id) { MCDI_DECLARE_BUF(inbuf, MC_CMD_VPORT_FREE_IN_LEN); MCDI_SET_DWORD(inbuf, VPORT_FREE_IN_VPORT_ID, port_id); return efx_mcdi_rpc(efx, MC_CMD_VPORT_FREE, inbuf, sizeof(inbuf), NULL, 0, NULL); } static void efx_ef10_sriov_free_vf_vports(struct efx_nic *efx) { struct efx_ef10_nic_data *nic_data = efx->nic_data; int i; if (!nic_data->vf) return; for (i = 0; i < efx->vf_count; i++) { struct ef10_vf *vf = nic_data->vf + i; /* If VF is assigned, do not free the vport */ if (vf->pci_dev && vf->pci_dev->dev_flags & PCI_DEV_FLAGS_ASSIGNED) continue; if (vf->vport_assigned) { efx_ef10_evb_port_assign(efx, EVB_PORT_ID_NULL, i); vf->vport_assigned = 0; } if (!is_zero_ether_addr(vf->mac)) { efx_ef10_vport_del_mac(efx, vf->vport_id, vf->mac); eth_zero_addr(vf->mac); } if (vf->vport_id) { efx_ef10_vport_free(efx, vf->vport_id); vf->vport_id = 0; } vf->efx = NULL; } } static void efx_ef10_sriov_free_vf_vswitching(struct efx_nic *efx) { struct efx_ef10_nic_data *nic_data = efx->nic_data; efx_ef10_sriov_free_vf_vports(efx); kfree(nic_data->vf); nic_data->vf = NULL; } static int efx_ef10_sriov_assign_vf_vport(struct efx_nic *efx, unsigned int vf_i) { struct efx_ef10_nic_data *nic_data = efx->nic_data; struct ef10_vf *vf = nic_data->vf + vf_i; int rc; if (WARN_ON_ONCE(!nic_data->vf)) return -EOPNOTSUPP; rc = efx_ef10_vport_alloc(efx, EVB_PORT_ID_ASSIGNED, MC_CMD_VPORT_ALLOC_IN_VPORT_TYPE_NORMAL, vf->vlan, &vf->vport_id); if (rc) return rc; rc = efx_ef10_vport_add_mac(efx, vf->vport_id, vf->mac); if (rc) { eth_zero_addr(vf->mac); return rc; } rc = efx_ef10_evb_port_assign(efx, vf->vport_id, vf_i); if (rc) return rc; vf->vport_assigned = 1; return 0; } static int efx_ef10_sriov_alloc_vf_vswitching(struct efx_nic *efx) { struct efx_ef10_nic_data *nic_data = efx->nic_data; unsigned int i; int rc; nic_data->vf = kcalloc(efx->vf_count, sizeof(struct ef10_vf), GFP_KERNEL); if (!nic_data->vf) return -ENOMEM; for (i = 0; i < efx->vf_count; i++) { random_ether_addr(nic_data->vf[i].mac); nic_data->vf[i].efx = NULL; nic_data->vf[i].vlan = EFX_EF10_NO_VLAN; rc = efx_ef10_sriov_assign_vf_vport(efx, i); if (rc) goto fail; } return 0; fail: efx_ef10_sriov_free_vf_vports(efx); kfree(nic_data->vf); nic_data->vf = NULL; return rc; } static int efx_ef10_sriov_restore_vf_vswitching(struct efx_nic *efx) { unsigned int i; int rc; for (i = 0; i < efx->vf_count; i++) { rc = efx_ef10_sriov_assign_vf_vport(efx, i); if (rc) goto fail; } return 0; fail: efx_ef10_sriov_free_vf_vswitching(efx); return rc; } static int efx_ef10_vadaptor_alloc_set_features(struct efx_nic *efx) { struct efx_ef10_nic_data *nic_data = efx->nic_data; u32 port_flags; int rc; rc = efx_ef10_vadaptor_alloc(efx, nic_data->vport_id); if (rc) goto fail_vadaptor_alloc; rc = efx_ef10_vadaptor_query(efx, nic_data->vport_id, &port_flags, NULL, NULL); if (rc) goto fail_vadaptor_query; if (port_flags & (1 << MC_CMD_VPORT_ALLOC_IN_FLAG_VLAN_RESTRICT_LBN)) efx->fixed_features |= NETIF_F_HW_VLAN_CTAG_FILTER; else efx->fixed_features &= ~NETIF_F_HW_VLAN_CTAG_FILTER; return 0; fail_vadaptor_query: efx_ef10_vadaptor_free(efx, EVB_PORT_ID_ASSIGNED); fail_vadaptor_alloc: return rc; } /* On top of the default firmware vswitch setup, create a VEB vswitch and * expansion vport for use by this function. */ int efx_ef10_vswitching_probe_pf(struct efx_nic *efx) { struct efx_ef10_nic_data *nic_data = efx->nic_data; struct net_device *net_dev = efx->net_dev; int rc; if (pci_sriov_get_totalvfs(efx->pci_dev) <= 0) { /* vswitch not needed as we have no VFs */ efx_ef10_vadaptor_alloc_set_features(efx); return 0; } rc = efx_ef10_vswitch_alloc(efx, EVB_PORT_ID_ASSIGNED, MC_CMD_VSWITCH_ALLOC_IN_VSWITCH_TYPE_VEB); if (rc) goto fail1; rc = efx_ef10_vport_alloc(efx, EVB_PORT_ID_ASSIGNED, MC_CMD_VPORT_ALLOC_IN_VPORT_TYPE_NORMAL, EFX_EF10_NO_VLAN, &nic_data->vport_id); if (rc) goto fail2; rc = efx_ef10_vport_add_mac(efx, nic_data->vport_id, net_dev->dev_addr); if (rc) goto fail3; ether_addr_copy(nic_data->vport_mac, net_dev->dev_addr); rc = efx_ef10_vadaptor_alloc_set_features(efx); if (rc) goto fail4; return 0; fail4: efx_ef10_vport_del_mac(efx, nic_data->vport_id, nic_data->vport_mac); eth_zero_addr(nic_data->vport_mac); fail3: efx_ef10_vport_free(efx, nic_data->vport_id); nic_data->vport_id = EVB_PORT_ID_ASSIGNED; fail2: efx_ef10_vswitch_free(efx, EVB_PORT_ID_ASSIGNED); fail1: return rc; } int efx_ef10_vswitching_probe_vf(struct efx_nic *efx) { return efx_ef10_vadaptor_alloc_set_features(efx); } int efx_ef10_vswitching_restore_pf(struct efx_nic *efx) { struct efx_ef10_nic_data *nic_data = efx->nic_data; int rc; if (!nic_data->must_probe_vswitching) return 0; rc = efx_ef10_vswitching_probe_pf(efx); if (rc) goto fail; rc = efx_ef10_sriov_restore_vf_vswitching(efx); if (rc) goto fail; nic_data->must_probe_vswitching = false; fail: return rc; } int efx_ef10_vswitching_restore_vf(struct efx_nic *efx) { struct efx_ef10_nic_data *nic_data = efx->nic_data; int rc; if (!nic_data->must_probe_vswitching) return 0; rc = efx_ef10_vadaptor_free(efx, EVB_PORT_ID_ASSIGNED); if (rc) return rc; nic_data->must_probe_vswitching = false; return 0; } void efx_ef10_vswitching_remove_pf(struct efx_nic *efx) { struct efx_ef10_nic_data *nic_data = efx->nic_data; efx_ef10_sriov_free_vf_vswitching(efx); efx_ef10_vadaptor_free(efx, nic_data->vport_id); if (nic_data->vport_id == EVB_PORT_ID_ASSIGNED) return; /* No vswitch was ever created */ if (!is_zero_ether_addr(nic_data->vport_mac)) { efx_ef10_vport_del_mac(efx, nic_data->vport_id, efx->net_dev->dev_addr); eth_zero_addr(nic_data->vport_mac); } efx_ef10_vport_free(efx, nic_data->vport_id); nic_data->vport_id = EVB_PORT_ID_ASSIGNED; /* Only free the vswitch if no VFs are assigned */ if (!pci_vfs_assigned(efx->pci_dev)) efx_ef10_vswitch_free(efx, nic_data->vport_id); } void efx_ef10_vswitching_remove_vf(struct efx_nic *efx) { efx_ef10_vadaptor_free(efx, EVB_PORT_ID_ASSIGNED); } static int efx_ef10_pci_sriov_enable(struct efx_nic *efx, int num_vfs) { int rc = 0; struct pci_dev *dev = efx->pci_dev; efx->vf_count = num_vfs; rc = efx_ef10_sriov_alloc_vf_vswitching(efx); if (rc) goto fail1; rc = pci_enable_sriov(dev, num_vfs); if (rc) goto fail2; return 0; fail2: efx_ef10_sriov_free_vf_vswitching(efx); fail1: efx->vf_count = 0; netif_err(efx, probe, efx->net_dev, "Failed to enable SRIOV VFs\n"); return rc; } static int efx_ef10_pci_sriov_disable(struct efx_nic *efx, bool force) { struct pci_dev *dev = efx->pci_dev; unsigned int vfs_assigned = 0; vfs_assigned = pci_vfs_assigned(dev); if (vfs_assigned && !force) { netif_info(efx, drv, efx->net_dev, "VFs are assigned to guests; " "please detach them before disabling SR-IOV\n"); return -EBUSY; } if (!vfs_assigned) pci_disable_sriov(dev); efx_ef10_sriov_free_vf_vswitching(efx); efx->vf_count = 0; return 0; } int efx_ef10_sriov_configure(struct efx_nic *efx, int num_vfs) { if (num_vfs == 0) return efx_ef10_pci_sriov_disable(efx, false); else return efx_ef10_pci_sriov_enable(efx, num_vfs); } int efx_ef10_sriov_init(struct efx_nic *efx) { return 0; } void efx_ef10_sriov_fini(struct efx_nic *efx) { struct efx_ef10_nic_data *nic_data = efx->nic_data; unsigned int i; int rc; if (!nic_data->vf) { /* Remove any un-assigned orphaned VFs */ if (pci_num_vf(efx->pci_dev) && !pci_vfs_assigned(efx->pci_dev)) pci_disable_sriov(efx->pci_dev); return; } /* Remove any VFs in the host */ for (i = 0; i < efx->vf_count; ++i) { struct efx_nic *vf_efx = nic_data->vf[i].efx; if (vf_efx) vf_efx->pci_dev->driver->remove(vf_efx->pci_dev); } rc = efx_ef10_pci_sriov_disable(efx, true); if (rc) netif_dbg(efx, drv, efx->net_dev, "Disabling SRIOV was not successful rc=%d\n", rc); else netif_dbg(efx, drv, efx->net_dev, "SRIOV disabled\n"); } static int efx_ef10_vport_del_vf_mac(struct efx_nic *efx, unsigned int port_id, u8 *mac) { MCDI_DECLARE_BUF(inbuf, MC_CMD_VPORT_DEL_MAC_ADDRESS_IN_LEN); MCDI_DECLARE_BUF_ERR(outbuf); size_t outlen; int rc; MCDI_SET_DWORD(inbuf, VPORT_DEL_MAC_ADDRESS_IN_VPORT_ID, port_id); ether_addr_copy(MCDI_PTR(inbuf, VPORT_DEL_MAC_ADDRESS_IN_MACADDR), mac); rc = efx_mcdi_rpc(efx, MC_CMD_VPORT_DEL_MAC_ADDRESS, inbuf, sizeof(inbuf), outbuf, sizeof(outbuf), &outlen); return rc; } int efx_ef10_sriov_set_vf_mac(struct efx_nic *efx, int vf_i, u8 *mac) { struct efx_ef10_nic_data *nic_data = efx->nic_data; struct ef10_vf *vf; int rc; if (!nic_data->vf) return -EOPNOTSUPP; if (vf_i >= efx->vf_count) return -EINVAL; vf = nic_data->vf + vf_i; if (vf->efx) { efx_device_detach_sync(vf->efx); efx_net_stop(vf->efx->net_dev); down_write(&vf->efx->filter_sem); vf->efx->type->filter_table_remove(vf->efx); rc = efx_ef10_vadaptor_free(vf->efx, EVB_PORT_ID_ASSIGNED); if (rc) { up_write(&vf->efx->filter_sem); return rc; } } rc = efx_ef10_evb_port_assign(efx, EVB_PORT_ID_NULL, vf_i); if (rc) return rc; if (!is_zero_ether_addr(vf->mac)) { rc = efx_ef10_vport_del_vf_mac(efx, vf->vport_id, vf->mac); if (rc) return rc; } if (!is_zero_ether_addr(mac)) { rc = efx_ef10_vport_add_mac(efx, vf->vport_id, mac); if (rc) { eth_zero_addr(vf->mac); goto fail; } if (vf->efx) ether_addr_copy(vf->efx->net_dev->dev_addr, mac); } ether_addr_copy(vf->mac, mac); rc = efx_ef10_evb_port_assign(efx, vf->vport_id, vf_i); if (rc) goto fail; if (vf->efx) { /* VF cannot use the vport_id that the PF created */ rc = efx_ef10_vadaptor_alloc(vf->efx, EVB_PORT_ID_ASSIGNED); if (rc) { up_write(&vf->efx->filter_sem); return rc; } vf->efx->type->filter_table_probe(vf->efx); up_write(&vf->efx->filter_sem); efx_net_open(vf->efx->net_dev); efx_device_attach_if_not_resetting(vf->efx); } return 0; fail: eth_zero_addr(vf->mac); return rc; } int efx_ef10_sriov_set_vf_vlan(struct efx_nic *efx, int vf_i, u16 vlan, u8 qos) { struct efx_ef10_nic_data *nic_data = efx->nic_data; struct ef10_vf *vf; u16 old_vlan, new_vlan; int rc = 0, rc2 = 0; if (vf_i >= efx->vf_count) return -EINVAL; if (qos != 0) return -EINVAL; vf = nic_data->vf + vf_i; new_vlan = (vlan == 0) ? EFX_EF10_NO_VLAN : vlan; if (new_vlan == vf->vlan) return 0; if (vf->efx) { efx_device_detach_sync(vf->efx); efx_net_stop(vf->efx->net_dev); mutex_lock(&vf->efx->mac_lock); down_write(&vf->efx->filter_sem); vf->efx->type->filter_table_remove(vf->efx); rc = efx_ef10_vadaptor_free(vf->efx, EVB_PORT_ID_ASSIGNED); if (rc) goto restore_filters; } if (vf->vport_assigned) { rc = efx_ef10_evb_port_assign(efx, EVB_PORT_ID_NULL, vf_i); if (rc) { netif_warn(efx, drv, efx->net_dev, "Failed to change vlan on VF %d.\n", vf_i); netif_warn(efx, drv, efx->net_dev, "This is likely because the VF is bound to a driver in a VM.\n"); netif_warn(efx, drv, efx->net_dev, "Please unload the driver in the VM.\n"); goto restore_vadaptor; } vf->vport_assigned = 0; } if (!is_zero_ether_addr(vf->mac)) { rc = efx_ef10_vport_del_mac(efx, vf->vport_id, vf->mac); if (rc) goto restore_evb_port; } if (vf->vport_id) { rc = efx_ef10_vport_free(efx, vf->vport_id); if (rc) goto restore_mac; vf->vport_id = 0; } /* Do the actual vlan change */ old_vlan = vf->vlan; vf->vlan = new_vlan; /* Restore everything in reverse order */ rc = efx_ef10_vport_alloc(efx, EVB_PORT_ID_ASSIGNED, MC_CMD_VPORT_ALLOC_IN_VPORT_TYPE_NORMAL, vf->vlan, &vf->vport_id); if (rc) goto reset_nic_up_write; restore_mac: if (!is_zero_ether_addr(vf->mac)) { rc2 = efx_ef10_vport_add_mac(efx, vf->vport_id, vf->mac); if (rc2) { eth_zero_addr(vf->mac); goto reset_nic_up_write; } } restore_evb_port: rc2 = efx_ef10_evb_port_assign(efx, vf->vport_id, vf_i); if (rc2) goto reset_nic_up_write; else vf->vport_assigned = 1; restore_vadaptor: if (vf->efx) { rc2 = efx_ef10_vadaptor_alloc(vf->efx, EVB_PORT_ID_ASSIGNED); if (rc2) goto reset_nic_up_write; } restore_filters: if (vf->efx) { rc2 = vf->efx->type->filter_table_probe(vf->efx); if (rc2) goto reset_nic_up_write; up_write(&vf->efx->filter_sem); mutex_unlock(&vf->efx->mac_lock); rc2 = efx_net_open(vf->efx->net_dev); if (rc2) goto reset_nic; efx_device_attach_if_not_resetting(vf->efx); } return rc; reset_nic_up_write: if (vf->efx) { up_write(&vf->efx->filter_sem); mutex_unlock(&vf->efx->mac_lock); } reset_nic: if (vf->efx) { netif_err(efx, drv, efx->net_dev, "Failed to restore VF - scheduling reset.\n"); efx_schedule_reset(vf->efx, RESET_TYPE_DATAPATH); } else { netif_err(efx, drv, efx->net_dev, "Failed to restore the VF and cannot reset the VF " "- VF is not functional.\n"); netif_err(efx, drv, efx->net_dev, "Please reload the driver attached to the VF.\n"); } return rc ? rc : rc2; } int efx_ef10_sriov_set_vf_spoofchk(struct efx_nic *efx, int vf_i, bool spoofchk) { return spoofchk ? -EOPNOTSUPP : 0; } int efx_ef10_sriov_set_vf_link_state(struct efx_nic *efx, int vf_i, int link_state) { MCDI_DECLARE_BUF(inbuf, MC_CMD_LINK_STATE_MODE_IN_LEN); struct efx_ef10_nic_data *nic_data = efx->nic_data; BUILD_BUG_ON(IFLA_VF_LINK_STATE_AUTO != MC_CMD_LINK_STATE_MODE_IN_LINK_STATE_AUTO); BUILD_BUG_ON(IFLA_VF_LINK_STATE_ENABLE != MC_CMD_LINK_STATE_MODE_IN_LINK_STATE_UP); BUILD_BUG_ON(IFLA_VF_LINK_STATE_DISABLE != MC_CMD_LINK_STATE_MODE_IN_LINK_STATE_DOWN); MCDI_POPULATE_DWORD_2(inbuf, LINK_STATE_MODE_IN_FUNCTION, LINK_STATE_MODE_IN_FUNCTION_PF, nic_data->pf_index, LINK_STATE_MODE_IN_FUNCTION_VF, vf_i); MCDI_SET_DWORD(inbuf, LINK_STATE_MODE_IN_NEW_MODE, link_state); return efx_mcdi_rpc(efx, MC_CMD_LINK_STATE_MODE, inbuf, sizeof(inbuf), NULL, 0, NULL); /* don't care what old mode was */ } int efx_ef10_sriov_get_vf_config(struct efx_nic *efx, int vf_i, struct ifla_vf_info *ivf) { MCDI_DECLARE_BUF(inbuf, MC_CMD_LINK_STATE_MODE_IN_LEN); MCDI_DECLARE_BUF(outbuf, MC_CMD_LINK_STATE_MODE_OUT_LEN); struct efx_ef10_nic_data *nic_data = efx->nic_data; struct ef10_vf *vf; size_t outlen; int rc; if (vf_i >= efx->vf_count) return -EINVAL; if (!nic_data->vf) return -EOPNOTSUPP; vf = nic_data->vf + vf_i; ivf->vf = vf_i; ivf->min_tx_rate = 0; ivf->max_tx_rate = 0; ether_addr_copy(ivf->mac, vf->mac); ivf->vlan = (vf->vlan == EFX_EF10_NO_VLAN) ? 0 : vf->vlan; ivf->qos = 0; MCDI_POPULATE_DWORD_2(inbuf, LINK_STATE_MODE_IN_FUNCTION, LINK_STATE_MODE_IN_FUNCTION_PF, nic_data->pf_index, LINK_STATE_MODE_IN_FUNCTION_VF, vf_i); MCDI_SET_DWORD(inbuf, LINK_STATE_MODE_IN_NEW_MODE, MC_CMD_LINK_STATE_MODE_IN_DO_NOT_CHANGE); rc = efx_mcdi_rpc(efx, MC_CMD_LINK_STATE_MODE, inbuf, sizeof(inbuf), outbuf, sizeof(outbuf), &outlen); if (rc) return rc; if (outlen < MC_CMD_LINK_STATE_MODE_OUT_LEN) return -EIO; ivf->linkstate = MCDI_DWORD(outbuf, LINK_STATE_MODE_OUT_OLD_MODE); return 0; }
{ "language": "C" }
/** @file api_fontrender.h Font renderer. * * @ingroup gl * * @authors Copyright © 1999-2017 Jaakko Keränen <jaakko.keranen@iki.fi> * @authors Copyright © 2006-2013 Daniel Swanson <danij@dengine.net> * * @par License * GPL: http://www.gnu.org/licenses/gpl.html * * <small>This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. This program is distributed in the hope that it * will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. You should have received a copy of the GNU * General Public License along with this program; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA</small> */ #ifndef LIBDENG_API_FONT_RENDERER_H #define LIBDENG_API_FONT_RENDERER_H #include "api_base.h" #ifdef __cplusplus extern "C" { #endif /** * Font attributes are managed as a finite stack of attribute sets. * This value defines the maximum allowed depth of the attribute stack. */ #define FR_MAX_ATTRIB_STACK_DEPTH (8) /** * Font attribute defaults. Used with FR_LoadDefaultAttrib. */ #define FR_DEF_ATTRIB_LEADING (.5) #define FR_DEF_ATTRIB_TRACKING (0) #define FR_DEF_ATTRIB_COLOR_RED (1) #define FR_DEF_ATTRIB_COLOR_GREEN (1) #define FR_DEF_ATTRIB_COLOR_BLUE (1) #define FR_DEF_ATTRIB_ALPHA (1) #define FR_DEF_ATTRIB_GLITTER_STRENGTH (.5) #define FR_DEF_ATTRIB_SHADOW_STRENGTH (.5) #define FR_DEF_ATTRIB_SHADOW_XOFFSET (2) #define FR_DEF_ATTRIB_SHADOW_YOFFSET (2) #define FR_DEF_ATTRIB_CASE_SCALE (false) /** * @defgroup drawTextFlags Draw Text Flags * @ingroup apiFlags */ /*@{*/ #define DTF_NO_TYPEIN (0x0001) #define DTF_NO_SHADOW (0x0002) #define DTF_NO_GLITTER (0x0004) #define DTF_NO_EFFECTS (DTF_NO_TYPEIN|DTF_NO_SHADOW|DTF_NO_GLITTER) #define DTF_ONLY_SHADOW (DTF_NO_TYPEIN|DTF_NO_GLITTER) /*@}*/ DENG_API_TYPEDEF(FR) { de_api_t api; fontid_t (*ResolveUri)(struct uri_s const *uri); /// @return Unique identifier associated with the current font. fontid_t (*Font)(void); /// Change the current font. void (*SetFont)(fontid_t font); /// Push the attribute stack. void (*PushAttrib)(void); /// Pop the attribute stack. void (*PopAttrib)(void); /// Load the default attributes at the current stack depth. void (*LoadDefaultAttrib)(void); /// @return Current leading (attribute). float (*Leading)(void); void (*SetLeading)(float value); /// @return Current tracking (attribute). int (*Tracking)(void); void (*SetTracking)(int value); /// Retrieve the current color and alpha factors. void (*ColorAndAlpha)(float rgba[4]); void (*SetColor)(float red, float green, float blue); void (*SetColorv)(const float rgb[3]); void (*SetColorAndAlpha)(float red, float green, float blue, float alpha); void (*SetColorAndAlphav)(const float rgba[4]); /// @return Current red color factor. float (*ColorRed)(void); void (*SetColorRed)(float value); /// @return Current green color factor. float (*ColorGreen)(void); void (*SetColorGreen)(float value); /// @return Current blue color factor. float (*ColorBlue)(void); void (*SetColorBlue)(float value); /// @return Current alpha factor. float (*Alpha)(void); void (*SetAlpha)(float value); /// Retrieve the current shadow offset (attribute). void (*ShadowOffset)(int* offsetX, int* offsetY); void (*SetShadowOffset)(int offsetX, int offsetY); /// @return Current shadow strength (attribute). float (*ShadowStrength)(void); void (*SetShadowStrength)(float value); /// @return Current glitter strength (attribute). float (*GlitterStrength)(void); void (*SetGlitterStrength)(float value); /// @return Current case scale (attribute). dd_bool (*CaseScale)(void); void (*SetCaseScale)(dd_bool value); /** * Text blocks (possibly formatted and/or multi-line text): * * Formatting of text blocks is initially determined by the current font * renderer state at draw time (i.e., the attribute stack and draw paramaters). * ** Paramater blocks: * * A single text block may also embed attribute and draw paramater changes * within the text string itself. Paramater blocks are defined within the curly * bracketed escape sequence {&nbsp;} A single paramater block may * contain any number of attribute and draw paramaters delimited by semicolons. * * A text block may contain any number of paramater blocks. The scope for which * extends until the last character has been drawn or another block overrides * the same attribute. * * Examples: * <pre> * "{r = 1.0; g = 0.0; b = 0.0; case}This is red text with a case-scaled first character" * "This is text with an {y = -14}offset{y = 0} internal fragment." * "{fontb; r=0.5; g=1; b=0; x=2; y=-2}This is good!" * </pre> */ /** * Draw a text block. * * @param text Block of text to be drawn. * @param origin Orient drawing about this offset (topleft:[0,0]). */ void (*DrawText)(const char* text, const Point2Raw* origin); /** * @copydoc de_api_FR_s::DrawText * @param alignFlags @ref alignmentFlags */ void (*DrawText2)(const char* text, const Point2Raw* origin, int alignFlags); /** * Draw a text block. * * @param text Block of text to be drawn. * @param _origin Orient drawing about this offset (topleft:[0,0]). * @param alignFlags @ref alignmentFlags * @param _textFlags @ref drawTextFlags */ void (*DrawText3)(const char* text, const Point2Raw* _origin, int alignFlags, uint16_t _textFlags); void (*DrawTextXY3)(const char* text, int x, int y, int alignFlags, short flags); void (*DrawTextXY2)(const char* text, int x, int y, int alignFlags); void (*DrawTextXY)(const char* text, int x, int y); // Utility routines: void (*TextSize)(Size2Raw* size, const char* text); /// @return Visible width of the text. int (*TextWidth)(const char* text); /// @return Visible height of the text. int (*TextHeight)(const char* text); /* * Single characters: */ /** * Draw a character. * * @param ch Character to be drawn. * @param origin Origin/offset at which to begin drawing. * @param alignFlags @ref alignmentFlags * @param textFlags @ref drawTextFlags */ void (*DrawChar3)(unsigned char ch, const Point2Raw* origin, int alignFlags, short textFlags); void (*DrawChar2)(unsigned char ch, const Point2Raw* origin, int alignFlags); void (*DrawChar)(unsigned char ch, const Point2Raw* origin); void (*DrawCharXY3)(unsigned char ch, int x, int y, int alignFlags, short textFlags); void (*DrawCharXY2)(unsigned char ch, int x, int y, int alignFlags); void (*DrawCharXY)(unsigned char ch, int x, int y); // Utility routines: void (*CharSize)(Size2Raw* size, unsigned char ch); /// @return Visible width of the character. int (*CharWidth)(unsigned char ch); /// @return Visible height of the character. int (*CharHeight)(unsigned char ch); /// @deprecated Will be replaced with per-text-object animations. void (*ResetTypeinTimer)(void); } DENG_API_T(FR); #ifndef DENG_NO_API_MACROS_FONT_RENDER #define Fonts_ResolveUri _api_FR.ResolveUri #define FR_Font _api_FR.Font #define FR_SetFont _api_FR.SetFont #define FR_PushAttrib _api_FR.PushAttrib #define FR_PopAttrib _api_FR.PopAttrib #define FR_LoadDefaultAttrib _api_FR.LoadDefaultAttrib #define FR_Leading _api_FR.Leading #define FR_SetLeading _api_FR.SetLeading #define FR_Tracking _api_FR.Tracking #define FR_SetTracking _api_FR.SetTracking #define FR_ColorAndAlpha _api_FR.ColorAndAlpha #define FR_SetColor _api_FR.SetColor #define FR_SetColorv _api_FR.SetColorv #define FR_SetColorAndAlpha _api_FR.SetColorAndAlpha #define FR_SetColorAndAlphav _api_FR.SetColorAndAlphav #define FR_ColorRed _api_FR.ColorRed #define FR_SetColorRed _api_FR.SetColorRed #define FR_ColorGreen _api_FR.ColorGreen #define FR_SetColorGreen _api_FR.SetColorGreen #define FR_ColorBlue _api_FR.ColorBlue #define FR_SetColorBlue _api_FR.SetColorBlue #define FR_Alpha _api_FR.Alpha #define FR_SetAlpha _api_FR.SetAlpha #define FR_ShadowOffset _api_FR.ShadowOffset #define FR_SetShadowOffset _api_FR.SetShadowOffset #define FR_ShadowStrength _api_FR.ShadowStrength #define FR_SetShadowStrength _api_FR.SetShadowStrength #define FR_GlitterStrength _api_FR.GlitterStrength #define FR_SetGlitterStrength _api_FR.SetGlitterStrength #define FR_CaseScale _api_FR.CaseScale #define FR_SetCaseScale _api_FR.SetCaseScale #define FR_DrawText _api_FR.DrawText #define FR_DrawText2 _api_FR.DrawText2 #define FR_DrawText3 _api_FR.DrawText3 #define FR_DrawTextXY3 _api_FR.DrawTextXY3 #define FR_DrawTextXY2 _api_FR.DrawTextXY2 #define FR_DrawTextXY _api_FR.DrawTextXY #define FR_TextSize _api_FR.TextSize #define FR_TextWidth _api_FR.TextWidth #define FR_TextHeight _api_FR.TextHeight #define FR_DrawChar3 _api_FR.DrawChar3 #define FR_DrawChar2 _api_FR.DrawChar2 #define FR_DrawChar _api_FR.DrawChar #define FR_DrawCharXY3 _api_FR.DrawCharXY3 #define FR_DrawCharXY2 _api_FR.DrawCharXY2 #define FR_DrawCharXY _api_FR.DrawCharXY #define FR_CharSize _api_FR.CharSize #define FR_CharWidth _api_FR.CharWidth #define FR_CharHeight _api_FR.CharHeight #define FR_ResetTypeinTimer _api_FR.ResetTypeinTimer #endif #if defined __DOOMSDAY__ && defined __CLIENT__ DENG_USING_API(FR); #endif #ifdef __cplusplus } // extern "C" #endif #endif /* LIBDENG_API_FONT_RENDERER_H */
{ "language": "C" }
/** ****************************************************************************** * @file stm32f4xx_dcmi.c * @author MCD Application Team * @version V1.3.0 * @date 08-November-2013 * @brief This file provides firmware functions to manage the following * functionalities of the DCMI peripheral: * + Initialization and Configuration * + Image capture functions * + Interrupts and flags management * @verbatim =============================================================================== ##### How to use this driver ##### =============================================================================== [..] The sequence below describes how to use this driver to capture image from a camera module connected to the DCMI Interface. This sequence does not take into account the configuration of the camera module, which should be made before to configure and enable the DCMI to capture images. (#) Enable the clock for the DCMI and associated GPIOs using the following functions: RCC_AHB2PeriphClockCmd(RCC_AHB2Periph_DCMI, ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOx, ENABLE); (#) DCMI pins configuration (++) Connect the involved DCMI pins to AF13 using the following function GPIO_PinAFConfig(GPIOx, GPIO_PinSourcex, GPIO_AF_DCMI); (++) Configure these DCMI pins in alternate function mode by calling the function GPIO_Init(); (#) Declare a DCMI_InitTypeDef structure, for example: DCMI_InitTypeDef DCMI_InitStructure; and fill the DCMI_InitStructure variable with the allowed values of the structure member. (#) Initialize the DCMI interface by calling the function DCMI_Init(&DCMI_InitStructure); (#) Configure the DMA2_Stream1 channel1 to transfer Data from DCMI DR register to the destination memory buffer. (#) Enable DCMI interface using the function DCMI_Cmd(ENABLE); (#) Start the image capture using the function DCMI_CaptureCmd(ENABLE); (#) At this stage the DCMI interface waits for the first start of frame, then a DMA request is generated continuously/once (depending on the mode used, Continuous/Snapshot) to transfer the received data into the destination memory. -@- If you need to capture only a rectangular window from the received image, you have to use the DCMI_CROPConfig() function to configure the coordinates and size of the window to be captured, then enable the Crop feature using DCMI_CROPCmd(ENABLE); In this case, the Crop configuration should be made before to enable and start the DCMI interface. @endverbatim ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2013 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2 * * 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. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_dcmi.h" #include "stm32f4xx_rcc.h" /** @addtogroup STM32F4xx_StdPeriph_Driver * @{ */ /** @defgroup DCMI * @brief DCMI driver modules * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** @defgroup DCMI_Private_Functions * @{ */ /** @defgroup DCMI_Group1 Initialization and Configuration functions * @brief Initialization and Configuration functions * @verbatim =============================================================================== ##### Initialization and Configuration functions ##### =============================================================================== @endverbatim * @{ */ /** * @brief Deinitializes the DCMI registers to their default reset values. * @param None * @retval None */ void DCMI_DeInit(void) { DCMI->CR = 0x0; DCMI->IER = 0x0; DCMI->ICR = 0x1F; DCMI->ESCR = 0x0; DCMI->ESUR = 0x0; DCMI->CWSTRTR = 0x0; DCMI->CWSIZER = 0x0; } /** * @brief Initializes the DCMI according to the specified parameters in the DCMI_InitStruct. * @param DCMI_InitStruct: pointer to a DCMI_InitTypeDef structure that contains * the configuration information for the DCMI. * @retval None */ void DCMI_Init(DCMI_InitTypeDef* DCMI_InitStruct) { uint32_t temp = 0x0; /* Check the parameters */ assert_param(IS_DCMI_CAPTURE_MODE(DCMI_InitStruct->DCMI_CaptureMode)); assert_param(IS_DCMI_SYNCHRO(DCMI_InitStruct->DCMI_SynchroMode)); assert_param(IS_DCMI_PCKPOLARITY(DCMI_InitStruct->DCMI_PCKPolarity)); assert_param(IS_DCMI_VSPOLARITY(DCMI_InitStruct->DCMI_VSPolarity)); assert_param(IS_DCMI_HSPOLARITY(DCMI_InitStruct->DCMI_HSPolarity)); assert_param(IS_DCMI_CAPTURE_RATE(DCMI_InitStruct->DCMI_CaptureRate)); assert_param(IS_DCMI_EXTENDED_DATA(DCMI_InitStruct->DCMI_ExtendedDataMode)); /* The DCMI configuration registers should be programmed correctly before enabling the CR_ENABLE Bit and the CR_CAPTURE Bit */ DCMI->CR &= ~(DCMI_CR_ENABLE | DCMI_CR_CAPTURE); /* Reset the old DCMI configuration */ temp = DCMI->CR; temp &= ~((uint32_t)DCMI_CR_CM | DCMI_CR_ESS | DCMI_CR_PCKPOL | DCMI_CR_HSPOL | DCMI_CR_VSPOL | DCMI_CR_FCRC_0 | DCMI_CR_FCRC_1 | DCMI_CR_EDM_0 | DCMI_CR_EDM_1); /* Sets the new configuration of the DCMI peripheral */ temp |= ((uint32_t)DCMI_InitStruct->DCMI_CaptureMode | DCMI_InitStruct->DCMI_SynchroMode | DCMI_InitStruct->DCMI_PCKPolarity | DCMI_InitStruct->DCMI_VSPolarity | DCMI_InitStruct->DCMI_HSPolarity | DCMI_InitStruct->DCMI_CaptureRate | DCMI_InitStruct->DCMI_ExtendedDataMode); DCMI->CR = temp; } /** * @brief Fills each DCMI_InitStruct member with its default value. * @param DCMI_InitStruct : pointer to a DCMI_InitTypeDef structure which will * be initialized. * @retval None */ void DCMI_StructInit(DCMI_InitTypeDef* DCMI_InitStruct) { /* Set the default configuration */ DCMI_InitStruct->DCMI_CaptureMode = DCMI_CaptureMode_Continuous; DCMI_InitStruct->DCMI_SynchroMode = DCMI_SynchroMode_Hardware; DCMI_InitStruct->DCMI_PCKPolarity = DCMI_PCKPolarity_Falling; DCMI_InitStruct->DCMI_VSPolarity = DCMI_VSPolarity_Low; DCMI_InitStruct->DCMI_HSPolarity = DCMI_HSPolarity_Low; DCMI_InitStruct->DCMI_CaptureRate = DCMI_CaptureRate_All_Frame; DCMI_InitStruct->DCMI_ExtendedDataMode = DCMI_ExtendedDataMode_8b; } /** * @brief Initializes the DCMI peripheral CROP mode according to the specified * parameters in the DCMI_CROPInitStruct. * @note This function should be called before to enable and start the DCMI interface. * @param DCMI_CROPInitStruct: pointer to a DCMI_CROPInitTypeDef structure that * contains the configuration information for the DCMI peripheral CROP mode. * @retval None */ void DCMI_CROPConfig(DCMI_CROPInitTypeDef* DCMI_CROPInitStruct) { /* Sets the CROP window coordinates */ DCMI->CWSTRTR = (uint32_t)((uint32_t)DCMI_CROPInitStruct->DCMI_HorizontalOffsetCount | ((uint32_t)DCMI_CROPInitStruct->DCMI_VerticalStartLine << 16)); /* Sets the CROP window size */ DCMI->CWSIZER = (uint32_t)(DCMI_CROPInitStruct->DCMI_CaptureCount | ((uint32_t)DCMI_CROPInitStruct->DCMI_VerticalLineCount << 16)); } /** * @brief Enables or disables the DCMI Crop feature. * @note This function should be called before to enable and start the DCMI interface. * @param NewState: new state of the DCMI Crop feature. * This parameter can be: ENABLE or DISABLE. * @retval None */ void DCMI_CROPCmd(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the DCMI Crop feature */ DCMI->CR |= (uint32_t)DCMI_CR_CROP; } else { /* Disable the DCMI Crop feature */ DCMI->CR &= ~(uint32_t)DCMI_CR_CROP; } } /** * @brief Sets the embedded synchronization codes * @param DCMI_CodesInitTypeDef: pointer to a DCMI_CodesInitTypeDef structure that * contains the embedded synchronization codes for the DCMI peripheral. * @retval None */ void DCMI_SetEmbeddedSynchroCodes(DCMI_CodesInitTypeDef* DCMI_CodesInitStruct) { DCMI->ESCR = (uint32_t)(DCMI_CodesInitStruct->DCMI_FrameStartCode | ((uint32_t)DCMI_CodesInitStruct->DCMI_LineStartCode << 8)| ((uint32_t)DCMI_CodesInitStruct->DCMI_LineEndCode << 16)| ((uint32_t)DCMI_CodesInitStruct->DCMI_FrameEndCode << 24)); } /** * @brief Enables or disables the DCMI JPEG format. * @note The Crop and Embedded Synchronization features cannot be used in this mode. * @param NewState: new state of the DCMI JPEG format. * This parameter can be: ENABLE or DISABLE. * @retval None */ void DCMI_JPEGCmd(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the DCMI JPEG format */ DCMI->CR |= (uint32_t)DCMI_CR_JPEG; } else { /* Disable the DCMI JPEG format */ DCMI->CR &= ~(uint32_t)DCMI_CR_JPEG; } } /** * @} */ /** @defgroup DCMI_Group2 Image capture functions * @brief Image capture functions * @verbatim =============================================================================== ##### Image capture functions ##### =============================================================================== @endverbatim * @{ */ /** * @brief Enables or disables the DCMI interface. * @param NewState: new state of the DCMI interface. * This parameter can be: ENABLE or DISABLE. * @retval None */ void DCMI_Cmd(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the DCMI by setting ENABLE bit */ DCMI->CR |= (uint32_t)DCMI_CR_ENABLE; } else { /* Disable the DCMI by clearing ENABLE bit */ DCMI->CR &= ~(uint32_t)DCMI_CR_ENABLE; } } /** * @brief Enables or disables the DCMI Capture. * @param NewState: new state of the DCMI capture. * This parameter can be: ENABLE or DISABLE. * @retval None */ void DCMI_CaptureCmd(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the DCMI Capture */ DCMI->CR |= (uint32_t)DCMI_CR_CAPTURE; } else { /* Disable the DCMI Capture */ DCMI->CR &= ~(uint32_t)DCMI_CR_CAPTURE; } } /** * @brief Reads the data stored in the DR register. * @param None * @retval Data register value */ uint32_t DCMI_ReadData(void) { return DCMI->DR; } /** * @} */ /** @defgroup DCMI_Group3 Interrupts and flags management functions * @brief Interrupts and flags management functions * @verbatim =============================================================================== ##### Interrupts and flags management functions ##### =============================================================================== @endverbatim * @{ */ /** * @brief Enables or disables the DCMI interface interrupts. * @param DCMI_IT: specifies the DCMI interrupt sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg DCMI_IT_FRAME: Frame capture complete interrupt mask * @arg DCMI_IT_OVF: Overflow interrupt mask * @arg DCMI_IT_ERR: Synchronization error interrupt mask * @arg DCMI_IT_VSYNC: VSYNC interrupt mask * @arg DCMI_IT_LINE: Line interrupt mask * @param NewState: new state of the specified DCMI interrupts. * This parameter can be: ENABLE or DISABLE. * @retval None */ void DCMI_ITConfig(uint16_t DCMI_IT, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_DCMI_CONFIG_IT(DCMI_IT)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the Interrupt sources */ DCMI->IER |= DCMI_IT; } else { /* Disable the Interrupt sources */ DCMI->IER &= (uint16_t)(~DCMI_IT); } } /** * @brief Checks whether the DCMI interface flag is set or not. * @param DCMI_FLAG: specifies the flag to check. * This parameter can be one of the following values: * @arg DCMI_FLAG_FRAMERI: Frame capture complete Raw flag mask * @arg DCMI_FLAG_OVFRI: Overflow Raw flag mask * @arg DCMI_FLAG_ERRRI: Synchronization error Raw flag mask * @arg DCMI_FLAG_VSYNCRI: VSYNC Raw flag mask * @arg DCMI_FLAG_LINERI: Line Raw flag mask * @arg DCMI_FLAG_FRAMEMI: Frame capture complete Masked flag mask * @arg DCMI_FLAG_OVFMI: Overflow Masked flag mask * @arg DCMI_FLAG_ERRMI: Synchronization error Masked flag mask * @arg DCMI_FLAG_VSYNCMI: VSYNC Masked flag mask * @arg DCMI_FLAG_LINEMI: Line Masked flag mask * @arg DCMI_FLAG_HSYNC: HSYNC flag mask * @arg DCMI_FLAG_VSYNC: VSYNC flag mask * @arg DCMI_FLAG_FNE: Fifo not empty flag mask * @retval The new state of DCMI_FLAG (SET or RESET). */ FlagStatus DCMI_GetFlagStatus(uint16_t DCMI_FLAG) { FlagStatus bitstatus = RESET; uint32_t dcmireg, tempreg = 0; /* Check the parameters */ assert_param(IS_DCMI_GET_FLAG(DCMI_FLAG)); /* Get the DCMI register index */ dcmireg = (((uint16_t)DCMI_FLAG) >> 12); if (dcmireg == 0x00) /* The FLAG is in RISR register */ { tempreg= DCMI->RISR; } else if (dcmireg == 0x02) /* The FLAG is in SR register */ { tempreg = DCMI->SR; } else /* The FLAG is in MISR register */ { tempreg = DCMI->MISR; } if ((tempreg & DCMI_FLAG) != (uint16_t)RESET ) { bitstatus = SET; } else { bitstatus = RESET; } /* Return the DCMI_FLAG status */ return bitstatus; } /** * @brief Clears the DCMI's pending flags. * @param DCMI_FLAG: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg DCMI_FLAG_FRAMERI: Frame capture complete Raw flag mask * @arg DCMI_FLAG_OVFRI: Overflow Raw flag mask * @arg DCMI_FLAG_ERRRI: Synchronization error Raw flag mask * @arg DCMI_FLAG_VSYNCRI: VSYNC Raw flag mask * @arg DCMI_FLAG_LINERI: Line Raw flag mask * @retval None */ void DCMI_ClearFlag(uint16_t DCMI_FLAG) { /* Check the parameters */ assert_param(IS_DCMI_CLEAR_FLAG(DCMI_FLAG)); /* Clear the flag by writing in the ICR register 1 in the corresponding Flag position*/ DCMI->ICR = DCMI_FLAG; } /** * @brief Checks whether the DCMI interrupt has occurred or not. * @param DCMI_IT: specifies the DCMI interrupt source to check. * This parameter can be one of the following values: * @arg DCMI_IT_FRAME: Frame capture complete interrupt mask * @arg DCMI_IT_OVF: Overflow interrupt mask * @arg DCMI_IT_ERR: Synchronization error interrupt mask * @arg DCMI_IT_VSYNC: VSYNC interrupt mask * @arg DCMI_IT_LINE: Line interrupt mask * @retval The new state of DCMI_IT (SET or RESET). */ ITStatus DCMI_GetITStatus(uint16_t DCMI_IT) { ITStatus bitstatus = RESET; uint32_t itstatus = 0; /* Check the parameters */ assert_param(IS_DCMI_GET_IT(DCMI_IT)); itstatus = DCMI->MISR & DCMI_IT; /* Only masked interrupts are checked */ if ((itstatus != (uint16_t)RESET)) { bitstatus = SET; } else { bitstatus = RESET; } return bitstatus; } /** * @brief Clears the DCMI's interrupt pending bits. * @param DCMI_IT: specifies the DCMI interrupt pending bit to clear. * This parameter can be any combination of the following values: * @arg DCMI_IT_FRAME: Frame capture complete interrupt mask * @arg DCMI_IT_OVF: Overflow interrupt mask * @arg DCMI_IT_ERR: Synchronization error interrupt mask * @arg DCMI_IT_VSYNC: VSYNC interrupt mask * @arg DCMI_IT_LINE: Line interrupt mask * @retval None */ void DCMI_ClearITPendingBit(uint16_t DCMI_IT) { /* Clear the interrupt pending Bit by writing in the ICR register 1 in the corresponding pending Bit position*/ DCMI->ICR = DCMI_IT; } /** * @} */ /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
{ "language": "C" }
// RUN: %clang_cc1 -verify -fopenmp %s // RUN: %clang_cc1 -verify -fopenmp -std=c++98 %s // RUN: %clang_cc1 -verify -fopenmp -std=c++11 %s // RUN: %clang_cc1 -verify -fopenmp-simd %s // RUN: %clang_cc1 -verify -fopenmp-simd -std=c++98 %s // RUN: %clang_cc1 -verify -fopenmp-simd -std=c++11 %s void foo() { } #if __cplusplus >= 201103L // expected-note@+2 4 {{declared here}} #endif bool foobool(int argc) { return argc; } struct S1; // expected-note {{declared here}} template <class T, typename S, int N, int ST> // expected-note {{declared here}} T tmain(T argc, S **argv) { //expected-note 2 {{declared here}} #pragma omp target teams distribute collapse // expected-error {{expected '(' after 'collapse'}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute collapse ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute collapse () // expected-error {{expected expression}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // expected-error@+2 2 {{expression is not an integral constant expression}} // expected-note@+1 2 {{read of non-const variable 'argc' is not allowed in a constant expression}} #pragma omp target teams distribute collapse (argc for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+1 2 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute collapse (ST // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute collapse (1)) // expected-warning {{extra tokens at the end of '#pragma omp target teams distribute' are ignored}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute collapse ((ST > 0) ? 1 + ST : 2) // expected-note 2 {{as specified in 'collapse' clause}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error 2 {{expected 2 for loops after '#pragma omp target teams distribute', but found only 1}} #if __cplusplus >= 201103L // expected-note@+5 2 {{non-constexpr function 'foobool' cannot be used in a constant expression}} #endif // expected-error@+3 2 {{directive '#pragma omp target teams distribute' cannot contain more than one 'collapse' clause}} // expected-error@+2 2 {{argument to 'collapse' clause must be a strictly positive integer value}} // expected-error@+1 2 {{expression is not an integral constant expression}} #pragma omp target teams distribute collapse (foobool(argc)), collapse (true), collapse (-5) for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute collapse (S) // expected-error {{'S' does not refer to a value}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #if __cplusplus <= 199711L // expected-error@+4 2 {{expression is not an integral constant expression}} #else // expected-error@+2 2 {{integral constant expression must have integral or unscoped enumeration type, not 'char *'}} #endif #pragma omp target teams distribute collapse (argv[1]=2) // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute collapse (1) for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute collapse (N) // expected-error {{argument to 'collapse' clause must be a strictly positive integer value}} for (T i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute collapse (2) // expected-note {{as specified in 'collapse' clause}} foo(); // expected-error {{expected 2 for loops after '#pragma omp target teams distribute'}} return argc; } int main(int argc, char **argv) { #pragma omp target teams distribute collapse // expected-error {{expected '(' after 'collapse'}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #pragma omp target teams distribute collapse ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #pragma omp target teams distribute collapse () // expected-error {{expected expression}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #pragma omp target teams distribute collapse (4 // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-note {{as specified in 'collapse' clause}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute', but found only 1}} #pragma omp target teams distribute collapse (2+2)) // expected-warning {{extra tokens at the end of '#pragma omp target teams distribute' are ignored}} expected-note {{as specified in 'collapse' clause}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute', but found only 1}} // expected-error@+4 {{expression is not an integral constant expression}} #if __cplusplus >= 201103L // expected-note@+2 {{non-constexpr function 'foobool' cannot be used in a constant expression}} #endif #pragma omp target teams distribute collapse (foobool(1) > 0 ? 1 : 2) for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #if __cplusplus >= 201103L // expected-note@+5{{non-constexpr function 'foobool' cannot be used in a constant expression}} #endif // expected-error@+3 {{expression is not an integral constant expression}} // expected-error@+2 2 {{directive '#pragma omp target teams distribute' cannot contain more than one 'collapse' clause}} // expected-error@+1 2 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute collapse (foobool(argc)), collapse (true), collapse (-5) for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #pragma omp target teams distribute collapse (S1) // expected-error {{'S1' does not refer to a value}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #if __cplusplus <= 199711L // expected-error@+4 {{expression is not an integral constant expression}} #else // expected-error@+2 {{integral constant expression must have integral or unscoped enumeration type, not 'char *'}} #endif #pragma omp target teams distribute collapse (argv[1]=2) // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error@+3 {{statement after '#pragma omp target teams distribute' must be a for loop}} // expected-note@+1 {{in instantiation of function template specialization 'tmain<int, char, -1, -2>' requested here}} #pragma omp target teams distribute collapse(collapse(tmain<int, char, -1, -2>(argc, argv) // expected-error 2 {{expected ')'}} expected-note 2 {{to match this '('}} foo(); #pragma omp target teams distribute collapse (2) // expected-note {{as specified in 'collapse' clause}} foo(); // expected-error {{expected 2 for loops after '#pragma omp target teams distribute'}} // expected-note@+1 {{in instantiation of function template specialization 'tmain<int, char, 1, 0>' requested here}} return tmain<int, char, 1, 0>(argc, argv); }
{ "language": "C" }
/* TA-LIB Copyright (c) 1999-2007, Mario Fortier * All rights reserved. * * 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 name of author nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* List of contributors: * * Initial Name/description * ------------------------------------------------------------------- * JP John Price <jp_talib@gcfl.net> * MF Mario Fortier * AM Adrian Michel <http://amichel.com> * * Change history: * * MMDDYY BY Description * ------------------------------------------------------------------- * 070203 JP Initial. * 072106 MF,AM Fix #1526632. Add missing atan(). */ /**** START GENCODE SECTION 1 - DO NOT DELETE THIS LINE ****/ /* All code within this section is automatically * generated by gen_code. Any modification will be lost * next time gen_code is run. */ /* Generated */ /* Generated */ #if defined( _MANAGED ) /* Generated */ #include "TA-Lib-Core.h" /* Generated */ #define TA_INTERNAL_ERROR(Id) (RetCode::InternalError) /* Generated */ namespace TicTacTec { namespace TA { namespace Library { /* Generated */ #elif defined( _JAVA ) /* Generated */ #include "ta_defs.h" /* Generated */ #include "ta_java_defs.h" /* Generated */ #define TA_INTERNAL_ERROR(Id) (RetCode.InternalError) /* Generated */ #else /* Generated */ #include <string.h> /* Generated */ #include <math.h> /* Generated */ #include "ta_func.h" /* Generated */ #endif /* Generated */ /* Generated */ #ifndef TA_UTILITY_H /* Generated */ #include "ta_utility.h" /* Generated */ #endif /* Generated */ /* Generated */ #ifndef TA_MEMORY_H /* Generated */ #include "ta_memory.h" /* Generated */ #endif /* Generated */ /* Generated */ #define TA_PREFIX(x) TA_##x /* Generated */ #define INPUT_TYPE double /* Generated */ /* Generated */ #if defined( _MANAGED ) /* Generated */ int Core::LinearRegAngleLookback( int optInTimePeriod ) /* From 2 to 100000 */ /* Generated */ /* Generated */ #elif defined( _JAVA ) /* Generated */ public int linearRegAngleLookback( int optInTimePeriod ) /* From 2 to 100000 */ /* Generated */ /* Generated */ #else /* Generated */ int TA_LINEARREG_ANGLE_Lookback( int optInTimePeriod ) /* From 2 to 100000 */ /* Generated */ /* Generated */ #endif /**** END GENCODE SECTION 1 - DO NOT DELETE THIS LINE ****/ { /* insert local variable here */ /**** START GENCODE SECTION 2 - DO NOT DELETE THIS LINE ****/ /* Generated */ #ifndef TA_FUNC_NO_RANGE_CHECK /* Generated */ /* min/max are checked for optInTimePeriod. */ /* Generated */ if( (int)optInTimePeriod == TA_INTEGER_DEFAULT ) /* Generated */ optInTimePeriod = 14; /* Generated */ else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) ) /* Generated */ return -1; /* Generated */ /* Generated */ #endif /* TA_FUNC_NO_RANGE_CHECK */ /**** END GENCODE SECTION 2 - DO NOT DELETE THIS LINE ****/ /* insert lookback code here. */ return optInTimePeriod-1; } /**** START GENCODE SECTION 3 - DO NOT DELETE THIS LINE ****/ /* * TA_LINEARREG_ANGLE - Linear Regression Angle * * Input = double * Output = double * * Optional Parameters * ------------------- * optInTimePeriod:(From 2 to 100000) * Number of period * * */ /* Generated */ /* Generated */ #if defined( _MANAGED ) && defined( USE_SUBARRAY ) /* Generated */ enum class Core::RetCode Core::LinearRegAngle( int startIdx, /* Generated */ int endIdx, /* Generated */ SubArray^ inReal, /* Generated */ int optInTimePeriod, /* From 2 to 100000 */ /* Generated */ [Out]int% outBegIdx, /* Generated */ [Out]int% outNBElement, /* Generated */ cli::array<double>^ outReal ) /* Generated */ #elif defined( _MANAGED ) /* Generated */ enum class Core::RetCode Core::LinearRegAngle( int startIdx, /* Generated */ int endIdx, /* Generated */ cli::array<double>^ inReal, /* Generated */ int optInTimePeriod, /* From 2 to 100000 */ /* Generated */ [Out]int% outBegIdx, /* Generated */ [Out]int% outNBElement, /* Generated */ cli::array<double>^ outReal ) /* Generated */ #elif defined( _JAVA ) /* Generated */ public RetCode linearRegAngle( int startIdx, /* Generated */ int endIdx, /* Generated */ double inReal[], /* Generated */ int optInTimePeriod, /* From 2 to 100000 */ /* Generated */ MInteger outBegIdx, /* Generated */ MInteger outNBElement, /* Generated */ double outReal[] ) /* Generated */ #else /* Generated */ TA_RetCode TA_LINEARREG_ANGLE( int startIdx, /* Generated */ int endIdx, /* Generated */ const double inReal[], /* Generated */ int optInTimePeriod, /* From 2 to 100000 */ /* Generated */ int *outBegIdx, /* Generated */ int *outNBElement, /* Generated */ double outReal[] ) /* Generated */ #endif /**** END GENCODE SECTION 3 - DO NOT DELETE THIS LINE ****/ { /* insert local variable here */ int outIdx; int today, lookbackTotal; double SumX, SumXY, SumY, SumXSqr, Divisor; double m; int i; double tempValue1; /**** START GENCODE SECTION 4 - DO NOT DELETE THIS LINE ****/ /* Generated */ /* Generated */ #ifndef TA_FUNC_NO_RANGE_CHECK /* Generated */ /* Generated */ /* Validate the requested output range. */ /* Generated */ if( startIdx < 0 ) /* Generated */ return ENUM_VALUE(RetCode,TA_OUT_OF_RANGE_START_INDEX,OutOfRangeStartIndex); /* Generated */ if( (endIdx < 0) || (endIdx < startIdx)) /* Generated */ return ENUM_VALUE(RetCode,TA_OUT_OF_RANGE_END_INDEX,OutOfRangeEndIndex); /* Generated */ /* Generated */ #if !defined(_JAVA) /* Generated */ if( !inReal ) return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam); /* Generated */ #endif /* !defined(_JAVA)*/ /* Generated */ /* min/max are checked for optInTimePeriod. */ /* Generated */ if( (int)optInTimePeriod == TA_INTEGER_DEFAULT ) /* Generated */ optInTimePeriod = 14; /* Generated */ else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) ) /* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam); /* Generated */ /* Generated */ #if !defined(_JAVA) /* Generated */ if( !outReal ) /* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam); /* Generated */ /* Generated */ #endif /* !defined(_JAVA) */ /* Generated */ #endif /* TA_FUNC_NO_RANGE_CHECK */ /* Generated */ /**** END GENCODE SECTION 4 - DO NOT DELETE THIS LINE ****/ /* Insert TA function code here. */ /* Linear Regression is a concept also known as the * "least squares method" or "best fit." Linear * Regression attempts to fit a straight line between * several data points in such a way that distance * between each data point and the line is minimized. * * For each point, a straight line over the specified * previous bar period is determined in terms * of y = b + m*x: * * TA_LINEARREG : Returns b+m*(period-1) * TA_LINEARREG_SLOPE : Returns 'm' * TA_LINEARREG_ANGLE : Returns 'm' in degree. * TA_LINEARREG_INTERCEPT: Returns 'b' * TA_TSF : Returns b+m*(period) */ /* Adjust startIdx to account for the lookback period. */ lookbackTotal = LOOKBACK_CALL(LINEARREG_ANGLE)( optInTimePeriod ); if( startIdx < lookbackTotal ) startIdx = lookbackTotal; /* Make sure there is still something to evaluate. */ if( startIdx > endIdx ) { VALUE_HANDLE_DEREF_TO_ZERO(outBegIdx); VALUE_HANDLE_DEREF_TO_ZERO(outNBElement); return ENUM_VALUE(RetCode,TA_SUCCESS,Success); } outIdx = 0; /* Index into the output. */ today = startIdx; SumX = optInTimePeriod * ( optInTimePeriod - 1 ) * 0.5; SumXSqr = optInTimePeriod * ( optInTimePeriod - 1 ) * ( 2 * optInTimePeriod - 1 ) / 6; Divisor = SumX * SumX - optInTimePeriod * SumXSqr; while( today <= endIdx ) { SumXY = 0; SumY = 0; for( i = optInTimePeriod; i-- != 0; ) { SumY += tempValue1 = inReal[today - i]; SumXY += (double)i * tempValue1; } m = ( optInTimePeriod * SumXY - SumX * SumY) / Divisor; outReal[outIdx++] = std_atan(m) * ( 180.0 / PI ); today++; } VALUE_HANDLE_DEREF(outBegIdx) = startIdx; VALUE_HANDLE_DEREF(outNBElement) = outIdx; return ENUM_VALUE(RetCode,TA_SUCCESS,Success); } /**** START GENCODE SECTION 5 - DO NOT DELETE THIS LINE ****/ /* Generated */ /* Generated */ #define USE_SINGLE_PRECISION_INPUT /* Generated */ #if !defined( _MANAGED ) && !defined( _JAVA ) /* Generated */ #undef TA_PREFIX /* Generated */ #define TA_PREFIX(x) TA_S_##x /* Generated */ #endif /* Generated */ #undef INPUT_TYPE /* Generated */ #define INPUT_TYPE float /* Generated */ #if defined( _MANAGED ) /* Generated */ enum class Core::RetCode Core::LinearRegAngle( int startIdx, /* Generated */ int endIdx, /* Generated */ cli::array<float>^ inReal, /* Generated */ int optInTimePeriod, /* From 2 to 100000 */ /* Generated */ [Out]int% outBegIdx, /* Generated */ [Out]int% outNBElement, /* Generated */ cli::array<double>^ outReal ) /* Generated */ #elif defined( _JAVA ) /* Generated */ public RetCode linearRegAngle( int startIdx, /* Generated */ int endIdx, /* Generated */ float inReal[], /* Generated */ int optInTimePeriod, /* From 2 to 100000 */ /* Generated */ MInteger outBegIdx, /* Generated */ MInteger outNBElement, /* Generated */ double outReal[] ) /* Generated */ #else /* Generated */ TA_RetCode TA_S_LINEARREG_ANGLE( int startIdx, /* Generated */ int endIdx, /* Generated */ const float inReal[], /* Generated */ int optInTimePeriod, /* From 2 to 100000 */ /* Generated */ int *outBegIdx, /* Generated */ int *outNBElement, /* Generated */ double outReal[] ) /* Generated */ #endif /* Generated */ { /* Generated */ int outIdx; /* Generated */ int today, lookbackTotal; /* Generated */ double SumX, SumXY, SumY, SumXSqr, Divisor; /* Generated */ double m; /* Generated */ int i; /* Generated */ double tempValue1; /* Generated */ #ifndef TA_FUNC_NO_RANGE_CHECK /* Generated */ if( startIdx < 0 ) /* Generated */ return ENUM_VALUE(RetCode,TA_OUT_OF_RANGE_START_INDEX,OutOfRangeStartIndex); /* Generated */ if( (endIdx < 0) || (endIdx < startIdx)) /* Generated */ return ENUM_VALUE(RetCode,TA_OUT_OF_RANGE_END_INDEX,OutOfRangeEndIndex); /* Generated */ #if !defined(_JAVA) /* Generated */ if( !inReal ) return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam); /* Generated */ #endif /* Generated */ if( (int)optInTimePeriod == TA_INTEGER_DEFAULT ) /* Generated */ optInTimePeriod = 14; /* Generated */ else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) ) /* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam); /* Generated */ #if !defined(_JAVA) /* Generated */ if( !outReal ) /* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam); /* Generated */ #endif /* Generated */ #endif /* Generated */ lookbackTotal = LOOKBACK_CALL(LINEARREG_ANGLE)( optInTimePeriod ); /* Generated */ if( startIdx < lookbackTotal ) /* Generated */ startIdx = lookbackTotal; /* Generated */ if( startIdx > endIdx ) /* Generated */ { /* Generated */ VALUE_HANDLE_DEREF_TO_ZERO(outBegIdx); /* Generated */ VALUE_HANDLE_DEREF_TO_ZERO(outNBElement); /* Generated */ return ENUM_VALUE(RetCode,TA_SUCCESS,Success); /* Generated */ } /* Generated */ outIdx = 0; /* Generated */ today = startIdx; /* Generated */ SumX = optInTimePeriod * ( optInTimePeriod - 1 ) * 0.5; /* Generated */ SumXSqr = optInTimePeriod * ( optInTimePeriod - 1 ) * ( 2 * optInTimePeriod - 1 ) / 6; /* Generated */ Divisor = SumX * SumX - optInTimePeriod * SumXSqr; /* Generated */ while( today <= endIdx ) /* Generated */ { /* Generated */ SumXY = 0; /* Generated */ SumY = 0; /* Generated */ for( i = optInTimePeriod; i-- != 0; ) /* Generated */ { /* Generated */ SumY += tempValue1 = inReal[today - i]; /* Generated */ SumXY += (double)i * tempValue1; /* Generated */ } /* Generated */ m = ( optInTimePeriod * SumXY - SumX * SumY) / Divisor; /* Generated */ outReal[outIdx++] = std_atan(m) * ( 180.0 / PI ); /* Generated */ today++; /* Generated */ } /* Generated */ VALUE_HANDLE_DEREF(outBegIdx) = startIdx; /* Generated */ VALUE_HANDLE_DEREF(outNBElement) = outIdx; /* Generated */ return ENUM_VALUE(RetCode,TA_SUCCESS,Success); /* Generated */ } /* Generated */ /* Generated */ #if defined( _MANAGED ) /* Generated */ }}} // Close namespace TicTacTec.TA.Lib /* Generated */ #endif /**** END GENCODE SECTION 5 - DO NOT DELETE THIS LINE ****/
{ "language": "C" }
/* * Shared CARL9170 Header * * Firmware descriptor format * * Copyright 2009-2011 Christian Lamparter <chunkeey@googlemail.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. * * 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; see the file COPYING. If not, see * http://www.gnu.org/licenses/. */ #ifndef __CARL9170_SHARED_FWDESC_H #define __CARL9170_SHARED_FWDESC_H /* NOTE: Don't mess with the order of the flags! */ enum carl9170fw_feature_list { /* Always set */ CARL9170FW_DUMMY_FEATURE, /* * Indicates that this image has special boot block which prevents * legacy drivers to drive the firmware. */ CARL9170FW_MINIBOOT, /* usb registers are initialized by the firmware */ CARL9170FW_USB_INIT_FIRMWARE, /* command traps & notifications are send through EP2 */ CARL9170FW_USB_RESP_EP2, /* usb download (app -> fw) stream */ CARL9170FW_USB_DOWN_STREAM, /* usb upload (fw -> app) stream */ CARL9170FW_USB_UP_STREAM, /* unusable - reserved to flag non-functional debug firmwares */ CARL9170FW_UNUSABLE, /* AR9170_CMD_RF_INIT, AR9170_CMD_FREQ_START, AR9170_CMD_FREQUENCY */ CARL9170FW_COMMAND_PHY, /* AR9170_CMD_EKEY, AR9170_CMD_DKEY */ CARL9170FW_COMMAND_CAM, /* Firmware has a software Content After Beacon Queueing mechanism */ CARL9170FW_WLANTX_CAB, /* The firmware is capable of responding to incoming BAR frames */ CARL9170FW_HANDLE_BACK_REQ, /* GPIO Interrupt | CARL9170_RSP_GPIO */ CARL9170FW_GPIO_INTERRUPT, /* Firmware PSM support | CARL9170_CMD_PSM */ CARL9170FW_PSM, /* Firmware RX filter | CARL9170_CMD_RX_FILTER */ CARL9170FW_RX_FILTER, /* Wake up on WLAN */ CARL9170FW_WOL, /* Firmware supports PSM in the 5GHZ Band */ CARL9170FW_FIXED_5GHZ_PSM, /* HW (ANI, CCA, MIB) tally counters */ CARL9170FW_HW_COUNTERS, /* KEEP LAST */ __CARL9170FW_FEATURE_NUM }; #define OTUS_MAGIC "OTAR" #define MOTD_MAGIC "MOTD" #define FIX_MAGIC "FIX\0" #define DBG_MAGIC "DBG\0" #define CHK_MAGIC "CHK\0" #define TXSQ_MAGIC "TXSQ" #define WOL_MAGIC "WOL\0" #define LAST_MAGIC "LAST" #define CARL9170FW_SET_DAY(d) (((d) - 1) % 31) #define CARL9170FW_SET_MONTH(m) ((((m) - 1) % 12) * 31) #define CARL9170FW_SET_YEAR(y) (((y) - 10) * 372) #define CARL9170FW_GET_DAY(d) (((d) % 31) + 1) #define CARL9170FW_GET_MONTH(m) ((((m) / 31) % 12) + 1) #define CARL9170FW_GET_YEAR(y) ((y) / 372 + 10) #define CARL9170FW_MAGIC_SIZE 4 struct carl9170fw_desc_head { u8 magic[CARL9170FW_MAGIC_SIZE]; __le16 length; u8 min_ver; u8 cur_ver; } __packed; #define CARL9170FW_DESC_HEAD_SIZE \ (sizeof(struct carl9170fw_desc_head)) #define CARL9170FW_OTUS_DESC_MIN_VER 6 #define CARL9170FW_OTUS_DESC_CUR_VER 7 struct carl9170fw_otus_desc { struct carl9170fw_desc_head head; __le32 feature_set; __le32 fw_address; __le32 bcn_addr; __le16 bcn_len; __le16 miniboot_size; __le16 tx_frag_len; __le16 rx_max_frame_len; u8 tx_descs; u8 cmd_bufs; u8 api_ver; u8 vif_num; } __packed; #define CARL9170FW_OTUS_DESC_SIZE \ (sizeof(struct carl9170fw_otus_desc)) #define CARL9170FW_MOTD_STRING_LEN 24 #define CARL9170FW_MOTD_RELEASE_LEN 20 #define CARL9170FW_MOTD_DESC_MIN_VER 1 #define CARL9170FW_MOTD_DESC_CUR_VER 2 struct carl9170fw_motd_desc { struct carl9170fw_desc_head head; __le32 fw_year_month_day; char desc[CARL9170FW_MOTD_STRING_LEN]; char release[CARL9170FW_MOTD_RELEASE_LEN]; } __packed; #define CARL9170FW_MOTD_DESC_SIZE \ (sizeof(struct carl9170fw_motd_desc)) #define CARL9170FW_FIX_DESC_MIN_VER 1 #define CARL9170FW_FIX_DESC_CUR_VER 2 struct carl9170fw_fix_entry { __le32 address; __le32 mask; __le32 value; } __packed; struct carl9170fw_fix_desc { struct carl9170fw_desc_head head; struct carl9170fw_fix_entry data[0]; } __packed; #define CARL9170FW_FIX_DESC_SIZE \ (sizeof(struct carl9170fw_fix_desc)) #define CARL9170FW_DBG_DESC_MIN_VER 1 #define CARL9170FW_DBG_DESC_CUR_VER 3 struct carl9170fw_dbg_desc { struct carl9170fw_desc_head head; __le32 bogoclock_addr; __le32 counter_addr; __le32 rx_total_addr; __le32 rx_overrun_addr; __le32 rx_filter; /* Put your debugging definitions here */ } __packed; #define CARL9170FW_DBG_DESC_SIZE \ (sizeof(struct carl9170fw_dbg_desc)) #define CARL9170FW_CHK_DESC_MIN_VER 1 #define CARL9170FW_CHK_DESC_CUR_VER 2 struct carl9170fw_chk_desc { struct carl9170fw_desc_head head; __le32 fw_crc32; __le32 hdr_crc32; } __packed; #define CARL9170FW_CHK_DESC_SIZE \ (sizeof(struct carl9170fw_chk_desc)) #define CARL9170FW_TXSQ_DESC_MIN_VER 1 #define CARL9170FW_TXSQ_DESC_CUR_VER 1 struct carl9170fw_txsq_desc { struct carl9170fw_desc_head head; __le32 seq_table_addr; } __packed; #define CARL9170FW_TXSQ_DESC_SIZE \ (sizeof(struct carl9170fw_txsq_desc)) #define CARL9170FW_WOL_DESC_MIN_VER 1 #define CARL9170FW_WOL_DESC_CUR_VER 1 struct carl9170fw_wol_desc { struct carl9170fw_desc_head head; __le32 supported_triggers; /* CARL9170_WOL_ */ } __packed; #define CARL9170FW_WOL_DESC_SIZE \ (sizeof(struct carl9170fw_wol_desc)) #define CARL9170FW_LAST_DESC_MIN_VER 1 #define CARL9170FW_LAST_DESC_CUR_VER 2 struct carl9170fw_last_desc { struct carl9170fw_desc_head head; } __packed; #define CARL9170FW_LAST_DESC_SIZE \ (sizeof(struct carl9170fw_fix_desc)) #define CARL9170FW_DESC_MAX_LENGTH 8192 #define CARL9170FW_FILL_DESC(_magic, _length, _min_ver, _cur_ver) \ .head = { \ .magic = _magic, \ .length = cpu_to_le16(_length), \ .min_ver = _min_ver, \ .cur_ver = _cur_ver, \ } static inline void carl9170fw_fill_desc(struct carl9170fw_desc_head *head, u8 magic[CARL9170FW_MAGIC_SIZE], __le16 length, u8 min_ver, u8 cur_ver) { head->magic[0] = magic[0]; head->magic[1] = magic[1]; head->magic[2] = magic[2]; head->magic[3] = magic[3]; head->length = length; head->min_ver = min_ver; head->cur_ver = cur_ver; } #define carl9170fw_for_each_hdr(desc, fw_desc) \ for (desc = fw_desc; \ memcmp(desc->magic, LAST_MAGIC, CARL9170FW_MAGIC_SIZE) && \ le16_to_cpu(desc->length) >= CARL9170FW_DESC_HEAD_SIZE && \ le16_to_cpu(desc->length) < CARL9170FW_DESC_MAX_LENGTH; \ desc = (void *)((unsigned long)desc + le16_to_cpu(desc->length))) #define CHECK_HDR_VERSION(head, _min_ver) \ (((head)->cur_ver < _min_ver) || ((head)->min_ver > _min_ver)) \ static inline bool carl9170fw_supports(__le32 list, u8 feature) { return le32_to_cpu(list) & BIT(feature); } static inline bool carl9170fw_desc_cmp(const struct carl9170fw_desc_head *head, const u8 descid[CARL9170FW_MAGIC_SIZE], u16 min_len, u8 compatible_revision) { if (descid[0] == head->magic[0] && descid[1] == head->magic[1] && descid[2] == head->magic[2] && descid[3] == head->magic[3] && !CHECK_HDR_VERSION(head, compatible_revision) && (le16_to_cpu(head->length) >= min_len)) return true; return false; } #define CARL9170FW_MIN_SIZE 32 #define CARL9170FW_MAX_SIZE 16384 static inline bool carl9170fw_size_check(unsigned int len) { return (len <= CARL9170FW_MAX_SIZE && len >= CARL9170FW_MIN_SIZE); } #endif /* __CARL9170_SHARED_FWDESC_H */
{ "language": "C" }
/* * Copyright (C) 2017-2019 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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. */ #pragma once #include "BAssert.h" #include "BMalloced.h" #include "IsoTLSLayout.h" #include <climits> namespace bmalloc { class IsoTLS; template<typename Entry> class IsoTLSEntryHolder { MAKE_BMALLOCED; IsoTLSEntryHolder(const IsoTLSEntryHolder&) = delete; IsoTLSEntryHolder& operator=(const IsoTLSEntryHolder&) = delete; public: template<typename... Args> IsoTLSEntryHolder(Args&&... args) : m_entry(std::forward<Args>(args)...) { IsoTLSLayout::get()->add(&m_entry); RELEASE_BASSERT(m_entry.offset() != UINT_MAX); } inline const Entry& operator*() const { m_entry; } inline Entry& operator*() { m_entry; } inline const Entry* operator->() const { return &m_entry; } inline Entry* operator->() { return &m_entry; } private: Entry m_entry; }; class BEXPORT IsoTLSEntry { MAKE_BMALLOCED; IsoTLSEntry(const IsoTLSEntry&) = delete; IsoTLSEntry& operator=(const IsoTLSEntry&) = delete; public: virtual ~IsoTLSEntry(); size_t offset() const { return m_offset; } size_t alignment() const { return sizeof(void*); } size_t size() const { return m_size; } size_t extent() const { return m_offset + m_size; } virtual void construct(void* entry) = 0; virtual void move(void* src, void* dst) = 0; virtual void destruct(void* entry) = 0; virtual void scavenge(void* entry) = 0; template<typename Func> void walkUpToInclusive(IsoTLSEntry*, const Func&); protected: IsoTLSEntry(size_t size); private: friend class IsoTLS; friend class IsoTLSLayout; IsoTLSEntry* m_next { nullptr }; unsigned m_offset { UINT_MAX }; // Computed in constructor. unsigned m_size; }; template<typename EntryType> class DefaultIsoTLSEntry : public IsoTLSEntry { public: ~DefaultIsoTLSEntry() = default; protected: DefaultIsoTLSEntry(); // This clones src onto dst and then destructs src. Therefore, entry destructors cannot do // scavenging. void move(void* src, void* dst) override; // Likewise, this is separate from scavenging. When the TLS is shutting down, we will be asked to // scavenge and then we will be asked to destruct. void destruct(void* entry) override; }; } // namespace bmalloc
{ "language": "C" }
/* * linux/fs/nls/nls_cp850.c * * Charset cp850 translation tables. * Generated automatically from the Unicode and charset * tables from the Unicode Organization (www.unicode.org). * The Unicode to charset table has only exact mappings. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/nls.h> #include <linux/errno.h> static const wchar_t charset2uni[256] = { /* 0x00*/ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, /* 0x10*/ 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, /* 0x20*/ 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, /* 0x30*/ 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, /* 0x40*/ 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, /* 0x50*/ 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, /* 0x60*/ 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, /* 0x70*/ 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f, /* 0x80*/ 0x00c7, 0x00fc, 0x00e9, 0x00e2, 0x00e4, 0x00e0, 0x00e5, 0x00e7, 0x00ea, 0x00eb, 0x00e8, 0x00ef, 0x00ee, 0x00ec, 0x00c4, 0x00c5, /* 0x90*/ 0x00c9, 0x00e6, 0x00c6, 0x00f4, 0x00f6, 0x00f2, 0x00fb, 0x00f9, 0x00ff, 0x00d6, 0x00dc, 0x00f8, 0x00a3, 0x00d8, 0x00d7, 0x0192, /* 0xa0*/ 0x00e1, 0x00ed, 0x00f3, 0x00fa, 0x00f1, 0x00d1, 0x00aa, 0x00ba, 0x00bf, 0x00ae, 0x00ac, 0x00bd, 0x00bc, 0x00a1, 0x00ab, 0x00bb, /* 0xb0*/ 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00c1, 0x00c2, 0x00c0, 0x00a9, 0x2563, 0x2551, 0x2557, 0x255d, 0x00a2, 0x00a5, 0x2510, /* 0xc0*/ 0x2514, 0x2534, 0x252c, 0x251c, 0x2500, 0x253c, 0x00e3, 0x00c3, 0x255a, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256c, 0x00a4, /* 0xd0*/ 0x00f0, 0x00d0, 0x00ca, 0x00cb, 0x00c8, 0x0131, 0x00cd, 0x00ce, 0x00cf, 0x2518, 0x250c, 0x2588, 0x2584, 0x00a6, 0x00cc, 0x2580, /* 0xe0*/ 0x00d3, 0x00df, 0x00d4, 0x00d2, 0x00f5, 0x00d5, 0x00b5, 0x00fe, 0x00de, 0x00da, 0x00db, 0x00d9, 0x00fd, 0x00dd, 0x00af, 0x00b4, /* 0xf0*/ 0x00ad, 0x00b1, 0x2017, 0x00be, 0x00b6, 0x00a7, 0x00f7, 0x00b8, 0x00b0, 0x00a8, 0x00b7, 0x00b9, 0x00b3, 0x00b2, 0x25a0, 0x00a0, }; static const unsigned char page00[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */ 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */ 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */ 0xff, 0xad, 0xbd, 0x9c, 0xcf, 0xbe, 0xdd, 0xf5, /* 0xa0-0xa7 */ 0xf9, 0xb8, 0xa6, 0xae, 0xaa, 0xf0, 0xa9, 0xee, /* 0xa8-0xaf */ 0xf8, 0xf1, 0xfd, 0xfc, 0xef, 0xe6, 0xf4, 0xfa, /* 0xb0-0xb7 */ 0xf7, 0xfb, 0xa7, 0xaf, 0xac, 0xab, 0xf3, 0xa8, /* 0xb8-0xbf */ 0xb7, 0xb5, 0xb6, 0xc7, 0x8e, 0x8f, 0x92, 0x80, /* 0xc0-0xc7 */ 0xd4, 0x90, 0xd2, 0xd3, 0xde, 0xd6, 0xd7, 0xd8, /* 0xc8-0xcf */ 0xd1, 0xa5, 0xe3, 0xe0, 0xe2, 0xe5, 0x99, 0x9e, /* 0xd0-0xd7 */ 0x9d, 0xeb, 0xe9, 0xea, 0x9a, 0xed, 0xe8, 0xe1, /* 0xd8-0xdf */ 0x85, 0xa0, 0x83, 0xc6, 0x84, 0x86, 0x91, 0x87, /* 0xe0-0xe7 */ 0x8a, 0x82, 0x88, 0x89, 0x8d, 0xa1, 0x8c, 0x8b, /* 0xe8-0xef */ 0xd0, 0xa4, 0x95, 0xa2, 0x93, 0xe4, 0x94, 0xf6, /* 0xf0-0xf7 */ 0x9b, 0x97, 0xa3, 0x96, 0x81, 0xec, 0xe7, 0x98, /* 0xf8-0xff */ }; static const unsigned char page01[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0xd5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0x00, 0x00, 0x9f, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ }; static const unsigned char page20[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf2, /* 0x10-0x17 */ }; static const unsigned char page25[256] = { 0xc4, 0x00, 0xb3, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0xda, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0xbf, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0xd9, 0x00, 0x00, 0x00, 0xc3, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0xc2, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0xc1, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0xc5, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0xcd, 0xba, 0x00, 0x00, 0xc9, 0x00, 0x00, 0xbb, /* 0x50-0x57 */ 0x00, 0x00, 0xc8, 0x00, 0x00, 0xbc, 0x00, 0x00, /* 0x58-0x5f */ 0xcc, 0x00, 0x00, 0xb9, 0x00, 0x00, 0xcb, 0x00, /* 0x60-0x67 */ 0x00, 0xca, 0x00, 0x00, 0xce, 0x00, 0x00, 0x00, /* 0x68-0x6f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */ 0xdf, 0x00, 0x00, 0x00, 0xdc, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0xdb, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0x00, 0xb0, 0xb1, 0xb2, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */ 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */ }; static const unsigned char *const page_uni2charset[256] = { page00, page01, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, page20, NULL, NULL, NULL, NULL, page25, NULL, NULL, }; static const unsigned char charset2lower[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x40-0x47 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x48-0x4f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x50-0x57 */ 0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */ 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x87, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */ 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x84, 0x86, /* 0x88-0x8f */ 0x82, 0x91, 0x91, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */ 0x98, 0x94, 0x81, 0x9b, 0x9c, 0x9b, 0x9e, 0x9f, /* 0x98-0x9f */ 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa4, 0xa6, 0xa7, /* 0xa0-0xa7 */ 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xa0, 0x83, 0x85, /* 0xb0-0xb7 */ 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc6, /* 0xc0-0xc7 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */ 0xd0, 0xd0, 0x88, 0x89, 0x8a, 0xd5, 0xa1, 0x8c, /* 0xd0-0xd7 */ 0x8b, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0x8d, 0xdf, /* 0xd8-0xdf */ 0xa2, 0xe1, 0x93, 0x95, 0xe4, 0xe4, 0xe6, 0xe7, /* 0xe0-0xe7 */ 0xe7, 0xa3, 0x96, 0x97, 0xec, 0xec, 0xee, 0xef, /* 0xe8-0xef */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */ }; static const unsigned char charset2upper[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */ 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */ 0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x80, 0x9a, 0x90, 0xb6, 0x8e, 0xb7, 0x8f, 0x80, /* 0x80-0x87 */ 0xd2, 0xd3, 0xd4, 0xd8, 0xd7, 0xde, 0x8e, 0x8f, /* 0x88-0x8f */ 0x90, 0x92, 0x92, 0xe2, 0x99, 0xe3, 0xea, 0xeb, /* 0x90-0x97 */ 0x00, 0x99, 0x9a, 0x9d, 0x9c, 0x9d, 0x9e, 0x00, /* 0x98-0x9f */ 0xb5, 0xd6, 0xe0, 0xe9, 0xa5, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */ 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */ 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc7, 0xc7, /* 0xc0-0xc7 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */ 0xd1, 0xd1, 0xd2, 0xd3, 0xd4, 0x49, 0xd6, 0xd7, /* 0xd0-0xd7 */ 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */ 0xe0, 0xe1, 0xe2, 0xe3, 0xe5, 0xe5, 0x00, 0xe8, /* 0xe0-0xe7 */ 0xe8, 0xe9, 0xea, 0xeb, 0xed, 0xed, 0xee, 0xef, /* 0xe8-0xef */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */ }; static int uni2char(wchar_t uni, unsigned char *out, int boundlen) { const unsigned char *uni2charset; unsigned char cl = uni & 0x00ff; unsigned char ch = (uni & 0xff00) >> 8; if (boundlen <= 0) return -ENAMETOOLONG; uni2charset = page_uni2charset[ch]; if (uni2charset && uni2charset[cl]) out[0] = uni2charset[cl]; else return -EINVAL; return 1; } static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni) { *uni = charset2uni[*rawstring]; if (*uni == 0x0000) return -EINVAL; return 1; } static struct nls_table table = { .charset = "cp850", .uni2char = uni2char, .char2uni = char2uni, .charset2lower = charset2lower, .charset2upper = charset2upper, }; static int __init init_nls_cp850(void) { return register_nls(&table); } static void __exit exit_nls_cp850(void) { unregister_nls(&table); } module_init(init_nls_cp850) module_exit(exit_nls_cp850) MODULE_LICENSE("Dual BSD/GPL");
{ "language": "C" }
/*************************************************************************** * Copyright (C) 2002~2005 by Yuking * * yuking_net@sohu.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. * * * * 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 St, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include "fcitx-utils/utils.h" #include "pyTools.h" void LoadPYMB(FILE *fi, struct _PYMB **pPYMB, int isUser) { struct _PYMB *PYMB; int i, j, r, n, t; /* Is there a way to avoid reading the whole file twice? */ /* First Pass: Determine the size of the PYMB array to be created */ n = 0; while (1) { int8_t clen; r = fcitx_utils_read_int32(fi, &t); if (!r) break; ++n; fread(&clen, sizeof(int8_t), 1, fi); fseek(fi, sizeof(char) * clen, SEEK_CUR); fcitx_utils_read_int32(fi, &t); for (i = 0; i < t; ++i) { int iLen; fcitx_utils_read_int32(fi, &iLen); fseek(fi , sizeof(char) * iLen, SEEK_CUR); fcitx_utils_read_int32(fi, &iLen); fseek(fi , sizeof(char) * iLen, SEEK_CUR); fcitx_utils_read_int32(fi, &iLen); if (isUser) fcitx_utils_read_int32(fi, &iLen); } } /* Second Pass: Actually read the data */ fseek(fi, 0, SEEK_SET); *pPYMB = PYMB = malloc(sizeof(*PYMB) * (n + 1)); for (i = 0; i < n; ++i) { fcitx_utils_read_int32(fi, &(PYMB[i].PYFAIndex)); int8_t clen; fread(&clen, sizeof(int8_t), 1, fi); fread(PYMB[i].HZ, sizeof(char) * clen, 1, fi); PYMB[i].HZ[clen] = '\0'; fcitx_utils_read_int32(fi, &(PYMB[i].UserPhraseCount)); PYMB[i].UserPhrase = malloc(sizeof(*(PYMB[i].UserPhrase)) * PYMB[i].UserPhraseCount); #define PU(i,j) (PYMB[(i)].UserPhrase[(j)]) for (j = 0; j < PYMB[i].UserPhraseCount; ++j) { fcitx_utils_read_int32(fi, &(PU(i, j).Length)); PU(i, j).Map = malloc(sizeof(char) * PU(i, j).Length + 1); fread(PU(i, j).Map, sizeof(char) * PU(i, j).Length, 1, fi); PU(i, j).Map[PU(i, j).Length] = '\0'; int32_t iLen; fcitx_utils_read_int32(fi, &iLen); PU(i, j).Phrase = malloc(sizeof(char) * iLen + 1); fread(PU(i, j).Phrase, sizeof(char) * iLen, 1, fi); PU(i, j).Phrase[iLen] = '\0'; fcitx_utils_read_int32(fi, &(PU(i, j).Index)); if (isUser) fcitx_utils_read_int32(fi, &(PU(i, j).Hit)); else PU(i, j).Hit = 0; } #undef PU } PYMB[n].HZ[0] = '\0'; return; } int LoadPYBase(FILE *fi, struct _HZMap **pHZMap) { int32_t i, j, r, PYFACount; struct _HZMap *HZMap; r = fcitx_utils_read_int32(fi, &PYFACount); if (!r) return 0; *pHZMap = HZMap = malloc(sizeof(*HZMap) * (PYFACount + 1)); for (i = 0; i < PYFACount; ++i) { fread(HZMap[i].Map, sizeof(char) * 2, 1, fi); HZMap[i].Map[2] = '\0'; fcitx_utils_read_int32(fi, &(HZMap[i].BaseCount)); HZMap[i].HZ = malloc(sizeof(char *) * HZMap[i].BaseCount); HZMap[i].Index = malloc(sizeof(int) * HZMap[i].BaseCount); for (j = 0; j < HZMap[i].BaseCount; ++j) { int8_t clen; fread(&clen, sizeof(int8_t), 1, fi); HZMap[i].HZ[j] = malloc(sizeof(char) * (clen + 1)); fread(HZMap[i].HZ[j], sizeof(char) * clen, 1, fi); HZMap[i].HZ[j][clen] = '\0'; fcitx_utils_read_int32(fi, &HZMap[i].Index[j]); } } HZMap[i].Map[0] = '\0'; return PYFACount; } // kate: indent-mode cstyle; space-indent on; indent-width 4;
{ "language": "C" }
#ifndef USOCKET_H #define USOCKET_H /*=========================================================================*\ * Socket compatibilization module for Unix * LuaSocket toolkit \*=========================================================================*/ /*=========================================================================*\ * BSD include files \*=========================================================================*/ /* error codes */ #include <errno.h> /* close function */ #include <unistd.h> /* fnctnl function and associated constants */ #include <fcntl.h> /* struct sockaddr */ #include <sys/types.h> /* socket function */ #include <sys/socket.h> /* struct timeval */ #include <sys/time.h> /* gethostbyname and gethostbyaddr functions */ #include <netdb.h> /* sigpipe handling */ #include <signal.h> /* IP stuff*/ #include <netinet/in.h> #include <arpa/inet.h> /* TCP options (nagle algorithm disable) */ #include <netinet/tcp.h> #include <net/if.h> #ifndef SO_REUSEPORT #define SO_REUSEPORT SO_REUSEADDR #endif /* Some platforms use IPV6_JOIN_GROUP instead if * IPV6_ADD_MEMBERSHIP. The semantics are same, though. */ #ifndef IPV6_ADD_MEMBERSHIP #ifdef IPV6_JOIN_GROUP #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP #endif /* IPV6_JOIN_GROUP */ #endif /* !IPV6_ADD_MEMBERSHIP */ /* Same with IPV6_DROP_MEMBERSHIP / IPV6_LEAVE_GROUP. */ #ifndef IPV6_DROP_MEMBERSHIP #ifdef IPV6_LEAVE_GROUP #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP #endif /* IPV6_LEAVE_GROUP */ #endif /* !IPV6_DROP_MEMBERSHIP */ typedef int t_socket; typedef t_socket *p_socket; typedef struct sockaddr_storage t_sockaddr_storage; #define SOCKET_INVALID (-1) #endif /* USOCKET_H */
{ "language": "C" }
// Copyright (C) 2018-2019, Cloudflare, Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <ev.h> #include <quiche.h> #define LOCAL_CONN_ID_LEN 16 #define MAX_DATAGRAM_SIZE 1350 struct conn_io { ev_timer timer; int sock; quiche_conn *conn; }; static void debug_log(const char *line, void *argp) { fprintf(stderr, "%s\n", line); } static void flush_egress(struct ev_loop *loop, struct conn_io *conn_io) { static uint8_t out[MAX_DATAGRAM_SIZE]; while (1) { ssize_t written = quiche_conn_send(conn_io->conn, out, sizeof(out)); if (written == QUICHE_ERR_DONE) { fprintf(stderr, "done writing\n"); break; } if (written < 0) { fprintf(stderr, "failed to create packet: %zd\n", written); return; } ssize_t sent = send(conn_io->sock, out, written, 0); if (sent != written) { perror("failed to send"); return; } fprintf(stderr, "sent %zd bytes\n", sent); } double t = quiche_conn_timeout_as_nanos(conn_io->conn) / 1e9f; conn_io->timer.repeat = t; ev_timer_again(loop, &conn_io->timer); } static void recv_cb(EV_P_ ev_io *w, int revents) { static bool req_sent = false; struct conn_io *conn_io = w->data; static uint8_t buf[65535]; while (1) { ssize_t read = recv(conn_io->sock, buf, sizeof(buf), 0); if (read < 0) { if ((errno == EWOULDBLOCK) || (errno == EAGAIN)) { fprintf(stderr, "recv would block\n"); break; } perror("failed to read"); return; } ssize_t done = quiche_conn_recv(conn_io->conn, buf, read); if (done < 0) { fprintf(stderr, "failed to process packet\n"); continue; } fprintf(stderr, "recv %zd bytes\n", done); } fprintf(stderr, "done reading\n"); if (quiche_conn_is_closed(conn_io->conn)) { fprintf(stderr, "connection closed\n"); ev_break(EV_A_ EVBREAK_ONE); return; } if (quiche_conn_is_established(conn_io->conn) && !req_sent) { const uint8_t *app_proto; size_t app_proto_len; quiche_conn_application_proto(conn_io->conn, &app_proto, &app_proto_len); fprintf(stderr, "connection established: %.*s\n", (int) app_proto_len, app_proto); const static uint8_t r[] = "GET /index.html\r\n"; if (quiche_conn_stream_send(conn_io->conn, 4, r, sizeof(r), true) < 0) { fprintf(stderr, "failed to send HTTP request\n"); return; } fprintf(stderr, "sent HTTP request\n"); req_sent = true; } if (quiche_conn_is_established(conn_io->conn)) { uint64_t s = 0; quiche_stream_iter *readable = quiche_conn_readable(conn_io->conn); while (quiche_stream_iter_next(readable, &s)) { fprintf(stderr, "stream %" PRIu64 " is readable\n", s); bool fin = false; ssize_t recv_len = quiche_conn_stream_recv(conn_io->conn, s, buf, sizeof(buf), &fin); if (recv_len < 0) { break; } printf("%.*s", (int) recv_len, buf); if (fin) { if (quiche_conn_close(conn_io->conn, true, 0, NULL, 0) < 0) { fprintf(stderr, "failed to close connection\n"); } } } quiche_stream_iter_free(readable); } flush_egress(loop, conn_io); } static void timeout_cb(EV_P_ ev_timer *w, int revents) { struct conn_io *conn_io = w->data; quiche_conn_on_timeout(conn_io->conn); fprintf(stderr, "timeout\n"); flush_egress(loop, conn_io); if (quiche_conn_is_closed(conn_io->conn)) { quiche_stats stats; quiche_conn_stats(conn_io->conn, &stats); fprintf(stderr, "connection closed, recv=%zu sent=%zu lost=%zu rtt=%" PRIu64 "ns\n", stats.recv, stats.sent, stats.lost, stats.rtt); ev_break(EV_A_ EVBREAK_ONE); return; } } int main(int argc, char *argv[]) { const char *host = argv[1]; const char *port = argv[2]; const struct addrinfo hints = { .ai_family = PF_UNSPEC, .ai_socktype = SOCK_DGRAM, .ai_protocol = IPPROTO_UDP }; quiche_enable_debug_logging(debug_log, NULL); struct addrinfo *peer; if (getaddrinfo(host, port, &hints, &peer) != 0) { perror("failed to resolve host"); return -1; } int sock = socket(peer->ai_family, SOCK_DGRAM, 0); if (sock < 0) { perror("failed to create socket"); return -1; } if (fcntl(sock, F_SETFL, O_NONBLOCK) != 0) { perror("failed to make socket non-blocking"); return -1; } if (connect(sock, peer->ai_addr, peer->ai_addrlen) < 0) { perror("failed to connect socket"); return -1; } quiche_config *config = quiche_config_new(0xbabababa); if (config == NULL) { fprintf(stderr, "failed to create config\n"); return -1; } quiche_config_set_application_protos(config, (uint8_t *) "\x05hq-29\x05hq-28\x05hq-27\x08http/0.9", 27); quiche_config_set_max_idle_timeout(config, 5000); quiche_config_set_max_udp_payload_size(config, MAX_DATAGRAM_SIZE); quiche_config_set_initial_max_data(config, 10000000); quiche_config_set_initial_max_stream_data_bidi_local(config, 1000000); quiche_config_set_initial_max_stream_data_uni(config, 1000000); quiche_config_set_initial_max_streams_bidi(config, 100); quiche_config_set_initial_max_streams_uni(config, 100); quiche_config_set_disable_active_migration(config, true); if (getenv("SSLKEYLOGFILE")) { quiche_config_log_keys(config); } uint8_t scid[LOCAL_CONN_ID_LEN]; int rng = open("/dev/urandom", O_RDONLY); if (rng < 0) { perror("failed to open /dev/urandom"); return -1; } ssize_t rand_len = read(rng, &scid, sizeof(scid)); if (rand_len < 0) { perror("failed to create connection ID"); return -1; } quiche_conn *conn = quiche_connect(host, (const uint8_t *) scid, sizeof(scid), config); if (conn == NULL) { fprintf(stderr, "failed to create connection\n"); return -1; } struct conn_io *conn_io = malloc(sizeof(*conn_io)); if (conn_io == NULL) { fprintf(stderr, "failed to allocate connection IO\n"); return -1; } conn_io->sock = sock; conn_io->conn = conn; ev_io watcher; struct ev_loop *loop = ev_default_loop(0); ev_io_init(&watcher, recv_cb, conn_io->sock, EV_READ); ev_io_start(loop, &watcher); watcher.data = conn_io; ev_init(&conn_io->timer, timeout_cb); conn_io->timer.data = conn_io; flush_egress(loop, conn_io); ev_loop(loop, 0); freeaddrinfo(peer); quiche_conn_free(conn); quiche_config_free(config); return 0; }
{ "language": "C" }
/** * Marlin 3D Printer Firmware * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm * * 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/>. * */ /** * Sanguinololu board pin assignments */ /** * Rev B 26 DEC 2016 * * 1) added pointer to a current Arduino IDE extension * 2) added support for M3, M4 & M5 spindle control commands * 3) added case light pin definition * */ /** * A useable Arduino IDE extension (board manager) can be found at * https://github.com/Lauszus/Sanguino * * This extension has been tested on Arduino 1.6.12 & 1.8.0 * * Here's the JSON path: * https://raw.githubusercontent.com/Lauszus/Sanguino/master/package_lauszus_sanguino_index.json * * When installing select 1.0.2 * * Installation instructions can be found at https://learn.sparkfun.com/pages/CustomBoardsArduino * Just use the above JSON URL instead of Sparkfun's JSON. * * Once installed select the Sanguino board and then select the CPU. * */ #if !defined(__AVR_ATmega644P__) && !defined(__AVR_ATmega1284P__) #error "Oops! Make sure you have 'Sanguino' selected from the 'Tools -> Boards' menu." #endif #ifndef BOARD_NAME #define BOARD_NAME "Sanguinololu <1.2" #endif // // Limit Switches // #define X_STOP_PIN 18 #define Y_STOP_PIN 19 #define Z_STOP_PIN 20 // // Steppers // #define X_STEP_PIN 15 #define X_DIR_PIN 21 #define Y_STEP_PIN 22 #define Y_DIR_PIN 23 #define Z_STEP_PIN 3 #define Z_DIR_PIN 2 #define E0_STEP_PIN 1 #define E0_DIR_PIN 0 // // Temperature Sensors // #define TEMP_0_PIN 7 // Analog Input (pin 33 extruder) #define TEMP_BED_PIN 6 // Analog Input (pin 34 bed) // // Heaters / Fans // #define HEATER_0_PIN 13 // (extruder) #if ENABLED(SANGUINOLOLU_V_1_2) #define HEATER_BED_PIN 12 // (bed) #define X_ENABLE_PIN 14 #define Y_ENABLE_PIN 14 #define Z_ENABLE_PIN 26 #define E0_ENABLE_PIN 14 #if !defined(FAN_PIN) && ENABLED(LCD_I2C_PANELOLU2) #define FAN_PIN 4 // Uses Transistor1 (PWM) on Panelolu2's Sanguino Adapter Board to drive the fan #endif #else #define HEATER_BED_PIN 14 // (bed) #define X_ENABLE_PIN -1 #define Y_ENABLE_PIN -1 #define Z_ENABLE_PIN -1 #define E0_ENABLE_PIN -1 #endif #if !defined(FAN_PIN) && (MB(AZTEEG_X1) || MB(STB_11) || ENABLED(IS_MELZI)) #define FAN_PIN 4 // Works for Panelolu2 too #endif // // Misc. Functions // /** * In some versions of the Sanguino libraries the pin * definitions are wrong, with SDSS = 24 and LED_PIN = 28 (Melzi). * If you encounter issues with these pins, upgrade your * Sanguino libraries! See #368. */ //#define SDSS 24 #define SDSS 31 #if ENABLED(IS_MELZI) #define LED_PIN 27 #elif MB(STB_11) #define LCD_BACKLIGHT_PIN 17 // LCD backlight LED #endif #if DISABLED(SPINDLE_LASER_ENABLE) && ENABLED(SANGUINOLOLU_V_1_2) && !(ENABLED(ULTRA_LCD) && ENABLED(NEWPANEL)) // try to use IO Header #define CASE_LIGHT_PIN 4 // MUST BE HARDWARE PWM - see if IO Header is available #endif /** * Sanguinololu 1.4 AUX pins: * * PWM TX1 RX1 SDA SCL * 12V 5V D12 D11 D10 D17 D16 * GND GND D31 D30 D29 D28 D27 * A4 A3 A2 A1 A0 */ // // LCD / Controller // #if ENABLED(ULTRA_LCD) && ENABLED(NEWPANEL) #if ENABLED(DOGLCD) #if ENABLED(U8GLIB_ST7920) // SPI GLCD 12864 ST7920 ( like [www.digole.com] ) For Melzi V2.0 #if ENABLED(IS_MELZI) #define LCD_PINS_RS 30 // CS chip select /SS chip slave select #define LCD_PINS_ENABLE 29 // SID (MOSI) #define LCD_PINS_D4 17 // SCK (CLK) clock // Pin 27 is taken by LED_PIN, but Melzi LED does nothing with // Marlin so this can be used for BEEPER_PIN. You can use this pin // with M42 instead of BEEPER_PIN. #define BEEPER_PIN 27 #else // Sanguinololu >=1.3 #define LCD_PINS_RS 4 #define LCD_PINS_ENABLE 17 #define LCD_PINS_D4 30 #define LCD_PINS_D5 29 #define LCD_PINS_D6 28 #define LCD_PINS_D7 27 #endif #else // DOGM SPI LCD Support #define DOGLCD_A0 30 #define LCD_CONTRAST 1 #if ENABLED(MAKRPANEL) #define BEEPER_PIN 29 #define DOGLCD_CS 17 #define LCD_BACKLIGHT_PIN 28 // PA3 #elif ENABLED(IS_MELZI) #define BEEPER_PIN 27 #define DOGLCD_CS 28 #else // !MAKRPANEL #define DOGLCD_CS 29 #endif #endif // Uncomment screen orientation #define LCD_SCREEN_ROT_0 //#define LCD_SCREEN_ROT_90 //#define LCD_SCREEN_ROT_180 //#define LCD_SCREEN_ROT_270 #else // !DOGLCD #define LCD_PINS_RS 4 #define LCD_PINS_ENABLE 17 #define LCD_PINS_D4 30 #define LCD_PINS_D5 29 #define LCD_PINS_D6 28 #define LCD_PINS_D7 27 #endif // !DOGLCD #define BTN_EN1 11 #define BTN_EN2 10 #if ENABLED(LCD_I2C_PANELOLU2) #if ENABLED(IS_MELZI) #define BTN_ENC 29 #define LCD_SDSS 30 // Panelolu2 SD card reader rather than the Melzi #else #define BTN_ENC 30 #endif #elif ENABLED(LCD_FOR_MELZI) #define LCD_PINS_RS 17 #define LCD_PINS_ENABLE 16 #define LCD_PINS_D4 11 #define BTN_ENC 28 #define BTN_EN1 29 #define BTN_EN2 30 #ifndef ST7920_DELAY_1 #define ST7920_DELAY_1 DELAY_NS(0) #endif #ifndef ST7920_DELAY_2 #define ST7920_DELAY_2 DELAY_NS(188) #endif #ifndef ST7920_DELAY_3 #define ST7920_DELAY_3 DELAY_NS(0) #endif #elif ENABLED(ZONESTAR_LCD) // For the Tronxy Melzi boards #define LCD_PINS_RS 28 #define LCD_PINS_ENABLE 29 #define LCD_PINS_D4 10 #define LCD_PINS_D5 11 #define LCD_PINS_D6 16 #define LCD_PINS_D7 17 #define ADC_KEYPAD_PIN 1 // Not used #define BTN_EN1 -1 #define BTN_EN2 -1 #else // !LCD_I2C_PANELOLU2 && !LCD_FOR_MELZI && !ZONESTAR_LCD #define BTN_ENC 16 #define LCD_SDSS 28 // Smart Controller SD card reader rather than the Melzi #endif #define SD_DETECT_PIN -1 #endif // ULTRA_LCD && NEWPANEL // // M3/M4/M5 - Spindle/Laser Control // #if ENABLED(SPINDLE_LASER_ENABLE) #if !MB(AZTEEG_X1) && ENABLED(SANGUINOLOLU_V_1_2) && !(ENABLED(ULTRA_LCD) && ENABLED(NEWPANEL)) // try to use IO Header #define SPINDLE_LASER_ENABLE_PIN 10 // Pin should have a pullup/pulldown! #define SPINDLE_LASER_PWM_PIN 4 // MUST BE HARDWARE PWM #define SPINDLE_DIR_PIN 11 #elif !MB(MELZI) // use X stepper motor socket /** * To control the spindle speed and have an LCD you must sacrifice * the Extruder and pull some signals off the X stepper driver socket. * * The following assumes: * - The X stepper driver socket is empty * - The extruder driver socket has a driver board plugged into it * - The X stepper wires are attached the the extruder connector */ /** * Where to get the spindle signals * * spindle signal socket name socket name * ------- * /ENABLE O| |O VMOT * MS1 O| |O GND * MS2 O| |O 2B * MS3 O| |O 2A * /RESET O| |O 1A * /SLEEP O| |O 1B * SPINDLE_LASER_PWM_PIN STEP O| |O VDD * SPINDLE_LASER_ENABLE_PIN DIR O| |O GND * ------- * * Note: Socket names vary from vendor to vendor. */ #undef X_DIR_PIN #undef X_ENABLE_PIN #undef X_STEP_PIN #define X_DIR_PIN 0 #define X_ENABLE_PIN 14 #define X_STEP_PIN 1 #define SPINDLE_LASER_PWM_PIN 15 // MUST BE HARDWARE PWM #define SPINDLE_LASER_ENABLE_PIN 21 // Pin should have a pullup! #define SPINDLE_DIR_PIN -1 // No pin available on the socket for the direction pin #endif #endif // SPINDLE_LASER_ENABLE
{ "language": "C" }
/* * wpa_supplicant/hostapd / OS specific functions for Win32 systems * Copyright (c) 2005-2006, Jouni Malinen <j@w1.fi> * * 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. * * Alternatively, this software may be distributed under the terms of BSD * license. * * See README and COPYING for more details. */ #include "includes.h" #include <winsock2.h> #include <wincrypt.h> #include "os.h" void os_sleep(os_time_t sec, os_time_t usec) { if (sec) Sleep(sec * 1000); if (usec) Sleep(usec / 1000); } int os_get_time(struct os_time *t) { #define EPOCHFILETIME (116444736000000000ULL) FILETIME ft; LARGE_INTEGER li; ULONGLONG tt; #ifdef _WIN32_WCE SYSTEMTIME st; GetSystemTime(&st); SystemTimeToFileTime(&st, &ft); #else /* _WIN32_WCE */ GetSystemTimeAsFileTime(&ft); #endif /* _WIN32_WCE */ li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; tt = (li.QuadPart - EPOCHFILETIME) / 10; t->sec = (os_time_t) (tt / 1000000); t->usec = (os_time_t) (tt % 1000000); return 0; } int os_mktime(int year, int month, int day, int hour, int min, int sec, os_time_t *t) { struct tm tm, *tm1; time_t t_local, t1, t2; os_time_t tz_offset; if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60) return -1; memset(&tm, 0, sizeof(tm)); tm.tm_year = year - 1900; tm.tm_mon = month - 1; tm.tm_mday = day; tm.tm_hour = hour; tm.tm_min = min; tm.tm_sec = sec; t_local = mktime(&tm); /* figure out offset to UTC */ tm1 = localtime(&t_local); if (tm1) { t1 = mktime(tm1); tm1 = gmtime(&t_local); if (tm1) { t2 = mktime(tm1); tz_offset = t2 - t1; } else tz_offset = 0; } else tz_offset = 0; *t = (os_time_t) t_local - tz_offset; return 0; } int os_daemonize(const char *pid_file) { /* TODO */ return -1; } void os_daemonize_terminate(const char *pid_file) { } int os_get_random(unsigned char *buf, size_t len) { HCRYPTPROV prov; BOOL ret; if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) return -1; ret = CryptGenRandom(prov, len, buf); CryptReleaseContext(prov, 0); return ret ? 0 : -1; } unsigned long os_random(void) { return rand(); } char * os_rel2abs_path(const char *rel_path) { return _strdup(rel_path); } int os_program_init(void) { #ifdef CONFIG_NATIVE_WINDOWS WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 0), &wsaData)) { printf("Could not find a usable WinSock.dll\n"); return -1; } #endif /* CONFIG_NATIVE_WINDOWS */ return 0; } void os_program_deinit(void) { #ifdef CONFIG_NATIVE_WINDOWS WSACleanup(); #endif /* CONFIG_NATIVE_WINDOWS */ } int os_setenv(const char *name, const char *value, int overwrite) { return -1; } int os_unsetenv(const char *name) { return -1; } char * os_readfile(const char *name, size_t *len) { FILE *f; char *buf; f = fopen(name, "rb"); if (f == NULL) return NULL; fseek(f, 0, SEEK_END); *len = ftell(f); fseek(f, 0, SEEK_SET); buf = malloc(*len); if (buf == NULL) { fclose(f); return NULL; } fread(buf, 1, *len, f); fclose(f); return buf; } void * os_zalloc(size_t size) { return calloc(1, size); } size_t os_strlcpy(char *dest, const char *src, size_t siz) { const char *s = src; size_t left = siz; if (left) { /* Copy string up to the maximum size of the dest buffer */ while (--left != 0) { if ((*dest++ = *s++) == '\0') break; } } if (left == 0) { /* Not enough room for the string; force NUL-termination */ if (siz != 0) *dest = '\0'; while (*s++) ; /* determine total src string length */ } return s - src - 1; }
{ "language": "C" }
/* * CTRubyAnnotation.h * CoreText * * Copyright (c) 2012-2018 Apple Inc. All rights reserved. * */ /*! @header Thread Safety Information All functions in this header are thread safe unless otherwise specified. */ #ifndef __CTRUBYANNOTATION__ #define __CTRUBYANNOTATION__ #include <CoreText/CTDefines.h> #include <CoreFoundation/CoreFoundation.h> #include <CoreGraphics/CoreGraphics.h> CF_IMPLICIT_BRIDGING_ENABLED CF_EXTERN_C_BEGIN CF_ASSUME_NONNULL_BEGIN /* --------------------------------------------------------------------------- */ /* RubyAnnotation Types */ /* --------------------------------------------------------------------------- */ typedef const struct CF_BRIDGED_TYPE(id) __CTRubyAnnotation * CTRubyAnnotationRef; /*! @function CTRubyAnnotationGetTypeID @abstract Returns the CFType of the ruby annotation object */ CFTypeID CTRubyAnnotationGetTypeID( void ) CT_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); /* --------------------------------------------------------------------------- */ /* Ruby alignment Values */ /* --------------------------------------------------------------------------- */ /*! @enum CTRubyAlignment @abstract These constants specify how to align the ruby annotation and the base text relative to each other when they don't have the same length. @constant kCTRubyAlignmentAuto CoreText will determine the alignment. @constant kCTRubyAlignmentStart The ruby text is aligned with the start edge of the base text. @constant kCTRubyAlignmentCenter The ruby text is centered within the width of the base text. If the ruby text is wider than the base text the base text is centered in the width of the ruby text. @constant kCTRubyAlignmentEnd The ruby text is aligned with the end edge of the base text. @constant kCTRubyAlignmentDistributeLetter If the width of the ruby text is less than the width of the base text, the ruby text is evenly distributed over the width of the base text, with the first letter of the ruby text aligning with the first letter of the base text and the last letter of the ruby text aligning with the last letter of the base text. If the width of the base text is less than the width of the ruby text, the base text is evenly distributed over the width of the ruby text. @constant kCTRubyAlignmentDistributeSpace If the width of the ruby text is less than the width of the base text, the ruby text is evenly distributed over the width of the base text, with a certain amount of space, usually half the inter-character width of the ruby text, before the first and after the last character. If the width of the base text is less than the width of the ruby text, the base text is similarly aligned to the width of the ruby text. @constant kCTRubyAlignmentLineEdge If the ruby text is not adjacent to a line edge it is aligned as with kCTRubyAlignmentAuto. If it is adjacent to a line edge the end of ruby text adjacent to the line edge is aligned to the line edge. This is only relevant if the width of the ruby text is greater than the width of the base text; otherwise alignment is as with kCTRubyAlignmentAuto. */ typedef CF_ENUM(uint8_t, CTRubyAlignment) { kCTRubyAlignmentInvalid = (uint8_t)-1, kCTRubyAlignmentAuto = 0, kCTRubyAlignmentStart = 1, kCTRubyAlignmentCenter = 2, kCTRubyAlignmentEnd = 3, kCTRubyAlignmentDistributeLetter = 4, kCTRubyAlignmentDistributeSpace = 5, kCTRubyAlignmentLineEdge = 6 } CT_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); /* --------------------------------------------------------------------------- */ /* Ruby overhang Values */ /* --------------------------------------------------------------------------- */ /*! @enum CTRubyOverhang @abstract These constants specify whether, and on which side, ruby text is allowed to overhang adjacent text if it is wider than the base text. @constant kCTRubyOverhangAuto The ruby text can overhang adjacent text on both sides. @constant kCTRubyOverhangStart The ruby text can overhang the text that proceeds it. @constant kCTRubyOverhangEnd The ruby text can overhang the text that follows it. @constant kCTRubyOverhangNone The ruby text cannot overhang the proceeding or following text. */ typedef CF_ENUM(uint8_t, CTRubyOverhang) { kCTRubyOverhangInvalid = (uint8_t)-1, kCTRubyOverhangAuto = 0, kCTRubyOverhangStart = 1, kCTRubyOverhangEnd = 2, kCTRubyOverhangNone = 3 } CT_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); /* --------------------------------------------------------------------------- */ /* Ruby position Values */ /* --------------------------------------------------------------------------- */ /*! @enum CTRubyPosition @abstract These constants specify the position of the ruby text with respect to the base text. @constant kCTRubyPositionBefore The ruby text is positioned before the base text; i.e. above horizontal text and to the right of vertical text. @constant kCTRubyPositionAfter The ruby text is positioned after the base text; i.e. below horizontal text and to the left of vertical text. @constant kCTRubyPositionInterCharacter The ruby text is positioned to the right of the base text whether it is horizontal or vertical. This is the way that Bopomofo annotations are attached to Chinese text in Taiwan. @constant kCTRubyPositionInline The ruby text follows the base text with no special styling. */ typedef CF_ENUM(uint8_t, CTRubyPosition) { kCTRubyPositionBefore = 0, kCTRubyPositionAfter = 1, kCTRubyPositionInterCharacter = 2, kCTRubyPositionInline = 3, kCTRubyPositionCount } CT_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); /* --------------------------------------------------------------------------- */ /* Ruby Annotation Creation */ /* --------------------------------------------------------------------------- */ /*! @function CTRubyAnnotationCreate @abstract Creates an immutable ruby annotation object. @discussion Using this function is the easiest and most efficient way to create a ruby annotation object. @param alignment Specifies how the ruby text and the base text should be aligned relative to each other. @param overhang Specifies how the ruby text can overhang adjacent characters. @param sizeFactor Specifies the size of the annotation text as a percent of the size of the base text. @param text An array of CFStringRef, indexed by CTRubyPosition. Supply NULL for any unused positions. @result This function will return a reference to a CTRubyAnnotation object. */ CTRubyAnnotationRef CTRubyAnnotationCreate( CTRubyAlignment alignment, CTRubyOverhang overhang, CGFloat sizeFactor, CFStringRef _Nullable text[_Nonnull kCTRubyPositionCount] ) CT_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); /*! @const kCTRubyAnnotationSizeFactorAttributeName @abstract Specifies the size of the annotation text as a percent of the size of the base text. @discussion Value must be a CFNumberRef. */ CT_EXPORT const CFStringRef kCTRubyAnnotationSizeFactorAttributeName CT_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0)); /*! @const kCTRubyAnnotationScaleToFitAttributeName @abstract Treat the size specified in kCTRubyAnnotationSizeFactorAttributeName as the maximum scale factor, when the base text size is smaller than annotation text size, we will try to scale the annotation font size down so that it will fit the base text without overhang or adding extra padding between base text. @discussion Value must be a CFBooleanRef. Default is false. */ CT_EXPORT const CFStringRef kCTRubyAnnotationScaleToFitAttributeName CT_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0)); /*! @function CTRubyAnnotationCreateWithAttributes @abstract Creates an immutable ruby annotation object. @discussion Using this function to create a ruby annotation object with more precise control of the annotation text. @param alignment Specifies how the ruby text and the base text should be aligned relative to each other. @param overhang Specifies how the ruby text can overhang adjacent characters. @param position The position of the annotation text. @param string A string without any formatting, its format will be derived from the attrs specified below. @param attributes A attribute dictionary to combine with the string specified above. If you don't specify kCTFontAttributeName, the font used by the Ruby annotation will be deduced from the base text, with a size factor specified by a CFNumberRef value keyed by kCTRubyAnnotationSizeFactorAttributeName. @result This function will return a reference to a CTRubyAnnotation object. */ CTRubyAnnotationRef CTRubyAnnotationCreateWithAttributes( CTRubyAlignment alignment, CTRubyOverhang overhang, CTRubyPosition position, CFStringRef string, CFDictionaryRef attributes ) CT_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0)); /*! @function CTRubyAnnotationCreateCopy @abstract Creates an immutable copy of a ruby annotation object. @param rubyAnnotation The ruby annotation that you wish to copy. @result If the "rubyAnnotation" reference is valid, then this function will return valid reference to an immutable CTRubyAnnotation object that is a copy of the one passed into "rubyAnnotation". */ CTRubyAnnotationRef CTRubyAnnotationCreateCopy( CTRubyAnnotationRef rubyAnnotation ) CT_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); /*! @function CTRubyAnnotationGetAlignment @abstract Get the alignment value of a ruby annotation object. @param rubyAnnotation The ruby annotation object. @result If the "rubyAnnotation" reference is valid, then this function will return its alignment. Otherwise it will return kCTRubyAlignmentInvalid. */ CTRubyAlignment CTRubyAnnotationGetAlignment( CTRubyAnnotationRef rubyAnnotation ) CT_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); /*! @function CTRubyAnnotationGetOverhang @abstract Get the overhang value of a ruby annotation object. @param rubyAnnotation The ruby annotation object. @result If the "rubyAnnotation" reference is valid, then this function will return its overhang value. Otherwise it will return kCTRubyOverhangInvalid. */ CTRubyOverhang CTRubyAnnotationGetOverhang( CTRubyAnnotationRef rubyAnnotation ) CT_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); /*! @function CTRubyAnnotationGetSizeFactor @abstract Get the size factor of a ruby annotation object. @param rubyAnnotation The ruby annotation object. @result If the "rubyAnnotation" reference is valid, then this function will return its sizeFactor. Otherwise it will return 0. */ CGFloat CTRubyAnnotationGetSizeFactor( CTRubyAnnotationRef rubyAnnotation ) CT_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); /*! @function CTRubyAnnotationGetTextForPosition @abstract Get the ruby text for a particular position in a ruby annotation. @param rubyAnnotation The ruby annotation object. @param position The position for which you want to get the ruby text. @result If the "rubyAnnotation" reference and the position are valid, then this function will return a CFStringRef for the text. Otherwise it will return NULL. */ CFStringRef _Nullable CTRubyAnnotationGetTextForPosition( CTRubyAnnotationRef rubyAnnotation, CTRubyPosition position ) CT_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); CF_ASSUME_NONNULL_END CF_EXTERN_C_END CF_IMPLICIT_BRIDGING_DISABLED #endif
{ "language": "C" }
// RUN: %libomp-compile-and-run #include <stdio.h> #include <omp.h> int main() { omp_alloctrait_t at[2]; omp_allocator_handle_t a; void *p[2]; at[0].key = OMP_ATK_POOL_SIZE; at[0].value = 2 * 1024 * 1024; at[1].key = OMP_ATK_FALLBACK; at[1].value = OMP_ATV_NULL_FB; a = omp_init_allocator(omp_high_bw_mem_space, 2, at); printf("allocator hbw created: %p\n", a); #pragma omp parallel num_threads(2) { int i = omp_get_thread_num(); p[i] = omp_alloc(1024 * 1024, a); #pragma omp barrier printf("th %d, ptr %p\n", i, p[i]); omp_free(p[i], a); } if (a != omp_null_allocator) { // As an allocator has some small memory overhead // exactly one of the two pointers should be NULL // because of NULL fallback requested if ((p[0] == NULL && p[1] != NULL) || (p[0] != NULL && p[1] == NULL)) { printf("passed\n"); return 0; } else { printf("failed: pointers %p %p\n", p[0], p[1]); return 1; } } else { // NULL allocator should cause default allocations if (p[0] != NULL && p[1] != NULL) { printf("passed\n"); return 0; } else { printf("failed: pointers %p %p\n", p[0], p[1]); return 1; } } }
{ "language": "C" }
/* * Copyright (c) 1997-2012 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@ */ /*- * Copyright (c) 1982, 1986, 1991, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)tty_tty.c 8.2 (Berkeley) 9/23/93 */ /* * Indirect driver for controlling tty. */ #include <sys/param.h> #include <sys/systm.h> #include <sys/conf.h> #include <sys/ioctl.h> #include <sys/proc_internal.h> #include <sys/tty.h> #include <sys/vnode_internal.h> #include <sys/file_internal.h> #include <sys/kauth.h> /* Forward declarations for cdevsw[] entry */ /* XXX we should consider making these static */ int cttyopen(dev_t dev, int flag, int mode, proc_t p); int cttyclose(dev_t dev, int flag, int mode, proc_t p); int cttyread(dev_t dev, struct uio *uio, int flag); int cttywrite(dev_t dev, struct uio *uio, int flag); int cttyioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, proc_t p); int cttyselect(dev_t dev, int flag, void* wql, proc_t p); static vnode_t cttyvp(proc_t p); int cttyopen(dev_t dev, int flag, __unused int mode, proc_t p) { vnode_t ttyvp; int error; /* * A little hack--this device, used by many processes, * does an open on another device, which can cause unhappiness * if the second-level open blocks indefinitely (e.g. if the * master side has hung up). This driver doesn't care * about serializing opens and closes, so drop the lock. */ devsw_unlock(dev, S_IFCHR); if ((ttyvp = cttyvp(p)) == NULL) { error = ENXIO; } else { struct vfs_context context; context.vc_thread = current_thread(); context.vc_ucred = kauth_cred_proc_ref(p); error = VNOP_OPEN(ttyvp, flag, &context); kauth_cred_unref(&context.vc_ucred); vnode_put(ttyvp); } devsw_lock(dev, S_IFCHR); return (error); } /* * This driver is marked D_TRACKCLOSE and so gets a close * for every open so that ttyvp->v_specinfo->si_count can be kept sane. */ int cttyclose(dev_t dev, int flag, __unused int mode, proc_t p) { vnode_t ttyvp; int error; /* See locking commentary above. */ devsw_unlock(dev, S_IFCHR); if ((ttyvp = cttyvp(p)) == NULL) { error = ENXIO; } else { struct vfs_context context; context.vc_thread = current_thread(); context.vc_ucred = kauth_cred_proc_ref(p); error = VNOP_CLOSE(ttyvp, flag, &context); kauth_cred_unref(&context.vc_ucred); vnode_put(ttyvp); } devsw_lock(dev, S_IFCHR); return (error); } int cttyread(__unused dev_t dev, struct uio *uio, int flag) { vnode_t ttyvp = cttyvp(current_proc()); struct vfs_context context; int error; if (ttyvp == NULL) return (EIO); context.vc_thread = current_thread(); context.vc_ucred = NOCRED; error = VNOP_READ(ttyvp, uio, flag, &context); vnode_put(ttyvp); return (error); } int cttywrite(__unused dev_t dev, struct uio *uio, int flag) { vnode_t ttyvp = cttyvp(current_proc()); struct vfs_context context; int error; if (ttyvp == NULL) return (EIO); context.vc_thread = current_thread(); context.vc_ucred = NOCRED; error = VNOP_WRITE(ttyvp, uio, flag, &context); vnode_put(ttyvp); return (error); } int cttyioctl(__unused dev_t dev, u_long cmd, caddr_t addr, int flag, proc_t p) { vnode_t ttyvp = cttyvp(current_proc()); struct vfs_context context; struct session *sessp; int error = 0; if (ttyvp == NULL) return (EIO); if (cmd == TIOCSCTTY) { /* don't allow controlling tty to be set */ error = EINVAL; /* to controlling tty -- infinite recursion */ goto out; } if (cmd == TIOCNOTTY) { sessp = proc_session(p); if (!SESS_LEADER(p, sessp)) { OSBitAndAtomic(~((uint32_t)P_CONTROLT), &p->p_flag); if (sessp != SESSION_NULL) session_rele(sessp); error = 0; goto out; } else { if (sessp != SESSION_NULL) session_rele(sessp); error = EINVAL; goto out; } } context.vc_thread = current_thread(); context.vc_ucred = NOCRED; error = VNOP_IOCTL(ttyvp, cmd, addr, flag, &context); out: vnode_put(ttyvp); return (error); } int cttyselect(__unused dev_t dev, int flag, void* wql, __unused proc_t p) { vnode_t ttyvp = cttyvp(current_proc()); struct vfs_context context; int error; context.vc_thread = current_thread(); context.vc_ucred = NOCRED; if (ttyvp == NULL) return (1); /* try operation to get EOF/failure */ error = VNOP_SELECT(ttyvp, flag, FREAD|FWRITE, wql, &context); vnode_put(ttyvp); return (error); } /* This returns vnode with ioref */ static vnode_t cttyvp(proc_t p) { vnode_t vp; int vid; struct session *sessp; sessp = proc_session(p); session_lock(sessp); vp = (p->p_flag & P_CONTROLT ? sessp->s_ttyvp : NULLVP); vid = sessp->s_ttyvid; session_unlock(sessp); session_rele(sessp); if (vp != NULLVP) { /* cannot get an IO reference, return NULLVP */ if (vnode_getwithvid(vp, vid) != 0) vp = NULLVP; } return(vp); }
{ "language": "C" }
/************************************************************************** * * Copyright 2006 VMware, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, 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 NON-INFRINGEMENT. * IN NO EVENT SHALL VMWARE 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. * **************************************************************************/ /* Provide additional functionality on top of bufmgr buffers: * - 2d semantics and blit operations * - refcounting of buffers for multiple images in a buffer. * - refcounting of buffer mappings. * - some logic for moving the buffers to the best memory pools for * given operations. * * Most of this is to make it easier to implement the fixed-layout * mipmap tree required by intel hardware in the face of GL's * programming interface where each image can be specifed in random * order and it isn't clear what layout the tree should have until the * last moment. */ #include <sys/ioctl.h> #include <errno.h> #include "main/hash.h" #include "intel_context.h" #include "intel_regions.h" #include "intel_blit.h" #include "intel_buffer_objects.h" #include "intel_bufmgr.h" #include "intel_batchbuffer.h" #define FILE_DEBUG_FLAG DEBUG_REGION /* This should be set to the maximum backtrace size desired. * Set it to 0 to disable backtrace debugging. */ #define DEBUG_BACKTRACE_SIZE 0 #if DEBUG_BACKTRACE_SIZE == 0 /* Use the standard debug output */ #define _DBG(...) DBG(__VA_ARGS__) #else /* Use backtracing debug output */ #define _DBG(...) {debug_backtrace(); DBG(__VA_ARGS__);} /* Backtracing debug support */ #include <execinfo.h> static void debug_backtrace(void) { void *trace[DEBUG_BACKTRACE_SIZE]; char **strings = NULL; int traceSize; register int i; traceSize = backtrace(trace, DEBUG_BACKTRACE_SIZE); strings = backtrace_symbols(trace, traceSize); if (strings == NULL) { DBG("no backtrace:"); return; } /* Spit out all the strings with a colon separator. Ignore * the first, since we don't really care about the call * to debug_backtrace() itself. Skip until the final "/" in * the trace to avoid really long lines. */ for (i = 1; i < traceSize; i++) { char *p = strings[i], *slash = strings[i]; while (*p) { if (*p++ == '/') { slash = p; } } DBG("%s:", slash); } /* Free up the memory, and we're done */ free(strings); } #endif static struct intel_region * intel_region_alloc_internal(struct intel_screen *screen, GLuint cpp, GLuint width, GLuint height, GLuint pitch, uint32_t tiling, drm_intel_bo *buffer) { struct intel_region *region; region = calloc(sizeof(*region), 1); if (region == NULL) return region; region->cpp = cpp; region->width = width; region->height = height; region->pitch = pitch; region->refcount = 1; region->bo = buffer; region->tiling = tiling; _DBG("%s <-- %p\n", __FUNCTION__, region); return region; } struct intel_region * intel_region_alloc(struct intel_screen *screen, uint32_t tiling, GLuint cpp, GLuint width, GLuint height, bool expect_accelerated_upload) { drm_intel_bo *buffer; unsigned long flags = 0; unsigned long aligned_pitch; struct intel_region *region; if (expect_accelerated_upload) flags |= BO_ALLOC_FOR_RENDER; buffer = drm_intel_bo_alloc_tiled(screen->bufmgr, "region", width, height, cpp, &tiling, &aligned_pitch, flags); if (buffer == NULL) return NULL; region = intel_region_alloc_internal(screen, cpp, width, height, aligned_pitch, tiling, buffer); if (region == NULL) { drm_intel_bo_unreference(buffer); return NULL; } return region; } bool intel_region_flink(struct intel_region *region, uint32_t *name) { if (region->name == 0) { if (drm_intel_bo_flink(region->bo, &region->name)) return false; } *name = region->name; return true; } struct intel_region * intel_region_alloc_for_handle(struct intel_screen *screen, GLuint cpp, GLuint width, GLuint height, GLuint pitch, GLuint handle, const char *name) { struct intel_region *region; drm_intel_bo *buffer; int ret; uint32_t bit_6_swizzle, tiling; buffer = intel_bo_gem_create_from_name(screen->bufmgr, name, handle); if (buffer == NULL) return NULL; ret = drm_intel_bo_get_tiling(buffer, &tiling, &bit_6_swizzle); if (ret != 0) { fprintf(stderr, "Couldn't get tiling of buffer %d (%s): %s\n", handle, name, strerror(-ret)); drm_intel_bo_unreference(buffer); return NULL; } region = intel_region_alloc_internal(screen, cpp, width, height, pitch, tiling, buffer); if (region == NULL) { drm_intel_bo_unreference(buffer); return NULL; } region->name = handle; return region; } struct intel_region * intel_region_alloc_for_fd(struct intel_screen *screen, GLuint cpp, GLuint width, GLuint height, GLuint pitch, GLuint size, int fd, const char *name) { struct intel_region *region; drm_intel_bo *buffer; int ret; uint32_t bit_6_swizzle, tiling; buffer = drm_intel_bo_gem_create_from_prime(screen->bufmgr, fd, size); if (buffer == NULL) return NULL; ret = drm_intel_bo_get_tiling(buffer, &tiling, &bit_6_swizzle); if (ret != 0) { fprintf(stderr, "Couldn't get tiling of buffer (%s): %s\n", name, strerror(-ret)); drm_intel_bo_unreference(buffer); return NULL; } region = intel_region_alloc_internal(screen, cpp, width, height, pitch, tiling, buffer); if (region == NULL) { drm_intel_bo_unreference(buffer); return NULL; } return region; } void intel_region_reference(struct intel_region **dst, struct intel_region *src) { _DBG("%s: %p(%d) -> %p(%d)\n", __FUNCTION__, *dst, *dst ? (*dst)->refcount : 0, src, src ? src->refcount : 0); if (src != *dst) { if (*dst) intel_region_release(dst); if (src) src->refcount++; *dst = src; } } void intel_region_release(struct intel_region **region_handle) { struct intel_region *region = *region_handle; if (region == NULL) { _DBG("%s NULL\n", __FUNCTION__); return; } _DBG("%s %p %d\n", __FUNCTION__, region, region->refcount - 1); ASSERT(region->refcount > 0); region->refcount--; if (region->refcount == 0) { drm_intel_bo_unreference(region->bo); free(region); } *region_handle = NULL; } /** * This function computes masks that may be used to select the bits of the X * and Y coordinates that indicate the offset within a tile. If the region is * untiled, the masks are set to 0. */ void intel_region_get_tile_masks(struct intel_region *region, uint32_t *mask_x, uint32_t *mask_y, bool map_stencil_as_y_tiled) { int cpp = region->cpp; uint32_t tiling = region->tiling; if (map_stencil_as_y_tiled) tiling = I915_TILING_Y; switch (tiling) { default: assert(false); case I915_TILING_NONE: *mask_x = *mask_y = 0; break; case I915_TILING_X: *mask_x = 512 / cpp - 1; *mask_y = 7; break; case I915_TILING_Y: *mask_x = 128 / cpp - 1; *mask_y = 31; break; } } /** * Compute the offset (in bytes) from the start of the region to the given x * and y coordinate. For tiled regions, caller must ensure that x and y are * multiples of the tile size. */ uint32_t intel_region_get_aligned_offset(struct intel_region *region, uint32_t x, uint32_t y, bool map_stencil_as_y_tiled) { int cpp = region->cpp; uint32_t pitch = region->pitch; uint32_t tiling = region->tiling; if (map_stencil_as_y_tiled) { tiling = I915_TILING_Y; /* When mapping a W-tiled stencil buffer as Y-tiled, each 64-high W-tile * gets transformed into a 32-high Y-tile. Accordingly, the pitch of * the resulting region is twice the pitch of the original region, since * each row in the Y-tiled view corresponds to two rows in the actual * W-tiled surface. So we need to correct the pitch before computing * the offsets. */ pitch *= 2; } switch (tiling) { default: assert(false); case I915_TILING_NONE: return y * pitch + x * cpp; case I915_TILING_X: assert((x % (512 / cpp)) == 0); assert((y % 8) == 0); return y * pitch + x / (512 / cpp) * 4096; case I915_TILING_Y: assert((x % (128 / cpp)) == 0); assert((y % 32) == 0); return y * pitch + x / (128 / cpp) * 4096; } }
{ "language": "C" }
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2016 Blender Foundation. * All rights reserved. */ #pragma once /** \file * \ingroup editor/io */ struct wmOperatorType; void CACHEFILE_OT_open(struct wmOperatorType *ot); void CACHEFILE_OT_reload(struct wmOperatorType *ot);
{ "language": "C" }
/* * COPYRIGHT: GPL - See COPYING in the top level directory * PROJECT: ReactOS Virtual DOS Machine * FILE: subsystems/mvdm/ntvdm/hardware/pit.c * PURPOSE: Programmable Interval Timer emulation - * i82C54/8254 compatible * PROGRAMMERS: Aleksandar Andrejevic <theflash AT sdf DOT lonestar DOT org> * Hermes Belusca-Maito (hermes.belusca@sfr.fr) */ /* INCLUDES *******************************************************************/ #include "ntvdm.h" #define NDEBUG #include <debug.h> #include "emulator.h" #include "pit.h" #include "io.h" #include "pic.h" #include "clock.h" /* PRIVATE VARIABLES **********************************************************/ static PIT_CHANNEL PitChannels[PIT_CHANNELS]; static PHARDWARE_TIMER MasterClock; /* PRIVATE FUNCTIONS **********************************************************/ static VOID PitLatchChannelStatus(BYTE Channel) { if (Channel >= PIT_CHANNELS) return; /* * A given counter can be latched only one time until it gets unlatched. * If the counter is latched and then is latched again later before the * value is read, then this last latch command is ignored and the value * will be the value at the time the first command was issued. */ if (PitChannels[Channel].LatchStatusSet == FALSE) { BYTE StatusLatch = 0; /** HACK!! **/BYTE NullCount = 0;/** HACK!! **/ StatusLatch = PitChannels[Channel].Out << 7 | NullCount << 6; StatusLatch |= (PitChannels[Channel].ReadWriteMode & 0x03) << 4; StatusLatch |= (PitChannels[Channel].Mode & 0x07) << 1; StatusLatch |= (PitChannels[Channel].Bcd & 0x01); /* Latch the counter's status */ PitChannels[Channel].LatchStatusSet = TRUE; PitChannels[Channel].StatusLatch = StatusLatch; } } static VOID PitLatchChannelCount(BYTE Channel) { if (Channel >= PIT_CHANNELS) return; /* * A given counter can be latched only one time until it gets unlatched. * If the counter is latched and then is latched again later before the * value is read, then this last latch command is ignored and the value * will be the value at the time the first command was issued. */ if (PitChannels[Channel].ReadStatus == 0x00) { /* Latch the counter's value */ PitChannels[Channel].ReadStatus = PitChannels[Channel].ReadWriteMode; /* Convert the current value to BCD if needed */ PitChannels[Channel].OutputLatch = READ_PIT_VALUE(PitChannels[Channel], PitChannels[Channel].CurrentValue); } } static VOID PitSetOut(PPIT_CHANNEL Channel, BOOLEAN State) { /** HACK!! **\ if (State == Channel->Out) return; \** HACK!! **/ /* Set the new state of the OUT pin */ Channel->Out = State; /* Call the callback */ if (!Channel->Gate) return; // HACK: This is a HACK until gates are properly used (needed for the speaker to work properly). if (Channel->OutFunction) Channel->OutFunction(Channel->OutParam, State); } static VOID PitInitCounter(PPIT_CHANNEL Channel) { switch (Channel->Mode) { case PIT_MODE_INT_ON_TERMINAL_COUNT: PitSetOut(Channel, FALSE); break; case PIT_MODE_HARDWARE_ONE_SHOT: case PIT_MODE_RATE_GENERATOR: case PIT_MODE_SQUARE_WAVE: case PIT_MODE_SOFTWARE_STROBE: case PIT_MODE_HARDWARE_STROBE: PitSetOut(Channel, TRUE); break; } } static VOID PitWriteCommand(BYTE Value) { BYTE Channel = (Value >> 6) & 0x03; BYTE ReadWriteMode = (Value >> 4) & 0x03; BYTE Mode = (Value >> 1) & 0x07; BOOLEAN IsBcd = Value & 0x01; /* * Check for valid PIT channel - Possible values: 0, 1, 2. * A value of 3 is for Read-Back Command. */ if (Channel > PIT_CHANNELS) return; /* Read-Back Command */ if (Channel == PIT_CHANNELS) { if ((Value & 0x20) == 0) // Bit 5 (Count) == 0: We latch multiple counters' counts { if (Value & 0x02) PitLatchChannelCount(0); if (Value & 0x04) PitLatchChannelCount(1); if (Value & 0x08) PitLatchChannelCount(2); } if ((Value & 0x10) == 0) // Bit 4 (Status) == 0: We latch multiple counters' statuses { if (Value & 0x02) PitLatchChannelStatus(0); if (Value & 0x04) PitLatchChannelStatus(1); if (Value & 0x08) PitLatchChannelStatus(2); } return; } /* Check if this is a counter latch command... */ if (ReadWriteMode == 0) { PitLatchChannelCount(Channel); return; } /* ... otherwise, set the modes and reset flip-flops */ PitChannels[Channel].ReadWriteMode = ReadWriteMode; PitChannels[Channel].ReadStatus = 0x00; PitChannels[Channel].WriteStatus = 0x00; PitChannels[Channel].LatchStatusSet = FALSE; PitChannels[Channel].StatusLatch = 0x00; PitChannels[Channel].CountRegister = 0x00; PitChannels[Channel].OutputLatch = 0x00; /** HACK!! **/PitChannels[Channel].FlipFlop = FALSE;/** HACK!! **/ /* Fix the current value if we switch to BCD counting */ PitChannels[Channel].Bcd = IsBcd; if (IsBcd && PitChannels[Channel].CurrentValue > 9999) PitChannels[Channel].CurrentValue = 9999; switch (Mode) { case 0: case 1: case 2: case 3: case 4: case 5: { PitChannels[Channel].Mode = Mode; break; } case 6: case 7: { /* * Modes 6 and 7 become PIT_MODE_RATE_GENERATOR * and PIT_MODE_SQUARE_WAVE respectively. */ PitChannels[Channel].Mode = Mode - 4; break; } } PitInitCounter(&PitChannels[Channel]); } static BYTE PitReadData(BYTE Channel) { LPBYTE ReadWriteMode = NULL; LPWORD CurrentValue = NULL; /* * If the status was latched, the first read operation will return the * latched status, whichever value (count or status) was latched first. */ if (PitChannels[Channel].LatchStatusSet) { PitChannels[Channel].LatchStatusSet = FALSE; return PitChannels[Channel].StatusLatch; } /* To be able to read the count asynchronously, latch it first if needed */ if (PitChannels[Channel].ReadStatus == 0) PitLatchChannelCount(Channel); /* The count is now latched */ ASSERT(PitChannels[Channel].ReadStatus != 0); ReadWriteMode = &PitChannels[Channel].ReadStatus ; CurrentValue = &PitChannels[Channel].OutputLatch; if (*ReadWriteMode & 1) { /* Read LSB */ *ReadWriteMode &= ~1; return LOBYTE(*CurrentValue); } if (*ReadWriteMode & 2) { /* Read MSB */ *ReadWriteMode &= ~2; return HIBYTE(*CurrentValue); } /* Shouldn't get here */ ASSERT(FALSE); return 0; } static VOID PitWriteData(BYTE Channel, BYTE Value) { LPBYTE ReadWriteMode = NULL; if (PitChannels[Channel].WriteStatus == 0x00) { PitChannels[Channel].WriteStatus = PitChannels[Channel].ReadWriteMode; } ASSERT(PitChannels[Channel].WriteStatus != 0); ReadWriteMode = &PitChannels[Channel].WriteStatus; if (*ReadWriteMode & 1) { /* Write LSB */ *ReadWriteMode &= ~1; PitChannels[Channel].CountRegister &= 0xFF00; PitChannels[Channel].CountRegister |= Value; } else if (*ReadWriteMode & 2) { /* Write MSB */ *ReadWriteMode &= ~2; PitChannels[Channel].CountRegister &= 0x00FF; PitChannels[Channel].CountRegister |= Value << 8; } /* ReadWriteMode went to zero: we are going to load the new count */ if (*ReadWriteMode == 0x00) { if (PitChannels[Channel].CountRegister == 0x0000) { /* Wrap around to the highest count */ if (PitChannels[Channel].Bcd) PitChannels[Channel].CountRegister = 9999; else PitChannels[Channel].CountRegister = 0xFFFF; // 0x10000; // 65536 } /* Convert the current value from BCD if needed */ PitChannels[Channel].CountRegister = WRITE_PIT_VALUE(PitChannels[Channel], PitChannels[Channel].CountRegister); PitChannels[Channel].ReloadValue = PitChannels[Channel].CountRegister; /* Reload now the new count */ PitChannels[Channel].CurrentValue = PitChannels[Channel].ReloadValue; } } static BYTE WINAPI PitReadPort(USHORT Port) { switch (Port) { case PIT_DATA_PORT(0): case PIT_DATA_PORT(1): case PIT_DATA_PORT(2): { return PitReadData(Port - PIT_DATA_PORT(0)); } } return 0; } static VOID WINAPI PitWritePort(USHORT Port, BYTE Data) { switch (Port) { case PIT_COMMAND_PORT: { PitWriteCommand(Data); break; } case PIT_DATA_PORT(0): case PIT_DATA_PORT(1): case PIT_DATA_PORT(2): { PitWriteData(Port - PIT_DATA_PORT(0), Data); break; } } } static VOID PitDecrementCount(PPIT_CHANNEL Channel, DWORD Count) { if (Count == 0) return; switch (Channel->Mode) { case PIT_MODE_INT_ON_TERMINAL_COUNT: { /* Decrement the value */ if (Count > Channel->CurrentValue) { /* The value does not reload in this case */ Channel->CurrentValue = 0; } else Channel->CurrentValue -= Count; /* Did it fall to the terminal count? */ if (Channel->CurrentValue == 0 && !Channel->Out) { /* Yes, raise the output line */ PitSetOut(Channel, TRUE); } break; } case PIT_MODE_RATE_GENERATOR: { BOOLEAN Reloaded = FALSE; while (Count) { if ((Count > Channel->CurrentValue) && (Channel->CurrentValue != 0)) { /* Decrement the count */ Count -= Channel->CurrentValue; /* Reload the value */ Channel->CurrentValue = Channel->ReloadValue; /* Set the flag */ Reloaded = TRUE; } else { /* Decrement the value */ Channel->CurrentValue -= Count; /* Clear the count */ Count = 0; /* Did it fall to zero? */ if (Channel->CurrentValue == 0) { Channel->CurrentValue = Channel->ReloadValue; Reloaded = TRUE; } } } /* If there was a reload, raise the output line */ if (Reloaded) PitSetOut(Channel, TRUE); break; } case PIT_MODE_SQUARE_WAVE: { INT ReloadCount = 0; WORD ReloadValue = Channel->ReloadValue; /* The reload value must be even */ ReloadValue &= ~1; while (Count) { if (((Count * 2) > Channel->CurrentValue) && (Channel->CurrentValue != 0)) { /* Decrement the count */ Count -= Channel->CurrentValue / 2; /* Reload the value */ Channel->CurrentValue = ReloadValue; /* Increment the reload count */ ReloadCount++; } else { /* Decrement the value */ Channel->CurrentValue -= Count * 2; /* Clear the count */ Count = 0; /* Did it fall to zero? */ if (Channel->CurrentValue == 0) { /* Reload the value */ Channel->CurrentValue = ReloadValue; /* Increment the reload count */ ReloadCount++; } } } if (ReloadCount == 0) break; /* Toggle the flip-flop if the number of reloads was odd */ if (ReloadCount & 1) { Channel->FlipFlop = !Channel->FlipFlop; PitSetOut(Channel, !Channel->Out); } /* Was there any rising edge? */ if ((Channel->FlipFlop && (ReloadCount == 1)) || (ReloadCount > 1)) { /* Yes, raise the output line */ PitSetOut(Channel, TRUE); } break; } case PIT_MODE_SOFTWARE_STROBE: { // TODO: NOT IMPLEMENTED break; } case PIT_MODE_HARDWARE_ONE_SHOT: case PIT_MODE_HARDWARE_STROBE: { /* These modes do not work on x86 PCs */ break; } } } static VOID FASTCALL PitClock(ULONGLONG Count) { UCHAR i; for (i = 0; i < PIT_CHANNELS; i++) { // if (!PitChannels[i].Counting) continue; PitDecrementCount(&PitChannels[i], Count); } } /* PUBLIC FUNCTIONS ***********************************************************/ VOID PitSetOutFunction(BYTE Channel, LPVOID Param, PIT_OUT_FUNCTION OutFunction) { if (Channel >= PIT_CHANNELS) return; PitChannels[Channel].OutParam = Param; PitChannels[Channel].OutFunction = OutFunction; } VOID PitSetGate(BYTE Channel, BOOLEAN State) { if (Channel >= PIT_CHANNELS) return; if (State == PitChannels[Channel].Gate) return; /* UNIMPLEMENTED */ PitChannels[Channel].Gate = State; } WORD PitGetReloadValue(BYTE Channel) { if (Channel >= PIT_CHANNELS) return 0xFFFF; if (PitChannels[Channel].ReloadValue == 0) return 0xFFFF; else return PitChannels[Channel].ReloadValue; } VOID PitInitialize(VOID) { /* Set up the timers to their default value */ PitSetOutFunction(0, NULL, NULL); PitSetGate(0, TRUE); PitSetOutFunction(1, NULL, NULL); PitSetGate(1, TRUE); PitSetOutFunction(2, NULL, NULL); PitSetGate(2, FALSE); /* Register the I/O Ports */ RegisterIoPort(PIT_COMMAND_PORT, NULL, PitWritePort); RegisterIoPort(PIT_DATA_PORT(0), PitReadPort, PitWritePort); RegisterIoPort(PIT_DATA_PORT(1), PitReadPort, PitWritePort); RegisterIoPort(PIT_DATA_PORT(2), PitReadPort, PitWritePort); /* Register the hardware timer */ MasterClock = CreateHardwareTimer(HARDWARE_TIMER_ENABLED | HARDWARE_TIMER_PRECISE, HZ_TO_NS(PIT_BASE_FREQUENCY), PitClock); } /* EOF */
{ "language": "C" }
/* * ILA kernel interface * * Copyright (c) 2015 Tom Herbert <tom@herbertland.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. */ #ifndef _NET_ILA_H #define _NET_ILA_H int ila_xlat_outgoing(struct sk_buff *skb); int ila_xlat_incoming(struct sk_buff *skb); #endif /* _NET_ILA_H */
{ "language": "C" }
/* -*- mode: c -*- */ /* Copyright (C) 2008-2016 Alexander Chernov <cher@ejudge.ru> */ /* * 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 "ejudge/sock_op.h" #include <stdlib.h> int sock_op_put_creds(int sock_fd) { abort(); }
{ "language": "C" }
/* SPDX-License-Identifier: GPL-2.0+ */ /* * Copyright (C) 2017, STMicroelectronics - All Rights Reserved * Author(s): Vikas Manocha, <vikas.manocha@st.com> for STMicroelectronics. */ #ifndef _ASM_ARMV7_MPU_H #define _ASM_ARMV7_MPU_H #ifdef CONFIG_CPU_V7M #define AP_SHIFT 24 #define XN_SHIFT 28 #define TEX_SHIFT 19 #define S_SHIFT 18 #define C_SHIFT 17 #define B_SHIFT 16 #else /* CONFIG_CPU_V7R */ #define XN_SHIFT 12 #define AP_SHIFT 8 #define TEX_SHIFT 3 #define S_SHIFT 2 #define C_SHIFT 1 #define B_SHIFT 0 #endif /* CONFIG_CPU_V7R */ #define CACHEABLE BIT(C_SHIFT) #define BUFFERABLE BIT(B_SHIFT) #define SHAREABLE BIT(S_SHIFT) #define REGION_SIZE_SHIFT 1 #define ENABLE_REGION BIT(0) #define DISABLE_REGION 0 enum region_number { REGION_0 = 0, REGION_1, REGION_2, REGION_3, REGION_4, REGION_5, REGION_6, REGION_7, }; enum ap { NO_ACCESS = 0, PRIV_RW_USR_NO, PRIV_RW_USR_RO, PRIV_RW_USR_RW, UNPREDICTABLE, PRIV_RO_USR_NO, PRIV_RO_USR_RO, }; enum mr_attr { STRONG_ORDER = 0, SHARED_WRITE_BUFFERED, O_I_WT_NO_WR_ALLOC, O_I_WB_NO_WR_ALLOC, O_I_NON_CACHEABLE, O_I_WB_RD_WR_ALLOC, DEVICE_NON_SHARED, }; enum size { REGION_8MB = 22, REGION_16MB, REGION_32MB, REGION_64MB, REGION_128MB, REGION_256MB, REGION_512MB, REGION_1GB, REGION_2GB, REGION_4GB, }; enum xn { XN_DIS = 0, XN_EN, }; struct mpu_region_config { uint32_t start_addr; enum region_number region_no; enum xn xn; enum ap ap; enum mr_attr mr_attr; enum size reg_size; }; void disable_mpu(void); void enable_mpu(void); int mpu_enabled(void); void mpu_config(struct mpu_region_config *reg_config); void setup_mpu_regions(struct mpu_region_config *rgns, u32 num_rgns); static inline u32 get_attr_encoding(u32 mr_attr) { u32 attr; switch (mr_attr) { case STRONG_ORDER: attr = SHAREABLE; break; case SHARED_WRITE_BUFFERED: attr = BUFFERABLE; break; case O_I_WT_NO_WR_ALLOC: attr = CACHEABLE; break; case O_I_WB_NO_WR_ALLOC: attr = CACHEABLE | BUFFERABLE; break; case O_I_NON_CACHEABLE: attr = 1 << TEX_SHIFT; break; case O_I_WB_RD_WR_ALLOC: attr = (1 << TEX_SHIFT) | CACHEABLE | BUFFERABLE; break; case DEVICE_NON_SHARED: attr = (2 << TEX_SHIFT) | BUFFERABLE; break; default: attr = 0; /* strongly ordered */ break; }; return attr; } #endif /* _ASM_ARMV7_MPU_H */
{ "language": "C" }
/* * Copyright (C) 2009 Texas Instruments 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. * * vpss - video processing subsystem module header file. * * Include this header file if a driver needs to configure vpss system * module. It exports a set of library functions for video drivers to * configure vpss system module functions such as clock enable/disable, * vpss interrupt mux to arm, and other common vpss system module * functions. */ #ifndef _VPSS_H #define _VPSS_H /* selector for ccdc input selection on DM355 */ enum vpss_ccdc_source_sel { VPSS_CCDCIN, VPSS_HSSIIN, VPSS_PGLPBK, /* for DM365 only */ VPSS_CCDCPG /* for DM365 only */ }; struct vpss_sync_pol { unsigned int ccdpg_hdpol:1; unsigned int ccdpg_vdpol:1; }; struct vpss_pg_frame_size { short hlpfr; short pplen; }; /* Used for enable/disable VPSS Clock */ enum vpss_clock_sel { /* DM355/DM365 */ VPSS_CCDC_CLOCK, VPSS_IPIPE_CLOCK, VPSS_H3A_CLOCK, VPSS_CFALD_CLOCK, /* * When using VPSS_VENC_CLOCK_SEL in vpss_enable_clock() api * following applies:- * en = 0 selects ENC_CLK * en = 1 selects ENC_CLK/2 */ VPSS_VENC_CLOCK_SEL, VPSS_VPBE_CLOCK, /* DM365 only clocks */ VPSS_IPIPEIF_CLOCK, VPSS_RSZ_CLOCK, VPSS_BL_CLOCK, /* * When using VPSS_PCLK_INTERNAL in vpss_enable_clock() api * following applies:- * en = 0 disable internal PCLK * en = 1 enables internal PCLK */ VPSS_PCLK_INTERNAL, /* * When using VPSS_PSYNC_CLOCK_SEL in vpss_enable_clock() api * following applies:- * en = 0 enables MMR clock * en = 1 enables VPSS clock */ VPSS_PSYNC_CLOCK_SEL, VPSS_LDC_CLOCK_SEL, VPSS_OSD_CLOCK_SEL, VPSS_FDIF_CLOCK, VPSS_LDC_CLOCK }; /* select input to ccdc on dm355 */ int vpss_select_ccdc_source(enum vpss_ccdc_source_sel src_sel); /* enable/disable a vpss clock, 0 - success, -1 - failure */ int vpss_enable_clock(enum vpss_clock_sel clock_sel, int en); /* set sync polarity, only for DM365*/ void dm365_vpss_set_sync_pol(struct vpss_sync_pol); /* set the PG_FRAME_SIZE register, only for DM365 */ void dm365_vpss_set_pg_frame_size(struct vpss_pg_frame_size); /* wbl reset for dm644x */ enum vpss_wbl_sel { VPSS_PCR_AEW_WBL_0 = 16, VPSS_PCR_AF_WBL_0, VPSS_PCR_RSZ4_WBL_0, VPSS_PCR_RSZ3_WBL_0, VPSS_PCR_RSZ2_WBL_0, VPSS_PCR_RSZ1_WBL_0, VPSS_PCR_PREV_WBL_0, VPSS_PCR_CCDC_WBL_O, }; /* clear wbl overflow flag for DM6446 */ int vpss_clear_wbl_overflow(enum vpss_wbl_sel wbl_sel); /* set sync polarity*/ void vpss_set_sync_pol(struct vpss_sync_pol sync); /* set the PG_FRAME_SIZE register */ void vpss_set_pg_frame_size(struct vpss_pg_frame_size frame_size); /* * vpss_check_and_clear_interrupt - check and clear interrupt * @irq - common enumerator for IRQ * * Following return values used:- * 0 - interrupt occurred and cleared * 1 - interrupt not occurred * 2 - interrupt status not available */ int vpss_dma_complete_interrupt(void); #endif
{ "language": "C" }
/* * Copyright 2014, General Dynamics C4 Systems * * SPDX-License-Identifier: GPL-2.0-only */ #include <config.h> #include <mode/machine.h> #include <api/debug.h> /* * The idle thread currently does not receive a stack pointer and so we rely on * optimisations for correctness here. More specifically, we assume: * - Ordinary prologue/epilogue stack operations are optimised out * - All nested function calls are inlined * Note that GCC does not correctly implement optimisation annotations on nested * functions, so FORCE_INLINE is required on the wfi declaration in this case. * Note that Clang doesn't obey FORCE_O2 and relies on the kernel being compiled * with optimisations enabled. */ void FORCE_O2 idle_thread(void) { while (1) { wfi(); } } /** DONT_TRANSLATE */ void NORETURN NO_INLINE VISIBLE halt(void) { /* halt is actually, idle thread without the interrupts */ asm volatile("cpsid iaf"); #ifdef CONFIG_PRINTING printf("halting..."); #ifdef CONFIG_DEBUG_BUILD debug_printKernelEntryReason(); #endif #endif idle_thread(); UNREACHABLE(); }
{ "language": "C" }
/* dso.h -*- mode:C; c-file-style: "eay" -*- */ /* Written by Geoff Thorpe (geoff@geoffthorpe.net) for the OpenSSL * project 2000. */ /* ==================================================================== * Copyright (c) 2000 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #ifndef HEADER_DSO_H #define HEADER_DSO_H #include <openssl/crypto.h> #ifdef __cplusplus extern "C" { #endif /* These values are used as commands to DSO_ctrl() */ #define DSO_CTRL_GET_FLAGS 1 #define DSO_CTRL_SET_FLAGS 2 #define DSO_CTRL_OR_FLAGS 3 /* By default, DSO_load() will translate the provided filename into a form * typical for the platform (more specifically the DSO_METHOD) using the * dso_name_converter function of the method. Eg. win32 will transform "blah" * into "blah.dll", and dlfcn will transform it into "libblah.so". The * behaviour can be overriden by setting the name_converter callback in the DSO * object (using DSO_set_name_converter()). This callback could even utilise * the DSO_METHOD's converter too if it only wants to override behaviour for * one or two possible DSO methods. However, the following flag can be set in a * DSO to prevent *any* native name-translation at all - eg. if the caller has * prompted the user for a path to a driver library so the filename should be * interpreted as-is. */ #define DSO_FLAG_NO_NAME_TRANSLATION 0x01 /* An extra flag to give if only the extension should be added as * translation. This is obviously only of importance on Unix and * other operating systems where the translation also may prefix * the name with something, like 'lib', and ignored everywhere else. * This flag is also ignored if DSO_FLAG_NO_NAME_TRANSLATION is used * at the same time. */ #define DSO_FLAG_NAME_TRANSLATION_EXT_ONLY 0x02 /* The following flag controls the translation of symbol names to upper * case. This is currently only being implemented for OpenVMS. */ #define DSO_FLAG_UPCASE_SYMBOL 0x10 /* This flag loads the library with public symbols. * Meaning: The exported symbols of this library are public * to all libraries loaded after this library. * At the moment only implemented in unix. */ #define DSO_FLAG_GLOBAL_SYMBOLS 0x20 typedef void (*DSO_FUNC_TYPE)(void); typedef struct dso_st DSO; /* The function prototype used for method functions (or caller-provided * callbacks) that transform filenames. They are passed a DSO structure pointer * (or NULL if they are to be used independantly of a DSO object) and a * filename to transform. They should either return NULL (if there is an error * condition) or a newly allocated string containing the transformed form that * the caller will need to free with OPENSSL_free() when done. */ typedef char* (*DSO_NAME_CONVERTER_FUNC)(DSO *, const char *); /* The function prototype used for method functions (or caller-provided * callbacks) that merge two file specifications. They are passed a * DSO structure pointer (or NULL if they are to be used independantly of * a DSO object) and two file specifications to merge. They should * either return NULL (if there is an error condition) or a newly allocated * string containing the result of merging that the caller will need * to free with OPENSSL_free() when done. * Here, merging means that bits and pieces are taken from each of the * file specifications and added together in whatever fashion that is * sensible for the DSO method in question. The only rule that really * applies is that if the two specification contain pieces of the same * type, the copy from the first string takes priority. One could see * it as the first specification is the one given by the user and the * second being a bunch of defaults to add on if they're missing in the * first. */ typedef char* (*DSO_MERGER_FUNC)(DSO *, const char *, const char *); typedef struct dso_meth_st { const char *name; /* Loads a shared library, NB: new DSO_METHODs must ensure that a * successful load populates the loaded_filename field, and likewise a * successful unload OPENSSL_frees and NULLs it out. */ int (*dso_load)(DSO *dso); /* Unloads a shared library */ int (*dso_unload)(DSO *dso); /* Binds a variable */ void *(*dso_bind_var)(DSO *dso, const char *symname); /* Binds a function - assumes a return type of DSO_FUNC_TYPE. * This should be cast to the real function prototype by the * caller. Platforms that don't have compatible representations * for different prototypes (this is possible within ANSI C) * are highly unlikely to have shared libraries at all, let * alone a DSO_METHOD implemented for them. */ DSO_FUNC_TYPE (*dso_bind_func)(DSO *dso, const char *symname); /* I don't think this would actually be used in any circumstances. */ #if 0 /* Unbinds a variable */ int (*dso_unbind_var)(DSO *dso, char *symname, void *symptr); /* Unbinds a function */ int (*dso_unbind_func)(DSO *dso, char *symname, DSO_FUNC_TYPE symptr); #endif /* The generic (yuck) "ctrl()" function. NB: Negative return * values (rather than zero) indicate errors. */ long (*dso_ctrl)(DSO *dso, int cmd, long larg, void *parg); /* The default DSO_METHOD-specific function for converting filenames to * a canonical native form. */ DSO_NAME_CONVERTER_FUNC dso_name_converter; /* The default DSO_METHOD-specific function for converting filenames to * a canonical native form. */ DSO_MERGER_FUNC dso_merger; /* [De]Initialisation handlers. */ int (*init)(DSO *dso); int (*finish)(DSO *dso); } DSO_METHOD; /**********************************************************************/ /* The low-level handle type used to refer to a loaded shared library */ struct dso_st { DSO_METHOD *meth; /* Standard dlopen uses a (void *). Win32 uses a HANDLE. VMS * doesn't use anything but will need to cache the filename * for use in the dso_bind handler. All in all, let each * method control its own destiny. "Handles" and such go in * a STACK. */ STACK *meth_data; int references; int flags; /* For use by applications etc ... use this for your bits'n'pieces, * don't touch meth_data! */ CRYPTO_EX_DATA ex_data; /* If this callback function pointer is set to non-NULL, then it will * be used in DSO_load() in place of meth->dso_name_converter. NB: This * should normally set using DSO_set_name_converter(). */ DSO_NAME_CONVERTER_FUNC name_converter; /* If this callback function pointer is set to non-NULL, then it will * be used in DSO_load() in place of meth->dso_merger. NB: This * should normally set using DSO_set_merger(). */ DSO_MERGER_FUNC merger; /* This is populated with (a copy of) the platform-independant * filename used for this DSO. */ char *filename; /* This is populated with (a copy of) the translated filename by which * the DSO was actually loaded. It is NULL iff the DSO is not currently * loaded. NB: This is here because the filename translation process * may involve a callback being invoked more than once not only to * convert to a platform-specific form, but also to try different * filenames in the process of trying to perform a load. As such, this * variable can be used to indicate (a) whether this DSO structure * corresponds to a loaded library or not, and (b) the filename with * which it was actually loaded. */ char *loaded_filename; }; DSO * DSO_new(void); DSO * DSO_new_method(DSO_METHOD *method); int DSO_free(DSO *dso); int DSO_flags(DSO *dso); int DSO_up_ref(DSO *dso); long DSO_ctrl(DSO *dso, int cmd, long larg, void *parg); /* This function sets the DSO's name_converter callback. If it is non-NULL, * then it will be used instead of the associated DSO_METHOD's function. If * oldcb is non-NULL then it is set to the function pointer value being * replaced. Return value is non-zero for success. */ int DSO_set_name_converter(DSO *dso, DSO_NAME_CONVERTER_FUNC cb, DSO_NAME_CONVERTER_FUNC *oldcb); /* These functions can be used to get/set the platform-independant filename * used for a DSO. NB: set will fail if the DSO is already loaded. */ const char *DSO_get_filename(DSO *dso); int DSO_set_filename(DSO *dso, const char *filename); /* This function will invoke the DSO's name_converter callback to translate a * filename, or if the callback isn't set it will instead use the DSO_METHOD's * converter. If "filename" is NULL, the "filename" in the DSO itself will be * used. If the DSO_FLAG_NO_NAME_TRANSLATION flag is set, then the filename is * simply duplicated. NB: This function is usually called from within a * DSO_METHOD during the processing of a DSO_load() call, and is exposed so that * caller-created DSO_METHODs can do the same thing. A non-NULL return value * will need to be OPENSSL_free()'d. */ char *DSO_convert_filename(DSO *dso, const char *filename); /* This function will invoke the DSO's merger callback to merge two file * specifications, or if the callback isn't set it will instead use the * DSO_METHOD's merger. A non-NULL return value will need to be * OPENSSL_free()'d. */ char *DSO_merge(DSO *dso, const char *filespec1, const char *filespec2); /* If the DSO is currently loaded, this returns the filename that it was loaded * under, otherwise it returns NULL. So it is also useful as a test as to * whether the DSO is currently loaded. NB: This will not necessarily return * the same value as DSO_convert_filename(dso, dso->filename), because the * DSO_METHOD's load function may have tried a variety of filenames (with * and/or without the aid of the converters) before settling on the one it * actually loaded. */ const char *DSO_get_loaded_filename(DSO *dso); void DSO_set_default_method(DSO_METHOD *meth); DSO_METHOD *DSO_get_default_method(void); DSO_METHOD *DSO_get_method(DSO *dso); DSO_METHOD *DSO_set_method(DSO *dso, DSO_METHOD *meth); /* The all-singing all-dancing load function, you normally pass NULL * for the first and third parameters. Use DSO_up and DSO_free for * subsequent reference count handling. Any flags passed in will be set * in the constructed DSO after its init() function but before the * load operation. If 'dso' is non-NULL, 'flags' is ignored. */ DSO *DSO_load(DSO *dso, const char *filename, DSO_METHOD *meth, int flags); /* This function binds to a variable inside a shared library. */ void *DSO_bind_var(DSO *dso, const char *symname); /* This function binds to a function inside a shared library. */ DSO_FUNC_TYPE DSO_bind_func(DSO *dso, const char *symname); /* This method is the default, but will beg, borrow, or steal whatever * method should be the default on any particular platform (including * DSO_METH_null() if necessary). */ DSO_METHOD *DSO_METHOD_openssl(void); /* This method is defined for all platforms - if a platform has no * DSO support then this will be the only method! */ DSO_METHOD *DSO_METHOD_null(void); /* If DSO_DLFCN is defined, the standard dlfcn.h-style functions * (dlopen, dlclose, dlsym, etc) will be used and incorporated into * this method. If not, this method will return NULL. */ DSO_METHOD *DSO_METHOD_dlfcn(void); /* If DSO_DL is defined, the standard dl.h-style functions (shl_load, * shl_unload, shl_findsym, etc) will be used and incorporated into * this method. If not, this method will return NULL. */ DSO_METHOD *DSO_METHOD_dl(void); /* If WIN32 is defined, use DLLs. If not, return NULL. */ DSO_METHOD *DSO_METHOD_win32(void); /* If VMS is defined, use shared images. If not, return NULL. */ DSO_METHOD *DSO_METHOD_vms(void); /* BEGIN ERROR CODES */ /* The following lines are auto generated by the script mkerr.pl. Any changes * made after this point may be overwritten when the script is next run. */ void ERR_load_DSO_strings(void); /* Error codes for the DSO functions. */ /* Function codes. */ #define DSO_F_DLFCN_BIND_FUNC 100 #define DSO_F_DLFCN_BIND_VAR 101 #define DSO_F_DLFCN_LOAD 102 #define DSO_F_DLFCN_MERGER 130 #define DSO_F_DLFCN_NAME_CONVERTER 123 #define DSO_F_DLFCN_UNLOAD 103 #define DSO_F_DL_BIND_FUNC 104 #define DSO_F_DL_BIND_VAR 105 #define DSO_F_DL_LOAD 106 #define DSO_F_DL_MERGER 131 #define DSO_F_DL_NAME_CONVERTER 124 #define DSO_F_DL_UNLOAD 107 #define DSO_F_DSO_BIND_FUNC 108 #define DSO_F_DSO_BIND_VAR 109 #define DSO_F_DSO_CONVERT_FILENAME 126 #define DSO_F_DSO_CTRL 110 #define DSO_F_DSO_FREE 111 #define DSO_F_DSO_GET_FILENAME 127 #define DSO_F_DSO_GET_LOADED_FILENAME 128 #define DSO_F_DSO_LOAD 112 #define DSO_F_DSO_MERGE 132 #define DSO_F_DSO_NEW_METHOD 113 #define DSO_F_DSO_SET_FILENAME 129 #define DSO_F_DSO_SET_NAME_CONVERTER 122 #define DSO_F_DSO_UP_REF 114 #define DSO_F_VMS_BIND_SYM 115 #define DSO_F_VMS_LOAD 116 #define DSO_F_VMS_MERGER 133 #define DSO_F_VMS_UNLOAD 117 #define DSO_F_WIN32_BIND_FUNC 118 #define DSO_F_WIN32_BIND_VAR 119 #define DSO_F_WIN32_JOINER 135 #define DSO_F_WIN32_LOAD 120 #define DSO_F_WIN32_MERGER 134 #define DSO_F_WIN32_NAME_CONVERTER 125 #define DSO_F_WIN32_SPLITTER 136 #define DSO_F_WIN32_UNLOAD 121 /* Reason codes. */ #define DSO_R_CTRL_FAILED 100 #define DSO_R_DSO_ALREADY_LOADED 110 #define DSO_R_EMPTY_FILE_STRUCTURE 113 #define DSO_R_FAILURE 114 #define DSO_R_FILENAME_TOO_BIG 101 #define DSO_R_FINISH_FAILED 102 #define DSO_R_INCORRECT_FILE_SYNTAX 115 #define DSO_R_LOAD_FAILED 103 #define DSO_R_NAME_TRANSLATION_FAILED 109 #define DSO_R_NO_FILENAME 111 #define DSO_R_NO_FILE_SPECIFICATION 116 #define DSO_R_NULL_HANDLE 104 #define DSO_R_SET_FILENAME_FAILED 112 #define DSO_R_STACK_ERROR 105 #define DSO_R_SYM_FAILURE 106 #define DSO_R_UNLOAD_FAILED 107 #define DSO_R_UNSUPPORTED 108 #ifdef __cplusplus } #endif #endif
{ "language": "C" }
/* 3c509.c: A 3c509 EtherLink3 ethernet driver for linux. */ /* Written 1993-2000 by Donald Becker. Copyright 1994-2000 by Donald Becker. Copyright 1993 United States Government as represented by the Director, National Security Agency. This software may be used and distributed according to the terms of the GNU General Public License, incorporated herein by reference. This driver is for the 3Com EtherLinkIII series. The author may be reached as becker@scyld.com, or C/O Scyld Computing Corporation 410 Severn Ave., Suite 210 Annapolis MD 21403 Known limitations: Because of the way 3c509 ISA detection works it's difficult to predict a priori which of several ISA-mode cards will be detected first. This driver does not use predictive interrupt mode, resulting in higher packet latency but lower overhead. If interrupts are disabled for an unusually long time it could also result in missed packets, but in practice this rarely happens. FIXES: Alan Cox: Removed the 'Unexpected interrupt' bug. Michael Meskes: Upgraded to Donald Becker's version 1.07. Alan Cox: Increased the eeprom delay. Regardless of what the docs say some people definitely get problems with lower (but in card spec) delays v1.10 4/21/97 Fixed module code so that multiple cards may be detected, other cleanups. -djb Andrea Arcangeli: Upgraded to Donald Becker's version 1.12. Rick Payne: Fixed SMP race condition v1.13 9/8/97 Made 'max_interrupt_work' an insmod-settable variable -djb v1.14 10/15/97 Avoided waiting..discard message for fast machines -djb v1.15 1/31/98 Faster recovery for Tx errors. -djb v1.16 2/3/98 Different ID port handling to avoid sound cards. -djb v1.18 12Mar2001 Andrew Morton - Avoid bogus detect of 3c590's (Andrzej Krzysztofowicz) - Reviewed against 1.18 from scyld.com v1.18a 17Nov2001 Jeff Garzik <jgarzik@pobox.com> - ethtool support v1.18b 1Mar2002 Zwane Mwaikambo <zwane@commfireservices.com> - Power Management support v1.18c 1Mar2002 David Ruggiero <jdr@farfalle.com> - Full duplex support v1.19 16Oct2002 Zwane Mwaikambo <zwane@linuxpower.ca> - Additional ethtool features v1.19a 28Oct2002 Davud Ruggiero <jdr@farfalle.com> - Increase *read_eeprom udelay to workaround oops with 2 cards. v1.19b 08Nov2002 Marc Zyngier <maz@wild-wind.fr.eu.org> - Introduce driver model for EISA cards. v1.20 04Feb2008 Ondrej Zary <linux@rainbow-software.org> - convert to isa_driver and pnp_driver and some cleanups */ #define DRV_NAME "3c509" #define DRV_VERSION "1.20" #define DRV_RELDATE "04Feb2008" /* A few values that may be tweaked. */ /* Time in jiffies before concluding the transmitter is hung. */ #define TX_TIMEOUT (400*HZ/1000) #include <linux/module.h> #include <linux/mca.h> #include <linux/isa.h> #include <linux/pnp.h> #include <linux/string.h> #include <linux/interrupt.h> #include <linux/errno.h> #include <linux/in.h> #include <linux/slab.h> #include <linux/ioport.h> #include <linux/init.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/pm.h> #include <linux/skbuff.h> #include <linux/delay.h> /* for udelay() */ #include <linux/spinlock.h> #include <linux/ethtool.h> #include <linux/device.h> #include <linux/eisa.h> #include <linux/bitops.h> #include <asm/uaccess.h> #include <asm/io.h> #include <asm/irq.h> static char version[] __devinitdata = DRV_NAME ".c:" DRV_VERSION " " DRV_RELDATE " becker@scyld.com\n"; #ifdef EL3_DEBUG static int el3_debug = EL3_DEBUG; #else static int el3_debug = 2; #endif /* Used to do a global count of all the cards in the system. Must be * a global variable so that the mca/eisa probe routines can increment * it */ static int el3_cards = 0; #define EL3_MAX_CARDS 8 /* To minimize the size of the driver source I only define operating constants if they are used several times. You'll need the manual anyway if you want to understand driver details. */ /* Offsets from base I/O address. */ #define EL3_DATA 0x00 #define EL3_CMD 0x0e #define EL3_STATUS 0x0e #define EEPROM_READ 0x80 #define EL3_IO_EXTENT 16 #define EL3WINDOW(win_num) outw(SelectWindow + (win_num), ioaddr + EL3_CMD) /* The top five bits written to EL3_CMD are a command, the lower 11 bits are the parameter, if applicable. */ enum c509cmd { TotalReset = 0<<11, SelectWindow = 1<<11, StartCoax = 2<<11, RxDisable = 3<<11, RxEnable = 4<<11, RxReset = 5<<11, RxDiscard = 8<<11, TxEnable = 9<<11, TxDisable = 10<<11, TxReset = 11<<11, FakeIntr = 12<<11, AckIntr = 13<<11, SetIntrEnb = 14<<11, SetStatusEnb = 15<<11, SetRxFilter = 16<<11, SetRxThreshold = 17<<11, SetTxThreshold = 18<<11, SetTxStart = 19<<11, StatsEnable = 21<<11, StatsDisable = 22<<11, StopCoax = 23<<11, PowerUp = 27<<11, PowerDown = 28<<11, PowerAuto = 29<<11}; enum c509status { IntLatch = 0x0001, AdapterFailure = 0x0002, TxComplete = 0x0004, TxAvailable = 0x0008, RxComplete = 0x0010, RxEarly = 0x0020, IntReq = 0x0040, StatsFull = 0x0080, CmdBusy = 0x1000, }; /* The SetRxFilter command accepts the following classes: */ enum RxFilter { RxStation = 1, RxMulticast = 2, RxBroadcast = 4, RxProm = 8 }; /* Register window 1 offsets, the window used in normal operation. */ #define TX_FIFO 0x00 #define RX_FIFO 0x00 #define RX_STATUS 0x08 #define TX_STATUS 0x0B #define TX_FREE 0x0C /* Remaining free bytes in Tx buffer. */ #define WN0_CONF_CTRL 0x04 /* Window 0: Configuration control register */ #define WN0_ADDR_CONF 0x06 /* Window 0: Address configuration register */ #define WN0_IRQ 0x08 /* Window 0: Set IRQ line in bits 12-15. */ #define WN4_MEDIA 0x0A /* Window 4: Various transcvr/media bits. */ #define MEDIA_TP 0x00C0 /* Enable link beat and jabber for 10baseT. */ #define WN4_NETDIAG 0x06 /* Window 4: Net diagnostic */ #define FD_ENABLE 0x8000 /* Enable full-duplex ("external loopback") */ /* * Must be a power of two (we use a binary and in the * circular queue) */ #define SKB_QUEUE_SIZE 64 enum el3_cardtype { EL3_ISA, EL3_PNP, EL3_MCA, EL3_EISA }; struct el3_private { spinlock_t lock; /* skb send-queue */ int head, size; struct sk_buff *queue[SKB_QUEUE_SIZE]; enum el3_cardtype type; }; static int id_port; static int current_tag; static struct net_device *el3_devs[EL3_MAX_CARDS]; /* Parameters that may be passed into the module. */ static int debug = -1; static int irq[] = {-1, -1, -1, -1, -1, -1, -1, -1}; /* Maximum events (Rx packets, etc.) to handle at each interrupt. */ static int max_interrupt_work = 10; #ifdef CONFIG_PNP static int nopnp; #endif static int __devinit el3_common_init(struct net_device *dev); static void el3_common_remove(struct net_device *dev); static ushort id_read_eeprom(int index); static ushort read_eeprom(int ioaddr, int index); static int el3_open(struct net_device *dev); static netdev_tx_t el3_start_xmit(struct sk_buff *skb, struct net_device *dev); static irqreturn_t el3_interrupt(int irq, void *dev_id); static void update_stats(struct net_device *dev); static struct net_device_stats *el3_get_stats(struct net_device *dev); static int el3_rx(struct net_device *dev); static int el3_close(struct net_device *dev); static void set_multicast_list(struct net_device *dev); static void el3_tx_timeout (struct net_device *dev); static void el3_down(struct net_device *dev); static void el3_up(struct net_device *dev); static const struct ethtool_ops ethtool_ops; #ifdef CONFIG_PM static int el3_suspend(struct device *, pm_message_t); static int el3_resume(struct device *); #else #define el3_suspend NULL #define el3_resume NULL #endif /* generic device remove for all device types */ static int el3_device_remove (struct device *device); #ifdef CONFIG_NET_POLL_CONTROLLER static void el3_poll_controller(struct net_device *dev); #endif /* Return 0 on success, 1 on error, 2 when found already detected PnP card */ static int el3_isa_id_sequence(__be16 *phys_addr) { short lrs_state = 0xff; int i; /* ISA boards are detected by sending the ID sequence to the ID_PORT. We find cards past the first by setting the 'current_tag' on cards as they are found. Cards with their tag set will not respond to subsequent ID sequences. */ outb(0x00, id_port); outb(0x00, id_port); for (i = 0; i < 255; i++) { outb(lrs_state, id_port); lrs_state <<= 1; lrs_state = lrs_state & 0x100 ? lrs_state ^ 0xcf : lrs_state; } /* For the first probe, clear all board's tag registers. */ if (current_tag == 0) outb(0xd0, id_port); else /* Otherwise kill off already-found boards. */ outb(0xd8, id_port); if (id_read_eeprom(7) != 0x6d50) return 1; /* Read in EEPROM data, which does contention-select. Only the lowest address board will stay "on-line". 3Com got the byte order backwards. */ for (i = 0; i < 3; i++) phys_addr[i] = htons(id_read_eeprom(i)); #ifdef CONFIG_PNP if (!nopnp) { /* The ISA PnP 3c509 cards respond to the ID sequence too. This check is needed in order not to register them twice. */ for (i = 0; i < el3_cards; i++) { struct el3_private *lp = netdev_priv(el3_devs[i]); if (lp->type == EL3_PNP && !memcmp(phys_addr, el3_devs[i]->dev_addr, ETH_ALEN)) { if (el3_debug > 3) pr_debug("3c509 with address %02x %02x %02x %02x %02x %02x was found by ISAPnP\n", phys_addr[0] & 0xff, phys_addr[0] >> 8, phys_addr[1] & 0xff, phys_addr[1] >> 8, phys_addr[2] & 0xff, phys_addr[2] >> 8); /* Set the adaptor tag so that the next card can be found. */ outb(0xd0 + ++current_tag, id_port); return 2; } } } #endif /* CONFIG_PNP */ return 0; } static void __devinit el3_dev_fill(struct net_device *dev, __be16 *phys_addr, int ioaddr, int irq, int if_port, enum el3_cardtype type) { struct el3_private *lp = netdev_priv(dev); memcpy(dev->dev_addr, phys_addr, ETH_ALEN); dev->base_addr = ioaddr; dev->irq = irq; dev->if_port = if_port; lp->type = type; } static int __devinit el3_isa_match(struct device *pdev, unsigned int ndev) { struct net_device *dev; int ioaddr, isa_irq, if_port, err; unsigned int iobase; __be16 phys_addr[3]; while ((err = el3_isa_id_sequence(phys_addr)) == 2) ; /* Skip to next card when PnP card found */ if (err == 1) return 0; iobase = id_read_eeprom(8); if_port = iobase >> 14; ioaddr = 0x200 + ((iobase & 0x1f) << 4); if (irq[el3_cards] > 1 && irq[el3_cards] < 16) isa_irq = irq[el3_cards]; else isa_irq = id_read_eeprom(9) >> 12; dev = alloc_etherdev(sizeof(struct el3_private)); if (!dev) return -ENOMEM; netdev_boot_setup_check(dev); if (!request_region(ioaddr, EL3_IO_EXTENT, "3c509-isa")) { free_netdev(dev); return 0; } /* Set the adaptor tag so that the next card can be found. */ outb(0xd0 + ++current_tag, id_port); /* Activate the adaptor at the EEPROM location. */ outb((ioaddr >> 4) | 0xe0, id_port); EL3WINDOW(0); if (inw(ioaddr) != 0x6d50) { free_netdev(dev); return 0; } /* Free the interrupt so that some other card can use it. */ outw(0x0f00, ioaddr + WN0_IRQ); el3_dev_fill(dev, phys_addr, ioaddr, isa_irq, if_port, EL3_ISA); dev_set_drvdata(pdev, dev); if (el3_common_init(dev)) { free_netdev(dev); return 0; } el3_devs[el3_cards++] = dev; return 1; } static int __devexit el3_isa_remove(struct device *pdev, unsigned int ndev) { el3_device_remove(pdev); dev_set_drvdata(pdev, NULL); return 0; } #ifdef CONFIG_PM static int el3_isa_suspend(struct device *dev, unsigned int n, pm_message_t state) { current_tag = 0; return el3_suspend(dev, state); } static int el3_isa_resume(struct device *dev, unsigned int n) { struct net_device *ndev = dev_get_drvdata(dev); int ioaddr = ndev->base_addr, err; __be16 phys_addr[3]; while ((err = el3_isa_id_sequence(phys_addr)) == 2) ; /* Skip to next card when PnP card found */ if (err == 1) return 0; /* Set the adaptor tag so that the next card can be found. */ outb(0xd0 + ++current_tag, id_port); /* Enable the card */ outb((ioaddr >> 4) | 0xe0, id_port); EL3WINDOW(0); if (inw(ioaddr) != 0x6d50) return 1; /* Free the interrupt so that some other card can use it. */ outw(0x0f00, ioaddr + WN0_IRQ); return el3_resume(dev); } #endif static struct isa_driver el3_isa_driver = { .match = el3_isa_match, .remove = __devexit_p(el3_isa_remove), #ifdef CONFIG_PM .suspend = el3_isa_suspend, .resume = el3_isa_resume, #endif .driver = { .name = "3c509" }, }; static int isa_registered; #ifdef CONFIG_PNP static struct pnp_device_id el3_pnp_ids[] = { { .id = "TCM5090" }, /* 3Com Etherlink III (TP) */ { .id = "TCM5091" }, /* 3Com Etherlink III */ { .id = "TCM5094" }, /* 3Com Etherlink III (combo) */ { .id = "TCM5095" }, /* 3Com Etherlink III (TPO) */ { .id = "TCM5098" }, /* 3Com Etherlink III (TPC) */ { .id = "PNP80f7" }, /* 3Com Etherlink III compatible */ { .id = "PNP80f8" }, /* 3Com Etherlink III compatible */ { .id = "" } }; MODULE_DEVICE_TABLE(pnp, el3_pnp_ids); static int __devinit el3_pnp_probe(struct pnp_dev *pdev, const struct pnp_device_id *id) { short i; int ioaddr, irq, if_port; __be16 phys_addr[3]; struct net_device *dev = NULL; int err; ioaddr = pnp_port_start(pdev, 0); if (!request_region(ioaddr, EL3_IO_EXTENT, "3c509-pnp")) return -EBUSY; irq = pnp_irq(pdev, 0); EL3WINDOW(0); for (i = 0; i < 3; i++) phys_addr[i] = htons(read_eeprom(ioaddr, i)); if_port = read_eeprom(ioaddr, 8) >> 14; dev = alloc_etherdev(sizeof(struct el3_private)); if (!dev) { release_region(ioaddr, EL3_IO_EXTENT); return -ENOMEM; } SET_NETDEV_DEV(dev, &pdev->dev); netdev_boot_setup_check(dev); el3_dev_fill(dev, phys_addr, ioaddr, irq, if_port, EL3_PNP); pnp_set_drvdata(pdev, dev); err = el3_common_init(dev); if (err) { pnp_set_drvdata(pdev, NULL); free_netdev(dev); return err; } el3_devs[el3_cards++] = dev; return 0; } static void __devexit el3_pnp_remove(struct pnp_dev *pdev) { el3_common_remove(pnp_get_drvdata(pdev)); pnp_set_drvdata(pdev, NULL); } #ifdef CONFIG_PM static int el3_pnp_suspend(struct pnp_dev *pdev, pm_message_t state) { return el3_suspend(&pdev->dev, state); } static int el3_pnp_resume(struct pnp_dev *pdev) { return el3_resume(&pdev->dev); } #endif static struct pnp_driver el3_pnp_driver = { .name = "3c509", .id_table = el3_pnp_ids, .probe = el3_pnp_probe, .remove = __devexit_p(el3_pnp_remove), #ifdef CONFIG_PM .suspend = el3_pnp_suspend, .resume = el3_pnp_resume, #endif }; static int pnp_registered; #endif /* CONFIG_PNP */ #ifdef CONFIG_EISA static struct eisa_device_id el3_eisa_ids[] = { { "TCM5090" }, { "TCM5091" }, { "TCM5092" }, { "TCM5093" }, { "TCM5094" }, { "TCM5095" }, { "TCM5098" }, { "" } }; MODULE_DEVICE_TABLE(eisa, el3_eisa_ids); static int el3_eisa_probe (struct device *device); static struct eisa_driver el3_eisa_driver = { .id_table = el3_eisa_ids, .driver = { .name = "3c579", .probe = el3_eisa_probe, .remove = __devexit_p (el3_device_remove), .suspend = el3_suspend, .resume = el3_resume, } }; static int eisa_registered; #endif #ifdef CONFIG_MCA static int el3_mca_probe(struct device *dev); static short el3_mca_adapter_ids[] __initdata = { 0x627c, 0x627d, 0x62db, 0x62f6, 0x62f7, 0x0000 }; static char *el3_mca_adapter_names[] __initdata = { "3Com 3c529 EtherLink III (10base2)", "3Com 3c529 EtherLink III (10baseT)", "3Com 3c529 EtherLink III (test mode)", "3Com 3c529 EtherLink III (TP or coax)", "3Com 3c529 EtherLink III (TP)", NULL }; static struct mca_driver el3_mca_driver = { .id_table = el3_mca_adapter_ids, .driver = { .name = "3c529", .bus = &mca_bus_type, .probe = el3_mca_probe, .remove = __devexit_p(el3_device_remove), .suspend = el3_suspend, .resume = el3_resume, }, }; static int mca_registered; #endif /* CONFIG_MCA */ static const struct net_device_ops netdev_ops = { .ndo_open = el3_open, .ndo_stop = el3_close, .ndo_start_xmit = el3_start_xmit, .ndo_get_stats = el3_get_stats, .ndo_set_multicast_list = set_multicast_list, .ndo_tx_timeout = el3_tx_timeout, .ndo_change_mtu = eth_change_mtu, .ndo_set_mac_address = eth_mac_addr, .ndo_validate_addr = eth_validate_addr, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = el3_poll_controller, #endif }; static int __devinit el3_common_init(struct net_device *dev) { struct el3_private *lp = netdev_priv(dev); int err; const char *if_names[] = {"10baseT", "AUI", "undefined", "BNC"}; spin_lock_init(&lp->lock); if (dev->mem_start & 0x05) { /* xcvr codes 1/3/4/12 */ dev->if_port = (dev->mem_start & 0x0f); } else { /* xcvr codes 0/8 */ /* use eeprom value, but save user's full-duplex selection */ dev->if_port |= (dev->mem_start & 0x08); } /* The EL3-specific entries in the device structure. */ dev->netdev_ops = &netdev_ops; dev->watchdog_timeo = TX_TIMEOUT; SET_ETHTOOL_OPS(dev, &ethtool_ops); err = register_netdev(dev); if (err) { pr_err("Failed to register 3c5x9 at %#3.3lx, IRQ %d.\n", dev->base_addr, dev->irq); release_region(dev->base_addr, EL3_IO_EXTENT); return err; } pr_info("%s: 3c5x9 found at %#3.3lx, %s port, address %pM, IRQ %d.\n", dev->name, dev->base_addr, if_names[(dev->if_port & 0x03)], dev->dev_addr, dev->irq); if (el3_debug > 0) pr_info("%s", version); return 0; } static void el3_common_remove (struct net_device *dev) { unregister_netdev (dev); release_region(dev->base_addr, EL3_IO_EXTENT); free_netdev (dev); } #ifdef CONFIG_MCA static int __init el3_mca_probe(struct device *device) { /* Based on Erik Nygren's (nygren@mit.edu) 3c529 patch, * heavily modified by Chris Beauregard * (cpbeaure@csclub.uwaterloo.ca) to support standard MCA * probing. * * redone for multi-card detection by ZP Gu (zpg@castle.net) * now works as a module */ short i; int ioaddr, irq, if_port; __be16 phys_addr[3]; struct net_device *dev = NULL; u_char pos4, pos5; struct mca_device *mdev = to_mca_device(device); int slot = mdev->slot; int err; pos4 = mca_device_read_stored_pos(mdev, 4); pos5 = mca_device_read_stored_pos(mdev, 5); ioaddr = ((short)((pos4&0xfc)|0x02)) << 8; irq = pos5 & 0x0f; pr_info("3c529: found %s at slot %d\n", el3_mca_adapter_names[mdev->index], slot + 1); /* claim the slot */ strncpy(mdev->name, el3_mca_adapter_names[mdev->index], sizeof(mdev->name)); mca_device_set_claim(mdev, 1); if_port = pos4 & 0x03; irq = mca_device_transform_irq(mdev, irq); ioaddr = mca_device_transform_ioport(mdev, ioaddr); if (el3_debug > 2) { pr_debug("3c529: irq %d ioaddr 0x%x ifport %d\n", irq, ioaddr, if_port); } EL3WINDOW(0); for (i = 0; i < 3; i++) phys_addr[i] = htons(read_eeprom(ioaddr, i)); dev = alloc_etherdev(sizeof (struct el3_private)); if (dev == NULL) { release_region(ioaddr, EL3_IO_EXTENT); return -ENOMEM; } netdev_boot_setup_check(dev); el3_dev_fill(dev, phys_addr, ioaddr, irq, if_port, EL3_MCA); dev_set_drvdata(device, dev); err = el3_common_init(dev); if (err) { dev_set_drvdata(device, NULL); free_netdev(dev); return -ENOMEM; } el3_devs[el3_cards++] = dev; return 0; } #endif /* CONFIG_MCA */ #ifdef CONFIG_EISA static int __init el3_eisa_probe (struct device *device) { short i; int ioaddr, irq, if_port; __be16 phys_addr[3]; struct net_device *dev = NULL; struct eisa_device *edev; int err; /* Yeepee, The driver framework is calling us ! */ edev = to_eisa_device (device); ioaddr = edev->base_addr; if (!request_region(ioaddr, EL3_IO_EXTENT, "3c579-eisa")) return -EBUSY; /* Change the register set to the configuration window 0. */ outw(SelectWindow | 0, ioaddr + 0xC80 + EL3_CMD); irq = inw(ioaddr + WN0_IRQ) >> 12; if_port = inw(ioaddr + 6)>>14; for (i = 0; i < 3; i++) phys_addr[i] = htons(read_eeprom(ioaddr, i)); /* Restore the "Product ID" to the EEPROM read register. */ read_eeprom(ioaddr, 3); dev = alloc_etherdev(sizeof (struct el3_private)); if (dev == NULL) { release_region(ioaddr, EL3_IO_EXTENT); return -ENOMEM; } netdev_boot_setup_check(dev); el3_dev_fill(dev, phys_addr, ioaddr, irq, if_port, EL3_EISA); eisa_set_drvdata (edev, dev); err = el3_common_init(dev); if (err) { eisa_set_drvdata (edev, NULL); free_netdev(dev); return err; } el3_devs[el3_cards++] = dev; return 0; } #endif /* This remove works for all device types. * * The net dev must be stored in the driver data field */ static int __devexit el3_device_remove (struct device *device) { struct net_device *dev; dev = dev_get_drvdata(device); el3_common_remove (dev); return 0; } /* Read a word from the EEPROM using the regular EEPROM access register. Assume that we are in register window zero. */ static ushort read_eeprom(int ioaddr, int index) { outw(EEPROM_READ + index, ioaddr + 10); /* Pause for at least 162 us. for the read to take place. Some chips seem to require much longer */ mdelay(2); return inw(ioaddr + 12); } /* Read a word from the EEPROM when in the ISA ID probe state. */ static ushort id_read_eeprom(int index) { int bit, word = 0; /* Issue read command, and pause for at least 162 us. for it to complete. Assume extra-fast 16Mhz bus. */ outb(EEPROM_READ + index, id_port); /* Pause for at least 162 us. for the read to take place. */ /* Some chips seem to require much longer */ mdelay(4); for (bit = 15; bit >= 0; bit--) word = (word << 1) + (inb(id_port) & 0x01); if (el3_debug > 3) pr_debug(" 3c509 EEPROM word %d %#4.4x.\n", index, word); return word; } static int el3_open(struct net_device *dev) { int ioaddr = dev->base_addr; int i; outw(TxReset, ioaddr + EL3_CMD); outw(RxReset, ioaddr + EL3_CMD); outw(SetStatusEnb | 0x00, ioaddr + EL3_CMD); i = request_irq(dev->irq, &el3_interrupt, 0, dev->name, dev); if (i) return i; EL3WINDOW(0); if (el3_debug > 3) pr_debug("%s: Opening, IRQ %d status@%x %4.4x.\n", dev->name, dev->irq, ioaddr + EL3_STATUS, inw(ioaddr + EL3_STATUS)); el3_up(dev); if (el3_debug > 3) pr_debug("%s: Opened 3c509 IRQ %d status %4.4x.\n", dev->name, dev->irq, inw(ioaddr + EL3_STATUS)); return 0; } static void el3_tx_timeout (struct net_device *dev) { int ioaddr = dev->base_addr; /* Transmitter timeout, serious problems. */ pr_warning("%s: transmit timed out, Tx_status %2.2x status %4.4x Tx FIFO room %d.\n", dev->name, inb(ioaddr + TX_STATUS), inw(ioaddr + EL3_STATUS), inw(ioaddr + TX_FREE)); dev->stats.tx_errors++; dev->trans_start = jiffies; /* Issue TX_RESET and TX_START commands. */ outw(TxReset, ioaddr + EL3_CMD); outw(TxEnable, ioaddr + EL3_CMD); netif_wake_queue(dev); } static netdev_tx_t el3_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct el3_private *lp = netdev_priv(dev); int ioaddr = dev->base_addr; unsigned long flags; netif_stop_queue (dev); dev->stats.tx_bytes += skb->len; if (el3_debug > 4) { pr_debug("%s: el3_start_xmit(length = %u) called, status %4.4x.\n", dev->name, skb->len, inw(ioaddr + EL3_STATUS)); } #if 0 #ifndef final_version { /* Error-checking code, delete someday. */ ushort status = inw(ioaddr + EL3_STATUS); if (status & 0x0001 /* IRQ line active, missed one. */ && inw(ioaddr + EL3_STATUS) & 1) { /* Make sure. */ pr_debug("%s: Missed interrupt, status then %04x now %04x" " Tx %2.2x Rx %4.4x.\n", dev->name, status, inw(ioaddr + EL3_STATUS), inb(ioaddr + TX_STATUS), inw(ioaddr + RX_STATUS)); /* Fake interrupt trigger by masking, acknowledge interrupts. */ outw(SetStatusEnb | 0x00, ioaddr + EL3_CMD); outw(AckIntr | IntLatch | TxAvailable | RxEarly | IntReq, ioaddr + EL3_CMD); outw(SetStatusEnb | 0xff, ioaddr + EL3_CMD); } } #endif #endif /* * We lock the driver against other processors. Note * we don't need to lock versus the IRQ as we suspended * that. This means that we lose the ability to take * an RX during a TX upload. That sucks a bit with SMP * on an original 3c509 (2K buffer) * * Using disable_irq stops us crapping on other * time sensitive devices. */ spin_lock_irqsave(&lp->lock, flags); /* Put out the doubleword header... */ outw(skb->len, ioaddr + TX_FIFO); outw(0x00, ioaddr + TX_FIFO); /* ... and the packet rounded to a doubleword. */ outsl(ioaddr + TX_FIFO, skb->data, (skb->len + 3) >> 2); dev->trans_start = jiffies; if (inw(ioaddr + TX_FREE) > 1536) netif_start_queue(dev); else /* Interrupt us when the FIFO has room for max-sized packet. */ outw(SetTxThreshold + 1536, ioaddr + EL3_CMD); spin_unlock_irqrestore(&lp->lock, flags); dev_kfree_skb (skb); /* Clear the Tx status stack. */ { short tx_status; int i = 4; while (--i > 0 && (tx_status = inb(ioaddr + TX_STATUS)) > 0) { if (tx_status & 0x38) dev->stats.tx_aborted_errors++; if (tx_status & 0x30) outw(TxReset, ioaddr + EL3_CMD); if (tx_status & 0x3C) outw(TxEnable, ioaddr + EL3_CMD); outb(0x00, ioaddr + TX_STATUS); /* Pop the status stack. */ } } return NETDEV_TX_OK; } /* The EL3 interrupt handler. */ static irqreturn_t el3_interrupt(int irq, void *dev_id) { struct net_device *dev = dev_id; struct el3_private *lp; int ioaddr, status; int i = max_interrupt_work; lp = netdev_priv(dev); spin_lock(&lp->lock); ioaddr = dev->base_addr; if (el3_debug > 4) { status = inw(ioaddr + EL3_STATUS); pr_debug("%s: interrupt, status %4.4x.\n", dev->name, status); } while ((status = inw(ioaddr + EL3_STATUS)) & (IntLatch | RxComplete | StatsFull)) { if (status & RxComplete) el3_rx(dev); if (status & TxAvailable) { if (el3_debug > 5) pr_debug(" TX room bit was handled.\n"); /* There's room in the FIFO for a full-sized packet. */ outw(AckIntr | TxAvailable, ioaddr + EL3_CMD); netif_wake_queue (dev); } if (status & (AdapterFailure | RxEarly | StatsFull | TxComplete)) { /* Handle all uncommon interrupts. */ if (status & StatsFull) /* Empty statistics. */ update_stats(dev); if (status & RxEarly) { /* Rx early is unused. */ el3_rx(dev); outw(AckIntr | RxEarly, ioaddr + EL3_CMD); } if (status & TxComplete) { /* Really Tx error. */ short tx_status; int i = 4; while (--i>0 && (tx_status = inb(ioaddr + TX_STATUS)) > 0) { if (tx_status & 0x38) dev->stats.tx_aborted_errors++; if (tx_status & 0x30) outw(TxReset, ioaddr + EL3_CMD); if (tx_status & 0x3C) outw(TxEnable, ioaddr + EL3_CMD); outb(0x00, ioaddr + TX_STATUS); /* Pop the status stack. */ } } if (status & AdapterFailure) { /* Adapter failure requires Rx reset and reinit. */ outw(RxReset, ioaddr + EL3_CMD); /* Set the Rx filter to the current state. */ outw(SetRxFilter | RxStation | RxBroadcast | (dev->flags & IFF_ALLMULTI ? RxMulticast : 0) | (dev->flags & IFF_PROMISC ? RxProm : 0), ioaddr + EL3_CMD); outw(RxEnable, ioaddr + EL3_CMD); /* Re-enable the receiver. */ outw(AckIntr | AdapterFailure, ioaddr + EL3_CMD); } } if (--i < 0) { pr_err("%s: Infinite loop in interrupt, status %4.4x.\n", dev->name, status); /* Clear all interrupts. */ outw(AckIntr | 0xFF, ioaddr + EL3_CMD); break; } /* Acknowledge the IRQ. */ outw(AckIntr | IntReq | IntLatch, ioaddr + EL3_CMD); /* Ack IRQ */ } if (el3_debug > 4) { pr_debug("%s: exiting interrupt, status %4.4x.\n", dev->name, inw(ioaddr + EL3_STATUS)); } spin_unlock(&lp->lock); return IRQ_HANDLED; } #ifdef CONFIG_NET_POLL_CONTROLLER /* * Polling receive - used by netconsole and other diagnostic tools * to allow network i/o with interrupts disabled. */ static void el3_poll_controller(struct net_device *dev) { disable_irq(dev->irq); el3_interrupt(dev->irq, dev); enable_irq(dev->irq); } #endif static struct net_device_stats * el3_get_stats(struct net_device *dev) { struct el3_private *lp = netdev_priv(dev); unsigned long flags; /* * This is fast enough not to bother with disable IRQ * stuff. */ spin_lock_irqsave(&lp->lock, flags); update_stats(dev); spin_unlock_irqrestore(&lp->lock, flags); return &dev->stats; } /* Update statistics. We change to register window 6, so this should be run single-threaded if the device is active. This is expected to be a rare operation, and it's simpler for the rest of the driver to assume that window 1 is always valid rather than use a special window-state variable. */ static void update_stats(struct net_device *dev) { int ioaddr = dev->base_addr; if (el3_debug > 5) pr_debug(" Updating the statistics.\n"); /* Turn off statistics updates while reading. */ outw(StatsDisable, ioaddr + EL3_CMD); /* Switch to the stats window, and read everything. */ EL3WINDOW(6); dev->stats.tx_carrier_errors += inb(ioaddr + 0); dev->stats.tx_heartbeat_errors += inb(ioaddr + 1); /* Multiple collisions. */ inb(ioaddr + 2); dev->stats.collisions += inb(ioaddr + 3); dev->stats.tx_window_errors += inb(ioaddr + 4); dev->stats.rx_fifo_errors += inb(ioaddr + 5); dev->stats.tx_packets += inb(ioaddr + 6); /* Rx packets */ inb(ioaddr + 7); /* Tx deferrals */ inb(ioaddr + 8); inw(ioaddr + 10); /* Total Rx and Tx octets. */ inw(ioaddr + 12); /* Back to window 1, and turn statistics back on. */ EL3WINDOW(1); outw(StatsEnable, ioaddr + EL3_CMD); return; } static int el3_rx(struct net_device *dev) { int ioaddr = dev->base_addr; short rx_status; if (el3_debug > 5) pr_debug(" In rx_packet(), status %4.4x, rx_status %4.4x.\n", inw(ioaddr+EL3_STATUS), inw(ioaddr+RX_STATUS)); while ((rx_status = inw(ioaddr + RX_STATUS)) > 0) { if (rx_status & 0x4000) { /* Error, update stats. */ short error = rx_status & 0x3800; outw(RxDiscard, ioaddr + EL3_CMD); dev->stats.rx_errors++; switch (error) { case 0x0000: dev->stats.rx_over_errors++; break; case 0x0800: dev->stats.rx_length_errors++; break; case 0x1000: dev->stats.rx_frame_errors++; break; case 0x1800: dev->stats.rx_length_errors++; break; case 0x2000: dev->stats.rx_frame_errors++; break; case 0x2800: dev->stats.rx_crc_errors++; break; } } else { short pkt_len = rx_status & 0x7ff; struct sk_buff *skb; skb = dev_alloc_skb(pkt_len+5); if (el3_debug > 4) pr_debug("Receiving packet size %d status %4.4x.\n", pkt_len, rx_status); if (skb != NULL) { skb_reserve(skb, 2); /* Align IP on 16 byte */ /* 'skb->data' points to the start of sk_buff data area. */ insl(ioaddr + RX_FIFO, skb_put(skb,pkt_len), (pkt_len + 3) >> 2); outw(RxDiscard, ioaddr + EL3_CMD); /* Pop top Rx packet. */ skb->protocol = eth_type_trans(skb,dev); netif_rx(skb); dev->stats.rx_bytes += pkt_len; dev->stats.rx_packets++; continue; } outw(RxDiscard, ioaddr + EL3_CMD); dev->stats.rx_dropped++; if (el3_debug) pr_debug("%s: Couldn't allocate a sk_buff of size %d.\n", dev->name, pkt_len); } inw(ioaddr + EL3_STATUS); /* Delay. */ while (inw(ioaddr + EL3_STATUS) & 0x1000) pr_debug(" Waiting for 3c509 to discard packet, status %x.\n", inw(ioaddr + EL3_STATUS) ); } return 0; } /* * Set or clear the multicast filter for this adaptor. */ static void set_multicast_list(struct net_device *dev) { unsigned long flags; struct el3_private *lp = netdev_priv(dev); int ioaddr = dev->base_addr; if (el3_debug > 1) { static int old; if (old != dev->mc_count) { old = dev->mc_count; pr_debug("%s: Setting Rx mode to %d addresses.\n", dev->name, dev->mc_count); } } spin_lock_irqsave(&lp->lock, flags); if (dev->flags&IFF_PROMISC) { outw(SetRxFilter | RxStation | RxMulticast | RxBroadcast | RxProm, ioaddr + EL3_CMD); } else if (dev->mc_count || (dev->flags&IFF_ALLMULTI)) { outw(SetRxFilter | RxStation | RxMulticast | RxBroadcast, ioaddr + EL3_CMD); } else outw(SetRxFilter | RxStation | RxBroadcast, ioaddr + EL3_CMD); spin_unlock_irqrestore(&lp->lock, flags); } static int el3_close(struct net_device *dev) { int ioaddr = dev->base_addr; struct el3_private *lp = netdev_priv(dev); if (el3_debug > 2) pr_debug("%s: Shutting down ethercard.\n", dev->name); el3_down(dev); free_irq(dev->irq, dev); /* Switching back to window 0 disables the IRQ. */ EL3WINDOW(0); if (lp->type != EL3_EISA) { /* But we explicitly zero the IRQ line select anyway. Don't do * it on EISA cards, it prevents the module from getting an * IRQ after unload+reload... */ outw(0x0f00, ioaddr + WN0_IRQ); } return 0; } static int el3_link_ok(struct net_device *dev) { int ioaddr = dev->base_addr; u16 tmp; EL3WINDOW(4); tmp = inw(ioaddr + WN4_MEDIA); EL3WINDOW(1); return tmp & (1<<11); } static int el3_netdev_get_ecmd(struct net_device *dev, struct ethtool_cmd *ecmd) { u16 tmp; int ioaddr = dev->base_addr; EL3WINDOW(0); /* obtain current transceiver via WN4_MEDIA? */ tmp = inw(ioaddr + WN0_ADDR_CONF); ecmd->transceiver = XCVR_INTERNAL; switch (tmp >> 14) { case 0: ecmd->port = PORT_TP; break; case 1: ecmd->port = PORT_AUI; ecmd->transceiver = XCVR_EXTERNAL; break; case 3: ecmd->port = PORT_BNC; default: break; } ecmd->duplex = DUPLEX_HALF; ecmd->supported = 0; tmp = inw(ioaddr + WN0_CONF_CTRL); if (tmp & (1<<13)) ecmd->supported |= SUPPORTED_AUI; if (tmp & (1<<12)) ecmd->supported |= SUPPORTED_BNC; if (tmp & (1<<9)) { ecmd->supported |= SUPPORTED_TP | SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full; /* hmm... */ EL3WINDOW(4); tmp = inw(ioaddr + WN4_NETDIAG); if (tmp & FD_ENABLE) ecmd->duplex = DUPLEX_FULL; } ecmd->speed = SPEED_10; EL3WINDOW(1); return 0; } static int el3_netdev_set_ecmd(struct net_device *dev, struct ethtool_cmd *ecmd) { u16 tmp; int ioaddr = dev->base_addr; if (ecmd->speed != SPEED_10) return -EINVAL; if ((ecmd->duplex != DUPLEX_HALF) && (ecmd->duplex != DUPLEX_FULL)) return -EINVAL; if ((ecmd->transceiver != XCVR_INTERNAL) && (ecmd->transceiver != XCVR_EXTERNAL)) return -EINVAL; /* change XCVR type */ EL3WINDOW(0); tmp = inw(ioaddr + WN0_ADDR_CONF); switch (ecmd->port) { case PORT_TP: tmp &= ~(3<<14); dev->if_port = 0; break; case PORT_AUI: tmp |= (1<<14); dev->if_port = 1; break; case PORT_BNC: tmp |= (3<<14); dev->if_port = 3; break; default: return -EINVAL; } outw(tmp, ioaddr + WN0_ADDR_CONF); if (dev->if_port == 3) { /* fire up the DC-DC convertor if BNC gets enabled */ tmp = inw(ioaddr + WN0_ADDR_CONF); if (tmp & (3 << 14)) { outw(StartCoax, ioaddr + EL3_CMD); udelay(800); } else return -EIO; } EL3WINDOW(4); tmp = inw(ioaddr + WN4_NETDIAG); if (ecmd->duplex == DUPLEX_FULL) tmp |= FD_ENABLE; else tmp &= ~FD_ENABLE; outw(tmp, ioaddr + WN4_NETDIAG); EL3WINDOW(1); return 0; } static void el3_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { strcpy(info->driver, DRV_NAME); strcpy(info->version, DRV_VERSION); } static int el3_get_settings(struct net_device *dev, struct ethtool_cmd *ecmd) { struct el3_private *lp = netdev_priv(dev); int ret; spin_lock_irq(&lp->lock); ret = el3_netdev_get_ecmd(dev, ecmd); spin_unlock_irq(&lp->lock); return ret; } static int el3_set_settings(struct net_device *dev, struct ethtool_cmd *ecmd) { struct el3_private *lp = netdev_priv(dev); int ret; spin_lock_irq(&lp->lock); ret = el3_netdev_set_ecmd(dev, ecmd); spin_unlock_irq(&lp->lock); return ret; } static u32 el3_get_link(struct net_device *dev) { struct el3_private *lp = netdev_priv(dev); u32 ret; spin_lock_irq(&lp->lock); ret = el3_link_ok(dev); spin_unlock_irq(&lp->lock); return ret; } static u32 el3_get_msglevel(struct net_device *dev) { return el3_debug; } static void el3_set_msglevel(struct net_device *dev, u32 v) { el3_debug = v; } static const struct ethtool_ops ethtool_ops = { .get_drvinfo = el3_get_drvinfo, .get_settings = el3_get_settings, .set_settings = el3_set_settings, .get_link = el3_get_link, .get_msglevel = el3_get_msglevel, .set_msglevel = el3_set_msglevel, }; static void el3_down(struct net_device *dev) { int ioaddr = dev->base_addr; netif_stop_queue(dev); /* Turn off statistics ASAP. We update lp->stats below. */ outw(StatsDisable, ioaddr + EL3_CMD); /* Disable the receiver and transmitter. */ outw(RxDisable, ioaddr + EL3_CMD); outw(TxDisable, ioaddr + EL3_CMD); if (dev->if_port == 3) /* Turn off thinnet power. Green! */ outw(StopCoax, ioaddr + EL3_CMD); else if (dev->if_port == 0) { /* Disable link beat and jabber, if_port may change here next open(). */ EL3WINDOW(4); outw(inw(ioaddr + WN4_MEDIA) & ~MEDIA_TP, ioaddr + WN4_MEDIA); } outw(SetIntrEnb | 0x0000, ioaddr + EL3_CMD); update_stats(dev); } static void el3_up(struct net_device *dev) { int i, sw_info, net_diag; int ioaddr = dev->base_addr; /* Activating the board required and does no harm otherwise */ outw(0x0001, ioaddr + 4); /* Set the IRQ line. */ outw((dev->irq << 12) | 0x0f00, ioaddr + WN0_IRQ); /* Set the station address in window 2 each time opened. */ EL3WINDOW(2); for (i = 0; i < 6; i++) outb(dev->dev_addr[i], ioaddr + i); if ((dev->if_port & 0x03) == 3) /* BNC interface */ /* Start the thinnet transceiver. We should really wait 50ms...*/ outw(StartCoax, ioaddr + EL3_CMD); else if ((dev->if_port & 0x03) == 0) { /* 10baseT interface */ /* Combine secondary sw_info word (the adapter level) and primary sw_info word (duplex setting plus other useless bits) */ EL3WINDOW(0); sw_info = (read_eeprom(ioaddr, 0x14) & 0x400f) | (read_eeprom(ioaddr, 0x0d) & 0xBff0); EL3WINDOW(4); net_diag = inw(ioaddr + WN4_NETDIAG); net_diag = (net_diag | FD_ENABLE); /* temporarily assume full-duplex will be set */ pr_info("%s: ", dev->name); switch (dev->if_port & 0x0c) { case 12: /* force full-duplex mode if 3c5x9b */ if (sw_info & 0x000f) { pr_cont("Forcing 3c5x9b full-duplex mode"); break; } case 8: /* set full-duplex mode based on eeprom config setting */ if ((sw_info & 0x000f) && (sw_info & 0x8000)) { pr_cont("Setting 3c5x9b full-duplex mode (from EEPROM configuration bit)"); break; } default: /* xcvr=(0 || 4) OR user has an old 3c5x9 non "B" model */ pr_cont("Setting 3c5x9/3c5x9B half-duplex mode"); net_diag = (net_diag & ~FD_ENABLE); /* disable full duplex */ } outw(net_diag, ioaddr + WN4_NETDIAG); pr_cont(" if_port: %d, sw_info: %4.4x\n", dev->if_port, sw_info); if (el3_debug > 3) pr_debug("%s: 3c5x9 net diag word is now: %4.4x.\n", dev->name, net_diag); /* Enable link beat and jabber check. */ outw(inw(ioaddr + WN4_MEDIA) | MEDIA_TP, ioaddr + WN4_MEDIA); } /* Switch to the stats window, and clear all stats by reading. */ outw(StatsDisable, ioaddr + EL3_CMD); EL3WINDOW(6); for (i = 0; i < 9; i++) inb(ioaddr + i); inw(ioaddr + 10); inw(ioaddr + 12); /* Switch to register set 1 for normal use. */ EL3WINDOW(1); /* Accept b-case and phys addr only. */ outw(SetRxFilter | RxStation | RxBroadcast, ioaddr + EL3_CMD); outw(StatsEnable, ioaddr + EL3_CMD); /* Turn on statistics. */ outw(RxEnable, ioaddr + EL3_CMD); /* Enable the receiver. */ outw(TxEnable, ioaddr + EL3_CMD); /* Enable transmitter. */ /* Allow status bits to be seen. */ outw(SetStatusEnb | 0xff, ioaddr + EL3_CMD); /* Ack all pending events, and set active indicator mask. */ outw(AckIntr | IntLatch | TxAvailable | RxEarly | IntReq, ioaddr + EL3_CMD); outw(SetIntrEnb | IntLatch|TxAvailable|TxComplete|RxComplete|StatsFull, ioaddr + EL3_CMD); netif_start_queue(dev); } /* Power Management support functions */ #ifdef CONFIG_PM static int el3_suspend(struct device *pdev, pm_message_t state) { unsigned long flags; struct net_device *dev; struct el3_private *lp; int ioaddr; dev = dev_get_drvdata(pdev); lp = netdev_priv(dev); ioaddr = dev->base_addr; spin_lock_irqsave(&lp->lock, flags); if (netif_running(dev)) netif_device_detach(dev); el3_down(dev); outw(PowerDown, ioaddr + EL3_CMD); spin_unlock_irqrestore(&lp->lock, flags); return 0; } static int el3_resume(struct device *pdev) { unsigned long flags; struct net_device *dev; struct el3_private *lp; int ioaddr; dev = dev_get_drvdata(pdev); lp = netdev_priv(dev); ioaddr = dev->base_addr; spin_lock_irqsave(&lp->lock, flags); outw(PowerUp, ioaddr + EL3_CMD); EL3WINDOW(0); el3_up(dev); if (netif_running(dev)) netif_device_attach(dev); spin_unlock_irqrestore(&lp->lock, flags); return 0; } #endif /* CONFIG_PM */ module_param(debug,int, 0); module_param_array(irq, int, NULL, 0); module_param(max_interrupt_work, int, 0); MODULE_PARM_DESC(debug, "debug level (0-6)"); MODULE_PARM_DESC(irq, "IRQ number(s) (assigned)"); MODULE_PARM_DESC(max_interrupt_work, "maximum events handled per interrupt"); #ifdef CONFIG_PNP module_param(nopnp, int, 0); MODULE_PARM_DESC(nopnp, "disable ISA PnP support (0-1)"); #endif /* CONFIG_PNP */ MODULE_DESCRIPTION("3Com Etherlink III (3c509, 3c509B, 3c529, 3c579) ethernet driver"); MODULE_LICENSE("GPL"); static int __init el3_init_module(void) { int ret = 0; if (debug >= 0) el3_debug = debug; #ifdef CONFIG_PNP if (!nopnp) { ret = pnp_register_driver(&el3_pnp_driver); if (!ret) pnp_registered = 1; } #endif /* Select an open I/O location at 0x1*0 to do ISA contention select. */ /* Start with 0x110 to avoid some sound cards.*/ for (id_port = 0x110 ; id_port < 0x200; id_port += 0x10) { if (!request_region(id_port, 1, "3c509-control")) continue; outb(0x00, id_port); outb(0xff, id_port); if (inb(id_port) & 0x01) break; else release_region(id_port, 1); } if (id_port >= 0x200) { id_port = 0; pr_err("No I/O port available for 3c509 activation.\n"); } else { ret = isa_register_driver(&el3_isa_driver, EL3_MAX_CARDS); if (!ret) isa_registered = 1; } #ifdef CONFIG_EISA ret = eisa_driver_register(&el3_eisa_driver); if (!ret) eisa_registered = 1; #endif #ifdef CONFIG_MCA ret = mca_register_driver(&el3_mca_driver); if (!ret) mca_registered = 1; #endif #ifdef CONFIG_PNP if (pnp_registered) ret = 0; #endif if (isa_registered) ret = 0; #ifdef CONFIG_EISA if (eisa_registered) ret = 0; #endif #ifdef CONFIG_MCA if (mca_registered) ret = 0; #endif return ret; } static void __exit el3_cleanup_module(void) { #ifdef CONFIG_PNP if (pnp_registered) pnp_unregister_driver(&el3_pnp_driver); #endif if (isa_registered) isa_unregister_driver(&el3_isa_driver); if (id_port) release_region(id_port, 1); #ifdef CONFIG_EISA if (eisa_registered) eisa_driver_unregister(&el3_eisa_driver); #endif #ifdef CONFIG_MCA if (mca_registered) mca_unregister_driver(&el3_mca_driver); #endif } module_init (el3_init_module); module_exit (el3_cleanup_module);
{ "language": "C" }
#include "core_reloc_types.h" void f(struct core_reloc_nesting___err_missing_container x) {}
{ "language": "C" }
/* SPDX-License-Identifier: BSD-3-Clause * Copyright(C) 2020 Marvell International Ltd. */ #include <rte_trace_point.h> RTE_TRACE_POINT( app_dpdk_test_tp, RTE_TRACE_POINT_ARGS(const char *str), rte_trace_point_emit_string(str); ) RTE_TRACE_POINT_FP( app_dpdk_test_fp, RTE_TRACE_POINT_ARGS(void), )
{ "language": "C" }
/* * QEMU VMWARE paravirtual RDMA ring utilities * * Copyright (C) 2018 Oracle * Copyright (C) 2018 Red Hat Inc * * Authors: * Yuval Shaia <yuval.shaia@oracle.com> * Marcel Apfelbaum <marcel@redhat.com> * * This work is licensed under the terms of the GNU GPL, version 2 or later. * See the COPYING file in the top-level directory. * */ #ifndef PVRDMA_DEV_RING_H #define PVRDMA_DEV_RING_H #define MAX_RING_NAME_SZ 32 typedef struct PvrdmaRing { char name[MAX_RING_NAME_SZ]; PCIDevice *dev; uint32_t max_elems; size_t elem_sz; struct pvrdma_ring *ring_state; /* used only for unmap */ int npages; void **pages; } PvrdmaRing; int pvrdma_ring_init(PvrdmaRing *ring, const char *name, PCIDevice *dev, struct pvrdma_ring *ring_state, uint32_t max_elems, size_t elem_sz, dma_addr_t *tbl, uint32_t npages); void *pvrdma_ring_next_elem_read(PvrdmaRing *ring); void pvrdma_ring_read_inc(PvrdmaRing *ring); void *pvrdma_ring_next_elem_write(PvrdmaRing *ring); void pvrdma_ring_write_inc(PvrdmaRing *ring); void pvrdma_ring_free(PvrdmaRing *ring); #endif
{ "language": "C" }
/* * Copyright 2012 Red Hat 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 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) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * */ #include "priv.h" #if defined(CONFIG_ACPI) && defined(CONFIG_X86) int nouveau_acpi_get_bios_chunk(uint8_t *bios, int offset, int len); bool nouveau_acpi_rom_supported(struct device *); #else static inline bool nouveau_acpi_rom_supported(struct device *dev) { return false; } static inline int nouveau_acpi_get_bios_chunk(uint8_t *bios, int offset, int len) { return -EINVAL; } #endif /* This version of the shadow function disobeys the ACPI spec and tries * to fetch in units of more than 4KiB at a time. This is a LOT faster * on some systems, such as Lenovo W530. */ static u32 acpi_read_fast(void *data, u32 offset, u32 length, struct nvkm_bios *bios) { u32 limit = (offset + length + 0xfff) & ~0xfff; u32 start = offset & ~0x00000fff; u32 fetch = limit - start; if (nvbios_extend(bios, limit) >= 0) { int ret = nouveau_acpi_get_bios_chunk(bios->data, start, fetch); if (ret == fetch) return fetch; } return 0; } /* Other systems, such as the one in fdo#55948, will report a success * but only return 4KiB of data. The common bios fetching logic will * detect an invalid image, and fall back to this version of the read * function. */ static u32 acpi_read_slow(void *data, u32 offset, u32 length, struct nvkm_bios *bios) { u32 limit = (offset + length + 0xfff) & ~0xfff; u32 start = offset & ~0xfff; u32 fetch = 0; if (nvbios_extend(bios, limit) >= 0) { while (start + fetch < limit) { int ret = nouveau_acpi_get_bios_chunk(bios->data, start + fetch, 0x1000); if (ret != 0x1000) break; fetch += 0x1000; } } return fetch; } static void * acpi_init(struct nvkm_bios *bios, const char *name) { if (!nouveau_acpi_rom_supported(bios->subdev.device->dev)) return ERR_PTR(-ENODEV); return NULL; } const struct nvbios_source nvbios_acpi_fast = { .name = "ACPI", .init = acpi_init, .read = acpi_read_fast, .rw = false, .require_checksum = true, }; const struct nvbios_source nvbios_acpi_slow = { .name = "ACPI", .init = acpi_init, .read = acpi_read_slow, .rw = false, };
{ "language": "C" }
/* SPDX-License-Identifier: GPL-2.0-only */ /* * tegra186_dspk.h - Definitions for Tegra186 DSPK driver * * Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved. * */ #ifndef __TEGRA186_DSPK_H__ #define __TEGRA186_DSPK_H__ /* Register offsets from DSPK BASE */ #define TEGRA186_DSPK_RX_STATUS 0x0c #define TEGRA186_DSPK_RX_INT_STATUS 0x10 #define TEGRA186_DSPK_RX_INT_MASK 0x14 #define TEGRA186_DSPK_RX_INT_SET 0x18 #define TEGRA186_DSPK_RX_INT_CLEAR 0x1c #define TEGRA186_DSPK_RX_CIF_CTRL 0x20 #define TEGRA186_DSPK_ENABLE 0x40 #define TEGRA186_DSPK_SOFT_RESET 0x44 #define TEGRA186_DSPK_CG 0x48 #define TEGRA186_DSPK_STATUS 0x4c #define TEGRA186_DSPK_INT_STATUS 0x50 #define TEGRA186_DSPK_CORE_CTRL 0x60 #define TEGRA186_DSPK_CODEC_CTRL 0x64 /* DSPK CORE CONTROL fields */ #define CH_SEL_SHIFT 8 #define TEGRA186_DSPK_CHANNEL_SELECT_MASK (0x3 << CH_SEL_SHIFT) #define DSPK_OSR_SHIFT 4 #define TEGRA186_DSPK_OSR_MASK (0x3 << DSPK_OSR_SHIFT) #define LRSEL_POL_SHIFT 0 #define TEGRA186_DSPK_CTRL_LRSEL_POLARITY_MASK (0x1 << LRSEL_POL_SHIFT) #define TEGRA186_DSPK_RX_FIFO_DEPTH 64 #define DSPK_OSR_FACTOR 32 /* DSPK interface clock ratio */ #define DSPK_CLK_RATIO 4 enum tegra_dspk_osr { DSPK_OSR_32, DSPK_OSR_64, DSPK_OSR_128, DSPK_OSR_256, }; enum tegra_dspk_ch_sel { DSPK_CH_SELECT_LEFT, DSPK_CH_SELECT_RIGHT, DSPK_CH_SELECT_STEREO, }; enum tegra_dspk_lrsel { DSPK_LRSEL_LEFT, DSPK_LRSEL_RIGHT, }; struct tegra186_dspk { unsigned int rx_fifo_th; unsigned int osr_val; unsigned int lrsel; unsigned int ch_sel; unsigned int mono_to_stereo; unsigned int stereo_to_mono; struct clk *clk_dspk; struct regmap *regmap; }; #endif
{ "language": "C" }
/* TMP_ALLOC routines for debugging. Copyright 2000, 2001, 2004 Free Software Foundation, Inc. This file is part of the GNU MP Library. The GNU MP Library is free software; you can redistribute it and/or modify it under the terms of either: * 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. or * 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. or both in parallel, as here. The GNU MP 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 General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with the GNU MP Library. If not, see https://www.gnu.org/licenses/. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "gmp-impl.h" /* This method aims to help a malloc debugger find problems. A linked list of allocated block is kept for TMP_FREE to release. This is reentrant and thread safe. Each TMP_ALLOC is a separate malloced block, so redzones or sentinels applied by a malloc debugger either above or below can guard against accesses outside the allocated area. A marker is a "struct tmp_debug_t *" so that TMP_DECL can initialize it to NULL and we can detect TMP_ALLOC without TMP_MARK. It will work to realloc an MPZ_TMP_INIT variable, but when TMP_FREE comes to release the memory it will have the old size, thereby triggering an error from tests/memory.c. Possibilities: It'd be possible to keep a global list of active "struct tmp_debug_t" records, so at the end of a program any TMP leaks could be printed. But if only a couple of routines are under test at any one time then the likely culprit should be easy enough to spot. */ void __gmp_tmp_debug_mark (const char *file, int line, struct tmp_debug_t **markp, struct tmp_debug_t *mark, const char *decl_name, const char *mark_name) { if (strcmp (mark_name, decl_name) != 0) { __gmp_assert_header (file, line); fprintf (stderr, "GNU MP: TMP_MARK(%s) but TMP_DECL(%s) is in scope\n", mark_name, decl_name); abort (); } if (*markp != NULL) { __gmp_assert_header (file, line); fprintf (stderr, "GNU MP: Repeat of TMP_MARK(%s)\n", mark_name); if (mark->file != NULL && mark->file[0] != '\0' && mark->line != -1) { __gmp_assert_header (mark->file, mark->line); fprintf (stderr, "previous was here\n"); } abort (); } *markp = mark; mark->file = file; mark->line = line; mark->list = NULL; } void * __gmp_tmp_debug_alloc (const char *file, int line, int dummy, struct tmp_debug_t **markp, const char *decl_name, size_t size) { struct tmp_debug_t *mark = *markp; struct tmp_debug_entry_t *p; ASSERT_ALWAYS (size >= 1); if (mark == NULL) { __gmp_assert_header (file, line); fprintf (stderr, "GNU MP: TMP_ALLOC without TMP_MARK(%s)\n", decl_name); abort (); } p = __GMP_ALLOCATE_FUNC_TYPE (1, struct tmp_debug_entry_t); p->size = size; p->block = (*__gmp_allocate_func) (size); p->next = mark->list; mark->list = p; return p->block; } void __gmp_tmp_debug_free (const char *file, int line, int dummy, struct tmp_debug_t **markp, const char *decl_name, const char *free_name) { struct tmp_debug_t *mark = *markp; struct tmp_debug_entry_t *p, *next; if (mark == NULL) { __gmp_assert_header (file, line); fprintf (stderr, "GNU MP: TMP_FREE(%s) without TMP_MARK(%s)\n", free_name, decl_name); abort (); } if (strcmp (free_name, decl_name) != 0) { __gmp_assert_header (file, line); fprintf (stderr, "GNU MP: TMP_FREE(%s) when TMP_DECL(%s) is in scope\n", free_name, decl_name); abort (); } p = mark->list; while (p != NULL) { next = p->next; (*__gmp_free_func) (p->block, p->size); __GMP_FREE_FUNC_TYPE (p, 1, struct tmp_debug_entry_t); p = next; } *markp = NULL; }
{ "language": "C" }
/* * Stuff used by all variants of the driver * * Copyright (c) 2001 by Stefan Eilers, * Hansjoerg Lipp <hjlipp@web.de>, * Tilman Schmidt <tilman@imap.cc>. * * ===================================================================== * 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 "gigaset.h" #include <linux/module.h> #include <linux/moduleparam.h> /* Version Information */ #define DRIVER_AUTHOR "Hansjoerg Lipp <hjlipp@web.de>, Tilman Schmidt <tilman@imap.cc>, Stefan Eilers" #define DRIVER_DESC "Driver for Gigaset 307x" #ifdef CONFIG_GIGASET_DEBUG #define DRIVER_DESC_DEBUG " (debug build)" #else #define DRIVER_DESC_DEBUG "" #endif /* Module parameters */ int gigaset_debuglevel; EXPORT_SYMBOL_GPL(gigaset_debuglevel); module_param_named(debug, gigaset_debuglevel, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(debug, "debug level"); /* driver state flags */ #define VALID_MINOR 0x01 #define VALID_ID 0x02 /** * gigaset_dbg_buffer() - dump data in ASCII and hex for debugging * @level: debugging level. * @msg: message prefix. * @len: number of bytes to dump. * @buf: data to dump. * * If the current debugging level includes one of the bits set in @level, * @len bytes starting at @buf are logged to dmesg at KERN_DEBUG prio, * prefixed by the text @msg. */ void gigaset_dbg_buffer(enum debuglevel level, const unsigned char *msg, size_t len, const unsigned char *buf) { unsigned char outbuf[80]; unsigned char c; size_t space = sizeof outbuf - 1; unsigned char *out = outbuf; size_t numin = len; while (numin--) { c = *buf++; if (c == '~' || c == '^' || c == '\\') { if (!space--) break; *out++ = '\\'; } if (c & 0x80) { if (!space--) break; *out++ = '~'; c ^= 0x80; } if (c < 0x20 || c == 0x7f) { if (!space--) break; *out++ = '^'; c ^= 0x40; } if (!space--) break; *out++ = c; } *out = 0; gig_dbg(level, "%s (%u bytes): %s", msg, (unsigned) len, outbuf); } EXPORT_SYMBOL_GPL(gigaset_dbg_buffer); static int setflags(struct cardstate *cs, unsigned flags, unsigned delay) { int r; r = cs->ops->set_modem_ctrl(cs, cs->control_state, flags); cs->control_state = flags; if (r < 0) return r; if (delay) { set_current_state(TASK_INTERRUPTIBLE); schedule_timeout(delay * HZ / 1000); } return 0; } int gigaset_enterconfigmode(struct cardstate *cs) { int i, r; cs->control_state = TIOCM_RTS; r = setflags(cs, TIOCM_DTR, 200); if (r < 0) goto error; r = setflags(cs, 0, 200); if (r < 0) goto error; for (i = 0; i < 5; ++i) { r = setflags(cs, TIOCM_RTS, 100); if (r < 0) goto error; r = setflags(cs, 0, 100); if (r < 0) goto error; } r = setflags(cs, TIOCM_RTS | TIOCM_DTR, 800); if (r < 0) goto error; return 0; error: dev_err(cs->dev, "error %d on setuartbits\n", -r); cs->control_state = TIOCM_RTS | TIOCM_DTR; cs->ops->set_modem_ctrl(cs, 0, TIOCM_RTS | TIOCM_DTR); return -1; } static int test_timeout(struct at_state_t *at_state) { if (!at_state->timer_expires) return 0; if (--at_state->timer_expires) { gig_dbg(DEBUG_MCMD, "decreased timer of %p to %lu", at_state, at_state->timer_expires); return 0; } gigaset_add_event(at_state->cs, at_state, EV_TIMEOUT, NULL, at_state->timer_index, NULL); return 1; } static void timer_tick(struct timer_list *t) { struct cardstate *cs = from_timer(cs, t, timer); unsigned long flags; unsigned channel; struct at_state_t *at_state; int timeout = 0; spin_lock_irqsave(&cs->lock, flags); for (channel = 0; channel < cs->channels; ++channel) if (test_timeout(&cs->bcs[channel].at_state)) timeout = 1; if (test_timeout(&cs->at_state)) timeout = 1; list_for_each_entry(at_state, &cs->temp_at_states, list) if (test_timeout(at_state)) timeout = 1; if (cs->running) { mod_timer(&cs->timer, jiffies + msecs_to_jiffies(GIG_TICK)); if (timeout) { gig_dbg(DEBUG_EVENT, "scheduling timeout"); tasklet_schedule(&cs->event_tasklet); } } spin_unlock_irqrestore(&cs->lock, flags); } int gigaset_get_channel(struct bc_state *bcs) { unsigned long flags; spin_lock_irqsave(&bcs->cs->lock, flags); if (bcs->use_count || !try_module_get(bcs->cs->driver->owner)) { gig_dbg(DEBUG_CHANNEL, "could not allocate channel %d", bcs->channel); spin_unlock_irqrestore(&bcs->cs->lock, flags); return -EBUSY; } ++bcs->use_count; bcs->busy = 1; gig_dbg(DEBUG_CHANNEL, "allocated channel %d", bcs->channel); spin_unlock_irqrestore(&bcs->cs->lock, flags); return 0; } struct bc_state *gigaset_get_free_channel(struct cardstate *cs) { unsigned long flags; int i; spin_lock_irqsave(&cs->lock, flags); if (!try_module_get(cs->driver->owner)) { gig_dbg(DEBUG_CHANNEL, "could not get module for allocating channel"); spin_unlock_irqrestore(&cs->lock, flags); return NULL; } for (i = 0; i < cs->channels; ++i) if (!cs->bcs[i].use_count) { ++cs->bcs[i].use_count; cs->bcs[i].busy = 1; spin_unlock_irqrestore(&cs->lock, flags); gig_dbg(DEBUG_CHANNEL, "allocated channel %d", i); return cs->bcs + i; } module_put(cs->driver->owner); spin_unlock_irqrestore(&cs->lock, flags); gig_dbg(DEBUG_CHANNEL, "no free channel"); return NULL; } void gigaset_free_channel(struct bc_state *bcs) { unsigned long flags; spin_lock_irqsave(&bcs->cs->lock, flags); if (!bcs->busy) { gig_dbg(DEBUG_CHANNEL, "could not free channel %d", bcs->channel); spin_unlock_irqrestore(&bcs->cs->lock, flags); return; } --bcs->use_count; bcs->busy = 0; module_put(bcs->cs->driver->owner); gig_dbg(DEBUG_CHANNEL, "freed channel %d", bcs->channel); spin_unlock_irqrestore(&bcs->cs->lock, flags); } int gigaset_get_channels(struct cardstate *cs) { unsigned long flags; int i; spin_lock_irqsave(&cs->lock, flags); for (i = 0; i < cs->channels; ++i) if (cs->bcs[i].use_count) { spin_unlock_irqrestore(&cs->lock, flags); gig_dbg(DEBUG_CHANNEL, "could not allocate all channels"); return -EBUSY; } for (i = 0; i < cs->channels; ++i) ++cs->bcs[i].use_count; spin_unlock_irqrestore(&cs->lock, flags); gig_dbg(DEBUG_CHANNEL, "allocated all channels"); return 0; } void gigaset_free_channels(struct cardstate *cs) { unsigned long flags; int i; gig_dbg(DEBUG_CHANNEL, "unblocking all channels"); spin_lock_irqsave(&cs->lock, flags); for (i = 0; i < cs->channels; ++i) --cs->bcs[i].use_count; spin_unlock_irqrestore(&cs->lock, flags); } void gigaset_block_channels(struct cardstate *cs) { unsigned long flags; int i; gig_dbg(DEBUG_CHANNEL, "blocking all channels"); spin_lock_irqsave(&cs->lock, flags); for (i = 0; i < cs->channels; ++i) ++cs->bcs[i].use_count; spin_unlock_irqrestore(&cs->lock, flags); } static void clear_events(struct cardstate *cs) { struct event_t *ev; unsigned head, tail; unsigned long flags; spin_lock_irqsave(&cs->ev_lock, flags); head = cs->ev_head; tail = cs->ev_tail; while (tail != head) { ev = cs->events + head; kfree(ev->ptr); head = (head + 1) % MAX_EVENTS; } cs->ev_head = tail; spin_unlock_irqrestore(&cs->ev_lock, flags); } /** * gigaset_add_event() - add event to device event queue * @cs: device descriptor structure. * @at_state: connection state structure. * @type: event type. * @ptr: pointer parameter for event. * @parameter: integer parameter for event. * @arg: pointer parameter for event. * * Allocate an event queue entry from the device's event queue, and set it up * with the parameters given. * * Return value: added event */ struct event_t *gigaset_add_event(struct cardstate *cs, struct at_state_t *at_state, int type, void *ptr, int parameter, void *arg) { unsigned long flags; unsigned next, tail; struct event_t *event = NULL; gig_dbg(DEBUG_EVENT, "queueing event %d", type); spin_lock_irqsave(&cs->ev_lock, flags); tail = cs->ev_tail; next = (tail + 1) % MAX_EVENTS; if (unlikely(next == cs->ev_head)) dev_err(cs->dev, "event queue full\n"); else { event = cs->events + tail; event->type = type; event->at_state = at_state; event->cid = -1; event->ptr = ptr; event->arg = arg; event->parameter = parameter; cs->ev_tail = next; } spin_unlock_irqrestore(&cs->ev_lock, flags); return event; } EXPORT_SYMBOL_GPL(gigaset_add_event); static void clear_at_state(struct at_state_t *at_state) { int i; for (i = 0; i < STR_NUM; ++i) { kfree(at_state->str_var[i]); at_state->str_var[i] = NULL; } } static void dealloc_temp_at_states(struct cardstate *cs) { struct at_state_t *cur, *next; list_for_each_entry_safe(cur, next, &cs->temp_at_states, list) { list_del(&cur->list); clear_at_state(cur); kfree(cur); } } static void gigaset_freebcs(struct bc_state *bcs) { int i; gig_dbg(DEBUG_INIT, "freeing bcs[%d]->hw", bcs->channel); bcs->cs->ops->freebcshw(bcs); gig_dbg(DEBUG_INIT, "clearing bcs[%d]->at_state", bcs->channel); clear_at_state(&bcs->at_state); gig_dbg(DEBUG_INIT, "freeing bcs[%d]->skb", bcs->channel); dev_kfree_skb(bcs->rx_skb); bcs->rx_skb = NULL; for (i = 0; i < AT_NUM; ++i) { kfree(bcs->commands[i]); bcs->commands[i] = NULL; } } static struct cardstate *alloc_cs(struct gigaset_driver *drv) { unsigned long flags; unsigned i; struct cardstate *cs; struct cardstate *ret = NULL; spin_lock_irqsave(&drv->lock, flags); if (drv->blocked) goto exit; for (i = 0; i < drv->minors; ++i) { cs = drv->cs + i; if (!(cs->flags & VALID_MINOR)) { cs->flags = VALID_MINOR; ret = cs; break; } } exit: spin_unlock_irqrestore(&drv->lock, flags); return ret; } static void free_cs(struct cardstate *cs) { cs->flags = 0; } static void make_valid(struct cardstate *cs, unsigned mask) { unsigned long flags; struct gigaset_driver *drv = cs->driver; spin_lock_irqsave(&drv->lock, flags); cs->flags |= mask; spin_unlock_irqrestore(&drv->lock, flags); } static void make_invalid(struct cardstate *cs, unsigned mask) { unsigned long flags; struct gigaset_driver *drv = cs->driver; spin_lock_irqsave(&drv->lock, flags); cs->flags &= ~mask; spin_unlock_irqrestore(&drv->lock, flags); } /** * gigaset_freecs() - free all associated ressources of a device * @cs: device descriptor structure. * * Stops all tasklets and timers, unregisters the device from all * subsystems it was registered to, deallocates the device structure * @cs and all structures referenced from it. * Operations on the device should be stopped before calling this. */ void gigaset_freecs(struct cardstate *cs) { int i; unsigned long flags; if (!cs) return; mutex_lock(&cs->mutex); spin_lock_irqsave(&cs->lock, flags); cs->running = 0; spin_unlock_irqrestore(&cs->lock, flags); /* event handler and timer are not rescheduled below */ tasklet_kill(&cs->event_tasklet); del_timer_sync(&cs->timer); switch (cs->cs_init) { default: /* clear B channel structures */ for (i = 0; i < cs->channels; ++i) { gig_dbg(DEBUG_INIT, "clearing bcs[%d]", i); gigaset_freebcs(cs->bcs + i); } /* clear device sysfs */ gigaset_free_dev_sysfs(cs); gigaset_if_free(cs); gig_dbg(DEBUG_INIT, "clearing hw"); cs->ops->freecshw(cs); /* fall through */ case 2: /* error in initcshw */ /* Deregister from LL */ make_invalid(cs, VALID_ID); gigaset_isdn_unregdev(cs); /* fall through */ case 1: /* error when registering to LL */ gig_dbg(DEBUG_INIT, "clearing at_state"); clear_at_state(&cs->at_state); dealloc_temp_at_states(cs); clear_events(cs); tty_port_destroy(&cs->port); /* fall through */ case 0: /* error in basic setup */ gig_dbg(DEBUG_INIT, "freeing inbuf"); kfree(cs->inbuf); kfree(cs->bcs); } mutex_unlock(&cs->mutex); free_cs(cs); } EXPORT_SYMBOL_GPL(gigaset_freecs); void gigaset_at_init(struct at_state_t *at_state, struct bc_state *bcs, struct cardstate *cs, int cid) { int i; INIT_LIST_HEAD(&at_state->list); at_state->waiting = 0; at_state->getstring = 0; at_state->pending_commands = 0; at_state->timer_expires = 0; at_state->timer_active = 0; at_state->timer_index = 0; at_state->seq_index = 0; at_state->ConState = 0; for (i = 0; i < STR_NUM; ++i) at_state->str_var[i] = NULL; at_state->int_var[VAR_ZDLE] = 0; at_state->int_var[VAR_ZCTP] = -1; at_state->int_var[VAR_ZSAU] = ZSAU_NULL; at_state->cs = cs; at_state->bcs = bcs; at_state->cid = cid; if (!cid) at_state->replystruct = cs->tabnocid; else at_state->replystruct = cs->tabcid; } static void gigaset_inbuf_init(struct inbuf_t *inbuf, struct cardstate *cs) /* inbuf->read must be allocated before! */ { inbuf->head = 0; inbuf->tail = 0; inbuf->cs = cs; inbuf->inputstate = INS_command; } /** * gigaset_fill_inbuf() - append received data to input buffer * @inbuf: buffer structure. * @src: received data. * @numbytes: number of bytes received. * * Return value: !=0 if some data was appended */ int gigaset_fill_inbuf(struct inbuf_t *inbuf, const unsigned char *src, unsigned numbytes) { unsigned n, head, tail, bytesleft; gig_dbg(DEBUG_INTR, "received %u bytes", numbytes); if (!numbytes) return 0; bytesleft = numbytes; tail = inbuf->tail; head = inbuf->head; gig_dbg(DEBUG_INTR, "buffer state: %u -> %u", head, tail); while (bytesleft) { if (head > tail) n = head - 1 - tail; else if (head == 0) n = (RBUFSIZE - 1) - tail; else n = RBUFSIZE - tail; if (!n) { dev_err(inbuf->cs->dev, "buffer overflow (%u bytes lost)\n", bytesleft); break; } if (n > bytesleft) n = bytesleft; memcpy(inbuf->data + tail, src, n); bytesleft -= n; tail = (tail + n) % RBUFSIZE; src += n; } gig_dbg(DEBUG_INTR, "setting tail to %u", tail); inbuf->tail = tail; return numbytes != bytesleft; } EXPORT_SYMBOL_GPL(gigaset_fill_inbuf); /* Initialize the b-channel structure */ static int gigaset_initbcs(struct bc_state *bcs, struct cardstate *cs, int channel) { int i; bcs->tx_skb = NULL; skb_queue_head_init(&bcs->squeue); bcs->corrupted = 0; bcs->trans_down = 0; bcs->trans_up = 0; gig_dbg(DEBUG_INIT, "setting up bcs[%d]->at_state", channel); gigaset_at_init(&bcs->at_state, bcs, cs, -1); #ifdef CONFIG_GIGASET_DEBUG bcs->emptycount = 0; #endif bcs->rx_bufsize = 0; bcs->rx_skb = NULL; bcs->rx_fcs = PPP_INITFCS; bcs->inputstate = 0; bcs->channel = channel; bcs->cs = cs; bcs->chstate = 0; bcs->use_count = 1; bcs->busy = 0; bcs->ignore = cs->ignoreframes; for (i = 0; i < AT_NUM; ++i) bcs->commands[i] = NULL; spin_lock_init(&bcs->aplock); bcs->ap = NULL; bcs->apconnstate = 0; gig_dbg(DEBUG_INIT, " setting up bcs[%d]->hw", channel); return cs->ops->initbcshw(bcs); } /** * gigaset_initcs() - initialize device structure * @drv: hardware driver the device belongs to * @channels: number of B channels supported by device * @onechannel: !=0 if B channel data and AT commands share one * communication channel (M10x), * ==0 if B channels have separate communication channels (base) * @ignoreframes: number of frames to ignore after setting up B channel * @cidmode: !=0: start in CallID mode * @modulename: name of driver module for LL registration * * Allocate and initialize cardstate structure for Gigaset driver * Calls hardware dependent gigaset_initcshw() function * Calls B channel initialization function gigaset_initbcs() for each B channel * * Return value: * pointer to cardstate structure */ struct cardstate *gigaset_initcs(struct gigaset_driver *drv, int channels, int onechannel, int ignoreframes, int cidmode, const char *modulename) { struct cardstate *cs; unsigned long flags; int i; gig_dbg(DEBUG_INIT, "allocating cs"); cs = alloc_cs(drv); if (!cs) { pr_err("maximum number of devices exceeded\n"); return NULL; } cs->cs_init = 0; cs->channels = channels; cs->onechannel = onechannel; cs->ignoreframes = ignoreframes; INIT_LIST_HEAD(&cs->temp_at_states); cs->running = 0; timer_setup(&cs->timer, timer_tick, 0); spin_lock_init(&cs->ev_lock); cs->ev_tail = 0; cs->ev_head = 0; tasklet_init(&cs->event_tasklet, gigaset_handle_event, (unsigned long) cs); tty_port_init(&cs->port); cs->commands_pending = 0; cs->cur_at_seq = 0; cs->gotfwver = -1; cs->dev = NULL; cs->tty_dev = NULL; cs->cidmode = cidmode != 0; cs->tabnocid = gigaset_tab_nocid; cs->tabcid = gigaset_tab_cid; init_waitqueue_head(&cs->waitqueue); cs->waiting = 0; cs->mode = M_UNKNOWN; cs->mstate = MS_UNINITIALIZED; cs->bcs = kmalloc_array(channels, sizeof(struct bc_state), GFP_KERNEL); cs->inbuf = kmalloc(sizeof(struct inbuf_t), GFP_KERNEL); if (!cs->bcs || !cs->inbuf) { pr_err("out of memory\n"); goto error; } ++cs->cs_init; gig_dbg(DEBUG_INIT, "setting up at_state"); spin_lock_init(&cs->lock); gigaset_at_init(&cs->at_state, NULL, cs, 0); cs->dle = 0; cs->cbytes = 0; gig_dbg(DEBUG_INIT, "setting up inbuf"); gigaset_inbuf_init(cs->inbuf, cs); cs->connected = 0; cs->isdn_up = 0; gig_dbg(DEBUG_INIT, "setting up cmdbuf"); cs->cmdbuf = cs->lastcmdbuf = NULL; spin_lock_init(&cs->cmdlock); cs->curlen = 0; cs->cmdbytes = 0; gig_dbg(DEBUG_INIT, "setting up iif"); if (gigaset_isdn_regdev(cs, modulename) < 0) { pr_err("error registering ISDN device\n"); goto error; } make_valid(cs, VALID_ID); ++cs->cs_init; gig_dbg(DEBUG_INIT, "setting up hw"); if (cs->ops->initcshw(cs) < 0) goto error; ++cs->cs_init; /* set up character device */ gigaset_if_init(cs); /* set up device sysfs */ gigaset_init_dev_sysfs(cs); /* set up channel data structures */ for (i = 0; i < channels; ++i) { gig_dbg(DEBUG_INIT, "setting up bcs[%d]", i); if (gigaset_initbcs(cs->bcs + i, cs, i) < 0) { pr_err("could not allocate channel %d data\n", i); goto error; } } spin_lock_irqsave(&cs->lock, flags); cs->running = 1; spin_unlock_irqrestore(&cs->lock, flags); cs->timer.expires = jiffies + msecs_to_jiffies(GIG_TICK); add_timer(&cs->timer); gig_dbg(DEBUG_INIT, "cs initialized"); return cs; error: gig_dbg(DEBUG_INIT, "failed"); gigaset_freecs(cs); return NULL; } EXPORT_SYMBOL_GPL(gigaset_initcs); /* ReInitialize the b-channel structure on hangup */ void gigaset_bcs_reinit(struct bc_state *bcs) { struct sk_buff *skb; struct cardstate *cs = bcs->cs; unsigned long flags; while ((skb = skb_dequeue(&bcs->squeue)) != NULL) dev_kfree_skb(skb); spin_lock_irqsave(&cs->lock, flags); clear_at_state(&bcs->at_state); bcs->at_state.ConState = 0; bcs->at_state.timer_active = 0; bcs->at_state.timer_expires = 0; bcs->at_state.cid = -1; /* No CID defined */ spin_unlock_irqrestore(&cs->lock, flags); bcs->inputstate = 0; #ifdef CONFIG_GIGASET_DEBUG bcs->emptycount = 0; #endif bcs->rx_fcs = PPP_INITFCS; bcs->chstate = 0; bcs->ignore = cs->ignoreframes; dev_kfree_skb(bcs->rx_skb); bcs->rx_skb = NULL; cs->ops->reinitbcshw(bcs); } static void cleanup_cs(struct cardstate *cs) { struct cmdbuf_t *cb, *tcb; int i; unsigned long flags; spin_lock_irqsave(&cs->lock, flags); cs->mode = M_UNKNOWN; cs->mstate = MS_UNINITIALIZED; clear_at_state(&cs->at_state); dealloc_temp_at_states(cs); gigaset_at_init(&cs->at_state, NULL, cs, 0); cs->inbuf->inputstate = INS_command; cs->inbuf->head = 0; cs->inbuf->tail = 0; cb = cs->cmdbuf; while (cb) { tcb = cb; cb = cb->next; kfree(tcb); } cs->cmdbuf = cs->lastcmdbuf = NULL; cs->curlen = 0; cs->cmdbytes = 0; cs->gotfwver = -1; cs->dle = 0; cs->cur_at_seq = 0; cs->commands_pending = 0; cs->cbytes = 0; spin_unlock_irqrestore(&cs->lock, flags); for (i = 0; i < cs->channels; ++i) { gigaset_freebcs(cs->bcs + i); if (gigaset_initbcs(cs->bcs + i, cs, i) < 0) pr_err("could not allocate channel %d data\n", i); } if (cs->waiting) { cs->cmd_result = -ENODEV; cs->waiting = 0; wake_up_interruptible(&cs->waitqueue); } } /** * gigaset_start() - start device operations * @cs: device descriptor structure. * * Prepares the device for use by setting up communication parameters, * scheduling an EV_START event to initiate device initialization, and * waiting for completion of the initialization. * * Return value: * 0 on success, error code < 0 on failure */ int gigaset_start(struct cardstate *cs) { unsigned long flags; if (mutex_lock_interruptible(&cs->mutex)) return -EBUSY; spin_lock_irqsave(&cs->lock, flags); cs->connected = 1; spin_unlock_irqrestore(&cs->lock, flags); if (cs->mstate != MS_LOCKED) { cs->ops->set_modem_ctrl(cs, 0, TIOCM_DTR | TIOCM_RTS); cs->ops->baud_rate(cs, B115200); cs->ops->set_line_ctrl(cs, CS8); cs->control_state = TIOCM_DTR | TIOCM_RTS; } cs->waiting = 1; if (!gigaset_add_event(cs, &cs->at_state, EV_START, NULL, 0, NULL)) { cs->waiting = 0; goto error; } gigaset_schedule_event(cs); wait_event(cs->waitqueue, !cs->waiting); mutex_unlock(&cs->mutex); return 0; error: mutex_unlock(&cs->mutex); return -ENOMEM; } EXPORT_SYMBOL_GPL(gigaset_start); /** * gigaset_shutdown() - shut down device operations * @cs: device descriptor structure. * * Deactivates the device by scheduling an EV_SHUTDOWN event and * waiting for completion of the shutdown. * * Return value: * 0 - success, -ENODEV - error (no device associated) */ int gigaset_shutdown(struct cardstate *cs) { mutex_lock(&cs->mutex); if (!(cs->flags & VALID_MINOR)) { mutex_unlock(&cs->mutex); return -ENODEV; } cs->waiting = 1; if (!gigaset_add_event(cs, &cs->at_state, EV_SHUTDOWN, NULL, 0, NULL)) goto exit; gigaset_schedule_event(cs); wait_event(cs->waitqueue, !cs->waiting); cleanup_cs(cs); exit: mutex_unlock(&cs->mutex); return 0; } EXPORT_SYMBOL_GPL(gigaset_shutdown); /** * gigaset_stop() - stop device operations * @cs: device descriptor structure. * * Stops operations on the device by scheduling an EV_STOP event and * waiting for completion of the shutdown. */ void gigaset_stop(struct cardstate *cs) { mutex_lock(&cs->mutex); cs->waiting = 1; if (!gigaset_add_event(cs, &cs->at_state, EV_STOP, NULL, 0, NULL)) goto exit; gigaset_schedule_event(cs); wait_event(cs->waitqueue, !cs->waiting); cleanup_cs(cs); exit: mutex_unlock(&cs->mutex); } EXPORT_SYMBOL_GPL(gigaset_stop); static LIST_HEAD(drivers); static DEFINE_SPINLOCK(driver_lock); struct cardstate *gigaset_get_cs_by_id(int id) { unsigned long flags; struct cardstate *ret = NULL; struct cardstate *cs; struct gigaset_driver *drv; unsigned i; spin_lock_irqsave(&driver_lock, flags); list_for_each_entry(drv, &drivers, list) { spin_lock(&drv->lock); for (i = 0; i < drv->minors; ++i) { cs = drv->cs + i; if ((cs->flags & VALID_ID) && cs->myid == id) { ret = cs; break; } } spin_unlock(&drv->lock); if (ret) break; } spin_unlock_irqrestore(&driver_lock, flags); return ret; } static struct cardstate *gigaset_get_cs_by_minor(unsigned minor) { unsigned long flags; struct cardstate *ret = NULL; struct gigaset_driver *drv; unsigned index; spin_lock_irqsave(&driver_lock, flags); list_for_each_entry(drv, &drivers, list) { if (minor < drv->minor || minor >= drv->minor + drv->minors) continue; index = minor - drv->minor; spin_lock(&drv->lock); if (drv->cs[index].flags & VALID_MINOR) ret = drv->cs + index; spin_unlock(&drv->lock); if (ret) break; } spin_unlock_irqrestore(&driver_lock, flags); return ret; } struct cardstate *gigaset_get_cs_by_tty(struct tty_struct *tty) { return gigaset_get_cs_by_minor(tty->index + tty->driver->minor_start); } /** * gigaset_freedriver() - free all associated ressources of a driver * @drv: driver descriptor structure. * * Unregisters the driver from the system and deallocates the driver * structure @drv and all structures referenced from it. * All devices should be shut down before calling this. */ void gigaset_freedriver(struct gigaset_driver *drv) { unsigned long flags; spin_lock_irqsave(&driver_lock, flags); list_del(&drv->list); spin_unlock_irqrestore(&driver_lock, flags); gigaset_if_freedriver(drv); kfree(drv->cs); kfree(drv); } EXPORT_SYMBOL_GPL(gigaset_freedriver); /** * gigaset_initdriver() - initialize driver structure * @minor: First minor number * @minors: Number of minors this driver can handle * @procname: Name of the driver * @devname: Name of the device files (prefix without minor number) * * Allocate and initialize gigaset_driver structure. Initialize interface. * * Return value: * Pointer to the gigaset_driver structure on success, NULL on failure. */ struct gigaset_driver *gigaset_initdriver(unsigned minor, unsigned minors, const char *procname, const char *devname, const struct gigaset_ops *ops, struct module *owner) { struct gigaset_driver *drv; unsigned long flags; unsigned i; drv = kmalloc(sizeof *drv, GFP_KERNEL); if (!drv) return NULL; drv->have_tty = 0; drv->minor = minor; drv->minors = minors; spin_lock_init(&drv->lock); drv->blocked = 0; drv->ops = ops; drv->owner = owner; INIT_LIST_HEAD(&drv->list); drv->cs = kmalloc_array(minors, sizeof(*drv->cs), GFP_KERNEL); if (!drv->cs) goto error; for (i = 0; i < minors; ++i) { drv->cs[i].flags = 0; drv->cs[i].driver = drv; drv->cs[i].ops = drv->ops; drv->cs[i].minor_index = i; mutex_init(&drv->cs[i].mutex); } gigaset_if_initdriver(drv, procname, devname); spin_lock_irqsave(&driver_lock, flags); list_add(&drv->list, &drivers); spin_unlock_irqrestore(&driver_lock, flags); return drv; error: kfree(drv); return NULL; } EXPORT_SYMBOL_GPL(gigaset_initdriver); /** * gigaset_blockdriver() - block driver * @drv: driver descriptor structure. * * Prevents the driver from attaching new devices, in preparation for * deregistration. */ void gigaset_blockdriver(struct gigaset_driver *drv) { drv->blocked = 1; } EXPORT_SYMBOL_GPL(gigaset_blockdriver); static int __init gigaset_init_module(void) { /* in accordance with the principle of least astonishment, * setting the 'debug' parameter to 1 activates a sensible * set of default debug levels */ if (gigaset_debuglevel == 1) gigaset_debuglevel = DEBUG_DEFAULT; pr_info(DRIVER_DESC DRIVER_DESC_DEBUG "\n"); gigaset_isdn_regdrv(); return 0; } static void __exit gigaset_exit_module(void) { gigaset_isdn_unregdrv(); } module_init(gigaset_init_module); module_exit(gigaset_exit_module); MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL");
{ "language": "C" }
/***************************************************************************/ /* */ /* ftcalc.h */ /* */ /* Arithmetic computations (specification). */ /* */ /* Copyright 1996-2006, 2008, 2009, 2012-2013 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTCALC_H__ #define __FTCALC_H__ #include <ft2build.h> #include FT_FREETYPE_H FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Function> */ /* FT_FixedSqrt */ /* */ /* <Description> */ /* Computes the square root of a 16.16 fixed-point value. */ /* */ /* <Input> */ /* x :: The value to compute the root for. */ /* */ /* <Return> */ /* The result of `sqrt(x)'. */ /* */ /* <Note> */ /* This function is not very fast. */ /* */ FT_BASE( FT_Int32 ) FT_SqrtFixed( FT_Int32 x ); /*************************************************************************/ /* */ /* FT_MulDiv() and FT_MulFix() are declared in freetype.h. */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* FT_MulDiv_No_Round */ /* */ /* <Description> */ /* A very simple function used to perform the computation `(a*b)/c' */ /* (without rounding) with maximum accuracy (it uses a 64-bit */ /* intermediate integer whenever necessary). */ /* */ /* This function isn't necessarily as fast as some processor specific */ /* operations, but is at least completely portable. */ /* */ /* <Input> */ /* a :: The first multiplier. */ /* b :: The second multiplier. */ /* c :: The divisor. */ /* */ /* <Return> */ /* The result of `(a*b)/c'. This function never traps when trying to */ /* divide by zero; it simply returns `MaxInt' or `MinInt' depending */ /* on the signs of `a' and `b'. */ /* */ FT_BASE( FT_Long ) FT_MulDiv_No_Round( FT_Long a, FT_Long b, FT_Long c ); /* * A variant of FT_Matrix_Multiply which scales its result afterwards. * The idea is that both `a' and `b' are scaled by factors of 10 so that * the values are as precise as possible to get a correct result during * the 64bit multiplication. Let `sa' and `sb' be the scaling factors of * `a' and `b', respectively, then the scaling factor of the result is * `sa*sb'. */ FT_BASE( void ) FT_Matrix_Multiply_Scaled( const FT_Matrix* a, FT_Matrix *b, FT_Long scaling ); /* * A variant of FT_Vector_Transform. See comments for * FT_Matrix_Multiply_Scaled. */ FT_BASE( void ) FT_Vector_Transform_Scaled( FT_Vector* vector, const FT_Matrix* matrix, FT_Long scaling ); /* * Return -1, 0, or +1, depending on the orientation of a given corner. * We use the Cartesian coordinate system, with positive vertical values * going upwards. The function returns +1 if the corner turns to the * left, -1 to the right, and 0 for undecidable cases. */ FT_BASE( FT_Int ) ft_corner_orientation( FT_Pos in_x, FT_Pos in_y, FT_Pos out_x, FT_Pos out_y ); /* * Return TRUE if a corner is flat or nearly flat. This is equivalent to * saying that the angle difference between the `in' and `out' vectors is * very small. */ FT_BASE( FT_Int ) ft_corner_is_flat( FT_Pos in_x, FT_Pos in_y, FT_Pos out_x, FT_Pos out_y ); /* * Return the most significant bit index. */ FT_BASE( FT_Int ) FT_MSB( FT_UInt32 z ); /* * Return sqrt(x*x+y*y), which is the same as `FT_Vector_Length' but uses * two fixed-point arguments instead. */ FT_BASE( FT_Fixed ) FT_Hypot( FT_Fixed x, FT_Fixed y ); #define INT_TO_F26DOT6( x ) ( (FT_Long)(x) << 6 ) #define INT_TO_F2DOT14( x ) ( (FT_Long)(x) << 14 ) #define INT_TO_FIXED( x ) ( (FT_Long)(x) << 16 ) #define F2DOT14_TO_FIXED( x ) ( (FT_Long)(x) << 2 ) #define FLOAT_TO_FIXED( x ) ( (FT_Long)( x * 65536.0 ) ) #define FIXED_TO_INT( x ) ( FT_RoundFix( x ) >> 16 ) #define ROUND_F26DOT6( x ) ( x >= 0 ? ( ( (x) + 32 ) & -64 ) \ : ( -( ( 32 - (x) ) & -64 ) ) ) FT_END_HEADER #endif /* __FTCALC_H__ */ /* END */
{ "language": "C" }
/*********************************************************************************************************/ // Filename : delay_config.h // Version : V1.00 // Programmer(s) : Liuqiuhu // funcion : This file is used to configure the delay time /*********************************************************************************************************/ #ifndef __DELAY_CONF_H__ #define __DELAY_CONF_H__ #include"rtconfig.h" #if RT_TICK_PER_SECOND == 1 #define DELAY_1S (RT_TICK_PER_SECOND) #define DELAY_S(X) (X*DELAY_1S) #elif RT_TICK_PER_SECOND == 10 #define DELAY_100MS(X) (X) #define DELAY_S(X) (X*10) #elif RT_TICK_PER_SECOND == 100 #define DELAY_10MS(X) (X) #define DELAY_100MS(X) (X*10) #define DELAY_S(X) (X*100) #elif (RT_TICK_PER_SECOND == 1000) #define DELAY_1MS (RT_TICK_PER_SECOND/1000) #define DELAY_MS(X) (X*DELAY_1MS) #define DELAY_S(X) (X*1000*DELAY_1MS) #elif (RT_TICK_PER_SECOND == 10000) #define DELAY_100US(X) (X*RT_TICK_PER_SECOND/10000) #define DELAY_1MS (RT_TICK_PER_SECOND/1000) #define DELAY_MS(X) (X*DELAY_1MS) #define DELAY_S(X) (X*1000*DELAY_1MS) #endif #define DELAY_SYS_INIT_LED_ON DELAY_MS(90) //系统初始化指示灯亮延时 #define DELAY_SYS_INIT_LED_OFF DELAY_MS(10) //系统初始化指示灯灭延时 #define DELAY_SYS_RUN_LED_ON DELAY_MS(960) //系统正常运行指示灯亮延时 #define DELAY_SYS_RUN_LED_OFF DELAY_MS(40) //系统正常运行指示灯灭延时 #define DELAY_SYS_FAULT_LED_ON DELAY_MS(40) //系统故障运行指示灯亮延时 #define DELAY_SYS_FAULT_LED_OFF DELAY_MS(960) //系统故障运行指示灯灭延时 #define DELAY_SYS_SLEEP_LED DELAY_MS(1000) //系统睡眠指示灯延时1s #define POLL_CONNECT_CLOUD DELAY_MS(100) //轮询连接到白象云服务器的周期时间 #define TIMEOUT_CONNECT_CLOUD DELAY_S(30) //连接到白象云服务器的超时时间 #endif
{ "language": "C" }
#include <stdlib.h> #include <math.h> #include <string.h> #include "fitsio2.h" /*--------------------------------------------------------------------------*/ int fits_read_wcstab( fitsfile *fptr, /* I - FITS file pointer */ int nwtb, /* Number of arrays to be read from the binary table(s) */ wtbarr *wtb, /* Address of the first element of an array of wtbarr typedefs. This wtbarr typedef is defined below to match the wtbarr struct defined in WCSLIB. An array of such structs returned by the WCSLIB function wcstab(). */ int *status) /* * Author: Mark Calabretta, Australia Telescope National Facility * http://www.atnf.csiro.au/~mcalabre/index.html * * fits_read_wcstab() extracts arrays from a binary table required in * constructing -TAB coordinates. This helper routine is intended for * use by routines in the WCSLIB library when dealing with the -TAB table * look up WCS convention. */ { int anynul, colnum, hdunum, iwtb, m, naxis, nostat; long *naxes = 0, nelem; wtbarr *wtbp; if (*status) return *status; if (fptr == 0) { return (*status = NULL_INPUT_PTR); } if (nwtb == 0) return 0; /* Zero the array pointers. */ wtbp = wtb; for (iwtb = 0; iwtb < nwtb; iwtb++, wtbp++) { *wtbp->arrayp = 0x0; } /* Save HDU number so that we can move back to it later. */ fits_get_hdu_num(fptr, &hdunum); wtbp = wtb; for (iwtb = 0; iwtb < nwtb; iwtb++, wtbp++) { /* Move to the required binary table extension. */ if (fits_movnam_hdu(fptr, BINARY_TBL, (char *)(wtbp->extnam), wtbp->extver, status)) { goto cleanup; } /* Locate the table column. */ if (fits_get_colnum(fptr, CASEINSEN, (char *)(wtbp->ttype), &colnum, status)) { goto cleanup; } /* Get the array dimensions and check for consistency. */ if (wtbp->ndim < 1) { *status = NEG_AXIS; goto cleanup; } if (!(naxes = calloc(wtbp->ndim, sizeof(long)))) { *status = MEMORY_ALLOCATION; goto cleanup; } if (fits_read_tdim(fptr, colnum, wtbp->ndim, &naxis, naxes, status)) { goto cleanup; } if (naxis != wtbp->ndim) { if (wtbp->kind == 'c' && wtbp->ndim == 2) { /* Allow TDIMn to be omitted for degenerate coordinate arrays. */ naxis = 2; naxes[1] = naxes[0]; naxes[0] = 1; } else { *status = BAD_TDIM; goto cleanup; } } if (wtbp->kind == 'c') { /* Coordinate array; calculate the array size. */ nelem = naxes[0]; for (m = 0; m < naxis-1; m++) { *(wtbp->dimlen + m) = naxes[m+1]; nelem *= naxes[m+1]; } } else { /* Index vector; check length. */ if ((nelem = naxes[0]) != *(wtbp->dimlen)) { /* N.B. coordinate array precedes the index vectors. */ *status = BAD_TDIM; goto cleanup; } } free(naxes); naxes = 0; /* Allocate memory for the array. */ if (!(*wtbp->arrayp = calloc((size_t)nelem, sizeof(double)))) { *status = MEMORY_ALLOCATION; goto cleanup; } /* Read the array from the table. */ if (fits_read_col_dbl(fptr, colnum, wtbp->row, 1L, nelem, 0.0, *wtbp->arrayp, &anynul, status)) { goto cleanup; } } cleanup: /* Move back to the starting HDU. */ nostat = 0; fits_movabs_hdu(fptr, hdunum, 0, &nostat); /* Release allocated memory. */ if (naxes) free(naxes); if (*status) { wtbp = wtb; for (iwtb = 0; iwtb < nwtb; iwtb++, wtbp++) { if (*wtbp->arrayp) free(*wtbp->arrayp); } } return *status; } /*--------------------------------------------------------------------------*/ int ffgiwcs(fitsfile *fptr, /* I - FITS file pointer */ char **header, /* O - pointer to the WCS related keywords */ int *status) /* IO - error status */ /* int fits_get_image_wcs_keys return a string containing all the image WCS header keywords. This string is then used as input to the wcsinit WCSlib routine. THIS ROUTINE IS DEPRECATED. USE fits_hdr2str INSTEAD */ { int hdutype; if (*status > 0) return(*status); fits_get_hdu_type(fptr, &hdutype, status); if (hdutype != IMAGE_HDU) { ffpmsg( "Error in ffgiwcs. This HDU is not an image. Can't read WCS keywords"); return(*status = NOT_IMAGE); } /* read header keywords into a long string of chars */ if (ffh2st(fptr, header, status) > 0) { ffpmsg("error creating string of image WCS keywords (ffgiwcs)"); return(*status); } return(*status); } /*--------------------------------------------------------------------------*/ int ffgics(fitsfile *fptr, /* I - FITS file pointer */ double *xrval, /* O - X reference value */ double *yrval, /* O - Y reference value */ double *xrpix, /* O - X reference pixel */ double *yrpix, /* O - Y reference pixel */ double *xinc, /* O - X increment per pixel */ double *yinc, /* O - Y increment per pixel */ double *rot, /* O - rotation angle (degrees) */ char *type, /* O - type of projection ('-tan') */ int *status) /* IO - error status */ /* read the values of the celestial coordinate system keywords. These values may be used as input to the subroutines that calculate celestial coordinates. (ffxypx, ffwldp) Modified in Nov 1999 to convert the CD matrix keywords back to the old CDELTn form, and to swap the axes if the dec-like axis is given first, and to assume default values if any of the keywords are not present. */ { int tstat = 0, cd_exists = 0, pc_exists = 0; char ctype[FLEN_VALUE]; double cd11 = 0.0, cd21 = 0.0, cd22 = 0.0, cd12 = 0.0; double pc11 = 1.0, pc21 = 0.0, pc22 = 1.0, pc12 = 0.0; double pi = 3.1415926535897932; double phia, phib, temp; double toler = .0002; /* tolerance for angles to agree (radians) */ /* (= approximately 0.01 degrees) */ if (*status > 0) return(*status); tstat = 0; if (ffgkyd(fptr, "CRVAL1", xrval, NULL, &tstat)) *xrval = 0.; tstat = 0; if (ffgkyd(fptr, "CRVAL2", yrval, NULL, &tstat)) *yrval = 0.; tstat = 0; if (ffgkyd(fptr, "CRPIX1", xrpix, NULL, &tstat)) *xrpix = 0.; tstat = 0; if (ffgkyd(fptr, "CRPIX2", yrpix, NULL, &tstat)) *yrpix = 0.; /* look for CDELTn first, then CDi_j keywords */ tstat = 0; if (ffgkyd(fptr, "CDELT1", xinc, NULL, &tstat)) { /* CASE 1: no CDELTn keyword, so look for the CD matrix */ tstat = 0; if (ffgkyd(fptr, "CD1_1", &cd11, NULL, &tstat)) tstat = 0; /* reset keyword not found error */ else cd_exists = 1; /* found at least 1 CD_ keyword */ if (ffgkyd(fptr, "CD2_1", &cd21, NULL, &tstat)) tstat = 0; /* reset keyword not found error */ else cd_exists = 1; /* found at least 1 CD_ keyword */ if (ffgkyd(fptr, "CD1_2", &cd12, NULL, &tstat)) tstat = 0; /* reset keyword not found error */ else cd_exists = 1; /* found at least 1 CD_ keyword */ if (ffgkyd(fptr, "CD2_2", &cd22, NULL, &tstat)) tstat = 0; /* reset keyword not found error */ else cd_exists = 1; /* found at least 1 CD_ keyword */ if (cd_exists) /* convert CDi_j back to CDELTn */ { /* there are 2 ways to compute the angle: */ phia = atan2( cd21, cd11); phib = atan2(-cd12, cd22); /* ensure that phia <= phib */ temp = minvalue(phia, phib); phib = maxvalue(phia, phib); phia = temp; /* there is a possible 180 degree ambiguity in the angles */ /* so add 180 degress to the smaller value if the values */ /* differ by more than 90 degrees = pi/2 radians. */ /* (Later, we may decide to take the other solution by */ /* subtracting 180 degrees from the larger value). */ if ((phib - phia) > (pi / 2.)) phia += pi; if (fabs(phia - phib) > toler) { /* angles don't agree, so looks like there is some skewness */ /* between the axes. Return with an error to be safe. */ *status = APPROX_WCS_KEY; } phia = (phia + phib) /2.; /* use the average of the 2 values */ *xinc = cd11 / cos(phia); *yinc = cd22 / cos(phia); *rot = phia * 180. / pi; /* common usage is to have a positive yinc value. If it is */ /* negative, then subtract 180 degrees from rot and negate */ /* both xinc and yinc. */ if (*yinc < 0) { *xinc = -(*xinc); *yinc = -(*yinc); *rot = *rot - 180.; } } else /* no CD matrix keywords either */ { *xinc = 1.; /* there was no CDELT1 keyword, but check for CDELT2 just in case */ tstat = 0; if (ffgkyd(fptr, "CDELT2", yinc, NULL, &tstat)) *yinc = 1.; tstat = 0; if (ffgkyd(fptr, "CROTA2", rot, NULL, &tstat)) *rot=0.; } } else /* Case 2: CDELTn + optional PC matrix */ { if (ffgkyd(fptr, "CDELT2", yinc, NULL, &tstat)) *yinc = 1.; tstat = 0; if (ffgkyd(fptr, "CROTA2", rot, NULL, &tstat)) { *rot=0.; /* no CROTA2 keyword, so look for the PC matrix */ tstat = 0; if (ffgkyd(fptr, "PC1_1", &pc11, NULL, &tstat)) tstat = 0; /* reset keyword not found error */ else pc_exists = 1; /* found at least 1 PC_ keyword */ if (ffgkyd(fptr, "PC2_1", &pc21, NULL, &tstat)) tstat = 0; /* reset keyword not found error */ else pc_exists = 1; /* found at least 1 PC_ keyword */ if (ffgkyd(fptr, "PC1_2", &pc12, NULL, &tstat)) tstat = 0; /* reset keyword not found error */ else pc_exists = 1; /* found at least 1 PC_ keyword */ if (ffgkyd(fptr, "PC2_2", &pc22, NULL, &tstat)) tstat = 0; /* reset keyword not found error */ else pc_exists = 1; /* found at least 1 PC_ keyword */ if (pc_exists) /* convert PCi_j back to CDELTn */ { /* there are 2 ways to compute the angle: */ phia = atan2( pc21, pc11); phib = atan2(-pc12, pc22); /* ensure that phia <= phib */ temp = minvalue(phia, phib); phib = maxvalue(phia, phib); phia = temp; /* there is a possible 180 degree ambiguity in the angles */ /* so add 180 degress to the smaller value if the values */ /* differ by more than 90 degrees = pi/2 radians. */ /* (Later, we may decide to take the other solution by */ /* subtracting 180 degrees from the larger value). */ if ((phib - phia) > (pi / 2.)) phia += pi; if (fabs(phia - phib) > toler) { /* angles don't agree, so looks like there is some skewness */ /* between the axes. Return with an error to be safe. */ *status = APPROX_WCS_KEY; } phia = (phia + phib) /2.; /* use the average of the 2 values */ *rot = phia * 180. / pi; } } } /* get the type of projection, if any */ tstat = 0; if (ffgkys(fptr, "CTYPE1", ctype, NULL, &tstat)) type[0] = '\0'; else { /* copy the projection type string */ strncpy(type, &ctype[4], 4); type[4] = '\0'; /* check if RA and DEC are inverted */ if (!strncmp(ctype, "DEC-", 4) || !strncmp(ctype+1, "LAT", 3)) { /* the latitudinal axis is given first, so swap them */ /* this case was removed on 12/9. Apparently not correct. if ((*xinc / *yinc) < 0. ) *rot = -90. - (*rot); else */ *rot = 90. - (*rot); /* Empirical tests with ds9 show the y-axis sign must be negated */ /* and the xinc and yinc values must NOT be swapped. */ *yinc = -(*yinc); temp = *xrval; *xrval = *yrval; *yrval = temp; } } return(*status); } /*--------------------------------------------------------------------------*/ int ffgicsa(fitsfile *fptr, /* I - FITS file pointer */ char version, /* I - character code of desired version */ /* A - Z or blank */ double *xrval, /* O - X reference value */ double *yrval, /* O - Y reference value */ double *xrpix, /* O - X reference pixel */ double *yrpix, /* O - Y reference pixel */ double *xinc, /* O - X increment per pixel */ double *yinc, /* O - Y increment per pixel */ double *rot, /* O - rotation angle (degrees) */ char *type, /* O - type of projection ('-tan') */ int *status) /* IO - error status */ /* read the values of the celestial coordinate system keywords. These values may be used as input to the subroutines that calculate celestial coordinates. (ffxypx, ffwldp) Modified in Nov 1999 to convert the CD matrix keywords back to the old CDELTn form, and to swap the axes if the dec-like axis is given first, and to assume default values if any of the keywords are not present. */ { int tstat = 0, cd_exists = 0, pc_exists = 0; char ctype[FLEN_VALUE], keyname[FLEN_VALUE], alt[2]; double cd11 = 0.0, cd21 = 0.0, cd22 = 0.0, cd12 = 0.0; double pc11 = 1.0, pc21 = 0.0, pc22 = 1.0, pc12 = 0.0; double pi = 3.1415926535897932; double phia, phib, temp; double toler = .0002; /* tolerance for angles to agree (radians) */ /* (= approximately 0.01 degrees) */ if (*status > 0) return(*status); if (version == ' ') { ffgics(fptr, xrval, yrval, xrpix, yrpix, xinc, yinc, rot, type, status); return (*status); } if (version > 'Z' || version < 'A') { ffpmsg("ffgicsa: illegal WCS version code (must be A - Z or blank)"); return(*status = WCS_ERROR); } alt[0] = version; alt[1] = '\0'; tstat = 0; strcpy(keyname, "CRVAL1"); strcat(keyname, alt); if (ffgkyd(fptr, keyname, xrval, NULL, &tstat)) *xrval = 0.; tstat = 0; strcpy(keyname, "CRVAL2"); strcat(keyname, alt); if (ffgkyd(fptr, keyname, yrval, NULL, &tstat)) *yrval = 0.; tstat = 0; strcpy(keyname, "CRPIX1"); strcat(keyname, alt); if (ffgkyd(fptr, keyname, xrpix, NULL, &tstat)) *xrpix = 0.; tstat = 0; strcpy(keyname, "CRPIX2"); strcat(keyname, alt); if (ffgkyd(fptr, keyname, yrpix, NULL, &tstat)) *yrpix = 0.; /* look for CDELTn first, then CDi_j keywords */ tstat = 0; strcpy(keyname, "CDELT1"); strcat(keyname, alt); if (ffgkyd(fptr, keyname, xinc, NULL, &tstat)) { /* CASE 1: no CDELTn keyword, so look for the CD matrix */ tstat = 0; strcpy(keyname, "CD1_1"); strcat(keyname, alt); if (ffgkyd(fptr, keyname, &cd11, NULL, &tstat)) tstat = 0; /* reset keyword not found error */ else cd_exists = 1; /* found at least 1 CD_ keyword */ strcpy(keyname, "CD2_1"); strcat(keyname, alt); if (ffgkyd(fptr, keyname, &cd21, NULL, &tstat)) tstat = 0; /* reset keyword not found error */ else cd_exists = 1; /* found at least 1 CD_ keyword */ strcpy(keyname, "CD1_2"); strcat(keyname, alt); if (ffgkyd(fptr, keyname, &cd12, NULL, &tstat)) tstat = 0; /* reset keyword not found error */ else cd_exists = 1; /* found at least 1 CD_ keyword */ strcpy(keyname, "CD2_2"); strcat(keyname, alt); if (ffgkyd(fptr, keyname, &cd22, NULL, &tstat)) tstat = 0; /* reset keyword not found error */ else cd_exists = 1; /* found at least 1 CD_ keyword */ if (cd_exists) /* convert CDi_j back to CDELTn */ { /* there are 2 ways to compute the angle: */ phia = atan2( cd21, cd11); phib = atan2(-cd12, cd22); /* ensure that phia <= phib */ temp = minvalue(phia, phib); phib = maxvalue(phia, phib); phia = temp; /* there is a possible 180 degree ambiguity in the angles */ /* so add 180 degress to the smaller value if the values */ /* differ by more than 90 degrees = pi/2 radians. */ /* (Later, we may decide to take the other solution by */ /* subtracting 180 degrees from the larger value). */ if ((phib - phia) > (pi / 2.)) phia += pi; if (fabs(phia - phib) > toler) { /* angles don't agree, so looks like there is some skewness */ /* between the axes. Return with an error to be safe. */ *status = APPROX_WCS_KEY; } phia = (phia + phib) /2.; /* use the average of the 2 values */ *xinc = cd11 / cos(phia); *yinc = cd22 / cos(phia); *rot = phia * 180. / pi; /* common usage is to have a positive yinc value. If it is */ /* negative, then subtract 180 degrees from rot and negate */ /* both xinc and yinc. */ if (*yinc < 0) { *xinc = -(*xinc); *yinc = -(*yinc); *rot = *rot - 180.; } } else /* no CD matrix keywords either */ { *xinc = 1.; /* there was no CDELT1 keyword, but check for CDELT2 just in case */ tstat = 0; strcpy(keyname, "CDELT2"); strcat(keyname, alt); if (ffgkyd(fptr, keyname, yinc, NULL, &tstat)) *yinc = 1.; tstat = 0; strcpy(keyname, "CROTA2"); strcat(keyname, alt); if (ffgkyd(fptr, keyname, rot, NULL, &tstat)) *rot=0.; } } else /* Case 2: CDELTn + optional PC matrix */ { strcpy(keyname, "CDELT2"); strcat(keyname, alt); if (ffgkyd(fptr, keyname, yinc, NULL, &tstat)) *yinc = 1.; tstat = 0; strcpy(keyname, "CROTA2"); strcat(keyname, alt); if (ffgkyd(fptr, keyname, rot, NULL, &tstat)) { *rot=0.; /* no CROTA2 keyword, so look for the PC matrix */ tstat = 0; strcpy(keyname, "PC1_1"); strcat(keyname, alt); if (ffgkyd(fptr, keyname, &pc11, NULL, &tstat)) tstat = 0; /* reset keyword not found error */ else pc_exists = 1; /* found at least 1 PC_ keyword */ strcpy(keyname, "PC2_1"); strcat(keyname, alt); if (ffgkyd(fptr, keyname, &pc21, NULL, &tstat)) tstat = 0; /* reset keyword not found error */ else pc_exists = 1; /* found at least 1 PC_ keyword */ strcpy(keyname, "PC1_2"); strcat(keyname, alt); if (ffgkyd(fptr, keyname, &pc12, NULL, &tstat)) tstat = 0; /* reset keyword not found error */ else pc_exists = 1; /* found at least 1 PC_ keyword */ strcpy(keyname, "PC2_2"); strcat(keyname, alt); if (ffgkyd(fptr, keyname, &pc22, NULL, &tstat)) tstat = 0; /* reset keyword not found error */ else pc_exists = 1; /* found at least 1 PC_ keyword */ if (pc_exists) /* convert PCi_j back to CDELTn */ { /* there are 2 ways to compute the angle: */ phia = atan2( pc21, pc11); phib = atan2(-pc12, pc22); /* ensure that phia <= phib */ temp = minvalue(phia, phib); phib = maxvalue(phia, phib); phia = temp; /* there is a possible 180 degree ambiguity in the angles */ /* so add 180 degress to the smaller value if the values */ /* differ by more than 90 degrees = pi/2 radians. */ /* (Later, we may decide to take the other solution by */ /* subtracting 180 degrees from the larger value). */ if ((phib - phia) > (pi / 2.)) phia += pi; if (fabs(phia - phib) > toler) { /* angles don't agree, so looks like there is some skewness */ /* between the axes. Return with an error to be safe. */ *status = APPROX_WCS_KEY; } phia = (phia + phib) /2.; /* use the average of the 2 values */ *rot = phia * 180. / pi; } } } /* get the type of projection, if any */ tstat = 0; strcpy(keyname, "CTYPE1"); strcat(keyname, alt); if (ffgkys(fptr, keyname, ctype, NULL, &tstat)) type[0] = '\0'; else { /* copy the projection type string */ strncpy(type, &ctype[4], 4); type[4] = '\0'; /* check if RA and DEC are inverted */ if (!strncmp(ctype, "DEC-", 4) || !strncmp(ctype+1, "LAT", 3)) { /* the latitudinal axis is given first, so swap them */ *rot = 90. - (*rot); /* Empirical tests with ds9 show the y-axis sign must be negated */ /* and the xinc and yinc values must NOT be swapped. */ *yinc = -(*yinc); temp = *xrval; *xrval = *yrval; *yrval = temp; } } return(*status); } /*--------------------------------------------------------------------------*/ int ffgtcs(fitsfile *fptr, /* I - FITS file pointer */ int xcol, /* I - column containing the RA coordinate */ int ycol, /* I - column containing the DEC coordinate */ double *xrval, /* O - X reference value */ double *yrval, /* O - Y reference value */ double *xrpix, /* O - X reference pixel */ double *yrpix, /* O - Y reference pixel */ double *xinc, /* O - X increment per pixel */ double *yinc, /* O - Y increment per pixel */ double *rot, /* O - rotation angle (degrees) */ char *type, /* O - type of projection ('-sin') */ int *status) /* IO - error status */ /* read the values of the celestial coordinate system keywords from a FITS table where the X and Y or RA and DEC coordinates are stored in separate column. Do this by converting the table to a temporary FITS image, then reading the keywords from the image file. These values may be used as input to the subroutines that calculate celestial coordinates. (ffxypx, ffwldp) */ { int colnum[2]; long naxes[2]; fitsfile *tptr; if (*status > 0) return(*status); colnum[0] = xcol; colnum[1] = ycol; naxes[0] = 10; naxes[1] = 10; /* create temporary FITS file, in memory */ ffinit(&tptr, "mem://", status); /* create a temporary image; the datatype and size are not important */ ffcrim(tptr, 32, 2, naxes, status); /* now copy the relevant keywords from the table to the image */ fits_copy_pixlist2image(fptr, tptr, 9, 2, colnum, status); /* write default WCS keywords, if they are not present */ fits_write_keys_histo(fptr, tptr, 2, colnum, status); if (*status > 0) return(*status); /* read the WCS keyword values from the temporary image */ ffgics(tptr, xrval, yrval, xrpix, yrpix, xinc, yinc, rot, type, status); if (*status > 0) { ffpmsg ("ffgtcs could not find all the celestial coordinate keywords"); return(*status = NO_WCS_KEY); } /* delete the temporary file */ fits_delete_file(tptr, status); return(*status); } /*--------------------------------------------------------------------------*/ int ffgtwcs(fitsfile *fptr, /* I - FITS file pointer */ int xcol, /* I - column number for the X column */ int ycol, /* I - column number for the Y column */ char **header, /* O - string of all the WCS keywords */ int *status) /* IO - error status */ /* int fits_get_table_wcs_keys Return string containing all the WCS keywords appropriate for the pair of X and Y columns containing the coordinate of each event in an event list table. This string may then be passed to Doug Mink's WCS library wcsinit routine, to create and initialize the WCS structure. The calling routine must free the header character string when it is no longer needed. THIS ROUTINE IS DEPRECATED. USE fits_hdr2str INSTEAD */ { int hdutype, ncols, tstatus, length; int naxis1 = 1, naxis2 = 1; long tlmin, tlmax; char keyname[FLEN_KEYWORD]; char valstring[FLEN_VALUE]; char comm[2]; char *cptr; /* construct a string of 80 blanks, for adding fill to the keywords */ /* 12345678901234567890123456789012345678901234567890123456789012345678901234567890 */ char blanks[] = " "; if (*status > 0) return(*status); fits_get_hdu_type(fptr, &hdutype, status); if (hdutype == IMAGE_HDU) { ffpmsg("Can't read table WSC keywords. This HDU is not a table"); return(*status = NOT_TABLE); } fits_get_num_cols(fptr, &ncols, status); if (xcol < 1 || xcol > ncols) { ffpmsg("illegal X axis column number in fftwcs"); return(*status = BAD_COL_NUM); } if (ycol < 1 || ycol > ncols) { ffpmsg("illegal Y axis column number in fftwcs"); return(*status = BAD_COL_NUM); } /* allocate character string for all the WCS keywords */ *header = calloc(1, 2401); /* room for up to 30 keywords */ if (*header == 0) { ffpmsg("error allocating memory for WCS header keywords (fftwcs)"); return(*status = MEMORY_ALLOCATION); } cptr = *header; comm[0] = '\0'; tstatus = 0; ffkeyn("TLMIN",xcol,keyname,status); ffgkyj(fptr,keyname, &tlmin,NULL,&tstatus); if (!tstatus) { ffkeyn("TLMAX",xcol,keyname,status); ffgkyj(fptr,keyname, &tlmax,NULL,&tstatus); } if (!tstatus) { naxis1 = tlmax - tlmin + 1; } tstatus = 0; ffkeyn("TLMIN",ycol,keyname,status); ffgkyj(fptr,keyname, &tlmin,NULL,&tstatus); if (!tstatus) { ffkeyn("TLMAX",ycol,keyname,status); ffgkyj(fptr,keyname, &tlmax,NULL,&tstatus); } if (!tstatus) { naxis2 = tlmax - tlmin + 1; } /* 123456789012345678901234567890 */ strcat(cptr, "NAXIS = 2"); strncat(cptr, blanks, 50); cptr += 80; ffi2c(naxis1, valstring, status); /* convert to formatted string */ ffmkky("NAXIS1", valstring, comm, cptr, status); /* construct the keyword*/ strncat(cptr, blanks, 50); /* pad with blanks */ cptr += 80; strcpy(keyname, "NAXIS2"); ffi2c(naxis2, valstring, status); /* convert to formatted string */ ffmkky(keyname, valstring, comm, cptr, status); /* construct the keyword*/ strncat(cptr, blanks, 50); /* pad with blanks */ cptr += 80; /* read the required header keywords (use defaults if not found) */ /* CTYPE1 keyword */ tstatus = 0; ffkeyn("TCTYP",xcol,keyname,status); if (ffgkey(fptr, keyname, valstring, NULL, &tstatus) ) valstring[0] = '\0'; ffmkky("CTYPE1", valstring, comm, cptr, status); /* construct the keyword*/ length = strlen(cptr); strncat(cptr, blanks, 80 - length); /* pad with blanks */ cptr += 80; /* CTYPE2 keyword */ tstatus = 0; ffkeyn("TCTYP",ycol,keyname,status); if (ffgkey(fptr, keyname, valstring, NULL, &tstatus) ) valstring[0] = '\0'; ffmkky("CTYPE2", valstring, comm, cptr, status); /* construct the keyword*/ length = strlen(cptr); strncat(cptr, blanks, 80 - length); /* pad with blanks */ cptr += 80; /* CRPIX1 keyword */ tstatus = 0; ffkeyn("TCRPX",xcol,keyname,status); if (ffgkey(fptr, keyname, valstring, NULL, &tstatus) ) strcpy(valstring, "1"); ffmkky("CRPIX1", valstring, comm, cptr, status); /* construct the keyword*/ strncat(cptr, blanks, 50); /* pad with blanks */ cptr += 80; /* CRPIX2 keyword */ tstatus = 0; ffkeyn("TCRPX",ycol,keyname,status); if (ffgkey(fptr, keyname, valstring, NULL, &tstatus) ) strcpy(valstring, "1"); ffmkky("CRPIX2", valstring, comm, cptr, status); /* construct the keyword*/ strncat(cptr, blanks, 50); /* pad with blanks */ cptr += 80; /* CRVAL1 keyword */ tstatus = 0; ffkeyn("TCRVL",xcol,keyname,status); if (ffgkey(fptr, keyname, valstring, NULL, &tstatus) ) strcpy(valstring, "1"); ffmkky("CRVAL1", valstring, comm, cptr, status); /* construct the keyword*/ strncat(cptr, blanks, 50); /* pad with blanks */ cptr += 80; /* CRVAL2 keyword */ tstatus = 0; ffkeyn("TCRVL",ycol,keyname,status); if (ffgkey(fptr, keyname, valstring, NULL, &tstatus) ) strcpy(valstring, "1"); ffmkky("CRVAL2", valstring, comm, cptr, status); /* construct the keyword*/ strncat(cptr, blanks, 50); /* pad with blanks */ cptr += 80; /* CDELT1 keyword */ tstatus = 0; ffkeyn("TCDLT",xcol,keyname,status); if (ffgkey(fptr, keyname, valstring, NULL, &tstatus) ) strcpy(valstring, "1"); ffmkky("CDELT1", valstring, comm, cptr, status); /* construct the keyword*/ strncat(cptr, blanks, 50); /* pad with blanks */ cptr += 80; /* CDELT2 keyword */ tstatus = 0; ffkeyn("TCDLT",ycol,keyname,status); if (ffgkey(fptr, keyname, valstring, NULL, &tstatus) ) strcpy(valstring, "1"); ffmkky("CDELT2", valstring, comm, cptr, status); /* construct the keyword*/ strncat(cptr, blanks, 50); /* pad with blanks */ cptr += 80; /* the following keywords may not exist */ /* CROTA2 keyword */ tstatus = 0; ffkeyn("TCROT",ycol,keyname,status); if (ffgkey(fptr, keyname, valstring, NULL, &tstatus) == 0 ) { ffmkky("CROTA2", valstring, comm, cptr, status); /* construct keyword*/ strncat(cptr, blanks, 50); /* pad with blanks */ cptr += 80; } /* EPOCH keyword */ tstatus = 0; if (ffgkey(fptr, "EPOCH", valstring, NULL, &tstatus) == 0 ) { ffmkky("EPOCH", valstring, comm, cptr, status); /* construct keyword*/ length = strlen(cptr); strncat(cptr, blanks, 80 - length); /* pad with blanks */ cptr += 80; } /* EQUINOX keyword */ tstatus = 0; if (ffgkey(fptr, "EQUINOX", valstring, NULL, &tstatus) == 0 ) { ffmkky("EQUINOX", valstring, comm, cptr, status); /* construct keyword*/ length = strlen(cptr); strncat(cptr, blanks, 80 - length); /* pad with blanks */ cptr += 80; } /* RADECSYS keyword */ tstatus = 0; if (ffgkey(fptr, "RADECSYS", valstring, NULL, &tstatus) == 0 ) { ffmkky("RADECSYS", valstring, comm, cptr, status); /*construct keyword*/ length = strlen(cptr); strncat(cptr, blanks, 80 - length); /* pad with blanks */ cptr += 80; } /* TELESCOPE keyword */ tstatus = 0; if (ffgkey(fptr, "TELESCOP", valstring, NULL, &tstatus) == 0 ) { ffmkky("TELESCOP", valstring, comm, cptr, status); length = strlen(cptr); strncat(cptr, blanks, 80 - length); /* pad with blanks */ cptr += 80; } /* INSTRUME keyword */ tstatus = 0; if (ffgkey(fptr, "INSTRUME", valstring, NULL, &tstatus) == 0 ) { ffmkky("INSTRUME", valstring, comm, cptr, status); length = strlen(cptr); strncat(cptr, blanks, 80 - length); /* pad with blanks */ cptr += 80; } /* DETECTOR keyword */ tstatus = 0; if (ffgkey(fptr, "DETECTOR", valstring, NULL, &tstatus) == 0 ) { ffmkky("DETECTOR", valstring, comm, cptr, status); length = strlen(cptr); strncat(cptr, blanks, 80 - length); /* pad with blanks */ cptr += 80; } /* MJD-OBS keyword */ tstatus = 0; if (ffgkey(fptr, "MJD-OBS", valstring, NULL, &tstatus) == 0 ) { ffmkky("MJD-OBS", valstring, comm, cptr, status); length = strlen(cptr); strncat(cptr, blanks, 80 - length); /* pad with blanks */ cptr += 80; } /* DATE-OBS keyword */ tstatus = 0; if (ffgkey(fptr, "DATE-OBS", valstring, NULL, &tstatus) == 0 ) { ffmkky("DATE-OBS", valstring, comm, cptr, status); length = strlen(cptr); strncat(cptr, blanks, 80 - length); /* pad with blanks */ cptr += 80; } /* DATE keyword */ tstatus = 0; if (ffgkey(fptr, "DATE", valstring, NULL, &tstatus) == 0 ) { ffmkky("DATE", valstring, comm, cptr, status); length = strlen(cptr); strncat(cptr, blanks, 80 - length); /* pad with blanks */ cptr += 80; } strcat(cptr, "END"); strncat(cptr, blanks, 77); return(*status); }
{ "language": "C" }
/* Simple DirectMedia Layer Copyright (C) 1997-2014 Sam Lantinga <slouken@libsdl.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. */ #include "../SDL_internal.h" /* Drag and drop event handling code for SDL */ #include "SDL_events.h" #include "SDL_events_c.h" #include "SDL_dropevents_c.h" int SDL_SendDropFile(const char *file) { int posted; /* Post the event, if desired */ posted = 0; if (SDL_GetEventState(SDL_DROPFILE) == SDL_ENABLE) { SDL_Event event; event.type = SDL_DROPFILE; event.drop.file = SDL_strdup(file); posted = (SDL_PushEvent(&event) > 0); } return (posted); } /* vi: set ts=4 sw=4 expandtab: */
{ "language": "C" }
/*************************************************************************/ /*! @Title RGX Core BVNC 5.9.1.46 @Copyright Copyright (c) Imagination Technologies Ltd. All Rights Reserved @License Dual MIT/GPLv2 The contents of this file are subject to the MIT license as set out below. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 ("GPL") in which case the provisions of GPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of GPL, and not to allow others to use your version of this file under the terms of the MIT license, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by GPL as set out in the file called "GPL-COPYING" included in this distribution. If you do not delete the provisions above, a recipient may use your version of this file under the terms of either the MIT license or GPL. This License is also included in this distribution in the file called "MIT-COPYING". EXCEPT AS OTHERWISE STATED IN A NEGOTIATED AGREEMENT: (A) 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; AND (B) IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /**************************************************************************/ #ifndef _RGXCORE_KM_5_9_1_46_H_ #define _RGXCORE_KM_5_9_1_46_H_ /***** Automatically generated file (26/08/2015 09:15:08): Do not edit manually ********************/ /***** Timestamp: (26/08/2015 09:15:08)************************************************************/ /***** CS: @2967148 ******************************************************************/ /****************************************************************************** * BVNC = 5.9.1.46 *****************************************************************************/ #define RGX_BVNC_KM_B 5 #define RGX_BVNC_KM_V 9 #define RGX_BVNC_KM_N 1 #define RGX_BVNC_KM_C 46 /****************************************************************************** * Errata *****************************************************************************/ #define FIX_HW_BRN_38344 /****************************************************************************** * Enhancements *****************************************************************************/ #define HW_ERN_36400 #endif /* _RGXCORE_KM_5_9_1_46_H_ */
{ "language": "C" }
/* -*- mode: c; c-basic-offset: 8; -*- * vim: noexpandtab sw=8 ts=8 sts=0: * * inode.h * * Function prototypes * * Copyright (C) 2002, 2004 Oracle. All rights reserved. * * 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 021110-1307, USA. */ #ifndef OCFS2_INODE_H #define OCFS2_INODE_H #include "extent_map.h" /* OCFS2 Inode Private Data */ struct ocfs2_inode_info { u64 ip_blkno; struct ocfs2_lock_res ip_rw_lockres; struct ocfs2_lock_res ip_inode_lockres; struct ocfs2_lock_res ip_open_lockres; /* protects allocation changes on this inode. */ struct rw_semaphore ip_alloc_sem; /* protects extended attribute changes on this inode */ struct rw_semaphore ip_xattr_sem; /* These fields are protected by ip_lock */ spinlock_t ip_lock; u32 ip_open_count; struct list_head ip_io_markers; u32 ip_clusters; u16 ip_dyn_features; struct mutex ip_io_mutex; u32 ip_flags; /* see below */ u32 ip_attr; /* inode attributes */ /* Record unwritten extents during direct io. */ struct list_head ip_unwritten_list; /* protected by recovery_lock. */ struct inode *ip_next_orphan; struct ocfs2_caching_info ip_metadata_cache; struct ocfs2_extent_map ip_extent_map; struct inode vfs_inode; struct jbd2_inode ip_jinode; u32 ip_dir_start_lookup; /* Only valid if the inode is the dir. */ u32 ip_last_used_slot; u64 ip_last_used_group; u32 ip_dir_lock_gen; struct ocfs2_alloc_reservation ip_la_data_resv; /* * Transactions that contain inode's metadata needed to complete * fsync and fdatasync, respectively. */ tid_t i_sync_tid; tid_t i_datasync_tid; struct dquot *i_dquot[MAXQUOTAS]; }; /* * Flags for the ip_flags field */ /* System file inodes */ #define OCFS2_INODE_SYSTEM_FILE 0x00000001 #define OCFS2_INODE_JOURNAL 0x00000002 #define OCFS2_INODE_BITMAP 0x00000004 /* This inode has been wiped from disk */ #define OCFS2_INODE_DELETED 0x00000008 /* Has the inode been orphaned on another node? * * This hints to ocfs2_drop_inode that it should clear i_nlink before * continuing. * * We *only* set this on unlink vote from another node. If the inode * was locally orphaned, then we're sure of the state and don't need * to twiddle i_nlink later - it's either zero or not depending on * whether our unlink succeeded. Otherwise we got this from a node * whose intention was to orphan the inode, however he may have * crashed, failed etc, so we let ocfs2_drop_inode zero the value and * rely on ocfs2_delete_inode to sort things out under the proper * cluster locks. */ #define OCFS2_INODE_MAYBE_ORPHANED 0x00000010 /* Does someone have the file open O_DIRECT */ #define OCFS2_INODE_OPEN_DIRECT 0x00000020 /* Tell the inode wipe code it's not in orphan dir */ #define OCFS2_INODE_SKIP_ORPHAN_DIR 0x00000040 /* Entry in orphan dir with 'dio-' prefix */ #define OCFS2_INODE_DIO_ORPHAN_ENTRY 0x00000080 static inline struct ocfs2_inode_info *OCFS2_I(struct inode *inode) { return container_of(inode, struct ocfs2_inode_info, vfs_inode); } #define INODE_JOURNAL(i) (OCFS2_I(i)->ip_flags & OCFS2_INODE_JOURNAL) #define SET_INODE_JOURNAL(i) (OCFS2_I(i)->ip_flags |= OCFS2_INODE_JOURNAL) extern const struct address_space_operations ocfs2_aops; extern const struct ocfs2_caching_operations ocfs2_inode_caching_ops; static inline struct ocfs2_caching_info *INODE_CACHE(struct inode *inode) { return &OCFS2_I(inode)->ip_metadata_cache; } void ocfs2_evict_inode(struct inode *inode); int ocfs2_drop_inode(struct inode *inode); /* Flags for ocfs2_iget() */ #define OCFS2_FI_FLAG_SYSFILE 0x1 #define OCFS2_FI_FLAG_ORPHAN_RECOVERY 0x2 #define OCFS2_FI_FLAG_FILECHECK_CHK 0x4 #define OCFS2_FI_FLAG_FILECHECK_FIX 0x8 struct inode *ocfs2_ilookup(struct super_block *sb, u64 feoff); struct inode *ocfs2_iget(struct ocfs2_super *osb, u64 feoff, unsigned flags, int sysfile_type); int ocfs2_inode_revalidate(struct dentry *dentry); void ocfs2_populate_inode(struct inode *inode, struct ocfs2_dinode *fe, int create_ino); void ocfs2_sync_blockdev(struct super_block *sb); void ocfs2_refresh_inode(struct inode *inode, struct ocfs2_dinode *fe); int ocfs2_mark_inode_dirty(handle_t *handle, struct inode *inode, struct buffer_head *bh); void ocfs2_set_inode_flags(struct inode *inode); void ocfs2_get_inode_flags(struct ocfs2_inode_info *oi); static inline blkcnt_t ocfs2_inode_sector_count(struct inode *inode) { int c_to_s_bits = OCFS2_SB(inode->i_sb)->s_clustersize_bits - 9; return (blkcnt_t)OCFS2_I(inode)->ip_clusters << c_to_s_bits; } /* Validate that a bh contains a valid inode */ int ocfs2_validate_inode_block(struct super_block *sb, struct buffer_head *bh); /* * Read an inode block into *bh. If *bh is NULL, a bh will be allocated. * This is a cached read. The inode will be validated with * ocfs2_validate_inode_block(). */ int ocfs2_read_inode_block(struct inode *inode, struct buffer_head **bh); /* The same, but can be passed OCFS2_BH_* flags */ int ocfs2_read_inode_block_full(struct inode *inode, struct buffer_head **bh, int flags); static inline struct ocfs2_inode_info *cache_info_to_inode(struct ocfs2_caching_info *ci) { return container_of(ci, struct ocfs2_inode_info, ip_metadata_cache); } /* Does this inode have the reflink flag set? */ static inline bool ocfs2_is_refcount_inode(struct inode *inode) { return (OCFS2_I(inode)->ip_dyn_features & OCFS2_HAS_REFCOUNT_FL); } #endif /* OCFS2_INODE_H */
{ "language": "C" }
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2008 Blender Foundation. * All rights reserved. */ /** \file * \ingroup edutil */ #include "MEM_guardedalloc.h" #include "BLI_rect.h" #include "BKE_colortools.h" #include "BKE_context.h" #include "BKE_image.h" #include "BKE_main.h" #include "BKE_screen.h" #include "BKE_sequencer.h" #include "ED_image.h" #include "ED_screen.h" #include "ED_space_api.h" #include "GPU_immediate.h" #include "GPU_state.h" #include "IMB_colormanagement.h" #include "IMB_imbuf.h" #include "IMB_imbuf_types.h" #include "UI_view2d.h" #include "WM_api.h" #include "WM_types.h" #include "sequencer_intern.h" /* Own define. */ #include "ED_util_imbuf.h" /* -------------------------------------------------------------------- */ /** \name Image Pixel Sample Struct (Operator Custom Data) * \{ */ typedef struct ImageSampleInfo { ARegionType *art; void *draw_handle; int x, y; int channels; int width, height; int sample_size; unsigned char col[4]; float colf[4]; float linearcol[4]; int z; float zf; unsigned char *colp; const float *colfp; int *zp; float *zfp; bool draw; bool color_manage; int use_default_view; } ImageSampleInfo; /** \} */ /* -------------------------------------------------------------------- */ /** \name Image Pixel Sample * \{ */ static void image_sample_pixel_color_ubyte(const ImBuf *ibuf, const int coord[2], uchar r_col[4], float r_col_linear[4]) { const uchar *cp = (unsigned char *)(ibuf->rect + coord[1] * ibuf->x + coord[0]); copy_v4_v4_uchar(r_col, cp); rgba_uchar_to_float(r_col_linear, r_col); IMB_colormanagement_colorspace_to_scene_linear_v4(r_col_linear, false, ibuf->rect_colorspace); } static void image_sample_pixel_color_float(ImBuf *ibuf, const int coord[2], float r_col[4]) { const float *cp = ibuf->rect_float + (ibuf->channels) * (coord[1] * ibuf->x + coord[0]); copy_v4_v4(r_col, cp); } /** \} */ /* -------------------------------------------------------------------- */ /** \name Image Pixel Region Sample * \{ */ static void image_sample_rect_color_ubyte(const ImBuf *ibuf, const rcti *rect, uchar r_col[4], float r_col_linear[4]) { uint col_accum_ub[4] = {0, 0, 0, 0}; zero_v4(r_col_linear); int col_tot = 0; int coord[2]; for (coord[0] = rect->xmin; coord[0] <= rect->xmax; coord[0]++) { for (coord[1] = rect->ymin; coord[1] <= rect->ymax; coord[1]++) { float col_temp_fl[4]; uchar col_temp_ub[4]; image_sample_pixel_color_ubyte(ibuf, coord, col_temp_ub, col_temp_fl); add_v4_v4(r_col_linear, col_temp_fl); col_accum_ub[0] += (uint)col_temp_ub[0]; col_accum_ub[1] += (uint)col_temp_ub[1]; col_accum_ub[2] += (uint)col_temp_ub[2]; col_accum_ub[3] += (uint)col_temp_ub[3]; col_tot += 1; } } mul_v4_fl(r_col_linear, 1.0 / (float)col_tot); r_col[0] = MIN2(col_accum_ub[0] / col_tot, 255); r_col[1] = MIN2(col_accum_ub[1] / col_tot, 255); r_col[2] = MIN2(col_accum_ub[2] / col_tot, 255); r_col[3] = MIN2(col_accum_ub[3] / col_tot, 255); } static void image_sample_rect_color_float(ImBuf *ibuf, const rcti *rect, float r_col[4]) { zero_v4(r_col); int col_tot = 0; int coord[2]; for (coord[0] = rect->xmin; coord[0] <= rect->xmax; coord[0]++) { for (coord[1] = rect->ymin; coord[1] <= rect->ymax; coord[1]++) { float col_temp_fl[4]; image_sample_pixel_color_float(ibuf, coord, col_temp_fl); add_v4_v4(r_col, col_temp_fl); col_tot += 1; } } mul_v4_fl(r_col, 1.0 / (float)col_tot); } /** \} */ /* -------------------------------------------------------------------- */ /** \name Image Pixel Sample (Internal Utilities) * \{ */ static void image_sample_apply(bContext *C, wmOperator *op, const wmEvent *event) { SpaceImage *sima = CTX_wm_space_image(C); ARegion *region = CTX_wm_region(C); Image *image = ED_space_image(sima); float uv[2]; UI_view2d_region_to_view(&region->v2d, event->mval[0], event->mval[1], &uv[0], &uv[1]); int tile = BKE_image_get_tile_from_pos(sima->image, uv, uv, NULL); void *lock; ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock, tile); ImageSampleInfo *info = op->customdata; Scene *scene = CTX_data_scene(C); CurveMapping *curve_mapping = scene->view_settings.curve_mapping; if (ibuf == NULL) { ED_space_image_release_buffer(sima, ibuf, lock); info->draw = false; return; } if (uv[0] >= 0.0f && uv[1] >= 0.0f && uv[0] < 1.0f && uv[1] < 1.0f) { int x = (int)(uv[0] * ibuf->x), y = (int)(uv[1] * ibuf->y); CLAMP(x, 0, ibuf->x - 1); CLAMP(y, 0, ibuf->y - 1); info->width = ibuf->x; info->height = ibuf->y; info->x = x; info->y = y; info->draw = true; info->channels = ibuf->channels; info->colp = NULL; info->colfp = NULL; info->zp = NULL; info->zfp = NULL; info->use_default_view = (image->flag & IMA_VIEW_AS_RENDER) ? false : true; rcti sample_rect; sample_rect.xmin = max_ii(0, x - info->sample_size / 2); sample_rect.ymin = max_ii(0, y - info->sample_size / 2); sample_rect.xmax = min_ii(ibuf->x, sample_rect.xmin + info->sample_size) - 1; sample_rect.ymax = min_ii(ibuf->y, sample_rect.ymin + info->sample_size) - 1; if (ibuf->rect) { image_sample_rect_color_ubyte(ibuf, &sample_rect, info->col, info->linearcol); rgba_uchar_to_float(info->colf, info->col); info->colp = info->col; info->colfp = info->colf; info->color_manage = true; } if (ibuf->rect_float) { image_sample_rect_color_float(ibuf, &sample_rect, info->colf); if (ibuf->channels == 4) { /* pass */ } else if (ibuf->channels == 3) { info->colf[3] = 1.0f; } else { info->colf[1] = info->colf[0]; info->colf[2] = info->colf[0]; info->colf[3] = 1.0f; } info->colfp = info->colf; copy_v4_v4(info->linearcol, info->colf); info->color_manage = true; } if (ibuf->zbuf) { /* TODO, blend depth (not urgent). */ info->z = ibuf->zbuf[y * ibuf->x + x]; info->zp = &info->z; if (ibuf->zbuf == (int *)ibuf->rect) { info->colp = NULL; } } if (ibuf->zbuf_float) { /* TODO, blend depth (not urgent). */ info->zf = ibuf->zbuf_float[y * ibuf->x + x]; info->zfp = &info->zf; if (ibuf->zbuf_float == ibuf->rect_float) { info->colfp = NULL; } } if (curve_mapping && ibuf->channels == 4) { /* we reuse this callback for set curves point operators */ if (RNA_struct_find_property(op->ptr, "point")) { int point = RNA_enum_get(op->ptr, "point"); if (point == 1) { BKE_curvemapping_set_black_white(curve_mapping, NULL, info->linearcol); } else if (point == 0) { BKE_curvemapping_set_black_white(curve_mapping, info->linearcol, NULL); } WM_event_add_notifier(C, NC_WINDOW, NULL); } } // XXX node curve integration .. #if 0 { ScrArea *sa, *cur = curarea; node_curvemap_sample(fp); /* sends global to node editor */ for (sa = G.curscreen->areabase.first; sa; sa = sa->next) { if (sa->spacetype == SPACE_NODE) { areawinset(sa->win); scrarea_do_windraw(sa); } } node_curvemap_sample(NULL); /* clears global in node editor */ curarea = cur; } #endif } else { info->draw = 0; } ED_space_image_release_buffer(sima, ibuf, lock); ED_area_tag_redraw(CTX_wm_area(C)); } static void sequencer_sample_apply(bContext *C, wmOperator *op, const wmEvent *event) { Main *bmain = CTX_data_main(C); struct Depsgraph *depsgraph = CTX_data_ensure_evaluated_depsgraph(C); Scene *scene = CTX_data_scene(C); SpaceSeq *sseq = (SpaceSeq *)CTX_wm_space_data(C); ARegion *region = CTX_wm_region(C); ImBuf *ibuf = sequencer_ibuf_get(bmain, region, depsgraph, scene, sseq, CFRA, 0, NULL); ImageSampleInfo *info = op->customdata; float fx, fy; if (ibuf == NULL) { IMB_freeImBuf(ibuf); info->draw = 0; return; } UI_view2d_region_to_view(&region->v2d, event->mval[0], event->mval[1], &fx, &fy); fx /= scene->r.xasp / scene->r.yasp; fx += (float)scene->r.xsch / 2.0f; fy += (float)scene->r.ysch / 2.0f; fx *= (float)ibuf->x / (float)scene->r.xsch; fy *= (float)ibuf->y / (float)scene->r.ysch; if (fx >= 0.0f && fy >= 0.0f && fx < ibuf->x && fy < ibuf->y) { const float *fp; unsigned char *cp; int x = (int)fx, y = (int)fy; info->x = x; info->y = y; info->draw = 1; info->channels = ibuf->channels; info->colp = NULL; info->colfp = NULL; if (ibuf->rect) { cp = (unsigned char *)(ibuf->rect + y * ibuf->x + x); info->col[0] = cp[0]; info->col[1] = cp[1]; info->col[2] = cp[2]; info->col[3] = cp[3]; info->colp = info->col; info->colf[0] = (float)cp[0] / 255.0f; info->colf[1] = (float)cp[1] / 255.0f; info->colf[2] = (float)cp[2] / 255.0f; info->colf[3] = (float)cp[3] / 255.0f; info->colfp = info->colf; copy_v4_v4(info->linearcol, info->colf); IMB_colormanagement_colorspace_to_scene_linear_v4( info->linearcol, false, ibuf->rect_colorspace); info->color_manage = true; } if (ibuf->rect_float) { fp = (ibuf->rect_float + (ibuf->channels) * (y * ibuf->x + x)); info->colf[0] = fp[0]; info->colf[1] = fp[1]; info->colf[2] = fp[2]; info->colf[3] = fp[3]; info->colfp = info->colf; /* sequencer's image buffers are in non-linear space, need to make them linear */ copy_v4_v4(info->linearcol, info->colf); BKE_sequencer_pixel_from_sequencer_space_v4(scene, info->linearcol); info->color_manage = true; } } else { info->draw = 0; } IMB_freeImBuf(ibuf); ED_area_tag_redraw(CTX_wm_area(C)); } static void ed_imbuf_sample_apply(bContext *C, wmOperator *op, const wmEvent *event) { ScrArea *sa = CTX_wm_area(C); if (sa && sa->spacetype == SPACE_IMAGE) { image_sample_apply(C, op, event); } if (sa && sa->spacetype == SPACE_SEQ) { sequencer_sample_apply(C, op, event); } } /** \} */ /* -------------------------------------------------------------------- */ /** \name Image Pixel Sample (Public Operator Callback) * * Callbacks for the sample operator, used by sequencer and image spaces. * \{ */ void ED_imbuf_sample_draw(const bContext *C, ARegion *region, void *arg_info) { ImageSampleInfo *info = arg_info; if (!info->draw) { return; } Scene *scene = CTX_data_scene(C); ED_image_draw_info(scene, region, info->color_manage, info->use_default_view, info->channels, info->x, info->y, info->colp, info->colfp, info->linearcol, info->zp, info->zfp); if (info->sample_size > 1) { ScrArea *sa = CTX_wm_area(C); if (sa && sa->spacetype == SPACE_IMAGE) { const wmWindow *win = CTX_wm_window(C); const wmEvent *event = win->eventstate; SpaceImage *sima = CTX_wm_space_image(C); GPUVertFormat *format = immVertexFormat(); uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); const float color[3] = {1, 1, 1}; immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); immUniformColor3fv(color); /* TODO(campbell): lock to pixels. */ rctf sample_rect_fl; BLI_rctf_init_pt_radius( &sample_rect_fl, (float[2]){event->x - region->winrct.xmin, event->y - region->winrct.ymin}, (float)(info->sample_size / 2.0f) * sima->zoom); GPU_logic_op_xor_set(true); GPU_line_width(1.0f); imm_draw_box_wire_2d(pos, (float)sample_rect_fl.xmin, (float)sample_rect_fl.ymin, (float)sample_rect_fl.xmax, (float)sample_rect_fl.ymax); GPU_logic_op_xor_set(false); immUnbindProgram(); } } } void ED_imbuf_sample_exit(bContext *C, wmOperator *op) { ImageSampleInfo *info = op->customdata; ED_region_draw_cb_exit(info->art, info->draw_handle); ED_area_tag_redraw(CTX_wm_area(C)); MEM_freeN(info); } int ED_imbuf_sample_invoke(bContext *C, wmOperator *op, const wmEvent *event) { ARegion *region = CTX_wm_region(C); ImageSampleInfo *info; info = MEM_callocN(sizeof(ImageSampleInfo), "ImageSampleInfo"); info->art = region->type; info->draw_handle = ED_region_draw_cb_activate( region->type, ED_imbuf_sample_draw, info, REGION_DRAW_POST_PIXEL); info->sample_size = RNA_int_get(op->ptr, "size"); op->customdata = info; ScrArea *sa = CTX_wm_area(C); if (sa && sa->spacetype == SPACE_IMAGE) { SpaceImage *sima = CTX_wm_space_image(C); if (region->regiontype == RGN_TYPE_WINDOW) { if (event->mval[1] <= 16 && ED_space_image_show_cache(sima)) { return OPERATOR_PASS_THROUGH; } } if (!ED_space_image_has_buffer(sima)) { return OPERATOR_CANCELLED; } } ed_imbuf_sample_apply(C, op, event); WM_event_add_modal_handler(C, op); return OPERATOR_RUNNING_MODAL; } int ED_imbuf_sample_modal(bContext *C, wmOperator *op, const wmEvent *event) { switch (event->type) { case LEFTMOUSE: case RIGHTMOUSE: // XXX hardcoded if (event->val == KM_RELEASE) { ED_imbuf_sample_exit(C, op); return OPERATOR_CANCELLED; } break; case MOUSEMOVE: ed_imbuf_sample_apply(C, op, event); break; } return OPERATOR_RUNNING_MODAL; } void ED_imbuf_sample_cancel(bContext *C, wmOperator *op) { ED_imbuf_sample_exit(C, op); } bool ED_imbuf_sample_poll(bContext *C) { ScrArea *sa = CTX_wm_area(C); if (sa && sa->spacetype == SPACE_IMAGE) { SpaceImage *sima = CTX_wm_space_image(C); if (sima == NULL) { return false; } Object *obedit = CTX_data_edit_object(C); if (obedit) { /* Disable when UV editing so it doesn't swallow all click events * (use for setting cursor). */ if (ED_space_image_show_uvedit(sima, obedit)) { return false; } } else if (sima->mode != SI_MODE_VIEW) { return false; } return true; } if (sa && sa->spacetype == SPACE_SEQ) { SpaceSeq *sseq = CTX_wm_space_seq(C); if (sseq->mainb != SEQ_DRAW_IMG_IMBUF) { return false; } return sseq && BKE_sequencer_editing_get(CTX_data_scene(C), false) != NULL; } return false; } /** \} */
{ "language": "C" }
// SPDX-License-Identifier: GPL-2.0+ /* * Copyright (C) 2015 Google, Inc * Written by Simon Glass <sjg@chromium.org> * * This file contains dummy implementations of SCSI functions requried so * that CONFIG_SCSI can be enabled for sandbox. */ #include <common.h> #include <scsi.h> int scsi_bus_reset(struct udevice *dev) { return 0; } void scsi_init(void) { } int scsi_exec(struct udevice *dev, struct scsi_cmd *pccb) { return 0; }
{ "language": "C" }
dnl This file is `m4/all.m4' : m4 macros to autogenerate all_m4.h dnl Tell the user about this. /* This file was automatically generated from `m4/all.m4', do not edit! */ /* * all_m4.h -- internal header file that includes all single libTT object header files * * Copyright (C) 2002 by Massimiliano Ghilardi * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * */ #ifndef _TT_ALL_M4_H #define _TT_ALL_M4_H #ifndef _TT_TT_H #error "Never include <TT/all_m4.h> directly; include <TT/tt.h> instead." #endif divert(-1) include(`m4/TTclasses.m4') divert define(`el', ` typedef struct s_$1 * $1;') TTlist() undefine(`el') define(`el', ` `#'define s_$1 s_$1') TTlist() undefine(`el') /* useful types */ typedef void (*ttlistener_fn)(ttany arg0); typedef void (*ttvisible_repaint_fn)(ttvisible,ttshort,ttshort,ttshort,ttshort); define(`el', ` `#'include <TT/$1.h>') TTlist() undefine(`el') #endif /* _TT_ALL_M4_H */
{ "language": "C" }
/*** This file is part of PulseAudio. Copyright 2004-2006 Lennart Poettering Copyright 2004 Joe Marcus Clarke Copyright 2006-2007 Pierre Ossman <ossman@cendio.se> for Cendio AB PulseAudio 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. PulseAudio 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 Lesser General Public License along with PulseAudio; if not, see <http://www.gnu.org/licenses/>. ***/ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdlib.h> #include <signal.h> #include <errno.h> #include <string.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <sys/stat.h> #ifdef HAVE_SYS_UN_H #include <sys/un.h> #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETINET_IN_SYSTM_H #include <netinet/in_systm.h> #endif #ifdef HAVE_NETINET_IP_H #include <netinet/ip.h> #endif #ifdef HAVE_NETINET_TCP_H #include <netinet/tcp.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_SYSTEMD_DAEMON #include <systemd/sd-daemon.h> #endif #include <pulsecore/core-error.h> #include <pulsecore/core-util.h> #include <pulsecore/log.h> #include <pulsecore/macro.h> #include <pulsecore/socket.h> #include <pulsecore/arpa-inet.h> #include "socket-util.h" void pa_socket_peer_to_string(int fd, char *c, size_t l) { #ifndef OS_IS_WIN32 struct stat st; #endif pa_assert(fd >= 0); pa_assert(c); pa_assert(l > 0); #ifndef OS_IS_WIN32 pa_assert_se(fstat(fd, &st) == 0); if (S_ISSOCK(st.st_mode)) #endif { union { struct sockaddr_storage storage; struct sockaddr sa; struct sockaddr_in in; #ifdef HAVE_IPV6 struct sockaddr_in6 in6; #endif #ifdef HAVE_SYS_UN_H struct sockaddr_un un; #endif } sa; socklen_t sa_len = sizeof(sa); if (getpeername(fd, &sa.sa, &sa_len) >= 0) { if (sa.sa.sa_family == AF_INET) { uint32_t ip = ntohl(sa.in.sin_addr.s_addr); pa_snprintf(c, l, "TCP/IP client from %i.%i.%i.%i:%u", ip >> 24, (ip >> 16) & 0xFF, (ip >> 8) & 0xFF, ip & 0xFF, ntohs(sa.in.sin_port)); return; #ifdef HAVE_IPV6 } else if (sa.sa.sa_family == AF_INET6) { char buf[INET6_ADDRSTRLEN]; const char *res; res = inet_ntop(AF_INET6, &sa.in6.sin6_addr, buf, sizeof(buf)); if (res) { pa_snprintf(c, l, "TCP/IP client from [%s]:%u", buf, ntohs(sa.in6.sin6_port)); return; } #endif #ifdef HAVE_SYS_UN_H } else if (sa.sa.sa_family == AF_UNIX) { pa_snprintf(c, l, "UNIX socket client"); return; #endif } } pa_snprintf(c, l, "Unknown network client"); return; } #ifndef OS_IS_WIN32 else if (S_ISCHR(st.st_mode) && (fd == 0 || fd == 1)) { pa_snprintf(c, l, "STDIN/STDOUT client"); return; } #endif /* OS_IS_WIN32 */ pa_snprintf(c, l, "Unknown client"); } void pa_make_socket_low_delay(int fd) { #ifdef SO_PRIORITY int priority; pa_assert(fd >= 0); priority = 6; if (setsockopt(fd, SOL_SOCKET, SO_PRIORITY, (const void *) &priority, sizeof(priority)) < 0) pa_log_warn("SO_PRIORITY failed: %s", pa_cstrerror(errno)); #endif } void pa_make_tcp_socket_low_delay(int fd) { pa_assert(fd >= 0); pa_make_socket_low_delay(fd); #if defined(SOL_TCP) || defined(IPPROTO_TCP) { int on = 1; #if defined(SOL_TCP) if (setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *) &on, sizeof(on)) < 0) #else if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const void *) &on, sizeof(on)) < 0) #endif pa_log_warn("TCP_NODELAY failed: %s", pa_cstrerror(errno)); } #endif #if defined(IPTOS_LOWDELAY) && defined(IP_TOS) && (defined(SOL_IP) || defined(IPPROTO_IP)) { int tos = IPTOS_LOWDELAY; #ifdef SOL_IP if (setsockopt(fd, SOL_IP, IP_TOS, (const void *) &tos, sizeof(tos)) < 0) #else if (setsockopt(fd, IPPROTO_IP, IP_TOS, (const void *) &tos, sizeof(tos)) < 0) #endif pa_log_warn("IP_TOS failed: %s", pa_cstrerror(errno)); } #endif } void pa_make_udp_socket_low_delay(int fd) { pa_assert(fd >= 0); pa_make_socket_low_delay(fd); #if defined(IPTOS_LOWDELAY) && defined(IP_TOS) && (defined(SOL_IP) || defined(IPPROTO_IP)) { int tos = IPTOS_LOWDELAY; #ifdef SOL_IP if (setsockopt(fd, SOL_IP, IP_TOS, (const void *) &tos, sizeof(tos)) < 0) #else if (setsockopt(fd, IPPROTO_IP, IP_TOS, (const void *) &tos, sizeof(tos)) < 0) #endif pa_log_warn("IP_TOS failed: %s", pa_cstrerror(errno)); } #endif } int pa_socket_set_rcvbuf(int fd, size_t l) { int bufsz = (int) l; pa_assert(fd >= 0); if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (const void *) &bufsz, sizeof(bufsz)) < 0) { pa_log_warn("SO_RCVBUF: %s", pa_cstrerror(errno)); return -1; } return 0; } int pa_socket_set_sndbuf(int fd, size_t l) { int bufsz = (int) l; pa_assert(fd >= 0); if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const void *) &bufsz, sizeof(bufsz)) < 0) { pa_log_warn("SO_SNDBUF: %s", pa_cstrerror(errno)); return -1; } return 0; } #ifdef HAVE_SYS_UN_H int pa_unix_socket_is_stale(const char *fn) { struct sockaddr_un sa; int fd = -1, ret = -1; pa_assert(fn); if ((fd = pa_socket_cloexec(PF_UNIX, SOCK_STREAM, 0)) < 0) { pa_log("socket(): %s", pa_cstrerror(errno)); goto finish; } sa.sun_family = AF_UNIX; strncpy(sa.sun_path, fn, sizeof(sa.sun_path)-1); sa.sun_path[sizeof(sa.sun_path) - 1] = 0; if (connect(fd, (struct sockaddr*) &sa, sizeof(sa)) < 0) { if (errno == ECONNREFUSED) ret = 1; } else ret = 0; finish: if (fd >= 0) pa_close(fd); return ret; } int pa_unix_socket_remove_stale(const char *fn) { int r; pa_assert(fn); #ifdef HAVE_SYSTEMD_DAEMON { int n = sd_listen_fds(0); if (n > 0) { for (int i = 0; i < n; ++i) { if (sd_is_socket_unix(SD_LISTEN_FDS_START + i, SOCK_STREAM, 1, fn, 0) > 0) { /* This is a socket activated socket, therefore do not consider * it stale. */ return 0; } } } } #endif if ((r = pa_unix_socket_is_stale(fn)) < 0) return errno != ENOENT ? -1 : 0; if (!r) return 0; /* Yes, here is a race condition. But who cares? */ if (unlink(fn) < 0) return -1; return 0; } #else /* HAVE_SYS_UN_H */ int pa_unix_socket_is_stale(const char *fn) { return -1; } int pa_unix_socket_remove_stale(const char *fn) { return -1; } #endif /* HAVE_SYS_UN_H */ bool pa_socket_address_is_local(const struct sockaddr *sa) { pa_assert(sa); switch (sa->sa_family) { case AF_UNIX: return true; case AF_INET: return ((const struct sockaddr_in*) sa)->sin_addr.s_addr == INADDR_LOOPBACK; #ifdef HAVE_IPV6 case AF_INET6: return memcmp(&((const struct sockaddr_in6*) sa)->sin6_addr, &in6addr_loopback, sizeof(struct in6_addr)) == 0; #endif default: return false; } } bool pa_socket_is_local(int fd) { union { struct sockaddr_storage storage; struct sockaddr sa; struct sockaddr_in in; #ifdef HAVE_IPV6 struct sockaddr_in6 in6; #endif #ifdef HAVE_SYS_UN_H struct sockaddr_un un; #endif } sa; socklen_t sa_len = sizeof(sa); if (getpeername(fd, &sa.sa, &sa_len) < 0) return false; return pa_socket_address_is_local(&sa.sa); }
{ "language": "C" }
#include <Python.h> #include <stddef.h> /* this block of #ifs should be kept exactly identical between c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py */ #if defined(_MSC_VER) # include <malloc.h> /* for alloca() */ # if _MSC_VER < 1600 /* MSVC < 2010 */ typedef __int8 int8_t; typedef __int16 int16_t; typedef __int32 int32_t; typedef __int64 int64_t; typedef unsigned __int8 uint8_t; typedef unsigned __int16 uint16_t; typedef unsigned __int32 uint32_t; typedef unsigned __int64 uint64_t; typedef __int8 int_least8_t; typedef __int16 int_least16_t; typedef __int32 int_least32_t; typedef __int64 int_least64_t; typedef unsigned __int8 uint_least8_t; typedef unsigned __int16 uint_least16_t; typedef unsigned __int32 uint_least32_t; typedef unsigned __int64 uint_least64_t; typedef __int8 int_fast8_t; typedef __int16 int_fast16_t; typedef __int32 int_fast32_t; typedef __int64 int_fast64_t; typedef unsigned __int8 uint_fast8_t; typedef unsigned __int16 uint_fast16_t; typedef unsigned __int32 uint_fast32_t; typedef unsigned __int64 uint_fast64_t; typedef __int64 intmax_t; typedef unsigned __int64 uintmax_t; # else # include <stdint.h> # endif # if _MSC_VER < 1800 /* MSVC < 2013 */ typedef unsigned char _Bool; # endif #else # include <stdint.h> # if (defined (__SVR4) && defined (__sun)) || defined(_AIX) # include <alloca.h> # endif #endif #if PY_MAJOR_VERSION < 3 # undef PyCapsule_CheckExact # undef PyCapsule_GetPointer # define PyCapsule_CheckExact(capsule) (PyCObject_Check(capsule)) # define PyCapsule_GetPointer(capsule, name) \ (PyCObject_AsVoidPtr(capsule)) #endif #if PY_MAJOR_VERSION >= 3 # define PyInt_FromLong PyLong_FromLong #endif #define _cffi_from_c_double PyFloat_FromDouble #define _cffi_from_c_float PyFloat_FromDouble #define _cffi_from_c_long PyInt_FromLong #define _cffi_from_c_ulong PyLong_FromUnsignedLong #define _cffi_from_c_longlong PyLong_FromLongLong #define _cffi_from_c_ulonglong PyLong_FromUnsignedLongLong #define _cffi_to_c_double PyFloat_AsDouble #define _cffi_to_c_float PyFloat_AsDouble #define _cffi_from_c_int_const(x) \ (((x) > 0) ? \ ((unsigned long long)(x) <= (unsigned long long)LONG_MAX) ? \ PyInt_FromLong((long)(x)) : \ PyLong_FromUnsignedLongLong((unsigned long long)(x)) : \ ((long long)(x) >= (long long)LONG_MIN) ? \ PyInt_FromLong((long)(x)) : \ PyLong_FromLongLong((long long)(x))) #define _cffi_from_c_int(x, type) \ (((type)-1) > 0 ? /* unsigned */ \ (sizeof(type) < sizeof(long) ? \ PyInt_FromLong((long)x) : \ sizeof(type) == sizeof(long) ? \ PyLong_FromUnsignedLong((unsigned long)x) : \ PyLong_FromUnsignedLongLong((unsigned long long)x)) : \ (sizeof(type) <= sizeof(long) ? \ PyInt_FromLong((long)x) : \ PyLong_FromLongLong((long long)x))) #define _cffi_to_c_int(o, type) \ (sizeof(type) == 1 ? (((type)-1) > 0 ? (type)_cffi_to_c_u8(o) \ : (type)_cffi_to_c_i8(o)) : \ sizeof(type) == 2 ? (((type)-1) > 0 ? (type)_cffi_to_c_u16(o) \ : (type)_cffi_to_c_i16(o)) : \ sizeof(type) == 4 ? (((type)-1) > 0 ? (type)_cffi_to_c_u32(o) \ : (type)_cffi_to_c_i32(o)) : \ sizeof(type) == 8 ? (((type)-1) > 0 ? (type)_cffi_to_c_u64(o) \ : (type)_cffi_to_c_i64(o)) : \ (Py_FatalError("unsupported size for type " #type), (type)0)) #define _cffi_to_c_i8 \ ((int(*)(PyObject *))_cffi_exports[1]) #define _cffi_to_c_u8 \ ((int(*)(PyObject *))_cffi_exports[2]) #define _cffi_to_c_i16 \ ((int(*)(PyObject *))_cffi_exports[3]) #define _cffi_to_c_u16 \ ((int(*)(PyObject *))_cffi_exports[4]) #define _cffi_to_c_i32 \ ((int(*)(PyObject *))_cffi_exports[5]) #define _cffi_to_c_u32 \ ((unsigned int(*)(PyObject *))_cffi_exports[6]) #define _cffi_to_c_i64 \ ((long long(*)(PyObject *))_cffi_exports[7]) #define _cffi_to_c_u64 \ ((unsigned long long(*)(PyObject *))_cffi_exports[8]) #define _cffi_to_c_char \ ((int(*)(PyObject *))_cffi_exports[9]) #define _cffi_from_c_pointer \ ((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[10]) #define _cffi_to_c_pointer \ ((char *(*)(PyObject *, CTypeDescrObject *))_cffi_exports[11]) #define _cffi_get_struct_layout \ ((PyObject *(*)(Py_ssize_t[]))_cffi_exports[12]) #define _cffi_restore_errno \ ((void(*)(void))_cffi_exports[13]) #define _cffi_save_errno \ ((void(*)(void))_cffi_exports[14]) #define _cffi_from_c_char \ ((PyObject *(*)(char))_cffi_exports[15]) #define _cffi_from_c_deref \ ((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[16]) #define _cffi_to_c \ ((int(*)(char *, CTypeDescrObject *, PyObject *))_cffi_exports[17]) #define _cffi_from_c_struct \ ((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[18]) #define _cffi_to_c_wchar_t \ ((wchar_t(*)(PyObject *))_cffi_exports[19]) #define _cffi_from_c_wchar_t \ ((PyObject *(*)(wchar_t))_cffi_exports[20]) #define _cffi_to_c_long_double \ ((long double(*)(PyObject *))_cffi_exports[21]) #define _cffi_to_c__Bool \ ((_Bool(*)(PyObject *))_cffi_exports[22]) #define _cffi_prepare_pointer_call_argument \ ((Py_ssize_t(*)(CTypeDescrObject *, PyObject *, char **))_cffi_exports[23]) #define _cffi_convert_array_from_object \ ((int(*)(char *, CTypeDescrObject *, PyObject *))_cffi_exports[24]) #define _CFFI_NUM_EXPORTS 25 typedef struct _ctypedescr CTypeDescrObject; static void *_cffi_exports[_CFFI_NUM_EXPORTS]; static PyObject *_cffi_types, *_cffi_VerificationError; static int _cffi_setup_custom(PyObject *lib); /* forward */ static PyObject *_cffi_setup(PyObject *self, PyObject *args) { PyObject *library; int was_alive = (_cffi_types != NULL); (void)self; /* unused */ if (!PyArg_ParseTuple(args, "OOO", &_cffi_types, &_cffi_VerificationError, &library)) return NULL; Py_INCREF(_cffi_types); Py_INCREF(_cffi_VerificationError); if (_cffi_setup_custom(library) < 0) return NULL; return PyBool_FromLong(was_alive); } static int _cffi_init(void) { PyObject *module, *c_api_object = NULL; module = PyImport_ImportModule("_cffi_backend"); if (module == NULL) goto failure; c_api_object = PyObject_GetAttrString(module, "_C_API"); if (c_api_object == NULL) goto failure; if (!PyCapsule_CheckExact(c_api_object)) { PyErr_SetNone(PyExc_ImportError); goto failure; } memcpy(_cffi_exports, PyCapsule_GetPointer(c_api_object, "cffi"), _CFFI_NUM_EXPORTS * sizeof(void *)); Py_DECREF(module); Py_DECREF(c_api_object); return 0; failure: Py_XDECREF(module); Py_XDECREF(c_api_object); return -1; } #define _cffi_type(num) ((CTypeDescrObject *)PyList_GET_ITEM(_cffi_types, num)) /**********/ // This file is dual licensed under the terms of the Apache License, Version // 2.0, and the BSD License. See the LICENSE file in the root of this // repository for complete details. uint8_t Cryptography_constant_time_bytes_eq(uint8_t *a, size_t len_a, uint8_t *b, size_t len_b) { size_t i = 0; uint8_t mismatch = 0; if (len_a != len_b) { return 0; } for (i = 0; i < len_a; i++) { mismatch |= a[i] ^ b[i]; } /* Make sure any bits set are copied to the lowest bit */ mismatch |= mismatch >> 4; mismatch |= mismatch >> 2; mismatch |= mismatch >> 1; /* Now check the low bit to see if it's set */ return (mismatch & 1) == 0; } static PyObject * _cffi_f_Cryptography_constant_time_bytes_eq(PyObject *self, PyObject *args) { uint8_t * x0; size_t x1; uint8_t * x2; size_t x3; Py_ssize_t datasize; uint8_t result; PyObject *arg0; PyObject *arg1; PyObject *arg2; PyObject *arg3; if (!PyArg_ParseTuple(args, "OOOO:Cryptography_constant_time_bytes_eq", &arg0, &arg1, &arg2, &arg3)) return NULL; datasize = _cffi_prepare_pointer_call_argument( _cffi_type(0), arg0, (char **)&x0); if (datasize != 0) { if (datasize < 0) return NULL; x0 = alloca((size_t)datasize); memset((void *)x0, 0, (size_t)datasize); if (_cffi_convert_array_from_object((char *)x0, _cffi_type(0), arg0) < 0) return NULL; } x1 = _cffi_to_c_int(arg1, size_t); if (x1 == (size_t)-1 && PyErr_Occurred()) return NULL; datasize = _cffi_prepare_pointer_call_argument( _cffi_type(0), arg2, (char **)&x2); if (datasize != 0) { if (datasize < 0) return NULL; x2 = alloca((size_t)datasize); memset((void *)x2, 0, (size_t)datasize); if (_cffi_convert_array_from_object((char *)x2, _cffi_type(0), arg2) < 0) return NULL; } x3 = _cffi_to_c_int(arg3, size_t); if (x3 == (size_t)-1 && PyErr_Occurred()) return NULL; Py_BEGIN_ALLOW_THREADS _cffi_restore_errno(); { result = Cryptography_constant_time_bytes_eq(x0, x1, x2, x3); } _cffi_save_errno(); Py_END_ALLOW_THREADS (void)self; /* unused */ return _cffi_from_c_int(result, uint8_t); } static int _cffi_setup_custom(PyObject *lib) { return ((void)lib,0); } static PyMethodDef _cffi_methods[] = { {"Cryptography_constant_time_bytes_eq", _cffi_f_Cryptography_constant_time_bytes_eq, METH_VARARGS, NULL}, {"_cffi_setup", _cffi_setup, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL} /* Sentinel */ }; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef _cffi_module_def = { PyModuleDef_HEAD_INIT, "_Cryptography_cffi_590da19fxffc7b1ce", NULL, -1, _cffi_methods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit__Cryptography_cffi_590da19fxffc7b1ce(void) { PyObject *lib; lib = PyModule_Create(&_cffi_module_def); if (lib == NULL) return NULL; if (((void)lib,0) < 0 || _cffi_init() < 0) { Py_DECREF(lib); return NULL; } return lib; } #else PyMODINIT_FUNC init_Cryptography_cffi_590da19fxffc7b1ce(void) { PyObject *lib; lib = Py_InitModule("_Cryptography_cffi_590da19fxffc7b1ce", _cffi_methods); if (lib == NULL) return; if (((void)lib,0) < 0 || _cffi_init() < 0) return; return; } #endif
{ "language": "C" }
/* * * Copyright 2015 gRPC authors. * * 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. * */ #ifndef GRPC_CORE_LIB_IOMGR_IOMGR_INTERNAL_H #define GRPC_CORE_LIB_IOMGR_IOMGR_INTERNAL_H #include <stdbool.h> #include "src/core/lib/iomgr/iomgr.h" typedef struct grpc_iomgr_object { char *name; struct grpc_iomgr_object *next; struct grpc_iomgr_object *prev; } grpc_iomgr_object; void grpc_iomgr_register_object(grpc_iomgr_object *obj, const char *name); void grpc_iomgr_unregister_object(grpc_iomgr_object *obj); void grpc_iomgr_platform_init(void); /** flush any globally queued work from iomgr */ void grpc_iomgr_platform_flush(void); /** tear down all platform specific global iomgr structures */ void grpc_iomgr_platform_shutdown(void); bool grpc_iomgr_abort_on_leaks(void); #endif /* GRPC_CORE_LIB_IOMGR_IOMGR_INTERNAL_H */
{ "language": "C" }