repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
josnelihurt/algorithms
|
cpp-src/src/algorithms/hacker-rank/implementation/divisible_sum_pairs.h
|
#include <bits/stdc++.h>
#include <vector>
namespace divisible_sum_pairs{
int divisibleSumPairs(int n, int k, std::vector<int> ar);
}
|
josnelihurt/algorithms
|
cpp-src/src/tools/functions.h
|
int getRandomValue();
|
josnelihurt/algorithms
|
cpp-src/src/data-structures/tree/avl/avl_tree.h
|
<reponame>josnelihurt/algorithms
#pragma once
namespace avl{
struct node{
int val;
struct node* left;
struct node* right;
int ht;
};
//utils functions
int max(int l, int r);
//newNode creates a new instance of the node
node* newNode(int val);
//insert insets a new value into the datastructure
node* insert(node* root, int val);
//getHeight gets the hight of the current tree
int getHeight(node *root);
//deleteNode removes all nodes from the tree
void deleteNode(node *root);
int getBalanceFactor(node* root);
node* RRRotate(node* root);
node* LLRotate(node* root);
node* RLRotate(node* root);
node* LRRotate(node* root);
}
|
josnelihurt/algorithms
|
cpp-src/src/algorithms/hacker-rank/search/icecream_parlor.h
|
<reponame>josnelihurt/algorithms<filename>cpp-src/src/algorithms/hacker-rank/search/icecream_parlor.h
#include <vector>
namespace icecream_parlor{
//Function definition goes here
std::vector<int> icecreamParlor(int m, std::vector<int> arr);
}
|
josnelihurt/algorithms
|
cpp-src/src/algorithms/hacker-rank/implementation/breaking_best_and_worst_records.h
|
#include <bits/stdc++.h>
#include <vector>
namespace breaking_best_and_worst_records{
std::vector<int> breakingRecords(std::vector<int> scores);
}
|
josnelihurt/algorithms
|
cpp-src/src/algorithms/hacker-rank/strings/camelcase.h
|
<filename>cpp-src/src/algorithms/hacker-rank/strings/camelcase.h
#include <string>
namespace camelcase{
//Function definition goes here
int camelcase(std::string s);
}
|
finncyr/Drum_maschine
|
software/DM_final_PIO_solution_bsp/system.h
|
<gh_stars>1-10
/*
* system.h - SOPC Builder system and BSP software package information
*
* Machine generated for CPU 'CPU' in SOPC Builder design 'nios_system'
* SOPC Builder design path: C:/Sciebo/THK/DTS/Drum_maschine/_known_working_sdram/nios_system.sopcinfo
*
* Generated: Thu Jan 23 10:23:12 CET 2020
*/
/*
* DO NOT MODIFY THIS FILE
*
* Changing this file will have subtle consequences
* which will almost certainly lead to a nonfunctioning
* system. If you do modify this file, be aware that your
* changes will be overwritten and lost when this file
* is generated again.
*
* DO NOT MODIFY THIS FILE
*/
/*
* License Agreement
*
* Copyright (c) 2008
* Altera Corporation, San Jose, California, USA.
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* This agreement shall be governed in all respects by the laws of the State
* of California and by the laws of the United States of America.
*/
#ifndef __SYSTEM_H_
#define __SYSTEM_H_
/* Include definitions from linker script generator */
#include "linker.h"
/*
* CPU configuration
*
*/
#define ALT_CPU_ARCHITECTURE "altera_nios2_qsys"
#define ALT_CPU_BIG_ENDIAN 0
#define ALT_CPU_BREAK_ADDR 0xa000020
#define ALT_CPU_CPU_FREQ 50000000u
#define ALT_CPU_CPU_ID_SIZE 1
#define ALT_CPU_CPU_ID_VALUE 0x00000000
#define ALT_CPU_CPU_IMPLEMENTATION "fast"
#define ALT_CPU_DATA_ADDR_WIDTH 0x1d
#define ALT_CPU_DCACHE_LINE_SIZE 0
#define ALT_CPU_DCACHE_LINE_SIZE_LOG2 0
#define ALT_CPU_DCACHE_SIZE 0
#define ALT_CPU_EXCEPTION_ADDR 0x20
#define ALT_CPU_FLUSHDA_SUPPORTED
#define ALT_CPU_FREQ 50000000
#define ALT_CPU_HARDWARE_DIVIDE_PRESENT 1
#define ALT_CPU_HARDWARE_MULTIPLY_PRESENT 1
#define ALT_CPU_HARDWARE_MULX_PRESENT 0
#define ALT_CPU_HAS_DEBUG_CORE 1
#define ALT_CPU_HAS_DEBUG_STUB
#define ALT_CPU_HAS_JMPI_INSTRUCTION
#define ALT_CPU_ICACHE_LINE_SIZE 32
#define ALT_CPU_ICACHE_LINE_SIZE_LOG2 5
#define ALT_CPU_ICACHE_SIZE 4096
#define ALT_CPU_INST_ADDR_WIDTH 0x1c
#define ALT_CPU_NAME "CPU"
#define ALT_CPU_NUM_OF_SHADOW_REG_SETS 0
#define ALT_CPU_RESET_ADDR 0x0
/*
* CPU configuration (with legacy prefix - don't use these anymore)
*
*/
#define NIOS2_BIG_ENDIAN 0
#define NIOS2_BREAK_ADDR 0xa000020
#define NIOS2_CPU_FREQ 50000000u
#define NIOS2_CPU_ID_SIZE 1
#define NIOS2_CPU_ID_VALUE 0x00000000
#define NIOS2_CPU_IMPLEMENTATION "fast"
#define NIOS2_DATA_ADDR_WIDTH 0x1d
#define NIOS2_DCACHE_LINE_SIZE 0
#define NIOS2_DCACHE_LINE_SIZE_LOG2 0
#define NIOS2_DCACHE_SIZE 0
#define NIOS2_EXCEPTION_ADDR 0x20
#define NIOS2_FLUSHDA_SUPPORTED
#define NIOS2_HARDWARE_DIVIDE_PRESENT 1
#define NIOS2_HARDWARE_MULTIPLY_PRESENT 1
#define NIOS2_HARDWARE_MULX_PRESENT 0
#define NIOS2_HAS_DEBUG_CORE 1
#define NIOS2_HAS_DEBUG_STUB
#define NIOS2_HAS_JMPI_INSTRUCTION
#define NIOS2_ICACHE_LINE_SIZE 32
#define NIOS2_ICACHE_LINE_SIZE_LOG2 5
#define NIOS2_ICACHE_SIZE 4096
#define NIOS2_INST_ADDR_WIDTH 0x1c
#define NIOS2_NUM_OF_SHADOW_REG_SETS 0
#define NIOS2_RESET_ADDR 0x0
/*
* Char_LCD_16x2 configuration
*
*/
#define ALT_MODULE_CLASS_Char_LCD_16x2 altera_up_avalon_character_lcd
#define CHAR_LCD_16X2_BASE 0x10003050
#define CHAR_LCD_16X2_IRQ -1
#define CHAR_LCD_16X2_IRQ_INTERRUPT_CONTROLLER_ID -1
#define CHAR_LCD_16X2_NAME "/dev/Char_LCD_16x2"
#define CHAR_LCD_16X2_SPAN 2
#define CHAR_LCD_16X2_TYPE "altera_up_avalon_character_lcd"
/*
* Custom instruction macros
*
*/
#define ALT_CI_FPOINT(n,A,B) __builtin_custom_inii(ALT_CI_FPOINT_N+(n&ALT_CI_FPOINT_N_MASK),(A),(B))
#define ALT_CI_FPOINT_N 0xfc
#define ALT_CI_FPOINT_N_MASK ((1<<2)-1)
/*
* Define for each module class mastered by the CPU
*
*/
#define __ALTERA_AVALON_JTAG_UART
#define __ALTERA_AVALON_NEW_SDRAM_CONTROLLER
#define __ALTERA_AVALON_PIO
#define __ALTERA_AVALON_SYSID_QSYS
#define __ALTERA_AVALON_TIMER
#define __ALTERA_NIOS2_QSYS
#define __ALTERA_NIOS_CUSTOM_INSTR_FLOATING_POINT
#define __ALTERA_UP_AVALON_CHARACTER_LCD
#define __ALTERA_UP_AVALON_IRDA
#define __ALTERA_UP_AVALON_PARALLEL_PORT
#define __ALTERA_UP_AVALON_RS232
#define __ALTERA_UP_AVALON_SRAM
#define __ALTERA_UP_AVALON_USB
#define __ALTERA_UP_FLASH_MEMORY_IP_CORE_AVALON_INTERFACE
#define __ALTERA_UP_SD_CARD_AVALON_INTERFACE
/*
* Expansion_JP5 configuration
*
*/
#define ALT_MODULE_CLASS_Expansion_JP5 altera_up_avalon_parallel_port
#define EXPANSION_JP5_BASE 0x10000060
#define EXPANSION_JP5_IRQ 11
#define EXPANSION_JP5_IRQ_INTERRUPT_CONTROLLER_ID 0
#define EXPANSION_JP5_NAME "/dev/Expansion_JP5"
#define EXPANSION_JP5_SPAN 16
#define EXPANSION_JP5_TYPE "altera_up_avalon_parallel_port"
/*
* Flash_flash_data configuration
*
*/
#define ALT_MODULE_CLASS_Flash_flash_data Altera_UP_Flash_Memory_IP_Core_Avalon_Interface
#define FLASH_FLASH_DATA_BASE 0xc000000
#define FLASH_FLASH_DATA_IRQ -1
#define FLASH_FLASH_DATA_IRQ_INTERRUPT_CONTROLLER_ID -1
#define FLASH_FLASH_DATA_NAME "/dev/Flash_flash_data"
#define FLASH_FLASH_DATA_SPAN 8388608
#define FLASH_FLASH_DATA_TYPE "Altera_UP_Flash_Memory_IP_Core_Avalon_Interface"
/*
* Flash_flash_erase_control configuration
*
*/
#define ALT_MODULE_CLASS_Flash_flash_erase_control Altera_UP_Flash_Memory_IP_Core_Avalon_Interface
#define FLASH_FLASH_ERASE_CONTROL_BASE 0xbff0000
#define FLASH_FLASH_ERASE_CONTROL_IRQ -1
#define FLASH_FLASH_ERASE_CONTROL_IRQ_INTERRUPT_CONTROLLER_ID -1
#define FLASH_FLASH_ERASE_CONTROL_NAME "/dev/Flash_flash_erase_control"
#define FLASH_FLASH_ERASE_CONTROL_SPAN 4
#define FLASH_FLASH_ERASE_CONTROL_TYPE "Altera_UP_Flash_Memory_IP_Core_Avalon_Interface"
/*
* Green_LEDs configuration
*
*/
#define ALT_MODULE_CLASS_Green_LEDs altera_up_avalon_parallel_port
#define GREEN_LEDS_BASE 0x10000010
#define GREEN_LEDS_IRQ -1
#define GREEN_LEDS_IRQ_INTERRUPT_CONTROLLER_ID -1
#define GREEN_LEDS_NAME "/dev/Green_LEDs"
#define GREEN_LEDS_SPAN 16
#define GREEN_LEDS_TYPE "altera_up_avalon_parallel_port"
/*
* HEX3_HEX0 configuration
*
*/
#define ALT_MODULE_CLASS_HEX3_HEX0 altera_up_avalon_parallel_port
#define HEX3_HEX0_BASE 0x10000020
#define HEX3_HEX0_IRQ -1
#define HEX3_HEX0_IRQ_INTERRUPT_CONTROLLER_ID -1
#define HEX3_HEX0_NAME "/dev/HEX3_HEX0"
#define HEX3_HEX0_SPAN 16
#define HEX3_HEX0_TYPE "altera_up_avalon_parallel_port"
/*
* HEX7_HEX4 configuration
*
*/
#define ALT_MODULE_CLASS_HEX7_HEX4 altera_up_avalon_parallel_port
#define HEX7_HEX4_BASE 0x10000030
#define HEX7_HEX4_IRQ -1
#define HEX7_HEX4_IRQ_INTERRUPT_CONTROLLER_ID -1
#define HEX7_HEX4_NAME "/dev/HEX7_HEX4"
#define HEX7_HEX4_SPAN 16
#define HEX7_HEX4_TYPE "altera_up_avalon_parallel_port"
/*
* Interval_Timer configuration
*
*/
#define ALT_MODULE_CLASS_Interval_Timer altera_avalon_timer
#define INTERVAL_TIMER_ALWAYS_RUN 0
#define INTERVAL_TIMER_BASE 0x10002000
#define INTERVAL_TIMER_COUNTER_SIZE 32
#define INTERVAL_TIMER_FIXED_PERIOD 0
#define INTERVAL_TIMER_FREQ 50000000
#define INTERVAL_TIMER_IRQ 0
#define INTERVAL_TIMER_IRQ_INTERRUPT_CONTROLLER_ID 0
#define INTERVAL_TIMER_LOAD_VALUE 6249999
#define INTERVAL_TIMER_MULT 0.0010
#define INTERVAL_TIMER_NAME "/dev/Interval_Timer"
#define INTERVAL_TIMER_PERIOD 125.0
#define INTERVAL_TIMER_PERIOD_UNITS "ms"
#define INTERVAL_TIMER_RESET_OUTPUT 0
#define INTERVAL_TIMER_SNAPSHOT 1
#define INTERVAL_TIMER_SPAN 32
#define INTERVAL_TIMER_TICKS_PER_SEC 8.0
#define INTERVAL_TIMER_TIMEOUT_PULSE_OUTPUT 0
#define INTERVAL_TIMER_TYPE "altera_avalon_timer"
/*
* IrDA configuration
*
*/
#define ALT_MODULE_CLASS_IrDA altera_up_avalon_irda
#define IRDA_BASE 0x10001020
#define IRDA_IRQ 9
#define IRDA_IRQ_INTERRUPT_CONTROLLER_ID 0
#define IRDA_NAME "/dev/IrDA"
#define IRDA_SPAN 8
#define IRDA_TYPE "altera_up_avalon_irda"
/*
* JTAG_UART configuration
*
*/
#define ALT_MODULE_CLASS_JTAG_UART altera_avalon_jtag_uart
#define JTAG_UART_BASE 0x10001000
#define JTAG_UART_IRQ 8
#define JTAG_UART_IRQ_INTERRUPT_CONTROLLER_ID 0
#define JTAG_UART_NAME "/dev/JTAG_UART"
#define JTAG_UART_READ_DEPTH 64
#define JTAG_UART_READ_THRESHOLD 8
#define JTAG_UART_SPAN 8
#define JTAG_UART_TYPE "altera_avalon_jtag_uart"
#define JTAG_UART_WRITE_DEPTH 64
#define JTAG_UART_WRITE_THRESHOLD 8
/*
* Pushbuttons configuration
*
*/
#define ALT_MODULE_CLASS_Pushbuttons altera_up_avalon_parallel_port
#define PUSHBUTTONS_BASE 0x10000050
#define PUSHBUTTONS_IRQ 1
#define PUSHBUTTONS_IRQ_INTERRUPT_CONTROLLER_ID 0
#define PUSHBUTTONS_NAME "/dev/Pushbuttons"
#define PUSHBUTTONS_SPAN 16
#define PUSHBUTTONS_TYPE "altera_up_avalon_parallel_port"
/*
* Red_LEDs configuration
*
*/
#define ALT_MODULE_CLASS_Red_LEDs altera_up_avalon_parallel_port
#define RED_LEDS_BASE 0x10000000
#define RED_LEDS_IRQ -1
#define RED_LEDS_IRQ_INTERRUPT_CONTROLLER_ID -1
#define RED_LEDS_NAME "/dev/Red_LEDs"
#define RED_LEDS_SPAN 16
#define RED_LEDS_TYPE "altera_up_avalon_parallel_port"
/*
* SDRAM configuration
*
*/
#define ALT_MODULE_CLASS_SDRAM altera_avalon_new_sdram_controller
#define SDRAM_BASE 0x0
#define SDRAM_CAS_LATENCY 3
#define SDRAM_CONTENTS_INFO
#define SDRAM_INIT_NOP_DELAY 0.0
#define SDRAM_INIT_REFRESH_COMMANDS 2
#define SDRAM_IRQ -1
#define SDRAM_IRQ_INTERRUPT_CONTROLLER_ID -1
#define SDRAM_IS_INITIALIZED 1
#define SDRAM_NAME "/dev/SDRAM"
#define SDRAM_POWERUP_DELAY 100.0
#define SDRAM_REFRESH_PERIOD 15.625
#define SDRAM_REGISTER_DATA_IN 1
#define SDRAM_SDRAM_ADDR_WIDTH 0x19
#define SDRAM_SDRAM_BANK_WIDTH 2
#define SDRAM_SDRAM_COL_WIDTH 10
#define SDRAM_SDRAM_DATA_WIDTH 32
#define SDRAM_SDRAM_NUM_BANKS 4
#define SDRAM_SDRAM_NUM_CHIPSELECTS 1
#define SDRAM_SDRAM_ROW_WIDTH 13
#define SDRAM_SHARED_DATA 0
#define SDRAM_SIM_MODEL_BASE 0
#define SDRAM_SPAN 134217728
#define SDRAM_STARVATION_INDICATOR 0
#define SDRAM_TRISTATE_BRIDGE_SLAVE ""
#define SDRAM_TYPE "altera_avalon_new_sdram_controller"
#define SDRAM_T_AC 5.5
#define SDRAM_T_MRD 3
#define SDRAM_T_RCD 20.0
#define SDRAM_T_RFC 70.0
#define SDRAM_T_RP 20.0
#define SDRAM_T_WR 14.0
/*
* SD_Card configuration
*
*/
#define ALT_MODULE_CLASS_SD_Card Altera_UP_SD_Card_Avalon_Interface
#define SD_CARD_BASE 0xb000000
#define SD_CARD_IRQ -1
#define SD_CARD_IRQ_INTERRUPT_CONTROLLER_ID -1
#define SD_CARD_NAME "/dev/SD_Card"
#define SD_CARD_SPAN 1024
#define SD_CARD_TYPE "Altera_UP_SD_Card_Avalon_Interface"
/*
* SRAM configuration
*
*/
#define ALT_MODULE_CLASS_SRAM altera_up_avalon_sram
#define SRAM_BASE 0x8000000
#define SRAM_IRQ -1
#define SRAM_IRQ_INTERRUPT_CONTROLLER_ID -1
#define SRAM_NAME "/dev/SRAM"
#define SRAM_SPAN 2097152
#define SRAM_TYPE "altera_up_avalon_sram"
/*
* Serial_Port configuration
*
*/
#define ALT_MODULE_CLASS_Serial_Port altera_up_avalon_rs232
#define SERIAL_PORT_BASE 0x10001010
#define SERIAL_PORT_IRQ 10
#define SERIAL_PORT_IRQ_INTERRUPT_CONTROLLER_ID 0
#define SERIAL_PORT_NAME "/dev/Serial_Port"
#define SERIAL_PORT_SPAN 8
#define SERIAL_PORT_TYPE "altera_up_avalon_rs232"
/*
* Slider_Switches configuration
*
*/
#define ALT_MODULE_CLASS_Slider_Switches altera_up_avalon_parallel_port
#define SLIDER_SWITCHES_BASE 0x10000040
#define SLIDER_SWITCHES_IRQ -1
#define SLIDER_SWITCHES_IRQ_INTERRUPT_CONTROLLER_ID -1
#define SLIDER_SWITCHES_NAME "/dev/Slider_Switches"
#define SLIDER_SWITCHES_SPAN 16
#define SLIDER_SWITCHES_TYPE "altera_up_avalon_parallel_port"
/*
* System configuration
*
*/
#define ALT_DEVICE_FAMILY "Cyclone IV E"
#define ALT_IRQ_BASE NULL
#define ALT_LEGACY_INTERRUPT_API_PRESENT
#define ALT_LOG_PORT "/dev/null"
#define ALT_LOG_PORT_BASE 0x0
#define ALT_LOG_PORT_DEV null
#define ALT_LOG_PORT_TYPE ""
#define ALT_NUM_EXTERNAL_INTERRUPT_CONTROLLERS 0
#define ALT_NUM_INTERNAL_INTERRUPT_CONTROLLERS 1
#define ALT_NUM_INTERRUPT_CONTROLLERS 1
#define ALT_STDERR "/dev/JTAG_UART"
#define ALT_STDERR_BASE 0x10001000
#define ALT_STDERR_DEV JTAG_UART
#define ALT_STDERR_IS_JTAG_UART
#define ALT_STDERR_PRESENT
#define ALT_STDERR_TYPE "altera_avalon_jtag_uart"
#define ALT_STDIN "/dev/JTAG_UART"
#define ALT_STDIN_BASE 0x10001000
#define ALT_STDIN_DEV JTAG_UART
#define ALT_STDIN_IS_JTAG_UART
#define ALT_STDIN_PRESENT
#define ALT_STDIN_TYPE "altera_avalon_jtag_uart"
#define ALT_STDOUT "/dev/JTAG_UART"
#define ALT_STDOUT_BASE 0x10001000
#define ALT_STDOUT_DEV JTAG_UART
#define ALT_STDOUT_IS_JTAG_UART
#define ALT_STDOUT_PRESENT
#define ALT_STDOUT_TYPE "altera_avalon_jtag_uart"
#define ALT_SYSTEM_NAME "nios_system"
/*
* USB configuration
*
*/
#define ALT_MODULE_CLASS_USB altera_up_avalon_usb
#define USB_BASE 0x10000110
#define USB_IRQ 2
#define USB_IRQ_INTERRUPT_CONTROLLER_ID 0
#define USB_NAME "/dev/USB"
#define USB_SPAN 16
#define USB_TYPE "altera_up_avalon_usb"
/*
* hal configuration
*
*/
#define ALT_MAX_FD 32
#define ALT_SYS_CLK INTERVAL_TIMER
#define ALT_TIMESTAMP_CLK none
/*
* pio_0 configuration
*
*/
#define ALT_MODULE_CLASS_pio_0 altera_avalon_pio
#define PIO_0_BASE 0x10000120
#define PIO_0_BIT_CLEARING_EDGE_REGISTER 0
#define PIO_0_BIT_MODIFYING_OUTPUT_REGISTER 0
#define PIO_0_CAPTURE 0
#define PIO_0_DATA_WIDTH 16
#define PIO_0_DO_TEST_BENCH_WIRING 0
#define PIO_0_DRIVEN_SIM_VALUE 0
#define PIO_0_EDGE_TYPE "NONE"
#define PIO_0_FREQ 50000000
#define PIO_0_HAS_IN 1
#define PIO_0_HAS_OUT 1
#define PIO_0_HAS_TRI 0
#define PIO_0_IRQ -1
#define PIO_0_IRQ_INTERRUPT_CONTROLLER_ID -1
#define PIO_0_IRQ_TYPE "NONE"
#define PIO_0_NAME "/dev/pio_0"
#define PIO_0_RESET_VALUE 0
#define PIO_0_SPAN 16
#define PIO_0_TYPE "altera_avalon_pio"
/*
* pio_1 configuration
*
*/
#define ALT_MODULE_CLASS_pio_1 altera_avalon_pio
#define PIO_1_BASE 0x10000130
#define PIO_1_BIT_CLEARING_EDGE_REGISTER 0
#define PIO_1_BIT_MODIFYING_OUTPUT_REGISTER 0
#define PIO_1_CAPTURE 0
#define PIO_1_DATA_WIDTH 16
#define PIO_1_DO_TEST_BENCH_WIRING 0
#define PIO_1_DRIVEN_SIM_VALUE 0
#define PIO_1_EDGE_TYPE "NONE"
#define PIO_1_FREQ 50000000
#define PIO_1_HAS_IN 1
#define PIO_1_HAS_OUT 1
#define PIO_1_HAS_TRI 0
#define PIO_1_IRQ -1
#define PIO_1_IRQ_INTERRUPT_CONTROLLER_ID -1
#define PIO_1_IRQ_TYPE "NONE"
#define PIO_1_NAME "/dev/pio_1"
#define PIO_1_RESET_VALUE 0
#define PIO_1_SPAN 16
#define PIO_1_TYPE "altera_avalon_pio"
/*
* pio_2 configuration
*
*/
#define ALT_MODULE_CLASS_pio_2 altera_avalon_pio
#define PIO_2_BASE 0x10000140
#define PIO_2_BIT_CLEARING_EDGE_REGISTER 0
#define PIO_2_BIT_MODIFYING_OUTPUT_REGISTER 0
#define PIO_2_CAPTURE 0
#define PIO_2_DATA_WIDTH 8
#define PIO_2_DO_TEST_BENCH_WIRING 0
#define PIO_2_DRIVEN_SIM_VALUE 0
#define PIO_2_EDGE_TYPE "NONE"
#define PIO_2_FREQ 50000000
#define PIO_2_HAS_IN 1
#define PIO_2_HAS_OUT 1
#define PIO_2_HAS_TRI 0
#define PIO_2_IRQ -1
#define PIO_2_IRQ_INTERRUPT_CONTROLLER_ID -1
#define PIO_2_IRQ_TYPE "NONE"
#define PIO_2_NAME "/dev/pio_2"
#define PIO_2_RESET_VALUE 0
#define PIO_2_SPAN 16
#define PIO_2_TYPE "altera_avalon_pio"
/*
* sysid configuration
*
*/
#define ALT_MODULE_CLASS_sysid altera_avalon_sysid_qsys
#define SYSID_BASE 0x10002020
#define SYSID_ID 0
#define SYSID_IRQ -1
#define SYSID_IRQ_INTERRUPT_CONTROLLER_ID -1
#define SYSID_NAME "/dev/sysid"
#define SYSID_SPAN 8
#define SYSID_TIMESTAMP 1579770612
#define SYSID_TYPE "altera_avalon_sysid_qsys"
#endif /* __SYSTEM_H_ */
|
finncyr/Drum_maschine
|
software/DM_PIO_Ansatz_bsp/drivers/inc/altera_up_avalon_usb_ptd.h
|
<reponame>finncyr/Drum_maschine<gh_stars>1-10
/******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2007 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
* Altera does not recommend, suggest or require that this reference design *
* file be used in conjunction or combination with any other product. *
* *
******************************************************************************/
#ifndef __ALTERA_UP_AVALON_USB_PTD_H__
#define __ALTERA_UP_AVALON_USB_PTD_H__
#include "alt_types.h"
#include "altera_up_avalon_usb.h"
struct ptd_struct {
alt_u16 actualBytes;
alt_u8 completionCode;
alt_u8 active;
alt_u8 toggle;
alt_u16 maxPacketSize;
alt_u8 endpointNumber;
alt_u8 last; // For ISTL (ISO) only
alt_u8 speed;
alt_u16 totalBytes;
alt_u8 paired; // For ATL only
alt_u8 pingPong; // For ATL only
alt_u8 dirToken;
alt_u8 functionAddress;
alt_u8 pollingRate; // For Interrupt only
alt_u8 startingFrame; // For ISTL (ISO) and Interrupt
};
// Completion Codes
#define ALT_UP_USB_PTD_CC_NoError 0x0
#define ALT_UP_USB_PTD_CC_CRC 0x1
#define ALT_UP_USB_PTD_CC_BitStuffing 0x2
#define ALT_UP_USB_PTD_CC_DataToggleMismatch 0x3
#define ALT_UP_USB_PTD_CC_Stall 0x4
#define ALT_UP_USB_PTD_CC_DeviceNotResponding 0x5
#define ALT_UP_USB_PTD_CC_PIDCheckFailure 0x6
#define ALT_UP_USB_PTD_CC_UnexpectedPID 0x7
#define ALT_UP_USB_PTD_CC_DataOverrun 0x8
#define ALT_UP_USB_PTD_CC_DataUnderrun 0x9
#define ALT_UP_USB_PTD_CC_BufferOverrun 0xC
#define ALT_UP_USB_PTD_CC_BufferUnderrun 0xD
#define ALT_UP_USB_PTD_CC_Initial 0xF
void alt_up_usb_init_ptd(struct ptd_struct * ptd, unsigned int dirToken, alt_u8 endpointNumber, alt_u16 packetSize, alt_u8 toggle, alt_u8 functionAddress, alt_u8 portNumber);
//void alt_up_usb_init_ptd (struct ptd_struct * ptd, alt_u16 packetSize, alt_u8 functionAddress, alt_u8 portNumber);
//int alt_up_usb_make_ptd (struct ptd_struct * ptd, alt_u8 dirToken, alt_u8 endpointNumber, alt_u16 maxPacketSize, alt_u8 toggle, alt_u8 functionAddress, alt_u8 portNumber)
void alt_up_usb_convert_ptd_to_array(unsigned int * ptd_array, struct ptd_struct * ptd);
#endif /* __ALTERA_UP_AVALON_USB_PTD_H__ */
|
finncyr/Drum_maschine
|
software/DM_final_PIO_solution/main.c
|
/*
* main.c
*
* This is the Main IO Functions of the Drum Maschine
*
* 7Segments from Left to Right: [7][6] [5][4] [3][2][1][0]
* 7-6:
* 5-4: Bank Number
* 3-0: BPM
*
* Buttons from Left to Right: [1] [2] [3] [4]
* 1: Play/Pause
* 2: BPM up/down in Steps of 10 (Range: 60-240)
* 3: Bank Change 1-4 and save pattern
* 4: Reset
*
* Created on: 14.12.2019
* Author: <NAME>
*/
#include "main.h"
void init(
alt_up_parallel_port_dev *PIO0,
alt_up_parallel_port_dev *PIO1,
alt_up_parallel_port_dev *PIO2) {
alt_up_parallel_port_write_data(PIO0, 0x0000);
alt_up_parallel_port_write_data(PIO0, 0x78);
alt_up_parallel_port_write_data(PIO0, 0x00);
}
int main(void) {
alt_up_parallel_port_dev *greenLEDs, *redLEDs, *hex3to0, *hex7to4, *PIO0, *PIO1, *PIO2;
static int currentBank = 0;
static alt_u16 currentBPM = 120;
static alt_u8 playState = 0; // Data which indicates if the maschine is generating an output signal
alt_u8 keys = 0; // Data that contains the current loops pushbutton setting
alt_u32 switches = 0; // Data that contains the current loops switch setting
alt_u32 pattern[4] = {0}; // Data which contains all Patterns, created from switches
alt_u32 BPMData = 0; // Data that will be written to HEX3to0
static unsigned char digit1 = 0, digit2 = 0, digit3 = 0; // Variables for computing Digit by Digit of the BPM Value
static unsigned char digit_data[10] = {191, 134, 219, 207, 230, 237, 253, 135, 255, 239}; // Bit-Data for 7-Segment Digits
// Initialization of HAL Ports
greenLEDs = alt_up_parallel_port_open_dev(GREEN_LEDS_NAME);
redLEDs = alt_up_parallel_port_open_dev(RED_LEDS_NAME);
hex3to0 = alt_up_parallel_port_open_dev(HEX3_HEX0_NAME);
hex7to4 = alt_up_parallel_port_open_dev(HEX7_HEX4_NAME);
PIO0 = alt_up_parallel_port_open_dev(PIO_0_NAME);
PIO1 = alt_up_parallel_port_open_dev(PIO_1_NAME);
PIO2 = alt_up_parallel_port_open_dev(PIO_2_NAME);
//Initiating functions
init(PIO0, PIO1, PIO2);
///////////////
// MAIN LOOP //
///////////////
while(1){
//Grab Inputs
keys = IORD_ALT_UP_PARALLEL_PORT_DATA(PUSHBUTTONS_BASE);
switches = IORD_ALT_UP_PARALLEL_PORT_DATA(SLIDER_SWITCHES_BASE);
//Play/Pause Button
if(keys & (1<<1)){ // ^ => XOR
if(playState != 0) playState = 0;
else playState = 255;
while(keys & (1<<1)){keys = IORD_ALT_UP_PARALLEL_PORT_DATA(PUSHBUTTONS_BASE);}
}
//BPM Up/Down
if (keys & (1<<2)){
if(switches & (1<<0)){
currentBPM = currentBPM + STEP_BPM;
}
else{
currentBPM = currentBPM - STEP_BPM;
}
if(currentBPM >= (MAX_BPM + STEP_BPM)) currentBPM = MAX_BPM;
if(currentBPM <= (MIN_BPM - STEP_BPM)) currentBPM = MIN_BPM;
while(keys & (1<<2)){keys = IORD_ALT_UP_PARALLEL_PORT_DATA(PUSHBUTTONS_BASE);}
}
//Process Bank Change and save pattern
if(keys & (1<<3)){
pattern[currentBank] = switches;
currentBank++;
if (currentBank > 3) currentBank = 0;
while(keys & (1<<3)){keys = IORD_ALT_UP_PARALLEL_PORT_DATA(PUSHBUTTONS_BASE);}
}
/////////////////////////
// Output to RAM //
/////////////////////////
int i = 0;
for(i = 0; i<=3; i++){
IOWR_ALT_UP_PARALLEL_PORT_DATA(SRAM_BASE + OFFSET_PATTERN + (i*16), pattern[i]);
}
IOWR_ALT_UP_PARALLEL_PORT_DATA(SRAM_BASE + OFFSET_BPM, currentBPM);
IOWR_ALT_UP_PARALLEL_PORT_DATA(SRAM_BASE + OFFSET_PLAYPAUSE, playState);
//Output pattern 1 to PIO
alt_u16 test = pattern[0]>>2;
IOWR_ALT_UP_PARALLEL_PORT_DATA(PIO_0_BASE, test);
IOWR_ALT_UP_PARALLEL_PORT_DATA(PIO_1_BASE, currentBPM);
IOWR_ALT_UP_PARALLEL_PORT_DATA(PIO_2_BASE, playState);
//Output to red LEDs
IOWR_ALT_UP_PARALLEL_PORT_DATA(RED_LEDS_BASE, pattern[currentBank]);
//Output to green LEDs
IOWR_ALT_UP_PARALLEL_PORT_DATA(GREEN_LEDS_BASE, playState);
//Output to 7Segment Display
digit1 = currentBPM / 100;
digit2 = (currentBPM % 100) / 10;
digit3 = ((currentBPM % 100) % 10);
BPMData = (digit_data[digit1]<<16) + (digit_data[digit2]<<8) + (digit_data[digit3]<<0);
IOWR_ALT_UP_PARALLEL_PORT_DATA(HEX3_HEX0_BASE,BPMData);
IOWR_ALT_UP_PARALLEL_PORT_DATA(HEX7_HEX4_BASE,digit_data[currentBank]<<0);
}
}
|
finncyr/Drum_maschine
|
software/DM_PIO_Ansatz_bsp/drivers/src/altera_up_avalon_usb_low_level_driver.c
|
/******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2007 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
* Altera does not recommend, suggest or require that this reference design *
* file be used in conjunction or combination with any other product. *
* *
******************************************************************************/
#include <altera_up_avalon_usb_regs.h>
#include <altera_up_avalon_usb.h>
#include <altera_up_avalon_usb_low_level_driver.h>
/*
* Host Controller Function
*/
void alt_up_usb_hc_reg_write_16(alt_up_usb_dev * usb_device, unsigned char reg, unsigned int value) {
IOWR_ALT_UP_USB_HC_COMMAND(usb_device->base, reg | 0x80);
IOWR_ALT_UP_USB_HC_DATA(usb_device->base, value);
return;
}
void alt_up_usb_hc_reg_write_32(alt_up_usb_dev * usb_device, unsigned char reg, unsigned long value) {
unsigned int low_word;
unsigned int hi_word;
low_word = (value)&0x0000FFFF;
hi_word = ((value)&0xFFFF0000) >> 16;
IOWR_ALT_UP_USB_HC_COMMAND(usb_device->base, reg | 0x80);
IOWR_ALT_UP_USB_HC_DATA(usb_device->base, low_word);
IOWR_ALT_UP_USB_HC_DATA(usb_device->base, hi_word);
return;
}
unsigned int alt_up_usb_hc_reg_read_16(alt_up_usb_dev * usb_device, unsigned char reg) {
unsigned int result;
IOWR_ALT_UP_USB_HC_COMMAND(usb_device->base, reg);
result = IORD_ALT_UP_USB_HC_DATA(usb_device->base);
return result;
}
unsigned long alt_up_usb_hc_reg_read_32(alt_up_usb_dev * usb_device, unsigned char reg) {
unsigned int result_l, result_h;
unsigned long result;
IOWR_ALT_UP_USB_HC_COMMAND(usb_device->base, reg);
result_l = IORD_ALT_UP_USB_HC_DATA(usb_device->base);
result_h = IORD_ALT_UP_USB_HC_DATA(usb_device->base);
result = result_h;
result = result << 16;
result = result + result_l;
return (result);
}
void alt_up_usb_hc_write_atl(alt_up_usb_dev * usb_device, unsigned int *a_ptr, unsigned int data_size) {
int count = 0;
alt_up_usb_hc_reg_write_16(usb_device, ALT_UP_USB_HcTransferCounter, data_size * 2);
IOWR_ALT_UP_USB_HC_COMMAND(usb_device->base, ALT_UP_USB_HcATLBufferPort | 0x80);
do {
IOWR_ALT_UP_USB_HC_DATA(usb_device->base, *(a_ptr + count));
} while (++count < data_size);
return;
}
void alt_up_usb_hc_read_atl(alt_up_usb_dev * usb_device, unsigned int *a_ptr, unsigned int data_size) {
int count = 0;
alt_up_usb_hc_reg_write_16(usb_device, ALT_UP_USB_HcTransferCounter, data_size * 2);
IOWR_ALT_UP_USB_HC_COMMAND(usb_device->base, ALT_UP_USB_HcATLBufferPort);
do {
*(a_ptr + count) = IORD_ALT_UP_USB_HC_DATA(usb_device->base);
} while (++count < data_size);
return;
}
void alt_up_usb_hc_write_int(alt_up_usb_dev * usb_device, unsigned int *a_ptr, unsigned int data_size) {
int count = 0;
alt_up_usb_hc_reg_write_16(usb_device, ALT_UP_USB_HcTransferCounter, data_size * 2);
IOWR_ALT_UP_USB_HC_COMMAND(usb_device->base, ALT_UP_USB_HcINTLBufferPort | 0x80);
do {
IOWR_ALT_UP_USB_HC_DATA(usb_device->base, *(a_ptr + count));
} while (++count < data_size);
return;
}
void alt_up_usb_hc_read_int(alt_up_usb_dev * usb_device, unsigned int *a_ptr, unsigned int data_size) {
int count = 0;
alt_up_usb_hc_reg_write_16(usb_device, ALT_UP_USB_HcTransferCounter, data_size * 2);
IOWR_ALT_UP_USB_HC_COMMAND(usb_device->base, ALT_UP_USB_HcINTLBufferPort);
do {
*(a_ptr + count) = IORD_ALT_UP_USB_HC_DATA(usb_device->base);
} while (++count < data_size);
return;
}
void alt_up_usb_hc_direct_address_write(alt_up_usb_dev * usb_device, unsigned int *a_ptr, unsigned int start_addr, unsigned int data_size) {
int count = 0;
unsigned long HcDirectAddrLen_value;
HcDirectAddrLen_value = (unsigned long) (start_addr & 0x7fff);
HcDirectAddrLen_value |= (unsigned long) (data_size << 16);
alt_up_usb_hc_reg_write_32(usb_device, ALT_UP_USB_HcDirectAddressLength, HcDirectAddrLen_value);
IOWR_ALT_UP_USB_HC_COMMAND(usb_device->base, ALT_UP_USB_HcDirectAddressData | 0x80);
do {
IOWR_ALT_UP_USB_HC_DATA(usb_device->base, *(a_ptr + count));
} while (++count < data_size);
return;
}
void alt_up_usb_hc_direct_address_read(alt_up_usb_dev * usb_device, unsigned int *a_ptr, unsigned int start_addr, unsigned int data_size) {
int count = 0;
unsigned long HcDirectAddrLen_value;
HcDirectAddrLen_value = (unsigned long) (start_addr & 0x7fff);
HcDirectAddrLen_value |= (unsigned long) (data_size << 16);
alt_up_usb_hc_reg_write_32(usb_device, ALT_UP_USB_HcDirectAddressLength, HcDirectAddrLen_value);
IOWR_ALT_UP_USB_HC_COMMAND(usb_device->base, ALT_UP_USB_HcDirectAddressData);
do {
*(a_ptr + count) = IORD_ALT_UP_USB_HC_DATA(usb_device->base);
} while (++count < data_size);
return;
}
/*
* Device Controller Function
*/
void alt_up_usb_dc_reg_write_16(alt_up_usb_dev * usb_device, unsigned char reg, unsigned int value) {
IOWR_ALT_UP_USB_DC_COMMAND(usb_device->base, reg | 0x80);
IOWR_ALT_UP_USB_DC_DATA(usb_device->base, value);
return;
}
void alt_up_usb_dc_reg_write_32(alt_up_usb_dev * usb_device, unsigned char reg, unsigned long value) {
unsigned int low_word;
unsigned int hi_word;
low_word = (value)&0x0000FFFF;
hi_word = ((value)&0xFFFF0000) >> 16;
IOWR_ALT_UP_USB_DC_COMMAND(usb_device->base, reg | 0x80);
IOWR_ALT_UP_USB_DC_DATA(usb_device->base, low_word);
IOWR_ALT_UP_USB_DC_DATA(usb_device->base, hi_word);
return;
}
unsigned int alt_up_usb_dc_reg_read_16(alt_up_usb_dev * usb_device, unsigned char reg) {
unsigned int result;
IOWR_ALT_UP_USB_DC_COMMAND(usb_device->base, reg);
result = IORD_ALT_UP_USB_DC_DATA(usb_device->base);
return result;
}
unsigned long alt_up_usb_dc_reg_read_32(alt_up_usb_dev * usb_device, unsigned char reg) {
unsigned int result_l, result_h;
unsigned long result;
IOWR_ALT_UP_USB_DC_COMMAND(usb_device->base, reg);
result_l = IORD_ALT_UP_USB_DC_DATA(usb_device->base);
result_h = IORD_ALT_UP_USB_DC_DATA(usb_device->base);
result = result_h;
result = result << 16;
result = result + result_l;
return (result);
}
/*
int usb_register_port_1_write (unsigned int usb_device->base, unsigned int reg, unsigned int value)
{
IOWR_ALTERA_UP_AVALON_ETHERNET_PORT_1_INDEX(usb_device->base, reg);
IOWR_ALTERA_UP_AVALON_ETHERNET_PORT_1_DATA (usb_device->base, value);
return 0;
}
int usb_register_read (unsigned int usb_device->base, unsigned int reg)
{
return 0;
}
int usb_phy_write (alt_up_usb_dev * usb_device, unsigned char reg, unsigned int value);
int usb_phy_write (unsigned int usb_device->base, unsigned int reg, unsigned int value)
{
return 0;
}
*/
|
finncyr/Drum_maschine
|
software/DM_PIO_Ansatz_bsp/drivers/inc/altera_up_avalon_usb_regs.h
|
/******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2007 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
******************************************************************************/
/*
* Register definitions for the ISP1362 USB chip used on the
* DE2 Development and Education Board
*/
#include <io.h>
#ifndef __ALTERA_UP_AVALON_USB_REGS_H_
#define __ALTERA_UP_AVALON_USB_REGS_H_
#define ALTERA_UP_AVALON_USB_CHIP_ID 0x3630
/*
* USB Host Control Data Register
*/
#define ALT_UP_USB_HC_DATA_REG 0
#define IOADDR_ALT_UP_USB_HC_DATA(base) \
__IO_CALC_ADDRESS_NATIVE(base, ALT_UP_USB_HC_DATA_REG)
#define IORD_ALT_UP_USB_HC_DATA(base) \
IORD(base, ALT_UP_USB_HC_DATA_REG)
#define IOWR_ALT_UP_USB_HC_DATA(base,data) \
IOWR(base, ALT_UP_USB_HC_DATA_REG, data)
/*
* USB Host Control Command Register
*/
#define ALT_UP_USB_HC_COMMAND_REG 1
#define IOADDR_ALT_UP_USB_HC_COMMAND(base) \
__IO_CALC_ADDRESS_NATIVE(base, ALT_UP_USB_HC_COMMAND_REG)
#define IOWR_ALT_UP_USB_HC_COMMAND(base,data) \
IOWR(base, ALT_UP_USB_HC_COMMAND_REG, data)
/*
* USB Device Control Data Register
*/
#define ALT_UP_USB_DC_DATA_REG 2
#define IOADDR_ALT_UP_USB_DC_DATA(base) \
__IO_CALC_ADDRESS_NATIVE(base, ALT_UP_USB_DC_DATA_REG)
#define IORD_ALT_UP_USB_DC_DATA(base) \
IORD(base, ALT_UP_USB_DC_DATA_REG)
#define IOWR_ALT_UP_USB_DC_DATA(base,data) \
IOWR(base, ALT_UP_USB_DC_DATA_REG, data)
/*
* USB Device Control Command Register
*/
#define ALT_UP_USB_DC_COMMAND_REG 3
#define IOADDR_ALT_UP_USB_DC_COMMAND(base) \
__IO_CALC_ADDRESS_NATIVE(base, ALT_UP_USB_DC_COMMAND_REG)
#define IOWR_ALT_UP_USB_DC_COMMAND(base,data) \
IOWR(base, ALT_UP_USB_DC_COMMAND_REG, data)
/*
* USB Host Control Register Addresses
*/
// Control and Status Registers
#define ALT_UP_USB_HcRevision 0x00
#define ALT_UP_USB_HcControl 0x01
#define ALT_UP_USB_HcCommandStatus 0x02
#define ALT_UP_USB_HcInterruptStatus 0x03
#define ALT_UP_USB_HcInterruptEnable 0x04
#define ALT_UP_USB_HcInterruptDisable 0x05
// Frame Counter Registers
#define ALT_UP_USB_HcFmInterval 0x0D
#define ALT_UP_USB_HcFmRemaining 0x0E
#define ALT_UP_USB_HcFmNumber 0x0F
#define ALT_UP_USB_HcLSThreshold 0x11
// Root Hub Registers
#define ALT_UP_USB_HcRhDescriptorA 0x12
#define ALT_UP_USB_HcRhDescriptorB 0x13
#define ALT_UP_USB_HcRhStatus 0x14
#define ALT_UP_USB_HcRhPortStatus1 0x15
#define ALT_UP_USB_HcRhPortStatus2 0x16
// DMA and Interrupt Control Registers
#define ALT_UP_USB_HcHardwareConfiguration 0x20
#define ALT_UP_USB_HcDMAConfiguration 0x21
#define ALT_UP_USB_HcTransferCounter 0x22
#define ALT_UP_USB_HcuPInterrupt 0x24
#define ALT_UP_USB_HcuPInterruptEnable 0x25
// Miscellaneous Registers
#define ALT_UP_USB_HcChipID 0x27
#define ALT_UP_USB_HcScratch 0x28
#define ALT_UP_USB_HcSoftwareReset 0x29
// Buffer RAM Control Registers
#define ALT_UP_USB_HcBufferStatus 0x2C
#define ALT_UP_USB_HcDirectAddressLength 0x32
#define ALT_UP_USB_HcDirectAddressData 0x45
// ISO Transfer Registers
#define ALT_UP_USB_HcISTLBufferSize 0x30
#define ALT_UP_USB_HcISTL0BufferPort 0x40
#define ALT_UP_USB_HcISTL1BufferPort 0x42
#define ALT_UP_USB_HcISTLToggleRate 0x47
// Interrupt Transfer Registers
#define ALT_UP_USB_HcINTLBufferSize 0x33
#define ALT_UP_USB_HcINTLBufferPort 0x43
#define ALT_UP_USB_HcINTLBlkSize 0x53
#define ALT_UP_USB_HcINTLPTDDoneMap 0x17
#define ALT_UP_USB_HcINTLPTDSkipMap 0x18
#define ALT_UP_USB_HcINTLLastPTD 0x19
#define ALT_UP_USB_HcINTLCurrentActivePTD 0x1A
// Aperiodic Transfer Registers
#define ALT_UP_USB_HcATLBufferSize 0x34
#define ALT_UP_USB_HcATLBufferPort 0x44
#define ALT_UP_USB_HcATLBlkSize 0x54
#define ALT_UP_USB_HcATLPTDDoneMap 0x1B
#define ALT_UP_USB_HcATLPTDSkipMap 0x1C
#define ALT_UP_USB_HcATLLastPTD 0x1D
#define ALT_UP_USB_HcATLCurrentActivePTD 0x1E
#define ALT_UP_USB_HcATLPTDDoneThresholdCount 0x51
#define ALT_UP_USB_HcATLPTDDoneThresholdTimeOut 0x52
// OTG Control Registers
#define ALT_UP_USB_OTGControl 0x62
#define ALT_UP_USB_OTGStatus 0x67
#define ALT_UP_USB_OTGInterrupt 0x68
#define ALT_UP_USB_OTGInterruptEnable 0x69
#define ALT_UP_USB_OTGTimer 0x6A
#define ALT_UP_USB_OTGAltTimer 0x6C
#endif /* __ALTERA_UP_AVALON_USB_REGS_H_ */
|
finncyr/Drum_maschine
|
software/DM_PIO_Ansatz_bsp/drivers/src/altera_up_avalon_usb_ptd.c
|
/******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2007 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
* Altera does not recommend, suggest or require that this reference design *
* file be used in conjunction or combination with any other product. *
* *
******************************************************************************/
#include "alt_types.h"
#include "altera_up_avalon_usb_high_level_driver.h"
#include "altera_up_avalon_usb_ptd.h"
void alt_up_usb_init_ptd(struct ptd_struct * ptd, unsigned int dirToken, alt_u8 endpointNumber, alt_u16 packetSize, alt_u8 toggle, alt_u8 functionAddress, alt_u8 portNumber) {
ptd->actualBytes = 0;
ptd->completionCode = ALT_UP_USB_PTD_CC_Initial;
ptd->active = 1;
ptd->toggle = toggle;
ptd->maxPacketSize = packetSize;
ptd->endpointNumber = endpointNumber;
ptd->last = 0;
ptd->speed = alt_up_usb_get_port_speed(portNumber);
ptd->totalBytes = packetSize;
ptd->paired = 0;
ptd->pingPong = 0;
ptd->dirToken = dirToken;
ptd->functionAddress = functionAddress;
ptd->pollingRate = 0;
ptd->startingFrame = 0;
return;
}
// For PTD array format, see ISP1362 porduct datasheet page 42
void alt_up_usb_convert_ptd_to_array(unsigned int * ptd_array, struct ptd_struct * ptd) {
ptd_array[0] =
((ptd->completionCode & 0xf) << 12) |
((ptd->active & 0x1) << 11) |
((ptd->toggle & 0x1) << 10) |
(ptd->actualBytes & 0x3FF);
ptd_array[1] =
((ptd->endpointNumber & 0xF) << 12) |
((ptd->last & 0x1) << 11) |
((ptd->speed & 0x1) << 10) |
(ptd->maxPacketSize & 0x3FF);
ptd_array[2] =
((ptd->paired & 0x1) << 15) |
((ptd->pingPong & 0x1) << 14) |
((ptd->dirToken & 0x3) << 10) |
(ptd->totalBytes & 0x3FF);
ptd_array[3] =
((ptd->pollingRate & 0x7) << 13) |
((ptd->startingFrame & 0xFF) << 8) |
(ptd->functionAddress & 0x7F);
return;
}
|
finncyr/Drum_maschine
|
software/DM_PIO_Ansatz_bsp/drivers/inc/altera_up_avalon_character_lcd.h
|
#ifndef __ALTERA_UP_AVALON_CHARACTER_LCD_H__
#define __ALTERA_UP_AVALON_CHARACTER_LCD_H__
#include <stddef.h>
#include "sys/alt_dev.h"
#include "sys/alt_alarm.h"
#include "sys/alt_warning.h"
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/*
* Device structure definition. Each instance of the driver uses one
* of these structures to hold its associated state.
*/
typedef struct alt_up_character_lcd_dev {
/// @brief character mode device structure
/// @sa Developing Device Drivers for the HAL in Nios II Software Developer's Handbook
alt_dev dev;
/// @brief the base address of the device
unsigned int base;
} alt_up_character_lcd_dev;
// system functions
/**
* @brief Initialize the LCD by clearing its display
*
* @param lcd -- struct for the LCD Controller device
*
**/
void alt_up_character_lcd_init(alt_up_character_lcd_dev *lcd);
// direct operation functions
/**
* @brief Open the character LCD device specified by <em> name </em>
*
* @param name -- the character LCD name. For example, if the character LCD name in SOPC Builder is "character_lcd_0", then <em> name </em> should be "/dev/character_lcd_0"
*
* @return The corresponding device structure, or NULL if the device is not found
**/
alt_up_character_lcd_dev* alt_up_character_lcd_open_dev(const char* name);
/**
* @brief Write the characters in the buffer pointed to by <em> ptr </em> to
* the LCD, starting from where the current cursor points to
*
* @param lcd -- struct for the LCD Controller device
* @param ptr -- the pointer to the char buffer
* @param len -- the length of the char buffer
*
* @return nothing
**/
void alt_up_character_lcd_write(alt_up_character_lcd_dev *lcd, const char *ptr, unsigned int len);
/**
* @brief Write the characters in the NULL-terminated string to the LCD
*
* @param lcd -- struct for the LCD Controller device
* @param ptr -- the pointer to the char buffer
*
* @return nothing
**/
void alt_up_character_lcd_string(alt_up_character_lcd_dev *lcd, const char *ptr);
/**
* reserved for future use
*
**/
int alt_up_character_lcd_write_fd(alt_fd *fd, const char *ptr, int len);
/**
* @brief Set the cursor position
*
* @param lcd -- struct for the LCD Controller device
* @param x_pos -- x coordinate ( 0 to 15, from left to right )
* @param y_pos -- y coordinate ( 0 for the top row, 1 for the bottom row )
*
* @return 0 for success
**/
int alt_up_character_lcd_set_cursor_pos(alt_up_character_lcd_dev *lcd, unsigned x_pos,
unsigned y_pos);
/**
* @brief Shift the cursor to left or right
*
* @param lcd -- struct for the LCD Controller device
* @param x_right_shift_offset -- the number of spaces to shift to the right. If the offset is
* negative, then the cursor shifts to the left.
*
* @return nothing
**/
void alt_up_character_lcd_shift_cursor(alt_up_character_lcd_dev *lcd, int x_right_shift_offset);
/**
* @brief Shift the entire display to left or right
*
* @param lcd -- struct for the LCD Controller device
* @param x_right_shift_offset -- the number of spaces to shift to the right. If the offset is
* negative, then the display shifts to the left.
*
* @return nothing
**/
void alt_up_character_lcd_shift_display(alt_up_character_lcd_dev *lcd, int x_right_shift_offset);
/**
* @brief Erase the character at the specified coordinate
*
* @param lcd -- struct for the LCD Controller device
* @param x_pos -- x coordinate ( 0 to 15, from left to right )
* @param y_pos -- y coordinate ( 0 for the top row, 1 for the bottom row )
*
* @return 0 for success
**/
int alt_up_character_lcd_erase_pos(alt_up_character_lcd_dev *lcd, unsigned x_pos, unsigned y_pos);
/**
* @brief Turn off the cursor
*
* @param lcd -- struct for the LCD Controller device
*
* @return nothing
**/
void alt_up_character_lcd_cursor_off(alt_up_character_lcd_dev *lcd);
/**
* @brief Turn on the cursor
*
* @param lcd -- struct for the LCD Controller device
*
* @return nothing
**/
void alt_up_character_lcd_cursor_blink_on(alt_up_character_lcd_dev *lcd);
/*
* Macros used by alt_sys_init
*/
#define ALTERA_UP_AVALON_CHARACTER_LCD_INSTANCE(name, device) \
static alt_up_character_lcd_dev device = \
{ \
{ \
ALT_LLIST_ENTRY, \
name##_NAME, \
NULL, /* open */ \
NULL, /* close */ \
NULL, /* read */ \
alt_up_character_lcd_write_fd, \
NULL, /* lseek */ \
NULL, /* fstat */ \
NULL, /* ioctl */ \
}, \
name##_BASE, \
}
#define ALTERA_UP_AVALON_CHARACTER_LCD_INIT(name, device) \
{ \
alt_up_character_lcd_init(&device); \
alt_dev_reg(&device.dev); \
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __ALTERA_UP_AVALON_CHARACTER_LCD_H__ */
|
finncyr/Drum_maschine
|
software/DM_PIO_Ansatz_bsp/drivers/src/altera_up_avalon_irda.c
|
/******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2007 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
* Altera does not recommend, suggest or require that this reference design *
* file be used in conjunction or combination with any other product. *
* *
******************************************************************************/
#include <errno.h>
#include <priv/alt_file.h>
#include "altera_up_avalon_irda.h"
#include "altera_up_avalon_irda_regs.h"
void alt_up_irda_enable_read_interrupt(alt_up_irda_dev *irda)
{
alt_u32 ctrl_reg;
ctrl_reg = IORD_ALT_UP_IRDA_CONTROL(irda->base);
// set RE to 1 while maintaining other bits the same
ctrl_reg |= ALT_UP_IRDA_CONTROL_RE_MSK;
IOWR_ALT_UP_IRDA_CONTROL(irda->base, ctrl_reg);
}
void alt_up_irda_disable_read_interrupt(alt_up_irda_dev *irda)
{
alt_u32 ctrl_reg;
ctrl_reg = IORD_ALT_UP_IRDA_CONTROL(irda->base);
// set RE to 0 while maintaining other bits the same
ctrl_reg &= ~ALT_UP_IRDA_CONTROL_RE_MSK;
IOWR_ALT_UP_IRDA_CONTROL(irda->base, ctrl_reg);
}
unsigned alt_up_irda_get_used_space_in_read_FIFO(alt_up_irda_dev *irda)
{
alt_u16 ravail = 0;
// we can only read the 16 bits for RAVAIL --- a read of DATA will discard the data
// ravail = IORD_16DIRECT(IOADDR_ALT_UP_IRDA_DATA(irda->base), 2);
// return ravail;
ravail = IORD_ALT_UP_IRDA_RAVAIL(irda->base);
return (ravail & ALT_UP_IRDA_RAVAIL_MSK) >> ALT_UP_IRDA_RAVAIL_OFST;
}
unsigned alt_up_irda_get_available_space_in_write_FIFO(alt_up_irda_dev *irda)
{
alt_u32 ctrl_reg;
ctrl_reg = IORD_ALT_UP_IRDA_CONTROL(irda->base);
return (ctrl_reg & ALT_UP_IRDA_CONTROL_WSPACE_MSK) >> ALT_UP_IRDA_CONTROL_WSPACE_OFST;
}
int alt_up_irda_check_parity(alt_u32 data_reg)
{
unsigned parity_error = (data_reg & ALT_UP_IRDA_DATA_PE_MSK) >> ALT_UP_IRDA_DATA_PE_OFST;
return (parity_error ? -1 : 0);
}
int alt_up_irda_write_data(alt_up_irda_dev *irda, alt_u8 data)
{
alt_u32 data_reg;
data_reg = IORD_ALT_UP_IRDA_DATA(irda->base);
// we can write directly without thinking about other bit fields for this
// case ONLY, because only DATA field of the data register is writable
IOWR_ALT_UP_IRDA_DATA(irda->base, (data>>ALT_UP_IRDA_DATA_DATA_OFST) & ALT_UP_IRDA_DATA_DATA_MSK);
return 0;
}
int alt_up_irda_read_data(alt_up_irda_dev *irda, alt_u8 *data, alt_u8 *parity_error)
{
alt_u32 data_reg;
data_reg = IORD_ALT_UP_IRDA_DATA(irda->base);
*data = (data_reg & ALT_UP_IRDA_DATA_DATA_MSK) >> ALT_UP_IRDA_DATA_DATA_OFST;
*parity_error = alt_up_irda_check_parity(data_reg);
return (((data_reg & ALT_UP_IRDA_DATA_RVALID_MSK) >> ALT_UP_IRDA_DATA_RVALID_OFST) - 1);
}
int alt_up_irda_read_fd (alt_fd* fd, char* ptr, int len)
{
alt_up_irda_dev *irda = (alt_up_irda_dev*)fd->dev;
int count = 0;
alt_u8 parity_error;
while(len--)
{
if (alt_up_irda_read_data(irda, ptr++, &parity_error)==0)
count++;
else
break;
}
return count;
}
int alt_up_irda_write_fd (alt_fd* fd, const char* ptr, int len)
{
alt_up_irda_dev *irda = (alt_up_irda_dev*)fd->dev;
int count = 0;
while(len--)
{
if (alt_up_irda_write_data(irda, ptr++)==0)
count++;
else
break;
}
return count;
}
alt_up_irda_dev* alt_up_irda_open_dev(const char* name)
{
// find the device from the device list
// (see altera_hal/HAL/inc/priv/alt_file.h
// and altera_hal/HAL/src/alt_find_dev.c
// for details)
alt_up_irda_dev *dev = (alt_up_irda_dev*)alt_find_dev(name, &alt_dev_list);
return dev;
}
|
finncyr/Drum_maschine
|
software/DM_PIO_Ansatz_bsp/drivers/src/Altera_UP_SD_Card_Avalon_Interface.c
|
/******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2006 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
******************************************************************************/
#include <errno.h>
#include <priv/alt_file.h>
#include <io.h>
#include <stdio.h>
#include <string.h>
#include "Altera_UP_SD_Card_Avalon_Interface.h"
///////////////////////////////////////////////////////////////////////////
// Local Define Statements
///////////////////////////////////////////////////////////////////////////
#define CHAR_TO_UPPER(ch) ((char) (((ch >= 'a') && (ch <= 'z')) ? ((ch-'a')+'A'): ch))
// Data Buffer Address
#define SD_CARD_BUFFER(base, x) (base + x)
// 128-bit Card Identification Number
#define SD_CARD_CID(base, x) (base + 0x0200 + x)
// 128-bit Card Specific Data Register
#define SD_CARD_CSD(base, x) (base + 0x0210 + x)
// 32-bit Operating Conditions Register
#define SD_CARD_OCR(base) (base + 0x0220)
// 32-bit Card Status Register
#define SD_CARD_STATUS(base) (base + 0x0224)
// 16-bit Relative Card Address Register
#define SD_CARD_RCA(base) (base + 0x0228)
// 32-bit Card Argument Register
#define SD_CARD_ARGUMENT(base) (base + 0x022C)
// 16-bit Card Command Register
#define SD_CARD_COMMAND(base) (base + 0x0230)
// 16-bit Card Auxiliary Status Register
#define SD_CARD_AUX_STATUS(base) (base + 0x0234)
// 32-bit R1 Response Register
#define SD_CARD_R1_RESPONSE(base) (base + 0x0238)
#define CMD_READ_BLOCK 17
#define CMD_WRITE_BLOCK 24
// FAT 12/16 related stuff
//#define BOOT_SECTOR_DATA_SIZE 0x005A
#define MAX_FILES_OPENED 20
/******************************************************************************/
/****** LOCAL DATA STRUCTURES ***********************************************/
/******************************************************************************/
typedef struct s_FAT_12_16_boot_sector {
unsigned char jump_instruction[3];
char OEM_name[8];
unsigned short int sector_size_in_bytes;
unsigned char sectors_per_cluster;
unsigned short int reserved_sectors;
unsigned char number_of_FATs;
unsigned short int max_number_of_dir_entires;
unsigned short int number_of_sectors_in_partition;
unsigned char media_descriptor;
unsigned short int number_of_sectors_per_table;
unsigned short int number_of_sectors_per_track;
unsigned short int number_of_heads;
unsigned int number_of_hidden_sectors;
unsigned int total_sector_count_if_above_32MB;
unsigned char drive_number;
unsigned char current_head;
unsigned char boot_signature;
unsigned char volume_id[4];
char volume_label[11];
unsigned char file_system_type[8];
unsigned char bits_for_cluster_index;
unsigned int first_fat_sector_offset;
unsigned int second_fat_sector_offset;
unsigned int root_directory_sector_offset;
unsigned int data_sector_offset;
} t_FAT_12_16_boot_sector;
typedef struct s_file_record {
unsigned char name[8];
unsigned char extension[3];
unsigned char attributes;
unsigned short int create_time;
unsigned short int create_date;
unsigned short int last_access_date;
unsigned short int last_modified_time;
unsigned short int last_modified_date;
unsigned short int start_cluster_index;
unsigned int file_size_in_bytes;
/* The following fields are only used when a file has been created or opened. */
unsigned int current_cluster_index;
unsigned int current_sector_in_cluster;
unsigned int current_byte_position;
// Absolute location of the file record on the SD Card.
unsigned int file_record_cluster;
unsigned int file_record_sector_in_cluster;
short int file_record_offset;
// Is this record in use and has the file been modified.
unsigned int home_directory_cluster;
bool modified;
bool in_use;
} t_file_record;
typedef struct s_find_data {
unsigned int directory_root_cluster; // 0 means root directory.
unsigned int current_cluster_index;
unsigned int current_sector_in_cluster;
short int file_index_in_sector;
bool valid;
} t_find_data;
///////////////////////////////////////////////////////////////////////////
// Local Variables
///////////////////////////////////////////////////////////////////////////
bool initialized = false;
bool is_sd_card_formated_as_FAT16 = false;
volatile short int *aux_status_register = NULL;
volatile int *status_register = NULL;
volatile short int *CSD_register_w0 = NULL;
volatile short int *command_register = NULL;
volatile int *command_argument_register = NULL;
volatile char *buffer_memory = NULL;
int fat_partition_offset_in_512_byte_sectors = 0;
int fat_partition_size_in_512_byte_sectors = 0;
t_FAT_12_16_boot_sector boot_sector_data;
alt_up_sd_card_dev *device_pointer = NULL;
// Pointers to currently opened files.
t_file_record active_files[MAX_FILES_OPENED];
bool current_sector_modified = false;
unsigned int current_sector_index = 0;
t_find_data search_data;
///////////////////////////////////////////////////////////////////////////
// Local Functions
///////////////////////////////////////////////////////////////////////////
bool Write_Sector_Data(int sector_index, int partition_offset)
// This function writes a sector at the specified address on the SD Card.
{
bool result = false;
if (alt_up_sd_card_is_Present())
{
short int reg_state = 0xff;
/* Multiply sector offset by sector size to get the address. Sector size is 512. Also,
* the SD card reads data in 512 byte chunks, so the address must be a multiple of 512. */
IOWR_32DIRECT(command_argument_register, 0, (sector_index + partition_offset)*512);
IOWR_16DIRECT(command_register, 0, CMD_WRITE_BLOCK);
do {
reg_state = (short int) IORD_16DIRECT(aux_status_register,0);
} while ((reg_state & 0x04)!=0);
// Make sure the request did not time out.
if ((reg_state & 0x10) == 0)
{
result = true;
current_sector_modified = false;
current_sector_index = sector_index+partition_offset;
}
}
return result;
}
bool Save_Modified_Sector()
// If the sector has been modified, then save it to the SD Card.
{
bool result = true;
if (current_sector_modified)
{
result = Write_Sector_Data(current_sector_index, 0);
}
return result;
}
bool Read_Sector_Data(int sector_index, int partition_offset)
// This function reads a sector at the specified address on the SD Card.
{
bool result = false;
if (alt_up_sd_card_is_Present())
{
short int reg_state = 0xff;
/* Write data to the SD card if the current buffer is out of date. */
if (current_sector_modified)
{
if (Write_Sector_Data(current_sector_index, 0) == false)
{
return false;
}
}
/* Multiply sector offset by sector size to get the address. Sector size is 512. Also,
* the SD card reads data in 512 byte chunks, so the address must be a multiple of 512. */
IOWR_32DIRECT(command_argument_register, 0, (sector_index + partition_offset)*512);
IOWR_16DIRECT(command_register, 0, CMD_READ_BLOCK);
do {
reg_state = (short int) IORD_16DIRECT(aux_status_register,0);
} while ((reg_state & 0x04)!=0);
// Make sure the request did not time out.
if ((reg_state & 0x10) == 0)
{
result = true;
current_sector_modified = false;
current_sector_index = sector_index+partition_offset;
}
}
return result;
}
bool get_cluster_flag(unsigned int cluster_index, unsigned short int *flag)
// Read a cluster flag.
{
unsigned int sector_index = (cluster_index / 256) + fat_partition_offset_in_512_byte_sectors;
sector_index = sector_index + boot_sector_data.first_fat_sector_offset;
if (sector_index != current_sector_index)
{
if (Read_Sector_Data(sector_index, 0) == false)
{
return false;
}
}
*flag = (unsigned short int) IORD_16DIRECT(device_pointer->base, 2*(cluster_index % 256));
return true;
}
bool mark_cluster(unsigned int cluster_index, short int flag, bool first_fat)
// Place a marker on the specified cluster in a given FAT.
{
unsigned int sector_index = (cluster_index / 256) + fat_partition_offset_in_512_byte_sectors;
if (first_fat)
{
sector_index = sector_index + boot_sector_data.first_fat_sector_offset;
}
else
{
sector_index = sector_index + boot_sector_data.second_fat_sector_offset;
}
if (sector_index != current_sector_index)
{
if (Read_Sector_Data(sector_index, 0) == false)
{
return false;
}
}
IOWR_16DIRECT(device_pointer->base, 2*(cluster_index % 256), flag);
current_sector_modified = true;
return true;
}
bool Check_for_Master_Boot_Record(void)
// This function reads the first 512 bytes on the SD Card. This data should
// contain the Master Boot Record. If it does, then print
// relevant information and return true. Otherwise, return false.
{
bool result = false;
int index;
int end, offset, partition_size;
/* Load the first 512 bytes of data from SD card. */
if (Read_Sector_Data(0, 0))
{
end = (short int) IORD_16DIRECT(device_pointer->base,0x1fe);
// Check if the end of the sector contains an end string 0xaa55.
if ((end & 0x0000ffff) == 0x0000aa55)
{
// Check four partition entries and see if any are valid
for (index = 0; index < 4; index++)
{
int partition_data_offset = (index * 16) + 0x01be;
char type;
// Read Partition type
type = (unsigned char) IORD_8DIRECT(device_pointer->base,partition_data_offset + 0x04);
// Check if this is an FAT parition
if ((type == 1) || (type == 4) || (type == 6) || (type == 14))
{
// Get partition offset and size.
offset = (((unsigned short int) IORD_16DIRECT(device_pointer->base,partition_data_offset + 0x0A)) << 16) | ((unsigned short int) IORD_16DIRECT(device_pointer->base,partition_data_offset + 0x08));
partition_size = (((unsigned short int) IORD_16DIRECT(device_pointer->base,partition_data_offset + 0x0E)) << 16) | ((unsigned short int) IORD_16DIRECT(device_pointer->base,partition_data_offset + 0x0C));
// Check if the partition is valid
if (partition_size > 0)
{
result = true;
fat_partition_size_in_512_byte_sectors = partition_size;
fat_partition_offset_in_512_byte_sectors = offset;
break;
}
}
}
}
}
return result;
}
bool Read_File_Record_At_Offset(int offset, t_file_record *record, unsigned int cluster_index, unsigned int sector_in_cluster)
// This function reads a file record
{
bool result = false;
if (((offset & 0x01f) == 0) && (alt_up_sd_card_is_Present()) && (is_sd_card_formated_as_FAT16))
{
int counter;
for (counter = 0; counter < 8; counter++)
{
record->name[counter] = (char) IORD_8DIRECT(device_pointer->base, offset+counter);
}
for (counter = 0; counter < 3; counter++)
{
record->extension[counter] = (char) IORD_8DIRECT(device_pointer->base, offset+counter+8);
}
record->attributes = (char) IORD_8DIRECT(device_pointer->base, offset+11);
/* Ignore reserved bytes at locations 12 and 13. */
record->create_time = (unsigned short int) IORD_16DIRECT(device_pointer->base, offset+14);
record->create_date = (unsigned short int) IORD_16DIRECT(device_pointer->base, offset+16);
record->last_access_date = (unsigned short int) IORD_16DIRECT(device_pointer->base, offset+18);
/* Ignore reserved bytes at locations 20 and 21. */
record->last_modified_time = (unsigned short int) IORD_16DIRECT(device_pointer->base, offset+22);
record->last_modified_date = (unsigned short int) IORD_16DIRECT(device_pointer->base, offset+24);
record->start_cluster_index = (unsigned short int) IORD_16DIRECT(device_pointer->base, offset+26);
record->file_size_in_bytes = (unsigned int) IORD_32DIRECT(device_pointer->base, offset+28);
record->file_record_cluster = cluster_index;
record->file_record_sector_in_cluster = sector_in_cluster;
record->file_record_offset = offset;
result = true;
}
return result;
}
bool Write_File_Record_At_Offset(int offset, t_file_record *record)
// This function writes a file record at a given offset. The offset is given in bytes.
{
bool result = false;
if (((offset & 0x01f) == 0) && (alt_up_sd_card_is_Present()) && (is_sd_card_formated_as_FAT16))
{
int counter;
for (counter = 0; counter < 8; counter=counter+2)
{
short int two_chars = (short int) record->name[counter+1];
two_chars = two_chars << 8;
two_chars = two_chars | record->name[counter];
IOWR_16DIRECT(device_pointer->base, offset+counter, two_chars);
}
for (counter = 0; counter < 3; counter++)
{
IOWR_8DIRECT(device_pointer->base, offset+counter+8, record->extension[counter]);
}
IOWR_8DIRECT(device_pointer->base, offset+11, record->attributes);
/* Ignore reserved bytes at locations 12 and 13. */
IOWR_16DIRECT(device_pointer->base, offset+14, record->create_time);
IOWR_16DIRECT(device_pointer->base, offset+16, record->create_date);
IOWR_16DIRECT(device_pointer->base, offset+18, record->last_access_date);
/* Ignore reserved bytes at locations 20 and 21. */
IOWR_16DIRECT(device_pointer->base, offset+22, record->last_modified_time);
IOWR_16DIRECT(device_pointer->base, offset+24, record->last_modified_date);
IOWR_16DIRECT(device_pointer->base, offset+26, record->start_cluster_index);
IOWR_32DIRECT(device_pointer->base, offset+28, record->file_size_in_bytes);
current_sector_modified = true;
result = true;
}
return result;
}
bool Check_for_DOS_FAT(int FAT_partition_start_sector)
// This function reads the boot sector for the FAT file system on the SD Card.
// The offset_address should point to the sector on the card where the boot sector is located.
// The sector number is specified either in the master Boot Record, or is 0 by default for a purely FAT
// based file system. If the specified sector contains a FAT boot sector, then this function prints the
// relevant information and returns 1. Otherwise, it returns 0.
{
bool result = false;
int counter = 0;
short int end;
result = Read_Sector_Data(0, FAT_partition_start_sector);
end = (short int) IORD_16DIRECT(device_pointer->base, 0x1fe);
if (((end & 0x0000ffff) == 0x0000aa55) && (result))
{
int num_clusters = 0;
boot_sector_data.jump_instruction[0] = (char) IORD_8DIRECT(device_pointer->base, 0);
boot_sector_data.jump_instruction[1] = (char) IORD_8DIRECT(device_pointer->base, 1);
boot_sector_data.jump_instruction[2] = (char) IORD_8DIRECT(device_pointer->base, 2);
for (counter = 0; counter < 8; counter++)
{
boot_sector_data.OEM_name[counter] = (char) IORD_8DIRECT(device_pointer->base, 3+counter);
}
boot_sector_data.sector_size_in_bytes = (((unsigned char) IORD_8DIRECT(device_pointer->base, 12)) << 8 ) | ((char) IORD_8DIRECT(device_pointer->base, 11));
boot_sector_data.sectors_per_cluster = ((unsigned char) IORD_8DIRECT(device_pointer->base, 13));
boot_sector_data.reserved_sectors = ((unsigned short int) IORD_16DIRECT(device_pointer->base, 14));
boot_sector_data.number_of_FATs = ((unsigned char) IORD_8DIRECT(device_pointer->base, 16));
boot_sector_data.max_number_of_dir_entires = (((unsigned short int)(((unsigned char) IORD_8DIRECT(device_pointer->base, 18)))) << 8 ) | ((unsigned char) IORD_8DIRECT(device_pointer->base, 17));
boot_sector_data.number_of_sectors_in_partition = (((unsigned short int)(((unsigned char) IORD_8DIRECT(device_pointer->base, 20)))) << 8 ) | ((unsigned char) IORD_8DIRECT(device_pointer->base, 19));
boot_sector_data.media_descriptor = ((unsigned char) IORD_8DIRECT(device_pointer->base, 21));
boot_sector_data.number_of_sectors_per_table = ((unsigned short int) IORD_16DIRECT(device_pointer->base, 22));
boot_sector_data.number_of_sectors_per_track = ((unsigned short int) IORD_16DIRECT(device_pointer->base, 24));
boot_sector_data.number_of_heads = ((unsigned short int) IORD_16DIRECT(device_pointer->base, 26));
boot_sector_data.number_of_hidden_sectors = ((unsigned int) IORD_32DIRECT(device_pointer->base, 28));
boot_sector_data.total_sector_count_if_above_32MB = ((unsigned int) IORD_32DIRECT(device_pointer->base, 32));
boot_sector_data.drive_number = ((unsigned char) IORD_8DIRECT(device_pointer->base, 36));
boot_sector_data.current_head = ((unsigned char) IORD_8DIRECT(device_pointer->base, 37));
boot_sector_data.boot_signature = ((unsigned char) IORD_8DIRECT(device_pointer->base, 38));
boot_sector_data.first_fat_sector_offset = boot_sector_data.reserved_sectors;
boot_sector_data.second_fat_sector_offset = boot_sector_data.first_fat_sector_offset + boot_sector_data.number_of_sectors_per_table;
boot_sector_data.root_directory_sector_offset = boot_sector_data.second_fat_sector_offset + boot_sector_data.number_of_sectors_per_table;
boot_sector_data.data_sector_offset = boot_sector_data.root_directory_sector_offset + (32*boot_sector_data.max_number_of_dir_entires / boot_sector_data.sector_size_in_bytes);
if (boot_sector_data.number_of_sectors_in_partition > 0)
{
num_clusters = (boot_sector_data.number_of_sectors_in_partition / boot_sector_data.sectors_per_cluster);
}
else
{
num_clusters = (boot_sector_data.total_sector_count_if_above_32MB / boot_sector_data.sectors_per_cluster);
}
if (num_clusters < 4087)
{
boot_sector_data.bits_for_cluster_index = 12;
}
else if (num_clusters <= 65517)
{
boot_sector_data.bits_for_cluster_index = 16;
}
else
{
boot_sector_data.bits_for_cluster_index = 32;
}
for (counter = 0; counter < 4; counter++)
{
boot_sector_data.volume_id[counter] = ((char) IORD_8DIRECT(device_pointer->base, 39+counter));
}
for (counter = 0; counter < 11; counter++)
{
boot_sector_data.volume_label[counter] = ((char) IORD_8DIRECT(device_pointer->base, 43+counter));
}
for (counter = 0; counter < 8; counter++)
{
boot_sector_data.file_system_type[counter] = ((char) IORD_8DIRECT(device_pointer->base, 54+counter));
}
// Clear file records
for (counter = 0; counter < MAX_FILES_OPENED; counter++)
{
active_files[counter].in_use = false;
}
result = true;
}
else
{
result = false;
}
return result;
}
bool Look_for_FAT16(void)
// Read the SD card to determine if it contains a FAT16 partition.
{
bool result = false;
if (alt_up_sd_card_is_Present())
{
short int csd_file_format = *CSD_register_w0;
fat_partition_offset_in_512_byte_sectors = 0;
fat_partition_size_in_512_byte_sectors = 0;
if (((csd_file_format & 0x8000) == 0) && ((csd_file_format & 0x0c00) != 0x0c00))
{
if ((csd_file_format & 0x0c00) == 0x0400)
{
/* SD Card contains files stored in a DOS FAT (floppy like) file format, without a partition table */
result = Check_for_DOS_FAT(0);
}
if ((csd_file_format & 0x0c00) == 0x0000)
{
/* SD Card contains files stored in a Hard disk-like file format that contains a partition table */
if (Check_for_Master_Boot_Record())
{
result = Check_for_DOS_FAT(fat_partition_offset_in_512_byte_sectors);
}
}
if (result == true)
{
// Accept only FAT16, not FAT12.
if (boot_sector_data.bits_for_cluster_index != 16)
{
result = false;
}
else
{
fat_partition_size_in_512_byte_sectors = boot_sector_data.number_of_sectors_in_partition;
}
}
}
}
return result;
}
void filename_to_upper_case(char *file_name)
// Change file name to upper case.
{
int index;
int length = strlen(file_name);
for (index = 0; index < length; index++)
{
if ((file_name[index] >= 'a') && (file_name[index] <= 'z'))
{
file_name[index] = (file_name[index] - 'a') + 'A';
}
}
}
bool check_file_name_for_FAT16_compliance(char *file_name)
// Check if the file complies with FAT16 naming convention.
{
int length = strlen(file_name);
int index;
int last_dir_break_position = -1;
int last_period = -1;
bool result = true;
for(index = 0; index < length; index++)
{
if ((file_name[index] == ' ') ||
((last_dir_break_position == (index - 1)) && ((file_name[index] == '\\') || (file_name[index] == '/'))) ||
((index - last_period == 9) && (file_name[index] != '.')) ||
((last_dir_break_position != last_period) && (index - last_period > 3) &&
(file_name[index] != '\\') && (file_name[index] != '/'))
)
{
result = false;
break;
}
if ((file_name[index] == '\\') || (file_name[index] == '/'))
{
last_period = index;
last_dir_break_position = index;
}
if (file_name[index] == '.')
{
last_period = index;
}
}
if ((file_name[length-1] == '\\') || (file_name[length-1] == '/'))
{
result = false;
}
return result;
}
int get_dir_divider_location(char *name)
// Find a directory divider location.
{
int index = 0;
int length = strlen(name);
for(index = 0; index < length; index++)
{
if ((name[index] == '\\') || (name[index] == '/'))
{
break;
}
}
if (index == length)
{
index = -1;
}
return index;
}
bool match_file_record_to_name_ext(t_file_record *file_record, char *name, char *extension)
/* See if the given name and extension match the file record. Return true if this is so, false otherwise. */
{
bool match = true;
int index;
for (index = 0; index < 8; index++)
{
if (CHAR_TO_UPPER(file_record->name[index]) != CHAR_TO_UPPER(name[index]))
{
match = false;
break;
}
}
for (index = 0; index < 3; index++)
{
if (CHAR_TO_UPPER(file_record->extension[index]) != CHAR_TO_UPPER(extension[index]))
{
match = false;
break;
}
}
return match;
}
bool get_home_directory_cluster_for_file(char *file_name, int *home_directory_cluster, t_file_record *file_record)
// Scan the directories in given in the file name and find the root directory for the file.
{
bool result = false;
int home_dir_cluster = 0;
int location, index;
int start_location = 0;
/* Get Next Directory. */
location = get_dir_divider_location( file_name );
while (location > 0)
{
char name[8] = { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' };
char extension[3] = { ' ', ' ', ' ' };
int ext_index = -1;
int new_cluster = home_dir_cluster;
// Get the name of the directory in name/extension format.
for (index = 0; index < location; index++)
{
if (file_name[index+start_location] == '.')
{
ext_index = index;
}
else if (ext_index < 0)
{
name[index] = file_name[index+start_location];
}
else
{
extension[index-ext_index] = file_name[index+start_location];
}
}
if (home_dir_cluster == 0)
{
/* We are in the root directory. Scan the directory (of predefined size) and see if you can find the specified file. */
int max_root_dir_sectors = ((32*boot_sector_data.max_number_of_dir_entires) / boot_sector_data.sector_size_in_bytes);
int sector_index;
for (sector_index = 0; sector_index < max_root_dir_sectors; sector_index++)
{
if (Read_Sector_Data(sector_index+boot_sector_data.root_directory_sector_offset, fat_partition_offset_in_512_byte_sectors))
{
int file_counter;
for (file_counter = 0; file_counter < 16; file_counter++)
{
// Read file record.
Read_File_Record_At_Offset(file_counter*32, file_record, 0, sector_index);
if ((file_record->name[0] != 0xe5) && (file_record->name[0] != 0x00))
{
bool match = match_file_record_to_name_ext(file_record, name, extension);
if (match)
{
new_cluster = file_record->start_cluster_index;
file_record->file_record_cluster = 1; // Home directory is a subdirectory in the root directory.
break;
}
}
}
}
else
{
break;
}
if (new_cluster != home_dir_cluster)
{
break;
}
}
if (new_cluster != home_dir_cluster)
{
// A valid directory is found, so go to it.
home_dir_cluster = new_cluster;
start_location = start_location+location+1;
}
else
{
// Directory path is invalid.
return false;
}
} else {
// This is a subdirectory that can have any number of elements. So scan through it as though it was a file
// and see if you can find the directory of interest.
int cluster = home_dir_cluster;
do {
int start_sector = ( cluster - 2 ) * ( boot_sector_data.sectors_per_cluster ) + boot_sector_data.data_sector_offset;
int sector_index;
for (sector_index = 0; sector_index < boot_sector_data.sectors_per_cluster; sector_index++)
{
if (Read_Sector_Data(sector_index + start_sector, fat_partition_offset_in_512_byte_sectors))
{
int file_counter;
for (file_counter = 0; file_counter < 16; file_counter++)
{
// Read file record.
Read_File_Record_At_Offset(file_counter*32, file_record, cluster, sector_index);
if ((file_record->name[0] != 0xe5) && (file_record->name[0] != 0x00))
{
bool match = match_file_record_to_name_ext(file_record, name, extension);
if (match)
{
new_cluster = file_record->start_cluster_index;
break;
}
}
}
}
else
{
break;
}
if (new_cluster != home_dir_cluster)
{
break;
}
}
// If this is the end of the cluster and the directory has not been found, then see if there is another cluster
// that holds data for the current directory.
if (new_cluster == home_dir_cluster)
{
unsigned short int next_cluster;
if (get_cluster_flag(new_cluster, &next_cluster))
{
// The directory needs to be expanded to store more files.
if ((next_cluster & 0x0000fff8) == 0x0000fff8)
{
return false;
}
new_cluster = (next_cluster & 0x0000fff8);
}
else
{
// Directory path is invalid.
return false;
}
}
} while ((cluster < 0x0000fff8) && (new_cluster == home_dir_cluster));
if (new_cluster != home_dir_cluster)
{
// A valid directory is found, so go to it.
home_dir_cluster = new_cluster;
start_location = start_location+location+1;
}
else
{
// Directory path is invalid.
return false;
}
}
location = get_dir_divider_location(&(file_name[start_location]));
if (location < 0)
{
// Directory has been located.
result = true;
}
}
*home_directory_cluster = home_dir_cluster;
if (home_dir_cluster == 0)
{
file_record->file_record_cluster = 0; // Home directory is the root directory.
result = true;
}
return result;
}
bool find_file_in_directory(int directory_start_cluster, char *file_name, t_file_record *file_record)
// Given a cluster and a file name, check if the file already exists. Return the file record if the file is found.
{
int location = get_dir_divider_location( file_name );
int last_dir_separator = 0;
char name[8] = { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' };
char extension[3] = { ' ', ' ', ' ' };
int ext_index = -1;
int cluster = directory_start_cluster;
int index;
int length = strlen(file_name);
bool result = false;
// Skip through all directory separators.
while (location > 0)
{
last_dir_separator = last_dir_separator+location+1;
location = get_dir_divider_location( &(file_name[last_dir_separator]) );
}
// Get the name of the file in name/extension format.
for (index = last_dir_separator; index < length; index++)
{
if (file_name[index] == '.')
{
ext_index = index;
}
else if (ext_index < 0)
{
name[index-last_dir_separator] = file_name[index];
}
else
{
extension[index-ext_index-1] = file_name[index];
}
}
// Look for the file.
if (directory_start_cluster == 0)
{
/* We are in the root directory. Scan the directory (of predefined size) and see if you can find the specified file. */
int max_root_dir_sectors = ((32*boot_sector_data.max_number_of_dir_entires) / boot_sector_data.sector_size_in_bytes);
int sector_index;
for (sector_index = 0; sector_index < max_root_dir_sectors; sector_index++)
{
if (Read_Sector_Data( sector_index + boot_sector_data.root_directory_sector_offset,
fat_partition_offset_in_512_byte_sectors))
{
int file_counter;
for (file_counter = 0; file_counter < 16; file_counter++)
{
// Read file record.
Read_File_Record_At_Offset(file_counter*32, file_record, 0, sector_index);
if ((file_record->name[0] != 0xe5) && (file_record->name[0] != 0x00))
{
bool match = match_file_record_to_name_ext(file_record, name, extension);
if (match)
{
result = true;
break;
}
}
}
}
else
{
break;
}
if (result)
{
break;
}
}
}
else
{
do {
int start_sector = ( cluster - 2 ) * ( boot_sector_data.sectors_per_cluster ) + boot_sector_data.data_sector_offset;
int sector_index;
for (sector_index = 0; sector_index < boot_sector_data.sectors_per_cluster; sector_index++)
{
if (Read_Sector_Data(sector_index + start_sector, fat_partition_offset_in_512_byte_sectors))
{
int file_counter;
for (file_counter = 0; file_counter < 16; file_counter++)
{
// Read file record.
Read_File_Record_At_Offset(file_counter*32, file_record, cluster, sector_index);
if ((file_record->name[0] != 0xe5) && (file_record->name[0] != 0x00))
{
bool match = match_file_record_to_name_ext(file_record, name, extension);
if (match)
{
result = true;
break;
}
}
}
}
else
{
break;
}
if (result)
{
break;
}
}
// If this is the end of the cluster and the file has not been found, then see if there is another cluster
// that holds data for the current directory.
if (result == false)
{
unsigned short int new_cluster;
if (get_cluster_flag(cluster, &new_cluster))
{
// The directory needs to be expanded to store more files.
if ((new_cluster & 0x0000fff8) == 0x0000fff8)
{
return false;
}
cluster = (new_cluster & 0x0000fff8);
}
else
{
// Directory path is invalid.
return false;
}
}
} while ((cluster < 0x0000fff8) && (result == false));
}
return result;
}
bool find_first_empty_cluster(unsigned int *cluster_number)
// Find the first empty cluster. It will be marked by a 0 entry in the File Allocation Table.
{
unsigned int sector = boot_sector_data.first_fat_sector_offset;
unsigned int cluster_index = 2;
short int cluster = -1;
bool result = false;
unsigned max_cluster_index = 0;
unsigned int non_data_sectors = boot_sector_data.data_sector_offset;
unsigned int less_than_32 = boot_sector_data.number_of_sectors_in_partition;
unsigned int greater_than_32 = boot_sector_data.total_sector_count_if_above_32MB;
if (less_than_32 > greater_than_32)
{
max_cluster_index = ((less_than_32 - non_data_sectors) / boot_sector_data.sectors_per_cluster) + 1;
}
else
{
max_cluster_index = ((greater_than_32 - non_data_sectors) / boot_sector_data.sectors_per_cluster) + 1;
}
// Find an empty cluster for the file.
while (sector != boot_sector_data.second_fat_sector_offset)
{
if (Read_Sector_Data( sector, fat_partition_offset_in_512_byte_sectors))
{
do {
cluster = ((unsigned short int) IORD_16DIRECT(device_pointer->base, 2*(cluster_index % 256)));
if (cluster == 0)
{
// Free cluster found.
break;
}
else
{
cluster_index++;
}
} while ((cluster_index % 256) != 0);
}
if (cluster == 0)
{
break;
}
sector++;
}
if ((cluster == 0) && (cluster <= max_cluster_index))
{
*cluster_number = cluster_index;
result = true;
}
return result;
}
int find_first_empty_record_in_a_subdirectory(int start_cluster_index)
// Search for a free spot in a subdirectory. Return an encoded location for the file record.
{
int result = -1;
int cluster = start_cluster_index;
do {
int start_sector = ( cluster - 2 ) * ( boot_sector_data.sectors_per_cluster ) + boot_sector_data.data_sector_offset;
int sector_index;
for (sector_index = 0; sector_index < boot_sector_data.sectors_per_cluster; sector_index++)
{
if (Read_Sector_Data(sector_index + start_sector, fat_partition_offset_in_512_byte_sectors))
{
int file_counter;
for (file_counter = 0; file_counter < 16; file_counter++)
{
unsigned short int leading_char;
// Read file record.
leading_char = ((unsigned char) IORD_8DIRECT(device_pointer->base, file_counter*32));
if ((leading_char == 0x00e5) || (leading_char == 0))
{
result = (cluster) | ((sector_index*16 + file_counter) << 16);
return result;
}
}
}
else
{
break;
}
}
// If this is the end of the cluster and the file has not been found, then see if there is another cluster
// that holds data for the current directory.
if (result < 0)
{
unsigned short int new_cluster;
if (get_cluster_flag(cluster, &new_cluster))
{
// The directory needs to be expanded to store more files.
if ((new_cluster & 0x0000fff8) == 0x0000fff8)
{
int new_dir_cluster;
if (find_first_empty_cluster(&new_dir_cluster))
{
// Add the new cluster to the linked list of the given directory.
if (mark_cluster(cluster, ((short int) (new_dir_cluster)), true) &&
mark_cluster(new_dir_cluster, ((short int) (0xffff)), true) &&
mark_cluster(cluster, ((short int) (new_dir_cluster)), false) &&
mark_cluster(new_dir_cluster, ((short int) (0xffff)), false))
{
Save_Modified_Sector();
// The new file will begin at the first entry of the directory.
result = new_dir_cluster;
}
}
cluster = (new_cluster & 0x0000fff8);
}
}
else
{
// Error encountered.
result = -1;
}
}
} while ((cluster < 0x0000fff8) && (result == -1));
return result;
}
int find_first_empty_record_in_root_directory()
// Find a first unused record location to use. Return -1 if none is found.
{
int max_root_dir_sectors = ((32*boot_sector_data.max_number_of_dir_entires) / boot_sector_data.sector_size_in_bytes);
int sector_index;
int result = -1;
for (sector_index = 0; sector_index < max_root_dir_sectors; sector_index++)
{
if (Read_Sector_Data( sector_index + boot_sector_data.root_directory_sector_offset,
fat_partition_offset_in_512_byte_sectors))
{
int file_counter;
for (file_counter = 0; file_counter < 16; file_counter++)
{
unsigned short int leading_char;
// Read first character of the file record.
leading_char = ((unsigned char) IORD_8DIRECT(device_pointer->base, file_counter*32));
if ((leading_char == 0x00e5) || (leading_char == 0))
{
result = (sector_index*16 + file_counter) << 16;
return result;
}
}
}
else
{
break;
}
}
return result;
}
void convert_filename_to_name_extension(char *filename, char *name, char *extension)
// This function converts the file name into a name . extension format.
{
int counter;
int local = 0;
for(counter = 0; counter < 8; counter++)
{
if (filename[local] != '.')
{
name[counter] = filename[local];
if (filename[local] != 0) local++;
}
else
{
name[counter] = ' ';
}
}
if (filename[local] == '.') local++;
for(counter = 0; counter < 3; counter++)
{
if (filename[local] != 0)
{
extension[counter] = filename[local];
local++;
}
else
{
extension[counter] = ' ';
}
}
}
bool create_file(char *name, t_file_record *file_record, t_file_record *home_dir)
// Create a file in a given directory. Expand the directory if needed.
{
unsigned int cluster_number;
bool result = false;
if (find_first_empty_cluster(&cluster_number))
{
int record_index;
if (home_dir->file_record_cluster == 0)
{
// Put a file in the root directory.
record_index = find_first_empty_record_in_root_directory();
}
else
{
// Put a file in a subdirectory.
record_index = find_first_empty_record_in_a_subdirectory(home_dir->start_cluster_index);
}
if (record_index >= 0)
{
unsigned int file_record_sector;
int location = get_dir_divider_location( name );
int last_dir_separator = 0;
// Skip through all directory separators.
while (location > 0)
{
last_dir_separator = last_dir_separator+location+1;
location = get_dir_divider_location( &(name[last_dir_separator]) );
}
convert_filename_to_name_extension(&(name[last_dir_separator]), file_record->name, file_record->extension);
file_record->attributes = 0;
file_record->create_time = 0;
file_record->create_date = 0;
file_record->last_access_date = 0;
file_record->last_modified_time = 0;
file_record->last_modified_date = 0;
file_record->start_cluster_index = cluster_number;
file_record->file_size_in_bytes = 0;
file_record->current_cluster_index = cluster_number;
file_record->current_sector_in_cluster = 0;
file_record->current_byte_position = 0;
file_record->file_record_cluster = record_index & 0x0000ffff;
file_record->file_record_sector_in_cluster = ((record_index >> 16) & 0x0000ffff) / 16;
file_record->file_record_offset = (((record_index >> 16) & 0x0000ffff) % 16)*32;
file_record->home_directory_cluster = home_dir->start_cluster_index;
file_record->in_use = true;
file_record->modified = true;
// Now write the record at the specified location.
file_record_sector = (file_record->file_record_cluster == 0) ?
(boot_sector_data.root_directory_sector_offset + file_record->file_record_sector_in_cluster):
(boot_sector_data.data_sector_offset + (file_record->file_record_cluster-2)*boot_sector_data.sectors_per_cluster +
file_record->file_record_sector_in_cluster);
if (Read_Sector_Data(file_record_sector, fat_partition_offset_in_512_byte_sectors))
{
if (Write_File_Record_At_Offset(file_record->file_record_offset, file_record))
{
Save_Modified_Sector();
// Mark the first cluster of the file as the last cluster at first.
mark_cluster(cluster_number, ((short int) (0xffff)), true);
if (mark_cluster(cluster_number, ((short int) (0xffff)), false))
{
result = true;
}
}
}
}
}
return result;
}
void copy_file_record_name_to_string(t_file_record *file_record, char *file_name)
/* Copy a file name from the file record to a given string */
{
int index;
int flength = 0;
/* Copy file name.*/
for (index = 0; index < 8; index++)
{
if (file_record->name[index] != ' ')
{
file_name[flength] = file_record->name[index];
flength = flength + 1;
}
}
if (file_record->extension[0] != ' ')
{
file_name[flength] = '.';
flength = flength + 1;
for (index = 0; index < 3; index++)
{
if (file_record->extension[index] != ' ')
{
file_name[flength] = file_record->extension[index];
flength = flength + 1;
}
}
}
file_name[flength] = 0;
}
///////////////////////////////////////////////////////////////////////////
// Direct functions
///////////////////////////////////////////////////////////////////////////
alt_up_sd_card_dev* alt_up_sd_card_open_dev(const char* name)
{
// find the device from the device list
// (see altera_hal/HAL/inc/priv/alt_file.h
// and altera_hal/HAL/src/alt_find_dev.c
// for details)
alt_up_sd_card_dev *dev = (alt_up_sd_card_dev *) alt_find_dev(name, &alt_dev_list);
if (dev != NULL)
{
aux_status_register = ((short int *) SD_CARD_AUX_STATUS(dev->base));
status_register = ((int *) SD_CARD_STATUS(dev->base));
CSD_register_w0 = ((short int *) SD_CARD_CSD(dev->base, 0));
command_register = ((short int *) SD_CARD_COMMAND(dev->base));
command_argument_register = ((int *) SD_CARD_ARGUMENT(dev->base));
buffer_memory = (char *) SD_CARD_BUFFER(dev->base, 0);
device_pointer = dev;
initialized = false;
is_sd_card_formated_as_FAT16 = false;
search_data.valid = false;
}
return dev;
}
bool alt_up_sd_card_is_Present(void)
// Check if there is an SD Card insterted into the SD Card socket.
{
bool result = false;
if ((device_pointer != NULL) && ((IORD_16DIRECT(aux_status_register,0) & 0x02) != 0))
{
result = true;
}
else if (initialized == true)
{
int index;
initialized = false;
search_data.valid = false;
is_sd_card_formated_as_FAT16 = false;
for(index = 0; index < MAX_FILES_OPENED; index++)
{
active_files[index].in_use = false;
active_files[index].modified = false;
}
}
return result;
}
bool alt_up_sd_card_is_FAT16(void)
/* This function reads the SD card data in an effort to determine if the card is formated as a FAT16
* volume. Please note that FAT12 has a similar format, but will not be supported by this driver.
* If the card contains a FAT16 volume, the local data structures will be initialized to allow reading and writing
* to the SD card as though it was a hard drive.
*/
{
bool result = false;
if (alt_up_sd_card_is_Present())
{
// Check if an SD Card is in the SD Card slot.
if (initialized == false)
{
// Now determine if the card is formatted as FAT 16.
is_sd_card_formated_as_FAT16 = Look_for_FAT16();
initialized = is_sd_card_formated_as_FAT16;
search_data.valid = false;
}
result = is_sd_card_formated_as_FAT16;
}
else
{
// If not then you may as well not open the device.
initialized = false;
is_sd_card_formated_as_FAT16 = false;
}
return result;
}
short int alt_up_sd_card_find_first(char *directory_to_search_through, char *file_name)
/* This function sets up a search algorithm to go through a given directory looking for files.
* If the search directory is valid, then the function searches for the first file it finds.
* Inputs:
* directory_to_search_through - name of the directory to search through
* file_name - an array to store a name of the file found. Must be 13 bytes long (12 bytes for file name and 1 byte of NULL termination).
* Outputs:
* 0 - success
* 1 - invalid directory
* 2 - No card or incorrect card format.
*
* To specify a directory give the name in a format consistent with the following regular expression:
* [{[valid_chars]+}/]*.
*
* In other words, give a path name starting at the root directory, where each directory name is followed by a '/'.
* Then, append a '.' to the directory name. Examples:
* "." - look through the root directory
* "first/." - look through a directory named "first" that is located in the root directory.
* "first/sub/." - look through a directory named "sub", that is located within the subdirectory named "first". "first" is located in the root directory.
* Invalid examples include:
* "/.", "/////." - this is not the root directory.
* "/first/." - the first character may not be a '/'.
*/
{
short int result = 2;
if ((alt_up_sd_card_is_Present()) && (is_sd_card_formated_as_FAT16))
{
int home_directory_cluster;
t_file_record file_record;
if (get_home_directory_cluster_for_file(directory_to_search_through, &home_directory_cluster, &file_record))
{
search_data.directory_root_cluster = home_directory_cluster;
search_data.current_cluster_index = home_directory_cluster;
search_data.current_sector_in_cluster = 0;
search_data.file_index_in_sector = -1;
search_data.valid = true;
result = alt_up_sd_card_find_next(file_name);
}
else
{
result = 1;
}
}
return result;
}
short int alt_up_sd_card_find_next(char *file_name)
/* This function searches for the next file in a given directory, as specified by the find_first function.
* Inputs:
* file_name - an array to store a name of the file found. Must be 13 bytes long (12 bytes for file name and 1 byte of NULL termination).
* Outputs:
* -1 - end of directory.
* 0 - success
* 2 - No card or incorrect card format.
* 3 - find_first has not been called successfully.
*/
{
short int result = 2;
if ((alt_up_sd_card_is_Present()) && (is_sd_card_formated_as_FAT16))
{
if (search_data.valid)
{
t_file_record file_record;
int cluster = search_data.current_cluster_index;
if (cluster == 0)
{
// Searching through the root directory
int max_root_dir_sectors = ((32*boot_sector_data.max_number_of_dir_entires) / boot_sector_data.sector_size_in_bytes);
int sector_index = search_data.current_sector_in_cluster;
int file_counter = search_data.file_index_in_sector+1;
for (; sector_index < max_root_dir_sectors; sector_index++)
{
if (Read_Sector_Data( sector_index + boot_sector_data.root_directory_sector_offset,
fat_partition_offset_in_512_byte_sectors))
{
for (; file_counter < 16; file_counter++)
{
if (Read_File_Record_At_Offset(file_counter*32, &file_record, 0, sector_index))
{
if ((file_record.name[0] != 0) && (file_record.name[0] != 0xe5))
{
/* Update search structure. */
search_data.file_index_in_sector = file_counter;
search_data.current_sector_in_cluster = sector_index;
/* Copy file name.*/
copy_file_record_name_to_string(&file_record, file_name);
return 0;
}
}
}
file_counter = 0;
}
else
{
break;
}
}
result = -1;
}
else
{
int file_counter = search_data.file_index_in_sector+1;
do
{
int start_sector = ( cluster - 2 ) * ( boot_sector_data.sectors_per_cluster ) + boot_sector_data.data_sector_offset;
int sector_index = search_data.current_sector_in_cluster;
for (; sector_index < boot_sector_data.sectors_per_cluster; sector_index++)
{
if (Read_Sector_Data(sector_index + start_sector, fat_partition_offset_in_512_byte_sectors))
{
for (; file_counter < 16; file_counter++)
{
if (Read_File_Record_At_Offset(file_counter*32, &file_record, cluster, sector_index))
{
if ((file_record.name[0] != 0) && (file_record.name[0] != 0xe5))
{
/* Update search structure. */
search_data.current_cluster_index = cluster;
search_data.file_index_in_sector = file_counter;
search_data.current_sector_in_cluster = sector_index;
/* Copy file name.*/
copy_file_record_name_to_string(&file_record, file_name);
return 0;
}
}
}
file_counter = 0;
}
else
{
break;
}
}
// If this is the end of the cluster and the file has not been found, then see if there is another cluster
// that holds data for the current directory.
if (sector_index >= boot_sector_data.sectors_per_cluster)
{
short int new_cluster;
if (get_cluster_flag(cluster, &new_cluster))
{
if ((new_cluster & 0x0000fff8) == 0x0000fff8)
{
result = -1;
search_data.valid = false;
}
cluster = ((new_cluster) & 0x0000fff8);
}
else
{
// Error encountered.
result = -1;
}
}
} while (cluster < 0x0000fff8);
}
}
else
{
// Call Find_First first.
result = 3;
}
}
return result;
}
short int alt_up_sd_card_fopen(char *name, bool create)
/* This function reads the SD card data in an effort to determine if the card is formated as a FAT16
* volume. Please note that FAT12 has a similar format, but will not be supported by this driver.
*
* Inputs:
* name - a file name including a directory, relative to the root directory
* create - a flag set to true to create a file if it does not already exist
* Output:
* An index to the file record assigned to the specified file. -1 is returned if the file could not be opened.
* Return -2 if the specified file has already been opened previously.
*/
{
short int file_record_index = -1;
if ((alt_up_sd_card_is_Present()) && (is_sd_card_formated_as_FAT16))
{
unsigned int home_directory_cluster = 0;
t_file_record home_dir;
/* First check the file name format. It should not be longer than 12 characters, including a period and the extension.
* Rules:
* - no spaces
* - at most 12 chatacters per name, with a period in 9th position.
* - a / or a \ every at most 12 characters.
*/
filename_to_upper_case(name);
if (check_file_name_for_FAT16_compliance(name))
{
int index;
/* Get home directory cluster location for the specified file. 0 means root directory. */
if (!get_home_directory_cluster_for_file(name, &home_directory_cluster, &home_dir))
{
return file_record_index;
}
/* Find a free file slot to store file specs in. */
for (index = 0; index < MAX_FILES_OPENED; index++)
{
if (active_files[index].in_use == false)
{
file_record_index = index;
break;
}
}
if (file_record_index >= 0)
{
/* If file record is found, then look for the specified file. If the create flag is set to true
* and the file is not found, then it should be created in the current directory.
*/
if (find_file_in_directory(home_directory_cluster, name, &(active_files[file_record_index])))
{
if (create)
{
/* Do not allow overwriting existing files for now. */
return -1;
}
active_files[file_record_index].current_cluster_index = active_files[file_record_index].start_cluster_index;
active_files[file_record_index].current_sector_in_cluster = 0;
active_files[file_record_index].current_byte_position = 0;
active_files[file_record_index].in_use = true;
active_files[file_record_index].modified = false;
/* Check if the file has already been opened. */
for (index = 0; index < MAX_FILES_OPENED; index++)
{
if ((file_record_index != index) && (active_files[index].in_use == true))
{
if ((active_files[file_record_index].file_record_cluster == active_files[index].file_record_cluster) &&
(active_files[file_record_index].file_record_sector_in_cluster == active_files[index].file_record_sector_in_cluster) &&
(active_files[file_record_index].file_record_offset == active_files[index].file_record_offset))
{
// file already in use.
file_record_index = -2;
break;
}
}
}
}
else if (create)
{
/* Create file if needed. */
if (create_file(name, &(active_files[file_record_index]), &home_dir))
{
active_files[file_record_index].in_use = true;
active_files[file_record_index].modified = true;
}
else
{
/* If file creation fails then return an invalid file handle. */
file_record_index = -1;
}
}
else
{
/* Otherwise the file could not be opened.*/
file_record_index = -1;
}
}
}
}
return file_record_index;
}
void alt_up_sd_card_set_attributes(short int file_handle, short int attributes)
/* Return file attributes, or -1 if the file_handle is invalid.
*/
{
if ((file_handle >= 0) && (file_handle < MAX_FILES_OPENED))
{
if (active_files[file_handle].in_use)
{
active_files[file_handle].attributes = ((char)(attributes & 0x00ff));
}
}
}
short int alt_up_sd_card_get_attributes(short int file_handle)
/* Return file attributes, or -1 if the file_handle is invalid.
*/
{
short int result = -1;
if ((file_handle >= 0) && (file_handle < MAX_FILES_OPENED))
{
if (active_files[file_handle].in_use)
{
result = ((active_files[file_handle].attributes) & 0x00ff);
}
}
return result;
}
short int alt_up_sd_card_read(short int file_handle)
/* Read a single character from a given file. Return -1 if at the end of a file. Any other negative number
* means that the file could not be read. A number between 0 and 255 is an ASCII character read from the SD Card. */
{
short int ch = -1;
if ((file_handle >= 0) && (file_handle < MAX_FILES_OPENED))
{
if (active_files[file_handle].in_use)
{
if (active_files[file_handle].current_byte_position < active_files[file_handle].file_size_in_bytes)
{
int data_sector = boot_sector_data.data_sector_offset + (active_files[file_handle].current_cluster_index - 2)*boot_sector_data.sectors_per_cluster +
active_files[file_handle].current_sector_in_cluster;
if ((active_files[file_handle].current_byte_position > 0) && ((active_files[file_handle].current_byte_position % 512) == 0))
{
// Read in a new sector of data.
if (active_files[file_handle].current_sector_in_cluster == boot_sector_data.sectors_per_cluster - 1)
{
// Go to the next cluster.
unsigned short int next_cluster;
if (get_cluster_flag(active_files[file_handle].current_cluster_index, &next_cluster))
{
if ((next_cluster & 0x0000fff8) == 0x0000fff8)
{
/* End of file */
return -1;
}
else
{
active_files[file_handle].current_cluster_index = next_cluster;
active_files[file_handle].current_sector_in_cluster = 0;
data_sector = boot_sector_data.data_sector_offset + (active_files[file_handle].current_cluster_index - 2)*boot_sector_data.sectors_per_cluster +
active_files[file_handle].current_sector_in_cluster;
}
}
else
{
return -2;
}
}
else
{
active_files[file_handle].current_sector_in_cluster = active_files[file_handle].current_sector_in_cluster + 1;
data_sector = data_sector + 1;
}
}
// Reading te first byte of the file.
if (current_sector_index != (data_sector + fat_partition_offset_in_512_byte_sectors))
{
if (!Read_Sector_Data(data_sector, fat_partition_offset_in_512_byte_sectors))
{
return -2;
}
}
ch = (unsigned char) IORD_8DIRECT(buffer_memory, (active_files[file_handle].current_byte_position % 512));
active_files[file_handle].current_byte_position = active_files[file_handle].current_byte_position + 1;
}
}
}
return ch;
}
bool alt_up_sd_card_write(short int file_handle, char byte_of_data)
/* Write a single character to a given file. Return true if successful, and false otherwise. */
{
bool result = false;
if ((file_handle >= 0) && (file_handle < MAX_FILES_OPENED))
{
if (active_files[file_handle].in_use)
{
int data_sector = boot_sector_data.data_sector_offset + (active_files[file_handle].current_cluster_index - 2)*boot_sector_data.sectors_per_cluster +
active_files[file_handle].current_sector_in_cluster;
short int buffer_offset = active_files[file_handle].current_byte_position % boot_sector_data.sector_size_in_bytes;
if (active_files[file_handle].current_byte_position < active_files[file_handle].file_size_in_bytes)
{
if ((active_files[file_handle].current_byte_position > 0) && (buffer_offset == 0))
{
// Read in a new sector of data.
if (active_files[file_handle].current_sector_in_cluster == boot_sector_data.sectors_per_cluster - 1)
{
// Go to the next cluster.
unsigned short int next_cluster;
if (get_cluster_flag(active_files[file_handle].current_cluster_index, &next_cluster))
{
if (next_cluster < 0x0000fff8)
{
active_files[file_handle].current_cluster_index = next_cluster;
active_files[file_handle].current_sector_in_cluster = 0;
data_sector = boot_sector_data.data_sector_offset + (active_files[file_handle].current_cluster_index - 2)*boot_sector_data.sectors_per_cluster +
active_files[file_handle].current_sector_in_cluster;
}
}
else
{
return false;
}
}
else
{
active_files[file_handle].current_sector_in_cluster = active_files[file_handle].current_sector_in_cluster + 1;
data_sector = data_sector + 1;
}
}
}
else
{
/* You are adding data to the end of the file, so increment its size and look for an additional data cluster if needed. */
if ((active_files[file_handle].current_byte_position > 0) && (buffer_offset == 0))
{
if (active_files[file_handle].current_sector_in_cluster == boot_sector_data.sectors_per_cluster - 1)
{
/* Find a new cluster if possible. */
unsigned int cluster_number;
if (find_first_empty_cluster(&cluster_number))
{
// mark clusters in both File Allocation Tables.
mark_cluster(active_files[file_handle].current_cluster_index, ((unsigned short int) (cluster_number & 0x0000ffff)), true);
mark_cluster(cluster_number, 0xffff, true);
mark_cluster(active_files[file_handle].current_cluster_index, ((unsigned short int) (cluster_number & 0x0000ffff)), false);
mark_cluster(cluster_number, 0xffff, false);
// Change cluster index and sector index to compute a new data sector.
active_files[file_handle].current_cluster_index = cluster_number;
active_files[file_handle].current_sector_in_cluster = 0;
}
else
{
return false;
}
}
else
{
/* Read the next sector in the cluster and modify it. We only need to change the data_sector value. The actual read happens a few lines below. */
active_files[file_handle].current_sector_in_cluster = active_files[file_handle].current_byte_position / boot_sector_data.sector_size_in_bytes;
}
data_sector = boot_sector_data.data_sector_offset + (active_files[file_handle].current_cluster_index - 2)*boot_sector_data.sectors_per_cluster +
active_files[file_handle].current_sector_in_cluster;
}
}
// Reading a data sector into the buffer. Note that changes to the most recently modified sector will be saved before
// a new sector is read from the SD Card.
if (current_sector_index != data_sector + fat_partition_offset_in_512_byte_sectors)
{
if (!Read_Sector_Data(data_sector, fat_partition_offset_in_512_byte_sectors))
{
return false;
}
}
// Write a byte of data to the buffer.
IOWR_8DIRECT(buffer_memory, buffer_offset, byte_of_data);
active_files[file_handle].current_byte_position = active_files[file_handle].current_byte_position + 1;
// Modify the file record only when necessary.
if (active_files[file_handle].current_byte_position >= active_files[file_handle].file_size_in_bytes)
{
active_files[file_handle].file_size_in_bytes = active_files[file_handle].file_size_in_bytes + 1;
active_files[file_handle].modified = true;
}
// Invaldiate the buffer to ensure that the buffer contents are written to the SD card whe nthe file is closed.
current_sector_modified = true;
result = true;
}
}
return result;
}
bool alt_up_sd_card_fclose(short int file_handle)
// This function closes an opened file and saves data to SD Card if necessary.
{
bool result = false;
if ((alt_up_sd_card_is_Present()) && (is_sd_card_formated_as_FAT16))
{
if (active_files[file_handle].in_use)
{
if (active_files[file_handle].modified)
{
unsigned int record_sector = active_files[file_handle].file_record_sector_in_cluster;
if (active_files[file_handle].file_record_cluster == 0)
{
record_sector = record_sector + boot_sector_data.root_directory_sector_offset;
}
else
{
record_sector = record_sector + boot_sector_data.data_sector_offset +
(active_files[file_handle].file_record_cluster - 2)*boot_sector_data.sectors_per_cluster;
}
if (Read_Sector_Data(record_sector, fat_partition_offset_in_512_byte_sectors))
{
if (Write_File_Record_At_Offset(active_files[file_handle].file_record_offset, &(active_files[file_handle])))
{
// Make sure that the Data has been saved to the SD Card.
result = Save_Modified_Sector();
}
}
}
active_files[file_handle].in_use = false;
result = true;
}
}
return result;
}
|
finncyr/Drum_maschine
|
software/DM_PIO_Ansatz/main.h
|
/*
* DM_IO.h
*
* This is the Header File for the Main IO of the Drum Maschine.
* It contains all includes and defines.
*
* The SRAM is defined as follows:
*
* SRAM_BASE -> | patterns | BPM | Play/Pause | SD Files |
* | 64 bit | 16 bit | 8 bit | TBD |
* | 16bit [4] | ushort | 0 255 | ? |
*
* Created on: 14.12.2019
* Author: <NAME>
*/
#ifndef MAIN_H_
#define MAIN_H_
// Includes
//#include "Drum_maschine_C_Prototype_bsp\system.h"
#include "system.h"
#include <alt_types.h>
#include <altera_up_avalon_parallel_port.h>
// Defines
#define MIN_BPM 60
#define MAX_BPM 240
#define STEP_BPM 10
// Offsets
// starting at SRAM_BASE, for R/W in SRAM use Address SRAM_BASE + OFFSET_X
#define OFFSET_PATTERN 0
#define LENGTH_PATTERN 64
#define OFFSET_BPM 64
#define LENGTH_BPM 16
#define OFFSET_PLAYPAUSE 80
#define LENGTH_PLAYPAUSE 8
#endif /* DM_IO_H_ */
|
finncyr/Drum_maschine
|
software/DM_PIO_Ansatz_bsp/drivers/inc/altera_up_avalon_character_lcd_regs.h
|
/******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2003 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
******************************************************************************/
#ifndef __ALT_UP_CHARACTER_LCD_REGS_H__
#define __ALT_UP_CHARACTER_LCD_REGS_H__
#include <io.h>
/*
* Command Register (When RS = 0)
* (In the document, we used the name Instruction Register)
*/
#define ALT_UP_CHARACTER_LCD_COMMAND_REG 0
#define IOADDR_ALT_UP_CHARACTER_LCD_COMMAND(base) \
__IO_CALC_ADDRESS_DYNAMIC(base, ALT_UP_CHARACTER_LCD_COMMAND_REG)
#define IORD_ALT_UP_CHARACTER_LCD_COMMAND(base) \
IORD_8DIRECT(base, ALT_UP_CHARACTER_LCD_COMMAND_REG)
#define IOWR_ALT_UP_CHARACTER_LCD_COMMAND(base, data) \
IOWR_8DIRECT(base, ALT_UP_CHARACTER_LCD_COMMAND_REG, data)
//#define ALT_UP_CHARACTER_LCD_COMMAND_MSK (0xFF)
//#define ALT_UP_CHARACTER_LCD_COMMAND_OFST (0x00)
// Clear Display
#define ALT_UP_CHARACTER_LCD_COMM_CLEAR_DISPLAY (0x01)
// Return Home
#define ALT_UP_CHARACTER_LCD_COMM_RETURN_HOME (0x02)
//Entry Mode
#define ALT_UP_CHARACTER_LCD_COMM_ENTRY_DIR_RIGHT (0x06)
#define ALT_UP_CHARACTER_LCD_COMM_ENTRY_DIR_LEFT (0x04)
#define ALT_UP_CHARACTER_LCD_COMM_ENTRY_SHIFT_ENABLE (0x05)
#define ALT_UP_CHARACTER_LCD_COMM_ENTRY_SHIFT_DISABLE (0x04)
// Display ON/OFF Control
#define ALT_UP_CHARACTER_LCD_COMM_DISPLAY_ON (0x0C)
#define ALT_UP_CHARACTER_LCD_COMM_CURSOR_ON (0x0E)
#define ALT_UP_CHARACTER_LCD_COMM_CURSOR_BLINK_ON (0x0F)
#define ALT_UP_CHARACTER_LCD_COMM_DISPLAY_OFF (0x08)
#define ALT_UP_CHARACTER_LCD_COMM_CURSOR_OFF (0x0C) //equivalent to ALT_UP_CHARACTER_LCD_COMM_DISPLAY_ON
#define ALT_UP_CHARACTER_LCD_COMM_CURSOR_BLINK_OFF (0x0E) //equivalent to ALT_UP_CHARACTER_LCD_COMM_CURSOR_ON
// Cursor/Display Shift
// cause the entire display to move to left or right (the origin of the display is also changed)
#define ALT_UP_CHARACTER_LCD_COMM_DISPLAY_SHIFT_RIGHT (0x1C)
#define ALT_UP_CHARACTER_LCD_COMM_DISPLAY_SHIFT_LEFT (0x18)
// move the cursor to left or right
#define ALT_UP_CHARACTER_LCD_COMM_CURSOR_SHIFT_RIGHT (0x14)
#define ALT_UP_CHARACTER_LCD_COMM_CURSOR_SHIFT_LEFT (0x10)
/*
* Data Register (When RS = 1)
*/
#define ALT_UP_CHARACTER_LCD_DATA_REG 1
#define IOADDR_ALT_UP_CHARACTER_LCD_DATA(base) \
__IO_CALC_ADDRESS_DYNAMIC(base, ALT_UP_CHARACTER_LCD_DATA_REG)
#define IORD_ALT_UP_CHARACTER_LCD_DATA(base) \
IORD_8DIRECT(base, ALT_UP_CHARACTER_LCD_DATA_REG)
#define IOWR_ALT_UP_CHARACTER_LCD_DATA(base, data) \
IOWR_8DIRECT(base, ALT_UP_CHARACTER_LCD_DATA_REG, data)
//#define ALT_UP_CHARACTER_LCD_DATA_MSK (0xFF)
//#define ALT_UP_CHARACTER_LCD_DATA_OFST (0)
#define ALT_UP_CHARACTER_LCD_BF_MSK (0x80)
#define ALT_UP_CHARACTER_LCD_BF_OFST (7)
#endif /* __ALT_UP_CHARACTER_LCD_REGS_H__ */
|
so1h/so1
|
PRACT0/SO1PUB/LL_S_SO1/WAITPID.c
|
<gh_stars>0
#include <so1pub.h\ll_s_so1.h>
pid_t waitpid ( pid_t pid, int far * statloc )
{
asm
{
mov bx,pid ;
les dx,statloc ;
mov ax,WAITPID ;
int nVIntSO1 ;
}
return(_AX) ;
}
|
so1h/so1
|
PRACT0/SO1PUB/LL_S_SO1/EXIT.c
|
#include <so1pub.h\ll_s_so1.h>
void exit ( int status )
{
asm
{
mov bx,status ;
mov ax,EXIT ;
int nVIntSO1 ;
}
}
|
ondrejnovakcvut/ThermistorLibrary
|
src/tables/thermistortable_148.h
|
<filename>src/tables/thermistortable_148.h<gh_stars>0
/**
* Marlin 3D Printer Firmware
* Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (C) 2011 <NAME> / <NAME>
*
* 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/>.
*
*/
const short temptable_148[][2] PROGMEM = {
// These values have been calculated and tested over many days. See https://docs.google.com/spreadsheets/d/1MJXa6feEe0mGVCT2TrBwLxVOMoLDkJlvfQ4JXhAdV_E
// Values that are missing from the 5C gap are missing due to resolution limits.
{OV(19.00000), 0},
{OV(19.25000), 5},
{OV(19.50000), 10},
{OV(19.87500), 15},
{OV(20.25000), 20},
{OV(21.00000), 25},
{OV(21.75000), 35},
{OV(22.00000), 40},
{OV(23.00000), 50}, // 55C is more commonly used.
{OV(23.75000), 60},
{OV(24.00000), 65},
{OV(24.06250), 70},
{OV(25.00000), 75},
{OV(25.50000), 85},
{OV(26.00000), 90},
{OV(26.93750),100},
{OV(27.00000),105},
{OV(27.37500),110},
{OV(28.00000),115},
{OV(29.00000),125},
{OV(29.25000),135},
{OV(30.00000),140},
{OV(35.50000),150},
{OV(31.00000),155},
{OV(32.00000),165},
{OV(32.18750),175},
{OV(33.00000),180},
{OV(33.62500),190},
{OV(34.00000),195},
{OV(35.00000),205},
{OV(35.50000),215},
{OV(36.00000),220},
{OV(36.75000),230},
{OV(37.00000),235},
{OV(37.75000),245},
{OV(38.00000),250},
{OV(38.12500),255},
{OV(39.00000),260},
{OV(40.00000),275},
{OV(40.25000),285},
{OV(41.00000),290},
{OV(41.25000),300},
{OV(42.00000),305},
{OV(43.00000),315},
{OV(43.25000),325},
{OV(44.00000),330},
{OV(44.18750),340},
{OV(45.00000),345},
{OV(45.25000),355},
{OV(46.00000),360},
{OV(46.62500),370},
{OV(47.00000),375},
{OV(47.25000),385},
{OV(48.00000),390},
{OV(48.75000),400},
{OV(49.00000),405},
};
|
ondrejnovakcvut/ThermistorLibrary
|
src/tables/thermistortable_80.h
|
<reponame>ondrejnovakcvut/ThermistorLibrary
const short temptable_80[][2] PROGMEM = {
{ OV(21.5), 300 },
{ OV(23.0625), 295 },
{ OV(24.8125), 290 },
{ OV(26.75), 285 },
{ OV(28.8125), 280 },
{ OV(31.125), 275 },
{ OV(33.625), 270 },
{ OV(36.375), 265 },
{ OV(39.375), 260 },
{ OV(42.6875), 255 },
{ OV(46.3125), 250 },
{ OV(50.3125), 245 },
{ OV(54.6875), 240 },
{ OV(59.5625), 235 },
{ OV(64.875), 230 },
{ OV(70.75), 225 },
{ OV(77.25), 220 },
{ OV(84.4375), 215 },
{ OV(92.3125), 210 },
{ OV(101.0625), 205 },
{ OV(110.6875), 200 },
{ OV(121.3125), 195 },
{ OV(133), 190 },
{ OV(145.9375), 185 },
{ OV(160.125), 180 },
{ OV(175.6875), 175 },
{ OV(192.8125), 170 },
{ OV(211.5), 165 },
{ OV(231.9375), 160 },
{ OV(254.125), 155 },
{ OV(278.1875), 150 },
{ OV(304.125), 145 },
{ OV(332), 140 },
{ OV(361.6875), 135 },
{ OV(393.125), 130 },
{ OV(426.25), 125 },
{ OV(460.8125), 120 },
{ OV(496.5625), 115 },
{ OV(533.1875), 110 },
{ OV(570.3125), 105 },
{ OV(607.625), 100 },
{ OV(644.625), 95 },
{ OV(680.9375), 90 },
{ OV(716.125), 85 },
{ OV(749.875), 80 },
{ OV(781.8125), 75 },
{ OV(811.6875), 70 },
{ OV(839.25), 65 },
{ OV(864.5), 60 },
{ OV(887.3125), 55 },
{ OV(907.6875), 50 },
{ OV(925.6875), 45 },
{ OV(941.5), 40 },
{ OV(955.25), 35 },
{ OV(967), 30 },
{ OV(977.0625), 25 },
{ OV(985.5625), 20 },
{ OV(992.6875), 15 },
{ OV(998.625), 10 },
{ OV(1003.5625), 5 },
{ OV(1007.5625), 0 }
};
|
lukewli/pa01_lukewli
|
cards.h
|
<reponame>lukewli/pa01_lukewli
// cards.h
#ifndef CardBST_H
#define CardBST_H
#include <iostream>
#include <string>
using namespace std;
class CardBST {
private:
struct Node {
string suit;
string rank;
Node *left, *right, *parent;
// useful constructor:
Node(string s = "", string r = "") : suit(s), rank(r), left(nullptr), right(nullptr), parent(nullptr) { }
};
// just one instance variable (pointer to root node):
Node *root;
// recursive utility functions for use by public methods above
Node* getNodeFor(Node *card, Node* n); // IMPLEMENT THIS FIRST: returns the node for a given value or NULL if none exists
void clear(Node *n); // for destructor
bool insert(Node *card, Node *n); // note overloading names for simplicity
void printPreOrder(Node *n) const;
void printInOrder(Node *n) const;
void printPostOrder(Node *n) const;
int count(Node *n) const;
// these should be used by getPredecessor and getSuccessor, and ONE of them should be used by remove
Node* getSuccessorNode(Node *card) ; // returns the Node containing the successor of the given value
Node* getPredecessorNode(Node *card) ; // returns the Node containing the predecessor of the given value
public:
CardBST(); // constructor
~CardBST(); // destructor
bool insert(string suit, string rank); // insert value; return false if duplicate
void printPreOrder() const; // prints tree data pre-order to cout
void printInOrder() const; // print tree data in-order to cout
void printPostOrder() const; // print tree data post-order to cout
int count() const; // count of values
bool contains(Node *card) ; // true if value is in tree
// THESE ARE HARDER! DO THESE LAST
Node* getPredecessor(Node *card) ; // returns the predecessor value of the given value or 0 if there is none
Node* getSuccessor(Node *card) ; // returns the successor value of the given value or 0 if there is none
bool remove(Node *card); // deletes the Node containing the given value from the tree
bool comparelessthan(Node *lhs, Node *rhs);
void playgame(CardBST& other);
};
#endif
|
masteranza/qprop
|
base/factorial.h
|
<reponame>masteranza/qprop
#ifndef factorial_h
#define factorial_h factorial_h
#include <stdio.h>
#include <stdlib.h>
double factorial(long n);
#endif // factorial_h
|
masteranza/qprop
|
base/wavefunction.h
|
<gh_stars>0
#define __STDCPP_WANT_MATH_SPEC_FUNCS__ 1
#ifndef wavefunction_h
#define wavefunction_h wavefunction_h
#include <iostream>
#include <assert.h>
#include <complex>
#include <fstream>
#include <cmath>
#include <cstdlib>
#include <string>
#include <factorial.h>
using namespace std;
void f(double, double[], double[]);
typedef std::complex<double> cplxd;
class fluid;
class hamop;
class grid;
class wavefunction
{
public:
wavefunction(long x = 0) : wf_dim(x), start(new cplxd[x]) {}
wavefunction(const wavefunction &v)
{
wf_dim = v.wf_dim;
start = new cplxd[wf_dim];
for (long i = 0; i < wf_dim; i++)
start[i] = v.start[i];
}
virtual ~wavefunction() { delete[] start; }
//
// Functions
//
void apply(const wavefunction &a, const wavefunction &b,
const wavefunction &c, const wavefunction &psi);
cplxd *begin() { return start; }
const cplxd *begin() const { return start; }
void calculate_staticpot(grid g, hamop hamil);
wavefunction calculate_Theta(grid g, const fluid °eneracies, const fluid &ms);
fluid calculate_radial_density(grid g, const fluid °eneracies);
wavefunction conjugate();
void dump_to_file(grid g, FILE *os, int stepwidth, double fact);
void dump_xvector_to_file(long ngpsx, FILE *os, int stepwidth);
void dump_to_file_sh(grid g, FILE *os, int stepwidth, int iv);
void dump_expect_z(grid g, FILE *os, fluid °eneracies, const fluid &ms);
void embed_as_x(grid g, long yindex, long zindex, const wavefunction &v);
void embed_as_x(grid g, long l, long m, long i, const wavefunction &v);
void embed_as_xy(grid g, long zindex, const wavefunction &v);
cplxd energy(double time, grid g, hamop hamil, int me,
const wavefunction &staticpot, double charge);
wavefunction extract_x(grid g, long other_one, long other_two);
wavefunction extract_y(grid g, long other_one, long other_two);
wavefunction extract_z(grid g, long other_one, long other_two);
wavefunction extract_xy(grid g, long zindex);
void extract_xy2(FILE *os, grid g, long zindex);
wavefunction expwf(cplxd a);
wavefunction expwf(double a);
cplxd expect_z(grid g, fluid °eneracies, const fluid &ms);
cplxd expect_z(grid g);
cplxd expect_z(grid g, wavefunction &orig);
cplxd expect_z(grid g, int L);
cplxd expect_cycl_pol_plus(grid g);
cplxd expect_cycl_pol_minus(grid g);
cplxd accel_z(grid g, int m, hamop hamil, double time, int me, double deltat);
cplxd accel_cycl_pol_plus(grid g, hamop hamil, double time, int me, double deltat);
cplxd expect_rr(grid g, fluid °eneracies);
int init(long isize);
void init(grid g, int n, int l, double Z);
void init_analytic(grid g, int inittype, double width, fluid &ells, double mixture, long imag_potential_width);
void add_analytic(grid g, int inittype, double width, fluid &ells, double mixture);
void init_parabolic(grid g, int inittype, double width, int mu1, int mu2);
void init_rlm(grid g, int n, int l, int m, double Z);
void init(grid g, int inittype, FILE *file, int ooi);
int init(grid g, FILE *file, int ooi, int iv);
void regrid(grid g, grid g_small, const wavefunction &v);
void regrid_adding(grid g, grid g_small, const wavefunction &v, double weight);
void regrid_and_rebin(grid g, grid g_small, const wavefunction &v);
void select_single_orbital(grid g, grid g_small, int orb_of_interest,
double ell, const wavefunction &v);
double totalenergy_single_part(grid g, const wavefunction &orb_energs, const fluid °eneracies);
void nullify();
double norm(grid g);
void subtract(grid g, wavefunction &wf2);
// void extract_ell(grid g, long ell, long m0);
void extract_ell_m(grid g, long ell, long m0);
void normalize(grid g, const fluid &ms);
void normalize(grid g);
wavefunction project(grid g, grid gorig, wavefunction &orig);
cplxd project(grid g, grid gorig, wavefunction &orig, long zindex);
int load(FILE *, int);
cplxd *end() { return start + wf_dim; }
const cplxd *end() const { return start + wf_dim; }
void propagate(cplxd timestep,
double time,
grid g,
hamop hamil,
int me,
const wavefunction &staticpot,
const fluid &wf_one,
const wavefunction &wf_two,
const wavefunction &wf_three,
const fluid &ms,
double charge,
int propornot[]);
void propagate(cplxd timestep,
double time,
grid g,
hamop hamil,
int me,
const wavefunction &staticpot,
int m,
double charge);
wavefunction orb_fieldenergies(double time, grid g, hamop hamil, int me, const fluid &ms);
wavefunction orbital_energies(double time, grid g, hamop hamil, int me, const wavefunction &staticpot, double charge);
cplxd orbital_energy(double time, grid g, hamop hamil, int me, const wavefunction &staticpot, double charge, long orb_no);
fluid orbital_norms(grid g);
wavefunction orbital_hartrees(double time, grid g, int me,
const fluid &wf_one);
cplxd orbital_hartree(double time, grid g, int me,
const fluid &wf_one, long orb_no);
void realific();
void solve(const wavefunction &a, const wavefunction &b,
const wavefunction &c, const wavefunction &psi, long dimens);
void solve_du(const wavefunction &a, const wavefunction &b,
const wavefunction &c, const wavefunction &psi, long dimens);
void solve_toep(double a, double b, double b_upperleft, double b_lowerright,
double c, const wavefunction &psi, long dimens);
wavefunction sqrtwf();
wavefunction sqrtrealwf();
wavefunction mult_diag_with_diag(const wavefunction &a);
wavefunction invert();
long wf_size() const { return wf_dim; }
//
// Operators
//
wavefunction &operator*=(double z);
wavefunction &operator*=(cplxd z);
cplxd &operator[](long index)
{
// assert(index >= 0 && index < wf_dim);
return start[index];
}
const cplxd &operator[](long index) const
{
// assert(index >= 0 && index < wf_dim);
return start[index];
}
wavefunction &operator=(const wavefunction &);
private:
long wf_dim;
cplxd *start;
void do_muller_ell(cplxd timestep,
double time,
grid g,
hamop hamil,
const wavefunction &staticpot,
int me,
double charge,
int m);
void do_muller_ellm(cplxd timestep,
double time,
grid g,
hamop hamil,
const wavefunction &staticpot,
int me,
double charge);
};
ostream &operator<<(ostream &os, const wavefunction &v);
//istream& operator>>(istream& is, wavefunction& v);
cplxd operator*(const wavefunction &v, const wavefunction &w);
wavefunction operator*(double z, const wavefunction &v);
wavefunction operator*(cplxd z, const wavefunction &v);
wavefunction operator*(const wavefunction &v, double z);
wavefunction operator/(const wavefunction &v, double z);
wavefunction operator*(const wavefunction &v, cplxd z);
wavefunction operator+(const wavefunction &v, const wavefunction &vv);
wavefunction operator-(const wavefunction &v, const wavefunction &vv);
wavefunction operator+(const wavefunction &v, const fluid &vv);
wavefunction operator+(const fluid &v, const wavefunction &vv);
#endif // wavefunction_h
|
masteranza/qprop
|
base/gfunc.h
|
<gh_stars>0
#ifndef gfunc
#define gfunc gfunc
#include <wavefunction.h>
#include <grid.h>
#include <fluid.h>
class grid;
class hamop;
class wavefunction;
//
// Applies a Green's function operator 1/(H-Ek) to the wavefunction
//
void gfunc(wavefunction &psi_at_RI, wavefunction &d_psi_dr_at_RI,
double energy, wavefunction staticpot, fluid hartree_potential_zero, double nuclear_charge, grid g, wavefunction wf, double R_surff);
#endif
|
masteranza/qprop
|
base/fluid.h
|
<gh_stars>0
#ifndef fluid_h
#define fluid_h fluid_h
#include<assert.h>
#include<iostream>
#include<fstream>
#include<cmath>
#include<cstdlib>
#include<string>
using namespace std;
class grid;
class hamop;
class wavefunction;
class fluid
{
public:
fluid(long x=0) : fluid_dim(x), start(new double[x]) { }
fluid(const fluid& v)
{
fluid_dim = v.fluid_dim;
start = new double[fluid_dim];
for (long i = 0; i < fluid_dim; i++)
start[i] = v.start[i];
}
virtual ~fluid() { delete [] start;}
long wf_size() const {return fluid_dim;}
double& operator[](long index)
{
// assert(index >= 0 && index < fluid_dim);
return start[index];
}
const double& operator[](long index) const
{
// assert(index >= 0 && index < fluid_dim);
return start[index];
}
fluid& operator=(const fluid&);
fluid& operator=(const wavefunction&);
double* begin() { return start;}
double* end() { return start + fluid_dim;}
const double* begin() const { return start;}
const double* end() const { return start + fluid_dim;}
fluid& operator *= (double z);
void nullify();
void dump_to_file_sh(grid g, FILE* os, int stepwidth);
void load(FILE* os, int iv);
int init(long isize);
double integrate_along_x(grid g);
double expect_rr(grid g);
double expect_oneoverr(grid g);
double calculate_ionkinenergy(const fluid &Q, const double singlecharge, const double singlemass);
double calculate_ionpotenergy(const fluid &Q);
void embed_as_x(grid g, long yindex, long zindex, const fluid &v);
fluid extract_x(grid g, long other_one, long other_two);
private:
long fluid_dim;
double *start;
};
ostream& operator<<(ostream& os, const fluid& v);
//istream& operator>>(istream& is, fluid& v);
//istream& operator>>(ifstream& is, fluid& v);
double operator * (const fluid &v, const fluid &w );
fluid operator * (double z, const fluid &v);
fluid operator * (const fluid &v, double z);
fluid operator + (const fluid &v, const fluid &w );
fluid operator - (const fluid &v, const fluid &w );
#endif // fluid_h
|
masteranza/qprop
|
base/ylm.h
|
#ifndef ylm_h
#define ylm_h ylm_h
#include<iostream>
#include<cmath>
#include<complex>
#include<factorial.h>
typedef std::complex<double> cplxd;
using namespace std;
cplxd ylm(long l, long m, double theta, double phi);
cplxd ylm2(long l, long m, double theta, double phi);
#endif // ylm_h
|
masteranza/qprop
|
base/hamop.h
|
<filename>base/hamop.h
#ifndef hamop_h
#define hamop_h hamop_h
#include <functional>
#include <complex>
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <grid.h>
// using namespace std;
class wavefunction;
class fluid;
class hamop
{
public:
hamop(grid g,
std::function<double(double, int)> fpx,
std::function<double(double, int)> fpy,
std::function<double(double, int)> fpz,
std::function<double(double, double, double, double, int)> fpsx,
std::function<double(long, long, long, double, grid)> fpi);
hamop(void);
int init(grid g,
std::function<double(double, int)> fpx,
std::function<double(double, int)> fpy,
std::function<double(double, int)> fpz,
std::function<double(double, double, double, double, int)> fpsx,
std::function<double(long, long, long, double, grid)> fpi);
int init(std::function<double(double, int)> fpx,
std::function<double(double, int)> fpy,
std::function<double(double, int)> fpz,
std::function<double(double, double, double, double, int)> fpsx,
std::function<double(long, long, long, double, grid)> fpi);
double vecpot_x(double time, int me);
double vecpot_y(double time, int me);
double vecpot_z(double time, int me);
double scalarpot(double x, double y, double z, double time, int me);
double scalarpotx(double x, double y, double z, double time, int me);
double scalarpoty(double x, double y, double z, double time, int me);
double scalarpotz(double x, double y, double z, double time, int me);
double imagpot(long xindex, long yindex, long zindex, double time, grid g);
double field(double time, int me);
private:
double delta_x, delta_y, delta_z;
std::function<double(double, int)> hamopvecpotx;
std::function<double(double, int)> hamopvecpoty;
std::function<double(double, int)> hamopvecpotz;
std::function<double(double, double, double, double, int)> hamopscalarpotx;
std::function<double(long, long, long, double, grid)> hamopimagpot;
};
#endif // hamop_h
|
masteranza/qprop
|
base/bar.h
|
#ifndef bar_h
#define bar_h bar_h
#include<stdio.h>
#include<math.h>
#include<time.h>
bool is_time(double time_interval_s);
int put_progress_bar(FILE*,char *,long step,long no_of_steps,long len_of_bar);
int put_progress_counter(FILE*, long st, long no_st, long len, int ind);
int put_progress_counter(FILE* file, const char *c_str_format,
double acc, double time_interval_s, int ind);
#endif // bar_h
|
masteranza/qprop
|
base/winop.h
|
#ifndef winop_h
#define winop_h winop_h
#include<wavefunction.h>
#include<grid.h>
#include<fluid.h>
class grid;
class hamop;
class wavefunction;
//
// Applies a window operator W(energy, gamma) to the wavefunction
//
int winop_fullchi(wavefunction &fullchi, wavefunction &spec_result_lsub,
cplxd *spec_result_tot, double energ, double energ_width,
wavefunction staticpot, fluid hartree_potential_zero,
double nuclear_charge, grid g, wavefunction wf, int iv);
#endif // winop_h
|
XPliant/OpenXPS
|
include/openXpsAging.h
|
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* All Rights Reserved.
*
* 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.
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATIONS ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*
* FILE : openXpsAging.h
*
* Abstract: This file defines the apis for Aging Management in OpenXPS.
************************************************************************/
/**
* \file openXpsAging.h
* \brief This file contains API prototypes and type definitions
* for the openXps Aging Management
* \copyright (c) 2016 Cavium Inc
*/
#ifndef _openXpsAging_h_
#define _openXpsAging_h_
#include "openXpsTypes.h"
#include "openXpsEnums.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief This API calls the read FIFO message API to identify aged
* out entry. If it will find such entry then API will call
* process FIFO message API to call the registered handler
* and perform necessary steps on that entry
*
* \param [in] devId Device Id of device.
*
* \return XP_STATUS
*
*/
XP_STATUS xpsAgeFifoHandler(xpDevice_t devId);
/**
* \brief This API sets the Aging Mode to the global age Configuration.
*
* \param [in] devId Device Id of device.
* \param [in] ageMode Global table aging mode
*
* \return XP_STATUS
*
*/
XP_STATUS xpsSetAgingMode(xpDevice_t devId, XP_AGE_MODE_T ageMode);
/**
* \brief This API sets the Aging Cycle Unit Time into the
* global age Configuration.
*
* \param [in] devId Device Id of device.
* \param [in] unitTime Number of clock cycles
*
* \return XP_STATUS
*
*/
XP_STATUS xpsSetAgingCycleUnitTime(xpDevice_t devId, uint32_t unitTime);
#ifdef __cplusplus
}
#endif
#endif //_openXpsAging_h_
|
XPliant/OpenXPS
|
include/openXpsPlatformInterface.h
|
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* All Rights Reserved.
*
* 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.
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATIONS ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*
* FILE : openXpsPlatformInterface.h
*
* Abstract: This file defines the platform API in OpenXPS.
************************************************************************/
/**
* \file openXpsPlatformInterface.h
* \brief This file contains API prototypes and type definitions
* for the openXps Platform Interface Management
* \copyright (c) 2016 Cavium Inc
*/
#ifndef _openXpsPlatformInterface_h_
#define _openXpsPlatformInterface_h_
#include <sys/types.h>
#include "openXpsTypes.h"
#include "openXpsEnums.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Generic method for platform init.
*
* \param [in] target - Target name (svb, crb1, crb2, ...)
* \param [in] initType - possible init modes (if mode is not available use INIT_UNKNOWN)
* \param [in] diagMode
* \param [in] targetPlatformPath - Directory containing platform file
* The platform configuration file shall be placed under “targetPlatformPath/target/target.cfg”
* \return [XP_STATUS] On success XP_NO_ERR
*/
XP_STATUS xpPlatformInit(const char *target, xpInitType_t initType, bool diagMode, char *targetPlatformPath);
#ifdef __cplusplus
}
#endif
#endif // _openXpsPlatformInterface_h_
|
XPliant/OpenXPS
|
xpnet/include/xp_header.h
|
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* 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; version 2
* of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* A copy of the GNU General Public License, version 2 is available in the file
* named LICENSE-GPLv2.md either in this directory or its root.
* Alernatively to obtain a copy, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* File: xp_header.h
*
* Abstract: This file contains the XPH header definition required for XPliant.
************************************************************************/
#ifndef _XP_HEADER_H
#define _XP_HEADER_H
#include <linux/types.h>
/**
* \struct _xphRxHdrMetaData__
* \brief Rx metadata in Rx header. Max size is 64 bits.
*/
typedef struct __attribute__((__packed__)) _xphRxHdrMetaData__
{
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
uint8_t rsvd0 :8;
uint8_t rsvd2[1];
uint8_t bdId[2]; /* bdId[0] bdId[1]
MSB LSB */
uint8_t rsvd3[4];
#else
uint8_t rsvd1 :8;
uint8_t rsvd2[1];
uint8_t bdId[2]; /* bdId[0] bdId[1]
MSB LSB */
uint8_t rsvd3[4];
#endif
} xphRxHdrMetaData;
/**
* \struct _xphTxHdr__
* \brief Tx Header, to be prefixed while Packet Tx when encap
* is enabled.
*/
typedef struct __attribute__((__packed__)) _xphTxHdr__
{
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
uint8_t reserved0[8]; /* reserved0[0] reserved0[7]
MSB LSB */
uint64_t reserved1 :8;
uint64_t reserved2 :8;
uint64_t reserved3 :8;
uint64_t ingressVifLsbByte2 :8; /* MSB of ingressVif */
uint64_t ingressVifLsbByte1 :8; /* Intermidiate byte of ingressVif */
uint64_t egressVifLsbByte2 :4; /* MSN of egressVif */
uint64_t ingressVifLsbByte0 :4; /* LSN of ingressVif */
uint64_t egressVifLsbByte1 :8; /* Intermidiate byte of egressVif */
uint64_t egressVifLsbByte0 :8; /* LSB of egressVif */
uint64_t nextEngine :8;
uint64_t metadata :56;
#else
uint8_t reserved0[8]; /* reserved0[0] reserved0[7]
MSB LSB */
uint64_t reserved1 :8;
uint64_t reserved2 :8;
uint64_t reserved3 :8;
uint64_t ingressVifLsbByte2 :8; /* MSB of ingressVif */
uint64_t ingressVifLsbByte1 :8; /* Intermidiate byte of ingressVif */
uint64_t ingressVifLsbByte0 :4; /* LSN of ingressVif */
uint64_t egressVifLsbByte2 :4; /* MSN of egressVif */
uint64_t egressVifLsbByte1 :8; /* Intermidiate byte of egressVif */
uint64_t egressVifLsbByte0 :8; /* LSB of egressVif */
uint64_t nextEngine :8;
uint64_t metadata :56;
#endif
} xphTxHdr;
/**
* \struct _xphRxHdr__
* \brief Rx Header, to be parsed while Packet Rx.
*/
typedef struct __attribute__((__packed__)) _xphRxHdr__
{
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
uint8_t reserved0[8]; /* reserved0[0] reserved0[7]
MSB LSB */
uint64_t reserved1 :8;
uint64_t ingressPortNum :8;
uint64_t ingressVifLsbByte2 :8; /* MSB of ingressVif */
uint64_t ingressVifLsbByte1 :8; /* Intermidiate byte of ingressVif */
uint64_t r0 :4;
uint64_t ingressVifLsbByte0 :4; /* LSN of ingressVif */
uint64_t reasonCodeMSB :8; /* MSB of reasonCode */
uint64_t r2 :3;
uint64_t reserved3 :1;
uint64_t r1 :2;
uint64_t reasonCodeLsbs :2; /* Lsbs of reasonCode */
uint64_t r3 :8;
xphRxHdrMetaData metadata;
#else
uint8_t reserved0[8]; /* reserved0[0] reserved0[7]
MSB LSB */
uint64_t reserved1 :8;
uint64_t ingressPortNum :8;
uint64_t ingressVifLsbByte2 :8; /* MSB of ingressVif */
uint64_t ingressVifLsbByte1 :8; /* Intermidiate byte of ingressVif */
uint64_t ingressVifLsbByte0 :4; /* LSN of ingressVif */
uint64_t r0 :4;
uint64_t reasonCodeMSB :8; /* MSB of reasonCode */
uint64_t reasonCodeLsbs :2; /* Lsbs of reasonCode */
uint64_t r1 :2;
uint64_t reserved3 :1;
uint64_t r2 :3;
uint64_t r3 :8;
xphRxHdrMetaData metadata;
#endif
} xphRxHdr;
#endif /* _XP_HEADER_H */
|
XPliant/OpenXPS
|
include/openXpsInit.h
|
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* All Rights Reserved.
*
* 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.
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATIONS ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*
* FILE : openXpsInit.h
*
* Abstract: This file defines the apis for Initialization Management in OpenXPS.
************************************************************************/
/**
* \file openXpsInit.h
* \brief This file contains API prototypes and type definitions
* for the openXps Initialization Management
* \copyright (c) 2016 Cavium Inc
*/
#ifndef _openXpsInit_h_
#define _openXpsInit_h_
#include "openXpsTypes.h"
#include "openXpsEnums.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
*\brief This type defines an enumeration of the
* system specific (global) range profiles
* defined in the SDK.
* Additional Customized range profiles can be
* defined and managed within the SDK.
*/
typedef enum
{
RANGE_FULL_FEATURED = 0,
RANGE_FULL_FEATURED_2,
RANGE_ROUTE_CENTRIC,
RANGE_TUNNEL_CENTRIC,
RANGE_PROFILE_MAX
} xpsRangeProfileType_t;
/**
*\struct xpsDevConfigStruct_t
*\brief This type defines device configurations
*/
typedef struct xpsDevConfigStruct_t
{
XP_PROFILE_TYPE profileType; ///< Profile selection
xpSkuMode_e mode; ///< SKU selection
xpsDalType_e dalType; ///< Driver Abstration Layer (DAL) type selection
uint8_t skuInitSkip; ///< Skip SKU initialization
} xpsDevConfigStruct_t;
/**
* \brief Defines XDK initialization routine.
*
* This API initializes complete SDK and required data structures, managers.
* This is a device agnostic (global) initialization.
*
* \param [in] rpType
* \param [in] initType
*
* \return XP_STATUS
*/
XP_STATUS xpsSdkInit(xpsRangeProfileType_t rpType, xpsInitType_t initType);
/**
* \brief Initializes a device per default devConfigStruct
* identified by its' device ID.
*
* This API will reset the device and initialize the device to a configuration
* defined with xpsDevConfigStruct_t.
*
* \param [in] devId
* \param [in] initType - A type of initialization supported by the SDK (Cold, Warm, Warm_Sync_Shadow, Warm_Sync_Hardware).
* \param [in] devConfig - the configuration the device to be initialized with
* \param [in] packetInterface
*
* \return XP_STATUS
*/
XP_STATUS xpsSdkDefaultDevInit(xpsDevice_t devId, xpsInitType_t initType,
xpsDevConfigStruct_t *devConfig, xpPacketInterface packetInterface);
/**
* \brief Remove the device, and free corresponding data
* structures maintained in the SDK.
*
* This API will remove the device and de-initialize its corresponding data
* structures and software state.
*
* \param [in] devId
* \return XP_STATUS
*/
XP_STATUS xpsSdkDevDeInit(xpsDevice_t devId);
/**
* \brief Initialize the logger.
*
* This API will initialize the logger submodule within the SDK.
* \return const char **
*/
const char **xpsSdkLoggerInit(void);
/**
* \brief Enable logging to a file.
*
* This API will enable logging to file.
*
* \return XP_STATUS
*/
XP_STATUS xpsSdkLogToFile(const char*);
/**
* \brief Log the SDK version.
*
* This API will log the SDK version string.
*
* \return STATUS
*/
XP_STATUS xpsSdkLogVersion(void);
/**
* \brief This API sets SDK logging options.
*
* This API initializes SDK's logging options.
*
* \param [in] id
* \param [in] param
* \return STATUS
*/
XP_STATUS xpsSdkSetLoggerOptions(uint32_t id, char *param);
/**
* \brief Initialize debug shell server.
*
* This API initializes debug shell server.
*
* \return STATUS
*/
XP_STATUS xpsShellInit(void);
/**
* \brief De-initialize debug shell server.
*
* This API de-initializes debug shell server.
*
* \return STATUS
*/
XP_STATUS xpsShellDeInit(void);
#ifdef __cplusplus
}
#endif
#endif //_openXpsInit_h_
|
XPliant/OpenXPS
|
xpnet/include/xp_export.h
|
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* 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; version 2
* of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* A copy of the GNU General Public License, version 2 is available in the file
* named LICENSE-GPLv2.md either in this directory or its root.
* Alernatively to obtain a copy, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* File: xp_export.h
*
* Abstract: This file contains the enums, macros, definitions to be exported.
************************************************************************/
#ifndef _XP_EXPORT_H
#define _XP_EXPORT_H
#include <linux/if.h>
#include <linux/types.h>
#include "xp_header.h"
typedef enum xp_nl_hostif_trap_channel {
XP_NL_HOSTIF_TRAP_FD, /* Receive packets via file desriptor */
XP_NL_HOSTIF_TRAP_CB, /* Receive packets via callback */
XP_NL_HOSTIF_TRAP_NETDEV, /* Receive packets via OS net device */
XP_NL_HOSTIF_TRAP_CUSTOM_RANGE_BASE = 0x10000000
} xp_nl_hostif_trap_channel_t;
typedef enum xp_nl_operation {
XP_NL_OPERATION_ADD,
XP_NL_OPERATION_REMOVE,
XP_NL_OPERATION_ENABLE,
XP_NL_OPERATION_DISABLE,
} xp_nl_operation_t;
typedef enum xp_nl_msg {
XP_NL_MSG_INTF_ADD, /* Create a netdev interface */
XP_NL_MSG_INTF_DEL, /* Remove a netdev interface */
XP_NL_MSG_LINK_ADD, /* Link a netdev with a VIF/RIF */
XP_NL_MSG_LINK_DEL, /* Remove a netdev VIF/RIF link */
XP_NL_MSG_TX_HDR_SET, /* Add / remove a TX meta header */
XP_NL_MSG_TRAP_SET, /* Add / remove TRAP table entry */
XP_NL_MSG_CB_FD_SET, /* Add / remove FD callback */
XP_NL_MSG_MIRROR_SET, /* Enable / disable mirroring */
} xp_nl_msg_t;
typedef struct xp_nl_msg_intf {
__u32 xpnet_intf_id;
__u8 intf_name[IFNAMSIZ];
} xp_nl_msg_intf_t;
typedef struct xp_nl_msg_link {
__u32 xpnet_intf_id;
union {
__u32 vif;
__u32 rif;
};
} xp_nl_msg_link_t;
typedef struct xp_nl_msg_tx_hdr {
__u32 xpnet_intf_id;
__u8 operation;
__u8 tx_header[sizeof(xphTxHdr)];
} xp_nl_msg_tx_hdr_t;
typedef struct xp_nl_msg_trap {
__u32 rc;
__u32 fd;
__u32 ch;
__u32 trap_id;
__u8 operation;
} xp_nl_msg_trap_t;
typedef struct xp_nl_msg_cb_fd {
__u32 fd;
__u8 operation;
} xp_nl_msg_cb_fd_t;
typedef struct xp_nl_msg_mirror {
__u8 operation;
} xp_nl_msg_mirror_t;
typedef struct xp_nl_tlv_msg {
__u32 msg_type; /* xp_nl_msg_t */
__u32 payload_len; /* Len of payload[] */
__u8 payload[]; /* Payload */
} xp_nl_tlv_msg_t;
#endif /* _XP_EXPORT_H */
|
XPliant/OpenXPS
|
xpnet/src/xp_pcie_slave.c
|
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* 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; version 2
* of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* A copy of the GNU General Public License, version 2 is available in the file
* named LICENSE-GPLv2.md either in this directory or its root.
* Alernatively to obtain a copy, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* File: xp_pcie_slave.c
*
* Abstract: This file contains the pcie core/slave implementation required for
* xpliant.
************************************************************************/
#include <linux/fs.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/interrupt.h>
#include <linux/version.h>
#include <linux/pid_namespace.h>
#include <linux/netdevice.h>
#include "xp_common.h"
#include "xp_reg_info.h"
#include "xp_pcie_slave.h"
#include "xp_header.h"
#include "xp_netdev.h"
#include "version.h"
#define VENDOR_ID 0x177D
#define CNX88091_A0 0xF000
#define CNX88091_B0 0xF008
#define CNX88072_B0 0xF009
#define CNX88071_B0 0xF00A
#define CNX88061_B0 0xF00B
#define DRIVER_NAME "xpPCIe"
#define SUPPORTED_DEVICE_IDS 5
#define BYTE_MASK 0xFFU
#define WORD_MASK 0xFFFFU
#define DWORD_MASK 0xFFFFFFFFU
#define COMPATIBLE_XDK_VERSION "3.2.3"
#define XP_PCI_MAX_ADAPTERS 255
/* To restrict counts which is getting passed in copy_to_user and copy_from_user */
#define XP_MAX_BYTES_FOR_COPY 1024
/* XP80 IO memory size which should be mmaped. */
#define XP_MAX_IO_MEM (256 * 1024 * 1024)
#define XP_DMA_NODE_MINOR 1048575
#define BAR0 0 /* Base address register - 0 */
#define GET_REG 1 /* Read Flag for direction */
#define SET_REG 0 /* write flage for direction */
/* Intrupt Enable */
#define INTR_COUNT 2 /* MSI vector's count */
#define PCIE_IOCTL_ID 40 /* PCIe device ID */
#define PCIE_REG_ID 0
#define PCIE_REGISTER_ID 1
#define PHY_MEM_ALLOC_ID 2
#define PHY_MEM_FREE_ID 3
#define DMA_CLEAN_UP_ID 4
#define NETDEV_INIT_ID 5
#define NETDEV_DE_INIT_ID 6
#define DRIVER_VERSION_ID 7
#define PCIE_CONFIG_READ_ID 8
#define XP_RT_SIGNAL (SIGRTMIN + 3)
#define HIGH 1
#define LOW 0
#define TOTAL_RX_QUEUE 64
#define TOTAL_TX_QUEUE 64
#define PCI_CONFIG_SPACE_SIZE 256
#define RX_QUEUE 1
#define TX_QUEUE 0
#define XPREG_PROC_FILE_NAME "xpregaccess"
#define XPREG_PROC_FILE_PATH "/proc/" XPREG_PROC_FILE_NAME
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,16,0)
#define xp_pci_enable_msi_block(a,b) \
pci_enable_msi_range(a,b,b)
#else
#define xp_pci_enable_msi_block(a,b) \
pci_enable_msi_block(a,b)
#endif
#define INIT_NETDEV _IO(PCIE_IOCTL_ID, NETDEV_INIT_ID)
#define DMA_CLEAN_UP _IO(PCIE_IOCTL_ID, DMA_CLEAN_UP_ID)
#define REGISTER_PID _IO(PCIE_IOCTL_ID, PCIE_REGISTER_ID)
#define DEINIT_NETDEV _IO(PCIE_IOCTL_ID, NETDEV_DE_INIT_ID)
#define PCIE_REG_CMD _IOWR(PCIE_IOCTL_ID, PCIE_REG_ID, uint64_t)
#define PHY_MEM_FREE _IOWR(PCIE_IOCTL_ID, PHY_MEM_FREE_ID, uint64_t)
#define PHY_MEM_ALLOC _IOWR(PCIE_IOCTL_ID, PHY_MEM_ALLOC_ID, uint64_t)
#define GET_DRIVER_VERSION _IOWR(PCIE_IOCTL_ID, DRIVER_VERSION_ID, uint64_t)
#define PCIE_CONFIG_READ_CMD _IOWR(PCIE_IOCTL_ID, PCIE_CONFIG_READ_ID,\
uint64_t)
typedef struct __attribute__((__packed__)) xp_mem_user {
u64 addr;
u64 paddr;
u32 len;
u32 offset;
} xp_mem_user_t;
typedef struct __attribute__((__packed__)) xp_mem_info {
u64 addr;
u64 paddr;
u32 len;
u32 offset;
struct list_head list;
} xp_mem_list_t;
typedef struct xp_work {
pid_t app_pid;
struct siginfo sig_info;
struct work_struct work;
} xp_work_t;
typedef struct xp_dma_private {
struct cdev cdev;
u32 mem_index;
struct device *dev;
} xp_dma_private_t;
typedef struct xp_intr_info {
u32 reg_type : 1;
u32 block_id : 8;
u32 dev_id : 6;
u32 has_queue_info : 1;
u32 q_type : 1;
u32 q_num : 6;
u32 intr_status : 3;
u32 r0 : 6; /* Reserved */
} xp_intr_info_t;
/* Read PCIe config space */
typedef struct __attribute__((__packed__)) xp_pcie_config {
u16 offset; /* Pcie config space offset to read */
/* Size to be read in bytes this
should not be greater than 256 bytes */
u8 size;
u64 value; /* Value(s) to be read */
} xp_pcie_config_t;
#ifndef NO_NETDEV
extern netdev_tx_t xpnet_start_xmit(struct sk_buff *skb,
xpnet_private_t *net_priv);
extern int xp_netdev_init(xp_private_t *priv);
extern void xp_netdev_deinit(xp_private_t *priv);
#endif
/* User can override it via command line argument */
static bool isr_enable = 1;
/* Default 0, user can override it via command line argument */
static unsigned int dyn_pcie_dev_id;
static dev_t xp_dev;
static xp_dma_private_t *xp_dma_priv;
static unsigned int xp_pcidev_major;
static LIST_HEAD(xp_mem_list_head);
static struct class *xp_pci_class;
static u8 xp_hp_reg_bit_width[NUM_HP_INT_REG_BLOCKS] = {
1, 1, 1, 1, 1, 1, 1,
1, 1, 2, 12, 3, 4, 1,
1, 1, 1, 1, 12, 3, 4,
1, 1, 1, 1, 1, 1, 16,
2, 2, 2, 32, 1, 1, 1
};
static u8 xp_hp_reg_start_bit[NUM_HP_INT_REG_BLOCKS] = {
0, 1, 2, 3, 4, 5, 6,
7, 8, 9, 11, 23, 26, 30,
31, 32, 33, 34, 35, 47, 50,
54, 55, 56, 57, 58, 59, 60,
76, 78, 80, 82, 114, 115, 116
};
static u8 xp_hp_reg_end_bit[NUM_HP_INT_REG_BLOCKS] = {
0, 1, 2, 3, 4, 5, 6,
7, 8, 10, 22, 25, 29, 30,
31, 32, 33, 34, 46, 49, 53,
54, 55, 56, 57, 58, 59, 75,
77, 79, 81, 113, 114, 115, 116
};
static u8 xp_lp_reg_bit_width[NUM_LP_INT_REG_BLOCKS] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 12,
3, 4, 1, 1, 1, 1, 1, 12, 3, 4, 1,
1, 1, 1, 1, 1, 16, 2, 2, 2, 1, 1
};
static u8 xp_lp_reg_start_bit[NUM_LP_INT_REG_BLOCKS] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11,
23, 26, 30, 31, 32, 33, 34, 35, 47, 50, 54,
55, 56, 57, 58, 59, 60, 76, 78, 80, 82, 83
};
static u8 xp_lp_reg_end_bit[NUM_LP_INT_REG_BLOCKS] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 22,
25, 29, 30, 31, 32, 33, 34, 46, 49, 53, 54,
55, 56, 57, 58, 59, 75, 77, 79, 81, 82, 83
};
static u32 xp_reg_mask[33] = {
0x00000000, 0x00000001, 0x00000003,
0x00000007, 0x0000000f, 0x0000001f,
0x0000003f, 0x0000007f, 0x000000ff,
0x000001ff, 0x000003ff, 0x000007ff,
0x00000fff, 0x00001fff, 0x00003fff,
0x00007fff, 0x0000ffff, 0x0001ffff,
0x0003ffff, 0x0007ffff, 0x000fffff,
0x001fffff, 0x003fffff, 0x007fffff,
0x00ffffff, 0x01ffffff, 0x03ffffff,
0x07ffffff, 0x0fffffff, 0x1fffffff,
0x3fffffff, 0x7fffffff, 0xffffffff
};
u32 xp_regs_list[XP_MAX_REG_ACCESS_LIST][XP80_SUPPORTED_DEVICE_MODES] =
{ /* A0-Uncompressed, B0-Uncompressed, B0-Compressed */
/* HIGH_PRIO_REG */
{ 0x08a80080, 0x08a8019c, 0x025e819c },
/* LOW_PRIO_REG */
{ 0x08a80090, 0x08a801ac, 0x025e81ac },
/* HIGH_INTR_SOURCE_REG */
{ 0x08a8018c, 0x08a802c4, 0x025e82c4 },
/* TXDONE_STATUS_REG */
{ 0x08b50000, 0x08b50000, 0x02744000 },
/* RXDONE_STATUS_REG */
{ 0x08b50800, 0x08b50800, 0x02748000 },
/* HIGE_PRIO_INT_ENABLE_REG */
{ 0, 0x08a80180, 0x025e8180 },
/* LOW_PRIO_INT_ENABLE_REG */
{ 0, 0x08a80190, 0x025e8190 },
/* DMA0_RX_CDP_REG_E */
{ 0x08b51400, 0x08b51400, 0x02750000 },
/* DMA0_TX_CDP_REG_E */
{ 0x08b51000, 0x08b51000, 0x0274c000 },
/* DMA0_RX_CMD_REG_E */
{ 0x08b51600, 0x08b51600, 0x02750200 },
/* DMA0_TX_CMD_REG_E */
{ 0x08b51200, 0x08b51200, 0x0274c200 },
/* CORE_CTRL_REG__1_E */
{ 0x08a80168, 0x08a8028c, 0x025e828c },
/* TX_DMA0_RETRY_CNT_REG_E */
{ 0x08a802dc, 0x08a80444, 0x025e8444 },
/* MGMT_CTRL_REG_E */
{ 0x08a801a8, 0x08a802f4, 0x025e82f4 },
/* DMA0_CLR_ERR_CNT_REG_E */
{ 0x08b51300, 0x08b51300, 0x0274c300 },
/* DMA0_TX_CHAIN_LEN_ERR_REG_E */
{ 0x08b51304, 0x08b51304, 0x0274c304 },
/* DMA0_TX_CPU_OWN_DESC_ERR_REG_E */
{ 0x08b51308, 0x08b51308, 0x0274c308 },
/* DMA0_TX_ZERO_BUF_LEN_ERR_REG_E */
{ 0x08b5130c, 0x08b5130c, 0x0274c30c },
/* DMA0_TX_PCIE_ERR_REG_E */
{ 0x08b51310, 0x08b51310, 0x0274c310 },
/* DMA0_TX_DMA_INTF_ERR_REG_E */
{ 0x08b51314, 0x08b51314, 0x0274c314 },
/* DMA0_TX_PKT_DROP_E */
{ 0x08b51318, 0x08b51318, 0x0274c318 },
/* TX_DMA0_CFG_REGLOCKREG_E */
{ 0x08b5131c, 0x08b51328, 0x0274c328 },
/* TX_DMA0_SCRATCHPAD_E */
{ 0x08b51320, 0x08b5132c, 0x0274c32c },
/* DMA0_RX_CHAIN_LEN_ERR_REG_E */
{ 0x08b51700, 0x08b51700, 0x02750300 },
/* DMA0_RX_CPU_OWN_DESC_ERR_REG_E */
{ 0x08b51704, 0x08b51704, 0x02750304 },
/* DMA0_RX_ZERO_BUF_LEN_ERR_REG_E */
{ 0x08b51708, 0x08b51708, 0x02750308 },
/* DMA0_RX_PCIE_ERR_REG_E */
{ 0x08b5170c, 0x08b5170c, 0x0275030c },
/* RX_DMA0_CFG_REGLOCKREG_E */
{ 0x08b51710, 0x08b5171c, 0x0275031c },
/* RX_DMA0_SCRATCHPAD_E */
{ 0x08b51714, 0x08b51720, 0x02750320 },
/* CPU_CTRL_REG_E */
{ 0x8a80000+0x1f8, 0x8a80000+0x34c, 0x25e8000+0x34c },
/* CPU_STS_REG_E */
{ 0x8a80000+0x1fc, 0x8a80000+0x350, 0x25e8000+0x350 },
/* SRAM_MEM_CFG_SRAM_EXT_MEM_E */
{ 0x8800000+0x0, 0x8800000+0x0, 0x24a0000+0x0 },
};
#define MAX_DEV_SUPPORTED 8
static xp_private_t *xp_pcie_dev_ptr[MAX_DEV_SUPPORTED];
static int xp_driver_version_get(void __user *argp)
{
return copy_to_user(argp, COMPATIBLE_XDK_VERSION, sizeof(COMPATIBLE_XDK_VERSION));
}
int xp_dev_reg_read(u32 *rw_value, u32 reg_addr,
u8 reg_size, xp_private_t *priv, u32 count)
{
int rc = 0;
u32 i = 0;
unsigned long flags = 0;
spin_lock_irqsave(&priv->tx_dma_read_lock, flags);
switch (reg_size) {
case BYTE_SIZE:
for (i = 0; i < count; i++) {
rw_value[i] = *((u8*)((uint8_t*)(priv->vma) + reg_addr));
reg_addr += reg_size;
/* pr_debug("rw_value[i] = %x\n", %d,rw_value[i]); */
}
break;
case WORD_SIZE:
for (i = 0; i < count; i++) {
rw_value[i] = *((u16*)((uint8_t*)(priv->vma) + reg_addr));
reg_addr += reg_size;
/* pr_debug("rw_value[i] = %x\n", %d,rw_value[i]); */
}
break;
case DWORD_SIZE:
for (i = 0; i < count; i++) {
rw_value[i] = *(u32*)((uint8_t*)(priv->vma) + reg_addr);
reg_addr += reg_size;
/* pr_debug("rw_value[i] = %x\n", %d,rw_value[i]); */
/* pr_debug("rw_value = %x,
regoffset = 0x%x\n", *rw_value, reg_addr); */
/* pr_debug("%s:%d xpPrvPtr->vma = 0x%p reg_addr = %p\n",
__func__, __LINE__, priv->vma ,
((uint8_t*)(priv->vma) + reg_addr)); */
}
break;
default:
pr_err("%s: Invalid register reg_size=%x\n", __func__, reg_size);
rc = -EINVAL;
break;
}
spin_unlock_irqrestore(&priv->tx_dma_read_lock, flags);
return rc;
}
int xp_dev_reg_write(u32* rw_value, u32 reg_addr,
u8 reg_size, xp_private_t *priv, u32 count)
{
int rc = 0;
u32 i = 0;
u32 value = 0;
unsigned long flags = 0;
spin_lock_irqsave(&priv->tx_dma_read_lock, flags);
switch (reg_size) {
case BYTE_SIZE:
for (i = 0; i < count; i++) {
value = *(u32*)((uint8_t*)(priv->vma) + reg_addr);
*(u32*)((uint8_t*)(priv->vma) + reg_addr) =
(value & ~BYTE_MASK ) | (rw_value[i] & BYTE_MASK);
/* pr_debug("rw_value[i] = 0x%x\n", rw_value[i] & BYTE_MASK); */
reg_addr += reg_size;
}
break;
case WORD_SIZE:
for (i = 0; i < count; i++) {
value = *(u32*)((uint8_t*)(priv->vma) + reg_addr);
*(u32*)((uint8_t*)(priv->vma) + reg_addr) =
(value & ~WORD_MASK) | (rw_value[i] & WORD_MASK);
/* pr_debug("rw_value[i] = 0x%x\n", rw_value[i] & WORD_MASK); */
reg_addr += reg_size;
}
break;
case DWORD_SIZE:
for (i = 0; i < count; i++) {
*(u32*)((uint8_t*)(priv->vma) + reg_addr) = rw_value[i];
reg_addr += reg_size;
}
break;
default:
pr_err("%s: Invalid register rwSize = %x\n", __func__, reg_size);
rc = -EINVAL;
break;
}
spin_unlock_irqrestore(&priv->tx_dma_read_lock, flags);
return rc;
}
static void reg_procfs_help(struct seq_file *sf, int minor)
{
if(NULL == sf)
return;
seq_printf(sf, "\nUsage: echo [OPTIONS] >%s%d; cat %s%d\n\n",
XPREG_PROC_FILE_PATH, minor, XPREG_PROC_FILE_PATH, minor);
seq_printf(sf,"1) To read register value.\n"
"\techo r <regoffset> >%s%d; cat %s%d"
"\n\tex1: echo r 0x25e82f4 >%s%d; cat %s%d",
XPREG_PROC_FILE_PATH, minor, XPREG_PROC_FILE_PATH, minor,
XPREG_PROC_FILE_PATH, minor, XPREG_PROC_FILE_PATH, minor);
seq_printf(sf,"\n\n2) To write register value.\n"
"\techo w <regoffset> <value> >%s%d; cat %s%d"
"\n\tex1: echo w 0x25e82f4 0x12 >%s%d; cat %s%d",
XPREG_PROC_FILE_PATH, minor, XPREG_PROC_FILE_PATH, minor,
XPREG_PROC_FILE_PATH, minor, XPREG_PROC_FILE_PATH, minor);
seq_printf(sf,"\n\n3) To print help.\n"
"\techo help >%s%d; cat %s%d\n",
XPREG_PROC_FILE_PATH, minor, XPREG_PROC_FILE_PATH, minor);
}
static int xpreg_seq_show(struct seq_file *sf, void *v)
{
xp_private_t *xp_reg_priv = NULL;
xp_reg_priv = sf->private;
if (!strnicmp(xp_reg_priv->reg_rw_status, NAME_STR_HELP, sizeof(NAME_STR_HELP) - 1)) {
reg_procfs_help(sf, MINOR(xp_reg_priv->cdev.dev));
} else if(strlen(xp_reg_priv->reg_rw_status) < 1) {
seq_printf(sf, "Invalid input. Please find help as below..");
reg_procfs_help(sf, MINOR(xp_reg_priv->cdev.dev));
} else {
seq_printf(sf, "%s\n", xp_reg_priv->reg_rw_status);
}
return 0;
}
static int xpreg_seq_open(struct inode *inode, struct file *file)
{
xp_private_t *xp_reg_priv = NULL;
struct seq_file *s;
int result;
result = single_open(file, xpreg_seq_show, NULL);
s = (struct seq_file *)file->private_data;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0)
xp_reg_priv = PDE_DATA(file_inode(file));
#else
xp_reg_priv = PROC_I(inode)->pde->data;
#endif
s->private = xp_reg_priv;
return result;
}
static ssize_t xpreg_proc_write(struct file *filp, const char *buf,
size_t bufsize, loff_t * off)
{
u32 reg_index=0x0, reg_value=0x0;
xp_private_t *xp_reg_priv = NULL;
int rc;
if (bufsize != 0){
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0)
xp_reg_priv = PDE_DATA(file_inode(filp));
#else
struct dentry *dentry = filp->f_path.dentry;
struct inode *inode = dentry->d_inode;
xp_reg_priv = PROC_I(inode)->pde->data;
#endif
memset(xp_reg_priv->reg_rw_status, 0,
sizeof(xp_reg_priv->reg_rw_status));
if (2 == sscanf(buf, "w 0x%x 0x%x", ®_index, ®_value)) {
rc = xp_dev_reg_write(®_value,reg_index, DWORD_SIZE,
xp_reg_priv, 1);
if (rc == -EINVAL) {
snprintf(xp_reg_priv->reg_rw_status,
sizeof(xp_reg_priv->reg_rw_status) - 1,
"Register write failed\n");
} else {
snprintf(xp_reg_priv->reg_rw_status,
sizeof(xp_reg_priv->reg_rw_status) - 1,
"Write register = 0x%x value = 0x%x\n",
reg_index, reg_value);
}
} else if(1 == sscanf(buf, "r 0x%x", ®_index)) {
rc = xp_dev_reg_read(®_value,reg_index, DWORD_SIZE,
xp_reg_priv, 1);
if (rc == -EINVAL) {
snprintf(xp_reg_priv->reg_rw_status,
sizeof(xp_reg_priv->reg_rw_status) - 1,
"Register read failed\n");
} else {
snprintf(xp_reg_priv->reg_rw_status,
sizeof(xp_reg_priv->reg_rw_status) - 1,
"Read register = 0x%x value = 0x%x\n",reg_index,
reg_value);
}
} else if(!strnicmp(buf, NAME_STR_HELP, sizeof(NAME_STR_HELP) - 1)) {
snprintf(xp_reg_priv->reg_rw_status,
sizeof(xp_reg_priv->reg_rw_status) - 1,
"%s", NAME_STR_HELP);
}
}
return bufsize;
}
static const struct file_operations xpreg_proc_fops = {
.owner = THIS_MODULE,
.open = xpreg_seq_open,
.read = seq_read,
.write = xpreg_proc_write,
.llseek = seq_lseek,
.release = single_release,
};
struct proc_dir_entry *xpreg_proc_create(const char *root,
struct proc_dir_entry *parent, xp_private_t *data)
{
return proc_create_data(root, 0644, parent, &xpreg_proc_fops, data);
}
static u32 xp_block_number_get(u32 *reg_value, u32 start_bit,
u32 end_bit, u8 bit_width)
{
u8 index = 0;
u32 mask = 0x1, reg_word_0 = 0x0,
reg_word_1 = 0x0, reg_word_2 = 0x0;
/* Get the block data. */
if ((start_bit / 32) == (end_bit / 32)) {
/* If the start bit and end bit are in the same dword then
* the bits are in a single dword.
*/
index = start_bit / 32;
reg_word_0 = reg_value[index];
reg_word_0 >>= (start_bit % 32);
if (start_bit != end_bit)
mask = xp_reg_mask[bit_width];
/* else the bit width is 1 so use the default value of mask = 0x1 */
} else {
/* If the start bit and end bit are in the diffrent dwords then
* the bits are in different dwords. They need to be combined to get
* a single word.
*/
reg_word_1 = reg_value[start_bit / 32];
reg_word_1 = reg_word_1 >> (start_bit % 32);
reg_word_2 = reg_value[end_bit / 32];
reg_word_2 = reg_word_2 << (32- (start_bit % 32));
reg_word_0 = reg_word_1 | reg_word_2;
mask = xp_reg_mask[bit_width];
}
pr_debug("xppci: reg_word_0: 0x%x\n", reg_word_0);
return reg_word_0 & mask;
}
static void xp_task_work_handler(struct work_struct *w)
{
struct task_struct *task = NULL;
xp_work_t *work = container_of(w, xp_work_t, work);
if (!work->app_pid) {
pr_err("No pid is Registered for SDK.\n");
return;
}
pr_debug("Sending event with Interrupt Offset = %d\n",
work->sig_info.si_int);
pr_debug("Application Pid = %d\n", work->app_pid);
rcu_read_lock();
task = pid_task(find_pid_ns(work->app_pid, &init_pid_ns), PIDTYPE_PID);
rcu_read_unlock();
if (!task) {
pr_debug("Get Task for registered PID Fail!\n");
} else {
if (send_sig_info(XP_RT_SIGNAL, &work->sig_info, task) < 0)
pr_debug("Error in sending signal to user.\n");
}
kfree((void *)work);
}
static int xp_irq_handler(xp_private_t *priv, u8 reg_blocks,
u8 *reg_start_bits, u8 *reg_end_bits,
u8 *reg_bit_widths, u32 *intr_reg_val)
{
u32 block_num = 0, start_bit = 0, end_bit = 0, block_value = 0;
xp_work_t *task = NULL;
static xp_intr_info_t intr_info;
for (block_num = 0; block_num < reg_blocks; block_num++) {
start_bit = reg_start_bits[block_num];
end_bit = reg_end_bits[block_num];
block_value = xp_block_number_get(intr_reg_val, start_bit,
end_bit, reg_bit_widths[block_num]);
if (block_value) {
memset(&intr_info, 0, sizeof(intr_info));
intr_info.block_id = block_num;
if (reg_blocks == NUM_HP_INT_REG_BLOCKS) {
intr_info.reg_type = HIGH;
} else {
intr_info.reg_type = LOW;
}
intr_info.dev_id = MINOR(priv->cdev.dev);
task = kmalloc(sizeof(xp_work_t), GFP_ATOMIC);
if (!task) {
pr_err("Failed to allocate memory.\n");
return -ENOMEM;
}
/* Copy intr info to pass it to task handler. */
memcpy(&task->sig_info, &priv->sig_info, sizeof(task->sig_info));
memcpy(&task->sig_info.si_int,
&intr_info, sizeof(task->sig_info.si_int));
memcpy(&task->app_pid, &priv->app_pid, sizeof(task->app_pid));
if (priv->w_queue) {
INIT_WORK(&task->work, xp_task_work_handler);
}
pr_debug("block_num : %d\n", block_num);
pr_debug("Interrupt generated for block: %x\n",
task->sig_info.si_int);
queue_work(priv->w_queue, &task->work);
}
}
return 0;
}
static int xp_irq_mgmt_handler(xp_private_t *priv)
{
u8 i = 0, j = 0, bit_pos = 0;
u32 high_intr_src_reg[HIGH_INTR_SRC_REG_SIZE], status_reg_addr = 0, queue_bit_map = 0;
u32 intr_status = 0;
xp_work_t *task = NULL;
unsigned long flags = 0;
static xp_intr_info_t intr_info;
memset(&intr_info, 0, sizeof(intr_info));
for (i = 0; i < HIGH_INTR_SRC_REG_SIZE; i++) {
high_intr_src_reg[i] = 0; /* Clear the values for older interrupts. */
spin_lock_irqsave(&priv->tx_dma_read_lock, flags);
high_intr_src_reg[i] =
*((u32*)((uint8_t*)(priv->vma) +
XP_GET_PCI_BASE_OFFSET_FROM_REG_NAME(HIGH_INTR_SOURCE_REG_ADDR,
priv->mode)) + i);
spin_unlock_irqrestore(&priv->tx_dma_read_lock, flags);
if (high_intr_src_reg[i]) {
/* Get the queue number only if the bit in this register is set. */
if (i == 0) {
j = DMA0_INTR_START_BIT_POS(priv->mode);
} else {
j = 0;
}
for(; j < (sizeof(u32) * 8); j++) {
/* Check for any dma0 RX/TX interrupt bit enable or not. */
if ((high_intr_src_reg[i] >> j) & 0x1) {
intr_info.has_queue_info = 1;
break;
}
}
}
if (intr_info.has_queue_info) {
/* Calculate bit position. */
bit_pos = (i * 32) + j;
if (bit_pos >= DMA0_INTR_START_BIT_POS(priv->mode) &&
bit_pos < (TOTAL_RX_QUEUE + DMA0_INTR_START_BIT_POS(priv->mode))) {
intr_info.q_num = bit_pos - DMA0_INTR_START_BIT_POS(priv->mode);
intr_info.q_type = RX_QUEUE;
} else if (bit_pos >= (TOTAL_TX_QUEUE + DMA0_INTR_START_BIT_POS(priv->mode)) &&
bit_pos < (DMA0_INTR_START_BIT_POS(priv->mode) +
TOTAL_RX_QUEUE + TOTAL_TX_QUEUE)) {
intr_info.q_num = bit_pos -
(TOTAL_TX_QUEUE + DMA0_INTR_START_BIT_POS(priv->mode));
intr_info.q_type = TX_QUEUE;
}
intr_info.block_id = 0;
intr_info.dev_id = MINOR(priv->cdev.dev);
if (intr_info.q_type == RX_QUEUE) {
status_reg_addr =
DMA0_RXDONE(XP_GET_PCI_BASE_OFFSET_FROM_REG_NAME(
DMA0_RXDONE_STATUS_REG, priv->mode),
intr_info.q_num);
} else {
status_reg_addr =
DMA0_TXDONE(XP_GET_PCI_BASE_OFFSET_FROM_REG_NAME(
DMA0_TXDONE_STATUS_REG, priv->mode),
intr_info.q_num);
}
spin_lock_irqsave(&priv->tx_dma_read_lock, flags);
intr_status = *(u32*)((uint8_t*)(priv->vma) + status_reg_addr);
spin_unlock_irqrestore(&priv->tx_dma_read_lock, flags);
intr_info.intr_status = intr_status;
task = kmalloc(sizeof(xp_work_t), GFP_ATOMIC);
if (!task) {
pr_err("Failed to allocate memory.\n");
return -ENOMEM;
}
/* Copy intr info to pass it to task handler. */
memcpy(&task->sig_info, &priv->sig_info, sizeof(task->sig_info));
memcpy(&task->sig_info.si_int,
&intr_info, sizeof(task->sig_info.si_int));
memcpy(&task->app_pid, &priv->app_pid, sizeof(task->app_pid));
if (priv->w_queue) {
INIT_WORK(&task->work, xp_task_work_handler);
}
queue_work(priv->w_queue, &task->work);
intr_status = 0x7; /* Clear all interrupts. */
xp_dev_reg_write(&intr_status, status_reg_addr, 1, priv, 1);
queue_bit_map = 1 << j;
xp_dev_reg_write(&queue_bit_map,
XP_GET_PCI_BASE_OFFSET_FROM_REG_NAME(
HIGH_INTR_SOURCE_REG_ADDR, priv->mode) +
(i * 4), 4, priv, 1);
break;
}
}
return 0;
}
static irqreturn_t xp_msi_irq_handler_high(int irq, void *data)
{
int rc = 0;
int i = 0;
u32 reg_value[4];
unsigned long flags = 0;
xp_private_t *priv = (xp_private_t *)data;
pr_debug("XP80:%s:Interrupt handler at %d, "
"irq: %d\n", __func__, __LINE__, irq);
for (i = 0; i < XP_HP_INT_REG_SIZE_IN_DWRD; i++) {
reg_value[i] = 0; /* Clear the values for older interrupts. */
spin_lock_irqsave(&priv->tx_dma_read_lock, flags);
reg_value[i] = *((u32*)((uint8_t*)(priv->vma) +
XP_GET_PCI_BASE_OFFSET_FROM_REG_NAME(HIGH_PRIO_REG_ADDR,
priv->mode)) + i);
spin_unlock_irqrestore(&priv->tx_dma_read_lock, flags);
}
/* Bit 116 in high priority register indicates mgmt block. */
if (reg_value[3] & 0x100000) {
rc = xp_irq_mgmt_handler(priv);
if (rc < 0) {
return rc;
} else {
return IRQ_HANDLED;
}
}
if ((reg_value[0] == 0) & (reg_value[1] == 0) &
(reg_value[2] == 0) & (reg_value[3] == 0)) {
return IRQ_HANDLED;
} else {
/* Handle interrupts only if the high priority
interrupt summary register has non-zero value. */
rc = xp_irq_handler(priv, NUM_HP_INT_REG_BLOCKS, xp_hp_reg_start_bit,
xp_hp_reg_end_bit, xp_hp_reg_bit_width, reg_value);
if (rc < 0) {
pr_err("ERR: Could not handle high prioirty interrupts.\n");
return -1;
}
}
return IRQ_HANDLED;
}
static irqreturn_t xp_msi_irq_handler_low(int irq, void *data)
{
int rc = 0;
int i = 0;
u32 reg_value[4];
unsigned long flags = 0;
xp_private_t *priv = (xp_private_t *)data;
pr_debug("XP80:%s:Interrupt handler at %d, "
"irq: %d\n", __func__, __LINE__, irq);
for (i = 0; i < XP_LP_INT_REG_SIZE_IN_DWRD; i++) {
reg_value[i] = 0; /* Clear the values for older interrupts. */
spin_lock_irqsave(&priv->tx_dma_read_lock, flags);
reg_value[i] = *((u32*)((uint8_t*)(priv->vma) +
XP_GET_PCI_BASE_OFFSET_FROM_REG_NAME(LOW_PRIO_REG_ADDR,
priv->mode)) + i);
spin_unlock_irqrestore(&priv->tx_dma_read_lock, flags);
}
/* Bit 83 in low priority register indicates mgmt block. */
if(reg_value[2] & 0x80000) {
rc = xp_irq_mgmt_handler(priv);
if (rc < 0) {
return -1;
} else {
return IRQ_HANDLED;
}
}
if ((reg_value[0] == 0) & (reg_value[1] == 0) &
(reg_value[2] == 0) & (reg_value[3] == 0)) {
return IRQ_HANDLED;
} else {
rc = xp_irq_handler(priv, NUM_LP_INT_REG_BLOCKS, xp_lp_reg_start_bit,
xp_lp_reg_end_bit, xp_lp_reg_bit_width, reg_value);
if (rc < 0) {
pr_err("ERR: Could not handle low prioirty interrupts.\n");
}
}
return IRQ_HANDLED;
}
static int xp_dma_mem_access(void __user *argp, xp_dma_private_t *priv)
{
int i = 0;
int rc = 0;
size_t area = 0;
dma_addr_t mem_dma;
char *mem = NULL;
xp_mem_user_t *user_mem = NULL;
xp_mem_list_t *entry = NULL;
xp_mem_list_t *mem_info_list = NULL;
pr_debug("%s:Enter\n", __func__);
/* User level value. */
user_mem = (xp_mem_user_t *)kmalloc(sizeof(xp_mem_user_t), GFP_KERNEL);
if (user_mem == NULL) {
pr_err("Failed to allocate memory.\n");
return -ENOMEM;
}
rc = copy_from_user(user_mem, argp, sizeof(xp_mem_user_t));
if (rc) {
pr_err("Failed to copy from user space.\n");
goto err_nomem;
}
pr_info("user_mem->len = %d\n", user_mem->len);
/* Round it up to the page bondary. */
area = (size_t)((((u64)user_mem->len) + PAGE_SIZE - 1) & PAGE_MASK);
pr_info("area = %zx\n", (size_t) area);
/* Allocate a memory area with dma_alloc_coherent.
Will be rounded up to a page boundary. */
mem = dma_alloc_coherent(priv->dev, area, &mem_dma, GFP_KERNEL);
if (!mem) {
pr_err("Memory allocation fail.\n");
rc = -ENOMEM;
goto err_nomem;
}
mem_info_list = (xp_mem_list_t *)kmalloc(sizeof(xp_mem_list_t),
GFP_KERNEL);
if (mem_info_list == NULL) {
pr_err("Linked list kmalloc fail.\n");
rc = -ENOMEM;
goto err_nomem;
}
/* Linklist internal structure. */
mem_info_list->offset = priv->mem_index;
mem_info_list->addr = (u64)(size_t)mem;
mem_info_list->len = area;
mem_info_list->paddr = (u64)(size_t)mem_dma;
/* User level structure. */
user_mem->offset = priv->mem_index * PAGE_SIZE;
user_mem->addr = (u64)(size_t)mem;
user_mem->len = area;
user_mem->paddr = (u64)(size_t)mem_dma;
pr_info("mem_info_list->len : %d, mem_info_list->offset : %d,",
mem_info_list->len, mem_info_list->offset);
pr_info("mem_info_list->addr : %llu\n", mem_info_list->addr);
pr_info(" Virtual Addr : %llu, Physical Addr : %llu\n",
mem_info_list->addr, user_mem->paddr);
INIT_LIST_HEAD(&mem_info_list->list);
list_add_tail(&(mem_info_list->list), &xp_mem_list_head);
list_for_each_entry(entry, &xp_mem_list_head, list) {
pr_info("index : %d entry->len : %d,", i, entry->len);
pr_info("entry->offset : %d entry->addr : %llu\n",
entry->offset, entry->addr);
i++;
}
rc = copy_to_user((void *)argp, (void *)user_mem, sizeof(xp_mem_user_t));
if (rc)
goto err_nomem;
priv->mem_index++;
err_nomem:
kfree(user_mem);
return rc;
}
static int xp_dma_mem_free(void __user *argp, xp_dma_private_t *priv)
{
int rc = 0;
xp_mem_user_t *user_mem = NULL;
xp_mem_list_t *entry = NULL, *tmp_entry = NULL;
user_mem = (xp_mem_user_t *)kmalloc(sizeof(xp_mem_user_t), GFP_KERNEL);
if (user_mem == NULL) {
pr_err("Failed to allocate memory.\n");
return -ENOMEM;
}
rc = copy_from_user(user_mem, argp, sizeof(xp_mem_user_t));
if (rc) {
pr_err("Failed to copy from user space.");
goto err_copy_from_user;
}
list_for_each_entry_safe(entry, tmp_entry, &xp_mem_list_head, list) {
if (entry->paddr == user_mem->paddr) {
dma_free_coherent(priv->dev, entry->len,
(void*)entry->addr, (dma_addr_t)user_mem->paddr);
list_del(&entry->list);
kfree(entry);
pr_debug("Freeing node.\n");
}
}
err_copy_from_user:
kfree(user_mem);
return rc;
}
static int xp_dma_mem_cleanup(xp_dma_private_t *priv)
{
xp_mem_list_t *entry = NULL, *tmp_entry = NULL;
list_for_each_entry_safe(entry, tmp_entry, &xp_mem_list_head, list) {
pr_info("Freeing node : %llu\n", entry->paddr);
dma_free_coherent(priv->dev, entry->len,
(void*)entry->addr, (dma_addr_t)entry->paddr);
list_del(&entry->list);
kfree(entry);
}
pr_info("DMA cleanup done.\n");
priv->mem_index = 0;
return 0;
}
static int xp_dma_open(struct inode *inode, struct file *filp)
{
pr_info("PCI DMA node opened.");
filp->private_data = container_of(inode->i_cdev, xp_dma_private_t, cdev);
return 0;
}
static int xp_dma_close(struct inode *inode, struct file *filp)
{
pr_info("PCI node closed with minor number : %d\n", iminor(inode));
filp->private_data = NULL;
return 0;
}
static int xp_dma_mmap(struct file *filp, struct vm_area_struct *vma)
{
int mem_len = 0;
char *usr_addr = NULL;
xp_mem_list_t *entry = NULL;
long length = vma->vm_end - vma->vm_start;
xp_dma_private_t *priv = filp->private_data;
pr_debug("%s:Enter\n", __func__);
/* Page offset is bigger than allocated memory then return error. */
if (vma->vm_pgoff >= priv->mem_index) {
pr_err("Error xp_dma_mmap, invalid page offset.\n");
/* At any other offset we return an error. */
return -EIO;
}
/* Traversing loop for user specific offset. */
list_for_each_entry(entry, &xp_mem_list_head, list) {
pr_debug(" entry->offset= %d\t vma->vm_pgoff =%ld\n",
entry->offset, vma->vm_pgoff);
if (entry->offset == vma->vm_pgoff) {
pr_info("%s: entry->len : %d, entry->offset : %d, "
"entry->addr =%llu\n", __func__,
entry->len, entry->offset, entry->addr);
mem_len = entry->len;
usr_addr = (char*)entry->addr;
break;
}
}
pr_info("\n:mem_len=%d usr_addr = %p length = %ld\n",
mem_len, usr_addr, length);
/* Check length - do not allow larger mappings
than the number of pages allocated. */
if (length > mem_len) {
pr_err("Requested length of memory not available.\n");
return -ENOMEM;
}
pr_debug("\nMAP Memory.\n");
/* We must make this descriptor and buffer memory as
* non-cacheable mmaped to user space */
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
/* Map the whole physically contiguous area in one piece. */
return remap_pfn_range(vma, vma->vm_start,
virt_to_phys((void *)usr_addr) >> PAGE_SHIFT,
length, vma->vm_page_prot);
}
static long xp_dma_ioctl(struct file *filp,
unsigned int cmd, unsigned long arg)
{
long rc = 0;
void __user *argp = (void __user *)arg;
xp_dma_private_t *priv = filp->private_data;
/*pr_debug("%s:Enter\n", __func__);*/
/* This command is not involved in any DMA operation so don't check
* coherent_dma_mask flag. */
if (cmd == GET_DRIVER_VERSION) {
return xp_driver_version_get(argp);
} /* For all other commands check coherent_dma_mask flag. */
else if (!(priv->dev->coherent_dma_mask)) {
pr_err("Coherent_dma_mask is not set.\n");
return -ENODEV;
}
switch (cmd) {
case PHY_MEM_ALLOC:
pr_info("Physical memory allocation request.\n");
rc = xp_dma_mem_access(argp, priv);
break;
case PHY_MEM_FREE:
pr_info("Physical memory free request.\n");
rc = xp_dma_mem_free(argp, priv);
break;
case DMA_CLEAN_UP:
pr_info("DMA memory clean up request.\n");
rc = xp_dma_mem_cleanup(priv);
break;
default:
pr_err("XP DMA Invalid IOCTL command.\n");
return -EINVAL;
}
/*pr_debug("%s:Exit\n", __func__);*/
return rc;
}
static long xp_dma_compat_ioctl(struct file *filp,
unsigned int cmd, unsigned long arg)
{
long rc = 0;
void __user *argp = (void __user *)arg;
xp_dma_private_t *priv = filp->private_data;
/*pr_debug("%s:Enter\n", __func__);*/
/* This command is not involved in any DMA operation so don't check
* coherent_dma_mask flag. */
if (cmd == GET_DRIVER_VERSION) {
return xp_driver_version_get(argp);
} /* For all other commands check coherent_dma_mask flag. */
else if (!(priv->dev->coherent_dma_mask)) {
pr_err("Coherent_dma_mask is not set.\n");
return -ENODEV;
}
switch (cmd) {
case PHY_MEM_ALLOC:
pr_info("Physical memory allocation request.\n");
rc = xp_dma_mem_access(argp, priv);
break;
case PHY_MEM_FREE:
pr_info("Physical memory free request.\n");
rc = xp_dma_mem_free(argp, priv);
break;
case DMA_CLEAN_UP:
pr_info("DMA memory clean up request.\n");
rc = xp_dma_mem_cleanup(priv);
break;
default:
pr_err("XP DMA Invalid IOCTL command.\n");
return -EINVAL;
}
/*pr_debug("%s:Exit\n", __func__);*/
return rc;
}
static struct file_operations xp_dma_fops = {
.owner = THIS_MODULE,
.open = xp_dma_open,
.release = xp_dma_close,
.mmap = xp_dma_mmap,
.unlocked_ioctl = xp_dma_ioctl,
.compat_ioctl = xp_dma_compat_ioctl,
};
static int xp_dev_reg_access(void __user *argp, xp_private_t *priv)
{
int rc = 0;
u8 reg_size = 0;
u32 reg_addr = 0;
u32 count = 0;
u32 copy_count = 0, count_value = 0;
u8 idx = 0;
xp_reg_rw_t *pci_rw = NULL;
u32 *tmp_value = NULL, *tmp_alias = NULL;
pci_rw = (xp_reg_rw_t *) kmalloc(sizeof(xp_reg_rw_t), GFP_KERNEL);
if (pci_rw == NULL) {
pr_err("Failed to allocate memory.\n");
return -ENOMEM;
}
rc = copy_from_user(pci_rw, argp, sizeof(xp_reg_rw_t));
if (rc) {
pr_err("Failed to copy from user space.\n");
goto err_mem_pci_rw;
}
if(!(pci_rw->size % DWORD_SIZE))
{
count = pci_rw->size/DWORD_SIZE;
pci_rw->size = DWORD_SIZE;
}
else if(pci_rw->size == WORD_SIZE)
{
pci_rw->size = WORD_SIZE;
count = 1;
}
else
{
count = pci_rw->size;
pci_rw->size = BYTE_SIZE;
}
if (!count) {
rc = -EINVAL;
goto err_mem_pci_rw;
}
//printk("count = %d, pci_rw->size = %d \n", count, pci_rw->size);
reg_size = pci_rw->size;
reg_addr = pci_rw->reg_address;
tmp_value = kmalloc(count * sizeof(u32), GFP_KERNEL);
if (!tmp_value) {
rc = -ENOMEM;
goto err_mem_pci_rw;
}
if (pci_rw->direction == SET_REG) {
count_value = count * reg_size;
do
{
copy_count = (count_value > XP_MAX_BYTES_FOR_COPY) ? XP_MAX_BYTES_FOR_COPY : count_value;
count_value -= copy_count;
if (copy_from_user(((u8*)tmp_value + (idx * XP_MAX_BYTES_FOR_COPY)), (void*)(pci_rw->value + (idx * XP_MAX_BYTES_FOR_COPY)), copy_count)) {
rc = -EFAULT;
goto err_mem_tmp;
}
idx++;
}while(count_value);
rc = xp_dev_reg_write(tmp_value, reg_addr, reg_size, priv, count);
if (rc) {
rc = -EFAULT;
goto err_mem_tmp;
}
} else if (pci_rw->direction == GET_REG) {
tmp_alias = tmp_value;
rc = xp_dev_reg_read(tmp_value, reg_addr, reg_size, priv, count);
if (rc) {
rc = -EFAULT;
goto err_mem_tmp;
}
count_value = count * sizeof (u32);
do
{
copy_count = (count_value > XP_MAX_BYTES_FOR_COPY) ? XP_MAX_BYTES_FOR_COPY : count_value;
count_value -= copy_count;
if (copy_to_user((void *) (pci_rw->value + (idx * XP_MAX_BYTES_FOR_COPY)), ((u8 *) tmp_alias + (idx * XP_MAX_BYTES_FOR_COPY)), copy_count)){
rc = -EFAULT;
}
idx++;
}while (count_value);
} else {
pr_err("%s: Invalid choice of reg direction=%x\n",
__func__, pci_rw->direction);
rc = -EINVAL;
}
err_mem_tmp:
kfree(tmp_value);
err_mem_pci_rw:
kfree(pci_rw);
return rc;
}
static int xp_pci_conf_get(void __user *argp, xp_private_t *priv)
{
int i = 0;
int rc = 0;
u16 offset = 0;
u8 count = 0;
xp_pcie_config_t *conf = NULL;
u8 *tmp_value = NULL, *tmp_alias = NULL;
conf = (xp_pcie_config_t *) kmalloc(sizeof(xp_pcie_config_t), GFP_KERNEL);
if (conf == NULL) {
pr_err("Failed to allocate memory.\n");
return -ENOMEM;
}
rc = copy_from_user(conf, argp, sizeof(xp_pcie_config_t));
if (rc) {
pr_err("Failed to copy from user space.\n");
goto err_copy_config;
}
/* Copy value in local variables. */
count = conf->size;
if (!count) {
rc = -EINVAL;
goto err_copy_config;
}
offset = conf->offset;
if ((offset + count) > PCI_CONFIG_SPACE_SIZE) {
rc = -EINVAL;
goto err_copy_config;
}
tmp_value = kmalloc(count * sizeof(u8), GFP_KERNEL);
if (!tmp_value) {
rc = -ENOMEM;
goto err_copy_config;
}
tmp_alias = tmp_value;
for (i = 0; i < count; i++) {
pci_read_config_byte(priv->pdev, offset, &tmp_value[i]);
if (rc) {
rc = -EFAULT;
goto err_config_read;
}
offset++;
}
if (copy_to_user((void *)conf->value,
tmp_alias, count * sizeof(u8)))
rc = -EFAULT;
err_config_read:
kfree(tmp_value);
err_copy_config:
kfree(conf);
return rc;
}
static int xp_dev_open(struct inode *inode, struct file *filp)
{
pr_info("PCI node opened with minor number : %d\n", iminor(inode));
filp->private_data = container_of(inode->i_cdev, xp_private_t, cdev);
return 0;
}
static int xp_dev_close(struct inode *inode, struct file *filp)
{
pr_info("PCI node closed with minor number : %d\n", iminor(inode));
filp->private_data = NULL;
return 0;
}
static int xp_dev_mmap(struct file *filp, struct vm_area_struct *vma)
{
xp_private_t *priv = filp->private_data;
unsigned int vsize = vma->vm_end - vma->vm_start;
pr_info("MMAP request from minor number : %d\n", MINOR(priv->cdev.dev));
if (vsize > XP_MAX_IO_MEM) {
pr_err("Invalid size : Requested size %d is greater "
"than available size %d\n", vsize, XP_MAX_IO_MEM);
return -EINVAL;
}
vma->vm_flags |= VM_IO;
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
pr_info("Base Addr: 0x%lx\n",
(unsigned long int)pci_resource_start(priv->pdev, BAR0));
return io_remap_pfn_range(vma, vma->vm_start,
pci_resource_start(priv->pdev, BAR0)
>> PAGE_SHIFT, vsize, vma->vm_page_prot);
}
static long xp_dev_ioctl(struct file *filp,
unsigned int cmd, unsigned long arg)
{
long rc = 0;
void __user *argp = (void __user *)arg;
xp_private_t *priv = filp->private_data;
/*pr_debug("%s:Enter\n", __func__);*/
switch (cmd) {
case PCIE_REG_CMD:
rc = xp_dev_reg_access(argp, priv);
break;
case REGISTER_PID:
priv->sig_info.si_pid = current->tgid;
priv->app_pid = current->pid;
pr_debug("Registered Pid = %d\n", priv->app_pid);
break;
#ifndef NO_NETDEV
case INIT_NETDEV:
pr_info("Netdev init request.\n");
rc = xp_netdev_init(priv);
break;
case DEINIT_NETDEV:
pr_info("Netdev deinit request.\n");
xp_netdev_deinit(priv);
break;
#endif
case PCIE_CONFIG_READ_CMD:
pr_info(KERN_INFO "Pcie config space read request.\n");
rc = xp_pci_conf_get(argp, priv);
break;
default:
pr_err("XP80 PCI Invalid IOCTL command.\n");
return -EINVAL;
}
/*pr_debug("%s:Exit\n", __func__);*/
return rc;
}
static long xp_dev_compat_ioctl(struct file *filp,
unsigned int cmd, unsigned long arg)
{
long rc = 0;
void __user *argp = (void __user *)arg;
xp_private_t *priv = filp->private_data;
/*pr_debug("%s:Enter\n", __func__);*/
switch (cmd) {
case PCIE_REG_CMD:
rc = xp_dev_reg_access(argp, priv);
break;
case REGISTER_PID:
priv->sig_info.si_pid = current->tgid;
priv->app_pid = current->pid;
pr_debug("Registered Pid = %d\n", priv->app_pid);
break;
#ifndef NO_NETDEV
case INIT_NETDEV:
pr_info("Netdev init request.\n");
rc = xp_netdev_init(priv);
break;
case DEINIT_NETDEV:
pr_info("Netdev deinit request.\n");
xp_netdev_deinit(priv);
break;
#endif
case PCIE_CONFIG_READ_CMD:
pr_info(KERN_INFO "Pcie config space read request.\n");
rc = xp_pci_conf_get(argp, priv);
break;
default:
pr_err("XP80 PCI Invalid IOCTL command.\n");
return -EINVAL;
}
/*pr_debug("%s:Exit\n", __func__);*/
return rc;
}
static struct file_operations xp_dev_fops = {
.owner = THIS_MODULE,
.open = xp_dev_open,
.release = xp_dev_close,
.mmap = xp_dev_mmap,
.unlocked_ioctl = xp_dev_ioctl,
.compat_ioctl = xp_dev_compat_ioctl,
};
static int xp_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
char queue_name[25];
u16 dev_id = 0;
int rc = 0, msi_count = 0;
u32 mmio_start = 0, mmio_len = 0;
xp_private_t *priv = NULL;
struct device *pci_device;
static int minor;
static int instance;
/* Minor number is 20 bit field so max minor number can be 1048575,
* but we have reserved 1048575 for DMA node. */
if (WARN_ON(minor > 1048574)) {
pr_warn("Warning : Please restart system, no more minor available.\n");
return -EINVAL;
}
/* Allocate memory for private structure. */
priv = kzalloc(sizeof(xp_private_t), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->pdev = pdev;
rc = pci_enable_device(priv->pdev);
if (rc) {
pr_err("%s: pci_enable_device failed.\n", __func__);
rc = -EFAULT;
goto err_free_memory;
}
rc = pci_request_regions(priv->pdev, pci_name(priv->pdev));
if (rc) {
pr_err("Unable to request regions. (%s)\n", pci_name(priv->pdev));
rc = -ENOMEM;
goto err_req_region;
}
rc = pci_set_dma_mask(priv->pdev, 0xFFFFFFFF);
if (!rc) {
pr_debug("setConsitentDma Mask to 64\n");
/* The query for consistent allocations is performed via a call. */
rc = pci_set_consistent_dma_mask(priv->pdev, 0xFFFFFFFF);
if (rc) {
dev_err(&priv->pdev->dev,
"No usable DMA configuration, aborting\n");
goto err_dma;
}
} else {
pr_debug("setConsitentDma Mask to 32\n");
rc = pci_set_dma_mask(priv->pdev, DMA_BIT_MASK(32));
if (!rc) {
rc = pci_set_consistent_dma_mask(priv->pdev, DMA_BIT_MASK(32));
if (rc) {
dev_err(&priv->pdev->dev,
"No usable DMA configuration, aborting.\n");
goto err_dma;
}
}
}
/* Copy DMA mask and other details to dma private strcture. */
if (!(xp_dma_priv->dev->coherent_dma_mask)) {
if (priv->pdev->dev.dma_mask) {
*(xp_dma_priv->dev->dma_mask) = *(priv->pdev->dev.dma_mask);
}
xp_dma_priv->dev->coherent_dma_mask =
priv->pdev->dev.coherent_dma_mask;
if (priv->pdev->dev.dma_parms) {
memcpy(xp_dma_priv->dev->dma_parms, priv->pdev->dev.dma_parms,
sizeof(struct device_dma_parameters));
}
}
/* Enable the Dma by setting Bus master bit in the PCI_COMMAND register. */
pci_set_master(priv->pdev);
if (!pci_is_pcie(priv->pdev)) {
pr_err("Can't find PCI Express capability!\n");
rc = -EFAULT;
goto err_free_memory;
}
/* Save the PCI configuration space of a device before suspending. */
rc = pci_save_state(priv->pdev);
if (rc) {
pr_err("xp80: Failed to save state.\n");
rc = -EFAULT;
goto err_free_memory;
}
pci_set_drvdata(priv->pdev, priv);
if (isr_enable) {
msi_count = xp_pci_enable_msi_block(priv->pdev, INTR_COUNT);
if (msi_count < 0) {
pr_debug("xp80: Failed to enable MSI.\n");
priv->msi_fail = 1;
pr_warn("Warning : BOTH MSI registration failed.\n");
}
if (msi_count != 0 && msi_count < INTR_COUNT) {
rc = xp_pci_enable_msi_block(priv->pdev, msi_count);
if (rc < 0) {
priv->msi_fail = 1;
pr_warn("Warning : BOTH MSI registration failed.\n");
}
}
if (!(priv->msi_fail)) {
priv->msi_count = msi_count;
priv->irq = priv->pdev->irq;
sprintf(queue_name, "xp_queue_%d", instance);
/* Create Workqueue. */
priv->w_queue = create_workqueue(queue_name);
rc = request_irq(priv->pdev->irq,
xp_msi_irq_handler_high, 0, DRIVER_NAME, priv);
if (rc) {
pr_err("Failed to register MSI.\n");
rc = -ENODEV;
goto err_free_memory;
}
if (!msi_count) {
rc = request_irq(priv->pdev->irq + 1,
xp_msi_irq_handler_low, 0, DRIVER_NAME, priv);
if (rc) {
pr_err("Failed to register MSI.\n");
rc = -ENODEV;
}
} else {
pr_warn("Warning : Only High Priority MSI INTR is enabled.\n");
}
}
}
mmio_start = pci_resource_start(priv->pdev, BAR0);
mmio_len = pci_resource_len(priv->pdev, BAR0);
/* For A0 revision we need to map only
256M even though BAR advertises for 512M. */
#if 0
xpMmioLen = xpMmioLen / 2;
#endif
if (mmio_len) {
pr_debug("BAR_0 Base is %x size is %d successfull.\n",
mmio_start, mmio_len);
} else {
pr_err("BAR_0 Base is %x size is %d failed.\n", mmio_start, mmio_len);
rc = -ENOMEM;
goto cleanup_ports;
}
pr_debug("mmio_start: 0x%x mmio_len: 0x%x\n", mmio_start, mmio_len);
priv->vma = pci_iomap(priv->pdev, BAR0, mmio_len);
if (!priv->vma) {
rc = -ENOMEM;
goto err_pci_iomap;
}
pr_debug("%s::%d va:%pK pa:%llx\n",
__FILE__, __LINE__, priv->vma, (u64)__pa(priv->vma));
priv->mmio_start = mmio_start;
priv->mmio_end = priv->vma + mmio_len;
pr_info("Mapped BAR0 Address is %zx :: Mapped memLen is %d MBytes.\n",
(size_t)priv->vma, mmio_len / (1024 * 1024));
/* Reading PCI register space to identify the device. */
pci_read_config_word(priv->pdev, PCI_DEVICE_ID, &dev_id);
if (dev_id == CNX88091_A0) {
priv->mode = XP_A0_UNCOMPRESSED;
} else if ((dev_id == CNX88091_B0) || (dev_id == CNX88072_B0)) {
/* Verifying between compress and decompress mode. */
if (64 == mmio_len / (1024 * 1024)) {
priv->mode = XP_B0_COMPRESSED;
} else {
priv->mode = XP_B0_UNCOMPRESSED;
}
} else {
pr_debug(KERN_ERR "xp80: Failed to read configuration space.\n");
rc = -EFAULT;
goto err_free_memory;
}
cdev_init(&priv->cdev, &xp_dev_fops);
priv->cdev.owner = THIS_MODULE;
rc = cdev_add(&priv->cdev, MKDEV(xp_pcidev_major, minor), 1);
if (rc)
goto err_cdev_add;
pci_device = device_create(xp_pci_class, NULL,
MKDEV(xp_pcidev_major, minor),
NULL, "%s%u", "xppcidev", minor);
if (!pci_device)
goto err_device_create;
pr_debug("Device : %s%u created with Major : %d and Minor: %u",
"xppcidev", minor, xp_pcidev_major, minor);
priv->sig_info.si_signo = XP_RT_SIGNAL;
priv->sig_info.si_errno = 0;
priv->sig_info.si_code = SI_QUEUE;
priv->sig_info.si_pid = current->tgid;
priv->sig_info.si_int = 0;
priv->app_pid = current->pid;
priv->xpnet = 0;
spin_lock_init(&priv->tx_dma_read_lock);
memset(priv->proc_fs_name, 0, sizeof(priv->proc_fs_name));
snprintf(priv->proc_fs_name, sizeof(priv->proc_fs_name) - 1, "%s%u",
XPREG_PROC_FILE_NAME, minor);
priv->reg_proc = xpreg_proc_create(priv->proc_fs_name, NULL, priv);
if(NULL == priv->reg_proc){
pr_err("XP: xpreg_proc_create failed.\n");
}
if (minor < MAX_DEV_SUPPORTED) {
xp_pcie_dev_ptr[minor] = priv;
}
/* For each device there should be new workqueue instance. */
instance++;
minor++;
pr_info("XP: Pcie Slave Probe successful.\n");
return 0;
err_device_create:
cdev_del(&priv->cdev);
err_cdev_add:
pci_iounmap(priv->pdev, priv->vma);
err_pci_iomap:
pci_release_region(priv->pdev, BAR0);
cleanup_ports:
release_region(mmio_start, mmio_len);
err_dma:
err_req_region:
pci_disable_device(priv->pdev);
err_free_memory:
if (priv && priv->w_queue) {
flush_workqueue(priv->w_queue);
destroy_workqueue(priv->w_queue);
kfree(priv);
}
pr_err("Failed to probe.\n");
return rc;
}
static void xp_pci_remove(struct pci_dev *pdev)
{
xp_private_t *priv = pci_get_drvdata(pdev);
int minor = MINOR(priv->cdev.dev);
#ifndef NO_NETDEV
xp_netdev_deinit(priv);
#endif
device_destroy(xp_pci_class,
MKDEV(xp_pcidev_major, MINOR(priv->cdev.dev)));
cdev_del(&priv->cdev);
/* Release region. */
pci_iounmap(pdev, priv->vma);
pci_release_region(priv->pdev, BAR0);
/* No need to check isr_enable value. */
if (isr_enable && !(priv->msi_fail)) {
/* Free both irq. */
free_irq(pdev->irq, priv);
if (!priv->msi_count)
free_irq(pdev->irq + 1, priv);
/* Msi disable. */
pci_disable_msi(pdev);
/* Flush and destroy workqueue. */
flush_workqueue(priv->w_queue);
destroy_workqueue(priv->w_queue);
}
if(NULL != priv->reg_proc){
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0)
proc_remove(priv->reg_proc);
#else
remove_proc_entry(priv->proc_fs_name, NULL);
#endif
}
kfree(priv);
/* PCIe disable device. */
pci_disable_device(pdev);
unregister_chrdev(xp_pcidev_major, DRIVER_NAME);
if (minor < MAX_DEV_SUPPORTED) {
xp_pcie_dev_ptr[minor] = NULL;
}
pr_info("XP: Pci module remove successful.\n");
}
static struct pci_device_id xp_pci_ids[SUPPORTED_DEVICE_IDS + 2] = {
{ PCI_DEVICE(VENDOR_ID, CNX88091_A0), },
{ PCI_DEVICE(VENDOR_ID, CNX88091_B0), },
{ PCI_DEVICE(VENDOR_ID, CNX88072_B0), },
{ PCI_DEVICE(VENDOR_ID, CNX88061_B0), },
{ PCI_DEVICE(VENDOR_ID, CNX88071_B0), },
/* Reserved for command line argument */
{ PCI_DEVICE(VENDOR_ID, 0), },
{ 0, }
};
static struct pci_driver xp_pci_driver = {
.name = DRIVER_NAME,
.probe = xp_pci_probe,
.id_table = xp_pci_ids,
.remove = xp_pci_remove,
};
static int __init xp_module_init(void)
{
int rc = 0, i = 0, update_pci_table = 0;
pr_info("XP80 PCIe End Point Driver (version: %s).\n", XPTOOLS_VERSION),
pr_info("Compatible XDK (version: %s).\n", COMPATIBLE_XDK_VERSION),
pr_info("Copyright(c) 2013 Xpliant INC.\n");
/* Create sys class */
xp_pci_class = class_create(THIS_MODULE, "xppci");
if (!xp_pci_class) {
pr_debug("xpPcie driver : Error in creating class.\n\n");
return -ENOMEM;
}
/* Register char device, allocate major number. */
if (alloc_chrdev_region(&xp_dev, 0, XP_PCI_MAX_ADAPTERS, "xpPCI")) {
pr_debug("xpPcie driver : Error in allocating dev_t.\n");
rc = -EBUSY;
goto err_alloc_chrdev_region;
}
xp_pcidev_major = MAJOR(xp_dev);
pr_info("XP: Pcie Slave Driver: MAJOR NUMBER:= %d\n", xp_pcidev_major);
/* Allocate memory for private structure of DMA allocator. */
xp_dma_priv = kzalloc(sizeof(xp_dma_private_t), GFP_KERNEL);
if (!xp_dma_priv)
goto err_dma_prv_alloc;
cdev_init(&xp_dma_priv->cdev, &xp_dma_fops);
xp_dma_priv->cdev.owner = THIS_MODULE;
if (cdev_add(&xp_dma_priv->cdev,
MKDEV(xp_pcidev_major, XP_DMA_NODE_MINOR), 1))
goto err_cdev_dma_add;
xp_dma_priv->dev = device_create(xp_pci_class, NULL,
MKDEV(xp_pcidev_major, XP_DMA_NODE_MINOR), NULL, "%s", "xpdmamem");
if (!xp_dma_priv->dev)
goto err_device_create_dma;
pr_debug("Device : %s created with Major : %d and Minor: %u",
"xpdmamem", xp_pcidev_major, XP_DMA_NODE_MINOR);
/* It will be updated by probe of first device. */
xp_dma_priv->dev->coherent_dma_mask = 0;
xp_dma_priv->dev->dma_mask = kzalloc(sizeof(u64), GFP_KERNEL);
if (!(xp_dma_priv->dev->dma_mask))
goto err_dma_mask_alloc;
xp_dma_priv->dev->dma_parms =
kzalloc(sizeof(struct device_dma_parameters), GFP_KERNEL);
if (!(xp_dma_priv->dev->dma_parms))
goto err_dma_parms_alloc;
if (dyn_pcie_dev_id) {
/* Add device Id supplied by user in PCIe table. */
update_pci_table = 1;
/* Check existing device id list. */
for (i = 0; i < SUPPORTED_DEVICE_IDS; i++) {
if (xp_pci_ids[i].device == dyn_pcie_dev_id) {
pr_debug("Device ID : 0x%x is already part of PCIe table.\n",
dyn_pcie_dev_id);
update_pci_table = 0; /* Already present in PCIe table. */
}
}
}
if (update_pci_table) {
xp_pci_ids[SUPPORTED_DEVICE_IDS].device = dyn_pcie_dev_id;
pr_debug("Added 0x%x as part of PCIe table.\n", dyn_pcie_dev_id);
} else { /* Make invalid entry at SUPPORTED_DEVICE_IDS index. */
memset(&(xp_pci_ids[SUPPORTED_DEVICE_IDS]),
0x00, sizeof(struct pci_device_id));
pr_debug("Reset %d index of PCIe table.\n", SUPPORTED_DEVICE_IDS);
}
rc = pci_register_driver(&xp_pci_driver);
if (rc < 0) {
pr_err("PCI registration failed.\n");
goto err_pci_driver_register;
}
return 0;
err_pci_driver_register:
kfree(xp_dma_priv->dev->dma_parms);
err_dma_parms_alloc:
kfree(xp_dma_priv->dev->dma_mask);
err_dma_mask_alloc:
device_destroy(xp_pci_class,
MKDEV(xp_pcidev_major, MINOR(xp_dma_priv->cdev.dev)));
err_device_create_dma:
cdev_del(&xp_dma_priv->cdev);
err_cdev_dma_add:
kfree(xp_dma_priv);
xp_dma_priv = NULL;
err_dma_prv_alloc:
unregister_chrdev_region(xp_dev, XP_PCI_MAX_ADAPTERS);
err_alloc_chrdev_region:
class_destroy(xp_pci_class);
return rc;
}
static void __exit xp_module_exit(void)
{
if (xp_dma_priv) {
/* Cleanup allocated DMA memory, give it back to kernel. */
if (xp_dma_priv->dev->coherent_dma_mask)
xp_dma_mem_cleanup(xp_dma_priv);
kfree(xp_dma_priv->dev->dma_mask);
kfree(xp_dma_priv->dev->dma_parms);
device_destroy(xp_pci_class, MKDEV(xp_pcidev_major,
MINOR(xp_dma_priv->cdev.dev)));
cdev_del(&xp_dma_priv->cdev);
kfree(xp_dma_priv);
xp_dma_priv = NULL;
pci_unregister_driver(&xp_pci_driver);
unregister_chrdev_region(xp_dev, XP_PCI_MAX_ADAPTERS);
class_destroy(xp_pci_class);
}
pr_info("XP80 PCIe Unregistered successful.\n");
}
s32 xp_pci_drv_write_reg(int dev, u32 rw_value,
u32 reg_addr, u8 reg_size)
{
if (dev >= MAX_DEV_SUPPORTED) {
return -1;
}
if (NULL == xp_pcie_dev_ptr[dev]) {
return -1;
}
return xp_dev_reg_write(&rw_value, reg_addr,
reg_size, xp_pcie_dev_ptr[dev], 1);
}
s32 xp_pci_drv_read_reg(int dev, u32 *rw_value,
u32 reg_addr, u8 reg_size)
{
if (dev >= MAX_DEV_SUPPORTED) {
return -1;
}
if (NULL == xp_pcie_dev_ptr[dev]) {
return -1;
}
return xp_dev_reg_read(rw_value, reg_addr,
reg_size, xp_pcie_dev_ptr[dev], 1);
}
u32 xp_get_reg_addr_by_id(int dev, s32 reg_id) {
if (dev >= MAX_DEV_SUPPORTED) {
return -1;
}
if (NULL == xp_pcie_dev_ptr[dev]) {
return -1;
}
return XP_GET_PCI_BASE_OFFSET_FROM_REG_NAME(reg_id,
xp_pcie_dev_ptr[dev]->mode);
}
#ifndef NO_NETDEV
int xp_packet_send(int dev, struct sk_buff *skb) {
if (dev >= MAX_DEV_SUPPORTED) {
return -1;
}
if (NULL == xp_pcie_dev_ptr[dev]) {
return -1;
}
if (! xp_pcie_dev_ptr[dev]->xpnet) {
xp_netdev_init(xp_pcie_dev_ptr[dev]);
}
if (! xp_pcie_dev_ptr[dev]->xpnet) {
printk("Net probe error...\n");
return -1;
}
if (0 != xpnet_start_xmit(skb, xp_pcie_dev_ptr[dev]->xpnet)) {
printk("xmit failed DMA is busy...\n");
return -1;
}
return 0;
}
EXPORT_SYMBOL(xp_packet_send);
#endif
EXPORT_SYMBOL(xp_pci_drv_write_reg);
EXPORT_SYMBOL(xp_pci_drv_read_reg);
EXPORT_SYMBOL(xp_get_reg_addr_by_id);
module_init(xp_module_init);
module_exit(xp_module_exit);
module_param(dyn_pcie_dev_id, int, 0);
module_param(isr_enable, bool, 0);
MODULE_AUTHOR("Xpliant INC Confidential.");
MODULE_DESCRIPTION("User mode PCIe Endpoint device interface.");
MODULE_LICENSE("GPL");
MODULE_VERSION(XPTOOLS_VERSION);
MODULE_ALIAS("pcie:pciedev");
MODULE_DEVICE_TABLE(pci, xp_pci_ids);
|
XPliant/OpenXPS
|
include/openXpsReasonCodeTable.h
|
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* All Rights Reserved.
*
* 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.
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATIONS ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*
* FILE : openXpsReasonCodeTable.h
*
* Abstract: This file defines the reason codes in OpenXPS.
************************************************************************/
/**
* \file openXpsReasonCodeTable.h
* \brief This file contains API prototypes and type definitions
* for the openXps Reason Code Table
* \copyright (c) 2016 Cavium Inc
*/
#ifndef _openXpsReasonCodeTable_h_
#define _openXpsReasonCodeTable_h_
#define XP_BRIDGE_MAC_SA_NEW 11 ///< FDB MAC learning: New MAC SA indication
#define XP_BRIDGE_MAC_SA_MOVE 12 ///< FDB MAC learning: MAC SA has been moved indication
#define XP_ROUTE_RC_NH_TABLE_HIT 60 ///< NextHope table hit indication
#define XP_IVIF_RC_BPDU 103 ///< BPDU
#define XP_BRIDGE_RC_IVIF_ARPIGMPICMP_CMD 206 ///< ARP Broadcast Ingress VIF control
#define XP_BRIDGE_RC_IVIF_SA_MISS 211 ///< MAC SA Miss Ingress VIF control
#define XP_ROUTE_RC_HOST_TABLE_HIT 302 ///< Host Table hit indication
#define XP_ROUTE_RC_ROUTE_NOT_POSSIBLE 312 ///< IP Routing failure
#define XP_ROUTE_RC_TTL1_OR_IP_OPTION 313 ///< IP Options or TTL=1
#endif
|
XPliant/OpenXPS
|
xpnet/include/xp_common.h
|
<filename>xpnet/include/xp_common.h
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* 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; version 2
* of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* A copy of the GNU General Public License, version 2 is available in the file
* named LICENSE-GPLv2.md either in this directory or its root.
* Alernatively to obtain a copy, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* File: xp_common.h
*
* Abstract: This file contains the macros and definitions required.
************************************************************************/
#ifndef _XP_COMMON_H
#define _XP_COMMON_H
#include <linux/types.h>
#include "xp_netdev.h"
#define BYTE_SIZE 1
#define WORD_SIZE 2
#define DWORD_SIZE 4
#define QWORD_SIZE 8
#define ERR(...) printk(KERN_ERR "! "__VA_ARGS__)
#define LOG(...) printk(KERN_INFO "! "__VA_ARGS__)
#define DBG(...) if (xp_debug != 0) printk(KERN_INFO "! "__VA_ARGS__)
#define fdebug(fmt,args...)\
({\
if (g_debug != 0) {\
printk(KERN_CRIT "%s:%d" fmt, __FILE__, __LINE__, ##args);\
}\
})
#define pdebug(fmt,args...)\
({\
if (g_debug != 0) {\
if (printk_ratelimit()) printk(KERN_CRIT fmt, ##args);\
}\
})
#define pdebug_nr(fmt,args...)\
({\
if (g_debug != 0) {\
printk(KERN_CRIT fmt, ##args);\
}\
})
extern int g_debug;
#endif /* _XP_COMMON_H */
|
XPliant/OpenXPS
|
xpnet/include/xp_netdev.h
|
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* 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; version 2
* of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* A copy of the GNU General Public License, version 2 is available in the file
* named LICENSE-GPLv2.md either in this directory or its root.
* Alernatively to obtain a copy, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* File: xp_netdev.h
*
* Abstract: This file contains the enums, macros, defs required for netdev
* support in this kernel module.
************************************************************************/
#ifndef _XP_NETDEV_H
#define _XP_NETDEV_H
#include <linux/pci.h>
#include <linux/version.h>
#include <linux/etherdevice.h>
#include <linux/proc_fs.h>
#include <net/inet_sock.h>
#include "xp_header.h"
#include "xp_pcie_slave.h"
#include "xp_reg_info.h"
#define XPNET_NUM_QUEUES (64)
#define XPNET_RX_NUM_QUEUES (64)
#define XPNET_RX_NUM_DESCS (10)
#define XPNET_TX_NUM_QUEUES (64)
#define XPNET_TX_NUM_DESCS (10)
#define XPNET_MAX_DMA_SEGMENT_SIZE (4 << 10)
#define XPNET_DESC_SIZE (sizeof(xpnet_descriptor_t))
#define XPNET_MAX_ATTEMPTS (50)
#define XPNET_PROC_FILE_NAME "xpnet"
#define XPNET_PROC_FILE_PATH "/proc/" XPNET_PROC_FILE_NAME
#define XPNET_PROC_STATS "stats"
#define XPNET_PROC_TRAP_TABLE "trap-table"
#define XPNET_PROC_DEBUG "debug"
#define XPNET_PROC_NETDEV "net-dev"
#define XPNET_PROC_TXHDR "tx-hdr"
#define XPNET_CEIL_LEN(len, align)\
({\
((len + align - 1) & ~(align - 1));\
})
#define xpnet_decr_and_wrap(idx, limit)\
({\
(((idx + limit) - 1) % (limit));\
})
#define xpnet_add_and_wrap(idx, incr, limit)\
({\
(((idx + limit) + (incr)) % (limit));\
})
#define xpnet_get_busy_desc(q)\
({\
((q->xpq_num_desc + q->tail - (q->head + 1)) % q->xpq_num_desc);\
})
#define xpnet_get_free_desc(q)\
({\
(q->xpq_num_desc - 1 - (xpnet_get_busy_desc(q)));\
})
#define NAME_STR_HELP "help" /*help string name macro*/
#define NAME_STR_REG "reg" /*Reg string name macro*/
#define NAME_STR_TRAP "trap" /*Trap string name macro*/
#define NAME_STR_STAT "stat" /*Stat string name macro*/
#define NAME_STR_DESC "desc" /*Desc string name macro*/
#define NAME_STR_NETDEV "net-dev" /*net-dev string name macro*/
#define NAME_STR_TXHDR "tx-hdr" /*tx-hdr string name macro*/
typedef enum xpnet_enum {
XPNET_OK = 0,
XPNET_QUEUE_TYPE_RX = 0x100,
XPNET_QUEUE_TYPE_TX,
/* Not enough room for 4byte aligned length */
XPNET_REASON_TAILROOM,
XPNET_REASON_4KCROSS,
XPNET_REASON_SHORTPACKET, /* < 84 bytes */
XPNET_QUEUE_STOPPED,
XPNET_QUEUE_ACTIVE,
XPNET_QUEUE_RESET_PENDING,
XPNET_QUEUE_BUSY,
XPNET_QUEUE_ERROR,
XPNET_TYPE_MAX
} xpnet_enum_t;
typedef struct xpnet_descriptor {
/* Memory overlay of the descriptor in DMA memory */
u64 qword[4];
} xpnet_descriptor_t;
typedef struct xpnet_shards_struct {
void *va; /* Virtual address of the buffer */
dma_addr_t dma; /* Mapped dma address of the buffer */
int len; /* Length of buffer filled, allocated len = PAGE_SIZE */
} xpnet_shards_struct_t;
typedef struct xpnet_desc_struct {
/* Metadata required for book-keeping of the descriptors in a queue */
int num_shards; /* set only for the first one, how many shards */
xpnet_descriptor_t *va;
dma_addr_t cdp; /* to update the cdp in h/w */
xpnet_shards_struct_t buf_sta;
} xpnet_desc_struct_t;
typedef struct xpnet_queue_struct {
/* Metadata required for book-keeping of the queue */
spinlock_t xpq_lock; /* Lock for this queue access */
u32 xpq_id; /* ID of the queue */
xpnet_enum_t xpq_type; /* Enum RX/TX */
u32 xpq_num_desc; /* Elements on xpq_desc */
int status; /* Stopped, active, etc */
int tail; /* Index where producer function operates on */
int head; /* Index where consumer function operates on */
void *va; /* VA of the start of descriptor chain */
dma_addr_t dma; /* DMA address of the start of descriptor chain */
/* Metadata of the descriptors */
xpnet_desc_struct_t xpq_desc_meta[XPNET_RX_NUM_DESCS];
} xpnet_queue_struct_t;
typedef struct xpnet_private {
u32 hw_flags; /* 32 bits h/w specific usage, e.g., revision */
struct pci_dev *pdev; /* OS specific structure */
xp_private_t *pci_priv; /* Only for pci char drv dep */
struct napi_struct napi; /* Currently unused */
/* Host RX and host TX complete */
struct workqueue_struct *wqueue;
struct delayed_work dwork;
/* RX descritpr ring for queues */
xpnet_queue_struct_t rx_queue[XPNET_RX_NUM_QUEUES];
xpnet_queue_struct_t tx_queue[XPNET_RX_NUM_QUEUES];
int num_rxqueues, num_txqueues; /* Number of queues enabled */
int txqno, rxqno; /* CPU RX and TX queue numbers. */
spinlock_t priv_lock; /* Lock for this private data structure */
int dma_trigger; /* Lock for this private data structure */
struct net_device_stats stats; /* Netdev structure for DMA statastic */
int instance; /* Instance number */
struct proc_dir_entry *proc_root; /* PDE for root xpnet node */
struct proc_dir_entry *proc_que[XPNET_RX_NUM_QUEUES]; /* PDE for all 64 queues */
struct proc_dir_entry *proc_stats; /* PDE for stats */
struct proc_dir_entry *proc_ttable; /* PDE for trap table */
struct proc_dir_entry *proc_debug; /* PDE for debug mode */
struct proc_dir_entry *proc_netdev; /* PDE for net dev */
struct proc_dir_entry *proc_txhdr; /* PDE for tx header*/
} xpnet_private_t;
typedef struct xpnet_que_info {
xpnet_private_t *priv;
int que_no;
}xpnet_que_info_t;
extern xpnet_private_t *g_net_priv;
int32_t xp_dev_reg_write_q(xpnet_private_t *net_priv, u32 reg_id,
u8 data_size, u32 *value, u32 qnum);
int32_t xp_dev_reg_read_q(xpnet_private_t *net_priv, u32 reg_id,
u8 data_size, u32 *value, u32 qnum);
#endif /* _XP_NETDEV_H */
|
XPliant/OpenXPS
|
include/openXpsEnums.h
|
<gh_stars>10-100
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* All Rights Reserved.
*
* 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.
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATIONS ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*
* FILE : openXpsEnums.h
*
* Abstract: This file defines the XP enumerations in OpenXPS.
************************************************************************/
/**
* \file openXpsEnums.h
* \brief This file contains openXps enum definitions
* \copyright (c) 2016 Cavium Inc
*/
#ifndef _openXpsEnums_h_
#define _openXpsEnums_h_
/**
* \brief This type (enum) defines the hashable fields
*/
typedef enum xpHashField
{
XP_ETHERNET_MAC_DA, ///< Ethernet MAC DA
XP_ETHERNET_MAC_SA, ///< Ethernet MAC SA
XP_ETHERNET_E_TAG_TPID, ///< Ethernet 802.1Q Tag Protocol Identifier (TPID)
XP_ETHERNET_E_TAG_E_PCP, ///< Ethernet 802.1Q Tag Priority Code Point (PCP)
XP_ETHERNET_E_TAG_E_DEI, ///< Ethernet 802.1Q Tag Drop Eligible Indicator (DEI)
XP_ETHERNET_E_TAG_INGRESS_E_CID_BASE,
XP_ETHERNET_E_TAG_RESERVED, ///< Reserved
XP_ETHERNET_E_TAG_GRP,
XP_ETHERNET_E_TAG_E_CID_BASE,
XP_ETHERNET_E_TAG_INGRESS_E_CID_EXT,
XP_ETHERNET_E_TAG_E_CID_EXT,
XP_ETHERNET_O_TAG_TPID,
XP_ETHERNET_O_TAG_PCP,
XP_ETHERNET_O_TAG_DEI,
XP_ETHERNET_O_TAG_VID,
XP_ETHERNET_S_TAG_TPID,
XP_ETHERNET_S_TAG_PCP,
XP_ETHERNET_S_TAG_DEI,
XP_ETHERNET_S_TAG_VID,
XP_ETHERNET_C_TAG_TPID,
XP_ETHERNET_C_TAG_PCP,
XP_ETHERNET_C_TAG_DEI,
XP_ETHERNET_C_TAG_VID,
XP_ETHERNET_ETHERTYPE,
XP_TU_ETHER_MAC_DA,
XP_TU_ETHER_MAC_SA,
XP_TU_ETHER_S_TAG_TPID,
XP_TU_ETHER_S_TAG_PCP,
XP_TU_ETHER_S_TAG_DEI,
XP_TU_ETHER_S_TAG_VID,
XP_TU_ETHER_C_TAG_TPID,
XP_TU_ETHER_C_TAG_PCP,
XP_TU_ETHER_C_TAG_DEI,
XP_TU_ETHER_C_TAG_VID,
XP_TU_ETHER_ETHERTYPE,
XP_RESERVED1,
XP_RESERVED2,
XP_RESERVED3,
XP_RESERVED4,
XP_RESERVED5,
XP_RESERVED6,
XP_RESERVED7,
XP_PBB_MAC_DA,
XP_PBB_MAC_SA,
XP_PBB_E_TAG_TPID,
XP_PBB_E_TAG_E_PCP,
XP_PBB_E_TAG_E_DEI,
XP_PBB_E_TAG_INGRESS_E_CID_BASE,
XP_PBB_E_TAG_RESERVED,
XP_PBB_E_TAG_GRP,
XP_PBB_E_TAG_E_CID_BASE,
XP_PBB_E_TAG_INGRESS_E_CID_EXT,
XP_PBB_E_TAG_E_CID_EXT,
XP_PBB_O_TAG_TPID,
XP_PBB_O_TAG_PCP,
XP_PBB_O_TAG_DEI,
XP_PBB_O_TAG_VID,
XP_PBB_B_TAG_TPID,
XP_PBB_B_TAG_PCP,
XP_PBB_B_TAG_DEI,
XP_PBB_B_TAG_VID,
XP_PBB_I_SID_TPID,
XP_PBB_I_SID_I_PCP,
XP_PBB_I_SID_I_DEI,
XP_PBB_I_SID_UCA,
XP_PBB_I_SID_RESERVED,
XP_PBB_I_SID,
XP_ARP_HTYPE,
XP_ARP_PTYPE,
XP_ARP_HLEN,
XP_ARP_PLEN,
XP_ARP_OPER,
XP_ARP_SHA,
XP_ARP_SPA,
XP_ARP_SHA_2,
XP_ARP_SPA_2,
XP_IPV4_VERSION,
XP_IPV4_IHL,
XP_IPV4_DSCP,
XP_IPV4_ECN,
XP_IPV4_TOTAL_LENGTH,
XP_IPV4_IDENTIFICATION,
XP_IPV4_RESERVED_1,
XP_IPV4_DF,
XP_IPV4_MF,
XP_IPV4_FRAGMENT_OFFSET,
XP_IPV4_TIME_TO_LIVE,
XP_IPV4_PROTOCOL,
XP_IPV4_HEADER_CHECKSUM,
XP_IPV4_SOURCE_IP_ADDRESS,
XP_IPV4_DESTINATION_IP_ADDRESS,
XP_IPV4_OPTIONS,
XP_IPV6_VERSION,
XP_IPV6_ECN,
XP_IPV6_FLOW_LABEL,
XP_IPV6_PAYLOAD_LENGTH,
XP_IPV6_NEXT_HEADER,
XP_IPV6_TIME_TO_LIVE,
XP_IPV6_SOURCE_IP_ADDRESS,
XP_IPV6_SPLIT_DESTINATION_IP_ADDRESS,
XP_MPLS_LABEL0,
XP_MPLS_EXP0,
XP_MPLS_BS0,
XP_MPLS_TTL0,
XP_MPLS_LABEL1,
XP_MPLS_EXP1,
XP_MPLS_BS1,
XP_MPLS_TTL1,
XP_MPLS_LABEL2,
XP_MPLS_EXP2,
XP_MPLS_BS2,
XP_MPLS_TTL2,
XP_MPLS_LABEL3,
XP_MPLS_EXP3,
XP_MPLS_BS3,
XP_MPLS_TTL3,
XP_MPLS_CONTROL_WORD,
XP_GRE_C,
XP_GRE_R,
XP_GRE_K,
XP_GRE_S,
XP_GRE_VERSION,
XP_GRE_PROTOCOL,
XP_GRE_CHECKSUM,
XP_GRE_RESERVED_2,
XP_GRE_KEY,
XP_GRE_SEQ_NUM,
XP_ICMP_TYPE,
XP_ICMP_CODE,
XP_ICMP_CHECKSUM,
XP_ICMP_MESSAGE_SPECIFIC_INFO,
XP_IGMP_VERSIONORTYPE,
XP_IGMP_MAX_RESPONSE_TIME,
XP_IGMP_CHECKSUM,
XP_IGMP_GROUP_ADDRESS,
XP_ICMPV6_TYPE,
XP_ICMPV6_CODE,
XP_ICMPV6_CHECKSUM,
XP_ICMPV6_MESSAGE_BODY,
XP_UDP_SOURCE_PORT,
XP_UDP_DESTINATION_PORT,
XP_UDP_LENGTH,
XP_UDP_CHECKSUM,
XP_TCP_SOURCE_PORT,
XP_TCP_DESTINATION_PORT,
XP_TCP_SEQUENCE_NUMBER,
XP_TCP_ACK_NUMBER,
XP_TCP_OFFSET,
XP_TCP_RESERVED,
XP_TCP_FLAGS,
XP_TCP_WINDOW,
XP_TCP_CHECKSUM,
XP_TCP_URGENT_POINTER,
XP_TCP_TCP_OPTIONS,
XP_FCOE_VERSION,
XP_FCOE_RESERVED,
XP_FCOE_SOF,
XP_FCOE_R_CTL,
XP_FCOE_D_ID,
XP_FCOE_CS_CTL_PRIORITY,
XP_FCOE_S_ID,
XP_FCOE_TYPE,
XP_FCOE_F_CTL,
XP_FCOE_SEQ_ID,
XP_FCOE_DF_CTL,
XP_FCOE_SEQ_CNT,
XP_FCOE_SPLIT_OX_ID,
XP_FCOE_SPLIT_RX_ID,
XP_FCOE_SPLIT_PARAMETER,
XP_CNM_CNM_VER,
XP_CNM_QFEEDBACK,
XP_CNM_CPID,
XP_CNM_CNMQOFFSET,
XP_CNM_CNMQDELTA,
XP_CNM_ENCAP_PRIORITY,
XP_CNM_ENCAP_DA,
XP_CNM_ENCAP_LEN,
XP_GENEVE_VERSION,
XP_GENEVE_OPTIONSLEN,
XP_GENEVE_OAMFRAME,
XP_GENEVE_CRITICALFLAG,
XP_GENEVE_RESERVED_1,
XP_GENEVE_PROTOCOL,
XP_GENEVE_VNI,
XP_GENEVE_RESERVED_2,
XP_GENEVE_OPTIONCLASS,
XP_GENEVE_TYPE,
XP_GENEVE_RESERVED_3,
XP_GENEVE_OPTLEN,
XP_GENEVE_RESERVED_4,
XP_GENEVE_FLOWID,
XP_GENEVE_OPTIONCLASS_2,
XP_GENEVE_TYPE_2,
XP_GENEVE_RESERVED_5,
XP_GENEVE_OPTLEN_2,
XP_GENEVE_RESERVED_6,
XP_GENEVE_TEMPLATEID,
XP_GRE_NOLAYER_C,
XP_GRE_NOLAYER_R,
XP_GRE_NOLAYER_K,
XP_GRE_NOLAYER_S,
XP_GRE_NOLAYER_VERSION,
XP_GRE_NOLAYER_PROTOCOL,
XP_GRE_NOLAYER_CHECKSUM,
XP_GRE_NOLAYER_RESERVED_2,
XP_GRE_NOLAYER_KEY,
XP_GRE_NOLAYER_SEQ_NUM,
XP_UDPVXLANNSH_SOURCE_PORT,
XP_UDPVXLANNSH_DESTINATION_PORT,
XP_UDPVXLANNSH_LENGTH,
XP_UDPVXLANNSH_CHECKSUM,
XP_UDPVXLANNSH_FLAGS,
XP_UDPVXLANNSH_RESERVED_1,
XP_UDPVXLANNSH_NEXTPROTOCOL,
XP_UDPVXLANNSH_VNI,
XP_UDPVXLANNSH_RESEVED_2,
XP_UDPVXLANNSH_FLAGS_1,
XP_UDPVXLANNSH_NSH_LENGTH,
XP_UDPVXLANNSH_MD_TYPE,
XP_UDPVXLANNSH_NSHNEXTPROTOCOL,
XP_UDPVXLANNSH_SERVICEPATHID,
XP_UDPVXLANNSH_SERVICEINDEX,
XP_UDPVXLANNSH_SOURCEISLANDID,
XP_UDPVXLANNSH_DESTISLANDID,
XP_UDPVXLANNSH_RESERVED_3,
XP_NSH_FLAGS_1,
XP_NSH_NSH_LENGTH,
XP_NSH_MD_TYPE,
XP_NSH_NSHNEXTPROTOCOL,
XP_NSH_SERVICEPATHID,
XP_NSH_SERVICEINDEX,
XP_NSH_SOURCEISLANDID,
XP_NSH_DESTISLANDID,
XP_NSH_RESERVED_3,
XP_NUM_HASH_FIELDS
}xpHashField;
/**
* \brief This type (enum) lists the packet forwarding processing commands
*/
typedef enum xpPktCmd_e
{
XP_PKTCMD_DROP = 0, ///< DROP the packet
XP_PKTCMD_FWD, ///< FORWARD the packet
XP_PKTCMD_TRAP, ///< TRAP the packet
XP_PKTCMD_FWD_MIRROR, ///< FORWARD and Mirror the packet
XP_PKTCMD_MAX
} xpPktCmd_e;
/**
* \brief This type (enum) defines the accepted frame types at ingress port
*/
typedef enum
{
FRAMETYPE_ALL = 0,
FRAMETYPE_UN_PRI,
FRAMETYPE_TAG,
FRAMETYPE_MAX
}xpsPortFrameType_e;
/**
* \brief This type (enum) defines the port configuration parameters
*/
typedef enum xpsPortConfigFieldList_t
{
XPS_PORT_FIELD_NUM_MIN,
XPS_PORT_DEFAULT_EXP,
XPS_PORT_DEFAULT_DSCP,
XPS_PORT_DEFAULT_DEI,
XPS_PORT_DEFAULT_PCP,
XPS_PORT_DEFAULT_DP,
XPS_PORT_DEFAULT_TC,
XPS_PORT_MPLS_QOS_EN,
XPS_POST_IP_QOS_EN,
XPS_PORT_LAYER2_QOS_EN,
XPS_PORT_EGRESS_FILTER_ID,
XPS_PORT_SET_INGRESS_VIF,
XPS_PORT_SET_BRIDGE_DOMAIN,
XPS_PORT_ACCEPTED_FRAME_TYPE,
XPS_PORT_BYPASS_TUNNEL_VIF,
XPS_PORT_BYPASS_ACLSPBR,
XPS_PORT_SAMPLER_EN,
XPS_PORT_POLICER_EN,
XPS_PORT_STATE,
XPS_PORT_SET_EGRESS_PORT_FILTER,
XPS_PORT_MAC_SAMISSCMD,
XPS_PORT_BUM_POLICER_EN,
XPS_PORT_ACL_EN,
XPS_PORT_DEBUG_EN,
XPS_PORT_ACL_ID,
XPS_PORT_PRIVATE_WIRE_EN,
XPS_PORT_ADD_PORT_BASED_TAG,
XPS_PORT_RESERVED2,
XPS_PORT_BRIDGE_DOMAIN,
XPS_PORT_EVIF,
XPS_PORT_MIRROR_BITMASK,
XPS_PORT_INGRESS_VIF,
XPS_PORT_PVID_MODE_ALLPKT,
XPS_PORT_PVID,
XPS_PORT_MPLS_QOS_PROFILE_IDX,
XPS_PORT_IP_QOS_PROFILE_IDX,
XPS_PORT_L2QOS_PROFILE_IDX,
XPS_PORT_ETAG_EXISTS,
XPS_PORT_FIELD_NUM_MAX
} xpsPortConfigFieldList_t;
/**
* \typedef xpCountMode_e
* \brief This type (enum) defines the counting modes
* The configuration is a bitmask, which can enable
* counting (bit 0), policing (bit 1) and sampling (bit2).
*
*/
typedef enum xpCountMode_e
{
COUNT_MODE_NONE = 0x0, ///< None of Counting, Policing and Sampling
COUNT_MODE_CNT, ///< Counting only
COUNT_MODE_POL, ///< Policing only
COUNT_MODE_CNT_POL, ///< Counting and Policing
COUNT_MODE_SMP, ///< Sampling only
COUNT_MODE_CNT_SMP, ///< Counting and Sampling
COUNT_MODE_POL_SMP, ///< Policing and Sampling
COUNT_MODE_CNT_POL_SMP, ///< Counting, Policing and Sampling
COUNT_MODE_MAX
} xpCountMode_e;
/**
* \brief This type (enum) defines an the egress encapsulation
* types for an L2 Domain.
*/
typedef enum xpL2EncapType_e
{
XP_L2_ENCAP_DOT1Q_UNTAGGED, ///< Ethernet 802.1Q UnTagged
XP_L2_ENCAP_DOT1Q_TAGGED, ///< Ethernet 802.1Q Tagged
XP_L2_ENCAP_DOT1Q_PRIOTAGGED, ///< Ethernet Priority Tagged
XP_L2_ENCAP_QINQ_UNTAGGED, ///< Strip both Ctag and Stag
XP_L2_ENCAP_QINQ_CTAGGED, ///< Strip only Stag
XP_L2_ENCAP_QINQ_STAGGED, ///< Add Stag
XP_L2_ENCAP_VXLAN, ///< VXLAN Tunnel
XP_L2_ENCAP_NVGRE, ///< NVGRE Tunnel
XP_L2_ENCAP_PBB, ///< Provider Backbone Bridges (also known as "Mac-In-Mac") Tunnel
XP_L2_ENCAP_GENEVE, ///< GENEVE Tunnel
XP_L2_ENCAP_MPLS, ///< MPLS
XP_L2_ENCAP_INVALID = -1
} xpL2EncapType_e;
/**
* \brief This type (enum) defines the Multicast
* Bridging modes configurable for a VLAN.
*/
typedef enum xpVlanBridgeMcMode_e
{
MC_BRIDGE_MODE_DISABLED = 0, ///< Disabled
MC_BRIDGE_MODE_FDB, ///< FDB Mode
MC_BRIDGE_MODE_S_G, ///< {S, G} IP MC Bridging Mode
MC_BRIDGE_MODE_0_G, ///< {0, G} IP MC Bridging Mode
MC_BRIDGE_MODE_MAX
} xpVlanBridgeMcMode_e;
/**
* \brief This type (enum) defines the Spanning Tree States
* for a port.
*/
typedef enum xpVlanStgState_e
{
SPAN_STATE_DISABLE = 0, ///< Disable Spanning Tree State
SPAN_STATE_LEARN, ///< Learning Spanning Tree State
SPAN_STATE_FORWARD, ///< Forwarding Spanning Tree State
SPAN_STATE_BLOCK, ///< Blocking Spanning Tree State
SPAN_STATE_MAX
} xpVlanStgState_e;
/**
* \brief This type (enum) defines Count Mode.
*/
typedef enum xpBdCountMode_e
{
BD_COUNT_MODE_NONE, ///< Counting is disabled
BD_COUNT_MODE_ROUTED_AND_SWITCHED, ///< Count both switched and routed traffic
BD_COUNT_MODE_ONLY_ROUTED, ///< Count only routed traffic
BD_COUNT_MODE_MAX
} xpBdCountMode_e;
/**
* \brief This type (enum) defines IP type
* used as IP Route Table Prefix lookup.
*
**/
typedef enum xpIpPrefixType_t
{
XP_PREFIX_TYPE_IPV4, ///< IPv4
XP_PREFIX_TYPE_IPV6, ///< IPv6
XP_PREFIX_TYPE_MAX
} xpIpPrefixType_t;
/**
*\brief This type (enum) defines the device initialization modes
* INIT_COLD:
Performs addDevice and all respective managers
will perform "software init", "hardware init" and
load default values. This is used when the system
is initialized the first time.
INIT_WARM: (shadow is not present in the system)
Performs addDevice and all respective managers
will perform "software init" only. Most cases the
managers should recreate config and state from hardware
but typical case there is no shadow maintained, hence
table/reg data is not modified on the live system.
INIT_WARM_SYNC_TO_HW:
(shadow is available and is persistent across warm restart)
Performs addDevice, and software initialization
for all blocks. "software init" only. For
managers should load data from shadow to hardware
and push the configration to hardware.
INIT_WARM_SYNC_TO_SHADOW:
(shadow is available and is synced by reading hardware)
Performs addDevice, and software initialization
for all blocks. "software init" only. For
managers should load data from hardware to shadow. For
other configurations and data is recreated/read from hw.
*/
typedef enum xpInitType_t
{
INIT_UNKNOWN = 0,
INIT_COLD, ///< Software and Hardware Initialization with Default Values
INIT_WARM, ///< Software Initialization only, no Shadow present
INIT_WARM_SYNC_TO_HW, ///< Software Initialization only, Then load data from Shadow to Hardware
INIT_WARM_SYNC_TO_SHADOW, ///< Software Initialization only, Then load data from Hardware to Shadow
INIT_MAX
} xpInitType_t;
/**
* \brief This type (enum) defines the MAC configuration modes
*/
typedef enum xpMacConfigMode
{
MAC_MODE_4X10GB = 3, ///< 4x10Gbps
MAC_MODE_1X10GB = 9, ///< 1x10Gbps
MAC_MODE_1X40GB = 5, ///< 1x40Gbps
MAC_MODE_1X50GB = 14, ///< 50Gbps
MAC_MODE_1X100GB = 6, ///< 1x100Gbps
MAC_MODE_MAX_VAL = 15, ///< TOTAL NUMBER OF MAC_MODES
}xpMacConfigMode;
/**
* \brief This type (enum) defines the Packet Driver
* Rx modes
*/
typedef enum xpRxConfigMode
{
INTR = 0,
POLL
}xpRxConfigMode;
/**
* \brief This type (enum) defines SAL object types
*/
typedef enum xpSalType_e
{
XP_SAL_HW_TYPE, ///< Hardware
XP_SAL_WM_TYPE, ///< Simulation
XP_SAL_MAX_OS_TYPE,
XP_SAL_OTHER_OS_TYPE,
}xpSalType_t;
/**
* \brief This type (enum) defines the Packet Driver
* callback handler types
*/
typedef enum xpCallbackMethodType
{
PD_SEND = 0,
PD_RECV,
PD_ERR,
PD_ALL
} xpCallbackMethodType;
/**
* \brief This type (enum) defines the Packet Driver
* Tx modes
*/
typedef enum txMode
{
SYNC_TX,
ASYNC_TX
} txMode;
/**
* \brief This type (enum) defines the table aging modes
*/
typedef enum XP_AGE_MODE_T
{
XP_AGE_MODE_AUTO,
XP_AGE_MODE_TRIGGER,
XP_AGE_MODE_INVALID
}XP_AGE_MODE_T;
/**
* \brief This type (enum) defines the Packet Driver
* Rx handler types
*/
typedef enum xpCpuRxPktCbType
{
XP_L2_LEARN = 0,
XP_OPENFLOW = 3,
XP_MAX_CPU_RX_HDLR = 6
} xpCpuRxPktCbType_e;
/**
* \brief This type (enum) defines the Forward-Error-Correction (FEC) types
*/
typedef enum xpFecMode
{
RS_FEC_MODE, ///< Reed-Solomon FEC
FC_FEC_MODE, ///< Fire Code FEC
MAX_FEC_MODE
}xpFecMode;
/**
* \brief This type (enum) defines the serdes tuning types
*/
typedef enum xpSerdesDfeTuneMode_t
{
DFE_ICAL, ///< Initial calibration, coarse tuning. (Default)
DFE_PCAL, ///< Periodic calibration, fine tuning, no LF,HF adjustments
DFE_START_ADAPTIVE, ///< Launch continous pCAL
DFE_STOP_ADAPTIVE, ///< Stop continous pCAL
DFE_ENABLE_RR, ///< Enable SerDes to participate in Round-Robin pCal
DFE_DISABLE_RR ///< Disable SerDes from participation in Round-Robin pCal
} xpSerdesDfeTuneMode_t;
/**
* \brief This type (enum) defines the port speeds
*/
typedef enum xpSpeed
{
SPEED_10MB = 0, ///< 10Mbps
SPEED_100MB, ///< 100Mbps
SPEED_1GB, ///< 1Gbps
SPEED_1GB_PCS, ///< 1Gbps
SPEED_10GB, ///< 10Gbps
SPEED_40GB, ///< 40Gbps
SPEED_100GB, ///< 100Gbps
SPEED_25GB, ///< 25Gbps
SPEED_50GB, ///< 50Gbps
SPEED_MAX_VAL
}xpSpeed;
/**
* \brief This type (enum) defines the event source identifiers
*/
typedef enum xpEventType
{
/* Common interrupts in A0 and B0 */
LINK_UP = 0, ///< MAC Link Up Event
LINK_DOWN, ///< MAC Link Down Event
FAULT_DETECTED, ///< MAC Link Up Event
FAULT_NOT_DETECTED,
SERDES_SIG_DETECTED, ///< MAC Serdes Signal Detection Event
SERDES_SIG_NOT_DETECTED, ///< MAC Serdes Signal No Detection Event
TX_UNDER_RUN, ///< MAC Tx Packet Underrun Event: While transmitting a packet, MAC does not have data to read from the Transmit DMA Fifo
TX_JABBER, ///< MAC Tx Packet Jabber Event
TX_TIMESTAMPS_FIFO_OVER_FLOW, ///< MAC Tx Timestamp Overlow error Event: Last Timestamp value is dropped
TX_TIMESTAMPS_FIFO_AVAILABLE, ///< MAC Tx Timestamp Fifo available Event: An indication that the Transmit Timestamp FIFO has data and is not empty
/* RS/FC FEC interrupts */
FEC_ALIGNMENT_MAKER_LOST_LANE0, ///< FEC Alignment Marker error on lane 0 Event
FEC_ALIGNMENT_MAKER_LOST_LANE1, ///< FEC Alignment Marker error on lane 1 Event
FEC_ALIGNMENT_MAKER_LOST_LANE2, ///< FEC Alignment Marker error on lane 2 Event
FEC_ALIGNMENT_MAKER_LOST_LANE3, ///< FEC Alignment Marker error on lane 3 Event
FEC_UNCORRECTABLE_FRM, ///< FEC Uncorrectable Frame error Event
FEC_DESKEW_LOST, ///< FEC Deskew error Event
FEC_BER_OVER_THRESHOLD, ///< FEC High BER Event
/* pcs interrupts event */
/* High speed multi-channel pcs */
HSMCPCS_BLOCK_LOCK,
HSMCPCS_FAULT,
HSMCPCS_TX_GEARBOX_FIFO_ERROR,
HSMCPCS_DEBUG_DESKEW_OVERFLOW,
UMAC_COMMON_INT_END,
/* A0 interrupts */
UMAC_A0_INT_START,
TX_BASE_PAGE_STARTED,
TX_NEXT_PAGE_STARTED,
RX_BASE_PAGE_STARTED,
RX_NEXT_PAGE_STARTED,
BPAN_COMPLETED,
UMAC_A0_INT_END,
/* B0 interrupts */
UMAC_B0_INT_START,
HSMCPCS_DECODER_TRAP,
HSMCPCS_LOSS_OF_SYNC,
HSMCPCS_LOSS_OF_BLOCK_LOCK,
HSMCPCS_HIGH_BER_EVENT,
HSMCPCS_ERROR_BLOCK,
LSMCPCS_AN_DONE,
FC_FEC_BLOCK_LOCK_GAINED,
FC_FEC_BLOCK_LOCK_LOST,
FC_FEC_UNCORRECTED_CODEWORD,
FC_FEC_BAD_CODEWORD,
FC_FEC_TOO_MANY_REQUESTED,
BPAN_INT,
TX_IDLE, ///< TX idle event
RX_FIFO_ERR, ///< Rx FIFO error interrupt
TX_FIFO_OVERFLOW_ERR, ///< Rx FIFO overflow interrupt
TX_DCNT_VIOLATION_ERR, ///< Tx DCNT violation error
TX_FIFO_SOF_EOF_VIOLATION_ERR, ///< Tx FIFO SOF/EOF protocol violation error
RX_LOCAL_FAULT,
RX_REMOTE_FAULT,
RX_CRC_ERROR,
UMAC_B0_INT_END
}xpEventType;
/**
* \brief This type (enum) defines the Advanced Counting Module (ACM) modes
*/
typedef enum XP_ACM_CONFIG_MODE
{
XP_ACM_NONE, ///< None
XP_ACM_COUNTING, ///< Counting
XP_ACM_SAMPLING, ///< Sampling
XP_ACM_POLICING, ///< Policing
XP_ACM_MAX_NUM
}XP_ACM_CONFIG_MODE;
/**
* \brief This type (enum) defines the Advanced Counting Module (ACM) clients
*/
typedef enum xpAcmClient_e
{
XP_ACM_UNKNOWN,
/* Openflow ACM clients */
XP_ACM_OPENFLOW_0,
XP_ACM_OPENFLOW_1,
XP_ACM_OPENFLOW_2,
XP_ACM_OPENFLOW_3,
XP_ACM_OPENFLOW_4,
XP_ACM_OPENFLOW_5,
XP_ACM_OPENFLOW_6,
XP_ACM_OPENFLOW_7,
XP_ACM_OPENFLOW_8,
XP_ACM_OPENFLOW_9,
XP_ACM_OPENFLOW_10,
XP_ACM_OPENFLOW_11,
XP_ACM_OPENFLOW_12,
XP_ACM_OPENFLOW_13,
XP_ACM_OPENFLOW_14,
XP_ACM_OPENFLOW_15,
XP_ACM_OPENFLOW_16,
XP_ACM_OPENFLOW_17,
XP_ACM_OPENFLOW_18,
XP_ACM_OPENFLOW_19,
XP_ACM_OPENFLOW_20,
XP_ACM_OPENFLOW_21,
XP_ACM_OPENFLOW_22,
XP_ACM_OPENFLOW_23,
XP_ACM_OPENFLOW_MAX = 31,
/* Default profile ACM clients */
XP_ACM_ING_PORT_POLICER = 0x20,
XP_ACM_ING_PORT_SAMPLER = 0x40,
XP_ACM_VNI_COUNTER = 0x80,
XP_ACM_ING_BD_COUNTER = 0x100,
XP_ACM_VLAN_BUM_POLICER = 0x200,
XP_ACM_IACL_POLICER = 0x400,
XP_ACM_IPACL_COUNTER = 0x800,
XP_ACM_IBACL_COUNTER = 0x1000,
XP_ACM_IRACL_COUNTER = 0x2000,
XP_ACM_EACL_POLICER = 0x4000,
XP_ACM_EACL_COUNTER = 0x8000,
XP_ACM_EGR_BD_COUNTER = 0x10000,
XP_ACM_DROP_RSN_COUNTER = 0x20000,
XP_ACM_PORT_RANGE = 0x40000,
XP_ACM_PORT_VLAN = 0x80000,
XP_ACM_TUNNEL_COUNTER = 0x100000,
XP_ACM_COPP_POLICER = 0x200000,
}xpAcmClient_e;
/**
* \brief This type (enum) defines the interface upon which Packet Driver operation is performed
*/
typedef enum xpPacketInterface
{
XP_DMA = 0, ///< Perform DMA in user space
XP_NETDEV_DMA = 2 ///< Perform DMA in kernel space
} xpPacketInterface;
/**
* \brief This type (enum) defines the Policing results types
*/
typedef enum xpPolicingResultType
{
XP_POL_RESULT_EXP,
XP_POL_RESULT_DSCP,
XP_POL_RESULT_DEI,
XP_POL_RESULT_PCP,
XP_POL_RESULT_TC,
XP_POL_RESULT_DP
} xpPolicingResultType;
typedef enum XP_PROFILE_TYPE_E
{
XP_RESERVED_PROFILE = 0,
XP_DEFAULT_TWO_PIPE_PROFILE = 1,
XP_ROUTE_CENTRIC_SINGLE_PIPE_PROFILE = 2,
XP_OPENFLOW_HYBRID_SINGLE_PIPE_PROFILE = 3,
XP_MAX_PROFILE = 8
}XP_PROFILE_TYPE;
/**
* \typedef xpSkuMode_e
* \brief This type (enum) defines the typical SKUs modes the device may be configured to
*
*/
typedef enum xpSkuMode_e
{
SKU_128X10 = 0,
SKU_32X40 = 1,
SKU_64X40 = 2,
SKU_32X100 = 3,
SKU_128X25 = 4,
SKU_64X50 = 5,
SKU_MODE_MAX = 18
} xpSkuMode_e;
/**
* \typedef xpNlMsgType
* \brief This type (enum) defines the New Address Message types
* User defined data willbe in Type(int), Length(int), Value(Length bytes) format.
*
*/
typedef enum xpNlMsgType
{
XPNL_CREATE_NETDEV_INTF_MSG = 0x0001,
XPNL_DELETE_NETDEV_INTF_MSG,
XPNL_TXHEADER_MSG,
XPNL_TRAP_CONFIG_MSG,
XPNL_CB_FD_REG_MSG,
XPNL_INTF_ID = 0x7FFF,
XPNL_INTF_NAME,
XPNL_TXHEADER,
XPNL_TRAP_ID,
XPNL_REASONCODE,
XPNL_CHANNEL,
XPNL_FD,
}xpNlMsgType_e;
/**
* \brief OpenFlow Ports
*/
typedef enum xpOfPortNo_e
{
XP_OFPP_MAX = 0xffffff00u, ///< Maximum number of physical and logical switch ports.
/* Reserved OpenFlow Port (fake output "ports"). */
XP_OFPP_IN_PORT = 0xfffffff8u, ///< Send the packet out the input port.
///< This reserved port must be explicitly
///< used in order to send back out of
///< the input port.
XP_OFPP_TABLE = 0xfffffff9u, ///< Submit the packet to the first
///< flow table. This destination port can
///< only be used in packet-out messages.
XP_OFPP_NORMAL = 0xfffffffau, ///< Process with normal L2/L3 switching.
XP_OFPP_FLOOD = 0xfffffffbu, ///< All physical ports in VLAN, except
///< input port and those blocked or
///< link down.
XP_OFPP_ALL = 0xfffffffcu, ///< All physical ports except input port.
XP_OFPP_CONTROLLER = 0xfffffffdu, ///< Send to controller.
XP_OFPP_LOCAL = 0xfffffffeu, ///< Local openflow "port".
XP_OFPP_ANY = 0xffffffffu, ///< Not associated with any openflow "port".
} xpOfPortNo_e;
/**
* \brief OpenFlow Action Type
*/
typedef enum xpOfActionType_e
{
XP_OFPAT_OUTPUT = 0, ///< Output to switch port
XP_OFPAT_POP_VLAN = 6, ///< Pop the outer VLAN tag
XP_OFPAT_GROUP = 10, ///< Apply group
XP_OFPAT_SET_NW_TTL = 11, ///< Set IP TTL
XP_OFPAT_DEC_NW_TTL = 12, ///< Decrement IP TTL
XP_OFPAT_SET_FIELD = 13, ///< Set a header field using OXM TLV format
} xpOfActionType_e;
/**
* \brief OpenFlow Match Field Type
*/
typedef enum xpOxmType_e
{
XP_OFPXMT_OFB_IN_PORT = 0, ///< Switch input port
XP_OFPXMT_OFB_IN_PHY_PORT = 1, ///< Switch physical input port
XP_OFPXMT_OFB_METADATA = 2, ///< Metadata passed between tables
XP_OFPXMT_OFB_ETH_DST = 3, ///< Ethernet destination address
XP_OFPXMT_OFB_ETH_SRC = 4, ///< Ethernet source address
XP_OFPXMT_OFB_ETH_TYPE = 5, ///< Ethernet frame type
XP_OFPXMT_OFB_VLAN_VID = 6, ///< VLAN id
XP_OFPXMT_OFB_VLAN_PCP = 7, ///< VLAN priority
XP_OFPXMT_OFB_IP_PROTO = 10, ///< IP protocol
XP_OFPXMT_OFB_IPV4_SRC = 11, ///< IPv4 source address
XP_OFPXMT_OFB_IPV4_DST = 12, ///< IPv4 destination address
XP_OFPXMT_OFB_TCP_SRC = 13, ///< TCP source port
XP_OFPXMT_OFB_TCP_DST = 14, ///< TCP destination port
XP_OFPXMT_OFB_UDP_SRC = 15, ///< UDP source port
XP_OFPXMT_OFB_UDP_DST = 16, ///< UDP destination port
XP_OFPXMT_OFB_SCTP_SRC = 17, ///< SCTP source port
XP_OFPXMT_OFB_SCTP_DST = 18, ///< SCTP destination port
XP_OFPXMT_OFB_MAX
} xpOxmType_e;
/**
* \brief OpenFlow Match Packet Type
*/
typedef enum xpOfMatchPktType_e
{
XP_MATCH_PKT_ANY = 0, ///< Match packets with and without a VLAN tag.
///< The VLAN VID and PCP fields value
///< must be ignored.
XP_MATCH_PKT_UNTAGGED = 1, ///< Match only packets without a VLAN tag.
///<
XP_MATCH_PKT_TAGGED = 2, ///< Match only packets with a VLAN tag.
///< In case VLAN VID and PCP fields values
///< are not defined (wildcarded) match packets
///< with a VLAN tag regardless of its value.
XP_MATCH_PKT_MASK = 3, ///< Match packet mask
///<
} xpOfMatchPktType_e;
/**
* \brief OpenFlow Group Type
*/
typedef enum xpOfGroupType_e
{
XP_OFPGT_ALL = 0, ///< Executes all buckets in the group.
XP_OFPGT_SELECT = 1, ///< Executes one bucket in the group based on
///< a switch-computed selection algorithm.
XP_OFPGT_INDIRECT = 2, ///< Executes a single bucket defined in
///< this group.
XP_OFPGT_FF = 3, ///< Executes the first live bucket.
} xpOfGroupType_e;
/**
* \brief OpenFlow Flow Type
*/
typedef enum xpOfFlowType_e
{
XP_OFPFT_STANDARD_FLOW = 0, ///< Standard OpenFlow flow visible for
///< SDN controller.
XP_OFPFT_HIDDEN_HIGH_FLOW = 1, ///< Flow with priority higher than
///< standard OpenFlow flow. This flow
///< is invisible for SDN controller.
///< Can be used to implement in-band management.
XP_OFPFT_HIDDEN_LOW_FLOW = 2, ///< Flow with priority lower than
///< standard OpenFlow flow. This flow
///< is invisible for SDN controller.
///< Can be used to implement OF Table
///< default behavior through a hidden rule.
} xpOfFlowType_e;
/**
* \brief OpenFlow Packet-In reason codes
*/
typedef enum xpOfPacketInReason_e
{
XP_OFPR_TABLE_MISS = 0, ///< No matching flow (table-miss flow entry).
XP_OFPR_APPLY_ACTION = 1, ///< Output to controller in apply-actions.
XP_OFPR_INVALID_TTL = 2, ///< Packet has invalid IP or MPLS TTL.
XP_OFPR_ACTION_SET = 3, ///< Output to controller in action set.
XP_OFPR_GROUP = 4, ///< Output to controller in group bucket.
XP_OFPR_PACKET_OUT = 5, ///< Output to controller in packet-out.
XP_OFPR_PORT_LOCAL = 7, ///< Output to XP_OFPP_LOCAL.
} xpOfPacketInReason_e;
/**
* \brief OpenFlow Table type
*/
typedef enum xpOfTableType_e
{
XP_OF_HASH_TABLE = 0,
XP_OF_TCAM_TABLE,
XP_OF_TABLE_NUM
} xpOfTableType_e;
// XPS ENUMS
/**
* \brief This type (enum) defines the interfaces
*/
typedef enum xpsInterfaceType_e
{
XPS_PORT = 0,
XPS_EXTENDED_PORT, ///< 802.1BR port extention
XPS_PORT_CONTROL_VIF, ///< Control Vif with ignore TRT bit set
XPS_LAG, ///< LAG
XPS_TUNNEL_MPLS, ///< MPLS
XPS_TUNNEL_VXLAN, ///< VXLAN Tunnel
XPS_TUNNEL_NVGRE, ///< NVGRE Tunnel
XPS_TUNNEL_GENEVE, ///< GENEVE Tunnel
XPS_TUNNEL_PBB, ///< Provider Backbone Bridges (also known as "Mac-In-Mac") Tunnel
XPS_TUNNEL_GRE, ///< GRE Tunnel
XPS_TUNNEL_VPN_GRE, ///< VPN GRE Tunnel
XPS_TUNNEL_VPN_GRE_LOOSE, ///< VPN GRE Loose Mode Tunnel
XPS_TUNNEL_GRE_ERSPAN2, ///< GRE ERSPAN Tunnel
XPS_TUNNEL_IP_IN_IP, ///< IP-in-IP Tunnel
XPS_L2_MCAST_GROUP, ///< L2 Multicast Group
XPS_L3_MCAST_GROUP, ///< L3 Multicast Group
XPS_PORT_ROUTER, ///< Port Based Router
XPS_SUBINTERFACE_ROUTER, ///< Sub interface Router
XPS_VLAN_ROUTER, ///< VLAN Based Router
XPS_TUNNEL_ROUTER, ///< Tunnel Based Router
XPS_VPN_ROUTER ///< L3VPN Based Router
} xpsInterfaceType_e;
/**
* \public
* \brief This type (enum) defines the number of Qos Profiles
* supported in the QosMap Table
*/
typedef enum
{
QOSMAP_PROFILE_TRUST,
QOSMAP_PROFILE_1,
QOSMAP_PROFILE_2,
QOSMAP_PROFILE_3,
QOSMAP_PROFILE_4,
QOSMAP_PROFILE_5,
QOSMAP_PROFILE_6,
QOSMAP_PROFILE_7,
QOSMAP_PROFILE_MAX,
} xpQosMapPfl_t;
/**
*IACL related enums
*/
/**
* \public
* \brief This type (enum) defines types of ACL tables
*
**/
typedef enum
{
XP_ACL_IACL0, ///< Port IACL
XP_ACL_IACL1, ///< Bridge IACL
XP_ACL_IACL2, ///< Router IACL
XP_ACL_EACL, ///< EACL
XP_ACML_TOTAL_TYPE,
} xpAclType_e;
/**
* \public
* \brief This type (enum) defines type of IACL Table.
*
**/
typedef enum
{
XP_IACL0,
XP_IACL1,
XP_IACL2,
XP_IACL_TOTAL_TYPE,
} xpIaclType_e;
/**
* \brief IPv4 IACL Key Fields
*/
typedef enum
{
XP_IACL_KEY_TYPE_V4, ///< 8b
XP_IACL_ID, ///< 8b ACL ID
XP_IACL_MAC_DA, ///< 48b Mac DA
XP_IACL_MAC_SA, ///< 48b Mac SA
XP_IACL_V4_ETHER_TYPE, ///< 16b IPv4 Ethernet type
XP_IACL_CTAG_VID_DEI_PCP, ///< 16b C-Tag Virtual ID + DEI + PCP
XP_IACL_STAG_VID_DEI_PCP, ///< 16b S-Tag Virtual ID + DEI + PCP
XP_IACL_DIP_V4, ///< 32b DIP
XP_IACL_SIP_V4, ///< 32b SIP
XP_IACL_L4_DEST_PORT, ///< 16b L4 Destination Port
XP_IACL_L4_SRC_PORT, ///< 16b L4 Source Port
XP_IACL_IVIF, ///< 16b Ingress Virtual Interface
XP_IACL_ICMP_CODE, ///< 8b ICMP Code
XP_IACL_ICMP_MSG_TYPE, ///< 8b ICMP Message Type
XP_IACL_PROTOCOL, ///< 8b IP Protocol
XP_IACL_DSCP_ECN, ///< 8b QoS DSCP and ECN Value
XP_IACL_BD, ///< 16b Bridge Domain ID
XP_IACL_TTL, ///< 8b IP Time to Live
XP_IACL_PKTLEN, ///< 8b IP Packet Length
XP_IACL_TCP_FLAGS, ///< 8b TCP Flags
XP_IACL_VRF_ID, ///< 16b Virtual Router Interface ID
XP_IACL_TAG_FRAGMENT_INFO, ///< 8b IP Fragment Bits
XP_IACL_IPV4_MAX_FLDS
} xpIaclV4KeyFlds;
/**
* \brief IPv6 IACL Key Fields
*/
typedef enum
{
XP_IACL_KEY_TYPE_V6, ///< 8b
XP_IACL_V6_ID, ///< 8b ACL ID
XP_IACL_DIP_V6, ///< 128b V6 DIP
XP_IACL_SIP_V6, ///< 128b V6 SIP
XP_IACL_NXT_HDR, ///< 8b Next Header
XP_IACL_L4_V6_DEST_PORT, ///< 16b Destination Port
XP_IACL_L4_V6_SRC_PORT, ///< 16b Source Port
XP_IACL_ICMP_V6_CODE, ///< 8b ICMP Code
XP_IACL_ICMP_V6_MSG_TYPE, ///< 8b ICMP Message Type
XP_IACL_HOP_LIMIT, ///< 8b Hop Limit
XP_IACL_V6_PROTOCOL, ///< 8b IPv6 Protocol
XP_IACL_V6_TCP_FLAGS, ///< 8b TCP Flags
XP_IACL_V6_PKTLEN, ///< 8b IP Packet Length
XP_IACL_TC_ROUTERMAC, ///< 8b Router MAC & Traffic Class
XP_IACL_IPV6_MAX_FLDS
}xpIaclV6KeyFlds;
/**
* \brief MPLS IACL Key Fields
*/
typedef enum
{
XP_IACL_KEY_TYPE_MPLS_V4, ///< 8b
XP_IACL_MPLS_V4_ID, ///< 8b ACL ID
XP_IACL_MPLS_V4_DIP, ///< 32b DIP
XP_IACL_MPLS_V4_SIP, ///< 32b SIP
XP_IACL_MPLS_V4_L4_DEST_PORT, ///< 16b L4 Destination Port
XP_IACL_MPLS_V4_L4_SRC_PORT, ///< 16b L4 Source Port
XP_IACL_MPLS_V4_IVIF, ///< 8b IVIF
XP_IACL_MPLS_V4_ICMP_CODE, ///< 8b ICMP Code
XP_IACL_MPLS_V4_ICMP_MSG_TYPE, ///< 8b ICMP Message Type
XP_IACL_MPLS_V4_PROTOCOL, ///< 8b IPv4 Protocol
XP_IACL_MPLS_V4_DSCP_ECN, ///< 8b QoS DSCP and ECN
XP_IACL_MPLS_V4_BD, ///< 16b Bridge Domain ID
XP_IACL_MPLS_V4_TCP_FLAGS, ///< 8b TCP Flags
XP_IACL_MPLS_V4_TTL, ///< 8b Time to Live
XP_IACL_MPLS_V4_PKTLEN_LABEL_EXP, ///< 40b Packet Len & MPLS Label and EXP
XP_IACL_IPV4_MPLS_MAX_FLDS
}xpIaclV4MplsKeyFlds;
/**
* \brief IPv4 EACL Key Fields
*/
typedef enum
{
XP_EACL_KEY_TYPE_V4, ///< 8b
XP_EACL_MAC_DA,
XP_EACL_MAC_SA,
XP_EACL_DIP_V4,
XP_EACL_SIP_V4,
XP_EACL_L4_DEST_PORT,
XP_EACL_L4_SRC_PORT,
XP_EACL_V4_ETHER_TYPE,
XP_EACL_ICMP_MSG_TYPE,
XP_EACL_PROTOCOL,
XP_EACL_EGRESS_BD,
XP_EACL_EGRESS_VIF,
XP_EACL_VI,
XP_EACL_DSCP_PCP_EXP,
XP_EACL_TCP_FLAGS_RSNCODE,
XP_EACL_TC_DP,
XP_EACL_IPV4_MAX_FLDS,
} xpEaclV4KeyFlds;
/**
* \brief IPv6 EACL Key Fields
*/
typedef enum
{
XP_EACL_KEY_TYPE_V6,
XP_EACL_DIP_V6,
XP_EACL_SIP_V6,
XP_EACL_L4_V6_DEST_PORT,
XP_EACL_L4_V6_SRC_PORT,
XP_EACL_V6_ETHER_TYPE,
XP_EACL_ICMP_V6_MSG_TYPE,
XP_EACL_V6_EGRESS_BD,
XP_EACL_V6_EGRESS_VIF,
XP_EACL_V6_RSNCODE_TC_DP,
XP_EACL_IPV6_MAX_FLDS,
} xpEaclV6KeyFlds;
typedef enum
{
XP_IACL_V4_TYPE,
XP_IACL_V6_TYPE,
XP_IACL_V4_MPLS_TYPE,
} xpIaclKeyType;
/**
* \brief This type (enum) defines the hashable fields
*/
typedef xpHashField xpsHashField_e;
/**
* \brief This type (enum) lists the packet forwarding processing commands
*/
typedef xpPktCmd_e xpsPktCmd_e;
/**
* \brief This type (enum) defines the counting modes
* The configuration is a bitmask, which can enable
* counting (bit 0), policing (bit 1) and sampling (bit2).
*/
typedef xpCountMode_e xpsCountMode_e;
/**
* \brief This type (enum) defines an the egress encapsulation
* types for an L2 Domain.
*/
typedef xpL2EncapType_e xpsL2EncapType_e;
/**
* \brief This type (enum) defines the Multicast
* Bridging modes configurable for a VLAN.
*/
typedef xpVlanBridgeMcMode_e xpsVlanBridgeMcMode_e;
/**
* \brief This type (enum) defines the Count Mode
* for a VLAN.
*/
typedef xpBdCountMode_e xpsVlanCountMode_e;
/**
* \brief This type (enum) defines the Spanning Tree States
* for a port.
*/
typedef xpVlanStgState_e xpsStpState_e;
/**
* \brief This type (enum) defines IP type
* used as IP Route Table Prefix lookup.
**/
typedef xpIpPrefixType_t xpsIpPrefixType_e;
/**
*\brief This type (enum) defines the device initialization modes
* INIT_COLD:
Performs addDevice and all respective managers
will perform "software init", "hardware init" and
load default values. This is used when the system
is initialized the first time.
INIT_WARM: (shadow is not present in the system)
Performs addDevice and all respective managers
will perform "software init" only. Most cases the
managers should recreate config and state from hardware
but typical case there is no shadow maintained, hence
table/reg data is not modified on the live system.
INIT_WARM_SYNC_TO_HW:
(shadow is available and is persistent across warm restart)
Performs addDevice, and software initialization
for all blocks. "software init" only. For
managers should load data from shadow to hardware
and push the configration to hardware.
INIT_WARM_SYNC_TO_SHADOW:
(shadow is available and is synced by reading hardware)
Performs addDevice, and software initialization
for all blocks. "software init" only. For
managers should load data from hardware to shadow. For
other configurations and data is recreated/read from hw.
*/
typedef xpInitType_t xpsInitType_e;
typedef xpInitType_t xpsInitType_t;
/**
* \brief This type (enum) defines the MAC configuration modes
*
*/
typedef xpMacConfigMode xpsMacConfigMode_e;
/**
* \brief This type (enum) defines the Packet Driver
* Rx modes
*/
typedef xpRxConfigMode xpsRxConfigMode_e;
/**
* \brief This type (enum) defines SAL object types
*/
typedef xpSalType_t xpsSalType_e;
/**
* \brief This type (enum) defines the Packet Driver
* callback handler types
*/
typedef xpCallbackMethodType xpsCallbackMethodType_e;
/**
* \brief This type (enum) defines the Packet Driver
* Tx modes
*/
typedef txMode xpsTxMode_e;
/**
* \brief This type (enum) defines the Packet Driver
* Rx handler types
*/
typedef xpCpuRxPktCbType_e xpsCpuRxPktCbType_e;
/**
* \brief This type (enum) defines the Forward-Error-Correction (FEC) types
*/
typedef xpFecMode xpsFecMode_e;
/**
* \brief This type (enum) defines the serdes tuning types
*/
typedef xpSerdesDfeTuneMode_t xpsSerdesDfeTuneMode_e;
/**
* \brief This type (enum) defines the port speeds
*/
typedef enum xpSpeed xpsSpeed_e;
/**
* \brief This type (enum) defines the event source identifiers
*/
typedef enum xpEventType xpsEventType_e;
/**
* \brief This type (enum) defines the Advanced Counting Module (ACM) modes
*/
typedef XP_ACM_CONFIG_MODE xpsAcmConfigMode_e;
/**
* \brief This type (enum) defines the Advanced Counting Module (ACM) clients
*/
typedef xpAcmClient_e xpsAcmClient_e;
/**
* \brief This type (enum) defines the Driver Access Layer (DAL) types
*/
typedef enum xpsDalType_e
{
XPS_DAL_HARDWARE, ///< Hardware
XPS_DAL_WHITEMODEL ///< Simulation
}xpsDalType_e;
/**
* \brief This type (enum) defines the interface upon which Packet Driver operation is performed
*/
typedef xpPacketInterface xpsPacketInterface_e;
/**
* \brief This type (enum) defines the Policing results types
*/
typedef xpPolicingResultType xpsPolicingResultType_e;
typedef XP_PROFILE_TYPE xpsProfileType_e;
/**
* \brief This type (enum) defines the typical SKUs modes the device may be configured to
*/
typedef xpSkuMode_e xpsSkuMode_e;
/**
* \brief This type (enum) defines the New Address Message types
* User defined data willbe in Type(int), Length(int), Value(Length bytes) format.
*/
typedef xpNlMsgType_e xpsNlMsgType_e;
/**
* \brief OpenFlow Ports
*/
typedef xpOfPortNo_e xpsOfPortNo_e;
/**
* \brief OpenFlow Action Type
*/
typedef xpOfActionType_e xpsOfActionType_e;
/**
* \brief OpenFlow Match Field Type
*/
typedef xpOxmType_e xpsOxmType_e;
/**
* \brief OpenFlow Match Packet Type
*/
typedef xpOfMatchPktType_e xpsOfMatchPktType_e;
/**
* \brief OpenFlow Group Type
*/
typedef xpOfGroupType_e xpsOfGroupType_e;
/**
* \brief OpenFlow Flow Type
*/
typedef xpOfFlowType_e xpsOfFlowType_e;
/**
* \brief OpenFlow Packet-In reason codes
*/
typedef xpOfPacketInReason_e xpsOfPacketInReason_e;
/**
* \brief OpenFlow Table type
*/
typedef xpOfTableType_e xpsOfTableType_e;
#endif //_openXpsEnums_h_
|
XPliant/OpenXPS
|
include/openXpsPort.h
|
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* All Rights Reserved.
*
* 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.
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATIONS ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*
* FILE : openXpsPort.h
*
* Abstract: This file defines the apis for Port Management in OpenXPS.
************************************************************************/
/**
* \file openXpsPort.h
* \brief This file contains API prototypes and type definitions
* for the openXps Port Management
* \copyright (c) 2016 Cavium Inc
*/
#ifndef _openXpsPort_h_
#define _openXpsPort_h_
#include "openXpsTypes.h"
#include "openXpsEnums.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Get Ihe interface ID corresponding to the CPU port
*
* \param [in] devId Device Id of device
* \param [out] *intfId Interface ID
*
* \return XP_STATUS
*/
XP_STATUS xpsPortGetCPUPortIntfId(xpsDevice_t devId, xpsInterfaceId_t *intfId);
/**
* \brief Get the interface ID corresponding to a specific port
*
* \param [in] devId Device Id of device
* \param [in] portNum Port
* \param [out] intfId
*
* \return XP_STATUS
*/
XP_STATUS xpsPortGetPortIntfId(xpsDevice_t devId, xpsPort_t portNum, xpsInterfaceId_t *intfId);
/**
* \brief set fieldValue in port config
*
* \param [in] intfId
* \param [in] portIfId
* \param [in] fNum
* \param [in] fData
*
* \return int
*/
XP_STATUS xpsPortSetField(xpsDevice_t devId, xpsInterfaceId_t portIfId,xpsPortConfigFieldList_t fNum,uint32_t fData);
/**
* \brief get fieldValue in port config
*
* \param [in] intfId
* \param [in] portIfId
* \param [in] fNum
* \param [in] fData
*
* \return int
*/
XP_STATUS xpsPortGetField(xpsDevice_t devId, xpsInterfaceId_t portIfId,xpsPortConfigFieldList_t fNum,uint32_t *fData);
/**
* \brief Set configurations for a specific port
*
* \param [in] devId Device Id of device
* \param [in] portIfId Port
* \param [in] pConfig Port Configuration Entry added to hardware
*
* \return XP_STATUS
*/
XP_STATUS xpsPortSetConfig(xpsDevice_t devId, xpsInterfaceId_t portIfId, xpsPortConfig_t *pConfig);
/**
* \brief Get configurations for a specific port
*
* \param [in] devId Device Id of device
* \param [in] portIfId Port
* \param [in] pConfig Port Configuration Entry read
*
* \return XP_STATUS
*/
XP_STATUS xpsPortGetConfig(xpsDevice_t devId, xpsInterfaceId_t portIfId, xpsPortConfig_t *pConfig);
/**
* \brief Get the Device Id and Port Number from the interface
* Id
*
* \param [in] intfId
* \param [out] devId
* \param [out] portNum
*
* \return int
*/
XP_STATUS xpsPortGetDevAndPortNumFromIntf(xpsInterfaceId_t intfId, xpsDevice_t *devId, xpsPort_t *portNum);
/**
* \brief Get the port control interface id corresponding to the port
*
* Get the portControlIntfInfo i.e interfaceId and deviceNum
* \param [in] devId
* \param [in] portNum
* \param [out] * intfId
*
* \return int
*/
XP_STATUS xpsPortGetPortControlIntfId(xpsDevice_t devId, xpsPort_t portNum, xpsInterfaceId_t *intfId);
#ifdef __cplusplus
}
#endif
#endif //_openXpsPort_h_
|
XPliant/OpenXPS
|
include/openXpsFdb.h
|
<filename>include/openXpsFdb.h
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* All Rights Reserved.
*
* 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.
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATIONS ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*
* FILE : openXpsFdb.h
*
* Abstract: This file defines the apis for FDB Management in OpenXPS.
************************************************************************/
/**
* \file openXpsFdb.h
* \brief This file contains API prototypes and type definitions
* for the openXps FDB Management
* \copyright (c) 2016 Cavium Inc
*/
#ifndef _openXpsFdb_h_
#define _openXpsFdb_h_
#include "openXpsTypes.h"
#include "openXpsEnums.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Function pointer for FDB Aging registration
*/
typedef void (*xpFdbAgingHandler)(xpsDevice_t , uint32_t *, void *);
/**
* \struct xpsFdbEntry_t
* \brief This structure defines the FDB entry format.
*/
typedef struct
{
xpVlan_t vlanId; ///< VLAN-ID
macAddr_t macAddr; ///< MAC
xpPktCmd_e pktCmd; ///< Packet Command
uint8_t isControl; ///< Control MAC
uint8_t isRouter; ///< Router MAC
uint8_t isStatic; ///< Static MAC
xpsInterfaceId_t intfId; ///< Interface ID
uint32_t serviceInstId; ///< A Service Instance ID to represent VNI/TNI/ISID for tunnelled packets
} xpsFdbEntry_t;
/**
* \brief Functional Pointer for FDB MAC Learning Handler registration
*
* \param [in] devId
* \param [in] ingressVif
* \param [in] reasonCode
* \param [in] bdId
* \param [in] buf
* \param [in] bufSize
* \param [in] userData
*
*/
typedef XP_STATUS (*xpsFdbLearnHandler)(xpsDevice_t, uint32_t, uint32_t,
uint32_t, void*, uint16_t, void*);
/**
* \brief API to control FDB MAC Aging period
*
* \param [in] devId Device Id of device.
* \param [in] agingExpo Actual aging timeout is 2 ^ agingExpo * Unit Time
*
* \return XP_STATUS
*
*/
XP_STATUS xpsFdbSetAgingTime (xpsDevice_t devId, uint32_t agingExpo);
/**
* \brief Add an entry into the FDB table
*
* \param [in] devId Device Id of device.
* \param [in] *fdbEntry Pointer to FDB entry structure.
* \param [out] *index Index at which the FDB entry is written to hardware.
* \param [out] *rehashIndex Index of entry which has been rehashed.
*
* \return XP_STATUS
*
*/
XP_STATUS xpsFdbAddEntry (xpsDevice_t devId, xpsFdbEntry_t *fdbEntry, uint32_t *index, uint32_t *rehashIndex);
/**
* \brief Write an entry into the FDB table at a specific index
*
* \param [in] devId Device Id of device.
* \param [in] index Index at which the FDB entry will be written to hardware.
* \param [in] *fdbEntry Pointer to FDB entry structure that must be written to hardware.
*
* \return XP_STATUS
*
*/
XP_STATUS xpsFdbWriteEntry (xpsDevice_t devId, uint32_t index, xpsFdbEntry_t *fdbEntry);
/**
* \brief Remove an entry from the FDB table for a specific MAC and VLAN
*
* \param [in] devId Device Id of device.
* \param [in] *fdbEntry Pointer to FDB entry structure, containing the MAC and the VLAN of the FDB entry to be removed.
*
* \return XP_STATUS
*
*/
XP_STATUS xpsFdbRemoveEntry (xpsDevice_t devId, xpsFdbEntry_t *fdbEntry);
/**
* \brief Remove an entry from the FDB table at a specific index
*
* \param [in] devId Device Id of device.
* \param [in] index Index of the FDB entry to be removed from hardware.
*
* \return XP_STATUS
*
*/
XP_STATUS xpsFdbRemoveEntryByIndex (xpsDevice_t devId, uint32_t index);
/**
* \brief Find the index where a FDB entry is programmed, for a specific MAC and VLAN
*
* \param [in] devId Device Id of device.
* \param [in] *fdbEntry Pointer to FDB entry structure, containing the MAC and the VLAN of the FDB entry.
* \param [out] *index Index at which the FDB entry was found.
*
* \return XP_STATUS
*
*/
XP_STATUS xpsFdbFindEntry (xpsDevice_t devId, xpsFdbEntry_t *fdbEntry, uint32_t *index);
/**
* \brief The method allows to register the FDB learn handler
*
* \param [in] devId Device Id of device.
* \param [in] fdbLearnCb func where fdbLearnHandler is of type XP_STATUS (*xpsFdbLearnHandler)(xpsDevice_t,
* uint32_t ingressVif, uint32_t reasonCode, uint32_t bdId, void* buf, uint16_t bufSize , void*)
* \param [in] *userData User Provided Data
*
* \return XP_STATUS
*/
XP_STATUS xpsFdbRegisterLearn (xpsDevice_t devId, xpsFdbLearnHandler fdbLearnCb, void *userData);
/**
* \brief The method allows to unregister the FDB learn handler
*
* \param [in] devId Device Id of device.
*
* \return XP_STATUS
*/
XP_STATUS xpsFdbUnregisterLearnHandler (xpsDevice_t devId);
/**
* \brief The method allows to register the FDB aging handler
*
* \param [in] devId Device Id of device.
* \param [in] fdbAgingHandler User Provided Call back where fdbAgingHandler is of type void (*aging_handler)(xpsDevice_t , uint32_t *, void *)
* \param [in] userData User Provided Data
*
* \return XP_STATUS
*
*/
XP_STATUS xpsFdbRegisterAgingHandler (xpsDevice_t devId, xpFdbAgingHandler fdbAgingHandler, void *userData);
/**
* \brief The method allows to unregister the FDB aging handler
*
* \param [in] devId Device Id of device.
*
* \return XP_STATUS
*
*/
XP_STATUS xpsFdbUnregisterAgingHandler (xpsDevice_t devId);
/**
* \brief Enable Aging on the FDB table
*
* \param [in] devId Device Id of device.
* \param [in] enable Enable/disable aging for the FDB table.
*
* \return XP_STATUS
*
*/
XP_STATUS xpsFdbConfigureTableAging (xpsDevice_t devId, uint32_t enable);
/**
* \brief Display valid table entries in FDB table in the given range
*
* \param [in] devId
* \param [out] *numOfValidEntries
* \param [in] startIndex
* \param [in] endIndex
* \param [in] *logFile
* \param [in] detailFormat
* \param [in] silentMode
*
* \return XP_STATUS
*/
XP_STATUS xpsFdbDisplayTable (xpsDevice_t devId, uint32_t *numOfValidEntries, uint32_t startIndex, uint32_t endIndex, char * logFile, uint32_t detailFormat, uint32_t silentMode);
#ifdef __cplusplus
}
#endif
#endif //_openXpsFdb_h_
|
XPliant/OpenXPS
|
xpnet/src/xp_netdev_core.c
|
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* 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; version 2
* of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* A copy of the GNU General Public License, version 2 is available in the file
* named LICENSE-GPLv2.md either in this directory or its root.
* Alernatively to obtain a copy, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* File: xp_netdev_core.c
*
* Abstract: This file contains the netdev implementation requried for xpliant.
************************************************************************/
#include "xp_common.h"
#include "xp_netdev.h"
#define READ_REG 1U
#define WRITE_REG 0U
#define XPNET_MAX_PACKET_SIZE (16 << 10)
#define XPNET_MIN_PACKET_SIZE (60 + 24)
#define XPNET_MAX_DMA_SIZE (4 << 10)
/* RX descriptor and its required bit fields */
#define XP_RX_DESCRIPTOR_BITOFF_ERRORINDICATION (0)
#define XP_RX_DESCRIPTOR_BITOFF_OWNERSHIP (4)
#define XP_TX_DESCRIPTOR_BITOFF_ERRORINDICATION (0)
#define XP_TX_DESCRIPTOR_BITOFF_OWNERSHIP (4)
#define XPNET_ENABLE_QUEUE (8)
/* ACQLOCK tells the callee function that a lock is to be acquired
* if the lock is already acquired by the caller, this bit is set to 0 */
#define XPNET_AFLAG_ACQLOCK (0x1)
#define XPNET_AFLAG_DMA (0x10)
#define XPNET_HWFLAG_A0 0x1
extern int xp_netdev_mode_init(void);
extern int xp_netdev_mode_deinit(void);
extern void xp_rx_skb_process(xpnet_private_t *priv, struct sk_buff *skb);
extern int xpnet_proc_create(xpnet_private_t *net_priv);
extern int xp_dev_reg_read(u32 *rw_value, u32 reg_addr,
u8 reg_size, xp_private_t *priv, u32 count);
extern int xp_dev_reg_write(u32 *rw_value, u32 reg_addr,
u8 reg_size, xp_private_t *priv, u32 count);
typedef int32_t (*reg_rw_func)(xpnet_private_t *, u32, u8, u32 *, u32);
xpnet_private_t *g_net_priv;
int jiffies_defer = 5;
static int __xp_dev_reg_read(u32 *rw_value, u32 reg_addr,
u8 reg_size, xp_private_t *priv)
{
if (DWORD_SIZE != reg_size) {
pr_err("%s: Invalid register reg_size = %x\n", __func__, reg_size);
return -EINVAL;
}
*rw_value = *(u32*)((uint8_t*)(priv->vma) + reg_addr);
/* pr_debug("rw_value = %x, reg_addr = 0x%x\n", *rw_value, reg_addr); */
/* pr_debug("%s:%d priv->vma = 0x%p reg_addr = %p\n", __func__, __LINE__,
priv->vma , ((uint8_t*)(priv->vma) + reg_addr)); */
return 0;
}
static int __xp_dev_reg_write(u32 rw_value, u32 reg_addr,
u8 reg_size, xp_private_t *priv)
{
if (DWORD_SIZE != reg_size) {
pr_err("%s: Invalid register reg_size = %x\n", __func__, reg_size);
return -EINVAL;
}
*(u32*)((uint8_t*)(priv->vma) + reg_addr) = rw_value;
/* pr_debug("rw_value = 0x%x, reg_addr = 0x%x\n", rw_value, reg_addr); */
return 0;
}
static void __xpnet_endian_swap32(u32 *base, u32 buf_size,
xp_address_mode_t mode)
{
uint16_t chr_num = 0;
/* If device mode is A0 uncompress then only perform the swap. */
if (mode == XP_A0_UNCOMPRESSED) {
for (chr_num = 0; chr_num <= (buf_size - 1) / 4; chr_num++) {
base[chr_num] = __builtin_bswap32(base[chr_num]) & 0xFFFFFFFF;
}
}
}
static int32_t __xp_dev_reg_read_q(xpnet_private_t *net_priv, u32 reg_id,
u8 data_size, u32 *value, u32 qnum)
{
u32 reg_offset, i;
reg_offset =
XP_GET_PCI_BASE_OFFSET_FROM_REG_NAME(reg_id, net_priv->pci_priv->mode);
reg_offset = XP_GET_DMA_Q_REG_OFFSET(reg_offset, data_size, qnum);
/* No testing performed, caller ensures enough allocation. */
for (i = 0; i < data_size; i++) {
__xp_dev_reg_read(&value[i],
reg_offset + (i * sizeof(u32)),
4, net_priv->pci_priv);
}
return 0;
}
int32_t xp_dev_reg_read_q(xpnet_private_t *net_priv, u32 reg_id,
u8 data_size, u32 *value, u32 qnum)
{
u32 reg_offset;
reg_offset =
XP_GET_PCI_BASE_OFFSET_FROM_REG_NAME(reg_id, net_priv->pci_priv->mode);
reg_offset = XP_GET_DMA_Q_REG_OFFSET(reg_offset, data_size, qnum);
/* No testing performed, caller ensures enough allocation. */
xp_dev_reg_read(value, reg_offset,
4, net_priv->pci_priv, data_size);
return 0;
}
static int32_t __xp_dev_write_q(xpnet_private_t *net_priv, u32 reg_id,
u8 data_size, u32 *value, u32 qnum)
{
u32 reg_offset, i;
reg_offset =
XP_GET_PCI_BASE_OFFSET_FROM_REG_NAME(reg_id, net_priv->pci_priv->mode);
reg_offset = XP_GET_DMA_Q_REG_OFFSET(reg_offset, data_size, qnum);
for (i = 0; i < data_size; i++) {
__xp_dev_reg_write(value[i],
reg_offset +
(i * sizeof(u32)), 4, net_priv->pci_priv);
}
return 0;
}
int32_t xp_dev_reg_write_q(xpnet_private_t *net_priv, u32 reg_id,
u8 data_size, u32 *value, u32 qnum)
{
u32 reg_offset;
reg_offset =
XP_GET_PCI_BASE_OFFSET_FROM_REG_NAME(reg_id, net_priv->pci_priv->mode);
reg_offset = XP_GET_DMA_Q_REG_OFFSET(reg_offset, data_size, qnum);
xp_dev_reg_write(value,
reg_offset,
4, net_priv->pci_priv, data_size);
return 0;
}
/* xpnet_set_q_cdp
*
* @xpnet_priv : xpnet_private structure
* @q : the queue to be updated
* @cdp : cdp dma address
*
* DESC: the cdp is used only if the TX queue is not chained. If chained,
* the queue's starting descriptor is the cdp and h/w will update it auto-
* matically.
*/
static void xpnet_set_q_cdp(xpnet_private_t *net_priv,
xpnet_queue_struct_t *q, int idx, u8 aflags)
{
u64 base_cdp = (u64) q->dma + (idx * (sizeof(xpnet_descriptor_t)));
u32 reg = (q->xpq_type == XPNET_QUEUE_TYPE_TX) ?
DMA0_RX_CDP_REG_E :
DMA0_TX_CDP_REG_E;
fdebug("Entering %s(), cdp = %016llx\n", __func__, base_cdp);
(aflags & XPNET_AFLAG_ACQLOCK) ?
xp_dev_reg_write_q(net_priv, reg, 2, (u32 *) & base_cdp, q->xpq_id) :
__xp_dev_write_q(net_priv, reg, 2, (u32 *) & base_cdp, q->xpq_id);
}
u64 xpnet_get_q_cdp(xpnet_private_t *net_priv,
xpnet_queue_struct_t *q, u8 aflags)
{
u64 base_cdp = 0;
u32 reg = (q->xpq_type == XPNET_QUEUE_TYPE_TX) ?
DMA0_RX_CDP_REG_E :
DMA0_TX_CDP_REG_E;
fdebug("Entering %s()\n", __func__);
(aflags & XPNET_AFLAG_ACQLOCK) ?
xp_dev_reg_read_q(net_priv, reg, 2, (u32 *) & base_cdp, q->xpq_id) :
__xp_dev_reg_read_q(net_priv, reg, 2, (u32 *) & base_cdp, q->xpq_id);
fdebug("Read cdp = %016llx\n", base_cdp);
return base_cdp;
}
/*
* __xpnet_enable_queue
* @xpnet_priv : xpnet_private structure
* @q : queue to be updated in register
* @enable : if non zero, enables the queue, else
* disables the queue
* @prio : if > 8, keeps the priority,
* else overwrite with prio
*/
static void xpnet_queue_en_dis(xpnet_private_t *net_priv,
xpnet_queue_struct_t *q,
u8 enable, u8 prio, u8 aflags)
{
u32 reg = (q->xpq_type == XPNET_QUEUE_TYPE_TX) ?
DMA0_RX_CMD_REG_E :
DMA0_TX_CMD_REG_E;
u64 regval;
reg_rw_func read_fn, write_fn;
if (aflags & XPNET_AFLAG_ACQLOCK) {
read_fn = xp_dev_reg_read_q;
write_fn = xp_dev_reg_write_q;
} else {
read_fn = __xp_dev_reg_read_q;
write_fn = __xp_dev_write_q;
}
/* fdebug("Entering %s(), qid = %d, en %d, flag %d\n",
__func__, q->xpq_id, enable, aflags); */
read_fn(net_priv, reg, 1, (u32 *) ®val, q->xpq_id);
if (prio > 7) {
/* If prio > 7, use the existing priority. */
prio = regval & 7;
}
/* Enable/disable the queue. */
regval = (enable) ? XPNET_ENABLE_QUEUE | prio : prio;
/* fdebug("Writing cmd reg %#x, val %#016llx\n", reg, regval); */
write_fn(net_priv, reg, 1, (u32 *) & regval, q->xpq_id);
}
static void reset_mgmt_dma(void)
{
fdebug("Entering %s()\n", __func__);
}
static inline void xpnet_rx_desc_enable(xpnet_desc_struct_t *d)
{
u64 regval = d->va->qword[0] & 0x1f;
/* fdebug("Entering %s()\n", __func__); */
regval |= (1 << XP_TX_DESCRIPTOR_BITOFF_OWNERSHIP);
d->va->qword[0] = regval;
}
static void xpnet_queue_desc_link(xpnet_queue_struct_t *q, int circular)
{
int next = 0;
int n = 0;
/* fdebug("Entering %s()\n", __func__); */
/* fdebug("q = %p\n", q); */
/* Go through descriptors to create a linked list. */
for (n = 0; n < q->xpq_num_desc; n++) {
next = (n + 1) % q->xpq_num_desc;
q->xpq_desc_meta[n].va->qword[3] =
(u64) q->xpq_desc_meta[next].cdp;
}
if (!circular) {
q->xpq_desc_meta[q->xpq_num_desc - 1].va->qword[3] = 0;
}
}
static void xpnet_rx_queue_desc_change_own(xpnet_queue_struct_t *q, int cpu_owns)
{
int n = 0;
/* fdebug("Entering %s()\n", __func__); */
if (cpu_owns) {
/* Change the ownership bit of all descriptors of this queue. */
for (n = 0; n < q->xpq_num_desc; n++) {
xpnet_rx_desc_enable(&q->xpq_desc_meta[n]);
}
}
}
static void xpnet_rx_queue_link_and_enable(xpnet_queue_struct_t *q)
{
/* fdebug("Entering %s()\n", __func__); */
/* In case of interrupt enabling, disable pre-empting. */
xpnet_queue_desc_link(q, 0);
xpnet_rx_queue_desc_change_own(q, 1);
q->head = 0;
q->tail = 0; /* Indicate init complete. */
q->status = XPNET_QUEUE_ACTIVE;
}
/* __xpnet_rx_desc_reset
* Called with q->xpq_lock held
* Does not set qword[3] to next for chaining
*/
static int __xpnet_rx_desc_reset(xpnet_queue_struct_t *q, int idx)
{
int next = xpnet_add_and_wrap(idx, 1, q->xpq_num_desc);
/* fdebug("Entering %s()\n", __func__); */
q->xpq_desc_meta[idx].va->qword[3] = q->xpq_desc_meta[next].cdp;
q->xpq_desc_meta[idx].va->qword[2] = q->xpq_desc_meta[idx].buf_sta.dma;
q->xpq_desc_meta[idx].va->qword[1] = XPNET_MAX_PACKET_SIZE;
q->xpq_desc_meta[idx].va->qword[0] =
(1 << XP_TX_DESCRIPTOR_BITOFF_OWNERSHIP);
return 0;
}
/*
* @xpnet_priv : allocated xpnet_private structure
* @q : rx queue that needs to be un-initilized
* @meta_idx : index of the meta data where skb allocation failed
*
* cleans up metadata of one specific queue till `meta_idx`
* and then the queue itself
* DOES NOT deallocate the queue itself
*/
static void xpnet_rx_queue_uninit(xpnet_private_t *net_priv, int queue, int meta_idx)
{
int i = 0;
u32 memlen =
XPNET_CEIL_LEN((XPNET_RX_NUM_DESCS * XPNET_DESC_SIZE), PAGE_SIZE);
xpnet_desc_struct_t *d = NULL;
xpnet_queue_struct_t *q = &net_priv->rx_queue[queue];
/* fdebug("Entering %s()\n", __func__); */
fdebug("Disabling RX queue %d, idx till %d\n", queue, meta_idx);
/* Disable the queue in the command register. */
xpnet_queue_en_dis(net_priv, q, 0, 0, XPNET_AFLAG_ACQLOCK);
/* Uninit till failed index. */
for (i = 0; i < meta_idx; i++) {
d = &q->xpq_desc_meta[i];
memset(d->va, 0, sizeof(xpnet_descriptor_t));
d->cdp = 0;
if (d->buf_sta.va != NULL) {
dma_free_coherent(&net_priv->pdev->dev,
d->buf_sta.len, d->buf_sta.va, d->buf_sta.dma);
d->buf_sta.va = NULL;
}
}
/* Deallocate all coherent memory of the descriptors of this queue. */
fdebug("dma_free_coherent memlen %d, va %p, dma %#llx\n",
memlen, q->va, q->dma);
dma_free_coherent(&net_priv->pdev->dev, memlen, q->va, q->dma);
}
/*
* @xpnet_priv : allocated xpnet_private structure
* @failed_idx : index of the queue where allocation failed
*
* This function cleans up all queues till index `failed_idx`
*/
static void xpnet_rx_teardown(xpnet_private_t *net_priv, int failed_idx)
{
/* Teardown from 0 -> failed_idx */
int i = 0;
/* fdebug("Entering %s()\n", __func__); */
for (i = 0; i < failed_idx; i++) {
xpnet_rx_queue_uninit(net_priv, i, net_priv->rx_queue[i].xpq_num_desc);
}
}
static int xpnet_rx_desc_init(xpnet_queue_struct_t *q,
int idx, xpnet_shards_struct_t *prealloc)
{
xpnet_descriptor_t *d = (xpnet_descriptor_t *)q->dma;
xpnet_descriptor_t *v = (xpnet_descriptor_t *)q->va;
xpnet_desc_struct_t *desc = &q->xpq_desc_meta[idx];
/* fdebug("Entering %s()\n", __func__); */
desc->num_shards = 0;
desc->va = &v[idx];
desc->cdp = (dma_addr_t) & d[idx];
desc->buf_sta.dma = prealloc->dma;
desc->buf_sta.len = prealloc->len;
desc->buf_sta.va = prealloc->va;
/* Doing only one descriptor, so caller has to link. */
/* Do not touch the NDP field. */
/* desc->va->qword[3]; */
desc->va->qword[2] = prealloc->dma;
desc->va->qword[1] = prealloc->len;
return 0;
}
static int xpnet_prealloc_buf(xpnet_private_t *net_priv,
xpnet_shards_struct_t *tgt)
{
dma_addr_t dma;
/* Allocate a memory area with dma_alloc_coherent. */
void *va = dma_alloc_coherent(&net_priv->pdev->dev,
XPNET_MAX_PACKET_SIZE, &dma, GFP_KERNEL);
if (!va) {
fdebug("Memory allocation fail.\n");
return -ENOMEM;
}
tgt->va = va;
tgt->dma = dma;
tgt->len = XPNET_MAX_PACKET_SIZE;
return 0;
}
/*
* Logically, rxqueue is device -> host, that is txqueue of device
* This queue does NOT get drained fast, hence depth can be > 1
* This functin will be used to add the queue logic.
*/
static int xpnet_rx_queue_init(xpnet_private_t *net_priv, int i)
{
xpnet_queue_struct_t *q = NULL;
u32 memlen = 0;
int n = 0, rc = 0;
xpnet_shards_struct_t prealloc;
/* fdebug("Entering %s()\n", __func__); */
if (i >= XPNET_RX_NUM_QUEUES) {
fdebug("Invalid parameter %d (> XPNET_RX_NUM_QUEUES)\n", i);
return -EINVAL;
}
q = &net_priv->rx_queue[i];
/* Start initalizing all queue elements here. */
/* Allocate RX descriptors just for this queue. */
memlen = (XPNET_RX_NUM_DESCS * XPNET_DESC_SIZE);
/* fdebug("Required memlen for RX : %#010x bytes\n", memlen); */
memlen = XPNET_CEIL_LEN(memlen, PAGE_SIZE);
/*fdebug("Allocated memlen for RX : %#010x bytes\n", memlen); */
/* Allocate a memory area with dma_alloc_coherent. */
q->va = dma_alloc_coherent(&net_priv->pdev->dev,
memlen, &q->dma, GFP_KERNEL);
if (!q->va) {
fdebug("Memory allocation fail.\n");
return -ENOMEM;
}
memset(q->va, 0, memlen);
spin_lock_init(&q->xpq_lock);
q->xpq_id = i;
q->xpq_type = XPNET_QUEUE_TYPE_RX;
q->xpq_num_desc = XPNET_RX_NUM_DESCS;
q->status = XPNET_QUEUE_STOPPED;
q->tail = 0;
q->head = 0;
/* START from here. */
for (n = 0; n < q->xpq_num_desc; n++) {
if ((rc = xpnet_prealloc_buf(net_priv, &prealloc)) != 0) {
/* Free all allocated in this queue before returning. */
xpnet_rx_queue_uninit(net_priv, q->xpq_id, n);
return rc;
}
xpnet_rx_desc_init(q, n, &prealloc);
}
/* Link and change the ownership bit. */
xpnet_rx_queue_link_and_enable(q);
/* Set the queue up with current descriptor pointer CDP. */
xpnet_set_q_cdp(net_priv, q, 0, XPNET_AFLAG_ACQLOCK);
/* fdebug("Returning %s()\n", __func__); */
return 0;
}
static int xpnet_rx_all_queues_start(xpnet_private_t *net_priv)
{
int i = 0;
/* fdebug("Entering %s()\n", __func__); */
for (i = 0; i < net_priv->num_rxqueues; i++) {
xpnet_queue_en_dis(net_priv, &net_priv->rx_queue[i], 1, 0,
XPNET_AFLAG_ACQLOCK);
}
return 0;
}
static int xpnet_rx_queue_setup(xpnet_private_t *net_priv, int num_queues)
{
int i = 0, rc = 0;
/* fdebug("Entering %s()\n", __func__); */
/* RX descriptor allocation. */
net_priv->num_rxqueues = num_queues;
for (i = 0; i < num_queues; i++) {
if ((rc = xpnet_rx_queue_init(net_priv, i)) < 0) {
xpnet_rx_teardown(net_priv, i);
return rc;
}
}
return 0;
}
/* Initializes a descriptor (and its meta data in the queue)
* @xpnet_priv : xpnet private structure
* @q : tx queue
* @idx : index that is to be filled
*/
static int xpnet_tx_desc_init(xpnet_private_t *net_priv,
xpnet_queue_struct_t *q, int idx)
{
xpnet_descriptor_t *d = (xpnet_descriptor_t *)q->dma;
xpnet_descriptor_t *v = (xpnet_descriptor_t *)q->va;
xpnet_desc_struct_t *desc = &q->xpq_desc_meta[idx];
/* fdebug("Entering %s()\n", __func__); */
desc->num_shards = 0;
desc->va = &v[idx];
desc->cdp = (dma_addr_t) & d[idx];
desc->buf_sta.va = dma_alloc_coherent(&net_priv->pdev->dev, PAGE_SIZE,
&(desc->buf_sta.dma), GFP_KERNEL);
if (desc->va == NULL) {
return -ENOMEM;
}
desc->buf_sta.len = 0; /* Length of buffer filled, not allocated. */
return XPNET_OK;
}
static void xpnet_tx_queue_uninit(xpnet_private_t *net_priv,
xpnet_queue_struct_t *q, int meta_idx)
{
int i = 0;
u32 memlen =
XPNET_CEIL_LEN((XPNET_RX_NUM_DESCS * XPNET_DESC_SIZE), PAGE_SIZE);
xpnet_desc_struct_t *d = NULL;
/* fdebug("Entering %s()\n", __func__); */
/* Disable the queue in the command register. */
xpnet_queue_en_dis(net_priv, q, 0, 0, XPNET_AFLAG_ACQLOCK);
/* Uninit till failed index. */
for (i = 0; i < meta_idx; i++) {
d = &q->xpq_desc_meta[i];
fdebug("i = %d, d = %p, d->va %p\n", i, d, d ? d->va : NULL);
memset(d->va, 0, sizeof(xpnet_descriptor_t));
d->cdp = 0;
d->va = NULL;
if (d->buf_sta.va != NULL) {
dma_free_coherent(&net_priv->pdev->dev,
PAGE_SIZE, d->buf_sta.va, d->buf_sta.dma);
d->buf_sta.va = NULL;
d->buf_sta.dma = 0;
}
}
/* Deallocate all coherent memory of the descriptors of this queue. */
fdebug("Freeing q->va %p, q->dma %#llx, memlen %d\n",
q->va, q->dma, memlen);
dma_free_coherent(&net_priv->pdev->dev, memlen, q->va, q->dma);
}
static int xpnet_tx_queue_init(xpnet_private_t *net_priv, int i)
{
xpnet_queue_struct_t *q = NULL;
u32 mem_len;
int n = 0, rc = 0;
/* fdebug("Entering %s()\n", __func__); */
if (i >= net_priv->num_txqueues) {
fdebug("Invalid parameter %d (> num_txqueues(%d))\n",
i, net_priv->num_txqueues);
return -EINVAL;
}
q = &net_priv->tx_queue[i];
/* Start initalizing all queue elements here. */
spin_lock_init(&q->xpq_lock);
q->xpq_id = i;
q->xpq_type = XPNET_QUEUE_TYPE_TX;
q->xpq_num_desc = XPNET_TX_NUM_DESCS;
q->tail = 0;
q->head = q->xpq_num_desc - 1;
/* Allocate descriptors just for this queue. */
mem_len = (XPNET_TX_NUM_DESCS * XPNET_DESC_SIZE);
fdebug("Required memlen for TX : %#010x bytes.\n", mem_len);
mem_len = XPNET_CEIL_LEN(mem_len, PAGE_SIZE);
fdebug("Allocated memlen for TX : %#010x bytes.\n", mem_len);
/* Allocate a memory area with dma_alloc_coherent. */
q->va = dma_alloc_coherent(&net_priv->pdev->dev,
mem_len, &q->dma, GFP_KERNEL);
if (!q->va) {
fdebug("Memory allocation fail.\n");
return -ENOMEM;
}
fdebug("TX q->va %p, q->dma %llx\n", q->va, q->dma);
memset(q->va, 0, mem_len);
for (n = 0; n < q->xpq_num_desc; n++) {
rc = xpnet_tx_desc_init(net_priv, q, n);
if (rc != XPNET_OK) {
fdebug("TX_DESC_INIT FAILED, %d\n", n);
xpnet_tx_queue_uninit(net_priv, q, n);
return rc;
}
}
if ((net_priv->hw_flags & XPNET_HWFLAG_A0) == 0) {
/* HW is not A0, can go ahead and link. */
xpnet_queue_desc_link(q, 0);
}
/* Set the queue up with current descriptor pointer CDP. */
xpnet_set_q_cdp(net_priv, q, 0, XPNET_AFLAG_ACQLOCK);
q->status = XPNET_QUEUE_ACTIVE;
return XPNET_OK;
}
static void xpnet_tx_teardown(xpnet_private_t *net_priv, int failed_idx)
{
xpnet_queue_struct_t *q = NULL;
/* Teardown from 0 -> failed_idx */
int i = 0;
/* fdebug("Entering %s()\n", __func__); */
for (i = 0; i < failed_idx; i++) {
q = &net_priv->tx_queue[i];
xpnet_tx_queue_uninit(net_priv, q, q->xpq_num_desc);
}
}
static int xpnet_tx_queue_setup(xpnet_private_t *net_priv, int num_queues)
{
int i = 0, rc = 0;
/* fdebug("Entering %s()\n", __func__); */
net_priv->num_txqueues = num_queues;
/* TX descriptor allocation. */
for (i = 0; i < num_queues; i++) {
if ((rc = xpnet_tx_queue_init(net_priv, i)) < 0) {
xpnet_tx_teardown(net_priv, i);
return rc;
}
}
return 0;
}
/*
* xpnet_program_mux_setdma
*
* programs the mux for GMAC or DMA
* @flag : 0 -> GMAC
* : 1 -> DMA
*/
static void xpnet_program_mux_setdma(xpnet_private_t *net_priv, u32 flag)
{
u32 regval, reg;
/* fdebug("Entering %s()\n", __func__); */
reg = MGMT_CTRL_REG_E;
xp_dev_reg_read_q(net_priv, reg, 1, ®val, 0);
fdebug("Mux register %x.\n", regval);
if (flag != 0) {
/* Set to DMA */
regval |= (1 << 3);
} else {
/* Set to GMAC */
regval &= ~(1 << 3);
}
xp_dev_reg_write_q(net_priv, reg, 1, ®val, 0);
udelay(10);
xp_dev_reg_read_q(net_priv, reg, 1, ®val, 0);
fdebug("Mux register set to %x.\n", regval);
}
static void xpnet_rx_queue_process(xpnet_private_t *net_priv,
int queue, int maxiter)
{
int i = 0;
unsigned long flags = 0;
uint16_t pkt_size = XPNET_MAX_PACKET_SIZE;
dma_addr_t dma;
xpnet_desc_struct_t *d = NULL;
xpnet_queue_struct_t *q = &net_priv->rx_queue[queue];
struct sk_buff *skb = NULL;
/* fdebug("Entering %s()\n", __func__); */
/* Iterate through the queue descriptors upto maxiter times. */
for (i = 0; i < maxiter; i++) {
spin_lock_irqsave(&q->xpq_lock, flags);
d = &q->xpq_desc_meta[q->tail];
fdebug("Rx tail = %d\n", q->tail);
/* Check error first. */
if ((d->va->qword[0] >>
XP_RX_DESCRIPTOR_BITOFF_ERRORINDICATION) == 1) {
fdebug("Dma error. Resetting the descriptor.\n");
__xpnet_rx_desc_reset(q, q->tail);
xpnet_rx_desc_enable(d);
net_priv->stats.rx_dropped++;
net_priv->stats.rx_length_errors++;
spin_unlock_irqrestore(&q->xpq_lock, flags);
return;
}
/* Check completion if no error. */
if ((d->va->qword[0] >> XP_RX_DESCRIPTOR_BITOFF_OWNERSHIP) & 0x01) {
//fdebug("Dma still owns the desc. Rx in progress.\n");
spin_unlock_irqrestore(&q->xpq_lock, flags);
return;
}
/* Received a packet from HW. Set the next packet read delay to 0.
It means that may be we have one more packet
that should be read immediately. */
jiffies_defer = 0;
/* Process one complete packet : SOP to EOP */
dma = d->buf_sta.dma;
pkt_size = (d->va->qword[1] >> 16) & 0xffff;
if (net_priv->pci_priv->mode == XP_A0_UNCOMPRESSED) {
pkt_size -= 16;
}
if (pkt_size > XPNET_MAX_PACKET_SIZE) {
fdebug("Pkt size error. Resetting the descriptor.\n");
__xpnet_rx_desc_reset(q, q->tail);
xpnet_rx_desc_enable(d);
net_priv->stats.rx_dropped++;
spin_unlock_irqrestore(&q->xpq_lock, flags);
return;
}
skb = dev_alloc_skb(pkt_size);
if (!skb) {
spin_unlock_irqrestore(&q->xpq_lock, flags);
fdebug("No skb available.\n");
return;
}
__xpnet_endian_swap32(d->buf_sta.va, pkt_size,
net_priv->pci_priv->mode);
memcpy(skb->data, d->buf_sta.va, pkt_size);
skb->len = pkt_size;
/* Reset the length of dma bufffer. */
d->va->qword[1] = d->buf_sta.len;
/* Clear other bits set in the qword[0]. */
d->va->qword[0] = (1 << XP_TX_DESCRIPTOR_BITOFF_OWNERSHIP);
q->tail = xpnet_add_and_wrap(q->tail, 1, q->xpq_num_desc);
if (q->tail == 0) {
fdebug("q->tail == 0, cdp resetting\n");
/* Lockinig, strictly speaking, not required on RX. */
xpnet_set_q_cdp(net_priv, q, 0, XPNET_AFLAG_ACQLOCK);
xpnet_queue_en_dis(net_priv, q, 1, 0, XPNET_AFLAG_ACQLOCK);
}
spin_unlock_irqrestore(&q->xpq_lock, flags);
xp_rx_skb_process(net_priv, skb);
}
}
static int xpnet_rx_handle(xpnet_private_t *net_priv)
{
int i = 0;
unsigned long flags = 0;
spin_lock_irqsave(&net_priv->priv_lock, flags);
if (0 == net_priv->dma_trigger) {
printk("DMA engine not enabled.\n");
/* Schedule rx handler after some time. */
jiffies_defer = 3 * HZ;
spin_unlock_irqrestore(&net_priv->priv_lock, flags);
return 0;
}
spin_unlock_irqrestore(&net_priv->priv_lock, flags);
/* fdebug("Entering %s()\n", __func__); */
for (i = 0; i < XPNET_RX_NUM_QUEUES; i++) {
xpnet_rx_queue_process(net_priv, i, XPNET_RX_NUM_DESCS);
}
return 0;
}
/*
* __xpnet_skb_to_shards
* Splits the skb to shards
*/
static int __xpnet_skb_to_shards(struct sk_buff *skb, xpnet_queue_struct_t *q,
xpnet_private_t *net_priv)
{
/* Only the first packet should set SOP, only the last packet
* should set EOP, length should be a multiple of 8 bytes
* for all except last. */
int copied = 0, n = q->tail, max = skb->len, idx = 0, b2c = 0;
xpnet_desc_struct_t *d;
/* fdebug("Entering %s()\n", __func__); */
while (copied < max) {
d = &q->xpq_desc_meta[n];
b2c = ((max - copied) < XPNET_MAX_DMA_SIZE) ? (max - copied) :
XPNET_MAX_DMA_SIZE;
d->buf_sta.len = b2c;
/* Handle short packet. */
if (max < 128) {
memset(d->buf_sta.va, 0x00, 128);
d->buf_sta.len = 128;
}
memcpy(d->buf_sta.va, skb->data + copied, b2c);
__xpnet_endian_swap32(d->buf_sta.va,
d->buf_sta.len, net_priv->pci_priv->mode);
copied += b2c;
n = xpnet_add_and_wrap(n, 1, q->xpq_num_desc);
idx++;
}
return idx;
}
static int __xpnet_skb_stat_enqueue(xpnet_private_t *net_priv,
xpnet_queue_struct_t *q, int shards)
{
int idx, max = shards;
xpnet_desc_struct_t *d = &q->xpq_desc_meta[q->tail];
/* fdebug("Entering %s()\n", __func__); */
/* Check for space for all shards. */
for (idx = q->tail; max > 0; --max) {
d = &q->xpq_desc_meta[idx];
if ((d->va->qword[0] >> XP_TX_DESCRIPTOR_BITOFF_OWNERSHIP) & 0x01) {
/* At least one element is still busy. */
fdebug("Queue busy = %d\n", idx);
return XPNET_QUEUE_BUSY;
}
if ((d->va->qword[0] >>
XP_TX_DESCRIPTOR_BITOFF_ERRORINDICATION) & 0x01) {
fdebug("Queue error = %d\n", idx);
/* At least one element of the queue is hosed. */
return XPNET_QUEUE_ERROR;
}
idx = xpnet_add_and_wrap(idx, 1, q->xpq_num_desc);
}
max = shards;
for (idx = q->tail; max > 0; --max) {
d = &q->xpq_desc_meta[idx];
//d->va->qword[3] = 0; /* Will be reset in the next go. */
d->va->qword[2] = d->buf_sta.dma;
d->va->qword[1] = d->buf_sta.len;
if (idx == q->tail) {
/* First element, set SOP only. */
d->va->qword[0] = (1 << 3);
} else {
d->va->qword[0] = (1 << XP_TX_DESCRIPTOR_BITOFF_OWNERSHIP);
}
idx = xpnet_add_and_wrap(idx, 1, q->xpq_num_desc);
}
/* Set EOP for last element. */
d->va->qword[0] |= (1 << 2); /* Keep the ownership bit. */
/* Now all except the first one has ownership bit set. */
d = &q->xpq_desc_meta[q->tail];
d->num_shards = shards;
d->va->qword[0] |= (1 << XP_TX_DESCRIPTOR_BITOFF_OWNERSHIP);
if (net_priv->hw_flags & XPNET_HWFLAG_A0) {
xpnet_set_q_cdp(net_priv, q, q->tail, 0);
/* Do not lock, enable with priority 0. */
xpnet_queue_en_dis(net_priv, q, 1, 0, 0);
}
return XPNET_OK;
}
/*
* __xpnet_enforce_skb_sanity() checks 3 constraints
* 1. if the skb->len is a multiple of 4
* 2. if the skb->data starts at 4kB boundary
* 3. if the skb->data + len crosses 4kB boundary
*
* If any of these constraints are met, the buffer is split into
* chunks of size <= 4kB
*/
static int __xpnet_enforce_skb_sanity(xpnet_private_t *net_priv,
xpnet_queue_struct_t *q,
struct sk_buff *skb)
{
int new_len = 0;
/* fdebug("Entering %s()\n", __func__); */
if ((net_priv->hw_flags & XPNET_HWFLAG_A0) == 0) {
return XPNET_OK;
}
/* Check if the skb address+len crosses 4k boundary
* Since IOMMU is present, it happens only if skb->len > 4kB */
new_len = XPNET_CEIL_LEN(skb->len, 4);
if (new_len > XPNET_MAX_DMA_SEGMENT_SIZE) {
fdebug("Crosses 4k boundary\n");
return XPNET_REASON_4KCROSS;
}
/* Check if skb->len < (60 + 24) */
if (skb->len < XPNET_MIN_PACKET_SIZE) {
fdebug("Short packet %d\n", skb->len);
return XPNET_REASON_SHORTPACKET;
}
return XPNET_OK;
}
static void start_dma_reset(xpnet_private_t *net_priv)
{
/* fdebug("Entering %s()\n", __func__); */
}
static netdev_tx_t xpnet_hard_start_xmit(struct sk_buff *skb,
xpnet_private_t *net_priv, int txqno)
{
unsigned long flags = 0;
int shards = 0;
int rc = 0;
int num_free_desc = 0;
xpnet_enum_t skb_good = 0;
xpnet_desc_struct_t *d = NULL;
xpnet_queue_struct_t *q = &net_priv->tx_queue[txqno];
/* fdebug("Entering %s()\n", __func__); */
spin_lock_irqsave(&q->xpq_lock, flags);
if (q->status != XPNET_QUEUE_ACTIVE) {
net_priv->stats.tx_errors++;
fdebug("Internal queue(%d) not active.\n", txqno);
goto ret_txdrop;
}
if (skb == NULL) {
fdebug("Null skb.\n");
goto ret_txdrop;
}
/* Must lock q before calling. */
num_free_desc = xpnet_get_free_desc(q);
/* fdebug("num_free_desc = %d, tail %d,
head %d\n", num_free_desc, q->tail, q->head); */
if (num_free_desc == 0) {
/* Queue is full, can't xmit. */
goto ret_txbusy;
}
if ((skb->len == 0) ||
(skb->len > (num_free_desc * XPNET_MAX_DMA_SEGMENT_SIZE))) {
net_priv->stats.tx_errors++;
fdebug("Skb len : %d\n", skb->len);
goto ret_txdrop;
}
if (skb->data_len != 0) {
/* Contains fragments. Currently not handling in the driver. */
net_priv->stats.tx_errors++;
goto ret_txdrop;
}
d = &q->xpq_desc_meta[q->tail];
/* fdebug("q->tail = %d\n", n); */
if ((d->va->qword[0] >> XP_TX_DESCRIPTOR_BITOFF_OWNERSHIP) & 0x01) {
/* Queue still busy. */
goto ret_txbusy;
}
if ((d->va->qword[0] >> XP_TX_DESCRIPTOR_BITOFF_ERRORINDICATION) & 0x01) {
/* Queue is hosed. Need a dma reset. */
start_dma_reset(net_priv);
goto ret_txbusy;
}
/* Queue is ready and has space to transmit. */
skb_good = __xpnet_enforce_skb_sanity(net_priv, q, skb);
/* Need to copy the buffer to shard (buf_sta). */
shards = __xpnet_skb_to_shards(skb, q, net_priv);
/* The skb is split to n->n+shards descriptors. */
if (shards > num_free_desc) {
fdebug("CORRUPTION : shards(%d) > num_free_desc(%d)",
shards, num_free_desc);
}
rc = __xpnet_skb_stat_enqueue(net_priv, q, shards);
if (rc == XPNET_QUEUE_BUSY) {
goto ret_txbusy;
} else if (rc == XPNET_QUEUE_ERROR) {
net_priv->stats.tx_aborted_errors++;
net_priv->stats.tx_dropped++;
start_dma_reset(net_priv);
goto ret_txbusy;
}
/* Data is copied, don't need skb anymore */
dev_kfree_skb_any(skb);
net_priv->stats.tx_packets++;
net_priv->stats.tx_bytes += skb->len;
q->tail = xpnet_add_and_wrap(q->tail, shards, q->xpq_num_desc);
goto ret_txok;
ret_txbusy:
fdebug("Returning txbusy, q->head %d, q->tail %d\n", q->head, q->tail);
spin_unlock_irqrestore(&q->xpq_lock, flags);
return NETDEV_TX_BUSY;
ret_txdrop:
fdebug("Packet dropped.\n");
dev_kfree_skb_any(skb);
net_priv->stats.tx_dropped++;
spin_unlock_irqrestore(&q->xpq_lock, flags);
return NETDEV_TX_OK;
ret_txok:
spin_unlock_irqrestore(&q->xpq_lock, flags);
return NETDEV_TX_OK;
}
static void xpnet_rxtx_handler(struct work_struct *w)
{
xpnet_private_t *priv = container_of(w, xpnet_private_t, dwork.work);
/* Set read packet delay to 1 jiffies.
The value could be overriden inside xpnet_rx_queue_process(). */
jiffies_defer = 1;
/* fdebug("Entering %s()\n", __func__); */
xpnet_rx_handle(priv);
/* Queue self, no interrupt to queue self. */
queue_delayed_work(priv->wqueue, &priv->dwork, jiffies_defer);
}
static void xpnet_tx_complete(xpnet_private_t *net_priv, int qno, int maxiter)
{
xpnet_queue_struct_t *q = &net_priv->tx_queue[qno];
xpnet_desc_struct_t *d = NULL;
int head, tail;
int iter, busy;
unsigned long flags = 0;
int attempt = 0;
fdebug("Entering %s(), q = %d, maxiter %d\n", __func__, qno, maxiter);
spin_lock_irqsave(&q->xpq_lock, flags);
head = q->head;
tail = q->tail;
busy = xpnet_get_busy_desc(q); /* Must lock q before calling. */
maxiter = (busy > maxiter) ? maxiter : busy;
fdebug("Head %d, tail %d, processing %d pkts.\n", head, tail, busy);
for (iter = 0; iter < maxiter; iter++) {
attempt = 0;
head = xpnet_add_and_wrap(head, 1, q->xpq_num_desc);
if (head == tail) {
/* Empty queue*/
fdebug("Empty queue.\n");
break;
}
d = &q->xpq_desc_meta[head];
if (((d->va->qword[0] >>
XP_TX_DESCRIPTOR_BITOFF_ERRORINDICATION) & 1) == 1) {
/* Needs a dma reset. */
reset_mgmt_dma();
fdebug("Tx error.\n");
break;
}
while ((attempt++ < XPNET_MAX_ATTEMPTS) &&
(((d->va->qword[0] >>
XP_TX_DESCRIPTOR_BITOFF_OWNERSHIP) & 0x01))) {
fdebug("TX in progress.\n");
/* TX in progress. */
udelay(5);
}
if ((d->va->qword[0] >> XP_TX_DESCRIPTOR_BITOFF_OWNERSHIP) & 0x01) {
/* TX still incomplete. */
fdebug("TX still incomplete : %d\n", attempt);
break;
}
q->head = xpnet_add_and_wrap(q->head, 1, q->xpq_num_desc);
}
if (iter != maxiter) {
fdebug("Ownership is not released and still releasing the lock.\n");
}
if ((net_priv->hw_flags & XPNET_HWFLAG_A0) != 0) {
q->head = q->xpq_num_desc - 1;
q->tail = 0;
}
spin_unlock_irqrestore(&q->xpq_lock, flags);
}
netdev_tx_t xpnet_start_xmit(struct sk_buff *skb, xpnet_private_t *net_priv)
{
netdev_tx_t rc = NETDEV_TX_OK;
unsigned long flags = 0;
spin_lock_irqsave(&net_priv->priv_lock, flags);
if (0 == net_priv->dma_trigger) {
printk("DMA engine not enabled.\n");
dev_kfree_skb(skb);
spin_unlock_irqrestore(&net_priv->priv_lock, flags);
return NETDEV_TX_OK;
}
spin_unlock_irqrestore(&net_priv->priv_lock, flags);
/* fdebug("Entering %s()\n", __func__); */
/* Move locking from here. */
spin_lock_irqsave(&net_priv->pci_priv->tx_dma_read_lock, flags);
rc = xpnet_hard_start_xmit(skb, net_priv, net_priv->txqno);
if (rc == NETDEV_TX_OK) {
/* Handle tx complete. */
xpnet_tx_complete(net_priv, net_priv->txqno,
net_priv->tx_queue[net_priv->txqno].xpq_num_desc);
}
/* Move locking from here. */
spin_unlock_irqrestore(&net_priv->pci_priv->tx_dma_read_lock, flags);
return rc;
}
int xp_netdev_init(xp_private_t *priv)
{
char queue_name[25];
int rc = 0;
unsigned long flags = 0;
xpnet_private_t *net_priv = NULL;
static int instance;
if (priv->xpnet){
pr_err("xp_netdev_init already done.\n");
return 0;
}
net_priv = (xpnet_private_t *)kzalloc(sizeof(xpnet_private_t), GFP_KERNEL);
if (net_priv == NULL) {
pr_err("Failed to allocate memory for netdev private structure.\n");
return -ENOMEM;
}
priv->xpnet = net_priv;
g_net_priv = net_priv;
net_priv->pdev = priv->pdev;
net_priv->pci_priv = priv;
net_priv->hw_flags = XPNET_HWFLAG_A0;
net_priv->dma_trigger = 0;
spin_lock_init(&net_priv->priv_lock);
xpnet_program_mux_setdma(net_priv, 0);
xpnet_rx_queue_setup(net_priv, XPNET_RX_NUM_QUEUES);
xpnet_tx_queue_setup(net_priv, XPNET_TX_NUM_QUEUES);
rc = xp_netdev_mode_init();
if (rc) {
pr_err("Error in xp_netdev_mode_init().\n");
goto err_netdev_fp_netdev;
}
/* Create workqueue. */
sprintf(queue_name, "xp_queue_%d", instance);
net_priv->wqueue = create_workqueue(queue_name);
if (!net_priv->wqueue) {
fdebug("Failed to create work queue.\n");
rc = -ENOMEM;
goto err_queue_create_failure;
}
INIT_DELAYED_WORK(&net_priv->dwork, xpnet_rxtx_handler);
net_priv->instance = instance;
rc = xpnet_proc_create(net_priv);
if (rc) {
pr_err("Error in xpnet_proc_create.\n");
}
queue_delayed_work(net_priv->wqueue, &net_priv->dwork, HZ * 5);
xpnet_rx_all_queues_start(net_priv);
/* Enable the DMA engine. */
xpnet_program_mux_setdma(net_priv, 1);
spin_lock_irqsave(&net_priv->priv_lock, flags);
net_priv->dma_trigger = 1;
spin_unlock_irqrestore(&net_priv->priv_lock, flags);
return 0;
err_queue_create_failure:
xp_netdev_mode_deinit();
err_netdev_fp_netdev:
xpnet_rx_teardown(net_priv, XPNET_RX_NUM_QUEUES);
xpnet_tx_teardown(net_priv, XPNET_TX_NUM_QUEUES);
kfree(net_priv);
priv->xpnet = NULL;
g_net_priv = NULL;
return rc;
}
void xp_netdev_deinit(xp_private_t *priv)
{
xpnet_private_t *net_priv = priv->xpnet;
int count;
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,10,0)
char queue_name[25];
#endif
if (!net_priv) {
pr_info("Nothing to remove.\n");
return;
}
/* Flush and destroy workqueue. */
xp_netdev_mode_deinit();
cancel_delayed_work_sync(&net_priv->dwork);
flush_workqueue(net_priv->wqueue);
xpnet_tx_teardown(net_priv, XPNET_TX_NUM_QUEUES);
xpnet_rx_teardown(net_priv, XPNET_RX_NUM_QUEUES);
destroy_workqueue(net_priv->wqueue);
for (count = 0; count < XPNET_NUM_QUEUES; count++) {
if (NULL != net_priv->proc_que[count]) {
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0)
proc_remove(net_priv->proc_que[count]);
#else
memset(queue_name, 0, sizeof(queue_name));
snprintf(queue_name, sizeof(queue_name) - 1, "queue%d", count);
remove_proc_entry(queue_name, net_priv->proc_root);
#endif
}
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0)
if (NULL != net_priv->proc_stats) {
proc_remove(net_priv->proc_stats);
}
if (NULL != net_priv->proc_ttable) {
proc_remove(net_priv->proc_ttable);
}
if (NULL != net_priv->proc_debug) {
proc_remove(net_priv->proc_debug);
}
if (NULL != net_priv->proc_netdev) {
proc_remove(net_priv->proc_netdev);
}
if (NULL != net_priv->proc_txhdr) {
proc_remove(net_priv->proc_txhdr);
}
#else
remove_proc_entry(XPNET_PROC_STATS, net_priv->proc_root);
remove_proc_entry(XPNET_PROC_TRAP_TABLE, net_priv->proc_root);
remove_proc_entry(XPNET_PROC_DEBUG, net_priv->proc_root);
remove_proc_entry(XPNET_PROC_NETDEV, net_priv->proc_root);
remove_proc_entry(XPNET_PROC_TXHDR, net_priv->proc_root);
#endif
if (NULL != net_priv->proc_root) {
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0)
proc_remove(net_priv->proc_root);
#else
memset(queue_name, 0, sizeof(queue_name));
snprintf(queue_name, sizeof(queue_name) - 1, "xpnet_%d",
net_priv->instance);
remove_proc_entry(queue_name, NULL);
#endif
}
kfree(priv->xpnet);
priv->xpnet = 0;
fdebug("xp_netdev_deinit() complete.\n");
}
|
XPliant/OpenXPS
|
include/openXpsSalInterface.h
|
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* All Rights Reserved.
*
* 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.
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATIONS ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*
* FILE : openXpsSalInterface.h
*
* Abstract: This file defines the System Abstraction Layer (SAL)
* functions in OpenXPS to provide abstraction
* and infrastructure to specify SAL object types
************************************************************************/
/**
* \file openXpsSalInterface.h
* \brief This file contains API prototypes and type definitions
* for the openXp Software Abstraction Layer Interface
* \copyright (c) 2016 Cavium Inc
*/
#ifndef _openXpSalInterface_h_
#define _openXpSalInterface_h_
#include "openXpsTypes.h"
#include "openXpsEnums.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief This method sets the SAL object type.
*
* \param [in] salType SAL Object Type
*
*/
void xpsSetSalType(xpsSalType_e salType);
/**
* \brief This method initializes the default SAL object.
*
*/
int xpsSalDefaultInit(void);
#ifdef __cplusplus
}
#endif
#endif //_openXpSalInterface_h_
|
XPliant/OpenXPS
|
xpnet/include/xp_reg_info.h
|
<gh_stars>10-100
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* 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; version 2
* of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* A copy of the GNU General Public License, version 2 is available in the file
* named LICENSE-GPLv2.md either in this directory or its root.
* Alernatively to obtain a copy, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* File: xp_reg_info.h
*
* Abstract: This file contains the register definitions.
************************************************************************/
#ifndef _XP_REG_INFO_H
#define _XP_REG_INFO_H
#define XP_HP_INT_REG_SIZE_IN_DWRD 4
#define XP_LP_INT_REG_SIZE_IN_DWRD 3
#define NUM_HP_INT_REG_BLOCKS 35
#define NUM_LP_INT_REG_BLOCKS 33
#define DMA0_INTR_START_BIT_POS(addr_mode) ((addr_mode) ? 9 : 8)
#define DMA0_TXDONE(reg_addr, qnum) (reg_addr + 16 * qnum)
#define DMA0_RXDONE(reg_addr, qnum) (reg_addr + 16 * qnum)
#define XP_GET_PCI_BASE_OFFSET_FROM_REG_NAME(reg_name, type) \
(xp_regs_list[reg_name][type])
#define XP_GET_DMA_Q_REG_OFFSET(reg_offset, size, qnum) \
reg_offset + (qnum * size * sizeof(u32));
typedef enum xp_address_mode {
XP_A0_UNCOMPRESSED,
XP_B0_UNCOMPRESSED,
XP_B0_COMPRESSED,
XP80_SUPPORTED_DEVICE_MODES
} xp_address_mode_t;
typedef enum xp_register {
HIGH_PRIO_REG_ADDR,
LOW_PRIO_REG_ADDR,
HIGH_INTR_SOURCE_REG_ADDR,
DMA0_TXDONE_STATUS_REG,
DMA0_RXDONE_STATUS_REG,
HIGH_PRIO_INT_ENABLE_REG_ADDR,
LOW_PRIO_INT_ENABLE_REG_ADDR,
DMA0_RX_CDP_REG_E,
DMA0_TX_CDP_REG_E,
DMA0_RX_CMD_REG_E,
DMA0_TX_CMD_REG_E,
CORE_CTRL_REG__1_E,
TX_DMA0_RETRY_CNT_REG_E,
MGMT_CTRL_REG_E,
DMA0_CLR_ERR_CNT_REG_E,
DMA0_TX_CHAIN_LEN_ERR_REG_E,
DMA0_TX_CPU_OWN_DESC_ERR_REG_E,
DMA0_TX_ZERO_BUF_LEN_ERR_REG_E,
DMA0_TX_PCIE_ERR_REG_E,
DMA0_TX_DMA_INTF_ERR_REG_E,
DMA0_TX_PKT_DROP_E,
TX_DMA0_CFG_REGLOCKREG_E,
TX_DMA0_SCRATCHPAD_E,
DMA0_RX_CHAIN_LEN_ERR_REG_E,
DMA0_RX_CPU_OWN_DESC_ERR_REG_E,
DMA0_RX_ZERO_BUF_LEN_ERR_REG_E,
DMA0_RX_PCIE_ERR_REG_E,
RX_DMA0_CFG_REGLOCKREG_E,
RX_DMA0_SCRATCHPAD_E,
CPU_CTRL_REG_E,
CPU_STS_REG_E,
SRAM_MEM_CFG_SRAM_EXT_MEM_E,
XP_MAX_REG_ACCESS_LIST
} xp_register_t;
extern u32 xp_regs_list[XP_MAX_REG_ACCESS_LIST][XP80_SUPPORTED_DEVICE_MODES];
#endif /* _XP_REG_INFO_H */
|
XPliant/OpenXPS
|
xpnet/src/xp_netdev_proc.c
|
<filename>xpnet/src/xp_netdev_proc.c
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* 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; version 2
* of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* A copy of the GNU General Public License, version 2 is available in the file
* named LICENSE-GPLv2.md either in this directory or its root.
* Alernatively to obtain a copy, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* File: xp_netdev_proc.c
*
* Abstract: This file contains the netdev message processing implementation for
* xpliant.
************************************************************************/
#include "xp_common.h"
#include "xp_netdev.h"
#define XP_DBG_GLOBAL (1 << 0)
#define XP_DBG_FP (1 << 1)
#define XP_DBG_NETDEV_PRINT (1 << 2)
#define XP_DBG_TX_HDR_PRINT (1 << 3)
#define DEBUG_BUF_SIZE 256
char debug_buffer[DEBUG_BUF_SIZE];
int g_debug = 0;
xpnet_que_info_t g_net_que_info[XPNET_NUM_QUEUES];
extern int xp_trap_table_print(struct seq_file *sf);
extern void xp_debug_set(int mode);
extern void xp_netdev_print(struct seq_file *sf);
extern void xp_netdev_tx_header_print(unsigned int xpnet_intf_id,
struct seq_file *sf);
static int sprint_descriptor(char *buf, int bufsize, void *p, char *msg)
{
int i = 0;
int chars = 0;
char *fmt = "[%01d]=%#016llx ";
xpnet_descriptor_t *desc = (xpnet_descriptor_t *)p;
if (bufsize < 18) {
return 0;
}
chars += sprintf(buf + chars, "(%p):%s", desc, msg);
for (i = 0; i < 4; i++) {
if (chars < (bufsize - (23 + 1))) {
chars += sprintf(buf + chars, fmt, i, desc->qword[i]);
} else {
chars += sprintf(buf + chars, "No space...");
}
}
return chars;
}
static void dma_stats_dump(xpnet_private_t *net_priv, struct seq_file *sf)
{
seq_printf(sf, "\nRX-TX DMA statstastic\n");
seq_printf(sf, "----------------------------------------------------\n");
seq_printf(sf, "RX packets:%ld errors:%ld dropped:%ld\n",
net_priv->stats.rx_packets, net_priv->stats.rx_length_errors,
net_priv->stats.rx_dropped);
seq_printf(sf, "TX packets:%ld errors:%ld dropped:%ld\n",
net_priv->stats.tx_packets, net_priv->stats.tx_aborted_errors +
net_priv->stats.tx_errors, net_priv->stats.tx_dropped);
seq_printf(sf, "RX bytes:%ld TX bytes:%ld\n",
net_priv->stats.rx_bytes, net_priv->stats.tx_bytes);
}
static void common_registers_dump(xpnet_private_t *net_priv,
struct seq_file *sf)
{
u32 regval;
u32 reg;
int qno = 0;
seq_printf(sf, "DMA 0 registers\n");
seq_printf(sf, "----------------------------------------------------\n");
reg = MGMT_CTRL_REG_E;
xp_dev_reg_read_q(net_priv, reg, 1, (u32 *)®val, qno);
seq_printf(sf, "MGMT_CTRL_REG_E "
"= %#010x\n", regval);
reg = CORE_CTRL_REG__1_E;
xp_dev_reg_read_q(net_priv, reg, 1, (u32 *)®val, qno);
seq_printf(sf, "CORE_CTRL_REG__1_E "
"= %#010x\n", regval);
reg = TX_DMA0_RETRY_CNT_REG_E;
xp_dev_reg_read_q(net_priv, reg, 1, (u32 *)®val, qno);
seq_printf(sf, "XP_MGMT_LOCAL_REG_TX_DMA0_RETRY_CNT_REG "
"= %#010x\n", regval);
reg = DMA0_CLR_ERR_CNT_REG_E;
xp_dev_reg_read_q(net_priv, reg, 1, (u32 *)®val, qno);
seq_printf(sf, "DMA0_CLR_ERR_CNT_REG "
"= %#010x\n", regval);
reg = DMA0_TX_CHAIN_LEN_ERR_REG_E;
xp_dev_reg_read_q(net_priv, reg, 1, (u32 *)®val, qno);
seq_printf(sf, "DMA0_TX_CHAIN_LEN_ERR_REG "
"= %#010x\n", regval);
reg = DMA0_TX_CPU_OWN_DESC_ERR_REG_E;
xp_dev_reg_read_q(net_priv, reg, 1, (u32 *)®val, qno);
seq_printf(sf, "DMA0_TX_CPU_OWN_DESC_ERR_REG "
"= %#010x\n", regval);
reg = DMA0_TX_ZERO_BUF_LEN_ERR_REG_E;
xp_dev_reg_read_q(net_priv, reg, 1, (u32 *)®val, qno);
seq_printf(sf, "DMA0_TX_ZERO_BUF_LEN_ERR_REG "
"= %#010x\n", regval);
reg = DMA0_TX_PCIE_ERR_REG_E;
xp_dev_reg_read_q(net_priv, reg, 1, (u32 *)®val, qno);
seq_printf(sf, "DMA0_TX_PCIE_ERR_REG "
"= %#010x\n", regval);
reg = DMA0_TX_DMA_INTF_ERR_REG_E;
xp_dev_reg_read_q(net_priv, reg, 1, (u32 *)®val, qno);
seq_printf(sf, "DMA0_TX_DMA_INTF_ERR_REG "
"= %#010x\n", regval);
reg = DMA0_TX_PKT_DROP_E;
xp_dev_reg_read_q(net_priv, reg, 1, (u32 *)®val, qno);
seq_printf(sf, "DMA0_TX_PKT_DROP "
"= %#010x\n", regval);
reg = TX_DMA0_CFG_REGLOCKREG_E;
xp_dev_reg_read_q(net_priv, reg, 1, (u32 *)®val, qno);
seq_printf(sf, "XP_MGMT_TX_DMA0_CFG_REGLOCKREG "
"= %#010x\n", regval);
reg = TX_DMA0_SCRATCHPAD_E;
xp_dev_reg_read_q(net_priv, reg, 1, (u32 *)®val, qno);
seq_printf(sf, "TX_DMA0_SCRATCHPAD "
"= %#010x\n", regval);
reg = DMA0_RX_CHAIN_LEN_ERR_REG_E;
xp_dev_reg_read_q(net_priv, reg, 1, (u32 *)®val, qno);
seq_printf(sf, "DMA0_RX_CHAIN_LEN_ERR_REG "
"= %#010x\n", regval);
reg = DMA0_RX_CPU_OWN_DESC_ERR_REG_E;
xp_dev_reg_read_q(net_priv, reg, 1, (u32 *)®val, qno);
seq_printf(sf, "DMA0_RX_CPU_OWN_DESC_ERR_REG "
"= %#010x\n", regval);
reg = DMA0_RX_ZERO_BUF_LEN_ERR_REG_E;
xp_dev_reg_read_q(net_priv, reg, 1, (u32 *)®val, qno);
seq_printf(sf, "DMA0_RX_ZERO_BUF_LEN_ERR_REG "
"= %#010x\n", regval);
reg = DMA0_RX_PCIE_ERR_REG_E;
xp_dev_reg_read_q(net_priv, reg, 1, (u32 *)®val, qno);
seq_printf(sf, "DMA0_RX_PCIE_ERR_REG "
"= %#010x\n", regval);
reg = RX_DMA0_CFG_REGLOCKREG_E;
xp_dev_reg_read_q(net_priv, reg,1, (u32 *)®val, qno);
seq_printf(sf, "XP_MGMT_RX_DMA0_CFG_REGLOCKREG "
"= %#010x\n", regval);
reg = RX_DMA0_SCRATCHPAD_E;
xp_dev_reg_read_q(net_priv, reg, 1, (u32 *)®val, qno);
seq_printf(sf, "RX_DMA0_SCRATCHPAD "
"= %#010x\n", regval);
}
static void internal_qstate_dump(xpnet_private_t *net_priv,
int qno, struct seq_file *sf)
{
xpnet_queue_struct_t *rq = NULL, *tq = NULL;
char *type = NULL;
if (qno < XPNET_RX_NUM_QUEUES) {
rq = &net_priv->rx_queue[qno];
}
if (qno < XPNET_TX_NUM_QUEUES) {
tq = &net_priv->tx_queue[qno];
}
type = "\nUPSTREAM-RX(host)";
seq_printf(sf, "%s\n", type);
seq_printf(sf, "----------------------------------------------------\n");
if (rq) {
seq_printf(sf, "xpq_id = %d\n", rq->xpq_id);
seq_printf(sf, "xpq_num_desc = %d\n", rq->xpq_num_desc);
seq_printf(sf, "status = %d\n", rq->status);
seq_printf(sf, "va = %p, dma = %pad\n", rq->va, &rq->dma);
}
type = "\nDSTREAM-TX(host)";
seq_printf(sf, "%s\n", type);
seq_printf(sf, "----------------------------------------------------\n");
if (tq) {
seq_printf(sf, "xpq_id = %d\n", tq->xpq_id);
seq_printf(sf, "xpq_num_desc = %d\n", tq->xpq_num_desc);
seq_printf(sf, "status = %d\n", tq->status);
seq_printf(sf, "head %d, tail %d\n", tq->head, tq->tail);
seq_printf(sf, "free desc %d, busy %d\n",
xpnet_get_free_desc(tq), xpnet_get_busy_desc(tq));
seq_printf(sf, "va = %p, dma = %pad\n", tq->va, &tq->dma);
}
}
static void queue_registers_dump(xpnet_private_t *net_priv, int qno,
struct seq_file *sf)
{
char *type;
u64 regval = 0;
u32 reg;
type = "UPSTREAM-RX(host) registers";
seq_printf(sf, "\n%s\n", type);
seq_printf(sf, "----------------------------------------------------\n");
if(qno <= XPNET_TX_NUM_QUEUES){
reg = DMA0_TX_CDP_REG_E;
xp_dev_reg_read_q(net_priv, reg, 2, (u32 *)®val, qno);
seq_printf(sf, "DMA0_TX_CDP_REG[%d] "
"= %#016llx\n", qno, regval);
reg = DMA0_TX_CMD_REG_E;
regval = 0;
xp_dev_reg_read_q(net_priv, reg, 1, (u32 *)®val, qno);
seq_printf(sf, "DMA0_TX_CMD_REG[%d] "
"= %#016llx\n", qno, regval);
}
type = "DSTREAM-TX(host) registers";
seq_printf(sf, "\n%s\n", type);
seq_printf(sf, "----------------------------------------------------\n");
if(qno <= XPNET_RX_NUM_QUEUES){
reg = DMA0_RX_CDP_REG_E;
regval = 0;
xp_dev_reg_read_q(net_priv, reg, 2, (u32 *)®val, qno);
seq_printf(sf, "DMA0_RX_CDP_REG[%d] "
"= %#016llx\n", qno, regval);
reg = DMA0_RX_CMD_REG_E;
regval = 0;
xp_dev_reg_read_q(net_priv, reg, 1, (u32 *)®val, qno);
seq_printf(sf, "DMA0_RX_CMD_REG[%d] "
"= %#016llx\n", qno, regval);
}
}
static void descriptors_dump(xpnet_private_t *net_priv, char *dest_buf,
int dblen, int qno, xpnet_enum_t rxtx,
struct seq_file *sf)
{
xpnet_descriptor_t *d;
xpnet_queue_struct_t *q;
char *type;
char local[64];
int i;
if (rxtx == XPNET_QUEUE_TYPE_TX) {
q = (qno >= XPNET_TX_NUM_QUEUES) ? NULL : &net_priv->tx_queue[qno];
type = "DSTREAM-TX(host)";
} else {
q = (qno >= XPNET_RX_NUM_QUEUES) ? NULL : &net_priv->rx_queue[qno];
type = "UPSTREAM-RX(host)";
}
if (q == NULL) {
sprintf(dest_buf, "Invalid queue %d", qno);
return;
}
seq_printf(sf, "\n%s queue[%d] : #of desc = %d, status = %d\n",
type, qno, q->xpq_num_desc, q->status);
if (q->xpq_type == XPNET_QUEUE_TYPE_TX) {
seq_printf(sf, "head = %d, tail = %d\n", q->head, q->tail);
}
seq_printf(sf, "----------------------------------------------------\n");
for (i = 0; i < q->xpq_num_desc; i++) {
d = q->xpq_desc_meta[i].va;
sprintf(local, "%sDESC[%d] : ", type, i);
sprint_descriptor(dest_buf, dblen, d, local);
seq_printf(sf, "%s\n", dest_buf);
}
}
static int xpnet_seq_show_header(xpnet_private_t *priv, struct seq_file *sf)
{
seq_printf(sf, "DMA queue information\n");
seq_printf(sf, "----------------------------------------------------\n");
seq_printf(sf, "hw_flags = %#x\n", priv->hw_flags);
seq_printf(sf, "Base txqno = %d \nBase rxqno = %d\n",
priv->txqno, priv->rxqno);
seq_printf(sf, "Number of txqueues = %d\nNumber of rxqueues = %d\n",
priv->num_txqueues, priv->num_rxqueues);
return 0;
}
static int xpnet_que_seq_show(struct seq_file *sf, void *v)
{
xpnet_que_info_t *que_info = NULL;
xpnet_private_t *priv = NULL;
int que_no;
que_info = sf->private;
priv = que_info->priv;
que_no = que_info->que_no;
xpnet_seq_show_header(priv, sf);
common_registers_dump(priv, sf);
queue_registers_dump(priv, que_no, sf);
internal_qstate_dump(priv, que_no, sf);
descriptors_dump(priv, debug_buffer,sizeof(debug_buffer),
que_no, XPNET_QUEUE_TYPE_RX, sf);
descriptors_dump(priv, debug_buffer,sizeof(debug_buffer),
que_no, XPNET_QUEUE_TYPE_TX, sf);
return 0;
}
static int xpnet_que_seq_open(struct inode *inode, struct file *file)
{
struct seq_file *s;
xpnet_que_info_t *que_info = NULL;
int result;
result = single_open(file, xpnet_que_seq_show, NULL);
s = (struct seq_file *)file->private_data;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0)
que_info = PDE_DATA(file_inode(file));
#else
que_info = PROC_I(inode)->pde->data;
#endif
s->private = que_info;
return result;
}
static ssize_t xpnet_que_proc_write(struct file *filp, const char *buf,
size_t bufsize, loff_t * off)
{
return bufsize;
}
static const struct file_operations xpnet_proc_fops = {
.owner = THIS_MODULE,
.open = xpnet_que_seq_open,
.read = seq_read,
.write = xpnet_que_proc_write,
.llseek = seq_lseek,
.release = single_release,
};
static int xpnet_stats_seq_show(struct seq_file *sf, void *v)
{
xpnet_private_t *priv = NULL;
priv = sf->private;
xpnet_seq_show_header(priv, sf);
dma_stats_dump(priv, sf);
return 0;
}
static int xpnet_stats_seq_open(struct inode *inode, struct file *file)
{
struct seq_file *s;
xpnet_private_t *xp_net_priv = NULL;
int result;
result = single_open(file, xpnet_stats_seq_show, NULL);
s = (struct seq_file *)file->private_data;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0)
xp_net_priv = PDE_DATA(file_inode(file));
#else
xp_net_priv = PROC_I(inode)->pde->data;
#endif
s->private = xp_net_priv;
return result;
}
static ssize_t xpnet_stats_proc_write(struct file *filp, const char *buf,
size_t bufsize, loff_t * off)
{
return bufsize;
}
static const struct file_operations xpnet_proc_stats_fops = {
.owner = THIS_MODULE,
.open = xpnet_stats_seq_open,
.read = seq_read,
.write = xpnet_stats_proc_write,
.llseek = seq_lseek,
.release = single_release,
};
static int xpnet_ttable_seq_show(struct seq_file *sf, void *v)
{
xp_trap_table_print(sf);
return 0;
}
static int xpnet_ttable_seq_open(struct inode *inode, struct file *file)
{
return single_open(file, xpnet_ttable_seq_show, NULL);
}
static ssize_t xpnet_ttable_proc_write(struct file *filp, const char *buf,
size_t bufsize, loff_t * off)
{
return bufsize;
}
static const struct file_operations xpnet_proc_ttable_fops = {
.owner = THIS_MODULE,
.open = xpnet_ttable_seq_open,
.read = seq_read,
.write = xpnet_ttable_proc_write,
.llseek = seq_lseek,
.release = single_release,
};
static int xpnet_debug_seq_show(struct seq_file *sf, void *v)
{
seq_printf(sf, "Debug level = (%d)\n", g_debug);
return 0;
}
static int xpnet_debug_seq_open(struct inode *inode, struct file *file)
{
return single_open(file, xpnet_debug_seq_show, NULL);
}
static ssize_t xpnet_debug_proc_write(struct file *filp, const char *buf,
size_t bufsize, loff_t * off)
{
u32 val;
fdebug("Entering %s()\n", __func__);
fdebug("Called xpnet_write(), %zu\n", bufsize);
if (bufsize != 0) {
if (1 == sscanf(buf, "%u", &val)) {
g_debug = val & XP_DBG_GLOBAL;
xp_debug_set(val & XP_DBG_FP);
}
}
return bufsize;
}
static const struct file_operations xpnet_proc_debug_fops = {
.owner = THIS_MODULE,
.open = xpnet_debug_seq_open,
.read = seq_read,
.write = xpnet_debug_proc_write,
.llseek = seq_lseek,
.release = single_release,
};
static int xpnet_netdev_seq_show(struct seq_file *sf, void *v)
{
xp_netdev_print(sf);
return 0;
}
static int xpnet_netdev_seq_open(struct inode *inode, struct file *file)
{
return single_open(file, xpnet_netdev_seq_show, NULL);
}
static ssize_t xpnet_netdev_proc_write(struct file *filp, const char *buf,
size_t bufsize, loff_t * off)
{
return bufsize;
}
static const struct file_operations xpnet_proc_netdev_fops = {
.owner = THIS_MODULE,
.open = xpnet_netdev_seq_open,
.read = seq_read,
.write = xpnet_netdev_proc_write,
.llseek = seq_lseek,
.release = single_release,
};
static int xpnet_txhdr_seq_show(struct seq_file *sf, void *v)
{
xp_netdev_tx_header_print(0, sf);
return 0;
}
static int xpnet_txhdr_seq_open(struct inode *inode, struct file *file)
{
return single_open(file, xpnet_txhdr_seq_show, NULL);
}
static ssize_t xpnet_txhdr_proc_write(struct file *filp, const char *buf,
size_t bufsize, loff_t * off)
{
return bufsize;
}
static const struct file_operations xpnet_proc_txhdr_fops = {
.owner = THIS_MODULE,
.open = xpnet_txhdr_seq_open,
.read = seq_read,
.write = xpnet_txhdr_proc_write,
.llseek = seq_lseek,
.release = single_release,
};
int xpnet_proc_create(xpnet_private_t *net_priv)
{
int count = 0;
char queue_name[25];
fdebug("Entering %s()\n", __func__);
memset(queue_name, 0, sizeof(queue_name));
snprintf(queue_name, sizeof(queue_name) - 1, "xpnet%d", net_priv->instance);
net_priv->proc_root = proc_mkdir(queue_name, NULL);;
for (count = 0; count < XPNET_NUM_QUEUES; count++) {
g_net_que_info[count].que_no = count;
g_net_que_info[count].priv = g_net_priv;
memset(queue_name, 0, sizeof(queue_name));
snprintf(queue_name, sizeof(queue_name) - 1, "queue%d", count);
net_priv->proc_que[count] = proc_create_data(queue_name, 0644,
net_priv->proc_root, &xpnet_proc_fops,
&g_net_que_info[count]);
if (NULL == net_priv->proc_que[count]) {
return -1;
}
}
net_priv->proc_stats = proc_create_data(XPNET_PROC_STATS, 0644,
net_priv->proc_root, &xpnet_proc_stats_fops,
g_net_priv);
if (NULL == net_priv->proc_stats) {
return -1;
}
net_priv->proc_ttable = proc_create(XPNET_PROC_TRAP_TABLE, 0644,
net_priv->proc_root, &xpnet_proc_ttable_fops);
if (NULL == net_priv->proc_ttable) {
return -1;
}
net_priv->proc_debug = proc_create(XPNET_PROC_DEBUG, 0644,
net_priv->proc_root, &xpnet_proc_debug_fops);
if (NULL == net_priv->proc_debug) {
return -1;
}
net_priv->proc_netdev = proc_create(XPNET_PROC_NETDEV, 0644,
net_priv->proc_root, &xpnet_proc_netdev_fops);
if (NULL == net_priv->proc_netdev) {
return -1;
}
net_priv->proc_txhdr = proc_create(XPNET_PROC_TXHDR, 0644,
net_priv->proc_root, &xpnet_proc_txhdr_fops);
if (NULL == net_priv->proc_txhdr) {
return -1;
}
return 0;
}
|
XPliant/OpenXPS
|
include/openXpsPolicer.h
|
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* All Rights Reserved.
*
* 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.
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATIONS ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*
* FILE : openXpsPolicer.h
*
* Abstract: This file defines the apis for Policer Management in OpenXPS.
************************************************************************/
/**
* \file openXpsPolicer.h
* \brief This file contains API prototypes and type definitions
* for the openXps Policer Management
* \copyright (c) 2016 Cavium Inc
*/
#ifndef _openXpsPolicer_h_
#define _openXpsPolicer_h_
#include "openXpsTypes.h"
#include "openXpsEnums.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
*\struct xpsPolicerEntry_t
*\brief Policer entry format structure
*
*/
typedef struct xpsPolicerEntry_t
{
uint32_t cir;
uint32_t pir;
uint32_t cbs;
uint32_t pbs;
uint32_t colorAware;
uint32_t dropRed;
uint32_t dropYellow;
uint32_t updateResultRed;
uint32_t updateResultYellow;
uint32_t updateResultGreen;
xpPolicingResultType polResult;
} xpsPolicerEntry_t;
/**
* \brief Enable policing for a specific port.
*
* \param [in] portIntfId Port Interface ID
* \param [in] enable Policing enable
*
* \return XP_STATUS
*/
XP_STATUS xpsPolicerEnablePortPolicing (xpsInterfaceId_t portIntfId, uint16_t enable);
/**
* \brief Add a policing entry for specific port
*
* \param [in] portIntfId Port Interface ID
* \param [in] client Advanced Counting Module (ACM) client enum
* \param [in] *pEntry Policer Entry added to hardware
*
* \return XP_STATUS
*/
XP_STATUS xpsPolicerAddPortPolicingEntry (xpsInterfaceId_t portIntfId, xpAcmClient_e client, xpsPolicerEntry_t *pEntry);
#ifdef __cplusplus
}
#endif
#endif //_openXpsPolicer_h_
|
XPliant/OpenXPS
|
include/openXpsQos.h
|
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* All Rights Reserved.
*
* 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.
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATIONS ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*
* FILE : openXpsQos.h
*
* Abstract: This file defines the apis for QoS Management in OpenXPS.
************************************************************************/
/**
* \file openXpsQos.h
* \brief This file contains API prototypes and type definitions
* for the openXps QoS Management
* \copyright (c) 2016 Cavium Inc
*/
#ifndef _openXpsQos_h_
#define _openXpsQos_h_
#include "openXpsTypes.h"
#include "openXpsEnums.h"
#ifdef __cplusplus
extern "C"
{
#endif
/*
* Q-Mapping Control APIs
*/
/**
* \brief This API returns the qmap table index and the location
* of the queue within the entry for a given input set of
* data used for q mapping
*
* This API will take the following parameters to determine the
* index of the q map table and the location of the queue within
* the entry pointed to by the index of an absolute queue number
* that corresponds to an input set
*
* This API can be used to remap an egress ports q's to an
* arbitrary set of input data. For example we can remap a tc to
* egress port mapping using this API and the ones listed below:
*
* \see xpsQosAqmGetQueueAbsoluteNumber
* \see xpsQosAqmSetQueueAtQmapIndex
*
*
* \param [in] devId Device id
* \param [in] destPort Destination Port
* \param [in] srcPort Source Port
* \param [in] mc Multicast
* \param [in] txqSelVec Txq select vector
* \param [in] tc Traffic Class
* \param [out] qmapIdx Qmap index
* \param [out] queueLoc Queue location
*
* \return XP_STATUS
*/
XP_STATUS xpsQosAqmGetQmapTableIndex(xpsDevice_t devId, xpPort_t destPort, xpPort_t srcPort, uint32_t mc, uint32_t txqSelVec, uint32_t tc, uint32_t *qmapIdx, uint32_t *queueLoc);
/**
* \brief This API will return the absolute queue number that
* corresponds to the destination port and queue
* combination
*
* This API is used to retrieve the absolute queue number that
* corresponds to a port and queue combination
*
* The absolute queue number is used in many Traffic Manager
* configurations including mapping of a port and traffic class
* to egress queue
*
* If you wish to change this mapping of a traffic class to an
* egress queue, you will need to find out the absolute queue
* number for every port in the system for the queue you wish to
* remap, then you will need to update the qmap table
* accordingly using the indicies determined by tne expected
* input set of bits
*
* \see xpwQosAqmGetQmapTableIndex
* \see xpwQosAqmSetQueueAtQmapIndex
*
*
* \param [in] devId Device id
* \param [in] devPort Device Port
* \param [in] queueNum Queue number
* \param [out] absQNum Absolute queue number
*
* \return XP_STATUS
*/
XP_STATUS xpsQosAqmGetQueueAbsoluteNumber(xpsDevice_t devId, xpPort_t devPort, uint32_t queueNum, uint32_t *absQNum);
/**
* \brief This API will update the qmap table with a new
* absolute queue number at the qmap index and location
* desired
*
* This API in conjuction with two others can be used to remap a
* traffic class to an egress queue on a per port basis. This
* API will need to be called for each Traffic Class that you
* wish to remap for every egress port on the device
*
* \see xpQosAqmGetQmapTableIndex
* \see xpQosAqmGetQueueAbsoluteNumber
*
*
* \param [in] devId Device id
* \param [in] qmapIdx Qmap index
* \param [in] queueLoc Queue location
* \param [in] absQNum Absolute queue number
*
* \return XP_STATUS
*/
XP_STATUS xpsQosAqmSetQueueAtQmapIndex(xpsDevice_t devId, uint32_t qmapIdx, uint32_t queueLoc, uint32_t absQNum);
/*
* XPS Port Ingress Qos Map
*/
/**
* \brief API to configure a traffic class for a given L2 QOS
* Profile
*
* This API will allow a user to set a Traffic Class for a
* given L2 QOS Profile and combination of PCP and DEI values
* (also known as COS)
*
* There are 8 QOS profiles for each type of QOS marking
* (L2/L3/MPLS) supported by Xpliant. Each profile provides the
* ability to configure PCP/DEI to traffic class mapping
* independently
*
*
* \param [in] devId Device id
* \param [in] profile QOS Profile
* \param [in] pcpVal PCP value
* \param [in] deiVal DEI value
* \param [in] tc Traffic Class
*
* \return XP_STATUS
*/
XP_STATUS xpsQosPortIngressSetTrafficClassForL2QosProfile(xpsDevice_t devId, xpQosMapPfl_t profile, uint32_t pcpVal, uint32_t deiVal, uint32_t tc);
/**
* \brief API to configure a traffic class for a given L3 QOS
* Profile
*
* This API will allow a user to set a Traffic Class for a
* given L3 QOS Profile and DSCP value
*
* There are 8 QOS profiles for each type of QOS marking
* (L2/L3/MPLS) supported by Xpliant. Each profile provides the
* ability to configure DSCP to traffic class mapping
* independently
*
*
* \param [in] devId Device id
* \param [in] profile QOS Profile
* \param [in] dscpVal DSCP value
* \param [in] tc Traffic class
*
* \return XP_STATUS
*/
XP_STATUS xpsQosPortIngressSetTrafficClassForL3QosProfile(xpsDevice_t devId, xpQosMapPfl_t profile, uint32_t dscpVal, uint32_t tc);
/**
* \brief API to retrieve the configured traffic class for a
* given L3 QOS Profile
*
* This API will allow a user to get a set Traffic Class for a
* given L2 QOS Profile and DSCP value
*
* There are 8 QOS Profiles for each type of QOS marking
* (L2/L3/MPLS) supported by Xpliant. Each profile provides the
* ability to configure DSCP to traffic class mapping
* independently
*
*
* \param [in] devId Device id
* \param [in] profile QOS Profile
* \param [in] dscpVal DSCP value
* \param [out] tc Traffic class
*
* \return XP_STATUS
*/
XP_STATUS xpsQosPortIngressGetTrafficClassForL3QosProfile(xpsDevice_t devId, xpQosMapPfl_t profile, uint32_t dscpVal, uint32_t *tc);
/**
* \brief API to configure a drop precedence for a given L2 QOS
* Profile
*
* This API will allow a user to set a Drop Precedence for a
* given L2 QOS Profile and combination of PCP and DEI values
* (also known as COS)
*
* There are 8 QOS profiles for each type of QOS marking
* (L2/L3/MPLS) supported by Xpliant. Each profile provides the
* ability to configure PCP/DEI to drop precedence mapping
* independently
*
*
* \param [in] devId Device id
* \param [in] profile QOS Profile
* \param [in] pcpVal PCP value
* \param [in] deiVal DEI value
* \param [in] dp Drop Precedence
*
* \return XP_STATUS
*/
XP_STATUS xpsQosPortIngressSetDropPrecedenceForL2QosProfile(xpsDevice_t devId, xpQosMapPfl_t profile, uint32_t pcpVal, uint32_t deiVal, uint32_t dp);
/**
* \brief API to configure a drop precedence for a given L3 QOS
* Profile
*
* This API will allow a user to set a Drop Precedence for a
* given L3 QOS Profile and DSCP value
*
* There are 8 QOS profiles for each type of QOS marking
* (L2/L3/MPLS) supported by Xpliant. Each profile provides the
* ability to configure DSCP to drop precedence mapping
* independently
*
*
* \param [in] devId Device id
* \param [in] profile QOS Profile
* \param [in] dscpVal DSCP value
* \param [in] dp Drop Precedence
*
* \return XP_STATUS
*/
XP_STATUS xpsQosPortIngressSetDropPrecedenceForL3QosProfile(xpsDevice_t devId, xpQosMapPfl_t profile, uint32_t dscpVal, uint32_t dp);
/**
* \brief API to retrieve the configured drop precedence for a
* given L3 QOS Profile
*
* This API will allow a user to get a Drop Precedence for a
* given L3 QOS Profile and DSCP value
*
* There are 8 QOS Profiles for each type of QOS marking
* (L2/L3/MPLS) supported by Xpliant. Each profile provides the
* ability to configure DSCP to drop precedence mapping
* independently
*
*
* \param [in] devId Device id
* \param [in] profile QOS Profile
* \param [in] dscpVal DSCP value
* \param [out] dp Drop Precedence
*
* \return XP_STATUS
*/
XP_STATUS xpsQosPortIngressGetDropPrecedenceForL3QosProfile(xpsDevice_t devId, xpQosMapPfl_t profile, uint32_t dscpVal, uint32_t *dp);
/**
* \brief API to remap QOS Priority values based on an ingress
* PCP/DEI received from a packet for a profile
*
* This API will allow a user to remap all QOS priority values
* based off the values retrieved from a .1q tagged packet or
* from the port default PCP/DEI values
*
* There are 8 QOS Profiles for each type of QOS marking
* (L2/L3/MPLS) supported by Xpliant. Each profile provides the
* ability to remap QOS priorities independently
*
*
* \param [in] devId Device id
* \param [in] profile QOS Profile
* \param [in] pcpVal PCP value
* \param [in] deiVal DEI value
* \param [in] remapPcpVal Remap PCP value
* \param [in] remapDeiVal Remap DEI value
* \param [in] remapDscpVal Remap DSCP value
* \param [in] remapExpVal Remap EXP value
*
* \return XP_STATUS
*/
XP_STATUS xpsQosPortIngressRemapPriorityForL2QosProfile(xpsDevice_t devId, xpQosMapPfl_t profile,
uint32_t pcpVal, uint32_t deiVal,
uint32_t remapPcpVal, uint32_t remapDeiVal,
uint32_t remapDscpVal, uint32_t remapExpVal);
/**
* \brief API to remap QOS Priority values based on an ingress
* DSCP received from a packet for a profile
*
* This API will allow a user to remap all QOS priority values
* based off the value retrieved from an IP packet or from the
* port default DSCP value
*
* There are 8 QOS Profiles for each type of QOS marking
* (L2/L3/MPLS) supported by Xpliant. Each profile provides the
* ability to remap QOS Priorities independently
*
*
* \param [in] devId Device id
* \param [in] profile QOS Profile
* \param [in] dscpVal DSCP value
* \param [in] remapPcpVal Remap PCP value
* \param [in] remapDeiVal Remap DEI value
* \param [in] remapDscpVal Remap DSCP value
* \param [in] remapExpVal Remap EXP value
*
* \return XP_STATUS
*/
XP_STATUS xpsQosPortIngressRemapPriorityForL3QosProfile(xpsDevice_t devId, xpQosMapPfl_t profile, uint32_t dscpVal,
uint32_t remapPcpVal, uint32_t remapDeiVal, uint32_t remapDscpVal, uint32_t remapExpVal);
/**
* \brief API to set the Port Default DSCP value
*
* This API will set the port default DSCP value for all
* incoming IP packets
*
*
* \param [in] devId Device id
* \param [in] devPort Device Port
* \param [in] dscpVal DSCP value
*
* \return XP_STATUS
*/
XP_STATUS xpsQosPortIngressSetPortDefaultL3QosPriority(xpsDevice_t devId, xpPort_t devPort, uint32_t dscpVal);
/**
* \brief API to set the Port Default Traffic Class
*
* This API will set the port default Traffic Class for all
* incoming packets
*
*
* \param [in] devId Device id
* \param [in] devPort Device Port
* \param [in] tc Traffic Class
*
* \return XP_STATUS
*/
XP_STATUS xpsQosPortIngressSetPortDefaultTrafficClass(xpsDevice_t devId, xpPort_t devPort, uint32_t tc);
/**
* \brief API to set the Port Default Drop Precedence
*
* This API will set the port default Drop Precedence for all
* incoming packets
*
*
* \param [in] devId Device id
* \param [in] devPort Device Port
* \param [in] dp Drop Precedence
*
* \return XP_STATUS
*/
XP_STATUS xpsQosPortIngressSetPortDefaultDropPrecedence(xpsDevice_t devId, xpPort_t devPort, uint32_t dp);
/**
* \brief API to set the L2 QOS profile for a port
*
* This API will set a L2 QOS profile for a port as well as
* enable or disable its application to all incoming packets
*
* There is a precedence that is followed for the QOS Remarking
* scheme in Xpliant:
* - MPLS
* - IP
* - L2
* - Port default
*
* If MPLS Profile is enabled, all QOS priorities are taken from
* the MPLS Profile entry that was hit
*
* This API enables the L2 QOS Profile application. If other,
* higher in precedence, profiles are enabled, they take
* precedence
*
* \param [in] devId Device id
* \param [in] devPort Device Port
* \param [in] profile QOS Profile
* \param [in] enable Enable/Disable
*
* \return XP_STATUS
*/
XP_STATUS xpsQosPortIngressSetL2QosProfileForPort(xpsDevice_t devId, xpPort_t devPort, xpQosMapPfl_t profile, uint32_t enable);
/**
* \brief API to set the L3 QOS profile for a port
*
* This API will set a L3 QOS profile for a port as well as
* enable or disable its application to all incoming packets
*
* There is a precedence that is followed for the QOS Remarking
* scheme in Xpliant:
* - MPLS
* - IP
* - L2
* - Port default
*
* If MPLS Profile is enabled, all QOS priorities are taken from
* the MPLS Profile entry that was hit
*
* This API enables the L3 QOS Profile application. If other,
* higher in precedence, profiles are enabled, they take
* precedence
*
* \param [in] devId Device id
* \param [in] devPort Device Port
* \param [in] profile QOS Profile
* \param [in] enable Enable/Disable
*
* \return XP_STATUS
*/
XP_STATUS xpsQosPortIngressSetL3QosProfileForPort(xpsDevice_t devId, xpPort_t devPort, xpQosMapPfl_t profile, uint32_t enable);
/**
* \brief API to enable the L2 QOS Trust profile
*
* This profile by default trusts only the L2 Priorities and
* keeps the incoming PCP/DEI. Traffic Class and Drop Precedence
* are not set by this API, they will need to be set separately
*
*
* \param [in] devId Device id
* \param [in] devPort Device Port
*
* \return XP_STATUS
*/
XP_STATUS xpsQosPortIngressSetTrustL2ForPort(xpsDevice_t devId, xpPort_t devPort);
/**
* \brief API to enable the L3 QOS Trust profile
*
* This profile by default trusts only the L3 Priorities and
* keeps the incoming DSCP. Traffic Class and Drop Precedence
* are not set by this API, they will need to be set separately
*
*
* \param [in] devId Device id
* \param [in] devPort Device Port
*
* \return XP_STATUS
*/
XP_STATUS xpsQosPortIngressSetTrustL3ForPort(xpsDevice_t devId, xpPort_t devPort);
/**
* \brief This method enables DWRR scheduling for a particular port.
*
* \param [in] devId Device id
* \param [in] devPort Device Port
* \param [in] queueNum Queue Number
* \param [in] enable Enable/Disable
*
* \return XP_STATUS
*/
XP_STATUS xpsQosSetQueueSchedulerDWRR(xpsDevice_t devId, xpsPort_t devPort, uint32_t queueNum, uint32_t enable);
/**
* \brief This method sets the DWRR weights for a particular port.
*
* \param [in] devId Device id
* \param [in] devPort Device Port
* \param [in] queueNum Queue Number
* \param [in] weight Weight
*
* \return XP_STATUS
*/
XP_STATUS xpsQosSetQueueSchedulerDWRRWeight(xpsDevice_t devId, xpsPort_t devPort, uint32_t queueNum, uint32_t weight);
/**
* \brief This method enables Strict Priority scheduling for a particular port.
*
* \param [in] devId Device id
* \param [in] devPort Device Port
* \param [in] queueNum Queue Number
* \param [in] enable Enable/Disable
*
* \return XP_STATUS
*/
XP_STATUS xpsQosSetQueueSchedulerSP(xpsDevice_t devId, xpsPort_t devPort, uint32_t queueNum, uint32_t enable);
/**
* \brief This method sets SP priority for a particular port.
*
* \param [in] devId Device id
* \param [in] devPort Device Port
* \param [in] queueNum Queue Number
* \param [in] priority Priority
*
* \return XP_STATUS
*/
XP_STATUS xpsQosSetQueueSchedulerSPPriority(xpsDevice_t devId, xpsPort_t devPort, uint32_t queueNum, uint32_t priority);
/**
* \brief This method sets the Priority Flow Control priority for a specific port and queue.
*
* \param [in] devId Device id
* \param [in] portNum Port number
* \param [in] queueNum Queue number
* \param [in] prio Priority
*
* \return XP_STATUS
*/
XP_STATUS xpsQosFcSetPfcPriority(xpsDevice_t devId, uint32_t portNum, uint32_t queueNum, uint8_t prio);
/**
* \brief This method configures shaping for a specific port on a device
*
* This API is used only to configure a shape and does not
* explicitly enable shaping.
*
* \see xpsQosShaperSetPortShaperEnable()
*
*
* \param [in] devId Device id
* \param [in] devPort Device Port
* \param [in] rateKbps Rate
* \param [in] maxBurstByteSize Maximum burst byte size
*
* \return XP_STATUS
*/
XP_STATUS xpsQosShaperConfigurePortShaper(xpsDevice_t devId, xpPort_t devPort, uint64_t rateKbps, uint32_t maxBurstByteSize);
/**
* \brief This method enables or disables shaping for a specific port on a device
*
* \param [in] devId Device id
* \param [in] devPort Device Port
* \param [in] enableShaper Enable/Disable
*
* \return XP_STATUS
*/
XP_STATUS xpsQosShaperSetPortShaperEnable(xpsDevice_t devId, xpPort_t devPort, uint32_t enableShaper);
/*
* XPS Queue counter section
*/
/**
* \brief API to read the Forward counter for a Queue associated
* with a given port
*
* Wrap indicates if the counter has wrapped around since the
* last read
*
* This counter is a Clear-On-Read counter, which uses packet
* resolution
*
* \param [in] devId
* \param [in] port
* \param [in] queue
* \param [out] count
* \param [out] wrap
*
* \return XP_STATUS
*/
XP_STATUS xpsQosQcGetQueueFwdPacketCountForPort(xpsDevice_t devId, xpPort_t port, uint32_t queue, uint64_t *count, uint32_t *wrap);
/**
* \brief API to read the Drop counter for a Queue associated
* with a given port
*
* Wrap indicates if the counter has wrapped around since the
* last read
*
* This counter is a Clear-On-Read counter, which uses packet
* resolution
*
* \param [in] devId
* \param [in] port
* \param [in] queue
* \param [out] count
* \param [out] wrap
*
* \return XP_STATUS
*/
XP_STATUS xpsQosQcGetQueueDropPacketCountForPort(xpsDevice_t devId, xpPort_t port, uint32_t queue, uint64_t *count, uint32_t *wrap);
/**
* \brief API to read the Forward Length counter for a Queue
* associated with a given port
*
* Wrap indicates if the counter has wrapped around since the
* last read
*
* This counter is a Clear-On-Read counter, which uses byte
* resolution
*
* \param [in] devId
* \param [in] port
* \param [in] queue
* \param [out] count
* \param [out] wrap
*
* \return XP_STATUS
*/
XP_STATUS xpsQosQcGetQueueFwdByteCountForPort(xpsDevice_t devId, xpPort_t port, uint32_t queue, uint64_t *count, uint32_t *wrap);
#ifdef __cplusplus
}
#endif
#endif //_openXpsQos_h_
|
XPliant/OpenXPS
|
include/openXpsAcm.h
|
//
// openXpsAcm.h
//
/************************************************************************/
/* Copyright (c) [2011-2015] Cavium, Inc. All rights reserved. */
/* Unpublished - rights reserved under the Copyright Laws of the */
/* United States. Use, duplication, or disclosure by the */
/* Government is subject to restrictions as set forth in */
/* subparagraph (c)(1)(ii) of the Rights in Technical Data and */
/* Computer Software clause at 252.227-7013. */
/************************************************************************/
/**
* \file openXpsAcm.h
* \brief This file contains API prototypes and type definitions
* for the XPS ACM Manager
*/
#ifndef _openXpsAcm_h_
#define _openXpsAcm_h_
#include "openXpsTypes.h"
#include "openXpsEnums.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \public
* \brief Updates a field in the entry.
*
* This gets the counter value from the specified index in the
* device
*
* \param [in] devId
* \param [in] countIndex
* \param [out] * nPkts
* \param [out] * nBytes
*
* \return XP_STATUS
*/
XP_STATUS xpsAcmGetCounterValue(xpsDevice_t devId, xpAcmClient_e client, uint32_t countIndex, uint64_t *nPkts, uint64_t *nBytes);
#ifdef __cplusplus
}
#endif
#endif //_xpsAcm_h_
|
XPliant/OpenXPS
|
include/openXpsL3.h
|
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* All Rights Reserved.
*
* 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.
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATIONS ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*
* FILE : openXpsL3.h
*
* Abstract: This file defines the apis for L3 Management in OpenXPS.
************************************************************************/
/**
* \file openXpsL3.h
* \brief This file contains API prototypes and type definitions
* for the openXps L3 Management
* \copyright (c) 2016 Cavium Inc
*/
#ifndef _openXpsL3_h_
#define _openXpsL3_h_
#include "openXpsTypes.h"
#include "openXpsEnums.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \struct xpsL3NextHopData_t
* \brief This structure defines the L3
* Next-Hop data
*/
typedef struct xpsL3NextHopData_t
{
xpsInterfaceId_t l3InterfaceId;
macAddr_t macDa;
xpsInterfaceId_t egressIntfId;
}xpsL3NextHopData_t;
/**
* \struct xpsL3NextHopEntry_t
* \brief This structure defines the L3
* Next-Hop entry
*/
typedef struct xpsL3NextHopEntry_t
{
xpPktCmd_e pktCmd; ///< Packet forwarding processing command
uint32_t serviceInstId; ///< A Service Instance ID to represent VNI/TNI/ISID for tunnelled packets
uint32_t vpnLabel; ///< VPN Label
uint32_t propTTL; ///< TTL
xpsL3NextHopData_t nextHop; ///< Next-Hop Data
uint32_t reasonCode; ///< Reason Code
}xpsL3NextHopEntry_t;
/**
* \struct xpsL3HostEntry_t
* \brief This structure defines the L3
* host entry
*/
typedef struct xpsL3HostEntry_t
{
uint32_t vrfId; ///< VRF
xpIpPrefixType_t type; ///< IP Prefix type
ipv4Addr_t ipv4Addr; ///< IPv4
ipv6Addr_t ipv6Addr; ///< IPv6
xpsL3NextHopEntry_t nhEntry; ///< Next-Hop Entry
}xpsL3HostEntry_t;
/**
* \struct xpsL3RouteEntry_t
* \brief This structure defines the L3
* routing entry
*/
typedef struct xpsL3RouteEntry_t
{
uint32_t vrfId; ///< VRF
xpIpPrefixType_t type; ///< IP Prefix type
ipv4Addr_t ipv4Addr; ///< IPv4
ipv6Addr_t ipv6Addr; ///< IPv6
uint32_t ipMaskLen; ///< IP Mask
uint32_t nhEcmpSize; ///< Next-Hop size
uint32_t nhId; ///< Next-Hop ID
}xpsL3RouteEntry_t;
/**
* \brief This method Add Global Router Mac.
*
* \param [in] devId Device ID
* \param [in] mac Mac Address
*
* \return XP_STATUS
*/
XP_STATUS xpsL3AddIngressRouterMac(xpsDevice_t devId, macAddr_t mac);
/**
* \brief This method Add Global Router Mac for a given VLAN.
*
* \param [in] devId Device ID
* \param [in] vlan VLAN-ID
* \param [in] mac Mac Address
*
* \return XP_STATUS
*/
XP_STATUS xpsL3AddIngressRouterVlanMac(xpsDevice_t devId, xpsVlan_t vlan, macAddr_t mac);
/**
* \brief Set constant 40 MSB for a device Router Egress MAC.
*
* \param [in] devId Device ID
* \param [in] macHi 40 MSB bits of the Egress Router MAC
*
* \return XP_STATUS
*/
XP_STATUS xpsL3SetEgressRouterMacMSbs(xpsDevice_t devId, macAddrHigh_t macHi);
/**
* \brief Set constant 8 LSB for a device Router Egress MAC per L3 Interface.
*
* \param [in] devId Device ID
* \param [in] l3IntfId Layer 3 Interface ID
* \param [in] macSa Mac Source Address
*
* \return XP_STATUS
*/
XP_STATUS xpsL3SetIntfEgressRouterMacLSB(xpsDevice_t devId, xpsInterfaceId_t l3IntfId, macAddrLow_t macSa);
/**
* \brief Configures the VRF index for routing
* interface created on a specific L3 Interface.
*
* \param [in] devId
* \param [in] l3IntfId
* \param [in] vrfId
*
* \return XP_STATUS
*/
XP_STATUS xpsL3SetIntfVrf(xpsDevice_t devId, xpsInterfaceId_t l3IntfId, uint32_t vrfId);
/**
* \brief Enable IPv4 unicast routing lookups
* for packets ingressing on a specific L3 Interface.
*
* \param [in] devId
* \param [in] l3IntfId
* \param [in] enable
*
* \return XP_STATUS
*/
XP_STATUS xpsL3SetIntfIpv4UcRoutingEn(xpsDevice_t devId, xpsInterfaceId_t l3IntfId, uint32_t enable);
/**
* \brief Enable IPv6 unicast routing lookups
* for packets ingressing on a specific L3 Interface.
*
* \param [in] devId
* \param [in] l3IntfId
* \param [in] enable
*
* \return XP_STATUS
*/
XP_STATUS xpsL3SetIntfIpv6UcRoutingEn(xpsDevice_t devId, xpsInterfaceId_t l3IntfId, uint32_t enable);
/**
* \brief Add a L3 Host Entry
*
* \param [in] devId Device Id of device.
* \param [in] *pL3HostEntry Pointer to L3 Host entry structure.
* \param [out] *entryHashIndex Index at which the Host entry is written to hardware.
* \param [out] *entryRehashIndex Index of entry which has been rehashed.
*
* \return XP_STATUS
*/
XP_STATUS xpsL3AddIpHostEntry(xpsDevice_t devId, xpsL3HostEntry_t *pL3HostEntry, uint32_t *entryHashIndex, uint32_t *entryRehashIndex);
/**
* \brief This method is used for classifying IP host (myIP)
* control packets and assigning a unique reason code for
* control plane policing (CoPP). It internally adds a L3
* host entry. Reason Code is overloaded on the egressVif
* in the host entry.
*
* \param [in] devId Device Id of device.
* \param [in] *pL3HostEntry Pointer to L3 Host entry structure.
* \param [out] *entryHashIndex Index at which the Host entry is written to hardware.
* \param [out] *entryRehashIndex Index of entry which has been rehashed.
*
* \return XP_STATUS
*/
XP_STATUS xpsL3AddIpHostControlEntry(xpsDevice_t devId, xpsL3HostEntry_t *pL3HostEntry, uint32_t *entryHashIndex, uint32_t *entryRehashIndex);
/**
* \brief Update a L3 Route Entry
*
* \param [in] devId Device Id of device.
* \param [in] *pL3RouteEntry Pointer to L3 Route entry structure.
*
* \return XP_STATUS
*/
XP_STATUS xpsL3UpdateIpRouteEntry(xpsDevice_t devId, xpsL3RouteEntry_t *pL3RouteEntry);
/**
* \brief Remove the L3 Host Entry at the specific index
*
* \param [in] devId Device Id of device.
* \param [in] index Index of the Host entry to be removed from hardware.
* \param [in] pL3PrefixType Prefix Type
*
* \return XP_STATUS
*/
XP_STATUS xpsL3RemoveIpHostEntryByIndex(xpsDevice_t devId, uint32_t index, xpIpPrefixType_t pL3PrefixType);
/**
* \brief Add L3 Route Entry
*
* \param [in] devId Device Id of device.
* \param [in] *pL3RouteEntry Pointer to L3 Route entry structure.
* \param [out] *prfxBucketIdx Index at which the L3 Route entry is written to hardware.
*
* \return XP_STATUS
*/
XP_STATUS xpsL3AddIpRouteEntry(xpsDevice_t devId, xpsL3RouteEntry_t *pL3RouteEntry, uint32_t *prfxBucketIdx);
/**
* \brief Remove the L3 Route Entry at the specific index
*
* \param [in] devId Device Id of device.
* \param [in] *pL3RouteEntry Pointer to L3 Route entry to be removed from hardware.
*
* \return XP_STATUS
*/
XP_STATUS xpsL3RemoveIpRouteEntry(xpsDevice_t devId, xpsL3RouteEntry_t *pL3RouteEntry);
/**
* \brief Allocate Next-Hop for given ECMP Size
*
* \param [out] nhId Next-Hop ID
* \param [in] nhEcmpSize ECMP Group size
*
* \return XP_STATUS
*/
XP_STATUS xpsL3CreateRouteNextHop(uint32_t nhEcmpSize, uint32_t *nhId);
/**
* \brief Set the NextHop Entry for a specific Next-Hop ID
*
* \param [in] devId Device Id of device.
* \param [in] nhId Next-Hop Id of device.
* \param [in] *pL3NextHopEntry Pointer to L3 Next-Hop entry structure.
*
* \return XP_STATUS
*/
XP_STATUS xpsL3SetRouteNextHop(xpsDevice_t devId, uint32_t nhId, xpsL3NextHopEntry_t *pL3NextHopEntry);
/**
* \brief Clear the NextHop Entry for given Next-Hop ID in a device.
*
* \param [in] devId Device Id of device.
* \param [in] nhId Next-Hop Id of device.
*
* \return XP_STATUS
*/
XP_STATUS xpsL3ClearRouteNextHop(xpsDevice_t devId, uint32_t nhId);
/**
* \brief Free the allocated Next-Hop
*
* \param [in] nhId Next-Hop Id of device
*
* \return XP_STATUS
*/
XP_STATUS xpsL3DestroyRouteNextHop(uint32_t nhEcmpSize, uint32_t nhId);
/**
* \brief Create L3 Interface over a specific VLAN.
*
* \param [in] vlanId VLAN-ID
* \param [out] l3IntfId Pointer to the allocated L3 Interface ID
*
* \return XP_STATUS
*/
XP_STATUS xpsL3CreateVlanIntf(xpsVlan_t vlanId, xpsInterfaceId_t *l3IntfId);
/**
* \brief Removes L3 Interface from a specific VLAN.
*
* \param [in] vlanId
* \param [in] l3IntfId L3 Interface ID
*
* \return XP_STATUS
*/
XP_STATUS xpsL3DestroyVlanIntf(xpsVlan_t vlanId, xpsInterfaceId_t l3IntfId);
/**
* \brief Set hashable fields for a device
* \deprecated use \ref xpsGlobalSwitchControlSetHashFields
* \param [in] deviceId Device id
* \param [in] fields array of fields
* \param [in] size
*
* \return XP_STATUS
*/
XP_STATUS xpsL3SetHashFields(xpsDevice_t deviceId, xpHashField* fields, size_t size);
/**
* \brief This method enables/disables router ACL on the L3 Interface
*
* \param [in] devId Device Id of device.
* \param [in] l3IfId L3 Interface ID
* \param [in] enable
* \return int
*/
XP_STATUS xpsL3SetRouterAclEnable(xpsDevice_t devId, xpsInterfaceId_t l3IfId, uint8_t enable);
/**
* \brief This method sets router ACL ID on the L3 Interface
*
* \param [in] devId Device Id of device.
* \param [in] l3IfId L3 Interface ID
* \param [in] aclId
* \return int
*/
XP_STATUS xpsL3SetRouterAclId(xpsDevice_t devId, xpsInterfaceId_t l3IfId, uint32_t aclId);
/**
* \brief This method Creates an L3 sub interface.
*
* \param [out] *l3IntfId L3 Interface ID
*
* \return XP_STATUS
*/
XP_STATUS xpsL3CreateSubIntf(xpsInterfaceId_t *l3IntfId);
/**
* \brief This method destroys L3 sub interface.
*
* \param [in] l3IntfId L3 Interface ID
*
* \return XP_STATUS
*/
XP_STATUS xpsL3DestroySubIntf(xpsInterfaceId_t l3IntfId);
/**
* \brief This method binds L3 sub interface with the port interface
* over which it is created.
*
* \param [in] portIntfId Port Interface ID
* \param [in] l3IntfId L3 Interface ID
* \param [in] encapId VLAN-ID
*
* \return XP_STATUS
*/
XP_STATUS xpsL3BindSubIntf (xpsInterfaceId_t portIntfId, xpsInterfaceId_t l3IntfId, xpsVlan_t encapId);
/**
* \brief This method detaches L3 sub interface from the port interface
* over which it is created.
*
* \param [in] portIntfId Port Interface ID
* \param [in] l3IntfId L3 Interface ID
* \param [in] encapId Vlan-ID
*
* \return XP_STATUS
*/
XP_STATUS xpsL3UnBindSubIntf (xpsInterfaceId_t portIntfId, xpsInterfaceId_t l3IntfId, xpsVlan_t encapId);
/**
* \brief This method Initializes L3 sub interface.
*
* \param [in] devId Device Id of device.
* \param [in] l3IntfId L3 Interface ID
*
* \return XP_STATUS
*/
XP_STATUS xpsL3InitSubIntf (xpsDevice_t devId, xpsInterfaceId_t l3IntfId);
/**
* \brief This method De-Initializes L3 sub interface.
*
* \param [in] devId Device Id of device.
* \param [in] l3IntfId L3 Interface ID
*
* \return XP_STATUS
*/
XP_STATUS xpsL3DeInitSubIntf (xpsDevice_t devId, xpsInterfaceId_t l3IntfId);
/**
* \brief This method Creates L3 Interface Over Port.
*
* \param [in] tnnlIntfId
* \param [out] l3IntfId
*
* \return XP_STATUS
*/
XP_STATUS xpsL3CreatePortIntf(xpsInterfaceId_t *l3IntfId);
/**
* \brief This method Removes L3 Interface Over Port.
*
* \param [out] l3IntfId
*
* \return XP_STATUS
*/
XP_STATUS xpsL3DestroyPortIntf(xpsInterfaceId_t l3IntfId);
/**
* \brief This method Initializes L3 Interface Over Port.
*
* \param [in] portIntfId
* \param [in] l3IntfId
*
* \return XP_STATUS
*/
XP_STATUS xpsL3BindPortIntf(xpsInterfaceId_t portIntfId, xpsInterfaceId_t l3IntfId);
/**
* \brief This method De-Initializes L3 Interface Over Port.
*
* \param [in] portIntfId
*
* \return XP_STATUS
*/
XP_STATUS xpsL3UnBindPortIntf(xpsInterfaceId_t portIntfId);
/**
* \brief This method Initializes L3 Interface Over Port.
*
* \param [in] devId
* \param [in] l3IntfId
*
* \return XP_STATUS
*/
XP_STATUS xpsL3InitPortIntf(xpsDevice_t devId, xpsInterfaceId_t l3IntfId);
/**
* \brief This method De-Initializes L3 Interface Over Port.
*
* \param [in] devId
* \param [in] l3IntfId
*
* \return XP_STATUS
*/
XP_STATUS xpsL3DeInitPortIntf(xpsDevice_t devId, xpsInterfaceId_t l3IntfId);
#ifdef __cplusplus
}
#endif
#endif //_openXpsL3_h_
|
XPliant/OpenXPS
|
include/openXpsIacl.h
|
//
// openXpsIacl.h
//
/************************************************************************/
/* Copyright (c) [2011-2015] Cavium, Inc. All rights reservered. Confidential. */
/* Unpublished - rights reserved under the Copyright Laws of the */
/* United States. Use, duplication, or disclosure by the */
/* Government is subject to restrictions as set forth in */
/* subparagraph (c)(1)(ii) of the Rights in Technical Data and */
/* Computer Software clause at 252.227-7013. */
/************************************************************************/
/**
* \file openXpsIacl.h
* \brief This file contains API prototypes and type definitions
* for the XPS Ingress ACL Manager
*/
#ifndef _OPENXPSIACL_H_
#define _OPENXPSIACL_H_
#include "openXpsEnums.h"
#include "openXpsTypes.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef xpIaclData_t xpsIaclData_t;
typedef xpIaclKeyType xpsIaclKeyType_e;
typedef xpIaclkeyFieldList_t xpsIaclkeyFieldList_t;
typedef xpIaclKeyFieldId_t xpsIaclKeyFieldId_t;
#define XP_MAX_NUM_FLDS 18
/**
* \brief This will allow user to create tables based on user defined table
* profile. Profile will have info about acl type, keySize and number
* of Db's required corresponding to a acl type (XP_IACL0, XP_IACL1 and XP_IACL2)
* In table profile user can mention number of tables he wants to create. Number
* of ACL entries for a Specific ACL type in the TCAM will be determined by
* number of Dbs and the keySize assigned for that ACL type.
*
* \param [in] devId
* \param [in] tableProfile Its structure with info about number of tcam dbs and keysize
* for each type of ingress ACL tables(XP_IACL0, XP_IACL1 and
* XP_IACL2). Key Size possible values are(WIDTH_64, WIDTH_128,
* WIDTH_192, WIDTH_384).
*
* \return XP_STATUS
*/
XP_STATUS xpsIaclCreateTable(xpsDevice_t devId, xpIaclTableProfile_t tableProfile);
/**
* \brief This will allow the user to delete tables created previously based on the table
* profile specific to a acl type.It will free the db's allocated for the aclType.
*
*
* \param [in] devId
* \param [in] iaclType It can be of port,bridge or router aclType.
* Possible Values(XP_IACL0, XP_IACL1 and XP_IACL2).
*
* \return XP_STATUS
*/
XP_STATUS xpsIaclDeleteTable(xpsDevice_t devId, xpIaclType_e iaclType);
/**
* @brief this method provides user a flexibility to define port Iacl keyformat, wherein a definitive set of fields
* can be selected by user to be part of the key .This also enables the SW to determine the keySize based on
* user defined format.Based on the keySize number of possible ACL entries in the TCAM dB can also be determined.
* The user defined key format size should always be equal or less than the keySize provided for port aclType
* during xpsIaclCreateTable API call.Note:-There can be only one key format defined for each type
* of ACL type.
*
* \param [in] devId
* \param [in] keyType Possible values are XP_IACL_V4_TYPE or XP_IACL_V4_TYPE.
* \param [in] *fldData Its pointer to a ACL key structure which consists information about key
* Fields list,keyType,validity bit(0-valid,1-invalid) and number of fields in the key.The key field List
* consists of various flds which is to be filled based on the keyType.Possible values for flds are values
* in the following enums xpIaclV4KeyFlds and xpIaclV6KeyFlds.
*
* \return XP_STATUS
*/
XP_STATUS xpsIaclDefinePaclKey(xpsDevice_t devId, xpsIaclKeyType_e keyType, xpsIaclkeyFieldList_t *fldData);
/**
* \brief this method provides user a flexibility to define bridge Iacl keyformat, wherein a definitive set of fields
* can be selected by user to be part of the key .This also enables the SW to determine the keySize based on
* user defined format.Based on the keySize number of possible ACL entries in the TCAM dB can also be determined.
* The user defined key format size should always be equal or less than the keySize provided for bridge aclType
* during xpsIaclCreateTable API call.Note:-There can be only one key format defined for each type
* of ACL type.
*
* \param [in] xpsDevice_t devId
* \param [in] keyType Possible values are XP_IACL_V4_TYPE or XP_IACL_V4_TYPE.
* \param [in] *fldData Its pointer to a IACL key structure which consists information about key
* Fields list,keyType,validity bit(0-valid,1-invalid) and number of fields in the key.The key field List
* consists of various flds which is to be filled based on the keyType.Possible values for flds are values
* in the following enums xpIaclV4KeyFlds and xpIaclV6KeyFlds.
*
* \return XP_STATUS
*/
XP_STATUS xpsIaclDefineBaclKey(xpsDevice_t devId, xpsIaclKeyType_e keyType, xpsIaclkeyFieldList_t *fldData);
/**
* \brief this method provides user a flexibility to define router Iacl keyformat, wherein a definitive set of fields
* can be selected by user to be part of the key .This also enables the SW to determine the keySize based on
* user defined format.Based on the keySize number of possible ACL entries in the TCAM dB can also be determined.
* The user defined key format size should always be equal or less than the keySize provided for router aclType
* during xpsIaclCreateTable API call.Note:-There can be only one key format defined for each type
* of ACL type.
*
* \param [in] devId
* \param [in] keyType Possible values are XP_IACL_V4_TYPE or XP_IACL_V4_TYPE.
* \param [in] *fldData Its pointer to a IACL key structure which consists information about key
* Fields list,keyType,validity bit(0-valid,1-invalid) and number of fields in the key.The key field List
* consists of various flds which is to be filled based on the keyType.Possible values for flds are values
* in the following enums xpIaclV4KeyFlds and xpIaclV6KeyFlds.
*
* \return XP_STATUS
*/
XP_STATUS xpsIaclDefineRaclKey(xpsDevice_t devId, xpsIaclKeyType_e keyType, xpsIaclkeyFieldList_t *fldData);
//Writing the IACL Key:
/**
* \brief write Port IACL key(rule data)in the TCAM at user provided camIndex.User must have defined the key format once
* prior, using API xpsIaclDefinePaclKey.
*
*
* \param [in] devId
* \param [in] camIndex Its index at which the IACL key is written on the HW.User should manage cam index.
* \param [in] *fldData Its pointer to a IACL key structure which consists information about key
* Fields list,keyType,validity bit(0-valid,1-invalid) and number of fields in the key.The key field List
* consists of various flds which is to be filled based on the keyType.Possible values for flds are values
* in the following enums xpIaclV4KeyFlds and xpIaclV6KeyFlds.Along with each key fields the value and mask
* should be provided which is to be programed on the TCAM.
*
* \return XP_STATUS
*/
XP_STATUS xpsIaclWritePaclKey(xpsDevice_t devId, uint32_t camIndex, xpsIaclkeyFieldList_t *fldData);
/**
* \brief write Bridge IACL key(rule data)in the TCAM at user provided camIndex.User must have defined key format once
* prior, using API xpsIaclDefineBaclKey.
*
*
* \param [in] devId
* \param [in] camIndex Its index at which the IACL key is written on the HW.User should manage cam index.
* \param [in] *fldData Its pointer to a IACL key structure which consists information about key
* Fields list,keyType,validity bit(0-valid,1-invalid) and number of fields in the key.The key field List
* consists of various flds which is to be filled based on the keyType.Possible values for flds are values
* in the following enums xpIaclV4KeyFlds and xpIaclV6KeyFlds.Along with each key fields the value and mask
* should be provided which is to be programed on the TCAM.
*
* \return XP_STATUS
*/
XP_STATUS xpsIaclWriteBaclKey(xpsDevice_t devId, uint32_t camIndex, xpsIaclkeyFieldList_t *fldData);
/**
* \brief write RouterInf IACL key(rule data)inthe TCAM at user provided camIndex.User must have defined key format once
* prior, using API xpsIaclDefineRaclKey.
*
*
* \param [in] devId
* \param [in] camIndex Its index at which the IACL key is written on the HW.User should manage cam index.
* \param [in] *fldData Its pointer to a IACL key structure which consists information about key
* Fields list,keyType,validity bit(0-valid,1-invalid) and number of fields in the key.The key field List
* consists of various flds which is to be filled based on the keyType.Possible values for flds are values
* in the following enums xpIaclV4KeyFlds and xpIaclV6KeyFlds.Along with each key fields the value and mask
* should be provided which is to be programed on the TCAM.
*
* \return XP_STATUS
*/
XP_STATUS xpsIaclWriteRaclKey(xpsDevice_t devId, uint32_t camIndex, xpsIaclkeyFieldList_t *fldData);
//Writing the IACL Data:
/**
* \brief Write the IACL action data for port
*
*
* \param [in] devId
* \param [in] camIndex Its index at which the IACL action data is written on the HW.User should manage cam index.
* \param [in] *iaclData Its pointer to the action data specific to the IACL entry.
*
* \return XP_STATUS
*/
XP_STATUS xpsIaclWritePaclData(xpsDevice_t devId, uint32_t camIndex, xpsIaclData_t *iaclData);
/**
* \brief Write the IACL action Data for bridge Interface
*
*
* \param [in] devId
* \param [in] camIndex Its index at which the IACL action data is written on the HW.User should manage cam index.
* \param [in] *iaclData Its pointer to the action data specific to the IACL entry.
*
* \return XP_STATUS
*/
XP_STATUS xpsIaclWriteBaclData(xpsDevice_t devId, uint32_t camIndex, xpsIaclData_t *iaclData);
/**
* \brief Write the IACL action Data for router interface
*
*
* \param [in] devId
* \param [in] camIndex Its index at which the IACL action data is written on the HW.User should manage cam index.
* \param [in] *iaclData Its pointer to the action data specific to the IACL entry.
*
* \return XP_STATUS
*/
XP_STATUS xpsIaclWriteRaclData(xpsDevice_t devId, uint32_t camIndex, xpsIaclData_t *iaclData);
//Writing IACL Entry (Key + Data)
/**
* \brief This API enables user to write both key portion and action data
* portion of the IACL entry for the port on the HW.
*
*
* \param [in] devId
* \param [in] camIndex Its index at which the IACL entry is written on the Hw
* \param [in] *fldData Its pointer to a IACL key structure which consists information about key
* Fields list,keyType,validity bit(0-valid,1-invalid) and number of fields in the key.The key field List
* consists of various flds which is to be filled based on the keyType.Possible values for flds are values
* in the following enums xpIaclV4KeyFlds and xpIaclV6KeyFlds.Along with each key fields the value and mask
* should be provided which is to be programed on the TCAM.
* \param [in] *iaclData Its pointer to the action data specific to the IACL entry.
*
* \return XP_STATUS
*/
XP_STATUS xpsIaclWritePaclEntry(xpsDevice_t devId, uint32_t camIndex, xpsIaclkeyFieldList_t *fldData, xpsIaclData_t *iaclData);
/**
* \brief This API enables user to write both key portion and action data
* portion of the IACL entry for the vlan interface on the HW.
*
*
* \param [in] devId
* \param [in] camIndex Its index at which the IACL entry is written on the HW
* \param [in] *fldData Its pointer to a IACL key structure which consists information about key
* Fields list,keyType,validity bit(0-valid,1-invalid) and number of fields in the key.The key field List
* consists of various flds which is to be filled based on the keyType.Possible values for flds are values
* in the following enums xpIaclV4KeyFlds and xpIaclV6KeyFlds.Along with each key fields the value and mask
* should be provided which is to be programed on the TCAM.
* \param [in] *iaclData Its pointer to the action data specific to the IACL entry.
*
* \return XP_STATUS
*/
XP_STATUS xpsIaclWriteBaclEntry(xpsDevice_t devId, uint32_t camIndex, xpsIaclkeyFieldList_t *fldData, xpsIaclData_t *iaclData);
/**
* \brief This API enables user to write both key portion and action data
* portion of the IACL entry for the router interface on the HW.
*
*
* \param [in] devId
* \param [in] camIndex Its index at which the IACL entry is written on the HW
* \param [in] *fldData Its pointer to a IACL key structure which consists information about key
* Fields list,keyType,validity bit(0-valid,1-invalid) and number of fields in the key.The key field List
* consists of various flds which is to be filled based on the keyType.Possible values for flds are values
* in the following enums xpIaclV4KeyFlds and xpIaclV6KeyFlds.Along with each key fields the value and mask
* should be provided which is to be programed on the TCAM.
* \param [in] *iaclData Its pointer to the action data specific to the IACL entry.
*
* \return XP_STATUS
*/
XP_STATUS xpsIaclWriteRaclEntry(xpsDevice_t devId, uint32_t camIndex, xpsIaclkeyFieldList_t *fldData, xpsIaclData_t *iaclData);
#ifdef __cplusplus
}
#endif
#endif // _OPENXPSIACL_H_
|
XPliant/OpenXPS
|
include/openXpsPacketDrv.h
|
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* All Rights Reserved.
*
* 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.
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATIONS ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*
* FILE : openXpsPacketDrv.h
*
* Abstract: This file defines the apis for Packet Driver Management in OpenXPS.
************************************************************************/
/**
* \file openXpsPacketDrv.h
* \brief This file contains API prototypes and type definitions
* for the openXps Packet Driver Management
* \copyright (c) 2016 Cavium Inc
*/
#ifndef _OPENXPSPACKETDRV_H_
#define _OPENXPSPACKETDRV_H_
#include "openXpsTypes.h"
#include "openXpsEnums.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Function pointer for cpu packet rx processing
* \param [in] devId Device Id. Valid values are 0-63
* \param [in] portNum Port Number
* \param [out] buf Buffer pointer where packet data is available.
* \param [in] bufSize Size of the packet
* \param [in] userData User data passed to Rx handler callback
*
* \return XP_STATUS
*/
typedef XP_STATUS (*xpsPacketRxHdlr)(xpDevice_t devId, xpsPort_t portNum, void *buf, uint16_t bufSize, void* userData);
/**
* \brief Get the Packet driver current TX/RX interface
*
* \param [in] devId device Id. Valid values are 0-63
* \param [out] packetInterface Current packet driver interface. Enum value of DMA or ETHER
* \return [XP_STATUS] On success XP_NO_ERR
*/
XP_STATUS xpsPacketDriverInterfaceGet(xpsDevice_t devId, xpPacketInterface* const packetInterface);
/**
* \brief Set the configuration mode (Interrupt/Polling) for Packet driver\n
* Valid only for receive mode
*
* \param [in] devId device Id. Valid values are 0-63
* \param [in] configMode enum value of INTR or POLL
* \return [XP_STATUS] On success XP_NO_ERR
*/
XP_STATUS xpsPacketDriverRxConfigModeSet(xpsDevice_t devId, xpRxConfigMode configMode);
/**
* \brief Get the current configuration mode (Interrupt/Polling) for Packet driver
*
* \param [in] devId device Id. Valid values are 0-63
* \param [out] *configMode enum value to be return. Value is INTR or POLL
* \return [XP_STATUS] On success XP_NO_ERR
*/
XP_STATUS xpsPacketDriverRxConfigModeGet(xpsDevice_t devId, xpRxConfigMode* const configMode);
/**
* \brief Send packet on the current interface
*
* In DMA mode, this function will setup the descriptor from information provided in
* buffer and will configure the DMA and trigger it to start transfer of packets
* In Ethernet mode, this function will send buffer over Ethernet Interface.
* There are two tx modes: SYNC and ASYNC. In the SYNC mode the system waits till
* tx is completed. In the ASYNC mode the system moves ahead after the completion
* of packet transmission. The customer OS is notified about Tx completion via
* interrupt.
*
* \param [in] devId device Id. Valid values are 0-63
* \param [in] *pktInfo Packet information
* \param [in] sendMode Mode specifying Tx. Has value SYNC_TX/ASYNC_TX
*
* \return [XP_STATUS] On success XP_NO_ERR
*/
XP_STATUS xpsPacketDriverSend(xpsDevice_t devId, const struct xpPacketInfo* const pktInfo, txMode sendMode);
/**
* \brief Encapsulate the packet
*
* \param [in] devId device Id. Valid values are 0-63
* \param [out] pktInfo Packet pointer
* \param [in] srcVif source vif
* \param [in] dstVif destination vif
* \param [in] sendToEgress packet send egress or not
*/
XP_STATUS xpsPacketDriverCreateHeader(xpsDevice_t devId, xpPacketInfo* pktInfo, xpVif_t srcVif, xpVif_t dstVif, bool sendToEgress);
/**
* \brief Receive packet on default or previously set interface.
*
* In DMA mode receive maxPkt number of packets on the DMA interface. If requested
* number of packets are not available return the packets that are available.
* In Ethernet/netdev mode, this function will receive single buffer over Ethernet/netdev Interface.
*
* \param [in] devId device Id. Valid values are 0-63
* \param [in,out] **pktInfo pointer to array of xpPacketInfo
* \param [in,out] *maxPkt Maximum number of packets to be received. Will be updated to indicate number of packets actually received
* \return [XP_STATUS] On success XP_NO_ERR
*/
XP_STATUS xpsPacketDriverReceive(xpsDevice_t devId, struct xpPacketInfo **pktInfo, uint16_t *maxPkt);
/**
* \brief Receive packet on default or previously set interface.
*
* In DMA mode receive maxPkt number of packets on the DMA interface. If requested
* number of packets are not available return the packets that are available.
* In Ethernet mode, this function will receive single buffer over Ethernet Interface.
*
* \param [in] devId device Id. Valid values are 0-63
* \param [in] queue queue number for which to receive the packet
* \param [in,out] pktInfo pointer to array of xpPacketInfo
* \param [in,out] maxPkt Maximum number of packets to be received. Will be updated to indicate number of packets actually received
*
* \return XP_STATUS
*/
XP_STATUS xpsPacketDriverReceiveForQueue(xpDevice_t devId, uint8_t queue, xpPacketInfo **pktInfo, uint16_t *maxPkt);
/**
* \brief Register the packet send/receive completion handler
*
* \param [in] devId device Id. Valid values are 0-63
* \param [in] onSend Pointer to the handler to be called on packet send completion
* \param [in] onRecv Pointer to the handler to be called on packet receive completion
* \param [in] onError Pointer to handler to be called on error
* \return [XP_STATUS] On success XP_NO_ERR. On failure XP_ERR_NOT_INITED
*/
XP_STATUS xpsPacketDriverCompletionHndlrRegister(xpsDevice_t devId, xpPacketTxCompletion onSend, xpPacketAvailable onRecv, xpDmaError onError);
/**
* \brief De-register the packet send completion function,\n
* packet receive completion function or both type of function
*
* \param [in] devId device Id. Valid values are 0-63
* \param [in] what enum value to de-register packet send completion function/packet receive\n
* completion function or both type of function
* \return [XP_STATUS] On success XP_NO_ERR
*/
XP_STATUS xpsPacketDriverCompletionHndlrDeRegister(xpsDevice_t devId, xpCallbackMethodType what);
/**
* \brief register a callback
*
* \param [in] type feature type
* \param [in] cbPtr callback pointer
* \param [in] userData user argument
* \return [XP_STATUS] On success XP_NO_ERR
*/
XP_STATUS xpsPacketDriverFeatureRxHndlr(xpsCpuRxPktCbType_e type, xpsPacketRxHdlr cbPtr, void* userData);
/**
* \brief de-register a callback
*
* \param [in] type feature type
* \return [XP_STATUS] On success XP_NO_ERR
*/
XP_STATUS xpsPacketDriverFeatureRxHndlrDeRegister(xpsCpuRxPktCbType_e type);
/**
* \brief
*
* \param [out] sizeOfTxHd
* \return [XP_STATUS] On success XP_NO_ERR
*/
XP_STATUS xpsPacketDriverGetTxHdrSize(size_t* sizeOfTxHd);
/**
* \brief
*
* \param [in] devId
* \param [in] xpsIfId
* \param [in] msg
* \return [XP_STATUS] On success XP_NO_ERR
*/
XP_STATUS xpsNlTxHeaderMsgAssign(xpsDevice_t devId, xpsInterfaceId_t xpsIfId, uint8_t *msg);
/**
* \brief
*
* \param [out] nlData
* \param [out] nlBuf
* \return [XP_STATUS] On success XP_NO_ERR
*/
XP_STATUS xpsNlSockGetBuf(uint8_t** nlData, uint8_t** nlBuf);
/**
* \brief
*
* \param [in] nlBuf
* \return [XP_STATUS] On success XP_NO_ERR
*/
XP_STATUS xpsNlSockFreeBuf(uint8_t* nlBuf);
/**
* \brief
*
* \param [in] nlBuf
* \return [XP_STATUS] On success XP_NO_ERR
*/
XP_STATUS xpsNlSockSendMsg(uint8_t* nlBuf);
/**
* \brief xpsNetdevXpnetIdAllocate returns xpnetId
*
* \param [in] devId: device Id. Valid values are 0-63
* \param [out] xpnetId: xpnet identificator
*
* \return [XP_STATUS]
*/
XP_STATUS xpsNetdevXpnetIdAllocate(xpsDevice_t devId, uint32_t *xpnetId);
/**
* \brief xpsNetdevXpnetIdAllocateWith returns specified xpnetId
*
* \param [in] devId: device Id. Valid values are 0-63
* \param [in] xpnetId: xpnet identificator
*
* \return [XP_STATUS]
*/
XP_STATUS xpsNetdevXpnetIdAllocateWith(xpsDevice_t devId, uint32_t xpnetId);
/**
* \brief xpsNetdevXpnetIdFree frees xpnetId
*
* \param [in] devId: device Id. Valid values are 0-63
* \param [in] xpnetId: xpnet identificator
*
* \return [XP_STATUS]
*/
XP_STATUS xpsNetdevXpnetIdFree(xpsDevice_t devId, uint32_t xpnetId);
/**
* \brief xpsNetdevIfCreate creates a netdev interface
*
* \param [in] devId: device Id. Valid values are 0-63
* \param [in] xpnetId: xpnet identificator
* \param [in] ifName: interface name
*
* \return [XP_STATUS]
*/
XP_STATUS xpsNetdevIfCreate(xpsDevice_t devId, uint32_t xpnetId, char *ifName);
/**
* \brief xpsNetdevIfDelete deletes a netdev interface
*
* \param [in] devId: device Id. Valid values are 0-63
* \param [in] xpnetId: xpnet identificator
*
* \return [XP_STATUS]
*/
XP_STATUS xpsNetdevIfDelete(xpsDevice_t devId, uint32_t xpnetId);
/**
* \brief xpsNetdevIfLinkSet links/unlinks a netdev interface
* with xp interface
*
* \param [in] devId: device Id. Valid values are 0-63
* \param [in] xpnetId: xpnet identificator
* \param [in] xpsIf: xps interface
* \param [in] flag: link/unlink
*
* \return [XP_STATUS]
*/
XP_STATUS xpsNetdevIfLinkSet(xpsDevice_t devId, uint32_t xpnetId,
xpsInterfaceId_t xpsIf, bool flag);
/**
* \brief xpsNetdevIfTxHeaderSet sets XP TX header
*
* \param [in] devId: device Id. Valid values are 0-63
* \param [in] xpnetId: xpnet identificator
* \param [in] xpsIf: xps interface
* \param [in] flag: set/unset
*
* \return [XP_STATUS]
*/
XP_STATUS xpsNetdevIfTxHeaderSet(xpsDevice_t devId, uint32_t xpnetId,
xpsInterfaceId_t xpsIf, bool flag);
/**
* \brief xpsNetdevTrapSet assign/unassign trap
*
* \param [in] devId: device Id. Valid values are 0-63
* \param [in] trapId: trap indentificator
* \param [in] rCode: reason code
* \param [in] ch: channel
* \param [in] fd: socket descriptor
* \param [in] flag: add/remove
*
* \return [XP_STATUS]
*/
XP_STATUS xpsNetdevTrapSet(xpsDevice_t devId, uint32_t trapId, uint32_t rCode,
uint32_t ch, uint32_t fd, bool flag);
/**
* \brief xpsNetdevCbFdSet registers file descriptor in kernel
* module to recived packets
*
* \param [in] devId: device Id. Valid values are 0-63
* \param [in] fd: call back channel FD
* \param [in] flag: set/unset
*
* \return [XP_STATUS]
*/
XP_STATUS xpsNetdevCbFdSet(xpsDevice_t devId, uint32_t fd, bool flag);
/**
* \brief xpsNetdevMirrorSet enables mirroring to XDK
*
* \param [in] devId: device Id. Valid values are 0-63
* \param [in] flag: enable/disable
*
* \return [XP_STATUS]
*/
XP_STATUS xpsNetdevMirrorSet(xpsDevice_t devId, bool flag);
#ifdef __cplusplus
}
#endif
#endif //_OPENXPSPACKETDRV_H_
|
XPliant/OpenXPS
|
xpnet/include/version.h
|
<reponame>XPliant/OpenXPS<gh_stars>10-100
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* 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; version 2
* of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* A copy of the GNU General Public License, version 2 is available in the file
* named LICENSE-GPLv2.md either in this directory or its root.
* Alernatively to obtain a copy, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* File: version.h
*
* Abstract: This file contains the macros and definitions required.
************************************************************************/
#ifndef __VERSION_H__
#define __VERSION_H__
#define XPTOOLS_VERSION "XPTOOLS-XDK-3.2-GA-BRANCH_POINT-232-g8239a3e"
#define XPTOOLS_HASH_COMMIT "8239a3e814ba1a47b3ae47c54bda9bb86b70717d"
#endif // __VERSION_H__
|
XPliant/OpenXPS
|
include/openXpsTcamMgr.h
|
<gh_stars>10-100
// openXpsTcamMgr.h
/************************************************************************/
/* Copyright (c) [2011-2015] Cavium, Inc. All rights reserved. */
/* Unpublished - rights reserved under the Copyright Laws of the */
/* United States. Use, duplication, or disclosure by the */
/* Government is subject to restrictions as set forth in */
/* subparagraph (c)(1)(ii) of the Rights in Technical Data and */
/* Computer Software clause at 252.227-7013. */
/************************************************************************/
/**
* \file openXpsTcamMgr.h
* \brief This file contains API prototypes and type definitions
* for the XPS TCAM Manager
*
*/
#ifndef _openXpsTcamMgr_h_
#define _openXpsTcamMgr_h_
#include "openXpsTypes.h"
#include "openXpsEnums.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Some variables explanation:
* tableId - HW table ID
* entryId - ID that corresponds to TCAM hit index, but never changes. Application has to remember it.
* tcamId - HW hit index. Should be used for HW access.
*/
/**
* \brief Rule move function moves table entry from src to dst possition.
* Function is provided by TCAM Mgr user application.
* Source and destination indexes are HW indexes.
*/
typedef XP_STATUS (*xpsTcamMgrRuleMove_fn)(xpsDevice_t devId, uint32_t tableId, uint32_t dst, uint32_t src);
/**
* \typedef _xpsTcamMgrShufflingList_e
* \brief List of available shuffling algorithms.
*/
typedef enum _xpsTcamMgrShufflingList_e {
XPS_TCAM_ACL_ALGORITHM = 0,
XPS_TCAM_LIST_ALGORITHM,
XPS_SHUFFLING_ALGORITHM_NUM
} xpsTcamMgrShufflingList_e;
/*
* State Management APIs
*/
/**
* \brief API to initialize the TCAM Manager
*
* This will allocate memory for global and per device data
*
* \param [in] scopeId
*
* \return XP_STATUS
*/
XP_STATUS xpsTcamMgrInit(xpsScope_t scopeId);
/**
* \brief API to de-initialize the TCAM Manager
*
* This will de-allocate memory for global and per device data
*
* \param [in] scopeId
*
* \return XP_STATUS
*/
XP_STATUS xpsTcamMgrDeInit(xpsScope_t scopeId);
/**
* \brief API to Add Device Information to the TCAM Manager
*
* This API is a NOP. We need a more explicit Add Device for Per
* Device Databases
*
* \param [in] devId
*
* \return XP_STATUS
*/
XP_STATUS xpsTcamMgrAddDevice(xpsDevice_t devId);
/**
* \brief API to Remove Device Information from the TCAM
* Manager
*
* This API is a NOP. We need a more explicit Remove Device for
* Per Device Databases
*
* \param [in] devId
*
* \return XP_STATUS
*/
XP_STATUS xpsTcamMgrRemoveDevice(xpsDevice_t devId);
/**
* \brief API to start TCAM table management
*
* \param [in] devId
* \param [in] tableId
* \param [in] shufflingAlg
*
* \return XP_STATUS
*/
XP_STATUS xpsTcamMgrAddTable(xpsDevice_t devId, uint32_t tableId, xpsTcamMgrShufflingList_e shufflingAlg);
/**
* \brief API to configure TCAM table management
*
* \param [in] devId
* \param [in] tableId
* \param [in] ruleMove
* \param [in] tableEntryNum
* \param [in] entryPrioNum
*
* \return XP_STATUS
*/
XP_STATUS xpsTcamMgrConfigTable(xpsDevice_t devId, uint32_t tableId,
xpsTcamMgrRuleMove_fn ruleMove, uint32_t tableEntryNum,
uint32_t entryPrioNum);
/**
* \brief API to stop TCAM table management
*
* \param [in] devId
* \param [in] tableId
*
* \return XP_STATUS
*/
XP_STATUS xpsTcamMgrRemoveTable(xpsDevice_t devId, uint32_t tableId);
/**
* \brief API to add TCAM entry into TCAM Manager
*
* \param [in] devId
* \param [in] tableId
* \param [in] priority
* \param [out] entryId
*
* \return XP_STATUS
*/
XP_STATUS xpsTcamMgrAllocEntry(xpsDevice_t devId, uint32_t tableId, uint32_t priority, uint32_t* entryId);
/**
* \brief API to delete TCAM entry from TCAM Manager
*
* \param [in] devId
* \param [in] tableId
* \param [in] entryId
*
* \return XP_STATUS
*/
XP_STATUS xpsTcamMgrFreeEntry(xpsDevice_t devId, uint32_t tableId, uint32_t entryId);
/**
* \brief API to deliver entry ID from TCAM ID
*
* \param [in] devId
* \param [in] tableId
* \param [in] tcamId
* \param [out] entryId
*
* \return XP_STATUS
*/
XP_STATUS xpsTcamMgrEntryFromTcamIdGet(xpsDevice_t devId, uint32_t tableId, uint32_t tcamId, uint32_t* entryId);
/**
* \brief API to deliver TCAM ID from entry ID
*
* \param [in] devId
* \param [in] tableId
* \param [in] entryId
* \param [out] tcamId
*
* \return XP_STATUS
*/
XP_STATUS xpsTcamMgrTcamIdFromEntryGet(xpsDevice_t devId, uint32_t tableId, uint32_t entryId, uint32_t* tcamId);
/**
* \brief Debug API to simplify programmers life
*
* \param [in] devId
* \param [in] tableId
*
* \return XP_STATUS
*/
XP_STATUS xpsTcamMgrDebug(xpsDevice_t devId, uint32_t tableId);
/**
* \brief API to move the HW tcam values from one entry(src) to other entry(dst)
*
* \param [in] devId
* \param [in] tableId
* \param [in] dst
* \param [in] src
*
* \return XP_STATUS
*/
XP_STATUS xpsTcamMgrRuleMoveAcl(xpsDevice_t devId, uint32_t tableId, uint32_t dst, uint32_t src);
/**
* \brief API to allocate TCAM ID
*
* \param [in] devId
* \param [in] tableId
* \param [out] tcamId
*
* \return XP_STATUS
*/
XP_STATUS xpsTcamIdAllocEntry(xpsDevice_t devId, uint32_t tableId, uint32_t* tcamId);
/**
* \brief API to free TCAM ID
*
* \param [in] devId
* \param [in] tableId
* \param [in] tcamId
*
* \return XP_STATUS
*/
XP_STATUS xpsTcamIdFreeEntry(xpsDevice_t devId, uint32_t tableId, uint32_t tcamId);
#ifdef __cplusplus
}
#endif
#endif // _openXpsTcamMgr_h_
|
XPliant/OpenXPS
|
include/openXpsOpenflow.h
|
<filename>include/openXpsOpenflow.h
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* All Rights Reserved.
*
* 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.
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATIONS ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*
* FILE : openXpsOpenflow.h
*
* Abstract: This file defines the apis for OpenFlow Management in OpenXPS.
************************************************************************/
/**
* \file openXpsOpenflow.h
* \brief This file contains API prototypes and type definitions
* for the openXps OpenFlow Management
* \copyright (c) 2016 Cavium Inc
*/
#ifndef _openXpsOpenflow_h_
#define _openXpsOpenflow_h_
#include "openXpsTypes.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief This defines the type of function pointer that the user can register for
* OpenFlow packet-in messages.
*/
typedef XP_STATUS (*xpOfPacketInHandler) (xpsDevice_t, xpDatapath_t, xpOfPacketIn_t *, void *);
/**
* \brief This defines the type of function pointer that the user can register for
* OpenFlow statistics flush event.
*/
typedef XP_STATUS (*xpOfFlowStatsFlushHandler) (xpsDevice_t, xpDatapath_t, uint32_t, xpOfFlowId_t *, xpOfStats_t *, void *);
/**
* \brief This method maintains operation of XP_OFPP_FLOOD and XP_OFPP_ALL
* OpenFlow service ports. It enables/disables sending packet out of port
* interface in case action output is set to XP_OFPP_FLOOD or XP_OFPP_ALL
* service port.
*
* \param [in] devId Physical device identifier
* \param [in] ofppPort One of service OpenFlow ports: XP_OFPP_FLOOD, XP_OFPP_ALL
* \param [in] portIntf OpenFlow port identifier
* \param [in] enable Enable/disable sending packets out of port interface.
*
* \return XP_STATUS
*/
XP_STATUS xpsOfSetPortEnable(xpsDevice_t devId, xpOfPortNo_e ofppPort, xpsInterfaceId_t portIntf, uint8_t enable);
/**
* \brief This method reads the sending enable state of port interface from
* XP_OFPP_FLOOD or XP_OFPP_ALL OpenFlow service port. If 'enable' holds non
* zero value then the packets will be sent out of port interface in case
* action output is set to XP_OFPP_FLOOD or OFPP_ALL service port.
*
* \param [in] devId Physical device identifier
* \param [in] ofppPort One of service OpenFlow ports: XP_OFPP_FLOOD, XP_OFPP_ALL
* \param [in] portIntf OpenFlow port identifier
* \param [out] enable Enable/disable sending status for the port interface.
*
* \return XP_STATUS
*/
XP_STATUS xpsOfGetPortEnable(xpsDevice_t devId, xpOfPortNo_e ofppPort, xpsInterfaceId_t portIntf, uint8_t *enable);
/**
* \brief This method will take the table profile from the user
* and create the tables based on the key size and
* numDbs required.
*
* \param [in] devId Physical device identifier
* \param [in] tblInfo Table profile which describes particular HW tables properties
*
* \return XP_STATUS
*/
XP_STATUS xpsOfCreateTable(xpsDevice_t devId, xpOpenFlowTableProfile_t tblInfo);
/**
* \brief This method will delete particular OpenFlow HW tables
* base on provided table profile information.
*
* \param [in] devId Physical device identifier
* \param [in] tblInfo Table profile that indicates which HW tables must be removed
*
* \return XP_STATUS
*/
XP_STATUS xpsOfDeleteTable(xpDevice_t devId, const xpOpenFlowTableProfile_t *tblInfo);
/**
* \brief This method will enable lookup for a particular tableId and tableType
*
* \param [in] devId Physical device identifier
* \param [in] tableId OpenFlow table identifier
* \param [in] tableType HW table type
*
* \return XP_STATUS
*/
XP_STATUS xpsOfEnableTableLookup(xpsDevice_t devId, uint32_t tableId, xpOfTableType_e tableType);
/**
* \brief This method will disable lookup for a particular tableId and tableType
* Disabling TCAM lookup results in OpenFlow table-miss behavior that
* can only drop packets if no match is found in a flow table.
*
* \param [in] devId Physical device identifier
* \param [in] tableId OpenFlow table identifier
* \param [in] tableType HW table type
*
* \return XP_STATUS
*/
XP_STATUS xpsOfDisableTableLookup(xpsDevice_t devId, uint32_t tableId, xpOfTableType_e tableType);
/**
* \brief This method will take a key field list and a table id from the user
* and configure the key mask for the table according to the field list.
*
* \param [in] devId Physical device identifier
* \param [in] tableId OpenFlow table identifier
* \param [in] tableType HW table type
* \param [in] keyList List of Table's key fields
* \param [in] keyListLen Number of keys in keyList
*
* \return XP_STATUS
*/
XP_STATUS xpsOfSetTableKeyFormat(xpsDevice_t devId, uint32_t tableId, xpOfTableType_e tableType,
const xpOxmType_e *keyList, uint32_t keyListLen);
/**
* \brief This method applies actions to specified packet.
*
* A list of actions will be applied in the order
* they are specified; an empty action list
* drops the packet.
*
* \param [in] devId Physical device identifier
* \param [in] dpId Logical OpenFlow datapath identifier
* \param [in] inPort Ingress port that must be associated with the packet for OpenFlow processing
* \param [in] packet Packet to be processed
* \param [in] packetLen Packet's length
* \param [in] actionList List of actions defining how the packet should be processed by the switch
* \param [in] actionListLen Number of actions in actionList
*
* \return XP_STATUS
*/
XP_STATUS xpsOfApplyActions(xpsDevice_t devId, xpDatapath_t dpId, uint32_t inPort, uint8_t* packet,
uint32_t packetLen, xpOfAction_t* actionList, uint32_t actionListLen);
/**
* \brief This method returns one table statistics.
*
* \param [in] devId Physical device identifier
* \param [in] dpId Logical OpenFlow datapath identifier
* \param [in] tableId OpenFlow table identifier
* \param [out] tableStats OpenFlow table statistics
*
* \return XP_STATUS
*/
XP_STATUS xpsOfGetTableStats(xpsDevice_t devId, xpDatapath_t dpId,
uint8_t tableId, xpOfTableStats_t *tableStats);
/**
* \brief This method adds flow entry to the specified table.
*
* \param [in] devId Physical device identifier
* \param [in] dpId Logical OpenFlow datapath identifier
* \param [in] flowEntry OpenFlow flow entry to be created
* \param [out] flowId OpenFlow entry identifier
*
* \return XP_STATUS
*/
XP_STATUS xpsOfAddFlow(xpsDevice_t devId, xpDatapath_t dpId,
xpFlowEntry_t *flowEntry, xpOfFlowId_t *flowId);
/**
* \brief This method modifies one flow entry in the specified table
* based on provided flow entry identifier.
*
* If a matching entry exists in the table, the instructions
* field of this entry is updated with the value from
* the request.
*
* \param [in] devId Physical device identifier
* \param [in] dpId Logical OpenFlow datapath identifier
* \param [in] tableId OpenFlow table identifier
* \param [in] flowId OpenFlow entry to be modified
* \param [in] instructions New OpenFlow entry's instructions
*
* \return XP_STATUS
*/
XP_STATUS xpsOfModifyFlowById(xpsDevice_t devId, xpDatapath_t dpId,
uint8_t tableId, const xpOfFlowId_t *flowId,
const xpOfInstructions_t *instructions);
/**
* \brief This method modifies one flow entry in the specified table.
* It causes OpenFlow table lookup based on provided flow entry's
* match fields. If a matching entry exists in the table,
* the instructions field of this entry is updated with the value from
* the request.
*
* \param [in] devId Physical device identifier
* \param [in] dpId Logical OpenFlow datapath identifier
* \param [in] flowEntry OpenFlow flow entry to be modified with new OpenFlow instructions
*
* \return XP_STATUS
*/
XP_STATUS xpsOfModifyFlow(xpsDevice_t devId, xpDatapath_t dpId,
const xpFlowEntry_t *flowEntry);
/**
* \brief This method removes one flow entry from the specified table
* by flow entry identifier.
*
* \param [in] devId Physical device identifier
* \param [in] dpId Logical OpenFlow datapath identifier
* \param [in] tableId OpenFlow table identifier
* \param [in] flowId OpenFlow entry to be removed
*
* \return XP_STATUS
*/
XP_STATUS xpsOfRemoveFlowById(xpsDevice_t devId, xpDatapath_t dpId,
uint8_t tableId, const xpOfFlowId_t *flowId);
/**
* \brief This method removes one flow entry from the specified table.
* It causes OpenFlow table lookup based on provided flow entry's
* match fields. If a matching entry exists in the table,
* it is removed.
*
* \param [in] devId Physical device identifier
* \param [in] dpId Logical OpenFlow datapath identifier
* \param [in] flowEntry OpenFlow entry to be removed
*
* \return XP_STATUS
*/
XP_STATUS xpsOfRemoveFlow(xpsDevice_t devId, xpDatapath_t dpId,
const xpFlowEntry_t *flowEntry);
/**
* \brief This method returns one flow entry statistic.
*
* The function gets the value of per-flow statistic registers.
* The registers are "clear on read" so caller is responsible
* for accumulation of data if one is needed.
*
* \param [in] devId Physical device identifier
* \param [in] dpId Logical OpenFlow datapath identifier
* \param [in] tableId OpenFlow table identifier
* \param [in] flowId OpenFlow entry identifier
* \param [out] flowStats OpenFlow entry statistics
*
* \return XP_STATUS
*/
XP_STATUS xpsOfGetFlowStats(xpsDevice_t devId, xpDatapath_t dpId,
uint8_t tableId, const xpOfFlowId_t *flowId,
xpOfStats_t *flowStats);
/**
* \brief This method allows the user to register OF Packet-In handler
*
* \param [in] devId Physical device identifier
* \param [in] dpId Logical OpenFlow datapath identifier
* \param [in] func User provided callback function to be called on Packet-In event
* \param [in] userData User provided data that will be passed as callback function parameter
*
* \return XP_STATUS
*/
XP_STATUS xpsOfRegisterPacketInHandler(xpsDevice_t devId, xpDatapath_t dpId,
xpOfPacketInHandler func, void *userData);
/**
* \brief This method allows the user to unregister OF Packet-In handler
*
* \param [in] devId Physical device identifier
* \param [in] dpId Logical OpenFlow datapath identifier
*
* \return XP_STATUS
*/
XP_STATUS xpsOfUnregisterPacketInHandler(xpsDevice_t devId, xpDatapath_t dpId);
/**
* \brief This method allows the user to register handler
* that will be executed once flow entry has changed
* physical location due to SRAM entry rehashing or
* TCAM entries shuffling. This handler will receive
* current flow's statistic as input parameter.
*
* \param [in] func User provided callback function to be called
* \param [in] userData User provided data that will be passed as callback function parameter
*
* \return XP_STATUS
*/
XP_STATUS xpsOfRegisterFlowStatsFlushHandler(xpOfFlowStatsFlushHandler func,
void *userData);
/**
* \brief This method allows the user to unregister handler
* that should be executed once flow entry has changed
* physical location due to SRAM entry rehashing or
* TCAM entries shuffling.
*
* \return XP_STATUS
*/
XP_STATUS xpsOfUnregisterFlowStatsFlushHandler(void);
/**
* \brief Get the interface id corresponding to the XP_OFPP_LOCAL port
* for OpenFlow data path
*
* \param [in] devId Physical device identifier
* \param [in] dpId Logical OpenFlow datapath identifier
* \param [out] intfId XP_OFPP_LOCAL interface identifier
*
* \return XP_STATUS
*/
XP_STATUS xpsOfGetOfppLocalIntfId(xpsDevice_t devId, xpDatapath_t dpId,
xpsInterfaceId_t *intfId);
/**
* \brief Get the interface id corresponding to the XP_OFPP_CONTROLLER port
* for OpenFlow data path
*
* \param [in] devId Physical device identifier
* \param [in] dpId Logical OpenFlow datapath identifier
* \param [out] intfId XP_OFPP_CONTROLLER interface identifier
*
* \return XP_STATUS
*/
XP_STATUS xpsOfGetOfppControllerIntfId(xpsDevice_t devId, xpDatapath_t dpId,
xpsInterfaceId_t *intfId);
/**
* \brief This method adds new group entry to the group table.
*
* If a group entry with the specified group identifier
* already resides in the group table, then the switch
* will refuse to add the group entry and return an error.
*
* \param [in] devId Physical device identifier
* \param [in] dpId Logical OpenFlow datapath identifier
* \param [in] groupId OpenFlow group identifier to be created
* \param [in] groupType OpenFlow group type to be created
* \param [in] buckets OpenFlow group's action buckets array
* \param [in] bucketsNum Number of OpenFlow group's action buckets
*
* \return XP_STATUS
*/
XP_STATUS xpsOfAddGroup(xpsDevice_t devId, xpDatapath_t dpId,
uint32_t groupId, xpOfGroupType_e groupType,
xpOfBucket_t* buckets, uint32_t bucketsNum);
/**
* \brief This method modifies group entry in the group table.
*
* If a group entry with the specified group identifier already
* resides in the group table, then that entry will be removed,
* and the new group entry added.
*
* If a group entry with the specified group identifier
* does not already exist then the switch will refuse
* the group modification and return an error status.
*
* \param [in] devId Physical device identifier
* \param [in] dpId Logical OpenFlow datapath identifier
* \param [in] groupId OpenFlow group identifier to be modified
* \param [in] groupType OpenFlow group type to be modified
* \param [in] buckets OpenFlow group's action buckets array
* \param [in] bucketsNum Number of OpenFlow group's action buckets
*
* \return XP_STATUS
*/
XP_STATUS xpsOfModifyGroup(xpsDevice_t devId, xpDatapath_t dpId,
uint32_t groupId, xpOfGroupType_e groupType,
xpOfBucket_t* buckets, uint32_t bucketsNum);
/**
* \brief This method removes group entry from the specified table.
*
* \param [in] devId Physical device identifier
* \param [in] dpId Logical OpenFlow datapath identifier
* \param [in] groupId OpenFlow group identifier to be removed
*
* \return XP_STATUS
*/
XP_STATUS xpsOfRemoveGroup(xpsDevice_t devId, xpDatapath_t dpId,
uint32_t groupId);
/**
* \brief This method returns group entry statistic.
*
* \param [in] devId Physical device identifier
* \param [in] dpId Logical OpenFlow datapath identifier
* \param [in] groupId OpenFlow group identifier
* \param [out] groupStats OpenFlow group statistics
*
* \return XP_STATUS
*/
XP_STATUS xpsOfGetGroupStats(xpsDevice_t devId, xpDatapath_t dpId,
uint32_t groupId, xpOfStats_t *groupStats);
/**
* \brief This method returns per-bucket statistic of one group entry.
*
* \param [in] devId Physical device identifier
* \param [in] dpId Logical OpenFlow datapath identifier
* \param [in] groupId OpenFlow group identifier
* \param [in] bucketsNum Size of user-allocated array for per-bucket statistics
* \param [out] bucketStats User-allocated array for per-bucket statistics
*
* \return XP_STATUS
*/
XP_STATUS xpsOfGetBucketStats(xpsDevice_t devId, xpDatapath_t dpId,
uint32_t groupId, uint32_t bucketsNum,
xpOfStats_t* bucketStats);
#ifdef __cplusplus
}
#endif
#endif //_openXpsOpenflow_h_
|
XPliant/OpenXPS
|
include/openXpsVlan.h
|
<gh_stars>10-100
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* All Rights Reserved.
*
* 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.
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATIONS ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*
* FILE : openXpsVlan.h
*
* Abstract: This file defines the apis for VLAN Management in OpenXPS.
************************************************************************/
/**
* \file openXpsVlan.h
* \brief This file contains API prototypes and type definitions
* for the openXps Vlan Management
* \copyright (c) 2016 Cavium Inc
*/
#ifndef _openXpsVlan_h_
#define _openXpsVlan_h_
#include "openXpsTypes.h"
#include "openXpsEnums.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
*\struct xpsVlanConfig_t
*\brief VLAN entry format structure
*
*/
typedef struct
{
uint32_t stpId; ///< Spanning Tree Protocol ID
xpsVlanCountMode_e countMode; ///< ACM Count mode
uint32_t enableMirror; ///< Enable Mirroring
uint32_t mirrorAnalyzerId; ///< Mirror Analyzer ID
xpsPktCmd_e saMissCmd; ///< FDB MAC SA miss command
xpsPktCmd_e bcCmd; ///< Broadcast packet type command
xpsPktCmd_e unknownUcCmd; ///< Unknown Unicast packet type command
xpsPktCmd_e arpBcCmd; ///< ARP Broadcast packet type command
xpsVlanBridgeMcMode_e ipv4McbridgeMode; ///< IPv4 Bridge Multicast Multicast configuration
xpsVlanBridgeMcMode_e ipv6McbridgeMode; ///< IPv6 Bridge Multicast Multicast configuration
xpsPktCmd_e unRegMcCmd; ///< Unregistered Multicast packet type command
} xpsVlanConfig_t;
#define XPS_VLANID_MIN (0u)
#define XPS_VLANID_MAX (XP_MAX_VLAN_NUM - 1u)
/**
* \brief This method creates a VLAN instance on a device, and
* writes device specific table entries and fields
* with their default values.
*
* \param [in] devId Device ID
* \param [in] vlanId VLAN ID
*
* \return XP_STATUS
*/
XP_STATUS xpsVlanCreate (xpsDevice_t devId, xpsVlan_t vlanId);
/**
* \brief This method destroys a VLAN instance on a device, and
* releases and/or writes device specific table entries.
*
* \param [in] devId Device ID
* \param [in] vlanId VLAN ID
*
* \return XP_STATUS
*/
XP_STATUS xpsVlanDestroy (xpsDevice_t devId, xpsVlan_t vlanId);
/**
* \brief This method adds an End point to a specific VLAN instance.
*
* \param [in] devId Device ID
* \param [in] vlanId VLAN ID
* \param [in] intfId
* \param [in] tagType
* \param [in] data
*
* \return XP_STATUS
*/
XP_STATUS xpsVlanAddEndpoint(xpsDevice_t devId, xpsVlan_t vlanId, xpsInterfaceId_t intfId, xpsL2EncapType_e tagType, uint32_t data);
/**
* \brief This method adds an interface to a specific VLAN instance.
*
* \param [in] devId Device ID
* \param [in] vlanId VLAN ID
* \param [in] intfId
* \param [in] tagType
*
* \return XP_STATUS
*/
XP_STATUS xpsVlanAddInterface(xpsDevice_t devId, xpsVlan_t vlanId, xpsInterfaceId_t intfId, xpsL2EncapType_e tagType);
/**
* \brief This method removes an End point from a specific VLAN instance.
*
* \param [in] devId Device ID
* \param [in] vlanId VLAN ID
* \param [in] intfId
*
* \return XP_STATUS
*/
XP_STATUS xpsVlanRemoveEndpoint(xpsDevice_t devId, xpsVlan_t vlanId, xpsInterfaceId_t intfId);
/**
* \brief This method removes an interface from a specific VLAN instance.
*
* \param [in] devId Device ID
* \param [in] vlanId VLAN ID
* \param [in] intfId
*
* \return XP_STATUS
*/
XP_STATUS xpsVlanRemoveInterface(xpsDevice_t devId, xpsVlan_t vlanId, xpsInterfaceId_t intfId);
/**
* \brief This method configures the action (packet command)
* for ARP broadcast packets, for a specific VLAN.
*
* \param [in] devId Device ID
* \param [in] vlanId VLAN ID
* \param [in] arpBcCmd
*
* \return XP_STATUS
*/
XP_STATUS xpsVlanSetArpBcCmd (xpsDevice_t devId, xpsVlan_t vlanId, xpsPktCmd_e arpBcCmd);
/**
* \brief This method configures the Unknown SA command/action
* for a specific VLAN.
*
* \param [in] devId Device ID
* \param [in] vlanId VLAN ID
* \param [in] saMissCmd
*
* \return XP_STATUS
*/
XP_STATUS xpsVlanSetUnknownSaCmd (xpsDevice_t devId, xpsVlan_t vlanId, xpsPktCmd_e saMissCmd);
/**
* \brief This method returns configuration of Unknown SA command/action
* for a specific VLAN.
*
* \param [in] devId Device ID
* \param [in] vlanId VLAN ID
* \param [out] *saMissCmd
*
* \return XP_STATUS
*/
XP_STATUS xpsVlanGetUnknownSaCmd (xpsDevice_t devId, xpsVlan_t vlanId, xpsPktCmd_e *saMissCmd);
/**
* \brief This method configures multiple VLAN properties
* for a specific VLAN.
*
* \param [in] devId Device ID
* \param [in] vlanId VLAN ID
* \param [in] *vlanConfig
*
* \return XP_STATUS
*/
XP_STATUS xpsVlanSetConfig (xpsDevice_t devId, xpsVlan_t vlanId, xpsVlanConfig_t *vlanConfig);
/**
* \brief This method returns multiple VLAN properties
* for a specific VLAN.
*
* \param [in] devId Device ID
* \param [in] vlanId VLAN ID
* \param [out] *vlanConfig
*
* \return XP_STATUS
*/
XP_STATUS xpsVlanGetConfig (xpsDevice_t devId, xpsVlan_t vlanId, xpsVlanConfig_t *vlanConfig);
/**
* \brief This method sets the Global Control MAC.
* Applicable across all VLANs on a device
*
* \param [in] devId Device ID
* \param [in] mac
*
* \return XP_STATUS
*/
XP_STATUS xpsVlanSetGlobalControlMac(xpsDevice_t devId, macAddr_t mac);
/**
* \brief This method clears the Global Control MAC.
* Applicable across all VLAN'S
*
* \param [in] devId Device ID
* \param [in] mac
*
* \return XP_STATUS
*/
XP_STATUS xpsVlanClearGlobalControlMac(xpsDevice_t devId, macAddr_t mac);
/**
* \brief This method enables OpenFlow processing on a specific {VLAN, Interface}.
*
* \param [in] devId Device ID
* \param [in] vlanId VLAN ID
* \param [in] intfId
* \param [in] enable
*
* \return XP_STATUS
*/
XP_STATUS xpsVlanSetOpenFlowEnable(xpsDevice_t devId, xpsVlan_t vlanId, xpsInterfaceId_t intfId, uint32_t enable);
/**
* \brief This method sets a vlan instance to be default vlan
* on all ports of a device.
*
* \param [in] devId
* \param [in] vlanId
*
* \return XP_STATUS
*/
XP_STATUS xpsVlanSetDefault (xpsDevice_t devId, xpsVlan_t vlanId);
/**
* \brief This method returns the default vlan instance for a device.
*
* \param [in] devId
* \param [out] *vlanId
*
* \return XP_STATUS
*/
XP_STATUS xpsVlanGetDefault (xpsDevice_t devId, xpsVlan_t *vlanId);
/**
* \brief This method binds a vlan instance to corresponding
* STG instance. All the port state for vlan is
* controlled by its corresponding port state within the
* STG instance.
*
* \param [in] devId
* \param [in] vlanId
* \param [in] stpId
*
* \return XP_STATUS
*/
XP_STATUS xpsVlanBindStp (xpsDevice_t devId, xpsVlan_t vlanId, xpsStp_t stpId);
/**
* \brief This method unbinds a vlan instance from the corresponding
* STG instance. All the port state for vlan is
* controlled by its corresponding port state within the
* STG instance.
*
* \param [in] devId
* \param [in] vlanId
* \param [in] stpId
*
* \return XP_STATUS
*/
XP_STATUS xpsVlanUnbindStp (xpsDevice_t devId, xpsVlan_t vlanId, xpsStp_t stpId);
#ifdef __cplusplus
}
#endif
#endif //_openXpsVlan_h_
|
XPliant/OpenXPS
|
include/openXpsStp.h
|
<filename>include/openXpsStp.h<gh_stars>10-100
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* All Rights Reserved.
*
* 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.
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATIONS ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*
* FILE : openXpsStp.h
*
* Abstract: This file defines the apis for Spanning Tree Protocol Management in OpenXPS.
************************************************************************/
/**
* \file openXpsStp.h
* \brief This file contains API prototypes and type definitions
* for the openXps STP Management
* \copyright (c) 2016 Cavium Inc
*/
#ifndef _openXpsStp_h_
#define _openXpsStp_h_
#include "openXpsTypes.h"
#include "openXpsEnums.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief This method returns the default STP ID for the device.
*
* \param [in] devId Device Id of device
* \param [out] *stpId Spanning Tree Protocol ID
*
* \return XP_STATUS
*/
XP_STATUS xpsStpGetDefault (xpsDevice_t devId, xpsStp_t *stpId);
/**
* \brief This method configures spanning tree and returns the id to the user.
*
* \param [out] *stpId
*
* \return XP_STATUS
*/
XP_STATUS xpsStpCreate (xpsStp_t *stpId);
/**
* \brief This method destroys a spanning tree.
*
* \param [in] stpId
*
* \return XP_STATUS
*/
XP_STATUS xpsStpDestroy (xpsStp_t stpId);
/**
* \brief This method configures the spanning tree state for a specific interface.
*
* \param [in] devId
* \param [in] stpId
* \param [in] intfId
* \param [in] stpState
*
* \return XP_STATUS
*/
XP_STATUS xpsStpSetState (xpsDevice_t devId, xpsStp_t stpId, xpsInterfaceId_t intfId, xpsStpState_e stpState);
/**
* \brief This method returns the spanning tree state for an interface.
*
* \param [in] devId
* \param [in] stpId
* \param [in] intfId
* \param [in] stpState
*
* \return XP_STATUS
*/
XP_STATUS xpsStpGetState (xpsDevice_t devId, xpsStp_t stpId, xpsInterfaceId_t intfId, xpsStpState_e *stpState);
#ifdef __cplusplus
}
#endif
#endif //_openXpsStp_h_
|
XPliant/OpenXPS
|
include/openXpsAclIdMgr.h
|
<filename>include/openXpsAclIdMgr.h
// openXpsAclIdMgr.h
/************************************************************************/
/* Copyright (c) [2011-2015] Cavium, Inc. All rights reserved. */
/* Unpublished - rights reserved under the Copyright Laws of the */
/* United States. Use, duplication, or disclosure by the */
/* Government is subject to restrictions as set forth in */
/* subparagraph (c)(1)(ii) of the Rights in Technical Data and */
/* Computer Software clause at 252.227-7013. */
/************************************************************************/
/**
* \file openXpsAclIdMgr.h
* \brief This file contains API prototypes and type definitions
* for the ACL ID allocator
*
*/
#ifndef _openXpsAclIdMgr_h_
#define _openXpsAclIdMgr_h_
#include "openXpsTypes.h"
#include "openXpsEnums.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Some variables explanation:
* AclId - Access Control List Id
*/
/**
* \brief API to allocate AclId
*
* \param [in] devId
* \param [out] aclId
*
* \return XP_STATUS
*/
XP_STATUS xpsAclIdAllocEntry(xpsDevice_t devId, uint8_t* aclId);
/**
* \brief API to free AclId
*
* \param [in] devId
* \param [in] aclId
*
* \return XP_STATUS
*/
XP_STATUS xpsAclIdFreeEntry(xpsDevice_t devId, uint8_t aclId);
#ifdef __cplusplus
}
#endif
#endif // _openXpsAclIdMgr_h_
|
XPliant/OpenXPS
|
include/openXpsMac.h
|
<reponame>XPliant/OpenXPS<gh_stars>10-100
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* All Rights Reserved.
*
* 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.
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATIONS ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*
* FILE : openXpsMac.h
*
* Abstract: This file defines the apis for Port MAC Management in OpenXPS.
************************************************************************/
/**
* \file openXpsMac.h
* \brief This file contains API prototypes and type definitions
* for the openXps MAC Management
* \copyright (c) 2016 Cavium Inc
*/
#ifndef _openXpsMac_h_
#define _openXpsMac_h_
#include "openXpsTypes.h"
#include "openXpsEnums.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Initialise the port group (PTG) with the speed mode
*
* \param [in] devId device Id. Valid values are 0-63
* \param [in] macNum mac number. Valid values are 0 to 32.
* \param [in] macConfig mac mode of the port
* \param [in] speed speed of the 10/100/1000Mbps modes. used when these modes are used
* \param [in] initSerdes set to 1 to reinit SerDes
* \param [in] prbsTestMode prbsTest for the underlying serdes
* \param [in] firmwareUpload upload the serdes firmware
* \param [in] fecMode Forward error correction mode. Available modes are FC and RS.
* \param [in] enableFEC set to 1 to enable FEC
*
* \return XP_STATUS
*/
XP_STATUS xpsMacPortGroupInit(xpsDevice_t devId, uint8_t macNum, xpMacConfigMode macConfig, xpSpeed speed, uint8_t initSerdes, uint8_t prbsTestMode, uint8_t firmwareUpload, xpFecMode fecMode, uint8_t enableFEC);
/**
* \brief Deinitialise the port group
*
* \param [in] devId device Id. Valid values are 0-63
* \param [in] macNum mac number. Valid values are 0 to 32.
*
* \return XP_STATUS
*/
XP_STATUS xpsMacPortGroupDeInit(xpsDevice_t devId, uint8_t macNum);
/**
* \brief Change the MAC mode
*
* This method assumes that all existing ports are deleted for given MAC,
* and performs the mode change sequence
*
* \param [in] devId device Id. Valid values are 0-63
* \param [in] macNum Mac number. Valid values are 0 to 32.
* \param [in] newMode enum specifying mac configuration mode
* \param [in] fecMode enum specifying the FEC mode, if enabled
* \param [in] enableFEC enable FEC mode
*
* \return XP_STATUS
*/
XP_STATUS xpsMacSwitchMacConfigMode(xpsDevice_t devId, uint8_t macNum, xpMacConfigMode newMode, xpFecMode fecMode, uint8_t enableFEC);
/**
* \brief To get mac mode of port
*
* \param [in] devId device id. Valid values are 0-63
* \param [in] portNum Port number. Valid values are 0 to 127 and 176.
* \param [out] macConfigMode - mac mode
*
* \return XP_STATUS
*/
XP_STATUS xpsMacConfigModeGet(xpDevice_t devId, uint8_t portNum, xpMacConfigMode *macConfigMode);
/**
* \brief Get MAC number mapping for a specific port number
*
* \param [in] devId device Id. Valid values are 0-63
* \param [in] portNum Port number. Valid values are 0 to 127.
* \param [out] macNum Mac number. Valid values are 0 to 32.
*
* \return XP_STATUS
*/
XP_STATUS xpsMacGetMacNumForPortNum(xpsDevice_t devId, uint8_t portNum, uint8_t *macNum);
/**
* \brief Serdes Tuning
* \param [in] devId device Id. Valid values are 0-63
* \param [in] portList List of ports associated with the serdes to tune
* \param [in] numOfPort Number of ports to tune
* \param [in] tuneMode DFE serdes tuning type
* \param [in] force Force serdes tuning
*
* \return XP_STATUS
*/
XP_STATUS xpsMacPortSerdesTune(xpsDevice_t devId, xpsPort_t *portList, uint32_t numOfPort, xpSerdesDfeTuneMode_t tuneMode, uint8_t force);
/**
* \brief Port Serdes Dfe Wait
*
* \param [in] devId device Id. Valid values are 0-63
* \param [in] portNum Port number. Valid values are 0 to 127.
*
* \return XP_STATUS
*/
XP_STATUS xpsMacPortSerdesDfeWait(xpsDevice_t devId, xpsPort_t portNum);
/**
* \brief Read port serder status and determine if it is ready for tuning
*
* \param [in] devId device Id. Valid values are 0-63
* \param [in] portNum Port number. Valid values are 0 to 127.
*
* \return XP_STATUS
*/
XP_STATUS xpsMacPortSerdesTuneConditionGet(xpsDevice_t devId, xpsPort_t portNum);
/**
* \brief Check whether a specific port is initialized
* \param [in] devId device Id. Valid values are 0-63
* \param [in] portNum Port number. Valid values are 0 to 127.
*
* \return XP_STATUS
*/
XP_STATUS xpsIsPortInited(xpsDevice_t devId, uint8_t portNum);
/**
* \brief Check whether a specific port is valid
* \param [in] devId device Id. Valid values are 0-63
* \param [in] portNum Port number. Valid values are 0 to 127.
* \param [out] *valid - Port valid or not
*
* \return XP_STATUS
*/
XP_STATUS xpsMacIsPortNumValid(xpsDevice_t devId, uint8_t portNum, uint8_t *valid);
/**
* \brief Enable or Disable a given range of ports
* \param [in] devId device Id. Valid values are 0-63
* \param [in] portNum Port number. Valid values are 0 to 127.
* \param [in] enable true to enable the port, false to disable the port
*
* \return XP_STATUS
*/
XP_STATUS xpsMacPortEnable(xpsDevice_t devId, uint8_t portNum, uint8_t enable);
/**
* \brief Controls the MRU acceptance frame length for a specifoc port
* \param [in] devId device Id. Valid values are 0-63
* \param [in] portNum Port number. Valid values are 0 to 127.
* \param [in] frameSize MRU allowance frame length
*
* \return XP_STATUS
*/
XP_STATUS xpsMacSetRxMaxFrmLen(xpsDevice_t devId, uint8_t portNum, uint16_t frameSize);
/**
* \brief Get the speed for a specific port
*
* This API gets the port speed from Hardware or from
* the stored value xpSerdes / xpExtPhyPort class
* \param [in] devId device Id. Valid values are 0-63
* \param [in] portNum Port number. Valid values are 0 to 127.
* \param [out] speed - Enum specifies the port speed
*
* \return XP_STATUS
*/
XP_STATUS xpsMacGetPortSpeed(xpsDevice_t devId, uint8_t portNum, xpSpeed *speed);
/**
* \brief Get the Auto-negotiation status for a specific port
*
* \param [in] devId device Id. Valid values are 0-63
* \param [in] portNum Port number. Valid values are 0 to 127.
* \param [out] status - Enum specifies the the status of auto-negotiation setting
*
* \return XP_STATUS
*/
XP_STATUS xpsMacGetPortAutoNegEnable(xpsDevice_t devId, uint8_t portNum, uint8_t *status);
/**
* \brief DeRegister event handler for ports
* previously registered with eventHandlerDeRegister
*
* \param [in] devId device Id. Valid values are 0-63
* \param [in] portNum Port number. Valid values are 0 to 127.
* \param [in] eventType event type to be de-registered
*
* \return XP_STATUS
*/
XP_STATUS xpsMacEventHandlerDeRegister(xpsDevice_t devId, uint8_t portNum, xpEventType eventType);
/**
* \brief Register event handler for ports
*
* \param [in] devId device Id. Valid values are 0-63
* \param [in] portNum Port number. Valid values are 0 to 127.
* \param [in] eventType event type to be registered
* \param [in] eventHandler event type to be registered
*
* \return XP_STATUS
*/
XP_STATUS xpsMacEventHandlerRegister(xpsDevice_t devId, uint8_t portNum, xpEventType eventType, xpEventHandler eventHandler);
/**
* \brief Get MAC MIB counters statistics in xpStatistics structure for a specific port
*
* \param [in] devId device Id. Valid values are 0-63
* \param [in] portNum Port number. Valid values are 0 to 127.
* \param [in] fromStatNum Start collecting statistics from this number. Valid values are 0-31
* \param [in] toStatNum Collect statistics till this number. Valid values are 0-31
* \param [out] stat a structure which holds MAC MIB statistics of a port. Only statistics of counters which falls in range of fromStatNum to toStatNum will be updated.
*
* \return XP_STATUS
*/
XP_STATUS xpsMacGetCounterStats(xpsDevice_t devId, uint8_t portNum, uint8_t fromStatNum, uint8_t toStatNum, xp_Statistics *stat);
/**
* \brief Get the link status for a specific port
*
* \param [in] devId device Id. Valid values are 0-63
* \param [in] portNum Port number. Valid values are 0 to 127.
* \param [out] status Link status
*
* \return XP_STATUS
*/
XP_STATUS xpsMacGetLinkStatus(xpsDevice_t devId, uint8_t portNum, uint8_t *status);
/**
* \brief Get the MRU acceptance frame length configuration for a specific port
*
* \param [in] devId device Id. Valid values are 0-63
* \param [in] portNum Port number. Valid values are 0 to 127.
* \param [out] frameSize MRU acceptance frame length configuration for a specific port
*
* \return XP_STATUS
*/
XP_STATUS xpsMacGetRxMaxFrmLen(xpsDevice_t devId, uint8_t portNum, uint16_t *frameSize);
/**
* \public
* \brief To Override the serdes signal with serdesSignalVal which is going inside the port
* How it operate :
* - In case of 100G,40G all four serdes will override
* - In case of 50G, Two serdes per port will override
* - In case of 10G,25G, Single serdes per port will override
*
* \param [in] devId device Id. Valid values are 0-63
* \param [in] portNum Port number. Valid values are 0-127
* \param [in] serdesSignalVal. 0: Normal operation 1: inverted (not available in A0) 2: serdes ok to 0 going to pcs 3: serdes to 1 going in pcs
*
* \return XP_STATUS On success XP_NO_ERR
*/
XP_STATUS xpsMacPortSerdesSignalOverride(xpDevice_t devId, uint8_t portNum, uint8_t serdesSignalVal);
#ifdef __cplusplus
}
#endif
#endif // _openXpsMac_h_
|
XPliant/OpenXPS
|
xpnet/src/xp_netdev_intf.c
|
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* 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; version 2
* of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* A copy of the GNU General Public License, version 2 is available in the file
* named LICENSE-GPLv2.md either in this directory or its root.
* Alernatively to obtain a copy, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* File: xp_netdev_intf.c
*
* Abstract: This file contains the netdev interface implementation required
* for xpliant.
************************************************************************/
#include "xp_common.h"
#include "xp_export.h"
#include <linux/list.h>
#include <linux/hash.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/inet.h>
#include <linux/rwsem.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/version.h>
#include <linux/seq_file.h>
#include <linux/netdevice.h>
#include <net/netns/generic.h>
#include <linux/hashtable.h>
#define XP_VIF_TO_HASH(x) (x)
#define XP_NO_VIF -1
#define XP_NO_RIF -1
#define XP_CB_TX_PORT 5555
#define XP_HASH_BITS 8
#define XP_NETLINK_USER 31
#define XP_INVALID_TRAP_ID -1
#define XP_MAX_REASON_CODE 803
#define XP_MAX_TRAP_ID 0x5000
#define XP_MIN_FP_INTF 0
#define XP_MAX_FP_INTF 128
#define XP_MIN_LAG_INTF 4096
#define XP_MAX_LAG_INTF 5019
#define XP_OFFSET_BD_INTF 65536
#define XP_NUM_RP_INTF 16384
#define XP_MAX_BD_INTF (XP_OFFSET_BD_INTF + XP_NUM_RP_INTF)
typedef struct xp_trap_config
{
unsigned int fd; /* File descriptor */
unsigned int rc; /* Reason code */
unsigned int trap_id; /* Trap ID */
unsigned int rx_count; /* Rx packets counter */
struct socket *sock_ptr; /* User space socket */
xp_nl_hostif_trap_channel_t ch; /* Host interface channel */
} xp_trap_config_t;
typedef struct xp_trap_table {
spinlock_t lock;
struct xp_trap_config *trap[XP_MAX_TRAP_ID + 1];
unsigned int rc_map[XP_MAX_REASON_CODE + 1];
} xp_trap_table_t;
struct xp_pernet {
struct sock *nlsk;
};
typedef enum xp_netdev_type {
XP_FP_NETDEV=0,
XP_ROUTER_NETDEV,
XP_LAG_NETDEV
} xp_netdev_type;
struct xp_netdev_priv {
unsigned int xpnet_intf_id;
union {
unsigned int vif;
unsigned int rif;
};
xphTxHdr tx_header;
struct list_head list;
struct hlist_node hlist;
struct net_device *netdev;
unsigned int is_tx_header_set;
xp_netdev_type netdev_type;
rwlock_t netdev_priv_lock;
};
struct xp_skb_info {
unsigned int rc; /* Reason code */
unsigned int rif_id; /* Ingress router interaface */
unsigned int intf_id; /* Ingress interface */
unsigned int port_num; /* Ingress port number */
struct sk_buff *skb; /* Socket buffer the info belongs to */
};
extern netdev_tx_t xpnet_start_xmit(struct sk_buff *skb,
xpnet_private_t *net_priv);
static LIST_HEAD(xp_netdev_list);
static DEFINE_RWLOCK(xp_netdev_list_lock);
/* Active netdev table. */
static DEFINE_HASHTABLE(xp_active_netdev_htable, XP_HASH_BITS);
/* Serialize requests from userspace. */
static DEFINE_MUTEX(xp_netlink_mutex);
/* Per-network key. */
static int xp_pernet_id;
/* Debug flag. */
static int xp_debug;
/* Sign up on network namespace notifications. */
static int xp_netlink_sock_init(void);
/* Deregister network namespace notifications. */
static void xp_netlink_sock_deinit(void);
static u8 XP_ETH_ADDR_HIGH[3] = {0x08, 0x23, 0x56};
static xp_trap_table_t *trap_table;
static struct socket *cb_sock_ptr;
static struct socket *client_socket;
/* Packet mirroring to socket. */
static int packet_mirroring_enable;
static void xp_rx_skb_dump(struct sk_buff *skb)
{
if (xp_debug) {
#if 0
print_hex_dump_debug("RX: ", DUMP_PREFIX_NONE,
16, 1, skb->data, skb->len, true);
#endif
}
}
static int xp_trap_init(void)
{
unsigned int i = 0;
DBG("Enter: %s\n", __FUNCTION__);
trap_table = kmalloc(sizeof(xp_trap_table_t), GFP_ATOMIC);
if (!trap_table) {
return -ENOMEM;
}
for (i = 0; i < ARRAY_SIZE(trap_table->rc_map); i++) {
trap_table->rc_map[i] = XP_INVALID_TRAP_ID;
}
for (i = 0; i < ARRAY_SIZE(trap_table->trap); i++) {
trap_table->trap[i] = NULL;
}
spin_lock_init(&trap_table->lock);
return 0;
}
static void xp_trap_deinit(void)
{
unsigned int i = 0;
unsigned long flags = 0;
DBG("Enter: %s\n", __FUNCTION__);
spin_lock_irqsave(&trap_table->lock, flags);
for (i = 0; i < ARRAY_SIZE(trap_table->trap); i++) {
if (trap_table->trap[i]) {
trap_table->rc_map[trap_table->trap[i]->rc] = XP_INVALID_TRAP_ID;
kfree(trap_table->trap[i]);
trap_table->trap[i] = NULL;
}
}
spin_unlock_irqrestore(&trap_table->lock, flags);
kfree(trap_table);
trap_table = NULL;
}
static struct xp_trap_config* xp_trap_config_get(unsigned int id)
{
unsigned long flags = 0;
xp_trap_config_t *trap_cfg = NULL;
spin_lock_irqsave(&trap_table->lock, flags);
trap_cfg = (id >= ARRAY_SIZE(trap_table->trap)) ?
NULL : trap_table->trap[id];
spin_unlock_irqrestore(&trap_table->lock, flags);
return trap_cfg;
}
static unsigned int xp_trap_id_get(unsigned int rc)
{
unsigned int trap_id = 0;
unsigned long flags = 0;
spin_lock_irqsave(&trap_table->lock, flags);
trap_id = (rc >= ARRAY_SIZE(trap_table->rc_map)) ?
XP_INVALID_TRAP_ID : trap_table->rc_map[rc];
spin_unlock_irqrestore(&trap_table->lock, flags);
return trap_id;
}
static int xp_trap_id_entry_add(xp_trap_config_t *cfg)
{
unsigned long flags = 0;
xp_trap_config_t *trap_cfg = NULL;
DBG("Enter: %s\n", __FUNCTION__);
if (cfg->trap_id > XP_MAX_TRAP_ID) {
return -ESPIPE;
}
trap_cfg = kmalloc(sizeof(xp_trap_config_t), GFP_ATOMIC);
if (!trap_cfg) {
return -ENOMEM;
}
memcpy(trap_cfg, cfg, sizeof(xp_trap_config_t));
spin_lock_irqsave(&trap_table->lock, flags);
trap_table->rc_map[trap_cfg->rc] = trap_cfg->trap_id;
if (trap_table->trap[trap_cfg->trap_id]){
kfree(trap_table->trap[trap_cfg->trap_id]);
}
trap_table->trap[trap_cfg->trap_id] = trap_cfg;
spin_unlock_irqrestore(&trap_table->lock, flags);
return 0;
}
static int xp_trap_id_entry_remove(unsigned int trap_id)
{
unsigned long flags = 0;
DBG("Enter: %s\n", __FUNCTION__);
if (trap_id > XP_MAX_TRAP_ID) {
return -ESPIPE;
}
if (trap_table->trap[trap_id]) {
spin_lock_irqsave(&trap_table->lock, flags);
kfree(trap_table->trap[trap_id]);
trap_table->trap[trap_id] = NULL;
spin_unlock_irqrestore(&trap_table->lock, flags);
}
return 0;
}
static int xp_ndo_open(struct net_device *dev)
{
DBG("Enter: %s\n", __FUNCTION__);
netif_start_queue(dev);
return 0;
}
static int xp_ndo_stop(struct net_device *dev)
{
DBG("Enter: %s\n", __FUNCTION__);
netif_stop_queue(dev);
return 0;
}
static netdev_tx_t xp_ndo_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
netdev_tx_t rc = NETDEV_TX_OK;
xphTxHdr *tx_header = NULL;
unsigned int new_skb_used = 0;
unsigned int tx_header_len = sizeof(xphTxHdr);
unsigned int headroom = skb_headroom(skb);
struct sk_buff *new_skb = NULL;
struct xp_netdev_priv *priv = NULL;
unsigned long flags = 0;
if (!(dev->flags & IFF_UP)) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
priv = netdev_priv(dev);
/* Check if we have headroom to add xp tx header else allocate. */
if (headroom < tx_header_len) {
/* If called in interrupt shd be changed to GFP_ATOMIC. */
new_skb = skb_copy_expand(skb, tx_header_len, 0, GFP_ATOMIC);
new_skb_used = 1;
}
/* skb->data will point to xp tx header */
if (new_skb_used) {
tx_header = (xphTxHdr *)skb_push(new_skb, tx_header_len);
/* copy xp txheader. Read lock on entry */
read_lock_irqsave(&priv->netdev_priv_lock, flags);
memcpy(tx_header, &priv->tx_header, sizeof(xphTxHdr));
read_unlock_irqrestore(&priv->netdev_priv_lock, flags);
rc = xpnet_start_xmit(new_skb, g_net_priv);
} else {
tx_header = (xphTxHdr *)skb_push(skb, tx_header_len);
/* copy xp txheader. Read lock on entry */
read_lock_irqsave(&priv->netdev_priv_lock, flags);
memcpy(tx_header, &priv->tx_header, sizeof(xphTxHdr));
read_unlock_irqrestore(&priv->netdev_priv_lock, flags);
rc = xpnet_start_xmit(skb, g_net_priv);
}
if (rc == NETDEV_TX_OK) {
/*
* Case A:
* ->dma error - upper proctocol retries.
* Case 1(newSkb used): newSkb is freed by xpnet_start_xmit.
* We need to free skb here.
* Case 2(newSkb not used):
* If we used fpNet skb, then free is handled xpnet_start_xmit.
* No action reqd.
* Case B:
* ->trasmit success.
* Case 1(newSkb used): Packet free(newSkb) is handled in
* xpnet_start_xmit..
* No need of our fp skb buffer. So we free it right here in
* case we allocated a new one.
* Case 2(newSkb not used): If we used fnet skb, free is
* already handled. No action reqd.
*/
if (new_skb_used) {
dev_kfree_skb_any(skb);
}
dev->stats.tx_packets++;
} else if (rc == NETDEV_TX_BUSY) {
/* DMA is busy. IT cant handle more packets. We
* also inform to kernel.
* Kernel retries packet after wake queue, so no freeing of fp
* skb.xpnet_start_xmit also doesnot free skb. Case 1(newSkb used):
* But we free the expanded skb as it gets allocated again once
* kernel retries. Mapping this skb(fpnetdev) with expanded
* skb is not handled now(optimised soln). Case 2:(newSkb not
* used): fp skb alloced by kernel. we dont free it(kernel
* retry). */
if (new_skb_used) {
dev_kfree_skb_any(new_skb);
}
netif_stop_queue(dev);
}
return rc;
}
static int xp_ndo_set_mac_address(struct net_device *dev, void *p)
{
struct sockaddr *addr = p;
DBG("Enter: %s\n", __FUNCTION__);
memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);
DBG("%s: changed MAC to %pM for interface %u\n",
dev->name, dev->dev_addr,
((struct xp_netdev_priv *)netdev_priv(dev))->xpnet_intf_id);
return 0;
}
static struct net_device_ops xp_ndo = {
.ndo_open = xp_ndo_open,
.ndo_stop = xp_ndo_stop,
.ndo_change_mtu = eth_change_mtu,
.ndo_start_xmit = xp_ndo_start_xmit,
.ndo_set_mac_address = xp_ndo_set_mac_address,
};
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,15,0)
static void xp_packet_send(struct sock *sk)
#else
static void xp_packet_send(struct sock *sk, int bytes)
#endif
{
struct sk_buff *skb = skb_dequeue(&sk->sk_receive_queue);
if (skb) {
skb_pull(skb, 8); /* Strip UDP header */
if (NETDEV_TX_BUSY == xpnet_start_xmit(skb, g_net_priv)) {
ERR("DMA is busy...\n");
}
}
}
static void xp_netdev_all_remove(void)
{
struct list_head *iter = NULL;
struct list_head *iter_safe = NULL;
unsigned long flags = 0;
DBG("Enter: %s\n", __FUNCTION__);
write_lock_irqsave(&xp_netdev_list_lock, flags);
list_for_each_safe(iter, iter_safe, &xp_netdev_list) {
struct xp_netdev_priv *entry =
list_entry(iter, struct xp_netdev_priv, list);
LOG("Removed netdev interface, xpnet_id: %u\n",
entry->xpnet_intf_id);
hash_del(&entry->hlist);
list_del(&entry->list);
unregister_netdev(entry->netdev);
free_netdev(entry->netdev);
}
write_unlock_irqrestore(&xp_netdev_list_lock, flags);
}
static void xp_netdev_setup(struct net_device *dev)
{
DBG("Enter: %s\n", __FUNCTION__);
ether_setup(dev);
memset(netdev_priv(dev), 0, sizeof(struct xp_netdev_priv));
dev->netdev_ops = &xp_ndo;
/* Set XP MAC prefix */
memcpy(dev->dev_addr, XP_ETH_ADDR_HIGH, sizeof(XP_ETH_ADDR_HIGH));
}
static int xp_nl_msg_if_create(struct net *netns, xp_nl_msg_intf_t *intf_msg)
{
struct list_head *iter = NULL;
struct net_device *netdev = NULL;
struct xp_netdev_priv *priv = NULL;
unsigned long flags = 0;
DBG("Enter: %s\n", __FUNCTION__);
write_lock_irqsave(&xp_netdev_list_lock, flags);
list_for_each(iter, &xp_netdev_list) {
struct xp_netdev_priv *entry =
list_entry(iter, struct xp_netdev_priv, list);
if (entry->xpnet_intf_id == intf_msg->xpnet_intf_id) {
ERR("Specifed interface already exists, "
"intf name: %s, xpnet_id: %u\n",
intf_msg->intf_name, intf_msg->xpnet_intf_id);
write_unlock_irqrestore(&xp_netdev_list_lock, flags);
return 0;
}
}
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,19,0)
netdev = alloc_netdev(sizeof(struct xp_netdev_priv),
intf_msg->intf_name, xp_netdev_setup);
#else
netdev = alloc_netdev(sizeof(struct xp_netdev_priv), intf_msg->intf_name,
NET_NAME_UNKNOWN, xp_netdev_setup);
#endif
/* Move the interface to the specified network namespace. */
dev_net_set(netdev, netns);
priv = netdev_priv(netdev);
memset(priv, 0x00, sizeof(struct xp_netdev_priv));
priv->xpnet_intf_id = intf_msg->xpnet_intf_id;
rwlock_init(&priv->netdev_priv_lock);
priv->vif = XP_NO_VIF;
priv->rif = XP_NO_RIF;
priv->netdev = netdev;
if (0 > register_netdev(netdev)) {
ERR("Could not register netdev, intf name: %s, xpnet_id: %u\n",
intf_msg->intf_name, intf_msg->xpnet_intf_id);
free_netdev(netdev);
write_unlock_irqrestore(&xp_netdev_list_lock, flags);
return -EPERM;
}
list_add(&priv->list, &xp_netdev_list);
LOG("Registered a new netdev, intf name: %s, xpnet_id: %u\n",
intf_msg->intf_name, intf_msg->xpnet_intf_id);
write_unlock_irqrestore(&xp_netdev_list_lock, flags);
return 0;
}
static int xp_nl_msg_if_delete(struct net *netns, xp_nl_msg_intf_t *intf_msg)
{
struct list_head *iter = NULL;
unsigned long flags = 0;
DBG("Enter: %s\n", __FUNCTION__);
write_lock_irqsave(&xp_netdev_list_lock, flags);
list_for_each(iter, &xp_netdev_list) {
struct xp_netdev_priv *entry =
list_entry(iter, struct xp_netdev_priv, list);
if (entry->xpnet_intf_id == intf_msg->xpnet_intf_id) {
LOG("Removed netdev interface, xpnet_id: %u\n",
intf_msg->xpnet_intf_id);
hash_del(&entry->hlist);
list_del(&entry->list);
unregister_netdev(entry->netdev);
free_netdev(entry->netdev);
goto out;
}
}
ERR("Tried to remove interface but it wasn't found, xpnet_id: %u\n",
intf_msg->xpnet_intf_id);
out:
write_unlock_irqrestore(&xp_netdev_list_lock, flags);
return 0;
}
static int xp_nl_msg_if_link(struct net *netns, xp_nl_msg_link_t *link_msg)
{
struct list_head *iter = NULL;
unsigned long flags = 0;
DBG("Enter: %s\n", __FUNCTION__);
write_lock_irqsave(&xp_netdev_list_lock, flags);
list_for_each(iter, &xp_netdev_list) {
struct xp_netdev_priv *entry =
list_entry(iter, struct xp_netdev_priv, list);
if (entry->xpnet_intf_id == link_msg->xpnet_intf_id) {
if ((XP_NO_VIF != entry->vif) || (XP_NO_RIF != entry->rif)) {
ERR("Tried to link interface which has "
"been already linked, xpnet_id: %u, vif: %u, rif: %u\n",
entry->xpnet_intf_id, entry->vif, entry->rif);
break;
}
if ((XP_MIN_FP_INTF <= link_msg->vif) &&
(link_msg->vif < XP_MAX_FP_INTF)) {
LOG("Added netdev interface link, xpnet_id: %u, vif: %u\n",
link_msg->xpnet_intf_id, link_msg->vif);
entry->netdev_type = XP_FP_NETDEV;
entry->vif = link_msg->vif;
hash_add(xp_active_netdev_htable,
&entry->hlist, XP_VIF_TO_HASH(entry->vif));
} else if ((XP_OFFSET_BD_INTF <= link_msg->rif) &&
(link_msg->rif < XP_MAX_BD_INTF)) {
LOG("Added netdev interface link, xpnet_id: %u, rif: %u\n",
link_msg->xpnet_intf_id, link_msg->rif);
entry->rif = link_msg->rif;
entry->netdev_type = XP_ROUTER_NETDEV;
hash_add(xp_active_netdev_htable,
&entry->hlist, XP_VIF_TO_HASH(entry->rif));
} else if ((XP_MIN_LAG_INTF <= link_msg->vif) &&
(link_msg->vif < XP_MAX_LAG_INTF)) {
LOG("Added netdev interface link, xpnet_id: %u, lag vif: %u\n",
link_msg->xpnet_intf_id, link_msg->vif);
entry->vif = link_msg->vif;
entry->netdev_type = XP_LAG_NETDEV;
hash_add(xp_active_netdev_htable,
&entry->hlist, XP_VIF_TO_HASH(entry->vif));
} else {
ERR("Tried to link unknown type of interfaces, "
"xpnet_id: %u, vif: %u, rif: %u\n",
link_msg->xpnet_intf_id, link_msg->vif, link_msg->rif);
}
break;
}
}
write_unlock_irqrestore(&xp_netdev_list_lock, flags);
return 0;
}
static int xp_nl_msg_if_unlink(struct net *netns, xp_nl_msg_link_t *link_msg)
{
struct list_head *iter = NULL;
unsigned long flags = 0;
DBG("Enter: %s\n", __FUNCTION__);
write_lock_irqsave(&xp_netdev_list_lock, flags);
list_for_each(iter, &xp_netdev_list) {
struct xp_netdev_priv *entry =
list_entry(iter, struct xp_netdev_priv, list);
if (entry->xpnet_intf_id == link_msg->xpnet_intf_id) {
LOG("Removed netdev interface link, xpnet_id: %u\n",
link_msg->xpnet_intf_id);
hash_del(&entry->hlist);
entry->vif = XP_NO_VIF;
entry->rif = XP_NO_RIF;
break;
}
}
write_unlock_irqrestore(&xp_netdev_list_lock, flags);
return 0;
}
static int xp_nl_msg_tx_header(struct net *netns,
xp_nl_msg_tx_hdr_t *tx_header_msg)
{
struct list_head *iter = NULL;
unsigned long flags = 0;
DBG("Enter: %s\n", __FUNCTION__);
/* Read lock only */
read_lock_irqsave(&xp_netdev_list_lock, flags);
list_for_each(iter, &xp_netdev_list) {
struct xp_netdev_priv *entry =
list_entry(iter, struct xp_netdev_priv, list);
if (entry->xpnet_intf_id == tx_header_msg->xpnet_intf_id) {
write_lock_irqsave(&entry->netdev_priv_lock, flags);
if (XP_NL_OPERATION_ADD == tx_header_msg->operation) {
LOG("Set TX header for netdev interface, xpnet_id: %u\n",
tx_header_msg->xpnet_intf_id);
/* write lock on entry only */
memcpy(&entry->tx_header,
&tx_header_msg->tx_header, sizeof(xphTxHdr));
entry->is_tx_header_set = 1;
} else if (XP_NL_OPERATION_REMOVE == tx_header_msg->operation) {
LOG("Remove TX header for netdev interface, xpnet_id: %u\n",
tx_header_msg->xpnet_intf_id);
/* write lock on entry only */
memset(&entry->tx_header, 0x00, sizeof(xphTxHdr));
entry->is_tx_header_set = 0;
}
write_unlock_irqrestore(&entry->netdev_priv_lock, flags);
break;
}
}
read_unlock_irqrestore(&xp_netdev_list_lock, flags);
return 0;
}
static int xp_nl_msg_trap(struct net *netns, xp_nl_msg_trap_t *trap_msg)
{
unsigned int rc = 0;
xp_trap_config_t trap_cfg = { 0 };
DBG("Enter: %s\n", __FUNCTION__);
if (XP_NL_OPERATION_ADD == trap_msg->operation) {
if (XP_MAX_REASON_CODE < trap_msg->rc) {
ERR("Reason code %u is out of range.\n", trap_msg->rc);
return -ESPIPE;
}
trap_cfg.sock_ptr = NULL;
trap_cfg.rx_count = 0;
trap_cfg.trap_id = trap_msg->trap_id;
trap_cfg.rc = trap_msg->rc;
trap_cfg.fd = trap_msg->fd;
trap_cfg.ch = trap_msg->ch;
if (XP_NL_HOSTIF_TRAP_FD == trap_cfg.ch) {
trap_cfg.sock_ptr = sockfd_lookup(trap_cfg.fd, &rc);
}
xp_trap_id_entry_add(&trap_cfg);
} else if (XP_NL_OPERATION_REMOVE == trap_msg->operation) {
xp_trap_id_entry_remove(trap_msg->trap_id);
}
return 0;
}
static int xp_nl_msg_cb_fd(struct net *netns, xp_nl_msg_cb_fd_t *cb_fd_msg)
{
int rc = 0;
DBG("Enter: %s\n", __FUNCTION__);
if (!(cb_sock_ptr = sockfd_lookup(cb_fd_msg->fd, &rc))) {
ERR("Unable to get a callback for FD: %u\n", cb_fd_msg->fd);
}
return rc;
}
static int xp_nl_msg_mirror(struct net *netns, xp_nl_msg_mirror_t *mirror_msg)
{
DBG("Enter: %s\n", __FUNCTION__);
if ((XP_NL_OPERATION_ENABLE == mirror_msg->operation) ||
(XP_NL_OPERATION_DISABLE == mirror_msg->operation)) {
packet_mirroring_enable = (XP_NL_OPERATION_ENABLE ==
mirror_msg->operation) ? 1 : 0;
LOG("Packet mirroring: %u\n", packet_mirroring_enable);
}
return 0;
}
static int xp_nl_msg_process(struct net *netns, void *nl_msg_payload)
{
unsigned int offset = 0;
xp_nl_tlv_msg_t main_tlv_header;
DBG("Enter: %s\n", __FUNCTION__);
memcpy(&main_tlv_header, nl_msg_payload, sizeof(xp_nl_tlv_msg_t));
offset += sizeof(xp_nl_tlv_msg_t);
main_tlv_header.payload_len += sizeof(xp_nl_tlv_msg_t);
while (main_tlv_header.payload_len) {
xp_nl_msg_t msg_type;
memcpy(&msg_type,
(uint8_t *)nl_msg_payload + offset, sizeof(xp_nl_msg_t));
offset += sizeof(xp_nl_msg_t);
switch (msg_type) {
case XP_NL_MSG_INTF_ADD:
{
xp_nl_msg_intf_t msg;
memcpy(&msg, nl_msg_payload + offset, sizeof(msg));
xp_nl_msg_if_create(netns, &msg);
offset += sizeof(msg);
}
break;
case XP_NL_MSG_INTF_DEL:
{
xp_nl_msg_intf_t msg;
memcpy(&msg, nl_msg_payload + offset, sizeof(msg));
xp_nl_msg_if_delete(netns, &msg);
offset += sizeof(msg);
}
break;
case XP_NL_MSG_LINK_ADD:
{
xp_nl_msg_link_t msg;
memcpy(&msg, nl_msg_payload + offset, sizeof(msg));
xp_nl_msg_if_link(netns, &msg);
offset += sizeof(msg);
}
break;
case XP_NL_MSG_LINK_DEL:
{
xp_nl_msg_link_t msg;
memcpy(&msg, nl_msg_payload + offset, sizeof(msg));
xp_nl_msg_if_unlink(netns, &msg);
offset += sizeof(msg);
}
break;
case XP_NL_MSG_TX_HDR_SET:
{
xp_nl_msg_tx_hdr_t msg;
memcpy(&msg, nl_msg_payload + offset, sizeof(msg));
xp_nl_msg_tx_header(netns, &msg);
offset += sizeof(msg);
}
break;
case XP_NL_MSG_TRAP_SET:
{
xp_nl_msg_trap_t msg;
memcpy(&msg, nl_msg_payload + offset, sizeof(msg));
xp_nl_msg_trap(netns, &msg);
offset += sizeof(msg);
}
break;
case XP_NL_MSG_CB_FD_SET:
{
xp_nl_msg_cb_fd_t msg;
memcpy(&msg, nl_msg_payload + offset, sizeof(msg));
xp_nl_msg_cb_fd(netns, &msg);
offset += sizeof(msg);
}
break;
case XP_NL_MSG_MIRROR_SET:
{
xp_nl_msg_mirror_t msg;
memcpy(&msg, nl_msg_payload + offset, sizeof(msg));
xp_nl_msg_mirror(netns, &msg);
offset += sizeof(msg);
}
break;
default:
return -EINVAL;
}
main_tlv_header.payload_len -= offset;
}
return 0;
}
static void xp_netlink_rcv(struct sk_buff *skb)
{ /* Receive messages from netlink socket. */
DBG("Enter: %s\n", __FUNCTION__);
mutex_lock(&xp_netlink_mutex);
xp_nl_msg_process(sock_net(skb->sk),
nlmsg_data((struct nlmsghdr *)skb->data));
mutex_unlock(&xp_netlink_mutex);
}
static struct xp_pernet* xp_pernet(struct net *net)
{ /* Get private per network parameters. */
DBG("Enter: %s\n", __FUNCTION__);
return net_generic(net, xp_pernet_id);
}
static int __net_init xp_net_init(struct net *net)
{ /* Per-network init notificator. */
struct xp_pernet *pernet = xp_pernet(net);
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,5,0)
struct netlink_kernel_cfg cfg = {
.input = xp_netlink_rcv,
};
pernet->nlsk = netlink_kernel_create(net, XP_NETLINK_USER, &cfg);
#else
pernet->nlsk = netlink_kernel_create(net, XP_NETLINK_USER,
0, xp_netlink_rcv, NULL, NULL);
#endif
DBG("Enter: %s\n", __FUNCTION__);
if (NULL == pernet->nlsk) {
ERR("Could not create netlink socket in namespace.\n");
return -ENOMEM;
}
return 0;
}
static void __net_exit xp_net_exit(struct net *net)
{ /* Per-network exit notificator. */
struct xp_pernet *pernet = xp_pernet(net);
DBG("Enter: %s\n", __FUNCTION__);
netlink_kernel_release(pernet->nlsk);
pernet->nlsk = NULL;
}
static struct pernet_operations xp_net_ops = {
.init = xp_net_init,
.exit = xp_net_exit,
.id = &xp_pernet_id,
.size = sizeof(struct xp_pernet),
};
static int xp_netlink_sock_init(void)
{ /* Sign up on network namespace notifications. */
DBG("Enter: %s\n", __FUNCTION__);
return register_pernet_subsys(&xp_net_ops);
}
static void xp_netlink_sock_deinit(void)
{ /* Deregister network namespace notifications. */
DBG("Enter: %s\n", __FUNCTION__);
unregister_pernet_subsys(&xp_net_ops);
}
static int xp_client_sock_init(void)
{
int rc = 0;
struct sockaddr_in server = { 0 };
DBG("Enter: %s\n", __FUNCTION__);
rc = sock_create(PF_INET, SOCK_DGRAM, IPPROTO_UDP, &client_socket);
if (rc < 0) {
goto err_sock_create;
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons((unsigned short) XP_CB_TX_PORT);
rc = client_socket->ops->bind(client_socket,
(struct sockaddr *)&server, sizeof(server));
if (rc < 0) {
goto err_sock_bind;
}
client_socket->sk->sk_data_ready = xp_packet_send;
return 0;
err_sock_bind:
sock_release(client_socket);
err_sock_create:
return rc;
}
static void xp_client_sock_deinit(void)
{
DBG("Enter: %s\n", __FUNCTION__);
sock_release(client_socket);
}
static void xp_rx_skb_info_get(struct sk_buff *skb, struct xp_skb_info *info)
{
unsigned int bd_id = 0;
unsigned int intf_id = 0;
xphRxHdr *rx_header = (xphRxHdr *)skb->data;
/* Ingress port number */
info->port_num = rx_header->ingressPortNum;
/* Extract ivif from packet */
intf_id = rx_header->ingressVifLsbByte2;
intf_id = intf_id << 8 | rx_header->ingressVifLsbByte1;
intf_id = intf_id << 4 | rx_header->ingressVifLsbByte0;
info->intf_id = intf_id;
/* bdId */
bd_id = rx_header->metadata.bdId[0];
bd_id = ((bd_id << 8) | rx_header->metadata.bdId[1]);
/* Router interface */
info->rif_id = (bd_id < XP_OFFSET_BD_INTF) ?
bd_id + XP_OFFSET_BD_INTF : bd_id;
/* Get skb reason code */
info->rc = (rx_header->reasonCodeMSB << 2) | rx_header->reasonCodeLsbs;
info->skb = skb;
}
static void xp_rx_netdev_skb_netif_rx(struct sk_buff *skb,
struct net_device *netdev)
{
struct sk_buff *new_skb = netdev_alloc_skb_ip_align(netdev, skb->len);
if (new_skb) {
memcpy(new_skb->data, skb->data, skb->len);
skb_put(new_skb, skb->len);
new_skb->protocol = eth_type_trans(new_skb, netdev);
new_skb->pkt_type = PACKET_HOST;
new_skb->ip_summed = CHECKSUM_UNNECESSARY;
netdev->stats.rx_bytes += skb->len;
netdev->stats.rx_packets++;
/* Send packet to kernel stack. */
netif_rx(new_skb);
}
}
static void xp_rx_skb_fd_process(struct socket *sock,
struct xp_skb_info *skb_info)
{
if (sock) {
struct iovec iov;
struct msghdr msg;
struct sockaddr_in to;
struct inet_sock *inetp = inet_sk(sock->sk);
mm_segment_t old_fs = get_fs();
/* generate answer message */
memset(&to, 0, sizeof(to));
to.sin_family = AF_INET;
to.sin_addr.s_addr = in_aton("127.0.0.1");
to.sin_port = inetp->inet_sport;
iov.iov_base = skb_info->skb->data;
iov.iov_len = skb_info->skb->len;
memset(&msg, 0, sizeof(msg));
msg.msg_name = &to;
msg.msg_namelen = sizeof(to);
msg.msg_control = NULL;
msg.msg_controllen = 0;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 19, 0)
iov_iter_init(&msg.msg_iter, WRITE, &iov, 1, skb_info->skb->len);
#else
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
#endif
/* adjust memory boundaries */
set_fs(KERNEL_DS);
#if LINUX_VERSION_CODE < KERNEL_VERSION(4,1,0)
sock_sendmsg(sock, &msg, skb_info->skb->len);
#else
sock_sendmsg(sock, &msg);
#endif
set_fs(old_fs);
DBG("Queueing packet on inet->inet_sport fd: %d\n", inetp->inet_sport);
}
}
static void xp_rx_skb_netdev_process(struct xp_skb_info *skb_info)
{
unsigned int vif = XP_NO_VIF;
unsigned int rif = skb_info->rif_id;
struct xp_netdev_priv *entry = NULL;
unsigned long flags = 0;
if (packet_mirroring_enable) {
xp_rx_skb_fd_process(cb_sock_ptr, skb_info);
}
/* Netdev interface doesn't need RX metainfo header.
So, let's remove it. */
skb_pull(skb_info->skb, sizeof(xphRxHdr));
if (((XP_MIN_FP_INTF <= skb_info->intf_id) &&
(skb_info->intf_id < XP_MAX_FP_INTF)) ||
((XP_MIN_LAG_INTF <= skb_info->intf_id) &&
(skb_info->intf_id < XP_MAX_LAG_INTF))) {
vif = skb_info->port_num;
}
if (XP_NO_VIF != vif) {
read_lock_irqsave(&xp_netdev_list_lock, flags);
hash_for_each_possible(xp_active_netdev_htable,
entry, hlist, XP_VIF_TO_HASH(vif)) {
if (entry->vif == vif) {
xp_rx_netdev_skb_netif_rx(skb_info->skb, entry->netdev);
break;
}
}
read_unlock_irqrestore(&xp_netdev_list_lock, flags);
}
read_lock_irqsave(&xp_netdev_list_lock, flags);
hash_for_each_possible(xp_active_netdev_htable,
entry, hlist, XP_VIF_TO_HASH(rif)) {
if (entry->rif == rif) {
xp_rx_netdev_skb_netif_rx(skb_info->skb, entry->netdev);
break;
}
}
read_unlock_irqrestore(&xp_netdev_list_lock, flags);
}
void xp_rx_skb_process(xpnet_private_t *priv, struct sk_buff *skb)
{
unsigned int trap_id = 0;
struct xp_skb_info skb_info = { 0 };
struct xp_trap_config *trap_cfg = NULL;
xp_rx_skb_dump(skb);
xp_rx_skb_info_get(skb, &skb_info);
priv->stats.rx_packets++;
priv->stats.rx_bytes += skb->len;
DBG("Trapped packet, RC: %u\n", skb_info.rc);
trap_id = xp_trap_id_get(skb_info.rc);
trap_cfg = xp_trap_config_get(trap_id);
/* No trap is registered then send it traffic to CB channel. */
if (trap_id == XP_INVALID_TRAP_ID || !trap_cfg) {
xp_rx_skb_fd_process(cb_sock_ptr, &skb_info);
goto out;
}
switch (trap_cfg->ch) {
case XP_NL_HOSTIF_TRAP_CB:
xp_rx_skb_fd_process(cb_sock_ptr, &skb_info);
break;
case XP_NL_HOSTIF_TRAP_FD:
xp_rx_skb_fd_process(trap_cfg->sock_ptr, &skb_info);
break;
case XP_NL_HOSTIF_TRAP_NETDEV:
xp_rx_skb_netdev_process(&skb_info);
break;
default:
goto out;
}
trap_cfg->rx_count++;
out:
dev_kfree_skb_any(skb);
}
int xp_netdev_mode_init(void)
{
int rc = 0;
DBG("Enter: %s\n", __FUNCTION__);
rc = xp_trap_init();
if (rc < 0) {
ERR("Unable to init a trap table.\n");
goto err_xp_trap_init;
}
rc = xp_netlink_sock_init();
if (rc < 0) {
ERR("Unable to create a netlink socket.\n");
goto err_xp_netlink_sock_init;
}
rc = xp_client_sock_init();
if (rc < 0) {
ERR("Unable to create a client socket.\n");
goto err_xp_sock_create;
}
return 0;
err_xp_sock_create:
xp_netlink_sock_deinit();
err_xp_netlink_sock_init:
xp_trap_deinit();
err_xp_trap_init:
return rc;
}
int xp_netdev_mode_deinit(void)
{
DBG("Enter: %s\n", __FUNCTION__);
xp_trap_deinit();
xp_netlink_sock_deinit();
xp_netdev_all_remove();
xp_client_sock_deinit();
return 0;
}
void xp_debug_set(int mode)
{
DBG("Enter: %s\n", __FUNCTION__);
xp_debug = mode;
}
void xp_netdev_print(struct seq_file *sf)
{
unsigned int backet = 0;
struct list_head *iter = NULL;
struct xp_netdev_priv *entry = NULL;
char *ch_name[] = { "FP", "ROUTER", "LAG" };
unsigned long flags = 0;
DBG("Enter: %s\n", __FUNCTION__);
seq_printf(sf,"Netdev interfaces:\n");
seq_printf(sf, "----------------------------------------------------\n");
read_lock_irqsave(&xp_netdev_list_lock, flags);
list_for_each(iter, &xp_netdev_list) {
entry = list_entry(iter, struct xp_netdev_priv, list);
seq_printf(sf," - Netdev: %8s, xpnet_id: %4u, vif/rif: %5d,"
" tx header: %u\n", entry->netdev->name,
entry->xpnet_intf_id, entry->vif,
entry->is_tx_header_set);
}
seq_printf(sf,"\nActive netdev interfaces:\n");
seq_printf(sf,"----------------------------------------------------\n");
hash_for_each(xp_active_netdev_htable, backet, entry, hlist) {
seq_printf(sf," - Netdev: %8s, type: %s, xpnet_id: %4u, vif: %5d,"
" tx header: %u\n", entry->netdev->name, ch_name[entry->netdev_type],
entry->xpnet_intf_id, entry->vif, entry->is_tx_header_set);
}
read_unlock_irqrestore(&xp_netdev_list_lock, flags);
}
void xp_netdev_tx_header_print(unsigned int xpnet_intf_id, struct seq_file *sf)
{
struct list_head *iter = NULL;
unsigned long flags = 0;
DBG("Enter: %s\n", __FUNCTION__);
seq_printf(sf,"Netdev interfaces:\n");
seq_printf(sf,"----------------------------------------------------\n");
read_lock_irqsave(&xp_netdev_list_lock, flags);
list_for_each(iter, &xp_netdev_list) {
struct xp_netdev_priv *entry =
list_entry(iter, struct xp_netdev_priv, list);
if (entry->is_tx_header_set) {
seq_printf(sf," - Netdev: %8s, xpnet_id: %4u, vif: %5d\n",
entry->netdev->name, entry->xpnet_intf_id, entry->vif);
seq_printf(sf," EVIF: B0(0x%2x) B1(0x%2x) B2(0x%2x); "
"IVIF: B0(0x%2x) B1(0x%2x) B2(0x%2x); NextEngine: 0x%2x\n\n",
entry->tx_header.egressVifLsbByte0,
entry->tx_header.egressVifLsbByte1,
entry->tx_header.egressVifLsbByte2,
entry->tx_header.ingressVifLsbByte0,
entry->tx_header.ingressVifLsbByte1,
entry->tx_header.ingressVifLsbByte2,
entry->tx_header.nextEngine);
}
}
read_unlock_irqrestore(&xp_netdev_list_lock, flags);
}
int xp_trap_table_print(struct seq_file *sf)
{
unsigned int i = 0;
unsigned long flags = 0;
xp_trap_config_t *trap_cfg = NULL;
char *ch_name[] = { "FD", "CB", "NETDEV" };
DBG("Enter: %s\n", __FUNCTION__);
seq_printf(sf,"|----------------------------------------------------|\n");
seq_printf(sf,"|TrapId| RC | Fd | Channel | SockPtr | rxPktCnt |\n");
seq_printf(sf,"|----------------------------------------------------|\n");
if (!trap_table) {
return -EPERM;
}
spin_lock_irqsave(&trap_table->lock, flags);
for (i = 0; i < ARRAY_SIZE(trap_table->trap); i++) {
trap_cfg = trap_table->trap[i];
if (trap_cfg) {
seq_printf(sf, "|%6x|%4d|%4d|%9s|%14p|%10d|\n", trap_cfg->trap_id,
trap_cfg->rc, trap_cfg->fd, ch_name[trap_cfg->ch],
trap_cfg->sock_ptr, trap_cfg->rx_count);
}
}
seq_printf(sf,"|----------------------------------------------------|\n");
seq_printf(sf,"|SockPtr for CB channel is :%17p\n", cb_sock_ptr);
seq_printf(sf,"|----------------------------------------------------|\n");
spin_unlock_irqrestore(&trap_table->lock, flags);
return 0;
}
|
XPliant/OpenXPS
|
include/openXpsInterface.h
|
<filename>include/openXpsInterface.h
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* All Rights Reserved.
*
* 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.
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATIONS ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*
* FILE : openXpsInterface.h
*
* Abstract: This file defines the apis for Interface Management in OpenXPS.
************************************************************************/
/**
* \file openXpsInterface.h
* \brief This file contains API prototypes and type definitions
* for the openXps Interface Management
* \copyright (c) 2016 Cavium Inc
*/
#ifndef _openXpsInterface_h_
#define _openXpsInterface_h_
#include "openXpsTypes.h"
#include "openXpsEnums.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \def XPS_INTF_INVALID_ID
*
* Sentinel ID used to represent an invalid value
*/
#define XPS_INTF_INVALID_ID 0xFFFFFFFFu
/**
* \def XPS_INTF_MAP_INTFID_TO_VIF(intfId)
*
* A Macro that returns VIF for a specific intfId
*/
#define XPS_INTF_MAP_INTFID_TO_VIF(intfId) ((xpVif_t)(intfId))
/**
* \def XPS_INTF_MAP_VIF_TO_INTFID(vif)
*
* A Macro to return intfId for a specific VID
*/
#define XPS_INTF_MAP_VIF_TO_INTFID(vif) ((xpsInterfaceId_t)(vif))
/**
* \brief Retrieves an interface's type information
*
* There is no set interface type API. In order to change an
* interface's type, the interface must be destroyed and
* recreated
*
* \param [in] intfId Interface ID
* \param [out] *type
*
* \return XP_STATUS
*/
XP_STATUS xpsInterfaceGetType(xpsInterfaceId_t intfId, xpsInterfaceType_e *type);
#ifdef __cplusplus
}
#endif
#endif // _openXpsInterface_h_
|
XPliant/OpenXPS
|
include/openXpsLag.h
|
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* All Rights Reserved.
*
* 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.
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATIONS ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*
* FILE : openXpsLag.h
*
* Abstract: This file defines the apis for LAG Management in OpenXPS.
************************************************************************/
/**
* \file openXpsLag.h
* \brief This file contains API prototypes and type definitions
* for the openXps LAG Management
* \copyright (c) 2016 Cavium Inc
*/
#ifndef _openXpsLag_h_
#define _openXpsLag_h_
#include "openXpsTypes.h"
#include "openXpsEnums.h"
/**
* \def XPS_LAG_MAX_PORTS
* \brief Maximum number of ports in a lag
*/
#define XPS_LAG_MAX_PORTS 128
#ifdef __cplusplus
extern "C" {
#endif
/**
* \struct xpsLagPortIntfList_t
* \brief LAG Port Interface List Structure
*/
typedef struct xpsLagPortIntfList_s
{
uint32_t size;
xpsInterfaceId_t portIntf[XPS_LAG_MAX_PORTS];
} xpsLagPortIntfList_t;
/**
* \brief Enum used to indicate whether SDK should
* automatically distribute the ports in a LAG
*/
typedef enum xpsLagAutoDistributeControl_e
{
AUTO_DIST_DISABLE = 0,
AUTO_DIST_ENABLE,
} xpsLagAutoDistributeControl_e;
/**
* \brief Create a new LAG in the system
*
* Create a new LAG Interface and associate it with an ID.
* This ID to be used to perform Lag operations and deployment
*
* This API only modifies software states. Deploy must be called
* on each device in order to commit changes to LAG
* configuration to Hardware
*
* \param [out] lagIntf LAG Interface ID
*
* \return XP_STATUS
*/
XP_STATUS xpsLagCreate(xpsInterfaceId_t *lagIntf);
/**
* \brief Destroy an existing LAG in the system
*
* Destroy an existing LAG Interface and free the associated ID.
*
* Prior to calling this API, all ports must be removed from the LAG
* Upon removing all of the LAG ports, this API must be called for
* all devices in the system
*
* Calling xpsLagDestroy without following the steps above may
* lead to an inconsistent hardware state
*
* \see xpsLagRemovePort
* \see xpsLagDeploy
*
* \param [in] lagIntf
*
* \return XP_STATUS
*/
XP_STATUS xpsLagDestroy(xpsInterfaceId_t lagIntf);
/**
* \brief Add a port to a LAG
*
* This API will add a port to a LAG. This API will only change
* the software state of the LAG Interface. xpsLagDeploy must
* be called to commit these changes
*
* \param [in] lagIntf LAG Interface ID
* \param [in] portIntf Port Interface ID
*
* \return XP_STATUS
*/
XP_STATUS xpsLagAddPort(xpsInterfaceId_t lagIntf, xpsInterfaceId_t portIntf);
/**
* \brief Remove a port from a LAG
*
* Remove a port from a LAG. This API will only change
* the software state of the Lag Interface. xpsLagDeploy
* must be called to commit these changes
*
* \param [in] lagIntf LAG Interface ID
* \param [in] portIntf Port Interface ID
*
* \return XP_STATUS
*/
XP_STATUS xpsLagRemovePort(xpsInterfaceId_t lagIntf, xpsInterfaceId_t portIntf);
/**
* \brief Commit changes made to a Lag configuration to Hardware
*
* This API is like a "repository commit". In essence, it's job
* is to perform all of the hardware writes on a per device
* basis based off of changes made to a LAG Configuration
*
* These changes include the following:
* - Creating a new Lag
* - Adding Ports to a Lag
* - Removing Ports from a Lag
*
* Lag destruction is a multi step process, and xpsLagDeploy
* plays a role by virtue of performing the writes to the
* hardware post removal of ports of a Lag
*
* \param [in] devId Device Id of device.
* \param [in] lagIntf LAG Interface ID
* \param [in] autoEnable Automatically distribute in SDK the ports in a LAG
*
* \return XP_STATUS
*/
XP_STATUS xpsLagDeploy(xpsDevice_t devId, xpsInterfaceId_t lagIntf, xpsLagAutoDistributeControl_e autoEnable);
/**
* \brief Get list of port interfaces in the LAG
*
* \param [in] lagIntf LAG Interface ID
* \param [out] portIntfList List of ports that are members in a specific LAG
*
* \return XP_STATUS
*/
XP_STATUS xpsLagGetPortIntfList(xpsInterfaceId_t lagIntf, xpsLagPortIntfList_t *portIntfList);
/**
* \brief Check if a port interface is a part of a specific
* LAG interface
*
* This API will check specific port membership in a specific LAG
*
* \param [in] portIntf Port Interface ID
* \param [in] lagIntf LAG Interface ID
* \param [out] isMember a port is a member in a specific LAG or not
*
* \return XP_STATUS
*/
XP_STATUS xpsLagIsPortIntfMember(xpsInterfaceId_t portIntf, xpsInterfaceId_t lagIntf, uint32_t *isMember);
/**
* \brief Set the hashable fields for a specific device
* \deprecated use \ref xpsGlobalSwitchControlSetHashFields
* \param [in] deviceId Device Id of device.
* \param [in] fields array of hashable fields
* \param [in] size array fields sizes
*
* \return XP_STATUS
*/
XP_STATUS xpsLagSetHashFields(xpsDevice_t deviceId, xpHashField* fields, size_t size);
/**
* \brief Pick the first available LAG interface ID available in the system
*
* \param [out] *lagIntf LAG Interface ID
*
* \return XP_STATUS
*/
XP_STATUS xpsLagGetFirst(xpsInterfaceId_t *lagIntf);
/**
* \brief Get the next available LAG interface ID available in the system
*
* \param [in] lagIntf LAG Interface ID
* \param [out] *lagIntfNext Next available LAG Interface ID
*
* \return XP_STATUS
*/
XP_STATUS xpsLagGetNext(xpsInterfaceId_t lagIntf, xpsInterfaceId_t *lagIntfNext);
#ifdef __cplusplus
}
#endif
#endif //_openXpsLag_h_
|
XPliant/OpenXPS
|
xpnet/include/xp_pcie_slave.h
|
<reponame>XPliant/OpenXPS<gh_stars>10-100
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* 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; version 2
* of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* A copy of the GNU General Public License, version 2 is available in the file
* named LICENSE-GPLv2.md either in this directory or its root.
* Alernatively to obtain a copy, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* File: xp_pcie_slave.h
*
* Abstract: This file contains the enums, macros, msg defs required for pcie
* slave component/module of this driver.
************************************************************************/
#ifndef _XP_PCIE_SLAVE_H
#define _XP_PCIE_SLAVE_H
#include "xp_reg_info.h"
#include <linux/cdev.h>
#define PROC_FS_NAME_SIZE 50
#define REG_RW_STATUS_SIZE 200
#define HIGH_INTR_SRC_REG_SIZE 5
/* Register Read/Write */
typedef struct __attribute__((__packed__)) xp_reg_rw {
u32 reg_address; /* Address to read/write */
/* 0->Write, 1->Read, Note: Direction will be
same for all contiguous access */
u8 direction;
/* Size to be read/write in bytes,
valid values are: 1,2,4 */
u32 size;
/* Value(s) to be written/read */
u64 value;
} xp_reg_rw_t;
typedef struct xp_private {
/* OS specific structure. */
struct pci_dev *pdev;
/* Mem-mapped pointer to base of chip regs. */
u64 __iomem *vma;
/* End of mem-mapped chip space excluding sendbuf and user regs. */
u64 __iomem *mmio_end;
/* Physical address of chip for io_remap, etc. */
resource_size_t mmio_start;
/* User specific structure. */
xp_reg_rw_t *pci_rw;
s64 irq;
struct workqueue_struct *w_queue;
struct device *dev;
struct cdev cdev;
s32 msi_count;
s32 msi_fail;
/* For storing xpnet_private structure. */
struct xpnet_private *xpnet;
/* Lock to make tx DMA and reg read mutual exclusive. */
spinlock_t tx_dma_read_lock;
pid_t app_pid;
struct siginfo sig_info;
/* Device type with mode(compress or uncompress). */
xp_address_mode_t mode;
/* For storing PDE entry */
struct proc_dir_entry *reg_proc;
/* For storing PDE name */
char proc_fs_name[PROC_FS_NAME_SIZE];
/* For storing reg read/write status */
char reg_rw_status[REG_RW_STATUS_SIZE];
} xp_private_t;
#endif /* _XP_PCIE_SLAVE_H */
|
XPliant/OpenXPS
|
include/openXpsTypes.h
|
/************************************************************************
* Copyright (C) 2016, Cavium, Inc.
* All Rights Reserved.
*
* 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.
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATIONS ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*
* FILE : openXpsTypes.h
*
* Abstract: This file defines the XP data types in OpenXPS.
************************************************************************/
/**
* \file openXpsTypes.h
* \brief This file contains openXps type definitions
* \copyright (c) 2016 Cavium Inc
*/
#ifndef _openXpsTypes_h
#define _openXpsTypes_h
#include "errno.h"
#include "stddef.h"
#include "stdint.h"
#include "openXpsEnums.h"
#define XP_MAX_PACKET_SIZE 10*1024 ///< Max Packet Size
#define XP_MAX_DEVICES (64) ///< Max Supported Devices
#define CPU_PORT 176 ///< CPU Port Number
#define XP_MAX_10G_PORTS 128 ///< Max 10G Ports
#define XP_MAX_TOTAL_PORTS XP_MAX_10G_PORTS ///< Max Total Ports
#define XP_MAX_PTGS 32 ///< Max Ptgs
#define XP_PORTS_PER_PORT_GROUP 4 ///< Ports Per Port Group
#define XP_MAX_VLAN_NUM (4 * 1024) ///< Max Supported Vlan Num
#define XP_MAC_ADDR_LEN 6 ///< Mac Address Len
/**
* \brief Maximum number of OF tables
*/
#define XP_OF_MAX_TABLE_PROFILES 24 ///< OpenFlow Max Table Profiles
typedef uint32_t xpDevice_t; ///< User defined type for device
typedef uint16_t xpVlan_t; ///< User defined type for vlan
typedef uint32_t xpPort_t; ///< User defined type for port
typedef uint32_t xpVif_t; //< User defined type for vif
typedef uint8_t macAddr_t[6]; ///< User defined type for Mac Address
typedef uint8_t ipv4Addr_t[4]; ///< User defined type for Ipv4 Address
typedef uint8_t ipv6Addr_t[16]; ///< User defined type for Ipv6 Address
typedef uint8_t macAddrHigh_t[5]; ///< User defined type for MAC Address for Higher 32 Bits
typedef uint8_t macAddrLow_t;
typedef uint32_t xpDatapath_t;
typedef uint32_t xpReasonCode_t;
/**
* \brief This type (enum) defines the global function calls return statuses
*/
typedef enum XP_STATUS_E
{
XP_NO_ERR, ///< 0 - Normal return code (XP_OK)
XP_ERR_OUT_OF_MEM, ///< 1 - Out of Memory
XP_ERR_NULL_POINTER, ///< 2 - Dereferencing Null Pointer
XP_ERR_ARRAY_OUT_OF_BOUNDS, ///< 3 - Array out of Bounds
XP_ERR_OUT_OF_KPUS, ///< 4 - Exceeded all KPUs, Parsing is incomplete
XP_ERR_UNPACK_FAILURE, ///< 5 - Packer Unpack Failure
XP_ERR_PACK_FAILURE, ///< 6 - Packer Pack Failure
XP_ERR_INVALID_KPU, ///< 7 - Invalid KPU
XP_ERR_RESOURCE_DNE, ///< 8 - Does Not Exist
XP_ERR_RESOURCE_NOT_AVAILABLE, ///< 9 - Trying to access NULL object
XP_ERR_RESOURCE_IS_PRE_ALLOCATED, ///< 10 - Trying to allocate pre-allocated resource
XP_ERR_INVALID_OFFSET, ///< 11 - Trying to access an invalid offset in memory
XP_ERR_INVALID_KEY_SIZE, ///< 12 - Unsupported key size
XP_ERR_DATA_IS_NOT_ALLIGNED, ///< 13 - Data is not aligned
XP_ERR_INVALID_ID, ///< 14 - Invalid ID
XP_ERR_INVALID_DATA_SIZE, ///< 15 - Invalid Data Size
XP_ERR_INVALID_DATA, ///< 16 - Invalid Data
XP_ERR_SEARCH_MISS, ///< 17 - TxQ Search Miss
XP_ERR_REHASH_FAIL, ///< 18 - Hash Table Rehash Failure
XP_ERR_INVALID_SHARE_GROUP, ///< 19 - Hash Table Invalid Share Group
XP_ERR_UNRESOLVABLE_COL, ///< 20 -
XP_ERR_CALL_BASE_CLASS_OBJ, ///< 21 - Inheritence Error
XP_ERR_KEY_EXISTS, ///< 22 - Failed to insert key because key already present
XP_ERR_KEY_NOT_FOUND, ///< 23 - Failed to remove/update key because key does not exist
XP_ERR_MAILBOX_FULL, ///< 24 - Mailbox Full
XP_ERR_DATA_OUT_OF_RANGE, ///< 25 - Data out of Range
XP_ERR_INVALID_ROW_BLK_NUM, ///< 26 -
XP_ERR_INVALID_TABLE_TYPE, ///< 27 - Invalid Table Type
XP_ERR_INVALID_TABLE_PROPERTIES,///< 28 - Invalid Table Properties
XP_ERR_INVALID_INPUT, ///< 29 - Invalid Input
XP_ERR_INVALID_TABLE_DEPTH, ///< 30 - Invalid Table Depth
XP_ERR_INVALID_TABLE_PTR, ///< 31 - Invalid Table Pointer
XP_ERR_INVALID_TBL_CTX, ///< 32 - Invalid Table Context
XP_ERR_PM_NOT_INIT, ///< 33 -
XP_ERR_PM_SWPOOL_EMPTY, ///< 34 -
XP_ERR_INVALID_TABLE_KEY, ///< 35 - Invalid Table Key
XP_ERR_INVALID_TABLE_HANDLE, ///< 36 - Invalid Table Handle
XP_ERR_INVALID_TABLE_ENTRY, ///< 37 - Invalid Table Entry
XP_ERR_INVALID_VALUE_SIZE, ///< 38 - Invalid Size of Value
XP_ERR_GET_TABLE_OBJ, ///< 39 - Unable to get Table Object
XP_ERR_PM_INIT_DNE, ///< 40 -
XP_ERR_PM_DEV_ADD_DNE, ///< 41 - Device Primitives already added
XP_ERR_PM_DEV_NOT_ADD, ///< 42 - Device Primitives not been added
XP_ERR_PM_HWLOOKUP_FAIL, ///< 43 - Device Primitives HW Lookup Failure
XP_ERR_INVALID_ENTRY_HANDLE, ///< 44 - Invalid Entry Handle
XP_ERR_INVALID_FIELD_REQ, ///< 45 - Invalid Field
XP_ERR_INVALID_INSERTION_ID, ///< 46 - Invalid Insertion ID
XP_ERR_INVALID_VIF_ID, ///< 47 - Invalid Vif ID
XP_ERR_INVALID_DEV_ID, ///< 48 - Invalid Device ID
XP_ERR_OUT_OF_IDS, ///< 49 - Out of IDs
XP_ERR_ID_IS_PRE_ALLOCATED, ///< 50 - ID is already allocated
XP_ERR_FREEING_UNALLOCATED_ID, ///< 51 - Freeing an unallocated ID
XP_ERR_INVALID_ID_RANGE, ///< 52 - Invalid ID Range
XP_ERR_INVALID_PORT_MODE, ///< 53 - Invalid Port mode
XP_ERR_MDIO_READ_OP_NOT_SUPPORTED, ///< 54 - MDIO Read operation not supported
XP_ERR_MDIO_WRITE_OP_NOT_SUPPORTED, ///< 55 - MDIO Write operation not supported
XP_ERR_STATISTICS_STATUS_NOT_CLEAR, ///< 56 - Statistics Engine Busy
XP_ERR_INVALID_PREAMBLE_LEN_VALUE, ///< 57 - Invalid ingress preamble length value
XP_ERR_MODE_NOT_SUPPORTED, ///< 58 - Mode not supported
XP_ERR_MAC_NOT_CONFIGURED, ///< 59 - Mac not configured
XP_ERR_MEM_ALLOC_ERROR, ///< 60 - Memory Allocation Error
XP_ERR_MEM_DEALLOC_ERROR, ///< 61 - Memory De-allocation Error
XP_ERR_MUNMAP, ///< 62 -
XP_ERR_SHMEM, ///< 63 -
XP_ERR_NOT_INITED, ///< 64 - Not Inited
XP_ERR_INIT, ///< 65 - Initialization Error
XP_ERR_BUS_NOT_INITED, ///< 66 - Bus not initialized
XP_ERR_INVALID_BUS, ///< 67 - Invalid Bus
XP_ERR_BUS_INIT, ///< 68 - Bus Initialization error
XP_ERR_INVALID_INTERFACE, ///< 69 - Invalid Interface
XP_ERR_INVALID_CONFIG_MODE, ///< 70 - Invalid Configuration Mode
XP_ERR_INVALID_POLICY, ///< 71 - Invalid Policy Requested
XP_ERR_INVALID_VALUE, ///< 72 - Invalid Value
XP_ERR_INVALID_ARG, ///< 73 - Invalid Argument
XP_ERR_INVALID_SEND_MODE, ///< 74 -
XP_ERR_INVALID_QUEUE_NUM, ///< 75 - Invalid Queue Number
XP_ERR_PACKET_DRV_INTERFACE_INITED, ///< 76 - Packet Drive Interface already Initialized
XP_ERR_DESCRIPTORS_NOT_AVAILABLE, ///< 77 - Descriptors not available
XP_ERR_DMA0_TIMEOUT, ///< 78 - DMA 0 Timeout
XP_ERR_INVALID_QUEUE, ///< 79 - Invalid Queue
XP_ERR_NOT_FOUND, ///< 80 - Interface Not Found
XP_ERR_PKT_NOT_AVAILABLE, ///< 81 - Packet not Available
XP_ERR_BUFFERS_NOT_AVAILABLE, ///< 82 - Buffers not Available
XP_ERR_QUEUE_NOT_ENABLED, ///< 83 - Queue not Enabled
XP_ERR_DMA_TRANSMIT, ///< 84 - DMA Transmit Error
XP_ERR_REGACCESS, ///< 85 - Register Access Error
XP_ERR_DEVICE_OPEN, ///< 86 - Unable to open Device
XP_ERR_FILE_OPEN, ///< 87 - Unable to open File
XP_ERR_IOCTL, ///< 88 - IO Control Error
XP_ERR_DEVICE_CLOSE, ///< 89 - Unable to close Device
XP_ERR_SOCKET_SELECT, ///< 90 -
XP_ERR_SOCKET_RECV, ///< 91 - Socket Receive Error
XP_ERR_SOCKET_SEND, ///< 92 - Socket Send Error
XP_ERR_SOCKET_INIT, ///< 93 - Socket Init Error
XP_ERR_SOCKET_CLOSE, ///< 94 - Socket Close Error
XP_ERR_INVALID_MAGIC_NUM, ///< 95 -
XP_ERR_EVENT_REGISTRATION, ///< 96 - Event Registration Error
XP_ERR_REG_READ, ///< 97 - Register Read Failure
XP_ERR_REG_WRITE, ///< 98 - Register Write Failure
XP_ERR_SRAM_READ, ///< 99 - SRAM Read Failure
XP_ERR_SRAM_WRITE, ///< 100 - SRAM Write Failure
XP_ERR_SRAM_BUSY, ///< 101 - SRAM Busy
XP_ERR_IPC_BUSY, ///< 102 - IPC Busy
XP_ERR_AGE_INVALID_PROPERTIES, ///< 103 - Invalid Properties for Aging
XP_ERR_AGE_CYCLE_BUSY, ///< 104 - Aging Cycle Busy
XP_PORT_NOT_VALID, ///< 105 - Port not Valid
XP_PORT_INSTANCE_NOT_CREATED, ///< 106 - Port Instance not Created
XP_MDIO_MASTER_LIMIT_EXCEED, ///< 107 - MDIO Master Limit Exceeded
XP_MDIO_MASTER_BUSY, ///< 108 - MDIO Master Busy
XP_PORT_NOT_ENABLED, ///< 109 - Port not Enabled
XP_INVALID_MAC_MODE, ///< 110 - Invalid Mac Mode
XP_INVALID_PCS_MODE, ///< 111 - invalid PCS Mode
XP_ERR_PCS_SYNC, ///< 112 - PCS Synchronization Error
XP_ERR_MAC_NOT_INITED, ///< 113 - Mac not Initialized
XP_PORT_NOT_INITED, ///< 114 - Port not Initialized
XP_ERR_OUT_OF_RANGE, ///< 115 - Out of Range
XP_ERR_SERDES_NOT_INITED, ///< 116 - SERDES Not Initialized
XP_ERR_AAPL_NULL_POINTER, ///< 117 - AAPL Dereferencing Null Pointer
XP_ERR_INVALID_PCS_CONFIG_MODE, ///< 118 - Invalid PCS Configuration Mode
XP_ERR_MDIO_MASTER_NOT_CONFIGURED, ///< 119 - MDIO Master Not Configured
XP_ERR_INVALID_PORTNUM, ///< 120 - Invalid Port Number
XP_ERR_INVALID_CHAN_NUM, ///< 121 - Invalid Channel Number
XP_ERR_INVALID_MODE_SPEED, ///< 122 - Invalid Speed Mode
XP_ERR_INVALID_VLAN_FRM_LEN_CONFIG, ///< 123 - Invalid VLAN Frame Length Configuration
XP_ERR_VALUE_OUT_OF_RANGE, ///< 124 - Value out of Range
XP_ERR_INVALID_SPEED, ///< 125 - Invalid Speed
XP_ERR_INVALID_SERDES_CHANNEL_NUM, ///< 126 -Invalid SERDES Channel Number
XP_ERR_INTERRUPT_HANDLER_NOT_REGISTERED, ///< 127 - Link Up Handler not Registered
XP_ERR_AN_SET_NOT_ALLOWED, ///< 128 - AutoNegotiation Set Not Allowed
XP_ERR_AN_GET_NOT_ALLOWED, ///< 129 - AutoNegotiation Get Not Allowed
XP_ERR_AN_RESTART_NOT_ALLOWED, ///< 130 - AutoNegotiation Restart Not Allowed
XP_ERR_MDIO_STATUS_NOT_CLEAR, ///< 131 - MDIO Status Not Clear
XP_ERR_INVALID_PCSMODE, ///< 132 - Invalid PCS mode
XP_ERR_OP_NOT_SUPPORTED, ///< 133 - Operation not Supported
XP_ERR_UNKNOWN_EVENT, ///< 134 - Unknown Event Occured
XP_ERR_INIT_FAILED, ///< 135 - Initialization Failure
XP_ERR_SERDES_INIT, ///< 136 - SERDES Initialization Error
XP_ERR_SERDES_FW_NOT_INITED, ///< 137 -
XP_ERR_INVALID_MAX_ENTRIES, ///< 138 -
XP_ERR_INVALID_LANE_NUM, ///< 139 - Invalid Lane Number
XP_ERR_PORT_CONFIGURATION, ///< 140 - Port Configuration Error
XP_ERR_THREAD_CREATION, ///< 142 - Thread Creation Failure
XP_ERR_LOCK_INIT, ///< 142 - Lock Initialization error
XP_ERR_ACQUIRING_LOCK, ///< 143 -
XP_ERR_RELEASING_LOCK, ///< 144 -
XP_ERR_LOCK_DESTROY, ///< 145 -
XP_ERR_SOCKET_TX, ///< 146 - Transmit Packet Socket Failure
XP_ERR_SOCKET_POLLING, ///< 147 - Socket Polling Failure
XP_ERR_TIMEOUT, ///< 148 - Socket Timeout
XP_ERR_CONFIG_OPEN, ///< 149 -
XP_ERR_OFFSET_OPEN, ///< 150 -
XP_ERR_INVALID_VALE, ///< 151 - XXX Typo?
XP_SERDES_LOOPBACK_ERROR, ///< 152 - SERDES Loopback Failure
/* Management WM specific error codes */
XP_ERR_INVALID_PARAMS, ///< 153 - Invalid Parameters
XP_ERR_TESTBENCH_FAIL, ///< 154 - Testbench Failure
XP_ERR_UNREGISTERED_OFFSET, ///< 155 - Unregistered Offset
XP_ERR_SIGACTION_FAIL, ///< 156 - Signal Action Failure
XP_ERR_DMA_DESC_NULL_ADDR, ///< 157 - DMA Descriptor NULL
XP_ERR_DMA_DESC_OWN, ///< 158 - DMA Descriptor CPU Owned
XP_ERR_DMA_TX, ///< 159 - DMA Transmit Failure
XP_ERR_DMA_RX, ///< 160 - DMA Receive Failure
XP_ERR_DMA_RX_EXIT, ///< 161 - DMA Receive Exit error
XP_ERR_PORT_NOT_AVAILABLE, ///< 162 - Port Not Available
XP_UMAC_RX_DISABLE, ///< 163 -
XP_UMAC_TX_DISABLE, ///< 164 -
XP_UMAC_NO_ACTION_REQD, ///< 165 -
XP_ERR_INVALID_UMAC_MODE, ///< 166 -
XP_ERR_UMAC_NOT_IN_SGMII_MODE, ///< 167 -
XP_ERR_UMAC_NOT_IN_MIX_MODE, ///< 168 -
XP_ERR_UMAC_NOT_IN_QSGMII_MODE, ///< 169 -
XP_ERR_INVALID_SBUS_CMD, ///< 170 - Invalid SBUS Command
XP_ERR_FILE_CLOSE, ///< 171 - File Closed
XP_ERR_INVALID_BITFIELD, ///< 172 - Invalid Bitfield
XP_ERR_SHADOW_MEM_MGR_FAIL, ///< 173 - Shadow Memory Manager Failure
XP_ERR_SHADOW_MEM_IOCTL_FAIL, ///< 174 - Shadow Memory IOCTL Failure
XP_ERR_MEM_FAIL, ///< 175 - Memory Failure
XP_ERR_MEM_RDWR_FAIL, ///< 176 - Memory Read/Write Failure
XP_ERR_DMAC_RAW_SOCKET_FAIL, ///< 177 - Destination MAC Raw Socket Failure
XP_ERR_DMAC_IOCTL_FAIL, ///< 178 - Destination MAC IOCTL Failure
XP_ERR_DMAC_RAW_SOCKET_RD_FAIL, ///< 179 - Destination MAC Raw Socket Read Failure
XP_ERR_DMAC_RAW_SOCKET_WR_FAIL, ///< 180 - Destination MAC Raw Socket Write Failure
XP_ERR_FW_FILE_NOT_FOUND, ///< 181 - Unable to open Service CPU Firmware File
XP_ERR_FILE_READ, ///< 182 - Service CPU Firmware File Read Failure
XP_ERR_SCPU_EXCEPTION, ///< 183 - Service CPU Exception
XP_ERR_UMAC_READ_ONLY, ///< 184 -
XP_ERR_UMAC_WRITE_ONLY, ///< 185 -
XP_ERR_SERDES_ACCESS, ///< 186 - SERDES Access Failure
XP_ERR_SBUS_THERMAL_SENSOR_FAILED, ///< 187 - SBUS Thermal Sensor Failure
XP_ERR_I2C_DEV_OPEN, ///< 188 -
XP_ERR_I2C_DEV_CLOSE, ///< 189 -
XP_ERR_I2C_XFER, ///< 190 - I2C Transfer Error
XP_ERR_DONGLE_I2C_XFER, ///< 191 - I2C Dongle Transfer Error
XP_ERR_MDIO_XFER, ///< 192 - MDIO Transfer Error
XP_ERR_MDIO_BUSY, ///< 193 - MDIO Busy
XP_PORT_INITED, ///< 194 - port is already inited
XP_ERR_CALL_DERIVE_CLASS_OBJ, ///< 195
XP_ERR_INVALID_MIN_ETH_FRAME_SIZE, ///< 196 - Invalid min ethernet frame size received by UMAC. It should be min 64 byte
XP_MORE_PKTS_AVAILABLE, ///< 197 - In case of receiving packets from queue - notify user space if more packets are available
XP_ERR_OF_BAD_MATCH_FIELD = 300,///< 300 - Unsupported field type in OpenFlow match
XP_ERR_OF_BAD_MATCH_VALUE, ///< 301 - Unsupported value in a match field
XP_ERR_OF_BAD_MATCH_WILDCARDS, ///< 302 - Unsupported combination of fields masked or omitted in OpenFlow match.
XP_ERR_OF_BAD_ACTION, ///< 303 - Unknown or unsupported action type
XP_ERR_OF_BAD_SET_ACTION, ///< 304 - Unsupported type in SET_FIELD action
XP_ERR_OF_UNSUP_ACTION_ORDER, ///< 305 - Unsupported actions order
XP_ERR_OF_BAD_OUT_PORT, ///< 306 - Problem validating output port
XP_ERR_OF_UNSUP_METADATA, ///< 307 - Metadata value unsupported by datapath
XP_ERR_OF_BAD_TABLE_ID, ///< 308 - Table does not exist
XP_ERR_OF_TABLE_FULL, ///< 309 - Flow not added because table was full
XP_ERR_OF_UNSUP_INST, ///< 310 - Switch or table does not support the instruction
XP_ERR_OF_BAD_GOTO_TABLE_ID, ///< 311 - Invalid Table-ID specified for GOTO instruction
XP_ERR_OF_INVALID_FLOW_ID, ///< 312 - Invalid flow id of flow key specified
XP_ERR_OF_INVALID_GROUP, ///< 313 - Invalid group id or attempt to add more than one bucket to "indirect" group
XP_ERR_OF_GROUP_EXISTS, ///< 314 - Group with such ID exists
XP_ERR_OF_OUT_OF_GROUP, ///< 315 - Group add failed because luck of space
XP_ERR_OF_OUT_OF_BUCKET, ///< 316 - Group add failed because of bucket limitation
XP_ERR_OF_WEIGHT_UNSUPPORTED, ///< 317 - Group load sharing unsupported
XP_ERR_ACM_STATIC_RANGE, ///< 318 - ACM client corresponds to a static id range. Allocation is not allowed/required for this client+type.
XP_ERR_INVALID_VLAN_ID, ///< 319 - Group load sharing unsupported
XP_ERR_SERDES_NO_SIGNAL, ///< 320 - no signal detected on serdes
XP_ERR_MAX_LIMIT, ///< 321 - Max Limit Exceeded
XP_INVALID_FEC_MODE, ///< 322 - FEC mode is invalid
XP_ERR_LINK_UP, ///< 323
XP_ERR_INVALID_DEVICE_TYPE, ///< 324 - Invalid device type provided
XP_STATUS_NUM_OF_ENTRIES
} XP_STATUS;
/**
* \struct xpPacketInfo
* \brief Packet Information to be used while Packet Tx/Rx
*
*/
typedef struct xpPacketInfo
{
void *buf; /**< Packet data */
uint16_t bufSize; /**< Size of Packet */
uint8_t priority; /**< Priority of the Packet, applicable during Packet Tx */
}xpPacketInfo;
/**
* \struct xpPortConfigData
* \brief This structure defines the per-port configurations data format
*/
typedef struct xpPortConfig_t
{
uint32_t portDefaultEXP : 3; ///< MPLS <EXP> assignment, if enabled
uint32_t portDefaultDSCP : 6; ///< IP <DSCP> assignment, if enabled
uint32_t portDefaultDEI : 1; ///< Ethernet<DEI> assignment, if enabled
uint32_t portDefaultPCP : 3; ///< Ethernet<PCP> assignment, if enabled
uint32_t portDefaultDP : 2; ///< Packet <Drop Precedence> assignment, if enabled
uint32_t portDefaultTC : 4; ///< Packet <Traffic Class> assignment, if enabled
uint32_t mplsQosEn : 1; ///< Control to enable MPLS QoS assignment
uint32_t IPQosEn : 1; ///< Control to enable IP QoS assignment
uint32_t layer2QosEn : 1; ///< Control to enable Ethernet L2 QoS assignment
uint32_t egressFilterId : 8; ///< Egress Filtering ID assignment, if enabled
uint32_t setIngressVif : 1; ///< Control to enable Ingress VIF assignment
uint32_t setBridgeDomain : 1; ///< Control to enable Bridge Domain ID assignment
uint32_t acceptedFrameType : 2; ///< Control to enable accepted frames types
uint32_t bypassTunnelVif : 1; ///< Control to enable the VIF assignment for tunnels
uint32_t bypassACLsPBR : 1; ///< Control to enable the Policy-Based-Routing
uint32_t samplerEn : 1; ///< Control to enable the Sampling
uint32_t policerEn : 1; ///< Control to enable the Policing
uint32_t portState : 2; ///< Port Spanning State configuration
uint32_t setEgressPortFilter : 1; ///< Control ro enable Egress Filtering ID assignment
uint32_t macSAmissCmd : 2; ///< Packet Command assignment for MAC SA miss
uint32_t bumPolicerEn : 1; ///< Control to enable Policing of Broadcast, Unknown Unicast and Multicast packets
uint32_t portACLEn : 1; ///< Control to enable Ingress ACL Policy
uint32_t portDebugEn : 1; ///< Control to enable Debug Information Output
uint32_t portAclId : 8; ///< Ingress ACL-ID assignment, if enabled
uint32_t privateWireEn : 1; ///< Control to enable Virtual Private Wire Service (VPWS)
uint32_t addPortBasedTag : 1; ///< COntrol to enable adding a tag for Virtual Private Wire Service (VPWS)
uint32_t Reserved2 : 6; ///< Reserved
uint32_t bridgeDomain : 16; ///< Bridge Domain ID
uint32_t evif : 16; ///< Egress VIF
uint32_t mirrorBitMask : 16; ///< Mirroring Mask vector
uint32_t ingressVif : 20; ///< Ingress VIF assignment, if enabled
uint32_t pvidModeAllPkt : 1; ///< Control to enable Port VLAN-ID assignment to All Rx packets on a port
uint32_t pvid : 12; ///< Port VLAN-ID assignment, if enabled
uint32_t mplsQosProfileIdx : 3; ///< MPLS QoS Profile Index assignment, if enabled
uint32_t ipQosProfileIdx : 3; ///< IP QoS Profile Index assignment, if enabled
uint32_t l2QosProfileIdx : 3; ///< L2 Ethernet QoS Index assignment, if enabled
uint32_t etagExists : 1; ///< Control to enable E-Tag on Port Rx
} xpPortConfig_t;
/**
* \struct xpStatistics
* \brief This structure defines the per-port statistics MIB counters
*/
typedef struct __attribute__((packed)) xp_Statistics
{
uint64_t frameRxOk;
uint64_t frameRxAll;
uint64_t frameRxFcsErr;
uint64_t frameRxAnyErr;
uint64_t octetsRxGoodFrame;
uint64_t octetsRx;
uint64_t frameRxUnicastAddr;
uint64_t frameRxMulticastAddr;
uint64_t frameRxBroadcastAddr;
uint64_t frameRxTypePause;
uint64_t frameRxLengthErr;
uint64_t frameRxUndersize;
uint64_t frameRxOversize;
uint64_t fragmentsRx;
uint64_t jabberFrameRx;
uint64_t frameRxLength64;
uint64_t frameRxLength65To127;
uint64_t frameRxLength128To255;
uint64_t frameRxLength256To511;
uint64_t frameRxLength512To1023;
uint64_t frameRxLength1024To1518;
uint64_t frameRxLength1519AndUp;
uint64_t frameDroppedFromRxFIFOFullCondition;
uint64_t frameTransmittedOk;
uint64_t frameTransmittedAll;
uint64_t frameTransmittedWithErr;
uint64_t octetsTransmittedWithoutErr;
uint64_t octetsTransmittedTotal;
uint64_t framesTransmittedUnicast;
uint64_t framesTransmittedMulticast;
uint64_t framesTransmittedBroadcast0;
uint64_t framesTransmittedPause;
}xp_Statistics;
/**
* \struct xpOfFlowId_t
* \brief This structure defines OpenFlow entry identifier
*/
typedef struct xpOfFlowId_t {
bool exactMatch; ///< Exact match flow entry.
uint32_t index; ///< Flow logical ID.
uint32_t rehashIndex; ///< New logical ID of old exact match flow entry
///< that has been relocated due to insertion of new
///< exact match flow entry.
} xpOfFlowId_t;
/**
* \struct xpOfTableStats_t
* \brief This structure contains OpenFlow table statistic
*/
typedef struct xpOfTableStats_t {
uint64_t missedCount; ///< Number of packets that missed table.
uint64_t matchedCount; ///< Number of packets that hit table.
} xpOfTableStats_t;
/**
* \struct xpOfIpv4Match_t
* \brief This structure contains IPv4 match fields
*/
typedef struct xpOfIpv4Match_t {
/* IPv4 */
ipv4Addr_t srcAddr; ///< IPv4 source address.
ipv4Addr_t dstAddr; ///< IPv4 destination address.
uint8_t tos; ///< IP ToS (including DSCP and ECN).
uint8_t proto; ///< IP Protocol.
} xpOfIpv4Match_t;
/**
* \struct xpOfMatch_t
* \brief This structure contains OpenFlow match fields
*/
typedef struct xpOfMatch_t {
/* L1 */
uint64_t metadata; ///< Table Metadata.
uint32_t inPort; ///< Ingress vIf.
uint32_t ipPhyPort; ///< IN_PORT: Physical port.
/* L2 */
macAddr_t ethDst; ///< Ethernet destination address.
macAddr_t ethSrc; ///< Ethernet source address.
uint16_t ethType; ///< Ethernet frame type.
/* VLAN */
xpOfMatchPktType_e tagging; ///< Match packets with specific tagging type.
xpVlan_t vlanVID; ///< VLAN-ID from outermost 802.1Q header.
uint8_t vlanPCP; ///< VLAN_VID !=NONE:
///< VLAN-PCP from outermost 802.1Q header.
/* L3 */
union {
xpOfIpv4Match_t ipv4; ///< IPv4 match fields (ETH_TYPE=0x0800)
};
/* L4 */
uint16_t tpSrc; ///< TCP/UDP/SCTP source port (IP_PROTO=6/17/132).
uint16_t tpDst; ///< TCP/UDP/SCTP destination port (IP_PROTO=6/17/132).
} xpOfMatch_t;
/**
* \union xpOfPacketField_t
* \brief This union contains packet fields that can be modified by XP_OFPAT_SET_FIELD action.
*/
typedef union {
/* Ethernet */
macAddr_t ethAddr; ///< Ethernet address.
///< Valid for: ETH_DST | ETH_SRC |
///< ARP_SHA | ARP_THA |
///< IPV6_ND_SLL | IPV6_ND_TLL
uint16_t ethType; ///< Ethernet packet type.
///< Valid for ETH_TYPE.
/* VLAN */
xpVlan_t vlanVID; ///< VLAN_VID
///<
uint8_t vlanPCP; ///< VLAN_PCP
///<
/* IPv4 */
ipv4Addr_t ipv4Addr; ///< IPv4 address. Valid for: IPV4_SRC | IPV4_DST |
///< ARP_SPA | ARP_TPA
uint8_t ipDSCP; ///< IP_DSCP
///<
uint8_t ipECN; ///< IP_ECN
///<
uint8_t ipProto; ///< IP_PROTO
///<
/* L4 */
uint16_t l4Port; ///< L4 port number. Valid for: TCP_SRC | TCP_DST |
///< UDP_SRC | UDP_DST | SCTP_SRC | SCTP_DST.
} xpOfPacketField_t;
/**
* \struct xpOfActionSetField_t
* \brief This structure contains OpenFlow action set fields
*/
typedef struct xpOfActionSetField_t {
xpOfActionType_e type; ///< XP_OFPAT_SET_FIELD
xpOxmType_e subType; ///< Packet field to be modified. See xpOxmType_t.
xpOfPacketField_t data; ///< Data Packet’s Field.
xpOfPacketField_t mask; ///< Mask Packet’s Field.
} xpOfActionSetField_t;
/**
* \struct xpOfActionOutput_t
* \brief This structure contains OpenFlow action output fields
*/
typedef struct xpOfActionOutput_t {
xpOfActionType_e type; ///< XP_OFPAT_OUTPUT
uint32_t port; ///< Egress vIf or one of xpOfPortNo_e.
uint16_t pktMaxLen; ///< Max length to send to controller when
///< the 'port' is the XP_OFPP_CONTROLLER or
///< 0xffff to send complete packet. */
} xpOfActionOutput_t;
/**
* \struct xpOfActionSetTTL_t
* \brief This structure contains OpenFlow action set TTL fields
*/
typedef struct xpOfActionSetTTL_t {
xpOfActionType_e type; ///< XP_OFPAT_SET_NW_TTL
uint8_t ttl; ///< IP TTL
} xpOfActionSetTTL_t;
/**
* \struct xpOfActionGroup_t
* \brief This structure contains OpenFlow action group fields
*/
typedef struct xpOfActionGroup_t {
xpOfActionType_e type; ///< XP_OFPAT_GROUP
uint32_t groupId; ///< Group identifier.
} xpOfActionGroup_t;
/**
* \union xpOfAction_t
* \brief This union defines all supported OpenFlow actions
*/
typedef union xpOfAction_t {
xpOfActionType_e type; ///< Action type. The following actions
///< do not have specific data fields:
///< XP_OFPAT_DEC_NW_TTL,
///< XP_OFPAT_POP_VLAN
xpOfActionSetField_t setField; ///< Data for XP_OFPAT_SET_FIELD action
xpOfActionOutput_t output; ///< Data for XP_OFPAT_OUTPUT action
xpOfActionSetTTL_t setTTL; ///< Data for XP_OFPAT_SET_NW_TTL action
xpOfActionGroup_t group; ///< Data for XP_OFPAT_GROUP action
} xpOfAction_t;
/**
* \struct xpOfBucket_t
* \brief This structure defines a bucket for use in OF groups
*/
typedef struct xpOfBucket_t {
uint16_t weight; ///< Relative weight. Valid for XP_OFPGT_SELECT only!
uint32_t actionSetLen; ///< Number of actions in the action set.
xpOfAction_t *actionSet; ///< Action set associated with the bucket.
} xpOfBucket_t;
/**
* \struct xpOfInstructions_t
* \brief This structure defines OpenFlow instructions.
* The instructions of the set execute in the order
* specified by this structure.
*/
typedef struct xpOfInstructions_t {
//@{
uint32_t actionListLen; ///< Implements OFPIT_APPLY_ACTIONS instruction.
///< Specifies the number of actions in action list.
xpOfAction_t *actionList; ///< Implements OFPIT_APPLY_ACTIONS instruction.
///< Applies the specific action(s) immediately, without
///< any change to the Action Set. This instruction
///< may be used to modify the packet between two tables or
///< to execute multiple actions of the same type.
//@}
//@{
bool clearActions; ///< Implements OFPIT_CLEAR_ACTIONS instruction.
///< Clears all the actions in the action set immediately.
//@}
//@{
uint32_t actionSetLen; ///< Implements OFPIT_WRITE_ACTIONS instruction.
///< Specifies the number of actions in action set.
xpOfAction_t *actionSet; ///< Implements OFPIT_WRITE_ACTIONS instruction.
///< Merges the specified action(s) into the current
///< action set. If an action of the given type exists
///< in the current set, overwrite it, otherwise add it.
//@}
//@{
bool writeMetadata; ///< Implements OFPIT_WRITE_METADATA instruction.
uint64_t metadata; ///< Metadata value
uint64_t metadataMask; ///< Metadata bitmask
//@}
//@{
uint8_t gotoTable; ///< Implements OFPIT_GOTO_TABLE instruction.
///< Specifies a next table in the lookup pipeline or
///< zero if not specified.
//@}
} xpOfInstructions_t;
/**
* \struct xpFlowEntry_t
* \brief This structure specifies OpenFlow entry parameters.
*/
typedef struct xpFlowEntry_t {
xpOfFlowType_e type; ///< Flow type.
uint8_t tableId; ///< ID of OpenFlow Table.
uint16_t priority; ///< Priority level of flow entry.
xpOfMatch_t match; ///< Fields to match with packets.
xpOfMatch_t matchMask; ///< Match mask.
xpOfInstructions_t instructions; ///< Instructions that will be executed on packet match
} xpFlowEntry_t;
/**
* \struct xpOfStats_t
* \brief This structure specifies OpenFlow statistics.
* A counter will be set to the maximum field value
* if not supported.
*/
typedef struct xpOfStats_t
{
uint64_t packetCount; ///< Number of packets processed.
uint64_t byteCount; ///< Number of bytes processed.
} xpOfStats_t;
/**
* \struct xpOfPacketIn_t
* \brief Packet-in context.
*/
typedef struct xpOfPacketIn_t {
xpOfPacketInReason_e reason;
uint8_t tableId; ///< ID of the table that was looked up.
uint32_t flowId; ///< The ID of the flow entry that was looked up
///< or -1 if undefined (e.g., group bucket or
///< action set).
uint64_t tunnelId; ///< Metadata associated with a logical port.
uint64_t metadata; ///< Table Metadata.
uint32_t inPort; ///< Ingress vIf.
uint32_t inPhyPort; ///< Physical port.
uint8_t *packet; ///< Trapped packet.
uint16_t packetLen; ///< Trapped packet's full length.
uint16_t maxLen; ///< Number of bytes from 'packet' that
///< must be sent to the controller.
///< See pktMaxLen in xpOfActionOutput_t.
} xpOfPacketIn_t;
/**
* \struct xpOfTcam_t
* \brief OpenFlow TCAM table profile
*/
typedef struct xpOfTcam_t
{
uint32_t keySize;
uint32_t dataSize;
uint32_t numDb;
} xpOfTcam_t;
/**
* \struct xpOfHash_t
* \brief OpenFlow SRAM table profile
*/
typedef struct xpOfHash_t
{
uint32_t keySize;
uint32_t dataSize;
uint32_t numEntries;
uint32_t numOfWays;
} xpOfHash_t;
/**
* \union xpOfTableData_t
* \brief OpenFlow table profile
*/
typedef union xpOfTableData_t
{
xpOfTcam_t ofTcam;
xpOfHash_t ofHash;
} xpOfTableData_t;
/**
* \union xpOfTableInfo_t
* \brief OpenFlow table information
*/
typedef struct xpOfTableInfo_t
{
uint32_t tableId;
xpOfTableType_e tblType;
xpOfTableData_t tblData;
} xpOfTableInfo_t;
/**
* \union xpOpenFlowTableProfile_t
* \brief OpenFlow table profile
*/
typedef struct xpOpenFlowTableProfile_t
{
uint32_t numTables;
xpOfTableInfo_t ofTblProfile[XP_OF_MAX_TABLE_PROFILES];
} xpOpenFlowTableProfile_t;
/**
* Structures defintions for IACL
*/
typedef union xpIaclKeyFieldId
{
xpIaclV4KeyFlds v4Fld;
xpIaclV6KeyFlds v6Fld;
xpIaclV4MplsKeyFlds v4MplsFld;
} xpIaclKeyFieldId_t;
typedef struct xpIaclkeyField
{
//union{
// xpIaclV4KeyFlds v4Fld;
// xpIaclV6KeyFlds v6Fld;
//}fld;
xpIaclKeyFieldId_t fld;
uint8_t* value; //this is a pointer to an byte array
uint8_t* mask; //this is a pointer to an byte mask array
} xpIaclkeyField_t;
typedef struct xpIaclkeyFieldList
{
uint32_t numFlds;
uint32_t isValid;
xpIaclKeyType type;
xpIaclkeyField_t* fldList;
} xpIaclkeyFieldList_t;
typedef struct xpIaclKeyMask_t
{
uint8_t* value;
uint8_t* mask;
} xpIaclKeyMask_t;
typedef struct xpQosData_t
{
uint32_t dscp : 6;
uint32_t pcp : 3;
uint32_t rsvd : 5;
}xpQosData_t;
typedef union xpQosOrVlanRwData_t
{
xpQosData_t qosData;
uint32_t vlan : 14;
}xpQosOrVlanRwData_t;
typedef union xpEgrVifOrRsnCode_t
{
xpReasonCode_t rsnCode;
uint32_t eVifId;
}xpEgrVifOrRsnCode_t;
/**
* \struct xpIaclData
* \brief This struct represents the data portion of entry in
*/
typedef struct xpIaclData_t
{
uint32_t isTerminal : 1;
uint32_t enPktCmdUpd : 1;
uint32_t enRedirectToEvif : 1;
uint32_t enPolicer : 1;
uint32_t enMirrorSsnUpd : 1;
uint32_t enTcRemark : 1;
uint32_t enDpRemark : 1;
uint32_t enDscpRemarkOrVrfUpd : 1;
uint32_t enPcpRemarkOrStagRw : 1;
uint32_t qosOrVlanRw : 1;
uint32_t encapType : 2;
uint32_t pktCmd : 2;
uint32_t mirrorSessionId : 2;
xpEgrVifOrRsnCode_t egrVifIdOrRsnCode;
uint32_t enCopp: 1;
uint32_t available : 1;
uint32_t policerId : 10;
uint32_t tc : 4;
uint32_t dp : 2;
xpQosOrVlanRwData_t qosOrVlanRwData;
#ifdef __cplusplus
/**
* \public
* \brief Constructor of xpIaclData_t.
*
*/
xpIaclData_t();
/**
* \public
* \brief Prints xpIaclData_t.
*
*/
void printEntry();
#endif
} xpIaclData_t;
/*
* This structure will be passed in createTable
* to create tables based of the keySize and num db's
* user wants to create
*/
typedef struct xpIaclTableInfo
{
xpIaclType_e tblType;
uint32_t keySize;
uint32_t numDb;
}xpIaclTableInfo_t;
typedef struct xpIaclTableProfile
{
uint32_t numTables;
xpIaclTableInfo_t tableProfile[XP_IACL_TOTAL_TYPE];
}xpIaclTableProfile_t;
/**
* \struct xpRecvPacketInfo_t
* \brief Information fot the last interrupt of packet received
*/
typedef struct xpRecvPacketInfo_t
{
uint8_t queueNum; //< In case of DMA - queueNumber
const void *buf; //< Pointer to the packet received
uint16_t bufSize; //< Length of the packet received
} xpRecvPacketInfo_t;
/**
* \brief Function pointer to be registered for the port event handler
* \param [in] devId Device ID
* \param [in] portNum Port Number
*
* \return XP_STATUS
*/
typedef void (*xpEventHandler)(xpDevice_t devId, uint8_t portNum);
/**
* \brief Function pointer to be registered for completion of packet transmission
* \param [in] intrSrcDev Device Id. Valid values are 0-63
*
* \return XP_STATUS
*/
typedef void (*xpPacketTxCompletion)(xpDevice_t intrSrcDev);
/**
* \brief Function pointer to indicate whether the packet is available
* \param [in] intrSrcDev Device Id. Valid values are 0-63
* \param [data] recvPacketInfo Information needed for user space, to handle in registered event handler.
* \param [out] buf Buffer pointer where packet data is available.
* \param [in] bufSize Size of packet available
*
* \return XP_STATUS
*/
typedef void (*xpPacketAvailable)(xpDevice_t intrSrcDev, xpRecvPacketInfo_t recvPacketInfo);
/**
* \brief Function pointer to indicate a DMA error
* \param [in] intrSrcDev Device Id. Valid values are 0-63
*
* \return XP_STATUS
*/
typedef void (*xpDmaError)(xpDevice_t intrSrcDev);
// XPS TYPES
typedef xpDevice_t xpsDevice_t;
typedef xpVlan_t xpsVlan_t;
typedef xpPort_t xpsPort_t;
typedef xpVif_t xpsVif_t;
typedef macAddrLow_t xpsMacAddrLow_t;
typedef xpDatapath_t xpsDatapath_t;
typedef uint32_t xpsInterfaceId_t;
typedef uint32_t xpsStp_t;
/**
* \struct xpsPacketInfo_t
* \brief This structure defines the packet Tx/Rx information for Packet Driver
*
*/
typedef xpPacketInfo xpsPacketInfo_t;
/**
* \struct xpsPortConfig_t
* \brief This structure defines the per-port configurations data format
*
*/
typedef xpPortConfig_t xpsPortConfig_t;
/**
* \struct xpsStatistics_t
* \brief This structure defines the per-port statistics MIB counters
*
*/
typedef struct xp_Statistics xpsStatistics_t;
/**
* \struct xpsOfFlowId_t
* \brief This structure defines OpenFlow entry identifier
*
*/
typedef xpOfFlowId_t xpsOfFlowId_t;
/**
* \struct xpsOfTableStats_t
* \brief This structure contains OpenFlow table statistic
*
*/
typedef xpOfTableStats_t xpsOfTableStats_t;
/**
* \struct xpsOfIpv4Match_t
* \brief This structure contains IPv4 match fields
*
*/
typedef xpOfIpv4Match_t xpsOfIpv4Match_t;
/**
* \struct xpsOfMatch_t
* \brief This structure contains OpenFlow match fields
*
*/
typedef xpOfMatch_t xpsOfMatch_t;
/**
* \union xpsOfPacketField_t
* \brief This union contains packet fields that can be modified by XP_OFPAT_SET_FIELD action.
*
*/
typedef xpOfPacketField_t xpsOfPacketField_t;
/**
* \struct xpsOfActionSetField_t
* \brief This structure contains OpenFlow action set fields
*
*/
typedef xpOfActionSetField_t xpsOfActionSetField_t;
/**
* \struct xpsOfActionOutput_t
* \brief This structure contains OpenFlow action output fields
*
*/
typedef xpOfActionOutput_t xpsOfActionOutput_t;
/**
* \struct xpsOfActionSetTTL_t
* \brief This structure contains OpenFlow action set TTL fields
*
*/
typedef xpOfActionSetTTL_t xpsOfActionSetTTL_t;
/**
* \struct xpsOfActionGroup_t
* \brief This structure contains OpenFlow action group fields
*
*/
typedef xpOfActionGroup_t xpsOfActionGroup_t;
/**
* \union xpsOfAction_t
* \brief This union defines all supported OpenFlow actions
*
*/
typedef xpOfAction_t xpsOfAction_t;
/**
* \struct xpsOfBucket_t
* \brief This structure defines a bucket for use in OF groups
*
*/
typedef xpOfBucket_t xpsOfBucket_t;
/**
* \struct xpsOfInstructions_t
* \brief This structure defines OpenFlow instructions.
* The instructions of the set execute in the order
* specified by this structure.
*
*/
typedef xpOfInstructions_t xpsOfInstructions_t;
/**
* \struct xpsFlowEntry_t
* \brief This structure specifies OpenFlow entry parameters.
*
*/
typedef xpFlowEntry_t xpsFlowEntry_t;
/**
* \struct xpsOfStats_t
* \brief This structure specifies OpenFlow statistics.
* A counter will be set to the maximum field value
* if not supported.
*
*/
typedef xpOfStats_t xpsOfStats_t;
/**
* \struct xpsOfPacketIn_t
* \brief Packet-in context.
*
*/
typedef xpOfPacketIn_t xpsOfPacketIn_t;
/**
* \struct xpsOfTcam_t
* \brief OpenFlow TCAM table profile
*
*/
typedef xpOfTcam_t xpsOfTcam_t;
/**
* \struct xpsOfHash_t
* \brief OpenFlow SRAM table profile
*
*/
typedef xpOfHash_t xpsOfHash_t;
/**
* \union xpsOfTableData_t
* \brief OpenFlow table profile
*
*/
typedef xpOfTableData_t xpsOfTableData_t;
/**
* \union xpsOfTableInfo_t
* \brief OpenFlow table information
*
*/
typedef xpOfTableInfo_t xpsOfTableInfo_t;
/**
* \union xpsOpenFlowTableProfile_t
* \brief OpenFlow table profile
*
*/
typedef xpOpenFlowTableProfile_t xpsOpenFlowTableProfile_t;
/**
* \brief Function pointer to be registered for the port event handler
*
*/
typedef xpEventHandler xpsEventHandler_f;
/**
* \brief Function pointer to be registered for completion of packet transmission
*
*/
typedef xpPacketTxCompletion xpsPacketTxCompletion_f;
/**
* \brief Function pointer to indicate whether the packet is available
*
*/
typedef xpPacketAvailable xpsPacketAvailable_f;
/**
* \brief Function pointer to indicate a DMA error
* \param [in] intrSrcDev
*
* \return XP_STATUS
*/
typedef xpDmaError xpsDmaError_f;
/**
* \xp scope information
*/
typedef uint32_t xpScope_t;
/**
* \xps scope information
*/
typedef xpScope_t xpsScope_t;
#endif
|
maxi376/utcn-imp
|
lab5.c
|
<reponame>maxi376/utcn-imp<filename>lab5.c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#define LETTER 257
#define NEWLINE '\n'
int symbol;
char yylval;
typedef struct _tree {
struct _tree *left, *right;
char k;
}tree;
void next_symbol();
void error(int line);
tree *E();
tree *F();
tree *T();
tree *P();
void next_symbol()
{
symbol = yylex();
}
int yywrap()
{
return 1;
}
void error(int line)
{
printf ("Error on the line %d\n", line);
}
tree *E()
{
tree *t = T(); //left
if (symbol == '|')
{
next_symbol();
tree *var = E(); //right
tree *new = (tree *) malloc(sizeof(struct _tree));
new->left = t;
new->right = var;
new->k = '|';
return new;
}
return t;
}
tree *F()
{
tree *t;
//apeleaza P
t = P();
if (symbol == '*')
{
next_symbol();
tree *var = (tree *) malloc(sizeof(struct _tree));
var->left = NULL;
var->right = NULL;
var->k = '*';
var->left = t;
return var;
}
else
{
return t;
}
}
tree *T()
{
tree *t = F();
if (symbol == LETTER || symbol == '(')
{
tree *var = (tree *) malloc(sizeof(struct _tree));
var->k = '&';
tree *treeright = T();
var->left = t;
var->right = treeright;
return var;
}
return t;
}
tree *P()
{
tree *var;
if (symbol == '(')
{
next_symbol();
var = E();
if (symbol == ')')
{
next_symbol();
return var;
}
else
{
error(__LINE__);
}
}
else if (symbol == LETTER)
{
var = (tree*) malloc(sizeof(struct _tree));
var->left = NULL;
var->right = NULL;
var->k = yylval;
next_symbol();
}
return var;
}
void print_tree(tree *t)
{
if (t != NULL)
{
if (t->right)
{
printf(" ");
print_tree(t->right);
}
if (t->left)
{
printf(" ");
print_tree(t->left);
}
printf("%c \n", t->k);
}
}
void parser()
{
print_tree(E());
if (symbol != '\n')
error(__LINE__);
}
int main ()
{
next_symbol();
while(symbol !=0)
{
parser();
next_symbol();
}
return 0;
}
|
fmgoncalves/tectonic
|
tectonic/dpx-dvipdfmx.c
|
<gh_stars>1-10
/* This is (x)dvipdfmx, an extended version of...
DVIPDFMx, an eXtended version of DVIPDFM by <NAME>.
Copyright (C) 2002-2017 by <NAME>, <NAME>, and <NAME>,
the DVIPDFMx project team.
Copyright (c) 2006 SIL. (xdvipdfmx extensions for XeTeX support)
Copyright (C) 1998, 1999 by <NAME> <<EMAIL>>
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 "dpx-dvipdfmx.h"
#include <assert.h>
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "core-bridge.h"
#include "dpx-cid.h"
#include "dpx-dpxconf.h"
#include "dpx-dpxfile.h"
#include "dpx-dpxutil.h"
#include "dpx-dvi.h"
#include "dpx-error.h"
#include "dpx-fontmap.h"
#include "dpx-mem.h"
#include "dpx-pdfdev.h"
#include "dpx-pdfdoc.h"
#include "dpx-pdfencrypt.h"
#include "dpx-pdffont.h"
#include "dpx-pdflimits.h"
#include "dpx-pdfobj.h"
#include "dpx-pdfparse.h"
#include "dpx-spc_tpic.h"
#include "dpx-specials.h"
#include "dpx-tfm.h"
#include "dpx-vf.h"
#include "dpx-tt_aux.h"
typedef struct page_range
{
int first;
int last;
} PageRange;
int is_xdv = 0;
int translate_origin = 0;
#define OPT_TPIC_TRANSPARENT_FILL (1 << 1)
#define OPT_CIDFONT_FIXEDPITCH (1 << 2)
#define OPT_FONTMAP_FIRST_MATCH (1 << 3)
#define OPT_PDFDOC_NO_DEST_REMOVE (1 << 4)
#define OPT_PDFOBJ_NO_PREDICTOR (1 << 5)
#define OPT_PDFOBJ_NO_OBJSTM (1 << 6)
static char ignore_colors = 0;
static double annot_grow = 0.0;
static int bookmark_open = 0;
static double mag = 1.0;
static int font_dpi = 600;
/*
* Precision is essentially limited to 0.01pt.
* See, dev_set_string() in pdfdev.c.
*/
static int pdfdecimaldigits = 3;
/* Image cache life in hours */
/* 0 means erase all old images and leave new images */
/* -1 means erase all old images and also erase new images */
/* -2 means ignore image cache (default) */
static int image_cache_life = -2;
/* Encryption */
static int do_encryption = 0;
static int key_bits = 40;
static int32_t permission = 0x003C;
time_t source_date_epoch = (time_t) -1;
/* Page device */
double paper_width = 595.0;
double paper_height = 842.0;
static double x_offset = 72.0;
static double y_offset = 72.0;
int landscape_mode = 0;
int always_embed = 0; /* always embed fonts, regardless of licensing flags */
/* XXX: there are four quasi-redundant versions of this; grp for K_UNIT__PT */
static int
read_length (double *vp, const char **pp, const char *endptr)
{
char *q;
const char *p = *pp;
double v, u = 1.0;
const char *_ukeys[] = {
#define K_UNIT__PT 0
#define K_UNIT__IN 1
#define K_UNIT__CM 2
#define K_UNIT__MM 3
#define K_UNIT__BP 4
#define K_UNIT__PC 5
#define K_UNIT__DD 6
#define K_UNIT__CC 7
#define K_UNIT__SP 8
"pt", "in", "cm", "mm", "bp", "pc", "dd", "cc", "sp",
NULL
};
int k, error = 0;
q = parse_float_decimal(&p, endptr);
if (!q) {
*vp = 0.0; *pp = p;
return -1;
}
v = atof(q);
free(q);
skip_white(&p, endptr);
q = parse_c_ident(&p, endptr);
if (q) {
char *qq = q;
if (strlen(q) >= strlen("true") &&
!memcmp(q, "true", strlen("true"))) {
q += strlen("true"); /* just skip "true" */
}
if (strlen(q) == 0) {
free(qq);
skip_white(&p, endptr);
qq = q = parse_c_ident(&p, endptr);
}
if (q) {
for (k = 0; _ukeys[k] && strcmp(_ukeys[k], q); k++);
switch (k) {
case K_UNIT__PT: u *= 72.0 / 72.27; break;
case K_UNIT__IN: u *= 72.0; break;
case K_UNIT__CM: u *= 72.0 / 2.54 ; break;
case K_UNIT__MM: u *= 72.0 / 25.4 ; break;
case K_UNIT__BP: u *= 1.0 ; break;
case K_UNIT__PC: u *= 12.0 * 72.0 / 72.27 ; break;
case K_UNIT__DD: u *= 1238.0 / 1157.0 * 72.0 / 72.27 ; break;
case K_UNIT__CC: u *= 12.0 * 1238.0 / 1157.0 * 72.0 / 72.27 ; break;
case K_UNIT__SP: u *= 72.0 / (72.27 * 65536) ; break;
default:
dpx_warning("Unknown unit of measure: %s", q);
error = -1;
break;
}
free(qq);
}
else {
dpx_warning("Missing unit of measure after \"true\"");
error = -1;
}
}
*vp = v * u; *pp = p;
return error;
}
static void
select_paper (const char *paperspec)
{
const struct paper *pi;
int error = 0;
pi = paperinfo(paperspec);
if (pi && papername(pi)) {
paper_width = paperpswidth (pi);
paper_height = paperpsheight(pi);
} else {
const char *p = paperspec, *endptr, *comma;
comma = strchr(p, ',');
endptr = p + strlen(p);
if (!comma)
_tt_abort("Unrecognized paper format: %s", paperspec);
error = read_length(&paper_width, &p, comma);
p = comma + 1;
error = read_length(&paper_height, &p, endptr);
}
if (error || paper_width <= 0.0 || paper_height <= 0.0)
_tt_abort("Invalid paper size: %s (%.2fx%.2f)", paperspec, paper_width, paper_height);
}
static void
select_pages (
const char *pagespec,
PageRange **ret_page_ranges,
unsigned int *ret_num_page_ranges)
{
PageRange *page_ranges = NULL;
unsigned int num_page_ranges = 0;
unsigned int max_page_ranges = 0;
char *q;
const char *p = pagespec;
while (*p != '\0') {
/* Enlarge page range table if necessary */
if (num_page_ranges >= max_page_ranges) {
max_page_ranges += 4;
page_ranges = RENEW(page_ranges, max_page_ranges, PageRange);
}
page_ranges[num_page_ranges].first = 0;
page_ranges[num_page_ranges].last = 0;
for ( ; *p && isspace((unsigned char)*p); p++);
q = parse_unsigned(&p, p + strlen(p)); /* Can't be signed. */
if (q) { /* '-' is allowed here */
page_ranges[num_page_ranges].first = atoi(q) - 1;
page_ranges[num_page_ranges].last = page_ranges[num_page_ranges].first;
free(q);
}
for ( ; *p && isspace((unsigned char)*p); p++);
if (*p == '-') {
for (++p; *p && isspace((unsigned char)*p); p++);
page_ranges[num_page_ranges].last = -1;
if (*p) {
q = parse_unsigned(&p, p + strlen(p));
if (q) {
page_ranges[num_page_ranges].last = atoi(q) - 1;
free(q);
}
for ( ; *p && isspace((unsigned char)*p); p++);
}
} else {
page_ranges[num_page_ranges].last = page_ranges[num_page_ranges].first;
}
num_page_ranges++;
if (*p == ',')
p++;
else {
for ( ; *p && isspace((unsigned char)*p); p++);
if (*p)
_tt_abort("Bad page range specification: %s", p);
}
}
*ret_page_ranges = page_ranges;
*ret_num_page_ranges = num_page_ranges;
}
static void
system_default (void)
{
if (systempapername() != NULL) {
select_paper(systempapername());
} else if (defaultpapername() != NULL) {
select_paper(defaultpapername());
}
}
#define SWAP(v1,v2) do {\
double _tmp = (v1);\
(v1) = (v2);\
(v2) = _tmp;\
} while (0)
static void
do_dvi_pages (PageRange *page_ranges, unsigned int num_page_ranges)
{
int page_no, step;
unsigned int page_count, i;
double page_width, page_height;
double init_paper_width, init_paper_height;
pdf_rect mediabox;
spc_exec_at_begin_document();
init_paper_width = page_width = paper_width;
init_paper_height = page_height = paper_height;
page_count = 0;
mediabox.llx = 0.0;
mediabox.lly = 0.0;
mediabox.urx = paper_width;
mediabox.ury = paper_height;
pdf_doc_set_mediabox(0, &mediabox); /* Root node */
for (i = 0; i < num_page_ranges && dvi_npages(); i++) {
if (page_ranges[i].last < 0)
page_ranges[i].last += dvi_npages();
step = (page_ranges[i].first <= page_ranges[i].last) ? 1 : -1;
page_no = page_ranges[i].first;
while (dvi_npages()) {
if (page_no < dvi_npages()) {
double w, h, xo, yo;
int lm;
dpx_message("[%d", page_no+1);
/* Users want to change page size even after page is started! */
page_width = paper_width; page_height = paper_height;
w = page_width; h = page_height; lm = landscape_mode;
xo = x_offset; yo = y_offset;
dvi_scan_specials(page_no, &w, &h, &xo, &yo, &lm, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
if (lm != landscape_mode) {
SWAP(w, h);
landscape_mode = lm;
}
if (page_width != w || page_height != h) {
page_width = w;
page_height = h;
}
if (x_offset != xo || y_offset != yo) {
x_offset = xo;
y_offset = yo;
}
if (page_width != init_paper_width ||
page_height != init_paper_height) {
mediabox.llx = 0.0;
mediabox.lly = 0.0;
mediabox.urx = page_width;
mediabox.ury = page_height;
pdf_doc_set_mediabox(page_count+1, &mediabox);
}
dvi_do_page(page_height, x_offset, y_offset);
page_count++;
dpx_message("]");
}
if (step > 0 &&
page_no >= page_ranges[i].last)
break;
else if (step < 0 &&
page_no <= page_ranges[i].last)
break;
else {
page_no += step;
}
}
}
if (page_count < 1) {
_tt_abort("No pages fall in range!");
}
spc_exec_at_end_document();
}
int
dvipdfmx_main (
const char *pdf_filename,
const char *dvi_filename,
const char *pagespec,
int opt_flags,
bool translate,
bool compress,
bool deterministic_tags,
bool quiet,
unsigned int verbose,
time_t build_date)
{
bool enable_object_stream = true;
double dvi2pts;
unsigned int num_page_ranges = 0;
PageRange *page_ranges = NULL;
assert(pdf_filename);
assert(dvi_filename);
translate_origin = translate;
dvi_reset_global_state();
tfm_reset_global_state();
vf_reset_global_state();
pdf_dev_reset_global_state();
pdf_obj_reset_global_state();
pdf_font_reset_unique_tag_state();
if (quiet) {
shut_up(2);
} else {
dvi_set_verbose(verbose);
pdf_dev_set_verbose(verbose);
pdf_doc_set_verbose(verbose);
pdf_enc_set_verbose(verbose);
pdf_obj_set_verbose(verbose);
pdf_fontmap_set_verbose(verbose);
dpx_file_set_verbose(verbose);
tt_aux_set_verbose(verbose);
}
pdf_set_compression(compress ? 9 : 0);
pdf_font_set_deterministic_unique_tags(deterministic_tags ? 1 : 0);
system_default();
pdf_init_fontmaps(); /* This must come before parsing options... */
/* We used to read the config file here. It synthesized command-line
* arguments, so we emulate the default TeXLive config file by copying those
* code bits. */
pdf_set_version (5);
select_paper("letter");
annot_grow = 0;
bookmark_open = 0;
key_bits = 40;
permission = 0x003C;
font_dpi = 600;
pdfdecimaldigits = 5;
image_cache_life = -2;
source_date_epoch = build_date;
pdf_load_fontmap_file("pdftex.map", FONTMAP_RMODE_APPEND);
pdf_load_fontmap_file("kanjix.map", FONTMAP_RMODE_APPEND);
pdf_load_fontmap_file("ckx.map", FONTMAP_RMODE_APPEND);
if (pagespec) {
select_pages(pagespec, &page_ranges, &num_page_ranges);
}
if (!page_ranges) {
page_ranges = NEW(1, PageRange);
}
if (num_page_ranges == 0) {
page_ranges[0].first = 0;
page_ranges[0].last = -1; /* last page */
num_page_ranges = 1;
}
/*kpse_init_prog("", font_dpi, NULL, NULL);
kpse_set_program_enabled(kpse_pk_format, true, kpse_src_texmf_cnf);*/
pdf_font_set_dpi(font_dpi);
dpx_delete_old_cache(image_cache_life);
pdf_enc_compute_id_string(dvi_filename, pdf_filename);
{
int ver_major = 0, ver_minor = 0;
char owner_pw[MAX_PWD_LEN], user_pw[MAX_PWD_LEN];
/* Dependency between DVI and PDF side is rather complicated... */
dvi2pts = dvi_init(dvi_filename, mag);
if (dvi2pts == 0.0)
_tt_abort("dvi_init() failed!");
pdf_doc_set_creator(dvi_comment());
dvi_scan_specials(0,
&paper_width, &paper_height,
&x_offset, &y_offset, &landscape_mode,
&ver_major, &ver_minor,
&do_encryption, &key_bits, &permission, owner_pw, user_pw);
if (ver_minor >= PDF_VERSION_MIN && ver_minor <= PDF_VERSION_MAX) {
pdf_set_version(ver_minor);
}
if (do_encryption) {
if (!(key_bits >= 40 && key_bits <= 128 && (key_bits % 8 == 0)) &&
key_bits != 256)
_tt_abort("Invalid encryption key length specified: %u", key_bits);
else if (key_bits > 40 && pdf_get_version() < 4)
_tt_abort("Chosen key length requires at least PDF 1.4. " \
"Use \"-V 4\" to change.");
do_encryption = 1;
pdf_enc_set_passwd(key_bits, permission, owner_pw, user_pw);
}
if (landscape_mode) {
SWAP(paper_width, paper_height);
}
}
pdf_files_init();
if (opt_flags & OPT_PDFOBJ_NO_OBJSTM)
enable_object_stream = false;
/* Set default paper size here so that all page's can inherite it.
* annot_grow: Margin of annotation.
* bookmark_open: Miximal depth of open bookmarks.
*/
pdf_open_document(pdf_filename, do_encryption, enable_object_stream,
paper_width, paper_height, annot_grow, bookmark_open,
!(opt_flags & OPT_PDFDOC_NO_DEST_REMOVE));
/* Ignore_colors placed here since
* they are considered as device's capacity.
*/
pdf_init_device(dvi2pts, pdfdecimaldigits, ignore_colors);
if (opt_flags & OPT_CIDFONT_FIXEDPITCH)
CIDFont_set_flags(CIDFONT_FORCE_FIXEDPITCH);
/* Please move this to spc_init_specials(). */
if (opt_flags & OPT_TPIC_TRANSPARENT_FILL)
tpic_set_fill_mode(1);
if (opt_flags & OPT_PDFOBJ_NO_PREDICTOR)
pdf_set_use_predictor(0); /* No prediction */
do_dvi_pages(page_ranges, num_page_ranges);
pdf_files_close();
/* Order of close... */
pdf_close_device ();
/* pdf_close_document flushes XObject (image) and other resources. */
pdf_close_document();
pdf_close_fontmaps(); /* pdf_font may depend on fontmap. */
dvi_close();
dpx_message("\n");
free(page_ranges);
return 0;
}
|
fmgoncalves/tectonic
|
tectonic/dpx-cff_types.h
|
<gh_stars>1-10
/* This is dvipdfmx, an eXtended version of dvipdfm by <NAME>.
Copyright (C) 2002-2016 by <NAME> and <NAME>,
the dvipdfmx project team.
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.
*/
#ifndef _CFF_TYPES_H_
#define _CFF_TYPES_H_
#include "dpx-core.h"
#include <stdint.h>
/* CFF Data Types */
#define CFF_TYPE_UNKNOWN 0
#define CFF_TYPE_INTEGER (1 << 0)
#define CFF_TYPE_REAL (1 << 1)
#define CFF_TYPE_NUMBER (CFF_TYPE_INTEGER|CFF_TYPE_REAL)
#define CFF_TYPE_BOOLEAN (1 << 2)
#define CFF_TYPE_SID (1 << 3)
#define CFF_TYPE_ARRAY (1 << 4)
#define CFF_TYPE_DELTA (1 << 5)
/* SID SID number */
#define CFF_TYPE_ROS (1 << 6)
/* offset(0) */
#define CFF_TYPE_OFFSET (1 << 7)
/* size offset(0) */
#define CFF_TYPE_SZOFF (1 << 8)
typedef unsigned char card8; /* 1-byte unsigned number */
typedef unsigned short card16; /* 2-byte unsigned number */
typedef unsigned char c_offsize; /* 1-byte unsigned number specifies the size
of an Offset field or fields, range 1-4 */
typedef uint32_t l_offset; /* 1, 2, 3, or 4-byte offset */
typedef unsigned short s_SID; /* 2-byte string identifier */
typedef struct {
card16 count; /* number of objects stored in INDEX */
c_offsize offsize; /* Offset array element size, 1-4 */
l_offset *offset; /* Offset array, count + 1 offsets */
card8 *data; /* Object data */
} cff_index;
typedef struct {
card8 major; /* format major version (starting at 1) */
card8 minor; /* format minor version (starting at 0) */
card8 hdr_size; /* Header size (bytes) */
c_offsize offsize; /* Absolute offset (0) size */
} cff_header;
/* Dictionary */
typedef struct {
int id; /* encoded data value (as card8 or card16) */
const char *key; /* opname */
int count; /* number of values */
double *values; /* values */
} cff_dict_entry;
typedef struct {
int max;
int count;
cff_dict_entry *entries;
} cff_dict;
/* Encoding, Charset and FDSelect */
typedef struct
{
s_SID first; /* SID or CID, or card8 for Encoding */
card8 n_left; /* no. of remaining gids/codes in this range */
} cff_range1;
typedef struct
{
s_SID first; /* SID or CID (card16) */
card16 n_left; /* card16-version of range1 */
} cff_range2;
typedef struct
{
card8 code;
s_SID glyph;
} cff_map;
typedef struct
{
card8 format; /* if (format & 0x80) then have supplement */
card8 num_entries; /* number of entries */
union {
card8 *codes; /* format 0 */
cff_range1 *range1; /* format 1 */
} data;
card8 num_supps; /* number of supplementary data */
cff_map *supp; /* supplement */
} cff_encoding;
typedef struct
{
card8 format;
card16 num_entries;
union {
s_SID *glyphs; /* format 0 */
cff_range1 *range1; /* format 1 */
cff_range2 *range2; /* format 2 */
} data;
} cff_charsets;
/* CID-Keyed font specific */
typedef struct
{
card16 first;
card8 fd;
} cff_range3;
typedef struct
{
card8 format;
card16 num_entries; /* number of glyphs/ranges */
union {
card8 *fds; /* format 0 */
cff_range3 *ranges; /* format 3 */
} data;
/* card16 sentinel; */ /* format 3 only, must be equals to num_glyphs */
} cff_fdselect;
#endif /* _CFF_TYPES_H_ */
|
fmgoncalves/tectonic
|
tectonic/dpx-pdfdev.c
|
<gh_stars>1-10
/* This is dvipdfmx, an eXtended version of dvipdfm by <NAME>.
Copyright (C) 2002-2016 by <NAME> and <NAME>,
the dvipdfmx project team.
Copyright (C) 1998, 1999 by <NAME> <<EMAIL>>
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 "dpx-pdfdev.h"
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "core-bridge.h"
#include "dpx-cff.h"
#include "dpx-cff_types.h"
#include "dpx-cmap.h"
#include "dpx-dvi.h"
#include "dpx-error.h"
#include "dpx-fontmap.h"
#include "dpx-mem.h"
#include "dpx-mfileio.h"
#include "dpx-numbers.h"
#include "dpx-pdfcolor.h"
#include "dpx-pdfdoc.h"
#include "dpx-pdfdraw.h"
#include "dpx-pdffont.h"
#include "dpx-pdfobj.h"
#include "dpx-pdfximage.h"
#include "dpx-type0.h"
static int verbose = 0;
void
pdf_dev_set_verbose (int level)
{
verbose = level;
}
/* Not working yet... */
double
pdf_dev_scale (void)
{
return 1.0;
}
/*
* Unit conversion, formatting and others.
*/
#define TEX_ONE_HUNDRED_BP 6578176
static struct {
double dvi2pts;
int min_bp_val; /* Shortest resolvable distance in the output PDF. */
int precision; /* Number of decimal digits (in fractional part) kept. */
} dev_unit = {
0.0,
658,
2
};
double
dev_unit_dviunit (void)
{
return (1.0/dev_unit.dvi2pts);
}
#define DEV_PRECISION_MAX 8
static uint32_t ten_pow[10] = {
1u, 10u, 100u, 1000u, 10000u, 100000u, 1000000u, 10000000u, 100000000u, 1000000000u
};
static double ten_pow_inv[10] = {
1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001, 0.0000001, 0.00000001, 0.000000001
};
#define bpt2spt(b) ( (spt_t) round( (b) / dev_unit.dvi2pts ) )
#define spt2bpt(s) ( (s) * dev_unit.dvi2pts )
#define dround_at(v,p) (ROUND( (v), ten_pow_inv[(p)] ))
static unsigned int
p_itoa (int value, char *buf)
{
unsigned int sign, ndigits;
char *p = buf;
if (value < 0) {
*p++ = '-';
value = -value;
sign = 1;
} else {
sign = 0;
}
ndigits = 0;
/* Generate at least one digit in reverse order */
do {
p[ndigits++] = (value % 10) + '0';
value /= 10;
} while (value != 0);
/* Reverse the digits */
{
unsigned int i;
for (i = 0; i < ndigits / 2 ; i++) {
char tmp = p[i];
p[i] = p[ndigits-i-1];
p[ndigits-i-1] = tmp;
}
}
p[ndigits] = '\0';
return (sign ? ndigits + 1 : ndigits);
}
/* NOTE: Acrobat 5 and prior uses 16.16 fixed point representation for
* real numbers.
*/
static int
p_dtoa (double value, int prec, char *buf)
{
const int32_t p[10] = { 1, 10, 100, 1000, 10000,
100000, 1000000, 10000000,
100000000, 1000000000 };
double i, f;
int32_t g;
char *c = buf;
int n;
if (value < 0) {
value = -value;
*c++ = '-';
n = 1;
} else {
n = 0;
}
f = modf(value, &i);
g = (int32_t) (f * p[prec] + 0.5);
if (g == p[prec]) {
g = 0;
i += 1;
}
if (i) {
int m = sprintf(c, "%.0f", i);
c += m;
n += m;
} else if (g == 0) {
*(c = buf) = '0';
n = 1;
}
if (g) {
int j = prec;
*c++ = '.';
while (j--) {
c[j] = (g % 10) + '0';
g /= 10;
}
c += prec - 1;
n += 1 + prec;
while (*c == '0') {
c--;
n--;
}
}
*(++c) = 0;
return n;
}
static int
dev_sprint_bp (char *buf, spt_t value, spt_t *error)
{
double value_in_bp;
double error_in_bp;
int prec = dev_unit.precision;
value_in_bp = spt2bpt(value);
if (error) {
error_in_bp = value_in_bp - dround_at(value_in_bp, prec);
*error = bpt2spt(error_in_bp);
}
return p_dtoa(value_in_bp, prec, buf);
}
/* They are affected by precision (set at device initialization). */
int
pdf_sprint_matrix (char *buf, const pdf_tmatrix *M)
{
int len;
int prec2 = MIN(dev_unit.precision + 2, DEV_PRECISION_MAX);
int prec0 = MAX(dev_unit.precision, 2);
len = p_dtoa(M->a, prec2, buf);
buf[len++] = ' ';
len += p_dtoa(M->b, prec2, buf+len);
buf[len++] = ' ';
len += p_dtoa(M->c, prec2, buf+len);
buf[len++] = ' ';
len += p_dtoa(M->d, prec2, buf+len);
buf[len++] = ' ';
len += p_dtoa(M->e, prec0, buf+len);
buf[len++] = ' ';
len += p_dtoa(M->f, prec0, buf+len);
buf[len] = '\0'; /* xxx_sprint_xxx NULL terminates strings. */
return len;
}
int
pdf_sprint_rect (char *buf, const pdf_rect *rect)
{
int len;
len = p_dtoa(rect->llx, dev_unit.precision, buf);
buf[len++] = ' ';
len += p_dtoa(rect->lly, dev_unit.precision, buf+len);
buf[len++] = ' ';
len += p_dtoa(rect->urx, dev_unit.precision, buf+len);
buf[len++] = ' ';
len += p_dtoa(rect->ury, dev_unit.precision, buf+len);
buf[len] = '\0'; /* xxx_sprint_xxx NULL terminates strings. */
return len;
}
int
pdf_sprint_coord (char *buf, const pdf_coord *p)
{
int len;
len = p_dtoa(p->x, dev_unit.precision, buf);
buf[len++] = ' ';
len += p_dtoa(p->y, dev_unit.precision, buf+len);
buf[len] = '\0'; /* xxx_sprint_xxx NULL terminates strings. */
return len;
}
int
pdf_sprint_length (char *buf, double value)
{
int len;
len = p_dtoa(value, dev_unit.precision, buf);
buf[len] = '\0'; /* xxx_sprint_xxx NULL terminates strings. */
return len;
}
int
pdf_sprint_number (char *buf, double value)
{
int len;
len = p_dtoa(value, DEV_PRECISION_MAX, buf);
buf[len] = '\0'; /* xxx_sprint_xxx NULL terminates strings. */
return len;
}
static struct
{
/* Text composition (direction) mode is ignored (always same
* as font's writing mode) if autorotate is unset (value zero).
*/
int autorotate;
/*
* Ignore color migrated to here. This is device's capacity.
* colormode 0 for ignore colors
*/
int colormode;
} dev_param = {
1, /* autorotate */
1, /* colormode */
};
/*
* Text handling routines.
*/
/* Motion state:
* GRAPHICS_MODE Initial state (not within BT/ET block nor in string)
* TEXT_MODE Text section is started via BT operator but not
* in string.
* STRING_MODE In string. A string or array of strings are currently
* in process. May started '[', '<' or '('.
*/
#define GRAPHICS_MODE 1
#define TEXT_MODE 2
#define STRING_MODE 3
static int motion_state = GRAPHICS_MODE;
#define FORMAT_BUF_SIZE 4096
static char format_buffer[FORMAT_BUF_SIZE];
/*
* In PDF, vertical text positioning is always applied when current font
* is vertical font. While ASCII pTeX manages current writing direction
* and font's WMode separately.
*
* 000/101 WMODE_HH/VV h(v) font, h(v) direction.
* 001 WMODE_HV -90 deg. rotated
* 100 WMODE_VH +90 deg. rotated
* 011 WMODE_HD +90 deg. rotated
* 111 WMODE_VD 180 deg. rotated
* In MetaPost PostScript file processing (mp_mode = 1), only HH/VV mode
* is applied.
*/
#define TEXT_WMODE_HH 0
#define TEXT_WMODE_HV 1
#define TEXT_WMODE_VH 4
#define TEXT_WMODE_VV 5
#define TEXT_WMODE_HD 3
#define TEXT_WMODE_VD 7
#define ANGLE_CHANGES(m1,m2) ((abs((m1)-(m2)) % 5) == 0 ? 0 : 1)
#define ROTATE_TEXT(m) ((m) != TEXT_WMODE_HH && (m) != TEXT_WMODE_VV)
static struct {
/* Current font.
* This is index within dev_fonts.
*/
int font_id;
/* Dvipdfmx does compression of text by doing text positioning
* in relative motion and uses string array [(foo) -250 (bar)]
* with kerning (negative kern is used for white space as suited
* for TeX). This is offset within current string.
*/
spt_t offset;
/* This is reference point of strings.
* It may include error correction induced by rounding.
*/
spt_t ref_x;
spt_t ref_y;
/* Using text raise and leading is highly recommended for
* text extraction to work properly. But not implemented yet.
* We can't do consice output for \TeX without this.
*/
spt_t raise; /* unused */
spt_t leading; /* unused */
/* This is not always text matrix but rather font matrix.
* We do not use horizontal scaling in PDF text state parameter
* since they always apply scaling in fixed direction regardless
* of writing mode.
*/
struct {
double slant;
double extend;
int rotate; /* TEXT_WMODE_XX */
} matrix;
/* Fake bold parameter:
* If bold_param is positive, use text rendering mode
* fill-then-stroke with stroking line width specified
* by bold_param.
*/
double bold_param;
/* Text composition (direction) mode. */
int dir_mode;
/* internal */
/* Flag indicating text matrix to be forcibly reset.
* Enabled if synthetic font features (slant, extend, etc)
* are used for current font or when text rotation mode
* changes.
*/
int force_reset;
/* This information is duplicated from dev[font_id].format.
* Set to 1 if font is composite (Type0) font.
*/
int is_mb;
} text_state = {
-1, /* font */
0, /* offset */
0, 0, /* ref_x, ref_y */
0, 0, /* raise, leading */
{0.0, 1.0, 0},
0.0, /* Experimental boldness param */
0, /* dir_mode */
/* internal */
0, /* force_reset */
0 /* is_mb */
};
#define PDF_FONTTYPE_SIMPLE 1
#define PDF_FONTTYPE_BITMAP 2
#define PDF_FONTTYPE_COMPOSITE 3
struct dev_font {
/* Needs to be big enough to hold name "Fxxx"
* where xxx is number of largest font
*/
char short_name[7]; /* Resource name */
int used_on_this_page;
char *tex_name; /* String identifier of this font */
spt_t sptsize; /* Point size */
/* Returned values from font/encoding layer:
*
* The font_id and enc_id is font and encoding (CMap) identifier
* used in pdf_font or encoding/cmap layer.
* The PDF object "resource" is an indirect reference object
* pointing font resource of this font. The used_chars is somewhat
* misleading, this is actually used_glyphs in CIDFont for Type0
* and is 65536/8 bytes binary data with each bits representing
* whether the glyph is in-use or not. It is 256 char array for
* simple font.
*/
int font_id;
int enc_id;
/* if >= 0, index of a dev_font that really has the resource and used_chars */
int real_font_index;
pdf_obj *resource;
char *used_chars;
/* Font format:
* simple, composite or bitmap.
*/
int format;
/* Writing mode:
* Non-zero for vertical. Duplicated from CMap.
*/
int wmode;
/* Syntetic Font:
*
* We use text matrix for creating extended or slanted font,
* but not with font's FontMatrix since TrueType and Type0
* font don't support them.
*/
double extend;
double slant;
double bold; /* Boldness prameter */
/* Compatibility */
int mapc; /* Nasty workaround for Omega */
/* There are no font metric format supporting four-bytes
* charcter code. So we should provide an option to specify
* UCS group and plane.
*/
int ucs_group;
int ucs_plane;
int is_unicode;
cff_charsets *cff_charsets;
};
static struct dev_font *dev_fonts = NULL;
static int num_dev_fonts = 0;
static int max_dev_fonts = 0;
static int num_phys_fonts = 0;
#define CURRENTFONT() ((text_state.font_id < 0) ? NULL : &(dev_fonts[text_state.font_id]))
#define GET_FONT(n) (&(dev_fonts[(n)]))
static void
dev_set_text_matrix (spt_t xpos, spt_t ypos, double slant, double extend, int rotate)
{
pdf_tmatrix tm;
int len = 0;
/* slant is negated for vertical font so that right-side
* is always lower. */
switch (rotate) {
case TEXT_WMODE_VH:
/* Vertical font */
tm.a = slant ; tm.b = 1.0;
tm.c = -extend; tm.d = 0.0 ;
break;
case TEXT_WMODE_HV:
/* Horizontal font */
tm.a = 0.0; tm.b = -extend;
tm.c = 1.0; tm.d = -slant ;
break;
case TEXT_WMODE_HH:
/* Horizontal font */
tm.a = extend; tm.b = 0.0;
tm.c = slant ; tm.d = 1.0;
break;
case TEXT_WMODE_VV:
/* Vertical font */
tm.a = 1.0; tm.b = -slant;
tm.c = 0.0; tm.d = extend;
break;
case TEXT_WMODE_HD:
/* Horizontal font */
tm.a = 0.0; tm.b = extend;
tm.c = -1.0; tm.d = slant ;
break;
case TEXT_WMODE_VD:
/* Vertical font */
tm.a = -1.0; tm.b = slant;
tm.c = 0.0; tm.d = -extend;
break;
}
tm.e = xpos * dev_unit.dvi2pts;
tm.f = ypos * dev_unit.dvi2pts;
format_buffer[len++] = ' ';
len += pdf_sprint_matrix(format_buffer+len, &tm);
format_buffer[len++] = ' ';
format_buffer[len++] = 'T';
format_buffer[len++] = 'm';
pdf_doc_add_page_content(format_buffer, len); /* op: Tm */
text_state.ref_x = xpos;
text_state.ref_y = ypos;
text_state.matrix.slant = slant;
text_state.matrix.extend = extend;
text_state.matrix.rotate = rotate;
}
/*
* reset_text_state() outputs a BT and does any necessary coordinate
* transformations to get ready to ship out text.
*/
static void
reset_text_state (void)
{
/*
* We need to reset the line matrix to handle slanted fonts.
*/
pdf_doc_add_page_content(" BT", 3); /* op: BT */
/*
* text_state.matrix is identity at top of page.
* This sometimes write unnecessary "Tm"s when transition from
* GRAPHICS_MODE to TEXT_MODE occurs.
*/
if (text_state.force_reset ||
text_state.matrix.slant != 0.0 ||
text_state.matrix.extend != 1.0 ||
ROTATE_TEXT(text_state.matrix.rotate)) {
dev_set_text_matrix(0, 0,
text_state.matrix.slant,
text_state.matrix.extend,
text_state.matrix.rotate);
}
text_state.ref_x = 0;
text_state.ref_y = 0;
text_state.offset = 0;
text_state.force_reset = 0;
}
static void
text_mode (void)
{
switch (motion_state) {
case TEXT_MODE:
break;
case STRING_MODE:
pdf_doc_add_page_content(text_state.is_mb ? ">]TJ" : ")]TJ", 4); /* op: TJ */
break;
case GRAPHICS_MODE:
reset_text_state();
break;
}
motion_state = TEXT_MODE;
text_state.offset = 0;
}
void
graphics_mode (void)
{
switch (motion_state) {
case GRAPHICS_MODE:
break;
case STRING_MODE:
pdf_doc_add_page_content(text_state.is_mb ? ">]TJ" : ")]TJ", 4); /* op: TJ */
/* continue */
case TEXT_MODE:
pdf_doc_add_page_content(" ET", 3); /* op: ET */
text_state.force_reset = 0;
text_state.font_id = -1;
break;
}
motion_state = GRAPHICS_MODE;
}
static void
start_string (spt_t xpos, spt_t ypos, double slant, double extend, int rotate)
{
spt_t delx, dely, error_delx = 0, error_dely = 0;
spt_t desired_delx, desired_dely;
int len = 0;
delx = xpos - text_state.ref_x;
dely = ypos - text_state.ref_y;
/*
* Precompensating for line transformation matrix.
*
* Line transformation matrix L for horizontal font in horizontal
* mode and it's inverse I is
*
* | e 0| | 1/e 0|
* L_hh = | | , I_hh = | |
* | s 1| |-s/e 1|
*
* For vertical font in vertical mode,
*
* | 1 -s| | 1 s/e|
* L_vv = | | , I_vv = | |
* | 0 e| | 0 1/e|
*
* For vertical font in horizontal mode,
*
* | s 1| | 0 1|
* L_vh = | | = L_vv x | |
* |-e 0| |-1 0|
*
* | 0 -1|
* I_vh = | | x I_vv
* | 1 0|
*
* For horizontal font in vertical mode,
*
* | 0 -e| | 0 -1|
* L_hv = | | = L_hh x | |
* | 1 -s| | 1 0|
*
* | 0 1|
* I_hv = | | x I_hh
* |-1 0|
*
*/
switch (rotate) {
case TEXT_WMODE_VH:
/* Vertical font in horizontal mode: rot = +90
* | 0 -1/e|
* d_user = d x I_vh = d x | |
* | 1 s/e|
*/
desired_delx = dely;
desired_dely = (spt_t) (-(delx - dely*slant)/extend);
/* error_del is in device space
*
* | 0 1|
* e = e_user x | | = (-e_user_y, e_user_x)
* |-1 0|
*
* We must care about rotation here but not extend/slant...
* The extend and slant actually is font matrix.
*/
format_buffer[len++] = ' ';
len += dev_sprint_bp(format_buffer+len, desired_delx, &error_dely);
format_buffer[len++] = ' ';
len += dev_sprint_bp(format_buffer+len, desired_dely, &error_delx);
error_delx = -error_delx;
break;
case TEXT_WMODE_HV:
/* Horizontal font in vertical mode: rot = -90
*
* |-s/e 1|
* d_user = d x I_hv = d x | |
* |-1/e 0|
*/
desired_delx = (spt_t)(-(dely + delx*slant)/extend);
desired_dely = delx;
/*
* e = (e_user_y, -e_user_x)
*/
format_buffer[len++] = ' ';
len += dev_sprint_bp(format_buffer+len, desired_delx, &error_dely);
format_buffer[len++] = ' ';
len += dev_sprint_bp(format_buffer+len, desired_dely, &error_delx);
error_dely = -error_dely;
break;
case TEXT_WMODE_HH:
/* Horizontal font in horizontal mode:
* | 1/e 0|
* d_user = d x I_hh = d x | |
* |-s/e 1|
*/
desired_delx = (spt_t)((delx - dely*slant)/extend);
desired_dely = dely;
format_buffer[len++] = ' ';
len += dev_sprint_bp(format_buffer+len, desired_delx, &error_delx);
format_buffer[len++] = ' ';
len += dev_sprint_bp(format_buffer+len, desired_dely, &error_dely);
break;
case TEXT_WMODE_VV:
/* Vertical font in vertical mode:
* | 1 s/e|
* d_user = d x I_vv = d x | |
* | 0 1/e|
*/
desired_delx = delx;
desired_dely = (spt_t)((dely + delx*slant)/extend);
format_buffer[len++] = ' ';
len += dev_sprint_bp(format_buffer+len, desired_delx, &error_delx);
format_buffer[len++] = ' ';
len += dev_sprint_bp(format_buffer+len, desired_dely, &error_dely);
break;
case TEXT_WMODE_HD:
/* Horizontal font in down-to-up mode: rot = +90
*
* | s/e -1|
* d_user = d x -I_hv = d x | |
* | 1/e 0|
*/
desired_delx = -(spt_t)(-(dely + delx*slant)/extend);
desired_dely = -delx;
format_buffer[len++] = ' ';
len += dev_sprint_bp(format_buffer+len, desired_delx, &error_dely);
format_buffer[len++] = ' ';
len += dev_sprint_bp(format_buffer+len, desired_dely, &error_delx);
error_delx = -error_delx;
error_dely = -error_dely;
break;
case TEXT_WMODE_VD:
/* Vertical font in down-to-up mode: rot = 180
* |-1 -s/e|
* d_user = d x -I_vv = d x | |
* | 0 -1/e|
*/
desired_delx = -delx;
desired_dely = -(spt_t)((dely + delx*slant)/extend);
format_buffer[len++] = ' ';
len += dev_sprint_bp(format_buffer+len, desired_delx, &error_delx);
format_buffer[len++] = ' ';
len += dev_sprint_bp(format_buffer+len, desired_dely, &error_dely);
error_delx = -error_delx;
error_dely = -error_dely;
break;
}
pdf_doc_add_page_content(format_buffer, len); /* op: */
/*
* dvipdfm wrongly using "TD" in place of "Td".
* The TD operator set leading, but we are not using T* etc.
*/
pdf_doc_add_page_content(text_state.is_mb ? " Td[<" : " Td[(", 5); /* op: Td */
/* Error correction */
text_state.ref_x = xpos - error_delx;
text_state.ref_y = ypos - error_dely;
text_state.offset = 0;
}
static void
string_mode (spt_t xpos, spt_t ypos, double slant, double extend, int rotate)
{
switch (motion_state) {
case STRING_MODE:
break;
case GRAPHICS_MODE:
reset_text_state();
/* continue */
case TEXT_MODE:
if (text_state.force_reset) {
dev_set_text_matrix(xpos, ypos, slant, extend, rotate);
pdf_doc_add_page_content(text_state.is_mb ? "[<" : "[(", 2); /* op: */
text_state.force_reset = 0;
} else {
start_string(xpos, ypos, slant, extend, rotate);
}
break;
}
motion_state = STRING_MODE;
}
/*
* The purpose of the following routine is to force a Tf only
* when it's actually necessary. This became a problem when the
* VF code was added. The VF spec says to instantiate the
* first font contained in the VF file before drawing a virtual
* character. However, that font may not be used for
* many characters (e.g. small caps fonts). For this reason,
* dev_select_font() should not force a "physical" font selection.
* This routine prevents a PDF Tf font selection until there's
* really a character in that font.
*/
static int
dev_set_font (int font_id)
{
struct dev_font *font;
struct dev_font *real_font;
int text_rotate;
double font_scale;
int len;
int vert_dir, vert_font;
/* text_mode() must come before text_state.is_mb is changed. */
text_mode();
font = GET_FONT(font_id);
assert(font); /* Caller should check font_id. */
if (font->real_font_index >= 0)
real_font = GET_FONT(font->real_font_index);
else
real_font = font;
text_state.is_mb = (font->format == PDF_FONTTYPE_COMPOSITE) ? 1 : 0;
vert_font = font->wmode ? 1 : 0;
if (dev_param.autorotate) {
vert_dir = text_state.dir_mode;
} else {
vert_dir = vert_font;
}
text_rotate = (vert_font << 2)|vert_dir;
if (font->slant != text_state.matrix.slant ||
font->extend != text_state.matrix.extend ||
ANGLE_CHANGES(text_rotate, text_state.matrix.rotate)) {
text_state.force_reset = 1;
}
text_state.matrix.slant = font->slant;
text_state.matrix.extend = font->extend;
text_state.matrix.rotate = text_rotate;
if (!real_font->resource) {
real_font->resource = pdf_get_font_reference(real_font->font_id);
real_font->used_chars = pdf_get_font_usedchars(real_font->font_id);
}
if (!real_font->used_on_this_page) {
pdf_doc_add_page_resource("Font",
real_font->short_name,
pdf_link_obj(real_font->resource));
real_font->used_on_this_page = 1;
}
font_scale = (double) font->sptsize * dev_unit.dvi2pts;
len = sprintf(format_buffer, " /%s", real_font->short_name); /* space not necessary. */
format_buffer[len++] = ' ';
len += p_dtoa(font_scale, MIN(dev_unit.precision+1, DEV_PRECISION_MAX), format_buffer+len);
format_buffer[len++] = ' ';
format_buffer[len++] = 'T';
format_buffer[len++] = 'f';
pdf_doc_add_page_content(format_buffer, len); /* op: Tf */
if (font->bold > 0.0 || font->bold != text_state.bold_param) {
if (font->bold <= 0.0)
len = sprintf(format_buffer, " 0 Tr");
else
len = sprintf(format_buffer, " 2 Tr %.6f w", font->bold); /* _FIXME_ */
pdf_doc_add_page_content(format_buffer, len); /* op: Tr w */
}
text_state.bold_param = font->bold;
text_state.font_id = font_id;
return 0;
}
/* Access text state parameters.
*/
int
pdf_dev_get_font_wmode (int font_id)
{
struct dev_font *font;
font = GET_FONT(font_id);
if (font) {
return font->wmode;
}
return 0;
}
static unsigned char sbuf0[FORMAT_BUF_SIZE];
static unsigned char sbuf1[FORMAT_BUF_SIZE];
static int
handle_multibyte_string (struct dev_font *font,
const unsigned char **str_ptr, size_t *str_len, int ctype)
{
const unsigned char *p;
size_t i, length;
p = *str_ptr;
length = *str_len;
if (ctype == -1 && font->cff_charsets) { /* freetype glyph indexes */
/* Convert freetype glyph indexes to CID. */
const unsigned char *inbuf = p;
unsigned char *outbuf = sbuf0;
for (i = 0; i < length; i += 2) {
unsigned int gid;
gid = *inbuf++ << 8;
gid += *inbuf++;
gid = cff_charsets_lookup_cid(font->cff_charsets, gid);
*outbuf++ = gid >> 8;
*outbuf++ = gid & 0xff;
}
p = sbuf0;
length = outbuf - sbuf0;
}
/* _FIXME_ */
else if (font->is_unicode) { /* UCS-4 */
if (ctype == 1) {
if (length * 4 >= FORMAT_BUF_SIZE) {
dpx_warning("Too long string...");
return -1;
}
for (i = 0; i < length; i++) {
sbuf1[i*4 ] = font->ucs_group;
sbuf1[i*4+1] = font->ucs_plane;
sbuf1[i*4+2] = '\0';
sbuf1[i*4+3] = p[i];
}
length *= 4;
} else if (ctype == 2) {
size_t len = 0;
if (length * 2 >= FORMAT_BUF_SIZE) {
dpx_warning("Too long string...");
return -1;
}
for (i = 0; i < length; i += 2, len += 4) {
sbuf1[len ] = font->ucs_group;
if ((p[i] & 0xf8) == 0xd8) {
int c;
/* Check for valid surrogate pair. */
if ((p[i] & 0xfc) != 0xd8 || i + 2 >= length || (p[i+2] & 0xfc) != 0xdc) {
dpx_warning("Invalid surrogate p[%"PRIuZ"]=%02X...", i, p[i]);
return -1;
}
c = (((p[i] & 0x03) << 10) | (p[i+1] << 2) | (p[i+2] & 0x03)) + 0x100;
sbuf1[len+1] = (c >> 8) & 0xff;
sbuf1[len+2] = c & 0xff;
i += 2;
} else {
sbuf1[len+1] = font->ucs_plane;
sbuf1[len+2] = p[i];
}
sbuf1[len+3] = p[i+1];
}
length = len;
}
p = sbuf1;
} else if (ctype == 1 && font->mapc >= 0) {
/* Omega workaround...
* Translate single-byte chars to double byte code space.
*/
if (length * 2 >= FORMAT_BUF_SIZE) {
dpx_warning("Too long string...");
return -1;
}
for (i = 0; i < length; i++) {
sbuf1[i*2 ] = (font->mapc & 0xff);
sbuf1[i*2+1] = p[i];
}
length *= 2;
p = sbuf1;
}
/*
* Font is double-byte font. Output is assumed to be 16-bit fixed length
* encoding.
* TODO: A character decomposed to multiple characters.
*/
if (ctype != -1 && font->enc_id >= 0) {
const unsigned char *inbuf;
unsigned char *outbuf;
size_t inbytesleft, outbytesleft;
CMap *cmap;
cmap = CMap_cache_get(font->enc_id);
inbuf = p;
outbuf = sbuf0;
inbytesleft = length;
outbytesleft = FORMAT_BUF_SIZE;
CMap_decode(cmap,
&inbuf, &inbytesleft, &outbuf, &outbytesleft);
if (inbytesleft != 0) {
dpx_warning("CMap conversion failed. (%"PRIuZ" bytes remains)", inbytesleft);
return -1;
}
length = FORMAT_BUF_SIZE - outbytesleft;
p = sbuf0;
}
*str_ptr = p;
*str_len = length;
return 0;
}
static pdf_coord *dev_coords = NULL;
static int num_dev_coords = 0;
static int max_dev_coords = 0;
void pdf_dev_get_coord(double *xpos, double *ypos)
{
if (num_dev_coords > 0) {
*xpos = dev_coords[num_dev_coords-1].x;
*ypos = dev_coords[num_dev_coords-1].y;
} else {
*xpos = *ypos = 0.0;
}
}
void pdf_dev_push_coord(double xpos, double ypos)
{
if (num_dev_coords >= max_dev_coords) {
max_dev_coords += 4;
dev_coords = RENEW(dev_coords, max_dev_coords, pdf_coord);
}
dev_coords[num_dev_coords].x = xpos;
dev_coords[num_dev_coords].y = ypos;
num_dev_coords++;
}
void pdf_dev_pop_coord(void)
{
if (num_dev_coords > 0) num_dev_coords--;
}
/*
* ctype:
* -1 input string contains 2-byte Freetype glyph index values
* (XeTeX only)
* 0 byte-width of char can be variable and input string
* is properly encoded.
* n Single character cosumes n bytes in input string.
*
* _FIXME_
* -->
* selectfont(font_name, point_size) and show_string(pos, string)
*/
void
pdf_dev_set_string (spt_t xpos, spt_t ypos,
const void *instr_ptr, size_t instr_len,
spt_t width,
int font_id, int ctype)
{
struct dev_font *font;
struct dev_font *real_font;
const unsigned char *str_ptr; /* Pointer to the reencoded string. */
size_t length, i, len = 0;
spt_t kern, delh, delv;
spt_t text_xorigin;
spt_t text_yorigin;
if (font_id < 0 || font_id >= num_dev_fonts) {
_tt_abort("Invalid font: %d (%d)", font_id, num_dev_fonts);
}
if (font_id != text_state.font_id) {
dev_set_font(font_id);
}
font = CURRENTFONT();
if (!font) {
_tt_abort("Currentfont not set.");
}
if (font->real_font_index >= 0)
real_font = GET_FONT(font->real_font_index);
else
real_font = font;
text_xorigin = text_state.ref_x;
text_yorigin = text_state.ref_y;
str_ptr = instr_ptr;
length = instr_len;
if (font->format == PDF_FONTTYPE_COMPOSITE) {
if (handle_multibyte_string(font, &str_ptr, &length, ctype) < 0) {
_tt_abort("Error in converting input string...");
}
if (real_font->used_chars != NULL) {
for (i = 0; i < length; i += 2) {
unsigned short cid = (str_ptr[i] << 8) | str_ptr[i + 1];
add_to_used_chars2(real_font->used_chars, cid);
}
}
} else {
if (real_font->used_chars != NULL) {
for (i = 0; i < length; i++)
real_font->used_chars[str_ptr[i]] = 1;
}
}
if (num_dev_coords > 0) {
xpos -= bpt2spt(dev_coords[num_dev_coords-1].x);
ypos -= bpt2spt(dev_coords[num_dev_coords-1].y);
}
/*
* Kern is in units of character units, i.e., 1000 = 1 em.
*
* Positive kern means kerning (reduce excess white space).
*
* The following formula is of the form a*x/b where a, x, and b are signed long
* integers. Since in integer arithmetic (a*x) could overflow and a*(x/b) would
* not be accurate, we use floating point arithmetic rather than trying to do
* this all with integer arithmetic.
*
* 1000.0 / (font->extend * font->sptsize) is caluculated each times...
* Is accuracy really a matter? Character widths are always rounded to integer
* (in 1000 units per em) but dvipdfmx does not take into account of this...
*/
if (text_state.dir_mode==0) {
/* Left-to-right */
delh = text_xorigin + text_state.offset - xpos;
delv = ypos - text_yorigin;
} else if (text_state.dir_mode==1) {
/* Top-to-bottom */
delh = ypos - text_yorigin + text_state.offset;
delv = xpos - text_xorigin;
} else {
/* Bottom-to-top */
delh = ypos + text_yorigin + text_state.offset;
delv = xpos + text_xorigin;
}
/* White-space more than 3em is not considered as a part of single text.
* So we will break string mode in that case.
* Dvipdfmx spend most of time processing strings with kern = 0 (but far
* more times in font handling).
* You may want to use pre-calculated value for WORD_SPACE_MAX.
* More text compression may be possible by replacing kern with space char
* when -kern is equal to space char width.
*/
#define WORD_SPACE_MAX(f) (spt_t) (3.0 * (f)->extend * (f)->sptsize)
if (text_state.force_reset ||
labs(delv) > dev_unit.min_bp_val ||
labs(delh) > WORD_SPACE_MAX(font)) {
text_mode();
kern = 0;
} else {
kern = (spt_t) (1000.0 / font->extend * delh / font->sptsize);
}
/* Inaccucary introduced by rounding of character width appears within
* single text block. There are point_size/1000 rounding error per character.
* If you really care about accuracy, you should compensate this here too.
*/
if (motion_state != STRING_MODE)
string_mode(xpos, ypos,
font->slant, font->extend, text_state.matrix.rotate);
else if (kern != 0) {
/*
* Same issues as earlier. Use floating point for simplicity.
* This routine needs to be fast, so we don't call sprintf() or strcpy().
*/
text_state.offset -=
(spt_t) (kern * font->extend * (font->sptsize / 1000.0));
format_buffer[len++] = text_state.is_mb ? '>' : ')';
if (font->wmode)
len += p_itoa(-kern, format_buffer + len);
else {
len += p_itoa( kern, format_buffer + len);
}
format_buffer[len++] = text_state.is_mb ? '<' : '(';
pdf_doc_add_page_content(format_buffer, len); /* op: */
len = 0;
}
if (text_state.is_mb) {
if (FORMAT_BUF_SIZE - len < 2 * length)
_tt_abort("Buffer overflow...");
for (i = 0; i < length; i++) {
int first, second;
first = (str_ptr[i] >> 4) & 0x0f;
second = str_ptr[i] & 0x0f;
format_buffer[len++] = ((first >= 10) ? first + 'W' : first + '0');
format_buffer[len++] = ((second >= 10) ? second + 'W' : second + '0');
}
} else {
len += pdfobj_escape_str(format_buffer + len,
FORMAT_BUF_SIZE - len, str_ptr, length);
}
/* I think if you really care about speed, you should avoid memcopy here. */
pdf_doc_add_page_content(format_buffer, len); /* op: */
text_state.offset += width;
}
void
pdf_init_device (double dvi2pts, int precision, int black_and_white)
{
if (precision < 0 ||
precision > DEV_PRECISION_MAX)
dpx_warning("Number of decimal digits out of range [0-%d].",
DEV_PRECISION_MAX);
if (precision < 0) {
dev_unit.precision = 0;
} else if (precision > DEV_PRECISION_MAX) {
dev_unit.precision = DEV_PRECISION_MAX;
} else {
dev_unit.precision = precision;
}
dev_unit.dvi2pts = dvi2pts;
dev_unit.min_bp_val = (int) ROUND(1.0/(ten_pow[dev_unit.precision]*dvi2pts), 1);
if (dev_unit.min_bp_val < 0)
dev_unit.min_bp_val = -dev_unit.min_bp_val;
dev_param.colormode = (black_and_white ? 0 : 1);
graphics_mode();
pdf_color_clear_stack();
pdf_dev_init_gstates();
num_dev_fonts = max_dev_fonts = 0;
dev_fonts = NULL;
num_dev_coords = max_dev_coords = 0;
dev_coords = NULL;
}
void
pdf_close_device (void)
{
if (dev_fonts) {
int i;
for (i = 0; i < num_dev_fonts; i++) {
free(dev_fonts[i].tex_name);
pdf_release_obj(dev_fonts[i].resource);
dev_fonts[i].tex_name = NULL;
dev_fonts[i].resource = NULL;
dev_fonts[i].cff_charsets = NULL;
}
free(dev_fonts);
}
free(dev_coords);
pdf_dev_clear_gstates();
}
/*
* BOP, EOP, and FONT section.
* BOP and EOP manipulate some of the same data structures
* as the font stuff.
*/
void
pdf_dev_reset_fonts (int newpage)
{
int i;
for (i = 0; i < num_dev_fonts; i++) {
dev_fonts[i].used_on_this_page = 0;
}
text_state.font_id = -1;
text_state.matrix.slant = 0.0;
text_state.matrix.extend = 1.0;
text_state.matrix.rotate = TEXT_WMODE_HH;
if (newpage)
text_state.bold_param = 0.0;
text_state.is_mb = 0;
}
void
pdf_dev_reset_color (int force)
{
pdf_color *sc, *fc;
pdf_color_get_current(&sc, &fc);
pdf_dev_set_color(sc, 0, force);
pdf_dev_set_color(fc, 0x20, force);
}
void
pdf_dev_bop (const pdf_tmatrix *M)
{
graphics_mode();
text_state.force_reset = 0;
pdf_dev_gsave();
pdf_dev_concat(M);
pdf_dev_reset_fonts(1);
pdf_dev_reset_color(0);
}
void
pdf_dev_eop (void)
{
int depth;
graphics_mode();
depth = pdf_dev_current_depth();
if (depth != 1) {
dpx_warning("Unbalenced q/Q nesting...: %d", depth);
pdf_dev_grestore_to(0);
} else {
pdf_dev_grestore();
}
}
static void
print_fontmap (const char *font_name, fontmap_rec *mrec)
{
if (!mrec)
return;
dpx_message("\n");
dpx_message("fontmap: %s -> %s", font_name, mrec->font_name);
if (mrec->enc_name)
dpx_message("(%s)", mrec->enc_name);
if (mrec->opt.extend != 1.0)
dpx_message("[extend:%g]", mrec->opt.extend);
if (mrec->opt.slant != 0.0)
dpx_message("[slant:%g]", mrec->opt.slant);
if (mrec->opt.bold != 0.0)
dpx_message("[bold:%g]", mrec->opt.bold);
if (mrec->opt.flags & FONTMAP_OPT_NOEMBED)
dpx_message("[noemb]");
if (mrec->opt.mapc >= 0)
dpx_message("[map:<%02x>]", mrec->opt.mapc);
if (mrec->opt.charcoll)
dpx_message("[csi:%s]", mrec->opt.charcoll);
if (mrec->opt.index)
dpx_message("[index:%d]", mrec->opt.index);
switch (mrec->opt.style) {
case FONTMAP_STYLE_BOLD:
dpx_message("[style:bold]");
break;
case FONTMAP_STYLE_ITALIC:
dpx_message("[style:italic]");
break;
case FONTMAP_STYLE_BOLDITALIC:
dpx_message("[style:bolditalic]");
break;
}
dpx_message("\n");
}
/* _FIXME_
* Font is identified with font_name and point_size as in DVI here.
* However, except for PDF_FONTTYPE_BITMAP, we can share the
* short_name, resource and used_chars between multiple instances
* of the same font at different sizes.
*/
int
pdf_dev_locate_font (const char *font_name, spt_t ptsize)
{
int i;
fontmap_rec *mrec;
struct dev_font *font;
if (!font_name)
return -1;
if (ptsize == 0) {
_tt_abort("pdf_dev_locate_font() called with the zero ptsize.");
}
for (i = 0; i < num_dev_fonts; i++) {
if (streq_ptr(font_name, dev_fonts[i].tex_name)) {
if (ptsize == dev_fonts[i].sptsize)
return i; /* found a dev_font that matches the request */
if (dev_fonts[i].format != PDF_FONTTYPE_BITMAP)
break; /* new dev_font will share pdf resource with /i/ */
}
}
/*
* Make sure we have room for a new one, even though we may not
* actually create one.
*/
if (num_dev_fonts >= max_dev_fonts) {
max_dev_fonts += 16;
dev_fonts = RENEW(dev_fonts, max_dev_fonts, struct dev_font);
}
font = &dev_fonts[num_dev_fonts];
/* New font */
mrec = pdf_lookup_fontmap_record(font_name);
if (verbose > 1)
print_fontmap(font_name, mrec);
font->font_id = pdf_font_findresource(font_name, ptsize * dev_unit.dvi2pts, mrec);
if (font->font_id < 0)
return -1;
if (mrec)
font->cff_charsets = mrec->opt.cff_charsets;
/* We found device font here. */
if (i < num_dev_fonts) {
font->real_font_index = i;
strcpy(font->short_name, dev_fonts[i].short_name);
}
else {
font->real_font_index = -1;
font->short_name[0] = 'F';
p_itoa(num_phys_fonts + 1, &font->short_name[1]); /* NULL terminated here */
num_phys_fonts++;
}
font->used_on_this_page = 0;
font->tex_name = NEW(strlen(font_name) + 1, char);
strcpy(font->tex_name, font_name);
font->sptsize = ptsize;
switch (pdf_get_font_subtype(font->font_id)) {
case PDF_FONT_FONTTYPE_TYPE3:
font->format = PDF_FONTTYPE_BITMAP;
break;
case PDF_FONT_FONTTYPE_TYPE0:
font->format = PDF_FONTTYPE_COMPOSITE;
break;
default:
font->format = PDF_FONTTYPE_SIMPLE;
break;
}
font->wmode = pdf_get_font_wmode (font->font_id);
font->enc_id = pdf_get_font_encoding(font->font_id);
font->resource = NULL; /* Don't ref obj until font is actually used. */
font->used_chars = NULL;
font->extend = 1.0;
font->slant = 0.0;
font->bold = 0.0;
font->mapc = -1;
font->is_unicode = 0;
font->ucs_group = 0;
font->ucs_plane = 0;
if (mrec) {
font->extend = mrec->opt.extend;
font->slant = mrec->opt.slant;
font->bold = mrec->opt.bold;
if (mrec->opt.mapc >= 0)
font->mapc = (mrec->opt.mapc >> 8) & 0xff;
else {
font->mapc = -1;
}
if (streq_ptr(mrec->enc_name, "unicode")) {
font->is_unicode = 1;
if (mrec->opt.mapc >= 0) {
font->ucs_group = (mrec->opt.mapc >> 24) & 0xff;
font->ucs_plane = (mrec->opt.mapc >> 16) & 0xff;
} else {
font->ucs_group = 0;
font->ucs_plane = 0;
}
} else {
font->is_unicode = 0;
}
}
return num_dev_fonts++;
}
/* This does not remember current stroking width. */
static int
dev_sprint_line (char *buf, spt_t width,
spt_t p0_x, spt_t p0_y, spt_t p1_x, spt_t p1_y)
{
int len = 0;
double w;
w = width * dev_unit.dvi2pts;
len += p_dtoa(w, MIN(dev_unit.precision+1, DEV_PRECISION_MAX), buf+len);
buf[len++] = ' ';
buf[len++] = 'w';
buf[len++] = ' ';
len += dev_sprint_bp(buf+len, p0_x, NULL);
buf[len++] = ' ';
len += dev_sprint_bp(buf+len, p0_y, NULL);
buf[len++] = ' ';
buf[len++] = 'm';
buf[len++] = ' ';
len += dev_sprint_bp(buf+len, p1_x, NULL);
buf[len++] = ' ';
len += dev_sprint_bp(buf+len, p1_y, NULL);
buf[len++] = ' ';
buf[len++] = 'l';
buf[len++] = ' ';
buf[len++] = 'S';
return len;
}
/* Not optimized. */
#define PDF_LINE_THICKNESS_MAX 5.0
void
pdf_dev_set_rule (spt_t xpos, spt_t ypos, spt_t width, spt_t height)
{
int len = 0;
double width_in_bp;
if (num_dev_coords > 0) {
xpos -= bpt2spt(dev_coords[num_dev_coords-1].x);
ypos -= bpt2spt(dev_coords[num_dev_coords-1].y);
}
graphics_mode();
format_buffer[len++] = ' ';
format_buffer[len++] = 'q';
format_buffer[len++] = ' ';
/* Don't use too thick line. */
width_in_bp = ((width < height) ? width : height) * dev_unit.dvi2pts;
if (width_in_bp < 0.0 || /* Shouldn't happen */
width_in_bp > PDF_LINE_THICKNESS_MAX) {
pdf_rect rect;
rect.llx = dev_unit.dvi2pts * xpos;
rect.lly = dev_unit.dvi2pts * ypos;
rect.urx = dev_unit.dvi2pts * width;
rect.ury = dev_unit.dvi2pts * height;
len += pdf_sprint_rect(format_buffer+len, &rect);
format_buffer[len++] = ' ';
format_buffer[len++] = 'r';
format_buffer[len++] = 'e';
format_buffer[len++] = ' ';
format_buffer[len++] = 'f';
} else {
if (width > height) {
/* NOTE:
* A line width of 0 denotes the thinnest line that can be rendered at
* device resolution. See, PDF Reference Manual 4th ed., sec. 4.3.2,
* "Details of Graphics State Parameters", p. 185.
*/
if (height < dev_unit.min_bp_val) {
dpx_warning("Too thin line: height=%d (%g bp)", height, width_in_bp);
dpx_warning("Please consider using \"-d\" option.");
}
len += dev_sprint_line(format_buffer+len,
height,
xpos,
ypos + height/2,
xpos + width,
ypos + height/2);
} else {
if (width < dev_unit.min_bp_val) {
dpx_warning("Too thin line: width=%d (%g bp)", width, width_in_bp);
dpx_warning("Please consider using \"-d\" option.");
}
len += dev_sprint_line(format_buffer+len,
width,
xpos + width/2,
ypos,
xpos + width/2,
ypos + height);
}
}
format_buffer[len++] = ' ';
format_buffer[len++] = 'Q';
pdf_doc_add_page_content(format_buffer, len); /* op: q re f Q */
}
/* Rectangle in device space coordinate. */
void
pdf_dev_set_rect (pdf_rect *rect,
spt_t x_user, spt_t y_user,
spt_t width, spt_t height, spt_t depth)
{
double dev_x, dev_y;
pdf_coord p0, p1, p2, p3;
double min_x, min_y, max_x, max_y;
dev_x = x_user * dev_unit.dvi2pts;
dev_y = y_user * dev_unit.dvi2pts;
if (text_state.dir_mode) {
p0.x = dev_x - dev_unit.dvi2pts * depth;
p0.y = dev_y - dev_unit.dvi2pts * width;
p1.x = dev_x + dev_unit.dvi2pts * height;
p1.y = p0.y;
p2.x = p1.x;
p2.y = dev_y;
p3.x = p0.x;
p3.y = p2.y;
} else {
p0.x = dev_x;
p0.y = dev_y - dev_unit.dvi2pts * depth;
p1.x = dev_x + dev_unit.dvi2pts * width;
p1.y = p0.y;
p2.x = p1.x;
p2.y = dev_y + dev_unit.dvi2pts * height;
p3.x = p0.x;
p3.y = p2.y;
}
pdf_dev_transform(&p0, NULL); /* currentmatrix */
pdf_dev_transform(&p1, NULL);
pdf_dev_transform(&p2, NULL);
pdf_dev_transform(&p3, NULL);
min_x = MIN(p0.x , p1.x);
min_x = MIN(min_x, p2.x);
min_x = MIN(min_x, p3.x);
max_x = MAX(p0.x , p1.x);
max_x = MAX(max_x, p2.x);
max_x = MAX(max_x, p3.x);
min_y = MIN(p0.y , p1.y);
min_y = MIN(min_y, p2.y);
min_y = MIN(min_y, p3.y);
max_y = MAX(p0.y , p1.y);
max_y = MAX(max_y, p2.y);
max_y = MAX(max_y, p3.y);
rect->llx = min_x;
rect->lly = min_y;
rect->urx = max_x;
rect->ury = max_y;
return;
}
int
pdf_dev_get_dirmode (void)
{
return text_state.dir_mode;
}
void
pdf_dev_set_dirmode (int text_dir)
{
struct dev_font *font;
int text_rotate;
int vert_dir, vert_font;
font = CURRENTFONT();
vert_font = (font && font->wmode) ? 1 : 0;
if (dev_param.autorotate) {
vert_dir = text_dir;
} else {
vert_dir = vert_font;
}
text_rotate = (vert_font << 2)|vert_dir;
if (font &&
ANGLE_CHANGES(text_rotate, text_state.matrix.rotate)) {
text_state.force_reset = 1;
}
text_state.matrix.rotate = text_rotate;
text_state.dir_mode = text_dir;
}
static void
dev_set_param_autorotate (int auto_rotate)
{
struct dev_font *font;
int text_rotate, vert_font, vert_dir;
font = CURRENTFONT();
vert_font = (font && font->wmode) ? 1 : 0;
if (auto_rotate) {
vert_dir = text_state.dir_mode;
} else {
vert_dir = vert_font;
}
text_rotate = (vert_font << 2)|vert_dir;
if (ANGLE_CHANGES(text_rotate, text_state.matrix.rotate)) {
text_state.force_reset = 1;
}
text_state.matrix.rotate = text_rotate;
dev_param.autorotate = auto_rotate;
}
int
pdf_dev_get_param (int param_type)
{
int value = 0;
switch (param_type) {
case PDF_DEV_PARAM_AUTOROTATE:
value = dev_param.autorotate;
break;
case PDF_DEV_PARAM_COLORMODE:
value = dev_param.colormode;
break;
default:
_tt_abort("Unknown device parameter: %d", param_type);
}
return value;
}
void
pdf_dev_set_param (int param_type, int value)
{
switch (param_type) {
case PDF_DEV_PARAM_AUTOROTATE:
dev_set_param_autorotate(value);
break;
case PDF_DEV_PARAM_COLORMODE:
dev_param.colormode = value; /* 0 for B&W */
break;
default:
_tt_abort("Unknown device parameter: %d", param_type);
}
return;
}
int
pdf_dev_put_image (int id,
transform_info *p,
double ref_x,
double ref_y)
{
char *res_name;
pdf_tmatrix M, M1;
pdf_rect r;
int len = 0;
if (num_dev_coords > 0) {
ref_x -= dev_coords[num_dev_coords-1].x;
ref_y -= dev_coords[num_dev_coords-1].y;
}
pdf_copymatrix(&M, &(p->matrix));
M.e += ref_x; M.f += ref_y;
/* Just rotate by -90, but not tested yet. Any problem if M has scaling? */
if (dev_param.autorotate &&
text_state.dir_mode) {
double tmp;
tmp = -M.a; M.a = M.b; M.b = tmp;
tmp = -M.c; M.c = M.d; M.d = tmp;
}
graphics_mode();
pdf_dev_gsave();
pdf_ximage_scale_image(id, &M1, &r, p);
pdf_concatmatrix(&M, &M1);
pdf_dev_concat(&M);
/* Clip */
if (p->flags & INFO_DO_CLIP) {
pdf_dev_rectclip(r.llx, r.lly, r.urx - r.llx, r.ury - r.lly);
}
res_name = pdf_ximage_get_resname(id);
len = sprintf(work_buffer, " /%s Do", res_name);
pdf_doc_add_page_content(work_buffer, len); /* op: Do */
pdf_dev_grestore();
pdf_doc_add_page_resource("XObject",
res_name,
pdf_ximage_get_reference(id));
if (dvi_is_tracking_boxes()) {
pdf_tmatrix P;
unsigned int i;
pdf_rect rect;
pdf_coord corner[4];
pdf_dev_set_rect(&rect, 65536 * ref_x, 65536 * ref_y,
65536 * (r.urx - r.llx), 65536 * (r.ury - r.lly), 0);
corner[0].x = rect.llx; corner[0].y = rect.lly;
corner[1].x = rect.llx; corner[1].y = rect.ury;
corner[2].x = rect.urx; corner[2].y = rect.ury;
corner[3].x = rect.urx; corner[3].y = rect.lly;
pdf_copymatrix(&P, &(p->matrix));
for (i = 0; i < 4; ++i) {
corner[i].x -= rect.llx;
corner[i].y -= rect.lly;
pdf_dev_transform(&(corner[i]), &P);
corner[i].x += rect.llx;
corner[i].y += rect.lly;
}
rect.llx = corner[0].x;
rect.lly = corner[0].y;
rect.urx = corner[0].x;
rect.ury = corner[0].y;
for (i = 0; i < 4; ++i) {
if (corner[i].x < rect.llx)
rect.llx = corner[i].x;
if (corner[i].x > rect.urx)
rect.urx = corner[i].x;
if (corner[i].y < rect.lly)
rect.lly = corner[i].y;
if (corner[i].y > rect.ury)
rect.ury = corner[i].y;
}
pdf_doc_expand_box(&rect);
}
return 0;
}
void
transform_info_clear (transform_info *info)
{
/* Physical dimensions */
info->width = 0.0;
info->height = 0.0;
info->depth = 0.0;
info->bbox.llx = 0.0;
info->bbox.lly = 0.0;
info->bbox.urx = 0.0;
info->bbox.ury = 0.0;
/* Transformation matrix */
pdf_setmatrix(&(info->matrix), 1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
info->flags = 0;
}
void
pdf_dev_begin_actualtext (uint16_t *unicodes, int count)
{
int len, i, pdf_doc_enc = 1;
/* check whether we can use PDFDocEncoding for this string
(we punt on the 0x80..0xA0 range that does not directly correspond to unicode) */
for (i = 0; i < count; i++) {
if (unicodes[i] > 0xff || (unicodes[i] > 0x7f && unicodes[i] < 0xa1)) {
pdf_doc_enc = 0;
break;
}
}
graphics_mode();
len = sprintf(work_buffer, "\n/Span<</ActualText(");
if (!pdf_doc_enc) {
len += sprintf(work_buffer + len, "\xFE\xFF");
}
pdf_doc_add_page_content(work_buffer, len);
while (count-- > 0) {
unsigned char s[2] = { *unicodes >> 8, *unicodes & 0xff };
i = pdf_doc_enc; /* if using PDFDocEncoding, we only care about the low 8 bits,
so start with the second byte of our pair */
len = 0;
for (; i < 2; i++) {
unsigned char c = s[i];
if (c == '(' || c == ')' || c == '\\') {
len += sprintf(work_buffer + len, "\\%c", c);
} else if (c < ' ') {
len += sprintf(work_buffer + len, "\\%03o", c);
} else {
len += sprintf(work_buffer + len, "%c", c);
}
}
pdf_doc_add_page_content(work_buffer, len);
++unicodes;
}
len = sprintf(work_buffer, ")>>BDC");
pdf_doc_add_page_content(work_buffer, len);
}
void
pdf_dev_end_actualtext (void)
{
graphics_mode();
pdf_doc_add_page_content(" EMC", 4);
}
void
pdf_dev_reset_global_state(void)
{
dev_fonts = NULL;
num_dev_fonts = 0;
max_dev_fonts = 0;
num_phys_fonts = 0;
}
|
fmgoncalves/tectonic
|
tectonic/core-strutils.h
|
/* tectonic/core-strutils.h: miscellaneous C string utilities
Copyright 2016-2018 the Tectonic Project
Licensed under the MIT License.
*/
#ifndef TECTONIC_CORE_STRUTILS_H
#define TECTONIC_CORE_STRUTILS_H
#include "core-foundation.h"
#ifndef isblank
#define isblank(c) ((c) == ' ' || (c) == '\t')
#endif
#define ISBLANK(c) (isascii (c) && isblank ((unsigned char)c))
/* Note that we explicitly do *not* change this on Windows. For maximum
* portability, we should probably accept *either* forward or backward slashes
* as directory separators. */
#define IS_DIR_SEP(ch) ((ch) == '/')
static inline bool streq_ptr(const char *s1, const char *s2) {
if (s1 && s2)
return strcmp(s1, s2) == 0;
return false;
}
static inline const char *strstartswith(const char *s, const char *prefix) {
size_t length;
length = strlen(prefix);
if (strncmp(s, prefix, length) == 0)
return s + length;
return NULL;
}
BEGIN_EXTERN_C
/* Nothing here yet. */
END_EXTERN_C
#endif /* not TECTONIC_CORE_STRUTILS_H */
|
fmgoncalves/tectonic
|
tectonic/dpx-dpxconf.h
|
/* This is DVIPDFMx, an eXtended version of DVIPDFM by <NAME>.
Copyright (C) 2002-2016 by <NAME> and <NAME>,
the dvipdfmx project team.
Copyright (C) 1998, 1999 by <NAME> <<EMAIL>>
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.
*/
#ifndef _DPXCONF_H_
#define _DPXCONF_H_
#include "dpx-core.h"
#include <stddef.h>
#ifdef HAVE_LIBPAPER
#include <paper.h>
#else
struct paper {
const char* name;
double pswidth, psheight;
};
#ifndef DEFAULT_PAPER_NAME
#define DEFAULT_PAPER_NAME "a4"
#endif
extern const struct paper paperspecs[];
const struct paper *paperinfo (const char *ppformat);
#define paperpswidth(p) (((p) && (p)->name) ? p->pswidth : 0.0)
#define paperpsheight(p) (((p) && (p)->name) ? p->psheight : 0.0)
#define papername(p) (((p) && (p)->name) ? p->name : NULL)
#define paperfirst() &(paperspecs[0])
#define papernext(p) ((((p)+1) && ((p)+1)->name) ? (p+1) : NULL)
#define defaultpapername() DEFAULT_PAPER_NAME
#define systempapername() DEFAULT_PAPER_NAME
#define defaultpapersizefile() NULL
#define systempapersizefile() NULL
#endif /* HAVE_LIBPAPER */
void dumppaperinfo (void);
#endif /* _DPXCONF_H_ */
|
fmgoncalves/tectonic
|
tectonic/dpx-pdfdoc.h
|
<reponame>fmgoncalves/tectonic<filename>tectonic/dpx-pdfdoc.h
/* This is dvipdfmx, an eXtended version of dvipdfm by <NAME>.
Copyright (C) 2007-2017 by <NAME> and <NAME>,
the dvipdfmx project team.
Copyright (C) 1998, 1999 by <NAME> <<EMAIL>>
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.
*/
#ifndef _PDFDOC_H_
#define _PDFDOC_H_
#include "dpx-core.h"
#include <stdbool.h>
#include "dpx-pdfobj.h"
#include "dpx-pdfdev.h"
#define PDF_DOC_GRABBING_NEST_MAX 4
void pdf_doc_set_verbose (int level);
void pdf_open_document (const char *filename,
bool enable_encrypt,
bool enable_object_stream,
double media_width, double media_height,
double annot_grow_amount,
int bookmark_open_depth,
int check_gotos);
void pdf_close_document (void);
/* PDF document metadata */
void pdf_doc_set_creator (const char *creator);
/* They just return PDF dictionary object.
* Callers are completely responsible for doing right thing...
*/
pdf_obj *pdf_doc_get_dictionary (const char *category);
pdf_obj *pdf_doc_get_reference (const char *category);
#define pdf_doc_page_tree() pdf_doc_get_dictionary("Pages")
#define pdf_doc_catalog() pdf_doc_get_dictionary("Catalog")
#define pdf_doc_docinfo() pdf_doc_get_dictionary("Info")
#define pdf_doc_names() pdf_doc_get_dictionary("Names")
#define pdf_doc_this_page() pdf_doc_get_dictionary("@THISPAGE")
int pdf_doc_get_page_count (pdf_file *pf);
pdf_obj *pdf_doc_get_page (pdf_file *pf, int page_no, int options,
pdf_rect *bbox, pdf_tmatrix *matrix, pdf_obj **resources_p);
int pdf_doc_current_page_number (void);
pdf_obj *pdf_doc_current_page_resources (void);
pdf_obj *pdf_doc_ref_page (unsigned page_no);
#define pdf_doc_this_page_ref() pdf_doc_get_reference("@THISPAGE")
#define pdf_doc_next_page_ref() pdf_doc_get_reference("@NEXTPAGE")
#define pdf_doc_prev_page_ref() pdf_doc_get_reference("@PREVPAGE")
/* Not really managing tree...
* There should be something for number tree.
*/
int pdf_doc_add_names (const char *category,
const void *key, int keylen, pdf_obj *value);
void pdf_doc_set_bop_content (const char *str, unsigned int length);
void pdf_doc_set_eop_content (const char *str, unsigned int length);
/* Page */
void pdf_doc_begin_page (double scale, double x_origin, double y_origin);
void pdf_doc_end_page (void);
void pdf_doc_set_mediabox (unsigned page_no, const pdf_rect *mediabox);
void pdf_doc_add_page_content (const char *buffer, unsigned int length);
void pdf_doc_add_page_resource (const char *category,
const char *resource_name, pdf_obj *resources);
/* Article thread */
void pdf_doc_begin_article (const char *article_id, pdf_obj *info);
void pdf_doc_add_bead (const char *article_id,
const char *bead_id,
int page_no, const pdf_rect *rect);
/* Bookmarks */
int pdf_doc_bookmarks_up (void);
int pdf_doc_bookmarks_down (void);
void pdf_doc_bookmarks_add (pdf_obj *dict, int is_open);
int pdf_doc_bookmarks_depth (void);
/* Returns xobj_id of started xform. */
int pdf_doc_begin_grabbing (const char *ident,
double ref_x, double ref_y,
const pdf_rect *cropbox);
void pdf_doc_end_grabbing (pdf_obj *attrib);
/* Annotation */
void pdf_doc_add_annot (unsigned page_no,
const pdf_rect *rect,
pdf_obj *annot_dict,
int new_annot);
/* Annotation with auto- clip and line (or page) break */
void pdf_doc_begin_annot (pdf_obj *dict);
void pdf_doc_end_annot (void);
void pdf_doc_break_annot (void);
void pdf_doc_expand_box (const pdf_rect *rect);
/* Manual thumbnail */
void pdf_doc_enable_manual_thumbnails (void);
/* Similar to bop_content */
#include "dpx-pdfcolor.h"
void pdf_doc_set_bgcolor (const pdf_color *color);
#endif /* _PDFDOC_H_ */
|
fmgoncalves/tectonic
|
tectonic/dpx-pst.c
|
/* This is dvipdfmx, an eXtended version of dvipdfm by <NAME>.
Copyright (C) 2002-2016 by <NAME> and <NAME>,
the dvipdfmx project team.
Copyright (C) 1998, 1999 by <NAME> <<EMAIL>>
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 "dpx-pst.h"
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include "core-bridge.h"
#include "dpx-dpxutil.h"
#include "dpx-mem.h"
#include "dpx-pst_obj.h"
#define TYPE_CHECK(o, t) do { \
if ((o) == NULL || pst_type_of((o)) != (t)) \
_tt_abort("typecheck: object %p not of type %d.", (o), (t)); \
} while (0)
static pst_obj *
pst_parse_any (unsigned char **inbuf, unsigned char *inbufend)
{
unsigned char *data;
unsigned char *cur = *inbuf;
unsigned int len;
while (cur < inbufend && !PST_TOKEN_END(cur, inbufend))
cur++;
len = cur - (*inbuf);
data = NEW(len+1, unsigned char);
memcpy(data, *inbuf, len);
data[len] = '\0';
*inbuf = cur;
return pst_new_obj(PST_TYPE_UNKNOWN, data);
}
static void
skip_line (unsigned char **inbuf, unsigned char *inbufend)
{
while (*inbuf < inbufend && **inbuf != '\n' && **inbuf != '\r')
(*inbuf)++;
if (*inbuf < inbufend && **inbuf == '\r')
(*inbuf)++;
if (*inbuf < inbufend && **inbuf == '\n')
(*inbuf)++;
}
static void
skip_comments (unsigned char **inbuf, unsigned char *inbufend)
{
while (*inbuf < inbufend && **inbuf == '%') {
skip_line(inbuf, inbufend);
skip_white_spaces(inbuf, inbufend);
}
}
/* NOTE: the input buffer must be null-terminated, i.e., *inbufend == 0 */
pst_obj *
pst_get_token (unsigned char **inbuf, unsigned char *inbufend)
{
pst_obj *obj = NULL;
unsigned char c;
assert(*inbuf <= inbufend && !*inbufend);
skip_white_spaces(inbuf, inbufend);
skip_comments(inbuf, inbufend);
if (*inbuf >= inbufend)
return NULL;
c = **inbuf;
switch (c) {
case '/':
obj = pst_parse_name(inbuf, inbufend);
break;
case '[': case '{': /* This is wrong */
obj = pst_new_mark();
(*inbuf)++;
break;
case '<':
if (*inbuf + 1 >= inbufend)
return NULL;
c = *(*inbuf+1);
if (c == '<') {
obj = pst_new_mark();
*inbuf += 2;
} else if (isxdigit(c))
obj = pst_parse_string(inbuf, inbufend);
else if (c == '~') /* ASCII85 */
obj = pst_parse_string(inbuf, inbufend);
break;
case '(':
obj = pst_parse_string(inbuf, inbufend);
break;
case '>':
if (*inbuf + 1 >= inbufend || *(*inbuf+1) != '>') {
_tt_abort("Unexpected end of ASCII hex string marker.");
} else {
char *mark;
mark = NEW(3, char);
mark[0] = '>'; mark[1] = '>'; mark[2] = '\0';
obj = pst_new_obj(PST_TYPE_UNKNOWN, mark);
(*inbuf) += 2;
}
break;
case ']': case '}':
{
char *mark;
mark = NEW(2, char);
mark[0] = c; mark[1] = '\0';
obj = pst_new_obj(PST_TYPE_UNKNOWN, mark);
(*inbuf)++;
}
break;
default:
if (c == 't' || c == 'f')
obj = pst_parse_boolean(inbuf, inbufend);
else if (c == 'n')
obj = pst_parse_null(inbuf, inbufend);
else if (c == '+' || c == '-' || isdigit(c) || c == '.')
obj = pst_parse_number(inbuf, inbufend);
break;
}
if (!obj) {
obj = pst_parse_any(inbuf, inbufend);
}
return obj;
}
|
fmgoncalves/tectonic
|
tectonic/dpx-cs_type2.c
|
<filename>tectonic/dpx-cs_type2.c<gh_stars>1-10
/* This is dvipdfmx, an eXtended version of dvipdfm by <NAME>.
Copyright (C) 2002-2016 by <NAME> and <NAME>,
the dvipdfmx project team.
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.
*/
/*
* Type 2 Charstring support:
* Decode and encode Type 2 charstring
*
* All local/global subroutine calls in a given charstring is replace by the
* content of subroutine charstrings. We do this because some PostScript RIP
* may have problems with sparse subroutine array. Workaround for this is to
* re-order subroutine array so that no gap appears in the subroutine array,
* or put dummy charstrings that contains only `return' in the gap. However,
* re-ordering of subroutine is rather difficult for Type 2 charstrings due
* to the bias which depends on the total number of subroutines. Replacing
* callgsubr/callsubr calls with the content of the corresponding subroutine
* charstring may be more efficient than putting dummy subroutines in the
* case of subsetted font. Adobe distiller seems doing same thing.
*
* And also note that subroutine numbers within subroutines can depend on the
* content of operand stack as follows:
*
* ... l m callsubr << subr #(m+bias): n add callsubr >> ...
*
* I've not implemented the `random' operator which generates a pseudo-random
* number in the range (0, 1] and push them into argument stack.
* How pseudo-random sequences are generated is not documented in the Type 2
* charstring spec..
*/
#include "dpx-cs_type2.h"
/* fabs, sqrt ... */
#include <math.h>
#include <stdio.h>
#include <string.h>
#include "core-bridge.h"
#include "dpx-cff_limits.h"
/* data types, limits */
#include "dpx-cff_types.h"
#include "dpx-error.h"
#define CS_TYPE2_DEBUG_STR "Type2 Charstring Parser"
#define CS_TYPE2_DEBUG 5
/* decoder/encoder status codes */
#define CS_BUFFER_ERROR -3
#define CS_STACK_ERROR -2
#define CS_PARSE_ERROR -1
#define CS_PARSE_OK 0
#define CS_PARSE_END 1
#define CS_SUBR_RETURN 2
#define CS_CHAR_END 3
static int status = CS_PARSE_ERROR;
#define DST_NEED(a,b) {if ((a) < (b)) { status = CS_BUFFER_ERROR ; return ; }}
#define SRC_NEED(a,b) {if ((a) < (b)) { status = CS_PARSE_ERROR ; return ; }}
#define NEED(a,b) {if ((a) < (b)) { status = CS_STACK_ERROR ; return ; }}
/* hintmask and cntrmask need number of stem zones */
static int num_stems = 0;
static int phase = 0;
/* subroutine nesting */
static int nest = 0;
/* advance width */
static int have_width = 0;
static double width = 0.0;
/* Operand stack and Transient array */
static int stack_top = 0;
static double arg_stack[CS_ARG_STACK_MAX];
static double trn_array[CS_TRANS_ARRAY_MAX];
/*
* Type 2 CharString encoding
*/
/*
* 1-byte CharString operaotrs:
* cs_escape is first byte of two-byte operator
*/
/* RESERVED 0 */
#define cs_hstem 1
/* RESERVED 2 */
#define cs_vstem 3
#define cs_vmoveto 4
#define cs_rlineto 5
#define cs_hlineto 6
#define cs_vlineto 7
#define cs_rrcurveto 8
/* cs_closepath 9 : TYPE1 */
#define cs_callsubr 10
#define cs_return 11
#define cs_escape 12
/* cs_hsbw 13 : TYPE1 */
#define cs_endchar 14
/* RESERVED 15 */
/* RESERVED 16 */
/* RESERVED 17 */
#define cs_hstemhm 18
#define cs_hintmask 19
#define cs_cntrmask 20
#define cs_rmoveto 21
#define cs_hmoveto 22
#define cs_vstemhm 23
#define cs_rcurveline 24
#define cs_rlinecurve 25
#define cs_vvcurveto 26
#define cs_hhcurveto 27
/* SHORTINT 28 : first byte of shortint*/
#define cs_callgsubr 29
#define cs_vhcurveto 30
#define cs_hvcurveto 31
/*
* 2-byte CharString operaotrs:
* "dotsection" is obsoleted in Type 2 charstring.
*/
#define cs_dotsection 0
/* cs_vstem3 1 : TYPE1 */
/* cs_hstem3 2 : TYPE1 */
#define cs_and 3
#define cs_or 4
#define cs_not 5
/* cs_seac 6 : TYPE1 */
/* cs_sbw 7 : TYPE1 */
/* RESERVED 8 */
#define cs_abs 9
#define cs_add 10
#define cs_sub 11
#define cs_div 12
/* RESERVED 13 */
#define cs_neg 14
#define cs_eq 15
/* cs_callothersubr 16 : TYPE1 */
/* cs_pop 17 : TYPE1 */
#define cs_drop 18
/* RESERVED 19 */
#define cs_put 20
#define cs_get 21
#define cs_ifelse 22
#define cs_random 23
#define cs_mul 24
/* RESERVED 25 */
#define cs_sqrt 26
#define cs_dup 27
#define cs_exch 28
#define cs_index 29
#define cs_roll 30
/* cs_setcurrentpoint 31 : TYPE1 */
/* RESERVED 32 */
/* RESERVED 33 */
#define cs_hflex 34
#define cs_flex 35
#define cs_hflex1 36
#define cs_flex1 37
/*
* clear_stack() put all operands sotred in operand stack to dest.
*/
static void
clear_stack (card8 **dest, card8 *limit)
{
int i;
for (i = 0; i < stack_top; i++) {
double value;
int ivalue;
value = arg_stack[i];
/* Nearest integer value */
ivalue = (int) floor(value+0.5);
if (value >= 0x8000L || value <= (-0x8000L - 1)) {
/*
* This number cannot be represented as a single operand.
* We must use `a b mul ...' or `a c div' to represent large values.
*/
_tt_abort("%s: Argument value too large. (This is bug)", CS_TYPE2_DEBUG_STR);
} else if (fabs(value - ivalue) > 3.0e-5) {
/* 16.16-bit signed fixed value */
DST_NEED(limit, *dest + 5);
*(*dest)++ = 255;
ivalue = (int) floor(value); /* mantissa */
*(*dest)++ = (ivalue >> 8) & 0xff;
*(*dest)++ = ivalue & 0xff;
ivalue = (int)((value - ivalue) * 0x10000l); /* fraction */
*(*dest)++ = (ivalue >> 8) & 0xff;
*(*dest)++ = ivalue & 0xff;
/* Everything else are integers. */
} else if (ivalue >= -107 && ivalue <= 107) {
DST_NEED(limit, *dest + 1);
*(*dest)++ = ivalue + 139;
} else if (ivalue >= 108 && ivalue <= 1131) {
DST_NEED(limit, *dest + 2);
ivalue = 0xf700u + ivalue - 108;
*(*dest)++ = (ivalue >> 8) & 0xff;
*(*dest)++ = ivalue & 0xff;
} else if (ivalue >= -1131 && ivalue <= -108) {
DST_NEED(limit, *dest + 2);
ivalue = 0xfb00u - ivalue - 108;
*(*dest)++ = (ivalue >> 8) & 0xff;
*(*dest)++ = ivalue & 0xff;
} else if (ivalue >= -32768 && ivalue <= 32767) { /* shortint */
DST_NEED(limit, *dest + 3);
*(*dest)++ = 28;
*(*dest)++ = (ivalue >> 8) & 0xff;
*(*dest)++ = (ivalue) & 0xff;
} else { /* Shouldn't come here */
_tt_abort("%s: Unexpected error.", CS_TYPE2_DEBUG_STR);
}
}
stack_top = 0; /* clear stack */
return;
}
/*
* Single byte operators:
* Path construction, Operator for finishing a path, Hint operators.
*
* phase:
* 0: inital state
* 1: hint declaration, first stack-clearing operator appeared
* 2: in path construction
*/
static void
do_operator1 (card8 **dest, card8 *limit, card8 **data, card8 *endptr)
{
card8 op = **data;
*data += 1;
switch (op) {
case cs_hstemhm:
case cs_vstemhm:
/* charstring may have hintmask if above operator have seen */
case cs_hstem:
case cs_vstem:
if (phase == 0 && (stack_top % 2)) {
have_width = 1;
width = arg_stack[0];
}
num_stems += stack_top/2;
clear_stack(dest, limit);
DST_NEED(limit, *dest + 1);
*(*dest)++ = op;
phase = 1;
break;
case cs_hintmask:
case cs_cntrmask:
if (phase < 2) {
if (phase == 0 && (stack_top % 2)) {
have_width = 1;
width = arg_stack[0];
}
num_stems += stack_top/2;
}
clear_stack(dest, limit);
DST_NEED(limit, *dest + 1);
*(*dest)++ = op;
if (num_stems > 0) {
int masklen = (num_stems + 7) / 8;
DST_NEED(limit, *dest + masklen);
SRC_NEED(endptr, *data + masklen);
memmove(*dest, *data, masklen);
*data += masklen;
*dest += masklen;
}
phase = 2;
break;
case cs_rmoveto:
if (phase == 0 && (stack_top % 2)) {
have_width = 1;
width = arg_stack[0];
}
clear_stack(dest, limit);
DST_NEED(limit, *dest + 1);
*(*dest)++ = op;
phase = 2;
break;
case cs_hmoveto:
case cs_vmoveto:
if (phase == 0 && (stack_top % 2) == 0) {
have_width = 1;
width = arg_stack[0];
}
clear_stack(dest, limit);
DST_NEED(limit, *dest + 1);
*(*dest)++ = op;
phase = 2;
break;
case cs_endchar:
if (stack_top == 1) {
have_width = 1;
width = arg_stack[0];
clear_stack(dest, limit);
} else if (stack_top == 4 || stack_top == 5) {
dpx_warning("\"seac\" character deprecated in Type 2 charstring.");
status = CS_PARSE_ERROR;
return;
} else if (stack_top > 0) {
dpx_warning("%s: Operand stack not empty.", CS_TYPE2_DEBUG_STR);
}
DST_NEED(limit, *dest + 1);
*(*dest)++ = op;
status = CS_CHAR_END;
break;
/* above oprators are candidate for first stack-clearing operator */
case cs_rlineto:
case cs_hlineto:
case cs_vlineto:
case cs_rrcurveto:
case cs_rcurveline:
case cs_rlinecurve:
case cs_vvcurveto:
case cs_hhcurveto:
case cs_vhcurveto:
case cs_hvcurveto:
if (phase < 2) {
dpx_warning("%s: Broken Type 2 charstring.", CS_TYPE2_DEBUG_STR);
status = CS_PARSE_ERROR;
return;
}
clear_stack(dest, limit);
DST_NEED(limit, *dest + 1);
*(*dest)++ = op;
break;
/* all operotors above are stack-clearing operator */
/* no output */
case cs_return:
case cs_callgsubr:
case cs_callsubr:
_tt_abort("%s: Unexpected call(g)subr/return", CS_TYPE2_DEBUG_STR);
break;
default:
/* no-op ? */
dpx_warning("%s: Unknown charstring operator: 0x%02x", CS_TYPE2_DEBUG_STR, op);
status = CS_PARSE_ERROR;
break;
}
return;
}
/*
* Double byte operators:
* Flex, arithmetic, conditional, and storage operators.
*
* Following operators are not supported:
* random: How random ?
*/
static void
do_operator2 (card8 **dest, card8 *limit, card8 **data, card8 *endptr)
{
card8 op;
*data += 1;
SRC_NEED(endptr, *data + 1);
op = **data;
*data += 1;
switch(op) {
case cs_dotsection: /* deprecated */
dpx_warning("Operator \"dotsection\" deprecated in Type 2 charstring.");
status = CS_PARSE_ERROR;
return;
case cs_hflex:
case cs_flex:
case cs_hflex1:
case cs_flex1:
if (phase < 2) {
dpx_warning("%s: Broken Type 2 charstring.", CS_TYPE2_DEBUG_STR);
status = CS_PARSE_ERROR;
return;
}
clear_stack(dest, limit);
DST_NEED(limit, *dest + 2);
*(*dest)++ = cs_escape;
*(*dest)++ = op;
break;
/* all operator above are stack-clearing */
/* no output */
case cs_and:
NEED(stack_top, 2);
stack_top--;
if (arg_stack[stack_top] && arg_stack[stack_top-1]) {
arg_stack[stack_top-1] = 1.0;
} else {
arg_stack[stack_top-1] = 0.0;
}
break;
case cs_or:
NEED(stack_top, 2);
stack_top--;
if (arg_stack[stack_top] || arg_stack[stack_top-1]) {
arg_stack[stack_top-1] = 1.0;
} else {
arg_stack[stack_top-1] = 0.0;
}
break;
case cs_not:
NEED(stack_top, 1);
if (arg_stack[stack_top-1]) {
arg_stack[stack_top-1] = 0.0;
} else {
arg_stack[stack_top-1] = 1.0;
}
break;
case cs_abs:
NEED(stack_top, 1);
arg_stack[stack_top-1] = fabs(arg_stack[stack_top-1]);
break;
case cs_add:
NEED(stack_top, 2);
arg_stack[stack_top-2] += arg_stack[stack_top-1];
stack_top--;
break;
case cs_sub:
NEED(stack_top, 2);
arg_stack[stack_top-2] -= arg_stack[stack_top-1];
stack_top--;
break;
case cs_div: /* doesn't check overflow */
NEED(stack_top, 2);
arg_stack[stack_top-2] /= arg_stack[stack_top-1];
stack_top--;
break;
case cs_neg:
NEED(stack_top, 1);
arg_stack[stack_top-1] *= -1.0;
break;
case cs_eq:
NEED(stack_top, 2);
stack_top--;
if (arg_stack[stack_top] == arg_stack[stack_top-1]) {
arg_stack[stack_top-1] = 1.0;
} else {
arg_stack[stack_top-1] = 0.0;
}
break;
case cs_drop:
NEED(stack_top, 1);
stack_top--;
break;
case cs_put:
NEED(stack_top, 2);
{
int idx = (int)arg_stack[--stack_top];
NEED(CS_TRANS_ARRAY_MAX, idx);
trn_array[idx] = arg_stack[--stack_top];
}
break;
case cs_get:
NEED(stack_top, 1);
{
int idx = (int)arg_stack[stack_top-1];
NEED(CS_TRANS_ARRAY_MAX, idx);
arg_stack[stack_top-1] = trn_array[idx];
}
break;
case cs_ifelse:
NEED(stack_top, 4);
stack_top -= 3;
if (arg_stack[stack_top+1] > arg_stack[stack_top+2]) {
arg_stack[stack_top-1] = arg_stack[stack_top];
}
break;
case cs_mul:
NEED(stack_top, 2);
arg_stack[stack_top-2] = arg_stack[stack_top-2] * arg_stack[stack_top-1];
stack_top--;
break;
case cs_sqrt:
NEED(stack_top, 1);
arg_stack[stack_top-1] = sqrt(arg_stack[stack_top-1]);
break;
case cs_dup:
NEED(stack_top, 1);
NEED(CS_ARG_STACK_MAX, stack_top+1);
arg_stack[stack_top] = arg_stack[stack_top-1];
stack_top++;
break;
case cs_exch:
NEED(stack_top, 2);
{
double save = arg_stack[stack_top-2];
arg_stack[stack_top-2] = arg_stack[stack_top-1];
arg_stack[stack_top-1] = save;
}
break;
case cs_index:
NEED(stack_top, 2); /* need two arguments at least */
{
int idx = (int)arg_stack[stack_top-1];
if (idx < 0) {
arg_stack[stack_top-1] = arg_stack[stack_top-2];
} else {
NEED(stack_top, idx+2);
arg_stack[stack_top-1] = arg_stack[stack_top-idx-2];
}
}
break;
case cs_roll:
NEED(stack_top, 2);
{
int N, J;
J = (int)arg_stack[--stack_top];
N = (int)arg_stack[--stack_top];
NEED(stack_top, N);
if (J > 0) {
J = J % N;
while (J-- > 0) {
double save = arg_stack[stack_top-1];
int i = stack_top - 1;
while (i > stack_top-N) {
arg_stack[i] = arg_stack[i-1];
i--;
}
arg_stack[i] = save;
}
} else {
J = (-J) % N;
while (J-- > 0) {
double save = arg_stack[stack_top-N];
int i = stack_top - N;
while (i < stack_top-1) {
arg_stack[i] = arg_stack[i+1];
i++;
}
arg_stack[i] = save;
}
}
}
break;
case cs_random:
dpx_warning("%s: Charstring operator \"random\" found.", CS_TYPE2_DEBUG_STR);
NEED(CS_ARG_STACK_MAX, stack_top+1);
arg_stack[stack_top++] = 1.0;
break;
default:
/* no-op ? */
dpx_warning("%s: Unknown charstring operator: 0x0c%02x", CS_TYPE2_DEBUG_STR, op);
status = CS_PARSE_ERROR;
break;
}
return;
}
/*
* integer:
* exactly the same as the DICT encoding (except 29)
*/
static void
get_integer (card8 **data, card8 *endptr)
{
int result = 0;
card8 b0 = **data, b1, b2;
*data += 1;
if (b0 == 28) { /* shortint */
SRC_NEED(endptr, *data + 2);
b1 = **data;
b2 = *(*data+1);
result = b1*256+b2;
if (result > 0x7fff)
result -= 0x10000L;
*data += 2;
} else if (b0 >= 32 && b0 <= 246) { /* int (1) */
result = b0 - 139;
} else if (b0 >= 247 && b0 <= 250) { /* int (2) */
SRC_NEED(endptr, *data + 1);
b1 = **data;
result = (b0-247)*256+b1+108;
*data += 1;
} else if (b0 >= 251 && b0 <= 254) {
SRC_NEED(endptr, *data + 1);
b1 = **data;
result = -(b0-251)*256-b1-108;
*data += 1;
} else {
status = CS_PARSE_ERROR;
return;
}
NEED(CS_ARG_STACK_MAX, stack_top+1);
arg_stack[stack_top++] = (double) result;
return;
}
/*
* Signed 16.16-bits fixed number for Type 2 charstring encoding
*/
static void
get_fixed (card8 **data, card8 *endptr)
{
int ivalue;
double rvalue;
*data += 1;
SRC_NEED(endptr, *data + 4);
ivalue = *(*data) * 0x100 + *(*data+1);
rvalue = (ivalue > 0x7fffL) ? (ivalue - 0x10000L) : ivalue;
ivalue = *(*data+2) * 0x100 + *(*data+3);
rvalue += ((double) ivalue) / 0x10000L;
NEED(CS_ARG_STACK_MAX, stack_top+1);
arg_stack[stack_top++] = rvalue;
*data += 4;
return;
}
/*
* Subroutines:
* The bias for subroutine number is introduced in type 2 charstrings.
*
* subr: set to a pointer to the subroutine charstring.
* len: set to the length of subroutine charstring.
* subr_idx: CFF INDEX data that contains subroutines.
* id: biased subroutine number.
*/
static void
get_subr (card8 **subr, int *len, cff_index *subr_idx, int id)
{
card16 count;
if (subr_idx == NULL)
_tt_abort("%s: Subroutine called but no subroutine found.", CS_TYPE2_DEBUG_STR);
count = subr_idx->count;
/* Adding bias number */
if (count < 1240) {
id += 107;
} else if (count < 33900) {
id += 1131;
} else {
id += 32768;
}
if (id > count)
_tt_abort("%s: Invalid Subr index: %d (max=%u)", CS_TYPE2_DEBUG_STR, id, count);
*len = (subr_idx->offset)[id + 1] - (subr_idx->offset)[id];
*subr = subr_idx->data + (subr_idx->offset)[id] - 1;
return;
}
/*
* NOTE:
* The Type 2 interpretation of a number encoded in five-bytes (those with
* an initial byte value of 255) differs from how it is interpreted in the
* Type 1 format.
*/
static void
do_charstring (card8 **dest, card8 *limit,
card8 **data, card8 *endptr,
cff_index *gsubr_idx, cff_index *subr_idx)
{
card8 b0 = 0, *subr;
int len;
if (nest > CS_SUBR_NEST_MAX)
_tt_abort("%s: Subroutine nested too deeply.", CS_TYPE2_DEBUG_STR);
nest++;
while (*data < endptr && status == CS_PARSE_OK) {
b0 = **data;
if (b0 == 255) { /* 16-bit.16-bit fixed signed number */
get_fixed(data, endptr);
} else if (b0 == cs_return) {
status = CS_SUBR_RETURN;
} else if (b0 == cs_callgsubr) {
if (stack_top < 1) {
status = CS_STACK_ERROR;
} else {
stack_top--;
get_subr(&subr, &len, gsubr_idx, (int) arg_stack[stack_top]);
if (*dest + len > limit)
_tt_abort("%s: Possible buffer overflow.", CS_TYPE2_DEBUG_STR);
do_charstring(dest, limit, &subr, subr + len,
gsubr_idx, subr_idx);
*data += 1;
}
} else if (b0 == cs_callsubr) {
if (stack_top < 1) {
status = CS_STACK_ERROR;
} else {
stack_top--;
get_subr(&subr, &len, subr_idx, (int) arg_stack[stack_top]);
if (limit < *dest + len)
_tt_abort("%s: Possible buffer overflow.", CS_TYPE2_DEBUG_STR);
do_charstring(dest, limit, &subr, subr + len,
gsubr_idx, subr_idx);
*data += 1;
}
} else if (b0 == cs_escape) {
do_operator2(dest, limit, data, endptr);
} else if (b0 < 32 && b0 != 28) { /* 19, 20 need mask */
do_operator1(dest, limit, data, endptr);
} else if ((b0 >= 22 && b0 <= 27) || b0 == 31) { /* reserved */
status = CS_PARSE_ERROR; /* not an error ? */
} else { /* integer */
get_integer(data, endptr);
}
}
if (status == CS_SUBR_RETURN) {
status = CS_PARSE_OK;
} else if (status == CS_CHAR_END && *data < endptr) {
dpx_warning("%s: Garbage after endchar.", CS_TYPE2_DEBUG_STR);
} else if (status < CS_PARSE_OK) { /* error */
_tt_abort("%s: Parsing charstring failed: (status=%d, stack=%d)",
CS_TYPE2_DEBUG_STR, status, stack_top);
}
nest--;
return;
}
static void
cs_parse_init (void)
{
status = CS_PARSE_OK;
nest = 0;
phase = 0;
num_stems = 0;
stack_top = 0;
}
/*
* Not just copying...
*/
int
cs_copy_charstring (card8 *dst, int dstlen,
card8 *src, int srclen,
cff_index *gsubr, cff_index *subr,
double default_width, double nominal_width, cs_ginfo *ginfo)
{
card8 *save = dst;
cs_parse_init();
width = 0.0;
have_width = 0;
/* expand call(g)subrs */
do_charstring(&dst, dst + dstlen, &src, src + srclen, gsubr, subr);
if (ginfo) {
ginfo->flags = 0; /* not used */
if (have_width) {
ginfo->wx = nominal_width + width;
} else {
ginfo->wx = default_width;
}
}
return (int)(dst - save);
}
|
fmgoncalves/tectonic
|
tectonic/dpx-cmap.h
|
<filename>tectonic/dpx-cmap.h
/* This is dvipdfmx, an eXtended version of dvipdfm by <NAME>.
Copyright (C) 2002-2016 by <NAME> and <NAME>,
the dvipdfmx project team.
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.
*/
#ifndef _CMAP_H_
#define _CMAP_H_
#include "dpx-core.h"
#include <stdbool.h>
#include <stddef.h>
#include <sys/types.h>
#include "dpx-cid.h"
#include "dpx-cmap_p.h"
typedef unsigned short CID;
typedef unsigned short UCV16;
/* Limits */
#define CID_MAX_CID 65535
#define CID_MAX CID_MAX_CID
#define CID_NOTDEF_CHAR "\0\0"
#define CID_NOTDEF 0
#define UCS_NOTDEF_CHAR "\377\375"
#define UCS_NOTDEF 0xfffd
/*
* TYPE_IDENTITY and TYPE_CID_TO_CODE is not defined in the CMap spec.
*/
#define CMAP_TYPE_IDENTITY 0
#define CMAP_TYPE_CODE_TO_CID 1
#define CMAP_TYPE_TO_UNICODE 2
#define CMAP_TYPE_CID_TO_CODE 3
#define CMAP_PROF_TYPE_INBYTES_MIN 0
#define CMAP_PROF_TYPE_INBYTES_MAX 1
#define CMAP_PROF_TYPE_OUTBYTES_MIN 2
#define CMAP_PROF_TYPE_OUTBYTES_MAX 3
typedef struct CMap CMap;
/************************** CMAP_MAIN **************************/
void CMap_set_verbose (int level);
void CMap_set_silent (int value);
CMap *CMap_new (void);
void CMap_release (CMap *cmap);
bool CMap_is_valid (CMap *cmap);
bool CMap_is_Identity (CMap *cmap);
int CMap_get_profile (CMap *cmap, int type);
char *CMap_get_name (CMap *cmap);
int CMap_get_type (CMap *cmap);
int CMap_get_wmode(CMap *cmap);
CIDSysInfo *CMap_get_CIDSysInfo(CMap *cmap);
void CMap_set_name (CMap *cmap, const char *name);
void CMap_set_type (CMap *cmap, int type);
void CMap_set_wmode (CMap *cmap, int wmode);
void CMap_set_usecmap(CMap *cmap, CMap *ucmap);
void CMap_set_CIDSysInfo (CMap *cmap, const CIDSysInfo *csi);
/* charName not supported */
int CMap_add_bfchar (CMap *cmap,
const unsigned char *src, size_t srcdim,
const unsigned char *dest, size_t destdim);
int CMap_add_cidchar (CMap *cmap,
const unsigned char *src, size_t srcdim, CID dest);
int CMap_add_bfrange (CMap *cmap,
const unsigned char *srclo, const unsigned char *srchi, size_t srcdim,
const unsigned char *dest, size_t destdim);
int CMap_add_cidrange(CMap *cmap,
const unsigned char *srclo, const unsigned char *hi, size_t srcdim,
CID base);
int CMap_add_notdefchar (CMap *cmap, const unsigned char *src, size_t srcdim, CID dst);
int CMap_add_notdefrange (CMap *cmap,
const unsigned char *srclo, const unsigned char *srchi, size_t srcdim,
CID dst);
int CMap_add_codespacerange (CMap *cmap,
const unsigned char *codelo, const unsigned char *codehi, size_t dim);
void CMap_decode_char (CMap *cmap,
const unsigned char **inbuf, size_t *inbytesleft,
unsigned char **outbuf, size_t *outbytesleft);
size_t CMap_decode (CMap *cmap,
const unsigned char **inbuf, size_t *inbytesleft,
unsigned char **outbuf, size_t *outbytesleft);
int CMap_reverse_decode(CMap *cmap, CID cid);
void CMap_cache_init (void);
CMap *CMap_cache_get (int id);
int CMap_cache_find (const char *cmap_name);
void CMap_cache_close (void);
int CMap_cache_add (CMap *cmap);
#endif /* _CMAP_H_ */
|
fmgoncalves/tectonic
|
tectonic/xetex-XeTeXFontInst_Mac.h
|
<gh_stars>1-10
/****************************************************************************\
Part of the XeTeX typesetting system
Copyright (c) 1994-2008 by SIL International
Copyright (c) 2009 by <NAME>
Copyright (c) 2012, 2013 by <NAME>
SIL Author(s): <NAME>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT 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.
Except as contained in this notice, the name of the copyright holders
shall not be used in advertising or otherwise to promote the sale,
use or other dealings in this Software without prior written
authorization from the copyright holders.
\****************************************************************************/
/*
* file name: XeTeXFontInst_Mac.h
*
* created on: 2005-10-22
* created by: <NAME>
*/
#ifndef __XeTeXFontInst_Mac_H
#define __XeTeXFontInst_Mac_H
#include "xetex-core.h"
#include "xetex-XeTeXFontInst.h"
#include <ApplicationServices/ApplicationServices.h>
class XeTeXFontInst_Mac : public XeTeXFontInst
{
protected:
CTFontDescriptorRef m_descriptor;
CTFontRef m_fontRef;
public:
XeTeXFontInst_Mac(CTFontDescriptorRef descriptor, float pointSize, int &status);
virtual ~XeTeXFontInst_Mac();
virtual void initialize(int &status);
};
#endif
|
fmgoncalves/tectonic
|
tectonic/dpx-subfont.c
|
/* This is dvipdfmx, an eXtended version of dvipdfm by <NAME>.
Copyright (C) 2002-2016 by <NAME> and <NAME>,
the dvipdfmx project team.
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 "dpx-subfont.h"
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "core-bridge.h"
#include "dpx-dpxfile.h"
#include "dpx-error.h"
#include "dpx-mem.h"
#include "dpx-mfileio.h"
static int verbose = 0;
void
subfont_set_verbose (int level)
{
verbose = level;
}
/* Don't forget fontmap reading now requires information
* from SFD files. You must initialize at least sfd_file_
* cache before starting loading of fontmaps.
*/
/* Subfont Definition File:
* struct sfd_file_ is for storing subfont identifiers
* contained in a SFD file and for mapping string pair
* <SFD_file, Subfont_id> to internal code mapping table
* ID which is index within an array of struct sfd_rec_.
* We store code mapping tables in different place than
* struct sfd_file_.
*/
struct sfd_file_
{
char *ident; /* SFD file name */
char **sub_id; /* Subfont IDs */
int *rec_id; /* indices within struct sfd_rec_ array "sfd_record" */
int max_subfonts;
int num_subfonts;
};
/* Mapping table */
struct sfd_rec_
{
/* unsigned char misbit[32]; */
unsigned short vector[256]; /* 0 for undefined */
};
static void
init_sfd_file_ (struct sfd_file_ *sfd)
{
sfd->ident = NULL;
sfd->sub_id = NULL;
sfd->rec_id = NULL;
sfd->max_subfonts = sfd->num_subfonts = 0;
}
static void
clean_sfd_file_ (struct sfd_file_ *sfd)
{
int i;
free(sfd->ident);
if (sfd->sub_id) {
for (i = 0; i < sfd->num_subfonts; i++) {
free(sfd->sub_id[i]);
}
free(sfd->sub_id);
}
free(sfd->rec_id);
init_sfd_file_(sfd);
}
static struct sfd_file_ *sfd_files = NULL;
static int num_sfd_files = 0, max_sfd_files = 0;
static struct sfd_rec_ *sfd_record = NULL;
static int num_sfd_records = 0, max_sfd_records = 0;
/* Another buffer...
* We want buffer size at least 7 x 256 + a
* 4096 is usually enough.
*/
#define LINE_BUF_SIZE 4096
static char line_buf[LINE_BUF_SIZE];
/* Each lines describes character code mapping for each
* subfonts. '#' is start of comment.
* SFD file format uses a '\' before newline sequence
* for line-continuation.
*/
static char *
readline (char *buf, int buf_len, rust_input_handle_t *handle)
{
char *r, *q, *p = buf;
int n = 0, c = 0;
while (buf_len - n > 0 && (q = tt_mfgets(p, buf_len - n, handle))) {
c++;
r = strchr(q, '#');
/* Comment is converted to single wsp (followed by a newline). */
if (r) {
*r = ' ';
*(r + 1) = '\0';
}
if (strlen(q) == 0)
break; /* empty line */
n += strlen(q);
q += strlen(q) - 1;
if (*q != '\\')
break;
else { /* line continued */
n -= 1;
p = buf + n;
}
}
if (n >= buf_len - 1) {
dpx_warning("Possible buffer overflow in reading SFD file (buffer full, size=%d bytes)",
buf_len - 1);
}
return (c > 0 ? buf : NULL);
}
#define clear_vector(v) if ((v)) { \
int __i; \
for (__i = 0; __i < 256; __i++) \
(v)[__i] = 0; \
}
/* subfont_id ( integer ':' | integer '_' integer | integer )*
*
* 0x32: ==> Subsequent integers are place into slots starting at 0x32.
* 0x32: 0xA1A1 0xA1A2 ... ==> 0x32 is mappned to 0xA1A1, 0x33 to 0xA1A2
* 0xA1A1_0xA1A5 ==> Expanded to 0xA1A1 0xA1A2 ... 0xA1A5
*/
/* subfont_id is already consumed here. */
static int
read_sfd_record (struct sfd_rec_ *rec, const char *lbuf)
{
const char *p = lbuf, *q;
char *r;
int repos = 0;
int c, v1 = 0, v2 = 0;
int curpos = 0;
int error = 0;
#define IS_TOKSEP(c) ((c) == '\0' || isspace((unsigned char)(c)))
for ( ; *p && isspace((unsigned char)*p); p++);
while (!error && *p) {
repos = 0; q = p;
v1 = strtol(p, &r, 0);
q = r;
if (q == p ||
(!IS_TOKSEP(*q) && *q != ':' && *q != '_')) {
dpx_warning("Unknown token in subfont mapping table: %c", *q);
return -1;
}
switch (*q) {
case ':':
if (v1 < 0 || v1 > 0xff) {
dpx_warning("Invalud value for subfont table offset: %d", v1);
return -1;
}
repos = 1;
q++;
break;
case '_':
p = q + 1;
v2 = strtol(p, &r, 0);
q = r;
if (v1 < 0 || v1 > 0xffffL ||
v2 < 0 || v2 > 0xffffL) {
dpx_warning("Invalid value in subfont mapping table: 0x%x_0x%x", v1, v2);
return -1;
} else if (q == p || !IS_TOKSEP(*q)) {
dpx_warning("Invalid char in subfont mapping table: %c", *q);
return -1;
}
break;
default:
if (v1 < 0 || v1 > 0xffffL) {
dpx_warning("Invalid character code in subfont mapping table: 0x%x", v1);
return -1;
}
v2 = v1;
break;
}
if (repos)
curpos = v1;
else {
if (v2 < v1 || curpos + (v2 - v1) > 0xff) {
dpx_warning("Invalid range in subfont mapping: curpos=\"0x%02x\" range=\"0x%04x,0x%04x\"",
curpos, v1, v2);
return -1;
}
for (c = v1; c <= v2; c++) {
if (rec->vector[curpos] != 0) {
dpx_warning("Subfont mapping for slot=\"0x%02x\" already defined...", curpos);
return -1;
}
assert( curpos >= 0 && curpos <= 255 );
rec->vector[curpos++] = (unsigned short) c;
}
}
for (p = q; *p && isspace((unsigned char)*p); p++);
}
return error;
}
/* Scan for subfont IDs */
static int
scan_sfd_file (struct sfd_file_ *sfd, rust_input_handle_t *handle)
{
char *id;
char *q, *p;
int n, lpos = 0;
assert( sfd && handle );
if (verbose > 3) {
dpx_message("\nsubfont>> Scanning SFD file \"%s\"...\n", sfd->ident);
}
ttstub_input_seek(handle, 0, SEEK_SET);
sfd->max_subfonts = sfd->num_subfonts = 0;
while ((p = readline(line_buf, LINE_BUF_SIZE, handle)) != NULL) {
lpos++;
for ( ; *p && isspace((unsigned char)*p); p++);
if (*p == 0)
continue; /* empty */
/* Saw non-wsp here */
for (n = 0, q = p; *p && !isspace((unsigned char)*p); p++, n++);
id = NEW(n + 1, char);
memcpy(id, q, n); id[n] = '\0';
if (sfd->num_subfonts >= sfd->max_subfonts) {
sfd->max_subfonts += 16;
sfd->sub_id = RENEW(sfd->sub_id, sfd->max_subfonts, char *);
}
if (verbose > 3) {
dpx_message("subfont>> id=\"%s\" at line=\"%d\"\n", id, lpos);
}
sfd->sub_id[sfd->num_subfonts] = id;
sfd->num_subfonts++;
}
sfd->rec_id = NEW(sfd->num_subfonts, int);
for (n = 0; n < sfd->num_subfonts; n++) {
sfd->rec_id[n] = -1; /* Not loaded yet. We do lazy loading of map definitions. */
}
if (verbose > 3) {
dpx_message("subfont>> %d entries found in SFD file \"%s\".\n", sfd->num_subfonts, sfd->ident);
}
return 0;
}
/* Open SFD file and gather subfont IDs. We do not read mapping tables
* here but only read subfont IDs used in SFD file.
*/
static int
find_sfd_file (const char *sfd_name)
{
int id = -1;
int i, error = -1;
/* Check if we already opened SFD file */
for (i = 0; i < num_sfd_files; i++) {
if (streq_ptr(sfd_files[i].ident, sfd_name)) {
id = i;
break;
}
}
if (id < 0) {
struct sfd_file_ *sfd = NULL;
rust_input_handle_t *handle = NULL;
if (num_sfd_files >= max_sfd_files) {
max_sfd_files += 8;
sfd_files = RENEW(sfd_files, max_sfd_files, struct sfd_file_);
}
sfd = &sfd_files[num_sfd_files];
init_sfd_file_(sfd);
sfd->ident = NEW(strlen(sfd_name) + 1, char);
strcpy(sfd->ident, sfd_name);
handle = ttstub_input_open(sfd->ident, TTIF_SFD, 0);
if (handle == NULL) {
clean_sfd_file_(sfd);
return -1;
}
error = scan_sfd_file(sfd, handle);
ttstub_input_close(handle);
if (!error)
id = num_sfd_files++;
else {
dpx_warning("Error occured while reading SFD file \"%s\"", sfd_name);
clean_sfd_file_(sfd);
id = -1;
}
}
return id;
}
char **
sfd_get_subfont_ids (const char *sfd_name, int *num_ids)
{
int sfd_id;
if (!sfd_name)
return NULL;
sfd_id = find_sfd_file(sfd_name);
if (sfd_id < 0)
return NULL;
if (num_ids)
*num_ids = sfd_files[sfd_id].num_subfonts;
return sfd_files[sfd_id].sub_id;
}
/* Make sure that sfd_name does not have the extension '.sfd'.
* Mapping tables are actually read here.
*/
int
sfd_load_record (const char *sfd_name, const char *subfont_id)
{
int rec_id = -1;
struct sfd_file_ *sfd;
rust_input_handle_t *handle;
int sfd_id, i, error = 0;
char *p, *q;
if (!sfd_name || !subfont_id)
return -1;
sfd_id = find_sfd_file(sfd_name);
if (sfd_id < 0)
return -1;
sfd = &sfd_files[sfd_id];
/* Check if we already loaded mapping table. */
for (i = 0;
i < sfd->num_subfonts && strcmp(sfd->sub_id[i], subfont_id); i++);
if (i == sfd->num_subfonts) {
dpx_warning("Subfont id=\"%s\" not exist in SFD file \"%s\"...",
subfont_id, sfd->ident);
return -1;
} else if (sfd->rec_id[i] >= 0) {
return sfd->rec_id[i];
}
if (verbose > 3) {
dpx_message("\nsubfont>> Loading SFD mapping table for <%s,%s>...",
sfd->ident, subfont_id);
}
/* reopen */
handle = ttstub_input_open(sfd->ident, TTIF_SFD, 0);
if (handle == NULL) {
return -1;
/* _tt_abort("Could not open SFD file \"%s\"", sfd_name); */
}
/* Seek to record for 'sub_name'. */
while ((p = readline(line_buf, LINE_BUF_SIZE, handle))) {
for ( ; *p && isspace((unsigned char)*p); p++);
if (*p == 0)
continue; /* empty line */
/* q = parse_ident(&p, p + strlen(p)); */
for (q = p; *p && !isspace((unsigned char)*p); p++);
*p = '\0'; p++;
if (streq_ptr(q, subfont_id)) {
if (num_sfd_records >= max_sfd_records) {
max_sfd_records += 16;
sfd_record = RENEW(sfd_record, max_sfd_records, struct sfd_rec_);
}
clear_vector(sfd_record[num_sfd_records].vector);
error = read_sfd_record(&sfd_record[num_sfd_records], p);
if (error)
dpx_warning("Error occured while reading SFD file: file=\"%s\" subfont_id=\"%s\"",
sfd->ident, subfont_id);
else {
rec_id = num_sfd_records++;
}
}
}
if (rec_id < 0) {
dpx_warning("Failed to load subfont mapping table for SFD=\"%s\" subfont_id=\"%s\"",
sfd->ident, subfont_id);
}
sfd->rec_id[i] = rec_id;
ttstub_input_close(handle);
if (verbose > 3) {
int __i;
if (rec_id >= 0) {
dpx_message(" at id=\"%d\"", rec_id);
dpx_message("\nsubfont>> Content of mapping table:");
for (__i = 0; __i < 256; __i++) {
if (__i % 16 == 0)
dpx_message("\nsubfont>> ");
dpx_message(" %04x", sfd_record[rec_id].vector[__i]);
}
}
dpx_message("\n");
}
return rec_id;
}
/* Lookup mapping table */
unsigned short
lookup_sfd_record (int rec_id, unsigned char c)
{
if (!sfd_record ||
rec_id < 0 || rec_id >= num_sfd_records)
_tt_abort("Invalid subfont_id: %d", rec_id);
return sfd_record[rec_id].vector[c];
}
void
release_sfd_record (void)
{
int i;
if (sfd_record) {
free(sfd_record);
}
if (sfd_files) {
for (i = 0; i < num_sfd_files; i++) {
clean_sfd_file_(&sfd_files[i]);
}
free(sfd_files);
}
sfd_record = NULL;
sfd_files = NULL;
num_sfd_records = max_sfd_records = 0;
num_sfd_files = max_sfd_files = 0;
}
|
fmgoncalves/tectonic
|
tectonic/dpx-unicode.c
|
<reponame>fmgoncalves/tectonic
/* This is dvipdfmx, an eXtended version of dvipdfm by <NAME>.
Copyright (C) 2002-2016 by <NAME> and <NAME>,
the dvipdfmx project team.
Copyright (C) 1998, 1999 by <NAME> <<EMAIL>>
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.
*/
/*
* Unicode related:
* Conversion between UTF-* and UCS-*.
* ToUnicode CMap
*
* Normalization?
*
* I made some unused functions here for completeness and FUTURE USE.
*/
#include "dpx-unicode.h"
#include <assert.h>
#include <stdbool.h>
#define UC_DEBUG 3
#define UC_DEBUG_STR "UC"
#define UC_REPLACEMENT_CHAR 0x0000FFFD
#define UC_SUR_SHIFT 10
#define UC_SUR_MASK 0x03FFU
#define UC_SUR_LOW_START 0xDC00U
#define UC_SUR_HIGH_START 0xD800U
#define UC_SUR_END 0xE000U
bool
UC_is_valid (int32_t ucv)
{
return !(ucv < 0
|| ucv > 0x10FFFFL
|| (ucv >= 0x0000D800L && ucv <= 0x0000DFFFL)
);
}
bool
UC_UTF16BE_is_valid_string (const unsigned char *p, const unsigned char *endptr)
{
if (p + 1 >= endptr)
return false;
while (p < endptr) {
int32_t ucv = UC_UTF16BE_decode_char(&p, endptr);
if (!UC_is_valid(ucv))
return false;
}
return true;
}
bool
UC_UTF8_is_valid_string (const unsigned char *p, const unsigned char *endptr)
{
if (p + 1 >= endptr)
return false;
while (p < endptr) {
int32_t ucv = UC_UTF8_decode_char(&p, endptr);
if (!UC_is_valid(ucv))
return false;
}
return true;
}
int32_t
UC_UTF16BE_decode_char (const unsigned char **pp, const unsigned char *endptr)
{
const unsigned char *p = *pp;
int32_t ucv = -1;
uint16_t first, second;
if (p + 1 >= endptr)
return -1;
first = ((p[0]) << 8|p[1]); p += 2;
if (first >= UC_SUR_HIGH_START && first < UC_SUR_LOW_START) {
if (p + 1 >= endptr)
return -1;
second = (p[0] << 8|p[1]); p += 2;
ucv = second & UC_SUR_MASK;
ucv |= (first & UC_SUR_MASK) << UC_SUR_SHIFT;
ucv += 0x00010000;
} else if (first >= UC_SUR_LOW_START && first < UC_SUR_END) {
return -1;
} else {
ucv = first;
}
*pp = p;
return ucv;
}
size_t
UC_UTF16BE_encode_char (int32_t ucv, unsigned char **pp, unsigned char *endptr)
{
int count = 0;
unsigned char *p = *pp;
if (ucv >= 0 && ucv <= 0xFFFF) {
if (p + 2 >= endptr)
return 0;
p[0] = (ucv >> 8) & 0xff;
p[1] = ucv & 0xff;
count = 2;
} else if (ucv >= 0x010000 && ucv <= 0x10FFFF) {
unsigned short high, low;
if (p + 4 >= endptr)
return 0;
ucv -= 0x00010000;
high = (ucv >> UC_SUR_SHIFT) + UC_SUR_HIGH_START;
low = (ucv & UC_SUR_MASK) + UC_SUR_LOW_START;
p[0] = (high >> 8) & 0xff;
p[1] = (high & 0xff);
p[2] = (low >> 8) & 0xff;
p[3] = (low & 0xff);
count = 4;
} else {
if (p + 2 >= endptr)
return 0;
p[0] = (UC_REPLACEMENT_CHAR >> 8) & 0xff;
p[1] = (UC_REPLACEMENT_CHAR & 0xff);
count = 2;
}
*pp += count;
return count;
}
int32_t
UC_UTF8_decode_char (const unsigned char **pp, const unsigned char *endptr)
{
const unsigned char *p = *pp;
int32_t ucv;
unsigned char c = *p++;
int nbytes;
if (c <= 0x7f) {
ucv = c;
nbytes = 0;
} else if ((c & 0xe0) == 0xc0) { /* 110x xxxx */
ucv = c & 31;
nbytes = 1;
} else if ((c & 0xf0) == 0xe0) { /* 1110 xxxx */
ucv = c & 0x0f;
nbytes = 2;
} else if ((c & 0xf8) == 0xf0) { /* 1111 0xxx */
ucv = c & 0x07;
nbytes = 3;
} else if ((c & 0xfc) == 0xf8) { /* 1111 10xx */
ucv = c & 0x03;
nbytes = 4;
} else if ((c & 0xfe) == 0xfc) { /* 1111 110x */
ucv = c & 0x01;
nbytes = 5;
} else {
return -1;
}
if (p + nbytes > endptr)
return -1;
while (nbytes-- > 0) {
c = *p++;
if ((c & 0xc0) != 0x80)
return -1;
ucv = (ucv << 6) | (c & 0x3f);
}
*pp = p;
return ucv;
}
size_t
UC_UTF8_encode_char (int32_t ucv, unsigned char **pp, unsigned char *endptr)
{
int count = 0;
unsigned char *p = *pp;
assert( pp && *pp && endptr );
if (!UC_is_valid(ucv))
return 0;
if (ucv < 0x7f) {
if (p >= endptr - 1)
return 0;
p[0] = (unsigned char) ucv;
count = 1;
} else if (ucv <= 0x7ff) {
if (p >= endptr -2)
return 0;
p[0] = (unsigned char) (0xc0 | (ucv >> 6));
p[1] = (unsigned char) (0x80 | (ucv & 0x3f));
count = 2;
} else if (ucv <= 0xffff) {
if (p >= endptr - 3)
return 0;
p[0] = (unsigned char) (0xe0 | (ucv >> 12));
p[1] = (unsigned char) (0x80 | ((ucv >> 6) & 0x3f));
p[2] = (unsigned char) (0x80 | (ucv & 0x3f));
count = 3;
} else if (ucv <= 0x1fffff) {
if (p >= endptr - 4)
return 0;
p[0] = (unsigned char) (0xf0 | (ucv >> 18));
p[1] = (unsigned char) (0x80 | ((ucv >> 12) & 0x3f));
p[2] = (unsigned char) (0x80 | ((ucv >> 6) & 0x3f));
p[3] = (unsigned char) (0x80 | (ucv & 0x3f));
count = 4;
} else if (ucv <= 0x3ffffff) {
if (p >= endptr - 5)
return 0;
p[0] = (unsigned char) (0xf8 | (ucv >> 24));
p[1] = (unsigned char) (0x80 | ((ucv >> 18) & 0x3f));
p[2] = (unsigned char) (0x80 | ((ucv >> 12) & 0x3f));
p[3] = (unsigned char) (0x80 | ((ucv >> 6) & 0x3f));
p[4] = (unsigned char) (0x80 | (ucv & 0x3f));
count = 5;
} else if (ucv <= 0x7fffffff) {
if (p >= endptr - 6)
return 0;
p[0] = (unsigned char) (0xfc | (ucv >> 30));
p[1] = (unsigned char) (0x80 | ((ucv >> 24) & 0x3f));
p[2] = (unsigned char) (0x80 | ((ucv >> 18) & 0x3f));
p[3] = (unsigned char) (0x80 | ((ucv >> 12) & 0x3f));
p[4] = (unsigned char) (0x80 | ((ucv >> 6) & 0x3f));
p[5] = (unsigned char) (0x80 | (ucv & 0x3f));
count = 6;
}
*pp += count;
return count;
}
|
fmgoncalves/tectonic
|
tectonic/dpx-dpxfile.c
|
/* This is dvipdfmx, an eXtended version of dvipdfm by <NAME>.
Copyright (C) 2007-2016 by <NAME> and <NAME>,
the dvipdfmx project team.
Copyright (C) 1998, 1999 by <NAME> <<EMAIL>>
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 "dpx-dpxfile.h"
#include <fcntl.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <time.h>
#ifndef _MSC_VER
#include <unistd.h>
#include <dirent.h>
#endif
#include "dpx-mem.h"
#include "dpx-numbers.h"
#include "dpx-system.h"
#define MAX_KEY_LEN 16
#include <stdlib.h>
#include <string.h>
static int verbose = 0;
int keep_cache = 0;
void
dpx_file_set_verbose (int level)
{
verbose = level;
}
static char _sbuf[128];
/*
* SFNT type sigs:
* `true' (0x74727565): TrueType (Mac)
* `typ1' (0x74797031) (Mac): PostScript font housed in a sfnt wrapper
* 0x00010000: TrueType (Win)/OpenType
* `OTTO': PostScript CFF font with OpenType wrapper
* `ttcf': TrueType Collection
*/
static bool
check_stream_is_truetype (rust_input_handle_t handle)
{
int n;
ttstub_input_seek (handle, 0, SEEK_SET);
n = ttstub_input_read (handle, _sbuf, 4);
ttstub_input_seek (handle, 0, SEEK_SET);
if (n != 4)
return false;
if (!memcmp(_sbuf, "true", 4) || !memcmp(_sbuf, "\0\1\0\0", 4)) /* This doesn't help... */
return true;
if (!memcmp(_sbuf, "ttcf", 4))
return true;
return false;
}
/* "OpenType" is only for ".otf" here */
static bool
check_stream_is_opentype (rust_input_handle_t handle)
{
int n;
ttstub_input_seek (handle, 0, SEEK_SET);
n = ttstub_input_read (handle, _sbuf, 4);
ttstub_input_seek (handle, 0, SEEK_SET);
if (n != 4)
return false;
if (!memcmp(_sbuf, "OTTO", 4))
return true;
return false;
}
static bool
check_stream_is_type1 (rust_input_handle_t handle)
{
char *p = _sbuf;
int n;
ttstub_input_seek (handle, 0, SEEK_SET);
n = ttstub_input_read (handle, p, 21);
ttstub_input_seek (handle, 0, SEEK_SET);
if (n != 21)
return false;
if (p[0] != (char) 0x80 || p[1] < 0 || p[1] > 3)
return false;
if (!memcmp(p + 6, "%!PS-AdobeFont", 14) || !memcmp(p + 6, "%!FontType1", 11))
return true;
if (!memcmp(p + 6, "%!PS", 4)) {
/* This was #if-0'd out:
* p[20] = '\0'; p += 6;
* dpx_warning("Ambiguous PostScript resource type: %s", (char *) p);
*/
return true;
}
return false;
}
static bool
check_stream_is_dfont (rust_input_handle_t handle)
{
int i, n;
uint32_t pos;
ttstub_input_seek (handle, 0, SEEK_SET);
tt_get_unsigned_quad(handle);
pos = tt_get_unsigned_quad (handle);
ttstub_input_seek (handle, pos + 0x18, SEEK_SET);
ttstub_input_seek (handle, pos + tt_get_unsigned_pair (handle), SEEK_SET);
n = tt_get_unsigned_pair (handle);
for (i = 0; i <= n; i++) {
if (tt_get_unsigned_quad(handle) == 0x73666e74UL) /* "sfnt" */
return true;
tt_get_unsigned_quad(handle);
}
return false;
}
/* ensuresuffix() returns a copy of basename if sfx is "". */
static char *
ensuresuffix (const char *basename, const char *sfx)
{
char *q, *p;
p = NEW(strlen(basename) + strlen(sfx) + 1, char);
strcpy(p, basename);
q = strrchr(p, '.');
if (!q && sfx[0])
strcat(p, sfx);
return p;
}
rust_input_handle_t
dpx_tt_open (const char *filename, const char *suffix, tt_input_format_type format)
{
char *q;
rust_input_handle_t handle;
q = ensuresuffix(filename, suffix);
handle = ttstub_input_open(q, format, 0);
free(q);
return handle;
}
/* Search order:
* SFDFONTS (TDS 1.1)
* ttf2pk (text file)
* ttf2tfm (text file)
* dvipdfm (text file)
*/
rust_input_handle_t
dpx_open_type1_file (const char *filename)
{
rust_input_handle_t handle;
handle = ttstub_input_open (filename, TTIF_TYPE1, 0);
if (handle == NULL)
return NULL;
if (!check_stream_is_type1 (handle)) {
ttstub_input_close (handle);
return NULL;
}
return handle;
}
rust_input_handle_t
dpx_open_truetype_file (const char *filename)
{
rust_input_handle_t handle;
handle = ttstub_input_open (filename, TTIF_TRUETYPE, 0);
if (handle == NULL)
return NULL;
if (!check_stream_is_truetype (handle)) {
ttstub_input_close (handle);
return NULL;
}
return handle;
}
rust_input_handle_t
dpx_open_opentype_file (const char *filename)
{
rust_input_handle_t handle;
char *q;
q = ensuresuffix(filename, ".otf");
handle = ttstub_input_open (q, TTIF_OPENTYPE, 0);
free (q);
if (handle == NULL)
return NULL;
if (!check_stream_is_opentype (handle)) {
ttstub_input_close (handle);
return NULL;
}
return handle;
}
rust_input_handle_t
dpx_open_dfont_file (const char *filename)
{
char *q;
rust_input_handle_t handle;
int len = strlen(filename);
if (len > 6 && strncmp(filename + len - 6, ".dfont", 6)) {
/* I've double-checked that we're accurately representing the original
* code -- the above strncmp() is *not* missing a logical negation.
*/
q = NEW(len + 6, char);
strcpy(q, filename);
strcat(q, "/rsrc");
} else {
q = xstrdup (filename);
}
handle = ttstub_input_open (q, TTIF_TRUETYPE, 0);
free (q);
if (handle == NULL)
return NULL;
if (!check_stream_is_dfont (handle)) {
ttstub_input_close (handle);
return NULL;
}
return handle;
}
static char *
dpx_get_tmpdir (void)
{
# ifdef _MSC_VER
# define __TMPDIR "C:\\Windows\\Temp"
# else
# define __TMPDIR "/tmp"
# endif
size_t i;
char *ret;
const char *_tmpd;
_tmpd = getenv("TMPDIR");
if (!_tmpd)
_tmpd = __TMPDIR;
ret = xstrdup(_tmpd);
i = strlen(ret);
while(i > 1 && IS_DIR_SEP(ret[i-1])) {
ret[i-1] = '\0';
i--;
}
return ret;
}
char *
dpx_create_temp_file (void)
{
char *tmpdir;
size_t n;
char *tmp = NULL;
#ifndef _MSC_VER
# define TEMPLATE "/dvipdfmx.XXXXXX"
#else
# define TEMPLATE "\\dvipdfmx.XXXXXX"
#endif
tmpdir = dpx_get_tmpdir();
n = strlen(tmpdir) + strlen(TEMPLATE) + 1;
tmp = NEW(n, char);
strcpy(tmp, tmpdir);
free(tmpdir);
strcat(tmp, TEMPLATE);
#ifdef _MSC_VER
if (_mktemp_s(tmp, n) != 0)
tmp = mfree(tmp);
#else
{
int _fd = mkstemp(tmp);
if (_fd != -1)
close(_fd);
else
tmp = mfree(tmp);
}
#endif
return tmp;
}
void
dpx_delete_old_cache (int life)
{
/* This used to delete files in tmpdir, but that code was ripped out since
* it would have been annoying to port to Windows. */
if (life == -2)
keep_cache = -1;
}
void
dpx_delete_temp_file (char *tmp, int force)
{
if (!tmp)
return;
if (force || keep_cache != 1) remove (tmp);
free(tmp);
return;
}
/* dpx_file_apply_filter() is used for converting unsupported graphics
* format to one of the formats that dvipdfmx can natively handle.
* 'input' is the filename of the original file and 'output' is actually
* temporal files 'generated' by the above routine.
* This should be system dependent. (MiKTeX may want something different)
* Please modify as appropriate (see also pdfximage.c and dvipdfmx.c).
*/
int
dpx_file_apply_filter (const char *cmdtmpl,
const char *input, const char *output,
unsigned char version)
{
/* Tectonic: defused */
return -1;
}
|
fmgoncalves/tectonic
|
tectonic/dpx-cmap.c
|
/* This is dvipdfmx, an eXtended version of dvipdfm by <NAME>.
Copyright (C) 2002-2016 by <NAME> and <NAME>,
the dvipdfmx project team.
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.
*/
/*
* References:
*
* PostScript Language Reference Manual, 3rd. ed. (Adobe Systems Inc.)
* 5.11.4 CMap Dictionaries
* 5.11.5 FMapType 9 Composite Fonts
* Building CMap Files for CID-Keyed Fonts, Adobe Technical Note #5099
* CID-Keyed Font Technology Overview, Adobe Technical Note #5092
* Adobe CMap and CIDFont Files Specification, Adobe Technical Specification #5014
*
* Undefined Character Handling:
* PLRM 3rd. ed., sec. 5.11.5., "Handling Undefined Characters"
*
* TODO:
* Only cid(range|char) allowed for CODE_TO_CID and bf(range|char) for CID_TO_CODE ?
*/
#include "dpx-cmap.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "core-bridge.h"
#include "dpx-cmap_p.h"
#include "dpx-dpxutil.h"
#include "dpx-error.h"
#include "dpx-mem.h"
static int __verbose = 0;
static int __silent = 0;
void
CMap_set_verbose (int level)
{
__verbose = level;
}
void
CMap_set_silent (int value)
{
__silent = value ? 1 : 0;
}
/* Private funcs. */
static size_t bytes_consumed (CMap *cmap, const unsigned char *instr, size_t inbytes);
static void handle_undefined (CMap *cmap,
const unsigned char **inbuf, size_t *inbytesleft,
unsigned char **outbuf, size_t *outbytesleft);
static int check_range (CMap *cmap,
const unsigned char *srclo, const unsigned char *srchi, size_t srcdim,
const unsigned char *dst, size_t dstdim);
static unsigned char *get_mem (CMap *cmap, int size);
static mapDef *mapDef_new (void);
static void mapDef_release (mapDef *t);
static int locate_tbl (mapDef **cur, const unsigned char *code, int dim);
CMap *
CMap_new (void)
{
CMap *cmap;
cmap = NEW(1, struct CMap);
cmap->name = NULL;
cmap->type = CMAP_TYPE_CODE_TO_CID;
cmap->wmode = 0;
cmap->useCMap = NULL;
cmap->CSI = NULL;
cmap->profile.minBytesIn = 2;
cmap->profile.maxBytesIn = 2;
cmap->profile.minBytesOut = 2;
cmap->profile.maxBytesOut = 2;
cmap->flags = 0;
cmap->codespace.num = 0;
cmap->codespace.max = 10;
cmap->codespace.ranges = NEW(10, struct rangeDef);
cmap->mapTbl = NULL;
cmap->mapData = NEW(1, struct mapData);
cmap->mapData->prev = NULL;
cmap->mapData->pos = 0;
cmap->mapData->data = NEW(MEM_ALLOC_SIZE, unsigned char);
cmap->reverseMap = NEW(65536, int);
memset(cmap->reverseMap, 0, 65536 * sizeof(int));
return cmap;
}
void
CMap_release (CMap *cmap)
{
if (!cmap)
return;
free(cmap->name);
if (cmap->CSI) {
free(cmap->CSI->registry);
free(cmap->CSI->ordering);
free(cmap->CSI);
}
free(cmap->codespace.ranges);
if (cmap->mapTbl)
mapDef_release(cmap->mapTbl);
{
mapData *map = cmap->mapData;
while (map != NULL) {
mapData *prev = map->prev;
free(map->data);
free(map);
map = prev;
}
}
free(cmap->reverseMap);
free(cmap);
}
bool
CMap_is_Identity (CMap *cmap)
{
assert(cmap);
return streq_ptr(cmap->name, "Identity-H")
|| streq_ptr(cmap->name, "Identity-V");
}
bool
CMap_is_valid (CMap *cmap)
{
/* Quick check */
if (!cmap || !(cmap->name) || cmap->type < CMAP_TYPE_IDENTITY ||
cmap->type > CMAP_TYPE_CID_TO_CODE || cmap->codespace.num < 1 ||
(cmap->type != CMAP_TYPE_IDENTITY && !cmap->mapTbl))
return false;
if (cmap->useCMap) {
CIDSysInfo *csi1, *csi2;
csi1 = CMap_get_CIDSysInfo(cmap);
csi2 = CMap_get_CIDSysInfo(cmap->useCMap);
if (strcmp(csi1->registry, csi2->registry) ||
strcmp(csi1->ordering, csi2->ordering)) {
dpx_warning("CIDSystemInfo mismatched %s <--> %s",
CMap_get_name(cmap), CMap_get_name(cmap->useCMap));
return false;
}
}
return true;
}
int
CMap_get_profile (CMap *cmap, int type)
{
int value = 0;
assert(cmap);
switch (type) {
case CMAP_PROF_TYPE_INBYTES_MIN:
value = cmap->profile.minBytesIn;
break;
case CMAP_PROF_TYPE_INBYTES_MAX:
value = cmap->profile.maxBytesIn;
break;
case CMAP_PROF_TYPE_OUTBYTES_MIN:
value = cmap->profile.maxBytesOut;
break;
case CMAP_PROF_TYPE_OUTBYTES_MAX:
value = cmap->profile.maxBytesOut;
break;
default:
_tt_abort("%s: Unrecognized profile type %d.", CMAP_DEBUG_STR, type);
}
return value;
}
/*
* Put notdef chars for codes not declared in notdef(range|char)
*/
static void
handle_undefined (CMap *cmap,
const unsigned char **inbuf, size_t *inbytesleft,
unsigned char **outbuf, size_t *outbytesleft)
{
size_t len = 0;
if (*outbytesleft < 2)
_tt_abort("%s: Buffer overflow.", CMAP_DEBUG_STR);
switch (cmap->type) {
case CMAP_TYPE_CODE_TO_CID:
memcpy(*outbuf, CID_NOTDEF_CHAR, 2);
break;
case CMAP_TYPE_TO_UNICODE:
memcpy(*outbuf, UCS_NOTDEF_CHAR, 2);
break;
default:
dpx_warning("Cannot handle undefined mapping for this type of CMap mapping: %d", cmap->type);
dpx_warning("<0000> is used for .notdef char.");
memset(*outbuf, 0, 2);
}
*outbuf += 2;
*outbytesleft -= 2;
len = bytes_consumed(cmap, *inbuf, *inbytesleft);
*inbuf += len;
*inbytesleft -= len;
}
void
CMap_decode_char (CMap *cmap,
const unsigned char **inbuf, size_t *inbytesleft,
unsigned char **outbuf, size_t *outbytesleft)
{
mapDef *t;
const unsigned char *p, *save;
unsigned char c = 0;
size_t count = 0;
p = save = *inbuf;
/*
* First handle some special cases:
*/
if (cmap->type == CMAP_TYPE_IDENTITY) {
if ((*inbytesleft) % 2)
_tt_abort("%s: Invalid/truncated input string.", CMAP_DEBUG_STR);
if (*outbytesleft < 2)
_tt_abort("%s: Buffer overflow.", CMAP_DEBUG_STR);
memcpy(*outbuf, *inbuf, 2);
*inbuf += 2;
*outbuf += 2;
*outbytesleft -= 2;
*inbytesleft -= 2;
return;
} else if (!cmap->mapTbl) {
if (cmap->useCMap) {
CMap_decode_char(cmap->useCMap, inbuf, inbytesleft, outbuf, outbytesleft);
return;
} else {
/* no mapping available in this CMap */
dpx_warning("No mapping available for this character.");
handle_undefined(cmap, inbuf, inbytesleft, outbuf, outbytesleft);
return;
}
}
assert(cmap->mapTbl);
t = cmap->mapTbl;
while (count < *inbytesleft) {
c = *p++;
count++;
if (LOOKUP_END(t[c].flag))
break;
t = t[c].next;
}
if (LOOKUP_CONTINUE(t[c].flag)) /* need more bytes */
_tt_abort("%s: Premature end of input string.", CMAP_DEBUG_STR);
else if (!MAP_DEFINED(t[c].flag)) {
if (cmap->useCMap) {
CMap_decode_char(cmap->useCMap, inbuf, inbytesleft, outbuf, outbytesleft);
return;
} else {
/* no mapping available in this CMap */
dpx_warning("No character mapping available.");
dpx_message(" CMap name: %s\n", CMap_get_name(cmap));
dpx_message(" input str: ");
dpx_message("<");
while (save < p) {
dpx_message("%02x", *save);
save++;
}
dpx_message(">\n");
/*
* We know partial match found up to `count' bytes,
* but we will not use this information for the sake of simplicity.
*/
handle_undefined(cmap, inbuf, inbytesleft, outbuf, outbytesleft);
return;
}
} else {
switch (MAP_TYPE(t[c].flag)) {
case MAP_IS_NOTDEF:
dpx_warning("Character mapped to .notdef found.");
/* continue */
case MAP_IS_CID: case MAP_IS_CODE:
if (*outbytesleft >= t[c].len)
memcpy(*outbuf, t[c].code, t[c].len);
else
_tt_abort("%s: Buffer overflow.", CMAP_DEBUG_STR);
*outbuf += t[c].len;
*outbytesleft -= t[c].len;
break;
case MAP_IS_NAME:
_tt_abort("%s: CharName mapping not supported.", CMAP_DEBUG_STR);
break;
default:
_tt_abort("%s: Unknown mapping type.", CMAP_DEBUG_STR);
}
if (inbytesleft)
*inbytesleft -= count;
*inbuf = p;
}
}
/*
* For convenience, it does not do decoding to CIDs.
*/
size_t
CMap_decode (CMap *cmap,
const unsigned char **inbuf, size_t *inbytesleft,
unsigned char **outbuf, size_t *outbytesleft)
{
size_t count;
assert(cmap && inbuf && outbuf);
assert(inbytesleft && outbytesleft);
for (count = 0;*inbytesleft > 0 && *outbytesleft > 0; count++)
CMap_decode_char(cmap, inbuf, inbytesleft, outbuf, outbytesleft);
return count;
}
int
CMap_reverse_decode(CMap *cmap, CID cid) {
int ch = cmap->reverseMap ? cmap->reverseMap[cid] : -1;
if (ch == 0 && cmap->useCMap)
return CMap_reverse_decode(cmap->useCMap, cid);
return ch;
}
char *
CMap_get_name (CMap *cmap)
{
assert(cmap);
return cmap->name;
}
int
CMap_get_type (CMap *cmap)
{
assert(cmap);
return cmap->type;
}
int
CMap_get_wmode (CMap *cmap)
{
assert(cmap);
return cmap->wmode;
}
CIDSysInfo *
CMap_get_CIDSysInfo (CMap *cmap)
{
assert(cmap);
return cmap->CSI;
}
void
CMap_set_name (CMap *cmap, const char *name)
{
assert(cmap);
free(cmap->name);
cmap->name = NEW(strlen(name)+1, char);
strcpy(cmap->name, name);
}
void
CMap_set_type (CMap *cmap, int type)
{
assert(cmap);
cmap->type = type;
}
void
CMap_set_wmode (CMap *cmap, int wmode)
{
assert(cmap);
cmap->wmode = wmode;
}
void
CMap_set_CIDSysInfo (CMap *cmap, const CIDSysInfo *csi)
{
assert(cmap);
if (cmap->CSI) {
free(cmap->CSI->registry);
free(cmap->CSI->ordering);
free(cmap->CSI);
}
if (csi && csi->registry && csi->ordering) {
cmap->CSI = NEW(1, CIDSysInfo);
cmap->CSI->registry = NEW(strlen(csi->registry)+1, char);
strcpy(cmap->CSI->registry, csi->registry);
cmap->CSI->ordering = NEW(strlen(csi->ordering)+1, char);
strcpy(cmap->CSI->ordering, csi->ordering);
cmap->CSI->supplement = csi->supplement;
} else {
dpx_warning("Invalid CIDSystemInfo.");
cmap->CSI = NULL;
}
}
/*
* Can have muliple entry ?
*/
void
CMap_set_usecmap (CMap *cmap, CMap *ucmap)
{
unsigned int i;
assert(cmap);
assert(ucmap); /* Maybe if (!ucmap) _tt_abort() is better for this. */
if (cmap == ucmap)
_tt_abort("%s: Identical CMap object cannot be used for usecmap CMap: 0x%p=0x%p",
CMAP_DEBUG_STR, cmap, ucmap);
/* Check if ucmap have neccesary information. */
if (!CMap_is_valid(ucmap))
_tt_abort("%s: Invalid CMap.", CMAP_DEBUG_STR);
/*
* CMapName of cmap can be undefined when usecmap is executed in CMap parsing.
* And it is also possible CSI is not defined at that time.
*/
if (streq_ptr(cmap->name, ucmap->name))
_tt_abort("%s: CMap refering itself not allowed: CMap %s --> %s",
CMAP_DEBUG_STR, cmap->name, ucmap->name);
if (cmap->CSI && cmap->CSI->registry && cmap->CSI->ordering) {
if (strcmp(cmap->CSI->registry, ucmap->CSI->registry) ||
strcmp(cmap->CSI->ordering, ucmap->CSI->ordering))
_tt_abort("%s: CMap %s required by %s have different CSI.",
CMAP_DEBUG_STR, CMap_get_name(cmap), CMap_get_name(ucmap));
}
/* We must copy codespaceranges. */
for (i = 0; i < ucmap->codespace.num; i++) {
rangeDef *csr = ucmap->codespace.ranges + i;
CMap_add_codespacerange(cmap, csr->codeLo, csr->codeHi, csr->dim);
}
cmap->useCMap = ucmap;
}
/* Test the validity of character c. */
static int
CMap_match_codespace (CMap *cmap, const unsigned char *c, size_t dim)
{
unsigned int i, pos;
assert(cmap);
for (i = 0; i < cmap->codespace.num; i++) {
rangeDef *csr = cmap->codespace.ranges + i;
if (csr->dim != dim)
continue;
for (pos = 0; pos < dim; pos++) {
if (c[pos] > csr->codeHi[pos] || c[pos] < csr->codeLo[pos])
break;
}
if (pos == dim)
return 0; /* Valid */
}
return -1; /* Invalid */
}
/*
* No overlapping codespace ranges are allowed, otherwise mapping is ambiguous.
*/
int
CMap_add_codespacerange (CMap *cmap,
const unsigned char *codelo, const unsigned char *codehi, size_t dim)
{
rangeDef *csr = NULL;
unsigned int i;
assert(cmap && dim > 0);
for (i = 0; i < cmap->codespace.num; i++) {
size_t j;
bool overlap = true;
csr = cmap->codespace.ranges + i;
for (j = 0; j < MIN(csr->dim, dim) && overlap; j++) {
if ((codelo[j] >= csr->codeLo[j] && codelo[j] <= csr->codeHi[j]) ||
(codehi[j] >= csr->codeLo[j] && codehi[j] <= csr->codeHi[j]))
overlap = true;
else
overlap = false;
}
if (overlap) {
dpx_warning("Overlapping codespace found. (ingored)");
return -1;
}
}
if (dim < cmap->profile.minBytesIn)
cmap->profile.minBytesIn = dim;
if (dim > cmap->profile.maxBytesIn)
cmap->profile.maxBytesIn = dim;
if (cmap->codespace.num + 1 > cmap->codespace.max) {
cmap->codespace.max += 10;
cmap->codespace.ranges = RENEW(cmap->codespace.ranges, cmap->codespace.max, struct rangeDef);
}
csr = cmap->codespace.ranges + cmap->codespace.num;
csr->dim = dim;
csr->codeHi = get_mem(cmap, dim);
csr->codeLo = get_mem(cmap, dim);
memcpy(csr->codeHi, codehi, dim);
memcpy(csr->codeLo, codelo, dim);
(cmap->codespace.num)++;
return 0;
}
int
CMap_add_notdefchar (CMap *cmap, const unsigned char *src, size_t srcdim, CID dst)
{
return CMap_add_notdefrange(cmap, src, src, srcdim, dst);
}
int
CMap_add_notdefrange (CMap *cmap,
const unsigned char *srclo, const unsigned char *srchi, size_t srcdim, CID dst)
{
int c;
mapDef *cur;
assert(cmap);
/* dst not used here */
/* FIXME */
if (check_range(cmap, srclo, srchi, srcdim, (const unsigned char *)&dst, 2) < 0)
return -1;
if (cmap->mapTbl == NULL )
cmap->mapTbl = mapDef_new();
cur = cmap->mapTbl;
if (locate_tbl(&cur, srclo, srcdim) < 0)
return -1;
for (c = srclo[srcdim-1]; c <= srchi[srcdim-1]; c++) {
if (MAP_DEFINED(cur[c].flag)) {
if (!__silent)
dpx_warning("Trying to redefine already defined code mapping. (ignored)");
} else {
cur[c].flag = (MAP_LOOKUP_END|MAP_IS_NOTDEF);
cur[c].code = get_mem(cmap, 2);
cur[c].len = 2;
cur[c].code[0] = dst >> 8;
cur[c].code[1] = dst & 0xff;
}
/* Do not do dst++ for notdefrange */
}
return 0;
}
int
CMap_add_bfchar (CMap *cmap,
const unsigned char *src, size_t srcdim,
const unsigned char *dst, size_t dstdim)
{
return CMap_add_bfrange(cmap, src, src, srcdim, dst, dstdim);
}
int
CMap_add_bfrange (CMap *cmap,
const unsigned char *srclo, const unsigned char *srchi, size_t srcdim,
const unsigned char *base, size_t dstdim)
{
int c, last_byte, i;
mapDef *cur;
assert(cmap);
if (check_range(cmap, srclo, srchi, srcdim, base, dstdim) < 0)
return -1;
if (cmap->mapTbl == NULL)
cmap->mapTbl = mapDef_new();
cur = cmap->mapTbl;
if (locate_tbl(&cur, srclo, srcdim) < 0)
return -1;
for (c = srclo[srcdim-1]; c <= srchi[srcdim-1]; c++) {
/* According to 5014.CIDFont_Spec.pdf (p.52),
* Code mappings (unlike codespace ranges) may overlap,
* but succeeding maps superceded preceding maps.
* (reported and patched by <NAME> on 2007/12/2)
*/
if (!MAP_DEFINED(cur[c].flag) || cur[c].len < dstdim) {
cur[c].flag = (MAP_LOOKUP_END|MAP_IS_CODE);
cur[c].code = get_mem(cmap, dstdim);
}
/*
* We assume restriction to code ranges also applied here.
* Addition <00FF> + 1 is undefined.
*
* Changed on 2004-03-20:
*
* Should be treated as <0100> in Acrobat's "ToUnicode" CMap.
*/
cur[c].len = dstdim;
memcpy(cur[c].code, base, dstdim);
last_byte = c - srclo[srcdim-1] + base[dstdim-1];
cur[c].code[dstdim-1] = (last_byte & 0xFF);
for (i = dstdim - 2; i >= 0 && last_byte > 255; i--) {
last_byte = cur[c].code[i] + 1;
cur[c].code[i] = (last_byte & 0xFF);
}
}
return 0;
}
int
CMap_add_cidchar (CMap *cmap, const unsigned char *src, size_t srcdim, CID dst)
{
return CMap_add_cidrange(cmap, src, src, srcdim, dst);
}
int
CMap_add_cidrange (CMap *cmap,
const unsigned char *srclo, const unsigned char *srchi, size_t srcdim, CID base)
{
size_t i, c, v;
mapDef *cur;
assert(cmap);
/* base not used here */
if (check_range(cmap, srclo, srchi, srcdim, (const unsigned char *)&base, 2) < 0) /* FIXME */
return -1;
if (cmap->mapTbl == NULL )
cmap->mapTbl = mapDef_new();
cur = cmap->mapTbl;
if (locate_tbl(&cur, srclo, srcdim) < 0)
return -1;
for (v = 0, i = 0; i < srcdim - 1; i++)
v = (v << 8) + srclo[i];
cmap->reverseMap[base] = v;
for (c = srclo[srcdim-1]; c <= srchi[srcdim-1]; c++) {
if (cur[c].flag != 0) {
if (!__silent)
dpx_warning("Trying to redefine already defined CID mapping. (ignored)");
} else {
cur[c].flag = (MAP_LOOKUP_END|MAP_IS_CID);
cur[c].len = 2;
cur[c].code = get_mem(cmap, 2);
cur[c].code[0] = base >> 8;
cur[c].code[1] = base & 0xff;
cmap->reverseMap[base] = (v << 8) + c;
}
if (base >= CID_MAX)
dpx_warning("CID number too large.");
base++;
}
return 0;
}
static void
mapDef_release (mapDef *t)
{
int c;
assert(t);
for (c = 0; c < 256; c++) {
if (LOOKUP_CONTINUE(t[c].flag))
mapDef_release(t[c].next);
}
free(t);
}
static mapDef *
mapDef_new (void)
{
mapDef *t;
int c;
t = NEW(256, mapDef);
for (c=0; c<256; c++) {
t[c].flag = (MAP_LOOKUP_END|MAP_IS_UNDEF);
t[c].code = NULL;
t[c].next = NULL;
}
return t;
}
static unsigned char *
get_mem (CMap *cmap, int size)
{
mapData *map;
unsigned char *p;
assert(cmap && cmap->mapData && size >= 0);
map = cmap->mapData;
if (map->pos + size >= MEM_ALLOC_SIZE) {
mapData *prev = map;
map = NEW(1, struct mapData);
map->data = NEW(MEM_ALLOC_SIZE, unsigned char);
map->prev = prev;
map->pos = 0;
cmap->mapData = map;
}
p = map->data + map->pos;
map->pos += size;
return p;
}
static int
locate_tbl (mapDef **cur, const unsigned char *code, int dim)
{
int i, c;
assert(cur && *cur);
for (i = 0; i < dim-1; i++) {
c = code[i];
if (MAP_DEFINED((*cur)[c].flag)) {
dpx_warning("Ambiguous CMap entry.");
return -1;
}
if ((*cur)[c].next == NULL) /* create new node */
(*cur)[c].next = mapDef_new();
(*cur)[c].flag |= MAP_LOOKUP_CONTINUE;
*cur = (*cur)[c].next;
}
return 0;
}
/*
* Guess how many bytes consumed as a `single' character:
* Substring of length bytesconsumed bytes of input string is interpreted as
* a `single' character by CMap_decode().
*/
static size_t
bytes_consumed (CMap *cmap, const unsigned char *instr, size_t inbytes)
{
size_t i, pos, longest = 0, bytesconsumed;
assert(cmap);
for (i = 0; i < cmap->codespace.num; i++) {
rangeDef *csr = cmap->codespace.ranges + i;
for (pos = 0; pos < MIN(csr->dim, inbytes); pos++) {
if (instr[pos] > csr->codeHi[pos] || instr[pos] < csr->codeLo[pos])
break;
}
if (pos == csr->dim) /* part of instr is totally valid in this codespace. */
return csr->dim;
if (pos > longest)
longest = pos;
}
if (i == cmap->codespace.num) /* No matching at all */
bytesconsumed = cmap->profile.minBytesIn;
else {
bytesconsumed = cmap->profile.maxBytesIn;
for (i = 0; i< cmap->codespace.num; i++) {
rangeDef *csr = cmap->codespace.ranges + i;
if (csr->dim > longest && csr->dim < bytesconsumed)
bytesconsumed = csr->dim;
}
}
return bytesconsumed;
}
static int
check_range (CMap *cmap,
const unsigned char *srclo, const unsigned char *srchi, size_t srcdim,
const unsigned char *dst, size_t dstdim)
{
if ((srcdim < 1 || dstdim < 1) ||
(!srclo || !srchi || !dst) ||
memcmp(srclo, srchi, srcdim - 1) ||
srclo[srcdim-1] > srchi[srcdim-1]) {
dpx_warning("Invalid CMap mapping entry. (ignored)");
return -1;
}
if (CMap_match_codespace(cmap, srclo, srcdim) < 0 ||
CMap_match_codespace(cmap, srchi, srcdim) < 0) {
dpx_warning("Invalid CMap mapping entry. (ignored)");
return -1;
}
if (srcdim < cmap->profile.minBytesIn)
cmap->profile.minBytesIn = srcdim;
if (srcdim > cmap->profile.maxBytesIn)
cmap->profile.maxBytesIn = srcdim;
if (dstdim < cmap->profile.minBytesOut)
cmap->profile.minBytesOut = dstdim;
if (dstdim > cmap->profile.maxBytesOut)
cmap->profile.maxBytesOut = dstdim;
return 0;
}
/************************** CMAP_CACHE **************************/
#include "dpx-cmap_read.h"
#define CMAP_CACHE_ALLOC_SIZE 16u
struct CMap_cache {
int num;
int max;
CMap **cmaps;
};
static struct CMap_cache *__cache = NULL;
#define CHECK_ID(n) do { \
if (! __cache) \
_tt_abort("%s: CMap cache not initialized.", CMAP_DEBUG_STR); \
if ((n) < 0 || (n) >= __cache->num) \
_tt_abort("Invalid CMap ID %d", (n)); \
} while (0)
void
CMap_cache_init (void)
{
static unsigned char range_min[2] = {0x00, 0x00};
static unsigned char range_max[2] = {0xff, 0xff};
if (__cache)
_tt_abort("%s: Already initialized.", CMAP_DEBUG_STR);
__cache = NEW(1, struct CMap_cache);
__cache->max = CMAP_CACHE_ALLOC_SIZE;
__cache->cmaps = NEW(__cache->max, CMap *);
__cache->num = 0;
/* Create Identity mapping */
__cache->cmaps[0] = CMap_new();
CMap_set_name (__cache->cmaps[0], "Identity-H");
CMap_set_type (__cache->cmaps[0], CMAP_TYPE_IDENTITY);
CMap_set_wmode(__cache->cmaps[0], 0);
CMap_set_CIDSysInfo(__cache->cmaps[0], &CSI_IDENTITY);
CMap_add_codespacerange(__cache->cmaps[0], range_min, range_max, 2);
__cache->cmaps[1] = CMap_new();
CMap_set_name (__cache->cmaps[1], "Identity-V");
CMap_set_type (__cache->cmaps[1], CMAP_TYPE_IDENTITY);
CMap_set_wmode(__cache->cmaps[1], 1);
CMap_set_CIDSysInfo(__cache->cmaps[1], &CSI_IDENTITY);
CMap_add_codespacerange(__cache->cmaps[1], range_min, range_max, 2);
__cache->num += 2;
}
CMap *
CMap_cache_get (int id)
{
CHECK_ID(id);
return __cache->cmaps[id];
}
int
CMap_cache_find (const char *cmap_name)
{
int id = 0;
rust_input_handle_t handle = NULL;
if (!__cache)
CMap_cache_init();
assert(__cache);
for (id = 0; id < __cache->num; id++) {
char *name = NULL;
/* CMapName may be undefined when processing usecmap. */
name = CMap_get_name(__cache->cmaps[id]);
if (name && streq_ptr(cmap_name, name))
return id;
}
handle = ttstub_input_open(cmap_name, TTIF_CMAP, 0);
if (handle == NULL)
return -1;
if (CMap_parse_check_sig(handle) < 0) {
ttstub_input_close(handle);
return -1;
}
if (__verbose)
dpx_message("(CMap:%s", cmap_name);
if (__cache->num >= __cache->max) {
__cache->max += CMAP_CACHE_ALLOC_SIZE;
__cache->cmaps = RENEW(__cache->cmaps, __cache->max, CMap *);
}
id = __cache->num;
__cache->num++;
__cache->cmaps[id] = CMap_new();
if (CMap_parse(__cache->cmaps[id], handle) < 0)
_tt_abort("%s: Parsing CMap file failed.", CMAP_DEBUG_STR);
ttstub_input_close(handle);
if (__verbose)
dpx_message(")");
return id;
}
int
CMap_cache_add (CMap *cmap)
{
int id;
char *cmap_name0, *cmap_name1;
if (!CMap_is_valid(cmap))
_tt_abort("%s: Invalid CMap.", CMAP_DEBUG_STR);
for (id = 0; id < __cache->num; id++) {
cmap_name0 = CMap_get_name(cmap);
cmap_name1 = CMap_get_name(__cache->cmaps[id]);
if (streq_ptr(cmap_name0, cmap_name1)) {
_tt_abort("%s: CMap \"%s\" already defined.",
CMAP_DEBUG_STR, cmap_name0);
}
}
if (__cache->num >= __cache->max) {
__cache->max += CMAP_CACHE_ALLOC_SIZE;
__cache->cmaps = RENEW(__cache->cmaps, __cache->max, CMap *);
}
id = __cache->num;
(__cache->num)++;
__cache->cmaps[id] = cmap;
return id;
}
void
CMap_cache_close (void)
{
if (__cache) {
int id;
for (id = 0; id < __cache->num; id++) {
CMap_release(__cache->cmaps[id]);
}
free(__cache->cmaps);
__cache = mfree(__cache);
}
}
|
fmgoncalves/tectonic
|
tectonic/dpx-spc_pdfm.c
|
/* This is dvipdfmx, an eXtended version of dvipdfm by <NAME>.
Copyright (C) 2007-2017 by <NAME> and <NAME>,
the dvipdfmx project team.
Copyright (C) 1998, 1999 by <NAME> <<EMAIL>>
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 "dpx-spc_pdfm.h"
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dpx-dpxfile.h"
#include "dpx-dpxutil.h"
#include "dpx-dvipdfmx.h"
#include "dpx-error.h"
#include "dpx-fontmap.h"
#include "dpx-mem.h"
#include "dpx-mfileio.h"
#include "dpx-pdfcolor.h"
#include "dpx-pdfdev.h"
#include "dpx-pdfdoc.h"
#include "dpx-pdfdraw.h"
#include "dpx-pdfobj.h"
#include "dpx-pdfparse.h"
#include "dpx-pdfximage.h"
#include "dpx-spc_util.h"
#include "dpx-specials.h"
#include "dpx-unicode.h"
/* PLEASE REMOVE THIS */
struct resource_map {
int type;
int res_id;
};
struct tounicode {
int cmap_id;
int unescape_backslash;
pdf_obj *taintkeys; /* An array of PDF names. */
};
struct spc_pdf_
{
pdf_obj *annot_dict; /* pending annotation dict */
int lowest_level; /* current min level of outlines */
struct ht_table *resourcemap; /* see remark below (somewhere) */
struct tounicode cd; /* For to-UTF16-BE conversion :( */
};
static struct spc_pdf_ _pdf_stat = {
NULL,
255,
NULL,
{ -1, 0, NULL }
};
/* PLEASE REMOVE THIS */
static void
hval_free (void *vp)
{
free(vp);
}
static int
addresource (struct spc_pdf_ *sd, const char *ident, int res_id)
{
struct resource_map *r;
if (!ident || res_id < 0)
return -1;
r = NEW(1, struct resource_map);
r->type = 0; /* unused */
r->res_id = res_id;
ht_append_table(sd->resourcemap, ident, strlen(ident), r);
spc_push_object(ident, pdf_ximage_get_reference(res_id));
return 0;
}
static int
findresource (struct spc_pdf_ *sd, const char *ident)
{
struct resource_map *r;
if (!ident)
return -1;
r = ht_lookup_table(sd->resourcemap, ident, strlen(ident));
return (r ? r->res_id : -1);
}
static int
spc_handler_pdfm__init (void *dp)
{
struct spc_pdf_ *sd = dp;
/* The folllowing dictionary entry keys are considered as keys for
* text strings. Be sure that string object is NOT always a text string.
*/
static const char *default_taintkeys[] = {
"Title", "Author", "Subject", "Keywords",
"Creator", "Producer", "Contents", "Subj",
"TU", "T", "TM", NULL /* EOD */
};
int i;
sd->annot_dict = NULL;
sd->lowest_level = 255;
sd->resourcemap = NEW(1, struct ht_table);
ht_init_table(sd->resourcemap, hval_free);
sd->cd.taintkeys = pdf_new_array();
for (i = 0; default_taintkeys[i] != NULL; i++) {
pdf_add_array(sd->cd.taintkeys,
pdf_new_name(default_taintkeys[i]));
}
return 0;
}
static int
spc_handler_pdfm__clean (void *dp)
{
struct spc_pdf_ *sd = dp;
if (sd->annot_dict) {
dpx_warning("Unbalanced bann and eann found.");
pdf_release_obj(sd->annot_dict);
}
sd->lowest_level = 255;
sd->annot_dict = NULL;
if (sd->resourcemap) {
ht_clear_table(sd->resourcemap);
free(sd->resourcemap);
}
sd->resourcemap = NULL;
pdf_release_obj(sd->cd.taintkeys);
sd->cd.taintkeys = NULL;
return 0;
}
int
spc_pdfm_at_begin_document (void)
{
struct spc_pdf_ *sd = &_pdf_stat;
return spc_handler_pdfm__init(sd);
}
int
spc_pdfm_at_end_document (void)
{
struct spc_pdf_ *sd = &_pdf_stat;
return spc_handler_pdfm__clean(sd);
}
/* Dvipdfm specials */
static int
spc_handler_pdfm_bop (struct spc_env *spe, struct spc_arg *args)
{
if (args->curptr < args->endptr) {
pdf_doc_set_bop_content(args->curptr,
(int) (args->endptr - args->curptr));
}
args->curptr = args->endptr;
return 0;
}
static int
spc_handler_pdfm_eop (struct spc_env *spe, struct spc_arg *args)
{
if (args->curptr < args->endptr) {
pdf_doc_set_eop_content(args->curptr,
(int) (args->endptr - args->curptr));
}
args->curptr = args->endptr;
return 0;
}
#define streamfiltered(o) \
(pdf_lookup_dict(pdf_stream_dict((o)), "Filter") ? 1 : 0)
/* Why should we have this kind of things? */
static int
safeputresdent (pdf_obj *kp, pdf_obj *vp, void *dp)
{
char *key;
assert(kp && vp && dp);
key = pdf_name_value(kp);
if (pdf_lookup_dict(dp, key))
dpx_warning("Object \"%s\" already defined in dict! (ignored)", key);
else {
pdf_add_dict(dp,
pdf_link_obj(kp), pdf_link_obj(vp));
}
return 0;
}
#ifndef pdf_obj_isaref
#define pdf_obj_isaref(o) (pdf_obj_typeof((o)) == PDF_INDIRECT)
#endif
static int
safeputresdict (pdf_obj *kp, pdf_obj *vp, void *dp)
{
char *key;
pdf_obj *dict;
assert(kp && vp && dp);
key = pdf_name_value(kp);
dict = pdf_lookup_dict(dp, key);
if (pdf_obj_isaref(vp)) {
pdf_add_dict(dp, pdf_new_name(key), pdf_link_obj(vp));
} else if (pdf_obj_typeof(vp) == PDF_DICT) {
if (dict)
pdf_foreach_dict(vp, safeputresdent, dict);
else {
pdf_add_dict(dp, pdf_new_name(key), pdf_link_obj(vp));
}
} else {
dpx_warning("Invalid type (not DICT) for page/form resource dict entry: key=\"%s\"", key);
return -1;
}
return 0;
}
/* Think what happens if you do
*
* pdf:put @resources << /Font << >> >>
*
*/
static int
spc_handler_pdfm_put (struct spc_env *spe, struct spc_arg *ap)
{
pdf_obj *obj1, *obj2; /* put obj2 into obj1 */
char *ident;
int error = 0;
skip_white(&ap->curptr, ap->endptr);
ident = parse_opt_ident(&ap->curptr, ap->endptr);
if (!ident) {
spc_warn(spe, "Missing object identifier.");
return -1;
}
obj1 = spc_lookup_object(ident);
if (!obj1) {
spc_warn(spe, "Specified object not exist: %s", ident);
free(ident);
return -1;
}
skip_white(&ap->curptr, ap->endptr);
obj2 = parse_pdf_object(&ap->curptr, ap->endptr, NULL);
if (!obj2) {
spc_warn(spe, "Missing (an) object(s) to put into \"%s\"!", ident);
free(ident);
return -1;
}
switch (pdf_obj_typeof(obj1)) {
case PDF_DICT:
if (pdf_obj_typeof(obj2) != PDF_DICT) {
spc_warn(spe, "Inconsistent object type for \"put\" (expecting DICT): %s", ident);
error = -1;
} else {
if (streq_ptr(ident, "resources"))
error = pdf_foreach_dict(obj2, safeputresdict, obj1);
else {
pdf_merge_dict(obj1, obj2);
}
}
break;
case PDF_STREAM:
if (pdf_obj_typeof(obj2) == PDF_DICT)
pdf_merge_dict(pdf_stream_dict(obj1), obj2);
else if (pdf_obj_typeof(obj2) == PDF_STREAM)
{
spc_warn(spe, "\"put\" operation not supported for STREAM <- STREAM: %s", ident);
error = -1;
}
else {
spc_warn(spe, "Invalid type: expecting a DICT or STREAM: %s", ident);
error = -1;
}
break;
case PDF_ARRAY:
/* dvipdfm */
pdf_add_array(obj1, pdf_link_obj(obj2));
while (ap->curptr < ap->endptr) {
pdf_obj *obj3 = parse_pdf_object(&ap->curptr, ap->endptr, NULL);
if (!obj3)
break;
pdf_add_array(obj1, obj3);
skip_white(&ap->curptr, ap->endptr);
}
break;
default:
spc_warn(spe, "Can't \"put\" object into non-DICT/STREAM/ARRAY type object: %s", ident);
error = -1;
break;
}
pdf_release_obj(obj2);
free(ident);
return error;
}
/* For pdf:tounicode support
* This feature is provided for convenience. TeX can't do
* input encoding conversion.
*/
#include "dpx-cmap.h"
static int
reencodestring (CMap *cmap, pdf_obj *instring)
{
#define WBUF_SIZE 4096
unsigned char wbuf[WBUF_SIZE];
unsigned char *obufcur;
const unsigned char *inbufcur;
size_t inbufleft, obufleft;
if (!cmap || !instring)
return 0;
inbufleft = pdf_string_length(instring);
inbufcur = pdf_string_value (instring);
wbuf[0] = 0xfe;
wbuf[1] = 0xff;
obufcur = wbuf + 2;
obufleft = WBUF_SIZE - 2;
CMap_decode(cmap,
&inbufcur, &inbufleft,
&obufcur, &obufleft);
if (inbufleft > 0) {
return -1;
}
pdf_set_string(instring, wbuf, WBUF_SIZE - obufleft);
return 0;
}
static int
maybe_reencode_utf8(pdf_obj *instring)
{
unsigned char* inbuf;
int inlen;
int non_ascii = 0;
const unsigned char* cp;
unsigned char* op;
unsigned char wbuf[WBUF_SIZE];
if (!instring)
return 0;
inlen = pdf_string_length(instring);
inbuf = pdf_string_value(instring);
/* check if the input string is strictly ASCII */
for (cp = inbuf; cp < inbuf + inlen; ++cp) {
if (*cp > 127) {
non_ascii = 1;
}
}
if (non_ascii == 0)
return 0; /* no need to reencode ASCII strings */
/* Check if the input string is valid UTF8 string
* This routine may be called against non-text strings.
* We need to re-encode string only when string is a text string
* endcoded in UTF8.
*/
if (!UC_UTF8_is_valid_string(inbuf, inbuf + inlen))
return 0;
else if (inbuf[0] == 0xfe && inbuf[1] == 0xff &&
UC_UTF16BE_is_valid_string(inbuf + 2, inbuf + inlen))
return 0; /* no need to reencode UTF16BE with BOM */
cp = inbuf;
op = wbuf;
*op++ = 0xfe;
*op++ = 0xff;
while (cp < inbuf + inlen) {
int32_t usv;
int len;
usv = UC_UTF8_decode_char(&cp, inbuf + inlen);
if (!UC_is_valid(usv))
return -1; /* out of valid Unicode range, give up (redundant) */
len = UC_UTF16BE_encode_char(usv, &op, wbuf + WBUF_SIZE);
if (len == 0)
return -1;
}
pdf_set_string(instring, wbuf, op - wbuf);
return 0;
}
/* The purpose of this routine is to check if given string object is
* surely an object for *text* strings. It does not do a complete check
* but does a quick check. Please add entries for taintkeys if you have found
* additional dictionary entries which is considered as a text string.
*/
static int
needreencode (pdf_obj *kp, pdf_obj *vp, struct tounicode *cd)
{
int r = 0;
unsigned int i;
pdf_obj *tk;
assert( cd && cd->taintkeys );
assert( pdf_obj_typeof(kp) == PDF_NAME );
assert( pdf_obj_typeof(vp) == PDF_STRING );
for (i = 0; i < pdf_array_length(cd->taintkeys); i++) {
tk = pdf_get_array(cd->taintkeys, i);
assert( tk && pdf_obj_typeof(tk) == PDF_NAME );
if (streq_ptr(pdf_name_value(kp), pdf_name_value(tk))) {
r = 1;
break;
}
}
if (r) {
/* Check UTF-16BE BOM. */
if (pdf_string_length(vp) >= 2 &&
!memcmp(pdf_string_value(vp), "\xfe\xff", 2))
r = 0;
}
return r;
}
static int
modstrings (pdf_obj *kp, pdf_obj *vp, void *dp)
{
int r = 0; /* continue */
struct tounicode *cd = dp;
assert( pdf_obj_typeof(kp) == PDF_NAME );
switch (pdf_obj_typeof(vp)) {
case PDF_STRING:
if (cd && cd->cmap_id >= 0 && cd->taintkeys) {
CMap *cmap = CMap_cache_get(cd->cmap_id);
if (needreencode(kp, vp, cd))
r = reencodestring(cmap, vp);
} else if (is_xdv && cd && cd->taintkeys) {
/* Please fix this... PDF string object is not always a text string.
* needreencode() is assumed to do a simple check if given string
* object is actually a text string.
*/
if (needreencode(kp, vp, cd))
r = maybe_reencode_utf8(vp);
}
if (r < 0) /* error occured... */
dpx_warning("Failed to convert input string to UTF16...");
break;
case PDF_DICT:
r = pdf_foreach_dict(vp, modstrings, dp);
break;
case PDF_STREAM:
r = pdf_foreach_dict(pdf_stream_dict(vp), modstrings, dp);
break;
}
return r;
}
static pdf_obj *
parse_pdf_dict_with_tounicode (const char **pp, const char *endptr, struct tounicode *cd)
{
pdf_obj *dict;
/* disable this test for XDV files, as we do UTF8 reencoding with no cmap */
if (!is_xdv && cd->cmap_id < 0)
return parse_pdf_dict(pp, endptr, NULL);
/* :( */
if (cd && cd->unescape_backslash)
dict = parse_pdf_tainted_dict(pp, endptr);
else {
dict = parse_pdf_dict(pp, endptr, NULL);
}
if (dict)
pdf_foreach_dict(dict, modstrings, cd);
return dict;
}
static int
spc_handler_pdfm_annot (struct spc_env *spe, struct spc_arg *args)
{
struct spc_pdf_ *sd = &_pdf_stat;
pdf_obj *annot_dict;
pdf_rect rect;
char *ident = NULL;
pdf_coord cp;
transform_info ti;
skip_white(&args->curptr, args->endptr);
if (args->curptr[0] == '@') {
ident = parse_opt_ident(&args->curptr, args->endptr);
skip_white(&args->curptr, args->endptr);
}
transform_info_clear(&ti);
if (spc_util_read_dimtrns(spe, &ti, args, 0) < 0) {
free(ident);
return -1;
}
if ((ti.flags & INFO_HAS_USER_BBOX) &&
((ti.flags & INFO_HAS_WIDTH) || (ti.flags & INFO_HAS_HEIGHT))) {
spc_warn(spe, "You can't specify both bbox and width/height.");
free(ident);
return -1;
}
annot_dict = parse_pdf_dict_with_tounicode(&args->curptr, args->endptr, &sd->cd);
if (!annot_dict) {
spc_warn(spe, "Could not find dictionary object.");
free(ident);
return -1;
} else if (!PDF_OBJ_DICTTYPE(annot_dict)) {
spc_warn(spe, "Invalid type: not dictionary object.");
free(ident);
pdf_release_obj(annot_dict);
return -1;
}
cp.x = spe->x_user; cp.y = spe->y_user;
pdf_dev_transform(&cp, NULL);
if (ti.flags & INFO_HAS_USER_BBOX) {
rect.llx = ti.bbox.llx + cp.x;
rect.lly = ti.bbox.lly + cp.y;
rect.urx = ti.bbox.urx + cp.x;
rect.ury = ti.bbox.ury + cp.y;
} else {
rect.llx = cp.x;
rect.lly = cp.y - spe->mag * ti.depth;
rect.urx = cp.x + spe->mag * ti.width;
rect.ury = cp.y + spe->mag * ti.height;
}
/* Order is important... */
if (ident)
spc_push_object(ident, pdf_link_obj(annot_dict));
/* Add this reference. */
pdf_doc_add_annot(pdf_doc_current_page_number(), &rect, annot_dict, 1);
if (ident) {
spc_flush_object(ident);
free(ident);
}
pdf_release_obj(annot_dict);
return 0;
}
/* NOTE: This can't have ident. See "Dvipdfm User's Manual". */
static int
spc_handler_pdfm_bann (struct spc_env *spe, struct spc_arg *args)
{
struct spc_pdf_ *sd = &_pdf_stat;
int error = 0;
if (sd->annot_dict) {
spc_warn(spe, "Can't begin an annotation when one is pending.");
return -1;
}
skip_white(&args->curptr, args->endptr);
sd->annot_dict = parse_pdf_dict_with_tounicode(&args->curptr, args->endptr, &sd->cd);
if (!sd->annot_dict) {
spc_warn(spe, "Ignoring annotation with invalid dictionary.");
return -1;
} else if (!PDF_OBJ_DICTTYPE(sd->annot_dict)) {
spc_warn(spe, "Invalid type: not a dictionary object.");
pdf_release_obj(sd->annot_dict);
sd->annot_dict = NULL;
return -1;
}
error = spc_begin_annot(spe, sd->annot_dict);
return error;
}
static int
spc_handler_pdfm_eann (struct spc_env *spe, struct spc_arg *args)
{
struct spc_pdf_ *sd = &_pdf_stat;
int error = 0;
if (!sd->annot_dict) {
spc_warn(spe, "Tried to end an annotation without starting one!");
return -1;
}
error = spc_end_annot(spe);
pdf_release_obj(sd->annot_dict);
sd->annot_dict = NULL;
return error;
}
/* Color:.... */
static int
spc_handler_pdfm_bcolor (struct spc_env *spe, struct spc_arg *ap)
{
int error;
pdf_color fc, sc;
pdf_color *pfc, *psc;
pdf_color_get_current(&psc, &pfc);
error = spc_util_read_pdfcolor(spe, &fc, ap, pfc);
if (!error) {
if (ap->curptr < ap->endptr) {
error = spc_util_read_pdfcolor(spe, &sc, ap, psc);
} else {
pdf_color_copycolor(&sc, &fc);
}
}
if (error)
spc_warn(spe, "Invalid color specification?");
else {
pdf_color_push(&sc, &fc); /* save currentcolor */
}
return error;
}
/*
* This special changes the current color without clearing the color stack.
* It therefore differs from "color rgb 1 0 0".
*/
static int
spc_handler_pdfm_scolor (struct spc_env *spe, struct spc_arg *ap)
{
int error;
pdf_color fc, sc;
pdf_color *pfc, *psc;
pdf_color_get_current(&psc, &pfc);
error = spc_util_read_pdfcolor(spe, &fc, ap, pfc);
if (!error) {
if (ap->curptr < ap->endptr) {
error = spc_util_read_pdfcolor(spe, &sc, ap, psc);
} else {
pdf_color_copycolor(&sc, &fc);
}
}
if (error)
spc_warn(spe, "Invalid color specification?");
else
pdf_color_set(&sc, &fc);
return error;
}
static int
spc_handler_pdfm_ecolor (struct spc_env *spe, struct spc_arg *args)
{
pdf_color_pop();
return 0;
}
static int
spc_handler_pdfm_btrans (struct spc_env *spe, struct spc_arg *args)
{
pdf_tmatrix M;
transform_info ti;
transform_info_clear(&ti);
if (spc_util_read_dimtrns(spe, &ti, args, 0) < 0) {
return -1;
}
/* Create transformation matrix */
pdf_copymatrix(&M, &(ti.matrix));
M.e += ((1.0 - M.a) * spe->x_user - M.c * spe->y_user);
M.f += ((1.0 - M.d) * spe->y_user - M.b * spe->x_user);
pdf_dev_gsave();
pdf_dev_concat(&M);
return 0;
}
static int
spc_handler_pdfm_etrans (struct spc_env *spe, struct spc_arg *args)
{
pdf_dev_grestore();
/*
* Unfortunately, the following line is necessary in case
* of a color change inside of the save/restore pair.
* (Font changes are automatically corrected by pdf_dev_grestore().)
* Anything that was done there must be redone, so in effect,
* we make no assumptions about what fonts. We act like we are
* starting a new page.
*/
pdf_dev_reset_color(0);
return 0;
}
static int
spc_handler_pdfm_outline (struct spc_env *spe, struct spc_arg *args)
{
struct spc_pdf_ *sd = &_pdf_stat;
pdf_obj *item_dict, *tmp;
int level, is_open = -1;
int current_depth;
skip_white(&args->curptr, args->endptr);
/*
* pdf:outline is extended to support open/close feature
*
* pdf:outline 1 ... (as DVIPDFM)
* pdf:outline [] 1 ... (open bookmark)
* pdf:outline [-] 1 ... (closed bookmark)
*/
if (args->curptr+3 < args->endptr && *args->curptr == '[') {
args->curptr++;
if (*args->curptr == '-') {
args->curptr++;
} else {
is_open = 1;
}
args->curptr++;
}
skip_white(&args->curptr, args->endptr);
tmp = parse_pdf_object(&args->curptr, args->endptr, NULL);
if (!tmp) {
spc_warn(spe, "Missing number for outline item depth.");
return -1;
} else if (!PDF_OBJ_NUMBERTYPE(tmp)) {
pdf_release_obj(tmp);
spc_warn(spe, "Expecting number for outline item depth.");
return -1;
}
item_dict = NULL;
level = (int) pdf_number_value(tmp);
pdf_release_obj(tmp);
/* What is this? Starting at level 3 and can go down to level 1?
*
* Here is the original comment:
* Make sure we know where the starting level is
*
* NOTE: added
* We need this for converting pages from 3rd to... :(
*/
sd->lowest_level = MIN(sd->lowest_level, level);
level += 1 - sd->lowest_level;
item_dict = parse_pdf_dict_with_tounicode(&args->curptr, args->endptr, &sd->cd);
if (!item_dict) {
spc_warn(spe, "Ignoring invalid dictionary.");
return -1;
}
current_depth = pdf_doc_bookmarks_depth();
if (current_depth > level) {
while (current_depth-- > level)
pdf_doc_bookmarks_up();
} else if (current_depth < level) {
while (current_depth++ < level)
pdf_doc_bookmarks_down();
}
pdf_doc_bookmarks_add(item_dict, is_open);
return 0;
}
static int
spc_handler_pdfm_article (struct spc_env *spe, struct spc_arg *args)
{
struct spc_pdf_ *sd = &_pdf_stat;
char *ident;
pdf_obj *info_dict;
skip_white (&args->curptr, args->endptr);
ident = parse_opt_ident(&args->curptr, args->endptr);
if (!ident) {
spc_warn(spe, "Article name expected but not found.");
return -1;
}
info_dict = parse_pdf_dict_with_tounicode(&args->curptr, args->endptr, &sd->cd);
if (!info_dict) {
spc_warn(spe, "Ignoring article with invalid info dictionary.");
free(ident);
return -1;
}
pdf_doc_begin_article(ident, pdf_link_obj(info_dict));
spc_push_object(ident, info_dict);
free(ident);
return 0;
}
static int
spc_handler_pdfm_bead (struct spc_env *spe, struct spc_arg *args)
{
struct spc_pdf_ *sd = &_pdf_stat;
pdf_obj *article;
pdf_obj *article_info;
char *article_name;
pdf_rect rect;
int page_no;
transform_info ti;
pdf_coord cp;
skip_white(&args->curptr, args->endptr);
if (args->curptr[0] != '@') {
spc_warn(spe, "Article identifier expected but not found.");
return -1;
}
article_name = parse_opt_ident(&args->curptr, args->endptr);
if (!article_name) {
spc_warn(spe, "Article reference expected but not found.");
return -1;
}
/* If okay so far, try to get a bounding box */
transform_info_clear(&ti);
if (spc_util_read_dimtrns(spe, &ti, args, 0) < 0) {
free(article_name);
return -1;
}
if ((ti.flags & INFO_HAS_USER_BBOX) &&
((ti.flags & INFO_HAS_WIDTH) || (ti.flags & INFO_HAS_HEIGHT))) {
spc_warn(spe, "You can't specify both bbox and width/height.");
free(article_name);
return -1;
}
cp.x = spe->x_user; cp.y = spe->y_user;
pdf_dev_transform(&cp, NULL);
if (ti.flags & INFO_HAS_USER_BBOX) {
rect.llx = ti.bbox.llx + cp.x;
rect.lly = ti.bbox.lly + cp.y;
rect.urx = ti.bbox.urx + cp.x;
rect.ury = ti.bbox.ury + cp.y;
} else {
rect.llx = cp.x;
rect.lly = cp.y - spe->mag * ti.depth;
rect.urx = cp.x + spe->mag * ti.width;
rect.ury = cp.y + spe->mag * ti.height;
}
skip_white(&args->curptr, args->endptr);
if (args->curptr[0] != '<') {
article_info = pdf_new_dict();
} else {
article_info = parse_pdf_dict_with_tounicode(&args->curptr, args->endptr, &sd->cd);
if (!article_info) {
spc_warn(spe, "Error in reading dictionary.");
free(article_name);
return -1;
}
}
/* Does this article exist yet */
article = spc_lookup_object(article_name);
if (article) {
pdf_merge_dict (article, article_info);
pdf_release_obj(article_info);
} else {
pdf_doc_begin_article(article_name, pdf_link_obj(article_info));
spc_push_object(article_name, article_info);
}
page_no = pdf_doc_current_page_number();
pdf_doc_add_bead(article_name, NULL, page_no, &rect);
free(article_name);
return 0;
}
static int
spc_handler_pdfm_image (struct spc_env *spe, struct spc_arg *args)
{
struct spc_pdf_ *sd = &_pdf_stat;
int xobj_id;
char *ident = NULL;
pdf_obj *fspec;
transform_info ti;
load_options options = {1, 0, NULL};
skip_white(&args->curptr, args->endptr);
if (args->curptr[0] == '@') {
ident = parse_opt_ident(&args->curptr, args->endptr);
xobj_id = findresource(sd, ident);
if (xobj_id >= 0) {
spc_warn(spe, "Object reference name for image \"%s\" already used.", ident);
free(ident);
return -1;
}
}
/* 2015/12/29
* There should not be "page" and "pagebox" in read_dimtrns().
* It is for reading "dimensions" and "transformations" and "page" is
* completely unrelated.
*/
transform_info_clear(&ti);
if (spc_util_read_blahblah(spe, &ti,
&options.page_no, &options.bbox_type, args) < 0) {
spc_warn(spe, "Reading option field in pdf:image failed.");
free(ident);
return -1;
}
skip_white(&args->curptr, args->endptr);
fspec = parse_pdf_object(&args->curptr, args->endptr, NULL);
if (!fspec) {
spc_warn(spe, "Missing filename string for pdf:image.");
free(ident);
return -1;
} else if (!PDF_OBJ_STRINGTYPE(fspec)) {
spc_warn(spe, "Missing filename string for pdf:image.");
pdf_release_obj(fspec);
free(ident);
return -1;
}
skip_white(&args->curptr, args->endptr);
if (args->curptr < args->endptr) {
options.dict = parse_pdf_object(&args->curptr, args->endptr, NULL);
}
xobj_id = pdf_ximage_findresource(pdf_string_value(fspec), options);
if (xobj_id < 0) {
spc_warn(spe, "Could not find image resource...");
pdf_release_obj(fspec);
free(ident);
return -1;
}
if (!(ti.flags & INFO_DO_HIDE))
pdf_dev_put_image(xobj_id, &ti, spe->x_user, spe->y_user);
if (ident) {
addresource(sd, ident, xobj_id);
free(ident);
}
pdf_release_obj(fspec);
return 0;
}
/* Use do_names instead. */
static int
spc_handler_pdfm_dest (struct spc_env *spe, struct spc_arg *args)
{
pdf_obj *name, *array;
skip_white(&args->curptr, args->endptr);
name = parse_pdf_object(&args->curptr, args->endptr, NULL);
if (!name) {
spc_warn(spe, "PDF string expected for destination name but not found.");
return -1;
} else if (!PDF_OBJ_STRINGTYPE(name)) {
spc_warn(spe, "PDF string expected for destination name but invalid type.");
pdf_release_obj(name);
return -1;
}
array = parse_pdf_object(&args->curptr, args->endptr, NULL);
if (!array) {
spc_warn(spe, "No destination specified for pdf:dest.");
pdf_release_obj(name);
return -1;
} else if (!PDF_OBJ_ARRAYTYPE(array)) {
spc_warn(spe, "Destination not specified as an array object!");
pdf_release_obj(name);
pdf_release_obj(array);
return -1;
}
pdf_doc_add_names("Dests",
pdf_string_value (name),
pdf_string_length(name),
array);
pdf_release_obj(name);
return 0;
}
static int
spc_handler_pdfm_names (struct spc_env *spe, struct spc_arg *args)
{
pdf_obj *category, *key, *value, *tmp;
int i, size;
category = parse_pdf_object(&args->curptr, args->endptr, NULL);
if (!category) {
spc_warn(spe, "PDF name expected but not found.");
return -1;
} else if (!PDF_OBJ_NAMETYPE(category)) {
spc_warn(spe, "PDF name expected but not found.");
pdf_release_obj(category);
return -1;
}
tmp = parse_pdf_object(&args->curptr, args->endptr, NULL);
if (!tmp) {
spc_warn(spe, "PDF object expected but not found.");
pdf_release_obj(category);
return -1;
} else if (PDF_OBJ_ARRAYTYPE(tmp)) {
size = pdf_array_length(tmp);
if (size % 2 != 0) {
spc_warn(spe, "Array size not multiple of 2 for pdf:names.");
pdf_release_obj(category);
pdf_release_obj(tmp);
return -1;
}
for (i = 0; i < size / 2; i++) {
key = pdf_get_array(tmp, 2 * i);
value = pdf_get_array(tmp, 2 * i + 1);
if (!PDF_OBJ_STRINGTYPE(key)) {
spc_warn(spe, "Name tree key must be string.");
pdf_release_obj(category);
pdf_release_obj(tmp);
return -1;
} else if (pdf_doc_add_names(pdf_name_value(category),
pdf_string_value (key),
pdf_string_length(key),
pdf_link_obj(value)) < 0) {
spc_warn(spe, "Failed to add Name tree entry...");
pdf_release_obj(category);
pdf_release_obj(tmp);
return -1;
}
}
pdf_release_obj(tmp);
} else if (PDF_OBJ_STRINGTYPE(tmp)) {
key = tmp;
value = parse_pdf_object(&args->curptr, args->endptr, NULL);
if (!value) {
pdf_release_obj(category);
pdf_release_obj(key);
spc_warn(spe, "PDF object expected but not found.");
return -1;
}
if (pdf_doc_add_names(pdf_name_value(category),
pdf_string_value (key),
pdf_string_length(key),
value) < 0) {
spc_warn(spe, "Failed to add Name tree entry...");
pdf_release_obj(category);
pdf_release_obj(key);
return -1;
}
pdf_release_obj(key);
} else {
pdf_release_obj(tmp);
pdf_release_obj(category);
spc_warn(spe, "Invalid object type for pdf:names.");
return -1;
}
pdf_release_obj(category);
return 0;
}
static int
spc_handler_pdfm_docinfo (struct spc_env *spe, struct spc_arg *args)
{
struct spc_pdf_ *sd = &_pdf_stat;
pdf_obj *docinfo, *dict;
dict = parse_pdf_dict_with_tounicode(&args->curptr, args->endptr, &sd->cd);
if (!dict) {
spc_warn(spe, "Dictionary object expected but not found.");
return -1;
}
docinfo = pdf_doc_docinfo();
pdf_merge_dict(docinfo, dict);
pdf_release_obj(dict);
return 0;
}
static int
spc_handler_pdfm_docview (struct spc_env *spe, struct spc_arg *args)
{
struct spc_pdf_ *sd = &_pdf_stat;
pdf_obj *catalog, *dict;
pdf_obj *pref_old, *pref_add;
dict = parse_pdf_dict_with_tounicode(&args->curptr, args->endptr, &sd->cd);
if (!dict) {
spc_warn(spe, "Dictionary object expected but not found.");
return -1;
}
catalog = pdf_doc_catalog();
/* Avoid overriding whole ViewerPreferences */
pref_old = pdf_lookup_dict(catalog, "ViewerPreferences");
pref_add = pdf_lookup_dict(dict, "ViewerPreferences");
if (pref_old && pref_add) {
pdf_merge_dict (pref_old, pref_add);
pdf_remove_dict(dict, "ViewerPreferences");
}
pdf_merge_dict (catalog, dict);
pdf_release_obj(dict);
return 0;
}
static int
spc_handler_pdfm_close (struct spc_env *spe, struct spc_arg *args)
{
char *ident;
skip_white(&args->curptr, args->endptr);
ident = parse_opt_ident(&args->curptr, args->endptr);
if (ident) {
spc_flush_object(ident);
free(ident);
} else { /* Close all? */
spc_clear_objects();
}
return 0;
}
static int
spc_handler_pdfm_object (struct spc_env *spe, struct spc_arg *args)
{
char *ident;
pdf_obj *object;
skip_white(&args->curptr, args->endptr);
ident = parse_opt_ident(&args->curptr, args->endptr);
if (!ident) {
spc_warn(spe, "Could not find a object identifier.");
return -1;
}
object = parse_pdf_object(&args->curptr, args->endptr, NULL);
if (!object) {
spc_warn(spe, "Could not find an object definition for \"%s\".", ident);
free(ident);
return -1;
} else {
spc_push_object(ident, object);
}
free(ident);
return 0;
}
static int
spc_handler_pdfm_content (struct spc_env *spe, struct spc_arg *args)
{
int len = 0;
skip_white(&args->curptr, args->endptr);
if (args->curptr < args->endptr) {
pdf_tmatrix M;
pdf_setmatrix(&M, 1.0, 0.0, 0.0, 1.0, spe->x_user, spe->y_user);
work_buffer[len++] = ' ';
work_buffer[len++] = 'q';
work_buffer[len++] = ' ';
len += pdf_sprint_matrix(work_buffer + len, &M);
work_buffer[len++] = ' ';
work_buffer[len++] = 'c';
work_buffer[len++] = 'm';
work_buffer[len++] = ' ';
pdf_doc_add_page_content(work_buffer, len); /* op: q cm */
len = (int) (args->endptr - args->curptr);
pdf_doc_add_page_content(args->curptr, len); /* op: ANY */
pdf_doc_add_page_content(" Q", 2); /* op: Q */
}
args->curptr = args->endptr;
return 0;
}
static int
spc_handler_pdfm_literal (struct spc_env *spe, struct spc_arg *args)
{
int direct = 0;
skip_white(&args->curptr, args->endptr);
while (args->curptr < args->endptr) {
if (args->curptr + 7 <= args->endptr &&
strstartswith(args->curptr, "reverse")) {
args->curptr += 7;
dpx_warning("The special \"pdf:literal reverse ...\" is no longer supported.\nIgnore the \"reverse\" option.");
} else if (args->curptr + 6 <= args->endptr &&
strstartswith(args->curptr, "direct")) {
direct = 1;
args->curptr += 6;
} else {
break;
}
skip_white(&args->curptr, args->endptr);
}
if (args->curptr < args->endptr) {
pdf_tmatrix M;
if (!direct) {
M.a = M.d = 1.0; M.b = M.c = 0.0;
M.e = spe->x_user; M.f = spe->y_user;
pdf_dev_concat(&M);
}
pdf_doc_add_page_content(" ", 1); /* op: */
pdf_doc_add_page_content(args->curptr, (int) (args->endptr - args->curptr)); /* op: ANY */
if (!direct) {
M.e = -spe->x_user; M.f = -spe->y_user;
pdf_dev_concat(&M);
}
}
args->curptr = args->endptr;
return 0;
}
static int
spc_handler_pdfm_bcontent (struct spc_env *spe, struct spc_arg *args)
{
pdf_tmatrix M;
double xpos, ypos;
pdf_dev_gsave();
pdf_dev_get_coord(&xpos, &ypos);
pdf_setmatrix(&M, 1.0, 0.0, 0.0, 1.0, spe->x_user - xpos, spe->y_user - ypos);
pdf_dev_concat(&M);
pdf_dev_push_coord(spe->x_user, spe->y_user);
return 0;
}
static int
spc_handler_pdfm_econtent (struct spc_env *spe, struct spc_arg *args)
{
pdf_dev_pop_coord();
pdf_dev_grestore();
pdf_dev_reset_color(0);
return 0;
}
static int
spc_handler_pdfm_code (struct spc_env *spe, struct spc_arg *args)
{
skip_white(&args->curptr, args->endptr);
if (args->curptr < args->endptr) {
pdf_doc_add_page_content(" ", 1); /* op: */
pdf_doc_add_page_content(args->curptr, (int) (args->endptr - args->curptr)); /* op: ANY */
args->curptr = args->endptr;
}
return 0;
}
static int
spc_handler_pdfm_do_nothing (struct spc_env *spe, struct spc_arg *args)
{
args->curptr = args->endptr;
return 0;
}
#define STRING_STREAM 0
#define FILE_STREAM 1
static int
spc_handler_pdfm_stream_with_type (struct spc_env *spe, struct spc_arg *args, int type)
{
pdf_obj *fstream;
ssize_t nb_read;
char *ident, *instring, *fullname;
pdf_obj *tmp;
rust_input_handle_t *handle = NULL;
skip_white(&args->curptr, args->endptr);
ident = parse_opt_ident(&args->curptr, args->endptr);
if (!ident) {
spc_warn(spe, "Missing objname for pdf:(f)stream.");
return -1;
}
skip_white(&args->curptr, args->endptr);
tmp = parse_pdf_object(&args->curptr, args->endptr, NULL);
if (!tmp) {
spc_warn(spe, "Missing input string for pdf:(f)stream.");
free(ident);
return -1;
} else if (!PDF_OBJ_STRINGTYPE(tmp)) {
spc_warn(spe, "Invalid type of input string for pdf:(f)stream.");
pdf_release_obj(tmp);
free(ident);
return -1;
}
instring = pdf_string_value(tmp);
switch (type) {
case FILE_STREAM:
if (!instring) {
spc_warn(spe, "Missing filename for pdf:fstream.");
pdf_release_obj(tmp);
free(ident);
return -1;
}
fullname = NULL; /*kpse_find_pict(instring);*/
if (!fullname) {
spc_warn(spe, "File \"%s\" not found.", instring);
pdf_release_obj(tmp);
free(ident);
return -1;
}
handle = ttstub_input_open(fullname, TTIF_PICT, 0);
if (handle == NULL) {
spc_warn(spe, "Could not open file: %s", instring);
pdf_release_obj(tmp);
free(ident);
free(fullname);
return -1;
}
fstream = pdf_new_stream(STREAM_COMPRESS);
while ((nb_read =
ttstub_input_read(handle, work_buffer, WORK_BUFFER_SIZE)) > 0)
pdf_add_stream(fstream, work_buffer, nb_read);
ttstub_input_close(handle);
free(fullname);
break;
case STRING_STREAM:
fstream = pdf_new_stream(STREAM_COMPRESS);
if (instring)
pdf_add_stream(fstream, instring, strlen(instring));
break;
default:
pdf_release_obj(tmp);
free(ident);
return -1;
}
pdf_release_obj(tmp);
/*
* Optional dict.
*
* TODO: check Length, Filter...
*/
skip_white(&args->curptr, args->endptr);
if (args->curptr[0] == '<') {
pdf_obj *stream_dict;
stream_dict = pdf_stream_dict(fstream);
tmp = parse_pdf_dict(&args->curptr, args->endptr, NULL);
if (!tmp) {
spc_warn(spe, "Parsing dictionary failed.");
pdf_release_obj(fstream);
free(ident);
return -1;
}
if (pdf_lookup_dict(tmp, "Length")) {
pdf_remove_dict(tmp, "Length");
} else if (pdf_lookup_dict(tmp, "Filter")) {
pdf_remove_dict(tmp, "Filter");
}
pdf_merge_dict(stream_dict, tmp);
pdf_release_obj(tmp);
}
/* Users should explicitly close this. */
spc_push_object(ident, fstream);
free(ident);
return 0;
}
/*
* STREAM: Create a PDF stream object from an input string.
*
* pdf: stream @objname (input_string) [PDF_DICT]
*/
static int
spc_handler_pdfm_stream (struct spc_env *spe, struct spc_arg *args)
{
return spc_handler_pdfm_stream_with_type (spe, args, STRING_STREAM);
}
/*
* FSTREAM: Create a PDF stream object from an existing file.
*
* pdf: fstream @objname (filename) [PDF_DICT]
*/
static int
spc_handler_pdfm_fstream (struct spc_env *spe, struct spc_arg *args)
{
return spc_handler_pdfm_stream_with_type (spe, args, FILE_STREAM);
}
/* Grab page content as follows:
*
* Reference point = (x_user, y_user)
*
* Case 1. \special{pdf:bxobj @obj width WD height HT depth DP}
*
* Grab the box with the lower-left corner (x_user, y_user-DP)
* and the upper right corner (x_user+WD, y_user+HT).
*
* Case 2. \special{pdf:bxobj @obj bbox LLX LLY URX, URY}
*
* Grab the box with the lower-left corner (x_user+LLX, y_user+LLY)
* and the upper right corner (x_user+URX, y_user+URY).
*
* Note that scale, xscale, yscale, xoffset, yoffset options are ignored.
*/
static int
spc_handler_pdfm_bform (struct spc_env *spe, struct spc_arg *args)
{
int xobj_id;
char *ident;
pdf_rect cropbox;
transform_info ti;
skip_white(&args->curptr, args->endptr);
ident = parse_opt_ident(&args->curptr, args->endptr);
if (!ident) {
spc_warn(spe, "A form XObject must have name.");
return -1;
}
transform_info_clear(&ti);
if (spc_util_read_dimtrns(spe, &ti, args, 0) < 0) {
free(ident);
return -1;
}
/* A XForm with zero dimension results in a non-invertible transformation
* matrix. And it may result in unpredictable behaviour. It might be an
* error in Acrobat. Bounding box with zero dimension may cause division
* by zero.
*/
if (ti.flags & INFO_HAS_USER_BBOX) {
if (ti.bbox.urx - ti.bbox.llx == 0.0 ||
ti.bbox.ury - ti.bbox.lly == 0.0) {
spc_warn(spe, "Bounding box has a zero dimension.");
free(ident);
return -1;
}
cropbox.llx = ti.bbox.llx;
cropbox.lly = ti.bbox.lly;
cropbox.urx = ti.bbox.urx;
cropbox.ury = ti.bbox.ury;
} else {
if (ti.width == 0.0 ||
ti.depth + ti.height == 0.0) {
spc_warn(spe, "Bounding box has a zero dimension.");
free(ident);
return -1;
}
cropbox.llx = 0.0;
cropbox.lly = -ti.depth;
cropbox.urx = ti.width;
cropbox.ury = ti.height;
}
xobj_id = pdf_doc_begin_grabbing(ident, spe->x_user, spe->y_user, &cropbox);
if (xobj_id < 0) {
free(ident);
spc_warn(spe, "Couldn't start form object.");
return -1;
}
spc_push_object(ident, pdf_ximage_get_reference(xobj_id));
free(ident);
return 0;
}
/* An extra dictionary after exobj must be merged to the form dictionary,
* not resource dictionary.
* Please use pdf:put @resources (before pdf:exobj) instead.
*/
static int
spc_handler_pdfm_eform (struct spc_env *spe, struct spc_arg *args)
{
pdf_obj *attrib = NULL;
skip_white(&args->curptr, args->endptr);
if (args->curptr < args->endptr) {
attrib = parse_pdf_dict(&args->curptr, args->endptr, NULL);
if (attrib && !PDF_OBJ_DICTTYPE(attrib)) {
pdf_release_obj(attrib);
attrib = NULL;
}
}
pdf_doc_end_grabbing(attrib);
return 0;
}
/* Saved XObjects can be used as follows:
*
* Reference point = (x_user, y_user)
*
* Case 1. \special{pdf:uxobj @obj width WD height HT depth DP}
*
* Scale the XObject to fit in the box
* [x_user, y_user-DP, x_user+WD, y_user+HT].
*
* Case 2. \special{pdf:uxobj @obj xscale XS yscale YS}
*
* Scale the XObject with XS and YS. Note that width and xscale
* or height and yscale cannot be used together.
*
* Case 3. \special{pdf:bxobj @obj bbox LLX LLY URX, URY}
*
* Scale the XObject to fit in the box
* [x_user+LLX, y_user+LLY, x_user+URX, y_user+URY].
*
* Note that xoffset and yoffset moves the reference point where the
* lower-left corner of the XObject will be put.
*/
static int
spc_handler_pdfm_uxobj (struct spc_env *spe, struct spc_arg *args)
{
struct spc_pdf_ *sd = &_pdf_stat;
int xobj_id;
char *ident;
transform_info ti;
load_options options = {1, 0, NULL};
skip_white(&args->curptr, args->endptr);
ident = parse_opt_ident(&args->curptr, args->endptr);
if (!ident) {
spc_warn(spe, "No object identifier given.");
return -1;
}
transform_info_clear(&ti);
if (args->curptr < args->endptr) {
if (spc_util_read_dimtrns(spe, &ti, args, 0) < 0) {
free(ident);
return -1;
}
}
/* Dvipdfmx was suddenly changed to use file name to identify
* external images. We can't use ident to find image resource
* here.
*/
xobj_id = findresource(sd, ident);
if (xobj_id < 0) {
xobj_id = pdf_ximage_findresource(ident, options);
if (xobj_id < 0) {
spc_warn(spe, "Specified (image) object doesn't exist: %s", ident);
free(ident);
return -1;
}
}
pdf_dev_put_image(xobj_id, &ti, spe->x_user, spe->y_user);
free(ident);
return 0;
}
static int
spc_handler_pdfm_link (struct spc_env *spe, struct spc_arg *args)
{
return spc_resume_annot(spe);
}
static int
spc_handler_pdfm_nolink (struct spc_env *spe, struct spc_arg *args)
{
return spc_suspend_annot(spe);
}
/* Handled at BOP */
static int
spc_handler_pdfm_pagesize (struct spc_env *spe, struct spc_arg *args)
{
args->curptr = args->endptr;
return 0;
}
/* Please remove this.
* This should be handled before processing pages!
*/
static int
spc_handler_pdfm_bgcolor (struct spc_env *spe, struct spc_arg *args)
{
int error;
pdf_color colorspec;
error = spc_util_read_pdfcolor(spe, &colorspec, args, NULL);
if (error)
spc_warn(spe, "No valid color specified?");
else {
pdf_doc_set_bgcolor(&colorspec);
}
return error;
}
static int
spc_handler_pdfm_mapline (struct spc_env *spe, struct spc_arg *ap)
{
fontmap_rec *mrec;
char *map_name, opchr;
int error = 0;
static char buffer[1024];
const char *p;
char *q;
skip_white(&ap->curptr, ap->endptr);
if (ap->curptr >= ap->endptr) {
spc_warn(spe, "Empty mapline special?");
return -1;
}
opchr = ap->curptr[0];
if (opchr == '-' || opchr == '+')
ap->curptr++;
skip_white(&ap->curptr, ap->endptr);
switch (opchr) {
case '-':
map_name = parse_ident(&ap->curptr, ap->endptr);
if (map_name) {
pdf_remove_fontmap_record(map_name);
free(map_name);
} else {
spc_warn(spe, "Invalid fontmap line: Missing TFM name.");
error = -1;
}
break;
default:
p = ap->curptr;
q = buffer;
while (p < ap->endptr)
*q++ = *p++;
*q = '\0';
mrec = NEW(1, fontmap_rec);
pdf_init_fontmap_record(mrec);
error = pdf_read_fontmap_line(mrec, buffer, (int) (ap->endptr - ap->curptr), is_pdfm_mapline(buffer));
if (error)
spc_warn(spe, "Invalid fontmap line.");
else if (opchr == '+')
pdf_append_fontmap_record(mrec->map_name, mrec);
else
pdf_insert_fontmap_record(mrec->map_name, mrec);
pdf_clear_fontmap_record(mrec);
free(mrec);
break;
}
if (!error)
ap->curptr = ap->endptr;
return 0;
}
static int
spc_handler_pdfm_mapfile (struct spc_env *spe, struct spc_arg *args)
{
char *mapfile;
int mode, error = 0;
skip_white(&args->curptr, args->endptr);
if (args->curptr >= args->endptr)
return 0;
switch (args->curptr[0]) {
case '-':
mode = FONTMAP_RMODE_REMOVE;
args->curptr++;
break;
case '+':
mode = FONTMAP_RMODE_APPEND;
args->curptr++;
break;
default:
mode = FONTMAP_RMODE_REPLACE;
break;
}
mapfile = parse_val_ident(&args->curptr, args->endptr);
if (!mapfile) {
spc_warn(spe, "No fontmap file specified.");
return -1;
} else {
error = pdf_load_fontmap_file(mapfile, mode);
}
free(mapfile);
return error;
}
static int
spc_handler_pdfm_tounicode (struct spc_env *spe, struct spc_arg *args)
{
struct spc_pdf_ *sd = &_pdf_stat;
char *cmap_name;
/* First clear */
sd->cd.cmap_id = -1;
sd->cd.unescape_backslash = 0;
skip_white(&args->curptr, args->endptr);
if (args->curptr >= args->endptr) {
spc_warn(spe, "Missing CMap name for pdf:tounicode.");
return -1;
}
/* _FIXME_
* Any valid char allowed for PDF name object should be allowed here.
* The argument to this special should be a PDF name obejct.
* But it's too late to change this special.
*/
cmap_name = parse_ident(&args->curptr, args->endptr);
if (!cmap_name) {
spc_warn(spe, "Missing ToUnicode mapping name...");
return -1;
}
sd->cd.cmap_id = CMap_cache_find(cmap_name);
if (sd->cd.cmap_id < 0) {
spc_warn(spe, "Failed to load ToUnicode mapping: %s", cmap_name);
free(cmap_name);
return -1;
}
/* Shift-JIS like encoding may contain backslash in 2nd byte.
* WARNING: This will add nasty extension to PDF parser.
*/
if (sd->cd.cmap_id >= 0) {
if (strstr(cmap_name, "RKSJ") ||
strstr(cmap_name, "B5") ||
strstr(cmap_name, "GBK") ||
strstr(cmap_name, "KSC"))
sd->cd.unescape_backslash = 1;
}
free(cmap_name);
return 0;
}
static struct spc_handler pdfm_handlers[] = {
{"annotation", spc_handler_pdfm_annot},
{"annotate", spc_handler_pdfm_annot},
{"annot", spc_handler_pdfm_annot},
{"ann", spc_handler_pdfm_annot},
{"outline", spc_handler_pdfm_outline},
{"out", spc_handler_pdfm_outline},
{"article", spc_handler_pdfm_article},
{"art", spc_handler_pdfm_article},
{"bead", spc_handler_pdfm_bead},
{"thread", spc_handler_pdfm_bead},
{"destination", spc_handler_pdfm_dest},
{"dest", spc_handler_pdfm_dest},
{"object", spc_handler_pdfm_object},
{"obj", spc_handler_pdfm_object},
{"docinfo", spc_handler_pdfm_docinfo},
{"docview", spc_handler_pdfm_docview},
{"content", spc_handler_pdfm_content},
{"put", spc_handler_pdfm_put},
{"close", spc_handler_pdfm_close},
{"bop", spc_handler_pdfm_bop},
{"eop", spc_handler_pdfm_eop},
{"image", spc_handler_pdfm_image},
{"img", spc_handler_pdfm_image},
{"epdf", spc_handler_pdfm_image},
{"link", spc_handler_pdfm_link},
{"nolink", spc_handler_pdfm_nolink},
{"begincolor", spc_handler_pdfm_bcolor},
{"bcolor", spc_handler_pdfm_bcolor},
{"bc", spc_handler_pdfm_bcolor},
{"setcolor", spc_handler_pdfm_scolor},
{"scolor", spc_handler_pdfm_scolor},
{"sc", spc_handler_pdfm_scolor},
{"endcolor", spc_handler_pdfm_ecolor},
{"ecolor", spc_handler_pdfm_ecolor},
{"ec", spc_handler_pdfm_ecolor},
{"begingray", spc_handler_pdfm_bcolor},
{"bgray", spc_handler_pdfm_bcolor},
{"bg", spc_handler_pdfm_bcolor},
{"endgray", spc_handler_pdfm_ecolor},
{"egray", spc_handler_pdfm_ecolor},
{"eg", spc_handler_pdfm_ecolor},
{"bgcolor", spc_handler_pdfm_bgcolor},
{"bgc", spc_handler_pdfm_bgcolor},
{"bbc", spc_handler_pdfm_bgcolor},
{"bbg", spc_handler_pdfm_bgcolor},
{"pagesize", spc_handler_pdfm_pagesize},
{"bannot", spc_handler_pdfm_bann},
{"beginann", spc_handler_pdfm_bann},
{"bann", spc_handler_pdfm_bann},
{"eannot", spc_handler_pdfm_eann},
{"endann", spc_handler_pdfm_eann},
{"eann", spc_handler_pdfm_eann},
{"btrans", spc_handler_pdfm_btrans},
{"begintransform", spc_handler_pdfm_btrans},
{"begintrans", spc_handler_pdfm_btrans},
{"bt", spc_handler_pdfm_btrans},
{"etrans", spc_handler_pdfm_etrans},
{"endtransform", spc_handler_pdfm_etrans},
{"endtrans", spc_handler_pdfm_etrans},
{"et", spc_handler_pdfm_etrans},
{"bform", spc_handler_pdfm_bform},
{"beginxobj", spc_handler_pdfm_bform},
{"bxobj", spc_handler_pdfm_bform},
{"eform", spc_handler_pdfm_eform},
{"endxobj", spc_handler_pdfm_eform},
{"exobj", spc_handler_pdfm_eform},
{"usexobj", spc_handler_pdfm_uxobj},
{"uxobj", spc_handler_pdfm_uxobj},
{"tounicode", spc_handler_pdfm_tounicode},
{"literal", spc_handler_pdfm_literal},
{"stream", spc_handler_pdfm_stream},
{"fstream", spc_handler_pdfm_fstream},
{"names", spc_handler_pdfm_names},
{"mapline", spc_handler_pdfm_mapline},
{"mapfile", spc_handler_pdfm_mapfile},
{"bcontent", spc_handler_pdfm_bcontent},
{"econtent", spc_handler_pdfm_econtent},
{"code", spc_handler_pdfm_code},
{"minorversion", spc_handler_pdfm_do_nothing},
{"encrypt", spc_handler_pdfm_do_nothing},
};
bool
spc_pdfm_check_special (const char *buf, int len)
{
const char *p, *endptr;
p = buf;
endptr = p + len;
skip_white(&p, endptr);
if (p + strlen("pdf:") <= endptr &&
!memcmp(p, "pdf:", strlen("pdf:"))) {
return true;
}
return false;
}
int
spc_pdfm_setup_handler (struct spc_handler *sph,
struct spc_env *spe, struct spc_arg *ap)
{
int error = -1;
size_t i;
char *q;
assert(sph && spe && ap);
skip_white(&ap->curptr, ap->endptr);
if (ap->curptr + strlen("pdf:") >= ap->endptr ||
memcmp(ap->curptr, "pdf:", strlen("pdf:"))) {
spc_warn(spe, "Not pdf: special???");
return -1;
}
ap->curptr += strlen("pdf:");
skip_white(&ap->curptr, ap->endptr);
q = parse_c_ident(&ap->curptr, ap->endptr);
if (q) {
for (i = 0;
i < sizeof(pdfm_handlers) / sizeof(struct spc_handler); i++) {
if (streq_ptr(q, pdfm_handlers[i].key)) {
ap->command = pdfm_handlers[i].key;
sph->key = "pdf:";
sph->exec = pdfm_handlers[i].exec;
skip_white(&ap->curptr, ap->endptr);
error = 0;
break;
}
}
free(q);
}
return error;
}
|
fmgoncalves/tectonic
|
tectonic/dpx-pdfcolor.h
|
/* This is dvipdfmx, an eXtended version of dvipdfm by <NAME>.
Copyright (C) 2002-2016 by <NAME> and <NAME>,
the dvipdfmx project team.
Copyright (C) 1998, 1999 by <NAME> <<EMAIL>>
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.
*/
#ifndef _PDF_COLOR_H_
#define _PDF_COLOR_H_
#include "dpx-core.h"
#include <stdbool.h>
#include "dpx-pdfobj.h"
#define PDF_COLORSPACE_TYPE_DEVICECMYK -4
#define PDF_COLORSPACE_TYPE_DEVICERGB -3
#define PDF_COLORSPACE_TYPE_SPOT -2
#define PDF_COLORSPACE_TYPE_DEVICEGRAY -1
#define PDF_COLORSPACE_TYPE_INVALID 0
#define PDF_COLORSPACE_TYPE_CALGRAY 1
#define PDF_COLORSPACE_TYPE_CIELAB 2
#define PDF_COLORSPACE_TYPE_CALRGB 3
#define PDF_COLORSPACE_TYPE_ICCBASED 4
#define PDF_COLORSPACE_TYPE_CMYK PDF_COLORSPACE_TYPE_DEVICECMYK
#define PDF_COLORSPACE_TYPE_RGB PDF_COLORSPACE_TYPE_DEVICERGB
#define PDF_COLORSPACE_TYPE_GRAY PDF_COLORSPACE_TYPE_DEVICEGRAY
#define PDF_COLOR_COMPONENT_MAX 4
typedef struct
{
int num_components;
char* spot_color_name;
double values[PDF_COLOR_COMPONENT_MAX];
} pdf_color;
void pdf_color_set_verbose (int level);
int pdf_color_rgbcolor (pdf_color *color,
double r, double g, double b);
int pdf_color_cmykcolor (pdf_color *color,
double c, double m, double y, double k);
int pdf_color_graycolor (pdf_color *color, double g);
int pdf_color_spotcolor (pdf_color *color, char* color_name, double c);
void pdf_color_copycolor (pdf_color *color1, const pdf_color *color2);
#define pdf_color_black(c) pdf_color_graycolor(c, 0.0);
#define pdf_color_white(c) pdf_color_graycolor(c, 1.0);
void pdf_color_brighten_color (pdf_color *dst, const pdf_color *src, double f);
int pdf_color_type (const pdf_color *color);
int pdf_color_compare (const pdf_color *color1, const pdf_color *color2);
int pdf_color_to_string (const pdf_color *color, char *buffer, char mask);
bool pdf_color_is_white (const pdf_color *color);
bool pdf_color_is_valid (const pdf_color *color);
/* Not check size */
pdf_obj *iccp_get_rendering_intent (const void *profile, int proflen);
int iccp_check_colorspace (int colortype,
const void *profile, int proflen);
/* returns colorspace ID */
int iccp_load_profile (const char *ident,
const void *profile, int proflen);
void pdf_init_colors (void);
void pdf_close_colors (void);
pdf_obj *pdf_get_colorspace_reference (int cspc_id);
/* Color special
* See remark in spc_color.c.
*/
void pdf_color_set (pdf_color *sc, pdf_color *fc);
void pdf_color_push (pdf_color *sc, pdf_color *fc);
void pdf_color_pop (void);
/* Color stack
*/
void pdf_color_clear_stack (void);
void pdf_color_get_current (pdf_color **sc, pdf_color **fc);
#endif /* _PDF_COLOR_H_ */
|
fmgoncalves/tectonic
|
tectonic/dpx-cmap_read.c
|
/* This is dvipdfmx, an eXtended version of dvipdfm by <NAME>.
Copyright (C) 2002-2016 by <NAME> and <NAME>,
the dvipdfmx project team.
Copyright (C) 1998, 1999 by <NAME> <<EMAIL>>
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 "dpx-cmap_read.h"
#include <assert.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dpx-cid.h"
#include "dpx-cmap.h"
#include "dpx-dpxutil.h"
#include "dpx-error.h"
#include "dpx-mem.h"
#include "dpx-pst.h"
static int __verbose = 0;
#define CMAP_PARSE_DEBUG_STR "CMap_parse:"
#define CMAP_PARSE_DEBUG 3
typedef struct {
unsigned char *cursor;
unsigned char *endptr;
unsigned char *buf;
size_t max;
rust_input_handle_t handle;
size_t unread;
} ifreader;
static ifreader *ifreader_create (rust_input_handle_t handle, size_t remain, size_t bufsize);
static size_t ifreader_read (ifreader *reader, size_t size);
static void ifreader_destroy (ifreader *reader);
static ifreader *
ifreader_create (rust_input_handle_t handle, size_t size, size_t bufsize)
{
ifreader *reader;
reader = NEW(1, ifreader);
reader->buf = NEW(bufsize+1, unsigned char);
reader->max = bufsize;
reader->handle = handle;
reader->unread = size;
reader->cursor = reader->endptr = reader->buf;
*reader->endptr = 0;
return reader;
}
static void
ifreader_destroy (ifreader *reader)
{
assert(reader);
free(reader->buf);
free(reader);
}
static size_t
ifreader_read (ifreader *reader, size_t size)
{
size_t bytesread = 0, bytesrem = 0;
assert(reader);
bytesrem = (size_t) reader->endptr - (size_t) reader->cursor;
if (size > reader->max) {
if (__verbose)
dpx_message("\nExtending buffer (%"PRIuZ" bytes)...\n", size);
reader->buf = RENEW(reader->buf, size+1, unsigned char);
reader->max = size;
}
if (reader->unread > 0 && bytesrem < size) {
bytesread = MIN(reader->max - bytesrem, reader->unread);
memmove(reader->buf, reader->cursor, bytesrem);
reader->cursor = reader->buf;
reader->endptr = reader->buf + bytesrem;
if (ttstub_input_read(reader->handle, (char *) reader->endptr, bytesread) != bytesread)
_tt_abort("Reading file failed.");
reader->endptr += bytesread;
reader->unread -= bytesread;
if (__verbose)
dpx_message("Reading more %"PRIuZ" bytes (%"PRIuZ" bytes remains in buffer)...\n", bytesread, bytesrem);
}
*reader->endptr = 0;
return bytesread + bytesrem;
}
static int check_next_token (ifreader *input, const char *key);
static int get_coderange (ifreader *input, unsigned char *codeLo, unsigned char *codeHi, int *dim, int maxlen);
static int handle_codearray (CMap *cmap, ifreader *input, unsigned char *codeLo, int dim, int count);
static int do_codespacerange (CMap *cmap, ifreader *input, int count);
static int do_notdefrange (CMap *cmap, ifreader *input, int count);
static int do_bfrange (CMap *cmap, ifreader *input, int count);
static int do_cidrange (CMap *cmap, ifreader *input, int count);
static int do_notdefchar (CMap *cmap, ifreader *input, int count);
static int do_bfchar (CMap *cmap, ifreader *input, int count);
static int do_cidchar (CMap *cmap, ifreader *input, int count);
#define TOKEN_LEN_MAX 127
static int
check_next_token (ifreader *input, const char *key)
{
int cmp;
pst_obj *token;
char *str;
if (ifreader_read(input, strlen(key)) == 0)
return -1;
if ((token = pst_get_token(&(input->cursor), input->endptr)) == NULL)
return -1;
str = (char *) pst_getSV(token);
cmp = strcmp(str, key) ? -1 : 0;
free(str);
pst_release_obj(token);
return cmp;
}
static int
get_coderange (ifreader *input,
unsigned char *codeLo, unsigned char *codeHi, int *dim, int maxlen)
{
pst_obj *tok1, *tok2;
int dim1, dim2;
if ((tok1 = pst_get_token(&(input->cursor), input->endptr)) == NULL)
return -1;
if ((tok2 = pst_get_token(&(input->cursor), input->endptr)) == NULL) {
pst_release_obj(tok1);
return -1;
}
if (!PST_STRINGTYPE(tok1) || !PST_STRINGTYPE(tok2)) {
pst_release_obj(tok1);
pst_release_obj(tok2);
return -1;
}
dim1 = pst_length_of(tok1);
dim2 = pst_length_of(tok2);
if (dim1 != dim2 || dim1 > maxlen) {
pst_release_obj(tok1);
pst_release_obj(tok2);
return -1;
}
memcpy(codeLo, pst_data_ptr(tok1), dim1);
memcpy(codeHi, pst_data_ptr(tok2), dim2);
pst_release_obj(tok1);
pst_release_obj(tok2);
*dim = dim1;
return 0;
}
static int
do_codespacerange (CMap *cmap, ifreader *input, int count)
{
unsigned char codeLo[TOKEN_LEN_MAX], codeHi[TOKEN_LEN_MAX];
int dim;
while (count-- > 0) {
if (get_coderange(input, codeLo, codeHi, &dim, TOKEN_LEN_MAX) < 0)
return -1;
CMap_add_codespacerange(cmap, codeLo, codeHi, dim);
}
return check_next_token(input, "endcodespacerange");
}
/*
* bfrange
* <codeLo> <codeHi> [destCode1 destCode2 ...]
*/
static int
handle_codearray (CMap *cmap, ifreader *input, unsigned char *codeLo, int dim, int count)
{
pst_obj *tok = NULL;
if (dim < 1)
_tt_abort("Invalid code range.");
while (count-- > 0) {
if ((tok = pst_get_token(&(input->cursor), input->endptr)) == NULL)
return -1;
else if (PST_STRINGTYPE(tok)) {
CMap_add_bfchar(cmap, codeLo, dim, (unsigned char *) pst_data_ptr(tok), pst_length_of(tok));
} else if (PST_MARKTYPE(tok) || !PST_NAMETYPE(tok))
_tt_abort("%s: Invalid CMap mapping record.", CMAP_PARSE_DEBUG_STR);
else
_tt_abort("%s: Mapping to charName not supported.", CMAP_PARSE_DEBUG_STR);
pst_release_obj(tok);
codeLo[dim-1] += 1;
}
return check_next_token(input, "]");
}
static int
do_notdefrange (CMap *cmap, ifreader *input, int count)
{
pst_obj *tok;
unsigned char codeLo[TOKEN_LEN_MAX], codeHi[TOKEN_LEN_MAX];
int dstCID;
int dim;
while (count-- > 0) {
if (ifreader_read(input, TOKEN_LEN_MAX*3) == 0)
return -1;
if (get_coderange(input, codeLo, codeHi, &dim, TOKEN_LEN_MAX) < 0 ||
(tok = pst_get_token(&(input->cursor), input->endptr)) == NULL)
return -1;
if (PST_INTEGERTYPE(tok)) {
dstCID = pst_getIV(tok);
if (dstCID >= 0 && dstCID <= CID_MAX)
CMap_add_notdefrange(cmap, codeLo, codeHi, dim, (CID) dstCID);
} else
dpx_warning("%s: Invalid CMap mapping record. (ignored)", CMAP_PARSE_DEBUG_STR);
pst_release_obj(tok);
}
return check_next_token(input, "endnotdefrange");
}
static int
do_bfrange (CMap *cmap, ifreader *input, int count)
{
pst_obj *tok;
unsigned char codeLo[TOKEN_LEN_MAX], codeHi[TOKEN_LEN_MAX];
int srcdim;
while (count-- > 0) {
if (ifreader_read(input, TOKEN_LEN_MAX*3) == 0)
return -1;
if (get_coderange(input, codeLo, codeHi, &srcdim, TOKEN_LEN_MAX) < 0 ||
(tok = pst_get_token(&(input->cursor), input->endptr)) == NULL)
return -1;
if (PST_STRINGTYPE(tok)) {
CMap_add_bfrange(cmap, codeLo, codeHi, srcdim,
(unsigned char *) pst_data_ptr(tok), pst_length_of(tok));
} else if (PST_MARKTYPE(tok)) {
if (handle_codearray(cmap, input, codeLo, srcdim,
codeHi[srcdim-1] - codeLo[srcdim-1] + 1) < 0) {
pst_release_obj(tok);
return -1;
}
} else
dpx_warning("%s: Invalid CMap mapping record. (ignored)", CMAP_PARSE_DEBUG_STR);
pst_release_obj(tok);
}
return check_next_token(input, "endbfrange");
}
static int
do_cidrange (CMap *cmap, ifreader *input, int count)
{
pst_obj *tok;
unsigned char codeLo[TOKEN_LEN_MAX], codeHi[TOKEN_LEN_MAX];
int dstCID;
int dim;
while (count-- > 0) {
if (ifreader_read(input, TOKEN_LEN_MAX*3) == 0)
return -1;
if (get_coderange(input, codeLo, codeHi, &dim, TOKEN_LEN_MAX) < 0 ||
(tok = pst_get_token(&(input->cursor), input->endptr)) == NULL)
return -1;
if (PST_INTEGERTYPE(tok)) {
dstCID = pst_getIV(tok);
if (dstCID >= 0 && dstCID <= CID_MAX)
CMap_add_cidrange(cmap, codeLo, codeHi, dim, (CID) dstCID);
} else
dpx_warning("%s: Invalid CMap mapping record. (ignored)", CMAP_PARSE_DEBUG_STR);
pst_release_obj(tok);
}
return check_next_token(input, "endcidrange");
}
static int
do_notdefchar (CMap *cmap, ifreader *input, int count)
{
pst_obj *tok1, *tok2;
int dstCID;
while (count-- > 0) {
if (ifreader_read(input, TOKEN_LEN_MAX*2) == 0)
return -1;
if ((tok1 = pst_get_token(&(input->cursor), input->endptr)) == NULL)
return -1;
if ((tok2 = pst_get_token(&(input->cursor), input->endptr)) == NULL) {
pst_release_obj(tok1);
return -1;
}
if (PST_STRINGTYPE(tok1) && PST_INTEGERTYPE(tok2)) {
dstCID = pst_getIV(tok2);
if (dstCID >= 0 && dstCID <= CID_MAX)
CMap_add_notdefchar(cmap, pst_data_ptr(tok1), pst_length_of(tok1), (CID) dstCID);
} else
dpx_warning("%s: Invalid CMap mapping record. (ignored)", CMAP_PARSE_DEBUG_STR);
pst_release_obj(tok1);
pst_release_obj(tok2);
}
return check_next_token(input, "endnotdefchar");
}
static int
do_bfchar (CMap *cmap, ifreader *input, int count)
{
pst_obj *tok1, *tok2;
while (count-- > 0) {
if (ifreader_read(input, TOKEN_LEN_MAX*2) == 0)
return -1;
if ((tok1 = pst_get_token(&(input->cursor), input->endptr)) == NULL)
return -1;
if ((tok2 = pst_get_token(&(input->cursor), input->endptr)) == NULL) {
pst_release_obj(tok1);
return -1;
}
/* We only support single CID font as descendant font, charName should not come here. */
if (PST_STRINGTYPE(tok1) && PST_STRINGTYPE(tok2)) {
CMap_add_bfchar(cmap,
(unsigned char *) pst_data_ptr(tok1), pst_length_of(tok1),
(unsigned char *) pst_data_ptr(tok2), pst_length_of(tok2));
} else if (PST_NAMETYPE(tok2))
_tt_abort("%s: Mapping to charName not supported.", CMAP_PARSE_DEBUG_STR);
else
dpx_warning("%s: Invalid CMap mapping record. (ignored)", CMAP_PARSE_DEBUG_STR);
pst_release_obj(tok1);
pst_release_obj(tok2);
}
return check_next_token(input, "endbfchar");
}
static int
do_cidchar (CMap *cmap, ifreader *input, int count)
{
pst_obj *tok1, *tok2;
int dstCID;
while (count-- > 0) {
if (ifreader_read(input, TOKEN_LEN_MAX*2) == 0)
return -1;
if ((tok1 = pst_get_token(&(input->cursor), input->endptr)) == NULL)
return -1;
if ((tok2 = pst_get_token(&(input->cursor), input->endptr)) == NULL) {
pst_release_obj(tok1);
return -1;
}
if (PST_STRINGTYPE(tok1) && PST_INTEGERTYPE(tok2)) {
dstCID = pst_getIV(tok2);
if (dstCID >= 0 && dstCID <= CID_MAX)
CMap_add_cidchar(cmap, pst_data_ptr(tok1), pst_length_of(tok1), (CID) dstCID);
} else
dpx_warning("%s: Invalid CMap mapping record. (ignored)", CMAP_PARSE_DEBUG_STR);
pst_release_obj(tok1);
pst_release_obj(tok2);
}
return check_next_token(input, "endcidchar");
}
#define MATCH_NAME(t,n) (PST_NAMETYPE((t)) && !memcmp(pst_data_ptr((t)),(n),strlen((n))))
#define MATCH_OP(t,n) (PST_UNKNOWNTYPE((t)) && !memcmp(pst_data_ptr((t)),(n),strlen((n))))
static int
do_cidsysteminfo (CMap *cmap, ifreader *input)
{
pst_obj *tok1, *tok2;
CIDSysInfo csi = {NULL, NULL, -1};
int simpledict = 0;
int error = 0;
ifreader_read(input, TOKEN_LEN_MAX*2);
/*
* Assuming /CIDSystemInfo 3 dict dup begin .... end def
* or /CIDSystemInfo << ... >> def
*/
while ((tok1 = pst_get_token(&(input->cursor), input->endptr)) != NULL) {
if (PST_MARKTYPE(tok1)) {
simpledict = 1;
pst_release_obj(tok1);
break;
} else if (MATCH_OP(tok1, "begin")) {
simpledict = 0;
pst_release_obj(tok1);
break;
} else {
pst_release_obj(tok1);
/* continue */
}
}
tok1 = tok2 = NULL;
while (!error &&
(tok1 = pst_get_token(&(input->cursor), input->endptr)) != NULL) {
if (MATCH_OP(tok1, ">>") && simpledict) {
pst_release_obj(tok1);
break;
} else if (MATCH_OP(tok1, "end") && !simpledict) {
pst_release_obj(tok1);
break;
} else if (MATCH_NAME(tok1, "Registry") &&
(tok2 = pst_get_token(&(input->cursor), input->endptr)) != NULL) {
if (!PST_STRINGTYPE(tok2))
error = -1;
else if (!simpledict &&
check_next_token(input, "def"))
error = -1;
if (!error)
csi.registry = (char *) pst_getSV(tok2);
} else if (MATCH_NAME(tok1, "Ordering") &&
(tok2 = pst_get_token(&(input->cursor), input->endptr)) != NULL) {
if (!PST_STRINGTYPE(tok2))
error = -1;
else if (!simpledict &&
check_next_token(input, "def"))
error = -1;
if (!error)
csi.ordering = (char *) pst_getSV(tok2);
} else if (MATCH_NAME(tok1, "Supplement") &&
(tok2 = pst_get_token(&(input->cursor), input->endptr)) != NULL) {
if (!PST_INTEGERTYPE(tok2))
error = -1;
else if (!simpledict &&
check_next_token(input, "def"))
error = -1;
if (!error)
csi.supplement = pst_getIV(tok2);
}
if (tok2)
pst_release_obj(tok2);
if (tok1)
pst_release_obj(tok1);
tok1 = tok2 = NULL;
}
if (!error &&
check_next_token(input, "def"))
error = -1;
if (!error &&
csi.registry && csi.ordering &&
csi.supplement >= 0) {
CMap_set_CIDSysInfo(cmap, &csi);
}
free(csi.registry);
free(csi.ordering);
return error;
}
#define INPUT_BUF_SIZE 4096
#define CMAP_SIG_MAX 64
int
CMap_parse_check_sig (rust_input_handle_t handle)
{
int result = -1;
char sig[CMAP_SIG_MAX+1];
if (handle == NULL)
return -1;
ttstub_input_seek(handle, 0, SEEK_SET);
if (ttstub_input_read(handle, sig, CMAP_SIG_MAX) != CMAP_SIG_MAX)
result = -1;
else {
sig[CMAP_SIG_MAX] = 0;
if (!strstartswith(sig, "%!PS"))
result = -1;
else if (strstr(sig+4, "Resource-CMap"))
result = 0;
}
ttstub_input_seek (handle, 0, SEEK_SET);
return result;
}
int
CMap_parse (CMap *cmap, rust_input_handle_t handle)
{
pst_obj *tok1, *tok2;
ifreader *input;
int status = 0, tmpint = -1;
assert(cmap && handle);
input = ifreader_create(handle, ttstub_input_get_size(handle), INPUT_BUF_SIZE-1);
while (status >= 0) {
tok1 = tok2 = NULL;
ifreader_read(input, INPUT_BUF_SIZE/2);
tok1 = pst_get_token(&(input->cursor), input->endptr);
if (tok1 == NULL)
break;
else if (MATCH_NAME(tok1, "CMapName")) {
if ((tok2 = pst_get_token(&(input->cursor), input->endptr)) == NULL ||
!(PST_NAMETYPE(tok2) || PST_STRINGTYPE(tok2)) ||
check_next_token(input, "def") < 0)
status = -1;
else
CMap_set_name(cmap, pst_data_ptr(tok2));
} else if (MATCH_NAME(tok1, "CMapType")) {
if ((tok2 = pst_get_token(&(input->cursor), input->endptr)) == NULL ||
!PST_INTEGERTYPE(tok2) ||
check_next_token(input, "def") < 0)
status = -1;
else
CMap_set_type(cmap, pst_getIV(tok2));
} else if (MATCH_NAME(tok1, "WMode")) {
if ((tok2 = pst_get_token(&(input->cursor), input->endptr)) == NULL ||
!PST_INTEGERTYPE(tok2) ||
check_next_token(input, "def") < 0)
status = -1;
else
CMap_set_wmode(cmap, pst_getIV(tok2));
} else if (MATCH_NAME(tok1, "CIDSystemInfo")) {
status = do_cidsysteminfo(cmap, input);
} else if (MATCH_NAME(tok1, "Version") ||
MATCH_NAME(tok1, "UIDOffset") ||
MATCH_NAME(tok1, "XUID")) {
/* Ignore */
} else if (PST_NAMETYPE(tok1)) {
/* Possibly usecmap comes next */
if ((tok2 = pst_get_token(&(input->cursor), input->endptr)) != NULL &&
MATCH_OP(tok2, "usecmap")) {
int id;
CMap *ucmap;
id = CMap_cache_find(pst_data_ptr(tok1));
if (id < 0)
status = -1;
else {
ucmap = CMap_cache_get(id);
CMap_set_usecmap(cmap, ucmap);
}
}
} else if (MATCH_OP(tok1, "begincodespacerange")) {
status = do_codespacerange(cmap, input, tmpint);
} else if (MATCH_OP(tok1, "beginnotdefrange")) {
status = do_notdefrange(cmap, input, tmpint);
} else if (MATCH_OP(tok1, "beginnotdefchar")) {
status = do_notdefchar(cmap, input, tmpint);
} else if (MATCH_OP(tok1, "beginbfrange")) {
status = do_bfrange(cmap, input, tmpint);
} else if (MATCH_OP(tok1, "beginbfchar")) {
status = do_bfchar(cmap, input, tmpint);
} else if (MATCH_OP(tok1, "begincidrange")) {
status = do_cidrange(cmap, input, tmpint);
} else if (MATCH_OP(tok1, "begincidchar")) {
status = do_cidchar(cmap, input, tmpint);
} else if (PST_INTEGERTYPE(tok1)) {
tmpint = pst_getIV(tok1);
} /* else Simply ignore */
if (tok1)
pst_release_obj(tok1);
if (tok2)
pst_release_obj(tok2);
}
ifreader_destroy(input);
return (status < 0) ? -1 : CMap_is_valid(cmap);
}
|
fmgoncalves/tectonic
|
tectonic/dpx-pdfdev.h
|
<reponame>fmgoncalves/tectonic
/* This is dvipdfmx, an eXtended version of dvipdfm by <NAME>.
Copyright (C) 2002-2016 by <NAME> and <NAME>,
the dvipdfmx project team.
Copyright (C) 1998, 1999 by <NAME> <<EMAIL>>
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.
*/
#ifndef _PDFDEV_H_
#define _PDFDEV_H_
#include "dpx-core.h"
#include <stddef.h>
#include <stdint.h>
#include "dpx-numbers.h"
#include "dpx-pdfcolor.h"
#include "dpx-pdfobj.h"
typedef int spt_t;
typedef struct pdf_tmatrix
{
double a, b, c, d, e, f;
} pdf_tmatrix;
typedef struct pdf_rect
{
double llx, lly, urx, ury;
} pdf_rect;
typedef struct pdf_coord
{
double x, y;
} pdf_coord;
/* The name transform_info is misleading.
* I'll put this here for a moment...
*/
typedef struct
{
/* Physical dimensions
*
* If those values are given, images will be scaled
* and/or shifted to fit within a box described by
* those values.
*/
double width;
double height;
double depth;
pdf_tmatrix matrix; /* transform matrix */
pdf_rect bbox; /* user_bbox */
int flags;
} transform_info;
#define INFO_HAS_USER_BBOX (1 << 0)
#define INFO_HAS_WIDTH (1 << 1)
#define INFO_HAS_HEIGHT (1 << 2)
#define INFO_DO_CLIP (1 << 3)
#define INFO_DO_HIDE (1 << 4)
void transform_info_clear (transform_info *info);
void pdf_dev_set_verbose (int level);
void pdf_dev_reset_global_state (void);
/* Not in spt_t. */
int pdf_sprint_matrix (char *buf, const pdf_tmatrix *p);
int pdf_sprint_rect (char *buf, const pdf_rect *p);
int pdf_sprint_coord (char *buf, const pdf_coord *p);
int pdf_sprint_length (char *buf, double value);
int pdf_sprint_number (char *buf, double value);
/* unit_conv: multiplier for input unit (spt_t) to bp conversion.
* precision: How many fractional digits preserved in output (not real
* accuracy control).
* is_bw: Ignore color related special instructions.
*/
void pdf_init_device (double unit_conv, int precision, int is_bw);
void pdf_close_device (void);
/* returns 1.0/unit_conv */
double dev_unit_dviunit (void);
/* Draw texts and rules:
*
* xpos, ypos, width, and height are all fixed-point numbers
* converted to big-points by multiplying unit_conv (dvi2pts).
* They must be position in the user space.
*
* ctype:
* 0 - input string is in multi-byte encoding.
* 1 - input string is in 8-bit encoding.
* 2 - input string is in 16-bit encoding.
*/
void pdf_dev_set_string (spt_t xpos, spt_t ypos,
const void *instr_ptr, size_t instr_len,
spt_t text_width,
int font_id, int ctype);
void pdf_dev_set_rule (spt_t xpos, spt_t ypos,
spt_t width, spt_t height);
/* Place XObject */
int pdf_dev_put_image (int xobj_id,
transform_info *p, double ref_x, double ref_y);
/* The design_size and ptsize required by PK font support...
*/
int pdf_dev_locate_font (const char *font_name, spt_t ptsize);
/* The following two routines are NOT WORKING.
* Dvipdfmx doesn't manage gstate well..
*/
/* Always returns 1.0, please rename this. */
double pdf_dev_scale (void);
/* Access text state parameters. */
int pdf_dev_get_font_wmode (int font_id); /* ps: special support want this (pTeX). */
/* Text composition (direction) mode
* This affects only when auto_rotate is enabled.
*/
int pdf_dev_get_dirmode (void);
void pdf_dev_set_dirmode (int dir_mode);
/* Set rect to rectangle in device space.
* Unit conversion spt_t to bp and transformation applied within it.
*/
void pdf_dev_set_rect (pdf_rect *rect,
spt_t x_pos, spt_t y_pos,
spt_t width, spt_t height, spt_t depth);
/* Accessor to various device parameters.
*/
#define PDF_DEV_PARAM_AUTOROTATE 1
#define PDF_DEV_PARAM_COLORMODE 2
int pdf_dev_get_param (int param_type);
void pdf_dev_set_param (int param_type, int value);
/* Text composition mode is ignored (always same as font's
* writing mode) and glyph rotation is not enabled if
* auto_rotate is unset.
*/
#define pdf_dev_set_autorotate(v) pdf_dev_set_param(PDF_DEV_PARAM_AUTOROTATE, (v))
/*
* For pdf_doc, pdf_draw and others.
*/
/* Force reselecting font and color:
* XFrom (content grabbing) and Metapost support want them.
*/
void pdf_dev_reset_fonts (int newpage);
void pdf_dev_reset_color (int force);
/* Initialization of transformation matrix with M and others.
* They are called within pdf_doc_begin_page() and pdf_doc_end_page().
*/
void pdf_dev_bop (const pdf_tmatrix *M);
void pdf_dev_eop (void);
/* Text is normal and line art is not normal in dvipdfmx. So we don't have
* begin_text (BT in PDF) and end_text (ET), but instead we have graphics_mode()
* to terminate text section. pdf_dev_flushpath() and others call this.
*/
void graphics_mode (void);
void pdf_dev_get_coord(double *xpos, double *ypos);
void pdf_dev_push_coord(double xpos, double ypos);
void pdf_dev_pop_coord(void);
void pdf_dev_begin_actualtext (uint16_t *unicodes, int len);
void pdf_dev_end_actualtext (void);
#endif /* _PDFDEV_H_ */
|
fmgoncalves/tectonic
|
tectonic/xetex-shipout.c
|
/* Copyright 2016-2018 The Tectonic Project
* Licensed under the MIT License.
*/
#include "xetex-core.h"
#include "xetex-xetexd.h"
#include "xetex-synctex.h"
#include "core-bridge.h"
#define DVI_BUF_SIZE 16384
#define HALF_BUF 8192
#define FNT_NUM_0 171 /* DVI code */
static rust_output_handle_t dvi_file;
static str_number output_file_name;
static eight_bits *dvi_buf = NULL;
static int32_t dvi_limit;
static int32_t g;
static int32_t lq, lr;
static int32_t dvi_ptr;
static int32_t dvi_offset;
static int32_t dvi_gone;
static int32_t down_ptr, right_ptr;
static scaled_t dvi_h, dvi_v;
static internal_font_number dvi_f;
static int32_t cur_s;
static void hlist_out(void);
static void vlist_out(void);
static int32_t reverse(int32_t this_box, int32_t t, scaled_t * cur_g, double * cur_glue);
static void dvi_native_font_def(internal_font_number f);
static void movement(scaled_t w, eight_bits o);
static void prune_movements(int32_t l);
static void special_out(int32_t p);
static void write_out(int32_t p);
static void pic_out(int32_t p);
static void write_to_dvi(int32_t a, int32_t b);
static void dvi_swap(void);
static void dvi_four(int32_t x);
static void dvi_two(UTF16_code s);
static void dvi_pop(int32_t l);
static void dvi_font_def(internal_font_number f);
void
initialize_shipout_variables(void)
{
output_file_name = 0;
dvi_buf = xmalloc_array(eight_bits, DVI_BUF_SIZE);
dvi_limit = DVI_BUF_SIZE;
dvi_ptr = 0;
dvi_offset = 0;
dvi_gone = 0;
down_ptr = TEX_NULL;
right_ptr = TEX_NULL;
cur_s = -1;
}
void
deinitialize_shipout_variables(void)
{
free(dvi_buf);
dvi_buf = NULL;
}
static inline void
dvi_out(eight_bits c)
{
dvi_buf[dvi_ptr++] = c;
if (dvi_ptr == dvi_limit)
dvi_swap();
}
/*660: output the box `p` */
void
ship_out(int32_t p)
{
int32_t page_loc;
unsigned char j, k;
pool_pointer s;
unsigned char old_setting;
unsigned char l;
const char *output_comment = "tectonic";
synctex_sheet(INTPAR(mag));
if (job_name == 0)
open_log_file();
if (INTPAR(tracing_output) > 0) {
print_nl_cstr("");
print_ln();
print_cstr("Completed box being shipped out");
}
if (term_offset > max_print_line - 9)
print_ln();
else if (term_offset > 0 || file_offset > 0)
print_char(' ' );
print_char('[' );
j = 9;
while (j > 0 && COUNT_REG(j) == 0)
j--;
for (k = 0; k <= j; k++) {
print_int(COUNT_REG(k));
if (k < j)
print_char('.' );
}
ttstub_output_flush(rust_stdout);
if (INTPAR(tracing_output) > 0) {
print_char(']' );
begin_diagnostic();
show_box(p);
end_diagnostic(true);
}
/*662: "Ship box `p` out." */
/*663: "Update the values of max_h and max_v; but if the page is too
* large, goto done". */
if (BOX_height(p) > MAX_HALFWORD ||
BOX_depth(p) > MAX_HALFWORD ||
BOX_height(p) + BOX_depth(p) + DIMENPAR(v_offset) > MAX_HALFWORD ||
BOX_width(p) + DIMENPAR(h_offset) > MAX_HALFWORD)
{
if (file_line_error_style_p)
print_file_line();
else
print_nl_cstr("! ");
print_cstr("Huge page cannot be shipped out");
help_ptr = 2;
help_line[1] = "The page just created is more than 18 feet tall or";
help_line[0] = "more than 18 feet wide, so I suspect something went wrong.";
error();
if (INTPAR(tracing_output) <= 0) {
begin_diagnostic();
print_nl_cstr("The following box has been deleted:");
show_box(p);
end_diagnostic(true);
}
goto done;
}
if (BOX_height(p) + BOX_depth(p) + DIMENPAR(v_offset) > max_v)
max_v = BOX_height(p) + BOX_depth(p) + DIMENPAR(v_offset);
if (BOX_width(p) + DIMENPAR(h_offset) > max_h)
max_h = BOX_width(p) + DIMENPAR(h_offset);
/*637: "Initialize variables as ship_out begins." */
dvi_h = 0;
dvi_v = 0;
cur_h = DIMENPAR(h_offset);
dvi_f = FONT_BASE;
/*1405: "Calculate page dimensions and margins" */
/* 4736287 = round(0xFFFF * 72.27) ; i.e., 1 inch expressed as a scaled_t */
cur_h_offset = DIMENPAR(h_offset) + 4736287;
cur_v_offset = DIMENPAR(v_offset) + 4736287;
if (DIMENPAR(pdf_page_width) != 0)
cur_page_width = DIMENPAR(pdf_page_width);
else
cur_page_width = BOX_width(p) + 2 * cur_h_offset;
if (DIMENPAR(pdf_page_height) != 0)
cur_page_height = DIMENPAR(pdf_page_height);
else
cur_page_height = BOX_height(p) + BOX_depth(p) + 2 * cur_v_offset;
/* ... resuming 637 ... open up the DVI file if needed */
if (output_file_name == 0) {
if (job_name == 0)
open_log_file();
pack_job_name(output_file_extension);
dvi_file = ttstub_output_open(name_of_file, 0);
if (dvi_file == NULL)
_tt_abort("cannot open output file \"%s\"", name_of_file);
output_file_name = make_name_string();
}
/* First page? Emit preamble items. */
if (total_pages == 0) {
dvi_out(PRE);
if (semantic_pagination_enabled)
dvi_out(SPX_ID_BYTE);
else
dvi_out(XDV_ID_BYTE);
dvi_four(25400000L); /* magic values: conversion ratio for sp */
dvi_four(473628672L); /* magic values: conversion ratio for sp */
prepare_mag();
dvi_four(INTPAR(mag));
l = strlen(output_comment);
dvi_out(l);
for (s = 0; s < l; s++)
dvi_out(output_comment[s]);
}
/* ... resuming 662 ... Emit per-page preamble. */
page_loc = dvi_offset + dvi_ptr;
dvi_out(BOP);
for (k = 0; k < 10; k++)
dvi_four(COUNT_REG(k));
dvi_four(last_bop);
last_bop = page_loc;
/* Generate a PDF pagesize special unilaterally */
old_setting = selector;
selector = SELECTOR_NEW_STRING;
print_cstr("pdf:pagesize ");
if (DIMENPAR(pdf_page_width) <= 0 || DIMENPAR(pdf_page_height) <= 0) {
print_cstr("default");
} else {
print_cstr("width");
print(' ' );
print_scaled(DIMENPAR(pdf_page_width));
print_cstr("pt");
print(' ' );
print_cstr("height");
print(' ' );
print_scaled(DIMENPAR(pdf_page_height));
print_cstr("pt");
}
selector = old_setting;
dvi_out(XXX1);
dvi_out(cur_length());
for (s = str_start[str_ptr - TOO_BIG_CHAR]; s < pool_ptr; s++)
dvi_out(str_pool[s]);
pool_ptr = str_start[str_ptr - TOO_BIG_CHAR];
/* Done with the synthesized special. The meat: emit this page box. */
cur_v = BOX_height(p) + DIMENPAR(v_offset); /*"Does this need changing for upwards mode???"*/
temp_ptr = p;
if (NODE_type(p) == VLIST_NODE)
vlist_out();
else
hlist_out();
dvi_out(EOP);
total_pages++;
cur_s = -1;
done:
/*1518: "Check for LR anomalies at the end of ship_out" */
if (LR_problems > 0) {
print_ln();
print_nl_cstr("\\endL or \\endR problem (");
print_int(LR_problems / 10000);
print_cstr(" missing, ");
print_int(LR_problems % 10000);
print_cstr(" extra");
LR_problems = 0;
print_char(')');
print_ln();
}
if (LR_ptr != TEX_NULL || cur_dir != LEFT_TO_RIGHT)
confusion("LR3");
if (INTPAR(tracing_output) <= 0)
print_char(']');
dead_cycles = 0;
ttstub_output_flush(rust_stdout);
flush_node_list(p);
synctex_teehs();
}
/*639: Output an hlist */
static void
hlist_out(void)
{
scaled_t base_line;
scaled_t left_edge;
scaled_t save_h, save_v;
int32_t this_box;
glue_ord g_order;
unsigned char g_sign;
int32_t p;
int32_t save_loc;
int32_t leader_box;
scaled_t leader_wd;
scaled_t lx;
bool outer_doing_leaders;
scaled_t edge;
int32_t prev_p;
int32_t len;
int32_t q, r;
int32_t k, j;
double glue_temp;
double cur_glue;
scaled_t cur_g;
uint16_t c;
internal_font_number f;
cur_g = 0;
cur_glue = 0.0;
this_box = temp_ptr;
g_order = BOX_glue_order(this_box);
g_sign = BOX_glue_sign(this_box);
if (INTPAR(xetex_interword_space_shaping) > 1) {
/*640: "Extra stuff for justifiable AAT text..." "Merge sequences of
* words using native fonts and inter-word spaces into single
* nodes" */
p = BOX_list_ptr(this_box);
prev_p = this_box + 5; /* this gets the list within the box */
while (p != TEX_NULL) {
if (LLIST_link(p) != TEX_NULL) {
if (p != TEX_NULL
&& !is_char_node(p)
&& NODE_type(p) == WHATSIT_NODE
&& (NODE_subtype(p) == NATIVE_WORD_NODE || NODE_subtype(p) == NATIVE_WORD_NODE_AT)
&& font_letter_space[NATIVE_NODE_font(p)] == 0
) {
/* "got a word in an AAT font, might be the start of a run" */
r = p;
k = NATIVE_NODE_length(r);
q = LLIST_link(p);
check_next:
/*641: "Advance `q` past ignorable nodes." This test is
* mostly `node_is_invisible_to_interword_space`. 641 is
* reused a few times here. */
while (q != TEX_NULL
&& !is_char_node(q)
&& (NODE_type(q) == PENALTY_NODE
|| NODE_type(q) == INS_NODE
|| NODE_type(q) == MARK_NODE
|| NODE_type(q) == ADJUST_NODE
|| (NODE_type(q) == WHATSIT_NODE && NODE_subtype(q) <= 4)
))
q = LLIST_link(q);
if (q != TEX_NULL && !is_char_node(q)) {
if (NODE_type(q) == GLUE_NODE && GLUE_SPEC_shrink_order(q) == NORMAL) {
if (GLUE_NODE_glue_ptr(q) == font_glue[NATIVE_NODE_font(r)]) {
/* "Found a normal space; if the next node is
* another word in the same font, we'll
* merge." */
q = LLIST_link(q);
while (q != TEX_NULL && !is_char_node(q)
&& (NODE_type(q) == PENALTY_NODE
|| NODE_type(q) == INS_NODE
|| NODE_type(q) == MARK_NODE
|| NODE_type(q) == ADJUST_NODE
|| (NODE_type(q) == WHATSIT_NODE && NODE_subtype(q) <= 4)
))
q = LLIST_link(q);
if (q != TEX_NULL
&& !is_char_node(q)
&& NODE_type(q) == WHATSIT_NODE
&& (NODE_subtype(q) == NATIVE_WORD_NODE || NODE_subtype(q) == NATIVE_WORD_NODE_AT)
&& (mem[q + 4].b16.s2 == mem[r + 4].b16.s2)
) {
p = q;
k += 1 + NATIVE_NODE_length(q);
q = LLIST_link(q);
goto check_next;
}
} else {
q = LLIST_link(q);
}
if (q != TEX_NULL
&& !is_char_node(q)
&& NODE_type(q) == KERN_NODE
&& NODE_subtype(q) == SPACE_ADJUSTMENT
) {
q = LLIST_link(q);
while (q != TEX_NULL
&& !is_char_node(q)
&& (NODE_type(q) == PENALTY_NODE
|| NODE_type(q) == INS_NODE
|| NODE_type(q) == MARK_NODE
|| NODE_type(q) == ADJUST_NODE
|| (NODE_type(q) == WHATSIT_NODE && NODE_subtype(q) <= 4)
))
q = LLIST_link(q);
if (q != TEX_NULL
&& !is_char_node(q)
&& NODE_type(q) == WHATSIT_NODE
&& (NODE_subtype(q) == NATIVE_WORD_NODE || NODE_subtype(q) == NATIVE_WORD_NODE_AT)
&& NATIVE_NODE_font(q) == NATIVE_NODE_font(r)
) {
p = q;
k += 1 + NATIVE_NODE_length(q);
q = LLIST_link(q);
goto check_next;
}
}
goto end_node_run;
}
if (q != TEX_NULL
&& !is_char_node(q)
&& NODE_type(q) == WHATSIT_NODE
&& (NODE_subtype(q) == NATIVE_WORD_NODE || NODE_subtype(q) == NATIVE_WORD_NODE_AT)
&& NATIVE_NODE_font(q) == NATIVE_NODE_font(r)
) {
p = q;
q = LLIST_link(q);
goto check_next;
}
}
end_node_run:
/* "Now r points to the first native_word_node of the run,
* and p to the last." */
if (p != r) {
if (pool_ptr + k > pool_size)
overflow("pool size", pool_size - init_pool_ptr);
k = 0;
q = r;
while (true) {
if (NODE_type(q) == WHATSIT_NODE) {
if (NODE_subtype(q) == NATIVE_WORD_NODE || NODE_subtype(q) == NATIVE_WORD_NODE_AT) {
for (j = 0; j < NATIVE_NODE_length(q); j++) {
str_pool[pool_ptr] = NATIVE_NODE_text(q)[j];
pool_ptr++;
}
k += BOX_width(q);
}
} else if (NODE_type(q) == GLUE_NODE) {
str_pool[pool_ptr] = ' ';
pool_ptr++;
g = GLUE_NODE_glue_ptr(q);
k += BOX_width(g);
if (g_sign != NORMAL) {
if (g_sign == STRETCHING) {
if (GLUE_SPEC_stretch_order(g) == g_order)
k += tex_round(BOX_glue_set(this_box) * GLUE_SPEC_stretch(g));
} else {
if (GLUE_SPEC_shrink_order(g) == g_order)
k -= tex_round(BOX_glue_set(this_box) * GLUE_SPEC_shrink(g));
}
}
} else if (NODE_type(q) == KERN_NODE) {
k += BOX_width(q);
}
if (q == p)
break;
else
q = LLIST_link(q);
}
q = new_native_word_node(NATIVE_NODE_font(r), cur_length());
NODE_subtype(q) = NODE_subtype(r);
for (j = 0; j < cur_length(); j++)
NATIVE_NODE_text(q)[j] = str_pool[str_start[str_ptr - TOO_BIG_CHAR] + j];
/* "Link q into the list in place of r...p" */
BOX_width(q) = k;
set_justified_native_glyphs(q);
LLIST_link(prev_p) = q;
LLIST_link(q) = LLIST_link(p);
LLIST_link(p) = TEX_NULL;
prev_p = r;
p = LLIST_link(r);
/* "Extract any 'invisible' nodes from the old list
* and insert them after the new node, so we don't
* lose them altogether. Note that the first node
* cannot be one of these, as we always start merging
* at a native_word node." */
while (p != TEX_NULL) {
if (!is_char_node(p)
&& (NODE_type(p) == PENALTY_NODE
|| NODE_type(p) == INS_NODE
|| NODE_type(p) == MARK_NODE
|| NODE_type(p) == ADJUST_NODE
|| (NODE_type(p) == WHATSIT_NODE && NODE_subtype(p) <= 4))
) {
LLIST_link(prev_p) = LLIST_link(p);
LLIST_link(p) = LLIST_link(q);
LLIST_link(q) = p;
q = p;
}
prev_p = p;
p = LLIST_link(p);
}
flush_node_list(r);
pool_ptr = str_start[str_ptr - TOO_BIG_CHAR];
p = q;
}
}
prev_p = p;
}
p = LLIST_link(p);
}
}
/* ... resuming 639 ... */
p = BOX_list_ptr(this_box);
cur_s++;
if (cur_s > 0)
dvi_out(PUSH);
if (cur_s > max_push)
max_push = cur_s;
save_loc = dvi_offset + dvi_ptr;
base_line = cur_v;
prev_p = this_box + 5; /* this is list_offset, the offset of the box list pointer */
/*1501: "Initialize hlist_out for mixed direction typesetting" */
temp_ptr = get_avail();
LLIST_info(temp_ptr) = BEFORE;
LLIST_link(temp_ptr) = LR_ptr;
LR_ptr = temp_ptr;
if (BOX_lr_mode(this_box) == DLIST) {
if (cur_dir == RIGHT_TO_LEFT) {
cur_dir = LEFT_TO_RIGHT;
cur_h -= BOX_width(this_box);
} else {
BOX_lr_mode(this_box) = 0;
}
}
if (cur_dir == RIGHT_TO_LEFT && BOX_lr_mode(this_box) != REVERSED) {
/*1508: "Reverse the complete hlist and set the subtype to reversed." */
save_h = cur_h;
temp_ptr = p;
p = new_kern(0);
SYNCTEX_tag(p, MEDIUM_NODE_SIZE) = 0; /* "SyncTeX: do nothing, it is too late" */
LLIST_link(prev_p) = p;
cur_h = 0;
LLIST_link(p) = reverse(this_box, TEX_NULL, &cur_g, &cur_glue);
BOX_width(p) = -cur_h;
cur_h = save_h;
BOX_lr_mode(this_box) = REVERSED;
}
/* ... resuming 639 ... */
left_edge = cur_h;
synctex_hlist(this_box);
while (p != TEX_NULL) {
/*642: "Output node `p` for `hlist_out` and move to the next node,
* maintaining the condition `cur_v = base_line`." ... "We ought to
* give special care to the efficiency [here] since it belongs to TeX's
* inner loop. When a `char_node` is encountered, we save a little time
* by processing several nodes in succession[.] The program uses the
* fact that `set_char_0 = 0`. */
reswitch:
if (is_char_node(p)) {
if (cur_h != dvi_h) {
movement(cur_h - dvi_h, RIGHT1);
dvi_h = cur_h;
}
if (cur_v != dvi_v) {
movement(cur_v - dvi_v, DOWN1);
dvi_v = cur_v;
}
do {
f = CHAR_NODE_font(p);
c = CHAR_NODE_character(p);
if (p != LIG_TRICK && font_mapping[f] != NULL)
c = apply_tfm_font_mapping(font_mapping[f], c);
if (f != dvi_f) {
/*643: "Change font dvi_f to f" */
if (!font_used[f]) {
dvi_font_def(f);
font_used[f] = true;
}
if (f <= 64) {
dvi_out(f + FNT_NUM_0 - 1);
} else if (f <= 256) {
dvi_out(FNT1);
dvi_out(f - 1);
} else {
dvi_out(FNT1 + 1);
dvi_out((f - 1) / 256);
dvi_out((f - 1) % 256);
}
dvi_f = f;
}
if (font_ec[f] >= c) {
if (font_bc[f] <= c) {
if (FONT_CHARACTER_INFO(f, c).s3 > 0) { /* if (char_exists(orig_char_info(f)(c))) */
if (c >= 128)
dvi_out(SET1);
dvi_out(c);
cur_h += FONT_CHARACTER_WIDTH(f, c);
}
}
}
prev_p = LLIST_link(prev_p);
p = LLIST_link(p);
} while (is_char_node(p));
synctex_current();
dvi_h = cur_h;
} else {
/*644: "Output the non-char_node `p` and move to the next node" */
switch (NODE_type(p)) {
case HLIST_NODE:
case VLIST_NODE:
if (BOX_list_ptr(p) == TEX_NULL) {
if (NODE_type(p) == VLIST_NODE) {
synctex_void_vlist(p, this_box);
} else {
synctex_void_hlist(p, this_box);
}
cur_h += BOX_width(p);
} else {
save_h = dvi_h;
save_v = dvi_v;
cur_v = base_line + BOX_shift_amount(p);
temp_ptr = p;
edge = cur_h + BOX_width(p);
if (cur_dir == RIGHT_TO_LEFT)
cur_h = edge;
if (NODE_type(p) == VLIST_NODE)
vlist_out();
else
hlist_out();
dvi_h = save_h;
dvi_v = save_v;
cur_h = edge;
cur_v = base_line;
}
break;
case RULE_NODE:
rule_ht = BOX_height(p);
rule_dp = BOX_depth(p);
rule_wd = BOX_width(p);
goto fin_rule;
break;
case WHATSIT_NODE:
/*1407: "Output the whatsit node p in an hlist" */
switch (NODE_subtype(p)) {
case NATIVE_WORD_NODE:
case NATIVE_WORD_NODE_AT:
case GLYPH_NODE:
if (cur_h != dvi_h) {
movement(cur_h - dvi_h, RIGHT1);
dvi_h = cur_h;
}
if (cur_v != dvi_v) {
movement(cur_v - dvi_v, DOWN1);
dvi_v = cur_v;
}
f = NATIVE_NODE_font(p);
if (f != dvi_f) {
if (!font_used[f]) {
dvi_font_def(f);
font_used[f] = true;
}
if (f <= 64) {
dvi_out(f + 170);
} else if (f <= 256) {
dvi_out(FNT1);
dvi_out(f - 1);
} else {
dvi_out(FNT1 + 1);
dvi_out((f - 1) / 256);
dvi_out((f - 1) % 256);
}
dvi_f = f;
}
if (NODE_subtype(p) == GLYPH_NODE) {
dvi_out(SET_GLYPHS);
dvi_four(BOX_width(p));
dvi_two(1); /* glyph count */
dvi_four(0); /* x offset, as fixed-point */
dvi_four(0); /* y offset, as fixed-point */
dvi_two(NATIVE_NODE_glyph(p));
cur_h += BOX_width(p);
} else {
if (NODE_subtype(p) == NATIVE_WORD_NODE_AT) {
if (NATIVE_NODE_length(p) > 0 || NATIVE_NODE_glyph_info_ptr(p) != NULL) {
dvi_out(SET_TEXT_AND_GLYPHS);
len = NATIVE_NODE_length(p);
dvi_two(len);
for (k = 0; k < len; k++)
dvi_two(NATIVE_NODE_text(p)[k]);
len = make_xdv_glyph_array_data(p);
for (k = 0; k < len; k++)
dvi_out(xdv_buffer[k]);
}
} else {
if (NATIVE_NODE_glyph_info_ptr(p) != NULL) {
dvi_out(SET_GLYPHS);
len = make_xdv_glyph_array_data(p);
for (k = 0; k < len; k++)
dvi_out(xdv_buffer[k]);
}
}
cur_h += BOX_width(p);
}
dvi_h = cur_h;
break;
case PIC_NODE:
case PDF_NODE:
save_h = dvi_h;
save_v = dvi_v;
cur_v = base_line;
edge = cur_h + BOX_width(p);
pic_out(p);
dvi_h = save_h;
dvi_v = save_v;
cur_h = edge;
cur_v = base_line;
break;
case PDF_SAVE_POS_NODE:
pdf_last_x_pos = cur_h + cur_h_offset;
pdf_last_y_pos = cur_page_height - cur_v - cur_v_offset;
break;
default:
out_what(p);
break;
}
break; /* end of WHATSIT_NODE case */
case GLUE_NODE:
/*647: "Move right or output leaders" */
g = GLUE_NODE_glue_ptr(p);
rule_wd = BOX_width(g) - cur_g;
if (g_sign != NORMAL) {
if (g_sign == STRETCHING) {
if (GLUE_SPEC_stretch_order(g) == g_order) {
cur_glue += GLUE_SPEC_stretch(g);
glue_temp = BOX_glue_set(this_box) * cur_glue;
if (glue_temp > 1000000000.0)
glue_temp = 1000000000.0;
else if (glue_temp < -1000000000.0)
glue_temp = -1000000000.0;
cur_g = tex_round(glue_temp);
}
} else if (GLUE_SPEC_shrink_order(g) == g_order) {
cur_glue -= GLUE_SPEC_shrink(g);
glue_temp = BOX_glue_set(this_box) * cur_glue;
if (glue_temp > 1000000000.0)
glue_temp = 1000000000.0;
else if (glue_temp < -1000000000.0)
glue_temp = -1000000000.0;
cur_g = tex_round(glue_temp);
}
}
rule_wd += cur_g;
/*1486: "Handle a glue node for mixed direction typesetting". */
if ((g_sign == STRETCHING && GLUE_SPEC_stretch_order(g) == g_order) ||
(g_sign == SHRINKING && GLUE_SPEC_shrink_order(g) == g_order)) {
if (GLUE_SPEC_ref_count(g) == TEX_NULL)
free_node(g, GLUE_SPEC_SIZE);
else
GLUE_SPEC_ref_count(g)--;
if (NODE_subtype(p) < A_LEADERS) {
NODE_type(p) = KERN_NODE;
BOX_width(p) = rule_wd;
} else {
g = get_node(GLUE_SPEC_SIZE);
GLUE_SPEC_stretch_order(g) = FILLL + 1; /* "will never match" */
GLUE_SPEC_shrink_order(g) = FILLL + 1;
BOX_width(g) = rule_wd;
GLUE_SPEC_stretch(g) = 0;
GLUE_SPEC_shrink(g) = 0;
GLUE_NODE_glue_ptr(p) = g;
}
}
if (NODE_subtype(p) >= A_LEADERS) {
/*648: "Output leaders into an hlist, goto fin_rule if a
* rule or next_p if done." */
leader_box = GLUE_NODE_leader_ptr(p);
if (NODE_type(leader_box) == RULE_NODE) {
rule_ht = BOX_height(leader_box);
rule_dp = BOX_depth(leader_box);
goto fin_rule;
}
leader_wd = BOX_width(leader_box);
if (leader_wd > 0 && rule_wd > 0) {
rule_wd += 10; /* "compensate for floating-point rounding" ?? */
if (cur_dir == RIGHT_TO_LEFT)
cur_h -= 10;
edge = cur_h + rule_wd;
lx = 0;
/*649: "Let cur_h be the position of the first pox,
* and set leader_wd + lx to the spacing between
* corresponding parts of boxes". Additional
* explanator comments in XTTP. */
if (NODE_subtype(p) == A_LEADERS) {
save_h = cur_h;
cur_h = left_edge + leader_wd * ((cur_h - left_edge) / leader_wd);
if (cur_h < save_h)
cur_h = cur_h + leader_wd;
} else {
lq = rule_wd / leader_wd;
lr = rule_wd % leader_wd;
if (NODE_subtype(p) == C_LEADERS)
cur_h = cur_h + (lr / 2);
else {
lx = lr / (lq + 1);
cur_h = cur_h + ((lr - (lq - 1) * lx) / 2);
}
}
while (cur_h + leader_wd <= edge) {
/*650: "Output a leader box at cur_h, then advance cur_h by leader_wd + lx" */
cur_v = base_line + BOX_shift_amount(leader_box);
if (cur_v != dvi_v) {
movement(cur_v - dvi_v, DOWN1);
dvi_v = cur_v;
}
save_v = dvi_v;
if (cur_h != dvi_h) {
movement(cur_h - dvi_h, RIGHT1);
dvi_h = cur_h;
}
save_h = dvi_h;
temp_ptr = leader_box;
if (cur_dir == RIGHT_TO_LEFT)
cur_h += leader_wd;
outer_doing_leaders = doing_leaders;
doing_leaders = true;
if (NODE_type(leader_box) == VLIST_NODE)
vlist_out();
else
hlist_out();
doing_leaders = outer_doing_leaders;
dvi_v = save_v;
dvi_h = save_h;
cur_v = base_line;
cur_h = save_h + leader_wd + lx;
}
if (cur_dir == RIGHT_TO_LEFT)
cur_h = edge;
else
cur_h = edge - 10;
goto next_p;
}
}
goto move_past;
break; /* end GLUE_NODE case */
case MARGIN_KERN_NODE:
cur_h += BOX_width(p);
break;
case KERN_NODE:
synctex_kern(p, this_box);
cur_h += BOX_width(p);
break;
case MATH_NODE:
synctex_math(p, this_box);
/* 1504: "Adjust the LR stack...; if necessary reverse and
* hlist segment and goto reswitch." "Breaking a paragraph
* into lines while TeXXeT is disabled may result in lines
* with unpaired math nodes. Such hlists are silently accepted
* in the absence of text direction directives." */
if (odd(NODE_subtype(p))) { /* <= this is end_LR(p) */
if (LLIST_info(LR_ptr) == MATH_NODE_end_lr_type(p)) {
temp_ptr = LR_ptr;
LR_ptr = LLIST_link(temp_ptr);
LLIST_link(temp_ptr) = avail;
avail = temp_ptr;
} else {
if (NODE_subtype(p) > L_CODE)
LR_problems++;
}
} else {
temp_ptr = get_avail();
LLIST_info(temp_ptr) = MATH_NODE_end_lr_type(p);
LLIST_link(temp_ptr) = LR_ptr;
LR_ptr = temp_ptr;
if (MATH_NODE_lr_dir(p) != cur_dir) {
/*1509: "Reverse an hlist segment and goto reswitch" */
save_h = cur_h;
temp_ptr = LLIST_link(p);
rule_wd = BOX_width(p);
free_node(p, MEDIUM_NODE_SIZE);
cur_dir = 1 - cur_dir;
p = new_edge(cur_dir, rule_wd);
LLIST_link(prev_p) = p;
cur_h = cur_h - left_edge + rule_wd;
LLIST_link(p) = reverse(this_box, new_edge(1 - cur_dir, 0), &cur_g, &cur_glue);
EDGE_NODE_edge_dist(p) = cur_h;
cur_dir = 1 - cur_dir;
cur_h = save_h;
goto reswitch;
}
}
NODE_type(p) = KERN_NODE;
cur_h += BOX_width(p);
break;
case LIGATURE_NODE:
/* 675: "Make node p look like a char_node and goto reswitch" */
mem[LIG_TRICK] = mem[p + 1]; /* = lig_char(p) */
LLIST_link(LIG_TRICK) = LLIST_link(p);
p = LIG_TRICK;
xtx_ligature_present = true;
goto reswitch;
break;
/*1507: "Cases of hlist_out that arise in mixed direction text only" */
case EDGE_NODE:
cur_h += BOX_width(p);
left_edge = cur_h + EDGE_NODE_edge_dist(p);
cur_dir = NODE_subtype(p);
break;
default:
break;
}
goto next_p;
fin_rule:
/*646: "Output a rule in an hlist" */
if (rule_ht == NULL_FLAG)
rule_ht = BOX_height(this_box);
if (rule_dp == NULL_FLAG)
rule_dp = BOX_depth(this_box);
rule_ht += rule_dp;
if (rule_ht > 0 && rule_wd > 0) {
if (cur_h != dvi_h) {
movement(cur_h - dvi_h, RIGHT1);
dvi_h = cur_h;
}
cur_v = base_line + rule_dp;
if (cur_v != dvi_v) {
movement(cur_v - dvi_v, DOWN1);
dvi_v = cur_v;
}
dvi_out(SET_RULE);
dvi_four(rule_ht);
dvi_four(rule_wd);
cur_v = base_line;
dvi_h += rule_wd;
}
/* ... resuming 644 ... */
move_past:
cur_h += rule_wd;
synctex_horizontal_rule_or_glue(p, this_box);
next_p:
prev_p = p;
p = LLIST_link(p);
}
}
synctex_tsilh(this_box);
/*1502: "Finish hlist_out for mixed direction typesetting" */
/*1505: "Check for LR anomalies" */
while (LLIST_info(LR_ptr) != BEFORE) {
if (LLIST_info(LR_ptr) > L_CODE)
LR_problems += 10000;
temp_ptr = LR_ptr;
LR_ptr = LLIST_link(temp_ptr);
LLIST_link(temp_ptr) = avail;
avail = temp_ptr;
}
temp_ptr = LR_ptr;
LR_ptr = LLIST_link(temp_ptr);
LLIST_link(temp_ptr) = avail;
avail = temp_ptr;
if (BOX_lr_mode(this_box) == DLIST)
cur_dir = RIGHT_TO_LEFT;
/* ... finishing 639 */
prune_movements(save_loc);
if (cur_s > 0)
dvi_pop(save_loc);
cur_s--;
}
/*651: "When vlist_out is called, its duty is to output the box represented by
* the vlist_node pointed to by temp_ptr. The reference point of that box has
* coordinates (cur_h, cur_v)." */
static void
vlist_out(void)
{
scaled_t left_edge;
scaled_t top_edge;
scaled_t save_h, save_v;
int32_t this_box;
glue_ord g_order;
unsigned char g_sign;
int32_t p;
int32_t save_loc;
int32_t leader_box;
scaled_t leader_ht;
scaled_t lx;
bool outer_doing_leaders;
scaled_t edge;
double glue_temp;
double cur_glue;
scaled_t cur_g;
bool upwards;
internal_font_number f;
cur_g = 0;
cur_glue = 0.0;
this_box = temp_ptr;
g_order = BOX_glue_order(this_box);
g_sign = BOX_glue_sign(this_box);
p = BOX_list_ptr(this_box);
upwards = (NODE_subtype(this_box) == 1);
cur_s++;
if (cur_s > 0)
dvi_out(PUSH);
if (cur_s > max_push)
max_push = cur_s;
save_loc = dvi_offset + dvi_ptr;
left_edge = cur_h;
synctex_vlist(this_box);
if (upwards)
cur_v += BOX_depth(this_box);
else
cur_v -= BOX_height(this_box);
top_edge = cur_v;
while (p != TEX_NULL) {
/*652: "Output node p and move to the next node, maintaining the
* condition cur_h = left_edge" */
if (is_char_node(p))
confusion("vlistout");
else {
/*653: "Output the non-char_node p" */
switch (NODE_type(p)) {
case HLIST_NODE:
case VLIST_NODE:
/*654: "Output a box in a vlist" */
if (BOX_list_ptr(p) == TEX_NULL) {
if (upwards)
cur_v -= BOX_depth(p);
else
cur_v += BOX_height(p);
if (NODE_type(p) == VLIST_NODE) {
synctex_void_vlist(p, this_box);
} else {
synctex_void_hlist(p, this_box);
}
if (upwards)
cur_v -= BOX_height(p);
else
cur_v += BOX_depth(p);
} else {
if (upwards)
cur_v -= BOX_depth(p);
else
cur_v += BOX_height(p);
if (cur_v != dvi_v) {
movement(cur_v - dvi_v, DOWN1);
dvi_v = cur_v;
}
save_h = dvi_h;
save_v = dvi_v;
if (cur_dir == RIGHT_TO_LEFT)
cur_h = left_edge - BOX_shift_amount(p);
else
cur_h = left_edge + BOX_shift_amount(p);
temp_ptr = p;
if (NODE_type(p) == VLIST_NODE)
vlist_out();
else
hlist_out();
dvi_h = save_h;
dvi_v = save_v;
if (upwards)
cur_v = save_v - BOX_height(p);
else
cur_v = save_v + BOX_depth(p);
cur_h = left_edge;
}
break;
case RULE_NODE:
rule_ht = BOX_height(p);
rule_dp = BOX_depth(p);
rule_wd = BOX_width(p);
goto fin_rule;
break;
case WHATSIT_NODE:
/*1403: "Output the whatsit node p in a vlist" */
switch (NODE_subtype(p)) {
case GLYPH_NODE:
cur_v = cur_v + BOX_height(p);
cur_h = left_edge;
if (cur_h != dvi_h) {
movement(cur_h - dvi_h, RIGHT1);
dvi_h = cur_h;
}
if (cur_v != dvi_v) {
movement(cur_v - dvi_v, DOWN1);
dvi_v = cur_v;
}
f = NATIVE_NODE_font(p);
if (f != dvi_f) {
/*643:*/
if (!font_used[f]) {
dvi_font_def(f);
font_used[f] = true;
}
if (f <= 64) {
dvi_out(f + 170);
} else if (f <= 256) {
dvi_out(FNT1);
dvi_out(f - 1);
} else {
dvi_out(FNT1 + 1);
dvi_out((f - 1) / 256);
dvi_out((f - 1) % 256);
}
dvi_f = f;
}
dvi_out(SET_GLYPHS);
dvi_four(0); /* width */
dvi_two(1); /* glyph count */
dvi_four(0); /* x offset as fixed-point */
dvi_four(0); /* y offset as fixed-point */
dvi_two(NATIVE_NODE_glyph(p));
cur_v += BOX_depth(p);
cur_h = left_edge;
break;
case PIC_NODE:
case PDF_NODE:
save_h = dvi_h;
save_v = dvi_v;
cur_v = cur_v + BOX_height(p);
pic_out(p);
dvi_h = save_h;
dvi_v = save_v;
cur_v = save_v + BOX_depth(p);
cur_h = left_edge;
break;
case PDF_SAVE_POS_NODE:
pdf_last_x_pos = cur_h + cur_h_offset;
pdf_last_y_pos = cur_page_height - cur_v - cur_v_offset;
break;
default:
out_what(p);
break;
}
break; /* end WHATSIT_NODE case */
case GLUE_NODE:
/*656: "Move down or output leaders" */
g = GLUE_NODE_glue_ptr(p);
rule_ht = BOX_width(g) - cur_g;
if (g_sign != NORMAL) {
if (g_sign == STRETCHING) {
if (GLUE_SPEC_stretch_order(g) == g_order) {
cur_glue += GLUE_SPEC_stretch(g);
glue_temp = BOX_glue_set(this_box) * cur_glue;
if (glue_temp > 1000000000.0)
glue_temp = 1000000000.0;
else if (glue_temp < -1000000000.0)
glue_temp = -1000000000.0;
cur_g = tex_round(glue_temp);
}
} else if (GLUE_SPEC_shrink_order(g) == g_order) {
cur_glue -= GLUE_SPEC_shrink(g);
glue_temp = BOX_glue_set(this_box) * cur_glue;
if (glue_temp > 1000000000.0)
glue_temp = 1000000000.0;
else if (glue_temp < -1000000000.0)
glue_temp = -1000000000.0;
cur_g = tex_round(glue_temp);
}
}
rule_ht += cur_g;
if (NODE_subtype(p) >= A_LEADERS) {
/*657: "Output leaders in a vlist, goto fin_rule if a rule
* or next_p if done" */
leader_box = GLUE_NODE_leader_ptr(p);
if (NODE_type(leader_box) == RULE_NODE) {
rule_wd = BOX_width(leader_box);
rule_dp = 0;
goto fin_rule;
}
leader_ht = BOX_height(leader_box) + BOX_depth(leader_box);
if (leader_ht > 0 && rule_ht > 0) {
rule_ht += 10; /* "compensate for floating-point rounding" */
edge = cur_v + rule_ht;
lx = 0;
/*658: "Let cur_v be the position of the first box,
* and set leader_ht + lx to the spacing between
* corresponding parts of boxes" */
if (NODE_subtype(p) == A_LEADERS) {
save_v = cur_v;
cur_v = top_edge + leader_ht * ((cur_v - top_edge) / leader_ht);
if (cur_v < save_v)
cur_v = cur_v + leader_ht;
} else {
lq = rule_ht / leader_ht;
lr = rule_ht % leader_ht;
if (mem[p].b16.s0 == C_LEADERS)
cur_v = cur_v + (lr / 2);
else {
lx = lr / (lq + 1);
cur_v = cur_v + ((lr - (lq - 1) * lx) / 2);
}
}
while (cur_v + leader_ht <= edge) {
/*659: "Output a leader box at cur_v, then advance
* cur_v by leader_ht + lx". "When we reach this
* part of the program, cur_v indicates the top of
* a leader box, not its baseline." */
if (cur_dir == RIGHT_TO_LEFT)
cur_h = left_edge - BOX_shift_amount(leader_box);
else
cur_h = left_edge + BOX_shift_amount(leader_box);
if (cur_h != dvi_h) {
movement(cur_h - dvi_h, RIGHT1);
dvi_h = cur_h;
}
save_h = dvi_h;
cur_v += BOX_height(leader_box);
if (cur_v != dvi_v) {
movement(cur_v - dvi_v, DOWN1);
dvi_v = cur_v;
}
save_v = dvi_v;
temp_ptr = leader_box;
outer_doing_leaders = doing_leaders;
doing_leaders = true;
if (NODE_type(leader_box) == VLIST_NODE)
vlist_out();
else
hlist_out();
doing_leaders = outer_doing_leaders;
dvi_v = save_v;
dvi_h = save_h;
cur_h = left_edge;
cur_v = save_v - BOX_height(leader_box) + leader_ht + lx;
}
cur_v = edge - 10;
goto next_p;
}
}
goto move_past;
break;
case KERN_NODE:
if (upwards)
cur_v -= BOX_width(p);
else
cur_v += BOX_width(p);
break;
default:
break;
}
goto next_p;
fin_rule:
/*655: "Output a rule in a vlist, goto next_p */
if (rule_wd == NULL_FLAG)
rule_wd = BOX_width(this_box);
rule_ht += rule_dp;
if (upwards)
cur_v -= rule_ht;
else
cur_v += rule_ht;
if (rule_ht > 0 && rule_wd > 0) {
if (cur_dir == RIGHT_TO_LEFT)
cur_h -= rule_wd;
if (cur_h != dvi_h) {
movement(cur_h - dvi_h, RIGHT1);
dvi_h = cur_h;
}
if (cur_v != dvi_v) {
movement(cur_v - dvi_v, DOWN1);
dvi_v = cur_v;
}
dvi_out(PUT_RULE);
dvi_four(rule_ht);
dvi_four(rule_wd);
cur_h = left_edge;
}
goto next_p;
move_past:
if (upwards)
cur_v -= rule_ht;
else
cur_v += rule_ht;
}
next_p:
p = LLIST_link(p);
}
synctex_tsilv(this_box);
prune_movements(save_loc);
if (cur_s > 0)
dvi_pop(save_loc);
cur_s--;
}
/*1510: "The reverse function defined here is responsible for reversing the
* nodes of an hlist (segment). this_box is the enclosing hlist_node; t is to
* become the tail of the reversed list; and the global variable temp_ptr is
* the head of the list to be reversed. cur_g and cur_glue are the current
* glue rounding state variables, to be updated by this function. We remove
* nodes from the original list and add them to the head of the new one."
*/
static int32_t
reverse(int32_t this_box, int32_t t, scaled_t *cur_g, double *cur_glue)
{
int32_t l;
int32_t p;
int32_t q;
glue_ord g_order;
unsigned char g_sign;
double glue_temp;
int32_t m, n;
uint16_t c;
internal_font_number f;
g_order = BOX_glue_order(this_box);
g_sign = BOX_glue_sign(this_box);
l = t;
p = temp_ptr;
m = MIN_HALFWORD;
n = MIN_HALFWORD;
while (true) {
while (p != TEX_NULL) {
/*1511: "Move node p to the new list and go to the next node; or
* goto done if the end of the reflected segment has been
* reached." */
reswitch:
if (is_char_node(p)) {
do {
f = CHAR_NODE_font(p);
c = CHAR_NODE_character(p);
cur_h += FONT_CHARACTER_WIDTH(f, effective_char(true, f, c));
q = LLIST_link(p);
LLIST_link(p) = l;
l = p;
p = q;
} while (is_char_node(p));
} else {
q = LLIST_link(p);
switch (NODE_type(p)) {
case HLIST_NODE:
case VLIST_NODE:
case RULE_NODE:
case KERN_NODE:
rule_wd = BOX_width(p);
break;
case WHATSIT_NODE:
if (NODE_subtype(p) == NATIVE_WORD_NODE
|| NODE_subtype(p) == NATIVE_WORD_NODE_AT
|| NODE_subtype(p) == GLYPH_NODE
|| NODE_subtype(p) == PIC_NODE
|| NODE_subtype(p) == PDF_NODE
)
rule_wd = BOX_width(p);
else
goto next_p;
break;
case GLUE_NODE:
/*1486: "Handle a glue node for mixed direction typesetting" */
g = GLUE_NODE_glue_ptr(p);
rule_wd = BOX_width(g) - *cur_g;
if (g_sign != NORMAL) {
if (g_sign == STRETCHING) {
if (GLUE_SPEC_stretch_order(g) == g_order) {
*cur_glue = *cur_glue + GLUE_SPEC_stretch(g);
glue_temp = BOX_glue_set(this_box) * *cur_glue;
if (glue_temp > 1000000000.0)
glue_temp = 1000000000.0;
else if (glue_temp < -1000000000.0)
glue_temp = -1000000000.0;
*cur_g = tex_round(glue_temp);
}
} else if (GLUE_SPEC_shrink_order(g) == g_order) {
*cur_glue = *cur_glue - GLUE_SPEC_shrink(g);
glue_temp = BOX_glue_set(this_box) * *cur_glue;
if (glue_temp > 1000000000.0)
glue_temp = 1000000000.0;
else if (glue_temp < -1000000000.0)
glue_temp = -1000000000.0;
*cur_g = tex_round(glue_temp);
}
}
rule_wd += *cur_g;
if ((g_sign == STRETCHING && mem[g].b16.s1 == g_order)
|| (g_sign == SHRINKING && mem[g].b16.s0 == g_order)) {
if (GLUE_SPEC_ref_count(g) == TEX_NULL)
free_node(g, GLUE_SPEC_SIZE);
else
GLUE_SPEC_ref_count(g)--;
if (NODE_subtype(p) < A_LEADERS) {
NODE_type(p) = KERN_NODE;
BOX_width(p) = rule_wd;
} else {
g = get_node(GLUE_SPEC_SIZE);
GLUE_SPEC_stretch_order(g) = FILLL + 1; /* "will never match" */
GLUE_SPEC_shrink_order(g) = FILLL + 1;
BOX_width(g) = rule_wd;
GLUE_SPEC_stretch(g) = 0;
GLUE_SPEC_shrink(g) = 0;
GLUE_NODE_glue_ptr(p) = g;
}
}
break; /* end GLUE_NODE case */
case LIGATURE_NODE:
flush_node_list(LIGATURE_NODE_lig_ptr(p));
temp_ptr = p;
p = get_avail();
mem[p] = mem[temp_ptr + 1]; /* = mem[lig_char(temp_ptr)] */
LLIST_link(p) = q;
free_node(temp_ptr, SMALL_NODE_SIZE);
goto reswitch;
case MATH_NODE:
/*1516: "Math nodes in an inner reflected segment are
* modified, those at the outer level are changed into
* kern nodes." */
rule_wd = BOX_width(p);
if (odd(BOX_lr_mode(p))) {
if (LLIST_info(LR_ptr) != MATH_NODE_end_lr_type(p)) {
NODE_type(p) = KERN_NODE;
LR_problems++;
} else {
temp_ptr = LR_ptr;
LR_ptr = LLIST_link(temp_ptr);
LLIST_link(temp_ptr) = avail;
avail = temp_ptr;
if (n > MIN_HALFWORD) {
n--;
NODE_subtype(p)--;
} else {
NODE_type(p) = KERN_NODE;
if (m > MIN_HALFWORD) {
m--;
} else {
/*1517: "Finish the reverse hlist segment and goto done" */
free_node(p, MEDIUM_NODE_SIZE);
LLIST_link(t) = q;
BOX_width(t) = rule_wd;
EDGE_NODE_edge_dist(t) = -cur_h - rule_wd;
goto done;
}
}
}
} else {
temp_ptr = get_avail();
LLIST_info(temp_ptr) = MATH_NODE_end_lr_type(p);
LLIST_link(temp_ptr) = LR_ptr;
LR_ptr = temp_ptr;
if (n > MIN_HALFWORD || MATH_NODE_lr_dir(p) != cur_dir) {
n++;
NODE_subtype(p)++;
} else {
NODE_type(p) = KERN_NODE;
m++;
}
}
break;
case EDGE_NODE:
confusion("LR2");
break;
default:
goto next_p;
}
cur_h += rule_wd;
next_p:
LLIST_link(p) = l;
if (NODE_type(p) == KERN_NODE) {
if (rule_wd == 0 || l == TEX_NULL) {
free_node(p, MEDIUM_NODE_SIZE);
p = l;
}
}
l = p;
p = q;
}
}
/* ... resuming 1510 ... */
if (t == TEX_NULL && m == MIN_HALFWORD && n == MIN_HALFWORD)
goto done;
p = new_math(0, LLIST_info(LR_ptr)); /* "Manufacture a missing math node" */
LR_problems += 10000;
}
done:
return l;
}
/*1506: Create a new edge node of subtype `s` and width `w` */
int32_t
new_edge(small_number s, scaled_t w)
{
int32_t p;
p = get_node(EDGE_NODE_SIZE);
NODE_type(p) = EDGE_NODE;
NODE_subtype(p) = s;
BOX_width(p) = w;
EDGE_NODE_edge_dist(p) = 0;
return p;
}
void
out_what(int32_t p)
{
small_number j;
unsigned char old_setting;
switch (mem[p].b16.s0) {
case OPEN_NODE:
case WRITE_NODE:
case CLOSE_NODE:
if (doing_leaders)
break;
j = mem[p + 1].b32.s0;
if (mem[p].b16.s0 == WRITE_NODE) {
write_out(p);
break;
}
if (write_open[j])
ttstub_output_close(write_file[j]);
if (mem[p].b16.s0 == CLOSE_NODE) {
write_open[j] = false;
break;
}
/* By this point must be OPEN_NODE */
if (j >= 16)
break;
cur_name = mem[p + 1].b32.s1;
cur_area = mem[p + 2].b32.s0;
cur_ext = mem[p + 2].b32.s1;
if (length(cur_ext) == 0)
cur_ext = maketexstring(".tex");
pack_file_name(cur_name, cur_area, cur_ext);
write_file[j] = ttstub_output_open(name_of_file, 0);
if (write_file[j] == NULL)
_tt_abort("cannot open output file \"%s\"", name_of_file);
write_open[j] = true;
if (log_opened) {
old_setting = selector;
if (INTPAR(tracing_online) <= 0)
selector = SELECTOR_LOG_ONLY;
else
selector = SELECTOR_TERM_AND_LOG;
print_nl_cstr("\\openout");
print_int(j);
print_cstr(" = `");
print_file_name(cur_name, cur_area, cur_ext);
print_cstr("'.");
print_nl_cstr("");
print_ln();
selector = old_setting;
}
break;
case SPECIAL_NODE:
special_out(p);
break;
case LANGUAGE_NODE:
break;
default:
confusion("ext4");
break;
}
}
static void
dvi_native_font_def(internal_font_number f)
{
int32_t font_def_length, i;
dvi_out(DEFINE_NATIVE_FONT);
dvi_four(f - 1);
font_def_length = make_font_def(f);
for (i = 0; i < font_def_length; i++)
dvi_out(xdv_buffer[i]);
}
void
dvi_font_def(internal_font_number f)
{
pool_pointer k;
int32_t l;
if (font_area[f] == AAT_FONT_FLAG || font_area[f] == OTGR_FONT_FLAG)
dvi_native_font_def(f);
else {
if (f <= 256) {
dvi_out(FNT_DEF1);
dvi_out(f - 1);
} else {
dvi_out(FNT_DEF1 + 1);
dvi_out((f - 1) / 256);
dvi_out((f - 1) % 256);
}
dvi_out(font_check[f].s3);
dvi_out(font_check[f].s2);
dvi_out(font_check[f].s1);
dvi_out(font_check[f].s0);
dvi_four(font_size[f]);
dvi_four(font_dsize[f]);
dvi_out(length(font_area[f]));
l = 0;
k = str_start[(font_name[f]) - 65536L];
while ((l == 0) && (k < str_start[(font_name[f] + 1) - 65536L])) {
if (str_pool[k] == ':' )
l = k - str_start[(font_name[f]) - 65536L];
k++;
}
if (l == 0)
l = length(font_name[f]);
dvi_out(l);
{
register int32_t for_end;
k = str_start[(font_area[f]) - 65536L];
for_end = str_start[(font_area[f] + 1) - 65536L] - 1;
if (k <= for_end)
do {
dvi_out(str_pool[k]);
}
while (k++ < for_end);
}
{
register int32_t for_end;
k = str_start[(font_name[f]) - 65536L];
for_end = str_start[(font_name[f]) - 65536L] + l - 1;
if (k <= for_end)
do {
dvi_out(str_pool[k]);
}
while (k++ < for_end);
}
}
}
static void
movement(scaled_t w, eight_bits o)
{
small_number mstate;
int32_t p, q;
int32_t k;
q = get_node(MOVEMENT_NODE_SIZE);
mem[q + 1].b32.s1 = w;
mem[q + 2].b32.s1 = dvi_offset + dvi_ptr;
if (o == DOWN1) {
mem[q].b32.s1 = down_ptr;
down_ptr = q;
} else {
mem[q].b32.s1 = right_ptr;
right_ptr = q;
}
p = mem[q].b32.s1;
mstate = MOV_NONE_SEEN;
while (p != TEX_NULL) {
if (mem[p + 1].b32.s1 == w) { /*632:*/
switch (mstate + mem[p].b32.s0) {
case (MOV_NONE_SEEN + MOV_YZ_OK):
case (MOV_NONE_SEEN + MOV_Y_OK):
case (MOV_Z_SEEN + MOV_YZ_OK):
case (MOV_Z_SEEN + MOV_Y_OK):
if (mem[p + 2].b32.s1 < dvi_gone) {
goto not_found;
} else { /*633:*/
k = mem[p + 2].b32.s1 - dvi_offset;
if (k < 0)
k = k + DVI_BUF_SIZE;
dvi_buf[k] = dvi_buf[k] + 5;
mem[p].b32.s0 = MOV_Y_HERE;
goto found;
}
break;
case (MOV_NONE_SEEN + MOV_Z_OK):
case (MOV_Y_SEEN + MOV_YZ_OK):
case (MOV_Y_SEEN + MOV_Z_OK):
if (mem[p + 2].b32.s1 < dvi_gone) {
goto not_found;
} else { /*634:*/
k = mem[p + 2].b32.s1 - dvi_offset;
if (k < 0)
k = k + DVI_BUF_SIZE;
dvi_buf[k] = dvi_buf[k] + 10;
mem[p].b32.s0 = MOV_Z_HERE;
goto found;
}
break;
case (MOV_NONE_SEEN + MOV_Y_HERE):
case (MOV_NONE_SEEN + MOV_Z_HERE):
case (MOV_Y_SEEN + MOV_Z_HERE):
case (MOV_Z_SEEN + MOV_Y_HERE):
goto found;
break;
default:
break;
}
} else {
switch (mstate + mem[p].b32.s0) {
case (MOV_NONE_SEEN + MOV_Y_HERE):
mstate = MOV_Y_SEEN;
break;
case (MOV_NONE_SEEN + MOV_Z_HERE):
mstate = MOV_Z_SEEN;
break;
case (MOV_Y_SEEN + MOV_Z_HERE):
case (MOV_Z_SEEN + MOV_Y_HERE):
goto not_found;
break;
default:
break;
}
}
p = LLIST_link(p);
}
not_found:
mem[q].b32.s0 = MOV_YZ_OK;
if (abs(w) >= 0x800000) {
dvi_out(o + 3);
dvi_four(w);
return;
}
if (abs(w) >= 0x8000) {
dvi_out(o + 2);
if (w < 0)
w = w + 0x1000000;
dvi_out(w / 0x10000);
w = w % 0x10000;
goto lab2;
}
if (abs(w) >= 128) {
dvi_out(o + 1);
if (w < 0)
w = w + 0x10000;
goto lab2;
}
dvi_out(o);
if (w < 0)
w = w + 256;
goto lab1;
lab2:
dvi_out(w / 256);
lab1:
dvi_out(w % 256);
return;
found: /*629:*/
mem[q].b32.s0 = mem[p].b32.s0;
if (mem[q].b32.s0 == MOV_Y_HERE) {
dvi_out(o + 4);
while (mem[q].b32.s1 != p) {
q = LLIST_link(q);
switch (mem[q].b32.s0) {
case MOV_YZ_OK:
mem[q].b32.s0 = MOV_Z_OK;
break;
case MOV_Y_OK:
mem[q].b32.s0 = MOV_D_FIXED;
break;
}
}
} else {
dvi_out(o + 9);
while (mem[q].b32.s1 != p) {
q = LLIST_link(q);
switch (mem[q].b32.s0) {
case MOV_YZ_OK:
mem[q].b32.s0 = MOV_Y_OK;
break;
case MOV_Z_OK:
mem[q].b32.s0 = MOV_D_FIXED;
break;
}
}
}
}
static void
prune_movements(int32_t l)
{
int32_t p;
while (down_ptr != TEX_NULL) {
if (mem[down_ptr + 2].b32.s1 < l)
break;
p = down_ptr;
down_ptr = mem[p].b32.s1;
free_node(p, MOVEMENT_NODE_SIZE);
}
while (right_ptr != TEX_NULL) {
if (mem[right_ptr + 2].b32.s1 < l)
return;
p = right_ptr;
right_ptr = mem[p].b32.s1;
free_node(p, MOVEMENT_NODE_SIZE);
}
}
static void
special_out(int32_t p)
{
unsigned char /*max_selector */ old_setting;
pool_pointer k;
if (cur_h != dvi_h) {
movement(cur_h - dvi_h, RIGHT1);
dvi_h = cur_h;
}
if (cur_v != dvi_v) {
movement(cur_v - dvi_v, DOWN1);
dvi_v = cur_v;
}
doing_special = true;
old_setting = selector;
selector = SELECTOR_NEW_STRING ;
show_token_list(mem[mem[p + 1].b32.s1].b32.s1, TEX_NULL, pool_size - pool_ptr);
selector = old_setting;
if (pool_ptr + 1 > pool_size)
overflow("pool size", pool_size - init_pool_ptr);
if (cur_length() < 256) {
dvi_out(XXX1);
dvi_out(cur_length());
} else {
dvi_out(XXX4);
dvi_four(cur_length());
}
{
register int32_t for_end;
k = str_start[str_ptr - TOO_BIG_CHAR];
for_end = pool_ptr - 1;
if (k <= for_end)
do {
dvi_out(str_pool[k]);
}
while (k++ < for_end);
}
pool_ptr = str_start[str_ptr - TOO_BIG_CHAR];
doing_special = false;
}
static void
write_out(int32_t p)
{
unsigned char old_setting; /* max_selector enum */
int32_t old_mode;
small_number j;
int32_t q, r;
int32_t d;
q = get_avail();
mem[q].b32.s0 = (RIGHT_BRACE_TOKEN + '}' );
r = get_avail();
mem[q].b32.s1 = r;
mem[r].b32.s0 = CS_TOKEN_FLAG + END_WRITE;
begin_token_list(q, INSERTED);
begin_token_list(mem[p + 1].b32.s1, WRITE_TEXT);
q = get_avail();
mem[q].b32.s0 = (LEFT_BRACE_TOKEN + '{' );
begin_token_list(q, INSERTED);
old_mode = cur_list.mode;
cur_list.mode = 0;
cur_cs = write_loc;
q = scan_toks(false, true);
get_token();
if (cur_tok != CS_TOKEN_FLAG + END_WRITE) { /*1412:*/
if (file_line_error_style_p)
print_file_line();
else
print_nl_cstr("! ");
print_cstr("Unbalanced write command");
help_ptr = 2;
help_line[1] = "On this page there's a \\write with fewer real {'s than }'s.";
help_line[0] = "I can't handle that very well; good luck.";
error();
do {
get_token();
} while (cur_tok != CS_TOKEN_FLAG + END_WRITE);
}
cur_list.mode = old_mode;
end_token_list();
old_setting = selector;
j = mem[p + 1].b32.s0;
if (j == 18) {
selector = SELECTOR_NEW_STRING;
} else if (write_open[j]) {
selector = j;
} else {
if (j == 17 && selector == SELECTOR_TERM_AND_LOG)
selector = SELECTOR_LOG_ONLY;
print_nl_cstr("");
}
token_show(def_ref);
print_ln();
flush_list(def_ref);
if (j == 18) {
if (INTPAR(tracing_online) <= 0)
selector = SELECTOR_LOG_ONLY;
else
selector = SELECTOR_TERM_AND_LOG;
if (!log_opened)
selector = SELECTOR_TERM_ONLY;
print_nl_cstr("runsystem(");
for (d = 0; d <= (cur_length()) - 1; d++)
print(str_pool[str_start[str_ptr - TOO_BIG_CHAR] + d]);
print_cstr(")...");
print_cstr("disabled");
print_char('.');
print_nl_cstr("");
print_ln();
pool_ptr = str_start[str_ptr - TOO_BIG_CHAR];
}
selector = old_setting;
}
static void
pic_out(int32_t p)
{
unsigned char /*max_selector */ old_setting;
int32_t i;
pool_pointer k;
if (cur_h != dvi_h) {
movement(cur_h - dvi_h, RIGHT1);
dvi_h = cur_h;
}
if (cur_v != dvi_v) {
movement(cur_v - dvi_v, DOWN1);
dvi_v = cur_v;
}
old_setting = selector;
selector = SELECTOR_NEW_STRING;
print_cstr("pdf:image ");
print_cstr("matrix ");
print_scaled(mem[p + 5].b32.s0);
print(' ');
print_scaled(mem[p + 5].b32.s1);
print(' ');
print_scaled(mem[p + 6].b32.s0);
print(' ');
print_scaled(mem[p + 6].b32.s1);
print(' ');
print_scaled(mem[p + 7].b32.s0);
print(' ');
print_scaled(mem[p + 7].b32.s1);
print(' ');
print_cstr("page ");
print_int(mem[p + 4].b16.s0);
print(' ');
switch (mem[p + 8].b16.s1) {
case 1:
print_cstr("pagebox cropbox ");
break;
case 2:
print_cstr("pagebox mediabox ");
break;
case 3:
print_cstr("pagebox bleedbox ");
break;
case 5:
print_cstr("pagebox artbox ");
break;
case 4:
print_cstr("pagebox trimbox ");
break;
default:
break;
}
print('(');
for (i = 0; i < PIC_NODE_path_len(p); i++)
print_raw_char(PIC_NODE_path(p)[i], true);
print(')');
selector = old_setting;
if (cur_length() < 256) {
dvi_out(XXX1);
dvi_out(cur_length());
} else {
dvi_out(XXX4);
dvi_four(cur_length());
}
for (k = str_start[str_ptr - TOO_BIG_CHAR]; k < pool_ptr; k++)
dvi_out(str_pool[k]);
pool_ptr = str_start[str_ptr - TOO_BIG_CHAR]; /* discard the string we just made */
}
void
finalize_dvi_file(void)
{
unsigned char k;
while (cur_s > -1) {
if (cur_s > 0) {
dvi_out(POP);
} else {
dvi_out(EOP);
total_pages++;
}
cur_s--;
}
if (total_pages == 0) {
print_nl_cstr("No pages of output.");
return;
}
if (cur_s == -2)
/* This happens when the DVI gets too big; a message has already been printed */
return;
dvi_out(POST);
dvi_four(last_bop);
last_bop = dvi_offset + dvi_ptr - 5;
dvi_four(25400000L); /* magic values: conversion ratio for sp */
dvi_four(473628672L); /* magic values: conversion ratio for sp */
prepare_mag();
dvi_four(INTPAR(mag));
dvi_four(max_v);
dvi_four(max_h);
dvi_out(max_push / 256);
dvi_out(max_push % 256);
dvi_out((total_pages / 256) % 256);
dvi_out(total_pages % 256);
while (font_ptr > FONT_BASE) {
if (font_used[font_ptr])
dvi_font_def(font_ptr);
font_ptr--;
}
dvi_out(POST_POST);
dvi_four(last_bop);
if (semantic_pagination_enabled)
dvi_out(SPX_ID_BYTE);
else
dvi_out(XDV_ID_BYTE);
k = 4 + (DVI_BUF_SIZE - dvi_ptr) % 4;
while (k > 0) {
dvi_out(223);
k--;
}
if (dvi_limit == HALF_BUF)
write_to_dvi(HALF_BUF, DVI_BUF_SIZE - 1);
if (dvi_ptr > TEX_INFINITY - dvi_offset) {
cur_s = -2;
fatal_error("dvi length exceeds 0x7FFFFFFF");
}
if (dvi_ptr > 0)
write_to_dvi(0, dvi_ptr - 1);
k = ttstub_output_close(dvi_file);
if (k == 0) {
print_nl_cstr("Output written on ");
print(output_file_name);
print_cstr(" (");
print_int(total_pages);
if (total_pages != 1)
print_cstr(" pages");
else
print_cstr(" page");
print_cstr(", ");
print_int(dvi_offset + dvi_ptr);
print_cstr(" bytes).");
} else {
print_nl_cstr("Error ");
print_int(k);
print_cstr(" (");
print_c_string(strerror(k));
print_cstr(") generating output;");
print_nl_cstr("file ");
print(output_file_name);
print_cstr(" may not be valid.");
/* XeTeX adds history = OUTPUT_FAILURE = 4 here; I'm not implementing that. */
}
}
static void
write_to_dvi(int32_t a, int32_t b)
{
int32_t n = b - a + 1;
if (ttstub_output_write (dvi_file, (char *) &dvi_buf[a], n) != n)
_tt_abort ("failed to write data to XDV file");
}
static void
dvi_swap(void)
{
if (dvi_ptr > (TEX_INFINITY - dvi_offset)) {
cur_s = -2;
fatal_error("dvi length exceeds 0x7FFFFFFF");
}
if (dvi_limit == DVI_BUF_SIZE) {
write_to_dvi(0, HALF_BUF - 1);
dvi_limit = HALF_BUF;
dvi_offset = dvi_offset + DVI_BUF_SIZE;
dvi_ptr = 0;
} else {
write_to_dvi(HALF_BUF, DVI_BUF_SIZE - 1);
dvi_limit = DVI_BUF_SIZE;
}
dvi_gone = dvi_gone + HALF_BUF;
}
static void
dvi_four(int32_t x)
{
if (x >= 0) {
dvi_out(x / 0x1000000);
} else {
x = x + 0x40000000;
x = x + 0x40000000;
dvi_out((x / 0x1000000) + 128);
}
x = x % 0x1000000;
dvi_out(x / 0x10000);
x = x % 0x10000;
dvi_out(x / 0x100);
dvi_out(x % 0x100);
}
static void
dvi_two(UTF16_code s)
{
dvi_out(s / 0x100);
dvi_out(s % 0x100);
}
static void
dvi_pop(int32_t l)
{
if (l == dvi_offset + dvi_ptr && dvi_ptr > 0)
dvi_ptr--;
else
dvi_out(POP);
}
|
fmgoncalves/tectonic
|
tectonic/dpx-error.c
|
/* This is dvipdfmx, an eXtended version of dvipdfm by <NAME>.
Copyright (C) 2002-2016 by <NAME> and <NAME>,
the dvipdfmx project team.
Copyright (C) 1998, 1999 by <NAME> <<EMAIL>>
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 "dpx-error.h"
#include <stdarg.h>
#include <stdio.h>
#include "core-bridge.h"
typedef enum _message_type {
DPX_MESG_INFO,
DPX_MESG_WARN,
} message_type_t;
static message_type_t _last_message_type = DPX_MESG_INFO;
static int _dpx_quietness = 0;
void
shut_up (int quietness)
{
_dpx_quietness = quietness;
}
static rust_output_handle_t _dpx_message_handle = NULL;
static char _dpx_message_buf[1024];
static rust_output_handle_t
_dpx_ensure_output_handle (void)
{
_dpx_message_handle = ttstub_output_open_stdout();
if (_dpx_message_handle == NULL)
_tt_abort("xdvipdfmx cannot get output logging handle?!");
return _dpx_message_handle;
}
PRINTF_FUNC(1, 0) static void
_dpx_print_to_stdout (const char *fmt, va_list argp, int warn)
{
int n;
n = vsnprintf(_dpx_message_buf, sizeof(_dpx_message_buf), fmt, argp);
/* n is the number of bytes the vsnprintf() wanted to write -- it might be
* bigger than sizeof(buf). */
if (n >= sizeof(_dpx_message_buf)) {
n = sizeof(_dpx_message_buf) - 1;
_dpx_message_buf[n] = '\0';
}
if (warn)
ttstub_issue_warning("%s", _dpx_message_buf);
ttstub_output_write(_dpx_ensure_output_handle(), _dpx_message_buf, n);
}
void
dpx_message (const char *fmt, ...)
{
va_list argp;
if (_dpx_quietness > 0)
return;
va_start(argp, fmt);
_dpx_print_to_stdout (fmt, argp, 0);
va_end(argp);
_last_message_type = DPX_MESG_INFO;
}
void
dpx_warning (const char *fmt, ...)
{
va_list argp;
if (_dpx_quietness > 1)
return;
if (_last_message_type == DPX_MESG_INFO)
ttstub_output_write(_dpx_ensure_output_handle(), "\n", 1);
ttstub_output_write(_dpx_ensure_output_handle(), "warning: ", 9);
va_start(argp, fmt);
_dpx_print_to_stdout (fmt, argp, 1);
va_end(argp);
ttstub_output_write(_dpx_ensure_output_handle(), "\n", 1);
_last_message_type = DPX_MESG_WARN;
}
|
fmgoncalves/tectonic
|
tectonic/dpx-tfm.c
|
/* This is dvipdfmx, an eXtended version of dvipdfm by <NAME>.
Copyright (C) 2002-2016 by <NAME> and <NAME>,
the dvipdfmx project team.
Copyright (C) 1998, 1999 by <NAME> <<EMAIL>>
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 "dpx-tfm.h"
#include <fcntl.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include "core-bridge.h"
#include "dpx-dpxutil.h"
#include "dpx-error.h"
#include "dpx-mem.h"
#include "dpx-numbers.h"
#define TFM_FORMAT 1
#define OFM_FORMAT 2
#define FWBASE ((double) (1<<20))
static int verbose = 0;
#define CHARACTER_INDEX(i) ((i))
/*
* TFM Record structure:
* Multiple TFM's may be read in at once.
*/
struct tfm_font
{
int32_t level;
uint32_t wlenfile;
uint32_t wlenheader;
uint32_t bc, ec;
uint32_t nwidths, nheights, ndepths;
uint32_t nitcor, nlig, nkern, nextens;
uint32_t nfonparm;
uint32_t fontdir;
uint32_t nco, ncw, npc;
fixword *header;
uint32_t *char_info;
unsigned short *width_index;
unsigned char *height_index;
unsigned char *depth_index;
fixword *width;
fixword *height;
fixword *depth;
};
static void
tfm_font_init (struct tfm_font *tfm)
{
tfm->header = NULL;
tfm->level = 0;
tfm->fontdir = 0;
tfm->nco = tfm->ncw = tfm->npc = 0;
tfm->char_info = NULL;
tfm->width_index = NULL;
tfm->height_index = NULL;
tfm->depth_index = NULL;
tfm->width = tfm->height = tfm->depth = NULL;
}
static void
tfm_font_clear (struct tfm_font *tfm)
{
if (tfm) {
tfm->header = mfree(tfm->header);
tfm->char_info = mfree(tfm->char_info);
tfm->width = mfree(tfm->width);
tfm->height = mfree(tfm->height);
tfm->depth = mfree(tfm->depth);
tfm->width_index = mfree(tfm->width_index);
tfm->height_index = mfree(tfm->height_index);
tfm->depth_index = mfree(tfm->depth_index);
}
}
struct coverage
{
int first_char;
int num_chars;
};
/*
* All characters in the same range have same metrics.
*/
struct range_map {
unsigned short num_coverages;
struct coverage *coverages;
unsigned short *indices;
};
/* Special case of num_coverages = 1 */
struct char_map
{
struct coverage coverage;
unsigned short *indices;
};
static void
release_char_map (struct char_map *map)
{
map->indices = mfree(map->indices);
free(map);
}
static void
release_range_map (struct range_map *map)
{
free(map->coverages);
free(map->indices);
map->coverages = NULL;
map->indices = NULL;
free(map);
}
static int
lookup_char (const struct char_map *map, int charcode)
{
if (charcode >= map->coverage.first_char &&
charcode <= map->coverage.first_char + map->coverage.num_chars)
return map->indices[CHARACTER_INDEX(charcode - map->coverage.first_char)];
else
return -1;
}
static int
lookup_range (const struct range_map *map, int charcode)
{
int idx;
for (idx = map->num_coverages - 1; idx >= 0 &&
charcode >= map->coverages[idx].first_char; idx--) {
if (charcode <=
map->coverages[idx].first_char + map->coverages[idx].num_chars)
return map->indices[CHARACTER_INDEX(idx)];
}
return -1;
}
#define SOURCE_TYPE_TFM 0
#define SOURCE_TYPE_JFM 1
#define SOURCE_TYPE_OFM 2
#define MAPTYPE_NONE 0
#define MAPTYPE_CHAR 1
#define MAPTYPE_RANGE 2
#define FONT_DIR_HORIZ 0
#define FONT_DIR_VERT 1
struct font_metric
{
char *tex_name;
fixword designsize;
char *codingscheme;
int fontdir;
int firstchar, lastchar;
fixword *widths;
fixword *heights;
fixword *depths;
struct {
int type;
void *data;
} charmap;
int source;
};
static void
fm_init (struct font_metric *fm)
{
fm->tex_name = NULL;
fm->firstchar = 0;
fm->lastchar = 0;
fm->fontdir = FONT_DIR_HORIZ;
fm->codingscheme = NULL;
fm->designsize = 0;
fm->widths = NULL;
fm->heights = NULL;
fm->depths = NULL;
fm->charmap.type = MAPTYPE_NONE;
fm->charmap.data = NULL;
fm->source = SOURCE_TYPE_TFM;
}
static void
fm_clear (struct font_metric *fm)
{
if (fm) {
free(fm->tex_name);
free(fm->widths);
free(fm->heights);
free(fm->depths);
free(fm->codingscheme);
switch (fm->charmap.type) {
case MAPTYPE_CHAR:
release_char_map(fm->charmap.data);
break;
case MAPTYPE_RANGE:
release_range_map(fm->charmap.data);
break;
}
}
}
#ifndef MAX_FONTS
#define MAX_FONTS 16
#endif
static struct font_metric *fms = NULL;
static unsigned int numfms = 0, max_fms = 0;
void
tfm_reset_global_state(void)
{
fms = NULL;
numfms = 0, max_fms = 0;
}
static void
fms_need (unsigned n)
{
if (n > max_fms) {
max_fms = MAX(max_fms + MAX_FONTS, n);
fms = RENEW(fms, max_fms, struct font_metric);
}
}
void
tfm_set_verbose (int level)
{
verbose = level;
}
static int
fread_fwords (fixword *words, uint32_t nmemb, rust_input_handle_t handle)
{
uint32_t i;
for (i = 0; i < nmemb; i++)
words[i] = tt_get_signed_quad(handle);
return nmemb * 4;
}
static int
fread_uquads (uint32_t *quads, uint32_t nmemb, rust_input_handle_t handle)
{
uint32_t i;
for (i = 0; i < nmemb; i++)
quads[i] = tt_get_unsigned_quad(handle);
return nmemb * 4;
}
/*
* TFM and JFM
*/
static void
tfm_check_size (struct tfm_font *tfm, off_t tfm_file_size)
{
uint32_t expected_size = 6;
/* Removed the warning message caused by EC TFM metric files.
*
if (tfm->wlenfile != tfm_file_size / 4) {
dpx_warning("TFM file size is %ld bytes but it says it is %ld bytes!",
tfm_file_size, tfm->wlenfile * 4);
if (tfm_file_size > tfm->wlenfile * 4) {
dpx_warning("Proceeding nervously...");
} else {
_tt_abort("Can't proceed...");
}
}
*/
if ((int64_t)tfm_file_size < (int64_t)tfm->wlenfile * 4) {
_tt_abort("Can't proceed...");
}
expected_size += (tfm->ec - tfm->bc + 1);
expected_size += tfm->wlenheader;
expected_size += tfm->nwidths;
expected_size += tfm->nheights;
expected_size += tfm->ndepths;
expected_size += tfm->nitcor;
expected_size += tfm->nlig;
expected_size += tfm->nkern;
expected_size += tfm->nextens;
expected_size += tfm->nfonparm;
if (expected_size != tfm->wlenfile) {
dpx_warning("TFM file size is expected to be %" PRId64 " bytes but it says it is %" PRId64 "bytes!",
(int64_t)expected_size * 4, (int64_t)tfm->wlenfile * 4);
if ((int64_t)tfm_file_size > (int64_t)expected_size *4) {
dpx_warning("Proceeding nervously...");
} else {
_tt_abort("Can't proceed...");
}
}
}
static void
tfm_get_sizes (rust_input_handle_t tfm_handle, off_t tfm_file_size, struct tfm_font *tfm)
{
tfm->wlenfile = tt_get_unsigned_pair(tfm_handle);
tfm->wlenheader = tt_get_unsigned_pair(tfm_handle);
tfm->bc = tt_get_unsigned_pair(tfm_handle);
tfm->ec = tt_get_unsigned_pair(tfm_handle);
if (tfm->ec < tfm->bc)
_tt_abort("TFM file error: ec(%u) < bc(%u) ???", tfm->ec, tfm->bc);
tfm->nwidths = tt_get_unsigned_pair(tfm_handle);
tfm->nheights = tt_get_unsigned_pair(tfm_handle);
tfm->ndepths = tt_get_unsigned_pair(tfm_handle);
tfm->nitcor = tt_get_unsigned_pair(tfm_handle);
tfm->nlig = tt_get_unsigned_pair(tfm_handle);
tfm->nkern = tt_get_unsigned_pair(tfm_handle);
tfm->nextens = tt_get_unsigned_pair(tfm_handle);
tfm->nfonparm = tt_get_unsigned_pair(tfm_handle);
tfm_check_size(tfm, tfm_file_size);
return;
}
static void
tfm_unpack_arrays (struct font_metric *fm, struct tfm_font *tfm)
{
uint32_t charinfo;
unsigned short width_index;
unsigned char height_index, depth_index;
uint32_t i;
fm->widths = NEW(256, fixword);
fm->heights = NEW(256, fixword);
fm->depths = NEW(256, fixword);
for (i = 0; i < 256; i++) {
fm->widths [i] = 0;
fm->heights[i] = 0;
fm->depths [i] = 0;
}
for (i = tfm->bc; i <= tfm->ec; i++ ) {
charinfo = tfm->char_info[i - tfm->bc];
width_index = (charinfo >> 24);
height_index = (charinfo >> 20) & 0xf;
depth_index = (charinfo >> 16) & 0xf;
fm->widths [i] = tfm->width [width_index];
fm->heights[i] = tfm->height[height_index];
fm->depths [i] = tfm->depth [depth_index];
}
return;
}
static int
sput_bigendian (char *s, int32_t v, int n)
{
int i;
for (i = n-1; i >= 0; i--) {
s[i] = (char) (v & 0xff);
v >>= 8;
}
return n;
}
static void
tfm_unpack_header (struct font_metric *fm, struct tfm_font *tfm)
{
if (tfm->wlenheader < 12) {
fm->codingscheme = NULL;
} else {
int i, len;
char *p;
len = (tfm->header[2] >> 24);
if (len < 0 || len > 39)
_tt_abort("Invalid TFM header.");
if (len > 0) {
fm->codingscheme = NEW(40, char);
p = fm->codingscheme;
p += sput_bigendian(p, tfm->header[2], 3);
for (i = 1; i <= len / 4; i++) {
p += sput_bigendian(p, tfm->header[2+i], 4);
}
fm->codingscheme[len] = '\0';
} else {
fm->codingscheme = NULL;
}
}
fm->designsize = tfm->header[1];
}
static void
ofm_check_size_one (struct tfm_font *tfm, off_t ofm_file_size)
{
uint32_t ofm_size = 14;
ofm_size += 2 * (tfm->ec - tfm->bc + 1);
ofm_size += tfm->wlenheader;
ofm_size += tfm->nwidths;
ofm_size += tfm->nheights;
ofm_size += tfm->ndepths;
ofm_size += tfm->nitcor;
ofm_size += 2 * tfm->nlig;
ofm_size += tfm->nkern;
ofm_size += 2 * tfm->nextens;
ofm_size += tfm->nfonparm;
if (tfm->wlenfile != ofm_file_size / 4 || tfm->wlenfile != ofm_size)
_tt_abort("OFM file problem. Table sizes don't agree.");
}
static void
ofm_get_sizes (rust_input_handle_t ofm_handle, off_t ofm_file_size, struct tfm_font *tfm)
{
tfm->level = tt_get_signed_quad(ofm_handle);
tfm->wlenfile = tt_get_positive_quad(ofm_handle, "OFM", "wlenfile");
tfm->wlenheader = tt_get_positive_quad(ofm_handle, "OFM", "wlenheader");
tfm->bc = tt_get_positive_quad(ofm_handle, "OFM", "bc");
tfm->ec = tt_get_positive_quad(ofm_handle, "OFM", "ec");
if (tfm->ec < tfm->bc)
_tt_abort("OFM file error: ec(%u) < bc(%u) ???", tfm->ec, tfm->bc);
tfm->nwidths = tt_get_positive_quad(ofm_handle, "OFM", "nwidths");
tfm->nheights = tt_get_positive_quad(ofm_handle, "OFM", "nheights");
tfm->ndepths = tt_get_positive_quad(ofm_handle, "OFM", "ndepths");
tfm->nitcor = tt_get_positive_quad(ofm_handle, "OFM", "nitcor");
tfm->nlig = tt_get_positive_quad(ofm_handle, "OFM", "nlig");
tfm->nkern = tt_get_positive_quad(ofm_handle, "OFM", "nkern");
tfm->nextens = tt_get_positive_quad(ofm_handle, "OFM", "nextens");
tfm->nfonparm = tt_get_positive_quad(ofm_handle, "OFM", "nfonparm");
tfm->fontdir = tt_get_positive_quad(ofm_handle, "OFM", "fontdir");
if (tfm->fontdir)
dpx_warning("I may be interpreting a font direction incorrectly.");
if (tfm->level == 0) {
ofm_check_size_one(tfm, ofm_file_size);
} else if (tfm->level == 1) {
tfm->nco = tt_get_positive_quad(ofm_handle, "OFM", "nco");
tfm->ncw = tt_get_positive_quad(ofm_handle, "OFM", "nco");
tfm->npc = tt_get_positive_quad(ofm_handle, "OFM", "npc");
ttstub_input_seek(ofm_handle, 4 * (off_t)(tfm->nco - tfm->wlenheader), SEEK_SET);
} else {
_tt_abort("can't handle OFM files with level > 1");
}
}
static void
ofm_do_char_info_zero (rust_input_handle_t ofm_handle, struct tfm_font *tfm)
{
uint32_t num_chars;
num_chars = tfm->ec - tfm->bc + 1;
if (num_chars != 0) {
uint32_t i;
tfm->width_index = NEW(num_chars, unsigned short);
tfm->height_index = NEW(num_chars, unsigned char);
tfm->depth_index = NEW(num_chars, unsigned char);
for (i = 0; i < num_chars; i++) {
tfm->width_index [i] = tt_get_unsigned_pair(ofm_handle);
tfm->height_index[i] = tt_get_unsigned_byte(ofm_handle);
tfm->depth_index [i] = tt_get_unsigned_byte(ofm_handle);
/* Ignore remaining quad */
tt_skip_bytes(4, ofm_handle);
}
}
}
static void
ofm_do_char_info_one (rust_input_handle_t ofm_handle, struct tfm_font *tfm)
{
uint32_t num_char_infos;
uint32_t num_chars;
num_char_infos = tfm->ncw / (3 + (tfm->npc / 2));
num_chars = tfm->ec - tfm ->bc + 1;
if (num_chars != 0) {
uint32_t i;
uint32_t char_infos_read;
tfm->width_index = NEW(num_chars, unsigned short);
tfm->height_index = NEW(num_chars, unsigned char);
tfm->depth_index = NEW(num_chars, unsigned char);
char_infos_read = 0;
for (i = 0; i < num_chars && char_infos_read < num_char_infos; i++) {
uint32_t repeats, j;
tfm->width_index [i] = tt_get_unsigned_pair(ofm_handle);
tfm->height_index[i] = tt_get_unsigned_byte(ofm_handle);
tfm->depth_index [i] = tt_get_unsigned_byte(ofm_handle);
/* Ignore next quad */
tt_skip_bytes(4, ofm_handle);
repeats = tt_get_unsigned_pair(ofm_handle);
/* Skip params */
for (j = 0; j < tfm->npc; j++)
tt_get_unsigned_pair(ofm_handle);
/* Remove word padding if necessary */
if (ISEVEN(tfm->npc))
tt_get_unsigned_pair(ofm_handle);
char_infos_read++;
if (i + repeats > num_chars)
_tt_abort("OFM \"repeats\" causes number of characters to be exceeded.");
for (j = 0; j < repeats; j++) {
tfm->width_index [i+j+1] = tfm->width_index [i];
tfm->height_index[i+j+1] = tfm->height_index[i];
tfm->depth_index [i+j+1] = tfm->depth_index [i];
}
/* Skip ahead because we have already handled repeats */
i += repeats;
}
}
}
static void
ofm_unpack_arrays (struct font_metric *fm, struct tfm_font *tfm, uint32_t num_chars)
{
uint32_t i;
fm->widths = NEW(tfm->bc + num_chars, fixword);
fm->heights = NEW(tfm->bc + num_chars, fixword);
fm->depths = NEW(tfm->bc + num_chars, fixword);
for (i = 0; i < num_chars; i++) {
fm->widths [tfm->bc + i] = tfm->width [ tfm->width_index [i] ];
fm->heights[tfm->bc + i] = tfm->height[ tfm->height_index[i] ];
fm->depths [tfm->bc + i] = tfm->depth [ tfm->depth_index [i] ];
}
}
static void
read_ofm (struct font_metric *fm, rust_input_handle_t ofm_handle, off_t ofm_file_size)
{
struct tfm_font tfm;
tfm_font_init(&tfm);
ofm_get_sizes(ofm_handle, ofm_file_size, &tfm);
if (tfm.level < 0 || tfm.level > 1)
_tt_abort("OFM level %d not supported.", tfm.level);
if (tfm.wlenheader > 0) {
tfm.header = NEW(tfm.wlenheader, fixword);
fread_fwords(tfm.header, tfm.wlenheader, ofm_handle);
}
if (tfm.level == 0)
ofm_do_char_info_zero(ofm_handle, &tfm);
else if (tfm.level == 1)
ofm_do_char_info_one(ofm_handle, &tfm);
if (tfm.nwidths > 0) {
tfm.width = NEW(tfm.nwidths, fixword);
fread_fwords(tfm.width, tfm.nwidths, ofm_handle);
}
if (tfm.nheights > 0) {
tfm.height = NEW(tfm.nheights, fixword);
fread_fwords(tfm.height, tfm.nheights, ofm_handle);
}
if (tfm.ndepths > 0) {
tfm.depth = NEW(tfm.ndepths, fixword);
fread_fwords(tfm.depth, tfm.ndepths, ofm_handle);
}
ofm_unpack_arrays(fm, &tfm, tfm.ec - tfm.bc + 1);
tfm_unpack_header(fm, &tfm);
fm->firstchar = tfm.bc;
fm->lastchar = tfm.ec;
fm->source = SOURCE_TYPE_OFM;
tfm_font_clear(&tfm);
}
static void
read_tfm (struct font_metric *fm, rust_input_handle_t tfm_handle, off_t tfm_file_size)
{
struct tfm_font tfm;
tfm_font_init(&tfm);
tfm_get_sizes(tfm_handle, tfm_file_size, &tfm);
fm->firstchar = tfm.bc;
fm->lastchar = tfm.ec;
if (tfm.wlenheader > 0) {
tfm.header = NEW(tfm.wlenheader, fixword);
fread_fwords(tfm.header, tfm.wlenheader, tfm_handle);
}
if (tfm.ec - tfm.bc + 1 > 0) {
tfm.char_info = NEW(tfm.ec - tfm.bc + 1, uint32_t);
fread_uquads(tfm.char_info, tfm.ec - tfm.bc + 1, tfm_handle);
}
if (tfm.nwidths > 0) {
tfm.width = NEW(tfm.nwidths, fixword);
fread_fwords(tfm.width, tfm.nwidths, tfm_handle);
}
if (tfm.nheights > 0) {
tfm.height = NEW(tfm.nheights, fixword);
fread_fwords(tfm.height, tfm.nheights, tfm_handle);
}
if (tfm.ndepths > 0) {
tfm.depth = NEW(tfm.ndepths, fixword);
fread_fwords(tfm.depth, tfm.ndepths, tfm_handle);
}
tfm_unpack_arrays(fm, &tfm);
tfm_unpack_header(fm, &tfm);
tfm_font_clear(&tfm);
return;
}
int
tfm_open (const char *tfm_name, int must_exist)
{
rust_input_handle_t tfm_handle = NULL;
int i, format = TFM_FORMAT;
off_t tfm_file_size;
char *ofm_name, *suffix;
for (i = 0; i < numfms; i++) {
if (streq_ptr(tfm_name, fms[i].tex_name))
return i;
}
/* NOTE: the following comment is no longer operative with the switch to
* the Tectonic I/O system since we don't have `must_exist`. The logic
* of the current implementation might not be right; to be investigated.
* Comment preserved for posterity.
*
* "The procedure to search tfm or ofm files:
* 1. Search tfm file with the given name with the must_exist flag unset.
* 2. Search ofm file with the given name with the must_exist flag unset.
* 3. If not found and must_exist flag is set, try again to search
* tfm file with the must_exist flag set.
* 4. If not found and must_exist flag is not set, return -1.
*
* We first look for OFM and then TFM.
* The reason for this change is incompatibility introduced when dvipdfmx
* started to write correct glyph metrics to output PDF for CID fonts.
* I'll not explain this in detail... This change is mostly specific to
* Japanese support."
*/
suffix = strrchr(tfm_name, '.');
if (!suffix || (strcmp(suffix, ".tfm") != 0 && strcmp(suffix, ".ofm") != 0)) {
ofm_name = NEW(strlen(tfm_name) + strlen(".ofm") + 1, char);
strcpy(ofm_name, tfm_name);
strcat(ofm_name, ".ofm");
} else {
ofm_name = NULL;
}
if (ofm_name && (tfm_handle = ttstub_input_open(ofm_name, TTIF_OFM, 0)) != NULL) {
format = OFM_FORMAT;
} else if ((tfm_handle = ttstub_input_open(tfm_name, TTIF_TFM, 0)) != NULL) {
format = TFM_FORMAT;
} else if ((tfm_handle = ttstub_input_open(tfm_name, TTIF_OFM, 0)) != NULL) {
format = OFM_FORMAT;
}
free(ofm_name);
if (tfm_handle == NULL) {
if (must_exist)
_tt_abort("Unable to find TFM file \"%s\".", tfm_name);
return -1;
}
if (verbose) {
if (format == TFM_FORMAT)
dpx_message("(TFM:%s", tfm_name);
else if (format == OFM_FORMAT)
dpx_message("(OFM:%s", tfm_name);
}
tfm_file_size = ttstub_input_get_size (tfm_handle);
if (tfm_file_size > 0x1FFFFFFFF)
_tt_abort("TFM/OFM file size exceeds 33-bit");
if (tfm_file_size < 24)
_tt_abort("TFM/OFM file too small to be a valid file.");
fms_need(numfms + 1);
fm_init(fms + numfms);
if (format == OFM_FORMAT)
read_ofm(&fms[numfms], tfm_handle, tfm_file_size);
else
read_tfm(&fms[numfms], tfm_handle, tfm_file_size);
ttstub_input_close(tfm_handle);
fms[numfms].tex_name = NEW(strlen(tfm_name)+1, char);
strcpy(fms[numfms].tex_name, tfm_name);
if (verbose)
dpx_message(")");
return numfms++;
}
void
tfm_close_all (void)
{
unsigned int i;
if (fms) {
for (i = 0; i < numfms; i++) {
fm_clear(&(fms[i]));
}
free(fms);
}
}
#define CHECK_ID(n) do { \
if ((n) < 0 || (n) >= numfms) \
_tt_abort("TFM: Invalid TFM ID: %d", (n)); \
} while (0)
fixword
tfm_get_fw_width (int font_id, int32_t ch)
{
struct font_metric *fm;
int idx = 0;
CHECK_ID(font_id);
fm = &(fms[font_id]);
if (ch >= fm->firstchar && ch <= fm->lastchar) {
switch (fm->charmap.type) {
case MAPTYPE_CHAR:
idx = lookup_char(fm->charmap.data, ch);
if (idx < 0)
_tt_abort("Invalid char: %" PRId32 "\n", ch);
break;
case MAPTYPE_RANGE:
idx = lookup_range(fm->charmap.data, ch);
if (idx < 0)
_tt_abort("Invalid char: %" PRId32 "\n", ch);
break;
default:
idx = ch;
}
} else {
_tt_abort("Invalid char: %" PRId32 "\n", ch);
}
return fm->widths[idx];
}
fixword
tfm_get_fw_height (int font_id, int32_t ch)
{
struct font_metric *fm;
int idx = 0;
CHECK_ID(font_id);
fm = &(fms[font_id]);
if (ch >= fm->firstchar && ch <= fm->lastchar) {
switch (fm->charmap.type) {
case MAPTYPE_CHAR:
idx = lookup_char(fm->charmap.data, ch);
if (idx < 0)
_tt_abort("Invalid char: %" PRId32 "\n", ch);
break;
case MAPTYPE_RANGE:
idx = lookup_range(fm->charmap.data, ch);
if (idx < 0)
_tt_abort("Invalid char: %" PRId32 "\n", ch);
break;
default:
idx = ch;
}
} else {
_tt_abort("Invalid char: %" PRId32 "\n", ch);
}
return fm->heights[idx];
}
fixword
tfm_get_fw_depth (int font_id, int32_t ch)
{
struct font_metric *fm;
int idx = 0;
CHECK_ID(font_id);
fm = &(fms[font_id]);
if (ch >= fm->firstchar && ch <= fm->lastchar) {
switch (fm->charmap.type) {
case MAPTYPE_CHAR:
idx = lookup_char(fm->charmap.data, ch);
if (idx < 0)
_tt_abort("Invalid char: %" PRId32 "\n", ch);
break;
case MAPTYPE_RANGE:
idx = lookup_range(fm->charmap.data, ch);
if (idx < 0)
_tt_abort("Invalid char: %" PRId32 "\n", ch);
break;
default:
idx = ch;
}
} else {
_tt_abort("Invalid char: %" PRId32 "\n", ch);
}
return fm->depths[idx];
}
/*
* tfm_get_width returns the width of the font
* as a (double) fraction of the design size.
*/
double
tfm_get_width (int font_id, int32_t ch)
{
return ((double) tfm_get_fw_width(font_id, ch)/FWBASE);
}
/* tfm_string_xxx() do not work for OFM... */
fixword
tfm_string_width (int font_id, const unsigned char *s, unsigned len)
{
fixword result = 0;
unsigned int i;
CHECK_ID(font_id);
for (i = 0; i < len; i++) {
result += tfm_get_fw_width(font_id, s[i]);
}
return result;
}
double
tfm_get_design_size (int font_id)
{
CHECK_ID(font_id);
return (double) (fms[font_id].designsize)/FWBASE*(72.0/72.27);
}
bool
tfm_exists (const char *tfm_name)
{
rust_input_handle_t *handle;
handle = ttstub_input_open(tfm_name, TTIF_OFM, 0);
if (handle) {
ttstub_input_close(handle);
return true;
}
handle = ttstub_input_open(tfm_name, TTIF_TFM, 0);
if (handle) {
ttstub_input_close(handle);
return true;
}
return false;
}
|
fmgoncalves/tectonic
|
tectonic/core-bridge.c
|
<gh_stars>0
/* tectonic/core-bridge.c: the C/C++ => Rust bridge
Copyright 2017 the Tectonic Project
Licensed under the MIT License.
*/
#include "core-bridge.h"
#include <setjmp.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h> /*vsnprintf*/
/* TODO: these are needed for the various *_main routines which should
* probably be moved out into other files. */
#include "bibtex.h"
#include "dpx-dvipdfmx.h"
#include "xetex-xetexd.h"
/* The global variable that represents the Rust API. Some fine day we'll get
* rid of all of the globals ... */
static tt_bridge_api_t *tectonic_global_bridge = NULL;
/* Highest-level abort/error handling. */
#define BUF_SIZE 1024
static jmp_buf jump_buffer;
static char error_buf[BUF_SIZE] = "";
NORETURN PRINTF_FUNC(1,2) int
_tt_abort(const char *format, ...)
{
va_list ap;
va_start(ap, format);
vsnprintf(error_buf, BUF_SIZE, format, ap);
va_end(ap);
longjmp(jump_buffer, 1);
}
const char *
tt_get_error_message(void)
{
return error_buf;
}
/* Running the actual engines. Those code needs to be centralized for unified
* setjmp aborts and error message extraction. */
int
tex_simple_main(tt_bridge_api_t *api, char *dump_name, char *input_file_name, time_t build_date)
{
int rv;
tectonic_global_bridge = api;
if (setjmp(jump_buffer)) {
tectonic_global_bridge = NULL;
return HISTORY_FATAL_ERROR;
}
rv = tt_run_engine(dump_name, input_file_name, build_date);
tectonic_global_bridge = NULL;
return rv;
}
int
dvipdfmx_simple_main(tt_bridge_api_t *api, char *dviname, char *pdfname, bool compress, bool deterministic_tags, time_t build_date)
{
int rv;
tectonic_global_bridge = api;
if (setjmp(jump_buffer)) {
tectonic_global_bridge = NULL;
return 99;
}
rv = dvipdfmx_main(pdfname, dviname, NULL, 0, false, compress, deterministic_tags, false, 0, build_date);
tectonic_global_bridge = NULL;
return rv;
}
int
bibtex_simple_main(tt_bridge_api_t *api, char *aux_file_name)
{
int rv;
tectonic_global_bridge = api;
if (setjmp(jump_buffer)) {
tectonic_global_bridge = NULL;
return 99;
}
rv = bibtex_main(aux_file_name);
tectonic_global_bridge = NULL;
return rv;
}
/* Global symbols that route through the global API */
#define TGB tectonic_global_bridge
PRINTF_FUNC(1,2) void
ttstub_issue_warning(const char *format, ...)
{
va_list ap;
va_start(ap, format);
vsnprintf(error_buf, BUF_SIZE, format, ap); /* Not ideal to (ab)use error_buf here */
va_end(ap);
TGB->issue_warning(TGB->context, error_buf);
}
PRINTF_FUNC(1,2) void
ttstub_issue_error(const char *format, ...)
{
va_list ap;
va_start(ap, format);
vsnprintf(error_buf, BUF_SIZE, format, ap); /* Not ideal to (ab)use error_buf here */
va_end(ap);
TGB->issue_error(TGB->context, error_buf);
}
PRINTF_FUNC(2,3) int
ttstub_fprintf(rust_output_handle_t handle, const char *format, ...)
{
static char fprintf_buf[BUF_SIZE] = "";
va_list ap;
va_start(ap, format);
int len = vsnprintf(fprintf_buf, BUF_SIZE, format, ap);
va_end(ap);
if (len >= BUF_SIZE) {
len = BUF_SIZE - 1;
fprintf_buf[len] = '\0';
}
if (len >= 0) {
ttstub_output_write(handle, fprintf_buf, len);
}
return len;
}
int
ttstub_get_file_md5(char const *path, char *digest)
{
return TGB->get_file_md5(TGB->context, path, digest);
}
int
ttstub_get_data_md5(char const *data, size_t len, char *digest)
{
return TGB->get_data_md5(TGB->context, data, len, digest);
}
rust_output_handle_t
ttstub_output_open(char const *path, int is_gz)
{
return TGB->output_open(TGB->context, path, is_gz);
}
rust_output_handle_t
ttstub_output_open_stdout(void)
{
return TGB->output_open_stdout(TGB->context);
}
int
ttstub_output_putc(rust_output_handle_t handle, int c)
{
return TGB->output_putc(TGB->context, handle, c);
}
size_t
ttstub_output_write(rust_output_handle_t handle, const char *data, size_t len)
{
return TGB->output_write(TGB->context, handle, data, len);
}
int
ttstub_output_flush(rust_output_handle_t handle)
{
return TGB->output_flush(TGB->context, handle);
}
int
ttstub_output_close(rust_output_handle_t handle)
{
return TGB->output_close(TGB->context, handle);
}
rust_input_handle_t
ttstub_input_open(char const *path, tt_input_format_type format, int is_gz)
{
return TGB->input_open(TGB->context, path, format, is_gz);
}
rust_input_handle_t
ttstub_input_open_primary(void)
{
return TGB->input_open_primary(TGB->context);
}
size_t
ttstub_input_get_size(rust_input_handle_t handle)
{
return TGB->input_get_size(TGB->context, handle);
}
size_t
ttstub_input_seek(rust_input_handle_t handle, ssize_t offset, int whence)
{
int internal_error = 0;
size_t rv = TGB->input_seek(TGB->context, handle, offset, whence, &internal_error);
if (internal_error) {
// Nonzero indicates a serious internal error.
longjmp(jump_buffer, 1);
}
return rv;
}
ssize_t
ttstub_input_read(rust_input_handle_t handle, char *data, size_t len)
{
return TGB->input_read(TGB->context, handle, data, len);
}
int
ttstub_input_getc(rust_input_handle_t handle)
{
return TGB->input_getc(TGB->context, handle);
}
int
ttstub_input_ungetc(rust_input_handle_t handle, int ch)
{
return TGB->input_ungetc(TGB->context, handle, ch);
}
int
ttstub_input_close(rust_input_handle_t handle)
{
if (TGB->input_close(TGB->context, handle)) {
// Nonzero return value indicates a serious internal error.
longjmp(jump_buffer, 1);
}
return 0;
}
|
fmgoncalves/tectonic
|
tectonic/dpx-tt_glyf.h
|
<filename>tectonic/dpx-tt_glyf.h<gh_stars>1-10
/* This is dvipdfmx, an eXtended version of dvipdfm by <NAME>.
Copyright (C) 2002-2016 by <NAME> and <NAME>,
the dvipdfmx project team.
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.
*/
#ifndef _TT_GLYF_H_
#define _TT_GLYF_H_
#include "dpx-core.h"
#include "dpx-sfnt.h"
struct tt_glyph_desc
{
USHORT gid;
USHORT ogid; /* GID in original font */
USHORT advw, advh;
SHORT lsb, tsb;
SHORT llx, lly, urx, ury;
ULONG length;
BYTE *data;
};
struct tt_glyphs
{
USHORT num_glyphs;
USHORT max_glyphs;
USHORT last_gid;
USHORT emsize;
USHORT dw; /* optimal value for DW */
USHORT default_advh; /* default value */
SHORT default_tsb; /* default value */
struct tt_glyph_desc *gd;
unsigned char *used_slot;
};
struct tt_glyphs *tt_build_init (void);
void tt_build_finish (struct tt_glyphs *g);
USHORT tt_add_glyph (struct tt_glyphs *g, USHORT gid, USHORT new_gid);
USHORT tt_get_index (struct tt_glyphs *g, USHORT gid);
USHORT tt_find_glyph (struct tt_glyphs *g, USHORT gid);
int tt_build_tables (sfnt *sfont, struct tt_glyphs *g);
int tt_get_metrics (sfnt *sfont, struct tt_glyphs *g);
#endif /* _TT_GLYF_H_ */
|
fmgoncalves/tectonic
|
tectonic/dpx-t1_char.h
|
<filename>tectonic/dpx-t1_char.h
#ifndef _T1_CSTR_H_
#define _T1_CSTR_H_
#include "dpx-core.h"
#include "dpx-cff_types.h"
typedef struct {
int use_seac;
double wx, wy;
struct {
double llx, lly, urx, ury;
} bbox;
struct {
double asb, adx, ady;
card8 bchar, achar;
} seac;
} t1_ginfo;
int t1char_get_metrics (card8 *src, int srclen,
cff_index *subrs, t1_ginfo *ginfo);
int t1char_convert_charstring (card8 *dst, int dstlen,
card8 *src, int srclen,
cff_index *subrs,
double default_width, double nominal_width,
t1_ginfo *ginfo);
#endif /* _T1_CSTR_H_ */
|
fmgoncalves/tectonic
|
tectonic/xetex-scaledmath.c
|
<gh_stars>1-10
/* tectonic/xetex-scaledmath.c: low-level math functions
Copyright 2017 The Tectonic Project
Licensed under the MIT License.
*/
#include "xetex-core.h"
#include "xetex-xetexd.h"
int32_t
tex_round (double r)
{
/* We must reproduce very particular rounding semantics to pass the TRIP
* test. Specifically, values within the 32-bit range of TeX integers are
* rounded to the nearest integer with half-integral values going away
* from zero: 0.5 => 1, -0.5 => -1.
*
* `r` does not necessarily lie within the range of a 32-bit TeX integer;
* if it doesn't, we clip. The following LaTeX document allegedly triggers
* that codepath:
*
* \documentstyle{article}
* \begin{document}
* \begin{flushleft}
* $\hbox{} $\hfill
* \filbreak
* \eject
*
*/
if (r > 2147483647.0) /* 0x7FFFFFFF */
return 2147483647;
if (r < -2147483648.0) /* -0x80000000 */
return -2147483648;
/* ANSI defines the float-to-integer cast to truncate towards zero, so the
* following code is all that's necessary to get the desired behavior. The
* truncation technically causes an uncaught "inexact" floating-point
* exception, but exception is virtually impossible to avoid in real
* code. */
if (r >= 0.0)
return (int32_t) (r + 0.5);
return (int32_t) (r - 0.5);
}
int32_t
half(int32_t x)
{
if (odd(x))
return (x + 1) / 2;
return x / 2;
}
scaled_t
mult_and_add(int32_t n, scaled_t x, scaled_t y, scaled_t max_answer)
{
if (n < 0) {
x = -(int32_t) x;
n = -(int32_t) n;
}
if (n == 0)
return y;
else if (x <= (max_answer - y) / n && (-(int32_t) x <= (max_answer + y) / n))
return n * x + y;
else {
arith_error = true;
return 0;
}
}
scaled_t
x_over_n(scaled_t x, int32_t n)
{
if (n == 0) {
arith_error = true;
tex_remainder = x;
return 0;
} else {
if (n < 0) {
// negative
x = -(int32_t) x;
n = -(int32_t) n;
tex_remainder = -(int32_t) tex_remainder;
}
if (x >= 0) {
tex_remainder = x % n;
return x / n;
} else {
tex_remainder = -(int32_t) ((-(int32_t) x) % n);
return -(int32_t) ((-(int32_t) x) / n);
}
}
}
scaled_t
xn_over_d(scaled_t x, int32_t n, int32_t d)
{
bool positive;
int32_t t, u, v;
if (x >= 0)
positive = true;
else {
x = -(int32_t) x;
positive = false;
}
t = (x % 32768L) * n;
u = (x / 32768L) * n + (t / 32768L);
v = (u % d) * 32768L + (t % 32768L);
if (u / d >= 32768L)
arith_error = true;
else
u = 32768L * (u / d) + (v / d);
if (positive) {
tex_remainder = v % d;
return u;
} else {
tex_remainder = -(int32_t) (v % d);
return -(int32_t) u;
}
}
scaled_t
round_xn_over_d(scaled_t x, int32_t n, int32_t d)
{
bool positive;
int32_t t, u, v;
if (x >= 0) {
positive = true;
} else {
x = -(int32_t) x;
positive = false;
}
t = (x % 32768L) * n;
u = (x / 32768L) * n + (t / 32768L);
v = (u % d) * 32768L + (t % 32768L);
if (u / d >= 32768L)
arith_error = true;
else
u = 32768L * (u / d) + (v / d);
v = v % d;
if (2 * v >= d)
u++;
if (positive)
return u;
else
return -(int32_t) u;
}
|
fmgoncalves/tectonic
|
tectonic/core-memory.c
|
/* tectonic/core-memory.c: basic C dynamic memory helpers
Copyright 1993, 1994, 1995, 2008, 2009, 2010, 2011 <NAME>.
Copyright 1997, 2002, 2005 <NAME>.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, see <http://www.gnu.org/licenses/>. */
#include "core-foundation.h"
#include "core-bridge.h" /* _tt_abort */
#include "core-memory.h"
void *
xcalloc (size_t nelem, size_t elsize)
{
void *new_mem = calloc(nelem ? nelem : 1, elsize ? elsize : 1);
if (new_mem == NULL)
_tt_abort ("xcalloc request for %lu elements of size %lu failed",
(unsigned long) nelem, (unsigned long) elsize);
return new_mem;
}
void *
xmalloc (size_t size)
{
void *new_mem = malloc(size ? size : 1);
if (new_mem == NULL)
_tt_abort ("xmalloc request for %lu bytes failed", (unsigned long) size);
return new_mem;
}
void *
xrealloc (void *old_ptr, size_t size)
{
void *new_mem;
if (old_ptr == NULL) {
new_mem = xmalloc(size);
} else {
new_mem = realloc(old_ptr, size ? size : 1);
if (new_mem == NULL)
_tt_abort("xrealloc() to %lu bytes failed", (unsigned long) size);
}
return new_mem;
}
char *
xstrdup (const char *s)
{
char *new_string = xmalloc(strlen (s) + 1);
return strcpy(new_string, s);
}
|
fmgoncalves/tectonic
|
tectonic/core-memory.h
|
/* tectonic/core-memory.h: basic dynamic memory helpers
Copyright 2016-2018 the Tectonic Project
Licensed under the MIT License.
*/
#ifndef TECTONIC_CORE_MEMORY_H
#define TECTONIC_CORE_MEMORY_H
#include "core-foundation.h"
BEGIN_EXTERN_C
char *xstrdup (const char *s);
void *xmalloc (size_t size);
void *xrealloc (void *old_address, size_t new_size);
void *xcalloc (size_t nelem, size_t elsize);
static inline void *mfree(void *ptr) {
free(ptr);
return NULL;
}
END_EXTERN_C
#endif /* not TECTONIC_CORE_MEMORY_H */
|
fmgoncalves/tectonic
|
tectonic/dpx-core.h
|
<gh_stars>1-10
/* tectonic/dpx-core.h: core header for xdvipdvmx C code
Copyright 2018 the Tectonic Project
Licensed under the MIT License.
*/
#ifndef TECTONIC_DPX_CORE_H
#define TECTONIC_DPX_CORE_H
#include "core-foundation.h"
#include "core-bridge.h"
#include "core-memory.h"
#include "core-strutils.h"
#endif /* TECTONIC_DPX_CORE_H */
|
fmgoncalves/tectonic
|
tectonic/dpx-cs_type2.h
|
/* This is dvipdfmx, an eXtended version of dvipdfm by <NAME>.
Copyright (C) 2002-2016 by <NAME> and <NAME>,
the dvipdfmx project team.
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.
*/
#ifndef _CS_TYPE2_H_
#define _CS_TYPE2_H_
#include "dpx-core.h"
#include "dpx-cff_types.h"
typedef struct {
int flags; /* unused in Type 2 charstring */
double wx, wy;
struct {
double llx, lly, urx, ury;
} bbox;
struct {
double asb, adx, ady;
card8 bchar, achar;
} seac; /* unused in Type 2 charstring */
} cs_ginfo;
int cs_copy_charstring (card8 *dest, int destlen,
card8 *src, int srclen,
cff_index *gsubr, cff_index *subr,
double default_width, double nominal_width, cs_ginfo *ginfo);
#endif /* _CS_TYPE2_H_ */
|
sebastienvas/esp
|
src/api_manager/context/service_context.h
|
<reponame>sebastienvas/esp<filename>src/api_manager/context/service_context.h<gh_stars>0
/* Copyright (C) Extensible Service Proxy Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef API_MANAGER_CONTEXT_SERVICE_CONTEXT_H_
#define API_MANAGER_CONTEXT_SERVICE_CONTEXT_H_
#include "include/api_manager/method.h"
#include "src/api_manager/config.h"
#include "src/api_manager/context/global_context.h"
#include "src/api_manager/service_control/interface.h"
namespace google {
namespace api_manager {
namespace context {
// Shared context across request for every service
// Each RequestContext will hold a refcount to this object.
class ServiceContext {
public:
ServiceContext(std::shared_ptr<GlobalContext> global_context,
std::unique_ptr<Config> config);
// For unit-test only. It will create a global context
ServiceContext(std::unique_ptr<ApiManagerEnvInterface> env,
const std::string &server_config,
std::unique_ptr<Config> config);
bool Enabled() const { return RequireAuth() || service_control_; }
const std::string &service_name() const { return config_->service_name(); }
const ::google::api::Service &service() const { return config_->service(); }
Config *config() { return config_.get(); }
auth::ServiceAccountToken *service_account_token() {
return global_context_->service_account_token();
}
ApiManagerEnvInterface *env() { return global_context_->env(); }
MethodCallInfo GetMethodCallInfo(const std::string &http_method,
const std::string &url,
const std::string &query_params) const;
service_control::Interface *service_control() const {
return service_control_.get();
}
bool RequireAuth() const {
return !global_context_->is_auth_force_disabled() && config_->HasAuth();
}
bool IsRulesCheckEnabled() const {
return RequireAuth() && service().apis_size() > 0 &&
!config_->GetFirebaseServer().empty();
}
auth::Certs &certs() { return certs_; }
auth::JwtCache &jwt_cache() { return jwt_cache_; }
auth::AuthzCache &authz_cache() { return authz_cache_; }
bool GetJwksUri(const std::string &issuer, std::string *url) {
return config_->GetJwksUri(issuer, url);
}
void SetJwksUri(const std::string &issuer, const std::string &jwks_uri,
bool openid_valid) {
config_->SetJwksUri(issuer, jwks_uri, openid_valid);
}
const std::string &metadata_server() const {
return global_context_->metadata_server();
}
GceMetadata *gce_metadata() { return global_context_->gce_metadata(); }
const std::string &project_id() const;
cloud_trace::Aggregator *cloud_trace_aggregator() const {
return global_context_->cloud_trace_aggregator();
}
int64_t intermediate_report_interval() const {
return global_context_->intermediate_report_interval();
}
std::shared_ptr<GlobalContext> global_context() { return global_context_; }
private:
// Create service control.
std::unique_ptr<service_control::Interface> CreateInterface();
// The shared global context object.
std::shared_ptr<GlobalContext> global_context_;
// The service config object.
std::unique_ptr<Config> config_;
auth::Certs certs_;
auth::JwtCache jwt_cache_;
auth::AuthzCache authz_cache_;
// The service control object.
std::unique_ptr<service_control::Interface> service_control_;
};
} // namespace context
} // namespace api_manager
} // namespace google
#endif // API_MANAGER_CONTEXT_SERVICE_CONTEXT_H_
|
sebastienvas/esp
|
src/nginx/grpc_queue.h
|
/*
* Copyright (C) Extensible Service Proxy Authors
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef NGINX_NGX_ESP_GRPC_QUEUE_H_
#define NGINX_NGX_ESP_GRPC_QUEUE_H_
#include <deque>
#include <memory>
#include <thread>
#include <grpc++/grpc++.h>
extern "C" {
#include "ngx_core.h"
#include "ngx_event.h"
}
#include "src/grpc/async_grpc_queue.h"
namespace google {
namespace api_manager {
namespace nginx {
// The nginx-event-loop-based GRPC queue implementation.
class NgxEspGrpcQueue : public AsyncGrpcQueue {
public:
// Returns the global library instance, initializing it if necessary
// and returning an empty pointer on initialization failure. This
// call must be externally synchronized -- i.e. it's fine to call
// this from the main nginx thread, but not from any other thread.
static std::shared_ptr<NgxEspGrpcQueue> Instance();
// Returns the global library instance, or an empty pointer if the
// instance has not been initialized. This call must be externally
// synchronized -- i.e. it's fine to call this from the main nginx
// thread, but not from any other thread.
static std::shared_ptr<NgxEspGrpcQueue> TryInstance();
// Constructs a tag for use with the NgxEspGrpcQueue's completion queue.
// T must be MoveConstructible.
template <typename T>
static void *AllocTag(T callback) {
return static_cast<void *>(new TypedTag<T>(std::move(callback)));
}
// Constructs a tag for use with the NgxEspGrpcQueue's completion queue.
virtual void *MakeTag(std::function<void(bool)> callback) {
return AllocTag(std::move(callback));
}
// The completion queue processed by the library. Tags queued to
// this queue must be created by MakeTag or AllocTag.
virtual ::grpc::CompletionQueue *GetQueue() { return cq_.get(); }
void Init(ngx_cycle_t *cycle);
private:
static std::weak_ptr<NgxEspGrpcQueue> instance;
// The base class for the tags queued to the completion queue by the
// ESP components. Note that for completion queues accessed via the
// C++ interfaces, all tags must subclass
// ::grpc::CompletionQueueTag, since the framework will invoke the
// virtual FinalizeResult method on the tag before returning it.
class Tag : public ::grpc::CompletionQueueTag {
public:
virtual bool FinalizeResult(void **tag, bool *status) { return true; }
virtual void operator()(bool ok) = 0;
};
// Specializes Tag for the continuation being queued to a completion
// port. T must be MoveConstructible.
template <typename T>
class TypedTag : public Tag {
public:
TypedTag(T t) : t_(std::move(t)) {}
virtual void operator()(bool ok) { t_(ok); }
private:
T t_;
};
// The type stored in the pending event queue (pending_). This
// holds the callback function and the result to pass to that
// function once the Nginx main thread picks up the pending event.
struct Finalizer {
std::unique_ptr<Tag> callback;
bool success;
};
// Runs GRPC callbacks on the main nginx thread.
static void NginxTagHandler(ngx_event_t *);
// The GRPC worker thread main routine. This shuttles events from
// the GRPC completion queue to the nginx event queue, getting them
// onto the main nginx thread.
//
// Note that the worker thread's lifetime is strictly contained
// within the lifetime of its associated NgxEspGrpcQueue (the
// NgxEspGrpcQueue destructor joins on the thread). This makes it
// possible to pass the queue to the worker thread via a raw
// pointer.
static void WorkerThread(NgxEspGrpcQueue *queue);
// Deletes the NgxEspGrpcQueue. (This lets us avoid making the
// constructor and destructor public, which is a little overly
// paranoid, but doesn't hurt.)
static void Deleter(NgxEspGrpcQueue *queue);
NgxEspGrpcQueue();
virtual ~NgxEspGrpcQueue();
// Drains the contents of the pending_ queue.
void DrainPending();
std::mutex mu_;
ngx_event_t notify_;
std::unique_ptr<::grpc::CompletionQueue> cq_;
std::deque<Finalizer> pending_;
bool notified_;
std::thread worker_thread_;
};
} // namespace nginx
} // namespace api_manager
} // namespace google
#endif // NGINX_NGX_ESP_GRPC_QUEUE_H_
|
sebastienvas/esp
|
src/grpc/zero_copy_stream.h
|
<reponame>sebastienvas/esp<filename>src/grpc/zero_copy_stream.h
/*
* Copyright (C) Extensible Service Proxy Authors
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef GRPC_ZERO_COPY_STREAM_H_
#define GRPC_ZERO_COPY_STREAM_H_
#include <deque>
#include "google/protobuf/io/zero_copy_stream.h"
#include "grpc++/support/byte_buffer.h"
#include "grpc_transcoding/transcoder_input_stream.h"
#include "src/grpc/message_serializer.h"
namespace google {
namespace api_manager {
namespace grpc {
// ZeroCopyInputStream implementation over a stream of gRPC messages.
class GrpcZeroCopyInputStream
: public ::google::grpc::transcoding::TranscoderInputStream {
public:
GrpcZeroCopyInputStream();
// Add a message to the end of the stream
void AddMessage(grpc_byte_buffer* message, bool take_ownership);
// Marks the end of the stream, which means that ZeroCopyInputStream will
// return false after all the existing messages are consumed.
void Finish() { finished_ = true; }
// ZeroCopyInputStream implementation
bool Next(const void** data, int* size);
void BackUp(int count);
bool Skip(int count) { return false; } // not supported
::google::protobuf::int64 ByteCount() const { return 0; } // Not implemented
int64_t BytesAvailable() const;
private:
GrpcMessageSerializer serializer_;
const unsigned char* current_buffer_;
size_t current_buffer_size_;
size_t position_;
bool finished_;
};
} // namespace grpc
} // namespace api_manager
} // namespace google
#endif // GRPC_ZERO_COPY_STREAM_H_
|
sebastienvas/esp
|
src/nginx/zero_copy_stream.h
|
/*
* Copyright (C) Extensible Service Proxy Authors
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef NGINX_ZERO_COPY_STREAM_H_
#define NGINX_ZERO_COPY_STREAM_H_
#include <deque>
#include <memory>
#include <vector>
#include "google/protobuf/io/zero_copy_stream.h"
#include "grpc++/support/byte_buffer.h"
#include "include/api_manager/utils/status.h"
extern "C" {
#include "src/http/ngx_http.h"
}
namespace google {
namespace api_manager {
namespace nginx {
// ::google::protobuf::io::ZeroCopyInputStream implementation over an NGINX
// request body needed by transcoding interface.
// Given an ngx_http_request_t* r this implementation will return the data in
// r->request_body->bufs (if there is data) until r->reading_body is false and
// all the buffers have been processed.
class NgxRequestZeroCopyInputStream
: public ::google::protobuf::io::ZeroCopyInputStream {
public:
NgxRequestZeroCopyInputStream(ngx_http_request_t* r);
// Reports the status in case of an error
utils::Status Status() const { return status_; }
// ZeroCopyInputStream implementation
bool Next(const void** data, int* size);
void BackUp(int count);
bool Skip(int count) { return false; } // not supported
::google::protobuf::int64 ByteCount() const;
private:
// Advances to the next buffer. Returns true if successful; otherwise returns
// false (if no buffer is available or if an error occured).
bool NextBuffer();
// The request
ngx_http_request_t* r_;
// The current chain link
ngx_chain_t* cl_;
// The current buffer (might be different from cl_->buf in case cl_->buf is
// file-based)
ngx_buf_t* buf_;
// The current position in the buffer
u_char* pos_;
utils::Status status_;
};
} // namespace nginx
} // namespace api_manager
} // namespace google
#endif // NGINX_ZERO_COPY_STREAM_H_
|
typesAreSpaces/AXDInterpolator
|
include/AXDInterpolant.h
|
<reponame>typesAreSpaces/AXDInterpolator
#ifndef _AXD_INTERPOLANT_
#define _AXD_INTERPOLANT_
#include "z3++.h"
#include <iostream>
#include <utility>
#include <set>
#include <cstring>
#include <fstream>
#include "Preprocess.h"
#include "StandardInput.h"
#define _DEBUG_AXD_LOOP_ 0
#define _DEBUG_AXD_CONSTRUCTOR_ 0
#define _TEST_OUTPUT_ 0
#define _TEST_OUTPUT_ORIGINAL_THY_ 0
#define _INCLUDE_OUTPUT_ 1
#define CURRENT_DIR std::string("replace_once")
#define OUTPUT_DIR CURRENT_DIR + std::string("/output")
// Notes:
// The input file is a smt2 file
// with two assertions.
// Each assertion is
// of the form (and <pred_1> \dots <pred_n>).
class AXDInterpolant : public Preprocessor {
class CircularPairIterator {
friend class AXDInterpolant;
typedef Preprocessor::ArrayVars PArrayVars;
PArrayVars const & vars;
PArrayVars::Container::const_iterator
p_array_vars_it;
AXDSignature::z3_expr_set::const_iterator
z3_expr_set_first,
z3_expr_set_second;
void avoidLowerDiagonalAndDifferentTypes();
public:
CircularPairIterator(Preprocessor::ArrayVars const &);
void next();
StandardInput::DiffMap::z3_expr_pair operator *() const;
};
enum StateOutput { undefined, fine, notfine };
StandardInput part_a, part_b;
std::string m_file_name;
unsigned num_attempts, remaining_fuel;
bool is_interpolant_computed,
is_unsat,
is_valid_result;
StateOutput state_output;
z3::expr current_interpolant;
z3::solver solver;
void loop();
bool testOutput(
z3::expr_vector const &,
z3::expr_vector &,
z3::expr_vector &);
void testOutputArrayAxiomatization(z3::solver &);
void testOutputDiffLifting(
z3::solver & s,
StandardInput const &);
void SmtSolverSetup(
z3::solver &,
StandardInput const &);
void SmtSolverOutStreamSetup(
std::ostream &,
StandardInput const &);
void AB_VectorsSetup(
z3::expr_vector &,
StandardInput const &);
z3::expr liftInterpolant(z3::expr_vector const &);
void liftInterpolantDiffSubs(
z3::expr_vector &,
z3::expr_vector &,
StandardInput const &);
public:
AXDInterpolant(
AXDSignature &,
z3::expr const &,
z3::expr const &,
char const *,
unsigned);
void z3OutputFile();
void mathsatOutputFile();
void smtInterpolOutputFile();
friend std::ostream & operator << (
std::ostream &, AXDInterpolant const &);
};
#endif
|
typesAreSpaces/AXDInterpolator
|
include/StandardInput.h
|
<reponame>typesAreSpaces/AXDInterpolator<gh_stars>0
#ifndef _STANDARD_INPUT_
#define _STANDARD_INPUT_
#include "z3++.h"
#define _DEBUG_STDINPUT_ 0
#ifndef NDEBUG
# define ASSERT(condition, message) \
do { \
if (! (condition)) { \
std::cerr << "Assertion `" #condition "` failed in " << __FILE__ \
<< " line " << __LINE__ << ": " << message << std::endl; \
std::terminate(); \
} \
} while (false)
#else
# define ASSERT(condition, message) do { } while (false)
#endif
#include <set>
#include <utility>
#include <map>
#include <vector>
#include <tuple>
#include "Preprocess.h"
class StandardInput {
friend class AXDInterpolant;
struct DiffMapEntry : public z3::expr_vector {
z3::expr_vector lifted_b;
z3::expr_vector lifted_diff_k;
AXDSignature const & sig;
DiffMapEntry(
AXDSignature const &,
z3::expr const &,
z3::expr const &);
void push(
z3::expr const &,
z3::expr const &,
z3::expr const &);
};
// DiffMap :
// c_array_var.id() x c_array_var.id() -> sequence of diff_k
struct DiffMap {
friend class StandardInput;
typedef std::pair<z3::expr, z3::expr> z3_expr_pair;
struct Z3ExprExprComparator {
bool operator() (
z3_expr_pair const & a,
z3_expr_pair const & b) const;
};
std::map<z3_expr_pair,
DiffMapEntry,
Z3ExprExprComparator> m_map;
AXDSignature const & sig;
DiffMap(
Preprocessor::ArrayVars const &,
AXDSignature const &);
void add(
z3::expr const &,
z3::expr const &,
z3::expr const &);
void add_aux(
z3::expr const &,
z3::expr const &,
z3::expr const &);
unsigned size_of_entry(z3_expr_pair const &);
z3::expr lift_diff_k(
unsigned,
z3::expr const &,
z3::expr const &
) const;
};
// Container keeping track of a, b, i, e from
// a = wr(b, i, e) equations
struct WriteVector {
std::vector<
std::tuple<
z3::expr,
z3::expr,
z3::expr,
z3::expr>
> m_vector;
WriteVector();
void add(
z3::expr const &,
z3::expr const &,
z3::expr const &,
z3::expr const &);
};
class InstantiatedTerms {
AXDSignature const & sig;
AXDSignature::z3_expr_set terms;
unsigned num_of_instantiations;
unsigned num_of_new_index;
z3::expr_vector
new_succs, new_preds, new_minus,
new_adds, new_subtracts;
void instantiate_QF_IDL();
void instantiate_QF_UTVPI();
void instantiate_QF_LIA();
public:
InstantiatedTerms(
AXDSignature const &,
z3::expr_vector const &);
AXDSignature::z3_expr_set const & getInstantiatedTerms() const;
unsigned getNumOfNewIndex() const;
void operator++();
void add_var(z3::expr const &);
};
AXDSignature const & sig;
DiffMap diff_map;
WriteVector write_vector;
InstantiatedTerms instantiated_terms;
// -) part_1 contains wr-equations and diff(k)-equations
// of the original input
// -) part_2 contains the rest
z3::expr_vector part_1, part_2;
z3::expr const index_var;
z3::expr axiom_8, axiom_9;
z3::expr generateAxiom8(Preprocessor::ArrayVars const &)
const;
z3::expr generateAxiom9() const;
public:
StandardInput(
AXDSignature const &,
z3::expr_vector const &,
z3::expr_vector &,
Preprocessor::ArrayVars const &);
void initSaturation();
void updateSaturation(
DiffMap::z3_expr_pair const &,
z3::expr const &,
unsigned min_dim);
void instantiate(z3::solver &, z3::expr &) const;
void instantiate(std::ostream &, z3::expr &) const;
void instantiate(z3::expr_vector &, z3::expr &) const;
friend std::ostream & operator << (std::ostream &,
StandardInput const &);
friend std::ostream & operator << (std::ostream &,
StandardInput::DiffMap const &);
friend std::ostream & operator << (std::ostream &,
StandardInput::WriteVector const &);
};
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.