filename
stringlengths
3
9
code
stringlengths
4
1.05M
366115.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "module.h" #include "connection_manager.h" #include "addr_proxy.h" #include "edge_mgmt.h" #include "link_route_proxy.h" typedef struct { qdr_core_t *core; qcm_edge_conn_mgr_t *conn_mgr; qcm_edge_addr_proxy_t *addr_proxy; // TODO - Add pointers to other edge-router state here } qcm_edge_t; static bool qcm_edge_router_enable_CT(qdr_core_t *core) { return core->router_mode == QD_ROUTER_MODE_EDGE; } static void qcm_edge_router_init_CT(qdr_core_t *core, void **module_context) { qcm_edge_t *edge = NEW(qcm_edge_t); edge->core = core; edge->conn_mgr = qcm_edge_conn_mgr(core); edge->addr_proxy = qcm_edge_addr_proxy(core); qcm_edge_mgmt_init_CT(core); qcm_edge_link_route_init_CT(core); // TODO - Add initialization of other edge-router functions here *module_context = edge; } static void qcm_edge_router_final_CT(void *module_context) { qcm_edge_t *edge = (qcm_edge_t*) module_context; qcm_edge_conn_mgr_final(edge->conn_mgr); qcm_edge_addr_proxy_final(edge->addr_proxy); qcm_edge_mgmt_final_CT(edge->core); qcm_edge_link_route_final_CT(edge->core); // TODO - Add finalization of other edge-router functions here free(edge); } QDR_CORE_MODULE_DECLARE("edge_router", qcm_edge_router_enable_CT, qcm_edge_router_init_CT, qcm_edge_router_final_CT)
832013.c
/**************************************************************************** * arch/xtensa/src/esp32/esp32_serial.c * * Copyright (C) 2016-2017, 2019 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <sys/types.h> #include <stdint.h> #include <stdbool.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <debug.h> #ifdef CONFIG_SERIAL_TERMIOS # include <termios.h> #endif #include <nuttx/irq.h> #include <nuttx/arch.h> #include <nuttx/fs/ioctl.h> #include <nuttx/serial/serial.h> #include <arch/board/board.h> #include "xtensa.h" #include "hardware/esp32_soc.h" #include "hardware/esp32_iomux.h" #include "hardware/esp32_gpio_sigmap.h" #include "hardware/esp32_uart.h" #include "rom/esp32_gpio.h" #include "esp32_config.h" #include "esp32_gpio.h" #include "esp32_cpuint.h" /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ #ifdef USE_SERIALDRIVER /* Which UART with be tty0/console and which tty1-2? */ /* First pick the console and ttys0. This could be any of UART0-5 */ #if defined(CONFIG_UART0_SERIAL_CONSOLE) # define CONSOLE_DEV g_uart0port /* UART0 is console */ # define TTYS0_DEV g_uart0port /* UART0 is ttyS0 */ # define UART0_ASSIGNED 1 #elif defined(CONFIG_UART1_SERIAL_CONSOLE) # define CONSOLE_DEV g_uart1port /* UART1 is console */ # define TTYS0_DEV g_uart1port /* UART1 is ttyS0 */ # define UART1_ASSIGNED 1 #elif defined(CONFIG_UART2_SERIAL_CONSOLE) # define CONSOLE_DEV g_uart2port /* UART2 is console */ # define TTYS0_DEV g_uart2port /* UART2 is ttyS0 */ # define UART2_ASSIGNED 1 #else # undef CONSOLE_DEV /* No console */ # if defined(CONFIG_ESP32_UART0) # define TTYS0_DEV g_uart0port /* UART0 is ttyS0 */ # define UART0_ASSIGNED 1 # elif defined(CONFIG_ESP32_UART1) # define TTYS0_DEV g_uart1port /* UART1 is ttyS0 */ # define UART1_ASSIGNED 1 # elif defined(CONFIG_ESP32_UART2) # define TTYS0_DEV g_uart2port /* UART2 is ttyS0 */ # define UART2_ASSIGNED 1 # endif #endif /* Pick ttys1. This could be any of UART0-2 excluding the console * UART. */ #if defined(CONFIG_ESP32_UART0) && !defined(UART0_ASSIGNED) # define TTYS1_DEV g_uart0port /* UART0 is ttyS1 */ # define UART0_ASSIGNED 1 #elif defined(CONFIG_ESP32_UART1) && !defined(UART1_ASSIGNED) # define TTYS1_DEV g_uart1port /* UART1 is ttyS1 */ # define UART1_ASSIGNED 1 #elif defined(CONFIG_ESP32_UART2) && !defined(UART2_ASSIGNED) # define TTYS1_DEV g_uart2port /* UART2 is ttyS1 */ # define UART2_ASSIGNED 1 #endif /* Pick ttys2. This could be one of UART1-2. It can't be UART0 * because that was either assigned as ttyS0 or ttys1. One of these * could also be the console. */ #if defined(CONFIG_ESP32_UART1) && !defined(UART1_ASSIGNED) # define TTYS2_DEV g_uart1port /* UART1 is ttyS2 */ # define UART1_ASSIGNED 1 #elif defined(CONFIG_ESP32_UART2) && !defined(UART2_ASSIGNED) # define TTYS2_DEV g_uart2port /* UART2 is ttyS2 */ # define UART2_ASSIGNED 1 #endif /* UART source clock for BAUD generation */ #define UART_CLK_FREQ APB_CLK_FREQ /**************************************************************************** * Private Types ****************************************************************************/ /* Constant properties of the UART. Other configuration setting may be * changeable via Termios IOCTL calls. */ struct esp32_config_s { const uint32_t uartbase; /* Base address of UART registers */ uint8_t periph; /* UART peripheral ID */ uint8_t irq; /* IRQ number assigned to the peripheral */ uint8_t txpin; /* Tx pin number (0-39) */ uint8_t rxpin; /* Rx pin number (0-39) */ uint8_t txsig; /* Tx signal */ uint8_t rxsig; /* Rx signal */ #if defined(CONFIG_SERIAL_IFLOWCONTROL) || defined(CONFIG_SERIAL_OFLOWCONTROL) uint8_t rtspin; /* RTS pin number (0-39) */ uint8_t ctspin; /* CTS pin number (0-39) */ uint8_t rtssig; /* RTS signal */ uint8_t ctssig; /* CTS signal */ #endif }; /* Current state of the UART */ struct esp32_dev_s { const struct esp32_config_s *config; /* Constant configuration */ uint32_t baud; /* Configured baud */ uint32_t status; /* Saved status bits */ int cpuint; /* CPU interrupt assigned to this UART */ uint8_t parity; /* 0=none, 1=odd, 2=even */ uint8_t bits; /* Number of bits (5-9) */ bool stopbits2; /* true: Configure with 2 stop bits instead of 1 */ #if defined(CONFIG_SERIAL_IFLOWCONTROL) || defined(CONFIG_SERIAL_OFLOWCONTROL) bool flowc; /* Input flow control (RTS) enabled */ #endif }; /**************************************************************************** * Private Function Prototypes ****************************************************************************/ static int esp32_setup(struct uart_dev_s *dev); static void esp32_shutdown(struct uart_dev_s *dev); static int esp32_attach(struct uart_dev_s *dev); static void esp32_detach(struct uart_dev_s *dev); static int esp32_interrupt(int cpuint, void *context, FAR void *arg); static int esp32_ioctl(struct file *filep, int cmd, unsigned long arg); static int esp32_receive(struct uart_dev_s *dev, unsigned int *status); static void esp32_rxint(struct uart_dev_s *dev, bool enable); static bool esp32_rxavailable(struct uart_dev_s *dev); static void esp32_send(struct uart_dev_s *dev, int ch); static void esp32_txint(struct uart_dev_s *dev, bool enable); static bool esp32_txready(struct uart_dev_s *dev); static bool esp32_txempty(struct uart_dev_s *dev); /**************************************************************************** * Private Data ****************************************************************************/ static const struct uart_ops_s g_uart_ops = { .setup = esp32_setup, .shutdown = esp32_shutdown, .attach = esp32_attach, .detach = esp32_detach, .ioctl = esp32_ioctl, .receive = esp32_receive, .rxint = esp32_rxint, .rxavailable = esp32_rxavailable, #ifdef CONFIG_SERIAL_IFLOWCONTROL .rxflowcontrol = NULL, #endif .send = esp32_send, .txint = esp32_txint, .txready = esp32_txready, .txempty = esp32_txempty, }; /* I/O buffers */ #ifdef CONFIG_ESP32_UART0 static char g_uart0rxbuffer[CONFIG_UART0_RXBUFSIZE]; static char g_uart0txbuffer[CONFIG_UART0_TXBUFSIZE]; #endif #ifdef CONFIG_ESP32_UART1 static char g_uart1rxbuffer[CONFIG_UART1_RXBUFSIZE]; static char g_uart1txbuffer[CONFIG_UART1_TXBUFSIZE]; #endif #ifdef CONFIG_ESP32_UART2 static char g_uart2rxbuffer[CONFIG_UART2_RXBUFSIZE]; static char g_uart2txbuffer[CONFIG_UART2_TXBUFSIZE]; #endif /* This describes the state of the UART0 port. */ #ifdef CONFIG_ESP32_UART0 static const struct esp32_config_s g_uart0config = { .uartbase = DR_REG_UART_BASE, .periph = ESP32_PERIPH_UART, .irq = ESP32_IRQ_UART, .txpin = CONFIG_ESP32_UART0_TXPIN, .rxpin = CONFIG_ESP32_UART0_RXPIN, .txsig = U0TXD_OUT_IDX, .rxsig = U0RXD_IN_IDX, #if defined(CONFIG_SERIAL_IFLOWCONTROL) || defined(CONFIG_SERIAL_OFLOWCONTROL) .rtspin = CONFIG_ESP32_UART0_RTSPIN, .ctspin = CONFIG_ESP32_UART0_CTSPIN, .rtssig = U0RTS_OUT_IDX, .ctssig = U0CTS_IN_IDX, #endif }; static struct esp32_dev_s g_uart0priv = { .config = &g_uart0config, .baud = CONFIG_UART0_BAUD, .parity = CONFIG_UART0_PARITY, .bits = CONFIG_UART0_BITS, .stopbits2 = CONFIG_UART0_2STOP, }; static uart_dev_t g_uart0port = { .recv = { .size = CONFIG_UART0_RXBUFSIZE, .buffer = g_uart0rxbuffer, }, .xmit = { .size = CONFIG_UART0_TXBUFSIZE, .buffer = g_uart0txbuffer, }, .ops = &g_uart_ops, .priv = &g_uart0priv, }; #endif /* This describes the state of the UART1 port. */ #ifdef CONFIG_ESP32_UART1 static const struct esp32_config_s g_uart1config = { .uartbase = DR_REG_UART1_BASE, .periph = ESP32_PERIPH_UART1, .irq = ESP32_IRQ_UART1, .txpin = CONFIG_ESP32_UART1_TXPIN, .rxpin = CONFIG_ESP32_UART1_RXPIN, .txsig = U1TXD_OUT_IDX, .rxsig = U1RXD_IN_IDX, #if defined(CONFIG_SERIAL_IFLOWCONTROL) || defined(CONFIG_SERIAL_OFLOWCONTROL) .rtspin = CONFIG_ESP32_UART1_RTSPIN, .ctspin = CONFIG_ESP32_UART1_CTSPIN, .rtssig = U1RTS_OUT_IDX, .ctssig = U1CTS_IN_IDX, #endif }; static struct esp32_dev_s g_uart1priv = { .config = &g_uart1config, .baud = CONFIG_UART1_BAUD, .parity = CONFIG_UART1_PARITY, .bits = CONFIG_UART1_BITS, .stopbits2 = CONFIG_UART1_2STOP, }; static uart_dev_t g_uart1port = { .recv = { .size = CONFIG_UART1_RXBUFSIZE, .buffer = g_uart1rxbuffer, }, .xmit = { .size = CONFIG_UART1_TXBUFSIZE, .buffer = g_uart1txbuffer, }, .ops = &g_uart_ops, .priv = &g_uart1priv, }; #endif /* This describes the state of the UART2 port. */ #ifdef CONFIG_ESP32_UART2 static const struct esp32_config_s g_uart2config = { .uartbase = DR_REG_UART2_BASE, .periph = ESP32_PERIPH_UART2, .irq = ESP32_IRQ_UART2, .txpin = CONFIG_ESP32_UART2_TXPIN, .rxpin = CONFIG_ESP32_UART2_RXPIN, .txsig = U2TXD_OUT_IDX, .rxsig = U2RXD_IN_IDX, #if defined(CONFIG_SERIAL_IFLOWCONTROL) || defined(CONFIG_SERIAL_OFLOWCONTROL) .rtspin = CONFIG_ESP32_UART2_RTSPIN, .ctspin = CONFIG_ESP32_UART2_CTSPIN, .rtssig = U2RTS_OUT_IDX, .ctssig = U2CTS_IN_IDX, #endif }; static struct esp32_dev_s g_uart2priv = { .config = &g_uart2config, .baud = CONFIG_UART2_BAUD, .parity = CONFIG_UART2_PARITY, .bits = CONFIG_UART2_BITS, .stopbits2 = CONFIG_UART2_2STOP, }; static uart_dev_t g_uart2port = { .recv = { .size = CONFIG_UART2_RXBUFSIZE, .buffer = g_uart2rxbuffer, }, .xmit = { .size = CONFIG_UART2_TXBUFSIZE, .buffer = g_uart2txbuffer, }, .ops = &g_uart_ops, .priv = &g_uart2priv, }; #endif /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: esp32_serialin ****************************************************************************/ static inline uint32_t esp32_serialin(struct esp32_dev_s *priv, int offset) { return getreg32(priv->config->uartbase + offset); } /**************************************************************************** * Name: esp32_serialout ****************************************************************************/ static inline void esp32_serialout(struct esp32_dev_s *priv, int offset, uint32_t value) { putreg32(value, priv->config->uartbase + offset); } /**************************************************************************** * Name: esp32_restoreuartint ****************************************************************************/ static inline void esp32_restoreuartint(struct esp32_dev_s *priv, uint32_t intena) { /* Restore the previous interrupt state * (assuming all interrupts disabled) */ esp32_serialout(priv, UART_INT_ENA_OFFSET, intena); } /**************************************************************************** * Name: esp32_disableallints ****************************************************************************/ static void esp32_disableallints(struct esp32_dev_s *priv, uint32_t *intena) { irqstate_t flags; /* The following must be atomic */ flags = enter_critical_section(); if (intena) { /* Return the current interrupt mask */ *intena = esp32_serialin(priv, UART_INT_ENA_OFFSET); } /* Disable all interrupts */ esp32_serialout(priv, UART_INT_ENA_OFFSET, 0); leave_critical_section(flags); } /**************************************************************************** * Name: esp32_setup * * Description: * Configure the UART baud, bits, parity, etc. This method is called the * first time that the serial port is opened. * ****************************************************************************/ static int esp32_setup(struct uart_dev_s *dev) { #ifndef CONFIG_SUPPRESS_UART_CONFIG struct esp32_dev_s *priv = (struct esp32_dev_s *)dev->priv; uint32_t clkdiv; uint32_t regval; uint32_t conf0; /* Note: The logic here depends on the fact that that the UART module * was enabled and the pins were configured in esp32_lowsetup(). */ /* The shutdown method will put the UART in a known, disabled state */ esp32_shutdown(dev); /* Set up the CONF0 register. */ conf0 = UART_TICK_REF_ALWAYS_ON; #if defined(CONFIG_SERIAL_IFLOWCONTROL) || defined(CONFIG_SERIAL_OFLOWCONTROL) /* Check if flow control is enabled */ if (priv->flowc) { /* Enable hardware flow control */ conf0 |= UART_TX_FLOW_EN; } #endif /* OR in settings for the selected number of bits */ if (priv->bits == 5) { /* 0=5 bits */ } else if (priv->bits == 6) { conf0 |= (1 << UART_BIT_NUM_S); /* 1=6 bits */ } else if (priv->bits == 7) { conf0 |= (2 << UART_BIT_NUM_S); /* 2=7 bits */ } else /* if (priv->bits == 8) */ { conf0 |= (3 << UART_BIT_NUM_S); /* 3=8 bits */ } /* OR in settings for the selected parity */ if (priv->parity == 1) { conf0 |= UART_PARITY_EN; } else if (priv->parity == 2) { conf0 |= UART_PARITY_EN | UART_PARITY; } /* OR in settings for the number of stop bits */ if (priv->stopbits2) { conf0 |= 2 << UART_STOP_BIT_NUM_S; } else { conf0 |= 1 << UART_STOP_BIT_NUM_S; } /* Configure the UART BAUD */ clkdiv = (UART_CLK_FREQ << 4) / priv->baud; regval = (clkdiv >> 4) << UART_CLKDIV_S; regval |= (clkdiv & 15) << UART_CLKDIV_FRAG_S; esp32_serialout(priv, UART_CLKDIV_OFFSET, regval); /* Configure UART pins * * Internal signals can be output to multiple GPIO pads. * But only one GPIO pad can connect with input signal */ esp32_configgpio(priv->config->txpin, OUTPUT_FUNCTION_2); gpio_matrix_out(priv->config->txpin, priv->config->txsig, 0, 0); esp32_configgpio(priv->config->rxpin, INPUT_FUNCTION_2); gpio_matrix_in(priv->config->rxpin, priv->config->rxsig, 0); #if defined(CONFIG_SERIAL_IFLOWCONTROL) || defined(CONFIG_SERIAL_OFLOWCONTROL) esp32_configgpio(priv->config->rtspin, OUTPUT_FUNCTION_2); gpio_matrix_out(priv->config->rtspin, priv->config->rtssig, 0, 0); esp32_configgpio(priv->config->ctspin, INPUT_FUNCTION_2); gpio_matrix_in(priv->config->ctspin, priv->config->ctssig, 0); #endif /* Enable RX and error interrupts. Clear and pending interrtupt */ regval = UART_RXFIFO_FULL_INT_ENA | UART_FRM_ERR_INT_ENA | UART_RXFIFO_TOUT_INT_ENA; esp32_serialout(priv, UART_INT_ENA_OFFSET, regval); esp32_serialout(priv, UART_INT_CLR_OFFSET, 0xffffffff); /* Configure and enable the UART */ esp32_serialout(priv, UART_CONF0_OFFSET, conf0); regval = (112 << UART_RXFIFO_FULL_THRHD_S) | (0x02 << UART_RX_TOUT_THRHD_S) | UART_RX_TOUT_EN; esp32_serialout(priv, UART_CONF1_OFFSET, regval); #endif return OK; } /**************************************************************************** * Name: esp32_shutdown * * Description: * Disable the UART. This method is called when the serial port is * closed. It is assumed that esp32_detach was called earlier in the * shutdown sequence. * ****************************************************************************/ static void esp32_shutdown(struct uart_dev_s *dev) { struct esp32_dev_s *priv = (struct esp32_dev_s *)dev->priv; uint32_t status; /* Wait for outgoing FIFO to clear. The ROM bootloader does not flush * the FIFO before handing over to user code, so some of this output is * not currently seen when the UART is reconfigured in early stages of * startup. */ do { status = esp32_serialin(priv, UART_STATUS_OFFSET); } while ((status & UART_TXFIFO_CNT_M) != 0); /* Disable all UART interrupts */ esp32_disableallints(priv, NULL); /* Revert pins to inputs and detach UART signals */ esp32_configgpio(priv->config->txpin, INPUT); gpio_matrix_out(priv->config->txsig, MATRIX_DETACH_OUT_SIG, true, false); esp32_configgpio(priv->config->rxpin, INPUT); gpio_matrix_in(priv->config->rxsig, MATRIX_DETACH_IN_LOW_PIN, false); #if defined(CONFIG_SERIAL_IFLOWCONTROL) || defined(CONFIG_SERIAL_OFLOWCONTROL) esp32_configgpio(priv->config->rtspin, INPUT); gpio_matrix_out(priv->config->rtssig, MATRIX_DETACH_OUT_SIG, true, false); esp32_configgpio(priv->config->ctspin, INPUT); gpio_matrix_in(priv->config->ctssig, MATRIX_DETACH_IN_LOW_PIN, false); #endif /* Unconfigure and disable the UART */ esp32_serialout(priv, UART_CONF0_OFFSET, 0); esp32_serialout(priv, UART_CONF1_OFFSET, 0); esp32_serialout(priv, UART_INT_ENA_OFFSET, 0); esp32_serialout(priv, UART_INT_CLR_OFFSET, 0xffffffff); } /**************************************************************************** * Name: esp32_attach * * Description: * Configure the UART to operation in interrupt driven mode. This method * is called when the serial port is opened. Normally, this is just after * the the setup() method is called, however, the serial console may * operate in a non-interrupt driven mode during the boot phase. * * RX and TX interrupts are not enabled when by the attach method (unless * the hardware supports multiple levels of interrupt enabling). The RX * and TX interrupts are not enabled until the txint() and rxint() methods * are called. * ****************************************************************************/ static int esp32_attach(struct uart_dev_s *dev) { struct esp32_dev_s *priv = (struct esp32_dev_s *)dev->priv; int cpu; int ret = OK; /* Allocate a level-sensitive, priority 1 CPU interrupt for the UART */ priv->cpuint = esp32_alloc_levelint(1); if (priv->cpuint < 0) { /* Failed to allocate a CPU interrupt of this type */ return priv->cpuint; } /* Set up to receive peripheral interrupts on the current CPU */ #ifdef CONFIG_SMP cpu = up_cpu_index(); #else cpu = 0; #endif /* Attach the GPIO peripheral to the allocated CPU interrupt */ up_disable_irq(priv->cpuint); esp32_attach_peripheral(cpu, priv->config->periph, priv->cpuint); /* Attach and enable the IRQ */ ret = irq_attach(priv->config->irq, esp32_interrupt, dev); if (ret == OK) { /* Enable the CPU interrupt (RX and TX interrupts are still disabled * in the UART */ up_enable_irq(priv->cpuint); } return ret; } /**************************************************************************** * Name: esp32_detach * * Description: * Detach UART interrupts. This method is called when the serial port is * closed normally just before the shutdown method is called. The * exception is the serial console which is never shutdown. * ****************************************************************************/ static void esp32_detach(struct uart_dev_s *dev) { struct esp32_dev_s *priv = (struct esp32_dev_s *)dev->priv; int cpu; /* Disable and detach the CPU interrupt */ up_disable_irq(priv->cpuint); irq_detach(priv->config->irq); /* Disassociate the peripheral interrupt from the CPU interrupt */ #ifdef CONFIG_SMP cpu = up_cpu_index(); #else cpu = 0; #endif esp32_detach_peripheral(cpu, priv->config->periph, priv->cpuint); /* And release the CPU interrupt */ esp32_free_cpuint(priv->cpuint); priv->cpuint = -1; } /**************************************************************************** * Name: esp32_interrupt * * Description: * This is the common UART interrupt handler. It will be invoked * when an interrupt received on the device. It should call * uart_transmitchars or uart_receivechar to perform the appropriate data * transfers. * ****************************************************************************/ static int esp32_interrupt(int cpuint, void *context, FAR void *arg) { struct uart_dev_s *dev = (struct uart_dev_s *)arg; struct esp32_dev_s *priv; uint32_t regval; uint32_t status; uint32_t enabled; unsigned int nfifo; int passes; bool handled; DEBUGASSERT(dev != NULL && dev->priv != NULL); priv = (struct esp32_dev_s *)dev->priv; /* Loop until there are no characters to be transferred or, until we have * been looping for a long time. */ handled = true; for (passes = 0; passes < 256 && handled; passes++) { handled = false; priv->status = esp32_serialin(priv, UART_INT_RAW_OFFSET); status = esp32_serialin(priv, UART_STATUS_OFFSET); enabled = esp32_serialin(priv, UART_INT_ENA_OFFSET); /* Clear pending interrupts */ regval = (UART_RXFIFO_FULL_INT_CLR | UART_FRM_ERR_INT_CLR | UART_RXFIFO_TOUT_INT_CLR | UART_TX_DONE_INT_CLR | UART_TXFIFO_EMPTY_INT_CLR); esp32_serialout(priv, UART_INT_CLR_OFFSET, regval); /* Are Rx interrupts enabled? The upper layer may hold off Rx input * by disabling the Rx interrupts if there is no place to saved the * data, possibly resulting in an overrun error. */ if ((enabled & (UART_RXFIFO_FULL_INT_ENA | UART_RXFIFO_TOUT_INT_ENA)) != 0) { /* Is there any data waiting in the Rx FIFO? */ nfifo = (status & UART_RXFIFO_CNT_M) >> UART_RXFIFO_CNT_S; if (nfifo > 0) { /* Received data in the RXFIFO! ... Process incoming bytes */ uart_recvchars(dev); handled = true; } } /* Are Tx interrupts enabled? The upper layer will disable Tx * interrupts when it has nothing to send. */ if ((enabled & (UART_TX_DONE_INT_ENA | UART_TXFIFO_EMPTY_INT_ENA)) != 0) { nfifo = (status & UART_TXFIFO_CNT_M) >> UART_TXFIFO_CNT_S; if (nfifo < 0x7f) { /* The TXFIFO is not full ... process outgoing bytes */ uart_xmitchars(dev); handled = true; } } } return OK; } /**************************************************************************** * Name: esp32_ioctl * * Description: * All ioctl calls will be routed through this method * ****************************************************************************/ static int esp32_ioctl(struct file *filep, int cmd, unsigned long arg) { #if defined(CONFIG_SERIAL_TERMIOS) || defined(CONFIG_SERIAL_TIOCSERGSTRUCT) struct inode *inode = filep->f_inode; struct uart_dev_s *dev = inode->i_private; #endif int ret = OK; switch (cmd) { #ifdef CONFIG_SERIAL_TIOCSERGSTRUCT case TIOCSERGSTRUCT: { struct esp32_dev_s *user = (struct esp32_dev_s *)arg; if (!user) { ret = -EINVAL; } else { memcpy(user, dev, sizeof(struct esp32_dev_s)); } } break; #endif #ifdef CONFIG_SERIAL_TERMIOS case TCGETS: { struct termios *termiosp = (struct termios *)arg; struct esp32_dev_s *priv = (struct esp32_dev_s *)dev->priv; if (!termiosp) { ret = -EINVAL; break; } /* Return parity */ termiosp->c_cflag = ((priv->parity != 0) ? PARENB : 0) | ((priv->parity == 1) ? PARODD : 0); /* Return stop bits */ termiosp->c_cflag |= (priv->stopbits2) ? CSTOPB : 0; /* Return flow control */ #if defined(CONFIG_SERIAL_IFLOWCONTROL) || defined(CONFIG_SERIAL_OFLOWCONTROL) termiosp->c_cflag |= (priv->flowc) ? (CCTS_OFLOW | CRTS_IFLOW): 0; #endif /* Return baud */ cfsetispeed(termiosp, priv->baud); /* Return number of bits */ switch (priv->bits) { case 5: termiosp->c_cflag |= CS5; break; case 6: termiosp->c_cflag |= CS6; break; case 7: termiosp->c_cflag |= CS7; break; default: case 8: termiosp->c_cflag |= CS8; break; case 9: termiosp->c_cflag |= CS8 /* CS9 */ ; break; } } break; case TCSETS: { struct termios *termiosp = (struct termios *)arg; struct esp32_dev_s *priv = (struct esp32_dev_s *)dev->priv; uint32_t baud; uint32_t intena; uint8_t parity; uint8_t nbits; bool stop2; #if defined(CONFIG_SERIAL_IFLOWCONTROL) || defined(CONFIG_SERIAL_OFLOWCONTROL) bool flowc; #endif if (!termiosp) { ret = -EINVAL; break; } /* Decode baud. */ ret = OK; baud = cfgetispeed(termiosp); /* Decode number of bits */ switch (termiosp->c_cflag & CSIZE) { case CS5: nbits = 5; break; case CS6: nbits = 6; break; case CS7: nbits = 7; break; case CS8: nbits = 8; break; #if 0 case CS9: nbits = 9; break; #endif default: ret = -EINVAL; break; } /* Decode parity */ if ((termiosp->c_cflag & PARENB) != 0) { parity = (termiosp->c_cflag & PARODD) ? 1 : 2; } else { parity = 0; } /* Decode stop bits */ stop2 = (termiosp->c_cflag & CSTOPB) != 0; /* Decode flow control */ #if defined(CONFIG_SERIAL_IFLOWCONTROL) || defined(CONFIG_SERIAL_OFLOWCONTROL) flowc = (termiosp->c_cflag & (CCTS_OFLOW | CRTS_IFLOW)) != 0; #endif /* Verify that all settings are valid before committing */ if (ret == OK) { /* Commit */ priv->baud = baud; priv->parity = parity; priv->bits = nbits; priv->stopbits2 = stop2; #if defined(CONFIG_SERIAL_IFLOWCONTROL) || defined(CONFIG_SERIAL_OFLOWCONTROL) priv->flowc = flowc; #endif /* effect the changes immediately - note that we do not * implement TCSADRAIN / TCSAFLUSH */ esp32_disableallints(priv, &intena); ret = esp32_setup(dev); /* Restore the interrupt state */ esp32_restoreuartint(priv, intena); } } break; #endif /* CONFIG_SERIAL_TERMIOS */ default: ret = -ENOTTY; break; } return ret; } /**************************************************************************** * Name: esp32_receive * * Description: * Called (usually) from the interrupt level to receive one * character from the UART. Error bits associated with the * receipt are provided in the return 'status'. * ****************************************************************************/ static int esp32_receive(struct uart_dev_s *dev, unsigned int *status) { struct esp32_dev_s *priv = (struct esp32_dev_s *)dev->priv; /* Return the error information in the saved status */ *status = (unsigned int)priv->status; priv->status = 0; /* Then return the actual received byte */ return (int)(esp32_serialin(priv, UART_FIFO_OFFSET) & UART_RXFIFO_RD_BYTE_M); } /**************************************************************************** * Name: esp32_rxint * * Description: * Call to enable or disable RXRDY interrupts * ****************************************************************************/ static void esp32_rxint(struct uart_dev_s *dev, bool enable) { struct esp32_dev_s *priv = (struct esp32_dev_s *)dev->priv; irqstate_t flags; int regval; flags = enter_critical_section(); if (enable) { /* Receive an interrupt when their is anything in the Rx data register * (or an Rx timeout occurs). */ #ifndef CONFIG_SUPPRESS_SERIAL_INTS regval = esp32_serialin(priv, UART_INT_ENA_OFFSET); regval |= (UART_RXFIFO_FULL_INT_ENA | UART_FRM_ERR_INT_ENA | UART_RXFIFO_TOUT_INT_ENA); esp32_serialout(priv, UART_INT_ENA_OFFSET, regval); #endif } else { /* Disable the RX interrupts */ regval = esp32_serialin(priv, UART_INT_ENA_OFFSET); regval &= ~(UART_RXFIFO_FULL_INT_ENA | UART_FRM_ERR_INT_ENA | UART_RXFIFO_TOUT_INT_ENA); esp32_serialout(priv, UART_INT_ENA_OFFSET, regval); } leave_critical_section(flags); } /**************************************************************************** * Name: esp32_rxavailable * * Description: * Return true if the receive holding register is not empty * ****************************************************************************/ static bool esp32_rxavailable(struct uart_dev_s *dev) { struct esp32_dev_s *priv = (struct esp32_dev_s *)dev->priv; return ((esp32_serialin(priv, UART_STATUS_OFFSET) & UART_RXFIFO_CNT_M) > 0); } /**************************************************************************** * Name: esp32_send * * Description: * This method will send one byte on the UART. * ****************************************************************************/ static void esp32_send(struct uart_dev_s *dev, int ch) { struct esp32_dev_s *priv = (struct esp32_dev_s *)dev->priv; esp32_serialout(priv, UART_FIFO_OFFSET, (uint32_t)ch); } /**************************************************************************** * Name: esp32_txint * * Description: * Call to enable or disable TX interrupts * ****************************************************************************/ static void esp32_txint(struct uart_dev_s *dev, bool enable) { struct esp32_dev_s *priv = (struct esp32_dev_s *)dev->priv; irqstate_t flags; int regval; flags = enter_critical_section(); if (enable) { /* Set to receive an interrupt when the TX holding register register * is empty */ #ifndef CONFIG_SUPPRESS_SERIAL_INTS regval = esp32_serialin(priv, UART_INT_ENA_OFFSET); regval |= (UART_TX_DONE_INT_ENA | UART_TXFIFO_EMPTY_INT_ENA); esp32_serialout(priv, UART_INT_ENA_OFFSET, regval); /* Fake a TX interrupt here by just calling uart_xmitchars() with * interrupts disabled (note this may recurse). */ uart_xmitchars(dev); #endif } else { /* Disable the TX interrupt */ regval = esp32_serialin(priv, UART_INT_ENA_OFFSET); regval &= ~(UART_TX_DONE_INT_ENA | UART_TXFIFO_EMPTY_INT_ENA); esp32_serialout(priv, UART_INT_ENA_OFFSET, regval); } leave_critical_section(flags); } /**************************************************************************** * Name: esp32_txready * * Description: * Return true if the transmit holding register is empty (TXRDY) * ****************************************************************************/ static bool esp32_txready(struct uart_dev_s *dev) { struct esp32_dev_s *priv = (struct esp32_dev_s *)dev->priv; return ((esp32_serialin(priv, UART_STATUS_OFFSET) & UART_TXFIFO_CNT_M) < 0x7f); } /**************************************************************************** * Name: esp32_txempty * * Description: * Return true if the transmit holding and shift registers are empty * ****************************************************************************/ static bool esp32_txempty(struct uart_dev_s *dev) { struct esp32_dev_s *priv = (struct esp32_dev_s *)dev->priv; return ((esp32_serialin(priv, UART_STATUS_OFFSET) & UART_TXFIFO_CNT_M) == 0); } /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: xtensa_early_serial_initialize * * Description: * Performs the low level UART initialization early in debug so that the * serial console will be available during bootup. This must be called * before up_serialinit. * ****************************************************************************/ #ifdef USE_EARLYSERIALINIT void xtensa_early_serial_initialize(void) { /* NOTE: All GPIO configuration for the UARTs was performed in * esp32_lowsetup */ /* Disable all UARTS */ esp32_disableallints(TTYS0_DEV.priv, NULL); #ifdef TTYS1_DEV esp32_disableallints(TTYS1_DEV.priv, NULL); #endif #ifdef TTYS2_DEV esp32_disableallints(TTYS2_DEV.priv, NULL); #endif /* Configuration whichever one is the console */ #ifdef HAVE_SERIAL_CONSOLE CONSOLE_DEV.isconsole = true; esp32_setup(&CONSOLE_DEV); #endif } #endif /**************************************************************************** * Name: xtensa_serial_initialize * * Description: * Register serial console and serial ports. This assumes * that up_earlyserialinit was called previously. * ****************************************************************************/ void xtensa_serial_initialize(void) { /* Register the console */ #ifdef HAVE_SERIAL_CONSOLE uart_register("/dev/console", &CONSOLE_DEV); #endif /* Register all UARTs */ uart_register("/dev/ttyS0", &TTYS0_DEV); #ifdef TTYS1_DEV uart_register("/dev/ttyS1", &TTYS1_DEV); #endif #ifdef TTYS2_DEV uart_register("/dev/ttyS2", &TTYS2_DEV); #endif } /**************************************************************************** * Name: up_putc * * Description: * Provide priority, low-level access to support OS debug writes * ****************************************************************************/ int up_putc(int ch) { #ifdef HAVE_SERIAL_CONSOLE uint32_t intena; esp32_disableallints(CONSOLE_DEV.priv, &intena); /* Check for LF */ if (ch == '\n') { /* Add CR */ while (!esp32_txready(&CONSOLE_DEV)); esp32_send(&CONSOLE_DEV, '\r'); } while (!esp32_txready(&CONSOLE_DEV)); esp32_send(&CONSOLE_DEV, ch); esp32_restoreuartint(CONSOLE_DEV.priv, intena); #endif return ch; } #endif /* USE_SERIALDRIVER */
815755.c
/* * chap_ms.c - Microsoft MS-CHAP compatible implementation. * * Copyright (c) 1995 Eric Rosenquist. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The name(s) of the authors of this software must not be used to * endorse or promote products derived from this software without * prior written permission. * * THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS, IN NO EVENT SHALL THE AUTHORS 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. */ /* * Modifications by Lauri Pesonen / [email protected], april 1997 * * Implemented LANManager type password response to MS-CHAP challenges. * Now pppd provides both NT style and LANMan style blocks, and the * preferred is set by option "ms-lanman". Default is to use NT. * The hash text (StdText) was taken from Win95 RASAPI32.DLL. * * You should also use DOMAIN\\USERNAME as described in README.MSCHAP80 */ /* * Modifications by Frank Cusack, [email protected], March 2002. * * Implemented MS-CHAPv2 functionality, heavily based on sample * implementation in RFC 2759. Implemented MPPE functionality, * heavily based on sample implementation in RFC 3079. * * Copyright (c) 2002 Google, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The name(s) of the authors of this software must not be used to * endorse or promote products derived from this software without * prior written permission. * * THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS, IN NO EVENT SHALL THE AUTHORS 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. * */ #include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && MSCHAP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #if 0 /* UNUSED */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <sys/types.h> #include <sys/time.h> #include <unistd.h> #endif /* UNUSED */ #include "netif/ppp/ppp_impl.h" #include "netif/ppp/chap-new.h" #include "netif/ppp/chap_ms.h" #include "netif/ppp/pppcrypt.h" #include "netif/ppp/magic.h" #if MPPE_SUPPORT #include "netif/ppp/mppe.h" /* For mppe_sha1_pad*, mppe_set_key() */ #endif /* MPPE_SUPPORT */ #define SHA1_SIGNATURE_SIZE 20 #define MD4_SIGNATURE_SIZE 16 /* 16 bytes in a MD4 message digest */ #define MAX_NT_PASSWORD 256 /* Max (Unicode) chars in an NT pass */ #define MS_CHAP_RESPONSE_LEN 49 /* Response length for MS-CHAP */ #define MS_CHAP2_RESPONSE_LEN 49 /* Response length for MS-CHAPv2 */ #define MS_AUTH_RESPONSE_LENGTH 40 /* MS-CHAPv2 authenticator response, */ /* as ASCII */ /* Error codes for MS-CHAP failure messages. */ #define MS_CHAP_ERROR_RESTRICTED_LOGON_HOURS 646 #define MS_CHAP_ERROR_ACCT_DISABLED 647 #define MS_CHAP_ERROR_PASSWD_EXPIRED 648 #define MS_CHAP_ERROR_NO_DIALIN_PERMISSION 649 #define MS_CHAP_ERROR_AUTHENTICATION_FAILURE 691 #define MS_CHAP_ERROR_CHANGING_PASSWORD 709 /* * Offsets within the response field for MS-CHAP */ #define MS_CHAP_LANMANRESP 0 #define MS_CHAP_LANMANRESP_LEN 24 #define MS_CHAP_NTRESP 24 #define MS_CHAP_NTRESP_LEN 24 #define MS_CHAP_USENT 48 /* * Offsets within the response field for MS-CHAP2 */ #define MS_CHAP2_PEER_CHALLENGE 0 #define MS_CHAP2_PEER_CHAL_LEN 16 #define MS_CHAP2_RESERVED_LEN 8 #define MS_CHAP2_NTRESP 24 #define MS_CHAP2_NTRESP_LEN 24 #define MS_CHAP2_FLAGS 48 #if MPPE_SUPPORT #if 0 /* UNUSED */ /* These values are the RADIUS attribute values--see RFC 2548. */ #define MPPE_ENC_POL_ENC_ALLOWED 1 #define MPPE_ENC_POL_ENC_REQUIRED 2 #define MPPE_ENC_TYPES_RC4_40 2 #define MPPE_ENC_TYPES_RC4_128 4 /* used by plugins (using above values) */ extern void set_mppe_enc_types(int, int); #endif /* UNUSED */ #endif /* MPPE_SUPPORT */ /* Are we the authenticator or authenticatee? For MS-CHAPv2 key derivation. */ #define MS_CHAP2_AUTHENTICATEE 0 #define MS_CHAP2_AUTHENTICATOR 1 static void ascii2unicode (const char[], int, u_char[]); static void NTPasswordHash (u_char *, int, u_char[MD4_SIGNATURE_SIZE]); static void ChallengeResponse (const u_char *, const u_char *, u_char[24]); static void ChallengeHash (const u_char[16], const u_char *, const char *, u_char[8]); static void ChapMS_NT (const u_char *, const char *, int, u_char[24]); static void ChapMS2_NT (const u_char *, const u_char[16], const char *, const char *, int, u_char[24]); static void GenerateAuthenticatorResponsePlain (const char*, int, u_char[24], const u_char[16], const u_char *, const char *, u_char[41]); #ifdef MSLANMAN static void ChapMS_LANMan (u_char *, char *, int, u_char *); #endif static void GenerateAuthenticatorResponse(const u_char PasswordHashHash[MD4_SIGNATURE_SIZE], u_char NTResponse[24], const u_char PeerChallenge[16], const u_char *rchallenge, const char *username, u_char authResponse[MS_AUTH_RESPONSE_LENGTH+1]); #if MPPE_SUPPORT static void Set_Start_Key (ppp_pcb *pcb, const u_char *, const char *, int); static void SetMasterKeys (ppp_pcb *pcb, const char *, int, u_char[24], int); #endif /* MPPE_SUPPORT */ static void ChapMS (ppp_pcb *pcb, const u_char *, const char *, int, u_char *); static void ChapMS2 (ppp_pcb *pcb, const u_char *, const u_char *, const char *, const char *, int, u_char *, u_char[MS_AUTH_RESPONSE_LENGTH+1], int); #ifdef MSLANMAN bool ms_lanman = 0; /* Use LanMan password instead of NT */ /* Has meaning only with MS-CHAP challenges */ #endif #if MPPE_SUPPORT #ifdef DEBUGMPPEKEY /* For MPPE debug */ /* Use "[]|}{?/><,`!2&&(" (sans quotes) for RFC 3079 MS-CHAPv2 test value */ static char *mschap_challenge = NULL; /* Use "!@\#$%^&*()_+:3|~" (sans quotes, backslash is to escape #) for ... */ static char *mschap2_peer_challenge = NULL; #endif #include "netif/ppp/fsm.h" /* Need to poke MPPE options */ #include "netif/ppp/ccp.h" #endif /* MPPE_SUPPORT */ #if PPP_OPTIONS /* * Command-line options. */ static option_t chapms_option_list[] = { #ifdef MSLANMAN { "ms-lanman", o_bool, &ms_lanman, "Use LanMan passwd when using MS-CHAP", 1 }, #endif #ifdef DEBUGMPPEKEY { "mschap-challenge", o_string, &mschap_challenge, "specify CHAP challenge" }, { "mschap2-peer-challenge", o_string, &mschap2_peer_challenge, "specify CHAP peer challenge" }, #endif { NULL } }; #endif /* PPP_OPTIONS */ #if PPP_SERVER /* * chapms_generate_challenge - generate a challenge for MS-CHAP. * For MS-CHAP the challenge length is fixed at 8 bytes. * The length goes in challenge[0] and the actual challenge starts * at challenge[1]. */ static void chapms_generate_challenge(ppp_pcb *pcb, unsigned char *challenge) { LWIP_UNUSED_ARG(pcb); *challenge++ = 8; #ifdef DEBUGMPPEKEY if (mschap_challenge && strlen(mschap_challenge) == 8) memcpy(challenge, mschap_challenge, 8); else #endif magic_random_bytes(challenge, 8); } static void chapms2_generate_challenge(ppp_pcb *pcb, unsigned char *challenge) { LWIP_UNUSED_ARG(pcb); *challenge++ = 16; #ifdef DEBUGMPPEKEY if (mschap_challenge && strlen(mschap_challenge) == 16) memcpy(challenge, mschap_challenge, 16); else #endif magic_random_bytes(challenge, 16); } static int chapms_verify_response(ppp_pcb *pcb, int id, const char *name, const unsigned char *secret, int secret_len, const unsigned char *challenge, const unsigned char *response, char *message, int message_space) { unsigned char md[MS_CHAP_RESPONSE_LEN]; int diff; int challenge_len, response_len; LWIP_UNUSED_ARG(id); LWIP_UNUSED_ARG(name); challenge_len = *challenge++; /* skip length, is 8 */ response_len = *response++; if (response_len != MS_CHAP_RESPONSE_LEN) goto bad; #ifndef MSLANMAN if (!response[MS_CHAP_USENT]) { /* Should really propagate this into the error packet. */ ppp_notice(("Peer request for LANMAN auth not supported")); goto bad; } #endif /* Generate the expected response. */ ChapMS(pcb, (const u_char *)challenge, (const char *)secret, secret_len, md); #ifdef MSLANMAN /* Determine which part of response to verify against */ if (!response[MS_CHAP_USENT]) diff = memcmp(&response[MS_CHAP_LANMANRESP], &md[MS_CHAP_LANMANRESP], MS_CHAP_LANMANRESP_LEN); else #endif diff = memcmp(&response[MS_CHAP_NTRESP], &md[MS_CHAP_NTRESP], MS_CHAP_NTRESP_LEN); if (diff == 0) { ppp_slprintf(message, message_space, "Access granted"); return 1; } bad: /* See comments below for MS-CHAP V2 */ ppp_slprintf(message, message_space, "E=691 R=1 C=%0.*B V=0", challenge_len, challenge); return 0; } static int chapms2_verify_response(ppp_pcb *pcb, int id, const char *name, const unsigned char *secret, int secret_len, const unsigned char *challenge, const unsigned char *response, char *message, int message_space) { unsigned char md[MS_CHAP2_RESPONSE_LEN]; char saresponse[MS_AUTH_RESPONSE_LENGTH+1]; int challenge_len, response_len; LWIP_UNUSED_ARG(id); challenge_len = *challenge++; /* skip length, is 16 */ response_len = *response++; if (response_len != MS_CHAP2_RESPONSE_LEN) goto bad; /* not even the right length */ /* Generate the expected response and our mutual auth. */ ChapMS2(pcb, (const u_char*)challenge, (const u_char*)&response[MS_CHAP2_PEER_CHALLENGE], name, (const char *)secret, secret_len, md, (unsigned char *)saresponse, MS_CHAP2_AUTHENTICATOR); /* compare MDs and send the appropriate status */ /* * Per RFC 2759, success message must be formatted as * "S=<auth_string> M=<message>" * where * <auth_string> is the Authenticator Response (mutual auth) * <message> is a text message * * However, some versions of Windows (win98 tested) do not know * about the M=<message> part (required per RFC 2759) and flag * it as an error (reported incorrectly as an encryption error * to the user). Since the RFC requires it, and it can be * useful information, we supply it if the peer is a conforming * system. Luckily (?), win98 sets the Flags field to 0x04 * (contrary to RFC requirements) so we can use that to * distinguish between conforming and non-conforming systems. * * Special thanks to Alex Swiridov <[email protected]> for * help debugging this. */ if (memcmp(&md[MS_CHAP2_NTRESP], &response[MS_CHAP2_NTRESP], MS_CHAP2_NTRESP_LEN) == 0) { if (response[MS_CHAP2_FLAGS]) ppp_slprintf(message, message_space, "S=%s", saresponse); else ppp_slprintf(message, message_space, "S=%s M=%s", saresponse, "Access granted"); return 1; } bad: /* * Failure message must be formatted as * "E=e R=r C=c V=v M=m" * where * e = error code (we use 691, ERROR_AUTHENTICATION_FAILURE) * r = retry (we use 1, ok to retry) * c = challenge to use for next response, we reuse previous * v = Change Password version supported, we use 0 * m = text message * * The M=m part is only for MS-CHAPv2. Neither win2k nor * win98 (others untested) display the message to the user anyway. * They also both ignore the E=e code. * * Note that it's safe to reuse the same challenge as we don't * actually accept another response based on the error message * (and no clients try to resend a response anyway). * * Basically, this whole bit is useless code, even the small * implementation here is only because of overspecification. */ ppp_slprintf(message, message_space, "E=691 R=1 C=%0.*B V=0 M=%s", challenge_len, challenge, "Access denied"); return 0; } #endif /* PPP_SERVER */ static void chapms_make_response(ppp_pcb *pcb, unsigned char *response, int id, const char *our_name, const unsigned char *challenge, const char *secret, int secret_len, unsigned char *private_) { LWIP_UNUSED_ARG(id); LWIP_UNUSED_ARG(our_name); LWIP_UNUSED_ARG(private_); challenge++; /* skip length, should be 8 */ *response++ = MS_CHAP_RESPONSE_LEN; ChapMS(pcb, challenge, secret, secret_len, response); } static void chapms2_make_response(ppp_pcb *pcb, unsigned char *response, int id, const char *our_name, const unsigned char *challenge, const char *secret, int secret_len, unsigned char *private_) { LWIP_UNUSED_ARG(id); challenge++; /* skip length, should be 16 */ *response++ = MS_CHAP2_RESPONSE_LEN; ChapMS2(pcb, challenge, #ifdef DEBUGMPPEKEY mschap2_peer_challenge, #else NULL, #endif our_name, secret, secret_len, response, private_, MS_CHAP2_AUTHENTICATEE); } static int chapms2_check_success(ppp_pcb *pcb, unsigned char *msg, int len, unsigned char *private_) { LWIP_UNUSED_ARG(pcb); if ((len < MS_AUTH_RESPONSE_LENGTH + 2) || strncmp((char *)msg, "S=", 2) != 0) { /* Packet does not start with "S=" */ ppp_error(("MS-CHAPv2 Success packet is badly formed.")); return 0; } msg += 2; len -= 2; if (len < MS_AUTH_RESPONSE_LENGTH || memcmp(msg, private_, MS_AUTH_RESPONSE_LENGTH)) { /* Authenticator Response did not match expected. */ ppp_error(("MS-CHAPv2 mutual authentication failed.")); return 0; } /* Authenticator Response matches. */ msg += MS_AUTH_RESPONSE_LENGTH; /* Eat it */ len -= MS_AUTH_RESPONSE_LENGTH; if ((len >= 3) && !strncmp((char *)msg, " M=", 3)) { msg += 3; /* Eat the delimiter */ } else if (len) { /* Packet has extra text which does not begin " M=" */ ppp_error(("MS-CHAPv2 Success packet is badly formed.")); return 0; } return 1; } static void chapms_handle_failure(ppp_pcb *pcb, unsigned char *inp, int len) { int err; const char *p; char msg[64]; LWIP_UNUSED_ARG(pcb); /* We want a null-terminated string for strxxx(). */ len = LWIP_MIN(len, 63); MEMCPY(msg, inp, len); msg[len] = 0; p = msg; /* * Deal with MS-CHAP formatted failure messages; just print the * M=<message> part (if any). For MS-CHAP we're not really supposed * to use M=<message>, but it shouldn't hurt. See * chapms[2]_verify_response. */ if (!strncmp(p, "E=", 2)) err = strtol(p+2, NULL, 10); /* Remember the error code. */ else goto print_msg; /* Message is badly formatted. */ if (len && ((p = strstr(p, " M=")) != NULL)) { /* M=<message> field found. */ p += 3; } else { /* No M=<message>; use the error code. */ switch (err) { case MS_CHAP_ERROR_RESTRICTED_LOGON_HOURS: p = "E=646 Restricted logon hours"; break; case MS_CHAP_ERROR_ACCT_DISABLED: p = "E=647 Account disabled"; break; case MS_CHAP_ERROR_PASSWD_EXPIRED: p = "E=648 Password expired"; break; case MS_CHAP_ERROR_NO_DIALIN_PERMISSION: p = "E=649 No dialin permission"; break; case MS_CHAP_ERROR_AUTHENTICATION_FAILURE: p = "E=691 Authentication failure"; break; case MS_CHAP_ERROR_CHANGING_PASSWORD: /* Should never see this, we don't support Change Password. */ p = "E=709 Error changing password"; break; default: ppp_error(("Unknown MS-CHAP authentication failure: %.*v", len, inp)); return; } } print_msg: if (p != NULL) ppp_error(("MS-CHAP authentication failed: %v", p)); } static void ChallengeResponse(const u_char *challenge, const u_char PasswordHash[MD4_SIGNATURE_SIZE], u_char response[24]) { u_char ZPasswordHash[21]; lwip_des_context des; u_char des_key[8]; BZERO(ZPasswordHash, sizeof(ZPasswordHash)); MEMCPY(ZPasswordHash, PasswordHash, MD4_SIGNATURE_SIZE); #if 0 dbglog("ChallengeResponse - ZPasswordHash %.*B", sizeof(ZPasswordHash), ZPasswordHash); #endif pppcrypt_56_to_64_bit_key(ZPasswordHash + 0, des_key); lwip_des_init(&des); lwip_des_setkey_enc(&des, des_key); lwip_des_crypt_ecb(&des, challenge, response +0); lwip_des_free(&des); pppcrypt_56_to_64_bit_key(ZPasswordHash + 7, des_key); lwip_des_init(&des); lwip_des_setkey_enc(&des, des_key); lwip_des_crypt_ecb(&des, challenge, response +8); lwip_des_free(&des); pppcrypt_56_to_64_bit_key(ZPasswordHash + 14, des_key); lwip_des_init(&des); lwip_des_setkey_enc(&des, des_key); lwip_des_crypt_ecb(&des, challenge, response +16); lwip_des_free(&des); #if 0 dbglog("ChallengeResponse - response %.24B", response); #endif } static void ChallengeHash(const u_char PeerChallenge[16], const u_char *rchallenge, const char *username, u_char Challenge[8]) { lwip_sha1_context sha1Context; u_char sha1Hash[SHA1_SIGNATURE_SIZE]; const char *user; /* remove domain from "domain\username" */ if ((user = strrchr(username, '\\')) != NULL) ++user; else user = username; lwip_sha1_init(&sha1Context); lwip_sha1_starts(&sha1Context); lwip_sha1_update(&sha1Context, PeerChallenge, 16); lwip_sha1_update(&sha1Context, rchallenge, 16); lwip_sha1_update(&sha1Context, (const unsigned char*)user, strlen(user)); lwip_sha1_finish(&sha1Context, sha1Hash); lwip_sha1_free(&sha1Context); MEMCPY(Challenge, sha1Hash, 8); } /* * Convert the ASCII version of the password to Unicode. * This implicitly supports 8-bit ISO8859/1 characters. * This gives us the little-endian representation, which * is assumed by all M$ CHAP RFCs. (Unicode byte ordering * is machine-dependent.) */ static void ascii2unicode(const char ascii[], int ascii_len, u_char unicode[]) { int i; BZERO(unicode, ascii_len * 2); for (i = 0; i < ascii_len; i++) unicode[i * 2] = (u_char) ascii[i]; } static void NTPasswordHash(u_char *secret, int secret_len, u_char hash[MD4_SIGNATURE_SIZE]) { lwip_md4_context md4Context; lwip_md4_init(&md4Context); lwip_md4_starts(&md4Context); lwip_md4_update(&md4Context, secret, secret_len); lwip_md4_finish(&md4Context, hash); lwip_md4_free(&md4Context); } static void ChapMS_NT(const u_char *rchallenge, const char *secret, int secret_len, u_char NTResponse[24]) { u_char unicodePassword[MAX_NT_PASSWORD * 2]; u_char PasswordHash[MD4_SIGNATURE_SIZE]; /* Hash the Unicode version of the secret (== password). */ ascii2unicode(secret, secret_len, unicodePassword); NTPasswordHash(unicodePassword, secret_len * 2, PasswordHash); ChallengeResponse(rchallenge, PasswordHash, NTResponse); } static void ChapMS2_NT(const u_char *rchallenge, const u_char PeerChallenge[16], const char *username, const char *secret, int secret_len, u_char NTResponse[24]) { u_char unicodePassword[MAX_NT_PASSWORD * 2]; u_char PasswordHash[MD4_SIGNATURE_SIZE]; u_char Challenge[8]; ChallengeHash(PeerChallenge, rchallenge, username, Challenge); /* Hash the Unicode version of the secret (== password). */ ascii2unicode(secret, secret_len, unicodePassword); NTPasswordHash(unicodePassword, secret_len * 2, PasswordHash); ChallengeResponse(Challenge, PasswordHash, NTResponse); } #ifdef MSLANMAN static u_char *StdText = (u_char *)"KGS!@#$%"; /* key from rasapi32.dll */ static void ChapMS_LANMan(u_char *rchallenge, char *secret, int secret_len, unsigned char *response) { int i; u_char UcasePassword[MAX_NT_PASSWORD]; /* max is actually 14 */ u_char PasswordHash[MD4_SIGNATURE_SIZE]; lwip_des_context des; u_char des_key[8]; /* LANMan password is case insensitive */ BZERO(UcasePassword, sizeof(UcasePassword)); for (i = 0; i < secret_len; i++) UcasePassword[i] = (u_char)toupper(secret[i]); pppcrypt_56_to_64_bit_key(UcasePassword +0, des_key); lwip_des_init(&des); lwip_des_setkey_enc(&des, des_key); lwip_des_crypt_ecb(&des, StdText, PasswordHash +0); lwip_des_free(&des); pppcrypt_56_to_64_bit_key(UcasePassword +7, des_key); lwip_des_init(&des); lwip_des_setkey_enc(&des, des_key); lwip_des_crypt_ecb(&des, StdText, PasswordHash +8); lwip_des_free(&des); ChallengeResponse(rchallenge, PasswordHash, &response[MS_CHAP_LANMANRESP]); } #endif static void GenerateAuthenticatorResponse(const u_char PasswordHashHash[MD4_SIGNATURE_SIZE], u_char NTResponse[24], const u_char PeerChallenge[16], const u_char *rchallenge, const char *username, u_char authResponse[MS_AUTH_RESPONSE_LENGTH+1]) { /* * "Magic" constants used in response generation, from RFC 2759. */ static const u_char Magic1[39] = /* "Magic server to client signing constant" */ { 0x4D, 0x61, 0x67, 0x69, 0x63, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x74, 0x6F, 0x20, 0x63, 0x6C, 0x69, 0x65, 0x6E, 0x74, 0x20, 0x73, 0x69, 0x67, 0x6E, 0x69, 0x6E, 0x67, 0x20, 0x63, 0x6F, 0x6E, 0x73, 0x74, 0x61, 0x6E, 0x74 }; static const u_char Magic2[41] = /* "Pad to make it do more than one iteration" */ { 0x50, 0x61, 0x64, 0x20, 0x74, 0x6F, 0x20, 0x6D, 0x61, 0x6B, 0x65, 0x20, 0x69, 0x74, 0x20, 0x64, 0x6F, 0x20, 0x6D, 0x6F, 0x72, 0x65, 0x20, 0x74, 0x68, 0x61, 0x6E, 0x20, 0x6F, 0x6E, 0x65, 0x20, 0x69, 0x74, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6F, 0x6E }; int i; lwip_sha1_context sha1Context; u_char Digest[SHA1_SIGNATURE_SIZE]; u_char Challenge[8]; lwip_sha1_init(&sha1Context); lwip_sha1_starts(&sha1Context); lwip_sha1_update(&sha1Context, PasswordHashHash, MD4_SIGNATURE_SIZE); lwip_sha1_update(&sha1Context, NTResponse, 24); lwip_sha1_update(&sha1Context, Magic1, sizeof(Magic1)); lwip_sha1_finish(&sha1Context, Digest); lwip_sha1_free(&sha1Context); ChallengeHash(PeerChallenge, rchallenge, username, Challenge); lwip_sha1_init(&sha1Context); lwip_sha1_starts(&sha1Context); lwip_sha1_update(&sha1Context, Digest, sizeof(Digest)); lwip_sha1_update(&sha1Context, Challenge, sizeof(Challenge)); lwip_sha1_update(&sha1Context, Magic2, sizeof(Magic2)); lwip_sha1_finish(&sha1Context, Digest); lwip_sha1_free(&sha1Context); /* Convert to ASCII hex string. */ for (i = 0; i < LWIP_MAX((MS_AUTH_RESPONSE_LENGTH / 2), (int)sizeof(Digest)); i++) sprintf((char *)&authResponse[i * 2], "%02X", Digest[i]); } static void GenerateAuthenticatorResponsePlain( const char *secret, int secret_len, u_char NTResponse[24], const u_char PeerChallenge[16], const u_char *rchallenge, const char *username, u_char authResponse[MS_AUTH_RESPONSE_LENGTH+1]) { u_char unicodePassword[MAX_NT_PASSWORD * 2]; u_char PasswordHash[MD4_SIGNATURE_SIZE]; u_char PasswordHashHash[MD4_SIGNATURE_SIZE]; /* Hash (x2) the Unicode version of the secret (== password). */ ascii2unicode(secret, secret_len, unicodePassword); NTPasswordHash(unicodePassword, secret_len * 2, PasswordHash); NTPasswordHash(PasswordHash, sizeof(PasswordHash), PasswordHashHash); GenerateAuthenticatorResponse(PasswordHashHash, NTResponse, PeerChallenge, rchallenge, username, authResponse); } #if MPPE_SUPPORT /* * Set mppe_xxxx_key from MS-CHAP credentials. (see RFC 3079) */ static void Set_Start_Key(ppp_pcb *pcb, const u_char *rchallenge, const char *secret, int secret_len) { u_char unicodePassword[MAX_NT_PASSWORD * 2]; u_char PasswordHash[MD4_SIGNATURE_SIZE]; u_char PasswordHashHash[MD4_SIGNATURE_SIZE]; lwip_sha1_context sha1Context; u_char Digest[SHA1_SIGNATURE_SIZE]; /* >= MPPE_MAX_KEY_LEN */ /* Hash (x2) the Unicode version of the secret (== password). */ ascii2unicode(secret, secret_len, unicodePassword); NTPasswordHash(unicodePassword, secret_len * 2, PasswordHash); NTPasswordHash(PasswordHash, sizeof(PasswordHash), PasswordHashHash); lwip_sha1_init(&sha1Context); lwip_sha1_starts(&sha1Context); lwip_sha1_update(&sha1Context, PasswordHashHash, MD4_SIGNATURE_SIZE); lwip_sha1_update(&sha1Context, PasswordHashHash, MD4_SIGNATURE_SIZE); lwip_sha1_update(&sha1Context, rchallenge, 8); lwip_sha1_finish(&sha1Context, Digest); lwip_sha1_free(&sha1Context); /* Same key in both directions. */ mppe_set_key(pcb, &pcb->mppe_comp, Digest); mppe_set_key(pcb, &pcb->mppe_decomp, Digest); pcb->mppe_keys_set = 1; } /* * Set mppe_xxxx_key from MS-CHAPv2 credentials. (see RFC 3079) */ static void SetMasterKeys(ppp_pcb *pcb, const char *secret, int secret_len, u_char NTResponse[24], int IsServer) { u_char unicodePassword[MAX_NT_PASSWORD * 2]; u_char PasswordHash[MD4_SIGNATURE_SIZE]; u_char PasswordHashHash[MD4_SIGNATURE_SIZE]; lwip_sha1_context sha1Context; u_char MasterKey[SHA1_SIGNATURE_SIZE]; /* >= MPPE_MAX_KEY_LEN */ u_char Digest[SHA1_SIGNATURE_SIZE]; /* >= MPPE_MAX_KEY_LEN */ const u_char *s; /* "This is the MPPE Master Key" */ static const u_char Magic1[27] = { 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x4d, 0x50, 0x50, 0x45, 0x20, 0x4d, 0x61, 0x73, 0x74, 0x65, 0x72, 0x20, 0x4b, 0x65, 0x79 }; /* "On the client side, this is the send key; " "on the server side, it is the receive key." */ static const u_char Magic2[84] = { 0x4f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x20, 0x73, 0x69, 0x64, 0x65, 0x2c, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x20, 0x6b, 0x65, 0x79, 0x3b, 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x73, 0x69, 0x64, 0x65, 0x2c, 0x20, 0x69, 0x74, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x20, 0x6b, 0x65, 0x79, 0x2e }; /* "On the client side, this is the receive key; " "on the server side, it is the send key." */ static const u_char Magic3[84] = { 0x4f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x20, 0x73, 0x69, 0x64, 0x65, 0x2c, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x20, 0x6b, 0x65, 0x79, 0x3b, 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x73, 0x69, 0x64, 0x65, 0x2c, 0x20, 0x69, 0x74, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x20, 0x6b, 0x65, 0x79, 0x2e }; /* Hash (x2) the Unicode version of the secret (== password). */ ascii2unicode(secret, secret_len, unicodePassword); NTPasswordHash(unicodePassword, secret_len * 2, PasswordHash); NTPasswordHash(PasswordHash, sizeof(PasswordHash), PasswordHashHash); lwip_sha1_init(&sha1Context); lwip_sha1_starts(&sha1Context); lwip_sha1_update(&sha1Context, PasswordHashHash, MD4_SIGNATURE_SIZE); lwip_sha1_update(&sha1Context, NTResponse, 24); lwip_sha1_update(&sha1Context, Magic1, sizeof(Magic1)); lwip_sha1_finish(&sha1Context, MasterKey); lwip_sha1_free(&sha1Context); /* * generate send key */ if (IsServer) s = Magic3; else s = Magic2; lwip_sha1_init(&sha1Context); lwip_sha1_starts(&sha1Context); lwip_sha1_update(&sha1Context, MasterKey, 16); lwip_sha1_update(&sha1Context, mppe_sha1_pad1, SHA1_PAD_SIZE); lwip_sha1_update(&sha1Context, s, 84); lwip_sha1_update(&sha1Context, mppe_sha1_pad2, SHA1_PAD_SIZE); lwip_sha1_finish(&sha1Context, Digest); lwip_sha1_free(&sha1Context); mppe_set_key(pcb, &pcb->mppe_comp, Digest); /* * generate recv key */ if (IsServer) s = Magic2; else s = Magic3; lwip_sha1_init(&sha1Context); lwip_sha1_starts(&sha1Context); lwip_sha1_update(&sha1Context, MasterKey, 16); lwip_sha1_update(&sha1Context, mppe_sha1_pad1, SHA1_PAD_SIZE); lwip_sha1_update(&sha1Context, s, 84); lwip_sha1_update(&sha1Context, mppe_sha1_pad2, SHA1_PAD_SIZE); lwip_sha1_finish(&sha1Context, Digest); lwip_sha1_free(&sha1Context); mppe_set_key(pcb, &pcb->mppe_decomp, Digest); pcb->mppe_keys_set = 1; } #endif /* MPPE_SUPPORT */ static void ChapMS(ppp_pcb *pcb, const u_char *rchallenge, const char *secret, int secret_len, unsigned char *response) { #if !MPPE_SUPPORT LWIP_UNUSED_ARG(pcb); #endif /* !MPPE_SUPPORT */ BZERO(response, MS_CHAP_RESPONSE_LEN); ChapMS_NT(rchallenge, secret, secret_len, &response[MS_CHAP_NTRESP]); #ifdef MSLANMAN ChapMS_LANMan(rchallenge, secret, secret_len, &response[MS_CHAP_LANMANRESP]); /* preferred method is set by option */ response[MS_CHAP_USENT] = !ms_lanman; #else response[MS_CHAP_USENT] = 1; #endif #if MPPE_SUPPORT Set_Start_Key(pcb, rchallenge, secret, secret_len); #endif /* MPPE_SUPPORT */ } /* * If PeerChallenge is NULL, one is generated and the PeerChallenge * field of response is filled in. Call this way when generating a response. * If PeerChallenge is supplied, it is copied into the PeerChallenge field. * Call this way when verifying a response (or debugging). * Do not call with PeerChallenge = response. * * The PeerChallenge field of response is then used for calculation of the * Authenticator Response. */ static void ChapMS2(ppp_pcb *pcb, const u_char *rchallenge, const u_char *PeerChallenge, const char *user, const char *secret, int secret_len, unsigned char *response, u_char authResponse[], int authenticator) { /* ARGSUSED */ LWIP_UNUSED_ARG(authenticator); #if !MPPE_SUPPORT LWIP_UNUSED_ARG(pcb); #endif /* !MPPE_SUPPORT */ BZERO(response, MS_CHAP2_RESPONSE_LEN); /* Generate the Peer-Challenge if requested, or copy it if supplied. */ if (!PeerChallenge) magic_random_bytes(&response[MS_CHAP2_PEER_CHALLENGE], MS_CHAP2_PEER_CHAL_LEN); else MEMCPY(&response[MS_CHAP2_PEER_CHALLENGE], PeerChallenge, MS_CHAP2_PEER_CHAL_LEN); /* Generate the NT-Response */ ChapMS2_NT(rchallenge, &response[MS_CHAP2_PEER_CHALLENGE], user, secret, secret_len, &response[MS_CHAP2_NTRESP]); /* Generate the Authenticator Response. */ GenerateAuthenticatorResponsePlain(secret, secret_len, &response[MS_CHAP2_NTRESP], &response[MS_CHAP2_PEER_CHALLENGE], rchallenge, user, authResponse); #if MPPE_SUPPORT SetMasterKeys(pcb, secret, secret_len, &response[MS_CHAP2_NTRESP], authenticator); #endif /* MPPE_SUPPORT */ } #if 0 /* UNUSED */ #if MPPE_SUPPORT /* * Set MPPE options from plugins. */ void set_mppe_enc_types(int policy, int types) { /* Early exit for unknown policies. */ if (policy != MPPE_ENC_POL_ENC_ALLOWED || policy != MPPE_ENC_POL_ENC_REQUIRED) return; /* Don't modify MPPE if it's optional and wasn't already configured. */ if (policy == MPPE_ENC_POL_ENC_ALLOWED && !ccp_wantoptions[0].mppe) return; /* * Disable undesirable encryption types. Note that we don't ENABLE * any encryption types, to avoid overriding manual configuration. */ switch(types) { case MPPE_ENC_TYPES_RC4_40: ccp_wantoptions[0].mppe &= ~MPPE_OPT_128; /* disable 128-bit */ break; case MPPE_ENC_TYPES_RC4_128: ccp_wantoptions[0].mppe &= ~MPPE_OPT_40; /* disable 40-bit */ break; default: break; } } #endif /* MPPE_SUPPORT */ #endif /* UNUSED */ const struct chap_digest_type chapms_digest = { CHAP_MICROSOFT, /* code */ #if PPP_SERVER chapms_generate_challenge, chapms_verify_response, #endif /* PPP_SERVER */ chapms_make_response, NULL, /* check_success */ chapms_handle_failure, }; const struct chap_digest_type chapms2_digest = { CHAP_MICROSOFT_V2, /* code */ #if PPP_SERVER chapms2_generate_challenge, chapms2_verify_response, #endif /* PPP_SERVER */ chapms2_make_response, chapms2_check_success, chapms_handle_failure, }; #endif /* PPP_SUPPORT && MSCHAP_SUPPORT */
16593.c
/* * ZTee Copyright 2014 Regents of the University of Michigan * * 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 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <errno.h> #include <getopt.h> #include <pthread.h> #include <unistd.h> #include <signal.h> #include "../lib/lockfd.h" #include "../lib/logger.h" #include "../lib/queue.h" #include "../lib/util.h" #include "../lib/xalloc.h" #include "../lib/csv.h" #include "topt.h" typedef enum file_format { FORMAT_CSV, FORMAT_JSON, FORMAT_RAW } format_t; static const char *format_names[] = { "csv", "json", "raw" }; typedef struct ztee_conf { // Files char *output_filename; char *status_updates_filename; char *log_file_name; FILE *output_file; FILE *status_updates_file; FILE *log_file; // Log level int log_level; // Input formats format_t in_format; format_t out_format; // Output config int success_only; // Monitor config int monitor; // Field indicies size_t ip_field; size_t success_field; } ztee_conf_t; static ztee_conf_t tconf; static int print_from_csv(char *line); static format_t test_input_format(char *line, size_t len) { // Check for empty input, remember line contains '\n' if (len < 2) { return FORMAT_RAW; } if (len >= 3) { // If the input is JSON, the line should look like // {.......}\n if (line[0] == '{' && line[len - 2] == '}') { return FORMAT_JSON; } } if (strchr(line, ',') != NULL) { return FORMAT_CSV; } return FORMAT_RAW; } int done = 0; int process_done = 0; int total_read_in = 0; int read_in_last_sec = 0; int total_written = 0; double start_time; pthread_t threads[3]; //one thread reads in //one thread writes out and parses //pops next element and determines what to do //if zqueue_t is empty and read_in is finished, then //it exits void *process_queue (void* my_q); //uses fgets to read from stdin and add it to the zqueue_t void *read_in (void* my_q); //does the same as find UP but finds only successful IPs, determined by the //is_successful field and flag void find_successful_IP (char* my_string); //finds IP in the string of csv and sends it to stdout for zgrab //you need to know what position is the csv string the ip field is in //zero indexed void find_IP (char* my_string); //writes a csv string out to csv file //fprintf(stderr, "Is empty inside if %i\n", is_empty(queue)); void write_out_to_file (char* data); //figure out how many fields are present if it is a csv void figure_out_fields (char* data); //check that the output file is either in a csv form or json form //throws error is it is not either //NOTE: JSON OUTPUT NOT IMPLEMENTED void output_file_is_csv(); void print_thread_error(); //monitor code for ztee //executes every second void *monitor_ztee(void *my_q); #define SET_IF_GIVEN(DST,ARG) \ { if (args.ARG##_given) { (DST) = args.ARG##_arg; }; } #define SET_BOOL(DST,ARG) \ { if (args.ARG##_given) { (DST) = 1; }; } int main(int argc, char *argv[]) { struct gengetopt_args_info args; struct cmdline_parser_params *params; params = cmdline_parser_params_create(); assert(params); params->initialize = 1; params->override = 0; params->check_required = 0; if (cmdline_parser_ext(argc, argv, &args, params) != 0) { exit(EXIT_SUCCESS); } signal(SIGPIPE, SIG_IGN); // Handle help text and version if (args.help_given) { cmdline_parser_print_help(); exit(EXIT_SUCCESS); } if (args.version_given) { cmdline_parser_print_version(); exit(EXIT_SUCCESS); } // Try opening the log file tconf.log_level = ZLOG_WARN; if (args.log_file_given) { tconf.log_file = fopen(args.log_file_arg, "w"); } else { tconf.log_file = stderr; } // Check for an error opening the log file if (tconf.log_file == NULL) { log_init(stderr, tconf.log_level, 0, "ztee"); log_fatal("ztee", "Could not open log file"); } // Actually init the logging infrastructure log_init(tconf.log_file, tconf.log_level, 0, "ztee"); // Check for an output file if (args.inputs_num < 1) { log_fatal("ztee", "No output file specified"); } if (args.inputs_num > 1) { log_fatal("ztee", "Extra positional arguments starting with %s", args.inputs[1]); } tconf.output_filename = args.inputs[0]; tconf.output_file = fopen(tconf.output_filename, "w"); if (!tconf.output_file) { log_fatal("ztee", "Could not open output file %s, %s", tconf.output_filename, strerror(errno)); } // Read actual options int raw = 0; SET_BOOL(tconf.success_only, success_only); SET_BOOL(tconf.monitor, monitor); SET_BOOL(raw, raw); // Open the status update file if necessary if (args.status_updates_file_given) { // Try to open the status output file char *filename = args.status_updates_file_arg; FILE *file = fopen(filename, "w"); if (!file) { char *err = strerror(errno); log_fatal("ztee", "unable to open status updates file %s (%s)", filename, err); } // Set the variables in state tconf.status_updates_filename = filename; tconf.status_updates_file = file; } // Read the first line of the input file size_t first_line_len = 1024; char *first_line = xmalloc(first_line_len); if (getline(&first_line, &first_line_len, stdin) < 0) { log_fatal("ztee", "reading input to test format failed"); } // Detect the input format if (!raw) { format_t format = test_input_format(first_line, first_line_len); log_info("ztee", "detected input format %s", format_names[format]); tconf.in_format = format; } else { tconf.in_format = FORMAT_RAW; log_info("ztee", "raw input"); } if (tconf.in_format == FORMAT_JSON) { log_fatal("ztee", "json input not implemented"); } // Find fields if needed char *header = strdup(first_line); int found_success = 0; int found_ip = 0; if (tconf.in_format == FORMAT_CSV) { static const char *success_names[] = { "success" }; static const char *ip_names[] = { "saddr", "ip" }; int success_idx = csv_find_index(header, success_names, 1); if (success_idx >= 0) { found_success = 1; tconf.success_field = (size_t) success_idx; } int ip_idx = csv_find_index(header, ip_names, 2); if (found_ip >= 0) { found_ip = 1; tconf.ip_field = (size_t) ip_idx; } if (!found_ip) { log_fatal("ztee", "Unable to find IP/SADDR field"); } } if (tconf.success_only) { if (tconf.in_format != FORMAT_CSV) { log_fatal("ztee", "success filter requires csv input"); } if (!found_success) { log_fatal("ztee", "Could not find success field"); } } // Make the queue zqueue_t* queue = queue_init(); assert(queue); // Add the first line to the queue if needed push_back(first_line, queue); // Start the regular read thread pthread_t read_thread; if (pthread_create(&read_thread, NULL, read_in, queue)) { log_fatal("ztee", "unable to start read thread"); } // Record the start time start_time = now(); // Start the process thread pthread_t process_thread; if (pthread_create(&process_thread, NULL, process_queue, queue)) { log_fatal("ztee", "unable to start process thread"); } // Start the monitor thread if necessary, and join to it if (tconf.monitor || tconf.status_updates_file) { pthread_t monitor_thread; if (pthread_create(&monitor_thread, NULL, monitor_ztee, queue)) { log_fatal("ztee", "unable to create monitor thread"); } pthread_join(monitor_thread, NULL); } // Join to the remaining threads, pthread_join(read_thread, NULL); pthread_join(process_thread, NULL); return 0; } void *process_queue(void* arg) { zqueue_t *queue = arg; FILE *output_file = tconf.output_file; while (!process_done) { pthread_mutex_lock(&queue->lock); while (!done && is_empty(queue)) { pthread_cond_wait(&queue->empty, &queue->lock); } if (done && is_empty(queue)) { process_done = 1; pthread_mutex_unlock(&queue->lock); continue; } znode_t *node = pop_front_unsafe(queue); pthread_mutex_unlock(&queue->lock); // Write raw data to output file fprintf(output_file, "%s", node->data); fflush(output_file); if (ferror(output_file)) { log_fatal("ztee", "Error writing to output file"); } // Dump to stdout switch (tconf.in_format) { case FORMAT_JSON: log_fatal("ztee", "JSON input format unimplemented"); break; case FORMAT_CSV: print_from_csv(node->data); break; default: // Handle raw fprintf(stdout, "%s", node->data); break; } // Check to see if write failed fflush(stdout); if (ferror(stdout)) { log_fatal("ztee", "%s", "Error writing to stdout"); } // Record output lines total_written++; // Free the memory free(node->data); free(node); } process_done = 1; fflush(output_file); fclose(output_file); return NULL; } void *read_in(void* arg) { // Allocate buffers zqueue_t *queue = (zqueue_t*) arg; size_t length = 1000; char *input = xcalloc(sizeof(char), length);; // Read in from stdin and add to back of linked list while (getline(&input, &length, stdin) > 0) { push_back(input, queue); total_read_in++; read_in_last_sec++; } pthread_mutex_lock(&queue->lock); done = 1; pthread_cond_signal(&queue->empty); pthread_mutex_unlock(&queue->lock); return NULL; } int print_from_csv(char *line) { if (total_written == 0) { return 1; } if (tconf.success_only) { char *success_entry = csv_get_index(line, tconf.success_field); if (success_entry == NULL) { return 1; } int success = 0; if (atoi(success_entry)) { success = 1; } else if (strcasecmp(success_entry, "true") == 0) { success = 1; } if (!success) { return 1; } } // Find the ip char *ip = csv_get_index(line, tconf.ip_field); int ret = fprintf(stdout, "%s\n", ip); if (ferror(stdout)) { log_fatal("ztee", "unable to write to stdout"); } return ret; } void output_file_is_csv() { return; /* char *dot = strrchr(output_filename); if dot == NULL { return; } */ /* int length = strlen(output_filename); char *end_of_file = malloc(sizeof(char*) *4); strncpy(end_of_file, output_filename+(length - 3), 3); end_of_file[4] = '\0'; const char *csv = "csv\n"; const char *json = "jso\n"; if(!strncmp(end_of_file, csv, 3) && !strncmp(end_of_file, json, 3)){ log_fatal("ztee", "Invalid output format"); } if(!strncmp(end_of_file, csv, 3)) output_csv = 1; if(!strncmp(end_of_file, json, 3)) output_csv = 0; */ } void print_thread_error(char* string) { fprintf(stderr, "Could not create thread %s\n", string); return; } #define TIME_STR_LEN 20 typedef struct ztee_stats { // Read stats uint32_t total_read; uint32_t read_per_sec_avg; uint32_t read_last_sec; // Buffer stats uint32_t buffer_cur_size; uint32_t buffer_avg_size; uint64_t _buffer_size_sum; // Duration double _last_age; uint32_t time_past; char time_past_str[TIME_STR_LEN]; } stats_t; void update_stats(stats_t *stats, zqueue_t *queue) { double age = now() - start_time; double delta = age - stats->_last_age; stats->_last_age = age; stats->time_past = age; time_string((int)age, 0, stats->time_past_str, TIME_STR_LEN); uint32_t total_read = total_read_in; stats->read_last_sec = (total_read - stats->total_read) / delta; stats->total_read = total_read; stats->read_per_sec_avg = stats->total_read / age; stats->buffer_cur_size = get_size(queue); stats->_buffer_size_sum += stats->buffer_cur_size; stats->buffer_avg_size = stats->_buffer_size_sum / age; } void *monitor_ztee(void* arg) { zqueue_t *queue = (zqueue_t *) arg; stats_t *stats = xmalloc(sizeof(stats_t)); if (tconf.status_updates_file) { fprintf(tconf.status_updates_file, "time_past,total_read_in,read_in_last_sec,read_per_sec_avg," "buffer_current_size,buffer_avg_size\n"); fflush(tconf.status_updates_file); if (ferror(tconf.status_updates_file)) { log_fatal("ztee", "unable to write to status updates file"); } } while (!process_done) { sleep(1); update_stats(stats, queue); if (tconf.monitor) { lock_file(stderr); fprintf(stderr, "%5s read_rate: %u rows/s (avg %u rows/s), buffer_size: %u (avg %u)\n", stats->time_past_str, stats->read_last_sec, stats->read_per_sec_avg, stats->buffer_cur_size, stats->buffer_avg_size); fflush(stderr); unlock_file(stderr); if (ferror(stderr)) { log_fatal("ztee", "unable to write status updates to stderr"); } } if (tconf.status_updates_file) { fprintf(tconf.status_updates_file, "%u,%u,%u,%u,%u,%u\n", stats->time_past, stats->total_read, stats->read_last_sec, stats->read_per_sec_avg, stats->buffer_cur_size, stats->buffer_avg_size); fflush(tconf.status_updates_file); if (ferror(tconf.status_updates_file)) { log_fatal("ztee", "unable to write to status updates file"); } } } if (tconf.monitor) { lock_file(stderr); fflush(stderr); unlock_file(stderr); } if (tconf.status_updates_file) { fflush(tconf.status_updates_file); fclose(tconf.status_updates_file); } return NULL; }
666948.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strncmp.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cado-car <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/06/14 23:11:56 by cado-car #+# #+# */ /* Updated: 2021/06/14 23:11:57 by cado-car ### ########.fr */ /* */ /* ************************************************************************** */ int ft_strncmp(char *s1, char *s2, unsigned int n) { while ((*s1 && *s2) != '\0' && n > 0) { if (*s1 != *s2) break ; s1++; s2++; n--; } if (n == 0) return (0); return (*(unsigned char *)s1 - *(unsigned char *)s2); }
468596.c
#include "os.h" #include <libsec.h> // Because of the way that non multiple of 8 // buffers are handled, the decryptor must // be fed buffers of the same size as the // encryptor // If the length is not a multiple of 8, I encrypt // the overflow to be compatible with lacy's cryptlib void desCBCencrypt(uint8_t *p, int len, DESstate *s) { uint8_t *p2, *ip, *eip; for(; len >= 8; len -= 8){ p2 = p; ip = s->ivec; for(eip = ip+8; ip < eip; ) *p2++ ^= *ip++; block_cipher(s->expanded, p, 0); jehanne_memmove(s->ivec, p, 8); p += 8; } if(len > 0){ ip = s->ivec; block_cipher(s->expanded, ip, 0); for(eip = ip+len; ip < eip; ) *p++ ^= *ip++; } } void desCBCdecrypt(uint8_t *p, int len, DESstate *s) { uint8_t *ip, *eip, *tp; uint8_t tmp[8]; for(; len >= 8; len -= 8){ jehanne_memmove(tmp, p, 8); block_cipher(s->expanded, p, 1); tp = tmp; ip = s->ivec; for(eip = ip+8; ip < eip; ){ *p++ ^= *ip; *ip++ = *tp++; } } if(len > 0){ ip = s->ivec; block_cipher(s->expanded, ip, 0); for(eip = ip+len; ip < eip; ) *p++ ^= *ip++; } }
100789.c
/* Copyright (c) 2016-2017, The Tor Project, Inc. */ /* See LICENSE for licensing information */ /** * \file timers.c * \brief Wrapper around William Ahern's fast hierarchical timer wheel * implementation, to tie it in with a libevent backend. * * Only use these functions from the main thread. * * The main advantage of tor_timer_t over using libevent's timers is that * they're way more efficient if we need to have thousands or millions of * them. For more information, see * http://www.25thandclement.com/~william/projects/timeout.c.html * * Periodic timers are available in the backend, but I've turned them off. * We can turn them back on if needed. */ /* Notes: * * Having a way to free all timers on shutdown would free people from the * need to track them. Not sure if that's clever though. * * In an ideal world, Libevent would just switch to use this backend, and we * could throw this file away. But even if Libevent does switch, we'll be * stuck with legacy libevents for some time. */ #include "orconfig.h" #define TOR_TIMERS_PRIVATE #include "compat.h" #include "compat_libevent.h" #include "timers.h" #include "torlog.h" #include "util.h" #include <event2/event.h> struct timeout_cb { timer_cb_fn_t cb; void *arg; }; /* * These definitions are for timeouts.c and timeouts.h. */ #ifdef __GNUC__ /* We're not exposing any of the functions outside this file. */ #define TIMEOUT_PUBLIC __attribute__((__unused__)) static #else /* We're not exposing any of the functions outside this file. */ #define TIMEOUT_PUBLIC static #endif /* defined(__GNUC__) */ /* We're not using periodic events. */ #define TIMEOUT_DISABLE_INTERVALS /* We always know the global_timeouts object, so we don't need each timeout * to keep a pointer to it. */ #define TIMEOUT_DISABLE_RELATIVE_ACCESS /* We're providing our own struct timeout_cb. */ #define TIMEOUT_CB_OVERRIDE /* We're going to support timers that are pretty far out in advance. Making * this big can be inefficient, but having a significant number of timers * above TIMEOUT_MAX can also be super-inefficient. Choosing 5 here sets * timeout_max to 2^30 ticks, or 29 hours with our value for USEC_PER_TICK */ #define WHEEL_NUM 5 #include "src/ext/timeouts/timeout.c" static struct timeouts *global_timeouts = NULL; static struct event *global_timer_event = NULL; static monotime_t start_of_time; /** We need to choose this value carefully. Because we're using timer wheels, * it actually costs us to have extra resolution we don't use. So for now, * I'm going to define our resolution as .1 msec, and hope that's good enough. * * Note that two of the most popular libevent backends (epoll without timerfd, * and windows select), simply can't support sub-millisecond resolution, * do this is optimistic for a lot of users. */ #define USEC_PER_TICK 100 /** One million microseconds in a second */ #define USEC_PER_SEC 1000000 /** Check at least once every N seconds. */ #define MIN_CHECK_SECONDS 3600 /** Check at least once every N ticks. */ #define MIN_CHECK_TICKS \ (((timeout_t)MIN_CHECK_SECONDS) * (1000000 / USEC_PER_TICK)) /** * Convert the timeval in <b>tv</b> to a timeout_t, and return it. * * The output resolution is set by USEC_PER_TICK. Only use this to convert * delays to number of ticks; the time represented by 0 is undefined. */ static timeout_t tv_to_timeout(const struct timeval *tv) { uint64_t usec = tv->tv_usec; usec += ((uint64_t)USEC_PER_SEC) * tv->tv_sec; return usec / USEC_PER_TICK; } /** * Convert the timeout in <b>t</b> to a timeval in <b>tv_out</b>. Only * use this for delays, not absolute times. */ static void timeout_to_tv(timeout_t t, struct timeval *tv_out) { t *= USEC_PER_TICK; tv_out->tv_usec = (int)(t % USEC_PER_SEC); tv_out->tv_sec = (time_t)(t / USEC_PER_SEC); } /** * Update the timer <b>tv</b> to the current time in <b>tv</b>. */ static void timer_advance_to_cur_time(const monotime_t *now) { timeout_t cur_tick = CEIL_DIV(monotime_diff_usec(&start_of_time, now), USEC_PER_TICK); timeouts_update(global_timeouts, cur_tick); } /** * Adjust the time at which the libevent timer should fire based on * the next-expiring time in <b>global_timeouts</b> */ static void libevent_timer_reschedule(void) { monotime_t now; monotime_get(&now); timer_advance_to_cur_time(&now); timeout_t delay = timeouts_timeout(global_timeouts); struct timeval d; if (delay > MIN_CHECK_TICKS) delay = MIN_CHECK_TICKS; timeout_to_tv(delay, &d); event_add(global_timer_event, &d); } /** Run the callback of every timer that has expired, based on the current * output of monotime_get(). */ STATIC void timers_run_pending(void) { monotime_t now; monotime_get(&now); timer_advance_to_cur_time(&now); tor_timer_t *t; while ((t = timeouts_get(global_timeouts))) { t->callback.cb(t, t->callback.arg, &now); } } /** * Invoked when the libevent timer has expired: see which tor_timer_t events * have fired, activate their callbacks, and reschedule the libevent timer. */ static void libevent_timer_callback(evutil_socket_t fd, short what, void *arg) { (void)fd; (void)what; (void)arg; timers_run_pending(); libevent_timer_reschedule(); } /** * Initialize the timers subsystem. Requires that libevent has already been * initialized. */ void timers_initialize(void) { if (BUG(global_timeouts)) return; // LCOV_EXCL_LINE timeout_error_t err = 0; global_timeouts = timeouts_open(0, &err); if (!global_timeouts) { // LCOV_EXCL_START -- this can only fail on malloc failure. log_err(LD_BUG, "Unable to open timer backend: %s", strerror(err)); tor_assert(0); // LCOV_EXCL_STOP } monotime_init(); monotime_get(&start_of_time); struct event *timer_event; timer_event = tor_event_new(tor_libevent_get_base(), -1, 0, libevent_timer_callback, NULL); tor_assert(timer_event); global_timer_event = timer_event; libevent_timer_reschedule(); } /** * Release all storage held in the timers subsystem. Does not fire timers. */ void timers_shutdown(void) { if (global_timer_event) { tor_event_free(global_timer_event); global_timer_event = NULL; } if (global_timeouts) { timeouts_close(global_timeouts); global_timeouts = NULL; } } /** * Allocate and return a new timer, with given callback and argument. */ tor_timer_t * timer_new(timer_cb_fn_t cb, void *arg) { tor_timer_t *t = tor_malloc(sizeof(tor_timer_t)); timeout_init(t, 0); timer_set_cb(t, cb, arg); return t; } /** * Release all storage held by <b>t</b>, and unschedule it if was already * scheduled. */ void timer_free_(tor_timer_t *t) { if (! t) return; timeouts_del(global_timeouts, t); tor_free(t); } /** * Change the callback and argument associated with a timer <b>t</b>. */ void timer_set_cb(tor_timer_t *t, timer_cb_fn_t cb, void *arg) { t->callback.cb = cb; t->callback.arg = arg; } /** * Set *<b>cb_out</b> (if provided) to this timer's callback function, * and *<b>arg_out</b> (if provided) to this timer's callback argument. */ void timer_get_cb(const tor_timer_t *t, timer_cb_fn_t *cb_out, void **arg_out) { if (cb_out) *cb_out = t->callback.cb; if (arg_out) *arg_out = t->callback.arg; } /** * Schedule the timer t to fire at the current time plus a delay of * <b>delay</b> microseconds. All times are relative to monotime_get(). */ void timer_schedule(tor_timer_t *t, const struct timeval *tv) { const timeout_t delay = tv_to_timeout(tv); monotime_t now; monotime_get(&now); timer_advance_to_cur_time(&now); /* Take the old timeout value. */ timeout_t to = timeouts_timeout(global_timeouts); timeouts_add(global_timeouts, t, delay); /* Should we update the libevent timer? */ if (to <= delay) { return; /* we're already going to fire before this timer would trigger. */ } libevent_timer_reschedule(); } /** * Cancel the timer <b>t</b> if it is currently scheduled. (It's okay to call * this on an unscheduled timer. */ void timer_disable(tor_timer_t *t) { timeouts_del(global_timeouts, t); /* We don't reschedule the libevent timer here, since it's okay if it fires * early. */ }
994824.c
/* Copyright (c) 2013 The Squash Authors * * 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: * Evan Nemerson <[email protected]> */ #define _POSIX_C_SOURCE 199309L #include "timer.h" #if !defined(_MSC_VER) #include <unistd.h> #endif #include <stdlib.h> #include <stdio.h> #include <stdint.h> #define SQUASH_TIMER_METHOD_CLOCK_GETTIME 0 #define SQUASH_TIMER_METHOD_GETRUSAGE 1 #define SQUASH_TIMER_METHOD_CLOCK 2 #define SQUASH_TIMER_METHOD_GETPROCESSTIMES 3 #ifdef _WIN32 # define SQUASH_TIMER_METHOD SQUASH_TIMER_METHOD_GETPROCESSTIMES # include <windows.h> #endif #if !defined(SQUASH_TIMER_METHOD) && (_POSIX_TIMERS > 0) # ifdef _POSIX_CPUTIME # define SQUASH_TIMER_CPUTIME CLOCK_PROCESS_CPUTIME_ID # define SQUASH_TIMER_METHOD SQUASH_TIMER_METHOD_CLOCK_GETTIME # include <time.h> # elif defined(CLOCK_VIRTUAL) # define SQUASH_TIMER_CPUTIME CLOCK_VIRTUAL # define SQUASH_TIMER_METHOD SQUASH_TIMER_METHOD_CLOCK_GETTIME # include <time.h> # endif #endif #if !defined(SQUASH_TIMER_METHOD) # define SQUASH_TIMER_METHOD SQUASH_TIMER_METHOD_GETRUSAGE # include <sys/time.h> # include <sys/resource.h> #endif struct SquashTimer_s { double elapsed_cpu; double elapsed_wall; #if SQUASH_TIMER_METHOD == SQUASH_TIMER_METHOD_CLOCK_GETTIME struct timespec start_wall; struct timespec end_wall; struct timespec start_cpu; struct timespec end_cpu; #elif SQUASH_TIMER_METHOD == SQUASH_TIMER_METHOD_GETRUSAGE struct timeval start_wall; struct timeval end_wall; struct rusage start_cpu; struct rusage end_cpu; #elif SQUASH_TIMER_METHOD == SQUASH_TIMER_METHOD_GETPROCESSTIMES ULONGLONG start_wall; ULONGLONG end_wall; FILETIME start_cpu; FILETIME end_cpu; #endif }; /** * @defgroup SquashTimer SquashTimer * @brief A cross-platform timer * * @{ */ /** * @struct _SquashTimer * @brief Simple cross-platform timer * * Provides a timer for measuring the elapsed time between events, in * both wall-clock and CPU time. */ /** * @brief Create a new timer. * * Note that this function does not actually start timing. * * @return A new timer instance, or *NULL* on failure. * @see squash_timer_free */ SquashTimer* squash_timer_new (void) { SquashTimer* timer = (SquashTimer*) malloc (sizeof (SquashTimer)); squash_timer_reset (timer); return timer; } /** * @brief Free a timer. * * @param timer The timer. */ void squash_timer_free (SquashTimer* timer) { free (timer); } /** * @brief Begin or continue timing. * * @param timer The timer. */ void squash_timer_start (SquashTimer* timer) { #if SQUASH_TIMER_METHOD == SQUASH_TIMER_METHOD_CLOCK_GETTIME if (clock_gettime (CLOCK_REALTIME, &(timer->start_wall)) != 0) { fputs ("Unable to get wall clock time\n", stderr); exit (-1); } if (clock_gettime (SQUASH_TIMER_CPUTIME, &(timer->start_cpu)) != 0) { fputs ("Unable to get CPU clock time\n", stderr); exit (-1); } #elif SQUASH_TIMER_METHOD == SQUASH_TIMER_METHOD_GETRUSAGE if (gettimeofday(&(timer->start_wall), NULL) != 0) { fputs ("Unable to get time\n", stderr); } if (getrusage(RUSAGE_SELF, &(timer->start_cpu)) != 0) { fputs ("Unable to get CPU clock time\n", stderr); exit (-1); } #elif SQUASH_TIMER_METHOD == SQUASH_TIMER_METHOD_GETPROCESSTIMES #if _WIN32_WINNT >= 0x0600 timer->start_wall = GetTickCount64 (); #else timer->start_wall = GetTickCount (); #endif FILETIME CreationTime, ExitTime, KernelTime; if (!GetProcessTimes (GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &(timer->start_cpu))) { fputs ("Unable to get CPU clock time\n", stderr); } #endif } #if SQUASH_TIMER_METHOD == SQUASH_TIMER_METHOD_CLOCK_GETTIME static double squash_timer_timespec_elapsed (struct timespec* start, struct timespec* end) { return (double) (end->tv_sec - start->tv_sec) + (((double) (end->tv_nsec - start->tv_nsec)) / 1000000000); } #elif SQUASH_TIMER_METHOD == SQUASH_TIMER_METHOD_GETRUSAGE static double squash_timer_timeval_elapsed (struct timeval* start, struct timeval* end) { return (double) (end->tv_sec - start->tv_sec) + (((double) (end->tv_usec - start->tv_usec)) / 1000000); } static double squash_timer_rusage_elapsed (struct rusage* start, struct rusage* end) { return (double) ((end->ru_utime.tv_sec + end->ru_stime.tv_sec) - (start->ru_utime.tv_sec + start->ru_stime.tv_sec)) + (((double) ((end->ru_utime.tv_usec + end->ru_stime.tv_usec) - (start->ru_utime.tv_usec + start->ru_stime.tv_usec))) / 1000000); } #endif /** * @brief Stop timing. * * @param timer The timer. */ void squash_timer_stop (SquashTimer* timer) { #if SQUASH_TIMER_METHOD == SQUASH_TIMER_METHOD_CLOCK_GETTIME if (clock_gettime (SQUASH_TIMER_CPUTIME, &(timer->end_cpu)) != 0) { fputs ("Unable to get CPU clock time\n", stderr); exit (-1); } if (clock_gettime (CLOCK_REALTIME, &(timer->end_wall)) != 0) { fputs ("Unable to get wall clock time\n", stderr); exit (-1); } timer->elapsed_cpu += squash_timer_timespec_elapsed (&(timer->start_cpu), &(timer->end_cpu)); timer->elapsed_wall += squash_timer_timespec_elapsed (&(timer->start_wall), &(timer->end_wall)); #elif SQUASH_TIMER_METHOD == SQUASH_TIMER_METHOD_GETRUSAGE if (getrusage(RUSAGE_SELF, &(timer->end_cpu)) != 0) { fputs ("Unable to get CPU clock time\n", stderr); exit (-1); } if (gettimeofday(&(timer->end_wall), NULL) != 0) { fputs ("Unable to get time\n", stderr); exit (-1); } timer->elapsed_cpu += squash_timer_rusage_elapsed (&(timer->start_cpu), &(timer->end_cpu)); timer->elapsed_wall += squash_timer_timeval_elapsed (&(timer->start_wall), &(timer->end_wall)); #elif SQUASH_TIMER_METHOD == SQUASH_TIMER_METHOD_GETPROCESSTIMES FILETIME CreationTime, ExitTime, KernelTime; if (!GetProcessTimes (GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &(timer->end_cpu))) { fputs ("Unable to get CPU clock time\n", stderr); } #if _WIN32_WINNT >= 0x0600 timer->end_wall = GetTickCount64 (); #else timer->end_wall = GetTickCount (); if (timer->end_wall < timer->start_wall) { timer->end_wall += 0xffffffff; } #endif uint64_t start_cpu, end_cpu; start_cpu = timer->start_cpu.dwHighDateTime; start_cpu <<= sizeof (DWORD) * 8; start_cpu |= timer->start_cpu.dwLowDateTime; end_cpu = timer->end_cpu.dwHighDateTime; end_cpu <<= sizeof (DWORD) * 8; end_cpu |= timer->end_cpu.dwLowDateTime; timer->elapsed_cpu += ((double) (end_cpu - start_cpu)) / 10000000; timer->elapsed_wall += ((double) (timer->end_wall - timer->start_wall)) / 1000; #endif } /** * @brief Reset the timer. * * Resets the elapsed time to 0. * * @param timer The timer. */ void squash_timer_reset (SquashTimer* timer) { timer->elapsed_cpu = 0.0; timer->elapsed_wall = 0.0; } /** * @brief Restart the timer. * * This is a convenience wrapper for resetting the timer then starting * it. * * @param timer The timer. */ void squash_timer_restart (SquashTimer* timer) { squash_timer_reset (timer); squash_timer_start (timer); } /** * @brief Get the elapsed CPU time. * * @param timer The timer. * @return Number of seconds (CPU time) elapsed. */ double squash_timer_get_elapsed_cpu (SquashTimer* timer) { return timer->elapsed_cpu; } /** * @brief Get the elapsed wall-clock time. * * @param timer The timer. * @return Number of seconds (wall-clock time) elapsed. */ double squash_timer_get_elapsed_wall (SquashTimer* timer) { return timer->elapsed_wall; } /** * @} */
489358.c
/* Retrieves the size of the name * The returned size includes the end of string character * Returns 1 if successful or -1 on error */ int mount_file_entry_get_name_size( mount_file_entry_t *file_entry, size_t *string_size, libcerror_error_t **error ) { static char *function = "mount_file_entry_get_name_size"; if( file_entry == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid file entry.", function ); return( -1 ); } if( string_size == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid string size.", function ); return( -1 ); } *string_size = file_entry->name_size; return( 1 ); } /* Retrieves the name * The size should include the end of string character * Returns 1 if successful or -1 on error */ int mount_file_entry_get_name( mount_file_entry_t *file_entry, system_character_t *string, size_t string_size, libcerror_error_t **error ) { static char *function = "mount_file_entry_get_name"; if( file_entry == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid file entry.", function ); return( -1 ); } if( file_entry->name == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_MISSING, "%s: invalid file entry - missing name.", function ); return( -1 ); } if( string == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid string.", function ); return( -1 ); } if( string_size > (size_t) SSIZE_MAX ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM, "%s: invalid string size value exceeds maximum.", function ); return( -1 ); } if( string_size < file_entry->name_size ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_VALUE_TOO_SMALL, "%s: invalid string size value too small.", function ); return( -1 ); } if( system_string_copy( string, file_entry->name, file_entry->name_size ) == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_COPY_FAILED, "%s: unable to copy name.", function ); return( -1 ); } string[ file_entry->name_size - 1 ] = 0; return( 1 ); }
386453.c
/* Area: ffi_call, closure_call Purpose: Check structure passing with different structure size. Depending on the ABI. Double alignment check on darwin. Limitations: none. PR: none. Originator: <[email protected]> 20030915 */ /* { dg-do run } */ #include "ffitest.h" typedef struct cls_struct_18byte { double a; unsigned char b; unsigned char c; double d; } cls_struct_18byte; cls_struct_18byte cls_struct_18byte_fn(struct cls_struct_18byte a1, struct cls_struct_18byte a2) { struct cls_struct_18byte result; result.a = a1.a + a2.a; result.b = a1.b + a2.b; result.c = a1.c + a2.c; result.d = a1.d + a2.d; printf("%g %d %d %g %g %d %d %g: %g %d %d %g\n", a1.a, a1.b, a1.c, a1.d, a2.a, a2.b, a2.c, a2.d, result.a, result.b, result.c, result.d); return result; } static void cls_struct_18byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata __UNUSED__) { struct cls_struct_18byte a1, a2; a1 = *(struct cls_struct_18byte*)(args[0]); a2 = *(struct cls_struct_18byte*)(args[1]); *(cls_struct_18byte*)resp = cls_struct_18byte_fn(a1, a2); } int main (void) { ffi_cif cif; void *code; ffi_closure *pcl = (ffi_closure *)ffi_closure_alloc(sizeof(ffi_closure), &code); void* args_dbl[3]; ffi_type* cls_struct_fields[5]; ffi_type cls_struct_type; ffi_type* dbl_arg_types[3]; cls_struct_type.size = 0; cls_struct_type.alignment = 0; cls_struct_type.type = FFI_TYPE_STRUCT; cls_struct_type.elements = cls_struct_fields; struct cls_struct_18byte g_dbl = { 1.0, 127, 126, 3.0 }; struct cls_struct_18byte f_dbl = { 4.0, 125, 124, 5.0 }; struct cls_struct_18byte res_dbl; cls_struct_fields[0] = &ffi_type_double; cls_struct_fields[1] = &ffi_type_uchar; cls_struct_fields[2] = &ffi_type_uchar; cls_struct_fields[3] = &ffi_type_double; cls_struct_fields[4] = NULL; dbl_arg_types[0] = &cls_struct_type; dbl_arg_types[1] = &cls_struct_type; dbl_arg_types[2] = NULL; CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, dbl_arg_types) == FFI_OK); args_dbl[0] = &g_dbl; args_dbl[1] = &f_dbl; args_dbl[2] = NULL; ffi_call(&cif, FFI_FN(cls_struct_18byte_fn), &res_dbl, args_dbl); /* { dg-output "1 127 126 3 4 125 124 5: 5 252 250 8" } */ printf("res: %g %d %d %g\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d); /* { dg-output "\nres: 5 252 250 8" } */ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_18byte_gn, NULL, code) == FFI_OK); res_dbl = ((cls_struct_18byte(*)(cls_struct_18byte, cls_struct_18byte))(code))(g_dbl, f_dbl); /* { dg-output "\n1 127 126 3 4 125 124 5: 5 252 250 8" } */ printf("res: %g %d %d %g\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d); /* { dg-output "\nres: 5 252 250 8" } */ exit(0); }
241397.c
#include <stdio.h> int main(int argc, char *argv[]) { char numeroStr[3]; // 2 digitos + caracter terminal \0 int contador, numero; printf("Introduzca un numero: "); fgets(numeroStr, sizeof(numeroStr), stdin); for (contador = 1; contador <= numero; contador++ ) { if (contador % 2 == 0) { printf("%i es un numero par!", contador); } else { printf("%i es un numero impar!", contador); } } return 0; }
740842.c
// Copyright 2010 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // Coding trees and probas // // Author: Skal ([email protected]) #include "vp8i.h" #define USE_GENERIC_TREE #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #ifdef USE_GENERIC_TREE static const int8_t kYModesIntra4[18] = { -B_DC_PRED, 1, -B_TM_PRED, 2, -B_VE_PRED, 3, 4, 6, -B_HE_PRED, 5, -B_RD_PRED, -B_VR_PRED, -B_LD_PRED, 7, -B_VL_PRED, 8, -B_HD_PRED, -B_HU_PRED }; #endif #ifndef ONLY_KEYFRAME_CODE // inter prediction modes enum { LEFT4 = 0, ABOVE4 = 1, ZERO4 = 2, NEW4 = 3, NEARESTMV, NEARMV, ZEROMV, NEWMV, SPLITMV }; static const int8_t kYModesInter[8] = { -DC_PRED, 1, 2, 3, -V_PRED, -H_PRED, -TM_PRED, -B_PRED }; static const int8_t kMBSplit[6] = { -3, 1, -2, 2, -0, -1 }; static const int8_t kMVRef[8] = { -ZEROMV, 1, -NEARESTMV, 2, -NEARMV, 3, -NEWMV, -SPLITMV }; static const int8_t kMVRef4[6] = { -LEFT4, 1, -ABOVE4, 2, -ZERO4, -NEW4 }; #endif //------------------------------------------------------------------------------ // Default probabilities // Inter #ifndef ONLY_KEYFRAME_CODE static const uint8_t kYModeProbaInter0[4] = { 112, 86, 140, 37 }; static const uint8_t kUVModeProbaInter0[3] = { 162, 101, 204 }; static const uint8_t kMVProba0[2][NUM_MV_PROBAS] = { { 162, 128, 225, 146, 172, 147, 214, 39, 156, 128, 129, 132, 75, 145, 178, 206, 239, 254, 254 }, { 164, 128, 204, 170, 119, 235, 140, 230, 228, 128, 130, 130, 74, 148, 180, 203, 236, 254, 254 } }; #endif // Paragraph 13.5 static const uint8_t CoeffsProba0[NUM_TYPES][NUM_BANDS][NUM_CTX][NUM_PROBAS] = { // genereated using vp8_default_coef_probs() in entropy.c:129 { { { 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 }, { 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 }, { 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 } }, { { 253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128 }, { 189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128 }, { 106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128 } }, { { 1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128 }, { 181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128 }, { 78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128 }, }, { { 1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128 }, { 184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128 }, { 77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128 }, }, { { 1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128 }, { 170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128 }, { 37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128 } }, { { 1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128 }, { 207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128 }, { 102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128 } }, { { 1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128 }, { 177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128 }, { 80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128 } }, { { 1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128 }, { 246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128 }, { 255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 } } }, { { { 198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62 }, { 131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1 }, { 68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128 } }, { { 1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128 }, { 184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128 }, { 81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128 } }, { { 1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128 }, { 99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128 }, { 23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128 } }, { { 1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128 }, { 109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128 }, { 44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128 } }, { { 1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128 }, { 94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128 }, { 22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128 } }, { { 1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128 }, { 124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128 }, { 35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128 } }, { { 1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128 }, { 121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128 }, { 45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128 } }, { { 1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128 }, { 203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128 }, { 137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128 } } }, { { { 253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128 }, { 175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128 }, { 73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128 } }, { { 1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128 }, { 239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128 }, { 155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128 } }, { { 1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128 }, { 201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128 }, { 69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128 } }, { { 1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128 }, { 223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128 }, { 141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128 } }, { { 1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128 }, { 190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128 }, { 149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128 } }, { { 1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128 }, { 247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128 }, { 240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128 } }, { { 1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128 }, { 213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128 }, { 55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128 } }, { { 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 }, { 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 }, { 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 } } }, { { { 202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255 }, { 126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128 }, { 61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128 } }, { { 1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128 }, { 166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128 }, { 39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128 } }, { { 1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128 }, { 124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128 }, { 24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128 } }, { { 1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128 }, { 149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128 }, { 28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128 } }, { { 1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128 }, { 123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128 }, { 20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128 } }, { { 1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128 }, { 168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128 }, { 47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128 } }, { { 1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128 }, { 141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128 }, { 42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128 } }, { { 1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128 }, { 244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128 }, { 238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128 } } } }; // Paragraph 11.5 static const uint8_t kBModesProba[NUM_BMODES][NUM_BMODES][NUM_BMODES - 1] = { { { 231, 120, 48, 89, 115, 113, 120, 152, 112 }, { 152, 179, 64, 126, 170, 118, 46, 70, 95 }, { 175, 69, 143, 80, 85, 82, 72, 155, 103 }, { 56, 58, 10, 171, 218, 189, 17, 13, 152 }, { 114, 26, 17, 163, 44, 195, 21, 10, 173 }, { 121, 24, 80, 195, 26, 62, 44, 64, 85 }, { 144, 71, 10, 38, 171, 213, 144, 34, 26 }, { 170, 46, 55, 19, 136, 160, 33, 206, 71 }, { 63, 20, 8, 114, 114, 208, 12, 9, 226 }, { 81, 40, 11, 96, 182, 84, 29, 16, 36 } }, { { 134, 183, 89, 137, 98, 101, 106, 165, 148 }, { 72, 187, 100, 130, 157, 111, 32, 75, 80 }, { 66, 102, 167, 99, 74, 62, 40, 234, 128 }, { 41, 53, 9, 178, 241, 141, 26, 8, 107 }, { 74, 43, 26, 146, 73, 166, 49, 23, 157 }, { 65, 38, 105, 160, 51, 52, 31, 115, 128 }, { 104, 79, 12, 27, 217, 255, 87, 17, 7 }, { 87, 68, 71, 44, 114, 51, 15, 186, 23 }, { 47, 41, 14, 110, 182, 183, 21, 17, 194 }, { 66, 45, 25, 102, 197, 189, 23, 18, 22 } }, { { 88, 88, 147, 150, 42, 46, 45, 196, 205 }, { 43, 97, 183, 117, 85, 38, 35, 179, 61 }, { 39, 53, 200, 87, 26, 21, 43, 232, 171 }, { 56, 34, 51, 104, 114, 102, 29, 93, 77 }, { 39, 28, 85, 171, 58, 165, 90, 98, 64 }, { 34, 22, 116, 206, 23, 34, 43, 166, 73 }, { 107, 54, 32, 26, 51, 1, 81, 43, 31 }, { 68, 25, 106, 22, 64, 171, 36, 225, 114 }, { 34, 19, 21, 102, 132, 188, 16, 76, 124 }, { 62, 18, 78, 95, 85, 57, 50, 48, 51 } }, { { 193, 101, 35, 159, 215, 111, 89, 46, 111 }, { 60, 148, 31, 172, 219, 228, 21, 18, 111 }, { 112, 113, 77, 85, 179, 255, 38, 120, 114 }, { 40, 42, 1, 196, 245, 209, 10, 25, 109 }, { 88, 43, 29, 140, 166, 213, 37, 43, 154 }, { 61, 63, 30, 155, 67, 45, 68, 1, 209 }, { 100, 80, 8, 43, 154, 1, 51, 26, 71 }, { 142, 78, 78, 16, 255, 128, 34, 197, 171 }, { 41, 40, 5, 102, 211, 183, 4, 1, 221 }, { 51, 50, 17, 168, 209, 192, 23, 25, 82 } }, { { 138, 31, 36, 171, 27, 166, 38, 44, 229 }, { 67, 87, 58, 169, 82, 115, 26, 59, 179 }, { 63, 59, 90, 180, 59, 166, 93, 73, 154 }, { 40, 40, 21, 116, 143, 209, 34, 39, 175 }, { 47, 15, 16, 183, 34, 223, 49, 45, 183 }, { 46, 17, 33, 183, 6, 98, 15, 32, 183 }, { 57, 46, 22, 24, 128, 1, 54, 17, 37 }, { 65, 32, 73, 115, 28, 128, 23, 128, 205 }, { 40, 3, 9, 115, 51, 192, 18, 6, 223 }, { 87, 37, 9, 115, 59, 77, 64, 21, 47 } }, { { 104, 55, 44, 218, 9, 54, 53, 130, 226 }, { 64, 90, 70, 205, 40, 41, 23, 26, 57 }, { 54, 57, 112, 184, 5, 41, 38, 166, 213 }, { 30, 34, 26, 133, 152, 116, 10, 32, 134 }, { 39, 19, 53, 221, 26, 114, 32, 73, 255 }, { 31, 9, 65, 234, 2, 15, 1, 118, 73 }, { 75, 32, 12, 51, 192, 255, 160, 43, 51 }, { 88, 31, 35, 67, 102, 85, 55, 186, 85 }, { 56, 21, 23, 111, 59, 205, 45, 37, 192 }, { 55, 38, 70, 124, 73, 102, 1, 34, 98 } }, { { 125, 98, 42, 88, 104, 85, 117, 175, 82 }, { 95, 84, 53, 89, 128, 100, 113, 101, 45 }, { 75, 79, 123, 47, 51, 128, 81, 171, 1 }, { 57, 17, 5, 71, 102, 57, 53, 41, 49 }, { 38, 33, 13, 121, 57, 73, 26, 1, 85 }, { 41, 10, 67, 138, 77, 110, 90, 47, 114 }, { 115, 21, 2, 10, 102, 255, 166, 23, 6 }, { 101, 29, 16, 10, 85, 128, 101, 196, 26 }, { 57, 18, 10, 102, 102, 213, 34, 20, 43 }, { 117, 20, 15, 36, 163, 128, 68, 1, 26 } }, { { 102, 61, 71, 37, 34, 53, 31, 243, 192 }, { 69, 60, 71, 38, 73, 119, 28, 222, 37 }, { 68, 45, 128, 34, 1, 47, 11, 245, 171 }, { 62, 17, 19, 70, 146, 85, 55, 62, 70 }, { 37, 43, 37, 154, 100, 163, 85, 160, 1 }, { 63, 9, 92, 136, 28, 64, 32, 201, 85 }, { 75, 15, 9, 9, 64, 255, 184, 119, 16 }, { 86, 6, 28, 5, 64, 255, 25, 248, 1 }, { 56, 8, 17, 132, 137, 255, 55, 116, 128 }, { 58, 15, 20, 82, 135, 57, 26, 121, 40 } }, { { 164, 50, 31, 137, 154, 133, 25, 35, 218 }, { 51, 103, 44, 131, 131, 123, 31, 6, 158 }, { 86, 40, 64, 135, 148, 224, 45, 183, 128 }, { 22, 26, 17, 131, 240, 154, 14, 1, 209 }, { 45, 16, 21, 91, 64, 222, 7, 1, 197 }, { 56, 21, 39, 155, 60, 138, 23, 102, 213 }, { 83, 12, 13, 54, 192, 255, 68, 47, 28 }, { 85, 26, 85, 85, 128, 128, 32, 146, 171 }, { 18, 11, 7, 63, 144, 171, 4, 4, 246 }, { 35, 27, 10, 146, 174, 171, 12, 26, 128 } }, { { 190, 80, 35, 99, 180, 80, 126, 54, 45 }, { 85, 126, 47, 87, 176, 51, 41, 20, 32 }, { 101, 75, 128, 139, 118, 146, 116, 128, 85 }, { 56, 41, 15, 176, 236, 85, 37, 9, 62 }, { 71, 30, 17, 119, 118, 255, 17, 18, 138 }, { 101, 38, 60, 138, 55, 70, 43, 26, 142 }, { 146, 36, 19, 30, 171, 255, 97, 27, 20 }, { 138, 45, 61, 62, 219, 1, 81, 188, 64 }, { 32, 41, 20, 117, 151, 142, 20, 21, 163 }, { 112, 19, 12, 61, 195, 128, 48, 4, 24 } } }; void VP8ResetProba(VP8Proba* const proba) { memset(proba->segments_, 255u, sizeof(proba->segments_)); memcpy(proba->coeffs_, CoeffsProba0, sizeof(CoeffsProba0)); #ifndef ONLY_KEYFRAME_CODE memcpy(proba->mv_, kMVProba0, sizeof(kMVProba0)); memcpy(proba->ymode_, kYModeProbaInter0, sizeof(kYModeProbaInter0)); memcpy(proba->uvmode_, kUVModeProbaInter0, sizeof(kUVModeProbaInter0)); #endif } void VP8ParseIntraMode(VP8BitReader* const br, VP8Decoder* const dec) { uint8_t* const top = dec->intra_t_ + 4 * dec->mb_x_; uint8_t* const left = dec->intra_l_; // Hardcoded 16x16 intra-mode decision tree. dec->is_i4x4_ = !VP8GetBit(br, 145); // decide for B_PRED first if (!dec->is_i4x4_) { const int ymode = VP8GetBit(br, 156) ? (VP8GetBit(br, 128) ? TM_PRED : H_PRED) : (VP8GetBit(br, 163) ? V_PRED : DC_PRED); dec->imodes_[0] = ymode; memset(top, ymode, 4 * sizeof(top[0])); memset(left, ymode, 4 * sizeof(left[0])); } else { uint8_t* modes = dec->imodes_; int y; for (y = 0; y < 4; ++y) { int ymode = left[y]; int x; for (x = 0; x < 4; ++x) { const uint8_t* const prob = kBModesProba[top[x]][ymode]; #ifdef USE_GENERIC_TREE // Generic tree-parsing int i = 0; do { i = kYModesIntra4[2 * i + VP8GetBit(br, prob[i])]; } while (i > 0); ymode = -i; #else // Hardcoded tree parsing ymode = !VP8GetBit(br, prob[0]) ? B_DC_PRED : !VP8GetBit(br, prob[1]) ? B_TM_PRED : !VP8GetBit(br, prob[2]) ? B_VE_PRED : !VP8GetBit(br, prob[3]) ? (!VP8GetBit(br, prob[4]) ? B_HE_PRED : (!VP8GetBit(br, prob[5]) ? B_RD_PRED : B_VR_PRED)) : (!VP8GetBit(br, prob[6]) ? B_LD_PRED : (!VP8GetBit(br, prob[7]) ? B_VL_PRED : (!VP8GetBit(br, prob[8]) ? B_HD_PRED : B_HU_PRED))); #endif // USE_GENERIC_TREE top[x] = ymode; *modes++ = ymode; } left[y] = ymode; } } // Hardcoded UVMode decision tree dec->uvmode_ = !VP8GetBit(br, 142) ? DC_PRED : !VP8GetBit(br, 114) ? V_PRED : VP8GetBit(br, 183) ? TM_PRED : H_PRED; } //------------------------------------------------------------------------------ // Paragraph 13 static const uint8_t CoeffsUpdateProba[NUM_TYPES][NUM_BANDS][NUM_CTX][NUM_PROBAS] = { { { { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255 }, { 249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255 }, { 234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255 }, { 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255 }, { 239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 }, { 254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255 }, { 251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 }, { 251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255 }, { 254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255 }, { 250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255 }, { 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } } }, { { { 217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255 }, { 234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255 } }, { { 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255 }, { 238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255 }, { 249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 }, { 252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255 }, { 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255 }, { 250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } } }, { { { 186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255 }, { 234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255 }, { 251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255 } }, { { 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 }, { 236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 }, { 251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255 } }, { { 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255 }, { 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } } }, { { { 248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255 }, { 248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255 }, { 246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255 }, { 252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255 } }, { { 255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255 }, { 248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255 }, { 253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255 }, { 245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255 }, { 253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255 }, { 252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255 }, { 250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } }, { { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }, { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } } } }; #ifndef ONLY_KEYFRAME_CODE static const uint8_t MVUpdateProba[2][NUM_MV_PROBAS] = { { 237, 246, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 250, 252, 254, 254 }, { 231, 243, 245, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 251, 251, 254, 254, 254 } }; #endif // Paragraph 9.9 void VP8ParseProba(VP8BitReader* const br, VP8Decoder* const dec) { VP8Proba* const proba = &dec->proba_; int t, b, c, p; for (t = 0; t < NUM_TYPES; ++t) { for (b = 0; b < NUM_BANDS; ++b) { for (c = 0; c < NUM_CTX; ++c) { for (p = 0; p < NUM_PROBAS; ++p) { if (VP8GetBit(br, CoeffsUpdateProba[t][b][c][p])) { proba->coeffs_[t][b][c][p] = VP8GetValue(br, 8); } } } } } dec->use_skip_proba_ = VP8Get(br); if (dec->use_skip_proba_) { dec->skip_p_ = VP8GetValue(br, 8); } #ifndef ONLY_KEYFRAME_CODE if (!dec->frm_hdr_.key_frame_) { int i; dec->intra_p_ = VP8GetValue(br, 8); dec->last_p_ = VP8GetValue(br, 8); dec->golden_p_ = VP8GetValue(br, 8); if (VP8Get(br)) { // update y-mode for (i = 0; i < 4; ++i) { proba->ymode_[i] = VP8GetValue(br, 8); } } if (VP8Get(br)) { // update uv-mode for (i = 0; i < 3; ++i) { proba->uvmode_[i] = VP8GetValue(br, 8); } } // update MV for (i = 0; i < 2; ++i) { int k; for (k = 0; k < NUM_MV_PROBAS; ++k) { if (VP8GetBit(br, MVUpdateProba[i][k])) { const int v = VP8GetValue(br, 7); proba->mv_[i][k] = v ? v << 1 : 1; } } } } #endif } #if defined(__cplusplus) || defined(c_plusplus) } // extern "C" #endif
729188.c
/* * MikroSDK - MikroE Software Development Kit * Copyright© 2020 MikroElektronika d.o.o. * * 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. */ /*! * \file * */ #include "llci2c.h" // ------------------------------------------------ PUBLIC FUNCTION DEFINITIONS void llci2c_cfg_setup ( llci2c_cfg_t *cfg ) { // Communication gpio pins cfg->scl = HAL_PIN_NC; cfg->sda = HAL_PIN_NC; cfg->i2c_speed = I2C_MASTER_SPEED_STANDARD; cfg->i2c_address = 0x48; } LLCI2C_RETVAL llci2c_init ( llci2c_t *ctx, llci2c_cfg_t *cfg ) { i2c_master_config_t i2c_cfg; i2c_master_configure_default( &i2c_cfg ); i2c_cfg.speed = cfg->i2c_speed; i2c_cfg.scl = cfg->scl; i2c_cfg.sda = cfg->sda; ctx->slave_address = cfg->i2c_address; if ( i2c_master_open( &ctx->i2c, &i2c_cfg ) == I2C_MASTER_ERROR ) { return LLCI2C_INIT_ERROR; } i2c_master_set_slave_address( &ctx->i2c, ctx->slave_address ); i2c_master_set_speed( &ctx->i2c, cfg->i2c_speed ); return LLCI2C_OK; } void llci2c_generic_write ( llci2c_t *ctx, uint8_t reg, uint8_t *data_buf, uint8_t len ) { uint8_t tx_buf[ 256 ]; uint8_t cnt; tx_buf[ 0 ] = reg; for ( cnt = 1; cnt <= len; cnt++ ) { tx_buf[ cnt ] = data_buf[ cnt - 1 ]; } i2c_master_write( &ctx->i2c, tx_buf, len + 1 ); } void llci2c_generic_read ( llci2c_t *ctx, uint8_t reg, uint8_t *data_buf, uint8_t len ) { i2c_master_write_then_read( &ctx->i2c, &reg, 1, data_buf, len ); } // ------------------------------------------------------------------------- END
588514.c
// SPDX-License-Identifier: GPL-2.0-only /* * QLogic Fibre Channel HBA Driver * Copyright (c) 2003-2014 QLogic Corporation */ #include "qla_def.h" #include "qla_target.h" #include <linux/blkdev.h> #include <linux/delay.h> #include <scsi/scsi_tcq.h> /** * qla2x00_get_cmd_direction() - Determine control_flag data direction. * @sp: SCSI command * * Returns the proper CF_* direction based on CDB. */ static inline uint16_t qla2x00_get_cmd_direction(srb_t *sp) { uint16_t cflags; struct scsi_cmnd *cmd = GET_CMD_SP(sp); struct scsi_qla_host *vha = sp->vha; cflags = 0; /* Set transfer direction */ if (cmd->sc_data_direction == DMA_TO_DEVICE) { cflags = CF_WRITE; vha->qla_stats.output_bytes += scsi_bufflen(cmd); vha->qla_stats.output_requests++; } else if (cmd->sc_data_direction == DMA_FROM_DEVICE) { cflags = CF_READ; vha->qla_stats.input_bytes += scsi_bufflen(cmd); vha->qla_stats.input_requests++; } return (cflags); } /** * qla2x00_calc_iocbs_32() - Determine number of Command Type 2 and * Continuation Type 0 IOCBs to allocate. * * @dsds: number of data segment descriptors needed * * Returns the number of IOCB entries needed to store @dsds. */ uint16_t qla2x00_calc_iocbs_32(uint16_t dsds) { uint16_t iocbs; iocbs = 1; if (dsds > 3) { iocbs += (dsds - 3) / 7; if ((dsds - 3) % 7) iocbs++; } return (iocbs); } /** * qla2x00_calc_iocbs_64() - Determine number of Command Type 3 and * Continuation Type 1 IOCBs to allocate. * * @dsds: number of data segment descriptors needed * * Returns the number of IOCB entries needed to store @dsds. */ uint16_t qla2x00_calc_iocbs_64(uint16_t dsds) { uint16_t iocbs; iocbs = 1; if (dsds > 2) { iocbs += (dsds - 2) / 5; if ((dsds - 2) % 5) iocbs++; } return (iocbs); } /** * qla2x00_prep_cont_type0_iocb() - Initialize a Continuation Type 0 IOCB. * @vha: HA context * * Returns a pointer to the Continuation Type 0 IOCB packet. */ static inline cont_entry_t * qla2x00_prep_cont_type0_iocb(struct scsi_qla_host *vha) { cont_entry_t *cont_pkt; struct req_que *req = vha->req; /* Adjust ring index. */ req->ring_index++; if (req->ring_index == req->length) { req->ring_index = 0; req->ring_ptr = req->ring; } else { req->ring_ptr++; } cont_pkt = (cont_entry_t *)req->ring_ptr; /* Load packet defaults. */ put_unaligned_le32(CONTINUE_TYPE, &cont_pkt->entry_type); return (cont_pkt); } /** * qla2x00_prep_cont_type1_iocb() - Initialize a Continuation Type 1 IOCB. * @vha: HA context * @req: request queue * * Returns a pointer to the continuation type 1 IOCB packet. */ cont_a64_entry_t * qla2x00_prep_cont_type1_iocb(scsi_qla_host_t *vha, struct req_que *req) { cont_a64_entry_t *cont_pkt; /* Adjust ring index. */ req->ring_index++; if (req->ring_index == req->length) { req->ring_index = 0; req->ring_ptr = req->ring; } else { req->ring_ptr++; } cont_pkt = (cont_a64_entry_t *)req->ring_ptr; /* Load packet defaults. */ put_unaligned_le32(IS_QLAFX00(vha->hw) ? CONTINUE_A64_TYPE_FX00 : CONTINUE_A64_TYPE, &cont_pkt->entry_type); return (cont_pkt); } inline int qla24xx_configure_prot_mode(srb_t *sp, uint16_t *fw_prot_opts) { struct scsi_cmnd *cmd = GET_CMD_SP(sp); /* We always use DIFF Bundling for best performance */ *fw_prot_opts = 0; /* Translate SCSI opcode to a protection opcode */ switch (scsi_get_prot_op(cmd)) { case SCSI_PROT_READ_STRIP: *fw_prot_opts |= PO_MODE_DIF_REMOVE; break; case SCSI_PROT_WRITE_INSERT: *fw_prot_opts |= PO_MODE_DIF_INSERT; break; case SCSI_PROT_READ_INSERT: *fw_prot_opts |= PO_MODE_DIF_INSERT; break; case SCSI_PROT_WRITE_STRIP: *fw_prot_opts |= PO_MODE_DIF_REMOVE; break; case SCSI_PROT_READ_PASS: case SCSI_PROT_WRITE_PASS: if (cmd->prot_flags & SCSI_PROT_IP_CHECKSUM) *fw_prot_opts |= PO_MODE_DIF_TCP_CKSUM; else *fw_prot_opts |= PO_MODE_DIF_PASS; break; default: /* Normal Request */ *fw_prot_opts |= PO_MODE_DIF_PASS; break; } if (!(cmd->prot_flags & SCSI_PROT_GUARD_CHECK)) *fw_prot_opts |= PO_DISABLE_GUARD_CHECK; return scsi_prot_sg_count(cmd); } /* * qla2x00_build_scsi_iocbs_32() - Build IOCB command utilizing 32bit * capable IOCB types. * * @sp: SRB command to process * @cmd_pkt: Command type 2 IOCB * @tot_dsds: Total number of segments to transfer */ void qla2x00_build_scsi_iocbs_32(srb_t *sp, cmd_entry_t *cmd_pkt, uint16_t tot_dsds) { uint16_t avail_dsds; struct dsd32 *cur_dsd; scsi_qla_host_t *vha; struct scsi_cmnd *cmd; struct scatterlist *sg; int i; cmd = GET_CMD_SP(sp); /* Update entry type to indicate Command Type 2 IOCB */ put_unaligned_le32(COMMAND_TYPE, &cmd_pkt->entry_type); /* No data transfer */ if (!scsi_bufflen(cmd) || cmd->sc_data_direction == DMA_NONE) { cmd_pkt->byte_count = cpu_to_le32(0); return; } vha = sp->vha; cmd_pkt->control_flags |= cpu_to_le16(qla2x00_get_cmd_direction(sp)); /* Three DSDs are available in the Command Type 2 IOCB */ avail_dsds = ARRAY_SIZE(cmd_pkt->dsd32); cur_dsd = cmd_pkt->dsd32; /* Load data segments */ scsi_for_each_sg(cmd, sg, tot_dsds, i) { cont_entry_t *cont_pkt; /* Allocate additional continuation packets? */ if (avail_dsds == 0) { /* * Seven DSDs are available in the Continuation * Type 0 IOCB. */ cont_pkt = qla2x00_prep_cont_type0_iocb(vha); cur_dsd = cont_pkt->dsd; avail_dsds = ARRAY_SIZE(cont_pkt->dsd); } append_dsd32(&cur_dsd, sg); avail_dsds--; } } /** * qla2x00_build_scsi_iocbs_64() - Build IOCB command utilizing 64bit * capable IOCB types. * * @sp: SRB command to process * @cmd_pkt: Command type 3 IOCB * @tot_dsds: Total number of segments to transfer */ void qla2x00_build_scsi_iocbs_64(srb_t *sp, cmd_entry_t *cmd_pkt, uint16_t tot_dsds) { uint16_t avail_dsds; struct dsd64 *cur_dsd; scsi_qla_host_t *vha; struct scsi_cmnd *cmd; struct scatterlist *sg; int i; cmd = GET_CMD_SP(sp); /* Update entry type to indicate Command Type 3 IOCB */ put_unaligned_le32(COMMAND_A64_TYPE, &cmd_pkt->entry_type); /* No data transfer */ if (!scsi_bufflen(cmd) || cmd->sc_data_direction == DMA_NONE) { cmd_pkt->byte_count = cpu_to_le32(0); return; } vha = sp->vha; cmd_pkt->control_flags |= cpu_to_le16(qla2x00_get_cmd_direction(sp)); /* Two DSDs are available in the Command Type 3 IOCB */ avail_dsds = ARRAY_SIZE(cmd_pkt->dsd64); cur_dsd = cmd_pkt->dsd64; /* Load data segments */ scsi_for_each_sg(cmd, sg, tot_dsds, i) { cont_a64_entry_t *cont_pkt; /* Allocate additional continuation packets? */ if (avail_dsds == 0) { /* * Five DSDs are available in the Continuation * Type 1 IOCB. */ cont_pkt = qla2x00_prep_cont_type1_iocb(vha, vha->req); cur_dsd = cont_pkt->dsd; avail_dsds = ARRAY_SIZE(cont_pkt->dsd); } append_dsd64(&cur_dsd, sg); avail_dsds--; } } /* * Find the first handle that is not in use, starting from * req->current_outstanding_cmd + 1. The caller must hold the lock that is * associated with @req. */ uint32_t qla2xxx_get_next_handle(struct req_que *req) { uint32_t index, handle = req->current_outstanding_cmd; for (index = 1; index < req->num_outstanding_cmds; index++) { handle++; if (handle == req->num_outstanding_cmds) handle = 1; if (!req->outstanding_cmds[handle]) return handle; } return 0; } /** * qla2x00_start_scsi() - Send a SCSI command to the ISP * @sp: command to send to the ISP * * Returns non-zero if a failure occurred, else zero. */ int qla2x00_start_scsi(srb_t *sp) { int nseg; unsigned long flags; scsi_qla_host_t *vha; struct scsi_cmnd *cmd; uint32_t *clr_ptr; uint32_t handle; cmd_entry_t *cmd_pkt; uint16_t cnt; uint16_t req_cnt; uint16_t tot_dsds; struct device_reg_2xxx __iomem *reg; struct qla_hw_data *ha; struct req_que *req; struct rsp_que *rsp; /* Setup device pointers. */ vha = sp->vha; ha = vha->hw; reg = &ha->iobase->isp; cmd = GET_CMD_SP(sp); req = ha->req_q_map[0]; rsp = ha->rsp_q_map[0]; /* So we know we haven't pci_map'ed anything yet */ tot_dsds = 0; /* Send marker if required */ if (vha->marker_needed != 0) { if (qla2x00_marker(vha, ha->base_qpair, 0, 0, MK_SYNC_ALL) != QLA_SUCCESS) { return (QLA_FUNCTION_FAILED); } vha->marker_needed = 0; } /* Acquire ring specific lock */ spin_lock_irqsave(&ha->hardware_lock, flags); handle = qla2xxx_get_next_handle(req); if (handle == 0) goto queuing_error; /* Map the sg table so we have an accurate count of sg entries needed */ if (scsi_sg_count(cmd)) { nseg = dma_map_sg(&ha->pdev->dev, scsi_sglist(cmd), scsi_sg_count(cmd), cmd->sc_data_direction); if (unlikely(!nseg)) goto queuing_error; } else nseg = 0; tot_dsds = nseg; /* Calculate the number of request entries needed. */ req_cnt = ha->isp_ops->calc_req_entries(tot_dsds); if (req->cnt < (req_cnt + 2)) { cnt = rd_reg_word_relaxed(ISP_REQ_Q_OUT(ha, reg)); if (req->ring_index < cnt) req->cnt = cnt - req->ring_index; else req->cnt = req->length - (req->ring_index - cnt); /* If still no head room then bail out */ if (req->cnt < (req_cnt + 2)) goto queuing_error; } /* Build command packet */ req->current_outstanding_cmd = handle; req->outstanding_cmds[handle] = sp; sp->handle = handle; cmd->host_scribble = (unsigned char *)(unsigned long)handle; req->cnt -= req_cnt; cmd_pkt = (cmd_entry_t *)req->ring_ptr; cmd_pkt->handle = handle; /* Zero out remaining portion of packet. */ clr_ptr = (uint32_t *)cmd_pkt + 2; memset(clr_ptr, 0, REQUEST_ENTRY_SIZE - 8); cmd_pkt->dseg_count = cpu_to_le16(tot_dsds); /* Set target ID and LUN number*/ SET_TARGET_ID(ha, cmd_pkt->target, sp->fcport->loop_id); cmd_pkt->lun = cpu_to_le16(cmd->device->lun); cmd_pkt->control_flags = cpu_to_le16(CF_SIMPLE_TAG); /* Load SCSI command packet. */ memcpy(cmd_pkt->scsi_cdb, cmd->cmnd, cmd->cmd_len); cmd_pkt->byte_count = cpu_to_le32((uint32_t)scsi_bufflen(cmd)); /* Build IOCB segments */ ha->isp_ops->build_iocbs(sp, cmd_pkt, tot_dsds); /* Set total data segment count. */ cmd_pkt->entry_count = (uint8_t)req_cnt; wmb(); /* Adjust ring index. */ req->ring_index++; if (req->ring_index == req->length) { req->ring_index = 0; req->ring_ptr = req->ring; } else req->ring_ptr++; sp->flags |= SRB_DMA_VALID; /* Set chip new ring index. */ wrt_reg_word(ISP_REQ_Q_IN(ha, reg), req->ring_index); rd_reg_word_relaxed(ISP_REQ_Q_IN(ha, reg)); /* PCI Posting. */ /* Manage unprocessed RIO/ZIO commands in response queue. */ if (vha->flags.process_response_queue && rsp->ring_ptr->signature != RESPONSE_PROCESSED) qla2x00_process_response_queue(rsp); spin_unlock_irqrestore(&ha->hardware_lock, flags); return (QLA_SUCCESS); queuing_error: if (tot_dsds) scsi_dma_unmap(cmd); spin_unlock_irqrestore(&ha->hardware_lock, flags); return (QLA_FUNCTION_FAILED); } /** * qla2x00_start_iocbs() - Execute the IOCB command * @vha: HA context * @req: request queue */ void qla2x00_start_iocbs(struct scsi_qla_host *vha, struct req_que *req) { struct qla_hw_data *ha = vha->hw; device_reg_t *reg = ISP_QUE_REG(ha, req->id); if (IS_P3P_TYPE(ha)) { qla82xx_start_iocbs(vha); } else { /* Adjust ring index. */ req->ring_index++; if (req->ring_index == req->length) { req->ring_index = 0; req->ring_ptr = req->ring; } else req->ring_ptr++; /* Set chip new ring index. */ if (ha->mqenable || IS_QLA27XX(ha) || IS_QLA28XX(ha)) { wrt_reg_dword(req->req_q_in, req->ring_index); } else if (IS_QLA83XX(ha)) { wrt_reg_dword(req->req_q_in, req->ring_index); rd_reg_dword_relaxed(&ha->iobase->isp24.hccr); } else if (IS_QLAFX00(ha)) { wrt_reg_dword(&reg->ispfx00.req_q_in, req->ring_index); rd_reg_dword_relaxed(&reg->ispfx00.req_q_in); QLAFX00_SET_HST_INTR(ha, ha->rqstq_intr_code); } else if (IS_FWI2_CAPABLE(ha)) { wrt_reg_dword(&reg->isp24.req_q_in, req->ring_index); rd_reg_dword_relaxed(&reg->isp24.req_q_in); } else { wrt_reg_word(ISP_REQ_Q_IN(ha, &reg->isp), req->ring_index); rd_reg_word_relaxed(ISP_REQ_Q_IN(ha, &reg->isp)); } } } /** * __qla2x00_marker() - Send a marker IOCB to the firmware. * @vha: HA context * @qpair: queue pair pointer * @loop_id: loop ID * @lun: LUN * @type: marker modifier * * Can be called from both normal and interrupt context. * * Returns non-zero if a failure occurred, else zero. */ static int __qla2x00_marker(struct scsi_qla_host *vha, struct qla_qpair *qpair, uint16_t loop_id, uint64_t lun, uint8_t type) { mrk_entry_t *mrk; struct mrk_entry_24xx *mrk24 = NULL; struct req_que *req = qpair->req; struct qla_hw_data *ha = vha->hw; scsi_qla_host_t *base_vha = pci_get_drvdata(ha->pdev); mrk = (mrk_entry_t *)__qla2x00_alloc_iocbs(qpair, NULL); if (mrk == NULL) { ql_log(ql_log_warn, base_vha, 0x3026, "Failed to allocate Marker IOCB.\n"); return (QLA_FUNCTION_FAILED); } mrk->entry_type = MARKER_TYPE; mrk->modifier = type; if (type != MK_SYNC_ALL) { if (IS_FWI2_CAPABLE(ha)) { mrk24 = (struct mrk_entry_24xx *) mrk; mrk24->nport_handle = cpu_to_le16(loop_id); int_to_scsilun(lun, (struct scsi_lun *)&mrk24->lun); host_to_fcp_swap(mrk24->lun, sizeof(mrk24->lun)); mrk24->vp_index = vha->vp_idx; mrk24->handle = make_handle(req->id, mrk24->handle); } else { SET_TARGET_ID(ha, mrk->target, loop_id); mrk->lun = cpu_to_le16((uint16_t)lun); } } wmb(); qla2x00_start_iocbs(vha, req); return (QLA_SUCCESS); } int qla2x00_marker(struct scsi_qla_host *vha, struct qla_qpair *qpair, uint16_t loop_id, uint64_t lun, uint8_t type) { int ret; unsigned long flags = 0; spin_lock_irqsave(qpair->qp_lock_ptr, flags); ret = __qla2x00_marker(vha, qpair, loop_id, lun, type); spin_unlock_irqrestore(qpair->qp_lock_ptr, flags); return (ret); } /* * qla2x00_issue_marker * * Issue marker * Caller CAN have hardware lock held as specified by ha_locked parameter. * Might release it, then reaquire. */ int qla2x00_issue_marker(scsi_qla_host_t *vha, int ha_locked) { if (ha_locked) { if (__qla2x00_marker(vha, vha->hw->base_qpair, 0, 0, MK_SYNC_ALL) != QLA_SUCCESS) return QLA_FUNCTION_FAILED; } else { if (qla2x00_marker(vha, vha->hw->base_qpair, 0, 0, MK_SYNC_ALL) != QLA_SUCCESS) return QLA_FUNCTION_FAILED; } vha->marker_needed = 0; return QLA_SUCCESS; } static inline int qla24xx_build_scsi_type_6_iocbs(srb_t *sp, struct cmd_type_6 *cmd_pkt, uint16_t tot_dsds) { struct dsd64 *cur_dsd = NULL, *next_dsd; scsi_qla_host_t *vha; struct qla_hw_data *ha; struct scsi_cmnd *cmd; struct scatterlist *cur_seg; uint8_t avail_dsds; uint8_t first_iocb = 1; uint32_t dsd_list_len; struct dsd_dma *dsd_ptr; struct ct6_dsd *ctx; struct qla_qpair *qpair = sp->qpair; cmd = GET_CMD_SP(sp); /* Update entry type to indicate Command Type 3 IOCB */ put_unaligned_le32(COMMAND_TYPE_6, &cmd_pkt->entry_type); /* No data transfer */ if (!scsi_bufflen(cmd) || cmd->sc_data_direction == DMA_NONE) { cmd_pkt->byte_count = cpu_to_le32(0); return 0; } vha = sp->vha; ha = vha->hw; /* Set transfer direction */ if (cmd->sc_data_direction == DMA_TO_DEVICE) { cmd_pkt->control_flags = cpu_to_le16(CF_WRITE_DATA); qpair->counters.output_bytes += scsi_bufflen(cmd); qpair->counters.output_requests++; } else if (cmd->sc_data_direction == DMA_FROM_DEVICE) { cmd_pkt->control_flags = cpu_to_le16(CF_READ_DATA); qpair->counters.input_bytes += scsi_bufflen(cmd); qpair->counters.input_requests++; } cur_seg = scsi_sglist(cmd); ctx = sp->u.scmd.ct6_ctx; while (tot_dsds) { avail_dsds = (tot_dsds > QLA_DSDS_PER_IOCB) ? QLA_DSDS_PER_IOCB : tot_dsds; tot_dsds -= avail_dsds; dsd_list_len = (avail_dsds + 1) * QLA_DSD_SIZE; dsd_ptr = list_first_entry(&ha->gbl_dsd_list, struct dsd_dma, list); next_dsd = dsd_ptr->dsd_addr; list_del(&dsd_ptr->list); ha->gbl_dsd_avail--; list_add_tail(&dsd_ptr->list, &ctx->dsd_list); ctx->dsd_use_cnt++; ha->gbl_dsd_inuse++; if (first_iocb) { first_iocb = 0; put_unaligned_le64(dsd_ptr->dsd_list_dma, &cmd_pkt->fcp_dsd.address); cmd_pkt->fcp_dsd.length = cpu_to_le32(dsd_list_len); } else { put_unaligned_le64(dsd_ptr->dsd_list_dma, &cur_dsd->address); cur_dsd->length = cpu_to_le32(dsd_list_len); cur_dsd++; } cur_dsd = next_dsd; while (avail_dsds) { append_dsd64(&cur_dsd, cur_seg); cur_seg = sg_next(cur_seg); avail_dsds--; } } /* Null termination */ cur_dsd->address = 0; cur_dsd->length = 0; cur_dsd++; cmd_pkt->control_flags |= cpu_to_le16(CF_DATA_SEG_DESCR_ENABLE); return 0; } /* * qla24xx_calc_dsd_lists() - Determine number of DSD list required * for Command Type 6. * * @dsds: number of data segment descriptors needed * * Returns the number of dsd list needed to store @dsds. */ static inline uint16_t qla24xx_calc_dsd_lists(uint16_t dsds) { uint16_t dsd_lists = 0; dsd_lists = (dsds/QLA_DSDS_PER_IOCB); if (dsds % QLA_DSDS_PER_IOCB) dsd_lists++; return dsd_lists; } /** * qla24xx_build_scsi_iocbs() - Build IOCB command utilizing Command Type 7 * IOCB types. * * @sp: SRB command to process * @cmd_pkt: Command type 3 IOCB * @tot_dsds: Total number of segments to transfer * @req: pointer to request queue */ inline void qla24xx_build_scsi_iocbs(srb_t *sp, struct cmd_type_7 *cmd_pkt, uint16_t tot_dsds, struct req_que *req) { uint16_t avail_dsds; struct dsd64 *cur_dsd; scsi_qla_host_t *vha; struct scsi_cmnd *cmd; struct scatterlist *sg; int i; struct qla_qpair *qpair = sp->qpair; cmd = GET_CMD_SP(sp); /* Update entry type to indicate Command Type 3 IOCB */ put_unaligned_le32(COMMAND_TYPE_7, &cmd_pkt->entry_type); /* No data transfer */ if (!scsi_bufflen(cmd) || cmd->sc_data_direction == DMA_NONE) { cmd_pkt->byte_count = cpu_to_le32(0); return; } vha = sp->vha; /* Set transfer direction */ if (cmd->sc_data_direction == DMA_TO_DEVICE) { cmd_pkt->task_mgmt_flags = cpu_to_le16(TMF_WRITE_DATA); qpair->counters.output_bytes += scsi_bufflen(cmd); qpair->counters.output_requests++; } else if (cmd->sc_data_direction == DMA_FROM_DEVICE) { cmd_pkt->task_mgmt_flags = cpu_to_le16(TMF_READ_DATA); qpair->counters.input_bytes += scsi_bufflen(cmd); qpair->counters.input_requests++; } /* One DSD is available in the Command Type 3 IOCB */ avail_dsds = 1; cur_dsd = &cmd_pkt->dsd; /* Load data segments */ scsi_for_each_sg(cmd, sg, tot_dsds, i) { cont_a64_entry_t *cont_pkt; /* Allocate additional continuation packets? */ if (avail_dsds == 0) { /* * Five DSDs are available in the Continuation * Type 1 IOCB. */ cont_pkt = qla2x00_prep_cont_type1_iocb(vha, req); cur_dsd = cont_pkt->dsd; avail_dsds = ARRAY_SIZE(cont_pkt->dsd); } append_dsd64(&cur_dsd, sg); avail_dsds--; } } struct fw_dif_context { __le32 ref_tag; __le16 app_tag; uint8_t ref_tag_mask[4]; /* Validation/Replacement Mask*/ uint8_t app_tag_mask[2]; /* Validation/Replacement Mask*/ }; /* * qla24xx_set_t10dif_tags_from_cmd - Extract Ref and App tags from SCSI command * */ static inline void qla24xx_set_t10dif_tags(srb_t *sp, struct fw_dif_context *pkt, unsigned int protcnt) { struct scsi_cmnd *cmd = GET_CMD_SP(sp); pkt->ref_tag = cpu_to_le32(scsi_prot_ref_tag(cmd)); if (cmd->prot_flags & SCSI_PROT_REF_CHECK && qla2x00_hba_err_chk_enabled(sp)) { pkt->ref_tag_mask[0] = 0xff; pkt->ref_tag_mask[1] = 0xff; pkt->ref_tag_mask[2] = 0xff; pkt->ref_tag_mask[3] = 0xff; } pkt->app_tag = cpu_to_le16(0); pkt->app_tag_mask[0] = 0x0; pkt->app_tag_mask[1] = 0x0; } int qla24xx_get_one_block_sg(uint32_t blk_sz, struct qla2_sgx *sgx, uint32_t *partial) { struct scatterlist *sg; uint32_t cumulative_partial, sg_len; dma_addr_t sg_dma_addr; if (sgx->num_bytes == sgx->tot_bytes) return 0; sg = sgx->cur_sg; cumulative_partial = sgx->tot_partial; sg_dma_addr = sg_dma_address(sg); sg_len = sg_dma_len(sg); sgx->dma_addr = sg_dma_addr + sgx->bytes_consumed; if ((cumulative_partial + (sg_len - sgx->bytes_consumed)) >= blk_sz) { sgx->dma_len = (blk_sz - cumulative_partial); sgx->tot_partial = 0; sgx->num_bytes += blk_sz; *partial = 0; } else { sgx->dma_len = sg_len - sgx->bytes_consumed; sgx->tot_partial += sgx->dma_len; *partial = 1; } sgx->bytes_consumed += sgx->dma_len; if (sg_len == sgx->bytes_consumed) { sg = sg_next(sg); sgx->num_sg++; sgx->cur_sg = sg; sgx->bytes_consumed = 0; } return 1; } int qla24xx_walk_and_build_sglist_no_difb(struct qla_hw_data *ha, srb_t *sp, struct dsd64 *dsd, uint16_t tot_dsds, struct qla_tc_param *tc) { void *next_dsd; uint8_t avail_dsds = 0; uint32_t dsd_list_len; struct dsd_dma *dsd_ptr; struct scatterlist *sg_prot; struct dsd64 *cur_dsd = dsd; uint16_t used_dsds = tot_dsds; uint32_t prot_int; /* protection interval */ uint32_t partial; struct qla2_sgx sgx; dma_addr_t sle_dma; uint32_t sle_dma_len, tot_prot_dma_len = 0; struct scsi_cmnd *cmd; memset(&sgx, 0, sizeof(struct qla2_sgx)); if (sp) { cmd = GET_CMD_SP(sp); prot_int = scsi_prot_interval(cmd); sgx.tot_bytes = scsi_bufflen(cmd); sgx.cur_sg = scsi_sglist(cmd); sgx.sp = sp; sg_prot = scsi_prot_sglist(cmd); } else if (tc) { prot_int = tc->blk_sz; sgx.tot_bytes = tc->bufflen; sgx.cur_sg = tc->sg; sg_prot = tc->prot_sg; } else { BUG(); return 1; } while (qla24xx_get_one_block_sg(prot_int, &sgx, &partial)) { sle_dma = sgx.dma_addr; sle_dma_len = sgx.dma_len; alloc_and_fill: /* Allocate additional continuation packets? */ if (avail_dsds == 0) { avail_dsds = (used_dsds > QLA_DSDS_PER_IOCB) ? QLA_DSDS_PER_IOCB : used_dsds; dsd_list_len = (avail_dsds + 1) * 12; used_dsds -= avail_dsds; /* allocate tracking DS */ dsd_ptr = kzalloc(sizeof(struct dsd_dma), GFP_ATOMIC); if (!dsd_ptr) return 1; /* allocate new list */ dsd_ptr->dsd_addr = next_dsd = dma_pool_alloc(ha->dl_dma_pool, GFP_ATOMIC, &dsd_ptr->dsd_list_dma); if (!next_dsd) { /* * Need to cleanup only this dsd_ptr, rest * will be done by sp_free_dma() */ kfree(dsd_ptr); return 1; } if (sp) { list_add_tail(&dsd_ptr->list, &sp->u.scmd.crc_ctx->dsd_list); sp->flags |= SRB_CRC_CTX_DSD_VALID; } else { list_add_tail(&dsd_ptr->list, &(tc->ctx->dsd_list)); *tc->ctx_dsd_alloced = 1; } /* add new list to cmd iocb or last list */ put_unaligned_le64(dsd_ptr->dsd_list_dma, &cur_dsd->address); cur_dsd->length = cpu_to_le32(dsd_list_len); cur_dsd = next_dsd; } put_unaligned_le64(sle_dma, &cur_dsd->address); cur_dsd->length = cpu_to_le32(sle_dma_len); cur_dsd++; avail_dsds--; if (partial == 0) { /* Got a full protection interval */ sle_dma = sg_dma_address(sg_prot) + tot_prot_dma_len; sle_dma_len = 8; tot_prot_dma_len += sle_dma_len; if (tot_prot_dma_len == sg_dma_len(sg_prot)) { tot_prot_dma_len = 0; sg_prot = sg_next(sg_prot); } partial = 1; /* So as to not re-enter this block */ goto alloc_and_fill; } } /* Null termination */ cur_dsd->address = 0; cur_dsd->length = 0; cur_dsd++; return 0; } int qla24xx_walk_and_build_sglist(struct qla_hw_data *ha, srb_t *sp, struct dsd64 *dsd, uint16_t tot_dsds, struct qla_tc_param *tc) { void *next_dsd; uint8_t avail_dsds = 0; uint32_t dsd_list_len; struct dsd_dma *dsd_ptr; struct scatterlist *sg, *sgl; struct dsd64 *cur_dsd = dsd; int i; uint16_t used_dsds = tot_dsds; struct scsi_cmnd *cmd; if (sp) { cmd = GET_CMD_SP(sp); sgl = scsi_sglist(cmd); } else if (tc) { sgl = tc->sg; } else { BUG(); return 1; } for_each_sg(sgl, sg, tot_dsds, i) { /* Allocate additional continuation packets? */ if (avail_dsds == 0) { avail_dsds = (used_dsds > QLA_DSDS_PER_IOCB) ? QLA_DSDS_PER_IOCB : used_dsds; dsd_list_len = (avail_dsds + 1) * 12; used_dsds -= avail_dsds; /* allocate tracking DS */ dsd_ptr = kzalloc(sizeof(struct dsd_dma), GFP_ATOMIC); if (!dsd_ptr) return 1; /* allocate new list */ dsd_ptr->dsd_addr = next_dsd = dma_pool_alloc(ha->dl_dma_pool, GFP_ATOMIC, &dsd_ptr->dsd_list_dma); if (!next_dsd) { /* * Need to cleanup only this dsd_ptr, rest * will be done by sp_free_dma() */ kfree(dsd_ptr); return 1; } if (sp) { list_add_tail(&dsd_ptr->list, &sp->u.scmd.crc_ctx->dsd_list); sp->flags |= SRB_CRC_CTX_DSD_VALID; } else { list_add_tail(&dsd_ptr->list, &(tc->ctx->dsd_list)); *tc->ctx_dsd_alloced = 1; } /* add new list to cmd iocb or last list */ put_unaligned_le64(dsd_ptr->dsd_list_dma, &cur_dsd->address); cur_dsd->length = cpu_to_le32(dsd_list_len); cur_dsd = next_dsd; } append_dsd64(&cur_dsd, sg); avail_dsds--; } /* Null termination */ cur_dsd->address = 0; cur_dsd->length = 0; cur_dsd++; return 0; } int qla24xx_walk_and_build_prot_sglist(struct qla_hw_data *ha, srb_t *sp, struct dsd64 *cur_dsd, uint16_t tot_dsds, struct qla_tgt_cmd *tc) { struct dsd_dma *dsd_ptr = NULL, *dif_dsd, *nxt_dsd; struct scatterlist *sg, *sgl; struct crc_context *difctx = NULL; struct scsi_qla_host *vha; uint dsd_list_len; uint avail_dsds = 0; uint used_dsds = tot_dsds; bool dif_local_dma_alloc = false; bool direction_to_device = false; int i; if (sp) { struct scsi_cmnd *cmd = GET_CMD_SP(sp); sgl = scsi_prot_sglist(cmd); vha = sp->vha; difctx = sp->u.scmd.crc_ctx; direction_to_device = cmd->sc_data_direction == DMA_TO_DEVICE; ql_dbg(ql_dbg_tgt + ql_dbg_verbose, vha, 0xe021, "%s: scsi_cmnd: %p, crc_ctx: %p, sp: %p\n", __func__, cmd, difctx, sp); } else if (tc) { vha = tc->vha; sgl = tc->prot_sg; difctx = tc->ctx; direction_to_device = tc->dma_data_direction == DMA_TO_DEVICE; } else { BUG(); return 1; } ql_dbg(ql_dbg_tgt + ql_dbg_verbose, vha, 0xe021, "%s: enter (write=%u)\n", __func__, direction_to_device); /* if initiator doing write or target doing read */ if (direction_to_device) { for_each_sg(sgl, sg, tot_dsds, i) { u64 sle_phys = sg_phys(sg); /* If SGE addr + len flips bits in upper 32-bits */ if (MSD(sle_phys + sg->length) ^ MSD(sle_phys)) { ql_dbg(ql_dbg_tgt + ql_dbg_verbose, vha, 0xe022, "%s: page boundary crossing (phys=%llx len=%x)\n", __func__, sle_phys, sg->length); if (difctx) { ha->dif_bundle_crossed_pages++; dif_local_dma_alloc = true; } else { ql_dbg(ql_dbg_tgt + ql_dbg_verbose, vha, 0xe022, "%s: difctx pointer is NULL\n", __func__); } break; } } ha->dif_bundle_writes++; } else { ha->dif_bundle_reads++; } if (ql2xdifbundlinginternalbuffers) dif_local_dma_alloc = direction_to_device; if (dif_local_dma_alloc) { u32 track_difbundl_buf = 0; u32 ldma_sg_len = 0; u8 ldma_needed = 1; difctx->no_dif_bundl = 0; difctx->dif_bundl_len = 0; /* Track DSD buffers */ INIT_LIST_HEAD(&difctx->ldif_dsd_list); /* Track local DMA buffers */ INIT_LIST_HEAD(&difctx->ldif_dma_hndl_list); for_each_sg(sgl, sg, tot_dsds, i) { u32 sglen = sg_dma_len(sg); ql_dbg(ql_dbg_tgt + ql_dbg_verbose, vha, 0xe023, "%s: sg[%x] (phys=%llx sglen=%x) ldma_sg_len: %x dif_bundl_len: %x ldma_needed: %x\n", __func__, i, (u64)sg_phys(sg), sglen, ldma_sg_len, difctx->dif_bundl_len, ldma_needed); while (sglen) { u32 xfrlen = 0; if (ldma_needed) { /* * Allocate list item to store * the DMA buffers */ dsd_ptr = kzalloc(sizeof(*dsd_ptr), GFP_ATOMIC); if (!dsd_ptr) { ql_dbg(ql_dbg_tgt, vha, 0xe024, "%s: failed alloc dsd_ptr\n", __func__); return 1; } ha->dif_bundle_kallocs++; /* allocate dma buffer */ dsd_ptr->dsd_addr = dma_pool_alloc (ha->dif_bundl_pool, GFP_ATOMIC, &dsd_ptr->dsd_list_dma); if (!dsd_ptr->dsd_addr) { ql_dbg(ql_dbg_tgt, vha, 0xe024, "%s: failed alloc ->dsd_ptr\n", __func__); /* * need to cleanup only this * dsd_ptr rest will be done * by sp_free_dma() */ kfree(dsd_ptr); ha->dif_bundle_kallocs--; return 1; } ha->dif_bundle_dma_allocs++; ldma_needed = 0; difctx->no_dif_bundl++; list_add_tail(&dsd_ptr->list, &difctx->ldif_dma_hndl_list); } /* xfrlen is min of dma pool size and sglen */ xfrlen = (sglen > (DIF_BUNDLING_DMA_POOL_SIZE - ldma_sg_len)) ? DIF_BUNDLING_DMA_POOL_SIZE - ldma_sg_len : sglen; /* replace with local allocated dma buffer */ sg_pcopy_to_buffer(sgl, sg_nents(sgl), dsd_ptr->dsd_addr + ldma_sg_len, xfrlen, difctx->dif_bundl_len); difctx->dif_bundl_len += xfrlen; sglen -= xfrlen; ldma_sg_len += xfrlen; if (ldma_sg_len == DIF_BUNDLING_DMA_POOL_SIZE || sg_is_last(sg)) { ldma_needed = 1; ldma_sg_len = 0; } } } track_difbundl_buf = used_dsds = difctx->no_dif_bundl; ql_dbg(ql_dbg_tgt + ql_dbg_verbose, vha, 0xe025, "dif_bundl_len=%x, no_dif_bundl=%x track_difbundl_buf: %x\n", difctx->dif_bundl_len, difctx->no_dif_bundl, track_difbundl_buf); if (sp) sp->flags |= SRB_DIF_BUNDL_DMA_VALID; else tc->prot_flags = DIF_BUNDL_DMA_VALID; list_for_each_entry_safe(dif_dsd, nxt_dsd, &difctx->ldif_dma_hndl_list, list) { u32 sglen = (difctx->dif_bundl_len > DIF_BUNDLING_DMA_POOL_SIZE) ? DIF_BUNDLING_DMA_POOL_SIZE : difctx->dif_bundl_len; BUG_ON(track_difbundl_buf == 0); /* Allocate additional continuation packets? */ if (avail_dsds == 0) { ql_dbg(ql_dbg_tgt + ql_dbg_verbose, vha, 0xe024, "%s: adding continuation iocb's\n", __func__); avail_dsds = (used_dsds > QLA_DSDS_PER_IOCB) ? QLA_DSDS_PER_IOCB : used_dsds; dsd_list_len = (avail_dsds + 1) * 12; used_dsds -= avail_dsds; /* allocate tracking DS */ dsd_ptr = kzalloc(sizeof(*dsd_ptr), GFP_ATOMIC); if (!dsd_ptr) { ql_dbg(ql_dbg_tgt, vha, 0xe026, "%s: failed alloc dsd_ptr\n", __func__); return 1; } ha->dif_bundle_kallocs++; difctx->no_ldif_dsd++; /* allocate new list */ dsd_ptr->dsd_addr = dma_pool_alloc(ha->dl_dma_pool, GFP_ATOMIC, &dsd_ptr->dsd_list_dma); if (!dsd_ptr->dsd_addr) { ql_dbg(ql_dbg_tgt, vha, 0xe026, "%s: failed alloc ->dsd_addr\n", __func__); /* * need to cleanup only this dsd_ptr * rest will be done by sp_free_dma() */ kfree(dsd_ptr); ha->dif_bundle_kallocs--; return 1; } ha->dif_bundle_dma_allocs++; if (sp) { list_add_tail(&dsd_ptr->list, &difctx->ldif_dsd_list); sp->flags |= SRB_CRC_CTX_DSD_VALID; } else { list_add_tail(&dsd_ptr->list, &difctx->ldif_dsd_list); tc->ctx_dsd_alloced = 1; } /* add new list to cmd iocb or last list */ put_unaligned_le64(dsd_ptr->dsd_list_dma, &cur_dsd->address); cur_dsd->length = cpu_to_le32(dsd_list_len); cur_dsd = dsd_ptr->dsd_addr; } put_unaligned_le64(dif_dsd->dsd_list_dma, &cur_dsd->address); cur_dsd->length = cpu_to_le32(sglen); cur_dsd++; avail_dsds--; difctx->dif_bundl_len -= sglen; track_difbundl_buf--; } ql_dbg(ql_dbg_tgt + ql_dbg_verbose, vha, 0xe026, "%s: no_ldif_dsd:%x, no_dif_bundl:%x\n", __func__, difctx->no_ldif_dsd, difctx->no_dif_bundl); } else { for_each_sg(sgl, sg, tot_dsds, i) { /* Allocate additional continuation packets? */ if (avail_dsds == 0) { avail_dsds = (used_dsds > QLA_DSDS_PER_IOCB) ? QLA_DSDS_PER_IOCB : used_dsds; dsd_list_len = (avail_dsds + 1) * 12; used_dsds -= avail_dsds; /* allocate tracking DS */ dsd_ptr = kzalloc(sizeof(*dsd_ptr), GFP_ATOMIC); if (!dsd_ptr) { ql_dbg(ql_dbg_tgt + ql_dbg_verbose, vha, 0xe027, "%s: failed alloc dsd_dma...\n", __func__); return 1; } /* allocate new list */ dsd_ptr->dsd_addr = dma_pool_alloc(ha->dl_dma_pool, GFP_ATOMIC, &dsd_ptr->dsd_list_dma); if (!dsd_ptr->dsd_addr) { /* need to cleanup only this dsd_ptr */ /* rest will be done by sp_free_dma() */ kfree(dsd_ptr); return 1; } if (sp) { list_add_tail(&dsd_ptr->list, &difctx->dsd_list); sp->flags |= SRB_CRC_CTX_DSD_VALID; } else { list_add_tail(&dsd_ptr->list, &difctx->dsd_list); tc->ctx_dsd_alloced = 1; } /* add new list to cmd iocb or last list */ put_unaligned_le64(dsd_ptr->dsd_list_dma, &cur_dsd->address); cur_dsd->length = cpu_to_le32(dsd_list_len); cur_dsd = dsd_ptr->dsd_addr; } append_dsd64(&cur_dsd, sg); avail_dsds--; } } /* Null termination */ cur_dsd->address = 0; cur_dsd->length = 0; cur_dsd++; return 0; } /** * qla24xx_build_scsi_crc_2_iocbs() - Build IOCB command utilizing Command * Type 6 IOCB types. * * @sp: SRB command to process * @cmd_pkt: Command type 3 IOCB * @tot_dsds: Total number of segments to transfer * @tot_prot_dsds: Total number of segments with protection information * @fw_prot_opts: Protection options to be passed to firmware */ static inline int qla24xx_build_scsi_crc_2_iocbs(srb_t *sp, struct cmd_type_crc_2 *cmd_pkt, uint16_t tot_dsds, uint16_t tot_prot_dsds, uint16_t fw_prot_opts) { struct dsd64 *cur_dsd; __be32 *fcp_dl; scsi_qla_host_t *vha; struct scsi_cmnd *cmd; uint32_t total_bytes = 0; uint32_t data_bytes; uint32_t dif_bytes; uint8_t bundling = 1; uint16_t blk_size; struct crc_context *crc_ctx_pkt = NULL; struct qla_hw_data *ha; uint8_t additional_fcpcdb_len; uint16_t fcp_cmnd_len; struct fcp_cmnd *fcp_cmnd; dma_addr_t crc_ctx_dma; cmd = GET_CMD_SP(sp); /* Update entry type to indicate Command Type CRC_2 IOCB */ put_unaligned_le32(COMMAND_TYPE_CRC_2, &cmd_pkt->entry_type); vha = sp->vha; ha = vha->hw; /* No data transfer */ data_bytes = scsi_bufflen(cmd); if (!data_bytes || cmd->sc_data_direction == DMA_NONE) { cmd_pkt->byte_count = cpu_to_le32(0); return QLA_SUCCESS; } cmd_pkt->vp_index = sp->vha->vp_idx; /* Set transfer direction */ if (cmd->sc_data_direction == DMA_TO_DEVICE) { cmd_pkt->control_flags = cpu_to_le16(CF_WRITE_DATA); } else if (cmd->sc_data_direction == DMA_FROM_DEVICE) { cmd_pkt->control_flags = cpu_to_le16(CF_READ_DATA); } if ((scsi_get_prot_op(cmd) == SCSI_PROT_READ_INSERT) || (scsi_get_prot_op(cmd) == SCSI_PROT_WRITE_STRIP) || (scsi_get_prot_op(cmd) == SCSI_PROT_READ_STRIP) || (scsi_get_prot_op(cmd) == SCSI_PROT_WRITE_INSERT)) bundling = 0; /* Allocate CRC context from global pool */ crc_ctx_pkt = sp->u.scmd.crc_ctx = dma_pool_zalloc(ha->dl_dma_pool, GFP_ATOMIC, &crc_ctx_dma); if (!crc_ctx_pkt) goto crc_queuing_error; crc_ctx_pkt->crc_ctx_dma = crc_ctx_dma; sp->flags |= SRB_CRC_CTX_DMA_VALID; /* Set handle */ crc_ctx_pkt->handle = cmd_pkt->handle; INIT_LIST_HEAD(&crc_ctx_pkt->dsd_list); qla24xx_set_t10dif_tags(sp, (struct fw_dif_context *) &crc_ctx_pkt->ref_tag, tot_prot_dsds); put_unaligned_le64(crc_ctx_dma, &cmd_pkt->crc_context_address); cmd_pkt->crc_context_len = cpu_to_le16(CRC_CONTEXT_LEN_FW); /* Determine SCSI command length -- align to 4 byte boundary */ if (cmd->cmd_len > 16) { additional_fcpcdb_len = cmd->cmd_len - 16; if ((cmd->cmd_len % 4) != 0) { /* SCSI cmd > 16 bytes must be multiple of 4 */ goto crc_queuing_error; } fcp_cmnd_len = 12 + cmd->cmd_len + 4; } else { additional_fcpcdb_len = 0; fcp_cmnd_len = 12 + 16 + 4; } fcp_cmnd = &crc_ctx_pkt->fcp_cmnd; fcp_cmnd->additional_cdb_len = additional_fcpcdb_len; if (cmd->sc_data_direction == DMA_TO_DEVICE) fcp_cmnd->additional_cdb_len |= 1; else if (cmd->sc_data_direction == DMA_FROM_DEVICE) fcp_cmnd->additional_cdb_len |= 2; int_to_scsilun(cmd->device->lun, &fcp_cmnd->lun); memcpy(fcp_cmnd->cdb, cmd->cmnd, cmd->cmd_len); cmd_pkt->fcp_cmnd_dseg_len = cpu_to_le16(fcp_cmnd_len); put_unaligned_le64(crc_ctx_dma + CRC_CONTEXT_FCPCMND_OFF, &cmd_pkt->fcp_cmnd_dseg_address); fcp_cmnd->task_management = 0; fcp_cmnd->task_attribute = TSK_SIMPLE; cmd_pkt->fcp_rsp_dseg_len = 0; /* Let response come in status iocb */ /* Compute dif len and adjust data len to incude protection */ dif_bytes = 0; blk_size = cmd->device->sector_size; dif_bytes = (data_bytes / blk_size) * 8; switch (scsi_get_prot_op(GET_CMD_SP(sp))) { case SCSI_PROT_READ_INSERT: case SCSI_PROT_WRITE_STRIP: total_bytes = data_bytes; data_bytes += dif_bytes; break; case SCSI_PROT_READ_STRIP: case SCSI_PROT_WRITE_INSERT: case SCSI_PROT_READ_PASS: case SCSI_PROT_WRITE_PASS: total_bytes = data_bytes + dif_bytes; break; default: BUG(); } if (!qla2x00_hba_err_chk_enabled(sp)) fw_prot_opts |= 0x10; /* Disable Guard tag checking */ /* HBA error checking enabled */ else if (IS_PI_UNINIT_CAPABLE(ha)) { if ((scsi_get_prot_type(GET_CMD_SP(sp)) == SCSI_PROT_DIF_TYPE1) || (scsi_get_prot_type(GET_CMD_SP(sp)) == SCSI_PROT_DIF_TYPE2)) fw_prot_opts |= BIT_10; else if (scsi_get_prot_type(GET_CMD_SP(sp)) == SCSI_PROT_DIF_TYPE3) fw_prot_opts |= BIT_11; } if (!bundling) { cur_dsd = &crc_ctx_pkt->u.nobundling.data_dsd[0]; } else { /* * Configure Bundling if we need to fetch interlaving * protection PCI accesses */ fw_prot_opts |= PO_ENABLE_DIF_BUNDLING; crc_ctx_pkt->u.bundling.dif_byte_count = cpu_to_le32(dif_bytes); crc_ctx_pkt->u.bundling.dseg_count = cpu_to_le16(tot_dsds - tot_prot_dsds); cur_dsd = &crc_ctx_pkt->u.bundling.data_dsd[0]; } /* Finish the common fields of CRC pkt */ crc_ctx_pkt->blk_size = cpu_to_le16(blk_size); crc_ctx_pkt->prot_opts = cpu_to_le16(fw_prot_opts); crc_ctx_pkt->byte_count = cpu_to_le32(data_bytes); crc_ctx_pkt->guard_seed = cpu_to_le16(0); /* Fibre channel byte count */ cmd_pkt->byte_count = cpu_to_le32(total_bytes); fcp_dl = (__be32 *)(crc_ctx_pkt->fcp_cmnd.cdb + 16 + additional_fcpcdb_len); *fcp_dl = htonl(total_bytes); if (!data_bytes || cmd->sc_data_direction == DMA_NONE) { cmd_pkt->byte_count = cpu_to_le32(0); return QLA_SUCCESS; } /* Walks data segments */ cmd_pkt->control_flags |= cpu_to_le16(CF_DATA_SEG_DESCR_ENABLE); if (!bundling && tot_prot_dsds) { if (qla24xx_walk_and_build_sglist_no_difb(ha, sp, cur_dsd, tot_dsds, NULL)) goto crc_queuing_error; } else if (qla24xx_walk_and_build_sglist(ha, sp, cur_dsd, (tot_dsds - tot_prot_dsds), NULL)) goto crc_queuing_error; if (bundling && tot_prot_dsds) { /* Walks dif segments */ cmd_pkt->control_flags |= cpu_to_le16(CF_DIF_SEG_DESCR_ENABLE); cur_dsd = &crc_ctx_pkt->u.bundling.dif_dsd; if (qla24xx_walk_and_build_prot_sglist(ha, sp, cur_dsd, tot_prot_dsds, NULL)) goto crc_queuing_error; } return QLA_SUCCESS; crc_queuing_error: /* Cleanup will be performed by the caller */ return QLA_FUNCTION_FAILED; } /** * qla24xx_start_scsi() - Send a SCSI command to the ISP * @sp: command to send to the ISP * * Returns non-zero if a failure occurred, else zero. */ int qla24xx_start_scsi(srb_t *sp) { int nseg; unsigned long flags; uint32_t *clr_ptr; uint32_t handle; struct cmd_type_7 *cmd_pkt; uint16_t cnt; uint16_t req_cnt; uint16_t tot_dsds; struct req_que *req = NULL; struct rsp_que *rsp; struct scsi_cmnd *cmd = GET_CMD_SP(sp); struct scsi_qla_host *vha = sp->vha; struct qla_hw_data *ha = vha->hw; if (sp->fcport->edif.enable && (sp->fcport->flags & FCF_FCSP_DEVICE)) return qla28xx_start_scsi_edif(sp); /* Setup device pointers. */ req = vha->req; rsp = req->rsp; /* So we know we haven't pci_map'ed anything yet */ tot_dsds = 0; /* Send marker if required */ if (vha->marker_needed != 0) { if (qla2x00_marker(vha, ha->base_qpair, 0, 0, MK_SYNC_ALL) != QLA_SUCCESS) return QLA_FUNCTION_FAILED; vha->marker_needed = 0; } /* Acquire ring specific lock */ spin_lock_irqsave(&ha->hardware_lock, flags); handle = qla2xxx_get_next_handle(req); if (handle == 0) goto queuing_error; /* Map the sg table so we have an accurate count of sg entries needed */ if (scsi_sg_count(cmd)) { nseg = dma_map_sg(&ha->pdev->dev, scsi_sglist(cmd), scsi_sg_count(cmd), cmd->sc_data_direction); if (unlikely(!nseg)) goto queuing_error; } else nseg = 0; tot_dsds = nseg; req_cnt = qla24xx_calc_iocbs(vha, tot_dsds); sp->iores.res_type = RESOURCE_INI; sp->iores.iocb_cnt = req_cnt; if (qla_get_iocbs(sp->qpair, &sp->iores)) goto queuing_error; if (req->cnt < (req_cnt + 2)) { if (IS_SHADOW_REG_CAPABLE(ha)) { cnt = *req->out_ptr; } else { cnt = rd_reg_dword_relaxed(req->req_q_out); if (qla2x00_check_reg16_for_disconnect(vha, cnt)) goto queuing_error; } if (req->ring_index < cnt) req->cnt = cnt - req->ring_index; else req->cnt = req->length - (req->ring_index - cnt); if (req->cnt < (req_cnt + 2)) goto queuing_error; } /* Build command packet. */ req->current_outstanding_cmd = handle; req->outstanding_cmds[handle] = sp; sp->handle = handle; cmd->host_scribble = (unsigned char *)(unsigned long)handle; req->cnt -= req_cnt; cmd_pkt = (struct cmd_type_7 *)req->ring_ptr; cmd_pkt->handle = make_handle(req->id, handle); /* Zero out remaining portion of packet. */ /* tagged queuing modifier -- default is TSK_SIMPLE (0). */ clr_ptr = (uint32_t *)cmd_pkt + 2; memset(clr_ptr, 0, REQUEST_ENTRY_SIZE - 8); cmd_pkt->dseg_count = cpu_to_le16(tot_dsds); /* Set NPORT-ID and LUN number*/ cmd_pkt->nport_handle = cpu_to_le16(sp->fcport->loop_id); cmd_pkt->port_id[0] = sp->fcport->d_id.b.al_pa; cmd_pkt->port_id[1] = sp->fcport->d_id.b.area; cmd_pkt->port_id[2] = sp->fcport->d_id.b.domain; cmd_pkt->vp_index = sp->vha->vp_idx; int_to_scsilun(cmd->device->lun, &cmd_pkt->lun); host_to_fcp_swap((uint8_t *)&cmd_pkt->lun, sizeof(cmd_pkt->lun)); cmd_pkt->task = TSK_SIMPLE; /* Load SCSI command packet. */ memcpy(cmd_pkt->fcp_cdb, cmd->cmnd, cmd->cmd_len); host_to_fcp_swap(cmd_pkt->fcp_cdb, sizeof(cmd_pkt->fcp_cdb)); cmd_pkt->byte_count = cpu_to_le32((uint32_t)scsi_bufflen(cmd)); /* Build IOCB segments */ qla24xx_build_scsi_iocbs(sp, cmd_pkt, tot_dsds, req); /* Set total data segment count. */ cmd_pkt->entry_count = (uint8_t)req_cnt; wmb(); /* Adjust ring index. */ req->ring_index++; if (req->ring_index == req->length) { req->ring_index = 0; req->ring_ptr = req->ring; } else req->ring_ptr++; sp->qpair->cmd_cnt++; sp->flags |= SRB_DMA_VALID; /* Set chip new ring index. */ wrt_reg_dword(req->req_q_in, req->ring_index); /* Manage unprocessed RIO/ZIO commands in response queue. */ if (vha->flags.process_response_queue && rsp->ring_ptr->signature != RESPONSE_PROCESSED) qla24xx_process_response_queue(vha, rsp); spin_unlock_irqrestore(&ha->hardware_lock, flags); return QLA_SUCCESS; queuing_error: if (tot_dsds) scsi_dma_unmap(cmd); qla_put_iocbs(sp->qpair, &sp->iores); spin_unlock_irqrestore(&ha->hardware_lock, flags); return QLA_FUNCTION_FAILED; } /** * qla24xx_dif_start_scsi() - Send a SCSI command to the ISP * @sp: command to send to the ISP * * Returns non-zero if a failure occurred, else zero. */ int qla24xx_dif_start_scsi(srb_t *sp) { int nseg; unsigned long flags; uint32_t *clr_ptr; uint32_t handle; uint16_t cnt; uint16_t req_cnt = 0; uint16_t tot_dsds; uint16_t tot_prot_dsds; uint16_t fw_prot_opts = 0; struct req_que *req = NULL; struct rsp_que *rsp = NULL; struct scsi_cmnd *cmd = GET_CMD_SP(sp); struct scsi_qla_host *vha = sp->vha; struct qla_hw_data *ha = vha->hw; struct cmd_type_crc_2 *cmd_pkt; uint32_t status = 0; #define QDSS_GOT_Q_SPACE BIT_0 /* Only process protection or >16 cdb in this routine */ if (scsi_get_prot_op(cmd) == SCSI_PROT_NORMAL) { if (cmd->cmd_len <= 16) return qla24xx_start_scsi(sp); } /* Setup device pointers. */ req = vha->req; rsp = req->rsp; /* So we know we haven't pci_map'ed anything yet */ tot_dsds = 0; /* Send marker if required */ if (vha->marker_needed != 0) { if (qla2x00_marker(vha, ha->base_qpair, 0, 0, MK_SYNC_ALL) != QLA_SUCCESS) return QLA_FUNCTION_FAILED; vha->marker_needed = 0; } /* Acquire ring specific lock */ spin_lock_irqsave(&ha->hardware_lock, flags); handle = qla2xxx_get_next_handle(req); if (handle == 0) goto queuing_error; /* Compute number of required data segments */ /* Map the sg table so we have an accurate count of sg entries needed */ if (scsi_sg_count(cmd)) { nseg = dma_map_sg(&ha->pdev->dev, scsi_sglist(cmd), scsi_sg_count(cmd), cmd->sc_data_direction); if (unlikely(!nseg)) goto queuing_error; else sp->flags |= SRB_DMA_VALID; if ((scsi_get_prot_op(cmd) == SCSI_PROT_READ_INSERT) || (scsi_get_prot_op(cmd) == SCSI_PROT_WRITE_STRIP)) { struct qla2_sgx sgx; uint32_t partial; memset(&sgx, 0, sizeof(struct qla2_sgx)); sgx.tot_bytes = scsi_bufflen(cmd); sgx.cur_sg = scsi_sglist(cmd); sgx.sp = sp; nseg = 0; while (qla24xx_get_one_block_sg( cmd->device->sector_size, &sgx, &partial)) nseg++; } } else nseg = 0; /* number of required data segments */ tot_dsds = nseg; /* Compute number of required protection segments */ if (qla24xx_configure_prot_mode(sp, &fw_prot_opts)) { nseg = dma_map_sg(&ha->pdev->dev, scsi_prot_sglist(cmd), scsi_prot_sg_count(cmd), cmd->sc_data_direction); if (unlikely(!nseg)) goto queuing_error; else sp->flags |= SRB_CRC_PROT_DMA_VALID; if ((scsi_get_prot_op(cmd) == SCSI_PROT_READ_INSERT) || (scsi_get_prot_op(cmd) == SCSI_PROT_WRITE_STRIP)) { nseg = scsi_bufflen(cmd) / cmd->device->sector_size; } } else { nseg = 0; } req_cnt = 1; /* Total Data and protection sg segment(s) */ tot_prot_dsds = nseg; tot_dsds += nseg; sp->iores.res_type = RESOURCE_INI; sp->iores.iocb_cnt = qla24xx_calc_iocbs(vha, tot_dsds); if (qla_get_iocbs(sp->qpair, &sp->iores)) goto queuing_error; if (req->cnt < (req_cnt + 2)) { if (IS_SHADOW_REG_CAPABLE(ha)) { cnt = *req->out_ptr; } else { cnt = rd_reg_dword_relaxed(req->req_q_out); if (qla2x00_check_reg16_for_disconnect(vha, cnt)) goto queuing_error; } if (req->ring_index < cnt) req->cnt = cnt - req->ring_index; else req->cnt = req->length - (req->ring_index - cnt); if (req->cnt < (req_cnt + 2)) goto queuing_error; } status |= QDSS_GOT_Q_SPACE; /* Build header part of command packet (excluding the OPCODE). */ req->current_outstanding_cmd = handle; req->outstanding_cmds[handle] = sp; sp->handle = handle; cmd->host_scribble = (unsigned char *)(unsigned long)handle; req->cnt -= req_cnt; /* Fill-in common area */ cmd_pkt = (struct cmd_type_crc_2 *)req->ring_ptr; cmd_pkt->handle = make_handle(req->id, handle); clr_ptr = (uint32_t *)cmd_pkt + 2; memset(clr_ptr, 0, REQUEST_ENTRY_SIZE - 8); /* Set NPORT-ID and LUN number*/ cmd_pkt->nport_handle = cpu_to_le16(sp->fcport->loop_id); cmd_pkt->port_id[0] = sp->fcport->d_id.b.al_pa; cmd_pkt->port_id[1] = sp->fcport->d_id.b.area; cmd_pkt->port_id[2] = sp->fcport->d_id.b.domain; int_to_scsilun(cmd->device->lun, &cmd_pkt->lun); host_to_fcp_swap((uint8_t *)&cmd_pkt->lun, sizeof(cmd_pkt->lun)); /* Total Data and protection segment(s) */ cmd_pkt->dseg_count = cpu_to_le16(tot_dsds); /* Build IOCB segments and adjust for data protection segments */ if (qla24xx_build_scsi_crc_2_iocbs(sp, (struct cmd_type_crc_2 *) req->ring_ptr, tot_dsds, tot_prot_dsds, fw_prot_opts) != QLA_SUCCESS) goto queuing_error; cmd_pkt->entry_count = (uint8_t)req_cnt; /* Specify response queue number where completion should happen */ cmd_pkt->entry_status = (uint8_t) rsp->id; cmd_pkt->timeout = cpu_to_le16(0); wmb(); /* Adjust ring index. */ req->ring_index++; if (req->ring_index == req->length) { req->ring_index = 0; req->ring_ptr = req->ring; } else req->ring_ptr++; sp->qpair->cmd_cnt++; /* Set chip new ring index. */ wrt_reg_dword(req->req_q_in, req->ring_index); /* Manage unprocessed RIO/ZIO commands in response queue. */ if (vha->flags.process_response_queue && rsp->ring_ptr->signature != RESPONSE_PROCESSED) qla24xx_process_response_queue(vha, rsp); spin_unlock_irqrestore(&ha->hardware_lock, flags); return QLA_SUCCESS; queuing_error: if (status & QDSS_GOT_Q_SPACE) { req->outstanding_cmds[handle] = NULL; req->cnt += req_cnt; } /* Cleanup will be performed by the caller (queuecommand) */ qla_put_iocbs(sp->qpair, &sp->iores); spin_unlock_irqrestore(&ha->hardware_lock, flags); return QLA_FUNCTION_FAILED; } /** * qla2xxx_start_scsi_mq() - Send a SCSI command to the ISP * @sp: command to send to the ISP * * Returns non-zero if a failure occurred, else zero. */ static int qla2xxx_start_scsi_mq(srb_t *sp) { int nseg; unsigned long flags; uint32_t *clr_ptr; uint32_t handle; struct cmd_type_7 *cmd_pkt; uint16_t cnt; uint16_t req_cnt; uint16_t tot_dsds; struct req_que *req = NULL; struct rsp_que *rsp; struct scsi_cmnd *cmd = GET_CMD_SP(sp); struct scsi_qla_host *vha = sp->fcport->vha; struct qla_hw_data *ha = vha->hw; struct qla_qpair *qpair = sp->qpair; if (sp->fcport->edif.enable && (sp->fcport->flags & FCF_FCSP_DEVICE)) return qla28xx_start_scsi_edif(sp); /* Acquire qpair specific lock */ spin_lock_irqsave(&qpair->qp_lock, flags); /* Setup qpair pointers */ req = qpair->req; rsp = qpair->rsp; /* So we know we haven't pci_map'ed anything yet */ tot_dsds = 0; /* Send marker if required */ if (vha->marker_needed != 0) { if (__qla2x00_marker(vha, qpair, 0, 0, MK_SYNC_ALL) != QLA_SUCCESS) { spin_unlock_irqrestore(&qpair->qp_lock, flags); return QLA_FUNCTION_FAILED; } vha->marker_needed = 0; } handle = qla2xxx_get_next_handle(req); if (handle == 0) goto queuing_error; /* Map the sg table so we have an accurate count of sg entries needed */ if (scsi_sg_count(cmd)) { nseg = dma_map_sg(&ha->pdev->dev, scsi_sglist(cmd), scsi_sg_count(cmd), cmd->sc_data_direction); if (unlikely(!nseg)) goto queuing_error; } else nseg = 0; tot_dsds = nseg; req_cnt = qla24xx_calc_iocbs(vha, tot_dsds); sp->iores.res_type = RESOURCE_INI; sp->iores.iocb_cnt = req_cnt; if (qla_get_iocbs(sp->qpair, &sp->iores)) goto queuing_error; if (req->cnt < (req_cnt + 2)) { if (IS_SHADOW_REG_CAPABLE(ha)) { cnt = *req->out_ptr; } else { cnt = rd_reg_dword_relaxed(req->req_q_out); if (qla2x00_check_reg16_for_disconnect(vha, cnt)) goto queuing_error; } if (req->ring_index < cnt) req->cnt = cnt - req->ring_index; else req->cnt = req->length - (req->ring_index - cnt); if (req->cnt < (req_cnt + 2)) goto queuing_error; } /* Build command packet. */ req->current_outstanding_cmd = handle; req->outstanding_cmds[handle] = sp; sp->handle = handle; cmd->host_scribble = (unsigned char *)(unsigned long)handle; req->cnt -= req_cnt; cmd_pkt = (struct cmd_type_7 *)req->ring_ptr; cmd_pkt->handle = make_handle(req->id, handle); /* Zero out remaining portion of packet. */ /* tagged queuing modifier -- default is TSK_SIMPLE (0). */ clr_ptr = (uint32_t *)cmd_pkt + 2; memset(clr_ptr, 0, REQUEST_ENTRY_SIZE - 8); cmd_pkt->dseg_count = cpu_to_le16(tot_dsds); /* Set NPORT-ID and LUN number*/ cmd_pkt->nport_handle = cpu_to_le16(sp->fcport->loop_id); cmd_pkt->port_id[0] = sp->fcport->d_id.b.al_pa; cmd_pkt->port_id[1] = sp->fcport->d_id.b.area; cmd_pkt->port_id[2] = sp->fcport->d_id.b.domain; cmd_pkt->vp_index = sp->fcport->vha->vp_idx; int_to_scsilun(cmd->device->lun, &cmd_pkt->lun); host_to_fcp_swap((uint8_t *)&cmd_pkt->lun, sizeof(cmd_pkt->lun)); cmd_pkt->task = TSK_SIMPLE; /* Load SCSI command packet. */ memcpy(cmd_pkt->fcp_cdb, cmd->cmnd, cmd->cmd_len); host_to_fcp_swap(cmd_pkt->fcp_cdb, sizeof(cmd_pkt->fcp_cdb)); cmd_pkt->byte_count = cpu_to_le32((uint32_t)scsi_bufflen(cmd)); /* Build IOCB segments */ qla24xx_build_scsi_iocbs(sp, cmd_pkt, tot_dsds, req); /* Set total data segment count. */ cmd_pkt->entry_count = (uint8_t)req_cnt; wmb(); /* Adjust ring index. */ req->ring_index++; if (req->ring_index == req->length) { req->ring_index = 0; req->ring_ptr = req->ring; } else req->ring_ptr++; sp->qpair->cmd_cnt++; sp->flags |= SRB_DMA_VALID; /* Set chip new ring index. */ wrt_reg_dword(req->req_q_in, req->ring_index); /* Manage unprocessed RIO/ZIO commands in response queue. */ if (vha->flags.process_response_queue && rsp->ring_ptr->signature != RESPONSE_PROCESSED) qla24xx_process_response_queue(vha, rsp); spin_unlock_irqrestore(&qpair->qp_lock, flags); return QLA_SUCCESS; queuing_error: if (tot_dsds) scsi_dma_unmap(cmd); qla_put_iocbs(sp->qpair, &sp->iores); spin_unlock_irqrestore(&qpair->qp_lock, flags); return QLA_FUNCTION_FAILED; } /** * qla2xxx_dif_start_scsi_mq() - Send a SCSI command to the ISP * @sp: command to send to the ISP * * Returns non-zero if a failure occurred, else zero. */ int qla2xxx_dif_start_scsi_mq(srb_t *sp) { int nseg; unsigned long flags; uint32_t *clr_ptr; uint32_t handle; uint16_t cnt; uint16_t req_cnt = 0; uint16_t tot_dsds; uint16_t tot_prot_dsds; uint16_t fw_prot_opts = 0; struct req_que *req = NULL; struct rsp_que *rsp = NULL; struct scsi_cmnd *cmd = GET_CMD_SP(sp); struct scsi_qla_host *vha = sp->fcport->vha; struct qla_hw_data *ha = vha->hw; struct cmd_type_crc_2 *cmd_pkt; uint32_t status = 0; struct qla_qpair *qpair = sp->qpair; #define QDSS_GOT_Q_SPACE BIT_0 /* Check for host side state */ if (!qpair->online) { cmd->result = DID_NO_CONNECT << 16; return QLA_INTERFACE_ERROR; } if (!qpair->difdix_supported && scsi_get_prot_op(cmd) != SCSI_PROT_NORMAL) { cmd->result = DID_NO_CONNECT << 16; return QLA_INTERFACE_ERROR; } /* Only process protection or >16 cdb in this routine */ if (scsi_get_prot_op(cmd) == SCSI_PROT_NORMAL) { if (cmd->cmd_len <= 16) return qla2xxx_start_scsi_mq(sp); } spin_lock_irqsave(&qpair->qp_lock, flags); /* Setup qpair pointers */ rsp = qpair->rsp; req = qpair->req; /* So we know we haven't pci_map'ed anything yet */ tot_dsds = 0; /* Send marker if required */ if (vha->marker_needed != 0) { if (__qla2x00_marker(vha, qpair, 0, 0, MK_SYNC_ALL) != QLA_SUCCESS) { spin_unlock_irqrestore(&qpair->qp_lock, flags); return QLA_FUNCTION_FAILED; } vha->marker_needed = 0; } handle = qla2xxx_get_next_handle(req); if (handle == 0) goto queuing_error; /* Compute number of required data segments */ /* Map the sg table so we have an accurate count of sg entries needed */ if (scsi_sg_count(cmd)) { nseg = dma_map_sg(&ha->pdev->dev, scsi_sglist(cmd), scsi_sg_count(cmd), cmd->sc_data_direction); if (unlikely(!nseg)) goto queuing_error; else sp->flags |= SRB_DMA_VALID; if ((scsi_get_prot_op(cmd) == SCSI_PROT_READ_INSERT) || (scsi_get_prot_op(cmd) == SCSI_PROT_WRITE_STRIP)) { struct qla2_sgx sgx; uint32_t partial; memset(&sgx, 0, sizeof(struct qla2_sgx)); sgx.tot_bytes = scsi_bufflen(cmd); sgx.cur_sg = scsi_sglist(cmd); sgx.sp = sp; nseg = 0; while (qla24xx_get_one_block_sg( cmd->device->sector_size, &sgx, &partial)) nseg++; } } else nseg = 0; /* number of required data segments */ tot_dsds = nseg; /* Compute number of required protection segments */ if (qla24xx_configure_prot_mode(sp, &fw_prot_opts)) { nseg = dma_map_sg(&ha->pdev->dev, scsi_prot_sglist(cmd), scsi_prot_sg_count(cmd), cmd->sc_data_direction); if (unlikely(!nseg)) goto queuing_error; else sp->flags |= SRB_CRC_PROT_DMA_VALID; if ((scsi_get_prot_op(cmd) == SCSI_PROT_READ_INSERT) || (scsi_get_prot_op(cmd) == SCSI_PROT_WRITE_STRIP)) { nseg = scsi_bufflen(cmd) / cmd->device->sector_size; } } else { nseg = 0; } req_cnt = 1; /* Total Data and protection sg segment(s) */ tot_prot_dsds = nseg; tot_dsds += nseg; sp->iores.res_type = RESOURCE_INI; sp->iores.iocb_cnt = qla24xx_calc_iocbs(vha, tot_dsds); if (qla_get_iocbs(sp->qpair, &sp->iores)) goto queuing_error; if (req->cnt < (req_cnt + 2)) { if (IS_SHADOW_REG_CAPABLE(ha)) { cnt = *req->out_ptr; } else { cnt = rd_reg_dword_relaxed(req->req_q_out); if (qla2x00_check_reg16_for_disconnect(vha, cnt)) goto queuing_error; } if (req->ring_index < cnt) req->cnt = cnt - req->ring_index; else req->cnt = req->length - (req->ring_index - cnt); if (req->cnt < (req_cnt + 2)) goto queuing_error; } status |= QDSS_GOT_Q_SPACE; /* Build header part of command packet (excluding the OPCODE). */ req->current_outstanding_cmd = handle; req->outstanding_cmds[handle] = sp; sp->handle = handle; cmd->host_scribble = (unsigned char *)(unsigned long)handle; req->cnt -= req_cnt; /* Fill-in common area */ cmd_pkt = (struct cmd_type_crc_2 *)req->ring_ptr; cmd_pkt->handle = make_handle(req->id, handle); clr_ptr = (uint32_t *)cmd_pkt + 2; memset(clr_ptr, 0, REQUEST_ENTRY_SIZE - 8); /* Set NPORT-ID and LUN number*/ cmd_pkt->nport_handle = cpu_to_le16(sp->fcport->loop_id); cmd_pkt->port_id[0] = sp->fcport->d_id.b.al_pa; cmd_pkt->port_id[1] = sp->fcport->d_id.b.area; cmd_pkt->port_id[2] = sp->fcport->d_id.b.domain; int_to_scsilun(cmd->device->lun, &cmd_pkt->lun); host_to_fcp_swap((uint8_t *)&cmd_pkt->lun, sizeof(cmd_pkt->lun)); /* Total Data and protection segment(s) */ cmd_pkt->dseg_count = cpu_to_le16(tot_dsds); /* Build IOCB segments and adjust for data protection segments */ if (qla24xx_build_scsi_crc_2_iocbs(sp, (struct cmd_type_crc_2 *) req->ring_ptr, tot_dsds, tot_prot_dsds, fw_prot_opts) != QLA_SUCCESS) goto queuing_error; cmd_pkt->entry_count = (uint8_t)req_cnt; cmd_pkt->timeout = cpu_to_le16(0); wmb(); /* Adjust ring index. */ req->ring_index++; if (req->ring_index == req->length) { req->ring_index = 0; req->ring_ptr = req->ring; } else req->ring_ptr++; sp->qpair->cmd_cnt++; /* Set chip new ring index. */ wrt_reg_dword(req->req_q_in, req->ring_index); /* Manage unprocessed RIO/ZIO commands in response queue. */ if (vha->flags.process_response_queue && rsp->ring_ptr->signature != RESPONSE_PROCESSED) qla24xx_process_response_queue(vha, rsp); spin_unlock_irqrestore(&qpair->qp_lock, flags); return QLA_SUCCESS; queuing_error: if (status & QDSS_GOT_Q_SPACE) { req->outstanding_cmds[handle] = NULL; req->cnt += req_cnt; } /* Cleanup will be performed by the caller (queuecommand) */ qla_put_iocbs(sp->qpair, &sp->iores); spin_unlock_irqrestore(&qpair->qp_lock, flags); return QLA_FUNCTION_FAILED; } /* Generic Control-SRB manipulation functions. */ /* hardware_lock assumed to be held. */ void * __qla2x00_alloc_iocbs(struct qla_qpair *qpair, srb_t *sp) { scsi_qla_host_t *vha = qpair->vha; struct qla_hw_data *ha = vha->hw; struct req_que *req = qpair->req; device_reg_t *reg = ISP_QUE_REG(ha, req->id); uint32_t handle; request_t *pkt; uint16_t cnt, req_cnt; pkt = NULL; req_cnt = 1; handle = 0; if (sp && (sp->type != SRB_SCSI_CMD)) { /* Adjust entry-counts as needed. */ req_cnt = sp->iocbs; } /* Check for room on request queue. */ if (req->cnt < req_cnt + 2) { if (qpair->use_shadow_reg) cnt = *req->out_ptr; else if (ha->mqenable || IS_QLA83XX(ha) || IS_QLA27XX(ha) || IS_QLA28XX(ha)) cnt = rd_reg_dword(&reg->isp25mq.req_q_out); else if (IS_P3P_TYPE(ha)) cnt = rd_reg_dword(reg->isp82.req_q_out); else if (IS_FWI2_CAPABLE(ha)) cnt = rd_reg_dword(&reg->isp24.req_q_out); else if (IS_QLAFX00(ha)) cnt = rd_reg_dword(&reg->ispfx00.req_q_out); else cnt = qla2x00_debounce_register( ISP_REQ_Q_OUT(ha, &reg->isp)); if (!qpair->use_shadow_reg && cnt == ISP_REG16_DISCONNECT) { qla_schedule_eeh_work(vha); return NULL; } if (req->ring_index < cnt) req->cnt = cnt - req->ring_index; else req->cnt = req->length - (req->ring_index - cnt); } if (req->cnt < req_cnt + 2) goto queuing_error; if (sp) { handle = qla2xxx_get_next_handle(req); if (handle == 0) { ql_log(ql_log_warn, vha, 0x700b, "No room on outstanding cmd array.\n"); goto queuing_error; } /* Prep command array. */ req->current_outstanding_cmd = handle; req->outstanding_cmds[handle] = sp; sp->handle = handle; } /* Prep packet */ req->cnt -= req_cnt; pkt = req->ring_ptr; memset(pkt, 0, REQUEST_ENTRY_SIZE); if (IS_QLAFX00(ha)) { wrt_reg_byte((u8 __force __iomem *)&pkt->entry_count, req_cnt); wrt_reg_dword((__le32 __force __iomem *)&pkt->handle, handle); } else { pkt->entry_count = req_cnt; pkt->handle = handle; } return pkt; queuing_error: qpair->tgt_counters.num_alloc_iocb_failed++; return pkt; } void * qla2x00_alloc_iocbs_ready(struct qla_qpair *qpair, srb_t *sp) { scsi_qla_host_t *vha = qpair->vha; if (qla2x00_reset_active(vha)) return NULL; return __qla2x00_alloc_iocbs(qpair, sp); } void * qla2x00_alloc_iocbs(struct scsi_qla_host *vha, srb_t *sp) { return __qla2x00_alloc_iocbs(vha->hw->base_qpair, sp); } static void qla24xx_prli_iocb(srb_t *sp, struct logio_entry_24xx *logio) { struct srb_iocb *lio = &sp->u.iocb_cmd; logio->entry_type = LOGINOUT_PORT_IOCB_TYPE; logio->control_flags = cpu_to_le16(LCF_COMMAND_PRLI); if (lio->u.logio.flags & SRB_LOGIN_NVME_PRLI) { logio->control_flags |= cpu_to_le16(LCF_NVME_PRLI); if (sp->vha->flags.nvme_first_burst) logio->io_parameter[0] = cpu_to_le32(NVME_PRLI_SP_FIRST_BURST); if (sp->vha->flags.nvme2_enabled) { /* Set service parameter BIT_7 for NVME CONF support */ logio->io_parameter[0] |= cpu_to_le32(NVME_PRLI_SP_CONF); /* Set service parameter BIT_8 for SLER support */ logio->io_parameter[0] |= cpu_to_le32(NVME_PRLI_SP_SLER); /* Set service parameter BIT_9 for PI control support */ logio->io_parameter[0] |= cpu_to_le32(NVME_PRLI_SP_PI_CTRL); } } logio->nport_handle = cpu_to_le16(sp->fcport->loop_id); logio->port_id[0] = sp->fcport->d_id.b.al_pa; logio->port_id[1] = sp->fcport->d_id.b.area; logio->port_id[2] = sp->fcport->d_id.b.domain; logio->vp_index = sp->vha->vp_idx; } static void qla24xx_login_iocb(srb_t *sp, struct logio_entry_24xx *logio) { struct srb_iocb *lio = &sp->u.iocb_cmd; logio->entry_type = LOGINOUT_PORT_IOCB_TYPE; logio->control_flags = cpu_to_le16(LCF_COMMAND_PLOGI); if (lio->u.logio.flags & SRB_LOGIN_PRLI_ONLY) { logio->control_flags = cpu_to_le16(LCF_COMMAND_PRLI); } else { logio->control_flags = cpu_to_le16(LCF_COMMAND_PLOGI); if (lio->u.logio.flags & SRB_LOGIN_COND_PLOGI) logio->control_flags |= cpu_to_le16(LCF_COND_PLOGI); if (lio->u.logio.flags & SRB_LOGIN_SKIP_PRLI) logio->control_flags |= cpu_to_le16(LCF_SKIP_PRLI); if (lio->u.logio.flags & SRB_LOGIN_FCSP) { logio->control_flags |= cpu_to_le16(LCF_COMMON_FEAT | LCF_SKIP_PRLI); logio->io_parameter[0] = cpu_to_le32(LIO_COMM_FEAT_FCSP | LIO_COMM_FEAT_CIO); } } logio->nport_handle = cpu_to_le16(sp->fcport->loop_id); logio->port_id[0] = sp->fcport->d_id.b.al_pa; logio->port_id[1] = sp->fcport->d_id.b.area; logio->port_id[2] = sp->fcport->d_id.b.domain; logio->vp_index = sp->vha->vp_idx; } static void qla2x00_login_iocb(srb_t *sp, struct mbx_entry *mbx) { struct qla_hw_data *ha = sp->vha->hw; struct srb_iocb *lio = &sp->u.iocb_cmd; uint16_t opts; mbx->entry_type = MBX_IOCB_TYPE; SET_TARGET_ID(ha, mbx->loop_id, sp->fcport->loop_id); mbx->mb0 = cpu_to_le16(MBC_LOGIN_FABRIC_PORT); opts = lio->u.logio.flags & SRB_LOGIN_COND_PLOGI ? BIT_0 : 0; opts |= lio->u.logio.flags & SRB_LOGIN_SKIP_PRLI ? BIT_1 : 0; if (HAS_EXTENDED_IDS(ha)) { mbx->mb1 = cpu_to_le16(sp->fcport->loop_id); mbx->mb10 = cpu_to_le16(opts); } else { mbx->mb1 = cpu_to_le16((sp->fcport->loop_id << 8) | opts); } mbx->mb2 = cpu_to_le16(sp->fcport->d_id.b.domain); mbx->mb3 = cpu_to_le16(sp->fcport->d_id.b.area << 8 | sp->fcport->d_id.b.al_pa); mbx->mb9 = cpu_to_le16(sp->vha->vp_idx); } static void qla24xx_logout_iocb(srb_t *sp, struct logio_entry_24xx *logio) { u16 control_flags = LCF_COMMAND_LOGO; logio->entry_type = LOGINOUT_PORT_IOCB_TYPE; if (sp->fcport->explicit_logout) { control_flags |= LCF_EXPL_LOGO|LCF_FREE_NPORT; } else { control_flags |= LCF_IMPL_LOGO; if (!sp->fcport->keep_nport_handle) control_flags |= LCF_FREE_NPORT; } logio->control_flags = cpu_to_le16(control_flags); logio->nport_handle = cpu_to_le16(sp->fcport->loop_id); logio->port_id[0] = sp->fcport->d_id.b.al_pa; logio->port_id[1] = sp->fcport->d_id.b.area; logio->port_id[2] = sp->fcport->d_id.b.domain; logio->vp_index = sp->vha->vp_idx; } static void qla2x00_logout_iocb(srb_t *sp, struct mbx_entry *mbx) { struct qla_hw_data *ha = sp->vha->hw; mbx->entry_type = MBX_IOCB_TYPE; SET_TARGET_ID(ha, mbx->loop_id, sp->fcport->loop_id); mbx->mb0 = cpu_to_le16(MBC_LOGOUT_FABRIC_PORT); mbx->mb1 = HAS_EXTENDED_IDS(ha) ? cpu_to_le16(sp->fcport->loop_id) : cpu_to_le16(sp->fcport->loop_id << 8); mbx->mb2 = cpu_to_le16(sp->fcport->d_id.b.domain); mbx->mb3 = cpu_to_le16(sp->fcport->d_id.b.area << 8 | sp->fcport->d_id.b.al_pa); mbx->mb9 = cpu_to_le16(sp->vha->vp_idx); /* Implicit: mbx->mbx10 = 0. */ } static void qla24xx_adisc_iocb(srb_t *sp, struct logio_entry_24xx *logio) { logio->entry_type = LOGINOUT_PORT_IOCB_TYPE; logio->control_flags = cpu_to_le16(LCF_COMMAND_ADISC); logio->nport_handle = cpu_to_le16(sp->fcport->loop_id); logio->vp_index = sp->vha->vp_idx; } static void qla2x00_adisc_iocb(srb_t *sp, struct mbx_entry *mbx) { struct qla_hw_data *ha = sp->vha->hw; mbx->entry_type = MBX_IOCB_TYPE; SET_TARGET_ID(ha, mbx->loop_id, sp->fcport->loop_id); mbx->mb0 = cpu_to_le16(MBC_GET_PORT_DATABASE); if (HAS_EXTENDED_IDS(ha)) { mbx->mb1 = cpu_to_le16(sp->fcport->loop_id); mbx->mb10 = cpu_to_le16(BIT_0); } else { mbx->mb1 = cpu_to_le16((sp->fcport->loop_id << 8) | BIT_0); } mbx->mb2 = cpu_to_le16(MSW(ha->async_pd_dma)); mbx->mb3 = cpu_to_le16(LSW(ha->async_pd_dma)); mbx->mb6 = cpu_to_le16(MSW(MSD(ha->async_pd_dma))); mbx->mb7 = cpu_to_le16(LSW(MSD(ha->async_pd_dma))); mbx->mb9 = cpu_to_le16(sp->vha->vp_idx); } static void qla24xx_tm_iocb(srb_t *sp, struct tsk_mgmt_entry *tsk) { uint32_t flags; uint64_t lun; struct fc_port *fcport = sp->fcport; scsi_qla_host_t *vha = fcport->vha; struct qla_hw_data *ha = vha->hw; struct srb_iocb *iocb = &sp->u.iocb_cmd; struct req_que *req = vha->req; flags = iocb->u.tmf.flags; lun = iocb->u.tmf.lun; tsk->entry_type = TSK_MGMT_IOCB_TYPE; tsk->entry_count = 1; tsk->handle = make_handle(req->id, tsk->handle); tsk->nport_handle = cpu_to_le16(fcport->loop_id); tsk->timeout = cpu_to_le16(ha->r_a_tov / 10 * 2); tsk->control_flags = cpu_to_le32(flags); tsk->port_id[0] = fcport->d_id.b.al_pa; tsk->port_id[1] = fcport->d_id.b.area; tsk->port_id[2] = fcport->d_id.b.domain; tsk->vp_index = fcport->vha->vp_idx; if (flags == TCF_LUN_RESET) { int_to_scsilun(lun, &tsk->lun); host_to_fcp_swap((uint8_t *)&tsk->lun, sizeof(tsk->lun)); } } void qla2x00_init_timer(srb_t *sp, unsigned long tmo) { timer_setup(&sp->u.iocb_cmd.timer, qla2x00_sp_timeout, 0); sp->u.iocb_cmd.timer.expires = jiffies + tmo * HZ; sp->free = qla2x00_sp_free; if (IS_QLAFX00(sp->vha->hw) && sp->type == SRB_FXIOCB_DCMD) init_completion(&sp->u.iocb_cmd.u.fxiocb.fxiocb_comp); sp->start_timer = 1; } static void qla2x00_els_dcmd_sp_free(srb_t *sp) { struct srb_iocb *elsio = &sp->u.iocb_cmd; kfree(sp->fcport); if (elsio->u.els_logo.els_logo_pyld) dma_free_coherent(&sp->vha->hw->pdev->dev, DMA_POOL_SIZE, elsio->u.els_logo.els_logo_pyld, elsio->u.els_logo.els_logo_pyld_dma); del_timer(&elsio->timer); qla2x00_rel_sp(sp); } static void qla2x00_els_dcmd_iocb_timeout(void *data) { srb_t *sp = data; fc_port_t *fcport = sp->fcport; struct scsi_qla_host *vha = sp->vha; struct srb_iocb *lio = &sp->u.iocb_cmd; unsigned long flags = 0; int res, h; ql_dbg(ql_dbg_io, vha, 0x3069, "%s Timeout, hdl=%x, portid=%02x%02x%02x\n", sp->name, sp->handle, fcport->d_id.b.domain, fcport->d_id.b.area, fcport->d_id.b.al_pa); /* Abort the exchange */ res = qla24xx_async_abort_cmd(sp, false); if (res) { ql_dbg(ql_dbg_io, vha, 0x3070, "mbx abort_command failed.\n"); spin_lock_irqsave(sp->qpair->qp_lock_ptr, flags); for (h = 1; h < sp->qpair->req->num_outstanding_cmds; h++) { if (sp->qpair->req->outstanding_cmds[h] == sp) { sp->qpair->req->outstanding_cmds[h] = NULL; break; } } spin_unlock_irqrestore(sp->qpair->qp_lock_ptr, flags); complete(&lio->u.els_logo.comp); } else { ql_dbg(ql_dbg_io, vha, 0x3071, "mbx abort_command success.\n"); } } static void qla2x00_els_dcmd_sp_done(srb_t *sp, int res) { fc_port_t *fcport = sp->fcport; struct srb_iocb *lio = &sp->u.iocb_cmd; struct scsi_qla_host *vha = sp->vha; ql_dbg(ql_dbg_io, vha, 0x3072, "%s hdl=%x, portid=%02x%02x%02x done\n", sp->name, sp->handle, fcport->d_id.b.domain, fcport->d_id.b.area, fcport->d_id.b.al_pa); complete(&lio->u.els_logo.comp); } int qla24xx_els_dcmd_iocb(scsi_qla_host_t *vha, int els_opcode, port_id_t remote_did) { srb_t *sp; fc_port_t *fcport = NULL; struct srb_iocb *elsio = NULL; struct qla_hw_data *ha = vha->hw; struct els_logo_payload logo_pyld; int rval = QLA_SUCCESS; fcport = qla2x00_alloc_fcport(vha, GFP_KERNEL); if (!fcport) { ql_log(ql_log_info, vha, 0x70e5, "fcport allocation failed\n"); return -ENOMEM; } /* Alloc SRB structure */ sp = qla2x00_get_sp(vha, fcport, GFP_KERNEL); if (!sp) { kfree(fcport); ql_log(ql_log_info, vha, 0x70e6, "SRB allocation failed\n"); return -ENOMEM; } elsio = &sp->u.iocb_cmd; fcport->loop_id = 0xFFFF; fcport->d_id.b.domain = remote_did.b.domain; fcport->d_id.b.area = remote_did.b.area; fcport->d_id.b.al_pa = remote_did.b.al_pa; ql_dbg(ql_dbg_io, vha, 0x3073, "portid=%02x%02x%02x done\n", fcport->d_id.b.domain, fcport->d_id.b.area, fcport->d_id.b.al_pa); sp->type = SRB_ELS_DCMD; sp->name = "ELS_DCMD"; sp->fcport = fcport; elsio->timeout = qla2x00_els_dcmd_iocb_timeout; qla2x00_init_timer(sp, ELS_DCMD_TIMEOUT); init_completion(&sp->u.iocb_cmd.u.els_logo.comp); sp->done = qla2x00_els_dcmd_sp_done; sp->free = qla2x00_els_dcmd_sp_free; elsio->u.els_logo.els_logo_pyld = dma_alloc_coherent(&ha->pdev->dev, DMA_POOL_SIZE, &elsio->u.els_logo.els_logo_pyld_dma, GFP_KERNEL); if (!elsio->u.els_logo.els_logo_pyld) { sp->free(sp); return QLA_FUNCTION_FAILED; } memset(&logo_pyld, 0, sizeof(struct els_logo_payload)); elsio->u.els_logo.els_cmd = els_opcode; logo_pyld.opcode = els_opcode; logo_pyld.s_id[0] = vha->d_id.b.al_pa; logo_pyld.s_id[1] = vha->d_id.b.area; logo_pyld.s_id[2] = vha->d_id.b.domain; host_to_fcp_swap(logo_pyld.s_id, sizeof(uint32_t)); memcpy(&logo_pyld.wwpn, vha->port_name, WWN_SIZE); memcpy(elsio->u.els_logo.els_logo_pyld, &logo_pyld, sizeof(struct els_logo_payload)); ql_dbg(ql_dbg_disc + ql_dbg_buffer, vha, 0x3075, "LOGO buffer:"); ql_dump_buffer(ql_dbg_disc + ql_dbg_buffer, vha, 0x010a, elsio->u.els_logo.els_logo_pyld, sizeof(*elsio->u.els_logo.els_logo_pyld)); rval = qla2x00_start_sp(sp); if (rval != QLA_SUCCESS) { sp->free(sp); return QLA_FUNCTION_FAILED; } ql_dbg(ql_dbg_io, vha, 0x3074, "%s LOGO sent, hdl=%x, loopid=%x, portid=%02x%02x%02x.\n", sp->name, sp->handle, fcport->loop_id, fcport->d_id.b.domain, fcport->d_id.b.area, fcport->d_id.b.al_pa); wait_for_completion(&elsio->u.els_logo.comp); sp->free(sp); return rval; } static void qla24xx_els_logo_iocb(srb_t *sp, struct els_entry_24xx *els_iocb) { scsi_qla_host_t *vha = sp->vha; struct srb_iocb *elsio = &sp->u.iocb_cmd; els_iocb->entry_type = ELS_IOCB_TYPE; els_iocb->entry_count = 1; els_iocb->sys_define = 0; els_iocb->entry_status = 0; els_iocb->handle = sp->handle; els_iocb->nport_handle = cpu_to_le16(sp->fcport->loop_id); els_iocb->tx_dsd_count = cpu_to_le16(1); els_iocb->vp_index = vha->vp_idx; els_iocb->sof_type = EST_SOFI3; els_iocb->rx_dsd_count = 0; els_iocb->opcode = elsio->u.els_logo.els_cmd; els_iocb->d_id[0] = sp->fcport->d_id.b.al_pa; els_iocb->d_id[1] = sp->fcport->d_id.b.area; els_iocb->d_id[2] = sp->fcport->d_id.b.domain; /* For SID the byte order is different than DID */ els_iocb->s_id[1] = vha->d_id.b.al_pa; els_iocb->s_id[2] = vha->d_id.b.area; els_iocb->s_id[0] = vha->d_id.b.domain; if (elsio->u.els_logo.els_cmd == ELS_DCMD_PLOGI) { if (vha->hw->flags.edif_enabled) els_iocb->control_flags = cpu_to_le16(ECF_SEC_LOGIN); else els_iocb->control_flags = 0; els_iocb->tx_byte_count = els_iocb->tx_len = cpu_to_le32(sizeof(struct els_plogi_payload)); put_unaligned_le64(elsio->u.els_plogi.els_plogi_pyld_dma, &els_iocb->tx_address); els_iocb->rx_dsd_count = cpu_to_le16(1); els_iocb->rx_byte_count = els_iocb->rx_len = cpu_to_le32(sizeof(struct els_plogi_payload)); put_unaligned_le64(elsio->u.els_plogi.els_resp_pyld_dma, &els_iocb->rx_address); ql_dbg(ql_dbg_io + ql_dbg_buffer, vha, 0x3073, "PLOGI ELS IOCB:\n"); ql_dump_buffer(ql_log_info, vha, 0x0109, (uint8_t *)els_iocb, sizeof(*els_iocb)); } else { els_iocb->tx_byte_count = cpu_to_le32(sizeof(struct els_logo_payload)); put_unaligned_le64(elsio->u.els_logo.els_logo_pyld_dma, &els_iocb->tx_address); els_iocb->tx_len = cpu_to_le32(sizeof(struct els_logo_payload)); els_iocb->rx_byte_count = 0; els_iocb->rx_address = 0; els_iocb->rx_len = 0; ql_dbg(ql_dbg_io + ql_dbg_buffer, vha, 0x3076, "LOGO ELS IOCB:"); ql_dump_buffer(ql_log_info, vha, 0x010b, els_iocb, sizeof(*els_iocb)); } sp->vha->qla_stats.control_requests++; } static void qla2x00_els_dcmd2_iocb_timeout(void *data) { srb_t *sp = data; fc_port_t *fcport = sp->fcport; struct scsi_qla_host *vha = sp->vha; unsigned long flags = 0; int res, h; ql_dbg(ql_dbg_io + ql_dbg_disc, vha, 0x3069, "%s hdl=%x ELS Timeout, %8phC portid=%06x\n", sp->name, sp->handle, fcport->port_name, fcport->d_id.b24); /* Abort the exchange */ res = qla24xx_async_abort_cmd(sp, false); ql_dbg(ql_dbg_io, vha, 0x3070, "mbx abort_command %s\n", (res == QLA_SUCCESS) ? "successful" : "failed"); if (res) { spin_lock_irqsave(sp->qpair->qp_lock_ptr, flags); for (h = 1; h < sp->qpair->req->num_outstanding_cmds; h++) { if (sp->qpair->req->outstanding_cmds[h] == sp) { sp->qpair->req->outstanding_cmds[h] = NULL; break; } } spin_unlock_irqrestore(sp->qpair->qp_lock_ptr, flags); sp->done(sp, QLA_FUNCTION_TIMEOUT); } } void qla2x00_els_dcmd2_free(scsi_qla_host_t *vha, struct els_plogi *els_plogi) { if (els_plogi->els_plogi_pyld) dma_free_coherent(&vha->hw->pdev->dev, els_plogi->tx_size, els_plogi->els_plogi_pyld, els_plogi->els_plogi_pyld_dma); if (els_plogi->els_resp_pyld) dma_free_coherent(&vha->hw->pdev->dev, els_plogi->rx_size, els_plogi->els_resp_pyld, els_plogi->els_resp_pyld_dma); } static void qla2x00_els_dcmd2_sp_done(srb_t *sp, int res) { fc_port_t *fcport = sp->fcport; struct srb_iocb *lio = &sp->u.iocb_cmd; struct scsi_qla_host *vha = sp->vha; struct event_arg ea; struct qla_work_evt *e; struct fc_port *conflict_fcport; port_id_t cid; /* conflict Nport id */ const __le32 *fw_status = sp->u.iocb_cmd.u.els_plogi.fw_status; u16 lid; ql_dbg(ql_dbg_disc, vha, 0x3072, "%s ELS done rc %d hdl=%x, portid=%06x %8phC\n", sp->name, res, sp->handle, fcport->d_id.b24, fcport->port_name); fcport->flags &= ~(FCF_ASYNC_SENT|FCF_ASYNC_ACTIVE); del_timer(&sp->u.iocb_cmd.timer); if (sp->flags & SRB_WAKEUP_ON_COMP) complete(&lio->u.els_plogi.comp); else { switch (le32_to_cpu(fw_status[0])) { case CS_DATA_UNDERRUN: case CS_COMPLETE: memset(&ea, 0, sizeof(ea)); ea.fcport = fcport; ea.rc = res; qla_handle_els_plogi_done(vha, &ea); break; case CS_IOCB_ERROR: switch (le32_to_cpu(fw_status[1])) { case LSC_SCODE_PORTID_USED: lid = le32_to_cpu(fw_status[2]) & 0xffff; qlt_find_sess_invalidate_other(vha, wwn_to_u64(fcport->port_name), fcport->d_id, lid, &conflict_fcport); if (conflict_fcport) { /* * Another fcport shares the same * loop_id & nport id; conflict * fcport needs to finish cleanup * before this fcport can proceed * to login. */ conflict_fcport->conflict = fcport; fcport->login_pause = 1; ql_dbg(ql_dbg_disc, vha, 0x20ed, "%s %d %8phC pid %06x inuse with lid %#x post gidpn\n", __func__, __LINE__, fcport->port_name, fcport->d_id.b24, lid); } else { ql_dbg(ql_dbg_disc, vha, 0x20ed, "%s %d %8phC pid %06x inuse with lid %#x sched del\n", __func__, __LINE__, fcport->port_name, fcport->d_id.b24, lid); qla2x00_clear_loop_id(fcport); set_bit(lid, vha->hw->loop_id_map); fcport->loop_id = lid; fcport->keep_nport_handle = 0; qlt_schedule_sess_for_deletion(fcport); } break; case LSC_SCODE_NPORT_USED: cid.b.domain = (le32_to_cpu(fw_status[2]) >> 16) & 0xff; cid.b.area = (le32_to_cpu(fw_status[2]) >> 8) & 0xff; cid.b.al_pa = le32_to_cpu(fw_status[2]) & 0xff; cid.b.rsvd_1 = 0; ql_dbg(ql_dbg_disc, vha, 0x20ec, "%s %d %8phC lid %#x in use with pid %06x post gnl\n", __func__, __LINE__, fcport->port_name, fcport->loop_id, cid.b24); set_bit(fcport->loop_id, vha->hw->loop_id_map); fcport->loop_id = FC_NO_LOOP_ID; qla24xx_post_gnl_work(vha, fcport); break; case LSC_SCODE_NOXCB: vha->hw->exch_starvation++; if (vha->hw->exch_starvation > 5) { ql_log(ql_log_warn, vha, 0xd046, "Exchange starvation. Resetting RISC\n"); vha->hw->exch_starvation = 0; set_bit(ISP_ABORT_NEEDED, &vha->dpc_flags); qla2xxx_wake_dpc(vha); } fallthrough; default: ql_dbg(ql_dbg_disc, vha, 0x20eb, "%s %8phC cmd error fw_status 0x%x 0x%x 0x%x\n", __func__, sp->fcport->port_name, fw_status[0], fw_status[1], fw_status[2]); fcport->flags &= ~FCF_ASYNC_SENT; qla2x00_set_fcport_disc_state(fcport, DSC_LOGIN_FAILED); set_bit(RELOGIN_NEEDED, &vha->dpc_flags); break; } break; default: ql_dbg(ql_dbg_disc, vha, 0x20eb, "%s %8phC cmd error 2 fw_status 0x%x 0x%x 0x%x\n", __func__, sp->fcport->port_name, fw_status[0], fw_status[1], fw_status[2]); sp->fcport->flags &= ~FCF_ASYNC_SENT; qla2x00_set_fcport_disc_state(fcport, DSC_LOGIN_FAILED); set_bit(RELOGIN_NEEDED, &vha->dpc_flags); break; } e = qla2x00_alloc_work(vha, QLA_EVT_UNMAP); if (!e) { struct srb_iocb *elsio = &sp->u.iocb_cmd; qla2x00_els_dcmd2_free(vha, &elsio->u.els_plogi); sp->free(sp); return; } e->u.iosb.sp = sp; qla2x00_post_work(vha, e); } } int qla24xx_els_dcmd2_iocb(scsi_qla_host_t *vha, int els_opcode, fc_port_t *fcport, bool wait) { srb_t *sp; struct srb_iocb *elsio = NULL; struct qla_hw_data *ha = vha->hw; int rval = QLA_SUCCESS; void *ptr, *resp_ptr; /* Alloc SRB structure */ sp = qla2x00_get_sp(vha, fcport, GFP_KERNEL); if (!sp) { ql_log(ql_log_info, vha, 0x70e6, "SRB allocation failed\n"); fcport->flags &= ~FCF_ASYNC_ACTIVE; return -ENOMEM; } fcport->flags |= FCF_ASYNC_SENT; qla2x00_set_fcport_disc_state(fcport, DSC_LOGIN_PEND); elsio = &sp->u.iocb_cmd; ql_dbg(ql_dbg_io, vha, 0x3073, "%s Enter: PLOGI portid=%06x\n", __func__, fcport->d_id.b24); sp->type = SRB_ELS_DCMD; sp->name = "ELS_DCMD"; sp->fcport = fcport; elsio->timeout = qla2x00_els_dcmd2_iocb_timeout; if (wait) sp->flags = SRB_WAKEUP_ON_COMP; qla2x00_init_timer(sp, ELS_DCMD_TIMEOUT + 2); sp->done = qla2x00_els_dcmd2_sp_done; elsio->u.els_plogi.tx_size = elsio->u.els_plogi.rx_size = DMA_POOL_SIZE; ptr = elsio->u.els_plogi.els_plogi_pyld = dma_alloc_coherent(&ha->pdev->dev, elsio->u.els_plogi.tx_size, &elsio->u.els_plogi.els_plogi_pyld_dma, GFP_KERNEL); if (!elsio->u.els_plogi.els_plogi_pyld) { rval = QLA_FUNCTION_FAILED; goto out; } resp_ptr = elsio->u.els_plogi.els_resp_pyld = dma_alloc_coherent(&ha->pdev->dev, elsio->u.els_plogi.rx_size, &elsio->u.els_plogi.els_resp_pyld_dma, GFP_KERNEL); if (!elsio->u.els_plogi.els_resp_pyld) { rval = QLA_FUNCTION_FAILED; goto out; } ql_dbg(ql_dbg_io, vha, 0x3073, "PLOGI %p %p\n", ptr, resp_ptr); memset(ptr, 0, sizeof(struct els_plogi_payload)); memset(resp_ptr, 0, sizeof(struct els_plogi_payload)); memcpy(elsio->u.els_plogi.els_plogi_pyld->data, &ha->plogi_els_payld.fl_csp, LOGIN_TEMPLATE_SIZE); elsio->u.els_plogi.els_cmd = els_opcode; elsio->u.els_plogi.els_plogi_pyld->opcode = els_opcode; if (els_opcode == ELS_DCMD_PLOGI && vha->hw->flags.edif_enabled && vha->e_dbell.db_flags & EDB_ACTIVE) { struct fc_els_flogi *p = ptr; p->fl_csp.sp_features |= cpu_to_be16(FC_SP_FT_SEC); } ql_dbg(ql_dbg_disc + ql_dbg_buffer, vha, 0x3073, "PLOGI buffer:\n"); ql_dump_buffer(ql_dbg_disc + ql_dbg_buffer, vha, 0x0109, (uint8_t *)elsio->u.els_plogi.els_plogi_pyld, sizeof(*elsio->u.els_plogi.els_plogi_pyld)); init_completion(&elsio->u.els_plogi.comp); rval = qla2x00_start_sp(sp); if (rval != QLA_SUCCESS) { rval = QLA_FUNCTION_FAILED; } else { ql_dbg(ql_dbg_disc, vha, 0x3074, "%s PLOGI sent, hdl=%x, loopid=%x, to port_id %06x from port_id %06x\n", sp->name, sp->handle, fcport->loop_id, fcport->d_id.b24, vha->d_id.b24); } if (wait) { wait_for_completion(&elsio->u.els_plogi.comp); if (elsio->u.els_plogi.comp_status != CS_COMPLETE) rval = QLA_FUNCTION_FAILED; } else { goto done; } out: fcport->flags &= ~(FCF_ASYNC_SENT | FCF_ASYNC_ACTIVE); qla2x00_els_dcmd2_free(vha, &elsio->u.els_plogi); sp->free(sp); done: return rval; } /* it is assume qpair lock is held */ void qla_els_pt_iocb(struct scsi_qla_host *vha, struct els_entry_24xx *els_iocb, struct qla_els_pt_arg *a) { els_iocb->entry_type = ELS_IOCB_TYPE; els_iocb->entry_count = 1; els_iocb->sys_define = 0; els_iocb->entry_status = 0; els_iocb->handle = QLA_SKIP_HANDLE; els_iocb->nport_handle = a->nport_handle; els_iocb->rx_xchg_address = a->rx_xchg_address; els_iocb->tx_dsd_count = cpu_to_le16(1); els_iocb->vp_index = a->vp_idx; els_iocb->sof_type = EST_SOFI3; els_iocb->rx_dsd_count = cpu_to_le16(0); els_iocb->opcode = a->els_opcode; els_iocb->d_id[0] = a->did.b.al_pa; els_iocb->d_id[1] = a->did.b.area; els_iocb->d_id[2] = a->did.b.domain; /* For SID the byte order is different than DID */ els_iocb->s_id[1] = vha->d_id.b.al_pa; els_iocb->s_id[2] = vha->d_id.b.area; els_iocb->s_id[0] = vha->d_id.b.domain; els_iocb->control_flags = cpu_to_le16(a->control_flags); els_iocb->tx_byte_count = cpu_to_le32(a->tx_byte_count); els_iocb->tx_len = cpu_to_le32(a->tx_len); put_unaligned_le64(a->tx_addr, &els_iocb->tx_address); els_iocb->rx_byte_count = cpu_to_le32(a->rx_byte_count); els_iocb->rx_len = cpu_to_le32(a->rx_len); put_unaligned_le64(a->rx_addr, &els_iocb->rx_address); } static void qla24xx_els_iocb(srb_t *sp, struct els_entry_24xx *els_iocb) { struct bsg_job *bsg_job = sp->u.bsg_job; struct fc_bsg_request *bsg_request = bsg_job->request; els_iocb->entry_type = ELS_IOCB_TYPE; els_iocb->entry_count = 1; els_iocb->sys_define = 0; els_iocb->entry_status = 0; els_iocb->handle = sp->handle; els_iocb->nport_handle = cpu_to_le16(sp->fcport->loop_id); els_iocb->tx_dsd_count = cpu_to_le16(bsg_job->request_payload.sg_cnt); els_iocb->vp_index = sp->vha->vp_idx; els_iocb->sof_type = EST_SOFI3; els_iocb->rx_dsd_count = cpu_to_le16(bsg_job->reply_payload.sg_cnt); els_iocb->opcode = sp->type == SRB_ELS_CMD_RPT ? bsg_request->rqst_data.r_els.els_code : bsg_request->rqst_data.h_els.command_code; els_iocb->d_id[0] = sp->fcport->d_id.b.al_pa; els_iocb->d_id[1] = sp->fcport->d_id.b.area; els_iocb->d_id[2] = sp->fcport->d_id.b.domain; els_iocb->control_flags = 0; els_iocb->rx_byte_count = cpu_to_le32(bsg_job->reply_payload.payload_len); els_iocb->tx_byte_count = cpu_to_le32(bsg_job->request_payload.payload_len); put_unaligned_le64(sg_dma_address(bsg_job->request_payload.sg_list), &els_iocb->tx_address); els_iocb->tx_len = cpu_to_le32(sg_dma_len (bsg_job->request_payload.sg_list)); put_unaligned_le64(sg_dma_address(bsg_job->reply_payload.sg_list), &els_iocb->rx_address); els_iocb->rx_len = cpu_to_le32(sg_dma_len (bsg_job->reply_payload.sg_list)); sp->vha->qla_stats.control_requests++; } static void qla2x00_ct_iocb(srb_t *sp, ms_iocb_entry_t *ct_iocb) { uint16_t avail_dsds; struct dsd64 *cur_dsd; struct scatterlist *sg; int index; uint16_t tot_dsds; scsi_qla_host_t *vha = sp->vha; struct qla_hw_data *ha = vha->hw; struct bsg_job *bsg_job = sp->u.bsg_job; int entry_count = 1; memset(ct_iocb, 0, sizeof(ms_iocb_entry_t)); ct_iocb->entry_type = CT_IOCB_TYPE; ct_iocb->entry_status = 0; ct_iocb->handle1 = sp->handle; SET_TARGET_ID(ha, ct_iocb->loop_id, sp->fcport->loop_id); ct_iocb->status = cpu_to_le16(0); ct_iocb->control_flags = cpu_to_le16(0); ct_iocb->timeout = 0; ct_iocb->cmd_dsd_count = cpu_to_le16(bsg_job->request_payload.sg_cnt); ct_iocb->total_dsd_count = cpu_to_le16(bsg_job->request_payload.sg_cnt + 1); ct_iocb->req_bytecount = cpu_to_le32(bsg_job->request_payload.payload_len); ct_iocb->rsp_bytecount = cpu_to_le32(bsg_job->reply_payload.payload_len); put_unaligned_le64(sg_dma_address(bsg_job->request_payload.sg_list), &ct_iocb->req_dsd.address); ct_iocb->req_dsd.length = ct_iocb->req_bytecount; put_unaligned_le64(sg_dma_address(bsg_job->reply_payload.sg_list), &ct_iocb->rsp_dsd.address); ct_iocb->rsp_dsd.length = ct_iocb->rsp_bytecount; avail_dsds = 1; cur_dsd = &ct_iocb->rsp_dsd; index = 0; tot_dsds = bsg_job->reply_payload.sg_cnt; for_each_sg(bsg_job->reply_payload.sg_list, sg, tot_dsds, index) { cont_a64_entry_t *cont_pkt; /* Allocate additional continuation packets? */ if (avail_dsds == 0) { /* * Five DSDs are available in the Cont. * Type 1 IOCB. */ cont_pkt = qla2x00_prep_cont_type1_iocb(vha, vha->hw->req_q_map[0]); cur_dsd = cont_pkt->dsd; avail_dsds = 5; entry_count++; } append_dsd64(&cur_dsd, sg); avail_dsds--; } ct_iocb->entry_count = entry_count; sp->vha->qla_stats.control_requests++; } static void qla24xx_ct_iocb(srb_t *sp, struct ct_entry_24xx *ct_iocb) { uint16_t avail_dsds; struct dsd64 *cur_dsd; struct scatterlist *sg; int index; uint16_t cmd_dsds, rsp_dsds; scsi_qla_host_t *vha = sp->vha; struct qla_hw_data *ha = vha->hw; struct bsg_job *bsg_job = sp->u.bsg_job; int entry_count = 1; cont_a64_entry_t *cont_pkt = NULL; ct_iocb->entry_type = CT_IOCB_TYPE; ct_iocb->entry_status = 0; ct_iocb->sys_define = 0; ct_iocb->handle = sp->handle; ct_iocb->nport_handle = cpu_to_le16(sp->fcport->loop_id); ct_iocb->vp_index = sp->vha->vp_idx; ct_iocb->comp_status = cpu_to_le16(0); cmd_dsds = bsg_job->request_payload.sg_cnt; rsp_dsds = bsg_job->reply_payload.sg_cnt; ct_iocb->cmd_dsd_count = cpu_to_le16(cmd_dsds); ct_iocb->timeout = 0; ct_iocb->rsp_dsd_count = cpu_to_le16(rsp_dsds); ct_iocb->cmd_byte_count = cpu_to_le32(bsg_job->request_payload.payload_len); avail_dsds = 2; cur_dsd = ct_iocb->dsd; index = 0; for_each_sg(bsg_job->request_payload.sg_list, sg, cmd_dsds, index) { /* Allocate additional continuation packets? */ if (avail_dsds == 0) { /* * Five DSDs are available in the Cont. * Type 1 IOCB. */ cont_pkt = qla2x00_prep_cont_type1_iocb( vha, ha->req_q_map[0]); cur_dsd = cont_pkt->dsd; avail_dsds = 5; entry_count++; } append_dsd64(&cur_dsd, sg); avail_dsds--; } index = 0; for_each_sg(bsg_job->reply_payload.sg_list, sg, rsp_dsds, index) { /* Allocate additional continuation packets? */ if (avail_dsds == 0) { /* * Five DSDs are available in the Cont. * Type 1 IOCB. */ cont_pkt = qla2x00_prep_cont_type1_iocb(vha, ha->req_q_map[0]); cur_dsd = cont_pkt->dsd; avail_dsds = 5; entry_count++; } append_dsd64(&cur_dsd, sg); avail_dsds--; } ct_iocb->entry_count = entry_count; } /* * qla82xx_start_scsi() - Send a SCSI command to the ISP * @sp: command to send to the ISP * * Returns non-zero if a failure occurred, else zero. */ int qla82xx_start_scsi(srb_t *sp) { int nseg; unsigned long flags; struct scsi_cmnd *cmd; uint32_t *clr_ptr; uint32_t handle; uint16_t cnt; uint16_t req_cnt; uint16_t tot_dsds; struct device_reg_82xx __iomem *reg; uint32_t dbval; __be32 *fcp_dl; uint8_t additional_cdb_len; struct ct6_dsd *ctx; struct scsi_qla_host *vha = sp->vha; struct qla_hw_data *ha = vha->hw; struct req_que *req = NULL; struct rsp_que *rsp = NULL; /* Setup device pointers. */ reg = &ha->iobase->isp82; cmd = GET_CMD_SP(sp); req = vha->req; rsp = ha->rsp_q_map[0]; /* So we know we haven't pci_map'ed anything yet */ tot_dsds = 0; dbval = 0x04 | (ha->portnum << 5); /* Send marker if required */ if (vha->marker_needed != 0) { if (qla2x00_marker(vha, ha->base_qpair, 0, 0, MK_SYNC_ALL) != QLA_SUCCESS) { ql_log(ql_log_warn, vha, 0x300c, "qla2x00_marker failed for cmd=%p.\n", cmd); return QLA_FUNCTION_FAILED; } vha->marker_needed = 0; } /* Acquire ring specific lock */ spin_lock_irqsave(&ha->hardware_lock, flags); handle = qla2xxx_get_next_handle(req); if (handle == 0) goto queuing_error; /* Map the sg table so we have an accurate count of sg entries needed */ if (scsi_sg_count(cmd)) { nseg = dma_map_sg(&ha->pdev->dev, scsi_sglist(cmd), scsi_sg_count(cmd), cmd->sc_data_direction); if (unlikely(!nseg)) goto queuing_error; } else nseg = 0; tot_dsds = nseg; if (tot_dsds > ql2xshiftctondsd) { struct cmd_type_6 *cmd_pkt; uint16_t more_dsd_lists = 0; struct dsd_dma *dsd_ptr; uint16_t i; more_dsd_lists = qla24xx_calc_dsd_lists(tot_dsds); if ((more_dsd_lists + ha->gbl_dsd_inuse) >= NUM_DSD_CHAIN) { ql_dbg(ql_dbg_io, vha, 0x300d, "Num of DSD list %d is than %d for cmd=%p.\n", more_dsd_lists + ha->gbl_dsd_inuse, NUM_DSD_CHAIN, cmd); goto queuing_error; } if (more_dsd_lists <= ha->gbl_dsd_avail) goto sufficient_dsds; else more_dsd_lists -= ha->gbl_dsd_avail; for (i = 0; i < more_dsd_lists; i++) { dsd_ptr = kzalloc(sizeof(struct dsd_dma), GFP_ATOMIC); if (!dsd_ptr) { ql_log(ql_log_fatal, vha, 0x300e, "Failed to allocate memory for dsd_dma " "for cmd=%p.\n", cmd); goto queuing_error; } dsd_ptr->dsd_addr = dma_pool_alloc(ha->dl_dma_pool, GFP_ATOMIC, &dsd_ptr->dsd_list_dma); if (!dsd_ptr->dsd_addr) { kfree(dsd_ptr); ql_log(ql_log_fatal, vha, 0x300f, "Failed to allocate memory for dsd_addr " "for cmd=%p.\n", cmd); goto queuing_error; } list_add_tail(&dsd_ptr->list, &ha->gbl_dsd_list); ha->gbl_dsd_avail++; } sufficient_dsds: req_cnt = 1; if (req->cnt < (req_cnt + 2)) { cnt = (uint16_t)rd_reg_dword_relaxed( &reg->req_q_out[0]); if (req->ring_index < cnt) req->cnt = cnt - req->ring_index; else req->cnt = req->length - (req->ring_index - cnt); if (req->cnt < (req_cnt + 2)) goto queuing_error; } ctx = sp->u.scmd.ct6_ctx = mempool_alloc(ha->ctx_mempool, GFP_ATOMIC); if (!ctx) { ql_log(ql_log_fatal, vha, 0x3010, "Failed to allocate ctx for cmd=%p.\n", cmd); goto queuing_error; } memset(ctx, 0, sizeof(struct ct6_dsd)); ctx->fcp_cmnd = dma_pool_zalloc(ha->fcp_cmnd_dma_pool, GFP_ATOMIC, &ctx->fcp_cmnd_dma); if (!ctx->fcp_cmnd) { ql_log(ql_log_fatal, vha, 0x3011, "Failed to allocate fcp_cmnd for cmd=%p.\n", cmd); goto queuing_error; } /* Initialize the DSD list and dma handle */ INIT_LIST_HEAD(&ctx->dsd_list); ctx->dsd_use_cnt = 0; if (cmd->cmd_len > 16) { additional_cdb_len = cmd->cmd_len - 16; if ((cmd->cmd_len % 4) != 0) { /* SCSI command bigger than 16 bytes must be * multiple of 4 */ ql_log(ql_log_warn, vha, 0x3012, "scsi cmd len %d not multiple of 4 " "for cmd=%p.\n", cmd->cmd_len, cmd); goto queuing_error_fcp_cmnd; } ctx->fcp_cmnd_len = 12 + cmd->cmd_len + 4; } else { additional_cdb_len = 0; ctx->fcp_cmnd_len = 12 + 16 + 4; } cmd_pkt = (struct cmd_type_6 *)req->ring_ptr; cmd_pkt->handle = make_handle(req->id, handle); /* Zero out remaining portion of packet. */ /* tagged queuing modifier -- default is TSK_SIMPLE (0). */ clr_ptr = (uint32_t *)cmd_pkt + 2; memset(clr_ptr, 0, REQUEST_ENTRY_SIZE - 8); cmd_pkt->dseg_count = cpu_to_le16(tot_dsds); /* Set NPORT-ID and LUN number*/ cmd_pkt->nport_handle = cpu_to_le16(sp->fcport->loop_id); cmd_pkt->port_id[0] = sp->fcport->d_id.b.al_pa; cmd_pkt->port_id[1] = sp->fcport->d_id.b.area; cmd_pkt->port_id[2] = sp->fcport->d_id.b.domain; cmd_pkt->vp_index = sp->vha->vp_idx; /* Build IOCB segments */ if (qla24xx_build_scsi_type_6_iocbs(sp, cmd_pkt, tot_dsds)) goto queuing_error_fcp_cmnd; int_to_scsilun(cmd->device->lun, &cmd_pkt->lun); host_to_fcp_swap((uint8_t *)&cmd_pkt->lun, sizeof(cmd_pkt->lun)); /* build FCP_CMND IU */ int_to_scsilun(cmd->device->lun, &ctx->fcp_cmnd->lun); ctx->fcp_cmnd->additional_cdb_len = additional_cdb_len; if (cmd->sc_data_direction == DMA_TO_DEVICE) ctx->fcp_cmnd->additional_cdb_len |= 1; else if (cmd->sc_data_direction == DMA_FROM_DEVICE) ctx->fcp_cmnd->additional_cdb_len |= 2; /* Populate the FCP_PRIO. */ if (ha->flags.fcp_prio_enabled) ctx->fcp_cmnd->task_attribute |= sp->fcport->fcp_prio << 3; memcpy(ctx->fcp_cmnd->cdb, cmd->cmnd, cmd->cmd_len); fcp_dl = (__be32 *)(ctx->fcp_cmnd->cdb + 16 + additional_cdb_len); *fcp_dl = htonl((uint32_t)scsi_bufflen(cmd)); cmd_pkt->fcp_cmnd_dseg_len = cpu_to_le16(ctx->fcp_cmnd_len); put_unaligned_le64(ctx->fcp_cmnd_dma, &cmd_pkt->fcp_cmnd_dseg_address); sp->flags |= SRB_FCP_CMND_DMA_VALID; cmd_pkt->byte_count = cpu_to_le32((uint32_t)scsi_bufflen(cmd)); /* Set total data segment count. */ cmd_pkt->entry_count = (uint8_t)req_cnt; /* Specify response queue number where * completion should happen */ cmd_pkt->entry_status = (uint8_t) rsp->id; } else { struct cmd_type_7 *cmd_pkt; req_cnt = qla24xx_calc_iocbs(vha, tot_dsds); if (req->cnt < (req_cnt + 2)) { cnt = (uint16_t)rd_reg_dword_relaxed( &reg->req_q_out[0]); if (req->ring_index < cnt) req->cnt = cnt - req->ring_index; else req->cnt = req->length - (req->ring_index - cnt); } if (req->cnt < (req_cnt + 2)) goto queuing_error; cmd_pkt = (struct cmd_type_7 *)req->ring_ptr; cmd_pkt->handle = make_handle(req->id, handle); /* Zero out remaining portion of packet. */ /* tagged queuing modifier -- default is TSK_SIMPLE (0).*/ clr_ptr = (uint32_t *)cmd_pkt + 2; memset(clr_ptr, 0, REQUEST_ENTRY_SIZE - 8); cmd_pkt->dseg_count = cpu_to_le16(tot_dsds); /* Set NPORT-ID and LUN number*/ cmd_pkt->nport_handle = cpu_to_le16(sp->fcport->loop_id); cmd_pkt->port_id[0] = sp->fcport->d_id.b.al_pa; cmd_pkt->port_id[1] = sp->fcport->d_id.b.area; cmd_pkt->port_id[2] = sp->fcport->d_id.b.domain; cmd_pkt->vp_index = sp->vha->vp_idx; int_to_scsilun(cmd->device->lun, &cmd_pkt->lun); host_to_fcp_swap((uint8_t *)&cmd_pkt->lun, sizeof(cmd_pkt->lun)); /* Populate the FCP_PRIO. */ if (ha->flags.fcp_prio_enabled) cmd_pkt->task |= sp->fcport->fcp_prio << 3; /* Load SCSI command packet. */ memcpy(cmd_pkt->fcp_cdb, cmd->cmnd, cmd->cmd_len); host_to_fcp_swap(cmd_pkt->fcp_cdb, sizeof(cmd_pkt->fcp_cdb)); cmd_pkt->byte_count = cpu_to_le32((uint32_t)scsi_bufflen(cmd)); /* Build IOCB segments */ qla24xx_build_scsi_iocbs(sp, cmd_pkt, tot_dsds, req); /* Set total data segment count. */ cmd_pkt->entry_count = (uint8_t)req_cnt; /* Specify response queue number where * completion should happen. */ cmd_pkt->entry_status = (uint8_t) rsp->id; } /* Build command packet. */ req->current_outstanding_cmd = handle; req->outstanding_cmds[handle] = sp; sp->handle = handle; cmd->host_scribble = (unsigned char *)(unsigned long)handle; req->cnt -= req_cnt; wmb(); /* Adjust ring index. */ req->ring_index++; if (req->ring_index == req->length) { req->ring_index = 0; req->ring_ptr = req->ring; } else req->ring_ptr++; sp->flags |= SRB_DMA_VALID; /* Set chip new ring index. */ /* write, read and verify logic */ dbval = dbval | (req->id << 8) | (req->ring_index << 16); if (ql2xdbwr) qla82xx_wr_32(ha, (uintptr_t __force)ha->nxdb_wr_ptr, dbval); else { wrt_reg_dword(ha->nxdb_wr_ptr, dbval); wmb(); while (rd_reg_dword(ha->nxdb_rd_ptr) != dbval) { wrt_reg_dword(ha->nxdb_wr_ptr, dbval); wmb(); } } /* Manage unprocessed RIO/ZIO commands in response queue. */ if (vha->flags.process_response_queue && rsp->ring_ptr->signature != RESPONSE_PROCESSED) qla24xx_process_response_queue(vha, rsp); spin_unlock_irqrestore(&ha->hardware_lock, flags); return QLA_SUCCESS; queuing_error_fcp_cmnd: dma_pool_free(ha->fcp_cmnd_dma_pool, ctx->fcp_cmnd, ctx->fcp_cmnd_dma); queuing_error: if (tot_dsds) scsi_dma_unmap(cmd); if (sp->u.scmd.crc_ctx) { mempool_free(sp->u.scmd.crc_ctx, ha->ctx_mempool); sp->u.scmd.crc_ctx = NULL; } spin_unlock_irqrestore(&ha->hardware_lock, flags); return QLA_FUNCTION_FAILED; } static void qla24xx_abort_iocb(srb_t *sp, struct abort_entry_24xx *abt_iocb) { struct srb_iocb *aio = &sp->u.iocb_cmd; scsi_qla_host_t *vha = sp->vha; struct req_que *req = sp->qpair->req; srb_t *orig_sp = sp->cmd_sp; memset(abt_iocb, 0, sizeof(struct abort_entry_24xx)); abt_iocb->entry_type = ABORT_IOCB_TYPE; abt_iocb->entry_count = 1; abt_iocb->handle = make_handle(req->id, sp->handle); if (sp->fcport) { abt_iocb->nport_handle = cpu_to_le16(sp->fcport->loop_id); abt_iocb->port_id[0] = sp->fcport->d_id.b.al_pa; abt_iocb->port_id[1] = sp->fcport->d_id.b.area; abt_iocb->port_id[2] = sp->fcport->d_id.b.domain; } abt_iocb->handle_to_abort = make_handle(le16_to_cpu(aio->u.abt.req_que_no), aio->u.abt.cmd_hndl); abt_iocb->vp_index = vha->vp_idx; abt_iocb->req_que_no = aio->u.abt.req_que_no; /* need to pass original sp */ if (orig_sp) qla_nvme_abort_set_option(abt_iocb, orig_sp); /* Send the command to the firmware */ wmb(); } static void qla2x00_mb_iocb(srb_t *sp, struct mbx_24xx_entry *mbx) { int i, sz; mbx->entry_type = MBX_IOCB_TYPE; mbx->handle = sp->handle; sz = min(ARRAY_SIZE(mbx->mb), ARRAY_SIZE(sp->u.iocb_cmd.u.mbx.out_mb)); for (i = 0; i < sz; i++) mbx->mb[i] = sp->u.iocb_cmd.u.mbx.out_mb[i]; } static void qla2x00_ctpthru_cmd_iocb(srb_t *sp, struct ct_entry_24xx *ct_pkt) { sp->u.iocb_cmd.u.ctarg.iocb = ct_pkt; qla24xx_prep_ms_iocb(sp->vha, &sp->u.iocb_cmd.u.ctarg); ct_pkt->handle = sp->handle; } static void qla2x00_send_notify_ack_iocb(srb_t *sp, struct nack_to_isp *nack) { struct imm_ntfy_from_isp *ntfy = sp->u.iocb_cmd.u.nack.ntfy; nack->entry_type = NOTIFY_ACK_TYPE; nack->entry_count = 1; nack->ox_id = ntfy->ox_id; nack->u.isp24.handle = sp->handle; nack->u.isp24.nport_handle = ntfy->u.isp24.nport_handle; if (le16_to_cpu(ntfy->u.isp24.status) == IMM_NTFY_ELS) { nack->u.isp24.flags = ntfy->u.isp24.flags & cpu_to_le16(NOTIFY24XX_FLAGS_PUREX_IOCB); } nack->u.isp24.srr_rx_id = ntfy->u.isp24.srr_rx_id; nack->u.isp24.status = ntfy->u.isp24.status; nack->u.isp24.status_subcode = ntfy->u.isp24.status_subcode; nack->u.isp24.fw_handle = ntfy->u.isp24.fw_handle; nack->u.isp24.exchange_address = ntfy->u.isp24.exchange_address; nack->u.isp24.srr_rel_offs = ntfy->u.isp24.srr_rel_offs; nack->u.isp24.srr_ui = ntfy->u.isp24.srr_ui; nack->u.isp24.srr_flags = 0; nack->u.isp24.srr_reject_code = 0; nack->u.isp24.srr_reject_code_expl = 0; nack->u.isp24.vp_index = ntfy->u.isp24.vp_index; if (ntfy->u.isp24.status_subcode == ELS_PLOGI && (le16_to_cpu(ntfy->u.isp24.flags) & NOTIFY24XX_FLAGS_FCSP) && sp->vha->hw->flags.edif_enabled) { ql_dbg(ql_dbg_disc, sp->vha, 0x3074, "%s PLOGI NACK sent with FC SECURITY bit, hdl=%x, loopid=%x, to pid %06x\n", sp->name, sp->handle, sp->fcport->loop_id, sp->fcport->d_id.b24); nack->u.isp24.flags |= cpu_to_le16(NOTIFY_ACK_FLAGS_FCSP); } } /* * Build NVME LS request */ static void qla_nvme_ls(srb_t *sp, struct pt_ls4_request *cmd_pkt) { struct srb_iocb *nvme; nvme = &sp->u.iocb_cmd; cmd_pkt->entry_type = PT_LS4_REQUEST; cmd_pkt->entry_count = 1; cmd_pkt->control_flags = cpu_to_le16(CF_LS4_ORIGINATOR << CF_LS4_SHIFT); cmd_pkt->timeout = cpu_to_le16(nvme->u.nvme.timeout_sec); cmd_pkt->nport_handle = cpu_to_le16(sp->fcport->loop_id); cmd_pkt->vp_index = sp->fcport->vha->vp_idx; cmd_pkt->tx_dseg_count = cpu_to_le16(1); cmd_pkt->tx_byte_count = cpu_to_le32(nvme->u.nvme.cmd_len); cmd_pkt->dsd[0].length = cpu_to_le32(nvme->u.nvme.cmd_len); put_unaligned_le64(nvme->u.nvme.cmd_dma, &cmd_pkt->dsd[0].address); cmd_pkt->rx_dseg_count = cpu_to_le16(1); cmd_pkt->rx_byte_count = cpu_to_le32(nvme->u.nvme.rsp_len); cmd_pkt->dsd[1].length = cpu_to_le32(nvme->u.nvme.rsp_len); put_unaligned_le64(nvme->u.nvme.rsp_dma, &cmd_pkt->dsd[1].address); } static void qla25xx_ctrlvp_iocb(srb_t *sp, struct vp_ctrl_entry_24xx *vce) { int map, pos; vce->entry_type = VP_CTRL_IOCB_TYPE; vce->handle = sp->handle; vce->entry_count = 1; vce->command = cpu_to_le16(sp->u.iocb_cmd.u.ctrlvp.cmd); vce->vp_count = cpu_to_le16(1); /* * index map in firmware starts with 1; decrement index * this is ok as we never use index 0 */ map = (sp->u.iocb_cmd.u.ctrlvp.vp_index - 1) / 8; pos = (sp->u.iocb_cmd.u.ctrlvp.vp_index - 1) & 7; vce->vp_idx_map[map] |= 1 << pos; } static void qla24xx_prlo_iocb(srb_t *sp, struct logio_entry_24xx *logio) { logio->entry_type = LOGINOUT_PORT_IOCB_TYPE; logio->control_flags = cpu_to_le16(LCF_COMMAND_PRLO|LCF_IMPL_PRLO); logio->nport_handle = cpu_to_le16(sp->fcport->loop_id); logio->port_id[0] = sp->fcport->d_id.b.al_pa; logio->port_id[1] = sp->fcport->d_id.b.area; logio->port_id[2] = sp->fcport->d_id.b.domain; logio->vp_index = sp->fcport->vha->vp_idx; } int qla2x00_start_sp(srb_t *sp) { int rval = QLA_SUCCESS; scsi_qla_host_t *vha = sp->vha; struct qla_hw_data *ha = vha->hw; struct qla_qpair *qp = sp->qpair; void *pkt; unsigned long flags; if (vha->hw->flags.eeh_busy) return -EIO; spin_lock_irqsave(qp->qp_lock_ptr, flags); pkt = __qla2x00_alloc_iocbs(sp->qpair, sp); if (!pkt) { rval = EAGAIN; ql_log(ql_log_warn, vha, 0x700c, "qla2x00_alloc_iocbs failed.\n"); goto done; } switch (sp->type) { case SRB_LOGIN_CMD: IS_FWI2_CAPABLE(ha) ? qla24xx_login_iocb(sp, pkt) : qla2x00_login_iocb(sp, pkt); break; case SRB_PRLI_CMD: qla24xx_prli_iocb(sp, pkt); break; case SRB_LOGOUT_CMD: IS_FWI2_CAPABLE(ha) ? qla24xx_logout_iocb(sp, pkt) : qla2x00_logout_iocb(sp, pkt); break; case SRB_ELS_CMD_RPT: case SRB_ELS_CMD_HST: qla24xx_els_iocb(sp, pkt); break; case SRB_ELS_CMD_HST_NOLOGIN: qla_els_pt_iocb(sp->vha, pkt, &sp->u.bsg_cmd.u.els_arg); ((struct els_entry_24xx *)pkt)->handle = sp->handle; break; case SRB_CT_CMD: IS_FWI2_CAPABLE(ha) ? qla24xx_ct_iocb(sp, pkt) : qla2x00_ct_iocb(sp, pkt); break; case SRB_ADISC_CMD: IS_FWI2_CAPABLE(ha) ? qla24xx_adisc_iocb(sp, pkt) : qla2x00_adisc_iocb(sp, pkt); break; case SRB_TM_CMD: IS_QLAFX00(ha) ? qlafx00_tm_iocb(sp, pkt) : qla24xx_tm_iocb(sp, pkt); break; case SRB_FXIOCB_DCMD: case SRB_FXIOCB_BCMD: qlafx00_fxdisc_iocb(sp, pkt); break; case SRB_NVME_LS: qla_nvme_ls(sp, pkt); break; case SRB_ABT_CMD: IS_QLAFX00(ha) ? qlafx00_abort_iocb(sp, pkt) : qla24xx_abort_iocb(sp, pkt); break; case SRB_ELS_DCMD: qla24xx_els_logo_iocb(sp, pkt); break; case SRB_CT_PTHRU_CMD: qla2x00_ctpthru_cmd_iocb(sp, pkt); break; case SRB_MB_IOCB: qla2x00_mb_iocb(sp, pkt); break; case SRB_NACK_PLOGI: case SRB_NACK_PRLI: case SRB_NACK_LOGO: qla2x00_send_notify_ack_iocb(sp, pkt); break; case SRB_CTRL_VP: qla25xx_ctrlvp_iocb(sp, pkt); break; case SRB_PRLO_CMD: qla24xx_prlo_iocb(sp, pkt); break; case SRB_SA_UPDATE: qla24xx_sa_update_iocb(sp, pkt); break; case SRB_SA_REPLACE: qla24xx_sa_replace_iocb(sp, pkt); break; default: break; } if (sp->start_timer) add_timer(&sp->u.iocb_cmd.timer); wmb(); qla2x00_start_iocbs(vha, qp->req); done: spin_unlock_irqrestore(qp->qp_lock_ptr, flags); return rval; } static void qla25xx_build_bidir_iocb(srb_t *sp, struct scsi_qla_host *vha, struct cmd_bidir *cmd_pkt, uint32_t tot_dsds) { uint16_t avail_dsds; struct dsd64 *cur_dsd; uint32_t req_data_len = 0; uint32_t rsp_data_len = 0; struct scatterlist *sg; int index; int entry_count = 1; struct bsg_job *bsg_job = sp->u.bsg_job; /*Update entry type to indicate bidir command */ put_unaligned_le32(COMMAND_BIDIRECTIONAL, &cmd_pkt->entry_type); /* Set the transfer direction, in this set both flags * Also set the BD_WRAP_BACK flag, firmware will take care * assigning DID=SID for outgoing pkts. */ cmd_pkt->wr_dseg_count = cpu_to_le16(bsg_job->request_payload.sg_cnt); cmd_pkt->rd_dseg_count = cpu_to_le16(bsg_job->reply_payload.sg_cnt); cmd_pkt->control_flags = cpu_to_le16(BD_WRITE_DATA | BD_READ_DATA | BD_WRAP_BACK); req_data_len = rsp_data_len = bsg_job->request_payload.payload_len; cmd_pkt->wr_byte_count = cpu_to_le32(req_data_len); cmd_pkt->rd_byte_count = cpu_to_le32(rsp_data_len); cmd_pkt->timeout = cpu_to_le16(qla2x00_get_async_timeout(vha) + 2); vha->bidi_stats.transfer_bytes += req_data_len; vha->bidi_stats.io_count++; vha->qla_stats.output_bytes += req_data_len; vha->qla_stats.output_requests++; /* Only one dsd is available for bidirectional IOCB, remaining dsds * are bundled in continuation iocb */ avail_dsds = 1; cur_dsd = &cmd_pkt->fcp_dsd; index = 0; for_each_sg(bsg_job->request_payload.sg_list, sg, bsg_job->request_payload.sg_cnt, index) { cont_a64_entry_t *cont_pkt; /* Allocate additional continuation packets */ if (avail_dsds == 0) { /* Continuation type 1 IOCB can accomodate * 5 DSDS */ cont_pkt = qla2x00_prep_cont_type1_iocb(vha, vha->req); cur_dsd = cont_pkt->dsd; avail_dsds = 5; entry_count++; } append_dsd64(&cur_dsd, sg); avail_dsds--; } /* For read request DSD will always goes to continuation IOCB * and follow the write DSD. If there is room on the current IOCB * then it is added to that IOCB else new continuation IOCB is * allocated. */ for_each_sg(bsg_job->reply_payload.sg_list, sg, bsg_job->reply_payload.sg_cnt, index) { cont_a64_entry_t *cont_pkt; /* Allocate additional continuation packets */ if (avail_dsds == 0) { /* Continuation type 1 IOCB can accomodate * 5 DSDS */ cont_pkt = qla2x00_prep_cont_type1_iocb(vha, vha->req); cur_dsd = cont_pkt->dsd; avail_dsds = 5; entry_count++; } append_dsd64(&cur_dsd, sg); avail_dsds--; } /* This value should be same as number of IOCB required for this cmd */ cmd_pkt->entry_count = entry_count; } int qla2x00_start_bidir(srb_t *sp, struct scsi_qla_host *vha, uint32_t tot_dsds) { struct qla_hw_data *ha = vha->hw; unsigned long flags; uint32_t handle; uint16_t req_cnt; uint16_t cnt; uint32_t *clr_ptr; struct cmd_bidir *cmd_pkt = NULL; struct rsp_que *rsp; struct req_que *req; int rval = EXT_STATUS_OK; rval = QLA_SUCCESS; rsp = ha->rsp_q_map[0]; req = vha->req; /* Send marker if required */ if (vha->marker_needed != 0) { if (qla2x00_marker(vha, ha->base_qpair, 0, 0, MK_SYNC_ALL) != QLA_SUCCESS) return EXT_STATUS_MAILBOX; vha->marker_needed = 0; } /* Acquire ring specific lock */ spin_lock_irqsave(&ha->hardware_lock, flags); handle = qla2xxx_get_next_handle(req); if (handle == 0) { rval = EXT_STATUS_BUSY; goto queuing_error; } /* Calculate number of IOCB required */ req_cnt = qla24xx_calc_iocbs(vha, tot_dsds); /* Check for room on request queue. */ if (req->cnt < req_cnt + 2) { if (IS_SHADOW_REG_CAPABLE(ha)) { cnt = *req->out_ptr; } else { cnt = rd_reg_dword_relaxed(req->req_q_out); if (qla2x00_check_reg16_for_disconnect(vha, cnt)) goto queuing_error; } if (req->ring_index < cnt) req->cnt = cnt - req->ring_index; else req->cnt = req->length - (req->ring_index - cnt); } if (req->cnt < req_cnt + 2) { rval = EXT_STATUS_BUSY; goto queuing_error; } cmd_pkt = (struct cmd_bidir *)req->ring_ptr; cmd_pkt->handle = make_handle(req->id, handle); /* Zero out remaining portion of packet. */ /* tagged queuing modifier -- default is TSK_SIMPLE (0).*/ clr_ptr = (uint32_t *)cmd_pkt + 2; memset(clr_ptr, 0, REQUEST_ENTRY_SIZE - 8); /* Set NPORT-ID (of vha)*/ cmd_pkt->nport_handle = cpu_to_le16(vha->self_login_loop_id); cmd_pkt->port_id[0] = vha->d_id.b.al_pa; cmd_pkt->port_id[1] = vha->d_id.b.area; cmd_pkt->port_id[2] = vha->d_id.b.domain; qla25xx_build_bidir_iocb(sp, vha, cmd_pkt, tot_dsds); cmd_pkt->entry_status = (uint8_t) rsp->id; /* Build command packet. */ req->current_outstanding_cmd = handle; req->outstanding_cmds[handle] = sp; sp->handle = handle; req->cnt -= req_cnt; /* Send the command to the firmware */ wmb(); qla2x00_start_iocbs(vha, req); queuing_error: spin_unlock_irqrestore(&ha->hardware_lock, flags); return rval; }
481561.c
/* Dynamic architecture support for GDB, the GNU debugger. Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. This file is part of GDB. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "defs.h" #include "arch-utils.h" #include "buildsym.h" #include "gdbcmd.h" #include "inferior.h" /* enum CALL_DUMMY_LOCATION et.al. */ #include "gdb_string.h" #include "regcache.h" #include "gdb_assert.h" #include "sim-regno.h" #include "gdbcore.h" #include "osabi.h" #include "target-descriptions.h" #include "version.h" #include "floatformat.h" int legacy_register_sim_regno (struct gdbarch *gdbarch, int regnum) { /* Only makes sense to supply raw registers. */ gdb_assert (regnum >= 0 && regnum < gdbarch_num_regs (gdbarch)); /* NOTE: cagney/2002-05-13: The old code did it this way and it is suspected that some GDB/SIM combinations may rely on this behavour. The default should be one2one_register_sim_regno (below). */ if (gdbarch_register_name (gdbarch, regnum) != NULL && gdbarch_register_name (gdbarch, regnum)[0] != '\0') return regnum; else return LEGACY_SIM_REGNO_IGNORE; } CORE_ADDR generic_skip_trampoline_code (struct frame_info *frame, CORE_ADDR pc) { return 0; } CORE_ADDR generic_skip_solib_resolver (struct gdbarch *gdbarch, CORE_ADDR pc) { return 0; } int generic_in_solib_return_trampoline (CORE_ADDR pc, char *name) { return 0; } int generic_in_function_epilogue_p (struct gdbarch *gdbarch, CORE_ADDR pc) { return 0; } /* Helper functions for gdbarch_inner_than */ int core_addr_lessthan (CORE_ADDR lhs, CORE_ADDR rhs) { return (lhs < rhs); } int core_addr_greaterthan (CORE_ADDR lhs, CORE_ADDR rhs) { return (lhs > rhs); } /* Misc helper functions for targets. */ CORE_ADDR core_addr_identity (CORE_ADDR addr) { return addr; } CORE_ADDR convert_from_func_ptr_addr_identity (struct gdbarch *gdbarch, CORE_ADDR addr, struct target_ops *targ) { return addr; } int no_op_reg_to_regnum (struct gdbarch *gdbarch, int reg) { return reg; } void default_elf_make_msymbol_special (asymbol *sym, struct minimal_symbol *msym) { return; } void default_coff_make_msymbol_special (int val, struct minimal_symbol *msym) { return; } int cannot_register_not (struct gdbarch *gdbarch, int regnum) { return 0; } /* Legacy version of target_virtual_frame_pointer(). Assumes that there is an gdbarch_deprecated_fp_regnum and that it is the same, cooked or raw. */ void legacy_virtual_frame_pointer (struct gdbarch *gdbarch, CORE_ADDR pc, int *frame_regnum, LONGEST *frame_offset) { /* FIXME: cagney/2002-09-13: This code is used when identifying the frame pointer of the current PC. It is assuming that a single register and an offset can determine this. I think it should instead generate a byte code expression as that would work better with things like Dwarf2's CFI. */ if (gdbarch_deprecated_fp_regnum (gdbarch) >= 0 && gdbarch_deprecated_fp_regnum (gdbarch) < gdbarch_num_regs (gdbarch)) *frame_regnum = gdbarch_deprecated_fp_regnum (gdbarch); else if (gdbarch_sp_regnum (gdbarch) >= 0 && gdbarch_sp_regnum (gdbarch) < gdbarch_num_regs (gdbarch)) *frame_regnum = gdbarch_sp_regnum (gdbarch); else /* Should this be an internal error? I guess so, it is reflecting an architectural limitation in the current design. */ internal_error (__FILE__, __LINE__, _("No virtual frame pointer available")); *frame_offset = 0; } int generic_convert_register_p (struct gdbarch *gdbarch, int regnum, struct type *type) { return 0; } int default_stabs_argument_has_addr (struct gdbarch *gdbarch, struct type *type) { return 0; } int generic_instruction_nullified (struct gdbarch *gdbarch, struct regcache *regcache) { return 0; } int default_remote_register_number (struct gdbarch *gdbarch, int regno) { return regno; } /* Functions to manipulate the endianness of the target. */ static int target_byte_order_user = BFD_ENDIAN_UNKNOWN; static const char endian_big[] = "big"; static const char endian_little[] = "little"; static const char endian_auto[] = "auto"; static const char *endian_enum[] = { endian_big, endian_little, endian_auto, NULL, }; static const char *set_endian_string; enum bfd_endian selected_byte_order (void) { if (target_byte_order_user != BFD_ENDIAN_UNKNOWN) return gdbarch_byte_order (current_gdbarch); else return BFD_ENDIAN_UNKNOWN; } /* Called by ``show endian''. */ static void show_endian (struct ui_file *file, int from_tty, struct cmd_list_element *c, const char *value) { if (target_byte_order_user == BFD_ENDIAN_UNKNOWN) if (gdbarch_byte_order (current_gdbarch) == BFD_ENDIAN_BIG) fprintf_unfiltered (file, _("The target endianness is set automatically " "(currently big endian)\n")); else fprintf_unfiltered (file, _("The target endianness is set automatically " "(currently little endian)\n")); else if (gdbarch_byte_order (current_gdbarch) == BFD_ENDIAN_BIG) fprintf_unfiltered (file, _("The target is assumed to be big endian\n")); else fprintf_unfiltered (file, _("The target is assumed to be little endian\n")); } static void set_endian (char *ignore_args, int from_tty, struct cmd_list_element *c) { struct gdbarch_info info; gdbarch_info_init (&info); if (set_endian_string == endian_auto) { target_byte_order_user = BFD_ENDIAN_UNKNOWN; if (! gdbarch_update_p (info)) internal_error (__FILE__, __LINE__, _("set_endian: architecture update failed")); } else if (set_endian_string == endian_little) { info.byte_order = BFD_ENDIAN_LITTLE; if (! gdbarch_update_p (info)) printf_unfiltered (_("Little endian target not supported by GDB\n")); else target_byte_order_user = BFD_ENDIAN_LITTLE; } else if (set_endian_string == endian_big) { info.byte_order = BFD_ENDIAN_BIG; if (! gdbarch_update_p (info)) printf_unfiltered (_("Big endian target not supported by GDB\n")); else target_byte_order_user = BFD_ENDIAN_BIG; } else internal_error (__FILE__, __LINE__, _("set_endian: bad value")); show_endian (gdb_stdout, from_tty, NULL, NULL); } /* Given SELECTED, a currently selected BFD architecture, and FROM_TARGET, a BFD architecture reported by the target description, return what architecture to use. Either may be NULL; if both are specified, we use the more specific. If the two are obviously incompatible, warn the user. */ static const struct bfd_arch_info * choose_architecture_for_target (const struct bfd_arch_info *selected, const struct bfd_arch_info *from_target) { const struct bfd_arch_info *compat1, *compat2; if (selected == NULL) return from_target; if (from_target == NULL) return selected; /* struct bfd_arch_info objects are singletons: that is, there's supposed to be exactly one instance for a given machine. So you can tell whether two are equivalent by comparing pointers. */ if (from_target == selected) return selected; /* BFD's 'A->compatible (A, B)' functions return zero if A and B are incompatible. But if they are compatible, it returns the 'more featureful' of the two arches. That is, if A can run code written for B, but B can't run code written for A, then it'll return A. Some targets (e.g. MIPS as of 2006-12-04) don't fully implement this, instead always returning NULL or the first argument. We detect that case by checking both directions. */ compat1 = selected->compatible (selected, from_target); compat2 = from_target->compatible (from_target, selected); if (compat1 == NULL && compat2 == NULL) { warning (_("Selected architecture %s is not compatible " "with reported target architecture %s"), selected->printable_name, from_target->printable_name); return selected; } if (compat1 == NULL) return compat2; if (compat2 == NULL) return compat1; if (compat1 == compat2) return compat1; /* If the two didn't match, but one of them was a default architecture, assume the more specific one is correct. This handles the case where an executable or target description just says "mips", but the other knows which MIPS variant. */ if (compat1->the_default) return compat2; if (compat2->the_default) return compat1; /* We have no idea which one is better. This is a bug, but not a critical problem; warn the user. */ warning (_("Selected architecture %s is ambiguous with " "reported target architecture %s"), selected->printable_name, from_target->printable_name); return selected; } /* Functions to manipulate the architecture of the target */ enum set_arch { set_arch_auto, set_arch_manual }; static const struct bfd_arch_info *target_architecture_user; static const char *set_architecture_string; const char * selected_architecture_name (void) { if (target_architecture_user == NULL) return NULL; else return set_architecture_string; } /* Called if the user enters ``show architecture'' without an argument. */ static void show_architecture (struct ui_file *file, int from_tty, struct cmd_list_element *c, const char *value) { const char *arch; arch = gdbarch_bfd_arch_info (current_gdbarch)->printable_name; if (target_architecture_user == NULL) fprintf_filtered (file, _("\ The target architecture is set automatically (currently %s)\n"), arch); else fprintf_filtered (file, _("\ The target architecture is assumed to be %s\n"), arch); } /* Called if the user enters ``set architecture'' with or without an argument. */ static void set_architecture (char *ignore_args, int from_tty, struct cmd_list_element *c) { struct gdbarch_info info; gdbarch_info_init (&info); if (strcmp (set_architecture_string, "auto") == 0) { target_architecture_user = NULL; if (!gdbarch_update_p (info)) internal_error (__FILE__, __LINE__, _("could not select an architecture automatically")); } else { info.bfd_arch_info = bfd_scan_arch (set_architecture_string); if (info.bfd_arch_info == NULL) internal_error (__FILE__, __LINE__, _("set_architecture: bfd_scan_arch failed")); if (gdbarch_update_p (info)) target_architecture_user = info.bfd_arch_info; else printf_unfiltered (_("Architecture `%s' not recognized.\n"), set_architecture_string); } show_architecture (gdb_stdout, from_tty, NULL, NULL); } /* Try to select a global architecture that matches "info". Return non-zero if the attempt succeds. */ int gdbarch_update_p (struct gdbarch_info info) { struct gdbarch *new_gdbarch = gdbarch_find_by_info (info); /* If there no architecture by that name, reject the request. */ if (new_gdbarch == NULL) { if (gdbarch_debug) fprintf_unfiltered (gdb_stdlog, "gdbarch_update_p: " "Architecture not found\n"); return 0; } /* If it is the same old architecture, accept the request (but don't swap anything). */ if (new_gdbarch == current_gdbarch) { if (gdbarch_debug) fprintf_unfiltered (gdb_stdlog, "gdbarch_update_p: " "Architecture 0x%08lx (%s) unchanged\n", (long) new_gdbarch, gdbarch_bfd_arch_info (new_gdbarch)->printable_name); return 1; } /* It's a new architecture, swap it in. */ if (gdbarch_debug) fprintf_unfiltered (gdb_stdlog, "gdbarch_update_p: " "New architecture 0x%08lx (%s) selected\n", (long) new_gdbarch, gdbarch_bfd_arch_info (new_gdbarch)->printable_name); deprecated_current_gdbarch_select_hack (new_gdbarch); return 1; } /* Return the architecture for ABFD. If no suitable architecture could be find, return NULL. */ struct gdbarch * gdbarch_from_bfd (bfd *abfd) { struct gdbarch_info info; /* If we call gdbarch_find_by_info without filling in info.abfd, then it will use the global exec_bfd. That's fine if we don't have one of those either. And that's the only time we should reach here with a NULL ABFD argument - when we are discarding the executable. */ gdb_assert (abfd != NULL || exec_bfd == NULL); gdbarch_info_init (&info); info.abfd = abfd; return gdbarch_find_by_info (info); } /* Set the dynamic target-system-dependent parameters (architecture, byte-order) using information found in the BFD */ void set_gdbarch_from_file (bfd *abfd) { struct gdbarch *gdbarch; gdbarch = gdbarch_from_bfd (abfd); if (gdbarch == NULL) error (_("Architecture of file not recognized.")); deprecated_current_gdbarch_select_hack (gdbarch); } /* Initialize the current architecture. Update the ``set architecture'' command so that it specifies a list of valid architectures. */ #ifdef DEFAULT_BFD_ARCH extern const bfd_arch_info_type DEFAULT_BFD_ARCH; static const bfd_arch_info_type *default_bfd_arch = &DEFAULT_BFD_ARCH; #else static const bfd_arch_info_type *default_bfd_arch; #endif #ifdef DEFAULT_BFD_VEC extern const bfd_target DEFAULT_BFD_VEC; static const bfd_target *default_bfd_vec = &DEFAULT_BFD_VEC; #else static const bfd_target *default_bfd_vec; #endif static int default_byte_order = BFD_ENDIAN_UNKNOWN; void initialize_current_architecture (void) { const char **arches = gdbarch_printable_names (); /* determine a default architecture and byte order. */ struct gdbarch_info info; gdbarch_info_init (&info); /* Find a default architecture. */ if (default_bfd_arch == NULL) { /* Choose the architecture by taking the first one alphabetically. */ const char *chosen = arches[0]; const char **arch; for (arch = arches; *arch != NULL; arch++) { if (strcmp (*arch, chosen) < 0) chosen = *arch; } if (chosen == NULL) internal_error (__FILE__, __LINE__, _("initialize_current_architecture: No arch")); default_bfd_arch = bfd_scan_arch (chosen); if (default_bfd_arch == NULL) internal_error (__FILE__, __LINE__, _("initialize_current_architecture: Arch not found")); } info.bfd_arch_info = default_bfd_arch; /* Take several guesses at a byte order. */ if (default_byte_order == BFD_ENDIAN_UNKNOWN && default_bfd_vec != NULL) { /* Extract BFD's default vector's byte order. */ switch (default_bfd_vec->byteorder) { case BFD_ENDIAN_BIG: default_byte_order = BFD_ENDIAN_BIG; break; case BFD_ENDIAN_LITTLE: default_byte_order = BFD_ENDIAN_LITTLE; break; default: break; } } if (default_byte_order == BFD_ENDIAN_UNKNOWN) { /* look for ``*el-*'' in the target name. */ const char *chp; chp = strchr (target_name, '-'); if (chp != NULL && chp - 2 >= target_name && strncmp (chp - 2, "el", 2) == 0) default_byte_order = BFD_ENDIAN_LITTLE; } if (default_byte_order == BFD_ENDIAN_UNKNOWN) { /* Wire it to big-endian!!! */ default_byte_order = BFD_ENDIAN_BIG; } info.byte_order = default_byte_order; if (! gdbarch_update_p (info)) internal_error (__FILE__, __LINE__, _("initialize_current_architecture: Selection of " "initial architecture failed")); /* Create the ``set architecture'' command appending ``auto'' to the list of architectures. */ { struct cmd_list_element *c; /* Append ``auto''. */ int nr; for (nr = 0; arches[nr] != NULL; nr++); arches = xrealloc (arches, sizeof (char*) * (nr + 2)); arches[nr + 0] = "auto"; arches[nr + 1] = NULL; add_setshow_enum_cmd ("architecture", class_support, arches, &set_architecture_string, _("\ Set architecture of target."), _("\ Show architecture of target."), NULL, set_architecture, show_architecture, &setlist, &showlist); add_alias_cmd ("processor", "architecture", class_support, 1, &setlist); } } /* Initialize a gdbarch info to values that will be automatically overridden. Note: Originally, this ``struct info'' was initialized using memset(0). Unfortunately, that ran into problems, namely BFD_ENDIAN_BIG is zero. An explicit initialization function that can explicitly set each field to a well defined value is used. */ void gdbarch_info_init (struct gdbarch_info *info) { memset (info, 0, sizeof (struct gdbarch_info)); info->byte_order = BFD_ENDIAN_UNKNOWN; info->osabi = GDB_OSABI_UNINITIALIZED; } /* Similar to init, but this time fill in the blanks. Information is obtained from the global "set ..." options and explicitly initialized INFO fields. */ void gdbarch_info_fill (struct gdbarch_info *info) { /* Check for the current file. */ if (info->abfd == NULL) info->abfd = exec_bfd; if (info->abfd == NULL) info->abfd = core_bfd; /* Check for the current target description. */ if (info->target_desc == NULL) info->target_desc = target_current_description (); /* "(gdb) set architecture ...". */ if (info->bfd_arch_info == NULL && target_architecture_user) info->bfd_arch_info = target_architecture_user; /* From the file. */ if (info->bfd_arch_info == NULL && info->abfd != NULL && bfd_get_arch (info->abfd) != bfd_arch_unknown && bfd_get_arch (info->abfd) != bfd_arch_obscure) info->bfd_arch_info = bfd_get_arch_info (info->abfd); /* From the target. */ if (info->target_desc != NULL) info->bfd_arch_info = choose_architecture_for_target (info->bfd_arch_info, tdesc_architecture (info->target_desc)); /* From the default. */ if (info->bfd_arch_info == NULL) info->bfd_arch_info = default_bfd_arch; /* "(gdb) set byte-order ...". */ if (info->byte_order == BFD_ENDIAN_UNKNOWN && target_byte_order_user != BFD_ENDIAN_UNKNOWN) info->byte_order = target_byte_order_user; /* From the INFO struct. */ if (info->byte_order == BFD_ENDIAN_UNKNOWN && info->abfd != NULL) info->byte_order = (bfd_big_endian (info->abfd) ? BFD_ENDIAN_BIG : bfd_little_endian (info->abfd) ? BFD_ENDIAN_LITTLE : BFD_ENDIAN_UNKNOWN); /* From the default. */ if (info->byte_order == BFD_ENDIAN_UNKNOWN) info->byte_order = default_byte_order; /* "(gdb) set osabi ...". Handled by gdbarch_lookup_osabi. */ if (info->osabi == GDB_OSABI_UNINITIALIZED) info->osabi = gdbarch_lookup_osabi (info->abfd); /* Must have at least filled in the architecture. */ gdb_assert (info->bfd_arch_info != NULL); } /* */ extern initialize_file_ftype _initialize_gdbarch_utils; /* -Wmissing-prototypes */ void _initialize_gdbarch_utils (void) { struct cmd_list_element *c; add_setshow_enum_cmd ("endian", class_support, endian_enum, &set_endian_string, _("\ Set endianness of target."), _("\ Show endianness of target."), NULL, set_endian, show_endian, &setlist, &showlist); }
914119.c
/* * Copyright (c) 2015, The Linux Foundation. All rights reserved. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/kernel.h> #include <linux/bitops.h> #include <linux/err.h> #include <linux/platform_device.h> #include <linux/module.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/clk-provider.h> #include <linux/regmap.h> #include <linux/reset-controller.h> #include <dt-bindings/clock/qcom,gcc-msm8996.h> #include "common.h" #include "clk-regmap.h" #include "clk-alpha-pll.h" #include "clk-rcg.h" #include "clk-branch.h" #include "reset.h" #include "gdsc.h" enum { P_XO, P_GPLL0, P_GPLL2, P_GPLL3, P_GPLL1, P_GPLL2_EARLY, P_GPLL0_EARLY_DIV, P_SLEEP_CLK, P_GPLL4, P_AUD_REF_CLK, P_GPLL1_EARLY_DIV }; static const struct parent_map gcc_sleep_clk_map[] = { { P_SLEEP_CLK, 5 } }; static const char * const gcc_sleep_clk[] = { "sleep_clk" }; static const struct parent_map gcc_xo_gpll0_map[] = { { P_XO, 0 }, { P_GPLL0, 1 } }; static const char * const gcc_xo_gpll0[] = { "xo", "gpll0" }; static const struct parent_map gcc_xo_sleep_clk_map[] = { { P_XO, 0 }, { P_SLEEP_CLK, 5 } }; static const char * const gcc_xo_sleep_clk[] = { "xo", "sleep_clk" }; static const struct parent_map gcc_xo_gpll0_gpll0_early_div_map[] = { { P_XO, 0 }, { P_GPLL0, 1 }, { P_GPLL0_EARLY_DIV, 6 } }; static const char * const gcc_xo_gpll0_gpll0_early_div[] = { "xo", "gpll0", "gpll0_early_div" }; static const struct parent_map gcc_xo_gpll0_gpll4_map[] = { { P_XO, 0 }, { P_GPLL0, 1 }, { P_GPLL4, 5 } }; static const char * const gcc_xo_gpll0_gpll4[] = { "xo", "gpll0", "gpll4" }; static const struct parent_map gcc_xo_gpll0_aud_ref_clk_map[] = { { P_XO, 0 }, { P_GPLL0, 1 }, { P_AUD_REF_CLK, 2 } }; static const char * const gcc_xo_gpll0_aud_ref_clk[] = { "xo", "gpll0", "aud_ref_clk" }; static const struct parent_map gcc_xo_gpll0_sleep_clk_gpll0_early_div_map[] = { { P_XO, 0 }, { P_GPLL0, 1 }, { P_SLEEP_CLK, 5 }, { P_GPLL0_EARLY_DIV, 6 } }; static const char * const gcc_xo_gpll0_sleep_clk_gpll0_early_div[] = { "xo", "gpll0", "sleep_clk", "gpll0_early_div" }; static const struct parent_map gcc_xo_gpll0_gpll4_gpll0_early_div_map[] = { { P_XO, 0 }, { P_GPLL0, 1 }, { P_GPLL4, 5 }, { P_GPLL0_EARLY_DIV, 6 } }; static const char * const gcc_xo_gpll0_gpll4_gpll0_early_div[] = { "xo", "gpll0", "gpll4", "gpll0_early_div" }; static const struct parent_map gcc_xo_gpll0_gpll2_gpll3_gpll0_early_div_map[] = { { P_XO, 0 }, { P_GPLL0, 1 }, { P_GPLL2, 2 }, { P_GPLL3, 3 }, { P_GPLL0_EARLY_DIV, 6 } }; static const char * const gcc_xo_gpll0_gpll2_gpll3_gpll0_early_div[] = { "xo", "gpll0", "gpll2", "gpll3", "gpll0_early_div" }; static const struct parent_map gcc_xo_gpll0_gpll1_early_div_gpll1_gpll4_gpll0_early_div_map[] = { { P_XO, 0 }, { P_GPLL0, 1 }, { P_GPLL1_EARLY_DIV, 3 }, { P_GPLL1, 4 }, { P_GPLL4, 5 }, { P_GPLL0_EARLY_DIV, 6 } }; static const char * const gcc_xo_gpll0_gpll1_early_div_gpll1_gpll4_gpll0_early_div[] = { "xo", "gpll0", "gpll1_early_div", "gpll1", "gpll4", "gpll0_early_div" }; static const struct parent_map gcc_xo_gpll0_gpll2_gpll3_gpll1_gpll2_early_gpll0_early_div_map[] = { { P_XO, 0 }, { P_GPLL0, 1 }, { P_GPLL2, 2 }, { P_GPLL3, 3 }, { P_GPLL1, 4 }, { P_GPLL2_EARLY, 5 }, { P_GPLL0_EARLY_DIV, 6 } }; static const char * const gcc_xo_gpll0_gpll2_gpll3_gpll1_gpll2_early_gpll0_early_div[] = { "xo", "gpll0", "gpll2", "gpll3", "gpll1", "gpll2_early", "gpll0_early_div" }; static const struct parent_map gcc_xo_gpll0_gpll2_gpll3_gpll1_gpll4_gpll0_early_div_map[] = { { P_XO, 0 }, { P_GPLL0, 1 }, { P_GPLL2, 2 }, { P_GPLL3, 3 }, { P_GPLL1, 4 }, { P_GPLL4, 5 }, { P_GPLL0_EARLY_DIV, 6 } }; static const char * const gcc_xo_gpll0_gpll2_gpll3_gpll1_gpll4_gpll0_early_div[] = { "xo", "gpll0", "gpll2", "gpll3", "gpll1", "gpll4", "gpll0_early_div" }; static struct clk_fixed_factor xo = { .mult = 1, .div = 1, .hw.init = &(struct clk_init_data){ .name = "xo", .parent_names = (const char *[]){ "xo_board" }, .num_parents = 1, .ops = &clk_fixed_factor_ops, }, }; static struct clk_alpha_pll gpll0_early = { .offset = 0x00000, .regs = clk_alpha_pll_regs[CLK_ALPHA_PLL_TYPE_DEFAULT], .clkr = { .enable_reg = 0x52000, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gpll0_early", .parent_names = (const char *[]){ "xo" }, .num_parents = 1, .ops = &clk_alpha_pll_ops, }, }, }; static struct clk_fixed_factor gpll0_early_div = { .mult = 1, .div = 2, .hw.init = &(struct clk_init_data){ .name = "gpll0_early_div", .parent_names = (const char *[]){ "gpll0_early" }, .num_parents = 1, .ops = &clk_fixed_factor_ops, }, }; static struct clk_alpha_pll_postdiv gpll0 = { .offset = 0x00000, .regs = clk_alpha_pll_regs[CLK_ALPHA_PLL_TYPE_DEFAULT], .clkr.hw.init = &(struct clk_init_data){ .name = "gpll0", .parent_names = (const char *[]){ "gpll0_early" }, .num_parents = 1, .ops = &clk_alpha_pll_postdiv_ops, }, }; static struct clk_branch gcc_mmss_gpll0_div_clk = { .halt_check = BRANCH_HALT_DELAY, .clkr = { .enable_reg = 0x5200c, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_mmss_gpll0_div_clk", .parent_names = (const char *[]){ "gpll0" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_mss_gpll0_div_clk = { .halt_check = BRANCH_HALT_DELAY, .clkr = { .enable_reg = 0x5200c, .enable_mask = BIT(2), .hw.init = &(struct clk_init_data){ .name = "gcc_mss_gpll0_div_clk", .parent_names = (const char *[]){ "gpll0" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops }, }, }; static struct clk_alpha_pll gpll4_early = { .offset = 0x77000, .regs = clk_alpha_pll_regs[CLK_ALPHA_PLL_TYPE_DEFAULT], .clkr = { .enable_reg = 0x52000, .enable_mask = BIT(4), .hw.init = &(struct clk_init_data){ .name = "gpll4_early", .parent_names = (const char *[]){ "xo" }, .num_parents = 1, .ops = &clk_alpha_pll_ops, }, }, }; static struct clk_alpha_pll_postdiv gpll4 = { .offset = 0x77000, .regs = clk_alpha_pll_regs[CLK_ALPHA_PLL_TYPE_DEFAULT], .clkr.hw.init = &(struct clk_init_data){ .name = "gpll4", .parent_names = (const char *[]){ "gpll4_early" }, .num_parents = 1, .ops = &clk_alpha_pll_postdiv_ops, }, }; static const struct freq_tbl ftbl_system_noc_clk_src[] = { F(19200000, P_XO, 1, 0, 0), F(50000000, P_GPLL0_EARLY_DIV, 6, 0, 0), F(100000000, P_GPLL0, 6, 0, 0), F(150000000, P_GPLL0, 4, 0, 0), F(200000000, P_GPLL0, 3, 0, 0), F(240000000, P_GPLL0, 2.5, 0, 0), { } }; static struct clk_rcg2 system_noc_clk_src = { .cmd_rcgr = 0x0401c, .hid_width = 5, .parent_map = gcc_xo_gpll0_gpll2_gpll3_gpll1_gpll2_early_gpll0_early_div_map, .freq_tbl = ftbl_system_noc_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "system_noc_clk_src", .parent_names = gcc_xo_gpll0_gpll2_gpll3_gpll1_gpll2_early_gpll0_early_div, .num_parents = 7, .ops = &clk_rcg2_ops, }, }; static const struct freq_tbl ftbl_config_noc_clk_src[] = { F(19200000, P_XO, 1, 0, 0), F(37500000, P_GPLL0, 16, 0, 0), F(75000000, P_GPLL0, 8, 0, 0), { } }; static struct clk_rcg2 config_noc_clk_src = { .cmd_rcgr = 0x0500c, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_config_noc_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "config_noc_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static const struct freq_tbl ftbl_periph_noc_clk_src[] = { F(19200000, P_XO, 1, 0, 0), F(37500000, P_GPLL0, 16, 0, 0), F(50000000, P_GPLL0, 12, 0, 0), F(75000000, P_GPLL0, 8, 0, 0), F(100000000, P_GPLL0, 6, 0, 0), { } }; static struct clk_rcg2 periph_noc_clk_src = { .cmd_rcgr = 0x06014, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_periph_noc_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "periph_noc_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static const struct freq_tbl ftbl_usb30_master_clk_src[] = { F(19200000, P_XO, 1, 0, 0), F(120000000, P_GPLL0, 5, 0, 0), F(150000000, P_GPLL0, 4, 0, 0), { } }; static struct clk_rcg2 usb30_master_clk_src = { .cmd_rcgr = 0x0f014, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_gpll0_early_div_map, .freq_tbl = ftbl_usb30_master_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "usb30_master_clk_src", .parent_names = gcc_xo_gpll0_gpll0_early_div, .num_parents = 3, .ops = &clk_rcg2_ops, }, }; static const struct freq_tbl ftbl_usb30_mock_utmi_clk_src[] = { F(19200000, P_XO, 1, 0, 0), { } }; static struct clk_rcg2 usb30_mock_utmi_clk_src = { .cmd_rcgr = 0x0f028, .hid_width = 5, .parent_map = gcc_xo_gpll0_gpll0_early_div_map, .freq_tbl = ftbl_usb30_mock_utmi_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "usb30_mock_utmi_clk_src", .parent_names = gcc_xo_gpll0_gpll0_early_div, .num_parents = 3, .ops = &clk_rcg2_ops, }, }; static const struct freq_tbl ftbl_usb3_phy_aux_clk_src[] = { F(1200000, P_XO, 16, 0, 0), { } }; static struct clk_rcg2 usb3_phy_aux_clk_src = { .cmd_rcgr = 0x5000c, .hid_width = 5, .parent_map = gcc_xo_sleep_clk_map, .freq_tbl = ftbl_usb3_phy_aux_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "usb3_phy_aux_clk_src", .parent_names = gcc_xo_sleep_clk, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static const struct freq_tbl ftbl_usb20_master_clk_src[] = { F(120000000, P_GPLL0, 5, 0, 0), { } }; static struct clk_rcg2 usb20_master_clk_src = { .cmd_rcgr = 0x12010, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_gpll0_early_div_map, .freq_tbl = ftbl_usb20_master_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "usb20_master_clk_src", .parent_names = gcc_xo_gpll0_gpll0_early_div, .num_parents = 3, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 usb20_mock_utmi_clk_src = { .cmd_rcgr = 0x12024, .hid_width = 5, .parent_map = gcc_xo_gpll0_gpll0_early_div_map, .freq_tbl = ftbl_usb30_mock_utmi_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "usb20_mock_utmi_clk_src", .parent_names = gcc_xo_gpll0_gpll0_early_div, .num_parents = 3, .ops = &clk_rcg2_ops, }, }; static const struct freq_tbl ftbl_sdcc1_apps_clk_src[] = { F(144000, P_XO, 16, 3, 25), F(400000, P_XO, 12, 1, 4), F(20000000, P_GPLL0, 15, 1, 2), F(25000000, P_GPLL0, 12, 1, 2), F(50000000, P_GPLL0, 12, 0, 0), F(96000000, P_GPLL4, 4, 0, 0), F(192000000, P_GPLL4, 2, 0, 0), F(384000000, P_GPLL4, 1, 0, 0), { } }; static struct clk_rcg2 sdcc1_apps_clk_src = { .cmd_rcgr = 0x13010, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_gpll4_gpll0_early_div_map, .freq_tbl = ftbl_sdcc1_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "sdcc1_apps_clk_src", .parent_names = gcc_xo_gpll0_gpll4_gpll0_early_div, .num_parents = 4, .ops = &clk_rcg2_floor_ops, }, }; static struct freq_tbl ftbl_sdcc1_ice_core_clk_src[] = { F(19200000, P_XO, 1, 0, 0), F(150000000, P_GPLL0, 4, 0, 0), F(300000000, P_GPLL0, 2, 0, 0), { } }; static struct clk_rcg2 sdcc1_ice_core_clk_src = { .cmd_rcgr = 0x13024, .hid_width = 5, .parent_map = gcc_xo_gpll0_gpll4_gpll0_early_div_map, .freq_tbl = ftbl_sdcc1_ice_core_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "sdcc1_ice_core_clk_src", .parent_names = gcc_xo_gpll0_gpll4_gpll0_early_div, .num_parents = 4, .ops = &clk_rcg2_ops, }, }; static const struct freq_tbl ftbl_sdcc2_apps_clk_src[] = { F(144000, P_XO, 16, 3, 25), F(400000, P_XO, 12, 1, 4), F(20000000, P_GPLL0, 15, 1, 2), F(25000000, P_GPLL0, 12, 1, 2), F(50000000, P_GPLL0, 12, 0, 0), F(100000000, P_GPLL0, 6, 0, 0), F(200000000, P_GPLL0, 3, 0, 0), { } }; static struct clk_rcg2 sdcc2_apps_clk_src = { .cmd_rcgr = 0x14010, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_gpll4_map, .freq_tbl = ftbl_sdcc2_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "sdcc2_apps_clk_src", .parent_names = gcc_xo_gpll0_gpll4, .num_parents = 3, .ops = &clk_rcg2_floor_ops, }, }; static struct clk_rcg2 sdcc3_apps_clk_src = { .cmd_rcgr = 0x15010, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_gpll4_map, .freq_tbl = ftbl_sdcc2_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "sdcc3_apps_clk_src", .parent_names = gcc_xo_gpll0_gpll4, .num_parents = 3, .ops = &clk_rcg2_floor_ops, }, }; static const struct freq_tbl ftbl_sdcc4_apps_clk_src[] = { F(144000, P_XO, 16, 3, 25), F(400000, P_XO, 12, 1, 4), F(20000000, P_GPLL0, 15, 1, 2), F(25000000, P_GPLL0, 12, 1, 2), F(50000000, P_GPLL0, 12, 0, 0), F(100000000, P_GPLL0, 6, 0, 0), { } }; static struct clk_rcg2 sdcc4_apps_clk_src = { .cmd_rcgr = 0x16010, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_sdcc4_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "sdcc4_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_floor_ops, }, }; static const struct freq_tbl ftbl_blsp1_qup1_spi_apps_clk_src[] = { F(960000, P_XO, 10, 1, 2), F(4800000, P_XO, 4, 0, 0), F(9600000, P_XO, 2, 0, 0), F(15000000, P_GPLL0, 10, 1, 4), F(19200000, P_XO, 1, 0, 0), F(25000000, P_GPLL0, 12, 1, 2), F(50000000, P_GPLL0, 12, 0, 0), { } }; static struct clk_rcg2 blsp1_qup1_spi_apps_clk_src = { .cmd_rcgr = 0x1900c, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_spi_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp1_qup1_spi_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static const struct freq_tbl ftbl_blsp1_qup1_i2c_apps_clk_src[] = { F(19200000, P_XO, 1, 0, 0), F(50000000, P_GPLL0, 12, 0, 0), { } }; static struct clk_rcg2 blsp1_qup1_i2c_apps_clk_src = { .cmd_rcgr = 0x19020, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_i2c_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp1_qup1_i2c_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static const struct freq_tbl ftbl_blsp1_uart1_apps_clk_src[] = { F(3686400, P_GPLL0, 1, 96, 15625), F(7372800, P_GPLL0, 1, 192, 15625), F(14745600, P_GPLL0, 1, 384, 15625), F(16000000, P_GPLL0, 5, 2, 15), F(19200000, P_XO, 1, 0, 0), F(24000000, P_GPLL0, 5, 1, 5), F(32000000, P_GPLL0, 1, 4, 75), F(40000000, P_GPLL0, 15, 0, 0), F(46400000, P_GPLL0, 1, 29, 375), F(48000000, P_GPLL0, 12.5, 0, 0), F(51200000, P_GPLL0, 1, 32, 375), F(56000000, P_GPLL0, 1, 7, 75), F(58982400, P_GPLL0, 1, 1536, 15625), F(60000000, P_GPLL0, 10, 0, 0), F(63157895, P_GPLL0, 9.5, 0, 0), { } }; static struct clk_rcg2 blsp1_uart1_apps_clk_src = { .cmd_rcgr = 0x1a00c, .mnd_width = 16, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_uart1_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp1_uart1_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp1_qup2_spi_apps_clk_src = { .cmd_rcgr = 0x1b00c, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_spi_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp1_qup2_spi_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp1_qup2_i2c_apps_clk_src = { .cmd_rcgr = 0x1b020, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_i2c_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp1_qup2_i2c_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp1_uart2_apps_clk_src = { .cmd_rcgr = 0x1c00c, .mnd_width = 16, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_uart1_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp1_uart2_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp1_qup3_spi_apps_clk_src = { .cmd_rcgr = 0x1d00c, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_spi_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp1_qup3_spi_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp1_qup3_i2c_apps_clk_src = { .cmd_rcgr = 0x1d020, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_i2c_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp1_qup3_i2c_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp1_uart3_apps_clk_src = { .cmd_rcgr = 0x1e00c, .mnd_width = 16, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_uart1_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp1_uart3_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp1_qup4_spi_apps_clk_src = { .cmd_rcgr = 0x1f00c, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_spi_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp1_qup4_spi_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp1_qup4_i2c_apps_clk_src = { .cmd_rcgr = 0x1f020, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_i2c_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp1_qup4_i2c_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp1_uart4_apps_clk_src = { .cmd_rcgr = 0x2000c, .mnd_width = 16, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_uart1_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp1_uart4_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp1_qup5_spi_apps_clk_src = { .cmd_rcgr = 0x2100c, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_spi_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp1_qup5_spi_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp1_qup5_i2c_apps_clk_src = { .cmd_rcgr = 0x21020, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_i2c_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp1_qup5_i2c_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp1_uart5_apps_clk_src = { .cmd_rcgr = 0x2200c, .mnd_width = 16, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_uart1_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp1_uart5_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp1_qup6_spi_apps_clk_src = { .cmd_rcgr = 0x2300c, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_spi_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp1_qup6_spi_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp1_qup6_i2c_apps_clk_src = { .cmd_rcgr = 0x23020, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_i2c_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp1_qup6_i2c_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp1_uart6_apps_clk_src = { .cmd_rcgr = 0x2400c, .mnd_width = 16, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_uart1_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp1_uart6_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp2_qup1_spi_apps_clk_src = { .cmd_rcgr = 0x2600c, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_spi_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp2_qup1_spi_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp2_qup1_i2c_apps_clk_src = { .cmd_rcgr = 0x26020, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_i2c_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp2_qup1_i2c_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp2_uart1_apps_clk_src = { .cmd_rcgr = 0x2700c, .mnd_width = 16, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_uart1_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp2_uart1_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp2_qup2_spi_apps_clk_src = { .cmd_rcgr = 0x2800c, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_spi_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp2_qup2_spi_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp2_qup2_i2c_apps_clk_src = { .cmd_rcgr = 0x28020, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_i2c_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp2_qup2_i2c_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp2_uart2_apps_clk_src = { .cmd_rcgr = 0x2900c, .mnd_width = 16, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_uart1_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp2_uart2_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp2_qup3_spi_apps_clk_src = { .cmd_rcgr = 0x2a00c, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_spi_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp2_qup3_spi_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp2_qup3_i2c_apps_clk_src = { .cmd_rcgr = 0x2a020, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_i2c_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp2_qup3_i2c_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp2_uart3_apps_clk_src = { .cmd_rcgr = 0x2b00c, .mnd_width = 16, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_uart1_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp2_uart3_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp2_qup4_spi_apps_clk_src = { .cmd_rcgr = 0x2c00c, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_spi_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp2_qup4_spi_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp2_qup4_i2c_apps_clk_src = { .cmd_rcgr = 0x2c020, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_i2c_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp2_qup4_i2c_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp2_uart4_apps_clk_src = { .cmd_rcgr = 0x2d00c, .mnd_width = 16, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_uart1_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp2_uart4_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp2_qup5_spi_apps_clk_src = { .cmd_rcgr = 0x2e00c, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_spi_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp2_qup5_spi_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp2_qup5_i2c_apps_clk_src = { .cmd_rcgr = 0x2e020, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_i2c_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp2_qup5_i2c_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp2_uart5_apps_clk_src = { .cmd_rcgr = 0x2f00c, .mnd_width = 16, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_uart1_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp2_uart5_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp2_qup6_spi_apps_clk_src = { .cmd_rcgr = 0x3000c, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_spi_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp2_qup6_spi_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp2_qup6_i2c_apps_clk_src = { .cmd_rcgr = 0x30020, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_qup1_i2c_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp2_qup6_i2c_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 blsp2_uart6_apps_clk_src = { .cmd_rcgr = 0x3100c, .mnd_width = 16, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_blsp1_uart1_apps_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "blsp2_uart6_apps_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static const struct freq_tbl ftbl_pdm2_clk_src[] = { F(60000000, P_GPLL0, 10, 0, 0), { } }; static struct clk_rcg2 pdm2_clk_src = { .cmd_rcgr = 0x33010, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_pdm2_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "pdm2_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static const struct freq_tbl ftbl_tsif_ref_clk_src[] = { F(105495, P_XO, 1, 1, 182), { } }; static struct clk_rcg2 tsif_ref_clk_src = { .cmd_rcgr = 0x36010, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_aud_ref_clk_map, .freq_tbl = ftbl_tsif_ref_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "tsif_ref_clk_src", .parent_names = gcc_xo_gpll0_aud_ref_clk, .num_parents = 3, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 gcc_sleep_clk_src = { .cmd_rcgr = 0x43014, .hid_width = 5, .parent_map = gcc_sleep_clk_map, .clkr.hw.init = &(struct clk_init_data){ .name = "gcc_sleep_clk_src", .parent_names = gcc_sleep_clk, .num_parents = 1, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 hmss_rbcpr_clk_src = { .cmd_rcgr = 0x48040, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_usb30_mock_utmi_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "hmss_rbcpr_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 hmss_gpll0_clk_src = { .cmd_rcgr = 0x48058, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .clkr.hw.init = &(struct clk_init_data){ .name = "hmss_gpll0_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static const struct freq_tbl ftbl_gp1_clk_src[] = { F(19200000, P_XO, 1, 0, 0), F(100000000, P_GPLL0, 6, 0, 0), F(200000000, P_GPLL0, 3, 0, 0), { } }; static struct clk_rcg2 gp1_clk_src = { .cmd_rcgr = 0x64004, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_sleep_clk_gpll0_early_div_map, .freq_tbl = ftbl_gp1_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "gp1_clk_src", .parent_names = gcc_xo_gpll0_sleep_clk_gpll0_early_div, .num_parents = 4, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 gp2_clk_src = { .cmd_rcgr = 0x65004, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_sleep_clk_gpll0_early_div_map, .freq_tbl = ftbl_gp1_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "gp2_clk_src", .parent_names = gcc_xo_gpll0_sleep_clk_gpll0_early_div, .num_parents = 4, .ops = &clk_rcg2_ops, }, }; static struct clk_rcg2 gp3_clk_src = { .cmd_rcgr = 0x66004, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_sleep_clk_gpll0_early_div_map, .freq_tbl = ftbl_gp1_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "gp3_clk_src", .parent_names = gcc_xo_gpll0_sleep_clk_gpll0_early_div, .num_parents = 4, .ops = &clk_rcg2_ops, }, }; static const struct freq_tbl ftbl_pcie_aux_clk_src[] = { F(1010526, P_XO, 1, 1, 19), { } }; static struct clk_rcg2 pcie_aux_clk_src = { .cmd_rcgr = 0x6c000, .mnd_width = 16, .hid_width = 5, .parent_map = gcc_xo_sleep_clk_map, .freq_tbl = ftbl_pcie_aux_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "pcie_aux_clk_src", .parent_names = gcc_xo_sleep_clk, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static const struct freq_tbl ftbl_ufs_axi_clk_src[] = { F(100000000, P_GPLL0, 6, 0, 0), F(200000000, P_GPLL0, 3, 0, 0), F(240000000, P_GPLL0, 2.5, 0, 0), { } }; static struct clk_rcg2 ufs_axi_clk_src = { .cmd_rcgr = 0x75024, .mnd_width = 8, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_ufs_axi_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "ufs_axi_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static const struct freq_tbl ftbl_ufs_ice_core_clk_src[] = { F(19200000, P_XO, 1, 0, 0), F(150000000, P_GPLL0, 4, 0, 0), F(300000000, P_GPLL0, 2, 0, 0), { } }; static struct clk_rcg2 ufs_ice_core_clk_src = { .cmd_rcgr = 0x76014, .hid_width = 5, .parent_map = gcc_xo_gpll0_map, .freq_tbl = ftbl_ufs_ice_core_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "ufs_ice_core_clk_src", .parent_names = gcc_xo_gpll0, .num_parents = 2, .ops = &clk_rcg2_ops, }, }; static const struct freq_tbl ftbl_qspi_ser_clk_src[] = { F(75000000, P_GPLL0, 8, 0, 0), F(150000000, P_GPLL0, 4, 0, 0), F(256000000, P_GPLL4, 1.5, 0, 0), F(300000000, P_GPLL0, 2, 0, 0), { } }; static struct clk_rcg2 qspi_ser_clk_src = { .cmd_rcgr = 0x8b00c, .hid_width = 5, .parent_map = gcc_xo_gpll0_gpll1_early_div_gpll1_gpll4_gpll0_early_div_map, .freq_tbl = ftbl_qspi_ser_clk_src, .clkr.hw.init = &(struct clk_init_data){ .name = "qspi_ser_clk_src", .parent_names = gcc_xo_gpll0_gpll1_early_div_gpll1_gpll4_gpll0_early_div, .num_parents = 6, .ops = &clk_rcg2_ops, }, }; static struct clk_branch gcc_sys_noc_usb3_axi_clk = { .halt_reg = 0x0f03c, .clkr = { .enable_reg = 0x0f03c, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_sys_noc_usb3_axi_clk", .parent_names = (const char *[]){ "usb30_master_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_sys_noc_ufs_axi_clk = { .halt_reg = 0x75038, .clkr = { .enable_reg = 0x75038, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_sys_noc_ufs_axi_clk", .parent_names = (const char *[]){ "ufs_axi_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_periph_noc_usb20_ahb_clk = { .halt_reg = 0x6010, .clkr = { .enable_reg = 0x6010, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_periph_noc_usb20_ahb_clk", .parent_names = (const char *[]){ "usb20_master_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_mmss_noc_cfg_ahb_clk = { .halt_reg = 0x9008, .clkr = { .enable_reg = 0x9008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_mmss_noc_cfg_ahb_clk", .parent_names = (const char *[]){ "config_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT | CLK_IGNORE_UNUSED, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_mmss_bimc_gfx_clk = { .halt_reg = 0x9010, .clkr = { .enable_reg = 0x9010, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_mmss_bimc_gfx_clk", .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_usb30_master_clk = { .halt_reg = 0x0f008, .clkr = { .enable_reg = 0x0f008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_usb30_master_clk", .parent_names = (const char *[]){ "usb30_master_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_usb30_sleep_clk = { .halt_reg = 0x0f00c, .clkr = { .enable_reg = 0x0f00c, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_usb30_sleep_clk", .parent_names = (const char *[]){ "gcc_sleep_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_usb30_mock_utmi_clk = { .halt_reg = 0x0f010, .clkr = { .enable_reg = 0x0f010, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_usb30_mock_utmi_clk", .parent_names = (const char *[]){ "usb30_mock_utmi_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_usb3_phy_aux_clk = { .halt_reg = 0x50000, .clkr = { .enable_reg = 0x50000, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_usb3_phy_aux_clk", .parent_names = (const char *[]){ "usb3_phy_aux_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_usb3_phy_pipe_clk = { .halt_reg = 0x50004, .halt_check = BRANCH_HALT_SKIP, .clkr = { .enable_reg = 0x50004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_usb3_phy_pipe_clk", .parent_names = (const char *[]){ "usb3_phy_pipe_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_usb20_master_clk = { .halt_reg = 0x12004, .clkr = { .enable_reg = 0x12004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_usb20_master_clk", .parent_names = (const char *[]){ "usb20_master_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_usb20_sleep_clk = { .halt_reg = 0x12008, .clkr = { .enable_reg = 0x12008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_usb20_sleep_clk", .parent_names = (const char *[]){ "gcc_sleep_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_usb20_mock_utmi_clk = { .halt_reg = 0x1200c, .clkr = { .enable_reg = 0x1200c, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_usb20_mock_utmi_clk", .parent_names = (const char *[]){ "usb20_mock_utmi_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_usb_phy_cfg_ahb2phy_clk = { .halt_reg = 0x6a004, .clkr = { .enable_reg = 0x6a004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_usb_phy_cfg_ahb2phy_clk", .parent_names = (const char *[]){ "periph_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_sdcc1_apps_clk = { .halt_reg = 0x13004, .clkr = { .enable_reg = 0x13004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_sdcc1_apps_clk", .parent_names = (const char *[]){ "sdcc1_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_sdcc1_ahb_clk = { .halt_reg = 0x13008, .clkr = { .enable_reg = 0x13008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_sdcc1_ahb_clk", .parent_names = (const char *[]){ "periph_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_sdcc1_ice_core_clk = { .halt_reg = 0x13038, .clkr = { .enable_reg = 0x13038, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_sdcc1_ice_core_clk", .parent_names = (const char *[]){ "sdcc1_ice_core_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_sdcc2_apps_clk = { .halt_reg = 0x14004, .clkr = { .enable_reg = 0x14004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_sdcc2_apps_clk", .parent_names = (const char *[]){ "sdcc2_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_sdcc2_ahb_clk = { .halt_reg = 0x14008, .clkr = { .enable_reg = 0x14008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_sdcc2_ahb_clk", .parent_names = (const char *[]){ "periph_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_sdcc3_apps_clk = { .halt_reg = 0x15004, .clkr = { .enable_reg = 0x15004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_sdcc3_apps_clk", .parent_names = (const char *[]){ "sdcc3_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_sdcc3_ahb_clk = { .halt_reg = 0x15008, .clkr = { .enable_reg = 0x15008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_sdcc3_ahb_clk", .parent_names = (const char *[]){ "periph_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_sdcc4_apps_clk = { .halt_reg = 0x16004, .clkr = { .enable_reg = 0x16004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_sdcc4_apps_clk", .parent_names = (const char *[]){ "sdcc4_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_sdcc4_ahb_clk = { .halt_reg = 0x16008, .clkr = { .enable_reg = 0x16008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_sdcc4_ahb_clk", .parent_names = (const char *[]){ "periph_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp1_ahb_clk = { .halt_reg = 0x17004, .halt_check = BRANCH_HALT_VOTED, .clkr = { .enable_reg = 0x52004, .enable_mask = BIT(17), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp1_ahb_clk", .parent_names = (const char *[]){ "periph_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp1_sleep_clk = { .halt_reg = 0x17008, .halt_check = BRANCH_HALT_VOTED, .clkr = { .enable_reg = 0x52004, .enable_mask = BIT(16), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp1_sleep_clk", .parent_names = (const char *[]){ "gcc_sleep_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp1_qup1_spi_apps_clk = { .halt_reg = 0x19004, .clkr = { .enable_reg = 0x19004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp1_qup1_spi_apps_clk", .parent_names = (const char *[]){ "blsp1_qup1_spi_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp1_qup1_i2c_apps_clk = { .halt_reg = 0x19008, .clkr = { .enable_reg = 0x19008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp1_qup1_i2c_apps_clk", .parent_names = (const char *[]){ "blsp1_qup1_i2c_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp1_uart1_apps_clk = { .halt_reg = 0x1a004, .clkr = { .enable_reg = 0x1a004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp1_uart1_apps_clk", .parent_names = (const char *[]){ "blsp1_uart1_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp1_qup2_spi_apps_clk = { .halt_reg = 0x1b004, .clkr = { .enable_reg = 0x1b004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp1_qup2_spi_apps_clk", .parent_names = (const char *[]){ "blsp1_qup2_spi_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp1_qup2_i2c_apps_clk = { .halt_reg = 0x1b008, .clkr = { .enable_reg = 0x1b008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp1_qup2_i2c_apps_clk", .parent_names = (const char *[]){ "blsp1_qup2_i2c_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp1_uart2_apps_clk = { .halt_reg = 0x1c004, .clkr = { .enable_reg = 0x1c004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp1_uart2_apps_clk", .parent_names = (const char *[]){ "blsp1_uart2_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp1_qup3_spi_apps_clk = { .halt_reg = 0x1d004, .clkr = { .enable_reg = 0x1d004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp1_qup3_spi_apps_clk", .parent_names = (const char *[]){ "blsp1_qup3_spi_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp1_qup3_i2c_apps_clk = { .halt_reg = 0x1d008, .clkr = { .enable_reg = 0x1d008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp1_qup3_i2c_apps_clk", .parent_names = (const char *[]){ "blsp1_qup3_i2c_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp1_uart3_apps_clk = { .halt_reg = 0x1e004, .clkr = { .enable_reg = 0x1e004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp1_uart3_apps_clk", .parent_names = (const char *[]){ "blsp1_uart3_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp1_qup4_spi_apps_clk = { .halt_reg = 0x1f004, .clkr = { .enable_reg = 0x1f004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp1_qup4_spi_apps_clk", .parent_names = (const char *[]){ "blsp1_qup4_spi_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp1_qup4_i2c_apps_clk = { .halt_reg = 0x1f008, .clkr = { .enable_reg = 0x1f008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp1_qup4_i2c_apps_clk", .parent_names = (const char *[]){ "blsp1_qup4_i2c_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp1_uart4_apps_clk = { .halt_reg = 0x20004, .clkr = { .enable_reg = 0x20004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp1_uart4_apps_clk", .parent_names = (const char *[]){ "blsp1_uart4_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp1_qup5_spi_apps_clk = { .halt_reg = 0x21004, .clkr = { .enable_reg = 0x21004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp1_qup5_spi_apps_clk", .parent_names = (const char *[]){ "blsp1_qup5_spi_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp1_qup5_i2c_apps_clk = { .halt_reg = 0x21008, .clkr = { .enable_reg = 0x21008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp1_qup5_i2c_apps_clk", .parent_names = (const char *[]){ "blsp1_qup5_i2c_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp1_uart5_apps_clk = { .halt_reg = 0x22004, .clkr = { .enable_reg = 0x22004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp1_uart5_apps_clk", .parent_names = (const char *[]){ "blsp1_uart5_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp1_qup6_spi_apps_clk = { .halt_reg = 0x23004, .clkr = { .enable_reg = 0x23004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp1_qup6_spi_apps_clk", .parent_names = (const char *[]){ "blsp1_qup6_spi_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp1_qup6_i2c_apps_clk = { .halt_reg = 0x23008, .clkr = { .enable_reg = 0x23008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp1_qup6_i2c_apps_clk", .parent_names = (const char *[]){ "blsp1_qup6_i2c_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp1_uart6_apps_clk = { .halt_reg = 0x24004, .clkr = { .enable_reg = 0x24004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp1_uart6_apps_clk", .parent_names = (const char *[]){ "blsp1_uart6_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp2_ahb_clk = { .halt_reg = 0x25004, .halt_check = BRANCH_HALT_VOTED, .clkr = { .enable_reg = 0x52004, .enable_mask = BIT(15), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp2_ahb_clk", .parent_names = (const char *[]){ "periph_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp2_sleep_clk = { .halt_reg = 0x25008, .halt_check = BRANCH_HALT_VOTED, .clkr = { .enable_reg = 0x52004, .enable_mask = BIT(14), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp2_sleep_clk", .parent_names = (const char *[]){ "gcc_sleep_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp2_qup1_spi_apps_clk = { .halt_reg = 0x26004, .clkr = { .enable_reg = 0x26004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp2_qup1_spi_apps_clk", .parent_names = (const char *[]){ "blsp2_qup1_spi_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp2_qup1_i2c_apps_clk = { .halt_reg = 0x26008, .clkr = { .enable_reg = 0x26008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp2_qup1_i2c_apps_clk", .parent_names = (const char *[]){ "blsp2_qup1_i2c_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp2_uart1_apps_clk = { .halt_reg = 0x27004, .clkr = { .enable_reg = 0x27004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp2_uart1_apps_clk", .parent_names = (const char *[]){ "blsp2_uart1_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp2_qup2_spi_apps_clk = { .halt_reg = 0x28004, .clkr = { .enable_reg = 0x28004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp2_qup2_spi_apps_clk", .parent_names = (const char *[]){ "blsp2_qup2_spi_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp2_qup2_i2c_apps_clk = { .halt_reg = 0x28008, .clkr = { .enable_reg = 0x28008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp2_qup2_i2c_apps_clk", .parent_names = (const char *[]){ "blsp2_qup2_i2c_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp2_uart2_apps_clk = { .halt_reg = 0x29004, .clkr = { .enable_reg = 0x29004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp2_uart2_apps_clk", .parent_names = (const char *[]){ "blsp2_uart2_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp2_qup3_spi_apps_clk = { .halt_reg = 0x2a004, .clkr = { .enable_reg = 0x2a004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp2_qup3_spi_apps_clk", .parent_names = (const char *[]){ "blsp2_qup3_spi_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp2_qup3_i2c_apps_clk = { .halt_reg = 0x2a008, .clkr = { .enable_reg = 0x2a008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp2_qup3_i2c_apps_clk", .parent_names = (const char *[]){ "blsp2_qup3_i2c_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp2_uart3_apps_clk = { .halt_reg = 0x2b004, .clkr = { .enable_reg = 0x2b004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp2_uart3_apps_clk", .parent_names = (const char *[]){ "blsp2_uart3_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp2_qup4_spi_apps_clk = { .halt_reg = 0x2c004, .clkr = { .enable_reg = 0x2c004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp2_qup4_spi_apps_clk", .parent_names = (const char *[]){ "blsp2_qup4_spi_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp2_qup4_i2c_apps_clk = { .halt_reg = 0x2c008, .clkr = { .enable_reg = 0x2c008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp2_qup4_i2c_apps_clk", .parent_names = (const char *[]){ "blsp2_qup4_i2c_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp2_uart4_apps_clk = { .halt_reg = 0x2d004, .clkr = { .enable_reg = 0x2d004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp2_uart4_apps_clk", .parent_names = (const char *[]){ "blsp2_uart4_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp2_qup5_spi_apps_clk = { .halt_reg = 0x2e004, .clkr = { .enable_reg = 0x2e004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp2_qup5_spi_apps_clk", .parent_names = (const char *[]){ "blsp2_qup5_spi_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp2_qup5_i2c_apps_clk = { .halt_reg = 0x2e008, .clkr = { .enable_reg = 0x2e008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp2_qup5_i2c_apps_clk", .parent_names = (const char *[]){ "blsp2_qup5_i2c_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp2_uart5_apps_clk = { .halt_reg = 0x2f004, .clkr = { .enable_reg = 0x2f004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp2_uart5_apps_clk", .parent_names = (const char *[]){ "blsp2_uart5_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp2_qup6_spi_apps_clk = { .halt_reg = 0x30004, .clkr = { .enable_reg = 0x30004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp2_qup6_spi_apps_clk", .parent_names = (const char *[]){ "blsp2_qup6_spi_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp2_qup6_i2c_apps_clk = { .halt_reg = 0x30008, .clkr = { .enable_reg = 0x30008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp2_qup6_i2c_apps_clk", .parent_names = (const char *[]){ "blsp2_qup6_i2c_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_blsp2_uart6_apps_clk = { .halt_reg = 0x31004, .clkr = { .enable_reg = 0x31004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_blsp2_uart6_apps_clk", .parent_names = (const char *[]){ "blsp2_uart6_apps_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_pdm_ahb_clk = { .halt_reg = 0x33004, .clkr = { .enable_reg = 0x33004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_pdm_ahb_clk", .parent_names = (const char *[]){ "periph_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_pdm2_clk = { .halt_reg = 0x3300c, .clkr = { .enable_reg = 0x3300c, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_pdm2_clk", .parent_names = (const char *[]){ "pdm2_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_prng_ahb_clk = { .halt_reg = 0x34004, .halt_check = BRANCH_HALT_VOTED, .clkr = { .enable_reg = 0x52004, .enable_mask = BIT(13), .hw.init = &(struct clk_init_data){ .name = "gcc_prng_ahb_clk", .parent_names = (const char *[]){ "config_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_tsif_ahb_clk = { .halt_reg = 0x36004, .clkr = { .enable_reg = 0x36004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_tsif_ahb_clk", .parent_names = (const char *[]){ "periph_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_tsif_ref_clk = { .halt_reg = 0x36008, .clkr = { .enable_reg = 0x36008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_tsif_ref_clk", .parent_names = (const char *[]){ "tsif_ref_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_tsif_inactivity_timers_clk = { .halt_reg = 0x3600c, .clkr = { .enable_reg = 0x3600c, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_tsif_inactivity_timers_clk", .parent_names = (const char *[]){ "gcc_sleep_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_boot_rom_ahb_clk = { .halt_reg = 0x38004, .halt_check = BRANCH_HALT_VOTED, .clkr = { .enable_reg = 0x52004, .enable_mask = BIT(10), .hw.init = &(struct clk_init_data){ .name = "gcc_boot_rom_ahb_clk", .parent_names = (const char *[]){ "config_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_bimc_gfx_clk = { .halt_reg = 0x46018, .clkr = { .enable_reg = 0x46018, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_bimc_gfx_clk", .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_hmss_rbcpr_clk = { .halt_reg = 0x4800c, .clkr = { .enable_reg = 0x4800c, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_hmss_rbcpr_clk", .parent_names = (const char *[]){ "hmss_rbcpr_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_gp1_clk = { .halt_reg = 0x64000, .clkr = { .enable_reg = 0x64000, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_gp1_clk", .parent_names = (const char *[]){ "gp1_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_gp2_clk = { .halt_reg = 0x65000, .clkr = { .enable_reg = 0x65000, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_gp2_clk", .parent_names = (const char *[]){ "gp2_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_gp3_clk = { .halt_reg = 0x66000, .clkr = { .enable_reg = 0x66000, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_gp3_clk", .parent_names = (const char *[]){ "gp3_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_pcie_0_slv_axi_clk = { .halt_reg = 0x6b008, .clkr = { .enable_reg = 0x6b008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_pcie_0_slv_axi_clk", .parent_names = (const char *[]){ "system_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_pcie_0_mstr_axi_clk = { .halt_reg = 0x6b00c, .clkr = { .enable_reg = 0x6b00c, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_pcie_0_mstr_axi_clk", .parent_names = (const char *[]){ "system_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_pcie_0_cfg_ahb_clk = { .halt_reg = 0x6b010, .clkr = { .enable_reg = 0x6b010, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_pcie_0_cfg_ahb_clk", .parent_names = (const char *[]){ "config_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_pcie_0_aux_clk = { .halt_reg = 0x6b014, .clkr = { .enable_reg = 0x6b014, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_pcie_0_aux_clk", .parent_names = (const char *[]){ "pcie_aux_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_pcie_0_pipe_clk = { .halt_reg = 0x6b018, .halt_check = BRANCH_HALT_SKIP, .clkr = { .enable_reg = 0x6b018, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_pcie_0_pipe_clk", .parent_names = (const char *[]){ "pcie_0_pipe_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_pcie_1_slv_axi_clk = { .halt_reg = 0x6d008, .clkr = { .enable_reg = 0x6d008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_pcie_1_slv_axi_clk", .parent_names = (const char *[]){ "system_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_pcie_1_mstr_axi_clk = { .halt_reg = 0x6d00c, .clkr = { .enable_reg = 0x6d00c, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_pcie_1_mstr_axi_clk", .parent_names = (const char *[]){ "system_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_pcie_1_cfg_ahb_clk = { .halt_reg = 0x6d010, .clkr = { .enable_reg = 0x6d010, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_pcie_1_cfg_ahb_clk", .parent_names = (const char *[]){ "config_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_pcie_1_aux_clk = { .halt_reg = 0x6d014, .clkr = { .enable_reg = 0x6d014, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_pcie_1_aux_clk", .parent_names = (const char *[]){ "pcie_aux_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_pcie_1_pipe_clk = { .halt_reg = 0x6d018, .halt_check = BRANCH_HALT_SKIP, .clkr = { .enable_reg = 0x6d018, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_pcie_1_pipe_clk", .parent_names = (const char *[]){ "pcie_1_pipe_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_pcie_2_slv_axi_clk = { .halt_reg = 0x6e008, .clkr = { .enable_reg = 0x6e008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_pcie_2_slv_axi_clk", .parent_names = (const char *[]){ "system_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_pcie_2_mstr_axi_clk = { .halt_reg = 0x6e00c, .clkr = { .enable_reg = 0x6e00c, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_pcie_2_mstr_axi_clk", .parent_names = (const char *[]){ "system_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_pcie_2_cfg_ahb_clk = { .halt_reg = 0x6e010, .clkr = { .enable_reg = 0x6e010, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_pcie_2_cfg_ahb_clk", .parent_names = (const char *[]){ "config_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_pcie_2_aux_clk = { .halt_reg = 0x6e014, .clkr = { .enable_reg = 0x6e014, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_pcie_2_aux_clk", .parent_names = (const char *[]){ "pcie_aux_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_pcie_2_pipe_clk = { .halt_reg = 0x6e018, .halt_check = BRANCH_HALT_SKIP, .clkr = { .enable_reg = 0x6e018, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_pcie_2_pipe_clk", .parent_names = (const char *[]){ "pcie_2_pipe_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_pcie_phy_cfg_ahb_clk = { .halt_reg = 0x6f004, .clkr = { .enable_reg = 0x6f004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_pcie_phy_cfg_ahb_clk", .parent_names = (const char *[]){ "config_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_pcie_phy_aux_clk = { .halt_reg = 0x6f008, .clkr = { .enable_reg = 0x6f008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_pcie_phy_aux_clk", .parent_names = (const char *[]){ "pcie_aux_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_ufs_axi_clk = { .halt_reg = 0x75008, .clkr = { .enable_reg = 0x75008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_ufs_axi_clk", .parent_names = (const char *[]){ "ufs_axi_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_ufs_ahb_clk = { .halt_reg = 0x7500c, .clkr = { .enable_reg = 0x7500c, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_ufs_ahb_clk", .parent_names = (const char *[]){ "config_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_fixed_factor ufs_tx_cfg_clk_src = { .mult = 1, .div = 16, .hw.init = &(struct clk_init_data){ .name = "ufs_tx_cfg_clk_src", .parent_names = (const char *[]){ "ufs_axi_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_fixed_factor_ops, }, }; static struct clk_branch gcc_ufs_tx_cfg_clk = { .halt_reg = 0x75010, .clkr = { .enable_reg = 0x75010, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_ufs_tx_cfg_clk", .parent_names = (const char *[]){ "ufs_tx_cfg_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_fixed_factor ufs_rx_cfg_clk_src = { .mult = 1, .div = 16, .hw.init = &(struct clk_init_data){ .name = "ufs_rx_cfg_clk_src", .parent_names = (const char *[]){ "ufs_axi_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_fixed_factor_ops, }, }; static struct clk_branch gcc_hlos1_vote_lpass_core_smmu_clk = { .halt_reg = 0x7d010, .halt_check = BRANCH_HALT_VOTED, .clkr = { .enable_reg = 0x7d010, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "hlos1_vote_lpass_core_smmu_clk", .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_hlos1_vote_lpass_adsp_smmu_clk = { .halt_reg = 0x7d014, .halt_check = BRANCH_HALT_VOTED, .clkr = { .enable_reg = 0x7d014, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "hlos1_vote_lpass_adsp_smmu_clk", .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_ufs_rx_cfg_clk = { .halt_reg = 0x75014, .clkr = { .enable_reg = 0x75014, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_ufs_rx_cfg_clk", .parent_names = (const char *[]){ "ufs_rx_cfg_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_ufs_tx_symbol_0_clk = { .halt_reg = 0x75018, .halt_check = BRANCH_HALT_SKIP, .clkr = { .enable_reg = 0x75018, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_ufs_tx_symbol_0_clk", .parent_names = (const char *[]){ "ufs_tx_symbol_0_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_ufs_rx_symbol_0_clk = { .halt_reg = 0x7501c, .halt_check = BRANCH_HALT_SKIP, .clkr = { .enable_reg = 0x7501c, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_ufs_rx_symbol_0_clk", .parent_names = (const char *[]){ "ufs_rx_symbol_0_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_ufs_rx_symbol_1_clk = { .halt_reg = 0x75020, .halt_check = BRANCH_HALT_SKIP, .clkr = { .enable_reg = 0x75020, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_ufs_rx_symbol_1_clk", .parent_names = (const char *[]){ "ufs_rx_symbol_1_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_fixed_factor ufs_ice_core_postdiv_clk_src = { .mult = 1, .div = 2, .hw.init = &(struct clk_init_data){ .name = "ufs_ice_core_postdiv_clk_src", .parent_names = (const char *[]){ "ufs_ice_core_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_fixed_factor_ops, }, }; static struct clk_branch gcc_ufs_unipro_core_clk = { .halt_reg = 0x7600c, .clkr = { .enable_reg = 0x7600c, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_ufs_unipro_core_clk", .parent_names = (const char *[]){ "ufs_ice_core_postdiv_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_ufs_ice_core_clk = { .halt_reg = 0x76010, .clkr = { .enable_reg = 0x76010, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_ufs_ice_core_clk", .parent_names = (const char *[]){ "ufs_ice_core_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_ufs_sys_clk_core_clk = { .halt_check = BRANCH_HALT_DELAY, .clkr = { .enable_reg = 0x76030, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_ufs_sys_clk_core_clk", .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_ufs_tx_symbol_clk_core_clk = { .halt_check = BRANCH_HALT_DELAY, .clkr = { .enable_reg = 0x76034, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_ufs_tx_symbol_clk_core_clk", .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_aggre0_snoc_axi_clk = { .halt_reg = 0x81008, .clkr = { .enable_reg = 0x81008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_aggre0_snoc_axi_clk", .parent_names = (const char *[]){ "system_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT | CLK_IS_CRITICAL, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_aggre0_cnoc_ahb_clk = { .halt_reg = 0x8100c, .clkr = { .enable_reg = 0x8100c, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_aggre0_cnoc_ahb_clk", .parent_names = (const char *[]){ "config_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT | CLK_IS_CRITICAL, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_smmu_aggre0_axi_clk = { .halt_reg = 0x81014, .clkr = { .enable_reg = 0x81014, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_smmu_aggre0_axi_clk", .parent_names = (const char *[]){ "system_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT | CLK_IS_CRITICAL, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_smmu_aggre0_ahb_clk = { .halt_reg = 0x81018, .clkr = { .enable_reg = 0x81018, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_smmu_aggre0_ahb_clk", .parent_names = (const char *[]){ "config_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT | CLK_IS_CRITICAL, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_aggre1_pnoc_ahb_clk = { .halt_reg = 0x82014, .clkr = { .enable_reg = 0x82014, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_aggre1_pnoc_ahb_clk", .parent_names = (const char *[]){ "periph_noc_clk_src" }, .num_parents = 1, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_aggre2_ufs_axi_clk = { .halt_reg = 0x83014, .clkr = { .enable_reg = 0x83014, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_aggre2_ufs_axi_clk", .parent_names = (const char *[]){ "ufs_axi_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_aggre2_usb3_axi_clk = { .halt_reg = 0x83018, .clkr = { .enable_reg = 0x83018, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_aggre2_usb3_axi_clk", .parent_names = (const char *[]){ "usb30_master_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_dcc_ahb_clk = { .halt_reg = 0x84004, .clkr = { .enable_reg = 0x84004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_dcc_ahb_clk", .parent_names = (const char *[]){ "config_noc_clk_src" }, .num_parents = 1, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_aggre0_noc_mpu_cfg_ahb_clk = { .halt_reg = 0x85000, .clkr = { .enable_reg = 0x85000, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_aggre0_noc_mpu_cfg_ahb_clk", .parent_names = (const char *[]){ "config_noc_clk_src" }, .num_parents = 1, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_qspi_ahb_clk = { .halt_reg = 0x8b004, .clkr = { .enable_reg = 0x8b004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_qspi_ahb_clk", .parent_names = (const char *[]){ "periph_noc_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_qspi_ser_clk = { .halt_reg = 0x8b008, .clkr = { .enable_reg = 0x8b008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_qspi_ser_clk", .parent_names = (const char *[]){ "qspi_ser_clk_src" }, .num_parents = 1, .flags = CLK_SET_RATE_PARENT, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_usb3_clkref_clk = { .halt_reg = 0x8800C, .clkr = { .enable_reg = 0x8800C, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_usb3_clkref_clk", .parent_names = (const char *[]){ "xo" }, .num_parents = 1, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_hdmi_clkref_clk = { .halt_reg = 0x88000, .clkr = { .enable_reg = 0x88000, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_hdmi_clkref_clk", .parent_names = (const char *[]){ "xo" }, .num_parents = 1, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_edp_clkref_clk = { .halt_reg = 0x88004, .clkr = { .enable_reg = 0x88004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_edp_clkref_clk", .parent_names = (const char *[]){ "xo" }, .num_parents = 1, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_ufs_clkref_clk = { .halt_reg = 0x88008, .clkr = { .enable_reg = 0x88008, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_ufs_clkref_clk", .parent_names = (const char *[]){ "xo" }, .num_parents = 1, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_pcie_clkref_clk = { .halt_reg = 0x88010, .clkr = { .enable_reg = 0x88010, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_pcie_clkref_clk", .parent_names = (const char *[]){ "xo" }, .num_parents = 1, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_rx2_usb2_clkref_clk = { .halt_reg = 0x88014, .clkr = { .enable_reg = 0x88014, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_rx2_usb2_clkref_clk", .parent_names = (const char *[]){ "xo" }, .num_parents = 1, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_rx1_usb2_clkref_clk = { .halt_reg = 0x88018, .clkr = { .enable_reg = 0x88018, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_rx1_usb2_clkref_clk", .parent_names = (const char *[]){ "xo" }, .num_parents = 1, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_mss_cfg_ahb_clk = { .halt_reg = 0x8a000, .clkr = { .enable_reg = 0x8a000, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_mss_cfg_ahb_clk", .parent_names = (const char *[]){ "config_noc_clk_src" }, .num_parents = 1, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_mss_mnoc_bimc_axi_clk = { .halt_reg = 0x8a004, .clkr = { .enable_reg = 0x8a004, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_mss_mnoc_bimc_axi_clk", .parent_names = (const char *[]){ "system_noc_clk_src" }, .num_parents = 1, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_mss_snoc_axi_clk = { .halt_reg = 0x8a024, .clkr = { .enable_reg = 0x8a024, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_mss_snoc_axi_clk", .parent_names = (const char *[]){ "system_noc_clk_src" }, .num_parents = 1, .ops = &clk_branch2_ops, }, }, }; static struct clk_branch gcc_mss_q6_bimc_axi_clk = { .halt_reg = 0x8a028, .clkr = { .enable_reg = 0x8a028, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "gcc_mss_q6_bimc_axi_clk", .parent_names = (const char *[]){ "system_noc_clk_src" }, .num_parents = 1, .ops = &clk_branch2_ops, }, }, }; static struct clk_hw *gcc_msm8996_hws[] = { &xo.hw, &gpll0_early_div.hw, &ufs_tx_cfg_clk_src.hw, &ufs_rx_cfg_clk_src.hw, &ufs_ice_core_postdiv_clk_src.hw, }; static struct gdsc aggre0_noc_gdsc = { .gdscr = 0x81004, .gds_hw_ctrl = 0x81028, .pd = { .name = "aggre0_noc", }, .pwrsts = PWRSTS_OFF_ON, .flags = VOTABLE | ALWAYS_ON, }; static struct gdsc hlos1_vote_aggre0_noc_gdsc = { .gdscr = 0x7d024, .pd = { .name = "hlos1_vote_aggre0_noc", }, .pwrsts = PWRSTS_OFF_ON, .flags = VOTABLE, }; static struct gdsc hlos1_vote_lpass_adsp_gdsc = { .gdscr = 0x7d034, .pd = { .name = "hlos1_vote_lpass_adsp", }, .pwrsts = PWRSTS_OFF_ON, .flags = VOTABLE, }; static struct gdsc hlos1_vote_lpass_core_gdsc = { .gdscr = 0x7d038, .pd = { .name = "hlos1_vote_lpass_core", }, .pwrsts = PWRSTS_OFF_ON, .flags = VOTABLE, }; static struct gdsc usb30_gdsc = { .gdscr = 0xf004, .pd = { .name = "usb30", }, .pwrsts = PWRSTS_OFF_ON, }; static struct gdsc pcie0_gdsc = { .gdscr = 0x6b004, .pd = { .name = "pcie0", }, .pwrsts = PWRSTS_OFF_ON, }; static struct gdsc pcie1_gdsc = { .gdscr = 0x6d004, .pd = { .name = "pcie1", }, .pwrsts = PWRSTS_OFF_ON, }; static struct gdsc pcie2_gdsc = { .gdscr = 0x6e004, .pd = { .name = "pcie2", }, .pwrsts = PWRSTS_OFF_ON, }; static struct gdsc ufs_gdsc = { .gdscr = 0x75004, .pd = { .name = "ufs", }, .pwrsts = PWRSTS_OFF_ON, }; static struct clk_regmap *gcc_msm8996_clocks[] = { [GPLL0_EARLY] = &gpll0_early.clkr, [GPLL0] = &gpll0.clkr, [GPLL4_EARLY] = &gpll4_early.clkr, [GPLL4] = &gpll4.clkr, [SYSTEM_NOC_CLK_SRC] = &system_noc_clk_src.clkr, [CONFIG_NOC_CLK_SRC] = &config_noc_clk_src.clkr, [PERIPH_NOC_CLK_SRC] = &periph_noc_clk_src.clkr, [USB30_MASTER_CLK_SRC] = &usb30_master_clk_src.clkr, [USB30_MOCK_UTMI_CLK_SRC] = &usb30_mock_utmi_clk_src.clkr, [USB3_PHY_AUX_CLK_SRC] = &usb3_phy_aux_clk_src.clkr, [USB20_MASTER_CLK_SRC] = &usb20_master_clk_src.clkr, [USB20_MOCK_UTMI_CLK_SRC] = &usb20_mock_utmi_clk_src.clkr, [SDCC1_APPS_CLK_SRC] = &sdcc1_apps_clk_src.clkr, [SDCC1_ICE_CORE_CLK_SRC] = &sdcc1_ice_core_clk_src.clkr, [SDCC2_APPS_CLK_SRC] = &sdcc2_apps_clk_src.clkr, [SDCC3_APPS_CLK_SRC] = &sdcc3_apps_clk_src.clkr, [SDCC4_APPS_CLK_SRC] = &sdcc4_apps_clk_src.clkr, [BLSP1_QUP1_SPI_APPS_CLK_SRC] = &blsp1_qup1_spi_apps_clk_src.clkr, [BLSP1_QUP1_I2C_APPS_CLK_SRC] = &blsp1_qup1_i2c_apps_clk_src.clkr, [BLSP1_UART1_APPS_CLK_SRC] = &blsp1_uart1_apps_clk_src.clkr, [BLSP1_QUP2_SPI_APPS_CLK_SRC] = &blsp1_qup2_spi_apps_clk_src.clkr, [BLSP1_QUP2_I2C_APPS_CLK_SRC] = &blsp1_qup2_i2c_apps_clk_src.clkr, [BLSP1_UART2_APPS_CLK_SRC] = &blsp1_uart2_apps_clk_src.clkr, [BLSP1_QUP3_SPI_APPS_CLK_SRC] = &blsp1_qup3_spi_apps_clk_src.clkr, [BLSP1_QUP3_I2C_APPS_CLK_SRC] = &blsp1_qup3_i2c_apps_clk_src.clkr, [BLSP1_UART3_APPS_CLK_SRC] = &blsp1_uart3_apps_clk_src.clkr, [BLSP1_QUP4_SPI_APPS_CLK_SRC] = &blsp1_qup4_spi_apps_clk_src.clkr, [BLSP1_QUP4_I2C_APPS_CLK_SRC] = &blsp1_qup4_i2c_apps_clk_src.clkr, [BLSP1_UART4_APPS_CLK_SRC] = &blsp1_uart4_apps_clk_src.clkr, [BLSP1_QUP5_SPI_APPS_CLK_SRC] = &blsp1_qup5_spi_apps_clk_src.clkr, [BLSP1_QUP5_I2C_APPS_CLK_SRC] = &blsp1_qup5_i2c_apps_clk_src.clkr, [BLSP1_UART5_APPS_CLK_SRC] = &blsp1_uart5_apps_clk_src.clkr, [BLSP1_QUP6_SPI_APPS_CLK_SRC] = &blsp1_qup6_spi_apps_clk_src.clkr, [BLSP1_QUP6_I2C_APPS_CLK_SRC] = &blsp1_qup6_i2c_apps_clk_src.clkr, [BLSP1_UART6_APPS_CLK_SRC] = &blsp1_uart6_apps_clk_src.clkr, [BLSP2_QUP1_SPI_APPS_CLK_SRC] = &blsp2_qup1_spi_apps_clk_src.clkr, [BLSP2_QUP1_I2C_APPS_CLK_SRC] = &blsp2_qup1_i2c_apps_clk_src.clkr, [BLSP2_UART1_APPS_CLK_SRC] = &blsp2_uart1_apps_clk_src.clkr, [BLSP2_QUP2_SPI_APPS_CLK_SRC] = &blsp2_qup2_spi_apps_clk_src.clkr, [BLSP2_QUP2_I2C_APPS_CLK_SRC] = &blsp2_qup2_i2c_apps_clk_src.clkr, [BLSP2_UART2_APPS_CLK_SRC] = &blsp2_uart2_apps_clk_src.clkr, [BLSP2_QUP3_SPI_APPS_CLK_SRC] = &blsp2_qup3_spi_apps_clk_src.clkr, [BLSP2_QUP3_I2C_APPS_CLK_SRC] = &blsp2_qup3_i2c_apps_clk_src.clkr, [BLSP2_UART3_APPS_CLK_SRC] = &blsp2_uart3_apps_clk_src.clkr, [BLSP2_QUP4_SPI_APPS_CLK_SRC] = &blsp2_qup4_spi_apps_clk_src.clkr, [BLSP2_QUP4_I2C_APPS_CLK_SRC] = &blsp2_qup4_i2c_apps_clk_src.clkr, [BLSP2_UART4_APPS_CLK_SRC] = &blsp2_uart4_apps_clk_src.clkr, [BLSP2_QUP5_SPI_APPS_CLK_SRC] = &blsp2_qup5_spi_apps_clk_src.clkr, [BLSP2_QUP5_I2C_APPS_CLK_SRC] = &blsp2_qup5_i2c_apps_clk_src.clkr, [BLSP2_UART5_APPS_CLK_SRC] = &blsp2_uart5_apps_clk_src.clkr, [BLSP2_QUP6_SPI_APPS_CLK_SRC] = &blsp2_qup6_spi_apps_clk_src.clkr, [BLSP2_QUP6_I2C_APPS_CLK_SRC] = &blsp2_qup6_i2c_apps_clk_src.clkr, [BLSP2_UART6_APPS_CLK_SRC] = &blsp2_uart6_apps_clk_src.clkr, [PDM2_CLK_SRC] = &pdm2_clk_src.clkr, [TSIF_REF_CLK_SRC] = &tsif_ref_clk_src.clkr, [GCC_SLEEP_CLK_SRC] = &gcc_sleep_clk_src.clkr, [HMSS_RBCPR_CLK_SRC] = &hmss_rbcpr_clk_src.clkr, [HMSS_GPLL0_CLK_SRC] = &hmss_gpll0_clk_src.clkr, [GP1_CLK_SRC] = &gp1_clk_src.clkr, [GP2_CLK_SRC] = &gp2_clk_src.clkr, [GP3_CLK_SRC] = &gp3_clk_src.clkr, [PCIE_AUX_CLK_SRC] = &pcie_aux_clk_src.clkr, [UFS_AXI_CLK_SRC] = &ufs_axi_clk_src.clkr, [UFS_ICE_CORE_CLK_SRC] = &ufs_ice_core_clk_src.clkr, [QSPI_SER_CLK_SRC] = &qspi_ser_clk_src.clkr, [GCC_SYS_NOC_USB3_AXI_CLK] = &gcc_sys_noc_usb3_axi_clk.clkr, [GCC_SYS_NOC_UFS_AXI_CLK] = &gcc_sys_noc_ufs_axi_clk.clkr, [GCC_PERIPH_NOC_USB20_AHB_CLK] = &gcc_periph_noc_usb20_ahb_clk.clkr, [GCC_MMSS_NOC_CFG_AHB_CLK] = &gcc_mmss_noc_cfg_ahb_clk.clkr, [GCC_MMSS_BIMC_GFX_CLK] = &gcc_mmss_bimc_gfx_clk.clkr, [GCC_USB30_MASTER_CLK] = &gcc_usb30_master_clk.clkr, [GCC_USB30_SLEEP_CLK] = &gcc_usb30_sleep_clk.clkr, [GCC_USB30_MOCK_UTMI_CLK] = &gcc_usb30_mock_utmi_clk.clkr, [GCC_USB3_PHY_AUX_CLK] = &gcc_usb3_phy_aux_clk.clkr, [GCC_USB3_PHY_PIPE_CLK] = &gcc_usb3_phy_pipe_clk.clkr, [GCC_USB20_MASTER_CLK] = &gcc_usb20_master_clk.clkr, [GCC_USB20_SLEEP_CLK] = &gcc_usb20_sleep_clk.clkr, [GCC_USB20_MOCK_UTMI_CLK] = &gcc_usb20_mock_utmi_clk.clkr, [GCC_USB_PHY_CFG_AHB2PHY_CLK] = &gcc_usb_phy_cfg_ahb2phy_clk.clkr, [GCC_SDCC1_APPS_CLK] = &gcc_sdcc1_apps_clk.clkr, [GCC_SDCC1_AHB_CLK] = &gcc_sdcc1_ahb_clk.clkr, [GCC_SDCC1_ICE_CORE_CLK] = &gcc_sdcc1_ice_core_clk.clkr, [GCC_SDCC2_APPS_CLK] = &gcc_sdcc2_apps_clk.clkr, [GCC_SDCC2_AHB_CLK] = &gcc_sdcc2_ahb_clk.clkr, [GCC_SDCC3_APPS_CLK] = &gcc_sdcc3_apps_clk.clkr, [GCC_SDCC3_AHB_CLK] = &gcc_sdcc3_ahb_clk.clkr, [GCC_SDCC4_APPS_CLK] = &gcc_sdcc4_apps_clk.clkr, [GCC_SDCC4_AHB_CLK] = &gcc_sdcc4_ahb_clk.clkr, [GCC_BLSP1_AHB_CLK] = &gcc_blsp1_ahb_clk.clkr, [GCC_BLSP1_SLEEP_CLK] = &gcc_blsp1_sleep_clk.clkr, [GCC_BLSP1_QUP1_SPI_APPS_CLK] = &gcc_blsp1_qup1_spi_apps_clk.clkr, [GCC_BLSP1_QUP1_I2C_APPS_CLK] = &gcc_blsp1_qup1_i2c_apps_clk.clkr, [GCC_BLSP1_UART1_APPS_CLK] = &gcc_blsp1_uart1_apps_clk.clkr, [GCC_BLSP1_QUP2_SPI_APPS_CLK] = &gcc_blsp1_qup2_spi_apps_clk.clkr, [GCC_BLSP1_QUP2_I2C_APPS_CLK] = &gcc_blsp1_qup2_i2c_apps_clk.clkr, [GCC_BLSP1_UART2_APPS_CLK] = &gcc_blsp1_uart2_apps_clk.clkr, [GCC_BLSP1_QUP3_SPI_APPS_CLK] = &gcc_blsp1_qup3_spi_apps_clk.clkr, [GCC_BLSP1_QUP3_I2C_APPS_CLK] = &gcc_blsp1_qup3_i2c_apps_clk.clkr, [GCC_BLSP1_UART3_APPS_CLK] = &gcc_blsp1_uart3_apps_clk.clkr, [GCC_BLSP1_QUP4_SPI_APPS_CLK] = &gcc_blsp1_qup4_spi_apps_clk.clkr, [GCC_BLSP1_QUP4_I2C_APPS_CLK] = &gcc_blsp1_qup4_i2c_apps_clk.clkr, [GCC_BLSP1_UART4_APPS_CLK] = &gcc_blsp1_uart4_apps_clk.clkr, [GCC_BLSP1_QUP5_SPI_APPS_CLK] = &gcc_blsp1_qup5_spi_apps_clk.clkr, [GCC_BLSP1_QUP5_I2C_APPS_CLK] = &gcc_blsp1_qup5_i2c_apps_clk.clkr, [GCC_BLSP1_UART5_APPS_CLK] = &gcc_blsp1_uart5_apps_clk.clkr, [GCC_BLSP1_QUP6_SPI_APPS_CLK] = &gcc_blsp1_qup6_spi_apps_clk.clkr, [GCC_BLSP1_QUP6_I2C_APPS_CLK] = &gcc_blsp1_qup6_i2c_apps_clk.clkr, [GCC_BLSP1_UART6_APPS_CLK] = &gcc_blsp1_uart6_apps_clk.clkr, [GCC_BLSP2_AHB_CLK] = &gcc_blsp2_ahb_clk.clkr, [GCC_BLSP2_SLEEP_CLK] = &gcc_blsp2_sleep_clk.clkr, [GCC_BLSP2_QUP1_SPI_APPS_CLK] = &gcc_blsp2_qup1_spi_apps_clk.clkr, [GCC_BLSP2_QUP1_I2C_APPS_CLK] = &gcc_blsp2_qup1_i2c_apps_clk.clkr, [GCC_BLSP2_UART1_APPS_CLK] = &gcc_blsp2_uart1_apps_clk.clkr, [GCC_BLSP2_QUP2_SPI_APPS_CLK] = &gcc_blsp2_qup2_spi_apps_clk.clkr, [GCC_BLSP2_QUP2_I2C_APPS_CLK] = &gcc_blsp2_qup2_i2c_apps_clk.clkr, [GCC_BLSP2_UART2_APPS_CLK] = &gcc_blsp2_uart2_apps_clk.clkr, [GCC_BLSP2_QUP3_SPI_APPS_CLK] = &gcc_blsp2_qup3_spi_apps_clk.clkr, [GCC_BLSP2_QUP3_I2C_APPS_CLK] = &gcc_blsp2_qup3_i2c_apps_clk.clkr, [GCC_BLSP2_UART3_APPS_CLK] = &gcc_blsp2_uart3_apps_clk.clkr, [GCC_BLSP2_QUP4_SPI_APPS_CLK] = &gcc_blsp2_qup4_spi_apps_clk.clkr, [GCC_BLSP2_QUP4_I2C_APPS_CLK] = &gcc_blsp2_qup4_i2c_apps_clk.clkr, [GCC_BLSP2_UART4_APPS_CLK] = &gcc_blsp2_uart4_apps_clk.clkr, [GCC_BLSP2_QUP5_SPI_APPS_CLK] = &gcc_blsp2_qup5_spi_apps_clk.clkr, [GCC_BLSP2_QUP5_I2C_APPS_CLK] = &gcc_blsp2_qup5_i2c_apps_clk.clkr, [GCC_BLSP2_UART5_APPS_CLK] = &gcc_blsp2_uart5_apps_clk.clkr, [GCC_BLSP2_QUP6_SPI_APPS_CLK] = &gcc_blsp2_qup6_spi_apps_clk.clkr, [GCC_BLSP2_QUP6_I2C_APPS_CLK] = &gcc_blsp2_qup6_i2c_apps_clk.clkr, [GCC_BLSP2_UART6_APPS_CLK] = &gcc_blsp2_uart6_apps_clk.clkr, [GCC_PDM_AHB_CLK] = &gcc_pdm_ahb_clk.clkr, [GCC_PDM2_CLK] = &gcc_pdm2_clk.clkr, [GCC_PRNG_AHB_CLK] = &gcc_prng_ahb_clk.clkr, [GCC_TSIF_AHB_CLK] = &gcc_tsif_ahb_clk.clkr, [GCC_TSIF_REF_CLK] = &gcc_tsif_ref_clk.clkr, [GCC_TSIF_INACTIVITY_TIMERS_CLK] = &gcc_tsif_inactivity_timers_clk.clkr, [GCC_BOOT_ROM_AHB_CLK] = &gcc_boot_rom_ahb_clk.clkr, [GCC_BIMC_GFX_CLK] = &gcc_bimc_gfx_clk.clkr, [GCC_HMSS_RBCPR_CLK] = &gcc_hmss_rbcpr_clk.clkr, [GCC_GP1_CLK] = &gcc_gp1_clk.clkr, [GCC_GP2_CLK] = &gcc_gp2_clk.clkr, [GCC_GP3_CLK] = &gcc_gp3_clk.clkr, [GCC_PCIE_0_SLV_AXI_CLK] = &gcc_pcie_0_slv_axi_clk.clkr, [GCC_PCIE_0_MSTR_AXI_CLK] = &gcc_pcie_0_mstr_axi_clk.clkr, [GCC_PCIE_0_CFG_AHB_CLK] = &gcc_pcie_0_cfg_ahb_clk.clkr, [GCC_PCIE_0_AUX_CLK] = &gcc_pcie_0_aux_clk.clkr, [GCC_PCIE_0_PIPE_CLK] = &gcc_pcie_0_pipe_clk.clkr, [GCC_PCIE_1_SLV_AXI_CLK] = &gcc_pcie_1_slv_axi_clk.clkr, [GCC_PCIE_1_MSTR_AXI_CLK] = &gcc_pcie_1_mstr_axi_clk.clkr, [GCC_PCIE_1_CFG_AHB_CLK] = &gcc_pcie_1_cfg_ahb_clk.clkr, [GCC_PCIE_1_AUX_CLK] = &gcc_pcie_1_aux_clk.clkr, [GCC_PCIE_1_PIPE_CLK] = &gcc_pcie_1_pipe_clk.clkr, [GCC_PCIE_2_SLV_AXI_CLK] = &gcc_pcie_2_slv_axi_clk.clkr, [GCC_PCIE_2_MSTR_AXI_CLK] = &gcc_pcie_2_mstr_axi_clk.clkr, [GCC_PCIE_2_CFG_AHB_CLK] = &gcc_pcie_2_cfg_ahb_clk.clkr, [GCC_PCIE_2_AUX_CLK] = &gcc_pcie_2_aux_clk.clkr, [GCC_PCIE_2_PIPE_CLK] = &gcc_pcie_2_pipe_clk.clkr, [GCC_PCIE_PHY_CFG_AHB_CLK] = &gcc_pcie_phy_cfg_ahb_clk.clkr, [GCC_PCIE_PHY_AUX_CLK] = &gcc_pcie_phy_aux_clk.clkr, [GCC_UFS_AXI_CLK] = &gcc_ufs_axi_clk.clkr, [GCC_UFS_AHB_CLK] = &gcc_ufs_ahb_clk.clkr, [GCC_UFS_TX_CFG_CLK] = &gcc_ufs_tx_cfg_clk.clkr, [GCC_UFS_RX_CFG_CLK] = &gcc_ufs_rx_cfg_clk.clkr, [GCC_HLOS1_VOTE_LPASS_CORE_SMMU_CLK] = &gcc_hlos1_vote_lpass_core_smmu_clk.clkr, [GCC_HLOS1_VOTE_LPASS_ADSP_SMMU_CLK] = &gcc_hlos1_vote_lpass_adsp_smmu_clk.clkr, [GCC_UFS_TX_SYMBOL_0_CLK] = &gcc_ufs_tx_symbol_0_clk.clkr, [GCC_UFS_RX_SYMBOL_0_CLK] = &gcc_ufs_rx_symbol_0_clk.clkr, [GCC_UFS_RX_SYMBOL_1_CLK] = &gcc_ufs_rx_symbol_1_clk.clkr, [GCC_UFS_UNIPRO_CORE_CLK] = &gcc_ufs_unipro_core_clk.clkr, [GCC_UFS_ICE_CORE_CLK] = &gcc_ufs_ice_core_clk.clkr, [GCC_UFS_SYS_CLK_CORE_CLK] = &gcc_ufs_sys_clk_core_clk.clkr, [GCC_UFS_TX_SYMBOL_CLK_CORE_CLK] = &gcc_ufs_tx_symbol_clk_core_clk.clkr, [GCC_AGGRE0_SNOC_AXI_CLK] = &gcc_aggre0_snoc_axi_clk.clkr, [GCC_AGGRE0_CNOC_AHB_CLK] = &gcc_aggre0_cnoc_ahb_clk.clkr, [GCC_SMMU_AGGRE0_AXI_CLK] = &gcc_smmu_aggre0_axi_clk.clkr, [GCC_SMMU_AGGRE0_AHB_CLK] = &gcc_smmu_aggre0_ahb_clk.clkr, [GCC_AGGRE1_PNOC_AHB_CLK] = &gcc_aggre1_pnoc_ahb_clk.clkr, [GCC_AGGRE2_UFS_AXI_CLK] = &gcc_aggre2_ufs_axi_clk.clkr, [GCC_AGGRE2_USB3_AXI_CLK] = &gcc_aggre2_usb3_axi_clk.clkr, [GCC_QSPI_AHB_CLK] = &gcc_qspi_ahb_clk.clkr, [GCC_QSPI_SER_CLK] = &gcc_qspi_ser_clk.clkr, [GCC_USB3_CLKREF_CLK] = &gcc_usb3_clkref_clk.clkr, [GCC_HDMI_CLKREF_CLK] = &gcc_hdmi_clkref_clk.clkr, [GCC_UFS_CLKREF_CLK] = &gcc_ufs_clkref_clk.clkr, [GCC_PCIE_CLKREF_CLK] = &gcc_pcie_clkref_clk.clkr, [GCC_RX2_USB2_CLKREF_CLK] = &gcc_rx2_usb2_clkref_clk.clkr, [GCC_RX1_USB2_CLKREF_CLK] = &gcc_rx1_usb2_clkref_clk.clkr, [GCC_EDP_CLKREF_CLK] = &gcc_edp_clkref_clk.clkr, [GCC_MSS_CFG_AHB_CLK] = &gcc_mss_cfg_ahb_clk.clkr, [GCC_MSS_Q6_BIMC_AXI_CLK] = &gcc_mss_q6_bimc_axi_clk.clkr, [GCC_MSS_SNOC_AXI_CLK] = &gcc_mss_snoc_axi_clk.clkr, [GCC_MSS_MNOC_BIMC_AXI_CLK] = &gcc_mss_mnoc_bimc_axi_clk.clkr, [GCC_DCC_AHB_CLK] = &gcc_dcc_ahb_clk.clkr, [GCC_AGGRE0_NOC_MPU_CFG_AHB_CLK] = &gcc_aggre0_noc_mpu_cfg_ahb_clk.clkr, [GCC_MMSS_GPLL0_DIV_CLK] = &gcc_mmss_gpll0_div_clk.clkr, [GCC_MSS_GPLL0_DIV_CLK] = &gcc_mss_gpll0_div_clk.clkr, }; static struct gdsc *gcc_msm8996_gdscs[] = { [AGGRE0_NOC_GDSC] = &aggre0_noc_gdsc, [HLOS1_VOTE_AGGRE0_NOC_GDSC] = &hlos1_vote_aggre0_noc_gdsc, [HLOS1_VOTE_LPASS_ADSP_GDSC] = &hlos1_vote_lpass_adsp_gdsc, [HLOS1_VOTE_LPASS_CORE_GDSC] = &hlos1_vote_lpass_core_gdsc, [USB30_GDSC] = &usb30_gdsc, [PCIE0_GDSC] = &pcie0_gdsc, [PCIE1_GDSC] = &pcie1_gdsc, [PCIE2_GDSC] = &pcie2_gdsc, [UFS_GDSC] = &ufs_gdsc, }; static const struct qcom_reset_map gcc_msm8996_resets[] = { [GCC_SYSTEM_NOC_BCR] = { 0x4000 }, [GCC_CONFIG_NOC_BCR] = { 0x5000 }, [GCC_PERIPH_NOC_BCR] = { 0x6000 }, [GCC_IMEM_BCR] = { 0x8000 }, [GCC_MMSS_BCR] = { 0x9000 }, [GCC_PIMEM_BCR] = { 0x0a000 }, [GCC_QDSS_BCR] = { 0x0c000 }, [GCC_USB_30_BCR] = { 0x0f000 }, [GCC_USB_20_BCR] = { 0x12000 }, [GCC_QUSB2PHY_PRIM_BCR] = { 0x12038 }, [GCC_QUSB2PHY_SEC_BCR] = { 0x1203c }, [GCC_USB3_PHY_BCR] = { 0x50020 }, [GCC_USB3PHY_PHY_BCR] = { 0x50024 }, [GCC_USB_PHY_CFG_AHB2PHY_BCR] = { 0x6a000 }, [GCC_SDCC1_BCR] = { 0x13000 }, [GCC_SDCC2_BCR] = { 0x14000 }, [GCC_SDCC3_BCR] = { 0x15000 }, [GCC_SDCC4_BCR] = { 0x16000 }, [GCC_BLSP1_BCR] = { 0x17000 }, [GCC_BLSP1_QUP1_BCR] = { 0x19000 }, [GCC_BLSP1_UART1_BCR] = { 0x1a000 }, [GCC_BLSP1_QUP2_BCR] = { 0x1b000 }, [GCC_BLSP1_UART2_BCR] = { 0x1c000 }, [GCC_BLSP1_QUP3_BCR] = { 0x1d000 }, [GCC_BLSP1_UART3_BCR] = { 0x1e000 }, [GCC_BLSP1_QUP4_BCR] = { 0x1f000 }, [GCC_BLSP1_UART4_BCR] = { 0x20000 }, [GCC_BLSP1_QUP5_BCR] = { 0x21000 }, [GCC_BLSP1_UART5_BCR] = { 0x22000 }, [GCC_BLSP1_QUP6_BCR] = { 0x23000 }, [GCC_BLSP1_UART6_BCR] = { 0x24000 }, [GCC_BLSP2_BCR] = { 0x25000 }, [GCC_BLSP2_QUP1_BCR] = { 0x26000 }, [GCC_BLSP2_UART1_BCR] = { 0x27000 }, [GCC_BLSP2_QUP2_BCR] = { 0x28000 }, [GCC_BLSP2_UART2_BCR] = { 0x29000 }, [GCC_BLSP2_QUP3_BCR] = { 0x2a000 }, [GCC_BLSP2_UART3_BCR] = { 0x2b000 }, [GCC_BLSP2_QUP4_BCR] = { 0x2c000 }, [GCC_BLSP2_UART4_BCR] = { 0x2d000 }, [GCC_BLSP2_QUP5_BCR] = { 0x2e000 }, [GCC_BLSP2_UART5_BCR] = { 0x2f000 }, [GCC_BLSP2_QUP6_BCR] = { 0x30000 }, [GCC_BLSP2_UART6_BCR] = { 0x31000 }, [GCC_PDM_BCR] = { 0x33000 }, [GCC_PRNG_BCR] = { 0x34000 }, [GCC_TSIF_BCR] = { 0x36000 }, [GCC_TCSR_BCR] = { 0x37000 }, [GCC_BOOT_ROM_BCR] = { 0x38000 }, [GCC_MSG_RAM_BCR] = { 0x39000 }, [GCC_TLMM_BCR] = { 0x3a000 }, [GCC_MPM_BCR] = { 0x3b000 }, [GCC_SEC_CTRL_BCR] = { 0x3d000 }, [GCC_SPMI_BCR] = { 0x3f000 }, [GCC_SPDM_BCR] = { 0x40000 }, [GCC_CE1_BCR] = { 0x41000 }, [GCC_BIMC_BCR] = { 0x44000 }, [GCC_SNOC_BUS_TIMEOUT0_BCR] = { 0x49000 }, [GCC_SNOC_BUS_TIMEOUT2_BCR] = { 0x49008 }, [GCC_SNOC_BUS_TIMEOUT1_BCR] = { 0x49010 }, [GCC_SNOC_BUS_TIMEOUT3_BCR] = { 0x49018 }, [GCC_SNOC_BUS_TIMEOUT_EXTREF_BCR] = { 0x49020 }, [GCC_PNOC_BUS_TIMEOUT0_BCR] = { 0x4a000 }, [GCC_PNOC_BUS_TIMEOUT1_BCR] = { 0x4a008 }, [GCC_PNOC_BUS_TIMEOUT2_BCR] = { 0x4a010 }, [GCC_PNOC_BUS_TIMEOUT3_BCR] = { 0x4a018 }, [GCC_PNOC_BUS_TIMEOUT4_BCR] = { 0x4a020 }, [GCC_CNOC_BUS_TIMEOUT0_BCR] = { 0x4b000 }, [GCC_CNOC_BUS_TIMEOUT1_BCR] = { 0x4b008 }, [GCC_CNOC_BUS_TIMEOUT2_BCR] = { 0x4b010 }, [GCC_CNOC_BUS_TIMEOUT3_BCR] = { 0x4b018 }, [GCC_CNOC_BUS_TIMEOUT4_BCR] = { 0x4b020 }, [GCC_CNOC_BUS_TIMEOUT5_BCR] = { 0x4b028 }, [GCC_CNOC_BUS_TIMEOUT6_BCR] = { 0x4b030 }, [GCC_CNOC_BUS_TIMEOUT7_BCR] = { 0x4b038 }, [GCC_CNOC_BUS_TIMEOUT8_BCR] = { 0x80000 }, [GCC_CNOC_BUS_TIMEOUT9_BCR] = { 0x80008 }, [GCC_CNOC_BUS_TIMEOUT_EXTREF_BCR] = { 0x80010 }, [GCC_APB2JTAG_BCR] = { 0x4c000 }, [GCC_RBCPR_CX_BCR] = { 0x4e000 }, [GCC_RBCPR_MX_BCR] = { 0x4f000 }, [GCC_PCIE_0_BCR] = { 0x6b000 }, [GCC_PCIE_0_PHY_BCR] = { 0x6c01c }, [GCC_PCIE_1_BCR] = { 0x6d000 }, [GCC_PCIE_1_PHY_BCR] = { 0x6d038 }, [GCC_PCIE_2_BCR] = { 0x6e000 }, [GCC_PCIE_2_PHY_BCR] = { 0x6e038 }, [GCC_PCIE_PHY_BCR] = { 0x6f000 }, [GCC_PCIE_PHY_COM_BCR] = { 0x6f014 }, [GCC_PCIE_PHY_COM_NOCSR_BCR] = { 0x6f00c }, [GCC_DCD_BCR] = { 0x70000 }, [GCC_OBT_ODT_BCR] = { 0x73000 }, [GCC_UFS_BCR] = { 0x75000 }, [GCC_SSC_BCR] = { 0x63000 }, [GCC_VS_BCR] = { 0x7a000 }, [GCC_AGGRE0_NOC_BCR] = { 0x81000 }, [GCC_AGGRE1_NOC_BCR] = { 0x82000 }, [GCC_AGGRE2_NOC_BCR] = { 0x83000 }, [GCC_DCC_BCR] = { 0x84000 }, [GCC_IPA_BCR] = { 0x89000 }, [GCC_QSPI_BCR] = { 0x8b000 }, [GCC_SKL_BCR] = { 0x8c000 }, [GCC_MSMPU_BCR] = { 0x8d000 }, [GCC_MSS_Q6_BCR] = { 0x8e000 }, [GCC_QREFS_VBG_CAL_BCR] = { 0x88020 }, [GCC_MSS_RESTART] = { 0x8f008 }, }; static const struct regmap_config gcc_msm8996_regmap_config = { .reg_bits = 32, .reg_stride = 4, .val_bits = 32, .max_register = 0x8f010, .fast_io = true, }; static const struct qcom_cc_desc gcc_msm8996_desc = { .config = &gcc_msm8996_regmap_config, .clks = gcc_msm8996_clocks, .num_clks = ARRAY_SIZE(gcc_msm8996_clocks), .resets = gcc_msm8996_resets, .num_resets = ARRAY_SIZE(gcc_msm8996_resets), .gdscs = gcc_msm8996_gdscs, .num_gdscs = ARRAY_SIZE(gcc_msm8996_gdscs), .clk_hws = gcc_msm8996_hws, .num_clk_hws = ARRAY_SIZE(gcc_msm8996_hws), }; static const struct of_device_id gcc_msm8996_match_table[] = { { .compatible = "qcom,gcc-msm8996" }, { } }; MODULE_DEVICE_TABLE(of, gcc_msm8996_match_table); static int gcc_msm8996_probe(struct platform_device *pdev) { struct regmap *regmap; regmap = qcom_cc_map(pdev, &gcc_msm8996_desc); if (IS_ERR(regmap)) return PTR_ERR(regmap); /* * Set the HMSS_AHB_CLK_SLEEP_ENA bit to allow the hmss_ahb_clk to be * turned off by hardware during certain apps low power modes. */ regmap_update_bits(regmap, 0x52008, BIT(21), BIT(21)); return qcom_cc_really_probe(pdev, &gcc_msm8996_desc, regmap); } static struct platform_driver gcc_msm8996_driver = { .probe = gcc_msm8996_probe, .driver = { .name = "gcc-msm8996", .of_match_table = gcc_msm8996_match_table, }, }; static int __init gcc_msm8996_init(void) { return platform_driver_register(&gcc_msm8996_driver); } core_initcall(gcc_msm8996_init); static void __exit gcc_msm8996_exit(void) { platform_driver_unregister(&gcc_msm8996_driver); } module_exit(gcc_msm8996_exit); MODULE_DESCRIPTION("QCOM GCC MSM8996 Driver"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("platform:gcc-msm8996");
649837.c
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. Support functions for Extended Window Manager Hints, http://www.freedesktop.org/wiki/Standards_2fwm_2dspec Copyright 2005-2011 Peter Astrand <[email protected]> for Cendio AB Copyright 2007 Pierre Ossman <[email protected]> for Cendio AB 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/>. */ /* * Oracle GPL Disclaimer: For the avoidance of doubt, except that if any license choice * other than GPL or LGPL is available it will apply instead, Oracle elects to use only * the General Public License version 2 (GPLv2) at this time for any software where * a choice of GPL license versions is made available with the language indicating * that GPLv2 or any later version may be used, or where a choice of which version * of the GPL is applied is otherwise unspecified. */ #include <X11/Xlib.h> #include <X11/Xatom.h> #include <X11/Xutil.h> #include "rdesktop.h" #define _NET_WM_STATE_REMOVE 0 /* remove/unset property */ #define _NET_WM_STATE_ADD 1 /* add/set property */ #define _NET_WM_STATE_TOGGLE 2 /* toggle property */ extern Display *g_display; static Atom g_net_wm_state_maximized_vert_atom, g_net_wm_state_maximized_horz_atom, g_net_wm_state_hidden_atom, g_net_wm_name_atom, g_utf8_string_atom, g_net_wm_state_skip_taskbar_atom, g_net_wm_state_skip_pager_atom, g_net_wm_state_modal_atom, g_net_wm_icon_atom, g_net_wm_state_above_atom; Atom g_net_wm_state_atom, g_net_wm_desktop_atom; /* Get window property value (32 bit format) Returns zero on success, -1 on error */ static int get_property_value(Window wnd, char *propname, long max_length, unsigned long *nitems_return, unsigned char **prop_return, int nowarn) { int result; Atom property; Atom actual_type_return; int actual_format_return; unsigned long bytes_after_return; property = XInternAtom(g_display, propname, True); if (property == None) { fprintf(stderr, "Atom %s does not exist\n", propname); return (-1); } result = XGetWindowProperty(g_display, wnd, property, 0, /* long_offset */ max_length, /* long_length */ False, /* delete */ AnyPropertyType, /* req_type */ &actual_type_return, &actual_format_return, nitems_return, &bytes_after_return, prop_return); if (result != Success) { fprintf(stderr, "XGetWindowProperty failed\n"); return (-1); } if (actual_type_return == None || actual_format_return == 0) { if (!nowarn) fprintf(stderr, "Window is missing property %s\n", propname); return (-1); } if (bytes_after_return) { fprintf(stderr, "%s is too big for me\n", propname); return (-1); } if (actual_format_return != 32) { fprintf(stderr, "%s has bad format\n", propname); return (-1); } return (0); } /* Get current desktop number Returns -1 on error */ static int get_current_desktop(void) { unsigned long nitems_return; unsigned char *prop_return; int current_desktop; if (get_property_value (DefaultRootWindow(g_display), "_NET_CURRENT_DESKTOP", 1, &nitems_return, &prop_return, 0) < 0) return (-1); if (nitems_return != 1) { fprintf(stderr, "_NET_CURRENT_DESKTOP has bad length\n"); return (-1); } current_desktop = *prop_return; XFree(prop_return); return current_desktop; } /* Get workarea geometry Returns zero on success, -1 on error */ int get_current_workarea(uint32 * x, uint32 * y, uint32 * width, uint32 * height) { int current_desktop; unsigned long nitems_return; unsigned char *prop_return; long *return_words; const uint32 net_workarea_x_offset = 0; const uint32 net_workarea_y_offset = 1; const uint32 net_workarea_width_offset = 2; const uint32 net_workarea_height_offset = 3; const uint32 max_prop_length = 32 * 4; /* Max 32 desktops */ if (get_property_value (DefaultRootWindow(g_display), "_NET_WORKAREA", max_prop_length, &nitems_return, &prop_return, 0) < 0) return (-1); if (nitems_return % 4) { fprintf(stderr, "_NET_WORKAREA has odd length\n"); return (-1); } current_desktop = get_current_desktop(); if (current_desktop < 0) return -1; return_words = (long *) prop_return; *x = return_words[current_desktop * 4 + net_workarea_x_offset]; *y = return_words[current_desktop * 4 + net_workarea_y_offset]; *width = return_words[current_desktop * 4 + net_workarea_width_offset]; *height = return_words[current_desktop * 4 + net_workarea_height_offset]; XFree(prop_return); return (0); } void ewmh_init() { /* FIXME: Use XInternAtoms */ g_net_wm_state_maximized_vert_atom = XInternAtom(g_display, "_NET_WM_STATE_MAXIMIZED_VERT", False); g_net_wm_state_maximized_horz_atom = XInternAtom(g_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False); g_net_wm_state_hidden_atom = XInternAtom(g_display, "_NET_WM_STATE_HIDDEN", False); g_net_wm_state_skip_taskbar_atom = XInternAtom(g_display, "_NET_WM_STATE_SKIP_TASKBAR", False); g_net_wm_state_skip_pager_atom = XInternAtom(g_display, "_NET_WM_STATE_SKIP_PAGER", False); g_net_wm_state_modal_atom = XInternAtom(g_display, "_NET_WM_STATE_MODAL", False); g_net_wm_state_above_atom = XInternAtom(g_display, "_NET_WM_STATE_ABOVE", False); g_net_wm_state_atom = XInternAtom(g_display, "_NET_WM_STATE", False); g_net_wm_desktop_atom = XInternAtom(g_display, "_NET_WM_DESKTOP", False); g_net_wm_name_atom = XInternAtom(g_display, "_NET_WM_NAME", False); g_net_wm_icon_atom = XInternAtom(g_display, "_NET_WM_ICON", False); g_utf8_string_atom = XInternAtom(g_display, "UTF8_STRING", False); } /* Get the window state: normal/minimized/maximized. */ #ifndef MAKE_PROTO int ewmh_get_window_state(Window w) { unsigned long nitems_return; unsigned char *prop_return; unsigned long *return_words; unsigned long item; RD_BOOL maximized_vert, maximized_horz, hidden; maximized_vert = maximized_horz = hidden = False; if (get_property_value(w, "_NET_WM_STATE", 64, &nitems_return, &prop_return, 0) < 0) return SEAMLESSRDP_NORMAL; return_words = (unsigned long *) prop_return; for (item = 0; item < nitems_return; item++) { if (return_words[item] == g_net_wm_state_maximized_vert_atom) maximized_vert = True; if (return_words[item] == g_net_wm_state_maximized_horz_atom) maximized_horz = True; if (return_words[item] == g_net_wm_state_hidden_atom) hidden = True; } XFree(prop_return); /* In EWMH, HIDDEN overrides MAXIMIZED_VERT/MAXIMIZED_HORZ */ if (hidden) return SEAMLESSRDP_MINIMIZED; else if (maximized_vert && maximized_horz) return SEAMLESSRDP_MAXIMIZED; else return SEAMLESSRDP_NORMAL; } static int ewmh_modify_state(Window wnd, int add, Atom atom1, Atom atom2) { Status status; XEvent xevent; int result; unsigned long nitems; unsigned char *props; uint32 state = WithdrawnState; /* The spec states that the window manager must respect any _NET_WM_STATE attributes on a withdrawn window. In order words, we modify the attributes directly for withdrawn windows and ask the WM to do it for active windows. */ result = get_property_value(wnd, "WM_STATE", 64, &nitems, &props, 1); if ((result >= 0) && nitems) { state = *(uint32 *) props; XFree(props); } if (state == WithdrawnState) { if (add) { Atom atoms[2]; atoms[0] = atom1; nitems = 1; if (atom2) { atoms[1] = atom2; nitems = 2; } XChangeProperty(g_display, wnd, g_net_wm_state_atom, XA_ATOM, 32, PropModeAppend, (unsigned char *) atoms, nitems); } else { Atom *atoms; int i; if (get_property_value(wnd, "_NET_WM_STATE", 64, &nitems, &props, 1) < 0) return 0; atoms = (Atom *) props; for (i = 0; i < nitems; i++) { if ((atoms[i] == atom1) || (atom2 && (atoms[i] == atom2))) { if (i != (nitems - 1)) memmove(&atoms[i], &atoms[i + 1], sizeof(Atom) * (nitems - i - 1)); nitems--; i--; } } XChangeProperty(g_display, wnd, g_net_wm_state_atom, XA_ATOM, 32, PropModeReplace, (unsigned char *) atoms, nitems); XFree(props); } return 0; } xevent.type = ClientMessage; xevent.xclient.window = wnd; xevent.xclient.message_type = g_net_wm_state_atom; xevent.xclient.format = 32; if (add) xevent.xclient.data.l[0] = _NET_WM_STATE_ADD; else xevent.xclient.data.l[0] = _NET_WM_STATE_REMOVE; xevent.xclient.data.l[1] = atom1; xevent.xclient.data.l[2] = atom2; xevent.xclient.data.l[3] = 0; xevent.xclient.data.l[4] = 0; status = XSendEvent(g_display, DefaultRootWindow(g_display), False, SubstructureNotifyMask | SubstructureRedirectMask, &xevent); if (!status) return -1; return 0; } /* Set the window state: normal/minimized/maximized. Returns -1 on failure. */ int ewmh_change_state(Window wnd, int state) { /* * Deal with the max atoms */ if (state == SEAMLESSRDP_MAXIMIZED) { if (ewmh_modify_state (wnd, 1, g_net_wm_state_maximized_vert_atom, g_net_wm_state_maximized_horz_atom) < 0) return -1; } else { if (ewmh_modify_state (wnd, 0, g_net_wm_state_maximized_vert_atom, g_net_wm_state_maximized_horz_atom) < 0) return -1; } return 0; } int ewmh_get_window_desktop(Window wnd) { unsigned long nitems_return; unsigned char *prop_return; int desktop; if (get_property_value(wnd, "_NET_WM_DESKTOP", 1, &nitems_return, &prop_return, 0) < 0) return (-1); if (nitems_return != 1) { fprintf(stderr, "_NET_WM_DESKTOP has bad length\n"); return (-1); } desktop = *prop_return; XFree(prop_return); return desktop; } int ewmh_move_to_desktop(Window wnd, unsigned int desktop) { Status status; XEvent xevent; xevent.type = ClientMessage; xevent.xclient.window = wnd; xevent.xclient.message_type = g_net_wm_desktop_atom; xevent.xclient.format = 32; xevent.xclient.data.l[0] = desktop; xevent.xclient.data.l[1] = 0; xevent.xclient.data.l[2] = 0; xevent.xclient.data.l[3] = 0; xevent.xclient.data.l[4] = 0; status = XSendEvent(g_display, DefaultRootWindow(g_display), False, SubstructureNotifyMask | SubstructureRedirectMask, &xevent); if (!status) return -1; return 0; } void ewmh_set_wm_name(Window wnd, const char *title) { int len; len = strlen(title); XChangeProperty(g_display, wnd, g_net_wm_name_atom, g_utf8_string_atom, 8, PropModeReplace, (unsigned char *) title, len); } int ewmh_set_window_popup(Window wnd) { if (ewmh_modify_state (wnd, 1, g_net_wm_state_skip_taskbar_atom, g_net_wm_state_skip_pager_atom) < 0) return -1; return 0; } int ewmh_set_window_modal(Window wnd) { if (ewmh_modify_state(wnd, 1, g_net_wm_state_modal_atom, 0) < 0) return -1; return 0; } void ewmh_set_icon(Window wnd, int width, int height, const char *rgba_data) { unsigned long nitems, i; unsigned char *props; unsigned long *cur_set, *new_set; unsigned long *icon; cur_set = NULL; new_set = NULL; if (get_property_value(wnd, "_NET_WM_ICON", 10000, &nitems, &props, 1) >= 0) { cur_set = (unsigned long *) props; for (i = 0; i < nitems;) { if (cur_set[i] == width && cur_set[i + 1] == height) break; i += 2 + cur_set[i] * cur_set[i + 1]; } if (i != nitems) icon = cur_set + i; else { new_set = xmalloc((nitems + width * height + 2) * sizeof(unsigned long)); memcpy(new_set, cur_set, nitems * sizeof(unsigned long)); icon = new_set + nitems; nitems += width * height + 2; } } else { new_set = xmalloc((width * height + 2) * sizeof(unsigned long)); icon = new_set; nitems = width * height + 2; } icon[0] = width; icon[1] = height; /* Convert RGBA -> ARGB */ for (i = 0; i < width * height; i++) { icon[i + 2] = rgba_data[i * 4 + 3] << 24 | ((rgba_data[i * 4 + 0] << 16) & 0x00FF0000) | ((rgba_data[i * 4 + 1] << 8) & 0x0000FF00) | ((rgba_data[i * 4 + 2] << 0) & 0x000000FF); } XChangeProperty(g_display, wnd, g_net_wm_icon_atom, XA_CARDINAL, 32, PropModeReplace, (unsigned char *) (new_set ? new_set : cur_set), nitems); if (cur_set) XFree(cur_set); if (new_set) xfree(new_set); } void ewmh_del_icon(Window wnd, int width, int height) { unsigned long nitems, i, icon_size; unsigned char *props; unsigned long *cur_set, *new_set; cur_set = NULL; new_set = NULL; if (get_property_value(wnd, "_NET_WM_ICON", 10000, &nitems, &props, 1) < 0) return; cur_set = (unsigned long *) props; for (i = 0; i < nitems;) { if (cur_set[i] == width && cur_set[i + 1] == height) break; i += 2 + cur_set[i] * cur_set[i + 1]; } if (i == nitems) goto out; icon_size = width * height + 2; new_set = xmalloc((nitems - icon_size) * sizeof(unsigned long)); if (i != 0) memcpy(new_set, cur_set, i * sizeof(unsigned long)); if (i != nitems - icon_size) memcpy(new_set + i, cur_set + i + icon_size, (nitems - (i + icon_size)) * sizeof(unsigned long)); nitems -= icon_size; XChangeProperty(g_display, wnd, g_net_wm_icon_atom, XA_CARDINAL, 32, PropModeReplace, (unsigned char *) new_set, nitems); xfree(new_set); out: XFree(cur_set); } int ewmh_set_window_above(Window wnd) { if (ewmh_modify_state(wnd, 1, g_net_wm_state_above_atom, 0) < 0) return -1; return 0; } RD_BOOL ewmh_is_window_above(Window w) { unsigned long nitems_return; unsigned char *prop_return; unsigned long *return_words; unsigned long item; RD_BOOL above; above = False; if (get_property_value(w, "_NET_WM_STATE", 64, &nitems_return, &prop_return, 0) < 0) return False; return_words = (unsigned long *) prop_return; for (item = 0; item < nitems_return; item++) { if (return_words[item] == g_net_wm_state_above_atom) above = True; } XFree(prop_return); return above; } #endif /* MAKE_PROTO */ #if 0 /* FIXME: _NET_MOVERESIZE_WINDOW is for pagers, not for applications. We should implement _NET_WM_MOVERESIZE instead */ int ewmh_net_moveresize_window(Window wnd, int x, int y, int width, int height) { Status status; XEvent xevent; Atom moveresize; moveresize = XInternAtom(g_display, "_NET_MOVERESIZE_WINDOW", False); if (!moveresize) { return -1; } xevent.type = ClientMessage; xevent.xclient.window = wnd; xevent.xclient.message_type = moveresize; xevent.xclient.format = 32; xevent.xclient.data.l[0] = StaticGravity | (1 << 8) | (1 << 9) | (1 << 10) | (1 << 11); xevent.xclient.data.l[1] = x; xevent.xclient.data.l[2] = y; xevent.xclient.data.l[3] = width; xevent.xclient.data.l[4] = height; status = XSendEvent(g_display, DefaultRootWindow(g_display), False, SubstructureNotifyMask | SubstructureRedirectMask, &xevent); if (!status) return -1; return 0; } #endif
501998.c
/* USER CODE BEGIN Header */ /** ****************************************************************************** * File Name : stm32f4xx_hal_msp.c * Description : This file provides code for the MSP Initialization * and de-Initialization codes. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2020 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" /* USER CODE BEGIN Includes */ /* USER CODE END Includes */ extern DMA_HandleTypeDef hdma_usart1_rx; extern DMA_HandleTypeDef hdma_usart1_tx; /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN TD */ /* USER CODE END TD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN Define */ /* USER CODE END Define */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN Macro */ /* USER CODE END Macro */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* External functions --------------------------------------------------------*/ /* USER CODE BEGIN ExternalFunctions */ /* USER CODE END ExternalFunctions */ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /** * Initializes the Global MSP. */ void HAL_MspInit(void) { /* USER CODE BEGIN MspInit 0 */ /* USER CODE END MspInit 0 */ __HAL_RCC_SYSCFG_CLK_ENABLE(); __HAL_RCC_PWR_CLK_ENABLE(); /* System interrupt init*/ /* PendSV_IRQn interrupt configuration */ HAL_NVIC_SetPriority(PendSV_IRQn, 2, 0); /* USER CODE BEGIN MspInit 1 */ /* USER CODE END MspInit 1 */ } /** * @brief ADC MSP Initialization * This function configures the hardware resources used in this example * @param hadc: ADC handle pointer * @retval None */ void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if(hadc->Instance==ADC1) { /* USER CODE BEGIN ADC1_MspInit 0 */ /* USER CODE END ADC1_MspInit 0 */ /* Peripheral clock enable */ __HAL_RCC_ADC1_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**ADC1 GPIO Configuration PA0/WKUP ------> ADC1_IN0 */ GPIO_InitStruct.Pin = GPIO_PIN_0; GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* ADC1 interrupt Init */ HAL_NVIC_SetPriority(ADC_IRQn, 2, 0); HAL_NVIC_EnableIRQ(ADC_IRQn); /* USER CODE BEGIN ADC1_MspInit 1 */ /* USER CODE END ADC1_MspInit 1 */ } } /** * @brief ADC MSP De-Initialization * This function freeze the hardware resources used in this example * @param hadc: ADC handle pointer * @retval None */ void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc) { if(hadc->Instance==ADC1) { /* USER CODE BEGIN ADC1_MspDeInit 0 */ /* USER CODE END ADC1_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_ADC1_CLK_DISABLE(); /**ADC1 GPIO Configuration PA0/WKUP ------> ADC1_IN0 */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_0); /* ADC1 interrupt DeInit */ HAL_NVIC_DisableIRQ(ADC_IRQn); /* USER CODE BEGIN ADC1_MspDeInit 1 */ /* USER CODE END ADC1_MspDeInit 1 */ } } /** * @brief DAC MSP Initialization * This function configures the hardware resources used in this example * @param hdac: DAC handle pointer * @retval None */ void HAL_DAC_MspInit(DAC_HandleTypeDef* hdac) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if(hdac->Instance==DAC) { /* USER CODE BEGIN DAC_MspInit 0 */ /* USER CODE END DAC_MspInit 0 */ /* Peripheral clock enable */ __HAL_RCC_DAC_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**DAC GPIO Configuration PA4 ------> DAC_OUT1 */ GPIO_InitStruct.Pin = GPIO_PIN_4; GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* DAC interrupt Init */ HAL_NVIC_SetPriority(TIM6_DAC_IRQn, 2, 0); HAL_NVIC_EnableIRQ(TIM6_DAC_IRQn); /* USER CODE BEGIN DAC_MspInit 1 */ /* USER CODE END DAC_MspInit 1 */ } } /** * @brief DAC MSP De-Initialization * This function freeze the hardware resources used in this example * @param hdac: DAC handle pointer * @retval None */ void HAL_DAC_MspDeInit(DAC_HandleTypeDef* hdac) { if(hdac->Instance==DAC) { /* USER CODE BEGIN DAC_MspDeInit 0 */ /* USER CODE END DAC_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_DAC_CLK_DISABLE(); /**DAC GPIO Configuration PA4 ------> DAC_OUT1 */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_4); /* DAC interrupt DeInit */ HAL_NVIC_DisableIRQ(TIM6_DAC_IRQn); /* USER CODE BEGIN DAC_MspDeInit 1 */ /* USER CODE END DAC_MspDeInit 1 */ } } /** * @brief TIM_Base MSP Initialization * This function configures the hardware resources used in this example * @param htim_base: TIM_Base handle pointer * @retval None */ void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* htim_base) { if(htim_base->Instance==TIM2) { /* USER CODE BEGIN TIM2_MspInit 0 */ /* USER CODE END TIM2_MspInit 0 */ /* Peripheral clock enable */ __HAL_RCC_TIM2_CLK_ENABLE(); /* TIM2 interrupt Init */ HAL_NVIC_SetPriority(TIM2_IRQn, 1, 0); HAL_NVIC_EnableIRQ(TIM2_IRQn); /* USER CODE BEGIN TIM2_MspInit 1 */ /* USER CODE END TIM2_MspInit 1 */ } } /** * @brief TIM_Base MSP De-Initialization * This function freeze the hardware resources used in this example * @param htim_base: TIM_Base handle pointer * @retval None */ void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef* htim_base) { if(htim_base->Instance==TIM2) { /* USER CODE BEGIN TIM2_MspDeInit 0 */ /* USER CODE END TIM2_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_TIM2_CLK_DISABLE(); /* TIM2 interrupt DeInit */ HAL_NVIC_DisableIRQ(TIM2_IRQn); /* USER CODE BEGIN TIM2_MspDeInit 1 */ /* USER CODE END TIM2_MspDeInit 1 */ } } /** * @brief UART MSP Initialization * This function configures the hardware resources used in this example * @param huart: UART handle pointer * @retval None */ void HAL_UART_MspInit(UART_HandleTypeDef* huart) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if(huart->Instance==USART1) { /* USER CODE BEGIN USART1_MspInit 0 */ /* USER CODE END USART1_MspInit 0 */ /* Peripheral clock enable */ __HAL_RCC_USART1_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ GPIO_InitStruct.Pin = GPIO_PIN_9|GPIO_PIN_10; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF7_USART1; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USART1 DMA Init */ /* USART1_RX Init */ hdma_usart1_rx.Instance = DMA2_Stream2; hdma_usart1_rx.Init.Channel = DMA_CHANNEL_4; hdma_usart1_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; hdma_usart1_rx.Init.PeriphInc = DMA_PINC_DISABLE; hdma_usart1_rx.Init.MemInc = DMA_MINC_ENABLE; hdma_usart1_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; hdma_usart1_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; hdma_usart1_rx.Init.Mode = DMA_NORMAL; hdma_usart1_rx.Init.Priority = DMA_PRIORITY_VERY_HIGH; hdma_usart1_rx.Init.FIFOMode = DMA_FIFOMODE_DISABLE; if (HAL_DMA_Init(&hdma_usart1_rx) != HAL_OK) { Error_Handler(); } __HAL_LINKDMA(huart,hdmarx,hdma_usart1_rx); /* USART1_TX Init */ hdma_usart1_tx.Instance = DMA2_Stream7; hdma_usart1_tx.Init.Channel = DMA_CHANNEL_4; hdma_usart1_tx.Init.Direction = DMA_MEMORY_TO_PERIPH; hdma_usart1_tx.Init.PeriphInc = DMA_PINC_DISABLE; hdma_usart1_tx.Init.MemInc = DMA_MINC_ENABLE; hdma_usart1_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; hdma_usart1_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; hdma_usart1_tx.Init.Mode = DMA_NORMAL; hdma_usart1_tx.Init.Priority = DMA_PRIORITY_VERY_HIGH; hdma_usart1_tx.Init.FIFOMode = DMA_FIFOMODE_DISABLE; if (HAL_DMA_Init(&hdma_usart1_tx) != HAL_OK) { Error_Handler(); } __HAL_LINKDMA(huart,hdmatx,hdma_usart1_tx); /* USART1 interrupt Init */ HAL_NVIC_SetPriority(USART1_IRQn, 0, 0); HAL_NVIC_EnableIRQ(USART1_IRQn); /* USER CODE BEGIN USART1_MspInit 1 */ /* USER CODE END USART1_MspInit 1 */ } } /** * @brief UART MSP De-Initialization * This function freeze the hardware resources used in this example * @param huart: UART handle pointer * @retval None */ void HAL_UART_MspDeInit(UART_HandleTypeDef* huart) { if(huart->Instance==USART1) { /* USER CODE BEGIN USART1_MspDeInit 0 */ /* USER CODE END USART1_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_USART1_CLK_DISABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_9|GPIO_PIN_10); /* USART1 DMA DeInit */ HAL_DMA_DeInit(huart->hdmarx); HAL_DMA_DeInit(huart->hdmatx); /* USART1 interrupt DeInit */ HAL_NVIC_DisableIRQ(USART1_IRQn); /* USER CODE BEGIN USART1_MspDeInit 1 */ /* USER CODE END USART1_MspDeInit 1 */ } } /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
728200.c
/* ** $Id: lstate.c 23036 2006-09-25 07:35:34Z gmaynard $ ** Global State ** See Copyright Notice in lua.h */ #include <stddef.h> #define lstate_c #define LUA_CORE #include "lua.h" #include "ldebug.h" #include "ldo.h" #include "lfunc.h" #include "lgc.h" #include "llex.h" #include "lmem.h" #include "lstate.h" #include "lstring.h" #include "ltable.h" #include "ltm.h" #define state_size(x) (sizeof(x) + LUAI_EXTRASPACE) #define fromstate(l) (cast(lu_byte *, (l)) - LUAI_EXTRASPACE) #define tostate(l) (cast(lua_State *, cast(lu_byte *, l) + LUAI_EXTRASPACE)) /* ** Main thread combines a thread state and the global state */ typedef struct LG { lua_State l; global_State g; } LG; static void stack_init (lua_State *L1, lua_State *L) { /* initialize CallInfo array */ L1->base_ci = luaM_newvector(L, BASIC_CI_SIZE, CallInfo); L1->ci = L1->base_ci; L1->size_ci = BASIC_CI_SIZE; L1->end_ci = L1->base_ci + L1->size_ci - 1; /* initialize stack array */ L1->stack = luaM_newvector(L, BASIC_STACK_SIZE + EXTRA_STACK, TValue); L1->stacksize = BASIC_STACK_SIZE + EXTRA_STACK; L1->top = L1->stack; L1->stack_last = L1->stack+(L1->stacksize - EXTRA_STACK)-1; /* initialize first ci */ L1->ci->func = L1->top; setnilvalue(L1->top++); /* `function' entry for this `ci' */ L1->base = L1->ci->base = L1->top; L1->ci->top = L1->top + LUA_MINSTACK; } static void freestack (lua_State *L, lua_State *L1) { luaM_freearray(L, L1->base_ci, L1->size_ci, CallInfo); luaM_freearray(L, L1->stack, L1->stacksize, TValue); } /* ** open parts that may cause memory-allocation errors */ static void f_luaopen (lua_State *L, void *ud) { global_State *g = G(L); UNUSED(ud); stack_init(L, L); /* init stack */ sethvalue(L, gt(L), luaH_new(L, 0, 2)); /* table of globals */ sethvalue(L, registry(L), luaH_new(L, 0, 2)); /* registry */ luaS_resize(L, MINSTRTABSIZE); /* initial size of string table */ luaT_init(L); luaX_init(L); luaS_fix(luaS_newliteral(L, MEMERRMSG)); g->GCthreshold = 4*g->totalbytes; } static void preinit_state (lua_State *L, global_State *g) { G(L) = g; L->stack = NULL; L->stacksize = 0; L->errorJmp = NULL; L->hook = NULL; L->hookmask = 0; L->basehookcount = 0; L->allowhook = 1; resethookcount(L); L->openupval = NULL; L->size_ci = 0; L->nCcalls = 0; L->status = 0; L->base_ci = L->ci = NULL; L->savedpc = NULL; L->errfunc = 0; setnilvalue(gt(L)); } static void close_state (lua_State *L) { global_State *g = G(L); luaF_close(L, L->stack); /* close all upvalues for this thread */ luaC_freeall(L); /* collect all objects */ lua_assert(g->rootgc == obj2gco(L)); lua_assert(g->strt.nuse == 0); luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size, TString *); luaZ_freebuffer(L, &g->buff); freestack(L, L); lua_assert(g->totalbytes == sizeof(LG)); (*g->frealloc)(g->ud, fromstate(L), state_size(LG), 0); } lua_State *luaE_newthread (lua_State *L) { lua_State *L1 = tostate(luaM_malloc(L, state_size(lua_State))); luaC_link(L, obj2gco(L1), LUA_TTHREAD); preinit_state(L1, G(L)); stack_init(L1, L); /* init stack */ setobj2n(L, gt(L1), gt(L)); /* share table of globals */ L1->hookmask = L->hookmask; L1->basehookcount = L->basehookcount; L1->hook = L->hook; resethookcount(L1); lua_assert(iswhite(obj2gco(L1))); return L1; } void luaE_freethread (lua_State *L, lua_State *L1) { luaF_close(L1, L1->stack); /* close all upvalues for this thread */ lua_assert(L1->openupval == NULL); luai_userstatefree(L1); freestack(L, L1); luaM_freemem(L, fromstate(L1), state_size(lua_State)); } LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { int i; lua_State *L; global_State *g; void *l = (*f)(ud, NULL, 0, state_size(LG)); if (l == NULL) return NULL; L = tostate(l); g = &((LG *)L)->g; L->next = NULL; L->tt = LUA_TTHREAD; g->currentwhite = bit2mask(WHITE0BIT, FIXEDBIT); L->marked = luaC_white(g); set2bits(L->marked, FIXEDBIT, SFIXEDBIT); preinit_state(L, g); g->frealloc = f; g->ud = ud; g->mainthread = L; g->uvhead.u.l.prev = &g->uvhead; g->uvhead.u.l.next = &g->uvhead; g->GCthreshold = 0; /* mark it as unfinished state */ g->strt.size = 0; g->strt.nuse = 0; g->strt.hash = NULL; setnilvalue(registry(L)); luaZ_initbuffer(L, &g->buff); g->panic = NULL; g->gcstate = GCSpause; g->rootgc = obj2gco(L); g->sweepstrgc = 0; g->sweepgc = &g->rootgc; g->gray = NULL; g->grayagain = NULL; g->weak = NULL; g->tmudata = NULL; g->totalbytes = sizeof(LG); g->gcpause = LUAI_GCPAUSE; g->gcstepmul = LUAI_GCMUL; g->gcdept = 0; for (i=0; i<NUM_TAGS; i++) g->mt[i] = NULL; if (luaD_rawrunprotected(L, f_luaopen, NULL) != 0) { /* memory allocation error: free partial state */ close_state(L); L = NULL; } else luai_userstateopen(L); return L; } static void callallgcTM (lua_State *L, void *ud) { UNUSED(ud); luaC_callGCTM(L); /* call GC metamethods for all udata */ } LUA_API void lua_close (lua_State *L) { L = G(L)->mainthread; /* only the main thread can be closed */ lua_lock(L); luaF_close(L, L->stack); /* close all upvalues for this thread */ luaC_separateudata(L, 1); /* separate udata that have GC metamethods */ L->errfunc = 0; /* no error function during GC metamethods */ do { /* repeat until no more errors */ L->ci = L->base_ci; L->base = L->top = L->ci->base; L->nCcalls = 0; } while (luaD_rawrunprotected(L, callallgcTM, NULL) != 0); lua_assert(G(L)->tmudata == NULL); luai_userstateclose(L); close_state(L); }
286197.c
#include <stdio.h> #include <stdlib.h> #include <limits.h> typedef int elem_type; typedef struct heap { int capacity; int size; elem_type *elements; } * priority_queue; //优先级队列 priority_queue init(int max_elements) { priority_queue queue; queue = (priority_queue)malloc(sizeof(struct heap)); if (!queue) { printf("Out of space\n"); return NULL; } queue->elements = (elem_type *)malloc(sizeof(elem_type) * max_elements); if (!queue->elements) { printf("Out of space\n"); return NULL; } queue->capacity = max_elements; queue->size = 0; //queue is empty } void insert(elem_type x, priority_queue queue) { int i; queue->elements[0] = x; //tag if (queue->capacity == queue->size) { printf("Priority queue is full\n"); return; } for (i = ++queue->size; queue->elements[i / 2] > x; i /= 2) //向上调整 queue->elements[i] = queue->elements[i / 2]; queue->elements[i] = x; } elem_type delete_min(priority_queue queue) { int i, child; if (queue->size == 0) { printf("Priority is empty\n"); exit(0); } queue->elements[0] = queue->elements[1]; elem_type last_elem = queue->elements[queue->size--]; for (i = 1; 2 * i <= queue->size; i = child) { child = 2 * i; //当前结点的左孩子 /*找到结点i的最小孩子结点*/ if (child != queue->size && queue->elements[child + 1] < queue->elements[child]) child++; if (last_elem > queue->elements[child]) queue->elements[i] = queue->elements[child]; else break; } queue->elements[i] = last_elem; return queue->elements[0]; } void up(priority_queue queue, int curr_pos) { if (curr_pos < 0 || curr_pos > queue->size) return; int i; queue->elements[0] = queue->elements[curr_pos]; //tag for (i = curr_pos; queue->elements[i / 2] > queue->elements[0]; i /= 2) queue->elements[i] = queue->elements[i / 2]; queue->elements[i] = queue->elements[0]; } void down(priority_queue queue, int curr_pos) { if (curr_pos < 0 || curr_pos > queue->size) return; queue->elements[0] = queue->elements[curr_pos]; int i, child; for (i = curr_pos; i * 2 <= queue->size; i = child) { child = i * 2; if (child != queue->size && queue->elements[child + 1] < queue->elements[child]) child++; if (queue->elements[0] < queue->elements[child]) return; else queue->elements[i] = queue->elements[child]; } queue->elements[i] = queue->elements[0]; } void decrease_key(int pos, unsigned int delta, priority_queue queue) { if (pos < 1 || pos > queue->size) return; queue->elements[pos] -= delta; up(queue, pos); } void increase_key(int pos, unsigned int delta, priority_queue queue) { if (pos < 1 || pos > queue->size) return; queue->elements[pos] += delta; down(queue, pos); } elem_type delete_key(int pos, priority_queue queue) { elem_type tmp = queue->elements[pos]; decrease_key(pos, INT_MAX, queue); delete_min(queue); return tmp; } priority_queue buid_heap(elem_type *list, int size, int max_elements) { priority_queue queue; int i; queue = init(max_elements); for (i = 0; i < size; i++) insert(list[i], queue); return queue; } void print_heap(priority_queue queue) { for (int i = 1; i <= queue->size; i++) printf("%d ", queue->elements[i]); printf("\n"); } int main() { elem_type list[15] = {150, 80, 40, 30, 10, 70, 110, 100, 20, 90, 60, 50, 120, 140, 130}; priority_queue test_queue = buid_heap(list, 15, 16); insert(55, test_queue); delete_key(1, test_queue); print_heap(test_queue); delete_min(test_queue); print_heap(test_queue); }
267759.c
#include <stdint.h> #include <stdio.h> #include <string.h> #include <sys/time.h> #include <time.h> #include "alertsDeleteAlertDirective.pb.h" #include "alertsSetAlertDirective.pb.h" #include "alexa.h" #include "alexaDiscoveryDiscoverDirective.pb.h" #include "alexaDiscoveryDiscoverResponseEvent.pb.h" #include "alexaGadgetSpeechDataSpeechmarksDirective.pb.h" #include "alexaGadgetStateListenerStateUpdateDirective.pb.h" #include "btstack_debug.h" #include "directiveParser.pb.h" #include "esp_heap_caps.h" #include "esp_log.h" #include "esp_system.h" #include "eventParser.pb.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "notificationsSetIndicatorDirective.pb.h" #include "output.h" #include "pb.h" #include "pb_decode.h" #include "pb_encode.h" #include "freertos/queue.h" static const char* TAG = "alexa.c"; uint8_t out_buffer[1000]; uint16_t out_buffer_len; static time_t timer; static char timer_token[100]; extern xQueueHandle timer_queue; void create_discovery_response() { ESP_LOGI(TAG, "Creating discover response event"); pb_ostream_t stream = pb_ostream_from_buffer(out_buffer, sizeof(out_buffer)); static alexaDiscovery_DiscoverResponseEventProto env = alexaDiscovery_DiscoverResponseEventProto_init_zero; strcpy(env.event.header.namespace, "Alexa.Discovery"); strcpy(env.event.header.name, "Discover.Response"); env.event.payload.endpoints_count = 1; strcpy(env.event.payload.endpoints[0].endpointId, "ledot00003"); strcpy(env.event.payload.endpoints[0].friendlyName, "ledot 03"); strcpy(env.event.payload.endpoints[0].description, "da ledot"); strcpy(env.event.payload.endpoints[0].manufacturerName, "Jesse Schoch"); env.event.payload.endpoints[0].capabilities_count = 2; strcpy(env.event.payload.endpoints[0].capabilities[0].type, "AlexaInterface"); strcpy(env.event.payload.endpoints[0].capabilities[0].interface, "Alerts"); strcpy(env.event.payload.endpoints[0].capabilities[0].version, "1.1"); strcpy(env.event.payload.endpoints[0].capabilities[1].type, "AlexaInterface"); strcpy(env.event.payload.endpoints[0].capabilities[1].interface, "Alexa.Gadget.StateListener"); strcpy(env.event.payload.endpoints[0].capabilities[1].version, "1.0"); env.event.payload.endpoints[0] .capabilities[1] .configuration.supportedTypes_count = 3; strcpy(env.event.payload.endpoints[0] .capabilities[1] .configuration.supportedTypes[0] .name, "timers"); strcpy(env.event.payload.endpoints[0] .capabilities[1] .configuration.supportedTypes[1] .name, "timeinfo"); strcpy(env.event.payload.endpoints[0] .capabilities[1] .configuration.supportedTypes[2] .name, "wakeword"); strcpy( env.event.payload.endpoints[0].additionalIdentification.firmwareVersion, "0"); strcpy(env.event.payload.endpoints[0].additionalIdentification.deviceToken, "b'a6f589a5a8f11dff86d88f6ac16f9161fa3a7b02fe61f947d8b1170c7ccde0d6'"); strcpy(env.event.payload.endpoints[0] .additionalIdentification.deviceTokenEncryptionType, "1"); strcpy( env.event.payload.endpoints[0].additionalIdentification.amazonDeviceType, "A3OPCPURPKGDTE"); strcpy(env.event.payload.endpoints[0].additionalIdentification.modelName, "ledot 03"); strcpy(env.event.payload.endpoints[0].additionalIdentification.radioAddress, //"3C71BF9ABE66"); // a4:cf:12:6c:2d:a4 "A4CF126C2DA6"); bool status = pb_encode( &stream, alexaDiscovery_DiscoverResponseEventProto_fields, &env); if (!status) { ESP_LOGE(TAG, "Error encoding message: %s", PB_GET_ERROR(&stream)); return; } out_buffer_len = stream.bytes_written; send_data_callback(out_buffer, out_buffer_len); memset(out_buffer, 0, sizeof(out_buffer)); out_buffer_len = 0; } void handle_discovery_request(pb_istream_t stream) { static alexaDiscovery_DiscoverDirectiveProto envelope = alexaDiscovery_DiscoverDirectiveProto_init_default; pb_decode(&stream, alexaDiscovery_DiscoverDirectiveProto_fields, &envelope); printf("scope type: %s\n", envelope.directive.payload.scope.type); printf("scope token: %s\n", envelope.directive.payload.scope.token); create_discovery_response(); } void handle_time_info(char* current_time) { static struct tm tm; strptime(current_time, "%Y-%m-%dT%H:%M:%S", &tm); time_t t = mktime(&tm); struct timeval now = {.tv_sec = t}; settimeofday(&now, NULL); ESP_LOGI(TAG, "time info: %d %d %d %d %d %d, %ld", tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, t); } int active = 0; void set_timer(char* token, char* scheduled_time) { static struct tm tm; strptime(scheduled_time, "%Y-%m-%dT%H:%M:%S", &tm); timer = mktime(&tm); int active = 1; memset(timer_token, 0, sizeof(timer_token)); strcpy(timer_token, token); ESP_LOGI(TAG, "timer: %s %d %d %d %d %d %d", token, tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); xQueueSendToBack(timer_queue, &active, 1000); } void cancel_timer() { ESP_LOGI(TAG, "Cancelling timer"); memset(timer_token, 0, sizeof(timer_token)); timer = 0; active = 0; xQueueSendToBack(timer_queue, &active, 1000); } void handle_set_alert(pb_istream_t stream) { static alerts_SetAlertDirectiveProto envelope = alerts_SetAlertDirectiveProto_init_default; pb_decode(&stream, alerts_SetAlertDirectiveProto_fields, &envelope); printf("alert type: %s\n", envelope.directive.payload.type); printf("alert token: %s\n", envelope.directive.payload.token); printf("alert scheduled time: %s\n", envelope.directive.payload.scheduledTime); if (0 == strcmp(envelope.directive.payload.type, "TIMER")) { set_timer(envelope.directive.payload.token, envelope.directive.payload.scheduledTime); } } void handle_delete_alert(pb_istream_t stream) { static alerts_DeleteAlertDirectiveProto envelope = alerts_DeleteAlertDirectiveProto_init_default; pb_decode(&stream, alerts_SetAlertDirectiveProto_fields, &envelope); printf("alert token: %s\n", envelope.directive.payload.token); if (0 == strcmp(timer_token, envelope.directive.payload.token)) { cancel_timer(); } } void handle_alexa_payload(uint8_t* buffer, uint16_t len) { ESP_LOGI(TAG, "Parsing Directive"); static directive_DirectiveParserProto envelope = directive_DirectiveParserProto_init_default; pb_istream_t stream = pb_istream_from_buffer(buffer, len); pb_decode(&stream, directive_DirectiveParserProto_fields, &envelope); stream = pb_istream_from_buffer(buffer, len); ESP_LOGI(TAG, "name = %s, namespace=%s", envelope.directive.header.name, envelope.directive.header.namespace); char* name = envelope.directive.header.name; char* namespace = envelope.directive.header.namespace; if (0 == strcmp(name, "SetIndicator") && (0 == strcmp(namespace, "Notifications"))) { // Parse the notification payload now static notifications_SetIndicatorDirectiveProto notifications_envelope = notifications_SetIndicatorDirectiveProto_init_default; pb_decode(&stream, notifications_SetIndicatorDirectiveProto_fields, &notifications_envelope); printf("visualIndicator:%d, audioIndicator=%d, assetId=%s, url=%s\n", notifications_envelope.directive.payload.persistVisualIndicator, notifications_envelope.directive.payload.playAudioIndicator, notifications_envelope.directive.payload.asset.assetId, notifications_envelope.directive.payload.asset.url); } else if (0 == strcmp(name, "Discover") && (0 == strcmp(namespace, "Alexa.Discovery"))) { handle_discovery_request(stream); } else if (0 == strcmp(name, "SetAlert") && 0 == strcmp(namespace, "Alerts")) { handle_set_alert(stream); } else if (0 == strcmp(name, "DeleteAlert") && 0 == strcmp(namespace, "Alerts")) { handle_delete_alert(stream); } else if (0 == strcmp(name, "StateUpdate") && (0 == strcmp(namespace, "Alexa.Gadget.StateListener"))) { static alexaGadgetStateListener_StateUpdateDirectiveProto envelope = alexaGadgetStateListener_StateUpdateDirectiveProto_init_default; pb_decode(&stream, alexaGadgetStateListener_StateUpdateDirectiveProto_fields, &envelope); int states_count = envelope.directive.payload.states_count; for (int i = 0; i < states_count; ++i) { char* name = envelope.directive.payload.states[i].name; char* value = envelope.directive.payload.states[i].value; printf("state name: %s\n", name); printf("state value: %s\n", value); if (0 == strcmp(name, "timeinfo")) { handle_time_info(value); } } } else if (0 == strcmp(name, "Speechmarks") && (0 == strcmp(namespace, "Alexa.Gadget.SpeechData"))) { static alexaGadgetSpeechData_SpeechmarksDirectiveProto envelope = alexaGadgetSpeechData_SpeechmarksDirectiveProto_init_default; pb_decode(&stream, alexaGadgetSpeechData_SpeechmarksDirectiveProto_fields, &envelope); int speechmarks_count = envelope.directive.payload.speechmarksData_count; printf("player offset: %d\n", envelope.directive.payload.playerOffsetInMilliSeconds); for (int i = 0; i < speechmarks_count; ++i) { printf("speechmark type: %s\n", envelope.directive.payload.speechmarksData[i].type); printf("speechmark value: %s\n", envelope.directive.payload.speechmarksData[i].value); printf("speechmark start offset: %d\n", envelope.directive.payload.speechmarksData[i] .startOffsetInMilliSeconds); } } else { ESP_LOGE(TAG, "Error: unknown directive. Name: %s, namespace: %s", name, namespace); } } void register_send_data_callback(send_data_callback_t callback) { send_data_callback = callback; }
568052.c
#include "math.h" inline uint32_t min(uint32_t l, uint32_t r) { return l < r ? l : r; } inline uint32_t max(uint32_t l, uint32_t r) { return l > r ? l : r; }
38764.c
/* * Miscellaneous functions for RPC service startup and shutdown. * * This code is partially snarfed from rpcgen -s tcp -s udp, * partly written by Mark Shand, Donald Becker, and Rick * Sladkey. It was tweaked slightly by Olaf Kirch to be * usable by both unfsd and mountd. * * This software may be used for any purpose provided * the above copyright notice is retained. It is supplied * as is, with no warranty expressed or implied. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <sys/types.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <sys/socket.h> #include <rpc/rpc.h> #include <rpc/pmap_clnt.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <fcntl.h> #include <memory.h> #include <errno.h> #include <unistd.h> #include <time.h> #include "nfslib.h" #if SIZEOF_SOCKLEN_T - 0 == 0 #define socklen_t int #endif #define _RPCSVC_CLOSEDOWN 120 int _rpcpmstart = 0; int _rpcfdtype = 0; int _rpcsvcdirty = 0; static void closedown(int sig) { (void) signal(sig, closedown); if (_rpcsvcdirty == 0) { static int size; int i, openfd; if (_rpcfdtype == SOCK_DGRAM) exit(0); if (size == 0) size = getdtablesize(); for (i = 0, openfd = 0; i < size && openfd < 2; i++) if (FD_ISSET(i, &svc_fdset)) openfd++; if (openfd <= 1) exit(0); } (void) alarm(_RPCSVC_CLOSEDOWN); } /* * Create listener socket for a given port * * Return an open network socket on success; otherwise return -1 * if some error occurs. */ static int makesock(int port, int proto) { struct sockaddr_in sin; int sock, sock_type, val; sock_type = (proto == IPPROTO_UDP) ? SOCK_DGRAM : SOCK_STREAM; sock = socket(AF_INET, sock_type, proto); if (sock < 0) { xlog(L_FATAL, "Could not make a socket: %s", strerror(errno)); return -1; } memset((char *) &sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = htonl(INADDR_ANY); sin.sin_port = htons(port); val = 1; if (proto == IPPROTO_TCP) if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0) xlog(L_ERROR, "setsockopt failed: %s", strerror(errno)); if (bind(sock, (struct sockaddr *) &sin, sizeof(sin)) == -1) { xlog(L_FATAL, "Could not bind name to socket: %s", strerror(errno)); return -1; } return sock; } void rpc_init(char *name, int prog, int vers, void (*dispatch)(struct svc_req *, register SVCXPRT *), int defport) { struct sockaddr_in saddr; SVCXPRT *transp; int sock; socklen_t asize; asize = sizeof(saddr); sock = 0; if (getsockname(0, (struct sockaddr *) &saddr, &asize) == 0 && saddr.sin_family == AF_INET) { socklen_t ssize = sizeof(int); int fdtype = 0; if (getsockopt(0, SOL_SOCKET, SO_TYPE, (char *)&fdtype, &ssize) == -1) xlog(L_FATAL, "getsockopt failed: %s", strerror(errno)); /* inetd passes a UDP socket or a listening TCP socket. * listen will fail on a connected TCP socket(passed by rsh). */ if (!(fdtype == SOCK_STREAM && listen(0,5) == -1)) { _rpcfdtype = fdtype; _rpcpmstart = 1; } } if (!_rpcpmstart) { pmap_unset(prog, vers); sock = RPC_ANYSOCK; } if ((_rpcfdtype == 0) || (_rpcfdtype == SOCK_DGRAM)) { static SVCXPRT *last_transp = NULL; if (_rpcpmstart == 0) { if (last_transp && (!defport || defport == last_transp->xp_port)) { transp = last_transp; goto udp_transport; } if (defport == 0) sock = RPC_ANYSOCK; else sock = makesock(defport, IPPROTO_UDP); } if (sock == RPC_ANYSOCK) sock = svcudp_socket (prog, 1); transp = svcudp_create(sock); if (transp == NULL) { xlog(L_FATAL, "cannot create udp service."); } udp_transport: if (!svc_register(transp, prog, vers, dispatch, IPPROTO_UDP)) { xlog(L_FATAL, "unable to register (%s, %d, udp).", name, vers); } last_transp = transp; } if ((_rpcfdtype == 0) || (_rpcfdtype == SOCK_STREAM)) { static SVCXPRT *last_transp = NULL; if (_rpcpmstart == 0) { if (last_transp && (!defport || defport == last_transp->xp_port)) { transp = last_transp; goto tcp_transport; } if (defport == 0) sock = RPC_ANYSOCK; else sock = makesock(defport, IPPROTO_TCP); } if (sock == RPC_ANYSOCK) sock = svctcp_socket (prog, 1); transp = svctcp_create(sock, 0, 0); if (transp == NULL) { xlog(L_FATAL, "cannot create tcp service."); } tcp_transport: if (!svc_register(transp, prog, vers, dispatch, IPPROTO_TCP)) { xlog(L_FATAL, "unable to register (%s, %d, tcp).", name, vers); } last_transp = transp; } if (_rpcpmstart) { signal(SIGALRM, closedown); alarm(_RPCSVC_CLOSEDOWN); } }
461027.c
/* * sipcalc, sub-func.c * * $Id: sub-func.c,v 1.28 2003/03/19 12:28:15 simius Exp $ * * - * Copyright (c) 2003 Simon Ekstrand * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ static const char rcsid[] = "$Id: sub-func.c,v 1.28 2003/03/19 12:28:15 simius Exp $"; //#ifdef HAVE_CONFIG_H //#include <config.h> //#endif //#ifdef HAVE_NETDB_H #include <netdb.h> //#endif #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include "sub.h" #include "sub-o.h" int count(char *buf, char ch) { int x, y; y = 0; for (x = 0; x < strlen(buf); x++) if (buf[x] == ch) y++; return y; } /* * 0 error * 1 normal */ int validate_v4addr(char *addr) { int x, y, z, m; char buf[16]; if (strlen(addr) < 7 || strlen(addr) > 15) return 0; x = 0; y = 0; while (x < strlen(addr)) { if (addr[x] == '.') y++; x++; } if (y != 3) return 0; x = 0; y = 0; while (x < strlen(addr)) { z = 0; y = 0; while (z < strlen(V4ADDR_VAL) && !y) { if (addr[x] == V4ADDR_VAL[z]) y = 1; z++; } if (!y) return 0; x++; } if (addr[0] == '.' || addr[strlen(addr) - 1] == '.') return 0; x = 0; while (x < (strlen(addr) - 1)) { if (addr[x] == '.' && addr[x + 1] == '.') return 0; x++; } y = 0; for (x = 0; x < 4; x++) { z = 0; safe_bzero(buf); while (y < strlen(addr) && addr[y] != '.') { buf[z] = addr[y]; y++; z++; } if (z > 3) return 0; m = atoi(buf); if (m < 0 || m > 255) return 0; y++; }; return 1; } /* * 0 error * 1 normal * 2 /x * 3 hex */ int validate_netmask(char *in_addr) { int x, y, z, m; char addr[16]; char *sl; u_int32_t sm; if (strlen(in_addr) > 18) return 0; x = 0; y = 0; z = 0; while (x < strlen(in_addr) && !y) { if (!isxdigit(in_addr[x]) && in_addr[x] != 'x' && in_addr[x] != 'X') y = 1; if (in_addr[x] == 'x' || in_addr[x] == 'X') { z++; y = 0; } x++; } x = 0; if (!y && z == 1) { x = 0; if (in_addr[0] == 'x' || in_addr[0] == 'X') x = 1; if (!x) { if (in_addr[0] == '0' && (in_addr[1] == 'x' || in_addr[1] == 'X')) x = 1; } } if (x == 1) return 3; safe_bzero(addr); if (strstr(in_addr, "/")) { x = 0; while (x < 15 && in_addr[x] != '/') { addr[x] = in_addr[x]; x++; } } else { safe_strncpy(addr, in_addr); } /* * This also calls validate_v4addr. */ if (quadtonum(addr, &sm)) return 0; if (!(sl = strstr(in_addr, "/"))) { y = 0; for (x = 0; x < 32; x++) { if (!y && !((sm >> (31 - x)) & 1)) y = 1; if (y == 1 && ((sm >> (31 - x)) & 1)) y = 2; } if (y == 2) return -1; /* * valid */ return 1; } sl++; if (strlen(sl) < 1 || strlen(sl) > 2) return 0; if (sl[0] == '.' || sl[1] == '.') return 0; x = 0; y = 0; while (x < strlen(sl)) { z = 0; y = 0; while (z < strlen(V4ADDR_VAL) && !y) { if (sl[x] == V4ADDR_VAL[z]) y = 1; z++; } if (!y) return 0; x++; } m = atoi(sl); if (m < 0 || m > 32) return 0; return 2; } int getsplitnumv4(char *buf, u_int32_t *splitmask) { int x, y; u_int32_t sm; if (strlen(buf) < 1) return -1; if (strlen(buf) < 4) { if (buf[0] == '/') buf++; y = atoi(buf); if (y < 1 || y > 32) return -1; sm = 0; for (x = 0; x < y; x++) sm = sm | (1 << (31 - x)); } else { if (!strstr(buf, ".")) sm = strtoul(buf, (char **)NULL, 16); else { if (quadtonum(buf, &sm)) return -1; } } y = 0; for (x = 0; x < 32; x++) { if (!y && !((sm >> (31 - x)) & 1)) y = 1; if (y == 1 && ((sm >> (31 - x)) & 1)) y = 2; } if (y == 2) return -1; *splitmask = sm; return 0; } int getsplitnumv6(char *buf, struct sip_in6_addr *splitmask, int *v6splitnum) { int x, y; if (strlen(buf) < 1) return -1; if (strlen(buf) > 4) return -1; if (buf[0] == '/') buf++; y = atoi(buf); if (y < 1 || y > 128) return -1; *v6splitnum = y; x = v6masktonum(buf, &y, splitmask); return 0; } int quadtonum(char *quad, u_int32_t *num) { char buf[128]; int x, y, z; if (!validate_v4addr(quad)) return -1; safe_bzero(buf); x = 0; while (quad[x] != '.') { buf[x] = quad[x]; x++; } *num = 0; x++; for (y = 0; y < 4; y++) { z = atoi(buf); if (z > 255 || z < 0) return -1; *num = *num | (z << (8 * (3 - y))); safe_bzero(buf); z = 0; while (quad[x] != '.' && quad[x] != '\0' && x < strlen(quad)) { buf[z] = quad[x]; x++; z++; } x++; } return 0; } char * numtoquad(u_int32_t num) { int a[4], x; static char quad[17]; for (x = 0; x < 4; x++) a[x] = num >> (8 * (3 - x)) & 0xff; safe_bzero(quad); safe_snprintf(quad, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]); return quad; } char * numtobitmap(u_int32_t num) { static char bitmap[36]; int x, y, z; safe_bzero(bitmap); y = 1; z = 0; for (x = 0; x < 32; x++) { if (!((num >> (31 - x)) & 1)) bitmap[z] = '0'; else bitmap[z] = '1'; if (y == 8 && z < 34) { z++; bitmap[z] = '.'; y = 0; } y++; z++; } return bitmap; } int parse_addr(struct if_info *ifi) { char buf[128], buf2[128]; char *s_find; int x, y, z; safe_bzero(buf); safe_bzero(buf2); ifi->v4ad.n_nmaskbits = 0; /* * netmask */ if (ifi->p_v4nmask[0] == '\0') { /* * "/netmask" */ if (!(s_find = strstr(ifi->p_v4addr, "/"))) { ifi->v4ad.n_nmask = 0xffffffff; ifi->v4ad.n_nmaskbits = 32; } else { *s_find = '\0'; s_find++; if (!*s_find) return -1; if (strlen(s_find) > 2) return -2; x = 0; y = 0; while (x < strlen(s_find)) { y = 0; z = 0; while (z < strlen(NETMASK_VAL) && !y) { if (s_find[x] == NETMASK_VAL[z]) y = 1; z++; } if (!y) return -2; x++; } buf[0] = *s_find; *s_find = '\0'; s_find++; if (*s_find) { buf[1] = *s_find; *s_find = '\0'; } ifi->v4ad.n_nmaskbits = atoi(buf); ifi->v4ad.n_nmask = 0; for (x = 0; x < ifi->v4ad.n_nmaskbits; x++) ifi->v4ad.n_nmask = ifi->v4ad.n_nmask | (1 << (31 - x)); } } else { /* * hex netmask */ if (!strstr(ifi->p_v4nmask, ".")) ifi->v4ad.n_nmask = strtoul(ifi->p_v4nmask, (char **)NULL, 16); /* * "normal" netmask */ else { if (quadtonum(ifi->p_v4nmask, &ifi->v4ad.n_nmask)) return -2; } } if (ifi->v4ad.n_nmaskbits < 0 || ifi->v4ad.n_nmaskbits > 32) return -2; /* * host address */ if (quadtonum(ifi->p_v4addr, &ifi->v4ad.n_haddr)) return -1; return 0; } /* * return * 0 ok * -1 invalid address * -2 invalid netmask */ int get_addrv4(struct if_info *ifi) { int x, y; x = 0; if (!ifi->name[0]) x = parse_addr(ifi); if (x) return x; /* * count netmask bits */ ifi->v4ad.n_nmaskbits = 0; for (x = 0; x < 32; x++) { if ((ifi->v4ad.n_nmask >> x) & 1) ifi->v4ad.n_nmaskbits++; } if (ifi->v4ad.n_nmaskbits < 0 || ifi->v4ad.n_nmaskbits > 32) return -2; /* * validate netmask */ y = 0; for (x = 0; x < 32; x++) { if (!y && !((ifi->v4ad.n_nmask >> (31 - x)) & 1)) y = 1; if (y == 1 && ((ifi->v4ad.n_nmask >> (31 - x)) & 1)) y = 2; } if (y == 2) return -2; /* * network class, class remark and classful netmask */ safe_bzero(ifi->v4ad.class_remark); x = ifi->v4ad.n_haddr >> 24; ifi->v4ad.n_cnaddr = 0; if (!(x & 0x80)) { ifi->v4ad.class = 'A'; ifi->v4ad.n_cnmask = 0xff000000; } if ((x & 0xc0) == 0x80) { ifi->v4ad.class = 'B'; ifi->v4ad.n_cnmask = 0xffff0000; } if ((x & 0xe0) == 0xc0) { ifi->v4ad.class = 'C'; ifi->v4ad.n_cnmask = 0xffffff00; } if ((x & 0xf0) == 0xe0) { ifi->v4ad.class = 'D'; safe_snprintf(ifi->v4ad.class_remark, " (multicast network)"); ifi->v4ad.n_cnmask = ifi->v4ad.n_nmask; } if ((x & 0xf8) == 0xf0) { ifi->v4ad.class = 'E'; safe_snprintf(ifi->v4ad.class_remark, " (reserved for future use)"); ifi->v4ad.n_cnmask = ifi->v4ad.n_nmask; } if (ifi->v4ad.class == '\0') { ifi->v4ad.n_cnmask = ifi->v4ad.n_nmask; safe_snprintf(ifi->v4ad.class_remark, "Nonexistant"); } /* * network address (classful + cidr) */ ifi->v4ad.n_naddr = ifi->v4ad.n_haddr & ifi->v4ad.n_nmask; ifi->v4ad.n_cnaddr = ifi->v4ad.n_haddr & ifi->v4ad.n_cnmask; /* * cidr broadcast address */ ifi->v4ad.n_broadcast = 0xffffffff - ifi->v4ad.n_nmask + ifi->v4ad.n_naddr; return 0; } /* * return * 0 ok * -1 invalid address * -2 invalid netmask */ int get_addrv6(struct if_info *ifi) { int x; x = mk_ipv6addr(&ifi->v6ad, ifi->p_v6addr); if (x < 0) return -1; return 0; } int split_ipv6addr(char *addr, struct ipv6_split *spstr) { char *split; int x, y, z; split = strstr(addr, "/"); if (split && (count(addr, '/') == 1)) { if (strlen(split) > 1 && strlen(split) < 5) { split++; safe_strncpy(spstr->nmask, split); } } x = 0; y = 0; split = strstr(addr, "."); if (split) x = strlen(split); split = strstr(addr, ":"); if (split) y = strlen(split); if (x < y) x = 1; else x = 0; if (count(addr, '.') == 3 && x) { split = strstr(addr, "."); x = strlen(addr) - strlen(split); while (addr[x] != ':') x--; x++; split = strstr(addr, "/"); if (split) y = strlen(addr) - strlen(split); else y = strlen(addr); if ((y - x >= 7) && (y - x <= 15)) { for (z = 0; z < y - x; z++) spstr->ipv4addr[z] = addr[x + z]; } } x = strlen(addr) - (strlen(spstr->ipv4addr) + strlen(spstr->nmask)); if (strlen(spstr->nmask) > 0) x--; if (x > 1 && x < 40) strncpy(spstr->ipv6addr, addr, x); return 0; } int validate_s_v6addr(char *addr, int type) { int x, y, z; int numcolon; int compressed; if (strlen(addr) < 2) return -1; if (strlen(addr) > 39) return -1; x = 0; y = 0; while (x < strlen(addr)) { y = 0; z = 0; while (z < strlen(V6ADDR_VAL) && !y) { if (addr[x] == V6ADDR_VAL[z]) y = 1; z++; } if (!y) return -1; x++; } x = 0; y = 0; while (x < strlen(addr)) { if (addr[x] == ':') y++; else y = 0; if (y == 3) return -1; x++; } if (addr[0] == ':' && addr[1] != ':') return -1; if (type == V6TYPE_STANDARD && addr[strlen(addr) - 1] == ':' && addr[strlen(addr) - 2] != ':') return -1; numcolon = 0; for (x = 0; x < strlen(addr); x++) { if (addr[x] == ':') numcolon++; } compressed = 0; x = 0; while (x < strlen(addr) - 1) { if (addr[x] == ':' && addr[x + 1] == ':') compressed++; x++; } if (compressed > 1) return -1; if (!compressed && numcolon != 7 && type == V6TYPE_STANDARD) return -1; if (!compressed && numcolon != 6 && type == V6TYPE_V4INV6) return -1; if (compressed && type == V6TYPE_STANDARD) { if (numcolon > 7) return -1; } if (compressed && type == V6TYPE_V4INV6) { if (numcolon > 6) return -1; } y = 0; for (x = 0; x < strlen(addr); x++) { if (addr[x] != ':') y++; else y = 0; if (y > 4) break; } if (y > 4) return -1; return 0; } int getcolon(char *addr, int pos, int type) { int x, y; int compressed; int cstart, cend; int max; char str[5]; if (type == V6TYPE_STANDARD) max = 7; if (type == V6TYPE_V4INV6) max = 5; compressed = 0; x = 0; while (x < strlen(addr) - 1) { if (addr[x] == ':' && addr[x + 1] == ':') compressed++; x++; } if (compressed) { cstart = 0; x = 0; while (x < strlen(addr) - 1) { if (addr[x] == ':' && addr[x + 1] == ':') break; if (addr[x] == ':') cstart++; x++; } x += 2; cend = 0; while (x < strlen(addr)) { if (addr[x] == ':') cend++; x++; } if (addr[strlen(addr) - 1] == ':' && addr[strlen(addr) - 2] != ':') cend--; } if (!compressed) { x = 0; y = 0; while (x < pos) { if (addr[y] == ':') x++; y++; } safe_bzero(str); x = 0; while (y < strlen(addr) && addr[y] != ':') { str[x] = addr[y]; x++; y++; } } if (compressed) { safe_bzero(str); if (pos <= cstart) { x = 0; y = 0; while (x < pos) { if (addr[y] == ':') x++; y++; } x = 0; while (y < strlen(addr) && addr[y] != ':') { str[x] = addr[y]; x++; y++; } } if ((pos > cstart) && (pos < (max - cend))) { str[0] = '0'; } if (pos >= (max - cend)) { y = 0; while (y < strlen(addr) - 1) { if (addr[y] == ':' && addr[y + 1] == ':') break; y++; } y += 2; x = max - cend; while (x < pos) { if (addr[y] == ':') x++; y++; } safe_bzero(str); x = 0; while (y < strlen(addr) && addr[y] != ':') { str[x] = addr[y]; x++; y++; } } } if (str[0] == '\0') str[0] = '0'; x = strtol(str, (char **)NULL, 16); return x; } int v6addrtonum(struct ipv6_split spstr, struct v6addr *in6_addr, int type) { int colon; int x, y, z, n; char buf[128]; colon = 0; if (type == V6TYPE_STANDARD) colon = 8; if (type == V6TYPE_V4INV6) colon = 6; for (x = 0; x < 4; x++) { in6_addr->haddr.sip6_addr32[x] = 0; } for (x = 0; x < colon; x++) { y = getcolon(spstr.ipv6addr, x, type); in6_addr->haddr.sip6_addr16[x] = y; } if (type == V6TYPE_V4INV6) { safe_bzero(buf); x = 0; while (spstr.ipv4addr[x] != '.') { buf[x] = spstr.ipv4addr[x]; x++; } x++; for (y = 0; y < 4; y++) { if (y == 1) { in6_addr->haddr.sip6_addr16[6] = (n << 8) | atoi(buf); } if (y == 3) { in6_addr->haddr.sip6_addr16[7] = (n << 8) | atoi(buf); } n = atoi(buf); safe_bzero(buf); z = 0; while (spstr.ipv4addr[x] != '.' && spstr.ipv4addr[x] != '\0' && x < strlen(spstr.ipv4addr)) { buf[z] = spstr.ipv4addr[x]; x++; z++; } x++; } } return 0; } int v6masktonum(char *nmask, int *nmaskbits, struct sip_in6_addr *in6_addr) { int x, y, z; if (nmask[0] == '\0') *nmaskbits = 128; else *nmaskbits = atoi(nmask); for (x = 0; x < 4; x++) in6_addr->sip6_addr32[x] = 0; y = 0; z = 0; for (x = 0; x < *nmaskbits; x++) { in6_addr->sip6_addr16[y] = in6_addr->sip6_addr16[y] | (1 << (15 - z)); z++; if (z == 16) { z = 0; y++; } } return 0; } /* * 0 error * 1 normal */ int validate_v6addr(char *addr) { int x; struct ipv6_split spstr; safe_bzero(spstr.ipv6addr); safe_bzero(spstr.ipv4addr); safe_bzero(spstr.nmask); split_ipv6addr(addr, &spstr); if (!spstr.ipv6addr[0]) return 0; x = V6TYPE_STANDARD; if (spstr.ipv4addr[0]) x = V6TYPE_V4INV6; if (validate_s_v6addr(spstr.ipv6addr, x) < 0) { return 0; } if (spstr.ipv4addr[0]) { if (!validate_v4addr(spstr.ipv4addr)) { return 0; } } return 1; } int v6addrtoprefix(struct v6addr *in6_addr) { int x; for (x = 0; x < 8; x++) { in6_addr->prefix.sip6_addr16[x] = in6_addr->haddr.sip6_addr16[x] & in6_addr->nmask.sip6_addr16[x]; } return 0; } int v6addrtosuffix(struct v6addr *in6_addr) { int x; for (x = 0; x < 8; x++) { in6_addr->suffix.sip6_addr16[x] = in6_addr->haddr.sip6_addr16[x] & (in6_addr->nmask.sip6_addr16[x] ^ 0xffff); } return 0; } int v6addrtobroadcast(struct v6addr *in6_addr) { int x; for (x = 0; x < 8; x++) { in6_addr->broadcast.sip6_addr16[x] = 0xffff - in6_addr->nmask.sip6_addr16[x] + in6_addr->prefix.sip6_addr16[x]; } return 0; } void v6_type(struct v6addr *in6_addr) { uint16_t a; a = in6_addr->haddr.sip6_addr16[0]; if (a == 0) safe_snprintf(in6_addr->class_remark, "Reserved"); if (a == 2 || a == 3) safe_snprintf(in6_addr->class_remark, "Reserved for NSAP Allocation"); if (a == 4 || a == 5) safe_snprintf(in6_addr->class_remark, "Reserved for IPX Allocation"); if ((a & 0xe000) == 0x2000) safe_snprintf(in6_addr->class_remark, "Aggregatable Global Unicast Addresses"); if ((a | 0x00ff) == 0x00ff) safe_snprintf(in6_addr->class_remark, "Reserved"); if ((a & 0xff00) == 0xff00) safe_snprintf(in6_addr->class_remark, "Multicast Addresses"); if ((a & 0xff80) == 0xfe80) safe_snprintf(in6_addr->class_remark, "Link-Local Unicast Addresses"); if ((a & 0xffc0) == 0xfec0) safe_snprintf(in6_addr->class_remark, "Site-Local Unicast Addresses"); if (in6_addr->class_remark[0] == '\0') safe_snprintf(in6_addr->class_remark, "Unassigned"); return; } void v6_comment(struct v6addr *in6_addr) { int x, y; y = 0; for (x = 0; x < 8; x++) { if (in6_addr->haddr.sip6_addr16[x]) y = 1; } if (!y) safe_snprintf(in6_addr->comment, "Unspecified"); y = 0; for (x = 0; x < 7; x++) { if (in6_addr->haddr.sip6_addr16[x]) y = 1; } if (!y) if (in6_addr->haddr.sip6_addr16[7] == 1) safe_snprintf(in6_addr->comment, "Loopback"); return; } int v6verifyv4(struct sip_in6_addr addr) { int x, y; y = 0; for (x = 0; x < 5; x++) { if (addr.sip6_addr16[x]) y = 1; } if (!y) { if (!addr.sip6_addr16[5]) return 1; if (addr.sip6_addr16[5] == 0xffff) return 2; } return 0; } char * get_comp_v6(struct sip_in6_addr addr) { static char outad[44]; char tmpad[5]; int x, y, z; int start, num; safe_bzero(outad); start = -1; num = 0; y = 0; z = 0; for (x = 0; x < 8; x++) { if (addr.sip6_addr16[x] == 0) { if (y == -1) y = x; z++; } else { if (z > num && z > 1) { start = y; num = z; } y = -1; z = 0; } } if (z > num && z > 1) { start = y; num = z; } for (x = 0; x < 8; x++) { if (x == start) { if (!x) safe_strncat(outad, ":"); safe_strncat(outad, ":"); x += num - 1; } else { safe_bzero(tmpad); safe_snprintf(tmpad, "%x", addr.sip6_addr16[x]); safe_strncat(outad, tmpad); if (x != 7) safe_strncat(outad, ":"); } } return outad; } int mk_ipv6addr(struct v6addr *in6_addr, char *addr) { int x, y, z; struct ipv6_split spstr; safe_bzero(spstr.ipv6addr); safe_bzero(spstr.ipv4addr); safe_bzero(spstr.nmask); split_ipv6addr(addr, &spstr); if (!spstr.ipv6addr[0]) return -1; x = V6TYPE_STANDARD; if (spstr.ipv4addr[0]) x = V6TYPE_V4INV6; if (validate_s_v6addr(spstr.ipv6addr, x) < 0) { return -1; } if (spstr.ipv4addr[0]) { if (!validate_v4addr(spstr.ipv4addr)) { return -1; } } x = 0; y = 0; while (x < strlen(spstr.nmask)) { y = 0; z = 0; while (z < strlen(NETMASK_VAL) && !y) { if (spstr.nmask[x] == NETMASK_VAL[z]) y = 1; z++; } if (!y) { return -1; } x++; } x = atoi(spstr.nmask); if (x < 0 || x > 128) { return -1; } if (spstr.ipv4addr[0] == '\0') in6_addr->type = V6TYPE_STANDARD; else in6_addr->type = V6TYPE_V4INV6; v6addrtonum(spstr, in6_addr, in6_addr->type); v6masktonum(spstr.nmask, &in6_addr->nmaskbits, &in6_addr->nmask); v6addrtoprefix(in6_addr); v6addrtosuffix(in6_addr); v6addrtobroadcast(in6_addr); in6_addr->real_v4 = v6verifyv4(in6_addr->haddr); safe_bzero(in6_addr->class_remark); v6_type(in6_addr); safe_bzero(in6_addr->comment); v6_comment(in6_addr); return 0; } struct dnsresp * new_dnsresp(struct dnsresp *d_resp) { d_resp->next = (struct dnsresp *)malloc(sizeof(struct dnsresp)); d_resp = d_resp->next; d_resp->next = NULL; safe_bzero(d_resp->str); d_resp->type = 0; return d_resp; } void free_dnsresp(struct dnsresp *d_resp) { struct dnsresp *old; while (d_resp) { old = d_resp; d_resp = d_resp->next; free(old); } } #ifdef HAVE_GETHOSTBYNAME char * _resolv_v4_ghbn(char *raddr, struct dnsresp *d_resp, char *extra) { struct hostent *he; static char retaddr[1024]; int x; safe_bzero(retaddr); he = gethostbyname(raddr); if (!he) return NULL; if (he->h_addrtype == AF_INET) { safe_snprintf(retaddr, "%s%s", inet_ntoa(*(struct in_addr *)he->h_addr_list[0]), extra); x = 0; while (he->h_addr_list[x]) { safe_snprintf(d_resp->str, "%s%s", inet_ntoa(*(struct in_addr *)he->h_addr_list[x]), extra); d_resp->type = AF_INET; x++; if (he->h_addr_list[x]) d_resp = new_dnsresp(d_resp); } } if (retaddr[0] == '\0') return NULL; return retaddr; } #else char * _resolv_v4_ghbn(char *raddr, struct dnsresp *d_resp, char *extra) { return NULL; } #endif #if defined(HAVE_GETHOSTBYNAME2) && defined(HAVE_INET_NTOP) char * _resolv_v6_ghbn2(char *raddr, struct dnsresp *d_resp, char *extra) { struct hostent *he; static char retaddr[1024]; char ip6addr[128]; int x; safe_bzero(retaddr); he = gethostbyname2(raddr, AF_INET6); if (!he) return NULL; if (he->h_addrtype == AF_INET6) { safe_bzero(ip6addr); safe_snprintf(retaddr, "%s%s", inet_ntop(AF_INET6, he->h_addr_list[0], ip6addr, 128), extra); x = 0; while (he->h_addr_list[x]) { safe_snprintf(d_resp->str, "%s%s", inet_ntop(AF_INET6, he->h_addr_list[x], ip6addr, 128), extra); d_resp->type = AF_INET6; x++; if (he->h_addr_list[x]) d_resp = new_dnsresp(d_resp); } } if (retaddr[0] == '\0') return NULL; return retaddr; } #else char * _resolv_v6_ghbn2(char *raddr, struct dnsresp *d_resp, char *extra) { return NULL; } #endif #if defined(HAVE_GETADDRINFO) && defined(HAVE_INET_NTOP) char * _resolv_v6_gai(char *raddr, struct dnsresp *d_resp, char *extra) { int x; struct addrinfo hints; struct addrinfo *res, *res_orig; struct sockaddr_in6 *sin6; static char retaddr[1024]; char ip6addr[128]; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET6; hints.ai_socktype = 0; hints.ai_flags = AI_CANONNAME; hints.ai_protocol = IPPROTO_TCP; x = getaddrinfo(raddr, NULL, &hints, &res); if (x) return NULL; if (!res) return NULL; res_orig = res; while (res) { safe_bzero(ip6addr); if (res->ai_family == PF_INET6) { sin6 = (struct sockaddr_in6 *)res->ai_addr; safe_snprintf(retaddr, "%s%s", inet_ntop(AF_INET6, &sin6->sin6_addr, ip6addr, 128), extra); safe_snprintf(d_resp->str, "%s%s", inet_ntop(AF_INET6, &sin6->sin6_addr, ip6addr, 128), extra); d_resp->type = AF_INET6; } if (res->ai_next && (res->ai_family == PF_INET || res->ai_family == PF_INET6)) d_resp = new_dnsresp(d_resp); res = res->ai_next; } freeaddrinfo(res_orig); if (retaddr[0] == '\0') return NULL; return retaddr; } #else char * _resolv_v6_gai(char *raddr, struct dnsresp *d_resp, char *extra) { return NULL; } #endif #if defined(HAVE_GETADDRINFO) && defined(HAVE_INET_NTOP) char * _resolv_unspec_gai(char *raddr, struct dnsresp *d_resp, char *extra) { int x; struct addrinfo hints; struct addrinfo *res, *res_orig; struct sockaddr_in *sin; struct sockaddr_in6 *sin6; static char retaddr[1024]; char ip6addr[128]; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = 0; hints.ai_flags = AI_CANONNAME; hints.ai_protocol = IPPROTO_TCP; x = getaddrinfo(raddr, NULL, &hints, &res); if (x) return NULL; if (!res) return NULL; res_orig = res; while (res) { safe_bzero(ip6addr); if (res->ai_family == PF_INET) { sin = (struct sockaddr_in *)res->ai_addr; safe_snprintf(retaddr, "%s%s", inet_ntoa(sin->sin_addr), extra); safe_snprintf(d_resp->str, "%s%s", inet_ntoa(sin->sin_addr), extra); d_resp->type = AF_INET; } if (res->ai_family == PF_INET6) { sin6 = (struct sockaddr_in6 *)res->ai_addr; safe_snprintf(retaddr, "%s%s", inet_ntop(AF_INET6, &sin6->sin6_addr, ip6addr, 128), extra); safe_snprintf(d_resp->str, "%s%s", inet_ntop(AF_INET6, &sin6->sin6_addr, ip6addr, 128), extra); d_resp->type = AF_INET6; } if (res->ai_next && (res->ai_family == PF_INET || res->ai_family == PF_INET6)) d_resp = new_dnsresp(d_resp); res = res->ai_next; } freeaddrinfo(res_orig); if (retaddr[0] == '\0') return NULL; return retaddr; } #else char * _resolv_unspec_gai(char *raddr, struct dnsresp *d_resp, char *extra) { return NULL; } #endif char * resolve_addr(char *addr, int family, struct dnsresp *d_resp) { char extra[32]; char *tmpstr; char raddr[1024]; static char retaddr[1024]; struct dnsresp *d_resp_tmp; int f_gethostbyname; int f_gethostbyname2; int f_getaddrinfo; int f_inet_ntop; int ipv4_cap; int ipv6_cap; f_gethostbyname = 0; f_gethostbyname2 = 0; f_getaddrinfo = 0; f_inet_ntop = 0; ipv4_cap = 0; ipv6_cap = 0; #ifdef HAVE_GETHOSTBYNAME f_gethostbyname = 1; #endif #ifdef HAVE_GETHOSTBYNAME2 f_gethostbyname2 = 1; #endif #ifdef HAVE_GETADDRINFO f_getaddrinfo = 1; #endif #ifdef HAVE_INET_NTOP f_inet_ntop = 1; #endif if (f_gethostbyname) ipv4_cap = 1; if ((f_gethostbyname2 || f_getaddrinfo) && f_inet_ntop) ipv6_cap = 1; if (family != PF_INET && family != PF_INET6 && family != PF_UNSPEC) return NULL; if (family == PF_INET && !ipv4_cap) return NULL; if (family == PF_INET6 && !ipv6_cap) return NULL; if (family == PF_UNSPEC && (!ipv4_cap && !ipv6_cap)) return NULL; if (strlen(addr) > 1023) return NULL; if (family == PF_UNSPEC && !ipv4_cap) family = PF_INET6; if (family == PF_UNSPEC && !ipv6_cap) family = PF_INET; safe_bzero(extra); safe_bzero(raddr); tmpstr = strstr(addr, "/"); if (tmpstr) { safe_strncpy(extra, tmpstr); strncpy(raddr, addr, strlen(addr) - strlen(tmpstr)); } else { tmpstr = strstr(addr, " "); if (tmpstr) { safe_strncpy(extra, tmpstr); strncpy(raddr, addr, strlen(addr) - strlen(tmpstr)); } else safe_strncpy(raddr, addr); } safe_bzero(retaddr); if (family == PF_INET) { tmpstr = _resolv_v4_ghbn(raddr, d_resp, extra); if (!tmpstr) return NULL; safe_strncpy(retaddr, tmpstr); return retaddr; } if (family == PF_INET6) { if (f_getaddrinfo) { tmpstr = _resolv_v6_gai(raddr, d_resp, extra); if (!tmpstr) return NULL; safe_strncpy(retaddr, tmpstr); return retaddr; } if (f_gethostbyname2) { tmpstr = _resolv_v6_ghbn2(raddr, d_resp, extra); if (!tmpstr) return NULL; safe_strncpy(retaddr, tmpstr); return retaddr; } } if (family == PF_UNSPEC) { if (f_getaddrinfo) { tmpstr = _resolv_unspec_gai(raddr, d_resp, extra); if (!tmpstr) return NULL; safe_strncpy(retaddr, tmpstr); return retaddr; } if (f_gethostbyname && f_gethostbyname2) { tmpstr = _resolv_v4_ghbn(raddr, d_resp, extra); if (tmpstr) { safe_strncpy(retaddr, tmpstr); d_resp_tmp = d_resp; d_resp = new_dnsresp(d_resp); } tmpstr = _resolv_v6_ghbn2(raddr, d_resp, extra); if (!tmpstr) { d_resp_tmp->next = NULL; free(d_resp); } return retaddr; } } return NULL; }
446761.c
/* * Copyright (c) 2004,2005 Damien Miller <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "Python.h" #include "flowd-common.h" #include "structmember.h" #include "store.h" #include "flowd-pytypes.h" /* $Id$ */ /* Prototypes */ PyMODINIT_FUNC initflowd(void); struct _FlowLogObject; struct _FlowLogIterObject; static struct _FlowLogIterObject *newFlowLogIterObject(struct _FlowLogObject *); /* ------------------------------------------------------------------------ */ /* Flows*/ typedef struct { PyObject_HEAD PyObject *user_attr; /* User-specified attributes */ PyObject *octets; /* bah. python >2.5 lacks T_LONGLONG */ PyObject *packets; /* ditto */ PyObject *agent_addr; PyObject *src_addr; PyObject *dst_addr; PyObject *gateway_addr; struct store_flow_complete flow; } FlowObject; static PyTypeObject Flow_Type; static FlowObject * newFlowObject(void) { FlowObject *self; self = PyObject_New(FlowObject, &Flow_Type); if (self == NULL) return NULL; self->user_attr = PyDict_New(); self->octets = Py_None; Py_INCREF(Py_None); self->packets = Py_None; Py_INCREF(Py_None); self->agent_addr = Py_None; Py_INCREF(Py_None); self->src_addr = Py_None; Py_INCREF(Py_None); self->dst_addr = Py_None; Py_INCREF(Py_None); self->gateway_addr = Py_None; Py_INCREF(Py_None); bzero(&self->flow, sizeof(self->flow)); if (self->user_attr == NULL) { /* Flow_dealloc will clean up for us */ Py_XDECREF(self); return (NULL); } return self; } static FlowObject * newFlowObject_from_flow(struct store_flow_complete *flow) { FlowObject *self; char addr_buf[128]; /* Sanity check */ if (flow == NULL) return NULL; self = PyObject_New(FlowObject, &Flow_Type); if (self == NULL) return NULL; self->user_attr = NULL; self->octets = NULL; self->packets = NULL; self->src_addr = self->dst_addr = NULL; self->agent_addr = self->gateway_addr = NULL; memcpy(&self->flow, flow, sizeof(self->flow)); store_swab_flow(&self->flow, 0); #define FL_ADDR_NTOP(addr, which) do { \ if ((self->flow.hdr.fields & STORE_FIELD_##which) != 0) { \ if (addr_ntop(&self->flow.addr, addr_buf, \ sizeof(addr_buf)) != -1) \ self->addr = PyString_FromString(addr_buf); \ } \ if (self->addr == NULL) { \ self->addr = Py_None; \ Py_INCREF(Py_None); \ } } while (0) FL_ADDR_NTOP(src_addr, SRC_ADDR); FL_ADDR_NTOP(dst_addr, DST_ADDR); FL_ADDR_NTOP(agent_addr, AGENT_ADDR); FL_ADDR_NTOP(gateway_addr, GATEWAY_ADDR); #undef FL_ADDR_NTOP if ((self->flow.hdr.fields & STORE_FIELD_OCTETS) != 0) { self->octets = PyLong_FromUnsignedLongLong( self->flow.octets.flow_octets); } else { self->octets = Py_None; Py_INCREF(Py_None); } if ((self->flow.hdr.fields & STORE_FIELD_PACKETS) != 0) { self->packets = PyLong_FromUnsignedLongLong( self->flow.packets.flow_packets); } else { self->packets = Py_None; Py_INCREF(Py_None); } self->user_attr = PyDict_New(); if (self->user_attr == NULL || self->octets == NULL || self->packets == NULL) { /* Flow_dealloc will clean up for us */ Py_XDECREF(self); return (NULL); } return self; } static int object_to_u64(PyObject *o, u_int64_t *u64) { if (o == NULL) return (-1); if (PyLong_Check(o)) { *u64 = PyLong_AsUnsignedLongLong(o); return (0); } *u64 = PyInt_AsUnsignedLongLongMask(o); if (PyErr_Occurred()) return (-1); return (0); } static int flowobj_normalise(FlowObject *f) { const char *tmp; if (f->octets != NULL && f->octets != Py_None) { if (object_to_u64(f->octets, &f->flow.octets.flow_octets) == -1) { PyErr_SetString(PyExc_TypeError, "incorrect type for Flow.octets"); return (-1); } f->flow.hdr.fields |= STORE_FIELD_OCTETS; } else f->flow.hdr.fields &= ~STORE_FIELD_OCTETS; if (f->packets != NULL && f->packets != Py_None) { if (object_to_u64(f->packets, &f->flow.packets.flow_packets) == -1) { PyErr_SetString(PyExc_TypeError, "incorrect type for Flow.packets"); return (-1); } f->flow.hdr.fields |= STORE_FIELD_PACKETS; } else f->flow.hdr.fields &= ~STORE_FIELD_PACKETS; #define FL_ADDR_PTON(addr, tag) do { \ if (f->addr == NULL || f->addr == Py_None || \ (tmp = PyString_AsString(f->addr)) == NULL || \ *tmp == '\0') { \ f->flow.hdr.fields &= ~STORE_FIELD_##tag; \ } else { \ if (addr_pton(tmp, &f->flow.addr) == -1) { \ PyErr_SetString(PyExc_ValueError, \ "Invalid \""#addr"\""); \ return (-1); \ } \ f->flow.hdr.fields |= STORE_FIELD_##tag; \ } } while (0) FL_ADDR_PTON(src_addr, SRC_ADDR); FL_ADDR_PTON(dst_addr, DST_ADDR); FL_ADDR_PTON(agent_addr, AGENT_ADDR); FL_ADDR_PTON(gateway_addr, GATEWAY_ADDR); #undef FL_ADDR_PTON return (0); } static FlowObject * newFlowObject_from_blob(u_int8_t *buf, u_int len) { struct store_flow_complete flow; char ebuf[512]; /* Sanity check */ if (buf == NULL || len == 0 || len > 8192) return NULL; if (store_flow_deserialise(buf, len, &flow, ebuf, sizeof(ebuf)) != STORE_ERR_OK) { PyErr_SetString(PyExc_ValueError, ebuf); return (NULL); } return newFlowObject_from_flow(&flow); } /* Flow methods */ static void Flow_dealloc(FlowObject *self) { Py_XDECREF(self->user_attr); Py_XDECREF(self->octets); Py_XDECREF(self->packets); Py_XDECREF(self->src_addr); Py_XDECREF(self->dst_addr); Py_XDECREF(self->agent_addr); Py_XDECREF(self->gateway_addr); PyObject_Del(self); } PyDoc_STRVAR(flow_format_doc, "Flow.format(utc = 0, mask = flowd.DISPLAY_BRIEF) -> String\n\ \n\ Format a flow to a string.\n\ "); static PyObject * flow_format(FlowObject *self, PyObject *args, PyObject *kw_args) { static char *keywords[] = { "utc", "mask", NULL }; char buf[1024]; int utcflag = 0; unsigned long mask = STORE_DISPLAY_BRIEF; if (!PyArg_ParseTupleAndKeywords(args, kw_args, "|ik:format", keywords, &utcflag, &mask)) return NULL; if (flowobj_normalise(self) == -1) return (NULL); store_format_flow(&self->flow, buf, sizeof(buf), utcflag, mask, 1); return PyString_FromString(buf); } PyDoc_STRVAR(flow_serialise_doc, "Flow.serialise() -> String\n\ \n\ Format convert a flow object to a binary representation.\n\ "); static PyObject * flow_serialise(FlowObject *self) { char buf[1024], ebuf[512]; struct store_flow_complete flow; int len; if (flowobj_normalise(self) == -1) return (NULL); memcpy(&self->flow, &flow, sizeof(flow)); store_swab_flow(&flow, 1); if (store_flow_serialise(&flow, buf, sizeof(buf), &len , ebuf, sizeof(ebuf)) != STORE_ERR_OK) { PyErr_SetString(PyExc_ValueError, ebuf); return (NULL); } return PyString_FromStringAndSize(buf, len); } PyDoc_STRVAR(flow_has_field_doc, "Flow.has_field(field) -> Boolean\n\ \n\ Test whether a flow field is set. Multiple fields may be specified by \n\ logical-ORing them together. If multiple fields are specified, the return \n\ value is only true if all the fields are present in the flow.\n\ "); static PyObject * flow_has_field(FlowObject *self, PyObject *args, PyObject *kw_args) { static char *keywords[] = { "field", NULL }; u_int32_t field = 0; PyObject *ret; if (!PyArg_ParseTupleAndKeywords(args, kw_args, "k:has_field", keywords, &field)) return NULL; if (field == 0) { PyErr_SetString(PyExc_ValueError, "No field specified"); return (NULL); } if (flowobj_normalise(self) == -1) return (NULL); ret = (self->flow.hdr.fields & field) == field ? Py_True : Py_False; Py_INCREF(ret); return (ret); } static PyMethodDef Flow_methods[] = { {"format", (PyCFunction)flow_format, METH_VARARGS|METH_KEYWORDS, flow_format_doc }, {"serialise", (PyCFunction)flow_serialise, 0, flow_serialise_doc }, {"has_field", (PyCFunction)flow_has_field, METH_VARARGS|METH_KEYWORDS, flow_has_field_doc }, {NULL, NULL} /* sentinel */ }; static PyMemberDef Flow_members[] = { {"data", T_OBJECT, offsetof(FlowObject, user_attr), 0}, {"src_addr", T_OBJECT, offsetof(FlowObject, src_addr), 0}, {"dst_addr", T_OBJECT, offsetof(FlowObject, dst_addr), 0}, {"agent_addr", T_OBJECT, offsetof(FlowObject, agent_addr), 0}, {"gateway_addr",T_OBJECT, offsetof(FlowObject, gateway_addr), 0}, {"octets", T_OBJECT, offsetof(FlowObject, octets), 0}, {"packets", T_OBJECT, offsetof(FlowObject, packets), 0}, {"src_addr_af", FL_T_AF, offsetof(FlowObject, flow.src_addr.af), 0}, {"dst_addr_af", FL_T_AF, offsetof(FlowObject, flow.dst_addr.af), 0}, {"agent_addr_af",FL_T_AF, offsetof(FlowObject, flow.agent_addr.af), 0}, {"gateway_addr_af",FL_T_AF,offsetof(FlowObject, flow.gateway_addr.af), 0}, {"flow_ver", FL_T_U8, offsetof(FlowObject, flow.hdr.version), 0}, {"fields", FL_T_U32, offsetof(FlowObject, flow.hdr.fields), 0}, {"tag", FL_T_U32, offsetof(FlowObject, flow.tag.tag), 0}, {"recv_sec", FL_T_U32, offsetof(FlowObject, flow.recv_time.recv_sec),0}, {"recv_usec", FL_T_U32, offsetof(FlowObject, flow.recv_time.recv_usec),0}, {"tcp_flags", FL_T_U8, offsetof(FlowObject, flow.pft.tcp_flags), 0}, {"protocol", FL_T_U8, offsetof(FlowObject, flow.pft.protocol), 0}, {"tos", FL_T_U8, offsetof(FlowObject, flow.pft.tos), 0}, {"src_port", FL_T_U16, offsetof(FlowObject, flow.ports.src_port), 0}, {"dst_port", FL_T_U16, offsetof(FlowObject, flow.ports.dst_port), 0}, {"if_ndx_in", FL_T_U32, offsetof(FlowObject, flow.ifndx.if_index_in),0}, {"if_ndx_out", FL_T_U32, offsetof(FlowObject, flow.ifndx.if_index_out),0}, {"sys_uptime_ms",FL_T_U32,offsetof(FlowObject, flow.ainfo.sys_uptime_ms),0}, {"agent_sec", FL_T_U32, offsetof(FlowObject, flow.ainfo.time_sec), 0}, {"agent_usec", FL_T_U32, offsetof(FlowObject, flow.ainfo.time_nanosec),0}, {"netflow_ver", FL_T_U16, offsetof(FlowObject, flow.ainfo.netflow_version),0}, {"flow_start", FL_T_U32, offsetof(FlowObject, flow.ftimes.flow_start),0}, {"flow_finish", FL_T_U32, offsetof(FlowObject, flow.ftimes.flow_finish),0}, {"src_as", FL_T_U32, offsetof(FlowObject, flow.asinf.src_as), 0}, {"dst_as", FL_T_U32, offsetof(FlowObject, flow.asinf.dst_as), 0}, {"src_mask", FL_T_U8, offsetof(FlowObject, flow.asinf.src_mask), 0}, {"dst_mask", FL_T_U8, offsetof(FlowObject, flow.asinf.dst_mask), 0}, {"engine_type", FL_T_U16, offsetof(FlowObject, flow.finf.engine_type),0}, {"engine_id", FL_T_U16, offsetof(FlowObject, flow.finf.engine_id), 0}, {"flow_sequence",FL_T_U32,offsetof(FlowObject, flow.finf.flow_sequence),0}, {"source_id", FL_T_U32, offsetof(FlowObject, flow.finf.source_id), 0}, {"crc32", FL_T_U32, offsetof(FlowObject, flow.crc32.crc32), 0}, {NULL} }; PyDoc_STRVAR(Flow_doc, "Object representing a single NetFlow flow"); static PyTypeObject Flow_Type = { /* The ob_type field must be initialized in the module init function * to be portable to Windows without using C++. */ PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "flowd.Flow", /*tp_name*/ sizeof(FlowObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)Flow_dealloc,/*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ Flow_doc, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ Flow_methods, /*tp_methods*/ Flow_members, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ 0, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ }; /* ------------------------------------------------------------------------ */ typedef struct _FlowLogObject { PyObject_HEAD PyObject *flowlog; /* PyFile */ } FlowLogObject; static PyTypeObject FlowLog_Type; /* FlowLog methods */ static void FlowLog_dealloc(FlowLogObject *self) { Py_XDECREF(self->flowlog); PyObject_Del(self); } PyDoc_STRVAR(FlowLog_read_flow_doc, "FlowLog.read_flow() -> new Flow object\n\ \n\ Reads a flow record from the flow log and returns a Flow object\n\ "); static PyObject * FlowLog_read_flow(FlowLogObject *self) { struct store_flow_complete flow; char ebuf[512]; switch (store_read_flow(PyFile_AsFile(self->flowlog), &flow, ebuf, sizeof(ebuf))) { case STORE_ERR_OK: return (PyObject *)newFlowObject_from_flow(&flow); case STORE_ERR_EOF: Py_INCREF(Py_None); return Py_None; default: PyErr_SetString(PyExc_ValueError, ebuf); return (NULL); } /* NOTREACHED */ } PyDoc_STRVAR(FlowLog_write_flow_doc, "FlowLog.write_flow(flow, mask = flowd.DISPLAY_ALL) -> None\n\ \n\ Writes a flow record to the flow log\n\ "); static PyObject * FlowLog_write_flow(FlowLogObject *self, PyObject *args, PyObject *kw_args) { struct store_flow_complete flow; static char *keywords[] = { "flow", "fieldmask", NULL }; char ebuf[512]; FlowObject *flowobj = NULL; u_int32_t mask = STORE_DISPLAY_ALL; if (!PyArg_ParseTupleAndKeywords(args, kw_args, "O!|k:write_flow", keywords, &Flow_Type, (PyObject *)&flowobj, &mask)) return NULL; if (flowobj_normalise(flowobj) == -1) return (NULL); memcpy(&flow, &flowobj->flow, sizeof(flow)); store_swab_flow(&flow, 1); if (store_write_flow(PyFile_AsFile(self->flowlog), &flow, mask, ebuf, sizeof(ebuf)) != STORE_ERR_OK) { PyErr_SetString(PyExc_ValueError, ebuf); return (NULL); } Py_INCREF(Py_None); return Py_None; } static PyObject * FlowLog_getiter(FlowLogObject *self) { return (PyObject *)newFlowLogIterObject(self); } static PyMemberDef FlowLog_members[] = { {"file", T_OBJECT, offsetof(FlowLogObject, flowlog), 0}, {NULL} }; PyDoc_STRVAR(FlowLog_doc, "NetFlow log"); static PyMethodDef FlowLog_methods[] = { {"read_flow", (PyCFunction)FlowLog_read_flow, 0, FlowLog_read_flow_doc }, {"write_flow", (PyCFunction)FlowLog_write_flow,METH_VARARGS|METH_KEYWORDS, FlowLog_write_flow_doc }, {NULL, NULL} /* sentinel */ }; static PyTypeObject FlowLog_Type = { /* The ob_type field must be initialized in the module init function * to be portable to Windows without using C++. */ PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "flowd.FlowLog", /*tp_name*/ sizeof(FlowLogObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)FlowLog_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ FlowLog_doc, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ (getiterfunc)FlowLog_getiter, /*tp_iter*/ 0, /*tp_iternext*/ FlowLog_methods, /*tp_methods*/ FlowLog_members, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ 0, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ }; /* ------------------------------------------------------------------------ */ /* FlowLogIter: netflow log iterator */ typedef struct _FlowLogIterObject { PyObject_HEAD FlowLogObject *parent; } FlowLogIterObject; static PyTypeObject FlowLogIter_Type; static FlowLogIterObject * newFlowLogIterObject(FlowLogObject *parent) { FlowLogIterObject *self; self = PyObject_New(FlowLogIterObject, &FlowLogIter_Type); if (self == NULL) return NULL; self->parent = parent; Py_XINCREF(self->parent); return self; } /* FlowLogIter methods */ static void FlowLogIter_dealloc(FlowLogIterObject *self) { Py_XDECREF(self->parent); PyObject_Del(self); } static PyObject * FlowLogIter_iternext(FlowLogIterObject *self) { struct store_flow_complete flow; char ebuf[512]; switch (store_read_flow(PyFile_AsFile(self->parent->flowlog), &flow, ebuf, sizeof(ebuf))) { case STORE_ERR_OK: return (PyObject *)newFlowObject_from_flow(&flow); case STORE_ERR_EOF: return NULL; default: PyErr_SetString(PyExc_ValueError, ebuf); return (NULL); } /* NOTREACHED */ } PyDoc_STRVAR(FlowLogIter_doc, "FlowLog tree iterator"); static PyTypeObject FlowLogIter_Type = { /* The ob_type field must be initialized in the module init function * to be portable to Windows without using C++. */ PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "flowd.FlowLogIter", /*tp_name*/ sizeof(FlowLogIterObject),/*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)FlowLogIter_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ FlowLogIter_doc, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ (iternextfunc)FlowLogIter_iternext, /*tp_iternext*/ 0, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ 0, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ }; /* ------------------------------------------------------------------------ */ PyDoc_STRVAR(flow_Flow_doc, "Flow(blob = None) -> new Flow object\n\ \n\ Instantiate a new Flow object. If the 'blob' parameter is specified,\n\ the flow will be created from the specified binary flow record, otherwise \n\ the Flow object will be created empty."); static PyObject * flow_Flow(PyObject *self, PyObject *args, PyObject *kw_args) { FlowObject *rv; static char *keywords[] = { "blob", NULL }; char *blob = NULL; int bloblen = -1; if (!PyArg_ParseTupleAndKeywords(args, kw_args, "|s#:Flow", keywords, &blob, &bloblen)) return NULL; if (bloblen == -1) rv = newFlowObject(); else rv = newFlowObject_from_blob(blob, bloblen); if (rv == NULL) return NULL; return (PyObject *)rv; } PyDoc_STRVAR(flow_FlowLog_doc, "FlowLog(path, mode = \"rb\") -> new FlowLog object\n\ \n\ Open a flowd log file by path.\n\ "); static PyObject * flow_FlowLog(PyObject *self, PyObject *args, PyObject *kw_args) { FlowLogObject *rv; static char *keywords[] = { "path", "mode", NULL }; char *path = NULL, *mode = "rb"; if (!PyArg_ParseTupleAndKeywords(args, kw_args, "s|s:FlowLog", keywords, &path, &mode)) return NULL; if ((rv = PyObject_New(FlowLogObject, &FlowLog_Type)) == NULL) return (NULL); if ((rv->flowlog = PyFile_FromString(path, mode)) == NULL) return (NULL); PyFile_SetBufSize(rv->flowlog, 8192); return (PyObject *)rv; } PyDoc_STRVAR(flow_FlowLog_fromfile_doc, "FlowLog_fromfile(file) -> new FlowLog object\n\ \n\ Open a flowd log file from an open file object.\n\ "); static PyObject * flow_FlowLog_fromfile(PyObject *self, PyObject *args, PyObject *kw_args) { FlowLogObject *rv; static char *keywords[] = { "file", NULL }; PyObject *file = NULL; if (!PyArg_ParseTupleAndKeywords(args, kw_args, "O!:FlowLog_fromfile", keywords, &PyFile_Type, (PyObject *)&file)) return NULL; if ((rv = PyObject_New(FlowLogObject, &FlowLog_Type)) == NULL) return (NULL); Py_INCREF(file); rv->flowlog = file; PyFile_SetBufSize(rv->flowlog, 8192); return (PyObject *)rv; } PyDoc_STRVAR(flow_iso_time_doc, "iso_time(time, utc_flag = 0) -> String\n\ \n\ Formats a time in seconds-since-epoch format into a ISO8601 string.\n\ The time will be rendered in the current timezone unless utc_flag is set.\n\ "); static PyObject * flow_iso_time(PyObject *self, PyObject *args, PyObject *kw_args) { static char *keywords[] = { "time", "utc_flag", NULL }; int utc_flag = 0; long when; if (!PyArg_ParseTupleAndKeywords(args, kw_args, "l|i:iso_time", keywords, &when, &utc_flag)) return NULL; return (PyObject *)PyString_FromString(iso_time(when, utc_flag)); } PyDoc_STRVAR(flow_interval_time_doc, "iso_time(time) -> String\n\ \n\ Formats a duration in seconds into a string.\n\ "); static PyObject * flow_interval_time(PyObject *self, PyObject *args, PyObject *kw_args) { static char *keywords[] = { "time", NULL }; long when; if (!PyArg_ParseTupleAndKeywords(args, kw_args, "l:iso_time", keywords, &when)) return NULL; return (PyObject *)PyString_FromString(interval_time(when)); } static PyMethodDef flowd_methods[] = { {"Flow", (PyCFunction)flow_Flow, METH_VARARGS|METH_KEYWORDS, flow_Flow_doc }, {"FlowLog", (PyCFunction)flow_FlowLog, METH_VARARGS|METH_KEYWORDS, flow_FlowLog_doc }, {"FlowLog_fromfile",(PyCFunction)flow_FlowLog_fromfile, METH_VARARGS|METH_KEYWORDS, flow_FlowLog_fromfile_doc }, {"iso_time", (PyCFunction)flow_iso_time, METH_VARARGS|METH_KEYWORDS, flow_iso_time_doc }, {"interval_time",(PyCFunction)flow_interval_time, METH_VARARGS|METH_KEYWORDS, flow_interval_time_doc }, {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(module_doc, "Interface to flowd NetFlow log files.\n\ "); PyMODINIT_FUNC initflowd(void) { PyObject *m; if (PyType_Ready(&Flow_Type) < 0) return; if (PyType_Ready(&FlowLog_Type) < 0) return; m = Py_InitModule3("flowd", flowd_methods, module_doc); #define STORE_CONST(c) \ PyModule_AddObject(m, #c, PyLong_FromUnsignedLong(STORE_##c)) STORE_CONST(FIELD_TAG); STORE_CONST(FIELD_RECV_TIME); STORE_CONST(FIELD_PROTO_FLAGS_TOS); STORE_CONST(FIELD_AGENT_ADDR4); STORE_CONST(FIELD_AGENT_ADDR6); STORE_CONST(FIELD_SRC_ADDR4); STORE_CONST(FIELD_SRC_ADDR6); STORE_CONST(FIELD_DST_ADDR4); STORE_CONST(FIELD_DST_ADDR6); STORE_CONST(FIELD_GATEWAY_ADDR4); STORE_CONST(FIELD_GATEWAY_ADDR6); STORE_CONST(FIELD_SRCDST_PORT); STORE_CONST(FIELD_PACKETS); STORE_CONST(FIELD_OCTETS); STORE_CONST(FIELD_IF_INDICES); STORE_CONST(FIELD_AGENT_INFO); STORE_CONST(FIELD_FLOW_TIMES); STORE_CONST(FIELD_AS_INFO); STORE_CONST(FIELD_FLOW_ENGINE_INFO); STORE_CONST(FIELD_CRC32); STORE_CONST(FIELD_RESERVED); STORE_CONST(FIELD_ALL); STORE_CONST(FIELD_AGENT_ADDR); STORE_CONST(FIELD_SRC_ADDR); STORE_CONST(FIELD_DST_ADDR); STORE_CONST(FIELD_SRCDST_ADDR); STORE_CONST(FIELD_GATEWAY_ADDR); STORE_CONST(DISPLAY_ALL); STORE_CONST(DISPLAY_BRIEF); #undef STORE_CONST #define STORE_CONST2(c) \ PyModule_AddObject(m, "STORE_"#c, PyLong_FromUnsignedLong(STORE_##c)) STORE_CONST2(VER_MAJOR); STORE_CONST2(VER_MINOR); STORE_CONST2(VERSION); #undef STORE_CONST2 PyModule_AddStringConstant(m, "__version__", PROGVER); }
109238.c
/*-------------- Telecommunications & Signal Processing Lab --------------- McGill University Routine: int AFfWrTA (AFILE *AFp, const float Dbuff[], int Nval) Purpose: Write text data to an audio file (float input values) Description: These routines write a specified number of samples to an audio file. The input to these routine is a buffer of float values. The output file contains the text representation of the data values. Parameters: <- int AFfWrTA Number of samples written. If this value is less than Nval, an error has occurred. -> AFILE *AFp Audio file pointer for an audio file opened by AFopnWrite -> const float Dbuff[] Array of floats with the samples to be written -> int Nval Number of samples to be written, normally a multiple of AFp->Nchan Author / revision: P. Kabal Copyright (C) 2017 $Revision: 1.3 $ $Date: 2017/05/18 17:09:32 $ -------------------------------------------------------------------------*/ #include <AFpar.h> #include <libtsp/AFdataio.h> int AFfWrTA (AFILE *AFp, const float Dbuff[], int Nval) { int i, Nc, Nmod; /* Print a frame of samples on the same line */ Nmod = AFp->Nchan; if (Nmod > 5 || Nval % AFp->Nchan != 0) Nmod = 1; for (i = 0; i < Nval; ++i) { if (i % Nmod < Nmod - 1) Nc = fprintf (AFp->fp, "%g ", AFp->ScaleF * Dbuff[i]); else Nc = fprintf (AFp->fp, "%g\n", AFp->ScaleF * Dbuff[i]); if (Nc < 0) /* fprintf returns a negative valued error code */ break; } return i; }
606533.c
/** * @file * @brief * * @author Anton Kozlov * @date 17.07.2014 */ #include <getopt.h> #include <embox/test.h> EMBOX_TEST_SUITE("getopt_long test suite"); TEST_SETUP(test_getopt_long_case_setup); static int test_getopt_long_case_setup(void) { optind = 1; return 0; } TEST_CASE("getopt_long should take NULL longindex") { char *const argv[] = {"", "--long1", NULL}; const int argc = ARRAY_SIZE(argv) - 1; struct option long_opts[] = { { "long1", no_argument, 0, 1 }, { }, }; test_assert_equal(1, getopt_long(argc, argv, "", long_opts, NULL)); } TEST_CASE("getopt_long should process every argument one time exactly") { char *const argv[] = {"", "--long1", "--long2", "--long1", "--long1", "--long4", NULL}; const int argc = ARRAY_SIZE(argv) - 1; struct option long_opts[] = { { "long1", no_argument, 0, 0 }, { "long2", no_argument, 0, 1 }, { "long3", no_argument, 0, 2 }, { }, }; int opt; int seen[2] = {0, 0}; while (-1 != (opt = getopt_long(argc, argv, "", long_opts, NULL))) { test_assert(opt == 0 || opt == 1); seen[opt]++; } test_assert_equal(3, seen[0]); test_assert_equal(1, seen[1]); test_assert_equal(5, optind); } TEST_CASE("getopt_long should fill longindex if provided") { char *const argv[] = {"", "--long1", "--long2", "--long1", "--long1", "--long4", NULL}; const int argc = ARRAY_SIZE(argv) - 1; struct option long_opts[] = { { "long1", no_argument, 0, 10 }, { "long2", no_argument, 0, 11 }, { "long3", no_argument, 0, 12 }, { }, }; int longindex, opt; while (-1 != (opt = getopt_long(argc, argv, "", long_opts, &longindex))) { test_assert_equal(longindex, opt - 10); } test_assert_equal(5, optind); } TEST_CASE("getopt_long should set optind to next arg") { char *const argv[] = {"", "--long1", "--long2", "arg1", "arg2", "arg3", NULL}; const int argc = ARRAY_SIZE(argv) - 1; struct option long_opts[] = { { "long1", no_argument, 0, 1 }, { "long2", no_argument, 0, 2 }, { }, }; int opt; while (-1 != (opt = getopt_long(argc, argv, "", long_opts, NULL))) { test_assert(opt == 1 || opt == 2); if (opt == 1) { test_assert_equal(2, optind); } else { test_assert_equal(3, optind); } } test_assert_equal(3, optind); } TEST_CASE("getopt_long should write to flag ptr, if provided") { char *const argv[] = {"", "--long1", NULL}; const int argc = ARRAY_SIZE(argv) - 1; int flag = 0; struct option long_opts[] = { { "long1", no_argument, &flag, 1 }, { }, }; test_assert_equal(0, getopt_long(argc, argv, "", long_opts, NULL)); test_assert_equal(1, flag); test_assert_equal(2, optind); } TEST_CASE("getopt_long should get mandatory arg") { char *const argv[] = {"", "--long2", "optarg", "--long3", NULL}; const int argc = ARRAY_SIZE(argv) - 1; struct option long_opts[] = { { "long2", required_argument, 0, 1 }, { }, }; test_assert_equal(1, getopt_long(argc, argv, "", long_opts, NULL)); test_assert_str_equal("optarg", optarg); test_assert_equal(3, optind); } TEST_CASE("getopt_long shouldn't get empty arg") { char *const argv[] = {"", "--long2", "optarg", "--long3", NULL}; const int argc = ARRAY_SIZE(argv) - 1; struct option long_opts[] = { { "long2", no_argument, 0, 1 }, { }, }; test_assert_equal(1, getopt_long(argc, argv, "", long_opts, NULL)); test_assert_equal(NULL, optarg); test_assert_equal(2, optind); } TEST_CASE("getopt_long should treat options with argument separated with =") { char *const argv[] = {"", "--long1=optarg1", "--long2=optarg2", NULL}; const int argc = ARRAY_SIZE(argv) - 1; struct option long_opts[] = { { "long1", required_argument, 0, 1 }, { "long2", no_argument, 0, 2 }, { }, }; int opt; while (-1 != (opt = getopt_long(argc, argv, "", long_opts, NULL))) { test_assert_equal(opt, 1); test_assert_str_equal("optarg1", optarg); } test_assert_equal(2, optind); } TEST_CASE("getopt_long should treat optional argument right") { char *const argv[] = {"", "--long1", "--long2=optarg", NULL}; const int argc = ARRAY_SIZE(argv) - 1; struct option long_opts[] = { { "long1", optional_argument, 0, 1 }, { "long2", optional_argument, 0, 2 }, { }, }; int opt; while (-1 != (opt = getopt_long(argc, argv, "", long_opts, NULL))) { switch(opt) { case 1: test_assert_null(optarg); break; case 2: test_assert_str_equal("optarg", optarg); break; default: test_fail(); } } test_assert_equal(3, optind); }
915291.c
#include <yaml.h> #include <stdlib.h> #include <stdio.h> int main(int argc, char *argv[]) { int help = 0; int canonical = 0; int unicode = 0; int k; int done = 0; yaml_parser_t parser; yaml_emitter_t emitter; yaml_document_t document; /* Clear the objects. */ memset(&parser, 0, sizeof(parser)); memset(&emitter, 0, sizeof(emitter)); memset(&document, 0, sizeof(document)); /* Analyze command line options. */ for (k = 1; k < argc; k ++) { if (strcmp(argv[k], "-h") == 0 || strcmp(argv[k], "--help") == 0) { help = 1; } else if (strcmp(argv[k], "-c") == 0 || strcmp(argv[k], "--canonical") == 0) { canonical = 1; } else if (strcmp(argv[k], "-u") == 0 || strcmp(argv[k], "--unicode") == 0) { unicode = 1; } else { fprintf(stderr, "Unrecognized option: %s\n" "Try `%s --help` for more information.\n", argv[k], argv[0]); return 1; } } /* Display the help string. */ if (help) { printf("%s [--canonical] [--unicode] <input >output\n" "or\n%s -h | --help\nReformat a YAML stream\n\nOptions:\n" "-h, --help\t\tdisplay this help and exit\n" "-c, --canonical\t\toutput in the canonical YAML format\n" "-u, --unicode\t\toutput unescaped non-ASCII characters\n", argv[0], argv[0]); return 0; } /* Initialize the parser and emitter objects. */ if (!yaml_parser_initialize(&parser)) goto parser_error; if (!yaml_emitter_initialize(&emitter)) goto emitter_error; /* Set the parser parameters. */ yaml_parser_set_input_file(&parser, stdin); /* Set the emitter parameters. */ yaml_emitter_set_output_file(&emitter, stdout); yaml_emitter_set_canonical(&emitter, canonical); yaml_emitter_set_unicode(&emitter, unicode); /* The main loop. */ while (!done) { /* Get the next event. */ if (!yaml_parser_load(&parser, &document)) goto parser_error; /* Check if this is the stream end. */ if (!yaml_document_get_root_node(&document)) { done = 1; } /* Emit the event. */ if (!yaml_emitter_dump(&emitter, &document)) goto emitter_error; } yaml_parser_delete(&parser); yaml_emitter_delete(&emitter); return 0; parser_error: /* Display a parser error message. */ switch (parser.error) { case YAML_MEMORY_ERROR: fprintf(stderr, "Memory error: Not enough memory for parsing\n"); break; case YAML_READER_ERROR: if (parser.problem_value != -1) { fprintf(stderr, "Reader error: %s: #%X at %d\n", parser.problem, parser.problem_value, parser.problem_offset); } else { fprintf(stderr, "Reader error: %s at %d\n", parser.problem, parser.problem_offset); } break; case YAML_SCANNER_ERROR: if (parser.context) { fprintf(stderr, "Scanner error: %s at line %d, column %d\n" "%s at line %d, column %d\n", parser.context, parser.context_mark.line+1, parser.context_mark.column+1, parser.problem, parser.problem_mark.line+1, parser.problem_mark.column+1); } else { fprintf(stderr, "Scanner error: %s at line %d, column %d\n", parser.problem, parser.problem_mark.line+1, parser.problem_mark.column+1); } break; case YAML_PARSER_ERROR: if (parser.context) { fprintf(stderr, "Parser error: %s at line %d, column %d\n" "%s at line %d, column %d\n", parser.context, parser.context_mark.line+1, parser.context_mark.column+1, parser.problem, parser.problem_mark.line+1, parser.problem_mark.column+1); } else { fprintf(stderr, "Parser error: %s at line %d, column %d\n", parser.problem, parser.problem_mark.line+1, parser.problem_mark.column+1); } break; case YAML_COMPOSER_ERROR: if (parser.context) { fprintf(stderr, "Composer error: %s at line %d, column %d\n" "%s at line %d, column %d\n", parser.context, parser.context_mark.line+1, parser.context_mark.column+1, parser.problem, parser.problem_mark.line+1, parser.problem_mark.column+1); } else { fprintf(stderr, "Composer error: %s at line %d, column %d\n", parser.problem, parser.problem_mark.line+1, parser.problem_mark.column+1); } break; default: /* Couldn't happen. */ fprintf(stderr, "Internal error\n"); break; } yaml_parser_delete(&parser); yaml_emitter_delete(&emitter); return 1; emitter_error: /* Display an emitter error message. */ switch (emitter.error) { case YAML_MEMORY_ERROR: fprintf(stderr, "Memory error: Not enough memory for emitting\n"); break; case YAML_WRITER_ERROR: fprintf(stderr, "Writer error: %s\n", emitter.problem); break; case YAML_EMITTER_ERROR: fprintf(stderr, "Emitter error: %s\n", emitter.problem); break; default: /* Couldn't happen. */ fprintf(stderr, "Internal error\n"); break; } yaml_parser_delete(&parser); yaml_emitter_delete(&emitter); return 1; }
621275.c
/* $NetBSD: int_bus_dma.c,v 1.7.4.1 2002/12/07 19:25:18 he Exp $ */ /*- * Copyright (c) 1996, 1997, 1998 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility, * NASA Ames Research Center. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the NetBSD * Foundation, Inc. and its contributors. * 4. Neither the name of The NetBSD Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * The integrator board has memory steering hardware that means that * the normal physical addresses used by the processor cannot be used * for DMA. Instead we have to use the "core module alias mapping * addresses". We don't use these for normal processor accesses since * they are much slower than the direct addresses when accessing * memory on the local board. */ #include <sys/param.h> #include <sys/systm.h> #include <sys/kernel.h> #include <sys/map.h> #include <sys/proc.h> #include <sys/buf.h> #include <sys/reboot.h> #include <sys/conf.h> #include <sys/file.h> #include <sys/malloc.h> #include <sys/mbuf.h> #include <sys/vnode.h> #include <sys/device.h> #include <uvm/uvm_extern.h> #define _ARM32_BUS_DMA_PRIVATE #include <evbarm/integrator/int_bus_dma.h> #include <machine/cpu.h> #include <arm/cpufunc.h> static int integrator_bus_dmamap_load_buffer __P((bus_dma_tag_t, bus_dmamap_t, void *, bus_size_t, struct proc *, int, vm_offset_t *, int *, int)); static int integrator_bus_dma_inrange __P((bus_dma_segment_t *, int, bus_addr_t)); /* * Common function for loading a DMA map with a linear buffer. May * be called by bus-specific DMA map load functions. */ int integrator_bus_dmamap_load(t, map, buf, buflen, p, flags) bus_dma_tag_t t; bus_dmamap_t map; void *buf; bus_size_t buflen; struct proc *p; int flags; { vm_offset_t lastaddr; int seg, error; #ifdef DEBUG_DMA printf("dmamap_load: t=%p map=%p buf=%p len=%lx p=%p f=%d\n", t, map, buf, buflen, p, flags); #endif /* DEBUG_DMA */ /* * Make sure that on error condition we return "no valid mappings". */ map->dm_mapsize = 0; map->dm_nsegs = 0; if (buflen > map->_dm_size) return (EINVAL); seg = 0; error = integrator_bus_dmamap_load_buffer(t, map, buf, buflen, p, flags, &lastaddr, &seg, 1); if (error == 0) { map->dm_mapsize = buflen; map->dm_nsegs = seg + 1; map->_dm_origbuf = buf; map->_dm_buftype = ARM32_BUFTYPE_LINEAR; map->_dm_proc = p; } #ifdef DEBUG_DMA printf("dmamap_load: error=%d\n", error); #endif /* DEBUG_DMA */ return (error); } /* * Like _bus_dmamap_load(), but for mbufs. */ int integrator_bus_dmamap_load_mbuf(t, map, m0, flags) bus_dma_tag_t t; bus_dmamap_t map; struct mbuf *m0; int flags; { vm_offset_t lastaddr; int seg, error, first; struct mbuf *m; #ifdef DEBUG_DMA printf("dmamap_load_mbuf: t=%p map=%p m0=%p f=%d\n", t, map, m0, flags); #endif /* DEBUG_DMA */ /* * Make sure that on error condition we return "no valid mappings." */ map->dm_mapsize = 0; map->dm_nsegs = 0; #ifdef DIAGNOSTIC if ((m0->m_flags & M_PKTHDR) == 0) panic("integrator_bus_dmamap_load_mbuf: no packet header"); #endif /* DIAGNOSTIC */ if (m0->m_pkthdr.len > map->_dm_size) return (EINVAL); first = 1; seg = 0; error = 0; for (m = m0; m != NULL && error == 0; m = m->m_next) { error = integrator_bus_dmamap_load_buffer(t, map, m->m_data, m->m_len, NULL, flags, &lastaddr, &seg, first); first = 0; } if (error == 0) { map->dm_mapsize = m0->m_pkthdr.len; map->dm_nsegs = seg + 1; map->_dm_origbuf = m0; map->_dm_buftype = ARM32_BUFTYPE_MBUF; map->_dm_proc = NULL; /* always kernel */ } #ifdef DEBUG_DMA printf("dmamap_load_mbuf: error=%d\n", error); #endif /* DEBUG_DMA */ return (error); } /* * Like _bus_dmamap_load(), but for uios. */ int integrator_bus_dmamap_load_uio(t, map, uio, flags) bus_dma_tag_t t; bus_dmamap_t map; struct uio *uio; int flags; { vm_offset_t lastaddr; int seg, i, error, first; bus_size_t minlen, resid; struct proc *p = NULL; struct iovec *iov; caddr_t addr; /* * Make sure that on error condition we return "no valid mappings." */ map->dm_mapsize = 0; map->dm_nsegs = 0; resid = uio->uio_resid; iov = uio->uio_iov; if (uio->uio_segflg == UIO_USERSPACE) { p = uio->uio_procp; #ifdef DIAGNOSTIC if (p == NULL) panic("integrator_bus_dmamap_load_uio: USERSPACE but no proc"); #endif } first = 1; seg = 0; error = 0; for (i = 0; i < uio->uio_iovcnt && resid != 0 && error == 0; i++) { /* * Now at the first iovec to load. Load each iovec * until we have exhausted the residual count. */ minlen = resid < iov[i].iov_len ? resid : iov[i].iov_len; addr = (caddr_t)iov[i].iov_base; error = integrator_bus_dmamap_load_buffer(t, map, addr, minlen, p, flags, &lastaddr, &seg, first); first = 0; resid -= minlen; } if (error == 0) { map->dm_mapsize = uio->uio_resid; map->dm_nsegs = seg + 1; map->_dm_origbuf = uio; map->_dm_buftype = ARM32_BUFTYPE_UIO; map->_dm_proc = p; } return (error); } /* * Common function for DMA-safe memory allocation. May be called * by bus-specific DMA memory allocation functions. */ extern vm_offset_t physical_start; extern vm_offset_t physical_freestart; extern vm_offset_t physical_freeend; extern vm_offset_t physical_end; int integrator_bus_dmamem_alloc(t, size, alignment, boundary, segs, nsegs, rsegs, flags) bus_dma_tag_t t; bus_size_t size, alignment, boundary; bus_dma_segment_t *segs; int nsegs; int *rsegs; int flags; { int error; #ifdef DEBUG_DMA printf("dmamem_alloc t=%p size=%lx align=%lx boundary=%lx segs=%p nsegs=%x rsegs=%p flags=%x\n", t, size, alignment, boundary, segs, nsegs, rsegs, flags); #endif /* DEBUG_DMA */ error = (integrator_bus_dmamem_alloc_range(t, size, alignment, boundary, segs, nsegs, rsegs, flags, trunc_page(physical_start), trunc_page(physical_end))); #ifdef DEBUG_DMA printf("dmamem_alloc: =%d\n", error); #endif /* DEBUG_DMA */ return(error); } /* * Common function for freeing DMA-safe memory. May be called by * bus-specific DMA memory free functions. */ void integrator_bus_dmamem_free(t, segs, nsegs) bus_dma_tag_t t; bus_dma_segment_t *segs; int nsegs; { struct vm_page *m; bus_addr_t addr; struct pglist mlist; int curseg; #ifdef DEBUG_DMA printf("dmamem_free: t=%p segs=%p nsegs=%x\n", t, segs, nsegs); #endif /* DEBUG_DMA */ /* * Build a list of pages to free back to the VM system. */ TAILQ_INIT(&mlist); for (curseg = 0; curseg < nsegs; curseg++) { for (addr = segs[curseg].ds_addr; addr < (segs[curseg].ds_addr + segs[curseg].ds_len); addr += PAGE_SIZE) { m = PHYS_TO_VM_PAGE(CM_ALIAS_TO_LOCAL(addr)); TAILQ_INSERT_TAIL(&mlist, m, pageq); } } uvm_pglistfree(&mlist); } /* * Common function for mapping DMA-safe memory. May be called by * bus-specific DMA memory map functions. */ int integrator_bus_dmamem_map(t, segs, nsegs, size, kvap, flags) bus_dma_tag_t t; bus_dma_segment_t *segs; int nsegs; size_t size; caddr_t *kvap; int flags; { vm_offset_t va; bus_addr_t addr; int curseg; pt_entry_t *ptep/*, pte*/; #ifdef DEBUG_DMA printf("dmamem_map: t=%p segs=%p nsegs=%x size=%lx flags=%x\n", t, segs, nsegs, (unsigned long)size, flags); #endif /* DEBUG_DMA */ size = round_page(size); va = uvm_km_valloc(kernel_map, size); if (va == 0) return (ENOMEM); *kvap = (caddr_t)va; for (curseg = 0; curseg < nsegs; curseg++) { for (addr = segs[curseg].ds_addr; addr < (segs[curseg].ds_addr + segs[curseg].ds_len); addr += NBPG, va += NBPG, size -= NBPG) { #ifdef DEBUG_DMA printf("wiring p%lx to v%lx", CM_ALIAS_TO_LOCAL(addr), va); #endif /* DEBUG_DMA */ if (size == 0) panic("integrator_bus_dmamem_map: size botch"); pmap_enter(pmap_kernel(), va, CM_ALIAS_TO_LOCAL(addr), VM_PROT_READ | VM_PROT_WRITE, VM_PROT_READ | VM_PROT_WRITE | PMAP_WIRED); /* * If the memory must remain coherent with the * cache then we must make the memory uncacheable * in order to maintain virtual cache coherency. * We must also guarentee the cache does not already * contain the virtal addresses we are making * uncacheable. */ if (flags & BUS_DMA_COHERENT) { cpu_dcache_wbinv_range(va, NBPG); cpu_drain_writebuf(); ptep = vtopte(va); *ptep &= ~(L2_C | L2_B); tlb_flush(); } #ifdef DEBUG_DMA ptep = vtopte(va); printf(" pte=v%p *pte=%x\n", ptep, *ptep); #endif /* DEBUG_DMA */ } } pmap_update(pmap_kernel()); #ifdef DEBUG_DMA printf("dmamem_map: =%p\n", *kvap); #endif /* DEBUG_DMA */ return (0); } /* * Common functin for mmap(2)'ing DMA-safe memory. May be called by * bus-specific DMA mmap(2)'ing functions. */ paddr_t integrator_bus_dmamem_mmap(t, segs, nsegs, off, prot, flags) bus_dma_tag_t t; bus_dma_segment_t *segs; int nsegs; off_t off; int prot, flags; { int i; for (i = 0; i < nsegs; i++) { #ifdef DIAGNOSTIC if (off & PGOFSET) panic("integrator_bus_dmamem_mmap: offset unaligned"); if (segs[i].ds_addr & PGOFSET) panic("integrator_bus_dmamem_mmap: segment unaligned"); if (segs[i].ds_len & PGOFSET) panic("integrator_bus_dmamem_mmap: segment size not multiple" " of page size"); #endif /* DIAGNOSTIC */ if (off >= segs[i].ds_len) { off -= segs[i].ds_len; continue; } return arm_btop((u_long)CM_ALIAS_TO_LOCAL(segs[i].ds_addr) + off); } /* Page not found. */ return -1; } /********************************************************************** * DMA utility functions **********************************************************************/ /* * Utility function to load a linear buffer. lastaddrp holds state * between invocations (for multiple-buffer loads). segp contains * the starting segment on entrace, and the ending segment on exit. * first indicates if this is the first invocation of this function. */ static int integrator_bus_dmamap_load_buffer(t, map, buf, buflen, p, flags, lastaddrp, segp, first) bus_dma_tag_t t; bus_dmamap_t map; void *buf; bus_size_t buflen; struct proc *p; int flags; vm_offset_t *lastaddrp; int *segp; int first; { bus_size_t sgsize; bus_addr_t curaddr, lastaddr, baddr, bmask; vm_offset_t vaddr = (vm_offset_t)buf; int seg; pmap_t pmap; #ifdef DEBUG_DMA printf("integrator_bus_dmamem_load_buffer(buf=%p, len=%lx, flags=%d, 1st=%d)\n", buf, buflen, flags, first); #endif /* DEBUG_DMA */ if (p != NULL) pmap = p->p_vmspace->vm_map.pmap; else pmap = pmap_kernel(); lastaddr = *lastaddrp; bmask = ~(map->_dm_boundary - 1); for (seg = *segp; buflen > 0; ) { /* * Get the physical address for this segment. */ (void) pmap_extract(pmap, (vaddr_t)vaddr, &curaddr); /* * Make sure we're in an allowed DMA range. */ if (t->_ranges != NULL && integrator_bus_dma_inrange(t->_ranges, t->_nranges, curaddr) == 0) return (EINVAL); /* * Compute the segment size, and adjust counts. */ sgsize = NBPG - ((u_long)vaddr & PGOFSET); if (buflen < sgsize) sgsize = buflen; /* * Make sure we don't cross any boundaries. */ if (map->_dm_boundary > 0) { baddr = (curaddr + map->_dm_boundary) & bmask; if (sgsize > (baddr - curaddr)) sgsize = (baddr - curaddr); } /* * Insert chunk into a segment, coalescing with * previous segment if possible. */ if (first) { map->dm_segs[seg].ds_addr = LOCAL_TO_CM_ALIAS(curaddr); map->dm_segs[seg].ds_len = sgsize; first = 0; } else { if (curaddr == lastaddr && (map->dm_segs[seg].ds_len + sgsize) <= map->_dm_maxsegsz && (map->_dm_boundary == 0 || (map->dm_segs[seg].ds_addr & bmask) == (LOCAL_TO_CM_ALIAS(curaddr) & bmask))) map->dm_segs[seg].ds_len += sgsize; else { if (++seg >= map->_dm_segcnt) break; map->dm_segs[seg].ds_addr = LOCAL_TO_CM_ALIAS(curaddr); map->dm_segs[seg].ds_len = sgsize; } } lastaddr = curaddr + sgsize; vaddr += sgsize; buflen -= sgsize; } *segp = seg; *lastaddrp = lastaddr; /* * Did we fit? */ if (buflen != 0) return (EFBIG); /* XXX better return value here? */ return (0); } /* * Check to see if the specified page is in an allowed DMA range. */ static int integrator_bus_dma_inrange(ranges, nranges, curaddr) bus_dma_segment_t *ranges; int nranges; bus_addr_t curaddr; { bus_dma_segment_t *ds; int i; for (i = 0, ds = ranges; i < nranges; i++, ds++) { if (curaddr >= CM_ALIAS_TO_LOCAL(ds->ds_addr) && round_page(curaddr) <= (CM_ALIAS_TO_LOCAL(ds->ds_addr) + ds->ds_len)) return (1); } return (0); } /* * Allocate physical memory from the given physical address range. * Called by DMA-safe memory allocation methods. */ int integrator_bus_dmamem_alloc_range(t, size, alignment, boundary, segs, nsegs, rsegs, flags, low, high) bus_dma_tag_t t; bus_size_t size, alignment, boundary; bus_dma_segment_t *segs; int nsegs; int *rsegs; int flags; vm_offset_t low; vm_offset_t high; { vm_offset_t curaddr, lastaddr; struct vm_page *m; struct pglist mlist; int curseg, error; #ifdef DEBUG_DMA printf("alloc_range: t=%p size=%lx align=%lx boundary=%lx segs=%p nsegs=%x rsegs=%p flags=%x lo=%lx hi=%lx\n", t, size, alignment, boundary, segs, nsegs, rsegs, flags, low, high); #endif /* DEBUG_DMA */ /* Always round the size. */ size = round_page(size); /* * Allocate pages from the VM system. */ TAILQ_INIT(&mlist); error = uvm_pglistalloc(size, low, high, alignment, boundary, &mlist, nsegs, (flags & BUS_DMA_NOWAIT) == 0); if (error) return (error); /* * Compute the location, size, and number of segments actually * returned by the VM code. */ m = mlist.tqh_first; curseg = 0; lastaddr = VM_PAGE_TO_PHYS(m); segs[curseg].ds_addr = LOCAL_TO_CM_ALIAS(lastaddr); segs[curseg].ds_len = PAGE_SIZE; #ifdef DEBUG_DMA printf("alloc: page %lx\n", lastaddr); #endif /* DEBUG_DMA */ m = m->pageq.tqe_next; for (; m != NULL; m = m->pageq.tqe_next) { curaddr = VM_PAGE_TO_PHYS(m); #ifdef DIAGNOSTIC if (curaddr < low || curaddr >= high) { printf("uvm_pglistalloc returned non-sensical" " address 0x%lx\n", curaddr); panic("integrator_bus_dmamem_alloc_range"); } #endif /* DIAGNOSTIC */ #ifdef DEBUG_DMA printf("alloc: page %lx\n", curaddr); #endif /* DEBUG_DMA */ if (curaddr == (lastaddr + PAGE_SIZE)) segs[curseg].ds_len += PAGE_SIZE; else { curseg++; segs[curseg].ds_addr = LOCAL_TO_CM_ALIAS(curaddr); segs[curseg].ds_len = PAGE_SIZE; } lastaddr = curaddr; } *rsegs = curseg + 1; return (0); }
576296.c
/* * IBM Hot Plug Controller Driver * * Written By: Jyoti Shah, IBM Corporation * * Copyright (C) 2001-2003 IBM Corp. * * 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, GOOD TITLE or * NON INFRINGEMENT. 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. * * Send feedback to <[email protected]> * <[email protected]> * */ #include <linux/wait.h> #include <linux/time.h> #include <linux/delay.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/mutex.h> #include <linux/sched.h> #include <linux/semaphore.h> #include <linux/kthread.h> #include "ibmphp.h" static int to_debug = 0; #define debug_polling(fmt, arg...) do { if (to_debug) debug (fmt, arg); } while (0) //---------------------------------------------------------------------------- // timeout values //---------------------------------------------------------------------------- #define CMD_COMPLETE_TOUT_SEC 60 // give HPC 60 sec to finish cmd #define HPC_CTLR_WORKING_TOUT 60 // give HPC 60 sec to finish cmd #define HPC_GETACCESS_TIMEOUT 60 // seconds #define POLL_INTERVAL_SEC 2 // poll HPC every 2 seconds #define POLL_LATCH_CNT 5 // poll latch 5 times, then poll slots //---------------------------------------------------------------------------- // Winnipeg Architected Register Offsets //---------------------------------------------------------------------------- #define WPG_I2CMBUFL_OFFSET 0x08 // I2C Message Buffer Low #define WPG_I2CMOSUP_OFFSET 0x10 // I2C Master Operation Setup Reg #define WPG_I2CMCNTL_OFFSET 0x20 // I2C Master Control Register #define WPG_I2CPARM_OFFSET 0x40 // I2C Parameter Register #define WPG_I2CSTAT_OFFSET 0x70 // I2C Status Register //---------------------------------------------------------------------------- // Winnipeg Store Type commands (Add this commands to the register offset) //---------------------------------------------------------------------------- #define WPG_I2C_AND 0x1000 // I2C AND operation #define WPG_I2C_OR 0x2000 // I2C OR operation //---------------------------------------------------------------------------- // Command set for I2C Master Operation Setup Register //---------------------------------------------------------------------------- #define WPG_READATADDR_MASK 0x00010000 // read,bytes,I2C shifted,index #define WPG_WRITEATADDR_MASK 0x40010000 // write,bytes,I2C shifted,index #define WPG_READDIRECT_MASK 0x10010000 #define WPG_WRITEDIRECT_MASK 0x60010000 //---------------------------------------------------------------------------- // bit masks for I2C Master Control Register //---------------------------------------------------------------------------- #define WPG_I2CMCNTL_STARTOP_MASK 0x00000002 // Start the Operation //---------------------------------------------------------------------------- // //---------------------------------------------------------------------------- #define WPG_I2C_IOREMAP_SIZE 0x2044 // size of linear address interval //---------------------------------------------------------------------------- // command index //---------------------------------------------------------------------------- #define WPG_1ST_SLOT_INDEX 0x01 // index - 1st slot for ctlr #define WPG_CTLR_INDEX 0x0F // index - ctlr #define WPG_1ST_EXTSLOT_INDEX 0x10 // index - 1st ext slot for ctlr #define WPG_1ST_BUS_INDEX 0x1F // index - 1st bus for ctlr //---------------------------------------------------------------------------- // macro utilities //---------------------------------------------------------------------------- // if bits 20,22,25,26,27,29,30 are OFF return 1 #define HPC_I2CSTATUS_CHECK(s) ((u8)((s & 0x00000A76) ? 0 : 1)) //---------------------------------------------------------------------------- // global variables //---------------------------------------------------------------------------- static struct mutex sem_hpcaccess; // lock access to HPC static struct semaphore semOperations; // lock all operations and // access to data structures static struct semaphore sem_exit; // make sure polling thread goes away static struct task_struct *ibmphp_poll_thread; //---------------------------------------------------------------------------- // local function prototypes //---------------------------------------------------------------------------- static u8 i2c_ctrl_read (struct controller *, void __iomem *, u8); static u8 i2c_ctrl_write (struct controller *, void __iomem *, u8, u8); static u8 hpc_writecmdtoindex (u8, u8); static u8 hpc_readcmdtoindex (u8, u8); static void get_hpc_access (void); static void free_hpc_access (void); static int poll_hpc(void *data); static int process_changeinstatus (struct slot *, struct slot *); static int process_changeinlatch (u8, u8, struct controller *); static int hpc_wait_ctlr_notworking (int, struct controller *, void __iomem *, u8 *); //---------------------------------------------------------------------------- /*---------------------------------------------------------------------- * Name: ibmphp_hpc_initvars * * Action: initialize semaphores and variables *---------------------------------------------------------------------*/ void __init ibmphp_hpc_initvars (void) { debug ("%s - Entry\n", __func__); mutex_init(&sem_hpcaccess); sema_init(&semOperations, 1); sema_init(&sem_exit, 0); to_debug = 0; debug ("%s - Exit\n", __func__); } /*---------------------------------------------------------------------- * Name: i2c_ctrl_read * * Action: read from HPC over I2C * *---------------------------------------------------------------------*/ static u8 i2c_ctrl_read (struct controller *ctlr_ptr, void __iomem *WPGBbar, u8 index) { u8 status; int i; void __iomem *wpg_addr; // base addr + offset unsigned long wpg_data; // data to/from WPG LOHI format unsigned long ultemp; unsigned long data; // actual data HILO format debug_polling ("%s - Entry WPGBbar[%p] index[%x] \n", __func__, WPGBbar, index); //-------------------------------------------------------------------- // READ - step 1 // read at address, byte length, I2C address (shifted), index // or read direct, byte length, index if (ctlr_ptr->ctlr_type == 0x02) { data = WPG_READATADDR_MASK; // fill in I2C address ultemp = (unsigned long)ctlr_ptr->u.wpeg_ctlr.i2c_addr; ultemp = ultemp >> 1; data |= (ultemp << 8); // fill in index data |= (unsigned long)index; } else if (ctlr_ptr->ctlr_type == 0x04) { data = WPG_READDIRECT_MASK; // fill in index ultemp = (unsigned long)index; ultemp = ultemp << 8; data |= ultemp; } else { err ("this controller type is not supported \n"); return HPC_ERROR; } wpg_data = swab32 (data); // swap data before writing wpg_addr = WPGBbar + WPG_I2CMOSUP_OFFSET; writel (wpg_data, wpg_addr); //-------------------------------------------------------------------- // READ - step 2 : clear the message buffer data = 0x00000000; wpg_data = swab32 (data); wpg_addr = WPGBbar + WPG_I2CMBUFL_OFFSET; writel (wpg_data, wpg_addr); //-------------------------------------------------------------------- // READ - step 3 : issue start operation, I2C master control bit 30:ON // 2020 : [20] OR operation at [20] offset 0x20 data = WPG_I2CMCNTL_STARTOP_MASK; wpg_data = swab32 (data); wpg_addr = WPGBbar + WPG_I2CMCNTL_OFFSET + WPG_I2C_OR; writel (wpg_data, wpg_addr); //-------------------------------------------------------------------- // READ - step 4 : wait until start operation bit clears i = CMD_COMPLETE_TOUT_SEC; while (i) { msleep(10); wpg_addr = WPGBbar + WPG_I2CMCNTL_OFFSET; wpg_data = readl (wpg_addr); data = swab32 (wpg_data); if (!(data & WPG_I2CMCNTL_STARTOP_MASK)) break; i--; } if (i == 0) { debug ("%s - Error : WPG timeout\n", __func__); return HPC_ERROR; } //-------------------------------------------------------------------- // READ - step 5 : read I2C status register i = CMD_COMPLETE_TOUT_SEC; while (i) { msleep(10); wpg_addr = WPGBbar + WPG_I2CSTAT_OFFSET; wpg_data = readl (wpg_addr); data = swab32 (wpg_data); if (HPC_I2CSTATUS_CHECK (data)) break; i--; } if (i == 0) { debug ("ctrl_read - Exit Error:I2C timeout\n"); return HPC_ERROR; } //-------------------------------------------------------------------- // READ - step 6 : get DATA wpg_addr = WPGBbar + WPG_I2CMBUFL_OFFSET; wpg_data = readl (wpg_addr); data = swab32 (wpg_data); status = (u8) data; debug_polling ("%s - Exit index[%x] status[%x]\n", __func__, index, status); return (status); } /*---------------------------------------------------------------------- * Name: i2c_ctrl_write * * Action: write to HPC over I2C * * Return 0 or error codes *---------------------------------------------------------------------*/ static u8 i2c_ctrl_write (struct controller *ctlr_ptr, void __iomem *WPGBbar, u8 index, u8 cmd) { u8 rc; void __iomem *wpg_addr; // base addr + offset unsigned long wpg_data; // data to/from WPG LOHI format unsigned long ultemp; unsigned long data; // actual data HILO format int i; debug_polling ("%s - Entry WPGBbar[%p] index[%x] cmd[%x]\n", __func__, WPGBbar, index, cmd); rc = 0; //-------------------------------------------------------------------- // WRITE - step 1 // write at address, byte length, I2C address (shifted), index // or write direct, byte length, index data = 0x00000000; if (ctlr_ptr->ctlr_type == 0x02) { data = WPG_WRITEATADDR_MASK; // fill in I2C address ultemp = (unsigned long)ctlr_ptr->u.wpeg_ctlr.i2c_addr; ultemp = ultemp >> 1; data |= (ultemp << 8); // fill in index data |= (unsigned long)index; } else if (ctlr_ptr->ctlr_type == 0x04) { data = WPG_WRITEDIRECT_MASK; // fill in index ultemp = (unsigned long)index; ultemp = ultemp << 8; data |= ultemp; } else { err ("this controller type is not supported \n"); return HPC_ERROR; } wpg_data = swab32 (data); // swap data before writing wpg_addr = WPGBbar + WPG_I2CMOSUP_OFFSET; writel (wpg_data, wpg_addr); //-------------------------------------------------------------------- // WRITE - step 2 : clear the message buffer data = 0x00000000 | (unsigned long)cmd; wpg_data = swab32 (data); wpg_addr = WPGBbar + WPG_I2CMBUFL_OFFSET; writel (wpg_data, wpg_addr); //-------------------------------------------------------------------- // WRITE - step 3 : issue start operation,I2C master control bit 30:ON // 2020 : [20] OR operation at [20] offset 0x20 data = WPG_I2CMCNTL_STARTOP_MASK; wpg_data = swab32 (data); wpg_addr = WPGBbar + WPG_I2CMCNTL_OFFSET + WPG_I2C_OR; writel (wpg_data, wpg_addr); //-------------------------------------------------------------------- // WRITE - step 4 : wait until start operation bit clears i = CMD_COMPLETE_TOUT_SEC; while (i) { msleep(10); wpg_addr = WPGBbar + WPG_I2CMCNTL_OFFSET; wpg_data = readl (wpg_addr); data = swab32 (wpg_data); if (!(data & WPG_I2CMCNTL_STARTOP_MASK)) break; i--; } if (i == 0) { debug ("%s - Exit Error:WPG timeout\n", __func__); rc = HPC_ERROR; } //-------------------------------------------------------------------- // WRITE - step 5 : read I2C status register i = CMD_COMPLETE_TOUT_SEC; while (i) { msleep(10); wpg_addr = WPGBbar + WPG_I2CSTAT_OFFSET; wpg_data = readl (wpg_addr); data = swab32 (wpg_data); if (HPC_I2CSTATUS_CHECK (data)) break; i--; } if (i == 0) { debug ("ctrl_read - Error : I2C timeout\n"); rc = HPC_ERROR; } debug_polling ("%s Exit rc[%x]\n", __func__, rc); return (rc); } //------------------------------------------------------------ // Read from ISA type HPC //------------------------------------------------------------ static u8 isa_ctrl_read (struct controller *ctlr_ptr, u8 offset) { u16 start_address; u16 end_address; u8 data; start_address = ctlr_ptr->u.isa_ctlr.io_start; end_address = ctlr_ptr->u.isa_ctlr.io_end; data = inb (start_address + offset); return data; } //-------------------------------------------------------------- // Write to ISA type HPC //-------------------------------------------------------------- static void isa_ctrl_write (struct controller *ctlr_ptr, u8 offset, u8 data) { u16 start_address; u16 port_address; start_address = ctlr_ptr->u.isa_ctlr.io_start; port_address = start_address + (u16) offset; outb (data, port_address); } static u8 pci_ctrl_read (struct controller *ctrl, u8 offset) { u8 data = 0x00; debug ("inside pci_ctrl_read\n"); if (ctrl->ctrl_dev) pci_read_config_byte (ctrl->ctrl_dev, HPC_PCI_OFFSET + offset, &data); return data; } static u8 pci_ctrl_write (struct controller *ctrl, u8 offset, u8 data) { u8 rc = -ENODEV; debug ("inside pci_ctrl_write\n"); if (ctrl->ctrl_dev) { pci_write_config_byte (ctrl->ctrl_dev, HPC_PCI_OFFSET + offset, data); rc = 0; } return rc; } static u8 ctrl_read (struct controller *ctlr, void __iomem *base, u8 offset) { u8 rc; switch (ctlr->ctlr_type) { case 0: rc = isa_ctrl_read (ctlr, offset); break; case 1: rc = pci_ctrl_read (ctlr, offset); break; case 2: case 4: rc = i2c_ctrl_read (ctlr, base, offset); break; default: return -ENODEV; } return rc; } static u8 ctrl_write (struct controller *ctlr, void __iomem *base, u8 offset, u8 data) { u8 rc = 0; switch (ctlr->ctlr_type) { case 0: isa_ctrl_write(ctlr, offset, data); break; case 1: rc = pci_ctrl_write (ctlr, offset, data); break; case 2: case 4: rc = i2c_ctrl_write(ctlr, base, offset, data); break; default: return -ENODEV; } return rc; } /*---------------------------------------------------------------------- * Name: hpc_writecmdtoindex() * * Action: convert a write command to proper index within a controller * * Return index, HPC_ERROR *---------------------------------------------------------------------*/ static u8 hpc_writecmdtoindex (u8 cmd, u8 index) { u8 rc; switch (cmd) { case HPC_CTLR_ENABLEIRQ: // 0x00.N.15 case HPC_CTLR_CLEARIRQ: // 0x06.N.15 case HPC_CTLR_RESET: // 0x07.N.15 case HPC_CTLR_IRQSTEER: // 0x08.N.15 case HPC_CTLR_DISABLEIRQ: // 0x01.N.15 case HPC_ALLSLOT_ON: // 0x11.N.15 case HPC_ALLSLOT_OFF: // 0x12.N.15 rc = 0x0F; break; case HPC_SLOT_OFF: // 0x02.Y.0-14 case HPC_SLOT_ON: // 0x03.Y.0-14 case HPC_SLOT_ATTNOFF: // 0x04.N.0-14 case HPC_SLOT_ATTNON: // 0x05.N.0-14 case HPC_SLOT_BLINKLED: // 0x13.N.0-14 rc = index; break; case HPC_BUS_33CONVMODE: case HPC_BUS_66CONVMODE: case HPC_BUS_66PCIXMODE: case HPC_BUS_100PCIXMODE: case HPC_BUS_133PCIXMODE: rc = index + WPG_1ST_BUS_INDEX - 1; break; default: err ("hpc_writecmdtoindex - Error invalid cmd[%x]\n", cmd); rc = HPC_ERROR; } return rc; } /*---------------------------------------------------------------------- * Name: hpc_readcmdtoindex() * * Action: convert a read command to proper index within a controller * * Return index, HPC_ERROR *---------------------------------------------------------------------*/ static u8 hpc_readcmdtoindex (u8 cmd, u8 index) { u8 rc; switch (cmd) { case READ_CTLRSTATUS: rc = 0x0F; break; case READ_SLOTSTATUS: case READ_ALLSTAT: rc = index; break; case READ_EXTSLOTSTATUS: rc = index + WPG_1ST_EXTSLOT_INDEX; break; case READ_BUSSTATUS: rc = index + WPG_1ST_BUS_INDEX - 1; break; case READ_SLOTLATCHLOWREG: rc = 0x28; break; case READ_REVLEVEL: rc = 0x25; break; case READ_HPCOPTIONS: rc = 0x27; break; default: rc = HPC_ERROR; } return rc; } /*---------------------------------------------------------------------- * Name: HPCreadslot() * * Action: issue a READ command to HPC * * Input: pslot - cannot be NULL for READ_ALLSTAT * pstatus - can be NULL for READ_ALLSTAT * * Return 0 or error codes *---------------------------------------------------------------------*/ int ibmphp_hpc_readslot (struct slot * pslot, u8 cmd, u8 * pstatus) { void __iomem *wpg_bbar = NULL; struct controller *ctlr_ptr; struct list_head *pslotlist; u8 index, status; int rc = 0; int busindex; debug_polling ("%s - Entry pslot[%p] cmd[%x] pstatus[%p]\n", __func__, pslot, cmd, pstatus); if ((pslot == NULL) || ((pstatus == NULL) && (cmd != READ_ALLSTAT) && (cmd != READ_BUSSTATUS))) { rc = -EINVAL; err ("%s - Error invalid pointer, rc[%d]\n", __func__, rc); return rc; } if (cmd == READ_BUSSTATUS) { busindex = ibmphp_get_bus_index (pslot->bus); if (busindex < 0) { rc = -EINVAL; err ("%s - Exit Error:invalid bus, rc[%d]\n", __func__, rc); return rc; } else index = (u8) busindex; } else index = pslot->ctlr_index; index = hpc_readcmdtoindex (cmd, index); if (index == HPC_ERROR) { rc = -EINVAL; err ("%s - Exit Error:invalid index, rc[%d]\n", __func__, rc); return rc; } ctlr_ptr = pslot->ctrl; get_hpc_access (); //-------------------------------------------------------------------- // map physical address to logical address //-------------------------------------------------------------------- if ((ctlr_ptr->ctlr_type == 2) || (ctlr_ptr->ctlr_type == 4)) wpg_bbar = ioremap (ctlr_ptr->u.wpeg_ctlr.wpegbbar, WPG_I2C_IOREMAP_SIZE); //-------------------------------------------------------------------- // check controller status before reading //-------------------------------------------------------------------- rc = hpc_wait_ctlr_notworking (HPC_CTLR_WORKING_TOUT, ctlr_ptr, wpg_bbar, &status); if (!rc) { switch (cmd) { case READ_ALLSTAT: // update the slot structure pslot->ctrl->status = status; pslot->status = ctrl_read (ctlr_ptr, wpg_bbar, index); rc = hpc_wait_ctlr_notworking (HPC_CTLR_WORKING_TOUT, ctlr_ptr, wpg_bbar, &status); if (!rc) pslot->ext_status = ctrl_read (ctlr_ptr, wpg_bbar, index + WPG_1ST_EXTSLOT_INDEX); break; case READ_SLOTSTATUS: // DO NOT update the slot structure *pstatus = ctrl_read (ctlr_ptr, wpg_bbar, index); break; case READ_EXTSLOTSTATUS: // DO NOT update the slot structure *pstatus = ctrl_read (ctlr_ptr, wpg_bbar, index); break; case READ_CTLRSTATUS: // DO NOT update the slot structure *pstatus = status; break; case READ_BUSSTATUS: pslot->busstatus = ctrl_read (ctlr_ptr, wpg_bbar, index); break; case READ_REVLEVEL: *pstatus = ctrl_read (ctlr_ptr, wpg_bbar, index); break; case READ_HPCOPTIONS: *pstatus = ctrl_read (ctlr_ptr, wpg_bbar, index); break; case READ_SLOTLATCHLOWREG: // DO NOT update the slot structure *pstatus = ctrl_read (ctlr_ptr, wpg_bbar, index); break; // Not used case READ_ALLSLOT: list_for_each (pslotlist, &ibmphp_slot_head) { pslot = list_entry (pslotlist, struct slot, ibm_slot_list); index = pslot->ctlr_index; rc = hpc_wait_ctlr_notworking (HPC_CTLR_WORKING_TOUT, ctlr_ptr, wpg_bbar, &status); if (!rc) { pslot->status = ctrl_read (ctlr_ptr, wpg_bbar, index); rc = hpc_wait_ctlr_notworking (HPC_CTLR_WORKING_TOUT, ctlr_ptr, wpg_bbar, &status); if (!rc) pslot->ext_status = ctrl_read (ctlr_ptr, wpg_bbar, index + WPG_1ST_EXTSLOT_INDEX); } else { err ("%s - Error ctrl_read failed\n", __func__); rc = -EINVAL; break; } } break; default: rc = -EINVAL; break; } } //-------------------------------------------------------------------- // cleanup //-------------------------------------------------------------------- // remove physical to logical address mapping if ((ctlr_ptr->ctlr_type == 2) || (ctlr_ptr->ctlr_type == 4)) iounmap (wpg_bbar); free_hpc_access (); debug_polling ("%s - Exit rc[%d]\n", __func__, rc); return rc; } /*---------------------------------------------------------------------- * Name: ibmphp_hpc_writeslot() * * Action: issue a WRITE command to HPC *---------------------------------------------------------------------*/ int ibmphp_hpc_writeslot (struct slot * pslot, u8 cmd) { void __iomem *wpg_bbar = NULL; struct controller *ctlr_ptr; u8 index, status; int busindex; u8 done; int rc = 0; int timeout; debug_polling ("%s - Entry pslot[%p] cmd[%x]\n", __func__, pslot, cmd); if (pslot == NULL) { rc = -EINVAL; err ("%s - Error Exit rc[%d]\n", __func__, rc); return rc; } if ((cmd == HPC_BUS_33CONVMODE) || (cmd == HPC_BUS_66CONVMODE) || (cmd == HPC_BUS_66PCIXMODE) || (cmd == HPC_BUS_100PCIXMODE) || (cmd == HPC_BUS_133PCIXMODE)) { busindex = ibmphp_get_bus_index (pslot->bus); if (busindex < 0) { rc = -EINVAL; err ("%s - Exit Error:invalid bus, rc[%d]\n", __func__, rc); return rc; } else index = (u8) busindex; } else index = pslot->ctlr_index; index = hpc_writecmdtoindex (cmd, index); if (index == HPC_ERROR) { rc = -EINVAL; err ("%s - Error Exit rc[%d]\n", __func__, rc); return rc; } ctlr_ptr = pslot->ctrl; get_hpc_access (); //-------------------------------------------------------------------- // map physical address to logical address //-------------------------------------------------------------------- if ((ctlr_ptr->ctlr_type == 2) || (ctlr_ptr->ctlr_type == 4)) { wpg_bbar = ioremap (ctlr_ptr->u.wpeg_ctlr.wpegbbar, WPG_I2C_IOREMAP_SIZE); debug ("%s - ctlr id[%x] physical[%lx] logical[%lx] i2c[%x]\n", __func__, ctlr_ptr->ctlr_id, (ulong) (ctlr_ptr->u.wpeg_ctlr.wpegbbar), (ulong) wpg_bbar, ctlr_ptr->u.wpeg_ctlr.i2c_addr); } //-------------------------------------------------------------------- // check controller status before writing //-------------------------------------------------------------------- rc = hpc_wait_ctlr_notworking (HPC_CTLR_WORKING_TOUT, ctlr_ptr, wpg_bbar, &status); if (!rc) { ctrl_write (ctlr_ptr, wpg_bbar, index, cmd); //-------------------------------------------------------------------- // check controller is still not working on the command //-------------------------------------------------------------------- timeout = CMD_COMPLETE_TOUT_SEC; done = 0; while (!done) { rc = hpc_wait_ctlr_notworking (HPC_CTLR_WORKING_TOUT, ctlr_ptr, wpg_bbar, &status); if (!rc) { if (NEEDTOCHECK_CMDSTATUS (cmd)) { if (CTLR_FINISHED (status) == HPC_CTLR_FINISHED_YES) done = 1; } else done = 1; } if (!done) { msleep(1000); if (timeout < 1) { done = 1; err ("%s - Error command complete timeout\n", __func__); rc = -EFAULT; } else timeout--; } } ctlr_ptr->status = status; } // cleanup // remove physical to logical address mapping if ((ctlr_ptr->ctlr_type == 2) || (ctlr_ptr->ctlr_type == 4)) iounmap (wpg_bbar); free_hpc_access (); debug_polling ("%s - Exit rc[%d]\n", __func__, rc); return rc; } /*---------------------------------------------------------------------- * Name: get_hpc_access() * * Action: make sure only one process can access HPC at one time *---------------------------------------------------------------------*/ static void get_hpc_access (void) { mutex_lock(&sem_hpcaccess); } /*---------------------------------------------------------------------- * Name: free_hpc_access() *---------------------------------------------------------------------*/ void free_hpc_access (void) { mutex_unlock(&sem_hpcaccess); } /*---------------------------------------------------------------------- * Name: ibmphp_lock_operations() * * Action: make sure only one process can change the data structure *---------------------------------------------------------------------*/ void ibmphp_lock_operations (void) { down (&semOperations); to_debug = 1; } /*---------------------------------------------------------------------- * Name: ibmphp_unlock_operations() *---------------------------------------------------------------------*/ void ibmphp_unlock_operations (void) { debug ("%s - Entry\n", __func__); up (&semOperations); to_debug = 0; debug ("%s - Exit\n", __func__); } /*---------------------------------------------------------------------- * Name: poll_hpc() *---------------------------------------------------------------------*/ #define POLL_LATCH_REGISTER 0 #define POLL_SLOTS 1 #define POLL_SLEEP 2 static int poll_hpc(void *data) { struct slot myslot; struct slot *pslot = NULL; struct list_head *pslotlist; int rc; int poll_state = POLL_LATCH_REGISTER; u8 oldlatchlow = 0x00; u8 curlatchlow = 0x00; int poll_count = 0; u8 ctrl_count = 0x00; debug ("%s - Entry\n", __func__); while (!kthread_should_stop()) { /* try to get the lock to do some kind of hardware access */ down (&semOperations); switch (poll_state) { case POLL_LATCH_REGISTER: oldlatchlow = curlatchlow; ctrl_count = 0x00; list_for_each (pslotlist, &ibmphp_slot_head) { if (ctrl_count >= ibmphp_get_total_controllers()) break; pslot = list_entry (pslotlist, struct slot, ibm_slot_list); if (pslot->ctrl->ctlr_relative_id == ctrl_count) { ctrl_count++; if (READ_SLOT_LATCH (pslot->ctrl)) { rc = ibmphp_hpc_readslot (pslot, READ_SLOTLATCHLOWREG, &curlatchlow); if (oldlatchlow != curlatchlow) process_changeinlatch (oldlatchlow, curlatchlow, pslot->ctrl); } } } ++poll_count; poll_state = POLL_SLEEP; break; case POLL_SLOTS: list_for_each (pslotlist, &ibmphp_slot_head) { pslot = list_entry (pslotlist, struct slot, ibm_slot_list); // make a copy of the old status memcpy ((void *) &myslot, (void *) pslot, sizeof (struct slot)); rc = ibmphp_hpc_readslot (pslot, READ_ALLSTAT, NULL); if ((myslot.status != pslot->status) || (myslot.ext_status != pslot->ext_status)) process_changeinstatus (pslot, &myslot); } ctrl_count = 0x00; list_for_each (pslotlist, &ibmphp_slot_head) { if (ctrl_count >= ibmphp_get_total_controllers()) break; pslot = list_entry (pslotlist, struct slot, ibm_slot_list); if (pslot->ctrl->ctlr_relative_id == ctrl_count) { ctrl_count++; if (READ_SLOT_LATCH (pslot->ctrl)) rc = ibmphp_hpc_readslot (pslot, READ_SLOTLATCHLOWREG, &curlatchlow); } } ++poll_count; poll_state = POLL_SLEEP; break; case POLL_SLEEP: /* don't sleep with a lock on the hardware */ up (&semOperations); msleep(POLL_INTERVAL_SEC * 1000); if (kthread_should_stop()) goto out_sleep; down (&semOperations); if (poll_count >= POLL_LATCH_CNT) { poll_count = 0; poll_state = POLL_SLOTS; } else poll_state = POLL_LATCH_REGISTER; break; } /* give up the hardware semaphore */ up (&semOperations); /* sleep for a short time just for good measure */ out_sleep: msleep(100); } up (&sem_exit); debug ("%s - Exit\n", __func__); return 0; } /*---------------------------------------------------------------------- * Name: process_changeinstatus * * Action: compare old and new slot status, process the change in status * * Input: pointer to slot struct, old slot struct * * Return 0 or error codes * Value: * * Side * Effects: None. * * Notes: *---------------------------------------------------------------------*/ static int process_changeinstatus (struct slot *pslot, struct slot *poldslot) { u8 status; int rc = 0; u8 disable = 0; u8 update = 0; debug ("process_changeinstatus - Entry pslot[%p], poldslot[%p]\n", pslot, poldslot); // bit 0 - HPC_SLOT_POWER if ((pslot->status & 0x01) != (poldslot->status & 0x01)) update = 1; // bit 1 - HPC_SLOT_CONNECT // ignore // bit 2 - HPC_SLOT_ATTN if ((pslot->status & 0x04) != (poldslot->status & 0x04)) update = 1; // bit 3 - HPC_SLOT_PRSNT2 // bit 4 - HPC_SLOT_PRSNT1 if (((pslot->status & 0x08) != (poldslot->status & 0x08)) || ((pslot->status & 0x10) != (poldslot->status & 0x10))) update = 1; // bit 5 - HPC_SLOT_PWRGD if ((pslot->status & 0x20) != (poldslot->status & 0x20)) // OFF -> ON: ignore, ON -> OFF: disable slot if ((poldslot->status & 0x20) && (SLOT_CONNECT (poldslot->status) == HPC_SLOT_CONNECTED) && (SLOT_PRESENT (poldslot->status))) disable = 1; // bit 6 - HPC_SLOT_BUS_SPEED // ignore // bit 7 - HPC_SLOT_LATCH if ((pslot->status & 0x80) != (poldslot->status & 0x80)) { update = 1; // OPEN -> CLOSE if (pslot->status & 0x80) { if (SLOT_PWRGD (pslot->status)) { // power goes on and off after closing latch // check again to make sure power is still ON msleep(1000); rc = ibmphp_hpc_readslot (pslot, READ_SLOTSTATUS, &status); if (SLOT_PWRGD (status)) update = 1; else // overwrite power in pslot to OFF pslot->status &= ~HPC_SLOT_POWER; } } // CLOSE -> OPEN else if ((SLOT_PWRGD (poldslot->status) == HPC_SLOT_PWRGD_GOOD) && (SLOT_CONNECT (poldslot->status) == HPC_SLOT_CONNECTED) && (SLOT_PRESENT (poldslot->status))) { disable = 1; } // else - ignore } // bit 4 - HPC_SLOT_BLINK_ATTN if ((pslot->ext_status & 0x08) != (poldslot->ext_status & 0x08)) update = 1; if (disable) { debug ("process_changeinstatus - disable slot\n"); pslot->flag = 0; rc = ibmphp_do_disable_slot (pslot); } if (update || disable) { ibmphp_update_slot_info (pslot); } debug ("%s - Exit rc[%d] disable[%x] update[%x]\n", __func__, rc, disable, update); return rc; } /*---------------------------------------------------------------------- * Name: process_changeinlatch * * Action: compare old and new latch reg status, process the change * * Input: old and current latch register status * * Return 0 or error codes * Value: *---------------------------------------------------------------------*/ static int process_changeinlatch (u8 old, u8 new, struct controller *ctrl) { struct slot myslot, *pslot; u8 i; u8 mask; int rc = 0; debug ("%s - Entry old[%x], new[%x]\n", __func__, old, new); // bit 0 reserved, 0 is LSB, check bit 1-6 for 6 slots for (i = ctrl->starting_slot_num; i <= ctrl->ending_slot_num; i++) { mask = 0x01 << i; if ((mask & old) != (mask & new)) { pslot = ibmphp_get_slot_from_physical_num (i); if (pslot) { memcpy ((void *) &myslot, (void *) pslot, sizeof (struct slot)); rc = ibmphp_hpc_readslot (pslot, READ_ALLSTAT, NULL); debug ("%s - call process_changeinstatus for slot[%d]\n", __func__, i); process_changeinstatus (pslot, &myslot); } else { rc = -EINVAL; err ("%s - Error bad pointer for slot[%d]\n", __func__, i); } } } debug ("%s - Exit rc[%d]\n", __func__, rc); return rc; } /*---------------------------------------------------------------------- * Name: ibmphp_hpc_start_poll_thread * * Action: start polling thread *---------------------------------------------------------------------*/ int __init ibmphp_hpc_start_poll_thread (void) { debug ("%s - Entry\n", __func__); ibmphp_poll_thread = kthread_run(poll_hpc, NULL, "hpc_poll"); if (IS_ERR(ibmphp_poll_thread)) { err ("%s - Error, thread not started\n", __func__); return PTR_ERR(ibmphp_poll_thread); } return 0; } /*---------------------------------------------------------------------- * Name: ibmphp_hpc_stop_poll_thread * * Action: stop polling thread and cleanup *---------------------------------------------------------------------*/ void __exit ibmphp_hpc_stop_poll_thread (void) { debug ("%s - Entry\n", __func__); kthread_stop(ibmphp_poll_thread); debug ("before locking operations \n"); ibmphp_lock_operations (); debug ("after locking operations \n"); // wait for poll thread to exit debug ("before sem_exit down \n"); down (&sem_exit); debug ("after sem_exit down \n"); // cleanup debug ("before free_hpc_access \n"); free_hpc_access (); debug ("after free_hpc_access \n"); ibmphp_unlock_operations (); debug ("after unlock operations \n"); up (&sem_exit); debug ("after sem exit up\n"); debug ("%s - Exit\n", __func__); } /*---------------------------------------------------------------------- * Name: hpc_wait_ctlr_notworking * * Action: wait until the controller is in a not working state * * Return 0, HPC_ERROR * Value: *---------------------------------------------------------------------*/ static int hpc_wait_ctlr_notworking (int timeout, struct controller *ctlr_ptr, void __iomem *wpg_bbar, u8 * pstatus) { int rc = 0; u8 done = 0; debug_polling ("hpc_wait_ctlr_notworking - Entry timeout[%d]\n", timeout); while (!done) { *pstatus = ctrl_read (ctlr_ptr, wpg_bbar, WPG_CTLR_INDEX); if (*pstatus == HPC_ERROR) { rc = HPC_ERROR; done = 1; } if (CTLR_WORKING (*pstatus) == HPC_CTLR_WORKING_NO) done = 1; if (!done) { msleep(1000); if (timeout < 1) { done = 1; err ("HPCreadslot - Error ctlr timeout\n"); rc = HPC_ERROR; } else timeout--; } } debug_polling ("hpc_wait_ctlr_notworking - Exit rc[%x] status[%x]\n", rc, *pstatus); return rc; }
298353.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE190_Integer_Overflow__int_fscanf_postinc_67b.c Label Definition File: CWE190_Integer_Overflow__int.label.xml Template File: sources-sinks-67b.tmpl.c */ /* * @description * CWE: 190 Integer Overflow * BadSource: fscanf Read data from the console using fscanf() * GoodSource: Set data to a small, non-zero number (two) * Sinks: increment * GoodSink: Ensure there will not be an overflow before incrementing data * BadSink : Increment data, which can cause an overflow * Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files * * */ #include "std_testcase.h" typedef struct _CWE190_Integer_Overflow__int_fscanf_postinc_67_structType { int structFirst; } CWE190_Integer_Overflow__int_fscanf_postinc_67_structType; #ifndef OMITBAD void CWE190_Integer_Overflow__int_fscanf_postinc_67b_badSink(CWE190_Integer_Overflow__int_fscanf_postinc_67_structType myStruct) { int data = myStruct.structFirst; { /* POTENTIAL FLAW: Incrementing data could cause an overflow */ data++; int result = data; printIntLine(result); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE190_Integer_Overflow__int_fscanf_postinc_67b_goodG2BSink(CWE190_Integer_Overflow__int_fscanf_postinc_67_structType myStruct) { int data = myStruct.structFirst; { /* POTENTIAL FLAW: Incrementing data could cause an overflow */ data++; int result = data; printIntLine(result); } } /* goodB2G uses the BadSource with the GoodSink */ void CWE190_Integer_Overflow__int_fscanf_postinc_67b_goodB2GSink(CWE190_Integer_Overflow__int_fscanf_postinc_67_structType myStruct) { int data = myStruct.structFirst; /* FIX: Add a check to prevent an overflow from occurring */ if (data < INT_MAX) { data++; int result = data; printIntLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } #endif /* OMITGOOD */
597458.c
/* * hx8347.c * * Created on: 2016. 7. 13. * Author: Baram */ #include "hx8347.h" #include "spi.h" #define _TFTWIDTH 320 #define _TFTHEIGHT 240 #define _PIN_DEF_DC 0 #define _PIN_DEF_CS 1 #define _PIN_DEF_RST 2 #define _PIN_DEF_BL 3 #define _PIN_DEF_SD 4 uint32_t colstart = 0; uint32_t rowstart = 0; typedef struct { GPIO_TypeDef *p_port; uint16_t pin_num; } gpio_pin_t; static gpio_pin_t pin_tbl[5] = { {GPIOF, GPIO_PIN_13}, // _PIN_DEF_DC {GPIOD, GPIO_PIN_14}, // _PIN_DEF_CS {GPIOF, GPIO_PIN_12}, // _PIN_DEF_RST {GPIOD, GPIO_PIN_15}, // _PIN_DEF_BL {GPIOE, GPIO_PIN_11}, // _PIN_DEF_SD }; static uint32_t _width = _TFTWIDTH; static uint32_t _height = _TFTHEIGHT; static uint16_t frame_buf[_TFTWIDTH*_TFTWIDTH] __attribute__((section(".NoneCacheableMem"))); const uint8_t initdataQT2[] = { //driving ability 0x40| 2, 0xEA, 0x00, 0x40| 2, 0xEB, 0x20, 0x40| 2, 0xEC, 0x0C, 0x40| 2, 0xED, 0xC4, 0x40| 2, 0xE8, 0x40, 0x40| 2, 0xE9, 0x38, 0x40| 2, 0xF1, 0x01, 0x40| 2, 0xF2, 0x10, 0x40| 2, 0x27, 0xA3, //power voltage 0x40| 2, 0x1B, 0x1B, 0x40| 2, 0x1A, 0x01, 0x40| 2, 0x24, 0x2F, 0x40| 2, 0x25, 0x57, //VCOM offset 0x40| 2, 0x23, 0x8D, //power on 0x40| 2, 0x18, 0x36, 0x40| 2, 0x19, 0x01, //start osc 0x40| 2, 0x01, 0x00, //wakeup 0x40| 2, 0x1F, 0x88, 0xC0| 5, //5ms 0x40| 2, 0x1F, 0x80, 0xC0| 5, //5ms 0x40| 2, 0x1F, 0x90, 0xC0| 5, //5ms 0x40| 2, 0x1F, 0xD0, 0xC0| 5, //5ms //color selection 0x40| 2, 0x17, 0x05, //0x05=65k, 0x06=262k //panel characteristic 0x40| 2, 0x36, 0x00, //display options 0x40| 2, 0x16, 0xA8, 0x40| 2, 0x03, 0x00, //x0 0x40| 2, 0x02, 0x00, //x0 0x40| 2, 0x05, ((_TFTWIDTH-1)>>0)&0xFF, 0x40| 2, 0x04, ((_TFTWIDTH-1)>>8)&0xFF, 0x40| 2, 0x07, 0x00, //y0 0x40| 2, 0x06, 0x00, //y0 0x40| 2, 0x09, ((_TFTHEIGHT-1)>>0)&0xFF, 0x40| 2, 0x08, ((_TFTHEIGHT-1)>>8)&0xFF, //display on 0x40| 2, 0x28, 0x38, 0xC0|50, //50ms 0x40| 2, 0x28, 0x3C, 0xC0| 5, //5ms 0xFF , 0xFF }; void hx8347WritePin(uint8_t pin_num, uint8_t pin_state); void hx8347InitRegs(void); void hx8347WriteReg(uint8_t cmd, uint8_t param); void hx8347Init(void) { GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; GPIO_InitStruct.Pin = pin_tbl[_PIN_DEF_DC].pin_num; // DC HAL_GPIO_Init(pin_tbl[_PIN_DEF_DC].p_port, &GPIO_InitStruct); GPIO_InitStruct.Pin = pin_tbl[_PIN_DEF_RST].pin_num; // RST HAL_GPIO_Init(pin_tbl[_PIN_DEF_RST].p_port, &GPIO_InitStruct); GPIO_InitStruct.Pin = pin_tbl[_PIN_DEF_CS].pin_num; // CS HAL_GPIO_Init(pin_tbl[_PIN_DEF_CS].p_port, &GPIO_InitStruct); GPIO_InitStruct.Pin = pin_tbl[_PIN_DEF_BL].pin_num; // BL HAL_GPIO_Init(pin_tbl[_PIN_DEF_BL].p_port, &GPIO_InitStruct); GPIO_InitStruct.Pin = pin_tbl[_PIN_DEF_SD].pin_num; // SD HAL_GPIO_Init(pin_tbl[_PIN_DEF_SD].p_port, &GPIO_InitStruct); hx8347WritePin(_PIN_DEF_CS, _DEF_HIGH); hx8347WritePin(_PIN_DEF_DC, _DEF_HIGH); hx8347WritePin(_PIN_DEF_RST, _DEF_HIGH); hx8347WritePin(_PIN_DEF_BL, _DEF_HIGH); hx8347WritePin(_PIN_DEF_SD, _DEF_HIGH); hx8347WritePin(_PIN_DEF_RST, _DEF_HIGH); delay(50); hx8347WritePin(_PIN_DEF_RST, _DEF_LOW); delay(50); hx8347WritePin(_PIN_DEF_RST, _DEF_HIGH); delay(50); spiBegin(_DEF_SPI1); spiSetBitOrder(_DEF_SPI1, SPI_FIRSTBIT_MSB); // 200Mhz / div spiSetClockDivider(_DEF_SPI1, SPI_BAUDRATEPRESCALER_8); // 25Mhz spiSetDataMode(_DEF_SPI1, SPI_MODE0); hx8347InitRegs(); } void hx8347WritePin(uint8_t pin_num, uint8_t pin_state) { if (pin_state == _DEF_HIGH) { HAL_GPIO_WritePin(pin_tbl[pin_num].p_port, pin_tbl[pin_num].pin_num, GPIO_PIN_SET); } else { HAL_GPIO_WritePin(pin_tbl[pin_num].p_port, pin_tbl[pin_num].pin_num, GPIO_PIN_RESET); } } void hx8347WriteCommand(uint8_t c) { hx8347WritePin(_PIN_DEF_DC, _DEF_LOW); hx8347WritePin(_PIN_DEF_CS, _DEF_LOW); spiTransfer8(_DEF_SPI1, c); hx8347WritePin(_PIN_DEF_CS, _DEF_HIGH); } void hx8347WriteData(uint8_t c) { hx8347WritePin(_PIN_DEF_DC, _DEF_HIGH); hx8347WritePin(_PIN_DEF_CS, _DEF_LOW); spiTransfer8(_DEF_SPI1, c); hx8347WritePin(_PIN_DEF_CS, _DEF_HIGH); } void hx8347WriteReg(uint8_t cmd, uint8_t param) { hx8347WritePin(_PIN_DEF_DC, _DEF_LOW); hx8347WritePin(_PIN_DEF_CS, _DEF_LOW); spiTransfer8(_DEF_SPI1, cmd); hx8347WritePin(_PIN_DEF_DC, _DEF_HIGH); spiTransfer8(_DEF_SPI1, param); hx8347WritePin(_PIN_DEF_CS, _DEF_HIGH); } void hx8347InitRegs(void) { uint_least8_t c, d, i; const uint8_t *ptr; //reset hx8347WritePin(_PIN_DEF_CS, _DEF_HIGH); //send init commands and data ptr = &initdataQT2[0]; while(1) { c = *(ptr); ptr++; if(c == 0xFF) //end of data { break; } switch(c&0xC0) { case 0x40: //command + data for(i=c&0x3F; i!=0; i-=2) { c = *(ptr); ptr++; d = *(ptr); ptr++; hx8347WriteReg(c, d); } break; case 0xC0: //delay c = c&0x3F; delay(c); break; } } } uint16_t hx8347GetWidth(void) { return _width; } uint16_t hx8347GetHeight(void) { return _height; } #define MADCTL_MY 0x80 #define MADCTL_MX 0x40 #define MADCTL_MV 0x20 #define MADCTL_ML 0x10 #define MADCTL_RGB 0x00 #define MADCTL_BGR 0x08 #define MADCTL_MH 0x04 void hx8347SetRotation(uint8_t mode) { uint8_t p = 0x00; switch (mode) { case 0: _width = _TFTWIDTH; _height = _TFTHEIGHT; colstart = 0; rowstart = 0; p = 0xA8; break; case 1: _width = _TFTHEIGHT; _height = _TFTWIDTH; colstart = 0; rowstart = 0; p = 0x08; break; case 2: _width = _TFTWIDTH; _height = _TFTHEIGHT; colstart = 0; rowstart = 0; p = 0x68; break; case 3: _width = _TFTHEIGHT; _height = _TFTWIDTH; colstart = 0; rowstart = 0; p = 0xC8; break; } hx8347WriteReg(0x16, p); hx8347SetAddrWindow(0, 0, _width-1, _height-1); } void hx8347SetAddrWindow(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1) { hx8347WriteReg(0x03, (x0+colstart)>>0); // XSTART hx8347WriteReg(0x02, (x0+colstart)>>8); hx8347WriteReg(0x05, (x1+colstart)>>0); // XEND hx8347WriteReg(0x04, (x1+colstart)>>8); hx8347WriteReg(0x07, (y0+rowstart)>>0); // YSTART hx8347WriteReg(0x06, (y0+rowstart)>>8); hx8347WriteReg(0x09, (y1+rowstart)>>0); // YEND hx8347WriteReg(0x08, (y1+rowstart)>>8); hx8347WriteCommand(0x22); // write to RAM } void hx8347drawBufferedLine(int16_t x, int16_t y, uint16_t *buffer, uint16_t w) { //create a local buffer line not to mess up the source uint16_t bufferedLine[w]; for (uint16_t i = 0; i < w; i++) { uint16_t color = buffer[i]; color = (color << 8) | (color >> 8); //change endianness bufferedLine[i] = color; } hx8347SetAddrWindow(x, y, x + w - 1, y + 1); hx8347WritePin(_PIN_DEF_DC, _DEF_HIGH); hx8347WritePin(_PIN_DEF_CS, _DEF_LOW); spiDmaTransfer(_DEF_SPI1, bufferedLine, w*2, 100); hx8347WritePin(_PIN_DEF_CS, _DEF_HIGH); } void hx8347drawBuffer(int16_t x, int16_t y, uint16_t *buffer, uint16_t w, uint16_t h) { hx8347SetAddrWindow(x, y, x + w - 1, y + h - 1); hx8347WritePin(_PIN_DEF_DC, _DEF_HIGH); hx8347WritePin(_PIN_DEF_CS, _DEF_LOW); spiDmaTransfer(_DEF_SPI1, buffer, w*h*2, 100); hx8347WritePin(_PIN_DEF_CS, _DEF_HIGH); } void hx8347sendBuffer(uint16_t *buffer, uint16_t n) { spiDmaTransfer(_DEF_SPI1, buffer, n*2, 0); } void hx8347DrawFrame(bool wait) { if (wait == true) { hx8347SetAddrWindow(0, 0, _width-1, _height-1); hx8347WritePin(_PIN_DEF_DC, _DEF_HIGH); hx8347WritePin(_PIN_DEF_CS, _DEF_LOW); spiDmaTransfer(_DEF_SPI1, frame_buf, _width*_height*2, 100); hx8347WritePin(_PIN_DEF_CS, _DEF_HIGH); } else { hx8347SetAddrWindow(0, 0, _width-1, _height-1); hx8347WritePin(_PIN_DEF_DC, _DEF_HIGH); hx8347WritePin(_PIN_DEF_CS, _DEF_LOW); spiDmaTransfer(_DEF_SPI1, frame_buf, _width*_height*2, 0); } } void hx8347FillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) { int32_t x_o = x; int32_t y_o = y; // rudimentary clipping (drawChar w/big text requires this) if((x >= _width) || (y >= _height)) return; if((x + w - 1) >= _width) w = _width - x; if((y + h - 1) >= _height) h = _height - y; uint8_t hi = color >> 8, lo = color; color = lo<<8 | hi<<0; for(y=0; y<h; y++) { for(x=0; x<w; x++) { frame_buf[(y_o+y)*_width+(x_o+x)] = color; } } } void hx8347DrawPixel(int16_t x, int16_t y, uint16_t color) { if((x < 0) ||(x >= _width) || (y < 0) || (y >= _height)) return; frame_buf[y*_width+x] = color>>8 | color<<8; } bool hx8347IsBusy(void) { if (spiDmaIsTxDone(_DEF_SPI1) == true) { return false; } else { return true; } }
799886.c
/* * Copyright 2013 Benjamin Vernoux <[email protected]> * * This file is part of HackRF. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include "hackrf_core.h" #include <stdint.h> #include "rom_iap.h" #include "w25q80bv.h" #define ROM_IAP_ADDR (0x10400100) #define ROM_IAP_UNDEF_ADDR (0x12345678) #define ROM_OTP_PART_ID_ADDR (0x40045000) typedef void (* IAP_t)(uint32_t [],uint32_t[]); typedef struct { const IAP_t IAP; /* If equal to 0x12345678 IAP not implemented */ /* Other TBD */ } *pENTRY_ROM_API_t; #define pROM_API ((pENTRY_ROM_API_t)ROM_IAP_ADDR) /* See Errata sheet ES_LPC43X0_A.pdf (LPC4350/30/20/10 Rev A) 3.5 IAP.1: In-Application Programming API not present on flashless parts Introduction: The LPC43x0 microcontrollers contain an APIfor In-Application Programming of flash memory. This API also allows identification of the part. Problem: On the LPC43x0 microcontrollers, the IAP API is not present. The ISP interface is present which allows the part to be identified externally (via the UART) but part identification is not possible internally using the IAP call because it is not implemented. The first word of the Part ID can be read directly from OTP at 0x40045000. The second word of the Part ID is always '0' on flashless parts. */ bool iap_is_implemented(void) { bool res; if( *((uint32_t*)ROM_IAP_ADDR) != ROM_IAP_UNDEF_ADDR ) { res = true; }else { res = false; } return res; } isp_iap_ret_code_t iap_cmd_call(iap_cmd_res_t* iap_cmd_res) { uint32_t* p_u32_data; if( iap_is_implemented() ) { pROM_API->IAP( (uint32_t*)&iap_cmd_res->cmd_param, (uint32_t*)&iap_cmd_res->status_res); }else { /* Alternative way to retrieve Part Id on MCU with no IAP Read Serial No => Read Unique ID in SPIFI (only compatible with W25Q80BV */ spi_bus_start(spi_flash.bus, &ssp_config_w25q80bv); w25q80bv_setup(&spi_flash); switch(iap_cmd_res->cmd_param.command_code) { case IAP_CMD_READ_PART_ID_NO: p_u32_data = (uint32_t*)ROM_OTP_PART_ID_ADDR; iap_cmd_res->status_res.iap_result[0] = p_u32_data[0]; iap_cmd_res->status_res.iap_result[1] = p_u32_data[1]; iap_cmd_res->status_res.status_ret = CMD_SUCCESS; break; case IAP_CMD_READ_SERIAL_NO: /* Only 64bits used */ iap_cmd_res->status_res.iap_result[0] = 0; iap_cmd_res->status_res.iap_result[1] = 0; w25q80bv_get_unique_id(&spi_flash, (w25q80bv_unique_id_t*)&iap_cmd_res->status_res.iap_result[2] ); iap_cmd_res->status_res.status_ret = CMD_SUCCESS; break; default: iap_cmd_res->status_res.status_ret = ERROR_IAP_NOT_IMPLEMENTED; break; } } return iap_cmd_res->status_res.status_ret; }
802020.c
/***************************************************************************//** * # License * * The licensor of this software is Silicon Laboratories Inc. Your use of this * software is governed by the terms of Silicon Labs Master Software License * Agreement (MSLA) available at * www.silabs.com/about-us/legal/master-software-license-agreement. This * software is Third Party Software licensed by Silicon Labs from a third party * and is governed by the sections of the MSLA applicable to Third Party * Software and the additional terms set forth below. * ******************************************************************************/ /********************************************************************* * SEGGER Microcontroller GmbH & Co. KG * * Solutions for real time microcontroller applications * ********************************************************************** * * * (c) 1996 - 2016 SEGGER Microcontroller GmbH & Co. KG * * * * Internet: www.segger.com Support: [email protected] * * * ********************************************************************** ** emWin V5.34 - Graphical user interface for embedded applications ** All Intellectual Property rights in the Software belongs to SEGGER. emWin is protected by international copyright laws. Knowledge of the source code may not be used to write a similar product. This file may only be used in accordance with the following terms: The software has been licensed to Silicon Labs Norway, a subsidiary of Silicon Labs Inc. whose registered office is 400 West Cesar Chavez, Austin, TX 78701, USA solely for the purposes of creating libraries for its ARM Cortex-M3, M4F processor-based devices, sublicensed and distributed under the terms and conditions of the End User License Agreement supplied by Silicon Labs. Full source code is available at: www.segger.com We appreciate your understanding and fairness. ---------------------------------------------------------------------- Licensing information Licensor: SEGGER Software GmbH Licensed to: Silicon Laboratories Norway Licensed SEGGER software: emWin License number: GUI-00140 License model: See Agreement, dated 20th April 2012 Licensed product: - Licensed platform: Cortex M3, Cortex M4F Licensed number of seats: - ---------------------------------------------------------------------- File : AA_Lines.c Purpose : Shows lines with different antialiasing qualities Requirements: WindowManager - ( ) MemoryDevices - ( ) AntiAliasing - (x) VNC-Server - ( ) PNG-Library - ( ) TrueTypeFonts - ( ) ---------------------------------------------------------------------- */ #include "GUI.h" /********************************************************************* * * Defines * ********************************************************************** */ // // Recommended memory to run the sample with adequate performance // #define RECOMMENDED_MEMORY (1024L * 5) /******************************************************************* * * Static code * ******************************************************************** */ /******************************************************************* * * _DemoAntialiasing * * Function description * Draws lines with different antialiasing factors */ static void _DemoAntialiasing(void) { const GUI_FONT * font_old; int i; int x1; int x2; int y1; int y2; y1 = 65; y2 = 5; // // Set drawing attributes // GUI_SetColor(GUI_WHITE); GUI_SetBkColor(GUI_BLACK); GUI_SetPenShape(GUI_PS_FLAT); GUI_Clear(); // // Draw headline // font_old = GUI_SetFont(&GUI_Font24_ASCII); GUI_SetTextAlign(GUI_TA_HCENTER); GUI_DispStringAt("AA_Lines - Sample", 160, 5); // // Draw lines without antialiased // GUI_Delay(1000); GUI_SetFont(&GUI_Font8x16); GUI_SetTextAlign(GUI_TA_LEFT); GUI_DispStringAtCEOL("draw normal lines using", 5, 40); GUI_DispStringAtCEOL("GUI_DrawLine", 5, 55); GUI_Delay(2500); x1 = 20; x2 = 100; GUI_SetFont(font_old); GUI_DispStringHCenterAt("Normal", (x1 + x2) / 2, 30 + y1); for (i = 1; i < 8; i++) { GUI_SetPenSize(i); GUI_DrawLine(x1, 40 + i * 15 + y1, x2, 40 + i * 15 + y1 + y2); } // // Draw lines with antialiasing quality factor 2 // GUI_Delay(3000); GUI_SetFont(&GUI_Font8x16); GUI_DispStringAtCEOL("", 5, 40); GUI_DispStringAtCEOL("", 5, 55); GUI_Delay(200); GUI_DispStringAtCEOL("draw antialiased lines using", 5, 40); GUI_DispStringAtCEOL("GUI_AA_DrawLine", 5, 55); GUI_Delay(3500); x1 = 120; x2 = 200; GUI_AA_SetFactor(2); GUI_SetFont(font_old); GUI_DispStringHCenterAt("Antialiased\nusing factor 2", (x1 + x2) / 2, 30 + y1); for (i = 1; i < 8; i++) { GUI_SetPenSize(i); GUI_AA_DrawLine(x1, 40 + i * 15 + y1, x2, 40 + i * 15 + y1 + y2); } // // Draw lines with antialiasing quality factor 6 // GUI_Delay(1500); x1 = 220; x2 = 300; GUI_AA_SetFactor(6); GUI_SetFont(font_old); GUI_DispStringHCenterAt("Antialiased\nusing factor 6", (x1 + x2) / 2, 30 + y1); for (i = 1; i < 8; i++) { GUI_SetPenSize(i); GUI_AA_DrawLine(x1, 40 + i * 15 + y1, x2, 40 + i * 15 + y1 + y2); } GUI_Delay(7500); } /********************************************************************* * * Public code * ********************************************************************** */ /********************************************************************* * * MainTask */ void MainTask(void) { GUI_Init(); // // Check if recommended memory for the sample is available // if (GUI_ALLOC_GetNumFreeBytes() < RECOMMENDED_MEMORY) { GUI_ErrorOut("Not enough memory available."); return; } while (1) { _DemoAntialiasing(); } } /*************************** End of file ****************************/
825766.c
#include "fftpack.h" #include "Python.h" #include "numpy/arrayobject.h" static PyObject *ErrorObject; /* ----------------------------------------------------- */ static char fftpack_cfftf__doc__[] = ""; PyObject * fftpack_cfftf(PyObject *NPY_UNUSED(self), PyObject *args) { PyObject *op1, *op2; PyArrayObject *data; PyArray_Descr *descr; double *wsave, *dptr; npy_intp nsave; int npts, nrepeats, i; if(!PyArg_ParseTuple(args, "OO", &op1, &op2)) { return NULL; } data = (PyArrayObject *)PyArray_CopyFromObject(op1, PyArray_CDOUBLE, 1, 0); if (data == NULL) { return NULL; } descr = PyArray_DescrFromType(PyArray_DOUBLE); if (PyArray_AsCArray(&op2, (void *)&wsave, &nsave, 1, descr) == -1) { goto fail; } if (data == NULL) { goto fail; } npts = PyArray_DIM(data, PyArray_NDIM(data) - 1); if (nsave != npts*4 + 15) { PyErr_SetString(ErrorObject, "invalid work array for fft size"); goto fail; } nrepeats = PyArray_SIZE(data)/npts; dptr = (double *)PyArray_BYTES(data); NPY_SIGINT_ON; for (i = 0; i < nrepeats; i++) { cfftf(npts, dptr, wsave); dptr += npts*2; } NPY_SIGINT_OFF; PyArray_Free(op2, (char *)wsave); return (PyObject *)data; fail: PyArray_Free(op2, (char *)wsave); Py_DECREF(data); return NULL; } static char fftpack_cfftb__doc__[] = ""; PyObject * fftpack_cfftb(PyObject *NPY_UNUSED(self), PyObject *args) { PyObject *op1, *op2; PyArrayObject *data; PyArray_Descr *descr; double *wsave, *dptr; npy_intp nsave; int npts, nrepeats, i; if(!PyArg_ParseTuple(args, "OO", &op1, &op2)) { return NULL; } data = (PyArrayObject *)PyArray_CopyFromObject(op1, PyArray_CDOUBLE, 1, 0); if (data == NULL) { return NULL; } descr = PyArray_DescrFromType(PyArray_DOUBLE); if (PyArray_AsCArray(&op2, (void *)&wsave, &nsave, 1, descr) == -1) { goto fail; } if (data == NULL) { goto fail; } npts = PyArray_DIM(data, PyArray_NDIM(data) - 1); if (nsave != npts*4 + 15) { PyErr_SetString(ErrorObject, "invalid work array for fft size"); goto fail; } nrepeats = PyArray_SIZE(data)/npts; dptr = (double *)PyArray_BYTES(data); NPY_SIGINT_ON; for (i = 0; i < nrepeats; i++) { cfftb(npts, dptr, wsave); dptr += npts*2; } NPY_SIGINT_OFF; PyArray_Free(op2, (char *)wsave); return (PyObject *)data; fail: PyArray_Free(op2, (char *)wsave); Py_DECREF(data); return NULL; } static char fftpack_cffti__doc__[] =""; static PyObject * fftpack_cffti(PyObject *NPY_UNUSED(self), PyObject *args) { PyArrayObject *op; npy_intp dim; long n; if (!PyArg_ParseTuple(args, "l", &n)) { return NULL; } /*Magic size needed by cffti*/ dim = 4*n + 15; /*Create a 1 dimensional array of dimensions of type double*/ op = (PyArrayObject *)PyArray_SimpleNew(1, &dim, PyArray_DOUBLE); if (op == NULL) { return NULL; } NPY_SIGINT_ON; cffti(n, (double *)PyArray_BYTES(op)); NPY_SIGINT_OFF; return (PyObject *)op; } static char fftpack_rfftf__doc__[] =""; PyObject * fftpack_rfftf(PyObject *NPY_UNUSED(self), PyObject *args) { PyObject *op1, *op2; PyArrayObject *data, *ret; PyArray_Descr *descr; double *wsave, *dptr, *rptr; npy_intp nsave; int npts, nrepeats, i, rstep; if(!PyArg_ParseTuple(args, "OO", &op1, &op2)) { return NULL; } data = (PyArrayObject *)PyArray_ContiguousFromObject(op1, PyArray_DOUBLE, 1, 0); if (data == NULL) { return NULL; } npts = PyArray_DIM(data, PyArray_NDIM(data)-1); PyArray_DIM(data, PyArray_NDIM(data) - 1) = npts/2 + 1; ret = (PyArrayObject *)PyArray_Zeros(PyArray_NDIM(data), PyArray_DIMS(data), PyArray_DescrFromType(PyArray_CDOUBLE), 0); PyArray_DIM(data, PyArray_NDIM(data) - 1) = npts; rstep = (PyArray_DIM(ret, PyArray_NDIM(ret) - 1))*2; descr = PyArray_DescrFromType(PyArray_DOUBLE); if (PyArray_AsCArray(&op2, (void *)&wsave, &nsave, 1, descr) == -1) { goto fail; } if (data == NULL || ret == NULL) { goto fail; } if (nsave != npts*2+15) { PyErr_SetString(ErrorObject, "invalid work array for fft size"); goto fail; } nrepeats = PyArray_SIZE(data)/npts; rptr = (double *)PyArray_BYTES(ret); dptr = (double *)PyArray_BYTES(data); NPY_SIGINT_ON; for (i = 0; i < nrepeats; i++) { memcpy((char *)(rptr+1), dptr, npts*sizeof(double)); rfftf(npts, rptr+1, wsave); rptr[0] = rptr[1]; rptr[1] = 0.0; rptr += rstep; dptr += npts; } NPY_SIGINT_OFF; PyArray_Free(op2, (char *)wsave); Py_DECREF(data); return (PyObject *)ret; fail: PyArray_Free(op2, (char *)wsave); Py_XDECREF(data); Py_XDECREF(ret); return NULL; } static char fftpack_rfftb__doc__[] =""; PyObject * fftpack_rfftb(PyObject *NPY_UNUSED(self), PyObject *args) { PyObject *op1, *op2; PyArrayObject *data, *ret; PyArray_Descr *descr; double *wsave, *dptr, *rptr; npy_intp nsave; int npts, nrepeats, i; if(!PyArg_ParseTuple(args, "OO", &op1, &op2)) { return NULL; } data = (PyArrayObject *)PyArray_ContiguousFromObject(op1, PyArray_CDOUBLE, 1, 0); if (data == NULL) { return NULL; } npts = PyArray_DIM(data, PyArray_NDIM(data) - 1); ret = (PyArrayObject *)PyArray_Zeros(PyArray_NDIM(data), PyArray_DIMS(data), PyArray_DescrFromType(PyArray_DOUBLE), 0); descr = PyArray_DescrFromType(PyArray_DOUBLE); if (PyArray_AsCArray(&op2, (void *)&wsave, &nsave, 1, descr) == -1) { goto fail; } if (data == NULL || ret == NULL) { goto fail; } if (nsave != npts*2 + 15) { PyErr_SetString(ErrorObject, "invalid work array for fft size"); goto fail; } nrepeats = PyArray_SIZE(ret)/npts; rptr = (double *)PyArray_BYTES(ret); dptr = (double *)PyArray_BYTES(data); NPY_SIGINT_ON; for (i = 0; i < nrepeats; i++) { memcpy((char *)(rptr + 1), (dptr + 2), (npts - 1)*sizeof(double)); rptr[0] = dptr[0]; rfftb(npts, rptr, wsave); rptr += npts; dptr += npts*2; } NPY_SIGINT_OFF; PyArray_Free(op2, (char *)wsave); Py_DECREF(data); return (PyObject *)ret; fail: PyArray_Free(op2, (char *)wsave); Py_XDECREF(data); Py_XDECREF(ret); return NULL; } static char fftpack_rffti__doc__[] =""; static PyObject * fftpack_rffti(PyObject *NPY_UNUSED(self), PyObject *args) { PyArrayObject *op; npy_intp dim; long n; if (!PyArg_ParseTuple(args, "l", &n)) { return NULL; } /*Magic size needed by rffti*/ dim = 2*n + 15; /*Create a 1 dimensional array of dimensions of type double*/ op = (PyArrayObject *)PyArray_SimpleNew(1, &dim, PyArray_DOUBLE); if (op == NULL) { return NULL; } NPY_SIGINT_ON; rffti(n, (double *)PyArray_BYTES(op)); NPY_SIGINT_OFF; return (PyObject *)op; } /* List of methods defined in the module */ static struct PyMethodDef fftpack_methods[] = { {"cfftf", fftpack_cfftf, 1, fftpack_cfftf__doc__}, {"cfftb", fftpack_cfftb, 1, fftpack_cfftb__doc__}, {"cffti", fftpack_cffti, 1, fftpack_cffti__doc__}, {"rfftf", fftpack_rfftf, 1, fftpack_rfftf__doc__}, {"rfftb", fftpack_rfftb, 1, fftpack_rfftb__doc__}, {"rffti", fftpack_rffti, 1, fftpack_rffti__doc__}, {NULL, NULL, 0, NULL} /* sentinel */ }; /* Initialization function for the module (*must* be called initfftpack) */ static char fftpack_module_documentation[] = "" ; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "fftpack_lite", NULL, -1, fftpack_methods, NULL, NULL, NULL, NULL }; #endif /* Initialization function for the module */ #if PY_MAJOR_VERSION >= 3 #define RETVAL m PyObject *PyInit_fftpack_lite(void) #else #define RETVAL PyMODINIT_FUNC initfftpack_lite(void) #endif { PyObject *m,*d; #if PY_MAJOR_VERSION >= 3 m = PyModule_Create(&moduledef); #else m = Py_InitModule4("fftpack_lite", fftpack_methods, fftpack_module_documentation, (PyObject*)NULL,PYTHON_API_VERSION); #endif /* Import the array object */ import_array(); /* Add some symbolic constants to the module */ d = PyModule_GetDict(m); ErrorObject = PyErr_NewException("fftpack.error", NULL, NULL); PyDict_SetItemString(d, "error", ErrorObject); /* XXXX Add constants here */ return RETVAL; }
711782.c
// // File: %c-function.c // Summary: "support for functions, actions, and routines" // Section: core // Project: "Rebol 3 Interpreter and Run-time (Ren-C branch)" // Homepage: https://github.com/metaeducation/ren-c/ // //=////////////////////////////////////////////////////////////////////////=// // // Copyright 2012 REBOL Technologies // Copyright 2012-2017 Rebol Open Source Contributors // REBOL is a trademark of REBOL Technologies // // See README.md and CREDITS.md for more information. // // 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 // //=////////////////////////////////////////////////////////////////////////=// // #include "sys-core.h" struct Params_Of_State { REBARR *arr; REBLEN num_visible; RELVAL *dest; bool just_words; }; // Reconstitute parameter back into a full value, e.g. REB_P_REFINEMENT // becomes `/spelling`. // // !!! See notes on Is_Param_Hidden() for why caller isn't filtering locals. // static bool Params_Of_Hook( REBVAL *param, REBFLGS flags, void *opaque ){ struct Params_Of_State *s = cast(struct Params_Of_State*, opaque); if (not (flags & PHF_SORTED_PASS)) { ++s->num_visible; // first pass we just count unspecialized params return true; } if (not s->arr) { // if first step on second pass, make the array s->arr = Make_Array(s->num_visible); s->dest = ARR_HEAD(s->arr); } Init_Any_Word(s->dest, REB_WORD, VAL_PARAM_SPELLING(param)); if (not s->just_words) { if ( not (flags & PHF_UNREFINED) and TYPE_CHECK(param, REB_TS_REFINEMENT) ){ Refinify(KNOWN(s->dest)); } switch (VAL_PARAM_CLASS(param)) { case REB_P_NORMAL: break; case REB_P_HARD_QUOTE: Getify(KNOWN(s->dest)); break; case REB_P_MODAL: if (flags & PHF_DEMODALIZED) { // associated refinement specialized out } else Symify(KNOWN(s->dest)); break; case REB_P_SOFT_QUOTE: Quotify(KNOWN(s->dest), 1); break; default: assert(false); DEAD_END; } } ++s->dest; return true; } // // Make_Action_Parameters_Arr: C // // Returns array of function words, unbound. // REBARR *Make_Action_Parameters_Arr(REBACT *act, bool just_words) { struct Params_Of_State s; s.arr = nullptr; s.num_visible = 0; s.just_words = just_words; For_Each_Unspecialized_Param(act, &Params_Of_Hook, &s); if (not s.arr) return Make_Array(1); // no unspecialized parameters, empty array TERM_ARRAY_LEN(s.arr, s.num_visible); ASSERT_ARRAY(s.arr); return s.arr; } static bool Typesets_Of_Hook( REBVAL *param, REBFLGS flags, void *opaque ){ struct Params_Of_State *s = cast(struct Params_Of_State*, opaque); if (not (flags & PHF_SORTED_PASS)) { ++s->num_visible; // first pass we just count unspecialized params return true; } if (not s->arr) { // if first step on second pass, make the array s->arr = Make_Array(s->num_visible); s->dest = ARR_HEAD(s->arr); } // It's already a typeset, but remove the parameter spelling. // // !!! Typesets must be revisited in a world with user-defined types, as // well as to accomodate multiple quoting levels. // Move_Value(s->dest, param); assert(IS_TYPESET(s->dest)); VAL_TYPESET_STRING_NODE(s->dest) = nullptr; ++s->dest; return true; } // // Make_Action_Typesets_Arr: C // // Return a block of function arg typesets. // Note: skips 0th entry. // REBARR *Make_Action_Typesets_Arr(REBACT *act) { struct Params_Of_State s; s.arr = nullptr; s.num_visible = 0; s.just_words = false; // (ignored) For_Each_Unspecialized_Param(act, &Typesets_Of_Hook, &s); if (not s.arr) return Make_Array(1); // no unspecialized parameters, empty array TERM_ARRAY_LEN(s.arr, s.num_visible); ASSERT_ARRAY(s.arr); return s.arr; } enum Reb_Spec_Mode { SPEC_MODE_NORMAL, // words are arguments SPEC_MODE_LOCAL, // words are locals SPEC_MODE_WITH // words are "extern" }; // // Push_Paramlist_Triads_May_Fail: C // // This is an implementation routine for Make_Paramlist_Managed_May_Fail(). // It was broken out into its own separate routine so that the AUGMENT // function could reuse the logic for function spec analysis. It may not // be broken out in a particularly elegant way, but it's a start. // void Push_Paramlist_Triads_May_Fail( const REBVAL *spec, REBFLGS *flags, REBDSP dsp_orig, REBDSP *definitional_return_dsp ){ assert(IS_BLOCK(spec)); enum Reb_Spec_Mode mode = SPEC_MODE_NORMAL; bool refinement_seen = false; const RELVAL* value = VAL_ARRAY_AT(spec); while (NOT_END(value)) { const RELVAL* item = value; // "faked", e.g. <return> => RETURN: ++value; // go ahead and consume next //=//// STRING! FOR FUNCTION DESCRIPTION OR PARAMETER NOTE ////////////=// if (IS_TEXT(item)) { // // Consider `[<with> some-extern "description of that extern"]` to // be purely commentary for the implementation, and don't include // it in the meta info. // if (mode == SPEC_MODE_WITH) continue; if (IS_PARAM(DS_TOP)) Move_Value(DS_PUSH(), EMPTY_BLOCK); // need block in position if (IS_BLOCK(DS_TOP)) { // in right spot to push notes/title Init_Text(DS_PUSH(), Copy_String_At(item)); } else { // !!! A string was already pushed. Should we append? assert(IS_TEXT(DS_TOP)); Init_Text(DS_TOP, Copy_String_At(item)); } if (DS_TOP == DS_AT(dsp_orig + 3)) *flags |= MKF_HAS_DESCRIPTION; else *flags |= MKF_HAS_NOTES; continue; } //=//// TOP-LEVEL SPEC TAGS LIKE <local>, <with> etc. /////////////////=// if (IS_TAG(item) and (*flags & MKF_KEYWORDS)) { if (0 == Compare_String_Vals(item, Root_With_Tag, true)) { mode = SPEC_MODE_WITH; continue; } else if (0 == Compare_String_Vals(item, Root_Local_Tag, true)) { mode = SPEC_MODE_LOCAL; continue; } else if (0 == Compare_String_Vals(item, Root_Void_Tag, true)) { *flags |= MKF_IS_VOIDER; // use Voider_Dispatcher() // Fake as if they said [void!] !!! make more efficient // item = Get_System(SYS_STANDARD, STD_PROC_RETURN_TYPE); goto process_typeset_block; } else fail (Error_Bad_Func_Def_Core(item, VAL_SPECIFIER(spec))); } //=//// BLOCK! OF TYPES TO MAKE TYPESET FROM (PLUS PARAMETER TAGS) ////=// if (IS_BLOCK(item)) { process_typeset_block: if (IS_BLOCK(DS_TOP)) // two blocks of types! fail (Error_Bad_Func_Def_Core(item, VAL_SPECIFIER(spec))); // You currently can't say `<local> x [integer!]`, because they // are always void when the function runs. You can't say // `<with> x [integer!]` because "externs" don't have param slots // to store the type in. // // !!! A type constraint on a <with> parameter might be useful, // though--and could be achieved by adding a type checker into // the body of the function. However, that would be more holistic // than this generation of just a paramlist. Consider for future. // if (mode != SPEC_MODE_NORMAL) fail (Error_Bad_Func_Def_Core(item, VAL_SPECIFIER(spec))); // Save the block for parameter types. // REBVAL* param; if (IS_PARAM(DS_TOP)) { REBSPC* derived = Derive_Specifier(VAL_SPECIFIER(spec), item); Init_Block( DS_PUSH(), Copy_Array_At_Deep_Managed( VAL_ARRAY(item), VAL_INDEX(item), derived ) ); param = DS_TOP - 1; // volatile if you DS_PUSH()! } else { assert(IS_TEXT(DS_TOP)); // !!! are blocks after notes good? if (IS_BLANK_RAW(DS_TOP - 2)) { // // No parameters pushed, e.g. func [[integer!] {<-- bad}] // fail (Error_Bad_Func_Def_Core(item, VAL_SPECIFIER(spec))); } assert(IS_PARAM(DS_TOP - 2)); param = DS_TOP - 2; assert(IS_BLOCK(DS_TOP - 1)); if (VAL_ARRAY(DS_TOP - 1) != EMPTY_ARRAY) fail (Error_Bad_Func_Def_Core(item, VAL_SPECIFIER(spec))); REBSPC* derived = Derive_Specifier(VAL_SPECIFIER(spec), item); Init_Block( DS_TOP - 1, Copy_Array_At_Deep_Managed( VAL_ARRAY(item), VAL_INDEX(item), derived ) ); } // Turn block into typeset for parameter at current index. // Leaves VAL_TYPESET_SYM as-is. // bool was_refinement = TYPE_CHECK(param, REB_TS_REFINEMENT); REBSPC* derived = Derive_Specifier(VAL_SPECIFIER(spec), item); VAL_TYPESET_LOW_BITS(param) = 0; VAL_TYPESET_HIGH_BITS(param) = 0; Add_Typeset_Bits_Core( param, VAL_ARRAY_HEAD(item), derived ); if (was_refinement) TYPE_SET(param, REB_TS_REFINEMENT); *flags |= MKF_HAS_TYPES; continue; } //=//// ANY-WORD! PARAMETERS THEMSELVES (MAKE TYPESETS w/SYMBOL) //////=// bool quoted = false; // single quoting level used as signal in spec if (VAL_NUM_QUOTES(item) > 0) { if (VAL_NUM_QUOTES(item) > 1) fail (Error_Bad_Func_Def_Core(item, VAL_SPECIFIER(spec))); quoted = true; } const REBCEL* cell = VAL_UNESCAPED(item); REBSTR* spelling; Reb_Param_Class pclass = REB_P_DETECT; bool refinement = false; // paths with blanks at head are refinements if (ANY_PATH_KIND(CELL_KIND(cell))) { if ( KIND_BYTE(VAL_ARRAY_AT(cell)) != REB_BLANK or KIND_BYTE(VAL_ARRAY_AT(cell) + 1) != REB_WORD or KIND_BYTE(VAL_ARRAY_AT(cell) + 2) != REB_0_END ){ fail (Error_Bad_Func_Def_Core(item, VAL_SPECIFIER(spec))); } refinement = true; refinement_seen = true; // !!! If you say [<with> x /foo y] the <with> terminates and a // refinement is started. Same w/<local>. Is this a good idea? // Note that historically, help hides any refinements that appear // behind a /local, but this feature has no parallel in Ren-C. // mode = SPEC_MODE_NORMAL; spelling = VAL_WORD_SPELLING(VAL_ARRAY_AT(cell) + 1); if (STR_SYMBOL(spelling) == SYM_LOCAL) // /LOCAL if (ANY_WORD_KIND(KIND_BYTE(item + 1))) // END is 0 fail (Error_Legacy_Local_Raw(spec)); // -> <local> if (CELL_KIND(cell) == REB_GET_PATH) { if (not quoted) pclass = REB_P_HARD_QUOTE; } else if (CELL_KIND(cell) == REB_PATH) { if (quoted) pclass = REB_P_SOFT_QUOTE; else pclass = REB_P_NORMAL; } } else if (ANY_WORD_KIND(CELL_KIND(cell))) { spelling = VAL_WORD_SPELLING(cell); if (CELL_KIND(cell) == REB_SET_WORD) { if (not quoted) pclass = REB_P_LOCAL; } else { if (refinement_seen and mode == SPEC_MODE_NORMAL) fail (Error_Legacy_Refinement_Raw(spec)); if (CELL_KIND(cell) == REB_GET_WORD) { if (not quoted) pclass = REB_P_HARD_QUOTE; } else if (CELL_KIND(cell) == REB_WORD) { if (quoted) pclass = REB_P_SOFT_QUOTE; else pclass = REB_P_NORMAL; } else if (CELL_KIND(cell) == REB_SYM_WORD) { if (not quoted) pclass = REB_P_MODAL; } } } else fail (Error_Bad_Func_Def_Core(item, VAL_SPECIFIER(spec))); if (pclass == REB_P_DETECT) // didn't match fail (Error_Bad_Func_Def_Core(item, VAL_SPECIFIER(spec))); if (mode != SPEC_MODE_NORMAL) { if (pclass != REB_P_NORMAL and pclass != REB_P_LOCAL) fail (Error_Bad_Func_Def_Core(item, VAL_SPECIFIER(spec))); if (mode == SPEC_MODE_LOCAL) pclass = REB_P_LOCAL; } REBSTR* canon = STR_CANON(spelling); if (STR_SYMBOL(canon) == SYM_RETURN and pclass != REB_P_LOCAL) { // // Cancel definitional return if any non-SET-WORD! uses the name // RETURN when defining a FUNC. // *flags &= ~MKF_RETURN; } // Because FUNC does not do any locals gathering by default, the main // purpose of tolerating <with> is for instructing it not to do the // definitional returns. However, it also makes changing between // FUNC and FUNCTION more fluid. // // !!! If you write something like `func [x <with> x] [...]` that // should be sanity checked with an error...TBD. // if (mode == SPEC_MODE_WITH) continue; // In rhythm of TYPESET! BLOCK! TEXT! we want to be on a string spot // at the time of the push of each new typeset. // if (IS_PARAM(DS_TOP)) Move_Value(DS_PUSH(), EMPTY_BLOCK); if (IS_BLOCK(DS_TOP)) Move_Value(DS_PUSH(), EMPTY_TEXT); assert(IS_TEXT(DS_TOP)); // Non-annotated arguments disallow ACTION!, VOID! and NULL. Not // having to worry about ACTION! and NULL means by default, code // does not have to worry about "disarming" arguments via GET-WORD!. // Also, keeping NULL a bit "prickly" helps discourage its use as // an input parameter...because it faces problems being used in // SPECIALIZE and other scenarios. // // Note there are currently two ways to get NULL: <opt> and <end>. // If the typeset bits contain REB_NULLED, that indicates <opt>. // But Is_Param_Endable() indicates <end>. if (refinement) { Init_Param( DS_PUSH(), pclass, spelling, // don't canonize, see #2258 FLAGIT_KIND(REB_TS_REFINEMENT) // must preserve if type block ); } else Init_Param( DS_PUSH(), pclass, spelling, // don't canonize, see #2258 (*flags & MKF_ANY_VALUE) ? TS_OPT_VALUE : TS_VALUE & ~( FLAGIT_KIND(REB_ACTION) | FLAGIT_KIND(REB_VOID) ) ); // All these would cancel a definitional return (leave has same idea): // // func [return [integer!]] // func [/refinement return] // func [<local> return] // func [<with> return] // // ...although `return:` is explicitly tolerated ATM for compatibility // (despite violating the "pure locals are NULL" premise) // if (STR_SYMBOL(canon) == SYM_RETURN) { if (*definitional_return_dsp != 0) { DECLARE_LOCAL(word); Init_Word(word, canon); fail (Error_Dup_Vars_Raw(word)); // most dup checks are later } if (pclass == REB_P_LOCAL) *definitional_return_dsp = DSP; // RETURN: explicit, tolerate else *flags &= ~MKF_RETURN; } } } // // Pop_Paramlist_And_Meta_May_Fail: C // // Assuming the stack is formed in a rhythm of the parameter, a type spec // block, and a description...produce a paramlist in a state suitable to be // passed to Make_Action(). It may not succeed because there could be // duplicate parameters on the stack, and the checking via a binder is done // as part of this popping process. // REBARR *Pop_Paramlist_With_Meta_May_Fail( REBDSP dsp_orig, REBFLGS flags, REBDSP definitional_return_dsp ){ // Go ahead and flesh out the TYPESET! BLOCK! TEXT! triples. // if (IS_PARAM(DS_TOP)) Move_Value(DS_PUSH(), EMPTY_BLOCK); if (IS_BLOCK(DS_TOP)) Move_Value(DS_PUSH(), EMPTY_TEXT); assert((DSP - dsp_orig) % 3 == 0); // must be a multiple of 3 // Definitional RETURN slots must have their argument value fulfilled with // an ACTION! specific to the action called on *every instantiation*. // They are marked with special parameter classes to avoid needing to // separately do canon comparison of their symbols to find them. // // Note: Since RETURN's typeset holds types that need to be checked at // the end of the function run, it is moved to a predictable location: // first slot of the paramlist. Initially it was the last slot...but this // enables adding more arguments/refinements/locals in derived functions. if (flags & MKF_RETURN) { if (definitional_return_dsp == 0) { // no explicit RETURN: pure local // // While default arguments disallow ACTION!, VOID!, and NULL... // they are allowed to return anything. Generally speaking, the // checks are on the input side, not the output. // Init_Param( DS_PUSH(), REB_P_RETURN, Canon(SYM_RETURN), TS_OPT_VALUE ); definitional_return_dsp = DSP; Move_Value(DS_PUSH(), EMPTY_BLOCK); Move_Value(DS_PUSH(), EMPTY_TEXT); } else { REBVAL *param = DS_AT(definitional_return_dsp); // Note: AUGMENT may be copying an already REB_P_RETURN'd argument // from a pre-existing parameter list. Else REB_P_LOCAL. // assert( VAL_PARAM_CLASS(param) == REB_P_LOCAL or VAL_PARAM_CLASS(param) == REB_P_RETURN ); mutable_KIND_BYTE(param) = REB_P_RETURN; assert(MIRROR_BYTE(param) == REB_TYPESET); } // definitional_return handled specially when paramlist copied // off of the stack...moved to head position. flags |= MKF_HAS_RETURN; } // Slots, which is length +1 (includes the rootvar or rootparam) // REBLEN num_slots = (DSP - dsp_orig) / 3; // There should be no more pushes past this point, so a stable pointer // into the stack for the definitional return can be found. // REBVAL *definitional_return = definitional_return_dsp == 0 ? nullptr : DS_AT(definitional_return_dsp); // Must make the function "paramlist" even if "empty", for identity. // // !!! In order to facilitate adding to the frame in the copy and // relativize step to add LET variables, don't pass SERIES_FLAG_FIXED_SIZE // in the creation step. This formats cells in such a way that the // series mechanically cannot be expanded even if the flag is removed. // Instead, add it onto a series allocated as resizable. This is likely // temporary--as LET mechanics should use some form of "virtual binding". // REBARR *paramlist = Make_Array_Core( num_slots, SERIES_MASK_PARAMLIST & ~(SERIES_FLAG_FIXED_SIZE) ); SET_SERIES_FLAG(paramlist, FIXED_SIZE); // Note: not a valid ACTION! paramlist yet, don't use SET_ACTION_FLAG() // if (flags & MKF_IS_VOIDER) SER(paramlist)->info.bits |= ARRAY_INFO_MISC_VOIDER; // !!! see note if (flags & MKF_HAS_RETURN) SER(paramlist)->header.bits |= PARAMLIST_FLAG_HAS_RETURN; blockscope { REBVAL *archetype = RESET_CELL( ARR_HEAD(paramlist), REB_ACTION, CELL_MASK_ACTION ); Sync_Paramlist_Archetype(paramlist); INIT_BINDING(archetype, UNBOUND); REBVAL *dest = archetype + 1; // We want to check for duplicates and a Binder can be used for that // purpose--but note that a fail () cannot happen while binders are // in effect UNLESS the BUF_COLLECT contains information to undo it! // There's no BUF_COLLECT here, so don't fail while binder in effect. // // (This is why we wait until the parameter list gathering process // is over to do the duplicate checks--it can fail.) // struct Reb_Binder binder; INIT_BINDER(&binder); REBSTR *duplicate = nullptr; REBVAL *src = DS_AT(dsp_orig + 1) + 3; if (definitional_return) { assert(flags & MKF_RETURN); Move_Value(dest, definitional_return); ++dest; } // Weird due to Spectre/MSVC: https://stackoverflow.com/q/50399940 // for (; src != DS_TOP + 1; src += 3) { if (not Try_Add_Binder_Index(&binder, VAL_PARAM_CANON(src), 1020)) duplicate = VAL_PARAM_SPELLING(src); if (definitional_return and src == definitional_return) continue; Move_Value(dest, src); ++dest; } // Must remove binder indexes for all words, even if about to fail // src = DS_AT(dsp_orig + 1) + 3; // Weird due to Spectre/MSVC: https://stackoverflow.com/q/50399940 // for (; src != DS_TOP + 1; src += 3, ++dest) { if ( Remove_Binder_Index_Else_0(&binder, VAL_PARAM_CANON(src)) == 0 ){ assert(duplicate); } } SHUTDOWN_BINDER(&binder); if (duplicate) { DECLARE_LOCAL (word); Init_Word(word, duplicate); fail (Error_Dup_Vars_Raw(word)); } TERM_ARRAY_LEN(paramlist, num_slots); Manage_Array(paramlist); } //=///////////////////////////////////////////////////////////////////=// // // BUILD META INFORMATION OBJECT (IF NEEDED) // //=///////////////////////////////////////////////////////////////////=// // !!! See notes on ACTION-META in %sysobj.r REBCTX *meta = nullptr; if (flags & (MKF_HAS_DESCRIPTION | MKF_HAS_TYPES | MKF_HAS_NOTES)) meta = Copy_Context_Shallow_Managed(VAL_CONTEXT(Root_Action_Meta)); MISC_META_NODE(paramlist) = NOD(meta); // If a description string was gathered, it's sitting in the first string // slot, the third cell we pushed onto the stack. Extract it if so. // if (flags & MKF_HAS_DESCRIPTION) { assert(IS_TEXT(DS_AT(dsp_orig + 3))); Move_Value( CTX_VAR(meta, STD_ACTION_META_DESCRIPTION), DS_AT(dsp_orig + 3) ); } // Only make `parameter-types` if there were blocks in the spec // if (flags & MKF_HAS_TYPES) { REBARR *types_varlist = Make_Array_Core( num_slots, SERIES_MASK_VARLIST | NODE_FLAG_MANAGED ); MISC_META_NODE(types_varlist) = nullptr; // GC sees, must initialize INIT_CTX_KEYLIST_SHARED(CTX(types_varlist), paramlist); REBVAL *rootvar = RESET_CELL( ARR_HEAD(types_varlist), REB_FRAME, CELL_MASK_CONTEXT ); INIT_VAL_CONTEXT_VARLIST(rootvar, types_varlist); // "canon FRAME!" INIT_VAL_CONTEXT_PHASE(rootvar, ACT(paramlist)); INIT_BINDING(rootvar, UNBOUND); REBVAL *dest = rootvar + 1; REBVAL *src = DS_AT(dsp_orig + 2); src += 3; if (definitional_return) { // // We put the return note in the top-level meta information, not // on the local itself (the "return-ness" is a distinct property // of the function from what word is used for RETURN:, and it // is possible to use the word RETURN for a local or refinement // argument while having nothing to do with the exit value of // the function.) // if (VAL_ARRAY_LEN_AT(definitional_return + 1) != 0) { Move_Value( CTX_VAR(meta, STD_ACTION_META_RETURN_TYPE), &definitional_return[1] ); } Init_Nulled(dest); // clear the local RETURN: var's description ++dest; } for (; src <= DS_TOP; src += 3) { assert(IS_BLOCK(src)); if (definitional_return and src == definitional_return + 1) continue; if (VAL_ARRAY_LEN_AT(src) == 0) Init_Nulled(dest); else Move_Value(dest, src); ++dest; } TERM_ARRAY_LEN(types_varlist, num_slots); Init_Any_Context( CTX_VAR(meta, STD_ACTION_META_PARAMETER_TYPES), REB_FRAME, CTX(types_varlist) ); } // Only make `parameter-notes` if there were strings (besides description) // if (flags & MKF_HAS_NOTES) { REBARR *notes_varlist = Make_Array_Core( num_slots, SERIES_MASK_VARLIST | NODE_FLAG_MANAGED ); MISC_META_NODE(notes_varlist) = nullptr; // GC sees, must initialize INIT_CTX_KEYLIST_SHARED(CTX(notes_varlist), paramlist); REBVAL *rootvar = RESET_CELL( ARR_HEAD(notes_varlist), REB_FRAME, CELL_MASK_CONTEXT ); INIT_VAL_CONTEXT_VARLIST(rootvar, notes_varlist); // canon FRAME! INIT_VAL_CONTEXT_PHASE(rootvar, ACT(paramlist)); INIT_BINDING(rootvar, UNBOUND); REBVAL *dest = rootvar + 1; REBVAL *src = DS_AT(dsp_orig + 3); src += 3; if (definitional_return) { // // See remarks on the return type--the RETURN is documented in // the top-level META-OF, not the "incidentally" named RETURN // parameter in the list // if (SER_LEN(VAL_SERIES(definitional_return + 2)) == 0) Init_Nulled(CTX_VAR(meta, STD_ACTION_META_RETURN_NOTE)); else { Move_Value( CTX_VAR(meta, STD_ACTION_META_RETURN_NOTE), &definitional_return[2] ); } Init_Nulled(dest); ++dest; } for (; src <= DS_TOP; src += 3) { assert(IS_TEXT(src)); if (definitional_return and src == definitional_return + 2) continue; if (SER_LEN(VAL_SERIES(src)) == 0) Init_Nulled(dest); else Move_Value(dest, src); ++dest; } TERM_ARRAY_LEN(notes_varlist, num_slots); Init_Frame( CTX_VAR(meta, STD_ACTION_META_PARAMETER_NOTES), CTX(notes_varlist) ); } // With all the values extracted from stack to array, restore stack pointer // DS_DROP_TO(dsp_orig); return paramlist; } // // Make_Paramlist_Managed_May_Fail: C // // Check function spec of the form: // // ["description" arg "notes" [type! type2! ...] /ref ...] // // !!! The spec language was not formalized in R3-Alpha. Strings were left // in and it was HELP's job (and any other clients) to make sense of it, e.g.: // // [foo [type!] {doc string :-)}] // [foo {doc string :-/} [type!]] // [foo {doc string1 :-/} {doc string2 :-(} [type!]] // // Ren-C breaks this into two parts: one is the mechanical understanding of // MAKE ACTION! for parameters in the evaluator. Then it is the job // of a generator to tag the resulting function with a "meta object" with any // descriptions. As a proxy for the work of a usermode generator, this // routine tries to fill in FUNCTION-META (see %sysobj.r) as well as to // produce a paramlist suitable for the function. // // Note a "true local" (indicated by a set-word) is considered to be tacit // approval of wanting a definitional return by the generator. This helps // because Red's model for specifying returns uses a SET-WORD! // // func [return: [integer!] {returns an integer}] // // In Ren-C's case it just means you want a local called return, but the // generator will be "initializing it with a definitional return" for you. // You don't have to use it if you don't want to...and may overwrite the // variable. But it won't be a void at the start. // // Note: While paramlists should ultimately carry SERIES_FLAG_FIXED_SIZE, // the product of this routine might need to be added to. And series that // are created fixed size have special preparation such that they will trip // more asserts. So the fixed size flag is *not* added here, but ensured // in the Make_Action() step. // REBARR *Make_Paramlist_Managed_May_Fail( const REBVAL *spec, REBFLGS flags ){ REBDSP dsp_orig = DSP; assert(DS_TOP == DS_AT(dsp_orig)); REBDSP definitional_return_dsp = 0; // As we go through the spec block, we push TYPESET! BLOCK! TEXT! triples. // These will be split out into separate arrays after the process is done. // The first slot of the paramlist needs to be the function canon value, // while the other two first slots need to be rootkeys. Get the process // started right after a BLOCK! so it's willing to take a string for // the function description--it will be extracted from the slot before // it is turned into a rootkey for param_notes. // Init_Unreadable_Blank(DS_PUSH()); // paramlist[0] becomes ACT_ARCHETYPE() Move_Value(DS_PUSH(), EMPTY_BLOCK); // param_types[0] (object canon) Move_Value(DS_PUSH(), EMPTY_TEXT); // param_notes[0] (desc, then canon) // The process is broken up into phases so that the spec analysis code // can be reused in AUGMENT. // Push_Paramlist_Triads_May_Fail( spec, &flags, dsp_orig, &definitional_return_dsp ); return Pop_Paramlist_With_Meta_May_Fail( dsp_orig, flags, definitional_return_dsp ); } // // Find_Param_Index: C // // Find function param word in function "frame". // // !!! This is semi-redundant with similar functions for Find_Word_In_Array // and key finding for objects, review... // REBLEN Find_Param_Index(REBARR *paramlist, REBSTR *spelling) { REBSTR *canon = STR_CANON(spelling); // don't recalculate each time RELVAL *param = ARR_AT(paramlist, 1); REBLEN len = ARR_LEN(paramlist); REBLEN n; for (n = 1; n < len; ++n, ++param) { if ( spelling == VAL_PARAM_SPELLING(param) or canon == VAL_PARAM_CANON(param) ){ return n; } } return 0; } // // Make_Action: C // // Create an archetypal form of a function, given C code implementing a // dispatcher that will be called by Eval_Core. Dispatchers are of the form: // // const REBVAL *Dispatcher(REBFRM *f) {...} // // The REBACT returned is "archetypal" because individual REBVALs which hold // the same REBACT may differ in a per-REBVAL "binding". (This is how one // RETURN is distinguished from another--the binding data stored in the REBVAL // identifies the pointer of the FRAME! to exit). // // Actions have an associated REBARR of data, accessible via ACT_DETAILS(). // This is where they can store information that will be available when the // dispatcher is called. // REBACT *Make_Action( REBARR *paramlist, REBNAT dispatcher, // native C function called by Eval_Core REBACT *opt_underlying, // optional underlying function REBCTX *opt_exemplar, // if provided, should be consistent w/next level REBLEN details_capacity // desired capacity of the ACT_DETAILS() array ){ ASSERT_ARRAY_MANAGED(paramlist); RELVAL *rootparam = ARR_HEAD(paramlist); assert(KIND_BYTE(rootparam) == REB_ACTION); // !!! not fully formed... assert(VAL_ACT_PARAMLIST(rootparam) == paramlist); assert(EXTRA(Binding, rootparam).node == UNBOUND); // archetype // "details" for an action is an array of cells which can be anything // the dispatcher understands it to be, by contract. Terminate it // at the given length implicitly. REBARR *details = Make_Array_Core( details_capacity, SERIES_MASK_DETAILS | NODE_FLAG_MANAGED ); TERM_ARRAY_LEN(details, details_capacity); VAL_ACT_DETAILS_NODE(rootparam) = NOD(details); MISC(details).dispatcher = dispatcher; // level of indirection, hijackable assert(IS_POINTER_SAFETRASH_DEBUG(LINK(paramlist).trash)); if (opt_underlying) { LINK_UNDERLYING_NODE(paramlist) = NOD(opt_underlying); // Note: paramlist still incomplete, don't use SET_ACTION_FLAG.... // if (GET_ACTION_FLAG(opt_underlying, HAS_RETURN)) SER(paramlist)->header.bits |= PARAMLIST_FLAG_HAS_RETURN; } else { // To avoid NULL checking when a function is called and looking for // underlying, just use the action's own paramlist if needed. // LINK_UNDERLYING_NODE(paramlist) = NOD(paramlist); } if (not opt_exemplar) { // // No exemplar is used as a cue to set the "specialty" to paramlist, // so that Push_Action() can assign f->special directly from it in // dispatch, and be equal to f->param. // LINK_SPECIALTY_NODE(details) = NOD(paramlist); } else { // The parameters of the paramlist should line up with the slots of // the exemplar (though some of these parameters may be hidden due to // specialization, see REB_TS_HIDDEN). // assert(GET_SERIES_FLAG(opt_exemplar, MANAGED)); assert(CTX_LEN(opt_exemplar) == ARR_LEN(paramlist) - 1); LINK_SPECIALTY_NODE(details) = NOD(CTX_VARLIST(opt_exemplar)); } // The meta information may already be initialized, since the native // version of paramlist construction sets up the FUNCTION-META information // used by HELP. If so, it must be a valid REBCTX*. Otherwise NULL. // assert( not MISC_META(paramlist) or GET_ARRAY_FLAG(CTX_VARLIST(MISC_META(paramlist)), IS_VARLIST) ); assert(NOT_ARRAY_FLAG(paramlist, HAS_FILE_LINE_UNMASKED)); assert(NOT_ARRAY_FLAG(details, HAS_FILE_LINE_UNMASKED)); REBACT *act = ACT(paramlist); // now it's a legitimate REBACT // Precalculate cached function flags. This involves finding the first // unspecialized argument which would be taken at a callsite, which can // be tricky to figure out with partial refinement specialization. So // the work of doing that is factored into a routine (`PARAMETERS OF` // uses it as well). if (GET_ACTION_FLAG(act, HAS_RETURN)) { REBVAL *param = ACT_PARAMS_HEAD(act); assert(VAL_PARAM_SYM(param) == SYM_RETURN); if (Is_Typeset_Invisible(param)) // e.g. `return []` SET_ACTION_FLAG(act, IS_INVISIBLE); if (TYPE_CHECK(param, REB_TS_DEQUOTE_REQUOTE)) SET_ACTION_FLAG(act, RETURN_REQUOTES); } REBVAL *first_unspecialized = First_Unspecialized_Param(act); if (first_unspecialized) { switch (VAL_PARAM_CLASS(first_unspecialized)) { case REB_P_NORMAL: break; case REB_P_HARD_QUOTE: case REB_P_MODAL: case REB_P_SOFT_QUOTE: SET_ACTION_FLAG(act, QUOTES_FIRST); break; default: assert(false); } if (TYPE_CHECK(first_unspecialized, REB_TS_SKIPPABLE)) SET_ACTION_FLAG(act, SKIPPABLE_FIRST); } return act; } // // Make_Expired_Frame_Ctx_Managed: C // // FUNC/PROC bodies contain relative words and relative arrays. Arrays from // this relativized body may only be put into a specified REBVAL once they // have been combined with a frame. // // Reflection asks for action body data, when no instance is called. Hence // a REBVAL must be produced somehow. If the body is being copied, then the // option exists to convert all the references to unbound...but this isn't // representative of the actual connections in the body. // // There could be an additional "archetype" state for the relative binding // machinery. But making a one-off expired frame is an inexpensive option. // REBCTX *Make_Expired_Frame_Ctx_Managed(REBACT *a) { // Since passing SERIES_MASK_VARLIST includes SERIES_FLAG_ALWAYS_DYNAMIC, // don't pass it in to the allocation...it needs to be set, but will be // overridden by SERIES_INFO_INACCESSIBLE. // REBARR *varlist = Alloc_Singular(NODE_FLAG_STACK | NODE_FLAG_MANAGED); SER(varlist)->header.bits |= SERIES_MASK_VARLIST; SET_SERIES_INFO(varlist, INACCESSIBLE); MISC_META_NODE(varlist) = nullptr; RELVAL *rootvar = RESET_CELL( ARR_SINGLE(varlist), REB_FRAME, CELL_MASK_CONTEXT ); INIT_VAL_CONTEXT_VARLIST(rootvar, varlist); INIT_VAL_CONTEXT_PHASE(rootvar, a); INIT_BINDING(rootvar, UNBOUND); // !!! is a binding relevant? REBCTX *expired = CTX(varlist); INIT_CTX_KEYLIST_SHARED(expired, ACT_PARAMLIST(a)); return expired; } // // Get_Maybe_Fake_Action_Body: C // // !!! While the interface as far as the evaluator is concerned is satisfied // with the OneAction ACTION!, the various dispatchers have different ideas // of what "source" would be like. There should be some mapping from the // dispatchers to code to get the BODY OF an ACTION. For the moment, just // handle common kinds so the SOURCE command works adquately, revisit later. // void Get_Maybe_Fake_Action_Body(REBVAL *out, const REBVAL *action) { REBSPC *binding = VAL_BINDING(action); REBACT *a = VAL_ACTION(action); // A Hijacker *might* not need to splice itself in with a dispatcher. // But if it does, bypass it to get to the "real" action implementation. // // !!! Should the source inject messages like {This is a hijacking} at // the top of the returned body? // while (ACT_DISPATCHER(a) == &Hijacker_Dispatcher) { a = VAL_ACTION(ARR_HEAD(ACT_DETAILS(a))); // !!! Review what should happen to binding } REBARR *details = ACT_DETAILS(a); // !!! Should the binding make a difference in the returned body? It is // exposed programmatically via CONTEXT OF. // UNUSED(binding); if ( ACT_DISPATCHER(a) == &Null_Dispatcher or ACT_DISPATCHER(a) == &Void_Dispatcher or ACT_DISPATCHER(a) == &Unchecked_Dispatcher or ACT_DISPATCHER(a) == &Voider_Dispatcher or ACT_DISPATCHER(a) == &Returner_Dispatcher or ACT_DISPATCHER(a) == &Block_Dispatcher ){ // Interpreted code, the body is a block with some bindings relative // to the action. RELVAL *body = ARR_HEAD(details); // The PARAMLIST_HAS_RETURN tricks for definitional return make it // seem like a generator authored more code in the action's body...but // the code isn't *actually* there and an optimized internal trick is // used. Fake the code if needed. REBVAL *example; REBLEN real_body_index; if (ACT_DISPATCHER(a) == &Voider_Dispatcher) { example = Get_System(SYS_STANDARD, STD_PROC_BODY); real_body_index = 4; } else if (GET_ACTION_FLAG(a, HAS_RETURN)) { example = Get_System(SYS_STANDARD, STD_FUNC_BODY); real_body_index = 4; } else { example = NULL; real_body_index = 0; // avoid compiler warning UNUSED(real_body_index); } REBARR *real_body = VAL_ARRAY(body); REBARR *maybe_fake_body; if (example == NULL) { maybe_fake_body = real_body; } else { // See %sysobj.r for STANDARD/FUNC-BODY and STANDARD/PROC-BODY // maybe_fake_body = Copy_Array_Shallow_Flags( VAL_ARRAY(example), VAL_SPECIFIER(example), NODE_FLAG_MANAGED ); // Index 5 (or 4 in zero-based C) should be #BODY, a "real" body. // To give it the appearance of executing code in place, we use // a GROUP!. RELVAL *slot = ARR_AT(maybe_fake_body, real_body_index); // #BODY assert(IS_ISSUE(slot)); // Note: clears VAL_FLAG_LINE // RESET_VAL_HEADER(slot, REB_GROUP, CELL_FLAG_FIRST_IS_NODE); INIT_VAL_NODE(slot, VAL_ARRAY(body)); VAL_INDEX(slot) = 0; INIT_BINDING(slot, a); // relative binding } // Cannot give user a relative value back, so make the relative // body specific to a fabricated expired frame. See #2221 RESET_VAL_HEADER(out, REB_BLOCK, CELL_FLAG_FIRST_IS_NODE); INIT_VAL_NODE(out, maybe_fake_body); VAL_INDEX(out) = 0; INIT_BINDING(out, Make_Expired_Frame_Ctx_Managed(a)); return; } if (ACT_DISPATCHER(a) == &Specializer_Dispatcher) { // // The FRAME! stored in the body for the specialization has a phase // which is actually the function to be run. // REBVAL *frame = KNOWN(ARR_HEAD(details)); assert(IS_FRAME(frame)); Move_Value(out, frame); return; } if (ACT_DISPATCHER(a) == &Generic_Dispatcher) { REBVAL *verb = KNOWN(ARR_HEAD(details)); assert(IS_WORD(verb)); Move_Value(out, verb); return; } Init_Blank(out); // natives, ffi routines, etc. return; } // // Make_Interpreted_Action_May_Fail: C // // This is the support routine behind both `MAKE ACTION!` and FUNC. // // Ren-C's schematic is *very* different from R3-Alpha, whose definition of // FUNC was simply: // // make function! copy/deep reduce [spec body] // // Ren-C's `make action!` doesn't need to copy the spec (it does not save // it--parameter descriptions are in a meta object). The body is copied // implicitly (as it must be in order to relativize it). // // There is also a "definitional return" MKF_RETURN option used by FUNC, so // the body will introduce a RETURN specific to each action invocation, thus // acting more like: // // return: make action! [ // [{Returns a value from a function.} value [<opt> any-value!]] // [unwind/with (binding of 'return) :value] // ] // (body goes here) // // This pattern addresses "Definitional Return" in a way that does not need to // build in RETURN as a language keyword in any specific form (in the sense // that MAKE ACTION! does not itself require it). // // FUNC optimizes by not internally building or executing the equivalent body, // but giving it back from BODY-OF. This gives FUNC the edge to pretend to // add containing code and simulate its effects, while really only holding // onto the body the caller provided. // // While plain MAKE ACTION! has no RETURN, UNWIND can be used to exit frames // but must be explicit about what frame is being exited. This can be used // by usermode generators that want to create something return-like. // REBACT *Make_Interpreted_Action_May_Fail( const REBVAL *spec, const REBVAL *body, REBFLGS mkf_flags // MKF_RETURN, etc. ) { assert(IS_BLOCK(spec) and IS_BLOCK(body)); REBACT *a = Make_Action( Make_Paramlist_Managed_May_Fail(spec, mkf_flags), &Null_Dispatcher, // will be overwritten if non-[] body nullptr, // no underlying action (use paramlist) nullptr, // no specialization exemplar (or inherited exemplar) 1 // details array capacity ); // We look at the *actual* function flags; e.g. the person may have used // the FUNC generator (with MKF_RETURN) but then named a parameter RETURN // which overrides it, so the value won't have PARAMLIST_HAS_RETURN. REBARR *copy; if (VAL_ARRAY_LEN_AT(body) == 0) { // optimize empty body case if (GET_ACTION_FLAG(a, IS_INVISIBLE)) { ACT_DISPATCHER(a) = &Commenter_Dispatcher; } else if (SER(a)->info.bits & ARRAY_INFO_MISC_VOIDER) { ACT_DISPATCHER(a) = &Voider_Dispatcher; // !!! ^-- see info note } else if (GET_ACTION_FLAG(a, HAS_RETURN)) { REBVAL *typeset = ACT_PARAMS_HEAD(a); assert(VAL_PARAM_SYM(typeset) == SYM_RETURN); if (not TYPE_CHECK(typeset, REB_NULLED)) // `do []` returns ACT_DISPATCHER(a) = &Returner_Dispatcher; // error when run } else { // Keep the Null_Dispatcher passed in above } // Reusing EMPTY_ARRAY won't allow adding ARRAY_HAS_FILE_LINE bits // copy = Make_Array_Core(1, NODE_FLAG_MANAGED); } else { // body not empty, pick dispatcher based on output disposition if (GET_ACTION_FLAG(a, IS_INVISIBLE)) ACT_DISPATCHER(a) = &Elider_Dispatcher; // no f->out mutation else if (SER(a)->info.bits & ARRAY_INFO_MISC_VOIDER) // !!! see note ACT_DISPATCHER(a) = &Voider_Dispatcher; // forces f->out void else if (GET_ACTION_FLAG(a, HAS_RETURN)) ACT_DISPATCHER(a) = &Returner_Dispatcher; // type checks f->out else ACT_DISPATCHER(a) = &Unchecked_Dispatcher; // unchecked f->out copy = Copy_And_Bind_Relative_Deep_Managed( body, // new copy has locals bound relatively to the new action ACT_PARAMLIST(a), TS_WORD, true // gather the LETs (transitional method) ); } // Favor the spec first, then the body, for file and line information. // if (GET_ARRAY_FLAG(VAL_ARRAY(spec), HAS_FILE_LINE_UNMASKED)) { LINK_FILE_NODE(copy) = LINK_FILE_NODE(VAL_ARRAY(spec)); MISC(copy).line = MISC(VAL_ARRAY(spec)).line; SET_ARRAY_FLAG(copy, HAS_FILE_LINE_UNMASKED); } else if (GET_ARRAY_FLAG(VAL_ARRAY(body), HAS_FILE_LINE_UNMASKED)) { LINK_FILE_NODE(copy) = LINK_FILE_NODE(VAL_ARRAY(body)); MISC(copy).line = MISC(VAL_ARRAY(body)).line; SET_ARRAY_FLAG(copy, HAS_FILE_LINE_UNMASKED); } else { // Ideally all source series should have a file and line numbering // At the moment, if a function is created in the body of another // function it doesn't work...trying to fix that. } // Save the relativized body in the action's details block. Since it is // a RELVAL* and not a REBVAL*, the dispatcher must combine it with a // running frame instance (the REBFRM* received by the dispatcher) before // executing the interpreted code. // REBARR *details = ACT_DETAILS(a); RELVAL *rebound = Init_Relative_Block( ARR_AT(details, IDX_NATIVE_BODY), a, copy ); // Capture the mutability flag that was in effect when this action was // created. This allows the following to work: // // >> do mutable [f: function [] [b: [1 2 3] clear b]] // >> f // == [] // // So even though the invocation is outside the mutable section, we have // a memory that it was created under those rules. (It's better to do // this based on the frame in effect than by looking at the CONST flag of // the incoming body block, because otherwise ordinary Ren-C functions // whose bodies were created from dynamic code would have mutable bodies // by default--which is not a desirable consequence from merely building // the body dynamically.) // // Note: besides the general concerns about mutability-by-default, when // functions are allowed to modify their bodies with words relative to // their frame, the words would refer to that specific recursion...and not // get picked up by other recursions that see the common structure. This // means compatibility would be with the behavior of R3-Alpha CLOSURE, // not with R3-Alpha FUNCTION. // if (GET_CELL_FLAG(body, CONST)) SET_CELL_FLAG(rebound, CONST); // Inherit_Const() would need REBVAL* return a; } // // REBTYPE: C // // This handler is used to fail for a type which cannot handle actions. // // !!! Currently all types have a REBTYPE() handler for either themselves or // their class. But having a handler that could be "swapped in" from a // default failing case is an idea that could be used as an interim step // to allow something like REB_GOB to fail by default, but have the failing // type handler swapped out by an extension. // REBTYPE(Fail) { UNUSED(frame_); UNUSED(verb); fail ("Datatype does not have a dispatcher registered."); } // // Generic_Dispatcher: C // // A "generic" is what R3-Alpha/Rebol2 had called "ACTION!" (until Ren-C took // that as the umbrella term for all "invokables"). This kind of dispatch is // based on the first argument's type, with the idea being a single C function // for the type has a switch() statement in it and can handle many different // such actions for that type. // // (e.g. APPEND copy [a b c] [d] would look at the type of the first argument, // notice it was a BLOCK!, and call the common C function for arrays with an // append instruction--where that instruction also handles insert, length, // etc. for BLOCK!s.) // // !!! This mechanism is a very primitive kind of "multiple dispatch". Rebol // will certainly need to borrow from other languages to develop a more // flexible idea for user-defined types, vs. this very limited concept. // // https://en.wikipedia.org/wiki/Multiple_dispatch // https://en.wikipedia.org/wiki/Generic_function // https://stackoverflow.com/q/53574843/ // REB_R Generic_Dispatcher(REBFRM *f) { REBACT *phase = FRM_PHASE(f); REBARR *details = ACT_DETAILS(phase); REBVAL *verb = KNOWN(ARR_HEAD(details)); assert(IS_WORD(verb)); // !!! It's technically possible to throw in locals or refinements at // any point in the sequence. So this should really be using something // like a First_Unspecialized_Arg() call. For now, we just handle the // case of a RETURN: sitting in the first parameter slot. // REBVAL *first_arg = GET_ACTION_FLAG(phase, HAS_RETURN) ? FRM_ARG(f, 2) : FRM_ARG(f, 1); return Run_Generic_Dispatch(first_arg, f, verb); } // // Dummy_Dispatcher: C // // Used for frame levels that want a varlist solely for the purposes of tying // API handle lifetimes to. These levels should be ignored by stack walks // that the user sees, and this associated dispatcher should never run. // REB_R Dummy_Dispatcher(REBFRM *f) { UNUSED(f); panic ("Dummy_Dispatcher() ran, but it never should get called"); } // // Void_Dispatcher: C // // If you write `func [return: <void> ...] []` it uses this dispatcher instead // of running Eval_Core() on an empty block. This serves more of a point than // it sounds, because you can make fast stub actions that only cost if they // are HIJACK'd (e.g. ASSERT is done this way). // REB_R Void_Dispatcher(REBFRM *f) { REBARR *details = ACT_DETAILS(FRM_PHASE(f)); assert(VAL_LEN_AT(ARR_HEAD(details)) == 0); UNUSED(details); return Init_Void(f->out); } // // Null_Dispatcher: C // // Analogue to Void_Dispatcher() for `func [return: [<opt>] ...] [null]` // situations. // REB_R Null_Dispatcher(REBFRM *f) { REBARR *details = ACT_DETAILS(FRM_PHASE(f)); assert(VAL_LEN_AT(ARR_HEAD(details)) == 0); UNUSED(details); return nullptr; } // // Datatype_Checker_Dispatcher: C // // Dispatcher used by TYPECHECKER generator for when argument is a datatype. // REB_R Datatype_Checker_Dispatcher(REBFRM *f) { REBARR *details = ACT_DETAILS(FRM_PHASE(f)); RELVAL *datatype = ARR_HEAD(details); if (VAL_TYPE_KIND_OR_CUSTOM(datatype) == REB_CUSTOM) { if (VAL_TYPE(FRM_ARG(f, 1)) != REB_CUSTOM) return Init_False(f->out); REBTYP *typ = VAL_TYPE_CUSTOM(datatype); return Init_Logic( f->out, CELL_CUSTOM_TYPE(FRM_ARG(f, 1)) == typ ); } return Init_Logic( // otherwise won't be equal to any custom type f->out, VAL_TYPE(FRM_ARG(f, 1)) == VAL_TYPE_KIND_OR_CUSTOM(datatype) ); } // // Typeset_Checker_Dispatcher: C // // Dispatcher used by TYPECHECKER generator for when argument is a typeset. // REB_R Typeset_Checker_Dispatcher(REBFRM *f) { REBARR *details = ACT_DETAILS(FRM_PHASE(f)); RELVAL *typeset = ARR_HEAD(details); assert(IS_TYPESET(typeset)); return Init_Logic(f->out, TYPE_CHECK(typeset, VAL_TYPE(FRM_ARG(f, 1)))); } // Common behavior shared by dispatchers which execute on BLOCK!s of code. // inline static bool Interpreted_Dispatch_Throws( REBVAL *out, // Note: Elider_Dispatcher() doesn't have `out = f->out` REBFRM *f ){ REBARR *details = ACT_DETAILS(FRM_PHASE(f)); RELVAL *body = ARR_HEAD(details); // usually CONST (doesn't have to be) assert(IS_BLOCK(body) and IS_RELATIVE(body) and VAL_INDEX(body) == 0); // The function body contains relativized words, that point to the // paramlist but do not have an instance of an action to line them up // with. We use the frame (identified by varlist) as the "specifier". // return Do_Any_Array_At_Throws(out, body, SPC(f->varlist)); } // // Unchecked_Dispatcher: C // // Runs block, then no typechecking (e.g. had no RETURN: [...] type spec) // REB_R Unchecked_Dispatcher(REBFRM *f) { if (Interpreted_Dispatch_Throws(f->out, f)) return R_THROWN; return f->out; } // // Voider_Dispatcher: C // // Runs block, then overwrites result w/void (e.g. RETURN: <void>) // REB_R Voider_Dispatcher(REBFRM *f) { if (Interpreted_Dispatch_Throws(f->out, f)) // action body is a BLOCK! return R_THROWN; return Init_Void(f->out); } // // Returner_Dispatcher: C // // Runs block, ensure type matches RETURN: [...] specification, else fail. // // Note: Natives get this check only in the debug build, but not here (their // dispatcher *is* the native!) So the extra check is in Eval_Core(). // REB_R Returner_Dispatcher(REBFRM *f) { if (Interpreted_Dispatch_Throws(f->out, f)) return R_THROWN; FAIL_IF_BAD_RETURN_TYPE(f); return f->out; } // // Elider_Dispatcher: C // // Used by "invisible" functions (who in their spec say `RETURN: []`). Runs // block but without changing any value already in f->out. // REB_R Elider_Dispatcher(REBFRM *f) { REBVAL * const discarded = FRM_SPARE(f); // spare usable during dispatch if (Interpreted_Dispatch_Throws(discarded, f)) { // // !!! In the implementation of invisibles, it seems reasonable to // want to be able to RETURN to its own frame. But in that case, we // don't want to actually overwrite the f->out content or this would // be no longer invisible. Until a better idea comes along, repeat // the work of catching here. (Note this does not handle REDO too, // and the hypothetical better idea should do so.) // const REBVAL *label = VAL_THROWN_LABEL(discarded); if (IS_ACTION(label)) { if ( VAL_ACTION(label) == NAT_ACTION(unwind) and VAL_BINDING(label) == NOD(f->varlist) ){ CATCH_THROWN(discarded, discarded); if (IS_NULLED(discarded)) // !!! catch loses "endish" flag return R_INVISIBLE; fail ("Only 0-arity RETURN should be used in invisibles."); } } Move_Value(f->out, discarded); return R_THROWN; } return R_INVISIBLE; } // // Commenter_Dispatcher: C // // This is a specialized version of Elider_Dispatcher() for when the body of // a function is empty. This helps COMMENT and functions like it run faster. // REB_R Commenter_Dispatcher(REBFRM *f) { REBARR *details = ACT_DETAILS(FRM_PHASE(f)); RELVAL *body = ARR_HEAD(details); assert(VAL_LEN_AT(body) == 0); UNUSED(body); return R_INVISIBLE; } // // Hijacker_Dispatcher: C // // A hijacker takes over another function's identity, replacing it with its // own implementation, injecting directly into the paramlist and body_holder // nodes held onto by all the victim's references. // // Sometimes the hijacking function has the same underlying function // as the victim, in which case there's no need to insert a new dispatcher. // The hijacker just takes over the identity. But otherwise it cannot, // and a "shim" is needed...since something like an ADAPT or SPECIALIZE // or a MAKE FRAME! might depend on the existing paramlist shape. // REB_R Hijacker_Dispatcher(REBFRM *f) { REBACT *phase = FRM_PHASE(f); REBARR *details = ACT_DETAILS(phase); RELVAL *hijacker = ARR_HEAD(details); // We need to build a new frame compatible with the hijacker, and // transform the parameters we've gathered to be compatible with it. // if (Redo_Action_Throws(f->out, f, VAL_ACTION(hijacker))) return R_THROWN; if (GET_ACTION_FLAG(phase, IS_INVISIBLE)) return R_INVISIBLE; return f->out; } // // Adapter_Dispatcher: C // // Dispatcher used by ADAPT. // REB_R Adapter_Dispatcher(REBFRM *f) { REBARR *details = ACT_DETAILS(FRM_PHASE(f)); assert(ARR_LEN(details) == 2); RELVAL* prelude = ARR_AT(details, 0); REBVAL* adaptee = KNOWN(ARR_AT(details, 1)); // The first thing to do is run the prelude code, which may throw. If it // does throw--including a RETURN--that means the adapted function will // not be run. REBVAL * const discarded = FRM_SPARE(f); if (Do_Any_Array_At_Throws(discarded, prelude, SPC(f->varlist))) { Move_Value(f->out, discarded); return R_THROWN; } INIT_FRM_PHASE(f, VAL_ACTION(adaptee)); FRM_BINDING(f) = VAL_BINDING(adaptee); return R_REDO_CHECKED; // the redo will use the updated phase & binding } // // Encloser_Dispatcher: C // // Dispatcher used by ENCLOSE. // REB_R Encloser_Dispatcher(REBFRM *f) { REBARR *details = ACT_DETAILS(FRM_PHASE(f)); assert(ARR_LEN(details) == 2); REBVAL *inner = KNOWN(ARR_AT(details, 0)); // same args as f assert(IS_ACTION(inner)); REBVAL *outer = KNOWN(ARR_AT(details, 1)); // takes 1 arg (a FRAME!) assert(IS_ACTION(outer)); assert(GET_SERIES_FLAG(f->varlist, STACK_LIFETIME)); // We want to call OUTER with a FRAME! value that will dispatch to INNER // when (and if) it runs DO on it. That frame is the one built for this // call to the encloser. If it isn't managed, there's no worries about // user handles on it...so just take it. Otherwise, "steal" its vars. // REBCTX *c = Steal_Context_Vars(CTX(f->varlist), NOD(FRM_PHASE(f))); INIT_LINK_KEYSOURCE(c, NOD(VAL_ACTION(inner))); CLEAR_SERIES_FLAG(c, STACK_LIFETIME); assert(GET_SERIES_INFO(f->varlist, INACCESSIBLE)); // look dead // f->varlist may or may not have wound up being managed. It was not // allocated through the usual mechanisms, so if unmanaged it's not in // the tracking list Init_Any_Context() expects. Just fiddle the bit. // SET_SERIES_FLAG(c, MANAGED); // When the DO of the FRAME! executes, we don't want it to run the // encloser again (infinite loop). // REBVAL *rootvar = CTX_ARCHETYPE(c); INIT_VAL_CONTEXT_PHASE(rootvar, VAL_ACTION(inner)); INIT_BINDING_MAY_MANAGE(rootvar, VAL_BINDING(inner)); // We don't actually know how long the frame we give back is going to // live, or who it might be given to. And it may contain things like // bindings in a RETURN or a VARARGS! which are to the old varlist, which // may not be managed...and so when it goes off the stack it might try // and think that since nothing managed it then it can be freed. Go // ahead and mark it managed--even though it's dead--so that returning // won't free it if there are outstanding references. // // Note that since varlists aren't added to the manual series list, the // bit must be tweaked vs. using Ensure_Array_Managed. // SET_SERIES_FLAG(f->varlist, MANAGED); const bool fully = true; if (RunQ_Throws(f->out, fully, rebU1(outer), rootvar, rebEND)) return R_THROWN; return f->out; } // // Chainer_Dispatcher: C // // Dispatcher used by CHAIN. // REB_R Chainer_Dispatcher(REBFRM *f) { REBARR *details = ACT_DETAILS(FRM_PHASE(f)); REBARR *pipeline = VAL_ARRAY(ARR_HEAD(details)); // The post-processing pipeline has to be "pushed" so it is not forgotten. // Go in reverse order, so the function to apply last is at the bottom of // the stack. // REBVAL *chained = KNOWN(ARR_LAST(pipeline)); for (; chained != ARR_HEAD(pipeline); --chained) { assert(IS_ACTION(chained)); Move_Value(DS_PUSH(), KNOWN(chained)); } // Extract the first function, itself which might be a chain. // INIT_FRM_PHASE(f, VAL_ACTION(chained)); FRM_BINDING(f) = VAL_BINDING(chained); return R_REDO_UNCHECKED; // signatures should match } // // Get_If_Word_Or_Path_Throws: C // // Some routines like APPLY and SPECIALIZE are willing to take a WORD! or // PATH! instead of just the value type they are looking for, and perform // the GET for you. By doing the GET inside the function, they are able // to preserve the symbol: // // >> applique 'append [value: 'c] // ** Script error: append is missing its series argument // // If push_refinements is used, then it avoids intermediate specializations... // e.g. `specialize 'append/dup [part: true]` can be done with one FRAME!. // bool Get_If_Word_Or_Path_Throws( REBVAL *out, REBSTR **opt_name_out, const RELVAL *v, REBSPC *specifier, bool push_refinements ) { if (IS_WORD(v) or IS_GET_WORD(v) or IS_SYM_WORD(v)) { if (opt_name_out) *opt_name_out = VAL_WORD_SPELLING(v); Get_Word_May_Fail(out, v, specifier); } else if (IS_PATH(v) or IS_GET_PATH(v) or IS_SYM_PATH(v)) { REBSPC *derived = Derive_Specifier(specifier, v); if (Eval_Path_Throws_Core( out, opt_name_out, // requesting says we run functions (not GET-PATH!) VAL_ARRAY(v), VAL_INDEX(v), derived, NULL, // `setval`: null means don't treat as SET-PATH! EVAL_MASK_DEFAULT | (push_refinements ? EVAL_FLAG_PUSH_PATH_REFINES // pushed in reverse order : 0) )){ return true; } } else { *opt_name_out = NULL; Derelativize(out, v, specifier); } return false; }
391326.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" FLA_Error FLA_Tridiag_apply_Q_external( FLA_Side side, FLA_Uplo uplo, FLA_Trans trans, FLA_Obj A, FLA_Obj t, FLA_Obj B ) { int info = 0; #ifdef FLA_ENABLE_EXTERNAL_LAPACK_INTERFACES FLA_Datatype datatype; // int m_A, n_A; int m_B, n_B; int cs_A; int cs_B; int k_t; int lwork; char blas_side; char blas_uplo; char blas_trans; FLA_Obj work; int i; //if ( FLA_Check_error_level() == FLA_FULL_ERROR_CHECKING ) // FLA_Apply_Q_check( side, trans, storev, A, t, B ); if ( FLA_Obj_has_zero_dim( A ) ) return FLA_SUCCESS; datatype = FLA_Obj_datatype( A ); // m_A = FLA_Obj_length( A ); // n_A = FLA_Obj_width( A ); cs_A = FLA_Obj_col_stride( A ); m_B = FLA_Obj_length( B ); n_B = FLA_Obj_width( B ); cs_B = FLA_Obj_col_stride( B ); k_t = FLA_Obj_vector_dim( t ); FLA_Param_map_flame_to_netlib_side( side, &blas_side ); FLA_Param_map_flame_to_netlib_uplo( uplo, &blas_uplo ); FLA_Param_map_flame_to_netlib_trans( trans, &blas_trans ); // Make a workspace query the first time through. This will provide us with // and ideal workspace size based on an internal block size. lwork = -1; FLA_Obj_create( datatype, 1, 1, 0, 0, &work ); for ( i = 0; i < 2; ++i ) { if ( i == 1 ) { // Grab the queried ideal workspace size from the work array, free the // work object, and then re-allocate the workspace with the ideal size. if ( datatype == FLA_FLOAT || datatype == FLA_COMPLEX ) lwork = ( int ) *FLA_FLOAT_PTR( work ); else if ( datatype == FLA_DOUBLE || datatype == FLA_DOUBLE_COMPLEX ) lwork = ( int ) *FLA_DOUBLE_PTR( work ); FLA_Obj_free( &work ); FLA_Obj_create( datatype, lwork, 1, 0, 0, &work ); } switch( datatype ){ case FLA_FLOAT: { float *buff_A = ( float * ) FLA_FLOAT_PTR( A ); float *buff_t = ( float * ) FLA_FLOAT_PTR( t ); float *buff_B = ( float * ) FLA_FLOAT_PTR( B ); float *buff_work = ( float * ) FLA_FLOAT_PTR( work ); F77_sormtr( &blas_side, &blas_uplo, &blas_trans, &m_B, &n_B, buff_A, &cs_A, buff_t, buff_B, &cs_B, buff_work, &lwork, &info ); break; } case FLA_DOUBLE: { double *buff_A = ( double * ) FLA_DOUBLE_PTR( A ); double *buff_t = ( double * ) FLA_DOUBLE_PTR( t ); double *buff_B = ( double * ) FLA_DOUBLE_PTR( B ); double *buff_work = ( double * ) FLA_DOUBLE_PTR( work ); F77_dormtr( &blas_side, &blas_uplo, &blas_trans, &m_B, &n_B, buff_A, &cs_A, buff_t, buff_B, &cs_B, buff_work, &lwork, &info ); break; } case FLA_COMPLEX: { scomplex *buff_A = ( scomplex * ) FLA_COMPLEX_PTR( A ); scomplex *buff_t = ( scomplex * ) FLA_COMPLEX_PTR( t ); scomplex *buff_B = ( scomplex * ) FLA_COMPLEX_PTR( B ); scomplex *buff_work = ( scomplex * ) FLA_COMPLEX_PTR( work ); F77_cunmtr( &blas_side, &blas_uplo, &blas_trans, &m_B, &n_B, buff_A, &cs_A, buff_t, buff_B, &cs_B, buff_work, &lwork, &info ); break; } case FLA_DOUBLE_COMPLEX: { dcomplex *buff_A = ( dcomplex * ) FLA_DOUBLE_COMPLEX_PTR( A ); dcomplex *buff_t = ( dcomplex * ) FLA_DOUBLE_COMPLEX_PTR( t ); dcomplex *buff_B = ( dcomplex * ) FLA_DOUBLE_COMPLEX_PTR( B ); dcomplex *buff_work = ( dcomplex * ) FLA_DOUBLE_COMPLEX_PTR( work ); F77_zunmtr( &blas_side, &blas_uplo, &blas_trans, &m_B, &n_B, buff_A, &cs_A, buff_t, buff_B, &cs_B, buff_work, &lwork, &info ); break; } } } FLA_Obj_free( &work ); #else FLA_Check_error_code( FLA_EXTERNAL_LAPACK_NOT_IMPLEMENTED ); #endif return info; }
236899.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. */ /** \file * \ingroup bli * \brief Generic memory manipulation API. * * This is to extend on existing functions * such as ``memcpy`` & ``memcmp``. */ #include <string.h> #include "BLI_sys_types.h" #include "BLI_utildefines.h" #include "BLI_memory_utils.h" #include "BLI_strict_flags.h" /** * Check if memory is zero'd, as with memset(s, 0, nbytes) */ bool BLI_memory_is_zero(const void *s, const size_t nbytes) { const char *s_byte = s; const char *s_end = (const char *)s + nbytes; while ((s_byte != s_end) && (*s_byte == 0)) { s_byte++; } return (s_byte == s_end); }
278615.c
#include "compat.h" #include "persistence.h" #if defined LINUX int EnablePersistence(char* beaconIP, int beaconPort) { //TODO: just to silence the compiler warning beaconIP++; beaconPort++; return 0; } #elif defined SOLARIS int EnablePersistence(char* beaconIP, int beaconPort) { //TODO: just to silence the compiler warning beaconIP++; beaconPort++; return 0; } #endif
27628.c
/* * Copyright © 2018, VideoLAN and dav1d authors * Copyright © 2018, Two Orioles, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "src/cpu.h" #include "src/mc.h" decl_mc_fn(dav1d_put_8tap_regular_avx2); decl_mc_fn(dav1d_put_8tap_regular_ssse3); decl_mc_fn(dav1d_put_8tap_regular_smooth_avx2); decl_mc_fn(dav1d_put_8tap_regular_smooth_ssse3); decl_mc_fn(dav1d_put_8tap_regular_sharp_avx2); decl_mc_fn(dav1d_put_8tap_regular_sharp_ssse3); decl_mc_fn(dav1d_put_8tap_smooth_avx2); decl_mc_fn(dav1d_put_8tap_smooth_ssse3); decl_mc_fn(dav1d_put_8tap_smooth_regular_avx2); decl_mc_fn(dav1d_put_8tap_smooth_regular_ssse3); decl_mc_fn(dav1d_put_8tap_smooth_sharp_avx2); decl_mc_fn(dav1d_put_8tap_smooth_sharp_ssse3); decl_mc_fn(dav1d_put_8tap_sharp_avx2); decl_mc_fn(dav1d_put_8tap_sharp_ssse3); decl_mc_fn(dav1d_put_8tap_sharp_regular_avx2); decl_mc_fn(dav1d_put_8tap_sharp_regular_ssse3); decl_mc_fn(dav1d_put_8tap_sharp_smooth_avx2); decl_mc_fn(dav1d_put_8tap_sharp_smooth_ssse3); decl_mc_fn(dav1d_put_bilin_avx2); decl_mc_fn(dav1d_put_bilin_ssse3); decl_mct_fn(dav1d_prep_8tap_regular_avx512icl); decl_mct_fn(dav1d_prep_8tap_regular_avx2); decl_mct_fn(dav1d_prep_8tap_regular_ssse3); decl_mct_fn(dav1d_prep_8tap_regular_sse2); decl_mct_fn(dav1d_prep_8tap_regular_smooth_avx512icl); decl_mct_fn(dav1d_prep_8tap_regular_smooth_avx2); decl_mct_fn(dav1d_prep_8tap_regular_smooth_ssse3); decl_mct_fn(dav1d_prep_8tap_regular_smooth_sse2); decl_mct_fn(dav1d_prep_8tap_regular_sharp_avx512icl); decl_mct_fn(dav1d_prep_8tap_regular_sharp_avx2); decl_mct_fn(dav1d_prep_8tap_regular_sharp_ssse3); decl_mct_fn(dav1d_prep_8tap_regular_sharp_sse2); decl_mct_fn(dav1d_prep_8tap_smooth_avx512icl); decl_mct_fn(dav1d_prep_8tap_smooth_avx2); decl_mct_fn(dav1d_prep_8tap_smooth_ssse3); decl_mct_fn(dav1d_prep_8tap_smooth_sse2); decl_mct_fn(dav1d_prep_8tap_smooth_regular_avx512icl); decl_mct_fn(dav1d_prep_8tap_smooth_regular_avx2); decl_mct_fn(dav1d_prep_8tap_smooth_regular_ssse3); decl_mct_fn(dav1d_prep_8tap_smooth_regular_sse2); decl_mct_fn(dav1d_prep_8tap_smooth_sharp_avx512icl); decl_mct_fn(dav1d_prep_8tap_smooth_sharp_avx2); decl_mct_fn(dav1d_prep_8tap_smooth_sharp_ssse3); decl_mct_fn(dav1d_prep_8tap_smooth_sharp_sse2); decl_mct_fn(dav1d_prep_8tap_sharp_avx512icl); decl_mct_fn(dav1d_prep_8tap_sharp_avx2); decl_mct_fn(dav1d_prep_8tap_sharp_ssse3); decl_mct_fn(dav1d_prep_8tap_sharp_sse2); decl_mct_fn(dav1d_prep_8tap_sharp_regular_avx512icl); decl_mct_fn(dav1d_prep_8tap_sharp_regular_avx2); decl_mct_fn(dav1d_prep_8tap_sharp_regular_ssse3); decl_mct_fn(dav1d_prep_8tap_sharp_regular_sse2); decl_mct_fn(dav1d_prep_8tap_sharp_smooth_avx512icl); decl_mct_fn(dav1d_prep_8tap_sharp_smooth_avx2); decl_mct_fn(dav1d_prep_8tap_sharp_smooth_ssse3); decl_mct_fn(dav1d_prep_8tap_sharp_smooth_sse2); decl_mct_fn(dav1d_prep_bilin_avx512icl); decl_mct_fn(dav1d_prep_bilin_avx2); decl_mct_fn(dav1d_prep_bilin_ssse3); decl_mct_fn(dav1d_prep_bilin_sse2); decl_mc_scaled_fn(dav1d_put_8tap_scaled_regular_avx2); decl_mc_scaled_fn(dav1d_put_8tap_scaled_regular_smooth_avx2); decl_mc_scaled_fn(dav1d_put_8tap_scaled_regular_sharp_avx2); decl_mc_scaled_fn(dav1d_put_8tap_scaled_smooth_avx2); decl_mc_scaled_fn(dav1d_put_8tap_scaled_smooth_regular_avx2); decl_mc_scaled_fn(dav1d_put_8tap_scaled_smooth_sharp_avx2); decl_mc_scaled_fn(dav1d_put_8tap_scaled_sharp_avx2); decl_mc_scaled_fn(dav1d_put_8tap_scaled_sharp_regular_avx2); decl_mc_scaled_fn(dav1d_put_8tap_scaled_sharp_smooth_avx2); decl_mc_scaled_fn(dav1d_put_bilin_scaled_avx2); decl_mct_scaled_fn(dav1d_prep_8tap_scaled_regular_avx2); decl_mct_scaled_fn(dav1d_prep_8tap_scaled_regular_smooth_avx2); decl_mct_scaled_fn(dav1d_prep_8tap_scaled_regular_sharp_avx2); decl_mct_scaled_fn(dav1d_prep_8tap_scaled_smooth_avx2); decl_mct_scaled_fn(dav1d_prep_8tap_scaled_smooth_regular_avx2); decl_mct_scaled_fn(dav1d_prep_8tap_scaled_smooth_sharp_avx2); decl_mct_scaled_fn(dav1d_prep_8tap_scaled_sharp_avx2); decl_mct_scaled_fn(dav1d_prep_8tap_scaled_sharp_regular_avx2); decl_mct_scaled_fn(dav1d_prep_8tap_scaled_sharp_smooth_avx2); decl_mct_scaled_fn(dav1d_prep_bilin_scaled_avx2); decl_avg_fn(dav1d_avg_avx512icl); decl_avg_fn(dav1d_avg_avx2); decl_avg_fn(dav1d_avg_ssse3); decl_w_avg_fn(dav1d_w_avg_avx512icl); decl_w_avg_fn(dav1d_w_avg_avx2); decl_w_avg_fn(dav1d_w_avg_ssse3); decl_mask_fn(dav1d_mask_avx512icl); decl_mask_fn(dav1d_mask_avx2); decl_mask_fn(dav1d_mask_ssse3); decl_w_mask_fn(dav1d_w_mask_420_avx512icl); decl_w_mask_fn(dav1d_w_mask_420_avx2); decl_w_mask_fn(dav1d_w_mask_420_ssse3); decl_w_mask_fn(dav1d_w_mask_422_avx512icl); decl_w_mask_fn(dav1d_w_mask_422_avx2); decl_w_mask_fn(dav1d_w_mask_444_avx512icl); decl_w_mask_fn(dav1d_w_mask_444_avx2); decl_blend_fn(dav1d_blend_avx2); decl_blend_fn(dav1d_blend_ssse3); decl_blend_dir_fn(dav1d_blend_v_avx2); decl_blend_dir_fn(dav1d_blend_v_ssse3); decl_blend_dir_fn(dav1d_blend_h_avx2); decl_blend_dir_fn(dav1d_blend_h_ssse3); decl_warp8x8_fn(dav1d_warp_affine_8x8_avx2); decl_warp8x8_fn(dav1d_warp_affine_8x8_sse4); decl_warp8x8_fn(dav1d_warp_affine_8x8_ssse3); decl_warp8x8_fn(dav1d_warp_affine_8x8_sse2); decl_warp8x8t_fn(dav1d_warp_affine_8x8t_avx2); decl_warp8x8t_fn(dav1d_warp_affine_8x8t_sse4); decl_warp8x8t_fn(dav1d_warp_affine_8x8t_ssse3); decl_warp8x8t_fn(dav1d_warp_affine_8x8t_sse2); decl_emu_edge_fn(dav1d_emu_edge_avx2); decl_emu_edge_fn(dav1d_emu_edge_ssse3); decl_resize_fn(dav1d_resize_avx2); decl_resize_fn(dav1d_resize_ssse3); COLD void bitfn(dav1d_mc_dsp_init_x86)(Dav1dMCDSPContext *const c) { #define init_mc_fn(type, name, suffix) \ c->mc[type] = dav1d_put_##name##_##suffix #define init_mct_fn(type, name, suffix) \ c->mct[type] = dav1d_prep_##name##_##suffix #define init_mc_scaled_fn(type, name, suffix) \ c->mc_scaled[type] = dav1d_put_##name##_##suffix #define init_mct_scaled_fn(type, name, suffix) \ c->mct_scaled[type] = dav1d_prep_##name##_##suffix const unsigned flags = dav1d_get_cpu_flags(); if(!(flags & DAV1D_X86_CPU_FLAG_SSE2)) return; #if BITDEPTH == 8 init_mct_fn(FILTER_2D_BILINEAR, bilin, sse2); init_mct_fn(FILTER_2D_8TAP_REGULAR, 8tap_regular, sse2); init_mct_fn(FILTER_2D_8TAP_REGULAR_SMOOTH, 8tap_regular_smooth, sse2); init_mct_fn(FILTER_2D_8TAP_REGULAR_SHARP, 8tap_regular_sharp, sse2); init_mct_fn(FILTER_2D_8TAP_SMOOTH_REGULAR, 8tap_smooth_regular, sse2); init_mct_fn(FILTER_2D_8TAP_SMOOTH, 8tap_smooth, sse2); init_mct_fn(FILTER_2D_8TAP_SMOOTH_SHARP, 8tap_smooth_sharp, sse2); init_mct_fn(FILTER_2D_8TAP_SHARP_REGULAR, 8tap_sharp_regular, sse2); init_mct_fn(FILTER_2D_8TAP_SHARP_SMOOTH, 8tap_sharp_smooth, sse2); init_mct_fn(FILTER_2D_8TAP_SHARP, 8tap_sharp, sse2); c->warp8x8 = dav1d_warp_affine_8x8_sse2; c->warp8x8t = dav1d_warp_affine_8x8t_sse2; #endif if(!(flags & DAV1D_X86_CPU_FLAG_SSSE3)) return; #if BITDEPTH == 8 init_mc_fn(FILTER_2D_BILINEAR, bilin, ssse3); init_mc_fn(FILTER_2D_8TAP_REGULAR, 8tap_regular, ssse3); init_mc_fn(FILTER_2D_8TAP_REGULAR_SMOOTH, 8tap_regular_smooth, ssse3); init_mc_fn(FILTER_2D_8TAP_REGULAR_SHARP, 8tap_regular_sharp, ssse3); init_mc_fn(FILTER_2D_8TAP_SMOOTH_REGULAR, 8tap_smooth_regular, ssse3); init_mc_fn(FILTER_2D_8TAP_SMOOTH, 8tap_smooth, ssse3); init_mc_fn(FILTER_2D_8TAP_SMOOTH_SHARP, 8tap_smooth_sharp, ssse3); init_mc_fn(FILTER_2D_8TAP_SHARP_REGULAR, 8tap_sharp_regular, ssse3); init_mc_fn(FILTER_2D_8TAP_SHARP_SMOOTH, 8tap_sharp_smooth, ssse3); init_mc_fn(FILTER_2D_8TAP_SHARP, 8tap_sharp, ssse3); init_mct_fn(FILTER_2D_BILINEAR, bilin, ssse3); init_mct_fn(FILTER_2D_8TAP_REGULAR, 8tap_regular, ssse3); init_mct_fn(FILTER_2D_8TAP_REGULAR_SMOOTH, 8tap_regular_smooth, ssse3); init_mct_fn(FILTER_2D_8TAP_REGULAR_SHARP, 8tap_regular_sharp, ssse3); init_mct_fn(FILTER_2D_8TAP_SMOOTH_REGULAR, 8tap_smooth_regular, ssse3); init_mct_fn(FILTER_2D_8TAP_SMOOTH, 8tap_smooth, ssse3); init_mct_fn(FILTER_2D_8TAP_SMOOTH_SHARP, 8tap_smooth_sharp, ssse3); init_mct_fn(FILTER_2D_8TAP_SHARP_REGULAR, 8tap_sharp_regular, ssse3); init_mct_fn(FILTER_2D_8TAP_SHARP_SMOOTH, 8tap_sharp_smooth, ssse3); init_mct_fn(FILTER_2D_8TAP_SHARP, 8tap_sharp, ssse3); c->avg = dav1d_avg_ssse3; c->w_avg = dav1d_w_avg_ssse3; c->mask = dav1d_mask_ssse3; c->w_mask[2] = dav1d_w_mask_420_ssse3; c->blend = dav1d_blend_ssse3; c->blend_v = dav1d_blend_v_ssse3; c->blend_h = dav1d_blend_h_ssse3; c->warp8x8 = dav1d_warp_affine_8x8_ssse3; c->warp8x8t = dav1d_warp_affine_8x8t_ssse3; c->emu_edge = dav1d_emu_edge_ssse3; c->resize = dav1d_resize_ssse3; #endif if(!(flags & DAV1D_X86_CPU_FLAG_SSE41)) return; #if BITDEPTH == 8 c->warp8x8 = dav1d_warp_affine_8x8_sse4; c->warp8x8t = dav1d_warp_affine_8x8t_sse4; #endif #if ARCH_X86_64 if (!(flags & DAV1D_X86_CPU_FLAG_AVX2)) return; #if BITDEPTH == 8 init_mc_fn(FILTER_2D_8TAP_REGULAR, 8tap_regular, avx2); init_mc_fn(FILTER_2D_8TAP_REGULAR_SMOOTH, 8tap_regular_smooth, avx2); init_mc_fn(FILTER_2D_8TAP_REGULAR_SHARP, 8tap_regular_sharp, avx2); init_mc_fn(FILTER_2D_8TAP_SMOOTH_REGULAR, 8tap_smooth_regular, avx2); init_mc_fn(FILTER_2D_8TAP_SMOOTH, 8tap_smooth, avx2); init_mc_fn(FILTER_2D_8TAP_SMOOTH_SHARP, 8tap_smooth_sharp, avx2); init_mc_fn(FILTER_2D_8TAP_SHARP_REGULAR, 8tap_sharp_regular, avx2); init_mc_fn(FILTER_2D_8TAP_SHARP_SMOOTH, 8tap_sharp_smooth, avx2); init_mc_fn(FILTER_2D_8TAP_SHARP, 8tap_sharp, avx2); init_mc_fn(FILTER_2D_BILINEAR, bilin, avx2); init_mct_fn(FILTER_2D_8TAP_REGULAR, 8tap_regular, avx2); init_mct_fn(FILTER_2D_8TAP_REGULAR_SMOOTH, 8tap_regular_smooth, avx2); init_mct_fn(FILTER_2D_8TAP_REGULAR_SHARP, 8tap_regular_sharp, avx2); init_mct_fn(FILTER_2D_8TAP_SMOOTH_REGULAR, 8tap_smooth_regular, avx2); init_mct_fn(FILTER_2D_8TAP_SMOOTH, 8tap_smooth, avx2); init_mct_fn(FILTER_2D_8TAP_SMOOTH_SHARP, 8tap_smooth_sharp, avx2); init_mct_fn(FILTER_2D_8TAP_SHARP_REGULAR, 8tap_sharp_regular, avx2); init_mct_fn(FILTER_2D_8TAP_SHARP_SMOOTH, 8tap_sharp_smooth, avx2); init_mct_fn(FILTER_2D_8TAP_SHARP, 8tap_sharp, avx2); init_mct_fn(FILTER_2D_BILINEAR, bilin, avx2); init_mc_scaled_fn(FILTER_2D_8TAP_REGULAR, 8tap_scaled_regular, avx2); init_mc_scaled_fn(FILTER_2D_8TAP_REGULAR_SMOOTH, 8tap_scaled_regular_smooth, avx2); init_mc_scaled_fn(FILTER_2D_8TAP_REGULAR_SHARP, 8tap_scaled_regular_sharp, avx2); init_mc_scaled_fn(FILTER_2D_8TAP_SMOOTH_REGULAR, 8tap_scaled_smooth_regular, avx2); init_mc_scaled_fn(FILTER_2D_8TAP_SMOOTH, 8tap_scaled_smooth, avx2); init_mc_scaled_fn(FILTER_2D_8TAP_SMOOTH_SHARP, 8tap_scaled_smooth_sharp, avx2); init_mc_scaled_fn(FILTER_2D_8TAP_SHARP_REGULAR, 8tap_scaled_sharp_regular, avx2); init_mc_scaled_fn(FILTER_2D_8TAP_SHARP_SMOOTH, 8tap_scaled_sharp_smooth, avx2); init_mc_scaled_fn(FILTER_2D_8TAP_SHARP, 8tap_scaled_sharp, avx2); init_mc_scaled_fn(FILTER_2D_BILINEAR, bilin_scaled, avx2); init_mct_scaled_fn(FILTER_2D_8TAP_REGULAR, 8tap_scaled_regular, avx2); init_mct_scaled_fn(FILTER_2D_8TAP_REGULAR_SMOOTH, 8tap_scaled_regular_smooth, avx2); init_mct_scaled_fn(FILTER_2D_8TAP_REGULAR_SHARP, 8tap_scaled_regular_sharp, avx2); init_mct_scaled_fn(FILTER_2D_8TAP_SMOOTH_REGULAR, 8tap_scaled_smooth_regular, avx2); init_mct_scaled_fn(FILTER_2D_8TAP_SMOOTH, 8tap_scaled_smooth, avx2); init_mct_scaled_fn(FILTER_2D_8TAP_SMOOTH_SHARP, 8tap_scaled_smooth_sharp, avx2); init_mct_scaled_fn(FILTER_2D_8TAP_SHARP_REGULAR, 8tap_scaled_sharp_regular, avx2); init_mct_scaled_fn(FILTER_2D_8TAP_SHARP_SMOOTH, 8tap_scaled_sharp_smooth, avx2); init_mct_scaled_fn(FILTER_2D_8TAP_SHARP, 8tap_scaled_sharp, avx2); init_mct_scaled_fn(FILTER_2D_BILINEAR, bilin_scaled, avx2); c->avg = dav1d_avg_avx2; c->w_avg = dav1d_w_avg_avx2; c->mask = dav1d_mask_avx2; c->w_mask[0] = dav1d_w_mask_444_avx2; c->w_mask[1] = dav1d_w_mask_422_avx2; c->w_mask[2] = dav1d_w_mask_420_avx2; c->blend = dav1d_blend_avx2; c->blend_v = dav1d_blend_v_avx2; c->blend_h = dav1d_blend_h_avx2; c->warp8x8 = dav1d_warp_affine_8x8_avx2; c->warp8x8t = dav1d_warp_affine_8x8t_avx2; c->emu_edge = dav1d_emu_edge_avx2; c->resize = dav1d_resize_avx2; #endif if (!(flags & DAV1D_X86_CPU_FLAG_AVX512ICL)) return; #if HAVE_AVX512ICL && BITDEPTH == 8 init_mct_fn(FILTER_2D_8TAP_REGULAR, 8tap_regular, avx512icl); init_mct_fn(FILTER_2D_8TAP_REGULAR_SMOOTH, 8tap_regular_smooth, avx512icl); init_mct_fn(FILTER_2D_8TAP_REGULAR_SHARP, 8tap_regular_sharp, avx512icl); init_mct_fn(FILTER_2D_8TAP_SMOOTH_REGULAR, 8tap_smooth_regular, avx512icl); init_mct_fn(FILTER_2D_8TAP_SMOOTH, 8tap_smooth, avx512icl); init_mct_fn(FILTER_2D_8TAP_SMOOTH_SHARP, 8tap_smooth_sharp, avx512icl); init_mct_fn(FILTER_2D_8TAP_SHARP_REGULAR, 8tap_sharp_regular, avx512icl); init_mct_fn(FILTER_2D_8TAP_SHARP_SMOOTH, 8tap_sharp_smooth, avx512icl); init_mct_fn(FILTER_2D_8TAP_SHARP, 8tap_sharp, avx512icl); init_mct_fn(FILTER_2D_BILINEAR, bilin, avx512icl); c->avg = dav1d_avg_avx512icl; c->w_avg = dav1d_w_avg_avx512icl; c->mask = dav1d_mask_avx512icl; c->w_mask[0] = dav1d_w_mask_444_avx512icl; c->w_mask[1] = dav1d_w_mask_422_avx512icl; c->w_mask[2] = dav1d_w_mask_420_avx512icl; #endif #endif }
550658.c
/** @file Application for Hash Primitives Validation. Copyright (c) 2010 - 2014, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #include "Cryptest.h" // // Max Known Digest Size is SHA512 Output (64 bytes) by far // #define MAX_DIGEST_SIZE 64 // // Message string for digest validation // GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR8 *HashData = "abc"; // // Result for MD4("abc"). (From "A.5 Test suite" of IETF RFC1320) // GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 Md4Digest[MD4_DIGEST_SIZE] = { 0xa4, 0x48, 0x01, 0x7a, 0xaf, 0x21, 0xd8, 0x52, 0x5f, 0xc1, 0x0a, 0xe8, 0x7a, 0xa6, 0x72, 0x9d }; // // Result for MD5("abc"). (From "A.5 Test suite" of IETF RFC1321) // GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 Md5Digest[MD5_DIGEST_SIZE] = { 0x90, 0x01, 0x50, 0x98, 0x3c, 0xd2, 0x4f, 0xb0, 0xd6, 0x96, 0x3f, 0x7d, 0x28, 0xe1, 0x7f, 0x72 }; // // Result for SHA-1("abc"). (From "A.1 SHA-1 Example" of NIST FIPS 180-2) // GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 Sha1Digest[SHA1_DIGEST_SIZE] = { 0xa9, 0x99, 0x3e, 0x36, 0x47, 0x06, 0x81, 0x6a, 0xba, 0x3e, 0x25, 0x71, 0x78, 0x50, 0xc2, 0x6c, 0x9c, 0xd0, 0xd8, 0x9d }; // // Result for SHA-256("abc"). (From "B.1 SHA-256 Example" of NIST FIPS 180-2) // GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 Sha256Digest[SHA256_DIGEST_SIZE] = { 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad }; // // Result for SHA-384("abc"). (From "D.1 SHA-384 Example" of NIST FIPS 180-2) // GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 Sha384Digest[SHA384_DIGEST_SIZE] = { 0xcb, 0x00, 0x75, 0x3f, 0x45, 0xa3, 0x5e, 0x8b, 0xb5, 0xa0, 0x3d, 0x69, 0x9a, 0xc6, 0x50, 0x07, 0x27, 0x2c, 0x32, 0xab, 0x0e, 0xde, 0xd1, 0x63, 0x1a, 0x8b, 0x60, 0x5a, 0x43, 0xff, 0x5b, 0xed, 0x80, 0x86, 0x07, 0x2b, 0xa1, 0xe7, 0xcc, 0x23, 0x58, 0xba, 0xec, 0xa1, 0x34, 0xc8, 0x25, 0xa7 }; // // Result for SHA-512("abc"). (From "C.1 SHA-512 Example" of NIST FIPS 180-2) // GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 Sha512Digest[SHA512_DIGEST_SIZE] = { 0xdd, 0xaf, 0x35, 0xa1, 0x93, 0x61, 0x7a, 0xba, 0xcc, 0x41, 0x73, 0x49, 0xae, 0x20, 0x41, 0x31, 0x12, 0xe6, 0xfa, 0x4e, 0x89, 0xa9, 0x7e, 0xa2, 0x0a, 0x9e, 0xee, 0xe6, 0x4b, 0x55, 0xd3, 0x9a, 0x21, 0x92, 0x99, 0x2a, 0x27, 0x4f, 0xc1, 0xa8, 0x36, 0xba, 0x3c, 0x23, 0xa3, 0xfe, 0xeb, 0xbd, 0x45, 0x4d, 0x44, 0x23, 0x64, 0x3c, 0xe8, 0x0e, 0x2a, 0x9a, 0xc9, 0x4f, 0xa5, 0x4c, 0xa4, 0x9f }; /** Validate UEFI-OpenSSL Digest Interfaces. @retval EFI_SUCCESS Validation succeeded. @retval EFI_ABORTED Validation failed. **/ EFI_STATUS ValidateCryptDigest ( VOID ) { UINTN CtxSize; VOID *HashCtx; UINTN DataSize; UINT8 Digest[MAX_DIGEST_SIZE]; BOOLEAN Status; Print (L" UEFI-OpenSSL Hash Engine Testing:\n"); DataSize = AsciiStrLen (HashData); Print (L"- MD4: "); // // MD4 Digest Validation // ZeroMem (Digest, MAX_DIGEST_SIZE); CtxSize = Md4GetContextSize (); HashCtx = AllocatePool (CtxSize); Print (L"Init... "); Status = Md4Init (HashCtx); if (!Status) { Print (L"[Fail]"); return EFI_ABORTED; } Print (L"Update... "); Status = Md4Update (HashCtx, HashData, DataSize); if (!Status) { Print (L"[Fail]"); return EFI_ABORTED; } Print (L"Finalize... "); Status = Md4Final (HashCtx, Digest); if (!Status) { Print (L"[Fail]"); return EFI_ABORTED; } FreePool (HashCtx); Print (L"Check Value... "); if (CompareMem (Digest, Md4Digest, MD5_DIGEST_SIZE) != 0) { Print (L"[Fail]"); return EFI_ABORTED; } Print (L"[Pass]\n"); Print (L"- MD5: "); // // MD5 Digest Validation // ZeroMem (Digest, MAX_DIGEST_SIZE); CtxSize = Md5GetContextSize (); HashCtx = AllocatePool (CtxSize); Print (L"Init... "); Status = Md5Init (HashCtx); if (!Status) { Print (L"[Fail]"); return EFI_ABORTED; } Print (L"Update... "); Status = Md5Update (HashCtx, HashData, DataSize); if (!Status) { Print (L"[Fail]"); return EFI_ABORTED; } Print (L"Finalize... "); Status = Md5Final (HashCtx, Digest); if (!Status) { Print (L"[Fail]"); return EFI_ABORTED; } FreePool (HashCtx); Print (L"Check Value... "); if (CompareMem (Digest, Md5Digest, MD5_DIGEST_SIZE) != 0) { Print (L"[Fail]"); return EFI_ABORTED; } Print (L"[Pass]\n"); Print (L"- SHA1: "); // // SHA-1 Digest Validation // ZeroMem (Digest, MAX_DIGEST_SIZE); CtxSize = Sha1GetContextSize (); HashCtx = AllocatePool (CtxSize); Print (L"Init... "); Status = Sha1Init (HashCtx); if (!Status) { Print (L"[Fail]"); return EFI_ABORTED; } Print (L"Update... "); Status = Sha1Update (HashCtx, HashData, DataSize); if (!Status) { Print (L"[Fail]"); return EFI_ABORTED; } Print (L"Finalize... "); Status = Sha1Final (HashCtx, Digest); if (!Status) { Print (L"[Fail]"); return EFI_ABORTED; } FreePool (HashCtx); Print (L"Check Value... "); if (CompareMem (Digest, Sha1Digest, SHA1_DIGEST_SIZE) != 0) { Print (L"[Fail]"); return EFI_ABORTED; } Print (L"[Pass]\n"); Print (L"- SHA256: "); // // SHA256 Digest Validation // ZeroMem (Digest, MAX_DIGEST_SIZE); CtxSize = Sha256GetContextSize (); HashCtx = AllocatePool (CtxSize); Print (L"Init... "); Status = Sha256Init (HashCtx); if (!Status) { Print (L"[Fail]"); return EFI_ABORTED; } Print (L"Update... "); Status = Sha256Update (HashCtx, HashData, DataSize); if (!Status) { Print (L"[Fail]"); return EFI_ABORTED; } Print (L"Finalize... "); Status = Sha256Final (HashCtx, Digest); if (!Status) { Print (L"[Fail]"); return EFI_ABORTED; } FreePool (HashCtx); Print (L"Check Value... "); if (CompareMem (Digest, Sha256Digest, SHA256_DIGEST_SIZE) != 0) { Print (L"[Fail]"); return EFI_ABORTED; } Print (L"[Pass]\n"); Print (L"- SHA384: "); // // SHA384 Digest Validation // ZeroMem (Digest, MAX_DIGEST_SIZE); CtxSize = Sha384GetContextSize (); HashCtx = AllocatePool (CtxSize); Print (L"Init... "); Status = Sha384Init (HashCtx); if (!Status) { Print (L"[Fail]"); return EFI_ABORTED; } Print (L"Update... "); Status = Sha384Update (HashCtx, HashData, DataSize); if (!Status) { Print (L"[Fail]"); return EFI_ABORTED; } Print (L"Finalize... "); Status = Sha384Final (HashCtx, Digest); if (!Status) { Print (L"[Fail]"); return EFI_ABORTED; } FreePool (HashCtx); Print (L"Check Value... "); if (CompareMem (Digest, Sha384Digest, SHA384_DIGEST_SIZE) != 0) { Print (L"[Fail]"); return EFI_ABORTED; } Print (L"[Pass]\n"); Print (L"- SHA512: "); // // SHA512 Digest Validation // ZeroMem (Digest, MAX_DIGEST_SIZE); CtxSize = Sha512GetContextSize (); HashCtx = AllocatePool (CtxSize); Print (L"Init... "); Status = Sha512Init (HashCtx); if (!Status) { Print (L"[Fail]"); return EFI_ABORTED; } Print (L"Update... "); Status = Sha512Update (HashCtx, HashData, DataSize); if (!Status) { Print (L"[Fail]"); return EFI_ABORTED; } Print (L"Finalize... "); Status = Sha512Final (HashCtx, Digest); if (!Status) { Print (L"[Fail]"); return EFI_ABORTED; } FreePool (HashCtx); Print (L"Check Value... "); if (CompareMem (Digest, Sha512Digest, SHA512_DIGEST_SIZE) != 0) { Print (L"[Fail]"); return EFI_ABORTED; } Print (L"[Pass]\n"); return EFI_SUCCESS; }
371660.c
/* * Copyright 2012-2020 M. Andersen and L. Vandenberghe. * Copyright 2010-2011 L. Vandenberghe. * Copyright 2004-2009 J. Dahl and L. Vandenberghe. * * This file is part of CVXOPT. * * CVXOPT 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. * * CVXOPT 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/>. */ #define BASE_MODULE #include "Python.h" #include "cvxopt.h" #include "misc.h" #include <complexobject.h> PyDoc_STRVAR(base__doc__,"Convex optimization package"); extern PyTypeObject matrix_tp ; extern PyTypeObject matrixiter_tp ; matrix * Matrix_New(int, int, int) ; matrix * Matrix_NewFromMatrix(matrix *, int) ; matrix * Matrix_NewFromSequence(PyObject *, int) ; matrix * Matrix_NewFromPyBuffer(PyObject *, int, int *) ; extern PyTypeObject spmatrix_tp ; extern PyTypeObject spmatrixiter_tp ; spmatrix * SpMatrix_New(int_t, int_t, int_t, int ) ; spmatrix * SpMatrix_NewFromMatrix(matrix *, int) ; spmatrix * SpMatrix_NewFromSpMatrix(spmatrix *, int) ; spmatrix * SpMatrix_NewFromIJV(matrix *, matrix *, matrix *, int_t, int_t, int) ; void free_ccs(ccs *); int get_id(void *val, int val_type); extern int (*sp_axpy[])(number, void *, void *, int, int, int, void **) ; extern int (*sp_gemm[])(char, char, number, void *, void *, number, void *, int, int, int, int, void **, int, int, int); extern int (*sp_gemv[])(char, int, int, number, void *, int, void *, int, number, void *, int) ; extern int (*sp_symv[])(char, int, number, ccs *, int, void *, int, number, void *, int) ; extern int (*sp_syrk[])(char, char, number, void *, number, void *, int, int, int, int, void **) ; #ifndef _MSC_VER const int E_SIZE[] = { sizeof(int_t), sizeof(double), sizeof(double complex) }; #else const int E_SIZE[] = { sizeof(int_t), sizeof(double), sizeof(_Dcomplex) }; #endif const char TC_CHAR[][2] = {"i","d","z"} ; /* * Helper routines and definitions to implement type transparency. */ number One[3], MinusOne[3], Zero[3]; int intOne = 1; static void write_inum(void *dest, int i, void *src, int j) { ((int_t *)dest)[i] = ((int_t *)src)[j]; } static void write_dnum(void *dest, int i, void *src, int j) { ((double *)dest)[i] = ((double *)src)[j]; } static void write_znum(void *dest, int i, void *src, int j) { #ifndef _MSC_VER ((double complex *)dest)[i] = ((double complex *)src)[j]; #else ((_Dcomplex *)dest)[i] = ((_Dcomplex *)src)[j]; #endif } void (*write_num[])(void *, int, void *, int) = { write_inum, write_dnum, write_znum }; static PyObject * inum2PyObject(void *src, int i) { return Py_BuildValue("l", ((int_t *)src)[i]); } static PyObject * dnum2PyObject(void *src, int i) { return Py_BuildValue("d", ((double *)src)[i]); } static PyObject * znum2PyObject(void *src, int i) { Py_complex z; #ifndef _MSC_VER z.real = creal (((double complex *)src)[i]); z.imag = cimag (((double complex *)src)[i]); #else z.real = creal (((_Dcomplex *)src)[i]); z.imag = cimag (((_Dcomplex *)src)[i]); #endif return Py_BuildValue("D", &z); } PyObject * (*num2PyObject[])(void *, int) = { inum2PyObject, dnum2PyObject, znum2PyObject }; /* val_id: 0 = matrix, 1 = PyNumber */ static int convert_inum(void *dest, void *val, int val_id, int_t offset) { if (val_id==0) { /* 1x1 matrix */ switch (MAT_ID(val)) { case INT: *(int_t *)dest = MAT_BUFI(val)[offset]; return 0; //case DOUBLE: //*(int_t *)dest = (int_t)round(MAT_BUFD(val)[offset]); return 0; default: PY_ERR_INT(PyExc_TypeError,"cannot cast argument as integer"); } } else { /* PyNumber */ #if PY_MAJOR_VERSION >= 3 if (PyLong_Check((PyObject *)val)) { *(int_t *)dest = PyLong_AS_LONG((PyObject *)val); return 0; } #else if (PyInt_Check((PyObject *)val)) { *(int_t *)dest = PyInt_AS_LONG((PyObject *)val); return 0; } #endif else PY_ERR_INT(PyExc_TypeError,"cannot cast argument as integer"); } } static int convert_dnum(void *dest, void *val, int val_id, int_t offset) { if (val_id==0) { /* matrix */ switch (MAT_ID(val)) { case INT: *(double *)dest = MAT_BUFI(val)[offset]; return 0; case DOUBLE: *(double *)dest = MAT_BUFD(val)[offset]; return 0; default: PY_ERR_INT(PyExc_TypeError, "cannot cast argument as double"); } } else { /* PyNumber */ #if PY_MAJOR_VERSION >= 3 if (PyLong_Check((PyObject *)val) || PyFloat_Check((PyObject *)val)) { #else if (PyInt_Check((PyObject *)val) || PyFloat_Check((PyObject *)val)) { #endif *(double *)dest = PyFloat_AsDouble((PyObject *)val); return 0; } else PY_ERR_INT(PyExc_TypeError,"cannot cast argument as double"); } } static int convert_znum(void *dest, void *val, int val_id, int_t offset) { if (val_id==0) { /* 1x1 matrix */ switch (MAT_ID(val)) { case INT: #ifndef _MSC_VER *(double complex *)dest = MAT_BUFI(val)[offset]; return 0; #else *(_Dcomplex *)dest = _Cbuild((double)MAT_BUFI(val)[offset],0.0); return 0; #endif case DOUBLE: #ifndef _MSC_VER *(double complex *)dest = MAT_BUFD(val)[offset]; return 0; #else *(_Dcomplex *)dest = _Cbuild(MAT_BUFD(val)[offset],0.0); return 0; #endif case COMPLEX: #ifndef _MSC_VER *(double complex *)dest = MAT_BUFZ(val)[offset]; return 0; #else *(_Dcomplex *)dest = MAT_BUFZ(val)[offset]; return 0; #endif default: return -1; } } else { /* PyNumber */ Py_complex c = PyComplex_AsCComplex((PyObject *)val); #ifndef _MSC_VER *(double complex *)dest = c.real + I*c.imag; #else *(_Dcomplex *)dest = _Cbuild(c.real,c.imag); #endif return 0; } } int (*convert_num[])(void *, void *, int, int_t) = { convert_inum, convert_dnum, convert_znum }; extern void daxpy_(int *, void *, void *, int *, void *, int *) ; extern void zaxpy_(int *, void *, void *, int *, void *, int *) ; static void i_axpy(int *n, void *a, void *x, int *incx, void *y, int *incy) { int i; for (i=0; i < *n; i++) { ((int_t *)y)[i*(*incy)] += *((int_t *)a)*((int_t *)x)[i*(*incx)]; } } void (*axpy[])(int *, void *, void *, int *, void *, int *) = { i_axpy, daxpy_, zaxpy_ }; extern void dscal_(int *, void *, void *, int *) ; extern void zscal_(int *, void *, void *, int *) ; /* we dont implement a BLAS iscal */ static void i_scal(int *n, void *a, void *x, int *incx) { int i; for (i=0; i < *n; i++) { ((int_t *)x)[i*(*incx)] *= *((int_t *)a); } } void (*scal[])(int *, void *, void *, int *) = { i_scal, dscal_, zscal_ }; extern void dgemm_(char *, char *, int *, int *, int *, void *, void *, int *, void *, int *, void *, void *, int *) ; extern void zgemm_(char *, char *, int *, int *, int *, void *, void *, int *, void *, int *, void *, void *, int *) ; /* we dont implement a BLAS igemm */ static void i_gemm(char *transA, char *transB, int *m, int *n, int *k, void *alpha, void *A, int *ldA, void *B, int *ldB, void *beta, void *C, int *ldC) { int i, j, l; for (j=0; j<*n; j++) { for (i=0; i<*m; i++) { ((int_t *)C)[i+j*(*m)] = 0; for (l=0; l<*k; l++) ((int_t *)C)[i+j*(*m)]+=((int_t *)A)[i+l*(*m)]*((int_t *)B)[j*(*k)+l]; } } } void (*gemm[])(char *, char *, int *, int *, int *, void *, void *, int *, void *, int *, void *, void *, int *) = { i_gemm, dgemm_, zgemm_ }; extern void dgemv_(char *, int *, int *, void *, void *, int *, void *, int *, void *, void *, int *); extern void zgemv_(char *, int *, int *, void *, void *, int *, void *, int *, void *, void *, int *); static void (*gemv[])(char *, int *, int *, void *, void *, int *, void *, int *, void *, void *, int *) = { NULL, dgemv_, zgemv_ }; extern void dsyrk_(char *, char *, int *, int *, void *, void *, int *, void *, void *, int *); extern void zsyrk_(char *, char *, int *, int *, void *, void *, int *, void *, void *, int *); void (*syrk[])(char *, char *, int *, int *, void *, void *, int *, void *, void *, int *) = { NULL, dsyrk_, zsyrk_ }; extern void dsymv_(char *, int *, void *, void *, int *, void *, int *, void *, void *, int *); extern void zsymv_(char *, int *, void *, void *, int *, void *, int *, void *, void *, int *); void (*symv[])(char *, int *, void *, void *, int *, void *, int *, void *, void *, int *) = { NULL, dsymv_, zsymv_ }; static void mtx_iabs(void *src, void *dest, int n) { int i; for (i=0; i<n; i++) ((int_t *)dest)[i] = labs(((int_t *)src)[i]); } static void mtx_dabs(void *src, void *dest, int n) { int i; for (i=0; i<n; i++) ((double *)dest)[i] = fabs(((double *)src)[i]); } static void mtx_zabs(void *src, void *dest, int n) { int i; for (i=0; i<n; i++) #ifndef _MSC_VER ((double *)dest)[i] = cabs(((double complex *)src)[i]); #else ((double *)dest)[i] = cabs(((_Dcomplex *)src)[i]); #endif } void (*mtx_abs[])(void *, void *, int) = { mtx_iabs, mtx_dabs, mtx_zabs }; static int idiv(void *dest, number a, int n) { if (a.i==0) PY_ERR_INT(PyExc_ZeroDivisionError, "division by zero"); int i; for (i=0; i<n; i++) ((int_t *)dest)[i] /= a.i; return 0; } static int ddiv(void *dest, number a, int n) { if (a.d==0.0) PY_ERR_INT(PyExc_ZeroDivisionError, "division by zero"); int _n = n, int1 = 1; double _a = 1/a.d; dscal_(&_n, (void *)&_a, dest, &int1); return 0; } static int zdiv(void *dest, number a, int n) { if (cabs(a.z) == 0.0) PY_ERR_INT(PyExc_ZeroDivisionError, "division by zero"); int _n = n, int1 = 1; #ifndef _MSC_VER double complex _a = 1.0/a.z; #else _Dcomplex _a = _Cmulcr(conj(a.z),1.0/norm(a.z)); #endif zscal_(&_n, (void *)&_a, dest, &int1); return 0; } int (*div_array[])(void *, number, int) = { idiv, ddiv, zdiv }; static int mtx_irem(void *dest, number a, int n) { if (a.i==0) PY_ERR_INT(PyExc_ZeroDivisionError, "division by zero"); int i; for (i=0; i<n; i++) ((int_t *)dest)[i] %= a.i; return 0; } static int mtx_drem(void *dest, number a, int n) { if (a.d==0.0) PY_ERR_INT(PyExc_ZeroDivisionError, "division by zero"); int i; for (i=0; i<n; i++) ((double *)dest)[i] -= floor(((double *)dest)[i]/a.d)*a.d; return 0; } int (*mtx_rem[])(void *, number, int) = { mtx_irem, mtx_drem }; /* val_type = 0: (sp)matrix if type = 0, PY_NUMBER if type = 1 */ int get_id(void *val, int val_type) { if (!val_type) { if Matrix_Check((PyObject *)val) return MAT_ID((matrix *)val); else return SP_ID((spmatrix *)val); } #if PY_MAJOR_VERSION >= 3 else if (PyLong_Check((PyObject *)val)) #else else if (PyInt_Check((PyObject *)val)) #endif return INT; else if (PyFloat_Check((PyObject *)val)) return DOUBLE; else return COMPLEX; } static int Matrix_Check_func(void *o) { return Matrix_Check((PyObject*)o); } static int SpMatrix_Check_func(void *o) { return SpMatrix_Check((PyObject *)o); } static char doc_axpy[] = "Constant times a vector plus a vector (y := alpha*x+y).\n\n" "axpy(x, y, n=None, alpha=1.0)\n\n" "ARGUMENTS\n" "x 'd' or 'z' (sp)matrix\n\n" "y 'd' or 'z' (sp)matrix. Must have the same type as x.\n\n" "n integer. If n<0, the default value of n is used.\n" " The default value is equal to\n" " (len(x)>=offsetx+1) ? 1+(len(x)-offsetx-1)/incx : 0.\n\n" "alpha number (int, float or complex). Complex alpha is only\n" " allowed if x is complex"; PyObject * base_axpy(PyObject *self, PyObject *args, PyObject *kwrds) { PyObject *x, *y, *partial = NULL; PyObject *ao=NULL; number a; char *kwlist[] = {"x", "y", "alpha", "partial", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OO|OO:axpy", kwlist, &x, &y, &ao, &partial)) return NULL; if (!Matrix_Check(x) && !SpMatrix_Check(x)) err_mtrx("x"); if (!Matrix_Check(y) && !SpMatrix_Check(y)) err_mtrx("y"); if (partial && !PyBool_Check(partial)) err_bool("partial"); if (X_ID(x) != X_ID(y)) err_conflicting_ids; int id = X_ID(x); if (X_NROWS(x) != X_NROWS(y) || X_NCOLS(x) != X_NCOLS(y)) PY_ERR_TYPE("dimensions of x and y do not match"); if (ao && convert_num[id](&a, ao, 1, 0)) err_type("alpha"); if (Matrix_Check(x) && Matrix_Check(y)) { int n = X_NROWS(x)*X_NCOLS(x); axpy[id](&n, (ao ? &a : &One[id]), MAT_BUF(x), &intOne, MAT_BUF(y), &intOne); } else { void *z = NULL; if (sp_axpy[id]((ao ? a : One[id]), Matrix_Check(x) ? MAT_BUF(x): ((spmatrix *)x)->obj, Matrix_Check(y) ? MAT_BUF(y): ((spmatrix *)y)->obj, SpMatrix_Check(x), SpMatrix_Check(y), #if PY_MAJOR_VERSION >= 3 partial ? PyLong_AS_LONG(partial) : 0, &z)) #else partial ? PyInt_AS_LONG(partial) : 0, &z)) #endif return PyErr_NoMemory(); if (z) { free_ccs( ((spmatrix *)y)->obj ); ((spmatrix *)y)->obj = z; } } return Py_BuildValue(""); } static char doc_gemm[] = "General matrix-matrix product.\n\n" "gemm(A, B, C, transA='N', transB='N', alpha=1.0, beta=0.0, \n" " partial=False) \n\n" "PURPOSE\n" "Computes \n" "C := alpha*A*B + beta*C if transA = 'N' and transB = 'N'.\n" "C := alpha*A^T*B + beta*C if transA = 'T' and transB = 'N'.\n" "C := alpha*A^H*B + beta*C if transA = 'C' and transB = 'N'.\n" "C := alpha*A*B^T + beta*C if transA = 'N' and transB = 'T'.\n" "C := alpha*A^T*B^T + beta*C if transA = 'T' and transB = 'T'.\n" "C := alpha*A^H*B^T + beta*C if transA = 'C' and transB = 'T'.\n" "C := alpha*A*B^H + beta*C if transA = 'N' and transB = 'C'.\n" "C := alpha*A^T*B^H + beta*C if transA = 'T' and transB = 'C'.\n" "C := alpha*A^H*B^H + beta*C if transA = 'C' and transB = 'C'.\n" "If k=0, this reduces to C := beta*C.\n\n" "ARGUMENTS\n\n" "A 'd' or 'z' matrix\n\n" "B 'd' or 'z' matrix. Must have the same type as A.\n\n" "C 'd' or 'z' matrix. Must have the same type as A.\n\n" "transA 'N', 'T' or 'C'\n\n" "transB 'N', 'T' or 'C'\n\n" "alpha number (int, float or complex). Complex alpha is only\n" " allowed if A is complex.\n\n" "beta number (int, float or complex). Complex beta is only\n" " allowed if A is complex.\n\n" "partial boolean. If C is sparse and partial is True, then only the\n" " nonzero elements of C are updated irrespective of the\n" " sparsity patterns of A and B."; PyObject* base_gemm(PyObject *self, PyObject *args, PyObject *kwrds) { PyObject *A, *B, *C, *partial=NULL; PyObject *ao=NULL, *bo=NULL; number a, b; int m, n, k; #if PY_MAJOR_VERSION >= 3 int transA='N', transB='N'; char transA_, transB_; #else char transA='N', transB='N'; #endif char *kwlist[] = {"A", "B", "C", "transA", "transB", "alpha", "beta", "partial", NULL}; #if PY_MAJOR_VERSION >= 3 if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OOO|CCOOO:gemm", kwlist, &A, &B, &C, &transA, &transB, &ao, &bo, &partial)) #else if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OOO|ccOOO:gemm", kwlist, &A, &B, &C, &transA, &transB, &ao, &bo, &partial)) #endif return NULL; if (!(Matrix_Check(A) || SpMatrix_Check(A))) PY_ERR_TYPE("A must a matrix or spmatrix"); if (!(Matrix_Check(B) || SpMatrix_Check(B))) PY_ERR_TYPE("B must a matrix or spmatrix"); if (!(Matrix_Check(C) || SpMatrix_Check(C))) PY_ERR_TYPE("C must a matrix or spmatrix"); if (partial && !PyBool_Check(partial)) err_bool("partial"); if (X_ID(A) != X_ID(B) || X_ID(A) != X_ID(C) || X_ID(B) != X_ID(C)) err_conflicting_ids; if (transA != 'N' && transA != 'T' && transA != 'C') err_char("transA", "'N', 'T', 'C'"); if (transB != 'N' && transB != 'T' && transB != 'C') err_char("transB", "'N', 'T', 'C'"); m = (transA == 'N') ? X_NROWS(A) : X_NCOLS(A); n = (transB == 'N') ? X_NCOLS(B) : X_NROWS(B); k = (transA == 'N') ? X_NCOLS(A) : X_NROWS(A); if (k != ((transB == 'N') ? X_NROWS(B) : X_NCOLS(B))) PY_ERR_TYPE("dimensions of A and B do not match"); if (m == 0 || n == 0) return Py_BuildValue(""); if (ao && convert_num[X_ID(A)](&a, ao, 1, 0)) err_type("alpha"); if (bo && convert_num[X_ID(A)](&b, bo, 1, 0)) err_type("beta"); #if PY_MAJOR_VERSION >= 3 transA_ = transA; transB_ = transB; #endif int id = X_ID(A); if (Matrix_Check(A) && Matrix_Check(B) && Matrix_Check(C)) { int ldA = MAX(1,MAT_NROWS(A)); int ldB = MAX(1,MAT_NROWS(B)); int ldC = MAX(1,MAT_NROWS(C)); if (id == INT) err_invalid_id; #if PY_MAJOR_VERSION >= 3 gemm[id](&transA_, &transB_, &m, &n, &k, (ao ? &a : &One[id]), MAT_BUF(A), &ldA, MAT_BUF(B), &ldB, (bo ? &b : &Zero[id]), MAT_BUF(C), &ldC); #else gemm[id](&transA, &transB, &m, &n, &k, (ao ? &a : &One[id]), MAT_BUF(A), &ldA, MAT_BUF(B), &ldB, (bo ? &b : &Zero[id]), MAT_BUF(C), &ldC); #endif } else { void *z = NULL; #if PY_MAJOR_VERSION >= 3 if (sp_gemm[id](transA_, transB_, (ao ? a : One[id]), Matrix_Check(A) ? MAT_BUF(A) : ((spmatrix *)A)->obj, Matrix_Check(B) ? MAT_BUF(B) : ((spmatrix *)B)->obj, (bo ? b : Zero[id]), Matrix_Check(C) ? MAT_BUF(C) : ((spmatrix *)C)->obj, SpMatrix_Check(A), SpMatrix_Check(B), SpMatrix_Check(C), partial ? PyLong_AS_LONG(partial) : 0, &z, m, n, k)) return PyErr_NoMemory(); #else if (sp_gemm[id](transA, transB, (ao ? a : One[id]), Matrix_Check(A) ? MAT_BUF(A) : ((spmatrix *)A)->obj, Matrix_Check(B) ? MAT_BUF(B) : ((spmatrix *)B)->obj, (bo ? b : Zero[id]), Matrix_Check(C) ? MAT_BUF(C) : ((spmatrix *)C)->obj, SpMatrix_Check(A), SpMatrix_Check(B), SpMatrix_Check(C), partial ? PyInt_AS_LONG(partial) : 0, &z, m, n, k)) return PyErr_NoMemory(); #endif if (z) { free_ccs( ((spmatrix *)C)->obj ); ((spmatrix *)C)->obj = z; } } return Py_BuildValue(""); } static char doc_gemv[] = "General matrix-vector product for sparse and dense matrices. \n\n" "gemv(A, x, y, trans='N', alpha=1.0, beta=0.0, m=A.size[0],\n" " n=A.size[1], incx=1, incy=1, offsetA=0, offsetx=0, offsety=0)\n\n" "PURPOSE\n" "If trans is 'N', computes y := alpha*A*x + beta*y.\n" "If trans is 'T', computes y := alpha*A^T*x + beta*y.\n" "If trans is 'C', computes y := alpha*A^H*x + beta*y.\n" "The matrix A is m by n.\n" "Returns immediately if n=0 and trans is 'T' or 'C', or if m=0 \n" "and trans is 'N'.\n" "Computes y := beta*y if n=0, m>0 and trans is 'N', or if m=0, \n" "n>0 and trans is 'T' or 'C'.\n\n" "ARGUMENTS\n" "A 'd' or 'z' (sp)matrix\n\n" "x 'd' or 'z' matrix. Must have the same type as A.\n\n" "y 'd' or 'z' matrix. Must have the same type as A.\n\n" "trans 'N', 'T' or 'C'\n\n" "alpha number (int, float or complex). Complex alpha is only\n" " allowed if A is complex.\n\n" "beta number (int, float or complex). Complex beta is only\n" " allowed if A is complex.\n\n" "m integer. If negative, the default value is used.\n\n" "n integer. If negative, the default value is used.\n\n" " If zero, the default value is used.\n\n" "incx nonzero integer\n\n" "incy nonzero integer\n\n" "offsetA nonnegative integer\n\n" "offsetx nonnegative integer\n\n" "offsety nonnegative integer\n\n" "This sparse version of GEMV requires that\n" " m <= A.size[0] - (offsetA % A.size[0])"; static PyObject* base_gemv(PyObject *self, PyObject *args, PyObject *kwrds) { matrix *x, *y; PyObject *A; PyObject *ao=NULL, *bo=NULL; number a, b; int m=-1, n=-1, ix=1, iy=1, oA=0, ox=0, oy=0; #if PY_MAJOR_VERSION >= 3 int trans='N'; char trans_; #else char trans='N'; #endif char *kwlist[] = {"A", "x", "y", "trans", "alpha", "beta", "m", "n", "incx", "incy", "offsetA", "offsetx", "offsety", NULL}; #if PY_MAJOR_VERSION >= 3 if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OOO|COOiiiiiii:gemv", kwlist, &A, &x, &y, &trans, &ao, &bo, &m, &n, &ix, &iy, &oA, &ox, &oy)) return NULL; #else if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OOO|cOOiiiiiii:gemv", kwlist, &A, &x, &y, &trans, &ao, &bo, &m, &n, &ix, &iy, &oA, &ox, &oy)) return NULL; #endif if (!Matrix_Check(A) && !SpMatrix_Check(A)) PY_ERR(PyExc_TypeError, "A must be a dense or sparse matrix"); if (!Matrix_Check(x)) err_mtrx("x"); if (!Matrix_Check(y)) err_mtrx("y"); if (MAT_ID(x) == INT || MAT_ID(y) == INT || X_ID(A) == INT) PY_ERR_TYPE("invalid matrix types"); if (X_ID(A) != MAT_ID(x) || X_ID(A) != MAT_ID(y)) err_conflicting_ids; if (trans != 'N' && trans != 'T' && trans != 'C') err_char("trans", "'N','T','C'"); if (ix == 0) err_nz_int("incx"); if (iy == 0) err_nz_int("incy"); int id = MAT_ID(x); if (m < 0) m = X_NROWS(A); if (n < 0) n = X_NCOLS(A); if ((!m && trans == 'N') || (!n && (trans == 'T' || trans == 'C'))) return Py_BuildValue(""); if (oA < 0) err_nn_int("offsetA"); if (n > 0 && m > 0 && oA + (n-1)*MAX(1,X_NROWS(A)) + m > X_NROWS(A)*X_NCOLS(A)) err_buf_len("A"); if (ox < 0) err_nn_int("offsetx"); if ((trans == 'N' && n > 0 && ox + (n-1)*abs(ix) + 1 > MAT_LGT(x)) || ((trans == 'T' || trans == 'C') && m > 0 && ox + (m-1)*abs(ix) + 1 > MAT_LGT(x))) err_buf_len("x"); if (oy < 0) err_nn_int("offsety"); if ((trans == 'N' && oy + (m-1)*abs(iy) + 1 > MAT_LGT(y)) || ((trans == 'T' || trans == 'C') && oy + (n-1)*abs(iy) + 1 > MAT_LGT(y))) err_buf_len("y"); if (ao && convert_num[MAT_ID(x)](&a, ao, 1, 0)) err_type("alpha"); if (bo && convert_num[MAT_ID(x)](&b, bo, 1, 0)) err_type("beta"); #if PY_MAJOR_VERSION >= 3 trans_ = trans; #endif if (Matrix_Check(A)) { int ldA = MAX(1,X_NROWS(A)); if (trans == 'N' && n == 0) scal[id](&m, (bo ? &b : &Zero[id]), (unsigned char*)MAT_BUF(y)+oy*E_SIZE[id], &iy); else if ((trans == 'T' || trans == 'C') && m == 0) scal[id](&n, (bo ? &b : &Zero[id]), (unsigned char*)MAT_BUF(y)+oy*E_SIZE[id], &iy); else #if PY_MAJOR_VERSION >= 3 gemv[id](&trans_, &m, &n, (ao ? &a : &One[id]), (unsigned char*)MAT_BUF(A) + oA*E_SIZE[id], &ldA, (unsigned char*)MAT_BUF(x) + ox*E_SIZE[id], &ix, (bo ? &b : &Zero[id]), (unsigned char*)MAT_BUF(y) + oy*E_SIZE[id], &iy); #else gemv[id](&trans, &m, &n, (ao ? &a : &One[id]), (unsigned char*)MAT_BUF(A) + oA*E_SIZE[id], &ldA, (unsigned char*)MAT_BUF(x) + ox*E_SIZE[id], &ix, (bo ? &b : &Zero[id]), (unsigned char*)MAT_BUF(y) + oy*E_SIZE[id], &iy); #endif } else { #if PY_MAJOR_VERSION >= 3 if (sp_gemv[id](trans_, m, n, (ao ? a : One[id]), ((spmatrix *)A)->obj, oA, (unsigned char*)MAT_BUF(x) + ox*E_SIZE[id], ix, (bo ? b : Zero[id]), (unsigned char*)MAT_BUF(y) + oy*E_SIZE[id], iy)) return PyErr_NoMemory(); #else if (sp_gemv[id](trans, m, n, (ao ? a : One[id]), ((spmatrix *)A)->obj, oA, (unsigned char*)MAT_BUF(x) + ox*E_SIZE[id], ix, (bo ? b : Zero[id]), (unsigned char*)MAT_BUF(y) + oy*E_SIZE[id], iy)) return PyErr_NoMemory(); #endif } return Py_BuildValue(""); } static char doc_syrk[] = "Rank-k update of symmetric sparse or dense matrix.\n\n" "syrk(A, C, uplo='L', trans='N', alpha=1.0, beta=0.0, partial=False)\n\n" "PURPOSE \n" "If trans is 'N', computes C := alpha*A*A^T + beta*C.\n" "If trans is 'T', computes C := alpha*A^T*A + beta*C.\n" "C is symmetric (real or complex) of order n. \n" "ARGUMENTS\n" "A 'd' or 'z' (sp)matrix\n\n" "C 'd' or 'z' (sp)matrix. Must have the same type as A.\n\n" "uplo 'L' or 'U'\n\n" "trans 'N' or 'T'\n\n" "alpha number (int, float or complex). Complex alpha is only\n" " allowed if A is complex.\n\n" "beta number (int, float or complex). Complex beta is only\n" " allowed if A is complex.\n\n" "partial boolean. If C is sparse and partial is True, then only the\n" " nonzero elements of C are updated irrespective of the\n" " sparsity patterns of A."; static PyObject* base_syrk(PyObject *self, PyObject *args, PyObject *kwrds) { PyObject *A, *C, *partial=NULL, *ao=NULL, *bo=NULL; number a, b; #if PY_MAJOR_VERSION >= 3 int trans='N', uplo='L'; char trans_, uplo_; #else char trans='N', uplo='L'; #endif char *kwlist[] = {"A", "C", "uplo", "trans", "alpha", "beta", "partial", NULL}; #if PY_MAJOR_VERSION >= 3 if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OO|CCOOO:syrk", kwlist, &A, &C, &uplo, &trans, &ao, &bo, &partial)) #else if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OO|ccOOO:syrk", kwlist, &A, &C, &uplo, &trans, &ao, &bo, &partial)) #endif return NULL; if (!(Matrix_Check(A) || SpMatrix_Check(A))) PY_ERR_TYPE("A must be a dense or sparse matrix"); if (!(Matrix_Check(C) || SpMatrix_Check(C))) PY_ERR_TYPE("C must be a dense or sparse matrix"); int id = X_ID(A); if (id == INT) PY_ERR_TYPE("invalid matrix types"); if (id != X_ID(C)) err_conflicting_ids; if (uplo != 'L' && uplo != 'U') err_char("uplo", "'L', 'U'"); if (id == DOUBLE && trans != 'N' && trans != 'T' && trans != 'C') err_char("trans", "'N', 'T', 'C'"); if (id == COMPLEX && trans != 'N' && trans != 'T') err_char("trans", "'N', 'T'"); if (partial && !PyBool_Check(partial)) err_bool("partial"); int n = (trans == 'N') ? X_NROWS(A) : X_NCOLS(A); int k = (trans == 'N') ? X_NCOLS(A) : X_NROWS(A); if (n == 0) return Py_BuildValue(""); if (ao && convert_num[id](&a, ao, 1, 0)) err_type("alpha"); if (bo && convert_num[id](&b, bo, 1, 0)) err_type("beta"); #if PY_MAJOR_VERSION >= 3 trans_ = trans; uplo_ = uplo; #endif if (Matrix_Check(A) && Matrix_Check(C)) { int ldA = MAX(1,MAT_NROWS(A)); int ldC = MAX(1,MAT_NROWS(C)); #if PY_MAJOR_VERSION >= 3 syrk[id](&uplo_, &trans_, &n, &k, (ao ? &a : &One[id]), MAT_BUF(A), &ldA, (bo ? &b : &Zero[id]), MAT_BUF(C), &ldC); #else syrk[id](&uplo, &trans, &n, &k, (ao ? &a : &One[id]), MAT_BUF(A), &ldA, (bo ? &b : &Zero[id]), MAT_BUF(C), &ldC); #endif } else { void *z = NULL; #if PY_MAJOR_VERSION >= 3 if (sp_syrk[id](uplo_, trans_, (ao ? a : One[id]), Matrix_Check(A) ? MAT_BUF(A) : ((spmatrix *)A)->obj, (bo ? b : Zero[id]), Matrix_Check(C) ? MAT_BUF(C) : ((spmatrix *)C)->obj, SpMatrix_Check(A), SpMatrix_Check(C), partial ? PyLong_AS_LONG(partial) : 0, (trans == 'N' ? X_NCOLS(A) : X_NROWS(A)), &z)) #else if (sp_syrk[id](uplo, trans, (ao ? a : One[id]), Matrix_Check(A) ? MAT_BUF(A) : ((spmatrix *)A)->obj, (bo ? b : Zero[id]), Matrix_Check(C) ? MAT_BUF(C) : ((spmatrix *)C)->obj, SpMatrix_Check(A), SpMatrix_Check(C), partial ? PyInt_AS_LONG(partial) : 0, (trans == 'N' ? X_NCOLS(A) : X_NROWS(A)), &z)) #endif return PyErr_NoMemory(); if (z) { free_ccs( ((spmatrix *)C)->obj ); ((spmatrix *)C)->obj = z; } } return Py_BuildValue(""); } static char doc_symv[] = "Matrix-vector product with a real symmetric dense or sparse matrix.\n\n" "symv(A, x, y, uplo='L', alpha=1.0, beta=0.0, n=A.size[0], \n" " ldA=max(1,A.size[0]), incx=1, incy=1, offsetA=0, offsetx=0,\n" " offsety=0)\n\n" "PURPOSE\n" "Computes y := alpha*A*x + beta*y with A real symmetric of order n." "n\n" "ARGUMENTS\n" "A 'd' (sp)matrix\n\n" "x 'd' matrix\n\n" "y 'd' matrix\n\n" "uplo 'L' or 'U'\n\n" "alpha real number (int or float)\n\n" "beta real number (int or float)\n\n" "n integer. If negative, the default value is used.\n" " If the default value is used, we require that\n" " A.size[0]=A.size[1].\n\n" "incx nonzero integer\n\n" "incy nonzero integer\n\n" "offsetA nonnegative integer\n\n" "offsetx nonnegative integer\n\n" "offsety nonnegative integer\n\n" "This sparse version of SYMV requires that\n" " m <= A.size[0] - (offsetA % A.size[0])"; static PyObject* base_symv(PyObject *self, PyObject *args, PyObject *kwrds) { PyObject *A, *ao=NULL, *bo=NULL; matrix *x, *y; number a, b; int n=-1, ix=1, iy=1, oA=0, ox=0, oy=0, ldA; #if PY_MAJOR_VERSION >= 3 int uplo='L'; char uplo_; #else char uplo='L'; #endif char *kwlist[] = {"A", "x", "y", "uplo", "alpha", "beta", "n", "incx", "incy", "offsetA", "offsetx", "offsety", NULL}; #if PY_MAJOR_VERSION >= 3 if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OOO|COOiiiiii:symv", kwlist, &A, &x, &y, &uplo, &ao, &bo, &n, &ix, &iy, &oA, &ox, &oy)) #else if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OOO|cOOiiiiii:symv", kwlist, &A, &x, &y, &uplo, &ao, &bo, &n, &ix, &iy, &oA, &ox, &oy)) #endif return NULL; if (!Matrix_Check(A) && !SpMatrix_Check(A)) PY_ERR_TYPE("A must be a dense or sparse matrix"); ldA = MAX(1,X_NROWS(A)); if (!Matrix_Check(x)) err_mtrx("x"); if (!Matrix_Check(y)) err_mtrx("y"); if (X_ID(A) != MAT_ID(x) || X_ID(A) != MAT_ID(y) || MAT_ID(x) != MAT_ID(y)) err_conflicting_ids; int id = X_ID(A); if (id == INT) PY_ERR_TYPE("invalid matrix types"); if (uplo != 'L' && uplo != 'U') err_char("uplo", "'L', 'U'"); if (ix == 0) err_nz_int("incx"); if (iy == 0) err_nz_int("incy"); if (n < 0) { if (X_NROWS(A) != X_NCOLS(A)) { PyErr_SetString(PyExc_ValueError, "A is not square"); return NULL; } n = X_NROWS(A); } if (n == 0) return Py_BuildValue(""); if (oA < 0) err_nn_int("offsetA"); if (oA + (n-1)*ldA + n > len(A)) err_buf_len("A"); if (ox < 0) err_nn_int("offsetx"); if (ox + (n-1)*abs(ix) + 1 > len(x)) err_buf_len("x"); if (oy < 0) err_nn_int("offsety"); if (oy + (n-1)*abs(iy) + 1 > len(y)) err_buf_len("y"); if (ao && convert_num[id](&a, ao, 1, 0)) err_type("alpha"); if (bo && convert_num[id](&b, bo, 1, 0)) err_type("beta"); #if PY_MAJOR_VERSION >= 3 uplo_ = uplo; #endif if (Matrix_Check(A)) { #if PY_MAJOR_VERSION >= 3 symv[id](&uplo_, &n, (ao ? &a : &One[id]), (unsigned char*)MAT_BUF(A) + oA*E_SIZE[id], &ldA, (unsigned char*)MAT_BUF(x) + ox*E_SIZE[id], &ix, (bo ? &b : &Zero[id]), (unsigned char*)MAT_BUF(y) + oy*E_SIZE[id], &iy); #else symv[id](&uplo, &n, (ao ? &a : &One[id]), (unsigned char*)MAT_BUF(A) + oA*E_SIZE[id], &ldA, ((char*)MAT_BUF(x)) + ox*E_SIZE[id], &ix, (bo ? &b : &Zero[id]), (unsigned char*)MAT_BUF(y) + oy*E_SIZE[id], &iy); #endif } else { #if PY_MAJOR_VERSION >= 3 if (sp_symv[id](uplo_, n, (ao ? a : One[id]), ((spmatrix *)A)->obj, oA, (unsigned char*)MAT_BUF(x) + ox*E_SIZE[id], ix, (bo ? b : Zero[id]), (unsigned char*)MAT_BUF(y) + oy*E_SIZE[id], iy)) #else if (sp_symv[id](uplo, n, (ao ? a : One[id]), ((spmatrix *)A)->obj, oA, (unsigned char*)MAT_BUF(x) + ox*E_SIZE[id], ix, (bo ? b : Zero[id]), (unsigned char*)MAT_BUF(y) + oy*E_SIZE[id], iy)) #endif return PyErr_NoMemory(); } return Py_BuildValue(""); } spmatrix * sparse_concat(PyObject *L, int id_arg) ; static char doc_sparse[] = "Constructs a sparse block matrix.\n\n" "sparse(x, tc = None)\n\n" "PURPOSE\n" "Constructs a sparse block matrix from a list of block matrices. If a\n" "single matrix is given as argument, then the matrix is converted to\n" "sparse format, optionally with a different typcode. If a single list\n" "of subblocks is specified, then a block column matrix is created;\n" "otherwise when a list of lists is specified, then the inner lists\n" "specify the different block-columns. Each block element must be either\n" "a dense or sparse matrix, or a scalar, and dense matrices are converted\n" "to sparse format by removing 0 elements.\n\n" "ARGUMENTS\n" "x a single matrix, or a list of matrices and scalars, or a list of\n" " lists of matrices and scalars\n\n" "tc typecode character 'd' or 'z'."; static PyObject * sparse(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *Objx = NULL; static char *kwlist[] = { "x", "tc", NULL}; #if PY_MAJOR_VERSION >= 3 int tc = 0; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|C:sparse", kwlist, &Objx, &tc)) #else char tc = 0; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|c:sparse", kwlist, &Objx, &tc)) #endif return NULL; if (tc && !(VALID_TC_SP(tc))) PY_ERR_TYPE("tc must be 'd' or 'z'"); int id = (tc ? TC2ID(tc) : -1); spmatrix *ret = NULL; /* a matrix */ if (Matrix_Check(Objx)) { int m = MAT_NROWS(Objx), n = MAT_NCOLS(Objx); ret = SpMatrix_NewFromMatrix((matrix *)Objx, (id == -1 ? MAX(DOUBLE,MAT_ID(Objx)) : id)); MAT_NROWS(Objx) = m; MAT_NCOLS(Objx) = n; } /* sparse matrix */ else if (SpMatrix_Check(Objx)) { int_t nnz = 0, ik, jk; for (jk=0; jk<SP_NCOLS(Objx); jk++) { for (ik=SP_COL(Objx)[jk]; ik<SP_COL(Objx)[jk+1]; ik++) { #ifndef _MSC_VER if (((SP_ID(Objx) == DOUBLE) && (SP_VALD(Objx)[ik] != 0.0)) || ((SP_ID(Objx) == COMPLEX) && (SP_VALZ(Objx)[ik] != 0.0))) #else if (((SP_ID(Objx) == DOUBLE) && (SP_VALD(Objx)[ik] != 0.0)) || ((SP_ID(Objx) == COMPLEX) && (creal(SP_VALZ(Objx)[ik]) != 0.0 || cimag(SP_VALZ(Objx)[ik]) != 0.0))) #endif nnz++; } } ret = SpMatrix_New(SP_NROWS(Objx), SP_NCOLS(Objx), nnz, SP_ID(Objx)); if (!ret) return NULL; nnz = 0; for (jk=0; jk<SP_NCOLS(Objx); jk++) { for (ik=SP_COL(Objx)[jk]; ik<SP_COL(Objx)[jk+1]; ik++) { if ((SP_ID(Objx) == DOUBLE) && (SP_VALD(Objx)[ik] != 0.0)) { SP_VALD(ret)[nnz] = SP_VALD(Objx)[ik]; SP_ROW(ret)[nnz++] = SP_ROW(Objx)[ik]; SP_COL(ret)[jk+1]++; } #ifndef _MSC_VER else if ((SP_ID(Objx) == COMPLEX) && (SP_VALZ(Objx)[ik] != 0.0)) { #else else if ((SP_ID(Objx) == COMPLEX) && (creal(SP_VALZ(Objx)[ik]) != 0.0 || cimag(SP_VALZ(Objx)[ik]) != 0.0)) { #endif SP_VALZ(ret)[nnz] = SP_VALZ(Objx)[ik]; SP_ROW(ret)[nnz++] = SP_ROW(Objx)[ik]; SP_COL(ret)[jk+1]++; } } } for (jk=0; jk<SP_NCOLS(Objx); jk++) SP_COL(ret)[jk+1] += SP_COL(ret)[jk]; } /* x is a list of lists */ else if (PyList_Check(Objx)) ret = sparse_concat(Objx, id); else PY_ERR_TYPE("invalid matrix initialization"); return (PyObject *)ret; } static char doc_spdiag[] = "Constructs a square block diagonal sparse matrix.\n\n" "spdiag(diag)\n\n" "ARGUMENTS\n" "diag a matrix with a single row or column, or a list of matrices\n" " and scalars."; static PyObject * spdiag(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *diag = NULL, *Dk; static char *kwlist[] = { "diag", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:spdiag", kwlist, &diag)) return NULL; if ((!PyList_Check(diag) && !Matrix_Check(diag) && !SpMatrix_Check(diag)) || (Matrix_Check(diag) && (MAT_LGT(diag) != MAX(MAT_NROWS(diag),MAT_NCOLS(diag)) )) || (SpMatrix_Check(diag) && (SP_LGT(diag) != MAX(SP_NROWS(diag),SP_NCOLS(diag)) )) ) PY_ERR_TYPE("invalid diag argument"); if (Matrix_Check(diag)) { int j, id = MAX(DOUBLE, MAT_ID(diag)), n = MAT_LGT(diag); spmatrix *ret = SpMatrix_New((int_t)n, (int_t)n, (int_t)n, id); if (!ret) return NULL; SP_COL(ret)[0] = 0; for (j=0; j<n; j++) { SP_COL(ret)[j+1] = j+1; SP_ROW(ret)[j] = j; if (MAT_ID(diag) == INT) SP_VALD(ret)[j] = MAT_BUFI(diag)[j]; else if (MAT_ID(diag) == DOUBLE) SP_VALD(ret)[j] = MAT_BUFD(diag)[j]; else SP_VALZ(ret)[j] = MAT_BUFZ(diag)[j]; } return (PyObject *)ret; } else if (SpMatrix_Check(diag)) { int k, id = MAX(DOUBLE, SP_ID(diag)); int_t n = SP_LGT(diag); spmatrix *ret = SpMatrix_New(n, n, SP_NNZ(diag), id); if (!ret) return NULL; SP_COL(ret)[0] = 0; for (k=0; k<SP_NNZ(diag); k++) { SP_COL(ret)[SP_ROW(diag)[k]+1] = 1; SP_ROW(ret)[k] = SP_ROW(diag)[k]; if (SP_ID(diag) == DOUBLE) SP_VALD(ret)[k] = SP_VALD(diag)[k]; else SP_VALZ(ret)[k] = SP_VALZ(diag)[k]; } for (k=0; k<n; k++) SP_COL(ret)[k+1] += SP_COL(ret)[k]; return (PyObject *)ret; } int j, k, l, idx, id=DOUBLE; int_t n=0, nnz=0; for (k=0; k<PyList_GET_SIZE(diag); k++) { Dk = PyList_GET_ITEM(diag, k); if (!Matrix_Check(Dk) && !SpMatrix_Check(Dk) && !PyNumber_Check(Dk)) PY_ERR_TYPE("invalid element in diag"); if (PyNumber_Check(Dk)) { int scalarid = (PyComplex_Check(Dk) ? COMPLEX : (PyFloat_Check(Dk) ? DOUBLE : INT)); id = MAX(id, scalarid); nnz += 1; n += 1; } else { if (X_NROWS(Dk) != X_NCOLS(Dk)) PY_ERR_TYPE("the elements in diag must be square"); n += X_NCOLS(Dk); nnz += (Matrix_Check(Dk) ? X_NROWS(Dk)*X_NROWS(Dk) : SP_NNZ(Dk)); id = MAX(id, X_ID(Dk)); } } spmatrix *ret = SpMatrix_New(n, n, nnz, id); if (!ret) return NULL; SP_COL(ret)[0] = 0; n = 0, idx = 0; for (k=0; k<PyList_GET_SIZE(diag); k++) { Dk = PyList_GET_ITEM(diag, k); if (PyNumber_Check(Dk)) { SP_COL(ret)[n+1] = SP_COL(ret)[n] + 1; SP_ROW(ret)[idx] = n; number val; convert_num[id](&val, Dk, 1, 0); write_num[id](SP_VAL(ret), idx, &val, 0); idx += 1; n += 1; } else { for (j=0; j<X_NCOLS(Dk); j++) { if (Matrix_Check(Dk)) { SP_COL(ret)[j+n+1] = SP_COL(ret)[j+n] + X_NROWS(Dk); for (l=0; l<X_NROWS(Dk); l++) { SP_ROW(ret)[idx] = n + l; if (id == DOUBLE) SP_VALD(ret)[idx] = (MAT_ID(Dk) == DOUBLE ? MAT_BUFD(Dk)[l + j*MAT_NROWS(Dk)] : MAT_BUFI(Dk)[l + j*MAT_NROWS(Dk)]); else #ifndef _MSC_VER SP_VALZ(ret)[idx] = (MAT_ID(Dk) == COMPLEX ? MAT_BUFZ(Dk)[l + j*MAT_NROWS(Dk)] : (MAT_ID(Dk) == DOUBLE ? MAT_BUFD(Dk)[l + j*MAT_NROWS(Dk)] : MAT_BUFI(Dk)[l + j*MAT_NROWS(Dk)])); #else SP_VALZ(ret)[idx] = (MAT_ID(Dk) == COMPLEX ? MAT_BUFZ(Dk)[l + j*MAT_NROWS(Dk)] : (MAT_ID(Dk) == DOUBLE ? _Cbuild(MAT_BUFD(Dk)[l + j*MAT_NROWS(Dk)],0.0) : _Cbuild((double)MAT_BUFI(Dk)[l + j*MAT_NROWS(Dk)],0.0))); #endif idx++; } } else { SP_COL(ret)[j+n+1] = SP_COL(ret)[j+n] + SP_COL(Dk)[j+1]-SP_COL(Dk)[j]; for (l=SP_COL(Dk)[j]; l<SP_COL(Dk)[j+1]; l++) { SP_ROW(ret)[idx] = n + SP_ROW(Dk)[l]; if (id == DOUBLE) SP_VALD(ret)[idx] = SP_VALD(Dk)[l]; else #ifndef _MSC_VER SP_VALZ(ret)[idx] = (SP_ID(Dk) == COMPLEX ? SP_VALZ(Dk)[l] : SP_VALD(Dk)[l]); #else SP_VALZ(ret)[idx] = (SP_ID(Dk) == COMPLEX ? SP_VALZ(Dk)[l] : _Cbuild(SP_VALD(Dk)[l],0.0)); #endif idx++; } } } n += X_NCOLS(Dk); } } return (PyObject *)ret; } matrix * dense(spmatrix *self); PyObject * matrix_elem_max(PyObject *self, PyObject *args, PyObject *kwrds) { PyObject *A, *B; if (!PyArg_ParseTuple(args, "OO:emax", &A, &B)) return NULL; if (!(X_Matrix_Check(A) || PyNumber_Check(A)) || !(X_Matrix_Check(B) || PyNumber_Check(B))) PY_ERR_TYPE("arguments must be either matrices or python numbers"); if (PyComplex_Check(A) || (X_Matrix_Check(A) && X_ID(A)==COMPLEX)) PY_ERR_TYPE("ordering not defined for complex numbers"); if (PyComplex_Check(B) || (X_Matrix_Check(B) && X_ID(B)==COMPLEX)) PY_ERR_TYPE("ordering not defined for complex numbers"); int a_is_number = PyNumber_Check(A) || (Matrix_Check(A) && MAT_LGT(A) == 1) || (SpMatrix_Check(A) && SP_LGT(A) == 1); int b_is_number = PyNumber_Check(B) || (Matrix_Check(B) && MAT_LGT(B) == 1) || (SpMatrix_Check(B) && SP_LGT(B) == 1); int ida = PyNumber_Check(A) ? PyFloat_Check(A) : X_ID(A); int idb = PyNumber_Check(B) ? PyFloat_Check(B) : X_ID(B); int id = MAX( ida, idb ); number a, b; if (a_is_number) { if (PyNumber_Check(A) || Matrix_Check(A)) convert_num[id](&a, A, PyNumber_Check(A), 0); else a.d = ((SP_LGT(A) > 0) ? SP_VALD(A)[0] : 0.0); } if (b_is_number) { if (PyNumber_Check(B) || Matrix_Check(B)) convert_num[id](&b, B, PyNumber_Check(B), 0); else b.d = ((SP_LGT(B) > 0) ? SP_VALD(B)[0] : 0.0); } if ((a_is_number && b_is_number) && (!X_Matrix_Check(A) && !X_Matrix_Check(B))) { if (id == INT) return Py_BuildValue("i", MAX(a.i, b.i) ); else return Py_BuildValue("d", MAX(a.d, b.d) ); } if (!(a_is_number || b_is_number)) { if (X_NROWS(A) != X_NROWS(B) || X_NCOLS(A) != X_NCOLS(B)) PY_ERR_TYPE("incompatible dimensions"); } int_t m = ( !a_is_number ? X_NROWS(A) : (!b_is_number ? X_NROWS(B) : 1)); int_t n = ( !a_is_number ? X_NCOLS(A) : (!b_is_number ? X_NCOLS(B) : 1)); if ((Matrix_Check(A) || a_is_number) || (Matrix_Check(B) || b_is_number)) { int freeA = SpMatrix_Check(A) && (SP_LGT(A) > 1); int freeB = SpMatrix_Check(B) && (SP_LGT(B) > 1); if (freeA) { if (!(A = (PyObject *)dense((spmatrix *)A)) ) return NULL; } if (freeB) { if (!(B = (PyObject *)dense((spmatrix *)B)) ) return NULL; } PyObject *ret = (PyObject *)Matrix_New((int)m, (int)n, id); if (!ret) { if (freeA) { Py_DECREF(A); } if (freeB) { Py_DECREF(B); } return NULL; } int_t i; for (i=0; i<m*n; i++) { if (!a_is_number) convert_num[id](&a, A, 0, i); if (!b_is_number) convert_num[id](&b, B, 0, i); if (id == INT) MAT_BUFI(ret)[i] = MAX(a.i, b.i); else MAT_BUFD(ret)[i] = MAX(a.d, b.d); } if (freeA) { Py_DECREF(A); } if (freeB) { Py_DECREF(B); } return ret; } else { spmatrix *ret = SpMatrix_New(m, n, 0, DOUBLE); if (!ret) return NULL; int_t j, ka = 0, kb = 0, kret = 0; for (j=0; j<n; j++) { while (ka < SP_COL(A)[j+1] && kb < SP_COL(B)[j+1]) { if (SP_ROW(A)[ka] < SP_ROW(B)[kb]) { if (SP_VALD(A)[ka++] > 0.0) SP_COL(ret)[j+1]++; } else if (SP_ROW(A)[ka] > SP_ROW(B)[kb]) { if (SP_VALD(B)[kb++] > 0.0) SP_COL(ret)[j+1]++; } else { SP_COL(ret)[j+1]++; ka++; kb++; } } while (ka < SP_COL(A)[j+1]) { if (SP_VALD(A)[ka++] > 0.0) SP_COL(ret)[j+1]++; } while (kb < SP_COL(B)[j+1]) { if (SP_VALD(B)[kb++] > 0.0) SP_COL(ret)[j+1]++; } } for (j=0; j<n; j++) SP_COL(ret)[j+1] += SP_COL(ret)[j]; int_t *newrow = malloc( sizeof(int_t)*SP_COL(ret)[n] ); double *newval = malloc( sizeof(double)*SP_COL(ret)[n] ); if (!newrow || !newval) { free(newrow); free(newval); Py_DECREF(ret); return PyErr_NoMemory(); } free( ret->obj->rowind ); free( ret->obj->values ); ret->obj->rowind = newrow; ret->obj->values = newval; ka = 0; kb = 0; for (j=0; j<n; j++) { while (ka < SP_COL(A)[j+1] && kb < SP_COL(B)[j+1]) { if (SP_ROW(A)[ka] < SP_ROW(B)[kb]) { if (SP_VALD(A)[ka] > 0.0) { SP_ROW(ret)[kret] = SP_ROW(A)[ka]; SP_VALD(ret)[kret++] = SP_VALD(A)[ka]; } ka++; } else if (SP_ROW(A)[ka] > SP_ROW(B)[kb]) { if (SP_VALD(B)[kb] > 0.0) { SP_ROW(ret)[kret] = SP_ROW(B)[kb]; SP_VALD(ret)[kret++] = SP_VALD(B)[kb]; } kb++; } else { SP_ROW(ret)[kret] = SP_ROW(A)[ka]; SP_VALD(ret)[kret] = MAX(SP_VALD(A)[ka], SP_VALD(B)[kb]); kret++; ka++; kb++; } } while (ka < SP_COL(A)[j+1]) { if (SP_VALD(A)[ka] > 0.0) { SP_ROW(ret)[kret] = SP_ROW(A)[ka]; SP_VALD(ret)[kret++] = SP_VALD(A)[ka]; } ka++; } while (kb < SP_COL(B)[j+1]) { if (SP_VALD(B)[kb] > 0.0) { SP_ROW(ret)[kret] = SP_ROW(B)[kb]; SP_VALD(ret)[kret++] = SP_VALD(B)[kb]; } kb++; } } return (PyObject *)ret; } } PyObject * matrix_elem_min(PyObject *self, PyObject *args, PyObject *kwrds) { PyObject *A, *B; if (!PyArg_ParseTuple(args, "OO:emin", &A, &B)) return NULL; if (!(X_Matrix_Check(A) || PyNumber_Check(A)) || !(X_Matrix_Check(B) || PyNumber_Check(B))) PY_ERR_TYPE("arguments must be either matrices or python numbers"); if (PyComplex_Check(A) || (X_Matrix_Check(A) && X_ID(A)==COMPLEX)) PY_ERR_TYPE("ordering not defined for complex numbers"); if (PyComplex_Check(B) || (X_Matrix_Check(B) && X_ID(B)==COMPLEX)) PY_ERR_TYPE("ordering not defined for complex numbers"); int a_is_number = PyNumber_Check(A) || (Matrix_Check(A) && MAT_LGT(A) == 1) || (SpMatrix_Check(A) && SP_LGT(A) == 1); int b_is_number = PyNumber_Check(B) || (Matrix_Check(B) && MAT_LGT(B) == 1) || (SpMatrix_Check(B) && SP_LGT(B) == 1); int ida = PyNumber_Check(A) ? PyFloat_Check(A) : X_ID(A); int idb = PyNumber_Check(B) ? PyFloat_Check(B) : X_ID(B); int id = MAX( ida, idb ); number a, b; if (a_is_number) { if (PyNumber_Check(A) || Matrix_Check(A)) convert_num[id](&a, A, PyNumber_Check(A), 0); else a.d = ((SP_LGT(A) > 0) ? SP_VALD(A)[0] : 0.0); } if (b_is_number) { if (PyNumber_Check(B) || Matrix_Check(B)) convert_num[id](&b, B, PyNumber_Check(B), 0); else b.d = ((SP_LGT(B) > 0) ? SP_VALD(B)[0] : 0.0); } if ((a_is_number && b_is_number) && (!X_Matrix_Check(A) && !X_Matrix_Check(B))) { if (id == INT) return Py_BuildValue("i", MIN(a.i, b.i) ); else return Py_BuildValue("d", MIN(a.d, b.d) ); } if (!(a_is_number || b_is_number)) { if (X_NROWS(A) != X_NROWS(B) || X_NCOLS(A) != X_NCOLS(B)) PY_ERR_TYPE("incompatible dimensions"); } int_t m = ( !a_is_number ? X_NROWS(A) : (!b_is_number ? X_NROWS(B) : 1)); int_t n = ( !a_is_number ? X_NCOLS(A) : (!b_is_number ? X_NCOLS(B) : 1)); if ((Matrix_Check(A) || a_is_number) || (Matrix_Check(B) || b_is_number)) { int freeA = SpMatrix_Check(A) && (SP_LGT(A) > 1); int freeB = SpMatrix_Check(B) && (SP_LGT(B) > 1); if (freeA) { if (!(A = (PyObject *)dense((spmatrix *)A)) ) return NULL; } if (freeB) { if (!(B = (PyObject *)dense((spmatrix *)B)) ) return NULL; } PyObject *ret = (PyObject *)Matrix_New(m, n, id); if (!ret) { if (freeA) { Py_DECREF(A); } if (freeB) { Py_DECREF(B); } return NULL; } int_t i; for (i=0; i<m*n; i++) { if (!a_is_number) convert_num[id](&a, A, 0, i); if (!b_is_number) convert_num[id](&b, B, 0, i); if (id == INT) MAT_BUFI(ret)[i] = MIN(a.i, b.i); else MAT_BUFD(ret)[i] = MIN(a.d, b.d); } if (freeA) { Py_DECREF(A); } if (freeB) { Py_DECREF(B); } return ret; } else { spmatrix *ret = SpMatrix_New(m, n, 0, DOUBLE); if (!ret) return NULL; int_t j, ka = 0, kb = 0, kret = 0; for (j=0; j<n; j++) { while (ka < SP_COL(A)[j+1] && kb < SP_COL(B)[j+1]) { if (SP_ROW(A)[ka] < SP_ROW(B)[kb]) { if (SP_VALD(A)[ka++] < 0.0) SP_COL(ret)[j+1]++; } else if (SP_ROW(A)[ka] > SP_ROW(B)[kb]) { if (SP_VALD(B)[kb++] < 0.0) SP_COL(ret)[j+1]++; } else { SP_COL(ret)[j+1]++; ka++; kb++; } } while (ka < SP_COL(A)[j+1]) { if (SP_VALD(A)[ka++] < 0.0) SP_COL(ret)[j+1]++; } while (kb < SP_COL(B)[j+1]) { if (SP_VALD(B)[kb++] < 0.0) SP_COL(ret)[j+1]++; } } for (j=0; j<n; j++) SP_COL(ret)[j+1] += SP_COL(ret)[j]; int_t *newrow = malloc( sizeof(int_t)*SP_COL(ret)[n] ); double *newval = malloc( sizeof(double)*SP_COL(ret)[n] ); if (!newrow || !newval) { free(newrow); free(newval); Py_DECREF(ret); return PyErr_NoMemory(); } free( ret->obj->rowind ); free( ret->obj->values ); ret->obj->rowind = newrow; ret->obj->values = newval; ka = 0; kb = 0; for (j=0; j<n; j++) { while (ka < SP_COL(A)[j+1] && kb < SP_COL(B)[j+1]) { if (SP_ROW(A)[ka] < SP_ROW(B)[kb]) { if (SP_VALD(A)[ka] < 0.0) { SP_ROW(ret)[kret] = SP_ROW(A)[ka]; SP_VALD(ret)[kret++] = SP_VALD(A)[ka]; } ka++; } else if (SP_ROW(A)[ka] > SP_ROW(B)[kb]) { if (SP_VALD(B)[kb] < 0.0) { SP_ROW(ret)[kret] = SP_ROW(B)[kb]; SP_VALD(ret)[kret++] = SP_VALD(B)[kb]; } kb++; } else { SP_ROW(ret)[kret] = SP_ROW(A)[ka]; SP_VALD(ret)[kret] = MIN(SP_VALD(A)[ka], SP_VALD(B)[kb]); kret++; ka++; kb++; } } while (ka < SP_COL(A)[j+1]) { if (SP_VALD(A)[ka] < 0.0) { SP_ROW(ret)[kret] = SP_ROW(A)[ka]; SP_VALD(ret)[kret++] = SP_VALD(A)[ka]; } ka++; } while (kb < SP_COL(B)[j+1]) { if (SP_VALD(B)[kb] < 0.0) { SP_ROW(ret)[kret] = SP_ROW(B)[kb]; SP_VALD(ret)[kret++] = SP_VALD(B)[kb]; } kb++; } } return (PyObject *)ret; } } PyObject * matrix_elem_mul(matrix *self, PyObject *args, PyObject *kwrds) { PyObject *A, *B; if (!PyArg_ParseTuple(args, "OO:emul", &A, &B)) return NULL; if (!(X_Matrix_Check(A) || PyNumber_Check(A)) || !(X_Matrix_Check(B) || PyNumber_Check(B))) PY_ERR_TYPE("arguments must be either matrices or python numbers"); int a_is_number = PyNumber_Check(A) || (Matrix_Check(A) && MAT_LGT(A) == 1); int b_is_number = PyNumber_Check(B) || (Matrix_Check(B) && MAT_LGT(B) == 1); int ida, idb; #if PY_MAJOR_VERSION >= 3 if (PyLong_Check(A)) { ida = INT; } #else if (PyInt_Check(A)) { ida = INT; } #endif else if (PyFloat_Check(A)) { ida = DOUBLE; } else if (PyComplex_Check(A)) { ida = COMPLEX; } else { ida = X_ID(A); } #if PY_MAJOR_VERSION >= 3 if (PyLong_Check(B)) { idb = INT; } #else if (PyInt_Check(B)) { idb = INT; } #endif else if (PyFloat_Check(B)) { idb = DOUBLE; } else if (PyComplex_Check(B)) { idb = COMPLEX; } else { idb = X_ID(B); } int id = MAX( ida, idb ); number a, b; if (a_is_number) convert_num[id](&a, A, PyNumber_Check(A), 0); if (b_is_number) convert_num[id](&b, B, PyNumber_Check(B), 0); if (a_is_number && b_is_number && (!X_Matrix_Check(A) && !X_Matrix_Check(B))) { if (!X_Matrix_Check(A) && !X_Matrix_Check(B)) { if (id == INT) return Py_BuildValue("i", a.i*b.i ); else if (id == DOUBLE) return Py_BuildValue("d", a.d*b.d ); else { number c; #ifndef _MSC_VER c.z = a.z*b.z; #else c.z = _Cmulcc(a.z,b.z); #endif return znum2PyObject(&c, 0); } } } if (!(a_is_number || b_is_number)) { if (X_NROWS(A) != X_NROWS(B) || X_NCOLS(A) != X_NCOLS(B)) PY_ERR_TYPE("incompatible dimensions"); } int_t m = ( !a_is_number ? X_NROWS(A) : (!b_is_number ? X_NROWS(B) : 1)); int_t n = ( !a_is_number ? X_NCOLS(A) : (!b_is_number ? X_NCOLS(B) : 1)); if ((Matrix_Check(A) || a_is_number) && (Matrix_Check(B) || b_is_number)) { PyObject *ret = (PyObject *)Matrix_New(m, n, id); if (!ret) return NULL; int_t i; for (i=0; i<m*n; i++) { if (!a_is_number) convert_num[id](&a, A, 0, i); if (!b_is_number) convert_num[id](&b, B, 0, i); if (id == INT) MAT_BUFI(ret)[i] = a.i*b.i; else if (id == DOUBLE) MAT_BUFD(ret)[i] = a.d*b.d; else #ifndef _MSC_VER MAT_BUFZ(ret)[i] = a.z*b.z; #else MAT_BUFZ(ret)[i] = _Cmulcc(a.z,b.z); #endif } return ret; } else if (SpMatrix_Check(A) && !SpMatrix_Check(B)) { PyObject *ret = (PyObject *)SpMatrix_NewFromSpMatrix((spmatrix *)A, id); if (!ret) return NULL; int_t j, k; for (j=0; j<SP_NCOLS(A); j++) { for (k=SP_COL(A)[j]; k<SP_COL(A)[j+1]; k++) { if (!b_is_number) convert_num[id](&b, B, 0, j*m + SP_ROW(A)[k]); if (id == DOUBLE) SP_VALD(ret)[k] *= b.d; else #ifndef _MSC_VER SP_VALZ(ret)[k] *= b.z; #else SP_VALZ(ret)[k] = _Cmulcc(SP_VALZ(ret)[k],b.z); #endif } } return ret; } else if (SpMatrix_Check(B) && !SpMatrix_Check(A)) { PyObject *ret = (PyObject *)SpMatrix_NewFromSpMatrix((spmatrix *)B, id); if (!ret) return NULL; int_t j, k; for (j=0; j<SP_NCOLS(B); j++) { for (k=SP_COL(B)[j]; k<SP_COL(B)[j+1]; k++) { if (!a_is_number) convert_num[id](&a, A, 0, j*m + SP_ROW(B)[k]); if (id == DOUBLE) SP_VALD(ret)[k] *= a.d; else #ifndef _MSC_VER SP_VALZ(ret)[k] *= a.z; #else SP_VALZ(ret)[k] = _Cmulcc(SP_VALZ(ret)[k],a.z); #endif } } return ret; } else { spmatrix *ret = SpMatrix_New(m, n, 0, id); if (!ret) return NULL; int_t j, ka = 0, kb = 0, kret = 0; for (j=0; j<n; j++) { while (ka < SP_COL(A)[j+1] && kb < SP_COL(B)[j+1]) { if (SP_ROW(A)[ka] < SP_ROW(B)[kb]) { ka++; } else if (SP_ROW(A)[ka] > SP_ROW(B)[kb]) { kb++; } else { SP_COL(ret)[j+1]++; ka++; kb++; } } ka = SP_COL(A)[j+1]; kb = SP_COL(B)[j+1]; } for (j=0; j<n; j++) SP_COL(ret)[j+1] += SP_COL(ret)[j]; int_t *newrow = malloc( sizeof(int_t)*SP_COL(ret)[n] ); double *newval = malloc( E_SIZE[id]*SP_COL(ret)[n] ); if (!newrow || !newval) { free(newrow); free(newval); Py_DECREF(ret); return PyErr_NoMemory(); } free( ret->obj->rowind ); free( ret->obj->values ); ret->obj->rowind = newrow; ret->obj->values = newval; ka = 0; kb = 0; for (j=0; j<n; j++) { while (ka < SP_COL(A)[j+1] && kb < SP_COL(B)[j+1]) { if (SP_ROW(A)[ka] < SP_ROW(B)[kb]) { ka++; } else if (SP_ROW(A)[ka] > SP_ROW(B)[kb]) { kb++; } else { SP_ROW(ret)[kret] = SP_ROW(A)[ka]; if (id == DOUBLE) SP_VALD(ret)[kret] = SP_VALD(A)[ka]*SP_VALD(B)[kb]; else #ifndef _MSC_VER SP_VALZ(ret)[kret] = (X_ID(A) == DOUBLE ? SP_VALD(A)[ka] : SP_VALZ(A)[ka])* (X_ID(B) == DOUBLE ? SP_VALD(B)[kb] : SP_VALZ(B)[kb]); #else SP_VALZ(ret)[kret] = _Cmulcc( (X_ID(A) == DOUBLE ? _Cbuild(SP_VALD(A)[ka],0.0) : SP_VALZ(A)[ka]), (X_ID(B) == DOUBLE ? _Cbuild(SP_VALD(B)[kb],0.0) : SP_VALZ(B)[kb])); #endif kret++; ka++; kb++; } } ka = SP_COL(A)[j+1]; kb = SP_COL(B)[j+1]; } return (PyObject *)ret; } } PyObject * matrix_elem_div(matrix *self, PyObject *args, PyObject *kwrds) { PyObject *A, *B, *ret; if (!PyArg_ParseTuple(args, "OO:ediv", &A, &B)) return NULL; if (!(X_Matrix_Check(A) || PyNumber_Check(A)) || !(X_Matrix_Check(B) || PyNumber_Check(B))) PY_ERR_TYPE("arguments must be either matrices or python numbers"); if (SpMatrix_Check(B)) PY_ERR_TYPE("elementwise division with sparse matrix\n"); int a_is_number = PyNumber_Check(A) || (Matrix_Check(A) && MAT_LGT(A) == 1); int b_is_number = PyNumber_Check(B) || (Matrix_Check(B) && MAT_LGT(B) == 1); int ida, idb; #if PY_MAJOR_VERSION >= 3 if (PyLong_Check(A)) { ida = INT; } #else if (PyInt_Check(A)) { ida = INT; } #endif else if (PyFloat_Check(A)) { ida = DOUBLE; } else if (PyComplex_Check(A)) { ida = COMPLEX; } else { ida = X_ID(A); } #if PY_MAJOR_VERSION >= 3 if (PyLong_Check(B)) { idb = INT; } #else if (PyInt_Check(B)) { idb = INT; } #endif else if (PyFloat_Check(B)) { idb = DOUBLE; } else if (PyComplex_Check(B)) { idb = COMPLEX; } else { idb = X_ID(B); } #if PY_MAJOR_VERSION >= 3 int id = MAX( DOUBLE, MAX( ida, idb ) ) ; #else int id = MAX( ida, idb ); #endif number a, b; if (a_is_number) convert_num[id](&a, A, PyNumber_Check(A), 0); if (b_is_number) convert_num[id](&b, B, PyNumber_Check(B), 0); if ((a_is_number && b_is_number) && (!X_Matrix_Check(A) && !Matrix_Check(B))) { if (id == INT) { if (b.i == 0) PY_ERR(PyExc_ArithmeticError, "division by zero"); return Py_BuildValue("i", a.i/b.i ); } else if (id == DOUBLE) { if (b.d == 0.0) PY_ERR(PyExc_ArithmeticError, "division by zero"); return Py_BuildValue("d", a.d/b.d ); } else { #ifndef _MSC_VER if (b.z == 0.0) PY_ERR(PyExc_ArithmeticError, "division by zero"); #else if (creal(b.z) == 0.0 && cimag(b.z) == 0.0) PY_ERR(PyExc_ArithmeticError, "division by zero"); #endif number c; #ifndef _MSC_VER c.z = a.z/b.z; #else c.z = _Cmulcc(a.z, _Cmulcr(conj(b.z),1.0/norm(b.z))); #endif return znum2PyObject(&c, 0); } } if (!(a_is_number || b_is_number)) { if (X_NROWS(A) != MAT_NROWS(B) || X_NCOLS(A) != MAT_NCOLS(B)) PY_ERR_TYPE("incompatible dimensions"); } int m = ( !a_is_number ? X_NROWS(A) : (!b_is_number ? X_NROWS(B) : 1)); int n = ( !a_is_number ? X_NCOLS(A) : (!b_is_number ? X_NCOLS(B) : 1)); if ((Matrix_Check(A) || a_is_number) && (Matrix_Check(B) || b_is_number)) { if (!(ret = (PyObject *)Matrix_New(m, n, id))) return NULL; int i; for (i=0; i<m*n; i++) { if (!a_is_number) convert_num[id](&a, A, 0, i); if (!b_is_number) convert_num[id](&b, B, 0, i); if (id == INT) { if (b.i == 0) goto divzero; MAT_BUFI(ret)[i] = a.i/b.i; } else if (id == DOUBLE) { if (b.d == 0) goto divzero; MAT_BUFD(ret)[i] = a.d/b.d; } else { #ifndef _MSC_VER if (b.z == 0) goto divzero; MAT_BUFZ(ret)[i] = a.z/b.z; #else if (creal(b.z) == 0 && cimag(b.z)== 0) goto divzero; MAT_BUFZ(ret)[i] = _Cmulcc(a.z,_Cmulcr(conj(b.z),1.0/norm(b.z))); #endif } } return ret; } else { // (SpMatrix_Check(A) && !SpMatrix_Check(B)) { if (!(ret = (PyObject *)SpMatrix_NewFromSpMatrix((spmatrix *)A, id))) return NULL; int j, k; for (j=0; j<SP_NCOLS(A); j++) { for (k=SP_COL(A)[j]; k<SP_COL(A)[j+1]; k++) { if (!b_is_number) convert_num[id](&b, B, 0, j*m + SP_ROW(A)[k]); if (id == DOUBLE) { if (b.d == 0.0) goto divzero; SP_VALD(ret)[k] /= b.d; } else { #ifndef _MSC_VER if (b.z == 0) goto divzero; SP_VALZ(ret)[k] /= b.z; #else if (creal(b.z) == 0 && cimag(b.z)== 0) goto divzero; SP_VALZ(ret)[k] = _Cmulcc(SP_VALZ(ret)[k],_Cmulcr(conj(b.z),1.0/norm(b.z))); #endif } } } return ret; } divzero: Py_DECREF(ret); PY_ERR(PyExc_ArithmeticError, "division by zero"); } extern PyObject * matrix_exp(matrix *, PyObject *, PyObject *) ; extern PyObject * matrix_log(matrix *, PyObject *, PyObject *) ; extern PyObject * matrix_sqrt(matrix *, PyObject *, PyObject *) ; extern PyObject * matrix_cos(matrix *, PyObject *, PyObject *) ; extern PyObject * matrix_sin(matrix *, PyObject *, PyObject *) ; extern PyObject * sumdR2_C(PyObject *self, PyObject *args); static PyMethodDef base_functions[] = { {"exp", (PyCFunction)matrix_exp, METH_VARARGS|METH_KEYWORDS, "Computes the element-wise expontial of a matrix"}, {"log", (PyCFunction)matrix_log, METH_VARARGS|METH_KEYWORDS, "Computes the element-wise logarithm of a matrix"}, {"sqrt", (PyCFunction)matrix_sqrt, METH_VARARGS|METH_KEYWORDS, "Computes the element-wise square-root of a matrix"}, {"cos", (PyCFunction)matrix_cos, METH_VARARGS|METH_KEYWORDS, "Computes the element-wise cosine of a matrix"}, {"sin", (PyCFunction)matrix_sin, METH_VARARGS|METH_KEYWORDS, "Computes the element-wise sine of a matrix"}, {"axpy", (PyCFunction)base_axpy, METH_VARARGS|METH_KEYWORDS, doc_axpy}, {"gemm", (PyCFunction)base_gemm, METH_VARARGS|METH_KEYWORDS, doc_gemm}, {"gemv", (PyCFunction)base_gemv, METH_VARARGS|METH_KEYWORDS, doc_gemv}, {"syrk", (PyCFunction)base_syrk, METH_VARARGS|METH_KEYWORDS, doc_syrk}, {"symv", (PyCFunction)base_symv, METH_VARARGS|METH_KEYWORDS, doc_symv}, {"emul", (PyCFunction)matrix_elem_mul, METH_VARARGS|METH_KEYWORDS, "elementwise product of two matrices"}, {"ediv", (PyCFunction)matrix_elem_div, METH_VARARGS|METH_KEYWORDS, "elementwise division between two matrices"}, {"emin", (PyCFunction)matrix_elem_min, METH_VARARGS|METH_KEYWORDS, "elementwise minimum between two matrices"}, {"emax", (PyCFunction)matrix_elem_max, METH_VARARGS|METH_KEYWORDS, "elementwise maximum between two matrices"}, {"sparse", (PyCFunction)sparse, METH_VARARGS|METH_KEYWORDS, doc_sparse}, {"spdiag", (PyCFunction)spdiag, METH_VARARGS|METH_KEYWORDS, doc_spdiag}, {"sumdR2_C", (PyCFunction)sumdR2_C, METH_VARARGS, "sumdR2 C implementation"}, {NULL} /* sentinel */ }; #if PY_MAJOR_VERSION >= 3 static PyModuleDef base_module = { PyModuleDef_HEAD_INIT, "base", base__doc__, -1, base_functions, NULL, NULL, NULL, NULL }; #define INITERROR return NULL PyMODINIT_FUNC PyInit_base(void) #else PyObject *base_mod, *c_api_object; #define INITERROR return PyMODINIT_FUNC initsumdR2(void) #endif { static void *base_API[8]; // PyObject *base_mod, *c_api_object; #if PY_MAJOR_VERSION >= 3 base_mod = PyModule_Create(&base_module); if (base_mod == NULL) #else if (!(base_mod = Py_InitModule3("sumdR2", base_functions, base__doc__))) #endif INITERROR; /* for MS VC++ compatibility */ matrix_tp.tp_alloc = PyType_GenericAlloc; matrix_tp.tp_free = PyObject_Del; if (PyType_Ready(&matrix_tp) < 0) INITERROR; if (PyType_Ready(&matrixiter_tp) < 0) INITERROR; Py_INCREF(&matrix_tp); if (PyModule_AddObject(base_mod, "matrix", (PyObject *) &matrix_tp) < 0) INITERROR; spmatrix_tp.tp_alloc = PyType_GenericAlloc; spmatrix_tp.tp_free = PyObject_Del; if (PyType_Ready(&spmatrix_tp) < 0) INITERROR; if (PyType_Ready(&spmatrixiter_tp) < 0) INITERROR; Py_INCREF(&spmatrix_tp); if (PyModule_AddObject(base_mod, "spmatrix", (PyObject *) &spmatrix_tp) < 0) INITERROR; #ifndef _MSC_VER One[INT].i = 1; One[DOUBLE].d = 1.0; One[COMPLEX].z = 1.0; #else One[INT].i = 1; One[DOUBLE].d = 1.0; One[COMPLEX].z = _Cbuild(1.0,0.0); #endif #ifndef _MSC_VER MinusOne[INT].i = -1; MinusOne[DOUBLE].d = -1.0; MinusOne[COMPLEX].z = -1.0; #else MinusOne[INT].i = -1; MinusOne[DOUBLE].d = -1.0; MinusOne[COMPLEX].z = _Cbuild(-1.0,0.0); #endif #ifndef _MSC_VER Zero[INT].i = 0; Zero[DOUBLE].d = 0.0; Zero[COMPLEX].z = 0.0; #else Zero[INT].i = 0; Zero[DOUBLE].d = 0.0; Zero[COMPLEX].z = _Cbuild(0.0,0.0); #endif /* initialize the C API object */ base_API[0] = (void *)Matrix_New; base_API[1] = (void *)Matrix_NewFromMatrix; base_API[2] = (void *)Matrix_NewFromSequence; base_API[3] = (void *)Matrix_Check_func; base_API[4] = (void *)SpMatrix_New; base_API[5] = (void *)SpMatrix_NewFromSpMatrix; base_API[6] = (void *)SpMatrix_NewFromIJV; base_API[7] = (void *)SpMatrix_Check_func; #if PY_MAJOR_VERSION >= 3 /* Create a Capsule containing the API pointer array's address */ c_api_object = PyCapsule_New((void *)base_API, "base_API", NULL); #else /* Create a CObject containing the API pointer array's address */ c_api_object = PyCObject_FromVoidPtr((void *)base_API, NULL); #endif if (c_api_object != NULL) PyModule_AddObject(base_mod, "_C_API", c_api_object); #if PY_MAJOR_VERSION >= 3 return base_mod; #endif }
356126.c
/* Broadcast flood - bcast 100KB to all, default to using 2 pSync vars */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <getopt.h> #include <string.h> #include <assert.h> #include <shmem.h> #include <shmemx.h> static int atoi_scaled(char *s); static void usage(char *pgm); int Verbose=0; int Serialize; long *pSync; #define DFLT_LOOPS 600 // downsized for 'make check' //#define DFLT_LOOPS 10000 #define N_ELEMENTS 25600 /*100 KB as ints */ int main(int argc, char **argv) { int i,ps,ps_cnt=2; int *target; int *source; int me, npes, elements=N_ELEMENTS, loops=DFLT_LOOPS; char *pgm; double start_time, time_taken; shmem_init(); me = shmem_my_pe(); npes = shmem_n_pes(); if ((pgm=strrchr(argv[0],'/'))) pgm++; else pgm = argv[0]; while ((i = getopt (argc, argv, "hve:l:p:s")) != EOF) { switch (i) { case 'v': Verbose++; break; case 'e': if ((elements = atoi_scaled(optarg)) <= 0) { fprintf(stderr,"ERR: Bad elements count %d\n",elements); shmem_finalize(); return 1; } break; case 'l': if ((loops = atoi_scaled(optarg)) <= 0) { fprintf(stderr,"ERR: Bad loop count %d\n",loops); shmem_finalize(); return 1; } break; case 'p': if ((ps_cnt = atoi_scaled(optarg)) <= 0) { fprintf(stderr,"ERR: Bad pSync[] elements %d\n",loops); shmem_finalize(); return 1; } break; case 's': Serialize++; break; case 'h': if (me == 0) usage(pgm); return 0; default: if (me == 0) { fprintf(stderr,"%s: unknown switch '-%c'?\n",pgm,i); usage(pgm); } shmem_finalize(); return 1; } } ps_cnt *= SHMEM_BCAST_SYNC_SIZE; pSync = shmem_malloc( ps_cnt * sizeof(long) ); for (i = 0; i < ps_cnt; i++) pSync[i] = SHMEM_SYNC_VALUE; source = (int *) shmem_malloc( elements * sizeof(*source) ); target = (int *) shmem_malloc( elements * sizeof(*target) ); for (i = 0; i < elements; i += 1) { source[i] = i + 1; target[i] = -90; } if (me==0 && Verbose) fprintf(stderr,"ps_cnt %d loops %d nElems %d\n", ps_cnt,loops,elements); shmem_barrier_all(); for(time_taken = 0.0, ps = i = 0; i < loops; i++) { start_time = shmemx_wtime(); shmem_broadcast32(target, source, elements, 0, 0, 0, npes, &pSync[ps]); if (Serialize) shmem_barrier_all(); time_taken += (shmemx_wtime() - start_time); if (ps_cnt > 1 ) { ps += SHMEM_BCAST_SYNC_SIZE; if ( ps >= ps_cnt ) ps = 0; } } if(me == 0 && Verbose) { printf("%d loops of Broadcast32(%ld bytes) over %d PEs: %7.3f secs\n", loops, (elements*sizeof(*source)), npes, time_taken); elements = (elements * loops * sizeof(*source)) / (1024*1024); printf(" %7.5f secs per broadcast() @ %7.4f MB/sec\n", (time_taken/(double)loops), ((double)elements / time_taken) ); } if (Verbose > 1) fprintf(stderr,"[%d] pre B1\n",me); shmem_barrier_all(); if (Verbose > 1) fprintf(stderr,"[%d] post B1\n",me); shmem_free(pSync); shmem_free(target); shmem_free(source); shmem_finalize(); return 0; } static int atoi_scaled(char *s) { long val; char *e; val = strtol(s,&e,0); if (e == NULL || *e =='\0') return (int)val; if (*e == 'k' || *e == 'K') val *= 1024; else if (*e == 'm' || *e == 'M') val *= 1024*1024; else if (*e == 'g' || *e == 'G') val *= 1024*1024*1024; return (int)val; } static void usage(char *pgm) { fprintf(stderr, "usage: %s -{lhv}\n" " where:\n" " -l loops (%d) loop count.\n" " -e ints # of integers to broadcast\n" " -p cnt # of pSync[] elements\n" " -v be verbose, multiple 'v' more verbose\n" " -h this text.\n", pgm,DFLT_LOOPS); }
116374.c
#include <sys/types.h> #include <assert.h> #include <inttypes.h> #include <limits.h> #include "crypto_onetimeauth_poly1305.h" #include "crypto_onetimeauth_poly1305_ref.h" static const crypto_onetimeauth_poly1305_implementation *implementation = &crypto_onetimeauth_poly1305_ref_implementation; int crypto_onetimeauth_poly1305_set_implementation(crypto_onetimeauth_poly1305_implementation *impl) { implementation = impl; return 0; } const char * crypto_onetimeauth_poly1305_implementation_name(void) { return implementation->implementation_name(); } int crypto_onetimeauth_poly1305(unsigned char *out, const unsigned char *in, unsigned long long inlen, const unsigned char *k) { return implementation->onetimeauth(out, in, inlen, k); } int crypto_onetimeauth_poly1305_verify(const unsigned char *h, const unsigned char *in, unsigned long long inlen, const unsigned char *k) { return implementation->onetimeauth_verify(h, in, inlen, k); }
131432.c
#include <stdio.h> struct student { int marks1,marks2,marks3,avg; char name[25]; } stud[100],t; void main() { int i,j,n; printf("Enter the no of students\n"); scanf("%d",&n); printf("enter student:name markofsubject1 markofsubject2 markofsubject3\n"); for(i=0;i<n;i++) { scanf("%s %d %d %d",stud[i].name,&stud[i].marks1,&stud[i].marks2,&stud[i].marks3); } for(i=0;i<n;i++) { stud[i].avg=(stud[i].marks1+stud[i].marks2+stud[i].marks3)/3; } for(i=0;i<n;i++) { for(j=0;j<n-1;j++) { if(stud[j].avg<stud[j+1].avg) { t=stud[j]; stud[j]=stud[j+1]; stud[j+1]=t; } } } printf("\nStudent info in terms of marks from highest to lowest\n"); printf("RANK\t\t\tNAME\t\t\tSCORE\n"); printf("---------------------------------------------------------\n"); for(i=0;i<n;i++) { printf("%d\t\t\t%s\t\t\t%d\t\t\t\n",i+1,stud[i].name,stud[i].avg); } }
654428.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE190_Integer_Overflow__int_fscanf_add_14.c Label Definition File: CWE190_Integer_Overflow__int.label.xml Template File: sources-sinks-14.tmpl.c */ /* * @description * CWE: 190 Integer Overflow * BadSource: fscanf Read data from the console using fscanf() * GoodSource: Set data to a small, non-zero number (two) * Sinks: add * GoodSink: Ensure there will not be an overflow before adding 1 to data * BadSink : Add 1 to data, which can cause an overflow * Flow Variant: 14 Control flow: if(globalFive==5) and if(globalFive!=5) * * */ #include "std_testcase.h" #ifndef OMITBAD void CWE190_Integer_Overflow__int_fscanf_add_14_bad() { int data; /* Initialize data */ data = 0; if(globalFive==5) { /* POTENTIAL FLAW: Read data from the console using fscanf() */ fscanf(stdin, "%d", &data); } if(globalFive==5) { { /* POTENTIAL FLAW: Adding 1 to data could cause an overflow */ int result = data + 1; printIntLine(result); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodB2G1() - use badsource and goodsink by changing the second globalFive==5 to globalFive!=5 */ static void goodB2G1() { int data; /* Initialize data */ data = 0; if(globalFive==5) { /* POTENTIAL FLAW: Read data from the console using fscanf() */ fscanf(stdin, "%d", &data); } if(globalFive!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Add a check to prevent an overflow from occurring */ if (data < INT_MAX) { int result = data + 1; printIntLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } } /* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */ static void goodB2G2() { int data; /* Initialize data */ data = 0; if(globalFive==5) { /* POTENTIAL FLAW: Read data from the console using fscanf() */ fscanf(stdin, "%d", &data); } if(globalFive==5) { /* FIX: Add a check to prevent an overflow from occurring */ if (data < INT_MAX) { int result = data + 1; printIntLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } } /* goodG2B1() - use goodsource and badsink by changing the first globalFive==5 to globalFive!=5 */ static void goodG2B1() { int data; /* Initialize data */ data = 0; if(globalFive!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Use a small, non-zero value that will not cause an integer overflow in the sinks */ data = 2; } if(globalFive==5) { { /* POTENTIAL FLAW: Adding 1 to data could cause an overflow */ int result = data + 1; printIntLine(result); } } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */ static void goodG2B2() { int data; /* Initialize data */ data = 0; if(globalFive==5) { /* FIX: Use a small, non-zero value that will not cause an integer overflow in the sinks */ data = 2; } if(globalFive==5) { { /* POTENTIAL FLAW: Adding 1 to data could cause an overflow */ int result = data + 1; printIntLine(result); } } } void CWE190_Integer_Overflow__int_fscanf_add_14_good() { goodB2G1(); goodB2G2(); goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE190_Integer_Overflow__int_fscanf_add_14_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE190_Integer_Overflow__int_fscanf_add_14_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
981202.c
/* http://gcc.gnu.org/ml/gcc-patches/2004-02/msg01307.html */ typedef struct xdef xdef; struct xdef { char xtyp; xdef *next; int y; }; extern void b (); extern void *foo (void *bar); extern void *foo2 (void *bar1, void *bar2); extern void *qwe; static void c (xdef * xp) { b (xp); } static void a (xdef ** xpp) { xdef *xp; xp = *xpp; foo (xp); xp = foo2 (xp, qwe); b (xp->next); foo (xp); if (xp->y) { foo (xp); if (xp) { xdef *p = foo2 (xp, qwe); foo2 (xp, p); xp = foo (p); } else { foo2 (foo(*xpp), *xpp); } } *xpp = foo2 (xpp, qwe); } void b (xdef ** xpp) { xdef *xp = *xpp; if (!xp) return; if (xp->xtyp == 0) a (xpp); c (xp); }
235642.c
/* * * BlueZ - Bluetooth protocol stack for Linux * * Copyright (C) 2006-2008 Nokia Corporation * Copyright (C) 2004-2008 Marcel Holtmann <[email protected]> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <bluetooth/bluetooth.h> #include <bluetooth/hci.h> #include <bluetooth/hci_lib.h> #include <bluetooth/sdp.h> #include <glib.h> #include <dbus/dbus.h> #include <gdbus.h> #include "hcid.h" #include "dbus-common.h" #include "dbus-service.h" #include "dbus-error.h" #include "error.h" #include "adapter.h" #include "dbus-hci.h" #include "device.h" #include "agent.h" #define REQUEST_TIMEOUT (60 * 1000) /* 60 seconds */ #define AGENT_TIMEOUT (10 * 60 * 1000) /* 10 minutes */ typedef enum { AGENT_REQUEST_PASSKEY, AGENT_REQUEST_CONFIRMATION, AGENT_REQUEST_PINCODE, AGENT_REQUEST_AUTHORIZE, AGENT_REQUEST_CONFIRM_MODE } agent_request_type_t; struct agent { struct adapter *adapter; char *name; char *path; uint8_t capability; struct agent_request *request; int exited; agent_remove_cb remove_cb; void *remove_cb_data; guint listener_id; }; struct agent_request { agent_request_type_t type; struct agent *agent; DBusPendingCall *call; void *cb; void *user_data; }; static DBusConnection *connection = NULL; static void agent_release(struct agent *agent) { DBusMessage *message; debug("Releasing agent %s, %s", agent->name, agent->path); if (agent->request) agent_cancel(agent); message = dbus_message_new_method_call(agent->name, agent->path, "org.bluez.Agent", "Release"); if (message == NULL) { error("Couldn't allocate D-Bus message"); return; } dbus_message_set_no_reply(message, TRUE); dbus_connection_send(connection, message, NULL); dbus_message_unref(message); } static int send_cancel_request(struct agent_request *req) { DBusMessage *message; message = dbus_message_new_method_call(req->agent->name, req->agent->path, "org.bluez.Agent", "Cancel"); if (message == NULL) { error("Couldn't allocate D-Bus message"); return -ENOMEM; } dbus_message_set_no_reply(message, TRUE); dbus_connection_send(connection, message, NULL); dbus_message_unref(message); return 0; } static void agent_request_free(struct agent_request *req) { if (req->call) dbus_pending_call_unref(req->call); if (req->agent && req->agent->request) req->agent->request = NULL; g_free(req); } static void agent_exited(void *user_data) { struct agent *agent = user_data; debug("Agent exited without calling Unregister"); agent_destroy(agent, TRUE); } static void agent_free(struct agent *agent) { if (!agent) return; if (agent->remove_cb) agent->remove_cb(agent, agent->remove_cb_data); if (agent->request) { DBusError err; agent_pincode_cb pincode_cb; agent_cb cb; dbus_error_init(&err); dbus_set_error_const(&err, "org.bluez.Error.Failed", "Canceled"); switch (agent->request->type) { case AGENT_REQUEST_PINCODE: pincode_cb = agent->request->cb; pincode_cb(agent, &err, NULL, agent->request->user_data); break; default: cb = agent->request->cb; cb(agent, &err, agent->request->user_data); } dbus_error_free(&err); agent_cancel(agent); } if (!agent->exited) { g_dbus_remove_watch(connection, agent->listener_id); agent_release(agent); } g_free(agent->name); g_free(agent->path); g_free(agent); } struct agent *agent_create(struct adapter *adapter, const char *name, const char *path, uint8_t capability, agent_remove_cb cb, void *remove_cb_data) { struct agent *agent; if (adapter->agent && g_str_equal(adapter->agent->name, name)) return NULL; agent = g_new0(struct agent, 1); agent->adapter = adapter; agent->name = g_strdup(name); agent->path = g_strdup(path); agent->capability = capability; agent->remove_cb = cb; agent->remove_cb_data = remove_cb_data; agent->listener_id = g_dbus_add_disconnect_watch(connection, name, agent_exited, agent, NULL); return agent; } int agent_destroy(struct agent *agent, gboolean exited) { agent->exited = exited; agent_free(agent); return 0; } static struct agent_request *agent_request_new(struct agent *agent, agent_request_type_t type, void *cb, void *user_data) { struct agent_request *req; req = g_new0(struct agent_request, 1); req->agent = agent; req->type = type; req->cb = cb; req->user_data = user_data; return req; } int agent_cancel(struct agent *agent) { if (!agent->request) return -EINVAL; if (agent->request->call) dbus_pending_call_cancel(agent->request->call); if (!agent->exited) send_cancel_request(agent->request); agent_request_free(agent->request); agent->request = NULL; return 0; } static DBusPendingCall *agent_call_authorize(struct agent *agent, const char *device_path, const char *uuid) { DBusMessage *message; DBusPendingCall *call; message = dbus_message_new_method_call(agent->name, agent->path, "org.bluez.Agent", "Authorize"); if (!message) { error("Couldn't allocate D-Bus message"); return NULL; } dbus_message_append_args(message, DBUS_TYPE_OBJECT_PATH, &device_path, DBUS_TYPE_STRING, &uuid, DBUS_TYPE_INVALID); if (dbus_connection_send_with_reply(connection, message, &call, REQUEST_TIMEOUT) == FALSE) { error("D-Bus send failed"); dbus_message_unref(message); return NULL; } dbus_message_unref(message); return call; } static void simple_agent_reply(DBusPendingCall *call, void *user_data) { struct agent_request *req = user_data; struct agent *agent = req->agent; DBusMessage *message; DBusError err; agent_cb cb = req->cb; /* steal_reply will always return non-NULL since the callback * is only called after a reply has been received */ message = dbus_pending_call_steal_reply(call); dbus_error_init(&err); if (dbus_set_error_from_message(&err, message)) { error("Agent replied with an error: %s, %s", err.name, err.message); cb(agent, &err, req->user_data); dbus_error_free(&err); goto done; } dbus_error_init(&err); if (!dbus_message_get_args(message, &err, DBUS_TYPE_INVALID)) { error("Wrong reply signature: %s", err.message); cb(agent, &err, req->user_data); dbus_error_free(&err); goto done; } cb(agent, NULL, req->user_data); done: dbus_message_unref(message); agent->request = NULL; agent_request_free(req); } int agent_authorize(struct agent *agent, const char *path, const char *uuid, agent_cb cb, void *user_data) { struct agent_request *req; if (agent->request) return -EBUSY; req = agent_request_new(agent, AGENT_REQUEST_AUTHORIZE, cb, user_data); req->call = agent_call_authorize(agent, path, uuid); if (!req->call) { agent_request_free(req); return DBUS_HANDLER_RESULT_NEED_MEMORY; } dbus_pending_call_set_notify(req->call, simple_agent_reply, req, NULL); agent->request = req; debug("authorize request was sent for %s", path); return 0; } static DBusPendingCall *pincode_request_new(struct agent *agent, const char *device_path, dbus_bool_t numeric) { DBusMessage *message; DBusPendingCall *call; message = dbus_message_new_method_call(agent->name, agent->path, "org.bluez.Agent", "RequestPinCode"); if (message == NULL) { error("Couldn't allocate D-Bus message"); return NULL; } dbus_message_append_args(message, DBUS_TYPE_OBJECT_PATH, &device_path, DBUS_TYPE_INVALID); if (dbus_connection_send_with_reply(connection, message, &call, REQUEST_TIMEOUT) == FALSE) { error("D-Bus send failed"); dbus_message_unref(message); return NULL; } dbus_message_unref(message); return call; } static void pincode_reply(DBusPendingCall *call, void *user_data) { struct agent_request *req = user_data; struct agent *agent = req->agent; struct adapter *adapter = agent->adapter; agent_pincode_cb cb = req->cb; DBusMessage *message; DBusError err; bdaddr_t sba; size_t len; char *pin; /* steal_reply will always return non-NULL since the callback * is only called after a reply has been received */ message = dbus_pending_call_steal_reply(call); dbus_error_init(&err); if (dbus_set_error_from_message(&err, message)) { error("Agent replied with an error: %s, %s", err.name, err.message); cb(agent, &err, NULL, req->user_data); dbus_error_free(&err); goto done; } dbus_error_init(&err); if (!dbus_message_get_args(message, &err, DBUS_TYPE_STRING, &pin, DBUS_TYPE_INVALID)) { error("Wrong passkey reply signature: %s", err.message); cb(agent, &err, NULL, req->user_data); dbus_error_free(&err); goto done; } len = strlen(pin); dbus_error_init(&err); if (len > 16 || len < 1) { error("Invalid passkey length from handler"); dbus_set_error_const(&err, "org.bluez.Error.InvalidArgs", "Invalid passkey length"); cb(agent, &err, NULL, req->user_data); dbus_error_free(&err); goto done; } str2ba(adapter->address, &sba); set_pin_length(&sba, len); cb(agent, NULL, pin, req->user_data); done: if (message) dbus_message_unref(message); dbus_pending_call_cancel(req->call); agent_request_free(req); } int agent_request_pincode(struct agent *agent, struct device *device, agent_pincode_cb cb, void *user_data) { struct agent_request *req; if (agent->request) return -EBUSY; req = agent_request_new(agent, AGENT_REQUEST_PINCODE, cb, user_data); req->call = pincode_request_new(agent, device->path, FALSE); if (!req->call) goto failed; dbus_pending_call_set_notify(req->call, pincode_reply, req, NULL); agent->request = req; return 0; failed: g_free(req); return -1; } static DBusPendingCall *confirm_mode_change_request_new(struct agent *agent, const char *mode) { DBusMessage *message; DBusPendingCall *call; message = dbus_message_new_method_call(agent->name, agent->path, "org.bluez.Agent", "ConfirmModeChange"); if (message == NULL) { error("Couldn't allocate D-Bus message"); return NULL; } dbus_message_append_args(message, DBUS_TYPE_STRING, &mode, DBUS_TYPE_INVALID); if (dbus_connection_send_with_reply(connection, message, &call, REQUEST_TIMEOUT) == FALSE) { error("D-Bus send failed"); dbus_message_unref(message); return NULL; } dbus_message_unref(message); return call; } int agent_confirm_mode_change(struct agent *agent, const char *new_mode, agent_cb cb, void *user_data) { struct agent_request *req; if (agent->request) return -EBUSY; debug("Calling Agent.ConfirmModeChange: name=%s, path=%s, mode=%s", agent->name, agent->path, new_mode); req = agent_request_new(agent, AGENT_REQUEST_CONFIRM_MODE, cb, user_data); req->call = confirm_mode_change_request_new(agent, new_mode); if (!req->call) goto failed; dbus_pending_call_set_notify(req->call, simple_agent_reply, req, NULL); agent->request = req; return 0; failed: agent_request_free(req); return -1; } static DBusPendingCall *passkey_request_new(struct agent *agent, const char *device_path) { DBusMessage *message; DBusPendingCall *call; message = dbus_message_new_method_call(agent->name, agent->path, "org.bluez.Agent", "RequestPasskey"); if (message == NULL) { error("Couldn't allocate D-Bus message"); return NULL; } dbus_message_append_args(message, DBUS_TYPE_OBJECT_PATH, &device_path, DBUS_TYPE_INVALID); if (dbus_connection_send_with_reply(connection, message, &call, REQUEST_TIMEOUT) == FALSE) { error("D-Bus send failed"); dbus_message_unref(message); return NULL; } dbus_message_unref(message); return call; } static void passkey_reply(DBusPendingCall *call, void *user_data) { struct agent_request *req = user_data; struct agent *agent = req->agent; agent_passkey_cb cb = req->cb; DBusMessage *message; DBusError err; uint32_t passkey; /* steal_reply will always return non-NULL since the callback * is only called after a reply has been received */ message = dbus_pending_call_steal_reply(call); dbus_error_init(&err); if (dbus_set_error_from_message(&err, message)) { error("Agent replied with an error: %s, %s", err.name, err.message); cb(agent, &err, 0, req->user_data); dbus_error_free(&err); goto done; } dbus_error_init(&err); if (!dbus_message_get_args(message, &err, DBUS_TYPE_UINT32, &passkey, DBUS_TYPE_INVALID)) { error("Wrong passkey reply signature: %s", err.message); cb(agent, &err, 0, req->user_data); dbus_error_free(&err); goto done; } cb(agent, NULL, passkey, req->user_data); done: if (message) dbus_message_unref(message); dbus_pending_call_cancel(req->call); agent_request_free(req); } int agent_request_passkey(struct agent *agent, struct device *device, agent_passkey_cb cb, void *user_data) { struct agent_request *req; if (agent->request) return -EBUSY; debug("Calling Agent.RequestPasskey: name=%s, path=%s", agent->name, agent->path); req = agent_request_new(agent, AGENT_REQUEST_PASSKEY, cb, user_data); req->call = passkey_request_new(agent, device->path); if (!req->call) goto failed; dbus_pending_call_set_notify(req->call, passkey_reply, req, NULL); agent->request = req; return 0; failed: agent_request_free(req); return -1; } static DBusPendingCall *confirmation_request_new(struct agent *agent, const char *device_path, uint32_t passkey) { DBusMessage *message; DBusPendingCall *call; message = dbus_message_new_method_call(agent->name, agent->path, "org.bluez.Agent", "RequestConfirmation"); if (message == NULL) { error("Couldn't allocate D-Bus message"); return NULL; } dbus_message_append_args(message, DBUS_TYPE_OBJECT_PATH, &device_path, DBUS_TYPE_UINT32, &passkey, DBUS_TYPE_INVALID); if (dbus_connection_send_with_reply(connection, message, &call, REQUEST_TIMEOUT) == FALSE) { error("D-Bus send failed"); dbus_message_unref(message); return NULL; } dbus_message_unref(message); return call; } int agent_request_confirmation(struct agent *agent, struct device *device, uint32_t passkey, agent_cb cb, void *user_data) { struct agent_request *req; if (agent->request) return -EBUSY; debug("Calling Agent.RequestConfirmation: name=%s, path=%s, passkey=%06u", agent->name, agent->path, passkey); req = agent_request_new(agent, AGENT_REQUEST_CONFIRMATION, cb, user_data); req->call = confirmation_request_new(agent, device->path, passkey); if (!req->call) goto failed; dbus_pending_call_set_notify(req->call, simple_agent_reply, req, NULL); agent->request = req; return 0; failed: agent_request_free(req); return -1; } int agent_display_passkey(struct agent *agent, struct device *device, uint32_t passkey) { DBusMessage *message; message = dbus_message_new_method_call(agent->name, agent->path, "org.bluez.Agent", "DisplayPasskey"); if (!message) { error("Couldn't allocate D-Bus message"); return -1; } dbus_message_append_args(message, DBUS_TYPE_OBJECT_PATH, &device->path, DBUS_TYPE_UINT32, &passkey, DBUS_TYPE_INVALID); if (!g_dbus_send_message(connection, message)) { error("D-Bus send failed"); dbus_message_unref(message); return -1; } return 0; } uint8_t agent_get_io_capability(struct agent *agent) { return agent->capability; } gboolean agent_matches(struct agent *agent, const char *name, const char *path) { if (g_str_equal(agent->name, name) && g_str_equal(agent->path, path)) return TRUE; return FALSE; } void agent_exit(void) { dbus_connection_unref(connection); } void agent_init(void) { connection = dbus_bus_get(DBUS_BUS_SYSTEM, NULL); }
212104.c
#include <stdio.h> int sum2d(int rows, int cols, int array[rows][cols]);
888277.c
/* PR middle-end/51644 */ /* { dg-do compile } */ /* { dg-options "-Wall -fexceptions" } */ #include <stdarg.h> extern void baz (int, va_list) __attribute__ ((__noreturn__)); __attribute__ ((__noreturn__)) void foo (int s, ...) { va_list ap; va_start (ap, s); baz (s, ap); va_end (ap); } /* { dg-bogus "function does return" } */ __attribute__ ((__noreturn__)) void bar (int s, ...) { va_list ap1; va_start (ap1, s); { va_list ap2; va_start (ap2, s); baz (s, ap1); baz (s, ap2); va_end (ap2); } va_end (ap1); } /* { dg-bogus "function does return" } */
553883.c
/* * fcl.beacon project * * FILE test_statistic.c * DATE 2013/08/27 * AUTHOR Arden Zhao * * */ #include <stdio.h> #include "../statistic/bc_statistic.h" #include "../utility/bc_utility.h" #include "../algorithm/bc_algorithm.h" void test_statistic() { // test sample data is generated from www.random.org 2013-11-13 08:13:41 UTC // number between 1 ~ 100. total 100 numbers. double d[]= { 24, 28, 4, 26, 53, 73, 31, 27, 62, 77, 51, 82, 85, 52, 34, 76, 45, 66, 70, 51, 49, 99, 50, 47, 21, 33, 58, 3, 19, 96, 6, 64, 90, 35, 76, 75, 97, 39, 78, 59, 30, 45, 32, 58, 53, 99, 70, 63, 31, 53, 15, 53, 86, 67, 55, 87, 55, 89, 80, 94, 61, 96, 34, 65, 16, 81, 64, 4, 50, 4, 100,41, 66, 52, 62, 16, 77, 19, 24, 24, 49, 81, 50, 4, 22, 9, 54, 19, 38, 25, 72, 39, 45, 37, 42, 57, 88, 67, 35, 33}; // sort sample data: double* sorted_data = ARRAY_CREATE(double, 100); ARRAY_COPY(sorted_data, d, 100); sort_double(sorted_data, 100); // MEAN double mean_value = mean(d,100); printf("function mean result: %f\n", mean_value); // COUNT size_t cnt = COUNT(d); printf("function count result: %d\n", cnt); // MIN double min_value = min(d, 100, 0); printf("function min without sorted result: %f\n", min_value); min_value = min(sorted_data, 100, 1); printf("function min with sorted result: %f\n", min_value); // MAX double max_value = max(d, 100, 0); printf("function max without sorted result: %f\n", max_value); max_value = max(sorted_data, 100, 1); printf("function max with sorted result: %f\n", max_value); // MEDIAN double median_value = median(d, 100, 0); printf("function median without sorted result: %f\n", median_value); median_value = median(sorted_data, 100, 1); printf("function median with sorted result: %f\n", median_value); // RANGE double range_value = range(d, 100, 0); printf("function range without sorted result: %f\n", range_value); range_value = range(sorted_data, 100, 1); printf("function range with sorted result: %f\n", range_value); //VARIANCE double variance_value = variance(d, 100); printf("function variance result: %f\n", variance_value); //VARIANCE_N1 double variance_n1_value = variance_n1(d, 100); printf("function variance_n1 result: %f\n", variance_n1_value); //STDEV double stdev_value = stdev(d, 100); printf("function stdev result: %f\n", stdev_value); //STDEV_N1 double stdev_n1_value = stdev_n1(d, 100); printf("function stdev_n1 result: %f\n", stdev_n1_value); //KURTOSIS double kurtosis_value = kurtosis(d, 100, mean_value, stdev_value); printf("function kurtosis result: %f\n", kurtosis_value); //EXCESS_KURTOSIS double excess_kurtosis_value = excess_kurtosis(d, 100, mean_value, stdev_value); printf("function excess_kurosis result: %f\n", excess_kurtosis_value); //SKEWNESS double skewness_value = skewness(d, 100, mean_value, stdev_value); printf("function skewness result: %f\n", skewness_value); // clean resource ARRAY_DELETE(sorted_data); }
693628.c
// -*-Mode: C++;-*- // technically C99 // * BeginRiceCopyright ***************************************************** // // $HeadURL$ // $Id$ // // -------------------------------------------------------------------------- // Part of HPCToolkit (hpctoolkit.org) // // Information about sources of support for research and development of // HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'. // -------------------------------------------------------------------------- // // Copyright ((c)) 2002-2018, Rice University // 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 the name of Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * #include <stdlib.h> #include <string.h> #include "sample_source_obj.h" #include "common.h" #include <messages/messages.h> #include <hpcrun/thread_data.h> void CMETHOD_FN(add_event, const char *ev) { char *evl = self->evl.evl_spec; TMSG(SS_COMMON,"add event %s to evl |%s|", ev, evl); strcat(evl, ev); strcat(evl," "); TMSG(SS_COMMON,"evl after event added = |%s|",evl); } void CMETHOD_FN(store_event, int event_id, long thresh) { TMSG(SAMPLE_SOURCE,"%s: store event %d thresh = %ld", self->name, event_id, thresh); evlist_t *_p = &(self->evl); int* ev = &(_p->nevents); if (*ev >= MAX_EVENTS) { EMSG("Too many events entered for sample source. Event code %d ignored", event_id); return; } _ev_t* current_event = &(_p->events[*ev]); current_event->event = event_id; current_event->thresh = thresh; (*ev)++; TMSG(SAMPLE_SOURCE,"%s now has %d events", self->name, *ev); } void CMETHOD_FN(store_metric_id, int event_idx, int metric_id) { TMSG(SAMPLE_SOURCE, "%s event[%d] = metric_id %d", self->name, event_idx, metric_id); evlist_t *_p = &(self->evl); int n_events = _p->nevents; if (event_idx >= n_events) { EMSG("Trying to store metric_id(=%d) for an invalid event index(=%d)." "Only %d events recorded for sample source %s", metric_id, event_idx, n_events, self->name); return; } _ev_t* current_event = &(_p->events[event_idx]); current_event->metric_id = metric_id; } char* CMETHOD_FN(get_event_str) { return (self->evl).evl_spec; } bool CMETHOD_FN(started) { return (TD_GET(ss_state)[self->sel_idx] == START); } // ********************************************************** // Interface (NON method) functions // ********************************************************** int hpcrun_event2metric(sample_source_t* ss, int event_idx) { TMSG(SAMPLE_SOURCE, "%s fetching metric_id for event %d", ss->name, event_idx); evlist_t *_p = &(ss->evl); int n_events = _p->nevents; if (event_idx >= n_events) { EMSG("Trying to fetch metric id an invalid event index." "Only %d events recorded for sample source %s. Returning 0", event_idx, n_events, ss->name); return 0; } _ev_t* current_event = &(_p->events[event_idx]); TMSG(SAMPLE_SOURCE, "Fetched metric id = %d", current_event->metric_id); return current_event->metric_id; } // ********************************************************** // Sample Source Failure Messages (ssfail) // ********************************************************** static char *prefix = "HPCToolkit fatal error"; static char *warning = "HPCToolkit warning"; static char *hpcrun_L = "If running a dynamically-linked program with hpcrun, use 'hpcrun -L <program>' for a list of available events.\n\n" "If running a statically-linked program built with hpclink, set HPCRUN_EVENT_LIST=LIST in your environment and\n" "run your program to see a list of available events.\n\n" "Note: Either of the aforementioned methods will exit after listing available events. Arguments to your program\n" "will be ignored. Thus, an execution to list events can be run on a single core and it will execute for only a few\n" "seconds."; static int papi_error = 0; // Special case to treat failure in PAPI init as a soft error. // If PAPI_library_init() fails, delay printing an error message until // after trying all other sample sources. // // This is useful on ranger where PAPI is not compiled into the kernel // on the login nodes, but we can still run with WALLCLOCK there. // void hpcrun_save_papi_error(int error) { papi_error = error; } static void hpcrun_display_papi_error(void) { if (papi_error == HPCRUN_PAPI_ERROR_UNAVAIL) { STDERR_MSG("%s: PAPI_library_init() failed as unavailable.\n" "Probably, the kernel is missing a module for accessing the hardware\n" "performance counters (perf_events, perfmon or perfctr).\n", warning); } else if (papi_error == HPCRUN_PAPI_ERROR_VERSION) { STDERR_MSG("%s: PAPI_library_init() failed with version mismatch.\n" "Probably, HPCToolkit is out of sync with PAPI, or else PAPI is\n" "out of sync with the kernel.\n", warning); } } // The none and unknown event failures happen before we set up the log // file, so we can only write to stderr. void hpcrun_ssfail_none(void) { STDERR_MSG("%s: no sampling source specified.\n" "Set HPCRUN_EVENT_LIST to a comma-separated list of EVENT@PERIOD pairs\n" "and rerun your program. If you truly want to run with no events, then\n" "set HPCRUN_EVENT_LIST=NONE.\n%s", prefix, hpcrun_L); exit(1); } void hpcrun_ssfail_unknown(char *event) { hpcrun_display_papi_error(); STDERR_MSG("%s: event %s is unknown or unsupported.\n%s", prefix, event, hpcrun_L); exit(1); } void hpcrun_ssfail_unsupported(char *source, char *event) { EEMSG("%s: %s event %s is not supported on this platform.\n%s", prefix, source, event, hpcrun_L); exit(1); } void hpcrun_ssfail_derived(char *source, char *event) { EEMSG("%s: %s event %s is a derived event and thus cannot be profiled.\n%s", prefix, source, event, hpcrun_L); exit(1); } void hpcrun_ssfail_all_derived(char *source) { EEMSG("%s: All %s events are derived. To use proxy sampling,\n" "at least one event must support hardware overflow (eg, PAPI_TOT_CYC).\n", prefix, source); exit(1); } void hpcrun_ssfail_conflict(char *source, char *event) { EEMSG("%s: %s event %s cannot be profiled in this sequence.\n" "Either it conflicts with another event, or it exceeds the number of\n" "hardware counters.\n%s", prefix, source, event, hpcrun_L); exit(1); } void hpcrun_ssfail_start(char *source) { EEMSG("%s: sample source %s failed to start.\n" "Check the event list and the HPCToolkit installation and try again.\n%s", prefix, source, hpcrun_L); exit(1); }
133961.c
#include <obs-module.h> struct fade_info { obs_source_t *source; gs_effect_t *effect; gs_eparam_t *a_param; gs_eparam_t *b_param; gs_eparam_t *fade_param; }; static const char *fade_get_name(void *type_data) { UNUSED_PARAMETER(type_data); return obs_module_text("FadeTransition"); } static void *fade_create(obs_data_t *settings, obs_source_t *source) { struct fade_info *fade; char *file = obs_module_file("fade_transition.effect"); gs_effect_t *effect; obs_enter_graphics(); effect = gs_effect_create_from_file(file, NULL); obs_leave_graphics(); bfree(file); if (!effect) { blog(LOG_ERROR, "Could not find fade_transition.effect"); return NULL; } fade = bmalloc(sizeof(*fade)); fade->source = source; fade->effect = effect; fade->a_param = gs_effect_get_param_by_name(effect, "tex_a"); fade->b_param = gs_effect_get_param_by_name(effect, "tex_b"); fade->fade_param = gs_effect_get_param_by_name(effect, "fade_val"); UNUSED_PARAMETER(settings); return fade; } static void fade_destroy(void *data) { struct fade_info *fade = data; bfree(fade); } static void fade_callback(void *data, gs_texture_t *a, gs_texture_t *b, float t, uint32_t cx, uint32_t cy) { struct fade_info *fade = data; gs_effect_set_texture(fade->a_param, a); gs_effect_set_texture(fade->b_param, b); gs_effect_set_float(fade->fade_param, t); while (gs_effect_loop(fade->effect, "Fade")) gs_draw_sprite(NULL, 0, cx, cy); } static void fade_video_render(void *data, gs_effect_t *effect) { struct fade_info *fade = data; obs_transition_video_render(fade->source, fade_callback); UNUSED_PARAMETER(effect); } static float mix_a(void *data, float t) { UNUSED_PARAMETER(data); return 1.0f - t; } static float mix_b(void *data, float t) { UNUSED_PARAMETER(data); return t; } static bool fade_audio_render(void *data, uint64_t *ts_out, struct obs_source_audio_mix *audio, uint32_t mixers, size_t channels, size_t sample_rate) { struct fade_info *fade = data; return obs_transition_audio_render(fade->source, ts_out, audio, mixers, channels, sample_rate, mix_a, mix_b); } struct obs_source_info fade_transition = { .id = "fade_transition", .type = OBS_SOURCE_TYPE_TRANSITION, .get_name = fade_get_name, .create = fade_create, .destroy = fade_destroy, .video_render = fade_video_render, .audio_render = fade_audio_render };
946002.c
/* * Mailslot regression test * * Copyright 2003 Mike McCormack * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #include <windef.h> #include <winbase.h> #include "wine/test.h" static const char szmspath[] = "\\\\.\\mailslot\\wine_mailslot_test"; static int mailslot_test(void) { HANDLE hSlot, hSlot2, hWriter, hWriter2; unsigned char buffer[16]; DWORD count, dwMax, dwNext, dwMsgCount, dwTimeout; BOOL ret; /* sanity check on GetMailslotInfo */ dwMax = dwNext = dwMsgCount = dwTimeout = 0; ok( !GetMailslotInfo( INVALID_HANDLE_VALUE, &dwMax, &dwNext, &dwMsgCount, &dwTimeout ), "getmailslotinfo succeeded\n"); /* open a mailslot that doesn't exist */ hWriter = CreateFileA(szmspath, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); ok( hWriter == INVALID_HANDLE_VALUE, "nonexistent mailslot\n"); /* open a mailslot without the right name */ hSlot = CreateMailslotA( "blah", 0, 0, NULL ); ok( hSlot == INVALID_HANDLE_VALUE, "Created mailslot with invalid name\n"); ok( GetLastError() == ERROR_INVALID_NAME, "error should be ERROR_INVALID_NAME\n"); /* open a mailslot with a null name */ hSlot = CreateMailslotA( NULL, 0, 0, NULL ); ok( hSlot == INVALID_HANDLE_VALUE, "Created mailslot with invalid name\n"); ok( GetLastError() == ERROR_PATH_NOT_FOUND, "error should be ERROR_PATH_NOT_FOUND\n"); /* valid open, but with wacky parameters ... then check them */ hSlot = CreateMailslotA( szmspath, -1, -1, NULL ); ok( hSlot != INVALID_HANDLE_VALUE , "mailslot with valid name failed\n"); dwMax = dwNext = dwMsgCount = dwTimeout = 0; ok( GetMailslotInfo( hSlot, &dwMax, &dwNext, &dwMsgCount, &dwTimeout ), "getmailslotinfo failed\n"); ok( dwMax == ~0U, "dwMax incorrect\n"); ok( dwNext == MAILSLOT_NO_MESSAGE, "dwNext incorrect\n"); ok( dwMsgCount == 0, "dwMsgCount incorrect\n"); ok( dwTimeout == ~0U, "dwTimeout incorrect\n"); ok( GetMailslotInfo( hSlot, NULL, NULL, NULL, NULL ), "getmailslotinfo failed\n"); ok( CloseHandle(hSlot), "failed to close mailslot\n"); /* now open it for real */ hSlot = CreateMailslotA( szmspath, 0, 0, NULL ); ok( hSlot != INVALID_HANDLE_VALUE , "valid mailslot failed\n"); /* try and read/write to it */ count = 0xdeadbeef; SetLastError(0xdeadbeef); ret = ReadFile(INVALID_HANDLE_VALUE, buffer, 0, &count, NULL); ok(!ret, "ReadFile should fail\n"); ok(GetLastError() == ERROR_INVALID_HANDLE, "wrong error %u\n", GetLastError()); ok(count == 0, "expected 0, got %u\n", count); count = 0xdeadbeef; SetLastError(0xdeadbeef); ret = ReadFile(hSlot, buffer, 0, &count, NULL); ok(!ret, "ReadFile should fail\n"); todo_wine ok(GetLastError() == ERROR_SEM_TIMEOUT, "wrong error %u\n", GetLastError()); ok(count == 0, "expected 0, got %u\n", count); count = 0; memset(buffer, 0, sizeof buffer); ret = ReadFile( hSlot, buffer, sizeof buffer, &count, NULL); ok( !ret, "slot read\n"); if (!ret) ok( GetLastError() == ERROR_SEM_TIMEOUT, "wrong error %u\n", GetLastError() ); else ok( count == 0, "wrong count %u\n", count ); ok( !WriteFile( hSlot, buffer, sizeof buffer, &count, NULL), "slot write\n"); ok( GetLastError() == ERROR_ACCESS_DENIED, "wrong error %u\n", GetLastError() ); /* now try and open the client, but with the wrong sharing mode */ hWriter = CreateFileA(szmspath, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); ok( hWriter != INVALID_HANDLE_VALUE /* vista */ || GetLastError() == ERROR_SHARING_VIOLATION, "error should be ERROR_SHARING_VIOLATION got %p / %u\n", hWriter, GetLastError()); if (hWriter != INVALID_HANDLE_VALUE) CloseHandle( hWriter ); /* now open the client with the correct sharing mode */ hWriter = CreateFileA(szmspath, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); ok( hWriter != INVALID_HANDLE_VALUE, "existing mailslot err %u\n", GetLastError()); /* * opening a client should make no difference to * whether we can read or write the mailslot */ ret = ReadFile( hSlot, buffer, sizeof buffer/2, &count, NULL); ok( !ret, "slot read\n"); if (!ret) ok( GetLastError() == ERROR_SEM_TIMEOUT, "wrong error %u\n", GetLastError() ); else ok( count == 0, "wrong count %u\n", count ); ok( !WriteFile( hSlot, buffer, sizeof buffer/2, &count, NULL), "slot write\n"); ok( GetLastError() == ERROR_ACCESS_DENIED, "wrong error %u\n", GetLastError() ); /* * we can't read from this client, * but we should be able to write to it */ ok( !ReadFile( hWriter, buffer, sizeof buffer/2, &count, NULL), "can read client\n"); ok( GetLastError() == ERROR_INVALID_PARAMETER || GetLastError() == ERROR_ACCESS_DENIED, "wrong error %u\n", GetLastError() ); ok( WriteFile( hWriter, buffer, sizeof buffer/2, &count, NULL), "can't write client\n"); ok( !ReadFile( hWriter, buffer, sizeof buffer/2, &count, NULL), "can read client\n"); ok( GetLastError() == ERROR_INVALID_PARAMETER || GetLastError() == ERROR_ACCESS_DENIED, "wrong error %u\n", GetLastError() ); /* * seeing as there's something in the slot, * we should be able to read it once */ ok( ReadFile( hSlot, buffer, sizeof buffer, &count, NULL), "slot read\n"); ok( count == (sizeof buffer/2), "short read\n" ); /* but not again */ ret = ReadFile( hSlot, buffer, sizeof buffer, &count, NULL); ok( !ret, "slot read\n"); if (!ret) ok( GetLastError() == ERROR_SEM_TIMEOUT, "wrong error %u\n", GetLastError() ); else ok( count == 0, "wrong count %u\n", count ); /* now try open another writer... should fail */ hWriter2 = CreateFileA(szmspath, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); /* succeeds on vista, don't test */ if (hWriter2 != INVALID_HANDLE_VALUE) CloseHandle( hWriter2 ); /* now try open another as a reader ... also fails */ hWriter2 = CreateFileA(szmspath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); /* succeeds on vista, don't test */ if (hWriter2 != INVALID_HANDLE_VALUE) CloseHandle( hWriter2 ); /* now try open another as a writer ... still fails */ hWriter2 = CreateFileA(szmspath, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); /* succeeds on vista, don't test */ if (hWriter2 != INVALID_HANDLE_VALUE) CloseHandle( hWriter2 ); /* now open another one */ hSlot2 = CreateMailslotA( szmspath, 0, 0, NULL ); ok( hSlot2 == INVALID_HANDLE_VALUE , "opened two mailslots\n"); /* close the client again */ ok( CloseHandle( hWriter ), "closing the client\n"); /* * now try reopen it with slightly different permissions ... * shared writing */ hWriter = CreateFileA(szmspath, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); ok( hWriter != INVALID_HANDLE_VALUE, "sharing writer\n"); /* * now try open another as a writer ... * but don't share with the first ... fail */ hWriter2 = CreateFileA(szmspath, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); /* succeeds on vista, don't test */ if (hWriter2 != INVALID_HANDLE_VALUE) CloseHandle( hWriter2 ); /* now try open another as a writer ... and share with the first */ hWriter2 = CreateFileA(szmspath, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); ok( hWriter2 != INVALID_HANDLE_VALUE, "2nd sharing writer\n"); /* check the mailslot info */ dwMax = dwNext = dwMsgCount = dwTimeout = 0; ok( GetMailslotInfo( hSlot, &dwMax, &dwNext, &dwMsgCount, &dwTimeout ), "getmailslotinfo failed\n"); ok( dwNext == MAILSLOT_NO_MESSAGE, "dwNext incorrect\n"); ok( dwMax == 0, "dwMax incorrect\n"); ok( dwMsgCount == 0, "dwMsgCount incorrect\n"); ok( dwTimeout == 0, "dwTimeout incorrect\n"); /* check there's still no data */ ret = ReadFile( hSlot, buffer, sizeof buffer, &count, NULL); ok( !ret, "slot read\n"); if (!ret) ok( GetLastError() == ERROR_SEM_TIMEOUT, "wrong error %u\n", GetLastError() ); else ok( count == 0, "wrong count %u\n", count ); /* write two messages */ buffer[0] = 'a'; ok( WriteFile( hWriter, buffer, 1, &count, NULL), "1st write failed\n"); /* check the mailslot info */ dwNext = dwMsgCount = 0; ok( GetMailslotInfo( hSlot, NULL, &dwNext, &dwMsgCount, NULL ), "getmailslotinfo failed\n"); ok( dwNext == 1, "dwNext incorrect\n"); ok( dwMsgCount == 1, "dwMsgCount incorrect\n"); buffer[0] = 'b'; buffer[1] = 'c'; ok( WriteFile( hWriter2, buffer, 2, &count, NULL), "2nd write failed\n"); /* check the mailslot info */ dwNext = dwMsgCount = 0; ok( GetMailslotInfo( hSlot, NULL, &dwNext, &dwMsgCount, NULL ), "getmailslotinfo failed\n"); ok( dwNext == 1, "dwNext incorrect\n"); todo_wine { ok( dwMsgCount == 2, "dwMsgCount incorrect\n"); } /* write a 3rd message with zero size */ ok( WriteFile( hWriter2, buffer, 0, &count, NULL), "3rd write failed\n"); /* check the mailslot info */ dwNext = dwMsgCount = 0; ok( GetMailslotInfo( hSlot, NULL, &dwNext, &dwMsgCount, NULL ), "getmailslotinfo failed\n"); ok( dwNext == 1, "dwNext incorrect\n"); todo_wine ok( dwMsgCount == 3, "dwMsgCount incorrect %u\n", dwMsgCount); buffer[0]=buffer[1]=0; /* * then check that they come out with the correct order and size, * then the slot is empty */ ok( ReadFile( hSlot, buffer, sizeof buffer, &count, NULL), "1st slot read failed\n"); ok( count == 1, "failed to get 1st message\n"); ok( buffer[0] == 'a', "1st message wrong\n"); /* check the mailslot info */ dwNext = dwMsgCount = 0; ok( GetMailslotInfo( hSlot, NULL, &dwNext, &dwMsgCount, NULL ), "getmailslotinfo failed\n"); ok( dwNext == 2, "dwNext incorrect\n"); todo_wine { ok( dwMsgCount == 2, "dwMsgCount incorrect %u\n", dwMsgCount); } /* read the second message */ ok( ReadFile( hSlot, buffer, sizeof buffer, &count, NULL), "2nd slot read failed\n"); ok( count == 2, "failed to get 2nd message\n"); ok( ( buffer[0] == 'b' ) && ( buffer[1] == 'c' ), "2nd message wrong\n"); /* check the mailslot info */ dwNext = dwMsgCount = 0; ok( GetMailslotInfo( hSlot, NULL, &dwNext, &dwMsgCount, NULL ), "getmailslotinfo failed\n"); ok( dwNext == 0, "dwNext incorrect %u\n", dwNext); todo_wine { ok( dwMsgCount == 1, "dwMsgCount incorrect %u\n", dwMsgCount); } /* read the 3rd (zero length) message */ todo_wine { ok( ReadFile( hSlot, buffer, sizeof buffer, &count, NULL), "3rd slot read failed\n"); } ok( count == 0, "failed to get 3rd message\n"); /* * now there should be no more messages * check the mailslot info */ dwNext = dwMsgCount = 0; ok( GetMailslotInfo( hSlot, NULL, &dwNext, &dwMsgCount, NULL ), "getmailslotinfo failed\n"); ok( dwNext == MAILSLOT_NO_MESSAGE, "dwNext incorrect\n"); ok( dwMsgCount == 0, "dwMsgCount incorrect\n"); /* check that reads fail */ ret = ReadFile( hSlot, buffer, sizeof buffer, &count, NULL); ok( !ret, "3rd slot read succeeded\n"); if (!ret) ok( GetLastError() == ERROR_SEM_TIMEOUT, "wrong error %u\n", GetLastError() ); else ok( count == 0, "wrong count %u\n", count ); /* finally close the mailslot and its client */ ok( CloseHandle( hWriter2 ), "closing 2nd client\n"); ok( CloseHandle( hWriter ), "closing the client\n"); ok( CloseHandle( hSlot ), "closing the mailslot\n"); /* test timeouts */ hSlot = CreateMailslotA( szmspath, 0, 1000, NULL ); ok( hSlot != INVALID_HANDLE_VALUE , "valid mailslot failed\n"); count = 0; memset(buffer, 0, sizeof buffer); dwTimeout = GetTickCount(); ok( !ReadFile( hSlot, buffer, sizeof buffer, &count, NULL), "slot read\n"); ok( GetLastError() == ERROR_SEM_TIMEOUT, "wrong error %u\n", GetLastError() ); dwTimeout = GetTickCount() - dwTimeout; ok( dwTimeout >= 900, "timeout too short %u\n", dwTimeout ); ok( CloseHandle( hSlot ), "closing the mailslot\n"); return 0; } START_TEST(mailslot) { mailslot_test(); }
961744.c
// Copyright 2011 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // Alpha-plane compression. // // Author: Skal ([email protected]) #include <assert.h> #include <stdlib.h> #include "./vp8enci.h" #include "../dsp/dsp.h" #include "../utils/filters.h" #include "../utils/quant_levels.h" #include "../utils/utils.h" #include "webp/format_constants.h" // ----------------------------------------------------------------------------- // Encodes the given alpha data via specified compression method 'method'. // The pre-processing (quantization) is performed if 'quality' is less than 100. // For such cases, the encoding is lossy. The valid range is [0, 100] for // 'quality' and [0, 1] for 'method': // 'method = 0' - No compression; // 'method = 1' - Use lossless coder on the alpha plane only // 'filter' values [0, 4] correspond to prediction modes none, horizontal, // vertical & gradient filters. The prediction mode 4 will try all the // prediction modes 0 to 3 and pick the best one. // 'effort_level': specifies how much effort must be spent to try and reduce // the compressed output size. In range 0 (quick) to 6 (slow). // // 'output' corresponds to the buffer containing compressed alpha data. // This buffer is allocated by this method and caller should call // WebPSafeFree(*output) when done. // 'output_size' corresponds to size of this compressed alpha buffer. // // Returns 1 on successfully encoding the alpha and // 0 if either: // invalid quality or method, or // memory allocation for the compressed data fails. #include "../enc/vp8li.h" static int EncodeLossless(const uint8_t* const data, int width, int height, int effort_level, // in [0..6] range VP8LBitWriter* const bw, WebPAuxStats* const stats) { int ok = 0; WebPConfig config; WebPPicture picture; WebPPictureInit(&picture); picture.width = width; picture.height = height; picture.use_argb = 1; picture.stats = stats; if (!WebPPictureAlloc(&picture)) return 0; // Transfer the alpha values to the green channel. WebPDispatchAlphaToGreen(data, width, picture.width, picture.height, picture.argb, picture.argb_stride); WebPConfigInit(&config); config.lossless = 1; config.method = effort_level; // impact is very small // Set a low default quality for encoding alpha. Ensure that Alpha quality at // lower methods (3 and below) is less than the threshold for triggering // costly 'BackwardReferencesTraceBackwards'. config.quality = 8.f * effort_level; assert(config.quality >= 0 && config.quality <= 100.f); ok = (VP8LEncodeStream(&config, &picture, bw) == VP8_ENC_OK); WebPPictureFree(&picture); ok = ok && !bw->error_; if (!ok) { VP8LBitWriterWipeOut(bw); return 0; } return 1; } // ----------------------------------------------------------------------------- // Small struct to hold the result of a filter mode compression attempt. typedef struct { size_t score; VP8BitWriter bw; WebPAuxStats stats; } FilterTrial; // This function always returns an initialized 'bw' object, even upon error. static int EncodeAlphaInternal(const uint8_t* const data, int width, int height, int method, int filter, int reduce_levels, int effort_level, // in [0..6] range uint8_t* const tmp_alpha, FilterTrial* result) { int ok = 0; const uint8_t* alpha_src; WebPFilterFunc filter_func; uint8_t header; const size_t data_size = width * height; const uint8_t* output = NULL; size_t output_size = 0; VP8LBitWriter tmp_bw; assert((uint64_t)data_size == (uint64_t)width * height); // as per spec assert(filter >= 0 && filter < WEBP_FILTER_LAST); assert(method >= ALPHA_NO_COMPRESSION); assert(method <= ALPHA_LOSSLESS_COMPRESSION); assert(sizeof(header) == ALPHA_HEADER_LEN); // TODO(skal): have a common function and #define's to validate alpha params. filter_func = WebPFilters[filter]; if (filter_func != NULL) { filter_func(data, width, height, width, tmp_alpha); alpha_src = tmp_alpha; } else { alpha_src = data; } if (method != ALPHA_NO_COMPRESSION) { ok = VP8LBitWriterInit(&tmp_bw, data_size >> 3); ok = ok && EncodeLossless(alpha_src, width, height, effort_level, &tmp_bw, &result->stats); if (ok) { output = VP8LBitWriterFinish(&tmp_bw); output_size = VP8LBitWriterNumBytes(&tmp_bw); if (output_size > data_size) { // compressed size is larger than source! Revert to uncompressed mode. method = ALPHA_NO_COMPRESSION; VP8LBitWriterWipeOut(&tmp_bw); } } else { VP8LBitWriterWipeOut(&tmp_bw); return 0; } } if (method == ALPHA_NO_COMPRESSION) { output = alpha_src; output_size = data_size; ok = 1; } // Emit final result. header = method | (filter << 2); if (reduce_levels) header |= ALPHA_PREPROCESSED_LEVELS << 4; VP8BitWriterInit(&result->bw, ALPHA_HEADER_LEN + output_size); ok = ok && VP8BitWriterAppend(&result->bw, &header, ALPHA_HEADER_LEN); ok = ok && VP8BitWriterAppend(&result->bw, output, output_size); if (method != ALPHA_NO_COMPRESSION) { VP8LBitWriterWipeOut(&tmp_bw); } ok = ok && !result->bw.error_; result->score = VP8BitWriterSize(&result->bw); return ok; } // ----------------------------------------------------------------------------- static int GetNumColors(const uint8_t* data, int width, int height, int stride) { int j; int colors = 0; uint8_t color[256] = { 0 }; for (j = 0; j < height; ++j) { int i; const uint8_t* const p = data + j * stride; for (i = 0; i < width; ++i) { color[p[i]] = 1; } } for (j = 0; j < 256; ++j) { if (color[j] > 0) ++colors; } return colors; } #define FILTER_TRY_NONE (1 << WEBP_FILTER_NONE) #define FILTER_TRY_ALL ((1 << WEBP_FILTER_LAST) - 1) // Given the input 'filter' option, return an OR'd bit-set of filters to try. static uint32_t GetFilterMap(const uint8_t* alpha, int width, int height, int filter, int effort_level) { uint32_t bit_map = 0U; if (filter == WEBP_FILTER_FAST) { // Quick estimate of the best candidate. int try_filter_none = (effort_level > 3); const int kMinColorsForFilterNone = 16; const int kMaxColorsForFilterNone = 192; const int num_colors = GetNumColors(alpha, width, height, width); // For low number of colors, NONE yields better compression. filter = (num_colors <= kMinColorsForFilterNone) ? WEBP_FILTER_NONE : WebPEstimateBestFilter(alpha, width, height, width); bit_map |= 1 << filter; // For large number of colors, try FILTER_NONE in addition to the best // filter as well. if (try_filter_none || num_colors > kMaxColorsForFilterNone) { bit_map |= FILTER_TRY_NONE; } } else if (filter == WEBP_FILTER_NONE) { bit_map = FILTER_TRY_NONE; } else { // WEBP_FILTER_BEST -> try all bit_map = FILTER_TRY_ALL; } return bit_map; } static void InitFilterTrial(FilterTrial* const score) { score->score = (size_t)~0U; VP8BitWriterInit(&score->bw, 0); } static int ApplyFiltersAndEncode(const uint8_t* alpha, int width, int height, size_t data_size, int method, int filter, int reduce_levels, int effort_level, uint8_t** const output, size_t* const output_size, WebPAuxStats* const stats) { int ok = 1; FilterTrial best; uint32_t try_map = GetFilterMap(alpha, width, height, filter, effort_level); InitFilterTrial(&best); if (try_map != FILTER_TRY_NONE) { uint8_t* filtered_alpha = (uint8_t*)WebPSafeMalloc(1ULL, data_size); if (filtered_alpha == NULL) return 0; for (filter = WEBP_FILTER_NONE; ok && try_map; ++filter, try_map >>= 1) { if (try_map & 1) { FilterTrial trial; ok = EncodeAlphaInternal(alpha, width, height, method, filter, reduce_levels, effort_level, filtered_alpha, &trial); if (ok && trial.score < best.score) { VP8BitWriterWipeOut(&best.bw); best = trial; } else { VP8BitWriterWipeOut(&trial.bw); } } } WebPSafeFree(filtered_alpha); } else { ok = EncodeAlphaInternal(alpha, width, height, method, WEBP_FILTER_NONE, reduce_levels, effort_level, NULL, &best); } if (ok) { if (stats != NULL) { stats->lossless_features = best.stats.lossless_features; stats->histogram_bits = best.stats.histogram_bits; stats->transform_bits = best.stats.transform_bits; stats->cache_bits = best.stats.cache_bits; stats->palette_size = best.stats.palette_size; stats->lossless_size = best.stats.lossless_size; stats->lossless_hdr_size = best.stats.lossless_hdr_size; stats->lossless_data_size = best.stats.lossless_data_size; } *output_size = VP8BitWriterSize(&best.bw); *output = VP8BitWriterBuf(&best.bw); } else { VP8BitWriterWipeOut(&best.bw); } return ok; } static int EncodeAlpha(VP8Encoder* const enc, int quality, int method, int filter, int effort_level, uint8_t** const output, size_t* const output_size) { const WebPPicture* const pic = enc->pic_; const int width = pic->width; const int height = pic->height; uint8_t* quant_alpha = NULL; const size_t data_size = width * height; uint64_t sse = 0; int ok = 1; const int reduce_levels = (quality < 100); // quick sanity checks assert((uint64_t)data_size == (uint64_t)width * height); // as per spec assert(enc != NULL && pic != NULL && pic->a != NULL); assert(output != NULL && output_size != NULL); assert(width > 0 && height > 0); assert(pic->a_stride >= width); assert(filter >= WEBP_FILTER_NONE && filter <= WEBP_FILTER_FAST); if (quality < 0 || quality > 100) { return 0; } if (method < ALPHA_NO_COMPRESSION || method > ALPHA_LOSSLESS_COMPRESSION) { return 0; } if (method == ALPHA_NO_COMPRESSION) { // Don't filter, as filtering will make no impact on compressed size. filter = WEBP_FILTER_NONE; } quant_alpha = (uint8_t*)WebPSafeMalloc(1ULL, data_size); if (quant_alpha == NULL) { return 0; } // Extract alpha data (width x height) from raw_data (stride x height). WebPCopyPlane(pic->a, pic->a_stride, quant_alpha, width, width, height); if (reduce_levels) { // No Quantization required for 'quality = 100'. // 16 alpha levels gives quite a low MSE w.r.t original alpha plane hence // mapped to moderate quality 70. Hence Quality:[0, 70] -> Levels:[2, 16] // and Quality:]70, 100] -> Levels:]16, 256]. const int alpha_levels = (quality <= 70) ? (2 + quality / 5) : (16 + (quality - 70) * 8); ok = QuantizeLevels(quant_alpha, width, height, alpha_levels, &sse); } if (ok) { VP8FiltersInit(); ok = ApplyFiltersAndEncode(quant_alpha, width, height, data_size, method, filter, reduce_levels, effort_level, output, output_size, pic->stats); if (pic->stats != NULL) { // need stats? pic->stats->coded_size += (int)(*output_size); enc->sse_[3] = sse; } } WebPSafeFree(quant_alpha); return ok; } //------------------------------------------------------------------------------ // Main calls static int CompressAlphaJob(VP8Encoder* const enc, void* dummy) { const WebPConfig* config = enc->config_; uint8_t* alpha_data = NULL; size_t alpha_size = 0; const int effort_level = config->method; // maps to [0..6] const WEBP_FILTER_TYPE filter = (config->alpha_filtering == 0) ? WEBP_FILTER_NONE : (config->alpha_filtering == 1) ? WEBP_FILTER_FAST : WEBP_FILTER_BEST; if (!EncodeAlpha(enc, config->alpha_quality, config->alpha_compression, filter, effort_level, &alpha_data, &alpha_size)) { return 0; } if (alpha_size != (uint32_t)alpha_size) { // Sanity check. WebPSafeFree(alpha_data); return 0; } enc->alpha_data_size_ = (uint32_t)alpha_size; enc->alpha_data_ = alpha_data; (void)dummy; return 1; } void VP8EncInitAlpha(VP8Encoder* const enc) { WebPInitAlphaProcessing(); enc->has_alpha_ = WebPPictureHasTransparency(enc->pic_); enc->alpha_data_ = NULL; enc->alpha_data_size_ = 0; if (enc->thread_level_ > 0) { WebPWorker* const worker = &enc->alpha_worker_; WebPGetWorkerInterface()->Init(worker); worker->data1 = enc; worker->data2 = NULL; worker->hook = (WebPWorkerHook)CompressAlphaJob; } } int VP8EncStartAlpha(VP8Encoder* const enc) { if (enc->has_alpha_) { if (enc->thread_level_ > 0) { WebPWorker* const worker = &enc->alpha_worker_; // Makes sure worker is good to go. if (!WebPGetWorkerInterface()->Reset(worker)) { return 0; } WebPGetWorkerInterface()->Launch(worker); return 1; } else { return CompressAlphaJob(enc, NULL); // just do the job right away } } return 1; } int VP8EncFinishAlpha(VP8Encoder* const enc) { if (enc->has_alpha_) { if (enc->thread_level_ > 0) { WebPWorker* const worker = &enc->alpha_worker_; if (!WebPGetWorkerInterface()->Sync(worker)) return 0; // error } } return WebPReportProgress(enc->pic_, enc->percent_ + 20, &enc->percent_); } int VP8EncDeleteAlpha(VP8Encoder* const enc) { int ok = 1; if (enc->thread_level_ > 0) { WebPWorker* const worker = &enc->alpha_worker_; // finish anything left in flight ok = WebPGetWorkerInterface()->Sync(worker); // still need to end the worker, even if !ok WebPGetWorkerInterface()->End(worker); } WebPSafeFree(enc->alpha_data_); enc->alpha_data_ = NULL; enc->alpha_data_size_ = 0; enc->has_alpha_ = 0; return ok; }
868731.c
/* * tclKqueueNotfy.c -- * * This file contains the implementation of the kqueue()-based * DragonFly/Free/Net/OpenBSD-specific notifier, which is the lowest- * level part of the Tcl event loop. This file works together with * generic/tclNotify.c. * * Copyright (c) 1995-1997 Sun Microsystems, Inc. * Copyright (c) 2016 Lucio Andrés Illanes Albornoz <[email protected]> * * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. */ #include "tclInt.h" <<<<<<< HEAD #if defined(NOTIFIER_KQUEUE) && TCL_THREADS ======= >>>>>>> upstream/master #ifndef HAVE_COREFOUNDATION /* Darwin/Mac OS X CoreFoundation notifier is * in tclMacOSXNotify.c */ #if defined(NOTIFIER_KQUEUE) && TCL_THREADS #include <signal.h> #include <sys/types.h> #include <sys/event.h> #include <sys/queue.h> #include <sys/time.h> /* * This structure is used to keep track of the notifier info for a registered * file. */ struct PlatformEventData; typedef struct FileHandler { int fd; int mask; /* Mask of desired events: TCL_READABLE, * etc. */ int readyMask; /* Mask of events that have been seen since * the last time file handlers were invoked * for this file. */ Tcl_FileProc *proc; /* Function to call, in the style of * Tcl_CreateFileHandler. */ ClientData clientData; /* Argument to pass to proc. */ struct FileHandler *nextPtr;/* Next in list of all files we care about. */ LIST_ENTRY(FileHandler) readyNode; /* Next/previous in list of FileHandlers asso- * ciated with regular files (S_IFREG) that are * ready for I/O. */ struct PlatformEventData *pedPtr; /* Pointer to PlatformEventData associating this * FileHandler with kevent(2) events. */ } FileHandler; /* * The following structure associates a FileHandler and the thread that owns * it with the file descriptors of interest and their event masks passed to * kevent(2) and their corresponding event(s) returned by kevent(2). */ struct ThreadSpecificData; struct PlatformEventData { FileHandler *filePtr; struct ThreadSpecificData *tsdPtr; }; /* * The following structure is what is added to the Tcl event queue when file * handlers are ready to fire. */ typedef struct { Tcl_Event header; /* Information that is standard for all * events. */ int fd; /* File descriptor that is ready. Used to find * the FileHandler structure for the file * (can't point directly to the FileHandler * structure because it could go away while * the event is queued). */ } FileHandlerEvent; /* * The following static structure contains the state information for the * kqueue based implementation of the Tcl notifier. One of these structures is * created for each thread that is using the notifier. */ LIST_HEAD(PlatformReadyFileHandlerList, FileHandler); typedef struct ThreadSpecificData { FileHandler *firstFileHandlerPtr; /* Pointer to head of file handler list. */ struct PlatformReadyFileHandlerList firstReadyFileHandlerPtr; /* Pointer to head of list of FileHandlers * associated with regular files (S_IFREG) * that are ready for I/O. */ pthread_mutex_t notifierMutex; /* Mutex protecting notifier termination in * PlatformEventsFinalize. */ int triggerPipe[2]; /* pipe(2) used by other threads to wake * up this thread for inter-thread IPC. */ int eventsFd; /* kqueue(2) file descriptor used to wait for * fds. */ struct kevent *readyEvents; /* Pointer to at most maxReadyEvents events * returned by kevent(2). */ size_t maxReadyEvents; /* Count of kevents in readyEvents. */ } ThreadSpecificData; static Tcl_ThreadDataKey dataKey; /* * Forward declarations of internal functions. */ static void PlatformEventsControl(FileHandler *filePtr, ThreadSpecificData *tsdPtr, int op, int isNew); static void PlatformEventsFinalize(void); static void PlatformEventsInit(void); static int PlatformEventsTranslate(struct kevent *eventPtr); static int PlatformEventsWait(struct kevent *events, size_t numEvents, struct timeval *timePtr); #include "tclUnixNotfy.c" /* *---------------------------------------------------------------------- * * Tcl_InitNotifier -- * * Initializes the platform specific notifier state. * * Results: * Returns a handle to the notifier state for this thread. * * Side effects: * If no initNotifierProc notifier hook exists, PlatformEventsInit * is called. * *---------------------------------------------------------------------- */ ClientData Tcl_InitNotifier(void) { if (tclNotifierHooks.initNotifierProc) { return tclNotifierHooks.initNotifierProc(); } else { ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); PlatformEventsInit(); return tsdPtr; } } /* *---------------------------------------------------------------------- * * Tcl_FinalizeNotifier -- * * This function is called to cleanup the notifier state before a thread * is terminated. * * Results: * None. * * Side effects: * If no finalizeNotifierProc notifier hook exists, PlatformEvents- * Finalize is called. * *---------------------------------------------------------------------- */ void Tcl_FinalizeNotifier( ClientData clientData) { if (tclNotifierHooks.finalizeNotifierProc) { tclNotifierHooks.finalizeNotifierProc(clientData); return; } else { PlatformEventsFinalize(); } } /* *---------------------------------------------------------------------- * * PlatformEventsControl -- * * This function registers interest for the file descriptor and the mask * of TCL_* bits associated with filePtr on the kqueue file descriptor * associated with tsdPtr. * * Future calls to kevent will return filePtr and tsdPtr alongside with * the event registered here via the PlatformEventData struct. * * Results: * None. * * Side effects: * - If adding a new file descriptor, a PlatformEventData struct will be * allocated and associated with filePtr. * - fstat is called on the file descriptor; if it is associated with * a regular file (S_IFREG,) filePtr is considered to be ready for I/O * and added to or deleted from the corresponding list in tsdPtr. * - If it is not associated with a regular file, the file descriptor is * added, modified concerning its mask of events of interest, or * deleted from the epoll file descriptor of the calling thread. * - If deleting a file descriptor, kevent(2) is called twice specifying * EVFILT_READ first and then EVFILT_WRITE (see note below.) * *---------------------------------------------------------------------- */ void PlatformEventsControl( FileHandler *filePtr, ThreadSpecificData *tsdPtr, int op, int isNew) { int numChanges; struct kevent changeList[2]; struct PlatformEventData *newPedPtr; struct stat fdStat; if (isNew) { newPedPtr = (struct PlatformEventData *)Tcl_Alloc(sizeof(struct PlatformEventData)); newPedPtr->filePtr = filePtr; newPedPtr->tsdPtr = tsdPtr; filePtr->pedPtr = newPedPtr; } /* * N.B. As discussed in Tcl_WaitForEvent(), kqueue(2) does not reproduce * the `always ready' {select,poll}(2) behaviour for regular files * (S_IFREG) prior to FreeBSD 11.0-RELEASE. Therefore, filePtr is in these * cases simply added or deleted from the list of FileHandlers associated * with regular files belonging to tsdPtr. */ if (fstat(filePtr->fd, &fdStat) == -1) { Tcl_Panic("fstat: %s", strerror(errno)); } else if ((fdStat.st_mode & S_IFMT) == S_IFREG) { switch (op) { case EV_ADD: if (isNew) { LIST_INSERT_HEAD(&tsdPtr->firstReadyFileHandlerPtr, filePtr, readyNode); } break; case EV_DELETE: LIST_REMOVE(filePtr, readyNode); break; } return; } numChanges = 0; switch (op) { case EV_ADD: if (filePtr->mask & (TCL_READABLE | TCL_EXCEPTION)) { EV_SET(&changeList[numChanges], (uintptr_t)filePtr->fd, EVFILT_READ, op, 0, 0, filePtr->pedPtr); numChanges++; } if (filePtr->mask & TCL_WRITABLE) { EV_SET(&changeList[numChanges], (uintptr_t)filePtr->fd, EVFILT_WRITE, op, 0, 0, filePtr->pedPtr); numChanges++; } if (numChanges) { if (kevent(tsdPtr->eventsFd, changeList, numChanges, NULL, 0, NULL) == -1) { Tcl_Panic("kevent: %s", strerror(errno)); } } break; case EV_DELETE: /* * N.B. kqueue(2) has separate filters for readability and writability * fd events. We therefore need to ensure that fds are ompletely * removed from the kqueue(2) fd when deleting. This is exacerbated * by changes to filePtr->mask w/o calls to PlatforEventsControl() * after e.g. an exec(3) in a child process. * * As one of these calls can fail, two separate kevent(2) calls are * made for EVFILT_{READ,WRITE}. */ EV_SET(&changeList[0], (uintptr_t)filePtr->fd, EVFILT_READ, op, 0, 0, NULL); if ((kevent(tsdPtr->eventsFd, changeList, 1, NULL, 0, NULL) == -1) && (errno != ENOENT)) { Tcl_Panic("kevent: %s", strerror(errno)); } EV_SET(&changeList[0], (uintptr_t)filePtr->fd, EVFILT_WRITE, op, 0, 0, NULL); if ((kevent(tsdPtr->eventsFd, changeList, 1, NULL, 0, NULL) == -1) && (errno != ENOENT)) { Tcl_Panic("kevent: %s", strerror(errno)); } break; } } /* *---------------------------------------------------------------------- * * PlatformEventsFinalize -- * * This function closes the pipe and the kqueue file descriptors and * frees the kevent structs owned by the thread of the caller. The above * operations are protected by tsdPtr->notifierMutex, which is destroyed * thereafter. * * Results: * None. * * Side effects: * While tsdPtr->notifierMutex is held: * The per-thread pipe(2) fds are closed, if non-zero, and set to -1. * The per-thread kqueue(2) fd is closed, if non-zero, and set to 0. * The per-thread kevent structs are freed, if any, and set to 0. * * tsdPtr->notifierMutex is destroyed. * *---------------------------------------------------------------------- */ void PlatformEventsFinalize( void) { ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); pthread_mutex_lock(&tsdPtr->notifierMutex); if (tsdPtr->triggerPipe[0]) { close(tsdPtr->triggerPipe[0]); tsdPtr->triggerPipe[0] = -1; } if (tsdPtr->triggerPipe[1]) { close(tsdPtr->triggerPipe[1]); tsdPtr->triggerPipe[1] = -1; } if (tsdPtr->eventsFd > 0) { close(tsdPtr->eventsFd); tsdPtr->eventsFd = 0; } if (tsdPtr->readyEvents) { Tcl_Free(tsdPtr->readyEvents); tsdPtr->maxReadyEvents = 0; } pthread_mutex_unlock(&tsdPtr->notifierMutex); if ((errno = pthread_mutex_destroy(&tsdPtr->notifierMutex))) { Tcl_Panic("pthread_mutex_destroy: %s", strerror(errno)); } } /* *---------------------------------------------------------------------- * * PlatformEventsInit -- * * This function abstracts creating a kqueue fd via the kqueue system * call and allocating memory for the kevents structs in tsdPtr for the * thread of the caller. * * Results: * None. * * Side effects: * The following per-thread entities are initialised: * - notifierMutex is initialised. * - The pipe(2) is created; fcntl(2) is called on both fds to set * FD_CLOEXEC and O_NONBLOCK. * - The kqueue(2) fd is created; fcntl(2) is called on it to set * FD_CLOEXEC. * - A FileHandler struct is allocated and initialised for the event- * fd(2), registering interest for TCL_READABLE on it via Platform- * EventsControl(). * - readyEvents and maxReadyEvents are initialised with 512 kevents. * *---------------------------------------------------------------------- */ void PlatformEventsInit(void) { ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); int i, fdFl; FileHandler *filePtr; errno = pthread_mutex_init(&tsdPtr->notifierMutex, NULL); if (errno) { Tcl_Panic("Tcl_InitNotifier: %s", "could not create mutex"); } if (pipe(tsdPtr->triggerPipe) != 0) { Tcl_Panic("Tcl_InitNotifier: %s", "could not create trigger pipe"); } else for (i = 0; i < 2; i++) { if (fcntl(tsdPtr->triggerPipe[i], F_SETFD, FD_CLOEXEC) == -1) { Tcl_Panic("fcntl: %s", strerror(errno)); } else { fdFl = fcntl(tsdPtr->triggerPipe[i], F_GETFL); fdFl |= O_NONBLOCK; } if (fcntl(tsdPtr->triggerPipe[i], F_SETFL, fdFl) == -1) { Tcl_Panic("fcntl: %s", strerror(errno)); } } if ((tsdPtr->eventsFd = kqueue()) == -1) { Tcl_Panic("kqueue: %s", strerror(errno)); } else if (fcntl(tsdPtr->eventsFd, F_SETFD, FD_CLOEXEC) == -1) { Tcl_Panic("fcntl: %s", strerror(errno)); } filePtr = (FileHandler *)Tcl_Alloc(sizeof(FileHandler)); filePtr->fd = tsdPtr->triggerPipe[0]; filePtr->mask = TCL_READABLE; PlatformEventsControl(filePtr, tsdPtr, EV_ADD, 1); if (!tsdPtr->readyEvents) { tsdPtr->maxReadyEvents = 512; tsdPtr->readyEvents = (struct kevent *)Tcl_Alloc( tsdPtr->maxReadyEvents * sizeof(tsdPtr->readyEvents[0])); } LIST_INIT(&tsdPtr->firstReadyFileHandlerPtr); } /* *---------------------------------------------------------------------- * * PlatformEventsTranslate -- * * This function translates the platform-specific mask of returned * events in eventPtr to a mask of TCL_* bits. * * Results: * Returns the translated mask. * * Side effects: * None. * *---------------------------------------------------------------------- */ int PlatformEventsTranslate( struct kevent *eventPtr) { int mask; mask = 0; if (eventPtr->filter == EVFILT_READ) { mask |= TCL_READABLE; if (eventPtr->flags & EV_ERROR) { mask |= TCL_EXCEPTION; } } if (eventPtr->filter == EVFILT_WRITE) { mask |= TCL_WRITABLE; if (eventPtr->flags & EV_ERROR) { mask |= TCL_EXCEPTION; } } return mask; } /* *---------------------------------------------------------------------- * * PlatformEventsWait -- * * This function abstracts waiting for I/O events via the kevent system * call. * * Results: * Returns -1 if kevent failed. Returns 0 if polling and if no events * became available whilst polling. Returns a pointer to and the count of * all returned events in all other cases. * * Side effects: * gettimeofday(2), kevent(2), and gettimeofday(2) are called, in the * specified order. * If timePtr specifies a positive value, it is updated to reflect the * amount of time that has passed; if its value would {under, over}flow, * it is set to zero. * *---------------------------------------------------------------------- */ int PlatformEventsWait( struct kevent *events, size_t numEvents, struct timeval *timePtr) { int numFound; struct timeval tv0, tv1, tv_delta; struct timespec timeout, *timeoutPtr; ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); /* * If timePtr is NULL, kevent(2) will wait indefinitely. If it specifies a * timeout of {0,0}, kevent(2) will poll. Otherwise, the timeout will * simply be converted to a timespec. */ if (!timePtr) { timeoutPtr = NULL; } else if (!timePtr->tv_sec && !timePtr->tv_usec) { timeout.tv_sec = 0; timeout.tv_nsec = 0; timeoutPtr = &timeout; } else { timeout.tv_sec = timePtr->tv_sec; timeout.tv_nsec = timePtr->tv_usec * 1000; timeoutPtr = &timeout; } /* * Call (and possibly block on) kevent(2) and substract the delta of * gettimeofday(2) before and after the call from timePtr if the latter is * not NULL. Return the number of events returned by kevent(2). */ gettimeofday(&tv0, NULL); numFound = kevent(tsdPtr->eventsFd, NULL, 0, events, (int) numEvents, timeoutPtr); gettimeofday(&tv1, NULL); if (timePtr && (timePtr->tv_sec && timePtr->tv_usec)) { timersub(&tv1, &tv0, &tv_delta); if (!timercmp(&tv_delta, timePtr, >)) { timersub(timePtr, &tv_delta, timePtr); } else { timePtr->tv_sec = 0; timePtr->tv_usec = 0; } } return numFound; } /* *---------------------------------------------------------------------- * * Tcl_CreateFileHandler -- * * This function registers a file handler with the kqueue notifier * of the thread of the caller. * * Results: * None. * * Side effects: * Creates a new file handler structure. * PlatformEventsControl() is called for the new file handler structure. * *---------------------------------------------------------------------- */ void Tcl_CreateFileHandler( int fd, /* Handle of stream to watch. */ int mask, /* OR'ed combination of TCL_READABLE, * TCL_WRITABLE, and TCL_EXCEPTION: indicates * conditions under which proc should be * called. */ Tcl_FileProc *proc, /* Function to call for each selected * event. */ ClientData clientData) /* Arbitrary data to pass to proc. */ { int isNew; if (tclNotifierHooks.createFileHandlerProc) { tclNotifierHooks.createFileHandlerProc(fd, mask, proc, clientData); return; } else { ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); FileHandler *filePtr; for (filePtr = tsdPtr->firstFileHandlerPtr; filePtr != NULL; filePtr = filePtr->nextPtr) { if (filePtr->fd == fd) { break; } } if (filePtr == NULL) { filePtr = (FileHandler *)Tcl_Alloc(sizeof(FileHandler)); filePtr->fd = fd; filePtr->readyMask = 0; filePtr->nextPtr = tsdPtr->firstFileHandlerPtr; tsdPtr->firstFileHandlerPtr = filePtr; isNew = 1; } else { isNew = 0; } filePtr->proc = proc; filePtr->clientData = clientData; filePtr->mask = mask; PlatformEventsControl(filePtr, tsdPtr, EV_ADD, isNew); } } /* *---------------------------------------------------------------------- * * Tcl_DeleteFileHandler -- * * Cancel a previously-arranged callback arrangement for a file on the * kqueue of the thread of the caller. * * Results: * None. * * Side effects: * If a callback was previously registered on file, remove it. * PlatformEventsControl() is called for the file handler structure. * The PlatformEventData struct associated with the new file handler * structure is freed. * *---------------------------------------------------------------------- */ void Tcl_DeleteFileHandler( int fd) /* Stream id for which to remove callback * function. */ { if (tclNotifierHooks.deleteFileHandlerProc) { tclNotifierHooks.deleteFileHandlerProc(fd); return; } else { FileHandler *filePtr, *prevPtr; ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); /* * Find the entry for the given file (and return if there isn't one). */ for (prevPtr = NULL, filePtr = tsdPtr->firstFileHandlerPtr; ; prevPtr = filePtr, filePtr = filePtr->nextPtr) { if (filePtr == NULL) { return; } if (filePtr->fd == fd) { break; } } /* * Update the check masks for this file. */ PlatformEventsControl(filePtr, tsdPtr, EV_DELETE, 0); if (filePtr->pedPtr) { Tcl_Free(filePtr->pedPtr); } /* * Clean up information in the callback record. */ if (prevPtr == NULL) { tsdPtr->firstFileHandlerPtr = filePtr->nextPtr; } else { prevPtr->nextPtr = filePtr->nextPtr; } Tcl_Free(filePtr); } } /* *---------------------------------------------------------------------- * * Tcl_WaitForEvent -- * * This function is called by Tcl_DoOneEvent to wait for new events on * the message queue. If the block time is 0, then Tcl_WaitForEvent just * polls without blocking. * * The waiting logic is implemented in PlatformEventsWait. * * Results: * Returns -1 if PlatformEventsWait() would block forever, otherwise * returns 0. * * Side effects: * Queues file events that are detected by PlatformEventsWait(). * *---------------------------------------------------------------------- */ int Tcl_WaitForEvent( const Tcl_Time *timePtr) /* Maximum block time, or NULL. */ { if (tclNotifierHooks.waitForEventProc) { return tclNotifierHooks.waitForEventProc(timePtr); } else { FileHandler *filePtr; int mask; Tcl_Time vTime; /* * Impl. notes: timeout & timeoutPtr are used if, and only if threads * are not enabled. They are the arguments for the regular epoll_wait() * used when the core is not thread-enabled. */ struct timeval timeout, *timeoutPtr; int numFound, numEvent; struct PlatformEventData *pedPtr; ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey); int numQueued; ssize_t i; char buf[1]; /* * Set up the timeout structure. Note that if there are no events to * check for, we return with a negative result rather than blocking * forever. */ if (timePtr != NULL) { /* * TIP #233 (Virtualized Time). Is virtual time in effect? And do * we actually have something to scale? If yes to both then we * call the handler to do this scaling. */ if (timePtr->sec != 0 || timePtr->usec != 0) { vTime = *timePtr; tclScaleTimeProcPtr(&vTime, tclTimeClientData); timePtr = &vTime; } timeout.tv_sec = timePtr->sec; timeout.tv_usec = timePtr->usec; timeoutPtr = &timeout; } else { timeoutPtr = NULL; } /* * Walk the list of FileHandlers associated with regular files * (S_IFREG) belonging to tsdPtr, queue Tcl events for them, and * update their mask of events of interest. * * kqueue(2), unlike epoll(7), does support regular files, but * EVFILT_READ only `[r]eturns when the file pointer is not at the end * of file' as opposed to unconditionally. While FreeBSD 11.0-RELEASE * adds support for this mode (NOTE_FILE_POLL,) this is not used for * reasons of compatibility. * * Therefore, the behaviour of {select,poll}(2) is simply simulated * here: fds associated with regular files are added to this list by * PlatformEventsControl() and processed here before calling (and * possibly blocking) on PlatformEventsWait(). */ numQueued = 0; LIST_FOREACH(filePtr, &tsdPtr->firstReadyFileHandlerPtr, readyNode) { mask = 0; if (filePtr->mask & TCL_READABLE) { mask |= TCL_READABLE; } if (filePtr->mask & TCL_WRITABLE) { mask |= TCL_WRITABLE; } /* * Don't bother to queue an event if the mask was previously * non-zero since an event must still be on the queue. */ if (filePtr->readyMask == 0) { FileHandlerEvent *fileEvPtr = (FileHandlerEvent *) Tcl_Alloc(sizeof(FileHandlerEvent)); fileEvPtr->header.proc = FileHandlerEventProc; fileEvPtr->fd = filePtr->fd; Tcl_QueueEvent((Tcl_Event *) fileEvPtr, TCL_QUEUE_TAIL); numQueued++; } filePtr->readyMask = mask; } /* * If any events were queued in the above loop, force PlatformEvents- * Wait() to poll as there already are events that need to be processed * at this point. */ if (numQueued) { timeout.tv_sec = 0; timeout.tv_usec = 0; timeoutPtr = &timeout; } /* * Wait or poll for new events, queue Tcl events for the FileHandlers * corresponding to them, and update the FileHandlers' mask of events * of interest registered by the last call to Tcl_CreateFileHandler(). * * Events for the trigger pipe are processed here in order to facilitate * inter-thread IPC. If another thread intends to wake up this thread * whilst it's blocking on PlatformEventsWait(), it write(2)s to the * other end of the pipe (see Tcl_AlertNotifier(),) which in turn will * cause PlatformEventsWait() to return immediately. */ numFound = PlatformEventsWait(tsdPtr->readyEvents, tsdPtr->maxReadyEvents, timeoutPtr); for (numEvent = 0; numEvent < numFound; numEvent++) { pedPtr = (struct PlatformEventData *) tsdPtr->readyEvents[numEvent].udata; filePtr = pedPtr->filePtr; mask = PlatformEventsTranslate(&tsdPtr->readyEvents[numEvent]); if (filePtr->fd == tsdPtr->triggerPipe[0]) { i = read(tsdPtr->triggerPipe[0], buf, 1); if ((i == -1) && (errno != EAGAIN)) { Tcl_Panic("Tcl_WaitForEvent: read from %p->triggerPipe: %s", (void *) tsdPtr, strerror(errno)); } continue; } if (!mask) { continue; } /* * Don't bother to queue an event if the mask was previously * non-zero since an event must still be on the queue. */ if (filePtr->readyMask == 0) { FileHandlerEvent *fileEvPtr = (FileHandlerEvent *) Tcl_Alloc(sizeof(FileHandlerEvent)); fileEvPtr->header.proc = FileHandlerEventProc; fileEvPtr->fd = filePtr->fd; Tcl_QueueEvent((Tcl_Event *) fileEvPtr, TCL_QUEUE_TAIL); } filePtr->readyMask |= mask; } return 0; } } #endif /* NOTIFIER_KQUEUE && TCL_THREADS */ #endif /* !HAVE_COREFOUNDATION */ /* * Local Variables: * mode: c * c-basic-offset: 4 * fill-column: 78 * End: */
712959.c
inherit NPC; string do_reply(); void create() { set_name("莫欣芳" , ({ "shinfun","fun","girl" }) ); set("gender", "女性" ); set("age", 27); set("long", @TEXT 她国色天香,娇丽无伦;温柔娴静,秀绝人寰。 她姿容绝美,世所罕见。从她身旁你闻道一寒谷 幽香。 TEXT ); set("inquiry", ([ "舞曲谱": (: this_object(), "do_reply" :), ]) ); set("class", "dancer"); set("combat_exp", 200000); set_skill("unarmed", 50); set_skill("dodge", 70); set_skill("stormdance", 50); set_skill("tenderzhi", 70); set_skill("force",50); map_skill("dodge","stormdance"); map_skill("unarmed","tenderzhi"); set("force", 1000); set("max_force", 500); set_temp("apply/armor", 70); set_temp("apply/attack", 50); create_family("晚月庄",2,"弟子"); setup(); carry_object("/d/latemoon/obj/deer_boot")->wear(); carry_object("/d/latemoon/obj/belt")->wear(); carry_object("/d/latemoon/obj/clasp")->wear(); } string do_reply() { this_player()->set("mark/dance-book",1); return("舞曲谱啊,师姐她们练习舞步的时候才用的着,\n"+ "你也想学吗? 嘻嘻...\n"); }
163529.c
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Derick Rethans <[email protected]> | | Pierre-A. Joye <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id: logical_filters.c 321634 2012-01-01 13:15:04Z felipe $ */ #include "php_filter.h" #include "filter_private.h" #include "ext/standard/url.h" #include "ext/pcre/php_pcre.h" #include "zend_multiply.h" #if HAVE_ARPA_INET_H # include <arpa/inet.h> #endif #ifndef INADDR_NONE # define INADDR_NONE ((unsigned long int) -1) #endif /* {{{ FETCH_LONG_OPTION(var_name, option_name) */ #define FETCH_LONG_OPTION(var_name, option_name) \ var_name = 0; \ var_name##_set = 0; \ if (option_array) { \ if (zend_hash_find(HASH_OF(option_array), option_name, sizeof(option_name), (void **) &option_val) == SUCCESS) { \ PHP_FILTER_GET_LONG_OPT(option_val, var_name); \ var_name##_set = 1; \ } \ } /* }}} */ /* {{{ FETCH_STRING_OPTION(var_name, option_name) */ #define FETCH_STRING_OPTION(var_name, option_name) \ var_name = NULL; \ var_name##_set = 0; \ var_name##_len = 0; \ if (option_array) { \ if (zend_hash_find(HASH_OF(option_array), option_name, sizeof(option_name), (void **) &option_val) == SUCCESS) { \ if (Z_TYPE_PP(option_val) == IS_STRING) { \ var_name = Z_STRVAL_PP(option_val); \ var_name##_len = Z_STRLEN_PP(option_val); \ var_name##_set = 1; \ } \ } \ } /* }}} */ #define FORMAT_IPV4 4 #define FORMAT_IPV6 6 static int php_filter_parse_int(const char *str, unsigned int str_len, long *ret TSRMLS_DC) { /* {{{ */ long ctx_value; int sign = 0, digit = 0; const char *end = str + str_len; switch (*str) { case '-': sign = 1; case '+': str++; default: break; } /* must start with 1..9*/ if (str < end && *str >= '1' && *str <= '9') { ctx_value = ((sign)?-1:1) * ((*(str++)) - '0'); } else { return -1; } if ((end - str > MAX_LENGTH_OF_LONG - 1) /* number too long */ || (SIZEOF_LONG == 4 && (end - str == MAX_LENGTH_OF_LONG - 1) && *str > '2')) { /* overflow */ return -1; } while (str < end) { if (*str >= '0' && *str <= '9') { digit = (*(str++) - '0'); if ( (!sign) && ctx_value <= (LONG_MAX-digit)/10 ) { ctx_value = (ctx_value * 10) + digit; } else if ( sign && ctx_value >= (LONG_MIN+digit)/10) { ctx_value = (ctx_value * 10) - digit; } else { return -1; } } else { return -1; } } *ret = ctx_value; return 1; } /* }}} */ static int php_filter_parse_octal(const char *str, unsigned int str_len, long *ret TSRMLS_DC) { /* {{{ */ unsigned long ctx_value = 0; const char *end = str + str_len; while (str < end) { if (*str >= '0' && *str <= '7') { unsigned long n = ((*(str++)) - '0'); if ((ctx_value > ((unsigned long)(~(long)0)) / 8) || ((ctx_value = ctx_value * 8) > ((unsigned long)(~(long)0)) - n)) { return -1; } ctx_value += n; } else { return -1; } } *ret = (long)ctx_value; return 1; } /* }}} */ static int php_filter_parse_hex(const char *str, unsigned int str_len, long *ret TSRMLS_DC) { /* {{{ */ unsigned long ctx_value = 0; const char *end = str + str_len; unsigned long n; while (str < end) { if (*str >= '0' && *str <= '9') { n = ((*(str++)) - '0'); } else if (*str >= 'a' && *str <= 'f') { n = ((*(str++)) - ('a' - 10)); } else if (*str >= 'A' && *str <= 'F') { n = ((*(str++)) - ('A' - 10)); } else { return -1; } if ((ctx_value > ((unsigned long)(~(long)0)) / 16) || ((ctx_value = ctx_value * 16) > ((unsigned long)(~(long)0)) - n)) { return -1; } ctx_value += n; } *ret = (long)ctx_value; return 1; } /* }}} */ void php_filter_int(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { zval **option_val; long min_range, max_range, option_flags; int min_range_set, max_range_set; int allow_octal = 0, allow_hex = 0; int len, error = 0; long ctx_value; char *p; /* Parse options */ FETCH_LONG_OPTION(min_range, "min_range"); FETCH_LONG_OPTION(max_range, "max_range"); option_flags = flags; len = Z_STRLEN_P(value); if (len == 0) { RETURN_VALIDATION_FAILED } if (option_flags & FILTER_FLAG_ALLOW_OCTAL) { allow_octal = 1; } if (option_flags & FILTER_FLAG_ALLOW_HEX) { allow_hex = 1; } /* Start the validating loop */ p = Z_STRVAL_P(value); ctx_value = 0; PHP_FILTER_TRIM_DEFAULT(p, len); if (*p == '0') { p++; len--; if (allow_hex && (*p == 'x' || *p == 'X')) { p++; len--; if (php_filter_parse_hex(p, len, &ctx_value TSRMLS_CC) < 0) { error = 1; } } else if (allow_octal) { if (php_filter_parse_octal(p, len, &ctx_value TSRMLS_CC) < 0) { error = 1; } } else if (len != 0) { error = 1; } } else { if (php_filter_parse_int(p, len, &ctx_value TSRMLS_CC) < 0) { error = 1; } } if (error > 0 || (min_range_set && (ctx_value < min_range)) || (max_range_set && (ctx_value > max_range))) { RETURN_VALIDATION_FAILED } else { zval_dtor(value); Z_TYPE_P(value) = IS_LONG; Z_LVAL_P(value) = ctx_value; return; } } /* }}} */ void php_filter_boolean(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { char *str = Z_STRVAL_P(value); int len = Z_STRLEN_P(value); int ret; PHP_FILTER_TRIM_DEFAULT(str, len); /* returns true for "1", "true", "on" and "yes" * returns false for "0", "false", "off", "no", and "" * null otherwise. */ switch (len) { case 1: if (*str == '1') { ret = 1; } else if (*str == '0') { ret = 0; } else { ret = -1; } break; case 2: if (strncasecmp(str, "on", 2) == 0) { ret = 1; } else if (strncasecmp(str, "no", 2) == 0) { ret = 0; } else { ret = -1; } break; case 3: if (strncasecmp(str, "yes", 3) == 0) { ret = 1; } else if (strncasecmp(str, "off", 3) == 0) { ret = 0; } else { ret = -1; } break; case 4: if (strncasecmp(str, "true", 4) == 0) { ret = 1; } else { ret = -1; } break; case 5: if (strncasecmp(str, "false", 5) == 0) { ret = 0; } else { ret = -1; } break; default: ret = -1; } if (ret == -1) { RETURN_VALIDATION_FAILED } else { zval_dtor(value); ZVAL_BOOL(value, ret); } } /* }}} */ void php_filter_float(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { int len; char *str, *end; char *num, *p; zval **option_val; char *decimal; int decimal_set, decimal_len; char dec_sep = '.'; char tsd_sep[3] = "',."; long lval; double dval; int first, n; len = Z_STRLEN_P(value); str = Z_STRVAL_P(value); PHP_FILTER_TRIM_DEFAULT(str, len); end = str + len; FETCH_STRING_OPTION(decimal, "decimal"); if (decimal_set) { if (decimal_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "decimal separator must be one char"); RETURN_VALIDATION_FAILED } else { dec_sep = *decimal; } } num = p = emalloc(len+1); if (str < end && (*str == '+' || *str == '-')) { *p++ = *str++; } first = 1; while (1) { n = 0; while (str < end && *str >= '0' && *str <= '9') { ++n; *p++ = *str++; } if (str == end || *str == dec_sep || *str == 'e' || *str == 'E') { if (!first && n != 3) { goto error; } if (*str == dec_sep) { *p++ = '.'; str++; while (str < end && *str >= '0' && *str <= '9') { *p++ = *str++; } } if (*str == 'e' || *str == 'E') { *p++ = *str++; if (str < end && (*str == '+' || *str == '-')) { *p++ = *str++; } while (str < end && *str >= '0' && *str <= '9') { *p++ = *str++; } } break; } if ((flags & FILTER_FLAG_ALLOW_THOUSAND) && (*str == tsd_sep[0] || *str == tsd_sep[1] || *str == tsd_sep[2])) { if (first?(n < 1 || n > 3):(n != 3)) { goto error; } first = 0; str++; } else { goto error; } } if (str != end) { goto error; } *p = 0; switch (is_numeric_string(num, p - num, &lval, &dval, 0)) { case IS_LONG: zval_dtor(value); Z_TYPE_P(value) = IS_DOUBLE; Z_DVAL_P(value) = lval; break; case IS_DOUBLE: if ((!dval && p - num > 1 && strpbrk(num, "123456789")) || !zend_finite(dval)) { goto error; } zval_dtor(value); Z_TYPE_P(value) = IS_DOUBLE; Z_DVAL_P(value) = dval; break; default: error: efree(num); RETURN_VALIDATION_FAILED } efree(num); } /* }}} */ void php_filter_validate_regexp(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { zval **option_val; char *regexp; int regexp_len; long option_flags; int regexp_set, option_flags_set; pcre *re = NULL; pcre_extra *pcre_extra = NULL; int preg_options = 0; int ovector[3]; int matches; /* Parse options */ FETCH_STRING_OPTION(regexp, "regexp"); FETCH_LONG_OPTION(option_flags, "flags"); if (!regexp_set) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "'regexp' option missing"); RETURN_VALIDATION_FAILED } re = pcre_get_compiled_regex(regexp, &pcre_extra, &preg_options TSRMLS_CC); if (!re) { RETURN_VALIDATION_FAILED } matches = pcre_exec(re, NULL, Z_STRVAL_P(value), Z_STRLEN_P(value), 0, 0, ovector, 3); /* 0 means that the vector is too small to hold all the captured substring offsets */ if (matches < 0) { RETURN_VALIDATION_FAILED } } /* }}} */ void php_filter_validate_url(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { php_url *url; int old_len = Z_STRLEN_P(value); php_filter_url(value, flags, option_array, charset TSRMLS_CC); if (Z_TYPE_P(value) != IS_STRING || old_len != Z_STRLEN_P(value)) { RETURN_VALIDATION_FAILED } /* Use parse_url - if it returns false, we return NULL */ url = php_url_parse_ex(Z_STRVAL_P(value), Z_STRLEN_P(value)); if (url == NULL) { RETURN_VALIDATION_FAILED } if (url->scheme != NULL && (!strcasecmp(url->scheme, "http") || !strcasecmp(url->scheme, "https"))) { char *e, *s; if (url->host == NULL) { goto bad_url; } e = url->host + strlen(url->host); s = url->host; /* First char of hostname must be alphanumeric */ if(!isalnum((int)*(unsigned char *)s)) { goto bad_url; } while (s < e) { if (!isalnum((int)*(unsigned char *)s) && *s != '-' && *s != '.') { goto bad_url; } s++; } if (*(e - 1) == '.') { goto bad_url; } } if ( url->scheme == NULL || /* some schemas allow the host to be empty */ (url->host == NULL && (strcmp(url->scheme, "mailto") && strcmp(url->scheme, "news") && strcmp(url->scheme, "file"))) || ((flags & FILTER_FLAG_PATH_REQUIRED) && url->path == NULL) || ((flags & FILTER_FLAG_QUERY_REQUIRED) && url->query == NULL) ) { bad_url: php_url_free(url); RETURN_VALIDATION_FAILED } php_url_free(url); } /* }}} */ void php_filter_validate_email(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { /* * The regex below is based on a regex by Michael Rushton. * However, it is not identical. I changed it to only consider routeable * addresses as valid. Michael's regex considers a@b a valid address * which conflicts with section 2.3.5 of RFC 5321 which states that: * * Only resolvable, fully-qualified domain names (FQDNs) are permitted * when domain names are used in SMTP. In other words, names that can * be resolved to MX RRs or address (i.e., A or AAAA) RRs (as discussed * in Section 5) are permitted, as are CNAME RRs whose targets can be * resolved, in turn, to MX or address RRs. Local nicknames or * unqualified names MUST NOT be used. * * This regex does not handle comments and folding whitespace. While * this is technically valid in an email address, these parts aren't * actually part of the address itself. * * Michael's regex carries this copyright: * * Copyright © Michael Rushton 2009-10 * http://squiloople.com/ * Feel free to use and redistribute this code. But please keep this copyright notice. * */ const char regexp[] = "/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD"; pcre *re = NULL; pcre_extra *pcre_extra = NULL; int preg_options = 0; int ovector[150]; /* Needs to be a multiple of 3 */ int matches; /* The maximum length of an e-mail address is 320 octets, per RFC 2821. */ if (Z_STRLEN_P(value) > 320) { RETURN_VALIDATION_FAILED } re = pcre_get_compiled_regex((char *)regexp, &pcre_extra, &preg_options TSRMLS_CC); if (!re) { RETURN_VALIDATION_FAILED } matches = pcre_exec(re, NULL, Z_STRVAL_P(value), Z_STRLEN_P(value), 0, 0, ovector, 3); /* 0 means that the vector is too small to hold all the captured substring offsets */ if (matches < 0) { RETURN_VALIDATION_FAILED } } /* }}} */ static int _php_filter_validate_ipv4(char *str, int str_len, int *ip) /* {{{ */ { const char *end = str + str_len; int num, m; int n = 0; while (str < end) { int leading_zero; if (*str < '0' || *str > '9') { return 0; } leading_zero = (*str == '0'); m = 1; num = ((*(str++)) - '0'); while (str < end && (*str >= '0' && *str <= '9')) { num = num * 10 + ((*(str++)) - '0'); if (num > 255 || ++m > 3) { return 0; } } /* don't allow a leading 0; that introduces octal numbers, * which we don't support */ if (leading_zero && (num != 0 || m > 1)) return 0; ip[n++] = num; if (n == 4) { return str == end; } else if (str >= end || *(str++) != '.') { return 0; } } return 0; } /* }}} */ static int _php_filter_validate_ipv6(char *str, int str_len TSRMLS_DC) /* {{{ */ { int compressed = 0; int blocks = 0; int n; char *ipv4; char *end; int ip4elm[4]; char *s = str; if (!memchr(str, ':', str_len)) { return 0; } /* check for bundled IPv4 */ ipv4 = memchr(str, '.', str_len); if (ipv4) { while (ipv4 > str && *(ipv4-1) != ':') { ipv4--; } if (!_php_filter_validate_ipv4(ipv4, (str_len - (ipv4 - str)), ip4elm)) { return 0; } str_len = ipv4 - str; /* length excluding ipv4 */ if (str_len < 2) { return 0; } if (ipv4[-2] != ':') { /* don't include : before ipv4 unless it's a :: */ str_len--; } blocks = 2; } end = str + str_len; while (str < end) { if (*str == ':') { if (++str >= end) { /* cannot end in : without previous : */ return 0; } if (*str == ':') { if (compressed) { return 0; } blocks++; /* :: means 1 or more 16-bit 0 blocks */ compressed = 1; if (++str == end) { return (blocks <= 8); } } else if ((str - 1) == s) { /* dont allow leading : without another : following */ return 0; } } n = 0; while ((str < end) && ((*str >= '0' && *str <= '9') || (*str >= 'a' && *str <= 'f') || (*str >= 'A' && *str <= 'F'))) { n++; str++; } if (n < 1 || n > 4) { return 0; } if (++blocks > 8) return 0; } return ((compressed && blocks <= 8) || blocks == 8); } /* }}} */ void php_filter_validate_ip(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { /* validates an ipv4 or ipv6 IP, based on the flag (4, 6, or both) add a * flag to throw out reserved ranges; multicast ranges... etc. If both * allow_ipv4 and allow_ipv6 flags flag are used, then the first dot or * colon determine the format */ int ip[4]; int mode; if (memchr(Z_STRVAL_P(value), ':', Z_STRLEN_P(value))) { mode = FORMAT_IPV6; } else if (memchr(Z_STRVAL_P(value), '.', Z_STRLEN_P(value))) { mode = FORMAT_IPV4; } else { RETURN_VALIDATION_FAILED } if ((flags & FILTER_FLAG_IPV4) && (flags & FILTER_FLAG_IPV6)) { /* Both formats are cool */ } else if ((flags & FILTER_FLAG_IPV4) && mode == FORMAT_IPV6) { RETURN_VALIDATION_FAILED } else if ((flags & FILTER_FLAG_IPV6) && mode == FORMAT_IPV4) { RETURN_VALIDATION_FAILED } switch (mode) { case FORMAT_IPV4: if (!_php_filter_validate_ipv4(Z_STRVAL_P(value), Z_STRLEN_P(value), ip)) { RETURN_VALIDATION_FAILED } /* Check flags */ if (flags & FILTER_FLAG_NO_PRIV_RANGE) { if ( (ip[0] == 10) || (ip[0] == 172 && (ip[1] >= 16 && ip[1] <= 31)) || (ip[0] == 192 && ip[1] == 168) ) { RETURN_VALIDATION_FAILED } } if (flags & FILTER_FLAG_NO_RES_RANGE) { if ( (ip[0] == 0) || (ip[0] == 128 && ip[1] == 0) || (ip[0] == 191 && ip[1] == 255) || (ip[0] == 169 && ip[1] == 254) || (ip[0] == 192 && ip[1] == 0 && ip[2] == 2) || (ip[0] == 127 && ip[1] == 0 && ip[2] == 0 && ip[3] == 1) || (ip[0] >= 224 && ip[0] <= 255) ) { RETURN_VALIDATION_FAILED } } break; case FORMAT_IPV6: { int res = 0; res = _php_filter_validate_ipv6(Z_STRVAL_P(value), Z_STRLEN_P(value) TSRMLS_CC); if (res < 1) { RETURN_VALIDATION_FAILED } /* Check flags */ if (flags & FILTER_FLAG_NO_PRIV_RANGE) { if (Z_STRLEN_P(value) >=2 && (!strncasecmp("FC", Z_STRVAL_P(value), 2) || !strncasecmp("FD", Z_STRVAL_P(value), 2))) { RETURN_VALIDATION_FAILED } } if (flags & FILTER_FLAG_NO_RES_RANGE) { switch (Z_STRLEN_P(value)) { case 1: case 0: break; case 2: if (!strcmp("::", Z_STRVAL_P(value))) { RETURN_VALIDATION_FAILED } break; case 3: if (!strcmp("::1", Z_STRVAL_P(value)) || !strcmp("5f:", Z_STRVAL_P(value))) { RETURN_VALIDATION_FAILED } break; default: if (Z_STRLEN_P(value) >= 5) { if ( !strncasecmp("fe8", Z_STRVAL_P(value), 3) || !strncasecmp("fe9", Z_STRVAL_P(value), 3) || !strncasecmp("fea", Z_STRVAL_P(value), 3) || !strncasecmp("feb", Z_STRVAL_P(value), 3) ) { RETURN_VALIDATION_FAILED } } if ( (Z_STRLEN_P(value) >= 9 && !strncasecmp("2001:0db8", Z_STRVAL_P(value), 9)) || (Z_STRLEN_P(value) >= 2 && !strncasecmp("5f", Z_STRVAL_P(value), 2)) || (Z_STRLEN_P(value) >= 4 && !strncasecmp("3ff3", Z_STRVAL_P(value), 4)) || (Z_STRLEN_P(value) >= 8 && !strncasecmp("2001:001", Z_STRVAL_P(value), 8)) ) { RETURN_VALIDATION_FAILED } } } } break; } } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
483832.c
/* * Copyright (c) 2013 Red Hat Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or * other materials provided with the distribution. * * The names of contributors to this software may not be * used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * Author: Stef Walter <[email protected]> */ #include "config.h" #include "test.h" #include <stdlib.h> static void test_success (void) { /* Yup, nothing */ } static void test_failure (void) { if (getenv ("TEST_FAIL")) { p11_test_fail (__FILE__, __LINE__, __FUNCTION__, "Unconditional test failure due to TEST_FAIL environment variable"); } } static void test_memory (void) { char *mem; if (getenv ("TEST_FAIL")) { mem = malloc (1); assert (mem != NULL); free (mem); /* cppcheck-suppress deallocuse */ *mem = 1; } } static void test_leak (void) { char *mem; if (getenv ("TEST_FAIL")) { mem = malloc (1); assert (mem != NULL); *mem = 1; } /* cppcheck-suppress memleak */ } int main (int argc, char *argv[]) { p11_test (test_success, "/test/success"); if (getenv ("TEST_FAIL")) { p11_test (test_failure, "/test/failure"); p11_test (test_memory, "/test/memory"); p11_test (test_leak, "/test/leak"); } return p11_test_run (argc, argv); }
52075.c
#include "ADF4351.h" u8 buf[4]; //д��32���ֽ� void ADF4351_Write(u32 adf_dat) { u8 i; CLR_LE(); for (i = 0; i < 32; i++) { if ((adf_dat & 0x80000000) == 0x80000000) SET_DATA(); else CLR_DATA(); CLR_SCL(); SET_SCL(); CLR_SCL(); adf_dat <<= 1; } SET_LE(); delay(1); CLR_LE(); } void delay (int length) { int i; i = length * 200 ; while (i >0) i--; } void ADF4351_Initiate(void) { GPIO_InitTypeDef GPIO_InitStructure; RCC_AHB1PeriphClockCmd( RCC_AHB1Periph_GPIOB, ENABLE); ; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12|GPIO_Pin_13|GPIO_Pin_14|GPIO_Pin_15; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP ; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_Init(GPIOB, &GPIO_InitStructure); SET_CE(); // GPIO_ResetBits(GPIOB, GPIO_Pin_1); //PDRF��Ϊ0 } //--------------------------------- //void WriteToADF4350(unsigned char count,unsigned char *buf); //--------------------------------- //Function that writes to the ADF4350 via the SPI port. //-------------------------------------------------------------------------------- void WriteToADF4350(unsigned char count, unsigned char *buf) { unsigned char ValueToWrite = 0; unsigned char i = 0; unsigned char j = 0; delay(1); CLR_SCL(); CLR_LE(); delay(1); for(i=count;i>0;i--) { ValueToWrite = *(buf + i - 1); for(j=0; j<8; j++) { if(0x80 == (ValueToWrite & 0x80)) { SET_DATA(); //Send one to SDO pin } else { CLR_DATA(); //Send zero to SDO pin } delay(1); SET_SCL(); delay(1); ValueToWrite <<= 1; //Rotate data CLR_SCL(); } } CLR_DATA(); delay(1); SET_LE(); delay(1); CLR_LE(); } //--------------------------------- //void ReadFromADF4350(unsigned char count,unsigned char *buf) //--------------------------------- //Function that reads from the ADF4350 via the SPI port. //-------------------------------------------------------------------------------- void ReadFromADF4350(unsigned char count, unsigned char *buf) { unsigned char i = 0; unsigned char j = 0; unsigned int iTemp = 0; unsigned char RotateData = 0; delay(1); CLR_SCL(); CLR_LE(); delay(1); for(j=count; j>0; j--) { for(i=0; i<8; i++) { RotateData <<= 1; //Rotate data delay(1); // iTemp = GP4DAT; //Read DATA of ADF4350 SET_SCL(); if(0x00000020 == (iTemp & 0x00000020)) { RotateData |= 1; } delay(1); CLR_SCL(); } *(buf + j - 1)= RotateData; } delay(1); SET_LE(); delay(1); CLR_LE(); } void gpsL1() { ADF4351_Write(0x580005); ADF4351_Write(0x9A003C); ADF4351_Write(0x4B3); ADF4351_Write(0x14E42); ADF4351_Write(0x8008191); ADF4351_Write(0x4E80D8); } void F35(){ u8 buf[4] = {0,0,0,0}; buf[3] = 0x00; //�˴����ù̶�����35M buf[2] = 0x58; buf[1] = 0x00; //write communication register 0x00580005 to control the progress buf[0] = 0x05; //to write Register 5 to set digital lock detector WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0xec; //(DB23=1)The signal is taken from the VCO directly;(DB22-20:4H)the RF divider is 16;(DB19-12:50H)R is 80 buf[1] = 0x80; //(DB11=0)VCO powerd up; buf[0] = 0x3C; //(DB5=1)RF output is enabled;(DB4-3=3H)Output power level is 5 WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; buf[1] = 0x04; //(DB14-3:96H)clock divider value is 150. buf[0] = 0xB3; WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x01; //(DB6=1)set PD polarity is positive;(DB7=1)LDP is 6nS; buf[1] = 0x0E; //(DB8=0)enable fractional-N digital lock detect; buf[0] = 0x42; //(DB12-9:7H)set Icp 2.50 mA; WriteToADF4350(4,buf); //(DB23-14:1H)R counter is 1 buf[3] = 0x00; buf[2] = 0x00; buf[1] = 0x80; //(DB14-3:6H)MOD counter is 6; buf[0] = 0x29; //(DB26-15:6H)PHASE word is 1,neither the phase resync WriteToADF4350(4,buf); //nor the spurious optimization functions are being used //(DB27=1)prescaler value is 8/9 buf[3] = 0x00; buf[2] = 0x2c; buf[1] = 0x80; buf[0] = 0x18; //(DB14-3:0H)FRAC value is 0; WriteToADF4350(4,buf); //(DB30-15:140H)INT value is 320; } void Frequency_100MHz(void) { buf[3] = 0x00; buf[2] = 0x58; buf[1] = 0x00; //write communication register 0x00580005 to control the progress buf[0] = 0x05; //to write Register 5 to set digital lock detector WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0xDC; //(DB23=1)The signal is taken from the VCO directly;(DB22-20:4H)the RF divider is 16;(DB19-12:50H)R is 80 buf[1] = 0x80; //(DB11=0)VCO powerd up; buf[0] = 0x3C; //(DB5=1)RF output is enabled;(DB4-3=3H)Output power level is 5 WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; buf[1] = 0x04; //(DB14-3:96H)clock divider value is 150. buf[0] = 0xB3; WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; //(DB6=1)set PD polarity is positive;(DB7=1)LDP is 6nS; buf[1] = 0x4E; //(DB8=0)enable fractional-N digital lock detect; buf[0] = 0x42; //(DB12-9:7H)set Icp 2.50 mA; WriteToADF4350(4,buf); //(DB23-14:1H)R counter is 1 buf[3] = 0x08; buf[2] = 0x00; buf[1] = 0x80; //(DB14-3:6H)MOD counter is 6; buf[0] = 0x11; //(DB26-15:6H)PHASE word is 1,neither the phase resync WriteToADF4350(4,buf); //nor the spurious optimization functions are being used //(DB27=1)prescaler value is 8/9 buf[3] = 0x00; buf[2] = 0x40; buf[1] = 0x00; buf[0] = 0x00; //(DB14-3:0H)FRAC value is 0; WriteToADF4350(4,buf); //(DB30-15:140H)INT value is 320; } void Frequency_200MHz(void) { buf[3] = 0x00; buf[2] = 0x58; buf[1] = 0x00; //write communication register 0x00580005 to control the progress buf[0] = 0x05; //to write Register 5 to set digital lock detector WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0xCC; //(DB23=1)The signal is taken from the VCO directly;(DB22-20:4H)the RF divider is 16;(DB19-12:50H)R is 80 buf[1] = 0x80; //(DB11=0)VCO powerd up; buf[0] = 0x3C; //(DB5=1)RF output is enabled;(DB4-3=3H)Output power level is 5 WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; buf[1] = 0x04; //(DB14-3:96H)clock divider value is 150. buf[0] = 0xB3; WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; //(DB6=1)set PD polarity is positive;(DB7=1)LDP is 6nS; buf[1] = 0x4E; //(DB8=0)enable fractional-N digital lock detect; buf[0] = 0x42; //(DB12-9:7H)set Icp 2.50 mA; WriteToADF4350(4,buf); //(DB23-14:1H)R counter is 1 buf[3] = 0x08; buf[2] = 0x00; buf[1] = 0x80; //(DB14-3:6H)MOD counter is 6; buf[0] = 0x11; //(DB26-15:6H)PHASE word is 1,neither the phase resync WriteToADF4350(4,buf); //nor the spurious optimization functions are being used //(DB27=1)prescaler value is 8/9 buf[3] = 0x00; buf[2] = 0x40; buf[1] = 0x00; buf[0] = 0x00; //(DB14-3:0H)FRAC value is 0; WriteToADF4350(4,buf); //(DB30-15:140H)INT value is 320; } void Frequency_300MHz(void) { buf[3] = 0x00; buf[2] = 0x58; buf[1] = 0x00; //write communication register 0x00580005 to control the progress buf[0] = 0x05; //to write Register 5 to set digital lock detector WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0xBC; //(DB23=1)The signal is taken from the VCO directly;(DB22-20:4H)the RF divider is 16;(DB19-12:50H)R is 80 buf[1] = 0x80; //(DB11=0)VCO powerd up; buf[0] = 0x3C; //(DB5=1)RF output is enabled;(DB4-3=3H)Output power level is 5 WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; buf[1] = 0x04; //(DB14-3:96H)clock divider value is 150. buf[0] = 0xB3; WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; //(DB6=1)set PD polarity is positive;(DB7=1)LDP is 6nS; buf[1] = 0x4E; //(DB8=0)enable fractional-N digital lock detect; buf[0] = 0x42; //(DB12-9:7H)set Icp 2.50 mA; WriteToADF4350(4,buf); //(DB23-14:1H)R counter is 1 buf[3] = 0x08; buf[2] = 0x00; buf[1] = 0x80; //(DB14-3:6H)MOD counter is 6; buf[0] = 0x11; //(DB26-15:6H)PHASE word is 1,neither the phase resync WriteToADF4350(4,buf); //nor the spurious optimization functions are being used //(DB27=1)prescaler value is 8/9 buf[3] = 0x00; buf[2] = 0x30; buf[1] = 0x00; buf[0] = 0x00; //(DB14-3:0H)FRAC value is 0; WriteToADF4350(4,buf); //(DB30-15:140H)INT value is 320; } void Frequency_400MHz(void) { buf[3] = 0x00; buf[2] = 0x58; buf[1] = 0x00; //write communication register 0x00580005 to control the progress buf[0] = 0x05; //to write Register 5 to set digital lock detector WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0xBC; //(DB23=1)The signal is taken from the VCO directly;(DB22-20:4H)the RF divider is 16;(DB19-12:50H)R is 80 buf[1] = 0x80; //(DB11=0)VCO powerd up; buf[0] = 0x3C; //(DB5=1)RF output is enabled;(DB4-3=3H)Output power level is 5 WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; buf[1] = 0x04; //(DB14-3:96H)clock divider value is 150. buf[0] = 0xB3; WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; //(DB6=1)set PD polarity is positive;(DB7=1)LDP is 6nS; buf[1] = 0x4E; //(DB8=0)enable fractional-N digital lock detect; buf[0] = 0x42; //(DB12-9:7H)set Icp 2.50 mA; WriteToADF4350(4,buf); //(DB23-14:1H)R counter is 1 buf[3] = 0x08; buf[2] = 0x00; buf[1] = 0x80; //(DB14-3:6H)MOD counter is 6; buf[0] = 0x11; //(DB26-15:6H)PHASE word is 1,neither the phase resync WriteToADF4350(4,buf); //nor the spurious optimization functions are being used //(DB27=1)prescaler value is 8/9 buf[3] = 0x00; buf[2] = 0x40; buf[1] = 0x00; buf[0] = 0x00; //(DB14-3:0H)FRAC value is 0; WriteToADF4350(4,buf); //(DB30-15:140H)INT value is 320; } void Frequency_500MHz(void) { buf[3] = 0x00; buf[2] = 0x58; buf[1] = 0x00; //write communication register 0x00580005 to control the progress buf[0] = 0x05; //to write Register 5 to set digital lock detector WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0xCC; //(DB23=1)The signal is taken from the VCO directly;(DB22-20:4H)the RF divider is 16;(DB19-12:50H)R is 80 buf[1] = 0x80; //(DB11=0)VCO powerd up; buf[0] = 0x3C; //(DB5=1)RF output is enabled;(DB4-3=3H)Output power level is 5 WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; buf[1] = 0x04; //(DB14-3:96H)clock divider value is 150. buf[0] = 0xB3; WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; //(DB6=1)set PD polarity is positive;(DB7=1)LDP is 6nS; buf[1] = 0x4E; //(DB8=0)enable fractional-N digital lock detect; buf[0] = 0x42; //(DB12-9:7H)set Icp 2.50 mA; WriteToADF4350(4,buf); //(DB23-14:1H)R counter is 1 buf[3] = 0x08; buf[2] = 0x00; buf[1] = 0x80; //(DB14-3:6H)MOD counter is 6; buf[0] = 0x11; //(DB26-15:6H)PHASE word is 1,neither the phase resync WriteToADF4350(4,buf); //nor the spurious optimization functions are being used //(DB27=1)prescaler value is 8/9 buf[3] = 0x00; buf[2] = 0x50; buf[1] = 0x00; buf[0] = 0x00; //(DB14-3:0H)FRAC value is 0; WriteToADF4350(4,buf); //(DB30-15:140H)INT value is 320; } void Frequency_600MHz(void) { buf[3] = 0x00; buf[2] = 0x58; buf[1] = 0x00; //write communication register 0x00580005 to control the progress buf[0] = 0x05; //to write Register 5 to set digital lock detector WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0xAC; //(DB23=1)The signal is taken from the VCO directly;(DB22-20:4H)the RF divider is 16;(DB19-12:50H)R is 80 buf[1] = 0x80; //(DB11=0)VCO powerd up; buf[0] = 0x3C; //(DB5=1)RF output is enabled;(DB4-3=3H)Output power level is 5 WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; buf[1] = 0x04; //(DB14-3:96H)clock divider value is 150. buf[0] = 0xB3; WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; //(DB6=1)set PD polarity is positive;(DB7=1)LDP is 6nS; buf[1] = 0x4E; //(DB8=0)enable fractional-N digital lock detect; buf[0] = 0x42; //(DB12-9:7H)set Icp 2.50 mA; WriteToADF4350(4,buf); //(DB23-14:1H)R counter is 1 buf[3] = 0x08; buf[2] = 0x00; buf[1] = 0x80; //(DB14-3:6H)MOD counter is 6; buf[0] = 0x11; //(DB26-15:6H)PHASE word is 1,neither the phase resync WriteToADF4350(4,buf); //nor the spurious optimization functions are being used //(DB27=1)prescaler value is 8/9 buf[3] = 0x00; buf[2] = 0x30; buf[1] = 0x00; buf[0] = 0x00; //(DB14-3:0H)FRAC value is 0; WriteToADF4350(4,buf); //(DB30-15:140H)INT value is 320; } void Frequency_700MHz(void) { buf[3] = 0x00; buf[2] = 0x58; buf[1] = 0x00; //write communication register 0x00580005 to control the progress buf[0] = 0x05; //to write Register 5 to set digital lock detector WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0xAC; //(DB23=1)The signal is taken from the VCO directly;(DB22-20:4H)the RF divider is 16;(DB19-12:50H)R is 80 buf[1] = 0x80; //(DB11=0)VCO powerd up; buf[0] = 0x3C; //(DB5=1)RF output is enabled;(DB4-3=3H)Output power level is 5 WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; buf[1] = 0x04; //(DB14-3:96H)clock divider value is 150. buf[0] = 0xB3; WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; //(DB6=1)set PD polarity is positive;(DB7=1)LDP is 6nS; buf[1] = 0x4E; //(DB8=0)enable fractional-N digital lock detect; buf[0] = 0x42; //(DB12-9:7H)set Icp 2.50 mA; WriteToADF4350(4,buf); //(DB23-14:1H)R counter is 1 buf[3] = 0x08; buf[2] = 0x00; buf[1] = 0x80; //(DB14-3:6H)MOD counter is 6; buf[0] = 0x11; //(DB26-15:6H)PHASE word is 1,neither the phase resync WriteToADF4350(4,buf); //nor the spurious optimization functions are being used //(DB27=1)prescaler value is 8/9 buf[3] = 0x00; buf[2] = 0x38; buf[1] = 0x00; buf[0] = 0x00; //(DB14-3:0H)FRAC value is 0; WriteToADF4350(4,buf); //(DB30-15:140H)INT value is 320; } void Frequency_800MHz(void) { buf[3] = 0x00; buf[2] = 0x58; buf[1] = 0x00; //write communication register 0x00580005 to control the progress buf[0] = 0x05; //to write Register 5 to set digital lock detector WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0xAC; //(DB23=1)The signal is taken from the VCO directly;(DB22-20:4H)the RF divider is 16;(DB19-12:50H)R is 80 buf[1] = 0x80; //(DB11=0)VCO powerd up; buf[0] = 0x3C; //(DB5=1)RF output is enabled;(DB4-3=3H)Output power level is 5 WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; buf[1] = 0x04; //(DB14-3:96H)clock divider value is 150. buf[0] = 0xB3; WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; //(DB6=1)set PD polarity is positive;(DB7=1)LDP is 6nS; buf[1] = 0x4E; //(DB8=0)enable fractional-N digital lock detect; buf[0] = 0x42; //(DB12-9:7H)set Icp 2.50 mA; WriteToADF4350(4,buf); //(DB23-14:1H)R counter is 1 buf[3] = 0x08; buf[2] = 0x00; buf[1] = 0x80; //(DB14-3:6H)MOD counter is 6; buf[0] = 0x11; //(DB26-15:6H)PHASE word is 1,neither the phase resync WriteToADF4350(4,buf); //nor the spurious optimization functions are being used //(DB27=1)prescaler value is 8/9 buf[3] = 0x00; buf[2] = 0x40; buf[1] = 0x00; buf[0] = 0x00; //(DB14-3:0H)FRAC value is 0; WriteToADF4350(4,buf); //(DB30-15:140H)INT value is 320; } void Frequency_900MHz(void) { buf[3] = 0x00; buf[2] = 0x58; buf[1] = 0x00; //write communication register 0x00580005 to control the progress buf[0] = 0x05; //to write Register 5 to set digital lock detector WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0xAC; //(DB23=1)The signal is taken from the VCO directly;(DB22-20:4H)the RF divider is 16;(DB19-12:50H)R is 80 buf[1] = 0x80; //(DB11=0)VCO powerd up; buf[0] = 0x3C; //(DB5=1)RF output is enabled;(DB4-3=3H)Output power level is 5 WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; buf[1] = 0x04; //(DB14-3:96H)clock divider value is 150. buf[0] = 0xB3; WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; //(DB6=1)set PD polarity is positive;(DB7=1)LDP is 6nS; buf[1] = 0x4E; //(DB8=0)enable fractional-N digital lock detect; buf[0] = 0x42; //(DB12-9:7H)set Icp 2.50 mA; WriteToADF4350(4,buf); //(DB23-14:1H)R counter is 1 buf[3] = 0x08; buf[2] = 0x00; buf[1] = 0x80; //(DB14-3:6H)MOD counter is 6; buf[0] = 0x11; //(DB26-15:6H)PHASE word is 1,neither the phase resync WriteToADF4350(4,buf); //nor the spurious optimization functions are being used //(DB27=1)prescaler value is 8/9 buf[3] = 0x00; buf[2] = 0x48; buf[1] = 0x00; buf[0] = 0x00; //(DB14-3:0H)FRAC value is 0; WriteToADF4350(4,buf); //(DB30-15:140H)INT value is 320; } void Frequency_35MHz(void) { buf[3] = 0x00; buf[2] = 0x58; buf[1] = 0x00; //write communication register 0x00580005 to control the progress buf[0] = 0x05; //to write Register 5 to set digital lock detector WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0xDc; //EC //(DB23=1)The signal is taken from the VCO directly;(DB22-20:6H)the RF divider is 64;(DB19-12:50H)R is 80 buf[1] = 0x80; //(DB11=0)VCO powerd up; buf[0] = 0x3C; //(DB5=1)RF output is enabled;(DB4-3=3H)Output power level is 5 WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; buf[1] = 0x04; //(DB14-3:96H)clock divider value is 150. buf[0] = 0xB3; WriteToADF4350(4,buf); buf[3] = 0x00; buf[2] = 0x00; //(DB6=1)set PD polarity is positive;(DB7=1)LDP is 6nS; buf[1] = 0x4E; //(DB8=0)enable fractional-N digital lock detect; buf[0] = 0x42; //(DB12-9:7H)set Icp 2.50 mA; WriteToADF4350(4,buf); //(DB23-14:1H)R counter is 1 buf[3] = 0x08; buf[2] = 0x00; buf[1] = 0x80; //(DB14-3:6H)MOD counter is 6; buf[0] = 0x29; //(DB26-15:6H)PHASE word is 1,neither the phase resync WriteToADF4350(4,buf); //nor the spurious optimization functions are being used //(DB27=1)prescaler value is 8/9 buf[3] = 0x00; buf[2] = 0x2C; buf[1] = 0x80; buf[0] = 0x18; //(DB14-3:0H)FRAC value is 0; WriteToADF4350(4,buf); //(DB30-15:140H)INT value is 320; } /*-------------------------------------200MHz--------------------------------------------- Reference frequency: 20MHz;Output frequency: 200MHz;VCO frequency: 3200MHz;Prescaler: 8/9; RF divider: 16;VCO channel spacing frequency: 200KHz;PFD frequency: 10MHz; INT: 320;FRAC: 0;MOD: 100;R: 1;Lock Clk Div: 6; bank clk div: 200; Phase: 1 ----------------------------------------------------------------------------------------*/ /*RFout = [INT + (FRAC/MOD)] * (Fpfd/RF Divider)*/ /*Fpfd = REFIN * [(1 + D)/(R * (1 + T))]*/ /*Fvco = RF divider * Output frequency 2.2G-4.4G*/ void ADF_SetFre(void){ u32 adf_data; u16 adf_R=1; //RF�ο���Ƶϵ�� u8 adf_D=0; //RF REFin��Ƶ��λ(0 or 1) u8 adf_T=0; //�ο�����Ƶλ,����ռ�ձ�50%,�������� u16 adf_Locktime=160; u16 adf_MOD=6; u16 adf_INT=320; u16 adf_FARC=0; u16 adf_PHASE=1; u16 adf_RFDiv=RF_div16; u8 pinduan; CLR_SCL(); CLR_LE(); //���üĴ���5 adf_data = 0x00580000; //�������� LD���ŵĹ�����ʽΪ�������� D23 D22=01 adf_data =adf_data | ADF_R5; ADF4351_Write(adf_data); //���üĴ���4 adf_data = 0x00800038; /*(DB23=1)The signal is taken from the VCO directly,�ź�ֱ�Ӵ�VCO���� ���޸�RF divider, R��ֵ(DB22-20)the RF divider is 16; (DB11=0)VCO powerd up; ����RF��������; Ƶ��ѡ��ʱ��,��Ƶ��125k, ��Ƶֵ160*/ adf_data = adf_data | (adf_RFDiv << 20); //RF divider is 16 adf_data = adf_data | (160 << 12); //Ƶ��ѡ��ʱ�� adf_data = adf_data | ADF_R4; //(DB5=1)RF output is enabled;(DB4-3=3H)Output power level is 5dBm ADF4351_Write(adf_data); //���üĴ���3 adf_data = 0x00848000; /*ѡ����Ƶ�Σ�D23=1��, APB6ns(D22=0,=����С����Ƶʹ��),,(D21=0,С����Ƶʹ��) ʹ��CSR(D18=1),(D16 D15=01)�������� ���޸�clock divider value��ֵ*/ adf_data = adf_data | (adf_Locktime << 3); adf_data = adf_data | ADF_R3; ADF4351_Write(adf_data); //���üĴ���2 adf_data = 0x61002040; //����ɢ����, ���òο���Ƶ, ����Ƶ������ʹ��(������������) //ʹ��˫������, ���õ��ɰ�����0.31, С��N��Ƶ(40), ����R��Ƶ����ֵΪ1 //���ü������ļ���, (DB6)ͬ���˲���1,�����˲���0,������ͬ���˲��� adf_data = adf_data | (adf_D << 25); adf_data = adf_data | (adf_T << 24); adf_data = adf_data | (adf_R << 14); adf_data = adf_data | ADF_R2; ADF4351_Write(adf_data); //���üĴ���1 adf_data = 0x01008000; //������λ����,Ԥ��Ƶ����ֵΪ8/9 //��λ��Ϊ1 adf_data = adf_data | (adf_PHASE << 15); adf_data = adf_data | (adf_MOD << 3); adf_data = adf_data | ADF_R1; ADF4351_Write(adf_data); //���üĴ���0 adf_data = 0x00000000; adf_data = adf_data | (adf_INT << 15); adf_data = adf_data | (adf_FARC << 3); adf_data= adf_data | ADF_R0; ADF4351_Write(adf_data); } // // /********************************************************** // �����Ƽ� // ���������������뵽�Ա��꣬�������ӽ߳�Ϊ������ ^_^ // https://kvdz.taobao.com/ // **********************************************************/ // // #include "ADF4351.h" // #include "stm32f4xx.h" // // void delay_us(uint32_t u) // { // for(int i=u;i--;i>0) // { // for(int q=168;q--;q>0); // } // } // // void ADF_Output_GPIOInit(void) // { // GPIO_InitTypeDef GPIO_InitStructure; // // RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE); // // GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12|GPIO_Pin_13|GPIO_Pin_14|GPIO_Pin_15; // GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; // GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; // GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP ; // GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; // GPIO_Init(GPIOB, &GPIO_InitStructure); // } // // void delay (int length) // { // while (length >0) // length--; // } // // void WriteToADF4351(uint8_t count, uint8_t *buf) // { // uint8_t ValueToWrite = 0; // uint8_t i = 0; // uint8_t j = 0; // // // ADF_Output_GPIOInit(); // // ADF4351_CE_SET; // delay_us(1); // ADF4351_CLK_RESET; // ADF4351_LE_RESET; // delay_us(1); // // for(i = count; i>0; i--) // { // ValueToWrite = *(buf+i-1); // for(j=0; j<8; j++) // { // if(0x80 == (ValueToWrite & 0x80)) // { // ADF4351_OUTPUT_DATA_SET; // } // else // { // ADF4351_OUTPUT_DATA_RESET; // } // delay_us(1); // ADF4351_CLK_SET; // delay_us(1); // ValueToWrite <<= 1; // ADF4351_CLK_RESET; // } // } // ADF4351_OUTPUT_DATA_RESET; // delay_us(1); // ADF4351_LE_SET; // delay_us(1); // ADF4351_LE_RESET; // } // // void ADF4351Init(void) // { // uint8_t buf[4] = {0,0,0,0}; // // ADF_Output_GPIOInit(); // // buf[3] = 0x00; //�˴����ù̶�����35M // buf[2] = 0x58; // buf[1] = 0x00; //write communication register 0x00580005 to control the progress // buf[0] = 0x05; //to write Register 5 to set digital lock detector // WriteToADF4351(4,buf); // // buf[3] = 0x00; // buf[2] = 0x9c; //(DB23=1)The signal is taken from the VCO directly;(DB22-20:4H)the RF divider is 2;(DB19-12:50H)R is 80 // buf[1] = 0x80; //(DB11=0)VCO powerd up; // buf[0] = 0x3C; //(DB5=1)RF output is enabled;(DB4-3=3H)Output power level is 5 // WriteToADF4351(4,buf); // // buf[3] = 0x00; // buf[2] = 0x00; // buf[1] = 0x04; //(DB14-3:96H)clock divider value is 150. // buf[0] = 0xB3; // WriteToADF4351(4,buf); // // buf[3] = 0x00; // buf[2] = 0x01; //(DB6=1)set PD polarity is positive;(DB7=1)LDP is 6nS; // buf[1] = 0x4E; //(DB8=0)enable fractional-N digital lock detect; // buf[0] = 0x42; //(DB12-9:7H)set Icp 2.50 mA; // WriteToADF4351(4,buf); //(DB23-14:1H)R counter is 1 // // buf[3] = 0x00; // buf[2] = 0x00; // buf[1] = 0x81; //(DB14-3:6H)MOD counter is 50; // buf[0] = 0x91; //(DB26-15:6H)PHASE word is 1,neither the phase resync // WriteToADF4351(4,buf); //nor the spurious optimization functions are being used // //(DB27=1)prescaler value is 8/9 // // buf[3] = 0x00; // buf[2] = 0x4e; // buf[1] = 0x80; // buf[0] = 0xdb; //(DB14-3:0H)FRAC value is 27; // WriteToADF4351(4,buf); //(DB30-15:140H)INT value is 157; // }
784499.c
#include "red_black_tree.h" #include <assert.h> /***********************************************************************/ /* FUNCTION: RBTreeCreate */ /**/ /* INPUTS: All the inputs are names of functions. CompFunc takes two */ /* void pointers to keys and returns 1 if the first arguement is */ /* "greater than" the second. DestFunc takes a pointer to a key and */ /* destroys it in the appropriate manner when the node containing that */ /* key is deleted. InfoDestFunc is similiar to DestFunc except it */ /* recieves a pointer to the info of a node and destroys it. */ /* PrintFunc recieves a pointer to the key of a node and prints it. */ /* PrintInfo recieves a pointer to the info of a node and prints it. */ /* If RBTreePrint is never called the print functions don't have to be */ /* defined and NullFunction can be used. */ /**/ /* OUTPUT: This function returns a pointer to the newly created */ /* red-black tree. */ /**/ /* Modifies Input: none */ /***********************************************************************/ rb_red_blk_tree* RBTreeCreate( int (*CompFunc) (const void*,const void*), void (*DestFunc) (void*), void (*InfoDestFunc) (void*), void (*PrintFunc) (const void*), void (*PrintInfo)(void*)) { rb_red_blk_tree* newTree; rb_red_blk_node* temp; newTree=(rb_red_blk_tree*) SafeMalloc(sizeof(rb_red_blk_tree)); newTree->Compare= CompFunc; newTree->DestroyKey= DestFunc; newTree->PrintKey= PrintFunc; newTree->PrintInfo= PrintInfo; newTree->DestroyInfo= InfoDestFunc; /* see the comment in the rb_red_blk_tree structure in red_black_tree.h */ /* for information on nil and root */ temp=newTree->nil= (rb_red_blk_node*) SafeMalloc(sizeof(rb_red_blk_node)); temp->parent=temp->left=temp->right=temp; temp->red=0; temp->key=0; temp=newTree->root= (rb_red_blk_node*) SafeMalloc(sizeof(rb_red_blk_node)); temp->parent=temp->left=temp->right=newTree->nil; temp->key=0; temp->red=0; return(newTree); } /***********************************************************************/ /* FUNCTION: LeftRotate */ /**/ /* INPUTS: This takes a tree so that it can access the appropriate */ /* root and nil pointers, and the node to rotate on. */ /**/ /* OUTPUT: None */ /**/ /* Modifies Input: tree, x */ /**/ /* EFFECTS: Rotates as described in _Introduction_To_Algorithms by */ /* Cormen, Leiserson, Rivest (Chapter 14). Basically this */ /* makes the parent of x be to the left of x, x the parent of */ /* its parent before the rotation and fixes other pointers */ /* accordingly. */ /***********************************************************************/ void LeftRotate(rb_red_blk_tree* tree, rb_red_blk_node* x) { rb_red_blk_node* y; rb_red_blk_node* nil=tree->nil; /* I originally wrote this function to use the sentinel for */ /* nil to avoid checking for nil. However this introduces a */ /* very subtle bug because sometimes this function modifies */ /* the parent pointer of nil. This can be a problem if a */ /* function which calls LeftRotate also uses the nil sentinel */ /* and expects the nil sentinel's parent pointer to be unchanged */ /* after calling this function. For example, when RBDeleteFixUP */ /* calls LeftRotate it expects the parent pointer of nil to be */ /* unchanged. */ y=x->right; x->right=y->left; if (y->left != nil) y->left->parent=x; /* used to use sentinel here */ /* and do an unconditional assignment instead of testing for nil */ y->parent=x->parent; /* instead of checking if x->parent is the root as in the book, we */ /* count on the root sentinel to implicitly take care of this case */ if( x == x->parent->left) { x->parent->left=y; } else { x->parent->right=y; } y->left=x; x->parent=y; #ifdef DEBUG_ASSERT Assert(!tree->nil->red,"nil not red in LeftRotate"); #endif } /***********************************************************************/ /* FUNCTION: RightRotate */ /**/ /* INPUTS: This takes a tree so that it can access the appropriate */ /* root and nil pointers, and the node to rotate on. */ /**/ /* OUTPUT: None */ /**/ /* Modifies Input?: tree, y */ /**/ /* EFFECTS: Rotates as described in _Introduction_To_Algorithms by */ /* Cormen, Leiserson, Rivest (Chapter 14). Basically this */ /* makes the parent of x be to the left of x, x the parent of */ /* its parent before the rotation and fixes other pointers */ /* accordingly. */ /***********************************************************************/ void RightRotate(rb_red_blk_tree* tree, rb_red_blk_node* y) { rb_red_blk_node* x; rb_red_blk_node* nil=tree->nil; /* I originally wrote this function to use the sentinel for */ /* nil to avoid checking for nil. However this introduces a */ /* very subtle bug because sometimes this function modifies */ /* the parent pointer of nil. This can be a problem if a */ /* function which calls LeftRotate also uses the nil sentinel */ /* and expects the nil sentinel's parent pointer to be unchanged */ /* after calling this function. For example, when RBDeleteFixUP */ /* calls LeftRotate it expects the parent pointer of nil to be */ /* unchanged. */ x=y->left; y->left=x->right; if (nil != x->right) x->right->parent=y; /*used to use sentinel here */ /* and do an unconditional assignment instead of testing for nil */ /* instead of checking if x->parent is the root as in the book, we */ /* count on the root sentinel to implicitly take care of this case */ x->parent=y->parent; if( y == y->parent->left) { y->parent->left=x; } else { y->parent->right=x; } x->right=y; y->parent=x; #ifdef DEBUG_ASSERT Assert(!tree->nil->red,"nil not red in RightRotate"); #endif } /***********************************************************************/ /* FUNCTION: TreeInsertHelp */ /**/ /* INPUTS: tree is the tree to insert into and z is the node to insert */ /**/ /* OUTPUT: none */ /**/ /* Modifies Input: tree, z */ /**/ /* EFFECTS: Inserts z into the tree as if it were a regular binary tree */ /* using the algorithm described in _Introduction_To_Algorithms_ */ /* by Cormen et al. This funciton is only intended to be called */ /* by the RBTreeInsert function and not by the user */ /***********************************************************************/ void TreeInsertHelp(rb_red_blk_tree* tree, rb_red_blk_node* z) { /* This function should only be called by InsertRBTree (see above) */ rb_red_blk_node* x; rb_red_blk_node* y; rb_red_blk_node* nil=tree->nil; z->left=z->right=nil; y=tree->root; x=tree->root->left; while( x != nil) { y=x; if (1 == tree->Compare(x->key,z->key)) { /* x.key > z.key */ x=x->left; } else { /* x,key <= z.key */ x=x->right; } } z->parent=y; if ( (y == tree->root) || (1 == tree->Compare(y->key,z->key))) { /* y.key > z.key */ y->left=z; } else { y->right=z; } #ifdef DEBUG_ASSERT Assert(!tree->nil->red,"nil not red in TreeInsertHelp"); #endif } /* Before calling Insert RBTree the node x should have its key set */ /***********************************************************************/ /* FUNCTION: RBTreeInsert */ /**/ /* INPUTS: tree is the red-black tree to insert a node which has a key */ /* pointed to by key and info pointed to by info. */ /**/ /* OUTPUT: This function returns a pointer to the newly inserted node */ /* which is guarunteed to be valid until this node is deleted. */ /* What this means is if another data structure stores this */ /* pointer then the tree does not need to be searched when this */ /* is to be deleted. */ /**/ /* Modifies Input: tree */ /**/ /* EFFECTS: Creates a node node which contains the appropriate key and */ /* info pointers and inserts it into the tree. */ /***********************************************************************/ rb_red_blk_node * RBTreeInsert(rb_red_blk_tree* tree, void* key, void* info) { rb_red_blk_node * y; rb_red_blk_node * x; rb_red_blk_node * newNode; x=(rb_red_blk_node*) SafeMalloc(sizeof(rb_red_blk_node)); x->key=key; x->info=info; TreeInsertHelp(tree,x); newNode=x; x->red=1; while(x->parent->red) { /* use sentinel instead of checking for root */ if (x->parent == x->parent->parent->left) { y=x->parent->parent->right; if (y->red) { x->parent->red=0; y->red=0; x->parent->parent->red=1; x=x->parent->parent; } else { if (x == x->parent->right) { x=x->parent; LeftRotate(tree,x); } x->parent->red=0; x->parent->parent->red=1; RightRotate(tree,x->parent->parent); } } else { /* case for x->parent == x->parent->parent->right */ y=x->parent->parent->left; if (y->red) { x->parent->red=0; y->red=0; x->parent->parent->red=1; x=x->parent->parent; } else { if (x == x->parent->left) { x=x->parent; RightRotate(tree,x); } x->parent->red=0; x->parent->parent->red=1; LeftRotate(tree,x->parent->parent); } } } tree->root->left->red=0; return(newNode); #ifdef DEBUG_ASSERT Assert(!tree->nil->red,"nil not red in RBTreeInsert"); Assert(!tree->root->red,"root not red in RBTreeInsert"); #endif } /***********************************************************************/ /* FUNCTION: TreeSuccessor */ /**/ /* INPUTS: tree is the tree in question, and x is the node we want the */ /* the successor of. */ /**/ /* OUTPUT: This function returns the successor of x or NULL if no */ /* successor exists. */ /**/ /* Modifies Input: none */ /**/ /* Note: uses the algorithm in _Introduction_To_Algorithms_ */ /***********************************************************************/ rb_red_blk_node* TreeSuccessor(rb_red_blk_tree* tree,rb_red_blk_node* x) { rb_red_blk_node* y; rb_red_blk_node* nil=tree->nil; rb_red_blk_node* root=tree->root; if (nil != (y = x->right)) { /* assignment to y is intentional */ while(y->left != nil) { /* returns the minium of the right subtree of x */ y=y->left; } return(y); } else { y=x->parent; while(x == y->right) { /* sentinel used instead of checking for nil */ x=y; y=y->parent; } if (y == root) return(nil); return(y); } } /***********************************************************************/ /* FUNCTION: Treepredecessor */ /**/ /* INPUTS: tree is the tree in question, and x is the node we want the */ /* the predecessor of. */ /**/ /* OUTPUT: This function returns the predecessor of x or NULL if no */ /* predecessor exists. */ /**/ /* Modifies Input: none */ /**/ /* Note: uses the algorithm in _Introduction_To_Algorithms_ */ /***********************************************************************/ rb_red_blk_node* TreePredecessor(rb_red_blk_tree* tree, rb_red_blk_node* x) { rb_red_blk_node* y; rb_red_blk_node* nil=tree->nil; rb_red_blk_node* root=tree->root; if (nil != (y = x->left)) { /* assignment to y is intentional */ while(y->right != nil) { /* returns the maximum of the left subtree of x */ y=y->right; } return(y); } else { y=x->parent; while(x == y->left) { if (y == root) return(nil); x=y; y=y->parent; } return(y); } } /***********************************************************************/ /* FUNCTION: InorderTreePrint */ /**/ /* INPUTS: tree is the tree to print and x is the current inorder node */ /**/ /* OUTPUT: none */ /**/ /* EFFECTS: This function recursively prints the nodes of the tree */ /* inorder using the PrintKey and PrintInfo functions. */ /**/ /* Modifies Input: none */ /**/ /* Note: This function should only be called from RBTreePrint */ /***********************************************************************/ void InorderTreePrint(rb_red_blk_tree* tree, rb_red_blk_node* x) { rb_red_blk_node* nil=tree->nil; rb_red_blk_node* root=tree->root; if (x != tree->nil) { InorderTreePrint(tree,x->left); printf("info="); tree->PrintInfo(x->info); printf(" key="); tree->PrintKey(x->key); printf(" l->key="); if( x->left == nil) printf("NULL"); else tree->PrintKey(x->left->key); printf(" r->key="); if( x->right == nil) printf("NULL"); else tree->PrintKey(x->right->key); printf(" p->key="); if( x->parent == root) printf("NULL"); else tree->PrintKey(x->parent->key); printf(" red=%i\n",x->red); InorderTreePrint(tree,x->right); } } /***********************************************************************/ /* FUNCTION: TreeDestHelper */ /**/ /* INPUTS: tree is the tree to destroy and x is the current node */ /**/ /* OUTPUT: none */ /**/ /* EFFECTS: This function recursively destroys the nodes of the tree */ /* postorder using the DestroyKey and DestroyInfo functions. */ /**/ /* Modifies Input: tree, x */ /**/ /* Note: This function should only be called by RBTreeDestroy */ /***********************************************************************/ void TreeDestHelper(rb_red_blk_tree* tree, rb_red_blk_node* x) { rb_red_blk_node* nil=tree->nil; if (x != nil) { TreeDestHelper(tree,x->left); TreeDestHelper(tree,x->right); tree->DestroyKey(x->key); tree->DestroyInfo(x->info); free(x); } } /***********************************************************************/ /* FUNCTION: RBTreeDestroy */ /**/ /* INPUTS: tree is the tree to destroy */ /**/ /* OUTPUT: none */ /**/ /* EFFECT: Destroys the key and frees memory */ /**/ /* Modifies Input: tree */ /**/ /***********************************************************************/ void RBTreeDestroy(rb_red_blk_tree* tree) { TreeDestHelper(tree,tree->root->left); free(tree->root); free(tree->nil); free(tree); } /***********************************************************************/ /* FUNCTION: RBTreePrint */ /**/ /* INPUTS: tree is the tree to print */ /**/ /* OUTPUT: none */ /**/ /* EFFECT: This function recursively prints the nodes of the tree */ /* inorder using the PrintKey and PrintInfo functions. */ /**/ /* Modifies Input: none */ /**/ /***********************************************************************/ void RBTreePrint(rb_red_blk_tree* tree) { InorderTreePrint(tree,tree->root->left); } /***********************************************************************/ /* FUNCTION: RBExactQuery */ /**/ /* INPUTS: tree is the tree to print and q is a pointer to the key */ /* we are searching for */ /**/ /* OUTPUT: returns the a node with key equal to q. If there are */ /* multiple nodes with key equal to q this function returns */ /* the one highest in the tree */ /**/ /* Modifies Input: none */ /**/ /***********************************************************************/ rb_red_blk_node* RBExactQuery(rb_red_blk_tree* tree, void* q) { rb_red_blk_node* x=tree->root->left; rb_red_blk_node* nil=tree->nil; int compVal; if (x == nil) return(0); compVal=tree->Compare(x->key,(int*) q); while(0 != compVal) {/*assignemnt*/ if (1 == compVal) { /* x->key > q */ x=x->left; } else { x=x->right; } if ( x == nil) return(0); compVal=tree->Compare(x->key,(int*) q); } return(x); } /***********************************************************************/ /* FUNCTION: RBDeleteFixUp */ /**/ /* INPUTS: tree is the tree to fix and x is the child of the spliced */ /* out node in RBTreeDelete. */ /**/ /* OUTPUT: none */ /**/ /* EFFECT: Performs rotations and changes colors to restore red-black */ /* properties after a node is deleted */ /**/ /* Modifies Input: tree, x */ /**/ /* The algorithm from this function is from _Introduction_To_Algorithms_ */ /***********************************************************************/ void RBDeleteFixUp(rb_red_blk_tree* tree, rb_red_blk_node* x) { rb_red_blk_node* root=tree->root->left; rb_red_blk_node* w; while( (!x->red) && (root != x)) { if (x == x->parent->left) { w=x->parent->right; if (w->red) { w->red=0; x->parent->red=1; LeftRotate(tree,x->parent); w=x->parent->right; } if ( (!w->right->red) && (!w->left->red) ) { w->red=1; x=x->parent; } else { if (!w->right->red) { w->left->red=0; w->red=1; RightRotate(tree,w); w=x->parent->right; } w->red=x->parent->red; x->parent->red=0; w->right->red=0; LeftRotate(tree,x->parent); x=root; /* this is to exit while loop */ } } else { /* the code below is has left and right switched from above */ w=x->parent->left; if (w->red) { w->red=0; x->parent->red=1; RightRotate(tree,x->parent); w=x->parent->left; } if ( (!w->right->red) && (!w->left->red) ) { w->red=1; x=x->parent; } else { if (!w->left->red) { w->right->red=0; w->red=1; LeftRotate(tree,w); w=x->parent->left; } w->red=x->parent->red; x->parent->red=0; w->left->red=0; RightRotate(tree,x->parent); x=root; /* this is to exit while loop */ } } } x->red=0; #ifdef DEBUG_ASSERT Assert(!tree->nil->red,"nil not black in RBDeleteFixUp"); #endif } /***********************************************************************/ /* FUNCTION: RBDelete */ /**/ /* INPUTS: tree is the tree to delete node z from */ /**/ /* OUTPUT: none */ /**/ /* EFFECT: Deletes z from tree and frees the key and info of z */ /* using DestoryKey and DestoryInfo. Then calls */ /* RBDeleteFixUp to restore red-black properties */ /**/ /* Modifies Input: tree, z */ /**/ /* The algorithm from this function is from _Introduction_To_Algorithms_ */ /***********************************************************************/ void RBDelete(rb_red_blk_tree* tree, rb_red_blk_node* z){ rb_red_blk_node* y; rb_red_blk_node* x; rb_red_blk_node* nil=tree->nil; rb_red_blk_node* root=tree->root; y= ((z->left == nil) || (z->right == nil)) ? z : TreeSuccessor(tree,z); x= (y->left == nil) ? y->right : y->left; if (root == (x->parent = y->parent)) { /* assignment of y->p to x->p is intentional */ root->left=x; } else { if (y == y->parent->left) { y->parent->left=x; } else { y->parent->right=x; } } if (y != z) { /* y should not be nil in this case */ #ifdef DEBUG_ASSERT Assert( (y!=tree->nil),"y is nil in RBDelete\n"); #endif /* y is the node to splice out and x is its child */ if (!(y->red)) RBDeleteFixUp(tree,x); tree->DestroyKey(z->key); tree->DestroyInfo(z->info); y->left=z->left; y->right=z->right; y->parent=z->parent; y->red=z->red; z->left->parent=z->right->parent=y; if (z == z->parent->left) { z->parent->left=y; } else { z->parent->right=y; } free(z); } else { tree->DestroyKey(y->key); tree->DestroyInfo(y->info); if (!(y->red)) RBDeleteFixUp(tree,x); free(y); } #ifdef DEBUG_ASSERT Assert(!tree->nil->red,"nil not black in RBDelete"); #endif } /***********************************************************************/ /* FUNCTION: RBEnumerate */ /**/ /* INPUTS: tree is the tree to look for keys >= low */ /* and <= high with respect to the Compare function */ /**/ /* OUTPUT: stack containing pointers to the nodes between [low,high] */ /**/ /* Modifies Input: none */ /***********************************************************************/ stk_stack* RBEnumerate(rb_red_blk_tree* tree, void* low, void* high) { stk_stack* enumResultStack; rb_red_blk_node* nil=tree->nil; rb_red_blk_node* x=tree->root->left; rb_red_blk_node* lastBest=nil; enumResultStack=StackCreate(); while(nil != x) { if ( 1 == (tree->Compare(x->key,high)) ) { /* x->key > high */ x=x->left; } else { lastBest=x; x=x->right; } } while ( (lastBest != nil) && (1 != tree->Compare(low,lastBest->key))) { StackPush(enumResultStack,lastBest); lastBest=TreePredecessor(tree,lastBest); } return(enumResultStack); } int checkRepHelper (rb_red_blk_node *node, rb_red_blk_tree *t) { int left_black_cnt, right_black_cnt; /* by convention sentinel nodes point to nil instead of null */ assert (node); if (node == t->nil) return 0; /* the tree order must be respected */ /* parents and children must point to each other */ if (node->left != t->nil) { int tmp = t->Compare (node->key, node->left->key); assert (tmp==0 || tmp==1); assert (node->left->parent == node); } if (node->right != t->nil) { int tmp = t->Compare (node->key, node->right->key); assert (tmp==0 || tmp==-1); assert (node->right->parent == node); } if (node->left != t->nil && node->right != t->nil) { int tmp = t->Compare (node->left->key, node->right->key); assert (tmp==0 || tmp==-1); } /* both children of a red node are black */ if (node->red) { assert (!node->left->red); assert (!node->right->red); } /* every root->leaf path has the same number of black nodes */ left_black_cnt = checkRepHelper (node->left, t); right_black_cnt = checkRepHelper (node->right, t); assert (left_black_cnt == right_black_cnt); return left_black_cnt + (node->red ? 0 : -1); } void checkRep (rb_red_blk_tree *tree) { /* root is black by convention */ assert (!tree->root->left->red); checkRepHelper (tree->root->left, tree); }
525005.c
/* Copyright 2013 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ #include "brotli_decode.h" #include <stdlib.h> /* free, malloc */ #include <string.h> /* memcpy, memset */ #include "brotli_common_constants.h" #include "brotli_common_context.h" #include "brotli_common_dictionary.h" #include "brotli_common_platform.h" #include "brotli_common_transform.h" #include "brotli_common_version.h" #include "brotli_dec_bit_reader.h" #include "brotli_dec_huffman.h" #include "brotli_dec_prefix.h" #include "brotli_dec_state.h" #if defined(BROTLI_TARGET_NEON) #include <arm_neon.h> #endif #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #define BROTLI_FAILURE(CODE) (BROTLI_DUMP(), CODE) #define BROTLI_LOG_UINT(name) \ BROTLI_LOG(("[%s] %s = %lu\n", __func__, #name, (unsigned long)(name))) #define BROTLI_LOG_ARRAY_INDEX(array_name, idx) \ BROTLI_LOG(("[%s] %s[%lu] = %lu\n", __func__, #array_name, \ (unsigned long)(idx), (unsigned long)array_name[idx])) #define HUFFMAN_TABLE_BITS 8U #define HUFFMAN_TABLE_MASK 0xFF /* We need the slack region for the following reasons: - doing up to two 16-byte copies for fast backward copying - inserting transformed dictionary word: 5 prefix + 24 base + 8 suffix */ static const uint32_t kRingBufferWriteAheadSlack = 42; static const uint8_t kCodeLengthCodeOrder[BROTLI_CODE_LENGTH_CODES] = { 1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15, }; /* Static prefix code for the complex code length code lengths. */ static const uint8_t kCodeLengthPrefixLength[16] = { 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2, 3, 2, 2, 2, 4, }; static const uint8_t kCodeLengthPrefixValue[16] = { 0, 4, 3, 2, 0, 4, 3, 1, 0, 4, 3, 2, 0, 4, 3, 5, }; BROTLI_BOOL BrotliDecoderSetParameter( BrotliDecoderState* state, BrotliDecoderParameter p, uint32_t value) { if (state->state != BROTLI_STATE_UNINITED) return BROTLI_FALSE; switch (p) { case BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: state->canny_ringbuffer_allocation = !!value ? 0 : 1; return BROTLI_TRUE; case BROTLI_DECODER_PARAM_LARGE_WINDOW: state->large_window = TO_BROTLI_BOOL(!!value); return BROTLI_TRUE; default: return BROTLI_FALSE; } } BrotliDecoderState* BrotliDecoderCreateInstance( brotli_alloc_func alloc_func, brotli_free_func free_func, void* opaque) { BrotliDecoderState* state = 0; if (!alloc_func && !free_func) { state = (BrotliDecoderState*)malloc(sizeof(BrotliDecoderState)); } else if (alloc_func && free_func) { state = (BrotliDecoderState*)alloc_func(opaque, sizeof(BrotliDecoderState)); } if (state == 0) { BROTLI_DUMP(); return 0; } if (!BrotliDecoderStateInit(state, alloc_func, free_func, opaque)) { BROTLI_DUMP(); if (!alloc_func && !free_func) { free(state); } else if (alloc_func && free_func) { free_func(opaque, state); } return 0; } return state; } /* Deinitializes and frees BrotliDecoderState instance. */ void BrotliDecoderDestroyInstance(BrotliDecoderState* state) { if (!state) { return; } else { brotli_free_func free_func = state->free_func; void* opaque = state->memory_manager_opaque; BrotliDecoderStateCleanup(state); free_func(opaque, state); } } /* Saves error code and converts it to BrotliDecoderResult. */ static BROTLI_NOINLINE BrotliDecoderResult SaveErrorCode( BrotliDecoderState* s, BrotliDecoderErrorCode e) { s->error_code = (int)e; switch (e) { case BROTLI_DECODER_SUCCESS: return BROTLI_DECODER_RESULT_SUCCESS; case BROTLI_DECODER_NEEDS_MORE_INPUT: return BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT; case BROTLI_DECODER_NEEDS_MORE_OUTPUT: return BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT; default: return BROTLI_DECODER_RESULT_ERROR; } } /* Decodes WBITS by reading 1 - 7 bits, or 0x11 for "Large Window Brotli". Precondition: bit-reader accumulator has at least 8 bits. */ static BrotliDecoderErrorCode DecodeWindowBits(BrotliDecoderState* s, BrotliBitReader* br) { uint32_t n; BROTLI_BOOL large_window = s->large_window; s->large_window = BROTLI_FALSE; BrotliTakeBits(br, 1, &n); if (n == 0) { s->window_bits = 16; return BROTLI_DECODER_SUCCESS; } BrotliTakeBits(br, 3, &n); if (n != 0) { s->window_bits = 17 + n; return BROTLI_DECODER_SUCCESS; } BrotliTakeBits(br, 3, &n); if (n == 1) { if (large_window) { BrotliTakeBits(br, 1, &n); if (n == 1) { return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS); } s->large_window = BROTLI_TRUE; return BROTLI_DECODER_SUCCESS; } else { return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS); } } if (n != 0) { s->window_bits = 8 + n; return BROTLI_DECODER_SUCCESS; } s->window_bits = 17; return BROTLI_DECODER_SUCCESS; } static BROTLI_INLINE void memmove16(uint8_t* dst, uint8_t* src) { #if defined(BROTLI_TARGET_NEON) vst1q_u8(dst, vld1q_u8(src)); #else uint32_t buffer[4]; memcpy(buffer, src, 16); memcpy(dst, buffer, 16); #endif } /* Decodes a number in the range [0..255], by reading 1 - 11 bits. */ static BROTLI_NOINLINE BrotliDecoderErrorCode DecodeVarLenUint8( BrotliDecoderState* s, BrotliBitReader* br, uint32_t* value) { uint32_t bits; switch (s->substate_decode_uint8) { case BROTLI_STATE_DECODE_UINT8_NONE: if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, 1, &bits))) { return BROTLI_DECODER_NEEDS_MORE_INPUT; } if (bits == 0) { *value = 0; return BROTLI_DECODER_SUCCESS; } /* Fall through. */ case BROTLI_STATE_DECODE_UINT8_SHORT: if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, 3, &bits))) { s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_SHORT; return BROTLI_DECODER_NEEDS_MORE_INPUT; } if (bits == 0) { *value = 1; s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_NONE; return BROTLI_DECODER_SUCCESS; } /* Use output value as a temporary storage. It MUST be persisted. */ *value = bits; /* Fall through. */ case BROTLI_STATE_DECODE_UINT8_LONG: if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, *value, &bits))) { s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_LONG; return BROTLI_DECODER_NEEDS_MORE_INPUT; } *value = (1U << *value) + bits; s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_NONE; return BROTLI_DECODER_SUCCESS; default: return BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE); } } /* Decodes a metablock length and flags by reading 2 - 31 bits. */ static BrotliDecoderErrorCode BROTLI_NOINLINE DecodeMetaBlockLength( BrotliDecoderState* s, BrotliBitReader* br) { uint32_t bits; int i; for (;;) { switch (s->substate_metablock_header) { case BROTLI_STATE_METABLOCK_HEADER_NONE: if (!BrotliSafeReadBits(br, 1, &bits)) { return BROTLI_DECODER_NEEDS_MORE_INPUT; } s->is_last_metablock = bits ? 1 : 0; s->meta_block_remaining_len = 0; s->is_uncompressed = 0; s->is_metadata = 0; if (!s->is_last_metablock) { s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NIBBLES; break; } s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_EMPTY; /* Fall through. */ case BROTLI_STATE_METABLOCK_HEADER_EMPTY: if (!BrotliSafeReadBits(br, 1, &bits)) { return BROTLI_DECODER_NEEDS_MORE_INPUT; } if (bits) { s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE; return BROTLI_DECODER_SUCCESS; } s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NIBBLES; /* Fall through. */ case BROTLI_STATE_METABLOCK_HEADER_NIBBLES: if (!BrotliSafeReadBits(br, 2, &bits)) { return BROTLI_DECODER_NEEDS_MORE_INPUT; } s->size_nibbles = (uint8_t)(bits + 4); s->loop_counter = 0; if (bits == 3) { s->is_metadata = 1; s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_RESERVED; break; } s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_SIZE; /* Fall through. */ case BROTLI_STATE_METABLOCK_HEADER_SIZE: i = s->loop_counter; for (; i < (int)s->size_nibbles; ++i) { if (!BrotliSafeReadBits(br, 4, &bits)) { s->loop_counter = i; return BROTLI_DECODER_NEEDS_MORE_INPUT; } if (i + 1 == (int)s->size_nibbles && s->size_nibbles > 4 && bits == 0) { return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE); } s->meta_block_remaining_len |= (int)(bits << (i * 4)); } s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED; /* Fall through. */ case BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED: if (!s->is_last_metablock) { if (!BrotliSafeReadBits(br, 1, &bits)) { return BROTLI_DECODER_NEEDS_MORE_INPUT; } s->is_uncompressed = bits ? 1 : 0; } ++s->meta_block_remaining_len; s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE; return BROTLI_DECODER_SUCCESS; case BROTLI_STATE_METABLOCK_HEADER_RESERVED: if (!BrotliSafeReadBits(br, 1, &bits)) { return BROTLI_DECODER_NEEDS_MORE_INPUT; } if (bits != 0) { return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_RESERVED); } s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_BYTES; /* Fall through. */ case BROTLI_STATE_METABLOCK_HEADER_BYTES: if (!BrotliSafeReadBits(br, 2, &bits)) { return BROTLI_DECODER_NEEDS_MORE_INPUT; } if (bits == 0) { s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE; return BROTLI_DECODER_SUCCESS; } s->size_nibbles = (uint8_t)bits; s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_METADATA; /* Fall through. */ case BROTLI_STATE_METABLOCK_HEADER_METADATA: i = s->loop_counter; for (; i < (int)s->size_nibbles; ++i) { if (!BrotliSafeReadBits(br, 8, &bits)) { s->loop_counter = i; return BROTLI_DECODER_NEEDS_MORE_INPUT; } if (i + 1 == (int)s->size_nibbles && s->size_nibbles > 1 && bits == 0) { return BROTLI_FAILURE( BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE); } s->meta_block_remaining_len |= (int)(bits << (i * 8)); } ++s->meta_block_remaining_len; s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE; return BROTLI_DECODER_SUCCESS; default: return BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE); } } } /* Decodes the Huffman code. This method doesn't read data from the bit reader, BUT drops the amount of bits that correspond to the decoded symbol. bits MUST contain at least 15 (BROTLI_HUFFMAN_MAX_CODE_LENGTH) valid bits. */ static BROTLI_INLINE uint32_t DecodeSymbol(uint32_t bits, const HuffmanCode* table, BrotliBitReader* br) { BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(table); BROTLI_HC_ADJUST_TABLE_INDEX(table, bits & HUFFMAN_TABLE_MASK); if (BROTLI_HC_FAST_LOAD_BITS(table) > HUFFMAN_TABLE_BITS) { uint32_t nbits = BROTLI_HC_FAST_LOAD_BITS(table) - HUFFMAN_TABLE_BITS; BrotliDropBits(br, HUFFMAN_TABLE_BITS); BROTLI_HC_ADJUST_TABLE_INDEX(table, BROTLI_HC_FAST_LOAD_VALUE(table) + ((bits >> HUFFMAN_TABLE_BITS) & BitMask(nbits))); } BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(table)); return BROTLI_HC_FAST_LOAD_VALUE(table); } /* Reads and decodes the next Huffman code from bit-stream. This method peeks 16 bits of input and drops 0 - 15 of them. */ static BROTLI_INLINE uint32_t ReadSymbol(const HuffmanCode* table, BrotliBitReader* br) { return DecodeSymbol(BrotliGet16BitsUnmasked(br), table, br); } /* Same as DecodeSymbol, but it is known that there is less than 15 bits of input are currently available. */ static BROTLI_NOINLINE BROTLI_BOOL SafeDecodeSymbol( const HuffmanCode* table, BrotliBitReader* br, uint32_t* result) { uint32_t val; uint32_t available_bits = BrotliGetAvailableBits(br); BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(table); if (available_bits == 0) { if (BROTLI_HC_FAST_LOAD_BITS(table) == 0) { *result = BROTLI_HC_FAST_LOAD_VALUE(table); return BROTLI_TRUE; } return BROTLI_FALSE; /* No valid bits at all. */ } val = (uint32_t)BrotliGetBitsUnmasked(br); BROTLI_HC_ADJUST_TABLE_INDEX(table, val & HUFFMAN_TABLE_MASK); if (BROTLI_HC_FAST_LOAD_BITS(table) <= HUFFMAN_TABLE_BITS) { if (BROTLI_HC_FAST_LOAD_BITS(table) <= available_bits) { BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(table)); *result = BROTLI_HC_FAST_LOAD_VALUE(table); return BROTLI_TRUE; } else { return BROTLI_FALSE; /* Not enough bits for the first level. */ } } if (available_bits <= HUFFMAN_TABLE_BITS) { return BROTLI_FALSE; /* Not enough bits to move to the second level. */ } /* Speculatively drop HUFFMAN_TABLE_BITS. */ val = (val & BitMask(BROTLI_HC_FAST_LOAD_BITS(table))) >> HUFFMAN_TABLE_BITS; available_bits -= HUFFMAN_TABLE_BITS; BROTLI_HC_ADJUST_TABLE_INDEX(table, BROTLI_HC_FAST_LOAD_VALUE(table) + val); if (available_bits < BROTLI_HC_FAST_LOAD_BITS(table)) { return BROTLI_FALSE; /* Not enough bits for the second level. */ } BrotliDropBits(br, HUFFMAN_TABLE_BITS + BROTLI_HC_FAST_LOAD_BITS(table)); *result = BROTLI_HC_FAST_LOAD_VALUE(table); return BROTLI_TRUE; } static BROTLI_INLINE BROTLI_BOOL SafeReadSymbol( const HuffmanCode* table, BrotliBitReader* br, uint32_t* result) { uint32_t val; if (BROTLI_PREDICT_TRUE(BrotliSafeGetBits(br, 15, &val))) { *result = DecodeSymbol(val, table, br); return BROTLI_TRUE; } return SafeDecodeSymbol(table, br, result); } /* Makes a look-up in first level Huffman table. Peeks 8 bits. */ static BROTLI_INLINE void PreloadSymbol(int safe, const HuffmanCode* table, BrotliBitReader* br, uint32_t* bits, uint32_t* value) { if (safe) { return; } BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(table); BROTLI_HC_ADJUST_TABLE_INDEX(table, BrotliGetBits(br, HUFFMAN_TABLE_BITS)); *bits = BROTLI_HC_FAST_LOAD_BITS(table); *value = BROTLI_HC_FAST_LOAD_VALUE(table); } /* Decodes the next Huffman code using data prepared by PreloadSymbol. Reads 0 - 15 bits. Also peeks 8 following bits. */ static BROTLI_INLINE uint32_t ReadPreloadedSymbol(const HuffmanCode* table, BrotliBitReader* br, uint32_t* bits, uint32_t* value) { uint32_t result = *value; if (BROTLI_PREDICT_FALSE(*bits > HUFFMAN_TABLE_BITS)) { uint32_t val = BrotliGet16BitsUnmasked(br); const HuffmanCode* ext = table + (val & HUFFMAN_TABLE_MASK) + *value; uint32_t mask = BitMask((*bits - HUFFMAN_TABLE_BITS)); BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(ext); BrotliDropBits(br, HUFFMAN_TABLE_BITS); BROTLI_HC_ADJUST_TABLE_INDEX(ext, (val >> HUFFMAN_TABLE_BITS) & mask); BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(ext)); result = BROTLI_HC_FAST_LOAD_VALUE(ext); } else { BrotliDropBits(br, *bits); } PreloadSymbol(0, table, br, bits, value); return result; } static BROTLI_INLINE uint32_t Log2Floor(uint32_t x) { uint32_t result = 0; while (x) { x >>= 1; ++result; } return result; } /* Reads (s->symbol + 1) symbols. Totally 1..4 symbols are read, 1..11 bits each. The list of symbols MUST NOT contain duplicates. */ static BrotliDecoderErrorCode ReadSimpleHuffmanSymbols( uint32_t alphabet_size_max, uint32_t alphabet_size_limit, BrotliDecoderState* s) { /* max_bits == 1..11; symbol == 0..3; 1..44 bits will be read. */ BrotliBitReader* br = &s->br; BrotliMetablockHeaderArena* h = &s->arena.header; uint32_t max_bits = Log2Floor(alphabet_size_max - 1); uint32_t i = h->sub_loop_counter; uint32_t num_symbols = h->symbol; while (i <= num_symbols) { uint32_t v; if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, max_bits, &v))) { h->sub_loop_counter = i; h->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_READ; return BROTLI_DECODER_NEEDS_MORE_INPUT; } if (v >= alphabet_size_limit) { return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET); } h->symbols_lists_array[i] = (uint16_t)v; BROTLI_LOG_UINT(h->symbols_lists_array[i]); ++i; } for (i = 0; i < num_symbols; ++i) { uint32_t k = i + 1; for (; k <= num_symbols; ++k) { if (h->symbols_lists_array[i] == h->symbols_lists_array[k]) { return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME); } } } return BROTLI_DECODER_SUCCESS; } /* Process single decoded symbol code length: A) reset the repeat variable B) remember code length (if it is not 0) C) extend corresponding index-chain D) reduce the Huffman space E) update the histogram */ static BROTLI_INLINE void ProcessSingleCodeLength(uint32_t code_len, uint32_t* symbol, uint32_t* repeat, uint32_t* space, uint32_t* prev_code_len, uint16_t* symbol_lists, uint16_t* code_length_histo, int* next_symbol) { *repeat = 0; if (code_len != 0) { /* code_len == 1..15 */ symbol_lists[next_symbol[code_len]] = (uint16_t)(*symbol); next_symbol[code_len] = (int)(*symbol); *prev_code_len = code_len; *space -= 32768U >> code_len; code_length_histo[code_len]++; BROTLI_LOG(("[ReadHuffmanCode] code_length[%d] = %d\n", (int)*symbol, (int)code_len)); } (*symbol)++; } /* Process repeated symbol code length. A) Check if it is the extension of previous repeat sequence; if the decoded value is not BROTLI_REPEAT_PREVIOUS_CODE_LENGTH, then it is a new symbol-skip B) Update repeat variable C) Check if operation is feasible (fits alphabet) D) For each symbol do the same operations as in ProcessSingleCodeLength PRECONDITION: code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH or code_len == BROTLI_REPEAT_ZERO_CODE_LENGTH */ static BROTLI_INLINE void ProcessRepeatedCodeLength(uint32_t code_len, uint32_t repeat_delta, uint32_t alphabet_size, uint32_t* symbol, uint32_t* repeat, uint32_t* space, uint32_t* prev_code_len, uint32_t* repeat_code_len, uint16_t* symbol_lists, uint16_t* code_length_histo, int* next_symbol) { uint32_t old_repeat; uint32_t extra_bits = 3; /* for BROTLI_REPEAT_ZERO_CODE_LENGTH */ uint32_t new_len = 0; /* for BROTLI_REPEAT_ZERO_CODE_LENGTH */ if (code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) { new_len = *prev_code_len; extra_bits = 2; } if (*repeat_code_len != new_len) { *repeat = 0; *repeat_code_len = new_len; } old_repeat = *repeat; if (*repeat > 0) { *repeat -= 2; *repeat <<= extra_bits; } *repeat += repeat_delta + 3U; repeat_delta = *repeat - old_repeat; if (*symbol + repeat_delta > alphabet_size) { BROTLI_DUMP(); *symbol = alphabet_size; *space = 0xFFFFF; return; } BROTLI_LOG(("[ReadHuffmanCode] code_length[%d..%d] = %d\n", (int)*symbol, (int)(*symbol + repeat_delta - 1), (int)*repeat_code_len)); if (*repeat_code_len != 0) { unsigned last = *symbol + repeat_delta; int next = next_symbol[*repeat_code_len]; do { symbol_lists[next] = (uint16_t)*symbol; next = (int)*symbol; } while (++(*symbol) != last); next_symbol[*repeat_code_len] = next; *space -= repeat_delta << (15 - *repeat_code_len); code_length_histo[*repeat_code_len] = (uint16_t)(code_length_histo[*repeat_code_len] + repeat_delta); } else { *symbol += repeat_delta; } } /* Reads and decodes symbol codelengths. */ static BrotliDecoderErrorCode ReadSymbolCodeLengths( uint32_t alphabet_size, BrotliDecoderState* s) { BrotliBitReader* br = &s->br; BrotliMetablockHeaderArena* h = &s->arena.header; uint32_t symbol = h->symbol; uint32_t repeat = h->repeat; uint32_t space = h->space; uint32_t prev_code_len = h->prev_code_len; uint32_t repeat_code_len = h->repeat_code_len; uint16_t* symbol_lists = h->symbol_lists; uint16_t* code_length_histo = h->code_length_histo; int* next_symbol = h->next_symbol; if (!BrotliWarmupBitReader(br)) { return BROTLI_DECODER_NEEDS_MORE_INPUT; } while (symbol < alphabet_size && space > 0) { const HuffmanCode* p = h->table; uint32_t code_len; BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(p); if (!BrotliCheckInputAmount(br, BROTLI_SHORT_FILL_BIT_WINDOW_READ)) { h->symbol = symbol; h->repeat = repeat; h->prev_code_len = prev_code_len; h->repeat_code_len = repeat_code_len; h->space = space; return BROTLI_DECODER_NEEDS_MORE_INPUT; } BrotliFillBitWindow16(br); BROTLI_HC_ADJUST_TABLE_INDEX(p, BrotliGetBitsUnmasked(br) & BitMask(BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH)); BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(p)); /* Use 1..5 bits. */ code_len = BROTLI_HC_FAST_LOAD_VALUE(p); /* code_len == 0..17 */ if (code_len < BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) { ProcessSingleCodeLength(code_len, &symbol, &repeat, &space, &prev_code_len, symbol_lists, code_length_histo, next_symbol); } else { /* code_len == 16..17, extra_bits == 2..3 */ uint32_t extra_bits = (code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) ? 2 : 3; uint32_t repeat_delta = (uint32_t)BrotliGetBitsUnmasked(br) & BitMask(extra_bits); BrotliDropBits(br, extra_bits); ProcessRepeatedCodeLength(code_len, repeat_delta, alphabet_size, &symbol, &repeat, &space, &prev_code_len, &repeat_code_len, symbol_lists, code_length_histo, next_symbol); } } h->space = space; return BROTLI_DECODER_SUCCESS; } static BrotliDecoderErrorCode SafeReadSymbolCodeLengths( uint32_t alphabet_size, BrotliDecoderState* s) { BrotliBitReader* br = &s->br; BrotliMetablockHeaderArena* h = &s->arena.header; BROTLI_BOOL get_byte = BROTLI_FALSE; while (h->symbol < alphabet_size && h->space > 0) { const HuffmanCode* p = h->table; uint32_t code_len; uint32_t available_bits; uint32_t bits = 0; BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(p); if (get_byte && !BrotliPullByte(br)) return BROTLI_DECODER_NEEDS_MORE_INPUT; get_byte = BROTLI_FALSE; available_bits = BrotliGetAvailableBits(br); if (available_bits != 0) { bits = (uint32_t)BrotliGetBitsUnmasked(br); } BROTLI_HC_ADJUST_TABLE_INDEX(p, bits & BitMask(BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH)); if (BROTLI_HC_FAST_LOAD_BITS(p) > available_bits) { get_byte = BROTLI_TRUE; continue; } code_len = BROTLI_HC_FAST_LOAD_VALUE(p); /* code_len == 0..17 */ if (code_len < BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) { BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(p)); ProcessSingleCodeLength(code_len, &h->symbol, &h->repeat, &h->space, &h->prev_code_len, h->symbol_lists, h->code_length_histo, h->next_symbol); } else { /* code_len == 16..17, extra_bits == 2..3 */ uint32_t extra_bits = code_len - 14U; uint32_t repeat_delta = (bits >> BROTLI_HC_FAST_LOAD_BITS(p)) & BitMask(extra_bits); if (available_bits < BROTLI_HC_FAST_LOAD_BITS(p) + extra_bits) { get_byte = BROTLI_TRUE; continue; } BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(p) + extra_bits); ProcessRepeatedCodeLength(code_len, repeat_delta, alphabet_size, &h->symbol, &h->repeat, &h->space, &h->prev_code_len, &h->repeat_code_len, h->symbol_lists, h->code_length_histo, h->next_symbol); } } return BROTLI_DECODER_SUCCESS; } /* Reads and decodes 15..18 codes using static prefix code. Each code is 2..4 bits long. In total 30..72 bits are used. */ static BrotliDecoderErrorCode ReadCodeLengthCodeLengths(BrotliDecoderState* s) { BrotliBitReader* br = &s->br; BrotliMetablockHeaderArena* h = &s->arena.header; uint32_t num_codes = h->repeat; unsigned space = h->space; uint32_t i = h->sub_loop_counter; for (; i < BROTLI_CODE_LENGTH_CODES; ++i) { const uint8_t code_len_idx = kCodeLengthCodeOrder[i]; uint32_t ix; uint32_t v; if (BROTLI_PREDICT_FALSE(!BrotliSafeGetBits(br, 4, &ix))) { uint32_t available_bits = BrotliGetAvailableBits(br); if (available_bits != 0) { ix = BrotliGetBitsUnmasked(br) & 0xF; } else { ix = 0; } if (kCodeLengthPrefixLength[ix] > available_bits) { h->sub_loop_counter = i; h->repeat = num_codes; h->space = space; h->substate_huffman = BROTLI_STATE_HUFFMAN_COMPLEX; return BROTLI_DECODER_NEEDS_MORE_INPUT; } } v = kCodeLengthPrefixValue[ix]; BrotliDropBits(br, kCodeLengthPrefixLength[ix]); h->code_length_code_lengths[code_len_idx] = (uint8_t)v; BROTLI_LOG_ARRAY_INDEX(h->code_length_code_lengths, code_len_idx); if (v != 0) { space = space - (32U >> v); ++num_codes; ++h->code_length_histo[v]; if (space - 1U >= 32U) { /* space is 0 or wrapped around. */ break; } } } if (!(num_codes == 1 || space == 0)) { return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_CL_SPACE); } return BROTLI_DECODER_SUCCESS; } /* Decodes the Huffman tables. There are 2 scenarios: A) Huffman code contains only few symbols (1..4). Those symbols are read directly; their code lengths are defined by the number of symbols. For this scenario 4 - 49 bits will be read. B) 2-phase decoding: B.1) Small Huffman table is decoded; it is specified with code lengths encoded with predefined entropy code. 32 - 74 bits are used. B.2) Decoded table is used to decode code lengths of symbols in resulting Huffman table. In worst case 3520 bits are read. */ static BrotliDecoderErrorCode ReadHuffmanCode(uint32_t alphabet_size_max, uint32_t alphabet_size_limit, HuffmanCode* table, uint32_t* opt_table_size, BrotliDecoderState* s) { BrotliBitReader* br = &s->br; BrotliMetablockHeaderArena* h = &s->arena.header; /* State machine. */ for (;;) { switch (h->substate_huffman) { case BROTLI_STATE_HUFFMAN_NONE: if (!BrotliSafeReadBits(br, 2, &h->sub_loop_counter)) { return BROTLI_DECODER_NEEDS_MORE_INPUT; } BROTLI_LOG_UINT(h->sub_loop_counter); /* The value is used as follows: 1 for simple code; 0 for no skipping, 2 skips 2 code lengths, 3 skips 3 code lengths */ if (h->sub_loop_counter != 1) { h->space = 32; h->repeat = 0; /* num_codes */ memset(&h->code_length_histo[0], 0, sizeof(h->code_length_histo[0]) * (BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH + 1)); memset(&h->code_length_code_lengths[0], 0, sizeof(h->code_length_code_lengths)); h->substate_huffman = BROTLI_STATE_HUFFMAN_COMPLEX; continue; } /* Fall through. */ case BROTLI_STATE_HUFFMAN_SIMPLE_SIZE: /* Read symbols, codes & code lengths directly. */ if (!BrotliSafeReadBits(br, 2, &h->symbol)) { /* num_symbols */ h->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_SIZE; return BROTLI_DECODER_NEEDS_MORE_INPUT; } h->sub_loop_counter = 0; /* Fall through. */ case BROTLI_STATE_HUFFMAN_SIMPLE_READ: { BrotliDecoderErrorCode result = ReadSimpleHuffmanSymbols(alphabet_size_max, alphabet_size_limit, s); if (result != BROTLI_DECODER_SUCCESS) { return result; } } /* Fall through. */ case BROTLI_STATE_HUFFMAN_SIMPLE_BUILD: { uint32_t table_size; if (h->symbol == 3) { uint32_t bits; if (!BrotliSafeReadBits(br, 1, &bits)) { h->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_BUILD; return BROTLI_DECODER_NEEDS_MORE_INPUT; } h->symbol += bits; } BROTLI_LOG_UINT(h->symbol); table_size = BrotliBuildSimpleHuffmanTable( table, HUFFMAN_TABLE_BITS, h->symbols_lists_array, h->symbol); if (opt_table_size) { *opt_table_size = table_size; } h->substate_huffman = BROTLI_STATE_HUFFMAN_NONE; return BROTLI_DECODER_SUCCESS; } /* Decode Huffman-coded code lengths. */ case BROTLI_STATE_HUFFMAN_COMPLEX: { uint32_t i; BrotliDecoderErrorCode result = ReadCodeLengthCodeLengths(s); if (result != BROTLI_DECODER_SUCCESS) { return result; } BrotliBuildCodeLengthsHuffmanTable(h->table, h->code_length_code_lengths, h->code_length_histo); memset(&h->code_length_histo[0], 0, sizeof(h->code_length_histo)); for (i = 0; i <= BROTLI_HUFFMAN_MAX_CODE_LENGTH; ++i) { h->next_symbol[i] = (int)i - (BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1); h->symbol_lists[h->next_symbol[i]] = 0xFFFF; } h->symbol = 0; h->prev_code_len = BROTLI_INITIAL_REPEATED_CODE_LENGTH; h->repeat = 0; h->repeat_code_len = 0; h->space = 32768; h->substate_huffman = BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS; } /* Fall through. */ case BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS: { uint32_t table_size; BrotliDecoderErrorCode result = ReadSymbolCodeLengths( alphabet_size_limit, s); if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) { result = SafeReadSymbolCodeLengths(alphabet_size_limit, s); } if (result != BROTLI_DECODER_SUCCESS) { return result; } if (h->space != 0) { BROTLI_LOG(("[ReadHuffmanCode] space = %d\n", (int)h->space)); return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE); } table_size = BrotliBuildHuffmanTable( table, HUFFMAN_TABLE_BITS, h->symbol_lists, h->code_length_histo); if (opt_table_size) { *opt_table_size = table_size; } h->substate_huffman = BROTLI_STATE_HUFFMAN_NONE; return BROTLI_DECODER_SUCCESS; } default: return BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE); } } } /* Decodes a block length by reading 3..39 bits. */ static BROTLI_INLINE uint32_t ReadBlockLength(const HuffmanCode* table, BrotliBitReader* br) { uint32_t code; uint32_t nbits; code = ReadSymbol(table, br); nbits = _kBrotliPrefixCodeRanges[code].nbits; /* nbits == 2..24 */ return _kBrotliPrefixCodeRanges[code].offset + BrotliReadBits24(br, nbits); } /* WARNING: if state is not BROTLI_STATE_READ_BLOCK_LENGTH_NONE, then reading can't be continued with ReadBlockLength. */ static BROTLI_INLINE BROTLI_BOOL SafeReadBlockLength( BrotliDecoderState* s, uint32_t* result, const HuffmanCode* table, BrotliBitReader* br) { uint32_t index; if (s->substate_read_block_length == BROTLI_STATE_READ_BLOCK_LENGTH_NONE) { if (!SafeReadSymbol(table, br, &index)) { return BROTLI_FALSE; } } else { index = s->block_length_index; } { uint32_t bits; uint32_t nbits = _kBrotliPrefixCodeRanges[index].nbits; uint32_t offset = _kBrotliPrefixCodeRanges[index].offset; if (!BrotliSafeReadBits(br, nbits, &bits)) { s->block_length_index = index; s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_SUFFIX; return BROTLI_FALSE; } *result = offset + bits; s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_NONE; return BROTLI_TRUE; } } /* Transform: 1) initialize list L with values 0, 1,... 255 2) For each input element X: 2.1) let Y = L[X] 2.2) remove X-th element from L 2.3) prepend Y to L 2.4) append Y to output In most cases max(Y) <= 7, so most of L remains intact. To reduce the cost of initialization, we reuse L, remember the upper bound of Y values, and reinitialize only first elements in L. Most of input values are 0 and 1. To reduce number of branches, we replace inner for loop with do-while. */ static BROTLI_NOINLINE void InverseMoveToFrontTransform( uint8_t* v, uint32_t v_len, BrotliDecoderState* state) { /* Reinitialize elements that could have been changed. */ uint32_t i = 1; uint32_t upper_bound = state->mtf_upper_bound; uint32_t* mtf = &state->mtf[1]; /* Make mtf[-1] addressable. */ uint8_t* mtf_u8 = (uint8_t*)mtf; /* Load endian-aware constant. */ const uint8_t b0123[4] = {0, 1, 2, 3}; uint32_t pattern; memcpy(&pattern, &b0123, 4); /* Initialize list using 4 consequent values pattern. */ mtf[0] = pattern; do { pattern += 0x04040404; /* Advance all 4 values by 4. */ mtf[i] = pattern; i++; } while (i <= upper_bound); /* Transform the input. */ upper_bound = 0; for (i = 0; i < v_len; ++i) { int index = v[i]; uint8_t value = mtf_u8[index]; upper_bound |= v[i]; v[i] = value; mtf_u8[-1] = value; do { index--; mtf_u8[index + 1] = mtf_u8[index]; } while (index >= 0); } /* Remember amount of elements to be reinitialized. */ state->mtf_upper_bound = upper_bound >> 2; } /* Decodes a series of Huffman table using ReadHuffmanCode function. */ static BrotliDecoderErrorCode HuffmanTreeGroupDecode( HuffmanTreeGroup* group, BrotliDecoderState* s) { BrotliMetablockHeaderArena* h = &s->arena.header; if (h->substate_tree_group != BROTLI_STATE_TREE_GROUP_LOOP) { h->next = group->codes; h->htree_index = 0; h->substate_tree_group = BROTLI_STATE_TREE_GROUP_LOOP; } while (h->htree_index < group->num_htrees) { uint32_t table_size; BrotliDecoderErrorCode result = ReadHuffmanCode(group->alphabet_size_max, group->alphabet_size_limit, h->next, &table_size, s); if (result != BROTLI_DECODER_SUCCESS) return result; group->htrees[h->htree_index] = h->next; h->next += table_size; ++h->htree_index; } h->substate_tree_group = BROTLI_STATE_TREE_GROUP_NONE; return BROTLI_DECODER_SUCCESS; } /* Decodes a context map. Decoding is done in 4 phases: 1) Read auxiliary information (6..16 bits) and allocate memory. In case of trivial context map, decoding is finished at this phase. 2) Decode Huffman table using ReadHuffmanCode function. This table will be used for reading context map items. 3) Read context map items; "0" values could be run-length encoded. 4) Optionally, apply InverseMoveToFront transform to the resulting map. */ static BrotliDecoderErrorCode DecodeContextMap(uint32_t context_map_size, uint32_t* num_htrees, uint8_t** context_map_arg, BrotliDecoderState* s) { BrotliBitReader* br = &s->br; BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS; BrotliMetablockHeaderArena* h = &s->arena.header; switch ((int)h->substate_context_map) { case BROTLI_STATE_CONTEXT_MAP_NONE: result = DecodeVarLenUint8(s, br, num_htrees); if (result != BROTLI_DECODER_SUCCESS) { return result; } (*num_htrees)++; h->context_index = 0; BROTLI_LOG_UINT(context_map_size); BROTLI_LOG_UINT(*num_htrees); *context_map_arg = (uint8_t*)BROTLI_DECODER_ALLOC(s, (size_t)context_map_size); if (*context_map_arg == 0) { return BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP); } if (*num_htrees <= 1) { memset(*context_map_arg, 0, (size_t)context_map_size); return BROTLI_DECODER_SUCCESS; } h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_READ_PREFIX; /* Fall through. */ case BROTLI_STATE_CONTEXT_MAP_READ_PREFIX: { uint32_t bits; /* In next stage ReadHuffmanCode uses at least 4 bits, so it is safe to peek 4 bits ahead. */ if (!BrotliSafeGetBits(br, 5, &bits)) { return BROTLI_DECODER_NEEDS_MORE_INPUT; } if ((bits & 1) != 0) { /* Use RLE for zeros. */ h->max_run_length_prefix = (bits >> 1) + 1; BrotliDropBits(br, 5); } else { h->max_run_length_prefix = 0; BrotliDropBits(br, 1); } BROTLI_LOG_UINT(h->max_run_length_prefix); h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_HUFFMAN; } /* Fall through. */ case BROTLI_STATE_CONTEXT_MAP_HUFFMAN: { uint32_t alphabet_size = *num_htrees + h->max_run_length_prefix; result = ReadHuffmanCode(alphabet_size, alphabet_size, h->context_map_table, NULL, s); if (result != BROTLI_DECODER_SUCCESS) return result; h->code = 0xFFFF; h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_DECODE; } /* Fall through. */ case BROTLI_STATE_CONTEXT_MAP_DECODE: { uint32_t context_index = h->context_index; uint32_t max_run_length_prefix = h->max_run_length_prefix; uint8_t* context_map = *context_map_arg; uint32_t code = h->code; BROTLI_BOOL skip_preamble = (code != 0xFFFF); while (context_index < context_map_size || skip_preamble) { if (!skip_preamble) { if (!SafeReadSymbol(h->context_map_table, br, &code)) { h->code = 0xFFFF; h->context_index = context_index; return BROTLI_DECODER_NEEDS_MORE_INPUT; } BROTLI_LOG_UINT(code); if (code == 0) { context_map[context_index++] = 0; continue; } if (code > max_run_length_prefix) { context_map[context_index++] = (uint8_t)(code - max_run_length_prefix); continue; } } else { skip_preamble = BROTLI_FALSE; } /* RLE sub-stage. */ { uint32_t reps; if (!BrotliSafeReadBits(br, code, &reps)) { h->code = code; h->context_index = context_index; return BROTLI_DECODER_NEEDS_MORE_INPUT; } reps += 1U << code; BROTLI_LOG_UINT(reps); if (context_index + reps > context_map_size) { return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT); } do { context_map[context_index++] = 0; } while (--reps); } } } /* Fall through. */ case BROTLI_STATE_CONTEXT_MAP_TRANSFORM: { uint32_t bits; if (!BrotliSafeReadBits(br, 1, &bits)) { h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_TRANSFORM; return BROTLI_DECODER_NEEDS_MORE_INPUT; } if (bits != 0) { InverseMoveToFrontTransform(*context_map_arg, context_map_size, s); } h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_NONE; return BROTLI_DECODER_SUCCESS; } default: return BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE); } } /* Decodes a command or literal and updates block type ring-buffer. Reads 3..54 bits. */ static BROTLI_INLINE BROTLI_BOOL DecodeBlockTypeAndLength( int safe, BrotliDecoderState* s, int tree_type) { uint32_t max_block_type = s->num_block_types[tree_type]; const HuffmanCode* type_tree = &s->block_type_trees[ tree_type * BROTLI_HUFFMAN_MAX_SIZE_258]; const HuffmanCode* len_tree = &s->block_len_trees[ tree_type * BROTLI_HUFFMAN_MAX_SIZE_26]; BrotliBitReader* br = &s->br; uint32_t* ringbuffer = &s->block_type_rb[tree_type * 2]; uint32_t block_type; if (max_block_type <= 1) { return BROTLI_FALSE; } /* Read 0..15 + 3..39 bits. */ if (!safe) { block_type = ReadSymbol(type_tree, br); s->block_length[tree_type] = ReadBlockLength(len_tree, br); } else { BrotliBitReaderState memento; BrotliBitReaderSaveState(br, &memento); if (!SafeReadSymbol(type_tree, br, &block_type)) return BROTLI_FALSE; if (!SafeReadBlockLength(s, &s->block_length[tree_type], len_tree, br)) { s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_NONE; BrotliBitReaderRestoreState(br, &memento); return BROTLI_FALSE; } } if (block_type == 1) { block_type = ringbuffer[1] + 1; } else if (block_type == 0) { block_type = ringbuffer[0]; } else { block_type -= 2; } if (block_type >= max_block_type) { block_type -= max_block_type; } ringbuffer[0] = ringbuffer[1]; ringbuffer[1] = block_type; return BROTLI_TRUE; } static BROTLI_INLINE void DetectTrivialLiteralBlockTypes( BrotliDecoderState* s) { size_t i; for (i = 0; i < 8; ++i) s->trivial_literal_contexts[i] = 0; for (i = 0; i < s->num_block_types[0]; i++) { size_t offset = i << BROTLI_LITERAL_CONTEXT_BITS; size_t error = 0; size_t sample = s->context_map[offset]; size_t j; for (j = 0; j < (1u << BROTLI_LITERAL_CONTEXT_BITS);) { BROTLI_REPEAT(4, error |= s->context_map[offset + j++] ^ sample;) } if (error == 0) { s->trivial_literal_contexts[i >> 5] |= 1u << (i & 31); } } } static BROTLI_INLINE void PrepareLiteralDecoding(BrotliDecoderState* s) { uint8_t context_mode; size_t trivial; uint32_t block_type = s->block_type_rb[1]; uint32_t context_offset = block_type << BROTLI_LITERAL_CONTEXT_BITS; s->context_map_slice = s->context_map + context_offset; trivial = s->trivial_literal_contexts[block_type >> 5]; s->trivial_literal_context = (trivial >> (block_type & 31)) & 1; s->literal_htree = s->literal_hgroup.htrees[s->context_map_slice[0]]; context_mode = s->context_modes[block_type] & 3; s->context_lookup = BROTLI_CONTEXT_LUT(context_mode); } /* Decodes the block type and updates the state for literal context. Reads 3..54 bits. */ static BROTLI_INLINE BROTLI_BOOL DecodeLiteralBlockSwitchInternal( int safe, BrotliDecoderState* s) { if (!DecodeBlockTypeAndLength(safe, s, 0)) { return BROTLI_FALSE; } PrepareLiteralDecoding(s); return BROTLI_TRUE; } static void BROTLI_NOINLINE DecodeLiteralBlockSwitch(BrotliDecoderState* s) { DecodeLiteralBlockSwitchInternal(0, s); } static BROTLI_BOOL BROTLI_NOINLINE SafeDecodeLiteralBlockSwitch( BrotliDecoderState* s) { return DecodeLiteralBlockSwitchInternal(1, s); } /* Block switch for insert/copy length. Reads 3..54 bits. */ static BROTLI_INLINE BROTLI_BOOL DecodeCommandBlockSwitchInternal( int safe, BrotliDecoderState* s) { if (!DecodeBlockTypeAndLength(safe, s, 1)) { return BROTLI_FALSE; } s->htree_command = s->insert_copy_hgroup.htrees[s->block_type_rb[3]]; return BROTLI_TRUE; } static void BROTLI_NOINLINE DecodeCommandBlockSwitch(BrotliDecoderState* s) { DecodeCommandBlockSwitchInternal(0, s); } static BROTLI_BOOL BROTLI_NOINLINE SafeDecodeCommandBlockSwitch( BrotliDecoderState* s) { return DecodeCommandBlockSwitchInternal(1, s); } /* Block switch for distance codes. Reads 3..54 bits. */ static BROTLI_INLINE BROTLI_BOOL DecodeDistanceBlockSwitchInternal( int safe, BrotliDecoderState* s) { if (!DecodeBlockTypeAndLength(safe, s, 2)) { return BROTLI_FALSE; } s->dist_context_map_slice = s->dist_context_map + (s->block_type_rb[5] << BROTLI_DISTANCE_CONTEXT_BITS); s->dist_htree_index = s->dist_context_map_slice[s->distance_context]; return BROTLI_TRUE; } static void BROTLI_NOINLINE DecodeDistanceBlockSwitch(BrotliDecoderState* s) { DecodeDistanceBlockSwitchInternal(0, s); } static BROTLI_BOOL BROTLI_NOINLINE SafeDecodeDistanceBlockSwitch( BrotliDecoderState* s) { return DecodeDistanceBlockSwitchInternal(1, s); } static size_t UnwrittenBytes(const BrotliDecoderState* s, BROTLI_BOOL wrap) { size_t pos = wrap && s->pos > s->ringbuffer_size ? (size_t)s->ringbuffer_size : (size_t)(s->pos); size_t partial_pos_rb = (s->rb_roundtrips * (size_t)s->ringbuffer_size) + pos; return partial_pos_rb - s->partial_pos_out; } /* Dumps output. Returns BROTLI_DECODER_NEEDS_MORE_OUTPUT only if there is more output to push and either ring-buffer is as big as window size, or |force| is true. */ static BrotliDecoderErrorCode BROTLI_NOINLINE WriteRingBuffer( BrotliDecoderState* s, size_t* available_out, uint8_t** next_out, size_t* total_out, BROTLI_BOOL force) { uint8_t* start = s->ringbuffer + (s->partial_pos_out & (size_t)s->ringbuffer_mask); size_t to_write = UnwrittenBytes(s, BROTLI_TRUE); size_t num_written = *available_out; if (num_written > to_write) { num_written = to_write; } if (s->meta_block_remaining_len < 0) { return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1); } if (next_out && !*next_out) { *next_out = start; } else { if (next_out) { memcpy(*next_out, start, num_written); *next_out += num_written; } } *available_out -= num_written; BROTLI_LOG_UINT(to_write); BROTLI_LOG_UINT(num_written); s->partial_pos_out += num_written; if (total_out) { *total_out = s->partial_pos_out; } if (num_written < to_write) { if (s->ringbuffer_size == (1 << s->window_bits) || force) { return BROTLI_DECODER_NEEDS_MORE_OUTPUT; } else { return BROTLI_DECODER_SUCCESS; } } /* Wrap ring buffer only if it has reached its maximal size. */ if (s->ringbuffer_size == (1 << s->window_bits) && s->pos >= s->ringbuffer_size) { s->pos -= s->ringbuffer_size; s->rb_roundtrips++; s->should_wrap_ringbuffer = (size_t)s->pos != 0 ? 1 : 0; } return BROTLI_DECODER_SUCCESS; } static void BROTLI_NOINLINE WrapRingBuffer(BrotliDecoderState* s) { if (s->should_wrap_ringbuffer) { memcpy(s->ringbuffer, s->ringbuffer_end, (size_t)s->pos); s->should_wrap_ringbuffer = 0; } } /* Allocates ring-buffer. s->ringbuffer_size MUST be updated by BrotliCalculateRingBufferSize before this function is called. Last two bytes of ring-buffer are initialized to 0, so context calculation could be done uniformly for the first two and all other positions. */ static BROTLI_BOOL BROTLI_NOINLINE BrotliEnsureRingBuffer( BrotliDecoderState* s) { uint8_t* old_ringbuffer = s->ringbuffer; if (s->ringbuffer_size == s->new_ringbuffer_size) { return BROTLI_TRUE; } s->ringbuffer = (uint8_t*)BROTLI_DECODER_ALLOC(s, (size_t)(s->new_ringbuffer_size) + kRingBufferWriteAheadSlack); if (s->ringbuffer == 0) { /* Restore previous value. */ s->ringbuffer = old_ringbuffer; return BROTLI_FALSE; } s->ringbuffer[s->new_ringbuffer_size - 2] = 0; s->ringbuffer[s->new_ringbuffer_size - 1] = 0; if (!!old_ringbuffer) { memcpy(s->ringbuffer, old_ringbuffer, (size_t)s->pos); BROTLI_DECODER_FREE(s, old_ringbuffer); } s->ringbuffer_size = s->new_ringbuffer_size; s->ringbuffer_mask = s->new_ringbuffer_size - 1; s->ringbuffer_end = s->ringbuffer + s->ringbuffer_size; return BROTLI_TRUE; } static BrotliDecoderErrorCode BROTLI_NOINLINE CopyUncompressedBlockToOutput( size_t* available_out, uint8_t** next_out, size_t* total_out, BrotliDecoderState* s) { /* TODO: avoid allocation for single uncompressed block. */ if (!BrotliEnsureRingBuffer(s)) { return BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1); } /* State machine */ for (;;) { switch (s->substate_uncompressed) { case BROTLI_STATE_UNCOMPRESSED_NONE: { int nbytes = (int)BrotliGetRemainingBytes(&s->br); if (nbytes > s->meta_block_remaining_len) { nbytes = s->meta_block_remaining_len; } if (s->pos + nbytes > s->ringbuffer_size) { nbytes = s->ringbuffer_size - s->pos; } /* Copy remaining bytes from s->br.buf_ to ring-buffer. */ BrotliCopyBytes(&s->ringbuffer[s->pos], &s->br, (size_t)nbytes); s->pos += nbytes; s->meta_block_remaining_len -= nbytes; if (s->pos < 1 << s->window_bits) { if (s->meta_block_remaining_len == 0) { return BROTLI_DECODER_SUCCESS; } return BROTLI_DECODER_NEEDS_MORE_INPUT; } s->substate_uncompressed = BROTLI_STATE_UNCOMPRESSED_WRITE; } /* Fall through. */ case BROTLI_STATE_UNCOMPRESSED_WRITE: { BrotliDecoderErrorCode result; result = WriteRingBuffer( s, available_out, next_out, total_out, BROTLI_FALSE); if (result != BROTLI_DECODER_SUCCESS) { return result; } if (s->ringbuffer_size == 1 << s->window_bits) { s->max_distance = s->max_backward_distance; } s->substate_uncompressed = BROTLI_STATE_UNCOMPRESSED_NONE; break; } } } BROTLI_DCHECK(0); /* Unreachable */ } /* Calculates the smallest feasible ring buffer. If we know the data size is small, do not allocate more ring buffer size than needed to reduce memory usage. When this method is called, metablock size and flags MUST be decoded. */ static void BROTLI_NOINLINE BrotliCalculateRingBufferSize( BrotliDecoderState* s) { int window_size = 1 << s->window_bits; int new_ringbuffer_size = window_size; /* We need at least 2 bytes of ring buffer size to get the last two bytes for context from there */ int min_size = s->ringbuffer_size ? s->ringbuffer_size : 1024; int output_size; /* If maximum is already reached, no further extension is retired. */ if (s->ringbuffer_size == window_size) { return; } /* Metadata blocks does not touch ring buffer. */ if (s->is_metadata) { return; } if (!s->ringbuffer) { output_size = 0; } else { output_size = s->pos; } output_size += s->meta_block_remaining_len; min_size = min_size < output_size ? output_size : min_size; if (!!s->canny_ringbuffer_allocation) { /* Reduce ring buffer size to save memory when server is unscrupulous. In worst case memory usage might be 1.5x bigger for a short period of ring buffer reallocation. */ while ((new_ringbuffer_size >> 1) >= min_size) { new_ringbuffer_size >>= 1; } } s->new_ringbuffer_size = new_ringbuffer_size; } /* Reads 1..256 2-bit context modes. */ static BrotliDecoderErrorCode ReadContextModes(BrotliDecoderState* s) { BrotliBitReader* br = &s->br; int i = s->loop_counter; while (i < (int)s->num_block_types[0]) { uint32_t bits; if (!BrotliSafeReadBits(br, 2, &bits)) { s->loop_counter = i; return BROTLI_DECODER_NEEDS_MORE_INPUT; } s->context_modes[i] = (uint8_t)bits; BROTLI_LOG_ARRAY_INDEX(s->context_modes, i); i++; } return BROTLI_DECODER_SUCCESS; } static BROTLI_INLINE void TakeDistanceFromRingBuffer(BrotliDecoderState* s) { int offset = s->distance_code - 3; if (s->distance_code <= 3) { /* Compensate double distance-ring-buffer roll for dictionary items. */ s->distance_context = 1 >> s->distance_code; s->distance_code = s->dist_rb[(s->dist_rb_idx - offset) & 3]; s->dist_rb_idx -= s->distance_context; } else { int index_delta = 3; int delta; int base = s->distance_code - 10; if (s->distance_code < 10) { base = s->distance_code - 4; } else { index_delta = 2; } /* Unpack one of six 4-bit values. */ delta = ((0x605142 >> (4 * base)) & 0xF) - 3; s->distance_code = s->dist_rb[(s->dist_rb_idx + index_delta) & 0x3] + delta; if (s->distance_code <= 0) { /* A huge distance will cause a BROTLI_FAILURE() soon. This is a little faster than failing here. */ s->distance_code = 0x7FFFFFFF; } } } static BROTLI_INLINE BROTLI_BOOL SafeReadBits( BrotliBitReader* const br, uint32_t n_bits, uint32_t* val) { if (n_bits != 0) { return BrotliSafeReadBits(br, n_bits, val); } else { *val = 0; return BROTLI_TRUE; } } static BROTLI_INLINE BROTLI_BOOL SafeReadBits32( BrotliBitReader* const br, uint32_t n_bits, uint32_t* val) { if (n_bits != 0) { return BrotliSafeReadBits32(br, n_bits, val); } else { *val = 0; return BROTLI_TRUE; } } /* RFC 7932 Section 4 with "..." shortenings and "[]" emendations. Each distance ... is represented with a pair <distance code, extra bits>... The distance code is encoded using a prefix code... The number of extra bits can be 0..24... Two additional parameters: NPOSTFIX (0..3), and ... NDIRECT (0..120) ... are encoded in the meta-block header... The first 16 distance symbols ... reference past distances... ring buffer ... Next NDIRECT distance symbols ... represent distances from 1 to NDIRECT... [For] distance symbols 16 + NDIRECT and greater ... the number of extra bits ... is given by the following formula: [ xcode = dcode - NDIRECT - 16 ] ndistbits = 1 + [ xcode ] >> (NPOSTFIX + 1) ... */ /* RFC 7932 Section 9.2 with "..." shortenings and "[]" emendations. ... to get the actual value of the parameter NDIRECT, left-shift this four-bit number by NPOSTFIX bits ... */ /* Remaining formulas from RFC 7932 Section 4 could be rewritten as following: alphabet_size = 16 + NDIRECT + (max_distbits << (NPOSTFIX + 1)) half = ((xcode >> NPOSTFIX) & 1) << ndistbits postfix = xcode & ((1 << NPOSTFIX) - 1) range_start = 2 * (1 << ndistbits - 1 - 1) distance = (range_start + half + extra) << NPOSTFIX + postfix + NDIRECT + 1 NB: ndistbits >= 1 -> range_start >= 0 NB: range_start has factor 2, as the range is covered by 2 "halves" NB: extra -1 offset in range_start formula covers the absence of ndistbits = 0 case NB: when NPOSTFIX = 0, NDIRECT is not greater than 15 In other words, xcode has the following binary structure - XXXHPPP: - XXX represent the number of extra distance bits - H selects upper / lower range of distances - PPP represent "postfix" "Regular" distance encoding has NPOSTFIX = 0; omitting the postfix part simplifies distance calculation. Using NPOSTFIX > 0 allows cheaper encoding of regular structures, e.g. where most of distances have the same reminder of division by 2/4/8. For example, the table of int32_t values that come from different sources; if it is likely that 3 highest bytes of values from the same source are the same, then copy distance often looks like 4x + y. Distance calculation could be rewritten to: ndistbits = NDISTBITS(NDIRECT, NPOSTFIX)[dcode] distance = OFFSET(NDIRECT, NPOSTFIX)[dcode] + extra << NPOSTFIX NDISTBITS and OFFSET could be pre-calculated, as NDIRECT and NPOSTFIX could change only once per meta-block. */ /* Calculates distance lookup table. NB: it is possible to have all 64 tables precalculated. */ static void CalculateDistanceLut(BrotliDecoderState* s) { BrotliMetablockBodyArena* b = &s->arena.body; uint32_t npostfix = s->distance_postfix_bits; uint32_t ndirect = s->num_direct_distance_codes; uint32_t alphabet_size_limit = s->distance_hgroup.alphabet_size_limit; uint32_t postfix = 1u << npostfix; uint32_t j; uint32_t bits = 1; uint32_t half = 0; /* Skip short codes. */ uint32_t i = BROTLI_NUM_DISTANCE_SHORT_CODES; /* Fill direct codes. */ for (j = 0; j < ndirect; ++j) { b->dist_extra_bits[i] = 0; b->dist_offset[i] = j + 1; ++i; } /* Fill regular distance codes. */ while (i < alphabet_size_limit) { uint32_t base = ndirect + ((((2 + half) << bits) - 4) << npostfix) + 1; /* Always fill the complete group. */ for (j = 0; j < postfix; ++j) { b->dist_extra_bits[i] = (uint8_t)bits; b->dist_offset[i] = base + j; ++i; } bits = bits + half; half = half ^ 1; } } /* Precondition: s->distance_code < 0. */ static BROTLI_INLINE BROTLI_BOOL ReadDistanceInternal( int safe, BrotliDecoderState* s, BrotliBitReader* br) { BrotliMetablockBodyArena* b = &s->arena.body; uint32_t code; uint32_t bits; BrotliBitReaderState memento; HuffmanCode* distance_tree = s->distance_hgroup.htrees[s->dist_htree_index]; if (!safe) { code = ReadSymbol(distance_tree, br); } else { BrotliBitReaderSaveState(br, &memento); if (!SafeReadSymbol(distance_tree, br, &code)) { return BROTLI_FALSE; } } --s->block_length[2]; /* Convert the distance code to the actual distance by possibly looking up past distances from the s->dist_rb. */ s->distance_context = 0; if ((code & ~0xFu) == 0) { s->distance_code = (int)code; TakeDistanceFromRingBuffer(s); return BROTLI_TRUE; } if (!safe) { bits = BrotliReadBits32(br, b->dist_extra_bits[code]); } else { if (!SafeReadBits32(br, b->dist_extra_bits[code], &bits)) { ++s->block_length[2]; BrotliBitReaderRestoreState(br, &memento); return BROTLI_FALSE; } } s->distance_code = (int)(b->dist_offset[code] + (bits << s->distance_postfix_bits)); return BROTLI_TRUE; } static BROTLI_INLINE void ReadDistance( BrotliDecoderState* s, BrotliBitReader* br) { ReadDistanceInternal(0, s, br); } static BROTLI_INLINE BROTLI_BOOL SafeReadDistance( BrotliDecoderState* s, BrotliBitReader* br) { return ReadDistanceInternal(1, s, br); } static BROTLI_INLINE BROTLI_BOOL ReadCommandInternal( int safe, BrotliDecoderState* s, BrotliBitReader* br, int* insert_length) { uint32_t cmd_code; uint32_t insert_len_extra = 0; uint32_t copy_length; CmdLutElement v; BrotliBitReaderState memento; if (!safe) { cmd_code = ReadSymbol(s->htree_command, br); } else { BrotliBitReaderSaveState(br, &memento); if (!SafeReadSymbol(s->htree_command, br, &cmd_code)) { return BROTLI_FALSE; } } v = kCmdLut[cmd_code]; s->distance_code = v.distance_code; s->distance_context = v.context; s->dist_htree_index = s->dist_context_map_slice[s->distance_context]; *insert_length = v.insert_len_offset; if (!safe) { if (BROTLI_PREDICT_FALSE(v.insert_len_extra_bits != 0)) { insert_len_extra = BrotliReadBits24(br, v.insert_len_extra_bits); } copy_length = BrotliReadBits24(br, v.copy_len_extra_bits); } else { if (!SafeReadBits(br, v.insert_len_extra_bits, &insert_len_extra) || !SafeReadBits(br, v.copy_len_extra_bits, &copy_length)) { BrotliBitReaderRestoreState(br, &memento); return BROTLI_FALSE; } } s->copy_length = (int)copy_length + v.copy_len_offset; --s->block_length[1]; *insert_length += (int)insert_len_extra; return BROTLI_TRUE; } static BROTLI_INLINE void ReadCommand( BrotliDecoderState* s, BrotliBitReader* br, int* insert_length) { ReadCommandInternal(0, s, br, insert_length); } static BROTLI_INLINE BROTLI_BOOL SafeReadCommand( BrotliDecoderState* s, BrotliBitReader* br, int* insert_length) { return ReadCommandInternal(1, s, br, insert_length); } static BROTLI_INLINE BROTLI_BOOL CheckInputAmount( int safe, BrotliBitReader* const br, size_t num) { if (safe) { return BROTLI_TRUE; } return BrotliCheckInputAmount(br, num); } #define BROTLI_SAFE(METHOD) \ { \ if (safe) { \ if (!Safe##METHOD) { \ result = BROTLI_DECODER_NEEDS_MORE_INPUT; \ goto saveStateAndReturn; \ } \ } else { \ METHOD; \ } \ } static BROTLI_INLINE BrotliDecoderErrorCode ProcessCommandsInternal( int safe, BrotliDecoderState* s) { int pos = s->pos; int i = s->loop_counter; BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS; BrotliBitReader* br = &s->br; if (!CheckInputAmount(safe, br, 28)) { result = BROTLI_DECODER_NEEDS_MORE_INPUT; goto saveStateAndReturn; } if (!safe) { BROTLI_UNUSED(BrotliWarmupBitReader(br)); } /* Jump into state machine. */ if (s->state == BROTLI_STATE_COMMAND_BEGIN) { goto CommandBegin; } else if (s->state == BROTLI_STATE_COMMAND_INNER) { goto CommandInner; } else if (s->state == BROTLI_STATE_COMMAND_POST_DECODE_LITERALS) { goto CommandPostDecodeLiterals; } else if (s->state == BROTLI_STATE_COMMAND_POST_WRAP_COPY) { goto CommandPostWrapCopy; } else { return BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE); } CommandBegin: if (safe) { s->state = BROTLI_STATE_COMMAND_BEGIN; } if (!CheckInputAmount(safe, br, 28)) { /* 156 bits + 7 bytes */ s->state = BROTLI_STATE_COMMAND_BEGIN; result = BROTLI_DECODER_NEEDS_MORE_INPUT; goto saveStateAndReturn; } if (BROTLI_PREDICT_FALSE(s->block_length[1] == 0)) { BROTLI_SAFE(DecodeCommandBlockSwitch(s)); goto CommandBegin; } /* Read the insert/copy length in the command. */ BROTLI_SAFE(ReadCommand(s, br, &i)); BROTLI_LOG(("[ProcessCommandsInternal] pos = %d insert = %d copy = %d\n", pos, i, s->copy_length)); if (i == 0) { goto CommandPostDecodeLiterals; } s->meta_block_remaining_len -= i; CommandInner: if (safe) { s->state = BROTLI_STATE_COMMAND_INNER; } /* Read the literals in the command. */ if (s->trivial_literal_context) { uint32_t bits; uint32_t value; PreloadSymbol(safe, s->literal_htree, br, &bits, &value); do { if (!CheckInputAmount(safe, br, 28)) { /* 162 bits + 7 bytes */ s->state = BROTLI_STATE_COMMAND_INNER; result = BROTLI_DECODER_NEEDS_MORE_INPUT; goto saveStateAndReturn; } if (BROTLI_PREDICT_FALSE(s->block_length[0] == 0)) { BROTLI_SAFE(DecodeLiteralBlockSwitch(s)); PreloadSymbol(safe, s->literal_htree, br, &bits, &value); if (!s->trivial_literal_context) goto CommandInner; } if (!safe) { s->ringbuffer[pos] = (uint8_t)ReadPreloadedSymbol(s->literal_htree, br, &bits, &value); } else { uint32_t literal; if (!SafeReadSymbol(s->literal_htree, br, &literal)) { result = BROTLI_DECODER_NEEDS_MORE_INPUT; goto saveStateAndReturn; } s->ringbuffer[pos] = (uint8_t)literal; } --s->block_length[0]; BROTLI_LOG_ARRAY_INDEX(s->ringbuffer, pos); ++pos; if (BROTLI_PREDICT_FALSE(pos == s->ringbuffer_size)) { s->state = BROTLI_STATE_COMMAND_INNER_WRITE; --i; goto saveStateAndReturn; } } while (--i != 0); } else { uint8_t p1 = s->ringbuffer[(pos - 1) & s->ringbuffer_mask]; uint8_t p2 = s->ringbuffer[(pos - 2) & s->ringbuffer_mask]; do { const HuffmanCode* hc; uint8_t context; if (!CheckInputAmount(safe, br, 28)) { /* 162 bits + 7 bytes */ s->state = BROTLI_STATE_COMMAND_INNER; result = BROTLI_DECODER_NEEDS_MORE_INPUT; goto saveStateAndReturn; } if (BROTLI_PREDICT_FALSE(s->block_length[0] == 0)) { BROTLI_SAFE(DecodeLiteralBlockSwitch(s)); if (s->trivial_literal_context) goto CommandInner; } context = BROTLI_CONTEXT(p1, p2, s->context_lookup); BROTLI_LOG_UINT(context); hc = s->literal_hgroup.htrees[s->context_map_slice[context]]; p2 = p1; if (!safe) { p1 = (uint8_t)ReadSymbol(hc, br); } else { uint32_t literal; if (!SafeReadSymbol(hc, br, &literal)) { result = BROTLI_DECODER_NEEDS_MORE_INPUT; goto saveStateAndReturn; } p1 = (uint8_t)literal; } s->ringbuffer[pos] = p1; --s->block_length[0]; BROTLI_LOG_UINT(s->context_map_slice[context]); BROTLI_LOG_ARRAY_INDEX(s->ringbuffer, pos & s->ringbuffer_mask); ++pos; if (BROTLI_PREDICT_FALSE(pos == s->ringbuffer_size)) { s->state = BROTLI_STATE_COMMAND_INNER_WRITE; --i; goto saveStateAndReturn; } } while (--i != 0); } BROTLI_LOG_UINT(s->meta_block_remaining_len); if (BROTLI_PREDICT_FALSE(s->meta_block_remaining_len <= 0)) { s->state = BROTLI_STATE_METABLOCK_DONE; goto saveStateAndReturn; } CommandPostDecodeLiterals: if (safe) { s->state = BROTLI_STATE_COMMAND_POST_DECODE_LITERALS; } if (s->distance_code >= 0) { /* Implicit distance case. */ s->distance_context = s->distance_code ? 0 : 1; --s->dist_rb_idx; s->distance_code = s->dist_rb[s->dist_rb_idx & 3]; } else { /* Read distance code in the command, unless it was implicitly zero. */ if (BROTLI_PREDICT_FALSE(s->block_length[2] == 0)) { BROTLI_SAFE(DecodeDistanceBlockSwitch(s)); } BROTLI_SAFE(ReadDistance(s, br)); } BROTLI_LOG(("[ProcessCommandsInternal] pos = %d distance = %d\n", pos, s->distance_code)); if (s->max_distance != s->max_backward_distance) { s->max_distance = (pos < s->max_backward_distance) ? pos : s->max_backward_distance; } i = s->copy_length; /* Apply copy of LZ77 back-reference, or static dictionary reference if the distance is larger than the max LZ77 distance */ if (s->distance_code > s->max_distance) { /* The maximum allowed distance is BROTLI_MAX_ALLOWED_DISTANCE = 0x7FFFFFFC. With this choice, no signed overflow can occur after decoding a special distance code (e.g., after adding 3 to the last distance). */ if (s->distance_code > BROTLI_MAX_ALLOWED_DISTANCE) { BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d " "len: %d bytes left: %d\n", pos, s->distance_code, i, s->meta_block_remaining_len)); return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_DISTANCE); } if (i >= BROTLI_MIN_DICTIONARY_WORD_LENGTH && i <= BROTLI_MAX_DICTIONARY_WORD_LENGTH) { int address = s->distance_code - s->max_distance - 1; const BrotliDictionary* words = s->dictionary; const BrotliTransforms* transforms = s->transforms; int offset = (int)s->dictionary->offsets_by_length[i]; uint32_t shift = s->dictionary->size_bits_by_length[i]; int mask = (int)BitMask(shift); int word_idx = address & mask; int transform_idx = address >> shift; /* Compensate double distance-ring-buffer roll. */ s->dist_rb_idx += s->distance_context; offset += word_idx * i; if (BROTLI_PREDICT_FALSE(!words->data)) { return BROTLI_FAILURE(BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET); } if (transform_idx < (int)transforms->num_transforms) { const uint8_t* word = &words->data[offset]; int len = i; if (transform_idx == transforms->cutOffTransforms[0]) { memcpy(&s->ringbuffer[pos], word, (size_t)len); BROTLI_LOG(("[ProcessCommandsInternal] dictionary word: [%.*s]\n", len, word)); } else { len = BrotliTransformDictionaryWord(&s->ringbuffer[pos], word, len, transforms, transform_idx); BROTLI_LOG(("[ProcessCommandsInternal] dictionary word: [%.*s]," " transform_idx = %d, transformed: [%.*s]\n", i, word, transform_idx, len, &s->ringbuffer[pos])); } pos += len; s->meta_block_remaining_len -= len; if (pos >= s->ringbuffer_size) { s->state = BROTLI_STATE_COMMAND_POST_WRITE_1; goto saveStateAndReturn; } } else { BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d " "len: %d bytes left: %d\n", pos, s->distance_code, i, s->meta_block_remaining_len)); return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_TRANSFORM); } } else { BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d " "len: %d bytes left: %d\n", pos, s->distance_code, i, s->meta_block_remaining_len)); return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_DICTIONARY); } } else { int src_start = (pos - s->distance_code) & s->ringbuffer_mask; uint8_t* copy_dst = &s->ringbuffer[pos]; uint8_t* copy_src = &s->ringbuffer[src_start]; int dst_end = pos + i; int src_end = src_start + i; /* Update the recent distances cache. */ s->dist_rb[s->dist_rb_idx & 3] = s->distance_code; ++s->dist_rb_idx; s->meta_block_remaining_len -= i; /* There are 32+ bytes of slack in the ring-buffer allocation. Also, we have 16 short codes, that make these 16 bytes irrelevant in the ring-buffer. Let's copy over them as a first guess. */ memmove16(copy_dst, copy_src); if (src_end > pos && dst_end > src_start) { /* Regions intersect. */ goto CommandPostWrapCopy; } if (dst_end >= s->ringbuffer_size || src_end >= s->ringbuffer_size) { /* At least one region wraps. */ goto CommandPostWrapCopy; } pos += i; if (i > 16) { if (i > 32) { memcpy(copy_dst + 16, copy_src + 16, (size_t)(i - 16)); } else { /* This branch covers about 45% cases. Fixed size short copy allows more compiler optimizations. */ memmove16(copy_dst + 16, copy_src + 16); } } } BROTLI_LOG_UINT(s->meta_block_remaining_len); if (s->meta_block_remaining_len <= 0) { /* Next metablock, if any. */ s->state = BROTLI_STATE_METABLOCK_DONE; goto saveStateAndReturn; } else { goto CommandBegin; } CommandPostWrapCopy: { int wrap_guard = s->ringbuffer_size - pos; while (--i >= 0) { s->ringbuffer[pos] = s->ringbuffer[(pos - s->distance_code) & s->ringbuffer_mask]; ++pos; if (BROTLI_PREDICT_FALSE(--wrap_guard == 0)) { s->state = BROTLI_STATE_COMMAND_POST_WRITE_2; goto saveStateAndReturn; } } } if (s->meta_block_remaining_len <= 0) { /* Next metablock, if any. */ s->state = BROTLI_STATE_METABLOCK_DONE; goto saveStateAndReturn; } else { goto CommandBegin; } saveStateAndReturn: s->pos = pos; s->loop_counter = i; return result; } #undef BROTLI_SAFE static BROTLI_NOINLINE BrotliDecoderErrorCode ProcessCommands( BrotliDecoderState* s) { return ProcessCommandsInternal(0, s); } static BROTLI_NOINLINE BrotliDecoderErrorCode SafeProcessCommands( BrotliDecoderState* s) { return ProcessCommandsInternal(1, s); } BrotliDecoderResult BrotliDecoderDecompress( size_t encoded_size, const uint8_t* encoded_buffer, size_t* decoded_size, uint8_t* decoded_buffer) { BrotliDecoderState s; BrotliDecoderResult result; size_t total_out = 0; size_t available_in = encoded_size; const uint8_t* next_in = encoded_buffer; size_t available_out = *decoded_size; uint8_t* next_out = decoded_buffer; if (!BrotliDecoderStateInit(&s, 0, 0, 0)) { return BROTLI_DECODER_RESULT_ERROR; } result = BrotliDecoderDecompressStream( &s, &available_in, &next_in, &available_out, &next_out, &total_out); *decoded_size = total_out; BrotliDecoderStateCleanup(&s); if (result != BROTLI_DECODER_RESULT_SUCCESS) { result = BROTLI_DECODER_RESULT_ERROR; } return result; } /* Invariant: input stream is never overconsumed: - invalid input implies that the whole stream is invalid -> any amount of input could be read and discarded - when result is "needs more input", then at least one more byte is REQUIRED to complete decoding; all input data MUST be consumed by decoder, so client could swap the input buffer - when result is "needs more output" decoder MUST ensure that it doesn't hold more than 7 bits in bit reader; this saves client from swapping input buffer ahead of time - when result is "success" decoder MUST return all unused data back to input buffer; this is possible because the invariant is held on enter */ BrotliDecoderResult BrotliDecoderDecompressStream( BrotliDecoderState* s, size_t* available_in, const uint8_t** next_in, size_t* available_out, uint8_t** next_out, size_t* total_out) { BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS; BrotliBitReader* br = &s->br; /* Ensure that |total_out| is set, even if no data will ever be pushed out. */ if (total_out) { *total_out = s->partial_pos_out; } /* Do not try to process further in a case of unrecoverable error. */ if ((int)s->error_code < 0) { return BROTLI_DECODER_RESULT_ERROR; } if (*available_out && (!next_out || !*next_out)) { return SaveErrorCode( s, BROTLI_FAILURE(BROTLI_DECODER_ERROR_INVALID_ARGUMENTS)); } if (!*available_out) next_out = 0; if (s->buffer_length == 0) { /* Just connect bit reader to input stream. */ br->avail_in = *available_in; br->next_in = *next_in; } else { /* At least one byte of input is required. More than one byte of input may be required to complete the transaction -> reading more data must be done in a loop -> do it in a main loop. */ result = BROTLI_DECODER_NEEDS_MORE_INPUT; br->next_in = &s->buffer.u8[0]; } /* State machine */ for (;;) { if (result != BROTLI_DECODER_SUCCESS) { /* Error, needs more input/output. */ if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) { if (s->ringbuffer != 0) { /* Pro-actively push output. */ BrotliDecoderErrorCode intermediate_result = WriteRingBuffer(s, available_out, next_out, total_out, BROTLI_TRUE); /* WriteRingBuffer checks s->meta_block_remaining_len validity. */ if ((int)intermediate_result < 0) { result = intermediate_result; break; } } if (s->buffer_length != 0) { /* Used with internal buffer. */ if (br->avail_in == 0) { /* Successfully finished read transaction. Accumulator contains less than 8 bits, because internal buffer is expanded byte-by-byte until it is enough to complete read. */ s->buffer_length = 0; /* Switch to input stream and restart. */ result = BROTLI_DECODER_SUCCESS; br->avail_in = *available_in; br->next_in = *next_in; continue; } else if (*available_in != 0) { /* Not enough data in buffer, but can take one more byte from input stream. */ result = BROTLI_DECODER_SUCCESS; s->buffer.u8[s->buffer_length] = **next_in; s->buffer_length++; br->avail_in = s->buffer_length; (*next_in)++; (*available_in)--; /* Retry with more data in buffer. */ continue; } /* Can't finish reading and no more input. */ break; } else { /* Input stream doesn't contain enough input. */ /* Copy tail to internal buffer and return. */ *next_in = br->next_in; *available_in = br->avail_in; while (*available_in) { s->buffer.u8[s->buffer_length] = **next_in; s->buffer_length++; (*next_in)++; (*available_in)--; } break; } /* Unreachable. */ } /* Fail or needs more output. */ if (s->buffer_length != 0) { /* Just consumed the buffered input and produced some output. Otherwise it would result in "needs more input". Reset internal buffer. */ s->buffer_length = 0; } else { /* Using input stream in last iteration. When decoder switches to input stream it has less than 8 bits in accumulator, so it is safe to return unused accumulator bits there. */ BrotliBitReaderUnload(br); *available_in = br->avail_in; *next_in = br->next_in; } break; } switch (s->state) { case BROTLI_STATE_UNINITED: /* Prepare to the first read. */ if (!BrotliWarmupBitReader(br)) { result = BROTLI_DECODER_NEEDS_MORE_INPUT; break; } /* Decode window size. */ result = DecodeWindowBits(s, br); /* Reads 1..8 bits. */ if (result != BROTLI_DECODER_SUCCESS) { break; } if (s->large_window) { s->state = BROTLI_STATE_LARGE_WINDOW_BITS; break; } s->state = BROTLI_STATE_INITIALIZE; break; case BROTLI_STATE_LARGE_WINDOW_BITS: if (!BrotliSafeReadBits(br, 6, &s->window_bits)) { result = BROTLI_DECODER_NEEDS_MORE_INPUT; break; } if (s->window_bits < BROTLI_LARGE_MIN_WBITS || s->window_bits > BROTLI_LARGE_MAX_WBITS) { result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS); break; } s->state = BROTLI_STATE_INITIALIZE; /* Fall through. */ case BROTLI_STATE_INITIALIZE: BROTLI_LOG_UINT(s->window_bits); /* Maximum distance, see section 9.1. of the spec. */ s->max_backward_distance = (1 << s->window_bits) - BROTLI_WINDOW_GAP; /* Allocate memory for both block_type_trees and block_len_trees. */ s->block_type_trees = (HuffmanCode*)BROTLI_DECODER_ALLOC(s, sizeof(HuffmanCode) * 3 * (BROTLI_HUFFMAN_MAX_SIZE_258 + BROTLI_HUFFMAN_MAX_SIZE_26)); if (s->block_type_trees == 0) { result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES); break; } s->block_len_trees = s->block_type_trees + 3 * BROTLI_HUFFMAN_MAX_SIZE_258; s->state = BROTLI_STATE_METABLOCK_BEGIN; /* Fall through. */ case BROTLI_STATE_METABLOCK_BEGIN: BrotliDecoderStateMetablockBegin(s); BROTLI_LOG_UINT(s->pos); s->state = BROTLI_STATE_METABLOCK_HEADER; /* Fall through. */ case BROTLI_STATE_METABLOCK_HEADER: result = DecodeMetaBlockLength(s, br); /* Reads 2 - 31 bits. */ if (result != BROTLI_DECODER_SUCCESS) { break; } BROTLI_LOG_UINT(s->is_last_metablock); BROTLI_LOG_UINT(s->meta_block_remaining_len); BROTLI_LOG_UINT(s->is_metadata); BROTLI_LOG_UINT(s->is_uncompressed); if (s->is_metadata || s->is_uncompressed) { if (!BrotliJumpToByteBoundary(br)) { result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_PADDING_1); break; } } if (s->is_metadata) { s->state = BROTLI_STATE_METADATA; break; } if (s->meta_block_remaining_len == 0) { s->state = BROTLI_STATE_METABLOCK_DONE; break; } BrotliCalculateRingBufferSize(s); if (s->is_uncompressed) { s->state = BROTLI_STATE_UNCOMPRESSED; break; } s->state = BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_HEADER; /* Fall through. */ case BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_HEADER: { BrotliMetablockHeaderArena* h = &s->arena.header; s->loop_counter = 0; /* Initialize compressed metablock header arena. */ h->sub_loop_counter = 0; /* Make small negative indexes addressable. */ h->symbol_lists = &h->symbols_lists_array[BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1]; h->substate_huffman = BROTLI_STATE_HUFFMAN_NONE; h->substate_tree_group = BROTLI_STATE_TREE_GROUP_NONE; h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_NONE; s->state = BROTLI_STATE_HUFFMAN_CODE_0; } /* Fall through. */ case BROTLI_STATE_HUFFMAN_CODE_0: if (s->loop_counter >= 3) { s->state = BROTLI_STATE_METABLOCK_HEADER_2; break; } /* Reads 1..11 bits. */ result = DecodeVarLenUint8(s, br, &s->num_block_types[s->loop_counter]); if (result != BROTLI_DECODER_SUCCESS) { break; } s->num_block_types[s->loop_counter]++; BROTLI_LOG_UINT(s->num_block_types[s->loop_counter]); if (s->num_block_types[s->loop_counter] < 2) { s->loop_counter++; break; } s->state = BROTLI_STATE_HUFFMAN_CODE_1; /* Fall through. */ case BROTLI_STATE_HUFFMAN_CODE_1: { uint32_t alphabet_size = s->num_block_types[s->loop_counter] + 2; int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_SIZE_258; result = ReadHuffmanCode(alphabet_size, alphabet_size, &s->block_type_trees[tree_offset], NULL, s); if (result != BROTLI_DECODER_SUCCESS) break; s->state = BROTLI_STATE_HUFFMAN_CODE_2; } /* Fall through. */ case BROTLI_STATE_HUFFMAN_CODE_2: { uint32_t alphabet_size = BROTLI_NUM_BLOCK_LEN_SYMBOLS; int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_SIZE_26; result = ReadHuffmanCode(alphabet_size, alphabet_size, &s->block_len_trees[tree_offset], NULL, s); if (result != BROTLI_DECODER_SUCCESS) break; s->state = BROTLI_STATE_HUFFMAN_CODE_3; } /* Fall through. */ case BROTLI_STATE_HUFFMAN_CODE_3: { int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_SIZE_26; if (!SafeReadBlockLength(s, &s->block_length[s->loop_counter], &s->block_len_trees[tree_offset], br)) { result = BROTLI_DECODER_NEEDS_MORE_INPUT; break; } BROTLI_LOG_UINT(s->block_length[s->loop_counter]); s->loop_counter++; s->state = BROTLI_STATE_HUFFMAN_CODE_0; break; } case BROTLI_STATE_UNCOMPRESSED: { result = CopyUncompressedBlockToOutput( available_out, next_out, total_out, s); if (result != BROTLI_DECODER_SUCCESS) { break; } s->state = BROTLI_STATE_METABLOCK_DONE; break; } case BROTLI_STATE_METADATA: for (; s->meta_block_remaining_len > 0; --s->meta_block_remaining_len) { uint32_t bits; /* Read one byte and ignore it. */ if (!BrotliSafeReadBits(br, 8, &bits)) { result = BROTLI_DECODER_NEEDS_MORE_INPUT; break; } } if (result == BROTLI_DECODER_SUCCESS) { s->state = BROTLI_STATE_METABLOCK_DONE; } break; case BROTLI_STATE_METABLOCK_HEADER_2: { uint32_t bits; if (!BrotliSafeReadBits(br, 6, &bits)) { result = BROTLI_DECODER_NEEDS_MORE_INPUT; break; } s->distance_postfix_bits = bits & BitMask(2); bits >>= 2; s->num_direct_distance_codes = bits << s->distance_postfix_bits; BROTLI_LOG_UINT(s->num_direct_distance_codes); BROTLI_LOG_UINT(s->distance_postfix_bits); s->context_modes = (uint8_t*)BROTLI_DECODER_ALLOC(s, (size_t)s->num_block_types[0]); if (s->context_modes == 0) { result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES); break; } s->loop_counter = 0; s->state = BROTLI_STATE_CONTEXT_MODES; } /* Fall through. */ case BROTLI_STATE_CONTEXT_MODES: result = ReadContextModes(s); if (result != BROTLI_DECODER_SUCCESS) { break; } s->state = BROTLI_STATE_CONTEXT_MAP_1; /* Fall through. */ case BROTLI_STATE_CONTEXT_MAP_1: result = DecodeContextMap( s->num_block_types[0] << BROTLI_LITERAL_CONTEXT_BITS, &s->num_literal_htrees, &s->context_map, s); if (result != BROTLI_DECODER_SUCCESS) { break; } DetectTrivialLiteralBlockTypes(s); s->state = BROTLI_STATE_CONTEXT_MAP_2; /* Fall through. */ case BROTLI_STATE_CONTEXT_MAP_2: { uint32_t npostfix = s->distance_postfix_bits; uint32_t ndirect = s->num_direct_distance_codes; uint32_t distance_alphabet_size_max = BROTLI_DISTANCE_ALPHABET_SIZE( npostfix, ndirect, BROTLI_MAX_DISTANCE_BITS); uint32_t distance_alphabet_size_limit = distance_alphabet_size_max; BROTLI_BOOL allocation_success = BROTLI_TRUE; if (s->large_window) { BrotliDistanceCodeLimit limit = BrotliCalculateDistanceCodeLimit( BROTLI_MAX_ALLOWED_DISTANCE, npostfix, ndirect); distance_alphabet_size_max = BROTLI_DISTANCE_ALPHABET_SIZE( npostfix, ndirect, BROTLI_LARGE_MAX_DISTANCE_BITS); distance_alphabet_size_limit = limit.max_alphabet_size; } result = DecodeContextMap( s->num_block_types[2] << BROTLI_DISTANCE_CONTEXT_BITS, &s->num_dist_htrees, &s->dist_context_map, s); if (result != BROTLI_DECODER_SUCCESS) { break; } allocation_success &= BrotliDecoderHuffmanTreeGroupInit( s, &s->literal_hgroup, BROTLI_NUM_LITERAL_SYMBOLS, BROTLI_NUM_LITERAL_SYMBOLS, s->num_literal_htrees); allocation_success &= BrotliDecoderHuffmanTreeGroupInit( s, &s->insert_copy_hgroup, BROTLI_NUM_COMMAND_SYMBOLS, BROTLI_NUM_COMMAND_SYMBOLS, s->num_block_types[1]); allocation_success &= BrotliDecoderHuffmanTreeGroupInit( s, &s->distance_hgroup, distance_alphabet_size_max, distance_alphabet_size_limit, s->num_dist_htrees); if (!allocation_success) { return SaveErrorCode(s, BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS)); } s->loop_counter = 0; s->state = BROTLI_STATE_TREE_GROUP; } /* Fall through. */ case BROTLI_STATE_TREE_GROUP: { HuffmanTreeGroup* hgroup = NULL; switch (s->loop_counter) { case 0: hgroup = &s->literal_hgroup; break; case 1: hgroup = &s->insert_copy_hgroup; break; case 2: hgroup = &s->distance_hgroup; break; default: return SaveErrorCode(s, BROTLI_FAILURE( BROTLI_DECODER_ERROR_UNREACHABLE)); } result = HuffmanTreeGroupDecode(hgroup, s); if (result != BROTLI_DECODER_SUCCESS) break; s->loop_counter++; if (s->loop_counter < 3) { break; } s->state = BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_BODY; } /* Fall through. */ case BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_BODY: PrepareLiteralDecoding(s); s->dist_context_map_slice = s->dist_context_map; s->htree_command = s->insert_copy_hgroup.htrees[0]; if (!BrotliEnsureRingBuffer(s)) { result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2); break; } CalculateDistanceLut(s); s->state = BROTLI_STATE_COMMAND_BEGIN; /* Fall through. */ case BROTLI_STATE_COMMAND_BEGIN: /* Fall through. */ case BROTLI_STATE_COMMAND_INNER: /* Fall through. */ case BROTLI_STATE_COMMAND_POST_DECODE_LITERALS: /* Fall through. */ case BROTLI_STATE_COMMAND_POST_WRAP_COPY: result = ProcessCommands(s); if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) { result = SafeProcessCommands(s); } break; case BROTLI_STATE_COMMAND_INNER_WRITE: /* Fall through. */ case BROTLI_STATE_COMMAND_POST_WRITE_1: /* Fall through. */ case BROTLI_STATE_COMMAND_POST_WRITE_2: result = WriteRingBuffer( s, available_out, next_out, total_out, BROTLI_FALSE); if (result != BROTLI_DECODER_SUCCESS) { break; } WrapRingBuffer(s); if (s->ringbuffer_size == 1 << s->window_bits) { s->max_distance = s->max_backward_distance; } if (s->state == BROTLI_STATE_COMMAND_POST_WRITE_1) { if (s->meta_block_remaining_len == 0) { /* Next metablock, if any. */ s->state = BROTLI_STATE_METABLOCK_DONE; } else { s->state = BROTLI_STATE_COMMAND_BEGIN; } break; } else if (s->state == BROTLI_STATE_COMMAND_POST_WRITE_2) { s->state = BROTLI_STATE_COMMAND_POST_WRAP_COPY; } else { /* BROTLI_STATE_COMMAND_INNER_WRITE */ if (s->loop_counter == 0) { if (s->meta_block_remaining_len == 0) { s->state = BROTLI_STATE_METABLOCK_DONE; } else { s->state = BROTLI_STATE_COMMAND_POST_DECODE_LITERALS; } break; } s->state = BROTLI_STATE_COMMAND_INNER; } break; case BROTLI_STATE_METABLOCK_DONE: if (s->meta_block_remaining_len < 0) { result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2); break; } BrotliDecoderStateCleanupAfterMetablock(s); if (!s->is_last_metablock) { s->state = BROTLI_STATE_METABLOCK_BEGIN; break; } if (!BrotliJumpToByteBoundary(br)) { result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_PADDING_2); break; } if (s->buffer_length == 0) { BrotliBitReaderUnload(br); *available_in = br->avail_in; *next_in = br->next_in; } s->state = BROTLI_STATE_DONE; /* Fall through. */ case BROTLI_STATE_DONE: if (s->ringbuffer != 0) { result = WriteRingBuffer( s, available_out, next_out, total_out, BROTLI_TRUE); if (result != BROTLI_DECODER_SUCCESS) { break; } } return SaveErrorCode(s, result); } } return SaveErrorCode(s, result); } BROTLI_BOOL BrotliDecoderHasMoreOutput(const BrotliDecoderState* s) { /* After unrecoverable error remaining output is considered nonsensical. */ if ((int)s->error_code < 0) { return BROTLI_FALSE; } return TO_BROTLI_BOOL( s->ringbuffer != 0 && UnwrittenBytes(s, BROTLI_FALSE) != 0); } const uint8_t* BrotliDecoderTakeOutput(BrotliDecoderState* s, size_t* size) { uint8_t* result = 0; size_t available_out = *size ? *size : 1u << 24; size_t requested_out = available_out; BrotliDecoderErrorCode status; if ((s->ringbuffer == 0) || ((int)s->error_code < 0)) { *size = 0; return 0; } WrapRingBuffer(s); status = WriteRingBuffer(s, &available_out, &result, 0, BROTLI_TRUE); /* Either WriteRingBuffer returns those "success" codes... */ if (status == BROTLI_DECODER_SUCCESS || status == BROTLI_DECODER_NEEDS_MORE_OUTPUT) { *size = requested_out - available_out; } else { /* ... or stream is broken. Normally this should be caught by BrotliDecoderDecompressStream, this is just a safeguard. */ if ((int)status < 0) SaveErrorCode(s, status); *size = 0; result = 0; } return result; } BROTLI_BOOL BrotliDecoderIsUsed(const BrotliDecoderState* s) { return TO_BROTLI_BOOL(s->state != BROTLI_STATE_UNINITED || BrotliGetAvailableBits(&s->br) != 0); } BROTLI_BOOL BrotliDecoderIsFinished(const BrotliDecoderState* s) { return TO_BROTLI_BOOL(s->state == BROTLI_STATE_DONE) && !BrotliDecoderHasMoreOutput(s); } BrotliDecoderErrorCode BrotliDecoderGetErrorCode(const BrotliDecoderState* s) { return (BrotliDecoderErrorCode)s->error_code; } const char* BrotliDecoderErrorString(BrotliDecoderErrorCode c) { switch (c) { #define BROTLI_ERROR_CODE_CASE_(PREFIX, NAME, CODE) \ case BROTLI_DECODER ## PREFIX ## NAME: return #NAME; #define BROTLI_NOTHING_ BROTLI_DECODER_ERROR_CODES_LIST(BROTLI_ERROR_CODE_CASE_, BROTLI_NOTHING_) #undef BROTLI_ERROR_CODE_CASE_ #undef BROTLI_NOTHING_ default: return "INVALID"; } } uint32_t BrotliDecoderVersion(void) { return BROTLI_VERSION; } #if defined(__cplusplus) || defined(c_plusplus) } /* extern "C" */ #endif
502743.c
/* * Copyright (C) 2001 Dave Engebretsen, IBM Corporation * Copyright (C) 2003 Anton Blanchard <[email protected]>, IBM * * pSeries specific routines for PCI. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/init.h> #include <linux/ioport.h> #include <linux/kernel.h> #include <linux/pci.h> #include <linux/string.h> #include <asm/pci-bridge.h> #include <asm/prom.h> #include <asm/ppc-pci.h> #if 0 void pcibios_name_device(struct pci_dev *dev) { struct device_node *dn; /* * Add IBM loc code (slot) as a prefix to the device names for service */ dn = pci_device_to_OF_node(dev); if (dn) { char *loc_code = get_property(dn, "ibm,loc-code", 0); if (loc_code) { int loc_len = strlen(loc_code); if (loc_len < sizeof(dev->dev.name)) { memmove(dev->dev.name+loc_len+1, dev->dev.name, sizeof(dev->dev.name)-loc_len-1); memcpy(dev->dev.name, loc_code, loc_len); dev->dev.name[loc_len] = ' '; dev->dev.name[sizeof(dev->dev.name)-1] = '\0'; } } } } DECLARE_PCI_FIXUP_HEADER(PCI_ANY_ID, PCI_ANY_ID, pcibios_name_device); #endif static void __init pSeries_request_regions(void) { if (!isa_io_base) return; request_region(0x20,0x20,"pic1"); request_region(0xa0,0x20,"pic2"); request_region(0x00,0x20,"dma1"); request_region(0x40,0x20,"timer"); request_region(0x80,0x10,"dma page reg"); request_region(0xc0,0x20,"dma2"); } void __init pSeries_final_fixup(void) { pSeries_request_regions(); pci_addr_cache_build(); } /* * Assume the winbond 82c105 is the IDE controller on a * p610/p615/p630. We should probably be more careful in case * someone tries to plug in a similar adapter. */ static void fixup_winbond_82c105(struct pci_dev* dev) { int i; unsigned int reg; if (!machine_is(pseries)) return; printk("Using INTC for W82c105 IDE controller.\n"); pci_read_config_dword(dev, 0x40, &reg); /* Enable LEGIRQ to use INTC instead of ISA interrupts */ pci_write_config_dword(dev, 0x40, reg | (1<<11)); for (i = 0; i < DEVICE_COUNT_RESOURCE; ++i) { /* zap the 2nd function of the winbond chip */ if (dev->resource[i].flags & IORESOURCE_IO && dev->bus->number == 0 && dev->devfn == 0x81) dev->resource[i].flags &= ~IORESOURCE_IO; if (dev->resource[i].start == 0 && dev->resource[i].end) { dev->resource[i].flags = 0; dev->resource[i].end = 0; } } } DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_WINBOND, PCI_DEVICE_ID_WINBOND_82C105, fixup_winbond_82c105);
75733.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % RRRR AAA W W % % R R A A W W % % RRRR AAAAA W W W % % R R A A WW WW % % R R A A W W % % % % % % Read/Write RAW Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/colorspace.h" #include "MagickCore/constitute.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum-private.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" /* Forward declarations. */ static MagickBooleanType WriteRAWImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d R A W I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadRAWImage() reads an image of raw samples and returns it. It allocates % the memory necessary for the new Image structure and returns a pointer to % the new image. % % The format of the ReadRAWImage method is: % % Image *ReadRAWImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadRAWImage(const ImageInfo *image_info,ExceptionInfo *exception) { const unsigned char *pixels; Image *canvas_image, *image; MagickBooleanType status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; size_t length; ssize_t count, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); /* Create virtual canvas to support cropping (i.e. image.gray[100x100+10+20]). */ canvas_image=CloneImage(image,image->extract_info.width,1,MagickFalse, exception); (void) SetImageVirtualPixelMethod(canvas_image,BlackVirtualPixelMethod, exception); quantum_type=GrayQuantum; quantum_info=AcquireQuantumInfo(image_info,canvas_image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(const unsigned char *) NULL; if (image_info->number_scenes != 0) while (image->scene < image_info->scene) { /* Skip to next image. */ image->scene++; length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) break; } } scene=0; count=0; length=0; do { /* Read pixels to virtual canvas image then push to image. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, image->columns,1,exception); q=QueueAuthenticPixels(image,0,y-image->extract_info.y,image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,GetPixelRed(canvas_image,p),q); SetPixelGreen(image,GetPixelGreen(canvas_image,p),q); SetPixelBlue(image,GetPixelBlue(canvas_image,p),q); p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); } SetQuantumImageType(image,quantum_type); /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (count == (ssize_t) length) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } scene++; } while (count == (ssize_t) length); quantum_info=DestroyQuantumInfo(quantum_info); canvas_image=DestroyImage(canvas_image); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r R A W I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterRAWImage() adds attributes for the RAW image format to the list of % supported formats. The attributes include the image format tag, a method to % read and/or write the format, whether the format supports the saving of % more than one frame to the same file or blob, whether the format supports % native in-memory I/O, and a brief description of the format. % % The format of the RegisterRAWImage method is: % % size_t RegisterRAWImage(void) % */ ModuleExport size_t RegisterRAWImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("RAW","R","Raw red samples"); entry->decoder=(DecodeImageHandler *) ReadRAWImage; entry->encoder=(EncodeImageHandler *) WriteRAWImage; entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; entry->format_type=ImplicitFormatType; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("RAW","C","Raw cyan samples"); entry->decoder=(DecodeImageHandler *) ReadRAWImage; entry->encoder=(EncodeImageHandler *) WriteRAWImage; entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; entry->format_type=ImplicitFormatType; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("RAW","G","Raw green samples"); entry->decoder=(DecodeImageHandler *) ReadRAWImage; entry->encoder=(EncodeImageHandler *) WriteRAWImage; entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; entry->format_type=ImplicitFormatType; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("RAW","M","Raw magenta samples"); entry->decoder=(DecodeImageHandler *) ReadRAWImage; entry->encoder=(EncodeImageHandler *) WriteRAWImage; entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; entry->format_type=ImplicitFormatType; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("RAW","B","Raw blue samples"); entry->decoder=(DecodeImageHandler *) ReadRAWImage; entry->encoder=(EncodeImageHandler *) WriteRAWImage; entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; entry->format_type=ImplicitFormatType; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("RAW","Y","Raw yellow samples"); entry->decoder=(DecodeImageHandler *) ReadRAWImage; entry->encoder=(EncodeImageHandler *) WriteRAWImage; entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; entry->format_type=ImplicitFormatType; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("RAW","A","Raw alpha samples"); entry->decoder=(DecodeImageHandler *) ReadRAWImage; entry->encoder=(EncodeImageHandler *) WriteRAWImage; entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; entry->format_type=ImplicitFormatType; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("RAW","O","Raw opacity samples"); entry->decoder=(DecodeImageHandler *) ReadRAWImage; entry->encoder=(EncodeImageHandler *) WriteRAWImage; entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; entry->format_type=ImplicitFormatType; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("RAW","K","Raw black samples"); entry->decoder=(DecodeImageHandler *) ReadRAWImage; entry->encoder=(EncodeImageHandler *) WriteRAWImage; entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; entry->format_type=ImplicitFormatType; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r R A W I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterRAWImage() removes format registrations made by the RAW module % from the list of supported formats. % % The format of the UnregisterRAWImage method is: % % UnregisterRAWImage(void) % */ ModuleExport void UnregisterRAWImage(void) { (void) UnregisterMagickInfo("R"); (void) UnregisterMagickInfo("C"); (void) UnregisterMagickInfo("G"); (void) UnregisterMagickInfo("M"); (void) UnregisterMagickInfo("B"); (void) UnregisterMagickInfo("Y"); (void) UnregisterMagickInfo("A"); (void) UnregisterMagickInfo("O"); (void) UnregisterMagickInfo("K"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e R A W I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteRAWImage() writes an image to a file as raw intensity values. % % The format of the WriteRAWImage method is: % % MagickBooleanType WriteRAWImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteRAWImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; MagickBooleanType status; register const Quantum *p; size_t length; ssize_t count, y; unsigned char *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); switch (*image->magick) { case 'A': case 'a': { quantum_type=AlphaQuantum; break; } case 'B': case 'b': { quantum_type=BlueQuantum; break; } case 'C': case 'c': { quantum_type=CyanQuantum; if (image->colorspace == CMYKColorspace) break; ThrowWriterException(ImageError,"ColorSeparatedImageRequired"); } case 'g': case 'G': { quantum_type=GreenQuantum; break; } case 'I': case 'i': { quantum_type=IndexQuantum; break; } case 'K': case 'k': { quantum_type=BlackQuantum; if (image->colorspace == CMYKColorspace) break; ThrowWriterException(ImageError,"ColorSeparatedImageRequired"); } case 'M': case 'm': { quantum_type=MagentaQuantum; if (image->colorspace == CMYKColorspace) break; ThrowWriterException(ImageError,"ColorSeparatedImageRequired"); } case 'o': case 'O': { quantum_type=OpacityQuantum; break; } case 'R': case 'r': { quantum_type=RedQuantum; break; } case 'Y': case 'y': { quantum_type=YellowQuantum; if (image->colorspace == CMYKColorspace) break; ThrowWriterException(ImageError,"ColorSeparatedImageRequired"); } default: { quantum_type=GrayQuantum; break; } } scene=0; do { /* Convert image to RAW raster pixels. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
742511.c
// Feature tests of typechecking new Checked C bounds declarations. // // The following lines are for the LLVM test harness: // // RUN: %clang_cc1 -Wno-check-bounds-decls -verify -verify-ignore-unexpected=note %s #include <stdchecked.h> _Static_assert(sizeof(void*) > sizeof(long), "Pointers must be larger than longs"); void int_local_var_bounds_decl(void) { // bounds declarations are allowed for integer variables to support // casting of pointers to integers and back. We usually expect this // to happen within expressions, but to allow uniform use of language // features, we allow bounds on integer-typed variables. int a1 checked[5]; long int t22 : byte_count(5 * sizeof(int)) = (long int)a1; // expected-warning {{cast to smaller integer type 'long' from '_Array_ptr<int>'}} unsigned long int t23 : byte_count(5 * sizeof(int)) = (unsigned long int) a1; // expected-warning {{cast to smaller integer type 'unsigned long' from '_Array_ptr<int>'}} }
765257.c
/* * Copyright 2004-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/opensslconf.h> #ifdef OPENSSL_NO_SRP NON_EMPTY_TRANSLATION_UNIT #else # include <stdio.h> # include <stdlib.h> # include <string.h> # include <openssl/conf.h> # include <openssl/bio.h> # include <openssl/err.h> # include <openssl/txt_db.h> # include <openssl/buffer.h> # include <openssl/srp.h> # include "apps.h" # define BASE_SECTION "srp" # define CONFIG_FILE "openssl.cnf" # define ENV_RANDFILE "RANDFILE" # define ENV_DATABASE "srpvfile" # define ENV_DEFAULT_SRP "default_srp" static int get_index(CA_DB *db, char *id, char type) { char **pp; int i; if (id == NULL) return -1; if (type == DB_SRP_INDEX) { for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { pp = sk_OPENSSL_PSTRING_value(db->db->data, i); if (pp[DB_srptype][0] == DB_SRP_INDEX && strcmp(id, pp[DB_srpid]) == 0) return i; } } else { for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { pp = sk_OPENSSL_PSTRING_value(db->db->data, i); if (pp[DB_srptype][0] != DB_SRP_INDEX && strcmp(id, pp[DB_srpid]) == 0) return i; } } return -1; } static void print_entry(CA_DB *db, int indx, int verbose, char *s) { if (indx >= 0 && verbose) { int j; char **pp = sk_OPENSSL_PSTRING_value(db->db->data, indx); BIO_printf(bio_err, "%s \"%s\"\n", s, pp[DB_srpid]); for (j = 0; j < DB_NUMBER; j++) { BIO_printf(bio_err, " %d = \"%s\"\n", j, pp[j]); } } } static void print_index(CA_DB *db, int indexindex, int verbose) { print_entry(db, indexindex, verbose, "g N entry"); } static void print_user(CA_DB *db, int userindex, int verbose) { if (verbose > 0) { char **pp = sk_OPENSSL_PSTRING_value(db->db->data, userindex); if (pp[DB_srptype][0] != 'I') { print_entry(db, userindex, verbose, "User entry"); print_entry(db, get_index(db, pp[DB_srpgN], 'I'), verbose, "g N entry"); } } } static int update_index(CA_DB *db, char **row) { char **irow; int i; irow = app_malloc(sizeof(*irow) * (DB_NUMBER + 1), "row pointers"); for (i = 0; i < DB_NUMBER; i++) irow[i] = row[i]; irow[DB_NUMBER] = NULL; if (!TXT_DB_insert(db->db, irow)) { BIO_printf(bio_err, "failed to update srpvfile\n"); BIO_printf(bio_err, "TXT_DB error number %ld\n", db->db->error); OPENSSL_free(irow); return 0; } return 1; } static char *lookup_conf(const CONF *conf, const char *section, const char *tag) { char *entry = NCONF_get_string(conf, section, tag); if (entry == NULL) BIO_printf(bio_err, "variable lookup failed for %s::%s\n", section, tag); return entry; } static char *srp_verify_user(const char *user, const char *srp_verifier, char *srp_usersalt, const char *g, const char *N, const char *passin, int verbose) { char password[1025]; PW_CB_DATA cb_tmp; char *verifier = NULL; char *gNid = NULL; int len; cb_tmp.prompt_info = user; cb_tmp.password = passin; len = password_callback(password, sizeof(password)-1, 0, &cb_tmp); if (len > 0) { password[len] = 0; if (verbose) BIO_printf(bio_err, "Validating\n user=\"%s\"\n srp_verifier=\"%s\"\n srp_usersalt=\"%s\"\n g=\"%s\"\n N=\"%s\"\n", user, srp_verifier, srp_usersalt, g, N); if (verbose > 1) BIO_printf(bio_err, "Pass %s\n", password); OPENSSL_assert(srp_usersalt != NULL); if (!(gNid = SRP_create_verifier(user, password, &srp_usersalt, &verifier, N, g)) ) { BIO_printf(bio_err, "Internal error validating SRP verifier\n"); } else { if (strcmp(verifier, srp_verifier)) gNid = NULL; OPENSSL_free(verifier); } OPENSSL_cleanse(password, len); } return gNid; } static char *srp_create_user(char *user, char **srp_verifier, char **srp_usersalt, char *g, char *N, char *passout, int verbose) { char password[1025]; PW_CB_DATA cb_tmp; char *gNid = NULL; char *salt = NULL; int len; cb_tmp.prompt_info = user; cb_tmp.password = passout; len = password_callback(password, sizeof(password)-1, 1, &cb_tmp); if (len > 0) { password[len] = 0; if (verbose) BIO_printf(bio_err, "Creating\n user=\"%s\"\n g=\"%s\"\n N=\"%s\"\n", user, g, N); if (!(gNid = SRP_create_verifier(user, password, &salt, srp_verifier, N, g)) ) { BIO_printf(bio_err, "Internal error creating SRP verifier\n"); } else { *srp_usersalt = salt; } OPENSSL_cleanse(password, len); if (verbose > 1) BIO_printf(bio_err, "gNid=%s salt =\"%s\"\n verifier =\"%s\"\n", gNid, salt, *srp_verifier); } return gNid; } typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_VERBOSE, OPT_CONFIG, OPT_NAME, OPT_SRPVFILE, OPT_ADD, OPT_DELETE, OPT_MODIFY, OPT_LIST, OPT_GN, OPT_USERINFO, OPT_PASSIN, OPT_PASSOUT, OPT_ENGINE } OPTION_CHOICE; OPTIONS srp_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"verbose", OPT_VERBOSE, '-', "Talk a lot while doing things"}, {"config", OPT_CONFIG, '<', "A config file"}, {"name", OPT_NAME, 's', "The particular srp definition to use"}, {"srpvfile", OPT_SRPVFILE, '<', "The srp verifier file name"}, {"add", OPT_ADD, '-', "Add a user and srp verifier"}, {"modify", OPT_MODIFY, '-', "Modify the srp verifier of an existing user"}, {"delete", OPT_DELETE, '-', "Delete user from verifier file"}, {"list", OPT_LIST, '-', "List users"}, {"gn", OPT_GN, 's', "Set g and N values to be used for new verifier"}, {"userinfo", OPT_USERINFO, 's', "Additional info to be set for user"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, # ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, # endif {NULL} }; int srp_main(int argc, char **argv) { ENGINE *e = NULL; CA_DB *db = NULL; CONF *conf = NULL; int gNindex = -1, maxgN = -1, ret = 1, errors = 0, verbose = 0, i; int doupdatedb = 0, mode = OPT_ERR; char *user = NULL, *passinarg = NULL, *passoutarg = NULL; char *passin = NULL, *passout = NULL, *gN = NULL, *userinfo = NULL; char *randfile = NULL, *section = NULL; char **gNrow = NULL, *configfile = NULL; char *srpvfile = NULL, **pp, *prog; OPTION_CHOICE o; prog = opt_init(argc, argv, srp_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(srp_options); ret = 0; goto end; case OPT_VERBOSE: verbose++; break; case OPT_CONFIG: configfile = opt_arg(); break; case OPT_NAME: section = opt_arg(); break; case OPT_SRPVFILE: srpvfile = opt_arg(); break; case OPT_ADD: case OPT_DELETE: case OPT_MODIFY: case OPT_LIST: if (mode != OPT_ERR) { BIO_printf(bio_err, "%s: Only one of -add/-delete/-modify/-list\n", prog); goto opthelp; } mode = o; break; case OPT_GN: gN = opt_arg(); break; case OPT_USERINFO: userinfo = opt_arg(); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_PASSOUT: passoutarg = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; } } argc = opt_num_rest(); argv = opt_rest(); if (srpvfile && configfile) { BIO_printf(bio_err, "-srpvfile and -configfile cannot be specified together.\n"); goto end; } if (mode == OPT_ERR) { BIO_printf(bio_err, "Exactly one of the options -add, -delete, -modify -list must be specified.\n"); goto opthelp; } if ((mode == OPT_DELETE || mode == OPT_MODIFY || mode == OPT_ADD) && argc < 1) { BIO_printf(bio_err, "Need at least one user for options -add, -delete, -modify. \n"); goto opthelp; } if ((passinarg || passoutarg) && argc != 1) { BIO_printf(bio_err, "-passin, -passout arguments only valid with one user.\n"); goto opthelp; } if (!app_passwd(passinarg, passoutarg, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } if (!srpvfile) { if (!configfile) configfile = default_config_file; if (verbose) BIO_printf(bio_err, "Using configuration from %s\n", configfile); conf = app_load_config(configfile); if (conf == NULL) goto end; if (configfile != default_config_file && !app_load_modules(conf)) goto end; /* Lets get the config section we are using */ if (section == NULL) { if (verbose) BIO_printf(bio_err, "trying to read " ENV_DEFAULT_SRP " in " BASE_SECTION "\n"); section = lookup_conf(conf, BASE_SECTION, ENV_DEFAULT_SRP); if (section == NULL) goto end; } if (randfile == NULL) randfile = NCONF_get_string(conf, BASE_SECTION, "RANDFILE"); if (verbose) BIO_printf(bio_err, "trying to read " ENV_DATABASE " in section \"%s\"\n", section); srpvfile = lookup_conf(conf, section, ENV_DATABASE); if (srpvfile == NULL) goto end; } if (randfile == NULL) ERR_clear_error(); else app_RAND_load_file(randfile, 0); if (verbose) BIO_printf(bio_err, "Trying to read SRP verifier file \"%s\"\n", srpvfile); db = load_index(srpvfile, NULL); if (db == NULL) goto end; /* Lets check some fields */ for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { pp = sk_OPENSSL_PSTRING_value(db->db->data, i); if (pp[DB_srptype][0] == DB_SRP_INDEX) { maxgN = i; if ((gNindex < 0) && (gN != NULL) && strcmp(gN, pp[DB_srpid]) == 0) gNindex = i; print_index(db, i, verbose > 1); } } if (verbose) BIO_printf(bio_err, "Database initialised\n"); if (gNindex >= 0) { gNrow = sk_OPENSSL_PSTRING_value(db->db->data, gNindex); print_entry(db, gNindex, verbose > 1, "Default g and N"); } else if (maxgN > 0 && !SRP_get_default_gN(gN)) { BIO_printf(bio_err, "No g and N value for index \"%s\"\n", gN); goto end; } else { if (verbose) BIO_printf(bio_err, "Database has no g N information.\n"); gNrow = NULL; } if (verbose > 1) BIO_printf(bio_err, "Starting user processing\n"); if (argc > 0) user = *(argv++); while (mode == OPT_LIST || user) { int userindex = -1; if (user != NULL && verbose > 1) BIO_printf(bio_err, "Processing user \"%s\"\n", user); if ((userindex = get_index(db, user, 'U')) >= 0) { print_user(db, userindex, (verbose > 0) || mode == OPT_LIST); } if (mode == OPT_LIST) { if (user == NULL) { BIO_printf(bio_err, "List all users\n"); for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { print_user(db, i, 1); } } else if (userindex < 0) { BIO_printf(bio_err, "user \"%s\" does not exist, ignored. t\n", user); errors++; } } else if (mode == OPT_ADD) { if (userindex >= 0) { /* reactivation of a new user */ char **row = sk_OPENSSL_PSTRING_value(db->db->data, userindex); BIO_printf(bio_err, "user \"%s\" reactivated.\n", user); row[DB_srptype][0] = 'V'; doupdatedb = 1; } else { char *row[DB_NUMBER]; char *gNid; row[DB_srpverifier] = NULL; row[DB_srpsalt] = NULL; row[DB_srpinfo] = NULL; if (! (gNid = srp_create_user(user, &(row[DB_srpverifier]), &(row[DB_srpsalt]), gNrow ? gNrow[DB_srpsalt] : gN, gNrow ? gNrow[DB_srpverifier] : NULL, passout, verbose))) { BIO_printf(bio_err, "Cannot create srp verifier for user \"%s\", operation abandoned .\n", user); errors++; goto end; } row[DB_srpid] = OPENSSL_strdup(user); row[DB_srptype] = OPENSSL_strdup("v"); row[DB_srpgN] = OPENSSL_strdup(gNid); if ((row[DB_srpid] == NULL) || (row[DB_srpgN] == NULL) || (row[DB_srptype] == NULL) || (row[DB_srpverifier] == NULL) || (row[DB_srpsalt] == NULL) || (userinfo && ((row[DB_srpinfo] = OPENSSL_strdup(userinfo)) == NULL)) || !update_index(db, row)) { OPENSSL_free(row[DB_srpid]); OPENSSL_free(row[DB_srpgN]); OPENSSL_free(row[DB_srpinfo]); OPENSSL_free(row[DB_srptype]); OPENSSL_free(row[DB_srpverifier]); OPENSSL_free(row[DB_srpsalt]); goto end; } doupdatedb = 1; } } else if (mode == OPT_MODIFY) { if (userindex < 0) { BIO_printf(bio_err, "user \"%s\" does not exist, operation ignored.\n", user); errors++; } else { char **row = sk_OPENSSL_PSTRING_value(db->db->data, userindex); char type = row[DB_srptype][0]; if (type == 'v') { BIO_printf(bio_err, "user \"%s\" already updated, operation ignored.\n", user); errors++; } else { char *gNid; if (row[DB_srptype][0] == 'V') { int user_gN; char **irow = NULL; if (verbose) BIO_printf(bio_err, "Verifying password for user \"%s\"\n", user); if ((user_gN = get_index(db, row[DB_srpgN], DB_SRP_INDEX)) >= 0) irow = sk_OPENSSL_PSTRING_value(db->db->data, userindex); if (!srp_verify_user (user, row[DB_srpverifier], row[DB_srpsalt], irow ? irow[DB_srpsalt] : row[DB_srpgN], irow ? irow[DB_srpverifier] : NULL, passin, verbose)) { BIO_printf(bio_err, "Invalid password for user \"%s\", operation abandoned.\n", user); errors++; goto end; } } if (verbose) BIO_printf(bio_err, "Password for user \"%s\" ok.\n", user); if (! (gNid = srp_create_user(user, &(row[DB_srpverifier]), &(row[DB_srpsalt]), gNrow ? gNrow[DB_srpsalt] : NULL, gNrow ? gNrow[DB_srpverifier] : NULL, passout, verbose))) { BIO_printf(bio_err, "Cannot create srp verifier for user \"%s\", operation abandoned.\n", user); errors++; goto end; } row[DB_srptype][0] = 'v'; row[DB_srpgN] = OPENSSL_strdup(gNid); if (row[DB_srpid] == NULL || row[DB_srpgN] == NULL || row[DB_srptype] == NULL || row[DB_srpverifier] == NULL || row[DB_srpsalt] == NULL || (userinfo && ((row[DB_srpinfo] = OPENSSL_strdup(userinfo)) == NULL))) goto end; doupdatedb = 1; } } } else if (mode == OPT_DELETE) { if (userindex < 0) { BIO_printf(bio_err, "user \"%s\" does not exist, operation ignored. t\n", user); errors++; } else { char **xpp = sk_OPENSSL_PSTRING_value(db->db->data, userindex); BIO_printf(bio_err, "user \"%s\" revoked. t\n", user); xpp[DB_srptype][0] = 'R'; doupdatedb = 1; } } if (--argc > 0) { user = *(argv++); } else { /* no more processing in any mode if no users left */ break; } } if (verbose) BIO_printf(bio_err, "User procession done.\n"); if (doupdatedb) { /* Lets check some fields */ for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { pp = sk_OPENSSL_PSTRING_value(db->db->data, i); if (pp[DB_srptype][0] == 'v') { pp[DB_srptype][0] = 'V'; print_user(db, i, verbose); } } if (verbose) BIO_printf(bio_err, "Trying to update srpvfile.\n"); if (!save_index(srpvfile, "new", db)) goto end; if (verbose) BIO_printf(bio_err, "Temporary srpvfile created.\n"); if (!rotate_index(srpvfile, "new", "old")) goto end; if (verbose) BIO_printf(bio_err, "srpvfile updated.\n"); } ret = (errors != 0); end: if (errors != 0) if (verbose) BIO_printf(bio_err, "User errors %d.\n", errors); if (verbose) BIO_printf(bio_err, "SRP terminating with code %d.\n", ret); OPENSSL_free(passin); OPENSSL_free(passout); if (ret) ERR_print_errors(bio_err); if (randfile) app_RAND_write_file(randfile); NCONF_free(conf); free_index(db); release_engine(e); return (ret); } #endif
264982.c
/* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "NR-RRC-Definitions" * found in "../../../rrc_15.5.1_asn.asn1" * `asn1c -D ./rrc_out_hlal -fcompound-names -fno-include-deps -findirect-choice -gen-PER -no-gen-example` */ #include "RRCSystemInfoRequest-r15-IEs.h" static int memb_requested_SI_List_constraint_1(const asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { const BIT_STRING_t *st = (const BIT_STRING_t *)sptr; size_t size; if(!sptr) { ASN__CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name, __FILE__, __LINE__); return -1; } if(st->size > 0) { /* Size in bits */ size = 8 * st->size - (st->bits_unused & 0x07); } else { size = 0; } if((size == 32)) { /* Constraint check succeeded */ return 0; } else { ASN__CTFAIL(app_key, td, sptr, "%s: constraint failed (%s:%d)", td->name, __FILE__, __LINE__); return -1; } } static int memb_spare_constraint_1(const asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { const BIT_STRING_t *st = (const BIT_STRING_t *)sptr; size_t size; if(!sptr) { ASN__CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name, __FILE__, __LINE__); return -1; } if(st->size > 0) { /* Size in bits */ size = 8 * st->size - (st->bits_unused & 0x07); } else { size = 0; } if((size == 12)) { /* Constraint check succeeded */ return 0; } else { ASN__CTFAIL(app_key, td, sptr, "%s: constraint failed (%s:%d)", td->name, __FILE__, __LINE__); return -1; } } static asn_oer_constraints_t asn_OER_memb_requested_SI_List_constr_2 CC_NOTUSED = { { 0, 0 }, 32 /* (SIZE(32..32)) */}; static asn_per_constraints_t asn_PER_memb_requested_SI_List_constr_2 CC_NOTUSED = { { APC_UNCONSTRAINED, -1, -1, 0, 0 }, { APC_CONSTRAINED, 0, 0, 32, 32 } /* (SIZE(32..32)) */, 0, 0 /* No PER value map */ }; static asn_oer_constraints_t asn_OER_memb_spare_constr_3 CC_NOTUSED = { { 0, 0 }, 12 /* (SIZE(12..12)) */}; static asn_per_constraints_t asn_PER_memb_spare_constr_3 CC_NOTUSED = { { APC_UNCONSTRAINED, -1, -1, 0, 0 }, { APC_CONSTRAINED, 0, 0, 12, 12 } /* (SIZE(12..12)) */, 0, 0 /* No PER value map */ }; asn_TYPE_member_t asn_MBR_RRCSystemInfoRequest_r15_IEs_1[] = { { ATF_NOFLAGS, 0, offsetof(struct RRCSystemInfoRequest_r15_IEs, requested_SI_List), (ASN_TAG_CLASS_CONTEXT | (0 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_BIT_STRING, 0, { &asn_OER_memb_requested_SI_List_constr_2, &asn_PER_memb_requested_SI_List_constr_2, memb_requested_SI_List_constraint_1 }, 0, 0, /* No default value */ "requested-SI-List" }, { ATF_NOFLAGS, 0, offsetof(struct RRCSystemInfoRequest_r15_IEs, spare), (ASN_TAG_CLASS_CONTEXT | (1 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_BIT_STRING, 0, { &asn_OER_memb_spare_constr_3, &asn_PER_memb_spare_constr_3, memb_spare_constraint_1 }, 0, 0, /* No default value */ "spare" }, }; static const ber_tlv_tag_t asn_DEF_RRCSystemInfoRequest_r15_IEs_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static const asn_TYPE_tag2member_t asn_MAP_RRCSystemInfoRequest_r15_IEs_tag2el_1[] = { { (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* requested-SI-List */ { (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 } /* spare */ }; asn_SEQUENCE_specifics_t asn_SPC_RRCSystemInfoRequest_r15_IEs_specs_1 = { sizeof(struct RRCSystemInfoRequest_r15_IEs), offsetof(struct RRCSystemInfoRequest_r15_IEs, _asn_ctx), asn_MAP_RRCSystemInfoRequest_r15_IEs_tag2el_1, 2, /* Count of tags in the map */ 0, 0, 0, /* Optional elements (not needed) */ -1, /* First extension addition */ }; asn_TYPE_descriptor_t asn_DEF_RRCSystemInfoRequest_r15_IEs = { "RRCSystemInfoRequest-r15-IEs", "RRCSystemInfoRequest-r15-IEs", &asn_OP_SEQUENCE, asn_DEF_RRCSystemInfoRequest_r15_IEs_tags_1, sizeof(asn_DEF_RRCSystemInfoRequest_r15_IEs_tags_1) /sizeof(asn_DEF_RRCSystemInfoRequest_r15_IEs_tags_1[0]), /* 1 */ asn_DEF_RRCSystemInfoRequest_r15_IEs_tags_1, /* Same as above */ sizeof(asn_DEF_RRCSystemInfoRequest_r15_IEs_tags_1) /sizeof(asn_DEF_RRCSystemInfoRequest_r15_IEs_tags_1[0]), /* 1 */ { 0, 0, SEQUENCE_constraint }, asn_MBR_RRCSystemInfoRequest_r15_IEs_1, 2, /* Elements count */ &asn_SPC_RRCSystemInfoRequest_r15_IEs_specs_1 /* Additional specs */ };
604860.c
/* lzo1x_9x.c -- implementation of the LZO1X-999 compression algorithm This file is part of the LZO real-time data compression library. Copyright (C) 1996-2014 Markus Franz Xaver Johannes Oberhumer All Rights Reserved. The LZO library 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. The LZO 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 a copy of the GNU General Public License along with the LZO library; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Markus F.X.J. Oberhumer <[email protected]> http://www.oberhumer.com/opensource/lzo/ */ #if !defined(LZO1X) && !defined(LZO1Y) && !defined(LZO1Z) # define LZO1X 1 #endif #if defined(LZO1X) # include "config1x.h" #elif defined(LZO1Y) # include "config1y.h" #elif defined(LZO1Z) # include "config1z.h" #else # error #endif /*********************************************************************** // ************************************************************************/ #define SWD_N M4_MAX_OFFSET /* size of ring buffer */ #define SWD_THRESHOLD 1 /* lower limit for match length */ #define SWD_F 2048 /* upper limit for match length */ #define SWD_BEST_OFF (LZO_MAX3( M2_MAX_LEN, M3_MAX_LEN, M4_MAX_LEN ) + 1) #if defined(LZO1X) # define LZO_COMPRESS_T lzo1x_999_t # define lzo_swd_t lzo1x_999_swd_t #elif defined(LZO1Y) # define LZO_COMPRESS_T lzo1y_999_t # define lzo_swd_t lzo1y_999_swd_t # define lzo1x_999_compress_internal lzo1y_999_compress_internal # define lzo1x_999_compress_dict lzo1y_999_compress_dict # define lzo1x_999_compress_level lzo1y_999_compress_level # define lzo1x_999_compress lzo1y_999_compress #elif defined(LZO1Z) # define LZO_COMPRESS_T lzo1z_999_t # define lzo_swd_t lzo1z_999_swd_t # define lzo1x_999_compress_internal lzo1z_999_compress_internal # define lzo1x_999_compress_dict lzo1z_999_compress_dict # define lzo1x_999_compress_level lzo1z_999_compress_level # define lzo1x_999_compress lzo1z_999_compress #else # error #endif #if 0 # define HEAD3(b,p) \ ((((((lzo_xint)b[p]<<3)^b[p+1])<<3)^b[p+2]) & (SWD_HSIZE-1)) #endif #if 0 && (LZO_OPT_UNALIGNED32) && (LZO_ABI_LITTLE_ENDIAN) # define HEAD3(b,p) \ (((* (lzo_uint32_tp) &b[p]) ^ ((* (lzo_uint32_tp) &b[p])>>10)) & (SWD_HSIZE-1)) #endif #include "lzo_mchw.ch" /* this is a public functions, but there is no prototype in a header file */ LZO_EXTERN(int) lzo1x_999_compress_internal ( const lzo_bytep in , lzo_uint in_len, lzo_bytep out, lzo_uintp out_len, lzo_voidp wrkmem, const lzo_bytep dict, lzo_uint dict_len, lzo_callback_p cb, int try_lazy_parm, lzo_uint good_length, lzo_uint max_lazy, lzo_uint nice_length, lzo_uint max_chain, lzo_uint32_t flags ); /*********************************************************************** // ************************************************************************/ static lzo_bytep code_match ( LZO_COMPRESS_T *c, lzo_bytep op, lzo_uint m_len, lzo_uint m_off ) { lzo_uint x_len = m_len; lzo_uint x_off = m_off; c->match_bytes += (unsigned long) m_len; #if 0 /* static lzo_uint last_m_len = 0, last_m_off = 0; static lzo_uint prev_m_off[4]; static unsigned prev_m_off_ptr = 0; unsigned i; //if (m_len >= 3 && m_len <= M2_MAX_LEN && m_off <= M2_MAX_OFFSET) if (m_len >= 3 && m_len <= M2_MAX_LEN) { //if (m_len == last_m_len && m_off == last_m_off) //printf("last_m_len + last_m_off\n"); //else if (m_off == last_m_off) printf("last_m_off\n"); else { for (i = 0; i < 4; i++) if (m_off == prev_m_off[i]) printf("prev_m_off %u: %5ld\n",i,(long)m_off); } } last_m_len = m_len; last_m_off = prev_m_off[prev_m_off_ptr] = m_off; prev_m_off_ptr = (prev_m_off_ptr + 1) & 3; */ #endif assert(op > c->out); if (m_len == 2) { assert(m_off <= M1_MAX_OFFSET); assert(c->r1_lit > 0); assert(c->r1_lit < 4); m_off -= 1; #if defined(LZO1Z) *op++ = LZO_BYTE(M1_MARKER | (m_off >> 6)); *op++ = LZO_BYTE(m_off << 2); #else *op++ = LZO_BYTE(M1_MARKER | ((m_off & 3) << 2)); *op++ = LZO_BYTE(m_off >> 2); #endif c->m1a_m++; } #if defined(LZO1Z) else if (m_len <= M2_MAX_LEN && (m_off <= M2_MAX_OFFSET || m_off == c->last_m_off)) #else else if (m_len <= M2_MAX_LEN && m_off <= M2_MAX_OFFSET) #endif { assert(m_len >= 3); #if defined(LZO1X) m_off -= 1; *op++ = LZO_BYTE(((m_len - 1) << 5) | ((m_off & 7) << 2)); *op++ = LZO_BYTE(m_off >> 3); assert(op[-2] >= M2_MARKER); #elif defined(LZO1Y) m_off -= 1; *op++ = LZO_BYTE(((m_len + 1) << 4) | ((m_off & 3) << 2)); *op++ = LZO_BYTE(m_off >> 2); assert(op[-2] >= M2_MARKER); #elif defined(LZO1Z) if (m_off == c->last_m_off) *op++ = LZO_BYTE(((m_len - 1) << 5) | (0x700 >> 6)); else { m_off -= 1; *op++ = LZO_BYTE(((m_len - 1) << 5) | (m_off >> 6)); *op++ = LZO_BYTE(m_off << 2); } #endif c->m2_m++; } else if (m_len == M2_MIN_LEN && m_off <= MX_MAX_OFFSET && c->r1_lit >= 4) { assert(m_len == 3); assert(m_off > M2_MAX_OFFSET); m_off -= 1 + M2_MAX_OFFSET; #if defined(LZO1Z) *op++ = LZO_BYTE(M1_MARKER | (m_off >> 6)); *op++ = LZO_BYTE(m_off << 2); #else *op++ = LZO_BYTE(M1_MARKER | ((m_off & 3) << 2)); *op++ = LZO_BYTE(m_off >> 2); #endif c->m1b_m++; } else if (m_off <= M3_MAX_OFFSET) { assert(m_len >= 3); m_off -= 1; if (m_len <= M3_MAX_LEN) *op++ = LZO_BYTE(M3_MARKER | (m_len - 2)); else { m_len -= M3_MAX_LEN; *op++ = M3_MARKER | 0; while (m_len > 255) { m_len -= 255; *op++ = 0; } assert(m_len > 0); *op++ = LZO_BYTE(m_len); } #if defined(LZO1Z) *op++ = LZO_BYTE(m_off >> 6); *op++ = LZO_BYTE(m_off << 2); #else *op++ = LZO_BYTE(m_off << 2); *op++ = LZO_BYTE(m_off >> 6); #endif c->m3_m++; } else { lzo_uint k; assert(m_len >= 3); assert(m_off > 0x4000); assert(m_off <= 0xbfff); m_off -= 0x4000; k = (m_off & 0x4000) >> 11; if (m_len <= M4_MAX_LEN) *op++ = LZO_BYTE(M4_MARKER | k | (m_len - 2)); else { m_len -= M4_MAX_LEN; *op++ = LZO_BYTE(M4_MARKER | k | 0); while (m_len > 255) { m_len -= 255; *op++ = 0; } assert(m_len > 0); *op++ = LZO_BYTE(m_len); } #if defined(LZO1Z) *op++ = LZO_BYTE(m_off >> 6); *op++ = LZO_BYTE(m_off << 2); #else *op++ = LZO_BYTE(m_off << 2); *op++ = LZO_BYTE(m_off >> 6); #endif c->m4_m++; } c->last_m_len = x_len; c->last_m_off = x_off; return op; } static lzo_bytep STORE_RUN ( LZO_COMPRESS_T *c, lzo_bytep op, const lzo_bytep ii, lzo_uint t ) { c->lit_bytes += (unsigned long) t; if (op == c->out && t <= 238) { *op++ = LZO_BYTE(17 + t); } else if (t <= 3) { #if defined(LZO1Z) op[-1] = LZO_BYTE(op[-1] | t); #else op[-2] = LZO_BYTE(op[-2] | t); #endif c->lit1_r++; } else if (t <= 18) { *op++ = LZO_BYTE(t - 3); c->lit2_r++; } else { lzo_uint tt = t - 18; *op++ = 0; while (tt > 255) { tt -= 255; *op++ = 0; } assert(tt > 0); *op++ = LZO_BYTE(tt); c->lit3_r++; } do *op++ = *ii++; while (--t > 0); return op; } static lzo_bytep code_run ( LZO_COMPRESS_T *c, lzo_bytep op, const lzo_bytep ii, lzo_uint lit, lzo_uint m_len ) { if (lit > 0) { assert(m_len >= 2); op = STORE_RUN(c,op,ii,lit); c->r1_m_len = m_len; c->r1_lit = lit; } else { assert(m_len >= 3); c->r1_m_len = 0; c->r1_lit = 0; } return op; } /*********************************************************************** // ************************************************************************/ static lzo_uint len_of_coded_match ( lzo_uint m_len, lzo_uint m_off, lzo_uint lit ) { lzo_uint n = 4; if (m_len < 2) return 0; if (m_len == 2) return (m_off <= M1_MAX_OFFSET && lit > 0 && lit < 4) ? 2 : 0; if (m_len <= M2_MAX_LEN && m_off <= M2_MAX_OFFSET) return 2; if (m_len == M2_MIN_LEN && m_off <= MX_MAX_OFFSET && lit >= 4) return 2; if (m_off <= M3_MAX_OFFSET) { if (m_len <= M3_MAX_LEN) return 3; m_len -= M3_MAX_LEN; while (m_len > 255) { m_len -= 255; n++; } return n; } if (m_off <= M4_MAX_OFFSET) { if (m_len <= M4_MAX_LEN) return 3; m_len -= M4_MAX_LEN; while (m_len > 255) { m_len -= 255; n++; } return n; } return 0; } static lzo_uint min_gain(lzo_uint ahead, lzo_uint lit1, lzo_uint lit2, lzo_uint l1, lzo_uint l2, lzo_uint l3) { lzo_uint lazy_match_min_gain; assert (ahead >= 1); lazy_match_min_gain = ahead; #if 0 if (l3) lit2 -= ahead; #endif if (lit1 <= 3) lazy_match_min_gain += (lit2 <= 3) ? 0 : 2; else if (lit1 <= 18) lazy_match_min_gain += (lit2 <= 18) ? 0 : 1; lazy_match_min_gain += (l2 - l1) * 2; if (l3) lazy_match_min_gain -= (ahead - l3) * 2; if ((lzo_int) lazy_match_min_gain < 0) lazy_match_min_gain = 0; #if 0 if (l1 == 2) if (lazy_match_min_gain == 0) lazy_match_min_gain = 1; #endif return lazy_match_min_gain; } /*********************************************************************** // ************************************************************************/ #if !defined(NDEBUG) static void assert_match( const lzo_swd_p swd, lzo_uint m_len, lzo_uint m_off ) { const LZO_COMPRESS_T *c = swd->c; lzo_uint d_off; assert(m_len >= 2); if (m_off <= (lzo_uint) (c->bp - c->in)) { assert(c->bp - m_off + m_len < c->ip); assert(lzo_memcmp(c->bp, c->bp - m_off, m_len) == 0); } else { assert(swd->dict != NULL); d_off = m_off - (lzo_uint) (c->bp - c->in); assert(d_off <= swd->dict_len); if (m_len > d_off) { assert(lzo_memcmp(c->bp, swd->dict_end - d_off, d_off) == 0); assert(c->in + m_len - d_off < c->ip); assert(lzo_memcmp(c->bp + d_off, c->in, m_len - d_off) == 0); } else { assert(lzo_memcmp(c->bp, swd->dict_end - d_off, m_len) == 0); } } } #else # define assert_match(a,b,c) ((void)0) #endif #if defined(SWD_BEST_OFF) static void better_match ( const lzo_swd_p swd, lzo_uint *m_len, lzo_uint *m_off ) { #if defined(LZO1Z) const LZO_COMPRESS_T *c = swd->c; #endif if (*m_len <= M2_MIN_LEN) return; #if defined(LZO1Z) if (*m_off == c->last_m_off && *m_len <= M2_MAX_LEN) return; #if 1 if (*m_len >= M2_MIN_LEN + 1 && *m_len <= M2_MAX_LEN + 1 && c->last_m_off && swd->best_off[*m_len-1] == c->last_m_off) { *m_len = *m_len - 1; *m_off = swd->best_off[*m_len]; return; } #endif #endif if (*m_off <= M2_MAX_OFFSET) return; #if 1 /* M3/M4 -> M2 */ if (*m_off > M2_MAX_OFFSET && *m_len >= M2_MIN_LEN + 1 && *m_len <= M2_MAX_LEN + 1 && swd->best_off[*m_len-1] && swd->best_off[*m_len-1] <= M2_MAX_OFFSET) { *m_len = *m_len - 1; *m_off = swd->best_off[*m_len]; return; } #endif #if 1 /* M4 -> M2 */ if (*m_off > M3_MAX_OFFSET && *m_len >= M4_MAX_LEN + 1 && *m_len <= M2_MAX_LEN + 2 && swd->best_off[*m_len-2] && swd->best_off[*m_len-2] <= M2_MAX_OFFSET) { *m_len = *m_len - 2; *m_off = swd->best_off[*m_len]; return; } #endif #if 1 /* M4 -> M3 */ if (*m_off > M3_MAX_OFFSET && *m_len >= M4_MAX_LEN + 1 && *m_len <= M3_MAX_LEN + 1 && swd->best_off[*m_len-1] && swd->best_off[*m_len-1] <= M3_MAX_OFFSET) { *m_len = *m_len - 1; *m_off = swd->best_off[*m_len]; } #endif } #endif /*********************************************************************** // ************************************************************************/ LZO_PUBLIC(int) lzo1x_999_compress_internal ( const lzo_bytep in , lzo_uint in_len, lzo_bytep out, lzo_uintp out_len, lzo_voidp wrkmem, const lzo_bytep dict, lzo_uint dict_len, lzo_callback_p cb, int try_lazy_parm, lzo_uint good_length, lzo_uint max_lazy, lzo_uint nice_length, lzo_uint max_chain, lzo_uint32_t flags ) { lzo_bytep op; const lzo_bytep ii; lzo_uint lit; lzo_uint m_len, m_off; LZO_COMPRESS_T cc; LZO_COMPRESS_T * const c = &cc; lzo_swd_p const swd = (lzo_swd_p) wrkmem; lzo_uint try_lazy; int r; /* sanity check */ #if defined(LZO1X) LZO_COMPILE_TIME_ASSERT(LZO1X_999_MEM_COMPRESS >= SIZEOF_LZO_SWD_T) #elif defined(LZO1Y) LZO_COMPILE_TIME_ASSERT(LZO1Y_999_MEM_COMPRESS >= SIZEOF_LZO_SWD_T) #elif defined(LZO1Z) LZO_COMPILE_TIME_ASSERT(LZO1Z_999_MEM_COMPRESS >= SIZEOF_LZO_SWD_T) #else # error #endif /* setup parameter defaults */ /* number of lazy match tries */ try_lazy = (lzo_uint) try_lazy_parm; if (try_lazy_parm < 0) try_lazy = 1; /* reduce lazy match search if we already have a match with this length */ if (good_length == 0) good_length = 32; /* do not try a lazy match if we already have a match with this length */ if (max_lazy == 0) max_lazy = 32; /* stop searching for longer matches than this one */ if (nice_length == 0) nice_length = 0; /* don't search more positions than this */ if (max_chain == 0) max_chain = SWD_MAX_CHAIN; c->init = 0; c->ip = c->in = in; c->in_end = in + in_len; c->out = out; c->cb = cb; c->m1a_m = c->m1b_m = c->m2_m = c->m3_m = c->m4_m = 0; c->lit1_r = c->lit2_r = c->lit3_r = 0; op = out; ii = c->ip; /* point to start of literal run */ lit = 0; c->r1_lit = c->r1_m_len = 0; r = init_match(c,swd,dict,dict_len,flags); if (r != 0) return r; if (max_chain > 0) swd->max_chain = max_chain; if (nice_length > 0) swd->nice_length = nice_length; r = find_match(c,swd,0,0); if (r != 0) return r; while (c->look > 0) { lzo_uint ahead; lzo_uint max_ahead; lzo_uint l1, l2, l3; c->codesize = pd(op, out); m_len = c->m_len; m_off = c->m_off; assert(c->bp == c->ip - c->look); assert(c->bp >= in); if (lit == 0) ii = c->bp; assert(ii + lit == c->bp); assert(swd->b_char == *(c->bp)); if ( m_len < 2 || (m_len == 2 && (m_off > M1_MAX_OFFSET || lit == 0 || lit >= 4)) || #if 1 /* Do not accept this match for compressed-data compatibility * with LZO v1.01 and before * [ might be a problem for decompress() and optimize() ] */ (m_len == 2 && op == out) || #endif (op == out && lit == 0)) { /* a literal */ m_len = 0; } else if (m_len == M2_MIN_LEN) { /* compression ratio improves if we code a literal in some cases */ if (m_off > MX_MAX_OFFSET && lit >= 4) m_len = 0; } if (m_len == 0) { /* a literal */ lit++; swd->max_chain = max_chain; r = find_match(c,swd,1,0); assert(r == 0); LZO_UNUSED(r); continue; } /* a match */ #if defined(SWD_BEST_OFF) if (swd->use_best_off) better_match(swd,&m_len,&m_off); #endif assert_match(swd,m_len,m_off); /* shall we try a lazy match ? */ ahead = 0; if (try_lazy == 0 || m_len >= max_lazy) { /* no */ l1 = 0; max_ahead = 0; } else { /* yes, try a lazy match */ l1 = len_of_coded_match(m_len,m_off,lit); assert(l1 > 0); #if 1 max_ahead = LZO_MIN(try_lazy, l1 - 1); #else max_ahead = LZO_MIN3(try_lazy, l1, m_len - 1); #endif } while (ahead < max_ahead && c->look > m_len) { lzo_uint lazy_match_min_gain; if (m_len >= good_length) swd->max_chain = max_chain >> 2; else swd->max_chain = max_chain; r = find_match(c,swd,1,0); ahead++; assert(r == 0); LZO_UNUSED(r); assert(c->look > 0); assert(ii + lit + ahead == c->bp); #if defined(LZO1Z) if (m_off == c->last_m_off && c->m_off != c->last_m_off) if (m_len >= M2_MIN_LEN && m_len <= M2_MAX_LEN) c->m_len = 0; #endif if (c->m_len < m_len) continue; #if 1 if (c->m_len == m_len && c->m_off >= m_off) continue; #endif #if defined(SWD_BEST_OFF) if (swd->use_best_off) better_match(swd,&c->m_len,&c->m_off); #endif l2 = len_of_coded_match(c->m_len,c->m_off,lit+ahead); if (l2 == 0) continue; #if 0 if (c->m_len == m_len && l2 >= l1) continue; #endif #if 1 /* compressed-data compatibility [see above] */ l3 = (op == out) ? 0 : len_of_coded_match(ahead,m_off,lit); #else l3 = len_of_coded_match(ahead,m_off,lit); #endif lazy_match_min_gain = min_gain(ahead,lit,lit+ahead,l1,l2,l3); if (c->m_len >= m_len + lazy_match_min_gain) { c->lazy++; assert_match(swd,c->m_len,c->m_off); if (l3) { /* code previous run */ op = code_run(c,op,ii,lit,ahead); lit = 0; /* code shortened match */ op = code_match(c,op,ahead,m_off); } else { lit += ahead; assert(ii + lit == c->bp); } goto lazy_match_done; } } assert(ii + lit + ahead == c->bp); /* 1 - code run */ op = code_run(c,op,ii,lit,m_len); lit = 0; /* 2 - code match */ op = code_match(c,op,m_len,m_off); swd->max_chain = max_chain; r = find_match(c,swd,m_len,1+ahead); assert(r == 0); LZO_UNUSED(r); lazy_match_done: ; } /* store final run */ if (lit > 0) op = STORE_RUN(c,op,ii,lit); #if defined(LZO_EOF_CODE) *op++ = M4_MARKER | 1; *op++ = 0; *op++ = 0; #endif c->codesize = pd(op, out); assert(c->textsize == in_len); *out_len = pd(op, out); if (c->cb && c->cb->nprogress) (*c->cb->nprogress)(c->cb, c->textsize, c->codesize, 0); #if 0 printf("%ld %ld -> %ld %ld: %ld %ld %ld %ld %ld %ld: %ld %ld %ld %ld\n", (long) c->textsize, (long) in_len, (long) c->codesize, c->match_bytes, c->m1a_m, c->m1b_m, c->m2_m, c->m3_m, c->m4_m, c->lit_bytes, c->lit1_r, c->lit2_r, c->lit3_r, c->lazy); #endif assert(c->lit_bytes + c->match_bytes == in_len); return LZO_E_OK; } /*********************************************************************** // ************************************************************************/ LZO_PUBLIC(int) lzo1x_999_compress_level ( const lzo_bytep in , lzo_uint in_len, lzo_bytep out, lzo_uintp out_len, lzo_voidp wrkmem, const lzo_bytep dict, lzo_uint dict_len, lzo_callback_p cb, int compression_level ) { static const struct { int try_lazy_parm; lzo_uint good_length; lzo_uint max_lazy; lzo_uint nice_length; lzo_uint max_chain; lzo_uint32_t flags; } c[9] = { /* faster compression */ { 0, 0, 0, 8, 4, 0 }, { 0, 0, 0, 16, 8, 0 }, { 0, 0, 0, 32, 16, 0 }, { 1, 4, 4, 16, 16, 0 }, { 1, 8, 16, 32, 32, 0 }, { 1, 8, 16, 128, 128, 0 }, { 2, 8, 32, 128, 256, 0 }, { 2, 32, 128, SWD_F, 2048, 1 }, { 2, SWD_F, SWD_F, SWD_F, 4096, 1 } /* max. compression */ }; if (compression_level < 1 || compression_level > 9) return LZO_E_ERROR; compression_level -= 1; return lzo1x_999_compress_internal(in, in_len, out, out_len, wrkmem, dict, dict_len, cb, c[compression_level].try_lazy_parm, c[compression_level].good_length, c[compression_level].max_lazy, #if 0 c[compression_level].nice_length, #else 0, #endif c[compression_level].max_chain, c[compression_level].flags); } /*********************************************************************** // ************************************************************************/ LZO_PUBLIC(int) lzo1x_999_compress_dict ( const lzo_bytep in , lzo_uint in_len, lzo_bytep out, lzo_uintp out_len, lzo_voidp wrkmem, const lzo_bytep dict, lzo_uint dict_len ) { return lzo1x_999_compress_level(in, in_len, out, out_len, wrkmem, dict, dict_len, 0, 8); } LZO_PUBLIC(int) lzo1x_999_compress ( const lzo_bytep in , lzo_uint in_len, lzo_bytep out, lzo_uintp out_len, lzo_voidp wrkmem ) { return lzo1x_999_compress_level(in, in_len, out, out_len, wrkmem, NULL, 0, (lzo_callback_p) 0, 8); } /* vi:ts=4:et */
930884.c
/* USER CODE BEGIN Header */ /** ****************************************************************************** * File Name : stm32l5xx_hal_msp.c * Description : This file provides code for the MSP Initialization * and de-Initialization codes. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" /* USER CODE BEGIN Includes */ /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN TD */ /* USER CODE END TD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN Define */ /* USER CODE END Define */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN Macro */ /* USER CODE END Macro */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* External functions --------------------------------------------------------*/ /* USER CODE BEGIN ExternalFunctions */ /* USER CODE END ExternalFunctions */ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /** * Initializes the Global MSP. */ void HAL_MspInit(void) { /* USER CODE BEGIN MspInit 0 */ /* USER CODE END MspInit 0 */ __HAL_RCC_SYSCFG_CLK_ENABLE(); __HAL_RCC_PWR_CLK_ENABLE(); /* System interrupt init*/ /** Disable the internal Pull-Up in Dead Battery pins of UCPD peripheral */ HAL_PWREx_DisableUCPDDeadBattery(); /* USER CODE BEGIN MspInit 1 */ /* USER CODE END MspInit 1 */ } /** * @brief LPTIM MSP Initialization * This function configures the hardware resources used in this example * @param hlptim: LPTIM handle pointer * @retval None */ void HAL_LPTIM_MspInit(LPTIM_HandleTypeDef* hlptim) { GPIO_InitTypeDef GPIO_InitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInit = {0}; if(hlptim->Instance==LPTIM2) { /* USER CODE BEGIN LPTIM2_MspInit 0 */ /* USER CODE END LPTIM2_MspInit 0 */ /** Initializes the peripherals clock */ PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_LPTIM2; PeriphClkInit.Lptim2ClockSelection = RCC_LPTIM2CLKSOURCE_LSI; if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) { Error_Handler(); } /* Peripheral clock enable */ __HAL_RCC_LPTIM2_CLK_ENABLE(); __HAL_RCC_GPIOD_CLK_ENABLE(); /**LPTIM2 GPIO Configuration PD12 ------> LPTIM2_IN1 */ GPIO_InitStruct.Pin = GPIO_PIN_12; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_PULLUP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM; GPIO_InitStruct.Alternate = GPIO_AF14_LPTIM2; HAL_GPIO_Init(GPIOD, &GPIO_InitStruct); /* LPTIM2 interrupt Init */ HAL_NVIC_SetPriority(LPTIM2_IRQn, 0, 0); HAL_NVIC_EnableIRQ(LPTIM2_IRQn); /* USER CODE BEGIN LPTIM2_MspInit 1 */ /* USER CODE END LPTIM2_MspInit 1 */ } } /** * @brief LPTIM MSP De-Initialization * This function freeze the hardware resources used in this example * @param hlptim: LPTIM handle pointer * @retval None */ void HAL_LPTIM_MspDeInit(LPTIM_HandleTypeDef* hlptim) { if(hlptim->Instance==LPTIM2) { /* USER CODE BEGIN LPTIM2_MspDeInit 0 */ /* USER CODE END LPTIM2_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_LPTIM2_CLK_DISABLE(); /**LPTIM2 GPIO Configuration PD12 ------> LPTIM2_IN1 */ HAL_GPIO_DeInit(GPIOD, GPIO_PIN_12); /* LPTIM2 interrupt DeInit */ HAL_NVIC_DisableIRQ(LPTIM2_IRQn); /* USER CODE BEGIN LPTIM2_MspDeInit 1 */ /* USER CODE END LPTIM2_MspDeInit 1 */ } } /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
743699.c
#include "gpu.h" #include "memorymap.h" #include <stdlib.h> #include <string.h> // RGB555 or RGBA5551 #define RGB555(R,G,B) ((((int)(B))<<10)|(((int)(G))<<5)|(((int)(R)))|(1<<15)) static uint16 rgb555(uint8 r, uint8 g, uint8 b) { return RGB555(r >> 3, g >> 3, b >> 3); } static SV_MapRGBFunc mapRGB = rgb555; static const uint8 palettes[SV_COLOR_SCHEME_COUNT][12] = { { 252, 252, 252, 168, 168, 168, 84, 84, 84, 0, 0, 0, }, { 252, 154, 0, 168, 102, 0, 84, 51, 0, 0, 0, 0, }, { 50, 227, 50, 34, 151, 34, 17, 76, 17, 0, 0, 0, }, { 0, 154, 252, 0, 102, 168, 0, 51, 84, 0, 0, 0, }, { 224, 248, 208, 136, 192, 112, 52, 104, 86, 8, 24, 32, }, { 0x7b, 0xc7, 0x7b, 0x52, 0xa6, 0x8c, 0x2e, 0x62, 0x60, 0x0d, 0x32, 0x2e, }, }; static uint16 *palette; static int paletteIndex; #define SB_MAX (SV_GHOSTING_MAX + 1) static int ghostCount = 0; static uint8 *screenBuffers[SB_MAX]; static uint8 screenBufferInnerX[SB_MAX]; static void add_ghosting(uint32 scanline, uint16 *backbuffer, uint8 start_x, uint8 end_x); void gpu_init(void) { palette = (uint16*)malloc(4 * sizeof(int16)); } void gpu_reset(void) { gpu_set_map_func(NULL); gpu_set_color_scheme(SV_COLOR_SCHEME_DEFAULT); gpu_set_ghosting(0); } void gpu_done(void) { free(palette); palette = NULL; gpu_set_ghosting(0); } void gpu_set_map_func(SV_MapRGBFunc func) { mapRGB = func; if (mapRGB == NULL) { mapRGB = rgb555; } } void gpu_set_color_scheme(int colorScheme) { int i; if (colorScheme < 0 || colorScheme >= SV_COLOR_SCHEME_COUNT) { return; } for (i = 0; i < 4; i++) { palette[i] = mapRGB(palettes[colorScheme][i * 3 + 0], palettes[colorScheme][i * 3 + 1], palettes[colorScheme][i * 3 + 2]); } paletteIndex = colorScheme; } // Faster but it's not accurate //void gpu_render_scanline(uint32 scanline, uint16 *backbuffer) //{ // uint8 *vram_line = memorymap_getUpperRamPointer() + scanline; // uint8 x; // // for (x = 0; x < SV_W; x += 4) { // uint8 b = *(vram_line++); // backbuffer[0] = palette[((b >> 0) & 0x03)]; // backbuffer[1] = palette[((b >> 2) & 0x03)]; // backbuffer[2] = palette[((b >> 4) & 0x03)]; // backbuffer[3] = palette[((b >> 6) & 0x03)]; // backbuffer += 4; // } //} void gpu_render_scanline(uint32 scanline, uint16 *backbuffer, uint8 innerx, uint8 size) { uint8 *vram_line = memorymap_getUpperRamPointer() + scanline; uint8 x, j = innerx, b = 0; // #1 if (j & 3) { b = *vram_line++; b >>= (j & 3) * 2; } for (x = 0; x < size; x++, j++) { if (!(j & 3)) { b = *(vram_line++); } backbuffer[x] = palette[b & 3]; b >>= 2; } // #2 Slow /*for (x = 0; x < size; x++, j++) { b = vram_line[j >> 2]; backbuffer[x] = palette[(b >> ((j & 3) * 2)) & 3]; }*/ if (ghostCount != 0) { add_ghosting(scanline, backbuffer, innerx, size); } } void gpu_set_ghosting(int frameCount) { int i; if (frameCount < 0) ghostCount = 0; else if (frameCount > SV_GHOSTING_MAX) ghostCount = SV_GHOSTING_MAX; else ghostCount = frameCount; if (ghostCount != 0) { if (screenBuffers[0] == NULL) { for (i = 0; i < SB_MAX; i++) { screenBuffers[i] = malloc(SV_H * SV_W / 4); if (screenBuffers[i] == NULL) { return; } } } for (i = 0; i < SB_MAX; i++) { memset(screenBuffers[i], 0, SV_H * SV_W / 4); } } else { for (i = 0; i < SB_MAX; i++) { free(screenBuffers[i]); screenBuffers[i] = NULL; } } } static void add_ghosting(uint32 scanline, uint16 *backbuffer, uint8 innerx, uint8 size) { static int curSB = 0; static int lineCount = 0; uint8 *vram_line = memorymap_getUpperRamPointer() + scanline; uint8 x, i, j; screenBufferInnerX[curSB] = innerx; memset(screenBuffers[curSB] + lineCount * SV_W / 4, 0, SV_W / 4); for (j = innerx, x = 0; x < size; x++, j++) { uint8 b = vram_line[j >> 2]; uint8 innerInd = (j & 3) * 2; uint8 c = (b >> innerInd) & 3; int pixInd = (x + lineCount * SV_W) / 4; if (c != 3) { for (i = 0; i < ghostCount; i++) { uint8 sbInd = (curSB + (SB_MAX - 1) - i) % SB_MAX; uint8 innerInd_ = ((screenBufferInnerX[sbInd] + x) & 3) * 2; uint8 c_ = (screenBuffers[sbInd][pixInd] >> innerInd_) & 3; if (c_ > c) { #if 0 backbuffer[x] = palette[3 - 3 * i / ghostCount]; #else uint8 r = palettes[paletteIndex][c_ * 3 + 0]; uint8 g = palettes[paletteIndex][c_ * 3 + 1]; uint8 b = palettes[paletteIndex][c_ * 3 + 2]; r = r + (palettes[paletteIndex][c * 3 + 0] - r) * i / ghostCount; g = g + (palettes[paletteIndex][c * 3 + 1] - g) * i / ghostCount; b = b + (palettes[paletteIndex][c * 3 + 2] - b) * i / ghostCount; backbuffer[x] = mapRGB(r, g, b); #endif break; } } } screenBuffers[curSB][pixInd] |= c << innerInd; } if (lineCount == SV_H - 1) { curSB = (curSB + 1) % SB_MAX; } lineCount = (lineCount + 1) % SV_H; }
95275.c
/******************************************************************** * filename: kbhit.c * * purpose : simulate the kbhit() and getch() functions * * known from DOS * * Author : Christian Schoett * * Date : 20.02.2001 * * Version : 1.0 * ********************************************************************/ #include <stdio.h> #include <termios.h> #include <unistd.h> #include "kbhit.h" static struct termios orig, tnew; static int peek = -1; void kbdinit(void) { tcgetattr(0, &orig); tnew = orig; tnew.c_lflag &= ~ICANON; tnew.c_lflag &= ~ECHO; tnew.c_lflag &= ~ISIG; tnew.c_cc[VMIN] = 1; tnew.c_cc[VTIME] = 0; tcsetattr(0, TCSANOW, &tnew); } void kbdexit(void) { tcsetattr(0,TCSANOW, &orig); } int kbhit(void) { char ch; int nread = -1; if(peek != -1) return 1; tnew.c_cc[VMIN]=0; tcsetattr(0, TCSANOW, &tnew); nread = read(0,&ch,1); tnew.c_cc[VMIN]=1; tcsetattr(0, TCSANOW, &tnew); if(nread == 1) { peek = ch; return nread; } return 0; } int readch(void) { char ch; if(peek != -1) { ch = peek; peek = -1; return ch; } read(0,&ch,1); return ch; } #if 0 /* a 'main' routine to test the above functions */ int main() { int ch = ' '; kbdinit(); while(ch != 'q') { if(kbhit()){ ch = readch(); if(ch == 0x1B){ ch = readch(); ch = readch(); ch = readch(); if(ch == '1') printf("you hit F1\n"); else if(ch == '2') printf("you hit F2\n"); else if(ch == '3') printf("you hit F3\n"); else if(ch == '4') printf("you hit F4\n"); else if(ch == '5') printf("you hit F5\n"); else if(ch == '7') printf("you hit F6\n"); else if(ch == '8') printf("you hit F7\n"); else if(ch == '9') printf("you hit F8\n"); ch = readch(); } else printf("you hit %2.2X %d, %c\n", ch, ch, ch); } } kbdexit(); exit(0); } #endif
785711.c
#include<stdio.h> #include<math.h> int addition(int a, int b); int subtraction(int a, int b); int multiplication(int a, int b); float division(int a, int b); int modulo(int a, int b); float average(int a, int b); int power(int a, int b); int main() { int a,b,choice; float result; scanf("%d\n%d\n%d",&a,&b,&choice); switch(choice){ case 1: //int result; result = addition(a,b); printf("%.0f",result); break; case 2: //int result; result = subtraction(a,b); printf("%.0f",result); break; case 3: //int result; result = multiplication(a,b); printf("%.0f",result); break; case 4: //float result; result = division(a,b); printf("%.2f",result); break; case 5: //int result; result = modulo(a,b); printf("%.0f",result); break; case 6: //float result; result = average(a,b); printf("%.2f",result); break; case 7: //int result; result = power(a,b); printf("%.0f",result); break; } return 0; } int addition(int a, int b) { return (a+b); } int subtraction(int a, int b) { return (a-b); } int multiplication(int a, int b) { return (a*b); } float division(int a, int b) { return ((float)a/b); } int modulo(int a, int b) { return (a%b); } float average(int a, int b) { return ((a+b)/2.0); } int power(int a, int b) { return (int)pow(a,b); }
956158.c
/*---------------------------------------------------------------------------- * Tencent is pleased to support the open source community by making TencentOS * available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * If you have downloaded a copy of the TencentOS binary from Tencent, please * note that the TencentOS binary is licensed under the BSD 3-Clause License. * * If you have downloaded a copy of the TencentOS source code from Tencent, * please note that TencentOS source code is licensed under the BSD 3-Clause * License, except for the third-party components listed below which are * subject to different license terms. Your integration of TencentOS into your * own projects may require compliance with the BSD 3-Clause License, as well * as the other licenses applicable to the third-party components included * within TencentOS. *---------------------------------------------------------------------------*/ #include "tos_k.h" #if TOS_CFG_PWR_MGR_EN > 0u #if TOS_CFG_TICKLESS_EN > 0u __API__ k_err_t tos_pm_cpu_lpwr_mode_set(k_cpu_lpwr_mode_t cpu_lpwr_mode) { TOS_CPU_CPSR_ALLOC(); if (cpu_lpwr_mode != TOS_LOW_POWER_MODE_NONE && !tickless_wkup_alarm_is_installed(cpu_lpwr_mode)) { return K_ERR_PM_WKUP_SOURCE_NOT_INSTALL; } TOS_CPU_INT_DISABLE(); k_cpu_lpwr_mode = cpu_lpwr_mode; TOS_CPU_INT_ENABLE(); return K_ERR_NONE; } #endif __STATIC__ int pm_device_is_registered(k_pm_device_t *device) { uint8_t i = 0; for (i = 0; i < k_pm_device_ctl.count; ++i) { if (strcmp(k_pm_device_ctl.mgr[i]->name, device->name) == 0) { return 1; } } return 0; } __API__ k_err_t tos_pm_device_register(k_pm_device_t *device) { TOS_PTR_SANITY_CHECK(device); if (pm_device_is_registered(device)) { return K_ERR_PM_DEVICE_ALREADY_REG; } if (k_pm_device_ctl.count >= K_PM_DEVICE_MAX_COUNT) { return K_ERR_PM_DEVICE_OVERFLOW; } k_pm_device_ctl.mgr[k_pm_device_ctl.count++] = device; return K_ERR_NONE; } __KNL__ void pm_init(void) { memset(&k_pm_device_ctl, 0, sizeof(k_pm_device_ctl)); k_pm_device_ctl.count = 0u; } __STATIC_INLINE__ void pm_cpu_sleep_mode_enter(void) { cpu_sleep_mode_enter(); } __STATIC_INLINE__ void pm_cpu_stop_mode_enter(void) { cpu_stop_mode_enter(); } __STATIC_INLINE__ void pm_cpu_standby_mode_enter(void) { cpu_standby_mode_enter(); } __KNL__ void pm_cpu_lpwr_mode_enter(k_cpu_lpwr_mode_t lpwr_mode) { if (TOS_LOW_POWER_MODE_SLEEP == lpwr_mode) { pm_cpu_sleep_mode_enter(); } else if (TOS_LOW_POWER_MODE_STOP == lpwr_mode) { pm_device_suspend(); pm_cpu_stop_mode_enter(); pm_device_resume(); } else if (TOS_LOW_POWER_MODE_STANDBY == lpwr_mode) { pm_device_suspend(); pm_cpu_standby_mode_enter(); pm_device_resume(); } } __KNL__ k_cpu_lpwr_mode_t pm_cpu_lpwr_mode_get(void) { return k_cpu_lpwr_mode; } __KNL__ void pm_idle_pwr_mgr_mode_set(idle_pwrmgr_mode_t idle_pwrmgr_mode) { k_idle_pwr_mgr_mode = idle_pwrmgr_mode; } __KNL__ int pm_idle_pwr_mgr_mode_is_sleep(void) { return k_idle_pwr_mgr_mode == IDLE_POWER_MANAGER_MODE_SLEEP; } __KNL__ int pm_idle_pwr_mgr_mode_is_tickless(void) { return k_idle_pwr_mgr_mode == IDLE_POWER_MANAGER_MODE_TICKLESS; } __KNL__ void pm_power_manager(void) { if (pm_idle_pwr_mgr_mode_is_sleep()) { pm_cpu_sleep_mode_enter(); } #if TOS_CFG_TICKLESS_EN > 0u else if (pm_idle_pwr_mgr_mode_is_tickless()) { tickless_proc(); } #endif } __KNL__ int pm_device_suspend(void) { uint8_t i = 0; for (i = 0; i < k_pm_device_ctl.count; ++i) { if (*k_pm_device_ctl.mgr[i]->suspend) { (*k_pm_device_ctl.mgr[i]->suspend)(); } } return 0; } __KNL__ int pm_device_resume(void) { uint8_t i = 0; for (i = 0; i < k_pm_device_ctl.count; ++i) { if (*k_pm_device_ctl.mgr[i]->resume) { (*k_pm_device_ctl.mgr[i]->resume)(); } } return 0; } #endif
683772.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strnstr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: itonoli- <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/11/10 18:22:20 by itonoli- #+# #+# */ /* Updated: 2017/06/26 20:51:50 by itonoli- ### ########.fr */ /* */ /* ************************************************************************** */ #include "../inc/libft.h" char *ft_strnstr(const char *big, const char *little, size_t len) { unsigned int i; unsigned int len_little; i = 0; if (ft_strcmp(little, "") == 0) return ((char *)&big[i]); len_little = ft_strlen(little); while (big[i] != '\0' && len >= len_little) { if (ft_strncmp(&big[i], little, len_little) == 0) return ((char *)&big[i]); i++; len--; } return (NULL); }
224490.c
/* Copyright 2000-2005 The Apache Software Foundation or its licensors, as * applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include "apr_md5.h" #include "apr_xlate.h" #include "apr_general.h" #include "abts.h" #include "testutil.h" static struct { const char *string; const char *digest; } md5sums[] = { {"Jeff was here!", "\xa5\x25\x8a\x89\x11\xb2\x9d\x1f\x81\x75\x96\x3b\x60\x94\x49\xc0"}, {"01234567890aBcDeFASDFGHJKLPOIUYTR" "POIUYTREWQZXCVBN LLLLLLLLLLLLLLL", "\xd4\x1a\x06\x2c\xc5\xfd\x6f\x24\x67\x68\x56\x7c\x40\x8a\xd5\x69"}, {"111111118888888888888888*******%%%%%%%%%%#####" "142134u8097289720432098409289nkjlfkjlmn,m.. ", "\xb6\xea\x5b\xe8\xca\x45\x8a\x33\xf0\xf1\x84\x6f\xf9\x65\xa8\xe1"}, {"01234567890aBcDeFASDFGHJKLPOIUYTR" "POIUYTREWQZXCVBN LLLLLLLLLLLLLLL" "01234567890aBcDeFASDFGHJKLPOIUYTR" "POIUYTREWQZXCVBN LLLLLLLLLLLLLLL" "1", "\xd1\xa1\xc0\x97\x8a\x60\xbb\xfb\x2a\x25\x46\x9d\xa5\xae\xd0\xb0"} }; static int num_sums = sizeof(md5sums) / sizeof(md5sums[0]); static int count; static void test_md5sum(abts_case *tc, void *data) { apr_md5_ctx_t context; unsigned char digest[APR_MD5_DIGESTSIZE]; const void *string = md5sums[count].string; const void *sum = md5sums[count].digest; unsigned int len = strlen(string); ABTS_ASSERT(tc, "apr_md5_init", (apr_md5_init(&context) == 0)); ABTS_ASSERT(tc, "apr_md5_update", (apr_md5_update(&context, string, len) == 0)); ABTS_ASSERT(tc, "apr_md5_final", (apr_md5_final(digest, &context) == 0)); ABTS_ASSERT(tc, "check for correct md5 digest", (memcmp(digest, sum, APR_MD5_DIGESTSIZE) == 0)); } abts_suite *testmd5(abts_suite *suite) { suite = ADD_SUITE(suite); for (count=0; count < num_sums; count++) { abts_run_test(suite, test_md5sum, NULL); } return suite; }
702803.c
/* * Copyright 2020 Broadcom * * SPDX-License-Identifier: Apache-2.0 */ #define DT_DRV_COMPAT brcm_iproc_pax_dma_v1 #include <arch/cpu.h> #include <cache.h> #include <errno.h> #include <init.h> #include <kernel.h> #include <linker/sections.h> #include <soc.h> #include <string.h> #include <toolchain.h> #include <zephyr/types.h> #include <drivers/dma.h> #include <drivers/pcie/endpoint/pcie_ep.h> #include "dma_iproc_pax_v1.h" #define LOG_LEVEL CONFIG_DMA_LOG_LEVEL #include <logging/log.h> LOG_MODULE_REGISTER(dma_iproc_pax); #define PAX_DMA_DEV_NAME(dev) ((dev)->name) #define PAX_DMA_DEV_CFG(dev) \ ((struct dma_iproc_pax_cfg *)(dev)->config) #define PAX_DMA_DEV_DATA(dev) \ ((struct dma_iproc_pax_data *)(dev)->data) /* Driver runtime data for PAX DMA and RM */ static struct dma_iproc_pax_data pax_dma_data; DEVICE_DECLARE(dma_iproc_pax); static inline uint32_t reset_pkt_id(struct dma_iproc_pax_ring_data *ring) { return ring->pkt_id = 0x0; } /** * @brief Opaque/packet id allocator, range 0 to 31 */ static inline uint32_t alloc_pkt_id(struct dma_iproc_pax_ring_data *ring) { ring->pkt_id = (ring->pkt_id + 1) % 32; return ring->pkt_id; } static inline uint32_t curr_pkt_id(struct dma_iproc_pax_ring_data *ring) { return ring->pkt_id; } static inline uint32_t curr_toggle_val(struct dma_iproc_pax_ring_data *ring) { return ring->curr.toggle; } /** * @brief Populate header descriptor */ static inline void rm_write_header_desc(void *desc, uint32_t toggle, uint32_t opq, uint32_t bdcount) { struct rm_header *r = (struct rm_header *)desc; r->opq = opq; /* DMA descriptor count init vlaue */ r->bdcount = bdcount; r->prot = 0x0; /* No packet extension, start and end set to '1' */ r->start = 1; r->end = 1; r->toggle = toggle; /* RM header type */ r->type = PAX_DMA_TYPE_RM_HEADER; } /** * @brief Fill RM header descriptor for next transfer * with invalid toggle */ static inline void rm_write_header_next_desc(void *desc, struct dma_iproc_pax_ring_data *r, uint32_t opq, uint32_t bdcount) { /* Toggle bit is invalid until next payload configured */ rm_write_header_desc(desc, (r->curr.toggle == 0) ? 1 : 0, opq, bdcount); } static inline void rm_header_set_bd_count(void *desc, uint32_t bdcount) { struct rm_header *r = (struct rm_header *)desc; /* DMA descriptor count */ r->bdcount = bdcount; } static inline void rm_header_set_toggle(void *desc, uint32_t toggle) { struct rm_header *r = (struct rm_header *)desc; r->toggle = toggle; } /** * @brief Populate dma header descriptor */ static inline void rm_write_dma_header_desc(void *desc, struct dma_iproc_pax_payload *pl) { struct dma_header_desc *hdr = (struct dma_header_desc *)desc; hdr->length = pl->xfer_sz; hdr->opcode = pl->direction; /* DMA header type */ hdr->type = PAX_DMA_TYPE_DMA_DESC; } /** * @brief Populate axi address descriptor */ static inline void rm_write_axi_addr_desc(void *desc, struct dma_iproc_pax_payload *pl) { struct axi_addr_desc *axi = (struct axi_addr_desc *)desc; axi->axi_addr = pl->axi_addr; axi->type = PAX_DMA_TYPE_DMA_DESC; } /** * @brief Populate pci address descriptor */ static inline void rm_write_pci_addr_desc(void *desc, struct dma_iproc_pax_payload *pl) { struct pci_addr_desc *pci = (struct pci_addr_desc *)desc; pci->pcie_addr = pl->pci_addr >> PAX_DMA_PCI_ADDR_ALIGNMT_SHIFT; pci->type = PAX_DMA_TYPE_DMA_DESC; } /** * @brief Return's pointer to the descriptor memory to be written next, * skip next pointer descriptor address. */ static void *next_desc_addr(struct dma_iproc_pax_ring_data *ring) { struct next_ptr_desc *nxt; uintptr_t curr; curr = (uintptr_t)ring->curr.write_ptr + PAX_DMA_RM_DESC_BDWIDTH; /* if hit next table ptr, skip to next location, flip toggle */ nxt = (struct next_ptr_desc *)curr; if (nxt->type == PAX_DMA_TYPE_NEXT_PTR) { LOG_DBG("hit next_ptr@0x%lx:T%d, next_table@0x%lx\n", curr, nxt->toggle, (uintptr_t)nxt->addr); uintptr_t last = (uintptr_t)ring->bd + PAX_DMA_RM_DESC_RING_SIZE * PAX_DMA_NUM_BD_BUFFS; ring->curr.toggle = (ring->curr.toggle == 0) ? 1 : 0; /* move to next addr, wrap around if hits end */ curr += PAX_DMA_RM_DESC_BDWIDTH; if (curr == last) { curr = (uintptr_t)ring->bd; LOG_DBG("hit end of desc:0x%lx, wrap to 0x%lx\n", last, curr); } } ring->curr.write_ptr = (void *)curr; return (void *)curr; } /** * @brief Populate next ptr descriptor */ static void rm_write_next_table_desc(void *desc, void *next_ptr, uint32_t toggle) { struct next_ptr_desc *nxt = (struct next_ptr_desc *)desc; nxt->addr = (uintptr_t)next_ptr; nxt->type = PAX_DMA_TYPE_NEXT_PTR; nxt->toggle = toggle; } static void prepare_ring(struct dma_iproc_pax_ring_data *ring) { uintptr_t curr, next, last; uint32_t toggle; int buff_count = PAX_DMA_NUM_BD_BUFFS; /* zero out descriptor area */ memset(ring->bd, 0x0, PAX_DMA_RM_DESC_RING_SIZE * PAX_DMA_NUM_BD_BUFFS); memset(ring->cmpl, 0x0, PAX_DMA_RM_CMPL_RING_SIZE); /* opaque/packet id value */ rm_write_header_desc(ring->bd, 0x0, reset_pkt_id(ring), PAX_DMA_RM_DESC_BDCOUNT); /* start with first buffer, valid toggle is 0x1 */ toggle = 0x1; curr = (uintptr_t)ring->bd; next = curr + PAX_DMA_RM_DESC_RING_SIZE; last = curr + PAX_DMA_RM_DESC_RING_SIZE * PAX_DMA_NUM_BD_BUFFS; do { /* Place next_table desc as last BD entry on each buffer */ rm_write_next_table_desc(PAX_DMA_NEXT_TBL_ADDR((void *)curr), (void *)next, toggle); /* valid toggle flips for each buffer */ toggle = toggle ? 0x0 : 0x1; curr += PAX_DMA_RM_DESC_RING_SIZE; next += PAX_DMA_RM_DESC_RING_SIZE; /* last entry, chain back to first buffer */ if (next == last) { next = (uintptr_t)ring->bd; } } while (--buff_count); dma_mb(); /* start programming from first RM header */ ring->curr.write_ptr = ring->bd; /* valid toggle starts with 1 after reset */ ring->curr.toggle = 1; /* completion read offset */ ring->curr.cmpl_rd_offs = 0; /* init sync data for the ring */ ring->curr.sync_data.signature = PAX_DMA_WRITE_SYNC_SIGNATURE; ring->curr.sync_data.ring = ring->idx; /* pkt id for active dma xfer */ ring->curr.sync_data.opaque = 0x0; /* pkt count for active dma xfer */ ring->curr.sync_data.total_pkts = 0x0; } static int init_rm(struct dma_iproc_pax_data *pd) { int ret = -ETIMEDOUT, timeout = 1000; k_mutex_lock(&pd->dma_lock, K_FOREVER); /* Wait for Ring Manager ready */ do { LOG_DBG("Waiting for RM HW init\n"); if ((sys_read32(RM_COMM_REG(pd, RM_COMM_MAIN_HW_INIT_DONE)) & RM_COMM_MAIN_HW_INIT_DONE_MASK)) { ret = 0; break; } k_sleep(K_MSEC(1)); } while (--timeout); k_mutex_unlock(&pd->dma_lock); if (!timeout) { LOG_WRN("RM HW Init timedout!\n"); } else { LOG_INF("PAX DMA RM HW Init Done\n"); } return ret; } static void rm_cfg_start(struct dma_iproc_pax_data *pd) { uint32_t val; k_mutex_lock(&pd->dma_lock, K_FOREVER); /* set config done 0, enable toggle mode */ val = sys_read32(RM_COMM_REG(pd, RM_COMM_CONTROL)); val &= ~RM_COMM_CONTROL_CONFIG_DONE; sys_write32(val, RM_COMM_REG(pd, RM_COMM_CONTROL)); val &= ~(RM_COMM_CONTROL_MODE_MASK << RM_COMM_CONTROL_MODE_SHIFT); val |= (RM_COMM_CONTROL_MODE_TOGGLE << RM_COMM_CONTROL_MODE_SHIFT); sys_write32(val, RM_COMM_REG(pd, RM_COMM_CONTROL)); /* Disable MSI */ sys_write32(RM_COMM_MSI_DISABLE_VAL, RM_COMM_REG(pd, RM_COMM_MSI_DISABLE)); /* Enable Line interrupt */ val = sys_read32(RM_COMM_REG(pd, RM_COMM_CONTROL)); val |= RM_COMM_CONTROL_LINE_INTR_EN; sys_write32(val, RM_COMM_REG(pd, RM_COMM_CONTROL)); /* Enable AE_TIMEOUT */ sys_write32(RM_COMM_AE_TIMEOUT_VAL, RM_COMM_REG(pd, RM_COMM_AE_TIMEOUT)); val = sys_read32(RM_COMM_REG(pd, RM_COMM_CONTROL)); val |= RM_COMM_CONTROL_AE_TIMEOUT_EN; sys_write32(val, RM_COMM_REG(pd, RM_COMM_CONTROL)); /* AE (Acceleration Engine) grouping to group '0' */ val = sys_read32(RM_COMM_REG(pd, RM_AE0_AE_CONTROL)); val &= ~RM_AE_CTRL_AE_GROUP_MASK; sys_write32(val, RM_COMM_REG(pd, RM_AE0_AE_CONTROL)); val |= RM_AE_CONTROL_ACTIVE; sys_write32(val, RM_COMM_REG(pd, RM_AE0_AE_CONTROL)); /* AXI read/write channel enable */ val = sys_read32(RM_COMM_REG(pd, RM_COMM_AXI_CONTROL)); val |= (RM_COMM_AXI_CONTROL_RD_CH_EN | RM_COMM_AXI_CONTROL_WR_CH_EN); sys_write32(val, RM_COMM_REG(pd, RM_COMM_AXI_CONTROL)); /* Tune RM control programming for 4 rings */ sys_write32(RM_COMM_TIMER_CONTROL0_VAL, RM_COMM_REG(pd, RM_COMM_TIMER_CONTROL_0)); sys_write32(RM_COMM_TIMER_CONTROL1_VAL, RM_COMM_REG(pd, RM_COMM_TIMER_CONTROL_1)); sys_write32(RM_COMM_RM_BURST_LENGTH, RM_COMM_REG(pd, RM_COMM_RM_BURST_LENGTH)); /* Set Sequence max count to the max supported value */ val = sys_read32(RM_COMM_REG(pd, RM_COMM_MASK_SEQUENCE_MAX_COUNT)); val = (val | RING_MASK_SEQ_MAX_COUNT_MASK); sys_write32(val, RM_COMM_REG(pd, RM_COMM_MASK_SEQUENCE_MAX_COUNT)); k_mutex_unlock(&pd->dma_lock); } static void rm_ring_clear_stats(struct dma_iproc_pax_data *pd, enum ring_idx idx) { /* Read ring Tx, Rx, and Outstanding counts to clear */ sys_read32(RM_RING_REG(pd, idx, RING_NUM_REQ_RECV_LS)); sys_read32(RM_RING_REG(pd, idx, RING_NUM_REQ_RECV_MS)); sys_read32(RM_RING_REG(pd, idx, RING_NUM_REQ_TRANS_LS)); sys_read32(RM_RING_REG(pd, idx, RING_NUM_REQ_TRANS_MS)); sys_read32(RM_RING_REG(pd, idx, RING_NUM_REQ_OUTSTAND)); } static void rm_cfg_finish(struct dma_iproc_pax_data *pd) { uint32_t val; k_mutex_lock(&pd->dma_lock, K_FOREVER); /* set Ring config done */ val = sys_read32(RM_COMM_REG(pd, RM_COMM_CONTROL)); val |= RM_COMM_CONTROL_CONFIG_DONE; sys_write32(val, RM_COMM_REG(pd, RM_COMM_CONTROL)); k_mutex_unlock(&pd->dma_lock); } /* Activate/Deactivate rings */ static inline void set_ring_active(struct dma_iproc_pax_data *pd, enum ring_idx idx, bool active) { uint32_t val; val = sys_read32(RM_RING_REG(pd, idx, RING_CONTROL)); if (active) { val |= RING_CONTROL_ACTIVE; } else { val &= ~RING_CONTROL_ACTIVE; } sys_write32(val, RM_RING_REG(pd, idx, RING_CONTROL)); } static int init_ring(struct dma_iproc_pax_data *pd, enum ring_idx idx) { uint32_t val; uintptr_t desc = (uintptr_t)pd->ring[idx].bd; uintptr_t cmpl = (uintptr_t)pd->ring[idx].cmpl; int timeout = 5000, ret = 0; k_mutex_lock(&pd->dma_lock, K_FOREVER); /* Read cmpl write ptr incase previous dma stopped */ sys_read32(RM_RING_REG(pd, idx, RING_CMPL_WRITE_PTR)); /* Inactivate ring */ sys_write32(0x0, RM_RING_REG(pd, idx, RING_CONTROL)); /* Flush ring before loading new descriptor */ sys_write32(RING_CONTROL_FLUSH, RM_RING_REG(pd, idx, RING_CONTROL)); do { if (sys_read32(RM_RING_REG(pd, idx, RING_FLUSH_DONE)) & RING_FLUSH_DONE_MASK) { break; } k_busy_wait(1); } while (--timeout); if (!timeout) { LOG_WRN("Ring %d flush timedout!\n", idx); ret = -ETIMEDOUT; goto err; } /* clear ring after flush */ sys_write32(0x0, RM_RING_REG(pd, idx, RING_CONTROL)); /* ring group id set to '0' */ val = sys_read32(RM_COMM_REG(pd, RM_COMM_CTRL_REG(idx))); val &= ~RING_COMM_CTRL_AE_GROUP_MASK; sys_write32(val, RM_COMM_REG(pd, RM_COMM_CTRL_REG(idx))); /* DDR update control, set timeout value */ val = RING_DDR_CONTROL_COUNT(RING_DDR_CONTROL_COUNT_VAL) | RING_DDR_CONTROL_TIMER(RING_DDR_CONTROL_TIMER_VAL) | RING_DDR_CONTROL_ENABLE; sys_write32(val, RM_RING_REG(pd, idx, RING_CMPL_WR_PTR_DDR_CONTROL)); val = (uint32_t)((uintptr_t)desc >> PAX_DMA_RING_BD_ALIGN_ORDER); sys_write32(val, RM_RING_REG(pd, idx, RING_BD_START_ADDR)); val = (uint32_t)((uintptr_t)cmpl >> PAX_DMA_RING_CMPL_ALIGN_ORDER); sys_write32(val, RM_RING_REG(pd, idx, RING_CMPL_START_ADDR)); val = sys_read32(RM_RING_REG(pd, idx, RING_BD_READ_PTR)); /* keep ring inactive after init to avoid BD poll */ set_ring_active(pd, idx, false); rm_ring_clear_stats(pd, idx); err: k_mutex_unlock(&pd->dma_lock); return ret; } static int poll_on_write_sync(const struct device *dev, struct dma_iproc_pax_ring_data *ring) { struct dma_iproc_pax_cfg *cfg = PAX_DMA_DEV_CFG(dev); const struct device *pcidev; struct dma_iproc_pax_write_sync_data sync_rd, *recv, *sent; uint64_t pci_addr; uint32_t *pci32, *axi32; uint32_t zero_init = 0, timeout = PAX_DMA_MAX_SYNC_WAIT; int ret; pcidev = device_get_binding(cfg->pcie_dev_name); if (!pcidev) { LOG_ERR("Cannot get pcie device\n"); return -EINVAL; } recv = &sync_rd; sent = &(ring->curr.sync_data); /* form host pci sync address */ pci32 = (uint32_t *)&pci_addr; pci32[0] = ring->sync_pci.addr_lo; pci32[1] = ring->sync_pci.addr_hi; axi32 = (uint32_t *)&sync_rd; do { ret = pcie_ep_xfer_data_memcpy(pcidev, pci_addr, (uintptr_t *)axi32, 4, PCIE_OB_LOWMEM, HOST_TO_DEVICE); if (memcmp((void *)recv, (void *)sent, 4) == 0) { /* clear the sync word */ ret = pcie_ep_xfer_data_memcpy(pcidev, pci_addr, (uintptr_t *)&zero_init, 4, PCIE_OB_LOWMEM, DEVICE_TO_HOST); dma_mb(); ret = 0; break; } k_busy_wait(1); } while (--timeout); if (!timeout) { LOG_DBG("[ring %d]: not recvd write sync!\n", ring->idx); ret = -ETIMEDOUT; } return ret; } static int process_cmpl_event(const struct device *dev, enum ring_idx idx, uint32_t pl_len) { struct dma_iproc_pax_data *pd = PAX_DMA_DEV_DATA(dev); uint32_t wr_offs, rd_offs, ret = 0; struct dma_iproc_pax_ring_data *ring = &(pd->ring[idx]); struct cmpl_pkt *c; uint32_t is_outstanding; /* cmpl read offset, unprocessed cmpl location */ rd_offs = ring->curr.cmpl_rd_offs; wr_offs = sys_read32(RM_RING_REG(pd, idx, RING_CMPL_WRITE_PTR)); /* Update read ptr to "processed" */ ring->curr.cmpl_rd_offs = wr_offs; /* * Ensure consistency of completion descriptor * The completion desc is updated by RM via AXI stream * CPU need to ensure the memory operations are completed * before reading cmpl area, by a "dsb" * If Dcache enabled, need to invalidate the cachelines to * read updated cmpl desc. The cache API also issues dsb. */ dma_mb(); /* Decode cmpl pkt id to verify */ c = (struct cmpl_pkt *)((uintptr_t)ring->cmpl + PAX_DMA_CMPL_DESC_SIZE * PAX_DMA_CURR_CMPL_IDX(wr_offs)); LOG_DBG("RING%d WR_PTR:%d opq:%d, rm_status:%x dma_status:%x\n", idx, wr_offs, c->opq, c->rm_status, c->dma_status); is_outstanding = sys_read32(RM_RING_REG(pd, idx, RING_NUM_REQ_OUTSTAND)); if ((ring->curr.opq != c->opq) && (is_outstanding != 0)) { LOG_ERR("RING%d: pkt id should be %d, rcvd %d outst=%d\n", idx, ring->curr.opq, c->opq, is_outstanding); ret = -EIO; } /* check for completion AE timeout */ if (c->rm_status == RM_COMPLETION_AE_TIMEOUT) { LOG_ERR("RING%d WR_PTR:%d rm_status:%x AE Timeout!\n", idx, wr_offs, c->rm_status); /* TBD: Issue full card reset to restore operations */ LOG_ERR("Needs Card Reset to recover!\n"); ret = -ETIMEDOUT; } if (ring->dma_callback) { ring->dma_callback(dev, ring->callback_arg, idx, ret); } return ret; } #ifdef CONFIG_DMA_IPROC_PAX_POLL_MODE static int peek_ring_cmpl(const struct device *dev, enum ring_idx idx, uint32_t pl_len) { struct dma_iproc_pax_data *pd = PAX_DMA_DEV_DATA(dev); uint32_t wr_offs, rd_offs, timeout = PAX_DMA_MAX_POLL_WAIT; struct dma_iproc_pax_ring_data *ring = &(pd->ring[idx]); /* cmpl read offset, unprocessed cmpl location */ rd_offs = ring->curr.cmpl_rd_offs; /* poll write_ptr until cmpl received for all buffers */ do { wr_offs = sys_read32(RM_RING_REG(pd, idx, RING_CMPL_WRITE_PTR)); if (PAX_DMA_GET_CMPL_COUNT(wr_offs, rd_offs) >= pl_len) break; k_busy_wait(1); } while (--timeout); if (timeout == 0) { LOG_ERR("RING%d timeout, rcvd %d, expected %d!\n", idx, PAX_DMA_GET_CMPL_COUNT(wr_offs, rd_offs), pl_len); /* More debug info on current dma instance */ LOG_ERR("WR_PTR:%x RD_PTR%x\n", wr_offs, rd_offs); return -ETIMEDOUT; } return process_cmpl_event(dev, idx, pl_len); } #else static void rm_isr(void *arg) { uint32_t status, err_stat, idx; const struct device *dev = arg; struct dma_iproc_pax_data *pd = PAX_DMA_DEV_DATA(dev); /* read and clear interrupt status */ status = sys_read32(RM_COMM_REG(pd, RM_COMM_MSI_INTR_INTERRUPT_STATUS)); sys_write32(status, RM_COMM_REG(pd, RM_COMM_MSI_INTERRUPT_STATUS_CLEAR)); /* read and clear DME/AE error interrupts */ err_stat = sys_read32(RM_COMM_REG(pd, RM_COMM_DME_INTERRUPT_STATUS_MASK)); sys_write32(err_stat, RM_COMM_REG(pd, RM_COMM_DME_INTERRUPT_STATUS_CLEAR)); err_stat = sys_read32(RM_COMM_REG(pd, RM_COMM_AE_INTERFACE_GROUP_0_INTERRUPT_MASK)); sys_write32(err_stat, RM_COMM_REG(pd, RM_COMM_AE_INTERFACE_GROUP_0_INTERRUPT_CLEAR)); /* alert waiting thread to process, for each completed ring */ for (idx = PAX_DMA_RING0; idx < PAX_DMA_RINGS_MAX; idx++) { if (status & (0x1 << idx)) { k_sem_give(&pd->ring[idx].alert); } } } #endif static int dma_iproc_pax_init(const struct device *dev) { struct dma_iproc_pax_cfg *cfg = PAX_DMA_DEV_CFG(dev); struct dma_iproc_pax_data *pd = PAX_DMA_DEV_DATA(dev); int r; uintptr_t mem_aligned; pd->dma_base = cfg->dma_base; pd->rm_comm_base = cfg->rm_comm_base; pd->used_rings = (cfg->use_rings < PAX_DMA_RINGS_MAX) ? cfg->use_rings : PAX_DMA_RINGS_MAX; LOG_DBG("dma base:0x%x, rm comm base:0x%x, needed rings %d\n", pd->dma_base, pd->rm_comm_base, pd->used_rings); /* dma/rm access lock */ k_mutex_init(&pd->dma_lock); /* Ring Manager H/W init */ if (init_rm(pd)) { return -ETIMEDOUT; } /* common rm config */ rm_cfg_start(pd); /* individual ring config */ for (r = 0; r < pd->used_rings; r++) { /* per-ring mutex lock */ k_mutex_init(&pd->ring[r].lock); /* Init alerts */ k_sem_init(&pd->ring[r].alert, 0, 1); pd->ring[r].idx = r; pd->ring[r].ring_base = cfg->rm_base + PAX_DMA_RING_ADDR_OFFSET(r); LOG_DBG("RING%d,VERSION:0x%x\n", pd->ring[r].idx, sys_read32(RM_RING_REG(pd, r, RING_VER))); /* Allocate for 2 BD buffers + cmpl buffer + payload struct */ pd->ring[r].ring_mem = (void *)((uintptr_t)cfg->bd_memory_base + r * PAX_DMA_PER_RING_ALLOC_SIZE); if (!pd->ring[r].ring_mem) { LOG_ERR("RING%d failed to alloc desc memory!\n", r); return -ENOMEM; } /* Find 8K aligned address within allocated region */ mem_aligned = ((uintptr_t)pd->ring[r].ring_mem + PAX_DMA_RING_ALIGN - 1) & ~(PAX_DMA_RING_ALIGN - 1); pd->ring[r].cmpl = (void *)mem_aligned; pd->ring[r].bd = (void *)(mem_aligned + PAX_DMA_RM_CMPL_RING_SIZE); pd->ring[r].payload = (void *)((uintptr_t)pd->ring[r].bd + PAX_DMA_RM_DESC_RING_SIZE * PAX_DMA_NUM_BD_BUFFS); LOG_DBG("Ring%d,allocated Mem:0x%p Size %d\n", pd->ring[r].idx, pd->ring[r].ring_mem, PAX_DMA_PER_RING_ALLOC_SIZE); LOG_DBG("Ring%d,BD:0x%p, CMPL:0x%p, PL:0x%p\n", pd->ring[r].idx, pd->ring[r].bd, pd->ring[r].cmpl, pd->ring[r].payload); /* Prepare ring desc table */ prepare_ring(&(pd->ring[r])); /* initialize ring */ init_ring(pd, r); } /* set ring config done */ rm_cfg_finish(pd); #ifndef CONFIG_DMA_IPROC_PAX_POLL_MODE /* Register and enable RM interrupt */ IRQ_CONNECT(DT_INST_IRQN(0), DT_INST_IRQ(0, priority), rm_isr, DEVICE_GET(dma_iproc_pax), 0); irq_enable(DT_INST_IRQN(0)); #else LOG_INF("%s PAX DMA rings in poll mode!\n", PAX_DMA_DEV_NAME(dev)); #endif LOG_INF("%s RM setup %d rings\n", PAX_DMA_DEV_NAME(dev), pd->used_rings); return 0; } #ifdef CONFIG_DMA_IPROC_PAX_POLL_MODE static void set_pkt_count(const struct device *dev, enum ring_idx idx, uint32_t pl_len) { /* Nothing needs to be programmed here in poll mode */ } static int wait_for_pkt_completion(const struct device *dev, enum ring_idx idx, uint32_t pl_len) { /* poll for completion */ return peek_ring_cmpl(dev, idx, pl_len + 1); } #else static void set_pkt_count(const struct device *dev, enum ring_idx idx, uint32_t pl_len) { struct dma_iproc_pax_data *pd = PAX_DMA_DEV_DATA(dev); uint32_t val; /* program packet count for interrupt assertion */ val = sys_read32(RM_RING_REG(pd, idx, RING_CMPL_WR_PTR_DDR_CONTROL)); val &= ~RING_DDR_CONTROL_COUNT_MASK; val |= RING_DDR_CONTROL_COUNT(pl_len); sys_write32(val, RM_RING_REG(pd, idx, RING_CMPL_WR_PTR_DDR_CONTROL)); } static int wait_for_pkt_completion(const struct device *dev, enum ring_idx idx, uint32_t pl_len) { struct dma_iproc_pax_data *pd = PAX_DMA_DEV_DATA(dev); struct dma_iproc_pax_ring_data *ring; ring = &(pd->ring[idx]); /* wait for sg dma completion alert */ if (k_sem_take(&ring->alert, K_MSEC(PAX_DMA_TIMEOUT)) != 0) { LOG_ERR("PAX DMA [ring %d] Timeout!\n", idx); return -ETIMEDOUT; } return process_cmpl_event(dev, idx, pl_len); } #endif static int dma_iproc_pax_do_xfer(const struct device *dev, enum ring_idx idx, struct dma_iproc_pax_payload *pl, uint32_t pl_len) { struct dma_iproc_pax_data *pd = PAX_DMA_DEV_DATA(dev); struct dma_iproc_pax_cfg *cfg = PAX_DMA_DEV_CFG(dev); int ret = 0, cnt; struct dma_iproc_pax_ring_data *ring; void *hdr; uint32_t toggle_bit; struct dma_iproc_pax_payload sync_pl; struct dma_iproc_pax_addr64 sync; ring = &(pd->ring[idx]); pl = ring->payload; /* * Host sync buffer isn't ready at zephyr/driver init-time * Read the host address location once at first DMA write * on that ring. */ if ((ring->sync_pci.addr_lo == 0x0) && (ring->sync_pci.addr_hi == 0x0)) { /* populate sync data location */ LOG_DBG("sync addr loc 0x%x\n", cfg->scr_addr_loc); sync.addr_lo = sys_read32(cfg->scr_addr_loc + 4); sync.addr_hi = sys_read32(cfg->scr_addr_loc); ring->sync_pci.addr_lo = sync.addr_lo + idx * 4; ring->sync_pci.addr_hi = sync.addr_hi; LOG_DBG("ring:%d,sync addr:0x%x.0x%x\n", idx, ring->sync_pci.addr_hi, ring->sync_pci.addr_lo); } /* account extra sync packet */ ring->curr.sync_data.opaque = ring->curr.opq; ring->curr.sync_data.total_pkts = pl_len; memcpy((void *)&ring->sync_loc, (void *)&(ring->curr.sync_data), 4); sync_pl.pci_addr = ring->sync_pci.addr_lo | (uint64_t)ring->sync_pci.addr_hi << 32; sync_pl.axi_addr = (uintptr_t)&ring->sync_loc; sync_pl.xfer_sz = 4; /* 4-bytes */ sync_pl.direction = CARD_TO_HOST; /* Get descriptor write pointer for first header */ hdr = (void *)ring->curr.write_ptr; /* current toggle bit */ toggle_bit = ring->curr.toggle; /* current opq value for cmpl check */ ring->curr.opq = curr_pkt_id(ring); /* DMA desc count for first payload */ rm_header_set_bd_count(hdr, PAX_DMA_RM_DESC_BDCOUNT); /* Form dma descriptors for total sg payload */ for (cnt = 0; cnt < pl_len; cnt++) { rm_write_dma_header_desc(next_desc_addr(ring), pl + cnt); rm_write_axi_addr_desc(next_desc_addr(ring), pl + cnt); rm_write_pci_addr_desc(next_desc_addr(ring), pl + cnt); /* Toggle may flip, program updated toggle value */ rm_write_header_desc(next_desc_addr(ring), curr_toggle_val(ring), curr_pkt_id(ring), PAX_DMA_RM_DESC_BDCOUNT); } /* Append write sync payload descriptors */ rm_write_dma_header_desc(next_desc_addr(ring), &sync_pl); rm_write_axi_addr_desc(next_desc_addr(ring), &sync_pl); rm_write_pci_addr_desc(next_desc_addr(ring), &sync_pl); /* RM header for next transfer, RM wait on (invalid) toggle bit */ rm_write_header_next_desc(next_desc_addr(ring), ring, alloc_pkt_id(ring), PAX_DMA_RM_DESC_BDCOUNT); set_pkt_count(dev, idx, pl_len + 1); /* Ensure memory write before toggle flip */ dma_mb(); /* set toggle to valid in first header */ rm_header_set_toggle(hdr, toggle_bit); /* activate the ring */ set_ring_active(pd, idx, true); ret = wait_for_pkt_completion(dev, idx, pl_len + 1); if (ret) goto err_ret; ret = poll_on_write_sync(dev, ring); k_mutex_lock(&ring->lock, K_FOREVER); ring->ring_active = 0; k_mutex_unlock(&ring->lock); err_ret: ring->ring_active = 0; /* deactivate the ring until next active transfer */ set_ring_active(pd, idx, false); return ret; } static int dma_iproc_pax_configure(const struct device *dev, uint32_t channel, struct dma_config *cfg) { struct dma_iproc_pax_data *pd = PAX_DMA_DEV_DATA(dev); struct dma_iproc_pax_ring_data *ring; uint32_t xfer_sz; int ret = 0; #ifdef CONFIG_DMA_IPROC_PAX_DEBUG uint32_t *pci_addr32; uint32_t *axi_addr32; #endif if (channel >= PAX_DMA_RINGS_MAX) { LOG_ERR("Invalid ring/channel %d\n", channel); return -EINVAL; } ring = &(pd->ring[channel]); k_mutex_lock(&ring->lock, K_FOREVER); if (cfg->block_count > 1) { /* Scatter/gather list handling is not supported */ ret = -ENOTSUP; goto err; } if (ring->ring_active) { ret = -EBUSY; goto err; } ring->ring_active = 1; if (cfg->channel_direction == MEMORY_TO_PERIPHERAL) { #ifdef CONFIG_DMA_IPROC_PAX_DEBUG axi_addr32 = (uint32_t *)&cfg->head_block->source_address; pci_addr32 = (uint32_t *)&cfg->head_block->dest_address; #endif ring->payload->direction = CARD_TO_HOST; ring->payload->pci_addr = cfg->head_block->dest_address; ring->payload->axi_addr = cfg->head_block->source_address; } else if (cfg->channel_direction == PERIPHERAL_TO_MEMORY) { #ifdef CONFIG_DMA_IPROC_PAX_DEBUG axi_addr32 = (uint32_t *)&cfg->head_block->dest_address; pci_addr32 = (uint32_t *)&cfg->head_block->source_address; #endif ring->payload->direction = HOST_TO_CARD; ring->payload->pci_addr = cfg->head_block->source_address; ring->payload->axi_addr = cfg->head_block->dest_address; } else { ring->ring_active = 0; ret = -ENOTSUP; goto err; } xfer_sz = cfg->head_block->block_size; #ifdef CONFIG_DMA_IPROC_PAX_DEBUG if (xfer_sz > PAX_DMA_MAX_SIZE) { LOG_ERR("Unsupported size: %d\n", xfer_size); ring->ring_active = 0; ret = -EINVAL; goto err; } if (xfer_sz % PAX_DMA_MIN_SIZE) { LOG_ERR("Unaligned size 0x%x\n", xfer_size); ring->ring_active = 0; ret = -EINVAL; goto err; } if (pci_addr32[0] % PAX_DMA_ADDR_ALIGN) { LOG_ERR("Unaligned Host addr: 0x%x.0x%x\n", pci_addr32[1], pci_addr32[0]); ring->ring_active = 0; ret = -EINVAL; goto err; } if (axi_addr32[0] % PAX_DMA_ADDR_ALIGN) { LOG_ERR("Unaligned Card addr: 0x%x.0x%x\n", axi_addr32[1], axi_addr32[0]); ring->ring_active = 0; ret = -EINVAL; goto err; } #endif ring->payload->xfer_sz = xfer_sz; ring->dma_callback = cfg->dma_callback; ring->callback_arg = cfg->user_data; err: k_mutex_unlock(&ring->lock); return ret; } static int dma_iproc_pax_transfer_start(const struct device *dev, uint32_t channel) { int ret = 0; struct dma_iproc_pax_data *pd = PAX_DMA_DEV_DATA(dev); struct dma_iproc_pax_ring_data *ring; if (channel >= PAX_DMA_RINGS_MAX) { LOG_ERR("Invalid ring %d\n", channel); return -EINVAL; } ring = &(pd->ring[channel]); /* do dma transfer of single buffer */ ret = dma_iproc_pax_do_xfer(dev, channel, ring->payload, 1); return ret; } static int dma_iproc_pax_transfer_stop(const struct device *dev, uint32_t channel) { return 0; } static const struct dma_driver_api pax_dma_driver_api = { .config = dma_iproc_pax_configure, .start = dma_iproc_pax_transfer_start, .stop = dma_iproc_pax_transfer_stop, }; static const struct dma_iproc_pax_cfg pax_dma_cfg = { .dma_base = DT_INST_REG_ADDR_BY_NAME(0, dme_regs), .rm_base = DT_INST_REG_ADDR_BY_NAME(0, rm_ring_regs), .rm_comm_base = DT_INST_REG_ADDR_BY_NAME(0, rm_comm_regs), .use_rings = DT_INST_PROP(0, dma_channels), .bd_memory_base = (void *)DT_INST_PROP_BY_IDX(0, bd_memory, 0), .scr_addr_loc = DT_INST_PROP(0, scr_addr_loc), .pcie_dev_name = DT_INST_PROP_BY_PHANDLE(0, pcie_ep, label), }; DEVICE_AND_API_INIT(dma_iproc_pax, DT_INST_LABEL(0), &dma_iproc_pax_init, &pax_dma_data, &pax_dma_cfg, POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEVICE, &pax_dma_driver_api);
991358.c
/* * linux/drivers/mfd/ucb1x00-core.c * * Copyright (C) 2001 Russell King, 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. * * The UCB1x00 core driver provides basic services for handling IO, * the ADC, interrupts, and accessing registers. It is designed * such that everything goes through this layer, thereby providing * a consistent locking methodology, as well as allowing the drivers * to be used on other non-MCP-enabled hardware platforms. * * Note that all locks are private to this file. Nothing else may * touch them. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/errno.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/device.h> #include <linux/mutex.h> #include <linux/mfd/ucb1x00.h> #include <linux/pm.h> #include <linux/gpio.h> static DEFINE_MUTEX(ucb1x00_mutex); static LIST_HEAD(ucb1x00_drivers); static LIST_HEAD(ucb1x00_devices); /** * ucb1x00_io_set_dir - set IO direction * @ucb: UCB1x00 structure describing chip * @in: bitfield of IO pins to be set as inputs * @out: bitfield of IO pins to be set as outputs * * Set the IO direction of the ten general purpose IO pins on * the UCB1x00 chip. The @in bitfield has priority over the * @out bitfield, in that if you specify a pin as both input * and output, it will end up as an input. * * ucb1x00_enable must have been called to enable the comms * before using this function. * * This function takes a spinlock, disabling interrupts. */ void ucb1x00_io_set_dir(struct ucb1x00 *ucb, unsigned int in, unsigned int out) { unsigned long flags; spin_lock_irqsave(&ucb->io_lock, flags); ucb->io_dir |= out; ucb->io_dir &= ~in; ucb1x00_reg_write(ucb, UCB_IO_DIR, ucb->io_dir); spin_unlock_irqrestore(&ucb->io_lock, flags); } /** * ucb1x00_io_write - set or clear IO outputs * @ucb: UCB1x00 structure describing chip * @set: bitfield of IO pins to set to logic '1' * @clear: bitfield of IO pins to set to logic '0' * * Set the IO output state of the specified IO pins. The value * is retained if the pins are subsequently configured as inputs. * The @clear bitfield has priority over the @set bitfield - * outputs will be cleared. * * ucb1x00_enable must have been called to enable the comms * before using this function. * * This function takes a spinlock, disabling interrupts. */ void ucb1x00_io_write(struct ucb1x00 *ucb, unsigned int set, unsigned int clear) { unsigned long flags; spin_lock_irqsave(&ucb->io_lock, flags); ucb->io_out |= set; ucb->io_out &= ~clear; ucb1x00_reg_write(ucb, UCB_IO_DATA, ucb->io_out); spin_unlock_irqrestore(&ucb->io_lock, flags); } /** * ucb1x00_io_read - read the current state of the IO pins * @ucb: UCB1x00 structure describing chip * * Return a bitfield describing the logic state of the ten * general purpose IO pins. * * ucb1x00_enable must have been called to enable the comms * before using this function. * * This function does not take any mutexes or spinlocks. */ unsigned int ucb1x00_io_read(struct ucb1x00 *ucb) { return ucb1x00_reg_read(ucb, UCB_IO_DATA); } static void ucb1x00_gpio_set(struct gpio_chip *chip, unsigned offset, int value) { struct ucb1x00 *ucb = container_of(chip, struct ucb1x00, gpio); unsigned long flags; spin_lock_irqsave(&ucb->io_lock, flags); if (value) ucb->io_out |= 1 << offset; else ucb->io_out &= ~(1 << offset); ucb1x00_enable(ucb); ucb1x00_reg_write(ucb, UCB_IO_DATA, ucb->io_out); ucb1x00_disable(ucb); spin_unlock_irqrestore(&ucb->io_lock, flags); } static int ucb1x00_gpio_get(struct gpio_chip *chip, unsigned offset) { struct ucb1x00 *ucb = container_of(chip, struct ucb1x00, gpio); unsigned val; ucb1x00_enable(ucb); val = ucb1x00_reg_read(ucb, UCB_IO_DATA); ucb1x00_disable(ucb); return val & (1 << offset); } static int ucb1x00_gpio_direction_input(struct gpio_chip *chip, unsigned offset) { struct ucb1x00 *ucb = container_of(chip, struct ucb1x00, gpio); unsigned long flags; spin_lock_irqsave(&ucb->io_lock, flags); ucb->io_dir &= ~(1 << offset); ucb1x00_enable(ucb); ucb1x00_reg_write(ucb, UCB_IO_DIR, ucb->io_dir); ucb1x00_disable(ucb); spin_unlock_irqrestore(&ucb->io_lock, flags); return 0; } static int ucb1x00_gpio_direction_output(struct gpio_chip *chip, unsigned offset , int value) { struct ucb1x00 *ucb = container_of(chip, struct ucb1x00, gpio); unsigned long flags; unsigned old, mask = 1 << offset; spin_lock_irqsave(&ucb->io_lock, flags); old = ucb->io_out; if (value) ucb->io_out |= mask; else ucb->io_out &= ~mask; ucb1x00_enable(ucb); if (old != ucb->io_out) ucb1x00_reg_write(ucb, UCB_IO_DATA, ucb->io_out); if (!(ucb->io_dir & mask)) { ucb->io_dir |= mask; ucb1x00_reg_write(ucb, UCB_IO_DIR, ucb->io_dir); } ucb1x00_disable(ucb); spin_unlock_irqrestore(&ucb->io_lock, flags); return 0; } static int ucb1x00_to_irq(struct gpio_chip *chip, unsigned offset) { struct ucb1x00 *ucb = container_of(chip, struct ucb1x00, gpio); return ucb->irq_base > 0 ? ucb->irq_base + offset : -ENXIO; } /* * UCB1300 data sheet says we must: * 1. enable ADC => 5us (including reference startup time) * 2. select input => 51*tsibclk => 4.3us * 3. start conversion => 102*tsibclk => 8.5us * (tsibclk = 1/11981000) * Period between SIB 128-bit frames = 10.7us */ /** * ucb1x00_adc_enable - enable the ADC converter * @ucb: UCB1x00 structure describing chip * * Enable the ucb1x00 and ADC converter on the UCB1x00 for use. * Any code wishing to use the ADC converter must call this * function prior to using it. * * This function takes the ADC mutex to prevent two or more * concurrent uses, and therefore may sleep. As a result, it * can only be called from process context, not interrupt * context. * * You should release the ADC as soon as possible using * ucb1x00_adc_disable. */ void ucb1x00_adc_enable(struct ucb1x00 *ucb) { mutex_lock(&ucb->adc_mutex); ucb->adc_cr |= UCB_ADC_ENA; ucb1x00_enable(ucb); ucb1x00_reg_write(ucb, UCB_ADC_CR, ucb->adc_cr); } /** * ucb1x00_adc_read - read the specified ADC channel * @ucb: UCB1x00 structure describing chip * @adc_channel: ADC channel mask * @sync: wait for syncronisation pulse. * * Start an ADC conversion and wait for the result. Note that * synchronised ADC conversions (via the ADCSYNC pin) must wait * until the trigger is asserted and the conversion is finished. * * This function currently spins waiting for the conversion to * complete (2 frames max without sync). * * If called for a synchronised ADC conversion, it may sleep * with the ADC mutex held. */ unsigned int ucb1x00_adc_read(struct ucb1x00 *ucb, int adc_channel, int sync) { unsigned int val; if (sync) adc_channel |= UCB_ADC_SYNC_ENA; ucb1x00_reg_write(ucb, UCB_ADC_CR, ucb->adc_cr | adc_channel); ucb1x00_reg_write(ucb, UCB_ADC_CR, ucb->adc_cr | adc_channel | UCB_ADC_START); for (;;) { val = ucb1x00_reg_read(ucb, UCB_ADC_DATA); if (val & UCB_ADC_DAT_VAL) break; /* yield to other processes */ set_current_state(TASK_INTERRUPTIBLE); schedule_timeout(1); } return UCB_ADC_DAT(val); } /** * ucb1x00_adc_disable - disable the ADC converter * @ucb: UCB1x00 structure describing chip * * Disable the ADC converter and release the ADC mutex. */ void ucb1x00_adc_disable(struct ucb1x00 *ucb) { ucb->adc_cr &= ~UCB_ADC_ENA; ucb1x00_reg_write(ucb, UCB_ADC_CR, ucb->adc_cr); ucb1x00_disable(ucb); mutex_unlock(&ucb->adc_mutex); } /* * UCB1x00 Interrupt handling. * * The UCB1x00 can generate interrupts when the SIBCLK is stopped. * Since we need to read an internal register, we must re-enable * SIBCLK to talk to the chip. We leave the clock running until * we have finished processing all interrupts from the chip. */ static void ucb1x00_irq(unsigned int irq, struct irq_desc *desc) { struct ucb1x00 *ucb = irq_desc_get_handler_data(desc); unsigned int isr, i; ucb1x00_enable(ucb); isr = ucb1x00_reg_read(ucb, UCB_IE_STATUS); ucb1x00_reg_write(ucb, UCB_IE_CLEAR, isr); ucb1x00_reg_write(ucb, UCB_IE_CLEAR, 0); for (i = 0; i < 16 && isr; i++, isr >>= 1, irq++) if (isr & 1) generic_handle_irq(ucb->irq_base + i); ucb1x00_disable(ucb); } static void ucb1x00_irq_update(struct ucb1x00 *ucb, unsigned mask) { ucb1x00_enable(ucb); if (ucb->irq_ris_enbl & mask) ucb1x00_reg_write(ucb, UCB_IE_RIS, ucb->irq_ris_enbl & ucb->irq_mask); if (ucb->irq_fal_enbl & mask) ucb1x00_reg_write(ucb, UCB_IE_FAL, ucb->irq_fal_enbl & ucb->irq_mask); ucb1x00_disable(ucb); } static void ucb1x00_irq_noop(struct irq_data *data) { } static void ucb1x00_irq_mask(struct irq_data *data) { struct ucb1x00 *ucb = irq_data_get_irq_chip_data(data); unsigned mask = 1 << (data->irq - ucb->irq_base); raw_spin_lock(&ucb->irq_lock); ucb->irq_mask &= ~mask; ucb1x00_irq_update(ucb, mask); raw_spin_unlock(&ucb->irq_lock); } static void ucb1x00_irq_unmask(struct irq_data *data) { struct ucb1x00 *ucb = irq_data_get_irq_chip_data(data); unsigned mask = 1 << (data->irq - ucb->irq_base); raw_spin_lock(&ucb->irq_lock); ucb->irq_mask |= mask; ucb1x00_irq_update(ucb, mask); raw_spin_unlock(&ucb->irq_lock); } static int ucb1x00_irq_set_type(struct irq_data *data, unsigned int type) { struct ucb1x00 *ucb = irq_data_get_irq_chip_data(data); unsigned mask = 1 << (data->irq - ucb->irq_base); raw_spin_lock(&ucb->irq_lock); if (type & IRQ_TYPE_EDGE_RISING) ucb->irq_ris_enbl |= mask; else ucb->irq_ris_enbl &= ~mask; if (type & IRQ_TYPE_EDGE_FALLING) ucb->irq_fal_enbl |= mask; else ucb->irq_fal_enbl &= ~mask; if (ucb->irq_mask & mask) { ucb1x00_reg_write(ucb, UCB_IE_RIS, ucb->irq_ris_enbl & ucb->irq_mask); ucb1x00_reg_write(ucb, UCB_IE_FAL, ucb->irq_fal_enbl & ucb->irq_mask); } raw_spin_unlock(&ucb->irq_lock); return 0; } static int ucb1x00_irq_set_wake(struct irq_data *data, unsigned int on) { struct ucb1x00 *ucb = irq_data_get_irq_chip_data(data); struct ucb1x00_plat_data *pdata = ucb->mcp->attached_device.platform_data; unsigned mask = 1 << (data->irq - ucb->irq_base); if (!pdata || !pdata->can_wakeup) return -EINVAL; raw_spin_lock(&ucb->irq_lock); if (on) ucb->irq_wake |= mask; else ucb->irq_wake &= ~mask; raw_spin_unlock(&ucb->irq_lock); return 0; } static struct irq_chip ucb1x00_irqchip = { .name = "ucb1x00", .irq_ack = ucb1x00_irq_noop, .irq_mask = ucb1x00_irq_mask, .irq_unmask = ucb1x00_irq_unmask, .irq_set_type = ucb1x00_irq_set_type, .irq_set_wake = ucb1x00_irq_set_wake, }; static int ucb1x00_add_dev(struct ucb1x00 *ucb, struct ucb1x00_driver *drv) { struct ucb1x00_dev *dev; int ret; dev = kmalloc(sizeof(struct ucb1x00_dev), GFP_KERNEL); if (!dev) return -ENOMEM; dev->ucb = ucb; dev->drv = drv; ret = drv->add(dev); if (ret) { kfree(dev); return ret; } list_add_tail(&dev->dev_node, &ucb->devs); list_add_tail(&dev->drv_node, &drv->devs); return ret; } static void ucb1x00_remove_dev(struct ucb1x00_dev *dev) { dev->drv->remove(dev); list_del(&dev->dev_node); list_del(&dev->drv_node); kfree(dev); } /* * Try to probe our interrupt, rather than relying on lots of * hard-coded machine dependencies. For reference, the expected * IRQ mappings are: * * Machine Default IRQ * adsbitsy IRQ_GPCIN4 * cerf IRQ_GPIO_UCB1200_IRQ * flexanet IRQ_GPIO_GUI * freebird IRQ_GPIO_FREEBIRD_UCB1300_IRQ * graphicsclient ADS_EXT_IRQ(8) * graphicsmaster ADS_EXT_IRQ(8) * lart LART_IRQ_UCB1200 * omnimeter IRQ_GPIO23 * pfs168 IRQ_GPIO_UCB1300_IRQ * simpad IRQ_GPIO_UCB1300_IRQ * shannon SHANNON_IRQ_GPIO_IRQ_CODEC * yopy IRQ_GPIO_UCB1200_IRQ */ static int ucb1x00_detect_irq(struct ucb1x00 *ucb) { unsigned long mask; mask = probe_irq_on(); if (!mask) { probe_irq_off(mask); return NO_IRQ; } /* * Enable the ADC interrupt. */ ucb1x00_reg_write(ucb, UCB_IE_RIS, UCB_IE_ADC); ucb1x00_reg_write(ucb, UCB_IE_FAL, UCB_IE_ADC); ucb1x00_reg_write(ucb, UCB_IE_CLEAR, 0xffff); ucb1x00_reg_write(ucb, UCB_IE_CLEAR, 0); /* * Cause an ADC interrupt. */ ucb1x00_reg_write(ucb, UCB_ADC_CR, UCB_ADC_ENA); ucb1x00_reg_write(ucb, UCB_ADC_CR, UCB_ADC_ENA | UCB_ADC_START); /* * Wait for the conversion to complete. */ while ((ucb1x00_reg_read(ucb, UCB_ADC_DATA) & UCB_ADC_DAT_VAL) == 0); ucb1x00_reg_write(ucb, UCB_ADC_CR, 0); /* * Disable and clear interrupt. */ ucb1x00_reg_write(ucb, UCB_IE_RIS, 0); ucb1x00_reg_write(ucb, UCB_IE_FAL, 0); ucb1x00_reg_write(ucb, UCB_IE_CLEAR, 0xffff); ucb1x00_reg_write(ucb, UCB_IE_CLEAR, 0); /* * Read triggered interrupt. */ return probe_irq_off(mask); } static void ucb1x00_release(struct device *dev) { struct ucb1x00 *ucb = classdev_to_ucb1x00(dev); kfree(ucb); } static struct class ucb1x00_class = { .name = "ucb1x00", .dev_release = ucb1x00_release, }; static int ucb1x00_probe(struct mcp *mcp) { struct ucb1x00_plat_data *pdata = mcp->attached_device.platform_data; struct ucb1x00_driver *drv; struct ucb1x00 *ucb; unsigned id, i, irq_base; int ret = -ENODEV; /* Tell the platform to deassert the UCB1x00 reset */ if (pdata && pdata->reset) pdata->reset(UCB_RST_PROBE); mcp_enable(mcp); id = mcp_reg_read(mcp, UCB_ID); mcp_disable(mcp); if (id != UCB_ID_1200 && id != UCB_ID_1300 && id != UCB_ID_TC35143) { printk(KERN_WARNING "UCB1x00 ID not found: %04x\n", id); goto out; } ucb = kzalloc(sizeof(struct ucb1x00), GFP_KERNEL); ret = -ENOMEM; if (!ucb) goto out; device_initialize(&ucb->dev); ucb->dev.class = &ucb1x00_class; ucb->dev.parent = &mcp->attached_device; dev_set_name(&ucb->dev, "ucb1x00"); raw_spin_lock_init(&ucb->irq_lock); spin_lock_init(&ucb->io_lock); mutex_init(&ucb->adc_mutex); ucb->id = id; ucb->mcp = mcp; ret = device_add(&ucb->dev); if (ret) goto err_dev_add; ucb1x00_enable(ucb); ucb->irq = ucb1x00_detect_irq(ucb); ucb1x00_disable(ucb); if (ucb->irq == NO_IRQ) { dev_err(&ucb->dev, "IRQ probe failed\n"); ret = -ENODEV; goto err_no_irq; } ucb->gpio.base = -1; irq_base = pdata ? pdata->irq_base : 0; ucb->irq_base = irq_alloc_descs(-1, irq_base, 16, -1); if (ucb->irq_base < 0) { dev_err(&ucb->dev, "unable to allocate 16 irqs: %d\n", ucb->irq_base); ret = ucb->irq_base; goto err_irq_alloc; } for (i = 0; i < 16; i++) { unsigned irq = ucb->irq_base + i; irq_set_chip_and_handler(irq, &ucb1x00_irqchip, handle_edge_irq); irq_set_chip_data(irq, ucb); set_irq_flags(irq, IRQF_VALID | IRQ_NOREQUEST); } irq_set_irq_type(ucb->irq, IRQ_TYPE_EDGE_RISING); irq_set_chained_handler_and_data(ucb->irq, ucb1x00_irq, ucb); if (pdata && pdata->gpio_base) { ucb->gpio.label = dev_name(&ucb->dev); ucb->gpio.dev = &ucb->dev; ucb->gpio.owner = THIS_MODULE; ucb->gpio.base = pdata->gpio_base; ucb->gpio.ngpio = 10; ucb->gpio.set = ucb1x00_gpio_set; ucb->gpio.get = ucb1x00_gpio_get; ucb->gpio.direction_input = ucb1x00_gpio_direction_input; ucb->gpio.direction_output = ucb1x00_gpio_direction_output; ucb->gpio.to_irq = ucb1x00_to_irq; ret = gpiochip_add(&ucb->gpio); if (ret) goto err_gpio_add; } else dev_info(&ucb->dev, "gpio_base not set so no gpiolib support"); mcp_set_drvdata(mcp, ucb); if (pdata) device_set_wakeup_capable(&ucb->dev, pdata->can_wakeup); INIT_LIST_HEAD(&ucb->devs); mutex_lock(&ucb1x00_mutex); list_add_tail(&ucb->node, &ucb1x00_devices); list_for_each_entry(drv, &ucb1x00_drivers, node) { ucb1x00_add_dev(ucb, drv); } mutex_unlock(&ucb1x00_mutex); return ret; err_gpio_add: irq_set_chained_handler(ucb->irq, NULL); err_irq_alloc: if (ucb->irq_base > 0) irq_free_descs(ucb->irq_base, 16); err_no_irq: device_del(&ucb->dev); err_dev_add: put_device(&ucb->dev); out: if (pdata && pdata->reset) pdata->reset(UCB_RST_PROBE_FAIL); return ret; } static void ucb1x00_remove(struct mcp *mcp) { struct ucb1x00_plat_data *pdata = mcp->attached_device.platform_data; struct ucb1x00 *ucb = mcp_get_drvdata(mcp); struct list_head *l, *n; mutex_lock(&ucb1x00_mutex); list_del(&ucb->node); list_for_each_safe(l, n, &ucb->devs) { struct ucb1x00_dev *dev = list_entry(l, struct ucb1x00_dev, dev_node); ucb1x00_remove_dev(dev); } mutex_unlock(&ucb1x00_mutex); if (ucb->gpio.base != -1) gpiochip_remove(&ucb->gpio); irq_set_chained_handler(ucb->irq, NULL); irq_free_descs(ucb->irq_base, 16); device_unregister(&ucb->dev); if (pdata && pdata->reset) pdata->reset(UCB_RST_REMOVE); } int ucb1x00_register_driver(struct ucb1x00_driver *drv) { struct ucb1x00 *ucb; INIT_LIST_HEAD(&drv->devs); mutex_lock(&ucb1x00_mutex); list_add_tail(&drv->node, &ucb1x00_drivers); list_for_each_entry(ucb, &ucb1x00_devices, node) { ucb1x00_add_dev(ucb, drv); } mutex_unlock(&ucb1x00_mutex); return 0; } void ucb1x00_unregister_driver(struct ucb1x00_driver *drv) { struct list_head *n, *l; mutex_lock(&ucb1x00_mutex); list_del(&drv->node); list_for_each_safe(l, n, &drv->devs) { struct ucb1x00_dev *dev = list_entry(l, struct ucb1x00_dev, drv_node); ucb1x00_remove_dev(dev); } mutex_unlock(&ucb1x00_mutex); } #ifdef CONFIG_PM_SLEEP static int ucb1x00_suspend(struct device *dev) { struct ucb1x00_plat_data *pdata = dev_get_platdata(dev); struct ucb1x00 *ucb = dev_get_drvdata(dev); struct ucb1x00_dev *udev; mutex_lock(&ucb1x00_mutex); list_for_each_entry(udev, &ucb->devs, dev_node) { if (udev->drv->suspend) udev->drv->suspend(udev); } mutex_unlock(&ucb1x00_mutex); if (ucb->irq_wake) { unsigned long flags; raw_spin_lock_irqsave(&ucb->irq_lock, flags); ucb1x00_enable(ucb); ucb1x00_reg_write(ucb, UCB_IE_RIS, ucb->irq_ris_enbl & ucb->irq_wake); ucb1x00_reg_write(ucb, UCB_IE_FAL, ucb->irq_fal_enbl & ucb->irq_wake); ucb1x00_disable(ucb); raw_spin_unlock_irqrestore(&ucb->irq_lock, flags); enable_irq_wake(ucb->irq); } else if (pdata && pdata->reset) pdata->reset(UCB_RST_SUSPEND); return 0; } static int ucb1x00_resume(struct device *dev) { struct ucb1x00_plat_data *pdata = dev_get_platdata(dev); struct ucb1x00 *ucb = dev_get_drvdata(dev); struct ucb1x00_dev *udev; if (!ucb->irq_wake && pdata && pdata->reset) pdata->reset(UCB_RST_RESUME); ucb1x00_enable(ucb); ucb1x00_reg_write(ucb, UCB_IO_DATA, ucb->io_out); ucb1x00_reg_write(ucb, UCB_IO_DIR, ucb->io_dir); if (ucb->irq_wake) { unsigned long flags; raw_spin_lock_irqsave(&ucb->irq_lock, flags); ucb1x00_reg_write(ucb, UCB_IE_RIS, ucb->irq_ris_enbl & ucb->irq_mask); ucb1x00_reg_write(ucb, UCB_IE_FAL, ucb->irq_fal_enbl & ucb->irq_mask); raw_spin_unlock_irqrestore(&ucb->irq_lock, flags); disable_irq_wake(ucb->irq); } ucb1x00_disable(ucb); mutex_lock(&ucb1x00_mutex); list_for_each_entry(udev, &ucb->devs, dev_node) { if (udev->drv->resume) udev->drv->resume(udev); } mutex_unlock(&ucb1x00_mutex); return 0; } #endif static SIMPLE_DEV_PM_OPS(ucb1x00_pm_ops, ucb1x00_suspend, ucb1x00_resume); static struct mcp_driver ucb1x00_driver = { .drv = { .name = "ucb1x00", .owner = THIS_MODULE, .pm = &ucb1x00_pm_ops, }, .probe = ucb1x00_probe, .remove = ucb1x00_remove, }; static int __init ucb1x00_init(void) { int ret = class_register(&ucb1x00_class); if (ret == 0) { ret = mcp_driver_register(&ucb1x00_driver); if (ret) class_unregister(&ucb1x00_class); } return ret; } static void __exit ucb1x00_exit(void) { mcp_driver_unregister(&ucb1x00_driver); class_unregister(&ucb1x00_class); } module_init(ucb1x00_init); module_exit(ucb1x00_exit); EXPORT_SYMBOL(ucb1x00_io_set_dir); EXPORT_SYMBOL(ucb1x00_io_write); EXPORT_SYMBOL(ucb1x00_io_read); EXPORT_SYMBOL(ucb1x00_adc_enable); EXPORT_SYMBOL(ucb1x00_adc_read); EXPORT_SYMBOL(ucb1x00_adc_disable); EXPORT_SYMBOL(ucb1x00_register_driver); EXPORT_SYMBOL(ucb1x00_unregister_driver); MODULE_ALIAS("mcp:ucb1x00"); MODULE_AUTHOR("Russell King <[email protected]>"); MODULE_DESCRIPTION("UCB1x00 core driver"); MODULE_LICENSE("GPL");
404720.c
/***************************************************************************//** * @file * @brief Used for testing the counters library via a command line interface. * For documentation on the counters library see counters.h. ******************************************************************************* * # License * <b>Copyright 2018 Silicon Laboratories Inc. www.silabs.com</b> ******************************************************************************* * * The licensor of this software is Silicon Laboratories Inc. Your use of this * software is governed by the terms of Silicon Labs Master Software License * Agreement (MSLA) available at * www.silabs.com/about-us/legal/master-software-license-agreement. This * software is distributed to you in Source Code format and is governed by the * sections of the MSLA applicable to Source Code. * ******************************************************************************/ #include "app/framework/include/af.h" #include "app/util/serial/command-interpreter2.h" #include "app/util/common/common.h" #include "counters.h" #include "counters-ota.h" #include "counters-cli.h" const char * titleStrings[] = { EMBER_COUNTER_STRINGS }; const char * unknownCounter = "???"; static void emberAfPluginCountersPrint(void); void emberAfPluginCountersPrintCommand(void) { #if defined(EZSP_HOST) ezspReadAndClearCounters(emberCounters); #endif emberAfPluginCountersPrint(); #if !defined(EZSP_HOST) emberAfPluginCountersClear(); #endif } void emberAfPluginCounterPrintCounterTypeCommand(void) { #if !defined(EZSP_HOST) uint8_t counterType = (uint8_t)emberUnsignedCommandArgument(0); if (counterType < EMBER_COUNTER_TYPE_COUNT) { emberAfCorePrintln("%u) %p: %u", counterType, (titleStrings[counterType] == NULL ? unknownCounter : titleStrings[counterType]), emberCounters[counterType]); } #endif } void emberAfPluginCountersSimplePrintCommand(void) { #if defined(EZSP_HOST) ezspReadCounters(emberCounters); #endif emberAfPluginCountersPrint(); } void emberAfPluginCountersSendRequestCommand(void) { #if defined(EMBER_AF_PLUGIN_COUNTERS_OTA) emberAfPluginCountersSendRequest(emberUnsignedCommandArgument(0), emberUnsignedCommandArgument(1)); #endif } void emberAfPluginCountersSetThresholdCommand(void) { EmberCounterType type = (uint8_t)emberUnsignedCommandArgument(0); uint16_t threshold = (uint16_t)emberUnsignedCommandArgument(1); emberAfCorePrintln("Setting Threshold command"); emberAfPluginCountersSetThreshold(type, threshold); } void emberAfPluginCountersPrintThresholdsCommand(void) { uint8_t i; for (i = 0; i < EMBER_COUNTER_TYPE_COUNT; i++) { emberAfCorePrintln("%u) %p: %u", i, (titleStrings[i] == NULL ? unknownCounter : titleStrings[i]), emberCountersThresholds[i]); } } #if !defined(EZSP_HOST) void emberAfPluginCounterPrintCountersResponse(EmberMessageBuffer message) { uint8_t i; uint8_t length = emberMessageBufferLength(message); for (i = 0; i < length; i += 3) { emberAfCorePrintln("%d: %d", emberGetLinkedBuffersByte(message, i), emberGetLinkedBuffersLowHighInt16u(message, i + 1)); } } #endif static void emberAfPluginCountersPrint(void) { uint8_t i; for (i = 0; i < EMBER_COUNTER_TYPE_COUNT; i++) { emberAfCorePrintln("%u) %p: %u", i, (titleStrings[i] == NULL ? unknownCounter : titleStrings[i]), emberCounters[i]); } }
423066.c
/* * Version: 0.0 * Design: manu k harshan * file : gsmmodem.c */ #include "datatypeconversion.h" #include "gsmModem.h" //int ginumber = 918610840814; //int ginumber = 918296448053; //int ginumber = 917795343490; int ginumber = 918317482672; char gcnumber[14]; char gsmcommandbuffer[40]; gsmmonitor gsgsmmonitor; int sms = 0; unsigned char command4[4]; unsigned char arg4[20]; gsmEventType gsmProcessReceiveEvent(char* response) { gsmEventType egsmEventType = GSM_NO_ANSWER; //duSendData1(response,strlen(response)); if(!memcmp(response,"OK\r",3)) return GSM_ANSWER_OK; else if(!memcmp(response,"ERROR\r",6)) return GSM_ERROR; // else if(!memcmp(response,"RING\r",14)) // return GSM_RING; else if(!memcmp(response,"+CME ERROR:",11)) return GSM_CME_ERROR; else if(!memcmp(response,"+CLIP:",6)) { //egsmEventType = gsmProcessReceivecommand(response); gsmProcessReceivecommand(CALLRECEIVECHECK,response); //return egsmEventType; return GSM_RING; } else if(!memcmp(response,"NO CARRIER\r",11)) return GSM_NO_CARRIER; else if(!memcmp(response,"+CMTI:",6)) { gsmProcessReceivecommand(SMSRECEIVEINDEX,response); //duSendData1("smsrec\r\n",strlen("smsrec\r\n")); return GSM_MESG_REC; } else if(!memcmp(response,"+CMGR:",6)) { egsmEventType = gsmProcessReceivecommand(SMSRECEIVECHECK,response); return egsmEventType; } else if(!memcmp(response,"+CSQ:",5)) { gsmProcessReceivecommand(RSSIRECEIVED,response); } else if(!memcmp(response,"+CPIN:",6)) { gsmProcessReceivecommand(SIMREADYCHECK,response); } else if(sms) { gsmProcessReceivecommand(SMSRECEIVED,response); } else if(!memcmp(response,">\r",2)) { return GSM_SMS_TRANMIT_READY; } // else if (!memcmp(response,"+CMGS:",6)) // { // // } } gsmEventType gsmProcessReceivecommand(recdatatype gerecdatatype,char* response) { gsmEventType gsmEvent; char message[40]; int i = 0,j=0,k=0,number; switch(gerecdatatype) { case CALLRECEIVECHECK: { while(*response!='\r') { if(i>8) { message[k++] = *response; } response++; i++; } k = 0; while(message[k] !='"') { gcnumber[j++] = message[k]; k++; } gcnumber[j]='\0'; number = atoi(&gcnumber[0]); if(ginumber == number) { duSendData1("call\r\n",strlen("call\r\n")); } gsmEvent = GSM_RING; break; } case SMSRECEIVECHECK: { response++; while(*response!='+') { response++; } response++; while(*response!='\r') { message[i++] = *response; response++; } i = 0; while(message[i] !='"') { gcnumber[j++] = message[i]; i++; } gcnumber[j]='\0'; number = atoi(&gcnumber[0]); if(ginumber == number) { duSendData1("sms\r\n",strlen("sms\r\n")); sms = 1; gsmEvent = GSM_KNOWN_MESG_REC; } gsmEvent = GSM_UNKNOWN_MESG_REC; break; } case SMSRECEIVEINDEX: { while(*response!='\r') { if(i>11) { message[k++] = *response; } response++; i++; } message[k] = '\0'; gsgsmmonitor.smsindex = atoi(&message[0]); unsignedIntToString(gsgsmmonitor.smsindex,DIGIT_2,&message[0]); duSendData1(message,2); gsmEvent = GSM_MESG_REC; break; } case SMSRECEIVED: { gsmProcessReceiveMsg(response); // while(*response!='\r') // { // message[i++] = *response; // response++; // } // message[i] = '\0'; sms = 0; duSendData1(response,strlen(response)); break; } case RSSIRECEIVED: { while(*response!=':') { response++; } response++; while(*response!=',') { message[i++] = *response; response++; } message[i] = '\0'; gsgsmmonitor.rssi = atoi(&message[0]); unsignedIntToString(gsgsmmonitor.rssi,DIGIT_2,&message[0]); duSendData1(message,strlen(message)); break; } case SIMREADYCHECK: { if(!memcmp(response,"+CPIN: READY",12)) { gsgsmmonitor.simstatus = 1; duSendData1("READY\r\n",strlen("READY\r\n")); gsmEvent = GSM_ANSWER_OK; } else { gsgsmmonitor.simstatus = 0; duSendData1("NOTREADY\r\n",strlen("NOTREADY\r\n")); gsmEvent = GSM_NO_ANSWER; } break; } } return gsmEvent; } int32_t getsmsindex(void) { return gsgsmmonitor.smsindex; } int32_t getrssi(void) { return gsgsmmonitor.rssi; } void gsmATcommand(void) { //strcpy(command,"radio set sf %s\r\n"); sprintf(gsmcommandbuffer,"AT\r",NULL); //send command guSendData(gsmcommandbuffer,strlen(gsmcommandbuffer)); } void gsmTurnOffecho(void) { sprintf(gsmcommandbuffer,"ATE0\r",NULL); //send command guSendData(gsmcommandbuffer,strlen(gsmcommandbuffer)); } void gsmSetErrcommand(char enable) { sprintf(gsmcommandbuffer,"AT+CMEE=%d\r",enable); //send command guSendData(gsmcommandbuffer,strlen(gsmcommandbuffer)); } void gsmSetStartIndication(int8_t start,int8_t ready) { sprintf(gsmcommandbuffer,"AT+MSTART:%d,%d\r",start,ready); //send command guSendData(gsmcommandbuffer,strlen(gsmcommandbuffer)); } void gsmSetCallerID(char set) { sprintf(gsmcommandbuffer,"AT+CLIP=%d\r",set); //send command guSendData(gsmcommandbuffer,strlen(gsmcommandbuffer)); } void gsmSimStatus(void) { sprintf(gsmcommandbuffer,"AT+CPIN?\r",NULL); //send command guSendData(gsmcommandbuffer,strlen(gsmcommandbuffer)); } void gsmTestorPduMode(char mod) { sprintf(gsmcommandbuffer,"AT+CMGF=%d\r",mod); //send command guSendData(gsmcommandbuffer,strlen(gsmcommandbuffer)); } void gsmSmsindication(int8_t mod,int8_t mt,int8_t bm,int8_t ds,int8_t bfr) { sprintf(gsmcommandbuffer,"AT+CNMI=%d,%d,%d,%d,%d\r",mod,mt,bm,ds,bfr); //send command guSendData(gsmcommandbuffer,strlen(gsmcommandbuffer)); } void gsmReadSms(int index1) { sprintf(gsmcommandbuffer,"AT+CMGR=%d\r",index1); //send command guSendData(gsmcommandbuffer,strlen(gsmcommandbuffer)); } void gsmSignalSrength(void) { sprintf(gsmcommandbuffer,"AT+CSQ?\r"); //send command guSendData(gsmcommandbuffer,strlen(gsmcommandbuffer)); } void gsmDeleteSms(int index1) { sprintf(gsmcommandbuffer,"AT+CMGD=%d\r",index1); guSendData(gsmcommandbuffer,strlen(gsmcommandbuffer)); } void gsmDeleteAllSms(void) { sprintf(gsmcommandbuffer,"AT+CMGD=1,4\r",NULL); guSendData(gsmcommandbuffer,strlen(gsmcommandbuffer)); } void gsmSendSms(char* mobNumber) { sprintf(gsmcommandbuffer,"AT+CMGS=\"+%s\"\r",mobNumber); duSendData1(gsmcommandbuffer,strlen(gsmcommandbuffer)); guSendData(gsmcommandbuffer,strlen(gsmcommandbuffer)); } void gsmSendSmsData(char* msg) { char ch=0x1A; sprintf(gsmcommandbuffer,"%s%c",msg,ch); duSendData1(gsmcommandbuffer,strlen(gsmcommandbuffer)); guSendData(gsmcommandbuffer,strlen(gsmcommandbuffer)); } gsmEventType gsmProcessReceiveMsg(char* Response) { gsmEventType geGsmEventType; geGsmEventType = GSM_MESG_REC; char message[20] = {0}; int i = 0; while(*Response != '\r') { message[i++] = *Response; Response++; } message[i] = '\0'; strncpy(&command4[0],&message[0],3); strcpy(&arg4[0],&message[3]); commandParse(&command4[0],&arg4[0],GSM); return geGsmEventType; }
663234.c
/* * FST module - Control Interface implementation * Copyright (c) 2014, Qualcomm Atheros, Inc. * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #include "utils/includes.h" #include "utils/common.h" #include "common/defs.h" #include "list.h" #include "fst/fst.h" #include "fst/fst_internal.h" #include "fst_ctrl_defs.h" #include "fst_ctrl_iface.h" static struct fst_group * get_fst_group_by_id(const char *id) { struct fst_group *g; foreach_fst_group(g) { const char *group_id = fst_group_get_id(g); if (os_strncmp(group_id, id, os_strlen(group_id)) == 0) return g; } return NULL; } /* notifications */ static bool format_session_state_extra(const union fst_event_extra *extra, char *buffer, size_t size) { int len; char reject_str[32] = FST_CTRL_PVAL_NONE; const char *initiator = FST_CTRL_PVAL_NONE; const struct fst_event_extra_session_state *ss; ss = &extra->session_state; if (ss->new_state != FST_SESSION_STATE_INITIAL) return true; switch (ss->extra.to_initial.reason) { case REASON_REJECT: if (ss->extra.to_initial.reject_code != WLAN_STATUS_SUCCESS) os_snprintf(reject_str, sizeof(reject_str), "%u", ss->extra.to_initial.reject_code); /* fall through */ case REASON_TEARDOWN: case REASON_SWITCH: switch (ss->extra.to_initial.initiator) { case FST_INITIATOR_LOCAL: initiator = FST_CS_PVAL_INITIATOR_LOCAL; break; case FST_INITIATOR_REMOTE: initiator = FST_CS_PVAL_INITIATOR_REMOTE; break; default: break; } break; default: break; } len = os_snprintf(buffer, size, FST_CES_PNAME_REASON "=%s " FST_CES_PNAME_REJECT_CODE "=%s " FST_CES_PNAME_INITIATOR "=%s", fst_reason_name(ss->extra.to_initial.reason), reject_str, initiator); return !os_snprintf_error(size, len); } static void fst_ctrl_iface_notify(struct fst_iface *f, u32 session_id, enum fst_event_type event_type, const union fst_event_extra *extra) { struct fst_group *g; char extra_str[128] = ""; const struct fst_event_extra_session_state *ss; const struct fst_event_extra_iface_state *is; const struct fst_event_extra_peer_state *ps; /* * FST can use any of interface objects as it only sends messages * on global Control Interface, so we just pick the 1st one. */ if (!f) { foreach_fst_group(g) { f = fst_group_first_iface(g); if (f) break; } if (!f) return; } WPA_ASSERT(f->iface_obj.ctx); switch (event_type) { case EVENT_FST_IFACE_STATE_CHANGED: if (!extra) return; is = &extra->iface_state; wpa_msg_global_only(f->iface_obj.ctx, MSG_INFO, FST_CTRL_EVENT_IFACE " %s " FST_CEI_PNAME_IFNAME "=%s " FST_CEI_PNAME_GROUP "=%s", is->attached ? FST_CEI_PNAME_ATTACHED : FST_CEI_PNAME_DETACHED, is->ifname, is->group_id); break; case EVENT_PEER_STATE_CHANGED: if (!extra) return; ps = &extra->peer_state; wpa_msg_global_only(fst_iface_get_wpa_obj_ctx(f), MSG_INFO, FST_CTRL_EVENT_PEER " %s " FST_CEP_PNAME_IFNAME "=%s " FST_CEP_PNAME_ADDR "=" MACSTR, ps->connected ? FST_CEP_PNAME_CONNECTED : FST_CEP_PNAME_DISCONNECTED, ps->ifname, MAC2STR(ps->addr)); break; case EVENT_FST_SESSION_STATE_CHANGED: if (!extra) return; if (!format_session_state_extra(extra, extra_str, sizeof(extra_str))) { fst_printf(MSG_ERROR, "CTRL: Cannot format STATE_CHANGE extra"); extra_str[0] = 0; } ss = &extra->session_state; wpa_msg_global_only(fst_iface_get_wpa_obj_ctx(f), MSG_INFO, FST_CTRL_EVENT_SESSION " " FST_CES_PNAME_SESSION_ID "=%u " FST_CES_PNAME_EVT_TYPE "=%s " FST_CES_PNAME_OLD_STATE "=%s " FST_CES_PNAME_NEW_STATE "=%s %s", session_id, fst_session_event_type_name(event_type), fst_session_state_name(ss->old_state), fst_session_state_name(ss->new_state), extra_str); break; case EVENT_FST_ESTABLISHED: case EVENT_FST_SETUP: wpa_msg_global_only(fst_iface_get_wpa_obj_ctx(f), MSG_INFO, FST_CTRL_EVENT_SESSION " " FST_CES_PNAME_SESSION_ID "=%u " FST_CES_PNAME_EVT_TYPE "=%s", session_id, fst_session_event_type_name(event_type)); break; } } /* command processors */ /* fst session_get */ static int session_get(const char *session_id, char *buf, size_t buflen) { struct fst_session *s; struct fst_iface *new_iface, *old_iface; const u8 *old_peer_addr, *new_peer_addr; u32 id; id = strtoul(session_id, NULL, 0); s = fst_session_get_by_id(id); if (!s) { fst_printf(MSG_WARNING, "CTRL: Cannot find session %u", id); return os_snprintf(buf, buflen, "FAIL\n"); } old_peer_addr = fst_session_get_peer_addr(s, true); new_peer_addr = fst_session_get_peer_addr(s, false); new_iface = fst_session_get_iface(s, false); old_iface = fst_session_get_iface(s, true); return os_snprintf(buf, buflen, FST_CSG_PNAME_OLD_PEER_ADDR "=" MACSTR "\n" FST_CSG_PNAME_NEW_PEER_ADDR "=" MACSTR "\n" FST_CSG_PNAME_NEW_IFNAME "=%s\n" FST_CSG_PNAME_OLD_IFNAME "=%s\n" FST_CSG_PNAME_LLT "=%u\n" FST_CSG_PNAME_STATE "=%s\n", MAC2STR(old_peer_addr), MAC2STR(new_peer_addr), new_iface ? fst_iface_get_name(new_iface) : FST_CTRL_PVAL_NONE, old_iface ? fst_iface_get_name(old_iface) : FST_CTRL_PVAL_NONE, fst_session_get_llt(s), fst_session_state_name(fst_session_get_state(s))); } /* fst session_set */ static int session_set(const char *session_id, char *buf, size_t buflen) { struct fst_session *s; char *p, *q; u32 id; int ret; id = strtoul(session_id, &p, 0); s = fst_session_get_by_id(id); if (!s) { fst_printf(MSG_WARNING, "CTRL: Cannot find session %u", id); return os_snprintf(buf, buflen, "FAIL\n"); } if (*p != ' ' || !(q = os_strchr(p + 1, '='))) return os_snprintf(buf, buflen, "FAIL\n"); p++; if (os_strncasecmp(p, FST_CSS_PNAME_OLD_IFNAME, q - p) == 0) { ret = fst_session_set_str_ifname(s, q + 1, true); } else if (os_strncasecmp(p, FST_CSS_PNAME_NEW_IFNAME, q - p) == 0) { ret = fst_session_set_str_ifname(s, q + 1, false); } else if (os_strncasecmp(p, FST_CSS_PNAME_OLD_PEER_ADDR, q - p) == 0) { ret = fst_session_set_str_peer_addr(s, q + 1, true); } else if (os_strncasecmp(p, FST_CSS_PNAME_NEW_PEER_ADDR, q - p) == 0) { ret = fst_session_set_str_peer_addr(s, q + 1, false); } else if (os_strncasecmp(p, FST_CSS_PNAME_LLT, q - p) == 0) { ret = fst_session_set_str_llt(s, q + 1); } else { fst_printf(MSG_ERROR, "CTRL: Unknown parameter: %s", p); return os_snprintf(buf, buflen, "FAIL\n"); } return os_snprintf(buf, buflen, "%s\n", ret ? "FAIL" : "OK"); } /* fst session_add/remove */ static int session_add(const char *group_id, char *buf, size_t buflen) { struct fst_group *g; struct fst_session *s; g = get_fst_group_by_id(group_id); if (!g) { fst_printf(MSG_WARNING, "CTRL: Cannot find group '%s'", group_id); return os_snprintf(buf, buflen, "FAIL\n"); } s = fst_session_create(g); if (!s) { fst_printf(MSG_ERROR, "CTRL: Cannot create session for group '%s'", group_id); return os_snprintf(buf, buflen, "FAIL\n"); } return os_snprintf(buf, buflen, "%u\n", fst_session_get_id(s)); } static int session_remove(const char *session_id, char *buf, size_t buflen) { struct fst_session *s; struct fst_group *g; u32 id; id = strtoul(session_id, NULL, 0); s = fst_session_get_by_id(id); if (!s) { fst_printf(MSG_WARNING, "CTRL: Cannot find session %u", id); return os_snprintf(buf, buflen, "FAIL\n"); } g = fst_session_get_group(s); fst_session_reset(s); fst_session_delete(s); fst_group_delete_if_empty(g); return os_snprintf(buf, buflen, "OK\n"); } /* fst session_initiate */ static int session_initiate(const char *session_id, char *buf, size_t buflen) { struct fst_session *s; u32 id; id = strtoul(session_id, NULL, 0); s = fst_session_get_by_id(id); if (!s) { fst_printf(MSG_WARNING, "CTRL: Cannot find session %u", id); return os_snprintf(buf, buflen, "FAIL\n"); } if (fst_session_initiate_setup(s)) { fst_printf(MSG_WARNING, "CTRL: Cannot initiate session %u", id); return os_snprintf(buf, buflen, "FAIL\n"); } return os_snprintf(buf, buflen, "OK\n"); } /* fst session_respond */ static int session_respond(const char *session_id, char *buf, size_t buflen) { struct fst_session *s; char *p; u32 id; u8 status_code; id = strtoul(session_id, &p, 0); s = fst_session_get_by_id(id); if (!s) { fst_printf(MSG_WARNING, "CTRL: Cannot find session %u", id); return os_snprintf(buf, buflen, "FAIL\n"); } if (*p != ' ') return os_snprintf(buf, buflen, "FAIL\n"); p++; if (!os_strcasecmp(p, FST_CS_PVAL_RESPONSE_ACCEPT)) { status_code = WLAN_STATUS_SUCCESS; } else if (!os_strcasecmp(p, FST_CS_PVAL_RESPONSE_REJECT)) { status_code = WLAN_STATUS_PENDING_ADMITTING_FST_SESSION; } else { fst_printf(MSG_WARNING, "CTRL: session %u: unknown response status: %s", id, p); return os_snprintf(buf, buflen, "FAIL\n"); } if (fst_session_respond(s, status_code)) { fst_printf(MSG_WARNING, "CTRL: Cannot respond to session %u", id); return os_snprintf(buf, buflen, "FAIL\n"); } fst_printf(MSG_INFO, "CTRL: session %u responded", id); return os_snprintf(buf, buflen, "OK\n"); } /* fst session_transfer */ static int session_transfer(const char *session_id, char *buf, size_t buflen) { struct fst_session *s; u32 id; id = strtoul(session_id, NULL, 0); s = fst_session_get_by_id(id); if (!s) { fst_printf(MSG_WARNING, "CTRL: Cannot find session %u", id); return os_snprintf(buf, buflen, "FAIL\n"); } if (fst_session_initiate_switch(s)) { fst_printf(MSG_WARNING, "CTRL: Cannot initiate ST for session %u", id); return os_snprintf(buf, buflen, "FAIL\n"); } return os_snprintf(buf, buflen, "OK\n"); } /* fst session_teardown */ static int session_teardown(const char *session_id, char *buf, size_t buflen) { struct fst_session *s; u32 id; id = strtoul(session_id, NULL, 0); s = fst_session_get_by_id(id); if (!s) { fst_printf(MSG_WARNING, "CTRL: Cannot find session %u", id); return os_snprintf(buf, buflen, "FAIL\n"); } if (fst_session_tear_down_setup(s)) { fst_printf(MSG_WARNING, "CTRL: Cannot tear down session %u", id); return os_snprintf(buf, buflen, "FAIL\n"); } return os_snprintf(buf, buflen, "OK\n"); } #ifdef CONFIG_FST_TEST /* fst test_request */ static int test_request(const char *request, char *buf, size_t buflen) { const char *p = request; int ret; if (!os_strncasecmp(p, FST_CTR_SEND_SETUP_REQUEST, os_strlen(FST_CTR_SEND_SETUP_REQUEST))) { ret = fst_test_req_send_fst_request( p + os_strlen(FST_CTR_SEND_SETUP_REQUEST)); } else if (!os_strncasecmp(p, FST_CTR_SEND_SETUP_RESPONSE, os_strlen(FST_CTR_SEND_SETUP_RESPONSE))) { ret = fst_test_req_send_fst_response( p + os_strlen(FST_CTR_SEND_SETUP_RESPONSE)); } else if (!os_strncasecmp(p, FST_CTR_SEND_ACK_REQUEST, os_strlen(FST_CTR_SEND_ACK_REQUEST))) { ret = fst_test_req_send_ack_request( p + os_strlen(FST_CTR_SEND_ACK_REQUEST)); } else if (!os_strncasecmp(p, FST_CTR_SEND_ACK_RESPONSE, os_strlen(FST_CTR_SEND_ACK_RESPONSE))) { ret = fst_test_req_send_ack_response( p + os_strlen(FST_CTR_SEND_ACK_RESPONSE)); } else if (!os_strncasecmp(p, FST_CTR_SEND_TEAR_DOWN, os_strlen(FST_CTR_SEND_TEAR_DOWN))) { ret = fst_test_req_send_tear_down( p + os_strlen(FST_CTR_SEND_TEAR_DOWN)); } else if (!os_strncasecmp(p, FST_CTR_GET_FSTS_ID, os_strlen(FST_CTR_GET_FSTS_ID))) { u32 fsts_id = fst_test_req_get_fsts_id( p + os_strlen(FST_CTR_GET_FSTS_ID)); if (fsts_id != FST_FSTS_ID_NOT_FOUND) return os_snprintf(buf, buflen, "%u\n", fsts_id); return os_snprintf(buf, buflen, "FAIL\n"); } else if (!os_strncasecmp(p, FST_CTR_GET_LOCAL_MBIES, os_strlen(FST_CTR_GET_LOCAL_MBIES))) { return fst_test_req_get_local_mbies( p + os_strlen(FST_CTR_GET_LOCAL_MBIES), buf, buflen); } else if (!os_strncasecmp(p, FST_CTR_IS_SUPPORTED, os_strlen(FST_CTR_IS_SUPPORTED))) { ret = 0; } else { fst_printf(MSG_ERROR, "CTRL: Unknown parameter: %s", p); return os_snprintf(buf, buflen, "FAIL\n"); } return os_snprintf(buf, buflen, "%s\n", ret ? "FAIL" : "OK"); } #endif /* CONFIG_FST_TEST */ /* fst list_sessions */ struct list_sessions_cb_ctx { char *buf; size_t buflen; size_t reply_len; }; static void list_session_enum_cb(struct fst_group *g, struct fst_session *s, void *ctx) { struct list_sessions_cb_ctx *c = ctx; int ret; ret = os_snprintf(c->buf, c->buflen, " %u", fst_session_get_id(s)); c->buf += ret; c->buflen -= ret; c->reply_len += ret; } static int list_sessions(const char *group_id, char *buf, size_t buflen) { struct list_sessions_cb_ctx ctx; struct fst_group *g; g = get_fst_group_by_id(group_id); if (!g) { fst_printf(MSG_WARNING, "CTRL: Cannot find group '%s'", group_id); return os_snprintf(buf, buflen, "FAIL\n"); } ctx.buf = buf; ctx.buflen = buflen; ctx.reply_len = 0; fst_session_enum(g, list_session_enum_cb, &ctx); ctx.reply_len += os_snprintf(buf + ctx.reply_len, ctx.buflen, "\n"); return ctx.reply_len; } /* fst iface_peers */ static int iface_peers(const char *group_id, char *buf, size_t buflen) { const char *ifname; struct fst_group *g; struct fst_iface *f; struct fst_get_peer_ctx *ctx; const u8 *addr; unsigned found = 0; int ret = 0; g = get_fst_group_by_id(group_id); if (!g) { fst_printf(MSG_WARNING, "CTRL: Cannot find group '%s'", group_id); return os_snprintf(buf, buflen, "FAIL\n"); } ifname = os_strchr(group_id, ' '); if (!ifname) return os_snprintf(buf, buflen, "FAIL\n"); ifname++; foreach_fst_group_iface(g, f) { const char *in = fst_iface_get_name(f); if (os_strncmp(ifname, in, os_strlen(in)) == 0) { found = 1; break; } } if (!found) return os_snprintf(buf, buflen, "FAIL\n"); addr = fst_iface_get_peer_first(f, &ctx, false); for (; addr != NULL; addr = fst_iface_get_peer_next(f, &ctx, false)) { int res; res = os_snprintf(buf + ret, buflen - ret, MACSTR "\n", MAC2STR(addr)); if (os_snprintf_error(buflen - ret, res)) break; ret += res; } return ret; } static int get_peer_mbies(const char *params, char *buf, size_t buflen) { char *endp; char ifname[FST_MAX_INTERFACE_SIZE]; u8 peer_addr[ETH_ALEN]; struct fst_group *g; struct fst_iface *iface = NULL; const struct wpabuf *mbies; if (fst_read_next_text_param(params, ifname, sizeof(ifname), &endp) || !*ifname) goto problem; while (isspace(*endp)) endp++; if (fst_read_peer_addr(endp, peer_addr)) goto problem; foreach_fst_group(g) { iface = fst_group_get_iface_by_name(g, ifname); if (iface) break; } if (!iface) goto problem; mbies = fst_iface_get_peer_mb_ie(iface, peer_addr); if (!mbies) goto problem; return wpa_snprintf_hex(buf, buflen, wpabuf_head(mbies), wpabuf_len(mbies)); problem: return os_snprintf(buf, buflen, "FAIL\n"); } /* fst list_ifaces */ static int list_ifaces(const char *group_id, char *buf, size_t buflen) { struct fst_group *g; struct fst_iface *f; int ret = 0; g = get_fst_group_by_id(group_id); if (!g) { fst_printf(MSG_WARNING, "CTRL: Cannot find group '%s'", group_id); return os_snprintf(buf, buflen, "FAIL\n"); } foreach_fst_group_iface(g, f) { int res; const u8 *iface_addr = fst_iface_get_addr(f); res = os_snprintf(buf + ret, buflen - ret, "%s|" MACSTR "|%u|%u\n", fst_iface_get_name(f), MAC2STR(iface_addr), fst_iface_get_priority(f), fst_iface_get_llt(f)); if (os_snprintf_error(buflen - ret, res)) break; ret += res; } return ret; } /* fst list_groups */ static int list_groups(const char *cmd, char *buf, size_t buflen) { struct fst_group *g; int ret = 0; foreach_fst_group(g) { int res; res = os_snprintf(buf + ret, buflen - ret, "%s\n", fst_group_get_id(g)); if (os_snprintf_error(buflen - ret, res)) break; ret += res; } return ret; } static const char * band_freq(enum mb_band_id band) { static const char *band_names[] = { [MB_BAND_ID_WIFI_2_4GHZ] = "2.4GHZ", [MB_BAND_ID_WIFI_5GHZ] = "5GHZ", [MB_BAND_ID_WIFI_60GHZ] = "60GHZ", }; return fst_get_str_name(band, band_names, ARRAY_SIZE(band_names)); } static int print_band(unsigned num, struct fst_iface *iface, const u8 *addr, char *buf, size_t buflen) { const struct wpabuf *wpabuf; enum hostapd_hw_mode hw_mode; u8 channel; int ret = 0; fst_iface_get_channel_info(iface, &hw_mode, &channel); ret += os_snprintf(buf + ret, buflen - ret, "band%u_frequency=%s\n", num, band_freq(fst_hw_mode_to_band(hw_mode))); ret += os_snprintf(buf + ret, buflen - ret, "band%u_iface=%s\n", num, fst_iface_get_name(iface)); wpabuf = fst_iface_get_peer_mb_ie(iface, addr); if (wpabuf) { ret += os_snprintf(buf + ret, buflen - ret, "band%u_mb_ies=", num); ret += wpa_snprintf_hex(buf + ret, buflen - ret, wpabuf_head(wpabuf), wpabuf_len(wpabuf)); ret += os_snprintf(buf + ret, buflen - ret, "\n"); } ret += os_snprintf(buf + ret, buflen - ret, "band%u_fst_group_id=%s\n", num, fst_iface_get_group_id(iface)); ret += os_snprintf(buf + ret, buflen - ret, "band%u_fst_priority=%u\n", num, fst_iface_get_priority(iface)); ret += os_snprintf(buf + ret, buflen - ret, "band%u_fst_llt=%u\n", num, fst_iface_get_llt(iface)); return ret; } static void fst_ctrl_iface_on_iface_state_changed(struct fst_iface *i, bool attached) { union fst_event_extra extra; os_memset(&extra, 0, sizeof(extra)); extra.iface_state.attached = attached; os_strlcpy(extra.iface_state.ifname, fst_iface_get_name(i), sizeof(extra.iface_state.ifname)); os_strlcpy(extra.iface_state.group_id, fst_iface_get_group_id(i), sizeof(extra.iface_state.group_id)); fst_ctrl_iface_notify(i, FST_INVALID_SESSION_ID, EVENT_FST_IFACE_STATE_CHANGED, &extra); } static int fst_ctrl_iface_on_iface_added(struct fst_iface *i) { fst_ctrl_iface_on_iface_state_changed(i, true); return 0; } static void fst_ctrl_iface_on_iface_removed(struct fst_iface *i) { fst_ctrl_iface_on_iface_state_changed(i, false); } static void fst_ctrl_iface_on_event(enum fst_event_type event_type, struct fst_iface *i, struct fst_session *s, const union fst_event_extra *extra) { u32 session_id = s ? fst_session_get_id(s) : FST_INVALID_SESSION_ID; fst_ctrl_iface_notify(i, session_id, event_type, extra); } static const struct fst_ctrl ctrl_cli = { .on_iface_added = fst_ctrl_iface_on_iface_added, .on_iface_removed = fst_ctrl_iface_on_iface_removed, .on_event = fst_ctrl_iface_on_event, }; const struct fst_ctrl *fst_ctrl_cli = &ctrl_cli; int fst_ctrl_iface_mb_info(const u8 *addr, char *buf, size_t buflen) { struct fst_group *g; struct fst_iface *f; unsigned num = 0; int ret = 0; foreach_fst_group(g) { foreach_fst_group_iface(g, f) { if (fst_iface_is_connected(f, addr, true)) { ret += print_band(num++, f, addr, buf + ret, buflen - ret); } } } return ret; } /* fst ctrl processor */ int fst_ctrl_iface_receive(const char *cmd, char *reply, size_t reply_size) { static const struct fst_command { const char *name; unsigned has_param; int (*process)(const char *group_id, char *buf, size_t buflen); } commands[] = { { FST_CMD_LIST_GROUPS, 0, list_groups}, { FST_CMD_LIST_IFACES, 1, list_ifaces}, { FST_CMD_IFACE_PEERS, 1, iface_peers}, { FST_CMD_GET_PEER_MBIES, 1, get_peer_mbies}, { FST_CMD_LIST_SESSIONS, 1, list_sessions}, { FST_CMD_SESSION_ADD, 1, session_add}, { FST_CMD_SESSION_REMOVE, 1, session_remove}, { FST_CMD_SESSION_GET, 1, session_get}, { FST_CMD_SESSION_SET, 1, session_set}, { FST_CMD_SESSION_INITIATE, 1, session_initiate}, { FST_CMD_SESSION_RESPOND, 1, session_respond}, { FST_CMD_SESSION_TRANSFER, 1, session_transfer}, { FST_CMD_SESSION_TEARDOWN, 1, session_teardown}, #ifdef CONFIG_FST_TEST { FST_CMD_TEST_REQUEST, 1, test_request }, #endif /* CONFIG_FST_TEST */ { NULL, 0, NULL } }; const struct fst_command *c; const char *p; const char *temp; bool non_spaces_found; for (c = commands; c->name; c++) { if (os_strncasecmp(cmd, c->name, os_strlen(c->name)) != 0) continue; p = cmd + os_strlen(c->name); if (c->has_param) { if (!isspace(p[0])) return os_snprintf(reply, reply_size, "FAIL\n"); p++; temp = p; non_spaces_found = false; while (*temp) { if (!isspace(*temp)) { non_spaces_found = true; break; } temp++; } if (!non_spaces_found) return os_snprintf(reply, reply_size, "FAIL\n"); } return c->process(p, reply, reply_size); } return os_snprintf(reply, reply_size, "UNKNOWN FST COMMAND\n"); } int fst_read_next_int_param(const char *params, bool *valid, char **endp) { int ret = -1; const char *curp; *valid = false; *endp = (char *) params; curp = params; if (*curp) { ret = (int) strtol(curp, endp, 0); if (!**endp || isspace(**endp)) *valid = true; } return ret; } int fst_read_next_text_param(const char *params, char *buf, size_t buflen, char **endp) { size_t max_chars_to_copy; char *cur_dest; *endp = (char *) params; while (isspace(**endp)) (*endp)++; if (!**endp || buflen <= 1) return -EINVAL; max_chars_to_copy = buflen - 1; /* We need 1 byte for the terminating zero */ cur_dest = buf; while (**endp && !isspace(**endp) && max_chars_to_copy > 0) { *cur_dest = **endp; (*endp)++; cur_dest++; max_chars_to_copy--; } *cur_dest = 0; return 0; } int fst_read_peer_addr(const char *mac, u8 *peer_addr) { if (hwaddr_aton(mac, peer_addr)) { fst_printf(MSG_WARNING, "Bad peer_mac %s: invalid addr string", mac); return -1; } if (is_zero_ether_addr(peer_addr) || is_multicast_ether_addr(peer_addr)) { fst_printf(MSG_WARNING, "Bad peer_mac %s: not a unicast addr", mac); return -1; } return 0; } int fst_parse_attach_command(const char *cmd, char *ifname, size_t ifname_size, struct fst_iface_cfg *cfg) { char *pos; char *endp; bool is_valid; int val; if (fst_read_next_text_param(cmd, ifname, ifname_size, &endp) || fst_read_next_text_param(endp, cfg->group_id, sizeof(cfg->group_id), &endp)) return -EINVAL; cfg->llt = FST_DEFAULT_LLT_CFG_VALUE; cfg->priority = 0; pos = os_strstr(endp, FST_ATTACH_CMD_PNAME_LLT); if (pos) { pos += os_strlen(FST_ATTACH_CMD_PNAME_LLT); if (*pos == '=') { val = fst_read_next_int_param(pos + 1, &is_valid, &endp); if (is_valid) cfg->llt = val; } } pos = os_strstr(endp, FST_ATTACH_CMD_PNAME_PRIORITY); if (pos) { pos += os_strlen(FST_ATTACH_CMD_PNAME_PRIORITY); if (*pos == '=') { val = fst_read_next_int_param(pos + 1, &is_valid, &endp); if (is_valid) cfg->priority = (u8) val; } } return 0; } int fst_parse_detach_command(const char *cmd, char *ifname, size_t ifname_size) { char *endp; return fst_read_next_text_param(cmd, ifname, ifname_size, &endp); } int fst_iface_detach(const char *ifname) { struct fst_group *g; foreach_fst_group(g) { struct fst_iface *f; f = fst_group_get_iface_by_name(g, ifname); if (f) { fst_detach(f); return 0; } } return -EINVAL; }
644572.c
// SPDX-License-Identifier: GPL-2.0+ /* NetworkManager Applet -- allow user control over networking * * Dan Williams <[email protected]> * * Copyright 2007 - 2014 Red Hat, Inc. */ #include "nm-default.h" #include <ctype.h> #include <string.h> #include "wireless-security.h" #include "eap-method.h" struct _WirelessSecurityDynamicWEP { WirelessSecurity parent; GtkSizeGroup *size_group; }; static void destroy (WirelessSecurity *parent) { WirelessSecurityDynamicWEP *sec = (WirelessSecurityDynamicWEP *) parent; if (sec->size_group) g_object_unref (sec->size_group); } static gboolean validate (WirelessSecurity *parent, GError **error) { return ws_802_1x_validate (parent, "dynamic_wep_auth_combo", error); } static void add_to_size_group (WirelessSecurity *parent, GtkSizeGroup *group) { WirelessSecurityDynamicWEP *sec = (WirelessSecurityDynamicWEP *) parent; if (sec->size_group) g_object_unref (sec->size_group); sec->size_group = g_object_ref (group); ws_802_1x_add_to_size_group (parent, sec->size_group, "dynamic_wep_auth_label", "dynamic_wep_auth_combo"); } static void fill_connection (WirelessSecurity *parent, NMConnection *connection) { NMSettingWirelessSecurity *s_wireless_sec; ws_802_1x_fill_connection (parent, "dynamic_wep_auth_combo", connection); s_wireless_sec = nm_connection_get_setting_wireless_security (connection); g_assert (s_wireless_sec); g_object_set (s_wireless_sec, NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, "ieee8021x", NULL); } static void auth_combo_changed_cb (GtkWidget *combo, gpointer user_data) { WirelessSecurity *parent = WIRELESS_SECURITY (user_data); WirelessSecurityDynamicWEP *sec = (WirelessSecurityDynamicWEP *) parent; ws_802_1x_auth_combo_changed (combo, parent, "dynamic_wep_method_vbox", sec->size_group); } static void update_secrets (WirelessSecurity *parent, NMConnection *connection) { ws_802_1x_update_secrets (parent, "dynamic_wep_auth_combo", connection); } WirelessSecurityDynamicWEP * ws_dynamic_wep_new (NMConnection *connection, gboolean is_editor, gboolean secrets_only) { WirelessSecurity *parent; GtkWidget *widget; parent = wireless_security_init (sizeof (WirelessSecurityDynamicWEP), validate, add_to_size_group, fill_connection, update_secrets, destroy, "/org/freedesktop/network-manager-applet/ws-dynamic-wep.ui", "dynamic_wep_notebook", NULL); if (!parent) return NULL; parent->adhoc_compatible = FALSE; parent->hotspot_compatible = FALSE; widget = ws_802_1x_auth_combo_init (parent, "dynamic_wep_auth_combo", "dynamic_wep_auth_label", (GCallback) auth_combo_changed_cb, connection, is_editor, secrets_only, NULL); auth_combo_changed_cb (widget, (gpointer) parent); return (WirelessSecurityDynamicWEP *) parent; }
970596.c
/* $Id: dshow_dev.c 5560 2017-02-24 04:21:07Z nanang $ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pjmedia-videodev/videodev_imp.h> #include <pj/assert.h> #include <pj/log.h> #include <pj/os.h> #include <pj/unicode.h> #if defined(PJMEDIA_HAS_VIDEO) && PJMEDIA_HAS_VIDEO != 0 && \ defined(PJMEDIA_VIDEO_DEV_HAS_DSHOW) && PJMEDIA_VIDEO_DEV_HAS_DSHOW != 0 #ifdef _MSC_VER # pragma warning(push, 3) #endif #include <windows.h> #define COBJMACROS #include <DShow.h> #include <wmsdkidl.h> #ifdef _MSC_VER # pragma warning(pop) #endif #pragma comment(lib, "Strmiids.lib") #pragma comment(lib, "Rpcrt4.lib") #pragma comment(lib, "Quartz.lib") #define THIS_FILE "dshow_dev.c" #define DEFAULT_CLOCK_RATE 90000 #define DEFAULT_WIDTH 640 #define DEFAULT_HEIGHT 480 #define DEFAULT_FPS 25 /* Temporarily disable DirectShow renderer (VMR) */ #define HAS_VMR 0 typedef void (*input_callback)(void *user_data, IMediaSample *pMediaSample); typedef struct NullRenderer NullRenderer; IBaseFilter* NullRenderer_Create(input_callback input_cb, void *user_data); typedef struct SourceFilter SourceFilter; IBaseFilter* SourceFilter_Create(SourceFilter **pSrc); HRESULT SourceFilter_Deliver(SourceFilter *src, void *buf, long size); void SourceFilter_SetMediaType(SourceFilter *src, AM_MEDIA_TYPE *pmt); typedef struct dshow_fmt_info { pjmedia_format_id pjmedia_format; const GUID *dshow_format; pj_bool_t enabled; } dshow_fmt_info; static dshow_fmt_info dshow_fmts[] = { {PJMEDIA_FORMAT_YUY2, &MEDIASUBTYPE_YUY2, PJ_FALSE} , {PJMEDIA_FORMAT_RGB24, &MEDIASUBTYPE_RGB24, PJ_FALSE} , {PJMEDIA_FORMAT_RGB32, &MEDIASUBTYPE_RGB32, PJ_FALSE} , {PJMEDIA_FORMAT_IYUV, &MEDIASUBTYPE_IYUV, PJ_FALSE} , {PJMEDIA_FORMAT_I420, &WMMEDIASUBTYPE_I420, PJ_FALSE} }; /* dshow_ device info */ struct dshow_dev_info { pjmedia_vid_dev_info info; unsigned dev_id; WCHAR display_name[192]; }; /* dshow_ factory */ struct dshow_factory { pjmedia_vid_dev_factory base; pj_pool_t *pool; pj_pool_t *dev_pool; pj_pool_factory *pf; unsigned dev_count; struct dshow_dev_info *dev_info; }; /* Video stream. */ struct dshow_stream { pjmedia_vid_dev_stream base; /**< Base stream */ pjmedia_vid_dev_param param; /**< Settings */ pj_pool_t *pool; /**< Memory pool. */ pjmedia_vid_dev_cb vid_cb; /**< Stream callback. */ void *user_data; /**< Application data. */ pj_bool_t quit_flag; pj_bool_t rend_thread_exited; pj_bool_t cap_thread_exited; pj_bool_t cap_thread_initialized; pj_thread_desc cap_thread_desc; pj_thread_t *cap_thread; void *frm_buf; unsigned frm_buf_size; struct dshow_graph { IFilterGraph *filter_graph; IMediaFilter *media_filter; SourceFilter *csource_filter; IBaseFilter *source_filter; IBaseFilter *rend_filter; AM_MEDIA_TYPE *mediatype; } dgraph; pj_timestamp cap_ts; unsigned cap_ts_inc; }; /* Prototypes */ static pj_status_t dshow_factory_init(pjmedia_vid_dev_factory *f); static pj_status_t dshow_factory_destroy(pjmedia_vid_dev_factory *f); static pj_status_t dshow_factory_refresh(pjmedia_vid_dev_factory *f); static unsigned dshow_factory_get_dev_count(pjmedia_vid_dev_factory *f); static pj_status_t dshow_factory_get_dev_info(pjmedia_vid_dev_factory *f, unsigned index, pjmedia_vid_dev_info *info); static pj_status_t dshow_factory_default_param(pj_pool_t *pool, pjmedia_vid_dev_factory *f, unsigned index, pjmedia_vid_dev_param *param); static pj_status_t dshow_factory_create_stream( pjmedia_vid_dev_factory *f, pjmedia_vid_dev_param *param, const pjmedia_vid_dev_cb *cb, void *user_data, pjmedia_vid_dev_stream **p_vid_strm); static pj_status_t dshow_stream_get_param(pjmedia_vid_dev_stream *strm, pjmedia_vid_dev_param *param); static pj_status_t dshow_stream_get_cap(pjmedia_vid_dev_stream *strm, pjmedia_vid_dev_cap cap, void *value); static pj_status_t dshow_stream_set_cap(pjmedia_vid_dev_stream *strm, pjmedia_vid_dev_cap cap, const void *value); static pj_status_t dshow_stream_start(pjmedia_vid_dev_stream *strm); static pj_status_t dshow_stream_put_frame(pjmedia_vid_dev_stream *strm, const pjmedia_frame *frame); static pj_status_t dshow_stream_stop(pjmedia_vid_dev_stream *strm); static pj_status_t dshow_stream_destroy(pjmedia_vid_dev_stream *strm); /* Operations */ static pjmedia_vid_dev_factory_op factory_op = { &dshow_factory_init, &dshow_factory_destroy, &dshow_factory_get_dev_count, &dshow_factory_get_dev_info, &dshow_factory_default_param, &dshow_factory_create_stream, &dshow_factory_refresh }; static pjmedia_vid_dev_stream_op stream_op = { &dshow_stream_get_param, &dshow_stream_get_cap, &dshow_stream_set_cap, &dshow_stream_start, NULL, &dshow_stream_put_frame, &dshow_stream_stop, &dshow_stream_destroy }; /**************************************************************************** * Factory operations */ /* * Init dshow_ video driver. */ pjmedia_vid_dev_factory* pjmedia_dshow_factory(pj_pool_factory *pf) { struct dshow_factory *f; pj_pool_t *pool; pool = pj_pool_create(pf, "dshow video", 1000, 1000, NULL); f = PJ_POOL_ZALLOC_T(pool, struct dshow_factory); f->pf = pf; f->pool = pool; f->base.op = &factory_op; return &f->base; } /* API: init factory */ static pj_status_t dshow_factory_init(pjmedia_vid_dev_factory *f) { HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); if (hr == RPC_E_CHANGED_MODE) { /* When using apartment mode, Dshow object would not be accessible from * other thread. Take this into consideration when implementing native * renderer using Dshow. */ hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); if (FAILED(hr)) { PJ_LOG(4,(THIS_FILE, "Failed initializing DShow: " "COM library already initialized with " "incompatible concurrency model")); return PJMEDIA_EVID_INIT; } } return dshow_factory_refresh(f); } /* API: destroy factory */ static pj_status_t dshow_factory_destroy(pjmedia_vid_dev_factory *f) { struct dshow_factory *df = (struct dshow_factory*)f; pj_pool_t *pool = df->pool; df->pool = NULL; if (df->dev_pool) pj_pool_release(df->dev_pool); if (pool) pj_pool_release(pool); CoUninitialize(); return PJ_SUCCESS; } static HRESULT get_cap_device(struct dshow_factory *df, unsigned id, IBaseFilter **filter) { IBindCtx *pbc; HRESULT hr; hr = CreateBindCtx(0, &pbc); if (SUCCEEDED (hr)) { IMoniker *moniker; DWORD pchEaten; hr = MkParseDisplayName(pbc, df->dev_info[id].display_name, &pchEaten, &moniker); if (SUCCEEDED(hr)) { hr = IMoniker_BindToObject(moniker, pbc, NULL, &IID_IBaseFilter, (LPVOID *)filter); IMoniker_Release(moniker); } IBindCtx_Release(pbc); } return hr; } static void enum_dev_cap(IBaseFilter *filter, pjmedia_dir dir, const GUID *dshow_fmt, AM_MEDIA_TYPE **pMediatype, int width, int height, IPin **pSrcpin, pjmedia_vid_dev_info *vdi) { IEnumPins *pEnum; AM_MEDIA_TYPE *mediatype = NULL; pj_bool_t match_wh = PJ_FALSE; HRESULT hr; if (pSrcpin) *pSrcpin = NULL; hr = IBaseFilter_EnumPins(filter, &pEnum); if (SUCCEEDED(hr)) { /* Loop through all the pins. */ IPin *pPin = NULL; while (IEnumPins_Next(pEnum, 1, &pPin, NULL) == S_OK) { PIN_DIRECTION pindirtmp; hr = IPin_QueryDirection(pPin, &pindirtmp); if (hr != S_OK || pindirtmp != PINDIR_OUTPUT) { if (SUCCEEDED(hr)) IPin_Release(pPin); continue; } if (dir == PJMEDIA_DIR_CAPTURE) { IAMStreamConfig *streamcaps; hr = IPin_QueryInterface(pPin, &IID_IAMStreamConfig, (LPVOID *)&streamcaps); if (SUCCEEDED(hr)) { VIDEO_STREAM_CONFIG_CAPS vscc; int i, isize, icount; IAMStreamConfig_GetNumberOfCapabilities(streamcaps, &icount, &isize); for (i = 0; i < icount; i++) { unsigned j, nformat; RPC_STATUS rpcstatus, rpcstatus2; hr = IAMStreamConfig_GetStreamCaps(streamcaps, i, &mediatype, (BYTE *)&vscc); if (FAILED (hr)) continue; nformat = (dshow_fmt? 1: sizeof(dshow_fmts)/sizeof(dshow_fmts[0])); for (j = 0; j < nformat; j++) { const GUID *dshow_format = dshow_fmt; if (!dshow_format) dshow_format = dshow_fmts[j].dshow_format; if (UuidCompare(&mediatype->subtype, (UUID*)dshow_format, &rpcstatus) == 0 && rpcstatus == RPC_S_OK && UuidCompare(&mediatype->formattype, (UUID*)&FORMAT_VideoInfo, &rpcstatus2) == 0 && rpcstatus2 == RPC_S_OK) { VIDEOINFOHEADER *vi; vi = (VIDEOINFOHEADER *)mediatype->pbFormat; if (!dshow_fmt) dshow_fmts[j].enabled = PJ_TRUE; if (vdi && vdi->fmt_cnt < PJMEDIA_VID_DEV_INFO_FMT_CNT) { unsigned fps_num=DEFAULT_FPS, fps_denum=1; if (vi->AvgTimePerFrame != 0) { fps_num = 10000000; fps_denum=(unsigned)vi->AvgTimePerFrame; } pjmedia_format_init_video( &vdi->fmt[vdi->fmt_cnt++], dshow_fmts[j].pjmedia_format, vi->bmiHeader.biWidth, vi->bmiHeader.biHeight, fps_num, fps_denum); } if (pSrcpin) { if ((width == 0 && height == 0 ) || (vi->bmiHeader.biWidth == width && vi->bmiHeader.biHeight == height)) { match_wh = PJ_TRUE; } *pSrcpin = pPin; *pMediatype = mediatype; } } } if (pSrcpin && *pSrcpin && match_wh) break; } IAMStreamConfig_Release(streamcaps); } } else { *pSrcpin = pPin; } if (pSrcpin && *pSrcpin) break; IPin_Release(pPin); } IEnumPins_Release(pEnum); } } /* API: refresh the list of devices */ static pj_status_t dshow_factory_refresh(pjmedia_vid_dev_factory *f) { struct dshow_factory *df = (struct dshow_factory*)f; struct dshow_dev_info *ddi; int dev_count = 0; unsigned c; ICreateDevEnum *dev_enum = NULL; IEnumMoniker *enum_cat = NULL; IMoniker *moniker = NULL; HRESULT hr; ULONG fetched; if (df->dev_pool) { pj_pool_release(df->dev_pool); df->dev_pool = NULL; } for (c = 0; c < sizeof(dshow_fmts) / sizeof(dshow_fmts[0]); c++) { dshow_fmts[c].enabled = PJ_FALSE; } df->dev_count = 0; df->dev_pool = pj_pool_create(df->pf, "dshow video", 500, 500, NULL); hr = CoCreateInstance(&CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, &IID_ICreateDevEnum, (void**)&dev_enum); if (FAILED(hr) || ICreateDevEnum_CreateClassEnumerator(dev_enum, &CLSID_VideoInputDeviceCategory, &enum_cat, 0) != S_OK) { PJ_LOG(4,(THIS_FILE, "Windows found no video input devices")); if (dev_enum) ICreateDevEnum_Release(dev_enum); dev_count = 0; } else { while (IEnumMoniker_Next(enum_cat, 1, &moniker, &fetched) == S_OK) { dev_count++; } } /* Add renderer device */ dev_count += 1; df->dev_info = (struct dshow_dev_info*) pj_pool_calloc(df->dev_pool, dev_count, sizeof(struct dshow_dev_info)); if (dev_count > 1) { IEnumMoniker_Reset(enum_cat); while (IEnumMoniker_Next(enum_cat, 1, &moniker, &fetched) == S_OK) { IPropertyBag *prop_bag; hr = IMoniker_BindToStorage(moniker, 0, 0, &IID_IPropertyBag, (void**)&prop_bag); if (SUCCEEDED(hr)) { VARIANT var_name; VariantInit(&var_name); hr = IPropertyBag_Read(prop_bag, L"FriendlyName", &var_name, NULL); if (SUCCEEDED(hr) && var_name.bstrVal) { WCHAR *wszDisplayName = NULL; IBaseFilter *filter; ddi = &df->dev_info[df->dev_count++]; pj_bzero(ddi, sizeof(*ddi)); pj_unicode_to_ansi(var_name.bstrVal, wcslen(var_name.bstrVal), ddi->info.name, sizeof(ddi->info.name)); hr = IMoniker_GetDisplayName(moniker, NULL, NULL, &wszDisplayName); if (hr == S_OK && wszDisplayName) { pj_memcpy(ddi->display_name, wszDisplayName, (wcslen(wszDisplayName)+1) * sizeof(WCHAR)); CoTaskMemFree(wszDisplayName); } strncpy(ddi->info.driver, "dshow", sizeof(ddi->info.driver)); ddi->info.driver[sizeof(ddi->info.driver)-1] = '\0'; ddi->info.dir = PJMEDIA_DIR_CAPTURE; ddi->info.has_callback = PJ_TRUE; /* Set the device capabilities here */ ddi->info.caps = PJMEDIA_VID_DEV_CAP_FORMAT; hr = get_cap_device(df, df->dev_count-1, &filter); if (SUCCEEDED(hr)) { ddi->info.fmt_cnt = 0; enum_dev_cap(filter, ddi->info.dir, NULL, NULL, 0, 0, NULL, &ddi->info); } } VariantClear(&var_name); IPropertyBag_Release(prop_bag); } IMoniker_Release(moniker); } IEnumMoniker_Release(enum_cat); ICreateDevEnum_Release(dev_enum); } #if HAS_VMR ddi = &df->dev_info[df->dev_count++]; pj_bzero(ddi, sizeof(*ddi)); pj_ansi_strncpy(ddi->info.name, "Video Mixing Renderer", sizeof(ddi->info.name)); ddi->info.name[sizeof(ddi->info.name)-1] = '\0'; pj_ansi_strncpy(ddi->info.driver, "dshow", sizeof(ddi->info.driver)); ddi->info.driver[sizeof(ddi->info.driver)-1] = '\0'; ddi->info.dir = PJMEDIA_DIR_RENDER; ddi->info.has_callback = PJ_FALSE; ddi->info.caps = PJMEDIA_VID_DEV_CAP_FORMAT; // TODO: // ddi->info.caps |= PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW; ddi->info.fmt_cnt = 1; pjmedia_format_init_video(&ddi->info.fmt[0], dshow_fmts[0].pjmedia_format, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_FPS, 1); #endif PJ_LOG(4, (THIS_FILE, "DShow has %d devices:", df->dev_count)); for (c = 0; c < df->dev_count; ++c) { PJ_LOG(4, (THIS_FILE, " dev_id %d: %s (%s)", c, df->dev_info[c].info.name, df->dev_info[c].info.dir & PJMEDIA_DIR_CAPTURE ? "capture" : "render")); } return PJ_SUCCESS; } /* API: get number of devices */ static unsigned dshow_factory_get_dev_count(pjmedia_vid_dev_factory *f) { struct dshow_factory *df = (struct dshow_factory*)f; return df->dev_count; } /* API: get device info */ static pj_status_t dshow_factory_get_dev_info(pjmedia_vid_dev_factory *f, unsigned index, pjmedia_vid_dev_info *info) { struct dshow_factory *df = (struct dshow_factory*)f; PJ_ASSERT_RETURN(index < df->dev_count, PJMEDIA_EVID_INVDEV); pj_memcpy(info, &df->dev_info[index].info, sizeof(*info)); return PJ_SUCCESS; } /* API: create default device parameter */ static pj_status_t dshow_factory_default_param(pj_pool_t *pool, pjmedia_vid_dev_factory *f, unsigned index, pjmedia_vid_dev_param *param) { struct dshow_factory *df = (struct dshow_factory*)f; struct dshow_dev_info *di = &df->dev_info[index]; PJ_ASSERT_RETURN(index < df->dev_count, PJMEDIA_EVID_INVDEV); PJ_UNUSED_ARG(pool); pj_bzero(param, sizeof(*param)); if (di->info.dir & PJMEDIA_DIR_CAPTURE) { param->dir = PJMEDIA_DIR_CAPTURE; param->cap_id = index; param->rend_id = PJMEDIA_VID_INVALID_DEV; } else if (di->info.dir & PJMEDIA_DIR_RENDER) { param->dir = PJMEDIA_DIR_RENDER; param->rend_id = index; param->cap_id = PJMEDIA_VID_INVALID_DEV; } else { return PJMEDIA_EVID_INVDEV; } /* Set the device capabilities here */ param->clock_rate = DEFAULT_CLOCK_RATE; param->flags = PJMEDIA_VID_DEV_CAP_FORMAT; pjmedia_format_copy(&param->fmt, &di->info.fmt[0]); return PJ_SUCCESS; } static void input_cb(void *user_data, IMediaSample *pMediaSample) { struct dshow_stream *strm = (struct dshow_stream*)user_data; pjmedia_frame frame = {0}; if (strm->quit_flag) { strm->cap_thread_exited = PJ_TRUE; return; } if (strm->cap_thread_initialized == 0 || !pj_thread_is_registered()) { pj_status_t status; status = pj_thread_register("ds_cap", strm->cap_thread_desc, &strm->cap_thread); if (status != PJ_SUCCESS) return; strm->cap_thread_initialized = 1; PJ_LOG(5,(THIS_FILE, "Capture thread started")); } frame.type = PJMEDIA_FRAME_TYPE_VIDEO; IMediaSample_GetPointer(pMediaSample, (BYTE **)&frame.buf); frame.size = IMediaSample_GetActualDataLength(pMediaSample); frame.bit_info = 0; frame.timestamp = strm->cap_ts; strm->cap_ts.u64 += strm->cap_ts_inc; if (strm->frm_buf_size) { unsigned i, stride; BYTE *src_buf, *dst_buf; pjmedia_video_format_detail *vfd; /* Image is bottom-up, convert it to top-down. */ src_buf = dst_buf = (BYTE *)frame.buf; stride = strm->frm_buf_size; vfd = pjmedia_format_get_video_format_detail(&strm->param.fmt, PJ_TRUE); src_buf += (vfd->size.h - 1) * stride; for (i = vfd->size.h / 2; i > 0; i--) { memcpy(strm->frm_buf, dst_buf, stride); memcpy(dst_buf, src_buf, stride); memcpy(src_buf, strm->frm_buf, stride); dst_buf += stride; src_buf -= stride; } } if (strm->vid_cb.capture_cb) (*strm->vid_cb.capture_cb)(&strm->base, strm->user_data, &frame); } /* API: Put frame from stream */ static pj_status_t dshow_stream_put_frame(pjmedia_vid_dev_stream *strm, const pjmedia_frame *frame) { struct dshow_stream *stream = (struct dshow_stream*)strm; HRESULT hr; if (stream->quit_flag) { stream->rend_thread_exited = PJ_TRUE; return PJ_SUCCESS; } hr = SourceFilter_Deliver(stream->dgraph.csource_filter, frame->buf, (long)frame->size); if (FAILED(hr)) return hr; return PJ_SUCCESS; } static dshow_fmt_info* get_dshow_format_info(pjmedia_format_id id) { unsigned i; for (i = 0; i < sizeof(dshow_fmts)/sizeof(dshow_fmts[0]); i++) { if (dshow_fmts[i].pjmedia_format == id && dshow_fmts[i].enabled) return &dshow_fmts[i]; } return NULL; } static pj_status_t create_filter_graph(pjmedia_dir dir, unsigned id, pj_bool_t use_def_size, pj_bool_t use_def_fps, struct dshow_factory *df, struct dshow_stream *strm, struct dshow_graph *graph) { HRESULT hr; IEnumPins *pEnum; IPin *srcpin = NULL; IPin *sinkpin = NULL; AM_MEDIA_TYPE *mediatype= NULL, mtype; VIDEOINFOHEADER *video_info, *vi = NULL; pjmedia_video_format_detail *vfd; const pjmedia_video_format_info *vfi; vfi = pjmedia_get_video_format_info(pjmedia_video_format_mgr_instance(), strm->param.fmt.id); if (!vfi) return PJMEDIA_EVID_BADFORMAT; hr = CoCreateInstance(&CLSID_FilterGraph, NULL, CLSCTX_INPROC, &IID_IFilterGraph, (LPVOID *)&graph->filter_graph); if (FAILED(hr)) { goto on_error; } hr = IFilterGraph_QueryInterface(graph->filter_graph, &IID_IMediaFilter, (LPVOID *)&graph->media_filter); if (FAILED(hr)) { goto on_error; } if (dir == PJMEDIA_DIR_CAPTURE) { hr = get_cap_device(df, id, &graph->source_filter); if (FAILED(hr)) { goto on_error; } } else { graph->source_filter = SourceFilter_Create(&graph->csource_filter); } hr = IFilterGraph_AddFilter(graph->filter_graph, graph->source_filter, L"capture"); if (FAILED(hr)) { goto on_error; } if (dir == PJMEDIA_DIR_CAPTURE) { graph->rend_filter = NullRenderer_Create(input_cb, strm); } else { hr = CoCreateInstance(&CLSID_VideoMixingRenderer, NULL, CLSCTX_INPROC, &IID_IBaseFilter, (LPVOID *)&graph->rend_filter); if (FAILED (hr)) { goto on_error; } } IBaseFilter_EnumPins(graph->rend_filter, &pEnum); if (SUCCEEDED(hr)) { // Loop through all the pins IPin *pPin = NULL; while (IEnumPins_Next(pEnum, 1, &pPin, NULL) == S_OK) { PIN_DIRECTION pindirtmp; hr = IPin_QueryDirection(pPin, &pindirtmp); if (hr == S_OK && pindirtmp == PINDIR_INPUT) { sinkpin = pPin; break; } IPin_Release(pPin); } IEnumPins_Release(pEnum); } vfd = pjmedia_format_get_video_format_detail(&strm->param.fmt, PJ_TRUE); enum_dev_cap(graph->source_filter, dir, get_dshow_format_info(strm->param.fmt.id)->dshow_format, &mediatype, (use_def_size? 0: vfd->size.w), (use_def_size? 0: vfd->size.h), &srcpin, NULL); graph->mediatype = mediatype; if (srcpin && dir == PJMEDIA_DIR_RENDER) { mediatype = graph->mediatype = &mtype; memset (mediatype, 0, sizeof(AM_MEDIA_TYPE)); mediatype->majortype = MEDIATYPE_Video; mediatype->subtype = *(get_dshow_format_info(strm->param.fmt.id)-> dshow_format); mediatype->bFixedSizeSamples = TRUE; mediatype->bTemporalCompression = FALSE; vi = (VIDEOINFOHEADER *) CoTaskMemAlloc(sizeof(VIDEOINFOHEADER)); memset (vi, 0, sizeof(VIDEOINFOHEADER)); mediatype->formattype = FORMAT_VideoInfo; mediatype->cbFormat = sizeof(VIDEOINFOHEADER); mediatype->pbFormat = (BYTE *)vi; vi->rcSource.bottom = vfd->size.h; vi->rcSource.right = vfd->size.w; vi->rcTarget.bottom = vfd->size.h; vi->rcTarget.right = vfd->size.w; vi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); vi->bmiHeader.biPlanes = 1; vi->bmiHeader.biBitCount = vfi->bpp; vi->bmiHeader.biCompression = strm->param.fmt.id; } if (!srcpin || !sinkpin || !mediatype) { hr = VFW_E_TYPE_NOT_ACCEPTED; goto on_error; } video_info = (VIDEOINFOHEADER *) mediatype->pbFormat; if (!use_def_size) { video_info->bmiHeader.biWidth = vfd->size.w; video_info->bmiHeader.biHeight = vfd->size.h; } if (video_info->AvgTimePerFrame == 0 || (!use_def_fps && vfd->fps.num != 0)) { video_info->AvgTimePerFrame = (LONGLONG) (10000000 * (double)vfd->fps.denum / vfd->fps.num); } video_info->bmiHeader.biSizeImage = DIBSIZE(video_info->bmiHeader); mediatype->lSampleSize = DIBSIZE(video_info->bmiHeader); if (graph->csource_filter) SourceFilter_SetMediaType(graph->csource_filter, mediatype); hr = IFilterGraph_AddFilter(graph->filter_graph, (IBaseFilter *)graph->rend_filter, L"renderer"); if (FAILED(hr)) goto on_error; hr = IFilterGraph_ConnectDirect(graph->filter_graph, srcpin, sinkpin, mediatype); if (SUCCEEDED(hr)) { if (use_def_size || use_def_fps) { pjmedia_format_init_video(&strm->param.fmt, strm->param.fmt.id, video_info->bmiHeader.biWidth, video_info->bmiHeader.biHeight, 10000000, (unsigned)video_info->AvgTimePerFrame); } strm->frm_buf_size = 0; if (dir == PJMEDIA_DIR_CAPTURE && video_info->bmiHeader.biCompression == BI_RGB && video_info->bmiHeader.biHeight > 0) { /* Allocate buffer to flip the captured image. */ strm->frm_buf_size = (video_info->bmiHeader.biBitCount >> 3) * video_info->bmiHeader.biWidth; strm->frm_buf = pj_pool_alloc(strm->pool, strm->frm_buf_size); } } on_error: if (srcpin) IPin_Release(srcpin); if (sinkpin) IPin_Release(sinkpin); if (vi) CoTaskMemFree(vi); if (FAILED(hr)) { char msg[80]; if (AMGetErrorText(hr, msg, sizeof(msg))) { PJ_LOG(4,(THIS_FILE, "Error creating filter graph: %s (hr=0x%x)", msg, hr)); } return PJ_EUNKNOWN; } return PJ_SUCCESS; } static void destroy_filter_graph(struct dshow_stream * stream) { if (stream->dgraph.source_filter) { IBaseFilter_Release(stream->dgraph.source_filter); stream->dgraph.source_filter = NULL; } if (stream->dgraph.rend_filter) { IBaseFilter_Release(stream->dgraph.rend_filter); stream->dgraph.rend_filter = NULL; } if (stream->dgraph.media_filter) { IMediaFilter_Release(stream->dgraph.media_filter); stream->dgraph.media_filter = NULL; } if (stream->dgraph.filter_graph) { IFilterGraph_Release(stream->dgraph.filter_graph); stream->dgraph.filter_graph = NULL; } } /* API: create stream */ static pj_status_t dshow_factory_create_stream( pjmedia_vid_dev_factory *f, pjmedia_vid_dev_param *param, const pjmedia_vid_dev_cb *cb, void *user_data, pjmedia_vid_dev_stream **p_vid_strm) { struct dshow_factory *df = (struct dshow_factory*)f; pj_pool_t *pool; struct dshow_stream *strm; pj_status_t status; PJ_ASSERT_RETURN(param->dir == PJMEDIA_DIR_CAPTURE || param->dir == PJMEDIA_DIR_RENDER, PJ_EINVAL); if (!get_dshow_format_info(param->fmt.id)) return PJMEDIA_EVID_BADFORMAT; /* Create and Initialize stream descriptor */ pool = pj_pool_create(df->pf, "dshow-dev", 1000, 1000, NULL); PJ_ASSERT_RETURN(pool != NULL, PJ_ENOMEM); strm = PJ_POOL_ZALLOC_T(pool, struct dshow_stream); pj_memcpy(&strm->param, param, sizeof(*param)); strm->pool = pool; pj_memcpy(&strm->vid_cb, cb, sizeof(*cb)); strm->user_data = user_data; if (param->dir & PJMEDIA_DIR_CAPTURE) { const pjmedia_video_format_detail *vfd; /* Create capture stream here */ status = create_filter_graph(PJMEDIA_DIR_CAPTURE, param->cap_id, PJ_FALSE, PJ_FALSE, df, strm, &strm->dgraph); if (status != PJ_SUCCESS) { destroy_filter_graph(strm); /* Try to use default fps */ PJ_LOG(4,(THIS_FILE, "Trying to open dshow dev with default fps")); status = create_filter_graph(PJMEDIA_DIR_CAPTURE, param->cap_id, PJ_FALSE, PJ_TRUE, df, strm, &strm->dgraph); if (status != PJ_SUCCESS) { /* Still failed, now try to use default fps and size */ destroy_filter_graph(strm); /* Try to use default fps */ PJ_LOG(4,(THIS_FILE, "Trying to open dshow dev with default " "size & fps")); status = create_filter_graph(PJMEDIA_DIR_CAPTURE, param->cap_id, PJ_TRUE, PJ_TRUE, df, strm, &strm->dgraph); } if (status != PJ_SUCCESS) goto on_error; pj_memcpy(param, &strm->param, sizeof(*param)); } vfd = pjmedia_format_get_video_format_detail(&param->fmt, PJ_TRUE); strm->cap_ts_inc = PJMEDIA_SPF2(param->clock_rate, &vfd->fps, 1); } else if (param->dir & PJMEDIA_DIR_RENDER) { /* Create render stream here */ status = create_filter_graph(PJMEDIA_DIR_RENDER, param->rend_id, PJ_FALSE, PJ_FALSE, df, strm, &strm->dgraph); if (status != PJ_SUCCESS) goto on_error; } /* Apply the remaining settings */ if (param->flags & PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW) { dshow_stream_set_cap(&strm->base, PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW, &param->window); } /* Done */ strm->base.op = &stream_op; *p_vid_strm = &strm->base; return PJ_SUCCESS; on_error: dshow_stream_destroy((pjmedia_vid_dev_stream *)strm); return status; } /* API: Get stream info. */ static pj_status_t dshow_stream_get_param(pjmedia_vid_dev_stream *s, pjmedia_vid_dev_param *pi) { struct dshow_stream *strm = (struct dshow_stream*)s; PJ_ASSERT_RETURN(strm && pi, PJ_EINVAL); pj_memcpy(pi, &strm->param, sizeof(*pi)); if (dshow_stream_get_cap(s, PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW, &pi->window) == PJ_SUCCESS) { pi->flags |= PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW; } return PJ_SUCCESS; } /* API: get capability */ static pj_status_t dshow_stream_get_cap(pjmedia_vid_dev_stream *s, pjmedia_vid_dev_cap cap, void *pval) { struct dshow_stream *strm = (struct dshow_stream*)s; PJ_UNUSED_ARG(strm); PJ_ASSERT_RETURN(s && pval, PJ_EINVAL); if (cap==PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW) { *(unsigned*)pval = 0; return PJ_SUCCESS; } else { return PJMEDIA_EVID_INVCAP; } } /* API: set capability */ static pj_status_t dshow_stream_set_cap(pjmedia_vid_dev_stream *s, pjmedia_vid_dev_cap cap, const void *pval) { struct dshow_stream *strm = (struct dshow_stream*)s; PJ_UNUSED_ARG(strm); PJ_ASSERT_RETURN(s && pval, PJ_EINVAL); if (cap==PJMEDIA_VID_DEV_CAP_OUTPUT_WINDOW) { // set renderer's window here return PJ_SUCCESS; } return PJMEDIA_EVID_INVCAP; } /* API: Start stream. */ static pj_status_t dshow_stream_start(pjmedia_vid_dev_stream *strm) { struct dshow_stream *stream = (struct dshow_stream*)strm; HRESULT hr; stream->quit_flag = PJ_FALSE; stream->cap_thread_exited = PJ_FALSE; stream->rend_thread_exited = PJ_FALSE; hr = IMediaFilter_Run(stream->dgraph.media_filter, 0); if (FAILED(hr)) { char msg[80]; if (AMGetErrorText(hr, msg, sizeof(msg))) { PJ_LOG(4,(THIS_FILE, "Error starting media: %s", msg)); } return PJ_EUNKNOWN; } PJ_LOG(4, (THIS_FILE, "Starting dshow video stream")); return PJ_SUCCESS; } /* API: Stop stream. */ static pj_status_t dshow_stream_stop(pjmedia_vid_dev_stream *strm) { struct dshow_stream *stream = (struct dshow_stream*)strm; unsigned i; stream->quit_flag = PJ_TRUE; if (stream->cap_thread) { for (i=0; !stream->cap_thread_exited && i<100; ++i) pj_thread_sleep(10); } if (stream->param.dir & PJMEDIA_DIR_RENDER) { for (i=0; !stream->rend_thread_exited && i<100; ++i) pj_thread_sleep(10); } if (stream->dgraph.media_filter) IMediaFilter_Stop(stream->dgraph.media_filter); PJ_LOG(4, (THIS_FILE, "Stopping dshow video stream")); return PJ_SUCCESS; } /* API: Destroy stream. */ static pj_status_t dshow_stream_destroy(pjmedia_vid_dev_stream *strm) { struct dshow_stream *stream = (struct dshow_stream*)strm; PJ_ASSERT_RETURN(stream != NULL, PJ_EINVAL); dshow_stream_stop(strm); destroy_filter_graph(stream); pj_pool_release(stream->pool); return PJ_SUCCESS; } #endif /* PJMEDIA_VIDEO_DEV_HAS_DSHOW */
5639.c
/* * File: DiskArb.c * * Contains: Disk Arbitration command processing. * * Written by: DTS * * Copyright: Copyright (c) 2008 Apple Inc. All Rights Reserved. * * Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. * ("Apple") in consideration of your agreement to the following * terms, and your use, installation, modification or * redistribution of this Apple software constitutes acceptance of * these terms. If you do not agree with these terms, please do * not use, install, modify or redistribute this Apple software. * * In consideration of your agreement to abide by the following * terms, and subject to these terms, Apple grants you a personal, * non-exclusive license, under Apple's copyrights in this * original Apple software (the "Apple Software"), to use, * reproduce, modify and redistribute the Apple Software, with or * without modifications, in source and/or binary forms; provided * that if you redistribute the Apple Software in its entirety and * without modifications, you must retain this notice and the * following text and disclaimers in all such redistributions of * the Apple Software. Neither the name, trademarks, service marks * or logos of Apple Inc. may be used to endorse or promote * products derived from the Apple Software without specific prior * written permission from Apple. Except as expressly stated in * this notice, no other rights or licenses, express or implied, * are granted by Apple herein, including but not limited to any * patent rights that may be infringed by your derivative works or * by other works in which the Apple Software may be incorporated. * * The Apple Software is provided by Apple on an "AS IS" basis. * APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING * THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN * COMBINATION WITH YOUR PRODUCTS. * * IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, * INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY * OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION * OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY * OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR * OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <DiskArbitration/DiskArbitration.h> #include "FieldPrinter.h" #include "Command.h" /***************************************************************/ #pragma mark * DADiskCopyDescription static CommandError PrintDADiskCopyDescription(CommandArgsRef args, uint32_t indent, uint32_t verbose) /* Prints results of DADiskCopyDescription. * * indent and verbose are as per the comments for FPPrinter. */ { int err; const char *bsdName; DASessionRef session; DADiskRef disk; CFDictionaryRef descDict; assert(CommandArgsValid(args)); session = NULL; disk = NULL; descDict = NULL; err = CommandArgsGetString(args, &bsdName); if (err == 0) { session = DASessionCreate(NULL); if (session == NULL) { err = EINVAL; } } if (err == 0) { disk = DADiskCreateFromBSDName(NULL, session, bsdName); if (disk == NULL) { err = EINVAL; } } if (err == 0) { descDict = DADiskCopyDescription(disk); if (descDict == NULL) { err = EINVAL; } } if (err == 0) { FPCFDictionary("description", sizeof(descDict), &descDict, indent, strlen("description"), verbose, NULL); } /* Clean up: */ if (descDict != NULL) { CFRelease(descDict); } if (disk != NULL) { CFRelease(disk); } if (session != NULL) { CFRelease(session); } return CommandErrorMakeWithErrno(err); } const CommandInfo kDADiskCopyDescriptionCommand = { PrintDADiskCopyDescription, "DADiskCopyDescription", "bsdDeviceName", "Print results of DADiskCopyDescription.", NULL }; /* EOF */
225718.c
#include <std.h> #include "/d/deku/inherits/forest.h" inherit FIRE_TUNI; void create() { ::create(); set_long(TO->query_long()+"%^RED%^ The tunnel dead ends "+ "here and your only option to trek back to the west.%^RESET%^"); set_exits(([ "west" : FTUN_ROOMS"firetunnels10", ] )); }
585851.c
/* * mini-x86.c: x86 backend for the Mono code generator * * Authors: * Paolo Molaro ([email protected]) * Dietmar Maurer ([email protected]) * Patrik Torstensson * * Copyright 2003 Ximian, Inc. * Copyright 2003-2011 Novell Inc. * Copyright 2011 Xamarin Inc. */ #include "mini.h" #include <string.h> #include <math.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <mono/metadata/abi-details.h> #include <mono/metadata/appdomain.h> #include <mono/metadata/debug-helpers.h> #include <mono/metadata/threads.h> #include <mono/metadata/profiler-private.h> #include <mono/metadata/mono-debug.h> #include <mono/metadata/gc-internal.h> #include <mono/utils/mono-math.h> #include <mono/utils/mono-counters.h> #include <mono/utils/mono-mmap.h> #include <mono/utils/mono-memory-model.h> #include <mono/utils/mono-hwcap-x86.h> #include <mono/utils/mono-threads.h> #include "trace.h" #include "mini-x86.h" #include "cpu-x86.h" #include "ir-emit.h" #include "mini-gc.h" #ifndef TARGET_WIN32 #ifdef MONO_XEN_OPT static gboolean optimize_for_xen = TRUE; #else #define optimize_for_xen 0 #endif #endif /* The single step trampoline */ static gpointer ss_trampoline; /* The breakpoint trampoline */ static gpointer bp_trampoline; /* This mutex protects architecture specific caches */ #define mono_mini_arch_lock() mono_mutex_lock (&mini_arch_mutex) #define mono_mini_arch_unlock() mono_mutex_unlock (&mini_arch_mutex) static mono_mutex_t mini_arch_mutex; #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1)) #define ARGS_OFFSET 8 #ifdef TARGET_WIN32 /* Under windows, the default pinvoke calling convention is stdcall */ #define CALLCONV_IS_STDCALL(sig) ((((sig)->call_convention) == MONO_CALL_STDCALL) || ((sig)->pinvoke && ((sig)->call_convention) == MONO_CALL_DEFAULT) || ((sig)->pinvoke && ((sig)->call_convention) == MONO_CALL_THISCALL)) #else #define CALLCONV_IS_STDCALL(sig) (((sig)->call_convention) == MONO_CALL_STDCALL || ((sig)->pinvoke && ((sig)->call_convention) == MONO_CALL_THISCALL)) #endif #define X86_IS_CALLEE_SAVED_REG(reg) (((reg) == X86_EBX) || ((reg) == X86_EDI) || ((reg) == X86_ESI)) #define OP_SEQ_POINT_BP_OFFSET 7 static guint8* emit_load_aotconst (guint8 *start, guint8 *code, MonoCompile *cfg, MonoJumpInfo **ji, int dreg, int tramp_type, gconstpointer target); #ifdef __native_client_codegen__ /* Default alignment for Native Client is 32-byte. */ gint8 nacl_align_byte = -32; /* signed version of 0xe0 */ /* mono_arch_nacl_pad: Add pad bytes of alignment instructions at code, */ /* Check that alignment doesn't cross an alignment boundary. */ guint8 * mono_arch_nacl_pad (guint8 *code, int pad) { const int kMaxPadding = 7; /* see x86-codegen.h: x86_padding() */ if (pad == 0) return code; /* assertion: alignment cannot cross a block boundary */ g_assert(((uintptr_t)code & (~kNaClAlignmentMask)) == (((uintptr_t)code + pad - 1) & (~kNaClAlignmentMask))); while (pad >= kMaxPadding) { x86_padding (code, kMaxPadding); pad -= kMaxPadding; } if (pad != 0) x86_padding (code, pad); return code; } guint8 * mono_arch_nacl_skip_nops (guint8 *code) { x86_skip_nops (code); return code; } #endif /* __native_client_codegen__ */ const char* mono_arch_regname (int reg) { switch (reg) { case X86_EAX: return "%eax"; case X86_EBX: return "%ebx"; case X86_ECX: return "%ecx"; case X86_EDX: return "%edx"; case X86_ESP: return "%esp"; case X86_EBP: return "%ebp"; case X86_EDI: return "%edi"; case X86_ESI: return "%esi"; } return "unknown"; } const char* mono_arch_fregname (int reg) { switch (reg) { case 0: return "%fr0"; case 1: return "%fr1"; case 2: return "%fr2"; case 3: return "%fr3"; case 4: return "%fr4"; case 5: return "%fr5"; case 6: return "%fr6"; case 7: return "%fr7"; default: return "unknown"; } } const char * mono_arch_xregname (int reg) { switch (reg) { case 0: return "%xmm0"; case 1: return "%xmm1"; case 2: return "%xmm2"; case 3: return "%xmm3"; case 4: return "%xmm4"; case 5: return "%xmm5"; case 6: return "%xmm6"; case 7: return "%xmm7"; default: return "unknown"; } } void mono_x86_patch (unsigned char* code, gpointer target) { x86_patch (code, (unsigned char*)target); } typedef enum { ArgInIReg, ArgInFloatSSEReg, ArgInDoubleSSEReg, ArgOnStack, ArgValuetypeInReg, ArgOnFloatFpStack, ArgOnDoubleFpStack, /* gsharedvt argument passed by addr */ ArgGSharedVt, ArgNone } ArgStorage; typedef struct { gint16 offset; gint8 reg; ArgStorage storage; int nslots; gboolean is_pair; /* Only if storage == ArgValuetypeInReg */ ArgStorage pair_storage [2]; gint8 pair_regs [2]; } ArgInfo; typedef struct { int nargs; guint32 stack_usage; guint32 reg_usage; guint32 freg_usage; gboolean need_stack_align; guint32 stack_align_amount; gboolean vtype_retaddr; /* The index of the vret arg in the argument list */ int vret_arg_index; int vret_arg_offset; /* Argument space popped by the callee */ int callee_stack_pop; ArgInfo ret; ArgInfo sig_cookie; ArgInfo args [1]; } CallInfo; #define FLOAT_PARAM_REGS 0 static const guint32 thiscall_param_regs [] = { X86_ECX, X86_NREG }; static const guint32 *callconv_param_regs(MonoMethodSignature *sig) { if (!sig->pinvoke) return NULL; switch (sig->call_convention) { case MONO_CALL_THISCALL: return thiscall_param_regs; default: return NULL; } } #if defined(TARGET_WIN32) || defined(__APPLE__) || defined(__FreeBSD__) #define SMALL_STRUCTS_IN_REGS static X86_Reg_No return_regs [] = { X86_EAX, X86_EDX }; #endif static void inline add_general (guint32 *gr, const guint32 *param_regs, guint32 *stack_size, ArgInfo *ainfo) { ainfo->offset = *stack_size; if (!param_regs || param_regs [*gr] == X86_NREG) { ainfo->storage = ArgOnStack; ainfo->nslots = 1; (*stack_size) += sizeof (gpointer); } else { ainfo->storage = ArgInIReg; ainfo->reg = param_regs [*gr]; (*gr) ++; } } static void inline add_general_pair (guint32 *gr, const guint32 *param_regs , guint32 *stack_size, ArgInfo *ainfo) { ainfo->offset = *stack_size; g_assert(!param_regs || param_regs[*gr] == X86_NREG); ainfo->storage = ArgOnStack; (*stack_size) += sizeof (gpointer) * 2; ainfo->nslots = 2; } static void inline add_float (guint32 *gr, guint32 *stack_size, ArgInfo *ainfo, gboolean is_double) { ainfo->offset = *stack_size; if (*gr >= FLOAT_PARAM_REGS) { ainfo->storage = ArgOnStack; (*stack_size) += is_double ? 8 : 4; ainfo->nslots = is_double ? 2 : 1; } else { /* A double register */ if (is_double) ainfo->storage = ArgInDoubleSSEReg; else ainfo->storage = ArgInFloatSSEReg; ainfo->reg = *gr; (*gr) += 1; } } static void add_valuetype (MonoMethodSignature *sig, ArgInfo *ainfo, MonoType *type, gboolean is_return, guint32 *gr, const guint32 *param_regs, guint32 *fr, guint32 *stack_size) { guint32 size; MonoClass *klass; klass = mono_class_from_mono_type (type); size = mini_type_stack_size_full (&klass->byval_arg, NULL, sig->pinvoke); #ifdef SMALL_STRUCTS_IN_REGS if (sig->pinvoke && is_return) { MonoMarshalType *info; /* * the exact rules are not very well documented, the code below seems to work with the * code generated by gcc 3.3.3 -mno-cygwin. */ info = mono_marshal_load_type_info (klass); g_assert (info); ainfo->pair_storage [0] = ainfo->pair_storage [1] = ArgNone; /* Special case structs with only a float member */ if (info->num_fields == 1) { int ftype = mini_get_underlying_type (info->fields [0].field->type)->type; if ((info->native_size == 8) && (ftype == MONO_TYPE_R8)) { ainfo->storage = ArgValuetypeInReg; ainfo->pair_storage [0] = ArgOnDoubleFpStack; return; } if ((info->native_size == 4) && (ftype == MONO_TYPE_R4)) { ainfo->storage = ArgValuetypeInReg; ainfo->pair_storage [0] = ArgOnFloatFpStack; return; } } if ((info->native_size == 1) || (info->native_size == 2) || (info->native_size == 4) || (info->native_size == 8)) { ainfo->storage = ArgValuetypeInReg; ainfo->pair_storage [0] = ArgInIReg; ainfo->pair_regs [0] = return_regs [0]; if (info->native_size > 4) { ainfo->pair_storage [1] = ArgInIReg; ainfo->pair_regs [1] = return_regs [1]; } return; } } #endif if (param_regs && param_regs [*gr] != X86_NREG && !is_return) { g_assert (size <= 4); ainfo->storage = ArgValuetypeInReg; ainfo->reg = param_regs [*gr]; (*gr)++; return; } ainfo->offset = *stack_size; ainfo->storage = ArgOnStack; *stack_size += ALIGN_TO (size, sizeof (gpointer)); ainfo->nslots = ALIGN_TO (size, sizeof (gpointer)) / sizeof (gpointer); } /* * get_call_info: * * Obtain information about a call according to the calling convention. * For x86 ELF, see the "System V Application Binary Interface Intel386 * Architecture Processor Supplment, Fourth Edition" document for more * information. * For x86 win32, see ???. */ static CallInfo* get_call_info_internal (CallInfo *cinfo, MonoMethodSignature *sig) { guint32 i, gr, fr, pstart; const guint32 *param_regs; MonoType *ret_type; int n = sig->hasthis + sig->param_count; guint32 stack_size = 0; gboolean is_pinvoke = sig->pinvoke; gr = 0; fr = 0; cinfo->nargs = n; param_regs = callconv_param_regs(sig); /* return value */ { ret_type = mini_get_underlying_type (sig->ret); switch (ret_type->type) { case MONO_TYPE_I1: case MONO_TYPE_U1: case MONO_TYPE_I2: case MONO_TYPE_U2: case MONO_TYPE_I4: case MONO_TYPE_U4: case MONO_TYPE_I: case MONO_TYPE_U: case MONO_TYPE_PTR: case MONO_TYPE_FNPTR: case MONO_TYPE_CLASS: case MONO_TYPE_OBJECT: case MONO_TYPE_SZARRAY: case MONO_TYPE_ARRAY: case MONO_TYPE_STRING: cinfo->ret.storage = ArgInIReg; cinfo->ret.reg = X86_EAX; break; case MONO_TYPE_U8: case MONO_TYPE_I8: cinfo->ret.storage = ArgInIReg; cinfo->ret.reg = X86_EAX; cinfo->ret.is_pair = TRUE; break; case MONO_TYPE_R4: cinfo->ret.storage = ArgOnFloatFpStack; break; case MONO_TYPE_R8: cinfo->ret.storage = ArgOnDoubleFpStack; break; case MONO_TYPE_GENERICINST: if (!mono_type_generic_inst_is_valuetype (ret_type)) { cinfo->ret.storage = ArgInIReg; cinfo->ret.reg = X86_EAX; break; } if (mini_is_gsharedvt_type (ret_type)) { cinfo->ret.storage = ArgOnStack; cinfo->vtype_retaddr = TRUE; break; } /* Fall through */ case MONO_TYPE_VALUETYPE: case MONO_TYPE_TYPEDBYREF: { guint32 tmp_gr = 0, tmp_fr = 0, tmp_stacksize = 0; add_valuetype (sig, &cinfo->ret, ret_type, TRUE, &tmp_gr, NULL, &tmp_fr, &tmp_stacksize); if (cinfo->ret.storage == ArgOnStack) { cinfo->vtype_retaddr = TRUE; /* The caller passes the address where the value is stored */ } break; } case MONO_TYPE_VAR: case MONO_TYPE_MVAR: g_assert (mini_is_gsharedvt_type (ret_type)); cinfo->ret.storage = ArgOnStack; cinfo->vtype_retaddr = TRUE; break; case MONO_TYPE_VOID: cinfo->ret.storage = ArgNone; break; default: g_error ("Can't handle as return value 0x%x", ret_type->type); } } pstart = 0; /* * To simplify get_this_arg_reg () and LLVM integration, emit the vret arg after * the first argument, allowing 'this' to be always passed in the first arg reg. * Also do this if the first argument is a reference type, since virtual calls * are sometimes made using calli without sig->hasthis set, like in the delegate * invoke wrappers. */ if (cinfo->vtype_retaddr && !is_pinvoke && (sig->hasthis || (sig->param_count > 0 && MONO_TYPE_IS_REFERENCE (mini_get_underlying_type (sig->params [0]))))) { if (sig->hasthis) { add_general (&gr, param_regs, &stack_size, cinfo->args + 0); } else { add_general (&gr, param_regs, &stack_size, &cinfo->args [sig->hasthis + 0]); pstart = 1; } cinfo->vret_arg_offset = stack_size; add_general (&gr, NULL, &stack_size, &cinfo->ret); cinfo->vret_arg_index = 1; } else { /* this */ if (sig->hasthis) add_general (&gr, param_regs, &stack_size, cinfo->args + 0); if (cinfo->vtype_retaddr) add_general (&gr, NULL, &stack_size, &cinfo->ret); } if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (n == 0)) { fr = FLOAT_PARAM_REGS; /* Emit the signature cookie just before the implicit arguments */ add_general (&gr, param_regs, &stack_size, &cinfo->sig_cookie); } for (i = pstart; i < sig->param_count; ++i) { ArgInfo *ainfo = &cinfo->args [sig->hasthis + i]; MonoType *ptype; if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (i == sig->sentinelpos)) { /* We allways pass the sig cookie on the stack for simplicity */ /* * Prevent implicit arguments + the sig cookie from being passed * in registers. */ fr = FLOAT_PARAM_REGS; /* Emit the signature cookie just before the implicit arguments */ add_general (&gr, param_regs, &stack_size, &cinfo->sig_cookie); } if (sig->params [i]->byref) { add_general (&gr, param_regs, &stack_size, ainfo); continue; } ptype = mini_get_underlying_type (sig->params [i]); switch (ptype->type) { case MONO_TYPE_I1: case MONO_TYPE_U1: add_general (&gr, param_regs, &stack_size, ainfo); break; case MONO_TYPE_I2: case MONO_TYPE_U2: add_general (&gr, param_regs, &stack_size, ainfo); break; case MONO_TYPE_I4: case MONO_TYPE_U4: add_general (&gr, param_regs, &stack_size, ainfo); break; case MONO_TYPE_I: case MONO_TYPE_U: case MONO_TYPE_PTR: case MONO_TYPE_FNPTR: case MONO_TYPE_CLASS: case MONO_TYPE_OBJECT: case MONO_TYPE_STRING: case MONO_TYPE_SZARRAY: case MONO_TYPE_ARRAY: add_general (&gr, param_regs, &stack_size, ainfo); break; case MONO_TYPE_GENERICINST: if (!mono_type_generic_inst_is_valuetype (ptype)) { add_general (&gr, param_regs, &stack_size, ainfo); break; } if (mini_is_gsharedvt_type (ptype)) { /* gsharedvt arguments are passed by ref */ add_general (&gr, param_regs, &stack_size, ainfo); g_assert (ainfo->storage == ArgOnStack); ainfo->storage = ArgGSharedVt; break; } /* Fall through */ case MONO_TYPE_VALUETYPE: case MONO_TYPE_TYPEDBYREF: add_valuetype (sig, ainfo, ptype, FALSE, &gr, param_regs, &fr, &stack_size); break; case MONO_TYPE_U8: case MONO_TYPE_I8: add_general_pair (&gr, param_regs, &stack_size, ainfo); break; case MONO_TYPE_R4: add_float (&fr, &stack_size, ainfo, FALSE); break; case MONO_TYPE_R8: add_float (&fr, &stack_size, ainfo, TRUE); break; case MONO_TYPE_VAR: case MONO_TYPE_MVAR: /* gsharedvt arguments are passed by ref */ g_assert (mini_is_gsharedvt_type (ptype)); add_general (&gr, param_regs, &stack_size, ainfo); g_assert (ainfo->storage == ArgOnStack); ainfo->storage = ArgGSharedVt; break; default: g_error ("unexpected type 0x%x", ptype->type); g_assert_not_reached (); } } if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (n > 0) && (sig->sentinelpos == sig->param_count)) { fr = FLOAT_PARAM_REGS; /* Emit the signature cookie just before the implicit arguments */ add_general (&gr, param_regs, &stack_size, &cinfo->sig_cookie); } if (cinfo->vtype_retaddr) { /* if the function returns a struct on stack, the called method already does a ret $0x4 */ cinfo->callee_stack_pop = 4; } else if (CALLCONV_IS_STDCALL (sig) && sig->pinvoke) { /* Have to compensate for the stack space popped by the native callee */ cinfo->callee_stack_pop = stack_size; } if (mono_do_x86_stack_align && (stack_size % MONO_ARCH_FRAME_ALIGNMENT) != 0) { cinfo->need_stack_align = TRUE; cinfo->stack_align_amount = MONO_ARCH_FRAME_ALIGNMENT - (stack_size % MONO_ARCH_FRAME_ALIGNMENT); stack_size += cinfo->stack_align_amount; } cinfo->stack_usage = stack_size; cinfo->reg_usage = gr; cinfo->freg_usage = fr; return cinfo; } static CallInfo* get_call_info (MonoMemPool *mp, MonoMethodSignature *sig) { int n = sig->hasthis + sig->param_count; CallInfo *cinfo; if (mp) cinfo = mono_mempool_alloc0 (mp, sizeof (CallInfo) + (sizeof (ArgInfo) * n)); else cinfo = g_malloc0 (sizeof (CallInfo) + (sizeof (ArgInfo) * n)); return get_call_info_internal (cinfo, sig); } /* * mono_arch_get_argument_info: * @csig: a method signature * @param_count: the number of parameters to consider * @arg_info: an array to store the result infos * * Gathers information on parameters such as size, alignment and * padding. arg_info should be large enought to hold param_count + 1 entries. * * Returns the size of the argument area on the stack. * This should be signal safe, since it is called from * mono_arch_unwind_frame (). * FIXME: The metadata calls might not be signal safe. */ int mono_arch_get_argument_info (MonoMethodSignature *csig, int param_count, MonoJitArgumentInfo *arg_info) { int len, k, args_size = 0; int size, pad; guint32 align; int offset = 8; CallInfo *cinfo; /* Avoid g_malloc as it is not signal safe */ len = sizeof (CallInfo) + (sizeof (ArgInfo) * (csig->param_count + 1)); cinfo = (CallInfo*)g_newa (guint8*, len); memset (cinfo, 0, len); cinfo = get_call_info_internal (cinfo, csig); arg_info [0].offset = offset; if (cinfo->vtype_retaddr && cinfo->vret_arg_index == 0) { args_size += sizeof (gpointer); offset += 4; } if (csig->hasthis) { args_size += sizeof (gpointer); offset += 4; } if (cinfo->vtype_retaddr && cinfo->vret_arg_index == 1 && csig->hasthis) { /* Emitted after this */ args_size += sizeof (gpointer); offset += 4; } arg_info [0].size = args_size; for (k = 0; k < param_count; k++) { size = mini_type_stack_size_full (csig->params [k], &align, csig->pinvoke); /* ignore alignment for now */ align = 1; args_size += pad = (align - (args_size & (align - 1))) & (align - 1); arg_info [k].pad = pad; args_size += size; arg_info [k + 1].pad = 0; arg_info [k + 1].size = size; offset += pad; arg_info [k + 1].offset = offset; offset += size; if (k == 0 && cinfo->vtype_retaddr && cinfo->vret_arg_index == 1 && !csig->hasthis) { /* Emitted after the first arg */ args_size += sizeof (gpointer); offset += 4; } } if (mono_do_x86_stack_align && !CALLCONV_IS_STDCALL (csig)) align = MONO_ARCH_FRAME_ALIGNMENT; else align = 4; args_size += pad = (align - (args_size & (align - 1))) & (align - 1); arg_info [k].pad = pad; return args_size; } gboolean mono_arch_tail_call_supported (MonoCompile *cfg, MonoMethodSignature *caller_sig, MonoMethodSignature *callee_sig) { MonoType *callee_ret; CallInfo *c1, *c2; gboolean res; if (cfg->compile_aot && !cfg->full_aot) /* OP_TAILCALL doesn't work with AOT */ return FALSE; c1 = get_call_info (NULL, caller_sig); c2 = get_call_info (NULL, callee_sig); /* * Tail calls with more callee stack usage than the caller cannot be supported, since * the extra stack space would be left on the stack after the tail call. */ res = c1->stack_usage >= c2->stack_usage; callee_ret = mini_get_underlying_type (callee_sig->ret); if (callee_ret && MONO_TYPE_ISSTRUCT (callee_ret) && c2->ret.storage != ArgValuetypeInReg) /* An address on the callee's stack is passed as the first argument */ res = FALSE; g_free (c1); g_free (c2); return res; } /* * Initialize the cpu to execute managed code. */ void mono_arch_cpu_init (void) { /* spec compliance requires running with double precision */ #ifndef _MSC_VER guint16 fpcw; __asm__ __volatile__ ("fnstcw %0\n": "=m" (fpcw)); fpcw &= ~X86_FPCW_PRECC_MASK; fpcw |= X86_FPCW_PREC_DOUBLE; __asm__ __volatile__ ("fldcw %0\n": : "m" (fpcw)); __asm__ __volatile__ ("fnstcw %0\n": "=m" (fpcw)); #else _control87 (_PC_53, MCW_PC); #endif } /* * Initialize architecture specific code. */ void mono_arch_init (void) { mono_mutex_init_recursive (&mini_arch_mutex); if (!mono_aot_only) bp_trampoline = mini_get_breakpoint_trampoline (); mono_aot_register_jit_icall ("mono_x86_throw_exception", mono_x86_throw_exception); mono_aot_register_jit_icall ("mono_x86_throw_corlib_exception", mono_x86_throw_corlib_exception); #if defined(ENABLE_GSHAREDVT) mono_aot_register_jit_icall ("mono_x86_start_gsharedvt_call", mono_x86_start_gsharedvt_call); #endif } /* * Cleanup architecture specific code. */ void mono_arch_cleanup (void) { mono_mutex_destroy (&mini_arch_mutex); } /* * This function returns the optimizations supported on this cpu. */ guint32 mono_arch_cpu_optimizations (guint32 *exclude_mask) { #if !defined(__native_client__) guint32 opts = 0; *exclude_mask = 0; if (mono_hwcap_x86_has_cmov) { opts |= MONO_OPT_CMOV; if (mono_hwcap_x86_has_fcmov) opts |= MONO_OPT_FCMOV; else *exclude_mask |= MONO_OPT_FCMOV; } else { *exclude_mask |= MONO_OPT_CMOV; } if (mono_hwcap_x86_has_sse2) opts |= MONO_OPT_SSE2; else *exclude_mask |= MONO_OPT_SSE2; #ifdef MONO_ARCH_SIMD_INTRINSICS /*SIMD intrinsics require at least SSE2.*/ if (!mono_hwcap_x86_has_sse2) *exclude_mask |= MONO_OPT_SIMD; #endif return opts; #else return MONO_OPT_CMOV | MONO_OPT_FCMOV | MONO_OPT_SSE2; #endif } /* * This function test for all SSE functions supported. * * Returns a bitmask corresponding to all supported versions. * */ guint32 mono_arch_cpu_enumerate_simd_versions (void) { guint32 sse_opts = 0; if (mono_hwcap_x86_has_sse1) sse_opts |= SIMD_VERSION_SSE1; if (mono_hwcap_x86_has_sse2) sse_opts |= SIMD_VERSION_SSE2; if (mono_hwcap_x86_has_sse3) sse_opts |= SIMD_VERSION_SSE3; if (mono_hwcap_x86_has_ssse3) sse_opts |= SIMD_VERSION_SSSE3; if (mono_hwcap_x86_has_sse41) sse_opts |= SIMD_VERSION_SSE41; if (mono_hwcap_x86_has_sse42) sse_opts |= SIMD_VERSION_SSE42; if (mono_hwcap_x86_has_sse4a) sse_opts |= SIMD_VERSION_SSE4a; return sse_opts; } /* * Determine whenever the trap whose info is in SIGINFO is caused by * integer overflow. */ gboolean mono_arch_is_int_overflow (void *sigctx, void *info) { MonoContext ctx; guint8* ip; mono_sigctx_to_monoctx (sigctx, &ctx); ip = (guint8*)ctx.eip; if ((ip [0] == 0xf7) && (x86_modrm_mod (ip [1]) == 0x3) && (x86_modrm_reg (ip [1]) == 0x7)) { gint32 reg; /* idiv REG */ switch (x86_modrm_rm (ip [1])) { case X86_EAX: reg = ctx.eax; break; case X86_ECX: reg = ctx.ecx; break; case X86_EDX: reg = ctx.edx; break; case X86_EBX: reg = ctx.ebx; break; case X86_ESI: reg = ctx.esi; break; case X86_EDI: reg = ctx.edi; break; default: g_assert_not_reached (); reg = -1; } if (reg == -1) return TRUE; } return FALSE; } GList * mono_arch_get_allocatable_int_vars (MonoCompile *cfg) { GList *vars = NULL; int i; for (i = 0; i < cfg->num_varinfo; i++) { MonoInst *ins = cfg->varinfo [i]; MonoMethodVar *vmv = MONO_VARINFO (cfg, i); /* unused vars */ if (vmv->range.first_use.abs_pos >= vmv->range.last_use.abs_pos) continue; if ((ins->flags & (MONO_INST_IS_DEAD|MONO_INST_VOLATILE|MONO_INST_INDIRECT)) || (ins->opcode != OP_LOCAL && ins->opcode != OP_ARG)) continue; /* we dont allocate I1 to registers because there is no simply way to sign extend * 8bit quantities in caller saved registers on x86 */ if (mono_is_regsize_var (ins->inst_vtype) && (ins->inst_vtype->type != MONO_TYPE_I1)) { g_assert (MONO_VARINFO (cfg, i)->reg == -1); g_assert (i == vmv->idx); vars = g_list_prepend (vars, vmv); } } vars = mono_varlist_sort (cfg, vars, 0); return vars; } GList * mono_arch_get_global_int_regs (MonoCompile *cfg) { GList *regs = NULL; /* we can use 3 registers for global allocation */ regs = g_list_prepend (regs, (gpointer)X86_EBX); regs = g_list_prepend (regs, (gpointer)X86_ESI); regs = g_list_prepend (regs, (gpointer)X86_EDI); return regs; } /* * mono_arch_regalloc_cost: * * Return the cost, in number of memory references, of the action of * allocating the variable VMV into a register during global register * allocation. */ guint32 mono_arch_regalloc_cost (MonoCompile *cfg, MonoMethodVar *vmv) { MonoInst *ins = cfg->varinfo [vmv->idx]; if (cfg->method->save_lmf) /* The register is already saved */ return (ins->opcode == OP_ARG) ? 1 : 0; else /* push+pop+possible load if it is an argument */ return (ins->opcode == OP_ARG) ? 3 : 2; } static void set_needs_stack_frame (MonoCompile *cfg, gboolean flag) { static int inited = FALSE; static int count = 0; if (cfg->arch.need_stack_frame_inited) { g_assert (cfg->arch.need_stack_frame == flag); return; } cfg->arch.need_stack_frame = flag; cfg->arch.need_stack_frame_inited = TRUE; if (flag) return; if (!inited) { mono_counters_register ("Could eliminate stack frame", MONO_COUNTER_INT|MONO_COUNTER_JIT, &count); inited = TRUE; } ++count; //g_print ("will eliminate %s.%s.%s\n", cfg->method->klass->name_space, cfg->method->klass->name, cfg->method->name); } static gboolean needs_stack_frame (MonoCompile *cfg) { MonoMethodSignature *sig; MonoMethodHeader *header; gboolean result = FALSE; #if defined(__APPLE__) /*OSX requires stack frame code to have the correct alignment. */ return TRUE; #endif if (cfg->arch.need_stack_frame_inited) return cfg->arch.need_stack_frame; header = cfg->header; sig = mono_method_signature (cfg->method); if (cfg->disable_omit_fp) result = TRUE; else if (cfg->flags & MONO_CFG_HAS_ALLOCA) result = TRUE; else if (cfg->method->save_lmf) result = TRUE; else if (cfg->stack_offset) result = TRUE; else if (cfg->param_area) result = TRUE; else if (cfg->flags & (MONO_CFG_HAS_CALLS | MONO_CFG_HAS_ALLOCA | MONO_CFG_HAS_TAIL)) result = TRUE; else if (header->num_clauses) result = TRUE; else if (sig->param_count + sig->hasthis) result = TRUE; else if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG)) result = TRUE; else if ((mono_jit_trace_calls != NULL && mono_trace_eval (cfg->method)) || (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)) result = TRUE; set_needs_stack_frame (cfg, result); return cfg->arch.need_stack_frame; } /* * Set var information according to the calling convention. X86 version. * The locals var stuff should most likely be split in another method. */ void mono_arch_allocate_vars (MonoCompile *cfg) { MonoMethodSignature *sig; MonoMethodHeader *header; MonoInst *inst; guint32 locals_stack_size, locals_stack_align; int i, offset; gint32 *offsets; CallInfo *cinfo; header = cfg->header; sig = mono_method_signature (cfg->method); cinfo = get_call_info (cfg->mempool, sig); cfg->frame_reg = X86_EBP; offset = 0; if (cfg->has_atomic_add_i4 || cfg->has_atomic_exchange_i4) { /* The opcode implementations use callee-saved regs as scratch regs by pushing and pop-ing them, but that is not async safe */ cfg->used_int_regs |= (1 << X86_EBX) | (1 << X86_EDI) | (1 << X86_ESI); } /* Reserve space to save LMF and caller saved registers */ if (cfg->method->save_lmf) { /* The LMF var is allocated normally */ } else { if (cfg->used_int_regs & (1 << X86_EBX)) { offset += 4; } if (cfg->used_int_regs & (1 << X86_EDI)) { offset += 4; } if (cfg->used_int_regs & (1 << X86_ESI)) { offset += 4; } } switch (cinfo->ret.storage) { case ArgValuetypeInReg: /* Allocate a local to hold the result, the epilog will copy it to the correct place */ offset += 8; cfg->ret->opcode = OP_REGOFFSET; cfg->ret->inst_basereg = X86_EBP; cfg->ret->inst_offset = - offset; break; default: break; } /* Allocate locals */ offsets = mono_allocate_stack_slots (cfg, TRUE, &locals_stack_size, &locals_stack_align); if (locals_stack_size > MONO_ARCH_MAX_FRAME_SIZE) { char *mname = mono_method_full_name (cfg->method, TRUE); cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM; cfg->exception_message = g_strdup_printf ("Method %s stack is too big.", mname); g_free (mname); return; } if (locals_stack_align) { int prev_offset = offset; offset += (locals_stack_align - 1); offset &= ~(locals_stack_align - 1); while (prev_offset < offset) { prev_offset += 4; mini_gc_set_slot_type_from_fp (cfg, - prev_offset, SLOT_NOREF); } } cfg->locals_min_stack_offset = - (offset + locals_stack_size); cfg->locals_max_stack_offset = - offset; /* * EBP is at alignment 8 % MONO_ARCH_FRAME_ALIGNMENT, so if we * have locals larger than 8 bytes we need to make sure that * they have the appropriate offset. */ if (MONO_ARCH_FRAME_ALIGNMENT > 8 && locals_stack_align > 8) offset += MONO_ARCH_FRAME_ALIGNMENT - sizeof (gpointer) * 2; for (i = cfg->locals_start; i < cfg->num_varinfo; i++) { if (offsets [i] != -1) { MonoInst *inst = cfg->varinfo [i]; inst->opcode = OP_REGOFFSET; inst->inst_basereg = X86_EBP; inst->inst_offset = - (offset + offsets [i]); //printf ("allocated local %d to ", i); mono_print_tree_nl (inst); } } offset += locals_stack_size; /* * Allocate arguments+return value */ switch (cinfo->ret.storage) { case ArgOnStack: if (cfg->vret_addr) { /* * In the new IR, the cfg->vret_addr variable represents the * vtype return value. */ cfg->vret_addr->opcode = OP_REGOFFSET; cfg->vret_addr->inst_basereg = cfg->frame_reg; cfg->vret_addr->inst_offset = cinfo->ret.offset + ARGS_OFFSET; if (G_UNLIKELY (cfg->verbose_level > 1)) { printf ("vret_addr ="); mono_print_ins (cfg->vret_addr); } } else { cfg->ret->opcode = OP_REGOFFSET; cfg->ret->inst_basereg = X86_EBP; cfg->ret->inst_offset = cinfo->ret.offset + ARGS_OFFSET; } break; case ArgValuetypeInReg: break; case ArgInIReg: cfg->ret->opcode = OP_REGVAR; cfg->ret->inst_c0 = cinfo->ret.reg; cfg->ret->dreg = cinfo->ret.reg; break; case ArgNone: case ArgOnFloatFpStack: case ArgOnDoubleFpStack: break; default: g_assert_not_reached (); } if (sig->call_convention == MONO_CALL_VARARG) { g_assert (cinfo->sig_cookie.storage == ArgOnStack); cfg->sig_cookie = cinfo->sig_cookie.offset + ARGS_OFFSET; } for (i = 0; i < sig->param_count + sig->hasthis; ++i) { ArgInfo *ainfo = &cinfo->args [i]; inst = cfg->args [i]; if (inst->opcode != OP_REGVAR) { inst->opcode = OP_REGOFFSET; inst->inst_basereg = X86_EBP; } inst->inst_offset = ainfo->offset + ARGS_OFFSET; } cfg->stack_offset = offset; } void mono_arch_create_vars (MonoCompile *cfg) { MonoType *sig_ret; MonoMethodSignature *sig; CallInfo *cinfo; sig = mono_method_signature (cfg->method); cinfo = get_call_info (cfg->mempool, sig); sig_ret = mini_get_underlying_type (sig->ret); if (cinfo->ret.storage == ArgValuetypeInReg) cfg->ret_var_is_local = TRUE; if ((cinfo->ret.storage != ArgValuetypeInReg) && (MONO_TYPE_ISSTRUCT (sig_ret) || mini_is_gsharedvt_variable_type (sig_ret))) { cfg->vret_addr = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_ARG); } if (cfg->gen_sdb_seq_points) { MonoInst *ins; ins = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL); ins->flags |= MONO_INST_VOLATILE; cfg->arch.ss_tramp_var = ins; ins = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL); ins->flags |= MONO_INST_VOLATILE; cfg->arch.bp_tramp_var = ins; } if (cfg->method->save_lmf) { cfg->create_lmf_var = TRUE; cfg->lmf_ir = TRUE; #ifndef HOST_WIN32 cfg->lmf_ir_mono_lmf = TRUE; #endif } cfg->arch_eh_jit_info = 1; } /* * It is expensive to adjust esp for each individual fp argument pushed on the stack * so we try to do it just once when we have multiple fp arguments in a row. * We don't use this mechanism generally because for int arguments the generated code * is slightly bigger and new generation cpus optimize away the dependency chains * created by push instructions on the esp value. * fp_arg_setup is the first argument in the execution sequence where the esp register * is modified. */ static G_GNUC_UNUSED int collect_fp_stack_space (MonoMethodSignature *sig, int start_arg, int *fp_arg_setup) { int fp_space = 0; MonoType *t; for (; start_arg < sig->param_count; ++start_arg) { t = mini_get_underlying_type (sig->params [start_arg]); if (!t->byref && t->type == MONO_TYPE_R8) { fp_space += sizeof (double); *fp_arg_setup = start_arg; } else { break; } } return fp_space; } static void emit_sig_cookie (MonoCompile *cfg, MonoCallInst *call, CallInfo *cinfo) { MonoMethodSignature *tmp_sig; int sig_reg; /* * mono_ArgIterator_Setup assumes the signature cookie is * passed first and all the arguments which were before it are * passed on the stack after the signature. So compensate by * passing a different signature. */ tmp_sig = mono_metadata_signature_dup (call->signature); tmp_sig->param_count -= call->signature->sentinelpos; tmp_sig->sentinelpos = 0; memcpy (tmp_sig->params, call->signature->params + call->signature->sentinelpos, tmp_sig->param_count * sizeof (MonoType*)); if (cfg->compile_aot) { sig_reg = mono_alloc_ireg (cfg); MONO_EMIT_NEW_SIGNATURECONST (cfg, sig_reg, tmp_sig); MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, X86_ESP, cinfo->sig_cookie.offset, sig_reg); } else { MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, X86_ESP, cinfo->sig_cookie.offset, tmp_sig); } } #ifdef ENABLE_LLVM LLVMCallInfo* mono_arch_get_llvm_call_info (MonoCompile *cfg, MonoMethodSignature *sig) { int i, n; CallInfo *cinfo; ArgInfo *ainfo; LLVMCallInfo *linfo; MonoType *t, *sig_ret; n = sig->param_count + sig->hasthis; cinfo = get_call_info (cfg->mempool, sig); sig_ret = sig->ret; linfo = mono_mempool_alloc0 (cfg->mempool, sizeof (LLVMCallInfo) + (sizeof (LLVMArgInfo) * n)); /* * LLVM always uses the native ABI while we use our own ABI, the * only difference is the handling of vtypes: * - we only pass/receive them in registers in some cases, and only * in 1 or 2 integer registers. */ if (cinfo->ret.storage == ArgValuetypeInReg) { if (sig->pinvoke) { cfg->exception_message = g_strdup ("pinvoke + vtypes"); cfg->disable_llvm = TRUE; return linfo; } cfg->exception_message = g_strdup ("vtype ret in call"); cfg->disable_llvm = TRUE; /* linfo->ret.storage = LLVMArgVtypeInReg; for (j = 0; j < 2; ++j) linfo->ret.pair_storage [j] = arg_storage_to_llvm_arg_storage (cfg, cinfo->ret.pair_storage [j]); */ } if (mini_type_is_vtype (sig_ret) && cinfo->ret.storage == ArgInIReg) { /* Vtype returned using a hidden argument */ linfo->ret.storage = LLVMArgVtypeRetAddr; linfo->vret_arg_index = cinfo->vret_arg_index; } if (mini_type_is_vtype (sig_ret) && cinfo->ret.storage != ArgInIReg) { // FIXME: cfg->exception_message = g_strdup ("vtype ret in call"); cfg->disable_llvm = TRUE; } for (i = 0; i < n; ++i) { ainfo = cinfo->args + i; if (i >= sig->hasthis) t = sig->params [i - sig->hasthis]; else t = &mono_defaults.int_class->byval_arg; linfo->args [i].storage = LLVMArgNone; switch (ainfo->storage) { case ArgInIReg: linfo->args [i].storage = LLVMArgInIReg; break; case ArgInDoubleSSEReg: case ArgInFloatSSEReg: linfo->args [i].storage = LLVMArgInFPReg; break; case ArgOnStack: if (mini_type_is_vtype (t)) { if (mono_class_value_size (mono_class_from_mono_type (t), NULL) == 0) /* LLVM seems to allocate argument space for empty structures too */ linfo->args [i].storage = LLVMArgNone; else linfo->args [i].storage = LLVMArgVtypeByVal; } else { linfo->args [i].storage = LLVMArgInIReg; if (t->byref) { if (t->type == MONO_TYPE_R4) linfo->args [i].storage = LLVMArgInFPReg; else if (t->type == MONO_TYPE_R8) linfo->args [i].storage = LLVMArgInFPReg; } } break; case ArgValuetypeInReg: if (sig->pinvoke) { cfg->exception_message = g_strdup ("pinvoke + vtypes"); cfg->disable_llvm = TRUE; return linfo; } cfg->exception_message = g_strdup ("vtype arg"); cfg->disable_llvm = TRUE; /* linfo->args [i].storage = LLVMArgVtypeInReg; for (j = 0; j < 2; ++j) linfo->args [i].pair_storage [j] = arg_storage_to_llvm_arg_storage (cfg, ainfo->pair_storage [j]); */ break; case ArgGSharedVt: linfo->args [i].storage = LLVMArgGSharedVt; break; default: cfg->exception_message = g_strdup ("ainfo->storage"); cfg->disable_llvm = TRUE; break; } } return linfo; } #endif static void emit_gc_param_slot_def (MonoCompile *cfg, int sp_offset, MonoType *t) { if (cfg->compute_gc_maps) { MonoInst *def; /* Needs checking if the feature will be enabled again */ g_assert_not_reached (); /* On x86, the offsets are from the sp value before the start of the call sequence */ if (t == NULL) t = &mono_defaults.int_class->byval_arg; EMIT_NEW_GC_PARAM_SLOT_LIVENESS_DEF (cfg, def, sp_offset, t); } } void mono_arch_emit_call (MonoCompile *cfg, MonoCallInst *call) { MonoType *sig_ret; MonoInst *arg, *in; MonoMethodSignature *sig; int i, j, n; CallInfo *cinfo; int sentinelpos = 0, sp_offset = 0; sig = call->signature; n = sig->param_count + sig->hasthis; sig_ret = mini_get_underlying_type (sig->ret); cinfo = get_call_info (cfg->mempool, sig); call->call_info = cinfo; if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG)) sentinelpos = sig->sentinelpos + (sig->hasthis ? 1 : 0); if (sig_ret && MONO_TYPE_ISSTRUCT (sig_ret)) { if (cinfo->ret.storage == ArgValuetypeInReg) { /* * Tell the JIT to use a more efficient calling convention: call using * OP_CALL, compute the result location after the call, and save the * result there. */ call->vret_in_reg = TRUE; #if defined(__APPLE__) if (cinfo->ret.pair_storage [0] == ArgOnDoubleFpStack || cinfo->ret.pair_storage [0] == ArgOnFloatFpStack) call->vret_in_reg_fp = TRUE; #endif if (call->vret_var) NULLIFY_INS (call->vret_var); } } // FIXME: Emit EMIT_NEW_GC_PARAM_SLOT_LIVENESS_DEF everywhere /* Handle the case where there are no implicit arguments */ if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (n == sentinelpos)) { emit_sig_cookie (cfg, call, cinfo); sp_offset = cinfo->sig_cookie.offset; emit_gc_param_slot_def (cfg, sp_offset, NULL); } /* Arguments are pushed in the reverse order */ for (i = n - 1; i >= 0; i --) { ArgInfo *ainfo = cinfo->args + i; MonoType *orig_type, *t; int argsize; if (cinfo->vtype_retaddr && cinfo->vret_arg_index == 1 && i == 0) { MonoInst *vtarg; /* Push the vret arg before the first argument */ MONO_INST_NEW (cfg, vtarg, OP_STORE_MEMBASE_REG); vtarg->type = STACK_MP; vtarg->inst_destbasereg = X86_ESP; vtarg->sreg1 = call->vret_var->dreg; vtarg->inst_offset = cinfo->ret.offset; MONO_ADD_INS (cfg->cbb, vtarg); emit_gc_param_slot_def (cfg, cinfo->ret.offset, NULL); } if (i >= sig->hasthis) t = sig->params [i - sig->hasthis]; else t = &mono_defaults.int_class->byval_arg; orig_type = t; t = mini_get_underlying_type (t); MONO_INST_NEW (cfg, arg, OP_X86_PUSH); in = call->args [i]; arg->cil_code = in->cil_code; arg->sreg1 = in->dreg; arg->type = in->type; g_assert (in->dreg != -1); if (ainfo->storage == ArgGSharedVt) { arg->opcode = OP_OUTARG_VT; arg->sreg1 = in->dreg; arg->klass = in->klass; arg->inst_p1 = mono_mempool_alloc (cfg->mempool, sizeof (ArgInfo)); memcpy (arg->inst_p1, ainfo, sizeof (ArgInfo)); sp_offset += 4; MONO_ADD_INS (cfg->cbb, arg); } else if ((i >= sig->hasthis) && (MONO_TYPE_ISSTRUCT(t))) { guint32 align; guint32 size; g_assert (in->klass); if (t->type == MONO_TYPE_TYPEDBYREF) { size = sizeof (MonoTypedRef); align = sizeof (gpointer); } else { size = mini_type_stack_size_full (&in->klass->byval_arg, &align, sig->pinvoke); } if (size > 0) { arg->opcode = OP_OUTARG_VT; arg->sreg1 = in->dreg; arg->klass = in->klass; arg->backend.size = size; arg->inst_p0 = call; arg->inst_p1 = mono_mempool_alloc (cfg->mempool, sizeof (ArgInfo)); memcpy (arg->inst_p1, ainfo, sizeof (ArgInfo)); MONO_ADD_INS (cfg->cbb, arg); if (ainfo->storage != ArgValuetypeInReg) { emit_gc_param_slot_def (cfg, ainfo->offset, orig_type); } } } else { switch (ainfo->storage) { case ArgOnStack: if (!t->byref) { if (t->type == MONO_TYPE_R4) { MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORER4_MEMBASE_REG, X86_ESP, ainfo->offset, in->dreg); argsize = 4; } else if (t->type == MONO_TYPE_R8) { MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORER8_MEMBASE_REG, X86_ESP, ainfo->offset, in->dreg); argsize = 8; } else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_U8) { MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, X86_ESP, ainfo->offset + 4, in->dreg + 2); MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, X86_ESP, ainfo->offset, in->dreg + 1); argsize = 4; } else { MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, X86_ESP, ainfo->offset, in->dreg); argsize = 4; } } else { MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, X86_ESP, ainfo->offset, in->dreg); argsize = 4; } break; case ArgInIReg: arg->opcode = OP_MOVE; arg->dreg = ainfo->reg; MONO_ADD_INS (cfg->cbb, arg); argsize = 0; break; default: g_assert_not_reached (); } if (cfg->compute_gc_maps) { if (argsize == 4) { /* FIXME: The == STACK_OBJ check might be fragile ? */ if (sig->hasthis && i == 0 && call->args [i]->type == STACK_OBJ) { /* this */ if (call->need_unbox_trampoline) /* The unbox trampoline transforms this into a managed pointer */ emit_gc_param_slot_def (cfg, ainfo->offset, &mono_defaults.int_class->this_arg); else emit_gc_param_slot_def (cfg, ainfo->offset, &mono_defaults.object_class->byval_arg); } else { emit_gc_param_slot_def (cfg, ainfo->offset, orig_type); } } else { /* i8/r8 */ for (j = 0; j < argsize; j += 4) emit_gc_param_slot_def (cfg, ainfo->offset + j, NULL); } } } if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (i == sentinelpos)) { /* Emit the signature cookie just before the implicit arguments */ emit_sig_cookie (cfg, call, cinfo); emit_gc_param_slot_def (cfg, cinfo->sig_cookie.offset, NULL); } } if (sig_ret && (MONO_TYPE_ISSTRUCT (sig_ret) || cinfo->vtype_retaddr)) { MonoInst *vtarg; if (cinfo->ret.storage == ArgValuetypeInReg) { /* Already done */ } else if (cinfo->ret.storage == ArgInIReg) { NOT_IMPLEMENTED; /* The return address is passed in a register */ MONO_INST_NEW (cfg, vtarg, OP_MOVE); vtarg->sreg1 = call->inst.dreg; vtarg->dreg = mono_alloc_ireg (cfg); MONO_ADD_INS (cfg->cbb, vtarg); mono_call_inst_add_outarg_reg (cfg, call, vtarg->dreg, cinfo->ret.reg, FALSE); } else if (cinfo->vtype_retaddr && cinfo->vret_arg_index == 0) { MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, X86_ESP, cinfo->ret.offset, call->vret_var->dreg); emit_gc_param_slot_def (cfg, cinfo->ret.offset, NULL); } } call->stack_usage = cinfo->stack_usage; call->stack_align_amount = cinfo->stack_align_amount; } void mono_arch_emit_outarg_vt (MonoCompile *cfg, MonoInst *ins, MonoInst *src) { MonoCallInst *call = (MonoCallInst*)ins->inst_p0; ArgInfo *ainfo = ins->inst_p1; int size = ins->backend.size; if (ainfo->storage == ArgValuetypeInReg) { int dreg = mono_alloc_ireg (cfg); switch (size) { case 1: MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, dreg, src->dreg, 0); break; case 2: MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU2_MEMBASE, dreg, src->dreg, 0); break; case 4: MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, src->dreg, 0); break; case 3: /* FIXME */ default: g_assert_not_reached (); } mono_call_inst_add_outarg_reg (cfg, call, dreg, ainfo->reg, FALSE); } else { if (cfg->gsharedvt && mini_is_gsharedvt_klass (ins->klass)) { /* Pass by addr */ MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, X86_ESP, ainfo->offset, src->dreg); } else if (size <= 4) { int dreg = mono_alloc_ireg (cfg); MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, src->dreg, 0); MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, X86_ESP, ainfo->offset, dreg); } else if (size <= 20) { mini_emit_memcpy (cfg, X86_ESP, ainfo->offset, src->dreg, 0, size, 4); } else { // FIXME: Code growth mini_emit_memcpy (cfg, X86_ESP, ainfo->offset, src->dreg, 0, size, 4); } } } void mono_arch_emit_setret (MonoCompile *cfg, MonoMethod *method, MonoInst *val) { MonoType *ret = mini_get_underlying_type (mono_method_signature (method)->ret); if (!ret->byref) { if (ret->type == MONO_TYPE_R4) { if (COMPILE_LLVM (cfg)) MONO_EMIT_NEW_UNALU (cfg, OP_FMOVE, cfg->ret->dreg, val->dreg); /* Nothing to do */ return; } else if (ret->type == MONO_TYPE_R8) { if (COMPILE_LLVM (cfg)) MONO_EMIT_NEW_UNALU (cfg, OP_FMOVE, cfg->ret->dreg, val->dreg); /* Nothing to do */ return; } else if (ret->type == MONO_TYPE_I8 || ret->type == MONO_TYPE_U8) { if (COMPILE_LLVM (cfg)) MONO_EMIT_NEW_UNALU (cfg, OP_LMOVE, cfg->ret->dreg, val->dreg); else { MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, X86_EAX, val->dreg + 1); MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, X86_EDX, val->dreg + 2); } return; } } MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->ret->dreg, val->dreg); } /* * Allow tracing to work with this interface (with an optional argument) */ void* mono_arch_instrument_prolog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments) { guchar *code = p; g_assert (MONO_ARCH_FRAME_ALIGNMENT >= 8); x86_alu_reg_imm (code, X86_SUB, X86_ESP, MONO_ARCH_FRAME_ALIGNMENT - 8); /* if some args are passed in registers, we need to save them here */ x86_push_reg (code, X86_EBP); if (cfg->compile_aot) { x86_push_imm (code, cfg->method); x86_mov_reg_imm (code, X86_EAX, func); x86_call_reg (code, X86_EAX); } else { mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_METHODCONST, cfg->method); x86_push_imm (code, cfg->method); mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_ABS, func); x86_call_code (code, 0); } x86_alu_reg_imm (code, X86_ADD, X86_ESP, MONO_ARCH_FRAME_ALIGNMENT); return code; } enum { SAVE_NONE, SAVE_STRUCT, SAVE_EAX, SAVE_EAX_EDX, SAVE_FP }; void* mono_arch_instrument_epilog_full (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments, gboolean preserve_argument_registers) { guchar *code = p; int arg_size = 0, stack_usage = 0, save_mode = SAVE_NONE; MonoMethod *method = cfg->method; MonoType *ret_type = mini_get_underlying_type (mono_method_signature (method)->ret); switch (ret_type->type) { case MONO_TYPE_VOID: /* special case string .ctor icall */ if (strcmp (".ctor", method->name) && method->klass == mono_defaults.string_class) { save_mode = SAVE_EAX; stack_usage = enable_arguments ? 8 : 4; } else save_mode = SAVE_NONE; break; case MONO_TYPE_I8: case MONO_TYPE_U8: save_mode = SAVE_EAX_EDX; stack_usage = enable_arguments ? 16 : 8; break; case MONO_TYPE_R4: case MONO_TYPE_R8: save_mode = SAVE_FP; stack_usage = enable_arguments ? 16 : 8; break; case MONO_TYPE_GENERICINST: if (!mono_type_generic_inst_is_valuetype (ret_type)) { save_mode = SAVE_EAX; stack_usage = enable_arguments ? 8 : 4; break; } /* Fall through */ case MONO_TYPE_VALUETYPE: // FIXME: Handle SMALL_STRUCT_IN_REG here for proper alignment on darwin-x86 save_mode = SAVE_STRUCT; stack_usage = enable_arguments ? 4 : 0; break; default: save_mode = SAVE_EAX; stack_usage = enable_arguments ? 8 : 4; break; } x86_alu_reg_imm (code, X86_SUB, X86_ESP, MONO_ARCH_FRAME_ALIGNMENT - stack_usage - 4); switch (save_mode) { case SAVE_EAX_EDX: x86_push_reg (code, X86_EDX); x86_push_reg (code, X86_EAX); if (enable_arguments) { x86_push_reg (code, X86_EDX); x86_push_reg (code, X86_EAX); arg_size = 8; } break; case SAVE_EAX: x86_push_reg (code, X86_EAX); if (enable_arguments) { x86_push_reg (code, X86_EAX); arg_size = 4; } break; case SAVE_FP: x86_alu_reg_imm (code, X86_SUB, X86_ESP, 8); x86_fst_membase (code, X86_ESP, 0, TRUE, TRUE); if (enable_arguments) { x86_alu_reg_imm (code, X86_SUB, X86_ESP, 8); x86_fst_membase (code, X86_ESP, 0, TRUE, TRUE); arg_size = 8; } break; case SAVE_STRUCT: if (enable_arguments) { x86_push_membase (code, X86_EBP, 8); arg_size = 4; } break; case SAVE_NONE: default: break; } if (cfg->compile_aot) { x86_push_imm (code, method); x86_mov_reg_imm (code, X86_EAX, func); x86_call_reg (code, X86_EAX); } else { mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_METHODCONST, method); x86_push_imm (code, method); mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_ABS, func); x86_call_code (code, 0); } x86_alu_reg_imm (code, X86_ADD, X86_ESP, arg_size + 4); switch (save_mode) { case SAVE_EAX_EDX: x86_pop_reg (code, X86_EAX); x86_pop_reg (code, X86_EDX); break; case SAVE_EAX: x86_pop_reg (code, X86_EAX); break; case SAVE_FP: x86_fld_membase (code, X86_ESP, 0, TRUE); x86_alu_reg_imm (code, X86_ADD, X86_ESP, 8); break; case SAVE_NONE: default: break; } x86_alu_reg_imm (code, X86_ADD, X86_ESP, MONO_ARCH_FRAME_ALIGNMENT - stack_usage); return code; } #define EMIT_COND_BRANCH(ins,cond,sign) \ if (ins->inst_true_bb->native_offset) { \ x86_branch (code, cond, cfg->native_code + ins->inst_true_bb->native_offset, sign); \ } else { \ mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_true_bb); \ if ((cfg->opt & MONO_OPT_BRANCH) && \ x86_is_imm8 (ins->inst_true_bb->max_offset - cpos)) \ x86_branch8 (code, cond, 0, sign); \ else \ x86_branch32 (code, cond, 0, sign); \ } /* * Emit an exception if condition is fail and * if possible do a directly branch to target */ #define EMIT_COND_SYSTEM_EXCEPTION(cond,signed,exc_name) \ do { \ MonoInst *tins = mono_branch_optimize_exception_target (cfg, bb, exc_name); \ if (tins == NULL) { \ mono_add_patch_info (cfg, code - cfg->native_code, \ MONO_PATCH_INFO_EXC, exc_name); \ x86_branch32 (code, cond, 0, signed); \ } else { \ EMIT_COND_BRANCH (tins, cond, signed); \ } \ } while (0); #define EMIT_FPCOMPARE(code) do { \ x86_fcompp (code); \ x86_fnstsw (code); \ } while (0); static guint8* emit_call (MonoCompile *cfg, guint8 *code, guint32 patch_type, gconstpointer data) { gboolean needs_paddings = TRUE; guint32 pad_size; MonoJumpInfo *jinfo = NULL; if (cfg->abs_patches) { jinfo = g_hash_table_lookup (cfg->abs_patches, data); if (jinfo && jinfo->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) needs_paddings = FALSE; } if (cfg->compile_aot) needs_paddings = FALSE; /*The address must be 4 bytes aligned to avoid spanning multiple cache lines. This is required for code patching to be safe on SMP machines. */ pad_size = (guint32)(code + 1 - cfg->native_code) & 0x3; #ifndef __native_client_codegen__ if (needs_paddings && pad_size) x86_padding (code, 4 - pad_size); #endif mono_add_patch_info (cfg, code - cfg->native_code, patch_type, data); x86_call_code (code, 0); return code; } #define INST_IGNORES_CFLAGS(opcode) (!(((opcode) == OP_ADC) || ((opcode) == OP_IADC) || ((opcode) == OP_ADC_IMM) || ((opcode) == OP_IADC_IMM) || ((opcode) == OP_SBB) || ((opcode) == OP_ISBB) || ((opcode) == OP_SBB_IMM) || ((opcode) == OP_ISBB_IMM))) /* * mono_peephole_pass_1: * * Perform peephole opts which should/can be performed before local regalloc */ void mono_arch_peephole_pass_1 (MonoCompile *cfg, MonoBasicBlock *bb) { MonoInst *ins, *n; MONO_BB_FOR_EACH_INS_SAFE (bb, n, ins) { MonoInst *last_ins = mono_inst_prev (ins, FILTER_IL_SEQ_POINT); switch (ins->opcode) { case OP_IADD_IMM: case OP_ADD_IMM: if ((ins->sreg1 < MONO_MAX_IREGS) && (ins->dreg >= MONO_MAX_IREGS)) { /* * X86_LEA is like ADD, but doesn't have the * sreg1==dreg restriction. */ ins->opcode = OP_X86_LEA_MEMBASE; ins->inst_basereg = ins->sreg1; } else if ((ins->inst_imm == 1) && (ins->dreg == ins->sreg1)) ins->opcode = OP_X86_INC_REG; break; case OP_SUB_IMM: case OP_ISUB_IMM: if ((ins->sreg1 < MONO_MAX_IREGS) && (ins->dreg >= MONO_MAX_IREGS)) { ins->opcode = OP_X86_LEA_MEMBASE; ins->inst_basereg = ins->sreg1; ins->inst_imm = -ins->inst_imm; } else if ((ins->inst_imm == 1) && (ins->dreg == ins->sreg1)) ins->opcode = OP_X86_DEC_REG; break; case OP_COMPARE_IMM: case OP_ICOMPARE_IMM: /* OP_COMPARE_IMM (reg, 0) * --> * OP_X86_TEST_NULL (reg) */ if (!ins->inst_imm) ins->opcode = OP_X86_TEST_NULL; break; case OP_X86_COMPARE_MEMBASE_IMM: /* * OP_STORE_MEMBASE_REG reg, offset(basereg) * OP_X86_COMPARE_MEMBASE_IMM offset(basereg), imm * --> * OP_STORE_MEMBASE_REG reg, offset(basereg) * OP_COMPARE_IMM reg, imm * * Note: if imm = 0 then OP_COMPARE_IMM replaced with OP_X86_TEST_NULL */ if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_REG) && ins->inst_basereg == last_ins->inst_destbasereg && ins->inst_offset == last_ins->inst_offset) { ins->opcode = OP_COMPARE_IMM; ins->sreg1 = last_ins->sreg1; /* check if we can remove cmp reg,0 with test null */ if (!ins->inst_imm) ins->opcode = OP_X86_TEST_NULL; } break; case OP_X86_PUSH_MEMBASE: if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_REG || last_ins->opcode == OP_STORE_MEMBASE_REG) && ins->inst_basereg == last_ins->inst_destbasereg && ins->inst_offset == last_ins->inst_offset) { ins->opcode = OP_X86_PUSH; ins->sreg1 = last_ins->sreg1; } break; } mono_peephole_ins (bb, ins); } } void mono_arch_peephole_pass_2 (MonoCompile *cfg, MonoBasicBlock *bb) { MonoInst *ins, *n; MONO_BB_FOR_EACH_INS_SAFE (bb, n, ins) { switch (ins->opcode) { case OP_ICONST: /* reg = 0 -> XOR (reg, reg) */ /* XOR sets cflags on x86, so we cant do it always */ if (ins->inst_c0 == 0 && (!ins->next || (ins->next && INST_IGNORES_CFLAGS (ins->next->opcode)))) { MonoInst *ins2; ins->opcode = OP_IXOR; ins->sreg1 = ins->dreg; ins->sreg2 = ins->dreg; /* * Convert succeeding STORE_MEMBASE_IMM 0 ins to STORE_MEMBASE_REG * since it takes 3 bytes instead of 7. */ for (ins2 = mono_inst_next (ins, FILTER_IL_SEQ_POINT); ins2; ins2 = ins2->next) { if ((ins2->opcode == OP_STORE_MEMBASE_IMM) && (ins2->inst_imm == 0)) { ins2->opcode = OP_STORE_MEMBASE_REG; ins2->sreg1 = ins->dreg; } else if ((ins2->opcode == OP_STOREI4_MEMBASE_IMM) && (ins2->inst_imm == 0)) { ins2->opcode = OP_STOREI4_MEMBASE_REG; ins2->sreg1 = ins->dreg; } else if ((ins2->opcode == OP_STOREI1_MEMBASE_IMM) || (ins2->opcode == OP_STOREI2_MEMBASE_IMM)) { /* Continue iteration */ } else break; } } break; case OP_IADD_IMM: case OP_ADD_IMM: if ((ins->inst_imm == 1) && (ins->dreg == ins->sreg1)) ins->opcode = OP_X86_INC_REG; break; case OP_ISUB_IMM: case OP_SUB_IMM: if ((ins->inst_imm == 1) && (ins->dreg == ins->sreg1)) ins->opcode = OP_X86_DEC_REG; break; } mono_peephole_ins (bb, ins); } } /* * mono_arch_lowering_pass: * * Converts complex opcodes into simpler ones so that each IR instruction * corresponds to one machine instruction. */ void mono_arch_lowering_pass (MonoCompile *cfg, MonoBasicBlock *bb) { MonoInst *ins, *next; /* * FIXME: Need to add more instructions, but the current machine * description can't model some parts of the composite instructions like * cdq. */ MONO_BB_FOR_EACH_INS_SAFE (bb, next, ins) { switch (ins->opcode) { case OP_IREM_IMM: case OP_IDIV_IMM: case OP_IDIV_UN_IMM: case OP_IREM_UN_IMM: /* * Keep the cases where we could generated optimized code, otherwise convert * to the non-imm variant. */ if ((ins->opcode == OP_IREM_IMM) && mono_is_power_of_two (ins->inst_imm) >= 0) break; mono_decompose_op_imm (cfg, bb, ins); break; default: break; } } bb->max_vreg = cfg->next_vreg; } static const int branch_cc_table [] = { X86_CC_EQ, X86_CC_GE, X86_CC_GT, X86_CC_LE, X86_CC_LT, X86_CC_NE, X86_CC_GE, X86_CC_GT, X86_CC_LE, X86_CC_LT, X86_CC_O, X86_CC_NO, X86_CC_C, X86_CC_NC }; /* Maps CMP_... constants to X86_CC_... constants */ static const int cc_table [] = { X86_CC_EQ, X86_CC_NE, X86_CC_LE, X86_CC_GE, X86_CC_LT, X86_CC_GT, X86_CC_LE, X86_CC_GE, X86_CC_LT, X86_CC_GT }; static const int cc_signed_table [] = { TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE }; static unsigned char* emit_float_to_int (MonoCompile *cfg, guchar *code, int dreg, int size, gboolean is_signed) { #define XMM_TEMP_REG 0 /*This SSE2 optimization must not be done which OPT_SIMD in place as it clobbers xmm0.*/ /*The xmm pass decomposes OP_FCONV_ ops anyway anyway.*/ if (cfg->opt & MONO_OPT_SSE2 && size < 8 && !(cfg->opt & MONO_OPT_SIMD)) { /* optimize by assigning a local var for this use so we avoid * the stack manipulations */ x86_alu_reg_imm (code, X86_SUB, X86_ESP, 8); x86_fst_membase (code, X86_ESP, 0, TRUE, TRUE); x86_movsd_reg_membase (code, XMM_TEMP_REG, X86_ESP, 0); x86_cvttsd2si (code, dreg, XMM_TEMP_REG); x86_alu_reg_imm (code, X86_ADD, X86_ESP, 8); if (size == 1) x86_widen_reg (code, dreg, dreg, is_signed, FALSE); else if (size == 2) x86_widen_reg (code, dreg, dreg, is_signed, TRUE); return code; } x86_alu_reg_imm (code, X86_SUB, X86_ESP, 4); x86_fnstcw_membase(code, X86_ESP, 0); x86_mov_reg_membase (code, dreg, X86_ESP, 0, 2); x86_alu_reg_imm (code, X86_OR, dreg, 0xc00); x86_mov_membase_reg (code, X86_ESP, 2, dreg, 2); x86_fldcw_membase (code, X86_ESP, 2); if (size == 8) { x86_alu_reg_imm (code, X86_SUB, X86_ESP, 8); x86_fist_pop_membase (code, X86_ESP, 0, TRUE); x86_pop_reg (code, dreg); /* FIXME: need the high register * x86_pop_reg (code, dreg_high); */ } else { x86_push_reg (code, X86_EAX); // SP = SP - 4 x86_fist_pop_membase (code, X86_ESP, 0, FALSE); x86_pop_reg (code, dreg); } x86_fldcw_membase (code, X86_ESP, 0); x86_alu_reg_imm (code, X86_ADD, X86_ESP, 4); if (size == 1) x86_widen_reg (code, dreg, dreg, is_signed, FALSE); else if (size == 2) x86_widen_reg (code, dreg, dreg, is_signed, TRUE); return code; } static unsigned char* mono_emit_stack_alloc (MonoCompile *cfg, guchar *code, MonoInst* tree) { int sreg = tree->sreg1; int need_touch = FALSE; #if defined(TARGET_WIN32) || defined(MONO_ARCH_SIGSEGV_ON_ALTSTACK) need_touch = TRUE; #endif if (need_touch) { guint8* br[5]; /* * Under Windows: * If requested stack size is larger than one page, * perform stack-touch operation */ /* * Generate stack probe code. * Under Windows, it is necessary to allocate one page at a time, * "touching" stack after each successful sub-allocation. This is * because of the way stack growth is implemented - there is a * guard page before the lowest stack page that is currently commited. * Stack normally grows sequentially so OS traps access to the * guard page and commits more pages when needed. */ x86_test_reg_imm (code, sreg, ~0xFFF); br[0] = code; x86_branch8 (code, X86_CC_Z, 0, FALSE); br[2] = code; /* loop */ x86_alu_reg_imm (code, X86_SUB, X86_ESP, 0x1000); x86_test_membase_reg (code, X86_ESP, 0, X86_ESP); /* * By the end of the loop, sreg2 is smaller than 0x1000, so the init routine * that follows only initializes the last part of the area. */ /* Same as the init code below with size==0x1000 */ if (tree->flags & MONO_INST_INIT) { x86_push_reg (code, X86_EAX); x86_push_reg (code, X86_ECX); x86_push_reg (code, X86_EDI); x86_mov_reg_imm (code, X86_ECX, (0x1000 >> 2)); x86_alu_reg_reg (code, X86_XOR, X86_EAX, X86_EAX); if (cfg->param_area) x86_lea_membase (code, X86_EDI, X86_ESP, 12 + ALIGN_TO (cfg->param_area, MONO_ARCH_FRAME_ALIGNMENT)); else x86_lea_membase (code, X86_EDI, X86_ESP, 12); x86_cld (code); x86_prefix (code, X86_REP_PREFIX); x86_stosl (code); x86_pop_reg (code, X86_EDI); x86_pop_reg (code, X86_ECX); x86_pop_reg (code, X86_EAX); } x86_alu_reg_imm (code, X86_SUB, sreg, 0x1000); x86_alu_reg_imm (code, X86_CMP, sreg, 0x1000); br[3] = code; x86_branch8 (code, X86_CC_AE, 0, FALSE); x86_patch (br[3], br[2]); x86_test_reg_reg (code, sreg, sreg); br[4] = code; x86_branch8 (code, X86_CC_Z, 0, FALSE); x86_alu_reg_reg (code, X86_SUB, X86_ESP, sreg); br[1] = code; x86_jump8 (code, 0); x86_patch (br[0], code); x86_alu_reg_reg (code, X86_SUB, X86_ESP, sreg); x86_patch (br[1], code); x86_patch (br[4], code); } else x86_alu_reg_reg (code, X86_SUB, X86_ESP, tree->sreg1); if (tree->flags & MONO_INST_INIT) { int offset = 0; if (tree->dreg != X86_EAX && sreg != X86_EAX) { x86_push_reg (code, X86_EAX); offset += 4; } if (tree->dreg != X86_ECX && sreg != X86_ECX) { x86_push_reg (code, X86_ECX); offset += 4; } if (tree->dreg != X86_EDI && sreg != X86_EDI) { x86_push_reg (code, X86_EDI); offset += 4; } x86_shift_reg_imm (code, X86_SHR, sreg, 2); if (sreg != X86_ECX) x86_mov_reg_reg (code, X86_ECX, sreg, 4); x86_alu_reg_reg (code, X86_XOR, X86_EAX, X86_EAX); if (cfg->param_area) x86_lea_membase (code, X86_EDI, X86_ESP, offset + ALIGN_TO (cfg->param_area, MONO_ARCH_FRAME_ALIGNMENT)); else x86_lea_membase (code, X86_EDI, X86_ESP, offset); x86_cld (code); x86_prefix (code, X86_REP_PREFIX); x86_stosl (code); if (tree->dreg != X86_EDI && sreg != X86_EDI) x86_pop_reg (code, X86_EDI); if (tree->dreg != X86_ECX && sreg != X86_ECX) x86_pop_reg (code, X86_ECX); if (tree->dreg != X86_EAX && sreg != X86_EAX) x86_pop_reg (code, X86_EAX); } return code; } static guint8* emit_move_return_value (MonoCompile *cfg, MonoInst *ins, guint8 *code) { /* Move return value to the target register */ switch (ins->opcode) { case OP_CALL: case OP_CALL_REG: case OP_CALL_MEMBASE: if (ins->dreg != X86_EAX) x86_mov_reg_reg (code, ins->dreg, X86_EAX, 4); break; default: break; } return code; } #ifdef __APPLE__ static int tls_gs_offset; #endif gboolean mono_x86_have_tls_get (void) { #ifdef TARGET_MACH static gboolean have_tls_get = FALSE; static gboolean inited = FALSE; if (inited) return have_tls_get; #ifdef MONO_HAVE_FAST_TLS guint32 *ins; ins = (guint32*)pthread_getspecific; /* * We're looking for these two instructions: * * mov 0x4(%esp),%eax * mov %gs:[offset](,%eax,4),%eax */ have_tls_get = ins [0] == 0x0424448b && ins [1] == 0x85048b65; tls_gs_offset = ins [2]; #endif inited = TRUE; return have_tls_get; #elif defined(TARGET_ANDROID) return FALSE; #else return TRUE; #endif } static guint8* mono_x86_emit_tls_set (guint8* code, int sreg, int tls_offset) { #if defined(__APPLE__) x86_prefix (code, X86_GS_PREFIX); x86_mov_mem_reg (code, tls_gs_offset + (tls_offset * 4), sreg, 4); #elif defined(TARGET_WIN32) g_assert_not_reached (); #else x86_prefix (code, X86_GS_PREFIX); x86_mov_mem_reg (code, tls_offset, sreg, 4); #endif return code; } /* * mono_x86_emit_tls_get: * @code: buffer to store code to * @dreg: hard register where to place the result * @tls_offset: offset info * * mono_x86_emit_tls_get emits in @code the native code that puts in * the dreg register the item in the thread local storage identified * by tls_offset. * * Returns: a pointer to the end of the stored code */ guint8* mono_x86_emit_tls_get (guint8* code, int dreg, int tls_offset) { #if defined(__APPLE__) x86_prefix (code, X86_GS_PREFIX); x86_mov_reg_mem (code, dreg, tls_gs_offset + (tls_offset * 4), 4); #elif defined(TARGET_WIN32) /* * See the Under the Hood article in the May 1996 issue of Microsoft Systems * Journal and/or a disassembly of the TlsGet () function. */ x86_prefix (code, X86_FS_PREFIX); x86_mov_reg_mem (code, dreg, 0x18, 4); if (tls_offset < 64) { x86_mov_reg_membase (code, dreg, dreg, 3600 + (tls_offset * 4), 4); } else { guint8 *buf [16]; g_assert (tls_offset < 0x440); /* Load TEB->TlsExpansionSlots */ x86_mov_reg_membase (code, dreg, dreg, 0xf94, 4); x86_test_reg_reg (code, dreg, dreg); buf [0] = code; x86_branch (code, X86_CC_EQ, code, TRUE); x86_mov_reg_membase (code, dreg, dreg, (tls_offset * 4) - 0x100, 4); x86_patch (buf [0], code); } #else if (optimize_for_xen) { x86_prefix (code, X86_GS_PREFIX); x86_mov_reg_mem (code, dreg, 0, 4); x86_mov_reg_membase (code, dreg, dreg, tls_offset, 4); } else { x86_prefix (code, X86_GS_PREFIX); x86_mov_reg_mem (code, dreg, tls_offset, 4); } #endif return code; } static guint8* emit_tls_get_reg (guint8* code, int dreg, int offset_reg) { /* offset_reg contains a value translated by mono_arch_translate_tls_offset () */ #if defined(__APPLE__) || defined(__linux__) if (dreg != offset_reg) x86_mov_reg_reg (code, dreg, offset_reg, sizeof (mgreg_t)); x86_prefix (code, X86_GS_PREFIX); x86_mov_reg_membase (code, dreg, dreg, 0, sizeof (mgreg_t)); #else g_assert_not_reached (); #endif return code; } guint8* mono_x86_emit_tls_get_reg (guint8* code, int dreg, int offset_reg) { return emit_tls_get_reg (code, dreg, offset_reg); } static guint8* emit_tls_set_reg (guint8* code, int sreg, int offset_reg) { /* offset_reg contains a value translated by mono_arch_translate_tls_offset () */ #ifdef HOST_WIN32 g_assert_not_reached (); #elif defined(__APPLE__) || defined(__linux__) x86_prefix (code, X86_GS_PREFIX); x86_mov_membase_reg (code, offset_reg, 0, sreg, sizeof (mgreg_t)); #else g_assert_not_reached (); #endif return code; } /* * mono_arch_translate_tls_offset: * * Translate the TLS offset OFFSET computed by MONO_THREAD_VAR_OFFSET () into a format usable by OP_TLS_GET_REG/OP_TLS_SET_REG. */ int mono_arch_translate_tls_offset (int offset) { #ifdef __APPLE__ return tls_gs_offset + (offset * 4); #else return offset; #endif } /* * emit_setup_lmf: * * Emit code to initialize an LMF structure at LMF_OFFSET. */ static guint8* emit_setup_lmf (MonoCompile *cfg, guint8 *code, gint32 lmf_offset, int cfa_offset) { /* save all caller saved regs */ x86_mov_membase_reg (code, cfg->frame_reg, lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, ebx), X86_EBX, sizeof (mgreg_t)); mono_emit_unwind_op_offset (cfg, code, X86_EBX, - cfa_offset + lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, ebx)); x86_mov_membase_reg (code, cfg->frame_reg, lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, edi), X86_EDI, sizeof (mgreg_t)); mono_emit_unwind_op_offset (cfg, code, X86_EDI, - cfa_offset + lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, edi)); x86_mov_membase_reg (code, cfg->frame_reg, lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, esi), X86_ESI, sizeof (mgreg_t)); mono_emit_unwind_op_offset (cfg, code, X86_ESI, - cfa_offset + lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, esi)); x86_mov_membase_reg (code, cfg->frame_reg, lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, ebp), X86_EBP, sizeof (mgreg_t)); /* save the current IP */ if (cfg->compile_aot) { /* This pushes the current ip */ x86_call_imm (code, 0); x86_pop_reg (code, X86_EAX); } else { mono_add_patch_info (cfg, code + 1 - cfg->native_code, MONO_PATCH_INFO_IP, NULL); x86_mov_reg_imm (code, X86_EAX, 0); } x86_mov_membase_reg (code, cfg->frame_reg, lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, eip), X86_EAX, sizeof (mgreg_t)); mini_gc_set_slot_type_from_cfa (cfg, -cfa_offset + lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, eip), SLOT_NOREF); mini_gc_set_slot_type_from_cfa (cfg, -cfa_offset + lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, ebp), SLOT_NOREF); mini_gc_set_slot_type_from_cfa (cfg, -cfa_offset + lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, esi), SLOT_NOREF); mini_gc_set_slot_type_from_cfa (cfg, -cfa_offset + lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, edi), SLOT_NOREF); mini_gc_set_slot_type_from_cfa (cfg, -cfa_offset + lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, ebx), SLOT_NOREF); mini_gc_set_slot_type_from_cfa (cfg, -cfa_offset + lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, esp), SLOT_NOREF); mini_gc_set_slot_type_from_cfa (cfg, -cfa_offset + lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, method), SLOT_NOREF); mini_gc_set_slot_type_from_cfa (cfg, -cfa_offset + lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, lmf_addr), SLOT_NOREF); mini_gc_set_slot_type_from_cfa (cfg, -cfa_offset + lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, previous_lmf), SLOT_NOREF); return code; } #define REAL_PRINT_REG(text,reg) \ mono_assert (reg >= 0); \ x86_push_reg (code, X86_EAX); \ x86_push_reg (code, X86_EDX); \ x86_push_reg (code, X86_ECX); \ x86_push_reg (code, reg); \ x86_push_imm (code, reg); \ x86_push_imm (code, text " %d %p\n"); \ x86_mov_reg_imm (code, X86_EAX, printf); \ x86_call_reg (code, X86_EAX); \ x86_alu_reg_imm (code, X86_ADD, X86_ESP, 3*4); \ x86_pop_reg (code, X86_ECX); \ x86_pop_reg (code, X86_EDX); \ x86_pop_reg (code, X86_EAX); /* REAL_PRINT_REG does not appear to be used, and was not adapted to work with Native Client. */ #ifdef __native__client_codegen__ #define REAL_PRINT_REG(text, reg) g_assert_not_reached() #endif /* benchmark and set based on cpu */ #define LOOP_ALIGNMENT 8 #define bb_is_loop_start(bb) ((bb)->loop_body_start && (bb)->nesting) #ifndef DISABLE_JIT void mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb) { MonoInst *ins; MonoCallInst *call; guint offset; guint8 *code = cfg->native_code + cfg->code_len; int max_len, cpos; if (cfg->opt & MONO_OPT_LOOP) { int pad, align = LOOP_ALIGNMENT; /* set alignment depending on cpu */ if (bb_is_loop_start (bb) && (pad = (cfg->code_len & (align - 1)))) { pad = align - pad; /*g_print ("adding %d pad at %x to loop in %s\n", pad, cfg->code_len, cfg->method->name);*/ x86_padding (code, pad); cfg->code_len += pad; bb->native_offset = cfg->code_len; } } #ifdef __native_client_codegen__ { /* For Native Client, all indirect call/jump targets must be */ /* 32-byte aligned. Exception handler blocks are jumped to */ /* indirectly as well. */ gboolean bb_needs_alignment = (bb->flags & BB_INDIRECT_JUMP_TARGET) || (bb->flags & BB_EXCEPTION_HANDLER); /* if ((cfg->code_len & kNaClAlignmentMask) != 0) { */ if ( bb_needs_alignment && ((cfg->code_len & kNaClAlignmentMask) != 0)) { int pad = kNaClAlignment - (cfg->code_len & kNaClAlignmentMask); if (pad != kNaClAlignment) code = mono_arch_nacl_pad(code, pad); cfg->code_len += pad; bb->native_offset = cfg->code_len; } } #endif /* __native_client_codegen__ */ if (cfg->verbose_level > 2) g_print ("Basic block %d starting at offset 0x%x\n", bb->block_num, bb->native_offset); cpos = bb->max_offset; if ((cfg->prof_options & MONO_PROFILE_COVERAGE) && cfg->coverage_info) { MonoProfileCoverageInfo *cov = cfg->coverage_info; g_assert (!cfg->compile_aot); cpos += 6; cov->data [bb->dfn].cil_code = bb->cil_code; /* this is not thread save, but good enough */ x86_inc_mem (code, &cov->data [bb->dfn].count); } offset = code - cfg->native_code; mono_debug_open_block (cfg, bb, offset); if (mono_break_at_bb_method && mono_method_desc_full_match (mono_break_at_bb_method, cfg->method) && bb->block_num == mono_break_at_bb_bb_num) x86_breakpoint (code); MONO_BB_FOR_EACH_INS (bb, ins) { offset = code - cfg->native_code; max_len = ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN]; #define EXTRA_CODE_SPACE (NACL_SIZE (16, 16 + kNaClAlignment)) if (G_UNLIKELY (offset > (cfg->code_size - max_len - EXTRA_CODE_SPACE))) { cfg->code_size *= 2; cfg->native_code = mono_realloc_native_code(cfg); code = cfg->native_code + offset; cfg->stat_code_reallocs++; } if (cfg->debug_info) mono_debug_record_line_number (cfg, ins, offset); switch (ins->opcode) { case OP_BIGMUL: x86_mul_reg (code, ins->sreg2, TRUE); break; case OP_BIGMUL_UN: x86_mul_reg (code, ins->sreg2, FALSE); break; case OP_X86_SETEQ_MEMBASE: case OP_X86_SETNE_MEMBASE: x86_set_membase (code, ins->opcode == OP_X86_SETEQ_MEMBASE ? X86_CC_EQ : X86_CC_NE, ins->inst_basereg, ins->inst_offset, TRUE); break; case OP_STOREI1_MEMBASE_IMM: x86_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 1); break; case OP_STOREI2_MEMBASE_IMM: x86_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 2); break; case OP_STORE_MEMBASE_IMM: case OP_STOREI4_MEMBASE_IMM: x86_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 4); break; case OP_STOREI1_MEMBASE_REG: x86_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 1); break; case OP_STOREI2_MEMBASE_REG: x86_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 2); break; case OP_STORE_MEMBASE_REG: case OP_STOREI4_MEMBASE_REG: x86_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 4); break; case OP_STORE_MEM_IMM: x86_mov_mem_imm (code, ins->inst_p0, ins->inst_c0, 4); break; case OP_LOADU4_MEM: x86_mov_reg_mem (code, ins->dreg, ins->inst_imm, 4); break; case OP_LOAD_MEM: case OP_LOADI4_MEM: /* These are created by the cprop pass so they use inst_imm as the source */ x86_mov_reg_mem (code, ins->dreg, ins->inst_imm, 4); break; case OP_LOADU1_MEM: x86_widen_mem (code, ins->dreg, ins->inst_imm, FALSE, FALSE); break; case OP_LOADU2_MEM: x86_widen_mem (code, ins->dreg, ins->inst_imm, FALSE, TRUE); break; case OP_LOAD_MEMBASE: case OP_LOADI4_MEMBASE: case OP_LOADU4_MEMBASE: x86_mov_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, 4); break; case OP_LOADU1_MEMBASE: x86_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, FALSE, FALSE); break; case OP_LOADI1_MEMBASE: x86_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, TRUE, FALSE); break; case OP_LOADU2_MEMBASE: x86_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, FALSE, TRUE); break; case OP_LOADI2_MEMBASE: x86_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, TRUE, TRUE); break; case OP_ICONV_TO_I1: case OP_SEXT_I1: x86_widen_reg (code, ins->dreg, ins->sreg1, TRUE, FALSE); break; case OP_ICONV_TO_I2: case OP_SEXT_I2: x86_widen_reg (code, ins->dreg, ins->sreg1, TRUE, TRUE); break; case OP_ICONV_TO_U1: x86_widen_reg (code, ins->dreg, ins->sreg1, FALSE, FALSE); break; case OP_ICONV_TO_U2: x86_widen_reg (code, ins->dreg, ins->sreg1, FALSE, TRUE); break; case OP_COMPARE: case OP_ICOMPARE: x86_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2); break; case OP_COMPARE_IMM: case OP_ICOMPARE_IMM: x86_alu_reg_imm (code, X86_CMP, ins->sreg1, ins->inst_imm); break; case OP_X86_COMPARE_MEMBASE_REG: x86_alu_membase_reg (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->sreg2); break; case OP_X86_COMPARE_MEMBASE_IMM: x86_alu_membase_imm (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm); break; case OP_X86_COMPARE_MEMBASE8_IMM: x86_alu_membase8_imm (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm); break; case OP_X86_COMPARE_REG_MEMBASE: x86_alu_reg_membase (code, X86_CMP, ins->sreg1, ins->sreg2, ins->inst_offset); break; case OP_X86_COMPARE_MEM_IMM: x86_alu_mem_imm (code, X86_CMP, ins->inst_offset, ins->inst_imm); break; case OP_X86_TEST_NULL: x86_test_reg_reg (code, ins->sreg1, ins->sreg1); break; case OP_X86_ADD_MEMBASE_IMM: x86_alu_membase_imm (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->inst_imm); break; case OP_X86_ADD_REG_MEMBASE: x86_alu_reg_membase (code, X86_ADD, ins->sreg1, ins->sreg2, ins->inst_offset); break; case OP_X86_SUB_MEMBASE_IMM: x86_alu_membase_imm (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->inst_imm); break; case OP_X86_SUB_REG_MEMBASE: x86_alu_reg_membase (code, X86_SUB, ins->sreg1, ins->sreg2, ins->inst_offset); break; case OP_X86_AND_MEMBASE_IMM: x86_alu_membase_imm (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->inst_imm); break; case OP_X86_OR_MEMBASE_IMM: x86_alu_membase_imm (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->inst_imm); break; case OP_X86_XOR_MEMBASE_IMM: x86_alu_membase_imm (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->inst_imm); break; case OP_X86_ADD_MEMBASE_REG: x86_alu_membase_reg (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->sreg2); break; case OP_X86_SUB_MEMBASE_REG: x86_alu_membase_reg (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->sreg2); break; case OP_X86_AND_MEMBASE_REG: x86_alu_membase_reg (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->sreg2); break; case OP_X86_OR_MEMBASE_REG: x86_alu_membase_reg (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->sreg2); break; case OP_X86_XOR_MEMBASE_REG: x86_alu_membase_reg (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->sreg2); break; case OP_X86_INC_MEMBASE: x86_inc_membase (code, ins->inst_basereg, ins->inst_offset); break; case OP_X86_INC_REG: x86_inc_reg (code, ins->dreg); break; case OP_X86_DEC_MEMBASE: x86_dec_membase (code, ins->inst_basereg, ins->inst_offset); break; case OP_X86_DEC_REG: x86_dec_reg (code, ins->dreg); break; case OP_X86_MUL_REG_MEMBASE: x86_imul_reg_membase (code, ins->sreg1, ins->sreg2, ins->inst_offset); break; case OP_X86_AND_REG_MEMBASE: x86_alu_reg_membase (code, X86_AND, ins->sreg1, ins->sreg2, ins->inst_offset); break; case OP_X86_OR_REG_MEMBASE: x86_alu_reg_membase (code, X86_OR, ins->sreg1, ins->sreg2, ins->inst_offset); break; case OP_X86_XOR_REG_MEMBASE: x86_alu_reg_membase (code, X86_XOR, ins->sreg1, ins->sreg2, ins->inst_offset); break; case OP_BREAK: x86_breakpoint (code); break; case OP_RELAXED_NOP: x86_prefix (code, X86_REP_PREFIX); x86_nop (code); break; case OP_HARD_NOP: x86_nop (code); break; case OP_NOP: case OP_DUMMY_USE: case OP_DUMMY_STORE: case OP_DUMMY_ICONST: case OP_DUMMY_R8CONST: case OP_NOT_REACHED: case OP_NOT_NULL: break; case OP_IL_SEQ_POINT: mono_add_seq_point (cfg, bb, ins, code - cfg->native_code); break; case OP_SEQ_POINT: { int i; if (cfg->compile_aot) NOT_IMPLEMENTED; /* Have to use ecx as a temp reg since this can occur after OP_SETRET */ /* * Read from the single stepping trigger page. This will cause a * SIGSEGV when single stepping is enabled. * We do this _before_ the breakpoint, so single stepping after * a breakpoint is hit will step to the next IL offset. */ if (ins->flags & MONO_INST_SINGLE_STEP_LOC) { MonoInst *var = cfg->arch.ss_tramp_var; guint8 *br [1]; g_assert (var); g_assert (var->opcode == OP_REGOFFSET); /* Load ss_tramp_var */ /* This is equal to &ss_trampoline */ x86_mov_reg_membase (code, X86_ECX, var->inst_basereg, var->inst_offset, sizeof (mgreg_t)); x86_alu_membase_imm (code, X86_CMP, X86_ECX, 0, 0); br[0] = code; x86_branch8 (code, X86_CC_EQ, 0, FALSE); x86_call_membase (code, X86_ECX, 0); x86_patch (br [0], code); } /* * Many parts of sdb depend on the ip after the single step trampoline call to be equal to the seq point offset. * This means we have to put the loading of bp_tramp_var after the offset. */ mono_add_seq_point (cfg, bb, ins, code - cfg->native_code); MonoInst *var = cfg->arch.bp_tramp_var; g_assert (var); g_assert (var->opcode == OP_REGOFFSET); /* Load the address of the bp trampoline */ /* This needs to be constant size */ guint8 *start = code; x86_mov_reg_membase (code, X86_ECX, var->inst_basereg, var->inst_offset, 4); if (code < start + OP_SEQ_POINT_BP_OFFSET) { int size = start + OP_SEQ_POINT_BP_OFFSET - code; x86_padding (code, size); } /* * A placeholder for a possible breakpoint inserted by * mono_arch_set_breakpoint (). */ for (i = 0; i < 2; ++i) x86_nop (code); /* * Add an additional nop so skipping the bp doesn't cause the ip to point * to another IL offset. */ x86_nop (code); break; } case OP_ADDCC: case OP_IADDCC: case OP_IADD: x86_alu_reg_reg (code, X86_ADD, ins->sreg1, ins->sreg2); break; case OP_ADC: case OP_IADC: x86_alu_reg_reg (code, X86_ADC, ins->sreg1, ins->sreg2); break; case OP_ADDCC_IMM: case OP_ADD_IMM: case OP_IADD_IMM: x86_alu_reg_imm (code, X86_ADD, ins->dreg, ins->inst_imm); break; case OP_ADC_IMM: case OP_IADC_IMM: x86_alu_reg_imm (code, X86_ADC, ins->dreg, ins->inst_imm); break; case OP_SUBCC: case OP_ISUBCC: case OP_ISUB: x86_alu_reg_reg (code, X86_SUB, ins->sreg1, ins->sreg2); break; case OP_SBB: case OP_ISBB: x86_alu_reg_reg (code, X86_SBB, ins->sreg1, ins->sreg2); break; case OP_SUBCC_IMM: case OP_SUB_IMM: case OP_ISUB_IMM: x86_alu_reg_imm (code, X86_SUB, ins->dreg, ins->inst_imm); break; case OP_SBB_IMM: case OP_ISBB_IMM: x86_alu_reg_imm (code, X86_SBB, ins->dreg, ins->inst_imm); break; case OP_IAND: x86_alu_reg_reg (code, X86_AND, ins->sreg1, ins->sreg2); break; case OP_AND_IMM: case OP_IAND_IMM: x86_alu_reg_imm (code, X86_AND, ins->sreg1, ins->inst_imm); break; case OP_IDIV: case OP_IREM: #if defined( __native_client_codegen__ ) x86_alu_reg_imm (code, X86_CMP, ins->sreg2, 0); EMIT_COND_SYSTEM_EXCEPTION (X86_CC_EQ, TRUE, "DivideByZeroException"); #endif /* * The code is the same for div/rem, the allocator will allocate dreg * to RAX/RDX as appropriate. */ if (ins->sreg2 == X86_EDX) { /* cdq clobbers this */ x86_push_reg (code, ins->sreg2); x86_cdq (code); x86_div_membase (code, X86_ESP, 0, TRUE); x86_alu_reg_imm (code, X86_ADD, X86_ESP, 4); } else { x86_cdq (code); x86_div_reg (code, ins->sreg2, TRUE); } break; case OP_IDIV_UN: case OP_IREM_UN: #if defined( __native_client_codegen__ ) x86_alu_reg_imm (code, X86_CMP, ins->sreg2, 0); EMIT_COND_SYSTEM_EXCEPTION (X86_CC_EQ, TRUE, "DivideByZeroException"); #endif if (ins->sreg2 == X86_EDX) { x86_push_reg (code, ins->sreg2); x86_alu_reg_reg (code, X86_XOR, X86_EDX, X86_EDX); x86_div_membase (code, X86_ESP, 0, FALSE); x86_alu_reg_imm (code, X86_ADD, X86_ESP, 4); } else { x86_alu_reg_reg (code, X86_XOR, X86_EDX, X86_EDX); x86_div_reg (code, ins->sreg2, FALSE); } break; case OP_DIV_IMM: #if defined( __native_client_codegen__ ) if (ins->inst_imm == 0) { mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_EXC, "DivideByZeroException"); x86_jump32 (code, 0); break; } #endif x86_mov_reg_imm (code, ins->sreg2, ins->inst_imm); x86_cdq (code); x86_div_reg (code, ins->sreg2, TRUE); break; case OP_IREM_IMM: { int power = mono_is_power_of_two (ins->inst_imm); g_assert (ins->sreg1 == X86_EAX); g_assert (ins->dreg == X86_EAX); g_assert (power >= 0); if (power == 1) { /* Based on http://compilers.iecc.com/comparch/article/93-04-079 */ x86_cdq (code); x86_alu_reg_imm (code, X86_AND, X86_EAX, 1); /* * If the divident is >= 0, this does not nothing. If it is positive, it * it transforms %eax=0 into %eax=0, and %eax=1 into %eax=-1. */ x86_alu_reg_reg (code, X86_XOR, X86_EAX, X86_EDX); x86_alu_reg_reg (code, X86_SUB, X86_EAX, X86_EDX); } else if (power == 0) { x86_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg); } else { /* Based on gcc code */ /* Add compensation for negative dividents */ x86_cdq (code); x86_shift_reg_imm (code, X86_SHR, X86_EDX, 32 - power); x86_alu_reg_reg (code, X86_ADD, X86_EAX, X86_EDX); /* Compute remainder */ x86_alu_reg_imm (code, X86_AND, X86_EAX, (1 << power) - 1); /* Remove compensation */ x86_alu_reg_reg (code, X86_SUB, X86_EAX, X86_EDX); } break; } case OP_IOR: x86_alu_reg_reg (code, X86_OR, ins->sreg1, ins->sreg2); break; case OP_OR_IMM: case OP_IOR_IMM: x86_alu_reg_imm (code, X86_OR, ins->sreg1, ins->inst_imm); break; case OP_IXOR: x86_alu_reg_reg (code, X86_XOR, ins->sreg1, ins->sreg2); break; case OP_XOR_IMM: case OP_IXOR_IMM: x86_alu_reg_imm (code, X86_XOR, ins->sreg1, ins->inst_imm); break; case OP_ISHL: g_assert (ins->sreg2 == X86_ECX); x86_shift_reg (code, X86_SHL, ins->dreg); break; case OP_ISHR: g_assert (ins->sreg2 == X86_ECX); x86_shift_reg (code, X86_SAR, ins->dreg); break; case OP_SHR_IMM: case OP_ISHR_IMM: x86_shift_reg_imm (code, X86_SAR, ins->dreg, ins->inst_imm); break; case OP_SHR_UN_IMM: case OP_ISHR_UN_IMM: x86_shift_reg_imm (code, X86_SHR, ins->dreg, ins->inst_imm); break; case OP_ISHR_UN: g_assert (ins->sreg2 == X86_ECX); x86_shift_reg (code, X86_SHR, ins->dreg); break; case OP_SHL_IMM: case OP_ISHL_IMM: x86_shift_reg_imm (code, X86_SHL, ins->dreg, ins->inst_imm); break; case OP_LSHL: { guint8 *jump_to_end; /* handle shifts below 32 bits */ x86_shld_reg (code, ins->backend.reg3, ins->sreg1); x86_shift_reg (code, X86_SHL, ins->sreg1); x86_test_reg_imm (code, X86_ECX, 32); jump_to_end = code; x86_branch8 (code, X86_CC_EQ, 0, TRUE); /* handle shift over 32 bit */ x86_mov_reg_reg (code, ins->backend.reg3, ins->sreg1, 4); x86_clear_reg (code, ins->sreg1); x86_patch (jump_to_end, code); } break; case OP_LSHR: { guint8 *jump_to_end; /* handle shifts below 32 bits */ x86_shrd_reg (code, ins->sreg1, ins->backend.reg3); x86_shift_reg (code, X86_SAR, ins->backend.reg3); x86_test_reg_imm (code, X86_ECX, 32); jump_to_end = code; x86_branch8 (code, X86_CC_EQ, 0, FALSE); /* handle shifts over 31 bits */ x86_mov_reg_reg (code, ins->sreg1, ins->backend.reg3, 4); x86_shift_reg_imm (code, X86_SAR, ins->backend.reg3, 31); x86_patch (jump_to_end, code); } break; case OP_LSHR_UN: { guint8 *jump_to_end; /* handle shifts below 32 bits */ x86_shrd_reg (code, ins->sreg1, ins->backend.reg3); x86_shift_reg (code, X86_SHR, ins->backend.reg3); x86_test_reg_imm (code, X86_ECX, 32); jump_to_end = code; x86_branch8 (code, X86_CC_EQ, 0, FALSE); /* handle shifts over 31 bits */ x86_mov_reg_reg (code, ins->sreg1, ins->backend.reg3, 4); x86_clear_reg (code, ins->backend.reg3); x86_patch (jump_to_end, code); } break; case OP_LSHL_IMM: if (ins->inst_imm >= 32) { x86_mov_reg_reg (code, ins->backend.reg3, ins->sreg1, 4); x86_clear_reg (code, ins->sreg1); x86_shift_reg_imm (code, X86_SHL, ins->backend.reg3, ins->inst_imm - 32); } else { x86_shld_reg_imm (code, ins->backend.reg3, ins->sreg1, ins->inst_imm); x86_shift_reg_imm (code, X86_SHL, ins->sreg1, ins->inst_imm); } break; case OP_LSHR_IMM: if (ins->inst_imm >= 32) { x86_mov_reg_reg (code, ins->sreg1, ins->backend.reg3, 4); x86_shift_reg_imm (code, X86_SAR, ins->backend.reg3, 0x1f); x86_shift_reg_imm (code, X86_SAR, ins->sreg1, ins->inst_imm - 32); } else { x86_shrd_reg_imm (code, ins->sreg1, ins->backend.reg3, ins->inst_imm); x86_shift_reg_imm (code, X86_SAR, ins->backend.reg3, ins->inst_imm); } break; case OP_LSHR_UN_IMM: if (ins->inst_imm >= 32) { x86_mov_reg_reg (code, ins->sreg1, ins->backend.reg3, 4); x86_clear_reg (code, ins->backend.reg3); x86_shift_reg_imm (code, X86_SHR, ins->sreg1, ins->inst_imm - 32); } else { x86_shrd_reg_imm (code, ins->sreg1, ins->backend.reg3, ins->inst_imm); x86_shift_reg_imm (code, X86_SHR, ins->backend.reg3, ins->inst_imm); } break; case OP_INOT: x86_not_reg (code, ins->sreg1); break; case OP_INEG: x86_neg_reg (code, ins->sreg1); break; case OP_IMUL: x86_imul_reg_reg (code, ins->sreg1, ins->sreg2); break; case OP_MUL_IMM: case OP_IMUL_IMM: switch (ins->inst_imm) { case 2: /* MOV r1, r2 */ /* ADD r1, r1 */ if (ins->dreg != ins->sreg1) x86_mov_reg_reg (code, ins->dreg, ins->sreg1, 4); x86_alu_reg_reg (code, X86_ADD, ins->dreg, ins->dreg); break; case 3: /* LEA r1, [r2 + r2*2] */ x86_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 1); break; case 5: /* LEA r1, [r2 + r2*4] */ x86_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2); break; case 6: /* LEA r1, [r2 + r2*2] */ /* ADD r1, r1 */ x86_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 1); x86_alu_reg_reg (code, X86_ADD, ins->dreg, ins->dreg); break; case 9: /* LEA r1, [r2 + r2*8] */ x86_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 3); break; case 10: /* LEA r1, [r2 + r2*4] */ /* ADD r1, r1 */ x86_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2); x86_alu_reg_reg (code, X86_ADD, ins->dreg, ins->dreg); break; case 12: /* LEA r1, [r2 + r2*2] */ /* SHL r1, 2 */ x86_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 1); x86_shift_reg_imm (code, X86_SHL, ins->dreg, 2); break; case 25: /* LEA r1, [r2 + r2*4] */ /* LEA r1, [r1 + r1*4] */ x86_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2); x86_lea_memindex (code, ins->dreg, ins->dreg, 0, ins->dreg, 2); break; case 100: /* LEA r1, [r2 + r2*4] */ /* SHL r1, 2 */ /* LEA r1, [r1 + r1*4] */ x86_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2); x86_shift_reg_imm (code, X86_SHL, ins->dreg, 2); x86_lea_memindex (code, ins->dreg, ins->dreg, 0, ins->dreg, 2); break; default: x86_imul_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_imm); break; } break; case OP_IMUL_OVF: x86_imul_reg_reg (code, ins->sreg1, ins->sreg2); EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException"); break; case OP_IMUL_OVF_UN: { /* the mul operation and the exception check should most likely be split */ int non_eax_reg, saved_eax = FALSE, saved_edx = FALSE; /*g_assert (ins->sreg2 == X86_EAX); g_assert (ins->dreg == X86_EAX);*/ if (ins->sreg2 == X86_EAX) { non_eax_reg = ins->sreg1; } else if (ins->sreg1 == X86_EAX) { non_eax_reg = ins->sreg2; } else { /* no need to save since we're going to store to it anyway */ if (ins->dreg != X86_EAX) { saved_eax = TRUE; x86_push_reg (code, X86_EAX); } x86_mov_reg_reg (code, X86_EAX, ins->sreg1, 4); non_eax_reg = ins->sreg2; } if (ins->dreg == X86_EDX) { if (!saved_eax) { saved_eax = TRUE; x86_push_reg (code, X86_EAX); } } else if (ins->dreg != X86_EAX) { saved_edx = TRUE; x86_push_reg (code, X86_EDX); } x86_mul_reg (code, non_eax_reg, FALSE); /* save before the check since pop and mov don't change the flags */ if (ins->dreg != X86_EAX) x86_mov_reg_reg (code, ins->dreg, X86_EAX, 4); if (saved_edx) x86_pop_reg (code, X86_EDX); if (saved_eax) x86_pop_reg (code, X86_EAX); EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException"); break; } case OP_ICONST: x86_mov_reg_imm (code, ins->dreg, ins->inst_c0); break; case OP_AOTCONST: g_assert_not_reached (); mono_add_patch_info (cfg, offset, (MonoJumpInfoType)ins->inst_i1, ins->inst_p0); x86_mov_reg_imm (code, ins->dreg, 0); break; case OP_JUMP_TABLE: mono_add_patch_info (cfg, offset, (MonoJumpInfoType)ins->inst_i1, ins->inst_p0); x86_mov_reg_imm (code, ins->dreg, 0); break; case OP_LOAD_GOTADDR: g_assert (ins->dreg == MONO_ARCH_GOT_REG); code = mono_arch_emit_load_got_addr (cfg->native_code, code, cfg, NULL); break; case OP_GOT_ENTRY: mono_add_patch_info (cfg, offset, (MonoJumpInfoType)ins->inst_right->inst_i1, ins->inst_right->inst_p0); x86_mov_reg_membase (code, ins->dreg, ins->inst_basereg, 0xf0f0f0f0, 4); break; case OP_X86_PUSH_GOT_ENTRY: mono_add_patch_info (cfg, offset, (MonoJumpInfoType)ins->inst_right->inst_i1, ins->inst_right->inst_p0); x86_push_membase (code, ins->inst_basereg, 0xf0f0f0f0); break; case OP_MOVE: if (ins->dreg != ins->sreg1) x86_mov_reg_reg (code, ins->dreg, ins->sreg1, 4); break; case OP_TAILCALL: { MonoCallInst *call = (MonoCallInst*)ins; int pos = 0, i; ins->flags |= MONO_INST_GC_CALLSITE; ins->backend.pc_offset = code - cfg->native_code; /* reset offset to make max_len work */ offset = code - cfg->native_code; g_assert (!cfg->method->save_lmf); /* restore callee saved registers */ for (i = 0; i < X86_NREG; ++i) if (X86_IS_CALLEE_SAVED_REG (i) && cfg->used_int_regs & (1 << i)) pos -= 4; if (cfg->used_int_regs & (1 << X86_ESI)) { x86_mov_reg_membase (code, X86_ESI, X86_EBP, pos, 4); pos += 4; } if (cfg->used_int_regs & (1 << X86_EDI)) { x86_mov_reg_membase (code, X86_EDI, X86_EBP, pos, 4); pos += 4; } if (cfg->used_int_regs & (1 << X86_EBX)) { x86_mov_reg_membase (code, X86_EBX, X86_EBP, pos, 4); pos += 4; } /* Copy arguments on the stack to our argument area */ for (i = 0; i < call->stack_usage - call->stack_align_amount; i += 4) { x86_mov_reg_membase (code, X86_EAX, X86_ESP, i, 4); x86_mov_membase_reg (code, X86_EBP, 8 + i, X86_EAX, 4); } /* restore ESP/EBP */ x86_leave (code); offset = code - cfg->native_code; mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_METHOD_JUMP, call->method); x86_jump32 (code, 0); ins->flags |= MONO_INST_GC_CALLSITE; cfg->disable_aot = TRUE; break; } case OP_CHECK_THIS: /* ensure ins->sreg1 is not NULL * note that cmp DWORD PTR [eax], eax is one byte shorter than * cmp DWORD PTR [eax], 0 */ x86_alu_membase_reg (code, X86_CMP, ins->sreg1, 0, ins->sreg1); break; case OP_ARGLIST: { int hreg = ins->sreg1 == X86_EAX? X86_ECX: X86_EAX; x86_push_reg (code, hreg); x86_lea_membase (code, hreg, X86_EBP, cfg->sig_cookie); x86_mov_membase_reg (code, ins->sreg1, 0, hreg, 4); x86_pop_reg (code, hreg); break; } case OP_FCALL: case OP_LCALL: case OP_VCALL: case OP_VCALL2: case OP_VOIDCALL: case OP_CALL: case OP_FCALL_REG: case OP_LCALL_REG: case OP_VCALL_REG: case OP_VCALL2_REG: case OP_VOIDCALL_REG: case OP_CALL_REG: case OP_FCALL_MEMBASE: case OP_LCALL_MEMBASE: case OP_VCALL_MEMBASE: case OP_VCALL2_MEMBASE: case OP_VOIDCALL_MEMBASE: case OP_CALL_MEMBASE: { CallInfo *cinfo; call = (MonoCallInst*)ins; cinfo = (CallInfo*)call->call_info; switch (ins->opcode) { case OP_FCALL: case OP_LCALL: case OP_VCALL: case OP_VCALL2: case OP_VOIDCALL: case OP_CALL: if (ins->flags & MONO_INST_HAS_METHOD) code = emit_call (cfg, code, MONO_PATCH_INFO_METHOD, call->method); else code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, call->fptr); break; case OP_FCALL_REG: case OP_LCALL_REG: case OP_VCALL_REG: case OP_VCALL2_REG: case OP_VOIDCALL_REG: case OP_CALL_REG: x86_call_reg (code, ins->sreg1); break; case OP_FCALL_MEMBASE: case OP_LCALL_MEMBASE: case OP_VCALL_MEMBASE: case OP_VCALL2_MEMBASE: case OP_VOIDCALL_MEMBASE: case OP_CALL_MEMBASE: x86_call_membase (code, ins->sreg1, ins->inst_offset); break; default: g_assert_not_reached (); break; } ins->flags |= MONO_INST_GC_CALLSITE; ins->backend.pc_offset = code - cfg->native_code; if (cinfo->callee_stack_pop) { /* Have to compensate for the stack space popped by the callee */ x86_alu_reg_imm (code, X86_SUB, X86_ESP, cinfo->callee_stack_pop); } code = emit_move_return_value (cfg, ins, code); break; } case OP_X86_LEA: x86_lea_memindex (code, ins->dreg, ins->sreg1, ins->inst_imm, ins->sreg2, ins->backend.shift_amount); break; case OP_X86_LEA_MEMBASE: x86_lea_membase (code, ins->dreg, ins->sreg1, ins->inst_imm); break; case OP_X86_XCHG: x86_xchg_reg_reg (code, ins->sreg1, ins->sreg2, 4); break; case OP_LOCALLOC: /* keep alignment */ x86_alu_reg_imm (code, X86_ADD, ins->sreg1, MONO_ARCH_LOCALLOC_ALIGNMENT - 1); x86_alu_reg_imm (code, X86_AND, ins->sreg1, ~(MONO_ARCH_LOCALLOC_ALIGNMENT - 1)); code = mono_emit_stack_alloc (cfg, code, ins); x86_mov_reg_reg (code, ins->dreg, X86_ESP, 4); if (cfg->param_area) x86_alu_reg_imm (code, X86_ADD, ins->dreg, ALIGN_TO (cfg->param_area, MONO_ARCH_FRAME_ALIGNMENT)); break; case OP_LOCALLOC_IMM: { guint32 size = ins->inst_imm; size = (size + (MONO_ARCH_FRAME_ALIGNMENT - 1)) & ~ (MONO_ARCH_FRAME_ALIGNMENT - 1); if (ins->flags & MONO_INST_INIT) { /* FIXME: Optimize this */ x86_mov_reg_imm (code, ins->dreg, size); ins->sreg1 = ins->dreg; code = mono_emit_stack_alloc (cfg, code, ins); x86_mov_reg_reg (code, ins->dreg, X86_ESP, 4); } else { x86_alu_reg_imm (code, X86_SUB, X86_ESP, size); x86_mov_reg_reg (code, ins->dreg, X86_ESP, 4); } if (cfg->param_area) x86_alu_reg_imm (code, X86_ADD, ins->dreg, ALIGN_TO (cfg->param_area, MONO_ARCH_FRAME_ALIGNMENT)); break; } case OP_THROW: { x86_alu_reg_imm (code, X86_SUB, X86_ESP, MONO_ARCH_FRAME_ALIGNMENT - 4); x86_push_reg (code, ins->sreg1); code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, (gpointer)"mono_arch_throw_exception"); ins->flags |= MONO_INST_GC_CALLSITE; ins->backend.pc_offset = code - cfg->native_code; break; } case OP_RETHROW: { x86_alu_reg_imm (code, X86_SUB, X86_ESP, MONO_ARCH_FRAME_ALIGNMENT - 4); x86_push_reg (code, ins->sreg1); code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, (gpointer)"mono_arch_rethrow_exception"); ins->flags |= MONO_INST_GC_CALLSITE; ins->backend.pc_offset = code - cfg->native_code; break; } case OP_CALL_HANDLER: x86_alu_reg_imm (code, X86_SUB, X86_ESP, MONO_ARCH_FRAME_ALIGNMENT - 4); mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_target_bb); x86_call_imm (code, 0); mono_cfg_add_try_hole (cfg, ins->inst_eh_block, code, bb); x86_alu_reg_imm (code, X86_ADD, X86_ESP, MONO_ARCH_FRAME_ALIGNMENT - 4); break; case OP_START_HANDLER: { MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region); x86_mov_membase_reg (code, spvar->inst_basereg, spvar->inst_offset, X86_ESP, 4); if (cfg->param_area) x86_alu_reg_imm (code, X86_SUB, X86_ESP, ALIGN_TO (cfg->param_area, MONO_ARCH_FRAME_ALIGNMENT)); break; } case OP_ENDFINALLY: { MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region); x86_mov_reg_membase (code, X86_ESP, spvar->inst_basereg, spvar->inst_offset, 4); x86_ret (code); break; } case OP_ENDFILTER: { MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region); x86_mov_reg_membase (code, X86_ESP, spvar->inst_basereg, spvar->inst_offset, 4); /* The local allocator will put the result into EAX */ x86_ret (code); break; } case OP_GET_EX_OBJ: if (ins->dreg != X86_EAX) x86_mov_reg_reg (code, ins->dreg, X86_EAX, sizeof (gpointer)); break; case OP_LABEL: ins->inst_c0 = code - cfg->native_code; break; case OP_BR: if (ins->inst_target_bb->native_offset) { x86_jump_code (code, cfg->native_code + ins->inst_target_bb->native_offset); } else { mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_BB, ins->inst_target_bb); if ((cfg->opt & MONO_OPT_BRANCH) && x86_is_imm8 (ins->inst_target_bb->max_offset - cpos)) x86_jump8 (code, 0); else x86_jump32 (code, 0); } break; case OP_BR_REG: x86_jump_reg (code, ins->sreg1); break; case OP_ICNEQ: case OP_ICGE: case OP_ICLE: case OP_ICGE_UN: case OP_ICLE_UN: case OP_CEQ: case OP_CLT: case OP_CLT_UN: case OP_CGT: case OP_CGT_UN: case OP_CNE: case OP_ICEQ: case OP_ICLT: case OP_ICLT_UN: case OP_ICGT: case OP_ICGT_UN: x86_set_reg (code, cc_table [mono_opcode_to_cond (ins->opcode)], ins->dreg, cc_signed_table [mono_opcode_to_cond (ins->opcode)]); x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE); break; case OP_COND_EXC_EQ: case OP_COND_EXC_NE_UN: case OP_COND_EXC_LT: case OP_COND_EXC_LT_UN: case OP_COND_EXC_GT: case OP_COND_EXC_GT_UN: case OP_COND_EXC_GE: case OP_COND_EXC_GE_UN: case OP_COND_EXC_LE: case OP_COND_EXC_LE_UN: case OP_COND_EXC_IEQ: case OP_COND_EXC_INE_UN: case OP_COND_EXC_ILT: case OP_COND_EXC_ILT_UN: case OP_COND_EXC_IGT: case OP_COND_EXC_IGT_UN: case OP_COND_EXC_IGE: case OP_COND_EXC_IGE_UN: case OP_COND_EXC_ILE: case OP_COND_EXC_ILE_UN: EMIT_COND_SYSTEM_EXCEPTION (cc_table [mono_opcode_to_cond (ins->opcode)], cc_signed_table [mono_opcode_to_cond (ins->opcode)], ins->inst_p1); break; case OP_COND_EXC_OV: case OP_COND_EXC_NO: case OP_COND_EXC_C: case OP_COND_EXC_NC: EMIT_COND_SYSTEM_EXCEPTION (branch_cc_table [ins->opcode - OP_COND_EXC_EQ], (ins->opcode < OP_COND_EXC_NE_UN), ins->inst_p1); break; case OP_COND_EXC_IOV: case OP_COND_EXC_INO: case OP_COND_EXC_IC: case OP_COND_EXC_INC: EMIT_COND_SYSTEM_EXCEPTION (branch_cc_table [ins->opcode - OP_COND_EXC_IEQ], (ins->opcode < OP_COND_EXC_INE_UN), ins->inst_p1); break; case OP_IBEQ: case OP_IBNE_UN: case OP_IBLT: case OP_IBLT_UN: case OP_IBGT: case OP_IBGT_UN: case OP_IBGE: case OP_IBGE_UN: case OP_IBLE: case OP_IBLE_UN: EMIT_COND_BRANCH (ins, cc_table [mono_opcode_to_cond (ins->opcode)], cc_signed_table [mono_opcode_to_cond (ins->opcode)]); break; case OP_CMOV_IEQ: case OP_CMOV_IGE: case OP_CMOV_IGT: case OP_CMOV_ILE: case OP_CMOV_ILT: case OP_CMOV_INE_UN: case OP_CMOV_IGE_UN: case OP_CMOV_IGT_UN: case OP_CMOV_ILE_UN: case OP_CMOV_ILT_UN: g_assert (ins->dreg == ins->sreg1); x86_cmov_reg (code, cc_table [mono_opcode_to_cond (ins->opcode)], cc_signed_table [mono_opcode_to_cond (ins->opcode)], ins->dreg, ins->sreg2); break; /* floating point opcodes */ case OP_R8CONST: { double d = *(double *)ins->inst_p0; if ((d == 0.0) && (mono_signbit (d) == 0)) { x86_fldz (code); } else if (d == 1.0) { x86_fld1 (code); } else { if (cfg->compile_aot) { guint32 *val = (guint32*)&d; x86_push_imm (code, val [1]); x86_push_imm (code, val [0]); x86_fld_membase (code, X86_ESP, 0, TRUE); x86_alu_reg_imm (code, X86_ADD, X86_ESP, 8); } else { mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_R8, ins->inst_p0); x86_fld (code, NULL, TRUE); } } break; } case OP_R4CONST: { float f = *(float *)ins->inst_p0; if ((f == 0.0) && (mono_signbit (f) == 0)) { x86_fldz (code); } else if (f == 1.0) { x86_fld1 (code); } else { if (cfg->compile_aot) { guint32 val = *(guint32*)&f; x86_push_imm (code, val); x86_fld_membase (code, X86_ESP, 0, FALSE); x86_alu_reg_imm (code, X86_ADD, X86_ESP, 4); } else { mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_R4, ins->inst_p0); x86_fld (code, NULL, FALSE); } } break; } case OP_STORER8_MEMBASE_REG: x86_fst_membase (code, ins->inst_destbasereg, ins->inst_offset, TRUE, TRUE); break; case OP_LOADR8_MEMBASE: x86_fld_membase (code, ins->inst_basereg, ins->inst_offset, TRUE); break; case OP_STORER4_MEMBASE_REG: x86_fst_membase (code, ins->inst_destbasereg, ins->inst_offset, FALSE, TRUE); break; case OP_LOADR4_MEMBASE: x86_fld_membase (code, ins->inst_basereg, ins->inst_offset, FALSE); break; case OP_ICONV_TO_R4: x86_push_reg (code, ins->sreg1); x86_fild_membase (code, X86_ESP, 0, FALSE); /* Change precision */ x86_fst_membase (code, X86_ESP, 0, FALSE, TRUE); x86_fld_membase (code, X86_ESP, 0, FALSE); x86_alu_reg_imm (code, X86_ADD, X86_ESP, 4); break; case OP_ICONV_TO_R8: x86_push_reg (code, ins->sreg1); x86_fild_membase (code, X86_ESP, 0, FALSE); x86_alu_reg_imm (code, X86_ADD, X86_ESP, 4); break; case OP_ICONV_TO_R_UN: x86_push_imm (code, 0); x86_push_reg (code, ins->sreg1); x86_fild_membase (code, X86_ESP, 0, TRUE); x86_alu_reg_imm (code, X86_ADD, X86_ESP, 8); break; case OP_X86_FP_LOAD_I8: x86_fild_membase (code, ins->inst_basereg, ins->inst_offset, TRUE); break; case OP_X86_FP_LOAD_I4: x86_fild_membase (code, ins->inst_basereg, ins->inst_offset, FALSE); break; case OP_FCONV_TO_R4: /* Change precision */ x86_alu_reg_imm (code, X86_SUB, X86_ESP, 4); x86_fst_membase (code, X86_ESP, 0, FALSE, TRUE); x86_fld_membase (code, X86_ESP, 0, FALSE); x86_alu_reg_imm (code, X86_ADD, X86_ESP, 4); break; case OP_FCONV_TO_I1: code = emit_float_to_int (cfg, code, ins->dreg, 1, TRUE); break; case OP_FCONV_TO_U1: code = emit_float_to_int (cfg, code, ins->dreg, 1, FALSE); break; case OP_FCONV_TO_I2: code = emit_float_to_int (cfg, code, ins->dreg, 2, TRUE); break; case OP_FCONV_TO_U2: code = emit_float_to_int (cfg, code, ins->dreg, 2, FALSE); break; case OP_FCONV_TO_I4: case OP_FCONV_TO_I: code = emit_float_to_int (cfg, code, ins->dreg, 4, TRUE); break; case OP_FCONV_TO_I8: x86_alu_reg_imm (code, X86_SUB, X86_ESP, 4); x86_fnstcw_membase(code, X86_ESP, 0); x86_mov_reg_membase (code, ins->dreg, X86_ESP, 0, 2); x86_alu_reg_imm (code, X86_OR, ins->dreg, 0xc00); x86_mov_membase_reg (code, X86_ESP, 2, ins->dreg, 2); x86_fldcw_membase (code, X86_ESP, 2); x86_alu_reg_imm (code, X86_SUB, X86_ESP, 8); x86_fist_pop_membase (code, X86_ESP, 0, TRUE); x86_pop_reg (code, ins->dreg); x86_pop_reg (code, ins->backend.reg3); x86_fldcw_membase (code, X86_ESP, 0); x86_alu_reg_imm (code, X86_ADD, X86_ESP, 4); break; case OP_LCONV_TO_R8_2: x86_push_reg (code, ins->sreg2); x86_push_reg (code, ins->sreg1); x86_fild_membase (code, X86_ESP, 0, TRUE); /* Change precision */ x86_fst_membase (code, X86_ESP, 0, TRUE, TRUE); x86_fld_membase (code, X86_ESP, 0, TRUE); x86_alu_reg_imm (code, X86_ADD, X86_ESP, 8); break; case OP_LCONV_TO_R4_2: x86_push_reg (code, ins->sreg2); x86_push_reg (code, ins->sreg1); x86_fild_membase (code, X86_ESP, 0, TRUE); /* Change precision */ x86_fst_membase (code, X86_ESP, 0, FALSE, TRUE); x86_fld_membase (code, X86_ESP, 0, FALSE); x86_alu_reg_imm (code, X86_ADD, X86_ESP, 8); break; case OP_LCONV_TO_R_UN_2: { static guint8 mn[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0x40 }; guint8 *br; /* load 64bit integer to FP stack */ x86_push_reg (code, ins->sreg2); x86_push_reg (code, ins->sreg1); x86_fild_membase (code, X86_ESP, 0, TRUE); /* test if lreg is negative */ x86_test_reg_reg (code, ins->sreg2, ins->sreg2); br = code; x86_branch8 (code, X86_CC_GEZ, 0, TRUE); /* add correction constant mn */ if (cfg->compile_aot) { x86_push_imm (code, (((guint32)mn [9]) << 24) | ((guint32)mn [8] << 16) | ((guint32)mn [7] << 8) | ((guint32)mn [6])); x86_push_imm (code, (((guint32)mn [5]) << 24) | ((guint32)mn [4] << 16) | ((guint32)mn [3] << 8) | ((guint32)mn [2])); x86_push_imm (code, (((guint32)mn [1]) << 24) | ((guint32)mn [0] << 16)); x86_fld80_membase (code, X86_ESP, 2); x86_alu_reg_imm (code, X86_ADD, X86_ESP, 12); } else { x86_fld80_mem (code, mn); } x86_fp_op_reg (code, X86_FADD, 1, TRUE); x86_patch (br, code); /* Change precision */ x86_fst_membase (code, X86_ESP, 0, TRUE, TRUE); x86_fld_membase (code, X86_ESP, 0, TRUE); x86_alu_reg_imm (code, X86_ADD, X86_ESP, 8); break; } case OP_LCONV_TO_OVF_I: case OP_LCONV_TO_OVF_I4_2: { guint8 *br [3], *label [1]; MonoInst *tins; /* * Valid ints: 0xffffffff:8000000 to 00000000:0x7f000000 */ x86_test_reg_reg (code, ins->sreg1, ins->sreg1); /* If the low word top bit is set, see if we are negative */ br [0] = code; x86_branch8 (code, X86_CC_LT, 0, TRUE); /* We are not negative (no top bit set, check for our top word to be zero */ x86_test_reg_reg (code, ins->sreg2, ins->sreg2); br [1] = code; x86_branch8 (code, X86_CC_EQ, 0, TRUE); label [0] = code; /* throw exception */ tins = mono_branch_optimize_exception_target (cfg, bb, "OverflowException"); if (tins) { mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, tins->inst_true_bb); if ((cfg->opt & MONO_OPT_BRANCH) && x86_is_imm8 (tins->inst_true_bb->max_offset - cpos)) x86_jump8 (code, 0); else x86_jump32 (code, 0); } else { mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_EXC, "OverflowException"); x86_jump32 (code, 0); } x86_patch (br [0], code); /* our top bit is set, check that top word is 0xfffffff */ x86_alu_reg_imm (code, X86_CMP, ins->sreg2, 0xffffffff); x86_patch (br [1], code); /* nope, emit exception */ br [2] = code; x86_branch8 (code, X86_CC_NE, 0, TRUE); x86_patch (br [2], label [0]); if (ins->dreg != ins->sreg1) x86_mov_reg_reg (code, ins->dreg, ins->sreg1, 4); break; } case OP_FMOVE: /* Not needed on the fp stack */ break; case OP_MOVE_F_TO_I4: x86_fst_membase (code, ins->backend.spill_var->inst_basereg, ins->backend.spill_var->inst_offset, FALSE, TRUE); x86_mov_reg_membase (code, ins->dreg, ins->backend.spill_var->inst_basereg, ins->backend.spill_var->inst_offset, 4); break; case OP_MOVE_I4_TO_F: x86_mov_membase_reg (code, ins->backend.spill_var->inst_basereg, ins->backend.spill_var->inst_offset, ins->sreg1, 4); x86_fld_membase (code, ins->backend.spill_var->inst_basereg, ins->backend.spill_var->inst_offset, FALSE); break; case OP_FADD: x86_fp_op_reg (code, X86_FADD, 1, TRUE); break; case OP_FSUB: x86_fp_op_reg (code, X86_FSUB, 1, TRUE); break; case OP_FMUL: x86_fp_op_reg (code, X86_FMUL, 1, TRUE); break; case OP_FDIV: x86_fp_op_reg (code, X86_FDIV, 1, TRUE); break; case OP_FNEG: x86_fchs (code); break; case OP_SIN: x86_fsin (code); x86_fldz (code); x86_fp_op_reg (code, X86_FADD, 1, TRUE); break; case OP_COS: x86_fcos (code); x86_fldz (code); x86_fp_op_reg (code, X86_FADD, 1, TRUE); break; case OP_ABS: x86_fabs (code); break; case OP_TAN: { /* * it really doesn't make sense to inline all this code, * it's here just to show that things may not be as simple * as they appear. */ guchar *check_pos, *end_tan, *pop_jump; x86_push_reg (code, X86_EAX); x86_fptan (code); x86_fnstsw (code); x86_test_reg_imm (code, X86_EAX, X86_FP_C2); check_pos = code; x86_branch8 (code, X86_CC_NE, 0, FALSE); x86_fstp (code, 0); /* pop the 1.0 */ end_tan = code; x86_jump8 (code, 0); x86_fldpi (code); x86_fp_op (code, X86_FADD, 0); x86_fxch (code, 1); x86_fprem1 (code); x86_fstsw (code); x86_test_reg_imm (code, X86_EAX, X86_FP_C2); pop_jump = code; x86_branch8 (code, X86_CC_NE, 0, FALSE); x86_fstp (code, 1); x86_fptan (code); x86_patch (pop_jump, code); x86_fstp (code, 0); /* pop the 1.0 */ x86_patch (check_pos, code); x86_patch (end_tan, code); x86_fldz (code); x86_fp_op_reg (code, X86_FADD, 1, TRUE); x86_pop_reg (code, X86_EAX); break; } case OP_ATAN: x86_fld1 (code); x86_fpatan (code); x86_fldz (code); x86_fp_op_reg (code, X86_FADD, 1, TRUE); break; case OP_SQRT: x86_fsqrt (code); break; case OP_ROUND: x86_frndint (code); break; case OP_IMIN: g_assert (cfg->opt & MONO_OPT_CMOV); g_assert (ins->dreg == ins->sreg1); x86_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2); x86_cmov_reg (code, X86_CC_GT, TRUE, ins->dreg, ins->sreg2); break; case OP_IMIN_UN: g_assert (cfg->opt & MONO_OPT_CMOV); g_assert (ins->dreg == ins->sreg1); x86_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2); x86_cmov_reg (code, X86_CC_GT, FALSE, ins->dreg, ins->sreg2); break; case OP_IMAX: g_assert (cfg->opt & MONO_OPT_CMOV); g_assert (ins->dreg == ins->sreg1); x86_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2); x86_cmov_reg (code, X86_CC_LT, TRUE, ins->dreg, ins->sreg2); break; case OP_IMAX_UN: g_assert (cfg->opt & MONO_OPT_CMOV); g_assert (ins->dreg == ins->sreg1); x86_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2); x86_cmov_reg (code, X86_CC_LT, FALSE, ins->dreg, ins->sreg2); break; case OP_X86_FPOP: x86_fstp (code, 0); break; case OP_X86_FXCH: x86_fxch (code, ins->inst_imm); break; case OP_FREM: { guint8 *l1, *l2; x86_push_reg (code, X86_EAX); /* we need to exchange ST(0) with ST(1) */ x86_fxch (code, 1); /* this requires a loop, because fprem somtimes * returns a partial remainder */ l1 = code; /* looks like MS is using fprem instead of the IEEE compatible fprem1 */ /* x86_fprem1 (code); */ x86_fprem (code); x86_fnstsw (code); x86_alu_reg_imm (code, X86_AND, X86_EAX, X86_FP_C2); l2 = code; x86_branch8 (code, X86_CC_NE, 0, FALSE); x86_patch (l2, l1); /* pop result */ x86_fstp (code, 1); x86_pop_reg (code, X86_EAX); break; } case OP_FCOMPARE: if (cfg->opt & MONO_OPT_FCMOV) { x86_fcomip (code, 1); x86_fstp (code, 0); break; } /* this overwrites EAX */ EMIT_FPCOMPARE(code); x86_alu_reg_imm (code, X86_AND, X86_EAX, X86_FP_CC_MASK); break; case OP_FCEQ: case OP_FCNEQ: if (cfg->opt & MONO_OPT_FCMOV) { /* zeroing the register at the start results in * shorter and faster code (we can also remove the widening op) */ guchar *unordered_check; x86_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg); x86_fcomip (code, 1); x86_fstp (code, 0); unordered_check = code; x86_branch8 (code, X86_CC_P, 0, FALSE); if (ins->opcode == OP_FCEQ) { x86_set_reg (code, X86_CC_EQ, ins->dreg, FALSE); x86_patch (unordered_check, code); } else { guchar *jump_to_end; x86_set_reg (code, X86_CC_NE, ins->dreg, FALSE); jump_to_end = code; x86_jump8 (code, 0); x86_patch (unordered_check, code); x86_inc_reg (code, ins->dreg); x86_patch (jump_to_end, code); } break; } if (ins->dreg != X86_EAX) x86_push_reg (code, X86_EAX); EMIT_FPCOMPARE(code); x86_alu_reg_imm (code, X86_AND, X86_EAX, X86_FP_CC_MASK); x86_alu_reg_imm (code, X86_CMP, X86_EAX, 0x4000); x86_set_reg (code, ins->opcode == OP_FCEQ ? X86_CC_EQ : X86_CC_NE, ins->dreg, TRUE); x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE); if (ins->dreg != X86_EAX) x86_pop_reg (code, X86_EAX); break; case OP_FCLT: case OP_FCLT_UN: if (cfg->opt & MONO_OPT_FCMOV) { /* zeroing the register at the start results in * shorter and faster code (we can also remove the widening op) */ x86_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg); x86_fcomip (code, 1); x86_fstp (code, 0); if (ins->opcode == OP_FCLT_UN) { guchar *unordered_check = code; guchar *jump_to_end; x86_branch8 (code, X86_CC_P, 0, FALSE); x86_set_reg (code, X86_CC_GT, ins->dreg, FALSE); jump_to_end = code; x86_jump8 (code, 0); x86_patch (unordered_check, code); x86_inc_reg (code, ins->dreg); x86_patch (jump_to_end, code); } else { x86_set_reg (code, X86_CC_GT, ins->dreg, FALSE); } break; } if (ins->dreg != X86_EAX) x86_push_reg (code, X86_EAX); EMIT_FPCOMPARE(code); x86_alu_reg_imm (code, X86_AND, X86_EAX, X86_FP_CC_MASK); if (ins->opcode == OP_FCLT_UN) { guchar *is_not_zero_check, *end_jump; is_not_zero_check = code; x86_branch8 (code, X86_CC_NZ, 0, TRUE); end_jump = code; x86_jump8 (code, 0); x86_patch (is_not_zero_check, code); x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_CC_MASK); x86_patch (end_jump, code); } x86_set_reg (code, X86_CC_EQ, ins->dreg, TRUE); x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE); if (ins->dreg != X86_EAX) x86_pop_reg (code, X86_EAX); break; case OP_FCLE: { guchar *unordered_check; guchar *jump_to_end; if (cfg->opt & MONO_OPT_FCMOV) { /* zeroing the register at the start results in * shorter and faster code (we can also remove the widening op) */ x86_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg); x86_fcomip (code, 1); x86_fstp (code, 0); unordered_check = code; x86_branch8 (code, X86_CC_P, 0, FALSE); x86_set_reg (code, X86_CC_NB, ins->dreg, FALSE); x86_patch (unordered_check, code); break; } if (ins->dreg != X86_EAX) x86_push_reg (code, X86_EAX); EMIT_FPCOMPARE(code); x86_alu_reg_imm (code, X86_AND, X86_EAX, X86_FP_CC_MASK); x86_alu_reg_imm (code, X86_CMP, X86_EAX, 0x4500); unordered_check = code; x86_branch8 (code, X86_CC_EQ, 0, FALSE); x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C0); x86_set_reg (code, X86_CC_NE, ins->dreg, TRUE); x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE); jump_to_end = code; x86_jump8 (code, 0); x86_patch (unordered_check, code); x86_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg); x86_patch (jump_to_end, code); if (ins->dreg != X86_EAX) x86_pop_reg (code, X86_EAX); break; } case OP_FCGT: case OP_FCGT_UN: if (cfg->opt & MONO_OPT_FCMOV) { /* zeroing the register at the start results in * shorter and faster code (we can also remove the widening op) */ guchar *unordered_check; x86_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg); x86_fcomip (code, 1); x86_fstp (code, 0); if (ins->opcode == OP_FCGT) { unordered_check = code; x86_branch8 (code, X86_CC_P, 0, FALSE); x86_set_reg (code, X86_CC_LT, ins->dreg, FALSE); x86_patch (unordered_check, code); } else { x86_set_reg (code, X86_CC_LT, ins->dreg, FALSE); } break; } if (ins->dreg != X86_EAX) x86_push_reg (code, X86_EAX); EMIT_FPCOMPARE(code); x86_alu_reg_imm (code, X86_AND, X86_EAX, X86_FP_CC_MASK); x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C0); if (ins->opcode == OP_FCGT_UN) { guchar *is_not_zero_check, *end_jump; is_not_zero_check = code; x86_branch8 (code, X86_CC_NZ, 0, TRUE); end_jump = code; x86_jump8 (code, 0); x86_patch (is_not_zero_check, code); x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_CC_MASK); x86_patch (end_jump, code); } x86_set_reg (code, X86_CC_EQ, ins->dreg, TRUE); x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE); if (ins->dreg != X86_EAX) x86_pop_reg (code, X86_EAX); break; case OP_FCGE: { guchar *unordered_check; guchar *jump_to_end; if (cfg->opt & MONO_OPT_FCMOV) { /* zeroing the register at the start results in * shorter and faster code (we can also remove the widening op) */ x86_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg); x86_fcomip (code, 1); x86_fstp (code, 0); unordered_check = code; x86_branch8 (code, X86_CC_P, 0, FALSE); x86_set_reg (code, X86_CC_NA, ins->dreg, FALSE); x86_patch (unordered_check, code); break; } if (ins->dreg != X86_EAX) x86_push_reg (code, X86_EAX); EMIT_FPCOMPARE(code); x86_alu_reg_imm (code, X86_AND, X86_EAX, X86_FP_CC_MASK); x86_alu_reg_imm (code, X86_CMP, X86_EAX, 0x4500); unordered_check = code; x86_branch8 (code, X86_CC_EQ, 0, FALSE); x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C0); x86_set_reg (code, X86_CC_GE, ins->dreg, TRUE); x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE); jump_to_end = code; x86_jump8 (code, 0); x86_patch (unordered_check, code); x86_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg); x86_patch (jump_to_end, code); if (ins->dreg != X86_EAX) x86_pop_reg (code, X86_EAX); break; } case OP_FBEQ: if (cfg->opt & MONO_OPT_FCMOV) { guchar *jump = code; x86_branch8 (code, X86_CC_P, 0, TRUE); EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE); x86_patch (jump, code); break; } x86_alu_reg_imm (code, X86_CMP, X86_EAX, 0x4000); EMIT_COND_BRANCH (ins, X86_CC_EQ, TRUE); break; case OP_FBNE_UN: /* Branch if C013 != 100 */ if (cfg->opt & MONO_OPT_FCMOV) { /* branch if !ZF or (PF|CF) */ EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE); EMIT_COND_BRANCH (ins, X86_CC_P, FALSE); EMIT_COND_BRANCH (ins, X86_CC_B, FALSE); break; } x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C3); EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE); break; case OP_FBLT: if (cfg->opt & MONO_OPT_FCMOV) { EMIT_COND_BRANCH (ins, X86_CC_GT, FALSE); break; } EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE); break; case OP_FBLT_UN: if (cfg->opt & MONO_OPT_FCMOV) { EMIT_COND_BRANCH (ins, X86_CC_P, FALSE); EMIT_COND_BRANCH (ins, X86_CC_GT, FALSE); break; } if (ins->opcode == OP_FBLT_UN) { guchar *is_not_zero_check, *end_jump; is_not_zero_check = code; x86_branch8 (code, X86_CC_NZ, 0, TRUE); end_jump = code; x86_jump8 (code, 0); x86_patch (is_not_zero_check, code); x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_CC_MASK); x86_patch (end_jump, code); } EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE); break; case OP_FBGT: case OP_FBGT_UN: if (cfg->opt & MONO_OPT_FCMOV) { if (ins->opcode == OP_FBGT) { guchar *br1; /* skip branch if C1=1 */ br1 = code; x86_branch8 (code, X86_CC_P, 0, FALSE); /* branch if (C0 | C3) = 1 */ EMIT_COND_BRANCH (ins, X86_CC_LT, FALSE); x86_patch (br1, code); } else { EMIT_COND_BRANCH (ins, X86_CC_LT, FALSE); } break; } x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C0); if (ins->opcode == OP_FBGT_UN) { guchar *is_not_zero_check, *end_jump; is_not_zero_check = code; x86_branch8 (code, X86_CC_NZ, 0, TRUE); end_jump = code; x86_jump8 (code, 0); x86_patch (is_not_zero_check, code); x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_CC_MASK); x86_patch (end_jump, code); } EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE); break; case OP_FBGE: /* Branch if C013 == 100 or 001 */ if (cfg->opt & MONO_OPT_FCMOV) { guchar *br1; /* skip branch if C1=1 */ br1 = code; x86_branch8 (code, X86_CC_P, 0, FALSE); /* branch if (C0 | C3) = 1 */ EMIT_COND_BRANCH (ins, X86_CC_BE, FALSE); x86_patch (br1, code); break; } x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C0); EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE); x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C3); EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE); break; case OP_FBGE_UN: /* Branch if C013 == 000 */ if (cfg->opt & MONO_OPT_FCMOV) { EMIT_COND_BRANCH (ins, X86_CC_LE, FALSE); break; } EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE); break; case OP_FBLE: /* Branch if C013=000 or 100 */ if (cfg->opt & MONO_OPT_FCMOV) { guchar *br1; /* skip branch if C1=1 */ br1 = code; x86_branch8 (code, X86_CC_P, 0, FALSE); /* branch if C0=0 */ EMIT_COND_BRANCH (ins, X86_CC_NB, FALSE); x86_patch (br1, code); break; } x86_alu_reg_imm (code, X86_AND, X86_EAX, (X86_FP_C0|X86_FP_C1)); x86_alu_reg_imm (code, X86_CMP, X86_EAX, 0); EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE); break; case OP_FBLE_UN: /* Branch if C013 != 001 */ if (cfg->opt & MONO_OPT_FCMOV) { EMIT_COND_BRANCH (ins, X86_CC_P, FALSE); EMIT_COND_BRANCH (ins, X86_CC_GE, FALSE); break; } x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C0); EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE); break; case OP_CKFINITE: { guchar *br1; x86_push_reg (code, X86_EAX); x86_fxam (code); x86_fnstsw (code); x86_alu_reg_imm (code, X86_AND, X86_EAX, 0x4100); x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C0); x86_pop_reg (code, X86_EAX); /* Have to clean up the fp stack before throwing the exception */ br1 = code; x86_branch8 (code, X86_CC_NE, 0, FALSE); x86_fstp (code, 0); EMIT_COND_SYSTEM_EXCEPTION (X86_CC_EQ, FALSE, "ArithmeticException"); x86_patch (br1, code); break; } case OP_TLS_GET: { code = mono_x86_emit_tls_get (code, ins->dreg, ins->inst_offset); break; } case OP_TLS_GET_REG: { code = emit_tls_get_reg (code, ins->dreg, ins->sreg1); break; } case OP_TLS_SET: { code = mono_x86_emit_tls_set (code, ins->sreg1, ins->inst_offset); break; } case OP_TLS_SET_REG: { code = emit_tls_set_reg (code, ins->sreg1, ins->sreg2); break; } case OP_MEMORY_BARRIER: { if (ins->backend.memory_barrier_kind == MONO_MEMORY_BARRIER_SEQ) { x86_prefix (code, X86_LOCK_PREFIX); x86_alu_membase_imm (code, X86_ADD, X86_ESP, 0, 0); } break; } case OP_ATOMIC_ADD_I4: { int dreg = ins->dreg; g_assert (cfg->has_atomic_add_i4); /* hack: limit in regalloc, dreg != sreg1 && dreg != sreg2 */ if (ins->sreg2 == dreg) { if (dreg == X86_EBX) { dreg = X86_EDI; if (ins->inst_basereg == X86_EDI) dreg = X86_ESI; } else { dreg = X86_EBX; if (ins->inst_basereg == X86_EBX) dreg = X86_EDI; } } else if (ins->inst_basereg == dreg) { if (dreg == X86_EBX) { dreg = X86_EDI; if (ins->sreg2 == X86_EDI) dreg = X86_ESI; } else { dreg = X86_EBX; if (ins->sreg2 == X86_EBX) dreg = X86_EDI; } } if (dreg != ins->dreg) { x86_push_reg (code, dreg); } x86_mov_reg_reg (code, dreg, ins->sreg2, 4); x86_prefix (code, X86_LOCK_PREFIX); x86_xadd_membase_reg (code, ins->inst_basereg, ins->inst_offset, dreg, 4); /* dreg contains the old value, add with sreg2 value */ x86_alu_reg_reg (code, X86_ADD, dreg, ins->sreg2); if (ins->dreg != dreg) { x86_mov_reg_reg (code, ins->dreg, dreg, 4); x86_pop_reg (code, dreg); } break; } case OP_ATOMIC_EXCHANGE_I4: { guchar *br[2]; int sreg2 = ins->sreg2; int breg = ins->inst_basereg; g_assert (cfg->has_atomic_exchange_i4); /* cmpxchg uses eax as comperand, need to make sure we can use it * hack to overcome limits in x86 reg allocator * (req: dreg == eax and sreg2 != eax and breg != eax) */ g_assert (ins->dreg == X86_EAX); /* We need the EAX reg for the cmpxchg */ if (ins->sreg2 == X86_EAX) { sreg2 = (breg == X86_EDX) ? X86_EBX : X86_EDX; x86_push_reg (code, sreg2); x86_mov_reg_reg (code, sreg2, X86_EAX, 4); } if (breg == X86_EAX) { breg = (sreg2 == X86_ESI) ? X86_EDI : X86_ESI; x86_push_reg (code, breg); x86_mov_reg_reg (code, breg, X86_EAX, 4); } x86_mov_reg_membase (code, X86_EAX, breg, ins->inst_offset, 4); br [0] = code; x86_prefix (code, X86_LOCK_PREFIX); x86_cmpxchg_membase_reg (code, breg, ins->inst_offset, sreg2); br [1] = code; x86_branch8 (code, X86_CC_NE, -1, FALSE); x86_patch (br [1], br [0]); if (breg != ins->inst_basereg) x86_pop_reg (code, breg); if (ins->sreg2 != sreg2) x86_pop_reg (code, sreg2); break; } case OP_ATOMIC_CAS_I4: { g_assert (ins->dreg == X86_EAX); g_assert (ins->sreg3 == X86_EAX); g_assert (ins->sreg1 != X86_EAX); g_assert (ins->sreg1 != ins->sreg2); x86_prefix (code, X86_LOCK_PREFIX); x86_cmpxchg_membase_reg (code, ins->sreg1, ins->inst_offset, ins->sreg2); break; } case OP_ATOMIC_LOAD_I1: { x86_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, TRUE, FALSE); break; } case OP_ATOMIC_LOAD_U1: { x86_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, FALSE, FALSE); break; } case OP_ATOMIC_LOAD_I2: { x86_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, TRUE, TRUE); break; } case OP_ATOMIC_LOAD_U2: { x86_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, FALSE, TRUE); break; } case OP_ATOMIC_LOAD_I4: case OP_ATOMIC_LOAD_U4: { x86_mov_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, 4); break; } case OP_ATOMIC_LOAD_R4: case OP_ATOMIC_LOAD_R8: { x86_fld_membase (code, ins->inst_basereg, ins->inst_offset, ins->opcode == OP_ATOMIC_LOAD_R8); break; } case OP_ATOMIC_STORE_I1: case OP_ATOMIC_STORE_U1: case OP_ATOMIC_STORE_I2: case OP_ATOMIC_STORE_U2: case OP_ATOMIC_STORE_I4: case OP_ATOMIC_STORE_U4: { int size; switch (ins->opcode) { case OP_ATOMIC_STORE_I1: case OP_ATOMIC_STORE_U1: size = 1; break; case OP_ATOMIC_STORE_I2: case OP_ATOMIC_STORE_U2: size = 2; break; case OP_ATOMIC_STORE_I4: case OP_ATOMIC_STORE_U4: size = 4; break; } x86_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, size); if (ins->backend.memory_barrier_kind == MONO_MEMORY_BARRIER_SEQ) x86_mfence (code); break; } case OP_ATOMIC_STORE_R4: case OP_ATOMIC_STORE_R8: { x86_fst_membase (code, ins->inst_destbasereg, ins->inst_offset, ins->opcode == OP_ATOMIC_STORE_R8, TRUE); if (ins->backend.memory_barrier_kind == MONO_MEMORY_BARRIER_SEQ) x86_mfence (code); break; } case OP_CARD_TABLE_WBARRIER: { int ptr = ins->sreg1; int value = ins->sreg2; guchar *br = NULL; int nursery_shift, card_table_shift; gpointer card_table_mask; size_t nursery_size; gulong card_table = (gulong)mono_gc_get_card_table (&card_table_shift, &card_table_mask); gulong nursery_start = (gulong)mono_gc_get_nursery (&nursery_shift, &nursery_size); gboolean card_table_nursery_check = mono_gc_card_table_nursery_check (); /* * We need one register we can clobber, we choose EDX and make sreg1 * fixed EAX to work around limitations in the local register allocator. * sreg2 might get allocated to EDX, but that is not a problem since * we use it before clobbering EDX. */ g_assert (ins->sreg1 == X86_EAX); /* * This is the code we produce: * * edx = value * edx >>= nursery_shift * cmp edx, (nursery_start >> nursery_shift) * jne done * edx = ptr * edx >>= card_table_shift * card_table[edx] = 1 * done: */ if (card_table_nursery_check) { if (value != X86_EDX) x86_mov_reg_reg (code, X86_EDX, value, 4); x86_shift_reg_imm (code, X86_SHR, X86_EDX, nursery_shift); x86_alu_reg_imm (code, X86_CMP, X86_EDX, nursery_start >> nursery_shift); br = code; x86_branch8 (code, X86_CC_NE, -1, FALSE); } x86_mov_reg_reg (code, X86_EDX, ptr, 4); x86_shift_reg_imm (code, X86_SHR, X86_EDX, card_table_shift); if (card_table_mask) x86_alu_reg_imm (code, X86_AND, X86_EDX, (int)card_table_mask); x86_mov_membase_imm (code, X86_EDX, card_table, 1, 1); if (card_table_nursery_check) x86_patch (br, code); break; } #ifdef MONO_ARCH_SIMD_INTRINSICS case OP_ADDPS: x86_sse_alu_ps_reg_reg (code, X86_SSE_ADD, ins->sreg1, ins->sreg2); break; case OP_DIVPS: x86_sse_alu_ps_reg_reg (code, X86_SSE_DIV, ins->sreg1, ins->sreg2); break; case OP_MULPS: x86_sse_alu_ps_reg_reg (code, X86_SSE_MUL, ins->sreg1, ins->sreg2); break; case OP_SUBPS: x86_sse_alu_ps_reg_reg (code, X86_SSE_SUB, ins->sreg1, ins->sreg2); break; case OP_MAXPS: x86_sse_alu_ps_reg_reg (code, X86_SSE_MAX, ins->sreg1, ins->sreg2); break; case OP_MINPS: x86_sse_alu_ps_reg_reg (code, X86_SSE_MIN, ins->sreg1, ins->sreg2); break; case OP_COMPPS: g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 7); x86_sse_alu_ps_reg_reg_imm (code, X86_SSE_COMP, ins->sreg1, ins->sreg2, ins->inst_c0); break; case OP_ANDPS: x86_sse_alu_ps_reg_reg (code, X86_SSE_AND, ins->sreg1, ins->sreg2); break; case OP_ANDNPS: x86_sse_alu_ps_reg_reg (code, X86_SSE_ANDN, ins->sreg1, ins->sreg2); break; case OP_ORPS: x86_sse_alu_ps_reg_reg (code, X86_SSE_OR, ins->sreg1, ins->sreg2); break; case OP_XORPS: x86_sse_alu_ps_reg_reg (code, X86_SSE_XOR, ins->sreg1, ins->sreg2); break; case OP_SQRTPS: x86_sse_alu_ps_reg_reg (code, X86_SSE_SQRT, ins->dreg, ins->sreg1); break; case OP_RSQRTPS: x86_sse_alu_ps_reg_reg (code, X86_SSE_RSQRT, ins->dreg, ins->sreg1); break; case OP_RCPPS: x86_sse_alu_ps_reg_reg (code, X86_SSE_RCP, ins->dreg, ins->sreg1); break; case OP_ADDSUBPS: x86_sse_alu_sd_reg_reg (code, X86_SSE_ADDSUB, ins->sreg1, ins->sreg2); break; case OP_HADDPS: x86_sse_alu_sd_reg_reg (code, X86_SSE_HADD, ins->sreg1, ins->sreg2); break; case OP_HSUBPS: x86_sse_alu_sd_reg_reg (code, X86_SSE_HSUB, ins->sreg1, ins->sreg2); break; case OP_DUPPS_HIGH: x86_sse_alu_ss_reg_reg (code, X86_SSE_MOVSHDUP, ins->dreg, ins->sreg1); break; case OP_DUPPS_LOW: x86_sse_alu_ss_reg_reg (code, X86_SSE_MOVSLDUP, ins->dreg, ins->sreg1); break; case OP_PSHUFLEW_HIGH: g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 0xFF); x86_pshufw_reg_reg (code, ins->dreg, ins->sreg1, ins->inst_c0, 1); break; case OP_PSHUFLEW_LOW: g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 0xFF); x86_pshufw_reg_reg (code, ins->dreg, ins->sreg1, ins->inst_c0, 0); break; case OP_PSHUFLED: g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 0xFF); x86_sse_shift_reg_imm (code, X86_SSE_PSHUFD, ins->dreg, ins->sreg1, ins->inst_c0); break; case OP_SHUFPS: g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 0xFF); x86_sse_alu_reg_reg_imm8 (code, X86_SSE_SHUFP, ins->sreg1, ins->sreg2, ins->inst_c0); break; case OP_SHUFPD: g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 0x3); x86_sse_alu_pd_reg_reg_imm8 (code, X86_SSE_SHUFP, ins->sreg1, ins->sreg2, ins->inst_c0); break; case OP_ADDPD: x86_sse_alu_pd_reg_reg (code, X86_SSE_ADD, ins->sreg1, ins->sreg2); break; case OP_DIVPD: x86_sse_alu_pd_reg_reg (code, X86_SSE_DIV, ins->sreg1, ins->sreg2); break; case OP_MULPD: x86_sse_alu_pd_reg_reg (code, X86_SSE_MUL, ins->sreg1, ins->sreg2); break; case OP_SUBPD: x86_sse_alu_pd_reg_reg (code, X86_SSE_SUB, ins->sreg1, ins->sreg2); break; case OP_MAXPD: x86_sse_alu_pd_reg_reg (code, X86_SSE_MAX, ins->sreg1, ins->sreg2); break; case OP_MINPD: x86_sse_alu_pd_reg_reg (code, X86_SSE_MIN, ins->sreg1, ins->sreg2); break; case OP_COMPPD: g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 7); x86_sse_alu_pd_reg_reg_imm (code, X86_SSE_COMP, ins->sreg1, ins->sreg2, ins->inst_c0); break; case OP_ANDPD: x86_sse_alu_pd_reg_reg (code, X86_SSE_AND, ins->sreg1, ins->sreg2); break; case OP_ANDNPD: x86_sse_alu_pd_reg_reg (code, X86_SSE_ANDN, ins->sreg1, ins->sreg2); break; case OP_ORPD: x86_sse_alu_pd_reg_reg (code, X86_SSE_OR, ins->sreg1, ins->sreg2); break; case OP_XORPD: x86_sse_alu_pd_reg_reg (code, X86_SSE_XOR, ins->sreg1, ins->sreg2); break; case OP_SQRTPD: x86_sse_alu_pd_reg_reg (code, X86_SSE_SQRT, ins->dreg, ins->sreg1); break; case OP_ADDSUBPD: x86_sse_alu_pd_reg_reg (code, X86_SSE_ADDSUB, ins->sreg1, ins->sreg2); break; case OP_HADDPD: x86_sse_alu_pd_reg_reg (code, X86_SSE_HADD, ins->sreg1, ins->sreg2); break; case OP_HSUBPD: x86_sse_alu_pd_reg_reg (code, X86_SSE_HSUB, ins->sreg1, ins->sreg2); break; case OP_DUPPD: x86_sse_alu_sd_reg_reg (code, X86_SSE_MOVDDUP, ins->dreg, ins->sreg1); break; case OP_EXTRACT_MASK: x86_sse_alu_pd_reg_reg (code, X86_SSE_PMOVMSKB, ins->dreg, ins->sreg1); break; case OP_PAND: x86_sse_alu_pd_reg_reg (code, X86_SSE_PAND, ins->sreg1, ins->sreg2); break; case OP_POR: x86_sse_alu_pd_reg_reg (code, X86_SSE_POR, ins->sreg1, ins->sreg2); break; case OP_PXOR: x86_sse_alu_pd_reg_reg (code, X86_SSE_PXOR, ins->sreg1, ins->sreg2); break; case OP_PADDB: x86_sse_alu_pd_reg_reg (code, X86_SSE_PADDB, ins->sreg1, ins->sreg2); break; case OP_PADDW: x86_sse_alu_pd_reg_reg (code, X86_SSE_PADDW, ins->sreg1, ins->sreg2); break; case OP_PADDD: x86_sse_alu_pd_reg_reg (code, X86_SSE_PADDD, ins->sreg1, ins->sreg2); break; case OP_PADDQ: x86_sse_alu_pd_reg_reg (code, X86_SSE_PADDQ, ins->sreg1, ins->sreg2); break; case OP_PSUBB: x86_sse_alu_pd_reg_reg (code, X86_SSE_PSUBB, ins->sreg1, ins->sreg2); break; case OP_PSUBW: x86_sse_alu_pd_reg_reg (code, X86_SSE_PSUBW, ins->sreg1, ins->sreg2); break; case OP_PSUBD: x86_sse_alu_pd_reg_reg (code, X86_SSE_PSUBD, ins->sreg1, ins->sreg2); break; case OP_PSUBQ: x86_sse_alu_pd_reg_reg (code, X86_SSE_PSUBQ, ins->sreg1, ins->sreg2); break; case OP_PMAXB_UN: x86_sse_alu_pd_reg_reg (code, X86_SSE_PMAXUB, ins->sreg1, ins->sreg2); break; case OP_PMAXW_UN: x86_sse_alu_sse41_reg_reg (code, X86_SSE_PMAXUW, ins->sreg1, ins->sreg2); break; case OP_PMAXD_UN: x86_sse_alu_sse41_reg_reg (code, X86_SSE_PMAXUD, ins->sreg1, ins->sreg2); break; case OP_PMAXB: x86_sse_alu_sse41_reg_reg (code, X86_SSE_PMAXSB, ins->sreg1, ins->sreg2); break; case OP_PMAXW: x86_sse_alu_pd_reg_reg (code, X86_SSE_PMAXSW, ins->sreg1, ins->sreg2); break; case OP_PMAXD: x86_sse_alu_sse41_reg_reg (code, X86_SSE_PMAXSD, ins->sreg1, ins->sreg2); break; case OP_PAVGB_UN: x86_sse_alu_pd_reg_reg (code, X86_SSE_PAVGB, ins->sreg1, ins->sreg2); break; case OP_PAVGW_UN: x86_sse_alu_pd_reg_reg (code, X86_SSE_PAVGW, ins->sreg1, ins->sreg2); break; case OP_PMINB_UN: x86_sse_alu_pd_reg_reg (code, X86_SSE_PMINUB, ins->sreg1, ins->sreg2); break; case OP_PMINW_UN: x86_sse_alu_sse41_reg_reg (code, X86_SSE_PMINUW, ins->sreg1, ins->sreg2); break; case OP_PMIND_UN: x86_sse_alu_sse41_reg_reg (code, X86_SSE_PMINUD, ins->sreg1, ins->sreg2); break; case OP_PMINB: x86_sse_alu_sse41_reg_reg (code, X86_SSE_PMINSB, ins->sreg1, ins->sreg2); break; case OP_PMINW: x86_sse_alu_pd_reg_reg (code, X86_SSE_PMINSW, ins->sreg1, ins->sreg2); break; case OP_PMIND: x86_sse_alu_sse41_reg_reg (code, X86_SSE_PMINSD, ins->sreg1, ins->sreg2); break; case OP_PCMPEQB: x86_sse_alu_pd_reg_reg (code, X86_SSE_PCMPEQB, ins->sreg1, ins->sreg2); break; case OP_PCMPEQW: x86_sse_alu_pd_reg_reg (code, X86_SSE_PCMPEQW, ins->sreg1, ins->sreg2); break; case OP_PCMPEQD: x86_sse_alu_pd_reg_reg (code, X86_SSE_PCMPEQD, ins->sreg1, ins->sreg2); break; case OP_PCMPEQQ: x86_sse_alu_sse41_reg_reg (code, X86_SSE_PCMPEQQ, ins->sreg1, ins->sreg2); break; case OP_PCMPGTB: x86_sse_alu_pd_reg_reg (code, X86_SSE_PCMPGTB, ins->sreg1, ins->sreg2); break; case OP_PCMPGTW: x86_sse_alu_pd_reg_reg (code, X86_SSE_PCMPGTW, ins->sreg1, ins->sreg2); break; case OP_PCMPGTD: x86_sse_alu_pd_reg_reg (code, X86_SSE_PCMPGTD, ins->sreg1, ins->sreg2); break; case OP_PCMPGTQ: x86_sse_alu_sse41_reg_reg (code, X86_SSE_PCMPGTQ, ins->sreg1, ins->sreg2); break; case OP_PSUM_ABS_DIFF: x86_sse_alu_pd_reg_reg (code, X86_SSE_PSADBW, ins->sreg1, ins->sreg2); break; case OP_UNPACK_LOWB: x86_sse_alu_pd_reg_reg (code, X86_SSE_PUNPCKLBW, ins->sreg1, ins->sreg2); break; case OP_UNPACK_LOWW: x86_sse_alu_pd_reg_reg (code, X86_SSE_PUNPCKLWD, ins->sreg1, ins->sreg2); break; case OP_UNPACK_LOWD: x86_sse_alu_pd_reg_reg (code, X86_SSE_PUNPCKLDQ, ins->sreg1, ins->sreg2); break; case OP_UNPACK_LOWQ: x86_sse_alu_pd_reg_reg (code, X86_SSE_PUNPCKLQDQ, ins->sreg1, ins->sreg2); break; case OP_UNPACK_LOWPS: x86_sse_alu_ps_reg_reg (code, X86_SSE_UNPCKL, ins->sreg1, ins->sreg2); break; case OP_UNPACK_LOWPD: x86_sse_alu_pd_reg_reg (code, X86_SSE_UNPCKL, ins->sreg1, ins->sreg2); break; case OP_UNPACK_HIGHB: x86_sse_alu_pd_reg_reg (code, X86_SSE_PUNPCKHBW, ins->sreg1, ins->sreg2); break; case OP_UNPACK_HIGHW: x86_sse_alu_pd_reg_reg (code, X86_SSE_PUNPCKHWD, ins->sreg1, ins->sreg2); break; case OP_UNPACK_HIGHD: x86_sse_alu_pd_reg_reg (code, X86_SSE_PUNPCKHDQ, ins->sreg1, ins->sreg2); break; case OP_UNPACK_HIGHQ: x86_sse_alu_pd_reg_reg (code, X86_SSE_PUNPCKHQDQ, ins->sreg1, ins->sreg2); break; case OP_UNPACK_HIGHPS: x86_sse_alu_ps_reg_reg (code, X86_SSE_UNPCKH, ins->sreg1, ins->sreg2); break; case OP_UNPACK_HIGHPD: x86_sse_alu_pd_reg_reg (code, X86_SSE_UNPCKH, ins->sreg1, ins->sreg2); break; case OP_PACKW: x86_sse_alu_pd_reg_reg (code, X86_SSE_PACKSSWB, ins->sreg1, ins->sreg2); break; case OP_PACKD: x86_sse_alu_pd_reg_reg (code, X86_SSE_PACKSSDW, ins->sreg1, ins->sreg2); break; case OP_PACKW_UN: x86_sse_alu_pd_reg_reg (code, X86_SSE_PACKUSWB, ins->sreg1, ins->sreg2); break; case OP_PACKD_UN: x86_sse_alu_sse41_reg_reg (code, X86_SSE_PACKUSDW, ins->sreg1, ins->sreg2); break; case OP_PADDB_SAT_UN: x86_sse_alu_pd_reg_reg (code, X86_SSE_PADDUSB, ins->sreg1, ins->sreg2); break; case OP_PSUBB_SAT_UN: x86_sse_alu_pd_reg_reg (code, X86_SSE_PSUBUSB, ins->sreg1, ins->sreg2); break; case OP_PADDW_SAT_UN: x86_sse_alu_pd_reg_reg (code, X86_SSE_PADDUSW, ins->sreg1, ins->sreg2); break; case OP_PSUBW_SAT_UN: x86_sse_alu_pd_reg_reg (code, X86_SSE_PSUBUSW, ins->sreg1, ins->sreg2); break; case OP_PADDB_SAT: x86_sse_alu_pd_reg_reg (code, X86_SSE_PADDSB, ins->sreg1, ins->sreg2); break; case OP_PSUBB_SAT: x86_sse_alu_pd_reg_reg (code, X86_SSE_PSUBSB, ins->sreg1, ins->sreg2); break; case OP_PADDW_SAT: x86_sse_alu_pd_reg_reg (code, X86_SSE_PADDSW, ins->sreg1, ins->sreg2); break; case OP_PSUBW_SAT: x86_sse_alu_pd_reg_reg (code, X86_SSE_PSUBSW, ins->sreg1, ins->sreg2); break; case OP_PMULW: x86_sse_alu_pd_reg_reg (code, X86_SSE_PMULLW, ins->sreg1, ins->sreg2); break; case OP_PMULD: x86_sse_alu_sse41_reg_reg (code, X86_SSE_PMULLD, ins->sreg1, ins->sreg2); break; case OP_PMULQ: x86_sse_alu_pd_reg_reg (code, X86_SSE_PMULUDQ, ins->sreg1, ins->sreg2); break; case OP_PMULW_HIGH_UN: x86_sse_alu_pd_reg_reg (code, X86_SSE_PMULHUW, ins->sreg1, ins->sreg2); break; case OP_PMULW_HIGH: x86_sse_alu_pd_reg_reg (code, X86_SSE_PMULHW, ins->sreg1, ins->sreg2); break; case OP_PSHRW: x86_sse_shift_reg_imm (code, X86_SSE_PSHIFTW, X86_SSE_SHR, ins->dreg, ins->inst_imm); break; case OP_PSHRW_REG: x86_sse_shift_reg_reg (code, X86_SSE_PSRLW_REG, ins->dreg, ins->sreg2); break; case OP_PSARW: x86_sse_shift_reg_imm (code, X86_SSE_PSHIFTW, X86_SSE_SAR, ins->dreg, ins->inst_imm); break; case OP_PSARW_REG: x86_sse_shift_reg_reg (code, X86_SSE_PSRAW_REG, ins->dreg, ins->sreg2); break; case OP_PSHLW: x86_sse_shift_reg_imm (code, X86_SSE_PSHIFTW, X86_SSE_SHL, ins->dreg, ins->inst_imm); break; case OP_PSHLW_REG: x86_sse_shift_reg_reg (code, X86_SSE_PSLLW_REG, ins->dreg, ins->sreg2); break; case OP_PSHRD: x86_sse_shift_reg_imm (code, X86_SSE_PSHIFTD, X86_SSE_SHR, ins->dreg, ins->inst_imm); break; case OP_PSHRD_REG: x86_sse_shift_reg_reg (code, X86_SSE_PSRLD_REG, ins->dreg, ins->sreg2); break; case OP_PSARD: x86_sse_shift_reg_imm (code, X86_SSE_PSHIFTD, X86_SSE_SAR, ins->dreg, ins->inst_imm); break; case OP_PSARD_REG: x86_sse_shift_reg_reg (code, X86_SSE_PSRAD_REG, ins->dreg, ins->sreg2); break; case OP_PSHLD: x86_sse_shift_reg_imm (code, X86_SSE_PSHIFTD, X86_SSE_SHL, ins->dreg, ins->inst_imm); break; case OP_PSHLD_REG: x86_sse_shift_reg_reg (code, X86_SSE_PSLLD_REG, ins->dreg, ins->sreg2); break; case OP_PSHRQ: x86_sse_shift_reg_imm (code, X86_SSE_PSHIFTQ, X86_SSE_SHR, ins->dreg, ins->inst_imm); break; case OP_PSHRQ_REG: x86_sse_shift_reg_reg (code, X86_SSE_PSRLQ_REG, ins->dreg, ins->sreg2); break; case OP_PSHLQ: x86_sse_shift_reg_imm (code, X86_SSE_PSHIFTQ, X86_SSE_SHL, ins->dreg, ins->inst_imm); break; case OP_PSHLQ_REG: x86_sse_shift_reg_reg (code, X86_SSE_PSLLQ_REG, ins->dreg, ins->sreg2); break; case OP_ICONV_TO_X: x86_movd_xreg_reg (code, ins->dreg, ins->sreg1); break; case OP_EXTRACT_I4: x86_movd_reg_xreg (code, ins->dreg, ins->sreg1); break; case OP_EXTRACT_I1: case OP_EXTRACT_U1: x86_movd_reg_xreg (code, ins->dreg, ins->sreg1); if (ins->inst_c0) x86_shift_reg_imm (code, X86_SHR, ins->dreg, ins->inst_c0 * 8); x86_widen_reg (code, ins->dreg, ins->dreg, ins->opcode == OP_EXTRACT_I1, FALSE); break; case OP_EXTRACT_I2: case OP_EXTRACT_U2: x86_movd_reg_xreg (code, ins->dreg, ins->sreg1); if (ins->inst_c0) x86_shift_reg_imm (code, X86_SHR, ins->dreg, 16); x86_widen_reg (code, ins->dreg, ins->dreg, ins->opcode == OP_EXTRACT_I2, TRUE); break; case OP_EXTRACT_R8: if (ins->inst_c0) x86_sse_alu_pd_membase_reg (code, X86_SSE_MOVHPD_MEMBASE_REG, ins->backend.spill_var->inst_basereg, ins->backend.spill_var->inst_offset, ins->sreg1); else x86_sse_alu_sd_membase_reg (code, X86_SSE_MOVSD_MEMBASE_REG, ins->backend.spill_var->inst_basereg, ins->backend.spill_var->inst_offset, ins->sreg1); x86_fld_membase (code, ins->backend.spill_var->inst_basereg, ins->backend.spill_var->inst_offset, TRUE); break; case OP_INSERT_I2: x86_sse_alu_pd_reg_reg_imm (code, X86_SSE_PINSRW, ins->sreg1, ins->sreg2, ins->inst_c0); break; case OP_EXTRACTX_U2: x86_sse_alu_pd_reg_reg_imm (code, X86_SSE_PEXTRW, ins->dreg, ins->sreg1, ins->inst_c0); break; case OP_INSERTX_U1_SLOW: /*sreg1 is the extracted ireg (scratch) /sreg2 is the to be inserted ireg (scratch) /dreg is the xreg to receive the value*/ /*clear the bits from the extracted word*/ x86_alu_reg_imm (code, X86_AND, ins->sreg1, ins->inst_c0 & 1 ? 0x00FF : 0xFF00); /*shift the value to insert if needed*/ if (ins->inst_c0 & 1) x86_shift_reg_imm (code, X86_SHL, ins->sreg2, 8); /*join them together*/ x86_alu_reg_reg (code, X86_OR, ins->sreg1, ins->sreg2); x86_sse_alu_pd_reg_reg_imm (code, X86_SSE_PINSRW, ins->dreg, ins->sreg1, ins->inst_c0 / 2); break; case OP_INSERTX_I4_SLOW: x86_sse_alu_pd_reg_reg_imm (code, X86_SSE_PINSRW, ins->dreg, ins->sreg2, ins->inst_c0 * 2); x86_shift_reg_imm (code, X86_SHR, ins->sreg2, 16); x86_sse_alu_pd_reg_reg_imm (code, X86_SSE_PINSRW, ins->dreg, ins->sreg2, ins->inst_c0 * 2 + 1); break; case OP_INSERTX_R4_SLOW: x86_fst_membase (code, ins->backend.spill_var->inst_basereg, ins->backend.spill_var->inst_offset, FALSE, TRUE); /*TODO if inst_c0 == 0 use movss*/ x86_sse_alu_pd_reg_membase_imm (code, X86_SSE_PINSRW, ins->dreg, ins->backend.spill_var->inst_basereg, ins->backend.spill_var->inst_offset + 0, ins->inst_c0 * 2); x86_sse_alu_pd_reg_membase_imm (code, X86_SSE_PINSRW, ins->dreg, ins->backend.spill_var->inst_basereg, ins->backend.spill_var->inst_offset + 2, ins->inst_c0 * 2 + 1); break; case OP_INSERTX_R8_SLOW: x86_fst_membase (code, ins->backend.spill_var->inst_basereg, ins->backend.spill_var->inst_offset, TRUE, TRUE); if (cfg->verbose_level) printf ("CONVERTING a OP_INSERTX_R8_SLOW %d offset %x\n", ins->inst_c0, offset); if (ins->inst_c0) x86_sse_alu_pd_reg_membase (code, X86_SSE_MOVHPD_REG_MEMBASE, ins->dreg, ins->backend.spill_var->inst_basereg, ins->backend.spill_var->inst_offset); else x86_movsd_reg_membase (code, ins->dreg, ins->backend.spill_var->inst_basereg, ins->backend.spill_var->inst_offset); break; case OP_STOREX_MEMBASE_REG: case OP_STOREX_MEMBASE: x86_movups_membase_reg (code, ins->dreg, ins->inst_offset, ins->sreg1); break; case OP_LOADX_MEMBASE: x86_movups_reg_membase (code, ins->dreg, ins->sreg1, ins->inst_offset); break; case OP_LOADX_ALIGNED_MEMBASE: x86_movaps_reg_membase (code, ins->dreg, ins->sreg1, ins->inst_offset); break; case OP_STOREX_ALIGNED_MEMBASE_REG: x86_movaps_membase_reg (code, ins->dreg, ins->inst_offset, ins->sreg1); break; case OP_STOREX_NTA_MEMBASE_REG: x86_sse_alu_reg_membase (code, X86_SSE_MOVNTPS, ins->dreg, ins->sreg1, ins->inst_offset); break; case OP_PREFETCH_MEMBASE: x86_sse_alu_reg_membase (code, X86_SSE_PREFETCH, ins->backend.arg_info, ins->sreg1, ins->inst_offset); break; case OP_XMOVE: /*FIXME the peephole pass should have killed this*/ if (ins->dreg != ins->sreg1) x86_movaps_reg_reg (code, ins->dreg, ins->sreg1); break; case OP_XZERO: x86_sse_alu_pd_reg_reg (code, X86_SSE_PXOR, ins->dreg, ins->dreg); break; case OP_FCONV_TO_R8_X: x86_fst_membase (code, ins->backend.spill_var->inst_basereg, ins->backend.spill_var->inst_offset, TRUE, TRUE); x86_movsd_reg_membase (code, ins->dreg, ins->backend.spill_var->inst_basereg, ins->backend.spill_var->inst_offset); break; case OP_XCONV_R8_TO_I4: x86_cvttsd2si (code, ins->dreg, ins->sreg1); switch (ins->backend.source_opcode) { case OP_FCONV_TO_I1: x86_widen_reg (code, ins->dreg, ins->dreg, TRUE, FALSE); break; case OP_FCONV_TO_U1: x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE); break; case OP_FCONV_TO_I2: x86_widen_reg (code, ins->dreg, ins->dreg, TRUE, TRUE); break; case OP_FCONV_TO_U2: x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, TRUE); break; } break; case OP_EXPAND_I1: /*FIXME this causes a partial register stall, maybe it would not be that bad to use shift + mask + or*/ /*The +4 is to get a mov ?h, ?l over the same reg.*/ x86_mov_reg_reg (code, ins->dreg + 4, ins->dreg, 1); x86_sse_alu_pd_reg_reg_imm (code, X86_SSE_PINSRW, ins->dreg, ins->sreg1, 0); x86_sse_alu_pd_reg_reg_imm (code, X86_SSE_PINSRW, ins->dreg, ins->sreg1, 1); x86_sse_shift_reg_imm (code, X86_SSE_PSHUFD, ins->dreg, ins->dreg, 0); break; case OP_EXPAND_I2: x86_sse_alu_pd_reg_reg_imm (code, X86_SSE_PINSRW, ins->dreg, ins->sreg1, 0); x86_sse_alu_pd_reg_reg_imm (code, X86_SSE_PINSRW, ins->dreg, ins->sreg1, 1); x86_sse_shift_reg_imm (code, X86_SSE_PSHUFD, ins->dreg, ins->dreg, 0); break; case OP_EXPAND_I4: x86_movd_xreg_reg (code, ins->dreg, ins->sreg1); x86_sse_shift_reg_imm (code, X86_SSE_PSHUFD, ins->dreg, ins->dreg, 0); break; case OP_EXPAND_R4: x86_fst_membase (code, ins->backend.spill_var->inst_basereg, ins->backend.spill_var->inst_offset, FALSE, TRUE); x86_movd_xreg_membase (code, ins->dreg, ins->backend.spill_var->inst_basereg, ins->backend.spill_var->inst_offset); x86_sse_shift_reg_imm (code, X86_SSE_PSHUFD, ins->dreg, ins->dreg, 0); break; case OP_EXPAND_R8: x86_fst_membase (code, ins->backend.spill_var->inst_basereg, ins->backend.spill_var->inst_offset, TRUE, TRUE); x86_movsd_reg_membase (code, ins->dreg, ins->backend.spill_var->inst_basereg, ins->backend.spill_var->inst_offset); x86_sse_shift_reg_imm (code, X86_SSE_PSHUFD, ins->dreg, ins->dreg, 0x44); break; case OP_CVTDQ2PD: x86_sse_alu_ss_reg_reg (code, X86_SSE_CVTDQ2PD, ins->dreg, ins->sreg1); break; case OP_CVTDQ2PS: x86_sse_alu_ps_reg_reg (code, X86_SSE_CVTDQ2PS, ins->dreg, ins->sreg1); break; case OP_CVTPD2DQ: x86_sse_alu_sd_reg_reg (code, X86_SSE_CVTPD2DQ, ins->dreg, ins->sreg1); break; case OP_CVTPD2PS: x86_sse_alu_pd_reg_reg (code, X86_SSE_CVTPD2PS, ins->dreg, ins->sreg1); break; case OP_CVTPS2DQ: x86_sse_alu_pd_reg_reg (code, X86_SSE_CVTPS2DQ, ins->dreg, ins->sreg1); break; case OP_CVTPS2PD: x86_sse_alu_ps_reg_reg (code, X86_SSE_CVTPS2PD, ins->dreg, ins->sreg1); break; case OP_CVTTPD2DQ: x86_sse_alu_pd_reg_reg (code, X86_SSE_CVTTPD2DQ, ins->dreg, ins->sreg1); break; case OP_CVTTPS2DQ: x86_sse_alu_ss_reg_reg (code, X86_SSE_CVTTPS2DQ, ins->dreg, ins->sreg1); break; #endif case OP_LIVERANGE_START: { if (cfg->verbose_level > 1) printf ("R%d START=0x%x\n", MONO_VARINFO (cfg, ins->inst_c0)->vreg, (int)(code - cfg->native_code)); MONO_VARINFO (cfg, ins->inst_c0)->live_range_start = code - cfg->native_code; break; } case OP_LIVERANGE_END: { if (cfg->verbose_level > 1) printf ("R%d END=0x%x\n", MONO_VARINFO (cfg, ins->inst_c0)->vreg, (int)(code - cfg->native_code)); MONO_VARINFO (cfg, ins->inst_c0)->live_range_end = code - cfg->native_code; break; } case OP_GC_SAFE_POINT: { const char *polling_func = NULL; int compare_val = 0; guint8 *br [1]; #if defined (USE_COOP_GC) polling_func = "mono_threads_state_poll"; compare_val = 1; #elif defined(__native_client_codegen__) && defined(__native_client_gc__) polling_func = "mono_nacl_gc"; compare_val = 0xFFFFFFFF; #endif if (!polling_func) break; x86_test_membase_imm (code, ins->sreg1, 0, compare_val); br[0] = code; x86_branch8 (code, X86_CC_EQ, 0, FALSE); code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, polling_func); x86_patch (br [0], code); break; } case OP_GC_LIVENESS_DEF: case OP_GC_LIVENESS_USE: case OP_GC_PARAM_SLOT_LIVENESS_DEF: ins->backend.pc_offset = code - cfg->native_code; break; case OP_GC_SPILL_SLOT_LIVENESS_DEF: ins->backend.pc_offset = code - cfg->native_code; bb->spill_slot_defs = g_slist_prepend_mempool (cfg->mempool, bb->spill_slot_defs, ins); break; case OP_GET_SP: x86_mov_reg_reg (code, ins->dreg, X86_ESP, sizeof (mgreg_t)); break; case OP_SET_SP: x86_mov_reg_reg (code, X86_ESP, ins->sreg1, sizeof (mgreg_t)); break; default: g_warning ("unknown opcode %s\n", mono_inst_name (ins->opcode)); g_assert_not_reached (); } if (G_UNLIKELY ((code - cfg->native_code - offset) > max_len)) { #ifndef __native_client_codegen__ g_warning ("wrong maximal instruction length of instruction %s (expected %d, got %d)", mono_inst_name (ins->opcode), max_len, code - cfg->native_code - offset); g_assert_not_reached (); #endif /* __native_client_codegen__ */ } cpos += max_len; } cfg->code_len = code - cfg->native_code; } #endif /* DISABLE_JIT */ void mono_arch_register_lowlevel_calls (void) { } void mono_arch_patch_code_new (MonoCompile *cfg, MonoDomain *domain, guint8 *code, MonoJumpInfo *ji, gpointer target) { unsigned char *ip = ji->ip.i + code; switch (ji->type) { case MONO_PATCH_INFO_IP: *((gconstpointer *)(ip)) = target; break; case MONO_PATCH_INFO_ABS: case MONO_PATCH_INFO_METHOD: case MONO_PATCH_INFO_METHOD_JUMP: case MONO_PATCH_INFO_INTERNAL_METHOD: case MONO_PATCH_INFO_BB: case MONO_PATCH_INFO_LABEL: case MONO_PATCH_INFO_RGCTX_FETCH: case MONO_PATCH_INFO_MONITOR_ENTER: case MONO_PATCH_INFO_MONITOR_ENTER_V4: case MONO_PATCH_INFO_MONITOR_EXIT: case MONO_PATCH_INFO_JIT_ICALL_ADDR: #if defined(__native_client_codegen__) && defined(__native_client__) if (nacl_is_code_address (code)) { /* For tail calls, code is patched after being installed */ /* but not through the normal "patch callsite" method. */ unsigned char buf[kNaClAlignment]; unsigned char *aligned_code = (uintptr_t)code & ~kNaClAlignmentMask; unsigned char *_target = target; int ret; /* All patch targets modified in x86_patch */ /* are IP relative. */ _target = _target + (uintptr_t)buf - (uintptr_t)aligned_code; memcpy (buf, aligned_code, kNaClAlignment); /* Patch a temp buffer of bundle size, */ /* then install to actual location. */ x86_patch (buf + ((uintptr_t)code - (uintptr_t)aligned_code), _target); ret = nacl_dyncode_modify (aligned_code, buf, kNaClAlignment); g_assert (ret == 0); } else { x86_patch (ip, (unsigned char*)target); } #else x86_patch (ip, (unsigned char*)target); #endif break; case MONO_PATCH_INFO_NONE: break; case MONO_PATCH_INFO_R4: case MONO_PATCH_INFO_R8: { guint32 offset = mono_arch_get_patch_offset (ip); *((gconstpointer *)(ip + offset)) = target; break; } default: { guint32 offset = mono_arch_get_patch_offset (ip); #if !defined(__native_client__) *((gconstpointer *)(ip + offset)) = target; #else *((gconstpointer *)(ip + offset)) = nacl_modify_patch_target (target); #endif break; } } } static G_GNUC_UNUSED void stack_unaligned (MonoMethod *m, gpointer caller) { printf ("%s\n", mono_method_full_name (m, TRUE)); g_assert_not_reached (); } guint8 * mono_arch_emit_prolog (MonoCompile *cfg) { MonoMethod *method = cfg->method; MonoBasicBlock *bb; MonoMethodSignature *sig; MonoInst *inst; int alloc_size, pos, max_offset, i, cfa_offset; guint8 *code; gboolean need_stack_frame; #ifdef __native_client_codegen__ guint alignment_check; #endif cfg->code_size = MAX (cfg->header->code_size * 4, 10240); if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) cfg->code_size += 512; #if defined(__default_codegen__) code = cfg->native_code = g_malloc (cfg->code_size); #elif defined(__native_client_codegen__) /* native_code_alloc is not 32-byte aligned, native_code is. */ cfg->code_size = NACL_BUNDLE_ALIGN_UP (cfg->code_size); cfg->native_code_alloc = g_malloc (cfg->code_size + kNaClAlignment); /* Align native_code to next nearest kNaclAlignment byte. */ cfg->native_code = (guint)cfg->native_code_alloc + kNaClAlignment; cfg->native_code = (guint)cfg->native_code & ~kNaClAlignmentMask; code = cfg->native_code; alignment_check = (guint)cfg->native_code & kNaClAlignmentMask; g_assert(alignment_check == 0); #endif #if 0 { guint8 *br [16]; /* Check that the stack is aligned on osx */ x86_mov_reg_reg (code, X86_EAX, X86_ESP, sizeof (mgreg_t)); x86_alu_reg_imm (code, X86_AND, X86_EAX, 15); x86_alu_reg_imm (code, X86_CMP, X86_EAX, 0xc); br [0] = code; x86_branch_disp (code, X86_CC_Z, 0, FALSE); x86_push_membase (code, X86_ESP, 0); x86_push_imm (code, cfg->method); x86_mov_reg_imm (code, X86_EAX, stack_unaligned); x86_call_reg (code, X86_EAX); x86_patch (br [0], code); } #endif /* Offset between RSP and the CFA */ cfa_offset = 0; // CFA = sp + 4 cfa_offset = sizeof (gpointer); mono_emit_unwind_op_def_cfa (cfg, code, X86_ESP, sizeof (gpointer)); // IP saved at CFA - 4 /* There is no IP reg on x86 */ mono_emit_unwind_op_offset (cfg, code, X86_NREG, -cfa_offset); mini_gc_set_slot_type_from_cfa (cfg, -cfa_offset, SLOT_NOREF); need_stack_frame = needs_stack_frame (cfg); if (need_stack_frame) { x86_push_reg (code, X86_EBP); cfa_offset += sizeof (gpointer); mono_emit_unwind_op_def_cfa_offset (cfg, code, cfa_offset); mono_emit_unwind_op_offset (cfg, code, X86_EBP, - cfa_offset); x86_mov_reg_reg (code, X86_EBP, X86_ESP, 4); mono_emit_unwind_op_def_cfa_reg (cfg, code, X86_EBP); /* These are handled automatically by the stack marking code */ mini_gc_set_slot_type_from_cfa (cfg, -cfa_offset, SLOT_NOREF); } else { cfg->frame_reg = X86_ESP; } cfg->stack_offset += cfg->param_area; cfg->stack_offset = ALIGN_TO (cfg->stack_offset, MONO_ARCH_FRAME_ALIGNMENT); alloc_size = cfg->stack_offset; pos = 0; if (!method->save_lmf) { if (cfg->used_int_regs & (1 << X86_EBX)) { x86_push_reg (code, X86_EBX); pos += 4; cfa_offset += sizeof (gpointer); mono_emit_unwind_op_offset (cfg, code, X86_EBX, - cfa_offset); /* These are handled automatically by the stack marking code */ mini_gc_set_slot_type_from_cfa (cfg, - cfa_offset, SLOT_NOREF); } if (cfg->used_int_regs & (1 << X86_EDI)) { x86_push_reg (code, X86_EDI); pos += 4; cfa_offset += sizeof (gpointer); mono_emit_unwind_op_offset (cfg, code, X86_EDI, - cfa_offset); mini_gc_set_slot_type_from_cfa (cfg, - cfa_offset, SLOT_NOREF); } if (cfg->used_int_regs & (1 << X86_ESI)) { x86_push_reg (code, X86_ESI); pos += 4; cfa_offset += sizeof (gpointer); mono_emit_unwind_op_offset (cfg, code, X86_ESI, - cfa_offset); mini_gc_set_slot_type_from_cfa (cfg, - cfa_offset, SLOT_NOREF); } } alloc_size -= pos; /* the original alloc_size is already aligned: there is %ebp and retip pushed, so realign */ if (mono_do_x86_stack_align && need_stack_frame) { int tot = alloc_size + pos + 4; /* ret ip */ if (need_stack_frame) tot += 4; /* ebp */ tot &= MONO_ARCH_FRAME_ALIGNMENT - 1; if (tot) { alloc_size += MONO_ARCH_FRAME_ALIGNMENT - tot; for (i = 0; i < MONO_ARCH_FRAME_ALIGNMENT - tot; i += sizeof (mgreg_t)) mini_gc_set_slot_type_from_fp (cfg, - (alloc_size + pos - i), SLOT_NOREF); } } cfg->arch.sp_fp_offset = alloc_size + pos; if (alloc_size) { /* See mono_emit_stack_alloc */ #if defined(TARGET_WIN32) || defined(MONO_ARCH_SIGSEGV_ON_ALTSTACK) guint32 remaining_size = alloc_size; /*FIXME handle unbounded code expansion, we should use a loop in case of more than X interactions*/ guint32 required_code_size = ((remaining_size / 0x1000) + 1) * 8; /*8 is the max size of x86_alu_reg_imm + x86_test_membase_reg*/ guint32 offset = code - cfg->native_code; if (G_UNLIKELY (required_code_size >= (cfg->code_size - offset))) { while (required_code_size >= (cfg->code_size - offset)) cfg->code_size *= 2; cfg->native_code = mono_realloc_native_code(cfg); code = cfg->native_code + offset; cfg->stat_code_reallocs++; } while (remaining_size >= 0x1000) { x86_alu_reg_imm (code, X86_SUB, X86_ESP, 0x1000); x86_test_membase_reg (code, X86_ESP, 0, X86_ESP); remaining_size -= 0x1000; } if (remaining_size) x86_alu_reg_imm (code, X86_SUB, X86_ESP, remaining_size); #else x86_alu_reg_imm (code, X86_SUB, X86_ESP, alloc_size); #endif g_assert (need_stack_frame); } if (cfg->method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED || cfg->method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) { x86_alu_reg_imm (code, X86_AND, X86_ESP, -MONO_ARCH_FRAME_ALIGNMENT); } #if DEBUG_STACK_ALIGNMENT /* check the stack is aligned */ if (need_stack_frame && method->wrapper_type == MONO_WRAPPER_NONE) { x86_mov_reg_reg (code, X86_ECX, X86_ESP, 4); x86_alu_reg_imm (code, X86_AND, X86_ECX, MONO_ARCH_FRAME_ALIGNMENT - 1); x86_alu_reg_imm (code, X86_CMP, X86_ECX, 0); x86_branch_disp (code, X86_CC_EQ, 3, FALSE); x86_breakpoint (code); } #endif /* compute max_offset in order to use short forward jumps */ max_offset = 0; if (cfg->opt & MONO_OPT_BRANCH) { for (bb = cfg->bb_entry; bb; bb = bb->next_bb) { MonoInst *ins; bb->max_offset = max_offset; if (cfg->prof_options & MONO_PROFILE_COVERAGE) max_offset += 6; /* max alignment for loops */ if ((cfg->opt & MONO_OPT_LOOP) && bb_is_loop_start (bb)) max_offset += LOOP_ALIGNMENT; #ifdef __native_client_codegen__ /* max alignment for native client */ if (bb->flags & BB_INDIRECT_JUMP_TARGET || bb->flags & BB_EXCEPTION_HANDLER) max_offset += kNaClAlignment; #endif MONO_BB_FOR_EACH_INS (bb, ins) { if (ins->opcode == OP_LABEL) ins->inst_c1 = max_offset; #ifdef __native_client_codegen__ switch (ins->opcode) { case OP_FCALL: case OP_LCALL: case OP_VCALL: case OP_VCALL2: case OP_VOIDCALL: case OP_CALL: case OP_FCALL_REG: case OP_LCALL_REG: case OP_VCALL_REG: case OP_VCALL2_REG: case OP_VOIDCALL_REG: case OP_CALL_REG: case OP_FCALL_MEMBASE: case OP_LCALL_MEMBASE: case OP_VCALL_MEMBASE: case OP_VCALL2_MEMBASE: case OP_VOIDCALL_MEMBASE: case OP_CALL_MEMBASE: max_offset += kNaClAlignment; break; default: max_offset += ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN] - 1; break; } #endif /* __native_client_codegen__ */ max_offset += ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN]; } } } /* store runtime generic context */ if (cfg->rgctx_var) { g_assert (cfg->rgctx_var->opcode == OP_REGOFFSET && cfg->rgctx_var->inst_basereg == X86_EBP); x86_mov_membase_reg (code, X86_EBP, cfg->rgctx_var->inst_offset, MONO_ARCH_RGCTX_REG, 4); } if (method->save_lmf) code = emit_setup_lmf (cfg, code, cfg->lmf_var->inst_offset, cfa_offset); if (mono_jit_trace_calls != NULL && mono_trace_eval (method)) code = mono_arch_instrument_prolog (cfg, mono_trace_enter_method, code, TRUE); { MonoInst *ins; if (cfg->arch.ss_tramp_var) { /* Initialize ss_tramp_var */ ins = cfg->arch.ss_tramp_var; g_assert (ins->opcode == OP_REGOFFSET); g_assert (!cfg->compile_aot); x86_mov_membase_imm (code, ins->inst_basereg, ins->inst_offset, (guint32)&ss_trampoline, 4); } if (cfg->arch.bp_tramp_var) { /* Initialize bp_tramp_var */ ins = cfg->arch.bp_tramp_var; g_assert (ins->opcode == OP_REGOFFSET); g_assert (!cfg->compile_aot); x86_mov_membase_imm (code, ins->inst_basereg, ins->inst_offset, (guint32)&bp_trampoline, 4); } } /* load arguments allocated to register from the stack */ sig = mono_method_signature (method); pos = 0; for (i = 0; i < sig->param_count + sig->hasthis; ++i) { inst = cfg->args [pos]; if (inst->opcode == OP_REGVAR) { g_assert (need_stack_frame); x86_mov_reg_membase (code, inst->dreg, X86_EBP, inst->inst_offset, 4); if (cfg->verbose_level > 2) g_print ("Argument %d assigned to register %s\n", pos, mono_arch_regname (inst->dreg)); } pos++; } cfg->code_len = code - cfg->native_code; g_assert (cfg->code_len < cfg->code_size); return code; } void mono_arch_emit_epilog (MonoCompile *cfg) { MonoMethod *method = cfg->method; MonoMethodSignature *sig = mono_method_signature (method); int i, quad, pos; guint32 stack_to_pop; guint8 *code; int max_epilog_size = 16; CallInfo *cinfo; gboolean need_stack_frame = needs_stack_frame (cfg); if (cfg->method->save_lmf) max_epilog_size += 128; while (cfg->code_len + max_epilog_size > (cfg->code_size - 16)) { cfg->code_size *= 2; cfg->native_code = mono_realloc_native_code(cfg); cfg->stat_code_reallocs++; } code = cfg->native_code + cfg->code_len; if (mono_jit_trace_calls != NULL && mono_trace_eval (method)) code = mono_arch_instrument_epilog (cfg, mono_trace_leave_method, code, TRUE); /* the code restoring the registers must be kept in sync with OP_TAILCALL */ pos = 0; if (method->save_lmf) { gint32 lmf_offset = cfg->lmf_var->inst_offset; guint8 *patch; gboolean supported = FALSE; if (cfg->compile_aot) { #if defined(MONO_HAVE_FAST_TLS) supported = TRUE; #endif } else if (mono_get_jit_tls_offset () != -1) { supported = TRUE; } /* check if we need to restore protection of the stack after a stack overflow */ if (supported) { if (cfg->compile_aot) { code = emit_load_aotconst (NULL, code, cfg, NULL, X86_ECX, MONO_PATCH_INFO_TLS_OFFSET, GINT_TO_POINTER (TLS_KEY_JIT_TLS)); code = emit_tls_get_reg (code, X86_ECX, X86_ECX); } else { code = mono_x86_emit_tls_get (code, X86_ECX, mono_get_jit_tls_offset ()); } /* we load the value in a separate instruction: this mechanism may be * used later as a safer way to do thread interruption */ x86_mov_reg_membase (code, X86_ECX, X86_ECX, MONO_STRUCT_OFFSET (MonoJitTlsData, restore_stack_prot), 4); x86_alu_reg_imm (code, X86_CMP, X86_ECX, 0); patch = code; x86_branch8 (code, X86_CC_Z, 0, FALSE); /* note that the call trampoline will preserve eax/edx */ x86_call_reg (code, X86_ECX); x86_patch (patch, code); } else { /* FIXME: maybe save the jit tls in the prolog */ } /* restore caller saved regs */ if (cfg->used_int_regs & (1 << X86_EBX)) { x86_mov_reg_membase (code, X86_EBX, cfg->frame_reg, lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, ebx), 4); } if (cfg->used_int_regs & (1 << X86_EDI)) { x86_mov_reg_membase (code, X86_EDI, cfg->frame_reg, lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, edi), 4); } if (cfg->used_int_regs & (1 << X86_ESI)) { x86_mov_reg_membase (code, X86_ESI, cfg->frame_reg, lmf_offset + MONO_STRUCT_OFFSET (MonoLMF, esi), 4); } /* EBP is restored by LEAVE */ } else { for (i = 0; i < X86_NREG; ++i) { if ((cfg->used_int_regs & X86_CALLER_REGS & (1 << i)) && (i != X86_EBP)) { pos -= 4; } } if (pos) { g_assert (need_stack_frame); x86_lea_membase (code, X86_ESP, X86_EBP, pos); } if (pos) { g_assert (need_stack_frame); x86_lea_membase (code, X86_ESP, X86_EBP, pos); } if (cfg->used_int_regs & (1 << X86_ESI)) { x86_pop_reg (code, X86_ESI); } if (cfg->used_int_regs & (1 << X86_EDI)) { x86_pop_reg (code, X86_EDI); } if (cfg->used_int_regs & (1 << X86_EBX)) { x86_pop_reg (code, X86_EBX); } } /* Load returned vtypes into registers if needed */ cinfo = get_call_info (cfg->mempool, sig); if (cinfo->ret.storage == ArgValuetypeInReg) { for (quad = 0; quad < 2; quad ++) { switch (cinfo->ret.pair_storage [quad]) { case ArgInIReg: x86_mov_reg_membase (code, cinfo->ret.pair_regs [quad], cfg->ret->inst_basereg, cfg->ret->inst_offset + (quad * sizeof (gpointer)), 4); break; case ArgOnFloatFpStack: x86_fld_membase (code, cfg->ret->inst_basereg, cfg->ret->inst_offset + (quad * sizeof (gpointer)), FALSE); break; case ArgOnDoubleFpStack: x86_fld_membase (code, cfg->ret->inst_basereg, cfg->ret->inst_offset + (quad * sizeof (gpointer)), TRUE); break; case ArgNone: break; default: g_assert_not_reached (); } } } if (need_stack_frame) x86_leave (code); if (CALLCONV_IS_STDCALL (sig)) { MonoJitArgumentInfo *arg_info = alloca (sizeof (MonoJitArgumentInfo) * (sig->param_count + 1)); stack_to_pop = mono_arch_get_argument_info (sig, sig->param_count, arg_info); } else if (cinfo->callee_stack_pop) stack_to_pop = cinfo->callee_stack_pop; else stack_to_pop = 0; if (stack_to_pop) { g_assert (need_stack_frame); x86_ret_imm (code, stack_to_pop); } else { x86_ret (code); } cfg->code_len = code - cfg->native_code; g_assert (cfg->code_len < cfg->code_size); } void mono_arch_emit_exceptions (MonoCompile *cfg) { MonoJumpInfo *patch_info; int nthrows, i; guint8 *code; MonoClass *exc_classes [16]; guint8 *exc_throw_start [16], *exc_throw_end [16]; guint32 code_size; int exc_count = 0; /* Compute needed space */ for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) { if (patch_info->type == MONO_PATCH_INFO_EXC) exc_count++; } /* * make sure we have enough space for exceptions * 16 is the size of two push_imm instructions and a call */ if (cfg->compile_aot) code_size = exc_count * 32; else code_size = exc_count * 16; while (cfg->code_len + code_size > (cfg->code_size - 16)) { cfg->code_size *= 2; cfg->native_code = mono_realloc_native_code(cfg); cfg->stat_code_reallocs++; } code = cfg->native_code + cfg->code_len; nthrows = 0; for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) { switch (patch_info->type) { case MONO_PATCH_INFO_EXC: { MonoClass *exc_class; guint8 *buf, *buf2; guint32 throw_ip; x86_patch (patch_info->ip.i + cfg->native_code, code); exc_class = mono_class_from_name (mono_defaults.corlib, "System", patch_info->data.name); g_assert (exc_class); throw_ip = patch_info->ip.i; /* Find a throw sequence for the same exception class */ for (i = 0; i < nthrows; ++i) if (exc_classes [i] == exc_class) break; if (i < nthrows) { x86_push_imm (code, (exc_throw_end [i] - cfg->native_code) - throw_ip); x86_jump_code (code, exc_throw_start [i]); patch_info->type = MONO_PATCH_INFO_NONE; } else { guint32 size; /* Compute size of code following the push <OFFSET> */ #if defined(__default_codegen__) size = 5 + 5; #elif defined(__native_client_codegen__) code = mono_nacl_align (code); size = kNaClAlignment; #endif /*This is aligned to 16 bytes by the callee. This way we save a few bytes here.*/ if ((code - cfg->native_code) - throw_ip < 126 - size) { /* Use the shorter form */ buf = buf2 = code; x86_push_imm (code, 0); } else { buf = code; x86_push_imm (code, 0xf0f0f0f0); buf2 = code; } if (nthrows < 16) { exc_classes [nthrows] = exc_class; exc_throw_start [nthrows] = code; } x86_push_imm (code, exc_class->type_token - MONO_TOKEN_TYPE_DEF); patch_info->data.name = "mono_arch_throw_corlib_exception"; patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD; patch_info->ip.i = code - cfg->native_code; x86_call_code (code, 0); x86_push_imm (buf, (code - cfg->native_code) - throw_ip); while (buf < buf2) x86_nop (buf); if (nthrows < 16) { exc_throw_end [nthrows] = code; nthrows ++; } } break; } default: /* do nothing */ break; } } cfg->code_len = code - cfg->native_code; g_assert (cfg->code_len < cfg->code_size); } void mono_arch_flush_icache (guint8 *code, gint size) { /* not needed */ } void mono_arch_flush_register_windows (void) { } gboolean mono_arch_is_inst_imm (gint64 imm) { return TRUE; } void mono_arch_finish_init (void) { if (!g_getenv ("MONO_NO_TLS")) { #ifndef TARGET_WIN32 #if MONO_XEN_OPT optimize_for_xen = access ("/proc/xen", F_OK) == 0; #endif #endif } } void mono_arch_free_jit_tls_data (MonoJitTlsData *tls) { } // Linear handler, the bsearch head compare is shorter //[2 + 4] x86_alu_reg_imm (code, X86_CMP, ins->sreg1, ins->inst_imm); //[1 + 1] x86_branch8(inst,cond,imm,is_signed) // x86_patch(ins,target) //[1 + 5] x86_jump_mem(inst,mem) #define CMP_SIZE 6 #if defined(__default_codegen__) #define BR_SMALL_SIZE 2 #define BR_LARGE_SIZE 5 #elif defined(__native_client_codegen__) /* I suspect the size calculation below is actually incorrect. */ /* TODO: fix the calculation that uses these sizes. */ #define BR_SMALL_SIZE 16 #define BR_LARGE_SIZE 12 #endif /*__native_client_codegen__*/ #define JUMP_IMM_SIZE 6 #define ENABLE_WRONG_METHOD_CHECK 0 #define DEBUG_IMT 0 static int imt_branch_distance (MonoIMTCheckItem **imt_entries, int start, int target) { int i, distance = 0; for (i = start; i < target; ++i) distance += imt_entries [i]->chunk_size; return distance; } /* * LOCKING: called with the domain lock held */ gpointer mono_arch_build_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp) { int i; int size = 0; guint8 *code, *start; GSList *unwind_ops; for (i = 0; i < count; ++i) { MonoIMTCheckItem *item = imt_entries [i]; if (item->is_equals) { if (item->check_target_idx) { if (!item->compare_done) item->chunk_size += CMP_SIZE; item->chunk_size += BR_SMALL_SIZE + JUMP_IMM_SIZE; } else { if (fail_tramp) { item->chunk_size += CMP_SIZE + BR_SMALL_SIZE + JUMP_IMM_SIZE * 2; } else { item->chunk_size += JUMP_IMM_SIZE; #if ENABLE_WRONG_METHOD_CHECK item->chunk_size += CMP_SIZE + BR_SMALL_SIZE + 1; #endif } } } else { item->chunk_size += CMP_SIZE + BR_LARGE_SIZE; imt_entries [item->check_target_idx]->compare_done = TRUE; } size += item->chunk_size; } #if defined(__native_client__) && defined(__native_client_codegen__) /* In Native Client, we don't re-use thunks, allocate from the */ /* normal code manager paths. */ size = NACL_BUNDLE_ALIGN_UP (size); code = mono_domain_code_reserve (domain, size); #else if (fail_tramp) code = mono_method_alloc_generic_virtual_thunk (domain, size); else code = mono_domain_code_reserve (domain, size); #endif start = code; unwind_ops = mono_arch_get_cie_program (); for (i = 0; i < count; ++i) { MonoIMTCheckItem *item = imt_entries [i]; item->code_target = code; if (item->is_equals) { if (item->check_target_idx) { if (!item->compare_done) x86_alu_reg_imm (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)item->key); item->jmp_code = code; x86_branch8 (code, X86_CC_NE, 0, FALSE); if (item->has_target_code) x86_jump_code (code, item->value.target_code); else x86_jump_mem (code, & (vtable->vtable [item->value.vtable_slot])); } else { if (fail_tramp) { x86_alu_reg_imm (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)item->key); item->jmp_code = code; x86_branch8 (code, X86_CC_NE, 0, FALSE); if (item->has_target_code) x86_jump_code (code, item->value.target_code); else x86_jump_mem (code, & (vtable->vtable [item->value.vtable_slot])); x86_patch (item->jmp_code, code); x86_jump_code (code, fail_tramp); item->jmp_code = NULL; } else { /* enable the commented code to assert on wrong method */ #if ENABLE_WRONG_METHOD_CHECK x86_alu_reg_imm (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)item->key); item->jmp_code = code; x86_branch8 (code, X86_CC_NE, 0, FALSE); #endif if (item->has_target_code) x86_jump_code (code, item->value.target_code); else x86_jump_mem (code, & (vtable->vtable [item->value.vtable_slot])); #if ENABLE_WRONG_METHOD_CHECK x86_patch (item->jmp_code, code); x86_breakpoint (code); item->jmp_code = NULL; #endif } } } else { x86_alu_reg_imm (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)item->key); item->jmp_code = code; if (x86_is_imm8 (imt_branch_distance (imt_entries, i, item->check_target_idx))) x86_branch8 (code, X86_CC_GE, 0, FALSE); else x86_branch32 (code, X86_CC_GE, 0, FALSE); } } /* patch the branches to get to the target items */ for (i = 0; i < count; ++i) { MonoIMTCheckItem *item = imt_entries [i]; if (item->jmp_code) { if (item->check_target_idx) { x86_patch (item->jmp_code, imt_entries [item->check_target_idx]->code_target); } } } if (!fail_tramp) mono_stats.imt_thunks_size += code - start; g_assert (code - start <= size); #if DEBUG_IMT { char *buff = g_strdup_printf ("thunk_for_class_%s_%s_entries_%d", vtable->klass->name_space, vtable->klass->name, count); mono_disassemble_code (NULL, (guint8*)start, code - start, buff); g_free (buff); } #endif if (mono_jit_map_is_enabled ()) { char *buff; if (vtable) buff = g_strdup_printf ("imt_%s_%s_entries_%d", vtable->klass->name_space, vtable->klass->name, count); else buff = g_strdup_printf ("imt_thunk_entries_%d", count); mono_emit_jit_tramp (start, code - start, buff); g_free (buff); } nacl_domain_code_validate (domain, &start, size, &code); mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_IMT_TRAMPOLINE, NULL); mono_tramp_info_register (mono_tramp_info_create (NULL, start, code - start, NULL, unwind_ops), domain); return start; } MonoMethod* mono_arch_find_imt_method (mgreg_t *regs, guint8 *code) { return (MonoMethod*) regs [MONO_ARCH_IMT_REG]; } MonoVTable* mono_arch_find_static_call_vtable (mgreg_t *regs, guint8 *code) { return (MonoVTable*) regs [MONO_ARCH_RGCTX_REG]; } GSList* mono_arch_get_cie_program (void) { GSList *l = NULL; mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, X86_ESP, 4); mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, X86_NREG, -4); return l; } MonoInst* mono_arch_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args) { MonoInst *ins = NULL; int opcode = 0; if (cmethod->klass == mono_defaults.math_class) { if (strcmp (cmethod->name, "Sin") == 0) { opcode = OP_SIN; } else if (strcmp (cmethod->name, "Cos") == 0) { opcode = OP_COS; } else if (strcmp (cmethod->name, "Tan") == 0) { opcode = OP_TAN; } else if (strcmp (cmethod->name, "Atan") == 0) { opcode = OP_ATAN; } else if (strcmp (cmethod->name, "Sqrt") == 0) { opcode = OP_SQRT; } else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8) { opcode = OP_ABS; } else if (strcmp (cmethod->name, "Round") == 0 && fsig->param_count == 1 && fsig->params [0]->type == MONO_TYPE_R8) { opcode = OP_ROUND; } if (opcode && fsig->param_count == 1) { MONO_INST_NEW (cfg, ins, opcode); ins->type = STACK_R8; ins->dreg = mono_alloc_freg (cfg); ins->sreg1 = args [0]->dreg; MONO_ADD_INS (cfg->cbb, ins); } if (cfg->opt & MONO_OPT_CMOV) { opcode = 0; if (strcmp (cmethod->name, "Min") == 0) { if (fsig->params [0]->type == MONO_TYPE_I4) opcode = OP_IMIN; } else if (strcmp (cmethod->name, "Max") == 0) { if (fsig->params [0]->type == MONO_TYPE_I4) opcode = OP_IMAX; } if (opcode && fsig->param_count == 2) { MONO_INST_NEW (cfg, ins, opcode); ins->type = STACK_I4; ins->dreg = mono_alloc_ireg (cfg); ins->sreg1 = args [0]->dreg; ins->sreg2 = args [1]->dreg; MONO_ADD_INS (cfg->cbb, ins); } } #if 0 /* OP_FREM is not IEEE compatible */ else if (strcmp (cmethod->name, "IEEERemainder") == 0 && fsig->param_count == 2) { MONO_INST_NEW (cfg, ins, OP_FREM); ins->inst_i0 = args [0]; ins->inst_i1 = args [1]; } #endif } return ins; } gboolean mono_arch_print_tree (MonoInst *tree, int arity) { return 0; } guint32 mono_arch_get_patch_offset (guint8 *code) { if ((code [0] == 0x8b) && (x86_modrm_mod (code [1]) == 0x2)) return 2; else if (code [0] == 0xba) return 1; else if (code [0] == 0x68) /* push IMM */ return 1; else if ((code [0] == 0xff) && (x86_modrm_reg (code [1]) == 0x6)) /* push <OFFSET>(<REG>) */ return 2; else if ((code [0] == 0xff) && (x86_modrm_reg (code [1]) == 0x2)) /* call *<OFFSET>(<REG>) */ return 2; else if ((code [0] == 0xdd) || (code [0] == 0xd9)) /* fldl <ADDR> */ return 2; else if ((code [0] == 0x58) && (code [1] == 0x05)) /* pop %eax; add <OFFSET>, %eax */ return 2; else if ((code [0] >= 0x58) && (code [0] <= 0x58 + X86_NREG) && (code [1] == 0x81)) /* pop <REG>; add <OFFSET>, <REG> */ return 3; else if ((code [0] >= 0xb8) && (code [0] < 0xb8 + 8)) /* mov <REG>, imm */ return 1; else { g_assert_not_reached (); return -1; } } /** * mono_breakpoint_clean_code: * * Copy @size bytes from @code - @offset to the buffer @buf. If the debugger inserted software * breakpoints in the original code, they are removed in the copy. * * Returns TRUE if no sw breakpoint was present. */ gboolean mono_breakpoint_clean_code (guint8 *method_start, guint8 *code, int offset, guint8 *buf, int size) { /* * If method_start is non-NULL we need to perform bound checks, since we access memory * at code - offset we could go before the start of the method and end up in a different * page of memory that is not mapped or read incorrect data anyway. We zero-fill the bytes * instead. */ if (!method_start || code - offset >= method_start) { memcpy (buf, code - offset, size); } else { int diff = code - method_start; memset (buf, 0, size); memcpy (buf + offset - diff, method_start, diff + size - offset); } return TRUE; } /* * mono_x86_get_this_arg_offset: * * Return the offset of the stack location where this is passed during a virtual * call. */ guint32 mono_x86_get_this_arg_offset (MonoMethodSignature *sig) { return 0; } gpointer mono_arch_get_this_arg_from_call (mgreg_t *regs, guint8 *code) { guint32 esp = regs [X86_ESP]; gpointer res; int offset; offset = 0; /* * The stack looks like: * <other args> * <this=delegate> */ res = ((MonoObject**)esp) [0]; return res; } #define MAX_ARCH_DELEGATE_PARAMS 10 static gpointer get_delegate_invoke_impl (MonoTrampInfo **info, gboolean has_target, guint32 param_count) { guint8 *code, *start; int code_reserve = 64; GSList *unwind_ops; unwind_ops = mono_arch_get_cie_program (); /* * The stack contains: * <delegate> * <return addr> */ if (has_target) { start = code = mono_global_codeman_reserve (code_reserve); /* Replace the this argument with the target */ x86_mov_reg_membase (code, X86_EAX, X86_ESP, 4, 4); x86_mov_reg_membase (code, X86_ECX, X86_EAX, MONO_STRUCT_OFFSET (MonoDelegate, target), 4); x86_mov_membase_reg (code, X86_ESP, 4, X86_ECX, 4); x86_jump_membase (code, X86_EAX, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr)); g_assert ((code - start) < code_reserve); } else { int i = 0; /* 8 for mov_reg and jump, plus 8 for each parameter */ #ifdef __native_client_codegen__ /* TODO: calculate this size correctly */ code_reserve = 13 + (param_count * 8) + 2 * kNaClAlignment; #else code_reserve = 8 + (param_count * 8); #endif /* __native_client_codegen__ */ /* * The stack contains: * <args in reverse order> * <delegate> * <return addr> * * and we need: * <args in reverse order> * <return addr> * * without unbalancing the stack. * So move each arg up a spot in the stack (overwriting un-needed 'this' arg) * and leaving original spot of first arg as placeholder in stack so * when callee pops stack everything works. */ start = code = mono_global_codeman_reserve (code_reserve); /* store delegate for access to method_ptr */ x86_mov_reg_membase (code, X86_ECX, X86_ESP, 4, 4); /* move args up */ for (i = 0; i < param_count; ++i) { x86_mov_reg_membase (code, X86_EAX, X86_ESP, (i+2)*4, 4); x86_mov_membase_reg (code, X86_ESP, (i+1)*4, X86_EAX, 4); } x86_jump_membase (code, X86_ECX, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr)); g_assert ((code - start) < code_reserve); } nacl_global_codeman_validate (&start, code_reserve, &code); if (has_target) { *info = mono_tramp_info_create ("delegate_invoke_impl_has_target", start, code - start, NULL, unwind_ops); } else { char *name = g_strdup_printf ("delegate_invoke_impl_target_%d", param_count); *info = mono_tramp_info_create (name, start, code - start, NULL, unwind_ops); g_free (name); } if (mono_jit_map_is_enabled ()) { char *buff; if (has_target) buff = (char*)"delegate_invoke_has_target"; else buff = g_strdup_printf ("delegate_invoke_no_target_%d", param_count); mono_emit_jit_tramp (start, code - start, buff); if (!has_target) g_free (buff); } mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_DELEGATE_INVOKE, NULL); return start; } #define MAX_VIRTUAL_DELEGATE_OFFSET 32 static gpointer get_delegate_virtual_invoke_impl (MonoTrampInfo **info, gboolean load_imt_reg, int offset) { guint8 *code, *start; int size = 24; char *tramp_name; GSList *unwind_ops; if (offset / (int)sizeof (gpointer) > MAX_VIRTUAL_DELEGATE_OFFSET) return NULL; /* * The stack contains: * <delegate> * <return addr> */ start = code = mono_global_codeman_reserve (size); unwind_ops = mono_arch_get_cie_program (); /* Replace the this argument with the target */ x86_mov_reg_membase (code, X86_EAX, X86_ESP, 4, 4); x86_mov_reg_membase (code, X86_ECX, X86_EAX, MONO_STRUCT_OFFSET (MonoDelegate, target), 4); x86_mov_membase_reg (code, X86_ESP, 4, X86_ECX, 4); if (load_imt_reg) { /* Load the IMT reg */ x86_mov_reg_membase (code, MONO_ARCH_IMT_REG, X86_EAX, MONO_STRUCT_OFFSET (MonoDelegate, method), 4); } /* Load the vtable */ x86_mov_reg_membase (code, X86_EAX, X86_ECX, MONO_STRUCT_OFFSET (MonoObject, vtable), 4); x86_jump_membase (code, X86_EAX, offset); mono_profiler_code_buffer_new (start, code - start, MONO_PROFILER_CODE_BUFFER_DELEGATE_INVOKE, NULL); if (load_imt_reg) tramp_name = g_strdup_printf ("delegate_virtual_invoke_imt_%d", - offset / sizeof (gpointer)); else tramp_name = g_strdup_printf ("delegate_virtual_invoke_%d", offset / sizeof (gpointer)); *info = mono_tramp_info_create (tramp_name, start, code - start, NULL, unwind_ops); g_free (tramp_name); return start; } GSList* mono_arch_get_delegate_invoke_impls (void) { GSList *res = NULL; MonoTrampInfo *info; int i; get_delegate_invoke_impl (&info, TRUE, 0); res = g_slist_prepend (res, info); for (i = 0; i <= MAX_ARCH_DELEGATE_PARAMS; ++i) { get_delegate_invoke_impl (&info, FALSE, i); res = g_slist_prepend (res, info); } for (i = 0; i <= MAX_VIRTUAL_DELEGATE_OFFSET; ++i) { get_delegate_virtual_invoke_impl (&info, TRUE, - i * SIZEOF_VOID_P); res = g_slist_prepend (res, info); get_delegate_virtual_invoke_impl (&info, FALSE, i * SIZEOF_VOID_P); res = g_slist_prepend (res, info); } return res; } gpointer mono_arch_get_delegate_invoke_impl (MonoMethodSignature *sig, gboolean has_target) { guint8 *code, *start; if (sig->param_count > MAX_ARCH_DELEGATE_PARAMS) return NULL; /* FIXME: Support more cases */ if (MONO_TYPE_ISSTRUCT (sig->ret)) return NULL; /* * The stack contains: * <delegate> * <return addr> */ if (has_target) { static guint8* cached = NULL; if (cached) return cached; if (mono_aot_only) { start = mono_aot_get_trampoline ("delegate_invoke_impl_has_target"); } else { MonoTrampInfo *info; start = get_delegate_invoke_impl (&info, TRUE, 0); mono_tramp_info_register (info, NULL); } mono_memory_barrier (); cached = start; } else { static guint8* cache [MAX_ARCH_DELEGATE_PARAMS + 1] = {NULL}; int i = 0; for (i = 0; i < sig->param_count; ++i) if (!mono_is_regsize_var (sig->params [i])) return NULL; code = cache [sig->param_count]; if (code) return code; if (mono_aot_only) { char *name = g_strdup_printf ("delegate_invoke_impl_target_%d", sig->param_count); start = mono_aot_get_trampoline (name); g_free (name); } else { MonoTrampInfo *info; start = get_delegate_invoke_impl (&info, FALSE, sig->param_count); mono_tramp_info_register (info, NULL); } mono_memory_barrier (); cache [sig->param_count] = start; } return start; } gpointer mono_arch_get_delegate_virtual_invoke_impl (MonoMethodSignature *sig, MonoMethod *method, int offset, gboolean load_imt_reg) { MonoTrampInfo *info; gpointer code; code = get_delegate_virtual_invoke_impl (&info, load_imt_reg, offset); if (code) mono_tramp_info_register (info, NULL); return code; } mgreg_t mono_arch_context_get_int_reg (MonoContext *ctx, int reg) { switch (reg) { case X86_EAX: return ctx->eax; case X86_EBX: return ctx->ebx; case X86_ECX: return ctx->ecx; case X86_EDX: return ctx->edx; case X86_ESP: return ctx->esp; case X86_EBP: return ctx->ebp; case X86_ESI: return ctx->esi; case X86_EDI: return ctx->edi; default: g_assert_not_reached (); return 0; } } void mono_arch_context_set_int_reg (MonoContext *ctx, int reg, mgreg_t val) { switch (reg) { case X86_EAX: ctx->eax = val; break; case X86_EBX: ctx->ebx = val; break; case X86_ECX: ctx->ecx = val; break; case X86_EDX: ctx->edx = val; break; case X86_ESP: ctx->esp = val; break; case X86_EBP: ctx->ebp = val; break; case X86_ESI: ctx->esi = val; break; case X86_EDI: ctx->edi = val; break; default: g_assert_not_reached (); } } #ifdef MONO_ARCH_SIMD_INTRINSICS static MonoInst* get_float_to_x_spill_area (MonoCompile *cfg) { if (!cfg->fconv_to_r8_x_var) { cfg->fconv_to_r8_x_var = mono_compile_create_var (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL); cfg->fconv_to_r8_x_var->flags |= MONO_INST_VOLATILE; /*FIXME, use the don't regalloc flag*/ } return cfg->fconv_to_r8_x_var; } /* * Convert all fconv opts that MONO_OPT_SSE2 would get wrong. */ void mono_arch_decompose_opts (MonoCompile *cfg, MonoInst *ins) { MonoInst *fconv; int dreg, src_opcode; if (!(cfg->opt & MONO_OPT_SSE2) || !(cfg->opt & MONO_OPT_SIMD) || COMPILE_LLVM (cfg)) return; switch (src_opcode = ins->opcode) { case OP_FCONV_TO_I1: case OP_FCONV_TO_U1: case OP_FCONV_TO_I2: case OP_FCONV_TO_U2: case OP_FCONV_TO_I4: case OP_FCONV_TO_I: break; default: return; } /* dreg is the IREG and sreg1 is the FREG */ MONO_INST_NEW (cfg, fconv, OP_FCONV_TO_R8_X); fconv->klass = NULL; /*FIXME, what can I use here as the Mono.Simd lib might not be loaded yet*/ fconv->sreg1 = ins->sreg1; fconv->dreg = mono_alloc_ireg (cfg); fconv->type = STACK_VTYPE; fconv->backend.spill_var = get_float_to_x_spill_area (cfg); mono_bblock_insert_before_ins (cfg->cbb, ins, fconv); dreg = ins->dreg; NULLIFY_INS (ins); ins->opcode = OP_XCONV_R8_TO_I4; ins->klass = mono_defaults.int32_class; ins->sreg1 = fconv->dreg; ins->dreg = dreg; ins->type = STACK_I4; ins->backend.source_opcode = src_opcode; } #endif /* #ifdef MONO_ARCH_SIMD_INTRINSICS */ void mono_arch_decompose_long_opts (MonoCompile *cfg, MonoInst *long_ins) { MonoInst *ins; int vreg; if (long_ins->opcode == OP_LNEG) { ins = long_ins; MONO_EMIT_NEW_UNALU (cfg, OP_INEG, ins->dreg + 1, ins->sreg1 + 1); MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADC_IMM, ins->dreg + 2, ins->sreg1 + 2, 0); MONO_EMIT_NEW_UNALU (cfg, OP_INEG, ins->dreg + 2, ins->dreg + 2); NULLIFY_INS (ins); return; } #ifdef MONO_ARCH_SIMD_INTRINSICS if (!(cfg->opt & MONO_OPT_SIMD)) return; /*TODO move this to simd-intrinsic.c once we support sse 4.1 dword extractors since we need the runtime caps info */ switch (long_ins->opcode) { case OP_EXTRACT_I8: vreg = long_ins->sreg1; if (long_ins->inst_c0) { MONO_INST_NEW (cfg, ins, OP_PSHUFLED); ins->klass = long_ins->klass; ins->sreg1 = long_ins->sreg1; ins->inst_c0 = 2; ins->type = STACK_VTYPE; ins->dreg = vreg = alloc_ireg (cfg); MONO_ADD_INS (cfg->cbb, ins); } MONO_INST_NEW (cfg, ins, OP_EXTRACT_I4); ins->klass = mono_defaults.int32_class; ins->sreg1 = vreg; ins->type = STACK_I4; ins->dreg = long_ins->dreg + 1; MONO_ADD_INS (cfg->cbb, ins); MONO_INST_NEW (cfg, ins, OP_PSHUFLED); ins->klass = long_ins->klass; ins->sreg1 = long_ins->sreg1; ins->inst_c0 = long_ins->inst_c0 ? 3 : 1; ins->type = STACK_VTYPE; ins->dreg = vreg = alloc_ireg (cfg); MONO_ADD_INS (cfg->cbb, ins); MONO_INST_NEW (cfg, ins, OP_EXTRACT_I4); ins->klass = mono_defaults.int32_class; ins->sreg1 = vreg; ins->type = STACK_I4; ins->dreg = long_ins->dreg + 2; MONO_ADD_INS (cfg->cbb, ins); long_ins->opcode = OP_NOP; break; case OP_INSERTX_I8_SLOW: MONO_INST_NEW (cfg, ins, OP_INSERTX_I4_SLOW); ins->dreg = long_ins->dreg; ins->sreg1 = long_ins->dreg; ins->sreg2 = long_ins->sreg2 + 1; ins->inst_c0 = long_ins->inst_c0 * 2; MONO_ADD_INS (cfg->cbb, ins); MONO_INST_NEW (cfg, ins, OP_INSERTX_I4_SLOW); ins->dreg = long_ins->dreg; ins->sreg1 = long_ins->dreg; ins->sreg2 = long_ins->sreg2 + 2; ins->inst_c0 = long_ins->inst_c0 * 2 + 1; MONO_ADD_INS (cfg->cbb, ins); long_ins->opcode = OP_NOP; break; case OP_EXPAND_I8: MONO_INST_NEW (cfg, ins, OP_ICONV_TO_X); ins->dreg = long_ins->dreg; ins->sreg1 = long_ins->sreg1 + 1; ins->klass = long_ins->klass; ins->type = STACK_VTYPE; MONO_ADD_INS (cfg->cbb, ins); MONO_INST_NEW (cfg, ins, OP_INSERTX_I4_SLOW); ins->dreg = long_ins->dreg; ins->sreg1 = long_ins->dreg; ins->sreg2 = long_ins->sreg1 + 2; ins->inst_c0 = 1; ins->klass = long_ins->klass; ins->type = STACK_VTYPE; MONO_ADD_INS (cfg->cbb, ins); MONO_INST_NEW (cfg, ins, OP_PSHUFLED); ins->dreg = long_ins->dreg; ins->sreg1 = long_ins->dreg;; ins->inst_c0 = 0x44; /*Magic number for swizzling (X,Y,X,Y)*/ ins->klass = long_ins->klass; ins->type = STACK_VTYPE; MONO_ADD_INS (cfg->cbb, ins); long_ins->opcode = OP_NOP; break; } #endif /* MONO_ARCH_SIMD_INTRINSICS */ } /*MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD*/ gpointer mono_arch_install_handler_block_guard (MonoJitInfo *ji, MonoJitExceptionInfo *clause, MonoContext *ctx, gpointer new_value) { int offset; gpointer *sp, old_value; char *bp; offset = clause->exvar_offset; /*Load the spvar*/ bp = MONO_CONTEXT_GET_BP (ctx); sp = *(gpointer*)(bp + offset); old_value = *sp; if (old_value < ji->code_start || (char*)old_value > ((char*)ji->code_start + ji->code_size)) return old_value; *sp = new_value; return old_value; } /* * mono_aot_emit_load_got_addr: * * Emit code to load the got address. * On x86, the result is placed into EBX. */ guint8* mono_arch_emit_load_got_addr (guint8 *start, guint8 *code, MonoCompile *cfg, MonoJumpInfo **ji) { x86_call_imm (code, 0); /* * The patch needs to point to the pop, since the GOT offset needs * to be added to that address. */ if (cfg) mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_GOT_OFFSET, NULL); else *ji = mono_patch_info_list_prepend (*ji, code - start, MONO_PATCH_INFO_GOT_OFFSET, NULL); x86_pop_reg (code, MONO_ARCH_GOT_REG); x86_alu_reg_imm (code, X86_ADD, MONO_ARCH_GOT_REG, 0xf0f0f0f0); return code; } static guint8* emit_load_aotconst (guint8 *start, guint8 *code, MonoCompile *cfg, MonoJumpInfo **ji, int dreg, int tramp_type, gconstpointer target) { if (cfg) mono_add_patch_info (cfg, code - cfg->native_code, tramp_type, target); else g_assert_not_reached (); x86_mov_reg_membase (code, dreg, MONO_ARCH_GOT_REG, 0xf0f0f0f0, 4); return code; } /* * mono_arch_emit_load_aotconst: * * Emit code to load the contents of the GOT slot identified by TRAMP_TYPE and * TARGET from the mscorlib GOT in full-aot code. * On x86, the GOT address is assumed to be in EBX, and the result is placed into * EAX. */ guint8* mono_arch_emit_load_aotconst (guint8 *start, guint8 *code, MonoJumpInfo **ji, int tramp_type, gconstpointer target) { /* Load the mscorlib got address */ x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4); *ji = mono_patch_info_list_prepend (*ji, code - start, tramp_type, target); /* arch_emit_got_access () patches this */ x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0xf0f0f0f0, 4); return code; } /* Can't put this into mini-x86.h */ gpointer mono_x86_get_signal_exception_trampoline (MonoTrampInfo **info, gboolean aot); GSList * mono_arch_get_trampolines (gboolean aot) { MonoTrampInfo *info; GSList *tramps = NULL; mono_x86_get_signal_exception_trampoline (&info, aot); tramps = g_slist_append (tramps, info); return tramps; } /* Soft Debug support */ #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED /* * mono_arch_set_breakpoint: * * Set a breakpoint at the native code corresponding to JI at NATIVE_OFFSET. * The location should contain code emitted by OP_SEQ_POINT. */ void mono_arch_set_breakpoint (MonoJitInfo *ji, guint8 *ip) { guint8 *code = ip + OP_SEQ_POINT_BP_OFFSET; g_assert (code [0] == 0x90); x86_call_membase (code, X86_ECX, 0); } /* * mono_arch_clear_breakpoint: * * Clear the breakpoint at IP. */ void mono_arch_clear_breakpoint (MonoJitInfo *ji, guint8 *ip) { guint8 *code = ip + OP_SEQ_POINT_BP_OFFSET; int i; for (i = 0; i < 2; ++i) x86_nop (code); } /* * mono_arch_start_single_stepping: * * Start single stepping. */ void mono_arch_start_single_stepping (void) { ss_trampoline = mini_get_single_step_trampoline (); } /* * mono_arch_stop_single_stepping: * * Stop single stepping. */ void mono_arch_stop_single_stepping (void) { ss_trampoline = NULL; } /* * mono_arch_is_single_step_event: * * Return whenever the machine state in SIGCTX corresponds to a single * step event. */ gboolean mono_arch_is_single_step_event (void *info, void *sigctx) { /* We use soft breakpoints */ return FALSE; } gboolean mono_arch_is_breakpoint_event (void *info, void *sigctx) { /* We use soft breakpoints */ return FALSE; } #define BREAKPOINT_SIZE 2 /* * mono_arch_skip_breakpoint: * * See mini-amd64.c for docs. */ void mono_arch_skip_breakpoint (MonoContext *ctx, MonoJitInfo *ji) { g_assert_not_reached (); } /* * mono_arch_skip_single_step: * * See mini-amd64.c for docs. */ void mono_arch_skip_single_step (MonoContext *ctx) { g_assert_not_reached (); } /* * mono_arch_get_seq_point_info: * * See mini-amd64.c for docs. */ gpointer mono_arch_get_seq_point_info (MonoDomain *domain, guint8 *code) { NOT_IMPLEMENTED; return NULL; } void mono_arch_init_lmf_ext (MonoLMFExt *ext, gpointer prev_lmf) { ext->lmf.previous_lmf = (gsize)prev_lmf; /* Mark that this is a MonoLMFExt */ ext->lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext->lmf.previous_lmf) | 2); ext->lmf.ebp = (gssize)ext; } #endif gboolean mono_arch_opcode_supported (int opcode) { switch (opcode) { case OP_ATOMIC_ADD_I4: case OP_ATOMIC_EXCHANGE_I4: case OP_ATOMIC_CAS_I4: case OP_ATOMIC_LOAD_I1: case OP_ATOMIC_LOAD_I2: case OP_ATOMIC_LOAD_I4: case OP_ATOMIC_LOAD_U1: case OP_ATOMIC_LOAD_U2: case OP_ATOMIC_LOAD_U4: case OP_ATOMIC_LOAD_R4: case OP_ATOMIC_LOAD_R8: case OP_ATOMIC_STORE_I1: case OP_ATOMIC_STORE_I2: case OP_ATOMIC_STORE_I4: case OP_ATOMIC_STORE_U1: case OP_ATOMIC_STORE_U2: case OP_ATOMIC_STORE_U4: case OP_ATOMIC_STORE_R4: case OP_ATOMIC_STORE_R8: return TRUE; default: return FALSE; } } #if defined(ENABLE_GSHAREDVT) #include "../../../mono-extensions/mono/mini/mini-x86-gsharedvt.c" #endif /* !MONOTOUCH */
949014.c
//Classification: #default/p/BO/UVIA/dA/D(A(v))/fr/ln //Written by: Sergey Pomelov //Reviewed by: Igor Eremeev //Comment: #include <stdio.h> #include <malloc.h> int *func(int *q) { int i = 31; q[i] = 2*i; return q; } int main(void) { int* a; if((a = (int*)malloc(32*sizeof(int)))==NULL) { printf("malloc error"); return 1; } printf("%d",*(func(a)+31)); free(a); return 0; }
193135.c
/* $OpenBSD: rom.c,v 1.5 2011/03/13 00:13:53 deraadt Exp $ */ /* $NetBSD: rom.c,v 1.3 2000/07/19 00:58:25 matt Exp $ */ /* * Copyright (c) 1996 Ludd, University of Lule}, Sweden. * All rights reserved. * * This code is derived from software contributed to Ludd by * Bertram Barth. * * 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 at Ludd, University of * Lule}, Sweden and its contributors. * 4. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "sys/param.h" #include "sys/reboot.h" #include "sys/disklabel.h" #include "lib/libsa/stand.h" #include "lib/libsa/ufs.h" #include "../include/pte.h" #include "../include/sid.h" #include "../include/mtpr.h" #include "../include/reg.h" #include "../include/rpb.h" #include "data.h" #include "vaxstand.h" static struct disklabel romlabel; static char io_buf[DEV_BSIZE]; static struct bqo *bqo; static int dpart, dunit; int romopen(struct open_file *f, int adapt, int ctlr, int unit, int part) { char *msg; struct disklabel *lp = &romlabel; size_t i; int err; bqo = (void *)bootrpb.iovec; if (bootrpb.unit > 0 && (bootrpb.unit % 100) == 0) { printf ("changing bootrpb.unit from %d ", bootrpb.unit); bootrpb.unit /= 100; printf ("to %d\n", bootrpb.unit); } bzero(lp, sizeof(struct disklabel)); dunit = unit; dpart = part; err = romstrategy(0, F_READ, LABELSECTOR, DEV_BSIZE, io_buf, &i); if (err) { printf("reading disklabel: %s\n",strerror(err)); return 0; } msg = getdisklabel(io_buf+LABELOFFSET, lp); if (msg) printf("getdisklabel: %s\n",msg); return(0); } int romwrite_uvax(int, int, void *, struct rpb *); int romread_uvax(int, int, void *, struct rpb *); int romstrategy (f, func, dblk, size, buf, rsize) void *f; int func; daddr32_t dblk; size_t size; void *buf; size_t *rsize; { struct disklabel *lp; int block; lp = &romlabel; block = dblk + lp->d_partitions[dpart].p_offset; if (dunit >= 0 && dunit < 10) bootrpb.unit = dunit; if (func == F_WRITE) romwrite_uvax(block, size, buf, &bootrpb); else romread_uvax(block, size, buf, &bootrpb); *rsize = size; return 0; }
513591.c
/* Part of SWI-Prolog Author: Jan Wielemaker E-mail: [email protected] WWW: http://www.swi-prolog.org Copyright (c) 2019, University of Amsterdam VU University Amsterdam CWI, Amsterdam All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "pl-incl.h" #include "pl-comp.h" #include "pl-wrap.h" #include "pl-dbref.h" #include "pl-util.h" #include "pl-supervisor.h" #include "pl-proc.h" #include "pl-gc.h" #include "pl-fli.h" #include "pl-funct.h" /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Wrap and unwrap predicates. Wrapping is realised by manipulating the predicate _supervisor_: - The wrapped predicate P gets a new supervisor that calls a dedicated clause in '$wrap$P'. - This clause may use call(Closure, Arg ...), where Closure is a blob that contains a predicate (struct definition) that is a copy of P which contains - A pointer to P in impl.wrapped.predicate - A pointer to P's supervisor in impl.wrapped.supervisor - A supervisor running S_WRAP. - I_USERCALLN picks up call(Closure, Arg ...) and sets up a call using the closure's copy. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /******************************* * CLOSURES * *******************************/ static int write_closure(IOSTREAM *s, atom_t aref, int flags) { closure *c = PL_blob_data(aref, NULL, NULL); (void)flags; Sfprintf(s, "<closure>(%s)", predicateName(&c->def)); return TRUE; } static void acquire_closure(atom_t aref) { closure *c = PL_blob_data(aref, NULL, NULL); (void)c; } static int release_closure(atom_t aref) { closure *c = PL_blob_data(aref, NULL, NULL); (void) c; return TRUE; } static int save_closure(atom_t aref, IOSTREAM *fd) { closure *c = PL_blob_data(aref, NULL, NULL); (void)fd; return PL_warning("Cannot save closure <closure>(%s)", predicateName(&c->def)); } static atom_t load_closure(IOSTREAM *fd) { (void)fd; return PL_new_atom("<saved-closure>"); } PL_blob_t _PL_closure_blob = { PL_BLOB_MAGIC, PL_BLOB_UNIQUE, "closure", release_closure, NULL, write_closure, acquire_closure, save_closure, load_closure }; static int unify_closure(term_t t, Definition def, Code supervisor) { closure c; c.def = *def; c.def.impl.wrapped.predicate = def; c.def.impl.wrapped.supervisor = supervisor; c.def.codes = SUPERVISOR(wrapper); return PL_unify_blob(t, &c, sizeof(c), &_PL_closure_blob); } /** get_closure_predicate(term_t t, Definition *def) * Get the predicate that is referenced by a closure. Fails silently * if t is not a closure. */ int get_closure_predicate(DECL_LD term_t t, Definition *def) { void *data; PL_blob_t *type; if ( PL_get_blob(t, &data, NULL, &type) && type == &_PL_closure_blob ) { closure *c = data; *def = c->def.impl.wrapped.predicate; return TRUE; } return FALSE; } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Called from freeCodesDefinition() to reset the eventually wrapped supervisor to S_VIRGIN after a change to the wrapped predicate. S_WRAP will eventually trap this and re-create an appropriate new supervisor. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ void resetWrappedSupervisor(Definition def0) { Definition def = def0; Code codes = def->codes; while ( codes[0] == encode(S_CALLWRAPPER) ) { closure *c = PL_blob_data(codes[2], NULL, NULL); def = &c->def; codes = c->def.impl.wrapped.supervisor; } assert(def != def0); def->impl.wrapped.supervisor = SUPERVISOR(virgin); freeSupervisor(def, codes, TRUE); /* is this the right def? */ } static Code find_wrapper(Definition def, atom_t name) { Code codes = def->codes; while ( codes[0] == encode(S_CALLWRAPPER) ) { closure *c; if ( codes[3] == (code)name ) return codes; c = PL_blob_data(codes[2], NULL, NULL); codes = c->def.impl.wrapped.supervisor; } return NULL; } #define assert_wrapper(clause) LDFUNC(assert_wrapper, clause) static ClauseRef assert_wrapper(DECL_LD term_t clause) { Clause cl; if ( (cl = assert_term(clause, NULL, CL_END, NULL_ATOM, NULL, 0)) ) { Definition def = cl->predicate; definition_ref *dref = pushPredicateAccessObj(def); ClauseRef cref; if ( !dref ) { retractClauseDefinition(def, cl, FALSE); return NULL; } acquire_def(def); for( cref = def->impl.clauses.first_clause; cref; cref = cref->next) { if ( cref->value.clause == cl ) break; } release_def(def); popPredicateAccess(def); assert(cref && cref->value.clause == cl); return cref; } return NULL; } #define unify_wrapped(wrapped, closure, head) LDFUNC(unify_wrapped, wrapped, closure, head) static int unify_wrapped(DECL_LD term_t wrapped, atom_t closure, term_t head) { Word from; retry: from = valTermRef(head); deRef(from); if ( isTerm(*from) ) { Functor fd = valueTerm(*from); size_t arity = arityFunctor(fd->definition); if ( hasGlobalSpace(arity+1) ) /* ensure space for unify */ { Word to = allocGlobalNoShift(arity+1); word w = consPtr(to, TAG_COMPOUND|STG_GLOBAL); Word f = fd->arguments; *to++ = PL_new_functor(closure, arity); for(; arity > 0; arity--) *to++ = linkValI(f++); return _PL_unify_atomic(wrapped, w); } else { int rc; if ( (rc = ensureGlobalSpace(1+arity, ALLOW_GC)) == TRUE ) goto retry; return raiseStackOverflow(rc); } } else { return PL_unify_atom(wrapped, closure); } } /******************************* * PROLOG * *******************************/ /** '$c_wrap_predicate'(:Head, +Name, -Closure, -Wrapped, +Body) * * Install a wrapper for the predicate Head */ static PRED_IMPL("$c_wrap_predicate", 5, c_wrap_predicate, PL_FA_TRANSPARENT) { PRED_LD Procedure proc; atom_t wname; Code codes = NULL; term_t head = PL_new_term_ref(); term_t closure = A3; if ( !PL_get_atom_ex(A2, &wname) || !get_procedure(A1, &proc, head, GP_DEFINE) ) return FALSE; if ( (codes = find_wrapper(proc->definition, wname)) ) { ClauseRef cref; atom_t aref = (atom_t)codes[2]; if ( !PL_unify_atom(closure, aref) || !unify_wrapped(A4, aref, head) ) return FALSE; if ( (cref = assert_wrapper(A5)) ) { Clause cl = ((ClauseRef)codes[1])->value.clause; codes[1] = (code)cref; retractClauseDefinition(cl->predicate, cl, FALSE); return TRUE; } } else { if ( unify_closure(closure, proc->definition, proc->definition->codes) ) { ClauseRef cref; atom_t aref; if ( !PL_get_atom_ex(closure, &aref) || !unify_wrapped(A4, aref, head) ) return FALSE; /* something really wrong */ if ( (cref = assert_wrapper(A5)) ) { codes = allocCodes(4); PL_register_atom(aref); PL_register_atom(wname); codes[0] = encode(S_CALLWRAPPER); codes[1] = (code)cref; codes[2] = (code)aref; codes[3] = (code)wname; proc->definition->codes = codes; return TRUE; } } } return FALSE; } /** * wrapped_predicate(:Head, -Wrappers) */ static PRED_IMPL("wrapped_predicate", 2, wrapped_predicate, PL_FA_TRANSPARENT) { PRED_LD Procedure proc; if ( get_procedure(A1, &proc, 0, GP_RESOLVE) ) { Definition def = proc->definition; Code codes = def->codes; if ( def->codes[0] == encode(S_CALLWRAPPER) ) { term_t tail = PL_copy_term_ref(A2); term_t head = PL_new_term_ref(); term_t ct = PL_new_term_ref(); for(;;) { closure *c = PL_blob_data(codes[2], NULL, NULL); ClauseRef cref = (ClauseRef)codes[1]; if ( !PL_put_clref(ct, cref->value.clause) || !PL_unify_list(tail, head, tail) || !PL_unify_term(head, PL_FUNCTOR, FUNCTOR_minus2, PL_ATOM, codes[3], PL_TERM, ct) ) return FALSE; codes = c->def.impl.wrapped.supervisor; if ( codes[0] != encode(S_CALLWRAPPER) ) return PL_unify_nil(tail); } } } return FALSE; } /** '$wrapped_implementation'(:Goal, +Name, -Wrapped) * * Calling Wrapped calls the predicate referenced by Goal as seen * from the wrapper Name. */ static PRED_IMPL("$wrapped_implementation", 3, wrapped_implementation, PL_FA_TRANSPARENT) { PRED_LD Procedure proc; atom_t wname; Code codes; term_t head = PL_new_term_ref(); if ( !PL_get_atom_ex(A2, &wname) || !get_procedure(A1, &proc, head, GP_RESOLVE) ) return FALSE; if ( (codes = find_wrapper(proc->definition, wname)) ) { atom_t aref = codes[2]; size_t arity = proc->definition->functor->arity; if ( arity > 0 ) { Word p; term_t impl = PL_new_term_ref(); if ( (p=allocGlobal(1+arity)) ) { Word a = valTermRef(head); size_t i; deRef(a); a = valueTerm(*a)->arguments; p[0] = lookupFunctorDef(aref, arity); for(i=0; i<arity; i++) p[i+1] = linkValI(&a[i]); *valTermRef(impl) = consPtr(p, TAG_COMPOUND|STG_GLOBAL); return PL_unify(A3, impl); } } else { return PL_unify_atom(A3, aref); } } return FALSE; } /** * unwrap_predicate(:Head, ?Name) is semidet. * * Remove the latest wrapper. Should we removing a specifically named * supervisor? */ static PRED_IMPL("unwrap_predicate", 2, uwrap_predicate, PL_FA_TRANSPARENT) { PRED_LD Procedure proc; if ( get_procedure(A1, &proc, 0, GP_NAMEARITY|GP_RESOLVE) ) { Definition def = proc->definition; Code *cp = &def->codes; Code codes = *cp; while ( codes[0] == encode(S_CALLWRAPPER) ) { ClauseRef cref = (ClauseRef)codes[1]; Clause cl = cref->value.clause; atom_t aref = (atom_t)codes[2]; atom_t wname = (atom_t)codes[3]; closure *cls = PL_blob_data(aref, NULL, NULL); if ( !PL_unify_atom(A2, wname) ) { cp = &cls->def.impl.wrapped.supervisor; codes = *cp; continue; } retractClauseDefinition(cl->predicate, cl, FALSE); *cp = cls->def.impl.wrapped.supervisor; freeSupervisor(def, codes, TRUE); PL_unregister_atom(aref); PL_unregister_atom(wname); return TRUE; } } return FALSE; } static PRED_IMPL("$closure_predicate", 2, closure_predicate, 0) { void *data; PL_blob_t *type; if ( PL_get_blob(A1, &data, NULL, &type) && type == &_PL_closure_blob ) { closure *c = data; return unify_definition(MODULE_user, A2, &c->def, 0, GP_QUALIFY|GP_NAMEARITY); } return PL_type_error("closure", A1); } /******************************* * PUBLISH PREDICATES * *******************************/ #define META PL_FA_TRANSPARENT BeginPredDefs(wrap) PRED_DEF("$c_wrap_predicate", 5, c_wrap_predicate, META) PRED_DEF("unwrap_predicate", 2, uwrap_predicate, META) PRED_DEF("$wrapped_predicate", 2, wrapped_predicate, META) PRED_DEF("$wrapped_implementation", 3, wrapped_implementation, META) PRED_DEF("$closure_predicate", 2, closure_predicate, 0) EndPredDefs
267.c
/* * $Id: pptpd-logwtmp.c,v 1.4 2005/08/03 09:10:59 quozl Exp $ * pptpd-logwtmp.c - pppd plugin to update wtmp for a pptpd user * * Copyright 2004 James Cameron. * * 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 <unistd.h> #include <utmp.h> #include <string.h> #include "pppd.h" #include "config.h" char pppd_version[] = PPPD_VERSION; static char pptpd_original_ip[PATH_MAX+1]; static bool pptpd_logwtmp_strip_domain = 0; static option_t options[] = { { "pptpd-original-ip", o_string, pptpd_original_ip, "Original IP address of the PPTP connection", OPT_STATIC, NULL, PATH_MAX }, { "pptpd-logwtmp-strip-domain", o_bool, &pptpd_logwtmp_strip_domain, "Strip domain from username before logging", OPT_PRIO | 1 }, { NULL } }; static void ip_up(void *opaque, int arg) { char *user = peer_authname; if (pptpd_logwtmp_strip_domain) { char *sep = strstr(user, "//"); if (sep != NULL) user = sep + 2; } if (debug) notice("pptpd-logwtmp.so ip-up %s %s %s", ifname, user, pptpd_original_ip); logwtmp(ifname, user, pptpd_original_ip); } static void ip_down(void *opaque, int arg) { if (debug) notice("pptpd-logwtmp.so ip-down %s", ifname); logwtmp(ifname, "", ""); } void plugin_init(void) { add_options(options); add_notifier(&ip_up_notifier, ip_up, NULL); add_notifier(&ip_down_notifier, ip_down, NULL); if (debug) notice("pptpd-logwtmp: $Version$"); }
867727.c
// SoftEther VPN Source Code // Cedar Communication Module // // SoftEther VPN Server, Client and Bridge are free software under GPLv2. // // Copyright (c) 2012-2015 Daiyuu Nobori. // Copyright (c) 2012-2015 SoftEther VPN Project, University of Tsukuba, Japan. // Copyright (c) 2012-2015 SoftEther Corporation. // // All Rights Reserved. // // http://www.softether.org/ // // Author: Daiyuu Nobori // Comments: Tetsuo Sugiyama, Ph.D. // // 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. // // You should have received a copy of the GNU General Public License version 2 // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // 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. // // THE LICENSE AGREEMENT IS ATTACHED ON THE SOURCE-CODE PACKAGE // AS "LICENSE.TXT" FILE. READ THE TEXT FILE IN ADVANCE TO USE THE SOFTWARE. // // // THIS SOFTWARE IS DEVELOPED IN JAPAN, AND DISTRIBUTED FROM JAPAN, // UNDER JAPANESE LAWS. YOU MUST AGREE IN ADVANCE TO USE, COPY, MODIFY, // MERGE, PUBLISH, DISTRIBUTE, SUBLICENSE, AND/OR SELL COPIES OF THIS // SOFTWARE, THAT ANY JURIDICAL DISPUTES WHICH ARE CONCERNED TO THIS // SOFTWARE OR ITS CONTENTS, AGAINST US (SOFTETHER PROJECT, SOFTETHER // CORPORATION, DAIYUU NOBORI OR OTHER SUPPLIERS), OR ANY JURIDICAL // DISPUTES AGAINST US WHICH ARE CAUSED BY ANY KIND OF USING, COPYING, // MODIFYING, MERGING, PUBLISHING, DISTRIBUTING, SUBLICENSING, AND/OR // SELLING COPIES OF THIS SOFTWARE SHALL BE REGARDED AS BE CONSTRUED AND // CONTROLLED BY JAPANESE LAWS, AND YOU MUST FURTHER CONSENT TO // EXCLUSIVE JURISDICTION AND VENUE IN THE COURTS SITTING IN TOKYO, // JAPAN. YOU MUST WAIVE ALL DEFENSES OF LACK OF PERSONAL JURISDICTION // AND FORUM NON CONVENIENS. PROCESS MAY BE SERVED ON EITHER PARTY IN // THE MANNER AUTHORIZED BY APPLICABLE LAW OR COURT RULE. // // USE ONLY IN JAPAN. DO NOT USE THIS SOFTWARE IN ANOTHER COUNTRY UNLESS // YOU HAVE A CONFIRMATION THAT THIS SOFTWARE DOES NOT VIOLATE ANY // CRIMINAL LAWS OR CIVIL RIGHTS IN THAT PARTICULAR COUNTRY. USING THIS // SOFTWARE IN OTHER COUNTRIES IS COMPLETELY AT YOUR OWN RISK. THE // SOFTETHER VPN PROJECT HAS DEVELOPED AND DISTRIBUTED THIS SOFTWARE TO // COMPLY ONLY WITH THE JAPANESE LAWS AND EXISTING CIVIL RIGHTS INCLUDING // PATENTS WHICH ARE SUBJECTS APPLY IN JAPAN. OTHER COUNTRIES' LAWS OR // CIVIL RIGHTS ARE NONE OF OUR CONCERNS NOR RESPONSIBILITIES. WE HAVE // NEVER INVESTIGATED ANY CRIMINAL REGULATIONS, CIVIL LAWS OR // INTELLECTUAL PROPERTY RIGHTS INCLUDING PATENTS IN ANY OF OTHER 200+ // COUNTRIES AND TERRITORIES. BY NATURE, THERE ARE 200+ REGIONS IN THE // WORLD, WITH DIFFERENT LAWS. IT IS IMPOSSIBLE TO VERIFY EVERY // COUNTRIES' LAWS, REGULATIONS AND CIVIL RIGHTS TO MAKE THE SOFTWARE // COMPLY WITH ALL COUNTRIES' LAWS BY THE PROJECT. EVEN IF YOU WILL BE // SUED BY A PRIVATE ENTITY OR BE DAMAGED BY A PUBLIC SERVANT IN YOUR // COUNTRY, THE DEVELOPERS OF THIS SOFTWARE WILL NEVER BE LIABLE TO // RECOVER OR COMPENSATE SUCH DAMAGES, CRIMINAL OR CIVIL // RESPONSIBILITIES. NOTE THAT THIS LINE IS NOT LICENSE RESTRICTION BUT // JUST A STATEMENT FOR WARNING AND DISCLAIMER. // // // SOURCE CODE CONTRIBUTION // ------------------------ // // Your contribution to SoftEther VPN Project is much appreciated. // Please send patches to us through GitHub. // Read the SoftEther VPN Patch Acceptance Policy in advance: // http://www.softether.org/5-download/src/9.patch // // // DEAR SECURITY EXPERTS // --------------------- // // If you find a bug or a security vulnerability please kindly inform us // about the problem immediately so that we can fix the security problem // to protect a lot of users around the world as soon as possible. // // Our e-mail address for security reports is: // softether-vpn-security [at] softether.org // // Please note that the above e-mail address is not a technical support // inquiry address. If you need technical assistance, please visit // http://www.softether.org/ and ask your question on the users forum. // // Thank you for your cooperation. // // // NO MEMORY OR RESOURCE LEAKS // --------------------------- // // The memory-leaks and resource-leaks verification under the stress // test has been passed before release this source code. // Server.c // VPN Server module #include "CedarPch.h" static SERVER *server = NULL; static LOCK *server_lock = NULL; char *SERVER_CONFIG_FILE_NAME = "@vpn_server.config"; char *SERVER_CONFIG_FILE_NAME_IN_CLIENT = "@vpn_gate_svc.config"; char *SERVER_CONFIG_FILE_NAME_IN_CLIENT_RELAY = "@vpn_gate_relay.config"; char *BRIDGE_CONFIG_FILE_NAME = "@vpn_bridge.config"; char *SERVER_CONFIG_TEMPLATE_NAME = "@vpn_server_template.config"; char *BRIDGE_CONFIG_TEMPLATE_NAME = "@vpn_server_template.config"; static bool server_reset_setting = false; static volatile UINT global_server_flags[NUM_GLOBAL_SERVER_FLAGS] = {0}; UINT vpn_global_parameters[NUM_GLOBAL_PARAMS] = {0}; // Set the OpenVPN and SSTP setting void SiSetOpenVPNAndSSTPConfig(SERVER *s, OPENVPN_SSTP_CONFIG *c) { // Validate arguments if (s == NULL || c == NULL) { return; } Lock(s->OpenVpnSstpConfigLock); { // Save the settings if (s->Cedar->Bridge || s->ServerType != SERVER_TYPE_STANDALONE) { s->DisableSSTPServer = true; s->DisableOpenVPNServer = true; } else { s->DisableSSTPServer = !c->EnableSSTP; s->DisableOpenVPNServer = !c->EnableOpenVPN; } NormalizeIntListStr(s->OpenVpnServerUdpPorts, sizeof(s->OpenVpnServerUdpPorts), c->OpenVPNPortList, true, ", "); // Apply the OpenVPN configuration if (s->OpenVpnServerUdp != NULL) { if (s->DisableOpenVPNServer) { OvsApplyUdpPortList(s->OpenVpnServerUdp, ""); } else { OvsApplyUdpPortList(s->OpenVpnServerUdp, s->OpenVpnServerUdpPorts); } } } Unlock(s->OpenVpnSstpConfigLock); } // Get the OpenVPN and SSTP setting void SiGetOpenVPNAndSSTPConfig(SERVER *s, OPENVPN_SSTP_CONFIG *c) { // Validate arguments if (s == NULL || c == NULL) { return; } Zero(c, sizeof(OPENVPN_SSTP_CONFIG)); Lock(s->OpenVpnSstpConfigLock); { if (s->DisableOpenVPNServer == false) { c->EnableOpenVPN = true; } if (s->DisableSSTPServer == false) { c->EnableSSTP = true; } StrCpy(c->OpenVPNPortList, sizeof(c->OpenVPNPortList), s->OpenVpnServerUdpPorts); } Unlock(s->OpenVpnSstpConfigLock); } // Get whether the number of user objects that are registered in the VPN Server is too many bool SiTooManyUserObjectsInServer(SERVER *s, bool oneMore) { return false; } // Get the number of user objects that are registered in the VPN Server UINT SiGetServerNumUserObjects(SERVER *s) { CEDAR *c; UINT ret = 0; // Validate arguments if (s == NULL) { return 0; } c = s->Cedar; LockList(c->HubList); { UINT i; for (i = 0;i < LIST_NUM(c->HubList);i++) { HUB *h = LIST_DATA(c->HubList, i); if (h->HubDb != NULL) { ret += LIST_NUM(h->HubDb->UserList); } } } UnlockList(c->HubList); return ret; } typedef struct SI_DEBUG_PROC_LIST { UINT Id; char *Description; char *Args; SI_DEBUG_PROC *Proc; } SI_DEBUG_PROC_LIST; // Debugging function UINT SiDebug(SERVER *s, RPC_TEST *ret, UINT i, char *str) { SI_DEBUG_PROC_LIST proc_list[] = { {1, "Hello World", "<test string>", SiDebugProcHelloWorld}, {2, "Terminate process now", "", SiDebugProcExit}, {3, "Write memory dumpfile", "", SiDebugProcDump}, {4, "Restore process priority", "", SiDebugProcRestorePriority}, {5, "Set the process priority high", "", SiDebugProcSetHighPriority}, {6, "Get the .exe filename of the process", "", SiDebugProcGetExeFileName}, {7, "Crash the process", "", SiDebugProcCrash}, {8, "Get IPsecMessageDisplayed Flag", "", SiDebugProcGetIPsecMessageDisplayedValue}, {9, "Set IPsecMessageDisplayed Flag", "", SiDebugProcSetIPsecMessageDisplayedValue}, {10, "Get VgsMessageDisplayed Flag", "", SiDebugProcGetVgsMessageDisplayedValue}, {11, "Set VgsMessageDisplayed Flag", "", SiDebugProcSetVgsMessageDisplayedValue}, {12, "Get the current TCP send queue length", "", SiDebugProcGetCurrentTcpSendQueueLength}, {13, "Get the current GetIP thread count", "", SiDebugProcGetCurrentGetIPThreadCount}, }; UINT num_proc_list = sizeof(proc_list) / sizeof(proc_list[0]); UINT j; UINT ret_value = ERR_NO_ERROR; // Validate arguments if (s == NULL || ret == NULL) { return ERR_INVALID_PARAMETER; } if (i == 0) { char tmp[MAX_SIZE]; Zero(ret, sizeof(RPC_TEST)); StrCat(ret->StrValue, sizeof(ret->StrValue), "\n--- Debug Functions List --\n"); for (j = 0;j < num_proc_list;j++) { SI_DEBUG_PROC_LIST *p = &proc_list[j]; if (IsEmptyStr(p->Args) == false) { Format(tmp, sizeof(tmp), " %u: %s - Usage: %u /ARG:\"%s\"\n", p->Id, p->Description, p->Id, p->Args); } else { Format(tmp, sizeof(tmp), " %u: %s - Usage: %u\n", p->Id, p->Description, p->Id); } StrCat(ret->StrValue, sizeof(ret->StrValue), tmp); } } else { ret_value = ERR_NOT_SUPPORTED; for (j = 0;j < num_proc_list;j++) { SI_DEBUG_PROC_LIST *p = &proc_list[j]; if (p->Id == i) { ret_value = p->Proc(s, str, ret->StrValue, sizeof(ret->StrValue)); if (ret_value == ERR_NO_ERROR && IsEmptyStr(ret->StrValue)) { StrCpy(ret->StrValue, sizeof(ret->StrValue), "Ok."); } break; } } } return ret_value; } UINT SiDebugProcHelloWorld(SERVER *s, char *in_str, char *ret_str, UINT ret_str_size) { // Validate arguments if (s == NULL || in_str == NULL || ret_str == NULL) { return ERR_INVALID_PARAMETER; } Format(ret_str, ret_str_size, "Hello World %s\n", in_str); return ERR_NO_ERROR; } UINT SiDebugProcExit(SERVER *s, char *in_str, char *ret_str, UINT ret_str_size) { // Validate arguments if (s == NULL || in_str == NULL || ret_str == NULL) { return ERR_INVALID_PARAMETER; } _exit(1); return ERR_NO_ERROR; } UINT SiDebugProcDump(SERVER *s, char *in_str, char *ret_str, UINT ret_str_size) { // Validate arguments if (s == NULL || in_str == NULL || ret_str == NULL) { return ERR_INVALID_PARAMETER; } #ifdef OS_WIN32 MsWriteMinidump(NULL, NULL); #else // OS_WIN32 return ERR_NOT_SUPPORTED; #endif // OS_WIN32 return ERR_NO_ERROR; } UINT SiDebugProcRestorePriority(SERVER *s, char *in_str, char *ret_str, UINT ret_str_size) { // Validate arguments if (s == NULL || in_str == NULL || ret_str == NULL) { return ERR_INVALID_PARAMETER; } OSRestorePriority(); return ERR_NO_ERROR; } UINT SiDebugProcSetHighPriority(SERVER *s, char *in_str, char *ret_str, UINT ret_str_size) { // Validate arguments if (s == NULL || in_str == NULL || ret_str == NULL) { return ERR_INVALID_PARAMETER; } OSSetHighPriority(); return ERR_NO_ERROR; } UINT SiDebugProcGetExeFileName(SERVER *s, char *in_str, char *ret_str, UINT ret_str_size) { // Validate arguments if (s == NULL || in_str == NULL || ret_str == NULL) { return ERR_INVALID_PARAMETER; } GetExeName(ret_str, ret_str_size); return ERR_NO_ERROR; } UINT SiDebugProcCrash(SERVER *s, char *in_str, char *ret_str, UINT ret_str_size) { // Validate arguments if (s == NULL || in_str == NULL || ret_str == NULL) { return ERR_INVALID_PARAMETER; } CrashNow(); return ERR_NO_ERROR; } UINT SiDebugProcGetIPsecMessageDisplayedValue(SERVER *s, char *in_str, char *ret_str, UINT ret_str_size) { // Validate arguments if (s == NULL || in_str == NULL || ret_str == NULL) { return ERR_INVALID_PARAMETER; } ToStr(ret_str, s->IPsecMessageDisplayed); return ERR_NO_ERROR; } UINT SiDebugProcSetIPsecMessageDisplayedValue(SERVER *s, char *in_str, char *ret_str, UINT ret_str_size) { // Validate arguments if (s == NULL || in_str == NULL || ret_str == NULL) { return ERR_INVALID_PARAMETER; } s->IPsecMessageDisplayed = ToInt(in_str); return ERR_NO_ERROR; } UINT SiDebugProcGetVgsMessageDisplayedValue(SERVER *s, char *in_str, char *ret_str, UINT ret_str_size) { // Validate arguments if (s == NULL || in_str == NULL || ret_str == NULL) { return ERR_INVALID_PARAMETER; } #if 0 if (VgDoNotPopupMessage() == false) { ToStr(ret_str, s->VgsMessageDisplayed); } else { ToStr(ret_str, 1); } #else // Do not show the VGS message in VPN Server of the current version ToStr(ret_str, 1); #endif return ERR_NO_ERROR; } UINT SiDebugProcGetCurrentTcpSendQueueLength(SERVER *s, char *in_str, char *ret_str, UINT ret_str_size) { char tmp1[64], tmp2[64], tmp3[64]; // Validate arguments if (s == NULL || in_str == NULL || ret_str == NULL) { return ERR_INVALID_PARAMETER; } ToStr3(tmp1, 0, CedarGetCurrentTcpQueueSize(s->Cedar)); ToStr3(tmp2, 0, CedarGetQueueBudgetConsuming(s->Cedar)); ToStr3(tmp3, 0, CedarGetFifoBudgetConsuming(s->Cedar)); Format(ret_str, 0, "CurrentTcpQueueSize = %s\n" "QueueBudgetConsuming = %s\n" "FifoBudgetConsuming = %s\n", tmp1, tmp2, tmp3); return ERR_NO_ERROR; } UINT SiDebugProcGetCurrentGetIPThreadCount(SERVER *s, char *in_str, char *ret_str, UINT ret_str_size) { char tmp1[64], tmp2[64]; // Validate arguments if (s == NULL || in_str == NULL || ret_str == NULL) { return ERR_INVALID_PARAMETER; } ToStr3(tmp1, 0, GetCurrentGetIpThreadNum()); ToStr3(tmp2, 0, GetGetIpThreadMaxNum()); Format(ret_str, 0, "Current threads = %s\n" "Quota = %s\n", tmp1, tmp2); return ERR_NO_ERROR; } UINT SiDebugProcSetVgsMessageDisplayedValue(SERVER *s, char *in_str, char *ret_str, UINT ret_str_size) { // Validate arguments if (s == NULL || in_str == NULL || ret_str == NULL) { return ERR_INVALID_PARAMETER; } return ERR_NO_ERROR; } // Write the debug log void SiDebugLog(SERVER *s, char *msg) { // Validate arguments if (s == NULL || msg == NULL) { return; } if (s->DebugLog != NULL) { WriteTinyLog(s->DebugLog, msg); } } // Deadlock inspection main void SiCheckDeadLockMain(SERVER *s, UINT timeout) { CEDAR *cedar; // Validate arguments if (s == NULL) { return; } //Debug("SiCheckDeadLockMain Start.\n"); cedar = s->Cedar; if (s->ServerListenerList != NULL) { CheckDeadLock(s->ServerListenerList->lock, timeout, "s->ServerListenerList->lock"); } CheckDeadLock(s->lock, timeout, "s->lock"); if (s->FarmMemberList != NULL) { CheckDeadLock(s->FarmMemberList->lock, timeout, "s->FarmMemberList->lock"); } if (s->HubCreateHistoryList != NULL) { CheckDeadLock(s->HubCreateHistoryList->lock, timeout, "s->HubCreateHistoryList->lock"); } CheckDeadLock(s->CapsCacheLock, timeout, "s->CapsCacheLock"); CheckDeadLock(s->TasksFromFarmControllerLock, timeout, "s->TasksFromFarmControllerLock"); if (cedar != NULL) { if (cedar->HubList != NULL) { CheckDeadLock(cedar->HubList->lock, timeout, "cedar->HubList->lock"); } if (cedar->ListenerList != NULL) { UINT i; LIST *o = NewListFast(NULL); CheckDeadLock(cedar->ListenerList->lock, timeout, "cedar->ListenerList->lock"); LockList(cedar->ListenerList); { for (i = 0;i < LIST_NUM(cedar->ListenerList);i++) { LISTENER *r = LIST_DATA(cedar->ListenerList, i); AddRef(r->ref); Add(o, r); } } UnlockList(cedar->ListenerList); for (i = 0;i < LIST_NUM(o);i++) { LISTENER *r = LIST_DATA(o, i); ReleaseListener(r); } ReleaseList(o); } if (cedar->ConnectionList != NULL) { CheckDeadLock(cedar->ConnectionList->lock, timeout, "cedar->ConnectionList->lock"); } if (cedar->CaList != NULL) { CheckDeadLock(cedar->CaList->lock, timeout, "cedar->CaList->lock"); } if (cedar->TrafficLock != NULL) { CheckDeadLock(cedar->TrafficLock, timeout, "cedar->TrafficLock"); } if (cedar->TrafficDiffList != NULL) { CheckDeadLock(cedar->TrafficDiffList->lock, timeout, "cedar->TrafficDiffList->lock"); } if (cedar->LocalBridgeList != NULL) { CheckDeadLock(cedar->LocalBridgeList->lock, timeout, "cedar->LocalBridgeList->lock"); } if (cedar->L3SwList != NULL) { CheckDeadLock(cedar->L3SwList->lock, timeout, "cedar->L3SwList->lock"); } } //Debug("SiCheckDeadLockMain Finish.\n"); } // Deadlock check thread void SiDeadLockCheckThread(THREAD *t, void *param) { SERVER *s = (SERVER *)param; // Validate arguments if (s == NULL || t == NULL) { return; } while (true) { Wait(s->DeadLockWaitEvent, SERVER_DEADLOCK_CHECK_SPAN); if (s->HaltDeadLockThread) { break; } SiCheckDeadLockMain(s, SERVER_DEADLOCK_CHECK_TIMEOUT); } } // Initialize the deadlock check void SiInitDeadLockCheck(SERVER *s) { // Validate arguments if (s == NULL) { return; } if (s->DisableDeadLockCheck) { return; } s->HaltDeadLockThread = false; s->DeadLockWaitEvent = NewEvent(); s->DeadLockCheckThread = NewThread(SiDeadLockCheckThread, s); } // Release the deadlock check void SiFreeDeadLockCheck(SERVER *s) { // Validate arguments if (s == NULL) { return; } if (s->DeadLockCheckThread == NULL) { return; } s->HaltDeadLockThread = true; Set(s->DeadLockWaitEvent); WaitThread(s->DeadLockCheckThread, INFINITE); ReleaseThread(s->DeadLockCheckThread); s->DeadLockCheckThread = NULL; ReleaseEvent(s->DeadLockWaitEvent); s->DeadLockWaitEvent = NULL; s->HaltDeadLockThread = false; } // Check whether the specified virtual HUB has been registered to creation history bool SiIsHubRegistedOnCreateHistory(SERVER *s, char *name) { UINT i; bool ret = false; // Validate arguments if (s == NULL || name == NULL) { return false; } SiDeleteOldHubCreateHistory(s); LockList(s->HubCreateHistoryList); { for (i = 0;i < LIST_NUM(s->HubCreateHistoryList);i++) { SERVER_HUB_CREATE_HISTORY *h = LIST_DATA(s->HubCreateHistoryList, i); if (StrCmpi(h->HubName, name) == 0) { ret = true; break; } } } UnlockList(s->HubCreateHistoryList); return ret; } // Delete the Virtual HUB creation history void SiDelHubCreateHistory(SERVER *s, char *name) { UINT i; // Validate arguments if (s == NULL || name == NULL) { return; } LockList(s->HubCreateHistoryList); { SERVER_HUB_CREATE_HISTORY *hh = NULL; for (i = 0;i < LIST_NUM(s->HubCreateHistoryList);i++) { SERVER_HUB_CREATE_HISTORY *h = LIST_DATA(s->HubCreateHistoryList, i); if (StrCmpi(h->HubName, name) == 0) { Delete(s->HubCreateHistoryList, h); Free(h); break; } } } UnlockList(s->HubCreateHistoryList); SiDeleteOldHubCreateHistory(s); } // Register to the Virtual HUB creation history void SiAddHubCreateHistory(SERVER *s, char *name) { UINT i; // Validate arguments if (s == NULL || name == NULL) { return; } LockList(s->HubCreateHistoryList); { SERVER_HUB_CREATE_HISTORY *hh = NULL; for (i = 0;i < LIST_NUM(s->HubCreateHistoryList);i++) { SERVER_HUB_CREATE_HISTORY *h = LIST_DATA(s->HubCreateHistoryList, i); if (StrCmpi(h->HubName, name) == 0) { hh = h; break; } } if (hh == NULL) { hh = ZeroMalloc(sizeof(SERVER_HUB_CREATE_HISTORY)); StrCpy(hh->HubName, sizeof(hh->HubName), name); Add(s->HubCreateHistoryList, hh); } hh->CreatedTime = Tick64(); } UnlockList(s->HubCreateHistoryList); SiDeleteOldHubCreateHistory(s); } // Delete outdated Virtual HUB creation histories void SiDeleteOldHubCreateHistory(SERVER *s) { UINT i; LIST *o; // Validate arguments if (s == NULL) { return; } LockList(s->HubCreateHistoryList); { o = NewListFast(NULL); for (i = 0;i < LIST_NUM(s->HubCreateHistoryList);i++) { SERVER_HUB_CREATE_HISTORY *h = LIST_DATA(s->HubCreateHistoryList, i); if ((h->CreatedTime + ((UINT64)TICKET_EXPIRES)) <= Tick64()) { // Expired Add(o, h); } } for (i = 0;i < LIST_NUM(o);i++) { SERVER_HUB_CREATE_HISTORY *h = LIST_DATA(o, i); Delete(s->HubCreateHistoryList, h); Free(h); } ReleaseList(o); } UnlockList(s->HubCreateHistoryList); } // Initialize the Virtual HUB creation history void SiInitHubCreateHistory(SERVER *s) { // Validate arguments if (s == NULL) { return; } s->HubCreateHistoryList = NewList(NULL); } // Release the Virtual HUB creation history void SiFreeHubCreateHistory(SERVER *s) { UINT i; // Validate arguments if (s == NULL) { return; } for (i = 0;i < LIST_NUM(s->HubCreateHistoryList);i++) { SERVER_HUB_CREATE_HISTORY *h = LIST_DATA(s->HubCreateHistoryList, i); Free(h); } ReleaseList(s->HubCreateHistoryList); s->HubCreateHistoryList = NULL; } // Identify whether the server can be connected from the VPN Client that is // created by the installer creating kit of Admin Pack bool IsAdminPackSupportedServerProduct(char *name) { return true; } // Get the saving status of syslog UINT SiGetSysLogSaveStatus(SERVER *s) { SYSLOG_SETTING set; // Validate arguments if (s == NULL) { return SYSLOG_NONE; } SiGetSysLogSetting(s, &set); return set.SaveType; } // Send a syslog void SiWriteSysLog(SERVER *s, char *typestr, char *hubname, wchar_t *message) { wchar_t tmp[1024]; char machinename[MAX_HOST_NAME_LEN + 1]; char datetime[MAX_PATH]; SYSTEMTIME st; // Validate arguments if (s == NULL || typestr == NULL || message == NULL) { return; } if (GetGlobalServerFlag(GSF_DISABLE_SYSLOG) != 0) { return; } // Host name GetMachineName(machinename, sizeof(machinename)); // Date and time LocalTime(&st); GetDateTimeStrMilli(datetime, sizeof(datetime), &st); if (IsEmptyStr(hubname) == false) { UniFormat(tmp, sizeof(tmp), L"[%S/VPN/%S] (%S) <%S>: %s", machinename, hubname, datetime, typestr, message); } else { UniFormat(tmp, sizeof(tmp), L"[%S/VPN] (%S) <%S>: %s", machinename, datetime, typestr, message); } SendSysLog(s->Syslog, tmp); } // Write the syslog configuration void SiSetSysLogSetting(SERVER *s, SYSLOG_SETTING *setting) { SYSLOG_SETTING set; // Validate arguments if (s == NULL || setting == NULL) { return; } Zero(&set, sizeof(set)); Copy(&set, setting, sizeof(SYSLOG_SETTING)); if (IsEmptyStr(set.Hostname) || set.Port == 0) { set.SaveType = SYSLOG_NONE; } Lock(s->SyslogLock); { Copy(&s->SyslogSetting, &set, sizeof(SYSLOG_SETTING)); SetSysLog(s->Syslog, set.Hostname, set.Port); } Unlock(s->SyslogLock); } // Read the syslog configuration void SiGetSysLogSetting(SERVER *s, SYSLOG_SETTING *setting) { // Validate arguments if (s == NULL || setting == NULL) { return; } //Lock(s->SyslogLock); { Copy(setting, &s->SyslogSetting, sizeof(SYSLOG_SETTING)); } //Unlock(s->SyslogLock); } // Get the server product name void GetServerProductName(SERVER *s, char *name, UINT size) { char *cpu; // Validate arguments if (s == NULL || name == NULL) { return; } GetServerProductNameInternal(s, name, size); #ifdef CPU_64 cpu = " (64 bit)"; #else // CPU_64 cpu = " (32 bit)"; #endif // CPU_64 StrCat(name, size, cpu); StrCat(name, size, " (Open Source)"); } void GetServerProductNameInternal(SERVER *s, char *name, UINT size) { // Validate arguments if (s == NULL || name == NULL) { return; } #ifdef BETA_NUMBER if (s->Cedar->Bridge) { StrCpy(name, size, CEDAR_BRIDGE_STR); } else { StrCpy(name, size, CEDAR_BETA_SERVER); } return; #else // BETA_NUMBER if (s->Cedar->Bridge) { StrCpy(name, size, CEDAR_BRIDGE_STR); } else { StrCpy(name, size, CEDAR_SERVER_STR); } #endif // BETA_NUMBER } // Adjoin the enumerations of log files void AdjoinEnumLogFile(LIST *o, LIST *src) { UINT i; // Validate arguments if (o == NULL || src == NULL) { return; } for (i = 0;i < LIST_NUM(src);i++) { LOG_FILE *f = LIST_DATA(src, i); Insert(o, Clone(f, sizeof(LOG_FILE))); } } // Check whether the log file with the specified name is contained in the enumerated list bool CheckLogFileNameFromEnumList(LIST *o, char *name, char *server_name) { LOG_FILE t; // Validate arguments if (o == NULL || name == NULL || server_name == NULL) { return false; } Zero(&t, sizeof(t)); StrCpy(t.Path, sizeof(t.Path), name); StrCpy(t.ServerName, sizeof(t.ServerName), server_name); if (Search(o, &t) == NULL) { return false; } return true; } // Release the log file enumeration void FreeEnumLogFile(LIST *o) { UINT i; // Validate arguments if (o == NULL) { return; } for (i = 0;i < LIST_NUM(o);i++) { LOG_FILE *f = LIST_DATA(o, i); Free(f); } ReleaseList(o); } // Enumerate the log files associated with the virtual HUB (All logs are listed in the case of server administrator) LIST *EnumLogFile(char *hubname) { char exe_dir[MAX_PATH]; char tmp[MAX_PATH]; LIST *o = NewListFast(CmpLogFile); DIRLIST *dir; if (StrLen(hubname) == 0) { hubname = NULL; } GetExeDir(exe_dir, sizeof(exe_dir)); // Enumerate in the server_log if (hubname == NULL) { EnumLogFileDir(o, "server_log"); } // Enumerate in the packet_log Format(tmp, sizeof(tmp), "%s/packet_log", exe_dir); dir = EnumDir(tmp); if (dir != NULL) { UINT i; for (i = 0;i < dir->NumFiles;i++) { DIRENT *e = dir->File[i]; if (e->Folder) { char dir_name[MAX_PATH]; if (hubname == NULL || StrCmpi(hubname, e->FileName) == 0) { Format(dir_name, sizeof(dir_name), "packet_log/%s", e->FileName); EnumLogFileDir(o, dir_name); } } } FreeDir(dir); } // Enumerate in the security_log Format(tmp, sizeof(tmp), "%s/security_log", exe_dir); dir = EnumDir(tmp); if (dir != NULL) { UINT i; for (i = 0;i < dir->NumFiles;i++) { DIRENT *e = dir->File[i]; if (e->Folder) { char dir_name[MAX_PATH]; if (hubname == NULL || StrCmpi(hubname, e->FileName) == 0) { Format(dir_name, sizeof(dir_name), "security_log/%s", e->FileName); EnumLogFileDir(o, dir_name); } } } FreeDir(dir); } return o; } // Enumerate log files in the specified directory void EnumLogFileDir(LIST *o, char *dirname) { UINT i; char exe_dir[MAX_PATH]; char dir_full_path[MAX_PATH]; DIRLIST *dir; // Validate arguments if (o == NULL || dirname == NULL) { return; } GetExeDir(exe_dir, sizeof(exe_dir)); Format(dir_full_path, sizeof(dir_full_path), "%s/%s", exe_dir, dirname); dir = EnumDir(dir_full_path); if (dir == NULL) { return; } for (i = 0;i < dir->NumFiles;i++) { DIRENT *e = dir->File[i]; if (e->Folder == false && e->FileSize > 0) { char full_path[MAX_PATH]; char file_path[MAX_PATH]; Format(file_path, sizeof(file_path), "%s/%s", dirname, e->FileName); Format(full_path, sizeof(full_path), "%s/%s", exe_dir, file_path); if (EndWith(file_path, ".log")) { LOG_FILE *f = ZeroMalloc(sizeof(LOG_FILE)); StrCpy(f->Path, sizeof(f->Path), file_path); f->FileSize = (UINT)(MIN(e->FileSize, 0xffffffffUL)); f->UpdatedTime = e->UpdateDate; GetMachineName(f->ServerName, sizeof(f->ServerName)); Insert(o, f); } } } FreeDir(dir); } // Log file list entry comparison int CmpLogFile(void *p1, void *p2) { LOG_FILE *f1, *f2; UINT i; if (p1 == NULL || p2 == NULL) { return 0; } f1 = *(LOG_FILE **)p1; f2 = *(LOG_FILE **)p2; if (f1 == NULL || f2 == NULL) { return 0; } i = StrCmpi(f1->Path, f2->Path); if (i != 0) { return i; } return StrCmpi(f1->ServerName, f2->ServerName); } // Get the Caps of the server UINT GetServerCapsInt(SERVER *s, char *name) { CAPSLIST t; UINT ret; // Validate arguments if (s == NULL || name == NULL) { return 0; } Zero(&t, sizeof(t)); GetServerCaps(s, &t); ret = GetCapsInt(&t, name); return ret; } bool GetServerCapsBool(SERVER *s, char *name) { return (GetServerCapsInt(s, name) == 0) ? false : true; } // Initialize the Caps cache of the server void InitServerCapsCache(SERVER *s) { // Validate arguments if (s == NULL) { return; } s->CapsCacheLock = NewLock(); s->CapsListCache = NULL; } // Release the Caps cache of the server void FreeServerCapsCache(SERVER *s) { // Validate arguments if (s == NULL) { return; } if (s->CapsListCache != NULL) { FreeCapsList(s->CapsListCache); s->CapsListCache = NULL; } DeleteLock(s->CapsCacheLock); } // Dispose the Caps cache of the server void DestroyServerCapsCache(SERVER *s) { // Validate arguments if (s == NULL) { return; } Lock(s->CapsCacheLock); { if (s->CapsListCache != NULL) { FreeCapsList(s->CapsListCache); s->CapsListCache = NULL; } } Unlock(s->CapsCacheLock); } // Flush the Caps list for this server void FlushServerCaps(SERVER *s) { CAPSLIST t; // Validate arguments if (s == NULL) { return; } DestroyServerCapsCache(s); Zero(&t, sizeof(t)); GetServerCaps(s, &t); } // Get the Caps list for this server void GetServerCaps(SERVER *s, CAPSLIST *t) { // Validate arguments if (s == NULL || t == NULL) { return; } Lock(s->CapsCacheLock); { if (s->CapsListCache == NULL) { s->CapsListCache = ZeroMalloc(sizeof(CAPSLIST)); GetServerCapsMain(s, s->CapsListCache); } Copy(t, s->CapsListCache, sizeof(s->CapsListCache)); } Unlock(s->CapsCacheLock); } // Update the global server flags void UpdateGlobalServerFlags(SERVER *s, CAPSLIST *t) { bool is_restricted = false; // Validate arguments if (s == NULL || t == NULL) { return; } is_restricted = SiIsEnterpriseFunctionsRestrictedOnOpenSource(s->Cedar); SetGlobalServerFlag(GSF_DISABLE_PUSH_ROUTE, is_restricted); SetGlobalServerFlag(GSF_DISABLE_RADIUS_AUTH, is_restricted); SetGlobalServerFlag(GSF_DISABLE_CERT_AUTH, is_restricted); SetGlobalServerFlag(GSF_DISABLE_DEEP_LOGGING, is_restricted); SetGlobalServerFlag(GSF_DISABLE_AC, is_restricted); SetGlobalServerFlag(GSF_DISABLE_SYSLOG, is_restricted); } // Set a global server flag void SetGlobalServerFlag(UINT index, UINT value) { // Validate arguments if (index >= NUM_GLOBAL_SERVER_FLAGS) { return; } global_server_flags[index] = value; } // Get a global server flag UINT GetGlobalServerFlag(UINT index) { // Validate arguments if (index >= NUM_GLOBAL_SERVER_FLAGS) { return 0; } return global_server_flags[index]; } // Main of the aquisition of Caps of the server void GetServerCapsMain(SERVER *s, CAPSLIST *t) { bool is_restricted = false; // Validate arguments if (s == NULL || t == NULL) { return; } is_restricted = SiIsEnterpriseFunctionsRestrictedOnOpenSource(s->Cedar); // Initialize InitCapsList(t); // Maximum Ethernet packet size AddCapsInt(t, "i_max_packet_size", MAX_PACKET_SIZE); if (s->Cedar->Bridge == false) { UINT max_sessions, max_clients, max_bridges, max_user_creations; max_clients = INFINITE; max_bridges = INFINITE; max_sessions = SERVER_MAX_SESSIONS_FOR_CARRIER_EDITION; max_user_creations = INFINITE; // Maximum number of virtual HUBs AddCapsInt(t, "i_max_hubs", SERVER_MAX_SESSIONS_FOR_CARRIER_EDITION); // The maximum number of concurrent sessions AddCapsInt(t, "i_max_sessions", max_sessions); // Maximum number of creatable users AddCapsInt(t, "i_max_user_creation", max_user_creations); // Maximum number of clients AddCapsInt(t, "i_max_clients", max_clients); // Maximum number of bridges AddCapsInt(t, "i_max_bridges", max_bridges); if (s->ServerType != SERVER_TYPE_FARM_MEMBER) { // Maximum number of registrable users / Virtual HUB AddCapsInt(t, "i_max_users_per_hub", MAX_USERS); // Maximum number of registrable groups / Virtual HUB AddCapsInt(t, "i_max_groups_per_hub", MAX_GROUPS); // Maximum number of registrable access list entries / Virtual HUB AddCapsInt(t, "i_max_access_lists", MAX_ACCESSLISTS); } else { // Maximum number of registrable users / Virtual HUB AddCapsInt(t, "i_max_users_per_hub", 0); // Maximum number of registrable groups / Virtual HUB AddCapsInt(t, "i_max_groups_per_hub", 0); // Maximum number of registrable access list entries / Virtual HUB AddCapsInt(t, "i_max_access_lists", 0); } // The policy related to multiple logins AddCapsBool(t, "b_support_limit_multilogin", true); // QoS / VoIP AddCapsBool(t, "b_support_qos", true); // syslog AddCapsBool(t, "b_support_syslog", true); // IPsec // (Only works in stand-alone mode currently) AddCapsBool(t, "b_support_ipsec", (s->ServerType == SERVER_TYPE_STANDALONE)); // SSTP // (Only works in stand-alone mode currently) AddCapsBool(t, "b_support_sstp", (s->ServerType == SERVER_TYPE_STANDALONE)); // OpenVPN // (Only works in stand-alone mode currently) AddCapsBool(t, "b_support_openvpn", (s->ServerType == SERVER_TYPE_STANDALONE)); // DDNS AddCapsBool(t, "b_support_ddns", (s->DDnsClient != NULL)); if (s->DDnsClient != NULL) { // DDNS via Proxy AddCapsBool(t, "b_support_ddns_proxy", true); } // VPN over ICMP, VPN over DNS AddCapsBool(t, "b_support_special_listener", true); } else { // Maximum number of virtual HUBs AddCapsInt(t, "i_max_hubs", 0); // The maximum number of concurrent sessions AddCapsInt(t, "i_max_sessions", 0); // Maximum number of clients AddCapsInt(t, "i_max_clients", 0); // Maximum number of bridges AddCapsInt(t, "i_max_bridges", 0); // Maximum number of registrable users / Virtual HUB AddCapsInt(t, "i_max_users_per_hub", 0); // Maximum number of registrable groups / Virtual HUB AddCapsInt(t, "i_max_groups_per_hub", 0); // Maximum number of registrable access list entries / Virtual HUB AddCapsInt(t, "i_max_access_lists", 0); // QoS / VoIP AddCapsBool(t, "b_support_qos", true); // syslog AddCapsBool(t, "b_support_syslog", true); // IPsec AddCapsBool(t, "b_support_ipsec", false); // SSTP AddCapsBool(t, "b_support_sstp", false); // OpenVPN AddCapsBool(t, "b_support_openvpn", false); // DDNS AddCapsBool(t, "b_support_ddns", false); // VPN over ICMP, VPN over DNS AddCapsBool(t, "b_support_special_listener", false); } // Changing the type of Virtual HUB in cluster is prohibited AddCapsBool(t, "b_cluster_hub_type_fixed", true); // Maximum MAC address table size / Virtual HUB AddCapsInt(t, "i_max_mac_tables", MAX_MAC_TABLES); // Maximum IP address table size / Virtual HUB AddCapsInt(t, "i_max_ip_tables", MAX_IP_TABLES); // SecureNAT function is available AddCapsBool(t, "b_support_securenat", true); // Pushing routing table function of SecureNAT Virtual DHCP Server is available AddCapsBool(t, "b_suppport_push_route", !is_restricted); AddCapsBool(t, "b_suppport_push_route_config", true); if (s->ServerType != SERVER_TYPE_STANDALONE) { AddCapsBool(t, "b_virtual_nat_disabled", true); } // Maximum NAT table size / Virtual HUB AddCapsInt(t, "i_max_secnat_tables", NAT_MAX_SESSIONS); // Cascade connction if (s->ServerType == SERVER_TYPE_STANDALONE) { AddCapsBool(t, "b_support_cascade", true); } else { AddCapsBool(t, "b_support_cascade", false); } if (s->Cedar->Bridge) { // Bridge mode AddCapsBool(t, "b_bridge", true); } else if (s->ServerType == SERVER_TYPE_STANDALONE) { // Stand-alone mode AddCapsBool(t, "b_standalone", true); } else if (s->ServerType == SERVER_TYPE_FARM_CONTROLLER) { // Cluster controller mode AddCapsBool(t, "b_cluster_controller", true); } else { // Cluster member mode AddCapsBool(t, "b_cluster_member", true); } // Virtual HUB is modifiable AddCapsBool(t, "b_support_config_hub", s->ServerType != SERVER_TYPE_FARM_MEMBER && s->Cedar->Bridge == false); // VPN client can be connected AddCapsBool(t, "b_vpn_client_connect", s->Cedar->Bridge == false ? true : false); // External authentication server is available AddCapsBool(t, "b_support_radius", s->ServerType != SERVER_TYPE_FARM_MEMBER && s->Cedar->Bridge == false); // Local-bridge function is available AddCapsBool(t, "b_local_bridge", IsBridgeSupported()); if (OS_IS_WINDOWS(GetOsInfo()->OsType)) { // Packet capture driver is not installed AddCapsBool(t, "b_must_install_pcap", IsEthSupported() == false ? true : false); } else { // Regard that the driver is installed in the Linux version AddCapsBool(t, "b_must_install_pcap", false); } if (IsBridgeSupported()) { // Tun / tap device is available (only Linux) AddCapsBool(t, "b_tap_supported", GetOsInfo()->OsType == OSTYPE_LINUX ? true : false); } // Cascade connction if (s->ServerType == SERVER_TYPE_STANDALONE) { AddCapsBool(t, "b_support_cascade", true); } else { AddCapsBool(t, "b_support_cascade", false); } // Server authentication can be used in cascade connection AddCapsBool(t, "b_support_cascade_cert", true); // the log file settings is modifiable AddCapsBool(t, "b_support_config_log", s->ServerType != SERVER_TYPE_FARM_MEMBER); // Automatic deletion of log file is available AddCapsBool(t, "b_support_autodelete", true); // Config file operation is available AddCapsBool(t, "b_support_config_rw", true); // Attribute of each Virtual HUB can be set AddCapsBool(t, "b_support_hub_admin_option", true); // Client certificate can be set in a cascade connection AddCapsBool(t, "b_support_cascade_client_cert", true); // Virtual HUB can be hidden AddCapsBool(t, "b_support_hide_hub", true); // Integrated management AddCapsBool(t, "b_support_cluster_admin", true); // Flag of open-source version AddCapsBool(t, "b_is_softether", true); if (s->Cedar->Bridge == false) { // The virtual layer 3 switch function is available AddCapsBool(t, "b_support_layer3", true); AddCapsInt(t, "i_max_l3_sw", MAX_NUM_L3_SWITCH); AddCapsInt(t, "i_max_l3_if", MAX_NUM_L3_IF); AddCapsInt(t, "i_max_l3_table", MAX_NUM_L3_TABLE); // Can act as a part of a cluster AddCapsBool(t, "b_support_cluster", true); } else { AddCapsBool(t, "b_support_layer3", false); AddCapsInt(t, "i_max_l3_sw", 0); AddCapsInt(t, "i_max_l3_if", 0); AddCapsInt(t, "i_max_l3_table", 0); AddCapsBool(t, "b_support_cluster", false); } if (s->ServerType != SERVER_TYPE_FARM_MEMBER && s->Cedar->Bridge == false) { // Support for CRL AddCapsBool(t, "b_support_crl", true); // Supports AC AddCapsBool(t, "b_support_ac", true); } // Supports downloading a log file AddCapsBool(t, "b_support_read_log", true); // Cascade connection can be renamed AddCapsBool(t, "b_support_rename_cascade", true); if (s->Cedar->Beta) { // Beta version AddCapsBool(t, "b_beta_version", true); } // VM discrimination AddCapsBool(t, "b_is_in_vm", s->IsInVm); // Support for display name of the network connection for the local bridge #ifdef OS_WIN32 if (IsBridgeSupported() && IsNt() && GetOsInfo()->OsType >= OSTYPE_WINDOWS_2000_PROFESSIONAL) { AddCapsBool(t, "b_support_network_connection_name", true); } #else // OS_WIN32 if (IsBridgeSupported() && EthIsInterfaceDescriptionSupportedUnix()) { AddCapsBool(t, "b_support_network_connection_name", true); } #endif // OS_WIN32 // Support for MAC address filtering AddCapsBool(t, "b_support_check_mac", true); // Support for status check of the TCP connection AddCapsBool(t, "b_support_check_tcp_state", true); // Can specify multiple server and retry intervals in Radius authentication AddCapsBool(t, "b_support_radius_retry_interval_and_several_servers", s->ServerType != SERVER_TYPE_FARM_MEMBER && s->Cedar->Bridge == false); // Can manage the ID of the tagged VLAN in the MAC address table AddCapsBool(t, "b_support_vlan", true); // Support for Virtual HUB extended options if ((s->Cedar->Bridge == false) && (s->ServerType == SERVER_TYPE_STANDALONE || s->ServerType == SERVER_TYPE_FARM_CONTROLLER)) { AddCapsBool(t, "b_support_hub_ext_options", true); } else { AddCapsBool(t, "b_support_hub_ext_options", false); } // Support for Security Policy version 3.0 AddCapsBool(t, "b_support_policy_ver_3", true); // Support for IPv6 access list AddCapsBool(t, "b_support_ipv6_acl", true); // Support for setting of delay, jitter and packet loss in the access list AddCapsBool(t, "b_support_ex_acl", true); // Support for URL redirection in the access list AddCapsBool(t, "b_support_redirect_url_acl", true); // Supports the specification by the group name in the access list AddCapsBool(t, "b_support_acl_group", true); // Support for IPv6 in connection source IP restriction list AddCapsBool(t, "b_support_ipv6_ac", true); // Support for VLAN tagged packet transmission configuration tool AddCapsBool(t, "b_support_eth_vlan", (OS_IS_WINDOWS_NT(GetOsType()) && GET_KETA(GetOsType(), 100) >= 2)); // Support for the message display function when the VPN connect to the Virtual HUB AddCapsBool(t, "b_support_msg", true); // UDP acceleration feature AddCapsBool(t, "b_support_udp_acceleration", true); // Intel AES Acceleration function AddCapsBool(t, "b_support_intel_aes", IsIntelAesNiSupported()); #ifdef OS_WIN32 // SeLow driver AddCapsBool(t, "b_using_selow_driver", Win32IsUsingSeLow()); #endif // OS_WIN32 // VPN Azure function AddCapsBool(t, "b_support_azure", SiIsAzureSupported(s)); // VPN3 AddCapsBool(t, "b_vpn3", true); // VPN4 AddCapsBool(t, "b_vpn4", true); UpdateGlobalServerFlags(s, t); } // SYSLOG_SETTING void InRpcSysLogSetting(SYSLOG_SETTING *t, PACK *p) { // Validate arguments if (t == NULL || p == NULL) { return; } Zero(t, sizeof(SYSLOG_SETTING)); t->SaveType = PackGetInt(p, "SaveType"); t->Port = PackGetInt(p, "Port"); PackGetStr(p, "Hostname", t->Hostname, sizeof(t->Hostname)); } void OutRpcSysLogSetting(PACK *p, SYSLOG_SETTING *t) { // Validate arguments if (t == NULL || p == NULL) { return; } PackAddInt(p, "SaveType", t->SaveType); PackAddInt(p, "Port", t->Port); PackAddStr(p, "Hostname", t->Hostname); } // CAPSLIST void InitCapsList(CAPSLIST *t) { // Validate arguments if (t == NULL) { return; } Zero(t, sizeof(CAPSLIST)); t->CapsList = NewListFast(NULL); } void InRpcCapsList(CAPSLIST *t, PACK *p) { UINT i; // Validate arguments if (t == NULL || p == NULL) { return; } Zero(t, sizeof(CAPSLIST)); t->CapsList = NewListFast(CompareCaps); for (i = 0;i < LIST_NUM(p->elements);i++) { ELEMENT *e = LIST_DATA(p->elements, i); if (StartWith(e->name, "caps_") && e->type == VALUE_INT && e->num_value == 1) { CAPS *c = NewCaps(e->name + 5, e->values[0]->IntValue); Insert(t->CapsList, c); } } } void OutRpcCapsList(PACK *p, CAPSLIST *t) { UINT i; // Validate arguments if (t == NULL || p == NULL) { return; } for (i = 0;i < LIST_NUM(t->CapsList);i++) { char tmp[MAX_SIZE]; CAPS *c = LIST_DATA(t->CapsList, i); Format(tmp, sizeof(tmp), "caps_%s", c->Name); PackAddInt(p, tmp, c->Value); } } void FreeRpcCapsList(CAPSLIST *t) { UINT i; // Validate arguments if (t == NULL) { return; } for (i = 0;i < LIST_NUM(t->CapsList);i++) { CAPS *c = LIST_DATA(t->CapsList, i); FreeCaps(c); } ReleaseList(t->CapsList); } // Add a bool type to Caps list void AddCapsBool(CAPSLIST *caps, char *name, bool b) { CAPS *c; // Validate arguments if (caps == NULL || name == NULL) { return; } c = NewCaps(name, b == false ? 0 : 1); AddCaps(caps, c); } // Add the int type to Caps list void AddCapsInt(CAPSLIST *caps, char *name, UINT i) { CAPS *c; // Validate arguments if (caps == NULL || name == NULL) { return; } c = NewCaps(name, i); AddCaps(caps, c); } // Get the int type from the Caps list UINT GetCapsInt(CAPSLIST *caps, char *name) { CAPS *c; // Validate arguments if (caps == NULL || name == NULL) { return 0; } c = GetCaps(caps, name); if (c == NULL) { return 0; } return c->Value; } // Get bool type from the Caps list bool GetCapsBool(CAPSLIST *caps, char *name) { CAPS *c; // Validate arguments if (caps == NULL || name == NULL) { return false; } c = GetCaps(caps, name); if (c == NULL) { return false; } return c->Value == 0 ? false : true; } // Release the Caps list void FreeCapsList(CAPSLIST *caps) { UINT i; // Validate arguments if (caps == NULL) { return; } for (i = 0;i < LIST_NUM(caps->CapsList);i++) { CAPS *c = LIST_DATA(caps->CapsList, i); FreeCaps(c); } ReleaseList(caps->CapsList); Free(caps); } // Get the Caps CAPS *GetCaps(CAPSLIST *caps, char *name) { UINT i; // Validate arguments if (caps == NULL || name == NULL) { return NULL; } for (i = 0;i < LIST_NUM(caps->CapsList);i++) { CAPS *c = LIST_DATA(caps->CapsList, i); if (StrCmpi(c->Name, name) == 0) { return c; } } return NULL; } // Add to the Caps void AddCaps(CAPSLIST *caps, CAPS *c) { // Validate arguments if (caps == NULL || c == NULL) { return; } Insert(caps->CapsList, c); } // Comparison of Caps int CompareCaps(void *p1, void *p2) { CAPS *c1, *c2; if (p1 == NULL || p2 == NULL) { return 0; } c1 = *(CAPS **)p1; c2 = *(CAPS **)p2; if (c1 == NULL || c2 == NULL) { return 0; } return StrCmpi(c1->Name, c2->Name); } // Create a Caps list CAPSLIST *NewCapsList() { CAPSLIST *caps = ZeroMalloc(sizeof(CAPSLIST)); caps->CapsList = NewListFast(CompareCaps); return caps; } // Release the Caps void FreeCaps(CAPS *c) { // Validate arguments if (c == NULL) { return; } Free(c->Name); Free(c); } // Create a Caps CAPS *NewCaps(char *name, UINT value) { CAPS *c; // Validate arguments if (name == NULL) { return NULL; } c = ZeroMalloc(sizeof(CAPS)); c->Name = CopyStr(name); c->Value = value; return c; } // Calculate the score from the current number of connections and weight UINT SiCalcPoint(SERVER *s, UINT num, UINT weight) { UINT server_max_sessions = SERVER_MAX_SESSIONS; if (s == NULL) { return 0; } if (weight == 0) { weight = 100; } server_max_sessions = GetServerCapsInt(s, "i_max_sessions"); return (UINT)(((double)server_max_sessions - MIN((double)num * 100.0 / (double)weight, (double)server_max_sessions)) * (double)FARM_BASE_POINT / (double)server_max_sessions); } // Get the server score UINT SiGetPoint(SERVER *s) { UINT num_session; // Validate arguments if (s == NULL) { return 0; } num_session = Count(s->Cedar->CurrentSessions); return SiCalcPoint(s, num_session, s->Weight); } // Generate the default certificate void SiGenerateDefaultCert(X **server_x, K **server_k) { SiGenerateDefaultCertEx(server_x, server_k, NULL); } void SiGenerateDefaultCertEx(X **server_x, K **server_k, char *common_name) { X *x; K *private_key, *public_key; NAME *name; char tmp[MAX_SIZE]; wchar_t cn[MAX_SIZE]; // Validate arguments if (server_x == NULL || server_k == NULL) { return; } // Create a key pair RsaGen(&private_key, &public_key, 2048); if (IsEmptyStr(common_name)) { // Get the host name StrCpy(tmp, sizeof(tmp), "server.softether.vpn"); GetMachineName(tmp, sizeof(tmp)); StrToUni(cn, sizeof(cn), tmp); } else { StrToUni(cn, sizeof(cn), common_name); } name = NewName(cn, cn, cn, L"US", NULL, NULL); x = NewRootX(public_key, private_key, name, MAX(GetDaysUntil2038(), SERVER_DEFAULT_CERT_DAYS), NULL); *server_x = x; *server_k = private_key; FreeName(name); FreeK(public_key); } // Set the server certificate to default void SiInitDefaultServerCert(SERVER *s) { X *x = NULL; K *k = NULL; // Validate arguments if (s == NULL) { return; } // Generate a server certificate and private key SiGenerateDefaultCert(&x, &k); // Configure SetCedarCert(s->Cedar, x, k); FreeX(x); FreeK(k); } // Set the encryption algorithm name to default void SiInitCipherName(SERVER *s) { // Validate arguments if (s == NULL) { return; } SetCedarCipherList(s->Cedar, SERVER_DEFAULT_CIPHER_NAME); } // Initialize the listener list void SiInitListenerList(SERVER *s) { // Validate arguments if (s == NULL) { return; } SiLockListenerList(s); { { // Register the 4 ports (443, 992, 1194, 8888) as the default port SiAddListener(s, SERVER_DEF_PORTS_1, true); SiAddListener(s, SERVER_DEF_PORTS_2, true); SiAddListener(s, SERVER_DEF_PORTS_3, true); SiAddListener(s, SERVER_DEF_PORTS_4, true); } } SiUnlockListenerList(s); } // Remove the listener bool SiDeleteListener(SERVER *s, UINT port) { SERVER_LISTENER *e; // Validate arguments if (s == NULL || port == 0) { return false; } e = SiGetListener(s, port); if (e == NULL) { return false; } // Stop if still alive SiDisableListener(s, port); if (e->Listener != NULL) { ReleaseListener(e->Listener); } Delete(s->ServerListenerList, e); Free(e); return true; } // Compare the SERVER_LISTENER int CompareServerListener(void *p1, void *p2) { SERVER_LISTENER *s1, *s2; if (p1 == NULL || p2 == NULL) { return 0; } s1 = *(SERVER_LISTENER **)p1; s2 = *(SERVER_LISTENER **)p2; if (s1 == NULL || s2 == NULL) { return 0; } if (s1->Port > s2->Port) { return 1; } else if (s1->Port < s2->Port) { return -1; } else { return 0; } } // Stop the listener bool SiDisableListener(SERVER *s, UINT port) { SERVER_LISTENER *e; // Validate arguments if (s == NULL || port == 0) { return false; } // Get the listener e = SiGetListener(s, port); if (e == NULL) { return false; } if (e->Enabled == false || e->Listener == NULL) { // Already stopped return true; } // Stop the listener StopListener(e->Listener); // Release the listener ReleaseListener(e->Listener); e->Listener = NULL; e->Enabled = false; return true; } // Start the listener bool SiEnableListener(SERVER *s, UINT port) { SERVER_LISTENER *e; // Validate arguments if (s == NULL || port == 0) { return false; } // Get the listener e = SiGetListener(s, port); if (e == NULL) { return false; } if (e->Enabled) { // It has already started return true; } // Create a listener e->Listener = NewListener(s->Cedar, LISTENER_TCP, e->Port); if (e->Listener == NULL) { // Failure return false; } e->Listener->DisableDos = e->DisableDos; e->Enabled = true; return true; } // Get the listener SERVER_LISTENER *SiGetListener(SERVER *s, UINT port) { UINT i; // Validate arguments if (s == NULL || port == 0) { return NULL; } for (i = 0;i < LIST_NUM(s->ServerListenerList);i++) { SERVER_LISTENER *e = LIST_DATA(s->ServerListenerList, i); if (e->Port == port) { return e; } } return NULL; } // Add a listener bool SiAddListener(SERVER *s, UINT port, bool enabled) { return SiAddListenerEx(s, port, enabled, false); } bool SiAddListenerEx(SERVER *s, UINT port, bool enabled, bool disable_dos) { SERVER_LISTENER *e; UINT i; // Validate arguments if (s == NULL || port == 0) { return false; } // Check whether the listener exists already for (i = 0;i < LIST_NUM(s->ServerListenerList);i++) { e = LIST_DATA(s->ServerListenerList, i); if (e->Port == port) { // Already exist return false; } } // Register by initializing a new listener e = ZeroMalloc(sizeof(SERVER_LISTENER)); e->Enabled = enabled; e->Port = port; e->DisableDos = disable_dos; if (e->Enabled) { // Create a listener e->Listener = NewListener(s->Cedar, LISTENER_TCP, e->Port); if (e->Listener != NULL) { e->Listener->DisableDos = e->DisableDos; } } Insert(s->ServerListenerList, e); return true; } // Lock the listener list void SiLockListenerList(SERVER *s) { // Validate arguments if (s == NULL) { return; } LockList(s->ServerListenerList); } // Unlock the listener list void SiUnlockListenerList(SERVER *s) { // Validate arguments if (s == NULL) { return; } UnlockList(s->ServerListenerList); } // Initialize the Bridge void SiInitBridge(SERVER *s) { HUB *h; HUB_OPTION o; HUB_LOG g; // Validate arguments if (s == NULL) { return; } Zero(&o, sizeof(o)); o.MaxSession = 0; h = NewHub(s->Cedar, SERVER_DEFAULT_BRIDGE_NAME, &o); AddHub(s->Cedar, h); h->Offline = true; SetHubOnline(h); // Log settings SiSetDefaultLogSetting(&g); SetHubLogSetting(h, &g); ReleaseHub(h); } // Set the default value of the Virtual HUB options void SiSetDefaultHubOption(HUB_OPTION *o) { // Validate arguments if (o == NULL) { return; } o->MaxSession = 0; o->VlanTypeId = MAC_PROTO_TAGVLAN; o->NoIPv6DefaultRouterInRAWhenIPv6 = true; o->ManageOnlyPrivateIP = true; o->ManageOnlyLocalUnicastIPv6 = true; o->NoMacAddressLog = true; o->NoDhcpPacketLogOutsideHub = true; o->AccessListIncludeFileCacheLifetime = ACCESS_LIST_INCLUDE_FILE_CACHE_LIFETIME; o->RemoveDefGwOnDhcpForLocalhost = true; o->FloodingSendQueueBufferQuota = DEFAULT_FLOODING_QUEUE_LENGTH; } // Create a default virtual HUB void SiInitDefaultHubList(SERVER *s) { HUB *h; HUB_OPTION o; HUB_LOG g; // Validate arguments if (s == NULL) { return; } Zero(&o, sizeof(o)); // Configure a default Virtual HUB management options SiSetDefaultHubOption(&o); h = NewHub(s->Cedar, s->Cedar->Bridge == false ? SERVER_DEFAULT_HUB_NAME : SERVER_DEFAULT_BRIDGE_NAME, &o); h->CreatedTime = SystemTime64(); AddHub(s->Cedar, h); if (s->Cedar->Bridge) { // Randomize the password Rand(h->HashedPassword, sizeof(h->HashedPassword)); Rand(h->SecurePassword, sizeof(h->SecurePassword)); } h->Offline = true; SetHubOnline(h); // Log settings SiSetDefaultLogSetting(&g); SetHubLogSetting(h, &g); { UINT i; for (i = 0;i < 0;i++) { char tmp[MAX_SIZE]; USER *u; sprintf(tmp, "user%u", i); AcLock(h); u = NewUser(tmp, L"test", L"", AUTHTYPE_ANONYMOUS, NULL); AcAddUser(h, u); ReleaseUser(u); AcUnlock(h); } } ReleaseHub(h); } // Set the log settings to default void SiSetDefaultLogSetting(HUB_LOG *g) { // Validate arguments if (g == NULL) { return; } Zero(g, sizeof(HUB_LOG)); g->SaveSecurityLog = true; g->SecurityLogSwitchType = LOG_SWITCH_DAY; g->SavePacketLog = true; g->PacketLogSwitchType = LOG_SWITCH_DAY; g->PacketLogConfig[PACKET_LOG_TCP_CONN] = g->PacketLogConfig[PACKET_LOG_DHCP] = PACKET_LOG_HEADER; } // Test void SiTest(SERVER *s) { } // Set the initial configuration void SiLoadInitialConfiguration(SERVER *s) { RPC_KEEP k; // Validate arguments if (s == NULL) { return; } // Auto saving interval related s->AutoSaveConfigSpan = SERVER_FILE_SAVE_INTERVAL_DEFAULT; s->BackupConfigOnlyWhenModified = true; s->Weight = FARM_DEFAULT_WEIGHT; SiLoadGlobalParamsCfg(NULL); // KEEP related Zero(&k, sizeof(k)); { k.UseKeepConnect = true; } k.KeepConnectPort = 80; StrCpy(k.KeepConnectHost, sizeof(k.KeepConnectHost), CLIENT_DEFAULT_KEEPALIVE_HOST); k.KeepConnectInterval = KEEP_INTERVAL_DEFAULT * 1000; k.KeepConnectProtocol = CONNECTION_UDP; Lock(s->Keep->lock); { KEEP *keep = s->Keep; keep->Enable = k.UseKeepConnect; keep->Server = true; StrCpy(keep->ServerName, sizeof(keep->ServerName), k.KeepConnectHost); keep->ServerPort = k.KeepConnectPort; keep->UdpMode = k.KeepConnectProtocol; keep->Interval = k.KeepConnectInterval; } Unlock(s->Keep->lock); // Initialize the password { Hash(s->HashedPassword, "", 0, true); } // Set the encryption algorithm name to default SiInitCipherName(s); // Set the server certificate to default SiInitDefaultServerCert(s); // Create a default HUB { SiInitDefaultHubList(s); } if (s->Cedar->Bridge == false) { // Create a DDNS client s->DDnsClient = NewDDNSClient(s->Cedar, NULL, NULL); } // Set the listener list to default setting SiInitListenerList(s); if (s->Cedar->Bridge) { // SSTP, OpenVPN, and NAT traversal function can not be used in the bridge environment s->DisableNatTraversal = true; s->DisableSSTPServer = true; s->DisableOpenVPNServer = true; } else { // Enable the SSTP and OpenVPN for default setting OPENVPN_SSTP_CONFIG c; Zero(&c, sizeof(c)); c.EnableOpenVPN = true; c.EnableSSTP = true; { ToStr(c.OpenVPNPortList, OPENVPN_UDP_PORT); } SiSetOpenVPNAndSSTPConfig(s, &c); { // Enable VPN-over-ICMP" and VPN-over-DNS for default setting s->EnableVpnOverIcmp = false; s->EnableVpnOverDns = false; } } s->Eraser = NewEraser(s->Logger, 0); } // Check whether the ports required for VPN-over-ICMP can be opened bool SiCanOpenVpnOverIcmpPort() { // Whether the ICMP can be opened SOCK *s = NewUDP(MAKE_SPECIAL_PORT(IP_PROTO_ICMPV4)); if (s == NULL) { // Failure return false; } Disconnect(s); ReleaseSock(s); return true; } // Check whether the ports required for VPN-over-DNS can be opened bool SiCanOpenVpnOverDnsPort() { // Whether UDP Port 53 can be listen on SOCK *s = NewUDP(53); if (s == NULL) { // Listening failure return false; } Disconnect(s); ReleaseSock(s); return true; } // Read the configuration file (main) bool SiLoadConfigurationFileMain(SERVER *s, FOLDER *root) { // Validate arguments if (s == NULL || root == NULL) { return false; } return SiLoadConfigurationCfg(s, root); } // Read the configuration file bool SiLoadConfigurationFile(SERVER *s) { // Validate arguments bool ret = false; FOLDER *root; char *server_config_filename = SERVER_CONFIG_FILE_NAME; if (s == NULL) { return false; } s->CfgRw = NewCfgRwEx2A(&root, s->Cedar->Bridge == false ? server_config_filename : BRIDGE_CONFIG_FILE_NAME, false, s->Cedar->Bridge == false ? SERVER_CONFIG_TEMPLATE_NAME : BRIDGE_CONFIG_TEMPLATE_NAME); if (server_reset_setting) { CfgDeleteFolder(root); root = NULL; server_reset_setting = false; } if (root == NULL) { return false; } ret = SiLoadConfigurationFileMain(s, root); CfgDeleteFolder(root); return ret; } // Initialize the configuration void SiInitConfiguration(SERVER *s) { // Validate arguments if (s == NULL) { return; } s->AutoSaveConfigSpan = SERVER_FILE_SAVE_INTERVAL_DEFAULT; s->BackupConfigOnlyWhenModified = true; // IPsec server if (s->Cedar->Bridge == false) { s->IPsecServer = NewIPsecServer(s->Cedar); } // OpenVPN server (UDP) if (s->Cedar->Bridge == false) { s->OpenVpnServerUdp = NewOpenVpnServerUdp(s->Cedar); } SLog(s->Cedar, "LS_LOAD_CONFIG_1"); if (SiLoadConfigurationFile(s) == false) { // Ethernet initialization InitEth(); SLog(s->Cedar, "LS_LOAD_CONFIG_3"); SiLoadInitialConfiguration(s); SetFifoCurrentReallocMemSize(MEM_FIFO_REALLOC_MEM_SIZE); server_reset_setting = false; } else { SLog(s->Cedar, "LS_LOAD_CONFIG_2"); } s->CfgRw->DontBackup = s->DontBackupConfig; // The arp_filter in Linux if (GetOsInfo()->OsType == OSTYPE_LINUX) { if (s->NoLinuxArpFilter == false) { SetLinuxArpFilter(); } } if (s->DisableDosProction) { DisableDosProtect(); } else { EnableDosProtect(); } s->AutoSaveConfigSpanSaved = s->AutoSaveConfigSpan; // Create a VPN Azure client if (s->DDnsClient != NULL && s->Cedar->Bridge == false && s->ServerType == SERVER_TYPE_STANDALONE) { s->AzureClient = NewAzureClient(s->Cedar, s); AcSetEnable(s->AzureClient, s->EnableVpnAzure); } // Reduce the storage interval in the case of user mode #ifdef OS_WIN32 if (MsIsUserMode()) { s->AutoSaveConfigSpan = MIN(s->AutoSaveConfigSpan, SERVER_FILE_SAVE_INTERVAL_USERMODE); } #endif //OS_WIN32 // Create a saving thread SLog(s->Cedar, "LS_INIT_SAVE_THREAD", s->AutoSaveConfigSpan / 1000); s->SaveHaltEvent = NewEvent(); s->SaveThread = NewThread(SiSaverThread, s); } // Set the state of Enabled / Disabled of Azure Client void SiSetAzureEnable(SERVER *s, bool enabled) { // Validate arguments if (s == NULL) { return; } if (s->AzureClient != NULL) { AcSetEnable(s->AzureClient, enabled); } s->EnableVpnAzure = enabled; } // Get the state of Enabled / Disabled of Azure Client bool SiGetAzureEnable(SERVER *s) { // Validate arguments if (s == NULL) { return false; } if (s->AzureClient != NULL) { return AcGetEnable(s->AzureClient); } else { return false; } } // Apply the Config to the Azure Client void SiApplyAzureConfig(SERVER *s, DDNS_CLIENT_STATUS *ddns_status) { // Validate arguments if (s == NULL) { return; } AcApplyCurrentConfig(s->AzureClient, ddns_status); } // Get whether the Azure Client is enabled bool SiIsAzureEnabled(SERVER *s) { // Validate arguments if (s == NULL) { return false; } if (s->AzureClient == NULL) { return false; } return s->EnableVpnAzure; } // Get whether the Azure Client is supported bool SiIsAzureSupported(SERVER *s) { // Validate arguments if (s == NULL) { return false; } if (s->AzureClient == NULL) { return false; } return true; } // Read the server settings from the CFG bool SiLoadConfigurationCfg(SERVER *s, FOLDER *root) { FOLDER *f1, *f2, *f3, *f4, *f5, *f6, *f7, *f8, *f; bool is_vgs_enabled = false; // Validate arguments if (s == NULL || root == NULL) { return false; } f = NULL; f1 = CfgGetFolder(root, "ServerConfiguration"); f2 = CfgGetFolder(root, "VirtualHUB"); f3 = CfgGetFolder(root, "ListenerList"); f4 = CfgGetFolder(root, "LocalBridgeList"); f5 = CfgGetFolder(root, "VirtualLayer3SwitchList"); f6 = CfgGetFolder(root, "LicenseManager"); f7 = CfgGetFolder(root, "IPsec"); f8 = CfgGetFolder(root, "DDnsClient"); if (f1 == NULL) { SLog(s->Cedar, "LS_BAD_CONFIG"); return false; } #ifdef OS_WIN32 if (f4 != NULL) { // Read the flag of using the SeLow driver bool b = true; if (CfgIsItem(f4, "EnableSoftEtherKernelModeDriver")) { b = CfgGetBool(f4, "EnableSoftEtherKernelModeDriver"); } Win32SetEnableSeLow(b); } #endif // OS_WIN32 // Ethernet initialization InitEth(); s->ConfigRevision = CfgGetInt(root, "ConfigRevision"); if (s->Cedar->Bridge == false && f6 != NULL) { if (GetServerCapsBool(s, "b_support_license")) { SiLoadLicenseManager(s, f6); } } DestroyServerCapsCache(s); SiLoadServerCfg(s, f1); if (s->ServerType != SERVER_TYPE_FARM_MEMBER) { SiLoadHubs(s, f2); } SiLoadListeners(s, f3); if (f4 != NULL) { SiLoadLocalBridges(s, f4); } if (s->Cedar->Bridge == false && f5 != NULL) { SiLoadL3Switchs(s, f5); } if (f7 != NULL && GetServerCapsBool(s, "b_support_ipsec")) { SiLoadIPsec(s, f7); } if (s->Cedar->Bridge == false) { if (f8 == NULL) { // Create a DDNS client with a new key s->DDnsClient = NewDDNSClient(s->Cedar, NULL, NULL); } else { // Create by reading the setting of the DDNS client UCHAR key[SHA1_SIZE]; if (CfgGetBool(f8, "Disabled")) { // Disabled } else { char machine_name[MAX_SIZE]; char machine_name2[MAX_SIZE]; INTERNET_SETTING t; BUF *pw; // Proxy Setting Zero(&t, sizeof(t)); t.ProxyType = CfgGetInt(f8, "ProxyType"); CfgGetStr(f8, "ProxyHostName", t.ProxyHostName, sizeof(t.ProxyHostName)); t.ProxyPort = CfgGetInt(f8, "ProxyPort"); CfgGetStr(f8, "ProxyUsername", t.ProxyUsername, sizeof(t.ProxyUsername)); pw = CfgGetBuf(f8, "ProxyPassword"); if (pw != NULL) { char *pw_str = DecryptPassword(pw); StrCpy(t.ProxyPassword, sizeof(t.ProxyPassword), pw_str); Free(pw_str); FreeBuf(pw); } GetMachineHostName(machine_name, sizeof(machine_name)); CfgGetStr(f8, "LocalHostname", machine_name2, sizeof(machine_name2)); if (CfgGetByte(f8, "Key", key, sizeof(key)) != sizeof(key) || StrCmpi(machine_name, machine_name2) != 0) { // Create a DDNS client with a new key s->DDnsClient = NewDDNSClient(s->Cedar, NULL, &t); } else { // Create the DDNS client with stored key s->DDnsClient = NewDDNSClient(s->Cedar, key, &t); } } } } { HUB *h = NULL; // Remove the virtual HUB "VPNGATE" when VGS disabled LockHubList(s->Cedar); { h = GetHub(s->Cedar, VG_HUBNAME); } UnlockHubList(s->Cedar); if (h != NULL) { StopHub(h); DelHub(s->Cedar, h); ReleaseHub(h); } } s->IPsecMessageDisplayed = CfgGetBool(root, "IPsecMessageDisplayed"); return true; } // Write the listener configuration void SiWriteListenerCfg(FOLDER *f, SERVER_LISTENER *r) { // Validate arguments if (f == NULL || r == NULL) { return; } CfgAddBool(f, "Enabled", r->Enabled); CfgAddInt(f, "Port", r->Port); CfgAddBool(f, "DisableDos", r->DisableDos); } // Read the listener configuration void SiLoadListenerCfg(SERVER *s, FOLDER *f) { bool enable; UINT port; bool disable_dos; // Validate arguments if (s == NULL || f == NULL) { return; } enable = CfgGetBool(f, "Enabled"); port = CfgGetInt(f, "Port"); disable_dos = CfgGetBool(f, "DisableDos"); if (port == 0) { return; } SiAddListenerEx(s, port, enable, disable_dos); } // Read the listener list void SiLoadListeners(SERVER *s, FOLDER *f) { TOKEN_LIST *t; UINT i; // Validate arguments if (s == NULL || f == NULL) { return; } t = CfgEnumFolderToTokenList(f); for (i = 0;i < t->NumTokens;i++) { FOLDER *ff = CfgGetFolder(f, t->Token[i]); if (ff != NULL) { SiLoadListenerCfg(s, ff); } } FreeToken(t); } // Write the listener list void SiWriteListeners(FOLDER *f, SERVER *s) { // Validate arguments if (f == NULL || s == NULL) { return; } LockList(s->ServerListenerList); { UINT i; for (i = 0;i < LIST_NUM(s->ServerListenerList);i++) { SERVER_LISTENER *r = LIST_DATA(s->ServerListenerList, i); char name[MAX_SIZE]; Format(name, sizeof(name), "Listener%u", i); SiWriteListenerCfg(CfgCreateFolder(f, name), r); } } UnlockList(s->ServerListenerList); } // Write the bridge void SiWriteLocalBridgeCfg(FOLDER *f, LOCALBRIDGE *br) { // Validate arguments if (f == NULL || br == NULL) { return; } CfgAddStr(f, "DeviceName", br->DeviceName); CfgAddStr(f, "HubName", br->HubName); CfgAddBool(f, "NoPromiscuousMode", br->Local); CfgAddBool(f, "MonitorMode", br->Monitor); CfgAddBool(f, "LimitBroadcast", br->LimitBroadcast); if (OS_IS_UNIX(GetOsInfo()->OsType)) { CfgAddBool(f, "TapMode", br->TapMode); if (br->TapMode) { char tmp[MAX_SIZE]; MacToStr(tmp, sizeof(tmp), br->TapMacAddress); CfgAddStr(f, "TapMacAddress", tmp); } } } // Write the bridge list void SiWriteLocalBridges(FOLDER *f, SERVER *s) { // Validate arguments if (s == NULL || f == NULL) { return; } #ifdef OS_WIN32 CfgAddBool(f, "ShowAllInterfaces", Win32EthGetShowAllIf()); CfgAddBool(f, "EnableSoftEtherKernelModeDriver", Win32GetEnableSeLow()); #endif // OS_WIN32 #ifdef UNIX_LINUX CfgAddBool(f, "DoNotDisableOffloading", GetGlobalServerFlag(GSF_LOCALBRIDGE_NO_DISABLE_OFFLOAD)); #endif // UNIX_LINUX LockList(s->Cedar->LocalBridgeList); { UINT i; for (i = 0;i < LIST_NUM(s->Cedar->LocalBridgeList);i++) { LOCALBRIDGE *br = LIST_DATA(s->Cedar->LocalBridgeList, i); char name[MAX_SIZE]; Format(name, sizeof(name), "LocalBridge%u", i); SiWriteLocalBridgeCfg(CfgCreateFolder(f, name), br); } } UnlockList(s->Cedar->LocalBridgeList); } // Read the bridge void SiLoadLocalBridgeCfg(SERVER *s, FOLDER *f) { char hub[MAX_SIZE]; char nic[MAX_SIZE]; bool tapmode = false; UCHAR tapaddr[6]; // Validate arguments if (s == NULL || f == NULL) { return; } Zero(hub, sizeof(hub)); Zero(nic, sizeof(nic)); CfgGetStr(f, "HubName", hub, sizeof(hub)); CfgGetStr(f, "DeviceName", nic, sizeof(nic)); if (IsEmptyStr(hub) || IsEmptyStr(nic) ) { return; } if (OS_IS_UNIX(GetOsInfo()->OsType)) { if (CfgGetBool(f, "TapMode")) { char tmp[MAX_SIZE]; tapmode = true; Zero(tapaddr, sizeof(tapaddr)); if (CfgGetStr(f, "TapMacAddress", tmp, sizeof(tmp))) { BUF *b; b = StrToBin(tmp); if (b != NULL && b->Size == 6) { Copy(tapaddr, b->Buf, sizeof(tapaddr)); } FreeBuf(b); } } } AddLocalBridge(s->Cedar, hub, nic, CfgGetBool(f, "NoPromiscuousMode"), CfgGetBool(f, "MonitorMode"), tapmode, tapaddr, CfgGetBool(f, "LimitBroadcast")); } // Read the bridge list void SiLoadLocalBridges(SERVER *s, FOLDER *f) { TOKEN_LIST *t; UINT i; // Validate arguments if (s == NULL || f == NULL) { return; } #ifdef OS_WIN32 Win32EthSetShowAllIf(CfgGetBool(f, "ShowAllInterfaces")); #endif // OS_WIN32 #ifdef UNIX_LINUX SetGlobalServerFlag(GSF_LOCALBRIDGE_NO_DISABLE_OFFLOAD, CfgGetBool(f, "DoNotDisableOffloading")); #endif // UNIX_LINUX t = CfgEnumFolderToTokenList(f); for (i = 0;i < t->NumTokens;i++) { char *name = t->Token[i]; SiLoadLocalBridgeCfg(s, CfgGetFolder(f, name)); } FreeToken(t); } // Increment the configuration revision of the server void IncrementServerConfigRevision(SERVER *s) { // Validate arguments if (s == NULL) { return; } s->ConfigRevision++; } // Write the server settings to CFG FOLDER *SiWriteConfigurationToCfg(SERVER *s) { FOLDER *root; char region[128]; // Validate arguments if (s == NULL) { return NULL; } root = CfgCreateFolder(NULL, TAG_ROOT); SiGetCurrentRegion(s->Cedar, region, sizeof(region)); CfgAddStr(root, "Region", region); CfgAddInt(root, "ConfigRevision", s->ConfigRevision); SiWriteListeners(CfgCreateFolder(root, "ListenerList"), s); SiWriteLocalBridges(CfgCreateFolder(root, "LocalBridgeList"), s); SiWriteServerCfg(CfgCreateFolder(root, "ServerConfiguration"), s); if (s->UpdatedServerType != SERVER_TYPE_FARM_MEMBER) { SiWriteHubs(CfgCreateFolder(root, "VirtualHUB"), s); } if (s->Cedar->Bridge == false) { SiWriteL3Switchs(CfgCreateFolder(root, "VirtualLayer3SwitchList"), s); if (GetServerCapsBool(s, "b_support_license")) { SiWriteLicenseManager(CfgCreateFolder(root, "LicenseManager"), s); } } if (s->Led) { CfgAddBool(root, "Led", true); CfgAddBool(root, "LedSpecial", s->LedSpecial); } if (GetServerCapsBool(s, "b_support_ipsec")) { SiWriteIPsec(CfgCreateFolder(root, "IPsec"), s); } if (s->Cedar->Bridge == false) { FOLDER *ddns_folder = CfgCreateFolder(root, "DDnsClient"); if (s->DDnsClient == NULL) { // Disabled CfgAddBool(ddns_folder, "Disabled", true); } else { char machine_name[MAX_SIZE]; BUF *pw; INTERNET_SETTING *t; // Enabled CfgAddBool(ddns_folder, "Disabled", false); CfgAddByte(ddns_folder, "Key", s->DDnsClient->Key, SHA1_SIZE); GetMachineHostName(machine_name, sizeof(machine_name)); CfgAddStr(ddns_folder, "LocalHostname", machine_name); t = &s->DDnsClient->InternetSetting; CfgAddInt(ddns_folder, "ProxyType", t->ProxyType); CfgAddStr(ddns_folder, "ProxyHostName", t->ProxyHostName); CfgAddInt(ddns_folder, "ProxyPort", t->ProxyPort); CfgAddStr(ddns_folder, "ProxyUsername", t->ProxyUsername); if (IsEmptyStr(t->ProxyPassword) == false) { pw = EncryptPassword(t->ProxyPassword); CfgAddBuf(ddns_folder, "ProxyPassword", pw); FreeBuf(pw); } } } CfgAddBool(root, "IPsecMessageDisplayed", s->IPsecMessageDisplayed); return root; } // Read the policy void SiLoadPolicyCfg(POLICY *p, FOLDER *f) { // Validate arguments if (f == NULL || p == NULL) { return; } Zero(p, sizeof(POLICY)); // Ver 2 p->Access = CfgGetBool(f, "Access"); p->DHCPFilter = CfgGetBool(f, "DHCPFilter"); p->DHCPNoServer = CfgGetBool(f, "DHCPNoServer"); p->DHCPForce = CfgGetBool(f, "DHCPForce"); p->NoBridge = CfgGetBool(f, "NoBridge"); p->NoRouting = CfgGetBool(f, "NoRouting"); p->CheckMac = CfgGetBool(f, "CheckMac"); p->CheckIP = CfgGetBool(f, "CheckIP"); p->ArpDhcpOnly = CfgGetBool(f, "ArpDhcpOnly"); p->PrivacyFilter = CfgGetBool(f, "PrivacyFilter"); p->NoServer = CfgGetBool(f, "NoServer"); p->NoBroadcastLimiter = CfgGetBool(f, "NoBroadcastLimiter"); p->MonitorPort = CfgGetBool(f, "MonitorPort"); p->MaxConnection = CfgGetInt(f, "MaxConnection"); p->TimeOut = CfgGetInt(f, "TimeOut"); p->MaxMac = CfgGetInt(f, "MaxMac"); p->MaxIP = CfgGetInt(f, "MaxIP"); p->MaxUpload = CfgGetInt(f, "MaxUpload"); p->MaxDownload = CfgGetInt(f, "MaxDownload"); p->FixPassword = CfgGetBool(f, "FixPassword"); p->MultiLogins = CfgGetInt(f, "MultiLogins"); p->NoQoS = CfgGetBool(f, "NoQoS"); // Ver 3 p->RSandRAFilter = CfgGetBool(f, "RSandRAFilter"); p->RAFilter = CfgGetBool(f, "RAFilter"); p->DHCPv6Filter = CfgGetBool(f, "DHCPv6Filter"); p->DHCPv6NoServer = CfgGetBool(f, "DHCPv6NoServer"); p->NoRoutingV6 = CfgGetBool(f, "NoRoutingV6"); p->CheckIPv6 = CfgGetBool(f, "CheckIPv6"); p->NoServerV6 = CfgGetBool(f, "NoServerV6"); p->MaxIPv6 = CfgGetInt(f, "MaxIPv6"); p->NoSavePassword = CfgGetBool(f, "NoSavePassword"); p->AutoDisconnect = CfgGetInt(f, "AutoDisconnect"); p->FilterIPv4 = CfgGetBool(f, "FilterIPv4"); p->FilterIPv6 = CfgGetBool(f, "FilterIPv6"); p->FilterNonIP = CfgGetBool(f, "FilterNonIP"); p->NoIPv6DefaultRouterInRA = CfgGetBool(f, "NoIPv6DefaultRouterInRA"); p->NoIPv6DefaultRouterInRAWhenIPv6 = CfgGetBool(f, "NoIPv6DefaultRouterInRAWhenIPv6"); p->VLanId = CfgGetInt(f, "VLanId"); } // Write the policy void SiWritePolicyCfg(FOLDER *f, POLICY *p, bool cascade_mode) { // Validate arguments if (f == NULL || p == NULL) { return; } // Ver 2.0 if (cascade_mode == false) { CfgAddBool(f, "Access", p->Access); } CfgAddBool(f, "DHCPFilter", p->DHCPFilter); CfgAddBool(f, "DHCPNoServer", p->DHCPNoServer); CfgAddBool(f, "DHCPForce", p->DHCPForce); if (cascade_mode == false) { CfgAddBool(f, "NoBridge", p->NoBridge); CfgAddBool(f, "NoRouting", p->NoRouting); } CfgAddBool(f, "CheckMac", p->CheckMac); CfgAddBool(f, "CheckIP", p->CheckIP); CfgAddBool(f, "ArpDhcpOnly", p->ArpDhcpOnly); if (cascade_mode == false) { CfgAddBool(f, "PrivacyFilter", p->PrivacyFilter); } CfgAddBool(f, "NoServer", p->NoServer); CfgAddBool(f, "NoBroadcastLimiter", p->NoBroadcastLimiter); if (cascade_mode == false) { CfgAddBool(f, "MonitorPort", p->MonitorPort); CfgAddInt(f, "MaxConnection", p->MaxConnection); CfgAddInt(f, "TimeOut", p->TimeOut); } CfgAddInt(f, "MaxMac", p->MaxMac); CfgAddInt(f, "MaxIP", p->MaxIP); CfgAddInt(f, "MaxUpload", p->MaxUpload); CfgAddInt(f, "MaxDownload", p->MaxDownload); if (cascade_mode == false) { CfgAddBool(f, "FixPassword", p->FixPassword); CfgAddInt(f, "MultiLogins", p->MultiLogins); CfgAddBool(f, "NoQoS", p->NoQoS); } // Ver 3.0 CfgAddBool(f, "RSandRAFilter", p->RSandRAFilter); CfgAddBool(f, "RAFilter", p->RAFilter); CfgAddBool(f, "DHCPv6Filter", p->DHCPv6Filter); CfgAddBool(f, "DHCPv6NoServer", p->DHCPv6NoServer); if (cascade_mode == false) { CfgAddBool(f, "NoRoutingV6", p->NoRoutingV6); } CfgAddBool(f, "CheckIPv6", p->CheckIPv6); CfgAddBool(f, "NoServerV6", p->NoServerV6); CfgAddInt(f, "MaxIPv6", p->MaxIPv6); if (cascade_mode == false) { CfgAddBool(f, "NoSavePassword", p->NoSavePassword); CfgAddInt(f, "AutoDisconnect", p->AutoDisconnect); } CfgAddBool(f, "FilterIPv4", p->FilterIPv4); CfgAddBool(f, "FilterIPv6", p->FilterIPv6); CfgAddBool(f, "FilterNonIP", p->FilterNonIP); CfgAddBool(f, "NoIPv6DefaultRouterInRA", p->NoIPv6DefaultRouterInRA); CfgAddBool(f, "NoIPv6DefaultRouterInRAWhenIPv6", p->NoIPv6DefaultRouterInRAWhenIPv6); CfgAddInt(f, "VLanId", p->VLanId); } // Write the link information of the Virtual HUB void SiWriteHubLinkCfg(FOLDER *f, LINK *k) { // Validate arguments if (f == NULL || k == NULL) { return; } Lock(k->lock); { // Online CfgAddBool(f, "Online", k->Offline ? false : true); // Client options CiWriteClientOption(CfgCreateFolder(f, "ClientOption"), k->Option); // Client authentication data CiWriteClientAuth(CfgCreateFolder(f, "ClientAuth"), k->Auth); // Policy if (k->Policy != NULL) { SiWritePolicyCfg(CfgCreateFolder(f, "Policy"), k->Policy, true); } CfgAddBool(f, "CheckServerCert", k->CheckServerCert); if (k->ServerCert != NULL) { BUF *b = XToBuf(k->ServerCert, false); CfgAddBuf(f, "ServerCert", b); FreeBuf(b); } } Unlock(k->lock); } // Read the link information void SiLoadHubLinkCfg(FOLDER *f, HUB *h) { bool online; CLIENT_OPTION *o; CLIENT_AUTH *a; FOLDER *pf; POLICY p; LINK *k; // Validate arguments if (f == NULL || h == NULL) { return; } pf = CfgGetFolder(f, "Policy"); if (pf == NULL) { return; } SiLoadPolicyCfg(&p, pf); online = CfgGetBool(f, "Online"); o = CiLoadClientOption(CfgGetFolder(f, "ClientOption")); a = CiLoadClientAuth(CfgGetFolder(f, "ClientAuth")); if (o == NULL || a == NULL) { Free(o); CiFreeClientAuth(a); return; } k = NewLink(h->Cedar, h, o, a, &p); if (k != NULL) { BUF *b; k->CheckServerCert = CfgGetBool(f, "CheckServerCert"); b = CfgGetBuf(f, "ServerCert"); if (b != NULL) { k->ServerCert = BufToX(b, false); FreeBuf(b); } if (online) { k->Offline = true; SetLinkOnline(k); } else { k->Offline = false; SetLinkOffline(k); } ReleaseLink(k); } Free(o); CiFreeClientAuth(a); } // Write the SecureNAT of the Virtual HUB void SiWriteSecureNAT(HUB *h, FOLDER *f) { // Validate arguments if (h == NULL || f == NULL) { return; } CfgAddBool(f, "Disabled", h->EnableSecureNAT ? false : true); NiWriteVhOptionEx(h->SecureNATOption, f); } // Read the administration options for the virtual HUB void SiLoadHubAdminOptions(HUB *h, FOLDER *f) { TOKEN_LIST *t; // Validate arguments if (h == NULL || f == NULL) { return; } t = CfgEnumItemToTokenList(f); if (t != NULL) { UINT i; LockList(h->AdminOptionList); { DeleteAllHubAdminOption(h, false); for (i = 0;i < t->NumTokens;i++) { char *name = t->Token[i]; ADMIN_OPTION *a; UINT value = CfgGetInt(f, name);; Trim(name); a = ZeroMalloc(sizeof(ADMIN_OPTION)); StrCpy(a->Name, sizeof(a->Name), name); a->Value = value; Insert(h->AdminOptionList, a); } AddHubAdminOptionsDefaults(h, false); } UnlockList(h->AdminOptionList); FreeToken(t); } } // Write the administration options for the virtual HUB void SiWriteHubAdminOptions(FOLDER *f, HUB *h) { // Validate arguments if (f == NULL || h == NULL) { return; } LockList(h->AdminOptionList); { UINT i; for (i = 0;i < LIST_NUM(h->AdminOptionList);i++) { ADMIN_OPTION *a = LIST_DATA(h->AdminOptionList, i); CfgAddInt(f, a->Name, a->Value); } } UnlockList(h->AdminOptionList); } // Write the link list of the Virtual HUB void SiWriteHubLinks(FOLDER *f, HUB *h) { // Validate arguments if (f == NULL || h == NULL) { return; } LockList(h->LinkList); { UINT i; for (i = 0;i < LIST_NUM(h->LinkList);i++) { LINK *k = LIST_DATA(h->LinkList, i); char name[MAX_SIZE]; Format(name, sizeof(name), "Cascade%u", i); SiWriteHubLinkCfg(CfgCreateFolder(f, name), k); } } UnlockList(h->LinkList); } // Read the link list void SiLoadHubLinks(HUB *h, FOLDER *f) { TOKEN_LIST *t; UINT i; // Validate arguments if (h == NULL || f == NULL) { return; } t = CfgEnumFolderToTokenList(f); for (i = 0;i < t->NumTokens;i++) { char *name = t->Token[i]; SiLoadHubLinkCfg(CfgGetFolder(f, name), h); } FreeToken(t); } // Write an item of the access list void SiWriteHubAccessCfg(FOLDER *f, ACCESS *a) { // Validate arguments if (f == NULL || a == NULL) { return; } CfgAddUniStr(f, "Note", a->Note); CfgAddBool(f, "Active", a->Active); CfgAddInt(f, "Priority", a->Priority); CfgAddBool(f, "Discard", a->Discard); CfgAddBool(f, "IsIPv6", a->IsIPv6); if (a->IsIPv6 == false) { CfgAddIp32(f, "SrcIpAddress", a->SrcIpAddress); CfgAddIp32(f, "SrcSubnetMask", a->SrcSubnetMask); CfgAddIp32(f, "DestIpAddress", a->DestIpAddress); CfgAddIp32(f, "DestSubnetMask", a->DestSubnetMask); } else { CfgAddIp6Addr(f, "SrcIpAddress6", &a->SrcIpAddress6); CfgAddIp6Addr(f, "SrcSubnetMask6", &a->SrcSubnetMask6); CfgAddIp6Addr(f, "DestIpAddress6", &a->DestIpAddress6); CfgAddIp6Addr(f, "DestSubnetMask6", &a->DestSubnetMask6); } CfgAddInt(f, "Protocol", a->Protocol); CfgAddInt(f, "SrcPortStart", a->SrcPortStart); CfgAddInt(f, "SrcPortEnd", a->SrcPortEnd); CfgAddInt(f, "DestPortStart", a->DestPortStart); CfgAddInt(f, "DestPortEnd", a->DestPortEnd); CfgAddStr(f, "SrcUsername", a->SrcUsername); CfgAddStr(f, "DestUsername", a->DestUsername); CfgAddBool(f, "CheckSrcMac", a->CheckSrcMac); if (a->CheckSrcMac) { char tmp[MAX_PATH]; MacToStr(tmp, sizeof(tmp), a->SrcMacAddress); CfgAddStr(f, "SrcMacAddress", tmp); MacToStr(tmp, sizeof(tmp), a->SrcMacMask); CfgAddStr(f, "SrcMacMask", tmp); } CfgAddBool(f, "CheckDstMac", a->CheckDstMac); if (a->CheckDstMac) { char tmp[MAX_PATH]; MacToStr(tmp, sizeof(tmp), a->DstMacAddress); CfgAddStr(f, "DstMacAddress", tmp); MacToStr(tmp, sizeof(tmp), a->DstMacMask); CfgAddStr(f, "DstMacMask", tmp); } CfgAddBool(f, "CheckTcpState", a->CheckTcpState); CfgAddBool(f, "Established", a->Established); CfgAddStr(f, "RedirectUrl", a->RedirectUrl); CfgAddInt(f, "Delay", a->Delay); CfgAddInt(f, "Jitter", a->Jitter); CfgAddInt(f, "Loss", a->Loss); } // Read an item of the access list void SiLoadHubAccessCfg(HUB *h, FOLDER *f) { ACCESS a; char tmp[MAX_PATH]; // Validate arguments if (h == NULL || f == NULL) { return; } Zero(&a, sizeof(a)); CfgGetUniStr(f, "Note", a.Note, sizeof(a.Note)); a.Active = CfgGetBool(f, "Active"); a.Priority = CfgGetInt(f, "Priority"); a.Discard = CfgGetBool(f, "Discard"); a.IsIPv6 = CfgGetBool(f, "IsIPv6"); if (a.IsIPv6 == false) { a.SrcIpAddress = CfgGetIp32(f, "SrcIpAddress"); a.SrcSubnetMask = CfgGetIp32(f, "SrcSubnetMask"); a.DestIpAddress = CfgGetIp32(f, "DestIpAddress"); a.DestSubnetMask = CfgGetIp32(f, "DestSubnetMask"); } else { CfgGetIp6Addr(f, "SrcIpAddress6", &a.SrcIpAddress6); CfgGetIp6Addr(f, "SrcSubnetMask6", &a.SrcSubnetMask6); CfgGetIp6Addr(f, "DestIpAddress6", &a.DestIpAddress6); CfgGetIp6Addr(f, "DestSubnetMask6", &a.DestSubnetMask6); } a.Protocol = CfgGetInt(f, "Protocol"); a.SrcPortStart = CfgGetInt(f, "SrcPortStart"); a.SrcPortEnd = CfgGetInt(f, "SrcPortEnd"); a.DestPortStart = CfgGetInt(f, "DestPortStart"); a.DestPortEnd = CfgGetInt(f, "DestPortEnd"); CfgGetStr(f, "SrcUsername", a.SrcUsername, sizeof(a.SrcUsername)); CfgGetStr(f, "DestUsername", a.DestUsername, sizeof(a.DestUsername)); a.CheckSrcMac = CfgGetBool(f, "CheckSrcMac"); if (CfgGetByte(f, "SrcMacAddress", a.SrcMacAddress, sizeof(a.SrcMacAddress)) == 0) { CfgGetStr(f, "SrcMacAddress", tmp, sizeof(tmp)); if (StrToMac(a.SrcMacAddress, tmp) == false) { a.CheckSrcMac = false; } } if (CfgGetByte(f, "SrcMacMask", a.SrcMacMask, sizeof(a.SrcMacMask)) == 0) { CfgGetStr(f, "SrcMacMask", tmp, sizeof(tmp)); if (StrToMac(a.SrcMacMask, tmp) == false) { a.CheckSrcMac = false; } } a.CheckDstMac = CfgGetBool(f, "CheckDstMac"); if (CfgGetByte(f, "DstMacAddress", a.DstMacAddress, sizeof(a.DstMacAddress)) == 0) { CfgGetStr(f, "DstMacAddress", tmp, sizeof(tmp)); if (StrToMac(a.DstMacAddress, tmp) == false) { a.CheckDstMac = false; } } if (CfgGetByte(f, "DstMacMask", a.DstMacMask, sizeof(a.DstMacMask)) == 0) { CfgGetStr(f, "DstMacMask", tmp, sizeof(tmp)); if (StrToMac(a.DstMacMask, tmp) == false) { a.CheckDstMac = false; } } a.CheckTcpState = CfgGetBool(f, "CheckTcpState"); a.Established = CfgGetBool(f, "Established"); a.Delay = MAKESURE(CfgGetInt(f, "Delay"), 0, HUB_ACCESSLIST_DELAY_MAX); a.Jitter = MAKESURE(CfgGetInt(f, "Jitter"), 0, HUB_ACCESSLIST_JITTER_MAX); a.Loss = MAKESURE(CfgGetInt(f, "Loss"), 0, HUB_ACCESSLIST_LOSS_MAX); CfgGetStr(f, "RedirectUrl", a.RedirectUrl, sizeof(a.RedirectUrl)); AddAccessList(h, &a); } // Write the access list void SiWriteHubAccessLists(FOLDER *f, HUB *h) { // Validate arguments if (f == NULL || h == NULL) { return; } LockList(h->AccessList); { UINT i; for (i = 0;i < LIST_NUM(h->AccessList);i++) { ACCESS *a = LIST_DATA(h->AccessList, i); char name[MAX_SIZE]; ToStr(name, a->Id); SiWriteHubAccessCfg(CfgCreateFolder(f, name), a); } } UnlockList(h->AccessList); } // Read the access list void SiLoadHubAccessLists(HUB *h, FOLDER *f) { TOKEN_LIST *t; UINT i; // Validate arguments if (f == NULL || h == NULL) { return; } t = CfgEnumFolderToTokenList(f); for (i = 0;i < t->NumTokens;i++) { char *name = t->Token[i]; UINT id = ToInt(name); SiLoadHubAccessCfg(h, CfgGetFolder(f, name)); } FreeToken(t); } // Read the HUB_OPTION void SiLoadHubOptionCfg(FOLDER *f, HUB_OPTION *o) { char tmp[MAX_SIZE]; // Validate arguments if (f == NULL || o == NULL) { return; } o->MaxSession = CfgGetInt(f, "MaxSession"); o->NoArpPolling = CfgGetBool(f, "NoArpPolling"); o->NoIPv6AddrPolling = CfgGetBool(f, "NoIPv6AddrPolling"); o->NoIpTable = CfgGetBool(f, "NoIpTable"); o->NoEnum = CfgGetBool(f, "NoEnum"); o->FilterPPPoE = CfgGetBool(f, "FilterPPPoE"); o->FilterOSPF = CfgGetBool(f, "FilterOSPF"); o->FilterIPv4 = CfgGetBool(f, "FilterIPv4"); o->FilterIPv6 = CfgGetBool(f, "FilterIPv6"); o->FilterNonIP = CfgGetBool(f, "FilterNonIP"); o->FilterBPDU = CfgGetBool(f, "FilterBPDU"); o->NoIPv4PacketLog = CfgGetBool(f, "NoIPv4PacketLog"); o->NoIPv6PacketLog = CfgGetBool(f, "NoIPv6PacketLog"); o->NoIPv6DefaultRouterInRAWhenIPv6 = CfgGetBool(f, "NoIPv6DefaultRouterInRAWhenIPv6"); o->DisableIPParsing = CfgGetBool(f, "DisableIPParsing"); o->YieldAfterStorePacket = CfgGetBool(f, "YieldAfterStorePacket"); o->NoSpinLockForPacketDelay = CfgGetBool(f, "NoSpinLockForPacketDelay"); o->BroadcastStormDetectionThreshold = CfgGetInt(f, "BroadcastStormDetectionThreshold"); o->ClientMinimumRequiredBuild = CfgGetInt(f, "ClientMinimumRequiredBuild"); o->RequiredClientId = CfgGetInt(f, "RequiredClientId"); o->NoManageVlanId = CfgGetBool(f, "NoManageVlanId"); o->VlanTypeId = 0; if (CfgGetStr(f, "VlanTypeId", tmp, sizeof(tmp))) { o->VlanTypeId = HexToInt(tmp); } if (o->VlanTypeId == 0) { o->VlanTypeId = MAC_PROTO_TAGVLAN; } o->FixForDLinkBPDU = CfgGetBool(f, "FixForDLinkBPDU"); o->BroadcastLimiterStrictMode = CfgGetBool(f, "BroadcastLimiterStrictMode"); o->MaxLoggedPacketsPerMinute = CfgGetInt(f, "MaxLoggedPacketsPerMinute"); if (CfgIsItem(f, "FloodingSendQueueBufferQuota")) { o->FloodingSendQueueBufferQuota = CfgGetInt(f, "FloodingSendQueueBufferQuota"); } else { o->FloodingSendQueueBufferQuota = DEFAULT_FLOODING_QUEUE_LENGTH; } o->DoNotSaveHeavySecurityLogs = CfgGetBool(f, "DoNotSaveHeavySecurityLogs"); if (CfgIsItem(f, "DropBroadcastsInPrivacyFilterMode")) { o->DropBroadcastsInPrivacyFilterMode = CfgGetBool(f, "DropBroadcastsInPrivacyFilterMode"); } else { o->DropBroadcastsInPrivacyFilterMode = true; } if (CfgIsItem(f, "DropArpInPrivacyFilterMode")) { o->DropArpInPrivacyFilterMode = CfgGetBool(f, "DropArpInPrivacyFilterMode"); } else { o->DropArpInPrivacyFilterMode = true; } o->NoLookBPDUBridgeId = CfgGetBool(f, "NoLookBPDUBridgeId"); o->AdjustTcpMssValue = CfgGetInt(f, "AdjustTcpMssValue"); o->DisableAdjustTcpMss = CfgGetBool(f, "DisableAdjustTcpMss"); if (CfgIsItem(f, "NoDhcpPacketLogOutsideHub")) { o->NoDhcpPacketLogOutsideHub = CfgGetBool(f, "NoDhcpPacketLogOutsideHub"); } else { o->NoDhcpPacketLogOutsideHub = true; } o->DisableHttpParsing = CfgGetBool(f, "DisableHttpParsing"); o->DisableUdpAcceleration = CfgGetBool(f, "DisableUdpAcceleration"); o->DisableUdpFilterForLocalBridgeNic = CfgGetBool(f, "DisableUdpFilterForLocalBridgeNic"); o->ApplyIPv4AccessListOnArpPacket = CfgGetBool(f, "ApplyIPv4AccessListOnArpPacket"); if (CfgIsItem(f, "RemoveDefGwOnDhcpForLocalhost")) { o->RemoveDefGwOnDhcpForLocalhost = CfgGetBool(f, "RemoveDefGwOnDhcpForLocalhost"); } else { o->RemoveDefGwOnDhcpForLocalhost = true; } o->SecureNAT_MaxTcpSessionsPerIp = CfgGetInt(f, "SecureNAT_MaxTcpSessionsPerIp"); o->SecureNAT_MaxTcpSynSentPerIp = CfgGetInt(f, "SecureNAT_MaxTcpSynSentPerIp"); o->SecureNAT_MaxUdpSessionsPerIp = CfgGetInt(f, "SecureNAT_MaxUdpSessionsPerIp"); o->SecureNAT_MaxDnsSessionsPerIp = CfgGetInt(f, "SecureNAT_MaxDnsSessionsPerIp"); o->SecureNAT_MaxIcmpSessionsPerIp = CfgGetInt(f, "SecureNAT_MaxIcmpSessionsPerIp"); o->AccessListIncludeFileCacheLifetime = CfgGetInt(f, "AccessListIncludeFileCacheLifetime"); if (o->AccessListIncludeFileCacheLifetime == 0) { o->AccessListIncludeFileCacheLifetime = ACCESS_LIST_INCLUDE_FILE_CACHE_LIFETIME; } o->DisableKernelModeSecureNAT = CfgGetBool(f, "DisableKernelModeSecureNAT"); o->DisableUserModeSecureNAT = CfgGetBool(f, "DisableUserModeSecureNAT"); o->DisableCheckMacOnLocalBridge = CfgGetBool(f, "DisableCheckMacOnLocalBridge"); o->DisableCorrectIpOffloadChecksum = CfgGetBool(f, "DisableCorrectIpOffloadChecksum"); o->SuppressClientUpdateNotification = CfgGetBool(f, "SuppressClientUpdateNotification"); o->AssignVLanIdByRadiusAttribute = CfgGetBool(f, "AssignVLanIdByRadiusAttribute"); o->SecureNAT_RandomizeAssignIp = CfgGetBool(f, "SecureNAT_RandomizeAssignIp"); o->DetectDormantSessionInterval = CfgGetInt(f, "DetectDormantSessionInterval"); o->NoPhysicalIPOnPacketLog = CfgGetBool(f, "NoPhysicalIPOnPacketLog"); // Enabled by default if (CfgIsItem(f, "ManageOnlyPrivateIP")) { o->ManageOnlyPrivateIP = CfgGetBool(f, "ManageOnlyPrivateIP"); } else { o->ManageOnlyPrivateIP = true; } if (CfgIsItem(f, "ManageOnlyLocalUnicastIPv6")) { o->ManageOnlyLocalUnicastIPv6 = CfgGetBool(f, "ManageOnlyLocalUnicastIPv6"); } else { o->ManageOnlyLocalUnicastIPv6 = true; } if (CfgIsItem(f, "NoMacAddressLog")) { o->NoMacAddressLog = CfgGetBool(f, "NoMacAddressLog"); } else { o->NoMacAddressLog = true; } } // Write the HUB_OPTION void SiWriteHubOptionCfg(FOLDER *f, HUB_OPTION *o) { char tmp[MAX_SIZE]; // Validate arguments if (f == NULL || o == NULL) { return; } CfgAddInt(f, "MaxSession", o->MaxSession); CfgAddBool(f, "NoArpPolling", o->NoArpPolling); CfgAddBool(f, "NoIPv6AddrPolling", o->NoIPv6AddrPolling); CfgAddBool(f, "NoIpTable", o->NoIpTable); CfgAddBool(f, "NoEnum", o->NoEnum); CfgAddBool(f, "FilterPPPoE", o->FilterPPPoE); CfgAddBool(f, "FilterOSPF", o->FilterOSPF); CfgAddBool(f, "FilterIPv4", o->FilterIPv4); CfgAddBool(f, "FilterIPv6", o->FilterIPv6); CfgAddBool(f, "FilterNonIP", o->FilterNonIP); CfgAddBool(f, "NoIPv4PacketLog", o->NoIPv4PacketLog); CfgAddBool(f, "NoIPv6PacketLog", o->NoIPv6PacketLog); CfgAddBool(f, "FilterBPDU", o->FilterBPDU); CfgAddBool(f, "NoIPv6DefaultRouterInRAWhenIPv6", o->NoIPv6DefaultRouterInRAWhenIPv6); CfgAddBool(f, "NoMacAddressLog", o->NoMacAddressLog); CfgAddBool(f, "ManageOnlyPrivateIP", o->ManageOnlyPrivateIP); CfgAddBool(f, "ManageOnlyLocalUnicastIPv6", o->ManageOnlyLocalUnicastIPv6); CfgAddBool(f, "DisableIPParsing", o->DisableIPParsing); CfgAddBool(f, "YieldAfterStorePacket", o->YieldAfterStorePacket); CfgAddBool(f, "NoSpinLockForPacketDelay", o->NoSpinLockForPacketDelay); CfgAddInt(f, "BroadcastStormDetectionThreshold", o->BroadcastStormDetectionThreshold); CfgAddInt(f, "ClientMinimumRequiredBuild", o->ClientMinimumRequiredBuild); CfgAddInt(f, "RequiredClientId", o->RequiredClientId); CfgAddBool(f, "NoManageVlanId", o->NoManageVlanId); Format(tmp, sizeof(tmp), "0x%x", o->VlanTypeId); CfgAddStr(f, "VlanTypeId", tmp); if (o->FixForDLinkBPDU) { CfgAddBool(f, "FixForDLinkBPDU", o->FixForDLinkBPDU); } CfgAddBool(f, "BroadcastLimiterStrictMode", o->BroadcastLimiterStrictMode); CfgAddInt(f, "MaxLoggedPacketsPerMinute", o->MaxLoggedPacketsPerMinute); CfgAddInt(f, "FloodingSendQueueBufferQuota", o->FloodingSendQueueBufferQuota); CfgAddBool(f, "DoNotSaveHeavySecurityLogs", o->DoNotSaveHeavySecurityLogs); CfgAddBool(f, "DropBroadcastsInPrivacyFilterMode", o->DropBroadcastsInPrivacyFilterMode); CfgAddBool(f, "DropArpInPrivacyFilterMode", o->DropArpInPrivacyFilterMode); CfgAddBool(f, "SuppressClientUpdateNotification", o->SuppressClientUpdateNotification); CfgAddBool(f, "AssignVLanIdByRadiusAttribute", o->AssignVLanIdByRadiusAttribute); CfgAddBool(f, "SecureNAT_RandomizeAssignIp", o->SecureNAT_RandomizeAssignIp); CfgAddBool(f, "NoPhysicalIPOnPacketLog", o->NoPhysicalIPOnPacketLog); CfgAddInt(f, "DetectDormantSessionInterval", o->DetectDormantSessionInterval); CfgAddBool(f, "NoLookBPDUBridgeId", o->NoLookBPDUBridgeId); CfgAddInt(f, "AdjustTcpMssValue", o->AdjustTcpMssValue); CfgAddBool(f, "DisableAdjustTcpMss", o->DisableAdjustTcpMss); CfgAddBool(f, "NoDhcpPacketLogOutsideHub", o->NoDhcpPacketLogOutsideHub); CfgAddBool(f, "DisableHttpParsing", o->DisableHttpParsing); CfgAddBool(f, "DisableUdpAcceleration", o->DisableUdpAcceleration); CfgAddBool(f, "DisableUdpFilterForLocalBridgeNic", o->DisableUdpFilterForLocalBridgeNic); CfgAddBool(f, "ApplyIPv4AccessListOnArpPacket", o->ApplyIPv4AccessListOnArpPacket); CfgAddBool(f, "RemoveDefGwOnDhcpForLocalhost", o->RemoveDefGwOnDhcpForLocalhost); CfgAddInt(f, "SecureNAT_MaxTcpSessionsPerIp", o->SecureNAT_MaxTcpSessionsPerIp); CfgAddInt(f, "SecureNAT_MaxTcpSynSentPerIp", o->SecureNAT_MaxTcpSynSentPerIp); CfgAddInt(f, "SecureNAT_MaxUdpSessionsPerIp", o->SecureNAT_MaxUdpSessionsPerIp); CfgAddInt(f, "SecureNAT_MaxDnsSessionsPerIp", o->SecureNAT_MaxDnsSessionsPerIp); CfgAddInt(f, "SecureNAT_MaxIcmpSessionsPerIp", o->SecureNAT_MaxIcmpSessionsPerIp); CfgAddInt(f, "AccessListIncludeFileCacheLifetime", o->AccessListIncludeFileCacheLifetime); CfgAddBool(f, "DisableKernelModeSecureNAT", o->DisableKernelModeSecureNAT); CfgAddBool(f, "DisableUserModeSecureNAT", o->DisableUserModeSecureNAT); CfgAddBool(f, "DisableCheckMacOnLocalBridge", o->DisableCheckMacOnLocalBridge); CfgAddBool(f, "DisableCorrectIpOffloadChecksum", o->DisableCorrectIpOffloadChecksum); } // Write the user void SiWriteUserCfg(FOLDER *f, USER *u) { BUF *b; AUTHPASSWORD *password; AUTHRADIUS *radius; AUTHNT *nt; AUTHUSERCERT *usercert; AUTHROOTCERT *rootcert; // Validate arguments if (f == NULL || u == NULL) { return; } Lock(u->lock); { CfgAddUniStr(f, "RealName", u->RealName); CfgAddUniStr(f, "Note", u->Note); if (u->Group != NULL) { CfgAddStr(f, "GroupName", u->GroupName); } CfgAddInt64(f, "CreatedTime", u->CreatedTime); CfgAddInt64(f, "UpdatedTime", u->UpdatedTime); CfgAddInt64(f, "ExpireTime", u->ExpireTime); CfgAddInt64(f, "LastLoginTime", u->LastLoginTime); CfgAddInt(f, "NumLogin", u->NumLogin); if (u->Policy != NULL) { SiWritePolicyCfg(CfgCreateFolder(f, "Policy"), u->Policy, false); } SiWriteTraffic(f, "Traffic", u->Traffic); CfgAddInt(f, "AuthType", u->AuthType); if (u->AuthData != NULL) { switch (u->AuthType) { case AUTHTYPE_ANONYMOUS: break; case AUTHTYPE_PASSWORD: password = (AUTHPASSWORD *)u->AuthData; CfgAddByte(f, "AuthPassword", password->HashedKey, sizeof(password->HashedKey)); if (IsZero(password->NtLmSecureHash, sizeof(password->NtLmSecureHash)) == false) { CfgAddByte(f, "AuthNtLmSecureHash", password->NtLmSecureHash, sizeof(password->NtLmSecureHash)); } break; case AUTHTYPE_NT: nt = (AUTHNT *)u->AuthData; CfgAddUniStr(f, "AuthNtUserName", nt->NtUsername); break; case AUTHTYPE_RADIUS: radius = (AUTHRADIUS *)u->AuthData; CfgAddUniStr(f, "AuthRadiusUsername", radius->RadiusUsername); break; case AUTHTYPE_USERCERT: usercert = (AUTHUSERCERT *)u->AuthData; b = XToBuf(usercert->UserX, false); if (b != NULL) { CfgAddBuf(f, "AuthUserCert", b); FreeBuf(b); } break; case AUTHTYPE_ROOTCERT: rootcert = (AUTHROOTCERT *)u->AuthData; if (rootcert->Serial != NULL && rootcert->Serial->size >= 1) { CfgAddByte(f, "AuthSerial", rootcert->Serial->data, rootcert->Serial->size); } if (rootcert->CommonName != NULL && UniIsEmptyStr(rootcert->CommonName) == false) { CfgAddUniStr(f, "AuthCommonName", rootcert->CommonName); } break; } } } Unlock(u->lock); } // Read an user void SiLoadUserCfg(HUB *h, FOLDER *f) { char *username; wchar_t realname[MAX_SIZE]; wchar_t note[MAX_SIZE]; char groupname[MAX_SIZE]; FOLDER *pf; UINT64 created_time; UINT64 updated_time; UINT64 expire_time; UINT64 last_login_time; UINT num_login; POLICY p; TRAFFIC t; BUF *b; UINT authtype; void *authdata; X_SERIAL *serial = NULL; wchar_t common_name[MAX_SIZE]; UCHAR hashed_password[SHA1_SIZE]; UCHAR md4_password[MD5_SIZE]; wchar_t tmp[MAX_SIZE]; USER *u; USERGROUP *g; // Validate arguments if (h == NULL || f == NULL) { return; } username = f->Name; CfgGetUniStr(f, "RealName", realname, sizeof(realname)); CfgGetUniStr(f, "Note", note, sizeof(note)); CfgGetStr(f, "GroupName", groupname, sizeof(groupname)); created_time = CfgGetInt64(f, "CreatedTime"); updated_time = CfgGetInt64(f, "UpdatedTime"); expire_time = CfgGetInt64(f, "ExpireTime"); last_login_time = CfgGetInt64(f, "LastLoginTime"); num_login = CfgGetInt(f, "NumLogin"); pf = CfgGetFolder(f, "Policy"); if (pf != NULL) { SiLoadPolicyCfg(&p, pf); } SiLoadTraffic(f, "Traffic", &t); authtype = CfgGetInt(f, "AuthType"); authdata = NULL; switch (authtype) { case AUTHTYPE_PASSWORD: Zero(hashed_password, sizeof(hashed_password)); Zero(md4_password, sizeof(md4_password)); CfgGetByte(f, "AuthPassword", hashed_password, sizeof(hashed_password)); CfgGetByte(f, "AuthNtLmSecureHash", md4_password, sizeof(md4_password)); authdata = NewPasswordAuthDataRaw(hashed_password, md4_password); break; case AUTHTYPE_NT: if (CfgGetUniStr(f, "AuthNtUserName", tmp, sizeof(tmp))) { authdata = NewNTAuthData(tmp); } else { authdata = NewNTAuthData(NULL); } break; case AUTHTYPE_RADIUS: if (CfgGetUniStr(f, "AuthRadiusUsername", tmp, sizeof(tmp))) { authdata = NewRadiusAuthData(tmp); } else { authdata = NewRadiusAuthData(NULL); } break; case AUTHTYPE_USERCERT: b = CfgGetBuf(f, "AuthUserCert"); if (b != NULL) { X *x = BufToX(b, false); if (x != NULL) { authdata = NewUserCertAuthData(x); FreeX(x); } FreeBuf(b); } break; case AUTHTYPE_ROOTCERT: b = CfgGetBuf(f, "AuthSerial"); if (b != NULL) { serial = NewXSerial(b->Buf, b->Size); FreeBuf(b); } CfgGetUniStr(f, "AuthCommonName", common_name, sizeof(common_name)); authdata = NewRootCertAuthData(serial, common_name); break; } // Add an user AcLock(h); { if (StrLen(groupname) > 0) { g = AcGetGroup(h, groupname); } else { g = NULL; } u = NewUser(username, realname, note, authtype, authdata); if (u != NULL) { if (g != NULL) { JoinUserToGroup(u, g); } SetUserTraffic(u, &t); if (pf != NULL) { SetUserPolicy(u, &p); } Lock(u->lock); { u->CreatedTime = created_time; u->UpdatedTime = updated_time; u->ExpireTime = expire_time; u->LastLoginTime = last_login_time; u->NumLogin = num_login; } Unlock(u->lock); AcAddUser(h, u); ReleaseUser(u); } if (g != NULL) { ReleaseGroup(g); } } AcUnlock(h); if (serial != NULL) { FreeXSerial(serial); } } // Write the user list void SiWriteUserList(FOLDER *f, LIST *o) { // Validate arguments if (f == NULL || o == NULL) { return; } LockList(o); { UINT i; for (i = 0;i < LIST_NUM(o);i++) { USER *u = LIST_DATA(o, i); SiWriteUserCfg(CfgCreateFolder(f, u->Name), u); } } UnlockList(o); } // Read the user list void SiLoadUserList(HUB *h, FOLDER *f) { TOKEN_LIST *t; UINT i; char *name; // Validate arguments if (f == NULL || h == NULL) { return; } t = CfgEnumFolderToTokenList(f); for (i = 0;i < t->NumTokens;i++) { FOLDER *ff; name = t->Token[i]; ff = CfgGetFolder(f, name); SiLoadUserCfg(h, ff); } FreeToken(t); } // Write the group information void SiWriteGroupCfg(FOLDER *f, USERGROUP *g) { // Validate arguments if (f == NULL || g == NULL) { return; } Lock(g->lock); { CfgAddUniStr(f, "RealName", g->RealName); CfgAddUniStr(f, "Note", g->Note); if (g->Policy != NULL) { SiWritePolicyCfg(CfgCreateFolder(f, "Policy"), g->Policy, false); } SiWriteTraffic(f, "Traffic", g->Traffic); } Unlock(g->lock); } // Read the group information void SiLoadGroupCfg(HUB *h, FOLDER *f) { wchar_t realname[MAX_SIZE]; wchar_t note[MAX_SIZE]; char *name; FOLDER *pf; POLICY p; TRAFFIC t; USERGROUP *g; // Validate arguments if (h == NULL || f == NULL) { return; } name = f->Name; CfgGetUniStr(f, "RealName", realname, sizeof(realname)); CfgGetUniStr(f, "Note", note, sizeof(note)); pf = CfgGetFolder(f, "Policy"); if (pf != NULL) { SiLoadPolicyCfg(&p, pf); } SiLoadTraffic(f, "Traffic", &t); g = NewGroup(name, realname, note); if (g == NULL) { return; } if (pf != NULL) { SetGroupPolicy(g, &p); } SetGroupTraffic(g, &t); AcLock(h); { AcAddGroup(h, g); } AcUnlock(h); ReleaseGroup(g); } // Write the group list void SiWriteGroupList(FOLDER *f, LIST *o) { // Validate arguments if (f == NULL || o == NULL) { return; } LockList(o); { UINT i; for (i = 0;i < LIST_NUM(o);i++) { USERGROUP *g = LIST_DATA(o, i); SiWriteGroupCfg(CfgCreateFolder(f, g->Name), g); } } UnlockList(o); } // Read the group List void SiLoadGroupList(HUB *h, FOLDER *f) { TOKEN_LIST *t; UINT i; char *name; // Validate arguments if (f == NULL || h == NULL) { return; } t = CfgEnumFolderToTokenList(f); for (i = 0;i < t->NumTokens;i++) { name = t->Token[i]; SiLoadGroupCfg(h, CfgGetFolder(f, name)); } FreeToken(t); } // Write the AC list void SiWriteAcList(FOLDER *f, LIST *o) { // Validate arguments if (f == NULL || o == NULL) { return; } LockList(o); { UINT i; for (i = 0;i < LIST_NUM(o);i++) { char name[MAX_SIZE]; AC *ac = LIST_DATA(o, i); FOLDER *ff; Format(name, sizeof(name), "Acl%u", i + 1); ff = CfgCreateFolder(f, name); CfgAddBool(ff, "Deny", ac->Deny); CfgAddInt(ff, "Priority", ac->Priority); CfgAddIp(ff, "IpAddress", &ac->IpAddress); if (ac->Masked) { CfgAddIp(ff, "NetMask", &ac->SubnetMask); } } } UnlockList(o); } // Read the AC list void SiLoadAcList(LIST *o, FOLDER *f) { // Validate arguments if (o == NULL || f == NULL) { return; } LockList(o); { TOKEN_LIST *t = CfgEnumFolderToTokenList(f); if (t != NULL) { UINT i; for (i = 0;i < t->NumTokens;i++) { FOLDER *ff = CfgGetFolder(f, t->Token[i]); if (ff != NULL) { AC ac; Zero(&ac, sizeof(ac)); ac.Deny = CfgGetBool(ff, "Deny"); ac.Priority = CfgGetInt(ff, "Priority"); CfgGetIp(ff, "IpAddress", &ac.IpAddress); if (CfgGetIp(ff, "NetMask", &ac.SubnetMask)) { ac.Masked = true; } AddAc(o, &ac); } } FreeToken(t); } } UnlockList(o); } // Write the certificate revocation list void SiWriteCrlList(FOLDER *f, LIST *o) { // Validate arguments if (f == NULL || o == NULL) { return; } LockList(o); { UINT i; for (i = 0;i < LIST_NUM(o);i++) { char name[MAX_SIZE]; CRL *crl = LIST_DATA(o, i); FOLDER *ff; NAME *n; Format(name, sizeof(name), "Crl%u", i); ff = CfgCreateFolder(f, name); n = crl->Name; if (UniIsEmptyStr(n->CommonName) == false) { CfgAddUniStr(ff, "CommonName", n->CommonName); } if (UniIsEmptyStr(n->Organization) == false) { CfgAddUniStr(ff, "Organization", n->Organization); } if (UniIsEmptyStr(n->Unit) == false) { CfgAddUniStr(ff, "Unit", n->Unit); } if (UniIsEmptyStr(n->Country) == false) { CfgAddUniStr(ff, "Country", n->Country); } if (UniIsEmptyStr(n->State) == false) { CfgAddUniStr(ff, "State", n->State); } if (UniIsEmptyStr(n->Local) == false) { CfgAddUniStr(ff, "Local", n->Local); } if (IsZero(crl->DigestMD5, MD5_SIZE) == false) { char tmp[MAX_SIZE]; BinToStr(tmp, sizeof(tmp), crl->DigestMD5, MD5_SIZE); CfgAddStr(ff, "DigestMD5", tmp); } if (IsZero(crl->DigestSHA1, SHA1_SIZE) == false) { char tmp[MAX_SIZE]; BinToStr(tmp, sizeof(tmp), crl->DigestSHA1, SHA1_SIZE); CfgAddStr(ff, "DigestSHA1", tmp); } if (crl->Serial != NULL) { char tmp[MAX_SIZE]; BinToStr(tmp, sizeof(tmp), crl->Serial->data, crl->Serial->size); CfgAddStr(ff, "Serial", tmp); } } } UnlockList(o); } // Read the certificate revocation list void SiLoadCrlList(LIST *o, FOLDER *f) { // Validate arguments if (o == NULL || f == NULL) { return; } LockList(o); { UINT i; TOKEN_LIST *t; t = CfgEnumFolderToTokenList(f); for (i = 0;i < t->NumTokens;i++) { CRL *crl; FOLDER *ff = CfgGetFolder(f, t->Token[i]); wchar_t cn[MAX_SIZE], org[MAX_SIZE], u[MAX_SIZE], c[MAX_SIZE], st[MAX_SIZE], l[MAX_SIZE]; char tmp[MAX_SIZE]; if (ff != NULL) { BUF *b; crl = ZeroMalloc(sizeof(CRL)); CfgGetUniStr(ff, "CommonName", cn, sizeof(cn)); CfgGetUniStr(ff, "Organization", org, sizeof(org)); CfgGetUniStr(ff, "Unit", u, sizeof(u)); CfgGetUniStr(ff, "Country", c, sizeof(c)); CfgGetUniStr(ff, "State", st, sizeof(st)); CfgGetUniStr(ff, "Local", l, sizeof(l)); crl->Name = NewName(cn, org, u, c, st, l); if (CfgGetStr(ff, "Serial", tmp, sizeof(tmp))) { b = StrToBin(tmp); if (b != NULL) { if (b->Size >= 1) { crl->Serial = NewXSerial(b->Buf, b->Size); } FreeBuf(b); } } if (CfgGetStr(ff, "DigestMD5", tmp, sizeof(tmp))) { b = StrToBin(tmp); if (b != NULL) { if (b->Size == MD5_SIZE) { Copy(crl->DigestMD5, b->Buf, MD5_SIZE); } FreeBuf(b); } } if (CfgGetStr(ff, "DigestSHA1", tmp, sizeof(tmp))) { b = StrToBin(tmp); if (b != NULL) { if (b->Size == SHA1_SIZE) { Copy(crl->DigestSHA1, b->Buf, SHA1_SIZE); } FreeBuf(b); } } Insert(o, crl); } } FreeToken(t); } UnlockList(o); } // Write the certificates list void SiWriteCertList(FOLDER *f, LIST *o) { // Validate arguments if (f == NULL || o == NULL) { return; } LockList(o); { UINT i; X *x; for (i = 0;i < LIST_NUM(o);i++) { char name[MAX_SIZE]; BUF *b; x = LIST_DATA(o, i); Format(name, sizeof(name), "Cert%u", i); b = XToBuf(x, false); if (b != NULL) { CfgAddBuf(CfgCreateFolder(f, name), "X509", b); FreeBuf(b); } } } UnlockList(o); } // Read the certificates list void SiLoadCertList(LIST *o, FOLDER *f) { // Validate arguments if (o == NULL || f == NULL) { return; } LockList(o); { UINT i; TOKEN_LIST *t; t = CfgEnumFolderToTokenList(f); for (i = 0;i < t->NumTokens;i++) { FOLDER *ff = CfgGetFolder(f, t->Token[i]); BUF *b; b = CfgGetBuf(ff, "X509"); if (b != NULL) { X *x = BufToX(b, false); if (x != NULL) { Insert(o, x); } FreeBuf(b); } } FreeToken(t); } UnlockList(o); } // Write the database void SiWriteHubDb(FOLDER *f, HUBDB *db, bool no_save_ac_list) { // Validate arguments if (f == NULL || db == NULL) { return; } SiWriteUserList(CfgCreateFolder(f, "UserList"), db->UserList); SiWriteGroupList(CfgCreateFolder(f, "GroupList"), db->GroupList); SiWriteCertList(CfgCreateFolder(f, "CertList"), db->RootCertList); SiWriteCrlList(CfgCreateFolder(f, "CrlList"), db->CrlList); if (no_save_ac_list == false) { SiWriteAcList(CfgCreateFolder(f, "IPAccessControlList"), db->AcList); } } // Read the database void SiLoadHubDb(HUB *h, FOLDER *f) { // Validate arguments if (f == NULL || h == NULL) { return; } SiLoadGroupList(h, CfgGetFolder(f, "GroupList")); SiLoadUserList(h, CfgGetFolder(f, "UserList")); if (h->HubDb != NULL) { SiLoadCertList(h->HubDb->RootCertList, CfgGetFolder(f, "CertList")); SiLoadCrlList(h->HubDb->CrlList, CfgGetFolder(f, "CrlList")); SiLoadAcList(h->HubDb->AcList, CfgGetFolder(f, "IPAccessControlList")); } } // Write the Virtual HUB setting void SiWriteHubCfg(FOLDER *f, HUB *h) { // Validate arguments if (f == NULL || h == NULL) { return; } // Radius server name Lock(h->RadiusOptionLock); { if (h->RadiusServerName != NULL) { CfgAddStr(f, "RadiusServerName", h->RadiusServerName); CfgAddBuf(f, "RadiusSecret", h->RadiusSecret); } CfgAddInt(f, "RadiusServerPort", h->RadiusServerPort); CfgAddInt(f, "RadiusRetryInterval", h->RadiusRetryInterval); CfgAddStr(f, "RadiusSuffixFilter", h->RadiusSuffixFilter); } Unlock(h->RadiusOptionLock); // Password CfgAddByte(f, "HashedPassword", h->HashedPassword, sizeof(h->HashedPassword)); CfgAddByte(f, "SecurePassword", h->SecurePassword, sizeof(h->SecurePassword)); // Online / Offline flag if (h->Cedar->Bridge == false) { CfgAddBool(f, "Online", (h->Offline && (h->HubIsOnlineButHalting == false)) ? false : true); } // Traffic information SiWriteTraffic(f, "Traffic", h->Traffic); // HUB options SiWriteHubOptionCfg(CfgCreateFolder(f, "Option"), h->Option); // Message { FOLDER *folder = CfgCreateFolder(f, "Message"); if (IsEmptyUniStr(h->Msg) == false) { CfgAddUniStr(folder, "MessageText", h->Msg); } } // HUB_LOG SiWriteHubLogCfg(CfgCreateFolder(f, "LogSetting"), &h->LogSetting); if (h->Type == HUB_TYPE_STANDALONE) { // Link list SiWriteHubLinks(CfgCreateFolder(f, "CascadeList"), h); } if (h->Type != HUB_TYPE_FARM_STATIC) { if (GetServerCapsBool(h->Cedar->Server, "b_support_securenat")) { // SecureNAT SiWriteSecureNAT(h, CfgCreateFolder(f, "SecureNAT")); } } // Access list SiWriteHubAccessLists(CfgCreateFolder(f, "AccessList"), h); // Administration options SiWriteHubAdminOptions(CfgCreateFolder(f, "AdminOption"), h); // Type of HUB CfgAddInt(f, "Type", h->Type); // Database if (h->Cedar->Bridge == false) { SiWriteHubDb(CfgCreateFolder(f, "SecurityAccountDatabase"), h->HubDb, false ); } // Usage status CfgAddInt64(f, "LastCommTime", h->LastCommTime); CfgAddInt64(f, "LastLoginTime", h->LastLoginTime); CfgAddInt64(f, "CreatedTime", h->CreatedTime); CfgAddInt(f, "NumLogin", h->NumLogin); } // Read the logging options void SiLoadHubLogCfg(HUB_LOG *g, FOLDER *f) { // Validate arguments if (f == NULL || g == NULL) { return; } Zero(g, sizeof(HUB_LOG)); g->SaveSecurityLog = CfgGetBool(f, "SaveSecurityLog"); g->SecurityLogSwitchType = CfgGetInt(f, "SecurityLogSwitchType"); g->SavePacketLog = CfgGetBool(f, "SavePacketLog"); g->PacketLogSwitchType = CfgGetInt(f, "PacketLogSwitchType"); g->PacketLogConfig[PACKET_LOG_TCP_CONN] = CfgGetInt(f, "PACKET_LOG_TCP_CONN"); g->PacketLogConfig[PACKET_LOG_TCP] = CfgGetInt(f, "PACKET_LOG_TCP"); g->PacketLogConfig[PACKET_LOG_DHCP] = CfgGetInt(f, "PACKET_LOG_DHCP"); g->PacketLogConfig[PACKET_LOG_UDP] = CfgGetInt(f, "PACKET_LOG_UDP"); g->PacketLogConfig[PACKET_LOG_ICMP] = CfgGetInt(f, "PACKET_LOG_ICMP"); g->PacketLogConfig[PACKET_LOG_IP] = CfgGetInt(f, "PACKET_LOG_IP"); g->PacketLogConfig[PACKET_LOG_ARP] = CfgGetInt(f, "PACKET_LOG_ARP"); g->PacketLogConfig[PACKET_LOG_ETHERNET] = CfgGetInt(f, "PACKET_LOG_ETHERNET"); } // Write the logging options void SiWriteHubLogCfg(FOLDER *f, HUB_LOG *g) { SiWriteHubLogCfgEx(f, g, false); } void SiWriteHubLogCfgEx(FOLDER *f, HUB_LOG *g, bool el_mode) { // Validate arguments if (f == NULL || g == NULL) { return; } if (el_mode == false) { CfgAddBool(f, "SaveSecurityLog", g->SaveSecurityLog); CfgAddInt(f, "SecurityLogSwitchType", g->SecurityLogSwitchType); CfgAddBool(f, "SavePacketLog", g->SavePacketLog); } CfgAddInt(f, "PacketLogSwitchType", g->PacketLogSwitchType); CfgAddInt(f, "PACKET_LOG_TCP_CONN", g->PacketLogConfig[PACKET_LOG_TCP_CONN]); CfgAddInt(f, "PACKET_LOG_TCP", g->PacketLogConfig[PACKET_LOG_TCP]); CfgAddInt(f, "PACKET_LOG_DHCP", g->PacketLogConfig[PACKET_LOG_DHCP]); CfgAddInt(f, "PACKET_LOG_UDP", g->PacketLogConfig[PACKET_LOG_UDP]); CfgAddInt(f, "PACKET_LOG_ICMP", g->PacketLogConfig[PACKET_LOG_ICMP]); CfgAddInt(f, "PACKET_LOG_IP", g->PacketLogConfig[PACKET_LOG_IP]); CfgAddInt(f, "PACKET_LOG_ARP", g->PacketLogConfig[PACKET_LOG_ARP]); CfgAddInt(f, "PACKET_LOG_ETHERNET", g->PacketLogConfig[PACKET_LOG_ETHERNET]); } // Read the Virtual HUB settings void SiLoadHubCfg(SERVER *s, FOLDER *f, char *name) { HUB *h; CEDAR *c; HUB_OPTION o; bool online; UINT hub_old_type = 0; // Validate arguments if (s == NULL || f == NULL || name == NULL) { return; } c = s->Cedar; // Get the option Zero(&o, sizeof(o)); SiLoadHubOptionCfg(CfgGetFolder(f, "Option"), &o); // Create a HUB h = NewHub(c, name, &o); if (h != NULL) { HUB_LOG g; // Radius server settings Lock(h->RadiusOptionLock); { char name[MAX_SIZE]; BUF *secret; UINT port; UINT interval; port = CfgGetInt(f, "RadiusServerPort"); interval = CfgGetInt(f, "RadiusRetryInterval"); CfgGetStr(f, "RadiusSuffixFilter", h->RadiusSuffixFilter, sizeof(h->RadiusSuffixFilter)); if (interval == 0) { interval = RADIUS_RETRY_INTERVAL; } if (port != 0 && CfgGetStr(f, "RadiusServerName", name, sizeof(name))) { secret = CfgGetBuf(f, "RadiusSecret"); if (secret != NULL) { char secret_str[MAX_SIZE]; Zero(secret_str, sizeof(secret_str)); if (secret->Size < sizeof(secret_str)) { Copy(secret_str, secret->Buf, secret->Size); } secret_str[sizeof(secret_str) - 1] = 0; //SetRadiusServer(h, name, port, secret_str); SetRadiusServerEx(h, name, port, secret_str, interval); FreeBuf(secret); } } } Unlock(h->RadiusOptionLock); // Password if (CfgGetByte(f, "HashedPassword", h->HashedPassword, sizeof(h->HashedPassword)) != sizeof(h->HashedPassword)) { Hash(h->HashedPassword, "", 0, true); } if (CfgGetByte(f, "SecurePassword", h->SecurePassword, sizeof(h->SecurePassword)) != sizeof(h->SecurePassword)) { HashPassword(h->SecurePassword, ADMINISTRATOR_USERNAME, ""); } // Log Settings Zero(&g, sizeof(g)); SiLoadHubLogCfg(&g, CfgGetFolder(f, "LogSetting")); SetHubLogSetting(h, &g); // Online / Offline flag if (h->Cedar->Bridge == false) { online = CfgGetBool(f, "Online"); } else { online = true; } // Traffic information SiLoadTraffic(f, "Traffic", h->Traffic); // Access list SiLoadHubAccessLists(h, CfgGetFolder(f, "AccessList")); // Type of HUB hub_old_type = h->Type = CfgGetInt(f, "Type"); if (s->ServerType == SERVER_TYPE_STANDALONE) { if (h->Type != HUB_TYPE_STANDALONE) { // Change the type of all HUB to a stand-alone if the server is a stand-alone h->Type = HUB_TYPE_STANDALONE; } } else { if (h->Type == HUB_TYPE_STANDALONE) { // If the server is a farm controller, change the type of HUB to the farm supported types h->Type = HUB_TYPE_FARM_DYNAMIC; } } if (h->Type == HUB_TYPE_FARM_DYNAMIC) { h->CurrentVersion = h->LastVersion = 1; } // Message { FOLDER *folder = CfgGetFolder(f, "Message"); if (folder != NULL) { wchar_t *tmp = Malloc(sizeof(wchar_t) * (HUB_MAXMSG_LEN + 1)); if (CfgGetUniStr(folder, "MessageText", tmp, sizeof(wchar_t) * (HUB_MAXMSG_LEN + 1))) { SetHubMsg(h, tmp); } Free(tmp); } } // Link list if (h->Type == HUB_TYPE_STANDALONE) { // The link list is used only on stand-alone HUB // In VPN Gate hubs, don't load this { SiLoadHubLinks(h, CfgGetFolder(f, "CascadeList")); } } // SecureNAT if (GetServerCapsBool(h->Cedar->Server, "b_support_securenat")) { if (h->Type == HUB_TYPE_STANDALONE || h->Type == HUB_TYPE_FARM_DYNAMIC) { // SecureNAT is used only in the case of dynamic HUB or standalone HUB SiLoadSecureNAT(h, CfgGetFolder(f, "SecureNAT")); if (h->Type != HUB_TYPE_STANDALONE && h->Cedar != NULL && h->Cedar->Server != NULL && h->Cedar->Server->ServerType == SERVER_TYPE_FARM_CONTROLLER) { NiClearUnsupportedVhOptionForDynamicHub(h->SecureNATOption, hub_old_type == HUB_TYPE_STANDALONE); } } } // Administration options SiLoadHubAdminOptions(h, CfgGetFolder(f, "AdminOption")); // Database if (h->Cedar->Bridge == false) { SiLoadHubDb(h, CfgGetFolder(f, "SecurityAccountDatabase")); } // Usage status h->LastCommTime = CfgGetInt64(f, "LastCommTime"); if (h->LastCommTime == 0) { h->LastCommTime = SystemTime64(); } h->LastLoginTime = CfgGetInt64(f, "LastLoginTime"); if (h->LastLoginTime == 0) { h->LastLoginTime = SystemTime64(); } h->CreatedTime = CfgGetInt64(f, "CreatedTime"); h->NumLogin = CfgGetInt(f, "NumLogin"); // Start the operation of the HUB AddHub(c, h); if (online) { h->Offline = true; SetHubOnline(h); } else { h->Offline = false; SetHubOffline(h); } WaitLogFlush(h->SecurityLogger); WaitLogFlush(h->PacketLogger); ReleaseHub(h); } } // Read the SecureNAT configuration void SiLoadSecureNAT(HUB *h, FOLDER *f) { VH_OPTION o; // Validate arguments if (h == NULL || f == NULL) { return; } // Read the VH_OPTION NiLoadVhOptionEx(&o, f); // Set the VH_OPTION Copy(h->SecureNATOption, &o, sizeof(VH_OPTION)); EnableSecureNAT(h, CfgGetBool(f, "Disabled") ? false : true); } // Read the virtual layer 3 switch settings void SiLoadL3SwitchCfg(L3SW *sw, FOLDER *f) { UINT i; FOLDER *if_folder, *table_folder; TOKEN_LIST *t; bool active = false; // Validate arguments if (sw == NULL || f == NULL) { return; } active = CfgGetBool(f, "Active"); // Interface list if_folder = CfgGetFolder(f, "InterfaceList"); if (if_folder != NULL) { t = CfgEnumFolderToTokenList(if_folder); if (t != NULL) { for (i = 0;i < t->NumTokens;i++) { FOLDER *ff = CfgGetFolder(if_folder, t->Token[i]); char name[MAX_HUBNAME_LEN + 1]; UINT ip, subnet; CfgGetStr(ff, "HubName", name, sizeof(name)); ip = CfgGetIp32(ff, "IpAddress"); subnet = CfgGetIp32(ff, "SubnetMask"); { L3AddIf(sw, name, ip, subnet); } } FreeToken(t); } } // Routing table table_folder = CfgGetFolder(f, "RoutingTable"); if (table_folder != NULL) { t = CfgEnumFolderToTokenList(table_folder); if (t != NULL) { for (i = 0;i < t->NumTokens;i++) { FOLDER *ff = CfgGetFolder(table_folder, t->Token[i]); L3TABLE tbl; Zero(&tbl, sizeof(tbl)); tbl.NetworkAddress = CfgGetIp32(ff, "NetworkAddress"); tbl.SubnetMask = CfgGetIp32(ff, "SubnetMask"); tbl.GatewayAddress = CfgGetIp32(ff, "GatewayAddress"); tbl.Metric = CfgGetInt(ff, "Metric"); L3AddTable(sw, &tbl); } FreeToken(t); } } if (active) { L3SwStart(sw); } } // Write the virtual layer 3 switch settings void SiWriteL3SwitchCfg(FOLDER *f, L3SW *sw) { UINT i; FOLDER *if_folder, *table_folder; char tmp[MAX_SIZE]; // Validate arguments if (f == NULL || sw == NULL) { return; } // Active flag CfgAddBool(f, "Active", sw->Active); // Interface list if_folder = CfgCreateFolder(f, "InterfaceList"); for (i = 0;i < LIST_NUM(sw->IfList);i++) { L3IF *e = LIST_DATA(sw->IfList, i); FOLDER *ff; Format(tmp, sizeof(tmp), "Interface%u", i); ff = CfgCreateFolder(if_folder, tmp); CfgAddStr(ff, "HubName", e->HubName); CfgAddIp32(ff, "IpAddress", e->IpAddress); CfgAddIp32(ff, "SubnetMask", e->SubnetMask); } // Routing table table_folder = CfgCreateFolder(f, "RoutingTable"); for (i = 0;i < LIST_NUM(sw->TableList);i++) { L3TABLE *e = LIST_DATA(sw->TableList, i); FOLDER *ff; Format(tmp, sizeof(tmp), "Entry%u", i); ff = CfgCreateFolder(table_folder, tmp); CfgAddIp32(ff, "NetworkAddress", e->NetworkAddress); CfgAddIp32(ff, "SubnetMask", e->SubnetMask); CfgAddIp32(ff, "GatewayAddress", e->GatewayAddress); CfgAddInt(ff, "Metric", e->Metric); } } // Read the Virtual Layer 3 switch list void SiLoadL3Switchs(SERVER *s, FOLDER *f) { UINT i; TOKEN_LIST *t; CEDAR *c; // Validate arguments if (s == NULL || f == NULL) { return; } c = s->Cedar; t = CfgEnumFolderToTokenList(f); if (t != NULL) { for (i = 0;i < t->NumTokens;i++) { char *name = t->Token[i]; L3SW *sw = L3AddSw(c, name); SiLoadL3SwitchCfg(sw, CfgGetFolder(f, name)); ReleaseL3Sw(sw); } } FreeToken(t); } // Write the Virtual Layer 3 switch list void SiWriteL3Switchs(FOLDER *f, SERVER *s) { UINT i; FOLDER *folder; CEDAR *c; // Validate arguments if (f == NULL || s == NULL) { return; } c = s->Cedar; LockList(c->L3SwList); { for (i = 0;i < LIST_NUM(c->L3SwList);i++) { L3SW *sw = LIST_DATA(c->L3SwList, i); Lock(sw->lock); { folder = CfgCreateFolder(f, sw->Name); SiWriteL3SwitchCfg(folder, sw); } Unlock(sw->lock); } } UnlockList(c->L3SwList); } // Read the IPsec server configuration void SiLoadIPsec(SERVER *s, FOLDER *f) { IPSEC_SERVICES sl; FOLDER *list_folder; // Validate arguments if (s == NULL || f == NULL) { return; } Zero(&sl, sizeof(sl)); CfgGetStr(f, "IPsec_Secret", sl.IPsec_Secret, sizeof(sl.IPsec_Secret)); CfgGetStr(f, "L2TP_DefaultHub", sl.L2TP_DefaultHub, sizeof(sl.L2TP_DefaultHub)); if (s->ServerType == SERVER_TYPE_STANDALONE) { // IPsec feature only be enabled on a standalone server sl.L2TP_Raw = CfgGetBool(f, "L2TP_Raw"); sl.L2TP_IPsec = CfgGetBool(f, "L2TP_IPsec"); sl.EtherIP_IPsec = CfgGetBool(f, "EtherIP_IPsec"); } IPsecServerSetServices(s->IPsecServer, &sl); list_folder = CfgGetFolder(f, "EtherIP_IDSettingsList"); if (list_folder != NULL) { TOKEN_LIST *t = CfgEnumFolderToTokenList(list_folder); if (t != NULL) { UINT i; for (i = 0;i < t->NumTokens;i++) { char *name = t->Token[i]; FOLDER *f = CfgGetFolder(list_folder, name); if (f != NULL) { ETHERIP_ID d; BUF *b; Zero(&d, sizeof(d)); StrCpy(d.Id, sizeof(d.Id), name); CfgGetStr(f, "HubName", d.HubName, sizeof(d.HubName)); CfgGetStr(f, "UserName", d.UserName, sizeof(d.UserName)); b = CfgGetBuf(f, "EncryptedPassword"); if (b != NULL) { char *pass = DecryptPassword2(b); StrCpy(d.Password, sizeof(d.Password), pass); Free(pass); AddEtherIPId(s->IPsecServer, &d); FreeBuf(b); } } } FreeToken(t); } } } // Write the IPsec server configuration void SiWriteIPsec(FOLDER *f, SERVER *s) { IPSEC_SERVICES sl; FOLDER *list_folder; UINT i; // Validate arguments if (s == NULL || f == NULL) { return; } if (s->IPsecServer == NULL) { return; } Zero(&sl, sizeof(sl)); IPsecServerGetServices(s->IPsecServer, &sl); CfgAddStr(f, "IPsec_Secret", sl.IPsec_Secret); CfgAddStr(f, "L2TP_DefaultHub", sl.L2TP_DefaultHub); CfgAddBool(f, "L2TP_Raw", sl.L2TP_Raw); CfgAddBool(f, "L2TP_IPsec", sl.L2TP_IPsec); CfgAddBool(f, "EtherIP_IPsec", sl.EtherIP_IPsec); list_folder = CfgCreateFolder(f, "EtherIP_IDSettingsList"); Lock(s->IPsecServer->LockSettings); { for (i = 0;i < LIST_NUM(s->IPsecServer->EtherIPIdList);i++) { ETHERIP_ID *d = LIST_DATA(s->IPsecServer->EtherIPIdList, i); FOLDER *f; BUF *b; f = CfgCreateFolder(list_folder, d->Id); CfgAddStr(f, "HubName", d->HubName); CfgAddStr(f, "UserName", d->UserName); b = EncryptPassword2(d->Password); CfgAddBuf(f, "EncryptedPassword", b); FreeBuf(b); } } Unlock(s->IPsecServer->LockSettings); } // Write the license list void SiWriteLicenseManager(FOLDER *f, SERVER *s) { } // Read the license list void SiLoadLicenseManager(SERVER *s, FOLDER *f) { } // Write the Virtual HUB list void SiWriteHubs(FOLDER *f, SERVER *s) { UINT i; FOLDER *hub_folder; CEDAR *c; UINT num; HUB **hubs; // Validate arguments if (f == NULL || s == NULL) { return; } c = s->Cedar; LockList(c->HubList); { hubs = ToArray(c->HubList); num = LIST_NUM(c->HubList); for (i = 0;i < num;i++) { AddRef(hubs[i]->ref); } } UnlockList(c->HubList); for (i = 0;i < num;i++) { HUB *h = hubs[i]; Lock(h->lock); { hub_folder = CfgCreateFolder(f, h->Name); SiWriteHubCfg(hub_folder, h); } Unlock(h->lock); ReleaseHub(h); if ((i % 30) == 1) { YieldCpu(); } } Free(hubs); } // Read the Virtual HUB list void SiLoadHubs(SERVER *s, FOLDER *f) { UINT i; FOLDER *hub_folder; CEDAR *c; TOKEN_LIST *t; bool b = false; // Validate arguments if (f == NULL || s == NULL) { return; } c = s->Cedar; t = CfgEnumFolderToTokenList(f); for (i = 0;i < t->NumTokens;i++) { char *name = t->Token[i]; if (s->Cedar->Bridge) { if (StrCmpi(name, SERVER_DEFAULT_BRIDGE_NAME) == 0) { // Read only the setting of Virtual HUB named "BRIDGE" // in the case of the Bridge b = true; } else { continue; } } hub_folder = CfgGetFolder(f, name); if (hub_folder != NULL) { SiLoadHubCfg(s, hub_folder, name); } } FreeToken(t); if (s->Cedar->Bridge && b == false) { // If there isn't "BRIDGE" virtual HUB setting, create it newly SiInitDefaultHubList(s); } } // Read the server-specific settings void SiLoadServerCfg(SERVER *s, FOLDER *f) { BUF *b; CEDAR *c; char tmp[MAX_SIZE]; X *x = NULL; K *k = NULL; bool cluster_allowed = false; UINT num_connections_per_ip = 0; FOLDER *params_folder; UINT i; // Validate arguments if (s == NULL || f == NULL) { return; } // Save interval related s->AutoSaveConfigSpan = CfgGetInt(f, "AutoSaveConfigSpan") * 1000; if (s->AutoSaveConfigSpan == 0) { s->AutoSaveConfigSpan = SERVER_FILE_SAVE_INTERVAL_DEFAULT; } else { s->AutoSaveConfigSpan = MAKESURE(s->AutoSaveConfigSpan, SERVER_FILE_SAVE_INTERVAL_MIN, SERVER_FILE_SAVE_INTERVAL_MAX); } i = CfgGetInt(f, "MaxConcurrentDnsClientThreads"); if (i != 0) { SetGetIpThreadMaxNum(i); } else { SetGetIpThreadMaxNum(DEFAULT_GETIP_THREAD_MAX_NUM); } s->DontBackupConfig = CfgGetBool(f, "DontBackupConfig"); if (CfgIsItem(f, "BackupConfigOnlyWhenModified")) { s->BackupConfigOnlyWhenModified = CfgGetBool(f, "BackupConfigOnlyWhenModified"); } else { s->BackupConfigOnlyWhenModified = true; } // Server log switch type if (CfgIsItem(f, "ServerLogSwitchType")) { UINT st = CfgGetInt(f, "ServerLogSwitchType"); SetLogSwitchType(s->Logger, st); } SetMaxLogSize(CfgGetInt64(f, "LoggerMaxLogSize")); params_folder = CfgGetFolder(f, "GlobalParams"); SiLoadGlobalParamsCfg(params_folder); c = s->Cedar; Lock(c->lock); { OPENVPN_SSTP_CONFIG config; FOLDER *syslog_f; { RPC_KEEP k; // Keep-alive related Zero(&k, sizeof(k)); k.UseKeepConnect = CfgGetBool(f, "UseKeepConnect"); CfgGetStr(f, "KeepConnectHost", k.KeepConnectHost, sizeof(k.KeepConnectHost)); k.KeepConnectPort = CfgGetInt(f, "KeepConnectPort"); k.KeepConnectProtocol = CfgGetInt(f, "KeepConnectProtocol"); k.KeepConnectInterval = CfgGetInt(f, "KeepConnectInterval") * 1000; if (k.KeepConnectPort == 0) { k.KeepConnectPort = 80; } if (StrLen(k.KeepConnectHost) == 0) { StrCpy(k.KeepConnectHost, sizeof(k.KeepConnectHost), CLIENT_DEFAULT_KEEPALIVE_HOST); } if (k.KeepConnectInterval == 0) { k.KeepConnectInterval = KEEP_INTERVAL_DEFAULT * 1000; } if (k.KeepConnectInterval < 5000) { k.KeepConnectInterval = 5000; } if (k.KeepConnectInterval > 600000) { k.KeepConnectInterval = 600000; } Lock(s->Keep->lock); { KEEP *keep = s->Keep; keep->Enable = k.UseKeepConnect; keep->Server = true; StrCpy(keep->ServerName, sizeof(keep->ServerName), k.KeepConnectHost); keep->ServerPort = k.KeepConnectPort; keep->UdpMode = k.KeepConnectProtocol; keep->Interval = k.KeepConnectInterval; } Unlock(s->Keep->lock); } // syslog syslog_f = CfgGetFolder(f, "SyslogSettings"); if (syslog_f != NULL && GetServerCapsBool(s, "b_support_syslog")) { SYSLOG_SETTING set; Zero(&set, sizeof(set)); set.SaveType = CfgGetInt(syslog_f, "SaveType"); CfgGetStr(syslog_f, "HostName", set.Hostname, sizeof(set.Hostname)); set.Port = CfgGetInt(syslog_f, "Port"); SiSetSysLogSetting(s, &set); } // Whether to disable the IPv6 listener s->Cedar->DisableIPv6Listener = CfgGetBool(f, "DisableIPv6Listener"); // DoS s->DisableDosProction = CfgGetBool(f, "DisableDosProction"); // Num Connections Per IP SetMaxConnectionsPerIp(CfgGetInt(f, "MaxConnectionsPerIP")); // MaxUnestablishedConnections SetMaxUnestablishedConnections(CfgGetInt(f, "MaxUnestablishedConnections")); // DeadLock s->DisableDeadLockCheck = CfgGetBool(f, "DisableDeadLockCheck"); // Eraser SetEraserCheckInterval(CfgGetInt(f, "AutoDeleteCheckIntervalSecs")); s->Eraser = NewEraser(s->Logger, CfgGetInt64(f, "AutoDeleteCheckDiskFreeSpaceMin")); // WebUI s->UseWebUI = CfgGetBool(f, "UseWebUI"); // WebTimePage s->UseWebTimePage = CfgGetBool(f, "UseWebTimePage"); // NoLinuxArpFilter s->NoLinuxArpFilter = CfgGetBool(f, "NoLinuxArpFilter"); // NoHighPriorityProcess s->NoHighPriorityProcess = CfgGetBool(f, "NoHighPriorityProcess"); // NoDebugDump s->NoDebugDump = CfgGetBool(f, "NoDebugDump"); if (s->NoDebugDump) { #ifdef OS_WIN32 MsSetEnableMinidump(false); #endif // OS_WIN32 } // Disable the SSTP server function s->DisableSSTPServer = CfgGetBool(f, "DisableSSTPServer"); // Disable the OpenVPN server function s->DisableOpenVPNServer = CfgGetBool(f, "DisableOpenVPNServer"); // OpenVPN Default Option String if (CfgGetStr(f, "OpenVPNDefaultClientOption", tmp, sizeof(tmp))) { if (IsEmptyStr(tmp) == false) { StrCpy(c->OpenVPNDefaultClientOption, sizeof(c->OpenVPNDefaultClientOption), tmp); } } // Disable the NAT-traversal feature s->DisableNatTraversal = CfgGetBool(f, "DisableNatTraversal"); // Intel AES s->DisableIntelAesAcceleration = CfgGetBool(f, "DisableIntelAesAcceleration"); if (s->Cedar->Bridge == false) { // Enable the VPN-over-ICMP if (CfgIsItem(f, "EnableVpnOverIcmp")) { s->EnableVpnOverIcmp = CfgGetBool(f, "EnableVpnOverIcmp"); } else { s->EnableVpnOverIcmp = false; } // Enable the VPN-over-DNS if (CfgIsItem(f, "EnableVpnOverDns")) { s->EnableVpnOverDns = CfgGetBool(f, "EnableVpnOverDns"); } else { s->EnableVpnOverDns = false; } } // Debug log s->SaveDebugLog = CfgGetBool(f, "SaveDebugLog"); if (s->SaveDebugLog) { s->DebugLog = NewTinyLog(); } // Let the client not to send a signature s->NoSendSignature = CfgGetBool(f, "NoSendSignature"); // Server certificate b = CfgGetBuf(f, "ServerCert"); if (b != NULL) { x = BufToX(b, false); FreeBuf(b); } // Server private key b = CfgGetBuf(f, "ServerKey"); if (b != NULL) { k = BufToK(b, true, false, NULL); FreeBuf(b); } if (x == NULL || k == NULL || CheckXandK(x, k) == false) { FreeX(x); FreeK(k); SiGenerateDefaultCert(&x, &k); SetCedarCert(c, x, k); FreeX(x); FreeK(k); } else { SetCedarCert(c, x, k); FreeX(x); FreeK(k); } // Cipher Name if (CfgGetStr(f, "CipherName", tmp, sizeof(tmp))) { StrUpper(tmp); if (CheckCipherListName(tmp)) { SetCedarCipherList(c, tmp); } } // Traffic information Lock(c->TrafficLock); { SiLoadTraffic(f, "ServerTraffic", c->Traffic); } Unlock(c->TrafficLock); // Get whether the current license allows cluster mode cluster_allowed = true; // Type of server s->UpdatedServerType = s->ServerType = cluster_allowed ? CfgGetInt(f, "ServerType") : SERVER_TYPE_STANDALONE; // Password if (CfgGetByte(f, "HashedPassword", s->HashedPassword, sizeof(s->HashedPassword)) != sizeof(s->HashedPassword)) { Hash(s->HashedPassword, "", 0, true); } if (s->ServerType != SERVER_TYPE_STANDALONE) { // Performance ratio of the server s->Weight = CfgGetInt(f, "ClusterMemberWeight"); if (s->Weight == 0) { s->Weight = FARM_DEFAULT_WEIGHT; } } else { s->Weight = FARM_DEFAULT_WEIGHT; } if (s->ServerType == SERVER_TYPE_FARM_CONTROLLER) { s->ControllerOnly = CfgGetBool(f, "ControllerOnly"); } if (s->ServerType != SERVER_TYPE_STANDALONE) { // SSTP, OpenVPN, and NAT traversal can not be used in a cluster environment s->DisableNatTraversal = true; s->DisableSSTPServer = true; s->DisableOpenVPNServer = true; } if (s->Cedar->Bridge) { // SSTP, OpenVPN, and NAT traversal function can not be used in the bridge environment s->DisableNatTraversal = true; s->DisableSSTPServer = true; s->DisableOpenVPNServer = true; } // Read the OpenVPN Port List if (CfgGetStr(f, "OpenVPN_UdpPortList", tmp, sizeof(tmp)) == false) { { ToStr(tmp, OPENVPN_UDP_PORT); } } // Apply the configuration of SSTP and OpenVPN Zero(&config, sizeof(config)); config.EnableOpenVPN = !s->DisableOpenVPNServer; config.EnableSSTP = !s->DisableSSTPServer; StrCpy(config.OpenVPNPortList, sizeof(config.OpenVPNPortList), tmp); SiSetOpenVPNAndSSTPConfig(s, &config); if (s->ServerType == SERVER_TYPE_FARM_MEMBER) { char tmp[6 * MAX_PUBLIC_PORT_NUM + 1]; // Load the settings item in the case of farm members CfgGetStr(f, "ControllerName", s->ControllerName, sizeof(s->ControllerName)); s->ControllerPort = CfgGetInt(f, "ControllerPort"); CfgGetByte(f, "MemberPassword", s->MemberPassword, SHA1_SIZE); s->PublicIp = CfgGetIp32(f, "PublicIp"); if (CfgGetStr(f, "PublicPorts", tmp, sizeof(tmp))) { TOKEN_LIST *t = ParseToken(tmp, ", "); UINT i; s->NumPublicPort = t->NumTokens; s->PublicPorts = ZeroMalloc(s->NumPublicPort * sizeof(UINT)); for (i = 0;i < s->NumPublicPort;i++) { s->PublicPorts[i] = ToInt(t->Token[i]); } FreeToken(t); } } // Configuration of VPN Azure Client s->EnableVpnAzure = CfgGetBool(f, "EnableVpnAzure"); // Disable GetHostName when accepting TCP s->DisableGetHostNameWhenAcceptTcp = CfgGetBool(f, "DisableGetHostNameWhenAcceptTcp"); if (s->DisableGetHostNameWhenAcceptTcp) { DisableGetHostNameWhenAcceptInit(); } // Disable core dump on UNIX s->DisableCoreDumpOnUnix = CfgGetBool(f, "DisableCoreDumpOnUnix"); // Disable session reconnect SetGlobalServerFlag(GSF_DISABLE_SESSION_RECONNECT, CfgGetBool(f, "DisableSessionReconnect")); // AcceptOnlyTls c->AcceptOnlyTls = CfgGetBool(f, "AcceptOnlyTls"); } Unlock(c->lock); #ifdef OS_UNIX if (s->DisableCoreDumpOnUnix) { UnixDisableCoreDump(); } #endif // OS_UNIX } // Load global params void SiLoadGlobalParamsCfg(FOLDER *f) { SiLoadGlobalParamItem(GP_MAX_SEND_SOCKET_QUEUE_SIZE, CfgGetInt(f, "MAX_SEND_SOCKET_QUEUE_SIZE")); SiLoadGlobalParamItem(GP_MIN_SEND_SOCKET_QUEUE_SIZE, CfgGetInt(f, "MIN_SEND_SOCKET_QUEUE_SIZE")); SiLoadGlobalParamItem(GP_MAX_SEND_SOCKET_QUEUE_NUM, CfgGetInt(f, "MAX_SEND_SOCKET_QUEUE_NUM")); SiLoadGlobalParamItem(GP_SELECT_TIME, CfgGetInt(f, "SELECT_TIME")); SiLoadGlobalParamItem(GP_SELECT_TIME_FOR_NAT, CfgGetInt(f, "SELECT_TIME_FOR_NAT")); SiLoadGlobalParamItem(GP_MAX_STORED_QUEUE_NUM, CfgGetInt(f, "MAX_STORED_QUEUE_NUM")); SiLoadGlobalParamItem(GP_MAX_BUFFERING_PACKET_SIZE, CfgGetInt(f, "MAX_BUFFERING_PACKET_SIZE")); SiLoadGlobalParamItem(GP_HUB_ARP_SEND_INTERVAL, CfgGetInt(f, "HUB_ARP_SEND_INTERVAL")); SiLoadGlobalParamItem(GP_MAC_TABLE_EXPIRE_TIME, CfgGetInt(f, "MAC_TABLE_EXPIRE_TIME")); SiLoadGlobalParamItem(GP_IP_TABLE_EXPIRE_TIME, CfgGetInt(f, "IP_TABLE_EXPIRE_TIME")); SiLoadGlobalParamItem(GP_IP_TABLE_EXPIRE_TIME_DHCP, CfgGetInt(f, "IP_TABLE_EXPIRE_TIME_DHCP")); SiLoadGlobalParamItem(GP_STORM_CHECK_SPAN, CfgGetInt(f, "STORM_CHECK_SPAN")); SiLoadGlobalParamItem(GP_STORM_DISCARD_VALUE_START, CfgGetInt(f, "STORM_DISCARD_VALUE_START")); SiLoadGlobalParamItem(GP_STORM_DISCARD_VALUE_END, CfgGetInt(f, "STORM_DISCARD_VALUE_END")); SiLoadGlobalParamItem(GP_MAX_MAC_TABLES, CfgGetInt(f, "MAX_MAC_TABLES")); SiLoadGlobalParamItem(GP_MAX_IP_TABLES, CfgGetInt(f, "MAX_IP_TABLES")); SiLoadGlobalParamItem(GP_MAX_HUB_LINKS, CfgGetInt(f, "MAX_HUB_LINKS")); SiLoadGlobalParamItem(GP_MEM_FIFO_REALLOC_MEM_SIZE, CfgGetInt(f, "MEM_FIFO_REALLOC_MEM_SIZE")); SiLoadGlobalParamItem(GP_QUEUE_BUDGET, CfgGetInt(f, "QUEUE_BUDGET")); SiLoadGlobalParamItem(GP_FIFO_BUDGET, CfgGetInt(f, "FIFO_BUDGET")); SetFifoCurrentReallocMemSize(MEM_FIFO_REALLOC_MEM_SIZE); } // Load global param itesm void SiLoadGlobalParamItem(UINT id, UINT value) { // Validate arguments if (id == 0) { return; } vpn_global_parameters[id] = value; } // Write global params void SiWriteGlobalParamsCfg(FOLDER *f) { // Validate arguments if (f == NULL) { return; } CfgAddInt(f, "MAX_SEND_SOCKET_QUEUE_SIZE", MAX_SEND_SOCKET_QUEUE_SIZE); CfgAddInt(f, "MIN_SEND_SOCKET_QUEUE_SIZE", MIN_SEND_SOCKET_QUEUE_SIZE); CfgAddInt(f, "MAX_SEND_SOCKET_QUEUE_NUM", MAX_SEND_SOCKET_QUEUE_NUM); CfgAddInt(f, "SELECT_TIME", SELECT_TIME); CfgAddInt(f, "SELECT_TIME_FOR_NAT", SELECT_TIME_FOR_NAT); CfgAddInt(f, "MAX_STORED_QUEUE_NUM", MAX_STORED_QUEUE_NUM); CfgAddInt(f, "MAX_BUFFERING_PACKET_SIZE", MAX_BUFFERING_PACKET_SIZE); CfgAddInt(f, "HUB_ARP_SEND_INTERVAL", HUB_ARP_SEND_INTERVAL); CfgAddInt(f, "MAC_TABLE_EXPIRE_TIME", MAC_TABLE_EXPIRE_TIME); CfgAddInt(f, "IP_TABLE_EXPIRE_TIME", IP_TABLE_EXPIRE_TIME); CfgAddInt(f, "IP_TABLE_EXPIRE_TIME_DHCP", IP_TABLE_EXPIRE_TIME_DHCP); CfgAddInt(f, "STORM_CHECK_SPAN", STORM_CHECK_SPAN); CfgAddInt(f, "STORM_DISCARD_VALUE_START", STORM_DISCARD_VALUE_START); CfgAddInt(f, "STORM_DISCARD_VALUE_END", STORM_DISCARD_VALUE_END); CfgAddInt(f, "MAX_MAC_TABLES", MAX_MAC_TABLES); CfgAddInt(f, "MAX_IP_TABLES", MAX_IP_TABLES); CfgAddInt(f, "MAX_HUB_LINKS", MAX_HUB_LINKS); CfgAddInt(f, "MEM_FIFO_REALLOC_MEM_SIZE", MEM_FIFO_REALLOC_MEM_SIZE); CfgAddInt(f, "QUEUE_BUDGET", QUEUE_BUDGET); CfgAddInt(f, "FIFO_BUDGET", FIFO_BUDGET); } // Write the server-specific settings void SiWriteServerCfg(FOLDER *f, SERVER *s) { BUF *b; CEDAR *c; FOLDER *params_folder; // Validate arguments if (f == NULL || s == NULL) { return; } CfgAddInt(f, "MaxConcurrentDnsClientThreads", GetGetIpThreadMaxNum()); CfgAddInt(f, "CurrentBuild", s->Cedar->Build); CfgAddInt(f, "AutoSaveConfigSpan", s->AutoSaveConfigSpanSaved / 1000); CfgAddBool(f, "DontBackupConfig", s->DontBackupConfig); CfgAddBool(f, "BackupConfigOnlyWhenModified", s->BackupConfigOnlyWhenModified); if (s->Logger != NULL) { CfgAddInt(f, "ServerLogSwitchType", s->Logger->SwitchType); } CfgAddInt64(f, "LoggerMaxLogSize", GetMaxLogSize()); params_folder = CfgCreateFolder(f, "GlobalParams"); if (params_folder != NULL) { SiWriteGlobalParamsCfg(params_folder); } c = s->Cedar; Lock(c->lock); { bool is_vgs_cert = false; FOLDER *syslog_f; Lock(s->Keep->lock); { KEEP *k = s->Keep; CfgAddBool(f, "UseKeepConnect", k->Enable); CfgAddStr(f, "KeepConnectHost", k->ServerName); CfgAddInt(f, "KeepConnectPort", k->ServerPort); CfgAddInt(f, "KeepConnectProtocol", k->UdpMode); CfgAddInt(f, "KeepConnectInterval", k->Interval / 1000); } Unlock(s->Keep->lock); // syslog syslog_f = CfgCreateFolder(f, "SyslogSettings"); if (syslog_f != NULL) { SYSLOG_SETTING set; SiGetSysLogSetting(s, &set); CfgAddInt(syslog_f, "SaveType", set.SaveType); CfgAddStr(syslog_f, "HostName", set.Hostname); CfgAddInt(syslog_f, "Port", set.Port); } // IPv6 listener disable setting CfgAddBool(f, "DisableIPv6Listener", s->Cedar->DisableIPv6Listener); // DoS CfgAddBool(f, "DisableDosProction", s->DisableDosProction); // MaxConnectionsPerIP CfgAddInt(f, "MaxConnectionsPerIP", GetMaxConnectionsPerIp()); // MaxUnestablishedConnections CfgAddInt(f, "MaxUnestablishedConnections", GetMaxUnestablishedConnections()); // DeadLock CfgAddBool(f, "DisableDeadLockCheck", s->DisableDeadLockCheck); // Eraser related CfgAddInt64(f, "AutoDeleteCheckDiskFreeSpaceMin", s->Eraser->MinFreeSpace); CfgAddInt(f, "AutoDeleteCheckIntervalSecs", GetEraserCheckInterval()); // WebUI CfgAddBool(f, "UseWebUI", s->UseWebUI); // NoLinuxArpFilter if (GetOsInfo()->OsType == OSTYPE_LINUX) { CfgAddBool(f, "NoLinuxArpFilter", s->NoLinuxArpFilter); } // NoHighPriorityProcess CfgAddBool(f, "NoHighPriorityProcess", s->NoHighPriorityProcess); #ifdef OS_WIN32 CfgAddBool(f, "NoDebugDump", s->NoDebugDump); #endif // OS_WIN32 if (s->ServerType == SERVER_TYPE_STANDALONE) { if (c->Bridge == false) { // Disable the NAT-traversal feature CfgAddBool(f, "DisableNatTraversal", s->DisableNatTraversal); // Disable the SSTP server function CfgAddBool(f, "DisableSSTPServer", s->DisableSSTPServer); // Disable the OpenVPN server function CfgAddBool(f, "DisableOpenVPNServer", s->DisableOpenVPNServer); } } CfgAddStr(f, "OpenVPNDefaultClientOption", c->OpenVPNDefaultClientOption); if (c->Bridge == false) { // VPN over ICMP CfgAddBool(f, "EnableVpnOverIcmp", s->EnableVpnOverIcmp); // VPN over DNS CfgAddBool(f, "EnableVpnOverDns", s->EnableVpnOverDns); } // Intel AES CfgAddBool(f, "DisableIntelAesAcceleration", s->DisableIntelAesAcceleration); if (c->Bridge == false) { OPENVPN_SSTP_CONFIG config; SiGetOpenVPNAndSSTPConfig(s, &config); CfgAddStr(f, "OpenVPN_UdpPortList", config.OpenVPNPortList); } // WebTimePage CfgAddBool(f, "UseWebTimePage", s->UseWebTimePage); // Debug log CfgAddBool(f, "SaveDebugLog", s->SaveDebugLog); // Let the client not to send a signature CfgAddBool(f, "NoSendSignature", s->NoSendSignature); if (is_vgs_cert == false) { // Server certificate b = XToBuf(c->ServerX, false); CfgAddBuf(f, "ServerCert", b); FreeBuf(b); // Server private key b = KToBuf(c->ServerK, false, NULL); CfgAddBuf(f, "ServerKey", b); FreeBuf(b); } // Traffic information Lock(c->TrafficLock); { SiWriteTraffic(f, "ServerTraffic", c->Traffic); } Unlock(c->TrafficLock); // Type of server if (s->Cedar->Bridge == false) { CfgAddInt(f, "ServerType", s->UpdatedServerType); } // Cipher Name CfgAddStr(f, "CipherName", s->Cedar->CipherList); // Password CfgAddByte(f, "HashedPassword", s->HashedPassword, sizeof(s->HashedPassword)); if (s->UpdatedServerType == SERVER_TYPE_FARM_MEMBER) { char tmp[6 * MAX_PUBLIC_PORT_NUM + 1]; UINT i; // Setting items in the case of farm members CfgAddStr(f, "ControllerName", s->ControllerName); CfgAddInt(f, "ControllerPort", s->ControllerPort); CfgAddByte(f, "MemberPassword", s->MemberPassword, SHA1_SIZE); CfgAddIp32(f, "PublicIp", s->PublicIp); tmp[0] = 0; for (i = 0;i < s->NumPublicPort;i++) { char tmp2[MAX_SIZE]; ToStr(tmp2, s->PublicPorts[i]); StrCat(tmp, sizeof(tmp), tmp2); StrCat(tmp, sizeof(tmp), ","); } if (StrLen(tmp) >= 1) { if (tmp[StrLen(tmp) - 1] == ',') { tmp[StrLen(tmp) - 1] = 0; } } CfgAddStr(f, "PublicPorts", tmp); } if (s->UpdatedServerType != SERVER_TYPE_STANDALONE) { CfgAddInt(f, "ClusterMemberWeight", s->Weight); } if (s->UpdatedServerType == SERVER_TYPE_FARM_CONTROLLER) { CfgAddBool(f, "ControllerOnly", s->ControllerOnly); } // VPN Azure Client if (s->AzureClient != NULL) { CfgAddBool(f, "EnableVpnAzure", s->EnableVpnAzure); } CfgAddBool(f, "DisableGetHostNameWhenAcceptTcp", s->DisableGetHostNameWhenAcceptTcp); CfgAddBool(f, "DisableCoreDumpOnUnix", s->DisableCoreDumpOnUnix); CfgAddBool(f, "AcceptOnlyTls", c->AcceptOnlyTls); // Disable session reconnect CfgAddBool(f, "DisableSessionReconnect", GetGlobalServerFlag(GSF_DISABLE_SESSION_RECONNECT)); } Unlock(c->lock); } // Read the traffic information void SiLoadTraffic(FOLDER *parent, char *name, TRAFFIC *t) { FOLDER *f; // Validate arguments if (t != NULL) { Zero(t, sizeof(TRAFFIC)); } if (parent == NULL || name == NULL || t == NULL) { return; } f = CfgGetFolder(parent, name); if (f == NULL) { return; } SiLoadTrafficInner(f, "SendTraffic", &t->Send); SiLoadTrafficInner(f, "RecvTraffic", &t->Recv); } void SiLoadTrafficInner(FOLDER *parent, char *name, TRAFFIC_ENTRY *e) { FOLDER *f; // Validate arguments if (e != NULL) { Zero(e, sizeof(TRAFFIC_ENTRY)); } if (parent == NULL || name == NULL || e == NULL) { return; } f = CfgGetFolder(parent, name); if (f == NULL) { return; } e->BroadcastCount = CfgGetInt64(f, "BroadcastCount"); e->BroadcastBytes = CfgGetInt64(f, "BroadcastBytes"); e->UnicastCount = CfgGetInt64(f, "UnicastCount"); e->UnicastBytes = CfgGetInt64(f, "UnicastBytes"); } // Write the traffic information void SiWriteTraffic(FOLDER *parent, char *name, TRAFFIC *t) { FOLDER *f; // Validate arguments if (parent == NULL || name == NULL || t == NULL) { return; } f = CfgCreateFolder(parent, name); SiWriteTrafficInner(f, "SendTraffic", &t->Send); SiWriteTrafficInner(f, "RecvTraffic", &t->Recv); } void SiWriteTrafficInner(FOLDER *parent, char *name, TRAFFIC_ENTRY *e) { FOLDER *f; // Validate arguments if (parent == NULL || name == NULL || e == NULL) { return; } f = CfgCreateFolder(parent, name); CfgAddInt64(f, "BroadcastCount", e->BroadcastCount); CfgAddInt64(f, "BroadcastBytes", e->BroadcastBytes); CfgAddInt64(f, "UnicastCount", e->UnicastCount); CfgAddInt64(f, "UnicastBytes", e->UnicastBytes); } // Thread for writing configuration file void SiSaverThread(THREAD *thread, void *param) { SERVER *s = (SERVER *)param; // Validate arguments if (thread == NULL || param == NULL) { return; } while (s->Halt == false) { // Save to the configuration file if (s->NoMoreSave == false) { SiWriteConfigurationFile(s); } Wait(s->SaveHaltEvent, s->AutoSaveConfigSpan); } } // Write to the configuration file UINT SiWriteConfigurationFile(SERVER *s) { UINT ret; // Validate arguments if (s == NULL) { return 0; } if (s->CfgRw == NULL) { return 0; } if (s->NoMoreSave) { return 0; } Lock(s->SaveCfgLock); { FOLDER *f; Debug("save: SiWriteConfigurationToCfg() start.\n"); f = SiWriteConfigurationToCfg(s); Debug("save: SiWriteConfigurationToCfg() finished.\n"); Debug("save: SaveCfgRw() start.\n"); ret = SaveCfgRwEx(s->CfgRw, f, s->BackupConfigOnlyWhenModified ? s->ConfigRevision : INFINITE); Debug("save: SaveCfgRw() finished.\n"); Debug("save: CfgDeleteFolder() start.\n"); CfgDeleteFolder(f); Debug("save: CfgDeleteFolder() finished.\n"); } Unlock(s->SaveCfgLock); return ret; } // Release the configuration void SiFreeConfiguration(SERVER *s) { // Validate arguments if (s == NULL) { return; } // Write to the configuration file SiWriteConfigurationFile(s); // Terminate the configuration file saving thread s->NoMoreSave = true; s->Halt = true; Set(s->SaveHaltEvent); WaitThread(s->SaveThread, INFINITE); ReleaseEvent(s->SaveHaltEvent); ReleaseThread(s->SaveThread); s->SaveHaltEvent = NULL; s->SaveThread = NULL; // Stop the IPsec server if (s->IPsecServer != NULL) { FreeIPsecServer(s->IPsecServer); s->IPsecServer = NULL; } // Terminate the OpenVPN server if (s->OpenVpnServerUdp != NULL) { FreeOpenVpnServerUdp(s->OpenVpnServerUdp); s->OpenVpnServerUdp = NULL; } // Terminate the DDNS client if (s->DDnsClient != NULL) { FreeDDNSClient(s->DDnsClient); s->DDnsClient = NULL; } // Terminate the VPN Azure client if (s->AzureClient != NULL) { FreeAzureClient(s->AzureClient); s->AzureClient = NULL; } FreeCfgRw(s->CfgRw); s->CfgRw = NULL; // Release the Ethernet FreeEth(); } // Initialize the StXxx related function void StInit() { if (server_lock != NULL) { return; } server_lock = NewLock(); } // Release the StXxx related function void StFree() { DeleteLock(server_lock); server_lock = NULL; } // Start the server void StStartServer(bool bridge) { Lock(server_lock); { if (server != NULL) { // It has already started Unlock(server_lock); return; } // Create a server server = SiNewServer(bridge); } Unlock(server_lock); // StartCedarLog(); } // Get the server SERVER *StGetServer() { if (server == NULL) { return NULL; } return server; } // Stop the server void StStopServer() { Lock(server_lock); { if (server == NULL) { // Not started Unlock(server_lock); return; } // Release the server SiReleaseServer(server); server = NULL; } Unlock(server_lock); StopCedarLog(); } // Set the type of server void SiSetServerType(SERVER *s, UINT type, UINT ip, UINT num_port, UINT *ports, char *controller_name, UINT controller_port, UCHAR *password, UINT weight, bool controller_only) { bool bridge; // Validate arguments if (s == NULL) { return; } if (type == SERVER_TYPE_FARM_MEMBER && (num_port == 0 || ports == NULL || controller_name == NULL || controller_port == 0 || password == NULL || num_port > MAX_PUBLIC_PORT_NUM)) { return; } if (weight == 0) { weight = FARM_DEFAULT_WEIGHT; } bridge = s->Cedar->Bridge; Lock(s->lock); { // Update types s->UpdatedServerType = type; s->Weight = weight; // Set the value if (type == SERVER_TYPE_FARM_MEMBER) { StrCpy(s->ControllerName, sizeof(s->ControllerName), controller_name); s->ControllerPort = controller_port; if (IsZero(password, SHA1_SIZE) == false) { Copy(s->MemberPassword, password, SHA1_SIZE); } s->PublicIp = ip; s->NumPublicPort = num_port; if (s->PublicPorts != NULL) { Free(s->PublicPorts); } s->PublicPorts = ZeroMalloc(num_port * sizeof(UINT)); Copy(s->PublicPorts, ports, num_port * sizeof(UINT)); } if (type == SERVER_TYPE_FARM_CONTROLLER) { s->ControllerOnly = controller_only; } } Unlock(s->lock); // Restart the server SiRebootServer(bridge); } // Thread to restart the server void SiRebootServerThread(THREAD *thread, void *param) { // Validate arguments if (thread == NULL) { return; } if (server == NULL) { return; } // Stop the server StStopServer(); // Start the server StStartServer((bool)param); } // Restart the server void SiRebootServer(bool bridge) { SiRebootServerEx(bridge, false); } void SiRebootServerEx(bool bridge, bool reset_setting) { THREAD *t; server_reset_setting = reset_setting; t = NewThread(SiRebootServerThread, (void *)bridge); ReleaseThread(t); } // Set the state of the special listener void SiApplySpecialListenerStatus(SERVER *s) { // Validate arguments if (s == NULL) { return; } if (s->DynListenerDns != NULL) { *s->DynListenerDns->EnablePtr = s->EnableVpnOverDns; ApplyDynamicListener(s->DynListenerDns); } if (s->DynListenerIcmp != NULL) { *s->DynListenerIcmp->EnablePtr = s->EnableVpnOverIcmp; ApplyDynamicListener(s->DynListenerIcmp); } } // Stop all listeners void SiStopAllListener(SERVER *s) { // Validate arguments if (s == NULL) { return; } SiLockListenerList(s); { UINT i; LIST *o = NewListFast(NULL); for (i = 0;i < LIST_NUM(s->ServerListenerList);i++) { SERVER_LISTENER *e = LIST_DATA(s->ServerListenerList, i); Add(o, e); } for (i = 0;i < LIST_NUM(o);i++) { SERVER_LISTENER *e = LIST_DATA(o, i); SiDeleteListener(s, e->Port); } ReleaseList(o); } SiUnlockListenerList(s); ReleaseList(s->ServerListenerList); // Stop the VPN over ICMP listener FreeDynamicListener(s->DynListenerIcmp); s->DynListenerIcmp = NULL; // Stop the VPN over DNS listener FreeDynamicListener(s->DynListenerDns); s->DynListenerDns = NULL; } // Clean-up the server void SiCleanupServer(SERVER *s) { UINT i; CEDAR *c; LISTENER **listener_list; UINT num_listener; HUB **hub_list; UINT num_hub; // Validate arguments if (s == NULL) { return; } SiFreeDeadLockCheck(s); c = s->Cedar; if (s->ServerType == SERVER_TYPE_FARM_MEMBER) { // In the case of farm members, stop the connection to the farm controller SLog(c, "LS_STOP_FARM_MEMBER"); SiStopConnectToController(s->FarmController); s->FarmController = NULL; SLog(c, "LS_STOP_FARM_MEMBER_2"); } IncrementServerConfigRevision(s); SLog(c, "LS_END_2"); SLog(c, "LS_STOP_ALL_LISTENER"); // Stop all listeners LockList(c->ListenerList); { listener_list = ToArray(c->ListenerList); num_listener = LIST_NUM(c->ListenerList); for (i = 0;i < num_listener;i++) { AddRef(listener_list[i]->ref); } } UnlockList(c->ListenerList); for (i = 0;i < num_listener;i++) { StopListener(listener_list[i]); ReleaseListener(listener_list[i]); } Free(listener_list); SLog(c, "LS_STOP_ALL_LISTENER_2"); SLog(c, "LS_STOP_ALL_HUB"); // Stop all HUBs LockList(c->HubList); { hub_list = ToArray(c->HubList); num_hub = LIST_NUM(c->HubList); for (i = 0;i < num_hub;i++) { AddRef(hub_list[i]->ref); } } UnlockList(c->HubList); for (i = 0;i < num_hub;i++) { StopHub(hub_list[i]); ReleaseHub(hub_list[i]); } Free(hub_list); SLog(c, "LS_STOP_ALL_HUB_2"); // Release the configuration SiFreeConfiguration(s); // Stop the Cedar SLog(c, "LS_STOP_CEDAR"); StopCedar(s->Cedar); SLog(c, "LS_STOP_CEDAR_2"); // Stop all listeners SiStopAllListener(s); if (s->ServerType == SERVER_TYPE_FARM_CONTROLLER) { // In the case of farm controller UINT i; SLog(c, "LS_STOP_FARM_CONTROL"); // Stop the farm controling SiStopFarmControl(s); // Release the farm member information ReleaseList(s->FarmMemberList); s->FarmMemberList = NULL; for (i = 0;i < LIST_NUM(s->Me->HubList);i++) { Free(LIST_DATA(s->Me->HubList, i)); } ReleaseList(s->Me->HubList); Free(s->Me); SLog(c, "LS_STOP_FARM_CONTROL_2"); } if (s->PublicPorts != NULL) { Free(s->PublicPorts); } SLog(s->Cedar, "LS_END_1"); SLog(s->Cedar, "L_LINE"); #ifdef ENABLE_AZURE_SERVER if (s->AzureServer != NULL) { FreeAzureServer(s->AzureServer); } #endif // ENABLE_AZURE_SERVER ReleaseCedar(s->Cedar); DeleteLock(s->lock); DeleteLock(s->SaveCfgLock); StopKeep(s->Keep); FreeEraser(s->Eraser); FreeLog(s->Logger); FreeSysLog(s->Syslog); DeleteLock(s->SyslogLock); FreeServerCapsCache(s); SiFreeHubCreateHistory(s); // Stop the debug log FreeTinyLog(s->DebugLog); DeleteLock(s->TasksFromFarmControllerLock); DeleteLock(s->OpenVpnSstpConfigLock); Free(s); } // Release the server void SiReleaseServer(SERVER *s) { // Validate arguments if (s == NULL) { return; } if (Release(s->ref) == 0) { SiCleanupServer(s); } } // Get the URL of the member selector bool SiGetMemberSelectorUrl(char *url, UINT url_size) { BUF *b; bool ret = false; // Validate arguments if (url == NULL) { return false; } b = ReadDump(MEMBER_SELECTOR_TXT_FILENAME); if (b == NULL) { return false; } while (true) { char *line = CfgReadNextLine(b); if (line == NULL) { break; } Trim(line); if (IsEmptyStr(line) == false && ret == false) { StrCpy(url, url_size, line); ret = true; } Free(line); } FreeBuf(b); return ret; } // Specify the farm member for the next processing FARM_MEMBER *SiGetNextFarmMember(SERVER *s, CONNECTION *c, HUB *h) { UINT i, num; UINT min_point = 0; FARM_MEMBER *ret = NULL; PACK *p; char url[MAX_SIZE]; // Validate arguments if (s == NULL || s->ServerType != SERVER_TYPE_FARM_CONTROLLER || c == NULL || h == NULL) { return NULL; } num = LIST_NUM(s->FarmMemberList); if (num == 0) { return NULL; } if (SiGetMemberSelectorUrl(url, sizeof(url))) { UINT64 ret_key = 0; // Generate the data for the member selector p = NewPack(); for (i = 0;i < num;i++) { UINT num_sessions; UINT max_sessions; FARM_MEMBER *f = LIST_DATA(s->FarmMemberList, i); bool do_not_select = false; if (s->ControllerOnly) { if (f->Me) { // No to select myself in the case of ControllerOnly do_not_select = true; } } if (f->Me == false) { num_sessions = f->NumSessions; max_sessions = f->MaxSessions; } else { num_sessions = Count(s->Cedar->CurrentSessions); max_sessions = GetServerCapsInt(s, "i_max_sessions"); } if (max_sessions == 0) { max_sessions = GetServerCapsInt(s, "i_max_sessions"); } if (num_sessions >= max_sessions) { do_not_select = true; } if (true) { UINT point = f->Point; char public_ip_str[MAX_SIZE]; IPToStr32(public_ip_str, sizeof(public_ip_str), f->Ip); PackAddIntEx(p, "Point", point, i, num); PackAddInt64Ex(p, "Key", (UINT64)f, i, num); PackAddStrEx(p, "Hostname", f->hostname, i, num); PackAddStrEx(p, "PublicIp", public_ip_str, i, num); PackAddIntEx(p, "NumSessions", num_sessions, i, num); PackAddIntEx(p, "MaxSessions", max_sessions, i, num); PackAddIntEx(p, "AssignedClientLicense", f->AssignedClientLicense, i, num); PackAddIntEx(p, "AssignedBridgeLicense", f->AssignedBridgeLicense, i, num); PackAddIntEx(p, "Weight", f->Weight, i, num); PackAddDataEx(p, "RandomKey", f->RandomKey, SHA1_SIZE, i, num); PackAddIntEx(p, "NumTcpConnections", f->NumTcpConnections, i, num); PackAddIntEx(p, "NumHubs", LIST_NUM(f->HubList), i, num); PackAddBoolEx(p, "Me", f->Me, i, num); PackAddInt64Ex(p, "ConnectedTime", f->ConnectedTime, i, num); PackAddInt64Ex(p, "SystemId", f->SystemId, i, num); PackAddBoolEx(p, "DoNotSelect", do_not_select, i, num); } } if (true) { char client_ip_str[MAX_SIZE]; UINT client_port = 0; UINT server_port = 0; SOCK *s = c->FirstSock; Zero(client_ip_str, sizeof(client_ip_str)); if (s != NULL) { IPToStr(client_ip_str, sizeof(client_ip_str), &s->RemoteIP); client_port = s->RemotePort; server_port = s->LocalPort; } PackAddStr(p, "ClientIp", client_ip_str); PackAddInt(p, "ClientPort", client_port); PackAddInt(p, "ServerPort", server_port); PackAddInt(p, "ClientBuild", c->ClientBuild); PackAddStr(p, "CipherName", c->CipherName); PackAddStr(p, "ClientStr", c->ClientStr); PackAddInt(p, "ClientVer", c->ClientVer); PackAddInt64(p, "ConnectedTime", Tick64ToTime64(c->ConnectedTick)); PackAddStr(p, "HubName", h->Name); PackAddBool(p, "StaticHub", h->Type == HUB_TYPE_FARM_STATIC); } PackAddInt(p, "NumMembers", num); // Make the member selector choose a member UnlockList(s->FarmMemberList); Unlock(s->Cedar->CedarSuperLock); { PACK *ret; Debug("Calling %s ...\n", url); ret = WpcCall(url, NULL, MEMBER_SELECTOR_CONNECT_TIMEOUT, MEMBER_SELECTOR_DATA_TIMEOUT, "Select", p, NULL, NULL, NULL); if (GetErrorFromPack(ret) == ERR_NO_ERROR) { ret_key = PackGetInt64(ret, "Key"); Debug("Ret Key = %I64u\n", ret_key); } else { Debug("Error: %u\n", GetErrorFromPack(ret)); } FreePack(ret); } Lock(s->Cedar->CedarSuperLock); LockList(s->FarmMemberList); FreePack(p); if (ret_key != 0) { FARM_MEMBER *f = (FARM_MEMBER *)ret_key; if (IsInList(s->FarmMemberList, f)) { Debug("Farm Member Selected by Selector: %s\n", f->hostname); return f; } else { Debug("Farm Member Key = %I64u Not Found.\n", ret_key); } } else { // The member selector failed to select a member return NULL; } } num = LIST_NUM(s->FarmMemberList); if (num == 0) { return NULL; } for (i = 0;i < num;i++) { UINT num_sessions; UINT max_sessions; FARM_MEMBER *f = LIST_DATA(s->FarmMemberList, i); if (s->ControllerOnly) { if (f->Me) { // No to select myself in the case of ControllerOnly continue; } } if (f->Me == false) { num_sessions = f->NumSessions; max_sessions = f->MaxSessions; } else { num_sessions = Count(s->Cedar->CurrentSessions); max_sessions = GetServerCapsInt(s, "i_max_sessions"); } if (max_sessions == 0) { max_sessions = GetServerCapsInt(s, "i_max_sessions"); } if (num_sessions < max_sessions) { if (f->Point >= min_point) { min_point = f->Point; ret = f; } } } return ret; } // Receive a HUB enumeration directive void SiCalledEnumHub(SERVER *s, PACK *p, PACK *req) { UINT i; CEDAR *c; UINT num = 0; // Validate arguments if (s == NULL || p == NULL || req == NULL) { return; } c = s->Cedar; LockList(c->HubList); { UINT num = LIST_NUM(c->HubList); for (i = 0;i < num;i++) { HUB *h = LIST_DATA(c->HubList, i); Lock(h->lock); { PackAddStrEx(p, "HubName", h->Name, i, num); PackAddIntEx(p, "HubType", h->Type, i, num); PackAddIntEx(p, "NumSession", Count(h->NumSessions), i, num); PackAddIntEx(p, "NumSessions", LIST_NUM(h->SessionList), i, num); PackAddIntEx(p, "NumSessionsClient", Count(h->NumSessionsClient), i, num); PackAddIntEx(p, "NumSessionsBridge", Count(h->NumSessionsBridge), i, num); PackAddIntEx(p, "NumMacTables", HASH_LIST_NUM(h->MacHashTable), i, num); PackAddIntEx(p, "NumIpTables", LIST_NUM(h->IpTable), i, num); PackAddInt64Ex(p, "LastCommTime", h->LastCommTime, i, num); PackAddInt64Ex(p, "CreatedTime", h->CreatedTime, i, num); } Unlock(h->lock); } } UnlockList(c->HubList); PackAddInt(p, "Point", SiGetPoint(s)); PackAddInt(p, "NumTcpConnections", Count(s->Cedar->CurrentTcpConnections)); PackAddInt(p, "NumTotalSessions", Count(s->Cedar->CurrentSessions)); PackAddInt(p, "MaxSessions", GetServerCapsInt(s, "i_max_sessions")); PackAddInt(p, "AssignedClientLicense", Count(s->Cedar->AssignedClientLicense)); PackAddInt(p, "AssignedBridgeLicense", Count(s->Cedar->AssignedBridgeLicense)); PackAddData(p, "RandomKey", s->MyRandomKey, SHA1_SIZE); Lock(c->TrafficLock); { OutRpcTraffic(p, c->Traffic); } Unlock(c->TrafficLock); LockList(c->TrafficDiffList); { UINT num = LIST_NUM(c->TrafficDiffList); UINT i; for (i = 0;i < num;i++) { TRAFFIC_DIFF *d = LIST_DATA(c->TrafficDiffList, i); PackAddIntEx(p, "TdType", d->Type, i, num); PackAddStrEx(p, "TdHubName", d->HubName, i, num); PackAddStrEx(p, "TdName", d->Name, i, num); OutRpcTrafficEx(&d->Traffic, p, i, num); Free(d->HubName); Free(d->Name); Free(d); } DeleteAll(c->TrafficDiffList); } UnlockList(c->TrafficDiffList); } // Receive a HUB delete directive void SiCalledDeleteHub(SERVER *s, PACK *p) { char name[MAX_SIZE]; HUB *h; // Validate arguments if (s == NULL || p == NULL) { return; } if (PackGetStr(p, "HubName", name, sizeof(name)) == false) { return; } LockHubList(s->Cedar); h = GetHub(s->Cedar, name); if (h == NULL) { UnlockHubList(s->Cedar); return; } UnlockHubList(s->Cedar); SetHubOffline(h); LockHubList(s->Cedar); DelHubEx(s->Cedar, h, true); UnlockHubList(s->Cedar); ReleaseHub(h); } // Receive a HUB update directive void SiCalledUpdateHub(SERVER *s, PACK *p) { char name[MAX_SIZE]; UINT type; HUB_OPTION o; HUB_LOG log; bool save_packet_log; UINT packet_log_switch_type; UINT packet_log_config[NUM_PACKET_LOG]; bool save_security_log; bool type_changed = false; UINT security_log_switch_type; UINT i; HUB *h; // Validate arguments if (s == NULL || p == NULL) { return; } PackGetStr(p, "HubName", name, sizeof(name)); type = PackGetInt(p, "HubType"); Zero(&o, sizeof(o)); o.MaxSession = PackGetInt(p, "MaxSession"); o.NoArpPolling = PackGetBool(p, "NoArpPolling"); o.NoIPv6AddrPolling = PackGetBool(p, "NoIPv6AddrPolling"); o.FilterPPPoE = PackGetBool(p, "FilterPPPoE"); o.YieldAfterStorePacket = PackGetBool(p, "YieldAfterStorePacket"); o.NoSpinLockForPacketDelay = PackGetBool(p, "NoSpinLockForPacketDelay"); o.BroadcastStormDetectionThreshold = PackGetInt(p, "BroadcastStormDetectionThreshold"); o.ClientMinimumRequiredBuild = PackGetInt(p, "ClientMinimumRequiredBuild"); o.FixForDLinkBPDU = PackGetBool(p, "FixForDLinkBPDU"); o.BroadcastLimiterStrictMode = PackGetBool(p, "BroadcastLimiterStrictMode"); o.NoLookBPDUBridgeId = PackGetBool(p, "NoLookBPDUBridgeId"); o.NoManageVlanId = PackGetBool(p, "NoManageVlanId"); o.MaxLoggedPacketsPerMinute = PackGetInt(p, "MaxLoggedPacketsPerMinute"); o.FloodingSendQueueBufferQuota = PackGetInt(p, "FloodingSendQueueBufferQuota"); o.DoNotSaveHeavySecurityLogs = PackGetBool(p, "DoNotSaveHeavySecurityLogs"); o.DropBroadcastsInPrivacyFilterMode = PackGetBool(p, "DropBroadcastsInPrivacyFilterMode"); o.DropArpInPrivacyFilterMode = PackGetBool(p, "DropArpInPrivacyFilterMode"); o.SuppressClientUpdateNotification = PackGetBool(p, "SuppressClientUpdateNotification"); o.AssignVLanIdByRadiusAttribute = PackGetBool(p, "AssignVLanIdByRadiusAttribute"); o.SecureNAT_RandomizeAssignIp = PackGetBool(p, "SecureNAT_RandomizeAssignIp"); o.DetectDormantSessionInterval = PackGetInt(p, "DetectDormantSessionInterval"); o.VlanTypeId = PackGetInt(p, "VlanTypeId"); o.NoPhysicalIPOnPacketLog = PackGetBool(p, "NoPhysicalIPOnPacketLog"); if (o.VlanTypeId == 0) { o.VlanTypeId = MAC_PROTO_TAGVLAN; } o.FilterOSPF = PackGetBool(p, "FilterOSPF"); o.FilterIPv4 = PackGetBool(p, "FilterIPv4"); o.FilterIPv6 = PackGetBool(p, "FilterIPv6"); o.FilterNonIP = PackGetBool(p, "FilterNonIP"); o.NoIPv4PacketLog = PackGetBool(p, "NoIPv4PacketLog"); o.NoIPv6PacketLog = PackGetBool(p, "NoIPv6PacketLog"); o.FilterBPDU = PackGetBool(p, "FilterBPDU"); o.NoIPv6DefaultRouterInRAWhenIPv6 = PackGetBool(p, "NoIPv6DefaultRouterInRAWhenIPv6"); o.NoMacAddressLog = PackGetBool(p, "NoMacAddressLog"); o.ManageOnlyPrivateIP = PackGetBool(p, "ManageOnlyPrivateIP"); o.ManageOnlyLocalUnicastIPv6 = PackGetBool(p, "ManageOnlyLocalUnicastIPv6"); o.DisableIPParsing = PackGetBool(p, "DisableIPParsing"); o.NoIpTable = PackGetBool(p, "NoIpTable"); o.NoEnum = PackGetBool(p, "NoEnum"); o.AdjustTcpMssValue = PackGetInt(p, "AdjustTcpMssValue"); o.DisableAdjustTcpMss = PackGetBool(p, "DisableAdjustTcpMss"); o.NoDhcpPacketLogOutsideHub = PackGetBool(p, "NoDhcpPacketLogOutsideHub"); o.DisableHttpParsing = PackGetBool(p, "DisableHttpParsing"); o.DisableUdpAcceleration = PackGetBool(p, "DisableUdpAcceleration"); o.DisableUdpFilterForLocalBridgeNic = PackGetBool(p, "DisableUdpFilterForLocalBridgeNic"); o.ApplyIPv4AccessListOnArpPacket = PackGetBool(p, "ApplyIPv4AccessListOnArpPacket"); o.RemoveDefGwOnDhcpForLocalhost = PackGetBool(p, "RemoveDefGwOnDhcpForLocalhost"); o.SecureNAT_MaxTcpSessionsPerIp = PackGetInt(p, "SecureNAT_MaxTcpSessionsPerIp"); o.SecureNAT_MaxTcpSynSentPerIp = PackGetInt(p, "SecureNAT_MaxTcpSynSentPerIp"); o.SecureNAT_MaxUdpSessionsPerIp = PackGetInt(p, "SecureNAT_MaxUdpSessionsPerIp"); o.SecureNAT_MaxDnsSessionsPerIp = PackGetInt(p, "SecureNAT_MaxDnsSessionsPerIp"); o.SecureNAT_MaxIcmpSessionsPerIp = PackGetInt(p, "SecureNAT_MaxIcmpSessionsPerIp"); o.AccessListIncludeFileCacheLifetime = PackGetInt(p, "AccessListIncludeFileCacheLifetime"); if (o.AccessListIncludeFileCacheLifetime == 0) { o.AccessListIncludeFileCacheLifetime = ACCESS_LIST_INCLUDE_FILE_CACHE_LIFETIME; } o.DisableKernelModeSecureNAT = PackGetBool(p, "DisableKernelModeSecureNAT"); o.DisableUserModeSecureNAT = PackGetBool(p, "DisableUserModeSecureNAT"); o.DisableCheckMacOnLocalBridge = PackGetBool(p, "DisableCheckMacOnLocalBridge"); o.DisableCorrectIpOffloadChecksum = PackGetBool(p, "DisableCorrectIpOffloadChecksum"); save_packet_log = PackGetInt(p, "SavePacketLog"); packet_log_switch_type = PackGetInt(p, "PacketLogSwitchType"); for (i = 0;i < NUM_PACKET_LOG;i++) { packet_log_config[i] = PackGetIntEx(p, "PacketLogConfig", i); } save_security_log = PackGetInt(p, "SaveSecurityLog"); security_log_switch_type = PackGetInt(p, "SecurityLogSwitchType"); Zero(&log, sizeof(log)); log.SavePacketLog = save_packet_log; log.PacketLogSwitchType = packet_log_switch_type; Copy(log.PacketLogConfig, packet_log_config, sizeof(log.PacketLogConfig)); log.SaveSecurityLog = save_security_log; log.SecurityLogSwitchType = security_log_switch_type; h = GetHub(s->Cedar, name); if (h == NULL) { return; } h->FarmMember_MaxSessionClient = PackGetInt(p, "MaxSessionClient"); h->FarmMember_MaxSessionBridge = PackGetInt(p, "MaxSessionBridge"); h->FarmMember_MaxSessionClientBridgeApply = PackGetBool(p, "MaxSessionClientBridgeApply"); if (h->FarmMember_MaxSessionClientBridgeApply == false) { h->FarmMember_MaxSessionClient = INFINITE; h->FarmMember_MaxSessionBridge = INFINITE; } Lock(h->lock); { Copy(h->Option, &o, sizeof(HUB_OPTION)); PackGetData2(p, "SecurePassword", h->SecurePassword, SHA1_SIZE); PackGetData2(p, "HashedPassword", h->HashedPassword, SHA1_SIZE); } Unlock(h->lock); SetHubLogSetting(h, &log); if (h->Type != type) { h->Type = type; type_changed = true; } LockList(h->AccessList); { UINT i; for (i = 0;i < LIST_NUM(h->AccessList);i++) { ACCESS *a = LIST_DATA(h->AccessList, i); Free(a); } DeleteAll(h->AccessList); } UnlockList(h->AccessList); for (i = 0;i < SiNumAccessFromPack(p);i++) { ACCESS *a = SiPackToAccess(p, i); AddAccessList(h, a); Free(a); } if (PackGetBool(p, "EnableSecureNAT")) { VH_OPTION t; bool changed; InVhOption(&t, p); changed = Cmp(h->SecureNATOption, &t, sizeof(VH_OPTION)) == 0 ? false : true; Copy(h->SecureNATOption, &t, sizeof(VH_OPTION)); EnableSecureNAT(h, true); if (changed) { Lock(h->lock_online); { if (h->SecureNAT != NULL) { SetVirtualHostOption(h->SecureNAT->Nat->Virtual, &t); Debug("SiCalledUpdateHub: SecureNAT Updated.\n"); } } Unlock(h->lock_online); } } else { EnableSecureNAT(h, false); Debug("SiCalledUpdateHub: SecureNAT Disabled.\n"); } if (type_changed) { // Remove all sessions since the type of HUB has been changed if (h->Offline == false) { SetHubOffline(h); SetHubOnline(h); } } ReleaseHub(h); } // Inspect the ticket bool SiCheckTicket(HUB *h, UCHAR *ticket, char *username, UINT username_size, char *usernamereal, UINT usernamereal_size, POLICY *policy, char *sessionname, UINT sessionname_size, char *groupname, UINT groupname_size) { bool ret = false; // Validate arguments if (h == NULL || ticket == NULL || username == NULL || usernamereal == NULL || policy == NULL || sessionname == NULL) { return false; } LockList(h->TicketList); { UINT i; for (i = 0;i < LIST_NUM(h->TicketList);i++) { TICKET *t = LIST_DATA(h->TicketList, i); if (Cmp(t->Ticket, ticket, SHA1_SIZE) == 0) { ret = true; StrCpy(username, username_size, t->Username); StrCpy(usernamereal, usernamereal_size, t->UsernameReal); StrCpy(sessionname, sessionname_size, t->SessionName); StrCpy(groupname, groupname_size, t->GroupName); Copy(policy, &t->Policy, sizeof(POLICY)); Delete(h->TicketList, t); Free(t); break; } } } UnlockList(h->TicketList); return ret; } // Receive a MAC address deletion directive void SiCalledDeleteMacTable(SERVER *s, PACK *p) { UINT key; char hubname[MAX_HUBNAME_LEN + 1]; HUB *h; // Validate arguments if (s == NULL || p == NULL) { return; } if (PackGetStr(p, "HubName", hubname, sizeof(hubname)) == false) { return; } key = PackGetInt(p, "Key"); LockHubList(s->Cedar); { h = GetHub(s->Cedar, hubname); } UnlockHubList(s->Cedar); if (h == NULL) { return; } LockHashList(h->MacHashTable); { MAC_TABLE_ENTRY *e = HashListKeyToPointer(h->MacHashTable, key); DeleteHash(h->MacHashTable, e); Free(e); } UnlockHashList(h->MacHashTable); ReleaseHub(h); } // Receive an IP address delete directive void SiCalledDeleteIpTable(SERVER *s, PACK *p) { UINT key; char hubname[MAX_HUBNAME_LEN + 1]; HUB *h; // Validate arguments if (s == NULL || p == NULL) { return; } if (PackGetStr(p, "HubName", hubname, sizeof(hubname)) == false) { return; } key = PackGetInt(p, "Key"); LockHubList(s->Cedar); { h = GetHub(s->Cedar, hubname); } UnlockHubList(s->Cedar); if (h == NULL) { return; } LockList(h->IpTable); { if (IsInList(h->IpTable, (void *)key)) { IP_TABLE_ENTRY *e = (IP_TABLE_ENTRY *)key; Delete(h->IpTable, e); Free(e); } } UnlockList(h->IpTable); ReleaseHub(h); } // Receive a session deletion directive void SiCalledDeleteSession(SERVER *s, PACK *p) { char name[MAX_SESSION_NAME_LEN + 1]; char hubname[MAX_HUBNAME_LEN + 1]; HUB *h; SESSION *sess; // Validate arguments if (s == NULL || p == NULL) { return; } if (PackGetStr(p, "HubName", hubname, sizeof(hubname)) == false) { return; } if (PackGetStr(p, "SessionName", name, sizeof(name)) == false) { return; } LockHubList(s->Cedar); { h = GetHub(s->Cedar, hubname); } UnlockHubList(s->Cedar); if (h == NULL) { return; } sess = GetSessionByName(h, name); if (sess != NULL) { if (sess->BridgeMode == false && sess->LinkModeServer == false && sess->SecureNATMode == false) { StopSession(sess); } ReleaseSession(sess); } ReleaseHub(h); } // Receive a log file reading directive PACK *SiCalledReadLogFile(SERVER *s, PACK *p) { RPC_READ_LOG_FILE t; PACK *ret; char filepath[MAX_PATH]; UINT offset; // Validate arguments if (s == NULL || p == NULL) { return NULL; } PackGetStr(p, "FilePath", filepath, sizeof(filepath)); offset = PackGetInt(p, "Offset"); Zero(&t, sizeof(t)); SiReadLocalLogFile(s, filepath, offset, &t); ret = NewPack(); OutRpcReadLogFile(ret, &t); FreeRpcReadLogFile(&t); return ret; } // Receive a log file enumeration directive PACK *SiCalledEnumLogFileList(SERVER *s, PACK *p) { RPC_ENUM_LOG_FILE t; PACK *ret; char hubname[MAX_HUBNAME_LEN + 1]; // Validate arguments if (s == NULL || p == NULL) { return NULL; } PackGetStr(p, "HubName", hubname, sizeof(hubname)); Zero(&t, sizeof(t)); SiEnumLocalLogFileList(s, hubname, &t); ret = NewPack(); OutRpcEnumLogFile(ret, &t); FreeRpcEnumLogFile(&t); return ret; } // Receive a session information directive PACK *SiCalledGetSessionStatus(SERVER *s, PACK *p) { RPC_SESSION_STATUS t; ADMIN a; PACK *ret; // Validate arguments if (s == NULL || p == NULL) { return NULL; } Zero(&t, sizeof(t)); InRpcSessionStatus(&t, p); Zero(&a, sizeof(a)); a.Server = s; a.ServerAdmin = true; if (StGetSessionStatus(&a, &t) != ERR_NO_ERROR) { FreeRpcSessionStatus(&t); return NULL; } ret = NewPack(); OutRpcSessionStatus(ret, &t); FreeRpcSessionStatus(&t); return ret; } // IP table enumeration directive PACK *SiCalledEnumIpTable(SERVER *s, PACK *p) { char hubname[MAX_HUBNAME_LEN + 1]; RPC_ENUM_IP_TABLE t; PACK *ret; // Validate arguments if (s == NULL || p == NULL) { return NewPack(); } if (PackGetStr(p, "HubName", hubname, sizeof(hubname)) == false) { return NewPack(); } Zero(&t, sizeof(t)); SiEnumIpTable(s, hubname, &t); ret = NewPack(); OutRpcEnumIpTable(ret, &t); FreeRpcEnumIpTable(&t); return ret; } // MAC table enumeration directive PACK *SiCalledEnumMacTable(SERVER *s, PACK *p) { char hubname[MAX_HUBNAME_LEN + 1]; RPC_ENUM_MAC_TABLE t; PACK *ret; // Validate arguments if (s == NULL || p == NULL) { return NewPack(); } if (PackGetStr(p, "HubName", hubname, sizeof(hubname)) == false) { return NewPack(); } Zero(&t, sizeof(t)); SiEnumMacTable(s, hubname, &t); ret = NewPack(); OutRpcEnumMacTable(ret, &t); FreeRpcEnumMacTable(&t); return ret; } // NAT status acquisition directive PACK *SiCalledGetNatStatus(SERVER *s, PACK *p) { char hubname[MAX_HUBNAME_LEN + 1]; RPC_NAT_STATUS t; PACK *ret; HUB *h; // Validate arguments if (s == NULL || p == NULL) { return NewPack(); } if (PackGetStr(p, "HubName", hubname, sizeof(hubname)) == false) { return NewPack(); } Zero(&t, sizeof(t)); LockHubList(s->Cedar); { h = GetHub(s->Cedar, hubname); } UnlockHubList(s->Cedar); if (h != NULL) { Lock(h->lock_online); { if (h->SecureNAT != NULL) { NtGetStatus(h->SecureNAT->Nat, &t); } } Unlock(h->lock_online); } ReleaseHub(h); ret = NewPack(); OutRpcNatStatus(ret, &t); FreeRpcNatStatus(&t); return ret; } // DHCP table enumeration directive PACK *SiCalledEnumDhcp(SERVER *s, PACK *p) { char hubname[MAX_HUBNAME_LEN + 1]; RPC_ENUM_DHCP t; PACK *ret; HUB *h; // Validate arguments if (s == NULL || p == NULL) { return NewPack(); } if (PackGetStr(p, "HubName", hubname, sizeof(hubname)) == false) { return NewPack(); } Zero(&t, sizeof(t)); LockHubList(s->Cedar); { h = GetHub(s->Cedar, hubname); } UnlockHubList(s->Cedar); if (h != NULL) { Lock(h->lock_online); { if (h->SecureNAT != NULL) { NtEnumDhcpList(h->SecureNAT->Nat, &t); } } Unlock(h->lock_online); } ReleaseHub(h); ret = NewPack(); OutRpcEnumDhcp(ret, &t); FreeRpcEnumDhcp(&t); return ret; } // NAT table enumeration directive PACK *SiCalledEnumNat(SERVER *s, PACK *p) { char hubname[MAX_HUBNAME_LEN + 1]; RPC_ENUM_NAT t; PACK *ret; HUB *h; // Validate arguments if (s == NULL || p == NULL) { return NewPack(); } if (PackGetStr(p, "HubName", hubname, sizeof(hubname)) == false) { return NewPack(); } Zero(&t, sizeof(t)); LockHubList(s->Cedar); { h = GetHub(s->Cedar, hubname); } UnlockHubList(s->Cedar); if (h != NULL) { Lock(h->lock_online); { if (h->SecureNAT != NULL) { NtEnumNatList(h->SecureNAT->Nat, &t); } } Unlock(h->lock_online); } ReleaseHub(h); ret = NewPack(); OutRpcEnumNat(ret, &t); FreeRpcEnumNat(&t); return ret; } // Receive a session enumeration directive PACK *SiCalledEnumSession(SERVER *s, PACK *p) { char hubname[MAX_HUBNAME_LEN + 1]; RPC_ENUM_SESSION t; PACK *ret; // Validate arguments if (s == NULL || p == NULL) { return NewPack(); } if (PackGetStr(p, "HubName", hubname, sizeof(hubname)) == false) { return NewPack(); } Zero(&t, sizeof(t)); SiEnumLocalSession(s, hubname, &t); ret = NewPack(); OutRpcEnumSession(ret, &t); FreeRpcEnumSession(&t); return ret; } // Receive a ticket creation directive PACK *SiCalledCreateTicket(SERVER *s, PACK *p) { char username[MAX_SIZE]; char hubname[MAX_SIZE]; char groupname[MAX_SIZE]; char realusername[MAX_SIZE]; char sessionname[MAX_SESSION_NAME_LEN + 1]; POLICY policy; UCHAR ticket[SHA1_SIZE]; char ticket_str[MAX_SIZE]; HUB *h; UINT i; PACK *ret; TICKET *t; // Validate arguments if (s == NULL || p == NULL) { return NewPack(); } PackGetStr(p, "UserName", username, sizeof(username)); PackGetStr(p, "GroupName", groupname, sizeof(groupname)); PackGetStr(p, "HubName", hubname, sizeof(hubname)); PackGetStr(p, "RealUserName", realusername, sizeof(realusername)); PackGetStr(p, "SessionName", sessionname, sizeof(sessionname)); InRpcPolicy(&policy, p); if (PackGetDataSize(p, "Ticket") == SHA1_SIZE) { PackGetData(p, "Ticket", ticket); } BinToStr(ticket_str, sizeof(ticket_str), ticket, SHA1_SIZE); SLog(s->Cedar, "LS_TICKET_2", hubname, username, realusername, sessionname, ticket_str, TICKET_EXPIRES / 1000); // Get the HUB h = GetHub(s->Cedar, hubname); if (h == NULL) { return NewPack(); } LockList(h->TicketList); { LIST *o = NewListFast(NULL); // Discard old tickets for (i = 0;i < LIST_NUM(h->TicketList);i++) { TICKET *t = LIST_DATA(h->TicketList, i); if ((t->CreatedTick + TICKET_EXPIRES) < Tick64()) { Add(o, t); } } for (i = 0;i < LIST_NUM(o);i++) { TICKET *t = LIST_DATA(o, i); Delete(h->TicketList, t); Free(t); } ReleaseList(o); // Create a ticket t = ZeroMalloc(sizeof(TICKET)); t->CreatedTick = Tick64(); Copy(&t->Policy, &policy, sizeof(POLICY)); Copy(t->Ticket, ticket, SHA1_SIZE); StrCpy(t->Username, sizeof(t->Username), username); StrCpy(t->UsernameReal, sizeof(t->UsernameReal), realusername); StrCpy(t->GroupName, sizeof(t->GroupName), groupname); StrCpy(t->SessionName, sizeof(t->SessionName), sessionname); Add(h->TicketList, t); } UnlockList(h->TicketList); ReleaseHub(h); ret = NewPack(); PackAddInt(ret, "Point", SiGetPoint(s)); return ret; } // Receive a HUB creation directive void SiCalledCreateHub(SERVER *s, PACK *p) { char name[MAX_SIZE]; UINT type; HUB_OPTION o; HUB_LOG log; bool save_packet_log; UINT packet_log_switch_type; UINT packet_log_config[NUM_PACKET_LOG]; bool save_security_log; UINT security_log_switch_type; UINT i; HUB *h; // Validate arguments if (s == NULL || p == NULL) { return; } PackGetStr(p, "HubName", name, sizeof(name)); type = PackGetInt(p, "HubType"); Zero(&o, sizeof(o)); o.MaxSession = PackGetInt(p, "MaxSession"); save_packet_log = PackGetInt(p, "SavePacketLog"); packet_log_switch_type = PackGetInt(p, "PacketLogSwitchType"); for (i = 0;i < NUM_PACKET_LOG;i++) { packet_log_config[i] = PackGetIntEx(p, "PacketLogConfig", i); } save_security_log = PackGetInt(p, "SaveSecurityLog"); security_log_switch_type = PackGetInt(p, "SecurityLogSwitchType"); Zero(&log, sizeof(log)); log.SavePacketLog = save_packet_log; log.PacketLogSwitchType = packet_log_switch_type; Copy(log.PacketLogConfig, packet_log_config, sizeof(log.PacketLogConfig)); log.SaveSecurityLog = save_security_log; log.SecurityLogSwitchType = security_log_switch_type; h = NewHub(s->Cedar, name, &o); h->LastCommTime = h->LastLoginTime = h->CreatedTime = 0; SetHubLogSetting(h, &log); h->Type = type; h->FarmMember_MaxSessionClient = PackGetInt(p, "MaxSessionClient"); h->FarmMember_MaxSessionBridge = PackGetInt(p, "MaxSessionBridge"); h->FarmMember_MaxSessionClientBridgeApply = PackGetBool(p, "MaxSessionClientBridgeApply"); if (h->FarmMember_MaxSessionClientBridgeApply == false) { h->FarmMember_MaxSessionClient = INFINITE; h->FarmMember_MaxSessionBridge = INFINITE; } PackGetData2(p, "SecurePassword", h->SecurePassword, SHA1_SIZE); PackGetData2(p, "HashedPassword", h->HashedPassword, SHA1_SIZE); for (i = 0;i < SiNumAccessFromPack(p);i++) { ACCESS *a = SiPackToAccess(p, i); AddAccessList(h, a); Free(a); } if (PackGetBool(p, "EnableSecureNAT")) { VH_OPTION t; InVhOption(&t, p); Copy(h->SecureNATOption, &t, sizeof(VH_OPTION)); EnableSecureNAT(h, true); Debug("SiCalledCreateHub: SecureNAT Created.\n"); } AddHub(s->Cedar, h); h->Offline = true; SetHubOnline(h); ReleaseHub(h); } // Farm control thread void SiFarmControlThread(THREAD *thread, void *param) { SERVER *s; CEDAR *c; EVENT *e; LIST *o; UINT i; char tmp[MAX_PATH]; // Validate arguments if (thread == NULL || param == NULL) { return; } s = (SERVER *)param; c = s->Cedar; e = s->FarmControlThreadHaltEvent; while (true) { Lock(c->CedarSuperLock); // Enumerate HUB list which is hosted by each farm member Format(tmp, sizeof(tmp), "CONTROLLER: %s %u", __FILE__, __LINE__); SiDebugLog(s, tmp); LockList(s->FarmMemberList); { UINT i; UINT num; UINT assigned_client_license = 0; UINT assigned_bridge_license = 0; LIST *fm_list = NewListFast(NULL); Format(tmp, sizeof(tmp), "CONTROLLER: %s %u", __FILE__, __LINE__); SiDebugLog(s, tmp); num = 0; while (true) { bool escape = true; for (i = 0;i < LIST_NUM(s->FarmMemberList);i++) { FARM_MEMBER *f = LIST_DATA(s->FarmMemberList, i); if (IsInList(fm_list, f) == false) { SiCallEnumHub(s, f); // Get the total number of sessions across the server farm num += f->NumSessions; assigned_client_license += f->AssignedClientLicense; assigned_bridge_license += f->AssignedBridgeLicense; escape = false; Add(fm_list, f); break; } } if (escape) { break; } UnlockList(s->FarmMemberList); LockList(s->FarmMemberList); } ReleaseList(fm_list); s->CurrentTotalNumSessionsOnFarm = num; // Update the number of assigned licenses s->CurrentAssignedBridgeLicense = assigned_bridge_license; s->CurrentAssignedClientLicense = assigned_client_license; Format(tmp, sizeof(tmp), "CONTROLLER: %s %u", __FILE__, __LINE__); SiDebugLog(s, tmp); } UnlockList(s->FarmMemberList); Format(tmp, sizeof(tmp), "CONTROLLER: %s %u", __FILE__, __LINE__); SiDebugLog(s, tmp); o = NewListFast(NULL); Format(tmp, sizeof(tmp), "CONTROLLER: %s %u", __FILE__, __LINE__); SiDebugLog(s, tmp); // Emit an update notification for each HUB LockList(c->HubList); { UINT i; for (i = 0;i < LIST_NUM(c->HubList);i++) { HUB *h = LIST_DATA(c->HubList, i); AddRef(h->ref); Add(o, h); } } UnlockList(c->HubList); Format(tmp, sizeof(tmp), "CONTROLLER: %s %u", __FILE__, __LINE__); SiDebugLog(s, tmp); for (i = 0;i < LIST_NUM(o);i++) { HUB *h = LIST_DATA(o, i); SiHubUpdateProc(h); ReleaseHub(h); } Format(tmp, sizeof(tmp), "CONTROLLER: %s %u", __FILE__, __LINE__); SiDebugLog(s, tmp); ReleaseList(o); Unlock(c->CedarSuperLock); Wait(e, SERVER_FARM_CONTROL_INTERVAL); if (s->Halt) { break; } } } // Start the farm controling void SiStartFarmControl(SERVER *s) { // Validate arguments if (s == NULL || s->ServerType != SERVER_TYPE_FARM_CONTROLLER) { return; } s->FarmControlThreadHaltEvent = NewEvent(); s->FarmControlThread = NewThread(SiFarmControlThread, s); } // Stop the farm controling void SiStopFarmControl(SERVER *s) { // Validate arguments if (s == NULL || s->ServerType != SERVER_TYPE_FARM_CONTROLLER) { return; } Set(s->FarmControlThreadHaltEvent); WaitThread(s->FarmControlThread, INFINITE); ReleaseEvent(s->FarmControlThreadHaltEvent); ReleaseThread(s->FarmControlThread); } // HUB enumeration directive (asynchronous start) void SiCallEnumHubBegin(SERVER *s, FARM_MEMBER *f) { // Validate arguments if (s == NULL || f == NULL) { return; } } // HUB enumeration directive (asynchronous end) void SiCallEnumHubEnd(SERVER *s, FARM_MEMBER *f) { // Validate arguments if (s == NULL || f == NULL) { return; } } // HUB enumeration directive void SiCallEnumHub(SERVER *s, FARM_MEMBER *f) { CEDAR *c; // Validate arguments if (s == NULL || f == NULL) { return; } c = s->Cedar; if (f->Me) { // Enumerate local HUBs LockList(f->HubList); { // For a local HUB, re-enumerate by erasing all STATIC HUB list once first UINT i; LIST *o = NewListFast(NULL); for (i = 0;i < LIST_NUM(f->HubList);i++) { HUB_LIST *h = LIST_DATA(f->HubList, i); if (h->DynamicHub == false) { Add(o, h); } } // Clear all the STATIC HUB for (i = 0;i < LIST_NUM(o);i++) { HUB_LIST *h = LIST_DATA(o, i); Free(h); Delete(f->HubList, h); } ReleaseList(o); // Second, stop DYNAMIC HUBs without user o = NewListFast(NULL); for (i = 0;i < LIST_NUM(f->HubList);i++) { HUB_LIST *h = LIST_DATA(f->HubList, i); if (h->DynamicHub == true) { LockList(c->HubList); { HUB *hub = GetHub(s->Cedar, h->Name); if (hub != NULL) { if (Count(hub->NumSessions) == 0 || hub->Type != HUB_TYPE_FARM_DYNAMIC) { Add(o, h); } ReleaseHub(hub); } } UnlockList(c->HubList); } } for (i = 0;i < LIST_NUM(o);i++) { HUB_LIST *h = LIST_DATA(o, i); Debug("Delete HUB: %s\n", h->Name); Free(h); Delete(f->HubList, h); } ReleaseList(o); // Set the enumeration results LockList(c->HubList); { for (i = 0;i < LIST_NUM(c->HubList);i++) { HUB *h = LIST_DATA(c->HubList, i); if (h->Offline == false) { if (h->Type == HUB_TYPE_FARM_STATIC) { HUB_LIST *hh = ZeroMalloc(sizeof(HUB_LIST)); hh->FarmMember = f; hh->DynamicHub = false; StrCpy(hh->Name, sizeof(hh->Name), h->Name); Add(f->HubList, hh); LockList(h->SessionList); { hh->NumSessions = LIST_NUM(h->SessionList); hh->NumSessionsBridge = Count(h->NumSessionsBridge); hh->NumSessionsClient = Count(h->NumSessionsClient); } UnlockList(h->SessionList); LockHashList(h->MacHashTable); { hh->NumMacTables = HASH_LIST_NUM(h->MacHashTable); } UnlockHashList(h->MacHashTable); LockList(h->IpTable); { hh->NumIpTables = LIST_NUM(h->IpTable); } UnlockList(h->IpTable); } } } } UnlockList(c->HubList); } UnlockList(f->HubList); // Point f->Point = SiGetPoint(s); f->NumSessions = Count(s->Cedar->CurrentSessions); f->MaxSessions = GetServerCapsInt(s, "i_max_sessions"); f->NumTcpConnections = Count(s->Cedar->CurrentTcpConnections); Lock(s->Cedar->TrafficLock); { Copy(&f->Traffic, s->Cedar->Traffic, sizeof(TRAFFIC)); } Unlock(s->Cedar->TrafficLock); f->AssignedBridgeLicense = Count(s->Cedar->AssignedBridgeLicense); f->AssignedClientLicense = Count(s->Cedar->AssignedClientLicense); Copy(f->RandomKey, s->MyRandomKey, SHA1_SIZE); Debug("Server %s: Point %u\n", f->hostname, f->Point); } else { // Enumerate HUBs which are remote member PACK *p = NewPack(); UINT i, num, j; LIST *o = NewListFast(NULL); num = 0; for (i = 0;i < LIST_NUM(s->FarmMemberList);i++) { FARM_MEMBER *f = LIST_DATA(s->FarmMemberList, i); if (IsZero(f->RandomKey, SHA1_SIZE) == false && f->SystemId != 0) { num++; } } j = 0; for (i = 0;i < LIST_NUM(s->FarmMemberList);i++) { FARM_MEMBER *f = LIST_DATA(s->FarmMemberList, i); if (IsZero(f->RandomKey, SHA1_SIZE) == false && f->SystemId != 0) { PackAddDataEx(p, "MemberRandomKey", f->RandomKey, SHA1_SIZE, j, num); PackAddInt64Ex(p, "MemberSystemId", f->SystemId, j, num); j++; } } PackAddInt(p, "MemberSystemIdNum", num); p = SiCallTask(f, p, "enumhub"); if (p != NULL) { LockList(f->HubList); { UINT i; // Erase the list for (i = 0;i < LIST_NUM(f->HubList);i++) { HUB_LIST *hh = LIST_DATA(f->HubList, i); Free(hh); } DeleteAll(f->HubList); for (i = 0;i < PackGetIndexCount(p, "HubName");i++) { HUB_LIST *hh = ZeroMalloc(sizeof(HUB_LIST)); UINT num; UINT64 LastCommTime; PackGetStrEx(p, "HubName", hh->Name, sizeof(hh->Name), i); num = PackGetIntEx(p, "NumSession", i); hh->DynamicHub = ((PackGetIntEx(p, "HubType", i) == HUB_TYPE_FARM_DYNAMIC) ? true : false); hh->FarmMember = f; hh->NumSessions = PackGetIntEx(p, "NumSessions", i); hh->NumSessionsClient = PackGetIntEx(p, "NumSessionsClient", i); hh->NumSessionsBridge = PackGetIntEx(p, "NumSessionsBridge", i); hh->NumIpTables = PackGetIntEx(p, "NumIpTables", i); hh->NumMacTables = PackGetIntEx(p, "NumMacTables", i); LastCommTime = PackGetInt64Ex(p, "LastCommTime", i); Add(f->HubList, hh); //Debug("%s\n", hh->Name); LockList(c->HubList); { HUB *h = GetHub(c, hh->Name); if (h != NULL) { // Update the LastCommTime of the Virtual HUB Lock(h->lock); { if (h->LastCommTime < LastCommTime) { h->LastCommTime = LastCommTime; } } Unlock(h->lock); ReleaseHub(h); } } UnlockList(c->HubList); if (hh->DynamicHub && num >= 1) { // It is not necessary to be registered in the virtual HUB creation // history list because user session is already connected. // Remove from the Virtual HUB creation history list SiDelHubCreateHistory(s, hh->Name); } if (hh->DynamicHub && num == 0) { // Check the Virtual HUB creation history list. // If it is created within 60 seconds of the most recent // in the case of Virtual HUB which the first user is not // connected yet, not to remove because there is no user if (SiIsHubRegistedOnCreateHistory(s, hh->Name) == false) { // Stop because all uses have gone in the dynamic HUB HUB *h; LockList(c->HubList); { h = GetHub(c, hh->Name); } UnlockList(c->HubList); if (h != NULL) { Add(o, h); } } } } } UnlockList(f->HubList); f->Point = PackGetInt(p, "Point"); Debug("Server %s: Point %u\n", f->hostname, f->Point); f->NumSessions = PackGetInt(p, "NumTotalSessions"); if (f->NumSessions == 0) { f->NumSessions = PackGetInt(p, "NumSessions"); } f->MaxSessions = PackGetInt(p, "MaxSessions"); f->NumTcpConnections = PackGetInt(p, "NumTcpConnections"); InRpcTraffic(&f->Traffic, p); f->AssignedBridgeLicense = PackGetInt(p, "AssignedBridgeLicense"); f->AssignedClientLicense = PackGetInt(p, "AssignedClientLicense"); if (PackGetDataSize(p, "RandomKey") == SHA1_SIZE) { PackGetData(p, "RandomKey", f->RandomKey); } f->SystemId = PackGetInt64(p, "SystemId"); // Apply the traffic difference information num = PackGetIndexCount(p, "TdType"); for (i = 0;i < num;i++) { TRAFFIC traffic; UINT type; HUB *h; char name[MAX_SIZE]; char hubname[MAX_SIZE]; type = PackGetIntEx(p, "TdType", i); PackGetStrEx(p, "TdName", name, sizeof(name), i); PackGetStrEx(p, "TdHubName", hubname, sizeof(hubname), i); InRpcTrafficEx(&traffic, p, i); LockList(c->HubList); { h = GetHub(c, hubname); if (h != NULL) { if (type == TRAFFIC_DIFF_HUB) { Lock(h->TrafficLock); { AddTraffic(h->Traffic, &traffic); } Unlock(h->TrafficLock); } else { AcLock(h); { USER *u = AcGetUser(h, name); if (u != NULL) { Lock(u->lock); { AddTraffic(u->Traffic, &traffic); } Unlock(u->lock); if (u->Group != NULL) { Lock(u->Group->lock); { AddTraffic(u->Group->Traffic, &traffic); } Unlock(u->Group->lock); } ReleaseUser(u); } } AcUnlock(h); } ReleaseHub(h); } UnlockList(c->HubList); } } FreePack(p); } for (i = 0;i < LIST_NUM(o);i++) { HUB *h = LIST_DATA(o, i); SiCallDeleteHub(s, f, h); Debug("Delete HUB: %s\n", h->Name); ReleaseHub(h); } ReleaseList(o); } } // Send a session information directive bool SiCallGetSessionStatus(SERVER *s, FARM_MEMBER *f, RPC_SESSION_STATUS *t) { PACK *p; // Validate arguments if (s == NULL || f == NULL) { return false; } p = NewPack(); OutRpcSessionStatus(p, t); FreeRpcSessionStatus(t); Zero(t, sizeof(RPC_SESSION_STATUS)); p = SiCallTask(f, p, "getsessionstatus"); if (p == NULL) { return false; } InRpcSessionStatus(t, p); FreePack(p); return true; } // Log file reading directive bool SiCallReadLogFile(SERVER *s, FARM_MEMBER *f, RPC_READ_LOG_FILE *t) { PACK *p; // Validate arguments if (s == NULL || f == NULL) { return false; } p = NewPack(); OutRpcReadLogFile(p, t); FreeRpcReadLogFile(t); Zero(t, sizeof(RPC_READ_LOG_FILE)); p = SiCallTask(f, p, "readlogfile"); if (p == NULL) { return false; } InRpcReadLogFile(t, p); FreePack(p); return true; } // Log file enumeration directive bool SiCallEnumLogFileList(SERVER *s, FARM_MEMBER *f, RPC_ENUM_LOG_FILE *t, char *hubname) { PACK *p; // Validate arguments if (s == NULL || f == NULL) { return false; } p = NewPack(); OutRpcEnumLogFile(p, t); FreeRpcEnumLogFile(t); Zero(t, sizeof(RPC_ENUM_LOG_FILE)); PackAddStr(p, "HubName", hubname); p = SiCallTask(f, p, "enumlogfilelist"); if (p == NULL) { return false; } InRpcEnumLogFile(t, p); FreePack(p); return true; } // HUB delete directive void SiCallDeleteHub(SERVER *s, FARM_MEMBER *f, HUB *h) { PACK *p; UINT i; // Validate arguments if (s == NULL || f == NULL) { return; } if (f->Me == false) { p = NewPack(); PackAddStr(p, "HubName", h->Name); p = SiCallTask(f, p, "deletehub"); FreePack(p); } LockList(f->HubList); { for (i = 0;i < LIST_NUM(f->HubList);i++) { HUB_LIST *hh = LIST_DATA(f->HubList, i); if (StrCmpi(hh->Name, h->Name) == 0) { Free(hh); Delete(f->HubList, hh); } } } UnlockList(f->HubList); } // Submit a HUB update directive void SiCallUpdateHub(SERVER *s, FARM_MEMBER *f, HUB *h) { PACK *p; // Validate arguments if (s == NULL || f == NULL) { return; } if (f->Me == false) { p = NewPack(); SiPackAddCreateHub(p, h); p = SiCallTask(f, p, "updatehub"); FreePack(p); } } // Send a ticket creation directive void SiCallCreateTicket(SERVER *s, FARM_MEMBER *f, char *hubname, char *username, char *realusername, POLICY *policy, UCHAR *ticket, UINT counter, char *groupname) { PACK *p; char name[MAX_SESSION_NAME_LEN + 1]; char hub_name_upper[MAX_SIZE]; char user_name_upper[MAX_USERNAME_LEN + 1]; char ticket_str[MAX_SIZE]; UINT point; // Validate arguments if (s == NULL || f == NULL || realusername == NULL || hubname == NULL || username == NULL || policy == NULL || ticket == NULL) { return; } if (groupname == NULL) { groupname = ""; } p = NewPack(); PackAddStr(p, "HubName", hubname); PackAddStr(p, "UserName", username); PackAddStr(p, "groupname", groupname); PackAddStr(p, "RealUserName", realusername); OutRpcPolicy(p, policy); PackAddData(p, "Ticket", ticket, SHA1_SIZE); BinToStr(ticket_str, sizeof(ticket_str), ticket, SHA1_SIZE); StrCpy(hub_name_upper, sizeof(hub_name_upper), hubname); StrUpper(hub_name_upper); StrCpy(user_name_upper, sizeof(user_name_upper), username); StrUpper(user_name_upper); Format(name, sizeof(name), "SID-%s-%u", user_name_upper, counter); PackAddStr(p, "SessionName", name); p = SiCallTask(f, p, "createticket"); SLog(s->Cedar, "LS_TICKET_1", f->hostname, hubname, username, realusername, name, ticket_str); point = PackGetInt(p, "Point"); if (point != 0) { f->Point = point; f->NumSessions++; } FreePack(p); } // Send a MAC address deletion directive void SiCallDeleteMacTable(SERVER *s, FARM_MEMBER *f, char *hubname, UINT key) { PACK *p; // Validate arguments if (s == NULL || f == NULL || hubname == NULL) { return; } p = NewPack(); PackAddStr(p, "HubName", hubname); PackAddInt(p, "Key", key); p = SiCallTask(f, p, "deletemactable"); FreePack(p); } // Send an IP address delete directive void SiCallDeleteIpTable(SERVER *s, FARM_MEMBER *f, char *hubname, UINT key) { PACK *p; // Validate arguments if (s == NULL || f == NULL || hubname == NULL) { return; } p = NewPack(); PackAddStr(p, "HubName", hubname); PackAddInt(p, "Key", key); p = SiCallTask(f, p, "deleteiptable"); FreePack(p); } // Send a session deletion directive void SiCallDeleteSession(SERVER *s, FARM_MEMBER *f, char *hubname, char *session_name) { PACK *p; // Validate arguments if (s == NULL || f == NULL || hubname == NULL || session_name == NULL) { return; } p = NewPack(); PackAddStr(p, "HubName", hubname); PackAddStr(p, "SessionName", session_name); p = SiCallTask(f, p, "deletesession"); FreePack(p); } // Send an IP table enumeration directive void SiCallEnumIpTable(SERVER *s, FARM_MEMBER *f, char *hubname, RPC_ENUM_IP_TABLE *t) { PACK *p; UINT i; // Validate arguments if (s == NULL || f == NULL || hubname == NULL || t == NULL) { return; } p = NewPack(); PackAddStr(p, "HubName", hubname); p = SiCallTask(f, p, "enumiptable"); Zero(t, sizeof(RPC_ENUM_IP_TABLE)); InRpcEnumIpTable(t, p); for (i = 0;i < t->NumIpTable;i++) { t->IpTables[i].RemoteItem = true; StrCpy(t->IpTables[i].RemoteHostname, sizeof(t->IpTables[i].RemoteHostname), f->hostname); } FreePack(p); } // Submit a MAC table enumeration directive void SiCallEnumMacTable(SERVER *s, FARM_MEMBER *f, char *hubname, RPC_ENUM_MAC_TABLE *t) { PACK *p; UINT i; // Validate arguments if (s == NULL || f == NULL || hubname == NULL || t == NULL) { return; } p = NewPack(); PackAddStr(p, "HubName", hubname); p = SiCallTask(f, p, "enummactable"); Zero(t, sizeof(RPC_ENUM_MAC_TABLE)); InRpcEnumMacTable(t, p); for (i = 0;i < t->NumMacTable;i++) { t->MacTables[i].RemoteItem = true; StrCpy(t->MacTables[i].RemoteHostname, sizeof(t->MacTables[i].RemoteHostname), f->hostname); } FreePack(p); } // Send a SecureNAT status acquisition directive void SiCallGetNatStatus(SERVER *s, FARM_MEMBER *f, char *hubname, RPC_NAT_STATUS *t) { PACK *p; // Validate arguments if (s == NULL || f == NULL || hubname == NULL || t == NULL) { return; } p = NewPack(); PackAddStr(p, "HubName", hubname); p = SiCallTask(f, p, "getnatstatus"); Zero(t, sizeof(RPC_NAT_STATUS)); InRpcNatStatus(t, p); FreePack(p); } // Submit a DHCP entry enumeration directive void SiCallEnumDhcp(SERVER *s, FARM_MEMBER *f, char *hubname, RPC_ENUM_DHCP *t) { PACK *p; // Validate arguments if (s == NULL || f == NULL || hubname == NULL || t == NULL) { return; } p = NewPack(); PackAddStr(p, "HubName", hubname); p = SiCallTask(f, p, "enumdhcp"); Zero(t, sizeof(RPC_ENUM_DHCP)); InRpcEnumDhcp(t, p); FreePack(p); } // Submit a NAT entry enumeration directive void SiCallEnumNat(SERVER *s, FARM_MEMBER *f, char *hubname, RPC_ENUM_NAT *t) { PACK *p; // Validate arguments if (s == NULL || f == NULL || hubname == NULL || t == NULL) { return; } p = NewPack(); PackAddStr(p, "HubName", hubname); p = SiCallTask(f, p, "enumnat"); Zero(t, sizeof(RPC_ENUM_NAT)); InRpcEnumNat(t, p); FreePack(p); } // Send a session enumeration directive void SiCallEnumSession(SERVER *s, FARM_MEMBER *f, char *hubname, RPC_ENUM_SESSION *t) { PACK *p; UINT i; // Validate arguments if (s == NULL || f == NULL || hubname == NULL || t == NULL) { return; } p = NewPack(); PackAddStr(p, "HubName", hubname); p = SiCallTask(f, p, "enumsession"); Zero(t, sizeof(RPC_ENUM_SESSION)); InRpcEnumSession(t, p); for (i = 0;i < t->NumSession;i++) { t->Sessions[i].RemoteSession = true; StrCpy(t->Sessions[i].RemoteHostname, sizeof(t->Sessions[i].RemoteHostname), f->hostname); } FreePack(p); } // Send a HUB creation directive void SiCallCreateHub(SERVER *s, FARM_MEMBER *f, HUB *h) { PACK *p; HUB_LIST *hh; // Validate arguments if (s == NULL || f == NULL) { return; } if (f->Me == false) { p = NewPack(); SiPackAddCreateHub(p, h); p = SiCallTask(f, p, "createhub"); FreePack(p); } hh = ZeroMalloc(sizeof(HUB_LIST)); hh->DynamicHub = (h->Type == HUB_TYPE_FARM_DYNAMIC ? true : false); StrCpy(hh->Name, sizeof(hh->Name), h->Name); hh->FarmMember = f; LockList(f->HubList); { bool exists = false; UINT i; for (i = 0;i < LIST_NUM(f->HubList);i++) { HUB_LIST *t = LIST_DATA(f->HubList, i); if (StrCmpi(t->Name, hh->Name) == 0) { exists = true; } } if (exists == false) { Add(f->HubList, hh); } else { Free(hh); } } UnlockList(f->HubList); } // Write the PACK for creating HUB void SiPackAddCreateHub(PACK *p, HUB *h) { UINT i; UINT max_session; SERVER *s; // Validate arguments if (p == NULL || h == NULL) { return; } s = h->Cedar->Server; if (s != NULL) { } PackAddStr(p, "HubName", h->Name); PackAddInt(p, "HubType", h->Type); max_session = h->Option->MaxSession; if (GetHubAdminOption(h, "max_sessions") != 0) { if (max_session == 0) { max_session = GetHubAdminOption(h, "max_sessions"); } else { UINT r = GetHubAdminOption(h, "max_sessions"); max_session = MIN(max_session, r); } } PackAddInt(p, "MaxSession", max_session); if (GetHubAdminOption(h, "max_sessions_client_bridge_apply") != 0 ) { PackAddInt(p, "MaxSessionClient", GetHubAdminOption(h, "max_sessions_client")); PackAddInt(p, "MaxSessionBridge", GetHubAdminOption(h, "max_sessions_bridge")); PackAddBool(p, "MaxSessionClientBridgeApply", true); } else { PackAddInt(p, "MaxSessionClient", INFINITE); PackAddInt(p, "MaxSessionBridge", INFINITE); } PackAddBool(p, "NoArpPolling", h->Option->NoArpPolling); PackAddBool(p, "NoIPv6AddrPolling", h->Option->NoIPv6AddrPolling); PackAddBool(p, "NoIpTable", h->Option->NoIpTable); PackAddBool(p, "NoEnum", h->Option->NoEnum); PackAddBool(p, "FilterPPPoE", h->Option->FilterPPPoE); PackAddBool(p, "YieldAfterStorePacket", h->Option->YieldAfterStorePacket); PackAddBool(p, "NoSpinLockForPacketDelay", h->Option->NoSpinLockForPacketDelay); PackAddInt(p, "BroadcastStormDetectionThreshold", h->Option->BroadcastStormDetectionThreshold); PackAddInt(p, "MaxLoggedPacketsPerMinute", h->Option->MaxLoggedPacketsPerMinute); PackAddInt(p, "FloodingSendQueueBufferQuota", h->Option->FloodingSendQueueBufferQuota); PackAddBool(p, "DoNotSaveHeavySecurityLogs", h->Option->DoNotSaveHeavySecurityLogs); PackAddBool(p, "DropBroadcastsInPrivacyFilterMode", h->Option->DropBroadcastsInPrivacyFilterMode); PackAddBool(p, "DropArpInPrivacyFilterMode", h->Option->DropArpInPrivacyFilterMode); PackAddBool(p, "SuppressClientUpdateNotification", h->Option->SuppressClientUpdateNotification); PackAddBool(p, "AssignVLanIdByRadiusAttribute", h->Option->AssignVLanIdByRadiusAttribute); PackAddInt(p, "ClientMinimumRequiredBuild", h->Option->ClientMinimumRequiredBuild); PackAddBool(p, "SecureNAT_RandomizeAssignIp", h->Option->SecureNAT_RandomizeAssignIp); PackAddBool(p, "NoPhysicalIPOnPacketLog", h->Option->NoPhysicalIPOnPacketLog); PackAddInt(p, "DetectDormantSessionInterval", h->Option->DetectDormantSessionInterval); PackAddBool(p, "FixForDLinkBPDU", h->Option->FixForDLinkBPDU); PackAddBool(p, "BroadcastLimiterStrictMode", h->Option->BroadcastLimiterStrictMode); PackAddBool(p, "NoLookBPDUBridgeId", h->Option->NoLookBPDUBridgeId); PackAddBool(p, "NoManageVlanId", h->Option->NoManageVlanId); PackAddInt(p, "VlanTypeId", h->Option->VlanTypeId); PackAddBool(p, "FilterOSPF", h->Option->FilterOSPF); PackAddBool(p, "FilterIPv4", h->Option->FilterIPv4); PackAddBool(p, "FilterIPv6", h->Option->FilterIPv6); PackAddBool(p, "FilterNonIP", h->Option->FilterNonIP); PackAddBool(p, "NoIPv4PacketLog", h->Option->NoIPv4PacketLog); PackAddBool(p, "NoIPv6PacketLog", h->Option->NoIPv6PacketLog); PackAddBool(p, "FilterBPDU", h->Option->FilterBPDU); PackAddBool(p, "NoIPv6DefaultRouterInRAWhenIPv6", h->Option->NoIPv6DefaultRouterInRAWhenIPv6); PackAddBool(p, "NoMacAddressLog", h->Option->NoMacAddressLog); PackAddBool(p, "ManageOnlyPrivateIP", h->Option->ManageOnlyPrivateIP); PackAddBool(p, "ManageOnlyLocalUnicastIPv6", h->Option->ManageOnlyLocalUnicastIPv6); PackAddBool(p, "DisableIPParsing", h->Option->DisableIPParsing); PackAddInt(p, "AdjustTcpMssValue", h->Option->AdjustTcpMssValue); PackAddBool(p, "DisableAdjustTcpMss", h->Option->DisableAdjustTcpMss); PackAddBool(p, "NoDhcpPacketLogOutsideHub", h->Option->NoDhcpPacketLogOutsideHub); PackAddBool(p, "DisableHttpParsing", h->Option->DisableHttpParsing); PackAddBool(p, "DisableUdpAcceleration", h->Option->DisableUdpAcceleration); PackAddBool(p, "DisableUdpFilterForLocalBridgeNic", h->Option->DisableUdpFilterForLocalBridgeNic); PackAddBool(p, "ApplyIPv4AccessListOnArpPacket", h->Option->ApplyIPv4AccessListOnArpPacket); PackAddBool(p, "RemoveDefGwOnDhcpForLocalhost", h->Option->RemoveDefGwOnDhcpForLocalhost); PackAddInt(p, "SecureNAT_MaxTcpSessionsPerIp", h->Option->SecureNAT_MaxTcpSessionsPerIp); PackAddInt(p, "SecureNAT_MaxTcpSynSentPerIp", h->Option->SecureNAT_MaxTcpSynSentPerIp); PackAddInt(p, "SecureNAT_MaxUdpSessionsPerIp", h->Option->SecureNAT_MaxUdpSessionsPerIp); PackAddInt(p, "SecureNAT_MaxDnsSessionsPerIp", h->Option->SecureNAT_MaxDnsSessionsPerIp); PackAddInt(p, "SecureNAT_MaxIcmpSessionsPerIp", h->Option->SecureNAT_MaxIcmpSessionsPerIp); PackAddInt(p, "AccessListIncludeFileCacheLifetime", h->Option->AccessListIncludeFileCacheLifetime); PackAddBool(p, "DisableKernelModeSecureNAT", h->Option->DisableKernelModeSecureNAT); PackAddBool(p, "DisableUserModeSecureNAT", h->Option->DisableUserModeSecureNAT); PackAddBool(p, "DisableCheckMacOnLocalBridge", h->Option->DisableCheckMacOnLocalBridge); PackAddBool(p, "DisableCorrectIpOffloadChecksum", h->Option->DisableCorrectIpOffloadChecksum); PackAddInt(p, "SavePacketLog", h->LogSetting.SavePacketLog); PackAddInt(p, "PacketLogSwitchType", h->LogSetting.PacketLogSwitchType); for (i = 0;i < NUM_PACKET_LOG;i++) { PackAddIntEx(p, "PacketLogConfig", h->LogSetting.PacketLogConfig[i], i, NUM_PACKET_LOG); } PackAddInt(p, "SaveSecurityLog", h->LogSetting.SaveSecurityLog); PackAddInt(p, "SecurityLogSwitchType", h->LogSetting.SecurityLogSwitchType); PackAddData(p, "HashedPassword", h->HashedPassword, SHA1_SIZE); PackAddData(p, "SecurePassword", h->SecurePassword, SHA1_SIZE); SiAccessListToPack(p, h->AccessList); if (h->EnableSecureNAT) { PackAddBool(p, "EnableSecureNAT", h->EnableSecureNAT); OutVhOption(p, h->SecureNATOption); } } // Setting of the HUB has been updated void SiHubUpdateProc(HUB *h) { SERVER *s; UINT i; // Validate arguments if (h == NULL || h->Cedar->Server == NULL || h->Cedar->Server->ServerType != SERVER_TYPE_FARM_CONTROLLER) { return; } s = h->Cedar->Server; if (s->FarmMemberList == NULL) { return; } if (h->LastVersion != h->CurrentVersion || h->CurrentVersion == 0) { LIST *fm_list; if (h->CurrentVersion == 0) { h->CurrentVersion = 1; } h->LastVersion = h->CurrentVersion; Debug("SiHubUpdateProc HUB=%s, Ver=%u, Type=%u, Offline=%u\n", h->Name, h->CurrentVersion, h->Type, h->Offline); fm_list = NewListFast(NULL); LockList(s->FarmMemberList); { while (true) { bool escape = true; // Update the HUB on all members for (i = 0;i < LIST_NUM(s->FarmMemberList);i++) { FARM_MEMBER *f = LIST_DATA(s->FarmMemberList, i); if (IsInList(fm_list, f) == false) { Add(fm_list, f); escape = false; if (f->Me == false) { SiCallUpdateHub(s, f, h); } break; } } if (escape) { break; } UnlockList(s->FarmMemberList); LockList(s->FarmMemberList); } } UnlockList(s->FarmMemberList); ReleaseList(fm_list); } if (h->Offline == false) { SiHubOnlineProc(h); } } // HUB turns to online void SiHubOnlineProc(HUB *h) { SERVER *s; UINT i; // Validate arguments if (h == NULL || h->Cedar->Server == NULL || h->Cedar->Server->ServerType != SERVER_TYPE_FARM_CONTROLLER) { // Process only on the farm controller return; } s = h->Cedar->Server; if (s->FarmMemberList == NULL) { return; } LockList(s->FarmMemberList); { if (h->Type == HUB_TYPE_FARM_STATIC) { // Static HUB // Create the HUB on all members for (i = 0;i < LIST_NUM(s->FarmMemberList);i++) { UINT j; bool exists = false; FARM_MEMBER *f = LIST_DATA(s->FarmMemberList, i); LockList(f->HubList); { for (j = 0;j < LIST_NUM(f->HubList);j++) { HUB_LIST *hh = LIST_DATA(f->HubList, j); if (StrCmpi(hh->Name, h->Name) == 0) { exists = true; } } } UnlockList(f->HubList); if (exists == false) { SiCallCreateHub(s, f, h); } } } } UnlockList(s->FarmMemberList); } // HUB turns to offline void SiHubOfflineProc(HUB *h) { SERVER *s; char hubname[MAX_HUBNAME_LEN + 1]; UINT i; LIST *fm_list; // Validate arguments if (h == NULL || h->Cedar->Server == NULL || h->Cedar->Server->ServerType != SERVER_TYPE_FARM_CONTROLLER) { // Process only on the farm controller return; } s = h->Cedar->Server; if (s->FarmMemberList == NULL) { return; } StrCpy(hubname, sizeof(hubname), h->Name); fm_list = NewListFast(NULL); LockList(s->FarmMemberList); { while (true) { bool escape = true; // Stop the HUB on all members for (i = 0;i < LIST_NUM(s->FarmMemberList);i++) { FARM_MEMBER *f = LIST_DATA(s->FarmMemberList, i); if (IsInList(fm_list, f) == false) { Add(fm_list, f); escape = false; SiCallDeleteHub(s, f, h); break; } } if (escape) { break; } UnlockList(s->FarmMemberList); LockList(s->FarmMemberList); } } UnlockList(s->FarmMemberList); ReleaseList(fm_list); } // Convert an access to PACK void SiAccessToPack(PACK *p, ACCESS *a, UINT i, UINT total) { // Validate arguments if (p == NULL || a == NULL) { return; } PackAddUniStrEx(p, "Note", a->Note, i, total); PackAddIntEx(p, "Active", a->Active, i, total); PackAddIntEx(p, "Priority", a->Priority, i, total); PackAddIntEx(p, "Discard", a->Discard, i, total); if (a->IsIPv6) { PackAddIp32Ex(p, "SrcIpAddress", 0xFDFFFFDF, i, total); PackAddIp32Ex(p, "SrcSubnetMask", 0xFFFFFFFF, i, total); PackAddIp32Ex(p, "DestIpAddress", 0xFDFFFFDF, i, total); PackAddIp32Ex(p, "DestSubnetMask", 0xFFFFFFFF, i, total); } else { PackAddIp32Ex(p, "SrcIpAddress", a->SrcIpAddress, i, total); PackAddIp32Ex(p, "SrcSubnetMask", a->SrcSubnetMask, i, total); PackAddIp32Ex(p, "DestIpAddress", a->DestIpAddress, i, total); PackAddIp32Ex(p, "DestSubnetMask", a->DestSubnetMask, i, total); } PackAddIntEx(p, "Protocol", a->Protocol, i, total); PackAddIntEx(p, "SrcPortStart", a->SrcPortStart, i, total); PackAddIntEx(p, "SrcPortEnd", a->SrcPortEnd, i, total); PackAddIntEx(p, "DestPortStart", a->DestPortStart, i, total); PackAddIntEx(p, "DestPortEnd", a->DestPortEnd, i, total); PackAddStrEx(p, "SrcUsername", a->SrcUsername, i, total); PackAddStrEx(p, "DestUsername", a->DestUsername, i, total); PackAddBoolEx(p, "CheckSrcMac", a->CheckSrcMac, i, total); PackAddDataEx(p, "SrcMacAddress", a->SrcMacAddress, sizeof(a->SrcMacAddress), i, total); PackAddDataEx(p, "SrcMacMask", a->SrcMacMask, sizeof(a->SrcMacMask), i, total); PackAddBoolEx(p, "CheckDstMac", a->CheckDstMac, i, total); PackAddDataEx(p, "DstMacAddress", a->DstMacAddress, sizeof(a->DstMacAddress), i, total); PackAddDataEx(p, "DstMacMask", a->DstMacMask, sizeof(a->DstMacMask), i, total); PackAddBoolEx(p, "CheckTcpState", a->CheckTcpState, i, total); PackAddBoolEx(p, "Established", a->Established, i, total); PackAddIntEx(p, "Delay", a->Delay, i, total); PackAddIntEx(p, "Jitter", a->Jitter, i, total); PackAddIntEx(p, "Loss", a->Loss, i, total); PackAddStrEx(p, "RedirectUrl", a->RedirectUrl, i, total); PackAddBoolEx(p, "IsIPv6", a->IsIPv6, i, total); if (a->IsIPv6) { PackAddIp6AddrEx(p, "SrcIpAddress6", &a->SrcIpAddress6, i, total); PackAddIp6AddrEx(p, "SrcSubnetMask6", &a->SrcSubnetMask6, i, total); PackAddIp6AddrEx(p, "DestIpAddress6", &a->DestIpAddress6, i, total); PackAddIp6AddrEx(p, "DestSubnetMask6", &a->DestSubnetMask6, i, total); } else { IPV6_ADDR zero; Zero(&zero, sizeof(zero)); PackAddIp6AddrEx(p, "SrcIpAddress6", &zero, i, total); PackAddIp6AddrEx(p, "SrcSubnetMask6", &zero, i, total); PackAddIp6AddrEx(p, "DestIpAddress6", &zero, i, total); PackAddIp6AddrEx(p, "DestSubnetMask6", &zero, i, total); } } // Get number of access contained in the PACK UINT SiNumAccessFromPack(PACK *p) { // Validate arguments if (p == NULL) { return 0; } return PackGetIndexCount(p, "Active"); } // Convert the PACK to access ACCESS *SiPackToAccess(PACK *p, UINT i) { ACCESS *a; // Validate arguments if (p == NULL) { return NULL; } a = ZeroMalloc(sizeof(ACCESS)); PackGetUniStrEx(p, "Note", a->Note, sizeof(a->Note), i); a->Active = PackGetIntEx(p, "Active", i); a->Priority = PackGetIntEx(p, "Priority", i); a->Discard = PackGetIntEx(p, "Discard", i); a->SrcIpAddress = PackGetIp32Ex(p, "SrcIpAddress", i); a->SrcSubnetMask = PackGetIp32Ex(p, "SrcSubnetMask", i); a->DestIpAddress = PackGetIp32Ex(p, "DestIpAddress", i); a->DestSubnetMask = PackGetIp32Ex(p, "DestSubnetMask", i); a->Protocol = PackGetIntEx(p, "Protocol", i); a->SrcPortStart = PackGetIntEx(p, "SrcPortStart", i); a->SrcPortEnd = PackGetIntEx(p, "SrcPortEnd", i); a->DestPortStart = PackGetIntEx(p, "DestPortStart", i); a->DestPortEnd = PackGetIntEx(p, "DestPortEnd", i); PackGetStrEx(p, "SrcUsername", a->SrcUsername, sizeof(a->SrcUsername), i); PackGetStrEx(p, "DestUsername", a->DestUsername, sizeof(a->DestUsername), i); a->CheckSrcMac = PackGetBoolEx(p, "CheckSrcMac", i); PackGetDataEx2(p, "SrcMacAddress", a->SrcMacAddress, sizeof(a->SrcMacAddress), i); PackGetDataEx2(p, "SrcMacMask", a->SrcMacMask, sizeof(a->SrcMacMask), i); a->CheckDstMac = PackGetBoolEx(p, "CheckDstMac", i); PackGetDataEx2(p, "DstMacAddress", a->DstMacAddress, sizeof(a->DstMacAddress), i); PackGetDataEx2(p, "DstMacMask", a->DstMacMask, sizeof(a->DstMacMask), i); a->CheckTcpState = PackGetBoolEx(p, "CheckTcpState", i); a->Established = PackGetBoolEx(p, "Established", i); a->Delay = PackGetIntEx(p, "Delay", i); a->Jitter = PackGetIntEx(p, "Jitter", i); a->Loss = PackGetIntEx(p, "Loss", i); a->IsIPv6 = PackGetBoolEx(p, "IsIPv6", i); PackGetStrEx(p, "RedirectUrl", a->RedirectUrl, sizeof(a->RedirectUrl), i); if (a->IsIPv6) { PackGetIp6AddrEx(p, "SrcIpAddress6", &a->SrcIpAddress6, i); PackGetIp6AddrEx(p, "SrcSubnetMask6", &a->SrcSubnetMask6, i); PackGetIp6AddrEx(p, "DestIpAddress6", &a->DestIpAddress6, i); PackGetIp6AddrEx(p, "DestSubnetMask6", &a->DestSubnetMask6, i); } return a; } // Convert the PACK to an access list void SiAccessListToPack(PACK *p, LIST *o) { // Validate arguments if (p == NULL || o == NULL) { return; } LockList(o); { UINT i; for (i = 0;i < LIST_NUM(o);i++) { ACCESS *a = LIST_DATA(o, i); SiAccessToPack(p, a, i, LIST_NUM(o)); } } UnlockList(o); } // Get the member that is hosting the specified HUB FARM_MEMBER *SiGetHubHostingMember(SERVER *s, HUB *h, bool admin_mode, CONNECTION *c) { FARM_MEMBER *ret = NULL; char name[MAX_SIZE]; UINT i; // Validate arguments if (s == NULL || h == NULL || c == NULL) { return NULL; } StrCpy(name, sizeof(name), h->Name); if (h->Type == HUB_TYPE_FARM_STATIC) { // It is good to select any member in the case of static HUB if (admin_mode == false) { ret = SiGetNextFarmMember(s, c, h); } else { UINT i; ret = NULL; for (i = 0;i < LIST_NUM(s->FarmMemberList);i++) { FARM_MEMBER *f = LIST_DATA(s->FarmMemberList, i); if (f->Me) { ret = f; break; } } } } else { // Examine whether there is a member that is hosting the HUB already in the case of dynamic HUB for (i = 0;i < LIST_NUM(s->FarmMemberList);i++) { FARM_MEMBER *f = LIST_DATA(s->FarmMemberList, i); HUB_LIST *hh, t; StrCpy(t.Name, sizeof(t.Name), name); LockList(f->HubList); { hh = Search(f->HubList, &t); if (hh != NULL) { // Found ret = f; } } UnlockList(f->HubList); } if (ret == NULL) { // Let host the new HUB FARM_MEMBER *f; // Select the member to host ret = SiGetNextFarmMember(s, c, h); f = ret; if (f != NULL) { // HUB creation directive SiAddHubCreateHistory(s, name); SiCallCreateHub(s, f, h); SiCallUpdateHub(s, f, h); } } } return ret; } // Task is called PACK *SiCalledTask(FARM_CONTROLLER *f, PACK *p, char *taskname) { PACK *ret; SERVER *s; // Validate arguments if (f == NULL || p == NULL || taskname == NULL) { return NULL; } ret = NULL; s = f->Server; if (StrCmpi(taskname, "noop") == 0) { // NO OPERATION ret = NewPack(); } else { Debug("Task Called: [%s].\n", taskname); if (StrCmpi(taskname, "createhub") == 0) { SiCalledCreateHub(s, p); ret = NewPack(); } else if (StrCmpi(taskname, "deletehub") == 0) { SiCalledDeleteHub(s, p); ret = NewPack(); } else if (StrCmpi(taskname, "enumhub") == 0) { ret = NewPack(); SiCalledEnumHub(s, ret, p); } else if (StrCmpi(taskname, "updatehub") == 0) { SiCalledUpdateHub(s, p); ret = NewPack(); } else if (StrCmpi(taskname, "createticket") == 0) { ret = SiCalledCreateTicket(s, p); } else if (StrCmpi(taskname, "enumnat") == 0) { ret = SiCalledEnumNat(s, p); } else if (StrCmpi(taskname, "enumdhcp") == 0) { ret = SiCalledEnumDhcp(s, p); } else if (StrCmpi(taskname, "getnatstatus") == 0) { ret = SiCalledGetNatStatus(s, p); } else if (StrCmpi(taskname, "enumsession") == 0) { ret = SiCalledEnumSession(s, p); } else if (StrCmpi(taskname, "deletesession") == 0) { SiCalledDeleteSession(s, p); ret = NewPack(); } else if (StrCmpi(taskname, "deletemactable") == 0) { SiCalledDeleteMacTable(s, p); ret = NewPack(); } else if (StrCmpi(taskname, "deleteiptable") == 0) { SiCalledDeleteIpTable(s, p); ret = NewPack(); } else if (StrCmpi(taskname, "enummactable") == 0) { ret = SiCalledEnumMacTable(s, p); } else if (StrCmpi(taskname, "enumiptable") == 0) { ret = SiCalledEnumIpTable(s, p); } else if (StrCmpi(taskname, "getsessionstatus") == 0) { ret = SiCalledGetSessionStatus(s, p); } else if (StrCmpi(taskname, "enumlogfilelist") == 0) { ret = SiCalledEnumLogFileList(s, p); } else if (StrCmpi(taskname, "readlogfile") == 0) { ret = SiCalledReadLogFile(s, p); } } return ret; } // Call the task (asynchronous) FARM_TASK *SiCallTaskAsyncBegin(FARM_MEMBER *f, PACK *p, char *taskname) { char tmp[MAX_PATH]; FARM_TASK *t; // Validate arguments if (f == NULL || p == NULL || taskname == NULL) { return NULL; } PackAddStr(p, "taskname", taskname); Debug("Call Async Task [%s] (%s)\n", taskname, f->hostname); Format(tmp, sizeof(tmp), "CLUSTER_CALL_ASYNC: Entering Call [%s] to %s", taskname, f->hostname); SiDebugLog(f->Cedar->Server, tmp); t = SiFarmServPostTask(f, p); StrCpy(t->TaskName, sizeof(t->TaskName), taskname); StrCpy(t->HostName, sizeof(t->HostName), f->hostname); t->FarmMember = f; return t; } // Get the results of the asynchronous task PACK *SiCallTaskAsyncEnd(CEDAR *c, FARM_TASK *t) { PACK *p; char taskname[MAX_PATH]; char hostname[MAX_PATH]; char tmp[MAX_SIZE]; // Validate arguments if (t == NULL || c == NULL) { return NULL; } StrCpy(taskname, sizeof(taskname), t->TaskName); StrCpy(hostname, sizeof(hostname), t->HostName); p = SiFarmServWaitTask(t); if (p == NULL) { Format(tmp, sizeof(tmp), "CLUSTER_CALL_ASYNC: Call ERROR [%s] to %s", taskname, hostname); SiDebugLog(c->Server, tmp); return NULL; } Format(tmp, sizeof(tmp), "CLUSTER_CALL_ASYNC: Retrieving Call Result [%s] to %s", taskname, hostname); SiDebugLog(c->Server, tmp); return p; } // Call the task PACK *SiCallTask(FARM_MEMBER *f, PACK *p, char *taskname) { PACK *ret; char tmp[MAX_PATH]; // Validate arguments if (f == NULL || p == NULL || taskname == NULL) { return NULL; } PackAddStr(p, "taskname", taskname); Debug("Call Task [%s] (%s)\n", taskname, f->hostname); Format(tmp, sizeof(tmp), "CLUSTER_CALL: Entering Call [%s] to %s", taskname, f->hostname); SiDebugLog(f->Cedar->Server, tmp); ret = SiExecTask(f, p); Format(tmp, sizeof(tmp), "CLUSTER_CALL: Leaving Call [%s] to %s", taskname, f->hostname); SiDebugLog(f->Cedar->Server, tmp); return ret; } // Task listening procedure (Main Process) void SiAcceptTasksFromControllerMain(FARM_CONTROLLER *f, SOCK *sock) { PACK *request; PACK *response; char taskname[MAX_SIZE]; // Validate arguments if (f == NULL || sock == NULL) { return; } f->IsConnected = true; while (true) { bool ret; // Receive the PACK request = HttpClientRecv(sock); if (request == NULL) { // Disconnect break; } response = NULL; // Get the name if (PackGetStr(request, "taskname", taskname, sizeof(taskname))) { Lock(f->Server->TasksFromFarmControllerLock); { response = SiCalledTask(f, request, taskname); } Unlock(f->Server->TasksFromFarmControllerLock); } FreePack(request); // Return a response if (response == NULL) { response = NewPack(); } else { PackAddInt(response, "succeed", 1); } ret = HttpClientSend(sock, response); FreePack(response); if (ret == false) { // Disconnect break; } } f->IsConnected = false; } // Task waiting procedure void SiAcceptTasksFromController(FARM_CONTROLLER *f, SOCK *sock) { UINT i; HUB **hubs; UINT num_hubs; CEDAR *c; SERVER *s; // Validate arguments if (f == NULL || sock == NULL) { return; } s = f->Server; c = s->Cedar; // Main process SiAcceptTasksFromControllerMain(f, sock); // Stop all Virtual HUBs since the connection to the controller is disconnected LockList(c->HubList); { hubs = ToArray(c->HubList); num_hubs = LIST_NUM(c->HubList); for (i = 0;i < num_hubs;i++) { AddRef(hubs[i]->ref); } } UnlockList(c->HubList); for (i = 0;i < num_hubs;i++) { SetHubOffline(hubs[i]); DelHub(c, hubs[i]); ReleaseHub(hubs[i]); } Free(hubs); } // Execute the task PACK *SiExecTask(FARM_MEMBER *f, PACK *p) { FARM_TASK *t; // Validate arguments if (f == NULL || p == NULL) { return NULL; } t = SiFarmServPostTask(f, p); if (t == NULL) { return NULL; } return SiFarmServWaitTask(t); } // Task queuing FARM_TASK *SiFarmServPostTask(FARM_MEMBER *f, PACK *request) { FARM_TASK *t; // Validate arguments if (f == NULL || request == NULL) { return NULL; } t = ZeroMalloc(sizeof(FARM_TASK)); t->CompleteEvent = NewEvent(); t->Request = request; LockQueue(f->TaskQueue); { if (f->Halting) { // Halting (failure) UnlockQueue(f->TaskQueue); ReleaseEvent(t->CompleteEvent); Free(t); return NULL; } InsertQueue(f->TaskQueue, t); } UnlockQueue(f->TaskQueue); Set(f->TaskPostEvent); return t; } // Wait for task results PACK *SiFarmServWaitTask(FARM_TASK *t) { PACK *response; // Validate arguments if (t == NULL) { return NULL; } Wait(t->CompleteEvent, INFINITE); ReleaseEvent(t->CompleteEvent); FreePack(t->Request); response = t->Response; Free(t); if (PackGetInt(response, "succeed") == 0) { // Task calling fails for any reason FreePack(response); return NULL; } return response; } // Server farm processing main void SiFarmServMain(SERVER *server, SOCK *sock, FARM_MEMBER *f) { UINT wait_time = SERVER_CONTROL_TCP_TIMEOUT / 2; bool send_noop = false; UINT i; CEDAR *c; // Validate arguments if (server == NULL || sock == NULL || f == NULL) { Debug("SiFarmServMain Failed.\n"); return; } Debug("SiFarmServMain Started.\n"); c = server->Cedar; // Send a directive to create all static HUBs at the stage // where the members have been connected to the controller LockList(c->HubList); { for (i = 0;i < LIST_NUM(c->HubList);i++) { HUB *h = LIST_DATA(c->HubList, i); if (h->Offline == false) { if (h->Type == HUB_TYPE_FARM_STATIC) { PACK *p; HUB_LIST *hh; p = NewPack(); SiPackAddCreateHub(p, h); PackAddStr(p, "taskname", "createhub"); HttpServerSend(sock, p); FreePack(p); p = HttpServerRecv(sock); FreePack(p); p = NewPack(); SiPackAddCreateHub(p, h); PackAddStr(p, "taskname", "updatehub"); HttpServerSend(sock, p); FreePack(p); p = HttpServerRecv(sock); FreePack(p); hh = ZeroMalloc(sizeof(HUB_LIST)); hh->DynamicHub = false; hh->FarmMember = f; StrCpy(hh->Name, sizeof(hh->Name), h->Name); LockList(f->HubList); { Add(f->HubList, hh); } UnlockList(f->HubList); } } } } UnlockList(c->HubList); Debug("SiFarmServMain: while (true)\n"); while (true) { FARM_TASK *t; UINT64 tick; do { // Check whether a new task arrived LockQueue(f->TaskQueue); { t = GetNext(f->TaskQueue); } UnlockQueue(f->TaskQueue); if (t != NULL) { // Handle this task PACK *p = t->Request; bool ret; // Transmission ret = HttpServerSend(sock, p); send_noop = false; if (ret == false) { // Disconnected // Cancel this task Set(t->CompleteEvent); goto DISCONNECTED; } // Receive p = HttpServerRecv(sock); t->Response = p; Set(t->CompleteEvent); send_noop = false; } } while (t != NULL); if (send_noop) { // Send a NOOP PACK *p; bool ret; p = NewPack(); PackAddStr(p, "taskname", "noop"); ret = HttpServerSend(sock, p); FreePack(p); if (ret == false) { goto DISCONNECTED; } p = HttpServerRecv(sock); if (p == NULL) { goto DISCONNECTED; } FreePack(p); } tick = Tick64(); while (true) { bool break_flag; if ((tick + wait_time) <= Tick64()) { break; } Wait(f->TaskPostEvent, 250); break_flag = false; LockQueue(f->TaskQueue); { if (f->TaskQueue->num_item != 0) { break_flag = true; } } UnlockQueue(f->TaskQueue); if (break_flag || f->Halting || server->Halt) { break; } } send_noop = true; } DISCONNECTED: Debug("SiFarmServMain: DISCONNECTED\n"); f->Halting = true; // Cancel all outstanding tasks LockQueue(f->TaskQueue); { FARM_TASK *t; while (t = GetNext(f->TaskQueue)) { Set(t->CompleteEvent); } } UnlockQueue(f->TaskQueue); } // Farm server function that handles the connection from farm members void SiFarmServ(SERVER *server, SOCK *sock, X *cert, UINT ip, UINT num_port, UINT *ports, char *hostname, UINT point, UINT weight, UINT max_sessions) { PACK *p; FARM_MEMBER *f; UINT i; char tmp[MAX_SIZE]; // Validate arguments if (server == NULL || sock == NULL || cert == NULL || num_port == 0 || ports == NULL || hostname == NULL) { return; } if (weight == 0) { weight = FARM_DEFAULT_WEIGHT; } if (max_sessions == 0) { max_sessions = SERVER_MAX_SESSIONS; } if (ip == 0) { // If the public IP address is not specified, specify the connection // source IP address of this farm member server ip = IPToUINT(&sock->RemoteIP); } IPToStr32(tmp, sizeof(tmp), ip); SLog(server->Cedar, "LS_FARM_SERV_START", tmp, hostname); // Inform the success p = NewPack(); HttpServerSend(sock, p); FreePack(p); IPToStr32(tmp, sizeof(tmp), ip); Debug("Farm Member %s Connected. IP: %s\n", hostname, tmp); SetTimeout(sock, SERVER_CONTROL_TCP_TIMEOUT); f = ZeroMalloc(sizeof(FARM_MEMBER)); f->Cedar = server->Cedar; f->Ip = ip; f->NumPort = num_port; f->Ports = ports; StrCpy(f->hostname, sizeof(f->hostname), hostname); f->ServerCert = cert; f->ConnectedTime = SystemTime64(); f->Weight = weight; f->MaxSessions = max_sessions; f->HubList = NewList(CompareHubList); f->Point = point; f->TaskQueue = NewQueue(); f->TaskPostEvent = NewEvent(); // Add to the list LockList(server->FarmMemberList); { Add(server->FarmMemberList, f); } UnlockList(server->FarmMemberList); // Main process SiFarmServMain(server, sock, f); // Remove from the list LockList(server->FarmMemberList); { Delete(server->FarmMemberList, f); } UnlockList(server->FarmMemberList); ReleaseQueue(f->TaskQueue); ReleaseEvent(f->TaskPostEvent); for (i = 0;i < LIST_NUM(f->HubList);i++) { HUB_LIST *hh = LIST_DATA(f->HubList, i); Free(hh); } ReleaseList(f->HubList); Free(f); SLog(server->Cedar, "LS_FARM_SERV_END", hostname); } // Search in HUB list int CompareHubList(void *p1, void *p2) { HUB_LIST *h1, *h2; if (p1 == NULL || p2 == NULL) { return 0; } h1 = *(HUB_LIST **)p1; h2 = *(HUB_LIST **)p2; if (h1 == NULL || h2 == NULL) { return 0; } return StrCmpi(h1->Name, h2->Name); } // Connection thread to the controller void SiConnectToControllerThread(THREAD *thread, void *param) { FARM_CONTROLLER *f; SESSION *s; CONNECTION *c; SERVER *server; bool first_failed; // Validate arguments if (thread == NULL || param == NULL) { return; } #ifdef OS_WIN32 MsSetThreadPriorityRealtime(); #endif // OS_WIN32 f = (FARM_CONTROLLER *)param; f->Thread = thread; AddRef(f->Thread->ref); NoticeThreadInit(thread); f->StartedTime = SystemTime64(); server = f->Server; f->StartedTime = SystemTime64(); SLog(server->Cedar, "LS_FARM_CONNECT_1", server->ControllerName); first_failed = true; while (true) { // Attempt to connect CLIENT_OPTION o; f->LastError = ERR_TRYING_TO_CONNECT; Zero(&o, sizeof(CLIENT_OPTION)); StrCpy(o.Hostname, sizeof(o.Hostname), server->ControllerName); o.Port = server->ControllerPort; f->NumTry++; Debug("Try to Connect %s (Controller).\n", server->ControllerName); s = NewRpcSessionEx(server->Cedar, &o, NULL, CEDAR_SERVER_FARM_STR); if (s != NULL) { // Connection success: send the authentication data PACK *p = NewPack(); UCHAR secure_password[SHA1_SIZE]; BUF *b; c = s->Connection; Lock(f->lock); { f->Sock = c->FirstSock; AddRef(f->Sock->ref); SetTimeout(f->Sock, SERVER_CONTROL_TCP_TIMEOUT); } Unlock(f->lock); // Method PackAddStr(p, "method", "farm_connect"); PackAddClientVersion(p, s->Connection); // Password SecurePassword(secure_password, server->MemberPassword, s->Connection->Random); PackAddData(p, "SecurePassword", secure_password, sizeof(secure_password)); Lock(server->Cedar->lock); { b = XToBuf(server->Cedar->ServerX, false); } Unlock(server->Cedar->lock); if (b != NULL) { char tmp[MAX_SIZE]; bool ret; UINT i; // Server certificate PackAddBuf(p, "ServerCert", b); FreeBuf(b); // Maximum number of sessions PackAddInt(p, "MaxSessions", GetServerCapsInt(server, "i_max_sessions")); // Point PackAddInt(p, "Point", SiGetPoint(server)); PackAddInt(p, "Weight", server->Weight); // Host name GetMachineName(tmp, sizeof(tmp)); PackAddStr(p, "HostName", tmp); // Public IP PackAddIp32(p, "PublicIp", server->PublicIp); // Public port for (i = 0;i < server->NumPublicPort;i++) { PackAddIntEx(p, "PublicPort", server->PublicPorts[i], i, server->NumPublicPort); } ret = HttpClientSend(c->FirstSock, p); if (ret) { PACK *p; UINT err = ERR_PROTOCOL_ERROR; first_failed = true; p = HttpClientRecv(c->FirstSock); if (p != NULL && (err = GetErrorFromPack(p)) == 0) { // Successful connection SLog(server->Cedar, "LS_FARM_START"); f->CurrentConnectedTime = SystemTime64(); if (f->FirstConnectedTime == 0) { f->FirstConnectedTime = SystemTime64(); } f->NumConnected++; Debug("Connect Succeed.\n"); f->Online = true; // Main process SiAcceptTasksFromController(f, c->FirstSock); f->Online = false; } else { // Error f->LastError = err; SLog(server->Cedar, "LS_FARM_CONNECT_2", server->ControllerName, GetUniErrorStr(err), err); } FreePack(p); } else { f->LastError = ERR_DISCONNECTED; if (first_failed) { SLog(server->Cedar, "LS_FARM_CONNECT_3", server->ControllerName, RETRY_CONNECT_TO_CONTROLLER_INTERVAL / 1000); first_failed = false; } } } FreePack(p); // Disconnect Lock(f->lock); { if (f->Sock != NULL) { ReleaseSock(f->Sock); f->Sock = NULL; } } Unlock(f->lock); ReleaseSession(s); s = NULL; if (f->LastError == ERR_TRYING_TO_CONNECT) { f->LastError = ERR_DISCONNECTED; } } else { // Connection failure f->LastError = ERR_CONNECT_TO_FARM_CONTROLLER; if (first_failed) { SLog(server->Cedar, "LS_FARM_CONNECT_3", server->ControllerName, RETRY_CONNECT_TO_CONTROLLER_INTERVAL / 1000); first_failed = false; } } Debug("Controller Disconnected. ERROR = %S\n", _E(f->LastError)); f->NumFailed = f->NumTry - f->NumConnected; // Wait for event Wait(f->HaltEvent, RETRY_CONNECT_TO_CONTROLLER_INTERVAL); if (f->Halt) { // Halting flag break; } } SLog(server->Cedar, "LS_FARM_DISCONNECT"); } // Disconnect the connection to the controller void SiStopConnectToController(FARM_CONTROLLER *f) { // Validate arguments if (f == NULL) { return; } f->Halt = true; // Stop the connection Lock(f->lock); { Disconnect(f->Sock); } Unlock(f->lock); Set(f->HaltEvent); // Wait for the thread termination WaitThread(f->Thread, INFINITE); ReleaseThread(f->Thread); DeleteLock(f->lock); ReleaseEvent(f->HaltEvent); Free(f); } // Start a connection to the controller FARM_CONTROLLER *SiStartConnectToController(SERVER *s) { FARM_CONTROLLER *f; THREAD *t; // Validate arguments if (s == NULL) { return NULL; } f = ZeroMalloc(sizeof(FARM_CONTROLLER)); f->Server = s; f->LastError = ERR_TRYING_TO_CONNECT; f->HaltEvent = NewEvent(); f->lock = NewLock(); t = NewThread(SiConnectToControllerThread, f); WaitThreadInit(t); ReleaseThread(t); return f; } // Get the current version void SiGetCurrentRegion(CEDAR *c, char *region, UINT region_size) { ClearStr(region, region_size); // Validate arguments if (c == NULL || region == NULL) { return; } Lock(c->CurrentRegionLock); { StrCpy(region, region_size, c->CurrentRegion); } Unlock(c->CurrentRegionLock); if (IsEmptyStr(region)) { if (GetCurrentLangId() == SE_LANG_JAPANESE) { StrCpy(region, region_size, "JP"); } else if (GetCurrentLangId() == SE_LANG_CHINESE_ZH) { StrCpy(region, region_size, "CN"); } } } // Check the current region bool SiCheckCurrentRegion(CEDAR *c, char *r) { char tmp[64]; // Validate arguments if (c == NULL || r == NULL) { return false; } SiGetCurrentRegion(c, tmp, sizeof(tmp)); return (StrCmpi(r, tmp) == 0); } // Check whether some enterprise functions are restricted // // ** Hints by Daiyuu Nobori, written on March 19, 2014 ** // // The following 'enterprise functions' are implemented on SoftEther VPN Server // since March 19, 2014. However, these functions are disabled on // SoftEther VPN Servers which run in Japan and China. // // - RADIUS / NT Domain user authentication // - RSA certificate authentication // - Deep-inspect packet logging // - Source IP address control list // - syslog transfer // // The SoftEther VPN Project intentionally disables these functions for users // in Japan and China. The reason is: Daiyuu Nobori, the chief author of // SoftEther VPN, has been liable to observe the existing agreements and // restrictions between him and some companies. The agreements have regulated // the region-limited restriction to implement and distribute the above // enterprise functions on the SoftEther VPN open-source program. // // Therefore, the SoftEther VPN Project distributes the binary program and // the source code with the "SiIsEnterpriseFunctionsRestrictedOnOpenSource" // function. This function identifies whether the SoftEther VPN Server // program is running in either Japan or China. If the restricted region is // detected, then the above enterprise functions will be disabled. // // Please note that the above restriction has been imposed only on the // original binaries and source codes from the SoftEther VPN Project. // Anyone, except Daiyuu Nobori, who understands and writes the C language // program can remove this restriction at his own risk. // bool SiIsEnterpriseFunctionsRestrictedOnOpenSource(CEDAR *c) { char region[128]; bool ret = false; // Validate arguments if (c == NULL) { return false; } SiGetCurrentRegion(c, region, sizeof(region)); if (StrCmpi(region, "JP") == 0 || StrCmpi(region, "CN") == 0) { ret = true; } return ret; } // Update the current region void SiUpdateCurrentRegion(CEDAR *c, char *region, bool force_update) { bool changed = false; // Validate arguments if (c == NULL) { return; } if (IsEmptyStr(region) == false) { Lock(c->CurrentRegionLock); { if (StrCmpi(c->CurrentRegion, region) != 0) { StrCpy(c->CurrentRegion, sizeof(c->CurrentRegion), region); changed = true; } } Unlock(c->CurrentRegionLock); } if (force_update) { changed = true; } if (changed) { FlushServerCaps(c->Server); } } // Create a server SERVER *SiNewServer(bool bridge) { return SiNewServerEx(bridge, false, false); } SERVER *SiNewServerEx(bool bridge, bool in_client_inner_server, bool relay_server) { SERVER *s; LISTENER *inproc; LISTENER *azure; LISTENER *rudp; SetGetIpThreadMaxNum(DEFAULT_GETIP_THREAD_MAX_NUM); s = ZeroMalloc(sizeof(SERVER)); SetEraserCheckInterval(0); SiInitHubCreateHistory(s); InitServerCapsCache(s); Rand(s->MyRandomKey, sizeof(s->MyRandomKey)); s->lock = NewLock(); s->OpenVpnSstpConfigLock = NewLock(); s->SaveCfgLock = NewLock(); s->ref = NewRef(); s->Cedar = NewCedar(NULL, NULL); s->Cedar->Server = s; #ifdef OS_WIN32 s->IsInVm = MsIsInVm(); #else // OS_WIN32 s->IsInVm = UnixIsInVm(); #endif // OS_WIN32 #ifdef ENABLE_AZURE_SERVER if (IsFileExists("@azureserver.config")) { DisableRDUPServerGlobally(); s->AzureServer = NewAzureServer(s->Cedar); SleepThread(500); } #endif // ENABLE_AZURE_SERVER s->Cedar->CheckExpires = true; s->ServerListenerList = NewList(CompareServerListener); s->StartTime = SystemTime64(); s->Syslog = NewSysLog(NULL, 0); s->SyslogLock = NewLock(); s->TasksFromFarmControllerLock = NewLock(); if (bridge) { SetCedarVpnBridge(s->Cedar); } #ifdef OS_WIN32 if (IsHamMode() == false) { RegistWindowsFirewallAll(); } #endif s->Keep = StartKeep(); // Log related MakeDir(bridge == false ? SERVER_LOG_DIR_NAME : BRIDGE_LOG_DIR_NAME); s->Logger = NewLog(bridge == false ? SERVER_LOG_DIR_NAME : BRIDGE_LOG_DIR_NAME, SERVER_LOG_PERFIX, LOG_SWITCH_DAY); SLog(s->Cedar, "L_LINE"); SLog(s->Cedar, "LS_START_2", s->Cedar->ServerStr, s->Cedar->VerString); SLog(s->Cedar, "LS_START_3", s->Cedar->BuildInfo); SLog(s->Cedar, "LS_START_UTF8"); SLog(s->Cedar, "LS_START_1"); // Initialize the configuration SiInitConfiguration(s); SetFifoCurrentReallocMemSize(MEM_FIFO_REALLOC_MEM_SIZE); if (s->DisableIntelAesAcceleration) { // Disable the Intel AES acceleration DisableIntelAesAccel(); } // Raise the priority if (s->NoHighPriorityProcess == false) { OSSetHighPriority(); } #ifdef OS_UNIX UnixSetHighOomScore(); #endif // OS_UNIX if (s->ServerType == SERVER_TYPE_FARM_MEMBER) { // Start a connection to the controller s->FarmController = SiStartConnectToController(s); } else if (s->ServerType == SERVER_TYPE_FARM_CONTROLLER) { FARM_MEMBER *f; // Start operating as a controller s->FarmMemberList = NewList(NULL); f = ZeroMalloc(sizeof(FARM_MEMBER)); f->Cedar = s->Cedar; GetMachineName(f->hostname, sizeof(f->hostname)); f->Me = true; f->HubList = NewList(CompareHubList); f->Weight = s->Weight; s->Me = f; Add(s->FarmMemberList, f); SiStartFarmControl(s); s->FarmControllerInited = true; } // Start a in-processlistener inproc = NewListener(s->Cedar, LISTENER_INPROC, 0); ReleaseListener(inproc); // Start a listener for Azure if (s->AzureClient != NULL) { azure = NewListener(s->Cedar, LISTENER_REVERSE, 0); ReleaseListener(azure); } // Start a R-UDP listener if (s->DisableNatTraversal == false && s->Cedar->Bridge == false) { rudp = NewListenerEx4(s->Cedar, LISTENER_RUDP, 0, TCPAcceptedThread, NULL, false, false, &s->NatTGlobalUdpPort, RAND_PORT_ID_SERVER_LISTEN); ReleaseListener(rudp); } // Start a VPN-over-ICMP listener s->DynListenerIcmp = NewDynamicListener(s->Cedar, &s->EnableVpnOverIcmp, LISTENER_ICMP, 0); // Start a VPN-over-DNS listener s->DynListenerDns = NewDynamicListener(s->Cedar, &s->EnableVpnOverDns, LISTENER_DNS, 53); SiInitDeadLockCheck(s); SiUpdateCurrentRegion(s->Cedar, "", true); return s; } // Developed by SoftEther VPN Project at University of Tsukuba in Japan. // Department of Computer Science has dozens of overly-enthusiastic geeks. // Join us: http://www.tsukuba.ac.jp/english/admission/
774085.c
/* * lib/version.c Run-time version information * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation version 2.1 * of the License. * * Copyright (c) 2003-2012 Thomas Graf <[email protected]> */ /** * @ingroup core * @defgroup utils Utilities * * Run-time version information * * @{ */ /** * @name Run-time version information * @{ */ #include <netlink/version.h> const int nl_ver_num = LIBNL_VER_NUM; const int nl_ver_maj = LIBNL_VER_MAJ; const int nl_ver_min = LIBNL_VER_MIN; const int nl_ver_mic = LIBNL_VER_MIC; /** @} */ /** @} */
840061.c
/* THIS SAMPLE CODE IS PROVIDED AS IS AND IS SUBJECT TO ALTERATIONS. FUJITSU */ /* MICROELECTRONICS ACCEPTS NO RESPONSIBILITY OR LIABILITY FOR ANY ERRORS OR */ /* ELIGIBILITY FOR ANY PURPOSES. */ /* (C) Fujitsu Microelectronics Europe GmbH */ /*------------------------------------------------------------------------ watchdog.c - This file contains the function deefinition for hardware watchdog. -------------------------------------------------------------------------*/ #include "mb96348hs.h" #include "FreeRTOS.h" #include "task.h" #include "watchdog.h" /*--------------------------------------------------------------------------- * Setup Watchdog *---------------------------------------------------------------------------*/ #if WATCHDOG != WTC_NONE void InitWatchdog( void ) { WDTC_WTI = WTC_PER_2_23; /* 2^23/CLKWT */ WDTC_WTCS = WTC_CLKMC; /* CLKWT=CLKMC, Watchdog expiration delay = 2.097s @ 4MHZ CLKMC*/ WDTCP = 0x00; /* Activate Watchdog, Clear Pattern 0x00 */ } #endif /*--------------------------------------------------------------------------- * The below task clears the watchdog and blocks itself for WTC_CLR_PER ticks. *---------------------------------------------------------------------------*/ #if WATCHDOG == WTC_IN_TASK static void prvWatchdogTask( void *pvParameters ) { const TickType_t xFrequency = WTC_CLR_PER; TickType_t xLastWakeTime; ( void ) pvParameters; /* Get currrent tick count */ xLastWakeTime = xTaskGetTickCount(); for( ;; ) { /* Get currrent tick count */ xLastWakeTime = xTaskGetTickCount(); Kick_Watchdog(); /* Block the task for WTC_CLR_PER ticks (1s) at watchdog overflow period of WTC_PER_2_23 CLKMC cycles */ vTaskDelayUntil( &xLastWakeTime, xFrequency ); } } #endif /*--------------------------------------------------------------------------- * The below function creates hardware watchdog task. *---------------------------------------------------------------------------*/ #if WATCHDOG == WTC_IN_TASK void vStartWatchdogTask( unsigned portBASE_TYPE uxPriority ) { xTaskCreate( prvWatchdogTask, "KickWTC", portMINIMAL_STACK_SIZE, ( void * ) NULL, uxPriority, ( TaskHandle_t * ) NULL ); } #endif
314167.c
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <stdatomic.h> static volatile atomic_llong total; struct worker_context { int repeat; }; void * Worker(void * ctxt) { struct worker_context * context; context = (struct worker_context *) ctxt; for (int i = 0; i < context->repeat; ++i) { for (int j = 1; j <= 1000000; ++j) { atomic_fetch_add(&total, j); } } pthread_exit(NULL); } int main(int argc, char * argv[]) { if (argc != 2) { fprintf(stderr, "Error: Must be called with number of threads.\n"); exit(EXIT_FAILURE); } int N = atoi(argv[1]); int repeat = 10000; int repetitions_per_thread = repeat / N; int excess = repeat % N; pthread_t threads[N]; struct worker_context thread_contexts[N]; for (int n = 0; n < N; ++n) { thread_contexts[n].repeat = repetitions_per_thread + (n < excess ? 1 : 0); int e = pthread_create(&threads[n], NULL, Worker, (void *) &thread_contexts[n]); if (e) { fprintf(stderr, "Error: Could not create threads.\n%i\n", e); exit(EXIT_FAILURE); } } void * status; for (int n = 0; n < N; ++n) { int e = pthread_join(threads[n], &status); if (e) { fprintf(stderr, "Error: Could not join threads.\n"); exit(EXIT_FAILURE); } } printf("%lli\n", total); return EXIT_SUCCESS; }
333621.c
/** ****************************************************************************** * @file usb_prop.c * @author MCD Application Team * @version V4.0.0 * @date 21-January-2013 * @brief All processings related to Custom HID Demo ****************************************************************************** * @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 "usb_lib.h" #include "usb_conf.h" #include "usb_prop.h" #include "usb_desc.h" #include "usb_pwr.h" #include "feature_report.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ typedef enum _HID_REPORTS { HID_INPUT = 1, HID_OUTPUT = 2, HID_FEATURE = 3 } HID_REPORTS; /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ uint32_t ProtocolValue; __IO uint8_t EXTI_Enable; __IO uint8_t Request = 0; uint8_t Report_Buf[2]; /* -------------------------------------------------------------------------- */ /* Structures initializations */ /* -------------------------------------------------------------------------- */ DEVICE Device_Table = { EP_NUM, 1 }; DEVICE_PROP Device_Property = { CustomHID_init, CustomHID_Reset, CustomHID_Status_In, CustomHID_Status_Out, CustomHID_Data_Setup, CustomHID_NoData_Setup, CustomHID_Get_Interface_Setting, CustomHID_GetDeviceDescriptor, CustomHID_GetConfigDescriptor, CustomHID_GetStringDescriptor, 0, 0x40 /*MAX PACKET SIZE*/ }; USER_STANDARD_REQUESTS User_Standard_Requests = { CustomHID_GetConfiguration, CustomHID_SetConfiguration, CustomHID_GetInterface, CustomHID_SetInterface, CustomHID_GetStatus, CustomHID_ClearFeature, CustomHID_SetEndPointFeature, CustomHID_SetDeviceFeature, CustomHID_SetDeviceAddress }; ONE_DESCRIPTOR Device_Descriptor = { (uint8_t*)CustomHID_DeviceDescriptor, CUSTOMHID_SIZ_DEVICE_DESC }; ONE_DESCRIPTOR Config_Descriptor = { (uint8_t*)CustomHID_ConfigDescriptor, CUSTOMHID_SIZ_CONFIG_DESC }; ONE_DESCRIPTOR CustomHID_Report_Descriptor = { (uint8_t *)CustomHID_ReportDescriptor, CUSTOMHID_SIZ_REPORT_DESC }; ONE_DESCRIPTOR CustomHID_Hid_Descriptor = { (uint8_t*)CustomHID_ConfigDescriptor + CUSTOMHID_OFF_HID_DESC, CUSTOMHID_SIZ_HID_DESC }; ONE_DESCRIPTOR String_Descriptor[4] = { {(uint8_t*)CustomHID_StringLangID, CUSTOMHID_SIZ_STRING_LANGID}, {(uint8_t*)CustomHID_StringVendor, CUSTOMHID_SIZ_STRING_VENDOR}, {(uint8_t*)CustomHID_StringProduct, CUSTOMHID_SIZ_STRING_PRODUCT}, {(uint8_t*)CustomHID_StringSerial, CUSTOMHID_SIZ_STRING_SERIAL} }; /* Extern variables ----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /*CustomHID_SetReport_Feature function prototypes*/ uint8_t *CustomHID_SetReport_Feature(uint16_t Length); /*CustomHID_GetReport_Feature function prototypes*/ uint8_t *CustomHID_GetReport_Feature(uint16_t Length); /* Extern function prototypes ------------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /******************************************************************************* * Function Name : CustomHID_init. * Description : Custom HID init routine. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void CustomHID_init(void) { /* Update the serial number string descriptor with the unique ID */ uuid_get((char *)CustomHID_StringSerial + 2, CUSTOMHID_SIZ_STRING_SERIAL, 1); pInformation->Current_Configuration = 0; /* Connect the device */ PowerOn(); /* Perform basic device initialization operations */ USB_SIL_Init(); bDeviceState = UNCONNECTED; } /******************************************************************************* * Function Name : CustomHID_Reset. * Description : Custom HID reset routine. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void CustomHID_Reset(void) { /* Set CustomHID_DEVICE as not configured */ pInformation->Current_Configuration = 0; pInformation->Current_Interface = 0;/*the default Interface*/ /* Current Feature initialization */ pInformation->Current_Feature = CustomHID_ConfigDescriptor[7]; SetBTABLE(BTABLE_ADDRESS); /* Initialize Endpoint 0 */ SetEPType(ENDP0, EP_CONTROL); SetEPTxStatus(ENDP0, EP_TX_STALL); SetEPRxAddr(ENDP0, ENDP0_RXADDR); SetEPTxAddr(ENDP0, ENDP0_TXADDR); Clear_Status_Out(ENDP0); SetEPRxCount(ENDP0, Device_Property.MaxPacketSize); SetEPTxCount(ENDP0, Device_Property.MaxPacketSize); // TODO: from Tracker SetEPRxValid(ENDP0); /* Initialize Endpoint 1 */ SetEPType(ENDP1, EP_INTERRUPT); SetEPTxAddr(ENDP1, ENDP1_TXADDR); SetEPRxAddr(ENDP1, ENDP1_RXADDR); SetEPTxCount(ENDP1, 64); SetEPRxCount(ENDP1, 64); SetEPRxStatus(ENDP1, EP_RX_VALID); SetEPTxStatus(ENDP1, EP_TX_NAK); /* Set this device to response on default address */ SetDeviceAddress(0); bDeviceState = ATTACHED; } /******************************************************************************* * Function Name : CustomHID_SetConfiguration. * Description : Update the device state to configured and command the ADC * conversion. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void CustomHID_SetConfiguration(void) { if (pInformation->Current_Configuration != 0) { /* Device configured */ bDeviceState = CONFIGURED; } } /******************************************************************************* * Function Name : CustomHID_SetConfiguration. * Description : Update the device state to addressed. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void CustomHID_SetDeviceAddress (void) { bDeviceState = ADDRESSED; } /******************************************************************************* * Function Name : CustomHID_Status_In. * Description : Joystick status IN routine. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void CustomHID_Status_In(void) { if (Request == SET_REPORT) { Request = 0; // This callback means the buffer has been filled, so parse it feature_report_parse(); } } /******************************************************************************* * Function Name : CustomHID_Status_Out * Description : Joystick status OUT routine. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void CustomHID_Status_Out (void) { } /******************************************************************************* * Function Name : CustomHID_Data_Setup * Description : Handle the data class specific requests. * Input : Request Nb. * Output : None. * Return : USB_UNSUPPORT or USB_SUCCESS. *******************************************************************************/ RESULT CustomHID_Data_Setup(uint8_t RequestNo) { uint8_t *(*CopyRoutine)(uint16_t); if (pInformation->USBwIndex != 0) return USB_UNSUPPORT; CopyRoutine = NULL; if ((RequestNo == GET_DESCRIPTOR) && (Type_Recipient == (STANDARD_REQUEST | INTERFACE_RECIPIENT)) ) { if (pInformation->USBwValue1 == REPORT_DESCRIPTOR) { CopyRoutine = CustomHID_GetReportDescriptor; } else if (pInformation->USBwValue1 == HID_DESCRIPTOR_TYPE) { CopyRoutine = CustomHID_GetHIDDescriptor; } } /* End of GET_DESCRIPTOR */ /*** GET_PROTOCOL, GET_REPORT, SET_REPORT ***/ else if ( (Type_Recipient == (CLASS_REQUEST | INTERFACE_RECIPIENT)) ) { switch( RequestNo ) { case GET_REPORT: CopyRoutine = CustomHID_GetReport_Feature; break; case GET_PROTOCOL: CopyRoutine = CustomHID_GetProtocolValue; break; case SET_REPORT: CopyRoutine = CustomHID_SetReport_Feature; Request = SET_REPORT; break; default: break; } } if (CopyRoutine == NULL) { return USB_UNSUPPORT; } pInformation->Ctrl_Info.CopyData = CopyRoutine; pInformation->Ctrl_Info.Usb_wOffset = 0; (*CopyRoutine)(0); return USB_SUCCESS; } /******************************************************************************* * Function Name : CustomHID_GetReport_Feature * Description : Set Feature request handling * Input : Length. * Output : None. * Return : Buffer *******************************************************************************/ uint8_t *CustomHID_GetReport_Feature(uint16_t Length) { if (Length == 0) { pInformation->Ctrl_Info.Usb_wLength = feature_report_length(pInformation->USBwValue0, Length); return NULL; } else { return feature_report_get_buf(pInformation->USBwValue0, pInformation->Ctrl_Info.Usb_wOffset); } } /******************************************************************************* * Function Name : CustomHID_SetReport_Feature * Description : Set Feature request handling * Input : Length. * Output : None. * Return : Buffer *******************************************************************************/ uint8_t *CustomHID_SetReport_Feature(uint16_t Length) { if (Length == 0) { pInformation->Ctrl_Info.Usb_wLength = feature_report_length(pInformation->USBwValue0, Length); return NULL; } else { return feature_report_set_buf(pInformation->USBwValue0, pInformation->Ctrl_Info.Usb_wOffset); } } /******************************************************************************* * Function Name : CustomHID_NoData_Setup * Description : handle the no data class specific requests * Input : Request Nb. * Output : None. * Return : USB_UNSUPPORT or USB_SUCCESS. *******************************************************************************/ RESULT CustomHID_NoData_Setup(uint8_t RequestNo) { if ((Type_Recipient == (CLASS_REQUEST | INTERFACE_RECIPIENT)) && (RequestNo == SET_PROTOCOL)) { return CustomHID_SetProtocol(); } else { return USB_UNSUPPORT; } } /******************************************************************************* * Function Name : CustomHID_GetDeviceDescriptor. * Description : Gets the device descriptor. * Input : Length * Output : None. * Return : The address of the device descriptor. *******************************************************************************/ uint8_t *CustomHID_GetDeviceDescriptor(uint16_t Length) { return Standard_GetDescriptorData(Length, &Device_Descriptor); } /******************************************************************************* * Function Name : CustomHID_GetConfigDescriptor. * Description : Gets the configuration descriptor. * Input : Length * Output : None. * Return : The address of the configuration descriptor. *******************************************************************************/ uint8_t *CustomHID_GetConfigDescriptor(uint16_t Length) { return Standard_GetDescriptorData(Length, &Config_Descriptor); } /******************************************************************************* * Function Name : CustomHID_GetStringDescriptor * Description : Gets the string descriptors according to the needed index * Input : Length * Output : None. * Return : The address of the string descriptors. *******************************************************************************/ uint8_t *CustomHID_GetStringDescriptor(uint16_t Length) { uint8_t wValue0 = pInformation->USBwValue0; // This is modified from ST's library. There are only 4 strings // TODO: report this to ST so that it is fixed in future USB lib revisions if (wValue0 >= 4) { return NULL; } else { return Standard_GetDescriptorData(Length, &String_Descriptor[wValue0]); } } /******************************************************************************* * Function Name : CustomHID_GetReportDescriptor. * Description : Gets the HID report descriptor. * Input : Length * Output : None. * Return : The address of the configuration descriptor. *******************************************************************************/ uint8_t *CustomHID_GetReportDescriptor(uint16_t Length) { return Standard_GetDescriptorData(Length, &CustomHID_Report_Descriptor); } /******************************************************************************* * Function Name : CustomHID_GetHIDDescriptor. * Description : Gets the HID descriptor. * Input : Length * Output : None. * Return : The address of the configuration descriptor. *******************************************************************************/ uint8_t *CustomHID_GetHIDDescriptor(uint16_t Length) { return Standard_GetDescriptorData(Length, &CustomHID_Hid_Descriptor); } /******************************************************************************* * Function Name : CustomHID_Get_Interface_Setting. * Description : tests the interface and the alternate setting according to the * supported one. * Input : - Interface : interface number. * - AlternateSetting : Alternate Setting number. * Output : None. * Return : USB_SUCCESS or USB_UNSUPPORT. *******************************************************************************/ RESULT CustomHID_Get_Interface_Setting(uint8_t Interface, uint8_t AlternateSetting) { if (AlternateSetting > 0) { return USB_UNSUPPORT; } else if (Interface > 0) { return USB_UNSUPPORT; } return USB_SUCCESS; } /******************************************************************************* * Function Name : CustomHID_SetProtocol * Description : Joystick Set Protocol request routine. * Input : None. * Output : None. * Return : USB SUCCESS. *******************************************************************************/ RESULT CustomHID_SetProtocol(void) { uint8_t wValue0 = pInformation->USBwValue0; ProtocolValue = wValue0; return USB_SUCCESS; } /******************************************************************************* * Function Name : CustomHID_GetProtocolValue * Description : get the protocol value * Input : Length. * Output : None. * Return : address of the protocol value. *******************************************************************************/ uint8_t *CustomHID_GetProtocolValue(uint16_t Length) { if (Length == 0) { pInformation->Ctrl_Info.Usb_wLength = 1; return NULL; } else { return (uint8_t *)(&ProtocolValue); } } /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
493968.c
/* * mem.c - memory allocation checkers * Copyright (c) Clemens Ladisch <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #define _GNU_SOURCE #include "aconfig.h" #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <errno.h> #include "die.h" #include "mem.h" static void check(void *p) { if (!p) fatal_error("out of memory"); } void *ccalloc(size_t n, size_t size) { void *mem = calloc(n, size); if (n && size) check(mem); return mem; } void *crealloc(void *ptr, size_t new_size) { ptr = realloc(ptr, new_size); if (new_size) check(ptr); return ptr; } char *cstrdup(const char *s) { char *str = strdup(s); check(str); return str; } char *casprintf(const char *fmt, ...) { va_list ap; char *str; va_start(ap, fmt); if (vasprintf(&str, fmt, ap) < 0) check(NULL); va_end(ap); return str; }
173473.c
#include <ansi.h> inherit ITEM; void create() { set_name(HIR "血蘑菇" NOR, ({"xuemogu"})); set_weight(1); if (clonep()) set_default_object(__FILE__); else { set("long", HIC "血蘑菇乃吸收了99種生物之血化成。\n" + "服食(fushi xuemogu)後可永久提升精力上限5點。\n" HIC "擁有者:zfny\n" NOR); set("unit", "顆"); set("owner", "zfny"); // 綁定擁有者 set("no_drop", 1);set("no_give", 1);set("no_store", 1);set("no_sell", 1); } setup(); } void init() { add_action("do_use", "fushi"); } int do_use(string arg) { object ob, me; me = this_player(); if (! arg || arg != query("id")) return notify_fail("你要服食什麼?\n"); if (! objectp(ob = present(arg, me))) return notify_fail("你身上沒有這個東西!\n"); if (ob->query("owner") != me->query("id")) return notify_fail(ob->name() + NOR "已經於其他玩家綁定!\n"); me->add("drug_addjingli", 10); tell_object(me, HIG "恭喜!你服下" + ob->name() + HIG "後,提升精力上限5點!\n"); log_file("super/"+ filter_color(query("name")) , me->query("id") + " at " + ctime(time()) + " 使用" + ob->name() + "。\n"); me->save(); destruct(ob); return 1; }
154335.c
/* * Copyright (c) 2016, Alliance for Open Media. All rights reserved * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at www.aomedia.org/license/software. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ #include <math.h> #include <stdlib.h> #include "av1/encoder/palette.h" static float calc_dist(const float *p1, const float *p2, int dim) { float dist = 0; int i; for (i = 0; i < dim; ++i) { const float diff = p1[i] - p2[i]; dist += diff * diff; } return dist; } void av1_calc_indices(const float *data, const float *centroids, uint8_t *indices, int n, int k, int dim) { int i, j; for (i = 0; i < n; ++i) { float min_dist = calc_dist(data + i * dim, centroids, dim); indices[i] = 0; for (j = 1; j < k; ++j) { const float this_dist = calc_dist(data + i * dim, centroids + j * dim, dim); if (this_dist < min_dist) { min_dist = this_dist; indices[i] = j; } } } } // Generate a random number in the range [0, 32768). static unsigned int lcg_rand16(unsigned int *state) { *state = (unsigned int)(*state * 1103515245ULL + 12345); return *state / 65536 % 32768; } static void calc_centroids(const float *data, float *centroids, const uint8_t *indices, int n, int k, int dim) { int i, j, index; int count[PALETTE_MAX_SIZE]; unsigned int rand_state = (unsigned int)data[0]; assert(n <= 32768); memset(count, 0, sizeof(count[0]) * k); memset(centroids, 0, sizeof(centroids[0]) * k * dim); for (i = 0; i < n; ++i) { index = indices[i]; assert(index < k); ++count[index]; for (j = 0; j < dim; ++j) { centroids[index * dim + j] += data[i * dim + j]; } } for (i = 0; i < k; ++i) { if (count[i] == 0) { memcpy(centroids + i * dim, data + (lcg_rand16(&rand_state) % n) * dim, sizeof(centroids[0]) * dim); } else { const float norm = 1.0f / count[i]; for (j = 0; j < dim; ++j) centroids[i * dim + j] *= norm; } } // Round to nearest integers. for (i = 0; i < k * dim; ++i) { centroids[i] = roundf(centroids[i]); } } static float calc_total_dist(const float *data, const float *centroids, const uint8_t *indices, int n, int k, int dim) { float dist = 0; int i; (void)k; for (i = 0; i < n; ++i) dist += calc_dist(data + i * dim, centroids + indices[i] * dim, dim); return dist; } void av1_k_means(const float *data, float *centroids, uint8_t *indices, int n, int k, int dim, int max_itr) { int i; float this_dist; float pre_centroids[2 * PALETTE_MAX_SIZE]; uint8_t pre_indices[MAX_SB_SQUARE]; av1_calc_indices(data, centroids, indices, n, k, dim); this_dist = calc_total_dist(data, centroids, indices, n, k, dim); for (i = 0; i < max_itr; ++i) { const float pre_dist = this_dist; memcpy(pre_centroids, centroids, sizeof(pre_centroids[0]) * k * dim); memcpy(pre_indices, indices, sizeof(pre_indices[0]) * n); calc_centroids(data, centroids, indices, n, k, dim); av1_calc_indices(data, centroids, indices, n, k, dim); this_dist = calc_total_dist(data, centroids, indices, n, k, dim); if (this_dist > pre_dist) { memcpy(centroids, pre_centroids, sizeof(pre_centroids[0]) * k * dim); memcpy(indices, pre_indices, sizeof(pre_indices[0]) * n); break; } if (!memcmp(centroids, pre_centroids, sizeof(pre_centroids[0]) * k * dim)) break; } } static int float_comparer(const void *a, const void *b) { const float fa = *(const float *)a; const float fb = *(const float *)b; return (fa > fb) - (fa < fb); } int av1_remove_duplicates(float *centroids, int num_centroids) { int num_unique; // number of unique centroids int i; qsort(centroids, num_centroids, sizeof(*centroids), float_comparer); // Remove duplicates. num_unique = 1; for (i = 1; i < num_centroids; ++i) { if (centroids[i] != centroids[i - 1]) { // found a new unique centroid centroids[num_unique++] = centroids[i]; } } return num_unique; } int av1_count_colors(const uint8_t *src, int stride, int rows, int cols) { int n = 0, r, c, i, val_count[256]; uint8_t val; memset(val_count, 0, sizeof(val_count)); for (r = 0; r < rows; ++r) { for (c = 0; c < cols; ++c) { val = src[r * stride + c]; ++val_count[val]; } } for (i = 0; i < 256; ++i) { if (val_count[i]) { ++n; } } return n; } #if CONFIG_AOM_HIGHBITDEPTH int av1_count_colors_highbd(const uint8_t *src8, int stride, int rows, int cols, int bit_depth) { int n = 0, r, c, i; uint16_t val; uint16_t *src = CONVERT_TO_SHORTPTR(src8); int val_count[1 << 12]; assert(bit_depth <= 12); memset(val_count, 0, (1 << 12) * sizeof(val_count[0])); for (r = 0; r < rows; ++r) { for (c = 0; c < cols; ++c) { val = src[r * stride + c]; ++val_count[val]; } } for (i = 0; i < (1 << bit_depth); ++i) { if (val_count[i]) { ++n; } } return n; } #endif // CONFIG_AOM_HIGHBITDEPTH
65669.c
/* ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio. This file is part of ChibiOS. ChibiOS 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. ChibiOS 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/>. */ /** * @file ARMCMx/compilers/GCC/crt1.c * @brief Startup stub functions. * * @addtogroup ARMCMx_GCC_STARTUP * @{ */ #include <stdbool.h> #include "cmparams.h" /** * @brief Architecture-dependent core initialization. * @details This hook is invoked immediately after the stack initialization * and before the DATA and BSS segments initialization. * @note This function is a weak symbol. */ #if !defined(__DOXYGEN__) __attribute__((weak)) #endif /*lint -save -e9075 [8.4] All symbols are invoked from asm context.*/ void __core_init(void) { #if __CORTEX_M == 7 SCB_EnableICache(); SCB_EnableDCache(); #endif } /** * @brief Early initialization. * @details This hook is invoked immediately after the stack and core * initialization and before the DATA and BSS segments * initialization. * @note This function is a weak symbol. */ #if !defined(__DOXYGEN__) __attribute__((weak)) #endif /*lint -save -e9075 [8.4] All symbols are invoked from asm context.*/ void __early_init(void) {} /*lint -restore*/ /** * @brief Late initialization. * @details This hook is invoked after the DATA and BSS segments * initialization and before any static constructor. The * default behavior is to do nothing. * @note This function is a weak symbol. */ #if !defined(__DOXYGEN__) __attribute__((weak)) #endif /*lint -save -e9075 [8.4] All symbols are invoked from asm context.*/ void __late_init(void) {} /*lint -restore*/ /** * @brief Default @p main() function exit handler. * @details This handler is invoked or the @p main() function exit. The * default behavior is to enter an infinite loop. * @note This function is a weak symbol. */ #if !defined(__DOXYGEN__) __attribute__((noreturn, weak)) #endif /*lint -save -e9075 [8.4] All symbols are invoked from asm context.*/ void __default_exit(void) { /*lint -restore*/ while (true) { } } /** @} */
887261.c
/* D O N U T S . C * BRL-CAD * * Copyright (c) 1998-2022 United States Government as represented by * the U.S. Army Research Laboratory. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this file; see the file named COPYING for more * information. */ /** @file donuts.c * * This program generates a "donut flake" similar to sphflake. * */ #include "common.h" #include <stdlib.h> #include <string.h> #include <math.h> #include "bio.h" #include "bu.h" #include "vmath.h" #include "bn.h" #include "raytrace.h" #include "wdb.h" #define DEFAULT_DEBUG 0 #define DEFAULT_VERBOSE 0 #define DEFAULT_INTERACTIVE 0 #define DEFAULT_DEBUG_OUTPUT stdout #define DEFAULT_VERBOSE_OUTPUT stderr /* this is the name of the default output file name */ #define DEFAULT_OUTPUTFILENAME "donuts.g" /* this is the default measuring units for the database file */ #define DEFAULT_UNITS "mm" /* this is the identifying title or name for the database file */ #define DEFAULT_TITLE "Untitled" /* this is an upper bounds restriction placed on the length of any and * all names in the database. */ #define DEFAULT_MAXNAMELENGTH MAXPATHLEN /* this is the upper bounds on input from the user */ #define MAX_INPUT_LENGTH MAXPATHLEN /* for all of the default names that are specified, a `.s' or `.r' suffix * will automatically get appended where needed for the solid and * region objects that are generated, respectively, and do not need * to be added. * * here are the default program values for the actual donut flake object */ #define DEFAULT_ORIGIN_X 0 #define DEFAULT_ORIGIN_Y 0 #define DEFAULT_ORIGIN_Z 0 #define DEFAULT_MAXDEPTH 3 #define DEFAULT_MAXINNERRADIUS 1000 #define DEFAULT_MAXTORUSRADIUS 25 #define DEFAULT_RADIUSDELTA .333333333 #define DEFAULT_POSITION {0.0, 0.0, 0.0} #define DEFAULT_NORMAL {0.0, 0.0, 1.0} #define DEFAULT_MATERIAL "mirror" #define DEFAULT_MATPARAM "sh=50 sp=.7 di=.3 re=.5" #define DEFAULT_MATCOLOR "80 255 255" #define DEFAULT_SCALE 10.3 #define ADDITIONAL_OBJECTS 5 #define SCENE_ID 0 #define LIGHT0_ID 1 #define LIGHT0_MAT "light" #define LIGHT0_MATPARAM "inten=10000 shadows=1" #define LIGHT0_MATCOLOR "255 255 255" #define LIGHT1_ID 2 #define LIGHT1_MAT "light" #define LIGHT1_MATPARAM "inten=5000 shadows=1 fract=.5" #define LIGHT1_MATCOLOR "255 255 255" #define PLANE_ID 3 #define PLANE_MAT "stack" #define PLANE_MATPARAM "checker; plastic sh=20 sp=.1 di=.9" #define PLANE_MATCOLOR "255 255 255" #define ENVIRON_ID 4 #define ENVIRON_MAT "envmap" #define ENVIRON_MATPARAM "cloud" struct depthMaterial { char name[DEFAULT_MAXNAMELENGTH]; char parameters[DEFAULT_MAXNAMELENGTH]; unsigned char color[3]; }; typedef struct depthMaterial depthMaterial_t; struct params { char fileName[DEFAULT_MAXNAMELENGTH]; int maxDepth; int maxInnerRadius; int maxTorusRadius; double innerRadiusDelta; double torusRadiusDelta; point_t position; vect_t normal; depthMaterial_t *materialArray; }; typedef struct params params_t; int count = 0; /* global sphere count */ struct rt_wdb *fp; /* make the wmember structs, in order to produce individual combinations so we can have separate materials among differing depths */ struct wmember *wmemberArray; /* the vector directions, in which the flakes will be drawn */ /* theta, phi */ int dir[9][2] = { {0, -90}, {60, -90}, {120, -90}, {180, -90}, {240, -90}, {300, -90}, {120, -30}, {240, -30}, {360, -30} }; /****** Function Prototypes ******/ #ifdef __cplusplus extern "C" { #endif extern void initializeInfo(params_t *p, char *name, int depth); extern void createDonuts(params_t *p); extern void createLights(params_t *p); extern void createPlane(params_t *p); extern void createScene(params_t *p); extern void createEnvironMap(params_t *p); extern void getYRotMat(mat_t *mat, fastf_t theta); extern void getZRotMat(mat_t *mat, fastf_t phi); extern void getTrans(mat_t *trans, int i, int j, fastf_t v); extern void makeFlake(int depth, mat_t *trans, point_t center, fastf_t radius, double delta, int maxDepth); extern void usage(char *n); extern void argumentHelp(FILE *fp, const char *progname, char *message); extern void argumentExamples(FILE *fp, char *progname); extern void defaultSettings(FILE *fp); extern int parseArguments(int argc, char *argv[]); extern void printMatrix(FILE *fp, char *n, mat_t m); extern char *getName(char *base, int id, char *suffix); extern char *getPrePostName(char *prefix, char *base, char *suffix); #ifdef __cplusplus } #endif /* command-line options are described in the parseArguments function */ const char *options="IiDdVvO:o:N:n:U:u:"; /* these variables control the "behavior" of this program's output: * * if debug is set, debug information (extra "useful" output is given) * is displayed on stdout. * * if verbose is set, then all prompting and output that may be shown * (such as results and errors) will be sent to stderr. this * should probably be switched with debug (maybe) but convention * was taken from another db program. * * if interactive is set, then the user will be prompted for values * from stdin. * * the default output file pointers for debug and verbose can be set * in the header file */ int debug=DEFAULT_DEBUG; int verbose=DEFAULT_VERBOSE; int interactive=DEFAULT_INTERACTIVE; /* start of variable definitions for the donut flake * * see the donuts.h header file for a description of each of the default values * that may be set. all default values should be set in the donuts.h header * file, not here. */ char outputFilename[DEFAULT_MAXNAMELENGTH]=DEFAULT_OUTPUTFILENAME; char title[DEFAULT_MAXNAMELENGTH]=DEFAULT_TITLE; char units[DEFAULT_MAXNAMELENGTH]=DEFAULT_UNITS; /* primary parameter variable for the donut flake */ params_t parameters; /* * getName() returns a name back based on a base string, a numerical id and a * parameter string for merging those two parameters. Basically it adds the * id number to the end of the base so that we can set unique ids for our * objects and groups. (i.e. base="rcc", id="5"==> returns "rcc005.s" or * something like that) ***********************************/ char * getName(char *base, int id, char *paramstring) { static char name[DEFAULT_MAXNAMELENGTH]; memset(name, 0, DEFAULT_MAXNAMELENGTH); if (id>=0) sprintf(name, paramstring, base, id); else sprintf(name, paramstring, base); if (debug) fprintf(DEFAULT_DEBUG_OUTPUT, "getName(): base[%s], id[%d]\n", base, id); if (verbose) fprintf(DEFAULT_VERBOSE_OUTPUT, "Using name[%s]\n", name); return name; } /* * getPrePostName() returns a name for a region. the name is formed by * simply appending three given strings passed. the three strings comprise * the base, prefix, and suffix of the name. any three are optional by * sending a NULL parameter *****************************************/ char *getPrePostName(char *prefix, char *base, char *suffix) { static char newname[DEFAULT_MAXNAMELENGTH] = {0}; struct bu_vls v = BU_VLS_INIT_ZERO; if (prefix) bu_vls_strcat(&v, prefix); if (base) bu_vls_strcat(&v, base); if (suffix) bu_vls_strcat(&v, suffix); bu_strlcat(newname, bu_vls_cstr(&v), DEFAULT_MAXNAMELENGTH); bu_vls_free(&v); return newname; } void initializeInfo(params_t *p, char *name, int depth) { char input[MAX_INPUT_LENGTH] = {0}; int i = 0; int len = 0; unsigned int c[3]; if (name == NULL) { bu_strlcpy(p->fileName, DEFAULT_OUTPUTFILENAME, DEFAULT_MAXNAMELENGTH); } else { bu_strlcpy(p->fileName, name, DEFAULT_MAXNAMELENGTH); } p->maxInnerRadius = DEFAULT_MAXINNERRADIUS; p->maxTorusRadius = DEFAULT_MAXTORUSRADIUS; p->maxDepth = (depth > 0) ? (depth) : (DEFAULT_MAXDEPTH); p->innerRadiusDelta = p->torusRadiusDelta = DEFAULT_RADIUSDELTA; p->position[X] = DEFAULT_ORIGIN_X; p->position[Y] = DEFAULT_ORIGIN_Y; p->position[Z] = DEFAULT_ORIGIN_Z; p->materialArray = (depthMaterial_t *)bu_malloc(sizeof(depthMaterial_t) * (p->maxDepth+1), "alloc materialArray"); for (i = 0; i <= p->maxDepth; i++) { bu_strlcpy(p->materialArray[i].name, DEFAULT_MATERIAL, MAX_INPUT_LENGTH); bu_strlcpy(p->materialArray[i].parameters, DEFAULT_MATPARAM, MAX_INPUT_LENGTH); sscanf(DEFAULT_MATCOLOR, "%u %u %u", &(c[0]), &(c[1]), &(c[2])); p->materialArray[i].color[0] = c[0]; p->materialArray[i].color[1] = c[1]; p->materialArray[i].color[2] = c[2]; } if (interactive) { /* prompt the user for some data */ /* no error checking here.... */ printf("\nPlease enter a filename for donuts output: [%s] ", p->fileName); if (! bu_fgets(input, MAX_INPUT_LENGTH, stdin)) { fprintf(stderr, "donuts: initializeInfo: bu_fgets filename read error.\n"); fprintf(stderr, "Continuing with default value.\n"); } else { len = strlen(input); if ((len > 0) && (input[len-1] == '\n')) input[len-1] = 0; if (bu_strncmp(input, "", MAX_INPUT_LENGTH) != 0) { sscanf(input, "%s", p->fileName); } } fflush(stdin); printf("Initial position X Y Z: [%.2f %.2f %.2f] ", p->position[X], p->position[Y], p->position[Z]); if (! bu_fgets(input, MAX_INPUT_LENGTH, stdin)) { fprintf(stderr, "donuts: initializeInfo: bu_fgets position read error.\n"); fprintf(stderr, "Continuing with default values.\n"); } else { len = strlen(input); if ((len > 0) && (input[len-1] == '\n')) input[len-1] = 0; if (bu_strncmp(input, "", MAX_INPUT_LENGTH) == 0) { sscanf(input, "%lg %lg %lg", &(p->position[X]), &(p->position[Y]), &(p->position[Z])); } } fflush(stdin); printf("maxInnerRadius: [%d] ", p->maxInnerRadius); if (! bu_fgets(input, MAX_INPUT_LENGTH, stdin)) { fprintf(stderr, "donuts: initializeInfo: bu_fgets maxinnerradius read error.\n"); fprintf(stderr, "Continuing with default value.\n"); } else { len = strlen(input); if ((len > 0) && (input[len-1] == '\n')) input[len-1] = 0; if (bu_strncmp(input, "", MAX_INPUT_LENGTH) != 0) { sscanf(input, "%d", &(p->maxInnerRadius)); } } fflush(stdin); printf("maxTorusRadius: [%d] ", p->maxTorusRadius); if (! bu_fgets(input, MAX_INPUT_LENGTH, stdin)) { fprintf(stderr, "donuts: initializeInfo: bu_fgets maxouterradius read error.\n"); fprintf(stderr, "Continuing with default value.\n"); } else { len = strlen(input); if ((len > 0) && (input[len-1] == '\n')) input[len-1] = 0; if (bu_strncmp(input, "", MAX_INPUT_LENGTH) != 0) { sscanf(input, "%d", &(p->maxTorusRadius)); } } fflush(stdin); printf("innerRadiusDelta: [%.2f] ", p->innerRadiusDelta); if (! bu_fgets(input, MAX_INPUT_LENGTH, stdin)) { fprintf(stderr, "donuts: initializeInfo: bu_fgets innerradiusdelta read error.\n"); fprintf(stderr, "Continuing with default value.\n"); } else { len = strlen(input); if ((len > 0) && (input[len-1] == '\n')) input[len-1] = 0; if (bu_strncmp(input, "", MAX_INPUT_LENGTH) != 0) { sscanf(input, "%lg", &(p->innerRadiusDelta)); } } fflush(stdin); printf("torusRadiusDelta: [%.2f] ", p->torusRadiusDelta); if (! bu_fgets(input, MAX_INPUT_LENGTH, stdin)) { fprintf(stderr, "donuts: initializeInfo: bu_fgets torusradiusdelta read error.\n"); fprintf(stderr, "Continuing with default value.\n"); } else { len = strlen(input); if ((len > 0) && (input[len-1] == '\n')) input[len-1] = 0; if (bu_strncmp(input, "", MAX_INPUT_LENGTH) != 0) { sscanf(input, "%lg", &(p->torusRadiusDelta)); } } fflush(stdin); printf("maxDepth: [%d] ", p->maxDepth); if (! bu_fgets(input, MAX_INPUT_LENGTH, stdin)) { fprintf(stderr, "donuts: initializeInfo: bu_fgets maxdepth read error.\n"); fprintf(stderr, "Continuing with default value.\n"); } else { len = strlen(input); if ((len > 0) && (input[len-1] == '\n')) input[len-1] = 0; if (bu_strncmp(input, "", MAX_INPUT_LENGTH) != 0) { sscanf(input, "%d", &(p->maxDepth)); } } fflush(stdin); for (i = 0; i <= p->maxDepth; i++) { printf("Material for depth %d: [%s] ", i, p->materialArray[i].name); if (! bu_fgets(input, MAX_INPUT_LENGTH, stdin)) { fprintf(stderr, "donuts: initializeInfo: bu_fgets material read error.\n"); fprintf(stderr, "Continuing with default value.\n"); } else { len = strlen(input); if ((len > 0) && (input[len-1] == '\n')) input[len-1] = 0; if (bu_strncmp(input, "", MAX_INPUT_LENGTH) != 0) { sscanf(input, "%s", p->materialArray[i].name); } } fflush(stdin); printf("Mat. params for depth %d: [%s] ", i, p->materialArray[i].parameters); if (! bu_fgets(input, MAX_INPUT_LENGTH, stdin)) { fprintf(stderr, "donuts: initializeInfo: bu_fgets params read error.\n"); fprintf(stderr, "Continuing with default value.\n"); } else { len = strlen(input); if ((len > 0) && (input[len-1] == '\n')) input[len-1] = 0; if (bu_strncmp(input, "", MAX_INPUT_LENGTH) != 0) { sscanf(input, "%s", p->materialArray[i].parameters); } } fflush(stdin); printf("Mat. color for depth %d: [%d %d %d] ", i, p->materialArray[i].color[0], p->materialArray[i].color[1], p->materialArray[i].color[2]); if (! bu_fgets(input, MAX_INPUT_LENGTH, stdin)) { fprintf(stderr, "donuts: initializeInfo: bu_fgets color read error.\n"); fprintf(stderr, "Continuing with default values.\n"); } else { len = strlen(input); if ((len > 0) && (input[len-1] == '\n')) input[len-1] = 0; if (bu_strncmp(input, "", MAX_INPUT_LENGTH) != 0) { sscanf(input, "%u %u %u", &(c[0]), &(c[1]), &(c[2])); p->materialArray[i].color[0] = c[0]; p->materialArray[i].color[1] = c[1]; p->materialArray[i].color[2] = c[2]; } } fflush(stdin); } } } void createDonuts(params_t *p) { mat_t trans; char name[MAX_INPUT_LENGTH]; int i = 0; /* now begin the creation of the donuts... */ MAT_IDN(trans); /* get the identity matrix */ makeFlake(0, &trans, p->position, (fastf_t)p->maxTorusRadius * DEFAULT_SCALE, p->torusRadiusDelta, p->maxDepth); /* Now create the depth combinations/regions This is done to facilitate application of different materials to the different depths */ for (i = 0; i <= p->maxDepth; i++) { memset(name, 0, MAX_INPUT_LENGTH); sprintf(name, "depth%d.r", i); mk_lcomb(fp, name, &(wmemberArray[i+ADDITIONAL_OBJECTS]), 1, p->materialArray[i].name, p->materialArray[i].parameters, p->materialArray[i].color, 0); } printf("\nDonuts created"); } void createLights(params_t *p) { char name[MAX_INPUT_LENGTH]; point_t lPos; int r, g, b; unsigned char c[3]; /* first create the light spheres */ VSET(lPos, p->position[X]+(5 * p->maxTorusRadius), p->position[Y]+(-5 * p->maxTorusRadius), p->position[Z]+(150 * p->maxTorusRadius)); memset(name, 0, MAX_INPUT_LENGTH); sprintf(name, "light0"); mk_sph(fp, name, lPos, p->maxTorusRadius*5); /* now make the light region... */ mk_addmember(name, &(wmemberArray[LIGHT0_ID].l), NULL, WMOP_UNION); bu_strlcat(name, ".r", MAX_INPUT_LENGTH); sscanf(LIGHT0_MATCOLOR, "%d %d %d", &r, &g, &b); c[0] = (char)r; c[1] = (char)g; c[2] = (char)b; mk_lcomb(fp, name, &(wmemberArray[LIGHT0_ID]), 1, LIGHT0_MAT, LIGHT0_MATPARAM, (const unsigned char *) c, 0); VSET(lPos, p->position[X]+(13 * p->maxTorusRadius), p->position[Y]+(-13 * p->maxTorusRadius), p->position[Z]+(152 * p->maxTorusRadius)); sprintf(name, "light1"); mk_sph(fp, name, lPos, p->maxTorusRadius*5); /* now make the light region... */ mk_addmember(name, &(wmemberArray[LIGHT1_ID].l), NULL, WMOP_UNION); bu_strlcat(name, ".r", MAX_INPUT_LENGTH); sscanf(LIGHT1_MATCOLOR, "%d %d %d", &r, &g, &b); c[0] = (char)r; c[1] = (char)g; c[2] = (char)b; mk_lcomb(fp, name, &(wmemberArray[LIGHT1_ID]), 1, LIGHT1_MAT, LIGHT1_MATPARAM, (const unsigned char *) c, 0); printf("\nLights created"); } void createPlane(params_t *p) { char name[MAX_INPUT_LENGTH]; point_t lPos; const unsigned char *matcolor = (unsigned char *)PLANE_MATCOLOR; VSET(lPos, 0, 0, 1); /* set the normal */ memset(name, 0, MAX_INPUT_LENGTH); sprintf(name, "plane"); mk_half(fp, name, lPos, -p->maxTorusRadius * 2 * DEFAULT_SCALE); /* now make the plane region... */ mk_addmember(name, &(wmemberArray[PLANE_ID].l), NULL, WMOP_UNION); bu_strlcat(name, ".r", MAX_INPUT_LENGTH); mk_lcomb(fp, name, &(wmemberArray[PLANE_ID]), 1, PLANE_MAT, PLANE_MATPARAM, matcolor, 0); printf("\nPlane created"); } void createEnvironMap(params_t *p) { char name[MAX_INPUT_LENGTH]; const unsigned char *color = (unsigned char *)"0 0 0"; if (!p) return; memset(name, 0, MAX_INPUT_LENGTH); sprintf(name, "light0"); mk_addmember(name, &(wmemberArray[ENVIRON_ID].l), NULL, WMOP_UNION); memset(name, 0, MAX_INPUT_LENGTH); sprintf(name, "environ.r"); mk_lcomb(fp, name, &(wmemberArray[ENVIRON_ID]), 1, ENVIRON_MAT, ENVIRON_MATPARAM, color, 0); printf("\nEnvironment map created"); } void createScene(params_t *p) { int i; char name[MAX_INPUT_LENGTH]; for (i = 0; i < p->maxDepth+1; i++) { memset(name, 0, MAX_INPUT_LENGTH); sprintf(name, "depth%d.r", i); mk_addmember(name, &(wmemberArray[SCENE_ID].l), NULL, WMOP_UNION); } mk_addmember("light0.r", &(wmemberArray[SCENE_ID].l), NULL, WMOP_UNION); mk_addmember("light1.r", &(wmemberArray[SCENE_ID].l), NULL, WMOP_UNION); mk_addmember("plane.r", &(wmemberArray[SCENE_ID].l), NULL, WMOP_UNION); mk_addmember("environ.r", &(wmemberArray[SCENE_ID].l), NULL, WMOP_UNION); memset(name, 0, MAX_INPUT_LENGTH); sprintf(name, "scene.r"); mk_lfcomb(fp, name, &(wmemberArray[SCENE_ID]), 0); printf("\nScene created (FILE: %s)\n", p->fileName); } /* * printMatrix() does just that, it prints out a matrix and a label passed to * some fp (usually DEFAULT_DEBUG_OUTPUT or DEFAULT_VERBOSE_OUTPUT). *************************/ void printMatrix(FILE *outfp, char *n, mat_t m) { int i = 0; fprintf(outfp, "\n-----%s------\n", n); for (i = 0; i < 16; i++) { if (i%4 == 0 && i != 0) fprintf(outfp, "\n"); fprintf(outfp, "%6.2f ", m[i]); } fprintf(outfp, "\n-----------\n"); } void getZRotMat(mat_t *t, fastf_t phi) { fastf_t sin_ = sin(DEG2RAD*phi); fastf_t cos_ = cos(DEG2RAD*phi); mat_t r; MAT_ZERO(r); r[0] = cos_; r[1] = -sin_; r[4] = sin_; r[5] = cos_; r[10] = 1; r[15] = 1; memcpy(*t, r, sizeof(*t)); } void getYRotMat(mat_t *t, fastf_t theta) { fastf_t sin_ = sin(DEG2RAD*theta); fastf_t cos_ = cos(DEG2RAD*theta); mat_t r; MAT_ZERO(r); r[0] = cos_; r[2] = sin_; r[5] = 1; r[8] = -sin_; r[10] = cos_; r[15] = 1; memcpy(*t, r, sizeof(*t)); } void getTrans(mat_t *t, int theta, int phi, fastf_t radius) { mat_t z; mat_t y; mat_t toRelative; mat_t newPos; MAT_IDN(z); MAT_IDN(y); MAT_IDN(newPos); MAT_IDN(toRelative); MAT_DELTAS(toRelative, 0, 0, radius); getZRotMat(&z, theta); getYRotMat(&y, phi); bn_mat_mul2(toRelative, newPos); /* translate to new position */ bn_mat_mul2(y, newPos); /* rotate z */ bn_mat_mul2(z, newPos); /* rotate y */ MAT_DELTAS(*t, 0, 0, 0); bn_mat_mul2(*t, newPos); memcpy(*t, newPos, sizeof(newPos)); } void makeFlake(int depth, mat_t *trans, point_t center, fastf_t radius, double delta, int maxDepth) { char name[MAX_INPUT_LENGTH]; int i = 0; point_t pcent; fastf_t newRadius; mat_t temp; point_t origin; point_t pcentTemp; vect_t normal; VSET(origin, 0, 0, 0); VSET(normal, 1.0, 0, 0); /* just return if depth == maxDepth */ if (depth > maxDepth) return; /* create self, then recurse for each different angle */ count++; sprintf(name, "sph%d", count); mk_tor(fp, name, center, normal, radius, radius/4.0); newRadius = radius*delta; /* add the sphere to the correct combination */ mk_addmember(name, &(wmemberArray[depth+ADDITIONAL_OBJECTS].l), NULL, WMOP_UNION); for (i = 0; i < 9; i++) { memcpy(temp, trans, sizeof(temp)); getTrans(&temp, dir[i][0], dir[i][1], radius+newRadius); MAT4X3PNT(pcentTemp, temp, origin); VADD2(pcent, pcentTemp, center); makeFlake(depth+1, &temp, pcent, newRadius, delta, maxDepth); } } /* * defaultSettings() outputs the default values of the program to a * given file pointer. * ***********************/ void defaultSettings(FILE *outfp) { fprintf(outfp, "Default values:\n\n"); fprintf(outfp, "\tVerbose mode is %s\n", verbose ? "on" : "off"); fprintf(outfp, "\tDebug mode is %s\n", debug ? "on" : "off"); fprintf(outfp, "\tInteractive mode is %s\n", interactive ? "on" : "off"); fprintf(outfp, "\n\tOutput file name is %s\n", outputFilename); fprintf(outfp, "\t\tid='%s' units='%s'\n", title, units); fprintf(outfp, "No action performed.\n"); } /* * argumentExamples() outputs some examples of using the command line * arguments in a useful manner **********************************/ void argumentExamples(FILE *outfp, char *progname) { if (progname) fprintf(outfp, "Usage Examples: \n\n"); return; } /* * parseArguments() is called by main to take care of all of the command-line * arguments that the user specifies. The args that are read set variables * which, in turn, are used as fence parameters. *****************************/ int parseArguments(int argc, char *argv[]) { int c = 0; const char *progname = argv[0]; bu_opterr = 0; while ((c=bu_getopt(argc, argv, options)) != -1) { switch (c) { case 'I' : interactive=(DEFAULT_INTERACTIVE) ? 0 : 1; break; case 'i' : interactive=1; break; case 'D' : debug=(DEFAULT_DEBUG) ? 0 : 1; break; case 'd' : debug=1; break; case 'V' : verbose=(DEFAULT_VERBOSE) ? 0 : 1; break; case 'v' : verbose=1; break; case 'o' : memset(outputFilename, 0, DEFAULT_MAXNAMELENGTH); bu_strlcpy(outputFilename, bu_optarg, DEFAULT_MAXNAMELENGTH); break; case 'O' : memset(outputFilename, 0, DEFAULT_MAXNAMELENGTH); bu_strlcpy(outputFilename, bu_optarg, DEFAULT_MAXNAMELENGTH); break; case 'n' : memset(title, 0, DEFAULT_MAXNAMELENGTH); bu_strlcpy(title, bu_optarg, DEFAULT_MAXNAMELENGTH); break; case 'N' : memset(title, 0, DEFAULT_MAXNAMELENGTH); bu_strlcpy(title, bu_optarg, DEFAULT_MAXNAMELENGTH); break; case 'u' : memset(units, 0, DEFAULT_MAXNAMELENGTH); bu_strlcpy(units, bu_optarg, DEFAULT_MAXNAMELENGTH); break; case 'U' : memset(units, 0, DEFAULT_MAXNAMELENGTH); bu_strlcpy(units, bu_optarg, DEFAULT_MAXNAMELENGTH); break; case 'l' : // maxDepth = atoi(c); break; case '?' : (void)argumentHelp(DEFAULT_VERBOSE_OUTPUT, progname, "Command-line argument assistance"); exit(1); break; default : /*shouldn't be reached since getopt throws a ? for args not found*/ (void)argumentHelp(DEFAULT_VERBOSE_OUTPUT, progname, "Illegal command-line argument"); exit(1); break; } } return(bu_optind); } /* * argumentHelp() is the all encompassing help message that is displayed when * an invalid command line argument is entered or if the user explicitly * requests assistance. ***************************************/ void argumentHelp(FILE *outfp, const char *progname, char *message) { if (message) { fprintf(outfp, "%s\n", message); } fprintf(outfp, "Usage Format: \n%s %s\n\n", progname, \ "-[ivdonu]" \ ); fprintf(outfp, "\t-[zZ]\n\t\tdisplays the default settings\n"); putc((int)'\n', outfp); return; } /* main() is basically just a simple interface to the program. The interface changes the * defaults according to what the user has specified and offers the opportunity to enter * data in an interactive mode *******************/ int main(int argc, char **argv) { int i; bu_setprogname(argv[0]); bu_strlcpy(parameters.fileName, DEFAULT_OUTPUTFILENAME, DEFAULT_MAXNAMELENGTH); parameters.maxDepth=DEFAULT_MAXDEPTH; parameters.maxInnerRadius=DEFAULT_MAXINNERRADIUS; parameters.maxTorusRadius=DEFAULT_MAXTORUSRADIUS; parameters.innerRadiusDelta=DEFAULT_RADIUSDELTA; parameters.torusRadiusDelta=DEFAULT_RADIUSDELTA; vect_t normal = DEFAULT_NORMAL; point_t position = DEFAULT_POSITION; VMOVE(parameters.normal, normal); VMOVE(parameters.position, position); // parameters.materialArray; (void) parseArguments(argc, argv); if (verbose) fprintf(DEFAULT_VERBOSE_OUTPUT, "\nUsing [%s] for output file\n\n", outputFilename); if (verbose) fprintf(DEFAULT_VERBOSE_OUTPUT, "Verbose mode is on\n"); if (debug) fprintf(DEFAULT_DEBUG_OUTPUT, "Debug mode is on\n"); if (verbose && interactive) fprintf(DEFAULT_VERBOSE_OUTPUT, "Interactive mode is on\n"); if (verbose) { fprintf(DEFAULT_VERBOSE_OUTPUT, "\nDonut Flake Properties:\n"); putc((int)'\n', DEFAULT_VERBOSE_OUTPUT); } initializeInfo(&parameters, parameters.fileName, parameters.maxDepth); /* now open a file for outputting the database */ bu_strlcpy(parameters.fileName, outputFilename, DEFAULT_MAXNAMELENGTH); fp = wdb_fopen(parameters.fileName); if (fp==NULL) { perror(outputFilename); exit(2); } /* create the initial id */ mk_id_units(fp, "DonutFlake", "mm"); /* initialize the wmember structs... this is for creating the regions */ wmemberArray = (struct wmember *)bu_malloc(sizeof(struct wmember) *(parameters.maxDepth+1+ADDITIONAL_OBJECTS), "alloc wmemberArray"); for (i = 0; i <= parameters.maxDepth+ADDITIONAL_OBJECTS; i++) { BU_LIST_INIT(&(wmemberArray[i].l)); } /****** Create the Donuts ******/ createDonuts(&parameters); /* now that the entire donuts has been created, we can create the additional objects needed to complete the scene. */ /****** Create the Lights ******/ createLights(&parameters); /****** Create the Plane ******/ createPlane(&parameters); /****** Create the Environment map ******/ createEnvironMap(&parameters); /****** Create the entire Scene combination ******/ createScene(&parameters); wdb_close(fp); bu_free(wmemberArray, "free wmemberArray"); return 0; } /* * Local Variables: * tab-width: 8 * mode: C * indent-tabs-mode: t * c-file-style: "stroustrup" * End: * ex: shiftwidth=4 tabstop=8 */
512619.c
/* * DCCP connection tracking protocol helper * * Copyright (c) 2005, 2006, 2008 Patrick McHardy <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/sysctl.h> #include <linux/spinlock.h> #include <linux/skbuff.h> #include <linux/dccp.h> #include <linux/slab.h> #include <net/net_namespace.h> #include <net/netns/generic.h> #include <linux/netfilter/nfnetlink_conntrack.h> #include <net/netfilter/nf_conntrack.h> #include <net/netfilter/nf_conntrack_l4proto.h> #include <net/netfilter/nf_conntrack_ecache.h> #include <net/netfilter/nf_log.h> /* Timeouts are based on values from RFC4340: * * - REQUEST: * * 8.1.2. Client Request * * A client MAY give up on its DCCP-Requests after some time * (3 minutes, for example). * * - RESPOND: * * 8.1.3. Server Response * * It MAY also leave the RESPOND state for CLOSED after a timeout of * not less than 4MSL (8 minutes); * * - PARTOPEN: * * 8.1.5. Handshake Completion * * If the client remains in PARTOPEN for more than 4MSL (8 minutes), * it SHOULD reset the connection with Reset Code 2, "Aborted". * * - OPEN: * * The DCCP timestamp overflows after 11.9 hours. If the connection * stays idle this long the sequence number won't be recognized * as valid anymore. * * - CLOSEREQ/CLOSING: * * 8.3. Termination * * The retransmission timer should initially be set to go off in two * round-trip times and should back off to not less than once every * 64 seconds ... * * - TIMEWAIT: * * 4.3. States * * A server or client socket remains in this state for 2MSL (4 minutes) * after the connection has been town down, ... */ #define DCCP_MSL (2 * 60 * HZ) static const char * const dccp_state_names[] = { [CT_DCCP_NONE] = "NONE", [CT_DCCP_REQUEST] = "REQUEST", [CT_DCCP_RESPOND] = "RESPOND", [CT_DCCP_PARTOPEN] = "PARTOPEN", [CT_DCCP_OPEN] = "OPEN", [CT_DCCP_CLOSEREQ] = "CLOSEREQ", [CT_DCCP_CLOSING] = "CLOSING", [CT_DCCP_TIMEWAIT] = "TIMEWAIT", [CT_DCCP_IGNORE] = "IGNORE", [CT_DCCP_INVALID] = "INVALID", }; #define sNO CT_DCCP_NONE #define sRQ CT_DCCP_REQUEST #define sRS CT_DCCP_RESPOND #define sPO CT_DCCP_PARTOPEN #define sOP CT_DCCP_OPEN #define sCR CT_DCCP_CLOSEREQ #define sCG CT_DCCP_CLOSING #define sTW CT_DCCP_TIMEWAIT #define sIG CT_DCCP_IGNORE #define sIV CT_DCCP_INVALID /* * DCCP state transition table * * The assumption is the same as for TCP tracking: * * We are the man in the middle. All the packets go through us but might * get lost in transit to the destination. It is assumed that the destination * can't receive segments we haven't seen. * * The following states exist: * * NONE: Initial state, expecting Request * REQUEST: Request seen, waiting for Response from server * RESPOND: Response from server seen, waiting for Ack from client * PARTOPEN: Ack after Response seen, waiting for packet other than Response, * Reset or Sync from server * OPEN: Packet other than Response, Reset or Sync seen * CLOSEREQ: CloseReq from server seen, expecting Close from client * CLOSING: Close seen, expecting Reset * TIMEWAIT: Reset seen * IGNORE: Not determinable whether packet is valid * * Some states exist only on one side of the connection: REQUEST, RESPOND, * PARTOPEN, CLOSEREQ. For the other side these states are equivalent to * the one it was in before. * * Packets are marked as ignored (sIG) if we don't know if they're valid * (for example a reincarnation of a connection we didn't notice is dead * already) and the server may send back a connection closing Reset or a * Response. They're also used for Sync/SyncAck packets, which we don't * care about. */ static const u_int8_t dccp_state_table[CT_DCCP_ROLE_MAX + 1][DCCP_PKT_SYNCACK + 1][CT_DCCP_MAX + 1] = { [CT_DCCP_ROLE_CLIENT] = { [DCCP_PKT_REQUEST] = { /* * sNO -> sRQ Regular Request * sRQ -> sRQ Retransmitted Request or reincarnation * sRS -> sRS Retransmitted Request (apparently Response * got lost after we saw it) or reincarnation * sPO -> sIG Ignore, conntrack might be out of sync * sOP -> sIG Ignore, conntrack might be out of sync * sCR -> sIG Ignore, conntrack might be out of sync * sCG -> sIG Ignore, conntrack might be out of sync * sTW -> sRQ Reincarnation * * sNO, sRQ, sRS, sPO. sOP, sCR, sCG, sTW, */ sRQ, sRQ, sRS, sIG, sIG, sIG, sIG, sRQ, }, [DCCP_PKT_RESPONSE] = { /* * sNO -> sIV Invalid * sRQ -> sIG Ignore, might be response to ignored Request * sRS -> sIG Ignore, might be response to ignored Request * sPO -> sIG Ignore, might be response to ignored Request * sOP -> sIG Ignore, might be response to ignored Request * sCR -> sIG Ignore, might be response to ignored Request * sCG -> sIG Ignore, might be response to ignored Request * sTW -> sIV Invalid, reincarnation in reverse direction * goes through sRQ * * sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */ sIV, sIG, sIG, sIG, sIG, sIG, sIG, sIV, }, [DCCP_PKT_ACK] = { /* * sNO -> sIV No connection * sRQ -> sIV No connection * sRS -> sPO Ack for Response, move to PARTOPEN (8.1.5.) * sPO -> sPO Retransmitted Ack for Response, remain in PARTOPEN * sOP -> sOP Regular ACK, remain in OPEN * sCR -> sCR Ack in CLOSEREQ MAY be processed (8.3.) * sCG -> sCG Ack in CLOSING MAY be processed (8.3.) * sTW -> sIV * * sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */ sIV, sIV, sPO, sPO, sOP, sCR, sCG, sIV }, [DCCP_PKT_DATA] = { /* * sNO -> sIV No connection * sRQ -> sIV No connection * sRS -> sIV No connection * sPO -> sIV MUST use DataAck in PARTOPEN state (8.1.5.) * sOP -> sOP Regular Data packet * sCR -> sCR Data in CLOSEREQ MAY be processed (8.3.) * sCG -> sCG Data in CLOSING MAY be processed (8.3.) * sTW -> sIV * * sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */ sIV, sIV, sIV, sIV, sOP, sCR, sCG, sIV, }, [DCCP_PKT_DATAACK] = { /* * sNO -> sIV No connection * sRQ -> sIV No connection * sRS -> sPO Ack for Response, move to PARTOPEN (8.1.5.) * sPO -> sPO Remain in PARTOPEN state * sOP -> sOP Regular DataAck packet in OPEN state * sCR -> sCR DataAck in CLOSEREQ MAY be processed (8.3.) * sCG -> sCG DataAck in CLOSING MAY be processed (8.3.) * sTW -> sIV * * sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */ sIV, sIV, sPO, sPO, sOP, sCR, sCG, sIV }, [DCCP_PKT_CLOSEREQ] = { /* * CLOSEREQ may only be sent by the server. * * sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */ sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV }, [DCCP_PKT_CLOSE] = { /* * sNO -> sIV No connection * sRQ -> sIV No connection * sRS -> sIV No connection * sPO -> sCG Client-initiated close * sOP -> sCG Client-initiated close * sCR -> sCG Close in response to CloseReq (8.3.) * sCG -> sCG Retransmit * sTW -> sIV Late retransmit, already in TIME_WAIT * * sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */ sIV, sIV, sIV, sCG, sCG, sCG, sIV, sIV }, [DCCP_PKT_RESET] = { /* * sNO -> sIV No connection * sRQ -> sTW Sync received or timeout, SHOULD send Reset (8.1.1.) * sRS -> sTW Response received without Request * sPO -> sTW Timeout, SHOULD send Reset (8.1.5.) * sOP -> sTW Connection reset * sCR -> sTW Connection reset * sCG -> sTW Connection reset * sTW -> sIG Ignore (don't refresh timer) * * sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */ sIV, sTW, sTW, sTW, sTW, sTW, sTW, sIG }, [DCCP_PKT_SYNC] = { /* * We currently ignore Sync packets * * sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */ sIV, sIG, sIG, sIG, sIG, sIG, sIG, sIG, }, [DCCP_PKT_SYNCACK] = { /* * We currently ignore SyncAck packets * * sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */ sIV, sIG, sIG, sIG, sIG, sIG, sIG, sIG, }, }, [CT_DCCP_ROLE_SERVER] = { [DCCP_PKT_REQUEST] = { /* * sNO -> sIV Invalid * sRQ -> sIG Ignore, conntrack might be out of sync * sRS -> sIG Ignore, conntrack might be out of sync * sPO -> sIG Ignore, conntrack might be out of sync * sOP -> sIG Ignore, conntrack might be out of sync * sCR -> sIG Ignore, conntrack might be out of sync * sCG -> sIG Ignore, conntrack might be out of sync * sTW -> sRQ Reincarnation, must reverse roles * * sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */ sIV, sIG, sIG, sIG, sIG, sIG, sIG, sRQ }, [DCCP_PKT_RESPONSE] = { /* * sNO -> sIV Response without Request * sRQ -> sRS Response to clients Request * sRS -> sRS Retransmitted Response (8.1.3. SHOULD NOT) * sPO -> sIG Response to an ignored Request or late retransmit * sOP -> sIG Ignore, might be response to ignored Request * sCR -> sIG Ignore, might be response to ignored Request * sCG -> sIG Ignore, might be response to ignored Request * sTW -> sIV Invalid, Request from client in sTW moves to sRQ * * sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */ sIV, sRS, sRS, sIG, sIG, sIG, sIG, sIV }, [DCCP_PKT_ACK] = { /* * sNO -> sIV No connection * sRQ -> sIV No connection * sRS -> sIV No connection * sPO -> sOP Enter OPEN state (8.1.5.) * sOP -> sOP Regular Ack in OPEN state * sCR -> sIV Waiting for Close from client * sCG -> sCG Ack in CLOSING MAY be processed (8.3.) * sTW -> sIV * * sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */ sIV, sIV, sIV, sOP, sOP, sIV, sCG, sIV }, [DCCP_PKT_DATA] = { /* * sNO -> sIV No connection * sRQ -> sIV No connection * sRS -> sIV No connection * sPO -> sOP Enter OPEN state (8.1.5.) * sOP -> sOP Regular Data packet in OPEN state * sCR -> sIV Waiting for Close from client * sCG -> sCG Data in CLOSING MAY be processed (8.3.) * sTW -> sIV * * sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */ sIV, sIV, sIV, sOP, sOP, sIV, sCG, sIV }, [DCCP_PKT_DATAACK] = { /* * sNO -> sIV No connection * sRQ -> sIV No connection * sRS -> sIV No connection * sPO -> sOP Enter OPEN state (8.1.5.) * sOP -> sOP Regular DataAck in OPEN state * sCR -> sIV Waiting for Close from client * sCG -> sCG Data in CLOSING MAY be processed (8.3.) * sTW -> sIV * * sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */ sIV, sIV, sIV, sOP, sOP, sIV, sCG, sIV }, [DCCP_PKT_CLOSEREQ] = { /* * sNO -> sIV No connection * sRQ -> sIV No connection * sRS -> sIV No connection * sPO -> sOP -> sCR Move directly to CLOSEREQ (8.1.5.) * sOP -> sCR CloseReq in OPEN state * sCR -> sCR Retransmit * sCG -> sCR Simultaneous close, client sends another Close * sTW -> sIV Already closed * * sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */ sIV, sIV, sIV, sCR, sCR, sCR, sCR, sIV }, [DCCP_PKT_CLOSE] = { /* * sNO -> sIV No connection * sRQ -> sIV No connection * sRS -> sIV No connection * sPO -> sOP -> sCG Move direcly to CLOSING * sOP -> sCG Move to CLOSING * sCR -> sIV Close after CloseReq is invalid * sCG -> sCG Retransmit * sTW -> sIV Already closed * * sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */ sIV, sIV, sIV, sCG, sCG, sIV, sCG, sIV }, [DCCP_PKT_RESET] = { /* * sNO -> sIV No connection * sRQ -> sTW Reset in response to Request * sRS -> sTW Timeout, SHOULD send Reset (8.1.3.) * sPO -> sTW Timeout, SHOULD send Reset (8.1.3.) * sOP -> sTW * sCR -> sTW * sCG -> sTW * sTW -> sIG Ignore (don't refresh timer) * * sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW, sTW */ sIV, sTW, sTW, sTW, sTW, sTW, sTW, sTW, sIG }, [DCCP_PKT_SYNC] = { /* * We currently ignore Sync packets * * sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */ sIV, sIG, sIG, sIG, sIG, sIG, sIG, sIG, }, [DCCP_PKT_SYNCACK] = { /* * We currently ignore SyncAck packets * * sNO, sRQ, sRS, sPO, sOP, sCR, sCG, sTW */ sIV, sIG, sIG, sIG, sIG, sIG, sIG, sIG, }, }, }; /* this module per-net specifics */ static int dccp_net_id __read_mostly; struct dccp_net { struct nf_proto_net pn; int dccp_loose; unsigned int dccp_timeout[CT_DCCP_MAX + 1]; }; static inline struct dccp_net *dccp_pernet(struct net *net) { return net_generic(net, dccp_net_id); } static bool dccp_pkt_to_tuple(const struct sk_buff *skb, unsigned int dataoff, struct net *net, struct nf_conntrack_tuple *tuple) { struct dccp_hdr _hdr, *dh; /* Actually only need first 4 bytes to get ports. */ dh = skb_header_pointer(skb, dataoff, 4, &_hdr); if (dh == NULL) return false; tuple->src.u.dccp.port = dh->dccph_sport; tuple->dst.u.dccp.port = dh->dccph_dport; return true; } static bool dccp_invert_tuple(struct nf_conntrack_tuple *inv, const struct nf_conntrack_tuple *tuple) { inv->src.u.dccp.port = tuple->dst.u.dccp.port; inv->dst.u.dccp.port = tuple->src.u.dccp.port; return true; } static bool dccp_new(struct nf_conn *ct, const struct sk_buff *skb, unsigned int dataoff, unsigned int *timeouts) { struct net *net = nf_ct_net(ct); struct dccp_net *dn; struct dccp_hdr _dh, *dh; const char *msg; u_int8_t state; dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &_dh); BUG_ON(dh == NULL); state = dccp_state_table[CT_DCCP_ROLE_CLIENT][dh->dccph_type][CT_DCCP_NONE]; switch (state) { default: dn = dccp_pernet(net); if (dn->dccp_loose == 0) { msg = "nf_ct_dccp: not picking up existing connection "; goto out_invalid; } case CT_DCCP_REQUEST: break; case CT_DCCP_INVALID: msg = "nf_ct_dccp: invalid state transition "; goto out_invalid; } ct->proto.dccp.role[IP_CT_DIR_ORIGINAL] = CT_DCCP_ROLE_CLIENT; ct->proto.dccp.role[IP_CT_DIR_REPLY] = CT_DCCP_ROLE_SERVER; ct->proto.dccp.state = CT_DCCP_NONE; ct->proto.dccp.last_pkt = DCCP_PKT_REQUEST; ct->proto.dccp.last_dir = IP_CT_DIR_ORIGINAL; ct->proto.dccp.handshake_seq = 0; return true; out_invalid: if (LOG_INVALID(net, IPPROTO_DCCP)) nf_log_packet(net, nf_ct_l3num(ct), 0, skb, NULL, NULL, NULL, "%s", msg); return false; } static u64 dccp_ack_seq(const struct dccp_hdr *dh) { const struct dccp_hdr_ack_bits *dhack; dhack = (void *)dh + __dccp_basic_hdr_len(dh); return ((u64)ntohs(dhack->dccph_ack_nr_high) << 32) + ntohl(dhack->dccph_ack_nr_low); } static unsigned int *dccp_get_timeouts(struct net *net) { return dccp_pernet(net)->dccp_timeout; } static int dccp_packet(struct nf_conn *ct, const struct sk_buff *skb, unsigned int dataoff, enum ip_conntrack_info ctinfo, u_int8_t pf, unsigned int hooknum, unsigned int *timeouts) { struct net *net = nf_ct_net(ct); enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo); struct dccp_hdr _dh, *dh; u_int8_t type, old_state, new_state; enum ct_dccp_roles role; dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &_dh); BUG_ON(dh == NULL); type = dh->dccph_type; if (type == DCCP_PKT_RESET && !test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) { /* Tear down connection immediately if only reply is a RESET */ nf_ct_kill_acct(ct, ctinfo, skb); return NF_ACCEPT; } spin_lock_bh(&ct->lock); role = ct->proto.dccp.role[dir]; old_state = ct->proto.dccp.state; new_state = dccp_state_table[role][type][old_state]; switch (new_state) { case CT_DCCP_REQUEST: if (old_state == CT_DCCP_TIMEWAIT && role == CT_DCCP_ROLE_SERVER) { /* Reincarnation in the reverse direction: reopen and * reverse client/server roles. */ ct->proto.dccp.role[dir] = CT_DCCP_ROLE_CLIENT; ct->proto.dccp.role[!dir] = CT_DCCP_ROLE_SERVER; } break; case CT_DCCP_RESPOND: if (old_state == CT_DCCP_REQUEST) ct->proto.dccp.handshake_seq = dccp_hdr_seq(dh); break; case CT_DCCP_PARTOPEN: if (old_state == CT_DCCP_RESPOND && type == DCCP_PKT_ACK && dccp_ack_seq(dh) == ct->proto.dccp.handshake_seq) set_bit(IPS_ASSURED_BIT, &ct->status); break; case CT_DCCP_IGNORE: /* * Connection tracking might be out of sync, so we ignore * packets that might establish a new connection and resync * if the server responds with a valid Response. */ if (ct->proto.dccp.last_dir == !dir && ct->proto.dccp.last_pkt == DCCP_PKT_REQUEST && type == DCCP_PKT_RESPONSE) { ct->proto.dccp.role[!dir] = CT_DCCP_ROLE_CLIENT; ct->proto.dccp.role[dir] = CT_DCCP_ROLE_SERVER; ct->proto.dccp.handshake_seq = dccp_hdr_seq(dh); new_state = CT_DCCP_RESPOND; break; } ct->proto.dccp.last_dir = dir; ct->proto.dccp.last_pkt = type; spin_unlock_bh(&ct->lock); if (LOG_INVALID(net, IPPROTO_DCCP)) nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL, "nf_ct_dccp: invalid packet ignored "); return NF_ACCEPT; case CT_DCCP_INVALID: spin_unlock_bh(&ct->lock); if (LOG_INVALID(net, IPPROTO_DCCP)) nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL, "nf_ct_dccp: invalid state transition "); return -NF_ACCEPT; } ct->proto.dccp.last_dir = dir; ct->proto.dccp.last_pkt = type; ct->proto.dccp.state = new_state; spin_unlock_bh(&ct->lock); if (new_state != old_state) nf_conntrack_event_cache(IPCT_PROTOINFO, ct); nf_ct_refresh_acct(ct, ctinfo, skb, timeouts[new_state]); return NF_ACCEPT; } static int dccp_error(struct net *net, struct nf_conn *tmpl, struct sk_buff *skb, unsigned int dataoff, enum ip_conntrack_info *ctinfo, u_int8_t pf, unsigned int hooknum) { struct dccp_hdr _dh, *dh; unsigned int dccp_len = skb->len - dataoff; unsigned int cscov; const char *msg; dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &_dh); if (dh == NULL) { msg = "nf_ct_dccp: short packet "; goto out_invalid; } if (dh->dccph_doff * 4 < sizeof(struct dccp_hdr) || dh->dccph_doff * 4 > dccp_len) { msg = "nf_ct_dccp: truncated/malformed packet "; goto out_invalid; } cscov = dccp_len; if (dh->dccph_cscov) { cscov = (dh->dccph_cscov - 1) * 4; if (cscov > dccp_len) { msg = "nf_ct_dccp: bad checksum coverage "; goto out_invalid; } } if (net->ct.sysctl_checksum && hooknum == NF_INET_PRE_ROUTING && nf_checksum_partial(skb, hooknum, dataoff, cscov, IPPROTO_DCCP, pf)) { msg = "nf_ct_dccp: bad checksum "; goto out_invalid; } if (dh->dccph_type >= DCCP_PKT_INVALID) { msg = "nf_ct_dccp: reserved packet type "; goto out_invalid; } return NF_ACCEPT; out_invalid: if (LOG_INVALID(net, IPPROTO_DCCP)) nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL, "%s", msg); return -NF_ACCEPT; } static void dccp_print_tuple(struct seq_file *s, const struct nf_conntrack_tuple *tuple) { seq_printf(s, "sport=%hu dport=%hu ", ntohs(tuple->src.u.dccp.port), ntohs(tuple->dst.u.dccp.port)); } static void dccp_print_conntrack(struct seq_file *s, struct nf_conn *ct) { seq_printf(s, "%s ", dccp_state_names[ct->proto.dccp.state]); } #if IS_ENABLED(CONFIG_NF_CT_NETLINK) static int dccp_to_nlattr(struct sk_buff *skb, struct nlattr *nla, struct nf_conn *ct) { struct nlattr *nest_parms; spin_lock_bh(&ct->lock); nest_parms = nla_nest_start(skb, CTA_PROTOINFO_DCCP | NLA_F_NESTED); if (!nest_parms) goto nla_put_failure; if (nla_put_u8(skb, CTA_PROTOINFO_DCCP_STATE, ct->proto.dccp.state) || nla_put_u8(skb, CTA_PROTOINFO_DCCP_ROLE, ct->proto.dccp.role[IP_CT_DIR_ORIGINAL]) || nla_put_be64(skb, CTA_PROTOINFO_DCCP_HANDSHAKE_SEQ, cpu_to_be64(ct->proto.dccp.handshake_seq), CTA_PROTOINFO_DCCP_PAD)) goto nla_put_failure; nla_nest_end(skb, nest_parms); spin_unlock_bh(&ct->lock); return 0; nla_put_failure: spin_unlock_bh(&ct->lock); return -1; } static const struct nla_policy dccp_nla_policy[CTA_PROTOINFO_DCCP_MAX + 1] = { [CTA_PROTOINFO_DCCP_STATE] = { .type = NLA_U8 }, [CTA_PROTOINFO_DCCP_ROLE] = { .type = NLA_U8 }, [CTA_PROTOINFO_DCCP_HANDSHAKE_SEQ] = { .type = NLA_U64 }, [CTA_PROTOINFO_DCCP_PAD] = { .type = NLA_UNSPEC }, }; static int nlattr_to_dccp(struct nlattr *cda[], struct nf_conn *ct) { struct nlattr *attr = cda[CTA_PROTOINFO_DCCP]; struct nlattr *tb[CTA_PROTOINFO_DCCP_MAX + 1]; int err; if (!attr) return 0; err = nla_parse_nested(tb, CTA_PROTOINFO_DCCP_MAX, attr, dccp_nla_policy); if (err < 0) return err; if (!tb[CTA_PROTOINFO_DCCP_STATE] || !tb[CTA_PROTOINFO_DCCP_ROLE] || nla_get_u8(tb[CTA_PROTOINFO_DCCP_ROLE]) > CT_DCCP_ROLE_MAX || nla_get_u8(tb[CTA_PROTOINFO_DCCP_STATE]) >= CT_DCCP_IGNORE) { return -EINVAL; } spin_lock_bh(&ct->lock); ct->proto.dccp.state = nla_get_u8(tb[CTA_PROTOINFO_DCCP_STATE]); if (nla_get_u8(tb[CTA_PROTOINFO_DCCP_ROLE]) == CT_DCCP_ROLE_CLIENT) { ct->proto.dccp.role[IP_CT_DIR_ORIGINAL] = CT_DCCP_ROLE_CLIENT; ct->proto.dccp.role[IP_CT_DIR_REPLY] = CT_DCCP_ROLE_SERVER; } else { ct->proto.dccp.role[IP_CT_DIR_ORIGINAL] = CT_DCCP_ROLE_SERVER; ct->proto.dccp.role[IP_CT_DIR_REPLY] = CT_DCCP_ROLE_CLIENT; } if (tb[CTA_PROTOINFO_DCCP_HANDSHAKE_SEQ]) { ct->proto.dccp.handshake_seq = be64_to_cpu(nla_get_be64(tb[CTA_PROTOINFO_DCCP_HANDSHAKE_SEQ])); } spin_unlock_bh(&ct->lock); return 0; } static int dccp_nlattr_size(void) { return nla_total_size(0) /* CTA_PROTOINFO_DCCP */ + nla_policy_len(dccp_nla_policy, CTA_PROTOINFO_DCCP_MAX + 1); } #endif #if IS_ENABLED(CONFIG_NF_CT_NETLINK_TIMEOUT) #include <linux/netfilter/nfnetlink.h> #include <linux/netfilter/nfnetlink_cttimeout.h> static int dccp_timeout_nlattr_to_obj(struct nlattr *tb[], struct net *net, void *data) { struct dccp_net *dn = dccp_pernet(net); unsigned int *timeouts = data; int i; /* set default DCCP timeouts. */ for (i=0; i<CT_DCCP_MAX; i++) timeouts[i] = dn->dccp_timeout[i]; /* there's a 1:1 mapping between attributes and protocol states. */ for (i=CTA_TIMEOUT_DCCP_UNSPEC+1; i<CTA_TIMEOUT_DCCP_MAX+1; i++) { if (tb[i]) { timeouts[i] = ntohl(nla_get_be32(tb[i])) * HZ; } } return 0; } static int dccp_timeout_obj_to_nlattr(struct sk_buff *skb, const void *data) { const unsigned int *timeouts = data; int i; for (i=CTA_TIMEOUT_DCCP_UNSPEC+1; i<CTA_TIMEOUT_DCCP_MAX+1; i++) { if (nla_put_be32(skb, i, htonl(timeouts[i] / HZ))) goto nla_put_failure; } return 0; nla_put_failure: return -ENOSPC; } static const struct nla_policy dccp_timeout_nla_policy[CTA_TIMEOUT_DCCP_MAX+1] = { [CTA_TIMEOUT_DCCP_REQUEST] = { .type = NLA_U32 }, [CTA_TIMEOUT_DCCP_RESPOND] = { .type = NLA_U32 }, [CTA_TIMEOUT_DCCP_PARTOPEN] = { .type = NLA_U32 }, [CTA_TIMEOUT_DCCP_OPEN] = { .type = NLA_U32 }, [CTA_TIMEOUT_DCCP_CLOSEREQ] = { .type = NLA_U32 }, [CTA_TIMEOUT_DCCP_CLOSING] = { .type = NLA_U32 }, [CTA_TIMEOUT_DCCP_TIMEWAIT] = { .type = NLA_U32 }, }; #endif /* CONFIG_NF_CT_NETLINK_TIMEOUT */ #ifdef CONFIG_SYSCTL /* template, data assigned later */ static struct ctl_table dccp_sysctl_table[] = { { .procname = "nf_conntrack_dccp_timeout_request", .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "nf_conntrack_dccp_timeout_respond", .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "nf_conntrack_dccp_timeout_partopen", .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "nf_conntrack_dccp_timeout_open", .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "nf_conntrack_dccp_timeout_closereq", .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "nf_conntrack_dccp_timeout_closing", .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "nf_conntrack_dccp_timeout_timewait", .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "nf_conntrack_dccp_loose", .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { } }; #endif /* CONFIG_SYSCTL */ static int dccp_kmemdup_sysctl_table(struct net *net, struct nf_proto_net *pn, struct dccp_net *dn) { #ifdef CONFIG_SYSCTL if (pn->ctl_table) return 0; pn->ctl_table = kmemdup(dccp_sysctl_table, sizeof(dccp_sysctl_table), GFP_KERNEL); if (!pn->ctl_table) return -ENOMEM; pn->ctl_table[0].data = &dn->dccp_timeout[CT_DCCP_REQUEST]; pn->ctl_table[1].data = &dn->dccp_timeout[CT_DCCP_RESPOND]; pn->ctl_table[2].data = &dn->dccp_timeout[CT_DCCP_PARTOPEN]; pn->ctl_table[3].data = &dn->dccp_timeout[CT_DCCP_OPEN]; pn->ctl_table[4].data = &dn->dccp_timeout[CT_DCCP_CLOSEREQ]; pn->ctl_table[5].data = &dn->dccp_timeout[CT_DCCP_CLOSING]; pn->ctl_table[6].data = &dn->dccp_timeout[CT_DCCP_TIMEWAIT]; pn->ctl_table[7].data = &dn->dccp_loose; /* Don't export sysctls to unprivileged users */ if (net->user_ns != &init_user_ns) pn->ctl_table[0].procname = NULL; #endif return 0; } static int dccp_init_net(struct net *net, u_int16_t proto) { struct dccp_net *dn = dccp_pernet(net); struct nf_proto_net *pn = &dn->pn; if (!pn->users) { /* default values */ dn->dccp_loose = 1; dn->dccp_timeout[CT_DCCP_REQUEST] = 2 * DCCP_MSL; dn->dccp_timeout[CT_DCCP_RESPOND] = 4 * DCCP_MSL; dn->dccp_timeout[CT_DCCP_PARTOPEN] = 4 * DCCP_MSL; dn->dccp_timeout[CT_DCCP_OPEN] = 12 * 3600 * HZ; dn->dccp_timeout[CT_DCCP_CLOSEREQ] = 64 * HZ; dn->dccp_timeout[CT_DCCP_CLOSING] = 64 * HZ; dn->dccp_timeout[CT_DCCP_TIMEWAIT] = 2 * DCCP_MSL; } return dccp_kmemdup_sysctl_table(net, pn, dn); } static struct nf_conntrack_l4proto dccp_proto4 __read_mostly = { .l3proto = AF_INET, .l4proto = IPPROTO_DCCP, .name = "dccp", .pkt_to_tuple = dccp_pkt_to_tuple, .invert_tuple = dccp_invert_tuple, .new = dccp_new, .packet = dccp_packet, .get_timeouts = dccp_get_timeouts, .error = dccp_error, .print_tuple = dccp_print_tuple, .print_conntrack = dccp_print_conntrack, #if IS_ENABLED(CONFIG_NF_CT_NETLINK) .to_nlattr = dccp_to_nlattr, .nlattr_size = dccp_nlattr_size, .from_nlattr = nlattr_to_dccp, .tuple_to_nlattr = nf_ct_port_tuple_to_nlattr, .nlattr_tuple_size = nf_ct_port_nlattr_tuple_size, .nlattr_to_tuple = nf_ct_port_nlattr_to_tuple, .nla_policy = nf_ct_port_nla_policy, #endif #if IS_ENABLED(CONFIG_NF_CT_NETLINK_TIMEOUT) .ctnl_timeout = { .nlattr_to_obj = dccp_timeout_nlattr_to_obj, .obj_to_nlattr = dccp_timeout_obj_to_nlattr, .nlattr_max = CTA_TIMEOUT_DCCP_MAX, .obj_size = sizeof(unsigned int) * CT_DCCP_MAX, .nla_policy = dccp_timeout_nla_policy, }, #endif /* CONFIG_NF_CT_NETLINK_TIMEOUT */ .net_id = &dccp_net_id, .init_net = dccp_init_net, }; static struct nf_conntrack_l4proto dccp_proto6 __read_mostly = { .l3proto = AF_INET6, .l4proto = IPPROTO_DCCP, .name = "dccp", .pkt_to_tuple = dccp_pkt_to_tuple, .invert_tuple = dccp_invert_tuple, .new = dccp_new, .packet = dccp_packet, .get_timeouts = dccp_get_timeouts, .error = dccp_error, .print_tuple = dccp_print_tuple, .print_conntrack = dccp_print_conntrack, #if IS_ENABLED(CONFIG_NF_CT_NETLINK) .to_nlattr = dccp_to_nlattr, .nlattr_size = dccp_nlattr_size, .from_nlattr = nlattr_to_dccp, .tuple_to_nlattr = nf_ct_port_tuple_to_nlattr, .nlattr_tuple_size = nf_ct_port_nlattr_tuple_size, .nlattr_to_tuple = nf_ct_port_nlattr_to_tuple, .nla_policy = nf_ct_port_nla_policy, #endif #if IS_ENABLED(CONFIG_NF_CT_NETLINK_TIMEOUT) .ctnl_timeout = { .nlattr_to_obj = dccp_timeout_nlattr_to_obj, .obj_to_nlattr = dccp_timeout_obj_to_nlattr, .nlattr_max = CTA_TIMEOUT_DCCP_MAX, .obj_size = sizeof(unsigned int) * CT_DCCP_MAX, .nla_policy = dccp_timeout_nla_policy, }, #endif /* CONFIG_NF_CT_NETLINK_TIMEOUT */ .net_id = &dccp_net_id, .init_net = dccp_init_net, }; static __net_init int dccp_net_init(struct net *net) { int ret = 0; ret = nf_ct_l4proto_pernet_register(net, &dccp_proto4); if (ret < 0) { pr_err("nf_conntrack_dccp4: pernet registration failed.\n"); goto out; } ret = nf_ct_l4proto_pernet_register(net, &dccp_proto6); if (ret < 0) { pr_err("nf_conntrack_dccp6: pernet registration failed.\n"); goto cleanup_dccp4; } return 0; cleanup_dccp4: nf_ct_l4proto_pernet_unregister(net, &dccp_proto4); out: return ret; } static __net_exit void dccp_net_exit(struct net *net) { nf_ct_l4proto_pernet_unregister(net, &dccp_proto6); nf_ct_l4proto_pernet_unregister(net, &dccp_proto4); } static struct pernet_operations dccp_net_ops = { .init = dccp_net_init, .exit = dccp_net_exit, .id = &dccp_net_id, .size = sizeof(struct dccp_net), }; static int __init nf_conntrack_proto_dccp_init(void) { int ret; ret = register_pernet_subsys(&dccp_net_ops); if (ret < 0) goto out_pernet; ret = nf_ct_l4proto_register(&dccp_proto4); if (ret < 0) goto out_dccp4; ret = nf_ct_l4proto_register(&dccp_proto6); if (ret < 0) goto out_dccp6; return 0; out_dccp6: nf_ct_l4proto_unregister(&dccp_proto4); out_dccp4: unregister_pernet_subsys(&dccp_net_ops); out_pernet: return ret; } static void __exit nf_conntrack_proto_dccp_fini(void) { nf_ct_l4proto_unregister(&dccp_proto6); nf_ct_l4proto_unregister(&dccp_proto4); unregister_pernet_subsys(&dccp_net_ops); } module_init(nf_conntrack_proto_dccp_init); module_exit(nf_conntrack_proto_dccp_fini); MODULE_AUTHOR("Patrick McHardy <[email protected]>"); MODULE_DESCRIPTION("DCCP connection tracking protocol helper"); MODULE_LICENSE("GPL");